From a587d3339eb2f6a1e1dfc95abad5ac5884b94a95 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Sun, 18 Oct 2026 00:11:14 +0000 Subject: [PATCH 001/225] Tests: more time for the web offline launches and the icon review server On a busy CI machine (several fork jobs under gVisor at once) a web offline launch took over 90 s and the icon review server took over ~2 s to answer. Launches now get 240 s and one retry; the review server gets up to 60 s to start. Co-Authored-By: Claude Opus 5.5 --- tests/tools/test_icon_export.py | 4 +++- xtask/src/web_offline_test.rs | 31 +++++++++++++++++++++---------- 2 files changed, 24 insertions(+), 11 deletions(-) diff --git a/tests/tools/test_icon_export.py b/tests/tools/test_icon_export.py index 18b08506a..1e6d977af 100644 --- a/tests/tools/test_icon_export.py +++ b/tests/tools/test_icon_export.py @@ -84,7 +84,9 @@ class IconExportTest(unittest.TestCase): stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) try: url = 'http://127.0.0.1:%d' % port - for attempt in range(100): + # Up to a minute: CI machines can be busy enough that the server starts slowly. + deadline = time.monotonic() + 60 + while time.monotonic() < deadline: try: with urllib.request.urlopen(url + '/api/review', timeout=1) as response: base = json.load(response) diff --git a/xtask/src/web_offline_test.rs b/xtask/src/web_offline_test.rs index 0c5faf8bf..6d7a399bb 100644 --- a/xtask/src/web_offline_test.rs +++ b/xtask/src/web_offline_test.rs @@ -61,8 +61,10 @@ use crate::web_offline; const PREFIX: &str = "/solidcraft/app/"; /// Another copy of the app on the same origin. const ELSEWHERE: &str = "/solidcraft/elsewhere/"; -/// How long one launch may take (a real build compiles ~30 MB of wasm). -const LAUNCH_TIMEOUT: Duration = Duration::from_secs(90); +/// How long one launch may take (a real build compiles ~30 MB of wasm). Generous: the CI +/// runners that take fork pull requests run several jobs per machine under gVisor, where one +/// launch has taken over 90 s. +const LAUNCH_TIMEOUT: Duration = Duration::from_secs(240); /// sw.js's NAVIGATE_TIMEOUT_MS, less a margin: a hung network is waited for at least this long. const SLOW_NETWORK_WAIT: Duration = Duration::from_secs(3); /// How long a file takes in Mode::SlowFiles. @@ -193,15 +195,24 @@ pub fn run(root: &Path, site: Option<&str>, required: bool) -> Result<(), String let n = count.get() + 1; count.set(n); let t = Instant::now(); - let r = cdp.call("Page.navigate", json!({ "url": format!("http://127.0.0.1:{}{at}?launch={n}", server.port) }))?; - if let Some(e) = r["errorText"].as_str().filter(|e| !e.is_empty()) { - return Err(format!("launch {n} (build {build}): the page didn't load: {e}")); - } let search = format!("?launch={n}"); - wait_for(cdp, &state_js, &format!("launch {n} starts build {build}"), |s| { - s["search"] == search.as_str() && s["ready"] == "complete" && s["build"] == build && s["started"] == true - })?; - Ok(t.elapsed()) + let what = format!("launch {n} starts build {build}"); + // One retry: on a heavily loaded machine a launch can stall past the timeout. Loading the + // same page again must still start the same build. + for attempt in 1..=2 { + let r = cdp.call("Page.navigate", json!({ "url": format!("http://127.0.0.1:{}{at}?launch={n}", server.port) }))?; + if let Some(e) = r["errorText"].as_str().filter(|e| !e.is_empty()) { + return Err(format!("launch {n} (build {build}): the page didn't load: {e}")); + } + match wait_for(cdp, &state_js, &what, |s| { + s["search"] == search.as_str() && s["ready"] == "complete" && s["build"] == build && s["started"] == true + }) { + Ok(()) => return Ok(t.elapsed()), + Err(e) if attempt == 1 => println!("retry {e}"), + Err(e) => return Err(e), + } + } + unreachable!() }; let launch = |cdp: &mut Cdp, build: &str| launch_at(cdp, PREFIX, build); // The page is controlled by the worker, which keeps exactly this build's files (and the mark From a940f77447cbf42f7e0be4262a8ee879b5fe4642 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Sun, 18 Oct 2026 01:44:15 +0000 Subject: [PATCH 002/225] Sketch: always show a grid on the open sketch's plane While a sketch is open its grid is drawn on the sketch's own plane, centred near the view target and snapped to the major step, whatever the Grid switch, the sketch's Sketch Grid option or Grid follows the view say. Headless window pictures follow. Outside a sketch nothing changes. Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/view.rs | 31 ++++++++++++---- crates/ui-egui/src/control.rs | 2 +- crates/ui-egui/src/viewport.rs | 64 ++++++++++++++++++++++++---------- 3 files changed, 72 insertions(+), 25 deletions(-) diff --git a/crates/engine/src/view.rs b/crates/engine/src/view.rs index 3684244e3..1dc0acaa6 100644 --- a/crates/engine/src/view.rs +++ b/crates/engine/src/view.rs @@ -349,6 +349,20 @@ pub fn scene_with_section(s: &Session, cam: &Camera, section: Option<(Vec3, Vec3 scene_with_guides(s, cam, section, Guides::default()) } +/// The plane of the sketch that is open, if any: it always shows a grid, whatever the Grid switch +/// says (outside a sketch the grid is the user's choice). +pub fn open_sketch_plane(s: &Session) -> Option { + let id = s.active_sketch?; + s.world_state().sketch(id).map(|ss| ss.plane) +} + +/// The grid on a sketch plane: its centre (the view target's foot on the plane, snapped to the +/// major step in the plane's own axes) and the plane's x and y directions. +pub fn sketch_grid_frame(plane: &Plane, target: Vec3, major: f64) -> (Vec3, Vec3, Vec3) { + let snap = |d: Vec3| d * (((target - plane.origin).dot(d) / major).round() * major); + (plane.origin + snap(plane.x) + snap(plane.y), plane.x, plane.y) +} + /// What a headless render draws besides the model: the ground grid and the origin's axes. /// Both are on by default; the grid lies on Z 0, so it cuts through a model that straddles it. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -434,12 +448,17 @@ fn build_scene( if guides.grid { let (minor, major) = grid_step(cam.half_height()); let ext = (cam.half_height() * 3.0 / major).ceil() * major; - let tf = cam.to_frame(cam.target); - // Headless pictures keep the grid on the ground, the viewport's default. - let (u, v) = (Vec3::X, Vec3::Y); - let snap = |a: Vec3| a * ((tf.dot(a) / major).round() * major); - let c = snap(u) + snap(v); - let w = |p: Vec3| cam.from_frame(p); + // Headless pictures keep the grid on the ground, the viewport's default; an open sketch + // has its own plane's grid (world coordinates, no camera frame). + let (c, u, v, w): (Vec3, Vec3, Vec3, Box Vec3>) = if let Some(pl) = open_sketch_plane(s) { + let (c, u, v) = sketch_grid_frame(&pl, cam.target, major); + (c, u, v, Box::new(|p| p)) + } else { + let tf = cam.to_frame(cam.target); + let (u, v) = (Vec3::X, Vec3::Y); + let snap = |a: Vec3| a * ((tf.dot(a) / major).round() * major); + (snap(u) + snap(v), u, v, Box::new(|p| cam.from_frame(p))) + }; let n = ((ext / minor) as i64).clamp(1, 400); for i in -n..=n { let t = i as f64 * minor; diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 0ed0b48f4..8647e0d07 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -208,7 +208,7 @@ pub(crate) fn view_scene(app: &SolveApp, guides: solidcraft_engine::view::Guides /// The grid and the origin's axes as the window shows them (the Grid and Origin switches). pub(crate) fn window_guides(app: &SolveApp) -> solidcraft_engine::view::Guides { - solidcraft_engine::view::Guides { grid: app.ui.show_grid && !crate::viewport::active_view(app).hide_grid, axes: app.origin_visible() } + solidcraft_engine::view::Guides { grid: app.session.active_sketch.is_some() || (app.ui.show_grid && !crate::viewport::active_view(app).hide_grid), axes: app.origin_visible() } } /// A picture of the view as the window shows it, RGBA, drawn on the GPU with the viewport's diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index a3099b9c8..5bbd5497f 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -733,33 +733,39 @@ fn build_sketch_scene(app: &SolveApp, proj: &Proj) -> GpuScene { let s = &app.session; let st = s.world_state(); let mut fill_budget = 131_072; - if app.ui.show_grid && !active_view(app).hide_grid { + let sketch_plane = solidcraft_engine::view::open_sketch_plane(s); + if sketch_plane.is_some() || (app.ui.show_grid && !active_view(app).hide_grid) { let (minor, major) = grid_step(app.cam.half_height()); let ext = (app.cam.half_height() * 3.0 / major).ceil() * major; - // The ground plane: XY with Z up, XZ with Y up (laid out in the camera's Z-up frame), or - // the upright origin plane facing the view when the ground is seen edge-on. - let tf = app.cam.to_frame(app.cam.target); - // On the ground (XY) unless the Grid follows the view preference is on (#1470); then on - // the plane the last frame drew, so the choice is hysteretic near the thresholds (#1993). - let (u, v) = if app.preferences.grid_follows_view { - app.viewport.grid_plane.lock().map_or((Vec3::X, Vec3::Y), |mut last| { - *last = grid_plane(app.cam.to_frame(app.cam.back()), *last); - last.axes() - }) + // An open sketch always has its grid on its own plane; otherwise the ground plane: XY with + // Z up, XZ with Y up (laid out in the camera's Z-up frame), or the upright origin plane + // facing the view when the ground is seen edge-on. + let (c, u, v, w3): (Vec3, Vec3, Vec3, Box [f32; 3]>) = if let Some(pl) = &sketch_plane { + let (c, u, v) = solidcraft_engine::view::sketch_grid_frame(pl, app.cam.target, major); + (c, u, v, Box::new(|p| p.to_f32())) } else { - (Vec3::X, Vec3::Y) + let tf = app.cam.to_frame(app.cam.target); + // On the ground (XY) unless the Grid follows the view preference is on (#1470); then on + // the plane the last frame drew, so the choice is hysteretic near the thresholds (#1993). + let (u, v) = if app.preferences.grid_follows_view { + app.viewport.grid_plane.lock().map_or((Vec3::X, Vec3::Y), |mut last| { + *last = grid_plane(app.cam.to_frame(app.cam.back()), *last); + last.axes() + }) + } else { + (Vec3::X, Vec3::Y) + }; + let snap = |a: Vec3| a * ((tf.dot(a) / major).round() * major); + (snap(u) + snap(v), u, v, Box::new(|p| app.cam.from_frame(p).to_f32())) }; - let snap = |a: Vec3| a * ((tf.dot(a) / major).round() * major); - let c = snap(u) + snap(v); - let w3 = |p: Vec3| app.cam.from_frame(p).to_f32(); let n = ((ext / minor) as i64).clamp(1, 300); for i in -n..=n { let t = i as f64 * minor; let maj = (t / major).round() * major == t; let col = if maj { c4(tk.grid_major) } else { c4(tk.grid) }; - let w = if maj { 1.0 } else { 0.7 }; - sc.under_line(w3(c + u * t - v * ext), w3(c + u * t + v * ext), col, w); - sc.under_line(w3(c - u * ext + v * t), w3(c + u * ext + v * t), col, w); + let wd = if maj { 1.0 } else { 0.7 }; + sc.under_line(w3(c + u * t - v * ext), w3(c + u * t + v * ext), col, wd); + sc.under_line(w3(c - u * ext + v * t), w3(c + u * ext + v * t), col, wd); } } for sid in visible_sketches(app) { @@ -6188,6 +6194,28 @@ mod grid_plane_tests { assert_eq!(*app.viewport.grid_plane.lock().unwrap(), GridPlane::Ground, "a clear turn off the ground returns"); } + /// An open sketch always has its grid, on its own plane, whatever the Grid switch and the + /// follow-the-view preference say; outside a sketch the switch decides. + #[test] + fn an_open_sketch_always_shows_a_grid_on_its_plane() { + let rect = Rect::from_min_size(Pos2::ZERO, egui::vec2(800.0, 600.0)); + let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + app.ui.show_grid = false; + let grid = |app: &SolveApp| build_sketch_scene(app, &projection(app, rect)).under; + assert!(grid(&app).is_empty(), "no grid outside a sketch with the switch off"); + app.run("sketch.create", json!({"plane": "XZ"})).unwrap(); + for follows in [false, true] { + app.preferences.grid_follows_view = follows; + let under = grid(&app); + assert!(!under.is_empty(), "the open sketch shows a grid (follows the view: {follows})"); + // Each line is 32 bytes: two f32 points, a colour and a width; the XZ plane is Y = 0. + let ys: Vec = under.chunks_exact(32).flat_map(|l| [&l[4..8], &l[16..20]]).map(|b| f32::from_le_bytes(b.try_into().unwrap())).collect(); + assert!(ys.iter().all(|y| y.abs() < 1e-3), "the grid lies on the sketch plane"); + } + app.ui.show_grid = true; + assert!(!grid(&app).is_empty()); + } + /// A sketch is drawn in a parallel view even when the preference asks for perspective; the /// preference comes back when the sketch is finished. #[test] From 46462957e4152c351933229e5161521d153b69fc Mon Sep 17 00:00:00 2001 From: bherbruck Date: Sun, 18 Oct 2026 15:55:45 -0400 Subject: [PATCH 003/225] Revert "CI: run the triage and claim bots on the trusted light runner (#2655)" (#2735) The trusted runners' guard refuses issue and pull_request_target events by design (they carry a write token and handle untrusted input), so the bots failed there. They go back to GitHub's runners. Co-authored-by: Claude Opus 5.5 --- .github/workflows/claim.yml | 4 +--- .github/workflows/triage.yml | 4 +--- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/.github/workflows/claim.yml b/.github/workflows/claim.yml index 14975a9df..f41587214 100644 --- a/.github/workflows/claim.yml +++ b/.github/workflows/claim.yml @@ -27,9 +27,7 @@ concurrency: jobs: claim: name: Claim bot - # The bots run main's own scripts (never PR code), so the trusted light runner takes them - # and GitHub's shared runners stay free for pull request builds. - runs-on: self-hosted-light + runs-on: ubuntu-24.04 timeout-minutes: 10 if: >- github.event_name != 'issue_comment' || diff --git a/.github/workflows/triage.yml b/.github/workflows/triage.yml index 7472e7194..00b8c9e8d 100644 --- a/.github/workflows/triage.yml +++ b/.github/workflows/triage.yml @@ -33,9 +33,7 @@ concurrency: jobs: triage: name: Triage bot - # The bots run main's own scripts (never PR code), so the trusted light runner takes them - # and GitHub's shared runners stay free for pull request builds. - runs-on: self-hosted-light + runs-on: ubuntu-24.04 timeout-minutes: 30 # Filtered here so the common events (every comment, every label) start no runner. if: >- From dded27277f78fa553879ea75de9c2c1ff183c777 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Sun, 18 Oct 2026 20:16:56 +0000 Subject: [PATCH 004/225] Version 0.16.1 Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 34 +++++++++++++++++----------------- Cargo.toml | 2 +- 2 files changed, 18 insertions(+), 18 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d8a031821..03a4027e6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4078,7 +4078,7 @@ dependencies = [ [[package]] name = "solidcraft" -version = "0.16.0" +version = "0.16.1" dependencies = [ "block2 0.6.2", "eframe", @@ -4109,11 +4109,11 @@ dependencies = [ [[package]] name = "solidcraft-3dx-client" -version = "0.16.0" +version = "0.16.1" [[package]] name = "solidcraft-cli" -version = "0.16.0" +version = "0.16.1" dependencies = [ "image", "serde_json", @@ -4124,7 +4124,7 @@ dependencies = [ [[package]] name = "solidcraft-derive" -version = "0.16.0" +version = "0.16.1" dependencies = [ "proc-macro2", "quote", @@ -4133,7 +4133,7 @@ dependencies = [ [[package]] name = "solidcraft-doc" -version = "0.16.0" +version = "0.16.1" dependencies = [ "log", "serde", @@ -4150,7 +4150,7 @@ dependencies = [ [[package]] name = "solidcraft-engine" -version = "0.16.0" +version = "0.16.1" dependencies = [ "log", "serde", @@ -4167,7 +4167,7 @@ dependencies = [ [[package]] name = "solidcraft-geom" -version = "0.16.0" +version = "0.16.1" dependencies = [ "serde", "serde_json", @@ -4176,7 +4176,7 @@ dependencies = [ [[package]] name = "solidcraft-gpu" -version = "0.16.0" +version = "0.16.1" dependencies = [ "log", "naga", @@ -4193,7 +4193,7 @@ dependencies = [ [[package]] name = "solidcraft-io" -version = "0.16.0" +version = "0.16.1" dependencies = [ "cadmpeg-core", "cadmpeg-ir", @@ -4213,7 +4213,7 @@ dependencies = [ [[package]] name = "solidcraft-kernel" -version = "0.16.0" +version = "0.16.1" dependencies = [ "log", "proptest", @@ -4233,7 +4233,7 @@ dependencies = [ [[package]] name = "solidcraft-mcp" -version = "0.16.0" +version = "0.16.1" dependencies = [ "serde_json", "solidcraft-engine", @@ -4242,7 +4242,7 @@ dependencies = [ [[package]] name = "solidcraft-render" -version = "0.16.0" +version = "0.16.1" dependencies = [ "image", "moxcms", @@ -4256,7 +4256,7 @@ dependencies = [ [[package]] name = "solidcraft-sketch" -version = "0.16.0" +version = "0.16.1" dependencies = [ "serde", "serde_json", @@ -4267,11 +4267,11 @@ dependencies = [ [[package]] name = "solidcraft-space-mouse" -version = "0.16.0" +version = "0.16.1" [[package]] name = "solidcraft-ui-egui" -version = "0.16.0" +version = "0.16.1" dependencies = [ "arboard", "egui", @@ -4296,7 +4296,7 @@ dependencies = [ [[package]] name = "solidcraft-web" -version = "0.16.0" +version = "0.16.1" dependencies = [ "eframe", "egui", @@ -5826,7 +5826,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7" [[package]] name = "xtask" -version = "0.16.0" +version = "0.16.1" dependencies = [ "serde_json", "sha2 0.10.9", diff --git a/Cargo.toml b/Cargo.toml index ded7e9b3c..ba9d53840 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,7 +5,7 @@ members = ["crates/*", "apps/*", "xtask"] exclude = ["vendor"] [workspace.package] -version = "0.16.0" +version = "0.16.1" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" From 6d410c342caef61557887dd50bcff8391405ae61 Mon Sep 17 00:00:00 2001 From: NOWN-DEV <257771410+NOWN-DEV@users.noreply.github.com> Date: Mon, 19 Oct 2026 00:10:28 +0200 Subject: [PATCH 005/225] Joints: origins on an edge of a face, at its middle or a corner (#2403) (#2404) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Joints: a face or circle origin keeps its turn as the face tilts A face- or circle-centre joint origin worked out its frame's x from the normal alone (`Vec3::any_perp`), which switches axis where the normal crosses 0.9 along X: a part on a face tilted past about 64° by a parameter spun a right angle about the face. New origins keep the x they have when picked (`x`, component coordinates) and each solve lays it onto the face as it is now, so the part tilts with the face without spinning. Origins saved without it are placed as before. Co-Authored-By: Claude Opus 5.5 (1M context) * Joints: origins on an edge of a face, at its middle or a corner `joint.origin` and `joint.create` take `edge: [x,y,z]` (a point on an edge of a planar face), with `on` (which face; default the larger planar face beside it) and `corner` (the end near that point). The origin sits at the edge's middle (z out of the face, y into it) or at the corner (x and y along its two edges into the face, right-handed whichever way the edges run). The edge, the face and the corner's other edge are kept by name and found again on every solve, so a part set 40 mm in from a panel's corner stays there when the panel changes size; a name that finds nothing leaves the joint out with the reason. Co-Authored-By: Claude Opus 5.5 (1M context) --------- Co-authored-by: Claude Opus 5.5 (1M context) Co-authored-by: bherbruck --- .../src/format/pending/joint-origin-edge.rs | 4 + .../format/pending/joint-origin-frame-x.rs | 5 + crates/doc/src/joints.rs | 46 ++++- crates/doc/src/joints_edge.rs | 193 ++++++++++++++++++ .../src/cmd/component_clone_assembly_tests.rs | 24 +++ crates/engine/src/cmd/joint_edge_tests.rs | 108 ++++++++++ crates/engine/src/cmd/joint_frames_tests.rs | 96 +++++++++ crates/engine/src/cmd/joints.rs | 23 ++- docs/book/src/guide/assemblies.md | 10 + 9 files changed, 503 insertions(+), 6 deletions(-) create mode 100644 crates/doc/src/format/pending/joint-origin-edge.rs create mode 100644 crates/doc/src/format/pending/joint-origin-frame-x.rs create mode 100644 crates/doc/src/joints_edge.rs create mode 100644 crates/engine/src/cmd/joint_edge_tests.rs create mode 100644 crates/engine/src/cmd/joint_frames_tests.rs diff --git a/crates/doc/src/format/pending/joint-origin-edge.rs b/crates/doc/src/format/pending/joint-origin-edge.rs new file mode 100644 index 000000000..628d743a8 --- /dev/null +++ b/crates/doc/src/format/pending/joint-origin-edge.rs @@ -0,0 +1,4 @@ +//! A joint origin can sit on an edge of a planar face (`Snap::Edge`, saved as `"type": "edge"`): +//! at the edge's middle or at a corner where it meets another edge, all three found again by name. +//! Older designs need no transformation: they have no such origins. The last release refuses a +//! design saved with this (the newer format number). diff --git a/crates/doc/src/format/pending/joint-origin-frame-x.rs b/crates/doc/src/format/pending/joint-origin-frame-x.rs new file mode 100644 index 000000000..c9a32ddf5 --- /dev/null +++ b/crates/doc/src/format/pending/joint-origin-frame-x.rs @@ -0,0 +1,5 @@ +//! A face or circle joint origin given no `x` reference keeps the x its frame had when picked +//! (`x` as a direction, component coordinates) and lays it onto the face as it is now, so a part +//! on a face that tilts keeps its turn. Older designs need no transformation: an origin without +//! `x` works its frame out from the normal alone, as before. The last release refuses a design +//! saved with this (the newer format number). diff --git a/crates/doc/src/joints.rs b/crates/doc/src/joints.rs index b126301e2..6aa54eeec 100644 --- a/crates/doc/src/joints.rs +++ b/crates/doc/src/joints.rs @@ -62,6 +62,18 @@ pub enum Snap { #[serde(default, skip_serializing_if = "Option::is_none")] x: Option, }, + /// A point on an edge of a planar face: the edge's middle, or the corner where it meets the + /// edge `corner` names (`joints_edge.rs`). `edge` and `face` are the persistent names of the + /// edge and the face (found first); `pick` is a point on the edge as it was picked. + Edge { + pick: Vec3, + #[serde(default, skip_serializing_if = "Option::is_none")] + edge: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + face: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + corner: Option, + }, /// A point, z along `z` (default +Z). Point { point: Vec3, @@ -88,7 +100,8 @@ pub enum XRef { } impl Snap { - /// The persistent face names the snap refers to (its face, its end's, its x reference's). + /// The persistent face and edge names the snap refers to (its face, its end's, its x reference's; + /// an edge origin's edge, face and corner edge). pub fn face_names(&self) -> Vec<&String> { let mut out = Vec::new(); if let Snap::FaceCenter { face, x, .. } | Snap::CircleCenter { face, x, .. } = self { @@ -100,6 +113,9 @@ impl Snap { if let Snap::CircleCenter { end: Some(end), .. } = self { out.push(end); } + if let Snap::Edge { edge, face, corner, .. } = self { + out.extend(edge.iter().chain(face.iter()).chain(corner.iter())); + } out } @@ -120,11 +136,33 @@ impl Snap { out.push(face); } } + Snap::Edge { edge, face, corner, .. } => out.extend(edge.iter_mut().chain(face.iter_mut()).chain(corner.iter_mut())), _ => {} } out } + /// The direction a face or circle snap keeps as its frame's x (`XRef::Dir`), in the + /// component's coordinates; `None` for a face reference or none. + pub fn frame_x(&self) -> Option { + match self { + Snap::FaceCenter { x: Some(XRef::Dir(d)), .. } | Snap::CircleCenter { x: Some(XRef::Dir(d)), .. } => Some(*d), + _ => None, + } + } + + /// A face or circle snap given no x reference keeps `x` (the frame's x as it is now): each + /// solve lays it onto the face, or square to the hole's axis, as the geometry is then, so a + /// part on a face that tilts keeps its turn about z. Without it (designs made before) x + /// follows from z alone, and turns through a right angle where z crosses 0.9 along the + /// component's X. A snap with a reference keeps it. + pub fn with_frame_x(mut self, x: Vec3) -> Snap { + if let Snap::FaceCenter { x: slot @ None, .. } | Snap::CircleCenter { x: slot @ None, .. } = &mut self { + *slot = Some(XRef::Dir(x)); + } + self + } + /// Whether every point and direction in the snap is finite. pub fn is_finite(&self) -> bool { let x_ok = |x: &Option| match x { @@ -136,6 +174,7 @@ impl Snap { Snap::Frame { origin, z, x } => origin.is_finite() && z.is_finite() && x.is_none_or(|x| x.is_finite()), Snap::FaceCenter { pick, x, .. } | Snap::CircleCenter { pick, x, .. } => pick.is_finite() && x_ok(x), Snap::Point { point, z } => point.is_finite() && z.is_none_or(|z| z.is_finite()), + Snap::Edge { pick, .. } => pick.is_finite(), } } } @@ -519,6 +558,7 @@ pub fn resolve_origin(doc: &Document, st: &ModelState, o: &JointOrigin) -> Resul }; frame(c, n, face::x_axis(doc, st, x.as_ref(), c)?).ok_or_else(bad) } + Snap::Edge { .. } => edge::edge_frame(doc, st, component_of(doc, o.occurrence)?, &o.snap), Snap::CircleCenter { x, .. } => { let r = round_of(doc, st, o)?; frame(r.centre, r.z, face::x_axis(doc, st, x.as_ref(), r.centre)?).ok_or_else(bad) @@ -1548,6 +1588,10 @@ impl Document { #[path = "joints_cam.rs"] pub mod cam; +#[path = "joints_edge.rs"] +mod edge; +pub use edge::edge_snap; + #[path = "joints_reach.rs"] mod reach; diff --git a/crates/doc/src/joints_edge.rs b/crates/doc/src/joints_edge.rs new file mode 100644 index 000000000..097d51bbc --- /dev/null +++ b/crates/doc/src/joints_edge.rs @@ -0,0 +1,193 @@ +//! Joint origins on an edge of a planar face (`Snap::Edge`): the edge's middle, or a corner where +//! it meets another edge of the face. The edge, the face and the corner's other edge are found +//! again by name on every solve, so the origin follows the face as it grows, shrinks or moves: +//! hardware set 40 mm in from a panel's corner stays 40 mm in from that corner at any size. +//! +//! The frame never depends on which way an edge's polyline runs: z is the face's outward normal; +//! at the middle y points into the face, square to the edge, and x = y × z runs along it; at a +//! corner x and y run along the two edges, away from the corner into the face, in the order that +//! makes the frame right-handed. + +use solidcraft_geom::Vec3; + +use super::{Snap, component_bodies, frame}; +use crate::{DocError, Document, Mat, ModelBody, ModelState, Result}; + +/// Points that close are one corner (as a share of the body's size, at least 1 µm). +fn tol(b: &ModelBody) -> f64 { + (b.body.size() * 2e-3).max(1e-3) +} + +/// The edge of `b` nearest `p`, and how far it is. +fn nearest_edge(b: &ModelBody, p: Vec3) -> Option<(usize, f64)> { + b.mesh() + .edges + .iter() + .enumerate() + .map(|(i, e)| (i, e.windows(2).map(|w| p.dist_to_segment(w[0], w[1])).fold(f64::INFINITY, f64::min))) + .filter(|(_, d)| d.is_finite()) + .min_by(|a, b| a.1.total_cmp(&b.1)) +} + +/// Edge `i` of `b`: by its name (`None` when the body has no such edge), else the edge at `pick`. +fn edge_index(b: &ModelBody, name: Option<&str>, pick: Vec3) -> Option { + match name { + Some(n) => crate::name_lookup::locate_edge(b, n, pick).ok().map(|h| h.edge), + None => nearest_edge(b, pick).filter(|(_, d)| *d <= tol(b)).map(|(i, _)| i), + } +} + +/// The planar face beside edge `i` the origin sits on: the named one, else the larger planar face +/// the edge bounds. Its index, outward normal and centroid. +fn face_of(b: &ModelBody, i: usize, name: Option<&str>, pick: Vec3) -> Result<(usize, Vec3, Vec3)> { + let m = b.mesh(); + let beside: Vec = m.edge_faces.get(i).map(|fs| fs.iter().map(|f| *f as usize).collect()).unwrap_or_default(); + let infos = b.body.faces(tol(b))?; + let planar = |f: usize| infos.iter().find(|x| x.index == f).and_then(|x| x.plane_normal.map(|n| (x.index, n, x.centroid, x.area))); + let chosen = match name { + Some(n) => { + let (f, _, _) = crate::naming::face_on_body(b, n, pick) + .ok_or_else(|| DocError::Invalid(format!("joint origin: the face `{n}` no longer exists (edit the joint to pick again)")))?; + if !beside.contains(&f) { + return Err(DocError::Invalid(format!("joint origin: the face `{n}` no longer meets its edge (edit the joint to pick again)"))); + } + planar(f) + } + None => beside.iter().filter_map(|f| planar(*f)).max_by(|a, b| a.3.total_cmp(&b.3)), + }; + chosen.map(|(f, n, c, _)| (f, n, c)).ok_or_else(|| DocError::Invalid("joint origin: no planar face beside that edge".into())) +} + +/// Edge `i`'s middle (along its polyline) and the direction it runs there. +fn middle(e: &[Vec3]) -> Option<(Vec3, Vec3)> { + let total: f64 = e.windows(2).map(|w| w[0].dist(w[1])).sum(); + let mut acc = 0.0; + for w in e.windows(2) { + let l = w[0].dist(w[1]); + if l > 0.0 && acc + l >= total / 2.0 { + let t = (total / 2.0 - acc) / l; + return Some((w[0] + (w[1] - w[0]) * t, (w[1] - w[0]) / l)); + } + acc += l; + } + None +} + +/// An edge's end at `p` (within `tol`) and the direction it leaves the end in. +fn leaving(e: &[Vec3], p: Vec3, tol: f64) -> Option { + let (first, last) = (*e.first()?, *e.last()?); + let away = |q: Option<&Vec3>, from: Vec3| q.and_then(|q| (*q - from).normalized()); + if first.dist(p) <= tol { + away(e.iter().find(|q| q.dist(first) > tol * 0.5), first) + } else if last.dist(p) <= tol { + away(e.iter().rev().find(|q| q.dist(last) > tol * 0.5), last) + } else { + None + } +} + +/// The corner where edges `e` and `f` meet: the closest pair of their ends, when within `tol`. +fn meeting(e: &[Vec3], f: &[Vec3], tol: f64) -> Option { + let ends = |x: &[Vec3]| [x.first().copied(), x.last().copied()]; + ends(e) + .into_iter() + .flatten() + .flat_map(|a| ends(f).into_iter().flatten().map(move |b| (a, a.dist(b)))) + .filter(|(_, d)| *d <= tol) + .min_by(|a, b| a.1.total_cmp(&b.1)) + .map(|(a, _)| a) +} + +/// The frame of an edge snap in its component's coordinates. +pub(super) fn edge_frame(doc: &Document, st: &ModelState, comp: u64, snap: &Snap) -> Result { + let Snap::Edge { pick, edge, face, corner } = snap else { return Err(DocError::Invalid("not an edge origin".into())) }; + let bad = || DocError::Invalid("joint origin: degenerate frame".into()); + let gone = |what: &str| DocError::Invalid(format!("joint origin: {what} no longer exists (edit the joint to pick again)")); + let found = component_bodies(doc, st, comp).into_iter().find_map(|b| edge_index(b, edge.as_deref(), *pick).map(|i| (b, i))); + let (b, i) = found.ok_or_else(|| match edge { + Some(n) => gone(&format!("the edge `{n}`")), + None => DocError::Invalid("joint origin: no edge there".into()), + })?; + let m = b.mesh(); + let e = m.edges.get(i).ok_or_else(bad)?; + let (_, z, centroid) = face_of(b, i, face.as_deref(), *pick)?; + let flat = |v: Vec3| (v - z * v.dot(z)).normalized(); + match corner { + None => { + let (mid, along) = middle(e).ok_or_else(bad)?; + // Into the face: toward its centroid, square to the edge; a face whose centroid lies on + // the edge's line (only a sliver) falls back to the side z × along gives. + let to_c = centroid - mid; + let y = flat(to_c - along * to_c.dot(along)).unwrap_or_else(|| z.cross(along)); + frame(mid, z, Some(y.cross(z))).ok_or_else(bad) + } + Some(other) => { + let j = crate::name_lookup::locate_edge(b, other, *pick).map_err(|_| gone(&format!("the edge `{other}`")))?.edge; + let f = m.edges.get(j).ok_or_else(bad)?; + let t = tol(b); + let at = meeting(e, f, t).ok_or_else(|| DocError::Invalid(format!("joint origin: its edges no longer meet at a corner (`{other}`)")))?; + let (de, df) = (leaving(e, at, t).and_then(flat).ok_or_else(bad)?, leaving(f, at, t).and_then(flat).ok_or_else(bad)?); + let x = if z.dot(de.cross(df)) >= 0.0 { de } else { df }; + frame(at, z, Some(x)).ok_or_else(bad) + } + } +} + +/// An edge snap for an edge picked at `pick` on component `comp` (its own coordinates): on the +/// planar face holding `on` (default: the larger planar face beside the edge), at the edge's +/// middle or, with `corner`, at the end nearest it. The edge, the face and the corner's other +/// edge are kept by name. +pub fn edge_snap(doc: &Document, st: &ModelState, comp: u64, pick: Vec3, on: Option, corner: Option) -> Result { + let (b, i) = component_bodies(doc, st, comp) + .into_iter() + .filter_map(|b| nearest_edge(b, pick).filter(|(_, d)| *d <= tol(b)).map(|(i, _)| (b, i))) + .next() + .ok_or_else(|| DocError::Invalid("joint origin: no edge there".into()))?; + let names = crate::naming::edge_names(b); + let face_names = crate::naming::face_names(b); + let m = b.mesh(); + let beside: Vec = m.edge_faces.get(i).map(|fs| fs.iter().map(|f| *f as usize).collect()).unwrap_or_default(); + let face_index = match on { + Some(p) => { + let f = crate::naming::face_name_at_body(b, p) + .and_then(|n| crate::naming::face_on_body(b, &n, p)) + .map(|(f, _, _)| f) + .ok_or_else(|| DocError::Invalid("joint origin: `on` is not on a face of that body".into()))?; + if !beside.contains(&f) { + return Err(DocError::Invalid("joint origin: `on` picks a face the edge doesn't bound".into())); + } + f + } + None => face_of(b, i, None, pick)?.0, + }; + let face = face_names.get(face_index).cloned().filter(|n| !n.is_empty()); + let corner = match corner { + None => None, + Some(c) => { + let e = m.edges.get(i).cloned().unwrap_or_default(); + let t = tol(b); + let end = [e.first().copied(), e.last().copied()] + .into_iter() + .flatten() + .min_by(|a, b| a.dist(c).total_cmp(&b.dist(c))) + .ok_or_else(|| DocError::Invalid("joint origin: that edge has no ends".into()))?; + // The other edge of the face that ends there. + let other = m + .edges + .iter() + .enumerate() + .filter(|(j, _)| *j != i && m.edge_faces.get(*j).is_some_and(|fs| fs.contains(&(face_index as u32)))) + .find(|(_, f)| meeting(&[end], f, t).is_some()) + .map(|(j, _)| j) + .ok_or_else(|| DocError::Invalid("joint origin: no other edge of the face meets that end (a round edge has no corner)".into()))?; + Some( + names + .get(other) + .cloned() + .filter(|n| !n.is_empty()) + .ok_or_else(|| DocError::Invalid("joint origin: the corner's other edge has no name".into()))?, + ) + } + }; + Ok(Snap::Edge { pick, edge: names.get(i).cloned().filter(|n| !n.is_empty()), face, corner }) +} diff --git a/crates/engine/src/cmd/component_clone_assembly_tests.rs b/crates/engine/src/cmd/component_clone_assembly_tests.rs index 23defb389..da1d30998 100644 --- a/crates/engine/src/cmd/component_clone_assembly_tests.rs +++ b/crates/engine/src/cmd/component_clone_assembly_tests.rs @@ -233,3 +233,27 @@ fn paste_new_internal_motion_study_drives_only_the_copied_assembly_and_reopens() assert_eq!(reopened.assembly, s.doc.assembly); assert!(reopened.assembly.studies.iter().any(|m| m.name == "Travel (copy)" && m.keys[0].joint == copied_joint)); } + +/// An edge origin's edge, face and corner edge are the copy's too. +#[test] +fn an_edge_origin_is_copied_onto_the_copys_edges() { + let (source, mut destination) = documents(); + let edge = |e: &str| Some(e.to_string()); + let mut source = source; + source.assembly.origins = vec![NamedOrigin { + name: "Corner".into(), + origin: JointOrigin { + occurrence: 1, + snap: Snap::Edge { pick: Vec3::new(1.0, 2.0, 3.0), edge: edge("F1:top|F1:side"), face: edge("F1:top"), corner: edge("F1:top|F10:end") }, + }, + }]; + destination.assembly.origins.clear(); + clone_assembly(&mut destination, &source, &BTreeMap::from([(1, 101), (2, 102)]), &BTreeMap::from([(1, 11), (10, 110)]), &BTreeMap::new()) + .unwrap(); + let copied = destination.assembly.origins.last().map(|o| &o.origin.snap); + assert!( + matches!(copied, Some(Snap::Edge { edge: Some(e), face: Some(f), corner: Some(c), .. }) + if e == "F11:top|F11:side" && f == "F11:top" && c == "F11:top|F110:end"), + "{copied:?}" + ); +} diff --git a/crates/engine/src/cmd/joint_edge_tests.rs b/crates/engine/src/cmd/joint_edge_tests.rs new file mode 100644 index 000000000..7b0fc9c2c --- /dev/null +++ b/crates/engine/src/cmd/joint_edge_tests.rs @@ -0,0 +1,108 @@ +//! Joint origins on an edge of a face (its middle, or a corner) follow the face as it changes size. + +use serde_json::json; +use solidcraft_geom::Vec3; + +use super::tests::{place, run}; +use crate::Session; + +/// A 2 mm panel `W` x 300 (W = 400) in component Panel, and a 20 x 10 x 6 bracket in component +/// Bracket, off to the side. +fn panel() -> Session { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "W", "expression": "400 mm"})); + run(&mut s, "component.create", json!({"name": "Panel"})); + run(&mut s, "solid.box", json!({"length": "W", "width": 300, "height": 2, "corner": [0, 0, 0]})); + run(&mut s, "component.activate", json!({"component": "root"})); + run(&mut s, "component.create", json!({"name": "Bracket"})); + run(&mut s, "solid.box", json!({"length": 20, "width": 10, "height": 6, "corner": [0, 500, 0]})); + s +} + +/// The middle of the bracket's bottom face, where it is now. +fn bracket(s: &Session) -> Vec3 { + place(s, "Bracket", Vec3::new(10.0, 505.0, 0.0)) +} + +fn near(a: Vec3, b: Vec3) -> bool { + a.dist(b) < 1e-6 +} + +#[test] +fn a_part_set_in_from_a_corner_stays_there_as_the_panel_grows() { + let mut s = panel(); + // The front right corner of the top face; the bracket 40 mm in along both edges. + run( + &mut s, + "joint.create", + json!({"type": "planar", "a": {"occurrence": "Panel", "edge": [200, 0, 2], "corner": [400, 0, 2]}, + "b": {"occurrence": "Bracket", "face": [10, 505, 0]}, "values": [40, 40, 0], "name": "Corner"}), + ); + for w in [400.0, 600.0, 250.0, 1000.0] { + run(&mut s, "parameters.change", json!({"name": "W", "expression": format!("{w} mm")})); + assert!(near(bracket(&s), Vec3::new(w - 40.0, 40.0, 2.0)), "W {w}: {:?}", bracket(&s)); + assert_eq!(run(&mut s, "joint.solve", json!({}))["errors"], json!([])); + } + let snap = s.doc.assembly.joints.first().map(|j| j.a.snap.clone()); + assert!( + matches!(&snap, Some(solidcraft_doc::joints::Snap::Edge { edge: Some(_), face: Some(_), corner: Some(_), .. })), + "the edge, the face and the corner's other edge are kept by name: {snap:?}" + ); +} + +#[test] +fn a_part_at_an_edges_middle_follows_it_and_the_face_can_be_chosen() { + let mut s = panel(); + // The right edge of the top face: its middle is (W, 150, 2), y points into the face (−X). + run( + &mut s, + "joint.create", + json!({"type": "planar", "a": {"occurrence": "Panel", "edge": [400, 100, 2]}, + "b": {"occurrence": "Bracket", "face": [10, 505, 0]}, "values": [0, 40, 0], "name": "Mid"}), + ); + for w in [400.0, 700.0, 320.0] { + run(&mut s, "parameters.change", json!({"name": "W", "expression": format!("{w} mm")})); + assert!(near(bracket(&s), Vec3::new(w - 40.0, 150.0, 2.0)), "W {w}: {:?}", bracket(&s)); + } + // The same edge on the end face: z points out of the end (+X), y into it (down). + run(&mut s, "joint.delete", json!({"joint": "Mid"})); + run( + &mut s, + "joint.create", + json!({"type": "rigid", "a": {"occurrence": "Panel", "edge": [320, 100, 2], "on": [320, 150, 1]}, + "b": {"occurrence": "Bracket", "face": [10, 505, 0]}, "name": "End"}), + ); + assert!(near(bracket(&s), Vec3::new(320.0, 150.0, 2.0)), "{:?}", bracket(&s)); + // The bracket's bottom faces the end face: its top (6 mm up its own z) is out along +X. + assert!( + near(place(&s, "Bracket", Vec3::new(10.0, 505.0, 6.0)), Vec3::new(326.0, 150.0, 2.0)), + "{:?}", + place(&s, "Bracket", Vec3::new(10.0, 505.0, 6.0)) + ); +} + +#[test] +fn edge_origins_refuse_bad_picks_and_report_a_lost_edge() { + let mut s = panel(); + let bad = |s: &mut Session, a: serde_json::Value| { + s.execute("joint.create", &json!({"type": "rigid", "a": a, "b": {"occurrence": "Bracket", "face": [10, 505, 0]}})).unwrap_err().to_string() + }; + // Not on an edge; a face the edge doesn't bound. + assert!(bad(&mut s, json!({"occurrence": "Panel", "edge": [200, 150, 2]})).contains("no edge there")); + assert!(bad(&mut s, json!({"occurrence": "Panel", "edge": [200, 0, 2], "on": [200, 150, 0]})).contains("doesn't bound")); + // A design whose edge name no longer finds anything: the joint is left out with the reason. + run( + &mut s, + "joint.create", + json!({"type": "rigid", "a": {"occurrence": "Panel", "edge": [200, 0, 2]}, "b": {"occurrence": "Bracket", "face": [10, 505, 0]}, "name": "J"}), + ); + let mut doc = (*s.doc).clone(); + if let Some(j) = doc.assembly.joints.first_mut() + && let solidcraft_doc::joints::Snap::Edge { edge, .. } = &mut j.a.snap + { + *edge = Some("F999:nothing|F998:nowhere".into()); + } + *s.doc_mut() = doc; + let r = run(&mut s, "joint.solve", json!({})); + assert!(r["errors"][0]["why"].as_str().is_some_and(|w| w.contains("no longer exists")), "{r}"); +} diff --git a/crates/engine/src/cmd/joint_frames_tests.rs b/crates/engine/src/cmd/joint_frames_tests.rs new file mode 100644 index 000000000..c0d2cc06b --- /dev/null +++ b/crates/engine/src/cmd/joint_frames_tests.rs @@ -0,0 +1,96 @@ +//! A joint origin on a face or a hole keeps its turn about z as the geometry tilts. + +use serde_json::{Value, json}; +use solidcraft_geom::Vec3; + +use super::tests::{occ, run}; +use crate::Session; + +/// A 40 x 40 x 2 plate in component Panel, turned about Y by the `tilt` parameter (a Move feature), +/// and a 10 x 4 x 4 bar in component Bar, long along its X. +fn tilted(tilt: f64) -> Session { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "tilt", "expression": format!("{tilt} deg")})); + run(&mut s, "component.create", json!({"name": "Panel"})); + run(&mut s, "solid.box", json!({"length": 40, "width": 40, "height": 2, "corner": [-20, -20, 0]})); + let plate = s.model.state().bodies.last().map(|b| b.name.clone()).unwrap_or_default(); + run(&mut s, "solid.move", json!({"bodies": [plate], "axis": [0, 1, 0], "angle": "tilt"})); + run(&mut s, "component.activate", json!({"component": "root"})); + run(&mut s, "component.create", json!({"name": "Bar"})); + run(&mut s, "solid.box", json!({"length": 10, "width": 4, "height": 4, "corner": [100, 0, 0]})); + s +} + +/// A point on the plate's top face (the largest face facing up). +fn top(s: &mut Session) -> Value { + let body = s.model.state().bodies.first().map(|b| b.name.clone()).unwrap_or_default(); + let faces = run(s, "model.faces", json!({"body": body})); + let best = faces["faces"] + .as_array() + .into_iter() + .flatten() + .filter(|f| f["plane_normal"][2].as_f64().is_some_and(|z| z > 0.3)) + .max_by(|a, b| a["area"].as_f64().unwrap_or(0.0).total_cmp(&b["area"].as_f64().unwrap_or(0.0))) + .cloned() + .unwrap_or_default(); + best["point"].clone() +} + +/// How far the bar's long axis is turned from Y, the plate's axis of tilt (degrees, 0…90). +fn bar_from_tilt_axis(s: &Session) -> f64 { + let m = solidcraft_doc::joints::occurrence_world(&s.doc, occ(s, "Bar")); + let x = solidcraft_doc::apply_vector(&m, Vec3::X); + x.dot(Vec3::Y).abs().min(1.0).acos().to_degrees() +} + +#[test] +fn a_part_on_a_tilting_face_keeps_its_turn_where_the_face_normal_crosses_0_9_along_x() { + // The plate starts at 60°: its normal is 0.87 along X. Past 64.2° it is over 0.9, where a + // frame worked out from the normal alone picks its x another way and the bar turned a + // right angle on the face. + let mut s = tilted(60.0); + let a = top(&mut s); + run( + &mut s, + "joint.create", + json!({"type": "rigid", "a": {"occurrence": "Panel", "face": a}, "b": {"occurrence": "Bar", "face": [105, 2, 0]}, "name": "Seat"}), + ); + let start = bar_from_tilt_axis(&s); + for tilt in [62.0, 64.0, 66.0, 70.0, 80.0, 50.0, 30.0] { + run(&mut s, "parameters.change", json!({"name": "tilt", "expression": format!("{tilt} deg")})); + let now = bar_from_tilt_axis(&s); + assert!((now - start).abs() < 1e-6, "at {tilt}°: the bar is {now:.3}° from the tilt axis, {start:.3}° at first"); + let r = run(&mut s, "joint.solve", json!({})); + assert_eq!(r["errors"], json!([]), "{r}"); + } + // The origin keeps that x in the design. + let snap = s.doc.assembly.joints.first().map(|j| j.a.snap.clone()); + assert!(snap.as_ref().and_then(solidcraft_doc::joints::Snap::frame_x).is_some(), "{snap:?}"); +} + +#[test] +fn an_origin_saved_without_a_kept_x_is_placed_as_before() { + let mut s = tilted(30.0); + let a = top(&mut s); + run( + &mut s, + "joint.create", + json!({"type": "rigid", "a": {"occurrence": "Panel", "face": a}, "b": {"occurrence": "Bar", "face": [105, 2, 0]}, "name": "Seat"}), + ); + let kept = bar_from_tilt_axis(&s); + // The same joint as an older design has it: no x kept on either side. It is placed as + // a frame from the normal alone places it, which here is where the kept x placed it too. + let mut doc = (*s.doc).clone(); + for j in &mut doc.assembly.joints { + for o in [&mut j.a, &mut j.b] { + if let solidcraft_doc::joints::Snap::FaceCenter { x, .. } | solidcraft_doc::joints::Snap::CircleCenter { x, .. } = &mut o.snap { + *x = None; + } + } + } + let text = serde_json::to_string(&doc.assembly).unwrap_or_default(); + assert!(!text.contains("\"x\""), "{text}"); + *s.doc_mut() = doc; + run(&mut s, "joint.solve", json!({})); + assert!((bar_from_tilt_axis(&s) - kept).abs() < 1e-6); +} diff --git a/crates/engine/src/cmd/joints.rs b/crates/engine/src/cmd/joints.rs index a6e3a5607..1654fd765 100644 --- a/crates/engine/src/cmd/joints.rs +++ b/crates/engine/src/cmd/joints.rs @@ -17,10 +17,10 @@ use crate::{EngineError, Result, Session}; pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("joint.origin", "Joint Origin", joint_origin).at("SOLID", "CREATE").icon("joint_origin").params( - "name?, occurrence?: id|name (default: from the pick, or the named face's component), face: [x,y,z] | \"\" (centre of a planar face) | circle: [x,y,z] | \"\" (centre of a round end: a point on its wall or rim, the end's centre, or the round face's name as model.faces lists it) | point: [x,y,z], z?: [x,y,z]; body?: the named face's body; end?: \"\" (a circle's end: the face across its rim there; default the end nearer the pick); x?: [x,y,z] (a direction, world) | \"\" | {face: [x,y,z]} (the frame's x: a direction, a plane's normal, or the way to another hole's axis; keeps a round origin's turn). Faces are kept by name: the origin follows its face, and a circle its end, when the design changes", + "name?, occurrence?: id|name (default: from the pick, or the named face's component), face: [x,y,z] | \"\" (centre of a planar face) | circle: [x,y,z] | \"\" (centre of a round end: a point on its wall or rim, the end's centre, or the round face's name as model.faces lists it) | edge: [x,y,z] (a point on an edge of a planar face: the edge's middle, z out of the face, y into it; on?: [x,y,z] a point on the face (default: the larger planar face beside the edge); corner?: [x,y,z] near one end: the corner there, x and y along its two edges into the face; found again by name, so it follows the face as it changes size) | point: [x,y,z], z?: [x,y,z]; body?: the named face's body; end?: \"\" (a circle's end: the face across its rim there; default the end nearer the pick); x?: [x,y,z] (a direction, world) | \"\" | {face: [x,y,z]} (the frame's x: a direction, a plane's normal, or the way to another hole's axis; keeps a round origin's turn). Faces are kept by name: the origin follows its face, and a circle its end, when the design changes", ), CommandSpec::new("joint.create", "Joint", joint).at("SOLID", "ASSEMBLE").icon("joint").key("J").params( - "type: rigid|revolute|slider|cylindrical|pin_slot|planar|ball; a, b: joint origins ({occurrence, face|circle|point: [x,y,z] in world, or face|circle: \"\"; end?, x? as joint.origin} | origin name); \ + "type: rigid|revolute|slider|cylindrical|pin_slot|planar|ball; a, b: joint origins ({occurrence, face|circle|edge|point: [x,y,z] in world, or face|circle: \"\"; end?, x? as joint.origin} | origin name); \ values?: [angles in deg or expressions, distances]; limits?: [[min, max] | null…]; flip?: bool (default false: the origins are mated, \ b's z against a's as two faces meet; true: b's z along a's, so two origins given at one point with the same z stay as they are); \ offset?; angle?; name?; quiet?: bool (leave out dof and fixed)", @@ -279,11 +279,11 @@ fn origin_param(s: &Session, v: Option<&Value>, cmd: &str) -> Result x, (None, Some(f)) => ("frame", f.get("origin").and_then(vec3).ok_or_else(|| bad(cmd, "`frame` needs origin and z"))?), - _ => return Err(bad(cmd, "a joint origin needs face, circle, point or frame [x, y, z], or a face's name")), + _ => return Err(bad(cmd, "a joint origin needs face, circle, edge, point or frame [x, y, z], or a face's name")), }; let occurrence = match v.get("occurrence") { Some(o) => occurrence_id(s, Some(o), cmd)?, @@ -304,6 +304,10 @@ fn origin_param(s: &Session, v: Option<&Value>, cmd: &str) -> Result { + let (on, corner) = (v.get("on").and_then(vec3).map(local), v.get("corner").and_then(vec3).map(local)); + joints::edge_snap(&s.doc, &st, component, local(world), on, corner).map_err(|e| bad(cmd, e.to_string()))? + } "point" => Snap::Point { point: local(world), z: v.get("z").and_then(vec3).map(local_dir) }, _ => { let f = v.get("frame").cloned().unwrap_or_default(); @@ -373,8 +377,11 @@ fn settle(s: &Session, mut o: JointOrigin, v: &Value, cmd: &str) -> Result (Vec<(usize, u (pairs, skipped) } +#[cfg(test)] +#[path = "joint_edge_tests.rs"] +mod edge_tests; #[cfg(test)] #[path = "joints_face_tests.rs"] mod face_tests; #[cfg(test)] +#[path = "joint_frames_tests.rs"] +mod frames_tests; +#[cfg(test)] #[path = "joints_reach_tests.rs"] mod reach_tests; #[cfg(test)] diff --git a/docs/book/src/guide/assemblies.md b/docs/book/src/guide/assemblies.md index 6672bbf1a..b261722a5 100644 --- a/docs/book/src/guide/assemblies.md +++ b/docs/book/src/guide/assemblies.md @@ -28,6 +28,16 @@ made. Contact sets stop motion where bodies would pass through each other, **Motion Study** keys joint values along a timeline, and **Interference** shows overlapping volumes in red, lists the pairs closer than its **Clearance** and each body's nearest neighbour. +A joint origin on a face or a hole keeps the turn it had when it was picked: when the face tilts +(a bend angle or a rotation changing with a parameter) the part on it tilts with the face but +doesn't spin about it. + +A joint origin can also sit on an edge of a flat face (`"edge": [x, y, z]`): at the edge's middle, +pointing out of the face with its y into it, or with `"corner": [x, y, z]` at the corner near that +point, its x and y running along the two edges into the face. The edge, the face and the corner +are found again by name, so a bracket set 40 mm in from a panel's corner (a planar joint with +values `[40, 40, 0]`) stays 40 mm in from that corner when the panel changes size. + The check behind it, `inspect.clearance`, does all of that in one call for any number of bodies, which suits scripts and agents checking a whole assembly: From bc68e14c3e8e80a3911f9cc42dbe00fb1c7adcc2 Mon Sep 17 00:00:00 2001 From: Jackson Oursland Date: Sun, 18 Oct 2026 15:10:36 -0700 Subject: [PATCH 006/225] Mutation testing: judge kernel mutants by the black-box suites (#2660) The kernel will move from truck to solidcore (#1597). The tests that must catch regressions across that switch are the ones that don't depend on the kernel: the reference tests and the robustness goldens. cargo-mutants checks whether they would notice a change in the kernel's behaviour. - apps/solidcraft-cli/tests/oracle_cases.rs: the reference tests as a cargo test (ignored; CI keeps replaying them through cargo xtask oracle), run over one process per core. - .cargo/mutants.toml: mutants are judged by that test and the pull-request sample of the robustness goldens, not by the kernel's own unit tests. - A mutants profile (ci with incremental builds): about 15 s to rebuild after a kernel change instead of about 3 minutes. - docs/mutation-testing.md: how to run it, its cost, two cargo-mutants 27.1 problems and the pilot's results (15% of sampled kernel mutants caught). Co-authored-by: Claude Opus 5.5 (1M context) --- .cargo/mutants.toml | 14 +++++ .gitignore | 3 + CONTRIBUTING.md | 2 + Cargo.toml | 6 ++ apps/solidcraft-cli/tests/oracle_cases.rs | 66 ++++++++++++++++++++++ docs/mutation-testing.md | 69 +++++++++++++++++++++++ 6 files changed, 160 insertions(+) create mode 100644 .cargo/mutants.toml create mode 100644 apps/solidcraft-cli/tests/oracle_cases.rs create mode 100644 docs/mutation-testing.md diff --git a/.cargo/mutants.toml b/.cargo/mutants.toml new file mode 100644 index 000000000..2cc2da3ea --- /dev/null +++ b/.cargo/mutants.toml @@ -0,0 +1,14 @@ +# cargo-mutants (docs/mutation-testing.md). Mutants are judged by the black-box suites that will +# outlive the kernel backend: the reference tests (tests/oracle, through the oracle_cases test) +# and the pull-request sample of the robustness goldens (every 8th seed, as ci.yml). The +# kernel's own unit tests are left out on purpose: a mutant only they catch is a behaviour the +# backend-neutral suites would miss when the kernel is swapped. +profile = "mutants" +additional_cargo_test_args = [ + "--test", "oracle_cases", "--lib", "--", "--include-ignored", + "oracle_suite", + "robustness_goldens::seed_00", "robustness_goldens::seed_08", "robustness_goldens::seed_16", + "robustness_goldens::seed_24", "robustness_goldens::seed_32", "robustness_goldens::seed_40", + "robustness_goldens::seed_48", "robustness_goldens::seed_56", "robustness_goldens::seed_64", + "robustness_goldens::seed_72", "robustness_goldens::seed_80", "robustness_goldens::seed_88", +] diff --git a/.gitignore b/.gitignore index 0a9913f05..8e0305251 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,6 @@ /.claude/worktrees/ /target-snapshot __pycache__/ + +# cargo-mutants output (docs/mutation-testing.md) +mutants.out*/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 971144e4e..b4567e198 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -148,6 +148,8 @@ the most complete description of the house style. A geometry change that changes the robustness goldens re-records them in the same pull request: `ROBUSTNESS_GOLDENS_BLESS="why it changed" cargo test --profile ci -p solidcraft-engine --lib robustness_goldens::` (see [docs/robustness.md](docs/robustness.md)); CI runs every seed on pull requests that touch geometry. +[docs/mutation-testing.md](docs/mutation-testing.md) shows how to find kernel behaviour these +black-box suites miss. **UI scenarios** drive the real app headless: start a tool, click a plane or a sketch point, press keys, then assert on the result. diff --git a/Cargo.toml b/Cargo.toml index ba9d53840..6369851fe 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -142,3 +142,9 @@ matext4cgmath = { path = "vendor/matext4cgmath" } # Keep OpenGL pipelines, resolve textures and CAD callbacks at the same safe sample count. egui-wgpu = { path = "vendor/egui-wgpu" } + +# Mutation testing (cargo-mutants, docs/mutation-testing.md): the ci profile with incremental +# builds, since every mutant rebuilds the crates above the one it changes. +[profile.mutants] +inherits = "ci" +incremental = true diff --git a/apps/solidcraft-cli/tests/oracle_cases.rs b/apps/solidcraft-cli/tests/oracle_cases.rs new file mode 100644 index 000000000..76b062763 --- /dev/null +++ b/apps/solidcraft-cli/tests/oracle_cases.rs @@ -0,0 +1,66 @@ +//! The reference tests (tests/oracle, docs/oracle.md) as a `cargo test`, so tools that drive +//! `cargo test` (cargo-mutants) can use them: every case with expected values and no +//! `known_failure` mark must pass, as `cargo xtask oracle` requires. + +use std::path::Path; +use std::process::Command; + +use serde_json::Value; + +#[test] +#[ignore = "run by cargo-mutants (.cargo/mutants.toml); CI replays the oracle through cargo xtask oracle"] +fn oracle_suite() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let dir = root.join("tests/oracle"); + let mut cases: Vec = std::fs::read_dir(&dir) + .unwrap() + .flatten() + .map(|e| e.path()) + .filter(|p| p.join("recipe.json").is_file()) + .map(|p| format!("tests/oracle/{}", p.file_name().unwrap().to_string_lossy())) + .collect(); + cases.sort(); + assert!(cases.len() >= 50, "oracle cases in {}", dir.display()); + // One process per core, cases dealt round-robin so the slow ones spread out. + let n = std::thread::available_parallelism().map_or(4, |n| n.get()).min(cases.len()); + let children: Vec<_> = (0..n) + .map(|i| { + let chunk: Vec<&String> = cases.iter().skip(i).step_by(n).collect(); + Command::new(env!("CARGO_BIN_EXE_solidcraft-cli")) + .current_dir(&root) + .arg("oracle") + .arg("--json") + .args(chunk) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap() + }) + .collect(); + let mut results: Vec = Vec::new(); + for child in children { + let out = child.wait_with_output().unwrap(); + let part: Vec = + serde_json::from_slice(&out.stdout).unwrap_or_else(|e| panic!("oracle JSON: {e}\n{}", String::from_utf8_lossy(&out.stderr))); + results.extend(part); + } + assert_eq!(results.len(), cases.len()); + let mut failed = Vec::new(); + for r in &results { + let case = r["case"].as_str().unwrap_or(""); + let want: Value = + std::fs::read_to_string(dir.join(case).join("expected.json")).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default(); + if want.is_null() || want["known_failure"].is_string() || r["pass"].as_bool().unwrap_or(false) { + continue; + } + let checks: Vec = r["checks"] + .as_array() + .into_iter() + .flatten() + .filter(|c| !c["ok"].as_bool().unwrap_or(false)) + .map(|c| format!("{} got {} want {}", c["check"].as_str().unwrap_or(""), c["got"], c["want"])) + .collect(); + failed.push(format!("{case}: {} {}", r["error"].as_str().unwrap_or(""), checks.join("; "))); + } + assert!(failed.is_empty(), "oracle cases failed:\n{}", failed.join("\n")); +} diff --git a/docs/mutation-testing.md b/docs/mutation-testing.md new file mode 100644 index 000000000..74c54f49f --- /dev/null +++ b/docs/mutation-testing.md @@ -0,0 +1,69 @@ +# Mutation testing + +SolidCraft will move from truck to solidcore (#1597). The tests that have to catch regressions +across that switch are the ones that don't depend on the kernel: the reference tests +([docs/oracle.md](oracle.md)), the robustness goldens ([docs/robustness.md](robustness.md)) and +the engine's command tests. Most of the kernel's own unit tests call truck-specific code and go +away with it. + +Mutation testing checks those suites. [cargo-mutants](https://mutants.rs) makes small changes to +the source, one at a time (`*` becomes `/`, a condition is negated, a function returns a default +value), rebuilds, and runs the tests. A mutant the tests don't catch is a change in behaviour +nobody would notice, and solidcore could get the same thing wrong without anyone noticing. + +## What judges a mutant + +`.cargo/mutants.toml` judges mutants by the black-box suites only: + +- `oracle_suite` (`apps/solidcraft-cli/tests/oracle_cases.rs`): every case in `tests/oracle` with + expected values and no `known_failure` must pass, as `cargo xtask oracle` requires. It is + `#[ignore]`d so CI doesn't replay the oracle twice. +- The pull-request sample of the robustness goldens: every 8th seed, as `ci.yml` runs it. + +The kernel's unit tests are left out on purpose. A mutant that only they catch marks a behaviour +the black-box suites would miss once the kernel is swapped. + +## Running it + +``` +cargo install cargo-mutants --locked +CARGO_TARGET_DIR=$PWD/target cargo mutants --in-place \ + -f crates/kernel/src/measure.rs \ + --test-package solidcraft-cli --test-package solidcraft-engine \ + --baseline skip --timeout 900 --build-timeout 900 +``` + +- Use a worktree you don't otherwise touch: `--in-place` writes each mutant into the source tree + and restores it afterwards. +- `--shard 0/200 --sharding round-robin` with `-d crates/kernel` takes an even sample (every 200th + mutant) of the whole crate. +- The `mutants` profile in `Cargo.toml` is the `ci` profile with incremental builds. It cuts the + rebuild after a kernel change from about 3 minutes to about 15 seconds. +- A mutant costs 1.5–5 minutes on a 12-core Mac, mostly the tests. The kernel has about 40,000 + mutants, so run a sample or one file at a time, never the whole crate. This is a tool for + finding gaps, not a CI gate. + +Two problems with cargo-mutants 27.1 are behind the flags above: + +- The baseline (the unmutated run) ignores `--test-package` and tests the mutated crate, which + fails. Skip it with `--baseline skip`, set `--timeout` yourself, and check the unmutated tree + passes first. +- `--re` and `--exclude-re` don't filter "delete field" mutants. Saved diffs in + `mutants.out/diff/` name the mutation, not the file, in their `+++` line: apply one with + `patch < `. + +## Pilot results (October 2026, `cb857f1f`) + +| Sample | Mutants that build | Caught by the black-box suites | +|---|---:|---:| +| `crates/kernel/src/measure.rs`, every mutant | 85 | 85% | +| Whole kernel, every 200th mutant | 173 | 15% (95% interval 10–21%) | + +Out of 49 of the kernel sample's survivors, the kernel's own unit tests caught 21 (43%) and +nothing caught 28 (57%). About 11% of survivors swap `>` and `>=` on floating-point values that +are never exactly equal, so they don't change behaviour. + +The black-box suites are weakest on tessellation and the display mesh (0 of 19 mutants caught), +offset, shell, emboss and lip (0 of 14), blends (15%) and STEP/IGES exchange (17%). For a +survivor that a kernel unit test catches, that test's design is the starting point for a new +oracle case or engine test. From ff5d96aaad732f0d196c9bae7447a514ecdd6f6b Mon Sep 17 00:00:00 2001 From: bherbruck Date: Sun, 18 Oct 2026 18:10:43 -0400 Subject: [PATCH 007/225] Docker: accept trunk's shorter content hashes (#2734) Trunk formats the content hash without leading zeros, so it is sometimes 15 hex characters. The immutable-cache rule and the smoke test's wasm match now accept 8 to 16. Co-authored-by: Claude Sonnet 5.5 --- packaging/docker/nginx.conf | 2 +- packaging/docker/smoke-test.sh | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packaging/docker/nginx.conf b/packaging/docker/nginx.conf index 935bd8515..4869bf433 100644 --- a/packaging/docker/nginx.conf +++ b/packaging/docker/nginx.conf @@ -20,7 +20,7 @@ server { add_header X-Content-Type-Options "nosniff" always; } - location ~ "-[0-9a-f]{16}(_bg)?\.(js|wasm|css)$" { + location ~ "-[0-9a-f]{8,16}(_bg)?\.(js|wasm|css)$" { add_header Cache-Control "public, max-age=31536000, immutable" always; add_header X-Content-Type-Options "nosniff" always; } diff --git a/packaging/docker/smoke-test.sh b/packaging/docker/smoke-test.sh index e2add0c95..60fb68bec 100755 --- a/packaging/docker/smoke-test.sh +++ b/packaging/docker/smoke-test.sh @@ -30,7 +30,7 @@ curl -fs "$BASE/" | grep -q 'solidcraft_canvas' || fail "index.html is not the a curl -fs "$BASE/sw.js" | grep -q 'const VERSION = "dev"' && fail "sw.js is the unbuilt template (not a release build)" [ "$(header "$BASE/build.json" Cache-Control)" = no-cache ] || fail "build.json must not be cached" -WASM="$(curl -fs "$BASE/" | grep -o 'solidcraft-web-[0-9a-f]*_bg\.wasm' | head -n1)" +WASM="$(curl -fs "$BASE/" | grep -o 'solidcraft-web-[0-9a-f]\{8,16\}_bg\.wasm' | head -n1)" [ -n "$WASM" ] || fail "index.html names no wasm" [ "$(header "$BASE/$WASM" Content-Type)" = application/wasm ] || fail "$WASM is not served as application/wasm" header "$BASE/$WASM" Cache-Control | grep -q immutable || fail "$WASM should be cached as immutable" From 207c67d1da16ffb0adc734bf1e0c278a4b122840 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Sun, 18 Oct 2026 18:10:49 -0400 Subject: [PATCH 008/225] Flatpak smoke test: wait for the viewport before the Wayland probe (#2736) The control port opens before the first frame, so a single ui.inspect sometimes returned no viewport and the check failed within seconds. The probe now polls ui.inspect until the viewport exists, for up to 60 s, and fails with the last reply if it never does. Co-authored-by: Claude Sonnet 5.5 --- packaging/linux/flatpak-smoke.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/packaging/linux/flatpak-smoke.py b/packaging/linux/flatpak-smoke.py index 7b360f73e..303a37fec 100644 --- a/packaging/linux/flatpak-smoke.py +++ b/packaging/linux/flatpak-smoke.py @@ -47,7 +47,18 @@ for ((attempt=0; attempt<300; attempt++)); do sleep .1 done test "$ready" = 1 -for request in "{\"id\":1,\"method\":\"ui.inspect\",\"params\":{},\"token\":\"$SOLIDCRAFT_CONTROL_TOKEN\"}" '{"id":2,"method":"engine.execute","params":{"command":"solid.box","params":{"length":30,"width":20,"height":10}}}' '{"id":3,"method":"document.inspect","params":{"measure":true}}'; do +# The control port opens before the first frame, so ui.inspect has no viewport yet; poll until it does. +inspect="{\"id\":1,\"method\":\"ui.inspect\",\"params\":{},\"token\":\"$SOLIDCRAFT_CONTROL_TOKEN\"}" +deadline=$((SECONDS + 60)) +until printf '%s\n' "$inspect" >&3 && IFS= read -r -t 30 reply <&3 && [[ "$reply" =~ \"viewport\":\ *\[ ]]; do + if ! kill -0 "$app" 2>/dev/null || ((SECONDS >= deadline)); then + echo "viewport never appeared: ${reply:-no reply}" >&2 + exit 1 + fi + sleep .25 +done +printf '%s\n' "$reply" +for request in '{"id":2,"method":"engine.execute","params":{"command":"solid.box","params":{"length":30,"width":20,"height":10}}}' '{"id":3,"method":"document.inspect","params":{"measure":true}}'; do printf '%s\n' "$request" >&3 IFS= read -r -t 30 reply <&3 printf '%s\n' "$reply" From 4a4eb59788eb2c87cde4f07c5c3d3b6a2c11d3ed Mon Sep 17 00:00:00 2001 From: Tyler Chiriboga Date: Sun, 18 Oct 2026 17:10:56 -0500 Subject: [PATCH 009/225] 3MF import: read objects in other model parts (production extension) (#2089) (#2127) * claim: #2089 Co-Authored-By: Claude Opus 5.5 * 3MF import: read objects in other model parts (production extension) (#2089) Slicers save multi-part projects with the 3MF Production extension: the root model's objects are components with `p:path` naming another model part of the package, which holds the meshes. The reader skipped those components and build items, so such files did not open at all. Components and build items now keep the part they name, and the parts objects name are read once each (looked up through an index of the zip entries), with the number of part names and their total size capped. Each part's unit is applied as it is read, so parts in different units fit together. Cycle detection keys on (part, object), so parts that place each other in a loop are refused. Tests: components and build items in another part, part names in any case, a part in centimetres under a root in millimetres, and hostile packages (missing part, a path out of the package, an empty path, an unknown object, a part that is no model, a loop between parts, more part names than a package can hold). The 3MF mutation fuzz also runs on a production-extension package. Co-Authored-By: Claude Opus 5.5 * 3MF import: count every placement toward the budget (#2089) An object that only places other objects added nothing to the triangle budget, so a few objects each placing hundreds of components multiplied at every level up to the depth cap (300 components, 3 levels: about 1 s; deeper never finished). That was already true for one model part and now reaches across parts. Every placement now costs at least one unit, so such a file stops at the budget. Test: six levels of 300 components over an empty object (300^6 placements) stop with a budget error in well under a second; without the change the test does not finish. Suggested in review by @jyviko. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Tyler Chiriboga <18270301+Tyler-Chiriboga@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 Co-authored-by: bherbruck --- crates/io/src/mutate.rs | 6 + crates/io/src/threemf.rs | 321 ++++++++++++++++++++++++++++++----- docs/book/src/guide/files.md | 4 + 3 files changed, 285 insertions(+), 46 deletions(-) diff --git a/crates/io/src/mutate.rs b/crates/io/src/mutate.rs index f907e56a6..9eb106170 100644 --- a/crates/io/src/mutate.rs +++ b/crates/io/src/mutate.rs @@ -461,6 +461,12 @@ outer survives("3MF", &mutations(&good, false, 0x3f), usize::MAX, |b| { crate::read_3mf(b).ok().map(|(objects, _)| objects.iter().map(|o| o.triangles.len()).sum()) }); + // Objects in another model part (production extension), as slicers save projects. + let production = crate::threemf::tests::production_package(); + assert!(crate::read_3mf(&production).is_ok()); + survives("3MF (production extension)", &mutations(&production, false, 0x2089), usize::MAX, |b| { + crate::read_3mf(b).ok().map(|(objects, _)| objects.iter().map(|o| o.triangles.len()).sum()) + }); } #[test] diff --git a/crates/io/src/threemf.rs b/crates/io/src/threemf.rs index 351f0f83f..534827def 100644 --- a/crates/io/src/threemf.rs +++ b/crates/io/src/threemf.rs @@ -6,10 +6,12 @@ //! triangle, the B-rep face it lies on (`ft:face`, SolidCraft's face-tag namespace; spec: //! docs/formats/3mf-face-tags.md) and are written at full `f64` //! precision so the receiver gets the tessellation exactly. Reading: every build item becomes one mesh -//! (components flattened with their transforms), converted to millimetres. Packages are -//! untrusted: sizes, entry counts, mesh sizes and component nesting are capped. +//! (components flattened with their transforms), converted to millimetres. Components and build +//! items may name an object in another model part of the package (`p:path`, the 3MF Production +//! extension, which slicers use for multi-part projects); those parts are read too. Packages are +//! untrusted: sizes, entry counts, model parts, mesh sizes and component nesting are capped. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::fmt::Write as _; use std::io::{Cursor, Read, Write}; @@ -350,13 +352,21 @@ fn bad(msg: impl Into) -> Result { Err(IoError::Invalid(format!("3MF: {}", msg.into()))) } +/// The name a part is looked up by: no leading `/`, in lower case (part names compare +/// case-insensitively). +fn part_key(name: &str) -> String { + name.replace('\\', "/").trim_start_matches('/').to_ascii_lowercase() +} + fn read_part(zip: &mut zip::ZipArchive>, name: &str) -> Result>> { - let want = name.trim_start_matches('/').to_ascii_lowercase(); - let Some(idx) = (0..zip.len()).find(|i| { - zip.name_for_index(*i).and_then(|n| n.ok()).is_some_and(|n| n.replace('\\', "/").trim_start_matches('/').to_ascii_lowercase() == want) - }) else { + let want = part_key(name); + let Some(idx) = (0..zip.len()).find(|i| zip.name_for_index(*i).and_then(|n| n.ok()).is_some_and(|n| part_key(&n) == want)) else { return Ok(None); }; + read_entry(zip, idx, name).map(Some) +} + +fn read_entry(zip: &mut zip::ZipArchive>, idx: usize, name: &str) -> Result> { let mut f = zip.by_index(idx).map_err(|e| IoError::Invalid(format!("3MF {name}: {e}")))?; if f.size() > MAX_PART { return bad(format!("{name} expands to {} bytes", f.size())); @@ -366,7 +376,7 @@ fn read_part(zip: &mut zip::ZipArchive>, name: &str) -> Result MAX_PART { return bad(format!("{name} expands to more than 1 GB")); } - Ok(Some(out)) + Ok(out) } fn attrs(e: &BytesStart) -> HashMap { @@ -401,6 +411,14 @@ fn parse_xf(s: Option<&String>) -> Result { Ok(m) } +/// `xf` with its translation, given in a model's `unit`, in millimetres. +fn in_mm(mut xf: Xf, unit: f64) -> Xf { + for t in xf.iter_mut().skip(9) { + *t *= unit; + } + xf +} + fn apply(m: &Xf, p: Vec3) -> Vec3 { Vec3::new(p.x * m[0] + p.y * m[3] + p.z * m[6] + m[9], p.x * m[1] + p.y * m[4] + p.z * m[7] + m[10], p.x * m[2] + p.y * m[5] + p.z * m[8] + m[11]) } @@ -417,22 +435,37 @@ fn det(m: &Xf) -> f64 { m[0] * (m[4] * m[8] - m[5] * m[7]) - m[1] * (m[3] * m[8] - m[5] * m[6]) + m[2] * (m[3] * m[7] - m[4] * m[6]) } +/// A component or build item: object `id` placed by `xf`, in model part `part` (its key, from +/// `p:path`) or, without one, in the part that names it. +struct Ref { + part: Option, + id: u32, + xf: Xf, +} + #[derive(Default)] struct Object { name: String, positions: Vec, triangles: Vec<[u32; 3]>, - components: Vec<(u32, Xf)>, + components: Vec, material: Option<(u32, usize)>, } +/// One model part. Positions and translations are in millimetres (converted with the part's +/// unit as it is read), so objects of parts in different units fit together. #[derive(Default)] struct Model { unit: f64, objects: HashMap, materials: HashMap>>, - build: Vec<(u32, Xf)>, - warnings: Vec, + build: Vec, +} + +/// The model parts read from a package, by key, and the key of the root model. +struct Package { + root: String, + parts: HashMap, } fn color(s: &str) -> Option<[f32; 3]> { @@ -540,7 +573,7 @@ fn parse_model(xml: &[u8]) -> Result { return bad("too many vertices"); } let (Some(x), Some(y), Some(z)) = (num("x"), num("y"), num("z")) else { return bad("vertex without x, y, z") }; - o.positions.push(Vec3::new(x, y, z)); + o.positions.push(Vec3::new(x, y, z) * m.unit); } b"triangle" => { let Some((_, o)) = cur.as_mut() else { return bad("triangle outside an object") }; @@ -552,22 +585,12 @@ fn parse_model(xml: &[u8]) -> Result { } b"component" => { let Some((_, o)) = cur.as_mut() else { return bad("component outside an object") }; - if a.keys().any(|k| k == "path") { - m.warnings.push("components in other model parts (production extension) are not read".into()); - buf.clear(); - continue; - } let target = id("objectid").ok_or_else(|| IoError::Invalid("3MF: component without objectid".into()))?; - o.components.push((target, parse_xf(a.get("transform"))?)); + o.components.push(Ref { part: a.get("path").map(|p| part_key(p)), id: target, xf: in_mm(parse_xf(a.get("transform"))?, m.unit) }); } b"item" => { - if a.keys().any(|k| k == "path") { - m.warnings.push("build items in other model parts (production extension) are not read".into()); - buf.clear(); - continue; - } let target = id("objectid").ok_or_else(|| IoError::Invalid("3MF: build item without objectid".into()))?; - m.build.push((target, parse_xf(a.get("transform"))?)); + m.build.push(Ref { part: a.get("path").map(|p| part_key(p)), id: target, xf: in_mm(parse_xf(a.get("transform"))?, m.unit) }); } _ => {} } @@ -579,15 +602,58 @@ fn parse_model(xml: &[u8]) -> Result { Ok(m) } -/// Append object `id` (and its components) placed by `xf` to `out`. -fn flatten(m: &Model, id: u32, xf: &Xf, out: &mut MeshObject, stack: &mut Vec, total: &mut usize) -> Result<()> { - if stack.len() > MAX_COMPONENT_DEPTH || stack.contains(&id) { +/// Queue the model parts `m` names that were not seen yet. +fn queue_parts(m: &Model, seen: &mut HashSet, pending: &mut Vec) -> Result<()> { + for key in m.objects.values().flat_map(|o| &o.components).chain(&m.build).filter_map(|r| r.part.as_ref()) { + if !seen.contains(key) { + // A package holds no more parts than it has entries. + if seen.len() >= MAX_ENTRIES { + return bad(format!("objects name more than {MAX_ENTRIES} model parts")); + } + seen.insert(key.clone()); + pending.push(key.clone()); + } + } + Ok(()) +} + +/// An error reading model part `key`, saying which part it was. +fn in_part(key: &str, e: IoError) -> IoError { + match e { + IoError::Invalid(msg) => { + let msg = msg.strip_prefix("3MF: ").or_else(|| msg.strip_prefix("3MF ")).unwrap_or(&msg); + IoError::Invalid(format!("3MF model part `{key}`: {msg}")) + } + e => e, + } +} + +/// Append object `id` of model part `part` (and its components) placed by `xf` to `out`. +fn flatten<'a>( + pkg: &'a Package, + part: &'a str, + id: u32, + xf: &Xf, + out: &mut MeshObject, + stack: &mut Vec<(&'a str, u32)>, + total: &mut usize, +) -> Result<()> { + if stack.len() > MAX_COMPONENT_DEPTH || stack.contains(&(part, id)) { return bad("components nested too deeply or recursive"); } - let o = m.objects.get(&id).ok_or_else(|| IoError::Invalid(format!("3MF: missing object {id}")))?; - *total = total.saturating_add(o.triangles.len()); + let m = pkg.parts.get(part).ok_or_else(|| IoError::Invalid(format!("3MF: no model part `{part}`")))?; + let o = m.objects.get(&id).ok_or_else(|| { + IoError::Invalid(if part == pkg.root { + format!("3MF: missing object {id}") + } else { + format!("3MF: missing object {id} in model part `{part}`") + }) + })?; + // Every placement costs at least one unit of the budget, so objects that only place other + // objects cannot fan out (hundreds of components per level, nested) into endless visits. + *total = total.saturating_add(o.triangles.len().max(1)); if *total > MAX_ELEMENTS { - return bad("too many triangles after placing components"); + return bad("too many triangles or placements after placing components"); } let n = o.positions.len(); // One object can be placed by thousands of build items and components, and each placement @@ -608,7 +674,7 @@ fn flatten(m: &Model, id: u32, xf: &Xf, out: &mut MeshObject, stack: &mut Vec Result<(Vec, Vec)> { } } let xml = read_part(&mut zip, &root)?.ok_or_else(|| IoError::Invalid(format!("3MF: no model part `{root}`")))?; - let m = parse_model(&xml)?; + let root = part_key(&root); + let model = parse_model(&xml)?; + let mut model_bytes = xml.len(); + // The model parts objects name (production extension), each read once. The entries are + // indexed first, so a package naming thousands of parts costs no scan per name; a name + // with no entry is left out, and the placements that need it say so. + let mut entries = HashMap::new(); + for i in 0..zip.len() { + if let Some(Ok(n)) = zip.name_for_index(i) { + entries.entry(part_key(&n)).or_insert(i); + } + } + let mut seen = HashSet::from([root.clone()]); + let mut pending = Vec::new(); + queue_parts(&model, &mut seen, &mut pending)?; + let mut parts = HashMap::from([(root.clone(), model)]); + while let Some(key) = pending.pop() { + let Some(&idx) = entries.get(&key) else { continue }; + let xml = read_entry(&mut zip, idx, &key)?; + model_bytes = model_bytes.saturating_add(xml.len()); + if model_bytes as u64 > MAX_PART { + return bad("model parts expand to more than 1 GB"); + } + let m = parse_model(&xml).map_err(|e| in_part(&key, e))?; + queue_parts(&m, &mut seen, &mut pending)?; + parts.insert(key, m); + } + let pkg = Package { root, parts }; + let Some(model) = pkg.parts.get(&pkg.root) else { return bad("no root model") }; let mut out = Vec::new(); - let mut warnings = m.warnings.clone(); + let mut warnings = Vec::new(); let mut total = 0usize; - for (k, (id, xf)) in m.build.iter().enumerate() { + for (k, item) in model.build.iter().enumerate() { + let part = item.part.as_deref().unwrap_or(&pkg.root); let mut mo = MeshObject::default(); - match flatten(&m, *id, xf, &mut mo, &mut Vec::new(), &mut total) { + match flatten(&pkg, part, item.id, &item.xf, &mut mo, &mut Vec::new(), &mut total) { Ok(()) if !mo.triangles.is_empty() => { - let name = m.objects.get(id).map(|o| o.name.trim().to_string()).filter(|n| !n.is_empty()); + let name = pkg.parts.get(part).and_then(|m| m.objects.get(&item.id)).map(|o| o.name.trim().to_string()).filter(|n| !n.is_empty()); mo.name = name.unwrap_or_else(|| format!("Mesh{}", k + 1)); out.push(mo); } @@ -690,7 +785,7 @@ pub fn read_3mf(bytes: &[u8]) -> Result<(Vec, Vec)> { } #[cfg(test)] -mod tests { +pub(crate) mod tests { use super::*; fn tetra(name: &str) -> MeshObject { @@ -718,18 +813,135 @@ mod tests { assert_eq!(model.matches("p1=\"1\"").count(), 1, "{model}"); } - fn package(model: &str, rels: Option<&str>) -> Vec { + /// A package of these parts (name, contents). + fn package_parts(parts: &[(&str, &str)]) -> Vec { let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new())); let o = zip::write::SimpleFileOptions::default(); - if let Some(r) = rels { - zip.start_file("_rels/.rels", o).unwrap(); - zip.write_all(r.as_bytes()).unwrap(); + for (name, data) in parts { + zip.start_file(*name, o).unwrap(); + zip.write_all(data.as_bytes()).unwrap(); } - zip.start_file("3D/3dmodel.model", o).unwrap(); - zip.write_all(model.as_bytes()).unwrap(); zip.finish().unwrap().into_inner() } + fn package(model: &str, rels: Option<&str>) -> Vec { + let mut parts: Vec<(&str, &str)> = rels.map(|r| ("_rels/.rels", r)).into_iter().collect(); + parts.push(("3D/3dmodel.model", model)); + package_parts(&parts) + } + + const PRODUCTION: &str = r#"xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02" xmlns:p="http://schemas.microsoft.com/3dmanufacturing/production/2015/06" requiredextensions="p""#; + const OBJECTS_PART: &str = "3D/Objects/object_1.model"; + + /// Object `id`: a tetrahedron with legs of `s` along the axes (volume s³/6). + fn tet_object(id: u32, name: &str, s: f64) -> String { + format!( + r#""# + ) + } + + /// A model part holding `objects`, in `unit`, with no build items of its own. + fn model_part(unit: &str, objects: &str) -> String { + format!(r#"{objects}"#) + } + + fn volume(o: &MeshObject) -> f64 { + let p = |i: u32| o.positions[i as usize]; + o.triangles.iter().map(|t| p(t[0]).dot(p(t[1]).cross(p(t[2])))).sum::() / 6.0 + } + + /// A multi-part project as slicers save it: the root model's object is two components in + /// another model part, which holds the meshes. + pub(crate) fn production_package() -> Vec { + let root = format!( + r#" + + +"# + ); + let objects = model_part("millimeter", &format!("{}{}", tet_object(1, "A", 1.0), tet_object(2, "B", 2.0))); + package_parts(&[("3D/3dmodel.model", &root), (OBJECTS_PART, &objects)]) + } + + /// Objects kept in a model part of their own (3MF Production extension) come in with their + /// components' and the build item's transforms (#2089). + #[test] + fn components_in_other_model_parts() { + let (objs, warnings) = read_3mf(&production_package()).unwrap(); + assert!(warnings.is_empty(), "{warnings:?}"); + assert_eq!(objs.len(), 1); + let o = &objs[0]; + assert_eq!(o.name, "Pair"); + assert_eq!(o.triangles.len(), 8); + assert!((volume(o) - (1.0 + 8.0) / 6.0).abs() < 1e-9, "{}", volume(o)); + // B moved 5 along x by its component, both 2 up by the build item. + let max_x = o.positions.iter().map(|p| p.x).fold(f64::MIN, f64::max); + assert!((max_x - 7.0).abs() < 1e-9, "{max_x}"); + assert!(o.positions.iter().all(|p| p.z >= 2.0 - 1e-9 && p.z <= 4.0 + 1e-9)); + } + + /// Build items can name another part too, part names compare without regard to case, and + /// each part has its own unit: positions come out in millimetres, translations in the unit + /// of the part that names them. + #[test] + fn build_items_in_other_model_parts_and_their_units() { + let root = format!( + r#" + +"# + ); + let objects = model_part("centimeter", &format!("{}{}", tet_object(1, "A", 1.0), tet_object(2, "B", 2.0))); + let (objs, warnings) = read_3mf(&package_parts(&[("3D/3dmodel.model", &root), (OBJECTS_PART, &objects)])).unwrap(); + assert!(warnings.is_empty(), "{warnings:?}"); + let names: Vec<&str> = objs.iter().map(|o| o.name.as_str()).collect(); + assert_eq!(names, ["A", "B"]); + // A: legs of 1 cm, moved 5 mm; B: legs of 2 cm. + assert!((volume(&objs[0]) - 1000.0 / 6.0).abs() < 1e-6 && (volume(&objs[1]) - 8000.0 / 6.0).abs() < 1e-6); + let xs = |o: &MeshObject| o.positions.iter().map(|p| p.x).fold((f64::MAX, f64::MIN), |(a, b), x| (a.min(x), b.max(x))); + assert_eq!(xs(&objs[0]), (5.0, 15.0)); + assert_eq!(xs(&objs[1]), (0.0, 20.0)); + } + + #[test] + fn hostile_model_parts_are_errors() { + let root = |components: &str| { + format!( + r#"{components}"# + ) + }; + let to_objects = r#""#; + let tet = model_part("millimeter", &tet_object(1, "A", 1.0)); + let looped = model_part( + "millimeter", + r#""#, + ); + let many: String = (0..=MAX_ENTRIES).map(|i| format!(r#""#)).collect(); + let cases = [ + // A part that isn't in the package, one outside it and an empty name. + package_parts(&[("3D/3dmodel.model", &root(r#""#))]), + package_parts(&[("3D/3dmodel.model", &root(r#""#)), (OBJECTS_PART, &tet)]), + package_parts(&[("3D/3dmodel.model", &root(r#""#)), (OBJECTS_PART, &tet)]), + // An object the part doesn't have. + package_parts(&[("3D/3dmodel.model", &root(r#""#)), (OBJECTS_PART, &tet)]), + // A part that is no model. + package_parts(&[("3D/3dmodel.model", &root(to_objects)), (OBJECTS_PART, "not xml")]), + // Parts that place each other in a loop. + package_parts(&[("3D/3dmodel.model", &root(to_objects)), (OBJECTS_PART, &looped)]), + // More part names than a package can hold. + package_parts(&[("3D/3dmodel.model", &root(&many))]), + ]; + for (i, c) in cases.iter().enumerate() { + assert!(read_3mf(c).is_err(), "case {i}"); + } + // A placement whose part is missing is reported; the others still come in. + let two = format!( + r#""# + ); + let (objs, warnings) = read_3mf(&package_parts(&[("3D/3dmodel.model", &two), (OBJECTS_PART, &tet)])).unwrap(); + assert_eq!(objs.len(), 1); + assert!(warnings.iter().any(|w| w.contains("build item 2") && w.contains("gone.model")), "{warnings:?}"); + } + #[test] fn package_is_well_formed() { let mut t = tetra("A <&> \"b\""); @@ -837,6 +1049,23 @@ mod tests { assert!(t.elapsed() < std::time::Duration::from_secs(30), "took {:?}", t.elapsed()); } + /// Objects that only place other objects count toward the budget too: six levels of 300 + /// components over an empty object (300^6 placements, and no triangles to count) stop at the + /// budget instead of running for days. + #[test] + fn nested_fan_out_of_empty_objects_is_bounded() { + let t = std::time::Instant::now(); + let components = |child: u32| (0..300).map(|_| format!(r#""#)).collect::(); + let mut objects = r#""#.to_string(); + for id in 2..=7 { + objects += &format!(r#"{}"#, components(id - 1)); + } + let model = format!(r#"{objects}"#); + let err = read_3mf(&package(&model, None)).unwrap_err().to_string(); + assert!(err.contains("placements"), "{err}"); + assert!(t.elapsed() < std::time::Duration::from_secs(30), "took {:?}", t.elapsed()); + } + /// Triangles are budgeted across every placement, so fan-out cannot outrun the cap. #[test] fn placements_share_the_triangle_budget() { diff --git a/docs/book/src/guide/files.md b/docs/book/src/guide/files.md index f0e5eeb30..ee253e6fa 100644 --- a/docs/book/src/guide/files.md +++ b/docs/book/src/guide/files.md @@ -34,6 +34,10 @@ the model looks right in Render; textures, skins and animations are not imported mirrored nodes are baked into their meshes. Compressed meshes (Draco, meshopt) are refused with a message: save the file uncompressed first. +A 3MF project saved by a slicer comes in too, also when it keeps its objects in model parts of +their own inside the file (the 3MF Production extension): each object on the build plate becomes +a mesh body, with its parts where the slicer placed them. + **File → Save as mesh…** (also on the Mesh tab under Modify, and in the right-click menu of a body) saves the selected bodies as STL, 3MF or 3MF with face tags (below). With **Send to slicer** ticked, it writes the file to a temporary folder and opens it in the chosen slicer instead of asking for a file name. The slicer From 011ff24107f0eff9064f4a3f02dec5f62912557c Mon Sep 17 00:00:00 2001 From: Irakli Kourtis Date: Sun, 18 Oct 2026 18:11:03 -0400 Subject: [PATCH 010/225] fix(i18n): unify font baseline for CJK UI (macOS, Linux, Windows) (#2123) In a CJK UI, the primary CJK face goes first in Proportional, so digits, units and symbols in mixed labels share the CJK text's metrics and baseline. A Korean UI puts the Hangul face first. The user's ~/Library/Fonts is scanned for a CJK font on macOS. Rebased onto main as one commit (main had added the Thai fallback). Co-authored-by: Mithril-3d <145893541+Mithril-3d@users.noreply.github.com> Co-authored-by: bherbruck --- crates/ui-egui/src/fonts.rs | 71 +++++++++++++++++++++++++++++++------ 1 file changed, 60 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/fonts.rs b/crates/ui-egui/src/fonts.rs index 1881f651c..14ec936eb 100644 --- a/crates/ui-egui/src/fonts.rs +++ b/crates/ui-egui/src/fonts.rs @@ -111,11 +111,31 @@ fn with_fallback(mut fonts: egui::FontDefinitions, name: &str, bytes: Vec) - Some(fonts) } +/// Move `name` to the head of [`egui::FontFamily::Proportional`] so that ASCII characters +/// (digits, units, labels) and CJK glyphs use the same face, keeping them on one baseline. +fn promote_font_to_front(fonts: &mut egui::FontDefinitions, name: &str) { + if let Some(list) = fonts.families.get_mut(&egui::FontFamily::Proportional) + && let Some(pos) = list.iter().position(|e| e == name) + { + let item = list.remove(pos); + list.insert(0, item); + } +} + /// Install font bytes as fallback for Proportional and Monospace font families. +/// For CJK languages, promotes the font to the front of Proportional so digits and labels share one baseline. /// Returns true if the font was parsed and installed successfully. pub fn install_cjk_font(ctx: &egui::Context, bytes: Vec) -> bool { + install_cjk_font_for(ctx, bytes, "ja") +} + +/// Install font bytes for `language`. +pub fn install_cjk_font_for(ctx: &egui::Context, bytes: Vec, language: &str) -> bool { match with_cjk_fallback(egui::FontDefinitions::default(), bytes) { - Some(fonts) => { + Some(mut fonts) => { + if needs_cjk_font(language) { + promote_font_to_front(&mut fonts, CJK_FALLBACK); + } ctx.set_fonts(fonts); true } @@ -460,9 +480,16 @@ fn find_system_cjk_font() -> Option> { #[cfg(target_os = "macos")] { - let dirs = ["/System/Library/Fonts", "/System/Library/Fonts/Supplemental", "/Library/Fonts"]; - for d in dirs { - if let Some(bytes) = scan_dir_for_font(std::path::Path::new(d), 2, is_cjk_font_name) { + let mut dirs = vec![ + std::path::PathBuf::from("/System/Library/Fonts"), + std::path::PathBuf::from("/System/Library/Fonts/Supplemental"), + std::path::PathBuf::from("/Library/Fonts"), + ]; + if let Ok(home) = std::env::var("HOME") { + dirs.push(std::path::PathBuf::from(home).join("Library/Fonts")); + } + for d in &dirs { + if let Some(bytes) = scan_dir_for_font(d, 2, is_cjk_font_name) { return Some(bytes); } } @@ -496,10 +523,10 @@ fn find_system_cjk_font() -> Option> { /// inside one word. One face for the whole word keeps them on one baseline. /// Thai comes last whatever the language: no other face draws it. pub fn fallback_order(language: &str) -> [&'static str; 4] { - if language == "zh" { - [CHINESE_FALLBACK, CJK_FALLBACK, HANGUL_FALLBACK, THAI_FALLBACK] - } else { - [CJK_FALLBACK, CHINESE_FALLBACK, HANGUL_FALLBACK, THAI_FALLBACK] + match language { + "zh" => [CHINESE_FALLBACK, CJK_FALLBACK, HANGUL_FALLBACK, THAI_FALLBACK], + "ko" => [HANGUL_FALLBACK, CJK_FALLBACK, CHINESE_FALLBACK, THAI_FALLBACK], + _ => [CJK_FALLBACK, CHINESE_FALLBACK, HANGUL_FALLBACK, THAI_FALLBACK], } } @@ -519,7 +546,8 @@ pub fn setup_fonts_for(ctx: &egui::Context, language: &str, ui_font: &str) { if let Some(font) = self::ui_font(ui_font) { fonts = with_ui_font(fonts, font); } - for name in fallback_order(language) { + let order = fallback_order(language); + for name in order { let bytes = match name { CJK_FALLBACK => cjk.clone(), CHINESE_FALLBACK => chinese.clone(), @@ -534,6 +562,15 @@ pub fn setup_fonts_for(ctx: &egui::Context, language: &str, ui_font: &str) { } } if found { + if needs_cjk_font(language) && ui_font.trim().is_empty() { + // For a CJK UI (Japanese, Chinese, Korean) without a custom interface font, + // promote the primary CJK font to the front of FontFamily::Proportional. + // This ensures that ASCII characters (digits, units, English words) within mixed + // labels (e.g. "4 個選択中", "2 mm") are drawn with the same font face as the + // CJK glyphs, sharing identical line height, ascender, and baseline (#1070 follow-up). + let primary = order[0]; + promote_font_to_front(&mut fonts, primary); + } ctx.set_fonts(fonts); } } @@ -624,7 +661,8 @@ mod tests { #[test] fn a_chinese_ui_puts_the_chinese_face_before_the_japanese_one() { assert_eq!(fallback_order("zh"), [CHINESE_FALLBACK, CJK_FALLBACK, HANGUL_FALLBACK, THAI_FALLBACK]); - for lang in ["en", "ja", "ko", "de"] { + assert_eq!(fallback_order("ko"), [HANGUL_FALLBACK, CJK_FALLBACK, CHINESE_FALLBACK, THAI_FALLBACK]); + for lang in ["en", "ja", "de"] { assert_eq!( fallback_order(lang), [CJK_FALLBACK, CHINESE_FALLBACK, HANGUL_FALLBACK, THAI_FALLBACK], @@ -665,6 +703,16 @@ mod tests { assert!(thai(with_fallback(egui::FontDefinitions::default(), THAI_FALLBACK, bytes).unwrap()), "Thai draws with the fallback"); } + #[test] + fn cjk_ui_promotes_primary_cjk_font_to_front_for_consistent_baseline() { + let defaults = egui::FontDefinitions::default(); + let mut fonts = with_cjk_fallback(defaults.clone(), latin_font_bytes()).unwrap(); + promote_font_to_front(&mut fonts, CJK_FALLBACK); + let prop = &fonts.families[&egui::FontFamily::Proportional]; + assert_eq!(prop.first().map(String::as_str), Some(CJK_FALLBACK), "CJK font is promoted to first so digits and CJK share one baseline"); + assert!(prop.contains(&defaults.families[&egui::FontFamily::Proportional][0]), "Latin font remains in the fallback chain"); + } + #[test] fn hangul_font_falls_back_after_the_cjk_font() { let defaults = egui::FontDefinitions::default(); @@ -755,10 +803,11 @@ mod tests { let ctx = egui::Context::default(); let run = |text: &'static str| { let mut seen = false; - let _ = ctx.run_ui(egui::RawInput::default(), |ui| { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { ui.label(text); seen = painted_cjk(ui.ctx()); }); + out.textures_delta.clear(); seen }; assert!(!run("Untitled")); From ab22da13431581e81a9e35d06804a07cf076da55 Mon Sep 17 00:00:00 2001 From: tdslot Date: Mon, 19 Oct 2026 01:11:11 +0300 Subject: [PATCH 011/225] Browser sidebar: drag its width, and float it over the workspace (#2741) * Browser sidebar: drag its right edge to size it, and remember the width The left browser sidebar was fixed at 250 px. Its right edge is now a drag handle: the width follows the pointer, is clamped to 170-620 px, and is kept in the preferences (browser_width) so it survives a restart and Reset Defaults returns it to 250. The few pixels of grip sit inside the panel's own margin, so the tree rows and the scroll bar keep their input. * Browser: float the tree over the workspace on a translucent card Preferences -> General gains "Parts browser -> Float it over the workspace": the tree then draws on a card over the 3D view instead of taking a column, so the workspace keeps the whole window width. The card hugs the tree, scrolls past 70 % of the view's height, and uses the remembered browser_width. The canvas keeps every point the card does not cover, and turning the preference off docks the browser again. --- crates/ui-egui/src/browser.rs | 72 +++++++++++++++++++++++++++-- crates/ui-egui/src/lib.rs | 9 +++- crates/ui-egui/src/prefs.rs | 19 ++++++++ crates/ui-egui/src/timeline_left.rs | 32 +++++++++++++ 4 files changed, 128 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/browser.rs b/crates/ui-egui/src/browser.rs index 96d248348..013734fc2 100644 --- a/crates/ui-egui/src/browser.rs +++ b/crates/ui-egui/src/browser.rs @@ -498,14 +498,24 @@ pub fn browser_below_timeline(app: &mut SolveApp, ui: &mut egui::Ui) { browser_panel(app, ui, true); } +/// How narrow the browser sidebar may be dragged, and how wide (the viewport keeps the rest). +const MIN_BROWSER_WIDTH: f32 = 170.0; +const MAX_BROWSER_WIDTH: f32 = 620.0; +/// How wide a grip the sidebar's right edge offers, counted inwards from the edge. +const BROWSER_RAIL: f32 = 6.0; +/// How opaque the floating browser's card is; the workspace shows through the rest. +const BROWSER_FLOAT_ALPHA: f32 = 0.4; + fn browser_panel(app: &mut SolveApp, ui: &mut egui::Ui, timeline_above: bool) { let t = Tokens::get(); app.tree.order.clear(); DRAWN.with(|d| d.borrow_mut().clear()); OCCURRENCES.with(|d| d.borrow_mut().clear()); let mut acts = Actions::default(); - egui::Panel::left("sc_browser") - .exact_size(250.0) + let remembered = app.preferences.browser_width; + let width = if remembered.is_finite() { remembered.clamp(MIN_BROWSER_WIDTH, MAX_BROWSER_WIDTH) } else { crate::prefs::DEFAULT_BROWSER_WIDTH }; + let panel = egui::Panel::left("sc_browser") + .exact_size(width) .resizable(false) .frame(egui::Frame::NONE.fill(t.panel).inner_margin(egui::Margin::symmetric(6, 6))) .show(ui, |ui| { @@ -548,6 +558,52 @@ fn browser_panel(app: &mut SolveApp, ui: &mut egui::Ui, timeline_above: bool) { browser_contents(app, ui, &mut acts); } }); + // The sidebar's right edge is a drag handle; the width it is dragged to is remembered. + let rect = panel.response.rect; + let rail = egui::Rect::from_x_y_ranges(rect.right() - BROWSER_RAIL..=rect.right(), rect.y_range()); + let response = ui.interact(rail, egui::Id::new("sc_browser_rail"), egui::Sense::drag()).on_hover_cursor(egui::CursorIcon::ResizeHorizontal); + if response.dragged() { + let delta = ui.input(|input| input.pointer.delta().x); + if delta.is_finite() { + app.preferences.browser_width = (width + delta).clamp(MIN_BROWSER_WIDTH, MAX_BROWSER_WIDTH); + } + } + crate::scenario::publish_handle("left-browser-rail", egui::pos2(rect.right() - BROWSER_RAIL / 2.0, rect.center().y)); + finish_browser(app, ui, acts); +} + +/// The tree on a translucent card over the workspace, instead of a column that takes width from +/// it (Preferences: "Float it over the workspace"). Drawn before the central view, in a layer +/// above it, so the viewport keeps the whole window and the card sits on top of it. +pub fn floating(app: &mut SolveApp, ui: &mut egui::Ui, viewport: egui::Rect) { + let t = Tokens::get(); + app.tree.order.clear(); + DRAWN.with(|d| d.borrow_mut().clear()); + OCCURRENCES.with(|d| d.borrow_mut().clear()); + let mut acts = Actions::default(); + let remembered = app.preferences.browser_width; + let width = if remembered.is_finite() { remembered.clamp(MIN_BROWSER_WIDTH, MAX_BROWSER_WIDTH) } else { crate::prefs::DEFAULT_BROWSER_WIDTH }; + // Tall enough for the tree, short enough to leave the view room; the rows scroll inside. + let height = (viewport.height() * 0.7).clamp(160.0, 560.0); + let card = crate::frame::area(egui::Id::new("sc_browser_float")).fixed_pos(viewport.min + vec2(8.0, 8.0)).order(egui::Order::Middle).show( + ui.ctx(), + |ui| { + egui::Frame::new() + .fill(t.panel.gamma_multiply(BROWSER_FLOAT_ALPHA)) + .stroke(egui::Stroke::new(1.0, t.border)) + .corner_radius(6) + .inner_margin(egui::Margin::symmetric(8, 6)) + .show(ui, |ui| { + ui.set_width(width - 16.0); + ui.set_max_height(height); + ui.label(RichText::new(crate::i18n::tr_label("BROWSER")).size(11.0).strong().color(t.text_dim)); + ui.add_space(4.0); + // The card hugs the tree, so it hides as little of the view as it can. + browser_rows_hugging(app, ui, &mut acts); + }); + }, + ); + crate::scenario::publish_rect("browser:float", card.response.rect); finish_browser(app, ui, acts); } @@ -611,9 +667,19 @@ fn model_feature_indices(app: &SolveApp, component: u64, sketches: bool) -> Vec< } fn browser_rows(app: &mut SolveApp, ui: &mut egui::Ui, acts: &mut Actions) { + rows_scrolling(app, ui, acts, false); +} + +/// As [browser_rows], but the area hugs the rows it drew (the floating card), up to the height +/// the caller allowed. +fn browser_rows_hugging(app: &mut SolveApp, ui: &mut egui::Ui, acts: &mut Actions) { + rows_scrolling(app, ui, acts, true); +} + +fn rows_scrolling(app: &mut SolveApp, ui: &mut egui::Ui, acts: &mut Actions, shrink_height: bool) { prepare_model(app); egui::ScrollArea::vertical() - .auto_shrink([false, false]) + .auto_shrink([false, shrink_height]) .scroll_source(egui::scroll_area::ScrollSource { scroll_bar: true, mouse_wheel: true, ..egui::scroll_area::ScrollSource::NONE }) .show(ui, |ui| { ui.spacing_mut().item_spacing.y = 0.0; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index a0e31d1bf..7a7da3d6f 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1387,7 +1387,9 @@ impl SolveApp { timeline::timeline(self, ui); } palette::palette_bar(self, ui); - if self.ui.show_browser { + // A floating browser keeps the workspace the whole width: it is drawn over the view below. + let browser_float = self.ui.show_browser && self.preferences.browser_float; + if self.ui.show_browser && !browser_float { if left_timeline { browser::browser_below_timeline(self, ui); } else { @@ -1401,6 +1403,11 @@ impl SolveApp { } agent_chat::show(self, ui); preview::update(self, ui.ctx()); + if browser_float { + // The room the central view is about to take, before it takes it. + let viewport = ui.available_rect_before_wrap(); + browser::floating(self, ui, viewport); + } egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| { if render_workspace::active(self) { render_workspace::show(self, ui); diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index 9c62d3e2d..48b12d3bb 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -251,6 +251,10 @@ pub enum OrbitAround { Cursor, } +/// The browser sidebar's first width, and the width [`Prefs::default`] restores; the panel +/// itself clamps what the user drags to its own range. +pub const DEFAULT_BROWSER_WIDTH: f32 = 250.0; + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default)] pub struct Prefs { @@ -318,6 +322,12 @@ pub struct Prefs { pub timeline_left_height: f32, /// Whether the browser below the left feature history is collapsed. pub timeline_left_browser_collapsed: bool, + /// Width of the left sidebar holding the browser (and the feature history above it), which + /// the user drags wider or narrower at its right edge. + pub browser_width: f32, + /// Draw the parts browser on a translucent card over the 3D view instead of a column of its + /// own, so the workspace keeps the whole window width. + pub browser_float: bool, /// The wheel zooms toward the point under the cursor (else toward the view's centre). pub zoom_to_cursor: bool, /// Spread discrete wheel input across frames (off: apply each event immediately). @@ -440,6 +450,8 @@ impl Default for Prefs { timeline_left: false, timeline_left_height: 360.0, timeline_left_browser_collapsed: false, + browser_width: DEFAULT_BROWSER_WIDTH, + browser_float: false, zoom_to_cursor: true, smooth_wheel_zoom: true, trackpad_pan: true, @@ -695,6 +707,8 @@ fn defaults(app: &mut SolveApp, page: usize) { p.timeline_left = d.timeline_left; p.timeline_left_height = d.timeline_left_height; p.timeline_left_browser_collapsed = d.timeline_left_browser_collapsed; + p.browser_width = d.browser_width; + p.browser_float = d.browser_float; p.default_units = d.default_units; p.length_decimals = d.length_decimals; p.angle_decimals = d.angle_decimals; @@ -1219,6 +1233,11 @@ fn page(app: &mut SolveApp, ui: &mut egui::Ui, t: &Tokens) { }); ui.end_row(); note(ui, app.tr("ui.timeline_left_note")); + ui.label(app.tr_label("Parts browser")); + let float_label = app.tr_label("Float it over the workspace").to_string(); + ui.checkbox(&mut app.preferences.browser_float, float_label); + ui.end_row(); + note(ui, app.tr_label("The tree draws on a translucent card over the 3D view instead of a column of its own.")); ui.label(app.tr("ui.units_of_new_designs")); egui::ComboBox::from_id_salt("pref_units").selected_text(app.preferences.default_units.clone()).show_ui(ui, |ui| { for u in UNITS { diff --git a/crates/ui-egui/src/timeline_left.rs b/crates/ui-egui/src/timeline_left.rs index d9792ad23..192cca55b 100644 --- a/crates/ui-egui/src/timeline_left.rs +++ b/crates/ui-egui/src/timeline_left.rs @@ -957,6 +957,38 @@ mod tests { assert!(handle_at("row:Untitled").is_some(), "expanding the browser should restore its rows"); } + #[test] + fn browser_sidebar_drags_wider_and_narrower() { + let mut harness = Harness::new(); + harness.frames(4); + let before = harness.app.preferences.browser_width; + let rail = handle_at("left-browser-rail").expect("the browser sidebar's right edge is drawn"); + harness.step(&json!({"drag": [[rail.x, rail.y], [rail.x + 90.0, rail.y]]})).unwrap(); + let wider = harness.app.preferences.browser_width; + assert!(wider > before + 40.0, "dragging the right edge right should widen the browser: {before} -> {wider}"); + + let rail = handle_at("left-browser-rail").expect("the browser sidebar's right edge is drawn"); + harness.step(&json!({"drag": [[rail.x, rail.y], [rail.x - 40.0, rail.y]]})).unwrap(); + let narrower = harness.app.preferences.browser_width; + assert!(narrower < wider - 20.0, "dragging it left should narrow it again: {wider} -> {narrower}"); + } + + #[test] + fn floating_browser_sits_over_the_workspace_and_docks_again() { + let mut harness = Harness::new(); + harness.app.preferences.browser_float = true; + harness.frames(4); + let card = crate::scenario::rect_of("browser:float").expect("the floating browser is drawn"); + assert!(card.min.x < 40.0, "the card sits at the view's left edge: {card:?}"); + assert!(handle_at("left-browser-rail").is_none(), "a floating browser must not take a column of the window"); + assert!(handle_at("row:Untitled").is_some(), "the tree is still drawn and usable"); + + harness.app.preferences.browser_float = false; + harness.frames(4); + assert!(crate::scenario::rect_of("browser:float").is_none(), "docking again removes the card"); + assert!(handle_at("left-browser-rail").is_some(), "the docked sidebar is back"); + } + #[test] fn rollback_bar_above_last_feature_can_be_dragged_to_the_end() { let mut harness = Harness::new(); From dd23be12d55483cae7f885ce4c14f070edb9bd6d Mon Sep 17 00:00:00 2001 From: rlartot <94693724+rlartot@users.noreply.github.com> Date: Mon, 19 Oct 2026 00:11:18 +0200 Subject: [PATCH 012/225] UI: the Interference dialog and the continuity legend's Gap are translatable (#2443) * UI: the Interference dialog and the continuity legend's Gap are translatable The Interference dialog's title, its Bodies input, the Compute and Compute again button, the checked-bodies count, "could not be checked" and the clearance error were English in every language. They now come from the catalogs (en, ja, zh, de, ko, fr). The continuity legend's Gap (an opening between faces) and the sheet-metal hem's gap shared the message "Gap", translated as the hem's gap (French "Jeu"). The hem keeps those translations under ui.sheet_gap; the legend gets ui.continuity_gap, and both read their message by id. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L15TLCjpXsQdp8ovC4ZacH * Polish: the sheet-metal gap is ui.sheet_gap too Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L15TLCjpXsQdp8ovC4ZacH * Every catalog gives the continuity legend's Gap the word it showed before The catalogs without their own ui.continuity_gap would have fallen back to English in the legend; they now keep the translation the shared Gap gave them. French and German keep separate words. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L15TLCjpXsQdp8ovC4ZacH --------- Co-authored-by: Claude Opus 5.5 --- assets/locales/cs.json | 3 ++- assets/locales/de.json | 10 ++++++++- assets/locales/en.json | 10 ++++++++- assets/locales/es.json | 3 ++- assets/locales/fr.json | 10 ++++++++- assets/locales/gl.json | 3 ++- assets/locales/it.json | 3 ++- assets/locales/ja.json | 10 ++++++++- assets/locales/ko.json | 10 ++++++++- assets/locales/pl.json | 3 ++- assets/locales/pt-BR.json | 3 ++- assets/locales/ru.json | 3 ++- assets/locales/tr.json | 3 ++- assets/locales/uk.json | 3 ++- assets/locales/zh.json | 10 ++++++++- crates/ui-egui/src/dialogs_assembly.rs | 8 +++---- crates/ui-egui/src/dialogs_sheet.rs | 2 +- crates/ui-egui/src/i18n_ui_tests.rs | 31 ++++++++++++++++++++++++++ crates/ui-egui/src/sketch_tools.rs | 5 +++-- 19 files changed, 111 insertions(+), 22 deletions(-) diff --git a/assets/locales/cs.json b/assets/locales/cs.json index 63d89a773..a27ed4e6e 100644 --- a/assets/locales/cs.json +++ b/assets/locales/cs.json @@ -113,7 +113,6 @@ "Follow the camera (Look At sketches)": "Sledovat kameru (náčrty natočené k pohledu)", "Font": "Písmo", "Full Length": "Celá délka", - "Gap": "Mezera", "Grid": "Mřížka", "Height": "Výška", "Hidden edges": "Skryté hrany", @@ -1031,6 +1030,7 @@ "ui.construct": "Konstrukce", "ui.construction": "Konstrukční", "ui.context_menu": "Místní nabídka", + "ui.continuity_gap": "Mezera", "ui.copy": "Kopírovat", "ui.corner": "Roh", "ui.corners": "Rohy", @@ -1347,6 +1347,7 @@ "ui.send": "Odeslat", "ui.send_to_slicer": "Odeslat do sliceru", "ui.sent_to_slicer": "Odesláno do {slicer}", + "ui.sheet_gap": "Mezera", "ui.shell": "Skořepina", "ui.show": "Zobrazit", "ui.showAll": "Zobrazit vše", diff --git a/assets/locales/de.json b/assets/locales/de.json index 9a9288884..77a6bbcb1 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -43,7 +43,6 @@ "Faces": "Flächen", "Find in Browser": "Im Browser suchen", "Flat": "Flach", - "Gap": "Spalt", "Hidden edges": "Verdeckte Kanten", "Holes": "Löcher", "Holes (edges on them)": "Löcher (ihre Kanten)", @@ -448,7 +447,12 @@ "coupling.rack": "Zahnstange", "coupling.radius_1": "Radius 1", "coupling.radius_2": "Radius 2", + "dialog.bodies_count": "{count} Körper", + "dialog.clearance_invalid": "der Abstand muss eine Länge von 0 oder mehr sein", + "dialog.compute": "Berechnen", + "dialog.compute_again": "Erneut berechnen", "dialog.computing": "Wird berechnet… {seconds} s", + "dialog.could_not_be_checked": "nicht prüfbar", "dialog.custom_axis": "↖ Eigene Achse", "dialog.edit_title": "{title} bearbeiten", "dialog.select": "↖ Auswählen", @@ -769,6 +773,7 @@ "ui.base_point": "Basispunkt", "ui.blocked": "Verdeckt", "ui.bodies": "Körper", + "ui.bodies_all_if_none": "Körper (alle, wenn keine)", "ui.box": "Block", "ui.break": "Unterbrechen", "ui.calibrate": "Kalibrieren", @@ -819,6 +824,7 @@ "ui.continuity_g0": "G0 Knick", "ui.continuity_g1": "G1 Tangente", "ui.continuity_g2": "G2 Krümmung", + "ui.continuity_gap": "Lücke", "ui.copy": "Kopieren", "ui.corner": "Ecke", "ui.corners": "Ecken", @@ -928,6 +934,7 @@ "ui.heading_home": "START", "ui.heading_insert": "EINFÜGEN", "ui.heading_inspect": "PRÜFEN", + "ui.heading_interference": "EINGRIFF", "ui.heading_loft": "LOFT", "ui.heading_measure": "Messen", "ui.heading_mesh": "MESH", @@ -1121,6 +1128,7 @@ "ui.send": "Senden", "ui.send_to_slicer": "An Slicer senden", "ui.sent_to_slicer": "An {slicer} gesendet", + "ui.sheet_gap": "Spalt", "ui.shell": "Hülle", "ui.show": "Einblenden", "ui.showAll": "Alle einblenden", diff --git a/assets/locales/en.json b/assets/locales/en.json index f22bb4087..4394f3d63 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -122,7 +122,6 @@ "Follow the camera (Look At sketches)": "Follow the camera (Look At sketches)", "Font": "Font", "Full Length": "Full Length", - "Gap": "Gap", "Grid": "Grid", "Height": "Height", "Hidden edges": "Hidden edges", @@ -656,7 +655,12 @@ "coupling.rack": "Rack", "coupling.radius_1": "Radius 1", "coupling.radius_2": "Radius 2", + "dialog.bodies_count": "{count} bodies", + "dialog.clearance_invalid": "the clearance must be a length of 0 or more", + "dialog.compute": "Compute", + "dialog.compute_again": "Compute again", "dialog.computing": "Computing… {seconds} s", + "dialog.could_not_be_checked": "could not be checked", "dialog.custom_axis": "↖ Custom Axis", "dialog.edit_title": "EDIT {title}", "dialog.select": "↖ Select", @@ -1049,6 +1053,7 @@ "ui.base_point": "Base point", "ui.blocked": "Blocked", "ui.bodies": "Bodies", + "ui.bodies_all_if_none": "Bodies (all if none)", "ui.box": "Box", "ui.break": "Break", "ui.calibrate": "Calibrate", @@ -1103,6 +1108,7 @@ "ui.continuity_g0": "G0 crease", "ui.continuity_g1": "G1 tangent", "ui.continuity_g2": "G2 curvature", + "ui.continuity_gap": "Gap", "ui.copy": "Copy", "ui.corner": "Corner", "ui.corners": "Corners", @@ -1218,6 +1224,7 @@ "ui.heading_home": "HOME", "ui.heading_insert": "INSERT", "ui.heading_inspect": "INSPECT", + "ui.heading_interference": "INTERFERENCE", "ui.heading_loft": "LOFT", "ui.heading_make": "MAKE", "ui.heading_measure": "MEASURE", @@ -1427,6 +1434,7 @@ "ui.send": "Send", "ui.send_to_slicer": "Send to slicer", "ui.sent_to_slicer": "Sent to {slicer}", + "ui.sheet_gap": "Gap", "ui.shell": "Shell", "ui.show": "Show", "ui.showAll": "Show All", diff --git a/assets/locales/es.json b/assets/locales/es.json index 3568c6d89..0b18f3c7a 100644 --- a/assets/locales/es.json +++ b/assets/locales/es.json @@ -120,7 +120,6 @@ "Follow the camera (Look At sketches)": "Seguir la cámara (orientar hacia los bocetos)", "Font": "Fuente", "Full Length": "Longitud total", - "Gap": "Separación", "Grid": "Cuadrícula", "Height": "Altura", "Hidden edges": "Aristas ocultas", @@ -1062,6 +1061,7 @@ "ui.continuity_g0": "G0 arista", "ui.continuity_g1": "G1 tangencia", "ui.continuity_g2": "G2 curvatura", + "ui.continuity_gap": "Separación", "ui.copy": "Copiar", "ui.corner": "Esquina", "ui.corners": "Esquinas", @@ -1383,6 +1383,7 @@ "ui.send": "Enviar", "ui.send_to_slicer": "Enviar al laminador", "ui.sent_to_slicer": "Enviado a {slicer}", + "ui.sheet_gap": "Separación", "ui.shell": "Vaciado", "ui.show": "Mostrar", "ui.showAll": "Mostrar todo", diff --git a/assets/locales/fr.json b/assets/locales/fr.json index 698eb5328..2bbbed45e 100644 --- a/assets/locales/fr.json +++ b/assets/locales/fr.json @@ -120,7 +120,6 @@ "Follow the camera (Look At sketches)": "Suivre la caméra (vue normale aux esquisses)", "Font": "Police", "Full Length": "Longueur totale", - "Gap": "Jeu", "Grid": "Grille", "Height": "Hauteur", "Hidden edges": "Arêtes cachées", @@ -652,7 +651,12 @@ "coupling.rack": "Crémaillère", "coupling.radius_1": "Rayon 1", "coupling.radius_2": "Rayon 2", + "dialog.bodies_count": "{count} corps", + "dialog.clearance_invalid": "le jeu doit être une longueur positive ou nulle", + "dialog.compute": "Calculer", + "dialog.compute_again": "Recalculer", "dialog.computing": "Calcul… {seconds} s", + "dialog.could_not_be_checked": "non vérifiable", "dialog.custom_axis": "↖ Axe personnalisé", "dialog.edit_title": "MODIFIER {title}", "dialog.select": "↖ Sélectionner", @@ -1008,6 +1012,7 @@ "ui.base_point": "Point de base", "ui.blocked": "Inaccessible", "ui.bodies": "Corps", + "ui.bodies_all_if_none": "Corps (tous si aucun)", "ui.box": "Boîte", "ui.break": "Fractionner", "ui.calibrate": "Étalonner", @@ -1062,6 +1067,7 @@ "ui.continuity_g0": "G0 angle vif", "ui.continuity_g1": "G1 tangence", "ui.continuity_g2": "G2 courbure", + "ui.continuity_gap": "Écart", "ui.copy": "Copier", "ui.corner": "Angle", "ui.corners": "Angles", @@ -1177,6 +1183,7 @@ "ui.heading_home": "ACCUEIL", "ui.heading_insert": "INSÉRER", "ui.heading_inspect": "INSPECTER", + "ui.heading_interference": "INTERFÉRENCE", "ui.heading_loft": "LISSAGE", "ui.heading_make": "FABRIQUER", "ui.heading_measure": "MESURER", @@ -1383,6 +1390,7 @@ "ui.send": "Envoyer", "ui.send_to_slicer": "Envoyer au slicer", "ui.sent_to_slicer": "Envoyé à {slicer}", + "ui.sheet_gap": "Jeu", "ui.shell": "Coque", "ui.show": "Afficher", "ui.showAll": "Tout afficher", diff --git a/assets/locales/gl.json b/assets/locales/gl.json index a557744a1..b34e88612 100644 --- a/assets/locales/gl.json +++ b/assets/locales/gl.json @@ -113,7 +113,6 @@ "Follow the camera (Look At sketches)": "Seguir a cámara (Mirar cara aos bosquexos)", "Font": "Tipo de letra", "Full Length": "Lonxitude completa", - "Gap": "Separación", "Grid": "Grella", "Height": "Altura", "Hidden edges": "Arestas ocultas", @@ -1031,6 +1030,7 @@ "ui.construct": "Construír", "ui.construction": "Construción", "ui.context_menu": "Menú contextual", + "ui.continuity_gap": "Separación", "ui.copy": "Copiar", "ui.corner": "Esquina", "ui.corners": "Esquinas", @@ -1347,6 +1347,7 @@ "ui.send": "Enviar", "ui.send_to_slicer": "Enviar ao laminador", "ui.sent_to_slicer": "Enviado a {slicer}", + "ui.sheet_gap": "Separación", "ui.shell": "Baleirado", "ui.show": "Mostrar", "ui.showAll": "Mostrar todo", diff --git a/assets/locales/it.json b/assets/locales/it.json index ef7ac3885..243c6290f 100644 --- a/assets/locales/it.json +++ b/assets/locales/it.json @@ -119,7 +119,6 @@ "Follow the camera (Look At sketches)": "Segui la camera (Vista normale agli schizzi)", "Font": "Carattere", "Full Length": "Lunghezza totale", - "Gap": "Gioco", "Grid": "Griglia", "Height": "Altezza", "Hidden edges": "Spigoli nascosti", @@ -1055,6 +1054,7 @@ "ui.construct": "Costruisci", "ui.construction": "Costruzione", "ui.context_menu": "Menu contestuale", + "ui.continuity_gap": "Gioco", "ui.copy": "Copia", "ui.corner": "Angolo", "ui.corners": "Angoli", @@ -1374,6 +1374,7 @@ "ui.send": "Invia", "ui.send_to_slicer": "Invia allo slicer", "ui.sent_to_slicer": "Inviato a {slicer}", + "ui.sheet_gap": "Gioco", "ui.shell": "Svuota", "ui.show": "Mostra", "ui.showAll": "Mostra tutto", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 5da8fa982..0cfb388f9 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -122,7 +122,6 @@ "Follow the camera (Look At sketches)": "カメラ追従(スケッチを正面視)", "Font": "フォント", "Full Length": "全長", - "Gap": "ギャップ", "Grid": "グリッド", "Height": "高さ", "Hidden edges": "隠線", @@ -656,7 +655,12 @@ "coupling.rack": "ラック", "coupling.radius_1": "半径 1", "coupling.radius_2": "半径 2", + "dialog.bodies_count": "{count} ボディ", + "dialog.clearance_invalid": "クリアランスは 0 以上の長さにしてください", + "dialog.compute": "計算", + "dialog.compute_again": "再計算", "dialog.computing": "計算中… {seconds} 秒", + "dialog.could_not_be_checked": "チェックできません", "dialog.custom_axis": "↖ カスタム軸", "dialog.edit_title": "{title}を編集", "dialog.select": "↖ 選択", @@ -1049,6 +1053,7 @@ "ui.base_point": "基点", "ui.blocked": "到達不可", "ui.bodies": "ボディ", + "ui.bodies_all_if_none": "ボディ(未選択ならすべて)", "ui.box": "直方体", "ui.break": "分割", "ui.calibrate": "校正", @@ -1103,6 +1108,7 @@ "ui.continuity_g0": "G0 折れ", "ui.continuity_g1": "G1 接線", "ui.continuity_g2": "G2 曲率", + "ui.continuity_gap": "隙間", "ui.copy": "コピー", "ui.corner": "コーナー", "ui.corners": "コーナー", @@ -1218,6 +1224,7 @@ "ui.heading_home": "ホーム", "ui.heading_insert": "挿入", "ui.heading_inspect": "検査", + "ui.heading_interference": "干渉", "ui.heading_loft": "ロフト", "ui.heading_make": "製造", "ui.heading_measure": "計測", @@ -1427,6 +1434,7 @@ "ui.send": "送信", "ui.send_to_slicer": "スライサーに送る", "ui.sent_to_slicer": "{slicer} に送信しました", + "ui.sheet_gap": "ギャップ", "ui.shell": "シェル", "ui.show": "表示", "ui.showAll": "すべて表示", diff --git a/assets/locales/ko.json b/assets/locales/ko.json index 47589baec..63df7e568 100644 --- a/assets/locales/ko.json +++ b/assets/locales/ko.json @@ -43,7 +43,6 @@ "Faces": "면", "Find in Browser": "브라우저에서 찾기", "Flat": "플랫", - "Gap": "틈", "Hidden edges": "숨겨진 모서리", "Holes": "구멍", "Holes (edges on them)": "구멍 (구멍의 모서리)", @@ -448,7 +447,12 @@ "coupling.rack": "랙", "coupling.radius_1": "반지름 1", "coupling.radius_2": "반지름 2", + "dialog.bodies_count": "바디 {count}개", + "dialog.clearance_invalid": "간격은 0 이상의 길이여야 합니다", + "dialog.compute": "계산", + "dialog.compute_again": "다시 계산", "dialog.computing": "계산 중… {seconds}초", + "dialog.could_not_be_checked": "확인할 수 없음", "dialog.custom_axis": "↖ 사용자 정의 축", "dialog.edit_title": "{title} 편집", "dialog.select": "↖ 선택", @@ -769,6 +773,7 @@ "ui.base_point": "기준점", "ui.blocked": "막힘", "ui.bodies": "바디", + "ui.bodies_all_if_none": "바디 (없으면 전체)", "ui.box": "박스", "ui.break": "끊기", "ui.calibrate": "캘리브레이션", @@ -819,6 +824,7 @@ "ui.continuity_g0": "G0 꺾임", "ui.continuity_g1": "G1 접선", "ui.continuity_g2": "G2 곡률", + "ui.continuity_gap": "틈", "ui.copy": "복사", "ui.corner": "코너", "ui.corners": "코너", @@ -928,6 +934,7 @@ "ui.heading_home": "홈", "ui.heading_insert": "삽입", "ui.heading_inspect": "검사", + "ui.heading_interference": "간섭", "ui.heading_loft": "로프트", "ui.heading_measure": "측정", "ui.heading_mesh": "메시", @@ -1118,6 +1125,7 @@ "ui.send": "보내기", "ui.send_to_slicer": "슬라이서로 보내기", "ui.sent_to_slicer": "{slicer}(으)로 보냈습니다", + "ui.sheet_gap": "틈", "ui.shell": "쉘", "ui.show": "표시", "ui.showAll": "모두 표시", diff --git a/assets/locales/pl.json b/assets/locales/pl.json index 9f4c101f4..501e0f7a9 100644 --- a/assets/locales/pl.json +++ b/assets/locales/pl.json @@ -122,7 +122,6 @@ "Follow the camera (Look At sketches)": "Podążaj za kamerą (Patrz na szkice)", "Font": "Czcionka", "Full Length": "Pełna długość", - "Gap": "Szczelina", "Grid": "Siatka", "Height": "Wysokość", "Hidden edges": "Krawędzie niewidoczne", @@ -1071,6 +1070,7 @@ "ui.continuity_g0": "G0 załamanie", "ui.continuity_g1": "G1 styczność", "ui.continuity_g2": "G2 krzywizna", + "ui.continuity_gap": "Szczelina", "ui.copy": "Kopiuj", "ui.corner": "Naroże", "ui.corners": "Naroża", @@ -1395,6 +1395,7 @@ "ui.send": "Wyślij", "ui.send_to_slicer": "Wyślij do slicera", "ui.sent_to_slicer": "Wysłano do {slicer}", + "ui.sheet_gap": "Szczelina", "ui.shell": "Skorupa", "ui.show": "Pokaż", "ui.showAll": "Pokaż wszystko", diff --git a/assets/locales/pt-BR.json b/assets/locales/pt-BR.json index f51f6a251..3653a46a5 100644 --- a/assets/locales/pt-BR.json +++ b/assets/locales/pt-BR.json @@ -113,7 +113,6 @@ "Follow the camera (Look At sketches)": "Seguir a câmera (Olhar para os esboços)", "Font": "Fonte", "Full Length": "Comprimento total", - "Gap": "Folga", "Grid": "Grade", "Height": "Altura", "Hidden edges": "Arestas ocultas", @@ -1011,6 +1010,7 @@ "ui.construct": "Construir", "ui.construction": "Construção", "ui.context_menu": "Menu de contexto", + "ui.continuity_gap": "Folga", "ui.copy": "Copiar", "ui.corner": "Canto", "ui.corners": "Cantos", @@ -1327,6 +1327,7 @@ "ui.send": "Enviar", "ui.send_to_slicer": "Enviar ao fatiador", "ui.sent_to_slicer": "Enviado para {slicer}", + "ui.sheet_gap": "Folga", "ui.shell": "Casca", "ui.show": "Mostrar", "ui.showAll": "Mostrar tudo", diff --git a/assets/locales/ru.json b/assets/locales/ru.json index 86d06c3ab..9550ec467 100644 --- a/assets/locales/ru.json +++ b/assets/locales/ru.json @@ -102,7 +102,6 @@ "Follow the camera (Look At sketches)": "Следовать за камерой (эскизы «Взгляд на»)", "Font": "Шрифт", "Full Length": "Полная длина", - "Gap": "Зазор", "Grid": "Сетка", "Height": "Высота", "Home view": "Главный вид", @@ -818,6 +817,7 @@ "ui.construct": "Построение", "ui.construction": "Вспомогательная", "ui.context_menu": "Контекстное меню", + "ui.continuity_gap": "Зазор", "ui.copy": "Копировать", "ui.corner": "Угол", "ui.corners": "Углы", @@ -1126,6 +1126,7 @@ "ui.send": "Отправить", "ui.send_to_slicer": "Отправить в слайсер", "ui.sent_to_slicer": "Отправлено в {slicer}", + "ui.sheet_gap": "Зазор", "ui.shell": "Оболочка", "ui.show": "Показать", "ui.showAll": "Показать всё", diff --git a/assets/locales/tr.json b/assets/locales/tr.json index 87c48b3fc..3769e61ac 100644 --- a/assets/locales/tr.json +++ b/assets/locales/tr.json @@ -107,7 +107,6 @@ "Follow the camera (Look At sketches)": "Kamera takibi (eskizlerde Bak)", "Font": "Yazı tipi", "Full Length": "Tam uzunluk", - "Gap": "Boşluk", "Grid": "Izgara", "Height": "Yükseklik", "Holes": "Delikler", @@ -960,6 +959,7 @@ "ui.construct": "Yapı", "ui.construction": "Yapı çizgisi", "ui.context_menu": "Bağlam menüsü", + "ui.continuity_gap": "Boşluk", "ui.copy": "Kopyala", "ui.corner": "Köşe", "ui.corners": "Köşeler", @@ -1274,6 +1274,7 @@ "ui.send": "Gönder", "ui.send_to_slicer": "Dilimleyiciye gönder", "ui.sent_to_slicer": "{slicer} uygulamasına gönderildi", + "ui.sheet_gap": "Boşluk", "ui.shell": "Kabuk", "ui.show": "Göster", "ui.showAll": "Tümünü göster", diff --git a/assets/locales/uk.json b/assets/locales/uk.json index 41461393a..724954ef4 100644 --- a/assets/locales/uk.json +++ b/assets/locales/uk.json @@ -118,7 +118,6 @@ "Follow the camera (Look At sketches)": "Стежити за камерою (ескізи наведення)", "Font": "Шрифт", "Full Length": "Повна довжина", - "Gap": "Проміжок", "Grid": "Сітка", "Height": "Висота", "Hidden edges": "Приховані ребра", @@ -1034,6 +1033,7 @@ "ui.construct": "Побудувати", "ui.construction": "Конструкційна", "ui.context_menu": "Контекстне меню", + "ui.continuity_gap": "Проміжок", "ui.copy": "Копіювати", "ui.corner": "Кут", "ui.corners": "Кути", @@ -1350,6 +1350,7 @@ "ui.send": "Надіслати", "ui.send_to_slicer": "Надіслати в слайсер", "ui.sent_to_slicer": "Надіслано в {slicer}", + "ui.sheet_gap": "Проміжок", "ui.shell": "Оболонка", "ui.show": "Показати", "ui.showAll": "Показати все", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index a1fe448ad..d342f7a19 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -122,7 +122,6 @@ "Follow the camera (Look At sketches)": "跟随相机(注视草图)", "Font": "字体", "Full Length": "全长", - "Gap": "间隙", "Grid": "网格", "Height": "高度", "Hidden edges": "隐藏线", @@ -656,7 +655,12 @@ "coupling.rack": "齿条", "coupling.radius_1": "半径 1", "coupling.radius_2": "半径 2", + "dialog.bodies_count": "{count} 个实体", + "dialog.clearance_invalid": "间隙必须是 0 或更大的长度", + "dialog.compute": "计算", + "dialog.compute_again": "重新计算", "dialog.computing": "正在计算… {seconds} 秒", + "dialog.could_not_be_checked": "无法检查", "dialog.custom_axis": "↖ 自定义轴", "dialog.edit_title": "编辑 {title}", "dialog.select": "↖ 选择", @@ -1049,6 +1053,7 @@ "ui.base_point": "基点", "ui.blocked": "被遮挡", "ui.bodies": "实体", + "ui.bodies_all_if_none": "实体(未选择则全部)", "ui.box": "长方体", "ui.break": "打断", "ui.calibrate": "校准", @@ -1103,6 +1108,7 @@ "ui.continuity_g0": "G0 折痕", "ui.continuity_g1": "G1 相切", "ui.continuity_g2": "G2 曲率", + "ui.continuity_gap": "缝隙", "ui.copy": "复制", "ui.corner": "角", "ui.corners": "角点", @@ -1218,6 +1224,7 @@ "ui.heading_home": "主页", "ui.heading_insert": "插入", "ui.heading_inspect": "检查", + "ui.heading_interference": "干涉", "ui.heading_loft": "放样", "ui.heading_make": "制作", "ui.heading_measure": "测量", @@ -1427,6 +1434,7 @@ "ui.send": "发送", "ui.send_to_slicer": "发送到切片软件", "ui.sent_to_slicer": "已发送到 {slicer}", + "ui.sheet_gap": "间隙", "ui.shell": "抽壳", "ui.show": "显示", "ui.showAll": "显示全部", diff --git a/crates/ui-egui/src/dialogs_assembly.rs b/crates/ui-egui/src/dialogs_assembly.rs index 493918224..a0124fb45 100644 --- a/crates/ui-egui/src/dialogs_assembly.rs +++ b/crates/ui-egui/src/dialogs_assembly.rs @@ -701,7 +701,7 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Asm, inputs: &mut [Se ui.end_row(); row_label(ui, ""); let stale = result.is_some() && *of != picked; - if ui.button(if stale { "Compute again" } else { "Compute" }).clicked() { + if ui.button(crate::i18n::tr(if stale { "dialog.compute_again" } else { "dialog.compute" })).clicked() { let (r, o) = interference(app, &picked, clearance); *result = Some(r); *overlaps = o; @@ -729,7 +729,7 @@ fn interference(app: &mut SolveApp, picked: &[Sel], clearance: &str) -> (Value, let (scale, _) = crate::prefs::unit_scale(&app.session.doc.units); let clearance = match crate::prefs::parse_length_mm(clearance, scale) { Some(v) if v >= 0.0 => v, - _ => return (json!({ "error": "the clearance must be a length of 0 or more" }), Vec::new()), + _ => return (json!({ "error": crate::i18n::tr("dialog.clearance_invalid") }), Vec::new()), }; let mut p = json!({ "clearance": clearance, "nearest": 1 }); if !names.is_empty() { @@ -762,7 +762,7 @@ fn interference_rows(app: &SolveApp, ui: &mut egui::Ui, r: &Value) { } let hits = r["overlaps"].as_array().cloned().unwrap_or_default(); row_label(ui, "Checked"); - ui.label(format!("{} bodies", r["bodies"].as_u64().unwrap_or(0))); + ui.label(crate::i18n::format("dialog.bodies_count", &[("count", &r["bodies"].as_u64().unwrap_or(0).to_string())])); ui.end_row(); let unchecked = r["unchecked"].as_array().cloned().unwrap_or_default(); let near = r["near"].as_array().cloned().unwrap_or_default(); @@ -812,7 +812,7 @@ fn interference_rows(app: &SolveApp, ui: &mut egui::Ui, r: &Value) { // Pairs the check could not work out: not clear, not known to interfere. for u in unchecked { row_label(ui, &format!("{} · {}", u["a"].as_str().unwrap_or(""), u["b"].as_str().unwrap_or(""))); - ui.label(RichText::new("could not be checked").color(t.warning)).on_hover_text(u["reason"].as_str().unwrap_or("")); + ui.label(RichText::new(crate::i18n::tr("dialog.could_not_be_checked")).color(t.warning)).on_hover_text(u["reason"].as_str().unwrap_or("")); ui.end_row(); } } diff --git a/crates/ui-egui/src/dialogs_sheet.rs b/crates/ui-egui/src/dialogs_sheet.rs index 91b5683bb..0de88ad6b 100644 --- a/crates/ui-egui/src/dialogs_sheet.rs +++ b/crates/ui-egui/src/dialogs_sheet.rs @@ -290,7 +290,7 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Sm, inputs: &mut [Sel row_label(ui, "Length"); enter |= field(ui, length); ui.end_row(); - row_label(ui, "Gap"); + row_label(ui, "ui.sheet_gap"); let r = ui.add(egui::TextEdit::singleline(gap).hint_text(crate::i18n::tr_label("from the rule"))); crate::params_dialog::complete(ui, &r, gap); enter |= r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)); diff --git a/crates/ui-egui/src/i18n_ui_tests.rs b/crates/ui-egui/src/i18n_ui_tests.rs index 26bd8551d..8614a0a60 100644 --- a/crates/ui-egui/src/i18n_ui_tests.rs +++ b/crates/ui-egui/src/i18n_ui_tests.rs @@ -290,3 +290,34 @@ fn long_panel_label_wraps_centred_and_its_button_is_centred() { assert!(rows.iter().all(|row| lr.contains_rect(*row)), "the highlight holds both lines: {lr:?} {rows:?}"); out.textures_delta.clear(); } + +/// The Interference dialog's title, input and Compute button come from the catalogs: they were +/// English in every language. +#[test] +fn interference_dialog_renders_in_the_active_language() { + let mut h = Harness::new(); + h.app.preferences.language = "fr".into(); + h.app.home.open = false; + h.call("ui.start", json!({"command":"inspect.interference"})); + h.frames(3); + for word in ["INTERFÉRENCE", "Corps (tous si aucun)", "Calculer"] { + assert!(h.widget(word).is_some(), "{word:?} must be shown"); + } + for english in ["INTERFERENCE", "Bodies (all if none)", "Compute"] { + assert!(h.widget(english).is_none(), "{english:?} is still shown in English"); + } + let fr = crate::i18n::Locale::for_language("fr"); + assert_eq!(fr.format("dialog.bodies_count", &[("count", "3")]), "3 corps"); + assert_eq!(fr.text("dialog.compute_again"), "Recalculer"); +} + +/// The continuity legend's Gap (an opening between faces) and the sheet-metal hem's gap are +/// different words in some languages, so each has its own message. +#[test] +fn continuity_gap_and_sheet_metal_gap_are_separate_messages() { + for (lang, legend, sheet) in [("fr", "Écart", "Jeu"), ("de", "Lücke", "Spalt")] { + let locale = crate::i18n::Locale::for_language(lang); + assert_eq!(locale.text("ui.continuity_gap"), legend, "{lang}"); + assert_eq!(locale.text("ui.sheet_gap"), sheet, "{lang}"); + } +} diff --git a/crates/ui-egui/src/sketch_tools.rs b/crates/ui-egui/src/sketch_tools.rs index a6e20fe10..4379774d3 100644 --- a/crates/ui-egui/src/sketch_tools.rs +++ b/crates/ui-egui/src/sketch_tools.rs @@ -106,8 +106,9 @@ fn continuity_legend(app: &SolveApp, painter: &egui::Painter, proj: &Proj) { } let tk = crate::theme::Tokens::get(); let [smooth, jump, sharp, gap] = tk.continuity; - let tr = crate::i18n::tr_label; - let rows = [(tr("G2 curvature"), smooth), (tr("G1 tangent"), jump), (tr("G0 crease"), sharp), (tr("Gap"), gap)]; + // Stable ids: this Gap is a hole between faces, not the sheet-metal gap (`ui.sheet_gap`). + let tr = crate::i18n::tr; + let rows = [(tr("ui.continuity_g2"), smooth), (tr("ui.continuity_g1"), jump), (tr("ui.continuity_g0"), sharp), (tr("ui.continuity_gap"), gap)]; let font = egui::FontId::proportional(12.0); let (row, pad, swatch) = (18.0, 8.0, 22.0); let text_width = rows.iter().map(|(label, _)| painter.layout_no_wrap(label.to_string(), font.clone(), tk.text).size().x).fold(0.0, f32::max); From e887792182a3d83d09b4000e6a72f2849a309346 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Sun, 18 Oct 2026 22:51:37 +0000 Subject: [PATCH 013/225] Fix orbit about the picked point (regression in 0.16.0) (#2753) Orbiting about the point under the cursor (or the origin) turned the camera about its target and then panned to put the pivot back. The pan works at the target's depth with the parallel-view scale, so in a perspective view the pivot slid off its pixel and the model swung about the camera. The camera now turns rigidly about the pivot: Camera::orbit_about keeps the pivot's coordinates in the camera's frame and rebuilds the target from the new orientation, so the pivot stays exactly on its pixel in both projections. The Shift snap spring and view.navigate's pivot orbit use the same. Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd/view_navigation.rs | 12 ++------ crates/render/src/camera.rs | 37 ++++++++++++++++++++++++ crates/ui-egui/src/navigation.rs | 29 +++++-------------- crates/ui-egui/src/viewport.rs | 27 +++++++++++++++++ 4 files changed, 73 insertions(+), 32 deletions(-) diff --git a/crates/engine/src/cmd/view_navigation.rs b/crates/engine/src/cmd/view_navigation.rs index 258c0b143..9556dca33 100644 --- a/crates/engine/src/cmd/view_navigation.rs +++ b/crates/engine/src/cmd/view_navigation.rs @@ -91,16 +91,8 @@ fn continuous(mut cam: Camera, p: &Value) -> Result { cam.pan(delta.x, delta.y, viewport()?.y); } else if p.get("pivot").is_some() { let pivot = req_vec3(cmd, p, "pivot")?; - let size = viewport()?; - let before = cam.to_screen(pivot, size.x, size.y, 1.0); - cam.orbit(delta.x, delta.y); - let after = cam.to_screen(pivot, size.x, size.y, 1.0); - if let (Some((ax, ay, _)), Some((bx, by, _))) = (before, after) { - // Pan operates at target depth. Perspective screen correction must instead - // use the pivot's depth after orbiting; lateral pan leaves that depth fixed. - let scale = if cam.fov > 0.0 { (cam.eye() - pivot).dot(cam.back()) / cam.distance } else { 1.0 }; - cam.pan((ax - bx) * scale, (ay - by) * scale, size.y); - } + viewport()?; + cam.orbit_about(delta.x, delta.y, pivot); } else { cam.orbit(delta.x, delta.y); } diff --git a/crates/render/src/camera.rs b/crates/render/src/camera.rs index 6e1d38f7b..abef03615 100644 --- a/crates/render/src/camera.rs +++ b/crates/render/src/camera.rs @@ -353,6 +353,25 @@ impl Camera { self.yaw = (self.yaw + dx * 0.008) % std::f64::consts::TAU; self.pitch = (self.pitch + dy * 0.008).clamp(-lim, lim); } + /// Orbit by pixel deltas about `pivot`: the camera turns rigidly about it, so the pivot keeps + /// its place in the camera's frame and on screen, in perspective as in parallel views. + pub fn orbit_about(&mut self, dx: f64, dy: f64, pivot: Vec3) { + let keep = self.frame_coords(pivot); + self.orbit(dx, dy); + self.place(pivot, keep); + } + /// Where `p` lies from the target along the camera's right, up and back axes. + pub fn frame_coords(&self, p: Vec3) -> Vec3 { + let (r, u, b) = self.basis(); + let d = p - self.target; + Vec3::new(d.dot(r), d.dot(u), d.dot(b)) + } + /// Move the target so `p` lies at `coords` (from [`Camera::frame_coords`]) in the camera's + /// frame: with the distance unchanged, `p` is where it was on screen. + pub fn place(&mut self, p: Vec3, coords: Vec3) { + let (r, u, b) = self.basis(); + self.target = p - (r * coords.x + u * coords.y + b * coords.z); + } /// Rotate the image about the viewing direction. pub fn roll_by(&mut self, radians: f64) { if radians.is_finite() { @@ -432,6 +451,24 @@ impl Camera { mod tests { use super::*; + /// Orbiting about a point keeps it on its pixel, with and without perspective and roll. + #[test] + fn orbit_about_keeps_the_pivot_on_screen() { + let pivot = Vec3::new(12.0, -7.0, 9.0); + for fov in [0.0, 0.6] { + for roll in [0.0, 0.4] { + let mut cam = Camera { target: Vec3::new(3.0, 4.0, -2.0), distance: 150.0, yaw: 0.3, pitch: 0.5, roll, fov, ..Camera::default() }; + let before = cam.to_screen(pivot, 800.0, 600.0, 100.0).unwrap(); + for _ in 0..10 { + cam.orbit_about(25.0, -12.0, pivot); + } + let after = cam.to_screen(pivot, 800.0, 600.0, 100.0).unwrap(); + assert!((after.0 - before.0).abs() < 1e-6 && (after.1 - before.1).abs() < 1e-6, "fov {fov}, roll {roll}: {before:?} -> {after:?}"); + assert!((cam.eye() - pivot).len() > 1.0); + } + } + } + #[test] fn front_view_projects_target_to_centre() { let mut c = Camera { target: Vec3::new(1.0, 2.0, 3.0), distance: 50.0, ..Default::default() }; diff --git a/crates/ui-egui/src/navigation.rs b/crates/ui-egui/src/navigation.rs index 90351a8a7..58ed4b723 100644 --- a/crates/ui-egui/src/navigation.rs +++ b/crates/ui-egui/src/navigation.rs @@ -574,7 +574,8 @@ pub(crate) struct OrbitSnap { pub(crate) target: Camera, pub(crate) yaw_velocity: f64, pub(crate) pitch_velocity: f64, - pub(crate) pivot: Option<(Vec3, Pos2)>, + /// The pivot and where it lies in the camera's frame ([`Camera::frame_coords`]). + pub(crate) pivot: Option<(Vec3, Vec3)>, } /// Pointer motion accumulates independently of the spring preview, so many small deltas @@ -610,10 +611,7 @@ pub(crate) fn orbit_drag(app: &mut SolveApp, rect: Rect, dx: f64, dy: f64, press } else { None } - .and_then(|p| { - app.cam = displayed; - projection(app, rect).to_screen(p).map(|at| (p, at)) - }); + .map(|p| (p, displayed.frame_coords(p))); let spring = app.viewport.orbit_snap.get_or_insert(OrbitSnap { target, yaw_velocity: 0.0, pitch_velocity: 0.0, pivot }); spring.target = target; spring.pivot = pivot; @@ -623,7 +621,7 @@ pub(crate) fn orbit_drag(app: &mut SolveApp, rect: Rect, dx: f64, dy: f64, press /// A lightly damped spring: mostly settled in about a third of a second, with a small /// elastic finish. Bounded substeps keep the behavior consistent across frame rates. -pub(crate) fn step_orbit_snap(app: &mut SolveApp, rect: Rect, dt: f64) { +pub(crate) fn step_orbit_snap(app: &mut SolveApp, _rect: Rect, dt: f64) { let Some(mut spring) = app.viewport.orbit_snap.take() else { return }; let dt = if dt.is_finite() { dt.clamp(0.0, 0.05) } else { 1.0 / 60.0 }; let steps = (dt * 240.0).ceil().max(1.0) as usize; @@ -645,10 +643,8 @@ pub(crate) fn step_orbit_snap(app: &mut SolveApp, rect: Rect, dt: f64) { if done { app.cam = spring.target; } - if let Some((pivot, at)) = spring.pivot - && let Some(after) = projection(app, rect).to_screen(pivot) - { - app.cam.pan(f64::from(at.x - after.x), f64::from(at.y - after.y), f64::from(rect.height().max(1.0))); + if let Some((pivot, coords)) = spring.pivot { + app.cam.place(pivot, coords); } if !done { app.viewport.orbit_snap = Some(spring); @@ -707,18 +703,7 @@ pub fn orbit(app: &mut SolveApp, rect: egui::Rect, dx: f64, dy: f64, press: Opti app.cam.orbit(dx, dy); return; }; - orbit_about(app, rect, dx, dy, pivot); -} - -/// Orbit by pixel deltas, keeping `pivot` still on screen: the camera turns about it and a pan -/// correction puts it back where it was. -pub(crate) fn orbit_about(app: &mut SolveApp, rect: egui::Rect, dx: f64, dy: f64, pivot: Vec3) { - let before = crate::viewport::projection(app, rect).to_screen(pivot); - app.cam.orbit(dx, dy); - let after = crate::viewport::projection(app, rect).to_screen(pivot); - if let (Some(a), Some(b)) = (before, after) { - app.cam.pan(f64::from(a.x - b.x), f64::from(a.y - b.y), f64::from(rect.height().max(1.0))); - } + app.cam.orbit_about(dx, dy, pivot); } #[cfg(test)] diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 295d199d6..6245f2db7 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -5911,6 +5911,33 @@ mod tests { } } + /// An orbit drag that starts on the model turns about the point under the cursor, which + /// stays on its pixel, in perspective as in parallel views. The perspective view used to + /// correct with a pan at the target's depth, so the point slid away and the view swung + /// about the camera instead. + #[test] + fn cursor_orbit_keeps_the_picked_point_on_its_pixel() { + for perspective in [false, true] { + for offset in [vec2(30.0, 20.0), vec2(-60.0, 10.0), vec2(120.0, -40.0)] { + let mut h = crate::scenario::Harness::new(); + h.app.preferences.orbit_around = crate::prefs::OrbitAround::Cursor; + h.app.ui.perspective = perspective; + h.app.run("solid.box", json!({"length":80,"width":50,"height":20})).unwrap(); + h.app.fit_view(); + let rect = h.app.viewport.rect.unwrap(); + let at = rect.center() + offset; + let proj = projection(&h.app, rect); + assert!(pick(&h.app, &proj, at).iter().any(|hit| matches!(hit, Hit::Face { .. })), "the drag starts on the box"); + let pivot = crate::prefs::pivot_under(&h.app, &proj, at); + let before = h.app.cam; + h.call("ui.drag", json!({"x0":at.x,"y0":at.y,"x1":at.x+150.0,"y1":at.y+60.0,"button":"middle","shift":true,"steps":20})); + assert!((h.app.cam.yaw - before.yaw).abs() > 0.5, "the view turned"); + let after = projection(&h.app, rect).to_screen(pivot).unwrap(); + assert!(after.distance(at) < 0.5, "perspective={perspective}: {at:?} -> {after:?}"); + } + } + } + #[test] fn shift_orbit_keeps_cursor_pivot_and_default_middle_pan() { let mut h = crate::scenario::Harness::new(); From 143435dc1cc605b45e193ce5b4499b20295c50a6 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Sun, 18 Oct 2026 23:53:43 +0000 Subject: [PATCH 014/225] Format and clippy Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/control.rs | 5 ++++- crates/ui-egui/src/viewport.rs | 3 ++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index a659f9b0f..204b14719 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -208,7 +208,10 @@ pub(crate) fn view_scene(app: &SolveApp, guides: solidcraft_engine::view::Guides /// The grid and the origin's axes as the window shows them (the Grid and Origin switches). pub(crate) fn window_guides(app: &SolveApp) -> solidcraft_engine::view::Guides { - solidcraft_engine::view::Guides { grid: app.session.active_sketch.is_some() || (app.ui.show_grid && !crate::viewport::active_view(app).hide_grid), axes: app.origin_visible() } + solidcraft_engine::view::Guides { + grid: app.session.active_sketch.is_some() || (app.ui.show_grid && !crate::viewport::active_view(app).hide_grid), + axes: app.origin_visible(), + } } /// A picture of the view as the window shows it, RGBA, drawn on the GPU with the viewport's diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 0ee2885ee..9f1eb8320 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -6293,7 +6293,8 @@ mod grid_plane_tests { let under = grid(&app); assert!(!under.is_empty(), "the open sketch shows a grid (follows the view: {follows})"); // Each line is 32 bytes: two f32 points, a colour and a width; the XZ plane is Y = 0. - let ys: Vec = under.chunks_exact(32).flat_map(|l| [&l[4..8], &l[16..20]]).map(|b| f32::from_le_bytes(b.try_into().unwrap())).collect(); + let ys: Vec = + under.as_chunks::<32>().0.iter().flat_map(|l| [&l[4..8], &l[16..20]]).map(|b| f32::from_le_bytes(b.try_into().unwrap())).collect(); assert!(ys.iter().all(|y| y.abs() < 1e-3), "the grid lies on the sketch plane"); } app.ui.show_grid = true; From 22a86a744ed606425c2e3e624811ffb5f057e8f0 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Sun, 18 Oct 2026 20:31:22 -0400 Subject: [PATCH 015/225] CI: keep the fast self-hosted runners for main and the merge queue (#2830) Same-repo pull requests ran their heavy jobs on the three fast runners too, and the merge queue's test shards waited behind them for hours. Pull requests now use the GitHub-hosted path. Co-authored-by: Claude Opus 5.5 --- .github/workflows/ci.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e8f2d7ac1..102743b64 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -94,7 +94,9 @@ jobs: # Whether the other Linux jobs use the self-hosted runners too. # Trusted self-hosted runs only: a fork PR's checks run on the untrusted pool and must never # route the jobs after them to the trusted runners. - local: ${{ runner.environment == 'self-hosted' && !(github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository) }} + # The fast self-hosted runners are kept for main and the merge queue (the pre-merge gate); + # pull requests, same-repo ones included, take the GitHub-hosted or untrusted paths. + local: ${{ runner.environment == 'self-hosted' && github.event_name != 'pull_request' }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: From 9c411859bc8d95ca965d66ca38bb69d36bab4534 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Sun, 18 Oct 2026 20:35:03 -0400 Subject: [PATCH 016/225] CI: self-hosted test shards build in their warm directories, no 3 GB download (#2833) On main and in the merge queue every test shard ran on the self-hosted machine but waited for the GitHub-hosted Build tests job and then spent about 12.5 minutes downloading its 3.2 GB archive (four shards at once over one connection). There, each shard now builds the tests in the runner's warm build directory (the existing build-tests one) and runs its slice directly; Build tests runs only where the shards run on GitHub's or the untrusted runners. Co-authored-by: Claude Opus 5.5 --- .github/workflows/ci.yml | 54 +++++++++++++++++++++++++++++++--------- 1 file changed, 42 insertions(+), 12 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 102743b64..b8bb2e0b0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,10 +23,12 @@ # build directories via scripts/ci/warm-target.sh). Fork PRs' Linux jobs run on the isolated, ephemeral # `self-hosted-untrusted` runners (no warm caches) when the PR number ends in 7, 8 or 9 (the rest of # the fork PRs, and everything else, run on GitHub's runners, which have far more free slots). -# The test archive is always built on GitHub's runners: the self-hosted machine has a newer -# glibc, so its binaries wouldn't start on ubuntu-24.04, while the archive runs there unchanged -# (same /home/runner/work checkout path). Fork pull requests, the nightly run and Run workflow -# use GitHub's runners only; the self-hosted runners refuse any other job. +# Where the test shards run on GitHub's runners, the test archive is built there too: the +# self-hosted machine has a newer glibc, so its binaries wouldn't start on ubuntu-24.04, while the +# archive runs there unchanged (same /home/runner/work checkout path). The self-hosted shards +# (main and the merge queue) skip the archive and build the tests in their warm build directories. +# Fork pull requests, the nightly run and Run workflow use GitHub's runners only; the self-hosted +# runners refuse any other job. name: CI on: @@ -270,7 +272,9 @@ jobs: build-tests: name: Build tests needs: changes - if: needs.changes.outputs.native == 'true' + # The self-hosted shards (main and the merge queue) build from their warm build directories + # instead: downloading the 3 GB archive took them longer than building. + if: needs.changes.outputs.native == 'true' && needs.changes.outputs.local != 'true' runs-on: ${{ (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository && (endsWith(format('{0}', github.event.pull_request.number), '7') || endsWith(format('{0}', github.event.pull_request.number), '8') || endsWith(format('{0}', github.event.pull_request.number), '9'))) && 'self-hosted-untrusted' || 'ubuntu-24.04' }} # Fork builds compile inside gVisor on shared boxes; give them room to finish and upload. timeout-minutes: ${{ (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository && (endsWith(format('{0}', github.event.pull_request.number), '7') || endsWith(format('{0}', github.event.pull_request.number), '8') || endsWith(format('{0}', github.event.pull_request.number), '9'))) && 90 || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository) && 60 || 45 }} @@ -317,6 +321,7 @@ jobs: tests: name: Native Linux tests (${{ matrix.shard }}/4) needs: [changes, build-tests] + if: ${{ !cancelled() && needs.changes.outputs.native == 'true' && (needs.changes.outputs.local == 'true' || needs.build-tests.result == 'success') }} runs-on: ${{ needs.changes.outputs.local == 'true' && 'self-hosted-fast' || ((github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository && (endsWith(format('{0}', github.event.pull_request.number), '7') || endsWith(format('{0}', github.event.pull_request.number), '8') || endsWith(format('{0}', github.event.pull_request.number), '9'))) && 'self-hosted-untrusted' || 'ubuntu-24.04') }} timeout-minutes: 60 strategy: @@ -341,12 +346,26 @@ jobs: - uses: taiki-e/install-action@1168f6810a3cb30a3514bf5756a3b7f0422c6df8 # v2.87.28 with: tool: cargo-nextest - - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + # On the self-hosted runners each shard builds the tests in its warm build directory (a few + # minutes for what changed); elsewhere it runs the archive the Build tests job made. + - name: Size parallel compiles to the job's memory + if: needs.changes.outputs.local == 'true' + run: scripts/ci/build-jobs.sh + - name: Warm build directory (self-hosted runner) + if: needs.changes.outputs.local == 'true' + run: scripts/ci/warm-target.sh build-tests + - if: needs.changes.outputs.local == 'true' + uses: dtolnay/rust-toolchain@stable + - if: needs.changes.outputs.local != 'true' + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: nextest-archive - name: Run tests env: EVENT_NAME: ${{ github.event_name }} + LOCAL: ${{ needs.changes.outputs.local }} + FULL: ${{ needs.changes.outputs.full }} + PACKAGES: ${{ needs.changes.outputs.packages }} SHARD: ${{ matrix.shard }} SHARDS: ${{ github.event_name == 'pull_request' && 2 || 4 }} run: | @@ -357,10 +376,19 @@ jobs: if [ "$EVENT_NAME" != pull_request ]; then all=(--ignore-default-filter -E 'not (package(solidcraft-kernel) & binary(boolean_props))') fi - # Extract into ./target: tests that run a built binary (env!("CARGO_BIN_EXE_*")) have - # the build job's path, which is the same checkout path here. - cargo nextest run --archive-file tests.tar.zst --workspace-remap . --extract-to . --extract-overwrite \ - --profile ci --partition "slice:$SHARD/$SHARDS" --no-tests=pass "${all[@]}" + if [ "$LOCAL" = true ]; then + scope=(--workspace) + if [ "$FULL" != true ]; then scope=(); for p in $PACKAGES; do scope+=(-p "$p"); done; fi + # The warm build directory keeps the last run's junit.xml: never upload that one. + rm -f "$CARGO_TARGET_DIR/nextest/ci/junit.xml" + cargo nextest run "${scope[@]}" --cargo-profile ci --locked \ + --profile ci --partition "slice:$SHARD/$SHARDS" --no-tests=pass "${all[@]}" + else + # Extract into ./target: tests that run a built binary (env!("CARGO_BIN_EXE_*")) have + # the build job's path, which is the same checkout path here. + cargo nextest run --archive-file tests.tar.zst --workspace-remap . --extract-to . --extract-overwrite \ + --profile ci --partition "slice:$SHARD/$SHARDS" --no-tests=pass "${all[@]}" + fi - name: Robustness goldens (pull requests that change geometry) # Every seed of tests/robustness/goldens.json (each seed is a test), split over the shards; # pushes to main and the nightly run them in the step above. @@ -381,7 +409,7 @@ jobs: uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: junit-${{ matrix.shard }} - path: target/nextest/ci/junit.xml + path: ${{ env.CARGO_TARGET_DIR || 'target' }}/nextest/ci/junit.xml retention-days: 7 action-matrix: @@ -638,6 +666,7 @@ jobs: CHANGES: ${{ needs.changes.result }} CHECKS: ${{ needs.checks.result }} NATIVE: ${{ needs.changes.outputs.native }} + LOCAL: ${{ needs.changes.outputs.local }} WINDOWS: ${{ needs.changes.outputs.windows }} ORACLE_RUN: ${{ needs.changes.outputs.oracle }} CLIPPY: ${{ needs.clippy.result }} @@ -652,7 +681,8 @@ jobs: test "$CHECKS" = success if [ "$NATIVE" = true ]; then test "$CLIPPY" = success - test "$BUILD" = success + # The self-hosted test shards build their own tests (no Build tests job there). + [ "$BUILD" = success ] || { [ "$LOCAL" = true ] && [ "$BUILD" = skipped ]; } test "$TESTS" = success test "$DOCS" = success fi From 2452513b658372723b8c1da30fdc5fda4c284341 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Sun, 18 Oct 2026 23:39:00 +0000 Subject: [PATCH 017/225] CI: faster test shards - Pull requests that can change a robustness golden check every seed but the 17 slowest, in the same nextest run as the other tests instead of a second step after it (16-30 minutes on its own). The slow seeds (about four fifths of the goldens' time) still run in the merge queue, on main and nightly. A failed golden still prints how to re-record it, and junit.xml now holds the whole run. - The slowest tests start first (nextest priority), so a shard no longer ends with one of them running alone. - tspline::tests::hostile_tsplines_never_panic joins the heavy tests pull requests skip (up to 12 minutes on a GitHub runner; the same kind of check as hostile_params_never_panic). - The ci profile builds dependencies without line tables: the test archive pull requests' shards download goes from 3.4 GB to 2.2 GB. Co-Authored-By: Claude Opus 5.5 --- .config/nextest.toml | 33 ++++++++++++- .github/workflows/ci.yml | 49 ++++++++++--------- CONTRIBUTING.md | 6 +-- Cargo.toml | 3 ++ crates/engine/src/tests/robustness_goldens.rs | 4 +- docs/book/src/dev/testing.md | 14 +++--- docs/robustness.md | 6 ++- 7 files changed, 76 insertions(+), 39 deletions(-) diff --git a/.config/nextest.toml b/.config/nextest.toml index 92451dd5c..a45691c8a 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -1,8 +1,9 @@ # cargo-nextest settings for CI (`cargo xtask test` does not use nextest). -# PR runs build the tests once and run them in 4 shards (.github/workflows/ci.yml). +# CI builds the tests once and runs them in shards: 2 for a pull request, 4 for main and the nightly +# (.github/workflows/ci.yml). [profile.ci] -# Heavy tests (one to four minutes each on a CI runner) that pull requests skip. They run on +# Heavy tests (one to twelve minutes each on a CI runner) that pull requests skip. They run on # every push to main and nightly (`--ignore-default-filter`), and in `cargo xtask test`. The # boolean_props property tests run only nightly (ci.yml excludes them from pushes to main). # Keep this list in sync with docs/book/src/dev/testing.md and CONTRIBUTING.md. @@ -17,6 +18,7 @@ not ( | test(=cmd::plastic::tests::enclosure_snap_fit_follows_resized_front_wall) )) | (package(solidcraft-kernel) & test(=tests::boolean_identity_on_tangent_primitives)) + | (package(solidcraft-kernel) & test(=tspline::tests::hostile_tsplines_never_panic)) | (package(solidcraft-kernel) & binary(boolean_props)) | (package(solidcraft-engine) & binary(atomic_commands)) | (package(solidcraft-ui-egui) & binary(scenarios) & test(=acceptance_sensor_enclosure)) @@ -39,3 +41,30 @@ path = "junit.xml" filter = "binary(action_matrix) & test(=action_matrix_sample)" threads-required = "num-cpus" + +# The slowest tests start first, so a shard does not end with one of them running alone on a +# core while the others sit idle (seed_81 alone takes about 20 minutes under CI load). Medians +# from the CI test timings (the junit artifacts), slowest first; a test over ~100 s belongs here. +[[profile.ci.overrides]] +filter = """ +(package(solidcraft-engine) & ( + test(/^tests::robustness_goldens::seed_(81|45|20|24|95|02|57|40|18|48|32|46|85|61)$/) + | test(/^tests::robustness::/) + | test(=tests::hostile_params_never_panic) + | test(=cmd::clearance::tests::distances_are_exact_on_edges_and_curved_faces) + | test(=cmd::clipboard::tests::a_pasted_coil_joins_the_pasted_body) + | test(=tests::pleat_join::the_pleats_join_at_every_wall_from_2_4_to_2_6_mm) + | test(=tests::flush_join_loft::a_flange_flush_with_the_end_of_a_bent_tapered_tube_joins) + | test(=cmd::sheet::tests::perforated_sheet_takes_a_thousand_round_holes) + | test(=boolean_regression_tests::joined_loft_frames_plan_their_display_at_every_quality) +)) +| (package(solidcraft-engine) & (binary(atomic_commands) | binary(step_export_regressions))) +| (package(solidcraft-kernel) & ( + test(=curveblend::tests::rolling_ball_turns_about_a_rounded_corner_of_its_radius) + | test(=tests::fillet_tabbed_plate_outer_loop_and_partial_selection_after_hole) + | test(=tspline::tests::hostile_tsplines_never_panic) + | test(=fill::tests::regular_rims_of_three_to_eight_sides_fill_with_one_face_and_close_the_cup) + | test(/^issue_788_tests::equal_bores_crossing_/) +)) +""" +priority = 100 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b8bb2e0b0..8bc782e27 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -5,7 +5,7 @@ # those. Changes to the lockfile, root manifest, toolchain/cargo/nextest config, .github/, # vendor/, tests/, scripts/ or any file no package owns select the whole workspace, as do # pushes to main, the nightly run and Run workflow. -# Tests are built once and run in 4 shards. A few heavy tests (see .config/nextest.toml) are +# Tests are built once and run in shards. A few heavy tests (see .config/nextest.toml) are # skipped on pull requests and run on pushes to main and nightly. The Windows jobs (D3D12 shaders # and app startup) run on pull requests only when what they test changes (the GPU crate, the app, # the viewport's GPU glue, the graphics dependencies, their scripts or this file); main and @@ -363,45 +363,46 @@ jobs: - name: Run tests env: EVENT_NAME: ${{ github.event_name }} + GOLDENS: ${{ needs.changes.outputs.goldens }} LOCAL: ${{ needs.changes.outputs.local }} FULL: ${{ needs.changes.outputs.full }} PACKAGES: ${{ needs.changes.outputs.packages }} SHARD: ${{ matrix.shard }} SHARDS: ${{ github.event_name == 'pull_request' && 2 || 4 }} + # The robustness golden seeds a pull request skips: each takes one to twenty minutes under + # CI load, together about four fifths of the goldens' time. Pushes to main, the merge + # queue and the nightly run every seed. + SLOW_SEEDS: 81|45|20|24|95|02|57|40|18|48|32|46|85|61|77|34|14 run: | # Pull requests skip the heavy tests (default-filter in .config/nextest.toml). - all=() - # The boolean property tests draw new random inputs every run; they run only in the - # nightly property-tests job, so a known kernel bug cannot turn main red at random. + filter=() if [ "$EVENT_NAME" != pull_request ]; then - all=(--ignore-default-filter -E 'not (package(solidcraft-kernel) & binary(boolean_props))') + # The boolean property tests draw new random inputs every run; they run only in the + # nightly property-tests job, so a known kernel bug cannot turn main red at random. + filter=(--ignore-default-filter -E 'not (package(solidcraft-kernel) & binary(boolean_props))') + elif [ "$GOLDENS" = true ]; then + # A pull request that can change a robustness golden (tests/robustness/goldens.json) + # also checks every seed but the slow ones, in the same run so they share its cores. + filter=(--ignore-default-filter -E "default() | (package(solidcraft-engine) & test(/^tests::robustness_goldens::/) & not test(/^tests::robustness_goldens::seed_($SLOW_SEEDS)\$/))") fi + junit=${CARGO_TARGET_DIR:-target}/nextest/ci/junit.xml + # The warm build directory keeps the last run's junit.xml: never upload that one. + rm -f "$junit" if [ "$LOCAL" = true ]; then scope=(--workspace) if [ "$FULL" != true ]; then scope=(); for p in $PACKAGES; do scope+=(-p "$p"); done; fi - # The warm build directory keeps the last run's junit.xml: never upload that one. - rm -f "$CARGO_TARGET_DIR/nextest/ci/junit.xml" - cargo nextest run "${scope[@]}" --cargo-profile ci --locked \ - --profile ci --partition "slice:$SHARD/$SHARDS" --no-tests=pass "${all[@]}" + run=(cargo nextest run "${scope[@]}" --cargo-profile ci --locked) else # Extract into ./target: tests that run a built binary (env!("CARGO_BIN_EXE_*")) have # the build job's path, which is the same checkout path here. - cargo nextest run --archive-file tests.tar.zst --workspace-remap . --extract-to . --extract-overwrite \ - --profile ci --partition "slice:$SHARD/$SHARDS" --no-tests=pass "${all[@]}" + run=(cargo nextest run --archive-file tests.tar.zst --workspace-remap . --extract-to . --extract-overwrite) fi - - name: Robustness goldens (pull requests that change geometry) - # Every seed of tests/robustness/goldens.json (each seed is a test), split over the shards; - # pushes to main and the nightly run them in the step above. - if: github.event_name == 'pull_request' && needs.changes.outputs.goldens == 'true' - env: - SHARD: ${{ matrix.shard }} - SHARDS: ${{ github.event_name == 'pull_request' && 2 || 4 }} - run: | - if ! cargo nextest run --archive-file tests.tar.zst --workspace-remap . --extract-to . --extract-overwrite \ - --profile ci --ignore-default-filter --partition "slice:$SHARD/$SHARDS" --no-tests=pass \ - -E 'package(solidcraft-engine) & test(/^tests::robustness_goldens::/)'; then - echo "::error::A robustness golden changed. If the new result is intended, re-record it in this pull request and say why:" - echo "::error::ROBUSTNESS_GOLDENS_BLESS=\"why it changed\" cargo test --profile ci -p solidcraft-engine --lib robustness_goldens:: (see docs/robustness.md)" + if ! "${run[@]}" --profile ci --partition "slice:$SHARD/$SHARDS" --no-tests=pass "${filter[@]}"; then + # A failed golden gets the hint to re-record it (junit.xml lists the failures). + if [ -f "$junit" ] && tr '\n' ' ' < "$junit" | grep -q ']*>[[:space:]]*.seeds` records override only the listed seeds on that From cd85efd73d9c77d74e2e447598109a09a4d8ae3e Mon Sep 17 00:00:00 2001 From: bherbruck Date: Mon, 19 Oct 2026 00:31:41 +0000 Subject: [PATCH 018/225] CI: the repository checks also keep off the fast runners for pull requests the format and repository checks job still took a self-hosted-fast runner for every same-repo pull request. It now follows the same rule, and the notes at the top say so. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b8bb2e0b0..2bcbe2ab9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,11 +18,13 @@ # Trusted runs use both pools: pushes to main, merge-queue groups and pull requests from a branch # of this repository (people with write access; fork pull requests never run on this machine). # There, Select checks and ci run on the self-hosted light runner (`self-hosted-light`, quick -# jobs, so they never wait behind a build), and the repository checks, Clippy, the doc tests, -# the reference tests and all four test shards on the self-hosted runners (`self-hosted-fast`, warm -# build directories via scripts/ci/warm-target.sh). Fork PRs' Linux jobs run on the isolated, ephemeral -# `self-hosted-untrusted` runners (no warm caches) when the PR number ends in 7, 8 or 9 (the rest of -# the fork PRs, and everything else, run on GitHub's runners, which have far more free slots). +# jobs, so they never wait behind a build). For pushes to main and the merge queue only, the +# repository checks, Clippy, the doc tests, the reference tests and all four test shards run on the +# self-hosted runners (`self-hosted-fast`, warm build directories via scripts/ci/warm-target.sh); +# a pull request runs them on GitHub's runners, so it never holds up the queue. Fork PRs' Linux +# jobs run on the isolated, ephemeral `self-hosted-untrusted` runners (no warm caches) when the +# PR number ends in 7, 8 or 9 (the rest of the fork PRs, and everything else, run on GitHub's +# runners, which have far more free slots). # Where the test shards run on GitHub's runners, the test archive is built there too: the # self-hosted machine has a newer glibc, so its binaries wouldn't start on ubuntu-24.04, while the # archive runs there unchanged (same /home/runner/work checkout path). The self-hosted shards @@ -93,9 +95,6 @@ jobs: full: ${{ steps.paths.outputs.full }} packages: ${{ steps.paths.outputs.packages }} oracle: ${{ steps.paths.outputs.oracle }} - # Whether the other Linux jobs use the self-hosted runners too. - # Trusted self-hosted runs only: a fork PR's checks run on the untrusted pool and must never - # route the jobs after them to the trusted runners. # The fast self-hosted runners are kept for main and the merge queue (the pre-merge gate); # pull requests, same-repo ones included, take the GitHub-hosted or untrusted paths. local: ${{ runner.environment == 'self-hosted' && github.event_name != 'pull_request' }} @@ -200,7 +199,7 @@ jobs: checks: name: Format and repository checks if: github.event_name != 'pull_request' || !github.event.pull_request.draft - runs-on: ${{ (github.event_name == 'merge_group' || (github.event_name == 'push' && github.ref == 'refs/heads/main') || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository)) && 'self-hosted-fast' || 'ubuntu-24.04' }} + runs-on: ${{ (github.event_name == 'merge_group' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) && 'self-hosted-fast' || 'ubuntu-24.04' }} timeout-minutes: 15 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 From cbf589eb8c280cfe8204f714637f5c7a224b492b Mon Sep 17 00:00:00 2001 From: bherbruck Date: Sun, 18 Oct 2026 20:36:37 -0400 Subject: [PATCH 019/225] Revert #2142: orbit pivot choice back to 0.15.0's, as in 0.16.1 (#2832) This reverts commit cac4bccea8af68a3712acc4e85e71eca71a1ebdb. Orbiting about the point under the cursor goes back to 0.15.0's pivot choice (the picked face or vertex point, an edge's midpoint, or the visible geometry's centre over empty space), matching 0.16.1. Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/prefs.rs | 76 +++++-------------------------------- 1 file changed, 9 insertions(+), 67 deletions(-) diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index 48b12d3bb..927d38eaa 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -863,47 +863,18 @@ pub fn zoom_sign(app: &SolveApp) -> f64 { } /// The model point under a screen position. Over empty space: the centre of the visible bodies -/// and sketches (what Fit frames) while it is on screen; zoomed in so far that it isn't, the -/// model point at the view's centre, so what you look at stays in view (#2138); and the view's -/// centre when neither is there. +/// and sketches (what Fit frames), or the view's centre when nothing is visible. pub(crate) fn pivot_under(app: &SolveApp, proj: &crate::viewport::Proj, at: Pos2) -> Vec3 { - let under = |at: Pos2| { - use crate::viewport::Hit; - crate::viewport::pick(app, proj, at).into_iter().find_map(|h| match h { - Hit::Face { point, .. } | Hit::Vertex { point, .. } => Some(point), - // The point of the edge under the cursor: a long edge's midpoint can be far off screen. - Hit::Edge { body, index, mid } => Some(edge_point_near(app, proj, &body, index, at).unwrap_or(mid)), - _ => None, - }) - }; - if let Some(p) = under(at) { - return p; - } - let b = crate::viewport::view_bounds(app); - if !b.is_empty() && proj.to_screen(b.center()).is_some_and(|s| proj.rect.contains(s)) { - return b.center(); - } - under(proj.rect.center()).unwrap_or(app.cam.target) -} - -/// The point of a body's edge nearest `at` on screen (each segment of its polyline measured on -/// screen, the nearest point taken along the segment in the model). -fn edge_point_near(app: &SolveApp, proj: &crate::viewport::Proj, body: &str, index: usize, at: Pos2) -> Option { - let st = app.session.world_state(); - let mesh = st.body(body)?.mesh(); - let edge = mesh.edges.get(index)?; - let mut best: Option<(f32, Vec3)> = None; - for w in edge.windows(2) { - let (Some(a), Some(b)) = (w.first().copied(), w.get(1).copied()) else { continue }; - let (Some(sa), Some(sb)) = (proj.to_screen(a), proj.to_screen(b)) else { continue }; - let d = sb - sa; - let t = if d.length_sq() > 1e-6 { ((at - sa).dot(d) / d.length_sq()).clamp(0.0, 1.0) } else { 0.0 }; - let dist = (sa + d * t).distance(at); - if best.is_none_or(|(bd, _)| dist < bd) { - best = Some((dist, a + (b - a) * f64::from(t))); + use crate::viewport::Hit; + for h in crate::viewport::pick(app, proj, at) { + match h { + Hit::Face { point, .. } | Hit::Vertex { point, .. } => return point, + Hit::Edge { mid, .. } => return mid, + _ => {} } } - best.map(|(_, p)| p) + let b = crate::viewport::view_bounds(app); + if b.is_empty() { app.cam.target } else { b.center() } } /// A plain number typed into a field, with a decimal point or a decimal comma (#1347): "2.5" @@ -2443,35 +2414,6 @@ mod tests { assert_eq!(app.viewport.orbit_pivot, Some(solidcraft_engine::geom::Vec3::new(5.0, -3.0, 2.0))); } - /// #2138: zoomed in on one end of a long part, the visible geometry's centre is off screen. A - /// drag from empty space must not turn around it, or the end you are looking at swings out of - /// view; it turns around the model point at the view's centre instead. - #[test] - fn orbiting_from_empty_space_keeps_a_zoomed_in_view_on_screen() { - use solidcraft_engine::geom::Vec3; - let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); - app.run("solid.box", json!({"length": 400, "width": 10, "height": 10})).unwrap(); - app.preferences.orbit_around = OrbitAround::Cursor; - let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0)); - app.fit_view(); - // Look closely at the end near the origin. - let end = Vec3::new(5.0, 5.0, 5.0); - app.cam.target = end; - app.cam.distance = 60.0; - let proj = crate::viewport::projection(&app, rect); - let centre = crate::viewport::view_bounds(&app).center(); - assert!(proj.to_screen(centre).is_none_or(|s| !rect.contains(s)), "the part's centre is off screen"); - let corner = egui::pos2(10.0, 10.0); - use crate::viewport::Hit; - assert!(!crate::viewport::pick(&app, &proj, corner).iter().any(|h| matches!(h, Hit::Face { .. } | Hit::Edge { .. } | Hit::Vertex { .. }))); - for _ in 0..4 { - orbit(&mut app, rect, 60.0, 20.0, Some(corner)); - } - assert_ne!(app.viewport.orbit_pivot, Some(centre)); - let s = crate::viewport::projection(&app, rect).to_screen(end); - assert!(s.is_some_and(|s| rect.contains(s)), "the end stays in view: {s:?}"); - } - /// The Y up preference turns the view: the camera's up axis follows it, startup included. #[test] fn up_axis_preference_turns_the_view() { From 03e6c3d4686f35d760aee2816f4d1e533f4dcb3c Mon Sep 17 00:00:00 2001 From: bherbruck Date: Mon, 19 Oct 2026 00:40:00 +0000 Subject: [PATCH 020/225] Version 0.16.2 Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 34 +++++++++++++++++----------------- Cargo.toml | 2 +- 2 files changed, 18 insertions(+), 18 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 03a4027e6..8a2231f10 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4078,7 +4078,7 @@ dependencies = [ [[package]] name = "solidcraft" -version = "0.16.1" +version = "0.16.2" dependencies = [ "block2 0.6.2", "eframe", @@ -4109,11 +4109,11 @@ dependencies = [ [[package]] name = "solidcraft-3dx-client" -version = "0.16.1" +version = "0.16.2" [[package]] name = "solidcraft-cli" -version = "0.16.1" +version = "0.16.2" dependencies = [ "image", "serde_json", @@ -4124,7 +4124,7 @@ dependencies = [ [[package]] name = "solidcraft-derive" -version = "0.16.1" +version = "0.16.2" dependencies = [ "proc-macro2", "quote", @@ -4133,7 +4133,7 @@ dependencies = [ [[package]] name = "solidcraft-doc" -version = "0.16.1" +version = "0.16.2" dependencies = [ "log", "serde", @@ -4150,7 +4150,7 @@ dependencies = [ [[package]] name = "solidcraft-engine" -version = "0.16.1" +version = "0.16.2" dependencies = [ "log", "serde", @@ -4167,7 +4167,7 @@ dependencies = [ [[package]] name = "solidcraft-geom" -version = "0.16.1" +version = "0.16.2" dependencies = [ "serde", "serde_json", @@ -4176,7 +4176,7 @@ dependencies = [ [[package]] name = "solidcraft-gpu" -version = "0.16.1" +version = "0.16.2" dependencies = [ "log", "naga", @@ -4193,7 +4193,7 @@ dependencies = [ [[package]] name = "solidcraft-io" -version = "0.16.1" +version = "0.16.2" dependencies = [ "cadmpeg-core", "cadmpeg-ir", @@ -4213,7 +4213,7 @@ dependencies = [ [[package]] name = "solidcraft-kernel" -version = "0.16.1" +version = "0.16.2" dependencies = [ "log", "proptest", @@ -4233,7 +4233,7 @@ dependencies = [ [[package]] name = "solidcraft-mcp" -version = "0.16.1" +version = "0.16.2" dependencies = [ "serde_json", "solidcraft-engine", @@ -4242,7 +4242,7 @@ dependencies = [ [[package]] name = "solidcraft-render" -version = "0.16.1" +version = "0.16.2" dependencies = [ "image", "moxcms", @@ -4256,7 +4256,7 @@ dependencies = [ [[package]] name = "solidcraft-sketch" -version = "0.16.1" +version = "0.16.2" dependencies = [ "serde", "serde_json", @@ -4267,11 +4267,11 @@ dependencies = [ [[package]] name = "solidcraft-space-mouse" -version = "0.16.1" +version = "0.16.2" [[package]] name = "solidcraft-ui-egui" -version = "0.16.1" +version = "0.16.2" dependencies = [ "arboard", "egui", @@ -4296,7 +4296,7 @@ dependencies = [ [[package]] name = "solidcraft-web" -version = "0.16.1" +version = "0.16.2" dependencies = [ "eframe", "egui", @@ -5826,7 +5826,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7" [[package]] name = "xtask" -version = "0.16.1" +version = "0.16.2" dependencies = [ "serde_json", "sha2 0.10.9", diff --git a/Cargo.toml b/Cargo.toml index 6369851fe..8166209a4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,7 +5,7 @@ members = ["crates/*", "apps/*", "xtask"] exclude = ["vendor"] [workspace.package] -version = "0.16.1" +version = "0.16.2" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" From ed64988d8fa7cc7d99232ea946cfcdb9da153e7b Mon Sep 17 00:00:00 2001 From: NOWN-DEV <257771410+NOWN-DEV@users.noreply.github.com> Date: Mon, 19 Oct 2026 03:16:01 +0200 Subject: [PATCH 021/225] Joints: a round origin keeps its end when the face it opens onto gets other neighbours (#2760) A round origin's end is kept by the name of the face across the rim. On a face in pieces (a sheet split by a groove or a bend) that name lists the faces round the piece, and when those change (a hole nearby moves or goes) the name matched neither rim, so the end fell back to the nearer end of the stored pick: a pick near one end of a thin wall that the design moved past mid-wall turned a part through 180 degrees. The end whose rim matches the name better now wins: the face itself, a face merged into it, then a piece of it, then the same face by its stem. Co-authored-by: Claude Opus 5.5 (1M context) --- crates/doc/src/joints_face.rs | 36 ++++++++++++++-------- crates/engine/src/cmd/joints_face_tests.rs | 28 +++++++++++++++++ 2 files changed, 52 insertions(+), 12 deletions(-) diff --git a/crates/doc/src/joints_face.rs b/crates/doc/src/joints_face.rs index 9f1433288..9e142b915 100644 --- a/crates/doc/src/joints_face.rs +++ b/crates/doc/src/joints_face.rs @@ -10,6 +10,7 @@ use solidcraft_geom::Vec3; use solidcraft_kernel::CylinderFace; use super::{Snap, XRef, component_bodies}; +use crate::history_names::Match; use crate::{DocError, Document, IDENTITY, Mat, ModelBody, ModelState, Result, apply_point, apply_vector, mat_inverse}; /// Rim points sampled to find the face across a cylinder's rim. @@ -170,21 +171,32 @@ impl Round { pub(super) fn named_round(doc: &Document, st: &ModelState, pick: Vec3, face: &str, end: Option<&str>) -> Result> { let nf = named_face(doc, st, pick, face)?; let Some(own) = nf.own_cylinder() else { return Ok(None) }; - let chosen = end - .and_then(|name| { - let hits: Vec<(f64, f64)> = ends(&own) - .into_iter() - .filter(|(at, _)| rim_neighbour(nf.body, nf.face, &own, *at).is_some_and(|f| crate::name_lookup::face_has_name(nf.body, f, name))) - .collect(); - match hits[..] { - [one] => Some(one), - _ => None, - } - }) - .unwrap_or_else(|| end_by_pick(&nf, &own)); + let chosen = end.and_then(|name| end_named(nf.body, nf.face, &own, name)).unwrap_or_else(|| end_by_pick(&nf, &own)); Ok(Some(Round::at(placed(&nf.offset, own), chosen))) } +/// The end of cylinder `own` (face `face` of `b`) whose rim meets the face called `name` better +/// than the other end's rim does: the very face, or one merged into it, else a piece of it whose +/// neighbours have changed (the face round a hole in a sheet is told apart from its other pieces +/// by the faces around it, and those change when the hole moves). `None` when neither rim, or +/// both, meet it as well. +fn end_named(b: &ModelBody, face: usize, own: &CylinderFace, name: &str) -> Option<(f64, f64)> { + let names = crate::naming::names(b); + let how = |at: f64| { + let f = rim_neighbour(b, face, own, at)?; + if crate::name_lookup::legacy_name(name).is_some() { + return crate::name_lookup::face_has_name(b, f, name).then_some(Match::Exact); + } + crate::history_names::matches(&names, f, name) + }; + let [start, end] = ends(own); + match (how(start.0), how(end.0)) { + (s, e) if s > e => Some(start), + (s, e) if e > s => Some(end), + _ => None, + } +} + /// The x axis an x reference gives a frame at `o` with axis `z` (`None`: no reference). pub(super) fn x_axis(doc: &Document, st: &ModelState, x: Option<&XRef>, o: Vec3) -> Result> { Ok(match x { diff --git a/crates/engine/src/cmd/joints_face_tests.rs b/crates/engine/src/cmd/joints_face_tests.rs index a97e2694b..9ef057f72 100644 --- a/crates/engine/src/cmd/joints_face_tests.rs +++ b/crates/engine/src/cmd/joints_face_tests.rs @@ -265,3 +265,31 @@ fn origins_on_a_body_placed_by_an_offset_agree_named_or_not() { assert!(near(named.0, unnamed.0) && near(named.1, unnamed.1), "{named:?} {unnamed:?}"); assert!(near(named.0, at(Vec3::new(20.0, 20.0, 5.0))) && near(named.1, up), "{named:?}"); } + +#[test] +fn a_round_origin_keeps_its_end_when_the_face_it_opens_onto_gets_other_neighbours() { + // A plate `T` thick with a groove across its top (so the top face is in pieces, each named + // by the faces round it), a small hole and a 6 mm hole in the left piece. The origin is + // picked on the 6 mm hole's wall near the top, and names the top piece as its end. + let mut s = Session::default(); + run(&mut s, "parameters.change", json!({"name": "T", "expression": "2 mm"})); + run(&mut s, "component.create", json!({"name": "Plate"})); + run(&mut s, "solid.box", json!({"length": 60, "width": 100, "height": "T", "corner": [0, 0, 0]})); + run(&mut s, "solid.box", json!({"length": 4, "width": 100, "height": 1, "corner": [28, 0, "T - 1 mm"], "operation": "cut"})); + run(&mut s, "solid.hole", json!({"position": [10, 50, "T"], "diameter": 4})); + let small = s.doc.features.last().map_or(0, |f| f.id); + run(&mut s, "solid.hole", json!({"position": [20, 50, "T"], "diameter": 6})); + run(&mut s, "component.activate", json!({"component": "root"})); + run(&mut s, "joint.origin", json!({"occurrence": "Plate", "circle": [23, 50, 1.6], "name": "O"})); + let top = |s: &Session| { + let o = s.doc.assembly.origins.iter().find(|o| o.name == "O").map(|o| o.origin.clone()); + o.and_then(|o| solidcraft_doc::joints::resolve_origin(&s.doc, &s.model.state(), &o).ok()).map(|m| (m[3][2], m[2][2])) + }; + assert_eq!(top(&s), Some((2.0, 1.0))); + // Thicker, the pick is nearer the bottom; without the small hole the top piece is named by + // fewer faces. The origin stays on the top. + run(&mut s, "parameters.change", json!({"name": "T", "expression": "4 mm"})); + run(&mut s, "timeline.suppress", json!({"feature": small, "suppressed": true})); + let (z, dz) = top(&s).unwrap_or_default(); + assert!((z - 4.0).abs() < 1e-9 && (dz - 1.0).abs() < 1e-9, "{z} {dz}"); +} From 9ee2de9a0f3a888d51107a7d38379fa1114afea4 Mon Sep 17 00:00:00 2001 From: fkirill Date: Mon, 19 Oct 2026 04:16:06 +0300 Subject: [PATCH 022/225] Fix drilled hole cuts through tapered walls (#2387) (#2401) Rebase the complete PR change onto current main, preserving changes previously stored in merge commits. --- crates/engine/src/hole_face_tests.rs | 52 ++++++++++ crates/kernel/src/boolean_diagnostics.rs | 3 + crates/kernel/src/ops.rs | 10 ++ crates/kernel/src/tool_reseam.rs | 124 +++++++++++++++++++++++ tests/robustness/goldens.json | 6 +- 5 files changed, 193 insertions(+), 2 deletions(-) create mode 100644 crates/kernel/src/tool_reseam.rs diff --git a/crates/engine/src/hole_face_tests.rs b/crates/engine/src/hole_face_tests.rs index 9f026ba43..43d6499e1 100644 --- a/crates/engine/src/hole_face_tests.rs +++ b/crates/engine/src/hole_face_tests.rs @@ -322,3 +322,55 @@ fn sketch_floating_in_the_gap_touching_neither_still_drills_down() { near(base - volume(&mut s), pi() * 25.0 * 4.0); assert!(!solid_at(&s, 20.0, 20.0, 4.0) && solid_at(&s, 20.0, 20.0, 16.0)); } + +/// #2387: a drill point crossing the sloping back of a wall must leave a real hole. +#[test] +fn drilled_sketch_points_break_through_a_sloping_back_face() { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": {"origin": [0, 0, 0], "x_dir": [1, 0, 0], "y_dir": [0, 0, 1]}, "name": "Wall"})); + run(&mut s, "sketch.line", json!({"points": [[0, 0], [15, 0], [15, 30], [7.5, 30], [0, 0]]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"sketch": "Wall", "distance": 40, "direction": "negative"})); + run(&mut s, "sketch.create", json!({"plane": {"origin": [15, 0, 0], "x_dir": [0, 1, 0], "y_dir": [0, 0, 1]}, "name": "Pts"})); + run(&mut s, "sketch.line", json!({"points": [[5, 16], [10, 16]], "ids": ["l10"]})); + run(&mut s, "sketch.point", json!({"point": [30, 16], "id": "p12"})); + run(&mut s, "sketch.finish", json!({})); + run( + &mut s, + "solid.hole", + json!({"sketch": "Pts", "points": ["l10.end", "p12"], "depth": "10 mm", "diameter": "5 mm", "type": "drilled", "tip_angle": "118 deg", "name": "H"}), + ); + let id = s.doc.find_feature("H").unwrap().id; + let result = s.model.result(id).unwrap(); + assert!(result.error.is_none()); + assert!(result.boolean_diagnostics.unverified().is_none()); + // The cylindrical bore and cone, less the oblique conical cap outside x = z/4. + let r = 2.5; + let k = 59f64.to_radians().tan(); + let tip = r / k; + let outside = 4.0 - (5.0 - tip); + let cap = pi() * k * k * outside.powi(3) / (3.0 * (1.0 - (k / 4.0).powi(2)).powf(1.5)); + let expected = 2.0 * (pi() * r * r * (10.0 + tip / 3.0) - cap); + let left = volume(&mut s); + // The measured curved faces are tessellated; 0.05 mm³ is 0.013% of the removed material. + assert!((13_500.0 - left - expected).abs() < 0.05, "removed {} vs {expected}", 13_500.0 - left); + assert_eq!(s.model.state().bodies.len(), 1); + for b in &s.model.state().bodies { + assert!(b.body.validity().is_empty()); + assert_eq!(b.body.shell_count(), 1); + } + for y in [10.0, 30.0] { + assert!(!solid_at(&s, 10.0, y, 16.0), "bore at y = {y}"); + assert!(!solid_at(&s, 4.2, y, 16.0), "tip breaks through at y = {y}"); + assert!(solid_at(&s, 10.0, y + 3.0, 16.0), "material beside the bore at y = {y}"); + } + let saved = s.doc.to_json(); + run(&mut s, "edit.undo", json!({})); + near(volume(&mut s), 13_500.0); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.doc.to_json(), saved); + near(volume(&mut s), left); + let mut reopened = Session::new(solidcraft_doc::Document::from_json(&saved).unwrap()); + assert!(reopened.model.result(id).unwrap().error.is_none()); + near(volume(&mut reopened), left); +} diff --git a/crates/kernel/src/boolean_diagnostics.rs b/crates/kernel/src/boolean_diagnostics.rs index e12e407e4..dc3e0100e 100644 --- a/crates/kernel/src/boolean_diagnostics.rs +++ b/crates/kernel/src/boolean_diagnostics.rs @@ -18,6 +18,8 @@ pub enum BooleanStrategy { GrownBoss, PlanarFallback, ToolNudge, + /// A rotationally symmetric tool turned about its own axis; its volume is unchanged. + ToolReseam, Piecewise, /// No retry gave a result, and the answer from sample points was kept although the bodies' /// facetings disagree with it. @@ -61,6 +63,7 @@ impl BooleanFallback { BooleanStrategy::GrownBoss => format!("boss grown {:.6e} mm into the material around the bore it fills", self.face_shift_mm), BooleanStrategy::PlanarFallback => "exact planar fallback (no displacement)".into(), BooleanStrategy::ToolNudge => format!("tool displacement {:.6e} mm, rotation {:.6e} rad", self.translation_mm, self.rotation_rad), + BooleanStrategy::ToolReseam => format!("axisymmetric tool reseamed by {:.6e} rad (no displacement)", self.rotation_rad), BooleanStrategy::Piecewise => "piecewise retry (no displacement)".into(), BooleanStrategy::UnverifiedShortcut => format!( "not verified: the bodies' facets pass through each other by more than {:.6e} mm, but they could not be intersected there; that part is ignored", diff --git a/crates/kernel/src/ops.rs b/crates/kernel/src/ops.rs index 08512db65..8433beb15 100644 --- a/crates/kernel/src/ops.rs +++ b/crates/kernel/src/ops.rs @@ -15,6 +15,9 @@ use crate::{KernelError, Result, guard, record}; #[path = "bore_union_tests.rs"] mod bore_union_tests; +#[path = "tool_reseam.rs"] +mod tool_reseam; + #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum BoolOp { @@ -572,6 +575,13 @@ fn boolean_untimed(a: &Body, b: &Body, op: BoolOp) -> Result> { } } let r = boolean_via(a, b, op, &boolean_whole); + if r.is_err() + && op == BoolOp::Cut + && !APART.with(|c| c.get()) + && let Some(result) = tool_reseam::cut(a, b) + { + return Ok(Some(result)); + } if r.is_ok() || !crate::tangent_cylinders::needed(a, b) { return r; } diff --git a/crates/kernel/src/tool_reseam.rs b/crates/kernel/src/tool_reseam.rs new file mode 100644 index 000000000..e0c09776c --- /dev/null +++ b/crates/kernel/src/tool_reseam.rs @@ -0,0 +1,124 @@ +//! Retry a failed cut with different boundaries between a round tool's faces (#2387). +//! Every curved support must be a revolution about the same axis and every planar support +//! perpendicular to it. Turning this closed solid about that axis changes only its seams. + +use solidcraft_geom::Vec3; +use truck_modeling::{self as mt, InnerSpace, Transform}; + +use super::{BoolOp, boolean_via, boolean_whole, nudged, transform}; +use crate::body::{Body, from_p3}; +use crate::boolean_diagnostics::{BooleanFallback, BooleanStrategy, capture_boolean_diagnostics, merge, record}; +use crate::{guard, record}; + +thread_local! { + static ACTIVE: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Exact revolution axes, rather than a fit to sampled normals: splines and affine +/// distortions of round tools must never be mistaken for rotational symmetry. +fn axis(body: &Body) -> Option<(Vec3, Vec3)> { + if body.is_mesh() || body.shell_count() != 1 || body.face_count() > 64 { + return None; + } + guard("round tool axis", || { + let mut axes = Vec::new(); + let mut normals = Vec::new(); + for face in body.solid.face_iter() { + match face.surface() { + mt::Surface::Plane(p) => { + let n = p.normal(); + let Some(n) = Vec3::new(n.x, n.y, n.z).normalized() else { return Ok(None) }; + normals.push(n); + } + mt::Surface::RevolutedCurve(s) => { + let m = s.transform(); + let (x, y, z) = (m.x.truncate(), m.y.truncate(), m.z.truncate()); + // Only rigid transforms: no elliptic scaling of the revolution. + if [x, y, z].iter().any(|v| (v.magnitude2() - 1.0).abs() > 1e-9) + || [x.dot(y), x.dot(z), y.dot(z)].iter().any(|v| v.abs() > 1e-9) + || m.x.w != 0.0 + || m.y.w != 0.0 + || m.z.w != 0.0 + || m.w.w != 1.0 + { + return Ok(None); + } + let o = from_p3(m.transform_point(s.entity().origin())); + let a = m.transform_vector(s.entity().axis()); + let Some(a) = Vec3::new(a.x, a.y, a.z).normalized() else { return Ok(None) }; + axes.push((o, a)); + } + _ => return Ok(None), + } + } + let Some(&(o, a)) = axes.first() else { return Ok(None) }; + let tol = (body.size() * 1e-9).max(1e-10); + let same = axes.iter().all(|(p, d)| a.cross(*d).len() < 1e-9 && (*p - o).cross(a).len() < tol); + // Surface orientation can reverse the same axis. Choose a stable direction for retries. + let first = [a.x, a.y, a.z].into_iter().find(|v| v.abs() > 1e-9).unwrap_or(1.0); + let a = if first < 0.0 { -a } else { a }; + Ok((same && normals.iter().all(|n| n.cross(a).len() < 1e-9)).then_some((o, a))) + }) + .ok() + .flatten() +} + +pub(super) fn cut(target: &Body, tool: &Body) -> Option { + if ACTIVE.with(|a| a.get()) { + return None; + } + let (origin, axis) = axis(tool)?; + ACTIVE.with(|a| a.set(true)); + let result = guard("cut with reseamed tool", || { + let counts = record::counts(&[target, tool]); + // Bounded exact retries. Keep the original error if neither can be verified. + for angle in [0.3, -0.3, 0.7, -0.7] { + let turned = transform(tool, Vec3::ZERO, origin, axis, angle)?; + let (result, diagnostics) = capture_boolean_diagnostics(|| boolean_via(target, &turned, BoolOp::Cut, &boolean_whole)); + if let Ok(Some(body)) = result + && crate::boolean_guard::check_retry(target, tool, BoolOp::Cut, Some(&body)).is_ok() + { + let body = nudged(body, &turned, &counts); + merge(diagnostics); + let mut event = BooleanFallback::new(BooleanStrategy::ToolReseam); + event.rotation_rad = angle; + record(event); + return Ok(Some(body)); + } + } + Ok(None) + }) + .ok() + .flatten(); + ACTIVE.with(|a| a.set(false)); + result +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::transform_matrix; + use solidcraft_geom::{Loop2, Plane, Region2, Vec2}; + + fn drill(angle: f64) -> Body { + let profile = + Region2 { outer: Loop2::polygon(&[Vec2::new(0., 1.), Vec2::new(2.5, 1.), Vec2::new(2.5, -10.), Vec2::new(0., -11.5)]), holes: vec![] }; + crate::revolve(&Plane::XZ, &[profile], Vec2::ZERO, Vec2::Y, angle).unwrap().pop().unwrap() + } + + #[test] + fn only_complete_coaxial_revolutions_can_be_reseamed() { + let tool = drill(std::f64::consts::TAU); + assert!(axis(&tool).is_some()); + let placed = transform(&tool, Vec3::new(11., -7., 5.), Vec3::ZERO, Vec3::new(1., 2., 3.), 0.8).unwrap(); + let (o, a) = axis(&placed).unwrap(); + let turned = transform(&placed, Vec3::ZERO, o, a, 0.3).unwrap(); + assert!((crate::measure(&placed).unwrap().volume - crate::measure(&turned).unwrap().volume).abs() < 1e-6); + // A partial turn's radial caps would move; an affine scale can make the bore elliptic. + assert!(axis(&drill(std::f64::consts::PI)).is_none()); + let scaled = transform_matrix(&tool, [[2., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]]).unwrap(); + assert!(axis(&scaled).is_none()); + let block = crate::box_solid(Vec3::ZERO, Vec3::new(10., 20., 30.)).unwrap(); + assert!(axis(&block).is_none()); + } +} diff --git a/tests/robustness/goldens.json b/tests/robustness/goldens.json index d1fe22461..56d799e33 100644 --- a/tests/robustness/goldens.json +++ b/tests/robustness/goldens.json @@ -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":7885.256491,"bodies":1,"edges":66,"error":"offset: a corner whose faces don't meet the same way after t","faces":28,"outcome":"failed","rejected":0,"shells":3,"steps":["extruded profile","join cylinder","join cylinder","circular pattern","rectangular pattern","shell"],"unsupported":2,"volume":21498.10695}, + "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}, "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}, @@ -140,6 +140,8 @@ {"platform":"windows","reason":"Independently reproduced on unmodified main 1e984c8e on Windows; the extrusion branch produces the same values. Shared references and tolerances remain unchanged.","seeds":[1,23,34,67]}, {"platform":"windows","reason":"Seed 94 independently reproduced on unmodified main c5992386 on Windows after the extrusion rebase: the same steps, outcome and geometry values as the rebased branch. Shared references and tolerances remain unchanged.","seeds":[94]}, {"reason":"#2064 (multi-profile extrusion) merges coplanar faces the boolean used to leave split. Seed 67 has one face/two edges fewer from its first cut on, at the same volume at every step; seed 94's last box cut leaves one face/two edges more, same volume and area. Seed 13's second cylinder cut leaves 35 faces/84 edges instead of 37/88 at the same volume, so its random fillet (edges picked by index) rounds different edges: 2688.99 instead of 2675.18 mm3 after the fillet; the hole after it removes the same 278.2 mm3. Every step passes the validity and volume-direction checks. Pull request CI ran only every 8th seed, so main was the first run to see these.","seeds":[13,67,94]}, - {"reason":"#2247: a cut no longer splits the separate pieces of a body into bodies of their own, so these seeds keep one body (bodies N -> 1). The generator looks at the model, so after the first such cut some seeds build different steps: seed 33 joins and patterns a box instead of chamfering (volume 13858 -> 24911 mm3), seed 18 now builds (its hole pattern failed with no result), and seed 54 picks a shell that fails the same way on main before #2247 (offset corner). Every step passes the validity and volume-direction checks.","seeds":[7,9,12,16,18,22,27,31,33,45,50,54,67,72,81,93]} + {"reason":"#2247: a cut no longer splits the separate pieces of a body into bodies of their own, so these seeds keep one body (bodies N -> 1). The generator looks at the model, so after the first such cut some seeds build different steps: seed 33 joins and patterns a box instead of chamfering (volume 13858 -> 24911 mm3), seed 18 now builds (its hole pattern failed with no result), and seed 54 picks a shell that fails the same way on main before #2247 (offset corner). Every step passes the validity and volume-direction checks.","seeds":[7,9,12,16,18,22,27,31,33,45,50,54,67,72,81,93]}, + {"reason":"Reseam rotationally symmetric drill cutters after failed cuts (#2387): seed 86 now drills its hole, so its following pattern, shell and sphere cut complete with the fuzz validity and material checks.","seeds":[86]}, + {"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]} ] } From 9eb1540a3449a16773438eb60561e833213e9895 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Sun, 18 Oct 2026 21:16:11 -0400 Subject: [PATCH 023/225] Docs: describe SolidCraft as independent CAD (#2768) Reword comments, docs and package descriptions so they describe SolidCraft's own behaviour instead of comparing it to another product. The trademark notice, the commercial-CAD rule and the navigation preset name stay as they were. Co-authored-by: Claude Sonnet 5.5 --- README.md | 2 +- ROADMAP.md | 2 +- apps/solidcraft-cli/tests/design_corpus.rs | 2 +- .../linux/ai.storyteller.solidcraft.metainfo.xml.in | 2 +- assets/shaders/viewport.wgsl | 2 +- crates/doc/src/canvas.rs | 2 +- crates/doc/src/construct.rs | 2 +- crates/doc/src/document.rs | 8 ++++---- crates/doc/src/expr.rs | 2 +- crates/doc/src/format.rs | 2 +- crates/doc/src/sheet.rs | 4 ++-- crates/engine/src/cmd/inspect.rs | 2 +- crates/engine/src/cmd/sketch.rs | 2 +- crates/engine/src/cmd/sketch_corner_tests.rs | 2 +- crates/engine/src/cmd/sketch_modify.rs | 2 +- crates/engine/src/cmd/sketch_project.rs | 2 +- crates/engine/src/cmd/sketch_robust_tests.rs | 2 +- crates/engine/src/lib.rs | 2 +- crates/engine/src/split_face_tests.rs | 2 +- crates/engine/src/tests.rs | 2 +- crates/engine/src/tests/robustness.rs | 2 +- crates/engine/src/view.rs | 2 +- crates/kernel/src/heal.rs | 2 +- crates/kernel/src/helix.rs | 2 +- crates/kernel/src/step_in/geom.rs | 2 +- crates/kernel/src/step_in/mod.rs | 2 +- crates/kernel/src/step_in/tests.rs | 2 +- crates/kernel/src/tests.rs | 2 +- crates/kernel/src/topo.rs | 2 +- crates/mcp/src/server.rs | 4 ++-- crates/sketch/src/model.rs | 2 +- crates/ui-egui/src/context_menu.rs | 2 +- crates/ui-egui/src/dialogs.rs | 2 +- crates/ui-egui/src/dialogs_assembly.rs | 2 +- crates/ui-egui/src/dialogs_assembly_tests.rs | 2 +- crates/ui-egui/src/dialogs_motion.rs | 2 +- crates/ui-egui/src/drag_snap.rs | 2 +- crates/ui-egui/src/inference.rs | 2 +- crates/ui-egui/src/lib.rs | 4 ++-- crates/ui-egui/src/menu_tests.rs | 2 +- crates/ui-egui/src/navigation.rs | 2 +- crates/ui-egui/src/prefs.rs | 2 +- crates/ui-egui/src/preselect_tests.rs | 2 +- crates/ui-egui/src/sketch_tools.rs | 4 ++-- crates/ui-egui/src/toolbar.rs | 2 +- crates/ui-egui/src/workspace.rs | 2 +- docs/plugins.md | 2 +- docs/robustness.md | 4 ++-- packaging/linux/nfpm.yaml | 2 +- 49 files changed, 57 insertions(+), 57 deletions(-) diff --git a/README.md b/README.md index 8eee5d8a9..94386e1ad 100644 --- a/README.md +++ b/README.md @@ -311,7 +311,7 @@ configuration and an example session: [docs/mcp.md](docs/mcp.md). ## Contributing -Coming from Autodesk Fusion? SolidCraft uses familiar parametric CAD workflows: constrained +SolidCraft uses a familiar parametric CAD workflow: constrained sketches, solid features, an editable timeline, parameters and assemblies. See the [roadmap](ROADMAP.md) for supported operations and current limitations. diff --git a/ROADMAP.md b/ROADMAP.md index e3ebd3811..f82dea99b 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -55,7 +55,7 @@ PCB / Package, Render, Animation, Simulation, Manufacture/CAM, Drawings. | M7 | Thin extrude (walls along open or closed curves: centre, inside, outside or two sides; mitred corners, crossing walls joined; #721), sweep, loft (incl. to a point), rib and web (to next / depth), emboss (planar faces and exact radial emboss/deboss of bounded orthogonal profiles on complete exterior cylinders/sleeves), thread (cosmetic, and modelled M3–M20 outside and inside: the ISO profile screwed in as a faceted cut), coil (smooth B-spline helical walls), pipe, pattern on path, patterns of bodies and components, replace face (parallel), align, remove, feature copy/paste: done. Unique eligible cylindrical targets are inferred for new Emboss features. Left: general curved-face emboss and exact (unfaceted) modelled threads | in progress | 12 | | M8 | Surface workspace (#772). Done: Patch (sketch regions; edge loops filled G0, plus `crown`), Stitch, Thicken (planes and cylinders), Extend (straight edges of planar surfaces), Trim (by a plane or a face), Delete Face (healing), Boundary Fill, zebra/draft/curvature-map analysis, Surface Extrude/Revolve/Sweep/Loft from open and closed curves, Offset, Unstitch and Reverse Normal; the continuity-driven core (`kernel/src/bridge.rs`, G0–G3 Hermite rows) with **Blend** (`surface.blend`, #764), **Match** (`surface.match`), **Boundary** (`surface.boundary`, #763 — two sketch curves exact with G0–G3, three or four as the flat patch of their loop, and curve networks: Coons and Gordon surfaces through sketch, 3D-sketch or edge curves, a point for a three-sided side, G1/G2 against the faces along one direction's edges, joined into their body on request; G1/G2 on two sides that meet at a corner waits for the Gregory-type corner), **Fair** (`surface.fair`, CV fairing), **continuity analysis** (`inspect.continuity`, #770; a toolbar tool with edge markers and a legend, and curvature combs along face isocurves) and a multi-section **loft** with per-end continuity and crown. Also in the Class-A pass: G1…G4 blend curves in the sketch, chord and variable-radius fillets on curved edges (with honest refusals where the fit cannot hold), and a G2 corner patch where filleted edges meet (kernel; the command refuses until the patch's sections can be sewn to the blends' contacts). Left: bias/form-factor fillet sections (design recorded), a Gregory-type corner, surface Fillet between separate surface bodies (#769), Ruled (#762), Untrim (#761), curved-face Extend (#760), loft guide rails (#201; sweep guide rails and two-rail sweeps are done, #771), and every remaining #757–#772 item | deferred | — | | M9 | Components and assemblies: New Component / Create Components from Bodies, active component, per-component origin/bodies/sketches/timeline entries, occurrences with transforms, Copy/Paste vs Paste New, nested Browser tree with visibility and isolate; Ground, Move/Copy of occurrences, joints (rigid, revolute, slider, cylindrical, pin-slot, planar, ball) by joint origins with limits and Drive Joints, closed kinematic loops (four-bar, slider-crank: the loop's other joints follow the driven one on its branch, and driving stops where a loop can no longer close), cams (`joint.cam`: a revolute cam drives a slider or revolute follower along a closed sketch profile or the cam's edges, knife, roller or flat followers, worked out again when the profile changes; drives, studies, closed loops, contact sets), As-built Joint, Rigid Group, Contact Sets (driving and motion studies stop where bodies in a set would pass through each other), Motion Study (joint values keyed along a timeline, playback, export of occurrence positions as JSON/CSV), motion analysis (joint values and a point's path charted over a study as value, velocity and acceleration; the parts that collide along a study, with the steps where they do), Exploded views (automatic or by hand, shown without changing placements); interference, per-component physical properties; STEP with assembly structure; URDF export for robot simulators (links with meshes, mass and inertia; joint chains whose values match Drive Joints; docs/urdf.md). Physical properties now measure material-aware component/occurrence placements, descendants and repeated instances, including pending moves and body reassignment offsets; contact geometry and automatic exploded centres respect those offsets. Groundwork done: component tree, occurrences with transforms (instances, Paste New), world placement, active component as authoring frame, ground, Capture/Revert Position, moving bodies and sketches. UI: ASSEMBLE panel dialogs for New Component, Joint (snaps on faces, edges, circles and vertices; animated motion preview; offsets, flip, limits), As-built Joint, Joint Origin, Rigid Group, Drive Joints (live slider), Motion Link, Cam and Interference (overlaps shown red); joints in the timeline and the Browser | in progress | 32 | -| M10 | Sheet metal: flange (base, edge, contour), hem, unfold/refold, convert, flat pattern + DXF, rules: done. PLASTIC enclosure subset: Boss, Rib, Web, Lip/Groove, Snap Fit, Rest, Plastic Rules (library, edit, assign; rule draft and clearance as feature defaults): done, tested against hand-computed geometry. UI: SHEET METAL and PLASTIC tabs in Fusion's layout with dialogs (live preview, Edit Feature, pre-selection) for Flange, Hem, Unfold/Refold, Convert, Sheet Metal Rules, Create Flat Pattern (flat view with bend lines, bend table CSV/JSON and DXF export with exact circle/arc/line cutouts), Boss, Lip/Groove, Snap Fit, Rest, Manage and Assign Plastic Rules; Fold (bend along a sketch line); flanges meeting at a corner closed at any angle with the rule's gap; edge flanges with their own angle and height per edge in one feature; corner reliefs (notch, round, rectangular, tear) chosen by the rule; Convert to Sheet Metal from a solid or shelled body by its bend edges (flat faces, sharp bends) | in progress | 36 | +| M10 | Sheet metal: flange (base, edge, contour), hem, unfold/refold, convert, flat pattern + DXF, rules: done. PLASTIC enclosure subset: Boss, Rib, Web, Lip/Groove, Snap Fit, Rest, Plastic Rules (library, edit, assign; rule draft and clearance as feature defaults): done, tested against hand-computed geometry. UI: SHEET METAL and PLASTIC tabs with dialogs (live preview, Edit Feature, pre-selection) for Flange, Hem, Unfold/Refold, Convert, Sheet Metal Rules, Create Flat Pattern (flat view with bend lines, bend table CSV/JSON and DXF export with exact circle/arc/line cutouts), Boss, Lip/Groove, Snap Fit, Rest, Manage and Assign Plastic Rules; Fold (bend along a sketch line); flanges meeting at a corner closed at any angle with the rule's gap; edge flanges with their own angle and height per edge in one feature; corner reliefs (notch, round, rectangular, tear) chosen by the rule; Convert to Sheet Metal from a solid or shelled body by its bend edges (flat faces, sharp bends) | in progress | 36 | | M11 | 2D drawings | deferred | — | | M12 | Release: cross-platform packages, verification and deliberate publication implemented; original current-UI demo refreshed. Trusted distribution signing and broader performance work remain | in progress | 16 | | M14 | Configurations: a table of rows (parameter expressions and feature suppressions per row) switched with config.activate (undoable, all or nothing), kept through parameter renames and feature deletes (config.configure, config.table, config.column/row/activate). Per-row body materials and appearances (library looks, custom colour/opacity and clearing overrides), undoable activation and save/reopen: done. Ordered typed configuration rules, atomic validation and structured rule editing: done. Component appearance and certified semantic face style columns, atomic preview/apply and independent-copy remapping: done. Exact constructed sketch-side and immutable imported-face lineage now preserve legacy names and reject retargeting. Left: ambiguous shifted/two-sided caps | in progress | 4 | diff --git a/apps/solidcraft-cli/tests/design_corpus.rs b/apps/solidcraft-cli/tests/design_corpus.rs index 2931be745..0e0bdc9d1 100644 --- a/apps/solidcraft-cli/tests/design_corpus.rs +++ b/apps/solidcraft-cli/tests/design_corpus.rs @@ -27,7 +27,7 @@ const KNOWN: [(&str, &str, &str); 2] = [ ( "m0-revolve-primitives", "Body1 bbox", - "partial revolves turn toward the sketch normal since ac43365 (as Fusion's do); M0 turned them the other way", + "partial revolves turn toward the sketch normal since ac43365 (as most parametric CAD tools do); M0 turned them the other way", ), ("components-arm", "body_count", "Measure counted only the root component's bodies then; it measures every placed body now"), ]; diff --git a/assets/platforms/linux/ai.storyteller.solidcraft.metainfo.xml.in b/assets/platforms/linux/ai.storyteller.solidcraft.metainfo.xml.in index 169907fb0..ef9b2c237 100644 --- a/assets/platforms/linux/ai.storyteller.solidcraft.metainfo.xml.in +++ b/assets/platforms/linux/ai.storyteller.solidcraft.metainfo.xml.in @@ -6,7 +6,7 @@ CC0-1.0 MIT OR Apache-2.0 SolidCraft - Parametric 3D CAD in the style of Fusion + Independent parametric 3D CAD SolidCraft contributors diff --git a/assets/shaders/viewport.wgsl b/assets/shaders/viewport.wgsl index 4842fbe1f..1c46be0a9 100644 --- a/assets/shaders/viewport.wgsl +++ b/assets/shaders/viewport.wgsl @@ -119,7 +119,7 @@ fn solid(i: TOut, front: bool) -> vec4 { let fw = fwidth(ndv); if (clipped(i.wp)) { discard; } if (!front && length(u.clip.xyz) > 0.5) { - // The cut face in its body's colour (as Fusion's "from component"), tinted toward the + // The cut face in its body's colour ("from component" colouring), tinted toward the // cap colour so it reads as a cut, hatched at 45 degrees on screen. let base = mix(i.c.rgb, u.cap.rgb, 0.35); let h = fract((i.pos.x + i.pos.y) / 9.0); diff --git a/crates/doc/src/canvas.rs b/crates/doc/src/canvas.rs index 6955a01fe..e3f3de5bb 100644 --- a/crates/doc/src/canvas.rs +++ b/crates/doc/src/canvas.rs @@ -1,4 +1,4 @@ -//! Canvases: reference images placed on a plane (Fusion's Insert Canvas), kept in the design. +//! Canvases: reference images placed on a plane (Insert Canvas), kept in the design. //! The image bytes travel inside the design file (base64), so it reopens without the original. use serde::{Deserialize, Serialize}; diff --git a/crates/doc/src/construct.rs b/crates/doc/src/construct.rs index 5940eab9e..e0adabbf2 100644 --- a/crates/doc/src/construct.rs +++ b/crates/doc/src/construct.rs @@ -1,6 +1,6 @@ //! Construction geometry from the model: references to vertices, edges, faces, planes, axes, //! points and sketch entities, resolved on each evaluation, and the axes, points and planes -//! built from them (Fusion's CONSTRUCT panel). +//! built from them (the CONSTRUCT panel). //! //! Face and edge references carry the persistent name of what was picked (see `naming`), so //! they follow the model when earlier features change; the picked point is the fallback. diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 72970d4c2..9b5a400ec 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -812,11 +812,11 @@ pub enum FeatureKind { #[serde(default, skip_serializing_if = "Option::is_none")] line: Option, }, - /// A construction axis (Fusion's CONSTRUCT axes). + /// A construction axis (CONSTRUCT axes). ConstructionAxis { def: AxisDef, }, - /// A construction point (Fusion's CONSTRUCT points). + /// A construction point (CONSTRUCT points). ConstructionPoint { def: PointDef, }, @@ -2065,7 +2065,7 @@ impl FeatureKind { ) } - /// Fusion-like type name (timeline tooltip, `inspect`). + /// Short type name (timeline tooltip, `inspect`). pub fn type_name(&self) -> &'static str { match self { FeatureKind::BodyTransfer { .. } => "BodyTransferFeature", @@ -3273,7 +3273,7 @@ impl Document { } } -/// Density of the default material (g/cm³), as Fusion's default. +/// Density of the default material (g/cm³), as the default. #[path = "../../../assets/materials/library.rs"] mod materials; pub use materials::{DEFAULT_DENSITY, MATERIALS, material_color}; diff --git a/crates/doc/src/expr.rs b/crates/doc/src/expr.rs index 95f3958fe..1ccb44018 100644 --- a/crates/doc/src/expr.rs +++ b/crates/doc/src/expr.rs @@ -395,7 +395,7 @@ fn lex_spans(s: &str) -> Result, DocError> { out.push((Tok::Op('-'), at(i), at(i + 1))); i += 1; } else if c == ';' { - // Fusion separates function arguments with `;` in some locales. + // Some CAD tools separate function arguments with `;` in some locales. out.push((Tok::Op(','), at(i), at(i + 1))); i += 1; } else if "+-*/^(),%".contains(c) { diff --git a/crates/doc/src/format.rs b/crates/doc/src/format.rs index 759200427..43fd8af5c 100644 --- a/crates/doc/src/format.rs +++ b/crates/doc/src/format.rs @@ -16,7 +16,7 @@ //! - 5: joins, cuts and intersects change only their own component's bodies unless bodies are //! named as `participants`; older features in designs with components get `participants: //! ["*"]` (every body), which is what they did, so those designs keep their shape. -//! - 4: joint origins mate by default (B's z against A's, as Fusion does); `flip` now means +//! - 4: joint origins mate by default (B's z against A's); `flip` now means //! "don't mate". Older joints keep their placement: their `flip` is inverted. //! - 6: XZ origin planes use sketch y = -Z and normal +Y. Older XZ references become //! explicit planes retaining their previous axes, including offset-plane expressions. diff --git a/crates/doc/src/sheet.rs b/crates/doc/src/sheet.rs index f72a3dee9..f209d20f8 100644 --- a/crates/doc/src/sheet.rs +++ b/crates/doc/src/sheet.rs @@ -290,7 +290,7 @@ fn rule_hem_gap() -> String { } impl SheetRule { - /// Fusion's default: Steel (mm), 2.5 mm, K 0.44, bend radius = Thickness. + /// Default: Steel (mm), 2.5 mm, K 0.44, bend radius = Thickness. pub fn steel() -> SheetRule { SheetRule { name: "Steel (mm)".into(), @@ -1989,7 +1989,7 @@ impl SheetBody { .sum() } - /// Topology counted as Fusion does: a round hole is one face bounded by two closed circular + /// Topology counted by faces and loops: a round hole is one face bounded by two closed circular /// edges (one vertex each), where the sewn solid splits it into arcs. Returns the change to /// the sewn (faces, edges, vertices). pub fn round_hole_correction(&self) -> (i64, i64, i64) { diff --git a/crates/engine/src/cmd/inspect.rs b/crates/engine/src/cmd/inspect.rs index 1d2159579..6b02a84a6 100644 --- a/crates/engine/src/cmd/inspect.rs +++ b/crates/engine/src/cmd/inspect.rs @@ -88,7 +88,7 @@ fn measure(s: &mut Session, p: &Value) -> Result { if !want.is_empty() && bodies.len() != want.len() { return Err(bad("inspect.measure", "unknown body name")); } - // Sheet metal keeps the edges where bends meet flat faces (as Fusion does): count its + // Sheet metal keeps the edges where bends meet flat faces (so bends stay visible): count its // B-rep faces as they are, without merging coplanar neighbours. let sheets = s.model.state().sheets.clone(); for b in &mut bodies { diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rs index 504f18381..a9b6ec59d 100644 --- a/crates/engine/src/cmd/sketch.rs +++ b/crates/engine/src/cmd/sketch.rs @@ -1435,7 +1435,7 @@ fn keep_size(sk: &Sketch, e: Ent) -> Vec { } } -/// Satisfy a just-added constraint the way Fusion applies it: the first-picked entities stay +/// Satisfy a just-added constraint the way a dimensional-constraint tool applies it: the first-picked entities stay /// put and only the second moves (first keeping its size, so it turns and slides, then also /// resizing). /// If the second can't move (fixed, projected or fully determined), the first moves instead; diff --git a/crates/engine/src/cmd/sketch_corner_tests.rs b/crates/engine/src/cmd/sketch_corner_tests.rs index a6e6214e4..9c58a85f9 100644 --- a/crates/engine/src/cmd/sketch_corner_tests.rs +++ b/crates/engine/src/cmd/sketch_corner_tests.rs @@ -166,7 +166,7 @@ fn filleting_a_side_keeps_its_original_midpoint() { /// The spout of a basin: a vertical riser and a horizontal top, the top's length dimensioned /// to the corner and the corner's height dimensioned from the origin. Filleting the corner used /// to drop the height and leave the length on the shortened straight part, so the top came out -/// a fillet radius too long. Like Fusion, the corner now stays as a virtual sharp corner (a point +/// a fillet radius too long. The corner now stays as a virtual sharp corner (a point /// on both lines' extensions) and the dimensions measure to it. #[test] fn a_fillet_keeps_the_dimensions_of_its_corner_on_a_virtual_sharp() { diff --git a/crates/engine/src/cmd/sketch_modify.rs b/crates/engine/src/cmd/sketch_modify.rs index cd9eeaf26..3db6db052 100644 --- a/crates/engine/src/cmd/sketch_modify.rs +++ b/crates/engine/src/cmd/sketch_modify.rs @@ -638,7 +638,7 @@ struct CornerKept { /// when anything measures to it: a constraint or dimension on the point, the length of either /// line, or it is the origin or still ends another curve. It stays as a virtual sharp corner, /// held on both curves' extensions (their intersection), and the line lengths become distances -/// from the far end to it, so the part keeps its size, as in Fusion. Otherwise None: the +/// from the far end to it, so the part keeps its size. Otherwise None: the /// caller removes the point. fn keep_corner(sk: &mut Sketch, c: usize, [(ca, na), (cb, nb)]: [(usize, usize); 2]) -> Result> { let used = sk.curves.iter().any(|x| uses(x, c)); diff --git a/crates/engine/src/cmd/sketch_project.rs b/crates/engine/src/cmd/sketch_project.rs index 54b13d316..07a3ee923 100644 --- a/crates/engine/src/cmd/sketch_project.rs +++ b/crates/engine/src/cmd/sketch_project.rs @@ -550,7 +550,7 @@ pub(super) fn project_internal_faces(s: &mut Session, id: u64, body: &str, indic Ok(links) } -/// Project the edges of the face a new sketch was created on (Fusion's default). +/// Project the edges of the face a new sketch was created on (the default). pub(super) fn auto_project_face(s: &mut Session, id: u64, _at: Vec3) -> Result> { let mut doc = (*s.doc).clone(); let Some(anchor) = doc diff --git a/crates/engine/src/cmd/sketch_robust_tests.rs b/crates/engine/src/cmd/sketch_robust_tests.rs index 458e32f6b..befbc09fd 100644 --- a/crates/engine/src/cmd/sketch_robust_tests.rs +++ b/crates/engine/src/cmd/sketch_robust_tests.rs @@ -61,7 +61,7 @@ fn trim_cases() { let _ = r; let mut s = new_sketch(); let l = add(&mut s, "sketch.line", json!({"points": [[0, 0], [10, 0]]}))[0].clone(); - // No crossings: the whole line goes (Fusion deletes it). + // No crossings: the whole line goes (it is deleted). let r = s.execute("sketch.trim", &json!({"curve": l, "at": [5, 0]})); sound_or_empty(&s); assert!(r.is_ok() || r.is_err()); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ab44c02d0..bf2318511 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -221,7 +221,7 @@ pub struct Session { pub log: Vec, /// Increments on every document change (views use it to refresh). pub revision: u64, - /// Project a face's edges into a sketch created on it (Fusion's default; `sketch.auto_project`). + /// Project a face's edges into a sketch created on it (the default; `sketch.auto_project`). pub auto_project: bool, /// The component new sketches and features go into (0 = the root). pub active_component: u64, diff --git a/crates/engine/src/split_face_tests.rs b/crates/engine/src/split_face_tests.rs index 1bf0cbfe7..721bb0a88 100644 --- a/crates/engine/src/split_face_tests.rs +++ b/crates/engine/src/split_face_tests.rs @@ -88,7 +88,7 @@ fn split_pieces_count_and_move_apart() { // Measure counts the two halves of the top as two faces. let m = run(&mut s, "inspect.measure", json!({ "bodies": ["B"] }))["bodies"][0].clone(); assert_eq!(m["faces"].as_u64(), Some(7), "{m}"); - // Offset Face on one half moves that half only (Fusion): a 20 × 30 step 5 high. + // Offset Face on one half moves that half only: a 20 × 30 step 5 high. run(&mut s, "solid.offset_face", json!({"faces": [[10, 15, 20]], "distance": 5})); let (_, v) = faces_volume(&mut s, "B"); assert!((v - 27000.0).abs() < 1e-6 * 27000.0, "{v}"); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index fcb1b259d..daceaaf47 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -652,7 +652,7 @@ fn sketch_tools_and_constraints() { assert!(s.execute("sketch.line", &json!({"points": [[0, 0], [1, 1]]})).is_err(), "needs an active sketch"); } -/// The recipe format of the Fusion oracle (01-box) drives the same commands. +/// The recipe format of the 01-box reference drives the same commands. #[test] fn script_runs_commands() { let mut s = Session::default(); diff --git a/crates/engine/src/tests/robustness.rs b/crates/engine/src/tests/robustness.rs index 229e3bee3..217e1cc4b 100644 --- a/crates/engine/src/tests/robustness.rs +++ b/crates/engine/src/tests/robustness.rs @@ -232,7 +232,7 @@ fn shell_of_a_filleted_box() { /// The first tutorial part: a 60×40×15 plate with its top front edge and front right edge /// rounded r2, shelled with the top open. At 2 mm the rounds' inner sides collapse to sharp -/// edges (as in Fusion); at 1.5 mm the top's round, tangent to the open top, keeps its +/// edges (the intended behaviour); at 1.5 mm the top's round, tangent to the open top, keeps its /// tangency (every face moves in, the opening is swept out through the top). #[test] fn shell_of_the_tutorial_plate() { diff --git a/crates/engine/src/view.rs b/crates/engine/src/view.rs index 3208fefe4..7a4e65845 100644 --- a/crates/engine/src/view.rs +++ b/crates/engine/src/view.rs @@ -528,7 +528,7 @@ pub fn section_segments(m: &solidcraft_geom::Mesh, o: Vec3, n: Vec3) -> Vec<(Vec } /// Is a sketch drawn? The active one is; others unless hidden. Finished sketches are hidden -/// once a feature uses them, like Fusion's default, unless shown one by one. +/// once a feature uses them, by default, unless shown one by one. pub fn sketch_shown(s: &Session, id: u64) -> bool { sketch_drawn(s, id, true) } diff --git a/crates/kernel/src/heal.rs b/crates/kernel/src/heal.rs index 5e51cd35a..5d7cd8f7f 100644 --- a/crates/kernel/src/heal.rs +++ b/crates/kernel/src/heal.rs @@ -1,5 +1,5 @@ //! Clean-up after operations: coplanar neighbouring faces become one face, and two straight -//! edges meeting in line at a vertex nothing else uses become one edge (as Fusion keeps them). +//! edges meeting in line at a vertex nothing else uses become one edge (they are kept as one). use std::collections::{BTreeSet, HashMap}; diff --git a/crates/kernel/src/helix.rs b/crates/kernel/src/helix.rs index 26eec4830..9948fed74 100644 --- a/crates/kernel/src/helix.rs +++ b/crates/kernel/src/helix.rs @@ -256,7 +256,7 @@ mod tests { #[test] fn coil_volume_is_section_times_helix_length() { // A 2 mm circle in a plane through the Z axis, 20 mm out, 3 turns, pitch 8: a screw - // motion of an axial section sweeps π r² · 2πR · turns (Fusion's spline helix: 4738.1). + // motion of an axial section sweeps π r² · 2πR · turns (spline helix: 4738.1). let pl = Plane { origin: Vec3::ZERO, x: Vec3::X, y: Vec3::Z }; let region = Region2 { outer: Loop2::circle(Vec2::new(20.0, 0.0), 2.0), holes: vec![] }; let b = sweep_helix(&pl, ®ion, Vec3::ZERO, Vec3::Z, 8.0, 3.0).unwrap(); diff --git a/crates/kernel/src/step_in/geom.rs b/crates/kernel/src/step_in/geom.rs index 91dcb1a17..ad024c1ab 100644 --- a/crates/kernel/src/step_in/geom.rs +++ b/crates/kernel/src/step_in/geom.rs @@ -1118,7 +1118,7 @@ pub(crate) fn surface(cx: &Ctx, id: u64, extent: &[mt::Point3], seam: &[mt::Poin }; // ISO 10303-42 parameterises a surface of revolution by the angle u and the profile // v, so its normal is ∂S/∂angle × ∂S/∂profile: the opposite of truck's revolution - // (profile first). Fusion reads it this way. Reversed sense turns it back. + // (profile first). Strict readers take it this way. Reversed sense turns it back. Ok(revolved(profile, o, -axis * sign)) } "SURFACE_OF_LINEAR_EXTRUSION" => { diff --git a/crates/kernel/src/step_in/mod.rs b/crates/kernel/src/step_in/mod.rs index 0e57150d7..b3f49f303 100644 --- a/crates/kernel/src/step_in/mod.rs +++ b/crates/kernel/src/step_in/mod.rs @@ -933,7 +933,7 @@ impl Reader { /// Check a STEP file's structure: it parses, no entity id is defined twice, every reference /// names a defined entity, nothing but root entities (relationships, definitions, /// presentation) is left unreferenced, and ids are dense (`#1`…`#n`). Returns the entity count. -/// Faces whose boundary runs the wrong way round their normal, as a strict reader (Fusion) +/// Faces whose boundary runs the wrong way round their normal, as a strict reader /// sees them: each face's normal is its surface's own parametric normal (∂S/∂u × ∂S/∂v, ISO /// 10303-42), reversed when `same_sense` is false, and the outer loop must run counter-clockwise /// seen from that side. Checked on faces whose loop spans a clear direction (patches, not bands diff --git a/crates/kernel/src/step_in/tests.rs b/crates/kernel/src/step_in/tests.rs index 4f04dea2e..30c52de25 100644 --- a/crates/kernel/src/step_in/tests.rs +++ b/crates/kernel/src/step_in/tests.rs @@ -974,7 +974,7 @@ fn hostile_boundaries_mesh_in_bounded_time() { } /// A cylinder written as a surface of revolution, oriented the ISO 10303-42 way (normal -/// ∂S/∂angle × ∂S/∂profile, outward here, so `same_sense` .T.). Fusion reads such faces this +/// ∂S/∂angle × ∂S/∂profile, outward here, so `same_sense` .T.). Strict readers read such faces this /// way; reading them with truck's profile-first normal turned faces inside out. #[test] fn surface_of_revolution_sense_follows_iso() { diff --git a/crates/kernel/src/tests.rs b/crates/kernel/src/tests.rs index d6df9e509..6b3e321f6 100644 --- a/crates/kernel/src/tests.rs +++ b/crates/kernel/src/tests.rs @@ -2477,7 +2477,7 @@ fn tangent_holes_pinch_alike() { } /// A d10 tube bent at R5: the inside of the bend is a horn torus pinched to a point. One torus -/// face, with a degenerate loop at the pinch (counted as Fusion does: 5 faces, 6 edges, 4 vertices). +/// face, with a degenerate loop at the pinch (5 faces, 6 edges, 4 vertices). #[test] fn tight_bend_counts() { use crate::build::PathSeg; diff --git a/crates/kernel/src/topo.rs b/crates/kernel/src/topo.rs index 93654c25b..0667e546d 100644 --- a/crates/kernel/src/topo.rs +++ b/crates/kernel/src/topo.rs @@ -554,7 +554,7 @@ pub fn merged_topology(b: &Body, mesh: &Mesh) -> Result { } let gs: Vec = faces.iter().map(|f| find(&mut fp, *f)).collect(); // A free-form face pinched to a point (a horn torus at its axis): a zero-length edge - // inside one face. Fusion keeps a degenerate loop there (two edges and a vertex). + // inside one face. A degenerate loop is kept there (two edges and a vertex). if let Some(g) = gs.first() && gs.iter().all(|x| x == g) && matches!(surfs.get(*g), Some(Surf::Other(_))) diff --git a/crates/mcp/src/server.rs b/crates/mcp/src/server.rs index 769587a53..b3091ef31 100644 --- a/crates/mcp/src/server.rs +++ b/crates/mcp/src/server.rs @@ -25,8 +25,8 @@ const RESOURCE_NOT_FOUND: i64 = -32002; /// Most messages in one JSON-RPC batch. const MAX_BATCH: usize = 1000; -const INSTRUCTIONS: &str = "SolidCraft is a parametric 3D CAD app in the style of Autodesk Fusion. Units are millimetres \ -and degrees in expressions (internally radians), Z is up. Model like in Fusion: `sketch.create {plane: XY}`, draw \ +const INSTRUCTIONS: &str = "SolidCraft is an independent parametric 3D CAD app. Units are millimetres \ +and degrees in expressions (internally radians), Z is up. Model like this: `sketch.create {plane: XY}`, draw \ (`sketch.rectangle.two_point {p0, p1}`, `sketch.circle.center {center, radius}`, `sketch.line {points, closed}`), constrain \ and dimension (`sketch.dimension {entities, value}`; values may name parameters), `sketch.finish`, then features \ (`solid.extrude {distance, operation?: new|join|cut|intersect}`, `solid.revolve`, `solid.fillet {edges: [[x,y,z] point on \ diff --git a/crates/sketch/src/model.rs b/crates/sketch/src/model.rs index 655818777..6e93064cd 100644 --- a/crates/sketch/src/model.rs +++ b/crates/sketch/src/model.rs @@ -390,7 +390,7 @@ impl ConstraintKind { pub fn is_angle(&self) -> bool { matches!(self, ConstraintKind::Angle { .. } | ConstraintKind::LineAngle { .. } | ConstraintKind::ArcSweep { .. }) } - /// Short type name (Fusion-like) for listings. + /// Short type name for listings. pub fn name(&self) -> &'static str { use ConstraintKind::*; match self { diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index d91637699..59b7e777a 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -383,7 +383,7 @@ fn body_feature_and_sketch(app: &SolveApp, body: &str) -> (Option, Option Vec { let sel = &app.session.selection; diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index d6b7f7e08..22a101559 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -481,7 +481,7 @@ impl Dialog { "solid.chamfer" => Dialog::new(fillet_kind("1 mm", true), vec![SelInput::new("Edges", EDGES | FACES, true)]), "solid.shell" => { let mut d = Dialog::new(Kind::Shell { thickness: "2 mm".into() }, vec![SelInput::new("Faces/Body", FACES, true)]); - // Fusion opens faces joined smoothly to the picked ones too. + // Faces joined smoothly to the picked ones too. d.extra.insert("tangent_chain".into(), json!(true)); d } diff --git a/crates/ui-egui/src/dialogs_assembly.rs b/crates/ui-egui/src/dialogs_assembly.rs index a0124fb45..9cb2d1bd4 100644 --- a/crates/ui-egui/src/dialogs_assembly.rs +++ b/crates/ui-egui/src/dialogs_assembly.rs @@ -930,7 +930,7 @@ pub fn commands(app: &SolveApp, k: &Asm, inputs: &[SelInput]) -> Result 1e-12 || y.abs() > 1e-12 { shifted(&a, x, y) } else { a.param }; - // Picked origins mate as in Fusion (the engine's default: B's z opposite A's, faces + // Picked origins mate by default (the engine's default: B's z opposite A's, faces // meet face to face, a pin goes into its hole); the dialog's Flip is the command's // `flip`, which turns B the other way. let p = json!({"type": kind, "a": a_param, "b": b.param, "flip": f.flip, "offset": f.offset[2], "angle": f.angle, "limits": limits}); diff --git a/crates/ui-egui/src/dialogs_assembly_tests.rs b/crates/ui-egui/src/dialogs_assembly_tests.rs index c8dffb0a9..fa655b686 100644 --- a/crates/ui-egui/src/dialogs_assembly_tests.rs +++ b/crates/ui-egui/src/dialogs_assembly_tests.rs @@ -273,7 +273,7 @@ fn picks_on_one_component_say_why_and_offer_components() { assert!(text_at(&out, &why).is_none(), "nothing left to say"); } -/// Two top faces mate face to face as in Fusion: B ends up upside down on A, not inside it; +/// Two top faces mate face to face: B ends up upside down on A, not inside it; /// Flip turns it back over (into A). #[test] fn face_snaps_mate_face_to_face() { diff --git a/crates/ui-egui/src/dialogs_motion.rs b/crates/ui-egui/src/dialogs_motion.rs index 90ea1580e..2ddc86d30 100644 --- a/crates/ui-egui/src/dialogs_motion.rs +++ b/crates/ui-egui/src/dialogs_motion.rs @@ -739,7 +739,7 @@ fn configurations_rows( value }); let mut tb = table(&v); - // Bare numbers show with their parameter's unit ("40" is 40 mm), as Fusion shows them. + // Bare numbers show with their parameter's unit ("40" is 40 mm). let kinds = app.session.doc.all_param_exprs(); for (_, vals) in &mut tb.rows { for (c, val) in tb.columns.iter().zip(vals.iter_mut()) { diff --git a/crates/ui-egui/src/drag_snap.rs b/crates/ui-egui/src/drag_snap.rs index 1cdc13597..c3708c275 100644 --- a/crates/ui-egui/src/drag_snap.rs +++ b/crates/ui-egui/src/drag_snap.rs @@ -1,4 +1,4 @@ -//! Snapping while a sketch point or a line is dragged, like Fusion: the dragged point snaps to +//! Snapping while a sketch point or a line is dragged: the dragged point snaps to //! other points (ends, centres, the origin, projected points), to the middle of a line and onto //! curves, and lines up horizontally or vertically with other points (a dashed guide). Letting //! go on a point, a midpoint or a curve adds the matching constraint; lining up adds none. Ctrl diff --git a/crates/ui-egui/src/inference.rs b/crates/ui-egui/src/inference.rs index d9067fda7..6620c93db 100644 --- a/crates/ui-egui/src/inference.rs +++ b/crates/ui-egui/src/inference.rs @@ -1,4 +1,4 @@ -//! Drawing-time inference for the Line tool, like Fusion's: while the next point is placed the +//! Drawing-time inference for the Line tool: while the next point is placed the //! cursor snaps to directions and places taken from the existing geometry (parallel or //! perpendicular to a line, on the extension of a line, tangent to a circle or arc). A dashed //! guide and a label show it; placing the point adds the matching constraint. diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 7a7da3d6f..f24a2e7e4 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -878,7 +878,7 @@ impl SolveApp { let _ = self.run(id, json!({})); } - /// Edit a feature the way Fusion does: sketches open in sketch mode; other features roll the + /// Edit a feature: sketches open in sketch mode; other features roll the /// timeline back to just before themselves and reopen their dialog, filled in. pub fn edit_feature(&mut self, id: u64) { use solidcraft_engine::doc::FeatureKind; @@ -906,7 +906,7 @@ impl SolveApp { } } - /// Edit a sketch the way Fusion does: roll the timeline back to just after it (so later + /// Edit a sketch: roll the timeline back to just after it (so later /// features don't hide it), turn the camera to face it, and remember both so Finish Sketch /// puts them back. Editing the sketch that is already open does nothing; editing another one /// finishes the current sketch first, so edit sessions never nest. diff --git a/crates/ui-egui/src/menu_tests.rs b/crates/ui-egui/src/menu_tests.rs index 7a0a3cf20..ad09152be 100644 --- a/crates/ui-egui/src/menu_tests.rs +++ b/crates/ui-egui/src/menu_tests.rs @@ -424,7 +424,7 @@ fn canvas_menu_hides_renames_calibrates_and_deletes() { assert!(app.session.doc.canvases.is_empty()); } -/// The canvas and browser menus keep Fusion's items in Fusion's order (the ones we have). +/// The canvas and browser menus keep their items in a fixed order. #[test] fn menus_follow_fusion_order() { let mut app = sample_app(); diff --git a/crates/ui-egui/src/navigation.rs b/crates/ui-egui/src/navigation.rs index 58ed4b723..b8e4a674c 100644 --- a/crates/ui-egui/src/navigation.rs +++ b/crates/ui-egui/src/navigation.rs @@ -451,7 +451,7 @@ pub(crate) fn handle(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect, resp: &e } else if mode == Some(NavMode::Orbit) { let press = ui.input(|i| i.pointer.press_origin()); app.cancel_view_animation(); - // Shift can be required to enter orbit (Fusion/Inventor middle drag, Alias Shift+Alt), + // Shift can be required to enter orbit (middle drag, Alias Shift+Alt), // rather than an additional request for snapping. Only an extra modifier snaps. let without_shift = egui::Modifiers { shift: false, ..mods }; let snap = app.preferences.nav != crate::prefs::OPENSCAD_NAV diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index 927d38eaa..293095621 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -1,4 +1,4 @@ -//! Preferences, one dialog in the spirit of Fusion's, opened from the gear at the top right of the +//! Preferences, one dialog, opened from the gear at the top right of the //! window, File › Preferences or Ctrl+, (Cmd+, on macOS): General (theme, UI scale, units of new //! designs, autosave, display precision, timeline layout, the agent cursor), Navigation (mouse presets, zoom //! direction, zoom to the cursor, orbit centre, Look At animation), Keyboard Shortcuts (search, diff --git a/crates/ui-egui/src/preselect_tests.rs b/crates/ui-egui/src/preselect_tests.rs index c3233dda3..ddb870660 100644 --- a/crates/ui-egui/src/preselect_tests.rs +++ b/crates/ui-egui/src/preselect_tests.rs @@ -898,7 +898,7 @@ fn shell_direction_and_tangent_chain_round_trip() { let mut app = boxed(); let top = face(&app, Vec3::new(20.0, 15.0, 20.0)); let mut d = start(&mut app, vec![top], "solid.shell"); - // Tangent Chain is on, as in Fusion; Direction Outside. + // Tangent Chain is on; Direction Outside. assert_eq!(d.extra.get("tangent_chain"), Some(&json!(true))); d.extra.insert("direction".into(), json!("outside")); let p = apply_commands(&app, &d).unwrap().remove(0).1; diff --git a/crates/ui-egui/src/sketch_tools.rs b/crates/ui-egui/src/sketch_tools.rs index 4379774d3..ce0be3ee2 100644 --- a/crates/ui-egui/src/sketch_tools.rs +++ b/crates/ui-egui/src/sketch_tools.rs @@ -36,7 +36,7 @@ thread_local! { static DEFERRED: Cell = const { Cell::new(false) }; } -/// Commands registered on one panel that Fusion also lists on another: the analyses (sketch +/// Commands registered on one panel that another panel also lists: the analyses (sketch /// INSPECT) on SOLID INSPECT, and Interference (SOLID INSPECT) on sketch INSPECT. const ALSO_IN: &[(&str, &str, &str)] = &[ ("SOLID", "INSPECT", "inspect.zebra"), @@ -258,7 +258,7 @@ fn combs(app: &SolveApp, painter: &egui::Painter, proj: &Proj) { }); } -/// Snap a cursor point on the sketch plane to what Fusion infers while drawing: a line's +/// Snap a cursor point on the sketch plane to what is inferred while drawing: a line's /// midpoint, or alignment (horizontal/vertical) with the previous point of the tool. None: /// nothing near, use the grid. pub fn refine_snap( diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index aab5a9952..e6aeb9bab 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -415,7 +415,7 @@ pub fn app_bar(app: &mut SolveApp, ui: &mut egui::Ui) { if response.on_hover_text(crate::i18n::tr_label("Report a bug — review a screenshot and open a GitHub draft")).clicked() { crate::help::run(app, &ui.ctx().clone(), "report"); } - // Preferences, at the top right like Fusion's profile menu (also Ctrl+,). + // Preferences, at the top right (also Ctrl+,). let gear = Rect::from_center_size(pos2(r.right() - captions - 70.0, r.center().y), vec2(24.0, 24.0)); let gresp = ui.interact(gear, ui.id().with("sc_prefs_button"), Sense::click()); if gresp.hovered() { diff --git a/crates/ui-egui/src/workspace.rs b/crates/ui-egui/src/workspace.rs index bec39cab0..c8ad5afb9 100644 --- a/crates/ui-egui/src/workspace.rs +++ b/crates/ui-egui/src/workspace.rs @@ -201,7 +201,7 @@ mod tests { assert!(h.widget("Add Row").is_some()); } - /// Fusion's layout: joints on every tab's ASSEMBLE panel, sheet metal and plastic tabs + /// Layout: joints on every tab's ASSEMBLE panel, sheet metal and plastic tabs /// reach the shared solid commands, the plastic rules sit on SETUP. #[test] fn tabs_share_commands_in_fusion_order() { diff --git a/docs/plugins.md b/docs/plugins.md index 31bfd8093..aa5bb724c 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -48,7 +48,7 @@ FeatureKind::Plugin { | `label` | Primary timeline / browser text | | `icon_id` | Host icon registry name (same system as [`feature_icon`](https://github.com/bherbruck/solidcraft/blob/main/crates/ui-egui/src/workspace.rs)) | | `tooltip` | Hover text, `inspect` type string | -| `type_name` | Fusion-like feature type for power users | +| `type_name` | short feature type name for power users | The timeline renders **any** `Plugin` feature through one code path: read `display`, draw icon + label, wire suppress/rename/delete/reorder like built-in features. No per-plugin egui in milestone 2. diff --git a/docs/robustness.md b/docs/robustness.md index dfa772fce..520765912 100644 --- a/docs/robustness.md +++ b/docs/robustness.md @@ -177,7 +177,7 @@ Found by QA on new users' first steps, each with an engine test against the anal round runs round the corners as spindle tori (the tube wider than its circle), which the offset now takes. Volume within 1e-5 of the analytic one. - **Shell thicker than or equal to a round** (r2 rounds shelled 2 mm): the round's inside - collapses to a sharp edge, as in Fusion, instead of "a cylinder shrinks to nothing". + collapses to a sharp edge, as intended, instead of "a cylinder shrinks to nothing". - **Shell thinner than a round tangent to the open face** (1.5 mm): every face moves in (tangencies keep) and the opening is the open face's copy swept out through the body. - **Shell after a drilled hole** (its tip a cone). @@ -192,7 +192,7 @@ Found by QA on new users' first steps, each with an engine test against the anal ### Known limitations (counted as "not supported", with a clear message) - A shell thicker than a wall or a step: the moved faces would cross and the cavity turn - inside out. Fusion fills such places solid; we need a topology-changing offset. + inside out. The intended behaviour fills such places solid; we need a topology-changing offset. - Fillets and chamfers between two curved faces, or ending at faces that aren't planar. ### Still failing diff --git a/packaging/linux/nfpm.yaml b/packaging/linux/nfpm.yaml index a6e2da1fd..e719f6051 100644 --- a/packaging/linux/nfpm.yaml +++ b/packaging/linux/nfpm.yaml @@ -23,7 +23,7 @@ vendor: SolidCraft contributors homepage: https://docs.solidcraft.io/ license: MIT OR Apache-2.0 description: |- - Open-source parametric 3D CAD in the style of Fusion + Open-source, independent parametric 3D CAD Sketches with a constraint solver, a parametric feature timeline, components and joints, sheet metal; STEP, IGES, 3MF, STL and OBJ. Includes solidcraft-cli, a headless command runner and MCP server for AI agents. From 17e173cb7b1191c8ba17559bb5ad0a1cd24d5f60 Mon Sep 17 00:00:00 2001 From: DuBearte <130190089+DuBearte@users.noreply.github.com> Date: Sun, 18 Oct 2026 21:16:20 -0400 Subject: [PATCH 024/225] Construct tools ask for their picks instead of failing with "a is required" (#2474, #2494) (#2563) * claim: #2474, #2494 * fix(ui): construct tools ask for their picks instead of failing (#2474, #2494) The 13 construct tools without a dialog of their own ran their command with no parameters from the toolbar and reported that `a` (or `face`, `edge`...) is required. One pick dialog now serves them: labelled inputs per tool, preselection fills them, and each pick becomes the construction reference the command takes; Point Along Path keeps its position. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 117 +++++++++++++++++++++++++- crates/ui-egui/src/preselect_tests.rs | 71 ++++++++++++++++ 2 files changed, 187 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 22a101559..6e778857c 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -116,6 +116,14 @@ pub enum Kind { }, /// Halfway between two planes or planar faces. Midplane, + /// A construction axis, point or plane made from picks alone (#2474): input `i` is the + /// command's parameter `keys[i]`, and `t` (along a path) when it takes one. + Construct { + command: &'static str, + title: &'static str, + keys: Vec<&'static str>, + t: Option, + }, /// A construction plane through an axis at an angle to a plane. AnglePlane { angle: String, @@ -529,6 +537,13 @@ impl Dialog { Kind::Midplane, vec![SelInput::new("First plane", PLANES | PLANAR_FACES, false), SelInput::new("Second plane", PLANES | PLANAR_FACES, false)], ), + id if construct_picks(id).is_some() => { + let (command, title, picks) = construct_picks(id)?; + let inputs = picks.iter().map(|(label, accept, _)| SelInput::new(label, *accept, false)).collect(); + let keys = picks.iter().map(|(_, _, key)| *key).collect(); + let t = (command == "construct.point.along_path").then(|| "0.5".to_string()); + Dialog::new(Kind::Construct { command, title, keys, t }, inputs) + } "construct.plane.along_path" => { Dialog::new(Kind::PathPlane { t: "0.5".into(), sketch: None }, vec![SelInput::new("Path", CURVES | EDGES, false)]) } @@ -805,6 +820,7 @@ impl Dialog { | Kind::Sweep { .. } | Kind::PathPlane { .. } | Kind::Midplane + | Kind::Construct { .. } | Kind::Move { .. } | Kind::Hole { .. } | Kind::Primitive { .. } @@ -1411,6 +1427,7 @@ fn title(k: &Kind) -> &'static str { Kind::Material { .. } => "PHYSICAL MATERIAL", Kind::OffsetPlane { .. } => "OFFSET PLANE", Kind::Midplane => "MIDPLANE", + Kind::Construct { title, .. } => title, Kind::PathPlane { .. } => "PLANE ALONG PATH", Kind::Rib { web: false, .. } => "RIB", Kind::Rib { web: true, .. } => "WEB", @@ -2728,7 +2745,12 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { enter |= field(ui, t); ui.end_row(); } - Kind::Split | Kind::ReplaceFace | Kind::Remove | Kind::Midplane => {} + Kind::Split | Kind::ReplaceFace | Kind::Remove | Kind::Midplane | Kind::Construct { t: None, .. } => {} + Kind::Construct { t: Some(t), .. } => { + row_label(ui, "Position (0 to 1)"); + enter |= field(ui, t); + ui.end_row(); + } Kind::Rib { thickness, depth, flip, normal, .. } => { row_label(ui, "Direction"); let mut i = usize::from(*normal); @@ -4013,6 +4035,18 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result, S let b = plane_arg(app, sels(d, 1).first())?; ("construct.plane.midplane", json!({"a": a, "b": b})) } + Kind::Construct { command, keys, t, .. } => { + let mut p = serde_json::Map::new(); + for (i, key) in keys.iter().enumerate() { + let input = d.inputs.get(i).map_or("", |inp| inp.label); + let sel = sels(d, i).first().ok_or_else(|| format!("pick the {}", input.to_lowercase()))?; + p.insert((*key).to_string(), construct_ref(app, sel)?); + } + if let Some(t) = t { + p.insert("t".into(), json!(t)); + } + (*command, Value::Object(p)) + } Kind::PathPlane { t, sketch } => { need(0, "a path")?; let path = match sels(d, 0).first() { @@ -4610,6 +4644,87 @@ fn emboss_face_sel(s: &Session, component: u64, face: &solidcraft_engine::doc::E Some(Sel::Face { body: world_name, index, point }) } +/// The construct tools that take only picks (#2474, #2494): their command, dialog title and +/// inputs as (label, what it accepts, parameter). Offset Plane, Midplane, Plane Along Path and +/// Plane At Angle have dialogs of their own. +fn construct_picks(id: &str) -> Option<(&'static str, &'static str, &'static [(&'static str, Accept, &'static str)])> { + const PLANE: Accept = PLANES | PLANAR_FACES; + const POINT: Accept = selection::VERTICES | selection::POINTS; + const LINE: Accept = EDGES | AXES; + const CURVE: Accept = EDGES | CURVES; + Some(match id { + "construct.axis.through_cylinder" => ("construct.axis.through_cylinder", "AXIS THROUGH CYLINDER", &[("Face", FACES | EDGES, "face")]), + "construct.axis.normal_to_face" => { + ("construct.axis.normal_to_face", "AXIS PERPENDICULAR TO FACE", &[("Face", FACES, "face"), ("Point", POINT, "point")]) + } + "construct.axis.two_planes" => { + ("construct.axis.two_planes", "AXIS THROUGH TWO PLANES", &[("First plane", PLANE, "a"), ("Second plane", PLANE, "b")]) + } + "construct.axis.two_points" => { + ("construct.axis.two_points", "AXIS THROUGH TWO POINTS", &[("First point", POINT, "a"), ("Second point", POINT, "b")]) + } + "construct.axis.edge" => ("construct.axis.edge", "AXIS THROUGH EDGE", &[("Edge", LINE, "edge")]), + "construct.point.vertex" => ("construct.point.vertex", "POINT AT VERTEX", &[("Point", POINT, "point")]), + "construct.point.two_edges" => { + ("construct.point.two_edges", "POINT THROUGH TWO EDGES", &[("First edge", CURVE, "a"), ("Second edge", CURVE, "b")]) + } + "construct.point.three_planes" => ( + "construct.point.three_planes", + "POINT THROUGH THREE PLANES", + &[("First plane", PLANE, "a"), ("Second plane", PLANE, "b"), ("Third plane", PLANE, "c")], + ), + "construct.point.center" => ("construct.point.center", "POINT AT CENTER", &[("Circle or sphere", FACES | CURVE, "of")]), + "construct.point.edge_plane" => { + ("construct.point.edge_plane", "POINT AT EDGE AND PLANE", &[("Edge", CURVE, "edge"), ("Plane", PLANE, "plane")]) + } + "construct.point.along_path" => ("construct.point.along_path", "POINT ALONG PATH", &[("Path", CURVE, "path")]), + "construct.plane.two_edges" => { + ("construct.plane.two_edges", "PLANE THROUGH TWO EDGES", &[("First edge", LINE, "a"), ("Second edge", LINE, "b")]) + } + "construct.plane.three_points" => ( + "construct.plane.three_points", + "PLANE THROUGH THREE POINTS", + &[("First point", POINT, "a"), ("Second point", POINT, "b"), ("Third point", POINT, "c")], + ), + "construct.plane.tangent" => ("construct.plane.tangent", "TANGENT PLANE", &[("Face", FACES, "face")]), + "construct.plane.perpendicular" => { + ("construct.plane.perpendicular", "PERPENDICULAR PLANE", &[("Plane", PLANE, "plane"), ("Line", LINE, "line")]) + } + _ => return None, + }) +} + +/// A dialog pick as a construction reference (`construct.*`'s `{face|edge|vertex: [x,y,z]}`, +/// `{plane}`, `{axis}` or `{sketch, point|curve}`). +fn construct_ref(app: &SolveApp, sel: &Sel) -> Result { + Ok(match sel { + Sel::Face { point, .. } => json!({"face": pt(*point)}), + Sel::Edge { point, .. } => json!({"edge": pt(*point)}), + Sel::Vertex { point, .. } => json!({"vertex": pt(*point)}), + Sel::Plane { name } => json!({"plane": name}), + Sel::Axis { name } => json!({"axis": name}), + // Picked across sketches as ":". + Sel::SketchPoint { id } => match id.split_once(':').and_then(|(sk, p)| Some((sk.parse::().ok()?, p))) { + Some((sketch, point)) => json!({"sketch": sketch, "point": point}), + None => return Err("pick the point in the viewport".into()), + }, + Sel::SketchCurve { id } => { + let st = app.session.world_state(); + let sketches: Vec = st + .sketches + .iter() + .filter(|ss| ss.sketch.curve_index(id).is_some() || ss.sketch.wire_index(id).is_some()) + .map(|ss| ss.feature) + .collect(); + match sketches.as_slice() { + [sketch] => json!({"sketch": sketch, "curve": id}), + _ => return Err("pick a model edge, or a sketch curve in only one sketch".into()), + } + } + _ => return Err("this pick can't be used here".into()), + }) +} + /// A picked plane or planar face as `construct.plane.*` takes it. fn plane_arg(app: &SolveApp, sel: Option<&Sel>) -> Result { match sel { diff --git a/crates/ui-egui/src/preselect_tests.rs b/crates/ui-egui/src/preselect_tests.rs index ddb870660..c7270f2e5 100644 --- a/crates/ui-egui/src/preselect_tests.rs +++ b/crates/ui-egui/src/preselect_tests.rs @@ -1717,3 +1717,74 @@ fn midplane_asks_for_two_planes_then_builds_the_one_between_them() { assert!(pl.normal().cross(Vec3::Z).len() < 1e-6, "{pl:?}"); assert!((pl.origin.z - 10.0).abs() < 1e-6, "{pl:?}"); } + +/// #2474, #2494: every construct tool asks for what it needs. Started from the toolbar with +/// nothing selected, none of them runs its command and reports that `a` (or `face`, `edge`…) +/// is required; a construct command added later without a dialog fails here too. +#[test] +fn every_construct_tool_opens_a_dialog_instead_of_failing() { + let mut h = crate::scenario::Harness::new(); + // A body, so the tools that need one are enabled. + h.app.run("solid.box", json!({"length":20,"width":20,"height":20})).unwrap(); + let commands = h.app.session.execute("engine.commands", &json!({})).unwrap(); + let ids: Vec = + commands.as_array().unwrap().iter().filter_map(|c| c["id"].as_str()).filter(|id| id.starts_with("construct.")).map(String::from).collect(); + assert!(ids.len() >= 17, "{ids:?}"); + for id in &ids { + h.app.session.selection.clear(); + h.app.status = None; + h.app.start(id); + h.frames(1); + let status = h.app.status.as_ref().map(|s| s.0.clone()).unwrap_or_default(); + assert!(!status.contains("is required"), "{id}: {status}"); + assert!(h.app.dialog.as_ref().is_some_and(|d| !d.inputs.is_empty()), "{id} opens a dialog that asks for picks"); + crate::dialogs::cancel(&mut h.app); + } +} + +/// #2494: two planes selected first, Axis Through Two Planes takes both and makes the axis +/// where they meet. +#[test] +fn axis_through_two_preselected_planes_builds_their_intersection() { + let mut h = crate::scenario::Harness::new(); + h.app.session.selection = vec![Sel::Plane { name: "XY".into() }, Sel::Plane { name: "XZ".into() }]; + h.app.start("construct.axis.two_planes"); + h.frames(1); + let d = h.app.dialog.as_ref().unwrap(); + assert!(matches!(d.kind, Kind::Construct { .. })); + assert_eq!((d.inputs[0].items.len(), d.inputs[1].items.len()), (1, 1), "each plane fills one input"); + h.step(&json!({"key":"Enter"})).unwrap(); + assert!(h.app.dialog.is_none(), "{:?}", h.app.dialog.as_ref().and_then(|d| d.error.clone())); + let axes = solidcraft_engine::view::construction_axes(&h.app.session); + let (_, _, _, dir) = axes.first().expect("the axis"); + assert!(dir.cross(Vec3::X).len() < 1e-6, "XY and XZ meet along X: {dir:?}"); +} + +/// #2474: Plane Through Two Edges takes two edges picked in the dialog. +#[test] +fn plane_through_two_picked_edges() { + let mut h = crate::scenario::Harness::new(); + h.app.run("solid.box", json!({"length":20,"width":20,"height":20})).unwrap(); + h.app.start("construct.plane.two_edges"); + h.frames(1); + let edge = |p: Vec3| Sel::Edge { body: "Body1".into(), index: 0, point: p }; + let d = h.app.dialog.as_mut().unwrap(); + d.inputs[0].items = vec![edge(Vec3::new(10.0, 0.0, 20.0))]; + d.inputs[1].items = vec![edge(Vec3::new(0.0, 10.0, 20.0))]; + h.step(&json!({"key":"Enter"})).unwrap(); + assert!(h.app.dialog.is_none(), "{:?}", h.app.dialog.as_ref().and_then(|d| d.error.clone())); + let (_, _, pl) = solidcraft_engine::view::construction_planes(&h.app.session).into_iter().next().expect("the plane"); + assert!(pl.normal().cross(Vec3::Z).len() < 1e-6 && (pl.origin.z - 20.0).abs() < 1e-6, "the top face's plane: {pl:?}"); +} + +/// Point Along Path asks for its position too, and a missing pick names the input. +#[test] +fn point_along_path_has_its_position_and_missing_picks_are_named() { + let mut h = crate::scenario::Harness::new(); + h.app.start("construct.point.along_path"); + h.frames(1); + assert!(matches!(&h.app.dialog.as_ref().unwrap().kind, Kind::Construct { t: Some(t), .. } if t == "0.5")); + h.step(&json!({"key":"Enter"})).unwrap(); + let e = h.app.dialog.as_ref().and_then(|d| d.error.clone()).unwrap_or_default(); + assert!(e.contains("path"), "{e}"); +} From a3080d02d6d9b04e2e7876402a3627d917035890 Mon Sep 17 00:00:00 2001 From: ealitt Date: Sun, 18 Oct 2026 21:16:25 -0400 Subject: [PATCH 025/225] claim: #2561 (#2562) --- crates/ui-egui/src/file_load.rs | 14 +++++ crates/ui-egui/src/file_load_ui_tests.rs | 67 +++++++++++------------- 2 files changed, 45 insertions(+), 36 deletions(-) diff --git a/crates/ui-egui/src/file_load.rs b/crates/ui-egui/src/file_load.rs index f9dc3cca3..87a56a594 100644 --- a/crates/ui-egui/src/file_load.rs +++ b/crates/ui-egui/src/file_load.rs @@ -163,6 +163,9 @@ pub struct FileLoad { /// Tests: the next load waits before this feature until cancelled. #[cfg(test)] pub hold_at: Option, + /// Tests: report the worker thread, then wait for the window's explicit release. + #[cfg(test)] + pub worker_gate: Option<(Sender, Receiver<()>)>, } impl FileLoad { @@ -369,7 +372,18 @@ fn start(app: &mut SolveApp) { partial_rx }); let worker_finished = finished; + #[cfg(test)] + let worker_gate = app.file_load.worker_gate.take(); let spawned = std::thread::Builder::new().name("file-load".into()).spawn(move || { + #[cfg(test)] + if let Some((started, release)) = worker_gate { + let _ = started.send(std::thread::current().id()); + if release.recv_timeout(std::time::Duration::from_secs(60)).is_err() { + worker_finished.store(true, Ordering::Relaxed); + let _ = tx.send(Err("test file worker was not released".into())); + return; + } + } let preview_began = std::time::Instant::now(); if command == "doc.open" { let progress = worker_progress.clone(); diff --git a/crates/ui-egui/src/file_load_ui_tests.rs b/crates/ui-egui/src/file_load_ui_tests.rs index 1b791dd4f..104617de8 100644 --- a/crates/ui-egui/src/file_load_ui_tests.rs +++ b/crates/ui-egui/src/file_load_ui_tests.rs @@ -25,8 +25,8 @@ impl Win { w } - /// One frame: (the viewport commands it sent, how long it took). - fn frame(&mut self, events: Vec) -> (Vec, std::time::Duration) { + /// One frame: the viewport commands it sent. + fn frame(&mut self, events: Vec) -> Vec { self.time += 1.0 / 60.0; let raw = RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 1000.0))), @@ -35,14 +35,13 @@ impl Win { events, ..Default::default() }; - let began = std::time::Instant::now(); let app = &mut self.app; let mut out = self.ctx.run_ui(raw, |ui| { app.logic(ui.ctx()); app.ui(ui); }); out.textures_delta.clear(); - (out.viewport_output.remove(&ViewportId::ROOT).map(|v| v.commands).unwrap_or_default(), began.elapsed()) + out.viewport_output.remove(&ViewportId::ROOT).map(|v| v.commands).unwrap_or_default() } /// The frames of a press-drag-release along `path`: the viewport commands they sent. @@ -51,7 +50,7 @@ impl Win { let mut events = vec![vec![Event::PointerMoved(path[0])], vec![button(path[0], true)]]; events.extend(path[1..].iter().map(|p| vec![Event::PointerMoved(*p)])); events.push(vec![button(*path.last().unwrap(), false)]); - events.into_iter().flat_map(|e| self.frame(e).0).collect() + events.into_iter().flat_map(|e| self.frame(e)).collect() } } @@ -97,46 +96,42 @@ fn fingerprint(s: &Session) -> serde_json::Value { fn the_window_keeps_drawing_and_moving_while_a_large_design_opens() { let dir = scratch("drag"); let path = large_design(&dir, 4); - let began = std::time::Instant::now(); let mut sync = Session::default(); sync.execute("doc.open", &json!({"path": path})).unwrap(); - let sync_ms = began.elapsed().as_secs_f64() * 1000.0; let mut w = Win::new(); let blank = w.app.session.doc.clone(); + let (started_tx, started_rx) = std::sync::mpsc::channel(); + let (release_tx, release_rx) = std::sync::mpsc::channel(); + w.app.file_load.worker_gate = Some((started_tx, release_rx)); w.app.open_path_async(&path); - assert!(w.app.file_load.busy(), "the open runs off the window thread"); + // The deadline only bounds a broken test; responsiveness is proved by ordering, not time. + let worker = started_rx.recv_timeout(std::time::Duration::from_secs(60)).expect("file worker started"); + assert_ne!(worker, std::thread::current().id(), "opening runs on another thread"); + for _ in 0..3 { + w.frame(vec![]); + assert!(w.app.file_load.busy(), "frames finish before the file worker is released"); + assert!(std::sync::Arc::ptr_eq(&w.app.session.doc, &blank), "the old design stays intact"); + } let bar = pos2(500.0, 17.0); let viewport = w.app.viewport.rect.map_or(pos2(800.0, 500.0), |r| r.center()); - let (mut busy_frames, mut slowest) = (0, std::time::Duration::ZERO); - let (mut moved, mut overlay, mut viewport_ignored) = (false, false, false); - for _ in 0..100_000 { - if !w.app.file_load.busy() { - break; - } - busy_frames += 1; - if busy_frames == 2 { - // The title bar still moves the window, and maximizes it on a double click. - let cmds = w.gesture(&[bar, bar + vec2(12.0, 4.0), bar + vec2(40.0, 10.0)]); - moved = cmds.iter().any(|c| matches!(c, ViewportCommand::StartDrag)) && w.app.file_load.busy(); - // A drag on the design reaches the overlay, not the viewport (no orbit). - let cam = serde_json::to_value(w.app.cam).unwrap(); - w.gesture(&[viewport, viewport + vec2(30.0, 0.0), viewport + vec2(80.0, 20.0)]); - viewport_ignored = serde_json::to_value(w.app.cam).unwrap() == cam && w.app.tool.is_none(); - overlay = crate::scenario::handle_at("file_loading:cancel").is_some(); - // Shortcuts and commands wait for the file. - assert!(w.app.run("solid.box", json!({"length": 5, "width": 5, "height": 5})).is_err()); - continue; - } - let (_, took) = w.frame(vec![]); - slowest = slowest.max(took); + let cmds = w.gesture(&[bar, bar + vec2(12.0, 4.0), bar + vec2(40.0, 10.0)]); + assert!(cmds.iter().any(|c| matches!(c, ViewportCommand::StartDrag)), "the title bar drag was handled during the open"); + let cam = serde_json::to_value(w.app.cam).unwrap(); + w.gesture(&[viewport, viewport + vec2(30.0, 0.0), viewport + vec2(80.0, 20.0)]); + assert_eq!(serde_json::to_value(w.app.cam).unwrap(), cam, "the design underneath took no camera input"); + assert!(w.app.tool.is_none()); + assert!(crate::scenario::handle_at("file_loading:cancel").is_some(), "the Opening overlay with Cancel was shown"); + assert!(w.app.run("solid.box", json!({"length": 5, "width": 5, "height": 5})).is_err()); + assert!(w.app.file_load.busy(), "all window interactions completed before releasing the worker"); + assert!(std::sync::Arc::ptr_eq(&w.app.session.doc, &blank)); + release_tx.send(()).expect("release the file worker after window interactions"); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60); + while w.app.file_load.busy() && std::time::Instant::now() < deadline { + w.frame(vec![]); + std::thread::yield_now(); } - assert!(!w.app.file_load.busy(), "the open finished"); - assert!(busy_frames >= 3, "frames kept coming during the {sync_ms:.0} ms open: {busy_frames}"); - assert!(moved, "the title bar drag was handled during the open"); - assert!(overlay, "the Opening overlay with Cancel was shown"); - assert!(viewport_ignored, "the design underneath took no input"); - assert!(slowest.as_secs_f64() * 1000.0 < (sync_ms * 0.5).max(250.0), "no frame waited for the open: slowest {slowest:?}, open {sync_ms:.0} ms"); + assert!(!w.app.file_load.busy(), "the released open finished"); for _ in 0..3 { w.frame(vec![]); } From 7ad5130cd222c257ce5cffdc341909fa7d670dbf Mon Sep 17 00:00:00 2001 From: JIJINBEI <87472238+jijinbei@users.noreply.github.com> Date: Mon, 19 Oct 2026 10:16:31 +0900 Subject: [PATCH 026/225] refactor: geom::UnitVec3 for unit axes and normals (#2603) * geom: UnitVec3; a face's analytic axes and normals are unit by type Co-Authored-By: Claude Opus 5.5 * geom: UnitVec3 adds to and subtracts from a Vec3 Co-Authored-By: Claude Opus 5.5 * kernel, doc, engine: cylinder axes and measured normals held as UnitVec3 Co-Authored-By: Claude Opus 5.5 * kernel, engine: functions that take a unit axis or direction say so by type Co-Authored-By: Claude Opus 5.5 * doc: a face's normal goes to Plane::from_normal as is Co-Authored-By: Claude Opus 5.5 * kernel, doc: main's new cylinder helpers take the face's axis as a UnitVec3 Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- apps/solidcraft-cli/tests/action_matrix.rs | 2 +- crates/doc/src/body_transfer_sheet.rs | 2 +- crates/doc/src/construct.rs | 10 +- crates/doc/src/eval.rs | 12 +- crates/doc/src/joints_face.rs | 2 +- crates/doc/src/sheet_convert.rs | 10 +- .../src/cmd/component_transfer_tests.rs | 4 +- crates/engine/src/cmd/measure_sel.rs | 18 +-- crates/engine/src/cmd/measure_shape.rs | 51 ++++---- crates/engine/src/display_mesh_tests.rs | 2 +- crates/geom/src/lib.rs | 2 + crates/geom/src/plane.rs | 4 +- crates/geom/src/unit_vec3.rs | 120 ++++++++++++++++++ crates/geom/src/vec.rs | 8 +- crates/kernel/src/bore_guard.rs | 14 +- crates/kernel/src/bore_union_tests.rs | 4 +- crates/kernel/src/coaxial_overlap.rs | 6 +- crates/kernel/src/coplanar.rs | 6 +- crates/kernel/src/display_mesh_tests.rs | 16 +-- crates/kernel/src/issue_788_tests.rs | 15 ++- crates/kernel/src/seam_faces.rs | 1 - crates/kernel/src/splitface.rs | 21 +-- crates/kernel/src/surface_extend.rs | 18 +-- crates/kernel/src/surface_kind.rs | 36 +++--- crates/kernel/src/surfaces.rs | 4 +- crates/kernel/src/tangent_cylinders.rs | 17 ++- crates/kernel/src/topo.rs | 19 ++- 27 files changed, 279 insertions(+), 145 deletions(-) create mode 100644 crates/geom/src/unit_vec3.rs diff --git a/apps/solidcraft-cli/tests/action_matrix.rs b/apps/solidcraft-cli/tests/action_matrix.rs index 23781cdc6..9e634be1b 100644 --- a/apps/solidcraft-cli/tests/action_matrix.rs +++ b/apps/solidcraft-cli/tests/action_matrix.rs @@ -350,7 +350,7 @@ fn actions(s: &Session) -> Vec { // The surface's normal at `p` (either way round): exact on analytic faces. let normal_at = |f: u32, p: Vec3| -> Option { match face_surface(&b.body, f as usize) { - Some(FaceSurface::Plane { normal, .. }) => Some(normal), + Some(FaceSurface::Plane { normal, .. }) => Some(*normal), Some(FaceSurface::Cylinder { origin, axis, .. }) => { let v = p - origin; (v - axis * v.dot(axis)).normalized() diff --git a/crates/doc/src/body_transfer_sheet.rs b/crates/doc/src/body_transfer_sheet.rs index be971d30a..5a0784781 100644 --- a/crates/doc/src/body_transfer_sheet.rs +++ b/crates/doc/src/body_transfer_sheet.rs @@ -32,7 +32,7 @@ pub(crate) fn remap_sheet_metadata(st: &mut ModelState, names: &[String], transf .filter(|(_, t)| names.contains(t.body.as_str())) .map(|(i, t)| { let point = apply_point(transform, t.axis_point); - let axis = apply_vector(transform, t.axis).normalized().ok_or_else(|| DocError::Invalid("invalid transferred thread axis".into()))?; + let axis = apply_vector(transform, *t.axis).unit().ok_or_else(|| DocError::Invalid("invalid transferred thread axis".into()))?; if !point.is_finite() { return Err(DocError::Invalid("invalid transferred thread placement".into())); } diff --git a/crates/doc/src/construct.rs b/crates/doc/src/construct.rs index e0adabbf2..c6abe8867 100644 --- a/crates/doc/src/construct.rs +++ b/crates/doc/src/construct.rs @@ -285,9 +285,9 @@ pub(crate) fn line(ctx: &Ctx, g: &GeoRef) -> Result<(Vec3, Vec3)> { GeoRef::Face { at, name } => { let (b, fi, _) = face_of(ctx.st, *at, name)?; match kernel::face_surface(&b.body, fi) { - Some(FaceSurface::Cylinder { origin, axis, .. }) => Ok((origin, axis)), - Some(FaceSurface::Cone { apex, axis, .. }) => Ok((apex, axis)), - Some(FaceSurface::Torus { center, axis, .. }) => Ok((center, axis)), + Some(FaceSurface::Cylinder { origin, axis, .. }) => Ok((origin, *axis)), + Some(FaceSurface::Cone { apex, axis, .. }) => Ok((apex, *axis)), + Some(FaceSurface::Torus { center, axis, .. }) => Ok((center, *axis)), _ => Err(bad("the face is not a cylinder, cone or torus")), } } @@ -367,7 +367,7 @@ fn path_points(ctx: &Ctx, g: &GeoRef) -> Result> { /// The surface's unit normal at (the point of the surface nearest) `p`, and that point. fn surface_normal(s: FaceSurface, p: Vec3) -> Option<(Vec3, Vec3)> { match s { - FaceSurface::Plane { normal, point } => Some((p - normal * (p - point).dot(normal), normal)), + FaceSurface::Plane { normal, point } => Some((p - normal * (p - point).dot(normal), *normal)), FaceSurface::Cylinder { origin, axis, radius } => { let w = p - origin; let r = (w - axis * w.dot(axis)).normalized()?; @@ -403,7 +403,7 @@ fn face_surface_at(ctx: &Ctx, g: &GeoRef) -> Result<(FaceSurface, Vec3)> { } GeoRef::Plane { .. } => { let pl = plane(ctx, g)?; - Ok((FaceSurface::Plane { normal: pl.normal(), point: pl.origin }, pl.origin)) + Ok((FaceSurface::Plane { normal: pl.normal().unit().ok_or_else(|| bad("degenerate plane"))?, point: pl.origin }, pl.origin)) } _ => Err(bad("pick a face")), } diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 2c372f64c..71e40fcc9 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -6,7 +6,7 @@ use std::sync::{Arc, OnceLock}; use serde::Serialize; use solidcraft_geom::tess::TessPlan; -use solidcraft_geom::{Mesh, Plane, Region2, Vec2, Vec3, regions_apart}; +use solidcraft_geom::{Mesh, Plane, Region2, UnitVec3, Vec2, Vec3, regions_apart}; use solidcraft_kernel::{self as kernel, Body, BoolOp}; use solidcraft_sketch::{CurveKind, Profile, SolveReport, find_profiles}; @@ -179,7 +179,7 @@ pub struct ThreadInfo { pub pitch: f64, pub internal: bool, pub axis_point: Vec3, - pub axis: Vec3, + pub axis: UnitVec3, /// Threaded part along the axis from `axis_point`. pub start: f64, pub end: f64, @@ -365,10 +365,10 @@ fn thread_groove(t: &ThreadInfo, radius: f64, open: (bool, bool)) -> Result Vec<(f64, Vec3, Option } for (f, (d, facet)) in near { let (exact, off) = match kernel::face_surface(&b.body, f as usize) { - Some(kernel::FaceSurface::Plane { normal, point }) => (Some(normal), Some((p - point).dot(normal).abs())), + Some(kernel::FaceSurface::Plane { normal, point }) => (Some(*normal), Some((p - point).dot(normal).abs())), Some(kernel::FaceSurface::Cylinder { origin, axis, .. }) => { let v = p - origin; ((v - axis * v.dot(axis)).normalized(), None) @@ -5805,7 +5805,7 @@ pub fn world_state_reusing(doc: &Document, st: &ModelState, placed_before: &mut let mut t2 = t.clone(); let frame = st.body(&t.body).and_then(|body| doc.model_body_offset(body)).map(|offset| crate::mat_mul(&m, offset)).unwrap_or(m); t2.axis_point = crate::apply_point(&frame, t.axis_point); - t2.axis = crate::apply_vector(&frame, t.axis); + t2.axis = crate::apply_vector(&frame, *t.axis).unit().unwrap_or(t.axis); out.threads.push(t2); } } diff --git a/crates/doc/src/joints_face.rs b/crates/doc/src/joints_face.rs index 9e142b915..35ded52f9 100644 --- a/crates/doc/src/joints_face.rs +++ b/crates/doc/src/joints_face.rs @@ -72,7 +72,7 @@ impl NamedFace<'_> { /// A cylinder of a body's own coordinates placed by the body's (rigid) offset. pub(super) fn placed(m: &Mat, c: CylinderFace) -> CylinderFace { - CylinderFace { axis_point: apply_point(m, c.axis_point), axis: apply_vector(m, c.axis), ..c } + CylinderFace { axis_point: apply_point(m, c.axis_point), axis: apply_vector(m, *c.axis).unit().unwrap_or(c.axis), ..c } } /// The face across the rim at the `at` end (along the axis) of cylinder `c`, face `face` of `b` diff --git a/crates/doc/src/sheet_convert.rs b/crates/doc/src/sheet_convert.rs index 660dae183..f64dc4f36 100644 --- a/crates/doc/src/sheet_convert.rs +++ b/crates/doc/src/sheet_convert.rs @@ -50,7 +50,7 @@ use std::collections::BTreeMap; use std::f64::consts::{FRAC_PI_2, PI, TAU}; -use solidcraft_geom::{Loop2, Mesh, Plane, Region2, Seg2, Vec2, Vec3}; +use solidcraft_geom::{Loop2, Mesh, Plane, Region2, Seg2, UnitVec3, Vec2, Vec3}; use solidcraft_kernel::{Body, FaceSurface, face_surface}; use super::{FlatWork, ReliefOverride, RuleValues, SheetBody, SheetFlange, base_flange, point_in, polys_cross, signed_area, snap}; @@ -71,7 +71,7 @@ fn at(p: Vec3) -> String { /// arc where that face is a round wall (`round[i]`: the circle's centre and the arc's middle). /// `holes`: its inner loops, in `plane`, each with the faces of its walls. struct Face { - n: Vec3, + n: UnitVec3, pts: Vec, across: Vec>, round: Vec>, @@ -89,7 +89,7 @@ struct Panel { } /// Area of a loop in space, positive when it runs counter-clockwise about `n`. -fn area_about(pts: &[Vec3], n: Vec3) -> f64 { +fn area_about(pts: &[Vec3], n: UnitVec3) -> f64 { let Some(&o) = pts.first() else { return 0.0 }; pts.windows(2).map(|w| (w[0] - o).cross(w[1] - o).dot(n)).sum::() / 2.0 } @@ -227,7 +227,7 @@ fn outline(b: &Body, mesh: &Mesh, f: usize, tol: f64) -> Result { loops.push(lp); } let mut walls = std::collections::HashMap::new(); - let mut wall = |g: u32| *walls.entry(g).or_insert_with(|| round_wall(b, &plane, n, g)); + let mut wall = |g: u32| *walls.entry(g).or_insert_with(|| round_wall(b, &plane, *n, g)); // Each loop with the faces of its walls. let mut shaped: Vec<(Vec<(Seg2, Option)>, Vec)> = loops .iter() @@ -388,7 +388,7 @@ fn bend_cylinder(b: &Body, mesh: &Mesh, f: usize, tol: f64) -> Option { let Some(FaceSurface::Plane { normal: n, .. }) = face_surface(b, g) else { continue }; let radial = (p - origin) - axis * (p - origin).dot(axis); if radial.normalized().is_some_and(|out| n.dot(out).abs() >= 1.0 - 1e-6) { - sides.push((g, n)); + sides.push((g, *n)); } } let &[(a, na), (bb, nb)] = sides.as_slice() else { return None }; diff --git a/crates/engine/src/cmd/component_transfer_tests.rs b/crates/engine/src/cmd/component_transfer_tests.rs index a47dd7379..75d9a103f 100644 --- a/crates/engine/src/cmd/component_transfer_tests.rs +++ b/crates/engine/src/cmd/component_transfer_tests.rs @@ -148,10 +148,10 @@ fn transferred_thread_follows_body_frame_without_changing_world_axis() { run(&mut s, "component.move_bodies", json!({"component":to,"bodies":["Shaft"]})); let after = s.world_state().threads[0].clone(); assert!(after.axis_point.dist(before.axis_point) < 1e-6); - assert!(after.axis.dist(before.axis) < 1e-6); + assert!(after.axis.dist(*before.axis) < 1e-6); let mut reopened = Session { doc: solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap().into(), ..Session::default() }; reopened.refresh(); - assert!(reopened.world_state().threads[0].axis.dist(before.axis) < 1e-6); + assert!(reopened.world_state().threads[0].axis.dist(*before.axis) < 1e-6); } #[test] diff --git a/crates/engine/src/cmd/measure_sel.rs b/crates/engine/src/cmd/measure_sel.rs index 18da943c9..8927abb74 100644 --- a/crates/engine/src/cmd/measure_sel.rs +++ b/crates/engine/src/cmd/measure_sel.rs @@ -5,7 +5,7 @@ //! have a direction (planar faces, straight edges), the angle. use serde_json::{Value, json}; -use solidcraft_geom::{Mesh, Vec3}; +use solidcraft_geom::{Mesh, UnitVec3, Vec3}; use super::measure_shape::{Shape, Slot, add_round, centre}; use crate::params::bad; @@ -84,7 +84,7 @@ struct Item { /// The circle through a polyline's points (all on one within `tol`): a fallback for edges the /// kernel can't name (mesh bodies). -fn fit_circle(pts: &[Vec3], tol: f64) -> Option<(Vec3, Vec3, f64)> { +fn fit_circle(pts: &[Vec3], tol: f64) -> Option<(Vec3, UnitVec3, f64)> { let n = pts.len().checked_sub(1)?; let (a, b, c) = (*pts.first()?, *pts.get(n / 3)?, *pts.get(2 * n / 3)?); let (u, v) = (b - a, c - a); @@ -93,7 +93,7 @@ fn fit_circle(pts: &[Vec3], tol: f64) -> Option<(Vec3, Vec3, f64)> { return None; } let center = a + (v * u.len2() - u * v.len2()).cross(w) * (1.0 / (2.0 * w.len2())); - let axis = w.normalized()?; + let axis = w.unit()?; let radius = center.dist(a); let on = pts.iter().all(|p| (p.dist(center) - radius).abs() <= tol && (*p - center).dot(axis).abs() <= tol); (on && radius.is_finite()).then_some((center, axis, radius)) @@ -123,7 +123,7 @@ fn edge_round(b: &solidcraft_doc::ModelBody, m: &Mesh, index: usize, whole: bool } /// Points along a circle or arc (`angle` from `start` about `axis`). -fn arc_points(center: Vec3, axis: Vec3, start: Vec3, angle: f64) -> Vec { +fn arc_points(center: Vec3, axis: UnitVec3, start: Vec3, angle: f64) -> Vec { let x = start - center; let y = axis.cross(x); let n = 128; @@ -157,7 +157,7 @@ fn sketch_curve(ss: &solidcraft_doc::SolvedSketch, id: &str) -> Option { let sk = &ss.sketch; let c = sk.curves.get(sk.curve_index(id)?)?; let at = |i: usize| sk.points.get(i).map(|p| ss.plane.to_world(p.pos)); - let normal = ss.plane.normal(); + let normal = ss.plane.normal().unit()?; let (shape, pts) = match c.kind { CurveKind::Circle { c, r } => { let center = at(c)?; @@ -203,7 +203,7 @@ fn profile(ss: &solidcraft_doc::SolvedSketch, index: usize) -> Option { let pr = ss.profiles.get(index)?; let outline: Vec = pr.region.outer.polyline(1e-3).iter().map(|p| ss.plane.to_world(*p)).collect(); let mut json = json!({"type": "profile", "area_mm2": pr.region.area()}); - let normal = ss.plane.normal(); + let normal = ss.plane.normal().unit()?; // Arcs about one centre merge (a circle is two halves); straight pieces stay as they are. let mut arcs: Vec<(Vec2, f64, f64)> = Vec::new(); let mut lines: Vec<(Vec2, Vec2)> = Vec::new(); @@ -242,7 +242,7 @@ fn profile(ss: &solidcraft_doc::SolvedSketch, index: usize) -> Option { slot = Some(s); } } - let planar = Some(normal); + let planar = Some(*normal); let geo = Geo::Points(densify(&outline)); let shape = if matches!(shape, Shape::Other) { Shape::Plane { point: ss.plane.origin, normal } } else { shape }; Some(Item { geo, dir: planar, json, shape, slot }) @@ -308,7 +308,7 @@ fn describe(s: &Session, sel: &Sel) -> Option { let patch = m.surface_patch(*index); let tris = patch.iter().flat_map(|f| face_tris(&m, *f)).collect::>(); let area: f64 = tris.iter().map(|[a, b, c]| (*b - *a).cross(*c - *a).len() * 0.5).sum(); - let normals: Vec = tris.iter().filter_map(|[a, b, c]| (*b - *a).cross(*c - *a).normalized()).collect(); + let normals: Vec = tris.iter().filter_map(|[a, b, c]| (*b - *a).cross(*c - *a).unit()).collect(); let planar = normals.first().copied().filter(|n0| normals.iter().all(|n| n.dot(*n0) > 1.0 - 1e-6)); let mut json = json!({"type": "face", "area_mm2": area, "planar": planar.is_some()}); let verts: Vec = tris.iter().flat_map(|t| t.iter().copied()).collect(); @@ -328,7 +328,7 @@ fn describe(s: &Session, sel: &Sel) -> Option { if let Some(sl) = &slot { json["slot"] = sl.json(); } - Some(Item { geo: Geo::Tris(tris), dir: planar, json, shape, slot }) + Some(Item { geo: Geo::Tris(tris), dir: planar.map(Vec3::from), json, shape, slot }) } Sel::Body { name } => { let m = st.body(name)?.mesh(); diff --git a/crates/engine/src/cmd/measure_shape.rs b/crates/engine/src/cmd/measure_shape.rs index 00f958c86..71fb6904a 100644 --- a/crates/engine/src/cmd/measure_shape.rs +++ b/crates/engine/src/cmd/measure_shape.rs @@ -4,7 +4,7 @@ //! round item measures from its centre or axis, with the closest and farthest distances too. use serde_json::{Value, json}; -use solidcraft_geom::Vec3; +use solidcraft_geom::{UnitVec3, Vec3}; use std::f64::consts::{PI, TAU}; @@ -17,7 +17,7 @@ pub(crate) enum Shape { /// around the axis (2π all the way round). Round { center: Vec3, - axis: Vec3, + axis: UnitVec3, radius: f64, angle: f64, planar: bool, @@ -26,7 +26,7 @@ pub(crate) enum Shape { }, Plane { point: Vec3, - normal: Vec3, + normal: UnitVec3, }, Line { a: Vec3, @@ -70,8 +70,7 @@ pub(crate) fn add_round(v: &mut Value, shape: &Shape) { /// Cylinder `axis` through `origin` of radius `radius` over the points of its face: the /// round shape, centred level with the middle of the face, with its extent and coverage. -pub(crate) fn cylinder(origin: Vec3, axis: Vec3, radius: f64, pts: &[Vec3]) -> Option { - let axis = axis.normalized()?; +pub(crate) fn cylinder(origin: Vec3, axis: UnitVec3, radius: f64, pts: &[Vec3]) -> Option { if pts.is_empty() || !(radius.is_finite() && radius > 0.0) { return None; } @@ -83,7 +82,7 @@ pub(crate) fn cylinder(origin: Vec3, axis: Vec3, radius: f64, pts: &[Vec3]) -> O } /// The angle around the axis the points cover: a whole turn less the widest gap between them. -pub(crate) fn coverage(center: Vec3, axis: Vec3, pts: &[Vec3]) -> f64 { +pub(crate) fn coverage(center: Vec3, axis: UnitVec3, pts: &[Vec3]) -> f64 { let x = axis.any_perp(); let y = axis.cross(x); let mut angles: Vec = pts @@ -105,7 +104,7 @@ pub(crate) fn coverage(center: Vec3, axis: Vec3, pts: &[Vec3]) -> f64 { } /// The unit direction a point leaves the axis at, towards the middle of the face's points. -fn bulge(center: Vec3, axis: Vec3, pts: &[Vec3]) -> Option { +fn bulge(center: Vec3, axis: UnitVec3, pts: &[Vec3]) -> Option { let sum = pts.iter().fold(Vec3::ZERO, |acc, p| { let d = *p - center; acc + (d - axis * d.dot(axis)).normalized().unwrap_or(Vec3::ZERO) @@ -114,7 +113,7 @@ fn bulge(center: Vec3, axis: Vec3, pts: &[Vec3]) -> Option { } /// Closest points of two infinite lines (a point and a unit direction each). -fn line_line(p1: Vec3, d1: Vec3, p2: Vec3, d2: Vec3) -> (Vec3, Vec3) { +fn line_line(p1: Vec3, d1: UnitVec3, p2: Vec3, d2: UnitVec3) -> (Vec3, Vec3) { let w = p1 - p2; let b = d1.dot(d2); let denom = 1.0 - b * b; @@ -127,8 +126,8 @@ fn line_line(p1: Vec3, d1: Vec3, p2: Vec3, d2: Vec3) -> (Vec3, Vec3) { (p1 + d1 * s, p2 + d2 * t) } -fn parallel(a: Vec3, b: Vec3) -> bool { - a.cross(b).len() < 1e-6 +fn parallel(a: impl Into, b: impl Into) -> bool { + a.into().cross(b).len() < 1e-6 } /// A measurement from a round item's centre or axis. @@ -214,7 +213,7 @@ fn from_round(a: &Shape, b: &Shape) -> Option { } } Shape::Line { a: la, b: lb } => { - let dir = (lb - la).normalized()?; + let dir = (lb - la).unit()?; let across = dir.dot(na).abs() < 1e-6; if pa { // A circle/arc has a fixed centre. Project that point onto the picked @@ -342,7 +341,7 @@ mod tests { use solidcraft_geom::Vec2; fn circle(c: Vec3, r: f64) -> Shape { - Shape::Round { center: c, axis: Vec3::Z, radius: r, angle: TAU, planar: true, lo: 0.0, hi: 0.0 } + Shape::Round { center: c, axis: UnitVec3::Z, radius: r, angle: TAU, planar: true, lo: 0.0, hi: 0.0 } } #[test] @@ -367,8 +366,8 @@ mod tests { #[test] fn arcs_on_different_planes_measure_between_their_centres() { - let a = Shape::Round { center: Vec3::ZERO, axis: Vec3::Z, radius: 2.0, angle: PI, planar: true, lo: 0.0, hi: 0.0 }; - let b = Shape::Round { center: Vec3::new(3.0, 4.0, 12.0), axis: Vec3::X, radius: 4.0, angle: PI / 2.0, planar: true, lo: 0.0, hi: 0.0 }; + let a = Shape::Round { center: Vec3::ZERO, axis: UnitVec3::Z, radius: 2.0, angle: PI, planar: true, lo: 0.0, hi: 0.0 }; + let b = Shape::Round { center: Vec3::new(3.0, 4.0, 12.0), axis: UnitVec3::X, radius: 4.0, angle: PI / 2.0, planar: true, lo: 0.0, hi: 0.0 }; let c = centre(&a, &b).unwrap(); assert_eq!((c.from, c.to, c.distance), (Vec3::ZERO, Vec3::new(3.0, 4.0, 12.0), 13.0)); assert!(c.min.is_none() && c.max.is_none()); @@ -377,10 +376,10 @@ mod tests { #[test] fn a_circle_to_a_cylinder_uses_its_fixed_centre_and_the_cylinders_axis() { let a = circle(Vec3::new(0.0, 0.0, 10.0), 4.0); - for axis in [Vec3::Z, Vec3::X] { + for axis in [UnitVec3::Z, UnitVec3::X] { let b = Shape::Round { center: Vec3::new(34.0, 19.0, 27.0), axis, radius: 4.0, angle: TAU, planar: false, lo: -5.0, hi: 5.0 }; let c = centre(&a, &b).unwrap(); - let expected = if axis == Vec3::Z { Vec3::new(34.0, 19.0, 10.0) } else { Vec3::new(0.0, 19.0, 27.0) }; + let expected = if axis == UnitVec3::Z { Vec3::new(34.0, 19.0, 10.0) } else { Vec3::new(0.0, 19.0, 27.0) }; assert_eq!((c.from, c.to), (Vec3::new(0.0, 0.0, 10.0), expected)); assert!((c.distance - c.from.dist(expected)).abs() < 1e-12); let swapped = centre(&b, &a).unwrap(); @@ -390,8 +389,8 @@ mod tests { #[test] fn two_cylindrical_faces_still_measure_axis_pitch() { - let a = Shape::Round { center: Vec3::new(0.0, 0.0, 5.0), axis: Vec3::Z, radius: 4.0, angle: TAU, planar: false, lo: -5.0, hi: 5.0 }; - let b = Shape::Round { center: Vec3::new(34.0, 19.0, 27.0), axis: Vec3::Z, radius: 4.0, angle: TAU, planar: false, lo: -5.0, hi: 5.0 }; + let a = Shape::Round { center: Vec3::new(0.0, 0.0, 5.0), axis: UnitVec3::Z, radius: 4.0, angle: TAU, planar: false, lo: -5.0, hi: 5.0 }; + let b = Shape::Round { center: Vec3::new(34.0, 19.0, 27.0), axis: UnitVec3::Z, radius: 4.0, angle: TAU, planar: false, lo: -5.0, hi: 5.0 }; let c = centre(&a, &b).unwrap(); assert_eq!((c.from, c.to), (Vec3::new(0.0, 0.0, 5.0), Vec3::new(34.0, 19.0, 5.0))); assert!((c.distance - 1517_f64.sqrt()).abs() < 1e-12); @@ -399,8 +398,8 @@ mod tests { #[test] fn a_cylinder_to_a_side_plane_measures_from_its_axis() { - let cyl = Shape::Round { center: Vec3::new(10.0, 15.0, 5.0), axis: Vec3::Z, radius: 2.5, angle: TAU, planar: false, lo: -5.0, hi: 5.0 }; - let plane = Shape::Plane { point: Vec3::ZERO, normal: Vec3::new(-1.0, 0.0, 0.0) }; + let cyl = Shape::Round { center: Vec3::new(10.0, 15.0, 5.0), axis: UnitVec3::Z, radius: 2.5, angle: TAU, planar: false, lo: -5.0, hi: 5.0 }; + let plane = Shape::Plane { point: Vec3::ZERO, normal: -UnitVec3::X }; let c = centre(&cyl, &plane).unwrap(); assert!((c.distance - 10.0).abs() < 1e-12); assert!((c.min.unwrap() - 7.5).abs() < 1e-12 && (c.max.unwrap() - 12.5).abs() < 1e-12); @@ -408,12 +407,12 @@ mod tests { let d = centre(&plane, &cyl).unwrap(); assert_eq!((d.from, d.to), (c.to, c.from)); // A cylinder crossing a plane has no single axis distance. - assert!(centre(&cyl, &Shape::Plane { point: Vec3::ZERO, normal: Vec3::Z }).is_none()); + assert!(centre(&cyl, &Shape::Plane { point: Vec3::ZERO, normal: UnitVec3::Z }).is_none()); } #[test] fn an_axis_to_a_crossing_edge_is_the_distance_between_the_lines() { - let cyl = Shape::Round { center: Vec3::new(10.0, 15.0, 5.0), axis: Vec3::Z, radius: 2.5, angle: TAU, planar: false, lo: -5.0, hi: 5.0 }; + let cyl = Shape::Round { center: Vec3::new(10.0, 15.0, 5.0), axis: UnitVec3::Z, radius: 2.5, angle: TAU, planar: false, lo: -5.0, hi: 5.0 }; let edge = Shape::Line { a: Vec3::new(0.0, 0.0, 10.0), b: Vec3::new(40.0, 0.0, 10.0) }; let c = centre(&cyl, &edge).unwrap(); assert!((c.distance - 15.0).abs() < 1e-12); @@ -425,7 +424,7 @@ mod tests { fn a_circle_or_arc_to_a_line_keeps_its_real_center() { let edge = Shape::Line { a: Vec3::new(0.0, 0.0, 6.0), b: Vec3::new(68.0, 0.0, 6.0) }; for angle in [TAU, PI / 2.0] { - let round = Shape::Round { center: Vec3::new(34.0, 25.0, 20.0), axis: Vec3::Z, radius: 12.0, angle, planar: true, lo: 0.0, hi: 0.0 }; + let round = Shape::Round { center: Vec3::new(34.0, 25.0, 20.0), axis: UnitVec3::Z, radius: 12.0, angle, planar: true, lo: 0.0, hi: 0.0 }; let c = centre(&round, &edge).unwrap(); assert_eq!((c.from, c.to), (Vec3::new(34.0, 25.0, 20.0), Vec3::new(34.0, 0.0, 6.0))); assert!((c.distance - 25_f64.hypot(14.0)).abs() < 1e-12); @@ -442,7 +441,7 @@ mod tests { #[test] fn a_tilted_arc_to_a_sloped_line_keeps_all_components() { let edge = Shape::Line { a: Vec3::ZERO, b: Vec3::new(6.0, 0.0, 6.0) }; - for axis in [Vec3::X, Vec3::Y, Vec3::Z] { + for axis in [UnitVec3::X, UnitVec3::Y, UnitVec3::Z] { let arc = Shape::Round { center: Vec3::new(3.0, 4.0, 6.0), axis, radius: 2.0, angle: PI, planar: true, lo: 0.0, hi: 0.0 }; let c = centre(&arc, &edge).unwrap(); assert!(c.from.dist(Vec3::new(3.0, 4.0, 6.0)) < 1e-12); @@ -468,8 +467,8 @@ mod tests { let ring = |n: usize, span: f64| -> Vec { (0..=n).map(|i| Vec3::new((span * i as f64 / n as f64).cos(), (span * i as f64 / n as f64).sin(), 0.0)).collect() }; - assert!((coverage(Vec3::ZERO, Vec3::Z, &ring(32, PI)) - PI).abs() < 1e-9); - assert_eq!(coverage(Vec3::ZERO, Vec3::Z, &ring(32, TAU)), TAU); + assert!((coverage(Vec3::ZERO, UnitVec3::Z, &ring(32, PI)) - PI).abs() < 1e-9); + assert_eq!(coverage(Vec3::ZERO, UnitVec3::Z, &ring(32, TAU)), TAU); } #[test] diff --git a/crates/engine/src/display_mesh_tests.rs b/crates/engine/src/display_mesh_tests.rs index d0902eeec..25d717b72 100644 --- a/crates/engine/src/display_mesh_tests.rs +++ b/crates/engine/src/display_mesh_tests.rs @@ -71,7 +71,7 @@ fn a_large_sheet_shows_its_small_bends_and_holes_round() { let (mut bends, mut walls) = (0, 0); for face in 0..b.body.face_count() { let Some(FaceSurface::Cylinder { origin, axis, radius }) = face_surface(&b.body, face) else { continue }; - let (steps, widest) = steps_around(&m, face, origin, axis); + let (steps, widest) = steps_around(&m, face, origin, *axis); assert!(widest <= DISPLAY_ANGLE * 1.001, "radius {radius}: a facet spans {} degrees", widest.to_degrees()); if (radius - 2.0).abs() < 1e-6 { // Half of a hole's wall. diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index f34c852fe..104de3f61 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -27,6 +27,7 @@ pub mod section; pub mod spline_space; pub mod tess; pub mod tspline; +mod unit_vec3; mod vec; pub use arcfit::MAX_FIT_PIECES; @@ -35,6 +36,7 @@ pub use bvh::{Bvh, MeshIndex}; pub use mesh::{Aabb3, BoxedTriangle, InsideIndex, MassProperties, Mesh, MeshMeasure, find_close_pair}; pub use plane::Plane; pub use profile::{Loop2, MAX_BEZIER_CTRL, MAX_BEZIER_DEGREE, MAX_DERIVATIVE_ORDER, Region2, Seg2, bezier, regions_apart}; +pub use unit_vec3::UnitVec3; pub use vec::{Vec2, Vec3}; /// Geometric tolerance for coincidence tests (mm). diff --git a/crates/geom/src/plane.rs b/crates/geom/src/plane.rs index 1d7d882ec..a668e5ae0 100644 --- a/crates/geom/src/plane.rs +++ b/crates/geom/src/plane.rs @@ -31,8 +31,8 @@ impl Plane { } /// Plane through `origin` with normal `n` (in-plane axes chosen deterministically). - pub fn from_normal(origin: Vec3, n: Vec3) -> Option { - let n = n.normalized()?; + pub fn from_normal(origin: Vec3, n: impl Into) -> Option { + let n = n.into().normalized()?; // Horizontal planes keep world X as sketch x; others use the horizontal direction Z × n. let cand = if n.dot(Vec3::Z).abs() > 0.9 { Vec3::X } else { Vec3::Z.cross(n) }; let x = (cand - n * cand.dot(n)).normalized()?; diff --git a/crates/geom/src/unit_vec3.rs b/crates/geom/src/unit_vec3.rs new file mode 100644 index 000000000..450e5e1a8 --- /dev/null +++ b/crates/geom/src/unit_vec3.rs @@ -0,0 +1,120 @@ +//! A unit vector: a 3D vector of length 1. + +use std::ops::{Add, Deref, Mul, Neg, Sub}; + +use serde::{Deserialize, Serialize}; + +use crate::Vec3; + +/// A unit vector: length 1 up to rounding. Made only from a vector with a length +/// ([`UnitVec3::new`], [`Vec3::unit`]), so a function taking one need not normalise it or +/// handle a zero vector again. It reads as the [`Vec3`] it holds (`d.dot(v)`, `*d`), and +/// [`Vec3::dot`] and [`Vec3::cross`] take one. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(into = "Vec3", try_from = "Vec3")] +pub struct UnitVec3(Vec3); + +impl UnitVec3 { + pub const X: UnitVec3 = UnitVec3(Vec3::X); + pub const Y: UnitVec3 = UnitVec3(Vec3::Y); + pub const Z: UnitVec3 = UnitVec3(Vec3::Z); + + /// `v` scaled to length 1; `None` when it has no length (or is not finite). + pub fn new(v: Vec3) -> Option { + v.normalized().map(UnitVec3) + } + pub fn vec(self) -> Vec3 { + self.0 + } +} + +impl Vec3 { + /// This vector scaled to length 1 ([`UnitVec3::new`]). + pub fn unit(self) -> Option { + UnitVec3::new(self) + } +} + +impl Deref for UnitVec3 { + type Target = Vec3; + fn deref(&self) -> &Vec3 { + &self.0 + } +} + +impl From for Vec3 { + fn from(d: UnitVec3) -> Vec3 { + d.0 + } +} + +impl TryFrom for UnitVec3 { + type Error = &'static str; + fn try_from(v: Vec3) -> Result { + UnitVec3::new(v).ok_or("a unit vector needs a finite vector with a length") + } +} + +impl From<&UnitVec3> for Vec3 { + fn from(d: &UnitVec3) -> Vec3 { + d.0 + } +} + +impl Neg for UnitVec3 { + type Output = UnitVec3; + fn neg(self) -> UnitVec3 { + UnitVec3(-self.0) + } +} + +/// `+` and `-` with a [`Vec3`] or another unit vector, giving a [`Vec3`]. +macro_rules! sum_ops { + ($($l:ty, $r:ty);*) => {$( + impl Add<$r> for $l { + type Output = Vec3; + fn add(self, o: $r) -> Vec3 { + Vec3::from(self) + Vec3::from(o) + } + } + impl Sub<$r> for $l { + type Output = Vec3; + fn sub(self, o: $r) -> Vec3 { + Vec3::from(self) - Vec3::from(o) + } + } + )*}; +} +sum_ops!(UnitVec3, Vec3; Vec3, UnitVec3; UnitVec3, UnitVec3); + +impl Mul for UnitVec3 { + type Output = Vec3; + fn mul(self, s: f64) -> Vec3 { + self.0 * s + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_unit_vector_has_length_one() { + let d = Vec3::new(0.0, 3.0, 4.0).unit().unwrap(); + assert_eq!(*d, Vec3::new(0.0, 0.6, 0.8)); + assert_eq!(d * 5.0, Vec3::new(0.0, 3.0, 4.0)); + assert_eq!(*-d, Vec3::new(0.0, -0.6, -0.8)); + assert_eq!(d.dot(Vec3::Z), 0.8); + assert_eq!(UnitVec3::Z.cross(UnitVec3::X), Vec3::Y); + assert_eq!(Vec3::X.dot(d), 0.0); + assert_eq!(Vec3::X + d, Vec3::new(1.0, 0.6, 0.8)); + assert!((d - UnitVec3::Z).dist(Vec3::new(0.0, 0.6, -0.2)) < 1e-15); + } + + #[test] + fn no_length_no_unit_vector() { + assert_eq!(Vec3::ZERO.unit(), None); + assert_eq!(Vec3::new(f64::NAN, 0.0, 1.0).unit(), None); + assert_eq!(Vec3::new(f64::INFINITY, 0.0, 0.0).unit(), None); + } +} diff --git a/crates/geom/src/vec.rs b/crates/geom/src/vec.rs index d18127b55..87c3ec294 100644 --- a/crates/geom/src/vec.rs +++ b/crates/geom/src/vec.rs @@ -96,10 +96,14 @@ impl Vec3 { pub const fn new(x: f64, y: f64, z: f64) -> Self { Vec3 { x, y, z } } - pub fn dot(self, o: Vec3) -> f64 { + /// Takes a [`Vec3`] or a [`UnitVec3`](crate::UnitVec3). + pub fn dot(self, o: impl Into) -> f64 { + let o = o.into(); self.x * o.x + self.y * o.y + self.z * o.z } - pub fn cross(self, o: Vec3) -> Vec3 { + /// Takes a [`Vec3`] or a [`UnitVec3`](crate::UnitVec3). + pub fn cross(self, o: impl Into) -> Vec3 { + let o = o.into(); Vec3::new(self.y * o.z - self.z * o.y, self.z * o.x - self.x * o.z, self.x * o.y - self.y * o.x) } pub fn len(self) -> f64 { diff --git a/crates/kernel/src/bore_guard.rs b/crates/kernel/src/bore_guard.rs index 533cb85a1..2b6651f9e 100644 --- a/crates/kernel/src/bore_guard.rs +++ b/crates/kernel/src/bore_guard.rs @@ -3,14 +3,22 @@ //! cylinder recut from silently removing an additional material boundary that //! the fallback's coarse material samples do not see. use crate::body::{Body, from_p3}; -use solidcraft_geom::{Plane, Seg2, Vec3}; +use solidcraft_geom::{Plane, Seg2, UnitVec3, Vec3}; use std::collections::HashSet; use truck_modeling as mt; -pub(super) fn boundaries_clear(body: &Body, bore_faces: &[usize], origin: Vec3, axis: Vec3, radius: f64, lo: f64, hi: f64, tol: f64) -> Option<()> { +pub(super) fn boundaries_clear( + body: &Body, + bore_faces: &[usize], + origin: Vec3, + axis: UnitVec3, + radius: f64, + lo: f64, + hi: f64, + tol: f64, +) -> Option<()> { let plane = Plane::from_normal(origin, axis)?; if !origin.is_finite() - || !axis.is_finite() || ![radius, lo, hi, tol].iter().all(|v| v.is_finite()) || radius <= tol || hi <= lo diff --git a/crates/kernel/src/bore_union_tests.rs b/crates/kernel/src/bore_union_tests.rs index 3b75567ec..7dd91a1ee 100644 --- a/crates/kernel/src/bore_union_tests.rs +++ b/crates/kernel/src/bore_union_tests.rs @@ -1,6 +1,6 @@ #![allow(clippy::unwrap_used, clippy::panic)] use crate::*; -use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2, Vec3}; +use solidcraft_geom::{Loop2, Plane, Region2, Seg2, UnitVec3, Vec2, Vec3}; fn fixture() -> (Body, Body, Vec3, f64) { let slope = 1f64.to_radians().tan(); @@ -113,7 +113,7 @@ fn unproved_curved_boundary_between_clear_endpoints_refuses_recut() { assert!(a.len() > 5. && b.len() > 5., "endpoint samples miss the interior excursion"); assert!(body.tessellate_with(1e-4, true).unwrap().contains(Vec3::new(4.5, 0., 16.06))); let before = step_export(&[&body], "curved source").unwrap(); - assert!(crate::bore_guard::boundaries_clear(&body, &[], Vec3::ZERO, Vec3::Z, 5., 14., 24., 1e-6).is_none()); + assert!(crate::bore_guard::boundaries_clear(&body, &[], Vec3::ZERO, UnitVec3::Z, 5., 14., 24., 1e-6).is_none()); assert_eq!(step_export(&[&body], "curved source").unwrap(), before); } diff --git a/crates/kernel/src/coaxial_overlap.rs b/crates/kernel/src/coaxial_overlap.rs index 378a4fbec..795e479a2 100644 --- a/crates/kernel/src/coaxial_overlap.rs +++ b/crates/kernel/src/coaxial_overlap.rs @@ -14,7 +14,7 @@ //! band, a hole that is not round all the way, a pin end inside the hole), the overlap is not //! answered here and the caller takes the general boolean. -use solidcraft_geom::{Aabb3, Vec3}; +use solidcraft_geom::{Aabb3, UnitVec3, Vec3}; use crate::body::Body; use crate::{BoolOp, FaceSurface}; @@ -43,7 +43,7 @@ const STEP: f64 = 0.1; struct Wall { faces: Vec, origin: Vec3, - axis: Vec3, + axis: UnitVec3, radius: f64, /// Material inside the cylinder (a pin), not outside it (a hole). boss: bool, @@ -209,7 +209,7 @@ fn cylinders(b: &Body) -> Vec { (0..b.face_count()) .filter_map(|i| match crate::face_surface(b, i)? { FaceSurface::Cylinder { origin, axis, radius } if origin.is_finite() && radius.is_finite() && radius > 0.0 => { - Some(Wall { faces: vec![i], origin, axis: axis.normalized()?, radius, boss: false, spans: Vec::new() }) + Some(Wall { faces: vec![i], origin, axis, radius, boss: false, spans: Vec::new() }) } _ => None, }) diff --git a/crates/kernel/src/coplanar.rs b/crates/kernel/src/coplanar.rs index 801b8a378..da0ffd69c 100644 --- a/crates/kernel/src/coplanar.rs +++ b/crates/kernel/src/coplanar.rs @@ -24,7 +24,7 @@ use std::collections::HashMap; -use solidcraft_geom::{Aabb3, Vec3}; +use solidcraft_geom::{Aabb3, UnitVec3, Vec3}; use truck_modeling::{self as mt, builder}; use crate::body::shell_groups::boxes_separate; @@ -1475,7 +1475,7 @@ fn inset_into(outer: &Body, inner: &Body, outer_operand: usize) -> Option bool) -> return Err(KernelError::Failed("narrowing a bore: an unsound result".into())); } let Some(joined) = crate::ops::boolean(target, &narrowed, BoolOp::Union)? else { return Ok(None) }; - let cut = crate::build::cylinder(at(lo, 0.0, 0.0), c.axis, c.radius, hi - lo)?; + let cut = crate::build::cylinder(at(lo, 0.0, 0.0), *c.axis, c.radius, hi - lo)?; let Some(r) = crate::ops::boolean(&joined, &cut, BoolOp::Cut)? else { return Ok(None) }; let h = recut(&r, &joined, &narrowed, &cut, &bore, tool_operand); Ok(Some(r.with_checked_history(h, &record::counts(&[a, b])))) diff --git a/crates/kernel/src/display_mesh_tests.rs b/crates/kernel/src/display_mesh_tests.rs index 13203e9f8..ca5d94a41 100644 --- a/crates/kernel/src/display_mesh_tests.rs +++ b/crates/kernel/src/display_mesh_tests.rs @@ -4,7 +4,7 @@ use std::collections::HashMap; use std::f64::consts::{FRAC_PI_2, PI, TAU}; -use solidcraft_geom::{Loop2, Mesh, Plane, Region2, Seg2, Vec2, Vec3}; +use solidcraft_geom::{Loop2, Mesh, Plane, Region2, Seg2, UnitVec3, Vec2, Vec3}; use super::{Body, DISPLAY_ANGLE}; use crate::{FaceSurface, extrude, face_surface}; @@ -46,7 +46,7 @@ fn plate_with_holes(centres: &[Vec2], radius: f64) -> Body { } /// The faces of a body on cylinders of this radius. -fn cylinder_faces(b: &Body, radius: f64) -> Vec<(usize, Vec3, Vec3)> { +fn cylinder_faces(b: &Body, radius: f64) -> Vec<(usize, Vec3, UnitVec3)> { (0..b.face_count()) .filter_map(|i| match face_surface(b, i)? { FaceSurface::Cylinder { origin, axis, radius: r } if (r - radius).abs() < 1e-6 => Some((i, origin, axis)), @@ -166,16 +166,16 @@ fn a_small_bend_on_a_large_sheet_is_meshed_round() { assert_eq!(faces.len(), 1, "one bend face of radius {radius}"); let (face, origin, axis) = faces[0]; // The chord tolerance alone: one flat strip from tangent line to tangent line. - assert_eq!(angles_around(&coarse, face, origin, axis).len(), 2, "radius {radius}"); - assert!(sag(&coarse, face, origin, axis, radius) > 0.29 * radius); - let a = angles_around(&round, face, origin, axis); + assert_eq!(angles_around(&coarse, face, origin, *axis).len(), 2, "radius {radius}"); + assert!(sag(&coarse, face, origin, *axis, radius) > 0.29 * radius); + let a = angles_around(&round, face, origin, *axis); assert!(a.len() > facets, "radius {radius}: {} facets across the bend", a.len() - 1); assert!((a[a.len() - 1] - FRAC_PI_2).abs() < 1e-6, "the bend is a quarter turn: {a:?}"); let widest = a.windows(2).map(|w| w[1] - w[0]).fold(0.0, f64::max); assert!(widest <= DISPLAY_ANGLE * 1.001, "radius {radius}: a facet spans {} degrees", widest.to_degrees()); // Within the chord tolerance of the cylinder, and by much: a facet that turns no more // than the angle sags no more than 1 - cos(angle / 2) of the radius. - let s = sag(&round, face, origin, axis, radius); + let s = sag(&round, face, origin, *axis, radius); assert!(s <= radius * (1.0 - (DISPLAY_ANGLE / 2.0).cos()) * 1.001 && s < tol, "radius {radius}: sag {s}"); } // The flat faces along the sheet meet the bends in straight lines and need nothing more: @@ -236,9 +236,9 @@ fn a_small_hole_on_a_large_plate_has_a_round_rim() { } // The hole's wall follows its rims. for (face, origin, axis) in cylinder_faces(&b, 2.0) { - let a = angles_around(&round, face, origin, axis); + let a = angles_around(&round, face, origin, *axis); assert!(a.windows(2).map(|w| w[1] - w[0]).fold(0.0, f64::max) <= DISPLAY_ANGLE * 1.001); - assert!(sag(&round, face, origin, axis, 2.0) <= 2.0 * (1.0 - (DISPLAY_ANGLE / 2.0).cos()) * 1.001); + assert!(sag(&round, face, origin, *axis, 2.0) <= 2.0 * (1.0 - (DISPLAY_ANGLE / 2.0).cos()) * 1.001); } assert_eq!(open_sides(&round, 1e-6), 0); } diff --git a/crates/kernel/src/issue_788_tests.rs b/crates/kernel/src/issue_788_tests.rs index 20e048d19..f12492352 100644 --- a/crates/kernel/src/issue_788_tests.rs +++ b/crates/kernel/src/issue_788_tests.rs @@ -120,7 +120,7 @@ fn crossings_that_are_not_touching_are_left_alone() { let r = 10.0; let size = 100.0; let tol = size * 1e-6; - let cyl = |face, origin: Vec3, axis: Vec3, radius| tangent_cylinders::Cylinder::new(face, origin, axis, radius); + let cyl = |face, origin: Vec3, axis: Vec3, radius| tangent_cylinders::Cylinder::new(face, origin, axis, radius).unwrap(); let z = cyl(0, Vec3::ZERO, Vec3::Z, r); // Different radius, parallel axes, skew axes: no touching points to split at. assert!(tangent_cylinders::crossing(&z, &cyl(1, Vec3::ZERO, Vec3::Y, r * 0.9), tol).is_none()); @@ -137,13 +137,14 @@ fn crossings_that_are_not_touching_are_left_alone() { fn hostile_cylinders_are_refused() { let tol = 1e-4; let cyl = |axis: Vec3, radius, origin: Vec3| tangent_cylinders::Cylinder::new(0, origin, axis, radius); - let good = cyl(Vec3::Z, 10.0, Vec3::ZERO); + // An axis with no direction cannot make a cylinder at all. + assert!(cyl(Vec3::new(f64::NAN, 0.0, 1.0), 10.0, Vec3::ZERO).is_none()); + assert!(cyl(Vec3::ZERO, 10.0, Vec3::ZERO).is_none()); + let good = cyl(Vec3::Z, 10.0, Vec3::ZERO).unwrap(); for bad in [ - cyl(Vec3::new(f64::NAN, 0.0, 1.0), 10.0, Vec3::ZERO), - cyl(Vec3::Y, f64::NAN, Vec3::ZERO), - cyl(Vec3::Y, f64::INFINITY, Vec3::ZERO), - cyl(Vec3::Y, 10.0, Vec3::new(f64::INFINITY, 0.0, 0.0)), - cyl(Vec3::ZERO, 10.0, Vec3::ZERO), + cyl(Vec3::Y, f64::NAN, Vec3::ZERO).unwrap(), + cyl(Vec3::Y, f64::INFINITY, Vec3::ZERO).unwrap(), + cyl(Vec3::Y, 10.0, Vec3::new(f64::INFINITY, 0.0, 0.0)).unwrap(), ] { assert!(tangent_cylinders::crossing(&good, &bad, tol).is_none(), "{bad:?}"); } diff --git a/crates/kernel/src/seam_faces.rs b/crates/kernel/src/seam_faces.rs index d2ec90444..e68948381 100644 --- a/crates/kernel/src/seam_faces.rs +++ b/crates/kernel/src/seam_faces.rs @@ -36,7 +36,6 @@ fn next_split(body: &Body) -> Option<(usize, Plane)> { FaceSurface::Cone { apex, axis, .. } => (apex, axis), _ => return None, }; - let axis = axis.normalized()?; let p = from_p3(seam.front().point()); let off = p - origin; let radial: Vec3 = (off - axis * off.dot(axis)).normalized()?; diff --git a/crates/kernel/src/splitface.rs b/crates/kernel/src/splitface.rs index 6ea125855..9afee8616 100644 --- a/crates/kernel/src/splitface.rs +++ b/crates/kernel/src/splitface.rs @@ -9,7 +9,7 @@ use std::collections::HashMap; use mt::{BoundedCurve, InnerSpace, MetricSpace, ParametricCurve, ParametricSurface, ParametricSurface3D, SearchNearestParameter}; -use solidcraft_geom::{Plane, Seg2, Vec2, Vec3}; +use solidcraft_geom::{Plane, Seg2, UnitVec3, Vec2, Vec3}; use truck_meshalgo::tessellation::RobustMeshableShape; use truck_modeling as mt; @@ -41,7 +41,7 @@ enum Field { /// +1 when the tool's normal points away from the axis. Cylinder { o: Vec3, - axis: Vec3, + axis: UnitVec3, r: f64, out: f64, }, @@ -464,7 +464,7 @@ fn fit_on(g: &Field, face: &mt::Face, pts: &[mt::Point3], scale: f64) -> Result< && a.distance(*b) > scale * 1e-9 { let n = pl.normal(); - if n.cross(crate::body::v3(*axis)).magnitude() < 1e-9 { + if n.cross(crate::body::v3(axis.vec())).magnitude() < 1e-9 { let (va, vb) = (mt::Vertex::new(*a), mt::Vertex::new(*b)); let e = guard("split arc", || Ok(mt::builder::circle_arc(&va, &vb, *m)))?; return Ok(e.curve()); @@ -908,7 +908,7 @@ fn surface_field(s: &mt::Surface) -> Field { for along_v in [true, false] { let pt = |t: f64, w: f64| if along_v { at(t, w) } else { at(w, t) }; let d = pt(0.0, 1.0) - pt(0.0, 0.0); - let Some(axis) = d.normalized() else { continue }; + let Some(axis) = d.unit() else { continue }; let straight = (0..=6).all(|k| { let t = k as f64 / 6.0; (0..=4).all(|m| (pt(t, m as f64 / 4.0) - pt(t, 0.0) - d * (m as f64 / 4.0)).len() <= tol) @@ -940,7 +940,7 @@ fn surface_field(s: &mt::Surface) -> Field { /// A plane or circular cylinder behind a surface (for offsetting). pub(crate) enum Analytic { Plane { n: Vec3 }, - Cylinder { o: Vec3, axis: Vec3, r: f64, out: f64 }, + Cylinder { o: Vec3, axis: UnitVec3, r: f64, out: f64 }, } pub(crate) fn analytic_field(s: &mt::Surface) -> Option { @@ -998,9 +998,12 @@ fn fields(tool: &SplitTool) -> Result> { let n = plane.normal().cross(wb - wa).normalized().ok_or_else(|| KernelError::Invalid("a zero-length split line".into()))?; Field::Plane { o: wa, n } } - [Seg2::Arc { center, radius, .. }] if radius.is_finite() && *radius > 0.0 => { - Field::Cylinder { o: plane.to_world(*center), axis: plane.normal(), r: *radius, out: 1.0 } - } + [Seg2::Arc { center, radius, .. }] if radius.is_finite() && *radius > 0.0 => Field::Cylinder { + o: plane.to_world(*center), + axis: plane.normal().unit().ok_or_else(|| KernelError::Invalid("a sketch plane with no normal".into()))?, + r: *radius, + out: 1.0, + }, segs => { let mut pts: Vec = Vec::new(); for sg in segs { @@ -1265,7 +1268,7 @@ pub fn split_body(body: &Body, tool: &SplitTool) -> Result> { let x = (if axis.x.abs() < 0.9 { Vec3::X } else { Vec3::Y }).cross(*axis).normalized().unwrap_or(Vec3::X); let (a, b) = (*o + *axis * lo + x * *r, *o + *axis * hi + x * *r); let line = mt::Curve::Line(mt::Line(p3(a), p3(b))); - crate::step_in::geom::revolved_oriented(line, p3(*o), crate::body::v3(*axis), 0.5, crate::body::v3(x * *out)) + crate::step_in::geom::revolved_oriented(line, p3(*o), crate::body::v3(axis.vec()), 0.5, crate::body::v3(x * *out)) } Field::Surface(s) => s.clone(), Field::Curve { .. } => return Err(KernelError::Invalid("a body is split by a plane or a face".into())), diff --git a/crates/kernel/src/surface_extend.rs b/crates/kernel/src/surface_extend.rs index 20d12c22d..202bd1c3b 100644 --- a/crates/kernel/src/surface_extend.rs +++ b/crates/kernel/src/surface_extend.rs @@ -26,8 +26,8 @@ use std::collections::HashMap; use mt::{BoundedCurve, ParametricCurve, ParametricSurface}; -use solidcraft_geom::Vec3; use solidcraft_geom::tess::EvalSurface; +use solidcraft_geom::{UnitVec3, Vec3}; use truck_modeling as mt; use crate::body::{Body, from_p3, p3}; @@ -145,9 +145,9 @@ struct Local { /// Its parameters on the surface (unwrapped along the loop). q: [f64; 2], /// The surface's unit normal (`S_u × S_v`, as the parameters run). - n: Vec3, + n: UnitVec3, /// The edge's unit direction as the loop runs, in the tangent plane. - d: Vec3, + d: UnitVec3, /// Unit, in the tangent plane, square to the edge, away from the face. out: Vec3, su: Vec3, @@ -247,7 +247,7 @@ impl Frame { let n = normal(su, sv)?; let dc = curve.der(t); let dc = Vec3::new(dc.x, dc.y, dc.z); - let d = (dc - n * dc.dot(n)).normalized().ok_or_else(|| KernelError::Invalid("an edge to extend has no direction".into()))?; + let d = (dc - n * dc.dot(n)).unit().ok_or_else(|| KernelError::Invalid("an edge to extend has no direction".into()))?; Ok(Local { p, q, n, d, out: d.cross(n) * self.ccw, su, sv }) } @@ -262,12 +262,12 @@ impl Frame { } /// The unit normal from the parameter derivatives; refused at a pole (where it has none). -fn normal(su: Vec3, sv: Vec3) -> Result { +fn normal(su: Vec3, sv: Vec3) -> Result { let c = su.cross(sv); if !(c.len() > 1e-12 * (su.len2() + sv.len2())) { return Err(KernelError::Invalid("the extension runs into a pole of the surface (a point with no normal)".into())); } - c.normalized().ok_or_else(|| KernelError::Invalid("the extension runs into a pole of the surface".into())) + c.unit().ok_or_else(|| KernelError::Invalid("the extension runs into a pole of the surface".into())) } /// The parameter step `(a, b)` with `a·S_u + b·S_v = w` for `w` in the tangent plane, its @@ -392,11 +392,11 @@ impl<'a> Extension<'a> { .ok_or_else(|| KernelError::Invalid("two extended edges turn back on each other at a corner".into()))?; (r, None) } else if pc { - if !self.opts.neighbours || smooth { (prev.out, None) } else { (-next.d, Some(i)) } + if !self.opts.neighbours || smooth { (prev.out, None) } else { ((-next.d).vec(), Some(i)) } } else if !self.opts.neighbours || smooth { (next.out, None) } else { - (prev.d, Some(pi)) + (prev.d.vec(), Some(pi)) }; for (chosen, l) in [(pc, &prev), (nc, &next)] { if chosen && r.dot(l.out) < MIN_COS { @@ -996,7 +996,7 @@ fn arc_param(fr: &Frame, q: [f64; 2], ab: [f64; 2], length: f64) -> Result /// The surface's normal curvature along the tangent `a·S_u + b·S_v` (unit) at `q`, signed /// toward `n`. -fn normal_curvature(s: &mt::Surface, q: [f64; 2], ab: [f64; 2], n: Vec3) -> f64 { +fn normal_curvature(s: &mt::Surface, q: [f64; 2], ab: [f64; 2], n: UnitVec3) -> f64 { let (uu, uv, vv) = (s.uuder(q[0], q[1]), s.uvder(q[0], q[1]), s.vvder(q[0], q[1])); let second = uu * (ab[0] * ab[0]) + uv * (2.0 * ab[0] * ab[1]) + vv * (ab[1] * ab[1]); let k = Vec3::new(second.x, second.y, second.z).dot(n); diff --git a/crates/kernel/src/surface_kind.rs b/crates/kernel/src/surface_kind.rs index 5f5cb47f8..ee72bf1cd 100644 --- a/crates/kernel/src/surface_kind.rs +++ b/crates/kernel/src/surface_kind.rs @@ -1,7 +1,7 @@ //! What surface a face lies on (plane, cylinder, cone, sphere, torus), for construction //! geometry: axes through round faces, centres of spheres and tori. -use solidcraft_geom::Vec3; +use solidcraft_geom::{UnitVec3, Vec3}; use truck_modeling as mt; @@ -9,23 +9,23 @@ use crate::Body; use crate::body::from_p3; use crate::offset::{Surf, surf_of}; -/// A face's analytic surface. Axes are unit vectors. +/// A face's analytic surface. #[derive(Clone, Copy, Debug, PartialEq)] pub enum FaceSurface { /// Outward unit normal and a point on the plane. Plane { - normal: Vec3, + normal: UnitVec3, point: Vec3, }, Cylinder { origin: Vec3, - axis: Vec3, + axis: UnitVec3, radius: f64, }, /// Apex, axis pointing into the cone, half-angle (radians). Cone { apex: Vec3, - axis: Vec3, + axis: UnitVec3, half_angle: f64, }, Sphere { @@ -35,7 +35,7 @@ pub enum FaceSurface { /// Centre of the ring, its axis, the ring (major) and tube (minor) radii. Torus { center: Vec3, - axis: Vec3, + axis: UnitVec3, major: f64, minor: f64, }, @@ -50,11 +50,11 @@ pub fn face_surface(b: &Body, face: usize) -> Option { pub(crate) fn surface_of(f: &mt::Face, size: f64) -> Option { let tol = (size * 1e-7).max(1e-9) * 100.0; Some(match surf_of(f, tol)? { - Surf::Plane { n, d } => FaceSurface::Plane { normal: n, point: n * d }, - Surf::Cylinder { o, a, r, .. } => FaceSurface::Cylinder { origin: o, axis: a, radius: r }, - Surf::Cone { v, a, half, .. } => FaceSurface::Cone { apex: v, axis: a, half_angle: half }, + Surf::Plane { n, d } => FaceSurface::Plane { normal: n.unit()?, point: n * d }, + Surf::Cylinder { o, a, r, .. } => FaceSurface::Cylinder { origin: o, axis: a.unit()?, radius: r }, + Surf::Cone { v, a, half, .. } => FaceSurface::Cone { apex: v, axis: a.unit()?, half_angle: half }, Surf::Sphere { c, r, .. } => FaceSurface::Sphere { center: c, radius: r }, - Surf::Torus { o, a, big, h, r, .. } => FaceSurface::Torus { center: o + a * h, axis: a, major: big, minor: r }, + Surf::Torus { o, a, big, h, r, .. } => FaceSurface::Torus { center: o + a * h, axis: a.unit()?, major: big, minor: r }, }) } @@ -62,8 +62,8 @@ pub(crate) fn surface_of(f: &mt::Face, size: f64) -> Option { #[derive(Clone, Copy, Debug, PartialEq)] pub struct EdgeCircle { pub center: Vec3, - /// Unit normal of the circle's plane, oriented so the edge runs counter-clockwise about it. - pub axis: Vec3, + /// Normal of the circle's plane, oriented so the edge runs counter-clockwise about it. + pub axis: UnitVec3, pub radius: f64, /// The edge's ends (the same point for a closed circle). pub start: Vec3, @@ -106,7 +106,7 @@ fn circle_through(s: &[Vec3], tol: f64) -> Option { return None; } let center = a + (v * u.len2() - u * v.len2()).cross(w) * (1.0 / (2.0 * w.len2())); - let axis = w.normalized()?; + let axis = w.unit()?; let radius = center.dist(a); if !(radius.is_finite() && radius > tol) || s.iter().any(|p| (p.dist(center) - radius).abs() > tol || (*p - center).dot(axis).abs() > tol) { return None; @@ -132,7 +132,7 @@ fn circle_through(s: &[Vec3], tol: f64) -> Option { angle += d; last = t; } - let (axis, angle) = if angle < 0.0 { (axis * -1.0, -angle) } else { (axis, angle) }; + let (axis, angle) = if angle < 0.0 { (-axis, -angle) } else { (axis, angle) }; let angle = if closed { std::f64::consts::TAU } else { angle.min(std::f64::consts::TAU) }; Some(EdgeCircle { center, axis, radius, start, end, angle }) } @@ -180,19 +180,19 @@ mod tests { /// Each surface's nearest point, worked out by hand. #[test] fn the_nearest_point_of_each_surface() { - let plane = FaceSurface::Plane { normal: Vec3::Z, point: Vec3::new(0.0, 0.0, 4.0) }; + let plane = FaceSurface::Plane { normal: UnitVec3::Z, point: Vec3::new(0.0, 0.0, 4.0) }; assert!(near(plane.nearest(Vec3::new(3.0, 5.0, 9.0)), Vec3::new(3.0, 5.0, 4.0))); // A cylinder of radius 5 about the line x = 1, y = 2: (7, 10, 3) is 10 from it along (3, 4)/5. - let cylinder = FaceSurface::Cylinder { origin: Vec3::new(1.0, 2.0, 0.0), axis: Vec3::Z, radius: 5.0 }; + let cylinder = FaceSurface::Cylinder { origin: Vec3::new(1.0, 2.0, 0.0), axis: UnitVec3::Z, radius: 5.0 }; assert!(near(cylinder.nearest(Vec3::new(7.0, 10.0, 3.0)), Vec3::new(4.0, 6.0, 3.0))); assert!(cylinder.nearest(Vec3::new(1.0, 2.0, 3.0)).is_none(), "on the axis every direction is as near"); let sphere = FaceSurface::Sphere { center: Vec3::new(1.0, 2.0, 3.0), radius: 5.0 }; assert!(near(sphere.nearest(Vec3::new(1.0, 2.0, 13.0)), Vec3::new(1.0, 2.0, 8.0))); // A torus of ring radius 10 and tube radius 2 about Z: (14, 0, 0) is 2 beyond the tube's outside. - let torus = FaceSurface::Torus { center: Vec3::ZERO, axis: Vec3::Z, major: 10.0, minor: 2.0 }; + let torus = FaceSurface::Torus { center: Vec3::ZERO, axis: UnitVec3::Z, major: 10.0, minor: 2.0 }; assert!(near(torus.nearest(Vec3::new(14.0, 0.0, 0.0)), Vec3::new(12.0, 0.0, 0.0))); // A cone of half-angle 45 degrees: (2, 0, 0) is √2 along its line (1, 0, 1)/√2. - let cone = FaceSurface::Cone { apex: Vec3::ZERO, axis: Vec3::Z, half_angle: std::f64::consts::FRAC_PI_4 }; + let cone = FaceSurface::Cone { apex: Vec3::ZERO, axis: UnitVec3::Z, half_angle: std::f64::consts::FRAC_PI_4 }; assert!(cone.nearest(Vec3::new(2.0, 0.0, 0.0)).is_some_and(|q| q.dist(Vec3::new(1.0, 0.0, 1.0)) < 1e-12)); assert!(plane.nearest(Vec3::new(f64::NAN, 0.0, 0.0)).is_none()); } diff --git a/crates/kernel/src/surfaces.rs b/crates/kernel/src/surfaces.rs index 70f86215e..b7c0ed015 100644 --- a/crates/kernel/src/surfaces.rs +++ b/crates/kernel/src/surfaces.rs @@ -8,7 +8,7 @@ use std::collections::HashMap; use mt::{BoundedCurve, InnerSpace, MetricSpace, ParametricCurve, ParametricSurface3D, SearchNearestParameter}; -use solidcraft_geom::{Plane, Region2, Seg2, Vec2, Vec3}; +use solidcraft_geom::{Plane, Region2, Seg2, UnitVec3, Vec2, Vec3}; use truck_modeling as mt; use crate::body::{Body, from_p3, p3}; @@ -706,7 +706,7 @@ pub fn stitch(bodies: &[&Body], tol: f64) -> Result { #[derive(Clone, Copy)] pub(crate) enum Offset { Plane { n: Vec3 }, - Cylinder { o: Vec3, axis: Vec3, r: f64, out: f64 }, + Cylinder { o: Vec3, axis: UnitVec3, r: f64, out: f64 }, } impl Offset { diff --git a/crates/kernel/src/tangent_cylinders.rs b/crates/kernel/src/tangent_cylinders.rs index c54c94778..7ade4ce60 100644 --- a/crates/kernel/src/tangent_cylinders.rs +++ b/crates/kernel/src/tangent_cylinders.rs @@ -10,7 +10,7 @@ //! through the touching points (the solids are unchanged), and the result's history is composed //! back over the operands as they were given. -use solidcraft_geom::{Plane, Vec3}; +use solidcraft_geom::{Plane, UnitVec3, Vec3}; use truck_modeling::{ParametricCurve, SearchNearestParameter}; use crate::body::{Body, from_p3, p3}; @@ -27,22 +27,23 @@ const MAX_SPLITS: usize = 16; pub(crate) struct Cylinder { face: usize, origin: Vec3, - axis: Vec3, + axis: UnitVec3, radius: f64, } impl Cylinder { #[cfg(test)] - pub(crate) fn new(face: usize, origin: Vec3, axis: Vec3, radius: f64) -> Self { - Self { face, origin, axis, radius } + /// `None` for an axis with no direction. + pub(crate) fn new(face: usize, origin: Vec3, axis: Vec3, radius: f64) -> Option { + Some(Self { face, origin, axis: axis.unit()?, radius }) } } fn cylinders(body: &Body) -> Vec { (0..body.face_count()) .filter_map(|face| match face_surface(body, face)? { - FaceSurface::Cylinder { origin, axis, radius } if origin.is_finite() && axis.is_finite() && radius.is_finite() => { - Some(Cylinder { face, origin, axis: axis.normalized()?, radius }) + FaceSurface::Cylinder { origin, axis, radius } if origin.is_finite() && radius.is_finite() => { + Some(Cylinder { face, origin, axis, radius }) } _ => None, }) @@ -58,12 +59,10 @@ pub(crate) struct Crossing { } pub(crate) fn crossing(x: &Cylinder, y: &Cylinder, tol: f64) -> Option { - let finite = [x, y].iter().all(|c| c.origin.is_finite() && c.axis.is_finite() && c.radius.is_finite() && c.radius > 0.0); + let finite = [x, y].iter().all(|c| c.origin.is_finite() && c.radius.is_finite() && c.radius > 0.0); if !finite || !tol.is_finite() || (x.radius - y.radius).abs() > tol { return None; } - // Unit axes, as the cross product below and the planes take them. - let (x, y) = (&Cylinder { axis: x.axis.normalized()?, ..*x }, &Cylinder { axis: y.axis.normalized()?, ..*y }); let across = x.axis.cross(y.axis); // Axes within a hair of parallel touch along a line, which is another matter. let sine = across.len(); diff --git a/crates/kernel/src/topo.rs b/crates/kernel/src/topo.rs index 0667e546d..eb4dece08 100644 --- a/crates/kernel/src/topo.rs +++ b/crates/kernel/src/topo.rs @@ -8,7 +8,7 @@ use std::collections::{BTreeMap, HashMap}; use serde::Serialize; -use solidcraft_geom::{Mesh, Vec3}; +use solidcraft_geom::{Mesh, UnitVec3, Vec3}; use crate::Result; use crate::body::{Body, from_p3}; @@ -24,7 +24,7 @@ pub struct TopoCounts { #[derive(Clone, Copy, Debug, PartialEq)] enum Surf { Plane { n: Vec3, d: f64 }, - Cylinder { axis: Vec3, p: Vec3, r: f64 }, + Cylinder { axis: UnitVec3, p: Vec3, r: f64 }, Sphere { c: Vec3, r: f64 }, Cone { axis: Vec3, apex: Vec3, cos: f64 }, Other(usize), @@ -97,7 +97,7 @@ fn classify(pts: &[Vec3], nrm: &[Vec3], tol: f64, id: usize) -> Surf { } // Cylinder: all normals perpendicular to one axis. let far = nrm.iter().copied().min_by(|a, b| a.dot(n0).abs().total_cmp(&b.dot(n0).abs())).unwrap_or(n0); - if let Some(axis) = n0.cross(far).normalized() + if let Some(axis) = n0.cross(far).unit() && nrm.iter().all(|n| n.dot(axis).abs() < 2e-3) { let u = axis.any_perp(); @@ -381,10 +381,10 @@ fn classify_faces(b: &Body, mesh: &Mesh, nf: usize, tol: f64) -> Vec { .map(|(i, fit)| match (fit, faces.get(i)) { (Surf::Sphere { .. } | Surf::Other(_), Some(face)) => match crate::offset::surf_of(face, exact_tol) { Some(crate::offset::Surf::Plane { n, d }) => Surf::Plane { n, d }, - Some(crate::offset::Surf::Cylinder { o, a, r, .. }) => { - let axis = if a.x + a.y * 1e-3 + a.z * 1e-6 < 0.0 { -a } else { a }; - Surf::Cylinder { axis, p: o, r } - } + Some(crate::offset::Surf::Cylinder { o, a, r, .. }) => match a.unit() { + Some(a) => Surf::Cylinder { axis: if a.x + a.y * 1e-3 + a.z * 1e-6 < 0.0 { -a } else { a }, p: o, r }, + None => fit, + }, Some(crate::offset::Surf::Sphere { c, r, .. }) => Surf::Sphere { c, r }, _ => fit, }, @@ -636,7 +636,7 @@ pub fn merged_topology(b: &Body, mesh: &Mesh) -> Result { #[derive(Clone, Copy, Debug, PartialEq, serde::Serialize)] pub struct CylinderFace { pub axis_point: Vec3, - pub axis: Vec3, + pub axis: UnitVec3, pub radius: f64, pub start: f64, pub end: f64, @@ -688,7 +688,6 @@ pub fn cylinder_face_at(b: &Body, p: Vec3) -> Option { /// body's). `None` when the face is not part of a cylinder, or has no triangles. pub fn cylinder_face(b: &Body, mesh: &Mesh, face: usize) -> Option { let crate::FaceSurface::Cylinder { origin, axis, radius } = crate::face_surface(b, face)? else { return None }; - let axis = axis.normalized()?; let c = cylinder_extent(mesh, u32::try_from(face).ok()?, axis, origin, radius); (c.start.is_finite() && c.end.is_finite()).then_some(c) } @@ -724,7 +723,7 @@ pub fn cylinder_end_at(b: &Body, p: Vec3) -> Option { } /// The extent along its axis, and the side, of a cylindrical face of a tessellated body. -fn cylinder_extent(mesh: &Mesh, face: u32, axis: Vec3, ap: Vec3, r: f64) -> CylinderFace { +fn cylinder_extent(mesh: &Mesh, face: u32, axis: UnitVec3, ap: Vec3, r: f64) -> CylinderFace { let mut lo = f64::INFINITY; let mut hi = f64::NEG_INFINITY; let mut inward = 0.0; From c177adfceb8d5c7795a4ca9c00975bc8249c4045 Mon Sep 17 00:00:00 2001 From: NOWN-DEV <257771410+NOWN-DEV@users.noreply.github.com> Date: Mon, 19 Oct 2026 03:16:37 +0200 Subject: [PATCH 027/225] Clearance: check a shared volume against the union, allowing for the bodies' measuring error (#2090) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Clearance: check a shared volume against the bodies and their union An intersection can come out well formed and still wrong: one of a mirrored pair of imported parts shared three times the volume of its twin. The shared volume is now compared with vol(a) + vol(b) - vol(a ∪ b), on the same (cut down) bodies; when they differ by more than 1 % (plus the bodies' own measuring error), the pair is reported unchecked with both numbers. Where the union gives no answer, the intersection stands. Co-Authored-By: Claude Opus 5.5 (1M context) * Clearance: let the union cross-check allow for the bodies' measuring error vol(a) + vol(b) - vol(a ∪ b) is a difference of measured volumes and carries the error of all three, so correct small overlaps on large bodies came back unchecked (0.96 mm³ where the union implied -0.75). measure keeps a face's fine tessellation when it is within 1 % of one with a 5 times coarser chord, so a measured volume can be off by up to 0.25 %: the allowance is now 1 % of the larger of the two answers plus 0.25 % of the three volumes. Past it, a union that implies nothing (within that noise of zero, or below it) while the shared part is at most a tenth of the smaller body cannot tell, and the shared part stands. A shared part of 412 mm³ where bodies of a few thousand imply 141 is still caught. Co-Authored-By: Claude Opus 5.5 (1M context) * Clearance: tighten the union check's measuring allowance to 1e-4 The old note cited measure's 1 % gate, which compares face areas, not volumes, and its 0.25 % was about 100 times the disagreement the bodies' measures actually show. The allowance is now justified from volumes: a curved face's chord shortfall cancels between a body and the union except where the chord changes, which stays near 2e-5 of the three volumes; 1e-4 leaves five times that. A 40 mm roller pressed 0.2 mm into a 2 m plate exercises it: with no allowance the pair is left unchecked (7.52 mm³ measured against 8.16 implied), with it the overlap is reported. Co-Authored-By: Claude Opus 5.5 (1M context) --------- Co-authored-by: Claude Opus 5.5 (1M context) Co-authored-by: bherbruck --- crates/engine/src/cmd/clearance.rs | 45 ++++++++++++++- crates/engine/src/cmd/clearance_tests.rs | 71 ++++++++++++++++++++++++ 2 files changed, 115 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/clearance.rs b/crates/engine/src/cmd/clearance.rs index 1752d56ef..14356d0c3 100644 --- a/crates/engine/src/cmd/clearance.rs +++ b/crates/engine/src/cmd/clearance.rs @@ -298,7 +298,14 @@ fn measure_pair( )); return out; } - Ok(m) => out.overlap = Some((m.volume, m.area, m.bbox, m.centroid)), + Ok(m) => { + let (wa, wb) = (ca.as_ref().unwrap_or(&ba.body), cb.as_ref().unwrap_or(&bb.body)); + if let Some(reason) = union_disagrees(wa, wb, m.volume, region.center()) { + out.unchecked = Some(reason); + return out; + } + out.overlap = Some((m.volume, m.area, m.bbox, m.centroid)); + } Err(e) => { out.unchecked = Some(e.to_string()); return out; @@ -375,6 +382,42 @@ fn measure_near_origin(body: &solidcraft_kernel::Body, at: solidcraft_geom::Vec3 Ok(m) } +/// Does the shared volume of `a` and `b` disagree with the one their union implies, +/// vol(a) + vol(b) − vol(a ∪ b)? The intersection can come out well formed and still wrong (a +/// mirrored pair read three times its volume). `None` when they agree, or when the union gives no +/// answer to compare with. +fn union_disagrees(a: &solidcraft_kernel::Body, b: &solidcraft_kernel::Body, shared: f64, at: solidcraft_geom::Vec3) -> Option { + let (union, report) = solidcraft_kernel::capture_boolean_diagnostics(|| solidcraft_kernel::boolean(a, b, solidcraft_kernel::BoolOp::Union)); + let union = union.ok().flatten().filter(|_| report.unverified().is_none())?; + let volume = |x: &solidcraft_kernel::Body| measure_near_origin(x, at).ok().map(|m| m.volume).filter(|v| v.is_finite()); + contradicted(shared, volume(a)?, volume(b)?, volume(&union)?) +} + +/// How far vol(a) + vol(b) − vol(a ∪ b) can stray from the shared volume by measuring alone, +/// as a share of vol(a) + vol(b) + vol(a ∪ b). [`solidcraft_kernel::measure`] facets a curved +/// face with chords of up to 3e-4 of its radius where the radius sets them, which leaves the +/// volume it encloses short by up to (4/3) × 3e-4 = 4e-4. That shortfall is the same for a face +/// measured on its own body and in the union, and cancels in the difference, except where the +/// chord changes with the body measured (it also follows the body's size). Measured, that +/// change stays near 2e-5 of the three volumes: 2.1e-5 for a 40 mm roller pressed 0.2 mm into a +/// 2 m plate (`a_roller_pressed_into_a_large_plate_is_reported`), 2e-5 and 1e-6 in the examples +/// of `the_union_check_allows_for_the_bodies_measuring_error`. This allows five times that. +const VOLUME_NOISE: f64 = 1e-4; + +/// [`union_disagrees`] on measured volumes: `shared` against vol(a) + vol(b) − vol(a ∪ b). +/// That difference of large numbers carries the measuring error of all three, so a small overlap +/// on large bodies can come out near zero or below it: then the union cannot tell, and a shared +/// part small next to both bodies stands. A shared part the union clearly contradicts (412 mm³ +/// where the bodies of a few thousand and their union imply 141) does not. +fn contradicted(shared: f64, va: f64, vb: f64, vu: f64) -> Option { + let implied = va + vb - vu; + let noise = VOLUME_NOISE * (va + vb + vu) + 1e-6; + let allowed = 0.01 * shared.max(implied.abs()) + noise; + let unresolved = implied <= noise && shared <= 0.1 * va.min(vb); + ((implied - shared).abs() > allowed && !unresolved) + .then(|| format!("the shared part measures {shared:.4} mm³ but the bodies and their union imply {implied:.4} mm³, so neither is reported")) +} + /// Is a measured shared part well formed? A part whose shell came out inside out or open can /// carry a volume with its centre outside its own box, or more volume than its box holds. fn plausible(volume: f64, centre: solidcraft_geom::Vec3, bbox: Aabb3) -> bool { diff --git a/crates/engine/src/cmd/clearance_tests.rs b/crates/engine/src/cmd/clearance_tests.rs index 5f1876e7b..57c25f9ed 100644 --- a/crates/engine/src/cmd/clearance_tests.rs +++ b/crates/engine/src/cmd/clearance_tests.rs @@ -251,3 +251,74 @@ fn a_small_gap_past_a_corner_is_not_contact() { assert!((f(&r["nearest"][a][0]["distance_mm"]) - want).abs() < 1e-9, "{a} {b}: {r}"); } } + +/// The shared volume is checked against the bodies and their union: two 10 mm cubes sharing a +/// 3 mm corner cube agree at 27 mm³, and a shared part read as three times that (as a mirrored +/// pair once was) does not. +#[test] +fn a_shared_volume_the_union_contradicts_is_caught() { + use solidcraft_geom::Vec3; + let a = solidcraft_kernel::box_solid(Vec3::new(0.0, 0.0, 0.0), Vec3::new(10.0, 10.0, 10.0)).unwrap_or_else(|e| panic!("{e}")); + let b = solidcraft_kernel::box_solid(Vec3::new(7.0, 7.0, 7.0), Vec3::new(17.0, 17.0, 17.0)).unwrap_or_else(|e| panic!("{e}")); + let at = Vec3::new(8.5, 8.5, 8.5); + assert_eq!(super::union_disagrees(&a, &b, 27.0, at), None); + assert!(super::union_disagrees(&a, &b, 81.0, at).is_some()); +} + +/// The check works on measured volumes, and vol(a) + vol(b) − vol(a ∪ b) carries the error of +/// all three: a small overlap on large bodies can come out near zero, or below it. A union that +/// cannot resolve the shared part leaves it standing; one that clearly contradicts it does not. +#[test] +fn the_union_check_allows_for_the_bodies_measuring_error() { + use super::contradicted; + // 0.96 mm³ shared where the union of 40 000 and 300 mm³ implies -0.75: noise, not a contradiction. + assert_eq!(contradicted(0.96, 40_000.0, 300.0, 40_300.75), None); + // 5.92 mm³ of a small body in a large sheet, with the union 0.4 mm³ off the bodies' sum. + assert_eq!(contradicted(5.92, 250_000.0, 80.0, 250_074.48), None); + // Past the noise, but the union implies nothing at all while the shared part is small next + // to both bodies: the union cannot tell, and the shared part stands. + assert_eq!(contradicted(6.0, 400.0, 200.0, 600.5), None); + // 412 mm³ shared where bodies of a few thousand and their union imply 141: caught. + assert!(contradicted(411.98, 3_200.0, 3_150.0, 6_350.0 - 141.18).is_some()); + // A large shared part the union says is not there at all: caught too. + assert!(contradicted(900.0, 3_200.0, 3_150.0, 6_350.0).is_some()); +} + +/// A small box pressed 0.6 mm into a 2000 × 1000 × 1 mm plate shares 3 × 3 × 0.6 = 5.4 mm³: an +/// overlap, not an unchecked pair. +#[test] +fn a_small_overlap_on_a_large_plate_is_reported() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 2000, "width": 1000, "height": 1, "corner": [0, 0, 0], "operation": "new", "body_name": "Plate"})); + run(&mut s, "solid.box", json!({"length": 3, "width": 3, "height": 3, "corner": [700, 400, 0.4], "operation": "new", "body_name": "Box"})); + let r = run(&mut s, "inspect.clearance", json!({})); + assert_eq!(r["unchecked"].as_array().map(Vec::len), Some(0), "{r}"); + let overlaps = r["overlaps"].as_array().cloned().unwrap_or_default(); + assert_eq!(overlaps.len(), 1, "{r}"); + assert_eq!(pair(&overlaps[0]), ["Box", "Plate"]); + assert!((f(&overlaps[0]["volume_mm3"]) - 5.4).abs() < 1e-6, "{r}"); +} + +/// A 40 mm roller lying on a 2000 × 1000 × 3 mm plate, pressed 0.2 mm into it, shares the +/// circular segment along its 10 mm (7.53 mm³). Its curved wall is faceted differently on its +/// own and in the union, so vol(a) + vol(b) − vol(a ∪ b) comes out 0.64 mm³ over the shared +/// volume (2e-5 of the three volumes, past the 1 % of the shared part): the measuring allowance +/// keeps it an overlap, not an unchecked pair. +#[test] +fn a_roller_pressed_into_a_large_plate_is_reported() { + let (r, depth, length) = (20.0_f64, 0.2_f64, 10.0); + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 2000, "width": 1000, "height": 3, "corner": [0, 0, 0], "operation": "new", "body_name": "Plate"})); + run( + &mut s, + "solid.cylinder", + json!({"radius": r, "height": length, "base": [100, 50, 3.0 + r - depth], "axis": [1, 0, 0], "operation": "new", "body_name": "Roller"}), + ); + let res = run(&mut s, "inspect.clearance", json!({})); + assert_eq!(res["unchecked"].as_array().map(Vec::len), Some(0), "{res}"); + let overlaps = res["overlaps"].as_array().cloned().unwrap_or_default(); + assert_eq!(overlaps.len(), 1, "{res}"); + assert_eq!(pair(&overlaps[0]), ["Plate", "Roller"]); + let want = (r * r * ((r - depth) / r).acos() - (r - depth) * (r * r - (r - depth) * (r - depth)).sqrt()) * length; + assert!((f(&overlaps[0]["volume_mm3"]) - want).abs() < 0.01 * want, "{want} {res}"); +} From 86b2b97d6fbf34a6039812b58b5a00aec066a4aa Mon Sep 17 00:00:00 2001 From: leValdemar19 Date: Mon, 19 Oct 2026 03:16:43 +0200 Subject: [PATCH 028/225] Sketch Offset: constrain to the ends of an offset spline (#2424) (#2615) * claim: #2424 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SBN24y2TcqRcm2zn8Gkj27 * Sketch Offset: constrain to the ends of an offset spline (#2424) An associated offset spline hid all of its generated fit nodes, its two end points included, so nothing snapped to them, and a curve drawn from one shared the node and was refused ("invalid offset output point roles"). - An open offset's end points are shown and snapped to again; its interior fit nodes stay private. - After every sketch edit, a curve that took an offset node gets its own point there, coincident with the node: the offset keeps sole ownership and the curve follows the offset when its source moves. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SBN24y2TcqRcm2zn8Gkj27 * Scenario: lines snap to and close onto an offset spline's ends (#2424) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SBN24y2TcqRcm2zn8Gkj27 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd/features.rs | 4 + crates/engine/src/cmd/offset_ends_tests.rs | 88 +++++++++++++++++++ crates/engine/src/cmd/sketch.rs | 2 + crates/engine/src/view.rs | 9 +- crates/sketch/src/freeform_offset.rs | 29 ++++++ .../scenarios/sketch_offset_spline_ends.json | 22 +++++ docs/book/src/guide/sketching.md | 3 + 7 files changed, 154 insertions(+), 3 deletions(-) create mode 100644 crates/engine/src/cmd/offset_ends_tests.rs create mode 100644 crates/ui-egui/tests/scenarios/sketch_offset_spline_ends.json diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs index b62e8aae1..66fd62490 100644 --- a/crates/engine/src/cmd/features.rs +++ b/crates/engine/src/cmd/features.rs @@ -2188,6 +2188,10 @@ mod offset_identity_tests; #[path = "offset_edit_guard_tests.rs"] mod offset_edit_guard_tests; +#[cfg(test)] +#[path = "offset_ends_tests.rs"] +mod offset_ends_tests; + #[cfg(test)] #[path = "offset_plane_face_tests.rs"] mod offset_plane_face_tests; diff --git a/crates/engine/src/cmd/offset_ends_tests.rs b/crates/engine/src/cmd/offset_ends_tests.rs new file mode 100644 index 000000000..9ebb58dcd --- /dev/null +++ b/crates/engine/src/cmd/offset_ends_tests.rs @@ -0,0 +1,88 @@ +#![allow(clippy::unwrap_used, clippy::panic)] +//! #2424: curves start at the ends of an associated offset spline, and follow them. +use serde_json::{Value, json}; +use solidcraft_doc::Document; +use solidcraft_sketch::{ConstraintKind, CurveKind, Sketch}; + +use crate::Session; + +fn run(s: &mut Session, command: &str, params: Value) -> Value { + s.execute(command, ¶ms).unwrap_or_else(|error| panic!("{command}: {error}")) +} +fn solved(s: &Session, id: u64) -> Sketch { + s.model.state().sketch(id).unwrap().sketch.clone() +} +/// An open fit-point spline `s1` and its associated offset; returns the offset's id. +fn offset_spline(s: &mut Session) -> (u64, String) { + run(s, "sketch.create", json!({"plane":"XY"})); + let sketch = s.active_sketch.unwrap(); + run(s, "sketch.spline.fit_point", json!({"points":[[0,0],[10,5],[20,0],[30,5]],"ids":["s1"]})); + let result = run(s, "sketch.offset", json!({"curves":["s1"],"distance":"2 mm","chain":true})); + (sketch, result["curves"][0].as_str().unwrap().into()) +} +fn coincident(sk: &Sketch, a: usize, b: usize) -> bool { + sk.constraints.iter().any(|k| matches!(k.kind, ConstraintKind::Coincident { p, q } if (p, q) == (a, b) || (p, q) == (b, a))) +} + +#[test] +fn lines_drawn_from_offset_spline_ends_get_their_own_coincident_points() { + let mut s = Session::default(); + let (id, output) = offset_spline(&mut s); + // Close the shape between the spline and its offset at both ends. + run(&mut s, "sketch.line", json!({"points":["s1.start", format!("{output}.start")],"ids":["l1"]})); + run(&mut s, "sketch.line", json!({"points":[format!("{output}.end"), "s1.end"],"ids":["l2"]})); + let sk = solved(&s, id); + sk.validate_freeform_offsets().unwrap(); + let o = sk.curve_index(&output).unwrap(); + let (start, end) = sk.curves[o].kind.ends().unwrap(); + let (l1, l2) = (sk.curve_index("l1").unwrap(), sk.curve_index("l2").unwrap()); + let (CurveKind::Line { b: l1_end, .. }, CurveKind::Line { a: l2_start, .. }) = (&sk.curves[l1].kind, &sk.curves[l2].kind) else { + panic!("lines") + }; + assert!(*l1_end != start && *l2_start != end, "the offset keeps sole ownership of its nodes"); + assert!(coincident(&sk, start, *l1_end) && coincident(&sk, end, *l2_start)); + assert!(sk.points[*l1_end].pos.dist(sk.points[start].pos) < 1e-9); + + // Moving the source moves the offset, and the lines follow its ends. + let from = sk.point(sk.resolve_point("s1.start").unwrap()).unwrap(); + run(&mut s, "sketch.drag", json!({"entity":"s1.start","from":[from.x, from.y],"to":[from.x - 3.0, from.y + 2.0]})); + let moved = solved(&s, id); + moved.validate_freeform_offsets().unwrap(); + assert!(moved.points[start].pos.dist(sk.points[start].pos) > 1.0, "the offset followed its source"); + assert!(moved.points[*l1_end].pos.dist(moved.points[start].pos) < 1e-6); + assert!(moved.points[*l2_start].pos.dist(moved.points[end].pos) < 1e-6); + + // The design saves and loads with the connection. + let doc = Document::from_json(&s.doc.to_json()).unwrap(); + let loaded = doc.sketch(id).unwrap(); + loaded.validate_freeform_offsets().unwrap(); + assert!(coincident(loaded, start, *l1_end)); +} + +#[test] +fn an_arc_from_an_offset_end_is_drawn_and_undone_atomically() { + let mut s = Session::default(); + let (id, output) = offset_spline(&mut s); + let before = s.doc.to_json(); + run(&mut s, "sketch.arc.three_point", json!({"start":format!("{output}.end"),"through":[33,3],"end":"s1.end"})); + let sk = solved(&s, id); + sk.validate_freeform_offsets().unwrap(); + let end = sk.curves[sk.curve_index(&output).unwrap()].kind.ends().unwrap().1; + assert_eq!(sk.curves.iter().filter(|c| c.kind.uses(end)).count(), 1); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.to_json(), before); +} + +#[test] +fn an_open_offset_spline_shows_only_its_ends() { + let mut s = Session::default(); + let (id, output) = offset_spline(&mut s); + let sk = solved(&s, id); + let o = sk.curve_index(&output).unwrap(); + let (start, end) = sk.curves[o].kind.ends().unwrap(); + let nodes = sk.curves[o].kind.point_ids(); + assert!(nodes.len() > 2); + for i in nodes { + assert_eq!(crate::view::sketch_point_visible(&sk, i), i == start || i == end, "node {i}"); + } +} diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rs index a9b6ec59d..f97f4575f 100644 --- a/crates/engine/src/cmd/sketch.rs +++ b/crates/engine/src/cmd/sketch.rs @@ -275,6 +275,8 @@ pub(super) fn edit_solved( // The stored sketch is solved for its stored values. let stored = sk.driving_values(); let (out, left) = f(&mut sk, &mut doc)?; + // A curve that took an offset spline's generated node (drawn from its end) gets its own point there. + sk.detach_offset_points()?; let offsets = !sk.offsets.is_empty() || !sk.freeform_offsets.is_empty(); let rep = match left { // A drag step solved it (held, with the dimensions' values applied). diff --git a/crates/engine/src/view.rs b/crates/engine/src/view.rs index 7a4e65845..a645e9fd6 100644 --- a/crates/engine/src/view.rs +++ b/crates/engine/src/view.rs @@ -301,7 +301,8 @@ pub fn sketch_curve_visible(sk: &Sketch, i: usize) -> bool { } /// Point roles shown and picked individually. Associated offsets keep their generated -/// fit nodes private until their association is broken. Build once per sketch/frame. +/// fit nodes private until their association is broken, except an open offset's two ends, +/// which other curves snap and constrain to. Build once per sketch/frame. pub struct SketchPointVisibility<'a> { hidden: std::collections::HashSet<&'a str>, } @@ -321,7 +322,9 @@ impl<'a> SketchPointVisibility<'a> { let mut hidden: std::collections::HashSet<&str> = sk.points.iter().filter(|p| p.link.as_deref().is_some_and(|l| text.contains(l))).map(|p| p.id.as_str()).collect(); for curve in sk.curves.iter().filter(|c| outputs.contains(c.id.as_str())) { - hidden.extend(curve.kind.point_ids().into_iter().filter_map(|i| sk.points.get(i).map(|p| p.id.as_str()))); + let ends = curve.kind.ends(); + let interior = curve.kind.point_ids().into_iter().filter(|i| ends.is_none_or(|(a, b)| *i != a && *i != b)); + hidden.extend(interior.filter_map(|i| sk.points.get(i).map(|p| p.id.as_str()))); } Self { hidden } } @@ -332,7 +335,7 @@ impl<'a> SketchPointVisibility<'a> { } /// Should sketch point `i` be drawn or picked individually? Text outlines and derived -/// offset fit nodes are private. Batch callers use [`SketchPointVisibility`]. +/// offset fit nodes (but an open offset's ends) are private. Batch callers use [`SketchPointVisibility`]. pub fn sketch_point_visible(sk: &Sketch, i: usize) -> bool { sk.points.get(i).is_some_and(|p| SketchPointVisibility::new(sk).takes(p)) } diff --git a/crates/sketch/src/freeform_offset.rs b/crates/sketch/src/freeform_offset.rs index 6529cd064..067686941 100644 --- a/crates/sketch/src/freeform_offset.rs +++ b/crates/sketch/src/freeform_offset.rs @@ -587,6 +587,35 @@ impl Sketch { *self = candidate; Ok(()) } + + /// Give every other curve that took a generated offset node (a line drawn from an open + /// offset's end) its own point there, coincident with the node: the output keeps sole + /// ownership of its nodes, and the curve follows the offset when its source moves. + /// Returns the ids of the constraints added. + pub fn detach_offset_points(&mut self) -> Result> { + if self.freeform_offsets.is_empty() { + return Ok(Vec::new()); + } + let outputs: std::collections::BTreeSet<&str> = self.freeform_offsets.iter().map(|o| o.output.as_str()).collect(); + let nodes: std::collections::BTreeSet = + self.curves.iter().filter(|c| outputs.contains(c.id.as_str())).flat_map(|c| c.kind.point_ids()).collect(); + let taken: Vec<(usize, usize)> = self + .curves + .iter() + .enumerate() + .filter(|(_, c)| !outputs.contains(c.id.as_str())) + .flat_map(|(ci, c)| c.kind.point_ids().into_iter().filter(|p| nodes.contains(p)).map(move |p| (ci, p))) + .collect(); + let mut added = Vec::new(); + for (ci, node) in taken { + let at = self.points.get(node).map(|p| p.pos).ok_or_else(|| bad("offset output point vanished"))?; + let own = self.add_point(at, None)?; + let curve = self.curves.get_mut(ci).ok_or_else(|| bad("offset neighbour curve vanished"))?; + curve.kind.map_points(&|p| if p == node { own } else { p }); + added.push(self.add_constraint(crate::ConstraintKind::Coincident { p: node, q: own }, None)?); + } + Ok(added) + } } #[cfg(test)] diff --git a/crates/ui-egui/tests/scenarios/sketch_offset_spline_ends.json b/crates/ui-egui/tests/scenarios/sketch_offset_spline_ends.json new file mode 100644 index 000000000..fb6b1e328 --- /dev/null +++ b/crates/ui-egui/tests/scenarios/sketch_offset_spline_ends.json @@ -0,0 +1,22 @@ +[ + {"note": "#2424: lines close the gap between an open spline and its associated offset. A click near the offset's end snaps to it; the line gets its own point there, coincident with the offset's end, and follows it when the source spline moves."}, + {"call": "engine.execute", "params": {"command": "sketch.create", "params": {"plane": "XY"}}}, + {"call": "engine.execute", "params": {"command": "sketch.spline.fit_point", "params": {"points": [[5,-5],[15,0],[25,-5],[35,0]], "ids": ["s1"]}}}, + {"call": "engine.execute", "params": {"command": "sketch.offset", "params": {"curves": ["s1"], "distance": "2 mm", "chain": true}}}, + {"call": "ui.view", "params": {"view": "top"}}, + {"call": "ui.view", "params": {"view": "fit"}}, + {"start": "sketch.line"}, + {"click": {"sketch": [5,-5]}}, + {"click": {"sketch": [3.85,-3.36]}}, + {"key": "Escape"}, + {"start": "sketch.line"}, + {"click": {"sketch": [33.85,1.64]}}, + {"click": {"sketch": [35,0]}}, + {"key": "Escape"}, + {"shot": "closed"}, + {"expect": {"errors": 0, "sketch_curves": {"own": 4}, "dof": 8}}, + {"call": "engine.execute", "params": {"command": "sketch.drag", "params": {"entity": "s1.start", "from": [5,-5], "to": [2,-2]}}}, + {"shot": "source-dragged"}, + {"expect": {"errors": 0, "dof": 8}}, + {"expect": {"query": {"command": "sketch.inspect", "path": ["curves", 2, "start_at", 0], "value": 2}}} +] diff --git a/docs/book/src/guide/sketching.md b/docs/book/src/guide/sketching.md index 18f82b389..d01540dbb 100644 --- a/docs/book/src/guide/sketching.md +++ b/docs/book/src/guide/sketching.md @@ -129,6 +129,9 @@ error bound of 0.002 mm. Singular tangents, curvature cusps, possible self-inter excessive subdivisions are refused. Offset these curves individually: mixed chain junctions currently require separate geometry. `sketch.offset.break` releases an offset for independent editing, and undo restores its association. Older independently sampled offsets remain independent. +The fit points of such an offset stay hidden, except the two ends of an open one: lines and +arcs snap to them and stay coincident with them as the offset follows its source, so the gap +between a spline and its offset can be closed into a profile. Smooth open and newly created smooth closed offsets can be offset again, including bounded refinement after a source edit. New closed outputs use a periodic cubic fit with continuous tangent and curvature at the seam. Break Offset Association preserves that interpolation, From aa438611a7aeeb931c28550563c4ef751dccf385 Mon Sep 17 00:00:00 2001 From: CamWight <91156642+CamWight@users.noreply.github.com> Date: Mon, 19 Oct 2026 02:16:48 +0100 Subject: [PATCH 029/225] S command search and the new design's name: shown and matched in the current language (#2544) (#2555) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * claim: #2544 * S command search and the command line: names, places and matching in the current language (#2544) The S box showed each command's English label and toolbar place in every language, and found only what was typed in English; the command line matched English only too. Rows, places and tooltips now go through the label lookup, and the query matches the translated label, tab and panel as well as the English ones and the id. The pin tooltips get catalog entries. A new sweep (i18n_painted_tests) runs every language, reads the text each frame paints, and fails on English painted where the language has a translation, skipping the design's own names and key names, so a painter call that skips the lookup can't come back unnoticed. Co-Authored-By: Claude Opus 5.5 * The painted-text sweep also covers every Preferences page and four right-click menus Each surface must show (the Preferences title in that language, or new text for a menu), so the sweep can't pass by painting nothing. Co-Authored-By: Claude Opus 5.5 * S box rows: labels stay 'static; the place's separator is drawn, level in every language A font's "›" (and one centred on the row) sits on the baseline beside Japanese or Chinese words, where it reads as a comma. The separator is now a drawn chevron (glyphs::breadcrumb) centred on the ink of the panel's name. search() returns the place as (tab, panel). Co-Authored-By: Claude Opus 5.5 * A new design's name, Untitled, shows translated in the browser too, like the other default names The tab and the save prompt translated "Untitled" through their own special case; the browser's top row showed it in English. It is now one of the default names the label layer translates (Locale::default_name, with Sketch1, Body2, Component3), so every place that shows a given name shows it translated, and the two special cases go. The painted-text sweep no longer skips a design name that the language translates, and splits a tab's dirty mark off, so it catches a place that shows the raw name. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- assets/icons/ui/source/glyphs.rs | 9 ++ assets/locales/cs.json | 2 + assets/locales/de.json | 2 + assets/locales/en.json | 2 + assets/locales/es.json | 2 + assets/locales/fr.json | 2 + assets/locales/gl.json | 2 + assets/locales/it.json | 2 + assets/locales/ja.json | 2 + assets/locales/ko.json | 2 + assets/locales/pl.json | 2 + assets/locales/pt-BR.json | 2 + assets/locales/ru.json | 2 + assets/locales/tr.json | 2 + assets/locales/uk.json | 2 + assets/locales/zh.json | 2 + crates/ui-egui/src/documents.rs | 9 +- crates/ui-egui/src/i18n.rs | 19 ++- crates/ui-egui/src/i18n_painted_tests.rs | 168 +++++++++++++++++++++++ crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/palette.rs | 36 ++++- crates/ui-egui/src/shortcut_box.rs | 89 ++++++++++-- 22 files changed, 335 insertions(+), 27 deletions(-) create mode 100644 crates/ui-egui/src/i18n_painted_tests.rs diff --git a/assets/icons/ui/source/glyphs.rs b/assets/icons/ui/source/glyphs.rs index c2b5eba7f..75edc8fe1 100644 --- a/assets/icons/ui/source/glyphs.rs +++ b/assets/icons/ui/source/glyphs.rs @@ -89,6 +89,15 @@ pub(crate) fn pin_icon(p: &egui::Painter, r: Rect, on: bool, col: Color32) { p.line_segment([at(0.0, -2.0), at(0.0, 7.0)], stroke); } +/// A breadcrumb separator ("Sketch › Create"): a thin chevron about 3 by 6 px, centred on `c`. +/// Drawn rather than typed, because a font's "›" sits on the baseline in some languages +/// (Japanese), where it reads as a comma. +pub(crate) fn breadcrumb(p: &egui::Painter, c: egui::Pos2, col: Color32) { + let s = Stroke::new(1.0, col); + p.line_segment([pos2(c.x - 1.5, c.y - 3.0), pos2(c.x + 1.5, c.y)], s); + p.line_segment([pos2(c.x + 1.5, c.y), pos2(c.x - 1.5, c.y + 3.0)], s); +} + pub(crate) fn caret(p: &egui::Painter, c: egui::Pos2, col: Color32) { p.add(egui::Shape::convex_polygon(vec![pos2(c.x - 3.5, c.y - 2.0), pos2(c.x + 3.5, c.y - 2.0), pos2(c.x, c.y + 2.5)], col, Stroke::NONE)); } diff --git a/assets/locales/cs.json b/assets/locales/cs.json index a27ed4e6e..a6119472b 100644 --- a/assets/locales/cs.json +++ b/assets/locales/cs.json @@ -1337,6 +1337,8 @@ "ui.save_mesh_pick_bodies": "Vyberte tělesa k uložení", "ui.save_mesh_temp_failed": "Nelze vytvořit {folder}: {error}", "ui.saved_to": "Uloženo {path}", + "ui.sbox_pin": "Připnout nahoru ve vyhledávání S", + "ui.sbox_unpin": "Odepnout", "ui.scale": "Měřítko", "ui.section_analysis": "Analýza řezu", "ui.select": "Vybrat", diff --git a/assets/locales/de.json b/assets/locales/de.json index 77a6bbcb1..914914962 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -1118,6 +1118,8 @@ "ui.save_mesh_pick_bodies": "Wähle die Körper zum Speichern aus", "ui.save_mesh_temp_failed": "{folder} konnte nicht angelegt werden: {error}", "ui.saved_to": "Gespeichert: {path}", + "ui.sbox_pin": "Oben im S-Feld anheften", + "ui.sbox_unpin": "Lösen", "ui.scale": "Skalieren", "ui.second_rail": "Zweite Leitkurve", "ui.section_analysis": "Querschnittsanalyse", diff --git a/assets/locales/en.json b/assets/locales/en.json index 4394f3d63..063cb9a4a 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -1423,6 +1423,8 @@ "ui.save_mesh_pick_bodies": "Select the bodies to save", "ui.save_mesh_temp_failed": "Couldn't make {folder}: {error}", "ui.saved_to": "Saved {path}", + "ui.sbox_pin": "Pin to the top of the S box", + "ui.sbox_unpin": "Unpin", "ui.scale": "Scale", "ui.second_rail": "Second Rail", "ui.section_analysis": "Section Analysis", diff --git a/assets/locales/es.json b/assets/locales/es.json index 0b18f3c7a..1750c8966 100644 --- a/assets/locales/es.json +++ b/assets/locales/es.json @@ -1372,6 +1372,8 @@ "ui.save_mesh_pick_bodies": "Selecciona los cuerpos que se van a guardar", "ui.save_mesh_temp_failed": "No se ha podido crear {folder}: {error}", "ui.saved_to": "Guardado en {path}", + "ui.sbox_pin": "Fijar arriba en la búsqueda S", + "ui.sbox_unpin": "Desfijar", "ui.scale": "Escala", "ui.second_rail": "Segunda línea guía", "ui.section_analysis": "Análisis de sección", diff --git a/assets/locales/fr.json b/assets/locales/fr.json index 2bbbed45e..444117d2b 100644 --- a/assets/locales/fr.json +++ b/assets/locales/fr.json @@ -1379,6 +1379,8 @@ "ui.save_mesh_pick_bodies": "Sélectionner les corps à enregistrer", "ui.save_mesh_temp_failed": "Impossible de créer {folder} : {error}", "ui.saved_to": "Enregistré : {path}", + "ui.sbox_pin": "Épingler en haut de la boîte S", + "ui.sbox_unpin": "Désépingler", "ui.scale": "Échelle", "ui.second_rail": "Second rail", "ui.section_analysis": "Analyse de coupe", diff --git a/assets/locales/gl.json b/assets/locales/gl.json index b34e88612..d7a219660 100644 --- a/assets/locales/gl.json +++ b/assets/locales/gl.json @@ -1337,6 +1337,8 @@ "ui.save_mesh_pick_bodies": "Selecciona os corpos que queres gardar", "ui.save_mesh_temp_failed": "Non se puido crear {folder}: {error}", "ui.saved_to": "Gardado {path}", + "ui.sbox_pin": "Fixar arriba na caixa S", + "ui.sbox_unpin": "Desfixar", "ui.scale": "Escala", "ui.section_analysis": "Análise de sección", "ui.select": "Seleccionar", diff --git a/assets/locales/it.json b/assets/locales/it.json index 243c6290f..e28daca5e 100644 --- a/assets/locales/it.json +++ b/assets/locales/it.json @@ -1363,6 +1363,8 @@ "ui.save_mesh_pick_bodies": "Seleziona i corpi da salvare", "ui.save_mesh_temp_failed": "Impossibile creare {folder}: {error}", "ui.saved_to": "Salvato {path}", + "ui.sbox_pin": "Fissa in cima al riquadro S", + "ui.sbox_unpin": "Sblocca", "ui.scale": "Scala", "ui.second_rail": "Seconda guida", "ui.section_analysis": "Analisi in sezione", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 0cfb388f9..58e7a1136 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -1423,6 +1423,8 @@ "ui.save_mesh_pick_bodies": "保存するボディを選択してください", "ui.save_mesh_temp_failed": "{folder} を作成できません: {error}", "ui.saved_to": "保存しました: {path}", + "ui.sbox_pin": "Sボックスの上部に固定", + "ui.sbox_unpin": "固定を解除", "ui.scale": "尺度", "ui.second_rail": "第2レール", "ui.section_analysis": "断面解析", diff --git a/assets/locales/ko.json b/assets/locales/ko.json index 63df7e568..367b9b628 100644 --- a/assets/locales/ko.json +++ b/assets/locales/ko.json @@ -1116,6 +1116,8 @@ "ui.save_mesh_pick_bodies": "저장할 바디를 선택하세요", "ui.save_mesh_temp_failed": "{folder}을(를) 만들 수 없습니다: {error}", "ui.saved_to": "저장됨: {path}", + "ui.sbox_pin": "S 상자 맨 위에 고정", + "ui.sbox_unpin": "고정 해제", "ui.scale": "축척", "ui.section_analysis": "단면 분석", "ui.select": "선택", diff --git a/assets/locales/pl.json b/assets/locales/pl.json index 501e0f7a9..8507e9f07 100644 --- a/assets/locales/pl.json +++ b/assets/locales/pl.json @@ -1384,6 +1384,8 @@ "ui.save_mesh_pick_bodies": "Zaznacz bryły do zapisania", "ui.save_mesh_temp_failed": "Nie udało się utworzyć {folder}: {error}", "ui.saved_to": "Zapisano {path}", + "ui.sbox_pin": "Przypnij na górze okna S", + "ui.sbox_unpin": "Odepnij", "ui.scale": "Skala", "ui.second_rail": "Druga prowadnica", "ui.section_analysis": "Analiza przekroju", diff --git a/assets/locales/pt-BR.json b/assets/locales/pt-BR.json index 3653a46a5..da4c5c4e5 100644 --- a/assets/locales/pt-BR.json +++ b/assets/locales/pt-BR.json @@ -1317,6 +1317,8 @@ "ui.save_mesh_pick_bodies": "Selecione os corpos a salvar", "ui.save_mesh_temp_failed": "Não foi possível criar {folder}: {error}", "ui.saved_to": "Salvo {path}", + "ui.sbox_pin": "Fixar no topo da caixa S", + "ui.sbox_unpin": "Desafixar", "ui.scale": "Escala", "ui.section_analysis": "Análise de seção", "ui.select": "Selecionar", diff --git a/assets/locales/ru.json b/assets/locales/ru.json index 9550ec467..79b92c584 100644 --- a/assets/locales/ru.json +++ b/assets/locales/ru.json @@ -1116,6 +1116,8 @@ "ui.save_mesh_pick_bodies": "Выберите тела для сохранения", "ui.save_mesh_temp_failed": "Не удалось создать {folder}: {error}", "ui.saved_to": "Сохранено: {path}", + "ui.sbox_pin": "Закрепить вверху панели S", + "ui.sbox_unpin": "Открепить", "ui.scale": "Масштаб", "ui.section_analysis": "Анализ сечения", "ui.select": "Выбрать", diff --git a/assets/locales/tr.json b/assets/locales/tr.json index 3769e61ac..513250cd1 100644 --- a/assets/locales/tr.json +++ b/assets/locales/tr.json @@ -1264,6 +1264,8 @@ "ui.save_mesh_pick_bodies": "Kaydedilecek gövdeleri seçin", "ui.save_mesh_temp_failed": "{folder} oluşturulamadı: {error}", "ui.saved_to": "{path} konumuna kaydedildi", + "ui.sbox_pin": "S kutusunun en üstüne sabitle", + "ui.sbox_unpin": "Sabitlemeyi kaldır", "ui.scale": "Ölçekle", "ui.section_analysis": "Kesit analizi", "ui.select": "Seç", diff --git a/assets/locales/uk.json b/assets/locales/uk.json index 724954ef4..898789df4 100644 --- a/assets/locales/uk.json +++ b/assets/locales/uk.json @@ -1340,6 +1340,8 @@ "ui.save_mesh_pick_bodies": "Виберіть тіла для збереження", "ui.save_mesh_temp_failed": "Не вдалося створити {folder}: {error}", "ui.saved_to": "Збережено {path}", + "ui.sbox_pin": "Закріпити вгорі поля S", + "ui.sbox_unpin": "Відкріпити", "ui.scale": "Масштаб", "ui.section_analysis": "Аналіз перерізу", "ui.select": "Вибрати", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index d342f7a19..f366f0df2 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -1423,6 +1423,8 @@ "ui.save_mesh_pick_bodies": "请选择要保存的实体", "ui.save_mesh_temp_failed": "无法创建 {folder}:{error}", "ui.saved_to": "已保存:{path}", + "ui.sbox_pin": "固定到 S 框顶部", + "ui.sbox_unpin": "取消固定", "ui.scale": "缩放", "ui.second_rail": "第二导轨", "ui.section_analysis": "截面分析", diff --git a/crates/ui-egui/src/documents.rs b/crates/ui-egui/src/documents.rs index be579a94f..7e7656aff 100644 --- a/crates/ui-egui/src/documents.rs +++ b/crates/ui-egui/src/documents.rs @@ -402,8 +402,7 @@ pub fn tabs(app: &mut SolveApp, ui: &mut egui::Ui, r: Rect, x0: f32, x1: f32) { } tab_shape(ui.painter(), &t, tr, active, resp.hovered()); let ink = if active { t.text } else { t.app_bar_text }; - let name_display = if name == "Untitled" { app.tr("ui.untitled") } else { name }; - let label = format!("{name_display}{}", if *dirty { " •" } else { "" }); + let label = format!("{}{}", crate::i18n::Locale::for_language(&app.preferences.language).given_name(name), if *dirty { " •" } else { "" }); let g = ui.painter().layout_no_wrap(label, FontId::proportional(13.0), ink); let text_w = (tr.width() - 30.0).max(10.0); let clip = Rect::from_min_size(tr.min, vec2(text_w + 10.0, tr.height())); @@ -528,7 +527,7 @@ pub fn prompt(app: &mut SolveApp, ctx: &egui::Context) { quit_step(app); let Some(i) = app.docs.closing else { return }; let name = tabs_info(app).get(i).map(|x| x.0.clone()).unwrap_or_default(); - let name_display = if name == "Untitled" { crate::i18n::tr("ui.untitled") } else { &name }; + let name_display = crate::i18n::tr_name(&name); let mut answer: Option = None; // Left and Right move between the buttons (Save is picked first); Enter gives the picked one. let order = [Answer::Save, Answer::DontSave, Answer::Cancel]; @@ -552,14 +551,14 @@ pub fn prompt(app: &mut SolveApp, ctx: &egui::Context) { if enter { answer = Some(choice); } - let title = crate::i18n::format("document.save_changes", &[("name", name_display)]); + let title = crate::i18n::format("document.save_changes", &[("name", &name_display)]); crate::frame::window(ctx, title, crate::frame::Width::Normal) .id(egui::Id::new("sc_close_prompt")) .collapsible(false) .resizable(false) .anchor(Align2::CENTER_CENTER, vec2(0.0, 0.0)) .show(ctx, |ui| { - ui.label(crate::i18n::format("document.unsaved_changes", &[("name", name_display)])); + ui.label(crate::i18n::format("document.unsaved_changes", &[("name", &name_display)])); ui.add_space(8.0); ui.horizontal(|ui| { if ui.add(egui::Button::new(crate::i18n::tr("ui.save")).selected(choice == Answer::Save)).clicked() { diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index dda84b6bb..1863d2de0 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -104,8 +104,12 @@ impl Locale { interpolate(self.text(id), args) } - /// The default names SolidCraft gives (`Sketch1`, `Body2`, `Component3`), translated. + /// The default names SolidCraft gives (`Untitled` for a new design, `Sketch1`, `Body2`, + /// `Component3`), translated. fn default_name(self, text: &str) -> Option { + if text == "Untitled" { + return Some(self.text("ui.untitled").to_string()); + } for (prefix, id) in [("Sketch", "browser.sketch_name"), ("Body", "browser.body_name"), ("Component", "browser.component_name")] { if let Some(number) = text.strip_prefix(prefix) && !number.is_empty() @@ -228,6 +232,19 @@ mod tests { assert_eq!(ids.first(), Some(&"en")); assert!(ids[1..].is_sorted(), "{ids:?}"); } + + /// A new design's name, `Untitled`, is a default name like `Sketch1`: it shows translated + /// wherever the design's name is shown (the tab, the browser's top row, the save prompt). + #[test] + fn a_new_designs_name_is_translated_like_the_other_default_names() { + let ja = Locale::for_language("ja"); + assert_eq!(ja.given_name("Untitled"), ja.text("ui.untitled")); + assert_ne!(ja.given_name("Untitled"), "Untitled"); + assert_eq!(Locale::for_language("en").given_name("Untitled"), "Untitled"); + // Only the whole default name: names people type stay as typed. + assert_eq!(ja.given_name("Untitled bracket"), "Untitled bracket"); + assert_eq!(ja.given_name("Boss"), "Boss"); + } use std::collections::BTreeSet; fn placeholders(text: &str) -> BTreeSet<&str> { diff --git a/crates/ui-egui/src/i18n_painted_tests.rs b/crates/ui-egui/src/i18n_painted_tests.rs new file mode 100644 index 000000000..3e97db262 --- /dev/null +++ b/crates/ui-egui/src/i18n_painted_tests.rs @@ -0,0 +1,168 @@ +//! No English where a translation exists (#2544): the text a frame actually paints, in every +//! language. A painter call that skips the label lookup (`ui.painter().text(.., c.label, ..)`) +//! paints the English text even though the language has a translation; this sweep catches it +//! wherever it happens on the surfaces it opens. + +use std::collections::{BTreeMap, BTreeSet}; + +use solidcraft_engine::Session; + +use crate::context_menu::Target; +use crate::scenario::Harness; +use crate::{Services, SolveApp}; + +/// English text → the catalog ids that carry it. +fn english_ids() -> BTreeMap> { + const EN: &str = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/en.json")); + let messages: BTreeMap = serde_json::from_str(EN).unwrap(); + let mut ids: BTreeMap> = BTreeMap::new(); + for (id, text) in messages { + ids.entry(text).or_default().push(id); + } + ids +} + +/// Every piece of text one more frame paints: whole texts, and the parts of a composed one +/// ("SKETCH › CREATE", "R SKETCH › CREATE", a tab's "Untitled •"). +fn painted(h: &mut Harness) -> BTreeSet { + fn walk(shape: &egui::Shape, out: &mut BTreeSet) { + match shape { + egui::Shape::Text(t) => { + let text = t.galley.job.text.trim(); + out.insert(text.to_string()); + for part in text.split(['›', '·', '•']).flat_map(|p| p.split(" ")) { + out.insert(part.trim().to_string()); + } + } + egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| walk(s, out)), + _ => {} + } + } + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 1000.0)); + let mut out = h.ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| { + h.app.logic(ui.ctx()); + h.app.ui(ui); + }); + out.textures_delta.clear(); + let mut texts = BTreeSet::new(); + out.shapes.iter().for_each(|s| walk(&s.shape, &mut texts)); + texts +} + +/// Names the design holds (its own name, features, bodies, components, occurrences), and the +/// keyboard shortcuts' key names. They are shown as typed or as printed on the key in every +/// language, even when one matches a label ("Boss", "Holes", the Delete key). +fn design_names(app: &SolveApp) -> BTreeSet { + let doc = &app.session.doc; + let mut names: BTreeSet = [doc.name.clone()].into(); + names.extend(doc.features.iter().map(|f| f.name.clone())); + names.extend(doc.components.iter().map(|c| c.name.clone())); + names.extend(doc.occurrences.iter().map(|o| o.name.clone())); + names.extend(app.session.model.state().bodies.iter().map(|b| b.name.clone())); + names.extend(solidcraft_engine::command_specs().iter().filter_map(|c| crate::keymap::effective(app, c.id))); + names +} + +/// Texts painted in English although every catalog entry with that English text is translated +/// in `language`. (When one entry with the text is still English there, English is right.) +/// `names` are the design's own names, which are not UI text, except the default names the +/// language translates (a new design's `Untitled`, `Sketch1`): those must show translated. +fn english_leaks(language: &str, texts: &BTreeSet, english: &BTreeMap>, names: &BTreeSet) -> Vec { + let locale = crate::i18n::Locale::for_language(language); + texts + .iter() + .filter(|text| !names.contains(*text) || locale.given_name(text) != text.as_str()) + .filter(|text| english.get(*text).is_some_and(|ids| ids.iter().all(|id| locale.text(id) != text.as_str()))) + .cloned() + .collect() +} + +fn sample() -> Harness { + let mut h = Harness::new(); + let mut session = Session::default(); + session.run_script(&solidcraft_engine::sample::script()).unwrap(); + h.app = SolveApp::new(session, Services::default()); + h.app.home.open = false; + h.frames(3); + h +} + +/// The surfaces the sweep opens, each in every language: the window with the sample design; the +/// S command search with nothing typed (the first rows of every command, by name) and with two +/// queries; every Preferences page; and the right-click menus of the viewport, a body, the +/// toolbar and the workspace. +fn sweep(h: &mut Harness, language: &str) -> BTreeMap<&'static str, BTreeSet> { + h.app.preferences.language = language.into(); + let mut seen = BTreeMap::new(); + h.app.ui.palette_open = false; + h.frames(2); + seen.insert("window", painted(h)); + for (name, query) in [("S box", ""), ("S box: rect", "rect"), ("S box: sketch", "sketch")] { + crate::shortcut_box::open(&mut h.app, None); + h.app.sbox.text = query.into(); + h.frames(2); + seen.insert(name, painted(h)); + } + h.app.ui.palette_open = false; + let title = crate::i18n::Locale::for_language(language).text("ui.preferences").to_string(); + for page in crate::prefs::PAGES { + h.call("ui.prefs", serde_json::json!({"open": page})); + h.frames(2); + let texts = painted(h); + assert!(texts.contains(&title), "{language}: the {page} page isn't showing"); + seen.insert(page, texts); + } + h.call("ui.prefs", serde_json::json!({"button": "cancel"})); + h.frames(1); + let body = h.app.session.model.state().bodies.first().map(|b| b.name.clone()).unwrap_or_default(); + let menus = [ + ("viewport menu", Target::Viewport), + ("body menu", Target::Body { name: body }), + ("toolbar menu", Target::Toolbar), + ("workspace menu", Target::Workspace), + ]; + for (name, target) in menus { + crate::context_menu::open_for(&mut h.app, egui::pos2(700.0, 400.0), target); + h.frames(2); + let texts = painted(h); + let new = texts.difference(&seen["window"]).count(); + assert!(new >= 2, "{language}: the {name} isn't showing ({new} new texts)"); + seen.insert(name, texts); + crate::context_menu::close(&mut h.app); + h.frames(1); + } + seen +} + +#[test] +fn no_english_is_painted_where_the_language_has_a_translation() { + let english = english_ids(); + let mut h = sample(); + let names = design_names(&h.app); + assert!(names.contains("Boss") && names.len() > 5, "{names:?}"); + let mut leaks = Vec::new(); + for catalog in crate::i18n::LOCALES.iter().filter(|c| c.id != "en") { + for (surface, texts) in sweep(&mut h, catalog.id) { + assert!(texts.len() > 20, "{} {surface}: only {} texts painted", catalog.id, texts.len()); + for text in english_leaks(catalog.id, &texts, &english, &names) { + leaks.push(format!("{} {surface}: {text:?}", catalog.id)); + } + } + } + assert!(leaks.is_empty(), "{} English text(s) painted where the language has a translation:\n{}", leaks.len(), leaks.join("\n")); +} + +/// The sweep can see a leak: English painted by a plain painter call is reported, the same text +/// in the language is not, and English that the language leaves untranslated is not either. +#[test] +fn the_sweep_reports_english_only_where_a_translation_exists() { + let english = english_ids(); + let locale = crate::i18n::Locale::for_language("ja"); + let translated = locale.text("cmd.sketch_rectangle_center").to_string(); + assert_ne!(translated, "Center Rectangle"); + let texts: BTreeSet = + ["Center Rectangle".to_string(), translated, "mm".to_string(), "Untranslated Text 2544".to_string(), "Fillet".to_string()].into(); + // "Fillet" here is a feature someone named so: a design name, not a label. + let names: BTreeSet = ["Fillet".to_string()].into(); + assert_eq!(english_leaks("ja", &texts, &english, &names), vec!["Center Rectangle".to_string()]); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index f24a2e7e4..edd7374ee 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -59,6 +59,8 @@ pub mod i18n; #[cfg(test)] mod i18n_menu_tests; #[cfg(test)] +mod i18n_painted_tests; +#[cfg(test)] mod i18n_ui_tests; pub mod icon_svg; pub mod icons; diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index 47cea3258..e26e33947 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -15,16 +15,22 @@ pub struct Palette { focus: bool, } -/// Commands whose id or label matches the query. +/// Commands whose id or label matches the query: (id, label in the current language, icon). +/// The label matches in the current language and in English, so a name typed in either finds +/// the command. pub fn matches(q: &str) -> Vec<(&'static str, &'static str, &'static str)> { - let q = q.trim().to_ascii_lowercase(); - let mut v: Vec<(&'static str, &'static str, &'static str)> = command_specs() + let q = q.trim().to_lowercase(); + let mut v: Vec<(bool, bool, &'static str, &'static str, &'static str)> = command_specs() .into_iter() - .filter(|c| q.is_empty() || c.label.to_ascii_lowercase().contains(&q) || c.id.to_ascii_lowercase().contains(&q)) - .map(|c| (c.id, c.label, c.icon)) + .filter_map(|c| { + let label = crate::i18n::tr_label(c.label); + let (shown, english, id) = (label.to_lowercase(), c.label.to_lowercase(), c.id.to_lowercase()); + let found = q.is_empty() || shown.contains(&q) || english.contains(&q) || id.contains(&q); + found.then(|| (!(shown.starts_with(&q) || english.starts_with(&q)), !id.starts_with(&q), label, c.id, c.icon)) + }) .collect(); - v.sort_by_key(|(id, label, _)| (!label.to_ascii_lowercase().starts_with(&q), !id.to_ascii_lowercase().starts_with(&q), *label)); - v + v.sort(); + v.into_iter().map(|(_, _, label, id, icon)| (id, label, icon)).collect() } /// Execute a line of palette input. @@ -136,3 +142,19 @@ pub fn popup(app: &mut SolveApp, ctx: &egui::Context) { app.palette.text.clear(); } } + +#[cfg(test)] +mod tests { + use super::*; + + /// The command line finds a name typed in the current language or in English (#2544). + #[test] + fn matches_finds_a_name_in_the_current_language_and_in_english() { + let _ja = crate::i18n::scope("ja"); + let name = crate::i18n::Locale::for_language("ja").text("cmd.sketch_rectangle_center"); + for query in [name, "Center Rectangle", "sketch.rectangle.center"] { + let found = matches(query); + assert_eq!(found.first().map(|m| (m.0, m.1)), Some(("sketch.rectangle.center", name)), "{query:?}"); + } + } +} diff --git a/crates/ui-egui/src/shortcut_box.rs b/crates/ui-egui/src/shortcut_box.rs index ca3da74de..a2b341bcd 100644 --- a/crates/ui-egui/src/shortcut_box.rs +++ b/crates/ui-egui/src/shortcut_box.rs @@ -98,23 +98,63 @@ pub fn score(q: &str, s: &str) -> u32 { 300u32.saturating_sub(gaps * 20).max(10) } -/// Commands matching `q`, best first: (id, label, icon, where it lives on the toolbar). With an -/// empty query, recent commands come first, then everything by name. -pub fn search(app: &SolveApp, q: &str) -> Vec<(&'static str, &'static str, &'static str, String)> { +/// A row of the box: the command id, its label, its icon, and where it lives on the toolbar +/// (tab, panel; `None` off the toolbar), in the current language. +pub type Row = (&'static str, &'static str, &'static str, Option<(&'static str, &'static str)>); + +/// Commands matching `q`, best first. With an empty query, recent commands come first, then +/// everything by name. +/// +/// The query matches the label, tab and panel in the current language and in English, and the +/// id, so a name typed in either language, or an id, finds the command in every language. +pub fn search(app: &SolveApp, q: &str) -> Vec { let q = q.trim().to_lowercase(); - let mut v: Vec<(u32, &'static str, &'static str, &'static str, String)> = command_specs() + let mut v: Vec<(u32, Row)> = command_specs() .into_iter() .filter_map(|c| { - let place = if c.tab.is_empty() { String::new() } else { format!("{} › {}", c.tab, c.panel) }; - let s = score(&q, c.label).max(score(&q, c.id) * 9 / 10).max(score(&q, c.tab) / 3).max(score(&q, c.panel) / 3); + let (label, tab, panel) = (crate::i18n::tr_label(c.label), crate::i18n::tr_label(c.tab), crate::i18n::tr_label(c.panel)); + let place = (!c.tab.is_empty()).then_some((tab, panel)); + let s = score(&q, label) + .max(score(&q, c.label)) + .max(score(&q, c.id) * 9 / 10) + .max(score(&q, tab).max(score(&q, c.tab)) / 3) + .max(score(&q, panel).max(score(&q, c.panel)) / 3); let recent = app.sbox.recent.iter().position(|r| r == c.id).map_or(0, |i| 2000 - i as u32); // Commands that can run now come before those that can't. let usable = if c.info(&app.session).enabled { 150 } else { 0 }; - (s > 0).then_some((s + usable + if q.is_empty() { recent } else { recent / 20 }, c.id, c.label, c.icon, place)) + (s > 0).then_some((s + usable + if q.is_empty() { recent } else { recent / 20 }, (c.id, label, c.icon, place))) }) .collect(); - v.sort_by(|a, b| b.0.cmp(&a.0).then(a.2.cmp(b.2))); - v.into_iter().map(|(_, id, label, icon, place)| (id, label, icon, place)).collect() + v.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.1.cmp(b.1.1))); + v.into_iter().map(|(_, row)| row).collect() +} + +/// A row's right-hand side, ending at `at`: the shortcut, then where the command lives +/// ("Sketch › Create"). The separator is drawn, centred on the ink of the panel's name: a +/// font's "›", or one centred on the row, sits low beside Japanese or Chinese words. +fn paint_key_and_place(painter: &egui::Painter, at: Pos2, key: &str, place: Option<(&str, &str)>, color: egui::Color32) { + let font = FontId::proportional(10.5); + // One piece of text ending at `x`, centred on the row: its left edge and the middle of its ink. + let piece = |x: f32, text: &str| -> (f32, f32) { + let galley = painter.layout_no_wrap(text.to_string(), font.clone(), color); + let pos = pos2(x - galley.size().x, at.y - galley.size().y / 2.0); + let ink = galley + .rows + .first() + .filter(|r| r.row.visuals.mesh_bounds.is_positive()) + .map_or(galley.size().y / 2.0, |r| r.pos.y + r.row.visuals.mesh_bounds.center().y); + painter.galley(pos, galley, color); + (pos.x, pos.y + ink) + }; + let mut x = at.x; + if let Some((tab, panel)) = place { + let (left, ink) = piece(x, panel); + icons::glyphs::breadcrumb(painter, pos2(left - 5.0, ink), color); + x = piece(left - 10.0, tab).0 - 14.0; + } + if !key.is_empty() { + piece(x, key); + } } /// Open the box at a point (the cursor), or at the middle of the window. @@ -178,7 +218,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { ui.painter().rect_filled(r, 4.0, t.hover); } icons::paint(ui.painter(), r.shrink(5.0), c.icon, t.icon, t.icon_fill, t.accent); - if resp.on_hover_text(c.label).clicked() { + if resp.on_hover_text(crate::i18n::tr_label(c.label)).clicked() { picked = Some(c.id); } } @@ -223,10 +263,9 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { t.accent, ); let col = if enabled { t.text } else { t.text_dim }; - ui.painter().text(pos2(r.left() + 30.0, r.center().y), Align2::LEFT_CENTER, *label, FontId::proportional(13.0), col); + ui.painter().text(pos2(r.left() + 30.0, r.center().y), Align2::LEFT_CENTER, label, FontId::proportional(13.0), col); let key = crate::keymap::effective(app, id).unwrap_or_default(); - let right = if key.is_empty() { place.clone() } else { format!("{key} {place}") }; - ui.painter().text(pos2(r.right() - 26.0, r.center().y), Align2::RIGHT_CENTER, right, FontId::proportional(10.5), t.text_dim); + paint_key_and_place(ui.painter(), pos2(r.right() - 26.0, r.center().y), &key, *place, t.text_dim); // The pin. let pinned = app.sbox.pinned.iter().any(|p| p == id); let pr = Rect::from_center_size(pos2(r.right() - 11.0, r.center().y), vec2(16.0, 16.0)); @@ -245,7 +284,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { } ui.painter().add(egui::Shape::closed_line(pts, Stroke::new(1.0, if pinned { t.warning } else { t.text_dim }))); } - if presp.on_hover_text(if pinned { "Unpin" } else { "Pin to the top of the S box" }).clicked() { + if presp.on_hover_text(crate::i18n::tr(if pinned { "ui.sbox_unpin" } else { "ui.sbox_pin" })).clicked() { pin = Some(id); } else if resp.clicked() && enabled { picked = Some(id); @@ -337,4 +376,26 @@ mod tests { other.sbox.load(&app.sbox.prefs()); assert_eq!((other.sbox.pinned.clone(), other.sbox.recent.len()), (vec!["solid.extrude".to_string()], 2)); } + + /// The box shows each command's label and place in the current language, and finds a name + /// typed in that language, in English, or an id (#2544). + #[test] + fn search_shows_and_matches_the_current_language() { + let app = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + let _ja = crate::i18n::scope("ja"); + let ja = crate::i18n::Locale::for_language("ja"); + let name = ja.text("cmd.sketch_rectangle_center"); + assert_ne!(name, "Center Rectangle"); + let place = Some((ja.label("SKETCH"), ja.label("CREATE"))); + for query in [name, "長方形", "center rect", "sketch.rectangle.center"] { + let rows = search(&app, query); + let row = rows.iter().find(|r| r.0 == "sketch.rectangle.center").unwrap_or_else(|| panic!("{query:?} doesn't find it")); + assert_eq!((row.1, row.3), (name, place), "{query:?}"); + } + assert_eq!(search(&app, name).first().map(|r| r.0), Some("sketch.rectangle.center"), "the exact name comes first"); + // English is unchanged. + drop(_ja); + let row = search(&app, "center rect").into_iter().find(|r| r.0 == "sketch.rectangle.center").unwrap(); + assert_eq!((row.1, row.3), ("Center Rectangle", Some(("SKETCH", "CREATE")))); + } } From 6b1fc16d472cff94a441e08a0486f2a6a3ec6972 Mon Sep 17 00:00:00 2001 From: phanoob Date: Mon, 19 Oct 2026 03:23:11 +0200 Subject: [PATCH 030/225] Sketch projection: a solid's edges come in as their exact curves (#1508) Thanks @phanoob. --- crates/doc/src/project.rs | 88 +++++++++++++------ crates/engine/src/cmd/sketch_project_tests.rs | 68 ++++++++++++++ crates/kernel/src/body.rs | 23 +++++ crates/kernel/src/prism_curve.rs | 52 ++++++++++- .../before-1508/engraved_face_sketched.json | 1 + 5 files changed, 204 insertions(+), 28 deletions(-) create mode 100644 tests/projection/before-1508/engraved_face_sketched.json diff --git a/crates/doc/src/project.rs b/crates/doc/src/project.rs index 696d3e7dc..39e556f5c 100644 --- a/crates/doc/src/project.rs +++ b/crates/doc/src/project.rs @@ -3,13 +3,16 @@ //! //! Model geometry is found again on every recompute: a face or an edge by the persistent name //! its link keeps, anything else (and a link saved without a name) from the reference point -//! stored in the link. Edge polylines from the tessellation lie exactly on their curves, -//! so lines and circular arcs are recovered exactly by fitting; anything else (an ellipse from -//! a tilted circle, a spline edge) becomes a chain of lines. +//! stored in the link. An edge of a solid lying in a plane parallel to the sketch's comes in as +//! its exact curve (a line, an arc, the Bézier pieces of a free-form curve such as a letter +//! cut from a font), so a profile drawn round it meets the solid's faces exactly. Anything +//! else is fitted to its polyline from the tessellation, which lies exactly on the curve: +//! lines and circular arcs are recovered exactly, the rest (an ellipse from a tilted circle, +//! a spline edge running out of the plane) becomes a chain of lines. use std::collections::BTreeMap; -use solidcraft_geom::{Mesh, Plane, Vec2, Vec3}; +use solidcraft_geom::{Mesh, Plane, Seg2, Vec2, Vec3}; use solidcraft_sketch::{CurveKind, LinkGeom, LinkKind, LinkSource, Sketch}; use crate::eval::ModelState; @@ -117,7 +120,8 @@ fn resolve_uncached( let name = st.bodies.get(bi).map(|b| b.name.clone()).unwrap_or_else(|| body.clone()); source = LinkSource::Edge { body: name, at: q }; edge_index = Some(e); - edge_geom(plane, kind, mesh.edges.get(e).cloned().unwrap_or_default(), &mut wires) + let exact = st.bodies.get(bi).and_then(|b| exact_edges(b, plane, &[e]).pop().flatten()); + edge_geom(plane, kind, exact, mesh.edges.get(e).cloned().unwrap_or_default(), &mut wires) } LinkSource::Face { body, at } => { let (bi, mesh) = body_mesh(st, body, *at)?; @@ -133,13 +137,8 @@ fn resolve_uncached( match kind { LinkKind::Intersect => section(plane, &mesh, Some(f)), _ => { - let mut g = Vec::new(); let target = st.bodies.get(bi).ok_or_else(|| lost("the projection body"))?; - for e in projection_face_edges(target, &mesh, f, plane)? { - if let Some(pts) = mesh.edges.get(e) { - g.extend(fit_world(plane, pts)); - } - } + let g = projected_edges(target, &mesh, plane, &projection_face_edges(target, &mesh, f, plane)?); if certified_planar_construction(target, f as usize) { merge_family_lines(g)? } else { g } } } @@ -282,19 +281,62 @@ fn off_plane(plane: &Plane, pts: &[Vec3]) -> bool { pts.iter().any(|p| plane.height(*p).abs() > size * 1e-7) } -/// What a body edge (its points) gives a sketch: its section with the sketch plane, itself as a -/// 3D curve (into `wires`) when it is included and leaves the plane, else its projection. -fn edge_geom(plane: &Plane, kind: LinkKind, pts: Vec, wires: &mut Vec>) -> Vec { +/// What a body edge (its `exact` curve when read, and its polyline `pts`) gives a sketch: its +/// section with the sketch plane, itself as a 3D curve (into `wires`) when it is included and +/// leaves the plane, else its projection (the exact curve, or the polyline fitted). +fn edge_geom(plane: &Plane, kind: LinkKind, exact: Option>, pts: Vec, wires: &mut Vec>) -> Vec { match kind { LinkKind::Intersect => section_of_polyline(plane, &pts), LinkKind::Include if off_plane(plane, &pts) => { wires.push(pts); Vec::new() } - _ => fit_world(plane, &pts), + _ => exact.unwrap_or_else(|| fit_world(plane, &pts)), } } +/// Edges `edges` of `body` (indices into its mesh's `edges`) on `plane` as their exact curves: +/// lines, circles and arcs, and the Bézier pieces of a free-form curve. `None` for an edge that +/// doesn't lie in a plane parallel to `plane` or isn't read exactly (a mesh body's): it is +/// fitted to its polyline instead. +fn exact_edges(body: &crate::ModelBody, plane: &Plane, edges: &[usize]) -> Vec>> { + body.body.planar_edges(plane, edges).into_iter().map(|segs| segs?.iter().map(link_geom).collect()).collect() +} + +/// `edges` of `body` projected on `plane`: each exactly ([`exact_edges`]) or fitted to its +/// polyline in `mesh`. +fn projected_edges(body: &crate::ModelBody, mesh: &Mesh, plane: &Plane, edges: &[usize]) -> Vec { + let mut out = Vec::new(); + for (e, exact) in edges.iter().zip(exact_edges(body, plane, edges)) { + match exact { + Some(g) => out.extend(g), + None => { + if let Some(pts) = mesh.edges.get(*e) { + out.extend(fit_world(plane, pts)); + } + } + } + } + out +} + +/// A boundary segment as the link geometry that is the same curve. +fn link_geom(s: &Seg2) -> Option { + Some(match *s { + Seg2::Line { a, b } => LinkGeom::Line(a, b), + Seg2::Arc { center, radius, sweep, .. } if sweep.abs() >= std::f64::consts::TAU - 1e-9 => LinkGeom::Circle(center, radius), + Seg2::Arc { center, radius, start, sweep } => { + let at = |t: f64| center + Vec2::new(t.cos(), t.sin()) * radius; + // Counter-clockwise from `a` to `b`. + let (a, b) = if sweep > 0. { (at(start), at(start + sweep)) } else { (at(start + sweep), at(start)) }; + LinkGeom::Arc { c: center, a, b } + } + Seg2::Conic { a, apex, b, w } => LinkGeom::Conic { a, apex, b, rho: w / (1. + w) }, + Seg2::Cubic { p0, p1, p2, p3 } => LinkGeom::Spline { pts: vec![p0, p1, p2, p3], control: true, degree: 3, periodic: false }, + Seg2::Bezier { n, p } => LinkGeom::Spline { pts: p.get(..=usize::from(n))?.to_vec(), control: true, degree: n, periodic: false }, + }) +} + /// The persistent name of the edge an `Edge` reference resolved to, for its link to keep and /// be found by from then on. None on a mesh body, whose edges have no names. pub fn resolved_edge_name(st: &ModelState, r: &Resolved) -> Option { @@ -331,7 +373,8 @@ fn resolve_named_edge(st: &ModelState, plane: &Plane, kind: LinkKind, body: &str .min_by(|a, b| a.dist(near).total_cmp(&b.dist(near))) .ok_or_else(|| lost("named projection edge"))?; let mut wires = Vec::new(); - let geom = edge_geom(plane, kind, pts, &mut wires); + let exact = exact_edges(target, plane, &[index]).pop().flatten(); + let geom = edge_geom(plane, kind, exact, pts, &mut wires); if geom.is_empty() && wires.is_empty() { return Err(DocError::Invalid("named edge projects to nothing on this sketch plane".into())); } @@ -350,12 +393,7 @@ fn resolve_named_face(st: &ModelState, plane: &Plane, kind: LinkKind, body: &str let geom = if kind == LinkKind::Intersect { section(plane, &mesh, Some(index)) } else { - let mut geom = Vec::new(); - for edge in projection_face_edges(target, &mesh, index, plane)? { - if let Some(points) = mesh.edges.get(edge) { - geom.extend(fit_world(plane, points)); - } - } + let geom = projected_edges(target, &mesh, plane, &projection_face_edges(target, &mesh, index, plane)?); let geom = merge_split_circles(geom); if certified_planar_construction(target, index as usize) { merge_family_lines(geom)? } else { geom } }; @@ -425,11 +463,7 @@ pub fn resolve_face_indices(st: &ModelState, plane: &Plane, kind: LinkKind, body } else { order::family_edges(&mesh, &selected, plane)? }; - for edge in edges { - if let Some(points) = mesh.edges.get(edge) { - geometry.extend(fit_world(plane, points)); - } - } + geometry.extend(projected_edges(body, &mesh, plane, &edges)); } if kind != LinkKind::Intersect && (indices.len() > 1 || indices.first().is_some_and(|index| certified_planar_construction(body, *index))) { geometry = merge_family_lines(geometry)?; diff --git a/crates/engine/src/cmd/sketch_project_tests.rs b/crates/engine/src/cmd/sketch_project_tests.rs index d9855856b..376cb3c60 100644 --- a/crates/engine/src/cmd/sketch_project_tests.rs +++ b/crates/engine/src/cmd/sketch_project_tests.rs @@ -609,3 +609,71 @@ fn a_rectangle_put_onto_a_projected_edge_stays_a_closed_profile() { let reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); assert!((volume(&reopened, "Pad") - 3000.0).abs() < 1e-6, "{}", volume(&reopened, "Pad")); } + +/// A face with letters cut into it, extruded as a cut: its edges come into the face's sketch +/// as the letters' exact curves (a font's quadratics and cubics), not fitted to the mesh, so the +/// tool's walls lie on the letters' walls and the cut takes what the same region picked in the +/// sketch takes (#1360). Fitted to the mesh (684 lines, 31 arcs and 18 splines here), they lay +/// a few hundredths off the letters' walls, and the boolean found no result. +#[test] +fn a_face_engraved_with_text_projects_its_letters_exactly_and_extrudes() { + let volume = |s: &mut Session| run(s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64().unwrap(); + let engraved = || { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane":"XY"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0":[0,0],"p1":[105,26]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"distance":40})); + run(&mut s, "sketch.create", json!({"plane":{"face":[50,13,40]}})); + run(&mut s, "sketch.text", json!({"text":"textvraiment tres long","at":[3,9],"height":6.5})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"distance":-1,"operation":"cut"})); + s + }; + // The face round the letters, drawn in a sketch in its plane. + let mut drawn = engraved(); + let before = volume(&mut drawn); + run(&mut drawn, "sketch.create", json!({"plane":"XY","offset":40})); + run(&mut drawn, "sketch.rectangle.two_point", json!({"p0":[0,0],"p1":[105,26]})); + run(&mut drawn, "sketch.text", json!({"text":"textvraiment tres long","at":[3,9],"height":6.5})); + run(&mut drawn, "sketch.finish", json!({})); + run(&mut drawn, "solid.extrude", json!({"distance":-3.5,"operation":"cut","profiles":[{"point":[1,1]}]})); + let taken = before - volume(&mut drawn); + assert!(taken > 0.0, "{taken}"); + // The engraved face itself, extruded as a cut. + let mut s = engraved(); + let id = run(&mut s, "solid.extrude", json!({"distance":-3.5,"operation":"cut","face":[1,1,40]}))["feature"].as_u64().unwrap(); + let r = s.model.result(id).unwrap(); + assert!(r.error.is_none(), "{r:?}"); + let face = before - volume(&mut s); + assert!((face - taken).abs() < 1e-6 * before, "{face} {taken}"); + // Its sketch got the letters as Bézier pieces. + let st = s.model.state(); + let sketch = &st.sketches.last().unwrap().sketch; + let pieces = + sketch.curves.iter().filter(|c| c.link.is_some() && matches!(c.kind, solidcraft_sketch::CurveKind::Spline { control: true, .. })).count(); + assert!(pieces > 100, "{pieces}"); +} + +/// A design saved before free-form edges came in exactly, by the build before it: an "S" cut +/// 1 mm into a 30 × 20 × 10 block, then a sketch on that face (its edges projected, the letter's +/// fitted to the mesh as 72 lines, 9 arcs and 2 splines) with a circle cut 3 mm. On reopening, the +/// face's link is laid out again with the letter's exact pieces, and the part builds the same. +#[test] +fn a_face_sketch_saved_with_fitted_letters_reopens_and_builds_the_same() { + let text = include_str!("../../../../tests/projection/before-1508/engraved_face_sketched.json"); + let mut s = Session::new(solidcraft_doc::Document::from_json(text).unwrap()); + let volume = run(&mut s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64().unwrap(); + for name in ["Extrude2", "Sketch3", "Extrude3"] { + let id = s.doc.find_feature(name).unwrap().id; + let r = s.model.result(id).unwrap(); + assert!(r.error.is_none(), "{name}: {:?}", r.error); + } + // The build that saved it measured 5916.018831 mm³. + assert!((volume - 5916.018830904924).abs() < 1e-3, "{volume}"); + let st = s.model.state(); + let sketch = &st.sketches.last().unwrap().sketch; + let pieces = + sketch.curves.iter().filter(|c| c.link.is_some() && matches!(c.kind, solidcraft_sketch::CurveKind::Spline { control: true, .. })).count(); + assert!(pieces > 0, "{pieces}"); +} diff --git a/crates/kernel/src/body.rs b/crates/kernel/src/body.rs index 2e07cd468..642826aff 100644 --- a/crates/kernel/src/body.rs +++ b/crates/kernel/src/body.rs @@ -1365,6 +1365,29 @@ impl Body { .collect()) } + /// Edges `indices` (as in [`Body::tessellate`]'s `edges`) 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 isn't there, and for every edge of a mesh body. + pub fn planar_edges(&self, plane: &solidcraft_geom::Plane, indices: &[usize]) -> Vec>> { + let none = || vec![None; indices.len()]; + if self.is_mesh() { + return none(); + } + let tol = (self.size() * 1e-7).max(1e-9) * 10.0; + guard("planar edges", || { + let edges = Self::unique_edges(&self.solid); + Ok(indices + .iter() + .map(|i| { + let mut work = 262_144usize; + edges.get(*i).and_then(|e| crate::prism_curve::projected(e, plane, tol, &mut work)) + }) + .collect()) + }) + .unwrap_or_else(|_| none()) + } + /// Faces with area and centroid. pub fn faces(&self, tol: f64) -> Result> { let m = self.tessellate(tol)?; diff --git a/crates/kernel/src/prism_curve.rs b/crates/kernel/src/prism_curve.rs index e4e03dd2d..7a14a9bb2 100644 --- a/crates/kernel/src/prism_curve.rs +++ b/crates/kernel/src/prism_curve.rs @@ -242,6 +242,18 @@ pub(super) fn segment_fitted(e: &mt::Edge, plane: &Plane, tol: f64, fit: f64, wo } pub(super) fn segment(e: &mt::Edge, plane: &Plane, tol: f64, work: &mut usize) -> Option> { + read(e, plane, tol, work, false) +} + +/// Edge `e` in `plane` exactly, for a sketch to project it: as [`segment`], and a curve of +/// several Bézier spans (a chain of a font's curves, a spline through points) as one segment +/// per span, each the line, conic or Bézier it is. `None` when the edge doesn't lie in a plane +/// parallel to `plane` or isn't read exactly. +pub(crate) fn projected(e: &mt::Edge, plane: &Plane, tol: f64, work: &mut usize) -> Option> { + read(e, plane, tol, work, true) +} + +fn read(e: &mt::Edge, plane: &Plane, tol: f64, work: &mut usize, each_span: bool) -> Option> { if !tol.is_finite() || tol <= 0. { return None; } @@ -279,7 +291,45 @@ pub(super) fn segment(e: &mt::Edge, plane: &Plane, tol: f64, work: &mut usize) - if a.dist(b) > tol && spans.iter().all(|s| line_span(s, a, b, tol, error, work).is_some()) { return Some(vec![Seg2::Line { a, b }]); } - arc(&c, &spans, plane, a, b, tol, error, work).or_else(|| free_form(&spans, a, b, tol)) + arc(&c, &spans, plane, a, b, tol, error, work) + .or_else(|| free_form(&spans, a, b, tol)) + .or_else(|| if each_span { span_by_span(&spans, a, b, tol) } else { None }) +} + +/// Several `spans` end to end, from `a` to `b`, each as the segment it is: a span whose control +/// polygon lies along its chord a line, the others as [`free_form`] reads them. Spans whose +/// ends meet are left out; each segment starts where the one before ended. +fn span_by_span(spans: &[Vec], a: Vec2, b: Vec2, tol: f64) -> Option> { + let spans: Vec<&Vec> = spans.iter().filter(|s| s.first().zip(s.last()).is_some_and(|(p, q)| point(*p).dist(point(*q)) > tol)).collect(); + if spans.len() < 2 { + return None; + } + let mut out = Vec::with_capacity(spans.len()); + let mut start = a; + for (i, span) in spans.iter().enumerate() { + let end = if i + 1 == spans.len() { b } else { point(*span.last()?) }; + let seg = match free_form(std::slice::from_ref(*span), start, end, tol) { + Some(mut s) => s.pop()?, + None if span.iter().all(|p| (p[2] - 1.).abs() <= 1e-12) && off_chord(&span.iter().map(|p| point(*p)).collect::>()) <= tol => { + Seg2::Line { a: start, b: end } + } + None => return None, + }; + out.push(seg); + start = end; + } + Some(out) +} + +/// How far the control points `pts` lie off the chord between the first and the last. +fn off_chord(pts: &[Vec2]) -> f64 { + let (Some(first), Some(last)) = (pts.first().copied(), pts.last().copied()) else { return f64::INFINITY }; + let chord = last - first; + let len = chord.len(); + if !(len > 0.) { + return f64::INFINITY; + } + pts.iter().map(|p| chord.cross(*p - first).abs()).fold(0., f64::max) / len } /// One Bézier span that is neither a line nor an arc, as the exact free-form segment it is diff --git a/tests/projection/before-1508/engraved_face_sketched.json b/tests/projection/before-1508/engraved_face_sketched.json new file mode 100644 index 000000000..108b1549e --- /dev/null +++ b/tests/projection/before-1508/engraved_face_sketched.json @@ -0,0 +1 @@ +{"features":[{"id":1,"name":"Sketch1","plane":{"name":"XY","type":"origin"},"sketch":{"constraints":[{"id":"k1","l":0,"type":"horizontal"},{"id":"k2","l":2,"type":"horizontal"},{"id":"k3","l":1,"type":"vertical"},{"id":"k4","l":3,"type":"vertical"},{"id":"k5","p":0,"q":1,"type":"coincident"}],"counters":{"k":5,"l":4,"p":4},"curves":[{"a":1,"b":2,"construction":false,"id":"l1","type":"line"},{"a":2,"b":3,"construction":false,"id":"l2","type":"line"},{"a":3,"b":4,"construction":false,"id":"l3","type":"line"},{"a":4,"b":1,"construction":false,"id":"l4","type":"line"}],"points":[{"fixed":true,"id":"origin","pos":[0.0,0.0]},{"fixed":false,"id":"p1","pos":[0.0,0.0]},{"fixed":false,"id":"p2","pos":[30.0,0.0]},{"fixed":false,"id":"p3","pos":[30.0,20.0]},{"fixed":false,"id":"p4","pos":[0.0,20.0]}]},"suppressed":false,"type":"sketch"},{"extent":{"convention":"total_distance","direction":"positive","distance":"10"},"id":2,"name":"Extrude1","operation":"new_body","param_names":["d1"],"profiles":{"type":"all"},"sketch":1,"suppressed":false,"type":"extrude"},{"id":3,"name":"Sketch2","plane":{"anchor":{"author_path":[],"component":0,"coordinates":[0.0,0.0],"path":[],"target":{"body":"Body1","certificate":{"high":true,"holes":[],"kind":"extrude_cap","outer":["l1","l2","l3","l4"],"sketch":1},"name":"F2:cap:high:ed6121d9bed14d3fd103f347231990d103349f33b7874ad292d3c4d3539266c3","origin_feature":2,"point":[0.0,0.0,10.0]},"x_axis":[1.0,0.0]},"at":[15.0,10.0,10.0],"name":"F2:top","plane":{"origin":[0.0,0.0,10.0],"x_dir":[1.0,0.0,0.0],"y_dir":[0.0,1.0,0.0]},"type":"face"},"sketch":{"constraints":[],"counters":{"j":2,"k":32,"l":6,"p":70},"curves":[{"a":1,"b":2,"construction":false,"id":"l1","link":"j1","type":"line"},{"a":3,"b":1,"construction":false,"id":"l2","link":"j1","type":"line"},{"a":2,"b":4,"construction":false,"id":"l3","link":"j1","type":"line"},{"a":4,"b":3,"construction":false,"id":"l4","link":"j1","type":"line"},{"a":5,"apex":7,"b":6,"construction":false,"id":"k1","link":"j2","rho":0.5,"type":"conic"},{"a":6,"apex":9,"b":8,"construction":false,"id":"k2","link":"j2","rho":0.5,"type":"conic"},{"a":8,"apex":11,"b":10,"construction":false,"id":"k3","link":"j2","rho":0.5,"type":"conic"},{"a":10,"b":12,"construction":false,"id":"l5","link":"j2","type":"line"},{"a":12,"apex":14,"b":13,"construction":false,"id":"k4","link":"j2","rho":0.5,"type":"conic"},{"a":13,"apex":16,"b":15,"construction":false,"id":"k5","link":"j2","rho":0.5,"type":"conic"},{"a":15,"apex":18,"b":17,"construction":false,"id":"k6","link":"j2","rho":0.5,"type":"conic"},{"a":17,"apex":20,"b":19,"construction":false,"id":"k7","link":"j2","rho":0.5,"type":"conic"},{"a":19,"apex":22,"b":21,"construction":false,"id":"k8","link":"j2","rho":0.5,"type":"conic"},{"a":21,"apex":24,"b":23,"construction":false,"id":"k9","link":"j2","rho":0.5,"type":"conic"},{"a":23,"apex":26,"b":25,"construction":false,"id":"k10","link":"j2","rho":0.5,"type":"conic"},{"a":25,"apex":28,"b":27,"construction":false,"id":"k11","link":"j2","rho":0.5,"type":"conic"},{"a":27,"apex":30,"b":29,"construction":false,"id":"k12","link":"j2","rho":0.5,"type":"conic"},{"a":29,"apex":32,"b":31,"construction":false,"id":"k13","link":"j2","rho":0.5,"type":"conic"},{"a":31,"apex":34,"b":33,"construction":false,"id":"k14","link":"j2","rho":0.5,"type":"conic"},{"a":33,"apex":36,"b":35,"construction":false,"id":"k15","link":"j2","rho":0.5,"type":"conic"},{"a":35,"apex":38,"b":37,"construction":false,"id":"k16","link":"j2","rho":0.5,"type":"conic"},{"a":37,"apex":40,"b":39,"construction":false,"id":"k17","link":"j2","rho":0.5,"type":"conic"},{"a":39,"apex":42,"b":41,"construction":false,"id":"k18","link":"j2","rho":0.5,"type":"conic"},{"a":41,"apex":44,"b":43,"construction":false,"id":"k19","link":"j2","rho":0.5,"type":"conic"},{"a":43,"b":45,"construction":false,"id":"l6","link":"j2","type":"line"},{"a":45,"apex":47,"b":46,"construction":false,"id":"k20","link":"j2","rho":0.5,"type":"conic"},{"a":46,"apex":49,"b":48,"construction":false,"id":"k21","link":"j2","rho":0.5,"type":"conic"},{"a":48,"apex":51,"b":50,"construction":false,"id":"k22","link":"j2","rho":0.5,"type":"conic"},{"a":50,"apex":53,"b":52,"construction":false,"id":"k23","link":"j2","rho":0.5,"type":"conic"},{"a":52,"apex":55,"b":54,"construction":false,"id":"k24","link":"j2","rho":0.5,"type":"conic"},{"a":54,"apex":57,"b":56,"construction":false,"id":"k25","link":"j2","rho":0.5,"type":"conic"},{"a":56,"apex":59,"b":58,"construction":false,"id":"k26","link":"j2","rho":0.5,"type":"conic"},{"a":58,"apex":61,"b":60,"construction":false,"id":"k27","link":"j2","rho":0.5,"type":"conic"},{"a":60,"apex":63,"b":62,"construction":false,"id":"k28","link":"j2","rho":0.5,"type":"conic"},{"a":62,"apex":65,"b":64,"construction":false,"id":"k29","link":"j2","rho":0.5,"type":"conic"},{"a":64,"apex":67,"b":66,"construction":false,"id":"k30","link":"j2","rho":0.5,"type":"conic"},{"a":66,"apex":69,"b":68,"construction":false,"id":"k31","link":"j2","rho":0.5,"type":"conic"},{"a":68,"apex":70,"b":5,"construction":false,"id":"k32","link":"j2","rho":0.5,"type":"conic"}],"links":[{"auto_face":true,"face_name":"F2:cap:high:ed6121d9bed14d3fd103f347231990d103349f33b7874ad292d3c4d3539266c3","id":"j1","kind":"project","source":{"at":[20.0,6.666666666666667,10.0],"body":"Body1","type":"face"}},{"id":"j2","kind":"text","source":{"angle":0.0,"at":[10.0,4.0],"height":12.0,"text":"S","type":"text"}}],"points":[{"fixed":true,"id":"origin","pos":[0.0,0.0]},{"fixed":true,"id":"p1","link":"j1","pos":[0.0,0.0]},{"fixed":true,"id":"p2","link":"j1","pos":[0.0,20.0]},{"fixed":true,"id":"p3","link":"j1","pos":[30.0,0.0]},{"fixed":true,"id":"p4","link":"j1","pos":[30.0,20.0]},{"fixed":true,"id":"p5","link":"j2","pos":[20.833215046132008,7.312987934705465]},{"fixed":true,"id":"p6","link":"j2","pos":[19.534421575585522,4.740951029098651]},{"fixed":true,"id":"p7","link":"j2","pos":[20.833215046132008,5.652235628105039]},{"fixed":true,"id":"p8","link":"j2","pos":[15.876508161816892,3.829666430092264]},{"fixed":true,"id":"p9","link":"j2","pos":[18.235628105039034,3.829666430092264]},{"fixed":true,"id":"p10","link":"j2","pos":[10.792051100070973,6.878637331440737]},{"fixed":true,"id":"p11","link":"j2","pos":[11.490418736692689,3.829666430092264]},{"fixed":true,"id":"p12","link":"j2","pos":[12.36763662171753,7.19375443577005]},{"fixed":true,"id":"p13","link":"j2","pos":[13.525904897090134,5.605393896380411]},{"fixed":true,"id":"p14","link":"j2","pos":[12.640170333569907,6.112136266855926]},{"fixed":true,"id":"p15","link":"j2","pos":[15.9361249112846,5.098651525904897]},{"fixed":true,"id":"p16","link":"j2","pos":[14.411639460610361,5.098651525904897]},{"fixed":true,"id":"p17","link":"j2","pos":[18.36763662171753,5.639460610361959]},{"fixed":true,"id":"p18","link":"j2","pos":[17.511710432931157,5.098651525904897]},{"fixed":true,"id":"p19","link":"j2","pos":[19.223562810503903,7.2278211497515965]},{"fixed":true,"id":"p20","link":"j2","pos":[19.223562810503903,6.180269694819021]},{"fixed":true,"id":"p21","link":"j2","pos":[18.95528743789922,8.18168914123492]},{"fixed":true,"id":"p22","link":"j2","pos":[19.223562810503903,7.815471965933286]},{"fixed":true,"id":"p23","link":"j2","pos":[18.20156139105749,8.786373314407381]},{"fixed":true,"id":"p24","link":"j2","pos":[18.687012065294535,8.547906316536551]},{"fixed":true,"id":"p25","link":"j2","pos":[17.043293115684882,9.186657203690562]},{"fixed":true,"id":"p26","link":"j2","pos":[17.716110716820438,9.024840312278211]},{"fixed":true,"id":"p27","link":"j2","pos":[15.552874378992193,9.53584102200142]},{"fixed":true,"id":"p28","link":"j2","pos":[16.370475514549327,9.34847409510291]},{"fixed":true,"id":"p29","link":"j2","pos":[13.39389638041164,10.166075230660041]},{"fixed":true,"id":"p30","link":"j2","pos":[14.130589070262598,9.850958126330731]},{"fixed":true,"id":"p31","link":"j2","pos":[12.231369765791342,10.868701206529455]},{"fixed":true,"id":"p32","link":"j2","pos":[12.657203690560682,10.481192334989354]},{"fixed":true,"id":"p33","link":"j2","pos":[11.57984386089425,11.775727466288147]},{"fixed":true,"id":"p34","link":"j2","pos":[11.805535841022001,11.256210078069554]},{"fixed":true,"id":"p35","link":"j2","pos":[11.354151880766501,12.968062455642299]},{"fixed":true,"id":"p36","link":"j2","pos":[11.354151880766501,12.295244854506743]},{"fixed":true,"id":"p37","link":"j2","pos":[12.533711852377573,15.344215755855217]},{"fixed":true,"id":"p38","link":"j2","pos":[11.354151880766501,14.50958126330731]},{"fixed":true,"id":"p39","link":"j2","pos":[15.910574875798439,16.178850248403123]},{"fixed":true,"id":"p40","link":"j2","pos":[13.713271823988645,16.178850248403123]},{"fixed":true,"id":"p41","link":"j2","pos":[19.036195883605394,15.552874378992193]},{"fixed":true,"id":"p42","link":"j2","pos":[17.95457771469127,16.178850248403123]},{"fixed":true,"id":"p43","link":"j2","pos":[20.552164655784246,13.4194464158978]},{"fixed":true,"id":"p44","link":"j2","pos":[20.117814052519517,14.926898509581264]},{"fixed":true,"id":"p45","link":"j2","pos":[18.951029098651524,13.138396025550035]},{"fixed":true,"id":"p46","link":"j2","pos":[17.946061036195886,14.52235628105039]},{"fixed":true,"id":"p47","link":"j2","pos":[18.687012065294535,14.092264017033356]},{"fixed":true,"id":"p48","link":"j2","pos":[15.893541518807666,14.952448545067423]},{"fixed":true,"id":"p49","link":"j2","pos":[17.205110007097232,14.952448545067423]},{"fixed":true,"id":"p50","link":"j2","pos":[13.69623846699787,14.475514549325762]},{"fixed":true,"id":"p51","link":"j2","pos":[14.454222853087295,14.952448545067423]},{"fixed":true,"id":"p52","link":"j2","pos":[12.938254080908447,13.053229240596167]},{"fixed":true,"id":"p53","link":"j2","pos":[12.938254080908447,13.998580553584102]},{"fixed":true,"id":"p54","link":"j2","pos":[13.23207948899929,12.137686302342086]},{"fixed":true,"id":"p55","link":"j2","pos":[12.938254080908447,12.499645138396026]},{"fixed":true,"id":"p56","link":"j2","pos":[14.079488999290277,11.524485450674238]},{"fixed":true,"id":"p57","link":"j2","pos":[13.525904897090134,11.775727466288147]},{"fixed":true,"id":"p58","link":"j2","pos":[16.285308729595457,10.907026259758695]},{"fixed":true,"id":"p59","link":"j2","pos":[14.633073101490417,11.273243435060326]},{"fixed":true,"id":"p60","link":"j2","pos":[17.388218594748047,10.647267565649397]},{"fixed":true,"id":"p61","link":"j2","pos":[16.8388928317956,10.779276082327893]},{"fixed":true,"id":"p62","link":"j2","pos":[18.44002838892832,10.332150461320085]},{"fixed":true,"id":"p63","link":"j2","pos":[17.937544357700496,10.5152590489709]},{"fixed":true,"id":"p64","link":"j2","pos":[19.38112136266856,9.902058197303052]},{"fixed":true,"id":"p65","link":"j2","pos":[18.942512420156138,10.149041873669269]},{"fixed":true,"id":"p66","link":"j2","pos":[20.143364088005676,9.297374024130589]},{"fixed":true,"id":"p67","link":"j2","pos":[19.81973030518098,9.655074520936836]},{"fixed":true,"id":"p68","link":"j2","pos":[20.65010645848119,8.454222853087295]},{"fixed":true,"id":"p69","link":"j2","pos":[20.466997870830376,8.939673527324343]},{"fixed":true,"id":"p70","link":"j2","pos":[20.833215046132008,7.968772178850248]}]},"suppressed":false,"type":"sketch"},{"extent":{"convention":"total_distance","direction":"positive","distance":"-1"},"id":4,"name":"Extrude2","operation":"cut","param_names":["d2"],"profiles":{"type":"all"},"sketch":3,"suppressed":false,"type":"extrude"},{"id":5,"name":"Sketch3","plane":{"anchor":{"author_path":[],"component":0,"coordinates":[0.0,0.0],"path":[],"target":{"body":"Body1","certificate":{"high":true,"holes":[],"kind":"extrude_cap","outer":["l1","l2","l3","l4"],"sketch":1},"name":"F2:cap:high:ed6121d9bed14d3fd103f347231990d103349f33b7874ad292d3c4d3539266c3","origin_feature":2,"point":[0.0,0.0,10.0]},"x_axis":[1.0,0.0]},"at":[1.0,1.0,10.0],"name":"F2:top","plane":{"origin":[0.0,0.0,10.000000000000012],"x_dir":[1.0,0.0,0.0],"y_dir":[0.0,1.0,0.0]},"type":"face"},"sketch":{"constraints":[],"counters":{"a":9,"c":1,"j":1,"l":76,"p":107,"s":2},"curves":[{"a":1,"b":2,"construction":false,"id":"l1","link":"j1","type":"line"},{"a":3,"b":1,"construction":false,"id":"l2","link":"j1","type":"line"},{"a":2,"b":4,"construction":false,"id":"l3","link":"j1","type":"line"},{"a":4,"b":3,"construction":false,"id":"l4","link":"j1","type":"line"},{"construction":false,"degree":3,"id":"s1","link":"j1","pts":[5,6,7,8,9,10,11,12,13],"type":"spline"},{"a":14,"b":5,"construction":false,"id":"l5","link":"j1","type":"line"},{"a":16,"b":17,"c":15,"construction":false,"id":"a1","link":"j1","type":"arc"},{"a":18,"b":19,"construction":false,"id":"l6","link":"j1","type":"line"},{"a":19,"b":20,"construction":false,"id":"l7","link":"j1","type":"line"},{"a":20,"b":21,"construction":false,"id":"l8","link":"j1","type":"line"},{"a":21,"b":16,"construction":false,"id":"l9","link":"j1","type":"line"},{"a":17,"b":23,"c":22,"construction":false,"id":"a2","link":"j1","type":"arc"},{"a":23,"b":25,"c":24,"construction":false,"id":"a3","link":"j1","type":"arc"},{"a":26,"b":27,"construction":false,"id":"l10","link":"j1","type":"line"},{"a":27,"b":28,"construction":false,"id":"l11","link":"j1","type":"line"},{"a":28,"b":29,"construction":false,"id":"l12","link":"j1","type":"line"},{"a":29,"b":14,"construction":false,"id":"l13","link":"j1","type":"line"},{"a":30,"b":31,"construction":false,"id":"l14","link":"j1","type":"line"},{"a":31,"b":32,"construction":false,"id":"l15","link":"j1","type":"line"},{"a":32,"b":33,"construction":false,"id":"l16","link":"j1","type":"line"},{"a":33,"b":18,"construction":false,"id":"l17","link":"j1","type":"line"},{"a":34,"b":35,"construction":false,"id":"l18","link":"j1","type":"line"},{"a":35,"b":36,"construction":false,"id":"l19","link":"j1","type":"line"},{"a":36,"b":37,"construction":false,"id":"l20","link":"j1","type":"line"},{"a":37,"b":38,"construction":false,"id":"l21","link":"j1","type":"line"},{"a":38,"b":39,"construction":false,"id":"l22","link":"j1","type":"line"},{"a":39,"b":40,"construction":false,"id":"l23","link":"j1","type":"line"},{"a":40,"b":41,"construction":false,"id":"l24","link":"j1","type":"line"},{"a":34,"b":43,"c":42,"construction":false,"id":"a4","link":"j1","type":"arc"},{"a":25,"b":44,"construction":false,"id":"l25","link":"j1","type":"line"},{"a":44,"b":45,"construction":false,"id":"l26","link":"j1","type":"line"},{"a":45,"b":46,"construction":false,"id":"l27","link":"j1","type":"line"},{"a":46,"b":47,"construction":false,"id":"l28","link":"j1","type":"line"},{"a":48,"b":49,"construction":false,"id":"l29","link":"j1","type":"line"},{"a":49,"b":50,"construction":false,"id":"l30","link":"j1","type":"line"},{"a":50,"b":51,"construction":false,"id":"l31","link":"j1","type":"line"},{"a":51,"b":26,"construction":false,"id":"l32","link":"j1","type":"line"},{"a":41,"b":52,"construction":false,"id":"l33","link":"j1","type":"line"},{"a":52,"b":53,"construction":false,"id":"l34","link":"j1","type":"line"},{"a":53,"b":54,"construction":false,"id":"l35","link":"j1","type":"line"},{"a":54,"b":55,"construction":false,"id":"l36","link":"j1","type":"line"},{"construction":false,"degree":3,"id":"s2","link":"j1","pts":[56,57,58,59,60,43],"type":"spline"},{"a":47,"b":61,"construction":false,"id":"l37","link":"j1","type":"line"},{"a":13,"b":62,"construction":false,"id":"l38","link":"j1","type":"line"},{"a":62,"b":63,"construction":false,"id":"l39","link":"j1","type":"line"},{"a":63,"b":64,"construction":false,"id":"l40","link":"j1","type":"line"},{"a":64,"b":65,"construction":false,"id":"l41","link":"j1","type":"line"},{"a":55,"b":66,"construction":false,"id":"l42","link":"j1","type":"line"},{"a":66,"b":67,"construction":false,"id":"l43","link":"j1","type":"line"},{"a":67,"b":68,"construction":false,"id":"l44","link":"j1","type":"line"},{"a":68,"b":69,"construction":false,"id":"l45","link":"j1","type":"line"},{"a":70,"b":71,"construction":false,"id":"l46","link":"j1","type":"line"},{"a":71,"b":72,"construction":false,"id":"l47","link":"j1","type":"line"},{"a":72,"b":73,"construction":false,"id":"l48","link":"j1","type":"line"},{"a":73,"b":30,"construction":false,"id":"l49","link":"j1","type":"line"},{"a":74,"b":75,"construction":false,"id":"l50","link":"j1","type":"line"},{"a":75,"b":76,"construction":false,"id":"l51","link":"j1","type":"line"},{"a":76,"b":77,"construction":false,"id":"l52","link":"j1","type":"line"},{"a":77,"b":48,"construction":false,"id":"l53","link":"j1","type":"line"},{"a":78,"b":56,"construction":false,"id":"l54","link":"j1","type":"line"},{"a":80,"b":61,"c":79,"construction":false,"id":"a5","link":"j1","type":"arc"},{"a":81,"b":78,"construction":false,"id":"l55","link":"j1","type":"line"},{"a":69,"b":82,"construction":false,"id":"l56","link":"j1","type":"line"},{"a":82,"b":83,"construction":false,"id":"l57","link":"j1","type":"line"},{"a":83,"b":84,"construction":false,"id":"l58","link":"j1","type":"line"},{"a":84,"b":85,"construction":false,"id":"l59","link":"j1","type":"line"},{"a":87,"b":80,"c":86,"construction":false,"id":"a6","link":"j1","type":"arc"},{"a":88,"b":89,"construction":false,"id":"l60","link":"j1","type":"line"},{"a":89,"b":90,"construction":false,"id":"l61","link":"j1","type":"line"},{"a":90,"b":91,"construction":false,"id":"l62","link":"j1","type":"line"},{"a":91,"b":74,"construction":false,"id":"l63","link":"j1","type":"line"},{"a":92,"b":81,"construction":false,"id":"l64","link":"j1","type":"line"},{"a":85,"b":93,"construction":false,"id":"l65","link":"j1","type":"line"},{"a":87,"b":94,"construction":false,"id":"l66","link":"j1","type":"line"},{"a":94,"b":95,"construction":false,"id":"l67","link":"j1","type":"line"},{"a":95,"b":88,"construction":false,"id":"l68","link":"j1","type":"line"},{"a":93,"b":96,"construction":false,"id":"l69","link":"j1","type":"line"},{"a":96,"b":97,"construction":false,"id":"l70","link":"j1","type":"line"},{"a":97,"b":98,"construction":false,"id":"l71","link":"j1","type":"line"},{"a":98,"b":70,"construction":false,"id":"l72","link":"j1","type":"line"},{"a":100,"b":92,"c":99,"construction":false,"id":"a7","link":"j1","type":"arc"},{"a":65,"b":101,"construction":false,"id":"l73","link":"j1","type":"line"},{"a":101,"b":102,"construction":false,"id":"l74","link":"j1","type":"line"},{"a":102,"b":103,"construction":false,"id":"l75","link":"j1","type":"line"},{"a":103,"b":104,"construction":false,"id":"l76","link":"j1","type":"line"},{"a":106,"b":100,"c":105,"construction":false,"id":"a8","link":"j1","type":"arc"},{"a":104,"b":106,"c":107,"construction":false,"id":"a9","link":"j1","type":"arc"},{"c":108,"construction":false,"id":"c1","r":2.0,"type":"circle"}],"links":[{"auto_face":true,"face_name":"F2:cap:high:ed6121d9bed14d3fd103f347231990d103349f33b7874ad292d3c4d3539266c3","id":"j1","kind":"project","source":{"at":[15.292169387272297,1.2765554766974212,9.999999999999998],"body":"Body1","type":"face"}}],"points":[{"fixed":true,"id":"origin","pos":[0.0,0.0]},{"fixed":true,"id":"p1","link":"j1","pos":[0.0,0.0]},{"fixed":true,"id":"p2","link":"j1","pos":[0.0,20.0]},{"fixed":true,"id":"p3","link":"j1","pos":[30.0,0.0]},{"fixed":true,"id":"p4","link":"j1","pos":[30.0,20.0]},{"fixed":true,"id":"p5","link":"j1","pos":[10.792051100070973,6.878637331440737]},{"fixed":true,"id":"p6","link":"j1","pos":[11.024263662171752,6.164034776437189]},{"fixed":true,"id":"p7","link":"j1","pos":[11.371717530163238,5.544712562100781]},{"fixed":true,"id":"p8","link":"j1","pos":[11.83441270404542,5.020670688431512]},{"fixed":true,"id":"p9","link":"j1","pos":[12.412349183818309,4.591909155429383]},{"fixed":true,"id":"p10","link":"j1","pos":[13.1055269694819,4.258427963094393]},{"fixed":true,"id":"p11","link":"j1","pos":[13.913946061036196,4.020227111426544]},{"fixed":true,"id":"p12","link":"j1","pos":[14.837606458481192,3.8773066004258343]},{"fixed":true,"id":"p13","link":"j1","pos":[15.876508161816892,3.829666430092264]},{"fixed":true,"id":"p14","link":"j1","pos":[12.36763662171753,7.19375443577005]},{"fixed":true,"id":"p15","link":"j1","pos":[14.321210265374514,12.912156592789684]},{"fixed":true,"id":"p16","link":"j1","pos":[11.354151880766501,12.968062455642299]},{"fixed":true,"id":"p17","link":"j1","pos":[11.579843860894265,11.775727466288153]},{"fixed":true,"id":"p18","link":"j1","pos":[12.533711852377573,15.344215755855217]},{"fixed":true,"id":"p19","link":"j1","pos":[12.017654364797728,14.882718239886444]},{"fixed":true,"id":"p20","link":"j1","pos":[11.649041873669269,14.332860184528034]},{"fixed":true,"id":"p21","link":"j1","pos":[11.427874378992193,13.694641589779984]},{"fixed":true,"id":"p22","link":"j1","pos":[13.99536666771571,12.823309443070993]},{"fixed":true,"id":"p23","link":"j1","pos":[12.231369765791332,10.868701206529442]},{"fixed":true,"id":"p24","link":"j1","pos":[14.925427192887696,14.013102125877557]},{"fixed":true,"id":"p25","link":"j1","pos":[13.393896380411652,10.166075230660072]},{"fixed":true,"id":"p26","link":"j1","pos":[13.525904897090134,5.605393896380411]},{"fixed":true,"id":"p27","link":"j1","pos":[13.121362668559263,5.8946948190205815]},{"fixed":true,"id":"p28","link":"j1","pos":[12.79347054648687,6.255855216465578]},{"fixed":true,"id":"p29","link":"j1","pos":[12.542228530872958,6.688875088715401]},{"fixed":true,"id":"p30","link":"j1","pos":[15.910574875798439,16.178850248403123]},{"fixed":true,"id":"p31","link":"j1","pos":[14.875532292405962,16.126685592618877]},{"fixed":true,"id":"p32","link":"j1","pos":[13.967707594038325,15.970191625266146]},{"fixed":true,"id":"p33","link":"j1","pos":[13.187100780695529,15.709368346344927]},{"fixed":true,"id":"p34","link":"j1","pos":[13.23207948899929,12.137686302342086]},{"fixed":true,"id":"p35","link":"j1","pos":[13.103530872959546,12.330642299503193]},{"fixed":true,"id":"p36","link":"j1","pos":[13.011710432931157,12.547551454932577]},{"fixed":true,"id":"p37","link":"j1","pos":[12.938254080908447,13.053229240596167]},{"fixed":true,"id":"p38","link":"j1","pos":[12.985628105039035,13.496628814762241]},{"fixed":true,"id":"p39","link":"j1","pos":[13.127750177430801,13.881476224272532]},{"fixed":true,"id":"p40","link":"j1","pos":[13.364620298083747,14.207771469127039]},{"fixed":true,"id":"p41","link":"j1","pos":[13.69623846699787,14.475514549325762]},{"fixed":true,"id":"p42","link":"j1","pos":[14.95699640745204,13.629288796634066]},{"fixed":true,"id":"p43","link":"j1","pos":[14.079488999290277,11.524485450674238]},{"fixed":true,"id":"p44","link":"j1","pos":[13.805092264017034,10.008516678495386]},{"fixed":true,"id":"p45","link":"j1","pos":[14.301987224982255,9.850958126330731]},{"fixed":true,"id":"p46","link":"j1","pos":[14.884581263307311,9.693399574166076]},{"fixed":true,"id":"p47","link":"j1","pos":[15.552874378992193,9.53584102200142]},{"fixed":true,"id":"p48","link":"j1","pos":[15.9361249112846,5.098651525904897]},{"fixed":true,"id":"p49","link":"j1","pos":[15.213804116394606,5.130322924059616]},{"fixed":true,"id":"p50","link":"j1","pos":[14.571327182398864,5.225337118523775]},{"fixed":true,"id":"p51","link":"j1","pos":[14.008694109297373,5.383694109297373]},{"fixed":true,"id":"p52","link":"j1","pos":[14.117814052519517,14.684173172462739]},{"fixed":true,"id":"p53","link":"j1","pos":[14.624556422995031,14.833215046132008]},{"fixed":true,"id":"p54","link":"j1","pos":[15.216465578424415,14.922640170333569]},{"fixed":true,"id":"p55","link":"j1","pos":[15.893541518807666,14.952448545067423]},{"fixed":true,"id":"p56","link":"j1","pos":[16.28530872959546,10.907026259758695]},{"fixed":true,"id":"p57","link":"j1","pos":[15.527856635911995,11.082948899929027]},{"fixed":true,"id":"p58","link":"j1","pos":[14.907735982966642,11.244499645138395]},{"fixed":true,"id":"p59","link":"j1","pos":[14.424946770759401,11.391678495386799]},{"fixed":true,"id":"p60","link":"j1","pos":[14.235051454932577,11.45987845990064]},{"fixed":true,"id":"p61","link":"j1","pos":[17.043293115684882,9.186657203690562]},{"fixed":true,"id":"p62","link":"j1","pos":[16.989797728885737,3.886621717530163]},{"fixed":true,"id":"p63","link":"j1","pos":[17.97054648687012,4.057487579843861]},{"fixed":true,"id":"p64","link":"j1","pos":[18.81875443577005,4.342264017033356]},{"fixed":true,"id":"p65","link":"j1","pos":[19.534421575585522,4.740951029098651]},{"fixed":true,"id":"p66","link":"j1","pos":[16.51366217175302,14.925567778566359]},{"fixed":true,"id":"p67","link":"j1","pos":[17.062455642299504,14.844925479063166]},{"fixed":true,"id":"p68","link":"j1","pos":[17.539921930447125,14.710521646557842]},{"fixed":true,"id":"p69","link":"j1","pos":[17.946061036195886,14.52235628105039]},{"fixed":true,"id":"p70","link":"j1","pos":[19.036195883605394,15.552874378992193]},{"fixed":true,"id":"p71","link":"j1","pos":[18.435237757274663,15.826738821859475]},{"fixed":true,"id":"p72","link":"j1","pos":[17.713981547196592,16.022356281050392]},{"fixed":true,"id":"p73","link":"j1","pos":[16.872427253371185,16.13972675656494]},{"fixed":true,"id":"p74","link":"j1","pos":[18.36763662171753,5.639460610361959]},{"fixed":true,"id":"p75","link":"j1","pos":[17.894694819020582,5.402856635911993]},{"fixed":true,"id":"p76","link":"j1","pos":[17.331795599716113,5.2338537970191625]},{"fixed":true,"id":"p77","link":"j1","pos":[16.678938963804118,5.1324520936834634]},{"fixed":true,"id":"p78","link":"j1","pos":[17.388218594748047,10.6472675656494]},{"fixed":true,"id":"p79","link":"j1","pos":[15.79972179981811,3.712303733873097]},{"fixed":true,"id":"p80","link":"j1","pos":[18.20156139105752,8.786373314407447]},{"fixed":true,"id":"p81","link":"j1","pos":[18.44002838892832,10.332150461320085]},{"fixed":true,"id":"p82","link":"j1","pos":[18.28672817601136,14.27457416607523]},{"fixed":true,"id":"p83","link":"j1","pos":[18.567778566359124,13.961320085166784]},{"fixed":true,"id":"p84","link":"j1","pos":[18.789212207239174,13.582594038325052]},{"fixed":true,"id":"p85","link":"j1","pos":[18.951029098651524,13.138396025550035]},{"fixed":true,"id":"p86","link":"j1","pos":[17.359186352552175,6.9642767421805685]},{"fixed":true,"id":"p87","link":"j1","pos":[18.95528743789927,8.181689141234957]},{"fixed":true,"id":"p88","link":"j1","pos":[19.223562810503903,7.2278211497515965]},{"fixed":true,"id":"p89","link":"j1","pos":[19.170067423704754,6.735716820440028]},{"fixed":true,"id":"p90","link":"j1","pos":[19.00958126330731,6.306955287437899]},{"fixed":true,"id":"p91","link":"j1","pos":[18.74210432931157,5.941536550745209]},{"fixed":true,"id":"p92","link":"j1","pos":[19.38112136266856,9.902058197303052]},{"fixed":true,"id":"p93","link":"j1","pos":[20.552164655784246,13.4194464158978]},{"fixed":true,"id":"p94","link":"j1","pos":[19.072657913413767,7.984740951029099]},{"fixed":true,"id":"p95","link":"j1","pos":[19.15649396735273,7.760113555713272]},{"fixed":true,"id":"p96","link":"j1","pos":[20.294535131298797,14.118080198722499]},{"fixed":true,"id":"p97","link":"j1","pos":[19.955997161107167,14.70652945351313]},{"fixed":true,"id":"p98","link":"j1","pos":[19.536550745209368,15.184794180269696]},{"fixed":true,"id":"p99","link":"j1","pos":[17.91521504245348,7.271420651307362]},{"fixed":true,"id":"p100","link":"j1","pos":[20.143364088005676,9.297374024130589]},{"fixed":true,"id":"p101","link":"j1","pos":[20.102643718949608,5.2434350603264726]},{"fixed":true,"id":"p102","link":"j1","pos":[20.508516678495386,5.83960255500355]},{"fixed":true,"id":"p103","link":"j1","pos":[20.752040454222854,6.529453513129879]},{"fixed":true,"id":"p104","link":"j1","pos":[20.833215046132008,7.312987934705465]},{"fixed":true,"id":"p105","link":"j1","pos":[18.1909006867968,7.550069570997099]},{"fixed":true,"id":"p106","link":"j1","pos":[20.65010645848119,8.454222853087295]},{"fixed":true,"id":"p107","link":"j1","pos":[17.604611132344434,7.380272805619005]},{"fixed":false,"id":"c1.center","pos":[4.0,4.0]}]},"suppressed":false,"type":"sketch"},{"extent":{"convention":"total_distance","direction":"positive","distance":"-3"},"id":6,"name":"Extrude3","operation":"cut","param_names":["d3"],"profiles":{"loops":[["c1"]],"type":"curves"},"sketch":5,"suppressed":false,"type":"extrude"}],"format":"solidcraft/22","name":"before","next_id":7,"params":[],"units":"mm"} \ No newline at end of file From 8e762fee578596fe37bc4348abaeca67b5f760c2 Mon Sep 17 00:00:00 2001 From: CypherNaugh_0x <9931495+CypherNaught-0x@users.noreply.github.com> Date: Mon, 19 Oct 2026 03:29:03 +0200 Subject: [PATCH 031/225] Add optional ambient occlusion and graphics quality presets (#1135) Thanks @CypherNaught-0x. --- CONTRIBUTING.md | 14 ++ ROADMAP.md | 4 + assets/locales/de.json | 9 + assets/locales/en.json | 9 + assets/locales/fr.json | 9 + assets/locales/ja.json | 9 + assets/locales/ko.json | 9 + assets/locales/ru.json | 9 + assets/locales/zh.json | 9 + assets/shaders/viewport.wgsl | 63 +++++- crates/engine/src/cmd/view_navigation.rs | 65 +++++- crates/gpu/src/capture.rs | 1 + crates/gpu/src/view.rs | 20 +- crates/gpu/src/view/ao.rs | 167 ++++++++++++++ crates/ui-egui/src/control.rs | 2 +- crates/ui-egui/src/gpu.rs | 1 + crates/ui-egui/src/lib.rs | 13 ++ crates/ui-egui/src/measurement_ui_tests.rs | 3 + crates/ui-egui/src/prefs.rs | 205 ++++++++++++++++-- crates/ui-egui/src/render_workspace.rs | 2 + crates/ui-egui/src/viewport.rs | 16 +- .../scenarios/colour_vision_setting.json | 9 +- docs/ambient-occlusion.md | 101 +++++++++ xtask/src/features.rs | 41 ++-- 24 files changed, 735 insertions(+), 55 deletions(-) create mode 100644 crates/gpu/src/view/ao.rs create mode 100644 docs/ambient-occlusion.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a5dbd3422..923c103c7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -359,6 +359,20 @@ In order of how much they'd help users: 3. **Drawings, CAM and mesh tools.** These are out of scope for now (see [ROADMAP.md](ROADMAP.md)), but anyone who wants to own one is welcome. +## Updating the generated feature list + +After adding or renaming commands, run `cargo xtask features`. The registry is the +source of truth for `docs/features.md`; do not hand-edit the generated rows. +The generator sorts commands by ID and omits global and per-section counters, +so additions to unrelated areas no longer rewrite shared summary lines. + +If two branches still conflict in this file (for example, adjacent additions in +the same area), first resolve the command registry and source conflicts, then run +`cargo xtask features` again and stage the regenerated file. Do not use Git's +`union` merge driver: it can silently retain stale or duplicate command rows. +The generator tests cover stable ordering and additions that leave existing lines +unchanged. The initial switch to sorted rows is a one-time larger diff. + ## Licence By contributing you agree that your contribution is licensed as MIT OR Apache-2.0, like the rest diff --git a/ROADMAP.md b/ROADMAP.md index f82dea99b..cfe4d7a47 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -14,6 +14,10 @@ features → parametric timeline) as an open, pure-Rust, agent-drivable applicat | Gates | `cargo xtask ci`: fmt, clippy -D warnings, tests, asset attribution, layering, wasm32 build — green | | Time to a useful alpha (M0–M6) | ≈ **82 agent hours** remain (sum of the M1–M6 estimates below) | +Optional GPU viewport ambient occlusion is available in View settings and Graphics preferences, +with persistent settings, Performance/Quality graphics presets (Quality combines AO, Fine tessellation and adaptive 2× supersampling; manual combinations show Custom), and the +`view.ambient_occlusion` and `view.graphics_preset` commands. See [display settings](docs/ambient-occlusion.md). + ## Scope (owner decision, 2026-10-07) The issue batch adds preservation of blind pockets in through cuts, associative projected diff --git a/assets/locales/de.json b/assets/locales/de.json index 914914962..78bbe8d25 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -425,8 +425,10 @@ "cmd.timeline_roll_to": "Verlaufsmarkierung verschieben", "cmd.timeline_rollback": "Zeitleistenmarkierung verschieben", "cmd.timeline_suppress": "Merkmal unterdrücken", + "cmd.view_ambient_occlusion": "Umgebungsverdeckung", "cmd.view_apply": "Benannte Ansicht wiederherstellen", "cmd.view_delete": "Benannte Ansicht löschen", + "cmd.view_graphics_preset": "Grafikprofil", "cmd.view_list": "Benannte Ansichten auflisten", "cmd.view_navigate": "Ansicht navigieren", "cmd.view_rename": "Benannte Ansicht umbenennen", @@ -756,6 +758,8 @@ "ui.ai_toolbar_button_note": "Die KI-Schaltfläche am rechten Ende der Werkzeugleiste. Strg+Umschalt+A und das Ansicht-Menü öffnen das Panel weiterhin.", "ui.ai_undo_tip": "Alles, was der Agent für diese Nachricht geändert hat, in einem Schritt rückgängig machen", "ui.all": "Alle", + "ui.ambient_occlusion": "Umgebungsverdeckung", + "ui.ambient_occlusion_help": "Sanfte Schattierung an Kontaktstellen und in Vertiefungen undurchsichtiger Flächen. Erfordert die GPU-Ansicht.", "ui.analysis": "Analyse", "ui.angle": "Winkel", "ui.angle_decimals": "Winkel-Dezimalstellen", @@ -910,6 +914,11 @@ "ui.fully_constrained": "Vollständig bestimmt", "ui.general": "Allgemein", "ui.graphics": "Grafik", + "ui.graphics_custom": "Benutzerdefiniert", + "ui.graphics_performance": "Leistung", + "ui.graphics_preset": "Grafikprofil", + "ui.graphics_preset_help": "Qualität: Umgebungsverdeckung, feine Anzeigequalität und adaptives 2× Supersampling. Leistung: keine Umgebungsverdeckung, normale Anzeigequalität und kein Supersampling. Manuelle Änderungen: Benutzerdefiniert. MSAA bleibt unverändert.", + "ui.graphics_quality": "Qualität", "ui.groupSelected": "Auswahl gruppieren", "ui.heading_assemble": "ZUSAMMENBAU", "ui.heading_box": "BLOCK", diff --git a/assets/locales/en.json b/assets/locales/en.json index 063cb9a4a..17b92389b 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -632,8 +632,10 @@ "cmd.timeline_roll_to": "Roll History Marker", "cmd.timeline_rollback": "Move Timeline Marker", "cmd.timeline_suppress": "Suppress Feature", + "cmd.view_ambient_occlusion": "Ambient Occlusion", "cmd.view_apply": "Restore Named View", "cmd.view_delete": "Delete Named View", + "cmd.view_graphics_preset": "Graphics Preset", "cmd.view_list": "List Named Views", "cmd.view_navigate": "Navigate View", "cmd.view_rename": "Rename Named View", @@ -1036,6 +1038,8 @@ "ui.ai_toolbar_button_note": "The AI button at the right end of the toolbar. Ctrl+Shift+A and the View menu still open the panel.", "ui.ai_undo_tip": "Undo everything the agent changed for this message, as one step", "ui.all": "All", + "ui.ambient_occlusion": "Ambient occlusion", + "ui.ambient_occlusion_help": "Soft shading where opaque surfaces meet. Requires the GPU viewport.", "ui.analysis": "Analysis", "ui.angle": "Angle", "ui.angle_decimals": "Angle decimals", @@ -1196,6 +1200,11 @@ "ui.fully_constrained": "Fully constrained", "ui.general": "General", "ui.graphics": "Graphics", + "ui.graphics_custom": "Custom", + "ui.graphics_performance": "Performance", + "ui.graphics_preset": "Graphics Preset", + "ui.graphics_preset_help": "Quality: ambient occlusion, Fine display quality and adaptive 2× supersampling. Performance: no ambient occlusion, Normal display quality and supersampling off. Manual changes show Custom. MSAA stays unchanged.", + "ui.graphics_quality": "Quality", "ui.grid_follows_view": "Grid follows the view", "ui.grid_follows_view_hint": "Side views show the grid on the upright plane facing them instead of the ground", "ui.ground_shadow": "Ground shadow", diff --git a/assets/locales/fr.json b/assets/locales/fr.json index 444117d2b..276e9dc21 100644 --- a/assets/locales/fr.json +++ b/assets/locales/fr.json @@ -628,8 +628,10 @@ "cmd.timeline_roll_to": "Déplacer le marqueur d'historique", "cmd.timeline_rollback": "Déplacer le marqueur de chronologie", "cmd.timeline_suppress": "Désactiver la fonction", + "cmd.view_ambient_occlusion": "Occlusion ambiante", "cmd.view_apply": "Restaurer la vue nommée", "cmd.view_delete": "Supprimer la vue nommée", + "cmd.view_graphics_preset": "Préréglage graphique", "cmd.view_list": "Lister les vues nommées", "cmd.view_navigate": "Naviguer dans la vue", "cmd.view_rename": "Renommer la vue nommée", @@ -995,6 +997,8 @@ "ui.ai_toolbar_button_note": "Le bouton IA à l'extrémité droite de la barre d'outils. Ctrl+Shift+A et le menu Vue ouvrent toujours le panneau.", "ui.ai_undo_tip": "Annuler tout ce que l'agent a modifié pour ce message, en une seule étape", "ui.all": "Tout", + "ui.ambient_occlusion": "Occlusion ambiante", + "ui.ambient_occlusion_help": "Ombrage doux aux jonctions des surfaces opaques. Nécessite la vue GPU.", "ui.analysis": "Analyse", "ui.angle": "Angle", "ui.angle_decimals": "Décimales des angles", @@ -1155,6 +1159,11 @@ "ui.fully_constrained": "Entièrement contrainte", "ui.general": "Général", "ui.graphics": "Graphisme", + "ui.graphics_custom": "Personnalisé", + "ui.graphics_performance": "Performances", + "ui.graphics_preset": "Préréglage graphique", + "ui.graphics_preset_help": "Qualité : occlusion ambiante, tessellation fine et suréchantillonnage adaptatif 2×. Performances : sans occlusion ambiante, tessellation normale et sans suréchantillonnage. Les réglages manuels affichent Personnalisé. MSAA reste inchangé.", + "ui.graphics_quality": "Qualité", "ui.grid_follows_view": "La grille suit la vue", "ui.grid_follows_view_hint": "Dans les vues de côté, la grille s'affiche sur le plan vertical qui leur fait face plutôt que sur le sol", "ui.ground_shadow": "Ombre au sol", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 58e7a1136..1a25af5d6 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -632,8 +632,10 @@ "cmd.timeline_roll_to": "履歴マーカーを移動", "cmd.timeline_rollback": "タイムライン マーカーを移動", "cmd.timeline_suppress": "フィーチャーを抑制", + "cmd.view_ambient_occlusion": "アンビエントオクルージョン", "cmd.view_apply": "名前付きビューを復元", "cmd.view_delete": "名前付きビューを削除", + "cmd.view_graphics_preset": "グラフィックスプリセット", "cmd.view_list": "名前付きビューを一覧表示", "cmd.view_navigate": "ビューナビゲーション", "cmd.view_rename": "名前付きビューの名前を変更", @@ -1036,6 +1038,8 @@ "ui.ai_toolbar_button_note": "ツールバー右端の AI ボタン。Ctrl+Shift+A と表示メニューからも引き続きパネルを開けます。", "ui.ai_undo_tip": "このメッセージでエージェントが行った変更を、1回でまとめて元に戻します", "ui.all": "すべて", + "ui.ambient_occlusion": "アンビエントオクルージョン", + "ui.ambient_occlusion_help": "不透明な面が接する部分に柔らかい陰影を加えます。GPUビューポートが必要です。", "ui.analysis": "解析", "ui.angle": "角度", "ui.angle_decimals": "角度の小数点以下の桁数", @@ -1196,6 +1200,11 @@ "ui.fully_constrained": "完全拘束", "ui.general": "一般", "ui.graphics": "グラフィックス", + "ui.graphics_custom": "カスタム", + "ui.graphics_performance": "パフォーマンス", + "ui.graphics_preset": "グラフィックスプリセット", + "ui.graphics_preset_help": "品質:アンビエントオクルージョン、細かい表示品質、適応型2×スーパーサンプリング。パフォーマンス:AOなし、標準の表示品質、スーパーサンプリングなし。手動変更はカスタムと表示されます。MSAAは変更されません。", + "ui.graphics_quality": "品質", "ui.grid_follows_view": "グリッドをビューに追従させる", "ui.grid_follows_view_hint": "側面ビューでは、グリッドを地面ではなく、そのビューに向いた垂直平面に表示します", "ui.ground_shadow": "地面の影", diff --git a/assets/locales/ko.json b/assets/locales/ko.json index 367b9b628..e4a4fbef4 100644 --- a/assets/locales/ko.json +++ b/assets/locales/ko.json @@ -425,8 +425,10 @@ "cmd.timeline_roll_to": "이력 마커 이동", "cmd.timeline_rollback": "타임라인 마커 이동", "cmd.timeline_suppress": "특성 비활성화", + "cmd.view_ambient_occlusion": "앰비언트 오클루전", "cmd.view_apply": "이름 있는 보기 복원", "cmd.view_delete": "이름 있는 보기 삭제", + "cmd.view_graphics_preset": "그래픽 프리셋", "cmd.view_list": "이름 있는 보기 목록", "cmd.view_navigate": "보기 탐색", "cmd.view_rename": "이름 있는 보기 이름 변경", @@ -756,6 +758,8 @@ "ui.ai_toolbar_button_note": "도구 모음 오른쪽 끝의 AI 버튼. Ctrl+Shift+A와 보기 메뉴로도 패널을 열 수 있습니다.", "ui.ai_undo_tip": "이 메시지에서 에이전트가 바꾼 모든 것을 한 번에 실행 취소", "ui.all": "모두", + "ui.ambient_occlusion": "앰비언트 오클루전", + "ui.ambient_occlusion_help": "불투명한 표면이 만나는 곳에 부드러운 음영을 추가합니다. GPU 뷰포트가 필요합니다.", "ui.analysis": "분석", "ui.angle": "각도", "ui.angle_decimals": "각도 소수점 자릿수", @@ -910,6 +914,11 @@ "ui.fully_constrained": "완전 구속", "ui.general": "일반", "ui.graphics": "그래픽", + "ui.graphics_custom": "사용자 지정", + "ui.graphics_performance": "성능", + "ui.graphics_preset": "그래픽 프리셋", + "ui.graphics_preset_help": "품질: 앰비언트 오클루전, 세밀한 표시 품질, 적응형 2× 슈퍼샘플링. 성능: 앰비언트 오클루전 끄기, 보통 표시 품질, 슈퍼샘플링 끄기. 수동 변경 시 사용자 지정으로 표시됩니다. MSAA는 유지됩니다.", + "ui.graphics_quality": "품질", "ui.groupSelected": "선택 항목 그룹화", "ui.heading_assemble": "조립", "ui.heading_box": "박스", diff --git a/assets/locales/ru.json b/assets/locales/ru.json index 79b92c584..bcfadce6e 100644 --- a/assets/locales/ru.json +++ b/assets/locales/ru.json @@ -568,8 +568,10 @@ "cmd.timeline_roll_to": "Переместить маркер истории", "cmd.timeline_rollback": "Сдвинуть маркер шкалы", "cmd.timeline_suppress": "Подавить операцию", + "cmd.view_ambient_occlusion": "Окружающее затенение", "cmd.view_apply": "Вернуть именованный вид", "cmd.view_delete": "Удалить именованный вид", + "cmd.view_graphics_preset": "Графический профиль", "cmd.view_list": "Список именованных видов", "cmd.view_navigate": "Навигация вида", "cmd.view_rename": "Переименовать именованный вид", @@ -750,6 +752,8 @@ "ui.agent_cursor": "Курсор агента", "ui.agent_cursor_speed": "Скорость курсора агента", "ui.all": "Все", + "ui.ambient_occlusion": "Окружающее затенение", + "ui.ambient_occlusion_help": "Мягкое затенение в местах соприкосновения непрозрачных поверхностей. Требуется видовой экран GPU.", "ui.analysis": "Анализ", "ui.angle": "Угол", "ui.angle_decimals": "Знаков после запятой (углы)", @@ -899,6 +903,11 @@ "ui.fully_constrained": "Полностью определён", "ui.general": "Общие", "ui.graphics": "Графика", + "ui.graphics_custom": "Настраиваемый", + "ui.graphics_performance": "Производительность", + "ui.graphics_preset": "Графический профиль", + "ui.graphics_preset_help": "Качество: окружающее затенение, детальная тесселяция и адаптивный суперсэмплинг 2×. Производительность: без затенения, обычная тесселяция и без суперсэмплинга. Ручные изменения отображаются как настраиваемые. MSAA не меняется.", + "ui.graphics_quality": "Качество", "ui.ground_shadow": "Тень на земле", "ui.groupSelected": "Группировать выбранное", "ui.heading_add_ins": "НАДСТРОЙКИ", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index f366f0df2..6519da022 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -632,8 +632,10 @@ "cmd.timeline_roll_to": "滚动历史标记", "cmd.timeline_rollback": "移动时间线标记", "cmd.timeline_suppress": "抑制特征", + "cmd.view_ambient_occlusion": "环境光遮蔽", "cmd.view_apply": "还原命名视图", "cmd.view_delete": "删除命名视图", + "cmd.view_graphics_preset": "图形预设", "cmd.view_list": "列出命名视图", "cmd.view_navigate": "导航视图", "cmd.view_rename": "重命名命名视图", @@ -1036,6 +1038,8 @@ "ui.ai_toolbar_button_note": "工具栏右端的 AI 按钮。Ctrl+Shift+A 和视图菜单仍可打开面板。", "ui.ai_undo_tip": "将智能体为此消息所做的全部更改一步撤销", "ui.all": "全部", + "ui.ambient_occlusion": "环境光遮蔽", + "ui.ambient_occlusion_help": "在不透明表面相接处添加柔和阴影。需要 GPU 视口。", "ui.analysis": "分析", "ui.angle": "角度", "ui.angle_decimals": "角度小数位", @@ -1196,6 +1200,11 @@ "ui.fully_constrained": "完全约束", "ui.general": "常规", "ui.graphics": "图形", + "ui.graphics_custom": "自定义", + "ui.graphics_performance": "性能", + "ui.graphics_preset": "图形预设", + "ui.graphics_preset_help": "质量:环境光遮蔽、精细显示质量和自适应2×超采样。性能:关闭环境光遮蔽、普通显示质量和关闭超采样。手动修改显示为自定义。MSAA保持不变。", + "ui.graphics_quality": "质量", "ui.grid_follows_view": "网格跟随视图", "ui.grid_follows_view_hint": "在侧视图中,将网格显示在朝向该视图的竖直平面上,而不是地面上", "ui.ground_shadow": "地面阴影", diff --git a/assets/shaders/viewport.wgsl b/assets/shaders/viewport.wgsl index 1c46be0a9..003d167ff 100644 --- a/assets/shaders/viewport.wgsl +++ b/assets/shaders/viewport.wgsl @@ -10,6 +10,7 @@ struct U { acc_u: vec4, // accessibility map axes (xyz, offset) acc_v: vec4, eye: vec4, // eye position, w = 1 for perspective (0: orthographic, looking along -back) + ao: vec4, // radius in world units (zero: disabled) // analysis colours (`theme::AnalysisColors`): draft positive, between, negative; reachable, // blocked; curvature flat, middle, tight ana_c: array, 8>, @@ -28,6 +29,7 @@ fn near_z(c: vec4) -> f32 { } @group(1) @binding(2) var acc_t: texture_2d; +@group(2) @binding(0) var ao_depth: texture_depth_2d; fn clipped(p: vec3) -> bool { return length(u.clip.xyz) > 0.5 && dot(u.clip.xyz, p) > u.clip.w; @@ -128,7 +130,7 @@ fn solid(i: TOut, front: bool) -> vec4 { if (u.ana.x > 0.5 && length(i.n) > 0.5) { return analysis(i, k); } - let c = shade(i); + let c = lit(i, occlusion(i)); // Silhouettes (styles with edges): where a curved surface turns away from the eye, a line // about 1.5 px wide, on the visible surface only (depth-correct). if (u.screen.w > 0.5 && length(i.n) > 0.5 && fw > 1e-6) { @@ -138,6 +140,59 @@ fn solid(i: TOut, front: bool) -> vec4 { return c; } +// A single-sample opaque depth map, independent of the window's MSAA and its UI offsets. +@fragment +fn fs_ao_depth(i: TOut, @builtin(front_facing) front: bool) -> @builtin(frag_depth) f32 { + if (clipped(i.wp) || length(i.n) < 0.5) { discard; } + if (!front && length(u.clip.xyz) > 0.5) { return cap_depth(i.wp, i.pos.z); } + return i.pos.z; +} + +// Deterministic cosine-weighted hemisphere samples. Projecting the sample and a point one +// radius toward the eye supplies a depth range in both orthographic and perspective views; +// distant foreground geometry cannot cast a dark halo onto a background surface. +fn occlusion(i: TOut) -> f32 { + let radius = u.ao.x; + if (radius <= 0.0 || length(i.n) < 0.5) { return 1.0; } + var n = normalize(i.n); + if (dot(n, u.back.xyz) < 0.0) { n = -n; } + let axis = select(vec3(0.0, 0.0, 1.0), vec3(0.0, 1.0, 0.0), abs(n.z) > 0.9); + let tangent = normalize(cross(axis, n)); + let bitangent = cross(n, tangent); + let size = vec2(textureDimensions(ao_depth)); + // The map is a 1 × 1 stand-in until a frame draws into it (the product preview draws no + // prepass): sampling it tells nothing, so leave the surface unoccluded. + if (size.x < 2 || size.y < 2) { return 1.0; } + // One comparison for both depth directions: depths read as 0 near / 1 far (mirrored when + // the buffer runs reversed). The map is cleared to its far plane either way, so a texel + // with nothing in it reads as 1 and the `d < 1.0` test below skips it. + let flip = reversed(); + var blocked = 0.0; + for (var j = 0u; j < 32u; j = j + 1u) { + let f = (f32(j) + 0.5) / 32.0; + let angle = f32(j) * 2.39996323; + let direction = tangent * (cos(angle) * sqrt(f)) + bitangent * (sin(angle) * sqrt(f)) + n * sqrt(1.0 - f); + let reach = radius * (0.2 + 0.8 * fract(f32(j) * 0.61803399 + 0.5)); + let sample = i.wp + n * (radius * 0.025) + direction * reach; + let q = u.vp * vec4(sample, 1.0); + let near = u.vp * vec4(sample + u.back.xyz * radius, 1.0); + if (q.w <= 0.0 || near.w <= 0.0) { continue; } + let ndc = q.xyz / q.w; + let uv = vec2(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5); + if (any(uv < vec2(0.0)) || any(uv >= vec2(1.0)) || ndc.z < 0.0 || ndc.z > 1.0) { continue; } + let d0 = textureLoad(ao_depth, vec2(uv * vec2(size)), 0); + let zs = select(ndc.z, 1.0 - ndc.z, flip); + let zn = select(near.z / near.w, 1.0 - near.z / near.w, flip); + let d = select(d0, 1.0 - d0, flip); + let span = max(zs - zn, 1e-7); + let delta = (zs - d) / span; + if (d < 1.0 && delta > 0.005 && delta < 1.0) { + blocked = blocked + smoothstep(0.005, 0.15, delta) * (1.0 - smoothstep(0.5, 1.0, delta)); + } + } + return 1.0 - 0.85 * blocked / 32.0; +} + /// How fast the normal turns across the pixel (per mm). fn curvature(i: TOut) -> f32 { let nn = normalize(i.n); @@ -230,6 +285,10 @@ fn fs_tri_all(i: TOut) -> @location(0) vec4 { } fn shade(i: TOut) -> vec4 { + return lit(i, 1.0); +} + +fn lit(i: TOut, visibility: f32) -> vec4 { // A zero normal marks flat colour (selection fills, translucent planes). if (length(i.n) < 0.5) { return out_color(i.c); @@ -242,7 +301,7 @@ fn shade(i: TOut) -> vec4 { let fill = max(dot(n, v), 0.0); let h = normalize(key + v); let spec = pow(max(dot(n, h), 0.0), 40.0) * 0.25; - let k = 0.42 + 0.38 * diff + 0.25 * fill; + let k = 0.42 + 0.38 * diff + 0.25 * fill - (0.42 + 0.25 * fill) * (1.0 - visibility); return out_color(vec4(min(i.c.rgb * k + vec3(spec), vec3(1.0)), i.c.a)); } diff --git a/crates/engine/src/cmd/view_navigation.rs b/crates/engine/src/cmd/view_navigation.rs index 9556dca33..a2d0bb643 100644 --- a/crates/engine/src/cmd/view_navigation.rs +++ b/crates/engine/src/cmd/view_navigation.rs @@ -6,7 +6,12 @@ use super::CommandSpec; use crate::params::{bad, num, req_vec2, req_vec3, vec3}; use crate::{Result, Session}; -pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("view.navigate", "Navigate View", navigate) +pub static COMMANDS: &[CommandSpec] = &[ +CommandSpec::new("view.graphics_preset", "Graphics Preset", graphics_preset) + .icon("settings").noundo().doc_only().params("preset: performance|quality → preset, enabled, display_quality, supersampling, supersampling_adaptive; Quality: AO, Fine, adaptive 2x SSAA; Performance: no AO, Normal, no SSAA"), +CommandSpec::new("view.ambient_occlusion", "Ambient Occlusion", ambient_occlusion) + .icon("settings").noundo().doc_only().params("enabled: bool → enabled; apply soft contact shading in the GPU viewport"), +CommandSpec::new("view.navigate", "Navigate View", navigate) .icon("orbit") .noundo() .doc_only() @@ -286,3 +291,61 @@ mod tests { } } } + +fn ambient_occlusion(_s: &mut Session, p: &Value) -> Result { + let enabled = p.get("enabled").and_then(Value::as_bool).ok_or_else(|| bad("view.ambient_occlusion", "enabled must be a boolean"))?; + Ok(json!({"enabled": enabled})) +} + +#[cfg(test)] +mod ambient_occlusion_tests { + use super::*; + #[test] + fn validates_display_setting_without_editing_design_or_history() { + let mut s = Session::default(); + let before = s.doc.to_json(); + for enabled in [true, false] { + assert_eq!(s.execute("view.ambient_occlusion", &json!({"enabled": enabled})).unwrap(), json!({"enabled": enabled})); + } + for p in [json!({}), json!({"enabled": 1}), json!({"enabled": "true"}), json!({"enabled": null})] { + assert!(s.execute("view.ambient_occlusion", &p).is_err()); + } + assert_eq!(s.doc.to_json(), before); + assert!(s.undo.is_empty()); + } +} + +/// One preset for contact shading, tessellation and supersampling. MSAA stays independent. +fn graphics_preset(_s: &mut Session, p: &Value) -> Result { + let preset = p.get("preset").and_then(Value::as_str); + let enabled = match preset { + Some("quality") => true, + Some("performance") => false, + _ => return Err(bad("view.graphics_preset", "preset must be performance or quality")), + }; + Ok(json!({"preset": preset, "enabled": enabled, "display_quality": if enabled { "fine" } else { "normal" }, + "supersampling": if enabled { 2.0 } else { 1.0 }, "supersampling_adaptive": true})) +} + +#[cfg(test)] +mod graphics_preset_tests { + use super::*; + + #[test] + fn presets_validate_without_changing_design_or_history() { + let mut s = Session::default(); + let before = s.doc.to_json(); + for (preset, enabled) in [("quality", true), ("performance", false)] { + assert_eq!( + s.execute("view.graphics_preset", &json!({"preset":preset})).unwrap(), + json!({"preset":preset,"enabled":enabled,"display_quality":if enabled { "fine" } else { "normal" }, + "supersampling":if enabled { 2.0 } else { 1.0 },"supersampling_adaptive":true}) + ); + } + for params in [json!({}), json!({"preset":"fast"}), json!({"preset":true}), json!({"preset":null})] { + assert!(s.execute("view.graphics_preset", ¶ms).is_err()); + } + assert_eq!(s.doc.to_json(), before); + assert!(s.undo.is_empty()); + } +} diff --git a/crates/gpu/src/capture.rs b/crates/gpu/src/capture.rs index 00a4c930c..befd54736 100644 --- a/crates/gpu/src/capture.rs +++ b/crates/gpu/src/capture.rs @@ -325,6 +325,7 @@ fn frame(scene: &Scene, cam: &Camera, [width, height]: [u32; 2], key: u64, acces access, outline: true, eye: [eye[0], eye[1], eye[2], if cam.fov > 0.0 { 1.0 } else { 0.0 }], + ao_radius: 0.0, ssaa: 1.0, } } diff --git a/crates/gpu/src/view.rs b/crates/gpu/src/view.rs index 3ac065feb..2225c0900 100644 --- a/crates/gpu/src/view.rs +++ b/crates/gpu/src/view.rs @@ -14,14 +14,17 @@ use wgpu::util::DeviceExt; use crate::pbr; +mod ao; + /// Triangle vertex: position (3 × f32), normal (3 × f32), sRGB colour (4 × u8). pub const TRI_SIZE: usize = 28; pub const PBR_SIZE: usize = pbr::VERTEX_SIZE; /// Line instance: a, b (3 × f32 each), colour (4 × u8), width in pixels (f32). pub const LINE_SIZE: usize = 32; -/// The shader's `U`: the view-projection matrix, 9 `vec4`s, the 8 analysis colours, their -/// flags and the depth direction (`uniform_bytes`). -const UNIFORM_SIZE: u64 = 368; +/// The shader's `U`: the view-projection matrix, 10 `vec4`s (the tenth carries the ambient +/// occlusion radius), the 8 analysis colours, their flags and the depth direction +/// (`uniform_bytes`). +const UNIFORM_SIZE: u64 = 384; /// A body drawn from its display plan, evaluated on the GPU: the plan, and a colour per face /// (the plan's face numbering; faces past the end take the last colour). @@ -245,6 +248,8 @@ pub struct Frame { /// Eye position and 1 for a perspective camera (0: orthographic), for the section cap's depth /// and the depth bias. pub eye: [f32; 4], + /// World-space occlusion radius; zero skips the depth prepass and all AO sampling. + pub ao_radius: f32, /// Supersampling (#1288): draw the frame this many times the viewport's pixels in each /// direction and filter it down (1: off). Under 1 the frame is drawn smaller and filtered up /// (the product preview past its pixel budget, #1464). @@ -541,6 +546,8 @@ impl Batches { /// The viewport's pipelines and the scenes uploaded to one device, for one kind of target. pub struct Renderer { + /// The AO depth prepass resources (a 1 × 1 stand-in while ambient occlusion is off). + ao: ao::Resources, tri: wgpu::RenderPipeline, /// `tri` and `tri_cut` for planned bodies (positions and normals from the GPU evaluation, /// colours per vertex, indexed). @@ -959,9 +966,10 @@ impl Renderer { count: None, }], }); + let ao = ao::Resources::new(device, &bgl, &module, reversed); let solid_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("sc_solid"), - bind_group_layouts: &[Some(&bgl), Some(&access_bgl)], + bind_group_layouts: &[Some(&bgl), Some(&access_bgl), Some(&ao.layout)], immediate_size: 0, }); let built = [Some(tri_layout())]; @@ -1108,6 +1116,7 @@ impl Renderer { }) }); Renderer { + ao, depth_reset, target: t, max_texture: device.limits().max_texture_dimension_2d, @@ -1305,6 +1314,7 @@ impl Renderer { res.access_bind = access_texture(device, Some(queue), &res.access_bgl, a.size, &a.depth); res.access_version = a.version; } + res.ao.prepare(device, encoder, &res.bind, cb.ao_radius, cb.size_px, res.target.reversed_depth(), [&res.model, &res.preview]); // Images: upload new or changed textures, drop removed ones, rebuild the quads. res.textures.retain(|id, _| cb.images.iter().any(|i| i.id == *id)); res.quads.clear(); @@ -1414,6 +1424,7 @@ impl Renderer { lines(pass, &res.overlay, &m.under); lines(pass, &res.overlay, &sk.under); pass.set_bind_group(1, &res.access_bind, &[]); + pass.set_bind_group(2, &res.ao.bind, &[]); let planned = |pass: &mut wgpu::RenderPass<'static>, p: &wgpu::RenderPipeline| { for d in &m.planned { pass.set_pipeline(p); @@ -1570,6 +1581,7 @@ pub fn uniform_bytes(cb: &Frame, w: f32, h: f32, linear: bool, reversed: bool) - None => v.extend([0.0; 8]), } v.extend(cb.eye); + v.extend([cb.ao_radius, 0.0, 0.0, 0.0]); v.extend(cb.analysis_colors); v.extend([if reversed { 1.0 } else { 0.0 }, FACE_STEPS as f32, FACE_SLOPE, 0.0]); v.iter().flat_map(|x| x.to_le_bytes()).collect() diff --git a/crates/gpu/src/view/ao.rs b/crates/gpu/src/view/ao.rs new file mode 100644 index 000000000..3fce30cf3 --- /dev/null +++ b/crates/gpu/src/view/ao.rs @@ -0,0 +1,167 @@ +//! The optional AO depth prepass. Only opaque model and preview triangles participate: their +//! depth is drawn once into a single-sample depth map the lit fragment samples for occlusion. +//! The map is independent of the window's MSAA, and the depth runs the same way as the +//! viewport's own buffer (see [`super::depth_compare`] and [`super::far_depth`]). + +use super::{Batches, color_layout, depth_compare, far_depth, planned_layout, tri_layout}; + +pub(super) struct Resources { + pub layout: wgpu::BindGroupLayout, + pub bind: wgpu::BindGroup, + depth: wgpu::TextureView, + size: [u32; 2], + pipeline: wgpu::RenderPipeline, + planned_pipeline: wgpu::RenderPipeline, +} + +fn texture(device: &wgpu::Device, layout: &wgpu::BindGroupLayout, size: [u32; 2]) -> (wgpu::TextureView, wgpu::BindGroup) { + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some("sc_ao_depth"), + size: wgpu::Extent3d { width: size[0], height: size[1], depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Depth32Float, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING, + view_formats: &[], + }); + let depth = texture.create_view(&Default::default()); + let bind = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("sc_ao_depth"), + layout, + entries: &[wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&depth) }], + }); + (depth, bind) +} + +impl Resources { + pub fn new(device: &wgpu::Device, uniform: &wgpu::BindGroupLayout, module: &wgpu::ShaderModule, reversed: bool) -> Self { + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("sc_ao_depth"), + entries: &[wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Depth, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }], + }); + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("sc_ao_prepass"), + bind_group_layouts: &[Some(uniform)], + immediate_size: 0, + }); + let built = [Some(tri_layout())]; + let evaluated = [Some(planned_layout()), Some(color_layout())]; + let pipeline = |planned: bool| { + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("sc_ao_prepass"), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module, + entry_point: Some("vs_tri"), + buffers: if planned { &evaluated } else { &built }, + compilation_options: Default::default(), + }, + primitive: wgpu::PrimitiveState::default(), + depth_stencil: Some(wgpu::DepthStencilState { + format: wgpu::TextureFormat::Depth32Float, + depth_write_enabled: Some(true), + depth_compare: Some(depth_compare(reversed, wgpu::CompareFunction::Less)), + stencil: Default::default(), + bias: Default::default(), + }), + multisample: wgpu::MultisampleState::default(), + fragment: Some(wgpu::FragmentState { + module, + entry_point: Some("fs_ao_depth"), + targets: &[], + compilation_options: Default::default(), + }), + multiview_mask: None, + cache: None, + }) + }; + let planned_pipeline = pipeline(true); + let pipeline = pipeline(false); + let (depth, bind) = texture(device, &layout, [1, 1]); + Self { layout, bind, depth, size: [1, 1], pipeline, planned_pipeline } + } + + pub fn prepare( + &mut self, + device: &wgpu::Device, + encoder: &mut wgpu::CommandEncoder, + uniform: &wgpu::BindGroup, + radius: f32, + size_px: [f32; 2], + reversed: bool, + batches: [&Batches; 2], + ) { + let enabled = radius.is_finite() && radius > 0.0; + // Bound memory at large window sizes; normalized coordinates also handle downsampling. + let size = target_size(enabled, size_px, device.limits().max_texture_dimension_2d); + if size != self.size { + (self.depth, self.bind) = texture(device, &self.layout, size); + self.size = size; + } + if !enabled { + return; + } + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("sc_ao_prepass"), + color_attachments: &[], + depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { + view: &self.depth, + depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(far_depth(reversed)), store: wgpu::StoreOp::Store }), + stencil_ops: None, + }), + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + pass.set_bind_group(0, uniform, &[]); + for batch in batches { + pass.set_pipeline(&self.pipeline); + if let Some(tris) = &batch.tris { + for (buffer, count) in &tris.parts { + pass.set_vertex_buffer(0, buffer.slice(..)); + pass.draw(0..*count, 0..1); + } + } + pass.set_pipeline(&self.planned_pipeline); + for draw in &batch.planned { + pass.set_vertex_buffer(0, draw.mesh.vertices.slice(..)); + pass.set_vertex_buffer(1, draw.colors.slice(..)); + pass.set_index_buffer(draw.mesh.indices.slice(..), wgpu::IndexFormat::Uint32); + pass.draw_indexed(0..draw.mesh.index_count, 0, 0..1); + } + } + } +} + +fn target_size(enabled: bool, pixels: [f32; 2], device_limit: u32) -> [u32; 2] { + if !enabled { + return [1, 1]; + } + let limit = device_limit.clamp(1, 2048); + let pixels = pixels.map(|s| if s.is_finite() { s.max(1.0) } else { 1.0 }); + let scale = (limit as f32 / pixels[0].max(pixels[1])).min(1.0); + pixels.map(|s| (s * scale).ceil().clamp(1.0, limit as f32) as u32) +} + +#[cfg(test)] +mod tests { + use super::target_size; + #[test] + fn depth_map_is_bounded_and_released_when_disabled() { + assert_eq!(target_size(true, [6000.0, 3000.0], 8192), [2048, 1024]); + assert_eq!(target_size(true, [6000.0, 3000.0], 1024), [1024, 512]); + assert_eq!(target_size(false, [6000.0, 3000.0], 8192), [1, 1]); + assert_eq!(target_size(true, [f32::NAN, f32::INFINITY], 8192), [1, 1]); + assert_eq!(target_size(true, [0.0, -1.0], 8192), [1, 1]); + } +} diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 204b14719..08ade43df 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -97,7 +97,7 @@ fn key_from(name: &str) -> Option { fn execute(app: &mut SolveApp, id: &str, params: Value) -> Result { let r = app.run(id, params); if r.is_ok() - && id != "view.navigate" + && !matches!(id, "view.navigate" | "view.ambient_occlusion" | "view.graphics_preset") && app.session.active_sketch.is_none() && app.session.world_state().bodies.len() == 1 && app.session.undo.len() <= 2 diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs index 222938e41..0dd840176 100644 --- a/crates/ui-egui/src/gpu.rs +++ b/crates/ui-egui/src/gpu.rs @@ -281,6 +281,7 @@ fn offscreen( access: None, outline: false, eye, + ao_radius: 0.0, ssaa, }); let texture = |format, usage| { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index edd7374ee..3ca76af58 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -641,6 +641,14 @@ impl SolveApp { let r = self.session.execute(id, ¶ms).map_err(|e| e.to_string()); self.big_operation |= now_ms() - t0 >= recovery_ui::BIG_OPERATION_MS; if let Ok(v) = &r { + if matches!(id, "view.ambient_occlusion" | "view.graphics_preset") { + self.preferences.ambient_occlusion = v.get("enabled").and_then(Value::as_bool).unwrap_or(false); + if id == "view.graphics_preset" { + self.preferences.display_quality = v.get("display_quality").and_then(Value::as_str).unwrap_or("normal").to_string(); + self.preferences.supersampling = v.get("supersampling").and_then(Value::as_f64).unwrap_or(1.0) as f32; + self.preferences.supersampling_adaptive = v.get("supersampling_adaptive").and_then(Value::as_bool).unwrap_or(true); + } + } if id == "view.navigate" { let to: Camera = serde_json::from_value(v.get("camera").cloned().unwrap_or_default()).map_err(|e| e.to_string())?; if v.get("continuous").and_then(Value::as_bool).unwrap_or(false) { @@ -734,6 +742,11 @@ impl SolveApp { self.home.open = false; return; } + // A display toggle leaves the current modelling tool and camera in place. + if id == "view.ambient_occlusion" { + let _ = self.run(id, json!({"enabled": !self.preferences.ambient_occlusion})); + return; + } // Another command ends Edit Text (its dialog is not a feature edit to keep). sketch_text_move::cancel_drag(self); if sketch_text::editing(self) || self.dialog.as_ref().is_some_and(|d| matches!(d.kind, dialogs::Kind::TextMove(_))) { diff --git a/crates/ui-egui/src/measurement_ui_tests.rs b/crates/ui-egui/src/measurement_ui_tests.rs index 12ca2ce86..a22fb5149 100644 --- a/crates/ui-egui/src/measurement_ui_tests.rs +++ b/crates/ui-egui/src/measurement_ui_tests.rs @@ -127,6 +127,9 @@ fn measurement_axis_distances_can_be_disabled_saved_and_restored_in_preferences( let mut h = vertex_measurement([0., 0., 0.], [-3., 4., -12.]); let measurement = result(&h).clone(); h.call("ui.prefs", json!({"open":"Graphics"})); + // The graphics page scrolls; the checkbox sits below the fold since the graphics preset + // and ambient occlusion rows were added, so scroll to it as the scenario tests do. + h.call("ui.scroll", json!({"x":800.0,"y":500.0,"delta":-3000.0})); let checkbox = crate::scenario::rect_of("prefs:measure_axis_distances").unwrap().center(); h.call("ui.click", json!({"x":checkbox.x,"y":checkbox.y})); assert!(!h.app.preferences.measure_axis_distances); diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index 293095621..f7fc8f00a 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -285,6 +285,8 @@ pub struct Prefs { pub space_mouse_axis_speed: [f32; 6], /// Anti-aliasing samples (applies on restart). pub msaa: u32, + /// Soft contact shading in the GPU viewport; optional and applied immediately. + pub ambient_occlusion: bool, /// The grid turns to the upright origin plane facing a side view (#1470). Off by default: the /// grid stays on the ground plane (XY) whatever the view. pub grid_follows_view: bool, @@ -434,6 +436,7 @@ impl Default for Prefs { space_mouse_reverse: [false; 6], space_mouse_axis_speed: [1.0; 6], msaa: 4, + ambient_occlusion: false, grid_follows_view: false, display_quality: "normal".into(), supersampling: 1.0, @@ -758,6 +761,7 @@ fn defaults(app: &mut SolveApp, page: usize) { PAGE_GRAPHICS => { let msaa = p.msaa != d.msaa; p.msaa = d.msaa; + p.ambient_occlusion = d.ambient_occlusion; p.display_quality = d.display_quality; p.supersampling = d.supersampling; p.supersampling_adaptive = d.supersampling_adaptive; @@ -1367,6 +1371,9 @@ fn page(app: &mut SolveApp, ui: &mut egui::Ui, t: &Tokens) { ui.end_row(); } 4 => { + ui.label(app.tr("ui.graphics_preset")); + graphics_preset_selector(app, ui); + ui.end_row(); ui.label(crate::i18n::tr_label("Visual style")); let styles = ["Shaded with edges", "Shaded", "Wireframe", "Shaded with hidden edges"]; let selected_label = crate::i18n::tr_label(styles[usize::from(app.ui.visual_style.min(3))]); @@ -1386,9 +1393,35 @@ fn page(app: &mut SolveApp, ui: &mut egui::Ui, t: &Tokens) { ui.label(crate::i18n::tr_label("Ground shadow")); ui.checkbox(&mut app.ui.ground_shadow, ""); ui.end_row(); + ui.label(crate::i18n::tr_label("Ambient occlusion")); + ambient_occlusion_checkbox(app, ui, ""); + ui.end_row(); ui.label(crate::i18n::tr_label("Perspective view")); ui.checkbox(&mut app.ui.perspective, ""); ui.end_row(); + // Keep accessibility controls visible before the longer rendering-quality controls. + ui.label(""); + ui.end_row(); + ui.label(RichText::new(app.tr("ui.colour_vision")).strong()); + ui.label(""); + ui.end_row(); + ui.label(app.tr("ui.colour_vision_mode")); + let mode = app.preferences.color_vision; + let response = egui::ComboBox::from_id_salt("pref_color_vision").selected_text(app.tr(mode.label_id())).show_ui(ui, |ui| { + for m in crate::theme::ColorVision::ALL { + ui.selectable_value(&mut app.preferences.color_vision, m, crate::i18n::tr(m.label_id())).on_hover_text(crate::i18n::tr(m.help_id())); + } + }); + crate::scenario::publish_handle("prefs:color_vision", response.response.rect.center()); + if app.preferences.color_vision != mode { + // At once, like the theme: the next frame draws in the new colours. + ui.ctx().request_repaint(); + } + ui.end_row(); + ui.label(app.tr("ui.colour_vision_sample")); + colour_vision_sample(ui, t); + ui.end_row(); + note(ui, app.tr("ui.colour_vision_note")); ui.label(app.tr("ui.anti_aliasing")); egui::ComboBox::from_id_salt("pref_msaa").selected_text(format!("{}×", app.preferences.msaa)).show_ui(ui, |ui| { for m in MSAA { @@ -1441,26 +1474,6 @@ fn page(app: &mut SolveApp, ui: &mut egui::Ui, t: &Tokens) { crate::scenario::publish_rect("prefs:measure_axis_distances", response.rect); response.on_hover_text(app.tr("settings.measure_axis_distances_help")); ui.end_row(); - // Colour vision (#778): its own section at the end of the page. - ui.label(RichText::new(app.tr("ui.colour_vision")).strong()); - ui.label(""); - ui.end_row(); - ui.label(app.tr("ui.colour_vision_mode")); - let mode = app.preferences.color_vision; - egui::ComboBox::from_id_salt("pref_color_vision").selected_text(app.tr(mode.label_id())).show_ui(ui, |ui| { - for m in crate::theme::ColorVision::ALL { - ui.selectable_value(&mut app.preferences.color_vision, m, crate::i18n::tr(m.label_id())).on_hover_text(crate::i18n::tr(m.help_id())); - } - }); - if app.preferences.color_vision != mode { - // At once, like the theme: the next frame draws in the new colours. - ui.ctx().request_repaint(); - } - ui.end_row(); - ui.label(app.tr("ui.colour_vision_sample")); - colour_vision_sample(ui, t); - ui.end_row(); - note(ui, app.tr("ui.colour_vision_note")); // Last, so the colour vision section above keeps its place on the page. ui.label(""); ui.end_row(); @@ -2486,3 +2499,155 @@ mod ui_scale_regression_tests { assert_eq!(h.ctx.zoom_factor(), 1.0); } } + +/// Both display-setting surfaces dispatch the same programmatic command. +pub(crate) fn ambient_occlusion_checkbox(app: &mut SolveApp, ui: &mut egui::Ui, label: &str) { + let mut enabled = app.preferences.ambient_occlusion; + let response = ui + .checkbox(&mut enabled, crate::i18n::tr_label(label)) + .on_hover_text(crate::i18n::tr_label("Soft shading where opaque surfaces meet. Requires the GPU viewport.")); + crate::scenario::publish_handle("view:ambient_occlusion", response.rect.center()); + if response.changed() { + let _ = app.run("view.ambient_occlusion", json!({"enabled": enabled})); + } +} + +#[cfg(test)] +mod ambient_occlusion_tests { + use super::*; + + #[test] + fn ambient_occlusion_is_optional_persistent_and_cancelable() { + let old: Prefs = serde_json::from_value(json!({"msaa": 4})).unwrap(); + assert!(!old.ambient_occlusion); + let mut h = crate::scenario::Harness::new(); + let camera = h.app.cam; + let design = h.app.session.doc.to_json(); + h.call("ui.prefs", json!({"open":"Graphics"})); + let checkbox = crate::scenario::handle_at("view:ambient_occlusion").unwrap(); + h.call("ui.click", json!({"x":checkbox.x,"y":checkbox.y})); + assert!(h.app.preferences.ambient_occlusion); + let mut restored = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + restored.load_prefs(&h.app.prefs()); + assert!(restored.preferences.ambient_occlusion); + h.call("ui.prefs", json!({"button":"cancel"})); + assert!(!h.app.preferences.ambient_occlusion); + h.call("ui.prefs", json!({"open":"Graphics", "ambient_occlusion":true})); + h.call("ui.prefs", json!({"button":"apply"})); + h.call("ui.prefs", json!({"button":"defaults"})); + assert!(!h.app.preferences.ambient_occlusion); + h.call("ui.prefs", json!({"button":"cancel"})); + assert!(h.app.preferences.ambient_occlusion); + h.call("engine.execute", json!({"command":"view.ambient_occlusion","params":{"enabled":false}})); + assert!(!h.app.preferences.ambient_occlusion); + h.call("engine.execute", json!({"command":"view.ambient_occlusion","params":{"enabled":"yes"}})); + assert!(!h.app.preferences.ambient_occlusion); + h.app.start("view.ambient_occlusion"); + assert!(h.app.preferences.ambient_occlusion); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.doc.to_json(), design); + assert!(h.app.session.undo.is_empty()); + } +} + +/// Manual edits are preserved and shown as Custom rather than claiming to match a preset. +fn graphics_preset(prefs: &Prefs) -> &'static str { + match (prefs.ambient_occlusion, prefs.display_quality.as_str(), prefs.supersampling, prefs.supersampling_adaptive) { + (false, "normal", 1.0, _) => "performance", + (true, "fine", 2.0, true) => "quality", + _ => "custom", + } +} + +pub(crate) fn graphics_preset_selector(app: &mut SolveApp, ui: &mut egui::Ui) { + let current = graphics_preset(&app.preferences); + let label = format!("ui.graphics_{current}"); + let response = egui::ComboBox::from_id_salt("graphics_preset") + .selected_text(app.tr(&label)) + .show_ui(ui, |ui| { + for (preset, label) in [("performance", "ui.graphics_performance"), ("quality", "ui.graphics_quality")] { + let item = ui.selectable_label(current == preset, app.tr(label)); + crate::scenario::publish_handle(&format!("view:graphics_preset:{preset}"), item.rect.center()); + if item.clicked() { + let _ = app.run("view.graphics_preset", json!({"preset":preset})); + } + } + }) + .response + .on_hover_text(app.tr("ui.graphics_preset_help")); + crate::scenario::publish_handle("view:graphics_preset", response.rect.center()); +} + +#[cfg(test)] +mod graphics_preset_tests { + use super::*; + + #[test] + fn viewport_preset_popup_accepts_quality_and_performance() { + let mut h = crate::scenario::Harness::new(); + h.call("ui.inspect", json!({})); + for handle in ["nav:view", "view:graphics_preset", "view:graphics_preset:quality"] { + let pos = crate::scenario::handle_at(handle).unwrap(); + h.call("ui.click", json!({"x":pos.x,"y":pos.y})); + } + assert!(h.app.preferences.ambient_occlusion); + for handle in ["view:graphics_preset", "view:graphics_preset:performance"] { + let pos = crate::scenario::handle_at(handle).unwrap(); + h.call("ui.click", json!({"x":pos.x,"y":pos.y})); + } + assert!(!h.app.preferences.ambient_occlusion); + } + + #[test] + fn quality_selector_enables_ao_and_supports_persistence_and_cancel() { + let mut h = crate::scenario::Harness::new(); + let camera = h.app.cam; + let design = h.app.session.doc.to_json(); + let msaa = h.app.preferences.msaa; + h.call("ui.prefs", json!({"open":"Graphics"})); + for handle in ["view:graphics_preset", "view:graphics_preset:quality"] { + let pos = crate::scenario::handle_at(handle).unwrap(); + h.call("ui.click", json!({"x":pos.x,"y":pos.y})); + } + assert!(h.app.preferences.ambient_occlusion); + let mut restored = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + restored.load_prefs(&h.app.prefs()); + assert!(restored.preferences.ambient_occlusion); + h.call("ui.prefs", json!({"button":"cancel"})); + assert_eq!(graphics_preset(&h.app.preferences), "performance"); + assert!(!h.app.preferences.ambient_occlusion); + h.call("engine.execute", json!({"command":"view.graphics_preset","params":{"preset":"quality"}})); + assert!(h.app.preferences.ambient_occlusion); + h.call("engine.execute", json!({"command":"view.graphics_preset","params":{"preset":"invalid"}})); + assert!(h.app.preferences.ambient_occlusion); + h.call("engine.execute", json!({"command":"view.graphics_preset","params":{"preset":"performance"}})); + assert!(!h.app.preferences.ambient_occlusion); + assert_eq!(graphics_preset(&h.app.preferences), "performance"); + assert_eq!(h.app.preferences.display_quality, "normal"); + assert_eq!(h.app.preferences.supersampling, 1.0); + h.call("engine.execute", json!({"command":"view.graphics_preset","params":{"preset":"quality"}})); + assert_eq!(graphics_preset(&h.app.preferences), "quality"); + assert_eq!(h.app.preferences.display_quality, "fine"); + assert_eq!(h.app.preferences.supersampling, 2.0); + assert!(h.app.preferences.supersampling_adaptive); + for edit in [ + json!({"display_quality":"ultra"}), + json!({"supersampling":1.5}), + json!({"supersampling_adaptive":false}), + json!({"ambient_occlusion":false}), + ] { + h.call("engine.execute", json!({"command":"view.graphics_preset","params":{"preset":"quality"}})); + h.call("ui.prefs", edit); + assert_eq!(graphics_preset(&h.app.preferences), "custom"); + } + assert_eq!(graphics_preset(&restored.preferences), "quality"); + h.call("ui.prefs", json!({"open":"Graphics"})); + h.call("ui.prefs", json!({"button":"defaults"})); + assert_eq!(graphics_preset(&h.app.preferences), "performance"); + h.call("ui.prefs", json!({"button":"ok"})); + assert_eq!(h.app.preferences.msaa, msaa); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.doc.to_json(), design); + assert!(h.app.session.undo.is_empty()); + } +} diff --git a/crates/ui-egui/src/render_workspace.rs b/crates/ui-egui/src/render_workspace.rs index 332ba2ca8..bdcbe43ba 100644 --- a/crates/ui-egui/src/render_workspace.rs +++ b/crates/ui-egui/src/render_workspace.rs @@ -538,6 +538,8 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { analysis_colors: [0.0; 36], access: None, outline: false, + // Product rendering has its own lighting; AO is a Design viewport setting. + ao_radius: 0.0, eye: [eye.x as f32, eye.y as f32, eye.z as f32, if camera.fov > 0.0 { 1.0 } else { 0.0 }], ssaa: if width < full.0 { width as f32 / full.0 as f32 } else { 1.0 }, }); diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 190e82c20..bde68cac6 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -2420,6 +2420,11 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { analysis_colors: crate::gpu::analysis_colors(&t.analysis), access: crate::access::map(app), outline: matches!(app.ui.visual_style, 0 | 3), + ao_radius: if app.preferences.ambient_occlusion && app.ui.visual_style != 2 { + (model_bounds(app).diagonal() * 0.04).clamp(1e-4, 1e6) as f32 + } else { + 0.0 + }, eye: { let e = proj.cam.eye().to_f32(); [e[0], e[1], e[2], if proj.cam.fov > 0.0 { 1.0 } else { 0.0 }] @@ -3446,7 +3451,7 @@ fn nav_bar(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect) { ("home", "Home view"), ("perspective", "Perspective / orthographic"), ("style", "Visual style: shaded with edges, shaded, wireframe, shaded with hidden edges"), - ("settings", "View settings: grid, ground shadow, agent cursor"), + ("settings", "View settings: grid, ground shadow, ambient occlusion, agent cursor"), ]; let menu_id = ui.id().with("nav_view_menu"); let mut menu_open = ui.data(|d| d.get_temp::(menu_id)).unwrap_or(false); @@ -3519,6 +3524,8 @@ fn nav_bar(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect) { /// The View settings above the navigation bar's last button: grid, ground shadow and the agent /// cursor (#35). False once it should close (a click outside it). fn view_menu(app: &mut SolveApp, ui: &mut egui::Ui, button: Rect) -> bool { + // A preset dropdown extends beyond this menu; let it consume its own clicks. + let child_popup_open = egui::Popup::is_any_open(ui.ctx()); let area = crate::frame::area(egui::Id::new("sc_view_menu")) .order(egui::Order::Foreground) .pivot(Align2::RIGHT_BOTTOM) @@ -3527,8 +3534,12 @@ fn view_menu(app: &mut SolveApp, ui: &mut egui::Ui, button: Rect) -> bool { egui::Frame::popup(ui.style()).show(ui, |ui| { ui.set_width(220.0); ui.label(egui::RichText::new(crate::i18n::tr_label("VIEW")).strong().size(11.5)); + ui.label(app.tr("ui.graphics_preset")); + crate::prefs::graphics_preset_selector(app, ui); + ui.separator(); ui.checkbox(&mut app.ui.show_grid, crate::i18n::tr_label("Grid")); ui.checkbox(&mut app.ui.ground_shadow, crate::i18n::tr_label("Ground shadow")); + crate::prefs::ambient_occlusion_checkbox(app, ui, "Ambient occlusion"); ui.separator(); let s = &mut app.ui.agent_cursor; let show = ui.checkbox(&mut s.show, crate::i18n::tr_label("Show Agent Cursor")); @@ -3553,7 +3564,8 @@ fn view_menu(app: &mut SolveApp, ui: &mut egui::Ui, button: Rect) -> bool { } }); }); - let clicked_out = ui.input(|i| i.pointer.any_pressed()) + let clicked_out = !child_popup_open + && ui.input(|i| i.pointer.any_pressed()) && ui.input(|i| i.pointer.interact_pos()).is_some_and(|p| !r.response.rect.contains(p) && !button.contains(p)); !clicked_out } diff --git a/crates/ui-egui/tests/scenarios/colour_vision_setting.json b/crates/ui-egui/tests/scenarios/colour_vision_setting.json index 6e1b35017..bad0d850d 100644 --- a/crates/ui-egui/tests/scenarios/colour_vision_setting.json +++ b/crates/ui-egui/tests/scenarios/colour_vision_setting.json @@ -1,25 +1,22 @@ [ - {"note": "#778: Preferences › Graphics › Colour vision. A mode applies at once, Cancel puts it back, OK keeps it, Restore Defaults on Graphics resets it, and the window keeps its size."}, + {"note": "#778: Preferences › Graphics › Colour vision. A mode applies at once, Cancel puts it back, OK keeps it, Restore Defaults on Graphics resets it, and the window keeps its size. The accessibility controls sit above the longer rendering-quality rows, so nothing here needs scrolling."}, {"click": {"handle": "titlebar:preferences"}}, {"expect": {"prefs": {"dialog": "General", "color_vision": "off"}, "same_width": "prefs:window"}}, {"widget": "Graphics"}, - {"call": "ui.scroll", "params": {"x": 800, "y": 500, "delta": -3000}}, {"expect": {"shown": "Colour vision", "prefs": {"dialog": "Graphics"}, "same_width": "prefs:window"}}, - {"widget": "Off"}, + {"click": {"handle": "prefs:color_vision"}}, {"widget": "Deutan"}, {"expect": {"prefs": {"color_vision": "deutan"}, "same_width": "prefs:window"}}, {"widget": "Cancel"}, {"expect": {"prefs": {"dialog": null, "color_vision": "off"}}}, {"key": "Comma", "cmd": true}, {"widget": "Graphics"}, - {"call": "ui.scroll", "params": {"x": 800, "y": 500, "delta": -3000}}, - {"widget": "Off"}, + {"click": {"handle": "prefs:color_vision"}}, {"widget": "Tritan"}, {"widget": "OK"}, {"expect": {"prefs": {"dialog": null, "color_vision": "tritan"}}}, {"key": "Comma", "cmd": true}, {"widget": "Graphics"}, - {"call": "ui.scroll", "params": {"x": 800, "y": 500, "delta": -3000}}, {"expect": {"shown": "Tritan", "same_width": "prefs:window"}}, {"widget": "Restore Defaults"}, {"expect": {"prefs": {"color_vision": "off"}}}, diff --git a/docs/ambient-occlusion.md b/docs/ambient-occlusion.md new file mode 100644 index 000000000..ab2a1c0de --- /dev/null +++ b/docs/ambient-occlusion.md @@ -0,0 +1,101 @@ +# Ambient occlusion + +Enable **Ambient occlusion** in the viewport's **View settings** menu or in +**Preferences → Graphics**. It adds soft contact shading at corners, recesses and +nearby opaque surfaces. It is off by default, applies immediately, and is saved +between runs. The shared **Graphics Preset** selector in both settings surfaces +combines AO with the display-quality and supersampling controls from #1319 and #1321: + +| Preset | Ambient occlusion | Display quality | Supersampling | +|---|---|---|---| +| Performance (default) | Off | Normal | Off (1×) | +| Quality | On | Fine | 2×, only while the view is still | +| Custom | Your manual combination | Your manual combination | Your manual combination | + +Custom is derived from the current settings, not a third preset that overwrites them. +Individual controls remain editable. Selecting a preset applies all three settings +immediately; MSAA, ground shadow, projection and visual style stay unchanged. +Graphics preferences support Cancel, Apply and Restore Defaults. Adaptive supersampling +keeps #1321's 0.25-second settling delay, texture limit and 384 MiB memory cap; +the requested 2× may be reduced or skipped when the device cannot accommodate it. + +The control channel and connected MCP clients can use the same command as the UI: + +```json +{"command":"view.ambient_occlusion","params":{"enabled":true}} +``` + +`view.graphics_preset {"preset":"quality"}` (or `"performance"`) selects the preset. + +`ui.prefs {"ambient_occlusion": true}` also sets the preference. The command changes +only display preferences, without adding a modelling undo step or moving the camera. + +The GPU viewport uses 32 deterministic hemisphere samples per shaded pixel against +an opaque depth prepass (at most 2048 pixels on its longest side). The radius follows +model size, and depth-range rejection avoids shadows from distant foreground objects. +It supports orthographic and perspective cameras and respects section clipping. +Wireframe, transparent bodies, overlays and surface-analysis colours are unaffected. +Disabling it skips the depth prepass and sampling and releases the full-size depth map. + +This is screen-space shading: off-screen and hidden surfaces cannot contribute. +The software fallback and CPU model snapshots do not apply this GPU effect. Capture +the actual window with `ui.screenshot` when reviewing it. + +## Metal startup comparison (2026-10-15) + +On an Apple M3 Pro (18-core GPU, 36 GiB unified memory), macOS 27.0 +(26A428), both unchanged main `0872eb95` and this branch merged with that +revision reproduce the same startup defect: `solidcraft --sample` shows the +plate's edges and ground shadow but no opaque faces. AO is disabled on the +branch and does not exist on main. Both were built with `--profile ci`, launched +separately on Metal with MSAA 4x, and captured at 1200 × 850 logical pixels +(2400 × 1700 physical pixels). Their viewport captures are pixel-identical. +This establishes that the symptom also exists on main; this PR does not fix it. + +For the AO comparison screenshots and timings below, the display mesh was +rebuilt by assigning the sample Plate opacity 0.99 and then restoring it to 1.0 +(with the same colour, `#a6b0bd`). Measurements use opaque faces, GPU +tessellation and the actual native viewport after that rebuild. The screenshots +are attached in the review conversation, rather than committed as generated assets. + +## AO-only rendering performance (2026-10-15) + +These measurements predate the combined presets. They isolate AO at Normal +tessellation with supersampling off; they are **not** timings for the combined +Quality preset, which also requests Fine tessellation and adaptive 2× supersampling. + +Same M3 Pro / macOS machine and `ci` build profile as above (not a release-build +claim). Window: 2400 × 1700 physical pixels; model viewport: 1900 × 1312. +Orthographic home view, shaded with edges, MSAA 4x, normal display quality, +supersampling off, ground shadow on, grid/origin/sketches hidden. The heavier +design is a rectangular body pattern of the sample: 5 × 5 plates, X spacing +90 mm, Y spacing 60 mm, fitted to the viewport (25 opaque bodies). + +These are **completed render-work milliseconds per frame**, not the UI-only +`ui.inspect.frame_ms` or a claimed display FPS. Temporary native instrumentation +measured from the beginning of `paint_and_update_textures` through command +submission and `device.poll(PollType::wait_indefinitely())`. The renderer's +accumulated surface-acquisition/queue-submit timing was subtracted; presentation +and UI layout are excluded. This includes CPU render preparation and waiting +for GPU completion. Continuous repaint was enabled. Instrumentation was removed +from the source after building the measurement binary. + +Each design ran three alternating Performance/Quality pairs: 2 seconds warm-up +after each switch, then 3 seconds recorded. No builds ran during measurement. +The table pools the recorded frames; p95 exposes variability on this shared +desktop. It is a local comparative measurement, not a hardware-independent FPS +guarantee or a modelling/recompute benchmark. + +| Design | Preset | Frames | Median render ms | p95 render ms | +|---|---|---:|---:|---:| +| sample | performance | 1082 | 2.52 | 2.65 | +| sample | quality | 1077 | 6.35 | 7.27 | +| 25-plates | performance | 1074 | 3.15 | 3.45 | +| 25-plates | quality | 1082 | 6.93 | 7.50 | + +Per-trial medians (ms), in chronological order: + +- sample-performance: 2.53, 2.47, 2.53. +- sample-quality: 5.82, 4.48, 7.08. +- 25-plates-performance: 3.13, 3.16, 3.14. +- 25-plates-quality: 6.80, 7.02, 6.95. diff --git a/xtask/src/features.rs b/xtask/src/features.rs index 72013bf86..0822678b6 100644 --- a/xtask/src/features.rs +++ b/xtask/src/features.rs @@ -4,7 +4,7 @@ //! label, id and toolbar place. It comes only from SolidCraft's command registry //! (`solidcraft-cli commands`), so it can't drift from what the program does; it compares with //! nothing else. Planned commands (registered, not built yet) are listed as planned, with their -//! issue, and are not counted. +//! issue. Counts are omitted so unrelated command additions do not edit shared headers. use std::path::Path; @@ -61,25 +61,18 @@ pub fn page(cmds: &[Value]) -> String { order.push((p.clone(), format!("`{p}.*`"))); } let planned = |c: &Value| c["planned"].as_str().map(str::to_string); - let built = cmds.iter().filter(|c| planned(c).is_none()).count(); - let later = match cmds.len() - built { - 0 => String::new(), - n => format!(" Planned (registered, not built yet): {n}."), - }; - let mut md = format!( + // Counts made every command addition edit the same header, even across unrelated areas. + // Keep generated text local to each command so parallel branches merge cleanly more often. + let mut md = String::from( "# Features\n\nSolidCraft's commands by area, generated by `cargo xtask features` from the command registry \ - (`solidcraft-cli commands`). **{built} commands.**{later} Every command runs the same way from the toolbar, a script, \ + (`solidcraft-cli commands`). Planned commands are marked in their rows. Every command runs the same way from the toolbar, a script, \ `solidcraft-cli exec ''`, the control channel and MCP; parameters are in the \ - [command reference](book/src/reference/commands.md) (`cargo xtask book`). Status and plans: [ROADMAP](../ROADMAP.md).\n" + [command reference](book/src/reference/commands.md) (`cargo xtask book`). Status and plans: [ROADMAP](../ROADMAP.md).\n", ); for (prefix, heading) in &order { - let in_area: Vec<&Value> = cmds.iter().filter(|c| area(&s(c, "id")) == prefix).collect(); - let n = in_area.iter().filter(|c| planned(c).is_none()).count(); - let count = match in_area.len() - n { - 0 => n.to_string(), - p => format!("{n}, {p} planned"), - }; - md += &format!("\n## {heading} ({count})\n\n| Command | Id | Toolbar |\n|---|---|---|\n"); + let mut in_area: Vec<&Value> = cmds.iter().filter(|c| area(&s(c, "id")) == prefix).collect(); + in_area.sort_by_key(|c| s(c, "id")); + md += &format!("\n## {heading}\n\n| Command | Id | Toolbar |\n|---|---|---|\n"); for c in in_area { let place = match (s(c, "tab"), s(c, "panel")) { (t, _) if t.is_empty() => "–".to_string(), @@ -108,12 +101,22 @@ mod tests { ) .unwrap(); let md = page(cmds.as_array().unwrap()); - assert!(md.contains("**3 commands.** Planned (registered, not built yet): 1.")); - let (sk, so, other) = - (md.find("## Sketch (1)").unwrap(), md.find("## Solid modelling (1, 1 planned)").unwrap(), md.find("## `view.*` (1)").unwrap()); + assert!(md.contains("Planned commands are marked in their rows.")); + let (sk, so, other) = (md.find("## Sketch").unwrap(), md.find("## Solid modelling").unwrap(), md.find("## `view.*`").unwrap()); assert!(sk < so && so < other); assert!(md.contains("| Extrude (E) | `solid.extrude` | SOLID › CREATE |")); assert!(md.contains("| Fit | `view.fit` | – |")); assert!(md.contains("| Knit *(planned: [#9](https://github.com/bherbruck/solidcraft/issues/9))* | `solid.knit` | SOLID › CREATE |")); } + #[test] + fn unrelated_additions_do_not_rewrite_existing_lines_and_order_is_stable() { + let commands = vec![serde_json::json!({"id":"view.zoom","label":"Zoom"}), serde_json::json!({"id":"view.fit","label":"Fit"})]; + let before = page(&commands); + let mut reordered = commands.clone(); + reordered.reverse(); + assert_eq!(before, page(&reordered)); + reordered.push(serde_json::json!({"id":"view.pan","label":"Pan"})); + let after = page(&reordered); + assert_eq!(before, after.lines().filter(|l| !l.contains("`view.pan`")).collect::>().join("\n") + "\n"); + } } From 66108a6b995b786294a4b861086f214f8886451a Mon Sep 17 00:00:00 2001 From: "A.Hakim Noor" <35808331+a-hakim@users.noreply.github.com> Date: Mon, 19 Oct 2026 09:34:54 +0800 Subject: [PATCH 032/225] Add Malay language support and update localization doc (#2188) Thanks @a-hakim. --- ATTRIBUTION.md | 1 + assets/locales/ms.json | 1530 ++++++++++++++++++++++++++++++++++++ crates/ui-egui/src/i18n.rs | 25 +- docs/control-protocol.md | 2 +- docs/localization.md | 6 +- 5 files changed, 1559 insertions(+), 5 deletions(-) create mode 100644 assets/locales/ms.json diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 30dcf13eb..3c649e1ae 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -96,6 +96,7 @@ Editable drawing code, native projects and shipped exports are collected under ` | assets/locales/it.json | SolidCraft contributors | Original Italian translation of SolidCraft's English catalog; no commercial CAD text used | MIT OR Apache-2.0 | | assets/locales/ja.json | SolidCraft contributors | Original SolidCraft resource data or drawing code, collected without redesign | MIT OR Apache-2.0 | | assets/locales/ko.json | SolidCraft contributors | Original SolidCraft resource data or drawing code, collected without redesign | MIT OR Apache-2.0 | +| assets/locales/ms.json | A.Hakim (a-hakim) | Malay translation of the English message catalog | MIT OR Apache-2.0 | | assets/locales/pl.json | cyryllo | Polish translation of the English catalog, contributed upstream | MIT OR Apache-2.0 | | assets/locales/ru.json | Alex Pro (del000) | Russian translation of the English catalog, contributed upstream | MIT OR Apache-2.0 | | assets/locales/pt-BR.json | DuBearte | Brazilian Portuguese translation of the English catalog, contributed upstream | MIT OR Apache-2.0 | diff --git a/assets/locales/ms.json b/assets/locales/ms.json new file mode 100644 index 000000000..42a7ad4d5 --- /dev/null +++ b/assets/locales/ms.json @@ -0,0 +1,1530 @@ +{ + "0 turns it off": "0 untuk matikan", + "1. Open GitHub draft below, then paste the report copied to your clipboard.": "1. Buka draf GitHub di bawah, kemudian tampal laporan yang disalin ke papan klip anda.", + "1. Open GitHub draft below. Your title and report will be filled in.": "1. Buka draf GitHub di bawah. Tajuk dan laporan anda akan diisi secara automatik.", + "2. Attach your screenshot: copy and paste it, or save and upload the PNG.": "2. Lampirkan tangkapan skrin anda: salin dan tampal, atau simpan dan muat naik PNG.", + "3. Click Submit new issue on GitHub to send your report.": "3. Klik Submit new issue di GitHub untuk menghantar laporan anda.", + "A new configuration, a copy of the active one": "Konfigurasi baharu, salinan konfigurasi aktif", + "AI": "AI", + "About SolidCraft": "Tentang SolidCraft", + "Acceleration": "Pecutan", + "Active": "Aktif", + "Active rule": "Peraturan aktif", + "Add": "Tambah", + "Add Key": "Tambah Bingkai Utama", + "Add Mid Radius": "Tambah Jejari Tengah", + "Add Row": "Tambah Baris", + "Add condition": "Tambah syarat", + "Against": "Bertentangan", + "Alignment": "Penjajaran", + "All Sketch Points": "Semua Titik Lakaran", + "All components": "Semua komponen", + "All open designs": "Semua reka bentuk terbuka", + "Allowed expressions, separated by semicolons": "Ungkapan yang dibenarkan, dipisahkan dengan titik koma", + "Also deletes": "Turut memadam", + "Angle 2": "Sudut 2", + "Animate": "Animasikan", + "Appearance name": "Nama penampilan", + "Applied Radius": "Jejari Digunakan", + "Apply To": "Gunakan Pada", + "Apply to selection": "Gunakan pada pilihan", + "Arc length": "Panjang lengkok", + "Area": "Luas", + "Attachment": "Pautan", + "BOUNDARY SURFACE": "PERMUKAAN SEMPADAN", + "BROWSER": "PELAYAR", + "Bend Line Position": "Kedudukan Garis Lenturan", + "Bend Position": "Kedudukan Lenturan", + "Bend Radius": "Jejari Lenturan", + "Bends": "Lenturan", + "Body": "Jasad", + "Boundary": "Sempadan", + "Bounding box": "Kotak pembatas", + "CSV or JSON: updates existing parameters, adds new ones": "CSV atau JSON: kemas kini parameter lama, tambah yang baharu", + "Capture All Positions": "Rakam Semua Kedudukan", + "Catch Direction": "Arah Cangkuk", + "Cells": "Sel", + "Center X": "Pusat X", + "Center Y": "Pusat Y", + "Center of mass": "Pusat jisim", + "Centre to centre": "Pusat ke pusat", + "Chamfer Type": "Jenis Serong", + "Check collisions": "Semak perlanggaran", + "Checked": "Disemak", + "Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.": "Pilih satah baharu. Geometri dan dimensi lakaran dikekalkan dalam koordinat dua dimensi lakaran tersebut.", + "Circumference": "Lilitan", + "Close draft": "Tutup draf", + "Collisions": "Perlanggaran", + "Colour": "Warna", + "Component1": "Komponen1", + "Configuration": "Konfigurasi", + "Configuration rules": "Peraturan konfigurasi", + "Construction": "Binaan", + "Contact": "Sentuhan", + "Contact sets": "Set sentuhan", + "Continuity": "Keselanjaran", + "Copy Error Message": "Salin Mesej Ralat", + "Copy Warning Message": "Salin Mesej Amaran", + "Copy all licences": "Salin semua lesen", + "Copy diagnostic information": "Salin maklumat diagnostik", + "Copy report": "Salin laporan", + "Copy screenshot": "Salin tangkapan skrin", + "Corner Relief": "Pelega Sudut", + "Corner Relief Shape": "Bentuk Pelega Sudut", + "Counterbore depth": "Kedalaman lubang benam rata", + "Countersink angle": "Sudut lubang benam tirus", + "Create Issue — review draft": "Cipta Isu — semak draf", + "Cross curves": "Lengkung silang", + "Cube": "Kubus", + "Current orthographic view (1:1 mm)": "Pandangan ortografik semasa (1:1 mm)", + "Current perspective view": "Pandangan perspektif semasa", + "Curvature (G2)": "Kelengkungan (G2)", + "Customize Toolbar": "Sesuaikan Bar Alat", + "Delete all": "Padam semua", + "Delete rule": "Padam peraturan", + "Delete the row": "Padam baris", + "Delete the set": "Padam set", + "Delete this parameter": "Padam parameter ini", + "Density": "Ketumpatan", + "Designs you open or save appear here.": "Reka bentuk dibuka atau disimpan ada di sini.", + "Determined by To Object. Choose Angle to edit the angular extent.": "Ditentukan oleh tetapan Ke Objek. Pilih Sudut untuk mengubah julat sudut.", + "Direction": "Arah", + "Discard": "Buang", + "Do not export hidden edges": "Jangan eksport tepi tersembunyi", + "Don't ask again": "Jangan tanya lagi", + "Double-click to rename": "Klik dua kali untuk tukar nama", + "Double-clicking the middle button in the view: Home (the home view, framing what is shown), Fit (frame what is shown, keeping the orientation) or nothing": "Klik dua kali butang tengah: Utama (pandangan utama, muatkan objek), Muatkan (muatkan objek, kekalkan orientasi) atau tiada tindakan", + "Drive Joint": "Gerakkan Sendi", + "Duration": "Tempoh", + "Edges": "Tepi", + "Edit Profile Sketch": "Sunting Lakaran Profil", + "Enable rule": "Aktifkan peraturan", + "Enabled": "Diaktifkan", + "Explode": "Leraikan", + "Explode Text": "Leraikan Teks", + "Export Animation…": "Eksport Animasi…", + "Export Current View as DXF": "Eksport Pandangan Semasa sebagai DXF", + "Export Current View as DXF…": "Eksport Pandangan Semasa sebagai DXF…", + "Export DXF…": "Eksport DXF…", + "Export hidden edges as dashed lines": "Eksport tepi tersembunyi sebagai garis putus-putus", + "Extents": "Julat", + "Face": "Muka", + "Face attachment lost": "Pautan muka hilang", + "Faces": "Muka", + "Faces / edges / vertices": "Muka / tepi / bucu", + "Favourite": "Kegemaran", + "Files from many CAD programs have Y up, so they open lying on their back here (Z up).": "Banyak fail CAD menggunakan Y ke atas, jadi model terbaring di sini (Z ke atas).", + "Filter": "Tapis", + "Find in Browser": "Cari dalam Pelayar", + "Flat": "Rata", + "Flat size": "Saiz rata", + "Follow camera (Look At sketches)": "Ikut kamera (Pandang Tepat pada lakaran)", + "Follow the camera (Look At sketches)": "Ikut kamera (Pandang Tepat pada lakaran)", + "Font": "Fon", + "Full Length": "Panjang Penuh", + "Gap": "Sela", + "Grid": "Grid", + "Height": "Ketinggian", + "Hidden edges": "Tepi tersembunyi", + "Holes": "Lubang", + "Holes (edges on them)": "Lubang (tepi lubang)", + "Home view": "Pandangan utama", + "In This Design": "Dalam Reka Bentuk Ini", + "In place (surfaces)": "Di tempat asal (permukaan)", + "In plane": "Dalam satah", + "Inside": "Dalam", + "Interferes": "Bertindih", + "Issue title": "Tajuk isu", + "Joint Origin1": "Titik Asal Sendi1", + "Keep Tools": "Kekalkan Alat", + "Later": "Kemudian", + "Leave it": "Biarkan", + "Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "Pautan muka lama. Paut semula ke muka yang disahkan untuk pautan tepat.", + "Length": "Panjang", + "Length units": "Unit panjang", + "Letter Spacing": "Jarak Huruf", + "Library": "Koleksi", + "Line Spacing": "Jarak Baris", + "Loop": "Gelung", + "Margin": "Jidar", + "Mass": "Jisim", + "Material": "Bahan", + "Max": "Maks", + "Mid Radius": "Jejari Tengah", + "Middle double-click": "Klik dua kali butang tengah", + "Min": "Min", + "Mitre": "Serong", + "Modeled": "Dimodelkan", + "More toolbar panels": "Panel bar alat lain", + "Motion": "Gerakan", + "Move Type": "Jenis Gerakan", + "Move earlier": "Alih lebih awal", + "Move later": "Alih lebih lewat", + "Name": "Nama", + "Nearest": "Terdekat", + "New study": "Kajian baharu", + "No crash reports.": "Tiada laporan ranap.", + "No matching appearances": "Tiada penampilan yang sepadan", + "No visible bodies to export.": "Tiada jasad kelihatan untuk dieksport.", + "None": "Tiada", + "Normal to sketch": "Serenjang", + "Not available yet": "Belum tersedia", + "Notch": "Takuk", + "Opacity": "Kelegapan", + "Open GitHub draft": "Buka draf GitHub", + "Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "CAD 3D parametrik sumber terbuka dalam Rust. Lesen MIT OR Apache-2.0.", + "Other side": "Sebelah lagi", + "Outside": "Luar", + "Overall length": "Panjang keseluruhan", + "Parameter values": "Nilai parameter", + "Pass through": "Tembus", + "Path": "Laluan", + "Per Edge": "Setiap Tepi", + "Pick the tool bodies": "Pilih jasad alat", + "Picked": "Dipilih", + "Picked point": "Titik yang dipilih", + "Place at the origin instead": "Letak di titik asal", + "Playback": "Main balik", + "Plot": "Plot", + "Position": "Kedudukan", + "Position (0 to 1)": "Kedudukan (0 hingga 1)", + "Position (G0)": "Kedudukan (G0)", + "Position along the edge, 0 at the start end, 1 at the other": "Kedudukan pada tepi: 0 di hujung mula, 1 di hujung satu lagi", + "Preferences › Design turns the offer back on": "Aktifkan semula di Tetapan › Reka Bentuk", + "Preview Row": "Pratonton Baris", + "Preview leaves the current design unchanged.": "Pratonton tidak mengubah reka bentuk semasa.", + "Profiles/Curves": "Profil/Lengkung", + "Projection": "Unjuran", + "Quantity": "Kuantiti", + "RECENT": "TERKINI", + "RULED SURFACE": "PERMUKAAN BERGARIS", + "Radius Fit": "Padanan Jejari", + "Ratio": "Nisbah", + "Reattach selected face": "Paut semula muka dipilih", + "Recover": "Pulihkan", + "Recover unsaved design?": "Pulihkan reka bentuk belum disimpan?", + "Rectangular": "Segi empat tepat", + "Reference face": "Muka rujukan", + "Remove Tools": "Buang Alat", + "Remove from list": "Buang daripada senarai", + "Remove override": "Buang penggantian", + "Remove private design details or paths before sharing.": "Buang butiran peribadi reka bentuk atau laluan fail sebelum berkongsi.", + "Remove screenshot": "Buang tangkapan skrin", + "Remove the column": "Buang lajur", + "Remove the track": "Buang trek", + "Remove this point": "Buang titik ini", + "Report a bug — review a screenshot and open a GitHub draft": "Laporkan pepijat — semak tangkapan skrin dan buka draf GitHub", + "Reset Toolbar": "Set Semula Bar Alat", + "Restore outer boundary": "Pulihkan sempadan luar", + "Restore the inherited component or physical material appearance": "Pulihkan penampilan yang diwarisi daripada komponen atau bahan fizikal", + "Result": "Hasil", + "Retake screenshot": "Tangkap semula", + "Reverse": "Songsangkan", + "Reverse Direction": "Songsangkan Arah", + "Revert": "Kembalikan", + "Revert All Positions": "Kembalikan Semua Kedudukan", + "Revert Position": "Kembalikan Kedudukan", + "Review the report and screenshot before opening GitHub.": "Semak laporan dan tangkapan skrin sebelum membuka GitHub.", + "Rim Edge": "Tepi Bibir", + "Roll History Marker Here": "Alih Penanda Sejarah ke Sini", + "Round": "Bulat", + "Rule": "Peraturan", + "Save Rule": "Simpan Peraturan", + "Save the study as an animated GIF, seen as the viewport shows it": "Simpan kajian sebagai GIF beranimasi mengikut paparan", + "Saved preview. Geometry is being checked before editing.": "Pratonton disimpan. Geometri disemak sebelum disunting.", + "Scale factor": "Faktor skala", + "Search": "Cari", + "Search commands": "Cari arahan", + "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Pilih Lain: tahan butang kiri pada model tanpa bergerak (atau klik kanan › Pilih Lain…) untuk senarai objek di bawah kursor. Klik tempat sama untuk objek seterusnya. Klik dua kali butang tengah untuk ke Utama (Tetapan › Navigasi).", + "Select bodies (a face picks its body)": "Pilih jasad (klik muka untuk pilih jasadnya)", + "Select bodies or faces instead": "Pilih jasad atau muka", + "Selection filter": "Penapis pilihan", + "Semantic faces share their appearance across instances.": "Muka semantik berkongsi penampilan pada semua salinan.", + "Send your report on GitHub": "Hantar laporan anda di GitHub", + "Shape": "Bentuk", + "Show Agent Cursor": "Papar Kursor Ejen", + "Show in folder": "Papar dalam folder", + "Show the pointer an AI agent moves (#35)": "Papar penuding yang digerakkan oleh ejen AI (#35)", + "Signed axes": "Paksi bertanda", + "Size": "Saiz", + "Sketch constraints": "Kekangan lakaran", + "Sketch curves": "Lengkung lakaran", + "Sketch dimensions": "Dimensi lakaran", + "Sketch geometry and profiles": "Geometri dan profil lakaran", + "Sketch plane has no body-face attachment.": "Satah lakaran tiada pautan ke muka jasad.", + "Sketch points": "Titik lakaran", + "Slot width": "Lebar slot", + "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft ditutup sebelum reka bentuk disimpan. Buka simpanan automatik terakhirnya.", + "Speed": "Kelajuan", + "Stand it up": "Tegakkan", + "Stand it up: a quarter turn about X, as one Move feature you can undo.": "Tegakkan: suku putaran pada X, satu ciri Alih yang boleh dibatalkan.", + "Stand this part up?": "Tegakkan bahagian ini?", + "Step": "Langkah", + "Steps": "Langkah", + "Study": "Kajian", + "Style": "Gaya", + "Suppressed": "Dinyahaktifkan", + "Swap Ends": "Tukar Hujung", + "Tangent (G1)": "Tangen (G1)", + "Tangent Chain": "Rantaian Tangen", + "Tear": "Koyakan", + "The dashed sketch is a saved plane guide. Select a new face to repair the attachment.": "Lakaran putus-putus ialah panduan satah disimpan. Pilih muka baharu untuk baiki pautan.", + "The saved author occurrence is missing. Select a valid author placement before rebinding.": "Salinan asal komponen lakaran tiada. Pilih penempatan komponen yang sah sebelum paut semula.", + "Then": "Kemudian", + "These features will be deleted:": "Ciri-ciri berikut akan dipadam:", + "These features will fail:": "Ciri-ciri berikut akan gagal:", + "Thickness Outside": "Ketebalan Luar", + "Thin": "Nipis", + "Thin Extrude": "Penyemperitan Nipis", + "This child is shared. Deleting it removes it from every copy of its parent.": "Komponen anak dikongsi. Jika dipadam, semua salinan induk turut kehilangannya.", + "This child is shared. Position changes apply to every copy of its parent.": "Komponen anak dikongsi. Kedudukan berubah pada semua salinan induk.", + "This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "Muka ini tidak dapat kekalkan pautan. Pilih muka lain atau gunakan satah tetap.", + "To Offset": "Ke Ofset", + "Tolerance": "Toleransi", + "Too close": "Terlalu dekat", + "Turn off section analysis before exporting the view.": "Matikan analisis keratan sebelum mengeksport pandangan.", + "Type": "Jenis", + "UNTRIM": "NYAHPANGKAS", + "Updating the preview": "Mengemas kini pratonton", + "Use active author placement": "Guna penempatan komponen aktif", + "Use fixed plane": "Guna satah tetap", + "Use saved fixed plane": "Guna satah tetap disimpan", + "Use selected face as fixed plane": "Guna muka dipilih sebagai satah tetap", + "VIEW": "PANDANGAN", + "Value": "Nilai", + "Velocity": "Halaju", + "Vertices": "Bucu", + "View navigator": "Kawalan pandangan", + "Visible bodies only. Curves use line segments (0.01 mm tolerance).": "Jasad kelihatan sahaja. Lengkung guna segmen garis (toleransi 0.01 mm).", + "Volume": "Isi padu", + "Wall": "Dinding", + "Wall Location": "Lokasi Dinding", + "Wall Thickness": "Ketebalan Dinding", + "When": "Apabila", + "Width": "Lebar", + "Will fail": "Akan gagal", + "angle, height": "sudut, ketinggian", + "appearance.dielectric_ior": "IOR Dielektrik", + "appearance.metallic": "Sifat Logam", + "appearance.pbr_help": "Lihat dalam Render atau PNG produk. Tiada pembiasan atau penembusan cahaya.", + "appearance.pbr_opaque": "PBR Legap", + "appearance.roughness": "Kekasaran", + "appearance.surface_response": "Tindak balas permukaan", + "browser.body_name": "Jasad{number}", + "browser.component_name": "Komponen{number}", + "browser.parameters": "Parameter ({count})", + "browser.precision": "Ketepatan: {precision}", + "browser.sketch_name": "Lakaran{number}", + "browser.units": "Unit: {units}", + "cam.flat": "Muka rata", + "cam.follower": "Pengikut", + "cam.knife": "Tepi pisau", + "cam.needs_joints": "perlu satu sendi putar dan satu sendi gelongsor atau ayun", + "cam.roller": "Penggelek", + "cam.roller_pick": "Penggelek (tidak wajib)", + "cam.tip_pick": "Hujung (tidak wajib)", + "cmd.appearance_assign": "Penampilan", + "cmd.appearance_library": "Koleksi Penampilan", + "cmd.appearance_list": "Senarai Penampilan", + "cmd.body_rename": "Tukar Nama Jasad", + "cmd.browser_group": "Kumpulan Baharu", + "cmd.browser_move": "Alih Item Pelayar", + "cmd.browser_order": "Susun Item Pelayar", + "cmd.browser_rename_group": "Tukar Nama Kumpulan", + "cmd.browser_ungroup": "Nyahkumpul", + "cmd.browser_visibility": "Papar/Sembunyi", + "cmd.canvas_calibrate": "Tentukur Kanvas", + "cmd.canvas_decal": "Dekal", + "cmd.canvas_delete": "Padam Kanvas", + "cmd.canvas_edit": "Sunting Kanvas", + "cmd.canvas_insert": "Kanvas", + "cmd.component_activate": "Aktifkan Komponen", + "cmd.component_break_link": "Putuskan Pautan", + "cmd.component_capture_position": "Rakam Kedudukan", + "cmd.component_create": "Komponen Baharu", + "cmd.component_delete": "Padam Komponen", + "cmd.component_from_bodies": "Cipta Komponen daripada Jasad", + "cmd.component_insert_design": "Sisip Reka Bentuk", + "cmd.component_links": "Senarai Pautan", + "cmd.component_list": "Senarai Komponen", + "cmd.component_move_bodies": "Alih Jasad ke Komponen", + "cmd.component_move_sketches": "Alih Lakaran ke Komponen", + "cmd.component_paste_new": "Tampal Baharu", + "cmd.component_properties": "Sifat Fizikal Komponen", + "cmd.component_rename": "Tukar Nama Komponen", + "cmd.component_revert_position": "Kembalikan Kedudukan", + "cmd.component_unlock": "Buka Kunci Kandungan", + "cmd.component_update_links": "Kemas Kini Pautan", + "cmd.config_activate": "Aktifkan Konfigurasi", + "cmd.config_column": "Lajur Konfigurasi", + "cmd.config_configure": "Konfigurasikan", + "cmd.config_preview": "Pratonton Konfigurasi", + "cmd.config_row": "Baris Konfigurasi", + "cmd.config_rule": "Peraturan Konfigurasi", + "cmd.config_rules": "Peraturan Konfigurasi", + "cmd.config_table": "Paparkan Jadual Konfigurasi", + "cmd.construct_axis_edge": "Paksi Melalui Tepi", + "cmd.construct_axis_normal_to_face": "Paksi Serenjang dengan Muka", + "cmd.construct_axis_through_cylinder": "Paksi Melalui Silinder/Kon/Torus", + "cmd.construct_axis_two_planes": "Paksi Melalui Dua Satah", + "cmd.construct_axis_two_points": "Paksi Melalui Dua Titik", + "cmd.construct_plane_along_path": "Satah Sepanjang Laluan", + "cmd.construct_plane_midplane": "Satah Tengah", + "cmd.construct_plane_perpendicular": "Satah Serenjang", + "cmd.construct_plane_tangent": "Satah Tangen", + "cmd.construct_plane_three_points": "Satah Melalui Tiga Titik", + "cmd.construct_plane_two_edges": "Satah Melalui Dua Tepi", + "cmd.construct_point_along_path": "Titik Sepanjang Laluan", + "cmd.construct_point_center": "Titik di Pusat Bulatan/Sfera/Torus", + "cmd.construct_point_edge_plane": "Titik pada Tepi dan Satah", + "cmd.construct_point_three_planes": "Titik Melalui Tiga Satah", + "cmd.construct_point_two_edges": "Titik Melalui Dua Tepi", + "cmd.construct_point_vertex": "Titik pada Bucu", + "cmd.contact_check": "Semak Sentuhan", + "cmd.contact_create": "Set Sentuhan Baharu", + "cmd.contact_disable_all": "Nyahaktifkan Sentuhan", + "cmd.contact_edit": "Sunting Set Sentuhan", + "cmd.contact_enable_all": "Aktifkan Semua Sentuhan", + "cmd.contact_enable_sets": "Aktifkan Set Sentuhan", + "cmd.contact_list": "Senarai Set Sentuhan", + "cmd.diagnostics_crash_report": "Laporan Ranap", + "cmd.diagnostics_crash_reports": "Laporan Ranap", + "cmd.diagnostics_crash_reports_clear": "Padam Laporan Ranap", + "cmd.diagnostics_crash_test": "Ujian Ranap", + "cmd.doc_recover": "Pulihkan Reka Bentuk", + "cmd.doc_recovery_discard": "Buang Reka Bentuk Dipulihkan", + "cmd.doc_recovery_list": "Reka Bentuk Boleh Dipulihkan", + "cmd.document_inspect": "Periksa Reka Bentuk", + "cmd.document_metadata": "Sifat Reka Bentuk", + "cmd.document_metadata_remove": "Buang Sifat Reka Bentuk", + "cmd.document_metadata_set": "Ubah Sifat Reka Bentuk", + "cmd.document_units": "Ubah Unit Reka Bentuk", + "cmd.edit_checkpoint": "Titik Semak", + "cmd.edit_restore_checkpoint": "Pulihkan Titik Semak", + "cmd.engine_commands": "Senarai Arahan", + "cmd.explode_create": "Pandangan Terlerai", + "cmd.explode_delete": "Padam Pandangan Terlerai", + "cmd.explode_list": "Senarai Pandangan Terlerai", + "cmd.explode_show": "Papar Pandangan Terlerai", + "cmd.expr_evaluate": "Nilaikan Ungkapan", + "cmd.face_delete": "Padam Muka", + "cmd.file_export": "Eksport", + "cmd.file_insert_mesh": "Sisip Mesh", + "cmd.file_insert_step": "Sisip STEP", + "cmd.file_save_mesh": "Simpan sebagai Mesh", + "cmd.file_slicers": "Penghiris Terpasang", + "cmd.inspect_accessibility": "Analisis Kebolehcapaian", + "cmd.inspect_center_of_mass": "Pusat Jisim", + "cmd.inspect_clearance": "Kelegaan", + "cmd.inspect_compare": "Bandingkan Jasad", + "cmd.inspect_continuity": "Analisis Keselanjaran", + "cmd.inspect_curvature_comb": "Analisis Sisir Kelengkungan", + "cmd.inspect_curvature_map": "Analisis Peta Kelengkungan", + "cmd.inspect_draft": "Analisis Sudut Draf", + "cmd.inspect_environment_map": "Analisis Peta Persekitaran", + "cmd.inspect_interference": "Pertindihan", + "cmd.inspect_isocurve": "Analisis Isolengkung", + "cmd.inspect_minimum_radius": "Analisis Jejari Minimum", + "cmd.inspect_silhouette": "Siluet", + "cmd.inspect_zebra": "Analisis Jalur Zebra", + "cmd.joint_as_built": "Sendi Sedia Ada", + "cmd.joint_cam": "Sesondol", + "cmd.joint_create": "Sendi", + "cmd.joint_delete": "Padam Sendi", + "cmd.joint_drive": "Gerakkan Sendi", + "cmd.joint_edit": "Sunting Sendi", + "cmd.joint_gear": "Gear", + "cmd.joint_limits": "Had Sendi", + "cmd.joint_list": "Senarai Sendi", + "cmd.joint_motion_link": "Pautan Gerakan", + "cmd.joint_origin": "Titik Asal Sendi", + "cmd.joint_rack_pinion": "Rak dan Pinan", + "cmd.joint_reach": "Capai Titik", + "cmd.joint_rigid_group": "Kumpulan Tegar", + "cmd.joint_screw": "Skru", + "cmd.joint_solve": "Selesaikan Sendi", + "cmd.library_apply": "Guna Item Koleksi Setempat", + "cmd.library_export": "Eksport Koleksi Reka Bentuk", + "cmd.library_inspect": "Periksa Koleksi Setempat", + "cmd.material_assign": "Bahan Fizikal", + "cmd.material_create": "Bahan Fizikal Baharu", + "cmd.material_delete": "Padam Bahan Fizikal", + "cmd.material_edit": "Sunting Bahan Fizikal", + "cmd.material_list": "Senarai Bahan", + "cmd.material_properties_directional": "Modulus Keanjalan Berarah", + "cmd.material_properties_validate": "Sahkan Data Bahan Fizikal", + "cmd.mesh_convert": "Tukar Mesh", + "cmd.model_edges": "Senarai Tepi", + "cmd.model_faces": "Senarai Muka", + "cmd.model_threads": "Senarai Bebenang", + "cmd.motion_delete": "Padam Kajian Gerakan", + "cmd.motion_export": "Eksport Kajian Gerakan", + "cmd.motion_export_animation": "Eksport Animasi Gerakan", + "cmd.motion_interference": "Pertindihan Gerakan", + "cmd.motion_list": "Senarai Kajian Gerakan", + "cmd.motion_play": "Mainkan Kajian Gerakan", + "cmd.motion_plot": "Plot Kajian Gerakan", + "cmd.motion_study": "Kajian Gerakan", + "cmd.motion_trace": "Jejak Gerakan", + "cmd.motion_trace_keep": "Kekalkan Jejak Gerakan", + "cmd.occurrence_copy": "Tampal (Salinan)", + "cmd.occurrence_ground": "Tetapkan", + "cmd.occurrence_move": "Alih Salinan", + "cmd.occurrence_properties": "Sifat Fizikal Salinan", + "cmd.parameters_add": "Tambah Parameter Pengguna", + "cmd.parameters_change": "Ubah Parameter", + "cmd.parameters_comment": "Tambah Ulasan Parameter", + "cmd.parameters_complete": "Lengkapkan Ungkapan", + "cmd.parameters_delete": "Padam Parameter", + "cmd.parameters_export": "Eksport Parameter", + "cmd.parameters_favorite": "Tanda Parameter Kegemaran", + "cmd.parameters_graph": "Graf Parameter", + "cmd.parameters_import": "Import Parameter", + "cmd.parameters_list": "Senarai Parameter", + "cmd.parameters_move": "Alih Parameter", + "cmd.parameters_rename": "Tukar Nama Parameter", + "cmd.parameters_users": "Rujukan Parameter", + "cmd.parts_fastener": "Sisip Pengikat", + "cmd.parts_insert": "Sisip Bahagian", + "cmd.parts_library": "Bahagian Piawai", + "cmd.parts_resize": "Ubah Saiz Bahagian", + "cmd.plastic_assign_rule": "Tetapkan Peraturan Plastik", + "cmd.plastic_boss": "Bonggol", + "cmd.plastic_lip": "Bibir", + "cmd.plastic_manage_rules": "Urus Peraturan Plastik", + "cmd.plastic_rest": "Penyokong", + "cmd.plastic_rules": "Senarai Peraturan Plastik", + "cmd.plastic_snap_fit": "Sambungan Sentap", + "cmd.render_backends": "Enjin Render", + "cmd.render_cancel": "Batal Render", + "cmd.render_export": "Eksport Imej Render", + "cmd.render_preflight": "Semak Permintaan Render", + "cmd.render_scene": "Periksa Adegan Render", + "cmd.render_settings_apply": "Gunakan Kamera Render", + "cmd.render_settings_get": "Tetapan Render", + "cmd.render_settings_set": "Simpan Tetapan Render", + "cmd.render_start": "Render Imej", + "cmd.render_status": "Kemajuan Render", + "cmd.select_clear": "Kosongkan Pilihan", + "cmd.sheet_convert": "Tukar kepada Logam Kepingan", + "cmd.sheet_export_bend_table": "Eksport Jadual Lenturan", + "cmd.sheet_export_dxf": "Eksport Bentangan Rata sebagai DXF", + "cmd.sheet_flange": "Bebibir", + "cmd.sheet_flat_pattern": "Cipta Bentangan Rata", + "cmd.sheet_fold": "Lipat", + "cmd.sheet_hem": "Kelim", + "cmd.sheet_manage_rules": "Peraturan Logam Kepingan", + "cmd.sheet_perforate": "Tebuk", + "cmd.sheet_refold": "Lipat Semula", + "cmd.sheet_rules": "Senarai Peraturan Logam Kepingan", + "cmd.sheet_unfold": "Buka Lipatan", + "cmd.sketch_arc_center_point": "Lengkok Titik Pusat", + "cmd.sketch_arc_tangent": "Lengkok Tangen", + "cmd.sketch_arc_three_point": "Lengkok 3 Titik", + "cmd.sketch_auto_constrain": "Kekangan Automatik", + "cmd.sketch_auto_constrain_from_datum": "Kekangan Automatik daripada Datum", + "cmd.sketch_auto_project": "Unjur Tepi Rujukan secara Automatik", + "cmd.sketch_blend_curve": "Lengkung Peralihan", + "cmd.sketch_chain": "Rantaian", + "cmd.sketch_chamfer_distance_angle": "Serong Jarak dan Sudut", + "cmd.sketch_chamfer_equal_distance": "Serong Jarak Sama", + "cmd.sketch_chamfer_two_distance": "Serong Dua Jarak", + "cmd.sketch_circle_center": "Bulatan Pusat dan Diameter", + "cmd.sketch_circle_three_point": "Bulatan 3 Titik", + "cmd.sketch_circle_three_tangent": "Bulatan 3 Tangen", + "cmd.sketch_circle_two_point": "Bulatan 2 Titik", + "cmd.sketch_circle_two_tangent": "Bulatan 2 Tangen", + "cmd.sketch_constrainer": "Penetap Kekangan Lakaran", + "cmd.sketch_constraint_fix": "Tetap/Lepas", + "cmd.sketch_constraint_midpoint": "Titik Tengah", + "cmd.sketch_construction": "Biasa/Binaan", + "cmd.sketch_copy": "Salin Entiti Lakaran", + "cmd.sketch_cut": "Potong Entiti Lakaran", + "cmd.sketch_delete": "Padam Entiti Lakaran", + "cmd.sketch_dimension_text": "Alih Teks Dimensi", + "cmd.sketch_drag": "Seret Geometri Lakaran", + "cmd.sketch_drag_end": "Tamatkan Seretan Lakaran", + "cmd.sketch_draw_dimensioned": "Lukis Geometri Lakaran Berdimensi", + "cmd.sketch_edit": "Sunting Lakaran", + "cmd.sketch_edit_text": "Sunting Teks", + "cmd.sketch_export_dxf": "Simpan sebagai DXF", + "cmd.sketch_finish_auto_constrain": "Tamatkan dengan Kekangan Automatik", + "cmd.sketch_fit_curves_to_section": "Padankan Lengkung pada Keratan Mesh", + "cmd.sketch_glyphs": "Glif Kekangan", + "cmd.sketch_include_3d": "Sertakan Geometri 3D", + "cmd.sketch_infinite": "Garis Tak Terhingga", + "cmd.sketch_insert_dxf": "Sisip DXF", + "cmd.sketch_insert_svg": "Sisip SVG", + "cmd.sketch_inspect": "Periksa Lakaran", + "cmd.sketch_intersection_curve": "Lengkung Persilangan", + "cmd.sketch_isoparametric_curve": "Lengkung Isoparametrik", + "cmd.sketch_line3d": "Garis 3D", + "cmd.sketch_line_midpoint": "Garis Titik Tengah", + "cmd.sketch_loose_ends": "Hujung Bebas", + "cmd.sketch_loose_ends_tie": "Ikat Hujung Bebas", + "cmd.sketch_move": "Alih/Salin Entiti Lakaran", + "cmd.sketch_move3d": "Alih Titik 3D", + "cmd.sketch_move_point": "Seret Titik Lakaran", + "cmd.sketch_offset_break": "Putuskan Perkaitan Ofset", + "cmd.sketch_options": "Pilihan Palet Lakaran", + "cmd.sketch_paste": "Tampal Entiti Lakaran", + "cmd.sketch_point3d": "Titik 3D", + "cmd.sketch_polygon_circumscribed": "Poligon di Luar Bulatan", + "cmd.sketch_polygon_edge": "Poligon Tepi", + "cmd.sketch_polygon_inscribed": "Poligon di Dalam Bulatan", + "cmd.sketch_project_to_surface": "Unjur ke Permukaan", + "cmd.sketch_rectangle_center": "Segi Empat Tepat Berpusat", + "cmd.sketch_rectangle_rounded": "Segi Empat Tepat Berbucu Bulat", + "cmd.sketch_rectangle_three_point": "Segi Empat Tepat 3 Titik", + "cmd.sketch_rectangle_two_point": "Segi Empat Tepat 2 Titik", + "cmd.sketch_redefine": "Takrifkan Semula Satah Lakaran", + "cmd.sketch_slot_arc_center": "Slot Lengkok Titik Pusat", + "cmd.sketch_slot_arc_three_point": "Slot Lengkok Tiga Titik", + "cmd.sketch_slot_center_point": "Slot Titik Pusat", + "cmd.sketch_slot_center_to_center": "Slot Pusat ke Pusat", + "cmd.sketch_slot_overall": "Slot Keseluruhan", + "cmd.sketch_snap": "Pengesanan Lekapan", + "cmd.sketch_solve": "Selesaikan Lakaran", + "cmd.sketch_spline3d": "Splin 3D", + "cmd.sketch_spline_control_point": "Splin Titik Kawalan", + "cmd.sketch_spline_control_point_5": "Splin Titik Kawalan (Darjah 5)", + "cmd.sketch_spline_fit_point": "Splin Titik Padanan", + "cmd.sketch_spun_profile": "Profil Putaran", + "cmd.sketch_toggle_driven": "Togol Dimensi Dipacu", + "cmd.solid_align": "Jajarkan", + "cmd.solid_boundary_fill": "Isi Sempadan", + "cmd.solid_bounding_solid": "Pepejal Pembatas", + "cmd.solid_emboss": "Timbulkan", + "cmd.solid_move": "Alih/Salin", + "cmd.solid_offset_face": "Ofset Muka", + "cmd.solid_press_pull": "Tekan Tarik", + "cmd.solid_remove": "Buang", + "cmd.solid_replace_face": "Ganti Muka", + "cmd.solid_rib": "Rusuk", + "cmd.solid_split_face": "Belah Muka", + "cmd.solid_web": "Pengukuh", + "cmd.surface_blend": "Permukaan Peralihan", + "cmd.surface_boundary": "Permukaan Sempadan", + "cmd.surface_extrude": "Penyemperitan Permukaan", + "cmd.surface_fair": "Licinkan Permukaan", + "cmd.surface_fillet": "Jejari Sudut Permukaan", + "cmd.surface_loft": "Loft Permukaan", + "cmd.surface_match": "Padankan Permukaan", + "cmd.surface_offset": "Ofset Permukaan", + "cmd.surface_patch": "Tampalan", + "cmd.surface_reverse_normal": "Songsangkan Normal", + "cmd.surface_revolve": "Putaran Permukaan", + "cmd.surface_ruled": "Permukaan Bergaris", + "cmd.surface_stitch": "Cantum", + "cmd.surface_sweep": "Sapuan Permukaan", + "cmd.surface_thicken": "Tebalkan", + "cmd.surface_unstitch": "Lerai", + "cmd.surface_untrim": "Nyahpangkas", + "cmd.timeline_add": "Tambah Ciri yang Dirakam", + "cmd.timeline_compute_all": "Kira Semua", + "cmd.timeline_copy": "Salin Ciri", + "cmd.timeline_dependents": "Ciri Bergantung", + "cmd.timeline_export_script": "Eksport Skrip Arahan", + "cmd.timeline_inspect": "Periksa Ciri", + "cmd.timeline_paste": "Tampal Ciri", + "cmd.timeline_redefine": "Sunting Ciri", + "cmd.timeline_rename": "Tukar Nama", + "cmd.timeline_reorder": "Susun Semula Ciri", + "cmd.timeline_roll_to": "Alih Penanda Sejarah", + "cmd.timeline_rollback": "Alih Penanda Garis Masa", + "cmd.timeline_suppress": "Nyahaktifkan Ciri", + "cmd.view_apply": "Pulihkan Pandangan", + "cmd.view_delete": "Padam Pandangan", + "cmd.view_list": "Senarai Pandangan", + "cmd.view_navigate": "Navigasi Pandangan", + "cmd.view_rename": "Tukar Nama Pandangan", + "cmd.view_save": "Simpan Pandangan", + "command name": "nama arahan", + "coupling.gear_1": "Gear 1", + "coupling.gear_1_pick": "Gear 1 (tidak wajib)", + "coupling.gear_2": "Gear 2", + "coupling.gear_2_pick": "Gear 2 (tidak wajib)", + "coupling.internal": "Gear dalaman", + "coupling.needs_turn_and_slide": "perlu satu sendi putar dan satu sendi gelongsor", + "coupling.needs_turns": "memerlukan dua sendi yang berputar", + "coupling.not_round": "bukan muka bulat", + "coupling.nut": "Nat", + "coupling.picked": "dipilih", + "coupling.pinion": "Pinan", + "coupling.pinion_pick": "Pinan (tidak wajib)", + "coupling.pitch": "Pic", + "coupling.rack": "Rak", + "coupling.radius_1": "Jejari 1", + "coupling.radius_2": "Jejari 2", + "dialog.computing": "Mengira… {seconds} s", + "dialog.custom_axis": "↖ Paksi Tersuai", + "dialog.edit_title": "SUNTING {title}", + "dialog.select": "↖ Pilih", + "dialog.selected_count": "↖ {count} dipilih", + "dialog.selection_guidance": "Pilih input untuk diubah. Klik objek dipilih untuk nyahpilih; Ctrl/Cmd+klik juga menogol pilihan. Semak pratonton, kemudian tekan OK.", + "dialog.selection_step": "{step} daripada {total}: Pilih {input}", + "dialog.step": "Langkah", + "document.save_changes": "Simpan perubahan pada {name}?", + "document.unsaved_changes": "{name}: perubahan belum disimpan dan akan hilang jika tidak disimpan.", + "drive.stopped_by_contact": "Berhenti pada {value}: {a} akan menembusi {b}", + "drive.stopped_by_loop": "Berhenti pada {value}: gelung melalui {joint} tidak lagi dapat ditutup", + "drive.unconnected": "{part} tidak bergerak: tiada sambungan ke komponen tetap", + "dxf.cancel_wait": "Menunggu eksport berhenti…", + "dxf.cancelled": "Eksport DXF dibatalkan", + "dxf.cancelling": "Membatalkan eksport DXF", + "dxf.exporting": "Mengeksport DXF", + "dxf.invalid_tolerance": "Toleransi lengkung mestilah antara 0.0001 dan 1 mm.", + "dxf.progress.index": "Menyediakan permukaan (2/5)", + "dxf.progress.meshes": "Menyediakan mesh (1/5)", + "dxf.progress.occlusion": "Menentukan garis tersembunyi (4/5)", + "dxf.progress.projection": "Mengunjurkan geometri (3/5)", + "dxf.progress.write": "Menulis DXF (5/5)", + "dxf.tolerance": "Toleransi lengkung", + "dxf.tolerance_help": "Jasad kelihatan sahaja. Lengkung guna segmen lurus. Toleransi kecil lebih halus tetapi guna lebih masa dan memori.", + "expression, e.g. 25 mm": "ungkapan, cth. 25 mm", + "fits the face, e.g. M8": "padan dengan muka, cth. M8", + "from the rule": "daripada peraturan", + "home.documentation": "Dokumentasi", + "home.in_this_browser": "dalam pelayar ini", + "home.missing": "tiada", + "home.open": "Buka…", + "home.opened_days_ago": "Dibuka {count} hari lalu", + "home.opened_hours_ago": "Dibuka {count} jam lalu", + "home.opened_just_now": "Baru dibuka", + "home.opened_minutes_ago": "Dibuka {count} minit lalu", + "home.opening": "membuka…", + "home.recent": "Terkini", + "home.report_issue": "Laporkan Isu", + "home.samples": "Contoh", + "home.whats_new": "Apa yang baharu", + "install.button_tip": "Pasang SolidCraft: tetingkap sendiri dan boleh guna di luar talian", + "install.dock_1": "Pilih File › Add to Dock.", + "install.dock_2": "Klik Add.", + "install.dock_after": "SolidCraft dibuka dari Dock dalam tetingkap sendiri dan boleh guna di luar talian.", + "install.done": "Selesai", + "install.home_screen_1": "Ketik Share (dalam menu … jika tiada pada bar alat).", + "install.home_screen_2": "Pilih Add to Home Screen.", + "install.home_screen_3": "Ketik Add.", + "install.home_screen_after": "SolidCraft dibuka dari ikon Skrin Utama tanpa bar alat Safari dan boleh guna di luar talian.", + "install.menu": "Pasang aplikasi…", + "install.steps_intro": "Safari memasang aplikasi web melalui menunya sendiri:", + "install.title": "Pasang SolidCraft", + "joint.from_bodies_hint": "Setiap jasad dipilih masuk ke komponen baharu tanpa berubah kedudukan.", + "joint.one_body": "Kedua-dua pilihan berada pada {body}. Buat pilihan kedua pada bahagian lain.", + "joint.one_component": "Jasad ini dalam satu komponen: {bodies}. Sendi menggerakkan satu komponen berbanding yang lain, jadi setiap bahagian perlu komponen sendiri.", + "motion.checked_to": "Semakan hanya selesai hingga langkah {step} kerana had kerja pengiraan telah dicapai", + "motion.collision": "{a} · {b}: langkah {steps}", + "motion.duration_hint": "saat (kosong: setiap langkah)", + "motion.no_collisions": "Tiada perlanggaran sepanjang kajian", + "nav.touchpad.help": "Tahan Shift dan gerakkan kursor untuk sorot; Alt/Option untuk orbit. Tidak perlu butang tetikus. Tatal menegak untuk zum.", + "nav.touchpad.label": "Pad sentuh", + "nav.touchpad.orbit": "Orbit (tahan Alt/Option dan gerak; tanpa klik)", + "nav.touchpad.pan": "Sorot (tahan Shift dan gerak; tanpa klik)", + "nav.touchpad.scroll": "Pad sentuh menggunakan tatal menegak untuk zum. Tetapan sorot dua jari anda dikekalkan untuk pratetap lain.", + "nav.touchpad.zoom": "Zum (tatal menegak atau cubit)", + "needs two joints": "memerlukan dua sendi", + "new configuration": "konfigurasi baharu", + "new name": "nama baharu", + "new parameter": "parameter baharu", + "no interference": "tiada pertindihan", + "no joint that moves yet": "belum ada sendi yang bergerak", + "no picture": "tiada gambar", + "pattern.alignment_2": "Penjajaran 2", + "pattern.alignment_hint": "Bilangan termasuk asal. Tengah seimbangkan salinan; Balik pilih sisi lebih untuk bilangan genap.", + "pattern.direction_1": "Arah 1", + "pattern.direction_2": "Arah 2", + "pattern.flip_direction": "Balikkan arah", + "pick a hole to seat it, or OK places it at the origin": "pilih lubang, atau tekan OK untuk letak di titik asal", + "pick one or two vertices, edges or faces": "pilih satu atau dua bucu, tepi atau muka", + "render.background": "Latar belakang adegan", + "render.fit": "Muatkan Produk", + "render.image_cancel": "Batal Render", + "render.image_cancelled": "Render dibatalkan", + "render.image_cancelling": "Membatalkan", + "render.image_check": "Semak Permintaan Render", + "render.image_completed": "Imej sedia untuk dieksport", + "render.image_encoding": "Mengekod PNG", + "render.image_export": "Eksport PNG", + "render.image_failed": "Render gagal", + "render.image_height": "Ketinggian", + "render.image_help": "Imej pratonton CPU · PNG · ketelusan dianggarkan", + "render.image_overwrite": "Ganti fail sedia ada", + "render.image_preparing": "Menyediakan imej", + "render.image_queued": "Menunggu render", + "render.image_reduce": "Cuba imej lebih kecil atau adegan lebih ringkas.", + "render.image_running": "Menghasilkan imej", + "render.image_stale": "Imej ini menggunakan adegan yang dirakam sebelum perubahan terbaharu.", + "render.image_start": "Mulakan Render", + "render.image_supported": "Permintaan render disokong; baris gilir dan peruntukan memori akan disemak semula apabila render bermula.", + "render.image_title": "Render Imej", + "render.image_too_large": "Melebihi had: 4096 piksel setiap sisi, 4,194,304 piksel keseluruhan.", + "render.image_transparent": "Latar belakang telus", + "render.image_unknown": "Status render tidak tersedia", + "render.image_use_largest": "Gunakan saiz terbesar pada nisbah aspek ini:", + "render.image_width": "Lebar", + "render.navigation_help": "Kamera seperti Reka Bentuk (Tetapan › Navigasi). Simpan Persediaan merekod kamera semasa.", + "render.opaque_image_summary": "Pratonton PNG · PBR legap · ketelusan campuran", + "render.opaque_preview_help": "PBR legap dan warna ringkas; ketelusan campuran. Pembiasan, HDRI dan render akhir belum tersedia.", + "render.perspective": "Kamera perspektif", + "render.preview": "Pratonton bersepadu", + "render.preview_help": "Lorekan raster dan ketelusan campuran. Pembiasan, HDRI dan render akhir belum tersedia.", + "render.reload_settings": "Muat Semula Tetapan Tersimpan", + "render.restore_camera": "Pulihkan Kamera Tersimpan", + "render.return_design": "Kembali ke Reka Bentuk", + "render.save_setup": "Simpan Persediaan", + "render.setup_name": "Nama persediaan", + "render.unavailable_preview": "Persediaan ini menggunakan profil pratonton yang tidak tersedia.", + "render.unsaved": "Perubahan pratonton belum disimpan", + "render.use_preview": "Gunakan Pratonton Bersepadu", + "sample.bracket.about": "Bebibir asas dengan bebibir tepi dan kelim mengikut peraturan 2 mm", + "sample.bracket.name": "Pendakap Logam Kepingan", + "sample.enclosure.about": "Kotak berongga dengan bibir, bonggol skru, penyokong dan sambungan sentap", + "sample.enclosure.name": "Sarung Plastik", + "sample.flange.about": "Hab dan bebibir dengan corak membulat yang dikawal oleh parameter", + "sample.flange.name": "Bebibir Berbolt", + "sample.hinge.about": "Dua komponen dengan sendi putar yang digerakkan hingga 60°", + "sample.hinge.name": "Pemasangan Engsel", + "sample.plate.about": "Plat parametrik dengan jejari sudut, lubang dan bonggol berlubang", + "sample.plate.name": "Plat Contoh", + "sample.vents.about": "Corak slot segi empat tepat: baris, lajur dan pic sebagai parameter", + "sample.vents.name": "Plat Pengudaraan", + "settings.display_quality_note": "Tahap halus melicinkan muka dan tepi melengkung, tetapi mesh lebih lambat disiapkan. Hanya paparan berubah, bukan reka bentuk atau eksport.", + "settings.frame_rate_note": "Papar bingkai sesaat di kanan bawah. Jika diaktifkan, pandangan dilukis semula tanpa henti.", + "settings.measure_axis_distances": "Papar jarak X/Y/Z", + "settings.measure_axis_distances_help": "Papar jarak paksi dunia X/Y/Z bersama jarak keseluruhan semasa Ukur dibuka.", + "settings.msaa_applies_on_restart": "Antialias digunakan apabila SolidCraft dimulakan semula", + "settings.msaa_reset": "{setting}: {requested}× tidak disokong oleh peranti grafik ini; kini {reset}× (disokong: {supported}).", + "settings.msaa_unsupported": "Tidak disokong oleh peranti grafik ini", + "settings.reset_intro": "Tetapan ini menghalang SolidCraft bermula pada komputer ini, jadi telah diubah:", + "settings.reset_title": "Tetapan telah diubah", + "settings.supersampling_note": "Lukis pada resolusi tinggi, kemudian kecilkan: tepi, garis dan grid lebih licin pada skrin bawah 4K. Lebih masa GPU: kira-kira 2.25× piksel pada 1.5× dan 4× pada 2×.", + "sketch.degrees_of_freedom": "{count} darjah kebebasan", + "sketch.draw_curves": "Lukis sebagai {linetype}", + "sketch.make_selection": "Tukar pilihan kepada {linetype}", + "sketch.open_ends": "Terbuka {count}", + "sketch.untied_ends": "Tak terikat {count}", + "sketch_text.align_center": "Tengah", + "sketch_text.align_left": "Kiri", + "sketch_text.align_right": "Kanan", + "sketch_text.bold": "Tebal", + "sketch_text.builtin_font": "{family} (terbina dalam)", + "sketch_text.font_search": "Cari fon", + "sketch_text.italic": "Condong", + "sketch_text.loading_fonts": "Mencari fon yang dipasang…", + "sketch_text.on_path": "Teks mengikut laluan lengkung, yang menentukan kedudukannya", + "sketch_text.path_clear": "Pisahkan teks daripada lengkung", + "sketch_text.path_hint": "Lengkung lakaran yang akan diikuti teks: klik di sini, kemudian klik lengkung", + "sketch_text.use_font_file": "Gunakan fail fon {path}", + "the parts library is not available": "koleksi bahagian tidak tersedia", + "thread.automatic_size": "Saiz automatik", + "thread.designation": "Penamaan", + "thread.iso_metric": "Metrik ISO", + "thread.select_size": "Pilih saiz", + "timeline.group": "Folder Ciri Baharu", + "timeline.move_many": "Alih Item Garis Masa", + "timeline.move_to_group": "Alih Ciri ke Folder", + "timeline.rename_group": "Tukar Nama Folder Ciri", + "timeline.reorder_many": "Susun Semula Ciri", + "timeline.ungroup": "Buang Folder Ciri", + "to the next face": "ke muka seterusnya", + "toolbar.image": "IMEJ", + "toolbar.render": "RENDER", + "toolbar.render_scene": "ADEGAN", + "trace.points": "{count} titik sepanjang laluan", + "trace.stopped_by_contact": "Berakhir pada sampel {sample}: {a} akan menembusi {b}", + "trace.stopped_by_loop": "Berakhir pada sampel {sample}: gelung melalui {joint} tidak lagi dapat ditutup", + "ui.1_degree_of_freedom": "1 darjah kebebasan", + "ui.3d_mouse_speed": "Kelajuan tetikus 3D", + "ui.3d_mouse_windows": "Tetikus 3D", + "ui.3d_sketch": "Lakaran 3D", + "ui.about": "Tentang", + "ui.activate": "Aktifkan", + "ui.active_component": "Komponen aktif", + "ui.agent_chat": "Sembang ejen", + "ui.agent_chat_allow": "Benarkan", + "ui.agent_chat_allowed": "Dibenarkan", + "ui.agent_chat_answered": "Jawapan: {option}", + "ui.agent_chat_approval": "Benarkan ejen melakukan ini?", + "ui.agent_chat_attach_view": "Lampirkan paparan", + "ui.agent_chat_attach_view_tip": "Hantar imej pandangan semasa bersama mesej", + "ui.agent_chat_auth_agent": "Log masuk dengan {name}", + "ui.agent_chat_auth_env": "Tetapkan {vars} dalam persekitaran, kemudian mula semula SolidCraft.", + "ui.agent_chat_auth_needed": "Ejen memerlukan anda log masuk melalui ejen itu sendiri. SolidCraft tidak dapat melihat kata laluan atau kunci anda.", + "ui.agent_chat_auth_none": "Ejen tidak menyediakan kaedah log masuk di sini. Ikut arahan dalam dokumentasi ejen untuk log masuk.", + "ui.agent_chat_auth_retry": "Sudah log masuk: sambung semula", + "ui.agent_chat_auth_terminal": "Jalankan arahan ini dalam terminal, kemudian tekan Sambung semula:", + "ui.agent_chat_auth_title": "Log masuk ke ejen", + "ui.agent_chat_cancel": "Batal", + "ui.agent_chat_changes": "{n} perubahan, satu Buat Asal", + "ui.agent_chat_changes_of": "{n}/{limit} perubahan", + "ui.agent_chat_close": "Tutup", + "ui.agent_chat_command": "Arahan ejen", + "ui.agent_chat_connect": "Sambung", + "ui.agent_chat_copy": "Salin", + "ui.agent_chat_custom_hint": "Program yang guna Agent Client Protocol melalui stdin dan stdout. Dijalankan tanpa shell.", + "ui.agent_chat_denied": "Ditolak", + "ui.agent_chat_deny": "Tolak", + "ui.agent_chat_desktop_only": "Sembang ejen memerlukan aplikasi desktop.", + "ui.agent_chat_detecting": "Mencari ejen…", + "ui.agent_chat_dock_left": "Letakkan di kiri", + "ui.agent_chat_dock_right": "Letakkan di kanan", + "ui.agent_chat_edit": "Sunting", + "ui.agent_chat_exited": "Ejen telah berhenti.", + "ui.agent_chat_failed_start": "Ejen tidak dapat dimulakan: {error}", + "ui.agent_chat_intro": "Sembang dengan ejen pengekodan biasa anda atau titik akhir model pilihan. Ejen mengubah reka bentuk melalui alat SolidCraft; perubahan dipaparkan terus dan boleh dibatalkan sekali bagi setiap mesej. Tetapkan kebenaran di Tetapan > AI.", + "ui.agent_chat_key_in_env": "kunci tersedia", + "ui.agent_chat_left": "Kiri", + "ui.agent_chat_limit": "Ejen telah mencapai had {limit} perubahan untuk satu mesej. Hantar mesej lain untuk meneruskan.", + "ui.agent_chat_minimize": "Kecilkan kepada bar", + "ui.agent_chat_model_tip": "Model yang digunakan oleh ejen. Pilihan anda disimpan untuk ejen ini.", + "ui.agent_chat_new": "Sembang baharu", + "ui.agent_chat_new_confirm": "Mulakan sembang baharu? Sembang semasa akan dikosongkan.", + "ui.agent_chat_new_yes": "Sembang baharu", + "ui.agent_chat_no_cli": "solidcraft-cli tidak ditemui dalam folder aplikasi, jadi ejen tidak dapat mengakses reka bentuk.", + "ui.agent_chat_no_control": "Titik akhir sembang ejen gagal dimulakan, jadi ejen tidak dapat mengakses reka bentuk.", + "ui.agent_chat_no_images": "Ejen ini tidak menerima imej", + "ui.agent_chat_none_found": "Tiada ejen pengekodan. Pasang satu ejen di bawah, kemudian tekan Muat Semula:", + "ui.agent_chat_none_found_short": "Tiada ejen ditemui", + "ui.agent_chat_not_installed": "Tidak dipasang", + "ui.agent_chat_not_signed_in": "belum log masuk", + "ui.agent_chat_permission": "Benarkan ejen jalankan: {title}", + "ui.agent_chat_pick": "Ejen", + "ui.agent_chat_placeholder": "Minta ejen mengubah reka bentuk…", + "ui.agent_chat_placeholder_busy": "Giliran mesej selepas ejen selesai (Ctrl+Enter: hantar terus)", + "ui.agent_chat_privacy": "Data hanya dihantar kepada ejen yang anda jalankan, melalui akaun anda sendiri.", + "ui.agent_chat_privacy_note": "SolidCraft tidak menghantar data. Ejen berhubung dengan perkhidmatannya melalui akaun anda. SolidCraft tidak melihat atau menyimpan kunci atau kata laluan.", + "ui.agent_chat_queue": "Hantar Nanti", + "ui.agent_chat_queue_full": "Terlalu banyak mesej menunggu: buang satu atau tunggu ejen selesai.", + "ui.agent_chat_queued": "Menunggu", + "ui.agent_chat_queued_stopped": "Menunggu (dihentikan, belum dihantar)", + "ui.agent_chat_refresh": "Muat Semula", + "ui.agent_chat_refused": "Tindakan ejen tidak dibenarkan: {reason}", + "ui.agent_chat_remove": "Buang daripada baris gilir", + "ui.agent_chat_right": "Kanan", + "ui.agent_chat_save": "Simpan", + "ui.agent_chat_send": "Hantar", + "ui.agent_chat_send_now": "Hantar terus", + "ui.agent_chat_send_now_tip": "Hentikan langkah semasa ejen dan hantar mesej ini selepas itu (Ctrl+Enter)", + "ui.agent_chat_side": "Sisi sembang ejen", + "ui.agent_chat_signed_in": "sudah log masuk", + "ui.agent_chat_state_auth": "Perlu log masuk", + "ui.agent_chat_state_busy": "Bekerja…", + "ui.agent_chat_state_exited": "Ejen dihentikan", + "ui.agent_chat_state_off": "Tidak disambungkan", + "ui.agent_chat_state_ready": "Sedia", + "ui.agent_chat_state_starting": "Memulakan…", + "ui.agent_chat_stop": "Hentikan", + "ui.agent_chat_stop_tip": "Hentikan ejen dan semua yang dimulakannya", + "ui.agent_chat_stop_turn_tip": "Hentikan ejen (Esc). Mesej dalam baris gilir kekal di situ.", + "ui.agent_chat_turn_limit": "Perubahan setiap mesej", + "ui.agent_chat_undo_changes": "Batalkan perubahan ini", + "ui.agent_chat_undo_label": "Sembang ejen: {message}", + "ui.agent_chat_undone": "(dibatalkan)", + "ui.agent_chat_view_attached": "Paparan dilampirkan", + "ui.agent_cursor": "Kursor ejen", + "ui.agent_cursor_speed": "Kelajuan kursor ejen", + "ui.ai_add": "Tambah", + "ui.ai_add_agent": "Tambah ejen…", + "ui.ai_add_agent_title": "Tambah ejen", + "ui.ai_add_api": "API serasi OpenAI", + "ui.ai_add_custom": "Arahan tersuai", + "ui.ai_add_installed": "Ejen yang dipasang", + "ui.ai_add_installed_note": "Tambah tetapan tersuai untuk ejen yang dipasang, contohnya untuk menggunakan argumen lain. Ejen yang dipasang sudah disenaraikan secara automatik.", + "ui.ai_added": "ditambah", + "ui.ai_agent_mode_tip": "Mod ejen menentukan penggunaan alatnya sendiri (shell dan suntingan fail). Alat SolidCraft mengikut kebenaran dalam Tetapan > AI.", + "ui.ai_agents": "Ejen", + "ui.ai_always_allow": "Sentiasa benarkan", + "ui.ai_always_allow_tip": "Benarkan {tool} untuk ejen ini mulai sekarang, tanpa bertanya", + "ui.ai_always_allowed": "Sentiasa dibenarkan", + "ui.ai_always_allowed_none": "Belum ada. Tindakan yang anda pilih \"Sentiasa benarkan\" dalam sembang disenaraikan di sini.", + "ui.ai_auto_allowed": "Izin automatik: {title} ({why})", + "ui.ai_auto_mode": "tetapan kebenaran anda", + "ui.ai_auto_ours": "SolidCraft menyemak alatnya sendiri", + "ui.ai_auto_remembered": "anda memilih Sentiasa benarkan", + "ui.ai_bad_url": "Masukkan URL yang bermula dengan http:// atau https://", + "ui.ai_base_url": "URL asas", + "ui.ai_button": "AI", + "ui.ai_copy_suffix": "salinan", + "ui.ai_custom_url": "URL tersuai", + "ui.ai_default": "Lalai", + "ui.ai_http_busy": "titik akhir sibuk atau telah melebihi had; cuba lagi kemudian", + "ui.ai_http_key": "kunci ditolak oleh titik akhir: semak dalam Tetapan > AI", + "ui.ai_http_not_found": "titik akhir atau model tidak ditemui: semak URL asas dan nama model", + "ui.ai_key": "Kunci API", + "ui.ai_key_hint": "tidak wajib; disimpan dalam rantai kunci sistem", + "ui.ai_key_needs_https": "Kunci hanya dihantar melalui HTTPS, atau ke komputer ini.", + "ui.ai_key_note": "Disimpan dalam rantai kunci sistem, bukan dalam tetapan SolidCraft. Biarkan kosong untuk pelayan setempat.", + "ui.ai_keychain_error": "Rantai kunci sistem menolak: {error}", + "ui.ai_mode_all": "Benarkan semua", + "ui.ai_mode_all_note": "Tiada permintaan izin. Laporan ranap masih disekat dan had folder kekal.", + "ui.ai_mode_all_warning": "Ejen boleh simpan, tulis ganti, eksport dan ganti reka bentuk tanpa izin. Guna hanya dengan ejen dipercayai, pada reka bentuk yang sudah disimpan.", + "ui.ai_mode_ask": "Tanya setiap kali", + "ui.ai_mode_ask_note": "Pilih Benarkan sebelum ejen boleh mengubah reka bentuk atau melakukan tindakan pada fail.", + "ui.ai_mode_edits": "Auto benarkan suntingan model", + "ui.ai_mode_edits_note": "Pemodelan dibenarkan terus; simpan, buka, eksport, tindakan fail lain atau pemadaman masih meminta izin.", + "ui.ai_mode_global": "Ikut tetapan atas", + "ui.ai_model": "Model", + "ui.ai_modes_scope": "Tetapan ini meliputi alat SolidCraft. Alat ejen sendiri (shell dan suntingan fail) mengikut mod ejen. Jika ejen menyediakan pilihan mod, anda boleh memilihnya di bahagian atas panel sembang.", + "ui.ai_name": "Nama", + "ui.ai_need_command": "Masukkan arahan untuk memulakan ejen", + "ui.ai_need_model": "Masukkan nama model", + "ui.ai_no_answer": "Ejen tidak menjawab dalam had masa", + "ui.ai_no_http": "Binaan ini tidak dapat mengakses titik akhir API", + "ui.ai_no_keychain": "Rantai kunci sistem tidak tersedia, jadi kunci tidak dapat disimpan. Pelayan setempat tanpa kunci masih berfungsi.", + "ui.ai_panel": "Panel", + "ui.ai_permissions": "Kebenaran", + "ui.ai_preset": "Pratetap", + "ui.ai_remove": "Buang", + "ui.ai_request_limit": "berhenti selepas 24 permintaan untuk satu mesej; hantar mesej lain untuk meneruskan", + "ui.ai_reset": "Set Semula", + "ui.ai_settings": "Tetapan AI…", + "ui.ai_show_features": "Papar ciri AI", + "ui.ai_show_features_note": "Panel sembang untuk ejen pengekodan atau titik akhir model pilihan mengubah reka bentuk terbuka. Jika dimatikan: tiada butang AI, pintasan, menu atau panel; tiada ejen dicari atau dimulakan.", + "ui.ai_switch_tip": "Tukar ejen untuk perbualan ini", + "ui.ai_test": "Uji", + "ui.ai_test_acp_ok": "Respons: {agent}", + "ui.ai_test_acp_tip": "Memulakan ejen untuk mencuba sambungan sesi, kemudian menutupnya semula", + "ui.ai_test_api_tip": "Meminta senarai model daripada titik akhir", + "ui.ai_test_no_model": "Disambung: {count} model, tiada {model}", + "ui.ai_test_ok": "Disambung: {count} model", + "ui.ai_testing": "Menguji…", + "ui.ai_tool_done": "selesai", + "ui.ai_tool_failed": "gagal", + "ui.ai_tool_running": "berjalan", + "ui.ai_tool_unfold": "Klik untuk melihat hasil yang diterima", + "ui.ai_tool_waiting": "menunggu", + "ui.ai_toolbar_button": "Papar butang pada bar alat", + "ui.ai_toolbar_button_note": "Butang AI di hujung kanan bar alat. Ctrl+Shift+A dan menu Pandangan masih membuka panel.", + "ui.ai_undo_tip": "Batalkan semua perubahan ejen bagi mesej ini dengan satu langkah Buat Asal", + "ui.all": "Semua", + "ui.analysis": "Analisis", + "ui.angle": "Sudut", + "ui.angle_decimals": "Perpuluhan sudut", + "ui.animateJoint": "Animasikan Sendi", + "ui.animate_view_changes": "Animasikan perubahan pandangan", + "ui.animation": "Animasi", + "ui.animation_speed": "Kelajuan animasi", + "ui.anti_aliasing": "Antialias", + "ui.apply": "Gunakan", + "ui.arc": "Lengkok", + "ui.assemble": "Pasang", + "ui.autosave_every": "Autosimpan setiap", + "ui.axes": "Paksi", + "ui.axis": "Paksi", + "ui.base_point": "Titik asas", + "ui.blocked": "Disekat", + "ui.bodies": "Jasad", + "ui.box": "Kotak", + "ui.break": "Putuskan", + "ui.calibrate": "Tentukur", + "ui.cancel": "Batal", + "ui.canvases": "Kanvas", + "ui.center": "Tengah", + "ui.centerline": "Garis tengah", + "ui.chain": "Rantaian", + "ui.chamfer": "Serong", + "ui.chamfer_type": "Jenis Serong", + "ui.change_workspace": "Tukar ruang kerja", + "ui.chord_length": "Panjang Perentas", + "ui.circle": "Bulatan", + "ui.circular_pattern": "Corak Membulat", + "ui.clear": "Kosongkan", + "ui.clear_recent": "Kosongkan Terkini", + "ui.clear_the_selection": "Kosongkan pilihan", + "ui.click_selects_whole_bodies": "Klik untuk memilih keseluruhan jasad", + "ui.click_then_press_key": "Klik, kemudian tekan kekunci baharu", + "ui.close": "Tutup", + "ui.coil": "Gegelung", + "ui.coincident": "Bertindih Tepat", + "ui.collapse": "Ringkaskan", + "ui.collinear": "Segaris", + "ui.colour_vision": "Penglihatan warna", + "ui.colour_vision_deutan": "Deutan", + "ui.colour_vision_deutan_tip": "Deria hijau lemah atau tiada", + "ui.colour_vision_failed": "Gagal", + "ui.colour_vision_fixed": "Tetap", + "ui.colour_vision_mode": "Mod", + "ui.colour_vision_note": "Melaraskan warna yang menunjukkan status lakaran, paksi, lenturan, analisis dan ikon. Jika anda menggunakan penapis warna Windows, biarkan tetapan ini Dimatikan.", + "ui.colour_vision_off": "Dimatikan", + "ui.colour_vision_off_tip": "Warna asal tema", + "ui.colour_vision_projected": "Diunjurkan", + "ui.colour_vision_protan": "Protan", + "ui.colour_vision_protan_tip": "Deria merah lemah atau tiada", + "ui.colour_vision_sample": "Contoh", + "ui.colour_vision_tritan": "Tritan", + "ui.colour_vision_tritan_tip": "Deria biru lemah atau tiada", + "ui.combine": "Gabung", + "ui.coming_later": "akan datang", + "ui.command_done": "{command} selesai", + "ui.command_palette_hint": "Taip arahan, cth. {example} — atau tekan S untuk mencari", + "ui.concentric": "Sepusat", + "ui.configurations": "Konfigurasi", + "ui.conic_curve": "Lengkung Kon", + "ui.constant": "Malar", + "ui.constraints_conflict": "Kekangan bercanggah", + "ui.construct": "Bina", + "ui.construction": "Binaan", + "ui.context_menu": "Menu konteks", + "ui.continuity_g0": "Lipatan G0", + "ui.continuity_g1": "Tangen G1", + "ui.continuity_g2": "Kelengkungan G2", + "ui.copy": "Salin", + "ui.corner": "Sudut", + "ui.corners": "Sudut", + "ui.counterbore": "Lubang Benam Rata", + "ui.countersink": "Lubang Benam Tirus", + "ui.create": "Cipta", + "ui.create_copy": "Cipta Salinan", + "ui.create_sketch": "Cipta Lakaran", + "ui.current": "semasa", + "ui.curvature": "Kelengkungan", + "ui.curvature_g2": "Kelengkungan (G2)", + "ui.curves": "Lengkung", + "ui.custom_program": "Tersuai…", + "ui.custom_program_tip": "Pilih program penghiris untuk ditambah pada senarai", + "ui.customizeToolbar": "Sesuaikan Bar Alat…", + "ui.cut": "Potong", + "ui.cylinder": "Silinder", + "ui.dark": "Gelap", + "ui.default_modelling_orientation": "Orientasi pemodelan lalai", + "ui.degrees_of_freedom": "darjah kebebasan", + "ui.delete": "Padam", + "ui.depth": "Kedalaman", + "ui.design": "Reka", + "ui.design_properties.author": "Pengarang", + "ui.design_properties.description": "Penerangan", + "ui.design_properties.exports": "Maklumat ini disertakan dalam eksport STEP, IGES dan 3MF jika disokong oleh format tersebut.", + "ui.design_properties.license": "Lesen", + "ui.design_properties.not_text": "Nilai bukan teks; menaip di sini menggantikannya.", + "ui.design_properties.organization": "Organisasi", + "ui.design_properties.others": "Data daripada alat lain", + "ui.design_properties.others_note": "Kekal dalam reka bentuk dan tidak dieksport.", + "ui.design_properties.part_number": "Nombor bahagian", + "ui.design_properties.project": "Projek", + "ui.design_properties.revision": "Semakan", + "ui.diameter": "Diameter", + "ui.dimension": "Dimensi", + "ui.direction": "Arah", + "ui.display_quality": "Kualiti paparan", + "ui.display_quality_coarse": "Kasar", + "ui.display_quality_fine": "Halus", + "ui.display_quality_normal": "Biasa", + "ui.display_quality_ultra": "Ultra", + "ui.distance": "Jarak", + "ui.distance_1": "Jarak 1", + "ui.distance_2": "Jarak 2", + "ui.document_settings": "Tetapan Dokumen", + "ui.don_t_save": "Jangan Simpan", + "ui.draft": "Sudut Draf", + "ui.drawing": "Lukisan", + "ui.drill_point": "Hujung Gerudi", + "ui.edit": "Sunting", + "ui.editJointLimits": "Sunting Had Sendi", + "ui.edit_section_analysis": "Sunting Analisis Keratan", + "ui.ellipse": "Elips", + "ui.end_radius": "Jejari Akhir", + "ui.end_scale": "Skala Akhir", + "ui.entities": "Entiti", + "ui.equal": "Sama", + "ui.equivalent_radius": "Jejari Setara", + "ui.expand": "Kembangkan", + "ui.exportDxf": "Eksport DXF…", + "ui.export_ellipsis": "Eksport...", + "ui.export_ellipsis_keymap": "Eksport…", + "ui.export_keymap_tip": "Simpan kekunci, kegemaran kotak S dan bar alat ke fail", + "ui.extend": "Panjangkan", + "ui.extent_type": "Jenis Julat", + "ui.extrude": "Semperit", + "ui.factor": "Faktor", + "ui.feature_history": "Sejarah ciri", + "ui.feature_options": "Pilihan Ciri", + "ui.features": "Ciri", + "ui.file": "Fail", + "ui.fillet": "Jejari Sudut", + "ui.filter_commands_or_keys": "Tapis arahan atau kekunci", + "ui.findInTimeline": "Cari dalam Garis Masa", + "ui.findInWindow": "Cari dalam Tetingkap", + "ui.finish_sketch": "Tamatkan Lakaran", + "ui.fit": "Muatkan", + "ui.fix_unfix": "Tetap/Lepas", + "ui.flat": "Rata", + "ui.flip": "Balik", + "ui.format": "Format", + "ui.frame_rate": "Kadar bingkai", + "ui.front": "Hadapan", + "ui.fully_constrained": "Dikekang sepenuhnya", + "ui.general": "Umum", + "ui.graphics": "Grafik", + "ui.grid_follows_view": "Grid mengikut pandangan", + "ui.grid_follows_view_hint": "Pandangan sisi guna grid satah tegak yang menghadapnya, bukan satah tanah", + "ui.ground_shadow": "Bayang tanah", + "ui.groupSelected": "Kumpulkan Pilihan", + "ui.heading_add_ins": "TAMBAHAN", + "ui.heading_assemble": "PASANG", + "ui.heading_box": "KOTAK", + "ui.heading_chamfer": "SERONG", + "ui.heading_circular_pattern": "CORAK MEMBULAT", + "ui.heading_coil": "GEGELUNG", + "ui.heading_combine": "GABUNG", + "ui.heading_configure": "KONFIGURASI", + "ui.heading_constraints": "KEKANGAN", + "ui.heading_construct": "BINA", + "ui.heading_create": "CIPTA", + "ui.heading_create_sketch": "CIPTA LAKARAN", + "ui.heading_cylinder": "SILINDER", + "ui.heading_design": "REKA", + "ui.heading_draft": "SUDUT DRAF", + "ui.heading_edit": "SUNTING", + "ui.heading_extrude": "SEMPERIT", + "ui.heading_fillet": "JEJARI SUDUT", + "ui.heading_finish_sketch": "TAMATKAN LAKARAN", + "ui.heading_front": "HADAPAN", + "ui.heading_hole": "LUBANG", + "ui.heading_home": "UTAMA", + "ui.heading_insert": "SISIP", + "ui.heading_inspect": "PERIKSA", + "ui.heading_loft": "LOFT", + "ui.heading_make": "HASILKAN", + "ui.heading_measure": "UKUR", + "ui.heading_mesh": "MESH", + "ui.heading_mirror": "CERMIN", + "ui.heading_modify": "UBAH SUAI", + "ui.heading_move": "ALIH", + "ui.heading_move_copy": "ALIH/SALIN", + "ui.heading_offset": "OFSET", + "ui.heading_offset_plane": "SATAH OFSET", + "ui.heading_ok": "OK", + "ui.heading_parameters": "PARAMETER", + "ui.heading_pattern": "CORAK", + "ui.heading_pattern_on_path": "CORAK SEPANJANG LALUAN", + "ui.heading_pipe": "PAIP", + "ui.heading_plane_at_angle": "SATAH BERSUDUT", + "ui.heading_plastic": "PLASTIK", + "ui.heading_position": "KEDUDUKAN", + "ui.heading_prepare": "SEDIAKAN", + "ui.heading_rectangular_pattern": "CORAK SEGI EMPAT TEPAT", + "ui.heading_revolve": "PUTAR", + "ui.heading_right": "KANAN", + "ui.heading_save_mesh": "SIMPAN SEBAGAI MESH", + "ui.heading_scale": "SKALA", + "ui.heading_section_analysis": "ANALISIS KERATAN", + "ui.heading_select": "PILIH", + "ui.heading_setup": "PERSEDIAAN", + "ui.heading_sheet_metal": "LOGAM KEPINGAN", + "ui.heading_shell": "RONGGAKAN", + "ui.heading_sketch": "LAKARAN", + "ui.heading_sketch_palette": "PALET LAKARAN", + "ui.heading_sketch_scale": "SKALA LAKARAN", + "ui.heading_solid": "PEPEJAL", + "ui.heading_sphere": "SFERA", + "ui.heading_split_body": "BELAH JASAD", + "ui.heading_surface": "PERMUKAAN", + "ui.heading_sweep": "SAPU", + "ui.heading_thread": "BEBENANG", + "ui.heading_top": "ATAS", + "ui.heading_torus": "TORUS", + "ui.heading_utilities": "UTILITI", + "ui.heading_utility": "UTILITI", + "ui.help": "Bantuan", + "ui.hide": "Sembunyi", + "ui.hideAxes": "Sembunyi Paksi", + "ui.hideDimension": "Sembunyi Dimensi", + "ui.hideOrigin": "Sembunyi Titik Asal", + "ui.hidePlanes": "Sembunyi Satah", + "ui.hideProfile": "Sembunyi Profil", + "ui.hole": "Lubang", + "ui.hole_tap_type": "Jenis Bebenang Lubang", + "ui.hole_type": "Jenis Lubang", + "ui.home": "Utama", + "ui.homeView": "Pandangan Utama", + "ui.horizontal_vertical": "Mendatar/Menegak", + "ui.import_ellipsis": "Import…", + "ui.infinite": "Tak Terhingga", + "ui.insert": "Sisip", + "ui.inspect": "Periksa", + "ui.intersect": "Silang", + "ui.isolate": "Asingkan", + "ui.join": "Cantum", + "ui.joints": "Sendi", + "ui.keyboard_shortcuts": "Pintasan Kekunci", + "ui.language": "Bahasa", + "ui.length_decimals": "Perpuluhan panjang", + "ui.light": "Cerah", + "ui.line": "Garis", + "ui.linetype": "Jenis garis", + "ui.lock": "Kunci", + "ui.loft": "Loft", + "ui.look_at": "Pandang Tepat", + "ui.look_at_anim_desc": "Pandangan paksi, Pandang Tepat, Utama dan Muatkan", + "ui.manufacture": "Pembuatan", + "ui.material_review.axes": "Paksi setempat bahan; orientasi pada jasad belum ditetapkan.", + "ui.material_review.claims": "Maklumat sumber dan lesen belum disahkan. Nilai yang tidak diberikan kekal tidak diketahui.", + "ui.material_review.compressive_strength": "Kekuatan mampatan", + "ui.material_review.conditions": "Keadaan yang dinyatakan", + "ui.material_review.density": "Ketumpatan", + "ui.material_review.derived": "Modulus isotropik terbitan", + "ui.material_review.elasticity": "Keanjalan", + "ui.material_review.input": "Tampal kad bahan skema-1 (JSON)", + "ui.material_review.limit": "Kad melebihi had input 256 KiB.", + "ui.material_review.moisture_unit": "kg air / kg bahan kering", + "ui.material_review.properties": "Sifat", + "ui.material_review.review": "Semak kad", + "ui.material_review.scope": "Bahan cadangan sahaja: belum ditetapkan atau disimpan. Pengesahan berangka bukan pensijilan kejuruteraan.", + "ui.material_review.shear_strength": "Kekuatan ricih", + "ui.material_review.source": "Sumber", + "ui.material_review.specific_heat": "Haba tentu", + "ui.material_review.tensile_strength": "Kekuatan tegangan", + "ui.material_review.thermal_conductivity": "Kekonduksian terma", + "ui.material_review.thermal_expansion": "Pengembangan terma", + "ui.material_review.title": "Semak Data Bahan Fizikal", + "ui.material_review.unknown": "Tidak diketahui", + "ui.material_review.yield_strength": "Kekuatan alah", + "ui.measure": "Ukur", + "ui.mesh_format_3mf": "3MF", + "ui.mesh_format_3mf_tagged": "3MF dengan tag muka", + "ui.mesh_format_stl": "STL", + "ui.midpoint": "Titik tengah", + "ui.mirror": "Cermin", + "ui.mirror_line": "Garis cermin", + "ui.modify": "Ubah Suai", + "ui.move": "Alih", + "ui.multiple": "Berbilang", + "ui.named_views": "Pandangan Bernama", + "ui.navigation": "Navigasi", + "ui.needs_design": "{command}: buka reka bentuk dahulu", + "ui.newSketchGroup": "Kumpulan Lakaran Baharu", + "ui.new_body": "Jasad Baharu", + "ui.new_design": "Reka Bentuk Baharu", + "ui.no_slicer_found": "Tiada penghiris ditemui", + "ui.normal": "Biasa", + "ui.normalConstruction": "Biasa / Binaan", + "ui.not_a_program": "{path} bukan program yang boleh dijalankan", + "ui.object_type": "Jenis Objek", + "ui.objects": "Objek", + "ui.offer_to_stand_up_y_up_files": "Cadang tegakkan fail Y ke atas", + "ui.offset": "Ofset", + "ui.offset_plane": "Satah Ofset", + "ui.one_side": "Satu Sisi", + "ui.open": "Buka", + "ui.open_ellipsis": "Buka...", + "ui.open_ends_tip": "Tidak bersentuh", + "ui.open_preferences": "Buka Tetapan", + "ui.open_recent": "Buka Terkini", + "ui.operation": "Operasi", + "ui.options": "Pilihan", + "ui.orbit": "Orbit", + "ui.orbit_around": "Orbit mengelilingi", + "ui.orientation": "Orientasi", + "ui.origin": "Titik Asal", + "ui.palette_points": "Titik", + "ui.palette_profile": "Profil", + "ui.pan": "Sorot", + "ui.pan_zoom_orbit": "Sorot, zum, orbit", + "ui.parallel": "Selari", + "ui.parameters": "Parameter", + "ui.paste": "Tampal", + "ui.path": "Laluan", + "ui.pattern_on_path": "Corak Sepanjang Laluan", + "ui.perpendicular": "Serenjang", + "ui.perspective_view": "Pandangan perspektif", + "ui.pinToShortcuts": "Semat pada Pintasan", + "ui.pinToToolbar": "Semat pada Bar Alat", + "ui.pipe": "Paip", + "ui.placement": "Penempatan", + "ui.plane": "Satah", + "ui.plane_at_angle": "Satah Bersudut", + "ui.point": "Titik", + "ui.point_under_the_cursor": "Titik di bawah kursor", + "ui.points": "Titik", + "ui.polygon": "Poligon", + "ui.preferences": "Tetapan", + "ui.press_a_key": "tekan kekunci…", + "ui.profile": "Profil", + "ui.profile_plane": "Satah Profil", + "ui.profiles": "Profil", + "ui.project": "Unjur", + "ui.project_face_edges_sketch": "Unjur tepi muka ke dalam lakaran baharu", + "ui.properties": "Sifat", + "ui.pull_direction": "Arah tarikan", + "ui.quantity": "Kuantiti", + "ui.quantity_2": "Kuantiti 2", + "ui.quit": "Keluar", + "ui.radial_context_menu": "Menu konteks membulat", + "ui.radius": "Jejari", + "ui.radius_type": "Jenis Jejari", + "ui.rail": "Rel", + "ui.rail_fit": "Padanan Rel", + "ui.reachable": "Boleh dicapai", + "ui.rectangle": "Segi Empat Tepat", + "ui.rectangular_pattern": "Corak Segi Empat Tepat", + "ui.redo": "Buat Semula", + "ui.removeFromToolbar": "Buang daripada Bar Alat", + "ui.removeSection": "Buang Keratan", + "ui.render": "Render", + "ui.renderer": "Enjin Render", + "ui.repeat": "Ulang", + "ui.report_a_bug": "Laporkan pepijat", + "ui.reset": "Set Semula", + "ui.reset_all": "Set Semula Semua", + "ui.reset_the_settings_on_this_page": "Set semula tetapan pada halaman ini", + "ui.restore": "Pulihkan", + "ui.restore_defaults": "Pulihkan Tetapan Lalai", + "ui.reverse_zoom_direction": "Songsangkan arah zum", + "ui.revolve": "Putar", + "ui.right": "Kanan", + "ui.save": "Simpan", + "ui.save_as": "Simpan Sebagai", + "ui.save_as_ellipsis": "Simpan Sebagai...", + "ui.save_mesh_no_slicer": "Tiada penghiris: pilih program melalui Tersuai… atau matikan Hantar ke penghiris", + "ui.save_mesh_pick_bodies": "Pilih jasad untuk disimpan", + "ui.save_mesh_temp_failed": "Tidak dapat mencipta {folder}: {error}", + "ui.saved_to": "{path} disimpan", + "ui.scale": "Skala", + "ui.second_rail": "Rel Kedua", + "ui.section_analysis": "Analisis Keratan", + "ui.select": "Pilih", + "ui.selectOther": "Pilih Lain…", + "ui.selectTangentChain": "Pilih Rantaian Tangen", + "ui.select_other_hint": "Pilih Lain: tahan butang kiri pada model tanpa bergerak (atau klik kanan › Pilih Lain…) untuk senarai objek di bawah kursor. Klik tempat sama untuk objek seterusnya.", + "ui.selection": "Pilihan", + "ui.send": "Hantar", + "ui.send_to_slicer": "Hantar ke penghiris", + "ui.sent_to_slicer": "Dihantar ke {slicer}", + "ui.shell": "Ronggakan", + "ui.show": "Papar", + "ui.showAll": "Papar Semua", + "ui.showAllBodies": "Papar Semua Jasad", + "ui.showAxes": "Papar Paksi", + "ui.showDimension": "Papar Dimensi", + "ui.showOrigin": "Papar Titik Asal", + "ui.showPlanes": "Papar Satah", + "ui.show_constraints": "Kekangan", + "ui.show_construction_geometries": "Geometri Binaan", + "ui.show_dimensions": "Dimensi", + "ui.show_points": "Papar Titik", + "ui.show_profile": "Papar Profil", + "ui.show_projected_geometries": "Geometri Unjuran", + "ui.simple": "Ringkas", + "ui.simulation": "Simulasi", + "ui.single": "Tunggal", + "ui.sketch": "Lakaran", + "ui.sketch_dimension": "Dimensi Lakaran", + "ui.sketch_grid": "Grid Lakaran", + "ui.sketch_scale": "Skala Lakaran", + "ui.sketch_status": "Status Lakaran", + "ui.sketches": "Lakaran", + "ui.slice": "Hiris", + "ui.slicer": "Penghiris", + "ui.slicer_delete_tip": "{program}\nTekan Delete untuk membuangnya daripada senarai", + "ui.slot": "Slot", + "ui.smooth": "Licin", + "ui.smooth_wheel_zoom": "Zum roda lancar", + "ui.smooth_wheel_zoom_tip": "Matikan untuk mengezum serta-merta bagi setiap putaran roda tetikus, tanpa gerakan susulan", + "ui.snap": "Lekap", + "ui.space_mouse_hint": "Alih dan putar pandangan serentak; dalam lakaran, hanya sorot dan zum digunakan.", + "ui.space_mouse_navigate": "Navigasi dengan SpaceNavigator / SpaceMouse", + "ui.spacing": "Selang", + "ui.spacing_2": "Selang 2", + "ui.sphere": "Sfera", + "ui.spline": "Splin", + "ui.split_body": "Belah Jasad", + "ui.stand_up_tip": "Selepas buka STEP atau IGES dengan Z ke atas, cadangkan suku putaran pada X", + "ui.start": "Mula", + "ui.start_radius": "Jejari Mula", + "ui.stretch": "Regang", + "ui.supersampling": "Pensampelan super (SSAA)", + "ui.supersampling_adaptive": "Hanya apabila pandangan pegun", + "ui.supersampling_off": "Dimatikan (1×)", + "ui.suppress": "Nyahaktifkan", + "ui.sweep": "Sapu", + "ui.sweep_follow_direction": "Ikut Arah", + "ui.sweep_keep_as_drawn": "Kekal seperti Dilukis", + "ui.sweep_turn_with_path": "Putar mengikut Laluan", + "ui.symmetric": "Simetri", + "ui.symmetry": "Simetri", + "ui.system": "Sistem", + "ui.tangent": "Tangen", + "ui.taper_angle": "Sudut Tirus", + "ui.tapped": "Berbebenang", + "ui.text": "Teks", + "ui.theme": "Tema", + "ui.thickness": "Ketebalan", + "ui.thread": "Bebenang", + "ui.tie_ends": "Ikat", + "ui.tie_ends_tip": "Ikat semua hujung tak terikat", + "ui.timeline_bottom": "Garis masa di bawah", + "ui.timeline_left_note": "Dalam susun atur kiri, bar undur terletak di atas pelayar bahagian dan adegan.", + "ui.timeline_left_sidebar": "Bar sisi kiri", + "ui.tip_angle": "Sudut Hujung", + "ui.to_object": "Ke Objek", + "ui.tool_direction": "Arah alat", + "ui.top": "Atas", + "ui.torus": "Torus", + "ui.total_angle": "Jumlah sudut", + "ui.trackpad_pan_tip": "Pad sentuh: sorot (jika mati: zum). Roda tetikus: zum. Roda ibu jari: sorot sisi. Cubit sentiasa zum.", + "ui.trim": "Pangkas", + "ui.twist": "Pintal", + "ui.two_finger_scroll_pans": "Tatal dua jari: sorot", + "ui.two_sides": "Dua Sisi", + "ui.ui_scale": "Skala UI", + "ui.undo": "Buat Asal", + "ui.unground": "Lepaskan", + "ui.unisolate": "Tamat Pengasingan", + "ui.units": "Unit", + "ui.units_of_new_designs": "Unit reka bentuk baharu", + "ui.unlock": "Buka Kunci", + "ui.unsuppress": "Aktifkan Semula", + "ui.untied_ends_tip": "Bersentuh tanpa kekangan", + "ui.untitled": "Tanpa Tajuk", + "ui.up_axis_note": "Paksi yang menghala ke atas dalam pandangan paksi, Utama dan Pandang Tepat. Reka bentuk tidak berubah.", + "ui.updateToCurrentView": "Kemas Kini Pandangan Semasa", + "ui.variable": "Berubah", + "ui.view_centre": "Pusat pandangan", + "ui.visual_shaded_hidden_edges": "Berlorek dengan tepi tersembunyi", + "ui.visual_shaded_with_edges": "Berlorek dengan tepi", + "ui.visual_style": "Gaya visual", + "ui.visual_wireframe": "Rangka dawai", + "ui.workspace": "ruang kerja", + "ui.x_distance": "Jarak X", + "ui.y_distance": "Jarak Y", + "ui.y_up": "Y ke atas", + "ui.z_up": "Z ke atas", + "ui.zoom": "Zum", + "ui.zoom_to_cursor_tip": "Roda tetikus mengezum ke arah titik di bawah kursor (jika dimatikan: ke arah pusat pandangan)", + "ui.zoom_to_the_cursor": "Zum ke kursor", + "update.available": "SolidCraft {version} tersedia", + "update.button": "Kemas kini", + "update.button_tip": "SolidCraft {version} tersedia", + "update.button_version": "Kemas kini ke {version}", + "update.check_automatically": "Semak kemas kini secara automatik", + "update.check_now": "Semak sekarang", + "update.checking": "Menyemak…", + "update.copy": "Salin", + "update.dmg_opened": "Imej cakera telah dibuka dan disahkan: seret SolidCraft ke Applications untuk menggantikan salinan lama, kemudian mulakan semula SolidCraft.", + "update.download": "Muat turun", + "update.download_open": "Muat turun dan buka", + "update.downloading": "Memuat turun dan mengesahkan… {done} daripada {total} MB", + "update.failed": "Tidak dapat menyemak: {error}", + "update.file": "Muat turun: {file}.", + "update.install_failed": "Kemas kini gagal dipasang: {error}. Tiada perubahan dibuat; gunakan Muat turun untuk mendapatkan pakej.", + "update.install_msi": "Pasang (menutup SolidCraft)", + "update.installed": "SolidCraft {version} telah dipasang. Mulakan semula untuk menggunakannya.", + "update.installer_started": "Pemasang bermula apabila SolidCraft ditutup.", + "update.later": "Ingatkan saya kemudian", + "update.no_notes": "Tiada nota untuk keluaran ini.", + "update.package_hint": "Salinan ini dipasang melalui {kind}. Muat turun pakej baharu, kemudian pasang dengan:", + "update.prefs_dev": "Ini ialah binaan pembangunan ({version}). Semakan kemas kini tidak dilakukan.", + "update.prefs_flatpak": "Flatpak mengemas kini {version}: jalankan {command} atau guna pusat perisian. SolidCraft tidak menyemak.", + "update.prefs_label": "Kemas kini", + "update.prefs_note": "SolidCraft {version} ({kind}). Semakan hanya meminta keluaran terkini dari GitHub, tanpa data lain dihantar.", + "update.release_page": "Buka halaman keluaran", + "update.restart": "Mula semula", + "update.restart_later": "Kemudian", + "update.show": "Papar kemas kini kepada {version}", + "update.skip": "Langkau versi ini", + "update.system_hint": "Salinan ini menggunakan {kind}. Kemas kini dengan:", + "update.title": "Kemas kini tersedia", + "update.up_to_date": "SolidCraft sudah terkini.", + "update.update_now": "Kemas kini", + "update.you_have": "Versi anda: {version}." +} diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 1863d2de0..28f8fc906 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -40,6 +40,7 @@ static GALICIAN: Catalog = Catalog::new("gl", "Galego", include_str!(concat!(env static ITALIAN: Catalog = Catalog::new("it", "Italiano", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/it.json"))); static JAPANESE: Catalog = Catalog::new("ja", "日本語", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/ja.json"))); static KOREAN: Catalog = Catalog::new("ko", "한국어", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/ko.json"))); +static MALAY: Catalog = Catalog::new("ms", "Bahasa Melayu", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/ms.json"))); static POLISH: Catalog = Catalog::new("pl", "Polski", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/pl.json"))); static PORTUGUESE_BR: Catalog = Catalog::new("pt-BR", "Português (Brasil)", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/pt-BR.json"))); @@ -60,6 +61,7 @@ pub const LOCALES: &[&Catalog] = &[ &ITALIAN, &JAPANESE, &KOREAN, + &MALAY, &POLISH, &PORTUGUESE_BR, &RUSSIAN, @@ -265,7 +267,7 @@ mod tests { } /// Catalogs delivered complete. English is the source catalog; Czech, Italian, Japanese and Chinese - /// are complete. German, Korean, Russian, French and Ukrainian + /// are complete. German, Korean, Malay, Russian, French and Ukrainian /// are partial (German and Korean predate the coverage guards; Russian, French and Ukrainian /// are kept partial so a new label doesn't need more translations), so their gaps fall back /// to English and are reported by `cargo xtask i18n` without failing the build, while @@ -569,6 +571,27 @@ mod tests { assert_eq!(ko.dynamic("Sketch of bracket"), "Sketch of bracket"); } + #[test] + fn malay_catalog_translates_keys_labels_and_browser_patterns() { + let ms = Locale::for_language("ms"); + assert!(is_supported("ms")); + assert_eq!(ms.name(), "Bahasa Melayu"); + assert_eq!(ms.text("ui.preferences"), "Tetapan"); + assert_eq!(ms.label("Extrude"), "Semperit"); + assert_eq!(ms.label("CREATE SKETCH"), "CIPTA LAKARAN"); + assert_eq!(ms.format("document.save_changes", &[("name", "My {design}")]), "Simpan perubahan pada My {design}?"); + assert_eq!(ms.format("dialog.selected_count", &[("count", "2")]), "↖ 2 dipilih"); + assert_eq!(ms.dynamic("Sketch1"), "Lakaran1"); + assert_eq!(ms.dynamic("Body2"), "Jasad2"); + assert_eq!(ms.dynamic("Component12"), "Komponen12"); + assert_eq!(ms.dynamic("Units: mm"), "Unit: mm"); + assert_eq!(ms.dynamic("Precision: 3"), "Ketepatan: 3"); + assert_eq!(ms.dynamic("Parameters (5)"), "Parameter (5)"); + assert_eq!(ms.dynamic("4 degrees of freedom"), "4 darjah kebebasan"); + assert_eq!(ms.given_name("Sketch of bracket"), "Sketch of bracket"); + assert_eq!(ms.label("NonExistentKey"), "NonExistentKey"); + } + #[test] fn russian_catalog_translates_keys_labels_and_browser_patterns() { let ru = Locale::for_language("ru"); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 184934273..b5726d1f1 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -152,7 +152,7 @@ labels; `prefs:measure_axis_distances` identifies the checkbox. | `ui.home` | `open?`: bool; `sample?`: index | the start page: show or hide it, open a built-in sample (once built); returns `open` and the recent designs | | `ui.shortcut` | `command`, `key?`, `replace?` | a command's key, or rebinds it (`""` clears; a key another command uses is refused unless `replace`) | | `ui.help` | `item?`: `about`, `shortcuts` (read only), `report` (opens a report draft for review), `crashes` (the Crash Reports window) | the version, commit, build date and diagnostic text | -| `ui.prefs` | any of `default_units`, `nav` (`fusion`, `solidworks`, `inventor`, `alias`, `blender`, `tinkercad`, `openscad`, `touchpad`), `zoom_reverse`, `pan_reverse_x` (default false: horizontal scrolling pans the other way), `zoom_to_cursor`, `smooth_wheel_zoom` (default true), `trackpad_pan` (default true: two-finger scroll pans, except Touchpad always zooms; pinch zooms), `orbit_around` (`view_centre` (default: what Pan moves and Fit frames), `origin` (the world origin stays still on screen), `cursor` (the model point under the pointer when the drag began); the older `orbit_cursor` boolean still sets `cursor` when true), `look_at_anim`, `look_at_speed`, `middle_double_click` (`home` (default), `fit`, `off`), `msaa`, `show_frame_rate` (default false: frames per second in the view's bottom-right corner; the view redraws every frame while it is on), `length_decimals`, `angle_decimals`, `theme` (`dark`, `light`, `system` or a theme file's id: a built-in one such as `gruvbox-dark`, or an imported one; the reply's `theme_ids` lists them), `theme_import` (a `solidcraft-theme/1` file's JSON or text: adds the theme and turns it on; the reply's `theme_imported` is its id), `theme_remove` (an imported theme's id), `theme_export: true` (the reply's `theme_file` is the theme on now as a complete file; see [colour themes](book/src/guide/ui-tour.md#colour-themes)), `language` (`en`, `ja`, `de`, `fr`, `ko`, `ru`, `uk`, `zh`; see [localization](localization.md)), `ui_scale`, `ui_font` (an installed font family or a font file for the interface; empty for the built-in font), `up_axis` (`z`, `y`), `offer_stand_up`, `color_vision` (`off` (default), `protan`, `deutan`, `tritan`: colour vision modes, #778), `check_updates` (default true; [updates](book/src/guide/updates.md)); `open` (a page: General, Navigation, Keyboard Shortcuts, Design, Graphics, Sketch, Selection, AI) opens the Preferences dialog there; `button`: `ok`, `cancel`, `apply`, `defaults`; `stand_up: true` stands up a just-opened Y-up file, `stand_up: false` leaves it as it is ("Leave it": the offer closes and `offer_stand_up` stays on); the offer's buttons are the handles `stand_up:stand`, `stand_up:leave` and `stand_up:never` | sets preferences (kept between runs), returns them all plus `dialog` (the open page or null), `dark` and `stand_up_offer` | +| `ui.prefs` | any of `default_units`, `nav` (`fusion`, `solidworks`, `inventor`, `alias`, `blender`, `tinkercad`, `openscad`, `touchpad`), `zoom_reverse`, `pan_reverse_x` (default false: horizontal scrolling pans the other way), `zoom_to_cursor`, `smooth_wheel_zoom` (default true), `trackpad_pan` (default true: two-finger scroll pans, except Touchpad always zooms; pinch zooms), `orbit_around` (`view_centre` (default: what Pan moves and Fit frames), `origin` (the world origin stays still on screen), `cursor` (the model point under the pointer when the drag began); the older `orbit_cursor` boolean still sets `cursor` when true), `look_at_anim`, `look_at_speed`, `middle_double_click` (`home` (default), `fit`, `off`), `msaa`, `show_frame_rate` (default false: frames per second in the view's bottom-right corner; the view redraws every frame while it is on), `length_decimals`, `angle_decimals`, `theme` (`dark`, `light`, `system` or a theme file's id: a built-in one such as `gruvbox-dark`, or an imported one; the reply's `theme_ids` lists them), `theme_import` (a `solidcraft-theme/1` file's JSON or text: adds the theme and turns it on; the reply's `theme_imported` is its id), `theme_remove` (an imported theme's id), `theme_export: true` (the reply's `theme_file` is the theme on now as a complete file; see [colour themes](book/src/guide/ui-tour.md#colour-themes)), `language` (`en`, `ja`, `de`, `fr`, `ko`, `ms`, `ru`, `uk`, `zh`; see [localization](localization.md)), `ui_scale`, `ui_font` (an installed font family or a font file for the interface; empty for the built-in font), `up_axis` (`z`, `y`), `offer_stand_up`, `color_vision` (`off` (default), `protan`, `deutan`, `tritan`: colour vision modes, #778), `check_updates` (default true; [updates](book/src/guide/updates.md)); `open` (a page: General, Navigation, Keyboard Shortcuts, Design, Graphics, Sketch, Selection, AI) opens the Preferences dialog there; `button`: `ok`, `cancel`, `apply`, `defaults`; `stand_up: true` stands up a just-opened Y-up file, `stand_up: false` leaves it as it is ("Leave it": the offer closes and `offer_stand_up` stays on); the offer's buttons are the handles `stand_up:stand`, `stand_up:leave` and `stand_up:never` | sets preferences (kept between runs), returns them all plus `dialog` (the open page or null), `dark` and `stand_up_offer` | | `ui.capture` | `action?`: `capture`, `revert`, `cancel` | answers the Capture Position question (asked when a command starts or the design is saved while components were moved without capturing); without `action`, what waits | | `ui.window` | `action`: minimize, maximize, restore, toggle, close | what the title bar's caption buttons do (on Windows and Linux the application bar is the title bar); close asks about unsaved designs first | | `ui.agent_cursor` | `show` (bool), `speed`: a number from 1 to 5 (times the normal speed) or `"instant"` (no animation: the command runs at once and the pointer jumps to where it acted), `follow_camera` (bool); all optional | the settings. While the cursor is shown, `engine.execute` first glides to the command's toolbar button and to each pick, then runs and replies; later requests wait their turn. `"animate": false` on a call skips it | diff --git a/docs/localization.md b/docs/localization.md index 80a551ec3..ed7575932 100644 --- a/docs/localization.md +++ b/docs/localization.md @@ -1,7 +1,7 @@ # UI localization SolidCraft embeds its translations and works offline. English, Czech, German, Spanish, French, Galician, Italian, -Japanese, Korean, Polish, Brazilian Portuguese, Russian, Turkish, Ukrainian and Chinese are currently registered in `crates/ui-egui/src/i18n.rs`. Adding a language requires an +Japanese, Korean, Malay, Polish, Brazilian Portuguese, Russian, Turkish, Ukrainian and Chinese are currently registered in `crates/ui-egui/src/i18n.rs`. Adding a language requires an embedded catalog and one registration there; the preferences selector and validation use the same registry. @@ -38,9 +38,9 @@ that looks untranslated. Two guards catch that in the build: - `every_complete_catalog_carries_every_english_message` — adding a key to `en.json` without giving it to a complete catalog fails the tests. English is the source catalog, - Japanese and Chinese are delivered complete; German, Spanish, Galician, Italian, Korean, Polish, Brazilian Portuguese, Russian, French, Ukrainian and + Japanese and Chinese are delivered complete; German, Spanish, Galician, Italian, Korean, Malay, Polish, Brazilian Portuguese, Russian, French, Ukrainian and Turkish are partial — their gaps fall back to English and are reported by `cargo xtask i18n` without - failing the build. A new label needs en, ja, zh, de and ko; Russian, French and Ukrainian may + failing the build. A new label needs en, ja, zh, de and ko; Russian, French, Ukrainian and Malay may follow later. - `every_toolbar_tab_and_panel_is_in_the_english_catalog` — tabs and panels reach the UI as bare source strings, resolved only by the English-label adapter, so a heading missing from `en.json` From 38f6ed76c9b66ce5cae1b08958dae44db3e78ea6 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 19 Oct 2026 01:41:21 +0000 Subject: [PATCH 033/225] Regenerate THIRD-PARTY-LICENSES.txt and docs/features.md [skip ci] --- docs/features.md | 608 ++++++++++++++++++++++++----------------------- 1 file changed, 305 insertions(+), 303 deletions(-) diff --git a/docs/features.md b/docs/features.md index 975b3cdb1..1906441e1 100644 --- a/docs/features.md +++ b/docs/features.md @@ -1,370 +1,370 @@ # Features -SolidCraft's commands by area, generated by `cargo xtask features` from the command registry (`solidcraft-cli commands`). **393 commands.** Planned (registered, not built yet): 1. Every command runs the same way from the toolbar, a script, `solidcraft-cli exec ''`, the control channel and MCP; parameters are in the [command reference](book/src/reference/commands.md) (`cargo xtask book`). Status and plans: [ROADMAP](../ROADMAP.md). +SolidCraft's commands by area, generated by `cargo xtask features` from the command registry (`solidcraft-cli commands`). Planned commands are marked in their rows. Every command runs the same way from the toolbar, a script, `solidcraft-cli exec ''`, the control channel and MCP; parameters are in the [command reference](book/src/reference/commands.md) (`cargo xtask book`). Status and plans: [ROADMAP](../ROADMAP.md). -## Sketch (105) +## Sketch | Command | Id | Toolbar | |---|---|---| -| Create Sketch | `sketch.create` | SOLID › CREATE | -| Edit Sketch | `sketch.edit` | – | -| Finish Sketch | `sketch.finish` | SKETCH › FINISH SKETCH | -| Line (L) | `sketch.line` | SKETCH › CREATE | -| Draw Dimensioned Sketch Geometry | `sketch.draw.dimensioned` | – | -| 2-Point Rectangle (R) | `sketch.rectangle.two_point` | SKETCH › CREATE | -| 3-Point Rectangle | `sketch.rectangle.three_point` | SKETCH › CREATE | -| Rounded Rectangle | `sketch.rectangle.rounded` | SKETCH › CREATE | -| Center Rectangle | `sketch.rectangle.center` | SKETCH › CREATE | -| Center Diameter Circle (C) | `sketch.circle.center` | SKETCH › CREATE | -| 2-Point Circle | `sketch.circle.two_point` | SKETCH › CREATE | -| 3-Point Circle | `sketch.circle.three_point` | SKETCH › CREATE | -| 3-Point Arc | `sketch.arc.three_point` | SKETCH › CREATE | | Center Point Arc | `sketch.arc.center_point` | SKETCH › CREATE | -| Inscribed Polygon | `sketch.polygon.inscribed` | SKETCH › CREATE | -| Circumscribed Polygon | `sketch.polygon.circumscribed` | SKETCH › CREATE | -| Edge Polygon | `sketch.polygon.edge` | SKETCH › CREATE | -| Center to Center Slot | `sketch.slot.center_to_center` | SKETCH › CREATE | -| Overall Slot | `sketch.slot.overall` | SKETCH › CREATE | -| Point | `sketch.point` | SKETCH › CREATE | -| Sketch Dimension (D) | `sketch.dimension` | SKETCH › CREATE | -| Horizontal/Vertical | `sketch.constraint.horizontal_vertical` | SKETCH › CONSTRAINTS | -| Coincident | `sketch.constraint.coincident` | SKETCH › CONSTRAINTS | -| Tangent | `sketch.constraint.tangent` | SKETCH › CONSTRAINTS | -| Equal | `sketch.constraint.equal` | SKETCH › CONSTRAINTS | -| Parallel | `sketch.constraint.parallel` | SKETCH › CONSTRAINTS | -| Perpendicular | `sketch.constraint.perpendicular` | SKETCH › CONSTRAINTS | -| Fix/UnFix | `sketch.constraint.fix` | SKETCH › CONSTRAINTS | -| MidPoint | `sketch.constraint.midpoint` | SKETCH › CONSTRAINTS | -| Concentric | `sketch.constraint.concentric` | SKETCH › CONSTRAINTS | -| Collinear | `sketch.constraint.collinear` | SKETCH › CONSTRAINTS | -| Symmetry | `sketch.constraint.symmetry` | SKETCH › CONSTRAINTS | -| Normal/Construction (X) | `sketch.construction` | SKETCH › CREATE | -| Delete Sketch Entities | `sketch.delete` | – | -| Drag Sketch Point | `sketch.move_point` | – | -| Drag Sketch Geometry | `sketch.drag` | – | -| End Sketch Drag | `sketch.drag_end` | – | -| Move Dimension Text | `sketch.dimension_text` | – | -| Sketch Palette Options | `sketch.options` | – | -| Chain | `sketch.chain` | – | -| Solve Sketch | `sketch.solve` | – | -| Midpoint Line | `sketch.line.midpoint` | SKETCH › CREATE | | Tangent Arc | `sketch.arc.tangent` | SKETCH › CREATE | -| 2-Tangent Circle | `sketch.circle.two_tangent` | SKETCH › CREATE | -| 3-Tangent Circle | `sketch.circle.three_tangent` | SKETCH › CREATE | -| Center Point Slot | `sketch.slot.center_point` | SKETCH › CREATE | -| Three Point Arc Slot | `sketch.slot.arc_three_point` | SKETCH › CREATE | -| Center Point Arc Slot | `sketch.slot.arc_center` | SKETCH › CREATE | -| Ellipse | `sketch.ellipse` | SKETCH › CREATE | -| Fit Point Spline | `sketch.spline.fit_point` | SKETCH › CREATE | -| Control Point Spline | `sketch.spline.control_point` | SKETCH › CREATE | -| Control Point Spline (Degree 5) | `sketch.spline.control_point_5` | SKETCH › CREATE | -| Conic Curve | `sketch.conic` | SKETCH › CREATE | -| Blend Curve | `sketch.blend_curve` | SKETCH › MODIFY | -| Centerline | `sketch.centerline` | SKETCH › CREATE | -| Infinite Line | `sketch.infinite` | – | -| Text | `sketch.text` | SKETCH › CREATE | -| Edit Text | `sketch.edit_text` | – | -| Curvature | `sketch.constraint.curvature` | SKETCH › CONSTRAINTS | -| Polygon | `sketch.constraint.polygon` | SKETCH › CONSTRAINTS | +| 3-Point Arc | `sketch.arc.three_point` | SKETCH › CREATE | | AutoConstrain | `sketch.auto_constrain` | SKETCH › CONSTRAINTS | | AutoConstrain from datum | `sketch.auto_constrain_from_datum` | SKETCH › CONSTRAINTS | -| Finish with AutoConstrain | `sketch.finish_auto_constrain` | SKETCH › FINISH SKETCH | +| Auto-Project Edges on Reference | `sketch.auto_project` | – | +| Blend Curve | `sketch.blend_curve` | SKETCH › MODIFY | +| Break | `sketch.break` | SKETCH › MODIFY | +| Break Link | `sketch.break_link` | – | +| Centerline | `sketch.centerline` | SKETCH › CREATE | +| Chain | `sketch.chain` | – | +| Distance and Angle Chamfer | `sketch.chamfer.distance_angle` | SKETCH › MODIFY | +| Equal Distance Chamfer | `sketch.chamfer.equal_distance` | SKETCH › MODIFY | +| Two Distance Chamfer | `sketch.chamfer.two_distance` | SKETCH › MODIFY | +| Center Diameter Circle (C) | `sketch.circle.center` | SKETCH › CREATE | +| 3-Point Circle | `sketch.circle.three_point` | SKETCH › CREATE | +| 3-Tangent Circle | `sketch.circle.three_tangent` | SKETCH › CREATE | +| 2-Point Circle | `sketch.circle.two_point` | SKETCH › CREATE | +| 2-Tangent Circle | `sketch.circle.two_tangent` | SKETCH › CREATE | +| Conic Curve | `sketch.conic` | SKETCH › CREATE | | Sketch Constrainer | `sketch.constrainer` | SKETCH › CREATE | -| Toggle Driven Dimension | `sketch.toggle_driven` | – | +| Coincident | `sketch.constraint.coincident` | SKETCH › CONSTRAINTS | +| Collinear | `sketch.constraint.collinear` | SKETCH › CONSTRAINTS | +| Concentric | `sketch.constraint.concentric` | SKETCH › CONSTRAINTS | +| Curvature | `sketch.constraint.curvature` | SKETCH › CONSTRAINTS | +| Equal | `sketch.constraint.equal` | SKETCH › CONSTRAINTS | +| Fix/UnFix | `sketch.constraint.fix` | SKETCH › CONSTRAINTS | +| Horizontal/Vertical | `sketch.constraint.horizontal_vertical` | SKETCH › CONSTRAINTS | +| MidPoint | `sketch.constraint.midpoint` | SKETCH › CONSTRAINTS | +| Parallel | `sketch.constraint.parallel` | SKETCH › CONSTRAINTS | +| Perpendicular | `sketch.constraint.perpendicular` | SKETCH › CONSTRAINTS | +| Polygon | `sketch.constraint.polygon` | SKETCH › CONSTRAINTS | +| Symmetry | `sketch.constraint.symmetry` | SKETCH › CONSTRAINTS | +| Tangent | `sketch.constraint.tangent` | SKETCH › CONSTRAINTS | +| Normal/Construction (X) | `sketch.construction` | SKETCH › CREATE | +| Copy Sketch Entities | `sketch.copy` | – | +| Create Sketch | `sketch.create` | SOLID › CREATE | +| Cut Sketch Entities | `sketch.cut` | – | +| Delete Sketch Entities | `sketch.delete` | – | +| Sketch Dimension (D) | `sketch.dimension` | SKETCH › CREATE | +| Move Dimension Text | `sketch.dimension_text` | – | +| Drag Sketch Geometry | `sketch.drag` | – | +| End Sketch Drag | `sketch.drag_end` | – | +| Draw Dimensioned Sketch Geometry | `sketch.draw.dimensioned` | – | +| Edit Sketch | `sketch.edit` | – | +| Edit Text | `sketch.edit_text` | – | +| Ellipse | `sketch.ellipse` | SKETCH › CREATE | +| Save As DXF | `sketch.export_dxf` | – | +| Extend | `sketch.extend` | SKETCH › MODIFY | +| Fillet | `sketch.fillet` | SKETCH › MODIFY | +| Finish Sketch | `sketch.finish` | SKETCH › FINISH SKETCH | +| Finish with AutoConstrain | `sketch.finish_auto_constrain` | SKETCH › FINISH SKETCH | +| Fit Curves to Mesh Section | `sketch.fit_curves_to_section` | SKETCH › CREATE | | Constraint Glyphs | `sketch.glyphs` | – | -| Snap Inference | `sketch.snap` | – | +| Include 3D Geometry | `sketch.include_3d` | SKETCH › CREATE | +| Infinite Line | `sketch.infinite` | – | | Insert DXF | `sketch.insert_dxf` | SKETCH › INSERT | | Insert SVG | `sketch.insert_svg` | SKETCH › INSERT | -| Save As DXF | `sketch.export_dxf` | – | +| Inspect Sketch | `sketch.inspect` | – | +| Intersect | `sketch.intersect` | SKETCH › CREATE | +| Intersection Curve | `sketch.intersection_curve` | SKETCH › CREATE | +| Isoparametric Curve | `sketch.isoparametric_curve` | SKETCH › CREATE | +| Line (L) | `sketch.line` | SKETCH › CREATE | +| Midpoint Line | `sketch.line.midpoint` | SKETCH › CREATE | +| 3D Line | `sketch.line3d` | – | | Loose Ends | `sketch.loose_ends` | – | | Tie Loose Ends | `sketch.loose_ends.tie` | – | -| 3D Line | `sketch.line3d` | – | -| 3D Spline | `sketch.spline3d` | – | -| 3D Point | `sketch.point3d` | – | +| Mirror | `sketch.mirror` | SKETCH › PATTERN | +| Move/Copy Sketch Entities | `sketch.move` | SKETCH › MODIFY | | Move 3D Point | `sketch.move3d` | – | -| Fillet | `sketch.fillet` | SKETCH › MODIFY | -| Equal Distance Chamfer | `sketch.chamfer.equal_distance` | SKETCH › MODIFY | -| Distance and Angle Chamfer | `sketch.chamfer.distance_angle` | SKETCH › MODIFY | -| Two Distance Chamfer | `sketch.chamfer.two_distance` | SKETCH › MODIFY | +| Drag Sketch Point | `sketch.move_point` | – | | Offset (O) | `sketch.offset` | SKETCH › MODIFY | | Break Offset Association | `sketch.offset.break` | – | -| Trim (T) | `sketch.trim` | SKETCH › MODIFY | -| Extend | `sketch.extend` | SKETCH › MODIFY | -| Break | `sketch.break` | SKETCH › MODIFY | -| Sketch Scale | `sketch.scale` | SKETCH › MODIFY | -| Move/Copy Sketch Entities | `sketch.move` | SKETCH › MODIFY | -| Mirror | `sketch.mirror` | SKETCH › PATTERN | +| Sketch Palette Options | `sketch.options` | – | +| Paste Sketch Entities | `sketch.paste` | – | | Circular Pattern | `sketch.pattern.circular` | SKETCH › PATTERN | | Rectangular Pattern | `sketch.pattern.rectangular` | SKETCH › PATTERN | +| Point | `sketch.point` | SKETCH › CREATE | +| 3D Point | `sketch.point3d` | – | +| Circumscribed Polygon | `sketch.polygon.circumscribed` | SKETCH › CREATE | +| Edge Polygon | `sketch.polygon.edge` | SKETCH › CREATE | +| Inscribed Polygon | `sketch.polygon.inscribed` | SKETCH › CREATE | | Project (P) | `sketch.project` | SKETCH › CREATE | -| Intersect | `sketch.intersect` | SKETCH › CREATE | -| Include 3D Geometry | `sketch.include_3d` | SKETCH › CREATE | | Project To Surface | `sketch.project_to_surface` | SKETCH › CREATE | -| Intersection Curve | `sketch.intersection_curve` | SKETCH › CREATE | -| Spun Profile | `sketch.spun_profile` | SKETCH › CREATE | -| Isoparametric Curve | `sketch.isoparametric_curve` | SKETCH › CREATE | -| Fit Curves to Mesh Section | `sketch.fit_curves_to_section` | SKETCH › CREATE | -| Break Link | `sketch.break_link` | – | -| Auto-Project Edges on Reference | `sketch.auto_project` | – | +| Center Rectangle | `sketch.rectangle.center` | SKETCH › CREATE | +| Rounded Rectangle | `sketch.rectangle.rounded` | SKETCH › CREATE | +| 3-Point Rectangle | `sketch.rectangle.three_point` | SKETCH › CREATE | +| 2-Point Rectangle (R) | `sketch.rectangle.two_point` | SKETCH › CREATE | | Redefine Sketch Plane | `sketch.redefine` | – | -| Copy Sketch Entities | `sketch.copy` | – | -| Cut Sketch Entities | `sketch.cut` | – | -| Paste Sketch Entities | `sketch.paste` | – | -| Inspect Sketch | `sketch.inspect` | – | +| Sketch Scale | `sketch.scale` | SKETCH › MODIFY | +| Center Point Arc Slot | `sketch.slot.arc_center` | SKETCH › CREATE | +| Three Point Arc Slot | `sketch.slot.arc_three_point` | SKETCH › CREATE | +| Center Point Slot | `sketch.slot.center_point` | SKETCH › CREATE | +| Center to Center Slot | `sketch.slot.center_to_center` | SKETCH › CREATE | +| Overall Slot | `sketch.slot.overall` | SKETCH › CREATE | +| Snap Inference | `sketch.snap` | – | +| Solve Sketch | `sketch.solve` | – | +| Control Point Spline | `sketch.spline.control_point` | SKETCH › CREATE | +| Control Point Spline (Degree 5) | `sketch.spline.control_point_5` | SKETCH › CREATE | +| Fit Point Spline | `sketch.spline.fit_point` | SKETCH › CREATE | +| 3D Spline | `sketch.spline3d` | – | +| Spun Profile | `sketch.spun_profile` | SKETCH › CREATE | +| Text | `sketch.text` | SKETCH › CREATE | +| Toggle Driven Dimension | `sketch.toggle_driven` | – | +| Trim (T) | `sketch.trim` | SKETCH › MODIFY | -## Solid modelling (35) +## Solid modelling | Command | Id | Toolbar | |---|---|---| -| Extrude (E) | `solid.extrude` | SOLID › CREATE | -| Revolve | `solid.revolve` | SOLID › CREATE | -| Sweep | `solid.sweep` | SOLID › CREATE | -| Loft | `solid.loft` | SOLID › CREATE | +| Align | `solid.align` | SOLID › MODIFY | +| Boundary Fill | `solid.boundary_fill` | SOLID › CREATE | +| Bounding Solid | `solid.bounding_solid` | SOLID › CREATE | | Box | `solid.box` | SOLID › CREATE | -| Cylinder | `solid.cylinder` | SOLID › CREATE | -| Sphere | `solid.sphere` | SOLID › CREATE | -| Torus | `solid.torus` | SOLID › CREATE | -| Fillet (F) | `solid.fillet` | SOLID › MODIFY | | Chamfer | `solid.chamfer` | SOLID › MODIFY | +| Coil | `solid.coil` | SOLID › CREATE | | Combine | `solid.combine` | SOLID › MODIFY | -| Rectangular Pattern | `solid.pattern.rectangular` | SOLID › CREATE | +| Cylinder | `solid.cylinder` | SOLID › CREATE | +| Draft | `solid.draft` | SOLID › MODIFY | +| Emboss | `solid.emboss` | SOLID › CREATE | +| Extrude (E) | `solid.extrude` | SOLID › CREATE | +| Fillet (F) | `solid.fillet` | SOLID › MODIFY | +| Hole (H) | `solid.hole` | SOLID › CREATE | +| Loft | `solid.loft` | SOLID › CREATE | +| Mirror | `solid.mirror` | SOLID › CREATE | +| Move/Copy (M) | `solid.move` | SOLID › MODIFY | +| Offset Face | `solid.offset_face` | SOLID › MODIFY | | Circular Pattern | `solid.pattern.circular` | SOLID › CREATE | | Pattern on Path | `solid.pattern.path` | SOLID › CREATE | -| Mirror | `solid.mirror` | SOLID › CREATE | -| Hole (H) | `solid.hole` | SOLID › CREATE | +| Rectangular Pattern | `solid.pattern.rectangular` | SOLID › CREATE | | Pipe | `solid.pipe` | SOLID › CREATE | -| Bounding Solid | `solid.bounding_solid` | SOLID › CREATE | -| Scale | `solid.scale` | SOLID › MODIFY | -| Offset Face | `solid.offset_face` | SOLID › MODIFY | -| Thread | `solid.thread` | SOLID › CREATE | -| Shell | `solid.shell` | SOLID › MODIFY | -| Draft | `solid.draft` | SOLID › MODIFY | -| Split Face | `solid.split_face` | SOLID › MODIFY | -| Split Body | `solid.split_body` | SOLID › MODIFY | | Press Pull (Q) | `solid.press_pull` | SOLID › MODIFY | -| Move/Copy (M) | `solid.move` | SOLID › MODIFY | -| Boundary Fill | `solid.boundary_fill` | SOLID › CREATE | -| Coil | `solid.coil` | SOLID › CREATE | -| Rib | `solid.rib` | SOLID › CREATE | -| Web | `solid.web` | SOLID › CREATE | -| Emboss | `solid.emboss` | SOLID › CREATE | -| Replace Face | `solid.replace_face` | SOLID › MODIFY | -| Align | `solid.align` | SOLID › MODIFY | | Remove | `solid.remove` | SOLID › MODIFY | +| Replace Face | `solid.replace_face` | SOLID › MODIFY | +| Revolve | `solid.revolve` | SOLID › CREATE | +| Rib | `solid.rib` | SOLID › CREATE | +| Scale | `solid.scale` | SOLID › MODIFY | +| Shell | `solid.shell` | SOLID › MODIFY | +| Sphere | `solid.sphere` | SOLID › CREATE | +| Split Body | `solid.split_body` | SOLID › MODIFY | +| Split Face | `solid.split_face` | SOLID › MODIFY | +| Sweep | `solid.sweep` | SOLID › CREATE | +| Thread | `solid.thread` | SOLID › CREATE | +| Torus | `solid.torus` | SOLID › CREATE | +| Web | `solid.web` | SOLID › CREATE | -## Surfaces (18, 1 planned) +## Surfaces | Command | Id | Toolbar | |---|---|---| -| Boundary Surface | `surface.boundary` | SURFACE › CREATE | -| Patch | `surface.patch` | SURFACE › CREATE | -| Stitch | `surface.stitch` | SURFACE › MODIFY | -| Thicken | `surface.thicken` | SURFACE › CREATE | -| Extend | `surface.extend` | SURFACE › MODIFY | -| Trim | `surface.trim` | SURFACE › MODIFY | -| Surface Extrude | `surface.extrude` | SURFACE › CREATE | -| Surface Revolve | `surface.revolve` | SURFACE › CREATE | -| Surface Sweep | `surface.sweep` | SURFACE › CREATE | -| Surface Loft | `surface.loft` | SURFACE › CREATE | -| Offset Surface | `surface.offset` | SURFACE › CREATE | -| Ruled Surface | `surface.ruled` | SURFACE › CREATE | | Blend Surface | `surface.blend` | SURFACE › CREATE | -| Untrim | `surface.untrim` | SURFACE › MODIFY | -| Unstitch | `surface.unstitch` | SURFACE › MODIFY | -| Reverse Normal | `surface.reverse_normal` | SURFACE › MODIFY | +| Boundary Surface | `surface.boundary` | SURFACE › CREATE | +| Extend | `surface.extend` | SURFACE › MODIFY | +| Surface Extrude | `surface.extrude` | SURFACE › CREATE | | Fair Surface | `surface.fair` | SURFACE › MODIFY | | Surface Fillet *(planned: [#769](https://github.com/bherbruck/solidcraft/issues/769))* | `surface.fillet` | SURFACE › MODIFY | +| Surface Loft | `surface.loft` | SURFACE › CREATE | | Match Surface | `surface.match` | SURFACE › MODIFY | +| Offset Surface | `surface.offset` | SURFACE › CREATE | +| Patch | `surface.patch` | SURFACE › CREATE | +| Reverse Normal | `surface.reverse_normal` | SURFACE › MODIFY | +| Surface Revolve | `surface.revolve` | SURFACE › CREATE | +| Ruled Surface | `surface.ruled` | SURFACE › CREATE | +| Stitch | `surface.stitch` | SURFACE › MODIFY | +| Surface Sweep | `surface.sweep` | SURFACE › CREATE | +| Thicken | `surface.thicken` | SURFACE › CREATE | +| Trim | `surface.trim` | SURFACE › MODIFY | +| Unstitch | `surface.unstitch` | SURFACE › MODIFY | +| Untrim | `surface.untrim` | SURFACE › MODIFY | -## Construction geometry (19) +## Construction geometry | Command | Id | Toolbar | |---|---|---| -| Offset Plane | `construct.plane.offset` | SOLID › CONSTRUCT | -| Plane at Angle | `construct.plane.at_angle` | SOLID › CONSTRUCT | -| Axis Through Cylinder/Cone/Torus | `construct.axis.through_cylinder` | SOLID › CONSTRUCT | +| Axis Through Edge | `construct.axis.edge` | SOLID › CONSTRUCT | | Axis Perpendicular To Face | `construct.axis.normal_to_face` | SOLID › CONSTRUCT | +| Axis Through Cylinder/Cone/Torus | `construct.axis.through_cylinder` | SOLID › CONSTRUCT | | Axis Through Two Planes | `construct.axis.two_planes` | SOLID › CONSTRUCT | | Axis Through Two Points | `construct.axis.two_points` | SOLID › CONSTRUCT | -| Axis Through Edge | `construct.axis.edge` | SOLID › CONSTRUCT | -| Point At Vertex | `construct.point.vertex` | SOLID › CONSTRUCT | -| Point Through Two Edges | `construct.point.two_edges` | SOLID › CONSTRUCT | -| Point Through Three Planes | `construct.point.three_planes` | SOLID › CONSTRUCT | +| Plane Along Path | `construct.plane.along_path` | SOLID › CONSTRUCT | +| Plane at Angle | `construct.plane.at_angle` | SOLID › CONSTRUCT | +| Midplane | `construct.plane.midplane` | SOLID › CONSTRUCT | +| Offset Plane | `construct.plane.offset` | SOLID › CONSTRUCT | +| Perpendicular Plane | `construct.plane.perpendicular` | SOLID › CONSTRUCT | +| Tangent Plane | `construct.plane.tangent` | SOLID › CONSTRUCT | +| Plane Through Three Points | `construct.plane.three_points` | SOLID › CONSTRUCT | +| Plane Through Two Edges | `construct.plane.two_edges` | SOLID › CONSTRUCT | +| Point Along Path | `construct.point.along_path` | SOLID › CONSTRUCT | | Point At Center Of Circle/Sphere/Torus | `construct.point.center` | SOLID › CONSTRUCT | | Point At Edge And Plane | `construct.point.edge_plane` | SOLID › CONSTRUCT | -| Point Along Path | `construct.point.along_path` | SOLID › CONSTRUCT | -| Midplane | `construct.plane.midplane` | SOLID › CONSTRUCT | -| Plane Through Two Edges | `construct.plane.two_edges` | SOLID › CONSTRUCT | -| Plane Through Three Points | `construct.plane.three_points` | SOLID › CONSTRUCT | -| Tangent Plane | `construct.plane.tangent` | SOLID › CONSTRUCT | -| Plane Along Path | `construct.plane.along_path` | SOLID › CONSTRUCT | -| Perpendicular Plane | `construct.plane.perpendicular` | SOLID › CONSTRUCT | +| Point Through Three Planes | `construct.point.three_planes` | SOLID › CONSTRUCT | +| Point Through Two Edges | `construct.point.two_edges` | SOLID › CONSTRUCT | +| Point At Vertex | `construct.point.vertex` | SOLID › CONSTRUCT | -## Sheet metal (12) +## Sheet metal | Command | Id | Toolbar | |---|---|---| -| Flange | `sheet.flange` | SHEET METAL › CREATE | -| Perforate | `sheet.perforate` | SHEET METAL › CREATE | -| Hem | `sheet.hem` | SHEET METAL › CREATE | -| Fold | `sheet.fold` | SHEET METAL › CREATE | -| Unfold | `sheet.unfold` | SHEET METAL › MODIFY | -| Refold | `sheet.refold` | SHEET METAL › MODIFY | | Convert to Sheet Metal | `sheet.convert` | SHEET METAL › CREATE | -| Sheet Metal Rules | `sheet.manage_rules` | SHEET METAL › MODIFY | -| List Sheet Metal Rules | `sheet.rules` | – | -| Create Flat Pattern | `sheet.flat_pattern` | SHEET METAL › CREATE | -| Export Flat Pattern as DXF | `sheet.export_dxf` | – | | Export Bend Table | `sheet.export_bend_table` | – | +| Export Flat Pattern as DXF | `sheet.export_dxf` | – | +| Flange | `sheet.flange` | SHEET METAL › CREATE | +| Create Flat Pattern | `sheet.flat_pattern` | SHEET METAL › CREATE | +| Fold | `sheet.fold` | SHEET METAL › CREATE | +| Hem | `sheet.hem` | SHEET METAL › CREATE | +| Sheet Metal Rules | `sheet.manage_rules` | SHEET METAL › MODIFY | +| Perforate | `sheet.perforate` | SHEET METAL › CREATE | +| Refold | `sheet.refold` | SHEET METAL › MODIFY | +| List Sheet Metal Rules | `sheet.rules` | – | +| Unfold | `sheet.unfold` | SHEET METAL › MODIFY | -## Plastic parts (7) +## Plastic parts | Command | Id | Toolbar | |---|---|---| +| Assign Plastic Rule | `plastic.assign_rule` | PLASTIC › SETUP | | Boss | `plastic.boss` | PLASTIC › CREATE | | Lip | `plastic.lip` | PLASTIC › CREATE | -| Snap Fit | `plastic.snap_fit` | PLASTIC › CREATE | -| Rest | `plastic.rest` | PLASTIC › CREATE | | Manage Plastic Rules | `plastic.manage_rules` | PLASTIC › SETUP | -| Assign Plastic Rule | `plastic.assign_rule` | PLASTIC › SETUP | +| Rest | `plastic.rest` | PLASTIC › CREATE | | List Plastic Rules | `plastic.rules` | – | +| Snap Fit | `plastic.snap_fit` | PLASTIC › CREATE | -## Components (17) +## Components | Command | Id | Toolbar | |---|---|---| -| New Component | `component.create` | SOLID › ASSEMBLE | -| Create Components from Bodies | `component.from_bodies` | – | | Activate Component | `component.activate` | – | -| List Components | `component.list` | – | -| Component Physical Properties | `component.properties` | – | -| Rename Component | `component.rename` | – | +| Break Link | `component.break_link` | – | +| Capture Position | `component.capture_position` | SOLID › POSITION | +| New Component | `component.create` | SOLID › ASSEMBLE | | Delete Component | `component.delete` | – | -| Unlock Contents | `component.unlock` | – | +| Create Components from Bodies | `component.from_bodies` | – | +| Insert Design | `component.insert_design` | SOLID › ASSEMBLE | +| List Links | `component.links` | – | +| List Components | `component.list` | – | | Move Bodies to Component | `component.move_bodies` | – | | Move Sketches to Component | `component.move_sketches` | – | | Paste New | `component.paste_new` | – | -| Capture Position | `component.capture_position` | SOLID › POSITION | +| Component Physical Properties | `component.properties` | – | +| Rename Component | `component.rename` | – | | Revert Position | `component.revert_position` | SOLID › POSITION | -| Insert Design | `component.insert_design` | SOLID › ASSEMBLE | +| Unlock Contents | `component.unlock` | – | | Update Links | `component.update_links` | – | -| Break Link | `component.break_link` | – | -| List Links | `component.links` | – | -## Assembly joints (16) +## Assembly joints | Command | Id | Toolbar | |---|---|---| -| Joint Origin | `joint.origin` | SOLID › CREATE | -| Joint (J) | `joint.create` | SOLID › ASSEMBLE | | As-Built Joint | `joint.as_built` | SOLID › ASSEMBLE | -| Rigid Group | `joint.rigid_group` | SOLID › ASSEMBLE | -| Drive Joints | `joint.drive` | SOLID › ASSEMBLE | -| Reach Point | `joint.reach` | – | -| Motion Link | `joint.motion_link` | SOLID › ASSEMBLE | -| Gear | `joint.gear` | SOLID › ASSEMBLE | -| Rack and Pinion | `joint.rack_pinion` | SOLID › ASSEMBLE | -| Screw | `joint.screw` | SOLID › ASSEMBLE | | Cam | `joint.cam` | SOLID › ASSEMBLE | -| Joint Limits | `joint.limits` | – | -| Edit Joint | `joint.edit` | – | +| Joint (J) | `joint.create` | SOLID › ASSEMBLE | | Delete Joint | `joint.delete` | – | +| Drive Joints | `joint.drive` | SOLID › ASSEMBLE | +| Edit Joint | `joint.edit` | – | +| Gear | `joint.gear` | SOLID › ASSEMBLE | +| Joint Limits | `joint.limits` | – | | List Joints | `joint.list` | – | +| Motion Link | `joint.motion_link` | SOLID › ASSEMBLE | +| Joint Origin | `joint.origin` | SOLID › CREATE | +| Rack and Pinion | `joint.rack_pinion` | SOLID › ASSEMBLE | +| Reach Point | `joint.reach` | – | +| Rigid Group | `joint.rigid_group` | SOLID › ASSEMBLE | +| Screw | `joint.screw` | SOLID › ASSEMBLE | | Solve Joints | `joint.solve` | – | -## Configurations (8) +## Configurations | Command | Id | Toolbar | |---|---|---| -| Configure | `config.configure` | SOLID › CONFIGURE | -| Display Configuration Table | `config.table` | SOLID › CONFIGURE | -| Configuration Column | `config.column` | – | -| Configuration Row | `config.row` | – | | Activate Configuration | `config.activate` | – | +| Configuration Column | `config.column` | – | +| Configure | `config.configure` | SOLID › CONFIGURE | | Preview Configuration | `config.preview` | – | +| Configuration Row | `config.row` | – | | Configuration Rule | `config.rule` | – | | Configuration Rules | `config.rules` | – | +| Display Configuration Table | `config.table` | SOLID › CONFIGURE | -## Timeline (21) +## Timeline | Command | Id | Toolbar | |---|---|---| +| Add Recorded Feature | `timeline.add` | – | | Compute All | `timeline.compute_all` | SOLID › MODIFY | +| Copy Features | `timeline.copy` | – | | Delete (Delete) | `timeline.delete` | SOLID › MODIFY | -| Rename | `timeline.rename` | – | +| Feature Dependents | `timeline.dependents` | – | +| Edit Feature | `timeline.edit` | – | +| Export Command Script | `timeline.export_script` | – | | New Feature Folder | `timeline.group` | – | -| Remove Feature Folders | `timeline.ungroup` | – | -| Rename Feature Folder | `timeline.rename_group` | – | -| Move Features to Folder | `timeline.move_to_group` | – | +| Inspect Feature | `timeline.inspect` | – | | Move Timeline Items | `timeline.move_many` | – | -| Move Timeline Marker | `timeline.rollback` | – | -| Roll History Marker | `timeline.roll_to` | – | +| Move Features to Folder | `timeline.move_to_group` | – | +| Paste Features | `timeline.paste` | – | +| Edit Feature | `timeline.redefine` | – | +| Rename | `timeline.rename` | – | +| Rename Feature Folder | `timeline.rename_group` | – | | Reorder Feature | `timeline.reorder` | – | | Reorder Features | `timeline.reorder_many` | – | -| Edit Feature | `timeline.redefine` | – | -| Feature Dependents | `timeline.dependents` | – | +| Roll History Marker | `timeline.roll_to` | – | +| Move Timeline Marker | `timeline.rollback` | – | | Suppress Feature | `timeline.suppress` | – | -| Edit Feature | `timeline.edit` | – | -| Inspect Feature | `timeline.inspect` | – | -| Copy Features | `timeline.copy` | – | -| Paste Features | `timeline.paste` | – | -| Add Recorded Feature | `timeline.add` | – | -| Export Command Script | `timeline.export_script` | – | +| Remove Feature Folders | `timeline.ungroup` | – | -## Inspect (16) +## Inspect | Command | Id | Toolbar | |---|---|---| -| Curvature Comb Analysis | `inspect.curvature_comb` | SKETCH › INSPECT | -| Minimum Radius Analysis | `inspect.minimum_radius` | SKETCH › INSPECT | -| Isocurve Analysis | `inspect.isocurve` | SKETCH › INSPECT | +| Accessibility Analysis | `inspect.accessibility` | SKETCH › INSPECT | | Center of Mass | `inspect.center_of_mass` | SKETCH › INSPECT | -| Zebra Analysis | `inspect.zebra` | SKETCH › INSPECT | +| Clearance | `inspect.clearance` | – | +| Compare Bodies | `inspect.compare` | – | +| Continuity Analysis | `inspect.continuity` | SURFACE › INSPECT | +| Curvature Comb Analysis | `inspect.curvature_comb` | SKETCH › INSPECT | +| Curvature Map Analysis | `inspect.curvature_map` | SKETCH › INSPECT | | Draft Analysis | `inspect.draft` | SKETCH › INSPECT | | Environment Map Analysis | `inspect.environment_map` | SKETCH › INSPECT | -| Accessibility Analysis | `inspect.accessibility` | SKETCH › INSPECT | -| Curvature Map Analysis | `inspect.curvature_map` | SKETCH › INSPECT | -| Continuity Analysis | `inspect.continuity` | SURFACE › INSPECT | | Interference | `inspect.interference` | SOLID › INSPECT | -| Clearance | `inspect.clearance` | – | +| Isocurve Analysis | `inspect.isocurve` | SKETCH › INSPECT | | Measure (I) | `inspect.measure` | SOLID › INSPECT | -| Compare Bodies | `inspect.compare` | – | -| Silhouette | `inspect.silhouette` | – | +| Minimum Radius Analysis | `inspect.minimum_radius` | SKETCH › INSPECT | | Section Analysis | `inspect.section` | SOLID › INSPECT | +| Silhouette | `inspect.silhouette` | – | +| Zebra Analysis | `inspect.zebra` | SKETCH › INSPECT | -## Files (9) +## Files | Command | Id | Toolbar | |---|---|---| -| New Design (Ctrl+N) | `file.new` | – | -| Insert STEP | `file.insert_step` | SOLID › INSERT | +| Export | `file.export` | – | +| Export Current View as DXF | `file.export_view_dxf` | – | | Insert Mesh | `file.insert_mesh` | SOLID › INSERT | +| Insert STEP | `file.insert_step` | SOLID › INSERT | +| New Design (Ctrl+N) | `file.new` | – | | Save (Ctrl+S) | `file.save` | – | | Save As | `file.save_as` | – | -| Export | `file.export` | – | | Save As Mesh | `file.save_mesh` | MESH › MODIFY | | Installed Slicers | `file.slicers` | – | -| Export Current View as DXF | `file.export_view_dxf` | – | -## Documents (4) +## Documents | Command | Id | Toolbar | |---|---|---| | Open (Ctrl+O) | `doc.open` | – | -| Recoverable Designs | `doc.recovery_list` | – | | Recover Design | `doc.recover` | – | | Discard Recovered Design | `doc.recovery_discard` | – | +| Recoverable Designs | `doc.recovery_list` | – | -## Edit (4) +## Edit | Command | Id | Toolbar | |---|---|---| -| Undo (Ctrl+Z) | `edit.undo` | – | -| Redo (Ctrl+Y) | `edit.redo` | – | | Checkpoint | `edit.checkpoint` | – | +| Redo (Ctrl+Y) | `edit.redo` | – | | Restore Checkpoint | `edit.restore_checkpoint` | – | +| Undo (Ctrl+Z) | `edit.undo` | – | -## `appearance.*` (3) +## `appearance.*` | Command | Id | Toolbar | |---|---|---| @@ -372,118 +372,118 @@ SolidCraft's commands by area, generated by `cargo xtask features` from the comm | Appearance Library | `appearance.library` | – | | List Appearances | `appearance.list` | – | -## `body.*` (1) +## `body.*` | Command | Id | Toolbar | |---|---|---| | Rename Body | `body.rename` | – | -## `browser.*` (6) +## `browser.*` | Command | Id | Toolbar | |---|---|---| | New Group | `browser.group` | – | -| Ungroup | `browser.ungroup` | – | -| Rename Group | `browser.rename_group` | – | | Move Browser Items | `browser.move` | – | | Order Browser Items | `browser.order` | – | +| Rename Group | `browser.rename_group` | – | +| Ungroup | `browser.ungroup` | – | | Show/Hide | `browser.visibility` | – | -## `canvas.*` (5) +## `canvas.*` | Command | Id | Toolbar | |---|---|---| -| Canvas | `canvas.insert` | SKETCH › INSERT | -| Decal | `canvas.decal` | SKETCH › INSERT | -| Edit Canvas | `canvas.edit` | SKETCH › INSERT | | Calibrate Canvas | `canvas.calibrate` | – | +| Decal | `canvas.decal` | SKETCH › INSERT | | Delete Canvas | `canvas.delete` | – | +| Edit Canvas | `canvas.edit` | SKETCH › INSERT | +| Canvas | `canvas.insert` | SKETCH › INSERT | -## `contact.*` (7) +## `contact.*` | Command | Id | Toolbar | |---|---|---| -| Enable Contact Sets | `contact.enable_sets` | SOLID › ASSEMBLE | -| Enable All Contact | `contact.enable_all` | SOLID › ASSEMBLE | -| Disable Contact | `contact.disable_all` | SOLID › ASSEMBLE | -| New Contact Set | `contact.create` | SOLID › ASSEMBLE | -| Edit Contact Set | `contact.edit` | – | -| List Contact Sets | `contact.list` | – | | Check Contact | `contact.check` | – | +| New Contact Set | `contact.create` | SOLID › ASSEMBLE | +| Disable Contact | `contact.disable_all` | SOLID › ASSEMBLE | +| Edit Contact Set | `contact.edit` | – | +| Enable All Contact | `contact.enable_all` | SOLID › ASSEMBLE | +| Enable Contact Sets | `contact.enable_sets` | SOLID › ASSEMBLE | +| List Contact Sets | `contact.list` | – | -## `diagnostics.*` (4) +## `diagnostics.*` | Command | Id | Toolbar | |---|---|---| -| Crash Reports | `diagnostics.crash_reports` | – | | Crash Report | `diagnostics.crash_report` | – | +| Crash Reports | `diagnostics.crash_reports` | – | | Delete Crash Reports | `diagnostics.crash_reports.clear` | – | | Crash Test | `diagnostics.crash_test` | – | -## `document.*` (5) +## `document.*` | Command | Id | Toolbar | |---|---|---| -| Change Design Units | `document.units` | – | -| Design Properties | `document.metadata` | – | -| Change Design Properties | `document.metadata.set` | – | -| Remove Design Property | `document.metadata.remove` | – | | Inspect Design | `document.inspect` | – | +| Design Properties | `document.metadata` | – | +| Remove Design Property | `document.metadata.remove` | – | +| Change Design Properties | `document.metadata.set` | – | +| Change Design Units | `document.units` | – | -## `engine.*` (1) +## `engine.*` | Command | Id | Toolbar | |---|---|---| | List Commands | `engine.commands` | – | -## `explode.*` (4) +## `explode.*` | Command | Id | Toolbar | |---|---|---| | Exploded View | `explode.create` | SOLID › ASSEMBLE | -| Show Exploded View | `explode.show` | – | -| List Exploded Views | `explode.list` | – | | Delete Exploded View | `explode.delete` | – | +| List Exploded Views | `explode.list` | – | +| Show Exploded View | `explode.show` | – | -## `expr.*` (1) +## `expr.*` | Command | Id | Toolbar | |---|---|---| | Evaluate Expression | `expr.evaluate` | – | -## `face.*` (1) +## `face.*` | Command | Id | Toolbar | |---|---|---| | Delete Face | `face.delete` | SOLID › MODIFY | -## `library.*` (3) +## `library.*` | Command | Id | Toolbar | |---|---|---| -| Inspect Local Library | `library.inspect` | – | -| Export Design Library | `library.export` | – | | Apply Local Library Entry | `library.apply` | – | +| Export Design Library | `library.export` | – | +| Inspect Local Library | `library.inspect` | – | -## `material.*` (7) +## `material.*` | Command | Id | Toolbar | |---|---|---| | Physical Material | `material.assign` | SOLID › MODIFY | -| List Materials | `material.list` | – | | New Physical Material | `material.create` | – | -| Edit Physical Material | `material.edit` | – | | Delete Physical Material | `material.delete` | – | -| Validate Physical Material Data | `material.properties.validate` | – | +| Edit Physical Material | `material.edit` | – | +| List Materials | `material.list` | – | | Directional Elastic Modulus | `material.properties.directional` | – | +| Validate Physical Material Data | `material.properties.validate` | – | -## `mesh.*` (1) +## `mesh.*` | Command | Id | Toolbar | |---|---|---| | Convert Mesh | `mesh.convert` | – | -## `model.*` (3) +## `model.*` | Command | Id | Toolbar | |---|---|---| @@ -491,92 +491,94 @@ SolidCraft's commands by area, generated by `cargo xtask features` from the comm | List Faces | `model.faces` | – | | List Threads | `model.threads` | – | -## `motion.*` (10) +## `motion.*` | Command | Id | Toolbar | |---|---|---| -| Motion Study | `motion.study` | SOLID › ASSEMBLE | -| Play Motion Study | `motion.play` | – | +| Delete Motion Study | `motion.delete` | – | | Export Motion Study | `motion.export` | – | | Export Motion Animation | `motion.export_animation` | – | -| Motion Trace | `motion.trace` | SOLID › ASSEMBLE | -| Keep Motion Trace | `motion.trace.keep` | – | -| Plot Motion Study | `motion.plot` | – | | Motion Interference | `motion.interference` | – | | List Motion Studies | `motion.list` | – | -| Delete Motion Study | `motion.delete` | – | +| Play Motion Study | `motion.play` | – | +| Plot Motion Study | `motion.plot` | – | +| Motion Study | `motion.study` | SOLID › ASSEMBLE | +| Motion Trace | `motion.trace` | SOLID › ASSEMBLE | +| Keep Motion Trace | `motion.trace.keep` | – | -## `occurrence.*` (4) +## `occurrence.*` | Command | Id | Toolbar | |---|---|---| -| Occurrence Physical Properties | `occurrence.properties` | – | | Paste (Instance) | `occurrence.copy` | – | -| Move Occurrence | `occurrence.move` | – | | Ground | `occurrence.ground` | – | +| Move Occurrence | `occurrence.move` | – | +| Occurrence Physical Properties | `occurrence.properties` | – | -## `parameters.*` (13) +## `parameters.*` | Command | Id | Toolbar | |---|---|---| -| Change Parameters | `parameters.change` | SOLID › MODIFY | -| List Parameters | `parameters.list` | – | | Add User Parameter | `parameters.add` | – | -| Rename Parameter | `parameters.rename` | – | -| Delete Parameter | `parameters.delete` | – | -| Favourite Parameter | `parameters.favorite` | – | -| Move Parameter | `parameters.move` | – | +| Change Parameters | `parameters.change` | SOLID › MODIFY | | Comment Parameter | `parameters.comment` | – | -| Parameter Users | `parameters.users` | – | -| Parameter Graph | `parameters.graph` | – | -| Export Parameters | `parameters.export` | – | -| Import Parameters | `parameters.import` | – | | Complete Expression | `parameters.complete` | – | +| Delete Parameter | `parameters.delete` | – | +| Export Parameters | `parameters.export` | – | +| Favourite Parameter | `parameters.favorite` | – | +| Parameter Graph | `parameters.graph` | – | +| Import Parameters | `parameters.import` | – | +| List Parameters | `parameters.list` | – | +| Move Parameter | `parameters.move` | – | +| Rename Parameter | `parameters.rename` | – | +| Parameter Users | `parameters.users` | – | -## `parts.*` (4) +## `parts.*` | Command | Id | Toolbar | |---|---|---| -| Standard Parts | `parts.library` | – | | Insert Fastener | `parts.fastener` | SOLID › INSERT | | Insert Part | `parts.insert` | – | +| Standard Parts | `parts.library` | – | | Change Part Size | `parts.resize` | – | -## `render.*` (10) +## `render.*` | Command | Id | Toolbar | |---|---|---| -| Check Render Request | `render.preflight` | – | -| Render Image | `render.start` | RENDER › IMAGE | -| Render Progress | `render.status` | – | +| Render Backends | `render.backends` | – | | Cancel Render | `render.cancel` | – | | Export Render Image | `render.export` | – | -| Render Backends | `render.backends` | – | -| Render Settings | `render.settings.get` | – | -| Save Render Settings | `render.settings.set` | – | +| Check Render Request | `render.preflight` | – | | Inspect Render Scene | `render.scene` | RENDER › SCENE | | Apply Render Camera | `render.settings.apply` | – | +| Render Settings | `render.settings.get` | – | +| Save Render Settings | `render.settings.set` | – | +| Render Image | `render.start` | RENDER › IMAGE | +| Render Progress | `render.status` | – | -## `select.*` (2) +## `select.*` | Command | Id | Toolbar | |---|---|---| -| Select | `select.set` | – | | Clear Selection | `select.clear` | – | +| Select | `select.set` | – | -## `selection.*` (1) +## `selection.*` | Command | Id | Toolbar | |---|---|---| | Delete | `selection.delete` | – | -## `view.*` (6) +## `view.*` | Command | Id | Toolbar | |---|---|---| -| New Named View | `view.save` | – | -| Rename Named View | `view.rename` | – | -| Delete Named View | `view.delete` | – | -| List Named Views | `view.list` | – | +| Ambient Occlusion | `view.ambient_occlusion` | – | | Restore Named View | `view.apply` | – | +| Delete Named View | `view.delete` | – | +| Graphics Preset | `view.graphics_preset` | – | +| List Named Views | `view.list` | – | | Navigate View | `view.navigate` | – | +| Rename Named View | `view.rename` | – | +| New Named View | `view.save` | – | From 71534117af4c11d7bccbef6088a5f994a583bb28 Mon Sep 17 00:00:00 2001 From: SiroArt <152216922+SiroArt@users.noreply.github.com> Date: Mon, 19 Oct 2026 03:56:28 +0200 Subject: [PATCH 034/225] Mesh a face thinner than the tolerance instead of leaving a hole (#2712) Thanks @SiroArt. --- crates/kernel/src/lib.rs | 2 + crates/kernel/src/thin_face_tests.rs | 43 ++++++ crates/kernel/tests/boolean_props.rs | 9 ++ crates/kernel/tests/tess_loop_fill.rs | 121 ++++++++++++++++ vendor/README.md | 11 ++ vendor/truck-meshalgo/src/tessellation/mod.rs | 2 +- .../src/tessellation/triangulation.rs | 134 ++++++++++++++++++ 7 files changed, 321 insertions(+), 1 deletion(-) create mode 100644 crates/kernel/src/thin_face_tests.rs create mode 100644 crates/kernel/tests/tess_loop_fill.rs diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rs index c75130a8d..429634378 100644 --- a/crates/kernel/src/lib.rs +++ b/crates/kernel/src/lib.rs @@ -132,6 +132,8 @@ mod sweep_rails_tests; mod tangent_cylinders; mod tess; #[cfg(test)] +mod thin_face_tests; +#[cfg(test)] mod thread_display_tests; #[cfg(test)] mod thread_tests; diff --git a/crates/kernel/src/thin_face_tests.rs b/crates/kernel/src/thin_face_tests.rs new file mode 100644 index 000000000..105df4152 --- /dev/null +++ b/crates/kernel/src/thin_face_tests.rs @@ -0,0 +1,43 @@ +//! A face thinner than the tolerance still meshes: the lens of a sphere's patch that pokes out +//! of a box's side has two edges that, sampled coarsely, run along one line in its parameters. +//! The shell's mesh had a hole there. + +use std::collections::HashMap; + +use solidcraft_geom::Vec3; + +use crate::{BoolOp, build::box_solid, build::sphere, ops::boolean}; + +/// Triangle sides in the mesh with no triangle on the other side of them, with the points +/// within a thousandth of a millimetre taken as one. +fn open_sides(mesh: &solidcraft_geom::Mesh) -> usize { + let key = |i: u32| { + let p = mesh.positions[i as usize]; + [p.x, p.y, p.z].map(|c| (c * 1e3).round() as i64) + }; + let mut sides: HashMap<([i64; 3], [i64; 3]), u32> = HashMap::new(); + for t in &mesh.triangles { + for (a, b) in [(t[0], t[1]), (t[1], t[2]), (t[2], t[0])] { + *sides.entry((key(a), key(b))).or_default() += 1; + } + } + sides.keys().filter(|(a, b)| !sides.contains_key(&(*b, *a))).count() +} + +/// The sphere's equator lies in the box's top and its circle on the box's side x = 22.5 dips to +/// z = 24.7, while the edge of the sphere's bottom patch bulges 0.15 mm past that side: a +/// face of about 0.35 mm² between the two. At 1 % of the body it had no triangle. +#[test] +fn a_lens_thinner_than_the_tolerance_is_meshed() { + let a = sphere(Vec3::new(20.0, 10.0, 27.5), 3.75).unwrap(); + let b = box_solid(Vec3::new(15.0, 0.0, 22.5), Vec3::new(22.5, 20.0, 27.5)).unwrap(); + let union = boolean(&a, &b, BoolOp::Union).unwrap().unwrap(); + assert!(union.validity().is_empty(), "{:?}", union.validity()); + let size = union.size(); + for tol in [size * 1e-2, size * 2.5e-3, size * 1e-3] { + let mesh = union.tessellate(tol).unwrap(); + let faces: std::collections::HashSet = mesh.tri_face.iter().copied().collect(); + assert_eq!(faces.len(), union.face_count(), "faces with triangles at {tol}"); + assert_eq!(open_sides(&mesh), 0, "open sides at {tol}"); + } +} diff --git a/crates/kernel/tests/boolean_props.rs b/crates/kernel/tests/boolean_props.rs index db634b332..064d210a4 100644 --- a/crates/kernel/tests/boolean_props.rs +++ b/crates/kernel/tests/boolean_props.rs @@ -303,6 +303,15 @@ fn grid_sphere_box_union_is_sound() { check(identity(&a, &b)); } +/// A small sphere on the top of a thin box: a patch of the sphere sticks out of the box's side +/// by less than the tolerance, a face of about 0.35 mm² that had no triangle when meshed at 1 % of the body. +#[test] +fn grid_small_sphere_thin_box_union_is_sound() { + let a = Prim::Sph { at: [20.0, 10.0, 27.5], r: 3.75 }; + let b = Prim::Box { at: [15.0, 0.0, 22.5], size: [7.5, 20.0, 5.0] }; + check(identity(&a, &b)); +} + /// Two crossing cylinders: the union moved 1000 mm away loses about a tenth of its volume. #[test] #[ignore = "kernel bug, #1649"] diff --git a/crates/kernel/tests/tess_loop_fill.rs b/crates/kernel/tests/tess_loop_fill.rs new file mode 100644 index 000000000..70055f52e --- /dev/null +++ b/crates/kernel/tests/tess_loop_fill.rs @@ -0,0 +1,121 @@ +//! The fallback in the vendored tessellator that triangulates the boundary loop of a face that +//! came out with no triangle (a lens thinner than the tolerance). Its ear clipping is checked on +//! the polygons it can meet: convex, concave, either winding, with collinear points, and loops +//! it must refuse. +//! +//! The vendored crates are outside the workspace, so their own tests never run in CI; the +//! function is reached through the crate's `test-hooks` feature (on only for kernel tests). + +use truck_meshalgo::tessellation::loop_fill_test_hooks::ear_clipping; + +fn area2(points: &[[f64; 2]]) -> f64 { + points.iter().zip(points.iter().cycle().skip(1)).map(|(p, q)| p[0] * q[1] - q[0] * p[1]).sum() +} + +/// The triangles turn the same way as the polygon, there are `n - 2` of them, and they add up to +/// its area: together they cover it once, with no overlap. +fn assert_covers_once(points: &[[f64; 2]]) { + let triangles = ear_clipping(points).expect("a simple polygon is triangulated"); + assert_eq!(triangles.len(), points.len() - 2); + let side = area2(points).signum(); + let mut sum = 0.0; + for t in &triangles { + let t = area2(&t.map(|i| points[i])); + assert!(t * side > 0.0, "a triangle turns the other way, or has no area: {t}"); + sum += t; + } + assert!((sum - area2(points)).abs() < 1e-9, "triangles cover {sum}, the polygon {}", area2(points)); +} + +#[test] +fn a_triangle_is_itself() { + let points = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]; + assert_eq!(ear_clipping(&points), Some(vec![[0, 1, 2]])); +} + +#[test] +fn a_convex_polygon_either_way_round() { + let square = [[0.0, 0.0], [2.0, 0.0], [2.0, 2.0], [0.0, 2.0]]; + assert_covers_once(&square); + let mut reversed = square; + reversed.reverse(); + assert_covers_once(&reversed); +} + +#[test] +fn a_concave_polygon_either_way_round() { + // An L: the reflex corner is at (1, 1). + let l = [[0.0, 0.0], [2.0, 0.0], [2.0, 1.0], [1.0, 1.0], [1.0, 2.0], [0.0, 2.0]]; + assert_covers_once(&l); + let mut reversed = l; + reversed.reverse(); + assert_covers_once(&reversed); +} + +#[test] +fn a_thin_lens_made_of_an_arc_and_a_chord() { + let lens = [[0.0, 0.0], [1.0, -0.15], [2.0, 0.0]]; + assert_covers_once(&lens); + let more = [[0.0, 0.0], [0.5, -0.1], [1.0, -0.15], [1.5, -0.1], [2.0, 0.0]]; + assert_covers_once(&more); +} + +#[test] +fn collinear_points_on_a_side_are_kept_as_corners() { + let square = [[0.0, 0.0], [1.0, 0.0], [2.0, 0.0], [2.0, 2.0], [0.0, 2.0]]; + let triangles = ear_clipping(&square).expect("triangulated"); + assert_eq!(triangles.len(), 3); + let covered: f64 = triangles.iter().map(|t| area2(&t.map(|i| square[i]))).sum(); + assert!((covered - area2(&square)).abs() < 1e-9); +} + +#[test] +fn a_loop_without_area_is_refused() { + assert_eq!(ear_clipping(&[[0.0, 0.0], [1.0, 0.0], [2.0, 0.0]]), None, "three collinear points"); + assert_eq!(ear_clipping(&[[0.0, 0.0], [1.0, 1.0], [0.0, 0.0], [1.0, 1.0]]), None, "a line walked twice"); +} + +#[test] +fn fewer_than_three_points_are_refused() { + assert_eq!(ear_clipping(&[]), None); + assert_eq!(ear_clipping(&[[0.0, 0.0]]), None); + assert_eq!(ear_clipping(&[[0.0, 0.0], [1.0, 0.0]]), None); +} + +/// A loop that crosses itself (the #1648 face pinched to a point is one) would get overlapping +/// triangles, and so a wrong mesh that hides the problem. It is refused, symmetric or not. +#[test] +fn a_loop_crossing_itself_is_refused() { + let bowtie = [[0.0, 0.0], [2.0, 2.0], [2.0, 0.0], [0.0, 2.0]]; + assert_eq!(ear_clipping(&bowtie), None); + let lopsided = [[0.0, 0.0], [3.0, 2.0], [3.0, 0.0], [0.0, 1.0]]; + assert_eq!(ear_clipping(&lopsided), None); + let pinched = [[0.0, 0.0], [5.0, 0.0], [5.0, 0.3], [3.0, -0.1], [2.0, -0.1], [0.0, 0.3]]; + assert_eq!(ear_clipping(&pinched), None); +} + +/// The loop of a face closes on its first point: a point given twice in a row is a corner with no +/// area, and the polygon is still triangulated on the rest. +#[test] +fn a_repeated_point_is_handled_without_a_wrong_mesh() { + let points = [[0.0, 0.0], [2.0, 0.0], [2.0, 2.0], [0.0, 2.0], [0.0, 0.0]]; + if let Some(triangles) = ear_clipping(&points) { + let covered: f64 = triangles.iter().map(|t| area2(&t.map(|i| points[i]))).sum(); + assert!((covered - area2(&points)).abs() < 1e-9, "triangles cover {covered}"); + } +} + +/// The largest loop the fallback takes, as a circle with a bite out of it: all of it is covered +/// exactly once. +#[test] +fn the_largest_loop_is_triangulated() { + let n = 256; + let points: Vec<[f64; 2]> = (0..n) + .map(|i| { + let t = std::f64::consts::TAU * i as f64 / n as f64; + let r = if i % 16 == 0 { 0.6 } else { 1.0 }; + [r * t.cos(), r * t.sin()] + }) + .collect(); + assert_covers_once(&points); +} diff --git a/vendor/README.md b/vendor/README.md index b4622948a..e3a7ff2fb 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -191,6 +191,17 @@ Changes: the face, many degrees round: those triangles cut through the surface and folded over each other (a cone face with a small hole meshed several mm² too large, and the boolean that made it was refused for its volume). +- `tessellation/triangulation.rs`: a face that comes out of the triangulation with no triangle + at all, though the points of its one boundary loop enclose an area in space, is given the + triangles of that loop (ears clipped on the plane of the loop, no point added, so the faces on + either side of its edges still meet it). Its two edges can be different curves that, sampled + as they are, run along the same line in the face's parameters (a lens thinner than the + tolerance), and the loop then has no area there. The shell's mesh had a hole. Faces that + mesh are untouched, and so are preview meshes (they have their own step grid). Only a face + with one loop of at most 256 points is filled, and not one whose loop crosses itself, whose + ears would overlap (the pinched face of #1648 is one): it stays as it was. + `crates/kernel/src/thin_face_tests.rs` holds it, `crates/kernel/tests/tess_loop_fill.rs` the + ear clipping (through the `test-hooks` feature). ## matext4cgmath 0.1.0 (Apache-2.0, © RICOS Co. Ltd., https://github.com/ricosjp/matext4cgmath) diff --git a/vendor/truck-meshalgo/src/tessellation/mod.rs b/vendor/truck-meshalgo/src/tessellation/mod.rs index 6c60fdb37..b51c098b0 100644 --- a/vendor/truck-meshalgo/src/tessellation/mod.rs +++ b/vendor/truck-meshalgo/src/tessellation/mod.rs @@ -524,4 +524,4 @@ mod closed; mod triangulation; #[cfg(feature = "test-hooks")] #[doc(hidden)] -pub use triangulation::include_test_hooks; +pub use triangulation::{include_test_hooks, loop_fill_test_hooks}; diff --git a/vendor/truck-meshalgo/src/tessellation/triangulation.rs b/vendor/truck-meshalgo/src/tessellation/triangulation.rs index cc09e76ab..60b78731e 100644 --- a/vendor/truck-meshalgo/src/tessellation/triangulation.rs +++ b/vendor/truck-meshalgo/src/tessellation/triangulation.rs @@ -967,10 +967,130 @@ fn trimming_with_steps(surface: &S, polyboundary: &PolyBo surface, polyboundary, ); + // 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, + // but sampled as they are, in the face's parameters they run along the same line), left a + // hole in the shell's mesh. Its boundary points are triangulated as they are, so it still + // meets the faces on either side of it. + if steps.is_none() && mesh.faces().is_empty() { + if let Some(filled) = loop_triangles(surface, polyboundary) { + mesh = filled; + } + } mesh.make_face_compatible_to_normal(); mesh } +/// SolidCraft: most points of a loop [`loop_triangles`] triangulates. +const MAX_LOOP_POINTS: usize = 256; + +/// SolidCraft: the triangles of a face's one boundary loop, taken in space on the plane the loop +/// lies near and with no point added, for a face whose parameters give none (see +/// [`trimming_with_steps`]). `None` when the face has several loops, too many points, or no +/// area in space. +fn loop_triangles(surface: &impl ParametricSurface3D, polyline: &PolyBoundary) -> Option { + let [curve] = polyline.0.as_slice() else { return None }; + if !(3..=MAX_LOOP_POINTS).contains(&curve.len()) { + return None; + } + let positions: Vec = curve.iter().map(|p| surface.subs(p.x, p.y)).collect(); + if positions.iter().any(|p| !(p.x.is_finite() && p.y.is_finite() && p.z.is_finite())) { + return None; + } + let normal = newell_normal(&positions); + if normal.magnitude() * 0.5 <= TOLERANCE { + return None; + } + // The loop seen along the axis its normal points along most. + let axis = (0..3).max_by(|&i, &j| normal[i].abs().total_cmp(&normal[j].abs()))?; + let flat: Vec<[f64; 2]> = positions + .iter() + .map(|p| match axis { + 0 => [p.y, p.z], + 1 => [p.z, p.x], + _ => [p.x, p.y], + }) + .collect(); + let triangles: Vec<[StandardVertex; 3]> = ear_clipping(&flat)? + .into_iter() + .filter(|&[a, b, c]| (positions[b] - positions[a]).cross(positions[c] - positions[a]).magnitude() * 0.5 > TOLERANCE) + .map(|corners| corners.map(|i| (i, Some(i), Some(i)).into())) + .collect(); + if triangles.is_empty() { + return None; + } + // The normals orient the triangles ([`NormalFilters::make_face_compatible_to_normal`]). + let normals = curve.iter().map(|p| surface.normal(p.x, p.y)).collect(); + let uv_coords = curve.iter().map(|p| Vector2::new(p.x, p.y)).collect(); + Some(PolygonMesh::debug_new( + StandardAttributes { positions, uv_coords, normals }, + Faces::from_tri_and_quad_faces(triangles, Vec::new()), + )) +} + +/// SolidCraft: twice the vector area of a closed polygon: the direction of its plane, as long as +/// it is large. +fn newell_normal(points: &[Point3]) -> Vector3 { + let next = points.iter().cycle().skip(1); + points.iter().zip(next).fold(Vector3::zero(), |sum, (p, q)| { + sum + Vector3::new((p.y - q.y) * (p.z + q.z), (p.z - q.z) * (p.x + q.x), (p.x - q.x) * (p.y + q.y)) + }) +} + +/// SolidCraft: twice the signed area of the triangle `a b c`: positive when it turns left. +fn turn(a: [f64; 2], b: [f64; 2], c: [f64; 2]) -> f64 { + (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]) +} + +/// SolidCraft: whether two sides of the closed polygon that do not share a corner cross each other. +/// Ears of a polygon that crosses itself overlap, so it is not triangulated. +fn crosses_itself(points: &[[f64; 2]]) -> bool { + let n = points.len(); + let side = |i: usize| (points[i], points[(i + 1) % n]); + (0..n).any(|i| { + let (a, b) = side(i); + (i + 2..n).filter(|&j| !(i == 0 && j == n - 1)).any(|j| { + let (c, d) = side(j); + turn(a, b, c) * turn(a, b, d) < 0.0 && turn(c, d, a) * turn(c, d, b) < 0.0 + }) + }) +} + +/// SolidCraft: the triangles of a simple polygon, as indices into its points, by clipping ears. +/// `None` when no ear is left to clip (the polygon crosses itself) or it has no area. +fn ear_clipping(points: &[[f64; 2]]) -> Option> { + if points.len() < 3 { + return None; + } + let next = points.iter().cycle().skip(1); + let area2: f64 = points.iter().zip(next).map(|(p, q)| p[0] * q[1] - q[0] * p[1]).sum(); + if area2 == 0.0 || crosses_itself(points) { + return None; + } + // Every turn of an ear, and of a point inside it, is on the polygon's own side. + let side = area2.signum(); + let is_ear = |left: &[usize], k: usize| { + let m = left.len(); + let corner = [left[(k + m - 1) % m], left[k], left[(k + 1) % m]]; + let [a, b, c] = corner.map(|i| points[i]); + turn(a, b, c) * side > 0.0 + && left.iter().filter(|q| !corner.contains(q)).all(|&q| { + let p = points[q]; + [turn(a, b, p), turn(b, c, p), turn(c, a, p)].iter().any(|t| t * side < 0.0) + }) + }; + let mut left: Vec = (0..points.len()).collect(); + let mut triangles = Vec::with_capacity(points.len() - 2); + while left.len() > 3 { + let m = left.len(); + let k = (0..m).find(|&k| is_ear(&left, k))?; + triangles.push([left[(k + m - 1) % m], left[k], left[(k + 1) % m]]); + left.remove(k); + } + triangles.push([left[0], left[1], left[2]]); + Some(triangles) +} + /// Inserts parameter divisions into triangulation. fn insert_surface( triangulation: &mut Cdt, @@ -1550,3 +1670,17 @@ pub mod include_test_hooks { assert!(matches!(n, Ok(n) if n > 100_000), "{n:?}"); } } + +/// SolidCraft: the fallback that triangulates a face's boundary loop when the face has no +/// triangle, for kernel tests (the vendored crates' own tests do not run in CI). +/// +/// Not part of the API. Built only for tests, or with the `test-hooks` feature. +#[cfg(any(test, feature = "test-hooks"))] +#[doc(hidden)] +pub mod loop_fill_test_hooks { + /// The triangles of a closed polygon, as indices into its points, or `None` when it has no + /// area, fewer than three points, or crosses itself. + pub fn ear_clipping(points: &[[f64; 2]]) -> Option> { + super::ear_clipping(points) + } +} From 57d210130c5f6cb5a87cd6e61f3ba5886fd3d8a2 Mon Sep 17 00:00:00 2001 From: NOWN-DEV <257771410+NOWN-DEV@users.noreply.github.com> Date: Mon, 19 Oct 2026 04:03:20 +0200 Subject: [PATCH 035/225] Assembly: place an occurrence or an inserted STEP file by a matrix (#1890) (#1901) Thanks @NOWN-DEV. --- crates/engine/src/cmd/component.rs | 39 +++--- crates/engine/src/cmd/component_matrix.rs | 121 ++++++++++++++++++ crates/engine/src/cmd/file.rs | 17 ++- crates/engine/src/cmd/occurrence_tests.rs | 82 ++++++++++++ .../engine/src/tests/step_import_options.rs | 26 ++++ 5 files changed, 268 insertions(+), 17 deletions(-) create mode 100644 crates/engine/src/cmd/component_matrix.rs diff --git a/crates/engine/src/cmd/component.rs b/crates/engine/src/cmd/component.rs index 76733d610..847737fc4 100644 --- a/crates/engine/src/cmd/component.rs +++ b/crates/engine/src/cmd/component.rs @@ -11,6 +11,8 @@ use super::CommandSpec; use crate::params::{bad, bool_, str_, string_list, vec3}; use crate::{Result, Session}; +#[path = "component_matrix.rs"] +pub(super) mod matrix; #[path = "component_properties.rs"] pub(super) mod properties; #[path = "component_transfer.rs"] @@ -52,7 +54,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .params("component (or occurrence): what to place again; path?: validates selected occurrence; parent?: component (default: the same parent); translate?: [x,y,z]. Copies the selected effective transform, including pending moves"), CommandSpec::new("component.paste_new", "Paste New", paste_new).icon("paste").params("component: independently copy its nested definition graph and history, materials and styles; occurrence?, path?: selected source placement; translate?: [x,y,z]. Reassigned external bodies become base geometry; retained external links and omitted boundary joints are reported"), CommandSpec::new("occurrence.move", "Move Occurrence", move_occurrence).icon("move") - .params("occurrence; path?: exact placement; space?: local|world (default local); translate?: [x,y,z]; axis?: [x,y,z], angle?: radians or \"30 deg\", origin?: [x,y,z]; capture?: bool (default true; false keeps it pending until Capture Position). Nested occurrence definitions remain shared"), + .params("occurrence; path?: exact placement; space?: local|world (default local); translate?: [x,y,z]; axis?: [x,y,z], angle?: radians or \"30 deg\", origin?: [x,y,z]; matrix?: [12 or 16 numbers] (instead of translate/axis/angle/origin: a rigid move as a row-major 3x4 rotation-and-translation or 4x4 matrix, flat or as rows; one that is a rotation only up to rounding is orthonormalised, a scale, shear or mirror is refused); tolerance?: largest accepted |RᵀR − I| (default 1e-9, at most 1e-3); capture?: bool (default true; false keeps it pending until Capture Position). Nested occurrence definitions remain shared"), CommandSpec::new("occurrence.ground", "Ground", ground).icon("ground").params("occurrence; grounded?: bool (default toggles)"), CommandSpec::new("component.capture_position", "Capture Position", capture).at("SOLID", "POSITION").icon("capture").params("keeps pending occurrence moves"), CommandSpec::new("component.revert_position", "Revert Position", revert).at("SOLID", "POSITION").icon("revert").noundo().params("occurrences?: [ids] (default all); drops selected pending occurrence moves"), @@ -416,21 +418,28 @@ fn move_occurrence(s: &mut Session, p: &Value) -> Result { let name = s.doc.components.iter().find(|c| c.id == group).map(|c| c.name.clone()).unwrap_or_default(); return Err(bad(cmd, format!("{} is held in {name} by a rigid group: move {name}, or Unlock Contents (component.unlock) first", o.name))); } - let t = move_vector(p, "translate", Vec3::ZERO, true, cmd)?; - let axis = move_vector(p, "axis", Vec3::Z, false, cmd)?; - let angle = match p.get("angle") { - Some(Value::String(e)) => s.doc.eval(e, solidcraft_doc::expr::Kind::Angle).map_err(|e| bad(cmd, e.to_string()))?, - None => 0.0, - Some(value) => value.as_f64().ok_or_else(|| bad(cmd, "angle must be a number or angle expression"))?, + let delta = if let Some(m) = p.get("matrix") { + if let Some(k) = ["translate", "axis", "angle", "origin"].into_iter().find(|k| p.get(*k).is_some()) { + return Err(bad(cmd, format!("give either matrix or {k}, not both"))); + } + matrix::rigid(m, matrix::tolerance(p, cmd)?, cmd)? + } else { + let t = move_vector(p, "translate", Vec3::ZERO, true, cmd)?; + let axis = move_vector(p, "axis", Vec3::Z, false, cmd)?; + let angle = match p.get("angle") { + Some(Value::String(e)) => s.doc.eval(e, solidcraft_doc::expr::Kind::Angle).map_err(|e| bad(cmd, e.to_string()))?, + None => 0.0, + Some(value) => value.as_f64().ok_or_else(|| bad(cmd, "angle must be a number or angle expression"))?, + }; + if !(t.is_finite() && axis.is_finite() && angle.is_finite()) { + return Err(bad(cmd, "non-finite move")); + } + if angle != 0.0 && axis.normalized().is_none() { + return Err(bad(cmd, "rotation axis must have a finite nonzero length")); + } + let origin = move_vector(p, "origin", Vec3::ZERO, true, cmd)?; + solidcraft_doc::rigid(t, origin, axis, angle) }; - if !(t.is_finite() && axis.is_finite() && angle.is_finite()) { - return Err(bad(cmd, "non-finite move")); - } - if angle != 0.0 && axis.normalized().is_none() { - return Err(bad(cmd, "rotation axis must have a finite nonzero length")); - } - let origin = move_vector(p, "origin", Vec3::ZERO, true, cmd)?; - let delta = solidcraft_doc::rigid(t, origin, axis, angle); let space = match p.get("space") { None => "local", Some(Value::String(space)) => space.as_str(), diff --git a/crates/engine/src/cmd/component_matrix.rs b/crates/engine/src/cmd/component_matrix.rs new file mode 100644 index 000000000..b005c820c --- /dev/null +++ b/crates/engine/src/cmd/component_matrix.rs @@ -0,0 +1,121 @@ +//! Placement given as a matrix: a script's 3×4 (rotation rows and a translation column) or +//! 4×4 transform, read as a rigid move. A rotation that is one only up to rounding is +//! orthonormalised; a scale, shear or mirror is refused with the reason (a mirror is +//! `solid.mirror`'s, not a placement's). + +use serde_json::Value; +use solidcraft_doc::{IDENTITY, Mat}; + +use crate::Result; +use crate::params::bad; + +/// The default largest departure from a rotation a matrix may show: |RᵀR − I| per entry. +pub const TOLERANCE: f64 = 1e-9; +/// The loosest tolerance a caller may ask for. +const MAX_TOLERANCE: f64 = 1e-3; + +/// The `tolerance` parameter: the default, or a finite positive number no looser than 1e-3. +pub fn tolerance(p: &Value, cmd: &str) -> Result { + match p.get("tolerance") { + None | Some(Value::Null) => Ok(TOLERANCE), + Some(v) => v + .as_f64() + .filter(|t| t.is_finite() && *t > 0.0 && *t <= MAX_TOLERANCE) + .ok_or_else(|| bad(cmd, format!("tolerance must be a number above 0 and at most {MAX_TOLERANCE}"))), + } +} + +/// Read `matrix` as a rigid transform. It is row-major: 12 numbers (three rows of rotation +/// and translation, `[r00, r01, r02, tx, r10, …, tz]`) or 16 (a fourth row `0, 0, 0, 1`), flat +/// or as rows. +pub fn rigid(v: &Value, tolerance: f64, cmd: &str) -> Result { + let numbers = numbers(v).ok_or_else(|| bad(cmd, "matrix must be 12 numbers (3x4, row by row) or 16 (4x4), flat or as rows"))?; + if numbers.iter().any(|x| !x.is_finite()) { + return Err(bad(cmd, "matrix must contain finite numbers")); + } + let at = |row: usize, col: usize| numbers.get(row * 4 + col).copied().unwrap_or(0.0); + if numbers.len() == 16 { + let last = [at(3, 0), at(3, 1), at(3, 2), at(3, 3) - 1.0]; + if last.iter().any(|x| x.abs() > tolerance) { + return Err(bad(cmd, "matrix is not affine: its fourth row must be 0, 0, 0, 1 (a projective transform is not a placement)")); + } + } + if (0..3).any(|r| at(r, 3).abs() > 1e9) { + return Err(bad(cmd, "matrix translation exceeds supported numeric range")); + } + // r[row][col], then |RᵀR − I| measures how far it is from a rotation. + let r: [[f64; 3]; 3] = std::array::from_fn(|row| std::array::from_fn(|col| at(row, col))); + let deviation = (0..3) + .flat_map(|i| (0..3).map(move |j| (i, j))) + .map(|(i, j)| { + let dot: f64 = (0..3).map(|k| r[k][i] * r[k][j]).sum(); + (dot - if i == j { 1.0 } else { 0.0 }).abs() + }) + .fold(0.0, f64::max); + let det = r[0][0] * (r[1][1] * r[2][2] - r[1][2] * r[2][1]) - r[0][1] * (r[1][0] * r[2][2] - r[1][2] * r[2][0]) + + r[0][2] * (r[1][0] * r[2][1] - r[1][1] * r[2][0]); + if det < 0.0 { + return Err(bad(cmd, "matrix mirrors (its determinant is negative): a placement only turns and moves; mirror bodies with solid.mirror")); + } + if !deviation.is_finite() || deviation > tolerance { + return Err(bad( + cmd, + format!("matrix is not rigid: it scales or shears by {deviation:.3e} (|RᵀR − I|), above the tolerance {tolerance:.0e}"), + )); + } + let rot = orthonormal(r); + let mut m = IDENTITY; + for (col, column) in m.iter_mut().enumerate().take(3) { + for (row, cell) in column.iter_mut().enumerate().take(3) { + *cell = rot[row][col]; + } + } + m[3] = [at(0, 3), at(1, 3), at(2, 3), 1.0]; + Ok(m) +} + +/// The matrix's numbers, row by row: 12 or 16 of them, flat or nested as 3 or 4 rows of 4. +fn numbers(v: &Value) -> Option> { + let a = v.as_array()?; + let flat: Vec = if a.iter().all(Value::is_array) { + if !matches!(a.len(), 3 | 4) { + return None; + } + let mut out = Vec::with_capacity(16); + for row in a { + let row = row.as_array().filter(|r| r.len() == 4)?; + for x in row { + out.push(x.as_f64()?); + } + } + out + } else { + a.iter().map(Value::as_f64).collect::>()? + }; + matches!(flat.len(), 12 | 16).then_some(flat) +} + +/// The rotation nearest to `r` (its polar factor), by Newton's iteration R ← (R + R⁻ᵀ) / 2, +/// which converges quadratically from a near-rotation; a few rounds reach machine precision. +fn orthonormal(mut r: [[f64; 3]; 3]) -> [[f64; 3]; 3] { + for _ in 0..4 { + let Some(inv_t) = inverse_transpose(&r) else { break }; + for (row, inv_row) in r.iter_mut().zip(inv_t) { + for (x, y) in row.iter_mut().zip(inv_row) { + *x = 0.5 * (*x + y); + } + } + } + r +} + +/// (R⁻¹)ᵀ: the cofactor matrix over the determinant. +fn inverse_transpose(r: &[[f64; 3]; 3]) -> Option<[[f64; 3]; 3]> { + let a = |i: usize, j: usize| r[i % 3][j % 3]; + let cof: [[f64; 3]; 3] = std::array::from_fn(|i| std::array::from_fn(|j| a(i + 1, j + 1) * a(i + 2, j + 2) - a(i + 1, j + 2) * a(i + 2, j + 1))); + let det: f64 = (0..3).map(|j| r[0][j] * cof[0][j]).sum(); + if !det.is_finite() || det.abs() < 1e-12 { + return None; + } + Some(cof.map(|row| row.map(|x| x / det))) +} diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 3ccca6b5b..efc83fda1 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -24,7 +24,7 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("file.insert_step", "Insert STEP", insert_step) .at("SOLID", "INSERT") .icon("import") - .params("path: STEP, IGES, FreeCAD .FCStd or Rhino .3dm file (its bodies join the design as an Import base feature in a new component named after the file, placed in the active component; an assembly's products become nested components, a repeated part one component with an occurrence per placement, all held as one rigid group until component.unlock → component, component_name, occurrence, subcomponents?, rigid_joints?); name? (the feature's and the component's); up?: z|y (default z: the file's axes are kept; y: the file has Y up, so the import's component is turned a quarter turn about X, Y becoming Z → stand_up: its occurrence); names?: solid|product|instance (what the bodies are named after: the solid's own name, else the product's (default); the name of the product (part) that holds the body; the name of the assembly occurrence (instance), else the product's)"), + .params("path: STEP, IGES, FreeCAD .FCStd or Rhino .3dm file (its bodies join the design as an Import base feature in a new component named after the file, placed in the active component; an assembly's products become nested components, a repeated part one component with an occurrence per placement, all held as one rigid group until component.unlock → component, component_name, occurrence, subcomponents?, rigid_joints?); name? (the feature's and the component's); up?: z|y (default z: the file's axes are kept; y: the file has Y up, so the import's component is turned a quarter turn about X, Y becoming Z → stand_up: its occurrence); names?: solid|product|instance (what the bodies are named after: the solid's own name, else the product's (default); the name of the product (part) that holds the body; the name of the assembly occurrence (instance), else the product's); matrix?: [12 or 16 numbers] (where the new component's occurrence sits in the active component, after `up`: a rigid row-major 3x4 rotation-and-translation or 4x4 matrix, flat or as rows, as occurrence.move takes it; a scale, shear or mirror is refused before the file is read); tolerance? (see occurrence.move)"), CommandSpec::new("file.insert_mesh", "Insert Mesh", insert_mesh) .at("SOLID", "INSERT") .icon("import") @@ -218,7 +218,20 @@ fn insert_step(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, "only STEP, IGES, FreeCAD and Rhino files (.step, .stp, .igs, .iges, .fcstd, .3dm) can be inserted")); } let options = step_options(p, cmd)?; - add_step(s, path, str_(p, "name"), &options) + let placement = match p.get("matrix") { + None | Some(Value::Null) => None, + Some(m) => Some(super::component::matrix::rigid(m, super::component::matrix::tolerance(p, cmd)?, cmd)?), + }; + let mut out = add_step(s, path, str_(p, "name"), &options)?; + if let Some(m) = placement { + let occ = out["occurrence"].as_u64().ok_or_else(|| EngineError::Other("the import has no placement to move".into()))?; + if let Some(o) = s.doc_mut().occurrences.iter_mut().find(|o| o.id == occ) { + o.transform = solidcraft_doc::mat_mul(&m, &o.transform); + out["transform"] = json!(o.transform); + } + s.refresh(); + } + Ok(out) } fn open(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/occurrence_tests.rs b/crates/engine/src/cmd/occurrence_tests.rs index c88c7f8c2..310a6e8f1 100644 --- a/crates/engine/src/cmd/occurrence_tests.rs +++ b/crates/engine/src/cmd/occurrence_tests.rs @@ -580,3 +580,85 @@ fn compact_component_list_counts_and_skips_identity_transforms() { // Body names on request. assert_eq!(block(&run(&mut s, "component.list", json!({"compact": true, "bodies": true})))["bodies"], json!(["Cube"])); } + +/// A script's 3x4 placement matrix (rotation rows, then the translation column) moves an +/// occurrence exactly as the same turn and move given as an axis, an angle and a translation. +#[test] +fn matrix_move_turns_a_quarter_and_moves() { + let mut s = Session::default(); + let (_, occ) = created(&mut s, "Block"); + run(&mut s, "solid.box", json!({"length": 2, "width": 1, "height": 1})); + // 90 degrees about Z, then (10, 20, 30): (x, y, z) goes to (10 - y, 20 + x, 30 + z). + let r = run(&mut s, "occurrence.move", json!({"occurrence": occ, "matrix": [0, -1, 0, 10, 1, 0, 0, 20, 0, 0, 1, 30]})); + let t = &r["transform"]; + for (col, expected) in [[0.0, 1.0, 0.0, 0.0], [-1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [10.0, 20.0, 30.0, 1.0]].iter().enumerate() { + for (row, x) in expected.iter().enumerate() { + near(&t[col][row], *x); + } + } + // The box's centre (1, 0.5, 0.5) lands at (9.5, 21, 30.5). + let props = run(&mut s, "occurrence.properties", json!({"occurrence": occ})); + for (i, x) in [9.5, 21.0, 30.5].into_iter().enumerate() { + near(&props["total"]["center_of_mass"][i], x); + } + // The same as axis/angle/translate, and the 4x4 form as rows says the same. + let mut other = Session::default(); + let (_, o2) = created(&mut other, "Block"); + let r2 = run(&mut other, "occurrence.move", json!({"occurrence": o2, "axis": [0, 0, 1], "angle": "90 deg", "translate": [10, 20, 30]})); + let mut rows = Session::default(); + let (_, o3) = created(&mut rows, "Block"); + let r3 = run(&mut rows, "occurrence.move", json!({"occurrence": o3, "matrix": [[0, -1, 0, 10], [1, 0, 0, 20], [0, 0, 1, 30], [0, 0, 0, 1]]})); + for col in 0..4 { + for row in 0..4 { + near(&r2["transform"][col][row], t[col][row].as_f64().unwrap()); + near(&r3["transform"][col][row], t[col][row].as_f64().unwrap()); + } + } +} + +/// A rotation that is one only up to rounding is orthonormalised; a scale, a shear or a mirror +/// is refused with the reason, and the occurrence stays where it was. +#[test] +fn matrix_move_orthonormalises_rounding_and_refuses_what_is_not_rigid() { + let mut s = Session::default(); + let (_, occ) = created(&mut s, "Block"); + let (sin, cos) = 30f64.to_radians().sin_cos(); + let e = 3e-10; + let nearly = json!([cos + e, -sin, 0, 5, sin, cos - e, e, 0, 0, -e, 1.0 + e, 0]); + let r = run(&mut s, "occurrence.move", json!({"occurrence": occ, "matrix": nearly, "space": "world"})); + let m: solidcraft_doc::Mat = serde_json::from_value(r["transform"].clone()).unwrap(); + for i in 0..3 { + for j in 0..3 { + let dot: f64 = (0..3).map(|k| m[i][k] * m[j][k]).sum(); + assert!((dot - f64::from(u8::from(i == j))).abs() < 1e-15, "column {i}·{j} = {dot}"); + } + } + assert!((m[0][0] - cos).abs() < 1e-9 && (m[0][1] - sin).abs() < 1e-9 && (m[3][0] - 5.0).abs() < 1e-12, "{m:?}"); + + let before = s.doc.occurrences.iter().find(|o| o.id == occ).unwrap().transform; + let refused = |s: &mut Session, p: Value| s.execute("occurrence.move", &p).unwrap_err().to_string(); + let scaled = refused(&mut s, json!({"occurrence": occ, "matrix": [1.001, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0]})); + assert!(scaled.contains("not rigid") && scaled.contains("2.00"), "{scaled}"); + let sheared = refused(&mut s, json!({"occurrence": occ, "matrix": [1, 0.01, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0]})); + assert!(sheared.contains("not rigid"), "{sheared}"); + let mirrored = refused(&mut s, json!({"occurrence": occ, "matrix": [-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0]})); + assert!(mirrored.contains("solid.mirror"), "{mirrored}"); + let projective = refused(&mut s, json!({"occurrence": occ, "matrix": [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0.5, 0, 0, 1]})); + assert!(projective.contains("fourth row"), "{projective}"); + // A looser tolerance is the caller's to ask for, up to 1e-3. + let rounded = json!([0.866, -0.5, 0, 0, 0.5, 0.866, 0, 0, 0, 0, 1, 0]); + assert!(refused(&mut s, json!({"occurrence": occ, "matrix": rounded})).contains("not rigid")); + for p in [ + json!({"occurrence": occ, "matrix": rounded, "tolerance": 1}), + json!({"occurrence": occ, "matrix": [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], "translate": [1, 0, 0]}), + json!({"occurrence": occ, "matrix": [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0], "translate": [1, 0, 0]}), + json!({"occurrence": occ, "matrix": [1, 0, 0, 1e12, 0, 1, 0, 0, 0, 0, 1, 0]}), + json!({"occurrence": occ, "matrix": [[1, 0, 0, 0], [0, 1, 0, 0]]}), + json!({"occurrence": occ, "matrix": "identity"}), + json!({"occurrence": occ, "matrix": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}), + ] { + assert!(s.execute("occurrence.move", &p).is_err(), "{p}"); + } + assert_eq!(s.doc.occurrences.iter().find(|o| o.id == occ).unwrap().transform, before); + run(&mut s, "occurrence.move", json!({"occurrence": occ, "matrix": rounded, "tolerance": 1e-3})); +} diff --git a/crates/engine/src/tests/step_import_options.rs b/crates/engine/src/tests/step_import_options.rs index 435c4d724..9f5913747 100644 --- a/crates/engine/src/tests/step_import_options.rs +++ b/crates/engine/src/tests/step_import_options.rs @@ -202,3 +202,29 @@ fn the_bodies_are_named_after_the_solid_the_product_or_the_instance() { run(&mut again, "solid.move", json!({"bodies": ["Post-1"], "translate": [0, 0, 5]})); assert_eq!(body_names(&again), ["Plate-1", "Post-1"]); } + +/// `matrix` places the inserted file's component, after `up`, in the same command (one undo +/// step); a matrix that is not rigid is refused before anything is added. +#[test] +fn a_step_file_can_be_inserted_at_a_matrix() { + let path = frame_file("matrix"); + let quarter = json!([0, -1, 0, 100, 1, 0, 0, 0, 0, 0, 1, 0]); + let mut s = Session::default(); + let r = run(&mut s, "file.insert_step", json!({"path": path, "matrix": quarter})); + // (x, y, z) goes to (100 - y, x, z): the frame (0..40, 0..34, 0..20) spans x 66..100, y 0..40. + let (lo, hi) = extent(&s); + assert!(near(lo, [66.0, 0.0, 0.0]) && near(hi, [100.0, 40.0, 20.0]), "{lo:?} {hi:?} {r}"); + assert_eq!(r["transform"][3][0], json!(100.0), "{r}"); + assert_eq!(s.undo.len(), 1); + + // Stood up first ((0..40, -20..0, 0..34)), then turned and moved. + let mut d = Session::default(); + run(&mut d, "file.insert_step", json!({"path": path, "up": "y", "matrix": quarter})); + let (lo, hi) = extent(&d); + assert!(near(lo, [100.0, 0.0, 0.0]) && near(hi, [120.0, 40.0, 34.0]), "{lo:?} {hi:?}"); + + let mut d = Session::default(); + let e = d.execute("file.insert_step", &json!({"path": path, "matrix": [2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0]})).unwrap_err().to_string(); + assert!(e.contains("not rigid"), "{e}"); + assert!(d.doc.features.is_empty() && d.doc.occurrences.is_empty()); +} From c66e33284bebf07a01cc81cef8323320de58834e Mon Sep 17 00:00:00 2001 From: NOWN-DEV <257771410+NOWN-DEV@users.noreply.github.com> Date: Mon, 19 Oct 2026 04:13:13 +0200 Subject: [PATCH 036/225] Joints: offsets, angles and values typed as expressions follow their parameters (#2385) (#2386) Thanks @NOWN-DEV. --- .../src/format/pending/joint-expressions.rs | 4 + crates/doc/src/joints.rs | 142 ++++++++++++++++- crates/doc/src/joints_cam.rs | 1 + crates/doc/src/params.rs | 17 ++ .../src/cmd/component_clone_assembly_tests.rs | 1 + crates/engine/src/cmd/file_import.rs | 1 + crates/engine/src/cmd/joints.rs | 94 ++++++++++- crates/engine/src/cmd/joints_exprs_tests.rs | 146 ++++++++++++++++++ crates/ui-egui/src/dialogs_assembly.rs | 6 +- crates/ui-egui/src/dialogs_assembly_tests.rs | 23 +++ docs/book/src/guide/assemblies.md | 8 + 11 files changed, 432 insertions(+), 11 deletions(-) create mode 100644 crates/doc/src/format/pending/joint-expressions.rs create mode 100644 crates/engine/src/cmd/joints_exprs_tests.rs diff --git a/crates/doc/src/format/pending/joint-expressions.rs b/crates/doc/src/format/pending/joint-expressions.rs new file mode 100644 index 000000000..882b87297 --- /dev/null +++ b/crates/doc/src/format/pending/joint-expressions.rs @@ -0,0 +1,4 @@ +//! A joint keeps the expressions its offset, angle and values were typed as (`exprs`) and works +//! them out again whenever the design changes, so it follows the parameters they name. Older +//! designs need no transformation: a joint without `exprs` keeps its numbers as before. The last +//! release refuses a design saved with this (the newer format number). diff --git a/crates/doc/src/joints.rs b/crates/doc/src/joints.rs index 6aa54eeec..ff84addcd 100644 --- a/crates/doc/src/joints.rs +++ b/crates/doc/src/joints.rs @@ -260,6 +260,92 @@ pub struct Joint { pub angle: f64, #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub suppressed: bool, + /// The expressions the offset, the angle and the values were typed as: they are worked out + /// again whenever the design changes, so a joint follows the parameters it is defined by. + #[serde(default, skip_serializing_if = "JointExprs::is_empty")] + pub exprs: JointExprs, +} + +/// Expressions a joint's numbers follow (over the design's parameters): the offset (a length), +/// the angle and each value (angles or lengths as the joint's values are). A number typed in +/// place of one drops it. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct JointExprs { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub offset: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub angle: Option, + /// By value index, as in `Joint::values`. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub values: Vec>, +} + +impl JointExprs { + pub fn is_empty(&self) -> bool { + self.offset.is_none() && self.angle.is_none() && self.values.iter().all(Option::is_none) + } + + /// The expression value `i` follows. + pub fn value(&self, i: usize) -> Option<&str> { + self.values.get(i).and_then(Option::as_deref) + } + + /// Value `i` follows `e` (or nothing). + pub fn set_value(&mut self, i: usize, e: Option) { + if e.is_some() && self.values.len() <= i { + self.values.resize(i + 1, None); + } + if let Some(slot) = self.values.get_mut(i) { + *slot = e; + } + while self.values.last().is_some_and(Option::is_none) { + self.values.pop(); + } + } +} + +/// Largest offset or value an expression may give a joint (mm, or radians for an angle). +const MAX_EXPR_VALUE: f64 = 1e9; + +/// A joint's offset, angle and values worked out from its expressions (those without one keep +/// their numbers), or why one can't be: an unknown name, a wrong unit, or a number too large. +pub fn expressed(doc: &Document, j: &Joint) -> Result<(f64, f64, Vec)> { + let eval = |e: &str, kind: crate::expr::Kind, what: &str| -> Result { + let v = doc.eval(e, kind).map_err(|err| DocError::Invalid(format!("joint {}: {what} `{e}`: {err}", j.name)))?; + if v.is_finite() && v.abs() < MAX_EXPR_VALUE { Ok(v) } else { Err(DocError::Invalid(format!("joint {}: {what} `{e}` gives {v}", j.name))) } + }; + let x = &j.exprs; + let offset = match &x.offset { + Some(e) => eval(e, crate::expr::Kind::Length, "offset")?, + None => j.offset, + }; + let angle = match &x.angle { + Some(e) => eval(e, crate::expr::Kind::Angle, "angle")?, + None => j.angle, + }; + let mut values = j.values.clone(); + for (i, e) in x.values.iter().enumerate().take(j.kind.dofs().len()) { + let Some(e) = e else { continue }; + let kind = if j.kind.is_angle(i) { crate::expr::Kind::Angle } else { crate::expr::Kind::Length }; + let name = j.kind.dofs().get(i).copied().unwrap_or("value"); + let v = eval(e, kind, name)?; + if values.len() <= i { + values.resize(i + 1, 0.0); + } + if let Some(slot) = values.get_mut(i) { + *slot = v; + } + } + Ok((offset, angle, values)) +} + +/// Values the loop solver leaves alone: those a motion link sets and those an expression does. +fn set_values(asm: &Assembly) -> BTreeSet<(u64, usize)> { + let mut set: BTreeSet<(u64, usize)> = asm.links.iter().map(|l| (l.b, l.ib)).collect(); + for j in &asm.joints { + set.extend(j.exprs.values.iter().enumerate().filter(|(_, e)| e.is_some()).map(|(i, _)| (j.id, i))); + } + set } /// Value of joint `b` (index `ib`) = ratio · value of joint `a` (index `ia`) + offset, or for a @@ -446,6 +532,49 @@ pub struct Assembly { } impl Assembly { + /// Every expression the joints and motion links keep, with the joint (or the driven joint of + /// a link) and what it sets: `offset`, `angle`, a value's name, or a coupling's length. + pub fn exprs(&self) -> Vec<(u64, String, &str)> { + let mut out = Vec::new(); + for j in &self.joints { + let x = &j.exprs; + out.extend(x.offset.as_deref().map(|e| (j.id, "offset".to_string(), e))); + out.extend(x.angle.as_deref().map(|e| (j.id, "angle".to_string(), e))); + for (i, e) in x.values.iter().enumerate() { + if let Some(e) = e { + out.push((j.id, j.kind.dofs().get(i).copied().unwrap_or("value").to_string(), e.as_str())); + } + } + } + for l in &self.links { + for s in l.coupling.as_ref().map(Coupling::sizes).unwrap_or_default() { + if let Size::Expr(e) = s { + out.push((l.b, "coupling".to_string(), e.as_str())); + } + } + } + out + } + + /// The expressions of `exprs`, to rewrite (a renamed parameter). + pub fn exprs_mut(&mut self) -> Vec<&mut String> { + let mut out = Vec::new(); + for j in &mut self.joints { + let x = &mut j.exprs; + out.extend(x.offset.as_mut()); + out.extend(x.angle.as_mut()); + out.extend(x.values.iter_mut().flatten()); + } + for l in &mut self.links { + for s in l.coupling.as_mut().map(Coupling::sizes_mut).unwrap_or_default() { + if let Size::Expr(e) = s { + out.push(e); + } + } + } + out + } + pub fn is_empty(&self) -> bool { self.joints.is_empty() && self.origins.is_empty() @@ -858,7 +987,7 @@ fn close_loops(tree: &Tree, closing: &[u64], asm: &Assembly, held: &Held, vals: if closing.len() > MAX_LOOPS { return (Values::new(), stuck); } - let linked: BTreeSet<(u64, usize)> = asm.links.iter().map(|l| (l.b, l.ib)).collect(); + let linked = set_values(asm); let groups = loop_groups(tree, closing, asm, &linked); let spent = std::cell::Cell::new(0usize); for (group, around, touches) in &groups { @@ -1053,7 +1182,7 @@ fn loop_dof(tree: &Tree, closing: &[u64], asm: &Assembly, vals: &Values, dof: &m if closing.len() > MAX_LOOPS { return; } - let linked: BTreeSet<(u64, usize)> = asm.links.iter().map(|l| (l.b, l.ib)).collect(); + let linked = set_values(asm); let groups = loop_groups(tree, closing, asm, &linked); // The joints loops depend on: those around them, those whose values they read, and those a // motion link carries any of these values into. @@ -1466,6 +1595,14 @@ fn build<'a>(doc: &'a Document, st: &ModelState, vals: &Values, sol: &mut Soluti // Joint frames in component coordinates (errors leave the joint out). let mut frames: BTreeMap = BTreeMap::new(); for j in &joints { + // A joint whose expressions can't be worked out (a parameter gone) is left out rather + // than placed by numbers that no longer say what it was defined by. + if !j.exprs.is_empty() + && let Err(e) = expressed(doc, j) + { + sol.errors.push((j.id, j.name.clone(), e.to_string())); + continue; + } match (resolve_origin(doc, st, &j.a), resolve_origin(doc, st, &j.b)) { (Ok(fa), Ok(fb)) => { frames.insert(j.id, (fa, fb)); @@ -1631,6 +1768,7 @@ mod tests { offset: 0.0, angle: 0.0, suppressed: false, + exprs: Default::default(), }) .collect(); let links = diff --git a/crates/doc/src/joints_cam.rs b/crates/doc/src/joints_cam.rs index 6d8454ae5..e0ad1095d 100644 --- a/crates/doc/src/joints_cam.rs +++ b/crates/doc/src/joints_cam.rs @@ -967,6 +967,7 @@ mod tests { offset: 0.0, angle: 0.0, suppressed: false, + exprs: Default::default(), }; let occ = |id: u64, grounded: bool| crate::Occurrence { id, component: id, parent: 0, name: format!("O{id}"), transform: IDENTITY, grounded }; // 1 frame (grounded), 2 cam, 3-6 a rigid chain to the guide 7, 8 the piston, 9 crank, 10 rod. diff --git a/crates/doc/src/params.rs b/crates/doc/src/params.rs index 76ab07461..25e0fc2c4 100644 --- a/crates/doc/src/params.rs +++ b/crates/doc/src/params.rs @@ -486,6 +486,9 @@ pub enum ParamUser { Dimension { feature: u64, name: String, constraint: String }, /// A configured column or an expression saved in a configuration row. Configuration { row: Option, column: String }, + /// A joint's offset, angle or value, or a motion link's gear, rack or screw length (`input` + /// says which; a link is named by the joint it drives). + Joint { joint: u64, name: String, input: String }, } impl ParamUser { @@ -498,6 +501,7 @@ impl ParamUser { Some(row) => format!("configuration `{row}` ({column})"), None => format!("configuration column {column}"), }, + ParamUser::Joint { name, input, .. } => format!("joint {name} ({input})"), } } } @@ -615,6 +619,12 @@ impl Document { } } } + for (joint, input, e) in self.assembly.exprs() { + if expr::references(e).iter().any(|r| r == name) { + let jname = self.assembly.joints.iter().find(|j| j.id == joint).map(|j| j.name.clone()).unwrap_or_else(|| joint.to_string()); + out.push(ParamUser::Joint { joint, name: jname, input }); + } + } out } @@ -719,6 +729,13 @@ impl Document { } } } + for e in self.assembly.exprs_mut() { + let r = expr::rename_reference(e, old, new); + if r != *e { + *e = r; + n += 1; + } + } if let Some(c) = self.param_comments.remove(old) { self.param_comments.insert(new.to_string(), c); } diff --git a/crates/engine/src/cmd/component_clone_assembly_tests.rs b/crates/engine/src/cmd/component_clone_assembly_tests.rs index da1d30998..cb0a2e08e 100644 --- a/crates/engine/src/cmd/component_clone_assembly_tests.rs +++ b/crates/engine/src/cmd/component_clone_assembly_tests.rs @@ -22,6 +22,7 @@ fn joint(id: u64, a: u64, b: u64) -> Joint { offset: 2.0, angle: 0.1, suppressed: false, + exprs: Default::default(), } } diff --git a/crates/engine/src/cmd/file_import.rs b/crates/engine/src/cmd/file_import.rs index 399b4f5df..f1cd7fe35 100644 --- a/crates/engine/src/cmd/file_import.rs +++ b/crates/engine/src/cmd/file_import.rs @@ -369,6 +369,7 @@ fn add_rigid_joints(s: &mut Session, pairs: &[(u64, u64, Mat)]) -> Result\"; end?, x? as joint.origin} | origin name); \ values?: [angles in deg or expressions, distances]; limits?: [[min, max] | null…]; flip?: bool (default false: the origins are mated, \ b's z against a's as two faces meet; true: b's z along a's, so two origins given at one point with the same z stay as they are); \ - offset?; angle?; name?; quiet?: bool (leave out dof and fixed)", + offset?: mm or an expression; angle?: deg or an expression; name?; quiet?: bool (leave out dof and fixed). An expression (text) is \ + kept with the joint and worked out again whenever the design changes, so the joint follows the parameters it names; a joint whose \ + expression no longer works out (a parameter deleted) is left out of the solve with the reason in its errors", ), CommandSpec::new("joint.as_built", "As-Built Joint", as_built).at("SOLID", "ASSEMBLE").icon("as_built").params( "type, a: occurrence, b: occurrence (stay where they are); at?: joint origin (default: b's origin) — the joint's frame; \ @@ -31,7 +33,7 @@ pub static COMMANDS: &[CommandSpec] = &[ ), CommandSpec::new("joint.rigid_group", "Rigid Group", rigid_group).at("SOLID", "ASSEMBLE").icon("rigid_group").params("occurrences: [ids or names] (move together, as they are)"), CommandSpec::new("joint.drive", "Drive Joints", drive).at("SOLID", "ASSEMBLE").icon("drive").params( - "joint: id|name; value | values: [angles in deg or expressions, distances] (values not given keep theirs; clamped to the limits; the other joints of a \ + "joint: id|name; value | values: [angles in deg or expressions, distances] (values not given keep theirs; a value driven drops the expression joint.create gave it; clamped to the limits; the other joints of a \ closed loop follow, and the motion stops where the loop can no longer close → stopped_by_loop); quiet?: bool (leave out dof \ and fixed) → values: [{name, value, unit: deg|mm, limits}] as joint.list gives them; moved: whether any occurrence moved; \ reason: why the joint can move nothing (suppressed, its origins lost, or its chain joined to nothing grounded → unconnected: \ @@ -65,10 +67,12 @@ pub static COMMANDS: &[CommandSpec] = &[ "a: the cam's joint (revolute); b: the follower's joint, a slider (a translating follower) or a revolute (an oscillating one), b driven by a; profile: {sketch: id|name, index?: the profile (default: the largest)} | {edges: [[x,y,z]…] (points on edges of the cam's bodies forming one closed loop, world), occurrence?}: the cam's outline, in a plane square to its axis, read again whenever the design changes; follower?: knife|roller|flat (default knife; flat: a face square to a slider's line); radius?: the roller's radius (mm, an expression or {circle: [x,y,z], occurrence?}: the roller's round face, which is its tip too); tip?: a joint origin where the follower touches: its knife's point or its roller's centre, such as {circle: [x,y,z]} on the roller (needed for an oscillating follower; a translating one's line runs through it, by default along its slider's axis); flip?: bool (ride the cam from the other side than the one the follower is on now); link?: index (replace that motion link) → link, lift: {min, max, rise, unit} (b's travel over a turn of the cam), reverse (the side it rides from), follower_offset (mm: how far a translating follower's line passes from the cam's axis); b keeps where it is", ), CommandSpec::new("joint.limits", "Joint Limits", limits).icon("joint").params("joint; index?: value index (default 0); min?, max? (omit both to clear)"), - CommandSpec::new("joint.edit", "Edit Joint", edit).icon("edit").params("joint; type?, flip?, offset?, angle?, suppressed?, name?"), + CommandSpec::new("joint.edit", "Edit Joint", edit) + .icon("edit") + .params("joint; type?, flip?, offset?, angle? (a number, or an expression the joint then follows), suppressed?, name?"), CommandSpec::new("joint.delete", "Delete Joint", delete).icon("delete").params("joint: id|name (or origin: name, link: index)"), CommandSpec::new("joint.list", "List Joints", list).icon("list").noundo().params( - "→ joints (type, occurrences, values, limits), origins, links, degrees of freedom, conflicts, floating: [{occurrences, joints}] \ + "→ joints (type, occurrences, values, limits; expressions: {offset?, angle?, values?} when they were typed as expressions), origins, links, degrees of freedom, conflicts, floating: [{occurrences, joints}] \ (joint chains joined to nothing grounded: the solver places none of them, so driving them moves nothing)", ), CommandSpec::new("joint.solve", "Solve Joints", solve_cmd).icon("compute").params("re-place the occurrences from the joints → conflicts, errors, dof"), @@ -80,10 +84,39 @@ pub static COMMANDS: &[CommandSpec] = &[ /// Re-solve the joints and move the occurrences they place (after any edit). Gears, racks and /// screws first take their ratios from the radii and pitches they are defined by. pub fn resolve(s: &mut Session) -> joints::Solution { + reexpress(s); recouple(s); resolve_holding(s, &BTreeMap::new()) } +/// Work out the offsets, angles and values joints were given as expressions again (a parameter +/// may have changed). One that can't be worked out (its parameter gone) keeps its numbers; the +/// solve leaves that joint out and says why. +fn reexpress(s: &mut Session) { + let changed: Vec<(usize, (f64, f64, Vec))> = s + .doc + .assembly + .joints + .iter() + .enumerate() + .filter(|(_, j)| !j.exprs.is_empty()) + .filter_map(|(i, j)| { + let (o, a, mut q) = joints::expressed(&s.doc, j).ok()?; + joints::clamp(j, &mut q); + ((o, a) != (j.offset, j.angle) || q != j.values).then_some((i, (o, a, q))) + }) + .collect(); + if changed.is_empty() { + return; + } + let doc = s.doc_mut(); + for (i, (o, a, q)) in changed { + if let Some(j) = doc.assembly.joints.get_mut(i) { + (j.offset, j.angle, j.values) = (o, a, q); + } + } +} + /// Work out the ratios (and cam tables) of the coupled motion links again (a radius, a parameter /// or a cam's profile may have changed). A coupling that can't be worked out (its face gone) /// keeps its last ratio and table; `joint.list` says why. @@ -449,6 +482,28 @@ pub(crate) fn value(s: &Session, v: &Value, angle: bool, cmd: &str) -> Result) -> Option { + match v { + Some(Value::String(t)) if !solidcraft_doc::expr::references(t).is_empty() => Some(t.trim().to_string()), + _ => None, + } +} + +/// The expressions among `values` (or `value`), by index. +fn value_exprs(p: &Value) -> Vec> { + let mut out: Vec> = match (p.get("values"), p.get("value")) { + (Some(Value::Array(a)), _) => a.iter().map(|v| typed(Some(v))).collect(), + (_, Some(v)) => vec![typed(Some(v))], + _ => Vec::new(), + }; + while out.last().is_some_and(Option::is_none) { + out.pop(); + } + out +} + fn values_param(s: &Session, p: &Value, kind: JointKind, cmd: &str) -> Result> { let n = kind.dofs().len(); let list: Vec = match (p.get("values"), p.get("value")) { @@ -589,6 +644,7 @@ fn joint(s: &mut Session, p: &Value) -> Result { offset, angle, suppressed: false, + exprs: JointExprs { offset: typed(p.get("offset")), angle: typed(p.get("angle")), values: value_exprs(p) }, }; add_joint(s, j, p) } @@ -622,6 +678,7 @@ fn as_built(s: &mut Session, p: &Value) -> Result { offset: 0.0, angle: 0.0, suppressed: false, + exprs: Default::default(), }; add_joint(s, j, p) } @@ -666,6 +723,11 @@ fn drive(s: &mut Session, p: &Value) -> Result { joints::clamp(j, &mut q); // Moved as far toward `q` as contact sets and closed loops allow. Values left out of // `values` are not driven: in a closed loop they follow. + // Driving moves the joint by hand: the values driven drop their expressions (an expression + // given here is worked out once, as contact or a loop may stop the motion short of it). + for i in 0..given.min(kind.dofs().len()) { + j.exprs.set_value(i, None); + } let before = super::motion::positions(s); let r = super::motion::drive_joint(s, id, q, given)?; let sol = joints::solve(&s.doc, &s.model.state()); @@ -1126,15 +1188,26 @@ fn edit(s: &mut Session, p: &Value) -> Result { let doc = s.doc_mut(); let Some(j) = doc.assembly.joints.iter_mut().find(|j| j.id == id) else { return Err(bad(cmd, "joint")) }; if let Some(k) = kind { + let was = j.kind; j.kind = k; j.values.resize(k.dofs().len(), 0.0); j.limits.resize(k.dofs().len(), None); + j.exprs.values.truncate(k.dofs().len()); + // A value that changes unit with the type (a slide becoming a turn) drops its expression, + // which would no longer work out and leave the joint out of the solve. + for i in 0..j.exprs.values.len() { + if was.is_angle(i) != k.is_angle(i) { + j.exprs.set_value(i, None); + } + } } if let Some(o) = offset { j.offset = o; + j.exprs.offset = typed(p.get("offset")); } if let Some(a) = angle { j.angle = a; + j.exprs.angle = typed(p.get("angle")); } if let Some(f) = bool_(p, "flip") { j.flip = f; @@ -1192,8 +1265,12 @@ fn list(s: &mut Session, p: &Value) -> Result { .map(|j| { let named = named_values(j, vals.get(&j.id).map(Vec::as_slice).unwrap_or_default()); let world = |o: &JointOrigin| s.doc.origin_world(&st, o).ok().map(|m| json!({"origin": [m[3][0], m[3][1], m[3][2]], "z": [m[2][0], m[2][1], m[2][2]]})); - json!({"id": j.id, "name": j.name, "type": j.kind, "a": j.a.occurrence, "b": j.b.occurrence, "values": named, - "flip": j.flip, "offset": j.offset, "suppressed": j.suppressed, "visible": s.joint_visible(j.id), "frame_a": world(&j.a), "frame_b": world(&j.b)}) + let mut out = json!({"id": j.id, "name": j.name, "type": j.kind, "a": j.a.occurrence, "b": j.b.occurrence, "values": named, + "flip": j.flip, "offset": j.offset, "suppressed": j.suppressed, "visible": s.joint_visible(j.id), "frame_a": world(&j.a), "frame_b": world(&j.b)}); + if !j.exprs.is_empty() { + out["expressions"] = json!(j.exprs); + } + out }) .collect(); let links: Vec = s @@ -1327,6 +1404,9 @@ pub(crate) fn overlapping_pairs(boxes: &[Aabb3], limit: usize) -> (Vec<(usize, u #[path = "joint_edge_tests.rs"] mod edge_tests; #[cfg(test)] +#[path = "joints_exprs_tests.rs"] +mod exprs_tests; +#[cfg(test)] #[path = "joints_face_tests.rs"] mod face_tests; #[cfg(test)] diff --git a/crates/engine/src/cmd/joints_exprs_tests.rs b/crates/engine/src/cmd/joints_exprs_tests.rs new file mode 100644 index 000000000..d3cdfa05b --- /dev/null +++ b/crates/engine/src/cmd/joints_exprs_tests.rs @@ -0,0 +1,146 @@ +//! Joints whose offset, angle or values are typed as expressions follow the parameters they name. + +use serde_json::json; +use solidcraft_geom::Vec3; + +use super::tests::{occ, place, run}; +use crate::Session; + +/// Two 10 mm cubes in components A (grounded) and B, a `gap` and a `turn` parameter. +fn cubes() -> Session { + let mut s = Session::default(); + for (name, x) in [("A", 0), ("B", 20)] { + run(&mut s, "component.activate", json!({"component": "root"})); + run(&mut s, "component.create", json!({"name": name})); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [x, 0, 0]})); + } + let o = occ(&s, "A"); + run(&mut s, "occurrence.ground", json!({"occurrence": o, "grounded": true})); + run(&mut s, "parameters.add", json!({"name": "gap", "expression": "5 mm"})); + run(&mut s, "parameters.add", json!({"name": "turn", "expression": "0 deg"})); + s +} + +/// Where B's bottom corner (20, 0, 0 in B) is. +fn b_corner(s: &Session) -> Vec3 { + place(s, "B", Vec3::new(20.0, 0.0, 0.0)) +} + +fn near(a: Vec3, b: Vec3) -> bool { + a.dist(b) < 1e-6 +} + +#[test] +fn an_offset_and_an_angle_typed_as_expressions_follow_their_parameters() { + let mut s = cubes(); + run( + &mut s, + "joint.create", + json!({"type": "rigid", "a": {"face": [5, 5, 10]}, "b": {"face": [25, 5, 0]}, "offset": "gap", "angle": "turn", "name": "Seat"}), + ); + let z = |s: &Session| place(s, "B", Vec3::new(25.0, 5.0, 0.0)).z; + assert!((z(&s) - 15.0).abs() < 1e-6, "{}", z(&s)); + // The gap changes: B rides up with it, without touching the joint. + run(&mut s, "parameters.change", json!({"name": "gap", "expression": "12 mm"})); + assert!((z(&s) - 22.0).abs() < 1e-6, "{}", z(&s)); + // A parameter the gap is worked out from changes too. + run(&mut s, "parameters.add", json!({"name": "base", "expression": "2 mm"})); + run(&mut s, "parameters.change", json!({"name": "gap", "expression": "base * 3"})); + assert!((z(&s) - 16.0).abs() < 1e-6, "{}", z(&s)); + // The angle turns B about the seat's axis (its centre stays, its corner swings round). + let centre = place(&s, "B", Vec3::new(25.0, 5.0, 0.0)); + let before = b_corner(&s); + run(&mut s, "parameters.change", json!({"name": "turn", "expression": "90 deg"})); + assert!(near(place(&s, "B", Vec3::new(25.0, 5.0, 0.0)), centre)); + let after = b_corner(&s); + assert!((before - centre).dot(after - centre).abs() < 1e-6, "{before:?} {after:?}"); + // The design keeps the expressions, so they are there after saving and opening. + let j = s.doc.assembly.joints.first().cloned().unwrap_or_else(|| panic!("no joint")); + assert_eq!((j.exprs.offset.as_deref(), j.exprs.angle.as_deref()), (Some("gap"), Some("turn"))); + let saved = serde_json::to_value(&j).unwrap_or_default(); + assert_eq!((&saved["exprs"]["offset"], &saved["exprs"]["angle"]), (&json!("gap"), &json!("turn")), "{saved}"); + let listed = run(&mut s, "joint.list", json!({})); + assert_eq!(listed["joints"][0]["expressions"]["offset"], json!("gap"), "{listed}"); + // A number typed over the expression drops it: B stays when the gap changes again. + run(&mut s, "joint.edit", json!({"joint": "Seat", "offset": 4})); + run(&mut s, "parameters.change", json!({"name": "gap", "expression": "30 mm"})); + assert!((z(&s) - 14.0).abs() < 1e-6, "{}", z(&s)); + assert!(s.doc.assembly.joints.first().is_some_and(|j| j.exprs.offset.is_none() && j.exprs.angle.is_some())); +} + +#[test] +fn a_joint_value_typed_as_an_expression_follows_it_until_it_is_driven() { + let mut s = cubes(); + run( + &mut s, + "joint.create", + json!({"type": "slider", "a": {"face": [5, 5, 10]}, "b": {"face": [25, 5, 0]}, "values": ["gap"], "limits": [[0, 20]], "name": "Rail"}), + ); + let z = |s: &Session| place(s, "B", Vec3::new(25.0, 5.0, 0.0)).z; + assert!((z(&s) - 15.0).abs() < 1e-6, "{}", z(&s)); + run(&mut s, "parameters.change", json!({"name": "gap", "expression": "8 mm"})); + assert!((z(&s) - 18.0).abs() < 1e-6, "{}", z(&s)); + // Past the limits it is held at them, like a typed value. + run(&mut s, "parameters.change", json!({"name": "gap", "expression": "50 mm"})); + assert!((z(&s) - 30.0).abs() < 1e-6, "{}", z(&s)); + // Driven by hand it drops the expression (contact or a loop may stop it short of any value). + run(&mut s, "joint.drive", json!({"joint": "Rail", "value": 1})); + run(&mut s, "parameters.change", json!({"name": "gap", "expression": "9 mm"})); + assert!((z(&s) - 11.0).abs() < 1e-6, "{}", z(&s)); + assert!(s.doc.assembly.joints.first().is_some_and(|j| j.exprs.is_empty())); +} + +#[test] +fn renaming_a_parameter_carries_into_joints_and_deleting_it_is_refused() { + let mut s = cubes(); + run(&mut s, "joint.create", json!({"type": "rigid", "a": {"face": [5, 5, 10]}, "b": {"face": [25, 5, 0]}, "offset": "gap + 1", "name": "Seat"})); + run(&mut s, "parameters.rename", json!({"name": "gap", "new_name": "clearance"})); + assert_eq!(s.doc.assembly.joints.first().and_then(|j| j.exprs.offset.clone()).as_deref(), Some("clearance + 1")); + run(&mut s, "parameters.change", json!({"name": "clearance", "expression": "9 mm"})); + assert!((place(&s, "B", Vec3::new(25.0, 5.0, 0.0)).z - 20.0).abs() < 1e-6); + // The joint uses it, so it can't be deleted from under the joint. + let e = s.execute("parameters.delete", &json!({"name": "clearance"})).unwrap_err().to_string(); + assert!(e.contains("joint Seat (offset)"), "{e}"); +} + +#[test] +fn a_joint_whose_expression_stops_working_out_is_left_out_with_the_reason() { + let mut s = cubes(); + run(&mut s, "joint.create", json!({"type": "rigid", "a": {"face": [5, 5, 10]}, "b": {"face": [25, 5, 0]}, "offset": "gap", "name": "Seat"})); + let at = b_corner(&s); + // The gap becomes an angle: the offset no longer works out as a length. B stays where it + // was (not thrown to an old number) and the solve says why. + run(&mut s, "parameters.change", json!({"name": "gap", "expression": "30 deg", "unit": "deg"})); + assert!(near(b_corner(&s), at), "{:?}", b_corner(&s)); + let r = run(&mut s, "joint.solve", json!({})); + let why = r["errors"][0]["why"].as_str().unwrap_or_default().to_string(); + assert!(why.contains("Seat") && why.contains("offset"), "{r}"); + // Fixed again, the joint places B again. + run(&mut s, "parameters.change", json!({"name": "gap", "expression": "2 mm", "unit": "mm"})); + assert!((place(&s, "B", Vec3::new(25.0, 5.0, 0.0)).z - 12.0).abs() < 1e-6); + assert_eq!(run(&mut s, "joint.solve", json!({}))["errors"], json!([])); +} + +#[test] +fn a_value_that_changes_unit_with_the_joint_type_drops_its_expression() { + let mut s = cubes(); + run(&mut s, "joint.create", json!({"type": "slider", "a": {"face": [5, 5, 10]}, "b": {"face": [25, 5, 0]}, "values": ["gap"], "name": "Rail"})); + // The slide becomes a turn: `gap` (a length) can't be its angle, so the turn keeps a number + // and the joint stays in the solve. + let r = run(&mut s, "joint.edit", json!({"joint": "Rail", "type": "revolute"})); + assert_eq!(r["errors"], json!([]), "{r}"); + assert!(s.doc.assembly.joints.first().is_some_and(|j| j.exprs.is_empty())); +} + +#[test] +fn text_that_names_no_parameter_is_kept_as_a_number() { + let mut s = cubes(); + run( + &mut s, + "joint.create", + json!({"type": "slider", "a": {"face": [5, 5, 10]}, "b": {"face": [25, 5, 0]}, "offset": "3 mm", "angle": "0 deg", "values": ["2 * 2 mm"]}), + ); + let j = s.doc.assembly.joints.first().cloned().unwrap_or_else(|| panic!("no joint")); + assert!(j.exprs.is_empty(), "{:?}", j.exprs); + assert!((j.offset - 3.0).abs() < 1e-12 && j.values.first().is_some_and(|v| (v - 4.0).abs() < 1e-12), "{j:?}"); +} diff --git a/crates/ui-egui/src/dialogs_assembly.rs b/crates/ui-egui/src/dialogs_assembly.rs index 9cb2d1bd4..0b8fcf5f1 100644 --- a/crates/ui-egui/src/dialogs_assembly.rs +++ b/crates/ui-egui/src/dialogs_assembly.rs @@ -281,8 +281,10 @@ pub fn edit_joint(app: &SolveApp, id: u64) -> Option { f.editing = Some(id); f.kind = TYPES.iter().position(|t| JointKind::parse(t) == Some(j.kind)).unwrap_or(0); f.flip = j.flip; - f.angle = num(j.angle.to_degrees(), "deg"); - f.offset[2] = num(j.offset, "mm"); + // An offset or angle typed as an expression shows (and is sent back) as that expression, so + // the joint keeps following its parameters. + f.angle = j.exprs.angle.clone().unwrap_or_else(|| num(j.angle.to_degrees(), "deg")); + f.offset[2] = j.exprs.offset.clone().unwrap_or_else(|| num(j.offset, "mm")); f.fit_limits(); for (i, l) in f.limits.iter_mut().enumerate() { if let Some(Some((lo, hi))) = j.limits.get(i) { diff --git a/crates/ui-egui/src/dialogs_assembly_tests.rs b/crates/ui-egui/src/dialogs_assembly_tests.rs index fa655b686..d163db67e 100644 --- a/crates/ui-egui/src/dialogs_assembly_tests.rs +++ b/crates/ui-egui/src/dialogs_assembly_tests.rs @@ -138,6 +138,29 @@ fn edit_joint_runs_edit_and_limits() { assert!((j.offset - 2.0).abs() < 1e-12); } +/// Edit Joint shows an offset typed as an expression as that expression, and OK keeps it; the +/// dialog's plain numbers keep no expression. +#[test] +fn edit_joint_keeps_an_offset_typed_as_an_expression() { + let mut app = two_boxes(); + let (a, b) = (occ(&app, "A"), occ(&app, "B")); + app.run("parameters.add", json!({"name": "gap", "expression": "3 mm"})).unwrap(); + let (fa, fb) = (json!({"occurrence": a, "face": [10, 10, 10]}), json!({"occurrence": b, "face": [40, 10, 0]})); + app.run("joint.create", json!({"type": "rigid", "a": fa, "b": fb, "offset": "gap", "angle": "0 deg"})).unwrap(); + let id = app.session.doc.assembly.joints[0].id; + let mut d = edit_joint(&app, id).unwrap(); + if let Kind::Assembly(Asm::Joint(f)) = &mut d.kind { + assert_eq!(f.offset[2], "gap"); + f.flip = true; + } + for (id, p) in apply_commands(&app, &d).unwrap() { + app.run(&id, p).unwrap(); + } + let j = &app.session.doc.assembly.joints[0]; + assert!(j.flip); + assert_eq!((j.exprs.offset.as_deref(), j.exprs.angle.as_deref()), (Some("gap"), None)); +} + /// As-built joints and rigid groups take components from body picks; New Component makes one /// from bodies when bodies are picked. #[test] diff --git a/docs/book/src/guide/assemblies.md b/docs/book/src/guide/assemblies.md index b261722a5..3280f83c8 100644 --- a/docs/book/src/guide/assemblies.md +++ b/docs/book/src/guide/assemblies.md @@ -38,6 +38,14 @@ point, its x and y running along the two edges into the face. The edge, the face are found again by name, so a bracket set 40 mm in from a panel's corner (a planar joint with values `[40, 40, 0]`) stays 40 mm in from that corner when the panel changes size. +A joint's offset, angle and values can be typed as expressions over the design's parameters +(`"offset": "gap + 2"`, `"values": ["travel"]`). The joint keeps them and works them out again +whenever the design changes, so a part seated `gap` above a panel moves with `gap`. Renaming a +parameter carries into the joints that use it, and deleting one they use is refused. If an +expression stops working out (say a parameter becomes an angle), the joint is left out of the +solve and `joint.solve` gives the reason, instead of placing the part from old numbers. Typing a +plain number, or driving the value, drops that expression. + The check behind it, `inspect.clearance`, does all of that in one call for any number of bodies, which suits scripts and agents checking a whole assembly: From 19ffb0dd75a207a81ee21ba7da7ae5c7cbdd87f3 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Sun, 18 Oct 2026 23:12:55 -0400 Subject: [PATCH 037/225] Orbit drags turn from where they began, so erratic drags don't drift (#2842) An orbit drag now applies its whole turn so far to the camera it began with, instead of adding each pointer step to the camera of the step before. The view then depends only on where the pointer is: dragging past straight up or down and back no longer loses the pitch that the clamp swallowed, and returning to the starting point brings back the starting view. The pivot is still picked once, when the drag begins, and kept still on screen by the rigid turn about it. Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/navigation.rs | 31 ++++++++++++++++--- crates/ui-egui/src/viewport.rs | 53 ++++++++++++++++++++++++++++++++ 2 files changed, 80 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/navigation.rs b/crates/ui-egui/src/navigation.rs index b8e4a674c..a8083ae15 100644 --- a/crates/ui-egui/src/navigation.rs +++ b/crates/ui-egui/src/navigation.rs @@ -169,6 +169,7 @@ pub(crate) fn modifier_motion( let previous = app.viewport.modifier_nav; if previous.map(|(m, _)| m) != next.map(|(m, _)| m) { app.viewport.orbit_pivot = None; + app.viewport.orbit_from = None; app.viewport.orbit_free = None; app.viewport.orbit_snap = None; } @@ -481,6 +482,7 @@ pub(crate) fn handle(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect, resp: &e } if !dragging && motion.is_none() { app.viewport.orbit_pivot = None; + app.viewport.orbit_from = None; } if app.viewport.spin { // A click on the navigation bar (its own button) is not a stop. @@ -699,11 +701,32 @@ pub fn orbit(app: &mut SolveApp, rect: egui::Rect, dx: f64, dy: f64, press: Opti } }), }; - let Some(pivot) = pivot else { - app.cam.orbit(dx, dy); - return; + // The drag's whole turn so far, applied to the camera it began with: the view depends on + // where the pointer is, not on the path it took, so fast or erratic drags (a pitch held at + // straight up or down for a while, many tiny steps) can't drift. Anything else that moves + // the camera meanwhile (a wheel zoom, a new pivot) starts the sum again from there. + let from = match app.viewport.orbit_from { + Some(f) if f.last == app.cam && f.pivot == pivot => f, + _ => OrbitFrom { start: app.cam, dx: 0.0, dy: 0.0, pivot, last: app.cam }, }; - app.cam.orbit_about(dx, dy, pivot); + let (dx, dy) = (from.dx + dx, from.dy + dy); + app.cam = from.start; + match pivot { + Some(p) => app.cam.orbit_about(dx, dy, p), + None => app.cam.orbit(dx, dy), + } + app.viewport.orbit_from = Some(OrbitFrom { dx, dy, last: app.cam, ..from }); +} + +/// An orbit drag so far: the camera it began with, the pointer's total motion since, the pivot +/// and the camera that produced. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct OrbitFrom { + start: Camera, + dx: f64, + dy: f64, + pivot: Option, + last: Camera, } #[cfg(test)] diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index bde68cac6..b36560580 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -96,6 +96,8 @@ pub struct ViewportState { pub hover_bodies: Vec, /// The model point an orbit turns around (Preferences: orbit around the cursor). pub orbit_pivot: Option, + /// The orbit drag under way, summed from where it began (see [`crate::navigation::orbit`]). + pub orbit_from: Option, /// Continuous orbit: the view turns about the vertical until the next click or key. pub spin: bool, /// The 3D mouse's motion this frame, for the page showing the camera to apply with what its @@ -5956,6 +5958,57 @@ mod tests { } } + /// An erratic orbit drag (big jumps, reversals, the pointer over the panels and back) keeps + /// the point picked when it began on its pixel the whole way, and coming back to where it + /// began brings back the view it began with (up to the rounding of the pointer's f32 steps). + #[test] + fn an_erratic_cursor_orbit_keeps_its_pivot_and_comes_back() { + for perspective in [false, true] { + let mut h = crate::scenario::Harness::new(); + h.app.preferences.orbit_around = crate::prefs::OrbitAround::Cursor; + h.app.ui.perspective = perspective; + h.app.run("solid.box", json!({"length":80,"width":50,"height":20})).unwrap(); + h.app.fit_view(); + h.frames(2); + let rect = h.app.viewport.rect.unwrap(); + let at = rect.center() + vec2(30.0, 20.0); + let pivot = crate::prefs::pivot_under(&h.app, &projection(&h.app, rect), at); + let start = h.app.cam; + let shift = egui::Modifiers { shift: true, ..Default::default() }; + let send = |h: &mut crate::scenario::Harness, e: egui::Event| { + h.app.synthetic.push(e); + h.frame(); + }; + send(&mut h, egui::Event::ModifiersChanged(egui::Modifiers::NONE)); + send(&mut h, egui::Event::PointerMoved(at)); + send(&mut h, egui::Event::PointerButton { pos: at, button: egui::PointerButton::Middle, pressed: true, modifiers: shift }); + let mut seed: u32 = 12345; + let mut next = move || { + seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + f32::from((seed >> 16) as u16) / 65535.0 + }; + for i in 0..300 { + // Mostly small moves, now and then a big jump, some of them over the panels. + let p = if i % 17 == 0 { pos2(next() * 1600.0, next() * 1000.0) } else { at + vec2((next() - 0.5) * 900.0, (next() - 0.5) * 200.0) }; + send(&mut h, egui::Event::PointerMoved(p)); + assert_eq!(h.app.viewport.orbit_pivot, Some(pivot), "move {i}: the pivot is picked once, when the drag begins"); + let s = projection(&h.app, rect).to_screen(pivot).unwrap(); + assert!(s.distance(at) < 1.0, "perspective={perspective}, move {i} to {p:?}: the pivot moved to {s:?}"); + } + send(&mut h, egui::Event::PointerMoved(at)); + let s = projection(&h.app, rect).to_screen(pivot).unwrap(); + assert!(s.distance(at) < 1.0, "{s:?}"); + let back = h.app.cam; + assert!( + (back.yaw - start.yaw).rem_euclid(std::f64::consts::TAU).min((start.yaw - back.yaw).rem_euclid(std::f64::consts::TAU)) < 1e-6, + "{start:?} -> {back:?}" + ); + assert!((back.pitch - start.pitch).abs() < 1e-6, "{start:?} -> {back:?}"); + assert!((back.target - start.target).len() < 1e-4, "back where it began: {start:?} -> {back:?}"); + send(&mut h, egui::Event::PointerButton { pos: at, button: egui::PointerButton::Middle, pressed: false, modifiers: shift }); + } + } + #[test] fn shift_orbit_keeps_cursor_pivot_and_default_middle_pan() { let mut h = crate::scenario::Harness::new(); From 59ba87103e9c5dbcfa7f7d7486b608fea64520aa Mon Sep 17 00:00:00 2001 From: bherbruck Date: Sun, 18 Oct 2026 23:28:17 -0400 Subject: [PATCH 038/225] CI: heavy checks run after review (approved-for-ci label) (#2689) * CI: heavy checks run after review (approved-for-ci label) Pull requests without the approved-for-ci label run Select checks, the format and repository checks and a quick cargo check. The label runs the full suite, and every push after that does too. Other labels start no work and never cancel a run. Main, merge groups, nightly and Run workflow are unchanged. Co-Authored-By: Claude Sonnet 5.5 * CI: approved fork PRs run heavy jobs on self-hosted-fast in private directories An approved-for-ci label on a fork pull request sends Clippy, Build tests, the test shards and Doc tests to the trusted runners, with private copies of the build directory, Cargo home and rustup home that are deleted after the job. Only the labeling event qualifies; later pushes use the old fork routing. The skipped run of an unrelated label names its ci job differently. Co-Authored-By: Claude Sonnet 5.5 * Revert "CI: approved fork PRs run heavy jobs on self-hosted-fast in private directories" This reverts commit 439f2f7dab77e60ebbe31489268438f623a4fed7. * CI: name the ci job differently on an ignored label's skipped run Co-Authored-By: Claude Sonnet 5.5 --------- Co-authored-by: Claude Sonnet 5.5 --- .github/workflows/ci.yml | 69 +++++++++++++++++++++++++++++++++++----- CONTRIBUTING.md | 4 +++ 2 files changed, 65 insertions(+), 8 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 58b542b19..7fc6f0032 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,6 +14,12 @@ # main that a passing merge-queue run already tested runs only the repository checks; a push # that skipped the queue still runs everything. Pull requests run the reference tests when the # command line (or anything it depends on) changes, and doc tests for the affected packages. +# Heavy checks wait for review: a pull request without the `approved-for-ci` label runs only +# Select checks, the format and repository checks and a quick compile. Adding the label (after +# review) runs everything above, and every later push to the PR does too. Pushes to main, merge +# groups, the nightly run and Run workflow are not pull requests and always run the full suite. +# GitHub cannot filter `labeled` events by label name, so any other label starts a run whose jobs +# are all skipped; it gets its own concurrency group (below) so it never cancels the real run. # Cross-compilation is opt-in through Run workflow; release builds remain in release.yml. # Trusted runs use both pools: pushes to main, merge-queue groups and pull requests from a branch # of this repository (people with write access; fork pull requests never run on this machine). @@ -35,9 +41,10 @@ name: CI on: # Draft pull requests run no CI (see `changes`, `checks` and `ci`): it starts when the PR is - # marked ready for review, and on every push after that. + # marked ready for review, and on every push after that. `labeled` is there for approved-for-ci + # only (other labels are skipped, see the top of this file). pull_request: - types: [opened, synchronize, reopened, ready_for_review] + types: [opened, synchronize, reopened, ready_for_review, labeled] # The merge queue: each queued group runs the full suite before it lands on main. merge_group: push: @@ -57,7 +64,10 @@ permissions: concurrency: # A new PR push replaces the old run. Only one run per group may wait, so a busy main would # cancel the waiting nightly (or a Run workflow) before it starts: they get groups of their own. - group: ci-${{ github.event_name }}-${{ github.ref }} + # A `labeled` event for any label but approved-for-ci does no work and must not cancel (or queue + # behind) the PR's real run, so it gets a group of its own; approved-for-ci replaces the + # unlabelled run with the full one. + group: ci-${{ github.event_name }}-${{ github.ref }}${{ github.event.action == 'labeled' && github.event.label.name != 'approved-for-ci' && format('-ignored-{0}', github.run_id) || '' }} cancel-in-progress: ${{ github.event_name == 'pull_request' }} env: @@ -79,8 +89,9 @@ jobs: changes: name: Select checks - # Not on a draft: every other check needs this one, so they skip too. - if: github.event_name != 'pull_request' || !github.event.pull_request.draft + # Not on a draft: every other check needs this one, so they skip too. Not on a label other than + # approved-for-ci either (the same skip, for the same reason). + if: (github.event_name != 'pull_request' || !github.event.pull_request.draft) && (github.event.action != 'labeled' || github.event.label.name == 'approved-for-ci') # Trusted runs (see the top of this file) use the self-hosted runners. runs-on: ${{ (github.event_name == 'merge_group' || (github.event_name == 'push' && github.ref == 'refs/heads/main') || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository)) && 'self-hosted-light' || 'ubuntu-24.04' }} permissions: @@ -93,6 +104,8 @@ jobs: goldens: ${{ steps.paths.outputs.goldens }} windows: ${{ steps.paths.outputs.windows }} full: ${{ steps.paths.outputs.full }} + # Code changed on a pull request that has no approved-for-ci label yet: only Quick compile. + quick: ${{ steps.paths.outputs.quick }} packages: ${{ steps.paths.outputs.packages }} oracle: ${{ steps.paths.outputs.oracle }} # The fast self-hosted runners are kept for main and the merge queue (the pre-merge gate); @@ -110,6 +123,7 @@ jobs: HEAD_SHA: ${{ github.event.pull_request.head.sha }} PUSH_SHA: ${{ github.sha }} REPO: ${{ github.repository }} + APPROVED: ${{ contains(github.event.pull_request.labels.*.name, 'approved-for-ci') }} GH_TOKEN: ${{ github.token }} run: | native=false @@ -186,6 +200,15 @@ jobs: # The pull request fast lane: Windows and the reference tests run on main (and the nightly), # not on every pull request push; a break there is fixed forward on main. if [ "$EVENT_NAME" = pull_request ]; then windows=false; oracle=false; fi + # Until a maintainer adds approved-for-ci, a pull request gets a quick compile instead of + # Clippy, the tests, the doc tests and the goldens. + quick=false + if [ "$EVENT_NAME" = pull_request ] && [ "$APPROVED" != true ]; then + quick=$native + native=false + oracle=false + goldens=false + fi { echo "native=$native" echo "kernel=$kernel" @@ -193,12 +216,13 @@ jobs: echo "windows=$windows" echo "oracle=$oracle" echo "full=$full" + echo "quick=$quick" echo "packages=$packages" } >> "$GITHUB_OUTPUT" checks: name: Format and repository checks - if: github.event_name != 'pull_request' || !github.event.pull_request.draft + if: (github.event_name != 'pull_request' || !github.event.pull_request.draft) && (github.event.action != 'labeled' || github.event.label.name == 'approved-for-ci') runs-on: ${{ (github.event_name == 'merge_group' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) && 'self-hosted-fast' || 'ubuntu-24.04' }} timeout-minutes: 15 steps: @@ -237,6 +261,26 @@ jobs: - name: Claim and triage bot tests run: node --test scripts/claim/*.test.js scripts/triage/*.test.js + # Fast feedback for a pull request that has not been approved for the full CI yet. + quick-compile: + name: Quick compile + needs: changes + if: needs.changes.outputs.quick == 'true' + runs-on: ${{ needs.changes.outputs.local == 'true' && 'self-hosted-light' || 'ubuntu-24.04' }} + timeout-minutes: 30 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Size parallel compiles to the job's memory + run: scripts/ci/build-jobs.sh + - uses: dtolnay/rust-toolchain@stable + - if: runner.environment == 'github-hosted' + uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 + with: + key: quick-compile + save-if: ${{ github.ref == 'refs/heads/main' }} + - name: Cargo check + run: cargo check --workspace --all-targets --locked + clippy: name: Native Linux Clippy needs: changes @@ -657,8 +701,11 @@ jobs: # Preserve the existing check name for branch protection, including docs-only PRs. ci: - needs: [changes, checks, clippy, build-tests, tests, doc-tests, oracle, windows-fxc, windows-startup] - if: always() && (github.event_name != 'pull_request' || !github.event.pull_request.draft) + # On the skipped run another label starts, this job is named differently, so that skipped job + # can never stand in for the required `ci` check of the pull request's real run. + name: ${{ github.event.action == 'labeled' && github.event.label.name != 'approved-for-ci' && 'ci (ignored label)' || 'ci' }} + needs: [changes, checks, quick-compile, clippy, build-tests, tests, doc-tests, oracle, windows-fxc, windows-startup] + if: always() && (github.event_name != 'pull_request' || !github.event.pull_request.draft) && (github.event.action != 'labeled' || github.event.label.name == 'approved-for-ci') runs-on: ${{ needs.changes.outputs.local == 'true' && 'self-hosted-light' || 'ubuntu-24.04' }} steps: - name: Verify required checks @@ -666,6 +713,8 @@ jobs: CHANGES: ${{ needs.changes.result }} CHECKS: ${{ needs.checks.result }} NATIVE: ${{ needs.changes.outputs.native }} + QUICK: ${{ needs.changes.outputs.quick }} + QUICK_COMPILE: ${{ needs.quick-compile.result }} LOCAL: ${{ needs.changes.outputs.local }} WINDOWS: ${{ needs.changes.outputs.windows }} ORACLE_RUN: ${{ needs.changes.outputs.oracle }} @@ -679,6 +728,10 @@ jobs: run: | test "$CHANGES" = success test "$CHECKS" = success + # An unapproved pull request: the heavy jobs are skipped on purpose. + if [ "$QUICK" = true ]; then + test "$QUICK_COMPILE" = success + fi if [ "$NATIVE" = true ]; then test "$CLIPPY" = success # The self-hosted test shards build their own tests (no Build tests job there). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 923c103c7..359341e73 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -285,6 +285,10 @@ and a fresh CI run: 2. Branch from `main` and keep the PR to one topic. 3. Run `cargo xtask ci` before pushing. It runs fmt, the asset, licence and layer checks, clippy (`-D warnings`), then the tests with the wasm build check alongside. A PR has to pass it. + Heavy CI runs after review: a pull request gets the formatting and repository checks and a + quick compile (`cargo check`) when you push. Once a maintainer has reviewed it they add the + `approved-for-ci` label, which runs the full CI (build, tests, goldens, Clippy); every push + after that runs the full set again. 4. Reference the issue (`Fixes #12`). In the PR, say what you tested and how. For geometry work, include the measured numbers (and the expected ones). From e3831b05d42189886358fdc77cc8be93e7da4397 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Sun, 18 Oct 2026 23:30:21 -0400 Subject: [PATCH 039/225] Agent chat: Ctrl/Cmd+V attaches copied files and pictures (#2812) (#2854) Files copied in the file manager attach as files, a picture on the clipboard attaches as a picture, text pastes as text. A picture-only or files-only paste is seen through the V key coming up (egui-winit sends nothing when the clipboard has no text); macOS sends no key-up while Cmd is held, so there only pastes that come with text are seen and + > Paste a picture still works. --- crates/ui-egui/src/agent_chat/mod.rs | 4 + crates/ui-egui/src/agent_chat/panel.rs | 5 + crates/ui-egui/src/agent_chat/paste.rs | 223 +++++++++++++++++++++++++ 3 files changed, 232 insertions(+) create mode 100644 crates/ui-egui/src/agent_chat/paste.rs diff --git a/crates/ui-egui/src/agent_chat/mod.rs b/crates/ui-egui/src/agent_chat/mod.rs index 3347c9ff8..42b0ecca4 100644 --- a/crates/ui-egui/src/agent_chat/mod.rs +++ b/crates/ui-egui/src/agent_chat/mod.rs @@ -31,6 +31,8 @@ mod markdown; mod markdown_view; mod panel; #[cfg(not(target_arch = "wasm32"))] +pub mod paste; +#[cfg(not(target_arch = "wasm32"))] mod process; pub mod settings; @@ -333,6 +335,8 @@ pub struct AgentChat { pub(crate) attachments: Vec, /// Pictures pasted so far, to name the next one. pasted: usize, + /// When the last text paste arrived (input time), so the V key coming up after it isn't a second paste. + pub(crate) text_pasted_at: Option, /// The chips' thumbnails, by the picture they show. thumbs: std::collections::HashMap, /// The last id given to a file added to a message. diff --git a/crates/ui-egui/src/agent_chat/panel.rs b/crates/ui-egui/src/agent_chat/panel.rs index 93344ba31..7ad6cd836 100644 --- a/crates/ui-egui/src/agent_chat/panel.rs +++ b/crates/ui-egui/src/agent_chat/panel.rs @@ -597,6 +597,11 @@ fn desktop_body(app: &mut SolveApp, ui: &mut egui::Ui) { ui.separator(); // The files for the next message (#1744), as chips of their own. attachment_chips(app, ui); + // Ctrl/Cmd+V: files and pictures on the clipboard attach; text goes to the box below. + #[cfg(not(target_arch = "wasm32"))] + if focused { + super::paste::handle(app, ui); + } let edit = egui::TextEdit::multiline(&mut app.agent_chat.input) .hint_text(tr(if busy { "ui.agent_chat_placeholder_busy" } else { "ui.agent_chat_placeholder" })) .desired_rows(2) diff --git a/crates/ui-egui/src/agent_chat/paste.rs b/crates/ui-egui/src/agent_chat/paste.rs new file mode 100644 index 000000000..2d722ca9e --- /dev/null +++ b/crates/ui-egui/src/agent_chat/paste.rs @@ -0,0 +1,223 @@ +//! Ctrl/Cmd+V in the chat's text box: files copied in the file manager attach as files, a picture +//! on the clipboard attaches as a picture, and text pastes as text. +//! +//! egui-winit answers a paste shortcut by reading the clipboard's *text*: with text it sends a +//! `Paste` event, without it nothing at all, not even the key press. So a clipboard that holds +//! only a picture or only files (a screenshot, files copied in Explorer) is seen through the V +//! key coming up (Shift+Insert likewise), which is still sent. Files and a picture are read with +//! arboard, which gives a file list on Windows, macOS and Linux (X11 and Wayland data-control). +//! Gap: macOS delivers no key-up while Cmd is held, so there a picture-only or files-only paste +//! doesn't arrive (text and files that come with text do); the + menu's "Paste a picture" works. + +use std::path::{Path, PathBuf}; + +use super::SolveApp; + +/// A picture on the clipboard: RGBA rows, as the system gives them. +pub struct Picture { + pub width: usize, + pub height: usize, + pub rgba: Vec, +} + +/// What the system clipboard can give besides text; read only when a paste needs it. +pub trait Clipboard { + fn files(&mut self) -> Vec; + fn picture(&mut self) -> Option; +} + +/// The system's clipboard. +pub struct System; + +impl Clipboard for System { + fn files(&mut self) -> Vec { + arboard::Clipboard::new().and_then(|mut c| c.get().file_list()).unwrap_or_default() + } + fn picture(&mut self) -> Option { + let i = arboard::Clipboard::new().and_then(|mut c| c.get_image()).ok()?; + Some(Picture { width: i.width, height: i.height, rgba: i.bytes.into_owned() }) + } +} + +/// What a paste does. +pub enum Paste { + /// Leave it to the text box. + Text, + Files(Vec), + Picture(Picture), + Nothing, +} + +/// Decide a paste. `text` is the clipboard's text when the shortcut brought some. Files win over +/// text (file managers put the files' names on the clipboard as text too); text wins over a +/// picture (a spreadsheet's cells come with a picture of them). +pub fn decide(text: Option<&str>, clip: &mut dyn Clipboard) -> Paste { + let files = clip.files(); + if !files.is_empty() { + return Paste::Files(files); + } + if let Some(text) = text { + let listed = files_in_text(text); + return if listed.is_empty() { Paste::Text } else { Paste::Files(listed) }; + } + clip.picture().map_or(Paste::Nothing, Paste::Picture) +} + +/// The files a text names, when it is a list of `file://` links to files that exist (what some +/// file managers put on the clipboard) and nothing else. +pub fn files_in_text(text: &str) -> Vec { + let mut out = Vec::new(); + for line in text.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#')) { + let Some(path) = line.strip_prefix("file://").and_then(uri_path) else { return Vec::new() }; + if !path.is_file() { + return Vec::new(); + } + out.push(path); + } + out +} + +/// The path of a `file://` link's rest (`/home/a%20b`, `localhost/home/a`, `/C:/Users/a`). +fn uri_path(rest: &str) -> Option { + let rest = rest.strip_prefix("localhost").unwrap_or(rest); + if !rest.starts_with('/') { + return None; + } + let bytes = rest.as_bytes(); + let mut raw = Vec::with_capacity(bytes.len()); + let mut i = 0; + while let Some(&b) = bytes.get(i) { + if b == b'%' { + let hex = rest.get(i + 1..i + 3)?; + raw.push(u8::from_str_radix(hex, 16).ok()?); + i += 3; + } else { + raw.push(b); + i += 1; + } + } + let s = String::from_utf8(raw).ok()?; + // A Windows drive: `/C:/Users` is `C:/Users`. + let drive = s.as_bytes(); + let s = if drive.get(2) == Some(&b':') && drive.get(1).is_some_and(u8::is_ascii_alphabetic) { s.get(1..)?.to_string() } else { s }; + Some(Path::new(&s).to_path_buf()) +} + +/// How long after a text paste the V key coming up still belongs to it. +const SAME_PASTE_SECS: f64 = 1.5; + +/// The paste shortcut for the focused text box this frame. Call before the box is drawn: a paste +/// that is files is taken out of the input, so the box doesn't type their names. +pub fn handle(app: &mut SolveApp, ui: &egui::Ui) { + let now = ui.input(|i| i.time); + let (text, released) = ui.input(|i| { + let text = i.events.iter().find_map(|e| if let egui::Event::Paste(t) = e { Some(t.clone()) } else { None }); + let released = i.events.iter().any(|e| { + matches!(e, egui::Event::Key { key, pressed: false, modifiers, .. } + if (*key == egui::Key::V && modifiers.command) || (*key == egui::Key::Insert && modifiers.shift)) + }); + (text, released) + }); + let after_text = app.agent_chat.text_pasted_at.is_some_and(|at| (0.0..SAME_PASTE_SECS).contains(&(now - at))); + if text.is_none() && !(released && !after_text) { + if released { + app.agent_chat.text_pasted_at = None; + } + return; + } + let paste = decide(text.as_deref(), &mut System); + if text.is_some() { + app.agent_chat.text_pasted_at = if matches!(paste, Paste::Text) { Some(now) } else { None }; + } else { + app.agent_chat.text_pasted_at = None; + } + apply(app, ui, paste, text.is_some()); +} + +/// Do what [`decide`] said. +fn apply(app: &mut SolveApp, ui: &egui::Ui, paste: Paste, had_text: bool) { + match paste { + Paste::Text | Paste::Nothing => {} + Paste::Files(paths) => { + if had_text { + ui.input_mut(|i| i.events.retain(|e| !matches!(e, egui::Event::Paste(_)))); + } + super::attach_dropped(app, paths.into_iter()); + } + Paste::Picture(p) => { + if let Err(e) = super::attach_rgba(app, p.width, p.height, &p.rgba) { + app.agent_chat.notice(e, true); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[derive(Default)] + struct Fake { + files: Vec, + picture: Option<(usize, usize)>, + } + + impl Clipboard for Fake { + fn files(&mut self) -> Vec { + self.files.clone() + } + fn picture(&mut self) -> Option { + self.picture.map(|(width, height)| Picture { width, height, rgba: vec![255; width * height * 4] }) + } + } + + #[test] + fn a_picture_alone_attaches_as_a_picture() { + let mut clip = Fake { picture: Some((2, 2)), ..Fake::default() }; + assert!(matches!(decide(None, &mut clip), Paste::Picture(p) if (p.width, p.height) == (2, 2))); + assert!(matches!(decide(None, &mut Fake::default()), Paste::Nothing), "an empty clipboard does nothing"); + } + + #[test] + fn copied_files_attach_even_when_their_names_came_as_text() { + let files = vec![PathBuf::from("/a/part.step"), PathBuf::from("/a/brief.pdf")]; + let mut clip = Fake { files: files.clone(), picture: Some((1, 1)) }; + assert!(matches!(decide(None, &mut clip), Paste::Files(f) if f == files), "files alone"); + assert!(matches!(decide(Some("part.step\nbrief.pdf"), &mut clip), Paste::Files(f) if f == files), "with their names as text"); + } + + #[test] + fn text_pastes_as_text_even_with_a_picture_beside_it() { + let mut clip = Fake { picture: Some((1, 1)), ..Fake::default() }; + assert!(matches!(decide(Some("wall 2 mm"), &mut clip), Paste::Text)); + } + + #[test] + fn a_text_of_file_links_attaches_the_files_but_other_text_does_not() { + let d = std::env::temp_dir().join(format!("solidcraft-paste-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + let spaced = d.join("my part.stl"); + std::fs::write(&spaced, b"solid").unwrap(); + let plain = d.join("brief.md"); + std::fs::write(&plain, b"x").unwrap(); + let link = |p: &Path| format!("file://{}", p.to_string_lossy().replace(' ', "%20")); + let list = format!("# copied\n{}\r\n{}\n", link(&spaced), link(&plain)); + assert_eq!(files_in_text(&list), vec![spaced.clone(), plain.clone()]); + assert!(matches!(decide(Some(&list), &mut Fake::default()), Paste::Files(f) if f.len() == 2)); + assert!(files_in_text(&format!("{}\nsee also", link(&plain))).is_empty(), "a line that is not a link: it is text"); + assert!(files_in_text(&link(&d.join("missing.png"))).is_empty(), "a file that isn't there: it is text"); + assert!(files_in_text(&link(&d)).is_empty(), "a folder is not a file"); + assert!(files_in_text("https://example.com/a.png").is_empty()); + assert!(files_in_text("file://host/share/a.png").is_empty(), "another machine's file"); + assert!(files_in_text("file:///a/%zz").is_empty(), "a bad escape"); + let _ = std::fs::remove_dir_all(&d); + } + + #[test] + fn links_to_windows_drives_lose_the_leading_slash() { + assert_eq!(uri_path("/C:/Users/a%20b/part.step"), Some(PathBuf::from("C:/Users/a b/part.step"))); + assert_eq!(uri_path("localhost/home/a"), Some(PathBuf::from("/home/a"))); + assert_eq!(uri_path("relative"), None); + } +} From dc27988bc2830e2380efb3d92a43ed7c242512bf Mon Sep 17 00:00:00 2001 From: bherbruck Date: Mon, 19 Oct 2026 00:02:29 -0400 Subject: [PATCH 040/225] Agent chat: PDFs as documents, any other file by reference (#2812) (#2858) A PDF goes whole to agents that take embedded documents; to the others, or past 12 MB, the message names it with its type, size and place. Any file that is not a picture, text or CAD file is attached by reference instead of refused. Chips show the type's extension; the file dialog offers All files. --- apps/solidcraft/src/main.rs | 3 +- assets/locales/en.json | 3 +- assets/locales/ja.json | 3 +- assets/locales/zh.json | 3 +- crates/ui-egui/src/agent_chat/acp.rs | 14 ++ crates/ui-egui/src/agent_chat/acp_client.rs | 4 + crates/ui-egui/src/agent_chat/api_client.rs | 8 +- crates/ui-egui/src/agent_chat/attach.rs | 232 ++++++++++++++++++-- crates/ui-egui/src/agent_chat/backend.rs | 28 +++ crates/ui-egui/src/agent_chat/mod.rs | 17 +- crates/ui-egui/src/agent_chat/panel.rs | 7 +- 11 files changed, 280 insertions(+), 42 deletions(-) diff --git a/apps/solidcraft/src/main.rs b/apps/solidcraft/src/main.rs index 014a58428..d346b1f2d 100644 --- a/apps/solidcraft/src/main.rs +++ b/apps/solidcraft/src/main.rs @@ -179,7 +179,8 @@ fn services(cc: &eframe::CreationContext<'_>) -> Services { } } let all: Vec<&str> = all.iter().map(String::as_str).collect(); - let future = file_parent.clone().add_filter(label, &all).pick_file(); + // Any other file attaches by reference, so the list is not the only choice. + let future = file_parent.clone().add_filter(label, &all).add_filter("All files", &["*"]).pick_file(); Box::pin(async move { future.await.map(|p| p.path().to_string_lossy().into_owned()) }) })), pick_program: Some(Box::new(move || { diff --git a/assets/locales/en.json b/assets/locales/en.json index 17b92389b..6c2253456 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -859,7 +859,7 @@ "ui.agent_chat_approval": "Allow the agent to do this?", "ui.agent_chat_attach_view": "Attach view", "ui.agent_chat_attach_view_tip": "Send a picture of the current view with the message", - "ui.agent_chat_attachable": "Pictures, text and CAD files", + "ui.agent_chat_attachable": "Pictures, PDFs, text and CAD files", "ui.agent_chat_auth_agent": "Sign in with {name}", "ui.agent_chat_auth_env": "Set {vars} in your environment and restart SolidCraft.", "ui.agent_chat_auth_needed": "The agent asks you to sign in. You sign in with the agent itself; SolidCraft never sees your password or keys.", @@ -891,7 +891,6 @@ "ui.agent_chat_file_error": "{name}: {error}", "ui.agent_chat_file_heic": "{name}: HEIC pictures can't be read here; export it as JPEG or PNG first", "ui.agent_chat_file_importing": "Importing into the design…", - "ui.agent_chat_file_kinds": "{name}: pictures (PNG, JPEG, GIF, WebP, BMP, TIFF), text files (SVG too) and CAD files (STEP, IGES, FreeCAD, Rhino, STL, 3MF, OBJ, glTF) can be attached", "ui.agent_chat_file_loading": "Reading the file…", "ui.agent_chat_file_not_a_file": "{name}: not a file", "ui.agent_chat_file_not_a_picture": "{name}: not a picture", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 1a25af5d6..396aebaee 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -859,7 +859,7 @@ "ui.agent_chat_approval": "エージェントにこの操作を許可しますか?", "ui.agent_chat_attach_view": "ビューを添付", "ui.agent_chat_attach_view_tip": "現在のビューの画像をメッセージと一緒に送ります", - "ui.agent_chat_attachable": "画像・テキスト・CAD ファイル", + "ui.agent_chat_attachable": "画像・PDF・テキスト・CAD ファイル", "ui.agent_chat_auth_agent": "{name} でサインイン", "ui.agent_chat_auth_env": "環境変数 {vars} を設定して SolidCraft を再起動してください。", "ui.agent_chat_auth_needed": "エージェントがサインインを求めています。サインインはエージェント自身で行います。SolidCraft がパスワードやキーを見ることはありません。", @@ -891,7 +891,6 @@ "ui.agent_chat_file_error": "{name}: {error}", "ui.agent_chat_file_heic": "{name}: HEIC 画像はここでは読めません。先に JPEG か PNG に書き出してください", "ui.agent_chat_file_importing": "デザインにインポート中…", - "ui.agent_chat_file_kinds": "{name}: 添付できるのは画像 (PNG、JPEG、GIF、WebP、BMP、TIFF)、テキストファイル (SVG も)、CAD ファイル (STEP、IGES、FreeCAD、Rhino、STL、3MF、OBJ、glTF) です", "ui.agent_chat_file_loading": "ファイルを読み込み中…", "ui.agent_chat_file_not_a_file": "{name}: ファイルではありません", "ui.agent_chat_file_not_a_picture": "{name}: 画像ではありません", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index 6519da022..c9eafe6ec 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -859,7 +859,7 @@ "ui.agent_chat_approval": "允许智能体执行此操作吗?", "ui.agent_chat_attach_view": "附加视图", "ui.agent_chat_attach_view_tip": "随消息发送当前视图的图片", - "ui.agent_chat_attachable": "图片、文本和 CAD 文件", + "ui.agent_chat_attachable": "图片、PDF、文本和 CAD 文件", "ui.agent_chat_auth_agent": "使用 {name} 登录", "ui.agent_chat_auth_env": "请在环境中设置 {vars},然后重启 SolidCraft。", "ui.agent_chat_auth_needed": "智能体要求你登录。登录在智能体本身完成;SolidCraft 从不接触你的密码或密钥。", @@ -891,7 +891,6 @@ "ui.agent_chat_file_error": "{name}:{error}", "ui.agent_chat_file_heic": "{name}:这里无法读取 HEIC 图片;请先导出为 JPEG 或 PNG", "ui.agent_chat_file_importing": "正在导入设计…", - "ui.agent_chat_file_kinds": "{name}:可以附加图片(PNG、JPEG、GIF、WebP、BMP、TIFF)、文本文件(包括 SVG)和 CAD 文件(STEP、IGES、FreeCAD、Rhino、STL、3MF、OBJ、glTF)", "ui.agent_chat_file_loading": "正在读取文件…", "ui.agent_chat_file_not_a_file": "{name}:不是文件", "ui.agent_chat_file_not_a_picture": "{name}:不是图片", diff --git a/crates/ui-egui/src/agent_chat/acp.rs b/crates/ui-egui/src/agent_chat/acp.rs index 28315f8d6..56c159edd 100644 --- a/crates/ui-egui/src/agent_chat/acp.rs +++ b/crates/ui-egui/src/agent_chat/acp.rs @@ -149,6 +149,12 @@ pub fn set_model_params(session: &str, model: &str) -> Value { json!({"sessionId": session, "modelId": model}) } +/// Whether the agent takes embedded documents in a message +/// (`agentCapabilities.promptCapabilities.embeddedContext`: it reads `resource` blocks). +pub fn takes_documents(init: &Value) -> bool { + init.pointer("/agentCapabilities/promptCapabilities/embeddedContext").and_then(Value::as_bool).unwrap_or(false) +} + /// Whether the agent takes pictures in a message (`agentCapabilities.promptCapabilities.image`). pub fn takes_images(init: &Value) -> bool { init.pointer("/agentCapabilities/promptCapabilities/image").and_then(Value::as_bool).unwrap_or(false) @@ -461,6 +467,14 @@ pub fn split_command(line: &str) -> Vec { mod tests { use super::*; + #[test] + fn documents_are_taken_only_when_the_agent_says_so() { + let yes = json!({"agentCapabilities": {"promptCapabilities": {"image": true, "embeddedContext": true}}}); + let no = json!({"agentCapabilities": {"promptCapabilities": {"image": true}}}); + assert!(takes_documents(&yes) && takes_images(&yes)); + assert!(!takes_documents(&no) && !takes_documents(&json!({}))); + } + #[test] fn commands_split_like_a_shell_without_one() { assert_eq!(split_command("gemini --acp"), ["gemini", "--acp"]); diff --git a/crates/ui-egui/src/agent_chat/acp_client.rs b/crates/ui-egui/src/agent_chat/acp_client.rs index ca9e16b76..82918e90f 100644 --- a/crates/ui-egui/src/agent_chat/acp_client.rs +++ b/crates/ui-egui/src/agent_chat/acp_client.rs @@ -33,6 +33,7 @@ pub struct AcpBackend { session: Option, agent: String, images: bool, + documents: bool, auth: Vec, /// Open permission questions: our key → the agent's request id. permissions: HashMap, @@ -54,6 +55,7 @@ impl AcpBackend { session: None, agent: String::new(), images: false, + documents: false, auth: Vec::new(), permissions: HashMap::new(), next_key: 0, @@ -82,6 +84,7 @@ impl AcpBackend { (Pending::Initialize, Ok(v)) => { self.agent = acp::agent_info(&v); self.images = acp::takes_images(&v); + self.documents = acp::takes_documents(&v); self.auth = acp::auth_methods(&v); self.new_session(); } @@ -94,6 +97,7 @@ impl AcpBackend { if let Some((current, available)) = acp::models(&v) { out.push(Event::Models { current, available }); } + out.push(Event::Documents(self.documents)); out.push(Event::Ready { agent: self.agent.clone(), images: self.images }); } None => out.push(Event::Error("session/new: no sessionId".into())), diff --git a/crates/ui-egui/src/agent_chat/api_client.rs b/crates/ui-egui/src/agent_chat/api_client.rs index 8c50fd316..39704695a 100644 --- a/crates/ui-egui/src/agent_chat/api_client.rs +++ b/crates/ui-egui/src/agent_chat/api_client.rs @@ -404,9 +404,11 @@ fn user_message(parts: &[PromptPart]) -> Value { } let content: Vec = parts .iter() - .map(|p| match p { - PromptPart::Text(t) => json!({"type": "text", "text": t}), - PromptPart::Image { mime, base64 } => json!({"type": "image_url", "image_url": {"url": format!("data:{mime};base64,{base64}")}}), + .filter_map(|p| match p { + PromptPart::Text(t) => Some(json!({"type": "text", "text": t})), + PromptPart::Image { mime, base64 } => Some(json!({"type": "image_url", "image_url": {"url": format!("data:{mime};base64,{base64}")}})), + // This endpoint takes no documents (the chat doesn't send any); the message names the file. + PromptPart::Document { .. } => None, }) .collect(); json!({"role": "user", "content": content}) diff --git a/crates/ui-egui/src/agent_chat/attach.rs b/crates/ui-egui/src/agent_chat/attach.rs index 5926e8cae..926aae003 100644 --- a/crates/ui-egui/src/agent_chat/attach.rs +++ b/crates/ui-egui/src/agent_chat/attach.rs @@ -1,9 +1,10 @@ //! Files a person adds to a message (the + button, a drop on the chat, a paste): pictures go to the -//! agent with it, text files go in as text, and CAD files are imported into the design, the agent -//! being told what arrived. Each file is checked and bounded before it is kept; a refused one says -//! why. +//! agent with it, text files go in as text, PDFs go as documents to agents that take them, CAD +//! files are imported into the design, and any other file is named by reference (its type, size +//! and place on this machine) for the agent to read with its own tools. The agent is told what +//! arrived. Each file is checked and bounded before it is kept; a refused one says why. -use std::path::Path; +use std::path::{Path, PathBuf}; use std::sync::Arc; use super::backend::{self, PromptPart}; @@ -27,6 +28,8 @@ pub const MAX_FILES: usize = 8; const MAX_PICTURE_BYTES: u64 = 40 * 1024 * 1024; /// Largest text file sent in full. const MAX_TEXT_BYTES: u64 = 256 * 1024; +/// Largest PDF sent as a document; a bigger one goes by reference. +const MAX_PDF_BYTES: u64 = 12 * 1024 * 1024; /// A picture's longer side is scaled down to this before it is sent. pub const MAX_SIDE: u32 = 2048; /// Largest picture sent, as it came or re-encoded: its base64 (a third larger) stays under 5 MB, @@ -47,9 +50,9 @@ const TEXT_EXTS: &[&str] = &["svg", "txt", "md", "markdown", "json", "csv", "tsv /// importers themselves). const CAD_EXTS: &[&str] = &["step", "stp", "igs", "iges", "FCStd", "3dm", "stl", "3mf", "obj", "glb", "gltf"]; -/// Every extension that can be attached, pictures first (the file picker's list). +/// Every extension the file picker lists first, pictures first (any other file can be chosen too). pub fn extensions() -> Vec<&'static str> { - PICTURE_EXTS.iter().chain(TEXT_EXTS).chain(CAD_EXTS).copied().collect() + PICTURE_EXTS.iter().chain(TEXT_EXTS).chain(CAD_EXTS).chain(&["pdf"]).copied().collect() } /// What a file is, by its extension. @@ -58,6 +61,8 @@ pub enum Kind { Picture, Text, Cad, + Pdf, + /// Anything else, attached by reference. Other, } @@ -66,6 +71,7 @@ pub fn kind(path: &Path) -> Kind { match ext.as_str() { e if PICTURE_EXTS.contains(&e) => Kind::Picture, e if TEXT_EXTS.contains(&e) => Kind::Text, + "pdf" => Kind::Pdf, _ => { let p = path.to_string_lossy(); if solidcraft_engine::io::is_step_path(&p) || solidcraft_engine::io::is_mesh_path(&p) { Kind::Cad } else { Kind::Other } @@ -82,6 +88,17 @@ pub enum Content { size: [u32; 2], }, Text(Arc), + /// A PDF, sent whole as a document to an agent that takes them. + Pdf { + bytes: Arc>, + path: PathBuf, + }, + /// A file the agent is pointed to, not given: what it is, its size and where it is. + Reference { + path: PathBuf, + size: u64, + mime: &'static str, + }, /// A CAD file imported into the design as its own component. Imported, } @@ -104,6 +121,70 @@ impl Attachment { pub fn is_picture(&self) -> bool { matches!(self.content, Content::Picture { .. }) } + /// The chip's mark for a file with no thumbnail: its extension, in capitals, cut to fit. + pub fn mark(&self) -> String { + let ext = Path::new(&self.name).extension().and_then(|e| e.to_str()).unwrap_or(""); + ext.chars().take(4).collect::().to_uppercase() + } +} + +/// What a file is called to the agent, by its extension. +fn mime_of(path: &Path) -> &'static str { + let ext = path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).unwrap_or_default(); + match ext.as_str() { + "pdf" => "application/pdf", + "zip" => "application/zip", + "7z" => "application/x-7z-compressed", + "gz" | "tgz" => "application/gzip", + "dxf" => "image/vnd.dxf", + "dwg" => "image/vnd.dwg", + "step" | "stp" => "model/step", + "iges" | "igs" => "model/iges", + "stl" => "model/stl", + "obj" => "model/obj", + "3mf" => "model/3mf", + "gltf" => "model/gltf+json", + "glb" => "model/gltf-binary", + "xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + "docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + "pptx" => "application/vnd.openxmlformats-officedocument.presentationml.presentation", + "mp4" | "mov" | "webm" => "video/mp4", + "wav" => "audio/wav", + "mp3" => "audio/mpeg", + _ => "application/octet-stream", + } +} + +/// A size for people: `1.5 MB`. +fn size_text(bytes: u64) -> String { + const KB: f64 = 1024.0; + let b = bytes as f64; + if b < KB { + format!("{bytes} bytes") + } else if b < KB * KB { + format!("{:.0} KB", b / KB) + } else if b < KB * KB * KB { + format!("{:.1} MB", b / KB / KB) + } else { + format!("{:.1} GB", b / KB / KB / KB) + } +} + +/// A `file://` link to a path, for a document sent to an agent. +fn file_uri(path: &Path) -> String { + let mut s = path.to_string_lossy().replace('\\', "/"); + if !s.starts_with('/') { + s.insert(0, '/'); + } + let mut out = String::from("file://"); + for b in s.bytes() { + if b.is_ascii_alphanumeric() || matches!(b, b'/' | b'-' | b'_' | b'.' | b'~' | b':') { + out.push(char::from(b)); + } else { + out.push_str(&format!("%{b:02X}")); + } + } + out } pub(crate) fn name_of(path: &Path) -> String { @@ -134,13 +215,29 @@ pub fn read(path: &Path) -> Result { Ok(Attachment { id: 0, name, content: Content::Text(Arc::new(text)), thumb: None }) } Kind::Cad => Err(refused("ui.agent_chat_file_cad_not_read", &name, &[])), + Kind::Pdf => { + let path = absolute(path); + // Too big to send: the agent is pointed to it instead. + if meta.len() > MAX_PDF_BYTES { + return Ok(Attachment { id: 0, name, content: Content::Reference { path, size: meta.len(), mime: "application/pdf" }, thumb: None }); + } + let bytes = std::fs::read(&path).map_err(|e| failed(&name, e))?; + Ok(Attachment { id: 0, name, content: Content::Pdf { bytes: Arc::new(bytes), path }, thumb: None }) + } Kind::Other if matches!(path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).as_deref(), Some("heic" | "heif")) => { Err(refused("ui.agent_chat_file_heic", &name, &[])) } - Kind::Other => Err(refused("ui.agent_chat_file_kinds", &name, &[])), + Kind::Other => { + Ok(Attachment { id: 0, name, content: Content::Reference { path: absolute(path), size: meta.len(), mime: mime_of(path) }, thumb: None }) + } } } +/// The path as an absolute one, so the agent (working in another folder) finds the file. +fn absolute(path: &Path) -> PathBuf { + std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf()) +} + /// A picture from a file's bytes: decoded within limits, and sent as it came when the agents read /// that format (PNG, JPEG, GIF, WebP), it is at most [`MAX_SIDE`] on a side and at most /// [`MAX_SENT_BYTES`]; otherwise re-encoded (see [`encoded`]). @@ -239,10 +336,10 @@ fn thumbnail(img: &image::DynamicImage) -> Option> { /// What the message says about its files, after the person's words: the text files' text, and the /// pictures and imported parts by name (the agent sees the pictures themselves as images). -/// `pictures_sent`: whether this agent takes pictures. The text files share `budget` characters +/// `pictures_sent` and `documents_sent`: whether this agent takes pictures and PDFs. The text files share `budget` characters /// in order: one that doesn't fit is cut and says how much is missing, and one past the budget /// is named only, so the message stays within the prompt cap. -pub fn note(files: &[Attachment], pictures_sent: bool, budget: usize) -> String { +pub fn note(files: &[Attachment], pictures_sent: bool, documents_sent: bool, budget: usize) -> String { let mut out = String::new(); let pictures: Vec<&str> = files.iter().filter(|f| f.is_picture()).map(|f| f.name.as_str()).collect(); if !pictures.is_empty() { @@ -270,6 +367,31 @@ pub fn note(files: &[Attachment], pictures_sent: bool, budget: usize) -> String left = 0; } } + Content::Pdf { path, bytes } if documents_sent => { + out += &format!( + "\n\nAttached PDF `{}` ({}, at {}): sent with this message as a document.", + f.name, + size_text(bytes.len() as u64), + path.display() + ); + } + // An agent that takes no documents is pointed to the file, as for any other file. + Content::Pdf { path, bytes } => { + out += &format!( + "\n\nAttached file `{}` (PDF, {}, at {}): read it with your own tools; it is not in this message.", + f.name, + size_text(bytes.len() as u64), + path.display() + ); + } + Content::Reference { path, size, mime } => { + out += &format!( + "\n\nAttached file `{}` ({mime}, {}, at {}): read it with your own tools; it is not in this message.", + f.name, + size_text(*size), + path.display() + ); + } Content::Imported => out += &format!("\n\n(I added `{}` to the design as a component of its own.)", f.name), Content::Picture { .. } => {} } @@ -277,12 +399,18 @@ pub fn note(files: &[Attachment], pictures_sent: bool, budget: usize) -> String out } -/// The pictures as image parts of the message. -pub fn parts(files: &[Attachment]) -> Vec { +/// The pictures and PDFs as parts of the message, to the agents that take them. +pub fn parts(files: &[Attachment], pictures: bool, documents: bool) -> Vec { files .iter() .filter_map(|f| match &f.content { - Content::Picture { mime, bytes, .. } => Some(PromptPart::Image { mime: (*mime).to_string(), base64: backend::base64(bytes) }), + Content::Picture { mime, bytes, .. } if pictures => Some(PromptPart::Image { mime: (*mime).to_string(), base64: backend::base64(bytes) }), + Content::Pdf { bytes, path } if documents => Some(PromptPart::Document { + name: f.name.clone(), + uri: file_uri(path), + mime: "application/pdf".to_string(), + base64: backend::base64(bytes), + }), _ => None, }) .collect() @@ -390,9 +518,6 @@ mod tests { let binary = d.join("bin.json"); std::fs::write(&binary, [0xff, 0xfe, 0x00, 0x80]).unwrap(); assert!(read(&binary).unwrap_err().contains("UTF-8")); - let other = d.join("movie.mov"); - std::fs::write(&other, b"x").unwrap(); - assert!(read(&other).unwrap_err().contains("can be attached")); assert!(read(&d.join("missing.png")).is_err()); assert_eq!(kind(Path::new("part.STEP")), Kind::Cad); assert_eq!(kind(Path::new("mount.stl")), Kind::Cad); @@ -411,12 +536,9 @@ mod tests { let d = dir("lang"); let binary = d.join("bin.json"); std::fs::write(&binary, [0xff, 0xfe, 0x00, 0x80]).unwrap(); - let other = d.join("movie.mov"); - std::fs::write(&other, b"x").unwrap(); { let _ja = crate::i18n::scope("ja"); assert!(read(&binary).unwrap_err().contains("UTF-8 のテキストではありません")); - assert!(read(&other).unwrap_err().starts_with("movie.mov: 添付できるのは")); } { let _zh = crate::i18n::scope("zh"); @@ -467,12 +589,12 @@ mod tests { fn attached_text_is_kept_within_the_prompt_budget() { let file = |n: &str, len: usize| Attachment { id: 0, name: n.into(), content: Content::Text(Arc::new("x".repeat(len))), thumb: None }; let files = vec![file("a.md", 600), file("b.md", 600), file("c.md", 600)]; - let n = note(&files, true, 1000); + let n = note(&files, true, false, 1000); assert!(n.contains("`a.md`") && n.contains("`b.md`") && n.contains("`c.md`"), "every file is named: {n}"); assert!(n.matches('x').count() <= 1000, "the files' text stays within the budget"); assert!(n.contains("200 more characters"), "a cut file says how much is missing: {n}"); assert!(n.contains("left out"), "a file past the budget is named only: {n}"); - assert_eq!(note(&files, true, usize::MAX).matches('x').count(), 1800, "with room, every file goes whole"); + assert_eq!(note(&files, true, false, usize::MAX).matches('x').count(), 1800, "with room, every file goes whole"); } #[test] @@ -481,13 +603,77 @@ mod tests { let text = Attachment { id: 0, name: "brief.md".into(), content: Content::Text(Arc::new("wall 2 mm\n".into())), thumb: None }; let part = Attachment::imported("motor.step".into()); let files = vec![pic, text, part]; - let n = note(&files, true, usize::MAX); + let n = note(&files, true, false, usize::MAX); assert!(n.contains("Attached pictures: target.png."), "{n}"); assert!(n.contains("Attached file `brief.md`:\n```\nwall 2 mm\n```"), "{n}"); assert!(n.contains("`motor.step` to the design"), "{n}"); - assert!(note(&files, false, usize::MAX).contains("not sent")); - let p = parts(&files); + assert!(note(&files, false, false, usize::MAX).contains("not sent")); + let p = parts(&files, true, true); assert_eq!(p.len(), 1); assert!(matches!(&p[0], PromptPart::Image { mime, base64 } if mime == "image/png" && base64.starts_with("iVBORw0KGgo"))); } + + /// Any file that is neither a picture, text, CAD nor a PDF is named by reference (what it is, + /// its size and its place) instead of refused; the agent reads it with its own tools. + #[test] + fn other_files_go_by_reference() { + let d = dir("reference"); + let zip = d.join("fixtures.zip"); + std::fs::write(&zip, vec![0u8; 3000]).unwrap(); + let dxf = d.join("outline.DXF"); + std::fs::write(&dxf, b"0\nSECTION\n").unwrap(); + let a = read(&zip).unwrap(); + let Content::Reference { path, size, mime } = &a.content else { panic!("a reference") }; + assert_eq!((*size, *mime), (3000, "application/zip")); + assert!(path.is_absolute() && path.ends_with("fixtures.zip")); + assert!(a.thumb.is_none() && a.mark() == "ZIP"); + assert!(matches!(read(&dxf).unwrap().content, Content::Reference { mime: "image/vnd.dxf", .. }), "by extension, in any case"); + let bare = d.join("LICENSE_BLOB"); + std::fs::write(&bare, b"x").unwrap(); + assert!(matches!(read(&bare).unwrap().content, Content::Reference { mime: "application/octet-stream", .. }), "no extension"); + let files = vec![a]; + let n = note(&files, true, true, usize::MAX); + assert!(n.contains("Attached file `fixtures.zip` (application/zip, 3 KB, at "), "{n}"); + assert!(n.contains("fixtures.zip): read it with your own tools"), "{n}"); + assert!(parts(&files, true, true).is_empty(), "a reference sends nothing but the note"); + assert!(read(&d).unwrap_err().contains("not a file"), "a folder is refused"); + assert!(read(&d.join("missing.bin")).is_err()); + let _ = std::fs::remove_dir_all(&d); + } + + /// A PDF goes whole as a document to an agent that takes them (and is named with its place); + /// to one that doesn't, and when it is too big to send, the agent is pointed to the file. + #[test] + fn pdfs_go_as_documents_or_by_reference() { + let d = dir("pdf"); + let pdf = d.join("brief 1.pdf"); + std::fs::write(&pdf, b"%PDF-1.4\n%%EOF\n").unwrap(); + let a = read(&pdf).unwrap(); + assert!(matches!(&a.content, Content::Pdf { bytes, .. } if bytes.starts_with(b"%PDF"))); + assert_eq!(a.mark(), "PDF"); + let files = vec![a]; + let sent = parts(&files, false, true); + let [PromptPart::Document { name, uri, mime, base64 }] = sent.as_slice() else { panic!("one document: {sent:?}") }; + assert_eq!((name.as_str(), mime.as_str()), ("brief 1.pdf", "application/pdf")); + assert!(uri.starts_with("file://") && uri.ends_with("/brief%201.pdf"), "{uri}"); + assert!(base64.starts_with("JVBERi0"), "the PDF's bytes: {base64}"); + assert!(note(&files, false, true, usize::MAX).contains("sent with this message as a document")); + assert!(parts(&files, true, false).is_empty(), "an agent with no documents gets none"); + let n = note(&files, true, false, usize::MAX); + assert!(n.contains("(PDF, 15 bytes, at ") && n.contains("read it with your own tools"), "{n}"); + let big = d.join("drawing set.pdf"); + std::fs::write(&big, vec![b'x'; usize::try_from(MAX_PDF_BYTES).unwrap() + 1]).unwrap(); + let b = read(&big).unwrap(); + assert!(matches!(b.content, Content::Reference { mime: "application/pdf", .. }), "too big to send: by reference"); + assert!(parts(&[b], true, true).is_empty()); + let _ = std::fs::remove_dir_all(&d); + } + + #[test] + fn links_to_files_are_escaped() { + assert_eq!(file_uri(Path::new("/home/a b/ü.pdf")), "file:///home/a%20b/%C3%BC.pdf"); + assert_eq!(file_uri(Path::new("C:\\Users\\a\\x.pdf")), "file:///C:/Users/a/x.pdf"); + assert_eq!(size_text(1536), "2 KB"); + assert_eq!(size_text(5 * 1024 * 1024 + 512 * 1024), "5.5 MB"); + } } diff --git a/crates/ui-egui/src/agent_chat/backend.rs b/crates/ui-egui/src/agent_chat/backend.rs index a44a54826..a470ccad9 100644 --- a/crates/ui-egui/src/agent_chat/backend.rs +++ b/crates/ui-egui/src/agent_chat/backend.rs @@ -19,11 +19,21 @@ pub enum PromptPart { mime: String, base64: String, }, + /// A file the agent reads as a document (a PDF), sent only to agents that take documents. + Document { + name: String, + /// Where it is on this machine (a `file://` link). + uri: String, + mime: String, + base64: String, + }, } /// What a backend reports to the panel. #[derive(Clone, Debug, PartialEq)] pub enum Event { + /// Whether the agent takes documents (PDFs) in a message; sent before [`Event::Ready`]. + Documents(bool), /// Ready for a message. `agent`: its name and version; `images`: it takes pictures. Ready { agent: String, images: bool }, /// Text it streams (`thought`: its reasoning, shown dimmed). @@ -136,6 +146,9 @@ pub fn content_blocks(parts: &[PromptPart]) -> Vec { .map(|p| match p { PromptPart::Text(t) => serde_json::json!({"type": "text", "text": t}), PromptPart::Image { mime, base64 } => serde_json::json!({"type": "image", "mimeType": mime, "data": base64}), + PromptPart::Document { uri, mime, base64, .. } => { + serde_json::json!({"type": "resource", "resource": {"uri": uri, "mimeType": mime, "blob": base64}}) + } }) .collect() } @@ -158,4 +171,19 @@ mod tests { assert_eq!(b[1]["type"], "image"); assert_eq!(b[1]["mimeType"], "image/png"); } + + #[test] + fn documents_go_as_embedded_resources() { + let doc = PromptPart::Document { + name: "brief.pdf".into(), + uri: "file:///a/brief.pdf".into(), + mime: "application/pdf".into(), + base64: "AA==".into(), + }; + let b = content_blocks(&[doc]); + assert_eq!(b[0]["type"], "resource"); + assert_eq!(b[0]["resource"]["uri"], "file:///a/brief.pdf"); + assert_eq!(b[0]["resource"]["mimeType"], "application/pdf"); + assert_eq!(b[0]["resource"]["blob"], "AA=="); + } } diff --git a/crates/ui-egui/src/agent_chat/mod.rs b/crates/ui-egui/src/agent_chat/mod.rs index 42b0ecca4..4dad5c60c 100644 --- a/crates/ui-egui/src/agent_chat/mod.rs +++ b/crates/ui-egui/src/agent_chat/mod.rs @@ -303,6 +303,8 @@ pub struct AgentChat { state: Option, agent: String, images: bool, + /// The agent takes documents (PDFs) in a message. + documents: bool, /// Send a picture of the view with the next message. pub attach_view: bool, auth: Vec, @@ -512,6 +514,7 @@ impl AgentChat { /// Take in what the backend reported. fn on_event(&mut self, e: Event) -> Option { match e { + Event::Documents(documents) => self.documents = documents, Event::Ready { agent, images } => { self.agent = agent; self.images = images; @@ -960,14 +963,14 @@ fn start_turn(app: &mut SolveApp, text: String, image: bool, at: Option, /// files are named after the text (text files in full), and pictures go as images to an agent /// that takes them. `at` is the message's place in the conversation, where its picture is kept. fn start_turn_with(app: &mut SolveApp, text: String, image: bool, at: Option, files: Vec, note: Option<&str>) { - let pictures = app.agent_chat.images; + let (pictures, documents) = (app.agent_chat.images, app.agent_chat.documents); let lead = match note { Some(n) => format!("{n}\n\n{text}"), None => text.clone(), }; // The whole message stays within the cap: the files' text gets what the words leave. let budget = MAX_PROMPT.saturating_sub(lead.chars().count() + FILE_NAMES_ROOM); - let about_files = attach::note(&files, pictures, budget); + let about_files = attach::note(&files, pictures, documents, budget); let sent: String = format!("{lead}{about_files}").chars().take(MAX_PROMPT).collect(); let mut parts = vec![PromptPart::Text(sent)]; if image { @@ -979,9 +982,7 @@ fn start_turn_with(app: &mut SolveApp, text: String, image: bool, at: Option log::warn!("the view's picture is left out of the prompt: {e}"), } } - if pictures { - parts.extend(attach::parts(&files)); - } + parts.extend(attach::parts(&files, pictures, documents)); // The undo step is named after the message, or its first file when it has no words. let first_line = text.lines().find(|l| !l.trim().is_empty()).or_else(|| files.first().map(|f| f.name.as_str())).unwrap_or(""); let label: String = first_line.chars().take(48).collect(); @@ -1017,9 +1018,10 @@ pub fn attach_path(app: &mut SolveApp, path: &str) -> std::result::Result Value { "state": c.state().id(), "agent": c.agent, "images": c.images, + "documents": c.documents, "authStatus": c.auth_status, "authMethods": c.auth.iter().map(|m| json!({"id": m.id, "name": m.name, "kind": match &m.kind { acp::AuthKind::Agent => "agent", acp::AuthKind::Terminal { .. } => "terminal", acp::AuthKind::EnvVar { .. } => "env_var" }})).collect::>(), "toolsPort": c.tools_port, diff --git a/crates/ui-egui/src/agent_chat/panel.rs b/crates/ui-egui/src/agent_chat/panel.rs index 7ad6cd836..354185a2d 100644 --- a/crates/ui-egui/src/agent_chat/panel.rs +++ b/crates/ui-egui/src/agent_chat/panel.rs @@ -1278,8 +1278,11 @@ fn chip(ui: &mut egui::Ui, thumbs: &mut std::collections::HashMap { - let (r, _) = ui.allocate_exact_size(vec2(16.0, 20.0), Sense::hover()); - ui.painter().rect_stroke(r.shrink2(vec2(2.0, 3.0)), 2.0, Stroke::new(1.2, t.text_dim), egui::StrokeKind::Inside); + // A page marked with the file's type. + let (r, _) = ui.allocate_exact_size(vec2(28.0, 20.0), Sense::hover()); + let color = if matches!(f.content, attach::Content::Pdf { .. }) { t.error } else { t.text_dim }; + ui.painter().rect_stroke(r.shrink2(vec2(1.0, 1.0)), 2.0, Stroke::new(1.2, color), egui::StrokeKind::Inside); + ui.painter().text(r.center(), Align2::CENTER_CENTER, f.mark(), egui::FontId::proportional(8.5), color); r.width() } }; From d9c3fdb80f112d89b36fe27a905085a0888a4b4d Mon Sep 17 00:00:00 2001 From: bherbruck Date: Mon, 19 Oct 2026 00:03:11 -0400 Subject: [PATCH 041/225] Agent chat: drops on the popped-out window attach (#2812) (#2861) The chat in a window of its own takes the files dropped on it and shows the drop hint while files are dragged over it; a window floating inside the app counts as the chat's place for the app's drop handling. --- crates/ui-egui/src/agent_chat/panel.rs | 15 +++++++++++++- crates/ui-egui/src/agent_chat/tests.rs | 28 ++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/agent_chat/panel.rs b/crates/ui-egui/src/agent_chat/panel.rs index 354185a2d..8f6c792c2 100644 --- a/crates/ui-egui/src/agent_chat/panel.rs +++ b/crates/ui-egui/src/agent_chat/panel.rs @@ -87,6 +87,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { #[cfg(not(target_arch = "wasm32"))] if app.preferences.agent_chat_popped { window(app, &ctx); + show_drop_hint(app, &ctx); return; } let t = Tokens::get(); @@ -304,12 +305,24 @@ fn window(app: &mut SolveApp, ctx: &egui::Context) { // The picture viewer opens over this window, where the click was, not over the main one. gallery_window(app, ui.ctx()); if class == egui::ViewportClass::EmbeddedWindow { - // Floating inside the app: its handles are the main window's, as the panel's are. + // Floating inside the app: its handles are the main window's, as the panel's are. The + // app's own drop handling sees the drops, so the window counts as the chat's place + // (the hint is drawn by the caller). crate::scenario::publish_rect("agent_chat:window", r.response.rect); app.agent_chat.panel_rect = Some(r.response.rect); + app.agent_chat.drop_rect = Some(r.response.rect); return; } let ctx = ui.ctx().clone(); + // A window of its own gets the drops made on it: the whole window is the chat, so there + // is no pointer to ask about (the main window's handling never sees them). + let dropped = ctx.input_mut(|i| std::mem::take(&mut i.raw.dropped_files)); + if !dropped.is_empty() { + attach_dropped(app, dropped.iter().map(|f| f.path().to_path_buf())); + } + if ctx.input(|i| !i.raw.hovered_files.is_empty()) { + drop_hint(&ctx, r.response.rect); + } if ctx.input_mut(|i| i.consume_shortcut(&SHORTCUT)) { toggle(app); } diff --git a/crates/ui-egui/src/agent_chat/tests.rs b/crates/ui-egui/src/agent_chat/tests.rs index 95756ff92..e0211bb9d 100644 --- a/crates/ui-egui/src/agent_chat/tests.rs +++ b/crates/ui-egui/src/agent_chat/tests.rs @@ -1348,6 +1348,34 @@ fn files_dropped_on_the_chat_attach_and_the_app_does_not_open_them() { let _ = std::fs::remove_dir_all(&d); } +/// The chat popped out into its own window takes drops too, and says so while files are dragged +/// over it (#2812). Here the window floats inside the app, as it does where the system can't open +/// one: a drop on the window is the chat's, one elsewhere is not. +#[test] +fn files_dropped_on_the_popped_out_chat_attach() { + use crate::scenario::rect_of; + let d = attachable("popdrop"); + let mut h = narrow_chat(); + h.call("ui.resize", json!({"width": 1600, "height": 1000})); + h.app.preferences.agent_chat_popped = true; + h.frames(4); + let window = rect_of("agent_chat:window").expect("popped out"); + let hovered = || vec![egui::HoveredFile { path: Some(d.join("target.png")), mime: String::new() }]; + h.drag_files(window.center(), hovered(), Vec::new()); + assert!(rect_of("agent_chat:drop_hint").is_some_and(|r| window.contains(r.center())), "the hint over the window"); + let outside = egui::pos2(5.0, 500.0); + assert!(!window.contains(outside)); + h.drag_files(outside, hovered(), Vec::new()); + assert!(rect_of("agent_chat:drop_hint").is_none(), "no hint away from it"); + drop_files(&mut h, window.center(), &[d.join("target.png"), d.join("brief.md")]); + settle_chat(&mut h); + assert_eq!(status(&h.app)["attachments"], json!(["target.png", "brief.md"])); + assert!(!h.app.file_load.busy(), "the app doesn't open them as well"); + drop_files(&mut h, outside, &[d.join("brief.md")]); + assert_eq!(status(&h.app)["attachments"].as_array().map(Vec::len), Some(2), "away from the window: not the chat's"); + let _ = std::fs::remove_dir_all(&d); +} + /// Many files and a long message in a narrow chat: the chips wrap onto more rows and the text box /// keeps to the chat (a row of chips wider than the chat would widen everything under it). #[test] From f9342aa8b6346716f67b43a993e9026d3084142e Mon Sep 17 00:00:00 2001 From: bherbruck Date: Mon, 19 Oct 2026 00:38:57 -0400 Subject: [PATCH 042/225] Malay: drop the "Gap" entry that is not in the English catalog The catalog test rejects ids English doesn't have. Co-authored-by: Claude Opus 5.5 --- assets/locales/ms.json | 1 - 1 file changed, 1 deletion(-) diff --git a/assets/locales/ms.json b/assets/locales/ms.json index 42a7ad4d5..9c5ad68a1 100644 --- a/assets/locales/ms.json +++ b/assets/locales/ms.json @@ -122,7 +122,6 @@ "Follow the camera (Look At sketches)": "Ikut kamera (Pandang Tepat pada lakaran)", "Font": "Fon", "Full Length": "Panjang Penuh", - "Gap": "Sela", "Grid": "Grid", "Height": "Ketinggian", "Hidden edges": "Tepi tersembunyi", From 5122b98af3fc5fe287c2e6d4beee8587a503244b Mon Sep 17 00:00:00 2001 From: bherbruck Date: Mon, 19 Oct 2026 02:16:36 -0400 Subject: [PATCH 043/225] Parameters window: no per-frame re-evaluation on big designs (#2723) The window listed (and so evaluated) every parameter and re-checked the add row's expression on every frame, and laid out every row. It now lists once per design revision, caches the add row's check, and lays out only the rows in view. Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/params_dialog.rs | 107 +++++++++++++++++++++++++++- 1 file changed, 104 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/params_dialog.rs b/crates/ui-egui/src/params_dialog.rs index d50af95c0..fbea97f99 100644 --- a/crates/ui-egui/src/params_dialog.rs +++ b/crates/ui-egui/src/params_dialog.rs @@ -39,6 +39,14 @@ pub struct ParamsDialog { pub error: Option, /// The expression edit to preview: (name, expression). pub preview: Option<(String, String)>, + /// The rows as the engine listed them at one revision of the design (#2723): listing + /// evaluates every parameter, so it happens when the design changes, not every frame. + listed: Option<(u64, Arc>)>, + /// The add row's live check, by (revision, unit, expression). + new_check: Option<((u64, String, String), Result)>, + /// How many times the rows were listed and the add row checked (for the tests). + pub lists: u32, + pub checks: u32, } impl ParamsDialog { @@ -131,7 +139,15 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { let Some(mut d) = app.params.take() else { return }; let t = Tokens::get(); let mut open = true; - let all = rows(app); + let all = if let Some((rev, r)) = d.listed.as_ref().filter(|(rev, _)| *rev == app.session.revision) { + let _ = rev; + r.clone() + } else { + let r = Arc::new(rows(app)); + d.listed = Some((app.session.revision, r.clone())); + d.lists += 1; + r + }; crate::frame::window(ctx, RichText::new(crate::i18n::tr_label("PARAMETERS")).strong().size(13.0), crate::frame::Width::Wide) .id(egui::Id::new("sc_params_dialog")) .open(&mut open) @@ -219,6 +235,25 @@ fn check(app: &mut SolveApp, e: &str, unit: &str) -> Result { } } +/// The add row's check of its expression, kept until the design, unit or text changes. +fn new_check(app: &mut SolveApp, d: &mut ParamsDialog, unit: &str) -> Result { + let key = (app.session.revision, unit.to_string(), d.new_expr.clone()); + if let Some((k, r)) = &d.new_check + && *k == key + { + return r.clone(); + } + let r = check(app, &d.new_expr, unit); + d.checks += 1; + d.new_check = Some((key, r.clone())); + r +} + +/// Height of a row in the tables: tall enough for the text boxes and the combo box. +fn row_height(ui: &egui::Ui) -> f32 { + ui.spacing().interact_size.y.max(20.0) +} + fn table(app: &mut SolveApp, ui: &mut egui::Ui, d: &mut ParamsDialog, rows: &[&Row], salt: &str) { let t = Tokens::get(); egui::Grid::new(("ptable", salt)).num_columns(7).striped(true).spacing([10.0, 4.0]).show(ui, |ui| { @@ -226,8 +261,21 @@ fn table(app: &mut SolveApp, ui: &mut egui::Ui, d: &mut ParamsDialog, rows: &[&R ui.label(RichText::new(h).color(t.text_dim).small()); } ui.end_row(); + // Only the rows in view are laid out (#2723); the others take their height, so the + // scroll bar and the columns stay as they are. A row being edited stays drawn. + let row_h = row_height(ui); + let clip = ui.clip_rect(); for (i, r) in rows.iter().enumerate() { + let top = ui.cursor().min.y; + let in_view = top + row_h >= clip.min.y && top <= clip.max.y; + let busy = d.editing.contains_key(&r.name) || d.comments.contains_key(&r.name) || d.renaming.as_ref().is_some_and(|(o, _)| *o == r.name); + if !in_view && !busy { + ui.allocate_space(egui::vec2(0.0, row_h)); + ui.end_row(); + continue; + } ui.horizontal(|ui| { + ui.set_min_height(row_h); // Favourite star. let star = if r.favorite { RichText::new("★").color(t.accent) } else { RichText::new("☆").color(t.text_dim) }; if ui.add(egui::Button::new(star).frame(false)).on_hover_text(crate::i18n::tr_label("Favourite")).clicked() { @@ -401,7 +449,7 @@ fn add_row(app: &mut SolveApp, ui: &mut egui::Ui, d: &mut ParamsDialog) { }); crate::scenario::publish_handle("param:new:unit", unit_response.response.rect.center()); let unit = UNITS.get(d.new_unit).copied().unwrap_or("mm"); - let bad = check(app, &d.new_expr, unit).is_err(); + let bad = new_check(app, d, unit).is_err(); let mut te = egui::TextEdit::singleline(&mut d.new_expr).id(expr_id).desired_width(170.0); if bad { te = te.text_color(t.error); @@ -409,7 +457,7 @@ fn add_row(app: &mut SolveApp, ui: &mut egui::Ui, d: &mut ParamsDialog) { let resp = ui.add(te); crate::scenario::publish_handle("param:new:expression", resp.rect.center()); let completed = complete(ui, &resp, &mut d.new_expr); - let live = check(app, &d.new_expr, unit); + let live = new_check(app, d, unit); match &live { Ok(v) => ui.label(RichText::new(v).color(t.text_dim)), Err(m) => ui.label(RichText::new(m).color(t.error)), @@ -578,4 +626,57 @@ mod tests { assert_eq!(editing.as_deref(), Some("1.1"), "favourite {favourite}, row {row}"); } } + + /// A design with hundreds of chained parameters. + fn big_design() -> crate::scenario::Harness { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.app.run("parameters.add", json!({"name": "p0", "expression": "10 mm"})).unwrap(); + for i in 1..400 { + h.app.run("parameters.add", json!({"name": format!("p{i}"), "expression": format!("p{} + 1 mm", i - 1)})).unwrap(); + } + h + } + + /// Mean milliseconds per frame over `n` frames. + fn frame_ms(h: &mut crate::scenario::Harness, n: usize) -> f64 { + let start = std::time::Instant::now(); + h.frames(n); + start.elapsed().as_secs_f64() * 1000.0 / n as f64 + } + + /// Frame times with the window closed and open (`cargo test -p solidcraft-ui-egui params_frame_time -- --nocapture`). + #[test] + fn params_frame_time() { + let mut h = big_design(); + h.frames(5); + let closed = frame_ms(&mut h, 20); + h.step(&json!({"start": "parameters.change"})).unwrap(); + h.frames(5); + let open = frame_ms(&mut h, 20); + assert!(h.app.params.is_some()); + eprintln!("params frame time: closed {closed:.2} ms, open {open:.2} ms"); + } + + /// An open window lists and checks once per revision of the design, not once per frame + /// (#2723), and shows a change at once. + #[test] + fn the_window_does_not_re_evaluate_every_frame() { + let mut h = big_design(); + h.step(&json!({"start": "parameters.change"})).unwrap(); + h.frames(30); + let d = h.app.params.as_ref().unwrap(); + assert_eq!((d.lists, d.checks), (1, 1), "30 frames of an unchanged design"); + h.app.run("parameters.change", json!({"name": "p0", "expression": "20 mm"})).unwrap(); + h.frames(30); + let d = h.app.params.as_ref().unwrap(); + assert_eq!((d.lists, d.checks), (2, 2), "one more for the change"); + let shown = d.listed.as_ref().unwrap().1.iter().find(|r| r.name == "p399").and_then(|r| r.value); + assert_eq!(shown, Some(20.0 + 399.0)); + // A comment is a change too. + h.app.run("parameters.comment", json!({"name": "p1", "comment": "hello"})).unwrap(); + h.frames(2); + let d = h.app.params.as_ref().unwrap(); + assert!(d.listed.as_ref().unwrap().1.iter().any(|r| r.name == "p1" && r.comment == "hello")); + } } From 5997d28de73eb7bfc746652dcd4af90f7a5805a7 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Mon, 19 Oct 2026 04:07:39 -0400 Subject: [PATCH 044/225] STEP import: orient each instanced part once (#2814) (#2875) Thanks @bherbruck. --- crates/kernel/src/body.rs | 45 +++++++++++++++++--- crates/kernel/src/ops.rs | 2 +- crates/kernel/src/step_in/mod.rs | 15 ++++++- crates/kernel/src/step_in/parallel.rs | 28 ++++++++++--- crates/kernel/src/step_in/tests.rs | 59 ++++++++++++++++++++++++++- 5 files changed, 134 insertions(+), 15 deletions(-) diff --git a/crates/kernel/src/body.rs b/crates/kernel/src/body.rs index 642826aff..feea4c25a 100644 --- a/crates/kernel/src/body.rs +++ b/crates/kernel/src/body.rs @@ -492,6 +492,12 @@ fn polyline_mid(pts: &[Vec3]) -> (Vec3, f64) { (pts.first().copied().unwrap_or_default(), len) } +#[cfg(test)] +thread_local! { + /// Solids [`Body::new`] meshed on this thread to orient them (tests count the work an import does). + pub(crate) static ORIENTED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// Deflection the orientation mesh uses: coarse enough for a large solid, fine enough that a /// small one still tessellates. `unmeshed_faces` counts at the same value, so the count the /// orientation mesh produced is reused instead of meshing the body again. @@ -559,13 +565,17 @@ impl Body { Ok((volume, missing)) }) }; - let (mut v, mut missing) = orient(tol)?; + #[cfg(test)] + ORIENTED.with(|n| n.set(n.get() + 1)); + // The faces missing from the coarse mesh are the same whichever way the solid turns out + // to face, so the count is kept for `unmeshed_faces` either way. + let (mut v, missing) = orient(tol)?; // A long thin round part (a through hole's tool: a cylinder whose vertices all lie on // its seam, so they span its length only) meshed that coarsely can come out with a // negative volume when it is outward already: check finely before turning it inside out. let fine = (tol * 0.02).max(1e-4); if v < 0.0 && fine < tol { - (v, missing) = orient(fine)?; + (v, _) = orient(fine)?; } if v < 0.0 { solid.not(); @@ -574,7 +584,7 @@ impl Body { solid: std::sync::Arc::new(solid), size: if span.is_finite() && span > 0.0 { span } else { 0.0 }, volume: Some(std::sync::Arc::new(std::sync::Mutex::new(None))), - coarse_missing: (v >= 0.0).then_some((tol, missing)), + coarse_missing: Some((tol, missing)), mesh: None, color: None, paint: None, @@ -595,7 +605,15 @@ impl Body { if solid.boundaries().is_empty() { return Err(KernelError::Failed("empty result".into())); } - let mut solid = rephase_revolved(solid); + Body::placed_as_is(rephase_revolved(solid), flip, coarse) + } + + /// [`Body::new_placed`] for a solid whose revolved faces were already turned away from + /// their seam (a placement of an oriented body keeps them where they were). + fn placed_as_is(mut solid: Solid, flip: bool, coarse: Option<(f64, usize)>) -> Result { + if solid.boundaries().is_empty() { + return Err(KernelError::Failed("empty result".into())); + } let span = span_of(&solid); if flip { solid.not(); @@ -616,6 +634,23 @@ impl Body { }) } + /// This oriented body's solid moved by `m` (an affine placement), as [`Body::new_placed`] + /// makes it: the orientation comes from the matrix, so a part placed many times (assembly + /// instances) is meshed to orient it only once. Topology only; appearance is the caller's. + pub(crate) fn placed(&self, m: &mt::Matrix4) -> Result { + use mt::SquareMatrix as _; + if *m == mt::Matrix4::from_scale(1.0) { + return Ok(self.clone()); + } + let a = [[m.x.x, m.x.y, m.x.z, m.x.w], [m.y.x, m.y.y, m.y.z, m.y.w], [m.z.x, m.z.y, m.z.z, m.z.w], [m.w.x, m.w.y, m.w.z, m.w.w]]; + let det = m.determinant(); + if !det.is_finite() || det.abs() < 1e-12 { + return Err(KernelError::Invalid("degenerate placement".into())); + } + let rigid = crate::ops::rigid_placement(&a); + Body::placed_as_is(mt::builder::transformed(&*self.solid, *m), det < 0.0, rigid.then_some(self.coarse_missing).flatten()) + } + pub(crate) fn inherit_regularization_protection(mut self, input: &Body) -> Self { self.regularization_protected |= input.regularization_protected; self @@ -1254,7 +1289,7 @@ impl Body { if self.is_mesh() { return 0; } - let tol = (self.size() * 1e-2).max(1e-3); + let tol = orientation_tolerance(self.size()); if let Some((cached_tol, missing)) = self.coarse_missing && cached_tol == tol { diff --git a/crates/kernel/src/ops.rs b/crates/kernel/src/ops.rs index 8433beb15..4194412c1 100644 --- a/crates/kernel/src/ops.rs +++ b/crates/kernel/src/ops.rs @@ -1686,7 +1686,7 @@ fn det3(m: &[[f64; 4]; 4]) -> f64 { } /// Whether the linear part is a rigid motion (rotation or reflection: no scale or shear). -fn rigid_placement(m: &[[f64; 4]; 4]) -> bool { +pub(crate) fn rigid_placement(m: &[[f64; 4]; 4]) -> bool { let r = [Vec3::new(m[0][0], m[0][1], m[0][2]), Vec3::new(m[1][0], m[1][1], m[1][2]), Vec3::new(m[2][0], m[2][1], m[2][2])]; (0..3).all(|i| (r[i].dot(r[i]) - 1.0).abs() < 1e-9) && r[0].dot(r[1]).abs() < 1e-9 && r[0].dot(r[2]).abs() < 1e-9 && r[1].dot(r[2]).abs() < 1e-9 } diff --git a/crates/kernel/src/step_in/mod.rs b/crates/kernel/src/step_in/mod.rs index b3f49f303..f40e44770 100644 --- a/crates/kernel/src/step_in/mod.rs +++ b/crates/kernel/src/step_in/mod.rs @@ -270,6 +270,9 @@ struct Reader { /// An item placed more than once: its first instance's display, shared by the later ones /// (with the placement that first instance had), so the part is meshed once. shown: HashMap, mt::Matrix4)>, + /// An item placed more than once: its body oriented where the file defines it, so each + /// later instance is only placed (orienting meshes the whole part). + oriented: HashMap, used_items: HashSet, /// Items already instanced for the product being read. node_items: HashSet, @@ -312,6 +315,7 @@ impl Reader { solids: HashMap::new(), once: HashSet::new(), shown: HashMap::new(), + oriented: HashMap::new(), used_items: HashSet::new(), node_items: HashSet::new(), visits: 0, @@ -743,7 +747,11 @@ impl Reader { Err(shared) => (*shared).clone(), }; sources.push((i, item, closed, file_faces, face_origin)); - solids.push(parallel::Job { solid, check_mesh: !self.unmeshed_checked.contains(&item) }); + let source = match self.oriented.get(&item) { + Some(body) => parallel::Source::Oriented(body.clone()), + None => parallel::Source::Solid(solid), + }; + solids.push(parallel::Job { source, check_mesh: !self.unmeshed_checked.contains(&item) }); } let Some(batch) = self.batches.get(id) else { return true }; let (m, path, product, instance) = (batch.m, batch.path.clone(), batch.product.clone(), batch.instance.clone()); @@ -751,7 +759,10 @@ impl Reader { for ((i, item, closed, file_faces, face_origin), body) in sources.into_iter().zip(prepared) { let Some(e) = ex.get(item) else { continue }; match body { - Ok((body, missing)) => { + Ok((body, missing, oriented)) => { + if !self.once.contains(&item) { + self.oriented.entry(item).or_insert(oriented); + } let own = e.params().first().and_then(Param::as_str).unwrap_or("").trim().to_string(); let name = if own.is_empty() { product.clone() } else { own }; // Faces the mesher gives up on (or that the budget cut short) are reported. diff --git a/crates/kernel/src/step_in/parallel.rs b/crates/kernel/src/step_in/parallel.rs index 4883a1d7b..2d9854eb6 100644 --- a/crates/kernel/src/step_in/parallel.rs +++ b/crates/kernel/src/step_in/parallel.rs @@ -2,11 +2,20 @@ use super::{Body, Result, guard, mt}; pub(super) struct Job { - pub solid: mt::Solid, + pub source: Source, pub check_mesh: bool, } -type Prepared = Result<(Body, usize)>; +/// What a job places: a solid read from the file (oriented here), or a body an earlier +/// instance of the same item already oriented. +pub(super) enum Source { + Solid(mt::Solid), + Oriented(Body), +} + +/// The placed body, its faces the mesher missed, and the body oriented where the file defines +/// it (for later instances of the same item). +type Prepared = Result<(Body, usize, Body)>; pub(super) fn workers() -> usize { #[cfg(not(target_arch = "wasm32"))] @@ -21,10 +30,17 @@ pub(super) fn workers() -> usize { fn prepare(job: &Job, placement: &mt::Matrix4) -> Prepared { guard("STEP body preparation", || { - let solid = if *placement == mt::Matrix4::from_scale(1.0) { job.solid.clone() } else { mt::builder::transformed(&job.solid, *placement) }; - let body = Body::new(solid)?; - let missing = if job.check_mesh { body.unmeshed_faces() } else { 0 }; - Ok((body, missing)) + // Orient once where the file defines the solid; each placement then takes its + // orientation from the matrix instead of meshing the whole part again. + let oriented = match &job.source { + Source::Solid(solid) => Body::new(solid.clone())?, + Source::Oriented(body) => body.clone(), + }; + let body = oriented.placed(placement)?; + // Counted where the orientation mesh already counted them (a placement meshes the + // same faces). + let missing = if job.check_mesh { oriented.unmeshed_faces() } else { 0 }; + Ok((body, missing, oriented)) }) } diff --git a/crates/kernel/src/step_in/tests.rs b/crates/kernel/src/step_in/tests.rs index 30c52de25..2f7791915 100644 --- a/crates/kernel/src/step_in/tests.rs +++ b/crates/kernel/src/step_in/tests.rs @@ -242,7 +242,7 @@ fn parallel_body_preparation_reports_errors_in_place_and_preserves_placement() { let body = cylinder(Vec3::new(2.0, 2.0, 0.0), Vec3::Z, 2.0, 4.0).unwrap(); let solids = vec![body.solid.as_ref().clone(), mt::Solid::new(Vec::new()), body.solid.as_ref().clone(), body.solid.as_ref().clone()]; let placement = mt::Matrix4::from_translation(mt::Vector3::new(10.0, 20.0, 30.0)); - let jobs: Vec<_> = solids.into_iter().map(|solid| parallel::Job { solid, check_mesh: true }).collect(); + let jobs: Vec<_> = solids.into_iter().map(|solid| parallel::Job { source: parallel::Source::Solid(solid), check_mesh: true }).collect(); let serial = parallel::bodies(&jobs, &placement, 1); let threaded = parallel::bodies(&jobs, &placement, 4); assert_eq!(serial.len(), 4); @@ -653,6 +653,63 @@ fn hand_written_assembly() { assert!((root.children[1].transform[3][0] - 100.0).abs() < 1e-9); } +/// The cube part (in cm) placed `n` times in a millimetre assembly, each instance moved along X +/// and turned about Z. +fn instanced_assembly(n: u64) -> String { + let mut t = String::from(HEAD); + t += "#8=PRODUCT_DEFINITION_CONTEXT('part definition',#9,'design');\n#9=APPLICATION_CONTEXT('');\n"; + t += &cube_entities(); + t += &context(20, "(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.CENTI.,.METRE.))"); + t += &context(30, "(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.))"); + t += &product(50, "Block"); + t += &product(70, "Assembly"); + t += "#60=ADVANCED_BREP_SHAPE_REPRESENTATION('',(#101,#65),#20);\n#61=SHAPE_DEFINITION_REPRESENTATION(#54,#60);\n"; + t += "#65=AXIS2_PLACEMENT_3D('',#66,$,$);\n#66=CARTESIAN_POINT('',(0.,0.,0.));\n"; + let items: Vec = (0..n).map(|k| format!("#{}", 3000 + k * 10)).collect(); + t += &format!("#80=SHAPE_REPRESENTATION('',({}),#30);\n#88=SHAPE_DEFINITION_REPRESENTATION(#74,#80);\n", items.join(",")); + for k in 0..n { + let (a, turn) = (3000 + k * 10, k as f64 * 0.7); + t += &format!("#{a}=AXIS2_PLACEMENT_3D('',#{},#{},#{});\n", a + 1, a + 2, a + 3); + t += &format!("#{}=CARTESIAN_POINT('',({}.,0.,0.));\n", a + 1, 50 * k); + t += &format!("#{}=DIRECTION('',(0.,0.,1.));\n#{}=DIRECTION('',({},{},0.));\n", a + 2, a + 3, turn.cos(), turn.sin()); + let u = 6000 + k * 10; + t += &format!("#{u}=NEXT_ASSEMBLY_USAGE_OCCURRENCE('{k}','Block:{k}','',#70,#50,$);\n"); + t += &format!("#{}=PRODUCT_DEFINITION_SHAPE('','',#{u});\n", u + 1); + t += &format!("#{}=ITEM_DEFINED_TRANSFORMATION('','',#65,#{a});\n", u + 2); + t += &format!( + "#{}=(REPRESENTATION_RELATIONSHIP('','',#60,#80)REPRESENTATION_RELATIONSHIP_WITH_TRANSFORMATION(#{})SHAPE_REPRESENTATION_RELATIONSHIP());\n", + u + 3, + u + 2 + ); + t += &format!("#{}=CONTEXT_DEPENDENT_SHAPE_REPRESENTATION(#{},#{});\n", u + 4, u + 3, u + 1); + } + t += TAIL; + t +} + +/// A part placed many times is oriented (meshed whole) once, not once per instance (#2814: +/// an assembly with hundreds of instances spent most of an hour re-meshing the same parts), +/// and every instance still comes out outward-facing at its own place. +#[test] +fn instanced_parts_are_oriented_once() { + let n = 24; + let t = instanced_assembly(n); + crate::body::ORIENTED.with(|c| c.set(0)); + let imp = step_import_with_workers(&t, 1).unwrap(); + assert_eq!(crate::body::ORIENTED.with(|c| c.get()), 1, "one distinct part"); + assert_eq!(imp.bodies.len(), n as usize); + assert!(imp.warnings.is_empty(), "{:?}", imp.warnings); + for (k, b) in imp.bodies.iter().enumerate() { + let m = measure(&b.body).unwrap(); + assert!(rel(m.volume, 1000.0) < 1e-9, "instance {k}: {}", m.volume); + let centre = (m.bbox.min + m.bbox.max) * 0.5; + let turn = k as f64 * 0.7; + let expected = Vec3::new(50.0 * k as f64 + 5.0 * (turn.cos() - turn.sin()), 5.0 * (turn.sin() + turn.cos()), 5.0); + assert!(centre.dist(expected) < 1e-6, "instance {k}: {centre:?} vs {expected:?}"); + } + assert_same_import(&imp, &step_import_with_workers(&t, 8).unwrap()); +} + /// A part an assembly places twice is meshed once: the second instance shows the first one's /// display mesh, placed (the same triangles and faces, at its own place), and keeps its own /// placed geometry for everything else. From 768e69c4c7dca8c35220999ef3256aff945ff263 Mon Sep 17 00:00:00 2001 From: NOWN-DEV <257771410+NOWN-DEV@users.noreply.github.com> Date: Mon, 19 Oct 2026 11:54:21 +0200 Subject: [PATCH 045/225] Joints: a new joint between faces that already meet leaves the part as it is (#2709) (#2710) Thanks @NOWN-DEV. --- crates/doc/src/joints.rs | 20 ++++++ crates/engine/src/cmd/joints.rs | 19 ++++-- crates/engine/src/cmd/joints_turn_tests.rs | 79 ++++++++++++++++++++++ docs/book/src/guide/assemblies.md | 7 +- 4 files changed, 118 insertions(+), 7 deletions(-) create mode 100644 crates/engine/src/cmd/joints_turn_tests.rs diff --git a/crates/doc/src/joints.rs b/crates/doc/src/joints.rs index ff84addcd..b9520c477 100644 --- a/crates/doc/src/joints.rs +++ b/crates/doc/src/joints.rs @@ -1737,6 +1737,26 @@ mod face; pub use face::{end_faces, face_name_at, named_face_spot, pin_end, round_end_at}; pub use reach::{REACH_TOL, Reach, Reached, reach}; +/// The rest angle that turns B least as joint `j` is made, as B sits now: none or a half turn +/// about the joint's z. Origins whose x is chosen for them (a face, a circle, a point without +/// x) get opposite x when their z are opposite, so two faces that already meet would, at angle +/// 0, spin B a half turn about their shared normal. +pub fn least_turn_angle(doc: &Document, st: &ModelState, j: &Joint) -> f64 { + let (Ok(fa), Ok(fb)) = (resolve_origin(doc, st, &j.a), resolve_origin(doc, st, &j.b)) else { return 0.0 }; + let (ta, tb) = (occurrence_world(doc, j.a.occurrence), occurrence_world(doc, j.b.occurrence)); + let mut q = j.values.clone(); + q.resize(j.kind.dofs().len(), 0.0); + clamp(j, &mut q); + let turn = |angle: f64| { + let k = Joint { angle, ..j.clone() }; + through(&k, &(fa, fb), &q, true, &ta).map(|m| mismatch(&m, &tb).1) + }; + match (turn(0.0), turn(std::f64::consts::PI)) { + (Some(none), Some(half)) if half + 1e-9 < none => std::f64::consts::PI, + _ => 0.0, + } +} + /// The frame matrix for an explicit origin / z / x (public for commands). pub fn frame_of(o: Vec3, z: Vec3, x: Option) -> Option { frame(o, z, x) diff --git a/crates/engine/src/cmd/joints.rs b/crates/engine/src/cmd/joints.rs index 7fe68860e..2dbe97540 100644 --- a/crates/engine/src/cmd/joints.rs +++ b/crates/engine/src/cmd/joints.rs @@ -23,7 +23,8 @@ pub static COMMANDS: &[CommandSpec] = &[ "type: rigid|revolute|slider|cylindrical|pin_slot|planar|ball; a, b: joint origins ({occurrence, face|circle|edge|point: [x,y,z] in world, or face|circle: \"\"; end?, x? as joint.origin} | origin name); \ values?: [angles in deg or expressions, distances]; limits?: [[min, max] | null…]; flip?: bool (default false: the origins are mated, \ b's z against a's as two faces meet; true: b's z along a's, so two origins given at one point with the same z stay as they are); \ - offset?: mm or an expression; angle?: deg or an expression; name?; quiet?: bool (leave out dof and fixed). An expression (text) is \ + offset?: mm or an expression; angle?: deg or an expression (default: none, or a half turn where that turns b less, so faces that \ + already meet stay as they are); name?; quiet?: bool (leave out dof and fixed). An expression (text) is \ kept with the joint and worked out again whenever the design changes, so the joint follows the parameters it names; a joint whose \ expression no longer works out (a parameter deleted) is left out of the solve with the reason in its errors", ), @@ -629,10 +630,10 @@ fn joint(s: &mut Session, p: &Value) -> Result { None => 0.0, }; let angle = match p.get("angle") { - Some(v) => value(s, v, true, cmd)?, - None => 0.0, + Some(v) => Some(value(s, v, true, cmd)?), + None => None, }; - let j = Joint { + let mut j = Joint { id, name, kind, @@ -642,10 +643,15 @@ fn joint(s: &mut Session, p: &Value) -> Result { limits: limits_param(s, p, kind, cmd)?, flip: bool_(p, "flip").unwrap_or(false), offset, - angle, + angle: angle.unwrap_or(0.0), suppressed: false, exprs: JointExprs { offset: typed(p.get("offset")), angle: typed(p.get("angle")), values: value_exprs(p) }, }; + // No angle given: B keeps its turn about the joint's axis where a half turn would otherwise + // come only from how its origin's x was chosen. + if angle.is_none() { + j.angle = joints::least_turn_angle(&s.doc, &s.model.state(), &j); + } add_joint(s, j, p) } @@ -1418,3 +1424,6 @@ mod reach_tests; #[cfg(test)] #[path = "joints_tests.rs"] mod tests; +#[cfg(test)] +#[path = "joints_turn_tests.rs"] +mod turn_tests; diff --git a/crates/engine/src/cmd/joints_turn_tests.rs b/crates/engine/src/cmd/joints_turn_tests.rs new file mode 100644 index 000000000..4e645a8ef --- /dev/null +++ b/crates/engine/src/cmd/joints_turn_tests.rs @@ -0,0 +1,79 @@ +//! A new joint given no angle keeps the part's turn about the joint's axis: two faces that +//! already meet stay as they are instead of the part spinning a half turn about their normal. + +use serde_json::json; +use solidcraft_geom::Vec3; + +use super::tests::{occ, place, run}; +use crate::Session; + +/// A grounded panel 80 x 30 x 3 at z 3 and a hinge plate of the same size under it, each with a +/// hole off its middle at x = 20: the two faces that meet at z = 3 have opposite normals. +fn panel_and_hinge() -> Session { + let mut s = Session::default(); + run(&mut s, "component.create", json!({"name": "Panel"})); + run(&mut s, "solid.box", json!({"length": 80, "width": 30, "height": 3, "corner": [0, 0, 3]})); + run(&mut s, "solid.hole", json!({"position": [20, 15, 6], "diameter": 5.5})); + run(&mut s, "component.activate", json!({"component": "root"})); + run(&mut s, "component.create", json!({"name": "Hinge"})); + run(&mut s, "solid.box", json!({"length": 80, "width": 30, "height": 3, "corner": [0, 0, 0]})); + run(&mut s, "solid.hole", json!({"position": [20, 15, 3], "diameter": 5.5})); + run(&mut s, "component.activate", json!({"component": "root"})); + let panel = occ(&s, "Panel"); + run(&mut s, "occurrence.ground", json!({"occurrence": panel, "grounded": true})); + s +} + +fn stays(s: &Session) -> bool { + [Vec3::new(20.0, 15.0, 0.0), Vec3::new(80.0, 0.0, 3.0)].iter().all(|p| place(s, "Hinge", *p).dist(*p) < 1e-6) +} + +#[test] +fn joining_two_faces_that_already_meet_leaves_the_part_where_it_is() { + // Each face's frame takes an x of its own; with opposite normals those x are opposite, and + // the joint used to spin the hinge a half turn about the normal, its hole to x = 60. + for kind in ["rigid", "slider", "planar"] { + let mut s = panel_and_hinge(); + let r = run( + &mut s, + "joint.create", + json!({"type": kind, "a": {"occurrence": "Panel", "face": [30, 25, 3]}, "b": {"occurrence": "Hinge", "face": [30, 25, 3]}, "name": "J"}), + ); + assert!(stays(&s), "{kind}: the hinge moved to {:?}: {r}", place(&s, "Hinge", Vec3::new(20.0, 15.0, 0.0))); + // Its value still moves it along the joint's axis (the faces' normal), without a turn. + if kind == "slider" { + run(&mut s, "joint.drive", json!({"joint": "J", "value": 5})); + let p = place(&s, "Hinge", Vec3::new(20.0, 15.0, 0.0)); + assert!(p.dist(Vec3::new(20.0, 15.0, -5.0)) < 1e-6, "{p:?}"); + } + } + // An angle given is kept as given. + let mut s = panel_and_hinge(); + run( + &mut s, + "joint.create", + json!({"type": "rigid", "a": {"occurrence": "Panel", "face": [30, 25, 3]}, "b": {"occurrence": "Hinge", "face": [30, 25, 3]}, "angle": 0}), + ); + assert!(!stays(&s)); + let j = s.doc.assembly.joints.last().map(|j| j.angle); + assert_eq!(j, Some(0.0)); +} + +#[test] +fn an_angle_typed_as_an_expression_is_not_replaced_by_the_kept_turn() { + // `turn` is 0 deg: the hinge takes the half turn the angle says, not the one that would + // leave it where it is, and follows the parameter when it changes. + let mut s = panel_and_hinge(); + run(&mut s, "parameters.add", json!({"name": "turn", "expression": "0 deg"})); + run( + &mut s, + "joint.create", + json!({"type": "rigid", "a": {"occurrence": "Panel", "face": [30, 25, 3]}, "b": {"occurrence": "Hinge", "face": [30, 25, 3]}, "angle": "turn", "name": "J"}), + ); + assert!(!stays(&s)); + let j = s.doc.assembly.joints.last().map(|j| (j.angle, j.exprs.angle.clone())); + assert_eq!(j, Some((0.0, Some("turn".to_string())))); + run(&mut s, "parameters.change", json!({"name": "turn", "expression": "180 deg"})); + assert!(stays(&s), "{:?}", place(&s, "Hinge", Vec3::new(20.0, 15.0, 0.0))); + assert!(s.doc.assembly.joints.last().is_some_and(|j| j.exprs.angle.as_deref() == Some("turn"))); +} diff --git a/docs/book/src/guide/assemblies.md b/docs/book/src/guide/assemblies.md index 3280f83c8..bbd40dda8 100644 --- a/docs/book/src/guide/assemblies.md +++ b/docs/book/src/guide/assemblies.md @@ -165,8 +165,11 @@ it where it is), and it moves. `joint.drive` answers the joint's values as `joint.list` gives them, in degrees and millimetres with their units and limits, and `moved` says whether any part moved. A joint's origins are mated by default: B's z axis is turned against A's, as two faces meet. `flip: true` lines them up -instead, so two origins given at one point with the same z stay as they are. For scripts that -drive many steps, `quiet: true` leaves the per-part degrees of freedom out of joint answers, and +instead, so two origins given at one point with the same z stay as they are. Without an +`angle`, a new joint takes no turn or a half turn about its axis, whichever turns B less: two +faces that already meet, a plate under a panel, stay as they are instead of B spinning about +their shared normal. For scripts that drive many steps, `quiet: true` leaves the per-part +degrees of freedom out of joint answers, and `motion.play` with `quiet: true` gives the poses of only the parts that moved. **Motion Trace** (`motion.trace`, on the **ASSEMBLE** panel) draws the path a point of a part From 1666ca7018b867b90c613e7b39830c89a7d2db82 Mon Sep 17 00:00:00 2001 From: abteenz <19427327+abteenz@users.noreply.github.com> Date: Mon, 19 Oct 2026 02:54:43 -0700 Subject: [PATCH 046/225] Fix the macOS launch hang with the 3Dconnexion driver installed (#2841) Thanks @abteenz. --- apps/solidcraft/src/space_mouse.rs | 42 +++++++++++++++----------- crates/threedx-client/examples/dump.rs | 10 +++++- crates/threedx-client/src/lib.rs | 14 ++++++--- crates/threedx-client/src/macos.rs | 17 ++++++----- 4 files changed, 53 insertions(+), 30 deletions(-) diff --git a/apps/solidcraft/src/space_mouse.rs b/apps/solidcraft/src/space_mouse.rs index b524c4a85..00568cf08 100644 --- a/apps/solidcraft/src/space_mouse.rs +++ b/apps/solidcraft/src/space_mouse.rs @@ -362,25 +362,31 @@ fn reader(ctx: Context, shared: Arc>) { fn start_driver_client(ctx: &Context, shared: &Arc>) { use solidcraft_3dx_client::Event; let (ctx, shared) = (ctx.clone(), Arc::clone(shared)); - let started = solidcraft_3dx_client::start("SolidCraft", move |event| match event { - Event::DeviceAdded => DRIVER_CONNECTED.store(true, Ordering::Relaxed), - Event::DeviceRemoved => { - DRIVER_CONNECTED.store(false, Ordering::Relaxed); - reset(&ctx, &shared); - } - Event::Axes { translation, rotation } => { - if let Ok(mut reading) = shared.lock() { - let now = Instant::now(); - reading.axes = Axes { translation, rotation }; - reading.at = [now; 6]; - ctx.request_repaint(); + let started = solidcraft_3dx_client::start( + "SolidCraft", + move |event| match event { + Event::DeviceAdded => DRIVER_CONNECTED.store(true, Ordering::Relaxed), + Event::DeviceRemoved => { + DRIVER_CONNECTED.store(false, Ordering::Relaxed); + reset(&ctx, &shared); } - } - Event::Buttons(_) => {} - }); - match started { - Ok(()) => DRIVER_REGISTERED.store(true, Ordering::Relaxed), - Err(error) => log::info!("3D mouse: no driver client: {error}"), + Event::Axes { translation, rotation } => { + if let Ok(mut reading) = shared.lock() { + let now = Instant::now(); + reading.axes = Axes { translation, rotation }; + reading.at = [now; 6]; + ctx.request_repaint(); + } + } + Event::Buttons(_) => {} + }, + |connected| match connected { + Ok(()) => DRIVER_REGISTERED.store(true, Ordering::Relaxed), + Err(error) => log::info!("3D mouse: no driver client: {error}"), + }, + ); + if let Err(error) = started { + log::info!("3D mouse: no driver client: {error}"); } } diff --git a/crates/threedx-client/examples/dump.rs b/crates/threedx-client/examples/dump.rs index 172e4c6b1..64cd30b87 100644 --- a/crates/threedx-client/examples/dump.rs +++ b/crates/threedx-client/examples/dump.rs @@ -3,7 +3,15 @@ //! use SolidCraft's own `.app` to see the cap move. fn main() { - if let Err(error) = solidcraft_3dx_client::start("SolidCraft dump", |event| println!("{event:?}")) { + if let Err(error) = solidcraft_3dx_client::start( + "SolidCraft dump", + |event| println!("{event:?}"), + |connected| { + if let Err(error) = connected { + eprintln!("{error}"); + } + }, + ) { eprintln!("{error}"); return; } diff --git a/crates/threedx-client/src/lib.rs b/crates/threedx-client/src/lib.rs index 77ef94f75..15082ed99 100644 --- a/crates/threedx-client/src/lib.rs +++ b/crates/threedx-client/src/lib.rs @@ -67,15 +67,21 @@ impl std::error::Error for Error {} /// Connects to the driver and calls `sink` (on the client's own thread) for everything it reports. /// `name` is how the driver lists this app. Only one client per process; the connection lasts -/// until the process ends. -pub fn start(name: &str, sink: impl Fn(Event) + Send + Sync + 'static) -> Result<(), Error> { +/// until the process ends. Returns once the client thread runs, without waiting for the driver +/// (which needs the main thread to register the client); `connected` gets that outcome later, on +/// the client's thread. +pub fn start( + name: &str, + sink: impl Fn(Event) + Send + Sync + 'static, + connected: impl FnOnce(Result<(), Error>) + Send + 'static, +) -> Result<(), Error> { #[cfg(target_os = "macos")] { - macos::start(name, Box::new(sink)) + macos::start(name, Box::new(sink), Box::new(connected)) } #[cfg(not(target_os = "macos"))] { - let _ = (name, sink); + let _ = (name, sink, connected); Err(Error::Unsupported) } } diff --git a/crates/threedx-client/src/macos.rs b/crates/threedx-client/src/macos.rs index d12c7d66a..5549425dd 100644 --- a/crates/threedx-client/src/macos.rs +++ b/crates/threedx-client/src/macos.rs @@ -53,6 +53,7 @@ type RegisterClient = unsafe extern "C" fn(u32, *const u8, u16, u32) -> u16; type SetMask = unsafe extern "C" fn(u16, u32); type Sink = Box; +type Connected = Box) + Send>; static SINK: OnceLock = OnceLock::new(); /// The id the driver gave this client: it broadcasts every message to every client. @@ -157,17 +158,19 @@ fn connect(name: &str) -> Result<(), Error> { Ok(()) } -pub fn start(name: &str, sink: Sink) -> Result<(), Error> { +/// Starts the client thread and returns without waiting for the driver: its registration +/// waits for the main thread, which is usually the caller (a wait here hangs the app at launch). +/// `connected` gets the outcome on the client thread. +pub fn start(name: &str, sink: Sink, connected: Connected) -> Result<(), Error> { SINK.set(sink).map_err(|_| Error::AlreadyStarted)?; let name = name.to_owned(); - let (ready, started) = std::sync::mpsc::channel(); std::thread::Builder::new() .name("3dx-client".into()) .spawn(move || { let result = connect(&name); - let connected = result.is_ok(); - let _ = ready.send(result); - if !connected { + let ok = result.is_ok(); + connected(result); + if !ok { return; } // The driver's messages arrive on this thread's run loop. Waking up now and then keeps @@ -177,8 +180,8 @@ pub fn start(name: &str, sink: Sink) -> Result<(), Error> { unsafe { CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1.0, 0) }; } }) - .map_err(|error| Error::Thread(error.to_string()))?; - started.recv().map_err(|error| Error::Thread(error.to_string()))? + .map(|_| ()) + .map_err(|error| Error::Thread(error.to_string())) } #[cfg(test)] From 34cb3167b697de7ef9557271698e7a2784e7ce69 Mon Sep 17 00:00:00 2001 From: Jacques <59315319+Jacquesvdberg92@users.noreply.github.com> Date: Mon, 19 Oct 2026 13:44:50 +0300 Subject: [PATCH 047/225] Sketch: trim keeps the rest of a dimensioned line where it was (#2910) Thanks @Jacquesvdberg92. --- crates/engine/src/cmd/sketch_modify.rs | 26 +++++++++++++++ crates/engine/src/cmd/sketch_modify_tests.rs | 34 ++++++++++++++++++++ 2 files changed, 60 insertions(+) diff --git a/crates/engine/src/cmd/sketch_modify.rs b/crates/engine/src/cmd/sketch_modify.rs index 3db6db052..6cc0d8dad 100644 --- a/crates/engine/src/cmd/sketch_modify.rs +++ b/crates/engine/src/cmd/sketch_modify.rs @@ -257,6 +257,31 @@ fn tie(sk: &mut Sketch, pieces: &[usize]) -> Result<()> { Ok(()) } +/// Dimensions and relations that measure the whole of curve `ci` (a line's length, an equal +/// length, its midpoint, an arc's length or sweep) would stay on the piece that keeps its id +/// after a trim and stretch that piece back to the old size, moving the rest of the sketch. A +/// length becomes the distance between the curve's old ends, as a fillet keeps it to its virtual +/// corner (it goes with an end the trim removes); the others go. +fn release_extent(sk: &mut Sketch, ci: usize) { + let ends = match sk.curves.get(ci).map(|c| &c.kind) { + Some(CurveKind::Line { a, b }) => Some((*a, *b)), + _ => None, + }; + sk.constraints.retain_mut(|k| match k.kind { + ConstraintKind::Length { l, value } if l == ci => match ends { + Some((p, q)) => { + k.kind = ConstraintKind::Distance { p, q, value }; + true + } + None => false, + }, + ConstraintKind::Equal { a, b } if ends.is_some() && (a == ci || b == ci) => false, + ConstraintKind::Midpoint { l, .. } if l == ci => false, + ConstraintKind::ArcLength { c, .. } | ConstraintKind::ArcSweep { c, .. } if c == ci => false, + _ => true, + }); +} + /// The cut parameters bracketing `tq` on curve `ci`: (before, after) with their cutter curves. fn bracket(sk: &Sketch, ci: usize, tq: f64) -> (Vec<(f64, Vec2, usize)>, bool) { let Some(sh) = sk.shape(ci) else { return (Vec::new(), false) }; @@ -305,6 +330,7 @@ fn trim(s: &mut Session, p: &Value) -> Result { doc.prune_model_params(); return Ok(json!({"deleted": id})); } + release_extent(sk, ci); let ts: Vec = cuts.iter().map(|c| c.0).collect(); let (pieces, pts) = split_at(sk, ci, &ts)?; // The piece containing tq. diff --git a/crates/engine/src/cmd/sketch_modify_tests.rs b/crates/engine/src/cmd/sketch_modify_tests.rs index 805c8a190..846cd32bd 100644 --- a/crates/engine/src/cmd/sketch_modify_tests.rs +++ b/crates/engine/src/cmd/sketch_modify_tests.rs @@ -1585,3 +1585,37 @@ fn offset_driver_format18_offsets_keep_fixed_distances_on_upgrade() { assert!(!sk.constraints.iter().any(|c| matches!(c.kind, ConstraintKind::OffsetDistance { .. }))); assert_eq!(ids(&result["curves"]).len(), sk.offsets[0].outputs.len()); } + +#[test] +fn trim_keeps_the_rest_of_a_dimensioned_line_where_it_was() { + // A 40 x 40 square, its right side dimensioned with the Dimension tool (a line length). + let mut s = new_sketch(); + let sq = ids(&run(&mut s, "sketch.line", json!({"points": [[0, 0], [40, 0], [40, 40], [0, 40]], "closed": true, "infer": true}))["curves"]); + let (right, top) = (sq[1].clone(), sq[2].clone()); + run(&mut s, "sketch.dimension", json!({"entities": [right]})); + // A step drawn across the top right corner, its ends on the top and right sides. + let step = ids(&run(&mut s, "sketch.line", json!({"points": [[23, 40], [23, 23], [40, 23]], "infer": true}))["curves"]); + run(&mut s, "sketch.constraint.coincident", json!({"a": format!("{}.start", step[0]), "b": top})); + run(&mut s, "sketch.constraint.coincident", json!({"a": format!("{}.end", step[1]), "b": right})); + let corner = |s: &Session| { + let sk = sketch(s); + sk.point(sk.resolve_point(&format!("{}.end", step[1])).unwrap()).unwrap() + }; + let forty = |s: &Session| { + sketch(s).constraints.iter().filter(|c| c.kind.value().is_some_and(|v| close(v, 40.0))).map(|c| c.kind.clone()).collect::>() + }; + + // Trim the right side above the step: the 40 stays between the square's corners, which are + // both still there, instead of stretching the 23 mm that is left back to 40. + run(&mut s, "sketch.trim", json!({"curve": right, "at": [40, 30]})); + assert!(corner(&s).dist(Vec2::new(40.0, 23.0)) < 1e-6, "the step moved to {:?}", corner(&s)); + let sk = sketch(&s); + let ends = sk.shape(sk.curve_index(&right).unwrap()).unwrap(); + assert!(matches!(ends, solidcraft_sketch::Shape::Line { a, b } if close(a.dist(b), 23.0)), "{ends:?}"); + assert!(matches!(forty(&s)[..], [ConstraintKind::Distance { .. }]), "{:?}", forty(&s)); + + // Trim the top side right of the step: the corner the 40 measured to goes, and the 40 with it. + run(&mut s, "sketch.trim", json!({"curve": top, "at": [30, 40]})); + assert!(corner(&s).dist(Vec2::new(40.0, 23.0)) < 1e-6, "the step moved to {:?}", corner(&s)); + assert!(forty(&s).is_empty(), "{:?}", forty(&s)); +} From 852d364d5f3ff4243265f2b5fdba2eaadcfcca30 Mon Sep 17 00:00:00 2001 From: Colin Faulkingham Date: Mon, 19 Oct 2026 06:14:07 -0500 Subject: [PATCH 048/225] Preserve curved face picks when reopening modeled threads (#2265) Co-authored-by: bherbruck --- crates/ui-egui/src/dialogs.rs | 22 +++++-- crates/ui-egui/src/preselect_tests.rs | 91 +++++++++++++++++++++++++++ 2 files changed, 109 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 6e778857c..e091a00fc 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -4615,21 +4615,35 @@ pub(crate) fn edge_sel(s: &Session, p0: Vec3) -> Option { /// The body face containing a point (nearest triangle). pub(crate) fn face_sel(s: &Session, p0: Vec3) -> Option { + use solidcraft_engine::kernel::{self, FaceSurface}; + + if !p0.is_finite() { + return None; + } let st = s.world_state(); let frames = stored_frames(s); - let mut best: Option<(f64, Sel)> = None; + let mut best: Option<(f64, &solidcraft_engine::doc::ModelBody, usize, Vec3)> = None; for b in &st.bodies { let p = stored_on(&frames, &b.name, p0); let m = b.mesh(); for (t, f) in m.triangles.iter().zip(&m.tri_face) { let Some([a, bb, c]) = m.tri(t) else { continue }; let d = crate::preview::point_triangle_dist(p, a, bb, c); - if best.as_ref().is_none_or(|(bd, _)| d < *bd) { - best = Some((d, Sel::Face { body: b.name.clone(), index: *f as usize, point: p })); + if best.as_ref().is_none_or(|(bd, _, _, _)| d < *bd) { + best = Some((d, b, *f as usize, p)); } } } - best.filter(|(d, _)| *d < 1e-3 + 1e-6 * p0.len()).map(|x| x.1) + let (d, body, index, point) = best?; + let surface = kernel::guard("refill face surface", || Ok(kernel::face_surface(&body.body, index))).ok().flatten(); + // A curved face's viewport pick can be a full chord tolerance from the reference + // facets. Planar and unclassified faces keep the tight limit so a stale pick cannot + // silently select a nearby plane, including a flat cap on an otherwise curved body. + let tolerance = match surface { + Some(FaceSurface::Plane { .. }) | None => 1e-3, + Some(_) => body.display_tol(), + } + 1e-6 * point.len(); + (d <= tolerance).then(|| Sel::Face { body: body.name.clone(), index, point }) } fn emboss_face_sel(s: &Session, component: u64, face: &solidcraft_engine::doc::EmbossFace, persistent: &str) -> Option { diff --git a/crates/ui-egui/src/preselect_tests.rs b/crates/ui-egui/src/preselect_tests.rs index c7270f2e5..bfb747128 100644 --- a/crates/ui-egui/src/preselect_tests.rs +++ b/crates/ui-egui/src/preselect_tests.rs @@ -1082,6 +1082,97 @@ fn thread_size_suggestion_can_be_cleared_and_edited_in_the_dialog() { assert_eq!(apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap()[0].1["designation"], "M8"); } +#[test] +fn modeled_thread_survives_timeline_double_click_and_ok() { + for (analytic_pick, change_length) in [(false, false), (false, true), (true, false), (true, true)] { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.app.apply_off_thread = Some(std::time::Duration::ZERO); + h.app.run("solid.cylinder", json!({"radius":4,"height":4})).unwrap(); + let smooth_volume = h.app.session.world_state().body("Body1").unwrap().mesh().measure().volume; + let Sel::Face { point, .. } = thread_face(&h.app, "Body1") else { panic!("face") }; + let point = if analytic_pick { Vec3::new(4.0, 0.0, 2.0) } else { point }; + let id = h.app.run("solid.thread", json!({"face":point,"designation":"M8x1","modeled":true})).unwrap()["feature"].as_u64().unwrap(); + let threaded_volume = h.app.session.world_state().body("Body1").unwrap().mesh().measure().volume; + assert!(smooth_volume - threaded_volume > 1.0); + h.frames(4); + h.step(&json!({"click":{"handle":"timeline:Thread1"},"double":true})).unwrap(); + h.frames(4); + assert_eq!(h.app.dialog.as_ref().unwrap().extra["modeled"], true); + assert_eq!(h.app.dialog.as_ref().unwrap().editing, Some((id, None))); + assert_eq!(h.app.dialog.as_ref().unwrap().inputs[0].items.len(), 1, "the cylinder stays selected"); + if change_length { + h.step(&json!({"click":{"handle":"dialog:Full Length"}})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:Length"}})).unwrap(); + h.step(&json!({"key":"A","cmd":true})).unwrap(); + h.step(&json!({"text":"2 mm"})).unwrap(); + } + if h.app.dialog.as_ref().unwrap().previews() { + wait_feature_preview(&mut h); + assert_eq!(h.app.preview.replaced, ["Body1"]); + } + h.step(&json!({"widget":"OK"})).unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20); + while h.app.applying.is_some() && std::time::Instant::now() < deadline { + h.frames(1); + std::thread::sleep(std::time::Duration::from_millis(10)); + } + h.frames(4); + assert!(h.app.dialog.is_none(), "{:?}", h.app.dialog); + assert!(h.app.applying.is_none() && !h.app.preview.active && h.app.preview.replaced.is_empty()); + assert_eq!(h.app.session.doc.marker, None); + assert!(matches!(h.app.session.doc.feature(id).unwrap().kind, solidcraft_engine::doc::FeatureKind::Thread { modeled: true, .. })); + let result = h.app.session.model.result(id).unwrap(); + assert!(!result.skipped && result.error.is_none(), "{result:?}"); + let edited_volume = h.app.session.world_state().body("Body1").unwrap().mesh().measure().volume; + assert!(smooth_volume - edited_volume > 1.0, "the modeled cut disappeared: {smooth_volume} -> {edited_volume}"); + if change_length { + assert!(edited_volume - threaded_volume > 1.0, "shortening the thread restores some material"); + } else { + assert!((edited_volume - threaded_volume).abs() < 1e-6); + } + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.marker, None); + let restored = h.app.session.world_state().body("Body1").unwrap().mesh().measure().volume; + assert!((restored - threaded_volume).abs() < 1e-6, "one undo restores the original modeled thread"); + } +} + +#[test] +fn planar_face_reopen_keeps_the_tight_pick_tolerance() { + for (command, mut params, point) in [ + ("solid.box", json!({"length":100,"width":100,"height":100}), Vec3::new(50.0, 50.0, 100.0)), + ("solid.cylinder", json!({"radius":50,"height":100}), Vec3::new(0.0, 0.0, 100.0)), + ] { + let mut h = crate::scenario::Harness::new(); + let base = h.app.run(command, params.clone()).unwrap()["feature"].clone(); + let feature = h.app.run("solid.offset_face", json!({"faces":[point],"distance":2})).unwrap()["feature"].as_u64().unwrap(); + h.app.edit_feature(feature); + assert_eq!(h.app.dialog.as_ref().unwrap().inputs[0].items.len(), 1, "an unchanged planar pick reopens"); + crate::dialogs::cancel(&mut h.app); + + // Move the upstream face away from its saved pick, but by less than the body's + // display tolerance. The cylinder case also checks planar caps on curved bodies. + params["height"] = json!(99.99); + h.app.run("timeline.redefine", json!({"feature":base,"command":command,"params":params})).unwrap(); + h.app.edit_feature(feature); + assert!(h.app.session.world_state().body("Body1").unwrap().display_tol() > 0.01); + assert!(crate::dialogs::face_sel(&h.app.session, point - Vec3::Z * 0.01).is_some()); + assert!(h.app.dialog.as_ref().unwrap().inputs[0].items.is_empty(), "{command}: a stale planar pick must stay empty"); + } +} + +#[test] +fn curved_face_refill_keeps_its_pick_but_rejects_points_outside_the_mesh_tolerance() { + let mut app = app_with(json!([])); + app.run("solid.cylinder", json!({"radius":4,"height":4})).unwrap(); + let point = Vec3::new(4.0, 0.0, 2.0); + let pick = crate::dialogs::face_sel(&app.session, point).unwrap(); + assert!(matches!(pick, Sel::Face { point: kept, .. } if kept == point)); + assert!(crate::dialogs::face_sel(&app.session, Vec3::new(4.1, 0.0, 2.0)).is_none()); + assert!(crate::dialogs::face_sel(&app.session, Vec3::new(f64::NAN, 0.0, 2.0)).is_none()); +} + #[test] fn thread_choices_apply_a_fine_pitch_and_partial_modelled_thread() { let mut h = crate::scenario::Harness::new(); From aaa35a94d8fd753fac02e6403f5ce7ef8403c5fd Mon Sep 17 00:00:00 2001 From: amolinari-autotex Date: Mon, 19 Oct 2026 13:14:33 +0200 Subject: [PATCH 049/225] Relink a linked assembly source from the Browser (#2772) (#2773) Thanks @amolinari-autotex. --- assets/locales/en.json | 6 + assets/locales/it.json | 6 + assets/locales/ja.json | 6 + assets/locales/ms.json | 1 + assets/locales/zh.json | 6 + crates/engine/src/cmd/component_link.rs | 68 +++++++ .../engine/src/cmd/component_relink_tests.rs | 147 ++++++++++++++ crates/ui-egui/src/context_menu.rs | 8 + crates/ui-egui/src/lib.rs | 5 + crates/ui-egui/src/linked_source.rs | 180 ++++++++++++++++++ docs/book/src/guide/assemblies.md | 16 ++ 11 files changed, 449 insertions(+) create mode 100644 crates/engine/src/cmd/component_relink_tests.rs create mode 100644 crates/ui-egui/src/linked_source.rs diff --git a/assets/locales/en.json b/assets/locales/en.json index 6c2253456..55f762924 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -350,6 +350,7 @@ "cmd.component_move_sketches": "Move Sketches to Component", "cmd.component_paste_new": "Paste New", "cmd.component_properties": "Component Physical Properties", + "cmd.component_relink": "Relink Source", "cmd.component_rename": "Rename Component", "cmd.component_revert_position": "Revert Position", "cmd.component_unlock": "Unlock Contents", @@ -1408,6 +1409,11 @@ "ui.rectangle": "Rectangle", "ui.rectangular_pattern": "Rectangular Pattern", "ui.redo": "Redo", + "ui.relink_design_changed": "The assembly changed while choosing a source. Start Relink Source again.", + "ui.relink_done": "Source relinked for all instances.", + "ui.relink_not_linked": "This component is not linked to a source design.", + "ui.relink_select_one": "Select one linked component or one of its instances first.", + "ui.relink_source_all": "Relink Source (All Instances)…", "ui.removeFromToolbar": "Remove from Toolbar", "ui.removeSection": "Remove Section", "ui.render": "Render", diff --git a/assets/locales/it.json b/assets/locales/it.json index e28daca5e..0d3784dc4 100644 --- a/assets/locales/it.json +++ b/assets/locales/it.json @@ -345,6 +345,7 @@ "cmd.component_move_sketches": "Sposta schizzi nel componente", "cmd.component_paste_new": "Incolla come nuovo", "cmd.component_properties": "Proprietà fisiche del componente", + "cmd.component_relink": "Ricollega sorgente", "cmd.component_rename": "Rinomina componente", "cmd.component_revert_position": "Ripristina posizione", "cmd.component_unlock": "Sblocca contenuto", @@ -1342,6 +1343,11 @@ "ui.rectangle": "Rettangolo", "ui.rectangular_pattern": "Ripetizione rettangolare", "ui.redo": "Ripeti", + "ui.relink_design_changed": "L'assieme è cambiato durante la scelta del sorgente. Avvia di nuovo Ricollega sorgente.", + "ui.relink_done": "Sorgente ricollegato per tutte le istanze.", + "ui.relink_not_linked": "Questo componente non è collegato a un progetto sorgente.", + "ui.relink_select_one": "Seleziona un componente collegato o una delle sue istanze.", + "ui.relink_source_all": "Ricollega sorgente (tutte le istanze)…", "ui.removeFromToolbar": "Rimuovi dalla barra degli strumenti", "ui.removeSection": "Rimuovi sezione", "ui.render": "Rendering", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 396aebaee..b40c29bc1 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -350,6 +350,7 @@ "cmd.component_move_sketches": "スケッチをコンポーネントに移動", "cmd.component_paste_new": "新規として貼り付け", "cmd.component_properties": "コンポーネントの物理的プロパティ", + "cmd.component_relink": "参照元を再リンク", "cmd.component_rename": "コンポーネントの名前を変更", "cmd.component_revert_position": "位置を元に戻す", "cmd.component_unlock": "内容のロックを解除", @@ -1408,6 +1409,11 @@ "ui.rectangle": "長方形", "ui.rectangular_pattern": "矩形パターン", "ui.redo": "やり直す", + "ui.relink_design_changed": "参照元の選択中にアセンブリが変更されました。再リンクをやり直してください。", + "ui.relink_done": "すべてのインスタンスの参照元を再リンクしました。", + "ui.relink_not_linked": "このコンポーネントは参照元の設計にリンクされていません。", + "ui.relink_select_one": "リンクされたコンポーネントまたはそのインスタンスを1つ選択してください。", + "ui.relink_source_all": "参照元を再リンク(すべてのインスタンス)…", "ui.removeFromToolbar": "ツールバーから削除", "ui.removeSection": "セクションを解除", "ui.render": "レンダリング", diff --git a/assets/locales/ms.json b/assets/locales/ms.json index 9c5ad68a1..11765f89a 100644 --- a/assets/locales/ms.json +++ b/assets/locales/ms.json @@ -1067,6 +1067,7 @@ "ui.continuity_g0": "Lipatan G0", "ui.continuity_g1": "Tangen G1", "ui.continuity_g2": "Kelengkungan G2", + "ui.continuity_gap": "Sela", "ui.copy": "Salin", "ui.corner": "Sudut", "ui.corners": "Sudut", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index c9eafe6ec..b4d664675 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -350,6 +350,7 @@ "cmd.component_move_sketches": "将草图移至组件", "cmd.component_paste_new": "粘贴为新对象", "cmd.component_properties": "组件物理属性", + "cmd.component_relink": "重新链接源文件", "cmd.component_rename": "重命名组件", "cmd.component_revert_position": "恢复位置", "cmd.component_unlock": "解锁内容", @@ -1408,6 +1409,11 @@ "ui.rectangle": "矩形", "ui.rectangular_pattern": "矩形阵列", "ui.redo": "重做", + "ui.relink_design_changed": "选择源文件时装配已更改。请重新开始链接。", + "ui.relink_done": "已为所有实例重新链接源文件。", + "ui.relink_not_linked": "此组件未链接到源设计。", + "ui.relink_select_one": "请先选择一个链接组件或其实例。", + "ui.relink_source_all": "重新链接源文件(所有实例)…", "ui.removeFromToolbar": "从工具栏移除", "ui.removeSection": "移除剖面", "ui.render": "渲染", diff --git a/crates/engine/src/cmd/component_link.rs b/crates/engine/src/cmd/component_link.rs index c5e3d6baa..343c67491 100644 --- a/crates/engine/src/cmd/component_link.rs +++ b/crates/engine/src/cmd/component_link.rs @@ -15,6 +15,11 @@ use super::CommandSpec; use crate::params::{bad, str_, vec3}; use crate::{EngineError, Result, Session}; +#[cfg(test)] +#[path = "component_relink_tests.rs"] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod relink_tests; + pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("component.insert_design", "Insert Design", insert_design).at("SOLID", "ASSEMBLE").icon("component").params( "path: a .solidcraft design → a new component linked to it, holding its solid bodies as placed in that design; \ @@ -23,6 +28,9 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("component.update_links", "Update Links", update_links).icon("update").params( "component?: id or name (default: every linked component) — reads the linked designs again and replaces their bodies where they changed", ), + CommandSpec::new("component.relink", "Relink Source", relink).icon("update").params( + "component: id or name of a linked component; path: a saved .solidcraft design — replaces the source and linked bodies for all its occurrences, preserving identities and placements; returns path, previous_path, warnings, joint_errors and joint_conflicts", + ), CommandSpec::new("component.break_link", "Break Link", break_link) .icon("break") .params("component: id or name of a linked component — keeps its bodies as they are and forgets the design file"), @@ -216,6 +224,66 @@ fn update_links(s: &mut Session, p: &Value) -> Result { Ok(json!({"updated": updated, "unchanged": unchanged, "warnings": warnings})) } +fn relink(s: &mut Session, p: &Value) -> Result { + let cmd = "component.relink"; + let comp = component_key(s, p, "component", cmd)?; + let link = s.doc.links.get(&comp).cloned().ok_or_else(|| bad(cmd, "that component is not linked to a design"))?; + if !matches!(s.doc.feature(link.feature), Some(f) if f.component == comp && matches!(f.kind, FeatureKind::Import { .. })) { + return Err(bad(cmd, "the linked bodies are gone; break the link or insert the design again")); + } + let given = str_(p, "path").filter(|x| !x.trim().is_empty() && x.len() < 4096).ok_or_else(|| bad(cmd, "`path` is required"))?; + let file = absolute(Path::new(given)); + if !file.extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("solidcraft")) { + return Err(bad(cmd, "choose a saved .solidcraft design")); + } + // The ordinary lexical check in linked_bodies also works in the browser VFS. On native + // hosts, reject an alias of this assembly too (a symlink or a path with different case). + if let (Ok(candidate), Some(Ok(own))) = (file.canonicalize(), s.path.as_deref().map(std::fs::canonicalize)) + && candidate == own + { + return Err(bad(cmd, "a design can't be linked into itself")); + } + // Read/evaluate the candidate before changing anything. Session::execute owns the single + // undo step and restores both the document and evaluated state on any later failure. + let (_, sf) = linked_bodies(&file, s.path.as_deref()).map_err(|e| bad(cmd, e.to_string()))?; + let geometry_changed = match (s.doc.feature(link.feature).map(|f| &f.kind), &sf.kind) { + (Some(FeatureKind::Import { step: old, .. }), FeatureKind::Import { step, .. }) => old != step, + _ => true, + }; + let path = stored(s.path.as_deref(), &file); + let mut warnings = sf.warnings; + if geometry_changed + && s.doc + .assembly + .joints + .iter() + .any(|j| s.doc.occurrences.iter().any(|o| o.component == comp && (j.a.occurrence == o.id || j.b.occurrence == o.id))) + { + warnings.push("the linked geometry changed; check this component's joints, even when the solver reports no error".to_string()); + } + if let Some(f) = s.doc_mut().feature_mut(link.feature) { + if f.body_names.len() != sf.body_names.len() { + f.body_names = sf.body_names; + } + f.kind = sf.kind; + } + s.doc_mut().links.insert(comp, DesignLink { path: path.clone(), feature: link.feature }); + s.refresh(); + if let Some(error) = s.model.result(link.feature).and_then(|r| r.error.clone()) { + return Err(bad(cmd, error)); + } + // Report the solver's diagnostics. A resolved joint can still describe the wrong + // connection after a source edit; the reminder above does not depend on solve errors. + let sol = solidcraft_doc::joints::solve(&s.doc, &s.model.state()); + let diagnostics = + |rows: &[(u64, String, String)]| rows.iter().map(|(id, name, why)| json!({"joint": id, "name": name, "why": why})).collect::>(); + for (_, name, why) in sol.errors.iter().chain(&sol.conflicts) { + warnings.push(format!("joint {name}: {why}")); + } + Ok(json!({"component": comp, "feature": link.feature, "path": path, "previous_path": link.path, "geometry_changed": geometry_changed, + "warnings": warnings, "joint_errors": diagnostics(&sol.errors), "joint_conflicts": diagnostics(&sol.conflicts)})) +} + fn break_link(s: &mut Session, p: &Value) -> Result { let cmd = "component.break_link"; let comp = component_key(s, p, "component", cmd)?; diff --git a/crates/engine/src/cmd/component_relink_tests.rs b/crates/engine/src/cmd/component_relink_tests.rs new file mode 100644 index 000000000..31b78c5a8 --- /dev/null +++ b/crates/engine/src/cmd/component_relink_tests.rs @@ -0,0 +1,147 @@ +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +use crate::Session; + +fn run(s: &mut Session, command: &str, params: Value) -> Value { + s.execute(command, ¶ms).unwrap_or_else(|e| panic!("{command}: {e}")) +} + +fn folder(case: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("solidcraft-relink-{case}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +fn part(path: &Path, height: u32) { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 10, "width": 20, "height": height, "corner": [0,0,0]})); + run(&mut s, "file.save", json!({"path": path})); +} + +fn volume(s: &mut Session) -> f64 { + run(s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64().unwrap() +} + +#[test] +fn relink_repairs_a_moved_source_for_every_instance_in_one_undo_step() { + let dir = folder("moved"); + let old = dir.join("old.solidcraft"); + let moved = dir.join("moved.solidcraft"); + let assembly = dir.join("assembly.solidcraft"); + part(&old, 30); + let mut s = Session::default(); + run(&mut s, "file.save", json!({"path": assembly})); + let inserted = run(&mut s, "component.insert_design", json!({"path": old})); + let component = inserted["component"].as_u64().unwrap(); + let first = inserted["occurrence"].as_u64().unwrap(); + let second = run(&mut s, "occurrence.copy", json!({"occurrence": first, "translate": [70,30,10]}))["occurrence"].as_u64().unwrap(); + run(&mut s, "occurrence.move", json!({"occurrence": second, "translate": [0,12,0], "capture": false})); + let occurrences = s.doc.occurrences.clone(); + let pending = s.pending_moves.clone(); + let before = serde_json::to_value(&*s.doc).unwrap(); + let undo = s.undo.len(); + std::fs::rename(&old, &moved).unwrap(); + part(&moved, 45); + let result = run(&mut s, "component.relink", json!({"component": component, "path": moved})); + assert_eq!(result["previous_path"], "old.solidcraft"); + assert_eq!(result["path"], "moved.solidcraft"); + assert_eq!(result["geometry_changed"], true); + assert_eq!(result["warnings"], json!([])); + assert_eq!(s.doc.occurrences, occurrences); + assert_eq!(s.pending_moves, pending); + assert_eq!(s.undo.len(), undo + 1); + assert!((volume(&mut s) - 18000.0).abs() < 1e-5); + let after = serde_json::to_value(&*s.doc).unwrap(); + run(&mut s, "edit.undo", json!({})); + assert_eq!(serde_json::to_value(&*s.doc).unwrap(), before); + assert_eq!(s.pending_moves, pending); + assert!((volume(&mut s) - 12000.0).abs() < 1e-5); + run(&mut s, "edit.redo", json!({})); + assert_eq!(serde_json::to_value(&*s.doc).unwrap(), after); + run(&mut s, "file.save", json!({})); + let mut reopened = Session::default(); + run(&mut reopened, "doc.open", json!({"path": assembly})); + assert_eq!(run(&mut reopened, "component.links", json!({}))["links"][0]["path"], "moved.solidcraft"); + assert_eq!(run(&mut reopened, "component.links", json!({}))["links"][0]["found"], true); + assert!((volume(&mut reopened) - 18000.0).abs() < 1e-5); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn relink_rejects_bad_sources_and_targets_without_touching_the_design_or_undo() { + let dir = folder("failures"); + let source = dir.join("source.solidcraft"); + let assembly = dir.join("assembly.solidcraft"); + let empty = dir.join("empty.solidcraft"); + let corrupt = dir.join("corrupt.solidcraft"); + part(&source, 30); + let mut s = Session::default(); + let component = run(&mut s, "component.insert_design", json!({"path": source}))["component"].as_u64().unwrap(); + run(&mut s, "file.save", json!({"path": assembly})); + run(&mut Session::default(), "file.save", json!({"path": empty})); + std::fs::write(&corrupt, b"not a design").unwrap(); + let before = serde_json::to_value(&*s.doc).unwrap(); + let undo = s.undo.len(); + for params in [ + json!({}), + json!({"component": component}), + json!({"component": false, "path": source}), + json!({"component": 0, "path": source}), + json!({"component": "unknown", "path": source}), + json!({"component": component, "path": " "}), + json!({"component": component, "path": false}), + json!({"component": component, "path": dir.join("missing.solidcraft")}), + json!({"component": component, "path": dir.join("source.step")}), + json!({"component": component, "path": empty}), + json!({"component": component, "path": corrupt}), + json!({"component": component, "path": assembly}), + ] { + assert!(s.execute("component.relink", ¶ms).is_err(), "{params}"); + assert_eq!(serde_json::to_value(&*s.doc).unwrap(), before, "{params}"); + assert_eq!(s.undo.len(), undo); + assert!((volume(&mut s) - 6000.0).abs() < 1e-5); + } + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn relink_keeps_joint_definitions_and_reports_solver_diagnostics() { + let dir = folder("joints"); + let original = dir.join("original.solidcraft"); + let replacement = dir.join("replacement.solidcraft"); + part(&original, 30); + part(&replacement, 45); + let mut s = Session::default(); + let inserted = run(&mut s, "component.insert_design", json!({"path": original})); + let component = inserted["component"].as_u64().unwrap(); + let occurrence = inserted["occurrence"].as_u64().unwrap(); + // Explicit points can keep solving after the source changes, even if the intended + // connection no longer exists. The source-change warning must still be present. + run( + &mut s, + "joint.create", + json!({"name": "Seat", "type": "rigid", "a": {"occurrence": 0, "point": [0,0,0]}, "b": {"occurrence": occurrence, "point": [0,0,0]}}), + ); + let joints = s.doc.assembly.joints.clone(); + let identical = dir.join("identical.solidcraft"); + std::fs::copy(&original, &identical).unwrap(); + let result = run(&mut s, "component.relink", json!({"component": component, "path": identical})); + assert_eq!(result["geometry_changed"], false, "renaming a source is not a geometry change"); + assert_eq!(result["warnings"], json!([])); + assert_eq!(s.doc.assembly.joints, joints); + let result = run(&mut s, "component.relink", json!({"component": component, "path": replacement})); + assert_eq!(s.doc.assembly.joints, joints); + assert!(result["warnings"].as_array().unwrap().iter().any(|w| w.as_str().is_some_and(|w| w.contains("check this component's joints")))); + // A deliberately lost named face exercises the ordinary solver diagnostics, without + // requiring relink to guess which face of a different design was intended. + let joint = s.doc_mut().assembly.joints.first_mut().unwrap(); + joint.b.snap = + solidcraft_doc::joints::Snap::FaceCenter { pick: solidcraft_geom::Vec3::ZERO, face: Some("no-such-linked-face".to_string()), x: None }; + s.refresh(); + let result = run(&mut s, "component.relink", json!({"component": component, "path": replacement})); + assert!(result["joint_errors"].as_array().unwrap().iter().any(|e| e["name"] == "Seat")); + assert!(result["warnings"].as_array().unwrap().iter().any(|w| w.as_str().is_some_and(|w| w.contains("joint Seat:")))); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index 59b7e777a..ec50701d7 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -703,6 +703,9 @@ fn component_items(app: &SolveApp, id: u64) -> Vec { .on(id != 0 || !bodies.is_empty()), ); v.push(act("ui.properties", "Properties", "measure").with(json!({ "component": id }))); + if doc.links.contains_key(&id) { + v.push(act("ui.relinkSource", "Relink Source (All Instances)…", "update").with(json!({"component": id}))); + } if id == 0 { v.push(act("ui.designProperties", "Design Properties", "settings")); } @@ -888,6 +891,11 @@ pub fn run_item(app: &mut SolveApp, item: &Item, at: Pos2) { "ui.delete" if item.params.is_some() => crate::delete::request(app, p), "ui.delete" => delete(app), "ui.finishSketch" => app.finish_sketch(), + "ui.relinkSource" => { + if let Some(component) = id_of(&p, "component") { + crate::linked_source::start(app, component); + } + } "ui.copy" => drop(crate::edit_clipboard::copy(app)), "ui.cut" => drop(crate::edit_clipboard::cut(app)), "ui.paste" => drop(crate::edit_clipboard::paste(app, Some(at))), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 3ca76af58..29b6fb11e 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -69,6 +69,7 @@ pub mod install; pub mod issue_report; pub mod joint_drag; pub mod keymap; +mod linked_source; mod material_card_review; #[cfg(test)] mod measurement_ui_tests; @@ -785,6 +786,10 @@ impl SolveApp { }); return; } + if id == "component.relink" { + linked_source::start_selected(self); + return; + } if matches!(id, "file.insert_step" | "file.insert_mesh") { self.pick_open(|app, path| { if let Some(path) = path { diff --git a/crates/ui-egui/src/linked_source.rs b/crates/ui-egui/src/linked_source.rs new file mode 100644 index 000000000..da5052881 --- /dev/null +++ b/crates/ui-egui/src/linked_source.rs @@ -0,0 +1,180 @@ +//! Explicitly choose a linked component's source; all its instances share that source. + +use std::sync::Arc; + +use serde_json::json; + +use crate::SolveApp; + +pub(crate) fn start_selected(app: &mut SolveApp) { + let mut components = app.tree.picked_components.clone(); + for selection in &app.session.selection { + if let solidcraft_engine::Sel::Occurrence { path } = selection + && let Ok(placement) = app.session.occurrence_placement(path) + { + components.push(placement.component); + } + } + components.sort_unstable(); + components.dedup(); + if let [component] = components.as_slice() + && app.session.doc.links.contains_key(component) + { + start(app, *component); + } else { + app.set_status(app.tr("ui.relink_select_one").to_string(), true); + } +} + +pub(crate) fn start(app: &mut SolveApp, component: u64) { + if app.file_picker_busy() || app.file_load.busy() { + return; + } + if !app.session.doc.links.contains_key(&component) { + app.set_status(app.tr_label("ui.relink_not_linked").to_string(), true); + return; + } + let document = app.session.doc.clone(); + app.pick_open_for(&["solidcraft"], move |app, path| { + let Some(path) = path else { return }; + // A host or programmatic caller can replace/edit a design while a native picker is + // pending. Never apply that old component id to a different design or newer revision. + if !Arc::ptr_eq(&document, &app.session.doc) { + app.set_status(app.tr_label("ui.relink_design_changed").to_string(), true); + return; + } + if let Ok(result) = app.run("component.relink", json!({"component": component, "path": path})) { + let warnings: Vec<&str> = result["warnings"].as_array().into_iter().flatten().filter_map(|w| w.as_str()).collect(); + if warnings.is_empty() { + app.set_status(app.tr_label("ui.relink_done").to_string(), false); + } else { + let text = format!("{} {}", app.tr_label("ui.relink_done"), warnings.join("; ")); + app.session.echo(text.clone()); + app.set_status(text, true); + } + } + }); +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod tests { + use super::*; + use crate::context_menu::{self, Target}; + use solidcraft_engine::Session; + use std::path::PathBuf; + + fn fixture(name: &str) -> (SolveApp, u64, u64, PathBuf, PathBuf) { + let folder = std::env::temp_dir().join(format!("solidcraft-relink-ui-{name}-{}", std::process::id())); + std::fs::create_dir_all(&folder).unwrap(); + let source = folder.join("source.solidcraft"); + let moved = folder.join("moved.solidcraft"); + let mut part = Session::default(); + part.execute("solid.box", &json!({"length": 10, "width": 20, "height": 30})).unwrap(); + part.execute("file.save", &json!({"path": source})).unwrap(); + let mut app = SolveApp::new(Session::default(), Default::default()); + let inserted = app.run("component.insert_design", json!({"path": source})).unwrap(); + let component = inserted["component"].as_u64().unwrap(); + let occurrence = inserted["occurrence"].as_u64().unwrap(); + std::fs::rename(&source, &moved).unwrap(); + (app, component, occurrence, folder, moved) + } + + fn menu(app: &SolveApp, target: Target) -> Option { + context_menu::items(app, &target).into_iter().find(|i| i.id == "ui.relinkSource") + } + + fn answer(app: &mut SolveApp, path: Option) { + app.services.pick_open = Some(Box::new(move |extensions| { + assert_eq!(extensions, &["solidcraft"]); + let result = path.clone(); + Box::pin(async move { result }) + })); + } + + #[test] + fn relink_menu_uses_the_selected_link_from_components_and_occurrences() { + let (mut app, component, occurrence, folder, moved) = fixture("menu"); + let second = app.run("occurrence.copy", json!({"occurrence": occurrence, "translate": [90,0,0]})).unwrap()["occurrence"].as_u64().unwrap(); + let occurrences = app.session.doc.occurrences.clone(); + let item = menu(&app, Target::Component { id: component }).unwrap(); + assert!(item.label.contains("All Instances")); + assert_eq!(menu(&app, Target::Occurrence { path: vec![second] }).unwrap().params, Some(json!({"component": component}))); + assert!(menu(&app, Target::Component { id: 0 }).is_none()); + answer(&mut app, Some(moved.to_string_lossy().into_owned())); + let before = app.session.doc.clone(); + context_menu::run_item(&mut app, &item, egui::Pos2::ZERO); + assert!(app.file_picker_busy()); + assert!(Arc::ptr_eq(&before, &app.session.doc), "choosing is not an edit"); + crate::file_picker::tick(&mut app, &egui::Context::default()); + assert!(!app.file_picker_busy()); + assert!(app.session.doc.links[&component].path.ends_with("moved.solidcraft")); + assert_eq!(app.session.doc.occurrences, occurrences); + assert!(app.status.as_ref().is_some_and(|(s, _, error)| s.contains("all instances") && !error)); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(serde_json::to_value(&*app.session.doc).unwrap(), serde_json::to_value(&*before).unwrap()); + let _ = std::fs::remove_dir_all(folder); + } + + #[test] + fn relink_picker_cancel_bad_file_and_changed_document_keep_the_link() { + let (mut app, component, _, folder, moved) = fixture("cancel"); + let before = serde_json::to_value(&*app.session.doc).unwrap(); + let undo = app.session.undo.len(); + answer(&mut app, None); + start(&mut app, component); + crate::file_picker::tick(&mut app, &egui::Context::default()); + assert_eq!(serde_json::to_value(&*app.session.doc).unwrap(), before); + assert_eq!(app.session.undo.len(), undo); + answer(&mut app, Some(folder.join("missing.solidcraft").to_string_lossy().into_owned())); + start(&mut app, component); + crate::file_picker::tick(&mut app, &egui::Context::default()); + assert_eq!(serde_json::to_value(&*app.session.doc).unwrap(), before); + assert_eq!(app.session.undo.len(), undo); + assert!(app.status.as_ref().is_some_and(|(_, _, error)| *error)); + answer(&mut app, Some(moved.to_string_lossy().into_owned())); + start(&mut app, component); + // The ordinary UI blocks edits while picking. Simulate a host replacing/editing the + // session directly to exercise the continuation's independent stale-target guard. + app.session.execute("component.rename", &json!({"component": component, "name": "Changed"})).unwrap(); + let changed = serde_json::to_value(&*app.session.doc).unwrap(); + crate::file_picker::tick(&mut app, &egui::Context::default()); + assert_eq!(serde_json::to_value(&*app.session.doc).unwrap(), changed); + assert!(app.status.as_ref().is_some_and(|(s, _, error)| s.contains("assembly changed") && *error)); + let _ = std::fs::remove_dir_all(folder); + } + + #[test] + fn relink_start_requires_one_linked_selection_and_opens_its_picker() { + let (mut app, component, occurrence, folder, moved) = fixture("start"); + answer(&mut app, Some(moved.to_string_lossy().into_owned())); + app.start("component.relink"); + assert!(!app.file_picker_busy()); + assert!(app.status.as_ref().is_some_and(|(s, _, error)| s.contains("Select one linked") && *error)); + app.session.selection = vec![solidcraft_engine::Sel::Occurrence { path: vec![occurrence] }]; + app.start("component.relink"); + assert!(app.file_picker_busy()); + crate::file_picker::tick(&mut app, &egui::Context::default()); + assert!(app.session.doc.links[&component].path.ends_with("moved.solidcraft")); + let _ = std::fs::remove_dir_all(folder); + } + + #[test] + fn relink_displays_the_warning_when_changed_geometry_has_joints() { + let (mut app, component, occurrence, folder, moved) = fixture("warning"); + app.run( + "joint.create", + json!({"name": "Seat", "type": "rigid", "a": {"occurrence": 0, "point": [0,0,0]}, "b": {"occurrence": occurrence, "point": [0,0,0]}}), + ) + .unwrap(); + let mut changed = Session::default(); + changed.execute("solid.box", &json!({"length": 10, "width": 20, "height": 45})).unwrap(); + changed.execute("file.save", &json!({"path": moved})).unwrap(); + answer(&mut app, Some(moved.to_string_lossy().into_owned())); + start(&mut app, component); + crate::file_picker::tick(&mut app, &egui::Context::default()); + assert!(app.status.as_ref().is_some_and(|(s, _, error)| s.contains("check this component's joints") && *error)); + assert!(app.session.log.iter().any(|s| s.contains("check this component's joints"))); + let _ = std::fs::remove_dir_all(folder); + } +} diff --git a/docs/book/src/guide/assemblies.md b/docs/book/src/guide/assemblies.md index bbd40dda8..5c20f1d9c 100644 --- a/docs/book/src/guide/assemblies.md +++ b/docs/book/src/guide/assemblies.md @@ -250,6 +250,22 @@ After the part file changes, **Update Links** (`component.update_links`) reads i the part's bodies only: its timeline, parameters and sheet-metal data (flat pattern, bend table) stay in the part's own design. +If a source file moves or is renamed, right-click its linked component or occurrence in the +Browser and choose **Relink Source (All Instances)…**. Choose the saved `.solidcraft` design +to use. Relinking updates that component's stored path and solid bodies for **all its +instances**, keeping their identities and placements. Cancelling or choosing a missing, +invalid, empty or self-referencing design leaves the assembly unchanged. The operation is +one undo step and the new path is saved relative to the assembly when possible. + +Scripts use `component.relink {component, path}`. The reply includes `previous_path`, `path`, +`warnings`, `joint_errors` and `joint_conflicts`. Changed geometry can invalidate a joint's +face reference: relinking reports those joints in the reply and UI status/message history; +repair the joint or undo the relink. Relink does not repair or verify the intended meaning of +existing joints. +When linked geometry changes and the component has joints, a reminder to check those joints +is also shown even if the solver reports no error: a successful solve does not prove that a +joint still describes the intended connection. + STEP export writes the component tree as an assembly. Right-click a component in the Browser and choose **Properties** to inspect From 3a9b053f5b054d505b323f90adbdca037d3413f2 Mon Sep 17 00:00:00 2001 From: takuto-NA Date: Mon, 19 Oct 2026 20:24:04 +0900 Subject: [PATCH 050/225] Fix constrained point dragging within the shared frame budget (#1976) (#1977) --- crates/engine/src/cmd/sketch.rs | 2 +- crates/engine/src/cmd/sketch_drag.rs | 51 +++- crates/engine/src/cmd/sketch_ux_tests.rs | 19 ++ crates/engine/tests/sketch_drag_target.rs | 107 ++++++++ crates/engine/tests/support/four_bar.rs | 45 ++++ crates/sketch/src/cursor.rs | 296 ++++++++++++++++++++++ crates/sketch/src/decompose.rs | 22 +- crates/sketch/src/lib.rs | 4 +- crates/sketch/src/solver.rs | 76 ++++-- crates/sketch/tests/cursor_target.rs | 160 ++++++++++++ 10 files changed, 751 insertions(+), 31 deletions(-) create mode 100644 crates/engine/tests/sketch_drag_target.rs create mode 100644 crates/engine/tests/support/four_bar.rs create mode 100644 crates/sketch/src/cursor.rs create mode 100644 crates/sketch/tests/cursor_target.rs diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rs index f97f4575f..34468fcd0 100644 --- a/crates/engine/src/cmd/sketch.rs +++ b/crates/engine/src/cmd/sketch.rs @@ -179,7 +179,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .params("entities: [curve, point or constraint ids]"), CommandSpec::new("sketch.move_point", "Drag Sketch Point", move_point).icon("sketch_move").enabled(in_sketch).params("point: ref, to: [x,y]"), CommandSpec::new("sketch.drag", "Drag Sketch Geometry", drag).icon("sketch_move").enabled(in_sketch).live(drag_live).params( - "entity: point or curve, from: [x,y] where it was grabbed, to: [x,y], live?: bool: a point goes to `to`, a line (spline, conic) slides by to - from, a circle or arc grabbed on its edge takes the radius to `to`; the rest moves as little as it can and keeps its solution branch (a long move is followed in short steps, each solved with the entity held; a step that cannot be solved that way is approached as far as it can be and the next ones tried; when none past it solves, the last one is left to the sketch's ordinary solve, which may pull it back or leave the sketch unsolved; a step that would sweep an arc through its start is undone and the drag ends there). Returns `reached`: how much of the way from `from` to `to` the geometry followed (0..1), and `at`: where the grabbed spot went (`from` moved as the dragged points did), the `from` of the next move. `live: true` (each frame of an interactive drag) solves the sketch once and leaves the features after it as they were (stale) until `sketch.drag_end` or any command that reads the model; `dof` is then the one from before the drag", + "entity: point or curve, from: [x,y] where it was grabbed, to: [x,y], live?: bool: a point moves toward `to` within the design constraints; when exact cursor placement is impossible, bounded feasible steps minimize cursor distance while keeping design constraints mandatory. A line (spline, conic) slides by to - from; a circle or arc grabbed on its edge takes the radius to `to`. Long moves use continuation to retain the solution branch, and a step that would sweep an arc through its start is rejected. Returns `reached`: progress along the requested move (0..1; feasible point motion projects its actual displacement onto that move), and `at`: where the grabbed spot went (`from` moved as the dragged points did), the `from` of the next move. `live: true` solves the sketch and leaves later features stale until `sketch.drag_end` or a command that reads the model; `dof` is then the one from before the drag", ), CommandSpec::new("sketch.drag_end", "End Sketch Drag", drag_end).icon("sketch_move").enabled(in_sketch).doc_only().params( "constraint?: {command: a sketch.constraint.* id, params}: ends a drag made of `sketch.drag` `live: true` frames: adds the constraint it let go on (not kept if it over-constrains the sketch), then evaluates the whole model once; returns the constraint's result and the sketch's solved state and degrees of freedom", diff --git a/crates/engine/src/cmd/sketch_drag.rs b/crates/engine/src/cmd/sketch_drag.rs index 9e175e9ba..889923032 100644 --- a/crates/engine/src/cmd/sketch_drag.rs +++ b/crates/engine/src/cmd/sketch_drag.rs @@ -104,29 +104,31 @@ impl Path { } } -/// Drag: the grabbed entity follows the cursor exactly (a point goes to it; a line or spline +/// Drag: the grabbed entity follows the cursor where possible (a point moves toward it; a line or spline /// slides by the cursor's move; a circle or arc grabbed on its edge changes radius about its /// centre; a conic grabbed on its curve reads its fullness, `rho`, off the cursor) and the rest /// of the sketch moves as little as it can, staying on the /// solution it started on. Fixed geometry stays. A step that cannot be solved with the entity /// held (the path crosses where the geometry cannot reach) is approached by halving the way to /// it, and the next steps are tried from the last solved state, the last of them being the whole -/// remaining move. When none past it solves, the first failed step stays placed but unsolved: +/// remaining move. A point whose exact pin fails instead minimizes cursor distance in the +/// design's remaining freedom, retaining only corrected, feasible poses. For other entities, +/// when none past it solves, the first failed step stays placed but unsolved: /// the edit's ordinary, non-strict solve that follows (seeded on the last solved state, see /// [`Left::MovedFrom`]) then pulls it back (fully constrained geometry) or leaves the sketch /// unsolved for the user to see. A step that would sweep an arc through its own start is undone /// and the drag ends there. Returns how far it got and what it leaves for the edit's solve /// ([`Left::Solved`]: the held solve of the last step it kept left the sketch solved). /// -/// `live`: one frame of an interactive drag, whose held solves share one frame's decomposition -/// budget ([`Budget::frame`]); otherwise each has a solve's own. +/// `live`: one frame of an interactive drag, whose held solves and cursor correction share +/// one frame's work budget ([`Budget::frame`]); otherwise each has a solve's own. pub(super) fn drag_entity(sk: &mut Sketch, e: Ent, from: Vec2, to: Vec2, live: bool) -> (Dragged, Left) { let Some((path, hold, n, short)) = prepare(sk, e, from, to) else { return (Dragged { reached: 0.0, moving: Vec::new() }, Left::Unsolved); }; #[cfg(test)] let (n, short) = (n.min(step_cap::get()), short.min(step_cap::get())); - let moving = path.points().filter_map(|q| Some((q, sk.point(q)?))).collect(); + let moving: Vec<_> = path.points().filter_map(|q| Some((q, sk.point(q)?))).collect(); let mut frame = live.then(frame_budget); // Only success matters to these solves: the degrees of freedom of a sketch with the entity // held are not the sketch's. Each is seeded on the last solved state (`last`), so what the @@ -211,6 +213,41 @@ pub(super) fn drag_entity(sk: &mut Sketch, e: Ent, from: Vec2, to: Vec2, live: b failed = Some(t); } } + // First retain held continuation across unreachable stretches of an otherwise reachable + // path (for example an arm dragged through the hole around its shoulder). If it cannot + // arrive, optimize the full cursor target without relaxing the design constraints. + if failed.is_some() + && let Ent::Point(q) = e + { + let (points, radii) = sk.coupled(&hold.points, &hold.radii); + let size = smallest_size(sk, &hold, Some(Group { points: &points, radii: &radii })); + let max_step = (size * SHORT_STEP_FRACTION).min(path.length()).max(MIN_STEP); + #[cfg(test)] + let spent = frame.as_ref().map_or(0, Budget::spent); + let followed = solidcraft_sketch::move_point_towards(sk, q, to, max_step, frame.as_mut(), |before, after| { + let mut geometry = Geometry::default(); + geometry.take(before); + !geometry.sweep_wrapped(after) + }); + #[cfg(test)] + if let Some(budget) = &frame { + solves.work += budget.spent() - spent; + solves.cut |= budget.exhausted(); + } + if followed { + #[cfg(test)] + last_drag::set(solves); + let reached = moving + .iter() + .find(|(p, _)| *p == q) + .and_then(|(_, start)| { + let d = to - *start; + sk.point(q).map(|at| if at.dist(to) < 1e-6 || d.dot(d) == 0.0 { 1.0 } else { ((at - *start).dot(d) / d.dot(d)).clamp(0.0, 1.0) }) + }) + .unwrap_or(0.0); + return (Dragged { reached, moving }, Left::Solved); + } + } #[cfg(test)] last_drag::set(solves); let left = match failed { @@ -225,8 +262,8 @@ pub(super) fn drag_entity(sk: &mut Sketch, e: Ent, from: Vec2, to: Vec2, live: b (Dragged { reached: good, moving }, left) } -/// The held solves of one drag: how many, the decomposition work they did, and whether one ran -/// out of budget. +/// The held solves of one drag: how many, their shared work (including cursor correction), +/// and whether it ran out of budget. #[derive(Clone, Copy, Debug, Default, PartialEq)] pub(super) struct Solves { pub count: usize, diff --git a/crates/engine/src/cmd/sketch_ux_tests.rs b/crates/engine/src/cmd/sketch_ux_tests.rs index 0e1c18301..c637d3bd7 100644 --- a/crates/engine/src/cmd/sketch_ux_tests.rs +++ b/crates/engine/src/cmd/sketch_ux_tests.rs @@ -1524,3 +1524,22 @@ fn the_first_dimension_does_not_scale_a_sketch_that_has_a_size() { let out = run(&mut s, "sketch.dimension", json!({"entities": ["l1", "l2"], "value": "60 deg", "scale_sketch": true})); assert!(out.get("scaled").is_none(), "{out}"); } + +/// The cursor fallback shares the held solves' frame budget; a scripted drag can finish later. +#[test] +fn cursor_fallback_respects_an_exhausted_live_frame_budget() { + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points": [[0, 0], [-10, 0]], "ids": ["crank"], "infer": false})); + run(&mut s, "sketch.dimension", json!({"entities": ["crank"], "value": 10})); + let target = v(-10.0, 16.0); + let nearest = target * (10.0 / target.len()); + super::drag::last_drag::with_frame_work(0, || { + run(&mut s, "sketch.drag", json!({"entity": "crank.end", "from": [-10, 0], "to": [target.x, target.y], "live": true})); + }); + let at = pt(&s, "crank.end"); + assert!(at.dist(nearest) > 1.0, "an exhausted frame must not start unbudgeted cursor work: {at:?}"); + assert!((at.len() - 10.0).abs() < 1e-6); + assert!(s.model.state().sketch(s.active_sketch.unwrap()).unwrap().report.ok()); + run(&mut s, "sketch.drag", json!({"entity": "crank.end", "from": [at.x, at.y], "to": [target.x, target.y], "live": false})); + assert!(pt(&s, "crank.end").dist(nearest) < 1e-4, "scripted motion retains the full cursor objective"); +} diff --git a/crates/engine/tests/sketch_drag_target.rs b/crates/engine/tests/sketch_drag_target.rs new file mode 100644 index 000000000..e7d1a9ca9 --- /dev/null +++ b/crates/engine/tests/sketch_drag_target.rs @@ -0,0 +1,107 @@ +//! Cursor distance is minimized within the design's freedom; lengths stay mandatory. +#[path = "support/four_bar.rs"] +mod four_bar; + +use serde_json::json; +use solidcraft_geom::Vec2; + +fn drag(s: &mut solidcraft_engine::Session, target: Vec2) { + let from = four_bar::point(s, "crank.end").unwrap(); + s.execute("sketch.drag", &json!({"entity":"crank.end","from":[from.x,from.y],"to":[target.x,target.y],"live":true})).unwrap(); +} + +#[test] +fn four_bar_large_off_locus_drag_reaches_the_closest_feasible_point() { + for target in [Vec2::new(-10.0, 8.0), Vec2::new(-10.0, -8.0), Vec2::new(20.0, 20.0), Vec2::new(20.0, 0.0), Vec2::new(1000.0, -1000.0)] { + let mut s = four_bar::session().unwrap(); + let side = four_bar::branch(&s).unwrap(); + drag(&mut s, target); + let actual = four_bar::point(&s, "crank.end").unwrap(); + let nearest = target * (10.0 / target.len()); + assert!(actual.dist(nearest) < 1e-4, "target {target:?}, actual {actual:?}, expected {nearest:?}"); + assert!(four_bar::length_error(&s).unwrap() < 1e-6); + assert_eq!(four_bar::branch(&s).unwrap(), side); + let state = s.model.state(); + let report = &state.sketch(s.active_sketch.unwrap()).unwrap().report; + assert!(report.ok()); + assert_eq!(report.dof, 1); + s.execute("sketch.drag_end", &json!({})).unwrap(); + assert!(four_bar::point(&s, "crank.end").unwrap().dist(nearest) < 1e-4); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(four_bar::point(&s, "crank.end").unwrap().dist(Vec2::new(-10.0, 0.0)) < 1e-7); + } +} + +#[test] +fn four_bar_reverse_motion_and_stationary_cursor_do_not_drift() { + let mut s = four_bar::session().unwrap(); + let side = four_bar::branch(&s).unwrap(); + for target in [Vec2::new(-10.0, 16.0), Vec2::new(-10.0, -16.0), Vec2::new(0.0, 25.0), Vec2::new(0.0, -25.0)] { + drag(&mut s, target); + let at = four_bar::point(&s, "crank.end").unwrap(); + assert!( + at.dist(target * (10.0 / target.len())) < 1e-4, + "target {target:?}, actual {at:?}, length error {}", + four_bar::length_error(&s).unwrap() + ); + for _ in 0..8 { + drag(&mut s, target); + assert!(four_bar::point(&s, "crank.end").unwrap().dist(at) < 1e-4); + assert!(four_bar::length_error(&s).unwrap() < 1e-6); + assert_eq!(four_bar::branch(&s).unwrap(), side); + } + } +} + +#[test] +fn four_bar_one_event_and_split_moves_agree_and_keep_the_branch() { + let target = Vec2::new(-10.0, 16.0); + let mut single = four_bar::session().unwrap(); + let mut split = four_bar::session().unwrap(); + let start = four_bar::point(&single, "crank.end").unwrap(); + let side = four_bar::branch(&single).unwrap(); + drag(&mut single, target); + for i in 1..=16 { + drag(&mut split, start + (target - start) * (i as f64 / 16.0)); + assert!(four_bar::length_error(&split).unwrap() < 1e-6); + assert_eq!(four_bar::branch(&split).unwrap(), side); + } + assert!(four_bar::point(&single, "crank.end").unwrap().dist(four_bar::point(&split, "crank.end").unwrap()) < 1e-4); +} + +#[test] +fn four_bar_live_cursor_motion_updates_driven_dimensions_before_release() { + let mut s = four_bar::session().unwrap(); + s.execute("sketch.dimension", &json!({"entities": ["crank"], "type": "horizontal", "driven": true})).unwrap(); + let id = s.active_sketch.unwrap(); + let dimension = s.doc.sketch(id).unwrap().constraints.last().unwrap().id.clone(); + drag(&mut s, Vec2::new(-10.0, 8.0)); + let at = four_bar::point(&s, "crank.end").unwrap(); + assert!(at.dist(Vec2::new(-10.0, 8.0) * (10.0 / 164.0_f64.sqrt())) < 1e-4); + let state = s.model.state(); + for sketch in [s.doc.sketch(id).unwrap(), &state.sketch(id).unwrap().sketch] { + let c = sketch.constraints.iter().find(|c| c.id == dimension).unwrap(); + assert!(c.driven); + assert!((c.kind.value().unwrap() - at.x.abs()).abs() < 1e-6, "reference dimension must measure the final live pose: {:?}", c.kind); + } +} + +#[test] +fn four_bar_other_joint_follows_the_rocker_arc_and_its_limits() { + let base = Vec2::new(42.0, 0.0); + let lo = -(-1264.0_f64 / 1680.0).acos(); + let hi = -(0.2_f64).acos(); + for angle in [-2.6_f64, -2.1, -1.5, -1.1] { + let mut s = four_bar::session().unwrap(); + let side = four_bar::branch(&s).unwrap(); + let from = four_bar::point(&s, "coupler.end").unwrap(); + let target = base + Vec2::new(angle.cos(), angle.sin()) * 60.0; + let nearest = base + Vec2::new(angle.clamp(lo, hi).cos(), angle.clamp(lo, hi).sin()) * 20.0; + s.execute("sketch.drag", &json!({"entity":"coupler.end","from":[from.x,from.y],"to":[target.x,target.y],"live":true})).unwrap(); + assert!(four_bar::point(&s, "coupler.end").unwrap().dist(nearest) < 1e-4, "angle {angle}"); + assert!(four_bar::length_error(&s).unwrap() < 1e-6); + assert_eq!(four_bar::branch(&s).unwrap(), side); + s.execute("sketch.drag_end", &json!({})).unwrap(); + assert!(four_bar::point(&s, "coupler.end").unwrap().dist(nearest) < 1e-4); + } +} diff --git a/crates/engine/tests/support/four_bar.rs b/crates/engine/tests/support/four_bar.rs new file mode 100644 index 000000000..8ec6366f2 --- /dev/null +++ b/crates/engine/tests/support/four_bar.rs @@ -0,0 +1,45 @@ +//! Public-safe 10/40/20/42 mm linkage, matching the reported one-degree-of-freedom sketch. +use serde_json::json; +use solidcraft_engine::Session; +use solidcraft_geom::Vec2; + +pub type Result = std::result::Result>; + +pub fn session() -> Result { + let mut s = Session::default(); + s.execute("sketch.create", &json!({"plane":"XZ"}))?; + let x = -10.0 + (1600.0 - 400.0 + 52.0 * 52.0) / 104.0; + let y = -(1600.0_f64 - (x + 10.0) * (x + 10.0)).sqrt(); + s.execute("sketch.line", &json!({"points":[[0,0],[-10,0],[x,y],[42,0]],"ids":["crank","coupler","rocker"],"infer":false}))?; + s.execute("sketch.line", &json!({"points":["crank.start","rocker.end"],"ids":["ground"],"infer":false}))?; + for (line, length) in [("crank", 10.0), ("coupler", 40.0), ("rocker", 20.0), ("ground", 42.0)] { + s.execute("sketch.dimension", &json!({"entities":[line],"value":length}))?; + } + s.execute("sketch.constraint.horizontal_vertical", &json!({"line":"ground"}))?; + Ok(s) +} + +pub fn point(s: &Session, name: &str) -> Result { + let sk = s.doc.sketch(s.active_sketch.ok_or("missing active sketch")?)?; + sk.resolve_point(name).and_then(|p| sk.point(p)).ok_or_else(|| format!("missing point {name}").into()) +} + +pub fn length_error(s: &Session) -> Result { + let mut error = 0.0_f64; + for (a, b, length) in [ + ("crank.start", "crank.end", 10.0), + ("coupler.start", "coupler.end", 40.0), + ("rocker.start", "rocker.end", 20.0), + ("ground.start", "ground.end", 42.0), + ] { + error = error.max((point(s, a)?.dist(point(s, b)?) - length).abs()); + } + error = error.max(point(s, "crank.start")?.len()); + error = error.max(point(s, "ground.end")?.dist(Vec2::new(42.0, 0.0))); + Ok(error) +} + +pub fn branch(s: &Session) -> Result { + let a = point(s, "crank.end")?; + Ok((point(s, "rocker.end")? - a).cross(point(s, "coupler.end")? - a).signum()) +} diff --git a/crates/sketch/src/cursor.rs b/crates/sketch/src/cursor.rs new file mode 100644 index 000000000..36bdf923d --- /dev/null +++ b/crates/sketch/src/cursor.rs @@ -0,0 +1,296 @@ +//! Feasible cursor motion: optimize only within the design Jacobian's null space, then +//! retract to the constraint manifold. Mouse error never competes with design residuals. +use super::{ + ACCEPT, Hold, Layout, State, TOL, build_blocks, columns, initial_x, layout, lm_capped_with_budget, local_system, max_abs, points_on_curves, + residual_work, system, within_budget, +}; +use crate::{ + Budget, CurveKind, Sketch, + linalg::{Mat, rref}, + union_find::{find, union}, +}; +use solidcraft_geom::Vec2; + +const MAX_VARIABLES: usize = 400; +const MAX_STEPS: usize = 96; +const CORRECTION_ITERS: usize = 16; +const TOTAL_CORRECTION_ITERS: usize = 256; + +/// Move a point toward `target` using freedom left by the design constraints. `max_step` +/// bounds the full variable displacement before constraint correction; `valid` can reject +/// a corrected candidate (for example, an arc crossing its own start). Only feasible, +/// cursor-improving candidates are committed. False leaves the sketch unchanged when the +/// input is unsolved, invalid or outside the dense-work limit. Work is bounded; true may +/// retain the best feasible pose when the iteration or optional shared frame-work budget is +/// exhausted. The work budget includes Jacobian, null-space and LM arithmetic, not wall time. +pub fn move_point_towards( + sk: &mut Sketch, + point: usize, + target: Vec2, + max_step: f64, + mut budget: Option<&mut Budget>, + valid: impl Fn(&Sketch, &Sketch) -> bool, +) -> bool { + let setup_work = sk.points.len().saturating_add(sk.curves.len()).saturating_add(sk.constraints.len()).max(1); + if !within_budget(&mut budget, setup_work) { + return false; + } + if !crate::model::in_range(target) || !max_step.is_finite() || max_step <= 0.0 || !in_range(sk) { + return false; + } + let problem = sk.clone(); + let lay = layout(&problem, &Hold::default()); + let Some(px) = lay.pvar.get(point).copied().flatten() else { return false }; + let (blocks, _) = build_blocks(&problem, &lay, &points_on_curves(&problem)); + let mut parent: Vec = (0..lay.n).collect(); + union(&mut parent, px, px + 1); + for (_, vars) in &blocks { + if let Some(&first) = vars.first() { + for &v in vars.iter().skip(1) { + union(&mut parent, first, v); + } + } + } + let root = find(&mut parent, px); + let vars: Vec = (0..lay.n).filter(|v| find(&mut parent, *v) == root).collect(); + if vars.len() > MAX_VARIABLES { + return false; + } + let sub: Vec<_> = + blocks.iter().filter(|(_, v)| v.iter().any(|i| vars.binary_search(i).is_ok())).map(|(b, v)| (super::copy_block(b), v.clone())).collect(); + // Reserve both initial and final all-block validation before starting cursor work. + // An exhausted search can then keep its best feasible pose, including unrelated blocks. + if !within_budget(&mut budget, residual_work(&lay, &blocks).saturating_mul(2)) { + return false; + } + let mut x = initial_x(&problem, &lay); + let initial_residual = max_abs(&system(&problem, &lay, &blocks, &mut x, false).0); + if initial_residual >= ACCEPT { + return false; + } + let mut col = vec![usize::MAX; lay.n]; + columns(&mut col, &vars, &vars); + let (Some(ix), Some(iy)) = (vars.iter().position(|v| *v == px), vars.iter().position(|v| *v == px + 1)) else { return false }; + let mut best = problem.clone(); + let mut spent = 0; + // Held feasibility solves accept up to ACCEPT. A tiny, nearly feasible hard pin can + // precede a failed step; refine it before constructing a tangent, rather than losing + // the cursor objective just because the previous pose is between TOL and ACCEPT. + if initial_residual >= TOL { + let Some((its, residual)) = lm_capped_with_budget(&problem, &lay, &sub, &vars, &mut x, &col, CORRECTION_ITERS, budget.as_deref_mut()) else { + return false; + }; + spent += its.max(1); + if !(residual < TOL) { + return false; + } + apply(&mut best, &lay, &x); + if !in_range(&best) || !valid(&problem, &best) { + return false; + } + } + let mut gain = 1.0_f64; + for _ in 0..MAX_STEPS { + let at = State { sk: &problem, lay: &lay, x: &x }.p(point); + let error = target - at; + if error.len() < 1e-7 || spent >= TOTAL_CORRECTION_ITERS { + break; + } + let n = vars.len(); + let jacobian_work = residual_work(&lay, &sub).saturating_mul(n.saturating_mul(2).saturating_add(1)); + if !within_budget(&mut budget, jacobian_work) { + break; + } + let (_, j, _) = local_system(&problem, &lay, &sub, &mut x, &col, n); + let null_work = n.saturating_mul(n).saturating_mul(j.rows.saturating_add(n)); + if !within_budget(&mut budget, null_work) { + break; + } + let z = null_space(j); + if z.is_empty() { + break; + } + let mut direction = target_step(&z, ix, iy, error); + let norm = length(&direction); + // Adapt to curvature of the reachable locus. Inside a circle the Gauss-Newton + // cursor step can be arbitrarily small although useful freedom remains. + let scale = if norm > 0.0 { gain.min(max_step / norm) } else { gain }; + for v in &mut direction { + *v *= scale; + } + let mut directions = vec![(direction, false)]; + // A cursor across a circular locus has (nearly) zero first derivative at the + // farthest point. If line search stalls, probe both tangent directions. Testing + // only an exactly zero gradient would strand reversed drags after rounding. + let influence = |v: &&Vec| v.get(ix).copied().unwrap_or(0.0).hypot(v.get(iy).copied().unwrap_or(0.0)); + let mut probes: Vec<_> = z.iter().collect(); + probes.sort_by(|a, b| influence(b).total_cmp(&influence(a))); + for v in probes.into_iter().take(2) { + directions.push((v.iter().map(|x| x * max_step).collect(), true)); + directions.push((v.iter().map(|x| -x * max_step).collect(), true)); + } + let old_cost = error.dot(error); + let mut accepted = None; + 'search: for (direction, probe) in directions { + if length(&direction) < 1e-12 { + continue; + } + for backtrack in 0..if probe { 1 } else { 8 } { + if spent >= TOTAL_CORRECTION_ITERS { + break 'search; + } + let alpha = 0.5_f64.powi(backtrack); + let mut trial = x.clone(); + for (&v, d) in vars.iter().zip(&direction) { + if let Some(t) = trial.get_mut(v) { + *t += alpha * d; + } + } + let Some((its, residual)) = lm_capped_with_budget( + &problem, + &lay, + &sub, + &vars, + &mut trial, + &col, + CORRECTION_ITERS.min(TOTAL_CORRECTION_ITERS - spent), + budget.as_deref_mut(), + ) else { + break 'search; + }; + spent += its.max(1); + if !(residual < TOL) { + if budget.as_ref().is_some_and(|b| b.exhausted()) { + break 'search; + } + continue; + } + let next = State { sk: &problem, lay: &lay, x: &trial }.p(point); + let cost = (target - next).dot(target - next); + if !cost.is_finite() || cost >= old_cost - 1e-14 * old_cost.max(1.0) { + continue; + } + if !within_budget(&mut budget, setup_work.saturating_mul(4)) { + break 'search; + } + let mut candidate = best.clone(); + apply(&mut candidate, &lay, &trial); + if !in_range(&candidate) || !valid(&best, &candidate) { + continue; + } + accepted = Some((trial, candidate, ((if probe { 1.0 } else { scale }) * alpha * 1.5).clamp(1e-8, 1e8))); + break 'search; + } + } + let Some((next, candidate, next_gain)) = accepted else { break }; + x = next; + best = candidate; + gain = next_gain; + } + // Full constraint validation includes constant blocks and disconnected components. + if max_abs(&system(&best, &lay, &blocks, &mut x, false).0) >= ACCEPT { + return false; + } + super::refresh_driven_dimensions(&mut best); + *sk = best; + true +} + +fn length(v: &[f64]) -> f64 { + v.iter().map(|x| x * x).sum::().sqrt() +} + +fn in_range(sk: &Sketch) -> bool { + sk.points.iter().all(|p| crate::model::in_range(p.pos)) + && sk + .curves + .iter() + .all(|c| !matches!(c.kind, CurveKind::Circle { r, .. } | CurveKind::Ellipse { r, .. } if !crate::model::radius_in_range(r))) +} + +fn null_space(mut j: Mat) -> Vec> { + for row in 0..j.rows { + let scale = (0..j.cols).map(|c| j.get(row, c).abs()).fold(0.0_f64, f64::max); + if scale > 0.0 { + for c in 0..j.cols { + j.set(row, c, j.get(row, c) / scale); + } + } + } + let pivots = rref(&mut j, 1e-9); + let mut z: Vec> = Vec::new(); + for free in (0..j.cols).filter(|c| !pivots.contains(c)) { + let mut v = vec![0.0; j.cols]; + if let Some(x) = v.get_mut(free) { + *x = 1.0; + } + for (row, &pivot) in pivots.iter().enumerate() { + if let Some(x) = v.get_mut(pivot) { + *x = -j.get(row, free); + } + } + for _ in 0..2 { + for q in &z { + let d: f64 = v.iter().zip(q).map(|(a, b)| a * b).sum(); + for (a, b) in v.iter_mut().zip(q) { + *a -= d * b; + } + } + } + let norm = length(&v); + if norm.is_finite() && norm > 1e-10 { + for x in &mut v { + *x /= norm; + } + z.push(v); + } + } + z +} + +fn target_step(z: &[Vec], ix: usize, iy: usize, error: Vec2) -> Vec { + let mut a = 0.0; + let mut b = 0.0; + let mut c = 0.0; + for q in z { + let x = q.get(ix).copied().unwrap_or(0.0); + let y = q.get(iy).copied().unwrap_or(0.0); + a += x * x; + b += x * y; + c += y * y; + } + let high = 0.5 * (a + c + (a - c).hypot(2.0 * b)); + let low = if high > 0.0 { (a * c - b * b).max(0.0) / high } else { 0.0 }; + let axis = if a >= c { Vec2::new(high - c, b) } else { Vec2::new(b, high - a) }.normalized().unwrap_or(if a >= c { Vec2::X } else { Vec2::Y }); + let other = Vec2::new(-axis.y, axis.x); + let mut u = if high > 1e-12 { axis * (axis.dot(error) / high) } else { Vec2::ZERO }; + if low > high * 1e-8 { + u += other * (other.dot(error) / low); + } + let mut step = vec![0.0; z.first().map_or(0, Vec::len)]; + for q in z { + let d = q.get(ix).copied().unwrap_or(0.0) * u.x + q.get(iy).copied().unwrap_or(0.0) * u.y; + for (x, v) in step.iter_mut().zip(q) { + *x += d * v; + } + } + step +} + +fn apply(sk: &mut Sketch, lay: &Layout, x: &[f64]) { + for (i, p) in sk.points.iter_mut().enumerate() { + if let Some(v) = lay.pvar.get(i).copied().flatten() + && let (Some(a), Some(b)) = (x.get(v), x.get(v + 1)) + { + p.pos = Vec2::new(*a, *b); + } + } + for (i, c) in sk.curves.iter_mut().enumerate() { + if let Some(v) = lay.rvar.get(i).copied().flatten() + && let Some(value) = x.get(v) + && let CurveKind::Circle { r, .. } | CurveKind::Ellipse { r, .. } = &mut c.kind + { + *r = *value; + } + } +} diff --git a/crates/sketch/src/decompose.rs b/crates/sketch/src/decompose.rs index a91bb921c..58afd2272 100644 --- a/crates/sketch/src/decompose.rs +++ b/crates/sketch/src/decompose.rs @@ -75,9 +75,9 @@ pub(crate) const MAX_WORK: usize = 20_000_000; /// frame (see [`Budget::exhausted`]). pub(crate) const FRAME_WORK: usize = 1_000_000; -/// Work the seed's cluster decomposition may do, shared by the solves it is passed to (the held -/// solves of one drag frame): each decomposition is bounded by what is left, and charges what it -/// did. +/// Work shared by the held solves and feasible cursor correction of one drag frame. Cluster +/// decomposition charges membership scans; cursor correction reserves estimates of dense +/// arithmetic before starting it. These deterministic units approximate time, not a deadline. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Budget { left: usize, @@ -86,7 +86,7 @@ pub struct Budget { } impl Budget { - /// A budget of `work` units (a unit is one membership scan of the merge search). + /// A budget of `work` units: membership scans or estimated dense arithmetic operations. pub fn new(work: usize) -> Budget { Budget { left: work, spent: 0, cut: false } } @@ -98,8 +98,7 @@ impl Budget { pub fn frame() -> Budget { Budget::new(FRAME_WORK) } - /// Some decomposition stopped because the budget ran out: what it would have placed was - /// left to LM, from where it was. + /// Some decomposition or cursor work stopped because the budget ran out. pub fn exhausted(&self) -> bool { self.cut } @@ -110,6 +109,17 @@ impl Budget { pub(crate) fn left(&self) -> usize { self.left } + /// Reserve estimated dense arithmetic before starting it. Unlike a decomposition scan, + /// a dense operation can be large, so it must not overshoot the remaining work. + pub(crate) fn try_charge(&mut self, work: usize) -> bool { + if work > self.left { + self.cut = true; + return false; + } + self.charge(work, false); + true + } + /// Charge a decomposition's `work`; `cut` when it stopped at the budget. pub(crate) fn charge(&mut self, work: usize, cut: bool) { self.left = self.left.saturating_sub(work); diff --git a/crates/sketch/src/lib.rs b/crates/sketch/src/lib.rs index aa941345d..60ba5da57 100644 --- a/crates/sketch/src/lib.rs +++ b/crates/sketch/src/lib.rs @@ -62,8 +62,8 @@ pub use profiles::{ }; pub use shape::{Shape, intersections}; pub use solver::{ - Analysis, CONSISTENT, DrivingValues, Hold, SolveReport, SolveStatus, constraint_residual, determined_by, measure_dimension, solve, - solve_after_edit, solve_after_value_edit, solve_holding, solve_with, + Analysis, CONSISTENT, DrivingValues, Hold, SolveReport, SolveStatus, constraint_residual, determined_by, measure_dimension, move_point_towards, + solve, solve_after_edit, solve_after_value_edit, solve_holding, solve_with, }; pub use text::{MAX_TEXT_CHARS, TextAlign, TextStyle, text_geometry, text_geometry_in, text_geometry_styled}; pub use thin::{MAX_THIN_SEGMENTS, thin_wall_regions}; diff --git a/crates/sketch/src/solver.rs b/crates/sketch/src/solver.rs index bd8974955..3c1dfa825 100644 --- a/crates/sketch/src/solver.rs +++ b/crates/sketch/src/solver.rs @@ -21,6 +21,10 @@ use crate::linalg::{Mat, determined_vars, solve as lin_solve}; use crate::model::{ConstraintKind, CurveKind, Sketch}; use crate::union_find::{find, union}; +#[path = "cursor.rs"] +mod cursor; +pub use cursor::move_point_towards; + #[path = "redundancy.rs"] mod redundancy; pub use redundancy::{CONSISTENT, constraint_residual, determined_by}; @@ -945,6 +949,26 @@ fn lm_capped( col: &[usize], max_iters: usize, ) -> (usize, f64) { + // Without a work budget the initial residual is always evaluated. + lm_capped_with_budget(sk, lay, blocks, vars, x, col, max_iters, None).unwrap_or((0, f64::INFINITY)) +} + +/// Deterministic work units, shared with the frame's decomposition budget. Estimates bound +/// dense arithmetic; they are not a wall-clock deadline. None means no residual was evaluated. +fn lm_capped_with_budget( + sk: &Sketch, + lay: &Layout, + blocks: &[(Block, Vec)], + vars: &[usize], + x: &mut Vec, + col: &[usize], + max_iters: usize, + mut budget: Option<&mut Budget>, +) -> Option<(usize, f64)> { + let evaluation_work = if budget.is_some() { residual_work(lay, blocks) } else { 0 }; + if !within_budget(&mut budget, evaluation_work) { + return None; + } let n = vars.len(); #[cfg(test)] lm_vars::add(n); @@ -953,7 +977,12 @@ fn lm_capped( let mut f = norm2(&r); for it in 0..max_iters { if max_abs(&r) < TOL { - return (it, max_abs(&r)); + return Some((it, max_abs(&r))); + } + let normal_work = + n.saturating_mul(n).saturating_mul(r.len()).saturating_add(evaluation_work.saturating_mul(n.saturating_mul(2).saturating_add(1))); + if !within_budget(&mut budget, normal_work) { + return Some((it, max_abs(&r))); } let (_, j, _) = local_system(sk, lay, blocks, x, col, n); // Normal equations of this component. @@ -979,7 +1008,11 @@ fn lm_capped( // the point sliding along it.) A point held on a curve is cheaper still, so it slides // rather than the curve's ends moving. let weight: Vec = vars.iter().map(|&v| if lay.slide.get(v).copied().unwrap_or(false) { SLIDE_WEIGHT } else { 1.0 }).collect(); - for _ in 0..30 { + for _attempt in 0..30 { + let linear_work = n.saturating_mul(n).saturating_mul(n).saturating_add(evaluation_work); + if !within_budget(&mut budget, linear_work) { + return Some((it, max_abs(&r))); + } let mut m = a.clone(); for (i, w) in weight.iter().enumerate() { m.add(i, i, lambda * w + 1e-12); @@ -1011,10 +1044,18 @@ fn lm_capped( } } if !improved { - return (it, max_abs(&r)); + return Some((it, max_abs(&r))); } } - (max_iters, max_abs(&r)) + Some((max_iters, max_abs(&r))) +} + +fn within_budget(budget: &mut Option<&mut Budget>, work: usize) -> bool { + budget.as_deref_mut().is_none_or(|b| b.try_charge(work)) +} + +fn residual_work(lay: &Layout, blocks: &[(Block, Vec)]) -> usize { + blocks.iter().fold(lay.n.max(1), |work, (_, vars)| work.saturating_add(vars.len().max(1))) } /// The variables LM was given and its runs on this thread, for tests that count what the @@ -2222,17 +2263,7 @@ fn solve_inner( Some(v) => vdet(Some(v)) && vdet(Some(v + 1)), None => true, }; - // Driven dimensions measure the solved geometry. - let fixed_lay = Layout { pvar: vec![None; sk.points.len()], rvar: vec![None; sk.curves.len()], n: 0, points: 0, slide: Vec::new() }; - let measured: Vec> = - sk.constraints.iter().map(|c| if c.driven { measure(&State { sk, lay: &fixed_lay, x: &[] }, &c.kind) } else { None }).collect(); - for (c, m) in sk.constraints.iter_mut().zip(measured) { - if let Some(v) = m - && v.is_finite() - { - c.kind.set_value(v); - } - } + refresh_driven_dimensions(sk); let (dof, point_determined, curve_determined) = match analysis { Analysis::Full => ( lay.n.saturating_sub(rank), @@ -2255,6 +2286,21 @@ fn solve_inner( } } +/// Geometry can also be finalized by feasible cursor motion, without another solve. +/// Both paths must measure reference dimensions from the pose they publish. +fn refresh_driven_dimensions(sk: &mut Sketch) { + let fixed_lay = Layout { pvar: vec![None; sk.points.len()], rvar: vec![None; sk.curves.len()], n: 0, points: 0, slide: Vec::new() }; + let measured: Vec> = + sk.constraints.iter().map(|c| if c.driven { measure(&State { sk, lay: &fixed_lay, x: &[] }, &c.kind) } else { None }).collect(); + for (c, m) in sk.constraints.iter_mut().zip(measured) { + if let Some(v) = m + && v.is_finite() + { + c.kind.set_value(v); + } + } +} + #[cfg(test)] mod continuation_unit_tests { use super::*; diff --git a/crates/sketch/tests/cursor_target.rs b/crates/sketch/tests/cursor_target.rs new file mode 100644 index 000000000..ae2fc8b44 --- /dev/null +++ b/crates/sketch/tests/cursor_target.rs @@ -0,0 +1,160 @@ +//! Analytic cursor oracle plus feasibility checks on every accepted continuation step. +use solidcraft_geom::Vec2; +use solidcraft_sketch::{ConstraintKind, Sketch, move_point_towards, solve}; + +fn linkage() -> (Sketch, usize, usize) { + let mut sk = Sketch::new(); + let a = sk.add_point(Vec2::new(-10.0, 0.0), None).unwrap(); + let x = -10.0 + (1600.0 - 400.0 + 52.0 * 52.0) / 104.0; + let c = sk.add_point(Vec2::new(x, -(1600.0_f64 - (x + 10.0).powi(2)).sqrt()), None).unwrap(); + let b = sk.add_point(Vec2::new(42.0, 0.0), None).unwrap(); + sk.points[b].fixed = true; + for (p, q, value) in [(0, a, 10.0), (a, c, 40.0), (c, b, 20.0)] { + sk.add_constraint(ConstraintKind::Distance { p, q, value }, None).unwrap(); + } + assert!(solve(&mut sk).ok()); + (sk, a, c) +} + +#[test] +fn circle_oracle_all_directions_and_large_targets() { + for radius in [1.0, 12.8, 28.3, 100.0, 1000.0] { + for i in 0..24 { + let (mut sk, a, c) = linkage(); + let angle = std::f64::consts::TAU * i as f64 / 24.0; + let target = Vec2::new(angle.cos(), angle.sin()) * radius; + let nearest = target * (10.0 / radius); + assert!(move_point_towards(&mut sk, a, target, 1.25, None, |before, after| { + assert!(after.points[a].pos.dist(target) < before.points[a].pos.dist(target)); + assert!((after.points[a].pos.len() - 10.0).abs() < 1e-9); + assert!((after.points[a].pos.dist(after.points[c].pos) - 40.0).abs() < 1e-9); + assert!((after.points[c].pos.dist(Vec2::new(42.0, 0.0)) - 20.0).abs() < 1e-9); + (Vec2::new(42.0, 0.0) - after.points[a].pos).cross(after.points[c].pos - after.points[a].pos) < 0.0 + })); + assert!(sk.points[a].pos.dist(nearest) < 1e-4, "radius {radius}, angle {angle}, actual {:?}, nearest {nearest:?}", sk.points[a].pos); + } + } +} + +#[test] +fn fixed_axis_and_rejected_candidates_keep_design_constraints() { + let mut sk = Sketch::new(); + let a = sk.add_point(Vec2::new(10.0, 0.0), None).unwrap(); + let l = sk.add_line_pts(0, a, None).unwrap(); + sk.add_constraint(ConstraintKind::Horizontal { l }, None).unwrap(); + assert!(move_point_towards(&mut sk, a, Vec2::new(20.0, 10.0), 2.0, None, |_, _| true)); + assert!(sk.points[a].pos.dist(Vec2::new(20.0, 0.0)) < 1e-5, "{:?}", sk.points[a].pos); + let before = sk.clone(); + assert!(move_point_towards(&mut sk, a, Vec2::new(-20.0, 10.0), 2.0, None, |_, _| false)); + assert_eq!(sk, before); + assert!(!move_point_towards(&mut sk, usize::MAX, Vec2::ZERO, 1.0, None, |_, _| true)); + assert!(!move_point_towards(&mut sk, a, Vec2::new(f64::NAN, 0.0), 1.0, None, |_, _| true)); + assert_eq!(sk, before); + sk.points[a].pos.x = f64::NAN; + assert!(!move_point_towards(&mut sk, a, Vec2::ZERO, 1.0, None, |_, _| true)); + assert!(sk.points[a].pos.x.is_nan()); +} + +#[test] +fn reversing_across_a_nearly_stationary_extremum_keeps_following() { + let (mut sk, a, _) = linkage(); + for target in [Vec2::new(-10.0, 16.0), Vec2::new(-10.0, -16.0), Vec2::new(0.0, 25.0), Vec2::new(0.0, -25.0)] { + assert!(move_point_towards(&mut sk, a, target, 1.25, None, |_, _| true)); + assert!(sk.points[a].pos.dist(target * (10.0 / target.len())) < 1e-4, "target {target:?}, actual {:?}", sk.points[a].pos); + } +} + +#[test] +fn accepted_constraint_roundoff_is_refined_before_following_the_cursor() { + let (mut sk, a, _) = linkage(); + sk.points[a].pos.x -= 1e-8; + let target = Vec2::new(-10.0, 8.0); + assert!(move_point_towards(&mut sk, a, target, 1.25, None, |_, _| true)); + assert!(sk.points[a].pos.dist(target * (10.0 / target.len())) < 1e-4); + assert!((sk.points[a].pos.len() - 10.0).abs() < 1e-9); +} + +#[test] +fn a_cursor_at_the_pivot_does_not_choose_a_pose_from_roundoff() { + let (mut sk, a, _) = linkage(); + let before = sk.clone(); + assert!(move_point_towards(&mut sk, a, Vec2::ZERO, 1.25, None, |_, _| true)); + assert!(sk.points[a].pos.dist(before.points[a].pos) < 1e-5, "{:?}", sk.points[a].pos); +} + +#[test] +fn cursor_motion_refreshes_driven_dimensions_without_a_followup_solve() { + let (mut sk, a, _) = linkage(); + sk.add_constraint(ConstraintKind::DistanceX { p: 0, q: a, value: 10.0 }, None).unwrap(); + sk.constraints.last_mut().unwrap().driven = true; + assert!(move_point_towards(&mut sk, a, Vec2::new(-10.0, 8.0), 1.25, None, |_, _| true)); + let value = sk.constraints.last().unwrap().kind.value().unwrap(); + assert!((value - sk.points[a].pos.x.abs()).abs() < 1e-6, "reference {value} does not measure {:?}", sk.points[a].pos); +} + +#[test] +fn the_other_moving_joint_reaches_its_rocker_arc_and_motion_limits() { + let base = Vec2::new(42.0, 0.0); + let lo = -(-1264.0_f64 / 1680.0).acos(); // |OC| >= 40 - 10 + let hi = -(0.2_f64).acos(); // |OC| <= 40 + 10 + for angle in [-2.6_f64, -2.1, -1.5, -1.1] { + let (mut sk, a, c) = linkage(); + let target = base + Vec2::new(angle.cos(), angle.sin()) * 60.0; + let nearest = base + Vec2::new(angle.clamp(lo, hi).cos(), angle.clamp(lo, hi).sin()) * 20.0; + assert!(move_point_towards(&mut sk, c, target, 1.25, None, |_, after| { + (base - after.points[a].pos).cross(after.points[c].pos - after.points[a].pos) < 0.0 + })); + assert!(sk.points[c].pos.dist(nearest) < 1e-4, "angle {angle}, actual {:?}, nearest {nearest:?}", sk.points[c].pos); + assert!((sk.points[a].pos.len() - 10.0).abs() < 1e-9); + assert!((sk.points[a].pos.dist(sk.points[c].pos) - 40.0).abs() < 1e-9); + assert!((sk.points[c].pos.dist(base) - 20.0).abs() < 1e-9); + } +} + +#[test] +fn zero_cursor_budget_does_not_start_optimization() { + let (mut sk, a, _) = linkage(); + let before = sk.clone(); + let mut budget = solidcraft_sketch::Budget::new(0); + assert!(!move_point_towards(&mut sk, a, Vec2::new(-10.0, 16.0), 1.25, Some(&mut budget), |_, _| { + panic!("an exhausted budget must not evaluate candidates") + })); + assert_eq!(sk, before); + assert_eq!(budget.spent(), 0); + assert!(budget.exhausted()); +} + +#[test] +fn a_cursor_budget_stop_keeps_the_best_corrected_pose_and_reference_dimensions() { + let target = Vec2::new(-10.0, 16.0); + let nearest = target * (10.0 / target.len()); + let mut stopped_after_progress = false; + for work in [128, 256, 512, 1024, 2048, 4096, 8192, 16384] { + let (mut sk, a, c) = linkage(); + sk.add_constraint(ConstraintKind::DistanceX { p: 0, q: a, value: 10.0 }, None).unwrap(); + sk.constraints.last_mut().unwrap().driven = true; + let before = sk.clone(); + let mut budget = solidcraft_sketch::Budget::new(work); + // The validation callback is Fn: Cell records whether a corrected step was accepted. + let calls = std::cell::Cell::new(0); + let moved = move_point_towards(&mut sk, a, target, 1.25, Some(&mut budget), |_, after| { + calls.set(calls.get() + 1); + assert!((after.points[a].pos.len() - 10.0).abs() < 1e-9); + assert!((after.points[a].pos.dist(after.points[c].pos) - 40.0).abs() < 1e-9); + assert!((after.points[c].pos.dist(Vec2::new(42.0, 0.0)) - 20.0).abs() < 1e-9); + true + }); + assert!(budget.spent() <= work, "{budget:?}"); + if !moved { + assert_eq!(sk, before); + continue; + } + assert!((sk.points[a].pos.len() - 10.0).abs() < 1e-9); + assert!((sk.constraints.last().unwrap().kind.value().unwrap() - sk.points[a].pos.x.abs()).abs() < 1e-6); + if calls.get() > 0 && budget.exhausted() && sk.points[a].pos.dist(nearest) > 1e-4 { + assert!(sk.points[a].pos.dist(target) < before.points[a].pos.dist(target)); + stopped_after_progress = true; + } + } + assert!(stopped_after_progress, "exercise exhaustion after a feasible cursor improvement"); +} From f1a5f4ab301d21914c36ba1326b77193203c29de Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 19 Oct 2026 11:38:55 +0000 Subject: [PATCH 051/225] Regenerate THIRD-PARTY-LICENSES.txt and docs/features.md [skip ci] --- docs/features.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/features.md b/docs/features.md index 1906441e1..2f53897d0 100644 --- a/docs/features.md +++ b/docs/features.md @@ -246,6 +246,7 @@ SolidCraft's commands by area, generated by `cargo xtask features` from the comm | Move Sketches to Component | `component.move_sketches` | – | | Paste New | `component.paste_new` | – | | Component Physical Properties | `component.properties` | – | +| Relink Source | `component.relink` | – | | Rename Component | `component.rename` | – | | Revert Position | `component.revert_position` | SOLID › POSITION | | Unlock Contents | `component.unlock` | – | From 355154fa9bce1ef2993679718daef35f09e849c9 Mon Sep 17 00:00:00 2001 From: JIJINBEI <87472238+jijinbei@users.noreply.github.com> Date: Mon, 19 Oct 2026 20:39:22 +0900 Subject: [PATCH 052/225] refactor: geom::Grid for control nets; one surface fit through a grid of samples (#2331) Thanks @jijinbei. --- crates/geom/src/bspline.rs | 4 + crates/geom/src/grid.rs | 144 ++++++++++++++++ crates/geom/src/lib.rs | 2 + crates/kernel/src/build.rs | 32 +++- crates/kernel/src/fair.rs | 254 ++++++++++++---------------- crates/kernel/src/helix.rs | 38 +---- crates/kernel/src/surface_offset.rs | 26 +-- crates/kernel/src/sweep_path.rs | 69 ++------ 8 files changed, 321 insertions(+), 248 deletions(-) create mode 100644 crates/geom/src/grid.rs diff --git a/crates/geom/src/bspline.rs b/crates/geom/src/bspline.rs index 8d36ae403..8b2cf84f8 100644 --- a/crates/geom/src/bspline.rs +++ b/crates/geom/src/bspline.rs @@ -532,6 +532,10 @@ impl NurbsSurface { pub fn homogeneous(&self) -> &[HPoint] { &self.ctrl } + /// The control net. + pub fn net(&self) -> crate::Grid { + crate::Grid::checked(self.count, self.ctrl.clone()) + } /// Control point `(i, j)`. pub fn point(&self, i: usize, j: usize) -> HPoint { self.ctrl.get(j * self.count[0] + i).copied().unwrap_or(HPoint::ZERO) diff --git a/crates/geom/src/grid.rs b/crates/geom/src/grid.rs new file mode 100644 index 000000000..bcb5c92e6 --- /dev/null +++ b/crates/geom/src/grid.rs @@ -0,0 +1,144 @@ +//! A rectangular net of values: a surface's control points, a sample grid. Rectangular by +//! construction, so code that walks it never meets a missing cell: a grid is made from a +//! function of `(i, j)`, from one row, or from rows checked once ([`Grid::from_u_rows`]). + +/// `count[0]` values along u by `count[1]` along v; value `(i, j)` (i along u) is stored at +/// `j·count[0] + i`, u fastest. +#[derive(Clone, Debug, PartialEq)] +pub struct Grid { + count: [usize; 2], + cells: Vec, +} + +impl Grid { + /// A grid of `f(i, j)` for every cell; `None` when `count[0]·count[1]` overflows. + pub fn from_fn(count: [usize; 2], mut f: impl FnMut(usize, usize) -> T) -> Option> { + let total = count[0].checked_mul(count[1])?; + let cu = count[0].max(1); + Some(Grid { count, cells: (0..total).map(|k| f(k % cu, k / cu)).collect() }) + } + + /// One row of values along u: `count` is `[cells.len(), 1]` (a curve's control points seen + /// as a net). + pub fn row(cells: Vec) -> Grid { + Grid { count: [cells.len(), 1], cells } + } + + /// A grid whose caller already holds `count[0]·count[1]` cells (a checked surface's net). + pub(crate) fn checked(count: [usize; 2], cells: Vec) -> Grid { + Grid { count, cells } + } + + /// Values along u and along v. + pub fn count(&self) -> [usize; 2] { + self.count + } + + pub fn is_empty(&self) -> bool { + self.cells.is_empty() + } + + /// Value `(i, j)`, i along u. + pub fn get(&self, i: usize, j: usize) -> Option<&T> { + if i < self.count[0] { self.cells.get(j * self.count[0] + i) } else { None } + } + + /// The values, u fastest. + pub fn cells(&self) -> &[T] { + &self.cells + } + + /// The runs along u, one per v index: run `j` holds values `(0, j)`, `(1, j)`, …. + pub fn lines(&self) -> std::slice::Chunks<'_, T> { + self.cells.chunks(self.count[0].max(1)) + } + + /// The grid with u and v swapped: value `(i, j)` becomes value `(j, i)`. + pub fn transposed(&self) -> Grid + where + T: Clone, + { + let [cu, cv] = self.count; + let cells = (0..self.cells.len()).filter_map(|k| self.get(k / cv.max(1), k % cv.max(1)).cloned()).collect(); + Grid { count: [cv, cu], cells } + } + + /// The values to change in place; the grid keeps its shape. + pub fn cells_mut(&mut self) -> &mut [T] { + &mut self.cells + } + + pub fn into_cells(self) -> Vec { + self.cells + } + + pub fn map(self, f: impl FnMut(T) -> U) -> Grid { + Grid { count: self.count, cells: self.cells.into_iter().map(f).collect() } + } + + /// [`Grid::map`] with a step that can fail: the first failure. + pub fn try_map(self, f: impl FnMut(T) -> Result) -> Result, E> { + Ok(Grid { count: self.count, cells: self.cells.into_iter().map(f).collect::>()? }) + } + + /// The grid as rows, one per u index: `rows[i][j]` is value `(i, j)` (truck's layout). + pub fn into_u_rows(self) -> Vec> { + let cu = self.count[0]; + let mut rows: Vec> = (0..cu).map(|_| Vec::with_capacity(self.count[1])).collect(); + for (k, v) in self.cells.into_iter().enumerate() { + if let Some(row) = rows.get_mut(k % cu) { + row.push(v); + } + } + rows + } +} + +impl Grid { + /// A grid from rows, one per u index: `rows[i][j]` is value `(i, j)` (truck's layout). + /// `None` when the rows differ in length, the one check rows from elsewhere need. + pub fn from_u_rows>(rows: &[R]) -> Option> { + let cv = rows.first().map_or(0, |r| r.as_ref().len()); + if rows.iter().any(|r| r.as_ref().len() != cv) { + return None; + } + let cells = (0..cv).flat_map(|j| rows.iter().filter_map(move |r| r.as_ref().get(j).cloned())).collect(); + Some(Grid { count: [rows.len(), cv], cells }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rows_go_in_and_come_back_out() { + // rows[i][j]: two along u, three along v. + let rows = vec![vec![(0, 0), (0, 1), (0, 2)], vec![(1, 0), (1, 1), (1, 2)]]; + let g = Grid::from_u_rows(&rows).unwrap(); + assert_eq!(g.count(), [2, 3]); + assert_eq!(g.cells(), &[(0, 0), (1, 0), (0, 1), (1, 1), (0, 2), (1, 2)]); + assert_eq!(g.get(1, 2), Some(&(1, 2))); + assert_eq!(g.get(2, 0), None); + assert_eq!(g.into_u_rows(), rows); + assert_eq!(Grid::row(vec![1, 2, 3]).count(), [3, 1]); + let g = Grid::from_fn([3, 2], |i, j| (i, j)).unwrap(); + assert_eq!(g.lines().collect::>(), vec![&[(0, 0), (1, 0), (2, 0)][..], &[(0, 1), (1, 1), (2, 1)][..]]); + let t = g.transposed(); + assert_eq!(t.count(), [2, 3]); + assert!((0..3).all(|i| (0..2).all(|j| t.get(j, i) == g.get(i, j)))); + assert!(Grid::from_fn([usize::MAX, 2], |_, _| 0).is_none()); + } + + #[test] + fn only_rectangles_are_grids() { + assert!(Grid::from_u_rows(&[vec![1, 2], vec![3]]).is_none()); + let empty: [Vec; 0] = []; + assert!(Grid::from_u_rows(&empty).is_some_and(|g| g.is_empty())); + } + + #[test] + fn try_map_stops_at_the_first_failure() { + assert_eq!(Grid::row(vec![1, -1, -2]).try_map(|x| if x > 0 { Ok(x) } else { Err(x) }), Err(-1)); + } +} diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index 104de3f61..a3f253494 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -18,6 +18,7 @@ pub mod compare; pub mod env; pub mod fill; pub mod fill_general; +mod grid; mod mesh; pub mod mesh_distance; pub mod network; @@ -33,6 +34,7 @@ mod vec; pub use arcfit::MAX_FIT_PIECES; pub use blend::hermite_bezier; pub use bvh::{Bvh, MeshIndex}; +pub use grid::Grid; pub use mesh::{Aabb3, BoxedTriangle, InsideIndex, MassProperties, Mesh, MeshMeasure, find_close_pair}; pub use plane::Plane; pub use profile::{Loop2, MAX_BEZIER_CTRL, MAX_BEZIER_DEGREE, MAX_DERIVATIVE_ORDER, Region2, Seg2, bezier, regions_apart}; diff --git a/crates/kernel/src/build.rs b/crates/kernel/src/build.rs index 34d0ca777..dc3ed31c0 100644 --- a/crates/kernel/src/build.rs +++ b/crates/kernel/src/build.rs @@ -1,7 +1,7 @@ //! Building bodies: extrude and revolve planar regions, primitives. use mt::builder; -use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2, Vec3}; +use solidcraft_geom::{Grid, Loop2, Plane, Region2, Seg2, Vec2, Vec3}; use truck_modeling as mt; use crate::body::{Body, Solid, from_p3, p3, v3}; @@ -2155,6 +2155,36 @@ pub(crate) fn interpolate_cubic(pts: &[Vec3]) -> Option, + /// The surface's edges at the first and the last u (curves across v). + pub u_ends: [mt::BSplineCurve; 2], + /// The surface's edges at the first and the last v (curves across u). + pub v_ends: [mt::BSplineCurve; 2], +} + +/// [`NetFit`] through `samples`; `None` with fewer than four samples across either direction. +pub(crate) fn interpolate_net(samples: &Grid) -> Option { + let across_v: Vec> = samples.transposed().lines().map(interpolate_cubic).collect::>()?; + let across_u: Vec> = + control_net(&across_v)?.lines().map(|run| interpolate_cubic(&run.iter().map(|&p| from_p3(p)).collect::>())).collect::>()?; + let net = control_net(&across_u)?.transposed().into_u_rows(); + let knots = (across_u.first()?.knot_vec().clone(), across_v.first()?.knot_vec().clone()); + let surface = mt::BSplineSurface::try_new(knots, net).ok()?; + let u_ends = [across_v.first()?.clone(), across_v.last()?.clone()]; + let v_ends = [across_u.first()?.clone(), across_u.last()?.clone()]; + Some(NetFit { surface, u_ends, v_ends }) +} + +/// The control points of `curves` as a grid: value `(i, j)` is control point `j` of curve `i`. +/// `None` unless every curve has as many control points. +fn control_net(curves: &[mt::BSplineCurve]) -> Option> { + let rows: Vec<&[mt::Point3]> = curves.iter().map(|c| c.control_points().as_slice()).collect(); + Grid::from_u_rows(&rows) +} + /// [`interpolate_cubic`] by chord length: the parameters (0 to 1) in proportion to the distance /// along the points. Points closer together toward an end (where a curve leaves another /// tangentially) then don't slow the curve to a stop there, where a uniform parameter lets it diff --git a/crates/kernel/src/fair.rs b/crates/kernel/src/fair.rs index d8b4a0bbc..2c65620b1 100644 --- a/crates/kernel/src/fair.rs +++ b/crates/kernel/src/fair.rs @@ -43,8 +43,8 @@ //! control point that does not change the geometry at all — is reported as an error and the //! geometry is left alone. -use solidcraft_geom::Vec3; use solidcraft_geom::bspline::{HPoint, MAX_SPLINE_DEGREE, NurbsSurface, Side, SplineError, check_knots, local_basis}; +use solidcraft_geom::{Grid, Vec3}; use truck_modeling as mt; use crate::body::Body; @@ -167,16 +167,15 @@ pub struct FairCurve { pub report: FairReport, } -/// A faired B-spline control net: the input's degrees, knots and counts, the moved control points -/// (u fastest) and the run's report. +/// A faired B-spline control net: the input's degrees and knots, the moved control points and the +/// run's report. #[derive(Clone, Debug, PartialEq)] pub struct FairNet { pub degree: [usize; 2], pub knots: [Vec; 2], - pub count: [usize; 2], - /// The faired control points, u fastest; the held boundary layers are bit-identical to the - /// input. - pub ctrl: Vec<[f64; N]>, + /// The faired control points, as many as the input's; the held boundary layers are + /// bit-identical to the input. + pub ctrl: Grid<[f64; N]>, pub report: FairReport, } @@ -274,23 +273,23 @@ impl Gram { /// A control net to fair: a tensor-product B-spline with the terms of its fairness energy. A /// direction of one control point (degree 0, knots `[0, 1]`) makes the net a curve, whose energy /// is the one-direction [`CURVE_ENERGY`]. -struct Net { +struct Net<'a, const N: usize> { degree: [usize; 2], - count: [usize; 2], - /// The number of control points, `count[0] · count[1]`. - total: usize, + /// The control points as the design has them; the run moves copies. + ctrl: &'a Grid<[f64; N]>, gram: [Gram; 2], terms: &'static [(usize, usize, f64)], } -impl Net { +impl<'a, const N: usize> Net<'a, N> { /// Check the degrees, knots and counts and build the Gram matrices: an error, never a panic, /// for a degree above [`MAX_SPLINE_DEGREE`], too few control points for the degree, a knot /// vector of the wrong length, unusable knots or an empty parameter range. - fn new(degree: [usize; 2], knots: [Vec; 2], count: [usize; 2], terms: &'static [(usize, usize, f64)]) -> Result { - let Some(total) = count[0].checked_mul(count[1]).filter(|&n| n <= MAX_FAIR_POINTS) else { + fn new(degree: [usize; 2], knots: [Vec; 2], ctrl: &'a Grid<[f64; N]>, terms: &'static [(usize, usize, f64)]) -> Result> { + let count = ctrl.count(); + if ctrl.cells().len() > MAX_FAIR_POINTS { return Err(KernelError::TooLarge(format!("fairing {} × {} control points (at most {MAX_FAIR_POINTS} in all)", count[0], count[1]))); - }; + } for d in 0..2 { let (p, c, kn) = (degree[d], count[d], &knots[d]); if p > MAX_SPLINE_DEGREE { @@ -316,18 +315,28 @@ impl Net { return Err(KernelError::Invalid("a fairness term does not fit the net's degrees".into())); } let gram = [Gram::new(degree[0], &knots[0], count[0])?, Gram::new(degree[1], &knots[1], count[1])?]; - Ok(Net { degree, count, total, gram, terms }) + Ok(Net { degree, ctrl, gram, terms }) + } + + /// Control points along u and along v. + fn count(&self) -> [usize; 2] { + self.ctrl.count() + } + + /// The number of control points, `count[0] · count[1]`. + fn total(&self) -> usize { + self.ctrl.cells().len() } /// The index of control point `(i, j)` in the flattened net (u fastest). fn index(&self, i: usize, j: usize) -> usize { - j * self.count[0] + i + j * self.count()[0] + i } /// The fairness energy `Pᵀ·G·P` of the net `ctrl` (u fastest) and, in `grad`, `G·P`. One /// banded sweep gives both, since `E = Σ Pₚ·(G·P)ₚ`. - fn energy_gradient(&self, ctrl: &[[f64; N]], grad: &mut [[f64; N]]) -> f64 { - let [cu, cv] = self.count; + fn energy_gradient(&self, ctrl: &[[f64; N]], grad: &mut [[f64; N]]) -> f64 { + let [cu, cv] = self.count(); let (pu, pv) = (self.degree[0], self.degree[1]); let mut energy = 0.0; for j in 0..cv { @@ -365,7 +374,7 @@ impl Net { /// step). In the u-fastest order two unknowns couple within `degree_u + degree_v · cols`: /// `degree_u` along a row, `degree_v` rows apart. fn system(&self, interior: &Interior) -> Result { - let [cu, cv] = self.count; + let [cu, cv] = self.count(); let (pu, pv) = (self.degree[0], self.degree[1]); let rows = if cv > 1 { interior.rows.saturating_sub(1).min(pv) } else { 0 }; let mut band = Band::new(interior.points.len(), pu + rows * interior.cols)?; @@ -383,20 +392,18 @@ impl Net { band.factorised() } - /// Fair `ctrl` (u fastest) with checked `opts`: see the module docs. The result is the input - /// with the interior control points moved; the held ones are bit-identical. - fn fair(&self, ctrl: &[[f64; N]], opts: &FairOptions) -> Result<(Vec<[f64; N]>, FairReport)> { - if ctrl.len() != self.total { - return Err(KernelError::Invalid(format!("{} control points, expected {}", ctrl.len(), self.total))); - } + /// Fair the net with checked `opts`: see the module docs. The result is the input with the + /// interior control points moved; the held ones are bit-identical. + fn fair(&self, opts: &FairOptions) -> Result<(Grid<[f64; N]>, FairReport)> { + let ctrl = self.ctrl.cells(); if ctrl.iter().flatten().any(|x| !x.is_finite()) { return Err(KernelError::Invalid("a control point is not a finite number".into())); } let interior = Interior::new(self, if opts.keep_edges { 2 } else { 1 })?; let system = self.system(&interior)?; - let mut current: Vec<[f64; N]> = ctrl.to_vec(); - let mut grad = vec![[0.0; N]; self.total]; - let energy_before = self.energy_gradient(¤t, &mut grad); + let mut current = self.ctrl.clone(); + let mut grad = vec![[0.0; N]; self.total()]; + let energy_before = self.energy_gradient(ctrl, &mut grad); if !energy_before.is_finite() { return Err(KernelError::Invalid("the fairness energy of this net is not a finite number".into())); } @@ -409,7 +416,7 @@ impl Net { let mut b = vec![0.0; interior.points.len()]; let mut report = FairReport { energy_before, energy_after: energy_before, steps: 0, movement: 0.0, energy_trace: Vec::new() }; for _ in 0..opts.iterations { - let e_now = self.energy_gradient(¤t, &mut grad); + let e_now = self.energy_gradient(current.cells(), &mut grad); if !e_now.is_finite() { break; } @@ -431,7 +438,7 @@ impl Net { } // The largest fraction of the step that keeps every control point within the // tolerance of where the design put it, and never more than the whole step. - let mut s = opts.strength.min(interior.limit(ctrl, ¤t, &step, opts.tolerance)); + let mut s = opts.strength.min(interior.limit(ctrl, current.cells(), &step, opts.tolerance)); if !(s > 0.0) { break; } @@ -444,7 +451,7 @@ impl Net { let mut taken = false; for _ in 0..MAX_HALVINGS { let candidate = interior.apply(¤t, &step, s); - let e = self.energy_gradient(&candidate, &mut grad); + let e = self.energy_gradient(candidate.cells(), &mut grad); if e < e_now { current = candidate; report.steps += 1; @@ -464,7 +471,7 @@ impl Net { } } report.energy_after = report.energy_trace.last().copied().unwrap_or(energy_before); - report.movement = interior.movement(ctrl, ¤t); + report.movement = interior.movement(ctrl, current.cells()); Ok((current, report)) } } @@ -483,13 +490,13 @@ struct Interior { impl Interior { /// The interior of `net` with `keep` layers held at each end of each direction (1 without /// [`FairOptions::keep_edges`], 2 with it). - fn new(net: &Net, keep: usize) -> Result { - let [cu, cv] = net.count; + fn new(net: &Net, keep: usize) -> Result { + let [cu, cv] = net.count(); let (i0, i1) = free_span(cu, keep)?; let (j0, j1) = free_span(cv, keep)?; let (cols, rows) = (i1 - i0, j1 - j0); let mut points = Vec::with_capacity(cols * rows); - let mut slot = vec![None; net.total]; + let mut slot = vec![None; net.total()]; for j in j0..j1 { for i in i0..i1 { if let Some(s) = slot.get_mut(net.index(i, j)) { @@ -509,10 +516,10 @@ impl Interior { /// `current` with `s` times the step `d` added to the interior control points; the held ones /// are copied as they are, bit for bit. - fn apply(&self, current: &[[f64; N]], d: &[[f64; N]], s: f64) -> Vec<[f64; N]> { - let mut out = current.to_vec(); + fn apply(&self, current: &Grid<[f64; N]>, d: &[[f64; N]], s: f64) -> Grid<[f64; N]> { + let mut out = current.clone(); for (slot, &at) in self.points.iter().enumerate() { - let (Some(p), Some(v)) = (out.get_mut(at), d.get(slot)) else { continue }; + let (Some(p), Some(v)) = (out.cells_mut().get_mut(at), d.get(slot)) else { continue }; for (x, dx) in p.iter_mut().zip(v) { *x += s * dx; } @@ -697,28 +704,20 @@ impl Band { /// wire in space, 2 for a sketch curve. pub fn fair_curve(degree: usize, knots: &[f64], ctrl: &[[f64; N]], opts: &FairOptions) -> Result> { let opts = opts.checked()?; - let net = Net::new([degree, 0], [knots.to_vec(), TRIVIAL_KNOTS.to_vec()], [ctrl.len(), 1], &CURVE_ENERGY)?; - let (faired, report) = net.fair(ctrl, &opts)?; - Ok(FairCurve { degree, knots: knots.to_vec(), ctrl: faired, report }) + let row = Grid::row(ctrl.to_vec()); + let (faired, report) = Net::new([degree, 0], [knots.to_vec(), TRIVIAL_KNOTS.to_vec()], &row, &CURVE_ENERGY)?.fair(&opts)?; + Ok(FairCurve { degree, knots: knots.to_vec(), ctrl: faired.into_cells(), report }) } /// Fair the interior of a B-spline control net with the thin-plate energy /// `∫∫ ‖S_uu‖² + 2‖S_uv‖² + ‖S_vv‖² du dv` in the net's own parameters (see the module docs). -/// `count[0]` control points lie along u and `count[1]` along v, `ctrl` is u fastest, and the -/// boundary layers (see [`FairOptions::keep_edges`]) are held. The generic core behind +/// The boundary layers (see [`FairOptions::keep_edges`]) are held. The generic core behind /// [`fair_surface`], [`fair_bspline_surface`] and their rational counterparts, for a caller with /// its own control net. -pub fn fair_net( - degree: [usize; 2], - knots: [&[f64]; 2], - count: [usize; 2], - ctrl: &[[f64; N]], - opts: &FairOptions, -) -> Result> { +pub fn fair_net(degree: [usize; 2], knots: [&[f64]; 2], ctrl: &Grid<[f64; N]>, opts: &FairOptions) -> Result> { let opts = opts.checked()?; - let net = Net::new(degree, [knots[0].to_vec(), knots[1].to_vec()], count, &SURFACE_ENERGY)?; - let (faired, report) = net.fair(ctrl, &opts)?; - Ok(FairNet { degree, knots: [knots[0].to_vec(), knots[1].to_vec()], count, ctrl: faired, report }) + let (faired, report) = Net::new(degree, [knots[0].to_vec(), knots[1].to_vec()], ctrl, &SURFACE_ENERGY)?.fair(&opts)?; + Ok(FairNet { degree, knots: [knots[0].to_vec(), knots[1].to_vec()], ctrl: faired, report }) } /// Fair a truck B-spline curve's control points: [`fair_curve`] on its three-dimensional points, @@ -762,64 +761,55 @@ pub fn fair_nurbs_curve(curve: &mt::NurbsCurve, opts: &FairOptions) /// of the same knots, with the boundary rows held. Guarded like [`fair_bspline_curve`]. pub fn fair_bspline_surface(surface: &mt::BSplineSurface, opts: &FairOptions) -> Result<(mt::BSplineSurface, FairReport)> { guard("fair a B-spline surface", || { - let rows = surface.control_points(); - let count = [rows.len(), rows.first().map_or(0, Vec::len)]; - if count[0] == 0 || count[1] == 0 { - return Err(KernelError::Invalid("the surface has no control points".into())); - } - if rows.iter().any(|r| r.len() != count[1]) { - return Err(KernelError::Invalid("the surface's control net is not rectangular".into())); - } - // truck keeps the net as control_points()[i][j] with i along u; fair_net wants u fastest. - let mut ctrl = Vec::with_capacity(count[0] * count[1]); - for j in 0..count[1] { - for i in 0..count[0] { - let Some(p) = rows.get(i).and_then(|r| r.get(j)) else { continue }; - ctrl.push([p.x, p.y, p.z]); - } - } + let net = truck_net(surface.control_points())?; let (ku, kv) = surface.knot_vecs(); let (pu, pv) = surface.degrees(); - let faired = fair_net([pu, pv], [ku, kv], count, &ctrl, opts)?; - let mut net: Vec> = Vec::with_capacity(count[0]); - for i in 0..count[0] { - let mut row = Vec::with_capacity(count[1]); - for j in 0..count[1] { - let Some(c) = faired.ctrl.get(j * count[0] + i) else { - return Err(KernelError::Failed("fairing lost a control point".into())); - }; - row.push(mt::Point3::new(c[0], c[1], c[2])); - } - net.push(row); - } + let faired = fair_net([pu, pv], [ku, kv], &net.map(|p| [p.x, p.y, p.z]), opts)?; + let net = faired.ctrl.map(|[x, y, z]| mt::Point3::new(x, y, z)).into_u_rows(); let surface = mt::BSplineSurface::try_new((ku.clone(), kv.clone()), net).map_err(|e| KernelError::Failed(format!("fair: {e}")))?; Ok((surface, faired.report)) }) } +/// A truck surface's control net (`rows[i][j]`, i along u) as a grid: refused when it is empty +/// or not rectangular. +fn truck_net(rows: &[Vec

]) -> Result> { + let net = Grid::from_u_rows(rows).ok_or_else(|| KernelError::Invalid("the surface's control net is not rectangular".into()))?; + if net.is_empty() { + return Err(KernelError::Invalid("the surface has no control points".into())); + } + Ok(net) +} + +/// A homogeneous control net's Cartesian points; refused when a weight is zero (the point has no +/// position). +fn positions(net: &Grid) -> Result> { + net.clone().try_map(|h| { + let p = h.project().ok_or_else(|| KernelError::Invalid("a control point has no position: its weight is zero".into()))?; + Ok([p.x, p.y, p.z]) + }) +} + +/// `net` moved to the faired `points`, each keeping its weight. +fn reweighted(mut net: Grid, points: &Grid<[f64; 3]>) -> Grid { + for (h, &[x, y, z]) in net.cells_mut().iter_mut().zip(points.cells()) { + *h = HPoint::weighted(Vec3::new(x, y, z), h.w); + } + net +} + /// Fair a geom NURBS surface's control net: [`fair_net`] on its Cartesian control points, with /// the weights kept as they are (a fairing moves points, not weights) and the boundary rows held. /// A rational surface's geometry then stays within the tolerance too, by the same convex-hull /// bound as the non-rational case. pub fn fair_surface(surface: &NurbsSurface, opts: &FairOptions) -> Result<(NurbsSurface, FairReport)> { - let [cu, cv] = surface.count(); - let mut ctrl = Vec::with_capacity(cu * cv); - let mut weights = Vec::with_capacity(cu * cv); - for j in 0..cv { - for i in 0..cu { - let h = surface.point(i, j); - let Some(p) = h.project() else { - return Err(KernelError::Invalid("a control point has no position: its weight is zero".into())); - }; - ctrl.push([p.x, p.y, p.z]); - weights.push(h.w); - } - } + let net = surface.net(); let [ku, kv] = surface.knots(); let degree = surface.degree(); - let faired = fair_net(degree, [ku, kv], [cu, cv], &ctrl, opts)?; - let points: Vec = faired.ctrl.iter().zip(&weights).map(|(p, w)| HPoint::weighted(Vec3::new(p[0], p[1], p[2]), *w)).collect(); - let out = NurbsSurface::from_homogeneous(degree, surface.knots().clone(), points).map_err(|e| spline_error("fairing the surface", e))?; + let faired = fair_net(degree, [ku, kv], &positions(&net)?, opts)?; + let net = reweighted(net, &faired.ctrl); + let out = + NurbsSurface::from_homogeneous(degree, surface.knots().clone(), net.into_cells()).map_err(|e| spline_error("fairing the surface", e))?; Ok((out, faired.report)) } @@ -829,40 +819,11 @@ pub fn fair_surface(surface: &NurbsSurface, opts: &FairOptions) -> Result<(Nurbs pub fn fair_nurbs_surface(surface: &mt::NurbsSurface, opts: &FairOptions) -> Result<(mt::NurbsSurface, FairReport)> { guard("fair a NURBS surface", || { let bsp = surface.non_rationalized(); - let rows = bsp.control_points(); - let count = [rows.len(), rows.first().map_or(0, Vec::len)]; - if count[0] == 0 || count[1] == 0 { - return Err(KernelError::Invalid("the surface has no control points".into())); - } - if rows.iter().any(|r| r.len() != count[1]) { - return Err(KernelError::Invalid("the surface's control net is not rectangular".into())); - } - let mut ctrl = Vec::with_capacity(count[0] * count[1]); - let mut weights = Vec::with_capacity(count[0] * count[1]); - for j in 0..count[1] { - for i in 0..count[0] { - let Some(h) = rows.get(i).and_then(|r| r.get(j)) else { continue }; - let Some(p) = (HPoint { x: h.x, y: h.y, z: h.z, w: h.w }).project() else { - return Err(KernelError::Invalid("a control point has no position: its weight is zero".into())); - }; - ctrl.push([p.x, p.y, p.z]); - weights.push(h.w); - } - } + let net = truck_net(bsp.control_points())?.map(|h| HPoint { x: h.x, y: h.y, z: h.z, w: h.w }); let (ku, kv) = bsp.knot_vecs(); let (pu, pv) = bsp.degrees(); - let faired = fair_net([pu, pv], [ku, kv], count, &ctrl, opts)?; - let mut net: Vec> = Vec::with_capacity(count[0]); - for i in 0..count[0] { - let mut row = Vec::with_capacity(count[1]); - for j in 0..count[1] { - let (Some(c), Some(w)) = (faired.ctrl.get(j * count[0] + i), weights.get(j * count[0] + i)) else { - return Err(KernelError::Failed("fairing lost a control point".into())); - }; - row.push(mt::Vector4::new(c[0] * w, c[1] * w, c[2] * w, *w)); - } - net.push(row); - } + let faired = fair_net([pu, pv], [ku, kv], &positions(&net)?, opts)?; + let net = reweighted(net, &faired.ctrl).map(|h| mt::Vector4::new(h.x, h.y, h.z, h.w)).into_u_rows(); let bsp = mt::BSplineSurface::try_new((ku.clone(), kv.clone()), net).map_err(|e| KernelError::Failed(format!("fair: {e}")))?; Ok((mt::NurbsSurface::new(bsp), faired.report)) }) @@ -1167,18 +1128,18 @@ mod tests { rough[j * cu + i][2] += d; } let opts = FairOptions::new(1.0, 6, false, 100.0).unwrap(); - let faired = fair_net(degree, [&ku, &kv], [cu, cv], &rough, &opts).unwrap(); + let faired = fair_net(degree, [&ku, &kv], &Grid::from_fn([cu, cv], |i, j| rough[j * cu + i]).unwrap(), &opts).unwrap(); for j in 0..cv { for i in [0, cu - 1] { - assert_eq!(faired.ctrl[j * cu + i], rough[j * cu + i], "column {i}, row {j} moved"); + assert_eq!(faired.ctrl.get(i, j), Some(&rough[j * cu + i]), "column {i}, row {j} moved"); } } for i in 0..cu { for j in [0, cv - 1] { - assert_eq!(faired.ctrl[j * cu + i], rough[j * cu + i], "row {j}, column {i} moved"); + assert_eq!(faired.ctrl.get(i, j), Some(&rough[j * cu + i]), "row {j}, column {i} moved"); } } - let near = (0..cu * cv).map(|k| dist(&faired.ctrl[k], &smooth[k])).fold(0.0, f64::max); + let near = faired.ctrl.cells().iter().zip(&smooth).map(|(a, b)| dist(a, b)).fold(0.0, f64::max); let far = (0..cu * cv).map(|k| dist(&rough[k], &smooth[k])).fold(0.0, f64::max); eprintln!("net: perturbation {far} mm, faired to {near:e} mm, energy {:e} → {:e}", faired.report.energy_before, faired.report.energy_after); assert!(near < 1e-6, "{near:e}"); @@ -1191,16 +1152,16 @@ mod tests { inner[j * cu + i][2] += d; } let kept = FairOptions::new(1.0, 6, true, 100.0).unwrap(); - let faired = fair_net(degree, [&ku, &kv], [cu, cv], &inner, &kept).unwrap(); + let faired = fair_net(degree, [&ku, &kv], &Grid::from_fn([cu, cv], |i, j| inner[j * cu + i]).unwrap(), &kept).unwrap(); let shell = |i: usize, j: usize| i < 2 || i + 2 >= cu || j < 2 || j + 2 >= cv; for j in 0..cv { for i in 0..cu { if shell(i, j) { - assert_eq!(faired.ctrl[j * cu + i], inner[j * cu + i], "({i}, {j}) is a boundary layer and moved"); + assert_eq!(faired.ctrl.get(i, j), Some(&inner[j * cu + i]), "({i}, {j}) is a boundary layer and moved"); } } } - let near = (0..cu * cv).filter(|&k| !shell(k % cu, k / cu)).map(|k| dist(&faired.ctrl[k], &smooth[k])).fold(0.0, f64::max); + let near = (0..cu * cv).filter(|&k| !shell(k % cu, k / cu)).map(|k| dist(&faired.ctrl.cells()[k], &smooth[k])).fold(0.0, f64::max); eprintln!("net with keep_edges: interior faired to {near:e} mm, energy {:e} → {:e}", faired.report.energy_before, faired.report.energy_after); assert!(near < 1e-6 && faired.report.energy_after < faired.report.energy_before); } @@ -1376,10 +1337,13 @@ mod tests { let flat = [0.0, 0.0, 1.0, 2.0, 2.0]; let grid = [[0.0, 0.0, 0.0]; 9]; let kept = FairOptions::new(1.0, 4, true, 1.0).unwrap(); - assert!(fair_net([1, 1], [&flat, &flat], [3, 3], &grid, &kept).is_err(), "keep_edges on a 3 × 3 net"); + assert!( + fair_net([1, 1], [&flat, &flat], &Grid::from_fn([3, 3], |i, j| grid[j * 3 + i]).unwrap(), &kept).is_err(), + "keep_edges on a 3 × 3 net" + ); // A net too large to fair, refused before anything is allocated for it. let line = [0.0, 0.0, 1.0, 1.0]; - assert!(fair_net([1, 1], [&line, &line], [65, 65], &vec![[0.0; 3]; 65 * 65], &ok).is_err(), "4225 control points"); + assert!(fair_net([1, 1], [&line, &line], &Grid::from_fn([65, 65], |_, _| [0.0; 3]).unwrap(), &ok).is_err(), "4225 control points"); // A singular system: a cubic whose last control points lie past the end of its domain // (0.5), where they do not move the curve at all, so the interior equations have no // unique solution and the run must refuse rather than move anything. @@ -1405,14 +1369,20 @@ mod tests { for &(i, j, d) in &[(1usize, 2usize, 2.5), (2, 2, -1.5), (3, 3, 3.0), (2, 1, -2.0)] { rough[j * cu + i][2] += d; } - let faired = fair_net(degree, [&ku, &kv], [cu, cv], &rough, &FairOptions::new(1.0, 8, false, 100.0).unwrap()).unwrap(); - let near = (0..cu * cv).map(|k| dist(&faired.ctrl[k], &smooth[k])).fold(0.0, f64::max); + let faired = fair_net( + degree, + [&ku, &kv], + &Grid::from_fn([cu, cv], |i, j| rough[j * cu + i]).unwrap(), + &FairOptions::new(1.0, 8, false, 100.0).unwrap(), + ) + .unwrap(); + let near = faired.ctrl.cells().iter().zip(&smooth).map(|(a, b)| dist(a, b)).fold(0.0, f64::max); eprintln!("5 × 5 quadratic net: faired to {near:e} mm, energy {:e} → {:e}", faired.report.energy_before, faired.report.energy_after); assert!(near < 1e-6 && faired.report.energy_after < 1e-9 * faired.report.energy_before); for j in 0..cv { for i in 0..cu { if i == 0 || i + 1 == cu || j == 0 || j + 1 == cv { - assert_eq!(faired.ctrl[j * cu + i], rough[j * cu + i], "({i}, {j}) is on the boundary and moved"); + assert_eq!(faired.ctrl.get(i, j), Some(&rough[j * cu + i]), "({i}, {j}) is on the boundary and moved"); } } } diff --git a/crates/kernel/src/helix.rs b/crates/kernel/src/helix.rs index 9948fed74..37b4a52c9 100644 --- a/crates/kernel/src/helix.rs +++ b/crates/kernel/src/helix.rs @@ -1,11 +1,11 @@ //! Helical sweeps (coils, springs) and lofts to a point (pyramids, cones). use mt::builder; -use solidcraft_geom::{Loop2, Mesh, Plane, Region2, Seg2, Vec2, Vec3}; +use solidcraft_geom::{Grid, Loop2, Mesh, Plane, Region2, Seg2, Vec2, Vec3}; use truck_modeling as mt; use crate::body::{Body, Solid, p3}; -use crate::build::{cap_and_close, uniform_wire}; +use crate::build::{NetFit, cap_and_close, interpolate_net, uniform_wire}; use crate::numbered::NumberedLoop; use crate::record::{self, Side}; use crate::{KernelError, Result, guard}; @@ -124,33 +124,13 @@ fn smooth_helix(plane: &Plane, profile: &NumberedLoop, o: Vec3, k: Vec3, pitch: o + rot(w - o, k, a) + k * (pitch * a / std::f64::consts::TAU) }; let fail = |w: &str| KernelError::Failed(format!("smooth helix: {w}")); - // Per segment: the station curves (control points along v) and the surface net. + // Per segment: the wall surface through its samples at every station. let mut faces_data = Vec::with_capacity(nseg); for s in &lp.segs { - let mut station_curves = Vec::with_capacity(n + 1); - for i in 0..=n { - let pts: Vec = (0..SEG_SAMPLES).map(|j| at(i, s.point_at(j as f64 / (SEG_SAMPLES - 1) as f64))).collect(); - station_curves.push(crate::build::interpolate_cubic(&pts).ok_or_else(|| fail("profile curve"))?); - } - let kv = station_curves.first().map(|c| c.knot_vec().clone()).ok_or_else(|| fail("no stations"))?; - // Along the helix: each control-point column interpolated across the stations. - let mut columns = Vec::with_capacity(SEG_SAMPLES); - for j in 0..SEG_SAMPLES { - let pts: Vec = station_curves - .iter() - .map(|c| { - let p = c.control_point(j); - Vec3::new(p.x, p.y, p.z) - }) - .collect(); - columns.push(crate::build::interpolate_cubic(&pts).ok_or_else(|| fail("helix curve"))?); - } - let ku = columns.first().map(|c| c.knot_vec().clone()).ok_or_else(|| fail("no columns"))?; - let net: Vec> = (0..=n).map(|m| columns.iter().map(|c| *c.control_point(m)).collect()).collect(); - let surf = mt::BSplineSurface::try_new((ku, kv), net).map_err(|e| fail(&e.to_string()))?; - let (Some(first), Some(last)) = (station_curves.first().cloned(), station_curves.last().cloned()) else { return Err(fail("stations")) }; - let seam = columns.first().cloned().ok_or_else(|| fail("seam"))?; - faces_data.push((first, last, seam, surf)); + // u along the helix (the stations), v along the profile segment. + let samples = + Grid::from_fn([n + 1, SEG_SAMPLES], |i, j| at(i, s.point_at(j as f64 / (SEG_SAMPLES - 1) as f64))).ok_or_else(|| fail("samples"))?; + faces_data.push(interpolate_net(&samples).ok_or_else(|| fail("wall surface"))?); } guard("smooth helix", || { let start: Vec = lp.segs.iter().map(|s| builder::vertex(p3(at(0, s.start())))).collect(); @@ -158,7 +138,7 @@ fn smooth_helix(plane: &Plane, profile: &NumberedLoop, o: Vec3, k: Vec3, pitch: let mut e0 = Vec::with_capacity(nseg); let mut e1 = Vec::with_capacity(nseg); let mut seams = Vec::with_capacity(nseg); - for (j, (c0, c1, seam, _)) in faces_data.iter().enumerate() { + for (j, NetFit { u_ends: [c0, c1], v_ends: [seam, _], .. }) in faces_data.iter().enumerate() { let (Some(a0), Some(b0), Some(a1), Some(b1)) = (start.get(j), start.get((j + 1) % nseg), end.get(j), end.get((j + 1) % nseg)) else { return Err(fail("vertices")); }; @@ -167,7 +147,7 @@ fn smooth_helix(plane: &Plane, profile: &NumberedLoop, o: Vec3, k: Vec3, pitch: seams.push(mt::Edge::try_new(a0, a1, mt::Curve::BSplineCurve(seam.clone())).map_err(|e| fail(&e.to_string()))?); } let mut walls = Vec::with_capacity(nseg); - for (j, (_, _, _, surf)) in faces_data.iter().enumerate() { + for (j, NetFit { surface: surf, .. }) in faces_data.iter().enumerate() { let (Some(a), Some(b), Some(sa), Some(sb)) = (e0.get(j), e1.get(j), seams.get(j), seams.get((j + 1) % nseg)) else { return Err(fail("edges")); }; diff --git a/crates/kernel/src/surface_offset.rs b/crates/kernel/src/surface_offset.rs index d4dadeb5f..a4b523552 100644 --- a/crates/kernel/src/surface_offset.rs +++ b/crates/kernel/src/surface_offset.rs @@ -10,10 +10,11 @@ use std::collections::HashMap; use mt::{BoundedCurve, InnerSpace, ParametricCurve, ParametricSurface, ParametricSurface3D, SearchNearestParameter}; -use solidcraft_geom::Vec3; +use solidcraft_geom::{Grid, Vec3}; use truck_modeling as mt; use crate::body::{Body, from_p3, p3}; +use crate::build::interpolate_net; use crate::history::FaceOrigin; use crate::surfaces::{Offset, map_curve, map_surface, surface_body}; use crate::{KernelError, Result, guard}; @@ -270,9 +271,10 @@ fn fit(f: &mt::Face, distance: f64, tolerance: f64) -> Result> = - (0..=n).map(|i| (0..=n).map(|j| at(i as f64 / n as f64, j as f64 / n as f64)).collect::>>()).collect::>()?; - let surface = interpolate_surface(&grid).ok_or_else(|| KernelError::Failed("offset: fitting the surface".into()))?; + let grid = Grid::from_fn([n + 1, n + 1], |i, j| at(i as f64 / n as f64, j as f64 / n as f64)) + .ok_or_else(|| KernelError::TooLarge("offset: the sample grid".into()))? + .try_map(|p| p)?; + let surface = interpolate_net(&grid).map(|fit| fit.surface).ok_or_else(|| KernelError::Failed("offset: fitting the surface".into()))?; // Checked between the samples, where a fit strays most. let mut worst = 0.0f64; for i in 0..n { @@ -315,22 +317,6 @@ fn principal_curvatures(s: &mt::Surface, u: f64, v: f64) -> Option<(f64, f64)> { Some((h + disc, h - disc)) } -/// A cubic B-spline surface through a grid of points at uniform parameters on [0, 1]². -fn interpolate_surface(grid: &[Vec]) -> Option> { - let rows: Vec> = grid.iter().map(|r| crate::build::interpolate_cubic(r)).collect::>()?; - let kv = rows.first()?.knot_vec().clone(); - let m = rows.first()?.control_points().len(); - let mut cols = Vec::with_capacity(m); - for j in 0..m { - let pts: Vec = rows.iter().filter_map(|r| r.control_points().get(j).map(|p| from_p3(*p))).collect(); - cols.push(crate::build::interpolate_cubic(&pts)?); - } - let ku = cols.first()?.knot_vec().clone(); - let n = cols.first()?.control_points().len(); - let net: Vec> = (0..n).map(|i| cols.iter().filter_map(|c| c.control_points().get(i).copied()).collect()).collect(); - mt::BSplineSurface::try_new((ku, kv), net).ok() -} - /// `s` (on [0, 1]²) with its knots stretched onto `u` × `v`. fn reparameterised(s: mt::BSplineSurface, u: (f64, f64), v: (f64, f64)) -> mt::BSplineSurface { let stretch = |kv: &mt::KnotVec, (a, b): (f64, f64)| mt::KnotVec::from(kv.iter().map(|k| a + (b - a) * k).collect::>()); diff --git a/crates/kernel/src/sweep_path.rs b/crates/kernel/src/sweep_path.rs index 322fc766e..f2e9292fb 100644 --- a/crates/kernel/src/sweep_path.rs +++ b/crates/kernel/src/sweep_path.rs @@ -6,11 +6,11 @@ //! described. use mt::builder; -use solidcraft_geom::{Plane, Region2, Seg2, Vec2, Vec3}; +use solidcraft_geom::{Grid, Plane, Region2, Seg2, Vec2, Vec3}; use truck_modeling as mt; use crate::body::{Body, p3}; -use crate::build::{cap_and_close, close_sweep, interpolate_cubic, smooth_loft_faces, uniform_wire}; +use crate::build::{NetFit, cap_and_close, close_sweep, interpolate_net, smooth_loft_faces, uniform_wire}; use crate::numbered::{NumberedLoop, NumberedRegion}; use crate::record::{self, Side}; use crate::{KernelError, Result, guard}; @@ -686,32 +686,9 @@ pub(crate) fn smooth_sheet(plane: &Plane, chains: &[Vec], path: &[Vec3], c // and end, and the wall surface. let mut data = Vec::with_capacity(chain.len()); for s in chain { - let mut station_curves = Vec::with_capacity(n + 1); - for i in 0..=n { - let q: Vec = (0..SEG_SAMPLES).map(|j| at(i, s.point_at(j as f64 / (SEG_SAMPLES - 1) as f64))).collect(); - station_curves.push(interpolate_cubic(&q).ok_or_else(|| fail("profile curve"))?); - } - let kv = station_curves.first().map(|c| c.knot_vec().clone()).ok_or_else(|| fail("no stations"))?; - let mut columns = Vec::with_capacity(SEG_SAMPLES); - for j in 0..SEG_SAMPLES { - let q: Vec = station_curves - .iter() - .map(|c| { - let p = c.control_point(j); - Vec3::new(p.x, p.y, p.z) - }) - .collect(); - columns.push(interpolate_cubic(&q).ok_or_else(|| fail("path curve"))?); - } - let ku = columns.first().map(|c| c.knot_vec().clone()).ok_or_else(|| fail("no columns"))?; - let net: Vec> = (0..=n).map(|m| columns.iter().map(|c| *c.control_point(m)).collect()).collect(); - let surf = mt::BSplineSurface::try_new((ku, kv), net).map_err(|e| fail(&e.to_string()))?; - let (Some(c0), Some(c1), Some(first), Some(last)) = - (station_curves.first().cloned(), station_curves.last().cloned(), columns.first().cloned(), columns.last().cloned()) - else { - return Err(fail("stations")); - }; - data.push((c0, c1, first, last, surf)); + let samples = + Grid::from_fn([n + 1, SEG_SAMPLES], |i, j| at(i, s.point_at(j as f64 / (SEG_SAMPLES - 1) as f64))).ok_or_else(|| fail("samples"))?; + data.push(interpolate_net(&samples).ok_or_else(|| fail("wall surface"))?); } let walls: Vec = guard("path sweep", || { let m = chain.len(); @@ -725,13 +702,13 @@ pub(crate) fn smooth_sheet(plane: &Plane, chains: &[Vec], path: &[Vec3], c // The column through each corner: the start column of the segment leaving it, or // the end column of the last segment. let col = match data.get(k) { - Some((_, _, first, _, _)) => first, - None => data.last().map(|d| &d.3).ok_or_else(|| fail("seam"))?, + Some(NetFit { v_ends: [first, _], .. }) => first, + None => data.last().map(|NetFit { v_ends: [_, last], .. }| last).ok_or_else(|| fail("seam"))?, }; seams.push(mt::Edge::try_new(a, b, mt::Curve::BSplineCurve(col.clone())).map_err(|e| fail(&e.to_string()))?); } let mut walls = Vec::with_capacity(m); - for (j, (c0, c1, _, _, surf)) in data.iter().enumerate() { + for (j, NetFit { surface: surf, u_ends: [c0, c1], .. }) in data.iter().enumerate() { let (Some(a0), Some(b0), Some(a1), Some(b1), Some(sa), Some(sb)) = (start.get(j), start.get(next(j)), end.get(j), end.get(next(j)), seams.get(j), seams.get(next(j))) else { @@ -826,35 +803,15 @@ fn smooth_walls(plane: &Plane, profile: &NumberedLoop, st: &[Station], expected: let n = st.len() - 1; let mut data = Vec::with_capacity(nseg); for s in &lp.segs { - let mut station_curves = Vec::with_capacity(n + 1); - for i in 0..=n { - let pts: Vec = (0..SEG_SAMPLES).map(|j| at(i, s.point_at(j as f64 / (SEG_SAMPLES - 1) as f64))).collect(); - station_curves.push(interpolate_cubic(&pts).ok_or_else(|| fail("profile curve"))?); - } - let kv = station_curves.first().map(|c| c.knot_vec().clone()).ok_or_else(|| fail("no stations"))?; - let mut columns = Vec::with_capacity(SEG_SAMPLES); - for j in 0..SEG_SAMPLES { - let pts: Vec = station_curves - .iter() - .map(|c| { - let p = c.control_point(j); - Vec3::new(p.x, p.y, p.z) - }) - .collect(); - columns.push(interpolate_cubic(&pts).ok_or_else(|| fail("path curve"))?); - } - let ku = columns.first().map(|c| c.knot_vec().clone()).ok_or_else(|| fail("no columns"))?; - let net: Vec> = (0..=n).map(|m| columns.iter().map(|c| *c.control_point(m)).collect()).collect(); - let surf = mt::BSplineSurface::try_new((ku, kv), net).map_err(|e| fail(&e.to_string()))?; - let (Some(first), Some(last)) = (station_curves.first().cloned(), station_curves.last().cloned()) else { return Err(fail("stations")) }; - let seam = columns.first().cloned().ok_or_else(|| fail("seam"))?; - data.push((first, last, seam, surf)); + let samples = + Grid::from_fn([n + 1, SEG_SAMPLES], |i, j| at(i, s.point_at(j as f64 / (SEG_SAMPLES - 1) as f64))).ok_or_else(|| fail("samples"))?; + data.push(interpolate_net(&samples).ok_or_else(|| fail("wall surface"))?); } guard("path sweep", || { let start: Vec = lp.segs.iter().map(|s| builder::vertex(p3(at(0, s.start())))).collect(); let end: Vec = lp.segs.iter().map(|s| builder::vertex(p3(at(n, s.start())))).collect(); let (mut e0, mut e1, mut seams) = (Vec::with_capacity(nseg), Vec::with_capacity(nseg), Vec::with_capacity(nseg)); - for (j, (c0, c1, seam, _)) in data.iter().enumerate() { + for (j, NetFit { u_ends: [c0, c1], v_ends: [seam, _], .. }) in data.iter().enumerate() { let (Some(a0), Some(b0), Some(a1), Some(b1)) = (start.get(j), start.get((j + 1) % nseg), end.get(j), end.get((j + 1) % nseg)) else { return Err(fail("vertices")); }; @@ -863,7 +820,7 @@ fn smooth_walls(plane: &Plane, profile: &NumberedLoop, st: &[Station], expected: seams.push(mt::Edge::try_new(a0, a1, mt::Curve::BSplineCurve(seam.clone())).map_err(|e| fail(&e.to_string()))?); } let mut walls = Vec::with_capacity(nseg); - for (j, (_, _, _, surf)) in data.iter().enumerate() { + for (j, NetFit { surface: surf, .. }) in data.iter().enumerate() { let (Some(a), Some(b), Some(sa), Some(sb)) = (e0.get(j), e1.get(j), seams.get(j), seams.get((j + 1) % nseg)) else { return Err(fail("edges")); }; From aef13b52f4c741bef5cb9ab630287c53de986f79 Mon Sep 17 00:00:00 2001 From: rlartot <94693724+rlartot@users.noreply.github.com> Date: Mon, 19 Oct 2026 13:44:40 +0200 Subject: [PATCH 053/225] Pattern and Mirror copies of a primitive change only the seed's targets (#2755) (#2756) Thanks @rlartot. --- crates/doc/src/eval.rs | 3 +++ crates/engine/src/cmd/patterns_tests.rs | 28 +++++++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 71e40fcc9..ca8773c4b 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -4356,6 +4356,9 @@ fn replay( continue; } let (op, targets) = feature_op(src); + // A primitive's or a hole's targets are its participants (#1108): the copies change + // those bodies only, like the feature itself (#2755). + let targets = if targets.is_empty() { src.participants.clone() } else { targets }; let mut copies = Vec::new(); if let FeatureKind::Hole { diameter, depth, hole, to, .. } = &src.kind { // A hole is drilled again at each copy of its spot (found on the surface there), so diff --git a/crates/engine/src/cmd/patterns_tests.rs b/crates/engine/src/cmd/patterns_tests.rs index 0444c02aa..97603e7a8 100644 --- a/crates/engine/src/cmd/patterns_tests.rs +++ b/crates/engine/src/cmd/patterns_tests.rs @@ -521,3 +521,31 @@ fn pattern_of_cuts_beside_a_round_needs_no_retries() { let v = volume(&mut s); assert!(rel(v, expected) < 1e-5, "{v} vs {expected}"); } + +/// #2755: a cut cylinder with `targets` cuts only those bodies, and so do its pattern and mirror +/// copies: a body over the plate that the cylinder was told to leave alone keeps its volume. +#[test] +fn copies_of_a_primitive_cut_only_its_targets() { + let body_volume = |s: &mut Session, name: &str| { + let m = run(s, "inspect.measure", json!({"bodies": [name]})); + m["bodies"][0]["volume_mm3"].as_f64().unwrap_or(f64::NAN) + }; + // The command, and the holes in the plate after it (the cylinder's and its copies). + for (copy, holes) in [ + (json!(["solid.pattern.rectangular", {"features": ["Trou"], "dir1": [1, 0, 0], "count1": 3, "spacing1": 30}]), 3.0), + (json!(["solid.mirror", {"features": ["Trou"], "plane": {"origin": [50, 0, 0], "normal": [1, 0, 0]}}]), 2.0), + ] { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 100, "width": 60, "height": 10, "body_name": "Plaque"})); + run(&mut s, "solid.box", json!({"length": 100, "width": 60, "height": 10, "corner": [0, 0, 5], "operation": "new", "body_name": "Voisin"})); + let cyl = json!({"radius": 3, "height": 30, "base": [10, 10, -5], "operation": "cut", "targets": ["Plaque"], "name": "Trou"}); + run(&mut s, "solid.cylinder", cyl); + assert!(rel(body_volume(&mut s, "Voisin"), 60000.0) < 1e-9); + let (id, p) = (copy[0].as_str().unwrap_or_default(), copy[1].clone()); + let r = run(&mut s, id, p); + assert_eq!(r["changed_bodies"], json!(["Plaque"]), "{id}"); + assert!(rel(body_volume(&mut s, "Voisin"), 60000.0) < 1e-9, "{id} cut Voisin"); + let removed = 60000.0 - body_volume(&mut s, "Plaque"); + assert!(rel(removed, holes * PI * 9.0 * 10.0) < 1e-3, "{id}: {removed} mm³ cut from Plaque"); + } +} From 7fd51ce6a5e27dfbc589c228aff4e47c0dc2b149 Mon Sep 17 00:00:00 2001 From: SS-EN <84559909+SS-EN@users.noreply.github.com> Date: Mon, 19 Oct 2026 08:18:01 -0400 Subject: [PATCH 054/225] timeline.roll_to: accept "end", refuse other non-number positions (#2902) A position that is not a number or "end" is now refused instead of moving the marker to the end. --- crates/engine/src/cmd/edit.rs | 16 +++++++++++++--- crates/engine/src/cmd/edit_tests.rs | 22 ++++++++++++++++++++++ 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 3d596cbe0..67d682d03 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -41,9 +41,9 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("timeline.move_many", "Move Timeline Items", move_many).icon("reorder").params( "features?: [id|name], groups?: [folder ids], group?: folder id, position: insertion slot; atomically changes folder membership and moves all selected contents as one block", ), - CommandSpec::new("timeline.rollback", "Move Timeline Marker", rollback).icon("rollback").params("position: number of features to keep active (omit = end)"), + CommandSpec::new("timeline.rollback", "Move Timeline Marker", rollback).icon("rollback").params("position: number of features to keep active, or \"end\" (omit = end)"), CommandSpec::new("timeline.roll_to", "Roll History Marker", rollback).icon("rollback") - .params("position: number of features to keep active (omit = end) | feature: id|name (the marker goes right after it)"), + .params("position: number of features to keep active, or \"end\" (omit = end) | feature: id|name (the marker goes right after it)"), CommandSpec::new("timeline.reorder", "Reorder Feature", reorder).icon("reorder") .params("feature: id|name, position: its new index; refused when a feature that worked would fail"), CommandSpec::new("timeline.reorder_many", "Reorder Features", reorder_many).icon("reorder").params( @@ -509,7 +509,17 @@ fn rollback(s: &mut Session, p: &Value) -> Result { let id = feature_id(s, Some(f), "timeline.roll_to")?; s.doc.feature_index(id).map(|i| i + 1) } - None => num(p, "position").map(|x| x.max(0.0) as usize), + // A number of features, or "end" (as omitting it); anything else is refused rather than + // read as "end". + None => match p.get("position") { + None | Some(Value::Null) => None, + Some(Value::String(t)) if t.trim().eq_ignore_ascii_case("end") => None, + Some(v) => { + let x = v.as_f64().or_else(|| v.as_str().and_then(|t| t.trim().parse::().ok())).and_then(crate::params::finite); + let why = "`position` must be a number of features to keep active, or \"end\""; + Some(x.map(|x| x.max(0.0) as usize).ok_or_else(|| bad("timeline.roll_to", why))?) + } + }, }; s.doc_mut().marker = match pos { Some(k) if k < n => Some(k), diff --git a/crates/engine/src/cmd/edit_tests.rs b/crates/engine/src/cmd/edit_tests.rs index 22ebcf033..a5381f327 100644 --- a/crates/engine/src/cmd/edit_tests.rs +++ b/crates/engine/src/cmd/edit_tests.rs @@ -8,6 +8,28 @@ fn run(s: &mut Session, id: &str, params: Value) -> Value { s.execute(id, ¶ms).unwrap_or_else(|e| panic!("{id} {params}: {e}")) } +/// `timeline.roll_to` takes a number of features or "end"; any other value is refused instead of +/// silently moving the marker to the end. +#[test] +fn roll_to_takes_a_number_or_end_and_refuses_anything_else() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10})); + run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 20, "operation": "join"})); + for cmd in ["timeline.roll_to", "timeline.rollback"] { + assert_eq!(run(&mut s, cmd, json!({"position": 1}))["marker"], 1); + assert_eq!(run(&mut s, cmd, json!({"position": "end"}))["marker"], 2); + assert_eq!(run(&mut s, cmd, json!({"position": "1"}))["marker"], 1, "a number in a string is still a number"); + assert_eq!(run(&mut s, cmd, json!({"position": "END"}))["marker"], 2); + run(&mut s, cmd, json!({"position": 1})); + for bad in [json!("start"), json!("first"), json!([1]), json!({"n": 1}), json!(true), json!("NaN")] { + let e = s.execute(cmd, &json!({"position": bad})).unwrap_err().to_string(); + assert!(e.contains("`position` must be a number") && e.contains("\"end\""), "{bad}: {e}"); + assert_eq!(s.doc.marker, Some(1), "{bad}: the refused call left the marker where it was"); + } + assert_eq!(run(&mut s, cmd, json!({}))["marker"], 2, "omitted: the end"); + } +} + #[test] fn g2_fillet_survives_edit_undo_and_reopen() { use solidcraft_doc::{Document, FeatureKind, FilletStyle}; From 5f399207bf048fff95b807da06cf3ac0309b56b5 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Mon, 19 Oct 2026 08:31:49 -0400 Subject: [PATCH 055/225] CI: a translation change tests the UI and xtask, not the whole workspace (#3061) assets/locales/ belongs to no crate, so affected.py selected the full workspace (every crate, all four test shards) for a catalog-only PR. Only solidcraft-ui-egui embeds the catalogs and xtask checks them; map the folder to those two packages and their dependents. Co-authored-by: Claude Opus 5.5 --- scripts/ci/affected.py | 4 ++++ scripts/ci/test_affected.py | 8 ++++++++ 2 files changed, 12 insertions(+) diff --git a/scripts/ci/affected.py b/scripts/ci/affected.py index b6d0a082a..bf1ff20bc 100644 --- a/scripts/ci/affected.py +++ b/scripts/ci/affected.py @@ -28,6 +28,8 @@ FULL_FILES = ("Cargo.toml", "Cargo.lock") IGNORED_PREFIXES = ("docs/", "packaging/") # Root files that a crate embeds (include_str!), so they are not ignorable documentation. EMBEDDED = {"ATTRIBUTION.md": "solidcraft-ui-egui"} +# Asset folders that only some packages read: the UI embeds the catalogs, xtask checks them. +EMBEDDED_PREFIXES = {"assets/locales/": ("solidcraft-ui-egui", "xtask")} def load_metadata(path): @@ -76,6 +78,8 @@ def select(meta, paths): hit.add(by_dir[max(owners, key=len)]) elif path in EMBEDDED: hit.add(EMBEDDED[path]) + elif any(path.startswith(p) for p in EMBEDDED_PREFIXES): + hit.update(next(v for p, v in EMBEDDED_PREFIXES.items() if path.startswith(p))) elif path.startswith(IGNORED_PREFIXES) or ("/" not in path and path.endswith(".md")): continue else: diff --git a/scripts/ci/test_affected.py b/scripts/ci/test_affected.py index 5fae56cd9..f31fabc1c 100644 --- a/scripts/ci/test_affected.py +++ b/scripts/ci/test_affected.py @@ -71,6 +71,14 @@ class RealWorkspace(unittest.TestCase): def test_docs_only_selects_nothing(self): self.assertEqual(affected.select(self.meta, ["docs/book/src/dev/testing.md", "CONTRIBUTING.md"]), (False, [])) + def test_translation_selects_the_ui_and_xtask_not_the_kernel(self): + full, pk = affected.select(self.meta, ["assets/locales/ja.json", "assets/locales/it.json"]) + self.assertFalse(full) + self.assertIn("solidcraft-ui-egui", pk) + self.assertIn("xtask", pk) + self.assertNotIn("solidcraft-kernel", pk) + self.assertNotIn("solidcraft-engine", pk) + if __name__ == "__main__": unittest.main() From 4c30d944f54113b75c3e2f06d343146a01118015 Mon Sep 17 00:00:00 2001 From: The Nomad Date: Mon, 19 Oct 2026 08:48:06 -0400 Subject: [PATCH 056/225] 3D mouse: only the window with focus moves (#2077) (#2212) With two windows open, the 3D mouse now moves only the one with focus. --- apps/solidcraft/src/space_mouse.rs | 5 ++++- crates/ui-egui/src/space_mouse.rs | 31 +++++++++++++++++++++++++----- 2 files changed, 30 insertions(+), 6 deletions(-) diff --git a/apps/solidcraft/src/space_mouse.rs b/apps/solidcraft/src/space_mouse.rs index 00568cf08..96c0d1ab3 100644 --- a/apps/solidcraft/src/space_mouse.rs +++ b/apps/solidcraft/src/space_mouse.rs @@ -625,7 +625,10 @@ mod tests { wheel: WheelGuard::default(), started: now, }; - mouse.tick_at(&mut app, &Context::default(), now); + // A window that has run a frame with focus, as the app's always has by now. + let ctx = Context::default(); + let _ = ctx.run_ui(egui::RawInput::default(), |_| {}); + mouse.tick_at(&mut app, &ctx, now); let DeviceMotion { motion, seconds } = app.viewport.device_motion.expect("the frame hands the page its motion"); assert_eq!(motion, Motion { translation: [0.0; 3], rotation: [0.0, 0.0, -1.0] }); assert!(seconds > 0.0); diff --git a/crates/ui-egui/src/space_mouse.rs b/crates/ui-egui/src/space_mouse.rs index 4b4ef6fed..f6663b369 100644 --- a/crates/ui-egui/src/space_mouse.rs +++ b/crates/ui-egui/src/space_mouse.rs @@ -139,7 +139,8 @@ pub struct DeviceMotion { /// picker is open. Returns whether there was motion to hand over; it then asks for the next frame /// itself. pub fn navigate_frame(app: &mut SolveApp, ctx: &egui::Context, mapping: DriverMapping, axes: Axes, seconds: f64) -> bool { - if !app.preferences.space_mouse_enabled || app.home.open || app.file_picker_busy() || axes == Axes::default() { + // Only the window with focus: with two windows open, the cap moves the one being used, not both. + if !app.preferences.space_mouse_enabled || app.home.open || app.file_picker_busy() || axes == Axes::default() || !ctx.input(|i| i.focused) { return false; } let speed = f64::from(app.preferences.space_mouse_speed); @@ -177,6 +178,15 @@ mod tests { crate::navigation::device_camera(cam, motion, seconds, height, !sketch, reverse_zoom); } + /// A window that has run a frame, with or without focus. A context that has never run one + /// reads as unfocused, so the tests run one first, as the app always has. + fn window(focused: bool) -> egui::Context { + let ctx = egui::Context::default(); + let mut output = ctx.run_ui(egui::RawInput { focused, ..Default::default() }, |_| {}); + output.textures_delta.clear(); + ctx + } + /// One frame: the 3D mouse hands its motion over, and the modelling viewport applies it. fn frame(app: &mut SolveApp, ctx: &egui::Context, mapping: DriverMapping, axes: Axes, seconds: f64) -> bool { let handed = navigate_frame(app, ctx, mapping, axes, seconds); @@ -339,7 +349,7 @@ mod tests { #[test] fn a_frame_moves_the_view_and_keeps_the_next_frame_coming() { - let ctx = egui::Context::default(); + let ctx = window(true); let mut app = app(); let before = app.cam; assert!(frame(&mut app, &ctx, DriverMapping::default(), PUSH, 0.02)); @@ -351,9 +361,20 @@ mod tests { assert_eq!(app.cam.distance, still.distance); } + #[test] + fn only_the_focused_window_moves() { + // Two windows side by side (#2077): the cap moves the one with focus and leaves the other. + let mut app = app(); + let before = app.cam; + assert!(!frame(&mut app, &window(false), DriverMapping::default(), PUSH, 0.02)); + assert_eq!(app.cam.distance, before.distance); + assert!(frame(&mut app, &window(true), DriverMapping::default(), PUSH, 0.02)); + assert!(app.cam.distance < before.distance); + } + #[test] fn an_open_file_picker_holds_the_view_until_it_closes() { - let ctx = egui::Context::default(); + let ctx = window(true); let mut app = app(); let slot: crate::picker_test_support::Slot = Default::default(); crate::picker_test_support::open(&mut app, &slot); @@ -372,7 +393,7 @@ mod tests { #[test] fn a_long_gap_between_frames_moves_as_far_as_a_short_one() { - let ctx = egui::Context::default(); + let ctx = window(true); let (mut short, mut long) = (app(), app()); frame(&mut short, &ctx, DriverMapping::default(), PUSH, 0.05); frame(&mut long, &ctx, DriverMapping::default(), PUSH, 30.0); @@ -387,7 +408,7 @@ mod tests { #[test] fn navigation_off_the_start_page_and_a_hostile_speed_leave_the_view_alone() { - let ctx = egui::Context::default(); + let ctx = window(true); let mut off = app(); off.preferences.space_mouse_enabled = false; let mut home = app(); From aee47fca0062c2ea03a82d1fda2d411c494c9b66 Mon Sep 17 00:00:00 2001 From: fugazister Date: Mon, 19 Oct 2026 15:09:35 +0200 Subject: [PATCH 057/225] Messages window: keep status messages to read and copy again (#2763) (#2764) Status messages are kept for the session in a Messages window (Help menu, or click the status chip), newest first, with Copy all. --- assets/locales/cs.json | 9 ++ assets/locales/en.json | 9 ++ assets/locales/it.json | 9 ++ assets/locales/ja.json | 9 ++ assets/locales/zh.json | 9 ++ crates/ui-egui/src/control.rs | 1 + crates/ui-egui/src/help.rs | 8 +- crates/ui-egui/src/lib.rs | 8 +- crates/ui-egui/src/messages.rs | 203 +++++++++++++++++++++++++++++ crates/ui-egui/src/select_other.rs | 4 +- crates/ui-egui/src/viewport.rs | 5 + docs/book/src/guide/ui-tour.md | 1 + docs/control-protocol.md | 1 + 13 files changed, 271 insertions(+), 5 deletions(-) create mode 100644 crates/ui-egui/src/messages.rs diff --git a/assets/locales/cs.json b/assets/locales/cs.json index a6119472b..9df1715f9 100644 --- a/assets/locales/cs.json +++ b/assets/locales/cs.json @@ -687,6 +687,15 @@ "joint.from_bodies_hint": "Každé vybrané těleso se přesune do vlastní nové komponenty a zůstane na místě.", "joint.one_body": "Oba výběry jsou na {body}. Druhý vyberte na jiném dílu.", "joint.one_component": "Tyto díly jsou tělesy jedné komponenty: {bodies}. Kloub pohybuje jednou komponentou vůči druhé, takže každý díl potřebuje vlastní komponentu.", + "messages.ago_h": "před {n} h", + "messages.ago_min": "před {n} min", + "messages.ago_s": "před {n} s", + "messages.chip_hint": "Klikněte pro všechny zprávy této relace", + "messages.clear": "Vymazat", + "messages.copy_all": "Kopírovat vše", + "messages.menu": "Zprávy…", + "messages.none": "Zatím žádné zprávy.", + "messages.title": "Zprávy", "nav.touchpad.help": "Podržením Shift a pohybem ukazatele posouváte; podržením Alt/Option a pohybem otáčíte. Tlačítko myši není potřeba. Svislé posouvání přibližuje.", "nav.touchpad.label": "Touchpad", "nav.touchpad.orbit": "Otáčení (podržte Alt/Option a pohybujte; bez tlačítka myši)", diff --git a/assets/locales/en.json b/assets/locales/en.json index 55f762924..d3c74c2b0 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -719,6 +719,15 @@ "joint.from_bodies_hint": "Each picked body moves into a new component of its own and stays where it is.", "joint.one_body": "Both picks are on {body}. Pick the second one on another part.", "joint.one_component": "These parts are bodies of one component: {bodies}. A joint moves one component against another, so each part needs a component of its own.", + "messages.ago_h": "{n} h ago", + "messages.ago_min": "{n} min ago", + "messages.ago_s": "{n} s ago", + "messages.chip_hint": "Click for all messages of this session", + "messages.clear": "Clear", + "messages.copy_all": "Copy all", + "messages.menu": "Messages…", + "messages.none": "No messages yet.", + "messages.title": "Messages", "motion.checked_to": "Checked to step {step} only: the check ran out of its work budget", "motion.collision": "{a} · {b}: steps {steps}", "motion.duration_hint": "seconds (empty: per step)", diff --git a/assets/locales/it.json b/assets/locales/it.json index 0d3784dc4..4b02cc884 100644 --- a/assets/locales/it.json +++ b/assets/locales/it.json @@ -704,6 +704,15 @@ "joint.from_bodies_hint": "Ogni corpo selezionato viene spostato in un nuovo componente distinto, mantenendo la sua posizione.", "joint.one_body": "Entrambe le selezioni sono su {body}. Seleziona il secondo elemento su un'altra parte.", "joint.one_component": "Queste parti sono corpi di un unico componente: {bodies}. Un giunto muove un componente rispetto a un altro, quindi ogni parte richiede un componente distinto.", + "messages.ago_h": "{n} h fa", + "messages.ago_min": "{n} min fa", + "messages.ago_s": "{n} s fa", + "messages.chip_hint": "Fai clic per tutti i messaggi di questa sessione", + "messages.clear": "Cancella", + "messages.copy_all": "Copia tutto", + "messages.menu": "Messaggi…", + "messages.none": "Ancora nessun messaggio.", + "messages.title": "Messaggi", "motion.checked_to": "Controllato solo fino al passo {step}: il controllo ha esaurito il limite di calcolo", "motion.collision": "{a} · {b}: passi {steps}", "motion.duration_hint": "secondi (vuoto: per passo)", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index b40c29bc1..a1c8c9f4a 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -719,6 +719,15 @@ "joint.from_bodies_hint": "選択した各ボディを、位置はそのままで専用の新しいコンポーネントに移動します。", "joint.one_body": "両方の選択が {body} 上にあります。2 つ目は別の部品で選択してください。", "joint.one_component": "これらの部品は 1 つのコンポーネントのボディです: {bodies}。ジョイントはコンポーネント同士を動かすため、部品ごとに専用のコンポーネントが必要です。", + "messages.ago_h": "{n} 時間前", + "messages.ago_min": "{n} 分前", + "messages.ago_s": "{n} 秒前", + "messages.chip_hint": "クリックするとこのセッションのすべてのメッセージを表示します", + "messages.clear": "クリア", + "messages.copy_all": "すべてコピー", + "messages.menu": "メッセージ…", + "messages.none": "まだメッセージはありません。", + "messages.title": "メッセージ", "motion.checked_to": "ステップ {step} までしか確認していません: 確認の計算量の上限に達しました", "motion.collision": "{a} · {b}: ステップ {steps}", "motion.duration_hint": "秒 (空欄: ステップごと)", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index b4d664675..8daee673e 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -719,6 +719,15 @@ "joint.from_bodies_hint": "每个所选实体移入各自的新组件,位置保持不变。", "joint.one_body": "两次选择都在 {body} 上。请在另一个零件上选择第二个。", "joint.one_component": "这些零件是同一组件的实体:{bodies}。接头使一个组件相对另一个组件运动,因此每个零件都需要自己的组件。", + "messages.ago_h": "{n} 小时前", + "messages.ago_min": "{n} 分钟前", + "messages.ago_s": "{n} 秒前", + "messages.chip_hint": "点击查看本次会话的所有消息", + "messages.clear": "清除", + "messages.copy_all": "全部复制", + "messages.menu": "消息…", + "messages.none": "暂无消息。", + "messages.title": "消息", "motion.checked_to": "仅检查到第 {step} 步:检查已用完其工作量上限", "motion.collision": "{a} · {b}:第 {steps} 步", "motion.duration_hint": "秒(留空:按步)", diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 08ade43df..c22f9b87f 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -284,6 +284,7 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) -> } "engine.commands" => wrap(app.session.execute("engine.commands", &json!({})).map_err(|e| e.to_string())), "document.inspect" => wrap(app.session.execute("document.inspect", p).map_err(|e| e.to_string())), + "ui.messages" => ok(crate::messages::control(app, p)), "ui.inspect" => ok(json!({ "ui": serde_json::to_value(&app.ui).unwrap_or_default(), "visibility": app.session.visibility, diff --git a/crates/ui-egui/src/help.rs b/crates/ui-egui/src/help.rs index 5b751a1ee..9f9cfb4dd 100644 --- a/crates/ui-egui/src/help.rs +++ b/crates/ui-egui/src/help.rs @@ -1,6 +1,7 @@ //! The Help menu (the ? button on the application bar): Documentation (the online book), About //! SolidCraft (version, commit, build date, licences, attributions, fonts), the keyboard shortcuts -//! (read only), and Report an Issue, which opens a local editable report draft. +//! (read only), Messages (every status message of the run, #2763), and Report an Issue, which +//! opens a local editable report draft. use egui::{RichText, vec2}; @@ -43,7 +44,7 @@ pub fn diagnostics(app: &SolveApp) -> String { ) } -/// Run a Help menu item: `docs`, `about`, `shortcuts`, `report`, `crashes`. +/// Run a Help menu item: `docs`, `about`, `shortcuts`, `messages`, `report`, `crashes`. pub fn run(app: &mut SolveApp, ctx: &egui::Context, item: &str) { app.help.menu = false; match item { @@ -54,6 +55,7 @@ pub fn run(app: &mut SolveApp, ctx: &egui::Context, item: &str) { app.keymap.read_only = true; } "crashes" => crate::crash_ui::open(app), + "messages" => app.messages.open = true, "report" => { let dialog = app.dialog.clone(); let error = dialog.as_ref().and_then(|d| d.error.clone()).or_else(|| app.preview.error.clone()); @@ -74,6 +76,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context, anchor: egui::Pos2) { ("docs", "Documentation"), ("about", "About SolidCraft"), ("shortcuts", "Keyboard Shortcuts"), + ("messages", "Messages…"), ("report", "Report an Issue…"), ("crashes", "Crash Reports…"), ] { @@ -95,6 +98,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context, anchor: egui::Pos2) { } about(app, ctx); crate::crash_ui::show(app, ctx); + crate::messages::show(app, ctx); } fn about(app: &mut SolveApp, ctx: &egui::Context) { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 29b6fb11e..d165e9129 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -75,6 +75,7 @@ mod material_card_review; mod measurement_ui_tests; #[cfg(test)] mod menu_tests; +pub mod messages; #[cfg(test)] mod pattern_arrow_tests; #[cfg(test)] @@ -326,6 +327,8 @@ pub struct SolveApp { pub keymap: keymap::Keymap, /// The Help menu and the About window. pub help: help::HelpState, + /// Every status message of this run, for the Messages window ([`messages`], #2763). + pub messages: messages::Messages, /// An editable local issue draft and optional captured app frame. pub issue_report: issue_report::ReportState, /// The Crash Reports window. @@ -452,6 +455,7 @@ impl SolveApp { sbox: shortcut_box::ShortcutBox::default(), keymap: keymap::Keymap::default(), help: help::HelpState::default(), + messages: messages::Messages::default(), issue_report: issue_report::ReportState::default(), crashes: crash_ui::CrashUi::default(), updater: update::Updater::default(), @@ -1015,7 +1019,9 @@ impl SolveApp { } pub fn set_status(&mut self, s: impl Into, error: bool) { - self.status = Some((s.into(), now_ms(), error)); + let (text, at) = (s.into(), now_ms()); + self.messages.push(&text, error, at); + self.status = Some((text, at, error)); } pub fn open_path(&mut self, path: &str) { diff --git a/crates/ui-egui/src/messages.rs b/crates/ui-egui/src/messages.rs new file mode 100644 index 000000000..9447ae5a8 --- /dev/null +++ b/crates/ui-egui/src/messages.rs @@ -0,0 +1,203 @@ +//! Messages (#2763): every status message of this run, kept so it can be read and copied after +//! the status chip has faded. Help › Messages… and a click on the chip open the window; the +//! control channel reads them as `ui.messages`. + +use std::collections::VecDeque; + +use egui::{RichText, vec2}; +use serde_json::{Value, json}; + +use crate::SolveApp; +use crate::i18n::{format, tr}; +use crate::theme::Tokens; + +/// Messages kept (the oldest go first). +pub const KEEP: usize = 200; +/// The longest message kept, in characters (a longer one is cut, saying so). +const MAX_CHARS: usize = 4000; + +/// One status message. +#[derive(Clone, Debug, PartialEq)] +pub struct Message { + pub text: String, + pub error: bool, + /// When it last came (ms since the Unix epoch). + pub at: f64, + /// How many times in a row it came. + pub count: u32, +} + +#[derive(Default)] +pub struct Messages { + /// Oldest first. + list: VecDeque, + /// The window is open. + pub open: bool, +} + +impl Messages { + /// Keep a message: the same one again in a row counts up instead. + pub fn push(&mut self, text: &str, error: bool, at: f64) { + if let Some(last) = self.list.back_mut() + && last.text == text + && last.error == error + { + last.count = last.count.saturating_add(1); + last.at = at; + return; + } + let text = + if text.chars().count() > MAX_CHARS { format!("{}…", text.chars().take(MAX_CHARS).collect::()) } else { text.to_string() }; + self.list.push_back(Message { text, error, at, count: 1 }); + while self.list.len() > KEEP { + self.list.pop_front(); + } + } + + /// Oldest first. + pub fn iter(&self) -> impl DoubleEndedIterator + ExactSizeIterator { + self.list.iter() + } + + pub fn clear(&mut self) { + self.list.clear(); + } + + /// The messages as text, oldest first, one per line: how long ago, `error:` for errors, the + /// text and the repeat count. + pub fn as_text(&self, now: f64) -> String { + self.list.iter().map(|m| format!("{}\t{}", ago(now, m.at), line(m))).collect::>().join("\n") + } +} + +/// A message as one line: `error:` for errors, and `(×n)` when it came more than once. +fn line(m: &Message) -> String { + let repeats = if m.count > 1 { format!(" (×{})", m.count) } else { String::new() }; + format!("{}{}{repeats}", if m.error { "error: " } else { "" }, m.text) +} + +/// How long ago `at` was, at `now` (both ms): seconds, minutes or hours. +fn ago(now: f64, at: f64) -> String { + let s = ((now - at) / 1000.0).max(0.0).floor(); + let (id, n) = if s < 60.0 { + ("messages.ago_s", s) + } else if s < 3600.0 { + ("messages.ago_min", (s / 60.0).floor()) + } else { + ("messages.ago_h", (s / 3600.0).floor()) + }; + format(id, &[("n", &format!("{n:.0}"))]) +} + +/// `ui.messages`: `clear?: true` empties the list, `open?: bool` shows or hides the window; the +/// reply lists them, oldest first (`text`, `error`, `at` in ms since the epoch, `count`). +pub fn control(app: &mut SolveApp, p: &Value) -> Value { + if p.get("clear").and_then(Value::as_bool) == Some(true) { + app.messages.clear(); + } + if let Some(open) = p.get("open").and_then(Value::as_bool) { + app.messages.open = open; + } + let list: Vec = app.messages.iter().map(|m| json!({"text": m.text, "error": m.error, "at": m.at, "count": m.count})).collect(); + json!({ "messages": list, "open": app.messages.open }) +} + +/// The Messages window. +pub fn show(app: &mut SolveApp, ctx: &egui::Context) { + if !app.messages.open { + return; + } + let t = Tokens::get(); + let now = crate::now_ms(); + let mut open = true; + crate::frame::window(ctx, tr("messages.title"), crate::frame::Width::Normal) + .id(egui::Id::new("sc_messages")) + .open(&mut open) + .default_size(vec2(460.0, 360.0)) + .show(ctx, |ui| { + ui.horizontal(|ui| { + let copy = ui.add_enabled(app.messages.iter().len() > 0, egui::Button::new(tr("messages.copy_all"))); + crate::scenario::publish_handle("messages:copy", copy.rect.center()); + if copy.clicked() { + ctx.copy_text(app.messages.as_text(now)); + } + let clear = ui.add_enabled(app.messages.iter().len() > 0, egui::Button::new(tr("messages.clear"))); + crate::scenario::publish_handle("messages:clear", clear.rect.center()); + if clear.clicked() { + app.messages.clear(); + } + }); + ui.separator(); + if app.messages.iter().len() == 0 { + ui.label(RichText::new(tr("messages.none")).color(t.text_dim)); + return; + } + egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { + for m in app.messages.iter().rev() { + ui.horizontal_top(|ui| { + ui.add_sized(vec2(70.0, 14.0), egui::Label::new(RichText::new(ago(now, m.at)).small().color(t.text_dim))); + let text = RichText::new(line(m)).color(if m.error { t.error } else { t.text }); + ui.add(egui::Label::new(text).wrap().selectable(true)); + }); + } + }); + }); + if !open { + app.messages.open = false; + } + // The ages tick on while it is open. + ctx.request_repaint_after(std::time::Duration::from_secs(1)); +} + +#[cfg(test)] +mod tests { + use super::{KEEP, Messages}; + + #[test] + fn repeats_count_up_and_the_oldest_go_past_the_limit() { + let mut m = Messages::default(); + m.push("Box done", false, 1000.0); + m.push("Box done", false, 2000.0); + m.push("`face` is required", true, 3000.0); + let got: Vec<(&str, bool, u32)> = m.iter().map(|x| (x.text.as_str(), x.error, x.count)).collect(); + assert_eq!(got, [("Box done", false, 2), ("`face` is required", true, 1)]); + assert_eq!(m.as_text(63_000.0), "1 min ago\tBox done (×2)\n1 min ago\terror: `face` is required"); + for i in 0..KEEP + 5 { + m.push(&format!("message {i}"), false, 0.0); + } + assert_eq!(m.iter().len(), KEEP); + assert_eq!(m.iter().next().map(|x| x.text.as_str()), Some("message 5"), "the oldest went first"); + } + + #[test] + fn a_very_long_message_is_cut() { + let mut m = Messages::default(); + m.push(&"x".repeat(10_000), true, 0.0); + assert_eq!(m.iter().next().map(|x| x.text.chars().count()), Some(4001)); + } + + /// Status messages land in the list, a click on the chip and Help › Messages… open the window, + /// and `ui.messages` reads, opens and clears it. + #[test] + fn status_messages_are_kept_and_the_window_opens() { + use serde_json::json; + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.app.set_status("STEP export needs a solid body", true); + h.app.set_status("Box done", false); + h.frames(2); + let chip = crate::scenario::handle_at("status:chip").expect("the chip is drawn"); + h.call("ui.click", json!({"x": chip.x, "y": chip.y})); + h.frames(2); + assert!(h.app.messages.open, "a click on the chip opens the messages"); + assert!(crate::scenario::handle_at("messages:copy").is_some()); + let out = h.call("ui.messages", json!({})); + let texts: Vec<&str> = out["result"]["messages"].as_array().into_iter().flatten().filter_map(|m| m["text"].as_str()).collect(); + assert_eq!(texts, ["STEP export needs a solid body", "Box done"], "{out}"); + assert_eq!(out["result"]["messages"][0]["error"], true); + let out = h.call("ui.messages", json!({"clear": true, "open": false})); + assert_eq!((out["result"]["messages"].as_array().map(Vec::len), out["result"]["open"].as_bool()), (Some(0), Some(false))); + crate::help::run(&mut h.app, &h.ctx.clone(), "messages"); + assert!(h.app.messages.open, "Help › Messages… opens it too"); + } +} diff --git a/crates/ui-egui/src/select_other.rs b/crates/ui-egui/src/select_other.rs index e40f40aca..bbe3f07e3 100644 --- a/crates/ui-egui/src/select_other.rs +++ b/crates/ui-egui/src/select_other.rs @@ -297,7 +297,7 @@ pub fn open(app: &mut SolveApp, at: Pos2) -> bool { fn open_with(app: &mut SolveApp, proj: &Proj, at: Pos2) -> bool { let (rows, total) = rows_capped(app, proj, at); if rows.is_empty() { - app.status = Some(("Nothing to select here".into(), crate::now_ms(), false)); + app.set_status("Nothing to select here", false); return false; } close(app); @@ -488,7 +488,7 @@ pub fn cycle_click(app: &mut SolveApp, proj: &Proj, at: Pos2) -> bool { let next = rows.iter().position(|r| crate::selection::same_item(&r.sel, &c.chosen)).map_or(0, |k| (k + 1) % rows.len()); let Some(row) = rows.get(next).cloned() else { return false }; apply(app, &row, false); - app.status = Some((format!("{} ({} of {})", row.label, next + 1, rows.len()), crate::now_ms(), false)); + app.set_status(format!("{} ({} of {})", row.label, next + 1, rows.len()), false); remember(app, c.at, Some(row.sel)); true } diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index b36560580..8ee4c5f44 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -2831,6 +2831,11 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { let r = Rect::from_min_size(pos, galley.size() + vec2(16.0, 8.0)); painter.rect_filled(r, 4.0, t.overlay); painter.galley(pos + vec2(8.0, 4.0), galley, t.text); + // A click opens every message of the run, to read and copy (#2763). + crate::scenario::publish_handle("status:chip", r.center()); + if ui.interact(r, egui::Id::new("sc_status_chip"), Sense::click()).on_hover_text(crate::i18n::tr("messages.chip_hint")).clicked() { + app.messages.open = true; + } ui.ctx().request_repaint_after(std::time::Duration::from_millis(500)); } else { app.status = None; diff --git a/docs/book/src/guide/ui-tour.md b/docs/book/src/guide/ui-tour.md index d2aa5f2a6..c407e9561 100644 --- a/docs/book/src/guide/ui-tour.md +++ b/docs/book/src/guide/ui-tour.md @@ -63,6 +63,7 @@ Preferences (File › Preferences) hold the theme, the units of new designs, the visual style and autosave. Graphics › Colour vision gives the colours that carry a meaning (sketch states, axes, bends, analyses, icons) values for a weak red, green or blue sense: Protan, Deutan or Tritan. In a mode, the faces Draft and Accessibility Analysis mark as failing are striped too. +Command messages and errors show for a few seconds in the status chip at the bottom left of the view. Click the chip, or choose Help › **Messages…**, for every message of the session: newest first, errors in red, each line selectable, with **Copy all** for a bug report. Help › Keyboard Shortcuts lists every key, and File › Keyboard Shortcuts changes them. diff --git a/docs/control-protocol.md b/docs/control-protocol.md index b5726d1f1..57281fe09 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -147,6 +147,7 @@ labels; `prefs:measure_axis_distances` identifies the checkbox. | `ui.screenshot` | `path?` | PNG of the window (needs a presented frame: a minimised or fully covered window answers at once with `hidden: true` and an error; use `ui.render`) | | `ui.render` | `path`, `width?`, `height?`, `grid?`, `axes?` | Render of the model with the current camera (no window needed), drawn on the app's GPU device with the viewport's pipelines (the reply's `renderer`: `gpu`, or `gpu-software` on a software adapter), in the window's theme (light or dark; `solidcraft-cli snapshot` keeps the light colours); cut by the section the viewport shows (`inspect.section`, an open Section Analysis dialog's preview, a sketch's Slice), with the cut face capped. The ground grid and the origin's axes are drawn as the window shows them (`ui.set` `showGrid` and `showOrigin`, `hiddenOrigin`); `grid` and `axes` (booleans) say otherwise for this render | | `ui.confirm` | `accept?`: bool | answers the Delete confirmation (shown when a delete takes other features with it or makes some fail); without `accept`, what it lists | +| `ui.messages` | `clear?`: `true` (empty the list), `open?`: bool (show or hide the Messages window) | every status message of this run, oldest first (the last 200; a message repeated in a row is one entry with a `count`): `messages` `[{text, error, at, count}]` (`at` in ms since the Unix epoch), and whether the window is `open` (#2763) | | `ui.documents` | `action?`: `new`, `switch`, `close`, `quit`; `index?`; `force?` (close without asking); `answer?`: `save`, `dont_save`, `cancel` (answers "save changes?") | the open designs (tabs): names, unsaved flags, the active one, a pending "save changes?" prompt, whether a quit is asking | | `ui.file` | `path`; `insert?`: bool | starts an interactive background Open or Insert; poll `ui.inspect.file_busy` for completion; the window stays responsive | | `ui.home` | `open?`: bool; `sample?`: index | the start page: show or hide it, open a built-in sample (once built); returns `open` and the recent designs | From 771f62be712429971ecd6453f665f5b8191cb65f Mon Sep 17 00:00:00 2001 From: SS-EN <84559909+SS-EN@users.noreply.github.com> Date: Mon, 19 Oct 2026 09:14:52 -0400 Subject: [PATCH 058/225] Interference: clear apart pairs from their meshes, intersect the rest in parallel, time budget (#2895) Thanks @SS-EN. --- crates/engine/src/cmd/interference.rs | 439 ++++++++++++++++++++ crates/engine/src/cmd/interference_tests.rs | 110 +++++ crates/engine/src/cmd/joints.rs | 61 +-- crates/engine/src/cmd/mod.rs | 1 + crates/kernel/src/lib.rs | 2 +- crates/kernel/src/measure.rs | 109 ++++- crates/kernel/src/profile.rs | 28 ++ docs/book/src/guide/assemblies.md | 5 +- 8 files changed, 681 insertions(+), 74 deletions(-) create mode 100644 crates/engine/src/cmd/interference.rs create mode 100644 crates/engine/src/cmd/interference_tests.rs diff --git a/crates/engine/src/cmd/interference.rs b/crates/engine/src/cmd/interference.rs new file mode 100644 index 000000000..06c5c1bfc --- /dev/null +++ b/crates/engine/src/cmd/interference.rs @@ -0,0 +1,439 @@ +//! Interference (`inspect.interference`): the pairs of bodies that share volume, and how much. +//! +//! Pairs are pruned in three steps before anything exact runs. Their boxes first (sort and +//! sweep), then their display meshes: a mesh lies within its chord tolerance of the faces, so +//! two meshes farther apart than a margin over both tolerances belong to bodies whose boundaries +//! don't meet, and unless one body sits inside the other (a point of each face of one tested +//! against the other's mesh) the pair is clear without a boolean. The pairs left are intersected +//! exactly and measured, in parallel on desktop (one after another in the browser), the slowest +//! first, under a time budget: pairs not finished when it runs out are listed as not checked +//! rather than holding the call. The shared part is measured as `solidcraft_kernel::measure` +//! measures it (its mass properties alone). + +use std::collections::HashSet; +use std::sync::Arc; + +use serde_json::{Value, json}; +use solidcraft_geom::mesh_distance::TriangleSet; +use solidcraft_geom::{Aabb3, Mesh, Vec3}; +use solidcraft_kernel::Body; +use solidcraft_kernel::profile::KernelTimes; + +use crate::params::{bad, num, string_list}; +use crate::{Result, Session}; + +/// Most pairs with overlapping bounding boxes one call intersects. +pub(crate) const MAX_INTERFERENCE_PAIRS: usize = 20_000; +/// The time budget when the call gives none (s): under the 300 s an MCP client waits for a tool. +pub(crate) const DEFAULT_BUDGET_S: f64 = 240.0; +/// The longest time budget a call may ask for (s). +const MAX_BUDGET_S: f64 = 86_400.0; +/// How many chord tolerances apart (of both meshes together) two meshes must be to clear a pair +/// without intersecting it: twice what the tolerances allow, for meshers that sag a little more. +const MESH_MARGIN: f64 = 4.0; +/// Most pairs listed under `slowest`. +const SLOWEST: usize = 8; + +/// One pair to intersect exactly: the bodies (cheap clones sharing the solids) and their names. +struct Job { + pair: usize, + a: Body, + b: Body, + names: (String, String), + /// Faces of one times faces of the other: the slowest pairs start first. + cost: usize, +} + +/// What an exact check of one pair came to. +enum Outcome { + Hit(Value), + Clear, + Unchecked(String), +} + +/// One pair's answer and where its time went. +struct Done { + outcome: Outcome, + /// Unverified boolean results are listed as unchecked and still reported as a hit. + note: Option, + ms: f64, + kernel: KernelTimes, +} + +pub(super) fn interference(s: &mut Session, p: &Value) -> Result { + let cmd = "inspect.interference"; + let started = web_time::Instant::now(); + let budget_s = match p.get("budget_s") { + None | Some(Value::Null) => DEFAULT_BUDGET_S, + Some(_) => match num(p, "budget_s") { + Some(v) if v > 0.0 && v <= MAX_BUDGET_S => v, + _ => return Err(bad(cmd, format!("`budget_s` must be a number of seconds above 0, at most {MAX_BUDGET_S}"))), + }, + }; + let budget = std::time::Duration::from_secs_f64(budget_s); + let want = string_list(p, "bodies"); + let st = s.world_state(); + let bodies: Vec<&solidcraft_doc::ModelBody> = + st.bodies.iter().filter(|b| want.is_empty() || want.contains(&b.name)).filter(|b| !b.body.is_mesh()).collect(); + + // The bodies' display meshes, made once (in parallel) and kept on the bodies: a design open + // in the app has them already. + let meshes: Vec> = { + let made = solidcraft_kernel::map_with_local_pools(&bodies, usize::MAX, |b| Ok(b.mesh())); + made.into_iter().map(|m| m.unwrap_or_default()).collect() + }; + // Prune by bounding boxes first (sort and sweep), so the cost follows the pairs that can + // touch rather than the square of the body count. + // Each mesh lies within its chord of the faces, inside a round one: grown by that, the boxes + // of bodies a hundredth of a millimetre into each other still meet (an arm's round end into a + // rounded rim, its facets clear of the rim's). + let chords: Vec = bodies.iter().map(|b| b.display_tol()).collect(); + let boxes: Vec = meshes + .iter() + .zip(&chords) + .map(|(m, &chord)| { + let (bx, g) = (m.bounds(), 2.0 * chord); + if bx.is_empty() { bx } else { Aabb3 { min: bx.min - Vec3::new(g, g, g), max: bx.max + Vec3::new(g, g, g) } } + }) + .collect(); + let (pairs, skipped) = super::joints::overlapping_pairs(&boxes, MAX_INTERFERENCE_PAIRS); + + // Then by the meshes: pairs whose meshes stay apart (and neither holds the other) are clear. + let used: Vec = { + let mut u = vec![false; bodies.len()]; + for &(i, j) in &pairs { + for k in [i, j] { + if let Some(x) = u.get_mut(k) { + *x = true; + } + } + } + u + }; + let sets: Vec> = { + let idx: Vec = (0..bodies.len()).filter(|&i| used.get(i).copied().unwrap_or(false)).collect(); + let made = solidcraft_kernel::map_with_local_pools(&idx, usize::MAX, |&i| Ok(meshes.get(i).map(|m| TriangleSet::new(m)))); + let mut out: Vec> = std::iter::repeat_with(|| None).take(bodies.len()).collect(); + for (&i, set) in idx.iter().zip(made) { + if let (Some(slot), Ok(set)) = (out.get_mut(i), set) { + *slot = set; + } + } + out + }; + let need_exact = solidcraft_kernel::map_with_local_pools(&pairs, usize::MAX, |&(i, j)| { + let (Some(Some(sa)), Some(Some(sb)), Some(ma), Some(mb)) = (sets.get(i), sets.get(j), meshes.get(i), meshes.get(j)) else { + return Ok(true); + }; + let margin = MESH_MARGIN * (chords.get(i).copied().unwrap_or(0.0) + chords.get(j).copied().unwrap_or(0.0)); + Ok(!meshes_apart(ma, sa, mb, sb, margin)) + }); + let mut jobs = Vec::new(); + let mut cleared = 0usize; + for (k, (&(i, j), exact)) in pairs.iter().zip(need_exact).enumerate() { + if !exact.unwrap_or(true) { + cleared += 1; + continue; + } + let (Some(a), Some(b)) = (bodies.get(i), bodies.get(j)) else { continue }; + jobs.push(Job { + pair: k, + a: a.body.clone(), + b: b.body.clone(), + names: (a.name.clone(), b.name.clone()), + cost: a.body.face_count().saturating_mul(b.body.face_count()), + }); + } + let intersected = jobs.len(); + jobs.sort_by(|x, y| y.cost.cmp(&x.cost).then(x.pair.cmp(&y.pair))); + + let left = budget.saturating_sub(started.elapsed()); + let waited = web_time::Instant::now(); + let (done, threads) = run_jobs(jobs, left); + let waited_ms = waited.elapsed().as_secs_f64() * 1000.0; + + let (mut hits, mut unchecked, mut timed) = (Vec::new(), Vec::new(), Vec::new()); + let (mut not_checked, mut boolean_ms, mut tessellate_ms) = (0usize, 0.0, 0.0); + for ((a, b), d) in done { + let Some(d) = d else { + not_checked += 1; + unchecked.push(json!({"a": a, "b": b, "reason": format!("not checked: the time budget of {budget_s} s ran out (budget_s)")})); + continue; + }; + boolean_ms += d.kernel.boolean_ms; + tessellate_ms += d.kernel.tessellate_ms; + timed.push(( + d.ms, + json!({"a": a, "b": b, "ms": round_ms(d.ms), "boolean_ms": round_ms(d.kernel.boolean_ms), + "tessellate_ms": round_ms(d.kernel.tessellate_ms)}), + )); + if let Some(reason) = d.note { + unchecked.push(json!({"a": a, "b": b, "reason": reason})); + } + match d.outcome { + Outcome::Hit(v) => hits.push(v), + Outcome::Clear => {} + Outcome::Unchecked(reason) => unchecked.push(json!({"a": a, "b": b, "reason": reason})), + } + } + // A timing profile of the command (`--profile`) counts the kernel time the workers spent, + // shared out over the time this thread waited for them (on the calling thread it is counted + // already). + if threads > 0 && boolean_ms + tessellate_ms > 0.0 { + let share = (waited_ms / (boolean_ms + tessellate_ms)).min(1.0); + solidcraft_kernel::profile::credit(KernelTimes { boolean_ms: boolean_ms * share, tessellate_ms: tessellate_ms * share }); + } + timed.sort_by(|x, y| y.0.total_cmp(&x.0)); + let slowest: Vec = timed.into_iter().take(SLOWEST).map(|t| t.1).collect(); + Ok(json!({ + "interferences": hits, "count": hits.len(), "checked": bodies.len(), "unchecked": unchecked, + "truncated": skipped > 0, "skipped_pairs": skipped, + "pairs_candidate": pairs.len(), "pairs_cleared": cleared, "pairs_intersected": intersected, + "pairs_not_checked": not_checked, "budget_s": budget_s, "budget_exceeded": not_checked > 0, + "threads": threads, "boolean_ms": round_ms(boolean_ms), "tessellate_ms": round_ms(tessellate_ms), + "slowest": slowest, "ms": round_ms(started.elapsed().as_secs_f64() * 1000.0), + })) +} + +fn round_ms(ms: f64) -> f64 { + (ms * 1000.0).round() / 1000.0 +} + +/// Are two bodies' meshes farther apart than `margin` with neither body inside the other? Then +/// their boundaries don't meet (each mesh is within its chord tolerance of its faces, which the +/// margin covers), so the bodies share no volume. Conservative: an empty mesh, nested boxes or +/// a point of one inside the other answer no. +fn meshes_apart(ma: &Mesh, sa: &TriangleSet, mb: &Mesh, sb: &TriangleSet, margin: f64) -> bool { + if ma.triangles.is_empty() || mb.triangles.is_empty() || !margin.is_finite() { + return false; + } + if sa.closest(sb, margin).is_some() { + return false; + } + // Apart boundaries: either the bodies are apart, or one holds the other (or a piece of it). + let (ba, bb) = (ma.bounds(), mb.bounds()); + if nested(&ba, &bb) || nested(&bb, &ba) { + return false; + } + !(any_inside(&face_points(ma), mb) || any_inside(&face_points(mb), ma)) +} + +/// Is `inner` inside `outer`? +fn nested(inner: &Aabb3, outer: &Aabb3) -> bool { + !inner.is_empty() + && outer.min.x <= inner.min.x + && outer.min.y <= inner.min.y + && outer.min.z <= inner.min.z + && inner.max.x <= outer.max.x + && inner.max.y <= outer.max.y + && inner.max.z <= outer.max.z +} + +/// A corner of each face's first triangle (every piece of a body in several pieces has a face). +fn face_points(m: &Mesh) -> Vec { + let mut seen = HashSet::new(); + let mut out = Vec::new(); + for (k, t) in m.triangles.iter().enumerate() { + let face = m.tri_face.get(k).copied().unwrap_or(0); + if seen.insert(face) + && let Some(p) = m.positions.get(t[0] as usize) + { + out.push(*p); + } + } + out +} + +/// Is any of `points` inside the closed mesh `outer`? +fn any_inside(points: &[Vec3], outer: &Mesh) -> bool { + let b = outer.bounds(); + let within = |p: &&Vec3| b.min.x <= p.x && p.x <= b.max.x && b.min.y <= p.y && p.y <= b.max.y && b.min.z <= p.z && p.z <= b.max.z; + let candidates: Vec<&Vec3> = points.iter().filter(within).collect(); + match candidates.len() { + 0 => false, + 1..=4 => candidates.iter().any(|p| outer.contains(**p)), + _ => { + let index = outer.inside_index(); + candidates.iter().any(|p| index.contains(**p)) + } + } +} + +/// The exact check of one pair: a pin a hair off the axis of its hole by the walls' crescent, +/// otherwise the intersection measured. +fn check(job: &Job) -> Done { + let started = web_time::Instant::now(); + let ((outcome, note), kernel) = solidcraft_kernel::profile::capture(|| check_pair(&job.a, &job.b, &job.names)); + Done { outcome, note, ms: started.elapsed().as_secs_f64() * 1000.0, kernel } +} + +fn check_pair(a: &Body, b: &Body, (na, nb): &(String, String)) -> (Outcome, Option) { + let threshold = 1e-9 * a.size().max(1.0).powi(3); + // A pin a hair off the axis of its hole: the crescent the walls share, which the boolean + // can't intersect. + if let Some(o) = solidcraft_kernel::coaxial_overlap(a, b) { + if o.volume > threshold { + let hit = json!({"a": na, "b": nb, "volume_mm3": o.volume, "area_mm2": o.area, "center": o.centroid, + "bbox": {"min": o.bbox.min, "max": o.bbox.max}, "near_coaxial": {"offset_mm": o.offset, "length_mm": o.length}}); + return (Outcome::Hit(hit), None); + } + return (Outcome::Clear, None); + } + // A pair whose shared part can't be worked out is reported, not passed as clear. + let (shared, report) = solidcraft_kernel::capture_boolean_diagnostics(|| solidcraft_kernel::boolean(a, b, solidcraft_kernel::BoolOp::Intersect)); + let shared = match shared { + Ok(o) => o, + Err(e) => return (Outcome::Unchecked(e.to_string()), None), + }; + let mut note = report.unverified(); + let pieces = match shared { + Some(o) => vec![o], + // A body in several pieces, one of them wholly inside the other body: the whole bodies' + // boolean can come out empty, so the pieces are intersected one by one. + None if a.shell_count() > 1 || b.shell_count() > 1 => match by_pieces(a, b) { + Ok((pieces, unverified)) => { + note = note.or(unverified); + pieces + } + Err(e) => return (Outcome::Unchecked(e), note), + }, + None => return (Outcome::Clear, note), + }; + // The shared parts measured together: volumes and areas add, the centre is the volumes'. + let mut measured = Vec::new(); + for o in &pieces { + match solidcraft_kernel::measure_mass(o) { + Ok(m) => measured.push(m), + Err(e) => return (Outcome::Unchecked(e.to_string()), note), + } + } + let volume: f64 = measured.iter().map(|m| m.volume).sum(); + if volume > threshold { + let area: f64 = measured.iter().map(|m| m.area).sum(); + let bbox = measured.iter().fold(Aabb3::EMPTY, |b, m| b.union(&m.bbox)); + let center = match measured.as_slice() { + [m] => m.centroid, + _ => measured.iter().fold(Vec3::ZERO, |c, m| c + m.centroid * m.volume) / volume, + }; + let hit = json!({"a": na, "b": nb, "volume_mm3": volume, "area_mm2": area, "center": center, "bbox": {"min": bbox.min, "max": bbox.max}}); + return (Outcome::Hit(hit), note); + } + (Outcome::Clear, note) +} + +/// Most pairs of pieces [`by_pieces`] intersects. +const MAX_PIECE_PAIRS: usize = 256; + +/// The shared parts of two bodies, a piece of each at a time, and why any of them is unverified. +fn by_pieces(a: &Body, b: &Body) -> std::result::Result<(Vec, Option), String> { + let (la, lb) = (a.lumps().map_err(|e| e.to_string())?, b.lumps().map_err(|e| e.to_string())?); + if la.len() < 2 && lb.len() < 2 { + return Ok((Vec::new(), None)); + } + if la.len().saturating_mul(lb.len()) > MAX_PIECE_PAIRS { + return Err(format!("not checked: {} by {} pieces are more than {MAX_PIECE_PAIRS} pairs of pieces", la.len(), lb.len())); + } + let (mut out, mut note) = (Vec::new(), None); + for x in &la { + for y in &lb { + let (r, report) = + solidcraft_kernel::capture_boolean_diagnostics(|| solidcraft_kernel::boolean(x, y, solidcraft_kernel::BoolOp::Intersect)); + note = note.or(report.unverified()); + if let Some(o) = r.map_err(|e| e.to_string())? { + out.push(o); + } + } + } + Ok((out, note)) +} + +/// Each job's answer (in pair order, with the pair's names; `None`: not finished within +/// `budget`) and how many worker threads ran them (0: this thread did). +fn run_jobs(jobs: Vec, budget: std::time::Duration) -> (Vec<((String, String), Option)>, usize) { + let mut order: Vec<(usize, usize, (String, String))> = jobs.iter().enumerate().map(|(k, j)| (j.pair, k, j.names.clone())).collect(); + order.sort_unstable_by_key(|o| o.0); + let (mut results, threads) = run_ordered(jobs, budget); + let out = order.into_iter().map(|(_, k, names)| (names, results.get_mut(k).and_then(Option::take))).collect(); + (out, threads) +} + +/// Each job's answer in job order, and the threads used. On desktop the jobs run on worker +/// threads of their own, which the call does not wait for once `budget` is spent: a pair still +/// running then finishes in the background and is dropped (a kernel boolean can't be stopped +/// part way). +#[cfg(not(target_arch = "wasm32"))] +fn run_ordered(jobs: Vec, budget: std::time::Duration) -> (Vec>, usize) { + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + use std::sync::mpsc; + + let n = jobs.len(); + let mut out: Vec> = std::iter::repeat_with(|| None).take(n).collect(); + if n == 0 || budget.is_zero() { + return (out, 0); + } + let deadline = web_time::Instant::now() + budget; + // The workers outlive the call when the budget runs out, so they own what they work on. + let jobs = Arc::new(jobs); + let next = Arc::new(AtomicUsize::new(0)); + let stop = Arc::new(AtomicBool::new(false)); + let (tx, rx) = mpsc::channel::<(usize, Done)>(); + let want = std::thread::available_parallelism().map(usize::from).unwrap_or(1).min(n).max(1); + let mut threads = 0; + for _ in 0..want { + let (jobs, next, stop, tx) = (jobs.clone(), next.clone(), stop.clone(), tx.clone()); + let spawned = std::thread::Builder::new().name("solidcraft-interference".into()).spawn(move || { + while !stop.load(Ordering::Relaxed) { + let k = next.fetch_add(1, Ordering::Relaxed); + let Some(job) = jobs.get(k) else { break }; + let done = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| check(job))).unwrap_or_else(|_| Done { + outcome: Outcome::Unchecked("internal error while checking this pair".into()), + note: None, + ms: 0.0, + kernel: KernelTimes::default(), + }); + if tx.send((k, done)).is_err() { + break; + } + } + }); + if spawned.is_ok() { + threads += 1; + } + } + drop(tx); + if threads == 0 { + // No thread could be started: one pair after another here. + return (run_here(&jobs, deadline), 0); + } + let mut received = 0; + while received < n { + let left = deadline.saturating_duration_since(web_time::Instant::now()); + match rx.recv_timeout(left) { + Ok((k, done)) => { + if let Some(slot) = out.get_mut(k) { + *slot = Some(done); + } + received += 1; + } + // Out of time, or every worker gone (none is left with work then). + Err(_) => break, + } + } + stop.store(true, Ordering::Relaxed); + (out, threads) +} + +/// The browser has no threads: one pair after another, none started once the budget is spent. +#[cfg(target_arch = "wasm32")] +fn run_ordered(jobs: Vec, budget: std::time::Duration) -> (Vec>, usize) { + (run_here(&jobs, web_time::Instant::now() + budget), 0) +} + +/// The jobs one after another on this thread, none started past `deadline`. +fn run_here(jobs: &[Job], deadline: web_time::Instant) -> Vec> { + jobs.iter().map(|job| (web_time::Instant::now() < deadline).then(|| check(job))).collect() +} + +#[cfg(test)] +#[path = "interference_tests.rs"] +mod tests; diff --git a/crates/engine/src/cmd/interference_tests.rs b/crates/engine/src/cmd/interference_tests.rs new file mode 100644 index 000000000..9d65ee89a --- /dev/null +++ b/crates/engine/src/cmd/interference_tests.rs @@ -0,0 +1,110 @@ +//! `inspect.interference`: the mesh pre-filter, the bodies it must not clear, and the budget. + +use serde_json::{Value, json}; + +use crate::Session; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + match s.execute(id, &p) { + Ok(v) => v, + Err(e) => panic!("{id} {p}: {e}"), + } +} + +fn f(v: &Value) -> f64 { + v.as_f64().unwrap_or(f64::NAN) +} + +/// Curved bodies whose boxes overlap but which stay apart are answered from their meshes: no +/// boolean runs. Two cylinders on a diagonal (centres 12.7 mm apart, radii 5), and a torus +/// beside a sphere that sits in the corner of its box. +#[test] +fn separated_curved_bodies_are_cleared_without_a_boolean() { + let mut s = Session::default(); + run(&mut s, "solid.cylinder", json!({"radius": 5, "height": 10, "base": [0, 0, 0], "body_name": "C1"})); + run(&mut s, "solid.cylinder", json!({"radius": 5, "height": 10, "base": [9, 9, 0], "operation": "new", "body_name": "C2"})); + run(&mut s, "solid.torus", json!({"major": 20, "minor": 3, "center": [60, 0, 0], "body_name": "Torus"})); + // In the torus box's corner (the box reaches 23 out on each axis), 1.66 mm clear of the tube. + run(&mut s, "solid.sphere", json!({"radius": 3, "center": [80, 19, 1], "operation": "new", "body_name": "Ball"})); + let i = run(&mut s, "inspect.interference", json!({})); + assert_eq!(i["count"], 0, "{i}"); + assert_eq!(i["pairs_candidate"], 2, "{i}"); + assert_eq!(i["pairs_cleared"], 2, "{i}"); + assert_eq!(i["pairs_intersected"], 0, "{i}"); + assert_eq!(f(&i["boolean_ms"]), 0.0, "{i}"); + assert_eq!(i["unchecked"].as_array().map(Vec::len), Some(0), "{i}"); + // Moved into each other, the same pairs are intersected and overlap. + run(&mut s, "solid.cylinder", json!({"radius": 5, "height": 10, "base": [7, 0, 0], "operation": "new", "body_name": "C3"})); + let i = run(&mut s, "inspect.interference", json!({"bodies": ["C1", "C3"]})); + assert_eq!(i["count"], 1, "{i}"); + assert_eq!(i["pairs_intersected"], 1, "{i}"); + // The lens of two r5 circles 7 apart, 10 high. + let (r, d): (f64, f64) = (5.0, 7.0); + let lens = 2.0 * r * r * (d / (2.0 * r)).acos() - d / 2.0 * (4.0 * r * r - d * d).sqrt(); + let got = f(&i["interferences"][0]["volume_mm3"]); + assert!((got - 10.0 * lens).abs() < 1e-3 * 10.0 * lens, "{got} against {}: {i}", 10.0 * lens); +} + +/// A body wholly inside another has meshes that never meet: it is still intersected, and its +/// whole volume is the overlap. +#[test] +fn a_body_inside_another_is_still_found() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 40, "width": 40, "height": 40, "corner": [-20, -20, -20], "body_name": "Block"})); + run(&mut s, "solid.sphere", json!({"radius": 5, "center": [3, -2, 1], "operation": "new", "body_name": "Ball"})); + let i = run(&mut s, "inspect.interference", json!({})); + assert_eq!(i["count"], 1, "{i}"); + assert_eq!(i["pairs_cleared"], 0, "{i}"); + let want = 4.0 / 3.0 * std::f64::consts::PI * 125.0; + let got = f(&i["interferences"][0]["volume_mm3"]); + assert!((got - want).abs() < 1e-3 * want, "{got} against {want}: {i}"); +} + +/// A body in two pieces, one of them wholly inside a block and the other outside it: the boxes +/// are not nested and the meshes never meet, but a point of the inner piece's faces is inside +/// the block, so the pair is intersected. The whole bodies' boolean comes out empty there, so +/// the pieces are intersected one by one. +#[test] +fn a_piece_of_a_body_inside_another_is_still_found() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 20, "width": 20, "height": 20, "corner": [0, 0, 0], "body_name": "Block"})); + run(&mut s, "solid.box", json!({"length": 2, "width": 2, "height": 2, "corner": [5, 5, 5], "operation": "new", "body_name": "Pieces"})); + run(&mut s, "solid.box", json!({"length": 2, "width": 2, "height": 2, "corner": [30, 5, 5], "operation": "join", "targets": ["Pieces"]})); + let st = s.world_state(); + let pieces = st.bodies.iter().find(|b| b.name == "Pieces").map(|b| b.body.shell_count()); + assert_eq!(pieces, Some(2), "the two cubes are one body in two pieces"); + let i = run(&mut s, "inspect.interference", json!({})); + assert_eq!(i["count"], 1, "{i}"); + assert_eq!(i["pairs_cleared"], 0, "{i}"); + assert!((f(&i["interferences"][0]["volume_mm3"]) - 8.0).abs() < 1e-6, "{i}"); +} + +/// A budget spent before any pair could start lists every pair as not checked (and the call +/// returns); bad budgets are refused. +#[test] +fn pairs_left_when_the_budget_runs_out_are_listed_not_checked() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [0, 0, 0], "body_name": "A"})); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [5, 0, 0], "operation": "new", "body_name": "B"})); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [12, 0, 0], "operation": "new", "body_name": "C"})); + let i = run(&mut s, "inspect.interference", json!({"budget_s": 1e-12})); + assert_eq!(i["count"], 0, "{i}"); + assert_eq!(i["budget_exceeded"], true, "{i}"); + assert_eq!(i["pairs_not_checked"], 2, "{i}"); + let unchecked = i["unchecked"].as_array().cloned().unwrap_or_default(); + assert_eq!(unchecked.len(), 2, "{i}"); + assert!(unchecked.iter().all(|u| u["reason"].as_str().is_some_and(|r| r.starts_with("not checked") && r.contains("time budget"))), "{i}"); + // The default budget checks both pairs: 500 and 300 mm³. + let i = run(&mut s, "inspect.interference", json!({})); + assert_eq!(i["budget_exceeded"], false, "{i}"); + assert_eq!(i["budget_s"], 240.0, "{i}"); + assert_eq!(i["count"], 2, "{i}"); + let mut v: Vec = i["interferences"].as_array().into_iter().flatten().map(|h| f(&h["volume_mm3"])).collect(); + v.sort_by(f64::total_cmp); + assert!((v[0] - 300.0).abs() < 1e-6 && (v[1] - 500.0).abs() < 1e-6, "{i}"); + // Answers come in pair order whatever order they finished in. + assert_eq!((i["interferences"][0]["a"].as_str(), i["interferences"][0]["b"].as_str()), (Some("A"), Some("B")), "{i}"); + for bad in [json!(0), json!(-1), json!("soon"), json!(f64::MAX), json!(1e6)] { + assert!(s.execute("inspect.interference", &json!({"budget_s": bad})).is_err(), "{bad}"); + } +} diff --git a/crates/engine/src/cmd/joints.rs b/crates/engine/src/cmd/joints.rs index 2dbe97540..aca98ef1d 100644 --- a/crates/engine/src/cmd/joints.rs +++ b/crates/engine/src/cmd/joints.rs @@ -12,7 +12,7 @@ use solidcraft_doc::joints::{self, Coupling, Joint, JointExprs, JointKind, Joint use solidcraft_geom::{Aabb3, Vec3}; use super::CommandSpec; -use crate::params::{bad, bool_, num, str_, string_list, vec3}; +use crate::params::{bad, bool_, num, str_, vec3}; use crate::{EngineError, Result, Session}; pub static COMMANDS: &[CommandSpec] = &[ @@ -77,8 +77,8 @@ pub static COMMANDS: &[CommandSpec] = &[ (joint chains joined to nothing grounded: the solver places none of them, so driving them moves nothing)", ), CommandSpec::new("joint.solve", "Solve Joints", solve_cmd).icon("compute").params("re-place the occurrences from the joints → conflicts, errors, dof"), - CommandSpec::new("inspect.interference", "Interference", interference).at("SOLID", "INSPECT").icon("interference").noundo().params( - "bodies?: [names] (default: all, in world placement) → interferences: pairs that overlap with the overlap volume, area, bounding box and centre (a pin a hair off the axis of a hole of its size also has near_coaxial: {offset_mm, length_mm}, its volume the crescent the walls share); unchecked: pairs that could not be checked, with the reason. Bodies are pruned by bounding box first, so any number of bodies is fine; at most 20000 pairs whose boxes overlap are intersected per call (truncated: true and skipped_pairs: n say when more were left out)", + CommandSpec::new("inspect.interference", "Interference", super::interference::interference).at("SOLID", "INSPECT").icon("interference").noundo().params( + "bodies?: [names] (default: all, in world placement); budget_s?: seconds (default 240, at most 86400: pairs not finished by then are listed in unchecked as \"not checked: the time budget … ran out\" and the call returns) → interferences: pairs that overlap with the overlap volume, area, bounding box and centre (a pin a hair off the axis of a hole of its size also has near_coaxial: {offset_mm, length_mm}, its volume the crescent the walls share); unchecked: pairs that could not be checked, with the reason. Bodies are pruned by bounding box first, then by their display meshes (pairs whose meshes stay apart by more than their chord tolerances, neither inside the other, are clear without a boolean), so any number of bodies is fine; the pairs left are intersected exactly, in parallel on desktop, the slowest first; at most 20000 pairs whose boxes overlap are intersected per call (truncated: true and skipped_pairs: n say when more were left out). Also: pairs_candidate (boxes overlap), pairs_cleared (by the meshes), pairs_intersected, pairs_not_checked, budget_exceeded, threads (worker threads; 0: on the calling thread), boolean_ms and tessellate_ms (kernel time summed over the pairs), slowest: [{a, b, ms, boolean_ms, tessellate_ms}] and ms", ), ]; @@ -1320,61 +1320,6 @@ fn solve_cmd(s: &mut Session, p: &Value) -> Result { Ok(sol_json(&sol, p)) } -fn interference(s: &mut Session, p: &Value) -> Result { - let want = string_list(p, "bodies"); - let st = s.world_state(); - let bodies: Vec<&solidcraft_doc::ModelBody> = - st.bodies.iter().filter(|b| want.is_empty() || want.contains(&b.name)).filter(|b| !b.body.is_mesh()).collect(); - // Prune by bounding boxes first (sort and sweep), so the cost follows the pairs that can - // touch rather than the square of the body count. - let boxes: Vec = bodies.iter().map(|b| b.mesh().bounds()).collect(); - let (pairs, skipped) = overlapping_pairs(&boxes, MAX_INTERFERENCE_PAIRS); - let (mut hits, mut unchecked) = (Vec::new(), Vec::new()); - for (i, j) in pairs { - let (Some(a), Some(b)) = (bodies.get(i), bodies.get(j)) else { continue }; - let threshold = 1e-9 * a.body.size().max(1.0).powi(3); - // A pin a hair off the axis of its hole: the crescent the walls share, which the - // boolean can't intersect. - if let Some(o) = solidcraft_kernel::coaxial_overlap(&a.body, &b.body) { - if o.volume > threshold { - hits.push(json!({"a": a.name, "b": b.name, "volume_mm3": o.volume, "area_mm2": o.area, "center": o.centroid, - "bbox": {"min": o.bbox.min, "max": o.bbox.max}, "near_coaxial": {"offset_mm": o.offset, "length_mm": o.length}})); - } - continue; - } - // A pair whose shared part can't be worked out is reported, not passed as clear. - let (shared, report) = - solidcraft_kernel::capture_boolean_diagnostics(|| solidcraft_kernel::boolean(&a.body, &b.body, solidcraft_kernel::BoolOp::Intersect)); - let mut skip = |reason: String| unchecked.push(json!({"a": a.name, "b": b.name, "reason": reason})); - let shared = match shared { - Ok(o) => o, - Err(e) => { - skip(e.to_string()); - continue; - } - }; - if let Some(reason) = report.unverified() { - skip(reason); - } - let Some(o) = shared else { continue }; - let m = match solidcraft_kernel::measure(&o) { - Ok(m) => m, - Err(e) => { - skip(e.to_string()); - continue; - } - }; - if m.volume > threshold { - hits.push(json!({"a": a.name, "b": b.name, "volume_mm3": m.volume, "area_mm2": m.area, "center": m.centroid, "bbox": {"min": m.bbox.min, "max": m.bbox.max}})); - } - } - Ok(json!({"interferences": hits, "count": hits.len(), "checked": bodies.len(), "unchecked": unchecked, - "truncated": skipped > 0, "skipped_pairs": skipped})) -} - -/// Most pairs with overlapping bounding boxes `inspect.interference` intersects in one call. -const MAX_INTERFERENCE_PAIRS: usize = 20_000; - /// Index pairs `(i, j)`, `i < j`, whose boxes overlap or touch (sort and sweep along X), at most /// `limit` of them, plus how many more there were. pub(crate) fn overlapping_pairs(boxes: &[Aabb3], limit: usize) -> (Vec<(usize, usize)>, usize) { diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index e0a4e34e8..d02c97148 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -39,6 +39,7 @@ mod component_link; mod config; mod file; mod inspect; +mod interference; pub(crate) mod joints; mod libraries; mod material_properties; diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rs index 429634378..055584995 100644 --- a/crates/kernel/src/lib.rs +++ b/crates/kernel/src/lib.rs @@ -176,7 +176,7 @@ pub use iges_out::iges_export_bodies; pub use lip::raise_band; pub use loft_blend::loft_blend; pub use matchsurf::{match_surface, seam_continuity}; -pub use measure::{BodyMeasure, measure}; +pub use measure::{BodyMeasure, MassMeasure, measure, measure_mass}; pub use mesh_convert::convert_prismatic_mesh; pub use meshbody::{MAX_TRIANGLES, mesh_body}; pub use native::{decode_native_body, encode_native_body, native_preview_mesh}; diff --git a/crates/kernel/src/measure.rs b/crates/kernel/src/measure.rs index 0f2e2e78a..febcf6f79 100644 --- a/crates/kernel/src/measure.rs +++ b/crates/kernel/src/measure.rs @@ -55,6 +55,16 @@ fn min_edge_radius(m: &Mesh) -> Option { best } +/// Volume, area, centre and box of a body, as [`measure`] works them out, without the topology +/// counts (and the tessellation they take). +#[derive(Clone, Copy, Debug, Serialize)] +pub struct MassMeasure { + pub volume: f64, + pub area: f64, + pub centroid: Vec3, + pub bbox: Aabb3, +} + /// Measure a body from a fine tessellation (chord tolerance 5e-5 of the body size, finer for /// small radii down to 5e-6). Faces whose fine tessellation disagrees with a coarse one (a /// meshing failure) use the coarse result. @@ -78,14 +88,69 @@ pub fn measure(b: &Body) -> Result { merged, }); } + let (m, topo) = mass(b, true)?; + let topo = match topo { + Some(t) => t, + None => b.tessellate((b.size() * 1e-3).max(1e-3))?, + }; + Ok(BodyMeasure { + volume: m.volume, + area: m.area, + centroid: m.centroid, + bbox: m.bbox, + faces: b.face_count(), + edges: b.edge_count(), + vertices: b.vertex_count(), + shells: b.shell_count(), + merged: merged_topology(b, &topo)?, + }) +} + +/// [`measure`]'s volume, area, centre and box alone: the same numbers, a tessellation fewer +/// (for callers that need no topology counts, such as an interference check). +pub fn measure_mass(b: &Body) -> Result { + if b.triangle_mesh().is_some() { + let m = measure(b)?; + return Ok(MassMeasure { volume: m.volume, area: m.area, centroid: m.centroid, bbox: m.bbox }); + } + Ok(mass(b, false)?.0) +} + +/// The mass properties of a B-rep body from three tessellations: a coarse one (which sets how +/// fine the others go), then a fine and a medium one at once on desktop (one after the other +/// in the browser). With `topology`, also the coarse unrefined mesh the topology counts take, +/// made alongside them. +fn mass(b: &Body, topology: bool) -> Result<(MassMeasure, Option)> { let size = b.size(); - let coarse = b.tessellate_with((size * 1e-3).max(1e-3), true)?; + let coarse_tol = (size * 1e-3).max(1e-3); + let coarse = b.tessellate_with(coarse_tol, true)?; // Chord error relative to a radius sets the volume error: keep it near 3e-4 of the // smallest radius (thin tubes, small fillets). let tight = min_edge_radius(&coarse).map(|r| r * 3e-4).unwrap_or(f64::INFINITY); let fine_tol = (size * 5e-5).min(tight).max(size * 5e-6).max(1e-4); - let fine = b.tessellate_with(fine_tol, true)?; - let medium = b.tessellate_with((fine_tol * 5.0).max(2e-4), true)?; + let mut jobs = vec![(fine_tol, true), ((fine_tol * 5.0).max(2e-4), true)]; + if topology { + jobs.push((coarse_tol, false)); + } + // Independent tessellations of one body: each on its own thread, the calling thread's + // profile counting their wall time once as tessellation. Not from inside a worker pool: a + // pool thread blocked on threads of its own could leave their meshing (which runs on the + // shared pool) without a worker. + #[cfg(not(target_arch = "wasm32"))] + let threads = if rayon::current_thread_index().is_none() { jobs.len() } else { 1 }; + #[cfg(target_arch = "wasm32")] + let threads = 1; + let made = crate::profile::timed(crate::profile::Kind::Tessellate, || { + crate::par::map_on_threads(&jobs, threads, |&(tol, refine)| b.tessellate_with(tol, refine)) + }); + let mut made = made.into_iter().map(|m| m.unwrap_or_else(|| Err(crate::KernelError::Internal("tessellation failed".into())))); + let missing = || crate::KernelError::Internal("tessellation missing".into()); + let fine = made.next().ok_or_else(missing)??; + let medium = made.next().ok_or_else(missing)??; + let topo = match made.next() { + Some(m) => Some(m?), + None => None, + }; let nf = b.face_count(); let (sf, sm, sc) = (face_sums(&fine, nf), face_sums(&medium, nf), face_sums(&coarse, nf)); let close = |x: f64, y: f64| (x - y).abs() <= 0.01 * x.abs().max(y.abs()) + 1e-9; @@ -105,15 +170,31 @@ pub fn measure(b: &Body) -> Result { } let volume = v6 / 6.0; let centroid = if v6.abs() > 1e-12 { mom / (4.0 * v6) } else { fine.bounds().center() }; - Ok(BodyMeasure { - volume, - area, - centroid, - bbox: coarse.bounds().union(&fine.bounds()), - faces: b.face_count(), - edges: b.edge_count(), - vertices: b.vertex_count(), - shells: b.shell_count(), - merged: merged_topology(b, &b.tessellate((size * 1e-3).max(1e-3))?)?, - }) + Ok((MassMeasure { volume, area, centroid, bbox: coarse.bounds().union(&fine.bounds()) }, topo)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{BoolOp, boolean, cylinder, torus}; + + /// The mass properties alone are [`measure`]'s, to the bit, with the tessellations made at + /// once; and on a curved intersection they are the textbook ones. + #[test] + fn mass_alone_is_the_full_measure() { + let ring = torus(Vec3::ZERO, 10.0, 2.0).unwrap(); + let post = cylinder(Vec3::new(10.0, 0.0, -5.0), Vec3::Z, 1.5, 10.0).unwrap(); + let shared = boolean(&ring, &post, BoolOp::Intersect).unwrap().unwrap(); + for b in [&ring, &shared] { + let (full, mass) = (measure(b).unwrap(), measure_mass(b).unwrap()); + assert_eq!(full.volume.to_bits(), mass.volume.to_bits()); + assert_eq!(full.area.to_bits(), mass.area.to_bits()); + assert_eq!(full.centroid, mass.centroid); + assert_eq!((full.bbox.min, full.bbox.max), (mass.bbox.min, mass.bbox.max)); + } + let want = 2.0 * std::f64::consts::PI.powi(2) * 10.0 * 4.0; + let got = measure_mass(&ring).unwrap().volume; + assert!((got - want).abs() < 1e-3 * want, "{got} against {want}"); + assert!(measure(&ring).unwrap().merged.faces > 0); + } } diff --git a/crates/kernel/src/profile.rs b/crates/kernel/src/profile.rs index 5d1cea894..bd40bd499 100644 --- a/crates/kernel/src/profile.rs +++ b/crates/kernel/src/profile.rs @@ -59,6 +59,21 @@ pub fn capture(f: impl FnOnce() -> T) -> (T, KernelTimes) { (r, times) } +/// Count kernel time spent on other threads for this thread's running capture (when one runs +/// and no timed call does): work this thread handed out and waited for. The caller keeps the +/// sum within the wall time it waited, so the totals still never pass what the command took. +pub fn credit(times: KernelTimes) { + let ok = |x: f64| if x.is_finite() && x > 0.0 { x } else { 0.0 }; + STATE.with(|s| { + let mut st = s.get(); + if st.on && !st.busy { + st.times.boolean_ms += ok(times.boolean_ms); + st.times.tessellate_ms += ok(times.tessellate_ms); + s.set(st); + } + }); +} + /// Time `f` as `kind` when a capture is running and no timed call is. pub(crate) fn timed(kind: Kind, f: impl FnOnce() -> T) -> T { let st = STATE.with(Cell::get); @@ -122,6 +137,19 @@ mod tests { assert!(t.boolean_ms + t.tessellate_ms <= elapsed + 1e-6, "{t:?} in {elapsed} ms"); } + #[test] + fn time_credited_from_other_threads_counts_only_inside_a_capture() { + let t = KernelTimes { boolean_ms: 4.0, tessellate_ms: 1.0 }; + credit(t); + let ((), got) = capture(|| { + credit(t); + credit(KernelTimes { boolean_ms: f64::NAN, tessellate_ms: -3.0 }); + // Inside a timed call it would count twice: it is the call's time already. + timed(Kind::Boolean, || credit(t)); + }); + assert_eq!((got.boolean_ms >= 4.0, got.boolean_ms < 8.0, got.tessellate_ms), (true, true, 1.0), "{got:?}"); + } + #[test] fn inner_captures_add_to_the_outer_one_and_a_panic_restores_it() { let ((), outer) = capture(|| { diff --git a/docs/book/src/guide/assemblies.md b/docs/book/src/guide/assemblies.md index 5c20f1d9c..f60701c1c 100644 --- a/docs/book/src/guide/assemblies.md +++ b/docs/book/src/guide/assemblies.md @@ -62,7 +62,10 @@ body in `bodies` and the other in `against`, and `skip_within` leaves out pairs occurrence (`"occurrence"`) or one placed component, its subcomponents included (`"component"`): the parts of a bought component that touch by design. Distances are measured on the exact faces and edges; the meshes only rule out pairs that are too far apart, and the pairs -left are checked in parallel. `inspect.interference` remains for the overlaps alone. +left are checked in parallel. `inspect.interference` remains for the overlaps alone: it clears +pairs whose meshes stay apart without intersecting them, intersects the rest in parallel, and +returns after `budget_s` seconds (default 240) at most, listing the pairs it had no time for as +not checked. **Gear**, **Rack and Pinion** and **Screw** (on the **ASSEMBLE** panel) are motion links whose ratio comes from the parts rather than a typed number: From b76302e850b6b6ae7c7d42882efd49488d1c0b18 Mon Sep 17 00:00:00 2001 From: takuto-NA Date: Mon, 19 Oct 2026 22:15:26 +0900 Subject: [PATCH 059/225] Assembly: reuse reference meshes during rigid joint motion (#2922) (#2924) Thanks @takuto-NA. --- crates/doc/src/eval.rs | 28 +++- crates/doc/src/placed_mesh.rs | 144 ++++++++++++++++++ .../engine/src/world_placement_cache_tests.rs | 51 ++++++- 3 files changed, 216 insertions(+), 7 deletions(-) create mode 100644 crates/doc/src/placed_mesh.rs diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index ca8773c4b..11817bef8 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -1,5 +1,8 @@ //! Timeline evaluation. +#[path = "placed_mesh.rs"] +mod placed_mesh; + use std::collections::BTreeMap; use std::hash::{Hash, Hasher}; use std::sync::{Arc, OnceLock}; @@ -28,6 +31,8 @@ pub struct ModelBody { // Timeline snapshots are cloned before meshes are requested. Share the cell itself so // meshing any snapshot also warms every unchanged copy of this body. mesh: Arc>>, + /// Lazy canonical reference triangles for a proper rigid occurrence placement. + mesh_placement: Option>, /// The display plan (none when the body has no plan: a mesh body, or one the planner /// refuses), shared like the mesh. A GPU viewport draws it. plan: Arc<[OnceLock>>; 4]>, @@ -61,6 +66,7 @@ impl ModelBody { body, feature, mesh: Arc::new(OnceLock::new()), + mesh_placement: None, plan: Arc::new(Default::default()), plan_mesh: Arc::new(Default::default()), key: 0, @@ -83,9 +89,10 @@ impl ModelBody { // finding their surface, picks naming their face, sketch planes), and a different // triangulation moved those and changed what designs build. A GPU viewport draws the // plan ([`ModelBody::display_plan`]). - self.mesh - .get_or_init(|| Arc::new(self.body.reference_display_mesh_angular(self.display_tol(), kernel::DISPLAY_ANGLE).unwrap_or_default())) - .clone() + match self.mesh_placement.as_deref() { + Some(placed) => self.mesh.get_or_init(|| placed.mesh()).clone(), + None => placed_mesh::reference_mesh(&self.body, &self.mesh, self.display_tol()), + } } /// The display plan of this body at the viewport's display quality @@ -145,9 +152,10 @@ impl ModelBody { Some((Arc::new(plan), Arc::new(mesh))) } - /// The chord tolerance of [`ModelBody::mesh`] (mm): 1/1000 of the body's size, at least 1 µm. + /// The chord tolerance of [`ModelBody::mesh`] (mm): 1/1000 of the definition's size, at least + /// 1 µm. Proper rigid placements retain that tolerance along with the reference triangles. pub fn display_tol(&self) -> f64 { - (self.body.size() * 1e-3).max(1e-3) + self.mesh_placement.as_ref().map(|placed| placed.tolerance).unwrap_or_else(|| (self.body.size() * 1e-3).max(1e-3)) } /// Already computed display geometry; saving must not trigger cold tessellation. @@ -5710,11 +5718,19 @@ impl PlacedBodies { Some((_, placed)) => { let mut fresh = ModelBody::new(name, placed.body.clone(), b.feature); fresh.mesh = placed.mesh.clone(); + fresh.mesh_placement = placed.mesh_placement.clone(); fresh.plan = placed.plan.clone(); fresh.plan_mesh = placed.plan_mesh.clone(); fresh } - None => ModelBody::new(name, kernel::transform_matrix(&b.body, *m).unwrap_or_else(|_| b.body.clone()), b.feature), + None => match kernel::transform_matrix(&b.body, *m) { + Ok(body) => { + let mut fresh = ModelBody::new(name, body, b.feature); + fresh.mesh_placement = placed_mesh::PlacedMesh::new(b, m).map(Arc::new); + fresh + } + Err(_) => ModelBody::new(name, b.body.clone(), b.feature), + }, } } } diff --git a/crates/doc/src/placed_mesh.rs b/crates/doc/src/placed_mesh.rs new file mode 100644 index 000000000..76c7243a4 --- /dev/null +++ b/crates/doc/src/placed_mesh.rs @@ -0,0 +1,144 @@ +//! Reference triangles belong to a definition, even while its occurrences move. Keep one lazy +//! source mesh and map it into each pose; retain the exact placed B-rep separately in ModelBody. +use std::sync::{Arc, OnceLock}; + +use solidcraft_geom::{Mesh, Vec3}; +use solidcraft_kernel::{self as kernel, Body}; + +use super::ModelBody; + +#[derive(Debug)] +pub(super) struct PlacedMesh { + body: Body, + mesh: Arc>>, + transform: crate::Mat, + pub(super) tolerance: f64, +} + +impl PlacedMesh { + /// Share the original definition, never a chain of previously placed meshes. A source's + /// OnceLock lives with its immutable geometry, so edits get a new source automatically. + pub(super) fn new(source: &ModelBody, transform: &crate::Mat) -> Option { + if !proper_rigid(transform) { + return None; + } + Some(match source.mesh_placement.as_deref() { + Some(original) => Self { + body: original.body.clone(), + mesh: original.mesh.clone(), + transform: crate::mat_mul(transform, &original.transform), + tolerance: original.tolerance, + }, + None => Self { body: source.body.clone(), mesh: source.mesh.clone(), transform: *transform, tolerance: source.display_tol() }, + }) + } + + pub(super) fn mesh(&self) -> Arc { + let source = reference_mesh(&self.body, &self.mesh, self.tolerance); + Arc::new(Mesh { + positions: source.positions.iter().map(|p| crate::apply_point(&self.transform, *p)).collect(), + normals: source.normals.iter().map(|n| crate::apply_vector(&self.transform, *n)).collect(), + edges: source.edges.iter().map(|edge| edge.iter().map(|p| crate::apply_point(&self.transform, *p)).collect()).collect(), + triangles: source.triangles.clone(), + tri_face: source.tri_face.clone(), + edge_faces: source.edge_faces.clone(), + seams: source.seams.clone(), + smooth_edges: source.smooth_edges.clone(), + sharp_edges: source.sharp_edges.clone(), + }) + } +} + +pub(super) fn reference_mesh(body: &Body, mesh: &OnceLock>, tolerance: f64) -> Arc { + mesh.get_or_init(|| Arc::new(body.reference_display_mesh_angular(tolerance, kernel::DISPLAY_ANGLE).unwrap_or_default())).clone() +} + +/// Only proper rotations and translations preserve triangle winding, normal lengths and the +/// reference chord tolerance. Scale, shear, reflection and malformed matrices use the mesher. +fn proper_rigid(m: &crate::Mat) -> bool { + if m.iter().flatten().any(|v| !v.is_finite()) || m[0][3] != 0. || m[1][3] != 0. || m[2][3] != 0. || m[3][3] != 1. { + return false; + } + let [x, y, z] = [Vec3::new(m[0][0], m[0][1], m[0][2]), Vec3::new(m[1][0], m[1][1], m[1][2]), Vec3::new(m[2][0], m[2][1], m[2][2])]; + [x, y, z].iter().all(|v| (v.dot(*v) - 1.).abs() < 1e-9) + && x.dot(y).abs() < 1e-9 + && x.dot(z).abs() < 1e-9 + && y.dot(z).abs() < 1e-9 + && (x.cross(y).dot(z) - 1.).abs() < 1e-9 +} +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn placed_mesh_is_lazy_and_composes_from_one_immutable_source() { + let source = ModelBody::new("Part".into(), kernel::box_solid(Vec3::ZERO, Vec3::new(2., 3., 4.)).unwrap(), 1); + let a = crate::rigid(Vec3::new(10., 20., 30.), Vec3::ZERO, Vec3::Z, 0.7); + let b = crate::rigid(Vec3::new(3., -5., 2.), Vec3::ZERO, Vec3::X, 0.4); + let mut first = ModelBody::new("First".into(), kernel::transform_matrix(&source.body, a).unwrap(), 1); + first.mesh_placement = Some(Arc::new(PlacedMesh::new(&source, &a).unwrap())); + let mut nested = ModelBody::new("Nested".into(), kernel::transform_matrix(&first.body, b).unwrap(), 1); + nested.mesh_placement = Some(Arc::new(PlacedMesh::new(&first, &b).unwrap())); + assert_eq!(first.display_tol(), source.display_tol()); + assert_eq!(nested.display_tol(), source.display_tol()); + assert!(source.cached_mesh().is_none()); + assert!(first.cached_mesh().is_none()); + let mesh = nested.mesh(); + assert!(source.cached_mesh().is_some(), "the canonical source is warmed on demand"); + assert!(first.cached_mesh().is_none(), "composition does not retain or evaluate intermediate poses"); + let local = source.mesh(); + let matrix = crate::mat_mul(&b, &a); + for (p, q) in local.positions.iter().zip(&mesh.positions) { + assert!(crate::apply_point(&matrix, *p).dist(*q) < 1e-8); + } + let (other, work) = kernel::profile::capture(|| first.mesh()); + assert_eq!(work.tessellate_ms, 0.); + assert_eq!(other.tri_face, local.tri_face); + assert!(Arc::ptr_eq(&mesh, &nested.mesh())); + } + + #[test] + fn world_instances_warm_one_definition_and_an_edit_replaces_it() { + let mut doc = crate::Document::new("instances"); + let component = doc.add_component(Some("Part"), 0).unwrap(); + doc.body_components.insert("Pin".into(), component); + let first = doc.occurrences[0].id; + doc.occurrences[0].transform = crate::rigid(Vec3::new(10., 0., 0.), Vec3::ZERO, Vec3::Y, 0.3); + doc.add_occurrence(component, 0, crate::rigid(Vec3::new(0., 20., 0.), Vec3::ZERO, Vec3::X, 0.6)).unwrap(); + let mut state = crate::ModelState::default(); + state.bodies.push(ModelBody::new("Pin".into(), kernel::cylinder(Vec3::ZERO, Vec3::Z, 2., 8.).unwrap(), 1)); + let mut cache = super::super::PlacedBodies::default(); + let before = super::super::world_state_reusing(&doc, &state, &mut cache); + assert!(state.bodies[0].cached_mesh().is_none(), "placing bodies must remain lazy"); + let old = before.bodies[0].mesh(); + assert!(state.bodies[0].cached_mesh().is_some()); + let (_, work) = kernel::profile::capture(|| before.bodies[1].mesh()); + assert_eq!(work.tessellate_ms, 0., "the second instance shares the first one's triangulation"); + doc.occurrences.iter_mut().find(|o| o.id == first).unwrap().transform = crate::rigid(Vec3::new(30., 0., 0.), Vec3::ZERO, Vec3::Y, 0.9); + let moved = super::super::world_state_reusing(&doc, &state, &mut cache); + let (_, work) = kernel::profile::capture(|| moved.bodies[0].mesh()); + assert_eq!(work.tessellate_ms, 0., "a new pose shares the same definition"); + state.bodies[0] = ModelBody::new("Pin".into(), kernel::cylinder(Vec3::ZERO, Vec3::Z, 4., 8.).unwrap(), 1); + let edited = super::super::world_state_reusing(&doc, &state, &mut cache); + assert!(state.bodies[0].cached_mesh().is_none()); + let new = edited.bodies[0].mesh(); + assert!(state.bodies[0].cached_mesh().is_some(), "changed geometry warms its new definition cache"); + assert_ne!(new.bounds(), moved.bodies[0].mesh().bounds()); + assert!(Arc::ptr_eq(&old, &before.bodies[0].mesh()), "editing does not mutate older snapshots"); + } + #[test] + fn only_proper_rigid_affine_matrices_reuse_reference_meshes() { + let source = ModelBody::new("Part".into(), kernel::box_solid(Vec3::ZERO, Vec3::new(2., 3., 4.)).unwrap(), 1); + assert!(PlacedMesh::new(&source, &crate::IDENTITY).is_some()); + for (col, row, value) in [(0, 0, -1.), (0, 0, 2.), (0, 1, 0.5), (0, 3, 0.1), (3, 3, 2.), (3, 0, f64::NAN), (3, 2, f64::INFINITY)] { + let mut matrix = crate::IDENTITY; + matrix[col][row] = value; + assert!(PlacedMesh::new(&source, &matrix).is_none(), "{matrix:?}"); + } + // A positive unit determinant alone is insufficient: this scale changes normals and tolerance. + let mut scale = crate::IDENTITY; + scale[0][0] = 2.; + scale[1][1] = 0.5; + assert!(PlacedMesh::new(&source, &scale).is_none()); + } +} diff --git a/crates/engine/src/world_placement_cache_tests.rs b/crates/engine/src/world_placement_cache_tests.rs index 7d1c4431c..9bd84a77e 100644 --- a/crates/engine/src/world_placement_cache_tests.rs +++ b/crates/engine/src/world_placement_cache_tests.rs @@ -197,7 +197,7 @@ fn moved_component_bodies_are_not_placed_again_when_something_else_changes() { let again = after.body(&rim.name).unwrap(); assert!(Arc::ptr_eq(&mesh, &again.mesh()), "an unchanged placed body keeps its mesh"); assert!(again.body.same(&rim.body)); - // The placement moves: placed and meshed again where it now is. + // The placement moves: new world coordinates, reusing the definition's triangulation. run(&mut session, "occurrence.move", json!({"occurrence":occurrence,"translate":[0,50,0]})); let moved = session.world_state(); let moved_rim = moved.bodies.iter().find(|b| b.source_name.as_deref() == Some("Rim")).unwrap(); @@ -213,3 +213,52 @@ fn moved_component_bodies_are_not_placed_again_when_something_else_changes() { assert!(source.mesh().bounds().min.dist(Vec3::ZERO) < 1e-6); assert!(mesh.bounds().min.dist(Vec3::new(100., 0., 0.)) < 1e-6); } + +/// Driving an unchanged definition must map its warm reference triangles, not re-tessellate +/// the placed B-rep on the first mesh read of every new pose (viewport bounds does that read). +#[test] +fn joint_drive_reuses_reference_tessellation_across_rigid_poses() { + let mut session = Session::default(); + run(&mut session, "solid.cylinder", json!({"radius":3,"height":8,"base":[4,0,0],"body_name":"Crank"})); + run(&mut session, "component.create", json!({"name":"Crank","parent":"root","activate":false})); + run(&mut session, "component.move_bodies", json!({"bodies":["Crank"],"component":"Crank"})); + run( + &mut session, + "joint.as_built", + json!({"type":"revolute","name":"Crank","a":0,"b":"Crank","at":{"occurrence":0,"point":[0,0,0],"z":[0,0,1]}}), + ); + let definitions = session.model.state(); + let original = session.world_state(); + let local = original.body("Crank").unwrap().mesh(); + let bounds = local.bounds(); + for angle in [37., 91., 37., 0.] { + let driven = run(&mut session, "joint.drive", json!({"joint":"Crank","value":angle})); + assert_eq!(driven["moved"], true); + assert!(Arc::ptr_eq(&definitions, &session.model.state())); + let world = session.world_state(); + let body = world.body("Crank").unwrap(); + let (mesh, work) = crate::kernel::profile::capture(|| body.mesh()); + assert_eq!(work.tessellate_ms, 0., "a warm definition must not enter the kernel mesher at a new pose: {work:?}"); + assert_eq!(mesh.positions.len(), local.positions.len()); + assert_eq!(mesh.normals.len(), local.normals.len()); + assert_eq!(mesh.edges.iter().map(Vec::len).collect::>(), local.edges.iter().map(Vec::len).collect::>()); + assert_eq!(mesh.triangles, local.triangles); + assert_eq!(mesh.tri_face, local.tri_face); + assert_eq!(mesh.edge_faces, local.edge_faces); + assert_eq!(mesh.seams, local.seams); + assert_eq!(mesh.smooth_edges, local.smooth_edges); + assert_eq!(mesh.sharp_edges, local.sharp_edges); + for (p, q) in local.positions.iter().zip(&mesh.positions) { + assert!(crate::doc::apply_point(&body.source_transform, *p).dist(*q) < 1e-8); + } + for (n, q) in local.normals.iter().zip(&mesh.normals) { + assert!(crate::doc::apply_vector(&body.source_transform, *n).dist(*q) < 1e-8); + } + for (edge, placed) in local.edges.iter().zip(&mesh.edges) { + for (p, q) in edge.iter().zip(placed) { + assert!(crate::doc::apply_point(&body.source_transform, *p).dist(*q) < 1e-8); + } + } + } + assert_eq!(local.bounds(), bounds, "old snapshots stay immutable"); +} From b4e049f9a63cb2283f016fec325cf713c8ba0455 Mon Sep 17 00:00:00 2001 From: fkirill Date: Mon, 19 Oct 2026 17:14:07 +0300 Subject: [PATCH 060/225] Preserve equal-radius fillet mitre tangency (#2485) Equal-radius mitres keep their endpoint tangent so a later fillet can select the chain (#2422). --- ROADMAP.md | 2 ++ crates/kernel/src/blend_corner.rs | 43 ++++++++++++++++++++++++++++++- 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/ROADMAP.md b/ROADMAP.md index cfe4d7a47..471240bb7 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -349,6 +349,8 @@ completed drawings publish atomically. The browser still exports synchronously. rounds next to earlier rounds of another radius, and smooth corner patches where three rounds meet (a sphere for equal radii); perpendicular corner fillets after a closed ring of earlier rounds preserve the ring's radii and the enclosed planar face (#1557); + mitres between separate rounds of the same radius keep their endpoint tangent, so a later + fillet can select an upright and its adjoining bottom mitre as one chain (#2422); straight edges (convex or concave) between planar faces with perpendicular planar end faces (equal-distance chamfers also meet sloped planar end faces, including inner basin rims within the rim width); convex fillets also meet sloped planar ends and reflex diff --git a/crates/kernel/src/blend_corner.rs b/crates/kernel/src/blend_corner.rs index a41528665..3def4625b 100644 --- a/crates/kernel/src/blend_corner.rs +++ b/crates/kernel/src/blend_corner.rs @@ -791,7 +791,22 @@ fn crease(a: &Sel, b: &Sel, q: Vec3, end: Vec3, size: f64) -> Result pts.push(p3(p)); } pts.push(p3(end)); - crate::splitface::fit(&pts, size) + let mut curve = crate::splitface::fit(&pts, size)?; + // The last chord tilts away from the cylinders' intersection tangent. At an equal-radius + // mitre that tangent continues the sharp third edge; losing it breaks the smooth chain + // used to map picks when a later fillet rebuilds these rounds (#2422). + let radial = |c: Vec3, d: Vec3| (end - c) - d * (end - c).dot(d); + if (a.r - b.r).abs() <= size * 1e-9 + && let Some(tangent) = radial(ca, da).cross(radial(cb, db)).normalized() + && let mt::Curve::BSplineCurve(ref mut spline) = curve + && let Some(index) = spline.control_points().len().checked_sub(2) + && let Some(control) = spline.control_points_mut().nth(index) + { + let toward_end = end - crate::body::from_p3(*control); + let tangent = if tangent.dot(toward_end) < 0.0 { -tangent } else { tangent }; + *control = p3(end - tangent * toward_end.len()); + } + Ok(curve) } /// Keep selected sharp edges while consuming a selected mitre that is on the same smooth @@ -1376,6 +1391,32 @@ mod tests { assert!(fillet_radii(&rounded, &[(seam, 2.0)]).is_err()); } + #[test] + fn issue2422_vertical_after_separate_bottom_rounds() { + let origin = Vec3::new(-5.0, 7.2, -2.0); + let b = box_solid(origin, origin + Vec3::new(40.0, 80.0, 27.0)).unwrap(); + let bottom = [Vec3::new(15.0, 7.2, -2.0), Vec3::new(35.0, 47.2, -2.0), Vec3::new(15.0, 87.2, -2.0), Vec3::new(-5.0, 47.2, -2.0)]; + // The issue has no design attached. Reconstruct its outside corner and bottom mitre, + // using the reported picks, with and without the open cavity visible in the screenshot. + let picks = [Vec3::new(-5.0, 87.2, 12.5), Vec3::new(-4.283446394180081, 86.48344639418008, -1.5001085324947512)]; + for base in [b.clone(), crate::shell(&b, &[Vec3::new(15.0, 47.2, 25.0)], 1.0).unwrap()] { + let mut rounded = base; + for edge in bottom { + rounded = fillet(&rounded, &[edge], 2.0).unwrap(); + } + let reference = fillet(&rounded, &picks[..1], 2.0).unwrap(); + for selection in [picks, [picks[1], picks[0]]] { + let result = fillet(&rounded, &selection, 2.0).unwrap(); + assert_eq!(result.face_count(), reference.face_count()); + assert_eq!(result.unmeshed_faces(), 0); + assert!(result.validity().is_empty(), "{:?}", result.validity()); + assert!((vol(&result) - vol(&reference)).abs() < 0.05); + assert!(!result.contains(Vec3::new(-4.9, 87.1, 10.0))); + assert!(result.contains(Vec3::new(-4.1, 86.3, 10.0))); + } + } + } + #[test] fn issue1557_all_vertical_corners_match_analytic_volume() { let origin = Vec3::new(10.0, -5.0, 7.0); From 5bed5196c735a729c010f108571bb1f09930e152 Mon Sep 17 00:00:00 2001 From: fkirill Date: Mon, 19 Oct 2026 17:14:12 +0300 Subject: [PATCH 061/225] Fix lens-profile cuts into revolved quarter spheres (#2791) Lens-profile cuts into revolved quarter spheres now build (#2750). --- crates/engine/src/tests.rs | 1 + crates/engine/src/tests/sphere_lens.rs | 37 +++++ crates/kernel/src/lib.rs | 1 + crates/kernel/src/ops.rs | 12 ++ crates/kernel/src/sphere_lens.rs | 187 +++++++++++++++++++++++++ crates/kernel/src/sphere_lens_tests.rs | 73 ++++++++++ 6 files changed, 311 insertions(+) create mode 100644 crates/engine/src/tests/sphere_lens.rs create mode 100644 crates/kernel/src/sphere_lens.rs create mode 100644 crates/kernel/src/sphere_lens_tests.rs diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index daceaaf47..844db5037 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -325,6 +325,7 @@ mod primitive_points; mod rim_cut; mod robustness; mod robustness_goldens; +mod sphere_lens; mod spiral_join; mod step_import_options; mod xz_plane; diff --git a/crates/engine/src/tests/sphere_lens.rs b/crates/engine/src/tests/sphere_lens.rs new file mode 100644 index 000000000..de06a19a9 --- /dev/null +++ b/crates/engine/src/tests/sphere_lens.rs @@ -0,0 +1,37 @@ +//! #2750: a negative extrude of the overlap between a circle and a dome outline. +use super::*; + +#[test] +fn negative_lens_extrude_cuts_a_partial_sphere_and_reopens() { + let mut s = Session::default(); + let plane = json!({"origin":[0,0,0],"x_dir":[1,0,0],"y_dir":[0,0,1]}); + run(&mut s, "sketch.create", json!({"name":"DomeProfile","plane":plane})); + run(&mut s, "sketch.arc.three_point", json!({"start":[25,0],"through":[0,25],"end":[-25,0]})); + run(&mut s, "sketch.line", json!({"points":[[-25,0],[25,0]]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.revolve", json!({"sketch":"DomeProfile","axis":"x","angle":"90 deg","body_name":"Dome"})); + // The same outline a face-attached sketch projects, and the intersecting circle. + run(&mut s, "sketch.create", json!({"name":"CutProfile","plane":{"origin":[0,0,0],"x_dir":[-1,0,0],"y_dir":[0,0,1]}})); + run(&mut s, "sketch.arc.three_point", json!({"start":[25,0],"through":[0,25],"end":[-25,0]})); + run(&mut s, "sketch.line", json!({"points":[[-25,0],[25,0]]})); + run(&mut s, "sketch.circle.center", json!({"center":[0,20],"radius":15})); + run(&mut s, "sketch.finish", json!({})); + run( + &mut s, + "solid.extrude", + json!({"sketch":"CutProfile","profiles":[{"point":[0,15]}],"direction":"positive","distance":"-30 mm","operation":"cut"}), + ); + let check = |s: &mut Session| { + assert!((volume(s) - 8810.08973246).abs() < 2.); + let state = s.model.state(); + assert_eq!(state.bodies.len(), 1); + let body = &state.bodies[0].body; + assert!(body.validity().is_empty(), "{:?}", body.validity()); + assert!(solidcraft_kernel::measure(body).unwrap().bbox.max.z < 20.01, "no lid across the opening"); + assert!(body.contains(Vec3::new(0., -10., 2.))); + assert!(!body.contains(Vec3::new(0., -10., 15.))); + }; + check(&mut s); + let mut reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); + check(&mut reopened); +} diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rs index 055584995..4ea1228fb 100644 --- a/crates/kernel/src/lib.rs +++ b/crates/kernel/src/lib.rs @@ -113,6 +113,7 @@ mod record; mod seam_faces; mod sew; mod smooth_edges; +mod sphere_lens; mod spline_conv; mod splitface; mod step; diff --git a/crates/kernel/src/ops.rs b/crates/kernel/src/ops.rs index 4194412c1..10e7fc481 100644 --- a/crates/kernel/src/ops.rs +++ b/crates/kernel/src/ops.rs @@ -1196,6 +1196,18 @@ fn boolean_whole_with_refinement(a: &Body, b: &Body, op: BoolOp, refine: bool) - return Ok(Some(body)); } } + // A lens cut from a sphere's projected outline carries a redundant cylinder + // tangent to the sphere (#2750). Remove it only after proving that it + // encloses the entire target, keeping the other wall and both caps exact. + if attempt == 1 && op == BoolOp::Cut { + let (lens, diagnostics) = capture_boolean_diagnostics(|| crate::sphere_lens::cut(a, b, &boolean_whole)); + if let Some(Ok(result)) = lens + && result.as_ref().is_none_or(|body| check(body).0) + { + merge(diagnostics); + return Ok(result); + } + } // A whole turn of a cylinder or cone bounded by one wire along its seam (as STEP files // write them) can't be divided by a loop lying inside it, and the tries below end in a // nudged tool, or fail: the same boolean with such faces in two halves, which is exact. diff --git a/crates/kernel/src/sphere_lens.rs b/crates/kernel/src/sphere_lens.rs new file mode 100644 index 000000000..05eda9638 --- /dev/null +++ b/crates/kernel/src/sphere_lens.rs @@ -0,0 +1,187 @@ +//! A lens extruded from a sphere's projected outline (#2750). One of its two +//! cylinders encloses the whole target and only touches the sphere. Removing that +//! redundant constraint gives the same cut without a tangent intersection. + +use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2, Vec3}; + +use crate::boolean_record as recorded; +use crate::history::Change; +use crate::{Body, BoolOp, FaceSource, FaceSurface, Result, face_surface}; + +/// Maximum signed height of a line or circular arc, including interior extrema. +fn height(segment: Seg2, plane: Plane, cap: Plane) -> Option { + let at = |p| cap.height(plane.to_world(p)); + let ends = at(segment.start()).max(at(segment.end())); + match segment { + Seg2::Line { .. } => Some(ends), + Seg2::Arc { center, radius, .. } => { + let n = cap.normal(); + let direction = Vec2::new(n.dot(plane.x), n.dot(plane.y)); + let probe = center + direction.normalized().unwrap_or(Vec2::X) * radius; + Some(ends.max(at(segment.point_at(segment.closest_param(probe))))) + } + _ => None, + } +} + +/// Recognize a quarter ball by its complete boundary: one spherical face, two +/// perpendicular semicircular caps sharing their diameter, each cap inside the +/// other's outward halfspace. The opposite cap orientation (three quarters of a +/// ball) is refused. Whole-span curve certificates prove the caps, not samples. +fn enclosing_ball(body: &Body, tol: f64) -> Option<(Vec3, f64, Vec)> { + if body.is_mesh() || body.shell_count() != 1 || body.face_count() != 3 { + return None; + } + let surfaces = (0..3).map(|i| face_surface(body, i)).collect::>>()?; + let (sphere, center, radius) = surfaces.iter().enumerate().find_map(|(i, surface)| match *surface { + FaceSurface::Sphere { center, radius } => Some((i, center, radius)), + _ => None, + })?; + let spherical = body.solid.face_iter().nth(sphere)?; + if spherical.boundaries().len() != 1 || spherical.edge_iter().count() != 2 { + return None; + } + let sphere_edges: std::collections::HashSet<_> = spherical.edge_iter().map(|e| e.id()).collect(); + let caps: Vec<_> = surfaces + .iter() + .filter_map(|surface| match *surface { + FaceSurface::Plane { normal, point } => Plane::from_normal(point, normal), + _ => None, + }) + .collect(); + let (cap0, cap1) = (*caps.first()?, *caps.get(1)?); + if caps.len() != 2 || cap0.normal().dot(cap1.normal()).abs() > 1e-9 || cap0.height(center).abs() > tol || cap1.height(center).abs() > tol { + return None; + } + let mut work = 2_000_000usize; + let mut diameters = Vec::new(); + for (i, face) in body.solid.face_iter().enumerate() { + if i == sphere { + continue; + } + let FaceSurface::Plane { normal, point } = *surfaces.get(i)? else { return None }; + let plane = Plane::from_normal(point, normal)?; + if face.boundaries().len() != 1 || face.edge_iter().count() != 2 { + return None; + } + let c = plane.to_local(center); + let mut arc = 0.; + let mut lines = 0; + for edge in face.edge_iter() { + if plane.height(crate::body::from_p3(edge.front().point())).abs() > tol + || plane.height(crate::body::from_p3(edge.back().point())).abs() > tol + { + return None; + } + for segment in crate::prism_curve::segment(&edge, &plane, tol, &mut work)? { + match segment { + Seg2::Line { a, b } if (a + b - c * 2.).len() <= tol && (a.dist(c) - radius).abs() <= tol => { + diameters.push(edge.id()); + lines += 1; + } + Seg2::Arc { center: q, radius: r, sweep, .. } if q.dist(c) + (r - radius).abs() <= tol && sphere_edges.contains(&edge.id()) => { + arc += sweep.abs(); + } + _ => return None, + } + if height(segment, plane, cap0)? > tol || height(segment, plane, cap1)? > tol { + return None; + } + } + } + if lines != 1 || (arc - std::f64::consts::PI).abs() > 1e-8 { + return None; + } + } + if diameters.len() != 2 || diameters.first()? != diameters.get(1)? { + return None; + } + Some((center, radius, caps)) +} + +/// Replace only a construction-certified, convex two-circle lens. Its cutting cylinder stays exact; a cap moves +/// only into a halfspace proved to be outside the target. The added tool material is outside the ball. +fn relaxed_tool(a: &Body, b: &Body) -> Option { + if b.is_mesh() || b.shell_count() != 1 || b.face_count() != 4 { + return None; + } + let tol = (a.size().max(b.size()) * 1e-9).max(1e-8); + let sources = b.face_sources()?; + let (region, plane) = sources.iter().find_map(|source| match source { + Some(FaceSource::ExtrudeCap { high: true, region, plane }) => Some((region, *plane)), + _ => None, + })?; + let bottom = sources.iter().find_map(|source| match source { + Some(FaceSource::ExtrudeCap { high: false, region: r, plane }) if r == region => Some(*plane), + _ => None, + })?; + if !region.holes.is_empty() || region.outer.segs.len() != 2 || !region.outer.is_closed(tol) { + return None; + } + let circles: Vec<(Vec2, f64)> = region + .outer + .segs + .iter() + .map(|s| match *s { + Seg2::Arc { center, radius, sweep, .. } if sweep > 0.0 && sweep <= std::f64::consts::PI + 1e-9 => Some((center, radius)), + _ => None, + }) + .collect::>()?; + let ((c0, r0), (c1, r1)) = (*circles.first()?, *circles.get(1)?); + let distance = c0.dist(c1); + if distance <= (r0 - r1).abs() + tol || distance >= r0 + r1 - tol { + return None; + } + let (center, radius, caps) = enclosing_ball(a, tol)?; + let projected = plane.to_local(center); + let redundant = circles.iter().position(|(c, r)| projected.dist(*c) + radius <= *r + tol)?; + let (c, r) = *circles.get(1 - redundant)?; + let height = plane.height(bottom.origin); + if !height.is_finite() || height >= -tol || plane.normal().dot(bottom.normal()) > -1.0 + 1e-9 { + return None; + } + // The proven quarter ball lies behind each cap. Extend a coincident tool + // end outward into that empty halfspace; this avoids the generic nudge's + // paper-thin lid across the opening, without moving the cutting cylinder. + let on_cap = |end: Plane| caps.iter().any(|cap| cap.normal().dot(end.normal()) > 1.0 - 1e-9 && cap.height(end.origin).abs() <= tol); + let (low, high) = (on_cap(bottom), on_cap(plane)); + if !low && !high { + return None; + } + let margin = (a.size().max(b.size()) * 0.01).max(1e-5); + let lo = height - if low { margin } else { 0. }; + let hi = if high { margin } else { 0. }; + let mut tool = + crate::extrude(&plane, &[Region2 { outer: Loop2::circle_from(c, r, crate::build::SEAM_ANGLE), holes: vec![] }], lo, hi).ok()?.pop()?; + // Each rebuilt surface names its original tool face. Extended portions never + // meet the target, so every face used in the cut still lies in that input face. + let mut faces = Vec::new(); + for i in 0..tool.face_count() { + let surface = face_surface(&tool, i)?; + let original = (0..b.face_count()).find(|j| match (surface, face_surface(b, *j)) { + (FaceSurface::Plane { normal: n, .. }, Some(FaceSurface::Plane { normal: m, .. })) => n.dot(m) > 1.0 - 1e-9, + (FaceSurface::Cylinder { origin: p, axis: n, radius: r }, Some(FaceSurface::Cylinder { origin: q, axis: m, radius: s })) => { + n.dot(m).abs() > 1.0 - 1e-9 && (p - q).cross(n).len() + (r - s).abs() <= tol + } + _ => false, + })?; + faces.push(crate::record::from_face(0, original, Change::Modified)); + } + let history = crate::record::from_faces(&tool.solid, 1, faces); + tool = tool.with_checked_history(Some(history), &crate::record::counts(&[b])); + Some(tool) +} + +pub(crate) fn cut(a: &Body, b: &Body, run: &dyn Fn(&Body, &Body, BoolOp) -> Result>) -> Option>> { + let tool = crate::guard("sphere lens tool", || Ok(relaxed_tool(a, b))).ok()??; + let result = run(a, &tool, BoolOp::Cut).ok()?; + crate::boolean_guard::check_retry(a, b, BoolOp::Cut, result.as_ref()).ok()?; + Some(Ok(result.map(|body| { + let history = recorded::through(&body, 1, tool.history()); + body.with_checked_history(history, &crate::record::counts(&[a, b])) + }))) +} + +#[cfg(test)] +#[path = "sphere_lens_tests.rs"] +mod tests; diff --git a/crates/kernel/src/sphere_lens_tests.rs b/crates/kernel/src/sphere_lens_tests.rs new file mode 100644 index 000000000..b46be3e8f --- /dev/null +++ b/crates/kernel/src/sphere_lens_tests.rs @@ -0,0 +1,73 @@ +use super::*; +use std::f64::consts::{FRAC_PI_2, PI}; + +fn dome() -> Body { + let profile = Region2 { + outer: Loop2 { + segs: vec![ + Seg2::Arc { center: Vec2::ZERO, radius: 25., start: 0., sweep: PI }, + Seg2::Line { a: Vec2::new(-25., 0.), b: Vec2::new(25., 0.) }, + ], + }, + holes: vec![], + }; + let plane = Plane { origin: Vec3::ZERO, x: Vec3::X, y: Vec3::Z }; + crate::revolve_whole(&plane, &[profile], Vec2::ZERO, Vec2::X, FRAC_PI_2).unwrap().pop().unwrap() +} + +fn lens(enclosing_radius: f64) -> Region2 { + crate::planar_regions_boolean( + &[Region2 { outer: Loop2::circle(Vec2::ZERO, enclosing_radius), holes: vec![] }], + &[Region2 { outer: Loop2::circle(Vec2::new(0., 20.), 15.), holes: vec![] }], + BoolOp::Intersect, + 1e-7, + ) + .unwrap() + .pop() + .unwrap() +} + +fn tool(region: Region2, depth: f64) -> Body { + let plane = Plane { origin: Vec3::ZERO, x: Vec3::X, y: Vec3::Z }; + crate::extrude(&plane, &[region], 0., depth).unwrap().pop().unwrap() +} + +#[test] +fn projected_spherical_outline_does_not_block_a_lens_cut() { + let target = dome(); + let cutter = tool(lens(25.), 30.); + let (result, diagnostics) = crate::capture_boolean_diagnostics(|| crate::boolean(&target, &cutter, BoolOp::Cut)); + let result = result.unwrap().unwrap(); + assert!(diagnostics.events.iter().all(|event| !event.strategy.alters_result()), "{diagnostics:?}"); + assert!(result.validity().is_empty(), "{:?}", result.validity()); + assert_eq!(result.lumps().unwrap().len(), 1); + // Integrating the half-disc cross-section left by the offset bore gives + // 8810.08973246 mm³ (R=25, bore radius=15, bore centre z=20). + let measured = crate::measure(&result).unwrap(); + assert!((measured.volume - 8810.08973246).abs() < 2., "{measured:?}"); + assert!(measured.bbox.max.z < 20.01, "no thin lid may remain above the cut: {measured:?}"); + assert!(result.contains(Vec3::new(0., -10., 2.))); + assert!(!result.contains(Vec3::new(0., -10., 15.))); + assert_eq!(measured.merged.face_types.get("cylinder"), Some(&1)); + let history = result.history().expect("the retry composes the tool's face history"); + history.check(&result, &[&target, &cutter]).unwrap(); + assert!(history.faces.iter().all(|f| !f.origins.is_empty())); +} + +#[test] +fn only_an_enclosing_wall_can_be_removed_and_cap_depth_stays_exact() { + let target = dome(); + assert!(relaxed_tool(&target, &tool(lens(24.), 30.)).is_none(), "a cylinder inside the sphere removes real material"); + let rectangle = + Region2 { outer: Loop2::polygon(&[Vec2::new(-4., 5.), Vec2::new(4., 5.), Vec2::new(4., 15.), Vec2::new(-4., 15.)]), holes: vec![] }; + assert!(relaxed_tool(&target, &tool(rectangle, 30.)).is_none()); + let cutter = tool(lens(25.), 7.); + let relaxed = relaxed_tool(&target, &cutter).unwrap(); + let bounds = crate::measure(&relaxed).unwrap().bbox; + assert!((bounds.min.y + 7.).abs() < 1e-6 && bounds.max.y > 0., "only the end outside the quarter ball is extended: {bounds:?}"); + let cut = crate::boolean(&target, &cutter, BoolOp::Cut).unwrap().unwrap(); + assert!(cut.contains(Vec3::new(0., -8., 15.)), "material past the pocket floor stays"); + assert!(!cut.contains(Vec3::new(0., -6., 15.)), "the shallow pocket removes material up to its floor"); + let box_target = crate::box_solid(Vec3::new(-25., -25., 0.), Vec3::new(25., 0., 25.)).unwrap(); + assert!(relaxed_tool(&box_target, &cutter).is_none()); +} From 3115c5035964b9c0cc1444221335f7149a39bdc4 Mon Sep 17 00:00:00 2001 From: SS-EN <84559909+SS-EN@users.noreply.github.com> Date: Mon, 19 Oct 2026 10:14:18 -0400 Subject: [PATCH 062/225] Chamfer: two distances and distance + angle on curved edges (#2893) Two-distance and distance + angle chamfers work on curved edges. --- crates/engine/src/tests.rs | 28 ++ crates/kernel/src/blend.rs | 90 +++++- .../kernel/src/chamfer_sides_curved_tests.rs | 257 ++++++++++++++++++ crates/kernel/src/lib.rs | 2 + crates/kernel/src/loopblend.rs | 178 ++++++++++-- 5 files changed, 519 insertions(+), 36 deletions(-) create mode 100644 crates/kernel/src/chamfer_sides_curved_tests.rs diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 844db5037..23b107875 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2691,6 +2691,34 @@ fn unequal_chamfers() { assert!(s.execute("solid.chamfer", &json!({"edges": [[0, 15, 20]], "distance": 1, "distance2": 2, "angle": "30 deg"})).is_err()); } +/// Unequal chamfers of a cylinder's circular rims: each cross-section is a right triangle +/// revolved about the axis (Pappus: area × the path of its centroid). +#[test] +fn unequal_chamfers_on_circular_rims() { + use std::f64::consts::PI; + let ring = |r: [f64; 3], legs: (f64, f64)| 2.0 * PI * (r[0] + r[1] + r[2]) / 3.0 * 0.5 * legs.0 * legs.1; + let mut s = Session::default(); + run(&mut s, "solid.cylinder", json!({"radius": 10, "height": 20})); + // The measured volume is of the meshed cylinder: compare what each chamfer takes away. + let full = volume(&mut s); + assert!(rel(full, PI * 100.0 * 20.0) < 1e-3); + // Top rim: 2 across the top (the face facing up), 3 down the wall. + run(&mut s, "solid.chamfer", json!({"edges": [[10, 0, 20]], "distance": 2, "distance2": 3})); + let top = ring([10.0, 8.0, 10.0], (2.0, 3.0)); + assert!(rel(full - volume(&mut s), top) < 5e-3, "{} vs {top}", full - volume(&mut s)); + // Bottom rim: 2 along the bottom at 30° from it (flipped: the wall would be first). + run(&mut s, "solid.chamfer", json!({"edges": [[10, 0, 0]], "distance": 2, "angle": "30 deg", "flip": true})); + let d2 = 2.0 * 30f64.to_radians().tan(); + let bottom = ring([10.0, 8.0, 10.0], (2.0, d2)); + assert!(rel(full - volume(&mut s), top + bottom) < 5e-3, "{} vs {}", full - volume(&mut s), top + bottom); + // Flipped on the top rim instead: 2 down the wall, 3 across the top (a different solid). + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "solid.chamfer", json!({"edges": [[10, 0, 20]], "distance": 2, "distance2": 3, "flip": true})); + let flipped = ring([10.0, 7.0, 10.0], (2.0, 3.0)); + assert!(rel(full - volume(&mut s), flipped) < 5e-3, "{} vs {flipped}", full - volume(&mut s)); +} + /// An enclosure built in the usual order: shell, bosses, then the lip on the rim. #[test] fn lip_after_boss() { diff --git a/crates/kernel/src/blend.rs b/crates/kernel/src/blend.rs index 7f0308793..7df495144 100644 --- a/crates/kernel/src/blend.rs +++ b/crates/kernel/src/blend.rs @@ -2295,9 +2295,11 @@ pub enum ChamferSide { Angle(f64), } -/// A chamfer with different setbacks on the two faces of each (straight) edge: `d1` along the -/// first face (the one facing up most, the other with `flip`), the second side by distance or -/// angle. +/// A chamfer with different setbacks on the two faces of each edge: `d1` along the first face +/// (the one facing up most, the other with `flip`), the second side by distance or angle. +/// Straight edges between planar faces are cut by prisms; curved edges where a planar face meets +/// a wall (a circular rim between a plane and a cylinder or cone, convex or concave, and loops of +/// lines and arcs) are chamfered along that face's loop. pub fn chamfer_sides(body: &Body, edges: &[Vec3], d1: f64, side: ChamferSide, flip: bool) -> Result { body.require_brep("chamfer")?; let ok = |x: f64| x.is_finite() && x > 1e-6 && x < 1e6; @@ -2314,15 +2316,85 @@ pub fn chamfer_sides(body: &Body, edges: &[Vec3], d1: f64, side: ChamferSide, fl } let size = crate::blend_fit::Size::Sides(d1, side, flip); let counts = record::counts(&[body]); - let mut cur = crate::boolean_record::operand(body, 0, &counts); - for (k, p) in edges.iter().enumerate() { - let t = chamfer_tool_sides(&cur, *p, d1, Some((side, flip)), k)?; - let step = cut_one(&cur, &t)?.ok_or_else(|| KernelError::Failed("the chamfer removed everything".into()))?; - cur = record::after(step, &cur, &counts); - } + let cut = || -> Result { + let mut cur = crate::boolean_record::operand(body, 0, &counts); + for (k, p) in edges.iter().enumerate() { + let t = chamfer_tool_sides(&cur, *p, d1, Some((side, flip)), k)?; + let step = cut_one(&cur, &t)?.ok_or_else(|| KernelError::Failed("the chamfer removed everything".into()))?; + cur = record::after(step, &cur, &counts); + } + Ok(cur) + }; + // A curved edge picked: the prisms cannot cut it, and cutting the others first moves what + // its pick lands on. + let picks_curved = { + let solid = body.deep_copy(); + let ids = edge_ids(body, &solid, edges)?; + guard("chamfer", || Ok(Body::unique_edges(&solid).iter().any(|x| ids.contains(&x.id()) && curved_case(&solid, x, false))))? + }; + let cur = match picks_curved { + true => chamfer_sides_curved(body, edges, d1, side, flip, None)?, + false => match cut() { + Ok(cur) => cur, + Err(e) => chamfer_sides_curved(body, edges, d1, side, flip, Some(e))?, + }, + }; crate::blend_fit::accept(body, cur, edges, size) } +/// [`chamfer_sides`] of a selection with curved edges, or one the prisms could not cut (`e`: +/// why) with edges running on smoothly into curved ones: whole loops of planar faces and runs of +/// one are chamfered along the loop ([`crate::loopblend::loop_chamfer_sides`]), other edges still +/// by a prism. A selection of straight edges only keeps the prisms' refusal. +fn chamfer_sides_curved(body: &Body, edges: &[Vec3], d1: f64, side: ChamferSide, flip: bool, e: Option) -> Result { + let counts = record::counts(&[body]); + let mut cur = crate::boolean_record::healed(body)?; + let curved = { + let solid = cur.deep_copy(); + let ids = edge_ids(&cur, &solid, edges)?; + guard("chamfer", || { + let all = Body::unique_edges(&solid); + let curved = |x: &mt::Edge| curved_case(&solid, x, false); + Ok(all + .iter() + .filter(|x| ids.contains(&x.id())) + .any(|x| curved(x) || smooth_chain(&solid, x).is_some_and(|chain| all.iter().any(|y| chain.contains(&y.id()) && curved(y))))) + })? + }; + if !curved { + return Err(e.unwrap_or_else(|| unsupported("these edges"))); + } + // The loop chamfer of the edges nearest `pts`, all on one planar face's loop. + let along_loop = |cur: &Body, pts: &[Vec3]| -> Result { + let size = cur.size(); + let solid = cur.deep_copy(); + let ids = edge_ids(cur, &solid, pts)?; + match crate::loopblend::loop_chamfer_sides(&solid, &ids, size, d1, side, flip) { + Some(res) => { + let (made, rec) = guard("chamfer", || res)?; + Ok(record::after(record::rebuilt(made, &[&solid], &rec)?, cur, &counts)) + } + None => Err(unsupported( + "a two-distance or distance-angle chamfer of a curved edge that is not on the boundary of a planar face (an equal-distance chamfer may work there)", + )), + } + }; + let (groups, rest) = loop_split(&cur, edges)?.unwrap_or_else(|| (Vec::new(), edges.to_vec())); + for g in &groups { + cur = along_loop(&cur, g)?; + } + for (k, p) in rest.iter().enumerate() { + cur = match chamfer_tool_sides(&cur, *p, d1, Some((side, flip)), k) { + Ok(t) => { + let step = cut_one(&cur, &t)?.ok_or_else(|| KernelError::Failed("the chamfer removed everything".into()))?; + record::after(step, &cur, &counts) + } + Err(_) => along_loop(&cur, std::slice::from_ref(p))?, + }; + } + Ok(cur) +} + /// The prism that cuts a chamfer: the body, which of its faces is the chamfer plane, and the /// edge (of the body it chamfers, in its edge order) that face is made in place of. pub(crate) struct Cutter { diff --git a/crates/kernel/src/chamfer_sides_curved_tests.rs b/crates/kernel/src/chamfer_sides_curved_tests.rs new file mode 100644 index 000000000..53e97e93d --- /dev/null +++ b/crates/kernel/src/chamfer_sides_curved_tests.rs @@ -0,0 +1,257 @@ +//! Two-distance and distance-angle chamfers of curved edges: a circular rim between a planar +//! face and a cylinder or cone, convex (a cylinder's top) and concave (a boss's foot), and a +//! hole's rim. Each chamfer's cross-section is a triangle revolved about the axis, so its volume +//! is the triangle's area times the path of its centroid (Pappus). + +use std::f64::consts::PI; + +use solidcraft_geom::{Loop2, Plane, Region2, Vec2, Vec3}; + +use crate::build::{box_solid, extrude, extrude_tapered}; +use crate::{Body, BoolOp, ChamferSide, KernelError, boolean, chamfer, chamfer_sides}; + +const TOL: f64 = 1e-3; + +fn volume(b: &Body) -> f64 { + b.volume_at(TOL).unwrap() +} + +fn rel(a: f64, b: f64) -> f64 { + (a - b).abs() / b.abs().max(1e-12) +} + +/// A cylinder of radius 10 and height 20 standing on XY, its seam at `seam`. +fn cylinder(seam: f64) -> Body { + let region = Region2 { outer: Loop2::circle_from(Vec2::ZERO, 10.0, seam), holes: vec![] }; + extrude(&Plane::XY, &[region], 0.0, 20.0).unwrap().pop().unwrap() +} + +/// The volume of the ring swept by the triangle `(r, z)` corners about the Z axis. +fn ring(t: [(f64, f64); 3]) -> f64 { + let [(r0, z0), (r1, z1), (r2, z2)] = t; + let area = 0.5 * ((r1 - r0) * (z2 - z0) - (r2 - r0) * (z1 - z0)).abs(); + 2.0 * PI * (r0 + r1 + r2) / 3.0 * area +} + +fn sound(b: &Body) { + assert!(b.validity().is_empty(), "{:?}", b.validity()); + assert_eq!(b.lumps().unwrap().len(), 1); +} + +const RIM: Vec3 = Vec3 { x: 10.0, y: 0.0, z: 20.0 }; + +#[test] +fn cylinder_rim_by_two_distances() { + for seam in [0.0, crate::build::SEAM_ANGLE] { + let c = cylinder(seam); + let base = volume(&c); + // 2 across the top (the face facing up), 3 down the wall. + let out = chamfer_sides(&c, &[RIM], 2.0, ChamferSide::Distance(3.0), false).unwrap(); + sound(&out); + let removed = ring([(10.0, 20.0), (8.0, 20.0), (10.0, 17.0)]); + assert!((removed - 56.0 * PI).abs() < 1e-9); + assert!(rel(volume(&out), base - removed) < 1e-5, "seam {seam}: {} vs {}", volume(&out), base - removed); + // Cone faces in place of the rim, as the equal chamfer's. + assert_eq!(out.face_count(), chamfer(&c, &[RIM], 2.0).unwrap().face_count()); + } +} + +#[test] +fn cylinder_rim_by_distance_and_angle() { + let c = cylinder(0.0); + let base = volume(&c); + // 2 across the top at 30° from it: down the wall 2·tan 30° (the faces are square). + let out = chamfer_sides(&c, &[RIM], 2.0, ChamferSide::Angle(30f64.to_radians()), false).unwrap(); + sound(&out); + let d2 = 2.0 * 30f64.to_radians().tan(); + let expected = base - ring([(10.0, 20.0), (8.0, 20.0), (10.0, 20.0 - d2)]); + assert!(rel(volume(&out), expected) < 1e-5, "{} vs {expected}", volume(&out)); +} + +#[test] +fn cylinder_rim_flipped() { + let c = cylinder(0.0); + let base = volume(&c); + // Flipped: the wall is the first face, 2 down it and 3 across the top. + let out = chamfer_sides(&c, &[RIM], 2.0, ChamferSide::Distance(3.0), true).unwrap(); + sound(&out); + let expected = base - ring([(10.0, 20.0), (7.0, 20.0), (10.0, 18.0)]); + assert!((base - expected - 54.0 * PI).abs() < 1e-9); + assert!(rel(volume(&out), expected) < 1e-5, "{} vs {expected}", volume(&out)); + // At 60° from the wall: across the top 2·tan 60°. + let out = chamfer_sides(&c, &[RIM], 2.0, ChamferSide::Angle(60f64.to_radians()), true).unwrap(); + let d2 = 2.0 * 60f64.to_radians().tan(); + let expected = base - ring([(10.0, 20.0), (10.0 - d2, 20.0), (10.0, 18.0)]); + assert!(rel(volume(&out), expected) < 1e-5, "{} vs {expected}", volume(&out)); +} + +/// The bottom rim, as a box's bottom edge: the bottom faces down, so the wall is the first face. +#[test] +fn cylinder_bottom_rim_takes_the_wall_first() { + let c = cylinder(0.0); + let base = volume(&c); + let out = chamfer_sides(&c, &[Vec3::new(10.0, 0.0, 0.0)], 2.0, ChamferSide::Distance(3.0), false).unwrap(); + sound(&out); + let expected = base - ring([(10.0, 0.0), (7.0, 0.0), (10.0, 2.0)]); + assert!(rel(volume(&out), expected) < 1e-5, "{} vs {expected}", volume(&out)); +} + +#[test] +fn equal_distances_are_unchanged() { + let c = cylinder(0.0); + let base = volume(&c); + let equal = chamfer(&c, &[RIM], 2.0).unwrap(); + let expected = base - ring([(10.0, 20.0), (8.0, 20.0), (10.0, 18.0)]); + assert!(rel(volume(&equal), expected) < 1e-5, "{} vs {expected}", volume(&equal)); + // Two equal distances, and 45° on square faces, are the same chamfer. + for side in [ChamferSide::Distance(2.0), ChamferSide::Angle(PI / 4.0)] { + let out = chamfer_sides(&c, &[RIM], 2.0, side, false).unwrap(); + assert!(rel(volume(&out), volume(&equal)) < 1e-7, "{side:?}: {} vs {}", volume(&out), volume(&equal)); + assert_eq!(out.face_count(), equal.face_count()); + } +} + +/// A 40 × 40 × 10 plate with a hole of radius 5 through it at (20, 20). +fn holed_plate() -> Body { + let plate = box_solid(Vec3::ZERO, Vec3::new(40.0, 40.0, 10.0)).unwrap(); + let hole = crate::build::cylinder(Vec3::new(20.0, 20.0, -5.0), Vec3::Z, 5.0, 20.0).unwrap(); + boolean(&plate, &hole, BoolOp::Cut).unwrap().unwrap() +} + +#[test] +fn hole_rim() { + let p = holed_plate(); + let base = volume(&p); + let rim = Vec3::new(25.0, 20.0, 10.0); + // 2 across the top, away from the hole, and 3 down its wall: a countersink. + let out = chamfer_sides(&p, &[rim], 2.0, ChamferSide::Distance(3.0), false).unwrap(); + sound(&out); + let removed = ring([(5.0, 10.0), (7.0, 10.0), (5.0, 7.0)]); + assert!((removed - 34.0 * PI).abs() < 1e-9); + assert!(rel(volume(&out), base - removed) < 1e-5, "{} vs {}", volume(&out), base - removed); + // Flipped, at 30° from the hole's wall. + let out = chamfer_sides(&p, &[rim], 2.0, ChamferSide::Angle(30f64.to_radians()), true).unwrap(); + sound(&out); + let d2 = 2.0 * 30f64.to_radians().tan(); + let expected = base - ring([(5.0, 10.0), (5.0 + d2, 10.0), (5.0, 8.0)]); + assert!(rel(volume(&out), expected) < 1e-5, "{} vs {expected}", volume(&out)); +} + +/// A concave rim: the foot of a boss of radius 5 standing 10 high on a 40 × 40 × 5 plate. +#[test] +fn boss_foot_fills() { + let plate = box_solid(Vec3::ZERO, Vec3::new(40.0, 40.0, 5.0)).unwrap(); + let boss = crate::build::cylinder(Vec3::new(20.0, 20.0, 5.0), Vec3::Z, 5.0, 10.0).unwrap(); + let b = boolean(&plate, &boss, BoolOp::Union).unwrap().unwrap(); + let base = volume(&b); + let foot = Vec3::new(25.0, 20.0, 5.0); + // The equal chamfer fills a ring. + let equal = chamfer(&b, &[foot], 2.0).unwrap(); + let filled = ring([(5.0, 5.0), (7.0, 5.0), (5.0, 7.0)]); + assert!(rel(volume(&equal), base + filled) < 1e-5, "{} vs {}", volume(&equal), base + filled); + // 2 across the plate (facing up), 3 up the boss. + let out = chamfer_sides(&b, &[foot], 2.0, ChamferSide::Distance(3.0), false).unwrap(); + sound(&out); + let filled = ring([(5.0, 5.0), (7.0, 5.0), (5.0, 8.0)]); + assert!(rel(volume(&out), base + filled) < 1e-5, "{} vs {}", volume(&out), base + filled); + // 2 up the boss at 30° from it. + let out = chamfer_sides(&b, &[foot], 2.0, ChamferSide::Angle(30f64.to_radians()), true).unwrap(); + sound(&out); + let d2 = 2.0 * 30f64.to_radians().tan(); + let filled = ring([(5.0, 5.0), (5.0 + d2, 5.0), (5.0, 7.0)]); + assert!(rel(volume(&out), base + filled) < 1e-5, "{} vs {}", volume(&out), base + filled); +} + +/// A frustum's top rim, between the top and a cone: the faces meet at 90° + the taper. +#[test] +fn cone_rim() { + let taper = 10f64.to_radians(); + let region = Region2 { outer: Loop2::circle_from(Vec2::ZERO, 10.0, 0.0), holes: vec![] }; + let f = extrude_tapered(&Plane::XY, ®ion, 20.0, 1.0, -taper).unwrap(); + let base = volume(&f); + let top = 10.0 - 20.0 * taper.tan(); + let rim = Vec3::new(top, 0.0, 20.0); + // Down the cone's slant, away from the top: (sin, −cos) of the taper. + let down = |d: f64| (top + d * taper.sin(), 20.0 - d * taper.cos()); + // The cone is meshed less closely than the cylinder: compare what the chamfer takes away + // (within the mesh's error, about 1e-3 of it at this tolerance). + let out = chamfer_sides(&f, &[rim], 2.0, ChamferSide::Distance(3.0), false).unwrap(); + sound(&out); + let removed = ring([(top, 20.0), (top - 2.0, 20.0), down(3.0)]); + assert!(rel(base - volume(&out), removed) < 3e-3, "{} vs {removed}", base - volume(&out)); + // By an angle: the triangle edge–A–B has φ = 90° + taper at the edge and 40° at A. + let a = 40f64.to_radians(); + let phi = PI / 2.0 + taper; + let d2 = 2.0 * a.sin() / (phi + a).sin(); + let out = chamfer_sides(&f, &[rim], 2.0, ChamferSide::Angle(a), false).unwrap(); + sound(&out); + let removed = ring([(top, 20.0), (top - 2.0, 20.0), down(d2)]); + assert!(rel(base - volume(&out), removed) < 3e-3, "{} vs {removed}", base - volume(&out)); + // The equal chamfer, as before. + let out = chamfer(&f, &[rim], 2.0).unwrap(); + let removed = ring([(top, 20.0), (top - 2.0, 20.0), down(2.0)]); + assert!(rel(base - volume(&out), removed) < 3e-3, "{} vs {removed}", base - volume(&out)); +} + +#[test] +fn too_large_or_unsupported_is_refused() { + let c = cylinder(0.0); + // Across the whole top: the cone would end in a point. + assert!(chamfer_sides(&c, &[RIM], 10.0, ChamferSide::Distance(3.0), false).is_err()); + assert!(chamfer_sides(&c, &[RIM], 12.0, ChamferSide::Distance(3.0), false).is_err()); + // Down past the bottom. + assert!(chamfer_sides(&c, &[RIM], 2.0, ChamferSide::Distance(25.0), false).is_err()); + // An angle that runs past the wall. + assert!(chamfer_sides(&c, &[RIM], 2.0, ChamferSide::Angle(PI / 2.0 + 0.01), false).is_err()); + // A cylinder's seam is smooth: nothing to chamfer. + assert!(chamfer_sides(&c, &[Vec3::new(10.0, 0.0, 10.0)], 2.0, ChamferSide::Distance(3.0), false).is_err()); + // A tilted cylinder cut flat: its rim on the cut is an ellipse, which the loop chamfer does + // not take. Refused as not supported, never a wrong solid. + let tilted = crate::build::cylinder(Vec3::new(0.0, 0.0, -10.0), Vec3::new(1.0, 0.0, 2.0), 5.0, 40.0).unwrap(); + let cut = box_solid(Vec3::new(-50.0, -50.0, 10.0), Vec3::new(50.0, 50.0, 50.0)).unwrap(); + let t = boolean(&tilted, &cut, BoolOp::Cut).unwrap().unwrap(); + let solid = t.deep_copy(); + let rim = crate::body::Body::unique_edges(&solid).iter().filter_map(crate::blend::edge_mid).find(|m| (m.z - 10.0).abs() < 1e-6).unwrap(); + match chamfer_sides(&t, &[rim], 1.0, ChamferSide::Distance(2.0), false) { + Err(KernelError::Failed(m)) => assert!(m.starts_with("not supported yet"), "{m}"), + Err(e) => panic!("{e}"), + Ok(_) => panic!("an unequal chamfer of an elliptical rim was built"), + } +} + +/// The top loop of a plate with rounded corners: lines and quarter circles, planar and +/// cylindrical walls, chamfered all round (every edge of the loop picked). +#[test] +fn rounded_plate_top_loop() { + let b = box_solid(Vec3::ZERO, Vec3::new(40.0, 30.0, 10.0)).unwrap(); + let corners = [Vec3::new(0.0, 0.0, 5.0), Vec3::new(40.0, 0.0, 5.0), Vec3::new(40.0, 30.0, 5.0), Vec3::new(0.0, 30.0, 5.0)]; + let b = crate::fillet(&b, &corners, 5.0).unwrap(); + let base = volume(&b); + let k = 5.0 * (1.0 - std::f64::consts::FRAC_1_SQRT_2); + let picks = [ + Vec3::new(20.0, 0.0, 10.0), + Vec3::new(40.0, 15.0, 10.0), + Vec3::new(20.0, 30.0, 10.0), + Vec3::new(0.0, 15.0, 10.0), + Vec3::new(k, k, 10.0), + Vec3::new(40.0 - k, k, 10.0), + Vec3::new(40.0 - k, 30.0 - k, 10.0), + Vec3::new(k, 30.0 - k, 10.0), + ]; + // Every pick is taken on the plate as given: cutting the lines first used to leave the arcs' + // picks nearest to the new chamfer faces' edges, which were cut instead (corner wedges). + let out = chamfer_sides(&b, &picks, 2.0, ChamferSide::Distance(3.0), false).unwrap(); + sound(&out); + // 100 of straight sides with the triangle (2 × 3) and four quarter rings about the corners. + let removed = 100.0 * 3.0 + ring([(5.0, 10.0), (3.0, 10.0), (5.0, 7.0)]); + assert!(rel(base - volume(&out), removed) < 2e-3, "{} vs {removed}", base - volume(&out)); + // Flipped: 2 down the walls, 3 across the top. + let out = chamfer_sides(&b, &picks, 2.0, ChamferSide::Distance(3.0), true).unwrap(); + sound(&out); + let removed = 100.0 * 3.0 + ring([(5.0, 10.0), (2.0, 10.0), (5.0, 8.0)]); + assert!(rel(base - volume(&out), removed) < 2e-3, "{} vs {removed}", base - volume(&out)); + // Equal distances: as the equal chamfer. + let equal = chamfer(&b, &picks, 2.0).unwrap(); + let out = chamfer_sides(&b, &picks, 2.0, ChamferSide::Distance(2.0), false).unwrap(); + assert!(rel(volume(&out), volume(&equal)) < 1e-9); +} diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rs index 4ea1228fb..046eb469c 100644 --- a/crates/kernel/src/lib.rs +++ b/crates/kernel/src/lib.rs @@ -28,6 +28,8 @@ mod boundary; mod boundary_network; mod bridge; mod build; +#[cfg(test)] +mod chamfer_sides_curved_tests; mod clearance; mod coaxial_overlap; mod continuity; diff --git a/crates/kernel/src/loopblend.rs b/crates/kernel/src/loopblend.rs index d9f97c047..89b21a2ef 100644 --- a/crates/kernel/src/loopblend.rs +++ b/crates/kernel/src/loopblend.rs @@ -5,13 +5,15 @@ //! gets a blend face: a cylinder (or plane, for a chamfer) along a line, a torus (or cone) along //! an arc, all meeting along the profile curves at the joints. Sharp joints at perpendicular //! curved walls follow the intersections of the exact offsets, fitted within tolerance. +//! A chamfer may also set back by different distances on the face and up the walls (two +//! distances, or a distance and an angle: [`loop_chamfer_sides`]). use std::collections::HashMap; use solidcraft_geom::Vec3; use truck_modeling::{self as mt, builder}; -use crate::blend::too_large; +use crate::blend::{ChamferSide, too_large}; use crate::body::{Solid, from_p3, p3, v3}; use crate::record::Rebuild; use crate::{KernelError, Result}; @@ -98,14 +100,15 @@ fn offset_joint(prev: &Seg, cur: &Seg, n: Vec3, d: f64) -> Option { /// A curved-wall joint is generally not planar. Fit its exact offset slices rather than /// projecting a circular section onto a tangent mitre and revolving that distorted section. -fn offset_profile(prev: &Seg, cur: &Seg, n: Vec3, side: f64, r: f64, round: bool, tol: f64) -> Result { +/// `(r, rw)`: the round's radius (`rw` unused), or a chamfer's setbacks on the face and up the wall. +fn offset_profile(prev: &Seg, cur: &Seg, n: Vec3, side: f64, (r, rw): (f64, f64), round: bool, tol: f64) -> Result { use mt::ParametricCurve; let point = |u: f64| { let (d, h) = if round { let (sin, cos) = (u * std::f64::consts::FRAC_PI_2).sin_cos(); (r * (1.0 - sin), r * (1.0 - cos)) } else { - (r * (1.0 - u), r * u) + (r * (1.0 - u), rw * u) }; offset_joint(prev, cur, n, d).map(|p| p + n * (side * h)) }; @@ -231,13 +234,40 @@ fn face_normal(f: &mt::Face, p: Vec3) -> Option { /// perpendicular walls, with what it built from `solid` (each blend face in place of its loop /// edge). `None` when the edges are not such a loop. pub(crate) fn loop_blend(solid: &Solid, edge_ids: &[mt::EdgeID], size: f64, r: f64, round: bool) -> Option> { - match crate::guard("loop blend", || Ok(loop_blend_inner(solid, edge_ids, size, r, round))) { + loop_blend_sized(solid, edge_ids, size, Sizing::Equal { r, round }) +} + +/// [`loop_blend`] as a chamfer of `d1` on its first face and the second side by `side`. The +/// first face is the one facing up most (the planar face or its wall, decided as for a straight +/// edge, see [`crate::chamfer_sides`]), the other one with `flip`. +pub(crate) fn loop_chamfer_sides( + solid: &Solid, + edge_ids: &[mt::EdgeID], + size: f64, + d1: f64, + side: ChamferSide, + flip: bool, +) -> Option> { + loop_blend_sized(solid, edge_ids, size, Sizing::Sides { d1, side, flip }) +} + +/// How large a loop blend is. +#[derive(Clone, Copy, Debug)] +enum Sizing { + /// A round of radius `r` (`round`), or an equal-distance chamfer of `r`. + Equal { r: f64, round: bool }, + /// A chamfer of `d1` on its first face, the second side by `side` ([`loop_chamfer_sides`]). + Sides { d1: f64, side: ChamferSide, flip: bool }, +} + +fn loop_blend_sized(solid: &Solid, edge_ids: &[mt::EdgeID], size: f64, sizing: Sizing) -> Option> { + match crate::guard("loop blend", || Ok(loop_blend_inner(solid, edge_ids, size, sizing))) { Ok(result) => result, Err(error) => Some(Err(error)), } } -fn loop_blend_inner(solid: &Solid, edge_ids: &[mt::EdgeID], size: f64, r: f64, round: bool) -> Option> { +fn loop_blend_inner(solid: &Solid, edge_ids: &[mt::EdgeID], size: f64, sizing: Sizing) -> Option> { #[cfg(test)] assert!(crate::guarded(), "loop selection must run inside the kernel guard"); let tol = (size * 1e-6).max(1e-7); @@ -251,7 +281,7 @@ fn loop_blend_inner(solid: &Solid, edge_ids: &[mt::EdgeID], size: f64, r: f64, r continue; } if ids.len() == edge_ids.len() { - return Some(build(solid, si, &faces, fi, wi, n, size, tol, r, round, None)); + return Some(build(solid, si, &faces, fi, wi, n, size, tol, sizing, None)); } // A run of neighbouring edges of the loop (its ends meet unblended edges). let m = ids.len(); @@ -260,7 +290,7 @@ fn loop_blend_inner(solid: &Solid, edge_ids: &[mt::EdgeID], size: f64, r: f64, r if let [s0] = starts[..] && (0..edge_ids.len()).all(|j| inside(s0 + j)) { - return Some(build(solid, si, &faces, fi, wi, n, size, tol, r, round, Some((s0, edge_ids.len())))); + return Some(build(solid, si, &faces, fi, wi, n, size, tol, sizing, Some((s0, edge_ids.len())))); } } } @@ -278,12 +308,17 @@ fn build( n: Vec3, size: f64, tol: f64, - r: f64, - round: bool, + sizing: Sizing, run: Option<(usize, usize)>, ) -> Result<(Solid, Rebuild)> { #[cfg(test)] assert!(crate::guarded(), "loop construction must run inside the kernel guard"); + // `r`: the round's radius or the equal chamfer's size; an unequal chamfer's first distance + // (its setbacks come from `frame`). + let (r, round, sides) = match sizing { + Sizing::Equal { r, round } => (r, round, None), + Sizing::Sides { d1, side, flip } => (d1, false, Some((side, flip))), + }; let f = faces.get(fi).ok_or_else(|| KernelError::Failed("face".into()))?; let wire = f.boundaries().get(wi).cloned().ok_or_else(|| KernelError::Failed("loop".into()))?; let all_edges: Vec = wire.edge_iter().cloned().collect(); @@ -384,16 +419,83 @@ fn build( let t = s.tangent(p)?.cross(gn).normalized()?; Some(if t.dot(n * side) < 0.0 { -t } else { t }) }; - let frame = |i: usize, p: Vec3| -> Option<(Vec3, Vec3, f64, f64)> { + // An unequal chamfer: whether its first side is the planar face (else the walls). As for a + // straight edge, that is the one facing up most (a curved wall by its mean normal along each + // edge), the other with `flip`; it must be the same all round the loop. + let face_first = match sides { + None => true, + Some((_, flip)) => { + use mt::{BoundedCurve, ParametricCurve}; + let up = Vec3::new(1e-6, 1e-3, 1.0); + let face_up = n.dot(up); + let mut first: Option = None; + for (pi, oi) in owner.iter().enumerate() { + if pi > 0 && owner.get(pi - 1) == Some(oi) { + continue; + } + let (Some(e), Some(g)) = (edges.get(*oi), walls.get(pi).and_then(|w| faces.get(*w))) else { + return Err(KernelError::Failed("loop edge".into())); + }; + let c = e.curve(); + let (t0, t1) = c.range_tuple(); + let ups: Vec = + (0..=8).filter_map(|j| face_normal(g, from_p3(c.subs(t0 + (t1 - t0) * f64::from(j) / 8.0))).map(|gn| gn.dot(up))).collect(); + if ups.is_empty() { + return Err(unsupported("wall normal")); + } + let wall_up = ups.iter().sum::() / ups.len() as f64; + let mine = (face_up >= wall_up) != flip; + if first.is_some_and(|x| x != mine) { + return Err(unsupported( + "an unequal chamfer round a loop whose first face changes along it (the face faces up more than some walls and less than others)", + )); + } + first = Some(mine); + } + first.unwrap_or(true) + } + }; + // Into the face (m), up the wall (t), the setbacks along each and the distance from the edge + // to a round's centre. + let frame = |i: usize, p: Vec3| -> Option<(Vec3, Vec3, f64, f64, f64)> { let s = segs.get(i)?; let (m, t) = (into(s, p), up(i, p)?); let phi = m.dot(t).clamp(-1.0, 1.0).acos(); if !(phi > 1e-3 && phi < std::f64::consts::PI - 1e-3) { return None; } - let sb = if round { r / (phi / 2.0).tan() } else { r }; - Some((m, t, sb, r / (phi / 2.0).sin())) + let (sf, sw) = match sides { + None => { + let sb = if round { r / (phi / 2.0).tan() } else { r }; + (sb, sb) + } + Some((cs, _)) => { + let d2 = match cs { + ChamferSide::Distance(d) => d, + // The triangle edge–A–B: angle φ at the edge, `a` at A (on the first side). + ChamferSide::Angle(a) => { + let den = (phi + a).sin(); + if den <= 1e-9 { + return None; + } + r * a.sin() / den + } + }; + if face_first { (r, d2) } else { (d2, r) } + } + }; + Some((m, t, sf, sw, r / (phi / 2.0).sin())) }; + if let Some((ChamferSide::Angle(a), _)) = sides { + for (i, s) in segs.iter().enumerate() { + let p = s.start(); + if let Some(t) = up(i, p) + && (into(s, p).dot(t).clamp(-1.0, 1.0).acos() + a).sin() <= 1e-9 + { + return Err(KernelError::Invalid("that chamfer angle runs past the other face".into())); + } + } + } // The straight seam between the walls at a sharp joint (direction away from the face). let seam_dir = |i: usize, p: Vec3| -> Option { let o = owner.get(i)?; @@ -426,17 +528,17 @@ fn build( let joint_point = |i: usize| if i < k { segs.get(i).map(|s| s.start()) } else { segs.last().map(|s| s.end()) }; for i in 0..nj { let p = joint_point(i).unwrap_or_default(); - let (m, t, sb, dc) = frame(i.min(k - 1), p).ok_or_else(|| unsupported("the face and wall meet at an angle the blend can't take"))?; + let (m, t, sb, sbw, dc) = frame(i.min(k - 1), p).ok_or_else(|| unsupported("the face and wall meet at an angle the blend can't take"))?; centres.push(p + (m + t).normalized().unwrap_or(m) * dc); if !mitre.get(i).copied().unwrap_or(false) { pa.push(p + m * sb); - pb.push(p + t * sb); + pb.push(p + t * sbw); continue; } // Sharp joint: the face rails meet where the two offset lines cross; the wall rails // meet on the seam. let ip = (i + k - 1) % k; - let (m0, t0, sb0, _) = frame(ip, p).ok_or_else(|| unsupported("the face and wall meet at an angle the blend can't take"))?; + let (m0, t0, sb0, sbw0, _) = frame(ip, p).ok_or_else(|| unsupported("the face and wall meet at an angle the blend can't take"))?; let (Some(d0), Some(d1)) = (segs.get(ip).and_then(|x| x.tangent(p)), segs.get(i).and_then(|x| x.tangent(p))) else { return Err(unsupported("degenerate loop edge")); }; @@ -447,7 +549,9 @@ fn build( && t0.dot(n * side) > 1.0 - 1e-9; if exact { let (Some(prev), Some(cur)) = (segs.get(ip), segs.get(i)) else { return Err(unsupported("corner segments")) }; - pa.push(offset_joint(prev, cur, n, r).ok_or_else(|| too_large("the blend's offset walls do not meet"))?); + pa.push( + offset_joint(prev, cur, n, if sides.is_some() { sb } else { r }).ok_or_else(|| too_large("the blend's offset walls do not meet"))?, + ); if let Some(slot) = curved_joint.get_mut(i) { *slot = true; } @@ -456,10 +560,10 @@ fn build( } let e = seam_dir(i, p).ok_or_else(|| unsupported("a sharp corner without one straight seam"))?; let (h0, h1) = (e.dot(t0), e.dot(t)); - if h0 < 1e-6 || h1 < 1e-6 || (sb0 / h0 - sb / h1).abs() > tol * 10.0 { + if h0 < 1e-6 || h1 < 1e-6 || (sbw0 / h0 - sbw / h1).abs() > tol * 10.0 { return Err(unsupported("a sharp corner whose walls meet the blend differently")); } - pb.push(p + e * (sb / h1)); + pb.push(p + e * (sbw / h1)); } // Sharp joints between straight rim edges can extend beyond the old corner. // Equal wall slopes reach this path instead of the corner builder, and must @@ -480,6 +584,14 @@ fn build( for (i, s) in segs.iter().enumerate() { if let Seg::Arc { a, c, .. } = *s { let toward = into(s, a).dot(c - a) > 0.0; + // An unequal chamfer's offset on the face; it never ends in a point (a cone's apex). + if sides.is_some() { + let reach = frame(i, a).map(|x| x.2).ok_or_else(|| unsupported("the face and wall meet at an angle the blend can't take"))?; + if toward && a.dist(c) <= reach + tol * 10.0 { + return Err(too_large("the chamfer is larger than a corner radius")); + } + continue; + } if toward && (a.dist(c) - r).abs() <= tol * 10.0 && !mitre.get(i).copied().unwrap_or(true) && !mitre.get(nxt(i)).copied().unwrap_or(true) { if let Some(x) = collapsed.get_mut(i) { @@ -548,7 +660,11 @@ fn build( let (Some(a), Some(b)) = (va.get(i), vb.get(i)) else { return Err(KernelError::Failed("joint".into())) }; if curved_joint.get(i).copied().unwrap_or(false) { let (Some(prev), Some(cur)) = (segs.get((i + k - 1) % k), segs.get(i)) else { return Err(unsupported("corner segments")) }; - let curve = offset_profile(prev, cur, n, side, r, round, (r * 1e-7).max(1e-9))?; + let setbacks = match sides { + None => (r, r), + Some(_) => joint_point(i).and_then(|p| frame(i.min(k - 1), p)).map(|x| (x.2, x.3)).ok_or_else(|| unsupported("frame"))?, + }; + let curve = offset_profile(prev, cur, n, side, setbacks, round, (setbacks.0.min(setbacks.1) * 1e-7).max(1e-9))?; profiles.push(mt::Edge::try_new(a, b, curve).map_err(|e| KernelError::Failed(format!("curved corner: {e}")))?); continue; } @@ -566,7 +682,7 @@ fn build( let d1 = segs.get(i).and_then(|x| x.tangent(p)).ok_or_else(|| unsupported("tangent"))?; let (pa_i, pb_i) = (from_p3(a.point()), from_p3(b.point())); let lam = (pa_i - p).dot(d1); - let (_, t, sb, _) = frame(i, p).ok_or_else(|| unsupported("frame"))?; + let (_, t, sb, _, _) = frame(i, p).ok_or_else(|| unsupported("frame"))?; let cc = centre(i) + d1 * lam; let q = p + t * sb + d1 * lam; let mid = cc + ((pa_i - cc) + (q - cc)).normalized().unwrap_or(t) * r; @@ -604,11 +720,11 @@ fn build( let piece_of = |s: &Seg| segs.iter().position(|x| std::ptr::eq(x, s)).unwrap_or(0); let face_off = |p: Vec3, s: &Seg| { let i = piece_of(s); - frame(i, p).map(|(m, _, sb, _)| p + m * sb).unwrap_or(p) + frame(i, p).map(|(m, _, sb, _, _)| p + m * sb).unwrap_or(p) }; let wall_off = |p: Vec3, s: &Seg| { let i = piece_of(s); - frame(i, p).map(|(_, t, sb, _)| p + t * sb).unwrap_or(p) + frame(i, p).map(|(_, t, _, sbw, _)| p + t * sbw).unwrap_or(p) }; let face_rails: Vec> = (0..k).map(|i| rail(&va, i, &face_off)).collect(); if face_rails.iter().zip(&collapsed).any(|(r, c)| r.is_none() && !c) { @@ -773,11 +889,11 @@ fn build( // The cross-section at the start, swept along the whole edge and beyond (the // face may reach past the edge's ends at a mitre). let d = (b - a).normalized().ok_or_else(|| unsupported("degenerate loop edge"))?; - let (_, t, sb, _) = frame(i, a).ok_or_else(|| unsupported("frame"))?; + let (_, t, sb, sbw, _) = frame(i, a).ok_or_else(|| unsupported("frame"))?; let m = into(s, a); let ext = size; let back = d * -ext; - let (fa, wa) = (builder::vertex(p3(a + m * sb + back)), builder::vertex(p3(a + t * sb + back))); + let (fa, wa) = (builder::vertex(p3(a + m * sb + back)), builder::vertex(p3(a + t * sbw + back))); let base = if round { builder::circle_arc(&fa, &wa, p3(profile_mid(i) + back)) } else { builder::line(&fa, &wa) }; vec![builder::tsweep(&base, v3(b - a + d * (2.0 * ext)))].into() } @@ -801,16 +917,24 @@ fn build( Seg::Arc { a, c, axis, angle, .. } => { // Sweep a radial section, not the shared corner curve: the latter can be // nonplanar and would change the round's radius all along this edge. - let (_, t, sb, _) = frame(i, a).ok_or_else(|| unsupported("frame"))?; - let (fa, wa) = (builder::vertex(p3(a + into(s, a) * sb)), builder::vertex(p3(a + t * sb))); + let (_, t, sb, sbw, _) = frame(i, a).ok_or_else(|| unsupported("frame"))?; + let (fa, wa) = (builder::vertex(p3(a + into(s, a) * sb)), builder::vertex(p3(a + t * sbw))); let base = if round { builder::circle_arc(&fa, &wa, p3(profile_mid(i))) } else { builder::line(&fa, &wa) }; builder::rsweep(&base, p3(c), v3(axis), mt::Rad(angle)) } }; let mut surf = swept.face_iter().next().map(|x| x.oriented_surface()).ok_or_else(|| KernelError::Failed("blend surface".into()))?; // Outward: toward the profile centre on a concave loop, away from it on a convex one. + // An unequal chamfer's profile has no centre: its middle, away from the edge on a concave + // loop (where the chamfer fills) and toward it on a convex one. let (c, mid) = (centre(i), profile_mid(i)); - let outward = (c - mid) * side; + let (mid, outward) = match (sides, joint_point(i)) { + (Some(_), Some(p)) => { + let m = (from_p3(pr.front().point()) + from_p3(pr.back().point())) * 0.5; + (m, (m - p) * side) + } + _ => (mid, (c - mid) * side), + }; if let Some((u, v)) = surf.search_nearest_parameter(p3(mid), None, 100) { let nn = surf.normal(u, v); if Vec3::new(nn.x, nn.y, nn.z).dot(outward) < 0.0 { From fb82ccb27356f9c4fbcb0bcdfc7901a888c87837 Mon Sep 17 00:00:00 2001 From: SS-EN <84559909+SS-EN@users.noreply.github.com> Date: Mon, 19 Oct 2026 10:14:23 -0400 Subject: [PATCH 063/225] Timeline/MCP API: suppress lists, dotted edit keys, set_parameter expression (#2899) Timeline and MCP edits take suppress lists, dotted edit keys and parameter expressions. --- crates/engine/src/cmd/edit.rs | 239 +++++++++++++++++++++++++--- crates/engine/src/cmd/edit_tests.rs | 130 +++++++++++++++ crates/engine/src/params.rs | 8 +- crates/mcp/src/tests.rs | 27 ++++ crates/mcp/src/tools.rs | 28 +++- docs/mcp.md | 2 +- 6 files changed, 401 insertions(+), 33 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 67d682d03..fc8e4b45a 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -25,7 +25,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .at("SOLID", "MODIFY") .icon("delete") .key("Delete") - .params("features: [id or name] (a sketch takes its dependent features with it) → deleted: [ids]; failing?: [{feature, error}] (later features that worked and now fail)"), + .params("feature: id|name | features: [id|name] (one undo step; a sketch takes its dependent features with it) → deleted: [ids]; failing?: [{feature, error}] (later features that worked and now fail)"), CommandSpec::new("timeline.rename", "Rename", rename).icon("rename").params("feature: id|name, name (references to it follow)"), CommandSpec::new("timeline.group", "New Feature Folder", group) .icon("folder") @@ -54,11 +54,15 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("timeline.dependents", "Feature Dependents", dependents).icon("graph") .noundo() .params("feature: id|name → features deleted with it, and features that would fail without it"), - CommandSpec::new("timeline.suppress", "Suppress Feature", suppress).icon("suppress").params("feature: id|name, suppressed?: bool (default toggles)"), + CommandSpec::new("timeline.suppress", "Suppress Feature", suppress).icon("suppress").params( + "feature: id|name | features: [id|name] (one undo step), suppressed?: bool (default toggles: several features are all \ + suppressed unless all of them already are, then all are unsuppressed) → feature: id (or features: [ids]), suppressed", + ), CommandSpec::new("timeline.edit", "Edit Feature", edit_feature).icon("edit").params( "feature: id|name, set: {fields to change, merged into the feature's definition as timeline.inspect returns it, \ e.g. {\"extent\": {\"distance\": \"30\"}} (extrude), {\"angle\": \"90 deg\"} (revolve); \ - expressions are text} → recomputed: features rebuilt, restored: features whose earlier result for the same inputs was reused", + a dotted key names a nested field ({\"plane.distance\": \"8 mm\"} = {\"plane\": {\"distance\": \"8 mm\"}}); \ + expressions are text, or a number in mm or degrees} → recomputed: features rebuilt, restored: features whose earlier result for the same inputs was reused", ), CommandSpec::new("timeline.inspect", "Inspect Feature", inspect_feature).icon("inspect").noundo().params( "feature: id|name → type, definition (the fields timeline.edit's set changes, with their current values), \ @@ -529,12 +533,52 @@ fn rollback(s: &mut Session, p: &Value) -> Result { Ok(json!({"marker": s.doc.marker.unwrap_or(n), "features": n})) } +/// The features named by `feature: id|name` and/or `features: [id|name]` (or one id|name), in +/// the order given and without repeats. Each must exist. +fn feature_ids(s: &Session, p: &Value, cmd: &str) -> Result> { + let mut given: Vec<&Value> = Vec::new(); + if let Some(f) = p.get("feature").filter(|v| !v.is_null()) { + given.push(f); + } + match p.get("features") { + None | Some(Value::Null) => {} + Some(Value::Array(a)) if a.len() <= 10_000 => given.extend(a), + Some(Value::Array(_)) => return Err(bad(cmd, "too many features")), + Some(one @ (Value::Number(_) | Value::String(_))) => given.push(one), + Some(_) => return Err(bad(cmd, "`features` must be a list of feature ids or names")), + } + if given.is_empty() { + return Err(bad(cmd, "`feature` (id or name) or `features` (a list of them) must name a feature")); + } + let mut ids = Vec::new(); + for v in given { + let id = feature_id(s, Some(v), cmd)?; + if !ids.contains(&id) { + ids.push(id); + } + } + Ok(ids) +} + fn suppress(s: &mut Session, p: &Value) -> Result { - let id = feature_id(s, p.get("feature"), "timeline.suppress")?; - let want = bool_(p, "suppressed"); - let f = s.doc_mut().feature_mut(id).ok_or_else(|| EngineError::Other("feature".into()))?; - f.suppressed = want.unwrap_or(!f.suppressed); - Ok(json!({"feature": id, "suppressed": f.suppressed})) + let cmd = "timeline.suppress"; + let ids = feature_ids(s, p, cmd)?; + let want = match bool_(p, "suppressed") { + Some(b) => b, + None if p.get("suppressed").is_some_and(|v| !v.is_null()) => return Err(bad(cmd, "`suppressed` must be true or false")), + // Toggle: one feature flips; several are all suppressed unless all already are. + None => !ids.iter().all(|id| s.doc.feature(*id).is_some_and(|f| f.suppressed)), + }; + // One command, so one undo step however many features it changes. + let doc = s.doc_mut(); + for id in &ids { + let f = doc.feature_mut(*id).ok_or_else(|| bad(cmd, format!("no feature {id}")))?; + f.suppressed = want; + } + match ids.as_slice() { + [id] if p.get("features").is_none_or(Value::is_null) => Ok(json!({"feature": id, "suppressed": want})), + _ => Ok(json!({"features": ids, "suppressed": want})), + } } fn merge(dst: &mut Value, src: &Value, depth: usize) { @@ -643,17 +687,20 @@ fn unknown_field( } /// "unknown field `offset`; ConstructionPlane has `plane.base.name`, `plane.distance`…": the -/// editable fields where it was given, as paths. -fn unknown_field_message(field: &[Step], def: &Value, type_name: &str) -> String { - fn leaves(v: &Value, prefix: &str, top: bool, depth: usize, out: &mut Vec) { +/// editable fields where it was given, as paths (each one timeline.edit's `set` takes as a key). +fn unknown_field_message(field: &[Step], def: &Value, kind: &FeatureKind) -> String { + let type_name = kind.type_name(); + let heavy = heavy_fields(kind); + let skip = |k: &str| NOT_EDITABLE.contains(&k) || heavy.iter().any(|(h, _)| *h == k); + fn leaves(v: &Value, prefix: &str, skip: Option<&dyn Fn(&str) -> bool>, depth: usize, out: &mut Vec) { match v { Value::Object(o) if depth < 4 && !o.is_empty() => { for (k, x) in o { - if top && NOT_EDITABLE.contains(&k.as_str()) { + if skip.is_some_and(|skip| skip(k)) { continue; } let at = if prefix.is_empty() { k.clone() } else { format!("{prefix}.{k}") }; - leaves(x, &at, false, depth + 1, out); + leaves(x, &at, None, depth + 1, out); } } _ if !prefix.is_empty() => out.push(format!("`{prefix}`")), @@ -663,7 +710,8 @@ fn unknown_field_message(field: &[Step], def: &Value, type_name: &str) -> String let parent = field.split_last().map(|(_, p)| p).unwrap_or_default(); let mut known = Vec::new(); if let Some(at) = at_path(def, parent) { - leaves(at, &path_text(parent), parent.is_empty(), 0, &mut known); + let top: Option<&dyn Fn(&str) -> bool> = if parent.is_empty() { Some(&skip) } else { None }; + leaves(at, &path_text(parent), top, 0, &mut known); } const SHOWN: usize = 40; let more = known.len().saturating_sub(SHOWN); @@ -679,6 +727,140 @@ fn unknown_field_message(field: &[Step], def: &Value, type_name: &str) -> String format!("unknown field `{field}`; {type_name} has {list} (timeline.inspect shows them with their values)") } +/// `set` with dotted keys (`"plane.distance"`, as timeline.edit's unknown-field message lists the +/// fields) expanded into the nested form (`{"plane": {"distance": …}}`), merged with any nested +/// form given next to them. A key the definition itself has at that level stays as it is. A field +/// given twice (`plane.distance` and `plane: {distance}`) is refused. +fn expand_dotted(set: &Value, def: Option<&Value>, cmd: &str, depth: usize) -> Result { + if depth > 16 { + return Ok(set.clone()); + } + match set { + Value::Object(o) => { + let mut nested = serde_json::Map::new(); + for (k, v) in o { + let parts: Vec<&str> = k.split('.').collect(); + let literal = parts.len() == 1 || parts.len() > 16 || parts.iter().any(|x| x.is_empty()) || def.and_then(|d| d.get(k)).is_some(); + let parts = if literal { vec![k.as_str()] } else { parts }; + insert_field(&mut nested, &parts, v.clone(), k, cmd)?; + } + let mut out = serde_json::Map::new(); + for (k, v) in nested { + let d = def.and_then(|d| d.get(&k)); + out.insert(k, expand_dotted(&v, d, cmd, depth + 1)?); + } + Ok(Value::Object(out)) + } + Value::Array(a) => a + .iter() + .enumerate() + .map(|(i, v)| expand_dotted(v, def.and_then(|d| d.get(i)), cmd, depth + 1)) + .collect::>>() + .map(Value::Array), + _ => Ok(set.clone()), + } +} + +/// Put `v` at `parts` in `out`, creating the objects on the way; `key` is the field as given. +fn insert_field(out: &mut serde_json::Map, parts: &[&str], v: Value, key: &str, cmd: &str) -> Result<()> { + let twice = || bad(cmd, format!("`{key}` is given twice (as a dotted key and in the nested form)")); + let Some((last, parents)) = parts.split_last() else { return Ok(()) }; + let mut at = out; + for part in parents { + let slot = at.entry(part.to_string()).or_insert_with(|| Value::Object(serde_json::Map::new())); + at = slot.as_object_mut().ok_or_else(twice)?; + } + match (at.get_mut(*last), v) { + (None, v) => { + at.insert(last.to_string(), v); + } + (Some(Value::Object(slot)), Value::Object(more)) => { + for (k, x) in more { + insert_field(slot, &[k.as_str()], x, key, cmd)?; + } + } + (Some(_), _) => return Err(twice()), + } + Ok(()) +} + +fn at_path_mut<'a>(v: &'a mut Value, path: &[Step]) -> Option<&'a mut Value> { + path.iter().try_fold(v, |v, s| match s { + Step::Key(k) => v.get_mut(k), + Step::Index(i) => v.get_mut(*i), + }) +} + +/// Paths of the finite numbers in `set` where the definition (`before`) has no number. +fn number_leaves(set: &Value, before: &Value, path: &mut Vec, out: &mut Vec>, depth: usize) { + if depth > 16 || out.len() >= 1_000 { + return; + } + match set { + Value::Object(o) => { + for (k, v) in o { + path.push(Step::Key(k.clone())); + number_leaves(v, before, path, out, depth + 1); + path.pop(); + } + } + Value::Array(a) => { + for (i, v) in a.iter().enumerate().take(10_000) { + path.push(Step::Index(i)); + number_leaves(v, before, path, out, depth + 1); + path.pop(); + } + } + Value::Number(n) if crate::params::number_text(n).is_some() && !matches!(at_path(before, path), Some(Value::Number(_))) => { + out.push(path.clone()); + } + _ => {} + } +} + +/// Finite numbers given for expression fields become the expression's text (`8` → `"8"`, mm or +/// degrees by context), as the feature commands take them (`params::expr`). Which fields are +/// expressions is what the feature's own walk says: each number is put in as a marker text, and +/// the markers the feature then shows among its expressions are expression fields. Numbers +/// anywhere else stay numbers. +fn numbers_as_expressions(mut set: Value, before: &Value) -> Value { + let mut found = Vec::new(); + number_leaves(&set, before, &mut Vec::new(), &mut found, 0); + if found.is_empty() { + return set; + } + let marker = |i: usize| format!("\u{1}number {i}"); + // The markers among the feature's expressions with the numbers at `which` marked, or None + // when the feature doesn't read that way. + let expressions = |which: &[usize]| -> Option> { + let mut marked = set.clone(); + for &i in which { + if let Some(slot) = found.get(i).and_then(|path| at_path_mut(&mut marked, path)) { + *slot = Value::String(marker(i)); + } + } + let mut v = before.clone(); + merge(&mut v, &marked, 0); + let f: Feature = serde_json::from_value(v).ok()?; + Some(f.kind.expressions().into_iter().filter(|e| e.starts_with('\u{1}')).map(str::to_string).collect()) + }; + let all: Vec = (0..found.len()).collect(); + let hits: Vec = match expressions(&all) { + Some(e) => all.into_iter().filter(|i| e.contains(&marker(*i))).collect(), + // Some of them are numbers after all: one at a time. + None => all.into_iter().take(64).filter(|i| expressions(&[*i]).is_some_and(|e| e.contains(&marker(*i)))).collect(), + }; + for i in hits { + if let Some(slot) = found.get(i).and_then(|path| at_path_mut(&mut set, path)) + && let Value::Number(n) = slot + && let Some(text) = crate::params::number_text(n) + { + *slot = Value::String(text); + } + } + set +} + /// `profiles` (also a loft section's) given as the feature commands take it (`"all"`, /// `[index]`, `[{curves}]`, `[{point}]`...) becomes the stored form; the stored form passes. fn command_profiles(set: &Value, cmd: &str) -> Result { @@ -706,6 +888,17 @@ fn command_profiles(set: &Value, cmd: &str) -> Result { /// the name and suppression, which timeline.rename and timeline.suppress change. const NOT_EDITABLE: &[&str] = &["id", "type", "name", "suppressed", "param_names", "edge_refs", "edge_names", "face_names"]; +/// Large payloads that timeline.edit cannot change, left out of a feature's definition: (field, +/// what it holds). +fn heavy_fields(kind: &FeatureKind) -> &'static [(&'static str, &'static str)] { + match kind { + FeatureKind::Sketch { .. } => &[("sketch", "the sketch geometry (sketch.inspect; edit it with the sketch commands)")], + FeatureKind::Import { .. } => &[("step", "the imported STEP text"), ("components", "the imported product tree")], + FeatureKind::MeshImport { .. } => &[("meshes", "the imported meshes")], + _ => &[], + } +} + fn inspect_feature(s: &mut Session, p: &Value) -> Result { let cmd = "timeline.inspect"; let id = feature_id(s, p.get("feature"), cmd)?; @@ -716,14 +909,7 @@ fn inspect_feature(s: &mut Session, p: &Value) -> Result { for k in NOT_EDITABLE { o.remove(*k); } - // Large payloads that timeline.edit cannot change. - let heavy: &[(&str, &str)] = match &f.kind { - FeatureKind::Sketch { .. } => &[("sketch", "the sketch geometry (sketch.inspect; edit it with the sketch commands)")], - FeatureKind::Import { .. } => &[("step", "the imported STEP text"), ("components", "the imported product tree")], - FeatureKind::MeshImport { .. } => &[("meshes", "the imported meshes")], - _ => &[], - }; - for (k, why) in heavy { + for (k, why) in heavy_fields(&f.kind) { if o.remove(*k).is_some() { omitted.push(json!({"field": k, "what": why})); } @@ -754,8 +940,10 @@ fn edit_feature(s: &mut Session, p: &Value) -> Result { let id = feature_id(s, p.get("feature"), cmd)?; let set = p.get("set").filter(|v| v.is_object()).ok_or_else(|| bad(cmd, "`set` must be an object of fields"))?; let f = s.doc.feature(id).cloned().ok_or_else(|| bad(cmd, "feature"))?; - let mut v = serde_json::to_value(&f).map_err(|e| EngineError::Other(e.to_string()))?; - let set = &command_profiles(set, cmd)?; + let before = serde_json::to_value(&f).map_err(|e| EngineError::Other(e.to_string()))?; + let set = expand_dotted(set, Some(&before), cmd, 0)?; + let set = &numbers_as_expressions(command_profiles(&set, cmd)?, &before); + let mut v = before.clone(); merge(&mut v, set, 0); let mut nf: Feature = serde_json::from_value(v.clone()).map_err(|e| bad(cmd, format!("invalid feature: {e}")))?; nf.id = f.id; @@ -772,9 +960,8 @@ fn edit_feature(s: &mut Session, p: &Value) -> Result { // serde drops fields the definition doesn't have without a word: refuse them, or a typo // would report success and change nothing. let after = serde_json::to_value(&nf).map_err(|e| EngineError::Other(e.to_string()))?; - let before = serde_json::to_value(&f).map_err(|e| EngineError::Other(e.to_string()))?; if let Some(field) = unknown_field(set, Some(&before), Some(&after), &v, &mut Vec::new(), 0) { - return Err(bad(cmd, unknown_field_message(&field, &before, f.kind.type_name()))); + return Err(bad(cmd, unknown_field_message(&field, &before, &f.kind))); } if let FeatureKind::BodyTransfer { bodies, from, to, transform } = &nf.kind { solidcraft_doc::validate_body_transfer(&s.doc, &solidcraft_doc::plain(bodies), *from, *to, transform)?; diff --git a/crates/engine/src/cmd/edit_tests.rs b/crates/engine/src/cmd/edit_tests.rs index a5381f327..9e78e2a14 100644 --- a/crates/engine/src/cmd/edit_tests.rs +++ b/crates/engine/src/cmd/edit_tests.rs @@ -544,3 +544,133 @@ fn edit_refuses_unknown_fields() { let def = run(&mut s, "timeline.inspect", json!({"feature": "Twin"}))["definition"].clone(); assert_eq!(def["combine"], json!(true), "{def}"); } + +fn suppressed(s: &Session, name: &str) -> bool { + s.doc.find_feature(name).unwrap().suppressed +} + +/// timeline.suppress takes `features: [..]` as timeline.delete does, as one undo step; it used to +/// refuse it ("`feature` must be an id or name"). +#[test] +fn suppress_takes_a_list_of_features_as_one_undo_step() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "name": "A"})); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [20, 0, 0], "name": "B"})); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [40, 0, 0], "name": "C"})); + let id = |s: &Session, name: &str| s.doc.find_feature(name).unwrap().id; + let undo = s.undo.len(); + let a = id(&s, "A"); + let r = run(&mut s, "timeline.suppress", json!({"features": [a, "B"], "suppressed": true})); + assert_eq!(r, json!({"features": [id(&s, "A"), id(&s, "B")], "suppressed": true})); + assert!(suppressed(&s, "A") && suppressed(&s, "B") && !suppressed(&s, "C")); + assert_eq!(s.undo.len(), undo + 1, "one undo step"); + assert_eq!(s.model.state().bodies.len(), 1); + run(&mut s, "edit.undo", json!({})); + assert!(!suppressed(&s, "A") && !suppressed(&s, "B")); + assert_eq!(s.model.state().bodies.len(), 3); + + // Toggling several: all suppressed unless all already are, then all unsuppressed. + run(&mut s, "timeline.suppress", json!({"feature": "A"})); + run(&mut s, "timeline.suppress", json!({"features": ["A", "B", "C"]})); + assert!(suppressed(&s, "A") && suppressed(&s, "B") && suppressed(&s, "C")); + run(&mut s, "timeline.suppress", json!({"features": ["A", "B", "C"]})); + assert!(!suppressed(&s, "A") && !suppressed(&s, "B") && !suppressed(&s, "C")); + // `feature` and `features` together; a repeat counts once. + let r = run(&mut s, "timeline.suppress", json!({"feature": "C", "features": ["C", "B"], "suppressed": true})); + assert_eq!(r["features"], json!([id(&s, "C"), id(&s, "B")]), "{r}"); + assert!(!suppressed(&s, "A") && suppressed(&s, "B") && suppressed(&s, "C")); + // A single `feature` replies as before. + let r = run(&mut s, "timeline.suppress", json!({"feature": "C", "suppressed": false})); + assert_eq!(r, json!({"feature": id(&s, "C"), "suppressed": false})); + + // An unknown feature in the list refuses the whole command, as do no features at all. + let before = (*s.doc).clone(); + let undo = s.undo.len(); + for bad in [ + json!({"features": ["A", "Nope"], "suppressed": true}), + json!({"features": []}), + json!({}), + json!({"features": [{}]}), + json!({"features": ["A"], "suppressed": "yes"}), + ] { + assert!(s.execute("timeline.suppress", &bad).is_err(), "{bad}"); + } + assert_eq!(*s.doc, before); + assert_eq!(s.undo.len(), undo); + // timeline.delete takes either. + run(&mut s, "timeline.delete", json!({"feature": "C"})); + run(&mut s, "timeline.delete", json!({"features": ["B"]})); + assert!(s.doc.find_feature("B").is_none() && s.doc.find_feature("C").is_none()); +} + +/// The value at a dotted path of a definition. +fn dotted<'a>(def: &'a Value, path: &str) -> &'a Value { + path.split('.').fold(def, |v, k| &v[k]) +} + +/// The lowest Z of the design's first body. +fn low_z(s: &mut Session) -> f64 { + let m = run(s, "inspect.measure", json!({})); + let min = &m["bodies"][0]["bbox"]["min"]; + min[2].as_f64().or_else(|| min["z"].as_f64()).unwrap_or_else(|| panic!("{m}")) +} + +/// timeline.edit takes the dotted keys its unknown-field message lists (`plane.distance`), and +/// numbers for expressions, as the feature commands do; both used to be refused. +#[test] +fn edit_takes_dotted_keys_and_numbers_for_expressions() { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY", "offset": 5, "name": "S"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [10, 10]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"distance": 5, "name": "Pad"})); + let def = |s: &mut Session, f: &str| run(s, "timeline.inspect", json!({"feature": f}))["definition"].clone(); + + run(&mut s, "timeline.edit", json!({"feature": "S", "set": {"plane.distance": "8 mm"}})); + assert_eq!(def(&mut s, "S")["plane"]["distance"], json!("8 mm")); + assert!((low_z(&mut s) - 8.0).abs() < 1e-9); + // A bare number is mm, as in sketch.create's `offset`. + run(&mut s, "timeline.edit", json!({"feature": "S", "set": {"plane.distance": 12}})); + assert_eq!(def(&mut s, "S")["plane"]["distance"], json!("12")); + assert!((low_z(&mut s) - 12.0).abs() < 1e-9); + run(&mut s, "timeline.edit", json!({"feature": "S", "set": {"plane": {"distance": 3.5}}})); + assert_eq!(def(&mut s, "S")["plane"]["distance"], json!("3.5")); + // The nested form works as before. + run(&mut s, "timeline.edit", json!({"feature": "S", "set": {"plane": {"distance": "4"}}})); + assert!((low_z(&mut s) - 4.0).abs() < 1e-9); + + // Every field the unknown-field message lists is accepted as it is written there. + let e = s.execute("timeline.edit", &json!({"feature": "S", "set": {"plane.dist": "1"}})).unwrap_err().to_string(); + assert!(e.contains("unknown field `plane.dist`") && e.contains("`plane.distance`"), "{e}"); + let e = s.execute("timeline.edit", &json!({"feature": "S", "set": {"nope": "1"}})).unwrap_err().to_string(); + let listed: Vec<&str> = e.split('`').skip(3).step_by(2).collect(); + assert!(listed.contains(&"plane.distance") && listed.contains(&"plane.type"), "{e}"); + // Not the sketch geometry, which timeline.inspect leaves out and the sketch commands edit. + assert!(!listed.iter().any(|k| k.starts_with("sketch")), "{e}"); + let now = def(&mut s, "S"); + for key in listed { + let value = dotted(&now, key).clone(); + run(&mut s, "timeline.edit", json!({"feature": "S", "set": {key: value}})); + } + assert_eq!(def(&mut s, "S"), now); + + // Numbers on an extrude, also for an expression the definition leaves out. + run(&mut s, "timeline.edit", json!({"feature": "Pad", "set": {"extent.distance": 20, "extent": {"taper": 0}}})); + let d = def(&mut s, "Pad"); + assert_eq!((&d["extent"]["distance"], &d["extent"]["taper"]), (&json!("20"), &json!("0")), "{d}"); + let volume = run(&mut s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64().unwrap(); + assert!((volume - 2000.0).abs() < 1e-6, "{volume}"); + + // Still refused: a field given twice, unknown dotted fields, a number for a name. + let before = (*s.doc).clone(); + for (set, says) in [ + (json!({"plane.distance": "1", "plane": {"distance": "2"}}), "given twice"), + (json!({"plane.wobble": "1"}), "unknown field `plane.wobble`"), + (json!({"plane.distance.x": "1"}), "invalid feature"), + (json!({"plane.base.name": 5}), "invalid feature"), + ] { + let e = s.execute("timeline.edit", &json!({"feature": "S", "set": set})).unwrap_err().to_string(); + assert!(e.contains(says), "{set}: {e}"); + } + assert_eq!(*s.doc, before); +} diff --git a/crates/engine/src/params.rs b/crates/engine/src/params.rs index b05f70a0e..54a50f353 100644 --- a/crates/engine/src/params.rs +++ b/crates/engine/src/params.rs @@ -58,10 +58,16 @@ pub fn vec2_list(cmd: &str, p: &Value, k: &str, max: usize) -> Result> a.iter().map(|v| vec2(v).ok_or_else(|| bad(cmd, format!("`{k}` must contain [x, y] points")))).collect() } +/// A finite number given for an expression, as the expression's text (`8` → `"8"`, which reads +/// as mm or degrees by context). +pub fn number_text(n: &serde_json::Number) -> Option { + n.as_f64().and_then(finite).map(|v| format!("{v}")) +} + /// An expression parameter: a number (mm or degrees by context) or an expression string. pub fn expr(p: &Value, k: &str) -> Option { match p.get(k)? { - Value::Number(n) => n.as_f64().and_then(finite).map(|v| Expr::new(format!("{v}"))), + Value::Number(n) => number_text(n).map(Expr::new), Value::String(s) if !s.trim().is_empty() && s.len() <= 4096 => Some(Expr::new(s.trim())), _ => None, } diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 38d637aa5..e60ef2aae 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -293,6 +293,33 @@ fn parameters_drive_the_design() { assert!(d["params"].as_array().unwrap().iter().any(|p| p["name"] == "len" && p["value"] == 50.0), "{d}"); } +/// `set_parameter` takes the new value as `value` or as `expression` (the name parameters.change +/// uses), which it used to refuse instead of forwarding. +#[test] +fn set_parameter_takes_value_or_expression() { + let mut s = server(); + let def = tool_definitions().into_iter().find(|d| d["name"] == "set_parameter").unwrap(); + assert_eq!(def["inputSchema"]["required"], json!(["name"]), "{def}"); + assert!(def["inputSchema"]["properties"]["expression"].is_object(), "{def}"); + tool(&mut s, "set_parameter", json!({"name": "len", "expression": "40 mm"})); + tool(&mut s, "execute", json!({"command": "solid.box", "params": {"length": "len", "width": 10, "height": 10, "corner": [0, 0, 0]}})); + assert!(rel(volume(&mut s), 4000.0) < 1e-9); + let r = tool(&mut s, "set_parameter", json!({"name": "len", "expression": 50})); + assert_eq!(r["value"], 50.0, "{r}"); + assert!(rel(volume(&mut s), 5000.0) < 1e-9); + // Both, when they agree. + let r = tool(&mut s, "set_parameter", json!({"name": "len", "value": 60, "expression": "60"})); + assert_eq!(r["value"], 60.0, "{r}"); + // Both disagreeing, or neither, is an error that changes nothing. + for args in [json!({"name": "len", "value": 70, "expression": "80"}), json!({"name": "len"}), json!({"name": "len", "value": null})] { + let r = raw_tool(&mut s, "set_parameter", args.clone()); + assert_eq!(r["result"]["isError"], json!(true), "{args}: {r}"); + let text = r["result"]["content"][0]["text"].as_str().unwrap_or_default(); + assert!(text.contains("`value`") && text.contains("`expression`"), "{args}: {text}"); + } + assert!(rel(volume(&mut s), 6000.0) < 1e-9); +} + /// Design properties (#1015) are set through `execute` and come back in `inspect_design`. #[test] fn design_properties_show_in_inspect_design() { diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index 7d97daaa7..8f0c457bc 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -164,16 +164,19 @@ pub fn tool_definitions() -> Vec { "set_parameter", "Set a parameter", "Create or change a user parameter and re-evaluate the timeline. `value` is a number (mm) or an expression \ - (\"40 mm\", \"width * 2\", \"30 deg\"). Returns the new value, the features recomputed (`recomputed`), the features whose earlier \ - result for the same inputs was reused instead (`restored`, e.g. after setting a value back) and any features that now fail.", + (\"40 mm\", \"width * 2\", \"30 deg\"); `expression` is the same thing under the name the parameters.change command \ + uses. Give one of the two (both only when they agree). Returns the new value, the features recomputed (`recomputed`), the \ + features whose earlier result for the same inputs was reused instead (`restored`, e.g. after setting a value back) and any \ + features that now fail.", obj( json!({ "name": string("Parameter name"), - "value": {"type": ["number", "string"], "description": "Number or expression"}, + "value": {"type": ["number", "string"], "description": "Number or expression (or give it as `expression`)"}, + "expression": {"type": ["number", "string"], "description": "Same as `value` (the parameters.change name); give one of the two"}, "unit": string("mm, deg or \"\" (unitless); default from the expression"), "comment": string("Comment shown in the parameters table"), }), - &["name", "value"], + &["name"], ), Effect::Edits, ), @@ -419,7 +422,7 @@ fn dispatch(b: &mut dyn Backend, name: &str, a: &Map) -> Result { let mut p = pick(a, &["name", "unit", "comment"]); - p["expression"] = a.get("value").cloned().unwrap_or(Value::Null); + p["expression"] = parameter_value(a)?; exec(b, "parameters.change", p) } "export" => exec(b, "file.export", pick(a, &["path", "format", "bodies", "mesh_prefix", "effort", "velocity"])), @@ -436,6 +439,21 @@ fn dispatch(b: &mut dyn Backend, name: &str, a: &Map) -> Result) -> Result { + let text = |v: &Value| match v { + Value::String(s) => s.trim().to_string(), + v => v.to_string(), + }; + match (a.get("value").filter(|v| !v.is_null()), a.get("expression").filter(|v| !v.is_null())) { + (Some(v), None) | (None, Some(v)) => Ok(v.clone()), + (Some(v), Some(e)) if text(v) == text(e) => Ok(v.clone()), + (Some(_), Some(_)) => Err("set_parameter: `value` and `expression` disagree; give one of them".into()), + (None, None) => Err("set_parameter: give the new value as `value` (or `expression`): a number (mm) or an expression".into()), + } +} + fn undo_depth(b: &mut dyn Backend) -> Option { b.call("document.inspect", json!({})).ok().and_then(|d| d["undo"].as_u64()) } diff --git a/docs/mcp.md b/docs/mcp.md index 1ddc2063d..7b15492b2 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -148,7 +148,7 @@ They cover the workflow, the command shapes, how to verify with `measure`, and t | `inspect_design` | `measure?` (default true), `sketches?` (default true) | Design properties (`metadata`: project, author… and other tools' keys; set them with `execute` `document.metadata.set`), parameters, timeline (type, suppressed, rolled back, error, warning, timing), bodies (volume, area, centre of mass, bbox, face/edge/vertex counts, visible; `removed_later: true` while a sketch is being edited on a rolled-back timeline and a later feature deletes the body, which is then not shown), sketches (curves, points, constraints, profiles, DOF, solve status, visible), selection, undo depth. Hide helper sketches, bodies or construction planes with `execute` `browser.visibility` (`{items, visible}` or `{folder, visible}`), and joint glyphs with `{joints: [id or name], visible}` or `{folder: "joints", visible}` (a hidden joint still constrains and drives; `joint.list` reports each joint's `visible`). | | `measure` | `body?` or `items?` | Volume (mm³), area (mm²), centre of mass, bbox and topology counts per body, with totals. With `items` (one or two selections as `execute` takes them: `face`, `edge`, `vertex`, `sketch_curve`, `profile`), the picked geometry instead: see below. | | `body_topology` | `body` | Edges (index, midpoint, length, ends) and faces (index, name, area, centroid, normal, `point`, and for a cylindrical face its `cylinder`: `origin`, `axis`, `radius`). An edge midpoint is the `[x,y,z]` that picks that edge for fillet and chamfer. A face's `point` lies on it and picks it (its centroid may not: that of a face with a hole is in the hole); a face's `name` picks it for the commands that take faces (`face.delete`, `solid.shell`, `solid.draft`, `solid.offset_face`, `solid.split_face`, `solid.replace_face`, and `face` of `sheet.convert`). | -| `set_parameter` | `name`, `value` (number or expression), `unit?`, `comment?` | Create or change a user parameter and recompute; reports `recomputed` (features rebuilt), `restored` (features whose earlier result for the same inputs was reused, e.g. a value set back) and features that now fail. | +| `set_parameter` | `name`, `value` or `expression` (number or expression), `unit?`, `comment?` | Create or change a user parameter and recompute. `expression` is another name for `value` (the one `parameters.change` uses): give one of them, or both only when they agree; neither, or two that differ, is an error. Reports `recomputed` (features rebuilt), `restored` (features whose earlier result for the same inputs was reused, e.g. a value set back) and features that now fail. | | `screenshot` | `view?` (iso, top, front, back, bottom, left, right, home, fit, or a named view saved with `view.save`), `camera?` (`{target, yaw, pitch, distance, fov?}`, as `view.apply`), `path?`, `width?`, `height?`, `source?` (window, model), `grid?`, `axes?` | A PNG image content block. Headless: a render with the viewport's pipelines on a headless GPU device (see `solidcraft-cli gpu`; with no adapter, the CPU rasterizer, without analysis colours), fitted to the model, or from the named view or camera; the reply's `renderer` says which (`gpu`, `gpu-software`, `cpu`, with a `warning` for `cpu`). Bridged: the app window (default) or a model render with the app's camera; a named view or camera moves the app's viewport there first (`execute` `view.apply` does the same without a screenshot). `grid: false` and `axes: false` leave the ground grid (it lies on Z 0 and cuts through a part that straddles it) and the origin's axes out of a model render; axes hidden with `browser.visibility` stay out whatever `axes` says. Bridged, a screenshot that gives `grid` or `axes` is a model render, which follows the app's Grid and Origin switches for what it does not give; `source: "window"` with either is an error. A window that is minimised or on another macOS Space presents no frame: with no `source` the reply is a model render and says so (`fallback`); `source: "window"` is an error saying why, at once. Agents that don't need the app's chrome can ask for `source: "model"`. | | `export` | `path`, `format?` (step, 3mf, 3mf-tagged, stl, stla, obj, urdf), `bodies?`, `mesh_prefix?`, `effort?`, `velocity?` | STEP, 3MF or mesh export; URDF writes the whole assembly with its meshes next to it (`docs/urdf.md`). | | `undo`, `redo` | — | Undo / redo one change. | From 3b4db52c10279251a068cfca5eb7447068bc28e7 Mon Sep 17 00:00:00 2001 From: fkirill Date: Mon, 19 Oct 2026 17:38:48 +0300 Subject: [PATCH 064/225] Respect display units in sketch fillet fields (#2420) (#2487) Thanks @fkirill. --- crates/ui-egui/src/dialogs.rs | 2 +- crates/ui-egui/src/sketch_corner_ui_tests.rs | 80 ++++++++++++++++++++ crates/ui-egui/src/sketch_modify_ui.rs | 14 ++-- 3 files changed, 89 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index e091a00fc..1f12a250b 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -3403,7 +3403,7 @@ fn fillet_kind(size: &str, chamfer: bool) -> Kind { /// A length field's first text: `number` in the design's units, with the unit written out so the /// field shows it as the other dialogs show theirs ("20 mm", "20 in"). OK makes the size the bare /// number would. -fn length_default(s: &Session, number: &str) -> String { +pub(crate) fn length_default(s: &Session, number: &str) -> String { match s.doc.with_design_unit(number, ValueKind::Length) { e if e != number => e, // A millimetre design (or one whose units are not a length): bare numbers are mm. diff --git a/crates/ui-egui/src/sketch_corner_ui_tests.rs b/crates/ui-egui/src/sketch_corner_ui_tests.rs index c80848f1d..6b75068c9 100644 --- a/crates/ui-egui/src/sketch_corner_ui_tests.rs +++ b/crates/ui-egui/src/sketch_corner_ui_tests.rs @@ -226,6 +226,86 @@ fn corner_window_takes_the_corner_then_applies_the_typed_size() { } } +/// #2420: the shared corner window shows the design unit, including both chamfer legs. +#[test] +fn corner_defaults_show_design_units() { + for units in ["mm", "cm", "m", "in", "ft"] { + for command in ["sketch.fillet", "sketch.chamfer.equal_distance", "sketch.chamfer.two_distance", "sketch.chamfer.distance_angle"] { + let mut h = crate::scenario::Harness::new(); + h.app.run("document.units", json!({"units": units})).unwrap(); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + h.step(&json!({"start":command})).unwrap(); + let Some(crate::dialogs::Kind::SketchModify(crate::sketch_modify_ui::Mod::Corner { size, distance2, angle, .. })) = + h.app.dialog.as_ref().map(|d| &d.kind) + else { + panic!("{command}: no corner window"); + }; + assert_eq!(size, &format!("2 {units}"), "{command}"); + assert_eq!(distance2, &format!("2 {units}"), "{command}"); + assert_eq!(angle, "45 deg", "length units must not change angles"); + } + } +} + +/// A typed inch radius must reach both corner selection routes as a persistent dimension. +#[test] +fn fillet_window_reads_design_units_and_preserves_explicit_units_and_parameters() { + for (units, text, radius) in + [("in", "0.25", 6.35), ("cm", "0.25", 2.5), ("mm", "0.25", 0.25), ("in", "2 mm", 2.0), ("mm", "0.25 in", 6.35), ("in", "rounding", 3.0)] + { + for lines in [false, true] { + let mut h = crate::scenario::Harness::new(); + h.app.preferences.length_decimals = 4; + h.app.run("document.units", json!({"units":units})).unwrap(); + h.app.run("parameters.add", json!({"name":"rounding", "expression":"3 mm"})).unwrap(); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + h.app.run("sketch.rectangle.two_point", json!({"p0":[0,0],"p1":[40,30]})).unwrap(); + // Keep the outer size fixed when the driving radius changes. + h.app.run("sketch.dimension", json!({"entities":["l1"],"value":"40 mm"})).unwrap(); + h.app.run("sketch.dimension", json!({"entities":["l2"],"value":"30 mm"})).unwrap(); + h.frames(2); + h.step(&json!({"start":"sketch.fillet"})).unwrap(); + if lines { + for point in [[25, 0, 0], [40, 15, 0]] { + h.step(&json!({"click":{"world":point}})).unwrap(); + } + } else { + h.step(&json!({"click":{"world":[40,0,0]}})).unwrap(); + } + retype(&mut h, "dialog:Radius", text); + apply(&mut h); + assert!(h.app.dialog.is_none(), "{units}, {text}, lines {lines}: {:?}", h.app.status); + let check = |session: &solidcraft_engine::Session, expected: f64| { + let state = session.world_state(); + let ss = state.sketch(1).unwrap(); + let arc = ss + .sketch + .curves + .iter() + .find_map(|c| match c.kind { + CurveKind::Arc { c: center, a: start, .. } => Some(ss.sketch.point(center).unwrap().dist(ss.sketch.point(start).unwrap())), + _ => None, + }) + .unwrap(); + assert!((arc - expected).abs() < 1e-6, "{units}, {text}, lines {lines}: radius {arc}, expected {expected}"); + let area = 1200.0 - expected * expected * (1.0 - std::f64::consts::PI / 4.0); + assert!( + (ss.profiles[0].area - area).abs() < 1e-6, + "{units}, {text}, lines {lines}: area {}, expected {area}, radius {expected}", + ss.profiles[0].area + ); + }; + check(&h.app.session, radius); + if text == "rounding" { + h.app.run("parameters.change", json!({"name":"rounding", "expression":"4 mm"})).unwrap(); + check(&h.app.session, 4.0); + } + let reopened = solidcraft_engine::Session::new(solidcraft_engine::doc::Document::from_json(&h.app.session.doc.to_json()).unwrap()); + check(&reopened, if text == "rounding" { 4.0 } else { radius }); + } + } +} + /// The window's reason to exist: a chamfer angle other than the 45 degrees the command used to /// receive hard-coded. 10 mm along the first line at 30 degrees puts the second cut at /// 10 * sin 30 / sin 60 mm, where 45 degrees would put it at 10 mm. diff --git a/crates/ui-egui/src/sketch_modify_ui.rs b/crates/ui-egui/src/sketch_modify_ui.rs index a48324915..b06713106 100644 --- a/crates/ui-egui/src/sketch_modify_ui.rs +++ b/crates/ui-egui/src/sketch_modify_ui.rs @@ -158,12 +158,12 @@ fn inputs(k: &Mod) -> Vec { } /// The dialog for a sketch modify command. -pub fn start(_app: &SolveApp, id: &str) -> Option<(Kind, Vec)> { +pub fn start(app: &SolveApp, id: &str) -> Option<(Kind, Vec)> { let corner = |chamfer: bool, ctype: usize| Mod::Corner { chamfer, ctype, - size: "2 mm".into(), - distance2: "2 mm".into(), + size: crate::dialogs::length_default(&app.session, "2"), + distance2: crate::dialogs::length_default(&app.session, "2"), angle: "45 deg".into(), flip: false, }; @@ -768,12 +768,14 @@ pub fn commands(app: &SolveApp, k: &Mod, inputs: &[SelInput], extra: &Map { let corners = corner_ids(app, inputs, 0); let lines = line_ids(inputs, 0); - // The radius is checked where it is evaluated, against the document's parameters. + // The engine keeps its millimetre API; bare UI values use the design unit. + // Keep expressions intact so the radius remains a driving dimension. + let radius = app.session.doc.with_design_unit(size.trim(), ValueKind::Length); match (corners.is_empty(), lines.as_slice()) { (true, []) => return Err("select the corners to round first".into()), - (false, []) => ("sketch.fillet", json!({"points": corners, "radius": size.trim()})), + (false, []) => ("sketch.fillet", json!({"points": corners, "radius": radius})), // Two lines name their corner even where other lines end at its point (#1824). - (true, [a, b]) => ("sketch.fillet", json!({"a": a, "b": b, "radius": size.trim()})), + (true, [a, b]) => ("sketch.fillet", json!({"a": a, "b": b, "radius": radius})), _ => return Err("select corner points, or the two lines of one corner".into()), } } From e4d9015f68bddbdd9a0359ef8d8f83cfbb5b54de Mon Sep 17 00:00:00 2001 From: NOWN-DEV <257771410+NOWN-DEV@users.noreply.github.com> Date: Mon, 19 Oct 2026 19:05:28 +0200 Subject: [PATCH 065/225] sketch: points placed by expressions (#2864) * Sketch points placed by expressions over the design's parameters A point typed as an expression ("W", "H / 2") in sketch.point, sketch.line and the other point arguments is fixed where its expressions come to, and moves there again before each solve when the parameters change: an outline that follows its parameters needs no dimensions and no solve per change. The expressions are saved with the point (one pending design-format change), listed with the sketch's other expressions, and renamed with their parameters; one that cannot be worked out is refused. Co-Authored-By: Claude Opus 5.5 (1M context) * Sketch point expressions: accurate params doc, out-of-range regression test The sketch.line params said every point argument takes expressions; only those that also take a point id do (the rectangle corners, an arc's through point and the like are plain [x, y]). PointExprs' comment called its expressions mm. A test covers a parameter that puts a placed point out of range and a design file whose point expression overflows: both are errors, not crashes, and the sketch recovers. Co-Authored-By: Claude Opus 5.5 (1M context) --------- Co-authored-by: Claude Opus 5.5 (1M context) Co-authored-by: bherbruck --- crates/doc/src/document.rs | 25 +++- .../pending/sketch-point-expressions.rs | 5 + crates/engine/src/cmd/sketch.rs | 76 +++++++--- crates/engine/src/cmd/sketch_create.rs | 28 ++-- .../engine/src/cmd/sketch_point_expr_tests.rs | 131 ++++++++++++++++++ crates/sketch/src/construct_tests.rs | 2 +- crates/sketch/src/decompose_tests.rs | 2 +- crates/sketch/src/lib.rs | 3 +- crates/sketch/src/link.rs | 5 +- crates/sketch/src/model.rs | 30 +++- 10 files changed, 267 insertions(+), 40 deletions(-) create mode 100644 crates/doc/src/format/pending/sketch-point-expressions.rs create mode 100644 crates/engine/src/cmd/sketch_point_expr_tests.rs diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 9b5a400ec..a661404b5 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -3195,8 +3195,10 @@ impl Document { } } - /// Apply parameter values to every dimension in a sketch (in place). + /// Apply parameter values to every dimension in a sketch, and to its points placed by + /// parameters (in place). pub fn apply_dimension_values(&self, vals: &std::collections::BTreeMap, sk: &mut Sketch) -> Result<()> { + self.apply_point_values(vals, sk)?; for c in &mut sk.constraints { if let Some(p) = &c.param { let kind = if c.kind.is_angle() { Kind::Angle } else { Kind::Length }; @@ -3210,6 +3212,27 @@ impl Document { Ok(()) } + /// Move the points placed by parameters to where their expressions come to (in place). Such + /// a point is fixed, so the solve keeps it there. + pub fn apply_point_values(&self, vals: &std::collections::BTreeMap, sk: &mut Sketch) -> Result<()> { + use crate::eval::val; + for p in &mut sk.points { + let Some(exprs) = p.exprs.as_deref() else { continue }; + let mut at = p.pos; + for (e, slot, what) in [(&exprs.x, &mut at.x, "X"), (&exprs.y, &mut at.y, "Y")] { + if let Some(e) = e { + *slot = val(vals, e, Kind::Length).map_err(|error| DocError::Expr(format!("point {} {what}: {error}", p.id)))?; + } + } + if !(at.is_finite() && at.x.abs() < solidcraft_sketch::MAX_COORD && at.y.abs() < solidcraft_sketch::MAX_COORD) { + return Err(DocError::Invalid(format!("point {} is placed out of range", p.id))); + } + p.pos = at; + p.fixed = true; + } + Ok(()) + } + /// Give the texts of a sketch the numbers their expressions come to (in place): a text's /// height, place and angle that were typed as expressions. A text's outlines are rebuilt from /// its numbers when the sketch's links are refreshed, so this comes before that. A number diff --git a/crates/doc/src/format/pending/sketch-point-expressions.rs b/crates/doc/src/format/pending/sketch-point-expressions.rs new file mode 100644 index 000000000..98570f851 --- /dev/null +++ b/crates/doc/src/format/pending/sketch-point-expressions.rs @@ -0,0 +1,5 @@ +//! A sketch point can be placed by parameters: `exprs` (`x` and/or `y`, expressions over the +//! design's parameters, in the design's units when a number in them has no unit) on a point that +//! is `fixed` where they come to, and moved there again before each solve when the parameters +//! change. Older designs need no transformation: their points have no `exprs`. The last release +//! asks for an update instead of opening a design with this format number. diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rs index 34468fcd0..e2ca211ab 100644 --- a/crates/engine/src/cmd/sketch.rs +++ b/crates/engine/src/cmd/sketch.rs @@ -3,7 +3,7 @@ use serde_json::{Value, json}; use solidcraft_doc::{FeatureKind, PlaneRef, expr::Kind}; use solidcraft_geom::{Plane, Vec2, Vec3}; -use solidcraft_sketch::{Analysis, Budget, ConstraintKind, CurveKind, Hold, Sketch, SolveReport, solve, solve_with}; +use solidcraft_sketch::{Analysis, Budget, ConstraintKind, CurveKind, Hold, PointExprs, Sketch, SolveReport, solve, solve_with}; use super::{CommandSpec, in_sketch}; use crate::params::{bad, bool_, expr, num, req_vec2, str_, string_list, vec2, vec3}; @@ -37,7 +37,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .icon("line") .key("L") .enabled(in_sketch) - .params(concat!("points: [[x,y] | \"l1.end\" | {at, ref}…], closed?: bool, construction?: bool, ids?: [..], infer?: bool (add horizontal/vertical)", connect_doc!(), created_doc!())), + .params(concat!("points: [[x,y] | \"l1.end\" | {at, ref}…] (x and y each a number or an expression over the design's parameters, \"W / 2\": such a point is fixed where it comes to and follows the parameters; likewise wherever a point argument also takes a point id), closed?: bool, construction?: bool, ids?: [..], infer?: bool (add horizontal/vertical)", connect_doc!(), created_doc!())), CommandSpec::new("sketch.draw.dimensioned", "Draw Dimensioned Sketch Geometry", draw_dimensioned).icon("dimension") .enabled(in_sketch) .params(concat!("command: sketch creation command, params: object, dimensions: object of role to numeric or expression value; creates geometry and all driving dimensions atomically in one undo step", created_doc!())), @@ -109,7 +109,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .icon("slot_overall") .enabled(in_sketch) .params(concat!("p0, p1: overall ends, width", connect_doc!(), created_doc!())), - CommandSpec::new("sketch.point", "Point", draw_point).at("SKETCH", "CREATE").icon("point").enabled(in_sketch).params(concat!("point: [x,y], id?", connect_doc!(), created_doc!())), + CommandSpec::new("sketch.point", "Point", draw_point).at("SKETCH", "CREATE").icon("point").enabled(in_sketch).params(concat!("point: [x,y] (each a number or an expression over the design's parameters: the point is then fixed where it comes to and follows them), id?", connect_doc!(), created_doc!())), CommandSpec::new("sketch.dimension", "Sketch Dimension", dimension).at("SKETCH", "CREATE").icon("dimension").key("D").enabled(in_sketch).params( "entities: [refs], type?: auto|distance|horizontal|vertical|length|radius|diameter|angle, value?: number or expression (default: current; a bare number is in the design's units, e.g. 2 means 2 in in an inch design; give a unit such as \"50 mm\" to override); text_at?: [x, y]. Two points or a line off the axes: with auto, text_at across from them is the distance between them, above or below them horizontal, beside them vertical. Two lines: the angle between them (acute, or 180° − it when the value is nearer that) unless text_at picks a sector. A dimension the sketch already determines is refused (naming what determines it); if_redundant?: \"driven\" places it as a driven (reference) dimension instead. scale_sketch?: bool (the dimension tool sends true): when this is the sketch's first length dimension and nothing in the sketch fixes a size (no other driving length dimension, nothing fixed or projected), the whole sketch scales about its origin to the value instead of distorting. Returns measured in unit (mm or deg), and scaled: the factor when the sketch was scaled", ), @@ -434,10 +434,16 @@ impl PArg { } } -pub(super) fn parg(sk: &Sketch, v: &Value, cmd: &str) -> Result { +pub(super) fn parg(sk: &mut Sketch, doc: &solidcraft_doc::Document, v: &Value, cmd: &str) -> Result { if let Some(p) = vec2(v) { return Ok(PArg::At(p)); } + if let Some((at, exprs)) = expr_point(doc, v, cmd)? { + return Ok(match exprs { + Some(exprs) => PArg::Ref(add_placed_point(sk, at, exprs, None)?, at), + None => PArg::At(at), + }); + } let r = match v { Value::String(r) => Some(r.as_str()), Value::Object(o) => o.get("ref").and_then(Value::as_str), @@ -453,8 +459,34 @@ pub(super) fn parg(sk: &Sketch, v: &Value, cmd: &str) -> Result { Err(bad(cmd, "a point must be [x, y], a point id like \"l1.end\", or {at, ref}")) } -pub(super) fn req_parg(sk: &Sketch, p: &Value, k: &str, cmd: &str) -> Result { - parg(sk, p.get(k).ok_or_else(|| bad(cmd, format!("missing `{k}`")))?, cmd) +pub(super) fn req_parg(sk: &mut Sketch, doc: &solidcraft_doc::Document, p: &Value, k: &str, cmd: &str) -> Result { + parg(sk, doc, p.get(k).ok_or_else(|| bad(cmd, format!("missing `{k}`")))?, cmd) +} + +const POINT_MUST: &str = "a point's coordinates must be numbers or expressions over the design's parameters"; + +/// A point given as `[x, y]` with a coordinate typed as text: where it is now and, when a +/// coordinate names a parameter, the expressions that place it (none: a plain point). +pub(super) fn expr_point(doc: &solidcraft_doc::Document, v: &Value, cmd: &str) -> Result)>> { + let Some([x, y]) = v.as_array().map(Vec::as_slice) else { return Ok(None) }; + if !x.is_string() && !y.is_string() { + return Ok(None); + } + let (px, ex) = super::sketch_create::text_number(doc, x, cmd, "point x", POINT_MUST, false)?; + let (py, ey) = super::sketch_create::text_number(doc, y, cmd, "point y", POINT_MUST, false)?; + let exprs = (ex.is_some() || ey.is_some()).then_some(PointExprs { x: ex, y: ey }); + Ok(Some((Vec2::new(px, py), exprs))) +} + +/// A new point placed by parameters: fixed where its expressions come to, and moved there +/// again whenever the parameters change. +pub(super) fn add_placed_point(sk: &mut Sketch, at: Vec2, exprs: PointExprs, id: Option<&str>) -> Result { + let i = sk.add_point(at, id)?; + if let Some(q) = sk.points.get_mut(i) { + q.fixed = true; + q.exprs = Some(Box::new(exprs)); + } + Ok(i) } pub(super) fn curve_ref(sk: &Sketch, v: Option<&Value>, cmd: &str, what: &str) -> Result { @@ -764,8 +796,8 @@ fn draw_line(s: &mut Session, p: &Value) -> Result { let closed = bool_(p, "closed").unwrap_or(false); let infer = bool_(p, "infer").unwrap_or(false); let ids = string_list(p, "ids"); - let ((curves, cons), info) = draw(s, p, cmd, |sk, _| { - let args: Vec = list.iter().map(|v| parg(sk, v, cmd)).collect::>()?; + let ((curves, cons), info) = draw(s, p, cmd, |sk, doc| { + let args: Vec = list.iter().map(|v| parg(sk, doc, v, cmd)).collect::>()?; let n = args.len(); let segs = if closed { n } else { n - 1 }; let mut pts: Vec> = args.iter().map(PArg::idx).collect(); @@ -1097,8 +1129,8 @@ fn circle_center(s: &mut Session, p: &Value) -> Result { let p = &super::sketch_project::snap_points(s, p, cmd)?; let r = radius_arg(p, cmd)?; let id = str_(p, "id").map(str::to_string); - let (out, info) = draw(s, p, cmd, |sk, _| { - let c = req_parg(sk, p, "center", cmd)?; + let (out, info) = draw(s, p, cmd, |sk, doc| { + let c = req_parg(sk, doc, p, "center", cmd)?; let ci = sk.add_circle(c.pos(), r, c.idx(), id.as_deref())?; mark_construction(sk, &[ci], p); Ok((ids_of(sk, &[ci]), Vec::new())) @@ -1149,8 +1181,8 @@ fn arc_three(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.arc.three_point"; let p = &super::sketch_project::snap_points(s, p, cmd)?; let id = str_(p, "id").map(str::to_string); - let (out, info) = draw(s, p, cmd, |sk, _| { - let (a, b) = (req_parg(sk, p, "start", cmd)?, req_parg(sk, p, "end", cmd)?); + let (out, info) = draw(s, p, cmd, |sk, doc| { + let (a, b) = (req_parg(sk, doc, p, "start", cmd)?, req_parg(sk, doc, p, "end", cmd)?); let t = req_vec2(cmd, p, "through")?; let (o, _) = circumcircle(a.pos(), t, b.pos()).ok_or_else(|| bad(cmd, "the points are collinear"))?; // Counter-clockwise from start to end must pass the through point; otherwise swap. @@ -1172,9 +1204,9 @@ fn arc_center(s: &mut Session, p: &Value) -> Result { let p = &super::sketch_project::snap_points(s, p, cmd)?; let id = str_(p, "id").map(str::to_string); let sweep = num(p, "sweep"); - let (out, info) = draw(s, p, cmd, |sk, _| { - let c = req_parg(sk, p, "center", cmd)?; - let a = req_parg(sk, p, "start", cmd)?; + let (out, info) = draw(s, p, cmd, |sk, doc| { + let c = req_parg(sk, doc, p, "center", cmd)?; + let a = req_parg(sk, doc, p, "start", cmd)?; if let Some(sw) = sweep { // Start point and signed sweep (degrees); clockwise arcs keep `.start` at the start. if !(sw.abs() > 1e-9 && sw.abs() < 360.0) { @@ -1201,7 +1233,7 @@ fn arc_center(s: &mut Session, p: &Value) -> Result { }; return Ok((ids_of(sk, &[ci]), Vec::new())); } - let b = req_parg(sk, p, "end", cmd)?; + let b = req_parg(sk, doc, p, "end", cmd)?; let ci = sk.add_arc(c.pos(), a.pos(), b.pos(), [c.idx(), a.idx(), b.idx()], id.as_deref())?; Ok((ids_of(sk, &[ci]), Vec::new())) })?; @@ -1327,10 +1359,13 @@ fn slot_overall(s: &mut Session, p: &Value) -> Result { fn draw_point(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.point"; - let at = req_vec2(cmd, p, "point")?; let id = str_(p, "id").map(str::to_string); - let ((pid, cons), info) = edit(s, p, cmd, false, |sk, _| { - let i = sk.add_point(at, id.as_deref())?; + let ((pid, cons), info) = edit(s, p, cmd, false, |sk, doc| { + let i = match expr_point(doc, p.get("point").unwrap_or(&Value::Null), cmd)? { + Some((at, Some(exprs))) => add_placed_point(sk, at, exprs, id.as_deref())?, + Some((at, None)) => sk.add_point(at, id.as_deref())?, + None => sk.add_point(req_vec2(cmd, p, "point")?, id.as_deref())?, + }; let cons = connect_points(sk, i, p)?; Ok((sk.points.get(i).map(|q| q.id.clone()).unwrap_or_default(), cons)) })?; @@ -2548,6 +2583,9 @@ mod ids_tests; #[path = "sketch_infinite_tests.rs"] mod infinite_tests; #[cfg(test)] +#[path = "sketch_point_expr_tests.rs"] +mod point_expr_tests; +#[cfg(test)] #[path = "sketch_redundant_tests.rs"] mod redundant_tests; #[cfg(test)] diff --git a/crates/engine/src/cmd/sketch_create.rs b/crates/engine/src/cmd/sketch_create.rs index fbc538b1a..0fb17162b 100644 --- a/crates/engine/src/cmd/sketch_create.rs +++ b/crates/engine/src/cmd/sketch_create.rs @@ -165,7 +165,7 @@ const AT_MUST: &str = "`at` must be the baseline start [x, y], each a number or /// it names a parameter, so that the text follows it; one that names none is the number it comes /// to. Returns the value (mm or radians) and the expression kept. Anything else is refused with /// `must`. -fn text_number(doc: &solidcraft_doc::Document, v: &Value, cmd: &str, key: &str, must: &str, angle: bool) -> Result<(f64, Option)> { +pub(super) fn text_number(doc: &solidcraft_doc::Document, v: &Value, cmd: &str, key: &str, must: &str, angle: bool) -> Result<(f64, Option)> { use solidcraft_doc::expr::{self, Kind}; let kind = if angle { Kind::Angle } else { Kind::Length }; match v { @@ -464,9 +464,9 @@ fn joint_derivatives(sk: &Sketch, ci: usize, pi: usize, order: usize, leaving: b fn blend(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.blend_curve"; let order = blend_order(p, cmd)?; - let (out, info) = edit(s, p, cmd, false, |sk, _| { - let pa = req_parg(sk, p, "a", cmd)?.idx().ok_or_else(|| bad(cmd, "`a` must be the end point of a curve"))?; - let pb = req_parg(sk, p, "b", cmd)?.idx().ok_or_else(|| bad(cmd, "`b` must be the end point of a curve"))?; + let (out, info) = edit(s, p, cmd, false, |sk, doc| { + let pa = req_parg(sk, doc, p, "a", cmd)?.idx().ok_or_else(|| bad(cmd, "`a` must be the end point of a curve"))?; + let pb = req_parg(sk, doc, p, "b", cmd)?.idx().ok_or_else(|| bad(cmd, "`b` must be the end point of a curve"))?; let (ca, ta) = end_of(sk, pa).ok_or_else(|| bad(cmd, "no curve ends at `a`"))?; let (cb, tb) = end_of(sk, pb).ok_or_else(|| bad(cmd, "no curve ends at `b`"))?; let (qa, qb) = (sk.point(pa).unwrap_or_default(), sk.point(pb).unwrap_or_default()); @@ -590,14 +590,14 @@ fn ellipse(s: &mut Session, p: &Value) -> Result { Ok(result(out, info)) } -fn point_list(sk: &mut Sketch, p: &Value, cmd: &str) -> Result> { +fn point_list(sk: &mut Sketch, doc: &solidcraft_doc::Document, p: &Value, cmd: &str) -> Result> { let list = p.get("points").and_then(Value::as_array).ok_or_else(|| bad(cmd, "`points` must be a list"))?; if list.len() < 2 || list.len() > solidcraft_sketch::MAX_SPLINE_POINTS { return Err(bad(cmd, "a spline needs 2 to 500 points")); } let mut out = Vec::new(); for v in list { - let a = super::sketch::parg(sk, v, cmd)?; + let a = super::sketch::parg(sk, doc, v, cmd)?; let i = match a.idx() { Some(i) => i, None => sk.add_point(a.pos(), None)?, @@ -620,8 +620,8 @@ fn spline(s: &mut Session, p: &Value, cmd: &str, control: bool, degree: u8) -> R return Err(bad(cmd, "periodic mode requires a cubic fit spline")); } let p = &super::sketch_project::snap_points(s, p, cmd)?; - let (out, info) = edit(s, p, cmd, false, |sk, _| { - let mut pts = point_list(sk, p, cmd)?; + let (out, info) = edit(s, p, cmd, false, |sk, doc| { + let mut pts = point_list(sk, doc, p, cmd)?; if periodic && sk.point(*pts.first().ok_or_else(|| bad(cmd, "missing first point"))?) != sk.point(*pts.last().ok_or_else(|| bad(cmd, "missing last point"))?) @@ -652,10 +652,10 @@ fn conic(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, "`rho` must be between 0 and 1")); } let p = &super::sketch_project::snap_points(s, p, cmd)?; - let (out, info) = edit(s, p, cmd, false, |sk, _| { + let (out, info) = edit(s, p, cmd, false, |sk, doc| { let mut idx = Vec::new(); for k in ["start", "end", "apex"] { - let a = req_parg(sk, p, k, cmd)?; + let a = req_parg(sk, doc, p, k, cmd)?; idx.push(match a.idx() { Some(i) => i, None => sk.add_point(a.pos(), None)?, @@ -675,8 +675,8 @@ fn conic(s: &mut Session, p: &Value) -> Result { fn midpoint_line(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.line.midpoint"; let end = req_vec2(cmd, p, "end")?; - let (out, info) = edit(s, p, cmd, false, |sk, _| { - let m = req_parg(sk, p, "mid", cmd)?; + let (out, info) = edit(s, p, cmd, false, |sk, doc| { + let m = req_parg(sk, doc, p, "mid", cmd)?; let start = m.pos() * 2.0 - end; if start.dist(end) < 1e-9 { return Err(bad(cmd, "the end must differ from the midpoint")); @@ -744,8 +744,8 @@ fn leaving_dir(sk: &Sketch, ci: usize, pi: usize) -> Option { fn arc_tangent(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.arc.tangent"; let end = req_vec2(cmd, p, "end")?; - let (out, info) = edit(s, p, cmd, false, |sk, _| { - let st = req_parg(sk, p, "start", cmd)?; + let (out, info) = edit(s, p, cmd, false, |sk, doc| { + let st = req_parg(sk, doc, p, "start", cmd)?; let picked = st.idx().ok_or_else(|| bad(cmd, "`start` must be the end point of a line or arc"))?; // The picked point, then any other point at the same place: a trimmed arc's end is its own // point, lying on the end of the curve that trimmed it, which is the one a click picks (#1485). diff --git a/crates/engine/src/cmd/sketch_point_expr_tests.rs b/crates/engine/src/cmd/sketch_point_expr_tests.rs new file mode 100644 index 000000000..2c5422014 --- /dev/null +++ b/crates/engine/src/cmd/sketch_point_expr_tests.rs @@ -0,0 +1,131 @@ +//! Sketch points placed by parameters: a coordinate typed as an expression fixes the point +//! where it comes to, and the point follows the parameters without a dimension or a solve. + +use serde_json::{Value, json}; +use solidcraft_geom::Vec2; + +use crate::Session; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + match s.execute(id, &p) { + Ok(v) => v, + Err(e) => panic!("{id} {p}: {e}"), + } +} + +fn volume(s: &mut Session) -> f64 { + run(s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64().unwrap_or(f64::NAN) +} + +fn no_trouble(s: &Session) { + for r in &s.model.results { + assert!(r.error.is_none() && r.warning.is_none(), "{}: {:?} {:?}", r.name, r.error, r.warning); + } +} + +/// Where point `id` of sketch `S` is in the evaluated model. +fn solved(s: &Session, id: &str) -> Vec2 { + let f = s.doc.find_feature("S").unwrap().id; + let st = s.model.state(); + let sk = &st.sketch(f).unwrap().sketch; + sk.points.iter().find(|q| q.id == id).unwrap().pos +} + +fn reopened(s: &Session) -> Session { + Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()) +} + +#[test] +fn an_outline_through_points_typed_as_expressions_follows_its_parameters() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "W", "expression": "40 mm"})); + run(&mut s, "parameters.add", json!({"name": "H", "expression": "30 mm"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"})); + run(&mut s, "sketch.line", json!({"points": [[0, 0], ["W", 0], ["W", "H / 2 + H / 2"], [0, "H"]], "closed": true})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"sketch": "S", "distance": 10})); + no_trouble(&s); + assert!((volume(&mut s) - 40.0 * 30.0 * 10.0).abs() < 1e-6); + // One change of both: the outline follows without a dimension. + run(&mut s, "parameters.change", json!({"name": "W", "expression": "70 mm"})); + run(&mut s, "parameters.change", json!({"name": "H", "expression": "2 in"})); + no_trouble(&s); + assert!((volume(&mut s) - 70.0 * 50.8 * 10.0).abs() < 1e-6); + assert!(s.doc.to_json().contains("\"exprs\""), "the design file keeps the expressions"); + let mut r = reopened(&s); + no_trouble(&r); + assert!((volume(&mut r) - 70.0 * 50.8 * 10.0).abs() < 1e-6); + // Editing the sketch later keeps the points where the parameters put them. + run(&mut s, "sketch.edit", json!({"sketch": "S"})); + run(&mut s, "sketch.point", json!({"point": [200, 200]})); + run(&mut s, "sketch.finish", json!({})); + assert!((volume(&mut s) - 70.0 * 50.8 * 10.0).abs() < 1e-6); +} + +#[test] +fn a_placed_point_is_fixed_listed_with_its_parameters_and_renamed_with_them() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "W", "expression": "60 mm"})); + run(&mut s, "parameters.add", json!({"name": "H", "expression": "30 mm"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"})); + run(&mut s, "sketch.point", json!({"point": ["W / 2", "H / 3"], "id": "c"})); + run(&mut s, "sketch.circle.center", json!({"center": ["W / 4", 5], "radius": 2, "id": "hole"})); + // A text without a parameter is just a number: a free point. + run(&mut s, "sketch.point", json!({"point": ["5", "6"], "id": "free"})); + run(&mut s, "sketch.finish", json!({})); + no_trouble(&s); + assert_eq!(solved(&s, "c"), Vec2::new(30.0, 10.0)); + let f = s.doc.find_feature("S").unwrap().id; + let sk = s.doc.sketch(f).unwrap(); + let c = sk.points.iter().find(|q| q.id == "c").unwrap(); + assert!(c.fixed && c.exprs.as_ref().is_some_and(|e| e.x.as_deref() == Some("W / 2")), "{c:?}"); + let free = sk.points.iter().find(|q| q.id == "free").unwrap(); + assert!(!free.fixed && free.exprs.is_none() && free.pos == Vec2::new(5.0, 6.0), "{free:?}"); + run(&mut s, "parameters.change", json!({"name": "W", "expression": "100 mm"})); + assert_eq!(solved(&s, "c"), Vec2::new(50.0, 10.0)); + let centre = s.doc.sketch(f).unwrap().curves.iter().find(|c| c.id == "hole").map(|c| c.kind.point_ids()).unwrap_or_default(); + let centre_id = s.doc.sketch(f).unwrap().points.get(centre[0]).unwrap().id.clone(); + assert_eq!(solved(&s, ¢re_id), Vec2::new(25.0, 5.0)); + // The parameter knows the point uses it; a rename reaches the expression. + let users = run(&mut s, "parameters.users", json!({"name": "H"})); + assert!(users.to_string().contains("Point Y"), "{users}"); + run(&mut s, "parameters.rename", json!({"name": "W", "new_name": "width"})); + let c = s.doc.sketch(f).unwrap().points.iter().find(|q| q.id == "c").unwrap().clone(); + assert_eq!(c.exprs.and_then(|e| e.x), Some("width / 2".to_string())); + run(&mut s, "parameters.change", json!({"name": "width", "expression": "80 mm"})); + no_trouble(&s); + assert_eq!(solved(&s, "c"), Vec2::new(40.0, 10.0)); +} + +#[test] +fn a_point_expression_that_cannot_be_worked_out_is_refused() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "turn", "expression": "30 deg"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"})); + for bad in [json!(["nope", 0]), json!(["turn", 0]), json!([0, ""]), json!(["1 / 0", 0]), json!(["1e300 * 1e300", 0])] { + assert!(s.execute("sketch.point", &json!({"point": bad})).is_err(), "{bad}"); + assert!(s.execute("sketch.line", &json!({"points": [[0, 0], bad]})).is_err(), "{bad}"); + } + assert_eq!(s.doc.sketch(s.doc.find_feature("S").unwrap().id).unwrap().points.len(), 1, "only the origin"); +} + +#[test] +fn a_point_its_parameters_put_out_of_range_is_an_error_not_a_crash() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "W", "expression": "40 mm"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"})); + run(&mut s, "sketch.point", json!({"point": ["W", 0], "id": "c"})); + run(&mut s, "sketch.finish", json!({})); + let changed = s.execute("parameters.change", &json!({"name": "W", "expression": "1e12 mm"})); + let failed = s.model.results.iter().any(|r| r.error.as_deref().is_some_and(|e| e.contains("out of range"))); + assert!(changed.is_err() || failed, "{changed:?}"); + run(&mut s, "parameters.change", json!({"name": "W", "expression": "50 mm"})); + no_trouble(&s); + assert_eq!(solved(&s, "c"), Vec2::new(50.0, 0.0)); + // A design file whose point expression cannot be worked out opens with that sketch in error. + let file = s.doc.to_json(); + let hostile = file.replace("\"x\": \"W\"", "\"x\": \"W * 1e300 * 1e300\"").replace("\"x\":\"W\"", "\"x\":\"W * 1e300 * 1e300\""); + assert_ne!(hostile, file, "the point's expression is in the file"); + let r = Session::new(solidcraft_doc::Document::from_json(&hostile).unwrap()); + assert!(r.model.results.iter().any(|r| r.error.is_some()), "the sketch reports the bad point"); +} diff --git a/crates/sketch/src/construct_tests.rs b/crates/sketch/src/construct_tests.rs index a69d9833e..503a1152b 100644 --- a/crates/sketch/src/construct_tests.rs +++ b/crates/sketch/src/construct_tests.rs @@ -890,7 +890,7 @@ fn given_points_are_never_placed() { sk.add_constraint(ConstraintKind::Fix { p }, None).unwrap(); } let g = sk.points.len(); - sk.points.push(SPoint { id: "far".into(), pos: v(2e9, 0.0), fixed: true, link: None }); + sk.points.push(SPoint { id: "far".into(), pos: v(2e9, 0.0), fixed: true, link: None, exprs: None }); let d = sk.add_point(v(20.0, 30.0), None).unwrap(); let push = |sk: &mut Sketch, kind: ConstraintKind| { sk.constraints.push(Constraint { id: format!("h{}", sk.constraints.len()), kind, param: None, driven: false, text: None }) diff --git a/crates/sketch/src/decompose_tests.rs b/crates/sketch/src/decompose_tests.rs index 9f4fd08ab..ad8d0cab7 100644 --- a/crates/sketch/src/decompose_tests.rs +++ b/crates/sketch/src/decompose_tests.rs @@ -45,7 +45,7 @@ fn raw(kind: ConstraintKind) -> Constraint { /// A point pushed past the sketch's own size cap. fn push_point(sk: &mut Sketch, pos: Vec2) { let id = format!("p{}", sk.points.len()); - sk.points.push(crate::model::SPoint { id, pos, fixed: false, link: None }); + sk.points.push(crate::model::SPoint { id, pos, fixed: false, link: None, exprs: None }); } /// Every point of `ids` placed at its `want` position. diff --git a/crates/sketch/src/lib.rs b/crates/sketch/src/lib.rs index 60ba5da57..9ddf30210 100644 --- a/crates/sketch/src/lib.rs +++ b/crates/sketch/src/lib.rs @@ -50,7 +50,8 @@ pub use fonts::{DEFAULT_FONT_FAMILY, FontData, families_in, find_style_in, font_ pub use freeform_offset::{FreeformOffset, OFFSET_TOLERANCE}; pub use link::{Link, LinkGeom, LinkKind, LinkSource, MAX_LINK_ENTITIES, SKETCH_AXIS_HALF, TextExprs, sketch_axis_geom}; pub use model::{ - Constraint, ConstraintKind, Curve, CurveKind, MAX_CONSTRAINTS, MAX_COORD, MAX_CURVES, MAX_POINTS, SPoint, Sketch, SketchError, SketchView, + Constraint, ConstraintKind, Curve, CurveKind, MAX_CONSTRAINTS, MAX_COORD, MAX_CURVES, MAX_POINTS, PointExprs, SPoint, Sketch, SketchError, + SketchView, }; pub use offset::OffsetChain; pub use offset_topology::{OffsetCreated, OffsetRole, OffsetRoleFlags, OffsetRoleKind, OffsetTopology}; diff --git a/crates/sketch/src/link.rs b/crates/sketch/src/link.rs index 819a4d3a7..2490d74f1 100644 --- a/crates/sketch/src/link.rs +++ b/crates/sketch/src/link.rs @@ -520,7 +520,8 @@ impl Sketch { self.links.iter().find(|l| l.id == id) } - /// The expressions of the sketch's texts, each with what it sets (`Text height`…). + /// The expressions of the sketch's texts and of its points placed by parameters, each with + /// what it sets (`Text height`, `Point X`…). pub fn text_exprs(&self) -> Vec<(&'static str, &String)> { self.links .iter() @@ -529,6 +530,7 @@ impl Sketch { _ => None, }) .flatten() + .chain(self.points.iter().filter_map(|p| p.exprs.as_deref()).flat_map(crate::PointExprs::list)) .collect() } @@ -541,6 +543,7 @@ impl Sketch { _ => None, }) .flatten() + .chain(self.points.iter_mut().filter_map(|p| p.exprs.as_deref_mut()).flat_map(crate::PointExprs::list_mut)) .collect() } diff --git a/crates/sketch/src/model.rs b/crates/sketch/src/model.rs index 6e93064cd..82ce56d89 100644 --- a/crates/sketch/src/model.rs +++ b/crates/sketch/src/model.rs @@ -53,6 +53,32 @@ pub struct SPoint { /// Projected (linked) reference geometry: the id of the link that owns this point. #[serde(default, skip_serializing_if = "Option::is_none")] pub link: Option, + /// A point placed by expressions over the design's parameters: it is `fixed` where they + /// come to (`Document::apply_point_values` works them out before each solve). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub exprs: Option>, +} + +/// The expressions of a point placed by parameters, over the design's parameters; a coordinate +/// without one keeps the number stored in the point (mm). +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct PointExprs { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub x: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub y: Option, +} + +impl PointExprs { + /// The expressions set, each with what it sets. + pub fn list(&self) -> Vec<(&'static str, &String)> { + [("Point X", &self.x), ("Point Y", &self.y)].into_iter().filter_map(|(what, e)| e.as_ref().map(|e| (what, e))).collect() + } + + /// Mutable view of [`PointExprs::list`], for renaming the parameters they refer to. + pub fn list_mut(&mut self) -> Vec<&mut String> { + [&mut self.x, &mut self.y].into_iter().filter_map(Option::as_mut).collect() + } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -615,7 +641,7 @@ impl Default for Sketch { impl Sketch { pub fn new() -> Self { Sketch { - points: vec![SPoint { id: "origin".into(), pos: Vec2::ZERO, fixed: true, link: None }], + points: vec![SPoint { id: "origin".into(), pos: Vec2::ZERO, fixed: true, link: None, exprs: None }], curves: Vec::new(), constraints: Vec::new(), patterns: Vec::new(), @@ -712,7 +738,7 @@ impl Sketch { Some(i) => i.to_string(), None => self.fresh("p")?, }; - self.points.push(SPoint { id, pos: p, fixed: false, link: None }); + self.points.push(SPoint { id, pos: p, fixed: false, link: None, exprs: None }); Ok(self.points.len() - 1) } From f3505f0db6542725345fdf8ff4bb76461f097e62 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Mon, 19 Oct 2026 15:43:22 -0400 Subject: [PATCH 066/225] World placement on all cores (#3053) (#3123) Co-authored-by: Claude Opus 5.5 --- apps/solidcraft-cli/src/main.rs | 6 +++++- crates/doc/src/eval.rs | 30 ++++++++++++++++++++++++------ 2 files changed, 29 insertions(+), 7 deletions(-) diff --git a/apps/solidcraft-cli/src/main.rs b/apps/solidcraft-cli/src/main.rs index 8aca7563b..38af451fb 100644 --- a/apps/solidcraft-cli/src/main.rs +++ b/apps/solidcraft-cli/src/main.rs @@ -630,10 +630,14 @@ pub(crate) fn cmd_bench_open(args: &[String]) -> Result<(), String> { } let t = std::time::Instant::now(); let st = s.world_state(); + let place_ms = t.elapsed().as_secs_f64() * 1000.0; // As the desktop app prepares a design it opened. st.warm_meshes(|| true); let triangles: usize = st.bodies.iter().map(|b| b.mesh().triangles.len()).sum(); - println!("{}", json!({"step": "mesh", "ms": t.elapsed().as_secs_f64() * 1000.0, "bodies": st.bodies.len(), "triangles": triangles})); + println!( + "{}", + json!({"step": "mesh", "ms": t.elapsed().as_secs_f64() * 1000.0, "place_ms": place_ms, "bodies": st.bodies.len(), "triangles": triangles}) + ); // `--display LEVEL`: the display plans the viewport draws at that display quality, made as // the GPU viewport makes them; `--edit NAME EXPR` then changes a parameter and times the // evaluation and the plans of the bodies it changed. diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 11817bef8..195280f6c 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -5765,21 +5765,39 @@ pub fn world_state_reusing(doc: &Document, st: &ModelState, placed_before: &mut path }; let mut out = ModelState { body_counter: st.body_counter, ..Default::default() }; - for (comp, path, m) in doc.placements() { + let placements = doc.placements(); + // A body moved in from another component keeps its place (its offset). + let body_matrix = |b: &ModelBody, m: &crate::Mat| doc.model_body_offset(b).map(|o| crate::mat_mul(m, o)).unwrap_or(*m); + // Every body placed elsewhere than its definition, placed on all cores: a large assembly + // places hundreds of parts, each a B-rep transform. + let mut jobs = Vec::new(); + for (comp, path, m) in &placements { + for b in st.bodies.iter().filter(|b| doc.model_body_component(b) == *comp) { + let bm = body_matrix(b, m); + if !crate::is_identity(&bm) { + jobs.push((b, bm, doc.world_body_name(st, &b.name, *comp, path))); + } + } + } + let mut moved = kernel::map_on_threads(&jobs, 16, |(b, bm, name)| placed_before.placed(b, bm, name.clone())).into_iter().zip(&jobs); + for (comp, path, m) in placements { let primary = path == first_path(comp); let ident = crate::is_identity(&m); for b in st.bodies.iter().filter(|b| doc.model_body_component(b) == comp) { - let name = doc.world_body_name(st, &b.name, comp, &path); - // A body moved in from another component keeps its place (its offset). - let bm = doc.model_body_offset(b).map(|o| crate::mat_mul(&m, o)).unwrap_or(m); + let bm = body_matrix(b, &m); // Identical geometry also shares its display mesh cell with the definition. // A changed placement keeps a distinct mesh, at that placement's coordinates. let mut placed = if crate::is_identity(&bm) { let mut placed = b.clone(); - placed.name = name; + placed.name = doc.world_body_name(st, &b.name, comp, &path); placed } else { - let placed = placed_before.placed(b, &bm, name); + // The same order as the jobs: this body's, made above (again here if it failed). + let placed = match moved.next() { + Some((Some(placed), _)) => placed, + Some((None, (_, _, name))) => placed_before.placed(b, &bm, name.clone()), + None => placed_before.placed(b, &bm, doc.world_body_name(st, &b.name, comp, &path)), + }; placed_now.by_source.insert(placed_key(b, &bm), (b.clone(), placed.clone())); placed }; From b00d45cc7b1c626071c4bfac719c1b57dcb7fc33 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Mon, 19 Oct 2026 15:44:06 -0400 Subject: [PATCH 067/225] Open: draw the Home picture after the design opens (#3053) (#3140) Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/file_load.rs | 25 ++++++++++++------------ crates/ui-egui/src/file_load_ui_tests.rs | 2 ++ crates/ui-egui/src/home.rs | 11 ++++++----- 3 files changed, 20 insertions(+), 18 deletions(-) diff --git a/crates/ui-egui/src/file_load.rs b/crates/ui-egui/src/file_load.rs index 87a56a594..3e34dfb69 100644 --- a/crates/ui-egui/src/file_load.rs +++ b/crates/ui-egui/src/file_load.rs @@ -81,7 +81,8 @@ impl Request { struct Made { session: Session, result: Value, - image: Option, + /// Draw its Home picture once it is open (off the UI thread: a large design takes a while). + thumbnail: bool, } type Job = Result; struct Running { @@ -508,8 +509,7 @@ fn step_staged(running: &mut Running) { } let (Some(session), Some(result)) = (staged.session.take(), staged.ran.take()) else { return }; let thumbnail = staged.command == "doc.open" && staged.triangles <= STAGED_THUMBNAIL_TRIANGLES; - let image = if thumbnail { crate::home::remember(&session) } else { None }; - send(staged, Ok(Made { session, result, image })); + send(staged, Ok(Made { session, result, thumbnail })); return; } let Some(reading) = staged.reading.as_mut() else { @@ -727,7 +727,7 @@ fn compute( if command == "file.export_view_dxf" { // A successful export has already published its complete file. A Cancel arriving // after that commit must not turn a completed save into a misleading cancellation. - return Ok(Made { session, result, image: None }); + return Ok(Made { session, result, thumbnail: false }); } if progress.is_cancelled() { return cancelled(); @@ -746,16 +746,13 @@ fn compute( let tessellation_ms = mesh_began.elapsed().as_secs_f64() * 1000.0; phase.store(2, Ordering::Relaxed); let view_ms = view_began.elapsed().as_secs_f64() * 1000.0; - let thumbnail_began = std::time::Instant::now(); - let image = if thumbnail { crate::home::remember(&session) } else { None }; if profile { eprintln!( - "SolidCraft open phases: geometry_ms={geometry_ms:.3} placement_ms={placement_ms:.3} tessellation_ms={tessellation_ms:.3} display_warmup_ms={view_ms:.3} thumbnail_ms={:.3} total_ms={:.3}", - thumbnail_began.elapsed().as_secs_f64() * 1000.0, + "SolidCraft open phases: geometry_ms={geometry_ms:.3} placement_ms={placement_ms:.3} tessellation_ms={tessellation_ms:.3} display_warmup_ms={view_ms:.3} total_ms={:.3}", began.elapsed().as_secs_f64() * 1000.0 ); } - Ok(Made { session, result, image }) + Ok(Made { session, result, thumbnail }) } pub fn tick(app: &mut SolveApp, ctx: &egui::Context) { @@ -804,7 +801,9 @@ pub fn tick(app: &mut SolveApp, ctx: &egui::Context) { crate::documents::adopt(app, made.session); if request.kind == Kind::Open { app.home.add_recent(&request.path); - crate::home::install(&mut app.home, ctx, &request.path, made.image); + if made.thumbnail { + crate::home::remember_session(&mut app.home, &app.session); + } } } app.home.open = false; @@ -1046,7 +1045,7 @@ mod tests { built: None, staged: None, }); - tx.send(Ok(Made { session: other, result: json!({"visible":12}), image: None })).unwrap(); + tx.send(Ok(Made { session: other, result: json!({"visible":12}), thumbnail: false })).unwrap(); h.frames(2); assert_eq!(reply_rx.try_recv().unwrap()["result"]["visible"], 12); assert!(Arc::ptr_eq(&base, &h.app.session.doc)); @@ -1085,7 +1084,7 @@ mod tests { let newer = app.session.doc.clone(); tick(&mut app, &egui::Context::default()); assert!(app.file_load.running.as_ref().unwrap().preview.is_none()); - tx.send(Ok(Made { session: Session::default(), result: Value::Null, image: None })).unwrap(); + tx.send(Ok(Made { session: Session::default(), result: Value::Null, thumbnail: false })).unwrap(); tick(&mut app, &egui::Context::default()); assert!(Arc::ptr_eq(&newer, &app.session.doc)); assert!(app.status.as_ref().unwrap().0.contains("discarded")); @@ -1174,7 +1173,7 @@ mod tests { assert!(app.file_load.running.is_some()); let mut computed = Session::default(); computed.execute("solid.box", &serde_json::json!({"length":10,"width":10,"height":10})).unwrap(); - tx.send(Ok(Made { session: computed, result: Value::Null, image: None })).unwrap(); + tx.send(Ok(Made { session: computed, result: Value::Null, thumbnail: false })).unwrap(); tick(&mut app, &egui::Context::default()); assert!(app.file_load.running.is_none()); assert!(Arc::ptr_eq(&old, &app.session.doc)); diff --git a/crates/ui-egui/src/file_load_ui_tests.rs b/crates/ui-egui/src/file_load_ui_tests.rs index 104617de8..c2d7635f5 100644 --- a/crates/ui-egui/src/file_load_ui_tests.rs +++ b/crates/ui-egui/src/file_load_ui_tests.rs @@ -211,6 +211,8 @@ fn a_control_open_answers_after_loading_without_freezing_the_window() { assert_eq!(reply["ok"], true, "{reply}"); assert_eq!(reply["result"], expected); assert!(count_rx.try_recv().is_ok(), "inspection answered while the file loaded"); + // Its Home picture is drawn after it opened, not before. + assert!(crate::home::remembering(&w.app.home), "the Home picture is drawn off the UI thread"); for _ in 0..3 { w.frame(vec![]); } diff --git a/crates/ui-egui/src/home.rs b/crates/ui-egui/src/home.rs index 06b30330f..a0e493369 100644 --- a/crates/ui-egui/src/home.rs +++ b/crates/ui-egui/src/home.rs @@ -141,6 +141,12 @@ fn remember_at(s: &Session, #[cfg(not(target_arch = "wasm32"))] identity: Option Some(img) } +/// A Home picture is being drawn off the UI thread. +#[cfg(test)] +pub(crate) fn remembering(h: &HomeState) -> bool { + h.remembering.is_some() +} + pub(crate) fn remember_session(h: &mut HomeState, s: &Session) { #[cfg(not(target_arch = "wasm32"))] if let Some(path) = &s.path { @@ -168,11 +174,6 @@ pub(crate) fn remember_session(h: &mut HomeState, s: &Session) { } } -pub(crate) fn install(h: &mut HomeState, ctx: &egui::Context, key: &str, img: Option) { - let tex = img.map(|i| ctx.load_texture(format!("thumb:{key}"), i, egui::TextureOptions::LINEAR)); - h.thumbs.insert(key.to_string(), tex); -} - /// Build what a key stands for (runs off the UI thread where threads exist). fn make(key: &str) -> Made { #[cfg(not(target_arch = "wasm32"))] From 15db51304ee2a038fcc24b1381594b4e67ce3521 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Mon, 19 Oct 2026 15:53:34 -0400 Subject: [PATCH 068/225] Agent instructions: a regression test goes into its area's test file, not a new per-bug file (#3230) Refs #3226. Co-authored-by: Claude Opus 5.5 --- AGENTS.md | 2 ++ CLAUDE.md | 2 ++ 2 files changed, 4 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index fa334ea2d..7f44f9ed0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -48,6 +48,8 @@ People trust SolidCraft with their designs; a crash loses their work. **This out `crashes replay ` (or the `diagnostics.crash_reports` command / MCP `crash_reports` tool). - **Prove it:** every crash fix lands with a regression test (see `hostile_params_never_panic`); a crash report's `design.solidcraft` + `replay.json` is the test's starting point. +- **Where tests go:** a regression test goes into the existing test file for its area (booleans, blends, + shell, sweep, STEP, naming…), never a new file named after the bug (#3226). - Every production crate root carries `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]`. diff --git a/CLAUDE.md b/CLAUDE.md index 26b27e44f..e996301cf 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -50,6 +50,8 @@ People trust SolidCraft with their designs; a crash loses their work. **This out `crashes replay ` (or the `diagnostics.crash_reports` command / MCP `crash_reports` tool). - **Prove it:** every crash fix lands with a regression test (see `hostile_params_never_panic`); a crash report's `design.solidcraft` + `replay.json` is the test's starting point. +- **Where tests go:** a regression test goes into the existing test file for its area (booleans, blends, + shell, sweep, STEP, naming…), never a new file named after the bug (#3226). - Every production crate root carries `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]`. From f1f5298bc5d469674bc05d61bd3eae0cf146a6c8 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Mon, 19 Oct 2026 16:02:11 -0400 Subject: [PATCH 069/225] Agent instructions: one source in AGENTS.md; CLAUDE.md imports it (#3240) Co-authored-by: Claude Opus 5.5 --- AGENTS.md | 14 +-- CLAUDE.md | 186 +-------------------------------------- README.md | 2 +- scripts/triage/triage.js | 2 +- 4 files changed, 12 insertions(+), 192 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 7f44f9ed0..6ef91355d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -27,8 +27,10 @@ new uses of it anywhere else. Public docs/web/Flatpak deployments use project Pa ## Never crash People trust SolidCraft with their designs; a crash loses their work. **This outranks feature work.** - **No panics in non-test code:** no `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!`, - `unimplemented!`; no `unsafe` (`unsafe_code = "forbid"`). The three exceptions, in the app crate - (which denies it instead), have no safe API: two functions in + `unimplemented!`; no `unsafe` (`unsafe_code = "forbid"`). The exceptions, in the app crate and in + `crates/threedx-client` (which deny it instead), have no safe API: the macOS-only + `crates/threedx-client/src/macos.rs` (loads the 3Dconnexion driver's client framework at run time + and calls through its function pointers), two functions in `apps/solidcraft/src/open_documents.rs` (macOS hands Finder files only to an Objective-C method), the Windows-only `apps/solidcraft/src/native_crash.rs` (the exception filter that records crashes inside native code such as graphics drivers) and the Windows-only @@ -134,10 +136,10 @@ People trust SolidCraft with their designs; a crash loses their work. **This out - Before working on issue #N, check nobody has it: `gh pr list -R bherbruck/solidcraft --state open --search "#N"`. - If none, branch from the latest `origin/main`, `git commit --allow-empty -m "claim: #N"`, push, and open a **draft** PR titled `

(#N)` right away. **The lowest-numbered open PR for an - issue wins**; if yours lost, close it. A comment or file edit alone does not replace the draft PR. -- After opening the draft PR, comment `/claim` on the issue so the bot records the claimant and - adds the `in progress` label. **Do both:** the draft PR establishes ownership and `/claim` marks - the issue as taken. Reference `#N` in the PR so the bot can find it. + issue wins**; if yours lost, close it. Opening the PR is the claim: the bot assigns you and + labels the issue `in progress` (or says on your PR who holds it). Reference `#N` in the PR title + so the bot can find it. Don't claim by editing files; comment `/claim` on the issue only to stake + a claim before you have a branch. - Push work in progress at least daily. A draft with no pushes for 72 hours may be taken over: comment on it first, then open your own claim (you may start from its branch). This takeover policy is separate from the bot's automatic cleanup deadlines in CONTRIBUTING.md. diff --git a/CLAUDE.md b/CLAUDE.md index e996301cf..de94a1990 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,185 +1,3 @@ -# SolidCraft — instructions for agents +@AGENTS.md -SolidCraft is a clean-room, open-source, pure-Rust parametric 3D CAD application: -sketches with a constraint solver, a parametric timeline of features, a B-rep -kernel, and a desktop UI that agents can drive. Projects published by -[storytold](https://github.com/storytold) can serve as references for implementation conventions. -Any code adapted from other projects (MIT OR Apache-2.0) is noted in ATTRIBUTION.md. - -## Product name -SolidCraft everywhere: crates `solidcraft-*`, binaries `solidcraft` and `solidcraft-cli`, -`.solidcraft` designs, the `solidcraft/N` format tag, `SOLIDCRAFT_*` environment variables, -settings and recovery folders, the MCP server name, docs, CI and packaging. The old name -survives only in the explicit compatibility shims listed in `docs/compatibility.md`; don't add -new uses of it anywhere else. Public docs/web/Flatpak deployments use project Pages -`/solidcraft/`; do not add permanent old-name Pages aliases. - -## Start every session here -1. Read `plan/STATUS.md` (current milestone, next task), then the task in `plan/execution-plan.md` - and the relevant `plan/architecture.md` section. -2. Kernel and library decisions: `plan/adr/0001-geometry-kernel.md` (what we may depend on, what - is rejected for licence reasons). -3. Follow the autonomous operation protocol (`plan/execution-plan.md` §6). Don't stop to ask - unless it lists the decision as the owner's. - -`plan/` is gitignored (local only). - -## Never crash -People trust SolidCraft with their designs; a crash loses their work. **This outranks feature work.** -- **No panics in non-test code:** no `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!`, - `unimplemented!`; no `unsafe` (`unsafe_code = "forbid"`). The exceptions, in the app crate and in - `crates/threedx-client` (which deny it instead), have no safe API: the macOS-only - `crates/threedx-client/src/macos.rs` (loads the 3Dconnexion driver's client framework at run time - and calls through its function pointers), two functions in - `apps/solidcraft/src/open_documents.rs` (macOS hands Finder files only to an Objective-C - method), the Windows-only `apps/solidcraft/src/native_crash.rs` (the exception filter that - records crashes inside native code such as graphics drivers) and the Windows-only - `apps/solidcraft/src/native_frame.rs` (the window procedure that answers the resize-border hit - test of the window without OS decorations). -- **Errors are `Result`** through the crate's error type and `?`. An unfinished feature - returns an error ("not supported yet: …"); it never panics. -- **Input-derived numbers are hostile** (command parameters, design files, control-channel - input): `get()` not `[i]`, finite checks, caps on sizes and loop counts. -- **Third-party kernel calls are guarded:** everything that calls `truck` goes through - `solidcraft_kernel::guard`, which turns a panic into `KernelError::Internal`. -- **Last-resort guard:** `Session::execute` runs every command under `catch_unwind`; an escaped - panic restores the design and reports `EngineError::Internal`. -- **Crash reports:** the desktop app writes every panic and every unclean exit to a local crash folder, - with the design and the commands that reproduce it (`solidcraft_engine::crash`, docs/crash-reports.md). - When someone says the app crashed, look there first: `solidcraft-cli crashes`, `crashes show `, - `crashes replay ` (or the `diagnostics.crash_reports` command / MCP `crash_reports` tool). -- **Prove it:** every crash fix lands with a regression test (see `hostile_params_never_panic`); a - crash report's `design.solidcraft` + `replay.json` is the test's starting point. -- **Where tests go:** a regression test goes into the existing test file for its area (booleans, blends, - shell, sweep, STEP, naming…), never a new file named after the bug (#3226). -- Every production crate root carries - `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]`. - -## Non-negotiables -- **Independent.** SolidCraft is independent. Behaviour is designed from public documentation, - general CAD conventions and user feedback. Reference tests use analytic values and open-source - tools. Never copy another product's code, icons, artwork, help text, tooltips, templates or - materials. File formats come from public specifications. -- **No commercial CAD products.** Agents must not drive, script, automate or extract data from - commercial CAD products (Fusion, SolidWorks, Onshape, …) for this project: no test data, - measurements, command lists, ids or files produced with them. -- **Never read, copy or link GPL/LGPL/AGPL code**: OpenCASCADE, FreeCAD (incl. planegcs), - SolveSpace, CadQuery/OCP, LibreCAD, QCAD — don't even read their sources. (`tools/freecad-oracle/` - runs FreeCAD as a separate program through its public scripting API to compute reference values; - nothing from FreeCAD is linked, vendored or shipped.) The sketch solver and the blend - operations are our own. -- **Assets — absolutely essential.** SolidCraft contains **no iconography, images, fonts or - artwork from commercial CAD products — ever.** Every UI icon is drawn in collected code - (`assets/icons/ui/source/`, compiled through `crates/ui-egui/src/icons.rs`). Any file asset must be original or openly licensed and **must have a row in ATTRIBUTION.md** - (`cargo xtask assets` enforces it). Screenshots of commercial CAD software are never committed. - Breaking this rule is the most serious mistake you can make in this repo. -- **Everything is a command.** User-visible behaviour = a command in `crates/engine/src/cmd/*` - (`CommandSpec`: id = our own dotted, lower-case id `.[.]` such as - `solid.extrude` or `sketch.rectangle.two_point`, never another product's command id; label; - toolbar tab and panel; icon; shortcut; params doc; `enabled`; JSON `run`) + tests. The toolbar, - dialogs, sketch tools, palette, scripts, CLI and control channel all reach the same commands. -- **Programmatic calls never open dialogs.** `engine.execute` runs the JSON form; only toolbar - clicks (`ui.start`) start interactive tools and dialogs, which then run commands. -- **Layering** is enforced by `cargo xtask layers`: L0 `geom` → L1 `sketch`, `kernel`, `render` - → L2 `doc` → L3 `io` → L4 `engine` → L5 `ui-egui` → apps. Nothing below L5 depends on - egui/eframe/winit/wgpu/rfd. **The UI crate is swappable.** Only `crates/kernel` may use `truck`. -- **The UI is thin**: panels read engine state and act through `app.run(id, params)` / - `app.start(id)`. Colours come from `theme::Tokens`. -- **One set of camera controls**: every page or canvas with a camera (viewport, Render - preview, future flat pattern or drawing pages) calls `navigation::handle` with its `NavCaps` - (orbit off for flat 2D pages). New canvases must use `navigation::handle`; never hand-roll - camera input (a test rejects it). -- **Rust only.** Units are millimetres and radians internally; Z is up. The one exception is - JavaScript the browser requires: the service worker `apps/solidcraft-web/sw.js` (browsers only - run service workers as JavaScript) and the small inline scripts in `apps/solidcraft-web/index.html`. - Keep them minimal; `cargo xtask web-offline-test` covers the service worker. -- **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings, tests, - assets, layers). Commit after every feature arc that builds. -- **Publishing**: `origin` is github.com/bherbruck/solidcraft. Changes land through **pull requests**: - push a branch, open a PR, and let GitHub CI run. Maintainers (and agents working for them) may - merge their own PR as soon as CI is green (`gh pr merge --squash`); a trivial fix (docs, typos) - may be merged right away. Keep each PR to one topic, rebase or merge `main` into it when it - conflicts, and never force-push `main`. Never commit `plan/`, build dirs (`target*/`) or - generated reference data; check `git ls-files` before pushing. -- **Never break wasm**: everything below the apps must build for `wasm32-unknown-unknown` - (`cargo xtask wasm`, part of `cargo xtask ci`). - -## Showing and following through on changes - -- Help reviewers see what is broken or changed. For observable CAD, UI or model behavior, - issues and PRs must include actual descriptive screenshots or a short recording from a - small reproduction. This includes kernel, geometry, assembly and backend changes whose - effects can be shown in the app. Coding agents should run the app and capture this evidence - themselves; do not ask a human for evidence the agent can produce. Show the actual failure - or result, preferably before and after, with brief reproduction steps, expected/actual - behavior and annotations that point out the relevant detail. -- Flowcharts and Mermaid diagrams cannot substitute for screenshots or recordings of visible - behavior. Use diagrams for architectural reasoning when actual screenshots cannot illustrate - the point. Changes with no useful observable behavior do not need screenshot or video evidence. -- Use a small public-safe example and check for private designs, paths, account details or - other sensitive content before sharing. Attach media to the issue/PR or link to an accessible - recording; do not commit generated screenshots or videos just to provide review evidence. -- Throughout the work and before handoff, check current upstream commits and the relevant - PR's merge status. Keep your branch current with upstream merges, resolve conflicts without - discarding others' work, and re-run validation when integration changes the result. Use - `git pull --rebase origin main` before pushing as above; never force-push. Report the checked - upstream/PR state, any conflicts resolved and the validation performed. If a PR remains open, - keep monitoring it while the task is active and make its pending status clear at handoff; - do not claim it merged without checking. - -## Claim = a draft PR -- Before working on issue #N, check nobody has it: `gh pr list -R bherbruck/solidcraft --state open --search "#N"`. -- If none, branch from the latest `origin/main`, `git commit --allow-empty -m "claim: #N"`, push, - and open a **draft** PR titled ` (#N)` right away. **The lowest-numbered open PR for an - issue wins**; if yours lost, close it. Opening the PR is the claim: the bot assigns you and - labels the issue `in progress` (or says on your PR who holds it). Don't claim by editing files. -- Push work in progress at least daily. A draft with no pushes for 72 hours may be taken over: - comment on it first, then open your own claim (you may start from its branch). -- On a shared build machine, check the load before a big build (`cut -d' ' -f1 /proc/loadavg`) - and wait while it is over 24; build with `nice`. - -## Design file format -A change that saves something new in a design adds ONE file, `crates/doc/src/format/pending/.rs` -(a `//!` note, and `pub fn step` if older designs must be rewritten). Never edit `FORMAT`, -`JSON_STEPS`, the history in `format.rs`, another change's file or a `v/` folder: the build -works out the number (the next one while anything is pending), and the release folds pending -changes into `v/` with `scripts/fold-format-pending.sh`. See CONTRIBUTING.md. - -## Application releases -Development pushes are not application releases. Follow `docs/releasing.md` when asked to -prepare or ship a release: choose the version from the actual changes, update Cargo.toml and -Cargo.lock, pass the quality gates, advance `release` without force-pushing, and verify the -resulting draft and its artifacts. When shipping is authorized, publish that verified draft -and confirm its tag and downstream deployment. Do not auto-release every push to `main`, infer -version bumps solely from commit prefixes, overwrite published versions, or push release tags -before the draft is verified. - -## Running and looking at the app -- `cargo run --release -p solidcraft -- --sample --control PORT` (sample design + control channel). - Pick a free port. Without a display, run it under `Xvfb :99` with `DISPLAY=:99`. -- Drive it with JSON lines on `127.0.0.1:PORT` (see `docs/control-protocol.md`). The first - request on a connection carries the launch's token as `"token"`: read it from - `~/.local/share/solidcraft/control/PORT.token`, or start the app with - `SOLIDCRAFT_CONTROL_TOKEN=$(openssl rand -hex 32)` and send that. - - `{"id":1,"method":"engine.execute","params":{"command":"solid.extrude","params":{"distance":20}}}` - - `{"id":2,"method":"ui.start","params":{"command":"sketch.create"}}` then `ui.click {x, y}` - - `{"id":3,"method":"ui.screenshot","params":{"path":"/tmp/shot.png"}}` then read the PNG. -- **For UI work, look at the result** (screenshot, read the PNG). Without a window use - `ui.render` or `solidcraft-cli snapshot`. -- Headless: `solidcraft-cli run script.json --out part.step`, `solidcraft-cli eval design.solidcraft`, - `solidcraft-cli snapshot script.json --out shot.png`, `solidcraft-cli commands`. -- Reference tests: `cargo xtask oracle` replays `tests/oracle/*/recipe.json` and compares with - each case's `expected.json` (analytic or FreeCAD values; writes `docs/oracle.md`). Expected - values never come from a commercial CAD product. -- Build with `CARGO_TARGET_DIR=/target`. Windows: `cargo xwin build --release --target x86_64-pc-windows-msvc -p solidcraft`. - -## Roadmap -`ROADMAP.md` (committed) tracks status, milestones and estimates. Update it whenever a -milestone task lands. `docs/features.md` (SolidCraft's commands by area, from the registry) and -`THIRD-PARTY-LICENSES.txt` are regenerated on `main` after each merge by the Generated files -workflow; never regenerate them in a PR. - -## Lists many PRs add to -Keep them conflict-free (CONTRIBUTING.md, "Lists many changes add to"): message catalogs sorted -(`cargo xtask lists --fix`), `mod` lines in their sorted group, the language list English first -then by id, generated files left to `main`, and a design-format change as one new file. +The agent instructions for this repo live in AGENTS.md; edit that file only. diff --git a/README.md b/README.md index 94386e1ad..f068a6483 100644 --- a/README.md +++ b/README.md @@ -321,7 +321,7 @@ and licence rules, and where help is wanted most. ## Licence MIT OR Apache-2.0, at your option. Developed under the -[clean-room contribution rules](CLAUDE.md); third-party code and assets retain their +[clean-room contribution rules](AGENTS.md); third-party code and assets retain their documented licences and attribution. SolidCraft is independent. Behaviour is designed from public documentation, general CAD diff --git a/scripts/triage/triage.js b/scripts/triage/triage.js index ba994e285..3928d1aa7 100644 --- a/scripts/triage/triage.js +++ b/scripts/triage/triage.js @@ -91,7 +91,7 @@ function classifyIssue(title, body) { const labels = new Set(); if (CRASH.test(t)) { labels.add('bug'); - labels.add('priority:P1'); // a crash loses work (CLAUDE.md, "Never crash") + labels.add('priority:P1'); // a crash loses work (AGENTS.md, "Never crash") } else if (IN_APP_FAILURE.test(t) || /^##\s*(behavior|actual behavior)\b/im.test(b)) { labels.add('bug'); } else if (FEATURE.test(t)) { From 1cd9983c8fc5da46a4079d2819b62969cd13f3bb Mon Sep 17 00:00:00 2001 From: Irakli Kourtis Date: Mon, 19 Oct 2026 16:04:02 -0400 Subject: [PATCH 070/225] Surface trim: projected curves, several kept regions, mutual trim (#767) (#1466) * kernel: trim keeps picked regions, mutual trim, curves swept along a direction (#767) Trim moves to surface_trim.rs: TrimKeep::Side (the old behaviour) or Regions (the connected pieces the points pick, parted where the tool runs along an edge). mutual_trim cuts two one-face surfaces by each other's surface, extending one that stops short when asked. SplitTool::Curves takes a sweep direction; a closed curve's field is signed by inside/outside instead of extending its end segments. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LGeCa5jWWdroMWvXxN3LLM * kernel: classify display edges of a face with a closed-edge hole without a panic A hole cut by a closed curve is a loop of one edge that starts and ends at one vertex; mapping the face rebuilt that edge through a check that panics on it (the guard caught it and dropped every smooth flag of the body). Such faces are now left out of the ruled-surface test. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LGeCa5jWWdroMWvXxN3LLM * surface.trim: keep several regions, trim by projected sketch curves, mutual trim (#767) keep takes a list of points (the regions they pick); curves: {sketch, curves?, direction?} sweeps sketch curves onto the surface (along the surface's normal: not supported yet); with + keep_with trims two surfaces by each other, extend? meets a short one, stitch? sews the kept pieces. Trimmed faces carry their lineage, so they are named after the faces they are pieces of. New fields noted in a pending format file. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LGeCa5jWWdroMWvXxN3LLM * Trim dialog: sketch curves as the tool, several keep points, mutual trim (#767) The tool input takes sketch curves too; keep points are places (several on one face add up); another surface with its keep points makes a mutual trim with Extend to meet and Stitch toggles. Edit Feature brings it all back. Labels in every locale catalog. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LGeCa5jWWdroMWvXxN3LLM * ROADMAP: M8 trim by projected curves, several regions and mutual trim (#767) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LGeCa5jWWdroMWvXxN3LLM --------- Co-authored-by: jyviko <2501648+jyviko@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 Co-authored-by: bherbruck --- ROADMAP.md | 2 +- assets/locales/cs.json | 8 + assets/locales/de.json | 8 + assets/locales/en.json | 8 + assets/locales/es.json | 8 + assets/locales/fr.json | 8 + assets/locales/gl.json | 8 + assets/locales/ja.json | 8 + assets/locales/ko.json | 8 + assets/locales/pt-BR.json | 8 + assets/locales/ru.json | 8 + assets/locales/tr.json | 8 + assets/locales/uk.json | 8 + assets/locales/zh.json | 8 + crates/doc/src/document.rs | 33 +- crates/doc/src/eval.rs | 2 +- crates/doc/src/eval_surface.rs | 75 +++- crates/doc/src/feature_walk_tests/fixtures.rs | 9 + .../src/feature_walk_tests/golden_exprs.txt | 10 + .../feature_walk_tests/golden_geometry.txt | 4 + .../src/feature_walk_tests/golden_refs.txt | 7 + .../surface-trim-regions-curves-mutual.rs | 6 + crates/engine/src/cmd/surface.rs | 298 ++++++++++++- crates/engine/src/tests.rs | 5 + crates/kernel/src/lib.rs | 4 +- crates/kernel/src/smooth_edges.rs | 27 ++ crates/kernel/src/splitface.rs | 129 +++++- crates/kernel/src/surface_trim.rs | 398 ++++++++++++++++++ crates/kernel/src/surfaces.rs | 27 +- crates/ui-egui/src/dialogs_surface.rs | 117 +++-- crates/ui-egui/src/preselect_tests.rs | 53 +++ crates/ui-egui/src/selection.rs | 23 +- 32 files changed, 1246 insertions(+), 87 deletions(-) create mode 100644 crates/doc/src/format/pending/surface-trim-regions-curves-mutual.rs create mode 100644 crates/kernel/src/surface_trim.rs diff --git a/ROADMAP.md b/ROADMAP.md index 471240bb7..fc02e7f62 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -57,7 +57,7 @@ PCB / Package, Render, Animation, Simulation, Manufacture/CAM, Drawings. | M5 | Persistent naming of faces and edges (docs/book/src/dev/naming.md): faces named from their exact kernel-reported history (sketch curve sides, caps, revolve sections, primitive sides, blends, shell inner walls, pattern/mirror copies; split pieces told apart by the faces around them, lumps of a cut body named after their faces), edges by their faces; fillets/chamfers, sketches on faces, shell/draft/offset/replace faces, hole placements, joint origins and face appearances resolve by name first and warn when the entity split or vanished: done. sheet metal edges by base sketch line and flange side, shell inner faces, sweep and loft roles: done. kernel-reported face history: done (merged faces answer to every name; operations without history yet fall back to geometric names, flagged unverified; format 14 keeps older designs' geometric names). Left: history through sheet metal, plastic, surface and emboss features; FaceSource certificates through history | in progress | 20 | | M6 | UI depth: selection feedback and origin (done), timeline editing (done: hover and selection highlight modifier faces, including fillets and chamfers; edit feature, history marker drag, dependency-checked single and multi-item reorder, suppress, rename, delete with dependents, re-resolved references; redefining selections refreshes persistent edge/face references while retaining feature identity and dimension names; optional compact named left feature history with rollback bar, multi-selection and persistent folders above the parts browser), right-docked dialogs (done), live previews for every feature dialog (done), keyboard-first commands with on-canvas value boxes and sketch inline dimensions (done), drag manipulators with automatic join/cut (done: extrude incl. two sides, fillet, shell, hole depth, move, pattern spacing, revolve rotator, extrude taper), dark theme (done), right-click menu with Repeat (done), measure tool (done), section analysis (done), selection filter (done), drag-solve of sketch points (done); appearance controls now preserve body/face/component targeting, named transparent looks, reuse/search and override removal; preferences | in progress | 6 | | M7 | Thin extrude (walls along open or closed curves: centre, inside, outside or two sides; mitred corners, crossing walls joined; #721), sweep, loft (incl. to a point), rib and web (to next / depth), emboss (planar faces and exact radial emboss/deboss of bounded orthogonal profiles on complete exterior cylinders/sleeves), thread (cosmetic, and modelled M3–M20 outside and inside: the ISO profile screwed in as a faceted cut), coil (smooth B-spline helical walls), pipe, pattern on path, patterns of bodies and components, replace face (parallel), align, remove, feature copy/paste: done. Unique eligible cylindrical targets are inferred for new Emboss features. Left: general curved-face emboss and exact (unfaceted) modelled threads | in progress | 12 | -| M8 | Surface workspace (#772). Done: Patch (sketch regions; edge loops filled G0, plus `crown`), Stitch, Thicken (planes and cylinders), Extend (straight edges of planar surfaces), Trim (by a plane or a face), Delete Face (healing), Boundary Fill, zebra/draft/curvature-map analysis, Surface Extrude/Revolve/Sweep/Loft from open and closed curves, Offset, Unstitch and Reverse Normal; the continuity-driven core (`kernel/src/bridge.rs`, G0–G3 Hermite rows) with **Blend** (`surface.blend`, #764), **Match** (`surface.match`), **Boundary** (`surface.boundary`, #763 — two sketch curves exact with G0–G3, three or four as the flat patch of their loop, and curve networks: Coons and Gordon surfaces through sketch, 3D-sketch or edge curves, a point for a three-sided side, G1/G2 against the faces along one direction's edges, joined into their body on request; G1/G2 on two sides that meet at a corner waits for the Gregory-type corner), **Fair** (`surface.fair`, CV fairing), **continuity analysis** (`inspect.continuity`, #770; a toolbar tool with edge markers and a legend, and curvature combs along face isocurves) and a multi-section **loft** with per-end continuity and crown. Also in the Class-A pass: G1…G4 blend curves in the sketch, chord and variable-radius fillets on curved edges (with honest refusals where the fit cannot hold), and a G2 corner patch where filleted edges meet (kernel; the command refuses until the patch's sections can be sewn to the blends' contacts). Left: bias/form-factor fillet sections (design recorded), a Gregory-type corner, surface Fillet between separate surface bodies (#769), Ruled (#762), Untrim (#761), curved-face Extend (#760), loft guide rails (#201; sweep guide rails and two-rail sweeps are done, #771), and every remaining #757–#772 item | deferred | — | +| M8 | Surface workspace (#772). Done: Patch (sketch regions; edge loops filled G0, plus `crown`), Stitch, Thicken (planes and cylinders), Extend (straight edges of planar surfaces), Trim (by a plane, a face or sketch curves swept onto the surface, keeping a side or the picked regions; mutual trim of two surfaces, extended to meet and stitched, #767), Delete Face (healing), Boundary Fill, zebra/draft/curvature-map analysis, Surface Extrude/Revolve/Sweep/Loft from open and closed curves, Offset, Unstitch and Reverse Normal; the continuity-driven core (`kernel/src/bridge.rs`, G0–G3 Hermite rows) with **Blend** (`surface.blend`, #764), **Match** (`surface.match`), **Boundary** (`surface.boundary`, #763 — two sketch curves exact with G0–G3, three or four as the flat patch of their loop, and curve networks: Coons and Gordon surfaces through sketch, 3D-sketch or edge curves, a point for a three-sided side, G1/G2 against the faces along one direction's edges, joined into their body on request; G1/G2 on two sides that meet at a corner waits for the Gregory-type corner), **Fair** (`surface.fair`, CV fairing), **continuity analysis** (`inspect.continuity`, #770; a toolbar tool with edge markers and a legend, and curvature combs along face isocurves) and a multi-section **loft** with per-end continuity and crown. Also in the Class-A pass: G1…G4 blend curves in the sketch, chord and variable-radius fillets on curved edges (with honest refusals where the fit cannot hold), and a G2 corner patch where filleted edges meet (kernel; the command refuses until the patch's sections can be sewn to the blends' contacts). Left: bias/form-factor fillet sections (design recorded), a Gregory-type corner, surface Fillet between separate surface bodies (#769), Ruled (#762), Untrim (#761), curved-face Extend (#760), loft guide rails (#201; sweep guide rails and two-rail sweeps are done, #771), and every remaining #757–#772 item | deferred | — | | M9 | Components and assemblies: New Component / Create Components from Bodies, active component, per-component origin/bodies/sketches/timeline entries, occurrences with transforms, Copy/Paste vs Paste New, nested Browser tree with visibility and isolate; Ground, Move/Copy of occurrences, joints (rigid, revolute, slider, cylindrical, pin-slot, planar, ball) by joint origins with limits and Drive Joints, closed kinematic loops (four-bar, slider-crank: the loop's other joints follow the driven one on its branch, and driving stops where a loop can no longer close), cams (`joint.cam`: a revolute cam drives a slider or revolute follower along a closed sketch profile or the cam's edges, knife, roller or flat followers, worked out again when the profile changes; drives, studies, closed loops, contact sets), As-built Joint, Rigid Group, Contact Sets (driving and motion studies stop where bodies in a set would pass through each other), Motion Study (joint values keyed along a timeline, playback, export of occurrence positions as JSON/CSV), motion analysis (joint values and a point's path charted over a study as value, velocity and acceleration; the parts that collide along a study, with the steps where they do), Exploded views (automatic or by hand, shown without changing placements); interference, per-component physical properties; STEP with assembly structure; URDF export for robot simulators (links with meshes, mass and inertia; joint chains whose values match Drive Joints; docs/urdf.md). Physical properties now measure material-aware component/occurrence placements, descendants and repeated instances, including pending moves and body reassignment offsets; contact geometry and automatic exploded centres respect those offsets. Groundwork done: component tree, occurrences with transforms (instances, Paste New), world placement, active component as authoring frame, ground, Capture/Revert Position, moving bodies and sketches. UI: ASSEMBLE panel dialogs for New Component, Joint (snaps on faces, edges, circles and vertices; animated motion preview; offsets, flip, limits), As-built Joint, Joint Origin, Rigid Group, Drive Joints (live slider), Motion Link, Cam and Interference (overlaps shown red); joints in the timeline and the Browser | in progress | 32 | | M10 | Sheet metal: flange (base, edge, contour), hem, unfold/refold, convert, flat pattern + DXF, rules: done. PLASTIC enclosure subset: Boss, Rib, Web, Lip/Groove, Snap Fit, Rest, Plastic Rules (library, edit, assign; rule draft and clearance as feature defaults): done, tested against hand-computed geometry. UI: SHEET METAL and PLASTIC tabs with dialogs (live preview, Edit Feature, pre-selection) for Flange, Hem, Unfold/Refold, Convert, Sheet Metal Rules, Create Flat Pattern (flat view with bend lines, bend table CSV/JSON and DXF export with exact circle/arc/line cutouts), Boss, Lip/Groove, Snap Fit, Rest, Manage and Assign Plastic Rules; Fold (bend along a sketch line); flanges meeting at a corner closed at any angle with the rule's gap; edge flanges with their own angle and height per edge in one feature; corner reliefs (notch, round, rectangular, tear) chosen by the rule; Convert to Sheet Metal from a solid or shelled body by its bend edges (flat faces, sharp bends) | in progress | 36 | | M11 | 2D drawings | deferred | — | diff --git a/assets/locales/cs.json b/assets/locales/cs.json index 9df1715f9..e70007ab6 100644 --- a/assets/locales/cs.json +++ b/assets/locales/cs.json @@ -98,6 +98,7 @@ "Export Current View as DXF…": "Exportovat aktuální pohled do DXF…", "Export DXF…": "Exportovat DXF…", "Export hidden edges as dashed lines": "Exportovat skryté hrany čárkovaně", + "Extend to meet": "Prodloužit k protnutí", "Extents": "Rozsahy", "Face": "Plocha", "Face attachment lost": "Připojení k ploše ztraceno", @@ -126,7 +127,9 @@ "Interferes": "Koliduje", "Issue title": "Název hlášení", "Joint Origin1": "Počátek kloubu1", + "Keep (points on it)": "Ponechat (body na ní)", "Keep Tools": "Ponechat nástroje", + "Keep of the other surface": "Ponechat z druhé plochy", "Later": "Později", "Leave it": "Nechat být", "Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "Starší typ připojení k ploše. Novým navázáním na ověřenou plochu vznikne přesné připojení.", @@ -162,6 +165,7 @@ "Open GitHub draft": "Otevřít koncept na GitHubu", "Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "Open-source parametrický 3D CAD v jazyce Rust. Licence MIT OR Apache-2.0.", "Other side": "Druhá strana", + "Other surface (mutual trim)": "Druhá plocha (vzájemné oříznutí)", "Outside": "Vně", "Overall length": "Celková délka", "Parameter values": "Hodnoty parametrů", @@ -245,9 +249,12 @@ "Stand this part up?": "Postavit tento díl?", "Step": "Krok", "Steps": "Kroky", + "Stitch the kept pieces": "Sešít ponechané části", "Style": "Styl", "Suppressed": "Potlačeno", + "Surface": "Plocha", "Swap Ends": "Prohodit konce", + "TRIM": "OŘÍZNOUT", "Tangent (G1)": "Tečně (G1)", "Tangent Chain": "Tečný řetězec", "Tear": "Roztržení", @@ -264,6 +271,7 @@ "This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "Tato plocha nemůže poskytnout trvalé připojení. Zvolte jinou plochu nebo výslovně použijte pevnou rovinu.", "To Offset": "Odsazení k objektu", "Tolerance": "Tolerance", + "Trimming tool (plane, face or curves)": "Ořezávací nástroj (rovina, plocha nebo křivky)", "Turn off section analysis before exporting the view.": "Před exportem pohledu vypněte analýzu řezu.", "Type": "Typ", "UNTRIM": "ZRUŠIT OŘEZ", diff --git a/assets/locales/de.json b/assets/locales/de.json index 78bbe8d25..4f2e2f2bf 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -39,6 +39,7 @@ "Export Current View as DXF…": "Aktuelle Ansicht als DXF exportieren…", "Export DXF…": "DXF exportieren…", "Export hidden edges as dashed lines": "Verdeckte Kanten gestrichelt exportieren", + "Extend to meet": "Verlängern, bis sie sich treffen", "Face": "Fläche", "Faces": "Flächen", "Find in Browser": "Im Browser suchen", @@ -49,6 +50,8 @@ "In place (surfaces)": "An Ort und Stelle (Flächen)", "In plane": "In der Ebene", "Inside": "Innen", + "Keep (points on it)": "Behalten (Punkte darauf)", + "Keep of the other surface": "Vom anderen Flächenkörper behalten", "Length": "Länge", "Max": "Max", "Min": "Min", @@ -58,6 +61,7 @@ "None": "Keine", "Normal to sketch": "Normal zur Skizze", "Notch": "Ausklinkung", + "Other surface (mutual trim)": "Anderer Flächenkörper (gegenseitig trimmen)", "Outside": "Außen", "Overall length": "Gesamtlänge", "Pass through": "Durch Punkte", @@ -87,12 +91,16 @@ "Sketch geometry and profiles": "Skizzengeometrie und Profile", "Sketch points": "Skizzenpunkte", "Slot width": "Langlochbreite", + "Stitch the kept pieces": "Behaltene Teile vernähen", "Study": "Untersuchung", + "Surface": "Flächenkörper", + "TRIM": "TRIMMEN", "Tangent (G1)": "Tangente (G1)", "Tear": "Reißen", "Thickness Outside": "Dicke außen", "Thin": "Dünnwandig", "Thin Extrude": "Dünnwandig extrudieren", + "Trimming tool (plane, face or curves)": "Trimmwerkzeug (Ebene, Fläche oder Kurven)", "Turn off section analysis before exporting the view.": "Deaktivieren Sie die Schnittanalyse, bevor Sie die Ansicht exportieren.", "Type": "Typ", "UNTRIM": "TRIMMEN AUFHEBEN", diff --git a/assets/locales/en.json b/assets/locales/en.json index d3c74c2b0..708ac23f0 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -107,6 +107,7 @@ "Export Current View as DXF…": "Export Current View as DXF…", "Export DXF…": "Export DXF…", "Export hidden edges as dashed lines": "Export hidden edges as dashed lines", + "Extend to meet": "Extend to meet", "Extents": "Extents", "Face": "Face", "Face attachment lost": "Face attachment lost", @@ -135,7 +136,9 @@ "Interferes": "Interferes", "Issue title": "Issue title", "Joint Origin1": "Joint Origin1", + "Keep (points on it)": "Keep (points on it)", "Keep Tools": "Keep Tools", + "Keep of the other surface": "Keep of the other surface", "Later": "Later", "Leave it": "Leave it", "Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "Legacy face attachment. Rebinding to a certified face creates an exact attachment.", @@ -173,6 +176,7 @@ "Open GitHub draft": "Open GitHub draft", "Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.", "Other side": "Other side", + "Other surface (mutual trim)": "Other surface (mutual trim)", "Outside": "Outside", "Overall length": "Overall length", "Parameter values": "Parameter values", @@ -260,10 +264,13 @@ "Stand this part up?": "Stand this part up?", "Step": "Step", "Steps": "Steps", + "Stitch the kept pieces": "Stitch the kept pieces", "Study": "Study", "Style": "Style", "Suppressed": "Suppressed", + "Surface": "Surface", "Swap Ends": "Swap Ends", + "TRIM": "TRIM", "Tangent (G1)": "Tangent (G1)", "Tangent Chain": "Tangent Chain", "Tear": "Tear", @@ -281,6 +288,7 @@ "To Offset": "To Offset", "Tolerance": "Tolerance", "Too close": "Too close", + "Trimming tool (plane, face or curves)": "Trimming tool (plane, face or curves)", "Turn off section analysis before exporting the view.": "Turn off section analysis before exporting the view.", "Type": "Type", "UNTRIM": "UNTRIM", diff --git a/assets/locales/es.json b/assets/locales/es.json index 1750c8966..a8939d7e2 100644 --- a/assets/locales/es.json +++ b/assets/locales/es.json @@ -105,6 +105,7 @@ "Export Current View as DXF…": "Exportar vista actual como DXF…", "Export DXF…": "Exportar DXF…", "Export hidden edges as dashed lines": "Exportar aristas ocultas como líneas discontinuas", + "Extend to meet": "Extender hasta encontrarla", "Extents": "Extensión", "Face": "Cara", "Face attachment lost": "Se ha perdido la vinculación de la cara", @@ -133,7 +134,9 @@ "Interferes": "Interfiere", "Issue title": "Título de la incidencia", "Joint Origin1": "Origen de unión1", + "Keep (points on it)": "Conservar (puntos sobre ella)", "Keep Tools": "Conservar herramientas", + "Keep of the other surface": "Conservar de la otra superficie", "Later": "Más tarde", "Leave it": "Dejar como está", "Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "Vinculación antigua de cara. Volver a vincularla a una cara verificada crea una vinculación exacta.", @@ -171,6 +174,7 @@ "Open GitHub draft": "Abrir borrador de GitHub", "Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "CAD 3D paramétrico de código abierto desarrollado en Rust. Licencia MIT O Apache-2.0.", "Other side": "Lado opuesto", + "Other surface (mutual trim)": "Otra superficie (recorte mutuo)", "Outside": "Exterior", "Overall length": "Longitud total", "Parameter values": "Valores de parámetros", @@ -258,10 +262,13 @@ "Stand this part up?": "¿Poner esta pieza en vertical?", "Step": "Paso", "Steps": "Pasos", + "Stitch the kept pieces": "Coser las piezas conservadas", "Study": "Estudio", "Style": "Estilo", "Suppressed": "Suprimido", + "Surface": "Superficie", "Swap Ends": "Intercambiar extremos", + "TRIM": "RECORTAR", "Tangent (G1)": "Tangencia (G1)", "Tangent Chain": "Cadena tangente", "Tear": "Desgarro", @@ -279,6 +286,7 @@ "To Offset": "Hasta desfase", "Tolerance": "Tolerancia", "Too close": "Demasiado cerca", + "Trimming tool (plane, face or curves)": "Herramienta de recorte (plano, cara o curvas)", "Turn off section analysis before exporting the view.": "Desactiva el análisis de sección antes de exportar la vista.", "Type": "Tipo", "UNTRIM": "ANULAR RECORTE", diff --git a/assets/locales/fr.json b/assets/locales/fr.json index 276e9dc21..6e2feab66 100644 --- a/assets/locales/fr.json +++ b/assets/locales/fr.json @@ -105,6 +105,7 @@ "Export Current View as DXF…": "Exporter la vue actuelle en DXF…", "Export DXF…": "Exporter en DXF…", "Export hidden edges as dashed lines": "Exporter les arêtes cachées en tirets", + "Extend to meet": "Prolonger jusqu'à la rencontre", "Extents": "Étendues", "Face": "Face", "Face attachment lost": "Rattachement à la face perdu", @@ -133,7 +134,9 @@ "Interferes": "Interfère", "Issue title": "Titre du ticket", "Joint Origin1": "Origine de liaison1", + "Keep (points on it)": "À conserver (points dessus)", "Keep Tools": "Conserver les outils", + "Keep of the other surface": "À conserver de l'autre surface", "Later": "Plus tard", "Leave it": "Laisser tel quel", "Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "Rattachement à la face hérité. Le relier à une face certifiée crée un rattachement exact.", @@ -171,6 +174,7 @@ "Open GitHub draft": "Ouvrir le brouillon GitHub", "Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "CAO 3D paramétrique open source en Rust. Sous licence MIT OR Apache-2.0.", "Other side": "Autre côté", + "Other surface (mutual trim)": "Autre surface (ajustement mutuel)", "Outside": "Extérieur", "Overall length": "Longueur hors tout", "Parameter values": "Valeurs des paramètres", @@ -258,10 +262,13 @@ "Stand this part up?": "Redresser cette pièce ?", "Step": "Étape", "Steps": "Étapes", + "Stitch the kept pieces": "Coudre les parties conservées", "Study": "Étude", "Style": "Style", "Suppressed": "Désactivé", + "Surface": "Surface", "Swap Ends": "Permuter les extrémités", + "TRIM": "AJUSTER", "Tangent (G1)": "Tangence (G1)", "Tangent Chain": "Chaîne tangente", "Tear": "Déchirure", @@ -279,6 +286,7 @@ "To Offset": "Jusqu'au décalage", "Tolerance": "Tolérance", "Too close": "Trop proches", + "Trimming tool (plane, face or curves)": "Outil d'ajustement (plan, face ou courbes)", "Turn off section analysis before exporting the view.": "Désactivez l'analyse de coupe avant d'exporter la vue.", "Type": "Type", "UNTRIM": "ANNULER L'AJUSTEMENT", diff --git a/assets/locales/gl.json b/assets/locales/gl.json index d7a219660..b0960fee8 100644 --- a/assets/locales/gl.json +++ b/assets/locales/gl.json @@ -98,6 +98,7 @@ "Export Current View as DXF…": "Exportar a vista actual como DXF…", "Export DXF…": "Exportar DXF…", "Export hidden edges as dashed lines": "Exportar as arestas ocultas como liñas descontinuas", + "Extend to meet": "Estender ata atopala", "Extents": "Extensións", "Face": "Cara", "Face attachment lost": "Perdeuse a ancoraxe á cara", @@ -126,7 +127,9 @@ "Interferes": "Interfire", "Issue title": "Título da incidencia", "Joint Origin1": "Orixe da unión1", + "Keep (points on it)": "Manter (puntos sobre ela)", "Keep Tools": "Manter as ferramentas", + "Keep of the other surface": "Manter da outra superficie", "Later": "Máis tarde", "Leave it": "Deixalo", "Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "Ancoraxe á cara antiga. Volver vincular a unha cara certificada crea unha ancoraxe exacta.", @@ -162,6 +165,7 @@ "Open GitHub draft": "Abrir o borrador de GitHub", "Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "CAD 3D paramétrico de código aberto en Rust. Con licenza MIT OR Apache-2.0.", "Other side": "Outro lado", + "Other surface (mutual trim)": "Outra superficie (recorte mutuo)", "Outside": "Fóra", "Overall length": "Lonxitude total", "Parameter values": "Valores dos parámetros", @@ -245,9 +249,12 @@ "Stand this part up?": "Poñer esta peza de pé?", "Step": "Paso", "Steps": "Pasos", + "Stitch the kept pieces": "Coser as pezas mantidas", "Style": "Estilo", "Suppressed": "Suprimida", + "Surface": "Superficie", "Swap Ends": "Intercambiar os extremos", + "TRIM": "RECORTAR", "Tangent (G1)": "Tanxente (G1)", "Tangent Chain": "Cadea tanxente", "Tear": "Rasgado", @@ -264,6 +271,7 @@ "This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "Esta cara non pode ofrecer unha ancoraxe duradeira. Escolle outra cara ou usa expresamente un plano fixo.", "To Offset": "Ata o desprazamento", "Tolerance": "Tolerancia", + "Trimming tool (plane, face or curves)": "Ferramenta de recorte (plano, cara ou curvas)", "Turn off section analysis before exporting the view.": "Desactiva a análise de sección antes de exportar a vista.", "Type": "Tipo", "UNTRIM": "DESRECORTAR", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index a1c8c9f4a..eeb2011c9 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -107,6 +107,7 @@ "Export Current View as DXF…": "現在の表示をDXFでエクスポート…", "Export DXF…": "DXFをエクスポート…", "Export hidden edges as dashed lines": "点線で出力", + "Extend to meet": "交わるまで延長", "Extents": "範囲", "Face": "面", "Face attachment lost": "面アタッチメントが失われました", @@ -135,7 +136,9 @@ "Interferes": "干渉あり", "Issue title": "Issueタイトル", "Joint Origin1": "ジョイント原点1", + "Keep (points on it)": "残す部分(その上の点)", "Keep Tools": "ツールボディを保持", + "Keep of the other surface": "相手のサーフェスで残す部分", "Later": "後で", "Leave it": "そのままにする", "Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "従来の面アタッチメントです。確定された面に再バインドすると正確なアタッチメントが作成されます。", @@ -173,6 +176,7 @@ "Open GitHub draft": "GitHubの下書きを開く", "Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "Rust製オープンソース・パラメトリック3D CAD。ライセンス: MIT または Apache-2.0。", "Other side": "反対側", + "Other surface (mutual trim)": "相手のサーフェス(相互トリム)", "Outside": "外側", "Overall length": "全長", "Parameter values": "パラメータ値", @@ -260,10 +264,13 @@ "Stand this part up?": "このパーツを正立させますか?", "Step": "ステップ", "Steps": "ステップ数", + "Stitch the kept pieces": "残した部分をステッチ", "Study": "スタディ", "Style": "スタイル", "Suppressed": "抑制", + "Surface": "サーフェス", "Swap Ends": "端点を入れ替え", + "TRIM": "トリム", "Tangent (G1)": "接線 (G1)", "Tangent Chain": "正接チェーン", "Tear": "引き裂き", @@ -281,6 +288,7 @@ "To Offset": "オフセットまで", "Tolerance": "公差", "Too close": "近すぎる", + "Trimming tool (plane, face or curves)": "トリムツール(平面、面、または曲線)", "Turn off section analysis before exporting the view.": "断面解析をオフにしてからエクスポートしてください。", "Type": "タイプ", "UNTRIM": "トリム解除", diff --git a/assets/locales/ko.json b/assets/locales/ko.json index e4a4fbef4..ba118b798 100644 --- a/assets/locales/ko.json +++ b/assets/locales/ko.json @@ -39,6 +39,7 @@ "Export Current View as DXF…": "현재 뷰를 DXF로 내보내기…", "Export DXF…": "DXF 내보내기…", "Export hidden edges as dashed lines": "숨겨진 모서리를 파선으로 내보내기", + "Extend to meet": "만날 때까지 연장", "Face": "면", "Faces": "면", "Find in Browser": "브라우저에서 찾기", @@ -49,6 +50,8 @@ "In place (surfaces)": "제자리에서 (서피스)", "In plane": "평면 내", "Inside": "안쪽", + "Keep (points on it)": "유지할 부분(그 위의 점)", + "Keep of the other surface": "다른 곡면에서 유지할 부분", "Length": "길이", "Max": "최대", "Min": "최소", @@ -58,6 +61,7 @@ "None": "없음", "Normal to sketch": "스케치에 수직", "Notch": "노치", + "Other surface (mutual trim)": "다른 곡면(상호 트림)", "Outside": "바깥쪽", "Overall length": "전체 길이", "Pass through": "통과점", @@ -87,12 +91,16 @@ "Sketch geometry and profiles": "스케치 기하 및 프로파일", "Sketch points": "스케치 점", "Slot width": "슬롯 폭", + "Stitch the kept pieces": "유지한 부분 재봉", "Study": "연구", + "Surface": "곡면", + "TRIM": "트림", "Tangent (G1)": "접선 (G1)", "Tear": "찢김", "Thickness Outside": "바깥쪽 두께", "Thin": "얇은 벽", "Thin Extrude": "얇은 벽 돌출", + "Trimming tool (plane, face or curves)": "트림 도구(평면, 면 또는 곡선)", "Turn off section analysis before exporting the view.": "뷰를 내보내기 전에 단면 분석을 끄세요.", "Type": "유형", "UNTRIM": "트림 해제", diff --git a/assets/locales/pt-BR.json b/assets/locales/pt-BR.json index da4c5c4e5..4e3328550 100644 --- a/assets/locales/pt-BR.json +++ b/assets/locales/pt-BR.json @@ -98,6 +98,7 @@ "Export Current View as DXF…": "Exportar vista atual como DXF…", "Export DXF…": "Exportar DXF…", "Export hidden edges as dashed lines": "Exportar arestas ocultas como linhas tracejadas", + "Extend to meet": "Estender até encontrar", "Extents": "Extensões", "Face": "Face", "Face attachment lost": "Fixação à face perdida", @@ -126,7 +127,9 @@ "Interferes": "Interfere", "Issue title": "Título da issue", "Joint Origin1": "Origem da junta1", + "Keep (points on it)": "Manter (pontos sobre ela)", "Keep Tools": "Manter ferramentas", + "Keep of the other surface": "Manter da outra superfície", "Later": "Depois", "Leave it": "Deixar assim", "Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "Fixação de face antiga. Vincular novamente a uma face certificada cria uma fixação exata.", @@ -162,6 +165,7 @@ "Open GitHub draft": "Abrir rascunho no GitHub", "Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "CAD 3D paramétrico de código aberto em Rust. Licenciado sob MIT OU Apache-2.0.", "Other side": "Outro lado", + "Other surface (mutual trim)": "Outra superfície (aparo mútuo)", "Outside": "Fora", "Overall length": "Comprimento total", "Parameter values": "Valores dos parâmetros", @@ -245,9 +249,12 @@ "Stand this part up?": "Colocar esta peça em pé?", "Step": "Passo", "Steps": "Passos", + "Stitch the kept pieces": "Costurar as partes mantidas", "Style": "Estilo", "Suppressed": "Suprimido", + "Surface": "Superfície", "Swap Ends": "Trocar extremidades", + "TRIM": "APARAR", "Tangent (G1)": "Tangente (G1)", "Tangent Chain": "Cadeia tangente", "Tear": "Rasgo", @@ -264,6 +271,7 @@ "This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "Esta face não pode fornecer uma fixação duradoura. Escolha outra face ou use explicitamente um plano fixo.", "To Offset": "Deslocamento final", "Tolerance": "Tolerância", + "Trimming tool (plane, face or curves)": "Ferramenta de aparo (plano, face ou curvas)", "Turn off section analysis before exporting the view.": "Desative a análise de seção antes de exportar a vista.", "Type": "Tipo", "UNTRIM": "DESAPARAR", diff --git a/assets/locales/ru.json b/assets/locales/ru.json index bcfadce6e..7cc15552e 100644 --- a/assets/locales/ru.json +++ b/assets/locales/ru.json @@ -88,6 +88,7 @@ "Enabled": "Включено", "Explode": "Разобрать", "Export Animation…": "Экспортировать анимацию…", + "Extend to meet": "Продлить до пересечения", "Extents": "Пределы", "Face attachment lost": "Привязка к грани потеряна", "Faces": "Грани", @@ -110,7 +111,9 @@ "Interferes": "Пересекается", "Issue title": "Заголовок Issue", "Joint Origin1": "Точка сопряжения1", + "Keep (points on it)": "Оставить (точки на нём)", "Keep Tools": "Оставить инструменты", + "Keep of the other surface": "Оставить от другой поверхности", "Later": "Позже", "Leave it": "Оставить как есть", "Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "Устаревшая привязка к грани. Перепривязка к сертифицированной грани создаёт точную привязку.", @@ -142,6 +145,7 @@ "Open GitHub draft": "Открыть черновик на GitHub", "Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "Открытая параметрическая 3D CAD на Rust. Лицензия MIT OR Apache-2.0.", "Other side": "Другая сторона", + "Other surface (mutual trim)": "Другая поверхность (взаимная обрезка)", "Parameter values": "Значения параметров", "Pass through": "Через точки", "Path": "Траектория", @@ -218,10 +222,13 @@ "Stand this part up?": "Поставить эту деталь вертикально?", "Step": "Шаг", "Steps": "Шаги", + "Stitch the kept pieces": "Сшить оставленные части", "Study": "Исследование", "Style": "Стиль", "Suppressed": "Подавлено", + "Surface": "Поверхность", "Swap Ends": "Поменять концы", + "TRIM": "ОБРЕЗКА", "Tangent (G1)": "Касание (G1)", "Tangent Chain": "Касательная цепочка", "Tear": "Разрыв", @@ -235,6 +242,7 @@ "This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "Эта грань не может обеспечить надёжную привязку. Выберите другую грань или явно используйте фиксированную плоскость.", "To Offset": "До смещения", "Tolerance": "Допуск", + "Trimming tool (plane, face or curves)": "Инструмент обрезки (плоскость, грань или кривые)", "Type": "Тип", "Updating the preview": "Обновление предпросмотра", "Use active author placement": "Использовать активное исходное положение", diff --git a/assets/locales/tr.json b/assets/locales/tr.json index 513250cd1..861dd5fc5 100644 --- a/assets/locales/tr.json +++ b/assets/locales/tr.json @@ -92,6 +92,7 @@ "Enabled": "Etkin", "Explode": "Patlat", "Export Animation…": "Animasyonu dışa aktar…", + "Extend to meet": "Buluşana kadar uzat", "Extents": "Kapsamlar", "Face": "Yüz", "Face attachment lost": "Yüze bağlama kayboldu", @@ -119,7 +120,9 @@ "Interferes": "Girişim var", "Issue title": "Sorun başlığı", "Joint Origin1": "Bağlantı orijini1", + "Keep (points on it)": "Koru (üzerindeki noktalar)", "Keep Tools": "Araçları koru", + "Keep of the other surface": "Diğer yüzeyden korunacak", "Later": "Daha sonra", "Leave it": "Olduğu gibi bırak", "Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "Eski tip yüz bağlaması. Doğrulanmış bir yüze yeniden bağlamak tam bir bağlama oluşturur.", @@ -154,6 +157,7 @@ "Open GitHub draft": "GitHub taslağını aç", "Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "Rust ile yazılmış açık kaynaklı parametrik 3D CAD. Lisans: MIT OR Apache-2.0.", "Other side": "Diğer taraf", + "Other surface (mutual trim)": "Diğer yüzey (karşılıklı kırpma)", "Outside": "Dış", "Overall length": "Toplam uzunluk", "Parameter values": "Parametre değerleri", @@ -236,10 +240,13 @@ "Stand this part up?": "Bu parça dik çevrilsin mi?", "Step": "Adım", "Steps": "Adımlar", + "Stitch the kept pieces": "Korunan parçaları dik", "Study": "Etüt", "Style": "Stil", "Suppressed": "Bastırılmış", + "Surface": "Yüzey", "Swap Ends": "Uçları değiştir", + "TRIM": "KIRP", "Tangent Chain": "Teğet zincir", "The dashed sketch is a saved plane guide. Select a new face to repair the attachment.": "Kesikli eskiz, kaydedilmiş bir düzlem kılavuzudur. Bağlamayı onarmak için yeni bir yüz seçin.", "The saved author occurrence is missing. Select a valid author placement before rebinding.": "Kaydedilmiş kaynak örnek eksik. Yeniden bağlamadan önce geçerli bir kaynak yerleşimi seçin.", @@ -254,6 +261,7 @@ "This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "Bu yüz kalıcı bir bağlama sağlayamaz. Başka bir yüz seçin veya açıkça sabit bir düzlem kullanın.", "To Offset": "Ofsete kadar", "Tolerance": "Tolerans", + "Trimming tool (plane, face or curves)": "Kırpma aracı (düzlem, yüz veya eğriler)", "Type": "Tür", "UNTRIM": "KIRPMAYI KALDIR", "Updating the preview": "Önizleme güncelleniyor", diff --git a/assets/locales/uk.json b/assets/locales/uk.json index 898789df4..2a936339b 100644 --- a/assets/locales/uk.json +++ b/assets/locales/uk.json @@ -103,6 +103,7 @@ "Export Current View as DXF…": "Експортувати поточний вид як DXF…", "Export DXF…": "Експорт DXF…", "Export hidden edges as dashed lines": "Експортувати приховані ребра як штрихові лінії", + "Extend to meet": "Подовжити до перетину", "Extents": "Межі", "Face": "Грань", "Face attachment lost": "Втрачено прив'язку до грані", @@ -131,7 +132,9 @@ "Interferes": "Перетинається", "Issue title": "Заголовок повідомлення", "Joint Origin1": "Початок з'єднання1", + "Keep (points on it)": "Залишити (точки на ньому)", "Keep Tools": "Зберегти інструменти", + "Keep of the other surface": "Залишити від іншої поверхні", "Later": "Пізніше", "Leave it": "Залишити як є", "Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "Застаріла прив'язка до грані. Повторна прив'язка до перевіреної грані створює точну прив'язку.", @@ -168,6 +171,7 @@ "Open GitHub draft": "Відкрити чернетку GitHub", "Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "Параметричний 3D-CAD з відкритим вихідним кодом на Rust. Ліцензовано за MIT OR Apache-2.0.", "Other side": "Інший бік", + "Other surface (mutual trim)": "Інша поверхня (взаємне обрізання)", "Outside": "Назовні", "Overall length": "Загальна довжина", "Parameter values": "Значення параметрів", @@ -254,10 +258,13 @@ "Stand this part up?": "Вирівняти цю деталь?", "Step": "Крок", "Steps": "Кроки", + "Stitch the kept pieces": "Зшити залишені частини", "Study": "Дослідження", "Style": "Стиль", "Suppressed": "Придушено", + "Surface": "Поверхня", "Swap Ends": "Поміняти кінці місцями", + "TRIM": "ОБРІЗАННЯ", "Tangent (G1)": "Дотик (G1)", "Tangent Chain": "Дотичний ланцюг", "Tear": "Розрив", @@ -274,6 +281,7 @@ "This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "Ця грань не може забезпечити надійну прив'язку. Виберіть іншу грань або явно використайте фіксовану площину.", "To Offset": "До зсуву", "Tolerance": "Допуск", + "Trimming tool (plane, face or curves)": "Інструмент обрізання (площина, грань або криві)", "Turn off section analysis before exporting the view.": "Вимкніть аналіз перерізу перед експортом виду.", "Type": "Тип", "UNTRIM": "ЗНЯТИ ОБРІЗАННЯ", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index 8daee673e..96b2405e0 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -107,6 +107,7 @@ "Export Current View as DXF…": "将当前视图导出为DXF…", "Export DXF…": "导出DXF…", "Export hidden edges as dashed lines": "以虚线导出隐藏线", + "Extend to meet": "延伸至相交", "Extents": "范围", "Face": "面", "Face attachment lost": "面附着丢失", @@ -135,7 +136,9 @@ "Interferes": "发生干涉", "Issue title": "Issue 标题", "Joint Origin1": "接头原点1", + "Keep (points on it)": "保留(其上的点)", "Keep Tools": "保留工具", + "Keep of the other surface": "另一曲面保留的部分", "Later": "稍后", "Leave it": "保持原样", "Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "旧版面附着。重新绑定到经验证的面可创建精确附着。", @@ -173,6 +176,7 @@ "Open GitHub draft": "打开 GitHub 草稿", "Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "使用 Rust 编写的开源参数化 3D CAD。基于 MIT OR Apache-2.0 许可。", "Other side": "另一侧", + "Other surface (mutual trim)": "另一曲面(相互修剪)", "Outside": "外侧", "Overall length": "总长", "Parameter values": "参数值", @@ -260,10 +264,13 @@ "Stand this part up?": "立起此零件?", "Step": "步骤", "Steps": "步数", + "Stitch the kept pieces": "缝合保留的部分", "Study": "研究", "Style": "样式", "Suppressed": "已抑制", + "Surface": "曲面", "Swap Ends": "交换端点", + "TRIM": "修剪", "Tangent (G1)": "相切 (G1)", "Tangent Chain": "相切链", "Tear": "撕裂", @@ -281,6 +288,7 @@ "To Offset": "偏移", "Tolerance": "公差", "Too close": "过近", + "Trimming tool (plane, face or curves)": "修剪工具(平面、面或曲线)", "Turn off section analysis before exporting the view.": "请关闭截面分析后再导出视图。", "Type": "类型", "UNTRIM": "取消修剪", diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index a661404b5..1ec44993b 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -1511,14 +1511,31 @@ pub enum FeatureKind { #[walk(length = "Tolerance")] tolerance: Expr, }, - /// A surface body trimmed by a plane, or by a face of a body (`tool`), keeping the side of - /// `keep`. + /// A surface body trimmed by a plane, by a face of a body (`tool`, its surface extended) or + /// by sketch curves swept onto it (`curves`), keeping the side of `keep`; with `keep_more`, + /// the regions (pieces that hang together once cut) `keep` and those points pick instead. + /// With `with`, a mutual trim: `body` and `with` (one face each) cut each other, `with` + /// keeping the side of its one `keep_with` point or the regions of several; `extend` + /// extends one that stops short of the other to meet it, and `stitch` sews the two kept + /// pieces into `body` (`with` is then gone). SurfaceTrim { body: BodyName, plane: PlaneRef, #[serde(default, skip_serializing_if = "Option::is_none")] tool: Option, keep: Position, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + keep_more: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + curves: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + with: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + keep_with: Vec, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + stitch: bool, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + extend: bool, }, Move { bodies: Vec, @@ -1689,6 +1706,18 @@ impl FilletStyle { } } +/// Sketch curves a trim cuts with: chains of the curves `curves` (every curve of the sketch +/// that is not construction geometry when empty) swept along `direction` (the sketch's normal +/// when none) onto the surface. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, solidcraft_derive::Walk)] +pub struct TrimCurves { + pub sketch: SketchId, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub curves: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub direction: Option, +} + /// A face picked by a point on it, on a named body. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, solidcraft_derive::Walk)] pub struct FaceAt { diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 195280f6c..153b2561f 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -5019,7 +5019,7 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: if curves.is_empty() { return Err(DocError::Invalid(format!("sketch `{}` has no curves to split with", ss.name))); } - kernel::split_faces(&mb.body, &picked, &kernel::SplitTool::Curves { plane: ss.plane, curves })? + kernel::split_faces(&mb.body, &picked, &kernel::SplitTool::Curves { plane: ss.plane, curves, along: None })? } (None, None) => { let pl = doc.resolve_plane_in(vals, plane, 0, Some(st))?; diff --git a/crates/doc/src/eval_surface.rs b/crates/doc/src/eval_surface.rs index 227a126a7..b59d557fc 100644 --- a/crates/doc/src/eval_surface.rs +++ b/crates/doc/src/eval_surface.rs @@ -67,20 +67,46 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, } apply_op(st, f, tools, *operation, &crate::plain(targets)) } - FeatureKind::SurfaceTrim { body, plane, tool, keep } => { + FeatureKind::SurfaceTrim { body, plane, tool, keep, keep_more, curves, with, keep_with, stitch, extend } => { let i = st.bodies.iter().position(|b| &b.name == body).ok_or_else(|| DocError::Unknown(format!("body `{body}`")))?; let Some(mb) = st.bodies.get(i).cloned() else { return Err(DocError::Invalid("body".into())) }; - let trimmed = match tool { - Some(t) => { + let picks: Vec = std::iter::once(keep.0).chain(keep_more.iter().map(|p| p.0)).collect(); + let keeps = if keep_more.is_empty() { kernel::TrimKeep::Side(keep.0) } else { kernel::TrimKeep::Regions(&picks) }; + if let Some(other) = with { + return mutual_trim(st, i, other, keeps, &crate::plain(keep_with), *stitch, *extend); + } + let trimmed = match (tool, curves) { + (Some(t), _) => { let tb = st.body(&t.body).ok_or_else(|| DocError::Unknown(format!("body `{}`", t.body)))?; let face = crate::appearance::face_index_at(tb, t.point.0) .ok_or_else(|| DocError::Invalid(format!("no face of `{}` at the tool point", t.body)))?; - kernel::trim(&mb.body, &kernel::SplitTool::Face { body: &tb.body, face }, keep.0)? + kernel::trim_keep(&mb.body, &kernel::SplitTool::Face { body: &tb.body, face }, keeps)? } - None => kernel::trim(&mb.body, &kernel::SplitTool::Plane(doc.resolve_plane_in(vals, plane, 0, Some(st))?), keep.0)?, + (None, Some(c)) => { + let ss = st + .sketch(c.sketch.0) + .ok_or_else(|| DocError::Unknown(format!("sketch {} (it must come earlier in the timeline)", c.sketch)))?; + let ss = sketch_in_feature_frame(doc, ss, f.component)?; + let ids: Vec = if c.curves.is_empty() { + ss.sketch.curves.iter().filter(|k| !k.construction).map(|k| k.id.clone()).collect() + } else { + c.curves.clone() + }; + let chains = curve_chains(&ss, &ids)?; + if chains.is_empty() { + return Err(DocError::Invalid(format!("sketch `{}` has no curves to trim with", ss.name))); + } + kernel::trim_keep( + &mb.body, + &kernel::SplitTool::Curves { plane: ss.plane, curves: chains, along: c.direction.map(|d| d.0) }, + keeps, + )? + } + (None, None) => kernel::trim_keep(&mb.body, &kernel::SplitTool::Plane(doc.resolve_plane_in(vals, plane, 0, Some(st))?), keeps)?, }; + let made = Traced::step(trimmed, &[&mb.traced()]); if let Some(slot) = st.bodies.get_mut(i) { - *slot = ModelBody::new(mb.name, trimmed, mb.feature); + *slot = ModelBody::traced_new(mb.name, made, mb.feature); } Ok(()) } @@ -669,6 +695,43 @@ fn boundary_frames( Ok(out) } +/// Mutual Trim: the body at `i` and `other` trimmed by each other (each keeping its picks), the +/// kept pieces sewn into the first when `stitch`; their faces named after the faces they are +/// pieces of. +fn mutual_trim(st: &mut ModelState, i: usize, other: &str, keeps: kernel::TrimKeep, keep_with: &[Vec3], stitch: bool, extend: bool) -> Result<()> { + let j = st.bodies.iter().position(|b| b.name == other).ok_or_else(|| DocError::Unknown(format!("body `{other}`")))?; + if i == j { + return Err(DocError::Invalid("a surface can't trim itself: pick another surface".into())); + } + let (Some(a), Some(b)) = (st.bodies.get(i).cloned(), st.bodies.get(j).cloned()) else { return Err(DocError::Invalid("body".into())) }; + let keeps_with = match keep_with { + [] => return Err(DocError::Invalid(format!("pick the side of `{other}` to keep"))), + [p] => kernel::TrimKeep::Side(*p), + ps => kernel::TrimKeep::Regions(ps), + }; + let (ta, tb) = kernel::mutual_trim(&a.body, &b.body, keeps, keeps_with, extend)?; + let (ta, tb) = (Traced::step(ta, &[&a.traced()]), Traced::step(tb, &[&b.traced()])); + if stitch { + let sewn = kernel::stitch(&[&ta.body, &tb.body], 0.0)?; + if sewn.edge_count() >= ta.body.edge_count() + tb.body.edge_count() { + return Err(DocError::Invalid("the trimmed surfaces don't meet along an edge: they can't be stitched".into())); + } + let sewn = Traced::step(sewn, &[&ta, &tb]); + if let Some(slot) = st.bodies.get_mut(i) { + *slot = ModelBody::traced_new(a.name, sewn, a.feature); + } + st.bodies.retain(|x| x.name != other); + } else { + if let Some(slot) = st.bodies.get_mut(i) { + *slot = ModelBody::traced_new(a.name, ta, a.feature); + } + if let Some(slot) = st.bodies.get_mut(j) { + *slot = ModelBody::traced_new(b.name, tb, b.feature); + } + } + Ok(()) +} + /// What a surface builder sweeps: the boundary loops of the picked profiles, then the picked /// curves chained end to end. fn sheet_chains(ss: &SolvedSketch, profiles: Option<&ProfileSel>, curves: &[String]) -> Result>> { diff --git a/crates/doc/src/feature_walk_tests/fixtures.rs b/crates/doc/src/feature_walk_tests/fixtures.rs index 71cecf9b3..ba9d31fdb 100644 --- a/crates/doc/src/feature_walk_tests/fixtures.rs +++ b/crates/doc/src/feature_walk_tests/fixtures.rs @@ -188,6 +188,15 @@ pub(super) fn fixtures() -> Vec<(&'static str, Value)> { "direction": [0, 0, 1], "face": [1, 0, 0]}), ), ("surface_trim", json!({"type": "surface_trim", "body": "B", "plane": plane("trim"), "keep": o})), + ( + "surface_trim_curves", + json!({"type": "surface_trim", "body": "B", "plane": plane("trim"), "keep": o, "keep_more": [o], + "curves": {"sketch": 1, "curves": ["l1"], "direction": [0, 0, 1]}}), + ), + ( + "surface_trim_mutual", + json!({"type": "surface_trim", "body": "B", "plane": plane("trim"), "keep": o, "with": "B", "keep_with": [o, o], "stitch": true, "extend": true}), + ), ("move", json!({"type": "move", "bodies": ["B"], "translate": ["move.x", "move.y", "move.z"], "angle": "move.angle"})), ("import", json!({"type": "import", "file": "a.step", "step": ""})), ("mesh_convert", json!({"type": "mesh_convert", "body": "B", "tolerance": "mesh_convert.tolerance"})), diff --git a/crates/doc/src/feature_walk_tests/golden_exprs.txt b/crates/doc/src/feature_walk_tests/golden_exprs.txt index d89871472..5a4f9da2e 100644 --- a/crates/doc/src/feature_walk_tests/golden_exprs.txt +++ b/crates/doc/src/feature_walk_tests/golden_exprs.txt @@ -375,6 +375,16 @@ surface_trim Angle = trim.angle (Angle) Offset = trim.offset (Length) expressions: trim.angle, trim.offset +surface_trim_curves + inputs: + Angle = trim.angle (Angle) + Offset = trim.offset (Length) + expressions: trim.angle, trim.offset +surface_trim_mutual + inputs: + Angle = trim.angle (Angle) + Offset = trim.offset (Length) + expressions: trim.angle, trim.offset move inputs: X distance = move.x (Length) diff --git a/crates/doc/src/feature_walk_tests/golden_geometry.txt b/crates/doc/src/feature_walk_tests/golden_geometry.txt index 314c4607f..af2ef727d 100644 --- a/crates/doc/src/feature_walk_tests/golden_geometry.txt +++ b/crates/doc/src/feature_walk_tests/golden_geometry.txt @@ -183,6 +183,10 @@ surface_ruled face points: [1, 0, 0] surface_trim moves: keep[0], keep[1], keep[2], plane.axis_dir[0], plane.axis_dir[1], plane.axis_origin[0], plane.axis_origin[1], plane.axis_origin[2], tool.point[0], tool.point[1], tool.point[2] +surface_trim_curves + moves: curves.direction[0], curves.direction[2], keep[0], keep[1], keep[2], keep_more[0][0], keep_more[0][1], keep_more[0][2], plane.axis_dir[0], plane.axis_dir[1], plane.axis_origin[0], plane.axis_origin[1], plane.axis_origin[2] +surface_trim_mutual + moves: keep[0], keep[1], keep[2], keep_with[0][0], keep_with[0][1], keep_with[0][2], keep_with[1][0], keep_with[1][1], keep_with[1][2], plane.axis_dir[0], plane.axis_dir[1], plane.axis_origin[0], plane.axis_origin[1], plane.axis_origin[2] move moves: rotate_axis[1], rotate_axis[2] import diff --git a/crates/doc/src/feature_walk_tests/golden_refs.txt b/crates/doc/src/feature_walk_tests/golden_refs.txt index 386158c4e..5eeaff421 100644 --- a/crates/doc/src/feature_walk_tests/golden_refs.txt +++ b/crates/doc/src/feature_walk_tests/golden_refs.txt @@ -208,6 +208,13 @@ surface_ruled surface_trim remap_refs: plane.base.base.name remap_bodies: body, tool.body +surface_trim_curves + sketches: [1] + remap_refs: curves.sketch, plane.base.base.name + remap_bodies: body +surface_trim_mutual + remap_refs: plane.base.base.name + remap_bodies: body, with move remap_bodies: bodies[0] import diff --git a/crates/doc/src/format/pending/surface-trim-regions-curves-mutual.rs b/crates/doc/src/format/pending/surface-trim-regions-curves-mutual.rs new file mode 100644 index 000000000..7fb3ba86f --- /dev/null +++ b/crates/doc/src/format/pending/surface-trim-regions-curves-mutual.rs @@ -0,0 +1,6 @@ +//! A `SurfaceTrim` can keep several regions (`keep_more`: more points; with them, the pieces that +//! hang together once cut that `keep` and these points pick are kept instead of the side of +//! `keep`), cut with sketch curves swept onto the surface (`curves`: `sketch`, optional `curves` +//! ids and `direction`), or trim another surface and be trimmed by it (`with`, `keep_with` points, +//! optional `stitch` and `extend`). Older designs need no transformation: a trim without them +//! saves as before; 0.14.x asks for an update instead of ignoring them and trimming by the plane. diff --git a/crates/engine/src/cmd/surface.rs b/crates/engine/src/cmd/surface.rs index ea161f8e9..32fb50bc1 100644 --- a/crates/engine/src/cmd/surface.rs +++ b/crates/engine/src/cmd/surface.rs @@ -4,7 +4,7 @@ use serde_json::Value; use solidcraft_doc::{ BlendSide, EdgeContinuity, Expr, ExtendMode, ExtendTo, FaceAt, FeatureKind, PatchContinuity, PlaneRef, ProfileSel, RuledCorners, RuledMode, - expr::Kind, + TrimCurves, expr::Kind, }; use solidcraft_doc::{BodyName, SketchId}; use solidcraft_doc::{Dir, FacePick, Position}; @@ -35,7 +35,7 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("surface.trim", "Trim", trim) .at("SURFACE", "MODIFY") .icon("surface_trim") - .params("body: surface name; plane: XY|XZ|YZ|plane name|{origin, normal} or tool: {body, point} (a face, its surface extended); keep: [x,y,z] (a point on the side to keep)"), + .params("body: surface name; plane: XY|XZ|YZ|plane name|{origin, normal} or tool: {body, point} (a face, its surface extended) or curves: {sketch, curves?: [curve ids] (chains of curves meeting end to end; default every curve), direction?: normal|[x,y,z] (swept onto the surface along the sketch's normal, the default, or this direction)}; keep: [x,y,z] (a point on the side to keep) or [[x,y,z], ...] (points on the regions to keep: the pieces that hang together once cut). Mutual trim: with: another surface (one face each; leave out plane, tool and curves), keep_with: [x,y,z] or [[x,y,z], ...] (what to keep of it); each is cut where the other's surface (extended) meets it; extend?: bool (a surface that stops short of the other is extended to meet it); stitch?: bool (the kept pieces sewn into `body`; `with` is then gone)"), CommandSpec::new("surface.extrude", "Surface Extrude", surface_extrude) .at("SURFACE", "CREATE") .icon("surface_extrude") @@ -595,22 +595,117 @@ fn extend(s: &mut Session, p: &Value) -> Result { ) } +/// Points to keep: one `[x, y, z]`, or a list of them (at most 10 000). +fn keep_points(v: Option<&Value>, cmd: &str, key: &str) -> Result> { + let Some(v) = v.filter(|v| !v.is_null()) else { return Ok(Vec::new()) }; + if let Some(p) = vec3(v) { + return Ok(vec![p]); + } + let list = v + .as_array() + .filter(|a| !a.is_empty() && a.len() <= 10_000) + .ok_or_else(|| bad(cmd, format!("`{key}` must be [x, y, z] or a list of them")))?; + list.iter().map(|q| vec3(q).ok_or_else(|| bad(cmd, format!("`{key}` must be [x, y, z] or a list of them")))).collect() +} + fn trim(s: &mut Session, p: &Value) -> Result { let cmd = "surface.trim"; let body = str_(p, "body").ok_or_else(|| bad(cmd, "`body` is required"))?.to_string(); if s.model.state().body(&body).is_none() { return Err(bad(cmd, format!("no body `{body}`"))); } - let keep = p.get("keep").and_then(vec3).ok_or_else(|| bad(cmd, "`keep` must be [x, y, z] on the side to keep"))?; - let (plane, tool) = match p.get("tool").filter(|t| !t.is_null()) { - Some(t) => { + let picks = keep_points(p.get("keep"), cmd, "keep")?; + let Some((&keep, more)) = picks.split_first() else { + return Err(bad(cmd, "`keep` must be [x, y, z] on the side to keep (or a list of points on the regions to keep)")); + }; + let keep_more = more.to_vec(); + let given = |k: &str| p.get(k).is_some_and(|v| !v.is_null()); + let xy = || PlaneRef::Origin { name: "XY".into() }; + if let Some(w) = p.get("with").filter(|v| !v.is_null()) { + let with = w.as_str().ok_or_else(|| bad(cmd, "`with` must name a surface body"))?.to_string(); + if with == body { + return Err(bad(cmd, "`with` must be another surface body")); + } + if s.model.state().body(&with).is_none() { + return Err(bad(cmd, format!("no body `{with}`"))); + } + if given("plane") || given("tool") || given("curves") { + return Err(bad(cmd, "a mutual trim cuts each surface with the other: leave out `plane`, `tool` and `curves`")); + } + let keep_with = keep_points(p.get("keep_with"), cmd, "keep_with")?; + if keep_with.is_empty() { + return Err(bad(cmd, "`keep_with` must be [x, y, z] on the side of the other surface to keep")); + } + let (stitch, extend) = (bool_(p, "stitch").unwrap_or(false), bool_(p, "extend").unwrap_or(false)); + let kind = FeatureKind::SurfaceTrim { + body: BodyName(body), + plane: xy(), + tool: None, + keep: Position(keep), + keep_more: keep_more.into_iter().map(Position).collect(), + curves: None, + with: Some(BodyName(with)), + keep_with: keep_with.into_iter().map(Position).collect(), + stitch, + extend, + }; + return add_feature(s, p, kind); + } + if given("keep_with") || given("stitch") || given("extend") { + return Err(bad(cmd, "`keep_with`, `stitch` and `extend` belong to a mutual trim (`with`)")); + } + let (plane, tool, curves) = match (p.get("tool").filter(|t| !t.is_null()), p.get("curves").filter(|c| !c.is_null())) { + (Some(_), Some(_)) => return Err(bad(cmd, "give `tool` or `curves`, not both")), + (Some(t), None) => { let tb = t.get("body").and_then(Value::as_str).ok_or_else(|| bad(cmd, "`tool.body` must name a body"))?.to_string(); let point = t.get("point").and_then(vec3).ok_or_else(|| bad(cmd, "`tool.point` must be [x, y, z] on the tool face"))?; - (PlaneRef::Origin { name: "XY".into() }, Some(FaceAt { body: BodyName(tb), point: Position(point) })) + (xy(), Some(FaceAt { body: BodyName(tb), point: Position(point) }), None) } - None => (plane_param(s, p.get("plane"), cmd)?, None), + (None, Some(c)) => { + let sketch = sketch_id(s, c.get("sketch"), cmd, "curves.sketch")?; + let ids = match c.get("curves").filter(|v| !v.is_null()) { + None => Vec::new(), + Some(v) => { + let a = v.as_array().filter(|a| a.len() <= 1000).ok_or_else(|| bad(cmd, "`curves.curves` must list curve ids"))?; + a.iter() + .map(|x| x.as_str().map(str::to_string).ok_or_else(|| bad(cmd, "`curves.curves` must list curve ids"))) + .collect::>>()? + } + }; + let direction = match c.get("direction").filter(|v| !v.is_null()) { + None => None, + Some(Value::String(d)) if d.trim() == "normal" => None, + Some(Value::String(d)) if d.trim() == "face_normal" => { + return Err(bad( + cmd, + "not supported yet: projecting curves along the surface's normal (#767); project along the sketch's normal or a direction", + )); + } + Some(v) => { + let d = vec3(v).ok_or_else(|| bad(cmd, "`curves.direction` must be normal or [x, y, z]"))?; + if !(d.len() > 1e-12) { + return Err(bad(cmd, "`curves.direction` must not be zero")); + } + Some(d) + } + }; + (xy(), None, Some(TrimCurves { sketch: SketchId(sketch), curves: ids, direction: direction.map(Dir) })) + } + (None, None) => (plane_param(s, p.get("plane"), cmd)?, None, None), }; - add_feature(s, p, FeatureKind::SurfaceTrim { body: BodyName(body), plane, tool, keep: Position(keep) }) + let kind = FeatureKind::SurfaceTrim { + body: BodyName(body), + plane, + tool, + keep: Position(keep), + keep_more: keep_more.into_iter().map(Position).collect(), + curves, + with: None, + keep_with: Vec::new(), + stitch: false, + extend: false, + }; + add_feature(s, p, kind) } /// `surface.fair`: the B-spline faces of a body faired in place. The tolerance a caller leaves @@ -1284,6 +1379,193 @@ mod tests { assert_eq!(s.doc.features.len(), before, "a planned command changed the design"); } + /// A rectangle patch in a plane (`plane`: a sketch plane name), corners (u0, v0) and (u1, v1) + /// in its coordinates. + fn sheet(s: &mut Session, plane: &str, name: &str, p0: [f64; 2], p1: [f64; 2]) { + let sk = format!("{name} sketch"); + run(s, "sketch.create", json!({"plane": plane, "name": sk})); + run(s, "sketch.rectangle.two_point", json!({"p0": p0, "p1": p1})); + run(s, "sketch.finish", json!({})); + run(s, "surface.patch", json!({"sketch": sk, "body_name": name})); + } + + fn names(s: &Session, body: &str) -> Vec { + solidcraft_doc::naming::face_names(s.model.state().body(body).unwrap()).to_vec() + } + + fn exact(s: &Session, body: &str, i: usize) -> bool { + solidcraft_doc::naming::face_name_exact(s.model.state().body(body).unwrap(), i) + } + + /// Two 20 × 10 sheets crossing at right angles (z = 0 and x = 0, both y = 0…10), trimmed by + /// each other and stitched: an L of two faces sharing one edge (7 edges), 200 in area; each + /// face named after the sheet it is a piece of. Undo, redo and reopening rebuild it. + #[test] + fn mutual_trim_stitches_crossing_sheets_into_an_l() { + let mut s = Session::default(); + sheet(&mut s, "XY", "Floor", [-10.0, 0.0], [10.0, 10.0]); + // YZ sketches have u along Y and v along Z. + sheet(&mut s, "YZ", "Wall", [0.0, -10.0], [10.0, 10.0]); + let (floor, wall) = (names(&s, "Floor"), names(&s, "Wall")); + // (A patch's face is named from geometry; its pieces inherit that, no surer.) + let sure = exact(&s, "Floor", 0); + run(&mut s, "surface.trim", json!({"body": "Floor", "keep": [5, 5, 0], "with": "Wall", "keep_with": [0, 5, 5], "stitch": true})); + let st = s.world_state(); + assert!(st.body("Wall").is_none(), "sewn into the floor"); + let l = &st.body("Floor").unwrap().body; + assert!(l.is_surface()); + assert_eq!((l.face_count(), l.edge_count()), (2, 7), "one connected sheet"); + assert!((area(&s, "Floor") - 200.0).abs() < 1e-9, "{}", area(&s, "Floor")); + let bb = solidcraft_kernel::measure(l).unwrap().bbox; + assert!(bb.min.x.abs() < 1e-9 && bb.min.z.abs() < 1e-9 && (bb.max.x - 10.0).abs() < 1e-9 && (bb.max.z - 10.0).abs() < 1e-9, "{bb:?}"); + let mut got = names(&s, "Floor"); + got.sort(); + let mut want = vec![floor[0].clone(), wall[0].clone()]; + want.sort(); + assert_eq!(got, want, "each face named after its sheet"); + assert!(exact(&s, "Floor", 0) == sure && exact(&s, "Floor", 1) == sure); + let saved = s.doc.to_json(); + run(&mut s, "edit.undo", json!({})); + assert!(s.world_state().body("Wall").is_some() && (area(&s, "Floor") - 200.0).abs() < 1e-9); + run(&mut s, "edit.redo", json!({})); + let cold = Session::new(solidcraft_doc::Document::from_json(&saved).unwrap()); + assert!((area(&cold, "Floor") - 200.0).abs() < 1e-9 && cold.world_state().body("Wall").is_none()); + // Without stitching, each keeps its half under its own name. + run(&mut s, "edit.undo", json!({})); + run(&mut s, "surface.trim", json!({"body": "Floor", "keep": [-5, 5, 0], "with": "Wall", "keep_with": [0, 5, -5]})); + assert!((area(&s, "Floor") - 100.0).abs() < 1e-9 && (area(&s, "Wall") - 100.0).abs() < 1e-9); + let bb = solidcraft_kernel::measure(&s.world_state().body("Wall").unwrap().body).unwrap().bbox; + assert!((bb.max.z).abs() < 1e-9, "the wall's lower half: {bb:?}"); + } + + /// A wall that stops 3 short of the floor is refused until `extend` brings it down to meet + /// it; then the two make the L. + #[test] + fn mutual_trim_extends_a_short_sheet() { + let mut s = Session::default(); + sheet(&mut s, "XY", "Floor", [-10.0, 0.0], [10.0, 10.0]); + sheet(&mut s, "YZ", "Wall", [0.0, 3.0], [10.0, 10.0]); + let mutual = json!({"body": "Floor", "keep": [5, 5, 0], "with": "Wall", "keep_with": [0, 5, 5], "stitch": true}); + let e = s.execute("surface.trim", &mutual).unwrap_err().to_string(); + assert!(e.contains("extend"), "{e}"); + let mut asked = mutual.clone(); + asked["extend"] = json!(true); + run(&mut s, "surface.trim", asked); + let st = s.world_state(); + let l = &st.body("Floor").unwrap().body; + assert_eq!((l.face_count(), l.edge_count()), (2, 7)); + assert!((area(&s, "Floor") - 200.0).abs() < 1e-6, "{}", area(&s, "Floor")); + } + + /// The slot |x| ≤ 3, round ends at z = 12 and 28 (overall 9…31), drawn on XZ and swept along + /// its normal onto a half cylinder (radius 10 about Z, y ≥ 0, 40 high): the piece inside is + /// ∫∫ R / √(R² − x²) dx dz over the slot, the straight run 16 · 2R·asin(3/R) and the round + /// ends one disc (Simpson in φ, x = 3 sin φ). Picking the inside region gives the same + /// piece; a direction along the face's normal is not supported yet. + #[test] + fn trim_a_cylinder_by_a_projected_slot() { + let pi = std::f64::consts::PI; + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"})); + let arc = run(&mut s, "sketch.arc.three_point", json!({"start": [10, 0], "end": [-10, 0], "through": [0, 10]}))["created"]["curves"][0] + .as_str() + .unwrap() + .to_string(); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "surface.extrude", json!({"sketch": "S", "curves": [arc], "distance": 40, "body_name": "Half"})); + let source = names(&s, "Half"); + // XZ sketches have v along −Z. + run(&mut s, "sketch.create", json!({"plane": "XZ", "name": "Slot"})); + run(&mut s, "sketch.slot.overall", json!({"p0": [0, -9], "p1": [0, -31], "width": 6})); + run(&mut s, "sketch.finish", json!({})); + let (r, a): (f64, f64) = (10.0, 3.0); + let n = 4000; + let f = |phi: f64| 2.0 * a * a * phi.cos().powi(2) * r / (r * r - (a * phi.sin()).powi(2)).sqrt(); + let h = pi / n as f64; + let ends = (0..=n) + .map(|k| { + (if k == 0 || k == n { + 1.0 + } else if k % 2 == 1 { + 4.0 + } else { + 2.0 + }) * f(-pi / 2.0 + h * k as f64) + }) + .sum::() + * h + / 3.0; + let inside = 16.0 * 2.0 * r * (a / r).asin() + ends; + run(&mut s, "surface.trim", json!({"body": "Half", "curves": {"sketch": "Slot"}, "keep": [0, 10, 20]})); + // (Measured on meshes.) + assert!((area(&s, "Half") - inside).abs() < inside * 1e-3, "{} vs {inside}", area(&s, "Half")); + assert_eq!(names(&s, "Half"), source, "the piece is the cylinder's face"); + assert!(exact(&s, "Half", 0)); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "surface.trim", json!({"body": "Half", "curves": {"sketch": "Slot", "direction": "normal"}, "keep": [[0, 10, 20]]})); + assert!((area(&s, "Half") - inside).abs() < inside * 1e-3, "{}", area(&s, "Half")); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "surface.trim", json!({"body": "Half", "curves": {"sketch": "Slot"}, "keep": [10, 0, 20]})); + let rest = pi * r * 40.0 - inside; + assert!((area(&s, "Half") - rest).abs() < rest * 1e-3, "{} vs {rest}", area(&s, "Half")); + run(&mut s, "edit.undo", json!({})); + let e = s + .execute("surface.trim", &json!({"body": "Half", "curves": {"sketch": "Slot", "direction": "face_normal"}, "keep": [0, 10, 20]})) + .unwrap_err(); + assert!(e.to_string().contains("not supported yet"), "{e}"); + } + + /// A U-shaped sheet (legs at x = 0 and 10, 10 high; base along y = 0; 10 deep) cut by the + /// plane y = 5: one point keeps its side (both legs' tops, 100), a list of points the regions + /// they pick (one leg's top, 50; the base region, 200). + #[test] + fn trim_keeps_several_regions() { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "U"})); + let created = run(&mut s, "sketch.line", json!({"points": [[0, 10], [0, 0], [10, 0], [10, 10]]})); + let ids: Vec = created["created"]["curves"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_string()).collect(); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "surface.extrude", json!({"sketch": "U", "curves": ids, "distance": 10, "body_name": "U"})); + let cut = json!({"origin": [0, 5, 0], "normal": [0, 1, 0]}); + run(&mut s, "surface.trim", json!({"body": "U", "plane": cut, "keep": [0, 8, 5]})); + assert!((area(&s, "U") - 100.0).abs() < 1e-9, "{}", area(&s, "U")); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "surface.trim", json!({"body": "U", "plane": cut, "keep": [[0, 8, 5], [0, 9, 1]]})); + assert!((area(&s, "U") - 50.0).abs() < 1e-9, "{}", area(&s, "U")); + let saved = s.doc.to_json(); + assert!(saved.contains("\"keep_more\""), "the other points are saved"); + let cold = Session::new(solidcraft_doc::Document::from_json(&saved).unwrap()); + assert!((area(&cold, "U") - 50.0).abs() < 1e-9); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "surface.trim", json!({"body": "U", "plane": cut, "keep": [[5, 0, 5], [10, 1, 5]]})); + assert!((area(&s, "U") - 200.0).abs() < 1e-9, "{}", area(&s, "U")); + } + + /// Trim requests that make no sense are refused and leave the design as it was. + #[test] + fn trim_refuses_bad_requests() { + let mut s = Session::default(); + sheet(&mut s, "XY", "Floor", [-10.0, 0.0], [10.0, 10.0]); + sheet(&mut s, "YZ", "Wall", [0.0, -10.0], [10.0, 10.0]); + let before = s.doc.features.len(); + for p in [ + json!({"body": "Floor", "with": "Floor", "keep": [5, 5, 0], "keep_with": [5, 5, 0]}), + json!({"body": "Floor", "with": "Nope", "keep": [5, 5, 0], "keep_with": [0, 5, 5]}), + json!({"body": "Floor", "with": "Wall", "keep": [5, 5, 0]}), + json!({"body": "Floor", "with": "Wall", "keep": [5, 5, 0], "keep_with": [0, 5, 5], "plane": "YZ"}), + json!({"body": "Floor", "plane": "YZ", "keep": [5, 5, 0], "stitch": true}), + json!({"body": "Floor", "plane": "YZ", "keep": []}), + json!({"body": "Floor", "plane": "YZ", "keep": [[5, 5]]}), + json!({"body": "Floor", "tool": {"body": "Wall", "point": [0, 5, 5]}, "curves": {"sketch": "Wall sketch"}, "keep": [5, 5, 0]}), + json!({"body": "Floor", "curves": {"sketch": "Nope"}, "keep": [5, 5, 0]}), + json!({"body": "Floor", "curves": {"sketch": "Wall sketch", "curves": ["nope"]}, "keep": [5, 5, 0]}), + json!({"body": "Floor", "curves": {"sketch": "Wall sketch", "direction": [0, 0, 0]}, "keep": [5, 5, 0]}), + ] { + assert!(s.execute("surface.trim", &p).is_err(), "{p}"); + } + assert_eq!(s.doc.features.len(), before); + } + /// A trim keeps its construction plane when the plane is renamed. #[test] fn renaming_a_plane_keeps_a_surface_trim_on_it() { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 23b107875..e65bd328d 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -810,6 +810,11 @@ fn hostile_params_never_panic() { "faces", "u", "v", + "keep", + "with", + "keep_with", + "stitch", + "extend", ]; // Commands are independent; worker threads take them one at a time (their costs vary a lot). let ids: Vec<&str> = command_specs() diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rs index 046eb469c..ae37c3448 100644 --- a/crates/kernel/src/lib.rs +++ b/crates/kernel/src/lib.rs @@ -127,6 +127,7 @@ mod surface_offset; mod surface_ruled; #[cfg(test)] mod surface_second_derivative_tests; +mod surface_trim; mod surface_untrim; mod surfaces; mod sweep_path; @@ -203,10 +204,11 @@ pub use surface_extend::{ExtendLimit, ExtendMode, ExtendOptions, extend_surface} pub use surface_kind::{EdgeCircle, FaceSurface, edge_circle, face_surface}; pub use surface_offset::offset_surface; pub use surface_ruled::{Ruled, RuledCorners, RuledMode, ruled_surface}; +pub use surface_trim::{TrimKeep, mutual_trim, trim, trim_keep}; pub use surface_untrim::{UntrimHoles, untrim}; pub use surfaces::{ copy_faces, extend, extrude_sheet, loft_sheet, patch_edges, patch_region, remove_faces, reverse_faces, revolve_sheet, stitch, sweep_sheet, - sweep_sheet_points, sweep_sheet_points_with, sweep_sheet_with, thicken, trim, unstitch, + sweep_sheet_points, sweep_sheet_points_with, sweep_sheet_with, thicken, unstitch, }; pub use sweep_path::{RailFit, SweepControl, SweepOrientation, sweep_path, sweep_path_with}; pub use topo::{CylinderFace, cylinder_end_at, cylinder_face, cylinder_face_at}; diff --git a/crates/kernel/src/smooth_edges.rs b/crates/kernel/src/smooth_edges.rs index bb24f5073..90460e3e9 100644 --- a/crates/kernel/src/smooth_edges.rs +++ b/crates/kernel/src/smooth_edges.rs @@ -151,6 +151,12 @@ fn classify(body: &Body, mesh: &Mesh, mut work: usize) -> (Vec, Vec) boundaries.push(None); continue; } + // Mapping rebuilds each edge through a check that refuses one starting and ending at + // the same vertex (a loop of one closed edge: a hole a closed curve cut). + if wires.iter().flat_map(|w| w.edge_iter()).any(|e| e.front().id() == e.back().id()) { + boundaries.push(None); + continue; + } let mapped = face.try_mapped(|_| Some(()), |_| Some(()), |surface| ruled(surface, face.orientation(), &mut work)); boundaries.push(mapped.map(|face| face.surface())); } @@ -243,6 +249,27 @@ mod tests { crate::extrude(&Plane::XY, &[Region2 { outer: circle(10., count), holes: vec![circle(9., count).reversed()] }], 0., 3.).unwrap().remove(0) } + /// A square sheet with a round hole a closed curve cut (its loop one closed edge) is + /// classified without a check refusing the closed edge (a panic the guard would catch). + #[test] + fn a_hole_of_one_closed_edge_is_classified() { + let sheet = crate::patch_region( + &Plane::XY, + &Region2 { + outer: Loop2::polygon(&[Vec2::new(-10., -10.), Vec2::new(10., -10.), Vec2::new(10., 10.), Vec2::new(-10., 10.)]), + holes: vec![], + }, + ) + .unwrap(); + let ring: Vec = circle(4., 8).segs; + let tool = crate::SplitTool::Curves { plane: Plane::XY, curves: vec![ring], along: None }; + let holed = crate::trim(&sheet, &tool, Vec3::new(9., 9., 0.)).unwrap(); + assert!(holed.solid.edge_iter().any(|e| e.front().id() == e.back().id()), "a closed edge"); + let mesh = holed.tessellate(0.02).unwrap(); + let (smooth, sharp) = classify(&holed, &mesh, WORK); + assert_eq!((smooth.len(), sharp.len()), (mesh.edges.len(), mesh.edges.len())); + } + #[test] fn periodic_ring_hides_only_whole_smooth_wall_joins() { let body = ring(256); diff --git a/crates/kernel/src/splitface.rs b/crates/kernel/src/splitface.rs index 9afee8616..cab1c2110 100644 --- a/crates/kernel/src/splitface.rs +++ b/crates/kernel/src/splitface.rs @@ -24,10 +24,11 @@ pub enum SplitTool<'a> { Plane(Plane), /// The surface of another body's face (`face` in that body's face order), extended. Face { body: &'a Body, face: usize }, - /// Sketch curves (chains of segments in `plane`) swept along the plane's normal; each curve - /// splits on its own, extended past its ends. A single line or arc splits exactly (a plane - /// or a cylinder); longer chains and splines follow the curve. - Curves { plane: Plane, curves: Vec> }, + /// Sketch curves (chains of segments in `plane`) swept along `along` (none: the plane's + /// normal); each curve splits on its own, an open one extended past its ends. A single line + /// splits exactly (a plane), and so does a single arc swept along the normal (a cylinder); + /// longer chains, splines and arcs swept aslant follow the curve. + Curves { plane: Plane, curves: Vec>, along: Option }, } /// Which side of the tool a point is on (zero on the tool). @@ -45,9 +46,13 @@ enum Field { r: f64, out: f64, }, + /// A chain of points in `plane`, swept along `along` (the plane's normal when none). A + /// closed chain is positive inside it; an open one on its left, its end segments extended. Curve { plane: Plane, pts: Vec, + closed: bool, + along: Option, }, } @@ -68,9 +73,28 @@ impl Field { let radial = v - *axis * v.dot(*axis); *out * (radial.len() - *r) } - Field::Curve { plane, pts } => { + Field::Curve { plane, pts, closed, along } => { + // Where p's line along the sweep direction meets the plane. + let p = match along { + Some(d) => p - *d * ((p - plane.origin).dot(plane.normal()) / d.dot(plane.normal())), + None => p, + }; let q = plane.to_local(p); let q = Vec2::new(q.x, q.y); + if *closed { + // Distance to the loop, positive inside it. + let d = (0..pts.len().saturating_sub(1)) + .filter_map(|i| Some((*pts.get(i)?, *pts.get(i + 1)?))) + .map(|(a, b)| { + let d = b - a; + let l2 = d.dot(d); + let t = if l2 > 0.0 { ((q - a).dot(d) / l2).clamp(0.0, 1.0) } else { 0.0 }; + (q - (a + d * t)).len() + }) + .fold(f64::INFINITY, f64::min); + let uv: Vec<(f64, f64)> = pts.iter().map(|p| (p.x, p.y)).collect(); + return if inside(&uv, (q.x, q.y)) { d } else { -d }; + } // Signed distance to the polyline, its end segments extended as lines. let n = pts.len(); let mut best = (f64::INFINITY, 0.0); @@ -119,6 +143,11 @@ struct Chain { /// Mesh tolerance for tracing a face. fn trace_tol(face: &mt::Face, size: f64) -> f64 { let _ = face; + trace_tol_of(size) +} + +/// Mesh tolerance for tracing on a body of this size. +fn trace_tol_of(size: f64) -> f64 { (size * 2e-3).max(1e-4) } @@ -989,18 +1018,36 @@ fn fields(tool: &SplitTool) -> Result> { let f = other.solid.face_iter().nth(*face).ok_or_else(|| KernelError::Invalid(format!("the tool body has no face {face}")))?; vec![surface_field(&f.oriented_surface())] } - SplitTool::Curves { plane, curves } => { + SplitTool::Curves { plane, curves, along } => { + let n = plane.normal(); + // The sweep direction, turned to the plane's side (a direction along the plane sweeps + // nothing). + let along = match along { + None => None, + Some(d) => { + let d = d + .normalized() + .filter(|d| d.is_finite()) + .ok_or_else(|| KernelError::Invalid("the projection direction must be a nonzero vector".into()))?; + if d.dot(n).abs() < 1e-6 { + return Err(KernelError::Invalid("the projection direction runs along the sketch plane".into())); + } + let d = if d.dot(n) < 0.0 { -d } else { d }; + (d.cross(n).len() > 1e-12).then_some(d) + } + }; + let sweep = along.unwrap_or(n); let mut out = Vec::new(); for c in curves { out.push(match c.as_slice() { [Seg2::Line { a, b }] => { let (wa, wb) = (plane.to_world(*a), plane.to_world(*b)); - let n = plane.normal().cross(wb - wa).normalized().ok_or_else(|| KernelError::Invalid("a zero-length split line".into()))?; + let n = sweep.cross(wb - wa).normalized().ok_or_else(|| KernelError::Invalid("a zero-length split line".into()))?; Field::Plane { o: wa, n } } - [Seg2::Arc { center, radius, .. }] if radius.is_finite() && *radius > 0.0 => Field::Cylinder { + [Seg2::Arc { center, radius, .. }] if along.is_none() && radius.is_finite() && *radius > 0.0 => Field::Cylinder { o: plane.to_world(*center), - axis: plane.normal().unit().ok_or_else(|| KernelError::Invalid("a sketch plane with no normal".into()))?, + axis: n.unit().ok_or_else(|| KernelError::Invalid("a sketch plane with no normal".into()))?, r: *radius, out: 1.0, }, @@ -1016,7 +1063,9 @@ fn fields(tool: &SplitTool) -> Result> { if pts.len() < 2 || pts.iter().any(|p| !(p.x.is_finite() && p.y.is_finite())) || pts.len() > 1_000_000 { return Err(KernelError::Invalid("split curves need finite segments".into())); } - Field::Curve { plane: *plane, pts } + let span = pts.iter().fold(0.0f64, |m, p| m.max(p.len())); + let closed = pts.len() > 3 && pts.first().zip(pts.last()).is_some_and(|(a, b)| (*a - *b).len() <= span * 1e-9 + 1e-9); + Field::Curve { plane: *plane, pts, closed, along } } }); } @@ -1193,6 +1242,62 @@ fn chain_loops(edges: &[mt::Edge]) -> Result>> { Ok(out) } +/// The regions of a body cut by a tool: for each face (in face order), the region it lies in, +/// and how many there are. Faces are in one region when they meet at an edge the tool does not +/// run along; an edge along the tool (a split line) parts them. +pub(crate) fn regions(split: &Body, tool: &SplitTool) -> Result<(Vec, usize)> { + let fields = fields(tool)?; + let tol = trace_tol_of(split.size()); + let faces: Vec<&mt::Face> = split.solid.face_iter().collect(); + let mut along_tool: HashMap = HashMap::new(); + let mut by_edge: HashMap> = HashMap::new(); + for (i, f) in faces.iter().enumerate() { + for e in f.boundaries().iter().flat_map(|w| w.edge_iter()) { + by_edge.entry(e.id()).or_default().push(i); + along_tool.entry(e.id()).or_insert_with(|| { + let c = e.curve(); + let (t0, t1) = c.range_tuple(); + let at: Vec = [0.25, 0.5, 0.75].iter().map(|s| from_p3(c.subs(t0 + (t1 - t0) * s))).collect(); + fields.iter().any(|g| at.iter().all(|p| g.eval(*p).abs() <= tol)) + }); + } + } + let mut region = vec![usize::MAX; faces.len()]; + let mut count = 0; + for s in 0..faces.len() { + if region.get(s) != Some(&usize::MAX) { + continue; + } + if let Some(r) = region.get_mut(s) { + *r = count; + } + let mut stack = vec![s]; + while let Some(i) = stack.pop() { + let Some(f) = faces.get(i) else { continue }; + for e in f.boundaries().iter().flat_map(|w| w.edge_iter()) { + if along_tool.get(&e.id()).copied().unwrap_or(false) { + continue; + } + for &j in by_edge.get(&e.id()).into_iter().flatten() { + if let Some(r) = region.get_mut(j) + && *r == usize::MAX + { + *r = count; + stack.push(j); + } + } + } + } + count += 1; + } + Ok((region, count)) +} + +/// How many fields a tool is (a sketch tool: one per curve). +pub(crate) fn field_count(tool: &SplitTool) -> Result { + Ok(fields(tool)?.len()) +} + /// Faces grouped by shared edges (in face order). fn components(faces: Vec) -> Vec> { let n = faces.len(); @@ -1484,7 +1589,7 @@ mod tests { let side = c.faces(0.01).unwrap().iter().position(|f| f.plane_normal.is_none()).unwrap(); // A horizontal line seen from the front (XZ sketch) at z = 5, swept along y. let xz = Plane { y: Vec3::Z, ..Plane::XZ }; - let tool = SplitTool::Curves { plane: xz, curves: vec![vec![Seg2::Line { a: Vec2::new(-20.0, 5.0), b: Vec2::new(20.0, 5.0) }]] }; + let tool = SplitTool::Curves { plane: xz, curves: vec![vec![Seg2::Line { a: Vec2::new(-20.0, 5.0), b: Vec2::new(20.0, 5.0) }]], along: None }; let s = split_faces(&c, &[side], &tool).unwrap(); let m = measure(&s).unwrap(); // (Measured on meshes: curved faces agree to about 1e-4.) @@ -1566,7 +1671,7 @@ mod tests { let t = top(&b, 30.0); let arc = Seg2::Arc { center: Vec2::new(0.0, 0.0), radius: 6.0, start: 0.0, sweep: std::f64::consts::FRAC_PI_2 }; let plane = Plane { origin: Vec3::new(0.0, 0.0, 30.0), ..Plane::XY }; - let tool = SplitTool::Curves { plane, curves: vec![vec![arc]] }; + let tool = SplitTool::Curves { plane, curves: vec![vec![arc]], along: None }; let (s, map) = split_faces_with_map(&b, &[t], &tool).unwrap(); assert_eq!(map.len(), s.face_count()); assert_eq!(map.iter().filter(|o| **o == t).count(), 2); diff --git a/crates/kernel/src/surface_trim.rs b/crates/kernel/src/surface_trim.rs new file mode 100644 index 000000000..06b22abaa --- /dev/null +++ b/crates/kernel/src/surface_trim.rs @@ -0,0 +1,398 @@ +//! Trim: a surface body cut where a tool meets it (a plane, another body's face, or sketch +//! curves swept onto it), keeping the side of a point or the regions points pick; and Mutual +//! Trim: two surfaces cut by each other, each keeping its picked side, extended to meet first +//! when one stops short of the other. + +use solidcraft_geom::Vec3; +use truck_modeling as mt; + +use crate::body::Body; +use crate::record::{Rebuild, rebuilt_body}; +use crate::splitface::{SplitTool, ToolSide}; +use crate::surface_extend::{ExtendLimit, ExtendMode, ExtendOptions}; +use crate::surfaces::surface_body; +use crate::{KernelError, Result, guard}; + +/// Most points one trim picks with. +const MAX_PICKS: usize = 10_000; + +/// What a trim keeps. +#[derive(Clone, Copy, Debug)] +pub enum TrimKeep<'a> { + /// Every piece on the side of the tool this point is on. A tool of several sketch curves + /// has no one side: the region the point picks is kept. + Side(Vec3), + /// The regions the points pick (a region: the pieces that hang together once the tool has + /// cut the body, each picked by the piece nearest a point). + Regions(&'a [Vec3]), +} + +impl TrimKeep<'_> { + fn points(&self) -> &[Vec3] { + match self { + TrimKeep::Side(p) => std::slice::from_ref(p), + TrimKeep::Regions(at) => at, + } + } + + fn check(&self) -> Result<()> { + let at = self.points(); + if at.is_empty() { + return Err(KernelError::Invalid("pick what to keep".into())); + } + if at.len() > MAX_PICKS { + return Err(KernelError::Invalid("too many points to keep".into())); + } + if at.iter().any(|p| !p.is_finite()) { + return Err(KernelError::Invalid("a point to keep is not finite".into())); + } + Ok(()) + } +} + +/// A surface body trimmed by a tool: its faces are cut where the tool meets them and the +/// pieces on the side of `keep` are kept. The result's history is over `[body]`. +pub fn trim(body: &Body, tool: &SplitTool, keep: Vec3) -> Result { + trim_keep(body, tool, TrimKeep::Side(keep)) +} + +/// A surface body trimmed by a tool, keeping what `keep` says. Each kept face is the face it is +/// a piece of (its history is over `[body]`). +pub fn trim_keep(body: &Body, tool: &SplitTool, keep: TrimKeep) -> Result { + body.require_brep("trim")?; + keep.check()?; + let total = body.solid.face_iter().count(); + let all: Vec = (0..total).collect(); + let (split, _) = crate::splitface::split_any(body, &all, tool)?; + let one_side = match keep { + TrimKeep::Side(p) if crate::splitface::field_count(tool)? == 1 => Some(crate::splitface::side_of_point(tool, p)?), + _ => None, + }; + let picked = match one_side { + Some(_) => Vec::new(), + None => nearest_faces(&split, keep.points())?, + }; + guard("trim", || { + let mut kept = Vec::new(); + match one_side { + Some(side) => { + for f in split.solid.face_iter() { + let x = crate::splitface::face_side(f, tool, split.size())?; + if (x >= 0.0) == (side >= 0.0) { + kept.push(f.clone()); + } + } + } + None => { + let (region, count) = crate::splitface::regions(&split, tool)?; + let mut wanted = vec![false; count]; + for f in &picked { + if let Some(w) = region.get(*f).and_then(|r| wanted.get_mut(*r)) { + *w = true; + } + } + for (f, r) in split.solid.face_iter().zip(®ion) { + if wanted.get(*r).copied().unwrap_or(false) { + kept.push(f.clone()); + } + } + } + } + if kept.is_empty() { + return Err(KernelError::Invalid("nothing is left on that side of the tool".into())); + } + // The kept pieces are the split's own; its history carries them back to `body`. + let trimmed = rebuilt_body(surface_body(kept), &[&split.solid], &Rebuild::default()); + Ok(crate::record::after(trimmed, &split, &crate::record::counts(&[body]))) + }) +} + +/// For each point, the face of `body` nearest it (over one tessellation). +fn nearest_faces(body: &Body, at: &[Vec3]) -> Result> { + let m = body.tessellate(body.size() * 2e-3)?; + at.iter() + .map(|p| { + let mut best: Option<(f64, u32)> = None; + for (t, f) in m.triangles.iter().zip(&m.tri_face) { + let Some([a, b, c]) = m.tri(t) else { continue }; + let d = ((a + b + c) / 3.0).dist(*p).min(a.dist(*p)).min(b.dist(*p)).min(c.dist(*p)); + if best.is_none_or(|(x, _)| d < x) { + best = Some((d, *f)); + } + } + best.map(|(_, f)| f as usize).ok_or_else(|| KernelError::Invalid("no face there".into())) + }) + .collect() +} + +/// Two surface bodies trimmed by each other: `a` cut where `b`'s surface (extended) meets it, +/// keeping what `keep_a` says, and `b` by `a`'s, keeping `keep_b`. A surface that stops short of +/// the other is extended to meet it when `extend` is set (naturally, its nearest boundary edge +/// up to the other's surface), else that is an error; one that ends on the other is kept whole. +/// Each body must be one face (its surface is the other's tool). The results' histories are over +/// `[a]` and `[b]`. +pub fn mutual_trim(a: &Body, b: &Body, keep_a: TrimKeep, keep_b: TrimKeep, extend: bool) -> Result<(Body, Body)> { + for (x, name) in [(a, "first"), (b, "second")] { + x.require_brep("trim")?; + if !x.is_surface() { + return Err(KernelError::Invalid(format!("the {name} body is a solid: a mutual trim takes two surfaces"))); + } + if x.face_count() != 1 { + return Err(KernelError::Invalid(format!( + "not supported yet: a mutual trim of a surface of more than one face (the {name} body has {}; trim it by one face instead)", + x.face_count() + ))); + } + } + keep_a.check()?; + keep_b.check()?; + let ta = cut_by(a, &SplitTool::Face { body: b, face: 0 }, keep_a, extend, "first")?; + let tb = cut_by(b, &SplitTool::Face { body: a, face: 0 }, keep_b, extend, "second")?; + Ok((ta, tb)) +} + +/// `x` trimmed by `tool` where the tool crosses it; whole where it ends on the tool; extended to +/// the tool first (when `extend`) where it stops short of it. +fn cut_by(x: &Body, tool: &SplitTool, keep: TrimKeep, extend: bool, name: &str) -> Result { + let side = ToolSide::of(tool)?; + let size = x.size(); + let touch = size * 1e-6 + 1e-9; + let m = x.tessellate(size * 2e-3)?; + let (mut lo, mut hi, mut near) = (f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY); + for p in &m.positions { + let v = side.at(*p); + if !v.is_finite() { + return Err(KernelError::Failed("the other surface cannot be evaluated over this one".into())); + } + lo = lo.min(v); + hi = hi.max(v); + near = near.min(v.abs()); + } + if lo < -touch && hi > touch { + return trim_keep(x, tool, keep); + } + if near <= touch { + return Ok(crate::boolean_record::operand(x, 0, &crate::record::counts(&[x]))); + } + if !extend { + return Err(KernelError::Invalid(format!("the {name} surface does not reach the other one: extend it to meet"))); + } + let edge = nearest_boundary_edge(x, &side)?; + let opts = ExtendOptions { mode: ExtendMode::Natural, limit: ExtendLimit::UpTo(tool), neighbours: true }; + crate::extend_surface(x, &[edge], &opts) +} + +/// A point in the middle of the boundary edge of `x` nearest the tool. +fn nearest_boundary_edge(x: &Body, side: &ToolSide) -> Result { + guard("trim", || { + let mut uses: std::collections::HashMap = std::collections::HashMap::new(); + for f in x.solid.face_iter() { + for e in f.boundaries().iter().flat_map(|w| w.edge_iter()) { + uses.entry(e.id()).or_insert((0, e.clone())).0 += 1; + } + } + let mut best: Option<(f64, Vec3)> = None; + for (count, e) in uses.values() { + if *count != 1 { + continue; + } + use mt::{BoundedCurve, ParametricCurve}; + let c = e.curve(); + let (t0, t1) = c.range_tuple(); + let mid = crate::body::from_p3(c.subs(0.5 * (t0 + t1))); + let d = side.at(mid).abs(); + if d.is_finite() && best.is_none_or(|(b, _)| d < b) { + best = Some((d, mid)); + } + } + best.map(|(_, p)| p).ok_or_else(|| KernelError::Invalid("the surface has no boundary edge to extend".into())) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::history::{Change, FaceOrigin}; + use crate::{extrude_sheet, measure, patch_region, stitch}; + use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2}; + use std::f64::consts::PI; + + fn rel(a: f64, b: f64) -> f64 { + (a - b).abs() / b.abs().max(1e-12) + } + + fn rect(plane: &Plane, u0: f64, v0: f64, u1: f64, v1: f64) -> Body { + let outer = Loop2::polygon(&[Vec2::new(u0, v0), Vec2::new(u1, v0), Vec2::new(u1, v1), Vec2::new(u0, v1)]); + patch_region(plane, &Region2 { outer, holes: vec![] }).unwrap() + } + + fn area(b: &Body) -> f64 { + measure(b).unwrap().area + } + + /// A U-shaped sheet (legs x = 0 and x = 10, 10 high, a base along y = 0, 10 deep in z) cut + /// by the plane y = 5: one side keeps both legs' tops, one region pick only one of them, two + /// picks both again. + #[test] + fn regions_keep_what_the_points_pick() { + let chain = vec![ + Seg2::Line { a: Vec2::new(0.0, 10.0), b: Vec2::new(0.0, 0.0) }, + Seg2::Line { a: Vec2::new(0.0, 0.0), b: Vec2::new(10.0, 0.0) }, + Seg2::Line { a: Vec2::new(10.0, 0.0), b: Vec2::new(10.0, 10.0) }, + ]; + let u = extrude_sheet(&Plane::XY, &[chain], 0.0, 10.0).unwrap(); + let cut = SplitTool::Plane(Plane::new(Vec3::new(0.0, 5.0, 0.0), Vec3::X, Vec3::Z).unwrap()); + let side = trim(&u, &cut, Vec3::new(0.0, 8.0, 5.0)).unwrap(); + assert!(rel(area(&side), 100.0) < 1e-9, "{}", area(&side)); + let one = trim_keep(&u, &cut, TrimKeep::Regions(&[Vec3::new(0.0, 8.0, 5.0)])).unwrap(); + assert!(rel(area(&one), 50.0) < 1e-9, "{}", area(&one)); + let both = trim_keep(&u, &cut, TrimKeep::Regions(&[Vec3::new(0.0, 8.0, 5.0), Vec3::new(10.0, 9.0, 2.0)])).unwrap(); + assert!(rel(area(&both), 100.0) < 1e-9, "{}", area(&both)); + // The base side is one region: its three faces hang together. + let base = trim_keep(&u, &cut, TrimKeep::Regions(&[Vec3::new(5.0, 0.0, 5.0)])).unwrap(); + assert!(rel(area(&base), 200.0) < 1e-9 && base.face_count() == 3, "{}", area(&base)); + // Each kept face is a piece of the face it was cut from. + let h = one.history().unwrap(); + assert_eq!(h.operands, 1); + assert!( + h.faces.iter().all(|f| f.change == Change::Modified && matches!(f.origins.as_slice(), [FaceOrigin::Face { operand: 0, .. }])), + "{h:?}" + ); + } + + /// A 10 × 10 square cut by two sketch lines (x = 3 and x = 7): a side is no answer for two + /// curves, so a point picks its region; two picks keep the two outer strips. + #[test] + fn several_curves_cut_regions() { + let sq = rect(&Plane::XY, 0.0, 0.0, 10.0, 10.0); + let lines = vec![ + vec![Seg2::Line { a: Vec2::new(3.0, -5.0), b: Vec2::new(3.0, 15.0) }], + vec![Seg2::Line { a: Vec2::new(7.0, -5.0), b: Vec2::new(7.0, 15.0) }], + ]; + let tool = SplitTool::Curves { plane: Plane { origin: Vec3::new(0.0, 0.0, 5.0), ..Plane::XY }, curves: lines, along: None }; + let mid = trim(&sq, &tool, Vec3::new(5.0, 5.0, 0.0)).unwrap(); + assert!(rel(area(&mid), 40.0) < 1e-9, "{}", area(&mid)); + let outer = trim_keep(&sq, &tool, TrimKeep::Regions(&[Vec3::new(1.0, 5.0, 0.0), Vec3::new(9.0, 5.0, 0.0)])).unwrap(); + assert!(rel(area(&outer), 60.0) < 1e-9 && outer.face_count() == 2, "{}", area(&outer)); + } + + /// A line sketched 10 above a 20 × 20 sheet at x = 5, swept along (1, 0, −1): it meets the + /// sheet at x = 15, so the side of x = 0 keeps 15 × 20. A direction along the sketch plane + /// is refused. + #[test] + fn curves_swept_aslant() { + let sq = rect(&Plane::XY, 0.0, 0.0, 20.0, 20.0); + let plane = Plane { origin: Vec3::new(0.0, 0.0, 10.0), ..Plane::XY }; + let curves = vec![vec![Seg2::Line { a: Vec2::new(5.0, -5.0), b: Vec2::new(5.0, 25.0) }]]; + let tool = SplitTool::Curves { plane, curves: curves.clone(), along: Some(Vec3::new(1.0, 0.0, -1.0)) }; + let t = trim(&sq, &tool, Vec3::new(1.0, 5.0, 0.0)).unwrap(); + assert!(rel(area(&t), 300.0) < 1e-9, "{}", area(&t)); + let flat = SplitTool::Curves { plane, curves, along: Some(Vec3::X) }; + assert!(trim(&sq, &flat, Vec3::new(1.0, 5.0, 0.0)).is_err()); + } + + /// The slot |x| ≤ 3 (a straight run z = 12…28 and round ends) sketched in front of a half + /// cylinder (radius 10 about Z, y ≥ 0, 40 high) and swept along the sketch's normal: the + /// piece inside it is ∫∫ R / √(R² − x²) dx dz over the slot (the straight run 16 · 2R·asin(3/R), + /// the two round ends one disc), the piece outside the rest of 10π · 40. + #[test] + fn a_slot_projected_onto_a_cylinder() { + let r: f64 = 10.0; + let half = extrude_sheet(&Plane::XY, &[vec![Seg2::Arc { center: Vec2::ZERO, radius: r, start: 0.0, sweep: PI }]], 0.0, 40.0).unwrap(); + let a: f64 = 3.0; + let slot = vec![ + Seg2::Line { a: Vec2::new(a, 12.0), b: Vec2::new(a, 28.0) }, + Seg2::Arc { center: Vec2::new(0.0, 28.0), radius: a, start: 0.0, sweep: PI }, + Seg2::Line { a: Vec2::new(-a, 28.0), b: Vec2::new(-a, 12.0) }, + Seg2::Arc { center: Vec2::new(0.0, 12.0), radius: a, start: PI, sweep: PI }, + ]; + let front = Plane { y: Vec3::Z, ..Plane::XZ }; + let tool = SplitTool::Curves { plane: front, curves: vec![slot], along: None }; + // The round ends: x = a·sin φ, the disc's height 2a·cos φ, dx = a·cos φ dφ (Simpson). + let n = 4000; + let f = |phi: f64| 2.0 * a * a * phi.cos().powi(2) * r / (r * r - (a * phi.sin()).powi(2)).sqrt(); + let h = PI / n as f64; + let ends = (0..=n) + .map(|k| { + let w = if k == 0 || k == n { + 1.0 + } else if k % 2 == 1 { + 4.0 + } else { + 2.0 + }; + w * f(-PI / 2.0 + h * k as f64) + }) + .sum::() + * h + / 3.0; + let inside = 16.0 * 2.0 * r * (a / r).asin() + ends; + let on = Vec3::new(0.0, r, 20.0); + let kept = trim(&half, &tool, on).unwrap(); + eprintln!("slot on the cylinder: {} measured, {inside} analytic", area(&kept)); + // (Measured on meshes.) + assert!(rel(area(&kept), inside) < 1e-3, "{} vs {inside}", area(&kept)); + let rest = trim(&half, &tool, Vec3::new(r, 0.0, 20.0)).unwrap(); + let all = PI * r * 40.0; + assert!(rel(area(&rest), all - inside) < 1e-3, "{} vs {}", area(&rest), all - inside); + let picked = trim_keep(&half, &tool, TrimKeep::Regions(&[on])).unwrap(); + assert!(rel(area(&picked), area(&kept)) < 1e-9); + } + + /// Two 20 × 10 sheets crossing at right angles (z = 0 and x = 0, both y = 0…10) trimmed by + /// each other, each keeping its x > 0 / z > 0 half, and stitched: an L of two faces sharing + /// their edge, 200 in area. + #[test] + fn crossing_sheets_trim_each_other_into_an_l() { + let a = rect(&Plane::XY, -10.0, 0.0, 10.0, 10.0); + let yz = Plane::new(Vec3::ZERO, Vec3::Y, Vec3::Z).unwrap(); + let b = rect(&yz, 0.0, -10.0, 10.0, 10.0); + let (ta, tb) = mutual_trim(&a, &b, TrimKeep::Side(Vec3::new(5.0, 5.0, 0.0)), TrimKeep::Side(Vec3::new(0.0, 5.0, 5.0)), false).unwrap(); + assert!(rel(area(&ta), 100.0) < 1e-9 && rel(area(&tb), 100.0) < 1e-9); + let l = stitch(&[&ta, &tb], 0.0).unwrap(); + assert_eq!((l.face_count(), l.edge_count()), (2, 7), "one shared edge"); + assert!(rel(area(&l), 200.0) < 1e-9); + assert!(l.is_surface()); + let bb = measure(&l).unwrap().bbox; + assert!(bb.min.x.abs() < 1e-9 && bb.min.z.abs() < 1e-9 && (bb.max.x - 10.0).abs() < 1e-9 && (bb.max.z - 10.0).abs() < 1e-9, "{bb:?}"); + // The pieces are the sheets' faces. + for t in [&ta, &tb] { + let h = t.history().unwrap(); + assert!(matches!(h.faces[0].origins.as_slice(), [FaceOrigin::Face { operand: 0, face: 0 }]) && h.faces[0].change == Change::Modified); + } + } + + /// A sheet that stops 3 short of the other (x = 0, z = 3…10) is refused until extended to + /// meet it; extended, the two still make the L. + #[test] + fn a_short_sheet_is_extended_to_meet() { + let a = rect(&Plane::XY, -10.0, 0.0, 10.0, 10.0); + let yz = Plane::new(Vec3::ZERO, Vec3::Y, Vec3::Z).unwrap(); + let b = rect(&yz, 0.0, 3.0, 10.0, 10.0); + let (ka, kb) = (TrimKeep::Side(Vec3::new(5.0, 5.0, 0.0)), TrimKeep::Side(Vec3::new(0.0, 5.0, 5.0))); + let e = mutual_trim(&a, &b, ka, kb, false).unwrap_err().to_string(); + assert!(e.contains("extend"), "{e}"); + let (ta, tb) = mutual_trim(&a, &b, ka, kb, true).unwrap(); + assert!(rel(area(&ta), 100.0) < 1e-9 && rel(area(&tb), 100.0) < 1e-6, "{} {}", area(&ta), area(&tb)); + let l = stitch(&[&ta, &tb], 0.0).unwrap(); + assert_eq!((l.face_count(), l.edge_count()), (2, 7)); + } + + #[test] + fn hostile_trims_are_refused() { + let a = rect(&Plane::XY, 0.0, 0.0, 10.0, 10.0); + let cut = SplitTool::Plane(Plane::new(Vec3::new(3.0, 0.0, 0.0), Vec3::Y, Vec3::Z).unwrap()); + assert!(trim_keep(&a, &cut, TrimKeep::Regions(&[])).is_err()); + assert!(trim_keep(&a, &cut, TrimKeep::Regions(&[Vec3::new(f64::NAN, 0.0, 0.0)])).is_err()); + assert!(trim(&a, &cut, Vec3::new(f64::INFINITY, 0.0, 0.0)).is_err()); + let many = vec![Vec3::ZERO; MAX_PICKS + 1]; + assert!(trim_keep(&a, &cut, TrimKeep::Regions(&many)).is_err()); + let solid = crate::box_solid(Vec3::ZERO, Vec3::new(1.0, 1.0, 1.0)).unwrap(); + assert!(mutual_trim(&a, &solid, TrimKeep::Side(Vec3::ZERO), TrimKeep::Side(Vec3::ZERO), true).is_err()); + let chain = + vec![Seg2::Line { a: Vec2::new(0.0, 0.0), b: Vec2::new(5.0, 0.0) }, Seg2::Line { a: Vec2::new(5.0, 0.0), b: Vec2::new(5.0, 5.0) }]; + let two = extrude_sheet(&Plane::XY, &[chain], 0.0, 5.0).unwrap(); + let e = mutual_trim(&a, &two, TrimKeep::Side(Vec3::ZERO), TrimKeep::Side(Vec3::ZERO), true).unwrap_err().to_string(); + assert!(e.contains("not supported yet"), "{e}"); + } +} diff --git a/crates/kernel/src/surfaces.rs b/crates/kernel/src/surfaces.rs index b7c0ed015..6031f4859 100644 --- a/crates/kernel/src/surfaces.rs +++ b/crates/kernel/src/surfaces.rs @@ -1098,31 +1098,6 @@ pub fn thicken(body: &Body, thickness: f64, symmetric: bool) -> Result { }) } -/// A surface body trimmed by a tool: its faces are cut where the tool meets them and the -/// pieces on the side of `keep` are kept. The result's history is over `[body]`. -pub fn trim(body: &Body, tool: &crate::SplitTool, keep: Vec3) -> Result { - body.require_brep("trim")?; - let total = body.solid.face_iter().count(); - let all: Vec = (0..total).collect(); - let (split, _) = crate::splitface::split_any(body, &all, tool)?; - let side = crate::splitface::side_of_point(tool, keep)?; - guard("trim", || { - let mut kept = Vec::new(); - for f in split.solid.face_iter() { - let x = crate::splitface::face_side(f, tool, split.size())?; - if (x >= 0.0) == (side >= 0.0) { - kept.push(f.clone()); - } - } - if kept.is_empty() { - return Err(KernelError::Invalid("nothing is left on that side of the tool".into())); - } - // The kept pieces are the split's own; its history carries them back to `body`. - let trimmed = rebuilt_body(surface_body(kept), &[&split.solid], &Rebuild::default()); - Ok(crate::record::after(trimmed, &split, &crate::record::counts(&[body]))) - }) -} - /// A planar surface extended: the chosen straight edges (picked by points on them) move /// outward in the face's plane by `distance`, their neighbours lengthened to meet them. The /// result's history is over `[body]`: the face and each edge the one it was moved from. @@ -1196,7 +1171,7 @@ pub fn extend(body: &Body, at: &[Vec3], distance: f64) -> Result { #[cfg(test)] mod tests { use super::*; - use crate::{box_solid, cylinder, measure}; + use crate::{box_solid, cylinder, measure, trim}; use solidcraft_geom::{Loop2, Vec2}; fn rel(a: f64, b: f64) -> f64 { diff --git a/crates/ui-egui/src/dialogs_surface.rs b/crates/ui-egui/src/dialogs_surface.rs index a984cf3e2..397ce0fa8 100644 --- a/crates/ui-egui/src/dialogs_surface.rs +++ b/crates/ui-egui/src/dialogs_surface.rs @@ -5,7 +5,7 @@ use serde_json::{Map, Value, json}; use solidcraft_engine::Sel; use solidcraft_engine::doc::expr::Kind as ValueKind; -use solidcraft_engine::doc::{AxisRef, Direction, FaceAt, FeatureKind, Mat, PlaneRef, ProfileSel, RuledCorners, RuledMode}; +use solidcraft_engine::doc::{AxisRef, Direction, FaceAt, FeatureKind, Mat, PlaneRef, Position, ProfileSel, RuledCorners, RuledMode}; use solidcraft_engine::geom::Vec3; use crate::SolveApp; @@ -65,7 +65,12 @@ pub enum Surf { Extend { distance: String, }, - Trim, + /// `direction`: the stored sweep direction of trimming curves (none: the sketch's normal). + Trim { + extend: bool, + stitch: bool, + direction: Option, + }, /// `holes`: an index into [`UNTRIM_HOLES`]. Untrim { holes: usize, @@ -91,7 +96,7 @@ impl Surf { Surf::Stitch { .. } => "STITCH", Surf::Thicken { .. } => "THICKEN", Surf::Extend { .. } => "EXTEND", - Surf::Trim => "TRIM", + Surf::Trim { .. } => "TRIM", Surf::Untrim { .. } => "UNTRIM", Surf::SplitFace => "SPLIT FACE", } @@ -151,10 +156,12 @@ fn inputs(k: &Surf) -> Vec { Surf::Stitch { .. } => vec![SelInput::new("Surfaces", BODIES, true)], Surf::Thicken { .. } => vec![SelInput::new("Surfaces", BODIES, true)], Surf::Extend { .. } => vec![SelInput::new("Edges", EDGES, true)], - Surf::Trim => vec![ + Surf::Trim { .. } => vec![ SelInput::new("Surface", BODIES, false), - SelInput::new("Trimming tool", PLANES | FACES, false), - SelInput::new("Side to keep", FACES, false), + SelInput::new("Trimming tool (plane, face or curves)", PLANES | FACES | CURVES, true), + SelInput::new("Keep (points on it)", FACES, true).places(), + SelInput::new("Other surface (mutual trim)", BODIES, false), + SelInput::new("Keep of the other surface", FACES, true).places(), ], Surf::Untrim { .. } => vec![SelInput::new("Face", FACES, false), SelInput::new("Holes (edges on them)", EDGES, true)], Surf::SplitFace => vec![SelInput::new("Faces to split", FACES, true), SelInput::new("Splitting tool", PLANES | FACES, false)], @@ -177,7 +184,7 @@ pub fn start(_app: &SolveApp, id: &str) -> Option<(Kind, Vec)> { "surface.stitch" => Surf::Stitch { tolerance: String::new() }, "surface.thicken" => Surf::Thicken { thickness: "2 mm".into(), symmetric: false, operation: 0 }, "surface.extend" => Surf::Extend { distance: "10 mm".into() }, - "surface.trim" => Surf::Trim, + "surface.trim" => Surf::Trim { extend: false, stitch: false, direction: None }, "surface.untrim" => Surf::Untrim { holes: 0, outer: false, in_place: false }, "solid.split_face" => Surf::SplitFace, _ => return None, @@ -288,8 +295,16 @@ pub fn rows(ui: &mut egui::Ui, k: &mut Surf) -> bool { *join = op == 1; ui.end_row(); } + Surf::Trim { extend, stitch, .. } => { + row_label(ui, "Extend to meet"); + ui.checkbox(extend, ""); + ui.end_row(); + row_label(ui, "Stitch the kept pieces"); + ui.checkbox(stitch, ""); + ui.end_row(); + } Surf::Sweep(opts) => enter |= crate::dialogs_sweep::rows(ui, opts, "ss"), - Surf::Trim | Surf::SplitFace | Surf::Unstitch | Surf::ReverseNormal | Surf::Loft => {} + Surf::SplitFace | Surf::Unstitch | Surf::ReverseNormal | Surf::Loft => {} } enter } @@ -673,18 +688,52 @@ pub fn commands(app: &SolveApp, k: &Surf, inputs: &[SelInput], extra: &Map { + Surf::Trim { extend, stitch, direction } => { need(0, "the surface to trim")?; - need(1, "the trimming tool")?; - need(2, "the side to keep (a point on it)")?; + need(2, "what to keep (points on it)")?; let body = bodies(inputs, 0).into_iter().next().unwrap_or_default(); - let (key, t) = tool(app, items(inputs, 1).first())?; - let keep = items(inputs, 2) - .first() - .and_then(|x| if let Sel::Face { point, .. } = x { Some(pt(*point)) } else { None }) - .ok_or("pick the side to keep")?; - let mut p = json!({"body": body, "keep": keep}); - p[key] = t; + // One point keeps its side, several the regions they pick. + let points = |i: usize| -> Option { + let pts: Vec = + items(inputs, i).iter().filter_map(|x| if let Sel::Face { point, .. } = x { Some(pt(*point)) } else { None }).collect(); + match pts.as_slice() { + [] => None, + [one] => Some(one.clone()), + _ => Some(json!(pts)), + } + }; + let mut p = json!({"body": body, "keep": points(2).ok_or("pick what to keep")?}); + if let Some(other) = bodies(inputs, 3).into_iter().next() { + need(4, "what to keep of the other surface")?; + p["with"] = json!(other); + p["keep_with"] = points(4).ok_or("pick what to keep of the other surface")?; + if *extend { + p["extend"] = json!(true); + } + if *stitch { + p["stitch"] = json!(true); + } + } else { + need(1, "the trimming tool")?; + let picks = items(inputs, 1); + let curves: Vec = + picks.iter().filter_map(|x| if let Sel::SketchCurve { id } = x { Some(id.clone()) } else { None }).collect(); + if curves.is_empty() { + let [one] = picks else { return Err("pick one plane or face as the tool, or sketch curves".into()) }; + let (key, t) = tool(app, Some(one))?; + p[key] = t; + } else { + if curves.len() != picks.len() { + return Err("trim by sketch curves, or by one plane or face".into()); + } + let sketch = crate::dialogs::curves_sketch(app, &curves, None).ok_or("the curves must be in one sketch")?; + let mut c = json!({"sketch": sketch, "curves": curves}); + if let Some(d) = direction { + c["direction"] = pt(*d); + } + p["curves"] = c; + } + } ("surface.trim", p) } Surf::Untrim { holes, outer, in_place } => { @@ -950,14 +999,30 @@ pub fn for_feature(app: &SolveApp, kind: &FeatureKind, frame: &Mat) -> Option<(K } return Some((Kind::Surface(k), ins, extra)); } - FeatureKind::SurfaceTrim { body, plane, tool, keep } => ( - Surf::Trim, - vec![ - vec![Sel::Body { name: body.to_string() }], - tool_sel(app, plane, tool.as_ref()).into_iter().collect(), - crate::dialogs::face_sel(s, keep.0).into_iter().collect(), - ], - ), + FeatureKind::SurfaceTrim { body, plane, tool, keep, keep_more, curves, with, keep_with, stitch, extend } => { + let faces = |pts: &mut dyn Iterator| -> Vec { pts.filter_map(|p| crate::dialogs::face_sel(s, p.0)).collect() }; + let tools: Vec = match (with, curves) { + (Some(_), _) => Vec::new(), + (None, Some(c)) if c.curves.is_empty() => { + let st = s.world_state(); + st.sketch(c.sketch.0) + .map(|ss| ss.sketch.curves.iter().filter(|k| !k.construction).map(|k| Sel::SketchCurve { id: k.id.clone() }).collect()) + .unwrap_or_default() + } + (None, Some(c)) => c.curves.iter().map(|id| Sel::SketchCurve { id: id.clone() }).collect(), + (None, None) => tool_sel(app, plane, tool.as_ref()).into_iter().collect(), + }; + ( + Surf::Trim { extend: *extend, stitch: *stitch, direction: curves.as_ref().and_then(|c| c.direction.map(|d| d.0)) }, + vec![ + vec![Sel::Body { name: body.to_string() }], + tools, + faces(&mut std::iter::once(keep).chain(keep_more)), + with.iter().map(|n| Sel::Body { name: n.to_string() }).collect(), + faces(&mut keep_with.iter()), + ], + ) + } FeatureKind::SurfaceUntrim { face, holes, outer, in_place } => { let (index, picked) = match holes { None => (0, Vec::new()), diff --git a/crates/ui-egui/src/preselect_tests.rs b/crates/ui-egui/src/preselect_tests.rs index bfb747128..d2ca0d548 100644 --- a/crates/ui-egui/src/preselect_tests.rs +++ b/crates/ui-egui/src/preselect_tests.rs @@ -1544,6 +1544,59 @@ fn ruled_surface_dialog_takes_edges_a_face_and_a_direction() { assert_eq!((&p["params"]["mode"], &p["params"]["direction"]), (&json!("direction"), &json!([0.0, 0.0, 1.0])), "{p}"); } +#[test] +fn trim_dialog_takes_curves_several_keep_points_and_another_surface() { + // Two 20 × 10 sheets crossing at x = 0 / z = 0 and a sketch line x = 3 on XY. + let mut app = app_with(json!([ + {"command": "sketch.create", "params": {"plane": "XY", "name": "F"}}, + {"command": "sketch.rectangle.two_point", "params": {"p0": [-10, 0], "p1": [10, 10]}}, + {"command": "sketch.finish", "params": {}}, + {"command": "surface.patch", "params": {"sketch": "F", "body_name": "Floor"}}, + {"command": "sketch.create", "params": {"plane": "YZ", "name": "W"}}, + {"command": "sketch.rectangle.two_point", "params": {"p0": [0, -10], "p1": [10, 10]}}, + {"command": "sketch.finish", "params": {}}, + {"command": "surface.patch", "params": {"sketch": "W", "body_name": "Wall"}}, + {"command": "sketch.create", "params": {"plane": "XY", "name": "Cut"}}, + {"command": "sketch.line", "params": {"points": [[3, -5], [3, 15]], "ids": ["c1"]}}, + {"command": "sketch.finish", "params": {}} + ])); + let face = |body: &str, p: [f64; 3]| Sel::Face { body: body.into(), index: 0, point: Vec3::new(p[0], p[1], p[2]) }; + let mut d = start(&mut app, vec![], "surface.trim"); + assert_eq!(d.inputs.len(), 5); + d.inputs[0].items = vec![Sel::Body { name: "Floor".into() }]; + d.inputs[1].items = vec![Sel::SketchCurve { id: "c1".into() }]; + // Two places on the one face both count (a face pick would toggle the face off). + d.inputs[2].toggle(vec![face("Floor", [1.0, 5.0, 0.0])]); + d.inputs[2].toggle(vec![face("Floor", [-5.0, 5.0, 0.0])]); + assert_eq!(d.inputs[2].items.len(), 2); + let (id, p) = apply_commands(&app, &d).unwrap().remove(0); + assert_eq!(p["curves"]["curves"], json!(["c1"]), "{p}"); + assert_eq!(p["keep"], json!([[1.0, 5.0, 0.0], [-5.0, 5.0, 0.0]]), "{p}"); + app.session.execute(&id, &p).unwrap(); + let area = |app: &SolveApp, n: &str| app.session.world_state().body(n).unwrap().mesh().measure().area; + assert!((area(&app, "Floor") - 130.0).abs() < 1e-6, "{}", area(&app, "Floor")); + app.session.execute("edit.undo", &json!({})).unwrap(); + // Mutual: the other surface replaces the tool; stitched into an L. + d.inputs[1].items.clear(); + d.inputs[2].items = vec![face("Floor", [5.0, 5.0, 0.0])]; + d.inputs[3].items = vec![Sel::Body { name: "Wall".into() }]; + assert!(apply_commands(&app, &d).is_err(), "nothing kept of the wall yet"); + d.inputs[4].items = vec![face("Wall", [0.0, 5.0, 5.0])]; + if let Kind::Surface(crate::dialogs_surface::Surf::Trim { stitch, .. }) = &mut d.kind { + *stitch = true; + } + let (id, p) = apply_commands(&app, &d).unwrap().remove(0); + assert_eq!((&p["with"], &p["keep_with"], &p["stitch"]), (&json!("Wall"), &json!([0.0, 5.0, 5.0]), &json!(true)), "{p}"); + assert!(p.get("extend").is_none() && p.get("plane").is_none(), "{p}"); + app.session.execute(&id, &p).unwrap(); + assert!((area(&app, "Floor") - 200.0).abs() < 1e-6 && app.session.world_state().body("Wall").is_none()); + let fid = app.session.doc.features.last().unwrap().id; + let back = crate::dialogs::for_feature(&app, fid, None).unwrap(); + assert!(matches!(back.kind, Kind::Surface(crate::dialogs_surface::Surf::Trim { stitch: true, extend: false, direction: None }))); + let counts: Vec = back.inputs.iter().map(|i| i.items.len()).collect(); + assert_eq!(counts, [1, 0, 1, 1, 1]); +} + #[test] fn untrim_dialog_takes_a_face_its_holes_and_the_outer_boundary() { // A 40 × 20 × 2 plate with three holes: its top untrimmed (every hole) is the whole 800 mm² diff --git a/crates/ui-egui/src/selection.rs b/crates/ui-egui/src/selection.rs index e4480ea13..e9f460f4b 100644 --- a/crates/ui-egui/src/selection.rs +++ b/crates/ui-egui/src/selection.rs @@ -46,12 +46,21 @@ pub struct SelInput { pub accept: Accept, /// Many items (clicks toggle them), or one (a click replaces it). pub multi: bool, + /// Face picks are places on the face, not the face: several on one face add up (a click on + /// the very spot of one takes it out). For points that pick pieces a face is cut into. + pub places: bool, pub items: Vec, } impl SelInput { pub fn new(label: &'static str, accept: Accept, multi: bool) -> SelInput { - SelInput { label, accept, multi, items: Vec::new() } + SelInput { label, accept, multi, places: false, items: Vec::new() } + } + + /// This input with face picks as places (see [`SelInput::places`]). + pub fn places(mut self) -> SelInput { + self.places = true; + self } /// The selection a hit stands for, if this input accepts it. @@ -85,11 +94,17 @@ impl SelInput { return; } // A pick of something already in (or a chain fully in) takes it out. - if picked.iter().all(|p| self.items.iter().any(|x| same_item(x, p))) { - self.items.retain(|x| !picked.iter().any(|p| same_item(x, p))); + let places = self.places; + // Whether two picks are the same item of this input. + let same = |a: &Sel, b: &Sel| match (a, b) { + (Sel::Face { point: p, .. }, Sel::Face { point: q, .. }) if places => same_item(a, b) && p.dist(*q) <= 1e-9, + _ => same_item(a, b), + }; + if picked.iter().all(|p| self.items.iter().any(|x| same(x, p))) { + self.items.retain(|x| !picked.iter().any(|p| same(x, p))); } else { for p in picked { - if !self.items.iter().any(|x| same_item(x, &p)) { + if !self.items.iter().any(|x| same(x, &p)) { self.items.push(p); } } From 6f93e7a851bb47ba79a247bd000e637e0cffe4b7 Mon Sep 17 00:00:00 2001 From: Victor Santos Oliveira <56417388+Vittuu@users.noreply.github.com> Date: Mon, 19 Oct 2026 17:04:23 -0300 Subject: [PATCH 071/225] fix(examples): cut both mounting holes in the bracket (#1515) Co-authored-by: bherbruck --- apps/solidcraft-cli/tests/bracket_example.rs | 62 ++++++++++++++++++++ examples/bracket.json | 6 +- tests/action_matrix/baseline.json | 20 +++++++ 3 files changed, 85 insertions(+), 3 deletions(-) create mode 100644 apps/solidcraft-cli/tests/bracket_example.rs diff --git a/apps/solidcraft-cli/tests/bracket_example.rs b/apps/solidcraft-cli/tests/bracket_example.rs new file mode 100644 index 000000000..8056a8786 --- /dev/null +++ b/apps/solidcraft-cli/tests/bracket_example.rs @@ -0,0 +1,62 @@ +//! The bracket example must cut two through holes, rather than successfully cutting empty +//! space beside the body. Check the shipped script and rebuild its saved design from scratch. + +use std::f64::consts::PI; + +use serde_json::Value; +use solidcraft_engine::geom::Vec3; +use solidcraft_engine::{Session, io, kernel}; + +fn assert_two_through_holes(session: &Session, stage: &str) { + let errors: Vec<_> = session.model.results.iter().filter_map(|r| r.error.as_ref().map(|e| (&r.name, e))).collect(); + assert!(errors.is_empty(), "{stage}: every example feature evaluates: {errors:?}"); + + let cut = session.doc.features.last().expect("the example ends with the hole cut"); + let before = session.model.state_before(cut.id); + let after = session.model.state(); + assert_eq!(before.bodies.len(), 1, "{stage}: one bracket before cutting the holes"); + assert_eq!(after.bodies.len(), 1, "{stage}: the holes leave one bracket"); + let uncut = &before.body("Bracket").expect("the uncut bracket").body; + let bracket = &after.body("Bracket").expect("the finished bracket").body; + + // Measure the actual state before the final cut so the existing edge fillet cancels out. + // Both holes have diameter 8 mm and pass through the 6 mm base. Kernel measurements are + // tessellated, so the relative tolerance applies to the removed material, not the body. + let removed = kernel::measure(uncut).unwrap().volume - kernel::measure(bracket).unwrap().volume; + let expected = 2.0 * PI * 4.0_f64.powi(2) * 6.0; + assert!((removed - expected).abs() < expected * 1e-3, "{stage}: the two holes remove {removed} mm³, expected {expected} mm³"); + + let before_mesh = uncut.tessellate(0.01).unwrap(); + let after_mesh = bracket.tessellate(0.01).unwrap(); + let down = Vec3::new(0.0, 0.0, -1.0); + for y in [-15.0, -45.0] { + let center = Vec3::new(25.0, y, 1.0); + assert_eq!(before_mesh.ray_crossings(center, down), 2, "{stage}: hole at y={y} starts over the solid base"); + // Rays through each opening must miss the entire bracket, including its top and + // bottom caps. Points away from the centre guard against a narrow slit or shifted cut. + for (dx, dy) in [(0.0, 0.0), (3.0, 0.0), (-3.0, 0.0), (0.0, 3.0), (0.0, -3.0)] { + let ray = center + Vec3::new(dx, dy, 0.0); + assert_eq!(after_mesh.ray_crossings(ray, down), 0, "{stage}: the hole at y={y} is open through both caps at ({dx}, {dy})"); + } + // Material just outside each radius remains, so neither opening is an edge notch. + for (dx, dy) in [(5.0, 0.0), (-5.0, 0.0), (0.0, 5.0), (0.0, -5.0)] { + let ray = center + Vec3::new(dx, dy, 0.0); + assert_eq!(after_mesh.ray_crossings(ray, down), 2, "{stage}: material remains around the hole at y={y}, offset ({dx}, {dy})"); + } + } +} + +#[test] +fn bracket_example_cuts_two_through_holes_and_reopens() { + let script: Value = serde_json::from_str(include_str!("../../../examples/bracket.json")).unwrap(); + let mut session = Session::default(); + session.run_script(&script).unwrap(); + assert_two_through_holes(&session, "script"); + + // No geometry cache is supplied: reopening the container re-evaluates the saved timeline. + let saved = io::write_design_container(&session.doc).unwrap(); + let document = io::read_design(&saved).unwrap(); + assert_eq!(document.features, session.doc.features, "saving preserves the example's feature parameters"); + let reopened = Session::new(document); + assert_two_through_holes(&reopened, "reopened"); +} diff --git a/examples/bracket.json b/examples/bracket.json index 752df039a..413346d3b 100644 --- a/examples/bracket.json +++ b/examples/bracket.json @@ -7,8 +7,8 @@ {"command": "solid.extrude", "params": {"distance": "width", "direction": "negative", "body_name": "Bracket"}}, {"command": "solid.fillet", "params": {"edges": [[40, -30, -6]], "radius": 2}}, {"command": "sketch.create", "params": {"plane": "XY", "name": "Holes"}}, - {"command": "sketch.circle.center", "params": {"center": [25, 15], "diameter": 8}}, - {"command": "sketch.circle.center", "params": {"center": [25, 45], "diameter": 8}}, + {"command": "sketch.circle.center", "params": {"center": [25, -15], "diameter": 8}}, + {"command": "sketch.circle.center", "params": {"center": [25, -45], "diameter": 8}}, {"command": "sketch.finish", "params": {}}, - {"command": "solid.extrude", "params": {"distance": "thickness", "operation": "cut"}} + {"command": "solid.extrude", "params": {"distance": "thickness", "direction": "negative", "operation": "cut"}} ]} diff --git a/tests/action_matrix/baseline.json b/tests/action_matrix/baseline.json index 3baf01a74..15b924f14 100644 --- a/tests/action_matrix/baseline.json +++ b/tests/action_matrix/baseline.json @@ -2688,6 +2688,10 @@ "Bracket/F2:side:a|F2:side:b": "edge.axis edge.chamfer edge.chamfer+edit edge.fillet edge.normal_plane edge.project", "Bracket/F2:side:a|F2:side:f": "edge.axis edge.chamfer edge.fillet edge.fillet+edit edge.normal_plane edge.normal_plane+edit edge.project", "Bracket/F2:side:a|F2:start": "edge.axis edge.axis+edit edge.chamfer edge.fillet edge.normal_plane edge.project", + "Bracket/F2:side:a|F5:side:c1#1": "edge.chamfer edge.fillet edge.normal_plane edge.normal_plane+edit edge.project", + "Bracket/F2:side:a|F5:side:c1#2": "edge.chamfer edge.fillet edge.normal_plane edge.normal_plane+edit edge.project", + "Bracket/F2:side:a|F5:side:c2#1": "edge.chamfer edge.fillet edge.normal_plane edge.project", + "Bracket/F2:side:a|F5:side:c2#2": "edge.chamfer edge.fillet edge.normal_plane edge.project", "Bracket/F2:side:b": "face.angle_plane !face.draft_neutral face.extrude face.hole face.hole+edit face.midplane face.offset_plane face.press_pull face.shell face.sketch face.sketch+edit", "Bracket/F2:side:b|F2:start": "edge.axis edge.chamfer edge.fillet edge.fillet+edit edge.normal_plane edge.project", "Bracket/F2:side:b|F3:blend:F2:side:b|F2:side:c": "edge.axis edge.normal_plane edge.project", @@ -2695,6 +2699,10 @@ "Bracket/F2:side:c|F2:side:d": "edge.axis edge.chamfer edge.chamfer+edit edge.fillet edge.normal_plane edge.normal_plane+edit edge.project", "Bracket/F2:side:c|F2:start": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project edge.project+edit", "Bracket/F2:side:c|F3:blend:F2:side:b|F2:side:c": "edge.axis edge.normal_plane edge.project", + "Bracket/F2:side:c|F5:side:c1#1": "edge.chamfer edge.fillet edge.fillet+edit edge.normal_plane edge.normal_plane+edit edge.project", + "Bracket/F2:side:c|F5:side:c1#2": "edge.chamfer edge.fillet edge.fillet+edit edge.normal_plane edge.normal_plane+edit edge.project", + "Bracket/F2:side:c|F5:side:c2#1": "edge.chamfer edge.fillet edge.normal_plane edge.project edge.project+edit", + "Bracket/F2:side:c|F5:side:c2#2": "edge.chamfer edge.fillet edge.normal_plane edge.project edge.project+edit", "Bracket/F2:side:d": "face.angle_plane !face.draft_neutral face.extrude face.hole face.hole+edit face.midplane face.midplane+edit face.offset_plane face.press_pull face.shell face.sketch", "Bracket/F2:side:d|F2:side:e": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.normal_plane+edit edge.project", "Bracket/F2:side:d|F2:start": "edge.axis edge.chamfer edge.fillet edge.fillet+edit edge.normal_plane edge.project", @@ -2706,6 +2714,10 @@ "Bracket/F2:start": "face.angle_plane !face.draft_neutral face.extrude face.hole face.offset_plane face.press_pull face.shell face.sketch", "Bracket/F2:start|F3:blend:F2:side:b|F2:side:c": "edge.chamfer edge.fillet edge.normal_plane edge.project", "Bracket/F3:blend:F2:side:b|F2:side:c": "curved.axis curved.tangent_plane", + "Bracket/F5:side:c1#1": "curved.axis curved.tangent_plane", + "Bracket/F5:side:c1#2": "curved.axis curved.tangent_plane", + "Bracket/F5:side:c2#1": "curved.axis curved.tangent_plane", + "Bracket/F5:side:c2#2": "curved.axis curved.tangent_plane", "Bracket/body": "body.copy body.mirror body.move body.pattern", "Bracket/v[F2:bottom & F2:side:a & F2:side:b]": "vertex.plane_three_points vertex.point vertex.point+edit", "Bracket/v[F2:bottom & F2:side:a & F2:side:f]": "vertex.plane_three_points vertex.point", @@ -2716,9 +2728,17 @@ "Bracket/v[F2:bottom & F2:side:e & F2:side:f]": "vertex.plane_three_points vertex.point", "Bracket/v[F2:side:a & F2:side:b & F2:start]": "vertex.plane_three_points vertex.point", "Bracket/v[F2:side:a & F2:side:f & F2:start]": "vertex.plane_three_points vertex.plane_three_points+edit vertex.point", + "Bracket/v[F2:side:a & F5:side:c1#1 & F5:side:c1#2]": "vertex.point", + "Bracket/v[F2:side:a & F5:side:c1#1 & F5:side:c1#2] (2)": "vertex.point", + "Bracket/v[F2:side:a & F5:side:c2#1 & F5:side:c2#2]": "vertex.point", + "Bracket/v[F2:side:a & F5:side:c2#1 & F5:side:c2#2] (2)": "vertex.point", "Bracket/v[F2:side:b & F2:start & F3:blend:F2:side:b|F2:side:c]": "vertex.plane_three_points vertex.point", "Bracket/v[F2:side:c & F2:side:d & F2:start]": "vertex.plane_three_points vertex.point", "Bracket/v[F2:side:c & F2:start & F3:blend:F2:side:b|F2:side:c]": "vertex.plane_three_points vertex.point", + "Bracket/v[F2:side:c & F5:side:c1#1 & F5:side:c1#2]": "vertex.point", + "Bracket/v[F2:side:c & F5:side:c1#1 & F5:side:c1#2] (2)": "vertex.point", + "Bracket/v[F2:side:c & F5:side:c2#1 & F5:side:c2#2]": "vertex.point", + "Bracket/v[F2:side:c & F5:side:c2#1 & F5:side:c2#2] (2)": "vertex.point", "Bracket/v[F2:side:d & F2:side:e & F2:start]": "vertex.plane_three_points vertex.plane_three_points+edit vertex.point", "Bracket/v[F2:side:e & F2:side:f & F2:start]": "vertex.plane_three_points vertex.point", "design": "load" From d8d04c9009cc538d863a476e2074043bb4c27d17 Mon Sep 17 00:00:00 2001 From: William Dunn Date: Mon, 19 Oct 2026 16:04:28 -0400 Subject: [PATCH 072/225] Tool modifiers: shared resolve, classic defaults, preview-safe Ctrl (#1616) * Centralise tool modifiers with classic defaults and preview-safe Ctrl. Route sketch/selection chords through a shared resolver. Keep Alt snap suppress and dual toggle as defaults; optional Shift add-only and Ctrl snap mapping. Skip preview rollback while a manipulator drag is active. * Address #1616 review: classic snap suppress, single viewport owner, docs. Default suppress to Ctrl/Cmd or Alt; drop navigation set_suppressed; remove unused label_key; add preview rollback gate test; document sketch modifiers. * fix(#1616): correct Modifiers primary in tests; simplify rollback fixture. * Treat Ctrl as primary off macOS, and rustfmt the modifier files. --- assets/locales/en.json | 8 + assets/locales/ja.json | 8 + assets/locales/zh.json | 8 + crates/gpu/src/capture.rs | 1 + crates/gpu/src/view.rs | 11 +- crates/ui-egui/src/canvas.rs | 11 +- crates/ui-egui/src/dialogs.rs | 50 ++ crates/ui-egui/src/drag_snap.rs | 12 +- crates/ui-egui/src/gizmo.rs | 6 +- crates/ui-egui/src/gpu.rs | 1 + crates/ui-egui/src/joint_browser_tests.rs | 2 +- crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/navigation.rs | 3 +- crates/ui-egui/src/prefs.rs | 124 +++- crates/ui-egui/src/preview.rs | 16 + crates/ui-egui/src/render_workspace.rs | 1 + crates/ui-egui/src/select_other.rs | 23 +- crates/ui-egui/src/sketch_modify_ui.rs | 20 + crates/ui-egui/src/sketch_tools.rs | 73 ++- crates/ui-egui/src/tool_modifiers.rs | 670 ++++++++++++++++++++++ crates/ui-egui/src/tools.rs | 36 ++ crates/ui-egui/src/viewport.rs | 95 ++- docs/book/src/guide/shortcuts.md | 12 + docs/book/src/guide/ui-tour.md | 2 +- 24 files changed, 1142 insertions(+), 52 deletions(-) create mode 100644 crates/ui-egui/src/tool_modifiers.rs diff --git a/assets/locales/en.json b/assets/locales/en.json index 708ac23f0..aff0a26e6 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -1324,6 +1324,8 @@ "ui.loft": "Loft", "ui.look_at": "Look At", "ui.look_at_anim_desc": "Axis view, Look At, Home and Fit", + "ui.manipulator_free_alt": "Manipulator free drag also on Alt/Option", + "ui.manipulator_free_alt_tip": "On: Alt/Option or Ctrl/Cmd on extrude / gizmo arrows disables value snapping. Off: Ctrl/Cmd only.", "ui.manufacture": "Manufacture", "ui.material_review.axes": "Material-local axes; no body orientation is assigned.", "ui.material_review.claims": "Sources and licences are unverified claims. Missing values remain unknown.", @@ -1464,6 +1466,9 @@ "ui.selectTangentChain": "Select Tangent Chain", "ui.select_other_hint": "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there.", "ui.selection": "Selection", + "ui.selection_modifiers": "Selection modifiers", + "ui.selection_shift_add_only": "Shift+click adds without removing", + "ui.selection_shift_add_only_tip": "On: Shift adds items, Ctrl/Cmd toggles. Off (default): Shift and Ctrl/Cmd both toggle.", "ui.send": "Send", "ui.send_to_slicer": "Send to slicer", "ui.sent_to_slicer": "Sent to {slicer}", @@ -1488,6 +1493,7 @@ "ui.sketch": "Sketch", "ui.sketch_dimension": "Sketch Dimension", "ui.sketch_grid": "Sketch Grid", + "ui.sketch_modifiers": "Sketch modifiers", "ui.sketch_scale": "Sketch Scale", "ui.sketch_status": "Sketch Status", "ui.sketches": "Sketches", @@ -1514,6 +1520,8 @@ "ui.supersampling_adaptive": "Only when the view is still", "ui.supersampling_off": "Off (1×)", "ui.suppress": "Suppress", + "ui.suppress_auto_snap": "Suppress auto-snap while drawing / dragging", + "ui.suppress_auto_snap_note": "Default: Ctrl/Cmd or Alt/Option each suppress sketch snapping. Choose a single key to narrow it.", "ui.sweep": "Sweep", "ui.sweep_follow_direction": "Follow Direction", "ui.sweep_keep_as_drawn": "Keep as Drawn", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index eeb2011c9..205309ba6 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -1324,6 +1324,8 @@ "ui.loft": "ロフト", "ui.look_at": "正面視", "ui.look_at_anim_desc": "軸ビュー、正面視、ホーム、全体表示", + "ui.manipulator_free_alt": "マニピュレータのフリードラッグを Alt/Option でも有効", + "ui.manipulator_free_alt_tip": "オン: 押し出し/ギズモ矢印で Alt/Option または Ctrl/Cmd が値スナップを無効にします。オフ: Ctrl/Cmd のみ。", "ui.manufacture": "製造", "ui.material_review.axes": "材料ローカル軸。ボディの方向は割り当てません。", "ui.material_review.claims": "出典とライセンスの申告は未確認です。欠落値は不明のままです。", @@ -1464,6 +1466,9 @@ "ui.selectTangentChain": "接線チェーンを選択", "ui.select_other_hint": "その他を選択: モデル上で左ボタンを長押し(または右クリック › その他を選択…)するとカーソル下の要素が一覧表示されます。同じ場所を再度クリックすると次の要素が選択されます。", "ui.selection": "選択", + "ui.selection_modifiers": "選択修飾キー", + "ui.selection_shift_add_only": "Shift+クリックで追加のみ(解除なし)", + "ui.selection_shift_add_only_tip": "オン: Shift は追加、Ctrl/Cmd はトグル。オフ(既定): Shift と Ctrl/Cmd の両方がトグル。", "ui.send": "送信", "ui.send_to_slicer": "スライサーに送る", "ui.sent_to_slicer": "{slicer} に送信しました", @@ -1488,6 +1493,7 @@ "ui.sketch": "スケッチ", "ui.sketch_dimension": "スケッチ寸法", "ui.sketch_grid": "スケッチ グリッド", + "ui.sketch_modifiers": "スケッチ修飾キー", "ui.sketch_scale": "スケッチ尺度", "ui.sketch_status": "スケッチの状態", "ui.sketches": "スケッチ", @@ -1514,6 +1520,8 @@ "ui.supersampling_adaptive": "ビューが静止しているときのみ", "ui.supersampling_off": "オフ (1×)", "ui.suppress": "抑制", + "ui.suppress_auto_snap": "作図・ドラッグ中の自動スナップを抑制", + "ui.suppress_auto_snap_note": "既定: Ctrl/Cmd または Alt/Option のどれでもスケッチスナップを抑制します。単一キーに絞ることもできます。", "ui.sweep": "スイープ", "ui.sweep_follow_direction": "方向に従う", "ui.sweep_keep_as_drawn": "描いた向きを保持", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index 96b2405e0..c5181f0ec 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -1324,6 +1324,8 @@ "ui.loft": "放样", "ui.look_at": "朝向", "ui.look_at_anim_desc": "轴视图、注视、主视图与适合窗口", + "ui.manipulator_free_alt": "操纵器自由拖动也适用于 Alt/Option", + "ui.manipulator_free_alt_tip": "开:在拉伸/小控件箭头上按 Alt/Option 或 Ctrl/Cmd 可关闭数值捕捉。关:仅 Ctrl/Cmd。", "ui.manufacture": "制造", "ui.material_review.axes": "材料局部坐标轴;不指定实体方向。", "ui.material_review.claims": "来源和许可证声明未经核实。缺失值保持未知。", @@ -1464,6 +1466,9 @@ "ui.selectTangentChain": "选择相切链", "ui.select_other_hint": "“选择其他”:在模型上按住左键(或右键单击 › 选择其他…)列出光标下的所有对象;在同一位置再次单击可选择该处的下一个对象。", "ui.selection": "选择", + "ui.selection_modifiers": "选择修饰键", + "ui.selection_shift_add_only": "Shift+点击仅添加、不取消选择", + "ui.selection_shift_add_only_tip": "开:Shift 添加,Ctrl/Cmd 切换。关(默认):Shift 与 Ctrl/Cmd 均可切换。", "ui.send": "发送", "ui.send_to_slicer": "发送到切片软件", "ui.sent_to_slicer": "已发送到 {slicer}", @@ -1488,6 +1493,7 @@ "ui.sketch": "草图", "ui.sketch_dimension": "草图尺寸", "ui.sketch_grid": "草图网格", + "ui.sketch_modifiers": "草图修饰键", "ui.sketch_scale": "草图比例", "ui.sketch_status": "草图状态", "ui.sketches": "草图", @@ -1514,6 +1520,8 @@ "ui.supersampling_adaptive": "仅在视图静止时", "ui.supersampling_off": "关 (1×)", "ui.suppress": "抑制", + "ui.suppress_auto_snap": "绘制/拖动时抑制自动捕捉", + "ui.suppress_auto_snap_note": "默认:Ctrl/Cmd 或 Alt/Option 均可抑制草图捕捉。也可改成只认其中一个键。", "ui.sweep": "扫掠", "ui.sweep_follow_direction": "跟随方向", "ui.sweep_keep_as_drawn": "保持绘制方向", diff --git a/crates/gpu/src/capture.rs b/crates/gpu/src/capture.rs index befd54736..4ec11a29b 100644 --- a/crates/gpu/src/capture.rs +++ b/crates/gpu/src/capture.rs @@ -314,6 +314,7 @@ fn frame(scene: &Scene, cam: &Camera, [width, height]: [u32; 2], key: u64, acces hl_slot: empty(), pv_key: 0, pv_slot: empty(), + pv_hide: false, view_proj: cam.view_proj(f64::from(width) / f64::from(height.max(1)), scene.radius.max(1.0)).to_f32(), back: cam.back().to_f32(), size_px: [width as f32, height as f32], diff --git a/crates/gpu/src/view.rs b/crates/gpu/src/view.rs index 2225c0900..c1b162c74 100644 --- a/crates/gpu/src/view.rs +++ b/crates/gpu/src/view.rs @@ -224,6 +224,8 @@ pub struct Frame { /// The live preview scene and its key. pub pv_key: u64, pub pv_slot: SceneSlot, + /// Preview reselect: skip drawing the preview while Primary rolls it back. + pub pv_hide: bool, /// Column-major view-projection. pub view_proj: [[f32; 4]; 4], /// Direction toward the eye (for lighting). @@ -1419,8 +1421,13 @@ impl Renderer { } } }; - let (m, sk, h, pv) = - if cb.product { (&res.product, &res.empty, &res.empty, &res.empty) } else { (&res.model, &res.sketch, &res.highlight, &res.preview) }; + let (m, sk, h, pv) = if cb.product { + (&res.product, &res.empty, &res.empty, &res.empty) + } else if cb.pv_hide { + (&res.model, &res.sketch, &res.highlight, &res.empty) + } else { + (&res.model, &res.sketch, &res.highlight, &res.preview) + }; lines(pass, &res.overlay, &m.under); lines(pass, &res.overlay, &sk.under); pass.set_bind_group(1, &res.access_bind, &[]); diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 28b05b856..c4f880487 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -606,8 +606,9 @@ fn drag_arrow( && let Some(p) = r.interact_pointer_pos() && let Some(v) = along(proj, p, base, n) { + crate::tool_modifiers::set_manipulator_dragging(true); let v = v - ui.data(|d| d.get_temp::(grab)).unwrap_or(0.0); - let free = ui.input(|i| i.modifiers.alt || i.modifiers.ctrl || i.modifiers.command); + let free = crate::tool_modifiers::manipulator_free(); let step = snap_step(half_height); let mut v = if free { v } else { (v / step).round() * step }; if !signed { @@ -780,7 +781,8 @@ fn radius_spline_handles(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Pain && let Some(p) = r.interact_pointer_pos() && let Some(v) = along(proj, p, at(*u), e.n) { - let free = ui.input(|i| i.modifiers.alt || i.modifiers.ctrl || i.modifiers.command); + crate::tool_modifiers::set_manipulator_dragging(true); + let free = crate::tool_modifiers::manipulator_free(); let step = snap_step(half_height); let v = if free { v } else { (v / step).round() * step }; // Zero only at an end, where the round closes to a point. @@ -974,9 +976,10 @@ fn taper_handle( && let Some(p) = r.interact_pointer_pos() && let Some(s) = along(proj, p, foot + span, e) { + crate::tool_modifiers::set_manipulator_dragging(true); let mut deg = s.atan2(l).to_degrees(); let (lo, hi) = limits; - if ui.input(|i| i.modifiers.alt || i.modifiers.ctrl || i.modifiers.command) { + if crate::tool_modifiers::manipulator_free() { deg = deg.clamp(lo, hi); } else { // Whole degrees, rounded towards zero at a limit so they stay inside it. @@ -1255,7 +1258,7 @@ fn rotation_handle( .min_by(|a, b| (a - boundary).abs().total_cmp(&(b - boundary).abs())) .unwrap_or_else(|| raw.clamp(bounds.0, bounds.1)); let mut angle = (boundary_angle.clamp(bounds.0, bounds.1) * scale + offset).to_degrees(); - if !ui.input(|input| input.modifiers.alt || input.modifiers.ctrl || input.modifiers.command) { + if !crate::tool_modifiers::manipulator_free() { angle = (angle / 5.0).round() * 5.0; } if angle.abs() < 0.05 { diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 1f12a250b..f06e5ef3b 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -15,8 +15,58 @@ use solidcraft_engine::geom::{Aabb3, Vec3}; use crate::SolveApp; use crate::selection::{self, AXES, Accept, BODIES, CURVES, EDGES, FACES, PLANAR_FACES, PLANES, PROFILES, SelInput}; use crate::theme::Tokens; +use crate::tool_modifiers::{Audit, Scope, ToolModifiers}; use crate::viewport::Hit; +const SELECT_ONLY: &[Scope] = &[Scope::Selection, Scope::FeaturePreview]; +const SELECT_MANIP: &[Scope] = &[Scope::Selection, Scope::Manipulator, Scope::FeaturePreview]; + +/// Per-tool modifier descriptors owned by this host file (SOLID / construct / inspect dialogs). +pub const MODIFIERS: &[ToolModifiers] = &[ + ToolModifiers { tool: "sketch.create", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.extrude", scopes: SELECT_MANIP, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.revolve", scopes: SELECT_MANIP, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.fillet", scopes: SELECT_MANIP, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.chamfer", scopes: SELECT_MANIP, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.shell", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.draft", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.mirror", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.rib", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.web", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.emboss", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.replace_face", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.boundary_fill", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.align", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.remove", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + // Pattern parameters are dialog-only - no viewport modifier chords. + ToolModifiers { tool: "solid.pattern.path", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.pattern.rectangular", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.pattern.circular", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.pipe", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.bounding_solid", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "construct.plane.offset", scopes: SELECT_MANIP, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "construct.plane.along_path", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "construct.plane.at_angle", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.split_body", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.scale", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.offset_face", scopes: SELECT_MANIP, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.thread", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "material.assign", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "inspect.section", scopes: SELECT_MANIP, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "inspect.measure", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.loft", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.sweep", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + // Move: no Alt-copy / inventable chords; inherits Selection + Manipulator only. + ToolModifiers { tool: "solid.move", scopes: SELECT_MANIP, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.hole", scopes: SELECT_MANIP, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.box", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.cylinder", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.sphere", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.torus", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.coil", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "solid.combine", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, +]; + pub(crate) const OPS: [&str; 4] = ["new", "join", "cut", "intersect"]; pub(crate) const OP_LABELS: [&str; 4] = ["New Body", "Join", "Cut", "Intersect"]; const DIRS: [&str; 4] = ["positive", "negative", "symmetric", "positive"]; diff --git a/crates/ui-egui/src/drag_snap.rs b/crates/ui-egui/src/drag_snap.rs index c3708c275..5646239a7 100644 --- a/crates/ui-egui/src/drag_snap.rs +++ b/crates/ui-egui/src/drag_snap.rs @@ -1,8 +1,8 @@ -//! Snapping while a sketch point or a line is dragged: the dragged point snaps to -//! other points (ends, centres, the origin, projected points), to the middle of a line and onto -//! curves, and lines up horizontally or vertically with other points (a dashed guide). Letting -//! go on a point, a midpoint or a curve adds the matching constraint; lining up adds none. Ctrl -//! or Alt held: no snapping (here and while drawing). +//! Snapping while a sketch point or a line is dragged: the dragged point snaps to other points +//! (ends, centres, the origin, projected points), to the middle of a line and onto curves, and +//! lines up horizontally or vertically with other points (a dashed guide). Letting go on a point, +//! a midpoint or a curve adds the matching constraint; lining up adds none. The suppress-snap +//! chord is configurable (default Ctrl/Cmd or Alt/Option; see `prefs::suppress_sketch_snap`). use std::cell::{Cell, RefCell}; @@ -60,7 +60,7 @@ thread_local! { static SUPPRESSED: Cell = const { Cell::new(false) }; } -/// Ctrl or Alt held this frame (no snapping). +/// Whether sketch snap is suppressed this frame (set from the viewport via `prefs::suppress_sketch_snap_held`). pub fn set_suppressed(on: bool) { SUPPRESSED.with(|s| s.set(on)); } diff --git a/crates/ui-egui/src/gizmo.rs b/crates/ui-egui/src/gizmo.rs index f3d2a9162..ebc4d23e1 100644 --- a/crates/ui-egui/src/gizmo.rs +++ b/crates/ui-egui/src/gizmo.rs @@ -277,7 +277,11 @@ pub fn show(ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj, id: egui::I active?; ui.ctx().set_cursor_icon(egui::CursorIcon::Grab); let r = ui.interact(Rect::from_center_size(p, vec2(24.0, 24.0)), id.with("hit"), Sense::drag()); - let free = ui.input(|i| i.modifiers.alt || i.modifiers.ctrl || i.modifiers.command); + // Free drag is driven by the per-frame thread-local set from prefs::manipulator_free_held. + let free = crate::tool_modifiers::manipulator_free(); + if state.is_some() || r.dragged() || r.drag_started() { + crate::tool_modifiers::set_manipulator_dragging(true); + } let view = proj.ray(sh.ball).1; let plane_normal = |h: Handle| match h { Handle::Plane(i) | Handle::Ring(i) => DIRS[i], diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs index 0dd840176..4179ebedf 100644 --- a/crates/ui-egui/src/gpu.rs +++ b/crates/ui-egui/src/gpu.rs @@ -270,6 +270,7 @@ fn offscreen( hl_slot: Arc::new(Mutex::new(highlight)), pv_key: 0, pv_slot: none(), + pv_hide: false, view_proj, back, size_px: [size as f32; 2], diff --git a/crates/ui-egui/src/joint_browser_tests.rs b/crates/ui-egui/src/joint_browser_tests.rs index 603c8daef..9d055bec4 100644 --- a/crates/ui-egui/src/joint_browser_tests.rs +++ b/crates/ui-egui/src/joint_browser_tests.rs @@ -92,7 +92,7 @@ fn a_hidden_joint_still_drives_and_shows_while_picked() { assert_eq!(h.app.tree.picked_joints, [hinge]); assert!(drawn(&h).contains(&(hinge, true)), "{:?}", drawn(&h)); assert!(!h.app.session.joint_visible(hinge), "picking doesn't show it"); - crate::viewport::select(&mut h.app, None, false); + crate::viewport::select(&mut h.app, None, false, false); assert!(h.app.tree.picked_joints.is_empty()); assert!(!drawn(&h).iter().any(|(j, _)| *j == hinge)); } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index d165e9129..c68afd2d6 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -187,6 +187,7 @@ mod thin_extrude_tests; pub mod timeline; pub mod timeline_left; pub mod titlebar; +pub mod tool_modifiers; pub mod toolbar; pub mod toolbar_custom; pub mod tools; diff --git a/crates/ui-egui/src/navigation.rs b/crates/ui-egui/src/navigation.rs index a8083ae15..657d5d423 100644 --- a/crates/ui-egui/src/navigation.rs +++ b/crates/ui-egui/src/navigation.rs @@ -282,8 +282,7 @@ pub(crate) fn handle(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect, resp: &e // with no window or menu above it. let inside = resp.contains_pointer() && ui.rect_contains_pointer(rect) && hover.is_some_and(|p| !axes.contains(p)); app.viewport.mouse = hover.filter(|_| inside); - // Ctrl or Alt held: drawing and dragging don't snap. - crate::drag_snap::set_suppressed(mods.ctrl || mods.alt || mods.command); + // Sketch snap suppression is set once in `viewport::show` from preferences. middle_double_click(app, ui, inside); // The 3D mouse's motion this frame, with what this page's camera may do. device(app, rect, caps); diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index f7fc8f00a..47963d692 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -27,6 +27,7 @@ pub fn stored(get: impl Fn(&str) -> Option) -> Option { use crate::SolveApp; use crate::theme::Tokens; +use crate::tool_modifiers::ModifierCombo; use crate::viewport::NavMode; pub const UNITS: [&str; 5] = ["mm", "cm", "m", "in", "ft"]; @@ -391,6 +392,16 @@ pub struct Prefs { pub agent_chat_window: Option<[f32; 4]>, /// Changes the agent may make for one message. pub agent_chat_turn_limit: u32, + + // ---- Sketch / selection modifier bindings (classic defaults; alternate mapping is opt-in) ---- + /// Modifier that suppresses sketch auto-snap while drawing or dragging a sketch point. + /// Default: Alt/Option. Set to Ctrl/Cmd for the alternate mapping. + pub suppress_sketch_snap: ModifierCombo, + /// Whether Alt/Option also frees gizmo / canvas manipulator arrows (Primary always does). + pub manipulator_free_alt: bool, + /// When true: Shift+click adds without removing; Primary toggles. + /// When false (default): Shift and Primary both toggle. + pub selection_shift_add_only: bool, } /// What a middle-button double-click in the view does. @@ -487,6 +498,9 @@ impl Default for Prefs { agent_chat_popped: false, agent_chat_window: None, agent_chat_turn_limit: crate::agent_chat::gate::DEFAULT_TURN_LIMIT, + suppress_sketch_snap: ModifierCombo::CTRL_ALT, + manipulator_free_alt: true, + selection_shift_add_only: false, } } } @@ -776,8 +790,15 @@ fn defaults(app: &mut SolveApp, page: usize) { save_graphics(app); } } - 5 => app.session.auto_project = true, - _ => app.ui.pick_bodies = false, + 5 => { + app.session.auto_project = true; + p.suppress_sketch_snap = d.suppress_sketch_snap; + p.manipulator_free_alt = d.manipulator_free_alt; + } + _ => { + app.ui.pick_bodies = false; + p.selection_shift_add_only = d.selection_shift_add_only; + } } } @@ -861,6 +882,25 @@ pub fn pan_sign_x(app: &SolveApp) -> f32 { if app.preferences.pan_reverse_x { -1.0 } else { 1.0 } } +/// Whether the configured suppress-snap chord is held. +pub fn suppress_sketch_snap_held(app: &SolveApp, m: Modifiers) -> bool { + let c = app.preferences.suppress_sketch_snap; + let held = crate::tool_modifiers::Held::from_modifiers(m); + // Classic default (`CTRL_ALT`): Ctrl/Cmd **or** Alt/Option each suppress snap. + // A single-key preference keeps the usual AtLeast match for that key only. + if c == ModifierCombo::CTRL_ALT { + return held.primary || held.alt; + } + c.held(m) +} + +/// Primary always frees manipulator arrows; Alt/Option also frees when `manipulator_free_alt` is on. +pub fn manipulator_free_held(app: &SolveApp, m: Modifiers) -> bool { + use crate::tool_modifiers::Held; + let held = Held::from_modifiers(m); + held.primary || (app.preferences.manipulator_free_alt && held.alt) +} + /// +1, or −1 when the wheel zooms the other way. pub fn zoom_sign(app: &SolveApp) -> f64 { if app.preferences.zoom_reverse { -1.0 } else { 1.0 } @@ -1489,11 +1529,50 @@ fn page(app: &mut SolveApp, ui: &mut egui::Ui, t: &Tokens) { let _ = app.run("sketch.auto_project", json!({ "value": auto })); } ui.end_row(); + + ui.label(""); + ui.end_row(); + ui.label(RichText::new(crate::i18n::tr_label("Sketch modifiers")).strong()); + ui.label(""); + ui.end_row(); + + ui.label(crate::i18n::tr_label("Suppress auto-snap while drawing / dragging")); + snap_suppress_picker(ui, "pref_suppress_sketch_snap", &mut app.preferences.suppress_sketch_snap); + ui.end_row(); + note(ui, crate::i18n::tr_label("ui.suppress_auto_snap_note")); + + ui.label(crate::i18n::tr_label("Manipulator free drag also on Alt/Option")); + ui.checkbox(&mut app.preferences.manipulator_free_alt, "").on_hover_text(crate::i18n::tr_label( + "On: Alt/Option or Ctrl/Cmd on extrude / gizmo arrows disables value snapping. Off: Ctrl/Cmd only.", + )); + ui.end_row(); } _ => { ui.label(crate::i18n::tr_label("Click selects whole bodies")); ui.checkbox(&mut app.ui.pick_bodies, ""); ui.end_row(); + + ui.label(""); + ui.end_row(); + ui.label(RichText::new(crate::i18n::tr_label("Selection modifiers")).strong()); + ui.label(""); + ui.end_row(); + + ui.label(crate::i18n::tr_label("Shift+click adds without removing")); + ui.checkbox(&mut app.preferences.selection_shift_add_only, "").on_hover_text(crate::i18n::tr_label( + "On: Shift adds items, Ctrl/Cmd toggles. Off (default): Shift and Ctrl/Cmd both toggle.", + )); + ui.end_row(); + } + }); +} + +/// Sketch snap-suppress picker: classic Ctrl/Cmd-or-Alt first, then single keys. +fn snap_suppress_picker(ui: &mut egui::Ui, salt: &str, combo: &mut ModifierCombo) { + let label = combo.label(); + egui::ComboBox::from_id_salt(salt).selected_text(label).show_ui(ui, |ui| { + for c in ModifierCombo::SNAP_SUPPRESS_CHOICES { + ui.selectable_value(combo, c, c.label()); } }); } @@ -2102,6 +2181,47 @@ mod tests { assert!(h.app.preferences.radial_context_menu, "Cancel restores the last Apply"); } + #[test] + fn tool_modifier_prefs_default_classic_and_persist() { + let d = Prefs::default(); + assert_eq!(d.suppress_sketch_snap, ModifierCombo::CTRL_ALT); + assert!(d.manipulator_free_alt); + assert!(!d.selection_shift_add_only); + let old: Prefs = serde_json::from_value(json!({"nav": "solidworks"})).unwrap(); + assert_eq!(old.suppress_sketch_snap, ModifierCombo::CTRL_ALT); + assert!(!old.selection_shift_add_only); + // Classic default: Ctrl/Cmd or Alt each suppress (`command` is primary on all hosts). + let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + let ctrl = Modifiers { ctrl: true, command: true, ..Default::default() }; + let alt = Modifiers { alt: true, ..Default::default() }; + let shift = Modifiers { shift: true, ..Default::default() }; + assert!(suppress_sketch_snap_held(&app, ctrl)); + assert!(suppress_sketch_snap_held(&app, alt)); + assert!(!suppress_sketch_snap_held(&app, shift)); + control( + &mut app, + &json!({"open": "Sketch", "suppress_sketch_snap": {"shift": false, "ctrl": true, "alt": false}, "manipulator_free_alt": false}), + ) + .unwrap(); + control(&mut app, &json!({"button": "apply"})).unwrap(); + control(&mut app, &json!({"open": "Selection", "selection_shift_add_only": true})).unwrap(); + control(&mut app, &json!({"button": "apply"})).unwrap(); + assert_eq!(app.preferences.suppress_sketch_snap, ModifierCombo::CTRL); + assert!(!app.preferences.manipulator_free_alt); + assert!(app.preferences.selection_shift_add_only); + let mut other = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + other.load_prefs(&app.prefs()); + assert_eq!(other.preferences.suppress_sketch_snap, ModifierCombo::CTRL); + assert!(!other.preferences.manipulator_free_alt); + assert!(other.preferences.selection_shift_add_only); + control(&mut app, &json!({"open": "Sketch", "button": "defaults"})).unwrap(); + assert_eq!(app.preferences.suppress_sketch_snap, ModifierCombo::CTRL_ALT); + assert!(app.preferences.manipulator_free_alt); + assert!(app.preferences.selection_shift_add_only, "Selection page setting stays until that page resets"); + control(&mut app, &json!({"button": "cancel"})).unwrap(); + assert_eq!(app.preferences.suppress_sketch_snap, ModifierCombo::CTRL); + } + #[test] fn wheel_smoothing_persists_and_follows_dialog_buttons() { assert!(serde_json::from_value::(json!({})).unwrap().smooth_wheel_zoom); diff --git a/crates/ui-egui/src/preview.rs b/crates/ui-egui/src/preview.rs index 355d760e8..633d6e7db 100644 --- a/crates/ui-egui/src/preview.rs +++ b/crates/ui-egui/src/preview.rs @@ -99,9 +99,21 @@ pub struct PreviewState { /// The radius splines the previewed fillet tapered its edges with. pub tapered: Vec<(Vec3, solidcraft_engine::kernel::Taper)>, straight: crate::extrude_preview::StraightPreview, + /// PreviewReselect: Primary held - hide the preview and restore replaced bodies for picks. + pub rolled_back: bool, } impl PreviewState { + /// Bodies the model scene should hide for the preview (empty while rolled back). + pub fn effective_replaced(&self) -> &[String] { + if self.rolled_back { &[] } else { &self.replaced } + } + + /// Whether the preview scene should be drawn. + pub fn draw_active(&self) -> bool { + self.active && !self.rolled_back + } + fn clear(&mut self) { self.straight.clear(); self.running = None; @@ -114,6 +126,7 @@ impl PreviewState { self.tapered.clear(); self.sketches.clear(); self.busy = false; + self.rolled_back = false; if self.active || !self.replaced.is_empty() { self.active = false; self.bounds = Aabb3::EMPTY; @@ -761,6 +774,9 @@ pub fn point_triangle_dist(p: Vec3, a: Vec3, b: Vec3, c: Vec3) -> f64 { /// The same computed sketch preview is drawn over both native GPU and CPU viewports. pub fn paint_sketches(app: &SolveApp, painter: &egui::Painter, proj: &crate::viewport::Proj) { + if app.preview.rolled_back { + return; + } if !app.dialog.as_ref().is_some_and(|d| matches!(d.kind, crate::dialogs::Kind::SketchModify(_)) && d.previews()) { return; } diff --git a/crates/ui-egui/src/render_workspace.rs b/crates/ui-egui/src/render_workspace.rs index bdcbe43ba..e59adfe6f 100644 --- a/crates/ui-egui/src/render_workspace.rs +++ b/crates/ui-egui/src/render_workspace.rs @@ -528,6 +528,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { hl_slot: slot.clone(), pv_key: 0, pv_slot: slot, + pv_hide: false, view_proj: camera.view_proj(f64::from(rect.width() / rect.height().max(1.0)), radius).to_f32(), back: camera.back().to_f32(), size_px: [rect.width() * ppp, rect.height() * ppp], diff --git a/crates/ui-egui/src/select_other.rs b/crates/ui-egui/src/select_other.rs index bbe3f07e3..210ec8591 100644 --- a/crates/ui-egui/src/select_other.rs +++ b/crates/ui-egui/src/select_other.rs @@ -318,23 +318,26 @@ pub fn is_open(app: &SolveApp) -> bool { app.viewport.select_other.popup.is_some() } -/// Pick row `i` of the open list (`add`: Shift/Ctrl, add to the selection) and close it. -pub fn choose(app: &mut SolveApp, i: usize, add: bool) -> Result { +/// Pick row `i` of the open list and close it. +/// +/// `add` / `toggle` match viewport selection (Shift pure-add, Primary toggle when +/// `selection_shift_add_only` is on). +pub fn choose(app: &mut SolveApp, i: usize, add: bool, toggle: bool) -> Result { let Some(p) = app.viewport.select_other.popup.as_ref() else { return Err("Select Other is not open".into()) }; let at = p.at; let row = p.rows.get(i).cloned().ok_or_else(|| format!("no row {i} (the list has {})", p.rows.len()))?; close(app); - apply(app, &row, add); + apply(app, &row, add, toggle); remember(app, at, if add { None } else { Some(row.sel.clone()) }); Ok(row) } /// Select a row's entity: into the dialog's active input, or as a click does. -fn apply(app: &mut SolveApp, row: &Row, add: bool) { +fn apply(app: &mut SolveApp, row: &Row, add: bool, toggle: bool) { if app.dialog.as_ref().is_some_and(|d| d.wants_picks()) { crate::viewport::dialog_pick(app, &row.hit, row.sel.clone()); } else { - crate::viewport::select(app, Some(row.sel.clone()), add); + crate::viewport::select(app, Some(row.sel.clone()), add, toggle); } } @@ -376,7 +379,9 @@ pub fn control(app: &mut SolveApp, p: &Value) -> Result { return Ok(describe(app)); } if let Some(i) = p.get("pick").and_then(Value::as_u64) { - let row = choose(app, i as usize, p.get("add").and_then(Value::as_bool).unwrap_or(false))?; + // Control channel: `add` enables both add and toggle (legacy API). + let add = p.get("add").and_then(Value::as_bool).unwrap_or(false); + let row = choose(app, i as usize, add, add)?; return Ok(json!({ "picked": row.label, "sel": row.sel, "selection": app.session.selection })); } Ok(describe(app)) @@ -487,7 +492,7 @@ pub fn cycle_click(app: &mut SolveApp, proj: &Proj, at: Pos2) -> bool { } let next = rows.iter().position(|r| crate::selection::same_item(&r.sel, &c.chosen)).map_or(0, |k| (k + 1) % rows.len()); let Some(row) = rows.get(next).cloned() else { return false }; - apply(app, &row, false); + apply(app, &row, false, false); app.set_status(format!("{} ({} of {})", row.label, next + 1, rows.len()), false); remember(app, c.at, Some(row.sel)); true @@ -552,7 +557,9 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { } let (pressed, pointer, mods) = ctx.input(|i| (i.pointer.any_pressed(), i.pointer.interact_pos(), i.modifiers)); if let Some(i) = picked { - let _ = choose(app, i, mods.shift || mods.ctrl || mods.command); + let held = crate::tool_modifiers::Held::from_modifiers(mods); + let (add, toggle) = crate::tool_modifiers::selection_click(held, app.preferences.selection_shift_add_only); + let _ = choose(app, i, add, toggle); } else if pressed && !pointer.is_some_and(|q| resp.response.rect.contains(q)) { // A press elsewhere only closes the list. close(app); diff --git a/crates/ui-egui/src/sketch_modify_ui.rs b/crates/ui-egui/src/sketch_modify_ui.rs index b06713106..be9644d23 100644 --- a/crates/ui-egui/src/sketch_modify_ui.rs +++ b/crates/ui-egui/src/sketch_modify_ui.rs @@ -33,8 +33,28 @@ use solidcraft_engine::sketch::PatternAlignment; use crate::SolveApp; use crate::dialogs::{CHAMFER_TYPES, Dialog, Kind, check, field, icon_choice, pattern_toggle, row_label}; use crate::selection::{AXES, CURVES, SKETCH_POINTS, SelInput}; +use crate::tool_modifiers::{Audit, Scope, ToolModifiers}; use crate::viewport::{Hit, Proj}; +const SELECT_MANIP: &[Scope] = &[Scope::Selection, Scope::Manipulator, Scope::FeaturePreview]; +const SELECT_ONLY: &[Scope] = &[Scope::Selection, Scope::FeaturePreview]; + +/// Per-tool modifier descriptors owned by this host file. +pub const MODIFIERS: &[ToolModifiers] = &[ + ToolModifiers { tool: "sketch.scale", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.offset", scopes: SELECT_MANIP, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.mirror", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + // Sketch Move: dialog/manipulator inherit only - no invented Alt-copy. + ToolModifiers { tool: "sketch.move", scopes: SELECT_MANIP, bindings: &[], audit: Audit::VerifiedNoOp }, + // Pattern spacing/count live in the dialog - no viewport modifier chords. + ToolModifiers { tool: "sketch.pattern.rectangular", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.pattern.circular", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.fillet", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.chamfer.equal_distance", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.chamfer.two_distance", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.chamfer.distance_angle", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp }, +]; + /// The three chamfer types, drawn as the cut each one makes, in `CHAMFER_TYPES` order. const CHAMFER_TYPE_ICONS: [&str; 3] = ["sketch_chamfer_equal", "sketch_chamfer_two", "sketch_chamfer_angle"]; diff --git a/crates/ui-egui/src/sketch_tools.rs b/crates/ui-egui/src/sketch_tools.rs index ce0be3ee2..f4edda24f 100644 --- a/crates/ui-egui/src/sketch_tools.rs +++ b/crates/ui-egui/src/sketch_tools.rs @@ -12,9 +12,61 @@ use serde_json::{Value, json}; use solidcraft_engine::geom::{Vec2, Vec3}; use crate::SolveApp; +use crate::tool_modifiers::{Audit, Binding, Match, ModAction, ModifierCombo, Scope, ToolModifiers, Trigger}; use crate::tools::{Kind, Tool}; use crate::viewport::{Hit, Proj, pick, sketch_point_at}; +const DRAW_SCOPES: &[Scope] = &[Scope::SketchDraw, Scope::SketchDrag]; +const NONE: &[Scope] = &[]; + +const ISOCURVE_ALT: &[Binding] = &[Binding { + action: ModAction::IsoCurveAlternate, + defaults: &[ModifierCombo::SHIFT], + matching: Match::AtLeast, + trigger: Trigger::Press, + rebindable: true, +}]; + +/// Per-tool modifier descriptors owned by this host file. +pub const MODIFIERS: &[ToolModifiers] = &[ + ToolModifiers { tool: "sketch.project", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.intersect", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.include_3d", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.fit_curves_to_section", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.isoparametric_curve", scopes: NONE, bindings: ISOCURVE_ALT, audit: Audit::Implemented }, + ToolModifiers { tool: "inspect.curvature_comb", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "inspect.minimum_radius", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "inspect.center_of_mass", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "inspect.isocurve", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "canvas.insert", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "canvas.decal", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.trim", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.extend", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.break", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.line.midpoint", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.arc.tangent", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.ellipse", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.conic", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.slot.center_point", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.slot.arc_three_point", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.slot.arc_center", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.spline.fit_point", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.spline.control_point", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.spline.control_point_5", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.text", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.edit_text", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.blend_curve", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.constraint.curvature", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.circle.two_tangent", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.circle.three_tangent", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.constrainer", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.constraint.polygon", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.centerline", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.project_to_surface", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.intersection_curve", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.spun_profile", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp }, +]; + thread_local! { /// Shift held this frame. static SHIFT: Cell = const { Cell::new(false) }; @@ -280,6 +332,9 @@ pub fn refine_snap( return Some((plane.to_local(point), Some(format!("vertex:{},{},{}", point.x, point.y, point.z)))); } } + let mid_only = crate::tool_modifiers::target_midpoint(); + // Shift midpoint mode: widen the midpoint capture a little and skip other inferences. + let mid_tol = if mid_only { tol * 1.5 } else { tol }; let mut best: Option<(f64, &'static str, Vec2)> = None; let mut mid_of: Option = None; for (i, c) in sk.curves.iter().enumerate() { @@ -288,7 +343,7 @@ pub fn refine_snap( { let m = (a + b) * 0.5; let d = m.dist(lp); - if d < tol && best.is_none_or(|x| d < x.0) { + if d < mid_tol && best.is_none_or(|x| d < x.0) { best = Some((d, "Mid", m)); mid_of = Some(c.id.clone()); } @@ -306,7 +361,8 @@ pub fn refine_snap( }; // Line tool: the tangent point of a circle or arc (before plain "on the curve"). let line_tool = app.tool.as_ref().is_none_or(|t| t.cmd == "sketch.line"); - if best.is_none() + if !mid_only + && best.is_none() && line_tool && let Some(prev) = prev && let Some(i) = crate::inference::tangent(sk, prev, lp, tol) @@ -314,7 +370,7 @@ pub fn refine_snap( best = Some((i.dist, i.label(), i.at)); } // On a curve (coincident with it). - if best.is_none() { + if !mid_only && best.is_none() { for (i, c) in sk.curves.iter().enumerate() { let Some(sh) = sk.shape(i) else { continue }; let d = sh.dist(lp); @@ -325,7 +381,8 @@ pub fn refine_snap( } } } - if best.is_none() + if !mid_only + && best.is_none() && let Some(prev) = prev { let (dx, dy) = ((lp.x - prev.x).abs(), (lp.y - prev.y).abs()); @@ -339,7 +396,8 @@ pub fn refine_snap( } } // Line tool: parallel or perpendicular to a line, or on a line's extension. - if best.is_none() + if !mid_only + && best.is_none() && line_tool && let Some(prev) = prev && let Some(i) = crate::inference::lines(sk, prev, lp, tol) @@ -1205,7 +1263,10 @@ fn snap_hint(app: &SolveApp, painter: &egui::Painter, proj: &Proj) { /// Per frame, after the viewport is drawn: constraint glyphs, snap hints and analysis marks. pub fn show(app: &mut SolveApp, ui: &egui::Ui, painter: &egui::Painter, proj: &Proj) { - SHIFT.with(|c| c.set(ui.input(|i| i.modifiers.shift))); + // IsoCurveAlternate (Shift default) for sketch.isoparametric_curve - via resolve, not raw shift. + let held = crate::tool_modifiers::Held::from_modifiers(ui.input(|i| i.modifiers)); + let iso = crate::tool_modifiers::resolve(&[], crate::tool_modifiers::descriptor("sketch.isoparametric_curve"), held, Trigger::Press); + SHIFT.with(|c| c.set(iso.contains(ModAction::IsoCurveAlternate))); glyphs(app, painter, proj, ui.input(|i| i.pointer.hover_pos()).filter(|_| ui.rect_contains_pointer(proj.rect))); snap_hint(app, painter, proj); combs(app, painter, proj); diff --git a/crates/ui-egui/src/tool_modifiers.rs b/crates/ui-egui/src/tool_modifiers.rs new file mode 100644 index 000000000..10f0e3cba --- /dev/null +++ b/crates/ui-egui/src/tool_modifiers.rs @@ -0,0 +1,670 @@ +//! Centralised modifier-key binding types for sketch and selection behaviours. +//! +//! [`ModifierCombo`] is a serialisable set of modifier keys. Modifier state that +//! must cross the boundary between the viewport event-loop and rendering helpers +//! (gizmo, canvas) that do not carry `&SolveApp` is communicated through +//! per-frame thread-local flags — the same pattern as [`crate::drag_snap`] — +//! so that neither gizmo nor canvas needs access to application state. +//! +//! Strategy: bindings name a chord; call sites ask whether the chord matches the +//! held keys (`held` / `matches_exact`) instead of reading `Modifiers` fields +//! directly. Platform primary is Ctrl on Windows/Linux and Cmd on macOS; the +//! physical Ctrl key on macOS is never treated as primary. + +use std::cell::Cell; + +use egui::Modifiers; +use serde::{Deserialize, Serialize}; + +/// Runtime platform for labels and primary-key normalisation. +/// Prefer [`Platform::of`] over `cfg!(target_os)` so wasm on a Mac still says Cmd. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Platform { + Mac, + Other, +} + +impl Platform { + pub fn of(ctx: &egui::Context) -> Self { + match ctx.os() { + egui::os::OperatingSystem::Mac | egui::os::OperatingSystem::IOS => Self::Mac, + _ => Self::Other, + } + } + + /// Compile-time fallback for unit tests and call sites without a context. + pub fn host() -> Self { + if cfg!(target_os = "macos") { Self::Mac } else { Self::Other } + } +} + +/// Held keys, normalised for binding matches. +/// +/// `primary` is Ctrl on Windows/Linux and Cmd on macOS (`Modifiers::command`). +/// On macOS, physical Ctrl (`Modifiers::ctrl`) is `other` and never counts as primary. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub struct Held { + pub shift: bool, + pub primary: bool, + pub alt: bool, + /// A key no chord names (physical Ctrl on macOS). Fails exact matches. + pub other: bool, +} + +impl Held { + pub fn new(m: Modifiers, platform: Platform) -> Self { + // On Windows and Linux, Ctrl is primary even when an event sets only `ctrl` + // (`Modifiers::CTRL`). On macOS, primary is Command; physical Ctrl is a different key. + let primary = m.command || (platform != Platform::Mac && m.ctrl); + Self { shift: m.shift, primary, alt: m.alt, other: platform == Platform::Mac && m.ctrl && !m.command } + } + + /// Host-platform normalisation without an egui context (tests, prefs helpers). + pub fn from_modifiers(m: Modifiers) -> Self { + Self::new(m, Platform::host()) + } +} + +/// How a chord matches held keys. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Match { + /// Exactly these keys and no others. + Exact, + /// At least these keys; extras allowed. + AtLeast, +} + +/// A set of modifier keys for a binding. +/// +/// `ctrl` is the persisted field name for **primary** (Ctrl on Windows/Linux, Cmd on macOS). +/// Matching uses [`Held::primary`] (`Modifiers::command`), not physical Ctrl on macOS. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, Serialize, Deserialize)] +pub struct ModifierCombo { + pub shift: bool, + /// Primary: Ctrl (Windows/Linux) or Cmd (macOS). Serde key stays `ctrl` for prefs stability. + pub ctrl: bool, + pub alt: bool, +} + +impl ModifierCombo { + pub const NONE: Self = Self { shift: false, ctrl: false, alt: false }; + pub const SHIFT: Self = Self { shift: true, ctrl: false, alt: false }; + pub const CTRL: Self = Self { shift: false, ctrl: true, alt: false }; + pub const ALT: Self = Self { shift: false, ctrl: false, alt: true }; + pub const CTRL_ALT: Self = Self { shift: false, ctrl: true, alt: true }; + + pub const fn key_count(self) -> u8 { + self.shift as u8 + self.ctrl as u8 + self.alt as u8 + } + + pub fn matches(self, held: Held, how: Match) -> bool { + match how { + Match::Exact => !held.other && self.shift == held.shift && self.ctrl == held.primary && self.alt == held.alt, + Match::AtLeast => (!self.shift || held.shift) && (!self.ctrl || held.primary) && (!self.alt || held.alt), + } + } + + /// True if **exactly** these modifiers (and no others) are held. + pub fn matches_exact(self, m: Modifiers) -> bool { + self.matches(Held::from_modifiers(m), Match::Exact) + } + + /// True if **at least** these modifiers are held (subset / "held" match). + pub fn held(self, m: Modifiers) -> bool { + self.matches(Held::from_modifiers(m), Match::AtLeast) + } + + /// Human-readable display label for the host platform. + pub fn label(self) -> String { + self.label_for(Platform::host()) + } + + /// Human-readable display label for a specific platform. + pub fn label_for(self, platform: Platform) -> String { + // Classic default: either primary or Alt/Option suppresses snap. + if self == Self::CTRL_ALT { + return format!("{} or {}", ctrl_name_for(platform), alt_name_for(platform)); + } + let mut parts: Vec<&str> = Vec::new(); + if self.shift { + parts.push("Shift"); + } + if self.ctrl { + parts.push(ctrl_name_for(platform)); + } + if self.alt { + parts.push(alt_name_for(platform)); + } + if parts.is_empty() { + return "None".into(); + } + parts.join("+") + } + + /// Combos offered by the sketch snap-suppress picker (classic OR first). + pub const SNAP_SUPPRESS_CHOICES: [Self; 4] = [Self::CTRL_ALT, Self::CTRL, Self::ALT, Self::SHIFT]; + + /// All single-key combos, in display order (for a picker widget). + pub const SINGLE_KEYS: [Self; 3] = [Self::CTRL, Self::ALT, Self::SHIFT]; +} + +/// "Ctrl/Cmd" on Windows/Linux, "Cmd" on macOS. +pub fn ctrl_name() -> &'static str { + ctrl_name_for(Platform::host()) +} + +pub fn ctrl_name_for(platform: Platform) -> &'static str { + match platform { + Platform::Mac => "Cmd", + Platform::Other => "Ctrl/Cmd", + } +} + +/// "Alt" on Windows/Linux, "Option" on macOS. +pub fn alt_name() -> &'static str { + alt_name_for(Platform::host()) +} + +pub fn alt_name_for(platform: Platform) -> &'static str { + match platform { + Platform::Mac => "Option", + Platform::Other => "Alt", + } +} + +thread_local! { + /// Set once per frame from the viewport event-loop; read by gizmo and canvas + /// helpers that do not receive `&SolveApp`. Communicates whether the current + /// modifier state enables free (unsnapped) manipulator drags. + static MANIPULATOR_FREE: Cell = const { Cell::new(false) }; + /// Shift while sketching forces midpoint targeting (see [`ModAction::TargetMidpoint`]). + static TARGET_MIDPOINT: Cell = const { Cell::new(false) }; + /// True while a canvas / gizmo manipulator drag is active this frame (or last frame until cleared). + static MANIPULATOR_DRAGGING: Cell = const { Cell::new(false) }; +} + +/// Set whether manipulator drags are free (no snap) this frame. +/// +/// Call from the viewport *before* canvas / gizmo rendering, passing the result of +/// [`crate::prefs::manipulator_free_held`]. +pub fn set_manipulator_free(on: bool) { + MANIPULATOR_FREE.with(|c| c.set(on)); +} + +/// Whether manipulator drags are free this frame (set by [`set_manipulator_free`]). +pub fn manipulator_free() -> bool { + MANIPULATOR_FREE.with(Cell::get) +} + +/// Set whether sketch refine-snap should target midpoints only this frame. +pub fn set_target_midpoint(on: bool) { + TARGET_MIDPOINT.with(|c| c.set(on)); +} + +/// Whether sketch refine-snap is in midpoint-only mode. +pub fn target_midpoint() -> bool { + TARGET_MIDPOINT.with(Cell::get) +} + +/// Set whether a manipulator (arrow / gizmo) drag is active. +pub fn set_manipulator_dragging(on: bool) { + MANIPULATOR_DRAGGING.with(|c| c.set(on)); +} + +/// Whether a manipulator drag is active (see [`set_manipulator_dragging`]). +pub fn manipulator_dragging() -> bool { + MANIPULATOR_DRAGGING.with(Cell::get) +} + +/// Semantic modifier actions. `id()` is persisted in prefs: never rename one, only add. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[repr(u8)] +pub enum ModAction { + SuppressSnap = 0, + FreeManipulatorDrag = 1, + SelectToggle = 2, + SelectAdd = 3, + TargetMidpoint = 4, + Cycle3dSketchPlane = 5, + PreviewReselect = 6, + TextSingleLetter = 7, + TextHandleConstrain = 8, + IsoCurveAlternate = 9, +} + +impl ModAction { + pub const ALL: &'static [Self] = &[ + Self::SuppressSnap, + Self::FreeManipulatorDrag, + Self::SelectToggle, + Self::SelectAdd, + Self::TargetMidpoint, + Self::Cycle3dSketchPlane, + Self::PreviewReselect, + Self::TextSingleLetter, + Self::TextHandleConstrain, + Self::IsoCurveAlternate, + ]; + + pub const fn id(self) -> &'static str { + match self { + Self::SuppressSnap => "suppress_snap", + Self::FreeManipulatorDrag => "free_manipulator_drag", + Self::SelectToggle => "select_toggle", + Self::SelectAdd => "select_add", + Self::TargetMidpoint => "target_midpoint", + Self::Cycle3dSketchPlane => "cycle_3d_sketch_plane", + Self::PreviewReselect => "preview_reselect", + Self::TextSingleLetter => "text_single_letter", + Self::TextHandleConstrain => "text_handle_constrain", + Self::IsoCurveAlternate => "isocurve_alternate", + } + } + + pub fn from_id(id: &str) -> Option { + Self::ALL.iter().copied().find(|a| a.id() == id) + } + + pub const fn group(self) -> Option { + match self { + Self::SelectToggle | Self::SelectAdd => Some(Group::SelectionClick), + _ => None, + } + } +} + +/// Actions that cannot both apply to one gesture: the most specific matching chord wins. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Group { + SelectionClick, +} + +/// When a binding is sampled relative to a pointer gesture. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Trigger { + /// Re-evaluated every frame (snap suppression, free drag). + Live, + /// Sampled at primary press and latched until release (click selection). + Press, +} + +/// Whether a tool's modifier bindings have been reviewed. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Audit { + Unaudited, + /// No tool-specific bindings beyond inherited scopes. + VerifiedNoOp, + Implemented, + /// A behaviour was considered and deliberately left out. + Declined, +} + +/// One binding: an action, default chords, match mode, and rebind flag. +#[derive(Clone, Copy, Debug)] +pub struct Binding { + pub action: ModAction, + /// Any one of these activates the action; empty means off by default. + pub defaults: &'static [ModifierCombo], + pub matching: Match, + pub trigger: Trigger, + pub rebindable: bool, +} + +/// Bindings shared by every tool active in that context. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Scope { + Selection, + SketchDraw, + SketchDrag, + Manipulator, + /// Feature dialogs with a live preview (Primary can roll the preview back for reselect). + FeaturePreview, +} + +impl Scope { + pub const fn bindings(self) -> &'static [Binding] { + match self { + Self::Selection => SELECTION_BINDINGS, + Self::SketchDraw | Self::SketchDrag => SKETCH_SNAP_BINDINGS, + Self::Manipulator => MANIPULATOR_BINDINGS, + Self::FeaturePreview => FEATURE_PREVIEW_BINDINGS, + } + } +} + +const SELECTION_BINDINGS: &[Binding] = &[ + Binding { action: ModAction::SelectAdd, defaults: &[ModifierCombo::SHIFT], matching: Match::AtLeast, trigger: Trigger::Press, rebindable: true }, + Binding { + action: ModAction::SelectToggle, + defaults: &[ModifierCombo::CTRL], + matching: Match::AtLeast, + trigger: Trigger::Press, + rebindable: true, + }, +]; + +const SKETCH_SNAP_BINDINGS: &[Binding] = &[ + Binding { + action: ModAction::SuppressSnap, + // Classic SolidCraft: Ctrl/Cmd or Alt/Option each suppress snap. + defaults: &[ModifierCombo::CTRL, ModifierCombo::ALT], + matching: Match::AtLeast, + trigger: Trigger::Live, + rebindable: true, + }, + Binding { + // Shift while sketching / coincident targeting prefers a line midpoint. + action: ModAction::TargetMidpoint, + defaults: &[ModifierCombo::SHIFT], + matching: Match::AtLeast, + trigger: Trigger::Live, + rebindable: true, + }, +]; + +const MANIPULATOR_BINDINGS: &[Binding] = &[Binding { + action: ModAction::FreeManipulatorDrag, + defaults: &[ModifierCombo::CTRL, ModifierCombo::ALT], + matching: Match::AtLeast, + trigger: Trigger::Live, + rebindable: true, +}]; + +const FEATURE_PREVIEW_BINDINGS: &[Binding] = &[Binding { + // Hold Primary to roll the command preview back so obscured geometry can be (re)selected. + action: ModAction::PreviewReselect, + defaults: &[ModifierCombo::CTRL], + matching: Match::AtLeast, + trigger: Trigger::Live, + rebindable: true, +}]; + +/// One entry per interactive command id. +#[derive(Clone, Copy, Debug)] +pub struct ToolModifiers { + pub tool: &'static str, + pub scopes: &'static [Scope], + /// Overrides scope bindings for the same action. + pub bindings: &'static [Binding], + pub audit: Audit, +} + +/// Host slices filled by each tool module. +pub const HOSTS: &[&[ToolModifiers]] = + &[crate::tools::MODIFIERS, crate::sketch_tools::MODIFIERS, crate::sketch_modify_ui::MODIFIERS, crate::dialogs::MODIFIERS]; + +pub fn descriptor(tool: &str) -> Option<&'static ToolModifiers> { + HOSTS.iter().flat_map(|h| h.iter()).find(|t| t.tool == tool) +} + +/// Bit set of active [`ModAction`]s for the current frame or press. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct ActionSet(u64); + +impl ActionSet { + pub fn insert(&mut self, a: ModAction) { + self.0 |= 1 << (a as u8); + } + + pub fn contains(self, a: ModAction) -> bool { + self.0 & (1 << (a as u8)) != 0 + } +} + +/// Selection click flags from held modifiers and the shift-add-only preference. +/// +/// Returns `(add, allow_toggle)`. When `shift_add_only`, Shift is pure-add and Primary toggles. +pub fn selection_click(held: Held, shift_add_only: bool) -> (bool, bool) { + let actions = resolve(&[Scope::Selection], None, held, Trigger::Press); + let toggle = actions.contains(ModAction::SelectToggle); + let add = toggle || actions.contains(ModAction::SelectAdd); + let allow_toggle = if shift_add_only { toggle } else { add }; + (add, allow_toggle) +} + +/// Whether preview reselect should apply: Primary chord matched and no manipulator drag under way. +pub fn preview_reselect(held: Held, manipulator_dragging: bool) -> bool { + if manipulator_dragging { + return false; + } + resolve(&[Scope::FeaturePreview], None, held, Trigger::Live).contains(ModAction::PreviewReselect) +} + +/// Resolve which actions are active for `held` under the given scopes and optional tool. +pub fn resolve(context: &[Scope], tool: Option<&ToolModifiers>, held: Held, trigger: Trigger) -> ActionSet { + let mut set = ActionSet::default(); + let mut bindings: Vec<&Binding> = context.iter().flat_map(|s| s.bindings()).collect(); + if let Some(t) = tool { + for s in t.scopes { + bindings.extend(s.bindings()); + } + for b in t.bindings { + // Tool-specific bindings replace earlier ones with the same action. + bindings.retain(|x| x.action != b.action); + bindings.push(b); + } + } + // Most specific chord wins within a group. + let mut best_group: [Option<(u8, ModAction)>; 1] = [None]; + for b in bindings { + if b.trigger != trigger { + continue; + } + if b.defaults.is_empty() { + continue; + } + let matched = b.defaults.iter().any(|c| { + if matches!(b.matching, Match::AtLeast) && c.key_count() == 0 { + return false; + } + c.matches(held, b.matching) + }); + if !matched { + continue; + } + if let Some(g) = b.action.group() { + let idx = match g { + Group::SelectionClick => 0, + }; + let specificity = b.defaults.iter().map(|c| c.key_count()).max().unwrap_or(0); + match best_group[idx] { + Some((s, _)) if s > specificity => {} + Some((s, prev)) if s == specificity => { + // Tie: earlier ModAction::ALL order wins. + let prev_i = ModAction::ALL.iter().position(|a| *a == prev).unwrap_or(0); + let cur_i = ModAction::ALL.iter().position(|a| *a == b.action).unwrap_or(0); + if cur_i < prev_i { + best_group[idx] = Some((specificity, b.action)); + } + } + _ => best_group[idx] = Some((specificity, b.action)), + } + } else { + set.insert(b.action); + } + } + for slot in best_group.into_iter().flatten() { + set.insert(slot.1); + } + set +} + +#[cfg(test)] +mod tests { + use super::*; + + fn mods(shift: bool, ctrl: bool, alt: bool) -> Modifiers { + Modifiers { shift, ctrl, alt, command: ctrl, ..Default::default() } + } + + #[test] + fn exact_match_requires_no_extra_keys() { + let ctrl = ModifierCombo::CTRL; + assert!(ctrl.matches_exact(mods(false, true, false))); + assert!(!ctrl.matches_exact(mods(true, true, false)), "extra shift must fail"); + assert!(!ctrl.matches_exact(mods(false, false, false))); + } + + #[test] + fn held_match_allows_extra_keys() { + let ctrl = ModifierCombo::CTRL; + assert!(ctrl.held(mods(false, true, false))); + assert!(ctrl.held(mods(true, true, false)), "shift+ctrl is fine for a ctrl binding"); + assert!(!ctrl.held(mods(false, false, false))); + } + + #[test] + fn physical_ctrl_is_primary_off_mac() { + let ctrl_only = Modifiers::CTRL; + assert!(ModifierCombo::CTRL.matches(Held::new(ctrl_only, Platform::Other), Match::AtLeast)); + assert!(!ModifierCombo::CTRL.matches(Held::new(ctrl_only, Platform::Mac), Match::AtLeast)); + assert_eq!(selection_click(Held::new(ctrl_only, Platform::Other), false), (true, true)); + } + + #[test] + fn cmd_normalises_to_ctrl() { + let ctrl = ModifierCombo::CTRL; + let cmd_mods = Modifiers { command: true, ..Default::default() }; + assert!(ctrl.held(cmd_mods), "Cmd on macOS should match a ctrl binding"); + assert!(ctrl.matches_exact(cmd_mods), "exact match also normalises command"); + } + + #[test] + fn mac_physical_ctrl_is_not_primary() { + let ctrl = ModifierCombo::CTRL; + let physical = Modifiers { ctrl: true, command: false, ..Default::default() }; + let held = Held::new(physical, Platform::Mac); + assert!(!held.primary && held.other); + assert!(!ctrl.matches(held, Match::AtLeast)); + assert!(!ctrl.matches(held, Match::Exact)); + let win = Held::new(Modifiers { ctrl: true, command: true, ..Default::default() }, Platform::Other); + assert!(ctrl.matches(win, Match::AtLeast)); + } + + #[test] + fn label_formats_correctly() { + assert_eq!(ModifierCombo::CTRL.label_for(Platform::Other), "Ctrl/Cmd"); + assert_eq!(ModifierCombo::CTRL.label_for(Platform::Mac), "Cmd"); + assert_eq!(ModifierCombo::NONE.label_for(Platform::Other), "None"); + assert_eq!(ModifierCombo::CTRL_ALT.label_for(Platform::Other), "Ctrl/Cmd or Alt"); + assert_eq!(ModifierCombo::CTRL_ALT.label_for(Platform::Mac), "Cmd or Option"); + assert_eq!(ModifierCombo { shift: true, ctrl: true, alt: false }.label_for(Platform::Other), "Shift+Ctrl/Cmd"); + } + + #[test] + fn manipulator_free_thread_local_roundtrip() { + set_manipulator_free(true); + assert!(manipulator_free()); + set_manipulator_free(false); + assert!(!manipulator_free()); + } + + #[test] + fn target_midpoint_live_resolves_from_sketch_scopes() { + set_target_midpoint(false); + let shift = Held { shift: true, ..Default::default() }; + let set = resolve(&[Scope::SketchDraw], None, shift, Trigger::Live); + assert!(set.contains(ModAction::TargetMidpoint)); + assert!(!set.contains(ModAction::SuppressSnap)); + set_target_midpoint(true); + assert!(target_midpoint()); + set_target_midpoint(false); + assert!(!target_midpoint()); + } + + #[test] + fn preview_reselect_resolves_from_feature_preview_scope() { + let primary = Held { primary: true, ..Default::default() }; + let set = resolve(&[Scope::FeaturePreview], None, primary, Trigger::Live); + assert!(set.contains(ModAction::PreviewReselect)); + let press = resolve(&[Scope::FeaturePreview], None, primary, Trigger::Press); + assert!(!press.contains(ModAction::PreviewReselect)); + } + + #[test] + fn preview_reselect_skips_while_manipulator_dragging() { + let primary = Held { primary: true, ..Default::default() }; + assert!(preview_reselect(primary, false)); + assert!(!preview_reselect(primary, true), "Ctrl free-drag must not hide the preview"); + set_manipulator_dragging(true); + assert!(manipulator_dragging()); + set_manipulator_dragging(false); + assert!(!manipulator_dragging()); + } + + #[test] + fn selection_scope_resolves_shift_add_and_primary_toggle() { + let shift = Held { shift: true, ..Default::default() }; + let primary = Held { primary: true, ..Default::default() }; + let both = Held { shift: true, primary: true, ..Default::default() }; + let add = resolve(&[Scope::Selection], None, shift, Trigger::Press); + assert!(add.contains(ModAction::SelectAdd)); + assert!(!add.contains(ModAction::SelectToggle)); + let toggle = resolve(&[Scope::Selection], None, primary, Trigger::Press); + assert!(toggle.contains(ModAction::SelectToggle)); + assert!(!toggle.contains(ModAction::SelectAdd)); + // Shift+Primary: single-key tie → SelectToggle wins (earlier in ModAction::ALL). + let combo = resolve(&[Scope::Selection], None, both, Trigger::Press); + assert!(combo.contains(ModAction::SelectToggle)); + assert!(!combo.contains(ModAction::SelectAdd)); + } + + #[test] + fn selection_click_respects_shift_add_only_pref() { + let shift = Held { shift: true, ..Default::default() }; + let primary = Held { primary: true, ..Default::default() }; + assert_eq!(selection_click(shift, true), (true, false)); + assert_eq!(selection_click(shift, false), (true, true)); + assert_eq!(selection_click(primary, true), (true, true)); + assert_eq!(selection_click(Held::default(), true), (false, false)); + } + + #[test] + fn isocurve_shift_resolves_via_descriptor() { + let held = Held { shift: true, ..Default::default() }; + let set = resolve(&[], descriptor("sketch.isoparametric_curve"), held, Trigger::Press); + assert!(set.contains(ModAction::IsoCurveAlternate)); + let bare = resolve(&[], None, held, Trigger::Press); + assert!(!bare.contains(ModAction::IsoCurveAlternate)); + } + + #[test] + fn action_ids_are_unique() { + let mut seen = std::collections::BTreeSet::new(); + for a in ModAction::ALL { + assert!(seen.insert(a.id()), "duplicate id {}", a.id()); + assert_eq!(ModAction::from_id(a.id()), Some(*a)); + } + } + + #[test] + fn tools_host_covers_interactive_sketch_create_commands() { + for entry in crate::tools::MODIFIERS { + assert!(crate::tools::Tool::for_command(entry.tool).is_some(), "orphan descriptor {}", entry.tool); + assert_eq!(descriptor(entry.tool).map(|d| d.tool), Some(entry.tool)); + } + // Every command owned directly by tools.rs (not sketch_tools) has a descriptor. + for id in ["sketch.line", "sketch.rectangle.two_point", "sketch.circle.center", "sketch.constraint.coincident", "sketch.dimension"] { + assert!(descriptor(id).is_some(), "missing descriptor for {id}"); + } + } + + #[test] + fn hosts_have_unique_tool_ids_and_cover_seeded_commands() { + let mut seen = std::collections::BTreeSet::new(); + for entry in HOSTS.iter().flat_map(|h| h.iter()) { + assert!(seen.insert(entry.tool), "duplicate tool id {}", entry.tool); + } + for id in ["sketch.isoparametric_curve", "sketch.pattern.rectangular", "solid.pattern.circular", "solid.extrude", "sketch.move"] { + assert!(descriptor(id).is_some(), "missing descriptor for {id}"); + } + assert_eq!(descriptor("sketch.pattern.rectangular").unwrap().audit, Audit::VerifiedNoOp); + assert_eq!(descriptor("solid.pattern.circular").unwrap().audit, Audit::VerifiedNoOp); + assert_eq!(descriptor("sketch.isoparametric_curve").unwrap().audit, Audit::Implemented); + assert_eq!(descriptor("sketch.line").unwrap().audit, Audit::Implemented); + // Seeded hosts: no Unaudited leftovers once scopes are assigned. + for entry in HOSTS.iter().flat_map(|h| h.iter()) { + assert_ne!(entry.audit, Audit::Unaudited, "{} still Unaudited", entry.tool); + } + } +} diff --git a/crates/ui-egui/src/tools.rs b/crates/ui-egui/src/tools.rs index cd23fc7b6..e34e2068e 100644 --- a/crates/ui-egui/src/tools.rs +++ b/crates/ui-egui/src/tools.rs @@ -6,8 +6,44 @@ use serde_json::{Value, json}; use solidcraft_engine::geom::Vec2; use crate::SolveApp; +use crate::tool_modifiers::{Audit, Scope, ToolModifiers}; use crate::viewport::{Hit, Proj, pick, sketch_point_at}; +const DRAW_SCOPES: &[Scope] = &[Scope::SketchDraw, Scope::SketchDrag]; + +/// Per-tool modifier descriptors owned by this host file (coordinator seeds / audits these). +pub const MODIFIERS: &[ToolModifiers] = &[ + ToolModifiers { tool: "sketch.line", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.rectangle.two_point", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.rectangle.center", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.rectangle.rounded", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.rectangle.three_point", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.circle.center", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.circle.two_point", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.circle.three_point", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.arc.three_point", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.arc.center_point", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.polygon.inscribed", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.polygon.circumscribed", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.polygon.edge", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.slot.center_to_center", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.slot.overall", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.point", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + ToolModifiers { tool: "sketch.dimension", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented }, + // Constraint tools: pick-only; no tool-specific modifier chords. + ToolModifiers { tool: "sketch.constraint.horizontal_vertical", scopes: &[], bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.constraint.fix", scopes: &[], bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.constraint.coincident", scopes: &[], bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.constraint.tangent", scopes: &[], bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.constraint.equal", scopes: &[], bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.constraint.parallel", scopes: &[], bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.constraint.perpendicular", scopes: &[], bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.constraint.concentric", scopes: &[], bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.constraint.collinear", scopes: &[], bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.constraint.midpoint", scopes: &[], bindings: &[], audit: Audit::VerifiedNoOp }, + ToolModifiers { tool: "sketch.constraint.symmetry", scopes: &[], bindings: &[], audit: Audit::VerifiedNoOp }, +]; + #[cfg(test)] #[path = "sketch_display_preview_tests.rs"] mod display_preview_tests; diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 8ee4c5f44..8e3264ba4 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -311,7 +311,8 @@ fn scene_key(app: &SolveApp) -> u64 { app.ui.hidden_profiles.hash(&mut h); app.session.active_component.hash(&mut h); app.session.active_occurrence_path.hash(&mut h); - app.preview.replaced.hash(&mut h); + app.preview.effective_replaced().hash(&mut h); + app.preview.rolled_back.hash(&mut h); app.tree.redefine.hash(&mut h); crate::theme::is_dark().hash(&mut h); crate::theme::vision().hash(&mut h); @@ -501,7 +502,7 @@ fn update_refinement(app: &mut SolveApp, ctx: &egui::Context, proj: &Proj) { if b.name != *name || b.body.is_mesh() { continue; } - let shown = app.session.body_visible(&b.name) && !app.preview.replaced.contains(&b.name); + let shown = app.session.body_visible(&b.name) && !app.preview.effective_replaced().contains(&b.name); let on_screen = match screen_box(proj, bx, 0.0).filter(|_| shown) { Some(r) => r.intersects(proj.rect).then(|| f64::from(r.width().max(r.height())) * ppp), // A corner behind the eye: the view is inside or right by the box. @@ -649,7 +650,7 @@ fn build_scene(app: &SolveApp) -> GpuScene { let mut run: Vec = Vec::new(); let mut run_key = std::collections::hash_map::DefaultHasher::new(); for b in &st.bodies { - if !app.session.body_visible(&b.name) || app.preview.replaced.contains(&b.name) { + if !app.session.body_visible(&b.name) || app.preview.effective_replaced().contains(&b.name) { continue; } let faded = body_faded(app, b, &active_bodies); @@ -1480,7 +1481,7 @@ fn feature_geometry(app: &SolveApp, id: u64) -> Vec { let prefix = format!("F{id}:"); let mut out = Vec::new(); for b in &st.bodies { - if !app.session.body_visible(&b.name) || app.preview.replaced.contains(&b.name) { + if !app.session.body_visible(&b.name) || app.preview.effective_replaced().contains(&b.name) { continue; } if b.feature == id { @@ -1903,7 +1904,8 @@ fn highlight_geometry_key(app: &SolveApp) -> u64 { (app.dialog.is_some(), app.tool.is_some()).hash(&mut h); crate::theme::is_dark().hash(&mut h); crate::theme::vision().hash(&mut h); - app.preview.replaced.hash(&mut h); + app.preview.effective_replaced().hash(&mut h); + app.preview.rolled_back.hash(&mut h); app.origin_visible().hash(&mut h); app.picking_sketch_plane().hash(&mut h); app.session.visibility.hidden_origin.hash(&mut h); @@ -2033,7 +2035,7 @@ fn build_highlight(app: &SolveApp) -> GpuScene { match x { Sel::Face { body, index, .. } => { // A live preview stands in for the body: its old faces would fight with it. - if let Some(b) = st.body(body).filter(|_| app.session.body_visible(body) && !app.preview.replaced.contains(body)) { + if let Some(b) = st.body(body).filter(|_| app.session.body_visible(body) && !app.preview.effective_replaced().contains(body)) { face_tris(&mut feedback, &shown(b), *index, c4(t.sel_face), false); hidden_face_outline(&mut feedback, &drawn_mesh(app, b), *index, t.sel_edge); } @@ -2096,7 +2098,7 @@ fn build_highlight(app: &SolveApp) -> GpuScene { // Timeline modifiers light only their resulting faces; browser rows light whole bodies. let mut hovered = app.viewport.hover_feature.map(|id| feature_geometry(app, id)).unwrap_or_default(); hovered.extend(app.viewport.hover_bodies.iter().map(|name| Sel::Body { name: name.clone() })); - for b in st.bodies.iter().filter(|b| app.session.body_visible(&b.name) && !app.preview.replaced.contains(&b.name)) { + for b in st.bodies.iter().filter(|b| app.session.body_visible(&b.name) && !app.preview.effective_replaced().contains(&b.name)) { let whole = hovered.iter().any(|x| matches!(x, Sel::Body { name } if name == &b.name)); let faces: Vec<_> = if whole { (0..b.body.face_count()).collect() @@ -2156,7 +2158,7 @@ fn build_highlight(app: &SolveApp) -> GpuScene { } } Some(Hit::Face { body, index, .. }) - if !app.preview.replaced.contains(body) + if !app.preview.effective_replaced().contains(body) && !sel.iter().any(|x| matches!(x, Sel::Face { body: b, index: i, .. } if b == body && i == index)) => { if let Some(b) = st.body(body) { @@ -2290,6 +2292,14 @@ pub fn delete_selection(app: &mut SolveApp) { crate::delete::delete_selection(app); } +/// Whether Primary should hide the live command preview so obscured geometry can be reselected. +/// +/// Shared by [`show`] so tests can lock the same path: a manipulator drag never rolls the +/// preview back, even when Primary (preview-reselect) is held. +pub(crate) fn preview_should_roll_back(app: &SolveApp, held: crate::tool_modifiers::Held, manipulator_dragging: bool) -> bool { + app.dialog.as_ref().is_some_and(|d| d.previews()) && app.preview.active && crate::tool_modifiers::preview_reselect(held, manipulator_dragging) +} + pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { let t = Tokens::get(); let rect = ui.max_rect(); @@ -2319,6 +2329,28 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { mode, } = input; app.viewport.physical_scale = ui.ctx().pixels_per_point(); + // Suppress-snap chord and manipulator-free prefs; Shift midpoint targeting while sketching. + // Preview reselect uses Primary but is skipped while a manipulator drag is under way. + crate::drag_snap::set_suppressed(crate::prefs::suppress_sketch_snap_held(app, mods)); + crate::tool_modifiers::set_manipulator_free(crate::prefs::manipulator_free_held(app, mods)); + let manipulator_dragging = crate::tool_modifiers::manipulator_dragging(); + crate::tool_modifiers::set_manipulator_dragging(false); + { + let held = crate::tool_modifiers::Held::from_modifiers(mods); + let mid = if let Some(cmd) = app.tool.as_ref().map(|t| t.cmd) { + let live = crate::tool_modifiers::resolve( + &[crate::tool_modifiers::Scope::SketchDraw, crate::tool_modifiers::Scope::SketchDrag], + crate::tool_modifiers::descriptor(cmd), + held, + crate::tool_modifiers::Trigger::Live, + ); + live.contains(crate::tool_modifiers::ModAction::TargetMidpoint) + } else { + false + }; + crate::tool_modifiers::set_target_midpoint(mid); + app.preview.rolled_back = preview_should_roll_back(app, held, manipulator_dragging); + } let proj = projection(app, rect); if let Ok(mut cache) = app.viewport.display.lock() { cache.prepare(app.session.world_state(), &proj, app.viewport.pixels_per_point()); @@ -2412,6 +2444,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { hl_slot: app.viewport.hl_slot.clone(), pv_key: app.preview.key, pv_slot: app.preview.slot.clone(), + pv_hide: app.preview.rolled_back, clip: section_clip(app), cap: t.section_cap.to_normalized_gamma_f32(), view_proj: proj.vp.to_f32(), @@ -2455,7 +2488,9 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { crate::tools::on_hover(app, &proj, p); } } - let add = mods.shift || mods.command || mods.ctrl; + // Selection chords via resolve (add-only Shift is a preference; default both toggle). + let held_mods = crate::tool_modifiers::Held::from_modifiers(mods); + let (add, allow_toggle) = crate::tool_modifiers::selection_click(held_mods, app.preferences.selection_shift_add_only); crate::sketch_text::set_one_letter(mods.shift); if let Some(p) = hover.filter(|_| inside) { if app.tool.is_some() { @@ -2509,13 +2544,13 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { // A text's resize or rotation handle: the text stays selected. } else if !crate::sketch3d::click(app, &proj, p) { match on_dim.or(on_glyph) { - Some(id) => select(app, Some(Sel::SketchConstraint { id }), add), + Some(id) => select(app, Some(Sel::SketchConstraint { id }), add, allow_toggle), // Clicking again on the same spot selects the next thing under it (not // the second click of a double-click, which has its own actions). None if !add && !resp.double_clicked() && crate::select_other::cycle_click(app, &proj, p) => {} None => { let sel = cand.and_then(|c| c.1); - select(app, sel.clone(), add); + select(app, sel.clone(), add, allow_toggle); crate::select_other::note_click(app, p, if add { None } else { sel }); } } @@ -2843,9 +2878,13 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { } } -/// A click without a command: select the candidate (replacing the selection, or toggling it -/// in with Shift/Ctrl); a click on nothing clears. -pub(crate) fn select(app: &mut SolveApp, sel: Option, add: bool) { +/// A click without a command: select the candidate (replacing the selection, or adding / +/// toggling with modifiers); a click on nothing clears. +/// +/// `toggle`: whether already-selected items may be removed by this click (Ctrl/Cmd held). +/// When `add` is true but `toggle` is false (Shift add-only preference), picked items +/// are only added. +pub(crate) fn select(app: &mut SolveApp, sel: Option, add: bool, toggle: bool) { if !add { // A joint picked in the browser (highlighted even when hidden) lets go. app.tree.picked_joints.clear(); @@ -2853,7 +2892,8 @@ pub(crate) fn select(app: &mut SolveApp, sel: Option, add: bool) { match sel { Some(x) => { let items = picked_selection(&app.session, &x); - if add && items.iter().all(|x| app.session.selection.iter().any(|y| crate::selection::same_item(x, y))) { + // Toggle-removal: all picked items are already selected and toggle is allowed. + if add && toggle && items.iter().all(|x| app.session.selection.iter().any(|y| crate::selection::same_item(x, y))) { let rest: Vec = app.session.selection.iter().filter(|y| !items.iter().any(|x| crate::selection::same_item(x, y))).cloned().collect(); let _ = app.run("select.set", json!({ "items": rest })); @@ -5238,12 +5278,12 @@ mod tests { app.viewport.hover = Some(Hit::Edge { body: b.name.clone(), index: i, mid }); assert_eq!(build_highlight(&app).merged().lines.len(), 2 * line_count * crate::gpu::LINE_SIZE); let item = hit_sel(app.viewport.hover.as_ref().unwrap()).unwrap(); - select(&mut app, Some(item.clone()), false); + select(&mut app, Some(item.clone()), false, false); assert_eq!(app.session.selection.len(), 2); // Selecting both pieces must not draw each highlight twice. assert_eq!(build_highlight(&app).merged().lines.len(), 2 * line_count * crate::gpu::LINE_SIZE); // Ctrl/Shift clicking either half deselects the entire rim. - select(&mut app, Some(item.clone()), true); + select(&mut app, Some(item.clone()), true, true); assert!(app.session.selection.is_empty()); let mut d = crate::dialogs::Dialog::for_command(&app, "solid.chamfer").unwrap(); if let crate::dialogs::Kind::Fillet { chain, .. } = &mut d.kind { @@ -5287,7 +5327,7 @@ mod tests { app.viewport.hover = Some(Hit::Face { body: b.name.clone(), index, point }); assert_eq!(build_highlight(&app).merged().tris.len(), triangle_count * 3 * crate::gpu::TRI_SIZE); let item = hit_sel(app.viewport.hover.as_ref().unwrap()).unwrap(); - select(&mut app, Some(item.clone()), false); + select(&mut app, Some(item.clone()), false, false); assert_eq!(app.session.selection.len(), 2); assert_eq!(build_highlight(&app).merged().tris.len(), triangle_count * 3 * crate::gpu::TRI_SIZE); assert_eq!(app.session.selection.first(), Some(&item), "keep the original tool placement point first"); @@ -5299,7 +5339,7 @@ mod tests { assert_eq!(dialog.items().len(), 2); // A point elsewhere on the opposite half still toggles the whole surface off. let other = faces.iter().find(|&&x| x != f).unwrap(); - select(&mut app, Some(Sel::Face { body: b.name.clone(), index: *other as usize, point: m.positions[0] }), true); + select(&mut app, Some(Sel::Face { body: b.name.clone(), index: *other as usize, point: m.positions[0] }), true, true); assert!(app.session.selection.is_empty()); } // Planar caps and box corners stay separate. @@ -6436,4 +6476,21 @@ mod grid_plane_tests { let sc = build_highlight(&app); assert!(sc.xray.is_empty() && !sc.guide_trans.is_empty(), "outside Create Sketch the planes are depth-tested"); } + + /// Primary rolls a live preview back for reselect, but not while a manipulator is dragged + /// (same gate [`show`] uses via [`preview_should_roll_back`]). + #[test] + fn preview_rollback_stays_off_while_manipulator_dragging() { + let mut s = solidcraft_engine::Session::default(); + s.execute("sketch.create", &json!({"plane": "xy"})).unwrap(); + s.execute("sketch.line", &json!({"points": [[0, 0], [20, 0]]})).unwrap(); + s.execute("sketch.finish", &json!({})).unwrap(); + let mut app = SolveApp::new(s, crate::Services::default()); + app.dialog = crate::dialogs::Dialog::for_command(&app, "solid.extrude"); + assert!(app.dialog.as_ref().is_some_and(|d| d.previews()), "extrude opens a preview dialog"); + app.preview.active = true; + let primary = crate::tool_modifiers::Held { primary: true, ..Default::default() }; + assert!(preview_should_roll_back(&app, primary, false), "Primary alone rolls the preview back when a preview dialog is open"); + assert!(!preview_should_roll_back(&app, primary, true), "Primary must not roll the preview back while a manipulator arrow is dragged"); + } } diff --git a/docs/book/src/guide/shortcuts.md b/docs/book/src/guide/shortcuts.md index 9b937313b..65c928af9 100644 --- a/docs/book/src/guide/shortcuts.md +++ b/docs/book/src/guide/shortcuts.md @@ -50,3 +50,15 @@ With the **Touchpad** navigation preset, hold **Shift** while moving the pointer **Alt/Option** to orbit, without pressing a mouse button. Vertical scrolling zooms. These viewport gestures are separate from rebindable command shortcuts; mouse-button selection and editing keep their existing modifiers. + +### Sketch modifiers + +While drawing or dragging a sketch point: + +| Keys | Action | +|---|---| +| Ctrl/Cmd or Alt/Option (default) | suppress auto-snap for that gesture | +| Shift | prefer a line midpoint when targeting | + +Change the snap-suppress chord in Preferences › Sketch. Selection still uses Shift and +Ctrl/Cmd to add or toggle (Preferences › Selection can make Shift add-only). diff --git a/docs/book/src/guide/ui-tour.md b/docs/book/src/guide/ui-tour.md index c407e9561..ea8ff9c88 100644 --- a/docs/book/src/guide/ui-tour.md +++ b/docs/book/src/guide/ui-tour.md @@ -16,7 +16,7 @@ origin, bodies, sketches, construction planes, canvases, joints and components. The eye shows or hides an item, a component's radio button makes it the active component, and right-clicking any row gives that item's menu. Rows drag into groups and other components. -- **Viewport.** Click to select, Shift or Ctrl to add, drag for a window or crossing box. To +- **Viewport.** Click to select, Shift or Ctrl to add (Preferences › Selection), drag for a window or crossing box. While sketching, Ctrl/Cmd or Alt/Option suppress auto-snap by default; Shift prefers a midpoint. To reach something under something else (two lines drawn on top of each other, coincident points, an edge in front of a face, overlapping bodies), hold the left button still for half a second (long-press on a touch screen) or right-click › **Select Other…**: a list of everything under From 99d8d382b98370e44557bf78e8f7b675da45c0a6 Mon Sep 17 00:00:00 2001 From: NOWN-DEV <257771410+NOWN-DEV@users.noreply.github.com> Date: Mon, 19 Oct 2026 22:04:39 +0200 Subject: [PATCH 073/225] Bill of materials: part properties on components and assembly.bom (#1888) (#1899) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Bill of materials: part properties on components and assembly.bom A component definition now carries part properties (part number, description, revision, other tools' keys) and free text properties, saved with the component and shared by its occurrences. component.metadata and component.metadata.set read and change them in one undo step; Paste New copies them; parts.insert numbers standard parts from their standard and size, and parts.resize renumbers them. assembly.bom counts the placed components (flat: parts at any depth through their subassemblies; top: direct children), grouped by part number or by definition, sorted by part number, and writes CSV (fixed, quoted columns) or JSON. The app gets a Bill of Materials window on the INSPECT panel that lists, edits and exports the rows. Co-Authored-By: Claude Opus 5.5 (1M context) * Bill of materials: name a merged row's equal definitions once Two standard parts with the same size are separate definitions with the same name; their row now reads "SHCS M6x20" instead of repeating it. Co-Authored-By: Claude Opus 5.5 (1M context) * Window widths test: close the Bill of Materials window between commands The test closes the floating windows a command opens before starting the next one; the Bill of Materials window was left open and measured against the next dialogs' limits. Co-Authored-By: Claude Opus 5.5 (1M context) * Bill of materials: sub-parts in their part's row, and part properties without re-evaluating assembly.bom takes group_children: true. A part with a part number keeps what is placed inside it (a bolt's washer and nut) in its own row, listed under it as children (items 1.1, 1.2, with each and count) instead of rows of their own; bolts with different contents stay different rows, and total_occurrences is the same either way. The window has a switch for it and shows the children under their part; the CSV lists them after their row. Changing part properties re-evaluated the model, re-seated every joint and rebuilt the placed model: 361 ms per change with 30 jointed bolts. A change that only touches components' metadata and properties now takes the same path as a render-only change (proved on the whole Document), also for its undo and redo: 0.6 ms. Co-Authored-By: Claude Opus 5.5 (1M context) * Bill of materials: look the structure up once, not per subassembly Deciding whether a subassembly is a part (it has bodies of its own) scanned every body of the model for each subassembly, and each body looked up its feature by a linear search of the timeline: subassemblies × bodies × features. assembly.bom now indexes the placements, the body owners (Document::body_owners: one pass over the bodies with the timeline in a map, the same rule as model_body_component) and the numbered components once per call. 600 bodies and features with 60 subassemblies: 8.1 ms → 1.3 ms; the old cost grows with the cube of the design's size. Co-Authored-By: Claude Opus 5.5 (1M context) --------- Co-authored-by: Claude Opus 5.5 (1M context) Co-authored-by: bherbruck --- assets/icons/ui/design/aliases.toml | 1 + assets/locales/en.json | 3 + assets/locales/ja.json | 3 + assets/locales/zh.json | 3 + crates/doc/src/document.rs | 46 +- .../src/format/pending/component-metadata.rs | 5 + crates/engine/src/cmd/bom.rs | 423 ++++++++++++++++++ crates/engine/src/cmd/bom_tests.rs | 277 ++++++++++++ crates/engine/src/cmd/component_clone.rs | 5 + crates/engine/src/cmd/mod.rs | 2 + crates/engine/src/cmd/parts.rs | 42 ++ .../engine/src/cmd/sketch_3d_frame_tests.rs | 2 +- crates/engine/src/cmd/urdf_tests.rs | 11 +- crates/engine/src/lib.rs | 7 +- crates/ui-egui/src/bom_panel.rs | 224 ++++++++++ crates/ui-egui/src/documents.rs | 1 + crates/ui-egui/src/lib.rs | 9 + crates/ui-egui/tests/window_widths.rs | 1 + docs/book/src/guide/assemblies.md | 38 ++ 19 files changed, 1095 insertions(+), 8 deletions(-) create mode 100644 crates/doc/src/format/pending/component-metadata.rs create mode 100644 crates/engine/src/cmd/bom.rs create mode 100644 crates/engine/src/cmd/bom_tests.rs create mode 100644 crates/ui-egui/src/bom_panel.rs diff --git a/assets/icons/ui/design/aliases.toml b/assets/icons/ui/design/aliases.toml index ef3fbb24a..f3443077c 100644 --- a/assets/icons/ui/design/aliases.toml +++ b/assets/icons/ui/design/aliases.toml @@ -35,3 +35,4 @@ sketch_scale = { master = "scale", accent = "sketch" } sketch_text = { master = "text", accent = "sketch" } surface_fair = { master = "spline_cv", accent = "surface" } mesh_export = { master = "export", accent = "mesh" } +bom = "list" diff --git a/assets/locales/en.json b/assets/locales/en.json index aff0a26e6..0e7e3226c 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -333,6 +333,7 @@ "cmd.appearance_assign": "Appearance", "cmd.appearance_library": "Appearance Library", "cmd.appearance_list": "List Appearances", + "cmd.assembly_bom": "Bill of Materials", "cmd.body_rename": "Rename Body", "cmd.browser_group": "New Group", "cmd.browser_move": "Move Browser Items", @@ -354,6 +355,8 @@ "cmd.component_insert_design": "Insert Design", "cmd.component_links": "List Links", "cmd.component_list": "List Components", + "cmd.component_metadata": "Part Properties", + "cmd.component_metadata_set": "Change Part Properties", "cmd.component_move_bodies": "Move Bodies to Component", "cmd.component_move_sketches": "Move Sketches to Component", "cmd.component_paste_new": "Paste New", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 205309ba6..f1f4ac468 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -333,6 +333,7 @@ "cmd.appearance_assign": "外観", "cmd.appearance_library": "外観ライブラリ", "cmd.appearance_list": "外観を一覧表示", + "cmd.assembly_bom": "部品表", "cmd.body_rename": "ボディの名前を変更", "cmd.browser_group": "新規グループ", "cmd.browser_move": "ブラウザ項目を移動", @@ -354,6 +355,8 @@ "cmd.component_insert_design": "デザインを挿入", "cmd.component_links": "リンクを一覧表示", "cmd.component_list": "コンポーネントを一覧表示", + "cmd.component_metadata": "部品プロパティ", + "cmd.component_metadata_set": "部品プロパティを変更", "cmd.component_move_bodies": "ボディをコンポーネントに移動", "cmd.component_move_sketches": "スケッチをコンポーネントに移動", "cmd.component_paste_new": "新規として貼り付け", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index c5181f0ec..7298363f4 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -333,6 +333,7 @@ "cmd.appearance_assign": "外观", "cmd.appearance_library": "外观库", "cmd.appearance_list": "列出外观", + "cmd.assembly_bom": "物料清单", "cmd.body_rename": "重命名实体", "cmd.browser_group": "新建组", "cmd.browser_move": "移动浏览器项目", @@ -354,6 +355,8 @@ "cmd.component_insert_design": "插入设计", "cmd.component_links": "列出链接", "cmd.component_list": "列出组件", + "cmd.component_metadata": "零件属性", + "cmd.component_metadata_set": "更改零件属性", "cmd.component_move_bodies": "将实体移至组件", "cmd.component_move_sketches": "将草图移至组件", "cmd.component_paste_new": "粘贴为新对象", diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 1ec44993b..34bae024e 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -1852,13 +1852,21 @@ pub struct SketchPoints { /// A component: a node of the design tree that owns sketches, features and bodies. The root /// (id 0) is the design itself and is not stored. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct Component { pub id: u64, pub name: String, /// Parent component (0 = the root). #[serde(default)] pub parent: u64, + /// The definition's part properties (part number, description, revision…) and other tools' + /// data, under the same rules as the design's own `metadata`. Every occurrence shares them; + /// the bill of materials reads them. + #[serde(default, skip_serializing_if = "crate::Metadata::is_empty")] + pub metadata: crate::Metadata, + /// Free text properties of the definition (material grade, finish, supplier…), by name. + #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")] + pub properties: std::collections::BTreeMap, } /// One loft section: profiles of a sketch. @@ -2622,6 +2630,23 @@ impl Document { *self == normalized } + /// Only components' part properties (metadata and free properties) changed: nothing to + /// evaluate. The same whole-Document proof as [`Document::differs_only_in_render`]. + pub fn differs_only_in_part_properties(&self, previous: &Document) -> bool { + if self.components.len() != previous.components.len() + || self.components.iter().zip(&previous.components).any(|(a, b)| a.id != b.id) + || self.components == previous.components + { + return false; + } + let mut normalized = previous.clone(); + for (n, c) in normalized.components.iter_mut().zip(&self.components) { + n.metadata = c.metadata.clone(); + n.properties = c.properties.clone(); + } + *self == normalized + } + /// The colour a body is shown and exported in (sRGB as 0–1 fractions): its appearance, /// else its component's, else its material's look, else the colour it was imported with. /// (Faces may have their own: `face_looks`.) @@ -2720,6 +2745,23 @@ impl Document { if body.transferred || body.source_name.is_some() { body.component } else { self.legacy_body_component(&body.name, body.feature) } } + /// The components that own a body in `state` ([`Document::model_body_component`] of each), + /// in one pass: the timeline is looked up once, not once per body. + pub fn body_owners(&self, state: &crate::ModelState) -> std::collections::HashSet { + let features: std::collections::HashMap = self.features.iter().rev().map(|f| (f.id, f.component)).collect(); + state + .bodies + .iter() + .map(|b| { + if b.transferred || b.source_name.is_some() { + b.component + } else { + self.body_components.get(&b.name).copied().unwrap_or_else(|| features.get(&b.feature).copied().unwrap_or(0)) + } + }) + .collect() + } + /// Recorded transfers already converted geometry into the new local frame. pub fn model_body_offset(&self, body: &crate::ModelBody) -> Option<&crate::Mat> { if body.transferred { None } else { self.body_offsets.get(&body.name) } @@ -2745,7 +2787,7 @@ impl Document { format!("Component{k}") } }; - self.components.push(Component { id, name, parent }); + self.components.push(Component { id, name, parent, ..Default::default() }); self.add_occurrence(id, parent, crate::IDENTITY)?; Ok(id) } diff --git a/crates/doc/src/format/pending/component-metadata.rs b/crates/doc/src/format/pending/component-metadata.rs new file mode 100644 index 000000000..e8b82ecab --- /dev/null +++ b/crates/doc/src/format/pending/component-metadata.rs @@ -0,0 +1,5 @@ +//! A component can carry its own part properties: `metadata` (`part_number`, `description`, +//! `revision`… and other tools' reverse-DNS keys, under the rules of the design's own `metadata`) +//! and `properties` (free text, by name), which every occurrence shares and the bill of materials +//! (`assembly.bom`) reads. Older designs need no transformation: a component without them has none. +//! The last release asks for an update instead of dropping them on save. diff --git a/crates/engine/src/cmd/bom.rs b/crates/engine/src/cmd/bom.rs new file mode 100644 index 000000000..e23f7dc43 --- /dev/null +++ b/crates/engine/src/cmd/bom.rs @@ -0,0 +1,423 @@ +//! Part properties and the bill of materials. `component.metadata` and +//! `component.metadata.set` read and change a component definition's part number, description, +//! revision and free properties (shared by every occurrence, saved with the component); +//! `assembly.bom` counts the placed components of the design, or of one component, and lists +//! them as rows, optionally written to a CSV or JSON file. With `group_children`, a part with a +//! part number keeps the parts placed inside it (a bolt's washers and nut) in its own row. + +use std::collections::{BTreeMap, HashSet}; + +use serde_json::{Map, Value, json}; +use solidcraft_doc::metadata::{DESCRIPTION, MAX_KEYS, MAX_TEXT_BYTES, PART_NUMBER, REVISION, WELL_KNOWN}; + +use super::CommandSpec; +use crate::params::{bad, str_}; +use crate::{EngineError, Result, Session}; + +pub static COMMANDS: &[CommandSpec] = &[ + CommandSpec::new("component.metadata", "Part Properties", read).icon("settings").noundo().doc_only().params( + "component: id or name (0 or \"root\": the design's own properties) → component, name, part_number, description, revision, \ + metadata (as saved, other tools' keys too), properties: {name: text}", + ), + CommandSpec::new("component.metadata.set", "Change Part Properties", set).icon("settings").doc_only().params( + "component: id or name (not the root: use document.metadata.set); part_number?, description?, revision?: text (empty or null \ + removes); values?: {key: value} (SolidCraft's keys project, part_number, revision, author, organization, description, \ + license, or a reverse-DNS key holding an object); properties?: {name: text, …} (free properties; empty or null removes). \ + All or nothing, one undo step → component, metadata, properties, changed: [keys]", + ), + CommandSpec::new("assembly.bom", "Bill of Materials", bom).at("SOLID", "INSPECT").icon("bom").noundo().params( + "component?: id or name (default the design); levels?: flat (default: every part at any depth, counted through its \ + subassemblies) | top (the component's direct children, subassemblies as one row each); group_by?: [\"part_number\"] \ + (default; components without a part number get a row per definition) | [\"definition\"]; group_children?: true (a component \ + with a part number is one row, the parts placed inside it listed under it as children: [{item, part_number, description, \ + revision, each, count, definition}], not as rows of their own); path?: write a .csv or .json file (children as items 1.1, \ + 1.2…); format?: csv|json (default from the path) → rows: [{item, part_number, description, revision, count, definition, \ + components, properties, children?}] sorted by part number, total_occurrences (children included)", + ), +]; + +/// Longest free property name, in bytes. +const MAX_PROPERTY_NAME_BYTES: usize = 128; +/// How deep, and over how many placements, the bill of materials walks. +const MAX_DEPTH: usize = 64; +const MAX_PLACEMENTS: usize = 100_000; + +fn key(v: Option<&Value>) -> Option { + match v { + Some(Value::Number(n)) => Some(n.to_string()), + Some(Value::String(s)) => Some(s.clone()), + _ => None, + } +} + +fn component_id(s: &Session, p: &Value, cmd: &str) -> Result { + let k = key(p.get("component")).ok_or_else(|| bad(cmd, "`component` must be a component id or name"))?; + s.doc.find_component(&k).ok_or_else(|| bad(cmd, format!("no component `{k}`"))) +} + +fn read(s: &mut Session, p: &Value) -> Result { + let cmd = "component.metadata"; + let id = component_id(s, p, cmd)?; + if id == 0 { + let m = &s.doc.metadata; + return Ok(json!({"component": 0, "name": s.doc.name, "part_number": m.part_number(), "description": m.description(), + "revision": m.revision(), "metadata": m, "properties": {}})); + } + let c = s.doc.components.iter().find(|c| c.id == id).ok_or_else(|| bad(cmd, format!("no component `{id}`")))?; + let m = &c.metadata; + Ok(json!({"component": id, "name": c.name, "part_number": m.part_number(), "description": m.description(), + "revision": m.revision(), "metadata": m, "properties": c.properties})) +} + +/// A free property as it may be saved (`None`: remove it), or why not. +fn property(name: &str, value: &Value, cmd: &str) -> Result> { + let shown: String = name.chars().take(64).collect(); + if name.trim().is_empty() || name.len() > MAX_PROPERTY_NAME_BYTES || name.chars().any(char::is_control) { + return Err(bad(cmd, format!("property name `{shown}` must be 1…{MAX_PROPERTY_NAME_BYTES} bytes of text without control characters"))); + } + let text = match value { + Value::Null => return Ok(None), + Value::String(t) if t.is_empty() => return Ok(None), + Value::String(t) => t.clone(), + Value::Number(n) => n.to_string(), + Value::Bool(b) => b.to_string(), + _ => return Err(bad(cmd, format!("property `{shown}` takes text"))), + }; + if text.len() > MAX_TEXT_BYTES { + return Err(bad(cmd, format!("property `{shown}` is longer than {MAX_TEXT_BYTES} bytes"))); + } + if text.chars().any(|c| c.is_control() && !matches!(c, '\n' | '\t' | '\r')) { + return Err(bad(cmd, format!("property `{shown}` has a control character"))); + } + Ok(Some(text)) +} + +fn set(s: &mut Session, p: &Value) -> Result { + let cmd = "component.metadata.set"; + let id = component_id(s, p, cmd)?; + if id == 0 { + return Err(bad(cmd, "the root is the design: its properties are document.metadata.set's")); + } + let c = s.doc.components.iter().find(|c| c.id == id).ok_or_else(|| bad(cmd, format!("no component `{id}`")))?; + let (mut metadata, mut properties) = (c.metadata.clone(), c.properties.clone()); + let mut entries: Vec<(String, Value)> = Vec::new(); + match p.get("values") { + None => {} + Some(Value::Object(v)) if v.len() <= MAX_KEYS => entries.extend(v.iter().map(|(k, v)| (k.clone(), v.clone()))), + Some(Value::Object(_)) => return Err(bad(cmd, format!("`values` can hold at most {MAX_KEYS} keys"))), + Some(_) => return Err(bad(cmd, "`values` must be an object: {key: value, …}")), + } + for k in [PART_NUMBER, DESCRIPTION, REVISION] { + if let Some(v) = p.get(k) { + entries.push((k.to_string(), v.clone())); + } + } + let props: Vec<(&String, &Value)> = match p.get("properties") { + None => Vec::new(), + Some(Value::Object(v)) if v.len() <= MAX_KEYS => v.iter().collect(), + Some(Value::Object(_)) => return Err(bad(cmd, format!("`properties` can hold at most {MAX_KEYS} names"))), + Some(_) => return Err(bad(cmd, "`properties` must be an object: {name: text, …}")), + }; + if entries.is_empty() && props.is_empty() { + return Err(bad(cmd, format!("give part_number, description, revision, values or properties ({})", WELL_KNOWN.join(", ")))); + } + let mut changed: Vec = Vec::new(); + for (k, v) in entries { + if metadata.set(&k, v).map_err(|e| bad(cmd, e.to_string()))? && !changed.contains(&k) { + changed.push(k); + } + } + for (name, value) in props { + let was = properties.get(name).cloned(); + match property(name, value, cmd)? { + Some(text) => { + properties.insert(name.clone(), text); + } + None => { + properties.remove(name); + } + } + if properties.get(name) != was.as_ref() { + changed.push(format!("properties.{name}")); + } + } + if properties.len() > MAX_KEYS { + return Err(bad(cmd, format!("a component holds at most {MAX_KEYS} properties"))); + } + // Only a real change touches the design (an undo step, unsaved changes). + if !changed.is_empty() + && let Some(c) = s.doc_mut().components.iter_mut().find(|c| c.id == id) + { + c.metadata = metadata; + c.properties = properties; + } + let c = s.doc.components.iter().find(|c| c.id == id); + Ok(json!({"component": id, "metadata": c.map(|c| &c.metadata), "properties": c.map(|c| &c.properties), "changed": changed})) +} + +#[derive(Clone, Copy, PartialEq)] +enum Levels { + Flat, + Top, +} + +#[derive(Clone, Copy, PartialEq)] +enum Group { + PartNumber, + Definition, +} + +/// One row being gathered. +struct Row { + part_number: String, + description: String, + revision: String, + count: u64, + components: Vec, + names: Vec, + properties: BTreeMap, + /// With `group_children`: what is placed inside one of this row's parts, and how often. + kit: BTreeMap, +} + +/// What the bill of materials lists and how. +#[derive(Clone, Copy)] +struct Options { + levels: Levels, + group: Group, + /// A part with a part number keeps its sub-parts in its row. + fold: bool, +} + +fn options(p: &Value, cmd: &str) -> Result { + let levels = match p.get("levels") { + None | Some(Value::Null) => Levels::Flat, + Some(Value::String(l)) if l == "flat" => Levels::Flat, + Some(Value::String(l)) if l == "top" => Levels::Top, + Some(_) => return Err(bad(cmd, "`levels` is flat or top")), + }; + let group = match p.get("group_by") { + None | Some(Value::Null) => Group::PartNumber, + Some(Value::String(g)) => group_key(g, cmd)?, + Some(Value::Array(a)) => match a.as_slice() { + [Value::String(g)] => group_key(g, cmd)?, + _ => return Err(bad(cmd, "`group_by` is [\"part_number\"] or [\"definition\"]")), + }, + Some(_) => return Err(bad(cmd, "`group_by` is [\"part_number\"] or [\"definition\"]")), + }; + let fold = match p.get("group_children") { + None | Some(Value::Null) => false, + Some(Value::Bool(b)) => *b, + Some(_) => return Err(bad(cmd, "`group_children` is true or false")), + }; + Ok(Options { levels, group, fold }) +} + +/// The design's structure, looked up once per bill of materials. +struct Index { + /// What each component places (by its id; 0 is the root). + children: BTreeMap>, + /// Components with bodies of their own. + owners: HashSet, + /// Components with a part number: with `group_children`, one row however much is inside. + numbered: HashSet, +} + +impl Index { + fn new(s: &Session) -> Index { + let mut children: BTreeMap> = BTreeMap::new(); + for o in &s.doc.occurrences { + children.entry(o.parent).or_default().push(o.component); + } + let numbered = s.doc.components.iter().filter(|c| c.metadata.part_number().is_some_and(|n| !n.is_empty())).map(|c| c.id).collect(); + Index { children, owners: s.doc.body_owners(&s.model.state()), numbered } + } +} + +fn group_key(g: &str, cmd: &str) -> Result { + match g { + "part_number" => Ok(Group::PartNumber), + "definition" => Ok(Group::Definition), + o => Err(bad(cmd, format!("can't group by `{o}` (part_number or definition)"))), + } +} + +/// How many times each component is placed below `root`: in `Top`, its direct children; in +/// `Flat`, every placement at any depth (a part in a subassembly placed twice counts twice), +/// not below a numbered part when `fold`. +fn counts(ix: &Index, root: u64, levels: Levels, fold: bool, cmd: &str) -> Result> { + let mut out: BTreeMap = BTreeMap::new(); + let mut placed = 0usize; + let mut stack: Vec<(u64, usize)> = vec![(root, 0)]; + while let Some((comp, depth)) = stack.pop() { + for child in ix.children.get(&comp).into_iter().flatten() { + placed += 1; + if depth >= MAX_DEPTH || placed > MAX_PLACEMENTS { + return Err(bad(cmd, format!("the assembly is deeper than {MAX_DEPTH} levels or has more than {MAX_PLACEMENTS} placements"))); + } + *out.entry(*child).or_default() += 1; + if levels == Levels::Flat && !(fold && ix.numbered.contains(child)) { + stack.push((*child, depth + 1)); + } + } + } + if levels == Levels::Flat { + // Parts only: a subassembly is listed through its parts, unless it has bodies of its own + // (or, folding, a part number). + out.retain(|c, _| !ix.children.contains_key(c) || (fold && ix.numbered.contains(c)) || ix.owners.contains(c)); + } + Ok(out) +} + +/// How a kit reads when rows are compared: its parts by part number (else definition) and count. +fn kit_key(s: &Session, kit: &BTreeMap) -> String { + let mut parts: Vec = kit + .iter() + .map(|(id, n)| { + let pn = s.doc.components.iter().find(|c| c.id == *id).and_then(|c| c.metadata.part_number()).unwrap_or_default(); + if pn.is_empty() { format!("#{id}×{n}") } else { format!("{pn}×{n}") } + }) + .collect(); + parts.sort(); + parts.join("\n") +} + +fn rows(s: &Session, counts: &BTreeMap, group: Group, kits: &BTreeMap>) -> Vec { + let mut grouped: BTreeMap<(String, String, u64), Row> = BTreeMap::new(); + for (id, n) in counts { + let Some(c) = s.doc.components.iter().find(|c| c.id == *id) else { continue }; + let m = &c.metadata; + let part_number = m.part_number().unwrap_or_default().to_string(); + let kit = kits.get(id).cloned().unwrap_or_default(); + // Without a part number a definition is its own row; parts with different contents + // (a bolt with or without its nut) are different rows. + let k = match group { + Group::PartNumber if !part_number.is_empty() => (part_number.clone(), kit_key(s, &kit), 0), + _ => (String::new(), String::new(), *id), + }; + let row = grouped.entry(k).or_insert_with(|| Row { + part_number: part_number.clone(), + description: String::new(), + revision: String::new(), + count: 0, + components: Vec::new(), + names: Vec::new(), + properties: BTreeMap::new(), + kit, + }); + row.count += n; + row.components.push(*id); + if !row.names.contains(&c.name) { + row.names.push(c.name.clone()); + } + if row.description.is_empty() { + row.description = m.description().unwrap_or_default().to_string(); + } + if row.revision.is_empty() { + row.revision = m.revision().unwrap_or_default().to_string(); + } + for (k, v) in &c.properties { + row.properties.entry(k.clone()).or_insert_with(|| v.clone()); + } + } + let mut out: Vec = grouped.into_values().collect(); + // By part number; rows without one after them, by name. + out.sort_by(|a, b| { + (a.part_number.is_empty(), &a.part_number, &a.names, &a.components).cmp(&(b.part_number.is_empty(), &b.part_number, &b.names, &b.components)) + }); + out +} + +/// A CSV field, always quoted. +fn quote(s: &str) -> String { + format!("\"{}\"", s.replace('"', "\"\"")) +} + +/// The bill of materials as CSV: fixed columns, every field quoted. +fn csv(rows: &[Value]) -> String { + let mut out = ["item", "part_number", "description", "revision", "count", "definition"].map(quote).join(","); + out.push('\n'); + let lines = rows.iter().flat_map(|r| std::iter::once(r).chain(r["children"].as_array().into_iter().flatten())); + for r in lines { + let text = |k: &str| match &r[k] { + Value::String(t) => t.clone(), + Value::Null => String::new(), + v => v.to_string(), + }; + let fields = ["item", "part_number", "description", "revision", "count", "definition"].map(|k| quote(&text(k))); + out.push_str(&fields.join(",")); + out.push('\n'); + } + out +} + +fn bom(s: &mut Session, p: &Value) -> Result { + let cmd = "assembly.bom"; + let root = if p.get("component").is_some_and(|v| !v.is_null()) { component_id(s, p, cmd)? } else { 0 }; + let o = options(p, cmd)?; + let ix = Index::new(s); + let counts = counts(&ix, root, o.levels, o.fold, cmd)?; + // Folding: what one of each numbered part holds, as parts at any depth. + let mut kits: BTreeMap> = BTreeMap::new(); + if o.fold { + for id in counts.keys().filter(|id| ix.numbered.contains(id)) { + let kit = self::counts(&ix, *id, Levels::Flat, false, cmd)?; + if !kit.is_empty() { + kits.insert(*id, kit); + } + } + } + let mut total: u64 = 0; + let rows: Vec = rows(s, &counts, o.group, &kits) + .into_iter() + .enumerate() + .map(|(i, r)| { + total += r.count; + let mut v = json!({"item": i + 1, "part_number": r.part_number, "description": r.description, "revision": r.revision, + "count": r.count, "definition": r.names.join("; "), "components": r.components, "properties": r.properties}); + if !r.kit.is_empty() { + let children: Vec = self::rows(s, &r.kit, Group::PartNumber, &BTreeMap::new()) + .into_iter() + .enumerate() + .map(|(j, c)| { + let count = c.count.saturating_mul(r.count); + total += count; + json!({"item": format!("{}.{}", i + 1, j + 1), "part_number": c.part_number, "description": c.description, + "revision": c.revision, "each": c.count, "count": count, "definition": c.names.join("; ")}) + }) + .collect(); + v["children"] = Value::Array(children); + } + v + }) + .collect(); + let mut out = Map::new(); + out.insert("component".into(), json!(root)); + out.insert("levels".into(), json!(if o.levels == Levels::Top { "top" } else { "flat" })); + out.insert("group_by".into(), json!([if o.group == Group::Definition { "definition" } else { "part_number" }])); + out.insert("group_children".into(), json!(o.fold)); + if let Some(path) = str_(p, "path") { + let format = match str_(p, "format").map(str::to_ascii_lowercase) { + Some(f) => f, + None if path.to_ascii_lowercase().ends_with(".json") => "json".into(), + None if path.to_ascii_lowercase().ends_with(".csv") => "csv".into(), + None => return Err(bad(cmd, "`path` must end in .csv or .json, or give `format`")), + }; + let text = match format.as_str() { + "csv" => csv(&rows), + "json" => serde_json::to_string_pretty(&json!({"rows": rows, "total_occurrences": total})).map_err(|e| bad(cmd, e.to_string()))?, + other => return Err(bad(cmd, format!("unknown format `{other}` (csv or json)"))), + }; + solidcraft_io::vfs::write(path, text.as_bytes()).map_err(|e| EngineError::Other(format!("{path}: {e}")))?; + out.insert("path".into(), json!(path)); + out.insert("format".into(), json!(format)); + } + out.insert("rows".into(), Value::Array(rows)); + out.insert("total_occurrences".into(), json!(total)); + Ok(Value::Object(out)) +} + +#[cfg(test)] +#[path = "bom_tests.rs"] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests; diff --git a/crates/engine/src/cmd/bom_tests.rs b/crates/engine/src/cmd/bom_tests.rs new file mode 100644 index 000000000..5faa6ca6f --- /dev/null +++ b/crates/engine/src/cmd/bom_tests.rs @@ -0,0 +1,277 @@ +use serde_json::{Value, json}; + +use crate::Session; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + match s.execute(id, &p) { + Ok(v) => v, + Err(e) => panic!("{id} {p}: {e}"), + } +} + +/// A folder of its own for one test's files. +fn scratch(name: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("solidcraft-bom-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// A plate placed three times, and a hinge subassembly (no bodies of its own) placed twice +/// that holds one pin: the plate has 3 occurrences, the pin 2 (one in each hinge). +fn assembly() -> Session { + let mut s = Session::default(); + run(&mut s, "component.create", json!({"name": "Plate"})); + run(&mut s, "solid.box", json!({"length": 40, "width": 20, "height": 3})); + run(&mut s, "component.activate", json!({"component": 0})); + run(&mut s, "component.create", json!({"name": "Hinge", "activate": false})); + run(&mut s, "component.create", json!({"name": "Pin", "parent": "Hinge"})); + run(&mut s, "solid.cylinder", json!({"diameter": 4, "height": 30})); + run(&mut s, "component.activate", json!({"component": 0})); + for x in [50, 100] { + run(&mut s, "occurrence.copy", json!({"component": "Plate", "translate": [x, 0, 0]})); + } + run(&mut s, "occurrence.copy", json!({"component": "Hinge", "translate": [0, 50, 0]})); + run(&mut s, "component.metadata.set", json!({"component": "Plate", "part_number": "PL-100", "description": "Plate, 3 mm", "revision": "B"})); + run( + &mut s, + "component.metadata.set", + json!({"component": "Pin", "part_number": "PN-040", "description": "Pin 4 x 30", "properties": {"finish": "zinc"}}), + ); + s +} + +fn summary(r: &Value) -> Vec<(String, String, u64)> { + r["rows"] + .as_array() + .unwrap() + .iter() + .map(|r| (r["part_number"].as_str().unwrap().to_string(), r["definition"].as_str().unwrap().to_string(), r["count"].as_u64().unwrap())) + .collect() +} + +#[test] +fn flat_counts_parts_through_subassemblies_and_top_counts_children() { + let mut s = assembly(); + let undo = s.undo.len(); + let flat = run(&mut s, "assembly.bom", json!({})); + assert_eq!(summary(&flat), [("PL-100".into(), "Plate".into(), 3), ("PN-040".into(), "Pin".into(), 2)], "{flat}"); + assert_eq!(flat["total_occurrences"], 5); + assert_eq!(flat["rows"][0]["item"], 1); + assert_eq!(flat["rows"][0]["description"], "Plate, 3 mm"); + assert_eq!(flat["rows"][0]["revision"], "B"); + assert_eq!(flat["rows"][1]["properties"], json!({"finish": "zinc"})); + + let top = run(&mut s, "assembly.bom", json!({"levels": "top"})); + assert_eq!(summary(&top), [("PL-100".into(), "Plate".into(), 3), (String::new(), "Hinge".into(), 2)], "{top}"); + assert_eq!(top["total_occurrences"], 5); + + // One subassembly's own bill of materials. + let hinge = run(&mut s, "assembly.bom", json!({"component": "Hinge"})); + assert_eq!(summary(&hinge), [("PN-040".into(), "Pin".into(), 1)]); + assert_eq!(s.undo.len(), undo, "the bill of materials only reads"); +} + +#[test] +fn equal_part_numbers_share_a_row_unless_grouped_by_definition() { + let mut s = assembly(); + // An independent copy keeps the part properties, so it is the same part. + run(&mut s, "component.paste_new", json!({"component": "Plate", "translate": [0, -60, 0]})); + let r = run(&mut s, "assembly.bom", json!({})); + let plate = &r["rows"][0]; + assert_eq!((plate["part_number"].as_str(), plate["count"].as_u64()), (Some("PL-100"), Some(4)), "{r}"); + assert_eq!(plate["components"].as_array().map(Vec::len), Some(2)); + let by_def = run(&mut s, "assembly.bom", json!({"group_by": ["definition"]})); + let counts: Vec = + by_def["rows"].as_array().unwrap().iter().filter(|r| r["part_number"] == "PL-100").map(|r| r["count"].as_u64().unwrap()).collect(); + assert_eq!(counts, [3, 1], "{by_def}"); + // Without a part number every definition is its own row, after the numbered ones. + run(&mut s, "component.create", json!({"name": "Spacer"})); + run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 5})); + run(&mut s, "component.activate", json!({"component": 0})); + let r = run(&mut s, "assembly.bom", json!({})); + let last = r["rows"].as_array().unwrap().last().cloned().unwrap(); + assert_eq!((last["part_number"].as_str(), last["definition"].as_str()), (Some(""), Some("Spacer"))); +} + +#[test] +fn part_properties_survive_save_and_open_and_undo_in_one_step() { + let dir = scratch("roundtrip"); + let mut s = assembly(); + let undo = s.undo.len(); + let r = run(&mut s, "component.metadata.set", json!({"component": "Pin", "revision": "C", "properties": {"finish": null, "material": "1.4301"}})); + assert_eq!(r["changed"], json!(["revision", "properties.finish", "properties.material"])); + assert_eq!(s.undo.len(), undo + 1, "one undo step"); + // Setting the same values again changes nothing. + let r = run(&mut s, "component.metadata.set", json!({"component": "Pin", "revision": "C"})); + assert_eq!(r["changed"], json!([])); + assert_eq!(s.undo.len(), undo + 1); + for (file, format) in [("bom.json", "json"), ("bom.solidcraft", "container")] { + let path = dir.join(file); + run(&mut s, "file.save_as", json!({"path": path, "format": format})); + let mut back = Session::default(); + run(&mut back, "doc.open", json!({"path": path})); + let pin = run(&mut back, "component.metadata", json!({"component": "Pin"})); + assert_eq!((pin["part_number"].as_str(), pin["revision"].as_str()), (Some("PN-040"), Some("C")), "{format}: {pin}"); + assert_eq!(pin["properties"], json!({"material": "1.4301"}), "{format}"); + assert_eq!(summary(&run(&mut back, "assembly.bom", json!({}))), summary(&run(&mut s, "assembly.bom", json!({}))), "{format}"); + } + run(&mut s, "edit.undo", json!({})); + let pin = run(&mut s, "component.metadata", json!({"component": "Pin"})); + assert_eq!((pin["revision"].as_str(), &pin["properties"]), (None, &json!({"finish": "zinc"}))); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn csv_quotes_every_field_and_json_writes_the_rows() { + let dir = scratch("export"); + let mut s = assembly(); + run(&mut s, "component.metadata.set", json!({"component": "Pin", "description": "Pin \"short\", 4 mm"})); + let csv = dir.join("bom.csv"); + let r = run(&mut s, "assembly.bom", json!({"path": csv})); + assert_eq!(r["format"], "csv"); + let text = std::fs::read_to_string(&csv).unwrap(); + assert_eq!( + text, + "\"item\",\"part_number\",\"description\",\"revision\",\"count\",\"definition\"\n\ + \"1\",\"PL-100\",\"Plate, 3 mm\",\"B\",\"3\",\"Plate\"\n\ + \"2\",\"PN-040\",\"Pin \"\"short\"\", 4 mm\",\"\",\"2\",\"Pin\"\n" + ); + let json_path = dir.join("bom.json"); + run(&mut s, "assembly.bom", json!({"path": json_path, "levels": "top"})); + let back: Value = serde_json::from_str(&std::fs::read_to_string(&json_path).unwrap()).unwrap(); + assert_eq!(back["total_occurrences"], 5); + assert_eq!(back["rows"][1]["definition"], "Hinge"); + assert!(s.execute("assembly.bom", &json!({"path": dir.join("bom.txt")})).is_err(), "unknown extension"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn standard_parts_carry_a_part_number_that_follows_a_resize() { + let mut s = Session::default(); + let a = run(&mut s, "parts.insert", json!({"family": "socket_head_cap_screw", "size": "M6", "length": 20})); + run(&mut s, "parts.insert", json!({"family": "socket_head_cap_screw", "size": "M6", "length": 20, "point": [30, 0, 0]})); + run(&mut s, "parts.insert", json!({"family": "bearing", "size": "608", "point": [60, 0, 0]})); + let r = run(&mut s, "assembly.bom", json!({})); + let rows: Vec<(String, String, u64)> = r["rows"] + .as_array() + .unwrap() + .iter() + .map(|r| (r["part_number"].as_str().unwrap().into(), r["description"].as_str().unwrap().into(), r["count"].as_u64().unwrap())) + .collect(); + assert_eq!( + rows, + [("608".into(), "Deep groove ball bearing (envelope) 608".into(), 1), ("ISO 4762 M6x20".into(), "Socket head cap screw M6x20".into(), 2)] + ); + let screws = r["rows"].as_array().unwrap().iter().find(|r| r["count"] == 2).cloned().unwrap(); + assert_eq!(screws["definition"], "SHCS M6x20", "equal names are named once"); + assert_eq!(screws["components"].as_array().map(Vec::len), Some(2)); + // A resize renumbers the part; a description someone wrote stays theirs. + let comp = a["component"].as_u64().unwrap(); + run(&mut s, "component.metadata.set", json!({"component": comp, "description": "Cap screw, A2"})); + run(&mut s, "parts.resize", json!({"component": comp, "size": "M8", "length": 25})); + let m = run(&mut s, "component.metadata", json!({"component": comp})); + assert_eq!((m["part_number"].as_str(), m["description"].as_str()), (Some("ISO 4762 M8x25"), Some("Cap screw, A2"))); +} + +#[test] +fn hostile_part_properties_are_refused_without_a_change() { + let mut s = assembly(); + let undo = s.undo.len(); + for p in [ + json!({"component": "Pin"}), + json!({"component": 0, "part_number": "X"}), + json!({"component": "Nope", "part_number": "X"}), + json!({"component": "Pin", "part_number": 7}), + json!({"component": "Pin", "part_number": "ok", "description": "bell\u{7}"}), + json!({"component": "Pin", "properties": {"": "x"}}), + json!({"component": "Pin", "properties": {"finish": ["x"]}}), + json!({"component": "Pin", "properties": {"finish": "x".repeat(5000)}}), + json!({"component": "Pin", "values": {"bogus": "x"}}), + json!({"component": "Pin", "values": "x"}), + ] { + assert!(s.execute("component.metadata.set", &p).is_err(), "{p}"); + } + assert_eq!(s.undo.len(), undo); + let pin = run(&mut s, "component.metadata", json!({"component": "Pin"})); + assert_eq!(pin["part_number"], "PN-040", "all or nothing"); + for p in [json!({"levels": "deep"}), json!({"group_by": ["colour"]}), json!({"group_by": 3}), json!({"component": "Nope"})] { + assert!(s.execute("assembly.bom", &p).is_err(), "{p}"); + } + // The root reads as the design's own properties. + run(&mut s, "document.metadata.set", json!({"key": "part_number", "value": "ASM-1"})); + assert_eq!(run(&mut s, "component.metadata", json!({"component": 0}))["part_number"], "ASM-1"); +} + +/// Two hex bolts, each with a washer and a nut placed inside it, and a third bolt alone. +fn bolts() -> Session { + let mut s = Session::default(); + for x in [0, 30] { + let bolt = run(&mut s, "parts.insert", json!({"family": "hex_bolt", "size": "M6", "length": 30, "point": [x, 0, 0], "direction": [0, 0, 1]})); + run(&mut s, "component.activate", json!({"component": bolt["component"]})); + run(&mut s, "parts.insert", json!({"family": "washer", "size": "M6", "point": [x, 0, -2], "direction": [0, 0, -1]})); + run(&mut s, "parts.insert", json!({"family": "hex_nut", "size": "M6", "point": [x, 0, -4], "direction": [0, 0, -1]})); + run(&mut s, "component.activate", json!({"component": 0})); + } + run(&mut s, "parts.insert", json!({"family": "hex_bolt", "size": "M6", "length": 30, "point": [60, 0, 0], "direction": [0, 0, 1]})); + s +} + +#[test] +fn group_children_keeps_a_bolts_washer_and_nut_in_its_row() { + let mut s = bolts(); + let plain = run(&mut s, "assembly.bom", json!({})); + let numbers: Vec<(String, u64)> = summary(&plain).into_iter().map(|(pn, _, n)| (pn, n)).collect(); + assert_eq!(numbers, [("ISO 4017 M6x30".into(), 3), ("ISO 4032 M6".into(), 2), ("ISO 7089 M6".into(), 2)], "{plain}"); + + let r = run(&mut s, "assembly.bom", json!({"group_children": true})); + let rows = r["rows"].as_array().unwrap(); + assert_eq!(rows.len(), 2, "the bolts with a nut and the bolt alone: {r}"); + let kit = &rows[0]; + assert_eq!((kit["part_number"].as_str(), kit["count"].as_u64()), (Some("ISO 4017 M6x30"), Some(2)), "{r}"); + let children: Vec<(&str, &str, u64, u64)> = kit["children"] + .as_array() + .unwrap() + .iter() + .map(|c| (c["item"].as_str().unwrap(), c["part_number"].as_str().unwrap(), c["each"].as_u64().unwrap(), c["count"].as_u64().unwrap())) + .collect(); + assert_eq!(children, [("1.1", "ISO 4032 M6", 1, 2), ("1.2", "ISO 7089 M6", 1, 2)]); + assert_eq!((rows[1]["count"].as_u64(), rows[1].get("children")), (Some(1), None)); + assert_eq!(r["total_occurrences"], plain["total_occurrences"], "the same parts, folded"); + + let dir = scratch("kit"); + let path = dir.join("bom.csv"); + run(&mut s, "assembly.bom", json!({"group_children": true, "path": path.to_str().unwrap()})); + let text = std::fs::read_to_string(&path).unwrap(); + let items: Vec<&str> = text.lines().skip(1).map(|l| l.split(',').next().unwrap()).collect(); + assert_eq!(items, ["\"1\"", "\"1.1\"", "\"1.2\"", "\"2\""], "{text}"); + assert!(s.execute("assembly.bom", &json!({"group_children": "yes"})).is_err()); +} + +#[test] +fn changing_part_properties_does_not_evaluate_the_model_again() { + let mut s = bolts(); + s.evaluations = 0; + run(&mut s, "component.metadata.set", json!({"component": 1, "description": "Bolt", "properties": {"finish": "zinc"}})); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.evaluations, 0, "part properties change no geometry"); + assert_eq!(run(&mut s, "component.metadata", json!({"component": 1}))["description"], "Bolt"); + // A geometric edit after it finds every other feature's earlier result. + let first = run(&mut s, "assembly.bom", json!({}))["rows"][1]["components"][0].clone(); + run(&mut s, "parts.resize", json!({"component": first, "size": "M8"})); + run(&mut s, "parts.resize", json!({"component": first, "size": "M6"})); + // Anything else still evaluates. + run(&mut s, "occurrence.copy", json!({"component": 1, "translate": [0, 40, 0]})); + assert!(s.evaluations > 0); +} + +#[test] +fn body_owners_match_each_bodys_component() { + for s in [assembly(), bolts()] { + let st = s.model.state(); + let each: std::collections::HashSet = st.bodies.iter().map(|b| s.doc.model_body_component(b)).collect(); + assert_eq!(s.doc.body_owners(&st), each); + assert!(each.len() > 1); + } +} diff --git a/crates/engine/src/cmd/component_clone.rs b/crates/engine/src/cmd/component_clone.rs index 368d324db..2dcf3da9a 100644 --- a/crates/engine/src/cmd/component_clone.rs +++ b/crates/engine/src/cmd/component_clone.rs @@ -253,6 +253,11 @@ pub(super) fn paste( }; let name = unique(&c.name, &mut used); let new = scratch.doc_mut().add_component(Some(&name), mapped_parent)?; + // A copy keeps the definition's part properties. + if let Some(added) = scratch.doc_mut().components.iter_mut().find(|x| x.id == new) { + added.metadata = c.metadata.clone(); + added.properties = c.properties.clone(); + } components.insert(*old, new); if *old != component { scratch.doc_mut().occurrences.retain(|o| o.component != new); diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index d02c97148..c5a1dc0d5 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -20,6 +20,7 @@ macro_rules! planned { }; } +mod bom; mod browser; mod clearance; mod clipboard; @@ -260,6 +261,7 @@ pub fn command_specs() -> Vec<&'static CommandSpec> { v.extend(motion::COMMANDS.iter()); v.extend(config::COMMANDS.iter()); v.extend(parts::COMMANDS.iter()); + v.extend(bom::COMMANDS.iter()); v.extend(browser::COMMANDS.iter()); v.extend(delete::COMMANDS.iter()); v.extend(edit::COMMANDS.iter()); diff --git a/crates/engine/src/cmd/parts.rs b/crates/engine/src/cmd/parts.rs index ffdb3e093..36ffcd4fc 100644 --- a/crates/engine/src/cmd/parts.rs +++ b/crates/engine/src/cmd/parts.rs @@ -316,6 +316,45 @@ fn part_name(family: &str, size: &str, sh: &Shape) -> String { } } +/// A standard part's part number and description: its standard and size (`ISO 4762 M6x20`), or +/// a bearing's designation, and the family's name with the size. +fn identity(family: &str, size: &str, sh: &Shape) -> (String, String) { + let size = match sh { + Shape::Screw { len, .. } | Shape::Rod { len, .. } => format!("{size}x{len}"), + _ => size.to_string(), + }; + let standard = match family { + "socket_head_cap_screw" => "ISO 4762", + "hex_bolt" => "ISO 4017", + "hex_nut" => "ISO 4032", + "washer" => "ISO 7089", + "set_screw" => "ISO 4026", + "dowel_pin" => "ISO 8734", + _ => "", + }; + let name = FAMILIES.iter().find(|f| f.0 == family).map_or("Part", |f| f.1); + let part_number = if standard.is_empty() { size.clone() } else { format!("{standard} {size}") }; + (part_number, format!("{name} {size}")) +} + +/// Give a standard part its part number and description; a field someone changed since the last +/// size (`was`) is theirs and stays. +fn set_identity(s: &mut Session, comp: u64, now: (String, String), was: Option<(String, String)>) { + use solidcraft_doc::metadata::{DESCRIPTION, PART_NUMBER}; + let Some(c) = s.doc.components.iter().find(|c| c.id == comp) else { return }; + let mut m = c.metadata.clone(); + for (k, new, old) in [(PART_NUMBER, now.0, was.as_ref().map(|w| w.0.as_str())), (DESCRIPTION, now.1, was.as_ref().map(|w| w.1.as_str()))] { + if m.text(k).is_none_or(|cur| Some(cur) == old) { + let _ = m.set(k, Value::String(new)); + } + } + if m != c.metadata + && let Some(c) = s.doc_mut().components.iter_mut().find(|c| c.id == comp) + { + c.metadata = m; + } +} + fn label(family: &str) -> &'static str { match family { "socket_head_cap_screw" => "SHCS", @@ -356,6 +395,7 @@ fn insert(s: &mut Session, p: &Value) -> Result { let (comp, occ) = (c["component"].as_u64().unwrap_or(0), c["occurrence"].as_u64().unwrap_or(0)); build(s, &sh)?; s.doc_mut().parts.insert(comp, solidcraft_doc::StandardPart { family: family.clone(), size: size.clone(), length: shape_len(&sh) }); + set_identity(s, comp, identity(&family, &size, &sh), None); run(s, "component.activate", json!({"component": active}))?; let mut out = json!({"component": comp, "occurrence": occ, "name": name}); if let (Some(a), Some(h)) = (at, host) { @@ -435,6 +475,8 @@ fn resize(s: &mut Session, p: &Value) -> Result { run(s, "component.activate", json!({"component": comp}))?; build(s, &sh)?; let name = part_name(&part.family, &size, &sh); + let was = shape(&part.family, &part.size, part.length).ok().map(|old| identity(&part.family, &part.size, &old)); + set_identity(s, comp, identity(&part.family, &size, &sh), was); s.doc_mut().parts.insert(comp, solidcraft_doc::StandardPart { family: part.family.clone(), size: size.clone(), length: shape_len(&sh) }); if let Some(c) = s.doc_mut().components.iter_mut().find(|c| c.id == comp) { c.name = name.clone(); diff --git a/crates/engine/src/cmd/sketch_3d_frame_tests.rs b/crates/engine/src/cmd/sketch_3d_frame_tests.rs index 4acd5d7df..6dfbe7d65 100644 --- a/crates/engine/src/cmd/sketch_3d_frame_tests.rs +++ b/crates/engine/src/cmd/sketch_3d_frame_tests.rs @@ -215,7 +215,7 @@ fn wire_frame_wide_owner_graph_has_bounded_indexed_traversal() { // A legal wide assembly used to force one whole occurrence scan for each leaf. let doc = s.doc_mut(); for i in 0..9998u64 { - doc.components.push(solidcraft_doc::Component { id: 10_000 + i, name: format!("Sibling{i}"), parent: 0 }); + doc.components.push(solidcraft_doc::Component { id: 10_000 + i, name: format!("Sibling{i}"), parent: 0, ..Default::default() }); doc.occurrences.push(solidcraft_doc::Occurrence { id: 100_000 + i, component: 10_000 + i, diff --git a/crates/engine/src/cmd/urdf_tests.rs b/crates/engine/src/cmd/urdf_tests.rs index 47e198156..1c497bc06 100644 --- a/crates/engine/src/cmd/urdf_tests.rs +++ b/crates/engine/src/cmd/urdf_tests.rs @@ -557,7 +557,12 @@ fn urdf_warns_when_placements_are_cut_off() { let s = Session::default(); let mut doc = (*s.doc).clone(); for k in 1..=66u64 { - doc.components.push(solidcraft_doc::Component { id: 1000 + k, name: format!("C{k}"), parent: if k == 1 { 0 } else { 999 + k } }); + doc.components.push(solidcraft_doc::Component { + id: 1000 + k, + name: format!("C{k}"), + parent: if k == 1 { 0 } else { 999 + k }, + ..Default::default() + }); doc.occurrences.push(solidcraft_doc::Occurrence { id: 2000 + k, component: 1000 + k, @@ -569,8 +574,8 @@ fn urdf_warns_when_placements_are_cut_off() { } // A component placed twice with a part nested in it, next to the deep chain: its copy is // still there, since only the branch past the limit stops. - doc.components.push(solidcraft_doc::Component { id: 3001, name: "Leg".into(), parent: 0 }); - doc.components.push(solidcraft_doc::Component { id: 3002, name: "Foot".into(), parent: 3001 }); + doc.components.push(solidcraft_doc::Component { id: 3001, name: "Leg".into(), parent: 0, ..Default::default() }); + doc.components.push(solidcraft_doc::Component { id: 3002, name: "Foot".into(), parent: 3001, ..Default::default() }); // Listed first, so the walk (a stack) goes down the chain before reaching them. for (id, component, parent, name) in [(4003, 3002, 3001, "Foot:1"), (4002, 3001, 0, "Leg:2"), (4001, 3001, 0, "Leg:1")] { let o = solidcraft_doc::Occurrence { id, component, parent, name: name.into(), transform: solidcraft_doc::IDENTITY, grounded: false }; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index bf2318511..889509b88 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -589,9 +589,12 @@ impl Session { } } - /// Only persistent render intent changed. Never evaluate or clear a stale model here. + /// Only persistent render intent, or only part properties, changed. Never evaluate or clear + /// a stale model here. fn render_only_change(&self, before: &Snapshot) -> bool { - self.active_sketch == before.active_sketch && self.pending_moves == before.pending_moves && self.doc.differs_only_in_render(&before.doc) + self.active_sketch == before.active_sketch + && self.pending_moves == before.pending_moves + && (self.doc.differs_only_in_render(&before.doc) || self.doc.differs_only_in_part_properties(&before.doc)) } fn refresh_render(&mut self, previous: &Arc) { diff --git a/crates/ui-egui/src/bom_panel.rs b/crates/ui-egui/src/bom_panel.rs new file mode 100644 index 000000000..5bab059de --- /dev/null +++ b/crates/ui-egui/src/bom_panel.rs @@ -0,0 +1,224 @@ +//! The Bill of Materials window: `assembly.bom`'s rows (flat or top level, grouped by part +//! number or by definition, a part's sub-parts in its row or not), with Export CSV… and Export +//! JSON…. Picking a row edits its part +//! number, description and revision through one `component.metadata.set` per definition. The +//! toolbar's Bill of Materials (`ui.start` of `assembly.bom`) opens it. + +use egui::RichText; +use serde_json::{Value, json}; + +use crate::SolveApp; +use crate::theme::Tokens; + +/// The window's state; the rows come from the engine. +#[derive(Default)] +pub struct BomPanel { + /// Top level instead of flat. + pub top: bool, + /// One row per definition instead of per part number. + pub by_definition: bool, + /// A part with a part number keeps its sub-parts (a bolt's washers and nut) in its row. + pub group_children: bool, + /// The rows for (design revision, top, by_definition, group_children). + cache: Option<(u64, [bool; 3], Value)>, + /// The picked row's index, and its fields as edited. + pub picked: Option, + pub fields: [String; 3], + /// The last refusal. + pub error: Option, +} + +impl BomPanel { + fn params(&self) -> Value { + json!({"levels": if self.top { "top" } else { "flat" }, "group_by": [if self.by_definition { "definition" } else { "part_number" }], + "group_children": self.group_children}) + } + + /// The bill of materials for the design as it is now (computed again only after a change). + fn rows(&mut self, app: &mut SolveApp) -> Value { + let revision = app.session.revision; + let key = [self.top, self.by_definition, self.group_children]; + if let Some((r, k, v)) = &self.cache + && (*r, *k) == (revision, key) + { + return v.clone(); + } + let v = match app.session.execute("assembly.bom", &self.params()) { + Ok(v) => v, + Err(e) => { + self.error = Some(e.to_string()); + json!({"rows": [], "total_occurrences": 0}) + } + }; + self.cache = Some((revision, key, v.clone())); + v + } +} + +/// Open the window. +pub fn open(app: &mut SolveApp) { + app.bom = Some(BomPanel::default()); +} + +fn text(row: &Value, k: &str) -> String { + match &row[k] { + Value::String(t) => t.clone(), + Value::Null => String::new(), + v => v.to_string(), + } +} + +/// Apply the picked row's fields to each of its definitions (one undo step each). +fn apply(app: &mut SolveApp, d: &mut BomPanel, row: &Value) { + let [pn, desc, rev] = d.fields.clone(); + for c in row["components"].as_array().into_iter().flatten() { + let r = app.run("component.metadata.set", json!({"component": c, "part_number": pn, "description": desc, "revision": rev})); + if let Err(e) = r { + d.error = Some(e); + return; + } + } + d.error = None; +} + +/// Draw the window when it is open. Called once per frame. +pub fn show(app: &mut SolveApp, ctx: &egui::Context) { + let Some(mut d) = app.bom.take() else { return }; + let t = Tokens::get(); + let mut open = true; + let bom = d.rows(app); + let rows: Vec = bom["rows"].as_array().cloned().unwrap_or_default(); + let (mut export, mut apply_row) = (None, None); + let title = RichText::new(crate::i18n::tr_label("Bill of Materials")).strong().size(13.0); + crate::frame::window(ctx, title, crate::frame::Width::Wide).id(egui::Id::new("sc_bom")).open(&mut open).resizable(true).show(ctx, |ui| { + ui.horizontal(|ui| { + let was = (d.top, d.by_definition, d.group_children); + ui.selectable_value(&mut d.top, false, "Parts only"); + ui.selectable_value(&mut d.top, true, "Top level"); + ui.separator(); + ui.selectable_value(&mut d.by_definition, false, "By part number"); + ui.selectable_value(&mut d.by_definition, true, "By definition"); + ui.separator(); + ui.checkbox(&mut d.group_children, "Sub-parts in their part's row"); + if was != (d.top, d.by_definition, d.group_children) { + d.picked = None; + } + }); + ui.separator(); + egui::ScrollArea::vertical().max_height(320.0).show(ui, |ui| { + egui::Grid::new("sc_bom_grid").num_columns(6).striped(true).spacing([14.0, 4.0]).show(ui, |ui| { + for h in ["Item", "Part number", "Description", "Rev", "Qty", "Definition"] { + ui.label(RichText::new(h).strong().color(t.text_dim)); + } + ui.end_row(); + for (i, row) in rows.iter().enumerate() { + let picked = d.picked == Some(i); + if ui.selectable_label(picked, text(row, "item")).clicked() { + d.picked = if picked { None } else { Some(i) }; + d.fields = [text(row, "part_number"), text(row, "description"), text(row, "revision")]; + } + ui.label(text(row, "part_number")); + ui.label(text(row, "description")); + ui.label(text(row, "revision")); + ui.label(text(row, "count")); + ui.label(RichText::new(text(row, "definition")).color(t.text_dim)); + ui.end_row(); + for c in row["children"].as_array().into_iter().flatten() { + ui.label(RichText::new(text(c, "item")).color(t.text_dim)); + ui.label(text(c, "part_number")); + ui.label(text(c, "description")); + ui.label(text(c, "revision")); + ui.label(text(c, "count")); + ui.label(RichText::new(text(c, "definition")).color(t.text_dim)); + ui.end_row(); + } + } + }); + }); + ui.label(RichText::new(format!("{} rows, {} placed", rows.len(), text(&bom, "total_occurrences"))).small().color(t.text_dim)); + if let Some(row) = d.picked.and_then(|i| rows.get(i)) { + ui.separator(); + egui::Grid::new("sc_bom_edit").num_columns(2).spacing([12.0, 6.0]).show(ui, |ui| { + for (label, field) in ["Part number", "Description", "Revision"].into_iter().zip(d.fields.iter_mut()) { + ui.label(label); + ui.add(egui::TextEdit::singleline(field).desired_width(280.0)); + ui.end_row(); + } + }); + if ui.button("Apply").clicked() { + apply_row = Some(row.clone()); + } + } + if let Some(e) = &d.error { + ui.label(RichText::new(e).color(t.error)); + } + ui.separator(); + ui.horizontal(|ui| { + for (label, ext) in [("Export CSV…", "csv"), ("Export JSON…", "json")] { + if ui.button(label).clicked() { + export = Some(ext); + } + } + }); + }); + if let Some(row) = apply_row { + apply(app, &mut d, &row); + } + if let Some(ext) = export { + let mut params = d.params(); + params["format"] = json!(ext); + app.pick_save_command(&format!("bill-of-materials.{ext}"), &[ext], "assembly.bom", params); + } + if open { + app.bom = Some(d); + } +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + use crate::scenario::Harness; + + #[test] + fn the_window_lists_counts_and_edits_a_part_number() { + let mut h = Harness::new(); + h.app.run("component.create", json!({"name": "Plate"})).unwrap(); + h.app.run("solid.box", json!({"length": 40, "width": 20, "height": 3})).unwrap(); + h.app.run("component.activate", json!({"component": 0})).unwrap(); + h.app.run("occurrence.copy", json!({"component": "Plate", "translate": [50, 0, 0]})).unwrap(); + h.step(&json!({"start": "assembly.bom"})).unwrap(); + assert!(h.app.bom.is_some(), "ui.start opens the window"); + h.frames(2); + assert!(h.widget("Export CSV…").is_some()); + assert!(h.widget("1 rows, 2 placed").is_some()); + let undo = h.app.session.undo.len(); + h.step(&json!({"widget": "1"})).unwrap(); + let d = h.app.bom.as_mut().unwrap(); + assert_eq!(d.picked, Some(0)); + d.fields[0] = "PL-100".into(); + h.frames(2); + h.step(&json!({"widget": "Apply"})).unwrap(); + let m = h.app.session.execute("component.metadata", &json!({"component": "Plate"})).unwrap(); + assert_eq!(m["part_number"], "PL-100"); + assert_eq!(h.app.session.undo.len(), undo + 1, "one undo step"); + h.frames(2); + assert!(h.widget("PL-100").is_some(), "the list follows the change"); + } + + #[test] + fn sub_parts_show_under_their_part() { + let mut h = Harness::new(); + let bolt = h.app.run("parts.insert", json!({"family": "hex_bolt", "size": "M6", "length": 30, "point": [0, 0, 0]})).unwrap(); + h.app.run("component.activate", json!({"component": bolt["component"]})).unwrap(); + h.app.run("parts.insert", json!({"family": "hex_nut", "size": "M6", "point": [0, 0, -4]})).unwrap(); + h.app.run("component.activate", json!({"component": 0})).unwrap(); + h.step(&json!({"start": "assembly.bom"})).unwrap(); + h.frames(2); + assert!(h.widget("2 rows, 2 placed").is_some()); + h.step(&json!({"widget": "Sub-parts in their part's row"})).unwrap(); + h.frames(2); + assert!(h.widget("1 rows, 2 placed").is_some()); + assert!(h.widget("1.1").is_some(), "the nut under its bolt"); + } +} diff --git a/crates/ui-egui/src/documents.rs b/crates/ui-egui/src/documents.rs index 7e7656aff..fced2be8a 100644 --- a/crates/ui-egui/src/documents.rs +++ b/crates/ui-egui/src/documents.rs @@ -96,6 +96,7 @@ fn swap_in(app: &mut SolveApp, slot: DocSlot) -> DocSlot { app.tool = None; app.params = None; app.design_properties = None; + app.bom = None; app.cancel_view_animation(); app.viewport.orbit_snap = None; app.viewport.orbit_free = None; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c68afd2d6..b5d2d4f00 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -11,6 +11,7 @@ pub mod access; pub mod agent_chat; pub mod agent_cursor; +pub mod bom_panel; pub mod browser; pub mod canvas; #[cfg(test)] @@ -316,6 +317,8 @@ pub struct SolveApp { pub params: Option, /// The Design Properties window, when open. pub design_properties: Option, + /// The Bill of Materials window, when open. + pub bom: Option, material_card_review: Option, pub palette: palette::Palette, /// Context menus, rename box and Properties window. @@ -449,6 +452,7 @@ impl SolveApp { dialog: None, params: None, design_properties: None, + bom: None, material_card_review: None, palette: palette::Palette::default(), menu: context_menu::MenuState::default(), @@ -817,6 +821,10 @@ impl SolveApp { design_properties::open(self); return; } + if id == "assembly.bom" { + bom_panel::open(self); + return; + } if id == "sketch.finish" { self.finish_sketch(); return; @@ -1448,6 +1456,7 @@ impl SolveApp { self.resolve_fit(ui.ctx()); params_dialog::show(self, ui.ctx()); design_properties::show(self, ui.ctx()); + bom_panel::show(self, ui.ctx()); material_card_review::show(self, ui.ctx()); recovery_ui::show(self, ui.ctx()); stand_up::show(self, ui.ctx()); diff --git a/crates/ui-egui/tests/window_widths.rs b/crates/ui-egui/tests/window_widths.rs index 25a744097..2f704929d 100644 --- a/crates/ui-egui/tests/window_widths.rs +++ b/crates/ui-egui/tests/window_widths.rs @@ -53,6 +53,7 @@ fn command_dialogs_shrink_to_their_content_within_limits() { h.app.dialog = None; h.app.params = None; h.app.design_properties = None; + h.app.bom = None; h.app.tool = None; if h.app.session.active_sketch.is_some() { h.app.finish_sketch(); diff --git a/docs/book/src/guide/assemblies.md b/docs/book/src/guide/assemblies.md index f60701c1c..033451123 100644 --- a/docs/book/src/guide/assemblies.md +++ b/docs/book/src/guide/assemblies.md @@ -279,3 +279,41 @@ measures the complete assembly. Volumes are summed, including overlapping bodies measuring their union. The same workflow is available through `component.properties` and `occurrence.properties`; see [placement and measurement details](https://github.com/bherbruck/solidcraft/blob/main/docs/assembly-properties.md). + +## Part properties and the bill of materials + +A component definition carries its own **part properties**: a part number, a description and a +revision, other tools' data under a reverse-DNS key (the same rules as the design's own +properties), and free text properties such as a material grade or a finish. Every occurrence of +the component shares them, Paste New copies them, and they are saved with the component. +`component.metadata {component}` reads them and +`component.metadata.set {component, part_number?, description?, revision?, values?, properties?}` +changes them in one undo step (an empty value removes a field). The root component is the +design itself: its properties are `document.metadata`'s. Standard parts (`parts.insert`) get a +part number from their standard and size (`ISO 4762 M6x20`, or a bearing's designation) and a +description; **Change Part Size** renumbers them, keeping a field you changed yourself. + +**Bill of Materials** (`assembly.bom`, on the **INSPECT** panel) counts the placed components: + +- `levels: "flat"` (the default) lists the parts at any depth, each counted through its + subassemblies: a part placed once in a subassembly that is placed twice counts 2. A + subassembly is listed through its parts, unless it has bodies of its own. +- `levels: "top"` lists the direct children, a subassembly as one row. +- `group_by: ["part_number"]` (the default) puts definitions with the same part number in one + row; a definition without a part number gets a row of its own. `["definition"]` gives every + definition its own row. +- `group_children: true` keeps what is placed inside a part with a part number in that part's + row: a bolt with a washer and a nut placed inside it is one row, the washer and the nut listed + under it as `children` (items 1.1, 1.2…, with `each` per bolt and `count` in all) instead of + rows of their own. Bolts with different contents (one with a nut, one without) are different + rows. `total_occurrences` counts the children too, so it is the same either way. +- `component` lists one subassembly's parts instead of the design's. + +Rows are sorted by part number (rows without one come last) and hold `item`, `part_number`, +`description`, `revision`, `count`, `definition` (the component names), `components` (their ids) +and `properties`, with `total_occurrences` beside them. `path` writes them to a `.csv` file +(the columns item, part_number, description, revision, count and definition, every field +quoted; children follow their row) or a `.json` file. The window lists the same rows, switches +between the levels and groupings and shows children under their part, edits a picked row's part +number, description and revision, and exports them. Changing part properties changes no +geometry, so it doesn't evaluate the model or re-seat joints again. From 45d0b6053bf122613b4bde4abf9f513092e67e6c Mon Sep 17 00:00:00 2001 From: HiroKenEz <59478073+HiroKenEz@users.noreply.github.com> Date: Mon, 19 Oct 2026 22:04:49 +0200 Subject: [PATCH 074/225] Icon tools: hashes and palette revisions ignore CRLF checkouts, text I/O is UTF-8 (#1930) (#1931) On Windows, Git's default core.autocrlf checks the icon masters and the palette out with CRLF, and `cargo xtask icons` failed four ways: - the accepted-icon hashes (lint_icons.py and the review page's review_state.master_hash) were taken over the files' bytes, so every accepted icon read as changed; both now use master_hash, which hashes the text with CRLF read as LF; - icon_palette.revision hashed the bytes while save_colours hashed the text it read, so every palette save was refused as stale; revision now reads the text too; - the tools and their tests read and wrote text in the locale's encoding (cp1252 can't write U+2194); they now say utf-8; - the icon inventory listed UI files with backslashes; it writes /. Co-authored-by: Claude Opus 5.5 Co-authored-by: bherbruck --- assets/icons/ui/design/tools/icon_palette.py | 3 +- assets/icons/ui/design/tools/icon_status.py | 4 +- assets/icons/ui/design/tools/lint_icons.py | 10 ++-- assets/icons/ui/design/tools/preview.py | 4 +- assets/icons/ui/design/tools/review_state.py | 10 ++-- tests/tools/test_icon_export.py | 32 ++++++------ tests/tools/test_icon_line_endings.py | 39 ++++++++++++++ tests/tools/test_icon_review.py | 54 ++++++++++---------- 8 files changed, 99 insertions(+), 57 deletions(-) create mode 100644 tests/tools/test_icon_line_endings.py diff --git a/assets/icons/ui/design/tools/icon_palette.py b/assets/icons/ui/design/tools/icon_palette.py index c399cc7fa..0410d1f8e 100644 --- a/assets/icons/ui/design/tools/icon_palette.py +++ b/assets/icons/ui/design/tools/icon_palette.py @@ -113,7 +113,8 @@ def palette_css(palette): def revision(path): - with open(path, 'rb') as source: return hashlib.sha256(source.read()).hexdigest() + # As save_colours reads it: text, so a CRLF checkout's line endings read as LF. + with open(path, encoding='utf-8') as source: return hashlib.sha256(source.read().encode()).hexdigest() def save_colours(path, base_revision, changes): diff --git a/assets/icons/ui/design/tools/icon_status.py b/assets/icons/ui/design/tools/icon_status.py index 2f2446f32..b69275654 100644 --- a/assets/icons/ui/design/tools/icon_status.py +++ b/assets/icons/ui/design/tools/icon_status.py @@ -82,7 +82,7 @@ def scan(): for f in glob.glob(ROOT + '/crates/ui-egui/src/**/*.rs', recursive=True): t = open(f, encoding='utf-8').read() for name in ui_icon_names(t): - uses[name].append('ui:' + os.path.relpath(f, ROOT + '/crates/ui-egui/src')) + uses[name].append('ui:' + os.path.relpath(f, ROOT + '/crates/ui-egui/src').replace(os.sep, '/')) mk = ROOT + '/assets/icons/ui/source/markers.rs' if os.path.exists(mk): for name in re.findall(r'=> "(c_[a-z_]+)"', open(mk, encoding='utf-8').read()): uses[name].append('ui:sketch constraint glyph') @@ -284,7 +284,7 @@ if '--serve' in args: request_id = uuid.uuid4().hex path = os.path.join(REQUESTS, request_id + '.json') # Publish a complete snapshot atomically so the chat never reads half a request. - with open(path + '.tmp', 'w') as f: + with open(path + '.tmp', 'w', encoding='utf-8') as f: json.dump({'version': 1, 'id': request_id, 'created_at': datetime.datetime.now(datetime.timezone.utc).isoformat(), 'notes': {i: r['notes'][i] for i in todo}}, f, indent=1) diff --git a/assets/icons/ui/design/tools/lint_icons.py b/assets/icons/ui/design/tools/lint_icons.py index c8bce5ae9..6c7fe532c 100644 --- a/assets/icons/ui/design/tools/lint_icons.py +++ b/assets/icons/ui/design/tools/lint_icons.py @@ -80,16 +80,14 @@ if os.path.exists(references): for message in icon_palette.validation_errors(pal, names | set(al)): err(d + '/palette.toml', message) # an icon accepted as final on the review page must not change (un-accept it there to work on it again) -import json, hashlib +import json, review_state rp = d + '/review.json' if os.path.exists(rp): - fin = json.load(open(rp)).get('final', {}) + fin = json.load(open(rp, encoding='utf-8')).get('final', {}) for iid, want in (fin.items() if isinstance(fin, dict) else []): v = al.get(iid, iid); m = v.get('master') if isinstance(v, dict) else v if not want: continue - h = hashlib.sha256() - for f in sorted(glob.glob(d + '/svg/*/' + m + '.svg')): - h.update(os.path.relpath(f, d).replace(os.sep, '/').encode()); h.update(open(f, 'rb').read()) - if h.hexdigest() != want: err(rp, 'final icon %s changed (master %s): un-accept it on the review page before editing it' % (iid, m)) + # The review page's own hash, so the two can't disagree. + if review_state.master_hash(m, d) != want: err(rp, 'final icon %s changed (master %s): un-accept it on the review page before editing it' % (iid, m)) print('\n'.join(bad) if bad else 'icons: %d masters, palette, naming and element rules ok' % len(files)) sys.exit(1 if bad else 0) diff --git a/assets/icons/ui/design/tools/preview.py b/assets/icons/ui/design/tools/preview.py index 69bf160db..400fe8df1 100644 --- a/assets/icons/ui/design/tools/preview.py +++ b/assets/icons/ui/design/tools/preview.py @@ -14,9 +14,9 @@ for theme in ('light', 'dark'): for fam in sorted(os.listdir(d + '/svg')): h += '

%s - %s

' % (theme, fam, theme) for f in sorted(glob.glob('%s/svg/%s/*.svg' % (d, fam))): - svg, icon = open(f).read(), os.path.basename(f)[:-4] + svg, icon = open(f, encoding='utf-8').read(), os.path.basename(f)[:-4] h += '
' h += '
%s
' % themed(svg, theme, icon, fam, 64).replace('%s' % (s, s, themed(svg, theme, icon, fam, s).replace('' + icon + '
' h += '
' -open(out, 'w').write(h) +open(out, 'w', encoding='utf-8').write(h) diff --git a/assets/icons/ui/design/tools/review_state.py b/assets/icons/ui/design/tools/review_state.py index 2b78ae2a9..e313276f8 100644 --- a/assets/icons/ui/design/tools/review_state.py +++ b/assets/icons/ui/design/tools/review_state.py @@ -16,10 +16,14 @@ def aliases(): def master_of(icon_id, al=None): v = (aliases() if al is None else al).get(icon_id) return (v['master'] if isinstance(v, dict) else v) if v else icon_id -def master_hash(master): +def lf(data): + """Text as committed: a checkout with CRLF line endings (Git for Windows' default) hashes as LF.""" + return data.replace(b'\r\n', b'\n') +def master_hash(master, design=None): + d = D if design is None else design h = hashlib.sha256() - for f in sorted(glob.glob(D + '/svg/*/' + master + '.svg')): - h.update(os.path.relpath(f, D).replace(os.sep, '/').encode()); h.update(open(f, 'rb').read()) + for f in sorted(glob.glob(d + '/svg/*/' + master + '.svg')): + h.update(os.path.relpath(f, d).replace(os.sep, '/').encode()); h.update(lf(open(f, 'rb').read())) return h.hexdigest() def load(): try: r = json.load(open(REVIEW, encoding='utf-8')) diff --git a/tests/tools/test_icon_export.py b/tests/tools/test_icon_export.py index 1e6d977af..bbc8f85fa 100644 --- a/tests/tools/test_icon_export.py +++ b/tests/tools/test_icon_export.py @@ -24,31 +24,31 @@ class IconExportTest(unittest.TestCase): for name in ('icon_status.py', 'review_state.py', 'icon_palette.py'): shutil.copy(source / name, tools / name) shutil.copytree(source / 'review', tools / 'review') - (design / 'palette.toml').write_text('[roles.line]\nlight="#000000"\ndark="#ffffff"\n') + (design / 'palette.toml').write_text('[roles.line]\nlight="#000000"\ndark="#ffffff"\n', encoding='utf-8') for name in ('aliases.toml',): - (design / name).write_text('') + (design / name).write_text('', encoding='utf-8') svg = design / 'svg/model' svg.mkdir(parents=True) for name in ('agent_chat', 'pattern_flip', 'normal', 'infinite', 'trace'): - (svg / (name + '.svg')).write_text('') + (svg / (name + '.svg')).write_text('', encoding='utf-8') ui = root / 'crates/ui-egui/src' (ui / 'agent_chat').mkdir(parents=True) - (ui / 'agent_chat/panel.rs').write_text('icons::paint(p, r, "agent_chat", ink, fill, a);') - (ui / 'dialogs.rs').write_text('pattern_toggle(ui, alignment_label, "Flip direction", "pattern_flip", reversed);') + (ui / 'agent_chat/panel.rs').write_text('icons::paint(p, r, "agent_chat", ink, fill, a);', encoding='utf-8') + (ui / 'dialogs.rs').write_text('pattern_toggle(ui, alignment_label, "Flip direction", "pattern_flip", reversed);', encoding='utf-8') (ui / 'sketch_palette.rs').write_text(''' for (i, (label, icon, tip)) in [ ("—", "normal", "Normal"), ("↔", "infinite", "Infinite"), ].iter().enumerate() { icons::paint(p, r, icon, ink, fill, a); } - ''') + ''', encoding='utf-8') engine = root / 'crates/engine/src/cmd' engine.mkdir(parents=True) # A long builder must not lose its icon after the first fourteen lines. (engine / 'motion.rs').write_text('CommandSpec::new("motion.trace", "Trace", trace)\n' - + '\n' * 16 + '.icon("trace").params("doc");') + + '\n' * 16 + '.icon("trace").params("doc");', encoding='utf-8') subprocess.run([sys.executable, '-B', str(tools / 'icon_status.py'), '--csv'], check=True, capture_output=True, text=True) - with open(root / 'target/icon-inventory.csv') as f: + with open(root / 'target/icon-inventory.csv', encoding='utf-8') as f: rows = {r['icon']: r for r in csv.DictReader(f)} self.assertEqual(set(rows), {'agent_chat', 'pattern_flip', 'normal', 'infinite', 'trace'}) self.assertIn('agent_chat/panel.rs', rows['agent_chat']['used_by_ui']) @@ -68,15 +68,15 @@ class IconExportTest(unittest.TestCase): shutil.copy(source / name, tools / name) shutil.copytree(source / 'review', tools / 'review') for name in ('palette.toml', 'aliases.toml'): - (design / name).write_text('') - (design / 'palette.toml').write_text('[roles.line]\nlight="#000000"\ndark="#ffffff"\n') + (design / name).write_text('', encoding='utf-8') + (design / 'palette.toml').write_text('[roles.line]\nlight="#000000"\ndark="#ffffff"\n', encoding='utf-8') svg = design / 'svg/model' svg.mkdir(parents=True) for name in ('box', 'joint'): - (svg / (name + '.svg')).write_text('') + (svg / (name + '.svg')).write_text('', encoding='utf-8') # An accepted icon's note must never be exported, even if it still has text. original = {'final': {'box': ''}, 'notes': {'box': 'Keep it', 'joint': 'Round the corners\nUse related icons'}} - (design / 'review.json').write_text(json.dumps(original)) + (design / 'review.json').write_text(json.dumps(original), encoding='utf-8') with socket.socket() as port_socket: port_socket.bind(('127.0.0.1', 0)) port = port_socket.getsockname()[1] @@ -112,7 +112,7 @@ class IconExportTest(unittest.TestCase): self.assertEqual(result['sent'], 1) requests = list(inbox.glob('*.json')) self.assertEqual(len(requests), 1) - request = json.loads(requests[0].read_text()) + request = json.loads(requests[0].read_text(encoding='utf-8')) self.assertEqual(request['id'], result['request_id']) self.assertEqual(request['notes'], {'joint': original['notes']['joint']}) self.assertFalse(list(inbox.glob('*.tmp'))) @@ -123,14 +123,14 @@ class IconExportTest(unittest.TestCase): self.assertNotIn('Claude', page) self.assertIn('location.reload()', page) # Existing tabs also reload when the server's page implementation changes. - with open(tools / 'icon_status.py', 'a') as f: + with open(tools / 'icon_status.py', 'a', encoding='utf-8') as f: f.write('\n# page update\n') with urllib.request.urlopen(url + '/api/review', timeout=2) as response: self.assertNotEqual(json.load(response)['rev'], base['rev']) # A note resolved on disk cannot be resurrected by an unchanged stale page. - saved = json.loads((design / 'review.json').read_text()) + saved = json.loads((design / 'review.json').read_text(encoding='utf-8')) saved['notes'] = {'box': 'Keep it'} - (design / 'review.json').write_text(json.dumps(saved)) + (design / 'review.json').write_text(json.dumps(saved), encoding='utf-8') empty = post('/api/export', state) self.assertEqual(empty['sent'], 0) self.assertEqual(len(list(inbox.glob('*.json'))), 1) diff --git a/tests/tools/test_icon_line_endings.py b/tests/tools/test_icon_line_endings.py new file mode 100644 index 000000000..52bd40588 --- /dev/null +++ b/tests/tools/test_icon_line_endings.py @@ -0,0 +1,39 @@ +"""The icon tools read a checkout with CRLF line endings (Git for Windows' default) as the LF text committed (#1930).""" +from pathlib import Path +import sys +import tempfile +import unittest + +TOOLS = Path(__file__).resolve().parents[2] / 'assets/icons/ui/design/tools' +sys.path.insert(0, str(TOOLS)) +import icon_palette # noqa: E402 +import review_state # noqa: E402 + +SVG = '\n\n\n' + + +class LineEndingTest(unittest.TestCase): + def test_an_accepted_icon_hashes_the_same_checked_out_with_crlf(self): + with tempfile.TemporaryDirectory() as temporary: + hashes = [] + for newline in (b'\n', b'\r\n'): + design = Path(temporary) / ('crlf' if newline == b'\r\n' else 'lf') + (design / 'svg/model').mkdir(parents=True) + (design / 'svg/model/box.svg').write_bytes(SVG.encode().replace(b'\n', newline)) + hashes.append(review_state.master_hash('box', str(design))) + self.assertEqual(hashes[0], hashes[1]) + + def test_a_palette_checked_out_with_crlf_takes_a_save_at_its_own_revision(self): + palette = '# roles\n[roles.ink]\nlight = "#111111"\ndark = "#eeeeee"\n' + with tempfile.TemporaryDirectory() as temporary: + path = Path(temporary) / 'palette.toml' + path.write_bytes(palette.encode().replace(b'\n', b'\r\n')) + lf = Path(temporary) / 'lf.toml' + lf.write_bytes(palette.encode()) + self.assertEqual(icon_palette.revision(path), icon_palette.revision(lf)) + icon_palette.save_colours(path, icon_palette.revision(path), {'roles.ink': {'light': '#222222', 'dark': '#dddddd'}}) + self.assertIn('dark = "#dddddd"', path.read_text(encoding='utf-8')) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/tools/test_icon_review.py b/tests/tools/test_icon_review.py index a61d8b34b..bcdf256d8 100644 --- a/tests/tools/test_icon_review.py +++ b/tests/tools/test_icon_review.py @@ -26,11 +26,11 @@ def review_fixture(): design = root / 'assets/icons/ui/design' shutil.copytree(TOOLS, design / 'tools') (design / 'svg/model').mkdir(parents=True) - (design / 'svg/model/box.svg').write_text(SVG) + (design / 'svg/model/box.svg').write_text(SVG, encoding='utf-8') shutil.copy2(TOOLS.parent / 'palette.toml', design / 'palette.toml') - (design / 'references.toml').write_text('[category.model]\nlabel="Model"\nrule="Standard projection"\nicons=["box"]\n') - (design / 'aliases.toml').write_text('[alias]\nbox_alias="box"\n') - (design / 'review.json').write_text(json.dumps({'final': {'box': ''}, 'notes': {}})) + (design / 'references.toml').write_text('[category.model]\nlabel="Model"\nrule="Standard projection"\nicons=["box"]\n', encoding='utf-8') + (design / 'aliases.toml').write_text('[alias]\nbox_alias="box"\n', encoding='utf-8') + (design / 'review.json').write_text(json.dumps({'final': {'box': ''}, 'notes': {}}), encoding='utf-8') with socket.socket() as available: available.bind(('127.0.0.1', 0)) port = available.getsockname()[1] @@ -99,7 +99,7 @@ class IconReviewTest(unittest.TestCase): def test_live_palette_tokens_save_only_display_colours_and_reject_stale_or_invalid_changes(self): with review_fixture() as (root, design, get, post): palette_path = design / 'palette.toml' - original = palette_path.read_text() + original = palette_path.read_text(encoding='utf-8') palette = tomllib.loads(original) state = json.loads(get('/api/palette')) tokens = {token['id']: token for token in state['tokens']} @@ -125,9 +125,9 @@ class IconReviewTest(unittest.TestCase): target = expected for part in key.split('.'): target = target[part] target.update(colours) - self.assertEqual(tomllib.loads(palette_path.read_text()), expected) - self.assertIn('# Icon colour roles.', palette_path.read_text(), 'comments remain intact') - self.assertEqual(tomllib.loads(palette_path.read_text())['roles']['ink']['source'], palette['roles']['ink']['source']) + self.assertEqual(tomllib.loads(palette_path.read_text(encoding='utf-8')), expected) + self.assertIn('# Icon colour roles.', palette_path.read_text(encoding='utf-8'), 'comments remain intact') + self.assertEqual(tomllib.loads(palette_path.read_text(encoding='utf-8'))['roles']['ink']['source'], palette['roles']['ink']['source']) for revision, changes in [ (state['revision'], {'roles.ink': paints}), (saved['revision'], {'roles.ink.source': paints}), @@ -152,7 +152,7 @@ class IconReviewTest(unittest.TestCase): with review_fixture() as (root, design, get, post): source = '''''' path = design / 'svg/model/cutout.svg' - path.write_text(source) + path.write_text(source, encoding='utf-8') accepted = (design / 'review.json').read_bytes() page = get('/') fragments = [svg for svg in re.findall(r'', page, re.S) if '-base"' in svg] @@ -172,17 +172,17 @@ class IconReviewTest(unittest.TestCase): self.assertTrue(foreground.get('id').endswith('-foreground')) self.assertIsNone(foreground.get('mask')) self.assertNotIn('roles-gap-', svg) - self.assertEqual(path.read_text(), source) + self.assertEqual(path.read_text(encoding='utf-8'), source) self.assertEqual((design / 'review.json').read_bytes(), accepted) def test_semantic_colours_reload_from_one_palette_without_changing_acceptance(self): with review_fixture() as (root, design, get, post): palette = design / 'palette.toml' - colours = tomllib.loads(palette.read_text()) + colours = tomllib.loads(palette.read_text(encoding='utf-8')) source = colours['roles']['active-3'].get('source', colours['roles']['active-3']['light']) art = SVG.replace('currentColor', source) for name in ('line', 'c_fix'): - (design / f'svg/model/{name}.svg').write_text(art) + (design / f'svg/model/{name}.svg').write_text(art, encoding='utf-8') with (design / 'aliases.toml').open('a') as aliases: aliases.write('ground="c_fix"\nsurface_line={master="line",accent="surface"}\n') state, accepted = get('/api/review'), (design / 'review.json').read_bytes() @@ -198,13 +198,13 @@ class IconReviewTest(unittest.TestCase): self.assertIn(colours['accents']['surface']['active-3']['light'], card(page, 'surface_line'), 'explicit alias accent wins over the Sketch master') def set_light(section, colour): - lines, current = palette.read_text().splitlines(), '' + lines, current = palette.read_text(encoding='utf-8').splitlines(), '' for index, line in enumerate(lines): if line.strip().startswith('['): current = line.strip().split(']', 1)[0] + ']' elif current == '[' + section + ']' and line.split('=', 1)[0].strip() == 'light': lines[index] = 'light = ' + json.dumps(colour) - palette.write_text('\n'.join(lines) + '\n') + palette.write_text('\n'.join(lines) + '\n', encoding='utf-8') return self.fail('missing palette section ' + section) replacement = '#123456' if colours['accents']['sketch']['active-3']['light'] != '#123456' else '#654321' @@ -215,7 +215,7 @@ class IconReviewTest(unittest.TestCase): set_light('roles.active-3', base) self.assertIn(base, card(get('/'), 'ground'), 'source identifiers survive changing the base display palette too') self.assertEqual((design / 'review.json').read_bytes(), accepted) - self.assertEqual((design / 'svg/model/line.svg').read_text(), art) + self.assertEqual((design / 'svg/model/line.svg').read_text(encoding='utf-8'), art) def test_new_unused_masters_and_alias_targets_are_never_hidden(self): with review_fixture() as (root, design, get, post): @@ -223,7 +223,7 @@ class IconReviewTest(unittest.TestCase): page = get('/') self.assertIn('data-id="box"', page, 'unused alias target must still have a card') self.assertIn('data-id="box_alias"', page) - (design / 'svg/model/brand_new.svg').write_text(SVG) + (design / 'svg/model/brand_new.svg').write_text(SVG, encoding='utf-8') current = get('/api/review') self.assertNotEqual(original['rev'], current['rev']) self.assertNotIn('brand_new', current['final']) @@ -241,25 +241,25 @@ class IconReviewTest(unittest.TestCase): with review_fixture() as (root, design, get, post): initial = get('/api/review') self.assertIn('box', initial['final']) - old_hash = json.loads((design / 'review.json').read_text())['final']['box'] - (design / 'svg/model/box.svg').write_text(SVG.replace('r="20"', 'r="18"')) + old_hash = json.loads((design / 'review.json').read_text(encoding='utf-8'))['final']['box'] + (design / 'svg/model/box.svg').write_text(SVG.replace('r="20"', 'r="18"'), encoding='utf-8') changed = get('/api/review') self.assertNotIn('box', changed['final']) self.assertIn('changed since acceptance', get('/')) - self.assertEqual(old_hash, json.loads((design / 'review.json').read_text())['final']['box']) - (design / 'svg/model/box.svg').write_text(SVG.replace('r="20"', 'r="17"')) + self.assertEqual(old_hash, json.loads((design / 'review.json').read_text(encoding='utf-8'))['final']['box']) + (design / 'svg/model/box.svg').write_text(SVG.replace('r="20"', 'r="17"'), encoding='utf-8') with self.assertRaises(urllib.error.HTTPError) as error: post(changed, final=['box']) self.assertEqual(error.exception.code, 400) post(get('/api/review'), final=['box']) self.assertIn('box', get('/api/review')['final']) - self.assertNotEqual(old_hash, json.loads((design / 'review.json').read_text())['final']['box']) + self.assertNotEqual(old_hash, json.loads((design / 'review.json').read_text(encoding='utf-8'))['final']['box']) def test_missing_art_is_visible_but_cannot_be_accepted(self): with review_fixture() as (root, design, get, post): commands = root / 'crates/engine/src/cmd' commands.mkdir(parents=True) - (commands / 'example.rs').write_text('CommandSpec::new("example.action", "Example", run).icon("missing");') + (commands / 'example.rs').write_text('CommandSpec::new("example.action", "Example", run).icon("missing");', encoding='utf-8') page = get('/') self.assertIn('data-id="missing"', page) self.assertIn('aria-label="Accept missing as final" disabled', page) @@ -275,16 +275,16 @@ class IconReviewTest(unittest.TestCase): state = get('/api/review') self.assertEqual(post(state, endpoint='/api/export')['sent'], 0) # A stale page changes another note; it must not resurrect replaced feedback. - saved = json.loads((design / 'review.json').read_text()) + saved = json.loads((design / 'review.json').read_text(encoding='utf-8')) saved['notes']['box'] = 'Newer feedback' - (design / 'review.json').write_text(json.dumps(saved)) + (design / 'review.json').write_text(json.dumps(saved), encoding='utf-8') post(state, notes={**state['notes'], 'box_alias': 'Another note'}) self.assertEqual(get('/api/review')['notes']['box'], 'Newer feedback') self.assertFalse(list(design.glob('*.tmp'))) def test_export_resolution_preserves_notes_added_since_the_snapshot(self): with review_fixture() as (root, design, get, post): - (design / 'svg/model/fresh.svg').write_text(SVG) + (design / 'svg/model/fresh.svg').write_text(SVG, encoding='utf-8') state = get('/api/review') post(state, notes={'fresh': 'Newer feedback'}) script = """ @@ -312,14 +312,14 @@ assert review_state.load()['notes'] == {} with review_fixture() as (root, design, get, post): # The fixture's palette is intentionally minimal; the scaffold uses # the real helper constants and emits an editable starter SVG. - (root / 'ATTRIBUTION.md').write_text('# Attribution\n') + (root / 'ATTRIBUTION.md').write_text('# Attribution\n', encoding='utf-8') command = [sys.executable, '-B', str(design / 'tools/author/new_icon.py')] first = subprocess.run(command + ['fresh_shape', '--base', 'cube'], capture_output=True, text=True) self.assertEqual(first.returncode, 0, first.stderr) artwork = design / 'svg/model/fresh_shape.svg' self.assertTrue(artwork.exists()) self.assertNotIn('fresh_shape', get('/api/review')['final']) - self.assertIn('fresh_shape.svg', (root / 'ATTRIBUTION.md').read_text()) + self.assertIn('fresh_shape.svg', (root / 'ATTRIBUTION.md').read_text(encoding='utf-8')) before = artwork.read_bytes() again = subprocess.run(command + ['fresh_shape'], capture_output=True, text=True) self.assertNotEqual(again.returncode, 0) From bd4eb42c2d5b6ef372f9b09c301efc77d87317de Mon Sep 17 00:00:00 2001 From: cronos Date: Tue, 20 Oct 2026 05:05:00 +0900 Subject: [PATCH 075/225] Pin analytic robustness and edge-contact scale regressions (#1950) * test: pin analytic robustness and edge-contact scale regressions * test: freeze patterned-bore reference after body grouping change --- crates/engine/src/fuzz.rs | 80 ++++++++++++++++++++++++++++ crates/kernel/tests/boolean_props.rs | 48 +++++++++++------ docs/robustness.md | 27 ++++++++++ 3 files changed, 140 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/fuzz.rs b/crates/engine/src/fuzz.rs index db78c2d80..c1f51c5f3 100644 --- a/crates/engine/src/fuzz.rs +++ b/crates/engine/src/fuzz.rs @@ -440,3 +440,83 @@ pub fn minimise(run: &Run) -> Run { } Run { seed: run.seed, steps, outcome, unsupported: Vec::new(), rejected: 0, boolean_fallbacks, boolean_reports_truncated } } + +#[cfg(test)] +mod tests { + use std::collections::BTreeMap; + + use super::*; + + #[allow(clippy::expect_used)] + fn body_measures(s: &Session) -> Vec { + s.model.state().bodies.iter().map(|b| solidcraft_kernel::measure(&b.body).expect("measure a valid body")).collect() + } + + fn seed_measures(seed: u64) -> Vec { + let (run, s) = run_session(seed, 8, &mut |_| {}); + assert_eq!(run.outcome.kind, "ok", "seed {seed}: {:?}", run.outcome); + body_measures(&s) + } + + /// Seed 34: a quarter cylinder R15 x 12.5, a spherical bite R2.5 centred + /// at (10, 12.5, 0), and an independent R2 x 5 blind drill with a 118° tip. + /// The circular-lens surface/volume integrals give these references + /// independently of the B-rep and its measurement tessellation (docs/robustness.md). + #[test] + fn a_spherical_bite_and_blind_drill_match_the_analytic_solid() { + let measured = seed_measures(34); + assert_eq!(measured.len(), 1); + let m = &measured[0]; + for (name, got, want) in [("volume", m.volume, 2_134.404_133), ("area", m.area, 1_086.316_691)] { + // measure uses a chordal mesh with a 5e-5 relative chord tolerance. + assert!((got - want).abs() <= 5e-5 * want, "{name}: {got} versus analytic {want}"); + } + assert_eq!(m.merged.face_types, BTreeMap::from([("cone".into(), 1), ("cylinder".into(), 2), ("plane".into(), 4), ("sphere".into(), 1)])); + } + + /// The recorded seed-67 design: a notched extrusion with bores and a boss, + /// and a chamfered block with a patterned bore. Freeze the commands because + /// retaining disconnected shells in one body (#2247) changes later generator picks. + /// Redundant raw subdivisions must preserve the original analytic surface inventory. + #[test] + fn a_patterned_bore_preserves_the_analytic_surfaces() { + let commands = [ + ("sketch.create", json!({"plane":"XY"})), + ("sketch.line", json!({"points":[[0,0],[30.0,0],[30.0,32.5],[17.5,32.5],[17.5,17.5],[10.0,17.5],[10.0,32.5],[0,32.5]]})), + ("sketch.arc.three_point", json!({"end":[0,0],"start":[0,32.5],"through":[-15.0,16.25]})), + ("sketch.finish", json!({})), + ("solid.extrude", json!({"distance":20.0})), + ("solid.cylinder", json!({"axis":[0.0,0.0,-1.0],"base":[-0.0,0.0,20.00000000000001],"height":2.5,"operation":"cut","radius":6.25})), + ("solid.hole", json!({"diameter":6.0,"position":[13.749999999999998,17.5,10.00000000000001]})), + ("solid.cylinder", json!({"axis":[0.0,0.0,1.0],"base":[-5.0,12.5,2.5],"height":30.0,"operation":"join","radius":3.75})), + ( + "solid.box", + json!({"corner":[-14.999881984669182,22.5,32.500000000000014],"height":20.0,"length":12.5,"operation":"join","width":12.5}), + ), + ("solid.hole", json!({"depth":12.5,"diameter":4.0,"position":[-8.749881984669182,28.75,32.500000000000014]})), + ( + "solid.chamfer", + json!({"distance":0.5,"edges":[[-2.499881984669182,28.75,32.500000000000014],[-9.900529629797113,27.11414854074047,32.500000000000014],[-8.749881984669182,35.0,32.500000000000014]]}), + ), + ("solid.pattern.rectangular", json!({"count1":2,"dir1":[1.0,0.0,0.0],"features":["Hole2"],"spacing1":7.5})), + ]; + let mut s = Session::default(); + for (command, params) in commands { + let result = s.execute(command, ¶ms); + assert!(result.is_ok(), "{command}: {result:?}"); + for body in &s.model.state().bodies { + assert!(body.body.validity().is_empty(), "{command}: {:?}", body.body.validity()); + } + } + let measured = body_measures(&s); + assert_eq!(measured.len(), 1); + assert_eq!(measured.iter().map(|m| m.shells).sum::(), 2); + let mut kinds = BTreeMap::new(); + for m in &measured { + for (kind, count) in &m.merged.face_types { + *kinds.entry(kind.clone()).or_insert(0) += count; + } + } + assert_eq!(kinds, BTreeMap::from([("cone".into(), 1), ("cylinder".into(), 6), ("plane".into(), 22)])); + } +} diff --git a/crates/kernel/tests/boolean_props.rs b/crates/kernel/tests/boolean_props.rs index 064d210a4..7fb11c31a 100644 --- a/crates/kernel/tests/boolean_props.rs +++ b/crates/kernel/tests/boolean_props.rs @@ -118,6 +118,25 @@ fn identity(a: &Prim, b: &Prim) -> Result<(), TestCaseError> { Ok(()) } +fn scale(a: &Prim, b: &Prim, k: f64) -> Result<(), TestCaseError> { + let sc = |p: &Prim| match p.clone() { + Prim::Box { at, size } => Prim::Box { at: at.map(|x| x * k), size: size.map(|x| x * k) }, + Prim::Cyl { at, axis, r, h } => Prim::Cyl { at: at.map(|x| x * k), axis, r: r * k, h: h * k }, + Prim::Sph { at, r } => Prim::Sph { at: at.map(|x| x * k), r: r * k }, + }; + let (ba, bb, ka, kb) = (a.body(), b.body(), sc(a).body(), sc(b).body()); + let s = vol(&ba) + vol(&bb); + for op in [BoolOp::Union, BoolOp::Intersect, BoolOp::Cut] { + let (one, big) = (run(&ba, &bb, op), run(&ka, &kb, op)); + if edge_contact_refusal(a, b, op, &one) && edge_contact_refusal(a, b, op, &big) { + continue; + } + let (one, big) = (one?, big? / (k * k * k)); + prop_assert!(close(one, big, s), "{op:?} at scale 1 gives {one:.4}, at scale {k} gives {big:.4} (normalised)"); + } + Ok(()) +} + fn cfg(default: u32) -> ProptestConfig { // The env var overrides the default; proptest reads PROPTEST_CASES itself only when the // config does not set `cases`, so read it here. @@ -186,21 +205,7 @@ proptest! { /// (40x) expose tolerances that do not scale. #[test] fn scale_invariant(a in grid_prim(), b in grid_prim(), k in prop::sample::select(vec![0.05, 1.0, 40.0])) { - let sc = |p: &Prim| match p.clone() { - Prim::Box { at, size } => Prim::Box { at: at.map(|x| x * k), size: size.map(|x| x * k) }, - Prim::Cyl { at, axis, r, h } => Prim::Cyl { at: at.map(|x| x * k), axis, r: r * k, h: h * k }, - Prim::Sph { at, r } => Prim::Sph { at: at.map(|x| x * k), r: r * k }, - }; - let (ba, bb, ka, kb) = (a.body(), b.body(), sc(&a).body(), sc(&b).body()); - let s = vol(&ba) + vol(&bb); - for op in [BoolOp::Union, BoolOp::Intersect, BoolOp::Cut] { - let (one, big) = (run(&ba, &bb, op), run(&ka, &kb, op)); - if edge_contact_refusal(&a, &b, op, &one) && edge_contact_refusal(&a, &b, op, &big) { - continue; - } - let (one, big) = (one?, big? / (k * k * k)); - prop_assert!(close(one, big, s), "{op:?} at scale 1 gives {one:.4}, at scale {k} gives {big:.4} (normalised)"); - } + scale(&a, &b, k)?; } /// A∪A = A, A∩A = A, A−A = nothing. @@ -279,6 +284,19 @@ fn edge_only_box_join_is_refused_in_both_orders() { } } +/// The saved scale-invariance failure: these boxes meet at y=30, z=20 along an +/// edge, so a join is refused at every scale. Intersection and cut still scale. +#[test] +fn edge_only_box_contact_is_scale_invariant() { + let a = Prim::Box { at: [0.0, 15.0, 7.5], size: [7.5, 15.0, 12.5] }; + let b = Prim::Box { at: [0.0, 30.0, 20.0], size: [5.0, 5.0, 5.0] }; + assert!(edge_only_boxes(&a, &b)); + for k in [0.05, 1.0, 40.0] { + check(scale(&a, &b, k)); + check(scale(&b, &a, k)); + } +} + fn check(r: Result<(), TestCaseError>) { if let Err(e) = r { panic!("{e}"); diff --git a/docs/robustness.md b/docs/robustness.md index 4aec674eb..168601cea 100644 --- a/docs/robustness.md +++ b/docs/robustness.md @@ -63,6 +63,33 @@ ROBUSTNESS_GOLDENS_BLESS="why it changed" cargo test --profile ci -p solidcraft- The changed seeds and the reason are added to the file's `notes`; say why in the pull request too. +The generator feeds the current geometry's bounds and face/edge picks back into later +commands. The same RNG seed can therefore generate different command coordinates or picks +on different math libraries. The original inputs are retained, including near-contact cases. +Platform snapshots track repeatability; they do not certify cross-platform geometric +equivalence or resolve the numerical differences tracked in #924. + +### Independent measurement checks + +The seeded snapshots also have checks against geometric references. Seed 34 starts with a +quarter cylinder of radius 15 and height 12.5 (`x,y >= 0`, `-12.5 <= z <= 0`), cuts it with a +radius-2.5 sphere centred at (10, 12.5, 0), then drills an independent radius-2, depth-5 blind +hole from (0, 7.5, -6.25) along +X, with a 118-degree tip. +Subtracting the sphere/cylinder intersection and the drill gives **2134.404133 mm³** and +**1086.316691 mm²**. The drill has tip height `2 / tan(59 degrees)`; the spherical bite is +integrated over the intersection of the radius-15 disk and the sphere's projected radius-2.5 +disk. Integrating the lower spherical hemisphere and the removed cylinder-wall patch gives +the surface reference. The test compares the chordal measurement with these independent +references at 5e-5 relative error. + +A fixed command replay recorded from seed 67 checks two disconnected shells kept in one +body after a cut (#2247), with a combined analytic surface inventory of 22 planar, six +cylindrical and one conical face after merging redundant subdivisions. The commands are +fixed because the generator chooses later operations from the current body and edge layout; +changes to body grouping can therefore change the generated design. This preserves the +original geometric reference independently of those choices. These checks supplement the +snapshots' stricter repeatability comparisons of raw topology and tessellated measurements. + ## Successful Boolean retries When an accepted Boolean result needs a retry that can make it differ from the From b3f205a6388eea005bad557efc9e4375bec88933 Mon Sep 17 00:00:00 2001 From: DuBearte <130190089+DuBearte@users.noreply.github.com> Date: Mon, 19 Oct 2026 16:05:17 -0400 Subject: [PATCH 076/225] Agent chat: the design bridge gets its own MCP name, so a user's solidcraft entry can't shadow it (#2592) (#2596) * claim: #2592 * fix(agent-chat): the design bridge is named solidcraft-app (#2592) A user's own MCP entry named `solidcraft` (as docs/mcp.md suggests) took the bridge's place in agents that keep their own entry on a name clash, so the chat worked on a headless session instead of the open design. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: bherbruck --- crates/ui-egui/src/agent_chat/acp.rs | 23 ++++++++++++++++++++--- docs/agent-chat.md | 4 +++- 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/agent_chat/acp.rs b/crates/ui-egui/src/agent_chat/acp.rs index 56c159edd..96555942a 100644 --- a/crates/ui-egui/src/agent_chat/acp.rs +++ b/crates/ui-egui/src/agent_chat/acp.rs @@ -44,6 +44,11 @@ pub fn initialize_params(version: &str) -> Value { }) } +/// The name the chat gives its MCP server (#2592): not `solidcraft`, the name docs/mcp.md suggests +/// for a user's own setup, so an agent that merges its own MCP servers with the session's (Codex +/// keeps its own entry on a clash) can't shadow the bridge with a headless session. +pub const BRIDGE_NAME: &str = "solidcraft-app"; + /// The MCP server the agent starts to reach the design: `solidcraft-cli mcp --connect` bridged to /// this app's control port. The server finds the port's token in the token file the app wrote /// (docs/control-protocol.md), so the token never travels through the agent, and it keeps its @@ -57,7 +62,7 @@ pub struct McpBridge { impl McpBridge { pub fn to_json(&self) -> Value { json!({ - "name": "solidcraft", + "name": BRIDGE_NAME, "command": self.cli.to_string_lossy(), "args": ["mcp", "--connect", format!("127.0.0.1:{}", self.port)], "env": [], @@ -67,7 +72,7 @@ impl McpBridge { /// What every session is told about where it is. Agents that don't read `_meta` ignore it. pub const SYSTEM_NOTE: &str = "You are running inside SolidCraft, a parametric 3D CAD application, as the user's assistant. \ -The open design is reachable through the `solidcraft` MCP server: use its tools (list_commands, batch, execute, inspect_design, \ +The open design is reachable through the `solidcraft-app` MCP server: use its tools (list_commands, batch, execute, inspect_design, \ measure, screenshot, set_parameter, undo) to read and change the design the user is looking at, and verify with measure or \ inspect_design. Prefer one `batch` over many small calls. Saving, opening or exporting files waits for the user's approval in \ the chat, and each message allows a limited number of changes. Don't use shell or file tools: work through the SolidCraft tools. \ @@ -483,12 +488,24 @@ mod tests { assert!(split_command(" ").is_empty()); } + /// #2592: the bridge is not called `solidcraft`, the name a user's own MCP entry takes from + /// docs/mcp.md, and the note tells the agent the name it really has. + #[test] + fn the_bridge_has_a_name_of_its_own_and_the_note_uses_it() { + assert_ne!(BRIDGE_NAME, "solidcraft"); + assert!(SYSTEM_NOTE.contains(&format!("`{BRIDGE_NAME}` MCP server")), "{SYSTEM_NOTE}"); + assert!(!SYSTEM_NOTE.contains("`solidcraft` MCP server")); + // The panel still recognises the bridge's tools as SolidCraft's (agents name them after + // their server, e.g. `mcp__solidcraft-app__batch`). + assert!(BRIDGE_NAME.contains("solidcraft")); + } + #[test] fn the_session_gets_the_bridged_mcp_server_without_a_token_or_any_path() { let b = McpBridge { cli: "/opt/solidcraft/solidcraft-cli".into(), port: 41234 }; let p = session_new_params(std::path::Path::new("/home/u/designs"), Some(&b)); let s = &p["mcpServers"][0]; - assert_eq!(s["name"], "solidcraft"); + assert_eq!(s["name"], BRIDGE_NAME); assert_eq!(s["args"], json!(["mcp", "--connect", "127.0.0.1:41234"])); let text = p.to_string(); assert!(!text.contains("allow-any-path") && !text.contains("TOKEN") && !text.contains("token"), "{text}"); diff --git a/docs/agent-chat.md b/docs/agent-chat.md index c5f14def8..b86aa3adc 100644 --- a/docs/agent-chat.md +++ b/docs/agent-chat.md @@ -185,7 +185,9 @@ Whatever you typed before signing in is sent once the agent is ready. ## What the agent can do The agent reaches the open design only through SolidCraft's own tools (the -[MCP server](mcp.md)), which SolidCraft hands it when the chat starts: +[MCP server](mcp.md)), which SolidCraft hands it when the chat starts. That server is named +`solidcraft-app`, so an MCP server you set up yourself under the name `solidcraft` (as in +[client configuration](mcp.md#client-configuration)) doesn't take its place: - **Read the design:** list commands, inspect features, sketches and parameters, measure, take pictures of the view. From b20e693c2eee848230c7c771cec478d36a98c8a8 Mon Sep 17 00:00:00 2001 From: phanoob Date: Mon, 19 Oct 2026 22:05:28 +0200 Subject: [PATCH 077/225] Sketch text: a letter crossed by an edge is picked whole with its text (#2619) Co-authored-by: Phanoob Co-authored-by: Claude Opus 5.5 Co-authored-by: bherbruck --- crates/ui-egui/src/sketch_text.rs | 99 ++++++++++++++++++++----------- 1 file changed, 64 insertions(+), 35 deletions(-) diff --git a/crates/ui-egui/src/sketch_text.rs b/crates/ui-egui/src/sketch_text.rs index 3eb30bdce..69b352b41 100644 --- a/crates/ui-egui/src/sketch_text.rs +++ b/crates/ui-egui/src/sketch_text.rs @@ -118,49 +118,51 @@ pub(crate) fn one_letter() -> bool { ONE_LETTER.with(std::cell::Cell::get) } -/// A text is picked whole: the profiles of its letters when profile `index` of `sketch` is -/// bounded by one text alone (none when other geometry shares it). The letters' counters (the -/// inside of an O) are left out; inside one, a letter is a letter again. The picked profile -/// comes first when it is a letter. +/// A text is picked whole: the profiles of its letters when profile `index` of `sketch` is a +/// letter of one text, or the counter of one (none when it is bounded by other geometry alone, +/// or by two texts). A letter that other geometry crosses (a face's projected edge the text runs +/// over) is cut into pieces bounded by both: each piece inside the letter is picked, so the +/// letter is picked whole. The letters' counters (the inside of an O) are left out; inside one, +/// a letter is a letter again. The picked profile comes first when it is a letter. pub(crate) fn text_profiles(s: &solidcraft_engine::Session, sketch: u64, index: usize) -> Option> { let state = s.world_state(); let ss = state.sketch(sketch)?; - let text_of = |profile: &solidcraft_engine::sketch::Profile| -> Option { - let mut link: Option<&str> = None; + // The text bounding a profile, with or without other curves; whether only it bounds it. + let text_of = |profile: &solidcraft_engine::sketch::Profile| -> Option<(String, bool)> { + let (mut link, mut alone): (Option<&str>, bool) = (None, true); for id in profile.curve_ids() { let curve = ss.sketch.curves.iter().find(|curve| curve.id == id)?; - let source = ss.sketch.link(curve.link.as_deref()?)?; - if source.kind != LinkKind::Text || link.is_some_and(|old| old != source.id.as_str()) { - return None; - } - link = Some(source.id.as_str()); - } - link.map(str::to_owned) - }; - let link = text_of(ss.profiles.get(index)?)?; - let sorted = |ids: &[String]| { - let mut ids = ids.to_vec(); - ids.sort(); - ids - }; - let mine: Vec = (0..ss.profiles.len()).filter(|&i| ss.profiles.get(i).and_then(text_of).as_deref() == Some(link.as_str())).collect(); - // A profile whose outer loop is a hole of another one lies inside it. - let parent = |i: usize| -> Option { - let outer = sorted(&ss.profiles.get(i)?.outer_curves); - mine.iter().copied().find(|&j| j != i && ss.profiles.get(j).is_some_and(|p| p.hole_curves.iter().any(|hole| sorted(hole) == outer))) - }; - let depth = |i: usize| { - let (mut at, mut depth) = (i, 0usize); - while let Some(up) = parent(at) { - at = up; - depth += 1; - if depth > mine.len() { - break; + match curve.link.as_deref().and_then(|l| ss.sketch.link(l)).filter(|source| source.kind == LinkKind::Text) { + Some(source) if link.is_some_and(|old| old != source.id.as_str()) => return None, + Some(source) => link = Some(source.id.as_str()), + None => alone = false, } } - depth + link.map(|l| (l.to_owned(), alone)) }; - let mut letters: Vec = mine.iter().copied().filter(|&i| depth(i) % 2 == 0).collect(); + let (link, alone) = text_of(ss.profiles.get(index)?)?; + // The text's own outlines, the other curves left out: a point is in a letter when an odd + // number of them surround it (an O's ring is in one, its counter in two). + let mut own = ss.sketch.clone(); + for curve in &mut own.curves { + if curve.link.as_deref() != Some(link.as_str()) { + curve.construction = true; + } + } + let outlines = solidcraft_engine::sketch::find_profiles(&own); + let in_letter = |i: usize| { + ss.profiles.get(i).is_some_and(|p| { + let at = p.region.interior_point(); + outlines.iter().filter(|o| o.region.outer.contains(at)).count() % 2 == 1 + }) + }; + // A piece the text shares with other geometry is the text's only inside a letter: the region + // round the letters (a face's, bounded by its edges and the letters crossing them) is not. + if !alone && !in_letter(index) { + return None; + } + let mut letters: Vec = + (0..ss.profiles.len()).filter(|&i| ss.profiles.get(i).and_then(text_of).is_some_and(|(l, _)| l == link) && in_letter(i)).collect(); letters.sort_by_key(|&i| i != index); (!letters.is_empty()).then_some(letters) } @@ -1359,6 +1361,33 @@ mod tests { assert!(text_profiles(&h.app.session, sid, 99).is_none()); } + /// The text runs over the edge of what it is drawn on (a face's projected edge, here a drawn + /// rectangle whose top crosses both letters): each letter is cut into pieces bounded by the + /// text and the edge. A click on a piece still picks the whole text, every piece of both + /// letters and nothing else; a click round the letters picks no text. + #[test] + fn a_text_crossed_by_an_edge_is_picked_whole() { + let (mut h, sid, i, _, _) = letters(); + let area = |h: &Harness, picked: &[usize]| { + let state = h.app.session.world_state(); + let profiles = &state.sketch(sid).unwrap().profiles; + picked.iter().map(|&k| profiles[k].region.area()).sum::() + }; + let whole = area(&h, &text_profiles(&h.app.session, sid, i).unwrap()); + // The I's stem, below where the rectangle's top will cross it. + let stem = solidcraft_engine::geom::Vec2::new(h.app.session.world_state().sketch(sid).unwrap().profiles[i].centroid.x, 2.0); + h.app.run("sketch.rectangle.two_point", json!({"p0":[-5,-5],"p1":[40,8]})).unwrap(); + let state = h.app.session.world_state(); + let profiles = &state.sketch(sid).unwrap().profiles; + let below = solidcraft_engine::sketch::profile_at_point(profiles, stem).unwrap(); + let picked = text_profiles(&h.app.session, sid, below).unwrap(); + assert_eq!(picked[0], below); + assert!(picked.len() > 2, "the letters are cut in pieces: {picked:?}"); + assert!((area(&h, &picked) - whole).abs() < 1e-5 * whole, "{} {whole}", area(&h, &picked)); + let round = solidcraft_engine::sketch::profile_at_point(profiles, solidcraft_engine::geom::Vec2::new(-3.0, -3.0)).unwrap(); + assert!(text_profiles(&h.app.session, sid, round).is_none()); + } + #[test] fn clicking_a_letter_selects_the_whole_text_for_an_extrude() { let (mut h, sid, i, ring, _) = letters(); From d306d6e658dd849693f1554db35f67b80d8d3dd8 Mon Sep 17 00:00:00 2001 From: CamWight <91156642+CamWight@users.noreply.github.com> Date: Mon, 19 Oct 2026 21:05:45 +0100 Subject: [PATCH 078/225] Two-sided extrudes: through all (or To Object) on either side, a distance on the other (#2700) (#2728) * claim: #2700 * Two-sided extrudes: the second distance goes the other way from the first side, either way round (#2700) extent_sides ignored `direction` when an extrude had `distance2`, so through all with `direction: negative` and a second distance went the positive way. The second distance now goes opposite the first side wherever that went (direction: negative, a negative distance, a To Object below the sketch). A pending format step makes older designs' reversed two-sided extrudes positive, which keeps their shape. The Extrude dialog's Two Sides shows Distance 2 for every extent type (it was hidden for All and To Object but still sent as 10 mm) and offers Reverse; the second arrow points the other way from the first. Co-Authored-By: Claude Opus 5.5 * The two-sided arrows test checks each tip against the sketch, not just their order Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/doc/src/document.rs | 4 +- crates/doc/src/eval.rs | 10 +++- .../pending/two-sided-extrude-direction.rs | 49 ++++++++++++++++ .../src/cmd/extrude_convention_tests.rs | 57 +++++++++++++++++++ crates/engine/src/cmd/features.rs | 2 +- crates/ui-egui/src/canvas.rs | 8 +-- crates/ui-egui/src/dialogs.rs | 51 ++++++++++++----- crates/ui-egui/src/extrude_edit_tests.rs | 48 ++++++++++++++++ 8 files changed, 209 insertions(+), 20 deletions(-) create mode 100644 crates/doc/src/format/pending/two-sided-extrude-direction.rs diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 34bae024e..ca0479a30 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -233,7 +233,9 @@ pub struct Extent { pub convention: ExtrudeConvention, #[serde(default)] pub direction: Direction, - /// Optional second side distance (two-sided extrude), along the negative normal. + /// Optional second side distance (two-sided extrude): the other way from the first side (against + /// the normal, or along it when the first side goes against it: `direction: negative`, a + /// negative distance, or a To Object below the sketch). #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(length = "Distance 2")] pub distance2: Option, diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 153b2561f..615dbb2e8 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -4072,9 +4072,17 @@ fn path_segments(ps: &SolvedSketch, ids: &[String], start: Vec3) -> Result, extent: &crate::Extent, d: f64, direction: crate::Direction) -> Result<(f64, f64)> { Ok(match (&extent.distance2, direction) { - (Some(d2), _) => (-val(vals, d2, Kind::Length)?, d), + (Some(d2), _) => { + let first = if direction == crate::Direction::Negative { -d } else { d }; + let d2 = val(vals, d2, Kind::Length)?; + (if first < 0.0 { d2 } else { -d2 }, first) + } (None, crate::Direction::Positive) => (0.0, d), (None, crate::Direction::Negative) => (-d, 0.0), (None, crate::Direction::Symmetric) => { diff --git a/crates/doc/src/format/pending/two-sided-extrude-direction.rs b/crates/doc/src/format/pending/two-sided-extrude-direction.rs new file mode 100644 index 000000000..4f54c39ee --- /dev/null +++ b/crates/doc/src/format/pending/two-sided-extrude-direction.rs @@ -0,0 +1,49 @@ +//! A two-sided extrude (`distance2`) follows its `direction` (#2700): with `direction: negative` +//! the first distance goes against the sketch normal and `distance2` along it, so either side can +//! be the through-all or To Object one. Older builds ignored `direction` when an extrude had a +//! second distance (the first always went along the normal), so this step makes the two-sided +//! `negative` extrudes of older designs `positive`, which keeps their shape. 0.15.x asks for an +//! update instead of opening a design with a reversed two-sided extrude. +use serde_json::Value; + +pub fn step(v: &mut Value) -> crate::Result<()> { + let Some(Value::Array(features)) = v.get_mut("features") else { + return Ok(()); + }; + for feature in features { + if !matches!(feature.get("type").and_then(Value::as_str), Some("extrude" | "surface_extrude")) { + continue; + } + if let Some(extent) = feature.get_mut("extent").and_then(Value::as_object_mut) + && extent.get("distance2").is_some_and(|d| !d.is_null()) + && extent.get("direction").and_then(Value::as_str) == Some("negative") + { + extent.insert("direction".into(), Value::from("positive")); + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + #[test] + fn older_reversed_two_sided_extrudes_keep_their_shape() { + let mut v = json!({"features": [ + {"type": "extrude", "extent": {"distance": "10 mm", "direction": "negative", "distance2": "5 mm"}}, + {"type": "surface_extrude", "extent": {"distance": "10 mm", "direction": "negative", "distance2": "5 mm"}}, + {"type": "extrude", "extent": {"distance": "10 mm", "direction": "negative"}}, + {"type": "extrude", "extent": {"distance": "10 mm", "direction": "symmetric", "distance2": "5 mm"}}, + {"type": "revolve", "extent": {"direction": "negative", "distance2": "5 mm"}}, + {"type": "sketch"} + ]}); + super::step(&mut v).unwrap(); + let dirs: Vec> = v["features"].as_array().unwrap().iter().map(|f| f["extent"]["direction"].as_str()).collect(); + assert_eq!(dirs, [Some("positive"), Some("positive"), Some("negative"), Some("symmetric"), Some("negative"), None]); + // A design with no features is left alone. + let mut empty = json!({"name": "Untitled"}); + super::step(&mut empty).unwrap(); + assert_eq!(empty, json!({"name": "Untitled"})); + } +} diff --git a/crates/engine/src/cmd/extrude_convention_tests.rs b/crates/engine/src/cmd/extrude_convention_tests.rs index def426979..09d2a223e 100644 --- a/crates/engine/src/cmd/extrude_convention_tests.rs +++ b/crates/engine/src/cmd/extrude_convention_tests.rs @@ -141,3 +141,60 @@ fn surface_extrude_shared_extent_retains_its_existing_per_side_semantics() { check_sheet(&s); check_sheet(&Session::new(Document::from_json(&s.doc.to_json()).unwrap())); } + +/// A second distance goes the other way from the first side (#2700): along the normal when the +/// first side goes against it, whether by `direction: negative` or by a negative distance. +#[test] +fn a_second_distance_goes_the_other_way_from_the_first_side() { + for (settings, lo, hi) in [ + (json!({"direction":"positive","distance":"10 mm","distance2":"4 mm"}), -4.0, 10.0), + (json!({"direction":"negative","distance":"10 mm","distance2":"4 mm"}), -10.0, 4.0), + (json!({"direction":"positive","distance":"-10 mm","distance2":"4 mm"}), -10.0, 4.0), + ] { + let s = fixture(settings.clone()); + check(&s, lo, hi); + // Saved and opened again, it keeps its sides. + check(&Session::new(Document::from_json(&s.doc.to_json()).unwrap()), lo, hi); + } +} + +/// Through all on one side and a distance on the other, either way round (#2700). A 40 mm cube +/// round the origin, and an r5 hole sketched 10 mm above its middle: through all goes 10 mm up +/// or 30 mm down to the cube's faces, and the 5 mm goes the other way. +#[test] +fn through_all_on_either_side_with_a_distance_on_the_other() { + let hole = std::f64::consts::PI * 25.0; + for (direction, depth) in [("positive", 15.0), ("negative", 35.0)] { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length":40,"width":40,"height":40,"corner":[-20,-20,-20],"body_name":"Box"})); + run(&mut s, "construct.plane.offset", json!({"base":"XY","offset":10,"name":"Above"})); + run(&mut s, "sketch.create", json!({"plane":"Above","name":"Hole"})); + run(&mut s, "sketch.circle.center", json!({"center":[0,0],"radius":5})); + run(&mut s, "sketch.finish", json!({})); + run( + &mut s, + "solid.extrude", + json!({"sketch":"Hole","through_all":true,"distance2":"5 mm","direction":direction,"operation":"cut","targets":["Box"]}), + ); + assert!(s.model.results.iter().all(|r| r.error.is_none())); + let st = s.model.state(); + let m = solidcraft_kernel::measure(&st.body("Box").unwrap().body).unwrap(); + // The hole's depth from the volume removed (within the circle's measuring precision). + let deep = (64000.0 - m.volume) / hole; + assert!((deep - depth).abs() < 0.05, "{direction}: {deep} deep, want {depth}"); + } +} + +/// Designs saved before #2700 ignored `direction` on a two-sided extrude; opening one keeps its +/// shape: its first distance still goes along the normal. +#[test] +fn an_older_reversed_two_sided_extrude_keeps_its_shape() { + let s = fixture(json!({"direction":"negative","distance":"10 mm","distance2":"4 mm"})); + let mut saved: Value = serde_json::from_str(&s.doc.to_json()).unwrap(); + saved["format"] = json!("solidcraft/27"); + saved.as_object_mut().unwrap().remove("format_pending"); + let s = Session::new(Document::from_json(&saved.to_string()).unwrap()); + check(&s, -4.0, 10.0); + let FeatureKind::Extrude { extent, .. } = &s.doc.find_feature("Depth").unwrap().kind else { panic!("extrude") }; + assert_eq!(extent.direction, solidcraft_doc::Direction::Positive); +} diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs index 66fd62490..1b517e1a1 100644 --- a/crates/engine/src/cmd/features.rs +++ b/crates/engine/src/cmd/features.rs @@ -18,7 +18,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .at("SOLID", "CREATE") .icon("extrude") .key("E") - .params("distance: expr (or through_all: true); taper?: angle expr; sketch?: id|name (default: active or last sketch); profiles?: all | [index] | [{curves: [ids]}] (the profile whose outer loop is made of exactly these curves, or pieces of them; found again on every recompute, so it follows parameter changes; islands inside are its holes; an error when no profile or several match) | [{point:[x,y]}] (index and point picks are stored by their curves when that finds the same profile); face?: [x,y,z] (extrude a planar body face instead of a sketch profile); faces?: [[x,y,z],…] (coplanar faces of one body); face_body?: name (whose face, where faces of several bodies meet at the point); direction?: positive|negative|symmetric (distance is total thickness, split evenly around the start plane); convention?: total_distance|legacy_per_side (default total_distance; legacy preserves older symmetric extents); distance2?; start_offset?: expr (along the sketch normal, also with direction: negative); to?: [x,y,z] (To Object: a face, vertex or point; to_offset?: expr past it); from?: [x,y,z] (From Object: start at that face or point); operation?: new|join|cut|intersect|auto (cut into a body, otherwise join existing solids; new in an empty component); targets?: [body] (Join from a face, or from a sketch on a body's face, defaults to that face's body; explicit targets or participants override); name?; body_name?; thin?: true (Thin: a wall along sketch curves instead of the profiles) with curves?: [curve ids] (open chains and closed loops, joined where they meet end to end; default: every drawn curve of the sketch), thickness: expr, side?: center|inside|outside|two_sides (a closed loop's inside is the area it encloses, an open chain's the side it bends toward, a straight line's the left of its first curve as drawn; default center), thickness2?: expr (two_sides: the thickness outside); corners are mitred, crossing walls are one"), + .params("distance: expr (or through_all: true); taper?: angle expr; sketch?: id|name (default: active or last sketch); profiles?: all | [index] | [{curves: [ids]}] (the profile whose outer loop is made of exactly these curves, or pieces of them; found again on every recompute, so it follows parameter changes; islands inside are its holes; an error when no profile or several match) | [{point:[x,y]}] (index and point picks are stored by their curves when that finds the same profile); face?: [x,y,z] (extrude a planar body face instead of a sketch profile); faces?: [[x,y,z],…] (coplanar faces of one body); face_body?: name (whose face, where faces of several bodies meet at the point); direction?: positive|negative|symmetric (distance is total thickness, split evenly around the start plane); convention?: total_distance|legacy_per_side (default total_distance; legacy preserves older symmetric extents); distance2?: expr (Two Sides: a second distance the other way from the first side, which may be through_all or to; with direction: negative the first side goes against the normal and distance2 along it); start_offset?: expr (along the sketch normal, also with direction: negative); to?: [x,y,z] (To Object: a face, vertex or point; to_offset?: expr past it); from?: [x,y,z] (From Object: start at that face or point); operation?: new|join|cut|intersect|auto (cut into a body, otherwise join existing solids; new in an empty component); targets?: [body] (Join from a face, or from a sketch on a body's face, defaults to that face's body; explicit targets or participants override); name?; body_name?; thin?: true (Thin: a wall along sketch curves instead of the profiles) with curves?: [curve ids] (open chains and closed loops, joined where they meet end to end; default: every drawn curve of the sketch), thickness: expr, side?: center|inside|outside|two_sides (a closed loop's inside is the area it encloses, an open chain's the side it bends toward, a straight line's the left of its first curve as drawn; default center), thickness2?: expr (two_sides: the thickness outside); corners are mitred, crossing walls are one"), CommandSpec::new("solid.revolve", "Revolve", revolve) .at("SOLID", "CREATE") .icon("revolve") diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index c4f880487..d3cd1bae9 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -378,7 +378,7 @@ fn draw(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj, 1.0 } } - (_, Kind::Extrude { direction: 1, .. }) => -1.0, + (_, Kind::Extrude { direction: 1 | crate::dialogs::TWO_SIDES_REVERSED, .. }) => -1.0, _ => 1.0, }; let symmetric = to_span.is_none() && matches!(d.kind, Kind::Extrude { direction: 2, .. }); @@ -411,11 +411,11 @@ fn draw(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj, } return; } - // Two sides: the second distance gets its own arrow the other way. - if let (Kind::Extrude { direction: crate::dialogs::TWO_SIDES, distance2, .. }, Some(n)) = (&mut d.kind, dir) + // Two sides: the second distance gets its own arrow, the other way from the first side. + if let (Kind::Extrude { direction: crate::dialogs::TWO_SIDES | crate::dialogs::TWO_SIDES_REVERSED, distance2, .. }, Some(n)) = (&mut d.kind, dir) && let Some(l2) = app.session.doc.eval(distance2, ValueKind::Length).ok().filter(|v| v.is_finite()) { - drag_arrow(ui, painter, proj, base, bs, -n, l2, true, egui::Id::new("sc_manipulator2"), half_height, distance2); + drag_arrow(ui, painter, proj, base, bs, -(n * sign), l2, true, egui::Id::new("sc_manipulator2"), half_height, distance2); } // A rectangular pattern's second direction gets its own arrow for Spacing 2 (#2462), as the // first direction's arrow sets Spacing. diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index f06e5ef3b..498737b31 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -69,9 +69,16 @@ pub const MODIFIERS: &[ToolModifiers] = &[ pub(crate) const OPS: [&str; 4] = ["new", "join", "cut", "intersect"]; pub(crate) const OP_LABELS: [&str; 4] = ["New Body", "Join", "Cut", "Intersect"]; -const DIRS: [&str; 4] = ["positive", "negative", "symmetric", "positive"]; +const DIRS: [&str; 5] = ["positive", "negative", "symmetric", "positive", "negative"]; /// The "Two sides" direction (a second distance the other way). pub const TWO_SIDES: usize = 3; +/// Two sides, reversed: the first side goes against the normal and the second along it (#2700). +pub const TWO_SIDES_REVERSED: usize = 4; + +/// An extrude direction with a second side. +pub fn two_sided(direction: usize) -> bool { + direction == TWO_SIDES || direction == TWO_SIDES_REVERSED +} /// Thin Extrude wall locations, as `solid.extrude` names them, and their labels. const WALL_SIDES: [&str; 4] = ["center", "inside", "outside", "two_sides"]; const WALL_LABELS: [&str; 4] = ["Center", "Inside", "Outside", "Two Sides"]; @@ -2487,10 +2494,21 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { row_label(ui, "Direction"); // One Side, Two Sides, Symmetric (a flip is a negative distance). let order = [0usize, TWO_SIDES, 2]; - let mut pos = order.iter().position(|o| o == direction).unwrap_or(0); + let reversed = *direction == 1 || *direction == TWO_SIDES_REVERSED; + let shown = match *direction { + 1 => 0, + TWO_SIDES_REVERSED => TWO_SIDES, + d => d, + }; + let mut pos = order.iter().position(|o| *o == shown).unwrap_or(0); combo(ui, "ex_dir", &["One Side", "Two Sides", "Symmetric"], &mut pos); - if pos != order.iter().position(|o| o == direction).unwrap_or(0) { - *direction = order.get(pos).copied().unwrap_or(0); + if pos != order.iter().position(|o| *o == shown).unwrap_or(0) { + // One Side and Two Sides keep Reverse. + *direction = match (order.get(pos).copied().unwrap_or(0), reversed) { + (0, true) => 1, + (TWO_SIDES, true) => TWO_SIDES_REVERSED, + (d, _) => d, + }; // Selecting Symmetric applies the current total-distance semantics. d.extra.insert("convention".into(), json!(solidcraft_engine::doc::ExtrudeConvention::TotalDistance)); // An explicit direction ends the automatic choices (#1257). @@ -2498,11 +2516,15 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { *auto_op = false; } ui.end_row(); - if *direction < 2 { + if *direction < 2 || two_sided(*direction) { row_label(ui, "Reverse"); - let mut reverse = *direction == 1; + let mut reverse = *direction == 1 || *direction == TWO_SIDES_REVERSED; if ui.checkbox(&mut reverse, tr("Reverse Direction")).changed() { - *direction = usize::from(reverse); + *direction = match (two_sided(*direction), reverse) { + (true, true) => TWO_SIDES_REVERSED, + (true, false) => TWO_SIDES, + (false, r) => usize::from(r), + }; // An explicit direction ends the automatic choices (#1257). smart.manual_dir = true; *auto_op = false; @@ -2520,17 +2542,19 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { row_label(ui, "Distance"); enter |= field(ui, distance); ui.end_row(); - if *direction == TWO_SIDES { - row_label(ui, "Distance 2"); - enter |= field(ui, distance2); - ui.end_row(); - } } if ext == 1 { row_label(ui, "To Offset"); enter |= field(ui, to_offset); ui.end_row(); } + // The second side is a distance whatever the first side's extent: All one + // way and a distance the other is a common two-sided cut (#2700). + if two_sided(*direction) { + row_label(ui, "Distance 2"); + enter |= field(ui, distance2); + ui.end_row(); + } if *direction < 2 { row_label(ui, "Taper Angle"); let before = taper.clone(); @@ -3805,7 +3829,7 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result, S need(0, if *thin { "curves or profiles" } else { "profiles or a planar face" })?; let mut common = json!({"distance": distance, "direction": DIRS.get(*direction).copied().unwrap_or("positive"), "operation": OPS.get(*operation).copied().unwrap_or("new")}); let tapered = s.doc.eval(taper, ValueKind::Angle).map(|v| v.abs() > 1e-12).unwrap_or(!taper.trim().is_empty()); - if *direction == TWO_SIDES { + if two_sided(*direction) { common["distance2"] = json!(distance2); } else if *direction < 2 && (*taper_present || tapered) { common["taper"] = json!(taper); @@ -4857,6 +4881,7 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option TWO_SIDES_REVERSED, (_, Some(_)) => TWO_SIDES, (Direction::Positive, None) => 0, (Direction::Negative, None) => 1, diff --git a/crates/ui-egui/src/extrude_edit_tests.rs b/crates/ui-egui/src/extrude_edit_tests.rs index 739631c34..05600cfe6 100644 --- a/crates/ui-egui/src/extrude_edit_tests.rs +++ b/crates/ui-egui/src/extrude_edit_tests.rs @@ -48,6 +48,7 @@ fn unchanged_actual_editor_preserves_all_extents_and_parameter_identities() { json!({"direction":"symmetric","distance":"5 mm"}), json!({"direction":"symmetric","distance":"5 mm","convention":"legacy_per_side"}), json!({"distance":"10 mm","distance2":"3 mm"}), + json!({"direction":"negative","distance":"10 mm","distance2":"3 mm"}), json!({"from":[0,0,5],"start_offset":"0 mm"}), json!({"to":[0,0,10],"to_offset":"3 mm"}), json!({"to":[0,0,-10],"to_offset":"-2 mm"}), @@ -453,3 +454,50 @@ fn a_click_on_the_extrude_arrow_stem_keeps_the_profile() { assert_eq!(picked(&h), before); assert!((dialog_distance(&h) - distance).abs() < 1e-9, "{} for {distance}", dialog_distance(&h)); } + +/// The volume of the body `name`. +fn volume(h: &Harness, name: &str) -> f64 { + let state = h.app.session.world_state(); + solidcraft_engine::doc::kernel::measure(&state.body(name).unwrap().body).unwrap().volume +} + +/// Two Sides with All (#2700): the editor shows Distance 2 and Reverse for a through-all cut, and +/// Reverse swaps the sides: through all down and 3 mm up instead of through all up and 3 mm down. +#[test] +fn two_sides_with_all_shows_distance_2_and_reverse_swaps_the_sides() { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.run("solid.box", json!({"length":20,"width":20,"height":40,"corner":[0,0,-30],"body_name":"Main"})).unwrap(); + h.app.run("sketch.create", json!({"plane":"XY","name":"Hole"})).unwrap(); + h.app.run("sketch.circle.center", json!({"center":[10,10],"radius":2})).unwrap(); + h.app.run("sketch.finish", json!({})).unwrap(); + let cut = json!({"sketch":"Hole","through_all":true,"distance2":"3 mm","operation":"cut","targets":["Main"],"name":"Depth"}); + h.app.run("solid.extrude", cut).unwrap(); + h.frames(4); + // The box runs 10 mm above the sketch and 30 mm below it. + let area = std::f64::consts::PI * 4.0; + let depth = |h: &Harness| (16000.0 - volume(h, "Main")) / area; + assert!((depth(&h) - 13.0).abs() < 0.05, "{}", depth(&h)); + open(&mut h); + assert!(h.widget("Distance 2").is_some(), "Two Sides with All shows the second side's distance"); + assert!(h.widget("Reverse Direction").is_some(), "Two Sides offers Reverse"); + // The first side's arrow goes up (through all) and the second's down, either side of the + // hole's centre on screen; Reverse swaps them. + let centre = h.at(&json!({"world":[10,10,0]})).unwrap()[1] as f32; + let tips = || (crate::scenario::handle_at("arrow").unwrap().y - centre, crate::scenario::handle_at("arrow2").unwrap().y - centre); + let (first, second) = tips(); + assert!(first < 0.0 && second > 0.0, "the first side's arrow is above the sketch, the second's below: {first} {second}"); + h.step(&json!({"widget":"Reverse Direction"})).unwrap(); + h.frames(2); + let (first, second) = tips(); + assert!(first > 0.0 && second < 0.0, "reversed, the first side's arrow is below, the second's above: {first} {second}"); + h.step(&json!({"widget":"OK"})).unwrap(); + assert!(h.app.dialog.is_none(), "{:?}", h.app.session.log); + let e = extent(&h); + assert_eq!((e.direction, e.through_all, e.distance2.as_deref()), (solidcraft_engine::doc::Direction::Negative, true, Some("3 mm"))); + assert!((depth(&h) - 33.0).abs() < 0.05, "{}", depth(&h)); + // And it opens reversed again: OK without changes keeps it. + open(&mut h); + h.step(&json!({"widget":"OK"})).unwrap(); + assert_eq!(extent(&h), e); +} From a9c7616e7f171a51f87adaeb66744e6be4ae3dd4 Mon Sep 17 00:00:00 2001 From: DuBearte <130190089+DuBearte@users.noreply.github.com> Date: Mon, 19 Oct 2026 16:05:56 -0400 Subject: [PATCH 079/225] Lines thinner than a pixel no longer vanish without multisampling (grid lines, #2823) (#2871) * claim: #2823 * fix(view): lines thinner than a pixel no longer vanish without multisampling (#2823) A line quad narrower than a pixel covers no pixel centre when it falls between two rows, so the grid's 0.7 px lines came and went as the view zoomed where the viewport draws without 4x MSAA (some browsers and devices). Such lines are now drawn a pixel wide, faded by the width they lack. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- assets/shaders/viewport.wgsl | 8 +++-- crates/gpu/src/capture.rs | 19 +++++++++++- crates/gpu/tests/thin_lines.rs | 53 ++++++++++++++++++++++++++++++++++ 3 files changed, 77 insertions(+), 3 deletions(-) create mode 100644 crates/gpu/tests/thin_lines.rs diff --git a/assets/shaders/viewport.wgsl b/assets/shaders/viewport.wgsl index 003d167ff..42ce753b7 100644 --- a/assets/shaders/viewport.wgsl +++ b/assets/shaders/viewport.wgsl @@ -347,10 +347,14 @@ fn vs_line(@builtin(vertex_index) vi: u32, @location(0) a: vec3, @location( let t = ts[vi]; let s = ss[vi]; let base = select(ca, cb, t > 0.5); - let off = nrm * s * w * 0.5 + dir * (t * 2.0 - 1.0) * w * 0.5; + // A line thinner than a pixel is drawn a pixel wide, faded by the width it lacks: a narrower + // quad covers no pixel centre when it falls between two rows, so without multisampling thin + // lines (the grid's) came and went as the view zoomed (#2823). + let wd = max(w, 1.0); + let off = nrm * s * wd * 0.5 + dir * (t * 2.0 - 1.0) * wd * 0.5; var o: LOut; o.pos = vec4(base.xy + off / half * base.w, base.z, base.w); - o.c = c; + o.c = vec4(c.rgb, c.a * (w / wd)); o.wp = select(pa, pb, t > 0.5); return o; } diff --git a/crates/gpu/src/capture.rs b/crates/gpu/src/capture.rs index 4ec11a29b..8d93c812d 100644 --- a/crates/gpu/src/capture.rs +++ b/crates/gpu/src/capture.rs @@ -62,8 +62,15 @@ impl Capturer { /// As [`Capturer::new`], drawing with the depth format `depth` (with a stencil): the fallback /// `Depth24PlusStencil8` on a device that has a float one too, to compare the two. pub fn with_depth(adapter: &wgpu::Adapter, device: wgpu::Device, queue: wgpu::Queue, depth: wgpu::TextureFormat) -> Result { + Self::with_samples(adapter, device, queue, depth, SAMPLES) + } + + /// As [`Capturer::with_depth`], with `samples` per pixel (1: no multisampling, as a device or + /// browser without 4× draws); 1 where the device lacks that many. + fn with_samples(adapter: &wgpu::Adapter, device: wgpu::Device, queue: wgpu::Queue, depth: wgpu::TextureFormat, samples: u32) -> Result { let flags = |f: wgpu::TextureFormat| adapter.get_texture_format_features(f).flags; - let samples = if flags(FORMAT).sample_count_supported(SAMPLES) && flags(depth).sample_count_supported(SAMPLES) { SAMPLES } else { 1 }; + let samples = + if samples > 1 && flags(FORMAT).sample_count_supported(samples) && flags(depth).sample_count_supported(samples) { samples } else { 1 }; let scopes = error_scopes(&device); let renderer = Renderer::new(&device, GpuTarget { format: FORMAT, depth: Some(depth), samples, tess: false }, None); let background = background_pipeline(&device, samples, depth); @@ -99,6 +106,16 @@ impl Capturer { Self::with_depth(&adapter, device, queue, depth) } + /// As [`Capturer::headless`], without multisampling: one sample per pixel, as the viewport + /// draws where 4× isn't available (some browsers and devices, or MSAA turned off). + #[cfg(not(target_arch = "wasm32"))] + pub fn headless_single_sample() -> Result { + let (adapter, device, queue) = crate::open_headless()?; + device.on_uncaptured_error(Arc::new(|e: wgpu::Error| log::error!("GPU: {e}"))); + let depth = crate::depth_format(&device, true); + Self::with_samples(&adapter, device, queue, depth, 1) + } + /// The depth format pictures are drawn with; float formats are drawn with reversed depth. pub fn depth_format(&self) -> wgpu::TextureFormat { self.depth diff --git a/crates/gpu/tests/thin_lines.rs b/crates/gpu/tests/thin_lines.rs new file mode 100644 index 000000000..c8cff8493 --- /dev/null +++ b/crates/gpu/tests/thin_lines.rs @@ -0,0 +1,53 @@ +//! Lines thinner than a pixel (the grid's minor lines are 0.7 px) are drawn wherever they fall, +//! without multisampling (#2823). A quad narrower than a pixel covers no pixel centre when it +//! falls between two rows, so such lines came and went as the view zoomed. Skipped, with the +//! reason printed, without a GPU adapter (`SOLIDCRAFT_REQUIRE_GPU=1` makes that a failure). + +use solidcraft_engine::geom::Vec3; +use solidcraft_engine::render::{Camera, Rgb, Scene, SceneLine, StandardView}; +use solidcraft_gpu::GpuError; +use solidcraft_gpu::capture::Capturer; + +/// Pictures drawn with one sample per pixel: with 4× multisampling a thin line covers some +/// samples wherever it falls, which hides the fault. +fn capturer() -> Option<&'static Capturer> { + static SINGLE: std::sync::OnceLock> = std::sync::OnceLock::new(); + match SINGLE.get_or_init(Capturer::headless_single_sample).as_ref() { + Ok(c) => { + assert_eq!(c.samples(), 1); + Some(c) + } + Err(e @ GpuError::NoAdapter(_)) if std::env::var_os("SOLIDCRAFT_REQUIRE_GPU").is_none() => { + eprintln!("skipping: {e}"); + None + } + Err(e) => panic!("{e}"), + } +} + +/// Lines `width` px wide across a front view, each drawn alone at its own height so it falls at +/// its own fraction of a pixel (0.23 mm apart, about 1.15 px at 5 px per mm); returns the ones +/// that left no pixel. +fn missing(c: &Capturer, width: f64) -> Vec { + const N: usize = 40; + let mut cam = Camera { distance: 62.5, fov: 0.0, ..Default::default() }; + cam.set_view(StandardView::Front); + (0..N) + .filter(|&i| { + let z = -4.0 + i as f64 * 0.23; + let line = SceneLine { points: vec![Vec3::new(-8.0, 0.0, z), Vec3::new(8.0, 0.0, z)], color: Rgb(255, 0, 0), width, on_top: true }; + let scene = Scene { lines: vec![line], radius: 30.0, ..Default::default() }; + let img = c.rgba(&scene, &cam, 200, 200).unwrap(); + !img.as_chunks::<4>().0.iter().any(|p| p[0] > 60 && p[0] > p[1].saturating_add(40) && p[0] > p[2].saturating_add(40)) + }) + .collect() +} + +#[test] +fn lines_thinner_than_a_pixel_are_drawn_wherever_they_fall() { + let Some(c) = capturer() else { return }; + for width in [0.4, 0.7, 1.0, 1.5] { + let gone = missing(c, width); + assert!(gone.is_empty(), "{width} px lines: {} of 40 left no pixel ({gone:?})", gone.len()); + } +} From 24d64799d8572eda124b1f1790cc1c06a8c6a928 Mon Sep 17 00:00:00 2001 From: DuBearte <130190089+DuBearte@users.noreply.github.com> Date: Mon, 19 Oct 2026 16:06:06 -0400 Subject: [PATCH 080/225] Update window: release-note links open in the browser (#2943) (#3004) * claim: #2943 * fix(update): release-note links open in the browser (#2943) The notes kept a link's text and dropped its target, so the blue text could not be clicked. Links keep their web address, and each paragraph or item is followed by its links as buttons that open them, as the agent chat shows links. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/update.rs | 46 +++++++++++++++++++++++++----- crates/ui-egui/src/update/tests.rs | 23 +++++++++++++-- 2 files changed, 60 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/update.rs b/crates/ui-egui/src/update.rs index 09dd0568b..f38e997ea 100644 --- a/crates/ui-egui/src/update.rs +++ b/crates/ui-egui/src/update.rs @@ -991,8 +991,17 @@ pub enum Span { Text(String), Strong(String), Code(String), - /// A link's text (the target is dropped: the release page has them). - Link(String), + /// A link's text and, for a web address (`https://`, `http://`), where it goes (#2943). + Link { + text: String, + url: Option, + }, +} + +/// A link target the notes may open: web addresses only. +fn web_url(url: &str) -> Option { + let url = url.trim(); + (url.starts_with("https://") || url.starts_with("http://")).then(|| url.to_string()) } /// A block of the release notes. @@ -1006,7 +1015,7 @@ pub enum Block { /// The Markdown GitHub release notes use, enough to read them: headings, paragraphs (soft line /// breaks joined), `-`/`*` lists, `**strong**`, `` `code` ``, `[links](…)` and bare pull-request -/// URLs (shown as `#123`). Anything else shows as written. +/// URLs (shown as `#123`, linking to them). Anything else shows as written. pub fn parse_markdown(src: &str) -> Vec { let mut blocks = Vec::new(); let mut para = String::new(); @@ -1075,7 +1084,8 @@ pub fn inline(text: &str) -> Vec { && let Some(end) = after.get(close + 2..).and_then(|s| s.find(')')) { push_plain(&mut out, &mut plain); - out.push(Span::Link(strip_links(after.get(..close).unwrap_or_default()))); + let url = after.get(close + 2..close + 2 + end).and_then(web_url); + out.push(Span::Link { text: strip_links(after.get(..close).unwrap_or_default()), url }); rest = after.get(close + 2 + end + 1..).unwrap_or_default(); } else if rest.starts_with("https://github.com/") { let end = rest.find(char::is_whitespace).unwrap_or(rest.len()); @@ -1086,7 +1096,7 @@ pub fn inline(text: &str) -> Vec { match (number, kind) { (Some(n), Some("pull" | "issues")) => { push_plain(&mut out, &mut plain); - out.push(Span::Link(format!("#{n}"))); + out.push(Span::Link { text: format!("#{n}"), url: web_url(tail) }); rest = rest.get(tail.len()..).unwrap_or_default(); } _ => { @@ -1108,7 +1118,7 @@ fn strip_links(s: &str) -> String { inline(s) .into_iter() .map(|span| match span { - Span::Text(t) | Span::Strong(t) | Span::Code(t) | Span::Link(t) => t, + Span::Text(t) | Span::Strong(t) | Span::Code(t) | Span::Link { text: t, .. } => t, }) .collect() } @@ -1123,12 +1133,32 @@ fn markdown(ui: &mut egui::Ui, src: &str, t: &Tokens) { Span::Text(s) => (s.as_str(), FontId::proportional(size), if strong { t.text } else { body }), Span::Strong(s) => (s.as_str(), FontId::proportional(size), t.text), Span::Code(s) => (s.as_str(), FontId::monospace(size - 1.0), body), - Span::Link(s) => (s.as_str(), FontId::proportional(size), t.accent), + Span::Link { text, .. } => (text.as_str(), FontId::proportional(size), t.accent), }; job.append(text, 0.0, egui::TextFormat { font_id: font, color, ..Default::default() }); } job }; + // A laid-out text can't be clicked in parts: a block's web links follow it as buttons that + // open them in the browser (#2943), as the agent chat shows its links. + let links = |ui: &mut egui::Ui, spans: &[Span], indent: f32| { + let targets: Vec<(&str, &str)> = spans + .iter() + .filter_map(|s| match s { + Span::Link { text, url: Some(url) } => Some((text.as_str(), url.as_str())), + _ => None, + }) + .collect(); + if targets.is_empty() { + return; + } + ui.horizontal_wrapped(|ui| { + ui.add_space(indent); + for (text, url) in targets { + ui.hyperlink_to(RichText::new(text).size(11.5), url).on_hover_text(url); + } + }); + }; // Fixed widths: the notes never widen the window, whatever their lines. let width = NOTES_W; for block in parse_markdown(src) { @@ -1139,6 +1169,7 @@ fn markdown(ui: &mut egui::Ui, src: &str, t: &Tokens) { } Block::Paragraph(spans) => { ui.add(egui::Label::new(job(&spans, 12.5, false, width)).wrap()); + links(ui, &spans, 0.0); ui.add_space(3.0); } Block::Item(depth, spans) => { @@ -1148,6 +1179,7 @@ fn markdown(ui: &mut egui::Ui, src: &str, t: &Tokens) { ui.label(RichText::new("•").size(12.5)); ui.add(egui::Label::new(job(&spans, 12.5, false, width - indent - 14.0)).wrap()); }); + links(ui, &spans, indent + 14.0); } } } diff --git a/crates/ui-egui/src/update/tests.rs b/crates/ui-egui/src/update/tests.rs index 8eda32e78..0baa62f77 100644 --- a/crates/ui-egui/src/update/tests.rs +++ b/crates/ui-egui/src/update/tests.rs @@ -454,13 +454,22 @@ fn release_notes_read_as_markdown() { Span::Text(" Revolve and ".into()), Span::Code("solidcraft-cli mcp".into()), Span::Text(" continued (".into()), - Span::Link("#925".into()), + Span::Link { text: "#925".into(), url: Some("https://x/925".into()) }, Span::Text(").".into()), ] )) ); assert_eq!(b.get(3), Some(&Block::Item(1, vec![Span::Text("nested".into())]))); - assert_eq!(b.get(4), Some(&Block::Item(0, vec![Span::Text("Fix by @a in ".into()), Span::Link("#1064".into())]))); + assert_eq!( + b.get(4), + Some(&Block::Item( + 0, + vec![ + Span::Text("Fix by @a in ".into()), + Span::Link { text: "#1064".into(), url: Some("https://github.com/bherbruck/solidcraft/pull/1064".into()) } + ] + )) + ); assert_eq!(b.get(5), Some(&Block::Paragraph(vec![Span::Text("See https://example.com/x.".into())]))); // Unclosed markers and odd input show as written, without panicking. for s in ["**open", "`tick", "[a](b", "[a]", "#", "- ", "é**", "https://github.com/", "**[x](y)**"] { @@ -469,6 +478,16 @@ fn release_notes_read_as_markdown() { assert_eq!(inline("**[x](y)**"), vec![Span::Strong("x".into())]); } +/// #2943: a release note's links keep where they go, so the window can open them; only web +/// addresses are kept (a relative or other link shows as text that opens nothing). +#[test] +fn release_note_links_keep_their_web_targets() { + let spans = inline("[guide](https://docs.solidcraft.io/guide) and [file](file:///etc/passwd) and [rel](../x)"); + let links: Vec<(String, Option)> = + spans.into_iter().filter_map(|s| if let Span::Link { text, url } = s { Some((text, url)) } else { None }).collect(); + assert_eq!(links, vec![("guide".into(), Some("https://docs.solidcraft.io/guide".into())), ("file".into(), None), ("rel".into(), None)]); +} + #[test] fn releases_under_either_owner_are_accepted() { let parse = |owner: &str| { From 45ae7c00e0ba9941b48244ff38562e623908f3d1 Mon Sep 17 00:00:00 2001 From: DuBearte <130190089+DuBearte@users.noreply.github.com> Date: Mon, 19 Oct 2026 16:06:16 -0400 Subject: [PATCH 081/225] Convert Mesh asks for the mesh body and its tolerance (#3001) (#3012) * claim: #3001 * fix(ui): Convert Mesh asks for the mesh body and its tolerance (#3001) It had no dialog, so the toolbar ran mesh.convert with no body and it always reported "select a mesh body". A dialog now takes the mesh body (a selected one fills it) and the tolerance. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 19 +++++++++++++ crates/ui-egui/src/preselect_tests.rs | 40 +++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 498737b31..8965fdeab 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -173,6 +173,10 @@ pub enum Kind { }, /// Halfway between two planes or planar faces. Midplane, + /// An imported mesh body rebuilt as editable faces (#3001). + MeshConvert { + tolerance: String, + }, /// A construction axis, point or plane made from picks alone (#2474): input `i` is the /// command's parameter `keys[i]`, and `t` (along a path) when it takes one. Construct { @@ -590,6 +594,7 @@ impl Dialog { "construct.plane.offset" => { Dialog::new(Kind::OffsetPlane { offset: "0 mm".into() }, vec![SelInput::new("Plane", PLANES | PLANAR_FACES, false)]) } + "mesh.convert" => Dialog::new(Kind::MeshConvert { tolerance: "0.05 mm".into() }, vec![SelInput::new("Mesh body", BODIES, false)]), "construct.plane.midplane" => Dialog::new( Kind::Midplane, vec![SelInput::new("First plane", PLANES | PLANAR_FACES, false), SelInput::new("Second plane", PLANES | PLANAR_FACES, false)], @@ -1484,6 +1489,7 @@ fn title(k: &Kind) -> &'static str { Kind::Material { .. } => "PHYSICAL MATERIAL", Kind::OffsetPlane { .. } => "OFFSET PLANE", Kind::Midplane => "MIDPLANE", + Kind::MeshConvert { .. } => "CONVERT MESH", Kind::Construct { title, .. } => title, Kind::PathPlane { .. } => "PLANE ALONG PATH", Kind::Rib { web: false, .. } => "RIB", @@ -2820,6 +2826,11 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { ui.end_row(); } Kind::Split | Kind::ReplaceFace | Kind::Remove | Kind::Midplane | Kind::Construct { t: None, .. } => {} + Kind::MeshConvert { tolerance } => { + row_label(ui, "Tolerance"); + enter |= field(ui, tolerance); + ui.end_row(); + } Kind::Construct { t: Some(t), .. } => { row_label(ui, "Position (0 to 1)"); enter |= field(ui, t); @@ -4102,6 +4113,14 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result, S let base = plane_arg(app, sels(d, 0).first())?; ("construct.plane.offset", json!({"base": base, "offset": offset})) } + Kind::MeshConvert { tolerance } => { + need(0, "the mesh body")?; + let body = match sels(d, 0).first() { + Some(Sel::Body { name }) => name.clone(), + _ => return Err("pick the mesh body to convert".into()), + }; + ("mesh.convert", json!({"body": body, "tolerance": tolerance})) + } Kind::Midplane => { need(0, "the first plane")?; need(1, "the second plane")?; diff --git a/crates/ui-egui/src/preselect_tests.rs b/crates/ui-egui/src/preselect_tests.rs index d2ca0d548..033a1f9a9 100644 --- a/crates/ui-egui/src/preselect_tests.rs +++ b/crates/ui-egui/src/preselect_tests.rs @@ -1932,3 +1932,43 @@ fn point_along_path_has_its_position_and_missing_picks_are_named() { let e = h.app.dialog.as_ref().and_then(|d| d.error.clone()).unwrap_or_default(); assert!(e.contains("path"), "{e}"); } + +/// #3001: Convert Mesh opens a dialog instead of failing with "select a mesh body". With the +/// mesh selected first it takes it, and OK rebuilds it as faces. +#[test] +fn convert_mesh_asks_for_the_body_and_converts_the_selected_one() { + use solidcraft_engine::doc::{Document, FeatureKind, MeshData}; + let body = solidcraft_engine::kernel::box_solid(Vec3::ZERO, Vec3::new(10., 20., 30.)).unwrap(); + let mesh = body.tessellate(0.01).unwrap(); + let mut doc = Document::default(); + doc.add_feature( + FeatureKind::MeshImport { + file: "box.stl".into(), + meshes: vec![MeshData { + name: "Mesh".into(), + positions: mesh.positions.iter().flat_map(|p| [p.x, p.y, p.z]).collect(), + triangles: mesh.triangles.iter().flatten().copied().collect(), + color: None, + }], + }, + Some("Imported mesh"), + ) + .unwrap(); + let mut h = crate::scenario::Harness::new(); + h.app.session = Session::new(doc); + h.app.start("mesh.convert"); + h.frames(1); + let status = h.app.status.as_ref().map(|s| s.0.clone()).unwrap_or_default(); + assert!(!status.contains("select a mesh body"), "{status}"); + assert!(matches!(h.app.dialog.as_ref().map(|d| &d.kind), Some(Kind::MeshConvert { .. }))); + crate::dialogs::cancel(&mut h.app); + + h.app.session.selection = vec![Sel::Body { name: "Mesh".into() }]; + h.app.start("mesh.convert"); + h.frames(1); + assert_eq!(h.app.dialog.as_ref().unwrap().inputs[0].items, vec![Sel::Body { name: "Mesh".into() }]); + h.step(&json!({"key":"Enter"})).unwrap(); + assert!(h.app.dialog.is_none(), "{:?}", h.app.dialog.as_ref().and_then(|d| d.error.clone())); + let state = h.app.session.model.state(); + assert!(!state.body("Mesh").unwrap().body.is_mesh(), "rebuilt as faces"); +} From d3fa22e9876a21ae3eb012e567da065695393f20 Mon Sep 17 00:00:00 2001 From: The Nomad Date: Mon, 19 Oct 2026 16:07:38 -0400 Subject: [PATCH 082/225] 3D mouse calibration in Preferences (#2326) Adds a 3D mouse calibration section to Preferences (#1463). --- Cargo.lock | 4 + apps/solidcraft-web/src/space_mouse.rs | 116 +- apps/solidcraft/src/space_mouse.rs | 198 ++- apps/solidcraft/src/space_mouse/hidraw.rs | 30 +- assets/locales/cs.json | 28 + assets/locales/de.json | 28 + assets/locales/en.json | 28 + assets/locales/es.json | 28 + assets/locales/fr.json | 28 + assets/locales/gl.json | 28 + assets/locales/it.json | 28 + assets/locales/ja.json | 28 + assets/locales/ko.json | 28 + assets/locales/pt-BR.json | 28 + assets/locales/ru.json | 28 + assets/locales/tr.json | 28 + assets/locales/uk.json | 28 + assets/locales/zh.json | 28 + crates/space-mouse/Cargo.toml | 4 + crates/space-mouse/src/calibration.rs | 1357 +++++++++++++++++ crates/space-mouse/src/lib.rs | 4 + crates/ui-egui/Cargo.toml | 1 + crates/ui-egui/src/lib.rs | 4 + crates/ui-egui/src/prefs.rs | 79 +- crates/ui-egui/src/space_mouse.rs | 167 +- crates/ui-egui/src/space_mouse_calibration.rs | 157 ++ 26 files changed, 2461 insertions(+), 52 deletions(-) create mode 100644 crates/space-mouse/src/calibration.rs create mode 100644 crates/ui-egui/src/space_mouse_calibration.rs diff --git a/Cargo.lock b/Cargo.lock index 8a2231f10..c421d34bc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4268,6 +4268,9 @@ dependencies = [ [[package]] name = "solidcraft-space-mouse" version = "0.16.2" +dependencies = [ + "serde", +] [[package]] name = "solidcraft-ui-egui" @@ -4286,6 +4289,7 @@ dependencies = [ "sha2 0.10.9", "solidcraft-engine", "solidcraft-gpu", + "solidcraft-space-mouse", "tiny-skia", "toml", "ttf-parser", diff --git a/apps/solidcraft-web/src/space_mouse.rs b/apps/solidcraft-web/src/space_mouse.rs index 07394de56..3fecfd027 100644 --- a/apps/solidcraft-web/src/space_mouse.rs +++ b/apps/solidcraft-web/src/space_mouse.rs @@ -7,7 +7,7 @@ //! navigation takes them with 3DxWare's object-mode mapping, as the Linux app does without a //! profile. -use solidcraft_ui_egui::space_mouse::{Axes, FULL_SCALE}; +use solidcraft_ui_egui::space_mouse::{Axes, Calibration, FULL_SCALE, calibrated}; /// Logitech's vendor id, which older 3Dconnexion devices carry, and those devices' product ids /// (usb.ids). Logitech's own gamepads and wheels carry the same vendor id. @@ -60,9 +60,43 @@ pub fn axes(values: &[f64]) -> Option { Some(Axes { translation: [raw(0)?, raw(1)?, raw(2)?], rotation: [raw(3)?, raw(4)?, raw(5)?] }) } +/// What a calibration of the gamepad with this id is saved under: `web` and its vendor and +/// product ids. +pub fn device_key(id: &str) -> Option { + vendor_product(id).map(|(vendor, product)| format!("web {vendor:04x}:{product:04x}")) +} + /// The 3D mouse to read among the ones listed: the first device, else the first joystick. -pub fn choose(found: impl IntoIterator) -> Option { - found.into_iter().min_by_key(|(source, _)| *source).map(|(_, axes)| axes) +pub fn choose(found: impl IntoIterator) -> Option { + found.into_iter().min_by_key(|(source, _)| *source).map(|(_, reading)| reading) +} + +/// Whether the cap is moving as the next frame will see it: through the device's calibration +/// (as of the last frame) when it has one. The idle page wakes for a short-range device's push, +/// and not for a device resting off zero; the wheel filter goes by the same. +pub fn moving(axes: Axes, calibration: Option) -> bool { + calibrated(axes, calibration).moving() +} + +/// The calibration as of the last frame, and the device it was for. +pub type Cached = (Option, Option); + +/// Whether the cap of `device` is moving, judged with the calibration kept from the last frame: +/// `None` when that was for another device, so another's calibration never judges this one. The +/// waker then lets a frame look, which brings the cache up to date. +pub fn moving_as_cached(device: &Option, axes: Axes, cached: &Cached) -> Option { + (*device == cached.0).then(|| moving(axes, cached.1)) +} + +/// Whether the idle page's timer redraws: when the cap is moving as the last frame's calibration +/// judges it, when the device read isn't the one that calibration was for (a frame then judges +/// it with its own), and once when the device the last frame read is gone, so the page shows +/// that. With no device, and none last frame, it stays quiet. +pub fn wakes(reading: Option<(Option, Axes)>, cached: &Cached) -> bool { + match reading { + Some((device, axes)) => moving_as_cached(&device, axes, cached).unwrap_or(true), + None => cached.0.is_some(), + } } #[cfg(target_arch = "wasm32")] @@ -70,29 +104,29 @@ pub use browser::SpaceMouse; #[cfg(target_arch = "wasm32")] mod browser { - use std::cell::Cell; + use std::cell::{Cell, RefCell}; use std::rc::Rc; use solidcraft_ui_egui::SolveApp; - use solidcraft_ui_egui::space_mouse::{Axes, DriverMapping, navigate_frame}; + use solidcraft_ui_egui::space_mouse::{Axes, DriverMapping, calibration, navigate_frame}; use wasm_bindgen::JsCast as _; use wasm_bindgen::closure::Closure; use solidcraft_ui_egui::space_mouse::WheelGuard; - use super::{axes, choose, source}; + use super::{Cached, axes, choose, device_key, moving_as_cached, source, wakes}; /// How often the page looks for the cap starting to move while nothing else redraws. const WAKE_MS: i32 = 50; - /// The 3D mouse the browser lists, if any. - fn read() -> Option { + /// The 3D mouse the browser lists, if any: its calibration key and its axes. + fn read() -> Option<(Option, Axes)> { let pads = web_sys::window()?.navigator().get_gamepads().ok()?; choose(pads.iter().filter_map(|pad| { let pad = pad.dyn_into::().ok().filter(web_sys::Gamepad::connected)?; let source = source(&pad.id())?; let values: Vec = pad.axes().iter().map(|v| v.as_f64().unwrap_or(f64::NAN)).collect(); - Some((source, axes(&values)?)) + Some((source, (device_key(&pad.id()), axes(&values)?))) })) } @@ -100,6 +134,8 @@ mod browser { #[derive(Default)] pub struct SpaceMouse { axes: Axes, + /// The 3D mouse being read, as `SolveApp::space_mouse` keeps it. + device: Option, /// The previous frame's time and the step since it (seconds). last: Option, seconds: f64, @@ -111,6 +147,8 @@ mod browser { waking: bool, /// Navigation is on (the waker reads it). enabled: Rc>, + /// The calibration as of the last frame and its device (the waker and the wheel filter read it). + cached: Rc>, } impl SpaceMouse { @@ -131,14 +169,18 @@ mod browser { } let reading = read(); if reading.is_some() && !self.waking { - self.waking = wake(ctx, &self.enabled); + self.waking = wake(ctx, &self.enabled, &self.cached); } - // Inside the dead zone is rest: a cap resting just off zero doesn't keep redrawing. - self.axes = reading.filter(|axes| axes.moving()).unwrap_or_default(); - self.wheel.filter(self.axes.moving(), now, &mut raw.events); + // As read: calibration needs the readings at rest too, and `navigate_frame` leaves a + // cap resting inside the dead zone alone. + (self.device, self.axes) = reading.unwrap_or_default(); + let moving = moving_as_cached(&self.device, self.axes, &self.cached.borrow()).unwrap_or_else(|| self.axes.moving()); + self.wheel.filter(moving, now, &mut raw.events); } pub fn logic(&self, app: &mut SolveApp, ctx: &egui::Context) { + app.space_mouse.device.clone_from(&self.device); + *self.cached.borrow_mut() = (self.device.clone(), calibration(app)); navigate_frame(app, ctx, DriverMapping::object_mode(), self.axes, self.seconds); } } @@ -156,11 +198,11 @@ mod browser { /// The browser sends no event when a gamepad moves, so a timer looks while the app is idle and /// redraws when the cap starts moving; the frames that follow keep going on their own. - fn wake(ctx: &egui::Context, enabled: &Rc>) -> bool { + fn wake(ctx: &egui::Context, enabled: &Rc>, cached: &Rc>) -> bool { let Some(window) = web_sys::window() else { return false }; - let (ctx, enabled) = (ctx.clone(), Rc::clone(enabled)); + let (ctx, enabled, cached) = (ctx.clone(), Rc::clone(enabled), Rc::clone(cached)); let tick = Closure::::new(move || { - if enabled.get() && read().is_some_and(Axes::moving) { + if enabled.get() && wakes(read(), &cached.borrow()) { ctx.request_repaint(); } }); @@ -192,6 +234,46 @@ mod tests { } } + #[test] + fn a_calibration_is_saved_under_the_ids_whichever_browser_lists_it() { + assert_eq!(device_key("SpaceMouse Pro (Vendor: 046d Product: c62b)").as_deref(), Some("web 046d:c62b")); + assert_eq!(device_key("46d-c62b-SpaceMouse Pro").as_deref(), Some("web 046d:c62b")); + assert_eq!(device_key("Xbox Wireless Controller"), None); + } + + #[test] + fn the_idle_page_wakes_for_motion_as_calibrated_not_as_read() { + let axis = + |source, rest, full| solidcraft_ui_egui::space_mouse::AxisCalibration { source, reversed: false, rest, dead_zone: 0, full: [full; 2] }; + // A short-range device: 15 of its 50 is under the raw dead zone, but 105 of 350 calibrated. + let short = Calibration { dead_zone_share: 0.0, axes: std::array::from_fn(|r| axis(r, 0, 50)) }; + let push = Axes { translation: [15, 0, 0], rotation: [0; 3] }; + assert!(!push.moving() && moving(push, Some(short))); + // A device resting at 100 on every axis: past the raw dead zone, but at rest calibrated. + let offset = Calibration { dead_zone_share: 0.0, axes: std::array::from_fn(|r| axis(r, 100, 350)) }; + let resting = Axes { translation: [100; 3], rotation: [100; 3] }; + assert!(resting.moving() && !moving(resting, Some(offset))); + // Without a calibration, as read. + assert!(!moving(push, None) && moving(resting, None)); + // Kept from the last frame: only for the device it was for. + let (a, b) = (Some("web 256f:c63a".to_string()), Some("web 1234:5678".to_string())); + assert_eq!(moving_as_cached(&b, push, &(b.clone(), Some(short))), Some(true)); + assert_eq!(moving_as_cached(&b, push, &(a.clone(), Some(offset))), None, "A's calibration doesn't judge B"); + assert_eq!(moving_as_cached(&b, push, &(None, None)), None); + assert_eq!(moving_as_cached(&a, resting, &(a.clone(), None)), Some(true), "A was read without a calibration"); + } + + #[test] + fn the_idle_page_wakes_once_for_a_device_change_and_stays_quiet_without_one() { + let (a, b) = (Some("web 256f:c63a".to_string()), Some("web 1234:5678".to_string())); + let still = Axes::default(); + let last_frame_read_a: Cached = (a.clone(), None); + assert!(!wakes(Some((a.clone(), still)), &last_frame_read_a), "A, at rest"); + assert!(wakes(Some((b.clone(), still)), &last_frame_read_a), "A to B: a frame looks at B"); + assert!(wakes(None, &last_frame_read_a), "A to none: a frame shows it's gone"); + assert!(!wakes(None, &(None, None)), "none to none: quiet"); + } + #[test] fn gamepads_and_other_logitech_devices_are_not_3d_mice() { for id in [ @@ -280,6 +362,6 @@ mod tests { assert_eq!(choose([(Source::VirtualJoystick, other)]), Some(other)); // Two devices: the first listed. assert_eq!(choose([(Source::Device, moving), (Source::Device, other)]), Some(moving)); - assert_eq!(choose([]), None); + assert_eq!(choose::([]), None); } } diff --git a/apps/solidcraft/src/space_mouse.rs b/apps/solidcraft/src/space_mouse.rs index 96c0d1ab3..9089ceac7 100644 --- a/apps/solidcraft/src/space_mouse.rs +++ b/apps/solidcraft/src/space_mouse.rs @@ -19,7 +19,7 @@ use quick_xml::Reader; use quick_xml::events::Event; use solidcraft_space_mouse::Layout; use solidcraft_ui_egui::SolveApp; -use solidcraft_ui_egui::space_mouse::{Axes, AxisRule, DriverMapping, WheelGuard, navigate_frame}; +use solidcraft_ui_egui::space_mouse::{Axes, AxisRule, Calibration, DriverMapping, WheelGuard, calibrated, calibration, navigate_frame}; const STALE_AFTER: Duration = Duration::from_millis(150); /// Whether the 3Dconnexion driver (macOS) has the device: it then reports the cap, and reading @@ -165,8 +165,36 @@ fn load_driver_mapping() -> Option { parse_driver_mapping(&xml) } +/// Where the reading comes from, which a calibration is saved under (`Source::key`). +#[derive(Clone, Copy, Debug, PartialEq)] +enum Source { + /// The device itself, with its vendor and product ids when known. + Hid(Option<(u16, u16)>), + /// spacenavd, which may have swapped or inverted axes on its own (`spnavcfg`). + #[cfg(target_os = "linux")] + Spacenavd, + /// The 3Dconnexion driver (macOS), which applies its own settings first. + #[cfg(target_os = "macos")] + Driver, +} + +impl Source { + fn key(self) -> String { + match self { + Self::Hid(Some((vendor, product))) => format!("hid {vendor:04x}:{product:04x}"), + Self::Hid(None) => "hid".into(), + #[cfg(target_os = "linux")] + Self::Spacenavd => "spacenavd".into(), + #[cfg(target_os = "macos")] + Self::Driver => "3dxware".into(), + } + } +} + #[derive(Clone, Copy)] struct Reading { + /// The device being read; none between devices. + device: Option, axes: Axes, /// When each of X, Y, Z, Rx, Ry and Rz last arrived. Each ages on its own: a device may send /// translation and rotation in separate reports, or spread even one group over several. @@ -179,15 +207,18 @@ struct Reading { impl Reading { fn new(now: Instant) -> Self { - Self { axes: Axes::default(), at: [now; 6], held: false } + Self { device: None, axes: Axes::default(), at: [now; 6], held: false } } - fn current(self, now: Instant) -> Axes { + /// The axes at `now`. One with nothing fresh reads as `rest`: the device's own rest when it + /// is calibrated, so a device that rests off zero calibrates to no motion rather than drifting. + fn current(self, now: Instant, rest: Axes) -> Axes { let mut axes = self.axes; if !self.held { - for (value, at) in axes.translation.iter_mut().chain(axes.rotation.iter_mut()).zip(self.at) { + let rest = rest.translation.into_iter().chain(rest.rotation); + for ((value, at), rest) in axes.translation.iter_mut().chain(axes.rotation.iter_mut()).zip(self.at).zip(rest) { if now.duration_since(at) >= STALE_AFTER { - *value = 0; + *value = rest; } } } @@ -195,6 +226,11 @@ impl Reading { } } +/// The raw axes at the device's rest, which calibrate to no motion; 0 without a calibration. +fn at_rest(calibration: Option) -> Axes { + calibration.map(|calibration| calibration.raw_rest().into()).unwrap_or_default() +} + /// The Generic Desktop "Multi-Axis Controller" usage names a 3D mouse's motion interface, whoever /// made it, and excludes ordinary mice and the keyboard interfaces of 3D mice. #[cfg(any(target_os = "windows", target_os = "macos"))] @@ -233,11 +269,22 @@ fn publish(ctx: &Context, shared: &Mutex, layout: Layout, report: &[u8] #[cfg(target_os = "linux")] fn publish_held(ctx: &Context, shared: &Mutex, axes: Axes) { if let Ok(mut reading) = shared.lock() { - *reading = Reading { axes, held: true, ..Reading::new(Instant::now()) }; + *reading = Reading { device: reading.device, axes, held: true, ..Reading::new(Instant::now()) }; ctx.request_repaint(); } } +/// A device is open: say which, so its calibration applies. +fn connected(ctx: &Context, shared: &Mutex, source: Source) { + if let Ok(mut reading) = shared.lock() { + // Nothing has arrived from it yet, so every axis starts out stale. + let now = Instant::now(); + let stale = now.checked_sub(STALE_AFTER).unwrap_or(now); + *reading = Reading { device: Some(source), at: [stale; 6], ..Reading::new(now) }; + } + ctx.request_repaint(); +} + /// The device is gone: stop reporting its last position. fn reset(ctx: &Context, shared: &Mutex) { if let Ok(mut reading) = shared.lock() { @@ -255,7 +302,7 @@ fn reader(ctx: Context, shared: Arc>) { loop { if let Err(error) = api.refresh_devices() { log::warn!("3D mouse: device scan failed: {error}"); - } else if let Some((device, layout)) = api.device_list().filter(|info| is_3d_mouse(info)).find_map(|info| { + } else if let Some((device, layout, ids)) = api.device_list().filter(|info| is_3d_mouse(info)).find_map(|info| { let device = info .open_device(&api) .inspect_err(|error| { @@ -267,8 +314,9 @@ fn reader(ctx: Context, shared: Arc>) { }) .ok()?; let layout = device_layout(&device, info.vendor_id())?; - Some((device, layout)) + Some((device, layout, (info.vendor_id(), info.product_id()))) }) { + connected(&ctx, &shared, Source::Hid(Some(ids))); let mut report = [0_u8; REPORT_BUFFER_BYTES]; loop { match device.read_timeout(&mut report, 100) { @@ -323,6 +371,7 @@ fn reader(ctx: Context, shared: Arc>) { loop { if let Some(daemon) = spacenavd::connect() { log::info!("3D mouse: reading spacenavd, which applies the spnavcfg settings"); + connected(&ctx, &shared, Source::Spacenavd); spacenavd::read(daemon, |axes| publish_held(&ctx, &shared, axes)); reset(&ctx, &shared); } else if let Some(device) = hidraw::find() { @@ -330,6 +379,7 @@ fn reader(ctx: Context, shared: Arc>) { Ok(mut file) => { denied = None; log::info!("3D mouse: reading {}", device.path.display()); + connected(&ctx, &shared, Source::Hid(device.ids)); let mut report = [0_u8; REPORT_BUFFER_BYTES]; loop { match file.read(&mut report) { @@ -365,7 +415,10 @@ fn start_driver_client(ctx: &Context, shared: &Arc>) { let started = solidcraft_3dx_client::start( "SolidCraft", move |event| match event { - Event::DeviceAdded => DRIVER_CONNECTED.store(true, Ordering::Relaxed), + Event::DeviceAdded => { + DRIVER_CONNECTED.store(true, Ordering::Relaxed); + connected(&ctx, &shared, Source::Driver); + } Event::DeviceRemoved => { DRIVER_CONNECTED.store(false, Ordering::Relaxed); reset(&ctx, &shared); @@ -398,6 +451,9 @@ pub struct SpaceMouse { /// Drops 3DxWare's emulated wheel while the cap moves (#1380). wheel: WheelGuard, started: Instant, + /// The calibration as of the last frame and the device it is for, for the wheel filter, which + /// runs before the app sees the frame. + calibration: Option<(Source, Calibration)>, } impl SpaceMouse { @@ -418,6 +474,7 @@ impl SpaceMouse { mapping_checked_at: now, wheel: WheelGuard::default(), started: now, + calibration: None, } } @@ -431,7 +488,15 @@ impl SpaceMouse { if !enabled { return; } - let moving = self.shared.lock().map(|reading| reading.current(now).moving()).unwrap_or(false); + let moving = self + .shared + .lock() + .map(|reading| { + // Only the calibration of the device being read: another's would misjudge it. + let calibration = self.calibration.filter(|(source, _)| Some(*source) == reading.device).map(|(_, calibration)| calibration); + calibrated(reading.current(now, at_rest(calibration)), calibration).moving() + }) + .unwrap_or(false); self.wheel.filter(moving, now.duration_since(self.started).as_secs_f64(), &mut raw.events); } @@ -451,11 +516,16 @@ impl SpaceMouse { } self.mapping_checked_at = now; } - let axes = match self.shared.lock() { - Ok(reading) => reading.current(now), - Err(_) => return, - }; - navigate_frame(app, ctx, self.driver_mapping, axes, seconds); + let Ok(reading) = self.shared.lock().map(|reading| *reading) else { return }; + app.space_mouse.device = reading.device.map(Source::key); + let calibration = calibration(app); + self.calibration = reading.device.zip(calibration); + // While this device is being calibrated, an axis with nothing fresh reads 0, as a HID + // device's silence means: the old calibration's rest isn't fed back into the new one. A + // calibration of another device doesn't count; it ends in `navigate_frame`. + let calibrating = app.space_mouse.calibrating.as_ref().is_some_and(|(device, _)| app.space_mouse.device.as_ref() == Some(device)); + let rest = if calibrating { Axes::default() } else { at_rest(calibration) }; + navigate_frame(app, ctx, self.driver_mapping, reading.current(now, rest), seconds); } } @@ -477,14 +547,14 @@ mod tests { let mut reading = Reading::new(now); let layout = Layout::default(); assert!(!decode_report(&[1, 1, 2], layout, &mut reading, now)); - assert_eq!(reading.current(now), Axes::default()); + assert_eq!(reading.current(now, Axes::default()), Axes::default()); assert!(decode_report(&[1, 0x9c, 0xff, 0x2c, 0x01, 0, 0], layout, &mut reading, now)); assert!(decode_report(&[2, 0, 0, 1, 0, 0xff, 0xff], layout, &mut reading, now)); - assert_eq!(reading.current(now), Axes { translation: [-100, 300, 0], rotation: [0, 1, -1] }); + assert_eq!(reading.current(now, Axes::default()), Axes { translation: [-100, 300, 0], rotation: [0, 1, -1] }); // Only rotation arrives again: translation goes stale, rotation stays current. let later = now + STALE_AFTER + Duration::from_millis(1); assert!(decode_report(&[2, 4, 0, 5, 0, 6, 0], layout, &mut reading, later)); - assert_eq!(reading.current(later), Axes { translation: [0; 3], rotation: [4, 5, 6] }); + assert_eq!(reading.current(later, Axes::default()), Axes { translation: [0; 3], rotation: [4, 5, 6] }); // A device sending all six in one report updates both at once. let combined = solidcraft_space_mouse::Descriptor::parse(&[ 0x05, 0x01, 0x09, 0x08, 0xA1, 0x01, 0x85, 0x01, 0x16, 0xA2, 0xFE, 0x26, 0x5E, 0x01, 0x75, 0x10, 0x95, 0x06, 0x19, 0x30, 0x29, 0x35, 0x81, @@ -494,7 +564,7 @@ mod tests { .expect("six axes declared"); let mut both = Reading::new(now); assert!(decode_report(&[1, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0], combined, &mut both, now)); - assert_eq!(both.current(now), Axes { translation: [1, 2, 3], rotation: [4, 5, 6] }); + assert_eq!(both.current(now, Axes::default()), Axes { translation: [1, 2, 3], rotation: [4, 5, 6] }); } #[test] @@ -513,11 +583,11 @@ mod tests { let mut reading = Reading::new(now); assert!(decode_report(&[1, 100, 0], split_x_y, &mut reading, now)); assert!(decode_report(&[2, 200, 0], split_x_y, &mut reading, now)); - assert_eq!(reading.current(now).translation, [100, 200, 0]); + assert_eq!(reading.current(now, Axes::default()).translation, [100, 200, 0]); // Then only X keeps coming: Y goes stale on its own. let later = now + STALE_AFTER + Duration::from_millis(1); assert!(decode_report(&[1, 50, 0], split_x_y, &mut reading, later)); - assert_eq!(reading.current(later).translation, [50, 0, 0]); + assert_eq!(reading.current(later, Axes::default()).translation, [50, 0, 0]); } #[test] @@ -530,8 +600,8 @@ mod tests { let mut reading = Reading::new(now); assert!(decode_report(&[1, 100, 0, 0, 0, 0, 0], layout, &mut reading, now)); // Just before the timeout X is still there; at exactly the timeout it's stale. - assert_eq!(reading.current(now + STALE_AFTER - Duration::from_millis(1)).translation, [100, 0, 0]); - assert_eq!(reading.current(now + STALE_AFTER).translation, [0; 3]); + assert_eq!(reading.current(now + STALE_AFTER - Duration::from_millis(1), Axes::default()).translation, [100, 0, 0]); + assert_eq!(reading.current(now + STALE_AFTER, Axes::default()).translation, [0; 3]); // Button reports and reports with an id the layout doesn't know keep coming, but neither // refreshes X: it goes stale on time all the same. for step in 1..=10 { @@ -539,7 +609,7 @@ mod tests { assert!(decode_report(&[3, 1], layout, &mut reading, at)); assert!(!decode_report(&[0x17, 80], layout, &mut reading, at)); } - assert_eq!(reading.current(now + STALE_AFTER).translation, [0; 3]); + assert_eq!(reading.current(now + STALE_AFTER, Axes::default()).translation, [0; 3]); } #[test] @@ -549,10 +619,10 @@ mod tests { let later = now + STALE_AFTER * 20; // spacenavd sends nothing while the values stay the same: the push lasts. let held = Reading { axes, held: true, ..Reading::new(now) }; - assert_eq!(held.current(later), axes); + assert_eq!(held.current(later, Axes::default()), axes); // A HID device repeats its report: silence means the cap, or the device, is gone. let hid = Reading { axes, ..Reading::new(now) }; - assert_eq!(hid.current(later), Axes::default()); + assert_eq!(hid.current(later, Axes::default()), Axes::default()); } #[test] @@ -624,6 +694,7 @@ mod tests { mapping_checked_at: now, wheel: WheelGuard::default(), started: now, + calibration: None, }; // A window that has run a frame with focus, as the app's always has by now. let ctx = Context::default(); @@ -651,9 +722,84 @@ mod tests { mapping_checked_at: now, wheel: WheelGuard::default(), started: now, + calibration: None, } } + const DEVICE: Source = Source::Hid(Some((0x1234, 0x5678))); + + /// A device whose raw axes all rest at 100, calibrated as such. + fn resting_at_100() -> Calibration { + Calibration { + dead_zone_share: 0.0, + axes: std::array::from_fn(|source| solidcraft_space_mouse::AxisCalibration { + source, + reversed: false, + rest: 100, + dead_zone: 0, + full: [350; 2], + }), + } + } + + #[test] + fn a_calibrated_device_resting_off_zero_leaves_the_wheel_alone() { + // Read raw, X at 100 is the cap pushed past the dead zone: the wheel is dropped. + let now = Instant::now(); + let mut resting = Reading::new(now); + resting.device = Some(DEVICE); + resting.axes = Axes { translation: [100; 3], rotation: [100; 3] }; + let wheel_kept = |calibration| { + let mut mouse = mouse(resting, now); + mouse.calibration = calibration; + let mut raw = egui::RawInput { events: vec![wheel()], ..Default::default() }; + mouse.raw_input_hook_at(true, &mut raw, now); + raw.events.len() == 1 + }; + assert!(!wheel_kept(None)); + // Calibrated, it's at rest, so the wheel is the user's. + assert!(wheel_kept(Some((DEVICE, resting_at_100())))); + // Another device's calibration, kept from the last frame, isn't used for this one. + assert!(!wheel_kept(Some((Source::Hid(Some((0x256f, 0xc63a))), resting_at_100())))); + } + + #[test] + fn a_calibrated_device_resting_off_zero_doesnt_drift_when_nothing_fresh_arrives() { + let mut app = SolveApp::new(solidcraft_engine::Session::default(), solidcraft_ui_egui::Services::default()); + app.home.open = false; + app.preferences.space_mouse_calibrations.insert(DEVICE.key(), resting_at_100()); + // A window that has run a frame with focus, as the app's always has by now. + let ctx = Context::default(); + let mut frame = ctx.run_ui(egui::RawInput::default(), |_| {}); + frame.textures_delta.clear(); + let motion = |app: &mut SolveApp, reading: Reading, now: Instant| { + let mut mouse = mouse(reading, now); + mouse.last_frame = now - Duration::from_millis(20); + app.viewport.device_motion = None; + mouse.tick_at(app, &ctx, now); + app.viewport.device_motion.is_some() + }; + // Connected, and nothing reported yet. + let shared = Mutex::new(Reading::new(Instant::now())); + connected(&Context::default(), &shared, DEVICE); + let fresh = *shared.lock().unwrap(); + let now = Instant::now(); + assert!(!motion(&mut app, fresh, now), "connected, nothing reported yet"); + // The same, while another device's calibration window was open: it ends, and this one + // doesn't move on the first frame either. + app.space_mouse.calibrating = Some(("hid 256f:c63a".into(), solidcraft_space_mouse::Wizard::default())); + assert!(!motion(&mut app, fresh, now), "connected mid-calibration of another device"); + assert!(app.space_mouse.calibrating.is_none()); + // Translation reported at rest, rotation not for a while. + let old = now - STALE_AFTER - Duration::from_millis(1); + let partly = Reading { axes: Axes { translation: [100; 3], rotation: [0; 3] }, at: [now, now, now, old, old, old], ..fresh }; + assert!(!motion(&mut app, partly, now), "translation at rest, rotation stale"); + // Pushed, then the reports stopped. + let pushed = Reading { axes: Axes { translation: [450, 100, 100], rotation: [100; 3] }, at: [old; 6], ..fresh }; + assert!(!motion(&mut app, pushed, now), "the push timed out"); + assert!(motion(&mut app, Reading { at: [now; 6], ..pushed }, now), "a fresh push moves the view"); + } + #[test] fn the_wheel_3dxware_makes_from_the_cap_is_dropped() { // The cap tilted forward: 3DxWare also sends wheel turns (#1380). They are dropped. diff --git a/apps/solidcraft/src/space_mouse/hidraw.rs b/apps/solidcraft/src/space_mouse/hidraw.rs index 46ab29432..45e8f2ba5 100644 --- a/apps/solidcraft/src/space_mouse/hidraw.rs +++ b/apps/solidcraft/src/space_mouse/hidraw.rs @@ -1,6 +1,6 @@ //! Finding a 3D mouse on Linux. The kernel exposes every HID interface as `/dev/hidrawN`, with -//! its report descriptor under `/sys/class/hidraw/hidrawN/device/`. Reading it is plain file -//! I/O, so no udev or hidapi library is needed. +//! its report descriptor and ids under `/sys/class/hidraw/hidrawN/device/`. Reading them is plain +//! file I/O, so no udev or hidapi library is needed. use std::path::{Path, PathBuf}; @@ -12,6 +12,8 @@ const DEV: &str = "/dev"; pub struct Device { pub path: PathBuf, pub layout: Layout, + /// Its vendor and product ids, when the kernel gives them. + pub ids: Option<(u16, u16)>, } /// The first hidraw interface that is a multi-axis controller with motion axes, whoever made it. @@ -25,5 +27,27 @@ fn probe(sysfs: &Path, path: PathBuf) -> Option { let descriptor = Descriptor::parse(&std::fs::read(sysfs.join("device/report_descriptor")).ok()?); // A controller that declares no motion axis (buttons only, say) isn't read. let layout = descriptor.is_multi_axis_controller().then(|| descriptor.layout()).flatten()?; - Some(Device { path, layout }) + let ids = std::fs::read_to_string(sysfs.join("device/uevent")).ok().as_deref().and_then(ids); + Some(Device { path, layout, ids }) +} + +/// The vendor and product ids in a HID device's uevent: `HID_ID=bus:vendor:product`, in hex. +fn ids(uevent: &str) -> Option<(u16, u16)> { + let id = uevent.lines().find_map(|line| line.strip_prefix("HID_ID="))?; + let mut hex = id.split(':').skip(1).map(|part| u32::from_str_radix(part, 16).ok().and_then(|v| u16::try_from(v).ok())); + Some((hex.next()??, hex.next()??)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ids_come_from_the_uevent() { + let wireless = "DRIVER=hid-generic\nHID_ID=0005:0000256F:0000C63A\nHID_NAME=SpaceMouse Wireless BT\n"; + assert_eq!(ids(wireless), Some((0x256f, 0xc63a))); + assert_eq!(ids("HID_ID=0003:0000046D\n"), None); + assert_eq!(ids("HID_ID=0003:0001046D:0000C62B\n"), None, "a vendor past 16 bits isn't a USB id"); + assert_eq!(ids("HID_NAME=keyboard\n"), None); + } } diff --git a/assets/locales/cs.json b/assets/locales/cs.json index e70007ab6..ba131237d 100644 --- a/assets/locales/cs.json +++ b/assets/locales/cs.json @@ -993,6 +993,7 @@ "ui.autosave_every": "Automaticky ukládat každých", "ui.axes": "Osy", "ui.axis": "Osa", + "ui.back": "Zpět", "ui.base_point": "Základní bod", "ui.blocked": "Blokováno", "ui.bodies": "Tělesa", @@ -1398,8 +1399,34 @@ "ui.smooth_wheel_zoom": "Plynulé přiblížení kolečkem", "ui.smooth_wheel_zoom_tip": "Vypnutím se každý pohyb kolečka projeví okamžitě, bez dobíhání", "ui.snap": "Přichytávání", + "ui.space_mouse_calibrate": "Kalibrovat…", + "ui.space_mouse_calibrate_tip": "Pohybujte hlavicí podle pokynů v okně, aby se SolidCraft naučil, kterým směrem a jak daleko se pohybuje každá osa této 3D myši. Uloží se pro tuto 3D myš.", + "ui.space_mouse_calibrate_title": "Kalibrace 3D myši", + "ui.space_mouse_calibrated": "Zkalibrováno", + "ui.space_mouse_calibration": "Kalibrace 3D myši", + "ui.space_mouse_calibration_done": "Hotovo. Uložte ji a použije se vždy, když bude tato 3D myš připojená.", + "ui.space_mouse_calibration_no_response": "Jedna osa se skoro nepohnula, takže ji nelze zkalibrovat. Začněte znovu a pokaždé hlavicí pohněte dál.", + "ui.space_mouse_dead_zone": "Mrtvá zóna", + "ui.space_mouse_dead_zone_tip": "Jak daleko se musí hlavice pohnout, než se pohne pohled, jako podíl jejího plného rozsahu. Zvyšte ji, pokud pohled ujíždí, i když je hlavice v klidu.", + "ui.space_mouse_forget": "Zapomenout kalibraci", "ui.space_mouse_hint": "Posun a otáčení pohledu současně; náčrty používají jen posun a přiblížení.", "ui.space_mouse_navigate": "Navigace pomocí SpaceNavigator / SpaceMouse", + "ui.space_mouse_none": "3D myš nenalezena", + "ui.space_mouse_not_calibrated": "Nezkalibrováno", + "ui.space_mouse_reading": "Hodnoty", + "ui.space_mouse_step_lift": "Zvedněte hlavici nahoru, podržte a pusťte.", + "ui.space_mouse_step_press": "Zatlačte hlavici dolů, podržte a pusťte.", + "ui.space_mouse_step_pull": "Přitáhněte hlavici k sobě, podržte a pusťte.", + "ui.space_mouse_step_push": "Odtlačte hlavici od sebe, podržte a pusťte.", + "ui.space_mouse_step_rest": "Dejte ruku z hlavice a nechte ji v klidu.", + "ui.space_mouse_step_slide_left": "Posuňte hlavici doleva, podržte a pusťte.", + "ui.space_mouse_step_slide_right": "Posuňte hlavici doprava, podržte a pusťte.", + "ui.space_mouse_step_tilt_back": "Nakloňte hlavici dozadu (přední hrana nahoru), podržte a pusťte.", + "ui.space_mouse_step_tilt_forward": "Nakloňte hlavici dopředu (přední hrana dolů), podržte a pusťte.", + "ui.space_mouse_step_tilt_left": "Nakloňte hlavici doleva (levá hrana dolů), podržte a pusťte.", + "ui.space_mouse_step_tilt_right": "Nakloňte hlavici doprava (pravá hrana dolů), podržte a pusťte.", + "ui.space_mouse_step_twist_clockwise": "Otočte hlavici po směru hodinových ručiček, podržte a pusťte.", + "ui.space_mouse_step_twist_counterclockwise": "Otočte hlavici proti směru hodinových ručiček, podržte a pusťte.", "ui.spacing": "Rozteč", "ui.spacing_2": "Rozteč 2", "ui.sphere": "Koule", @@ -1407,6 +1434,7 @@ "ui.split_body": "Rozdělit těleso", "ui.stand_up_tip": "Když se soubor STEP nebo IGES otevře s osou Z nahoru, nabídnout otočení o čtvrt otáčky kolem X", "ui.start": "Start", + "ui.start_over": "Začít znovu", "ui.start_radius": "Počáteční poloměr", "ui.supersampling": "Supersampling (SSAA)", "ui.supersampling_adaptive": "Jen když je pohled v klidu", diff --git a/assets/locales/de.json b/assets/locales/de.json index 4f2e2f2bf..8570b54c6 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -782,6 +782,7 @@ "ui.autosave_every": "Autospeichern alle", "ui.axes": "Achsen", "ui.axis": "Achse", + "ui.back": "Zurück", "ui.base_point": "Basispunkt", "ui.blocked": "Verdeckt", "ui.bodies": "Körper", @@ -1177,12 +1178,39 @@ "ui.slot": "Langloch", "ui.smooth": "Glatt", "ui.snap": "Einrasten", + "ui.space_mouse_calibrate": "Kalibrieren…", + "ui.space_mouse_calibrate_tip": "Bewegen Sie die Kappe so, wie das Fenster es verlangt. So lernt SolidCraft, in welche Richtung und wie weit jede Achse dieser 3D-Maus geht. Wird für diese 3D-Maus gespeichert.", + "ui.space_mouse_calibrate_title": "3D-Maus kalibrieren", + "ui.space_mouse_calibrated": "Kalibriert", + "ui.space_mouse_calibration": "3D-Maus-Kalibrierung", + "ui.space_mouse_calibration_done": "Fertig. Speichern Sie die Kalibrierung, damit sie immer gilt, wenn diese 3D-Maus angeschlossen ist.", + "ui.space_mouse_calibration_no_response": "Eine Achse hat sich kaum bewegt und lässt sich nicht kalibrieren. Beginnen Sie von vorn und bewegen Sie die Kappe jedes Mal weiter.", + "ui.space_mouse_dead_zone": "Totzone", + "ui.space_mouse_dead_zone_tip": "Wie weit sich die Kappe bewegen muss, bevor sich die Ansicht bewegt, als Anteil ihres vollen Wegs. Erhöhen Sie sie, wenn die Ansicht wandert, obwohl die Kappe ruht.", + "ui.space_mouse_forget": "Kalibrierung vergessen", + "ui.space_mouse_none": "Keine 3D-Maus gefunden", + "ui.space_mouse_not_calibrated": "Nicht kalibriert", + "ui.space_mouse_reading": "Werte", + "ui.space_mouse_step_lift": "Kappe nach oben ziehen, halten, dann loslassen.", + "ui.space_mouse_step_press": "Kappe nach unten drücken, halten, dann loslassen.", + "ui.space_mouse_step_pull": "Kappe zu sich heranziehen, halten, dann loslassen.", + "ui.space_mouse_step_push": "Kappe von sich wegschieben, halten, dann loslassen.", + "ui.space_mouse_step_rest": "Nehmen Sie die Hand von der Kappe und lassen Sie sie ruhen.", + "ui.space_mouse_step_slide_left": "Kappe nach links schieben, halten, dann loslassen.", + "ui.space_mouse_step_slide_right": "Kappe nach rechts schieben, halten, dann loslassen.", + "ui.space_mouse_step_tilt_back": "Kappe nach hinten kippen (Vorderkante hoch), halten, dann loslassen.", + "ui.space_mouse_step_tilt_forward": "Kappe nach vorn kippen (Vorderkante runter), halten, dann loslassen.", + "ui.space_mouse_step_tilt_left": "Kappe nach links kippen (linke Kante runter), halten, dann loslassen.", + "ui.space_mouse_step_tilt_right": "Kappe nach rechts kippen (rechte Kante runter), halten, dann loslassen.", + "ui.space_mouse_step_twist_clockwise": "Kappe im Uhrzeigersinn drehen, halten, dann loslassen.", + "ui.space_mouse_step_twist_counterclockwise": "Kappe gegen den Uhrzeigersinn drehen, halten, dann loslassen.", "ui.spacing": "Abstand", "ui.spacing_2": "Abstand 2", "ui.sphere": "Sphäre", "ui.spline": "Spline", "ui.split_body": "Körper trennen", "ui.start": "Start", + "ui.start_over": "Von vorn beginnen", "ui.start_radius": "Startradius", "ui.stretch": "Strecken", "ui.supersampling": "Supersampling (SSAA)", diff --git a/assets/locales/en.json b/assets/locales/en.json index 0e7e3226c..26538886b 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -1074,6 +1074,7 @@ "ui.autosave_every": "Autosave every", "ui.axes": "Axes", "ui.axis": "Axis", + "ui.back": "Back", "ui.base_point": "Base point", "ui.blocked": "Blocked", "ui.bodies": "Bodies", @@ -1508,8 +1509,34 @@ "ui.smooth_wheel_zoom": "Smooth wheel zoom", "ui.smooth_wheel_zoom_tip": "Turn off to apply each wheel event immediately, without a smoothing tail", "ui.snap": "Snap", + "ui.space_mouse_calibrate": "Calibrate…", + "ui.space_mouse_calibrate_tip": "Move the cap as the window asks, so SolidCraft learns which way each axis of this 3D mouse goes and how far. Saved for this 3D mouse.", + "ui.space_mouse_calibrate_title": "Calibrate 3D mouse", + "ui.space_mouse_calibrated": "Calibrated", + "ui.space_mouse_calibration": "3D mouse calibration", + "ui.space_mouse_calibration_done": "Done. Save it to use it whenever this 3D mouse is connected.", + "ui.space_mouse_calibration_no_response": "One axis barely moved, so it can't be calibrated. Start over and move the cap further each time.", + "ui.space_mouse_dead_zone": "Dead zone", + "ui.space_mouse_dead_zone_tip": "How far the cap has to move before the view does, as a share of its full travel. Raise it if the view drifts while the cap is at rest.", + "ui.space_mouse_forget": "Forget calibration", "ui.space_mouse_hint": "Move and rotate the view together; sketches use pan and zoom only.", "ui.space_mouse_navigate": "Navigate with SpaceNavigator / SpaceMouse", + "ui.space_mouse_none": "No 3D mouse found", + "ui.space_mouse_not_calibrated": "Not calibrated", + "ui.space_mouse_reading": "Reading", + "ui.space_mouse_step_lift": "Lift the cap up, hold it, then let go.", + "ui.space_mouse_step_press": "Press the cap down, hold it, then let go.", + "ui.space_mouse_step_pull": "Pull the cap toward you, hold it, then let go.", + "ui.space_mouse_step_push": "Push the cap away from you, hold it, then let go.", + "ui.space_mouse_step_rest": "Take your hand off the cap and leave it still.", + "ui.space_mouse_step_slide_left": "Slide the cap left, hold it, then let go.", + "ui.space_mouse_step_slide_right": "Slide the cap right, hold it, then let go.", + "ui.space_mouse_step_tilt_back": "Tilt the cap back (front edge up), hold it, then let go.", + "ui.space_mouse_step_tilt_forward": "Tilt the cap forward (front edge down), hold it, then let go.", + "ui.space_mouse_step_tilt_left": "Tilt the cap left (left edge down), hold it, then let go.", + "ui.space_mouse_step_tilt_right": "Tilt the cap right (right edge down), hold it, then let go.", + "ui.space_mouse_step_twist_clockwise": "Twist the cap clockwise, hold it, then let go.", + "ui.space_mouse_step_twist_counterclockwise": "Twist the cap anticlockwise, hold it, then let go.", "ui.spacing": "Spacing", "ui.spacing_2": "Spacing 2", "ui.sphere": "Sphere", @@ -1517,6 +1544,7 @@ "ui.split_body": "Split Body", "ui.stand_up_tip": "After a STEP or IGES file opens with Z up, offer a quarter turn about X", "ui.start": "Start", + "ui.start_over": "Start over", "ui.start_radius": "Start Radius", "ui.stretch": "Stretch", "ui.supersampling": "Supersampling (SSAA)", diff --git a/assets/locales/es.json b/assets/locales/es.json index a8939d7e2..3097988a8 100644 --- a/assets/locales/es.json +++ b/assets/locales/es.json @@ -1012,6 +1012,7 @@ "ui.autosave_every": "Guardar automáticamente cada", "ui.axes": "Ejes", "ui.axis": "Eje", + "ui.back": "Atrás", "ui.base_point": "Punto base", "ui.blocked": "Bloqueado", "ui.bodies": "Cuerpos", @@ -1425,8 +1426,34 @@ "ui.smooth_wheel_zoom": "Zoom suave con la rueda", "ui.smooth_wheel_zoom_tip": "Desactívalo para aplicar cada movimiento de la rueda inmediatamente, sin suavizado posterior", "ui.snap": "Referencia a objetos", + "ui.space_mouse_calibrate": "Calibrar…", + "ui.space_mouse_calibrate_tip": "Mueve el capuchón como pide la ventana para que SolidCraft aprenda hacia dónde y hasta dónde va cada eje de este ratón 3D. Se guarda para este ratón 3D.", + "ui.space_mouse_calibrate_title": "Calibrar ratón 3D", + "ui.space_mouse_calibrated": "Calibrado", + "ui.space_mouse_calibration": "Calibración del ratón 3D", + "ui.space_mouse_calibration_done": "Listo. Guárdala para usarla siempre que este ratón 3D esté conectado.", + "ui.space_mouse_calibration_no_response": "Un eje apenas se movió, así que no se puede calibrar. Vuelve a empezar y mueve el capuchón más lejos cada vez.", + "ui.space_mouse_dead_zone": "Zona muerta", + "ui.space_mouse_dead_zone_tip": "Cuánto tiene que moverse el capuchón antes de que se mueva la vista, como parte de su recorrido completo. Auméntala si la vista se desplaza con el capuchón en reposo.", + "ui.space_mouse_forget": "Olvidar calibración", "ui.space_mouse_hint": "Desplaza y gira la vista a la vez; los bocetos solo permiten desplazamiento y zoom.", "ui.space_mouse_navigate": "Navegar con SpaceNavigator / SpaceMouse", + "ui.space_mouse_none": "No se encontró ningún ratón 3D", + "ui.space_mouse_not_calibrated": "Sin calibrar", + "ui.space_mouse_reading": "Lectura", + "ui.space_mouse_step_lift": "Levanta el capuchón, mantenlo y suéltalo.", + "ui.space_mouse_step_press": "Presiona el capuchón hacia abajo, mantenlo y suéltalo.", + "ui.space_mouse_step_pull": "Tira del capuchón hacia ti, mantenlo y suéltalo.", + "ui.space_mouse_step_push": "Empuja el capuchón lejos de ti, mantenlo y suéltalo.", + "ui.space_mouse_step_rest": "Suelta el capuchón y déjalo quieto.", + "ui.space_mouse_step_slide_left": "Desliza el capuchón a la izquierda, mantenlo y suéltalo.", + "ui.space_mouse_step_slide_right": "Desliza el capuchón a la derecha, mantenlo y suéltalo.", + "ui.space_mouse_step_tilt_back": "Inclina el capuchón hacia atrás (borde delantero arriba), mantenlo y suéltalo.", + "ui.space_mouse_step_tilt_forward": "Inclina el capuchón hacia delante (borde delantero abajo), mantenlo y suéltalo.", + "ui.space_mouse_step_tilt_left": "Inclina el capuchón a la izquierda (borde izquierdo abajo), mantenlo y suéltalo.", + "ui.space_mouse_step_tilt_right": "Inclina el capuchón a la derecha (borde derecho abajo), mantenlo y suéltalo.", + "ui.space_mouse_step_twist_clockwise": "Gira el capuchón en sentido horario, mantenlo y suéltalo.", + "ui.space_mouse_step_twist_counterclockwise": "Gira el capuchón en sentido antihorario, mantenlo y suéltalo.", "ui.spacing": "Espaciado", "ui.spacing_2": "Espaciado 2", "ui.sphere": "Esfera", @@ -1434,6 +1461,7 @@ "ui.split_body": "Dividir cuerpo", "ui.stand_up_tip": "Tras abrir un archivo STEP o IGES con Z hacia arriba, ofrecer un cuarto de vuelta alrededor de X", "ui.start": "Iniciar", + "ui.start_over": "Volver a empezar", "ui.start_radius": "Radio inicial", "ui.stretch": "Estirar", "ui.supersampling": "Supermuestreo (SSAA)", diff --git a/assets/locales/fr.json b/assets/locales/fr.json index 6e2feab66..319456076 100644 --- a/assets/locales/fr.json +++ b/assets/locales/fr.json @@ -1021,6 +1021,7 @@ "ui.autosave_every": "Enregistrement automatique toutes les", "ui.axes": "Axes", "ui.axis": "Axe", + "ui.back": "Retour", "ui.base_point": "Point de base", "ui.blocked": "Inaccessible", "ui.bodies": "Corps", @@ -1441,8 +1442,34 @@ "ui.smooth_wheel_zoom": "Zoom fluide à la molette", "ui.smooth_wheel_zoom_tip": "Désactiver pour appliquer chaque cran de molette immédiatement, sans lissage", "ui.snap": "Accrochage", + "ui.space_mouse_calibrate": "Calibrer…", + "ui.space_mouse_calibrate_tip": "Déplacez le capuchon comme la fenêtre le demande, pour que SolidCraft apprenne dans quel sens et jusqu'où va chaque axe de cette souris 3D. Enregistré pour cette souris 3D.", + "ui.space_mouse_calibrate_title": "Calibrer la souris 3D", + "ui.space_mouse_calibrated": "Calibrée", + "ui.space_mouse_calibration": "Calibrage de la souris 3D", + "ui.space_mouse_calibration_done": "Terminé. Enregistrez-le pour l'utiliser chaque fois que cette souris 3D est connectée.", + "ui.space_mouse_calibration_no_response": "Un axe a à peine bougé, il ne peut donc pas être calibré. Recommencez en déplaçant le capuchon plus loin à chaque fois.", + "ui.space_mouse_dead_zone": "Zone morte", + "ui.space_mouse_dead_zone_tip": "De combien le capuchon doit bouger avant que la vue ne bouge, en part de sa course complète. Augmentez-la si la vue dérive alors que le capuchon est au repos.", + "ui.space_mouse_forget": "Oublier le calibrage", "ui.space_mouse_hint": "Déplace et fait pivoter la vue en même temps ; dans les esquisses, seuls le panoramique et le zoom sont utilisés.", "ui.space_mouse_navigate": "Naviguer avec SpaceNavigator / SpaceMouse", + "ui.space_mouse_none": "Aucune souris 3D trouvée", + "ui.space_mouse_not_calibrated": "Non calibrée", + "ui.space_mouse_reading": "Lecture", + "ui.space_mouse_step_lift": "Soulevez le capuchon, maintenez, puis relâchez.", + "ui.space_mouse_step_press": "Appuyez sur le capuchon, maintenez, puis relâchez.", + "ui.space_mouse_step_pull": "Tirez le capuchon vers vous, maintenez, puis relâchez.", + "ui.space_mouse_step_push": "Poussez le capuchon loin de vous, maintenez, puis relâchez.", + "ui.space_mouse_step_rest": "Lâchez le capuchon et laissez-le immobile.", + "ui.space_mouse_step_slide_left": "Glissez le capuchon vers la gauche, maintenez, puis relâchez.", + "ui.space_mouse_step_slide_right": "Glissez le capuchon vers la droite, maintenez, puis relâchez.", + "ui.space_mouse_step_tilt_back": "Inclinez le capuchon vers l'arrière (bord avant vers le haut), maintenez, puis relâchez.", + "ui.space_mouse_step_tilt_forward": "Inclinez le capuchon vers l'avant (bord avant vers le bas), maintenez, puis relâchez.", + "ui.space_mouse_step_tilt_left": "Inclinez le capuchon vers la gauche (bord gauche vers le bas), maintenez, puis relâchez.", + "ui.space_mouse_step_tilt_right": "Inclinez le capuchon vers la droite (bord droit vers le bas), maintenez, puis relâchez.", + "ui.space_mouse_step_twist_clockwise": "Tournez le capuchon dans le sens horaire, maintenez, puis relâchez.", + "ui.space_mouse_step_twist_counterclockwise": "Tournez le capuchon dans le sens antihoraire, maintenez, puis relâchez.", "ui.spacing": "Espacement", "ui.spacing_2": "Espacement 2", "ui.sphere": "Sphère", @@ -1450,6 +1477,7 @@ "ui.split_body": "Scinder le corps", "ui.stand_up_tip": "Après l'ouverture d'un fichier STEP ou IGES avec Z vers le haut, proposer un quart de tour autour de X", "ui.start": "Début", + "ui.start_over": "Recommencer", "ui.start_radius": "Rayon initial", "ui.stretch": "Étirer", "ui.supersampling": "Suréchantillonnage (SSAA)", diff --git a/assets/locales/gl.json b/assets/locales/gl.json index b0960fee8..c3a8e6a4d 100644 --- a/assets/locales/gl.json +++ b/assets/locales/gl.json @@ -984,6 +984,7 @@ "ui.autosave_every": "Gardar automaticamente cada", "ui.axes": "Eixes", "ui.axis": "Eixe", + "ui.back": "Atrás", "ui.base_point": "Punto base", "ui.blocked": "Bloqueado", "ui.bodies": "Corpos", @@ -1389,8 +1390,34 @@ "ui.smooth_wheel_zoom": "Zoom suave coa roda", "ui.smooth_wheel_zoom_tip": "Desactívao para aplicar cada movemento da roda de inmediato, sen suavizado", "ui.snap": "Axuste", + "ui.space_mouse_calibrate": "Calibrar…", + "ui.space_mouse_calibrate_tip": "Move o capuchón como pide a xanela para que SolidCraft aprenda cara a onde e ata onde vai cada eixe deste rato 3D. Gárdase para este rato 3D.", + "ui.space_mouse_calibrate_title": "Calibrar o rato 3D", + "ui.space_mouse_calibrated": "Calibrado", + "ui.space_mouse_calibration": "Calibración do rato 3D", + "ui.space_mouse_calibration_done": "Feito. Gárdaa para usala sempre que este rato 3D estea conectado.", + "ui.space_mouse_calibration_no_response": "Un eixe case non se moveu, así que non se pode calibrar. Volve comezar e move o capuchón máis lonxe cada vez.", + "ui.space_mouse_dead_zone": "Zona morta", + "ui.space_mouse_dead_zone_tip": "Canto ten que moverse o capuchón antes de que se mova a vista, como parte do seu percorrido completo. Auméntaa se a vista se despraza co capuchón en repouso.", + "ui.space_mouse_forget": "Esquecer a calibración", "ui.space_mouse_hint": "Move e rota a vista á vez; os bosquexos só usan desprazamento e zoom.", "ui.space_mouse_navigate": "Navegar con SpaceNavigator / SpaceMouse", + "ui.space_mouse_none": "Non se atopou ningún rato 3D", + "ui.space_mouse_not_calibrated": "Sen calibrar", + "ui.space_mouse_reading": "Lectura", + "ui.space_mouse_step_lift": "Levanta o capuchón, mantéño e sóltao.", + "ui.space_mouse_step_press": "Preme o capuchón cara abaixo, mantéño e sóltao.", + "ui.space_mouse_step_pull": "Tira do capuchón cara a ti, mantéño e sóltao.", + "ui.space_mouse_step_push": "Empurra o capuchón lonxe de ti, mantéño e sóltao.", + "ui.space_mouse_step_rest": "Solta o capuchón e déixao quieto.", + "ui.space_mouse_step_slide_left": "Despraza o capuchón á esquerda, mantéño e sóltao.", + "ui.space_mouse_step_slide_right": "Despraza o capuchón á dereita, mantéño e sóltao.", + "ui.space_mouse_step_tilt_back": "Inclina o capuchón cara atrás (bordo dianteiro arriba), mantéño e sóltao.", + "ui.space_mouse_step_tilt_forward": "Inclina o capuchón cara adiante (bordo dianteiro abaixo), mantéño e sóltao.", + "ui.space_mouse_step_tilt_left": "Inclina o capuchón á esquerda (bordo esquerdo abaixo), mantéño e sóltao.", + "ui.space_mouse_step_tilt_right": "Inclina o capuchón á dereita (bordo dereito abaixo), mantéño e sóltao.", + "ui.space_mouse_step_twist_clockwise": "Xira o capuchón no sentido horario, mantéño e sóltao.", + "ui.space_mouse_step_twist_counterclockwise": "Xira o capuchón no sentido antihorario, mantéño e sóltao.", "ui.spacing": "Espazado", "ui.spacing_2": "Espazado 2", "ui.sphere": "Esfera", @@ -1398,6 +1425,7 @@ "ui.split_body": "Dividir o corpo", "ui.stand_up_tip": "Despois de abrir un ficheiro STEP ou IGES con Z cara arriba, ofrecer un cuarto de volta arredor de X", "ui.start": "Inicio", + "ui.start_over": "Volver comezar", "ui.start_radius": "Raio inicial", "ui.supersampling": "Supermostraxe (SSAA)", "ui.supersampling_adaptive": "Só cando a vista está quieta", diff --git a/assets/locales/it.json b/assets/locales/it.json index 4b02cc884..05720236e 100644 --- a/assets/locales/it.json +++ b/assets/locales/it.json @@ -1010,6 +1010,7 @@ "ui.autosave_every": "Salvataggio automatico ogni", "ui.axes": "Assi", "ui.axis": "Asse", + "ui.back": "Indietro", "ui.base_point": "Punto base", "ui.blocked": "Bloccato", "ui.bodies": "Corpi", @@ -1423,8 +1424,34 @@ "ui.smooth_wheel_zoom": "Zoom fluido con rotellina", "ui.smooth_wheel_zoom_tip": "Disattiva per applicare immediatamente ogni evento della rotellina, senza coda di interpolazione", "ui.snap": "Aggancio", + "ui.space_mouse_calibrate": "Calibra…", + "ui.space_mouse_calibrate_tip": "Muovi la manopola come chiede la finestra, così SolidCraft impara in che direzione e quanto va ogni asse di questo mouse 3D. Viene salvata per questo mouse 3D.", + "ui.space_mouse_calibrate_title": "Calibra mouse 3D", + "ui.space_mouse_calibrated": "Calibrato", + "ui.space_mouse_calibration": "Calibrazione del mouse 3D", + "ui.space_mouse_calibration_done": "Fatto. Salvala per usarla ogni volta che questo mouse 3D è collegato.", + "ui.space_mouse_calibration_no_response": "Un asse si è mosso appena, quindi non si può calibrare. Ricomincia e muovi la manopola più a fondo ogni volta.", + "ui.space_mouse_dead_zone": "Zona morta", + "ui.space_mouse_dead_zone_tip": "Quanto deve muoversi la manopola prima che si muova la vista, come quota della sua corsa completa. Aumentala se la vista si sposta con la manopola a riposo.", + "ui.space_mouse_forget": "Dimentica calibrazione", "ui.space_mouse_hint": "Sposta e ruota la vista insieme; gli schizzi usano solo panoramica e zoom.", "ui.space_mouse_navigate": "Naviga con SpaceNavigator / SpaceMouse", + "ui.space_mouse_none": "Nessun mouse 3D trovato", + "ui.space_mouse_not_calibrated": "Non calibrato", + "ui.space_mouse_reading": "Lettura", + "ui.space_mouse_step_lift": "Solleva la manopola, tienila, poi lasciala.", + "ui.space_mouse_step_press": "Premi la manopola verso il basso, tienila, poi lasciala.", + "ui.space_mouse_step_pull": "Tira la manopola verso di te, tienila, poi lasciala.", + "ui.space_mouse_step_push": "Spingi la manopola lontano da te, tienila, poi lasciala.", + "ui.space_mouse_step_rest": "Togli la mano dalla manopola e lasciala ferma.", + "ui.space_mouse_step_slide_left": "Fai scorrere la manopola a sinistra, tienila, poi lasciala.", + "ui.space_mouse_step_slide_right": "Fai scorrere la manopola a destra, tienila, poi lasciala.", + "ui.space_mouse_step_tilt_back": "Inclina la manopola all'indietro (bordo anteriore in alto), tienila, poi lasciala.", + "ui.space_mouse_step_tilt_forward": "Inclina la manopola in avanti (bordo anteriore in basso), tienila, poi lasciala.", + "ui.space_mouse_step_tilt_left": "Inclina la manopola a sinistra (bordo sinistro in basso), tienila, poi lasciala.", + "ui.space_mouse_step_tilt_right": "Inclina la manopola a destra (bordo destro in basso), tienila, poi lasciala.", + "ui.space_mouse_step_twist_clockwise": "Ruota la manopola in senso orario, tienila, poi lasciala.", + "ui.space_mouse_step_twist_counterclockwise": "Ruota la manopola in senso antiorario, tienila, poi lasciala.", "ui.spacing": "Spaziatura", "ui.spacing_2": "Spaziatura 2", "ui.sphere": "Sfera", @@ -1432,6 +1459,7 @@ "ui.split_body": "Dividi corpo", "ui.stand_up_tip": "Dopo l'apertura di un file STEP o IGES con asse Z verticale, proponi un quarto di giro attorno a X", "ui.start": "Inizio", + "ui.start_over": "Ricomincia", "ui.start_radius": "Raggio iniziale", "ui.stretch": "Stira", "ui.supersampling": "Sovracampionamento (SSAA)", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index f1f4ac468..02c5e371d 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -1074,6 +1074,7 @@ "ui.autosave_every": "自動保存の間隔", "ui.axes": "軸", "ui.axis": "軸", + "ui.back": "戻る", "ui.base_point": "基点", "ui.blocked": "到達不可", "ui.bodies": "ボディ", @@ -1508,8 +1509,34 @@ "ui.smooth_wheel_zoom": "滑らかなホイールズーム", "ui.smooth_wheel_zoom_tip": "オフにすると、ホイール操作のたびにズームが即座に反映され、滑らかな減速効果は適用されません。", "ui.snap": "スナップ", + "ui.space_mouse_calibrate": "キャリブレーション…", + "ui.space_mouse_calibrate_tip": "ウィンドウの指示どおりにキャップを動かすと、この3Dマウスの各軸の向きと移動量をSolidCraftが学習します。この3Dマウス用に保存されます。", + "ui.space_mouse_calibrate_title": "3Dマウスのキャリブレーション", + "ui.space_mouse_calibrated": "キャリブレーション済み", + "ui.space_mouse_calibration": "3Dマウスのキャリブレーション", + "ui.space_mouse_calibration_done": "完了しました。保存すると、この3Dマウスを接続したときに毎回使われます。", + "ui.space_mouse_calibration_no_response": "ほとんど動かなかった軸があるため、キャリブレーションできません。最初からやり直し、毎回キャップをもっと大きく動かしてください。", + "ui.space_mouse_dead_zone": "デッドゾーン", + "ui.space_mouse_dead_zone_tip": "視点が動き出すまでにキャップを動かす量(全ストロークに対する割合)。キャップに触れていないのに視点が動く場合は大きくしてください。", + "ui.space_mouse_forget": "キャリブレーションを削除", "ui.space_mouse_hint": "視点の移動と回転を同時に行います(スケッチ中はパンとズームのみ)", "ui.space_mouse_navigate": "SpaceNavigator / SpaceMouseで視点を操作", + "ui.space_mouse_none": "3Dマウスが見つかりません", + "ui.space_mouse_not_calibrated": "未キャリブレーション", + "ui.space_mouse_reading": "読み取り値", + "ui.space_mouse_step_lift": "キャップを持ち上げて保持し、離してください。", + "ui.space_mouse_step_press": "キャップを押し下げて保持し、離してください。", + "ui.space_mouse_step_pull": "キャップを手前に引いて保持し、離してください。", + "ui.space_mouse_step_push": "キャップを奥に押して保持し、離してください。", + "ui.space_mouse_step_rest": "キャップから手を離し、動かさないでください。", + "ui.space_mouse_step_slide_left": "キャップを左にスライドして保持し、離してください。", + "ui.space_mouse_step_slide_right": "キャップを右にスライドして保持し、離してください。", + "ui.space_mouse_step_tilt_back": "キャップを後ろに傾け(手前の縁を上げて)保持し、離してください。", + "ui.space_mouse_step_tilt_forward": "キャップを前に傾け(手前の縁を下げて)保持し、離してください。", + "ui.space_mouse_step_tilt_left": "キャップを左に傾け(左の縁を下げて)保持し、離してください。", + "ui.space_mouse_step_tilt_right": "キャップを右に傾け(右の縁を下げて)保持し、離してください。", + "ui.space_mouse_step_twist_clockwise": "キャップを時計回りにひねって保持し、離してください。", + "ui.space_mouse_step_twist_counterclockwise": "キャップを反時計回りにひねって保持し、離してください。", "ui.spacing": "間隔", "ui.spacing_2": "間隔 2", "ui.sphere": "球", @@ -1517,6 +1544,7 @@ "ui.split_body": "ボディを分割", "ui.stand_up_tip": "Z軸上向きで開いたSTEPまたはIGESファイルに対し、X軸周りに90度回転させるか確認します", "ui.start": "開始", + "ui.start_over": "最初からやり直す", "ui.start_radius": "開始半径", "ui.stretch": "伸縮", "ui.supersampling": "スーパーサンプリング (SSAA)", diff --git a/assets/locales/ko.json b/assets/locales/ko.json index ba118b798..21198a398 100644 --- a/assets/locales/ko.json +++ b/assets/locales/ko.json @@ -782,6 +782,7 @@ "ui.autosave_every": "자동 저장 간격", "ui.axes": "축", "ui.axis": "축", + "ui.back": "뒤로", "ui.base_point": "기준점", "ui.blocked": "막힘", "ui.bodies": "바디", @@ -1174,12 +1175,39 @@ "ui.slot": "슬롯", "ui.smooth": "부드럽게", "ui.snap": "스냅", + "ui.space_mouse_calibrate": "보정…", + "ui.space_mouse_calibrate_tip": "창의 안내대로 캡을 움직이면 SolidCraft가 이 3D 마우스의 각 축이 어느 방향으로 얼마나 움직이는지 학습합니다. 이 3D 마우스에 저장됩니다.", + "ui.space_mouse_calibrate_title": "3D 마우스 보정", + "ui.space_mouse_calibrated": "보정됨", + "ui.space_mouse_calibration": "3D 마우스 보정", + "ui.space_mouse_calibration_done": "완료했습니다. 저장하면 이 3D 마우스를 연결할 때마다 사용됩니다.", + "ui.space_mouse_calibration_no_response": "거의 움직이지 않은 축이 있어 보정할 수 없습니다. 처음부터 다시 하고 매번 캡을 더 멀리 움직이세요.", + "ui.space_mouse_dead_zone": "데드존", + "ui.space_mouse_dead_zone_tip": "보기가 움직이기 전에 캡이 움직여야 하는 정도로, 전체 이동 범위에 대한 비율입니다. 캡을 건드리지 않았는데 보기가 움직이면 높이세요.", + "ui.space_mouse_forget": "보정 삭제", + "ui.space_mouse_none": "3D 마우스를 찾을 수 없음", + "ui.space_mouse_not_calibrated": "보정 안 됨", + "ui.space_mouse_reading": "읽은 값", + "ui.space_mouse_step_lift": "캡을 위로 들어 유지한 다음 놓으세요.", + "ui.space_mouse_step_press": "캡을 아래로 눌러 유지한 다음 놓으세요.", + "ui.space_mouse_step_pull": "캡을 몸 쪽으로 당겨 유지한 다음 놓으세요.", + "ui.space_mouse_step_push": "캡을 앞쪽으로 밀어 유지한 다음 놓으세요.", + "ui.space_mouse_step_rest": "캡에서 손을 떼고 가만히 두세요.", + "ui.space_mouse_step_slide_left": "캡을 왼쪽으로 밀어 유지한 다음 놓으세요.", + "ui.space_mouse_step_slide_right": "캡을 오른쪽으로 밀어 유지한 다음 놓으세요.", + "ui.space_mouse_step_tilt_back": "캡을 뒤로 기울여(앞쪽 가장자리를 위로) 유지한 다음 놓으세요.", + "ui.space_mouse_step_tilt_forward": "캡을 앞으로 기울여(앞쪽 가장자리를 아래로) 유지한 다음 놓으세요.", + "ui.space_mouse_step_tilt_left": "캡을 왼쪽으로 기울여(왼쪽 가장자리를 아래로) 유지한 다음 놓으세요.", + "ui.space_mouse_step_tilt_right": "캡을 오른쪽으로 기울여(오른쪽 가장자리를 아래로) 유지한 다음 놓으세요.", + "ui.space_mouse_step_twist_clockwise": "캡을 시계 방향으로 돌려 유지한 다음 놓으세요.", + "ui.space_mouse_step_twist_counterclockwise": "캡을 시계 반대 방향으로 돌려 유지한 다음 놓으세요.", "ui.spacing": "간격", "ui.spacing_2": "간격 2", "ui.sphere": "구", "ui.spline": "스플라인", "ui.split_body": "바디 분할", "ui.start": "시작", + "ui.start_over": "처음부터 다시", "ui.start_radius": "시작 반지름", "ui.supersampling": "슈퍼샘플링 (SSAA)", "ui.supersampling_adaptive": "뷰가 멈춰 있을 때만", diff --git a/assets/locales/pt-BR.json b/assets/locales/pt-BR.json index 4e3328550..0bc5944f9 100644 --- a/assets/locales/pt-BR.json +++ b/assets/locales/pt-BR.json @@ -964,6 +964,7 @@ "ui.autosave_every": "Salvar automaticamente a cada", "ui.axes": "Eixos", "ui.axis": "Eixo", + "ui.back": "Voltar", "ui.base_point": "Ponto base", "ui.blocked": "Bloqueado", "ui.bodies": "Corpos", @@ -1369,8 +1370,34 @@ "ui.smooth_wheel_zoom": "Zoom suave com a roda", "ui.smooth_wheel_zoom_tip": "Desative para aplicar cada evento da roda na hora, sem rastro de suavização", "ui.snap": "Encaixe", + "ui.space_mouse_calibrate": "Calibrar…", + "ui.space_mouse_calibrate_tip": "Mova a tampa como a janela pedir, para que o SolidCraft aprenda para onde e até onde vai cada eixo deste mouse 3D. Salvo para este mouse 3D.", + "ui.space_mouse_calibrate_title": "Calibrar mouse 3D", + "ui.space_mouse_calibrated": "Calibrado", + "ui.space_mouse_calibration": "Calibração do mouse 3D", + "ui.space_mouse_calibration_done": "Pronto. Salve para usá-la sempre que este mouse 3D estiver conectado.", + "ui.space_mouse_calibration_no_response": "Um eixo quase não se moveu, então não dá para calibrá-lo. Recomece e mova a tampa mais longe a cada vez.", + "ui.space_mouse_dead_zone": "Zona morta", + "ui.space_mouse_dead_zone_tip": "Quanto a tampa precisa se mover antes de a vista se mover, como fração do curso completo. Aumente se a vista se mexer com a tampa parada.", + "ui.space_mouse_forget": "Esquecer calibração", "ui.space_mouse_hint": "Move e gira a vista juntos; esboços usam apenas deslocamento e zoom.", "ui.space_mouse_navigate": "Navegar com SpaceNavigator / SpaceMouse", + "ui.space_mouse_none": "Nenhum mouse 3D encontrado", + "ui.space_mouse_not_calibrated": "Não calibrado", + "ui.space_mouse_reading": "Leitura", + "ui.space_mouse_step_lift": "Levante a tampa, segure e solte.", + "ui.space_mouse_step_press": "Pressione a tampa para baixo, segure e solte.", + "ui.space_mouse_step_pull": "Puxe a tampa na sua direção, segure e solte.", + "ui.space_mouse_step_push": "Empurre a tampa para longe de você, segure e solte.", + "ui.space_mouse_step_rest": "Tire a mão da tampa e deixe-a parada.", + "ui.space_mouse_step_slide_left": "Deslize a tampa para a esquerda, segure e solte.", + "ui.space_mouse_step_slide_right": "Deslize a tampa para a direita, segure e solte.", + "ui.space_mouse_step_tilt_back": "Incline a tampa para trás (borda da frente para cima), segure e solte.", + "ui.space_mouse_step_tilt_forward": "Incline a tampa para a frente (borda da frente para baixo), segure e solte.", + "ui.space_mouse_step_tilt_left": "Incline a tampa para a esquerda (borda esquerda para baixo), segure e solte.", + "ui.space_mouse_step_tilt_right": "Incline a tampa para a direita (borda direita para baixo), segure e solte.", + "ui.space_mouse_step_twist_clockwise": "Gire a tampa no sentido horário, segure e solte.", + "ui.space_mouse_step_twist_counterclockwise": "Gire a tampa no sentido anti-horário, segure e solte.", "ui.spacing": "Espaçamento", "ui.spacing_2": "Espaçamento 2", "ui.sphere": "Esfera", @@ -1378,6 +1405,7 @@ "ui.split_body": "Dividir corpo", "ui.stand_up_tip": "Depois que um arquivo STEP ou IGES abrir com Z para cima, oferecer um quarto de volta em torno de X", "ui.start": "Início", + "ui.start_over": "Recomeçar", "ui.start_radius": "Raio inicial", "ui.supersampling": "Supersampling (SSAA)", "ui.supersampling_adaptive": "Só quando a vista está parada", diff --git a/assets/locales/ru.json b/assets/locales/ru.json index 7cc15552e..9cd04228a 100644 --- a/assets/locales/ru.json +++ b/assets/locales/ru.json @@ -776,6 +776,7 @@ "ui.autosave_every": "Автосохранение каждые", "ui.axes": "Оси", "ui.axis": "Ось", + "ui.back": "Назад", "ui.base_point": "Базовая точка", "ui.bodies": "Тела", "ui.box": "Бокс", @@ -1177,8 +1178,34 @@ "ui.smooth_wheel_zoom": "Плавное масштабирование колесом", "ui.smooth_wheel_zoom_tip": "Отключите, чтобы каждое движение колеса применялось сразу, без сглаживания", "ui.snap": "Привязка", + "ui.space_mouse_calibrate": "Калибровать…", + "ui.space_mouse_calibrate_tip": "Двигайте колпачок так, как просит окно, чтобы SolidCraft узнал, куда и насколько далеко движется каждая ось этой 3D-мыши. Сохраняется для этой 3D-мыши.", + "ui.space_mouse_calibrate_title": "Калибровка 3D-мыши", + "ui.space_mouse_calibrated": "Откалибрована", + "ui.space_mouse_calibration": "Калибровка 3D-мыши", + "ui.space_mouse_calibration_done": "Готово. Сохраните её, чтобы она применялась всякий раз, когда подключена эта 3D-мышь.", + "ui.space_mouse_calibration_no_response": "Одна ось почти не сдвинулась, поэтому её нельзя откалибровать. Начните заново и каждый раз двигайте колпачок дальше.", + "ui.space_mouse_dead_zone": "Мёртвая зона", + "ui.space_mouse_dead_zone_tip": "Насколько нужно сдвинуть колпачок, прежде чем сдвинется вид, в доле от полного хода. Увеличьте, если вид смещается, когда колпачок в покое.", + "ui.space_mouse_forget": "Забыть калибровку", "ui.space_mouse_hint": "Совместное перемещение и вращение вида; в эскизе — только панорама и масштаб.", "ui.space_mouse_navigate": "Навигация через SpaceNavigator / SpaceMouse", + "ui.space_mouse_none": "3D-мышь не найдена", + "ui.space_mouse_not_calibrated": "Не откалибрована", + "ui.space_mouse_reading": "Показания", + "ui.space_mouse_step_lift": "Поднимите колпачок вверх, удержите и отпустите.", + "ui.space_mouse_step_press": "Нажмите на колпачок вниз, удержите и отпустите.", + "ui.space_mouse_step_pull": "Потяните колпачок на себя, удержите и отпустите.", + "ui.space_mouse_step_push": "Толкните колпачок от себя, удержите и отпустите.", + "ui.space_mouse_step_rest": "Уберите руку с колпачка и не трогайте его.", + "ui.space_mouse_step_slide_left": "Сдвиньте колпачок влево, удержите и отпустите.", + "ui.space_mouse_step_slide_right": "Сдвиньте колпачок вправо, удержите и отпустите.", + "ui.space_mouse_step_tilt_back": "Наклоните колпачок назад (передний край вверх), удержите и отпустите.", + "ui.space_mouse_step_tilt_forward": "Наклоните колпачок вперёд (передний край вниз), удержите и отпустите.", + "ui.space_mouse_step_tilt_left": "Наклоните колпачок влево (левый край вниз), удержите и отпустите.", + "ui.space_mouse_step_tilt_right": "Наклоните колпачок вправо (правый край вниз), удержите и отпустите.", + "ui.space_mouse_step_twist_clockwise": "Поверните колпачок по часовой стрелке, удержите и отпустите.", + "ui.space_mouse_step_twist_counterclockwise": "Поверните колпачок против часовой стрелки, удержите и отпустите.", "ui.spacing": "Интервал", "ui.spacing_2": "Интервал 2", "ui.sphere": "Сфера", @@ -1186,6 +1213,7 @@ "ui.split_body": "Разделить тело", "ui.stand_up_tip": "Если файл STEP или IGES открывается с Z вверх, предложить поворот на четверть оборота вокруг X", "ui.start": "Старт", + "ui.start_over": "Начать заново", "ui.start_radius": "Начальный радиус", "ui.suppress": "Подавить", "ui.sweep": "Сдвиг", diff --git a/assets/locales/tr.json b/assets/locales/tr.json index 861dd5fc5..f22c0478b 100644 --- a/assets/locales/tr.json +++ b/assets/locales/tr.json @@ -913,6 +913,7 @@ "ui.autosave_every": "Otomatik kaydetme aralığı", "ui.axes": "Eksenler", "ui.axis": "Eksen", + "ui.back": "Geri", "ui.base_point": "Temel nokta", "ui.blocked": "Engellenmiş", "ui.bodies": "Gövdeler", @@ -1316,8 +1317,34 @@ "ui.smooth_wheel_zoom": "Yumuşak tekerlek yakınlaştırması", "ui.smooth_wheel_zoom_tip": "Her tekerlek hareketini yumuşatma olmadan hemen uygulamak için kapatın", "ui.snap": "Yakala", + "ui.space_mouse_calibrate": "Kalibre et…", + "ui.space_mouse_calibrate_tip": "Pencerenin istediği gibi başlığı hareket ettirin; SolidCraft bu 3B farenin her ekseninin hangi yöne ve ne kadar gittiğini öğrensin. Bu 3B fare için kaydedilir.", + "ui.space_mouse_calibrate_title": "3B fareyi kalibre et", + "ui.space_mouse_calibrated": "Kalibre edildi", + "ui.space_mouse_calibration": "3B fare kalibrasyonu", + "ui.space_mouse_calibration_done": "Bitti. Bu 3B fare her bağlandığında kullanılması için kaydedin.", + "ui.space_mouse_calibration_no_response": "Bir eksen neredeyse hiç hareket etmedi, bu yüzden kalibre edilemiyor. Baştan başlayın ve başlığı her seferinde daha fazla hareket ettirin.", + "ui.space_mouse_dead_zone": "Ölü bölge", + "ui.space_mouse_dead_zone_tip": "Görünüm hareket etmeden önce başlığın ne kadar hareket etmesi gerektiği, tam hareket aralığının oranı olarak. Başlık dururken görünüm kayıyorsa artırın.", + "ui.space_mouse_forget": "Kalibrasyonu unut", "ui.space_mouse_hint": "Görünümü aynı anda kaydırın ve döndürün; eskizlerde yalnızca kaydırma ve yakınlaştırma kullanılır.", "ui.space_mouse_navigate": "SpaceNavigator / SpaceMouse ile gezin", + "ui.space_mouse_none": "3B fare bulunamadı", + "ui.space_mouse_not_calibrated": "Kalibre edilmedi", + "ui.space_mouse_reading": "Okunan değer", + "ui.space_mouse_step_lift": "Başlığı yukarı kaldırın, tutun, sonra bırakın.", + "ui.space_mouse_step_press": "Başlığı aşağı bastırın, tutun, sonra bırakın.", + "ui.space_mouse_step_pull": "Başlığı kendinize doğru çekin, tutun, sonra bırakın.", + "ui.space_mouse_step_push": "Başlığı sizden uzağa itin, tutun, sonra bırakın.", + "ui.space_mouse_step_rest": "Elinizi başlıktan çekin ve hareketsiz bırakın.", + "ui.space_mouse_step_slide_left": "Başlığı sola kaydırın, tutun, sonra bırakın.", + "ui.space_mouse_step_slide_right": "Başlığı sağa kaydırın, tutun, sonra bırakın.", + "ui.space_mouse_step_tilt_back": "Başlığı geriye eğin (ön kenar yukarı), tutun, sonra bırakın.", + "ui.space_mouse_step_tilt_forward": "Başlığı öne eğin (ön kenar aşağı), tutun, sonra bırakın.", + "ui.space_mouse_step_tilt_left": "Başlığı sola eğin (sol kenar aşağı), tutun, sonra bırakın.", + "ui.space_mouse_step_tilt_right": "Başlığı sağa eğin (sağ kenar aşağı), tutun, sonra bırakın.", + "ui.space_mouse_step_twist_clockwise": "Başlığı saat yönünde çevirin, tutun, sonra bırakın.", + "ui.space_mouse_step_twist_counterclockwise": "Başlığı saat yönünün tersine çevirin, tutun, sonra bırakın.", "ui.spacing": "Aralık", "ui.spacing_2": "Aralık 2", "ui.sphere": "Küre", @@ -1325,6 +1352,7 @@ "ui.split_body": "Gövdeyi böl", "ui.stand_up_tip": "Bir STEP veya IGES dosyası Z yukarı olarak açıldığında X etrafında çeyrek tur döndürmeyi öner", "ui.start": "Başlangıç", + "ui.start_over": "Baştan başla", "ui.start_radius": "Başlangıç yarıçapı", "ui.supersampling": "Süper örnekleme (SSAA)", "ui.supersampling_adaptive": "Yalnızca görünüm hareketsizken", diff --git a/assets/locales/uk.json b/assets/locales/uk.json index 2a936339b..ad83c4703 100644 --- a/assets/locales/uk.json +++ b/assets/locales/uk.json @@ -987,6 +987,7 @@ "ui.autosave_every": "Автозбереження кожні", "ui.axes": "Осі", "ui.axis": "Вісь", + "ui.back": "Назад", "ui.base_point": "Базова точка", "ui.blocked": "Заблоковані", "ui.bodies": "Тіла", @@ -1392,8 +1393,34 @@ "ui.smooth_wheel_zoom": "Плавне масштабування колесом", "ui.smooth_wheel_zoom_tip": "Вимкніть, щоб застосовувати кожну подію колеса негайно, без плавного завершення", "ui.snap": "Прив'язка", + "ui.space_mouse_calibrate": "Калібрувати…", + "ui.space_mouse_calibrate_tip": "Рухайте ковпачок так, як просить вікно, щоб SolidCraft дізнався, куди й наскільки далеко рухається кожна вісь цієї 3D-миші. Зберігається для цієї 3D-миші.", + "ui.space_mouse_calibrate_title": "Калібрування 3D-миші", + "ui.space_mouse_calibrated": "Відкалібровано", + "ui.space_mouse_calibration": "Калібрування 3D-миші", + "ui.space_mouse_calibration_done": "Готово. Збережіть його, щоб воно застосовувалося щоразу, коли підключено цю 3D-мишу.", + "ui.space_mouse_calibration_no_response": "Одна вісь майже не зрушила, тому її не можна відкалібрувати. Почніть спочатку й щоразу рухайте ковпачок далі.", + "ui.space_mouse_dead_zone": "Мертва зона", + "ui.space_mouse_dead_zone_tip": "Наскільки треба зсунути ковпачок, перш ніж зрушить вигляд, у частці від повного ходу. Збільште, якщо вигляд зміщується, коли ковпачок у спокої.", + "ui.space_mouse_forget": "Забути калібрування", "ui.space_mouse_hint": "Переміщуйте й обертайте вид разом; в ескізах доступні лише панорамування та масштаб.", "ui.space_mouse_navigate": "Навігація за допомогою SpaceNavigator / SpaceMouse", + "ui.space_mouse_none": "3D-мишу не знайдено", + "ui.space_mouse_not_calibrated": "Не відкалібровано", + "ui.space_mouse_reading": "Показники", + "ui.space_mouse_step_lift": "Підніміть ковпачок угору, утримайте й відпустіть.", + "ui.space_mouse_step_press": "Натисніть ковпачок униз, утримайте й відпустіть.", + "ui.space_mouse_step_pull": "Потягніть ковпачок до себе, утримайте й відпустіть.", + "ui.space_mouse_step_push": "Штовхніть ковпачок від себе, утримайте й відпустіть.", + "ui.space_mouse_step_rest": "Приберіть руку з ковпачка й не торкайтеся його.", + "ui.space_mouse_step_slide_left": "Зсуньте ковпачок ліворуч, утримайте й відпустіть.", + "ui.space_mouse_step_slide_right": "Зсуньте ковпачок праворуч, утримайте й відпустіть.", + "ui.space_mouse_step_tilt_back": "Нахиліть ковпачок назад (передній край угору), утримайте й відпустіть.", + "ui.space_mouse_step_tilt_forward": "Нахиліть ковпачок уперед (передній край униз), утримайте й відпустіть.", + "ui.space_mouse_step_tilt_left": "Нахиліть ковпачок ліворуч (лівий край униз), утримайте й відпустіть.", + "ui.space_mouse_step_tilt_right": "Нахиліть ковпачок праворуч (правий край униз), утримайте й відпустіть.", + "ui.space_mouse_step_twist_clockwise": "Поверніть ковпачок за годинниковою стрілкою, утримайте й відпустіть.", + "ui.space_mouse_step_twist_counterclockwise": "Поверніть ковпачок проти годинникової стрілки, утримайте й відпустіть.", "ui.spacing": "Крок", "ui.spacing_2": "Крок 2", "ui.sphere": "Куля", @@ -1401,6 +1428,7 @@ "ui.split_body": "Розділити тіло", "ui.stand_up_tip": "Після відкриття файлу STEP або IGES з напрямком Z вгору пропонувати поворот на чверть оберту навколо X", "ui.start": "Початок", + "ui.start_over": "Почати спочатку", "ui.start_radius": "Початковий радіус", "ui.supersampling": "Наддискретизація (SSAA)", "ui.supersampling_adaptive": "Лише коли вид нерухомий", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index 7298363f4..f36707f37 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -1074,6 +1074,7 @@ "ui.autosave_every": "自动保存间隔", "ui.axes": "轴", "ui.axis": "轴", + "ui.back": "返回", "ui.base_point": "基点", "ui.blocked": "被遮挡", "ui.bodies": "实体", @@ -1508,8 +1509,34 @@ "ui.smooth_wheel_zoom": "平滑滚轮缩放", "ui.smooth_wheel_zoom_tip": "关闭后每个滚轮事件立即生效,不做平滑延迟", "ui.snap": "捕捉", + "ui.space_mouse_calibrate": "校准…", + "ui.space_mouse_calibrate_tip": "按窗口提示移动摇杆帽,SolidCraft 会记住这个 3D 鼠标每个轴的方向和行程。校准结果按此 3D 鼠标保存。", + "ui.space_mouse_calibrate_title": "校准 3D 鼠标", + "ui.space_mouse_calibrated": "已校准", + "ui.space_mouse_calibration": "3D 鼠标校准", + "ui.space_mouse_calibration_done": "完成。保存后,每次连接此 3D 鼠标都会使用它。", + "ui.space_mouse_calibration_no_response": "有一个轴几乎没有移动,因此无法校准。请重新开始,并且每次把摇杆帽移得更远。", + "ui.space_mouse_dead_zone": "死区", + "ui.space_mouse_dead_zone_tip": "视图开始移动前摇杆帽需要移动的距离,以其全行程的比例表示。如果摇杆帽静止时视图仍在漂移,请调大。", + "ui.space_mouse_forget": "清除校准", "ui.space_mouse_hint": "同时移动和旋转视图;草图中仅支持平移和缩放。", "ui.space_mouse_navigate": "使用 SpaceNavigator / SpaceMouse 导航", + "ui.space_mouse_none": "未找到 3D 鼠标", + "ui.space_mouse_not_calibrated": "未校准", + "ui.space_mouse_reading": "读数", + "ui.space_mouse_step_lift": "向上提起摇杆帽,保持住,然后松开。", + "ui.space_mouse_step_press": "向下按压摇杆帽,保持住,然后松开。", + "ui.space_mouse_step_pull": "把摇杆帽拉向自己,保持住,然后松开。", + "ui.space_mouse_step_push": "把摇杆帽推离自己,保持住,然后松开。", + "ui.space_mouse_step_rest": "请把手从摇杆帽上移开,让它保持静止。", + "ui.space_mouse_step_slide_left": "向左推动摇杆帽,保持住,然后松开。", + "ui.space_mouse_step_slide_right": "向右推动摇杆帽,保持住,然后松开。", + "ui.space_mouse_step_tilt_back": "向后倾斜摇杆帽(前缘向上),保持住,然后松开。", + "ui.space_mouse_step_tilt_forward": "向前倾斜摇杆帽(前缘向下),保持住,然后松开。", + "ui.space_mouse_step_tilt_left": "向左倾斜摇杆帽(左缘向下),保持住,然后松开。", + "ui.space_mouse_step_tilt_right": "向右倾斜摇杆帽(右缘向下),保持住,然后松开。", + "ui.space_mouse_step_twist_clockwise": "顺时针扭转摇杆帽,保持住,然后松开。", + "ui.space_mouse_step_twist_counterclockwise": "逆时针扭转摇杆帽,保持住,然后松开。", "ui.spacing": "间距", "ui.spacing_2": "间距 2", "ui.sphere": "球体", @@ -1517,6 +1544,7 @@ "ui.split_body": "分割实体", "ui.stand_up_tip": "当 Z 朝上的 STEP 或 IGES 文件打开后,提示绕 X 轴旋转四分之一周", "ui.start": "开始", + "ui.start_over": "重新开始", "ui.start_radius": "起始半径", "ui.stretch": "伸展", "ui.supersampling": "超级采样 (SSAA)", diff --git a/crates/space-mouse/Cargo.toml b/crates/space-mouse/Cargo.toml index 7ae84345e..264ba6ab2 100644 --- a/crates/space-mouse/Cargo.toml +++ b/crates/space-mouse/Cargo.toml @@ -7,3 +7,7 @@ license.workspace = true [lints] workspace = true + +[dependencies] +# Saving a calibration with the app's preferences; off by default, so the crate needs nothing. +serde = { workspace = true, optional = true } diff --git a/crates/space-mouse/src/calibration.rs b/crates/space-mouse/src/calibration.rs new file mode 100644 index 000000000..bf8242520 --- /dev/null +++ b/crates/space-mouse/src/calibration.rs @@ -0,0 +1,1357 @@ +//! Calibration: which of a device's raw axes is which, and how far each one goes. The user holds +//! the cap still, then moves it along each axis both ways; [`Recording::solve`] turns what the +//! device sent into a [`Calibration`] that maps any reading onto 3Dconnexion's axes (X right, +//! Y towards the user, Z down, the rotations about them right-handed), ±[`FULL_SCALE`] at full +//! deflection. Everything after that, the driver mapping and the user's per-axis choices, then +//! treats every device the same. + +use crate::FULL_SCALE; + +/// One motion the user is asked for: a canonical axis, one way. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Step { + /// 0..3 = X, Y, Z; 3..6 = rotation about them. + pub axis: usize, + pub positive: bool, +} + +/// The motions, in the order they are asked for. The positive direction of each is what both +/// 3Dconnexion devices we measured report as positive: slide right, pull towards you, press down, +/// tilt back, tilt left, twist clockwise seen from above. +pub const STEPS: [Step; 12] = { + let mut steps = [Step { axis: 0, positive: true }; 12]; + let mut i = 0; + while i < 12 { + steps[i] = Step { axis: i / 2, positive: i % 2 == 0 }; + i += 1; + } + steps +}; + +/// Where one canonical axis comes from, and how to scale it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct AxisCalibration { + /// The raw axis it is read from. + pub source: usize, + /// The raw axis runs the other way. + pub reversed: bool, + /// The raw value with the cap at rest. + pub rest: i16, + /// How far from `rest` the value wanders with nobody touching the cap; readings within it are 0. + pub dead_zone: u16, + /// How far below and above `rest` the value goes at full deflection; each reads as + /// ±[`FULL_SCALE`], so a device that goes further one way than the other still reaches full + /// scale both ways. + pub full: [u16; 2], +} + +#[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct Calibration { + /// The user's dead zone on top of each axis's measured one, as a share of full deflection + /// (up to [`MAX_DEAD_ZONE_SHARE`]): readings within it are 0, and the rest of the travel + /// still reaches full scale. Widening it settles a device that drifts at rest, or whose rest + /// calibrated off. Calibrations saved before it existed read as 0. + #[cfg_attr(feature = "serde", serde(default))] + pub dead_zone_share: f32, + pub axes: [AxisCalibration; 6], +} + +/// The widest dead zone a calibration takes, as a share of full deflection. +pub const MAX_DEAD_ZONE_SHARE: f32 = 0.5; + +impl Calibration { + /// A reading in the device's raw axes, on the canonical ones. Past full deflection the value + /// keeps growing, up to the i16 range; a source the device doesn't have reads 0. + pub fn apply(&self, raw: [i16; 6]) -> [i16; 6] { + let share = if self.dead_zone_share.is_finite() { self.dead_zone_share.clamp(0.0, MAX_DEAD_ZONE_SHARE) } else { 0.0 }; + let shared = (f64::from(share) * f64::from(FULL_SCALE)).round() as i32; + self.axes.map(|axis| { + let Some(&value) = raw.get(axis.source) else { return 0 }; + let offset = i32::from(value) - i32::from(axis.rest); + let dead = i32::from(axis.dead_zone); + let full = axis.full[usize::from(offset > 0)]; + let span = (i32::from(full) - dead).max(1); + let past = offset.abs() - dead; + if past <= 0 { + return 0; + } + // In i64: a short calibrated range and an extreme reading go far past i32 here. + let full_scale = i64::from(FULL_SCALE); + let scaled = i64::from(past) * full_scale / i64::from(span); + // The user's dead zone, in the same units; the travel past it stretches back to full scale. + if scaled <= i64::from(shared) { + return 0; + } + let scaled = ((scaled - i64::from(shared)) * full_scale / (full_scale - i64::from(shared))).min(i64::from(i16::MAX)); + let signed = if (offset < 0) != axis.reversed { -scaled } else { scaled }; + i16::try_from(signed).unwrap_or(0) + }) + } + + /// How far each canonical axis is through its travel before any dead zone: ±1 at full + /// deflection either way, further past it. Where a reading sits on a picture of the axis. + pub fn travel(&self, raw: [i16; 6]) -> [f32; 6] { + self.axes.map(|axis| { + let Some(&value) = raw.get(axis.source) else { return 0.0 }; + let offset = f32::from(value) - f32::from(axis.rest); + let share = offset / f32::from(axis.full[usize::from(offset > 0.0)]).max(1.0); + if axis.reversed { -share } else { share } + }) + } + + /// How much of each canonical axis's travel reads as no motion, `[negative, positive]` as + /// shares of it: the measured dead zone with the user's on top, as [`Calibration::apply`] has it. + pub fn dead_zone_shares(&self) -> [[f32; 2]; 6] { + let user = if self.dead_zone_share.is_finite() { self.dead_zone_share.clamp(0.0, MAX_DEAD_ZONE_SHARE) } else { 0.0 }; + self.axes.map(|axis| { + let [below, above] = axis.full.map(|full| (f32::from(axis.dead_zone) / f32::from(full).max(1.0)).min(1.0)); + let sides = if axis.reversed { [above, below] } else { [below, above] }; + sides.map(|measured| measured + (1.0 - measured) * user) + }) + } + + /// Each raw axis's value at rest, which calibrates to no motion: what an app reads a raw axis + /// as while it has nothing fresh from it. A raw axis no canonical one reads rests at 0. + pub fn raw_rest(&self) -> [i16; 6] { + let mut rest = [0; 6]; + for axis in &self.axes { + if let Some(raw) = rest.get_mut(axis.source) { + *raw = axis.rest; + } + } + rest + } + + /// Whether it can be used as it is: each canonical axis reads its own raw axis, and goes + /// further both ways at full deflection than it wanders at rest. Every calibration + /// [`Recording::solve`] gives is; one from a hand-edited settings file may not be, and could + /// turn any touch of the cap into full speed. Its dead zone has to be a share from 0 to + /// [`MAX_DEAD_ZONE_SHARE`]. + pub fn is_usable(&self) -> bool { + let mut used = [false; 6]; + (0.0..=MAX_DEAD_ZONE_SHARE).contains(&self.dead_zone_share) + && self.axes.iter().all(|axis| { + axis.full.iter().all(|&full| full > axis.dead_zone) && used.get_mut(axis.source).is_some_and(|used| !std::mem::replace(used, true)) + }) + } +} + +/// Why a recording didn't give a calibration. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Problem { + /// Nothing was recorded with the cap at rest. + NoRest, + /// Nothing was recorded for this step. + NotRecorded(Step), + /// Moving the cap along this canonical axis barely moved its raw axis one way: less than twice + /// what it wanders at rest, or less than [`MIN_SHARE`] of how far any axis went. + NoResponse(usize), +} + +#[derive(Clone, Copy, Debug)] +struct Samples { + sum: [f64; 6], + count: u32, + min: [i16; 6], + max: [i16; 6], +} + +impl Default for Samples { + fn default() -> Self { + Self { sum: [0.0; 6], count: 0, min: [i16::MAX; 6], max: [i16::MIN; 6] } + } +} + +impl Samples { + fn add(&mut self, raw: [i16; 6]) { + for (((sum, min), max), value) in self.sum.iter_mut().zip(&mut self.min).zip(&mut self.max).zip(raw) { + *sum += f64::from(value); + *min = (*min).min(value); + *max = (*max).max(value); + } + self.count += 1; + } + + fn mean(&self) -> Option<[f64; 6]> { + (self.count > 0).then(|| self.sum.map(|sum| sum / f64::from(self.count))) + } + + /// Where raw axis `r` rests (its mean, rounded) and how far its readings went from there; + /// `None` without readings. + fn rest_and_wander(&self, r: usize) -> Option<(f64, f64)> { + let rest = self.mean()?.get(r)?.round(); + let (min, max) = (f64::from(*self.min.get(r)?), f64::from(*self.max.get(r)?)); + Some((rest, (max - rest).max(rest - min).max(0.0))) + } + + /// How far apart raw axis `r`'s lowest and highest readings were; 0 without readings. + fn spread(&self, r: usize) -> f64 { + match (self.min.get(r), self.max.get(r)) { + (Some(&min), Some(&max)) => (f64::from(max) - f64::from(min)).max(0.0), + _ => 0.0, + } + } +} + +/// What the device sent during calibration: readings at rest, during each of [`STEPS`], and +/// where the cap came back to after each one. +#[derive(Clone, Debug, Default)] +pub struct Recording { + rest: Samples, + steps: [Samples; 12], + /// The readings the cap settled on after step `n` was let go: all of a steady run. + settled: [Samples; 12], +} + +impl Recording { + /// One reading with nobody touching the cap. + pub fn rest(&mut self, raw: [i16; 6]) { + self.rest.add(raw); + } + + /// One reading during step `index` of [`STEPS`]; any other index is ignored. + pub fn step(&mut self, index: usize, raw: [i16; 6]) { + if let Some(samples) = self.steps.get_mut(index) { + samples.add(raw); + } + } + + /// One reading of where the cap settled after step `index` was let go; any other index is ignored. + pub fn settled(&mut self, index: usize, raw: [i16; 6]) { + if let Some(settled) = self.settled.get_mut(index) { + settled.add(raw); + } + } + + /// Whether step `index` has a reading yet. + pub fn has_step(&self, index: usize) -> bool { + self.steps.get(index).is_some_and(|samples| samples.count > 0) + } + + /// Forgets what was recorded for step `index`. + fn clear_step(&mut self, index: usize) { + if let Some(samples) = self.steps.get_mut(index) { + *samples = Samples::default(); + } + if let Some(settled) = self.settled.get_mut(index) { + *settled = Samples::default(); + } + } + + /// The calibration the recording gives. Hands are never exact: sliding the cap tilts it a + /// little and tilting it slides it, sometimes further than the axis being asked for. So the + /// raw axis for each canonical one isn't the one that moved most in its step. It is the + /// one-to-one assignment that best explains all six axes together, scored by how far each + /// raw axis moved between the step's two directions, as a share of the furthest it moved in + /// any step: an axis with a wider range doesn't win through cross-talk alone. A raw axis that + /// only wandered scores low, since its share is of at least four times its wander at rest. + /// + /// A device that doesn't come back to the same place after each release (a drifting stick, or + /// spacenavd keeping a relative-axis device's last small report, #2778) rests, here, at the + /// middle of everything it read at rest and after each release, and its dead zone covers all of + /// it, so where it stops doesn't creep. + pub fn solve(&self) -> Result { + let rest = self.rest.mean().ok_or(Problem::NoRest)?; + let mut means = [[0.0; 6]; 12]; + for ((mean, samples), step) in means.iter_mut().zip(&self.steps).zip(STEPS) { + *mean = samples.mean().ok_or(Problem::NotRecorded(step))?; + } + // travel[c][r]: how far raw axis r moved from canonical axis c's negative step to its positive one. + let travel: [[f64; 6]; 6] = std::array::from_fn(|c| std::array::from_fn(|r| means[2 * c][r] - means[2 * c + 1][r])); + let widest: [f64; 6] = std::array::from_fn(|r| travel.iter().map(|row| row[r].abs()).fold(4.0 * self.rest.spread(r), f64::max).max(1.0)); + let shares: [[f64; 6]; 6] = std::array::from_fn(|c| std::array::from_fn(|r| travel[c][r].abs() / widest[r])); + let sources = best_assignment(&shares); + let mut axes = [AxisCalibration { source: 0, reversed: false, rest: 0, dead_zone: 0, full: [0; 2] }; 6]; + for (c, (axis, source)) in axes.iter_mut().zip(sources).enumerate() { + let (rest_value, wander) = self.rest.rest_and_wander(source).unwrap_or((rest[source].round(), 0.0)); + let (rest_value, wander) = self.settled_rest(source, rest_value, wander); + let (positive, negative) = (&self.steps[2 * c], &self.steps[2 * c + 1]); + let reversed = travel[c][source] < 0.0; + // The steps that push the raw axis above and below rest, and how far each got. + let (above, below) = if reversed { (negative, positive) } else { (positive, negative) }; + let full = [rest_value - f64::from(below.min[source]), f64::from(above.max[source]) - rest_value]; + if full.iter().any(|&full| full < 2.0 * wander || full < 1.0) { + return Err(Problem::NoResponse(c)); + } + *axis = AxisCalibration { + source, + reversed, + rest: rest_value.clamp(f64::from(i16::MIN), f64::from(i16::MAX)) as i16, + dead_zone: wander.min(f64::from(u16::MAX)) as u16, + full: full.map(|full| full.min(f64::from(u16::MAX)) as u16), + }; + } + let most = axes.iter().flat_map(|axis| axis.full).max().unwrap_or(0); + if let Some(c) = axes.iter().position(|axis| axis.full.iter().any(|&full| f64::from(full) < MIN_SHARE * f64::from(most))) { + return Err(Problem::NoResponse(c)); + } + Ok(Calibration { dead_zone_share: 0.0, axes }) + } +} + +impl Recording { + /// Raw axis `r`'s rest and dead zone, given the rest stage's: unchanged while every reading + /// after a release stayed within the wander; otherwise the middle of everything read at rest + /// and after the releases, with a dead zone reaching every one of those readings. + fn settled_rest(&self, r: usize, rest: f64, wander: f64) -> (f64, f64) { + let (mut low, mut high) = (rest - wander, rest + wander); + for settled in self.settled.iter().filter(|settled| settled.count > 0) { + if let (Some(&min), Some(&max)) = (settled.min.get(r), settled.max.get(r)) { + (low, high) = (low.min(f64::from(min)), high.max(f64::from(max))); + } + } + if low >= rest - wander && high <= rest + wander { + return (rest, wander); + } + let middle = ((low + high) / 2.0).round(); + (middle, (high - middle).max(middle - low)) + } +} + +/// The raw axis for each canonical one, each raw axis used once, with the highest total share. +fn best_assignment(shares: &[[f64; 6]; 6]) -> [usize; 6] { + fn search(shares: &[[f64; 6]; 6], canonical: usize, used: [bool; 6], current: &mut [usize; 6], total: f64, best: &mut ([usize; 6], f64)) { + if canonical == 6 { + if total > best.1 { + *best = (*current, total); + } + return; + } + for raw in 0..6 { + if !used[raw] { + let mut now_used = used; + now_used[raw] = true; + current[canonical] = raw; + search(shares, canonical + 1, now_used, current, total + shares[canonical][raw], best); + } + } + } + let mut best = ([0, 1, 2, 3, 4, 5], f64::NEG_INFINITY); + search(shares, 0, [false; 6], &mut [0; 6], 0.0, &mut best); + best.0 +} + +/// The least a direction may go, as a share of how far the furthest axis went, before it counts +/// as not having responded. It turns away a step that recorded a resting hand rather than a push, +/// which would otherwise scale a few units of noise up to full speed, and still lets a homemade +/// device go ten times further one way than the other. +pub const MIN_SHARE: f64 = 1.0 / 12.0; + +/// Seconds of readings with the cap at rest before the first step. +pub const REST_SECONDS: f64 = 1.5; +/// Seconds the cap has to be held out in a step's direction before letting go finishes it. +pub const HOLD_SECONDS: f64 = 0.4; +/// Seconds the reading has to stay steady, back close to rest, to count as let go even outside the +/// rest wander: the cap stopped short of rest, as a drifting stick does, or spacenavd with a +/// relative-axis device (#2778). Back close to rest means the axis that went furthest this step is +/// at least [`RETURNED_SHARE`] of the way back, and some axis that moved about as far (at least +/// half as far) is within [`SETTLED_SHARE`] of its own peak: cross-talk can move another raw axis +/// further than the one being asked for, and which raw axis that is isn't known yet. Steady means +/// each raw axis's readings span no more than twice its rest wander, at least 4 units (±2) and +/// [`STEADY_SHARE`] of the furthest that axis has gone in any step: an axis that read flat at rest +/// may still dither once it's off-centre. +pub const SETTLE_SECONDS: f64 = 0.5; +/// How far from rest, as a share of its peak this step, an axis that moved has to be to count as let go. +pub const SETTLED_SHARE: f64 = 0.25; +/// How far from rest, as a share of its peak, the axis that went furthest may still be when the +/// step counts as let go. A hand still holding the push keeps it out. +pub const RETURNED_SHARE: f64 = 0.5; +/// The least spread steady readings may have, as a share of the furthest the axis has gone. +pub const STEADY_SHARE: f64 = 1.0 / 50.0; + +/// Where the guided calibration is. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Stage { + /// Hands off the cap. + Rest, + /// Step `n` of [`STEPS`]. + Step(usize), + /// Every step is recorded. + Done, +} + +/// The guided calibration: it records the cap at rest, then each of [`STEPS`] in turn, and moves +/// on by itself, so the user's hand stays on the cap. A step is done once the cap has been held +/// out for [`HOLD_SECONDS`] in one go and let go. Before calibration nothing says how far a raw +/// axis goes, so "held out" only means some raw axis is at least twice as far from rest as it +/// wandered at rest, each axis measured against its own wander: the least [`Recording::solve`] +/// accepts. So whatever the solver would accept can be recorded, a noisy axis doesn't hold up a +/// quiet one, and the solver judges whether each direction went far enough. "Let go" means every +/// raw axis is back within its rest wander, or the reading has gone steady close to rest +/// ([`SETTLE_SECONDS`], [`SETTLED_SHARE`]). +#[derive(Clone, Debug)] +pub struct Wizard { + stage: Stage, + recording: Recording, + /// Seconds spent in the current stage: at rest, or held out. + seconds: f64, + /// The dead zone the user set while calibrating, which the result carries. + dead_zone_share: f32, + /// The readings since the reading went steady, and for how long. + run: Samples, + steady: f64, + /// How far each raw axis went from rest in this step, in raw units. + peaks: [f64; 6], + /// The furthest each raw axis went from rest in any step so far. + reach: [f64; 6], + /// The readings the previous step settled on: while a reading stays within their spread, nobody has touched the cap. + settled: Option, +} + +impl Default for Wizard { + fn default() -> Self { + Self { + stage: Stage::Rest, + recording: Recording::default(), + seconds: 0.0, + dead_zone_share: 0.0, + run: Samples::default(), + steady: 0.0, + peaks: [0.0; 6], + reach: [0.0; 6], + settled: None, + } + } +} + +impl Wizard { + pub fn stage(&self) -> Stage { + self.stage + } + + /// How far through the current stage, 0..=1: the time at rest, or held out. + pub fn progress(&self) -> f64 { + match self.stage { + Stage::Rest => (self.seconds / REST_SECONDS).min(1.0), + Stage::Step(_) => (self.seconds / HOLD_SECONDS).min(1.0), + Stage::Done => 1.0, + } + } + + /// One reading, `seconds` after the previous one. + pub fn feed(&mut self, raw: [i16; 6], seconds: f64) { + // A stalled frame shouldn't finish a stage on its own. + let seconds = if seconds.is_finite() { seconds.clamp(0.0, 0.1) } else { 0.0 }; + // Steady while every axis's readings since the run began stay within its noise. + let mut run = self.run; + run.add(raw); + if (0..6).all(|r| run.spread(r) <= self.tolerance(r)) { + self.steady += seconds; + } else { + (run, self.steady) = (Samples::default(), 0.0); + run.add(raw); + } + self.run = run; + match self.stage { + Stage::Rest => { + self.recording.rest(raw); + self.seconds += seconds; + if self.seconds >= REST_SECONDS { + self.enter(Stage::Step(0)); + } + } + Stage::Step(index) => { + // Still where the last step settled: the cap hasn't been touched yet. Deliberately + // skips the peak and hold bookkeeping; a device that rests exactly there reads as + // untouched until it moves, which is what it is. + if self.settled.is_some_and(|settled| self.near(settled, raw)) { + return; + } + self.settled = None; + let away = self.away(raw); + let offsets = self.offsets(raw); + for ((peak, reach), offset) in self.peaks.iter_mut().zip(&mut self.reach).zip(offsets) { + *peak = peak.max(offset); + *reach = reach.max(offset); + } + let furthest = self.peaks.iter().copied().fold(0.0, f64::max); + let peaks = self.peaks; + // Close to rest is the cap settling, never held; it has let go once it's steady there. + // Every axis that moved about as far as the furthest has to be back by + // `RETURNED_SHARE` of its own peak too, or a lesser axis still held out would be + // missed while a larger cross-talk axis relaxes. + let settling = (0..6).any(|r| peaks[r] == furthest && offsets[r] <= RETURNED_SHARE * furthest) + && (0..6).any(|r| peaks[r] >= 0.5 * furthest && offsets[r] <= SETTLED_SHARE * peaks[r]) + && (0..6).all(|r| peaks[r] < 0.5 * furthest || offsets[r] <= RETURNED_SHARE * peaks[r]); + let stopped = settling && (self.steady >= SETTLE_SECONDS); + if away <= 0.5 || stopped { + // Where it settled: every reading of the steady run, or just this one. + let mut settled = Samples::default(); + settled.add(raw); + if stopped { + settled = self.run; + } + if self.seconds >= HOLD_SECONDS { + // Every reading of the steady run, so the dead zone covers all of them. + if stopped { + self.recording.settled[index] = self.run; + } else { + self.recording.settled(index, raw); + } + self.enter(if index + 1 < STEPS.len() { Stage::Step(index + 1) } else { Stage::Done }); + self.settled = Some(settled); + } else if self.seconds > 0.0 { + // Let go too soon: the hold starts over, and only a whole one is kept. + self.recording.clear_step(index); + self.enter(Stage::Step(index)); + self.settled = Some(settled); + } + } else if away >= 1.0 && !settling { + self.recording.step(index, raw); + self.seconds += seconds; + } + } + Stage::Done => {} + } + } + + /// Goes back one step and records it again; from the first step, back to rest. + pub fn back(&mut self) { + match self.stage { + Stage::Rest => {} + Stage::Step(0) => *self = Self::default(), + Stage::Step(index) => { + self.recording.clear_step(index); + self.recording.clear_step(index - 1); + self.enter(Stage::Step(index - 1)); + } + Stage::Done => { + self.recording.clear_step(STEPS.len() - 1); + self.enter(Stage::Step(STEPS.len() - 1)); + } + } + } + + /// Once every step is recorded, the calibration they give, with the dead zone set here. + pub fn result(&self) -> Option> { + (self.stage == Stage::Done) + .then(|| self.recording.solve().map(|calibration| Calibration { dead_zone_share: self.dead_zone_share, ..calibration })) + } + + pub fn dead_zone_share(&self) -> f32 { + self.dead_zone_share + } + + /// Sets the dead zone the result carries, a share from 0 to [`MAX_DEAD_ZONE_SHARE`]; anything + /// else is held to that range, and a value that isn't a number reads as 0. + pub fn set_dead_zone_share(&mut self, share: f32) { + self.dead_zone_share = if share.is_finite() { share.clamp(0.0, MAX_DEAD_ZONE_SHARE) } else { 0.0 }; + } + + fn enter(&mut self, stage: Stage) { + self.stage = stage; + self.seconds = 0.0; + self.peaks = [0.0; 6]; + // A new stage's steadiness starts with its own readings. + (self.run, self.steady) = (Samples::default(), 0.0); + } + + /// How far each raw axis is from rest, in raw units. + fn offsets(&self, raw: [i16; 6]) -> [f64; 6] { + std::array::from_fn(|r| (f64::from(raw[r]) - self.recording.rest.rest_and_wander(r).map_or(0.0, |(rest, _)| rest)).abs()) + } + + /// How far apart raw axis `r`'s readings may be and still be one position: its noise's whole + /// spread (twice its rest wander), at least 4 units (±2) and [`STEADY_SHARE`] of the furthest it + /// has gone in any step. + fn tolerance(&self, r: usize) -> f64 { + let wander = self.recording.rest.rest_and_wander(r).map_or(0.0, |(_, wander)| wander); + (2.0 * wander).max(4.0).max(STEADY_SHARE * self.reach.get(r).copied().unwrap_or(0.0)) + } + + /// Whether `raw` is still where `settled` was: adding it keeps every axis within [`Self::tolerance`], + /// the same band the steadiness check accepts. + fn near(&self, mut settled: Samples, raw: [i16; 6]) -> bool { + settled.add(raw); + (0..6).all(|r| settled.spread(r) <= self.tolerance(r)) + } + + /// How far the reading is from rest, on the raw axis furthest out, as a share of what counts as + /// held out for that axis (twice its rest wander, at least one unit): 1 or more is held out, + /// half or less is back within its wander. + fn away(&self, raw: [i16; 6]) -> f64 { + raw.iter() + .enumerate() + .map(|(r, &value)| { + let (rest, wander) = self.recording.rest.rest_and_wander(r).unwrap_or((0.0, 0.0)); + (f64::from(value) - rest).abs() / (2.0 * wander).max(1.0) + }) + .fold(0.0, f64::max) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The mean of each axis (X Y Z Rx Ry Rz) during each step, in `STEPS` order, as measured + /// with our own SpaceMouse Pro (046d:c62b) following capture prompts. Note the slide right + /// row: Ry moved further than X. + const PRO: [[i16; 6]; 12] = [ + [250, -10, 0, 0, -336, 0], // slide right + [-277, 55, 86, -36, -196, 0], // slide left + [0, 324, 82, -26, -3, -28], // pull towards you + [-2, -340, 219, -26, -20, 0], // push away + [-1, -3, 344, 0, -37, 0], // press down + [41, -24, -341, -11, -10, 32], // lift up + [0, 193, 0, 333, -26, 0], // tilt back + [0, -339, 163, -183, 0, 0], // tilt forward + [61, 0, 1, -12, 328, 0], // tilt left + [9, 80, 1, 0, -330, -6], // tilt right + [0, -1, 78, 0, 0, 341], // twist clockwise + [0, -6, 0, 0, -4, -337], // twist counterclockwise + ]; + + /// The same with our own SpaceMouse Wireless (256f:c63a), all six axes in one report. + const WIRELESS: [[i16; 6]; 12] = [ + [325, 92, 72, 0, 44, -6], + [-336, 38, 104, 19, -66, 5], + [-5, 339, 73, -71, 0, 0], + [-18, -323, 144, -2, 1, 0], + [0, 1, 341, -2, 2, 0], + [0, 1, -320, 1, -43, 0], + [0, -12, 3, 330, 4, -24], + [0, 51, 17, -319, -20, 0], + [-23, 0, 0, -1, 333, 0], + [7, 41, 23, 15, -163, -13], + [-13, 4, 44, -12, -12, 326], + [0, -1, -1, 1, -9, -313], + ]; + + fn record(steps: [[i16; 6]; 12], rest: [[i16; 6]; 2]) -> Recording { + let mut recording = Recording::default(); + for reading in rest { + recording.rest(reading); + } + for (index, reading) in steps.into_iter().enumerate() { + recording.step(index, reading); + } + recording + } + + const STILL: [[i16; 6]; 2] = [[-3, 2, 0, 1, -2, 0], [3, -2, 0, -1, 2, 0]]; + + #[test] + fn both_3dconnexion_devices_calibrate_to_their_own_axes() { + for steps in [PRO, WIRELESS] { + let calibration = record(steps, STILL).solve().unwrap(); + for (c, axis) in calibration.axes.iter().enumerate() { + assert_eq!((axis.source, axis.reversed), (c, false), "axis {c}"); + assert!(axis.full.iter().all(|full| (150..=350).contains(full)), "axis {c}: {axis:?}"); + } + } + } + + #[test] + fn a_homemade_device_with_shuffled_reversed_wider_axes_is_found() { + // A device reporting ±32767, its axes in another order (raw r carries canonical + // ORDER[r]), the odd ones running the other way, at rest around 100. + const ORDER: [usize; 6] = [4, 0, 5, 2, 1, 3]; + let wire = |canonical: [i16; 6]| -> [i16; 6] { + std::array::from_fn(|r| { + let v = i32::from(canonical[ORDER[r]]) * 32767 / 350; + i16::try_from(if r % 2 == 1 { -v } else { v } + 100).unwrap() + }) + }; + let calibration = record(PRO.map(wire), STILL.map(wire)).solve().unwrap(); + for (c, axis) in calibration.axes.iter().enumerate() { + let r = ORDER.iter().position(|&o| o == c).unwrap(); + assert_eq!((axis.source, axis.reversed), (r, r % 2 == 1), "axis {c}"); + assert_eq!(axis.rest, 100); + } + // Each step now reads on its own axis, the right way, at full scale: each direction is + // scaled on its own, so the Pro's shorter tilt forward gets there too. + for (step, reading) in STEPS.iter().zip(PRO.map(wire)) { + let value = calibration.apply(reading)[step.axis]; + assert_eq!(value, if step.positive { FULL_SCALE } else { -FULL_SCALE }, "{step:?}"); + } + } + + #[test] + fn readings_within_the_rest_wander_are_zero_and_full_deflection_is_full_scale() { + let axis = AxisCalibration { source: 1, reversed: true, rest: 10, dead_zone: 5, full: [105; 2] }; + let calibration = Calibration { dead_zone_share: 0.0, axes: [axis; 6] }; + assert_eq!(calibration.apply([0, 14, 0, 0, 0, 0]), [0; 6]); + assert_eq!(calibration.apply([0, 115, 0, 0, 0, 0]), [-FULL_SCALE; 6]); + assert_eq!(calibration.apply([0, -95, 0, 0, 0, 0]), [FULL_SCALE; 6]); + // Past full deflection the value keeps going, up to the i16 range. + assert_eq!(calibration.apply([0, i16::MIN, 0, 0, 0, 0]), [i16::MAX; 6]); + } + + #[test] + fn a_device_that_goes_further_one_way_reaches_full_scale_both_ways() { + let axis = AxisCalibration { source: 0, reversed: false, rest: 0, dead_zone: 0, full: [200, 500] }; + let calibration = Calibration { dead_zone_share: 0.0, axes: [axis; 6] }; + assert_eq!(calibration.apply([500, 0, 0, 0, 0, 0]), [FULL_SCALE; 6]); + assert_eq!(calibration.apply([-200, 0, 0, 0, 0, 0]), [-FULL_SCALE; 6]); + assert_eq!(calibration.apply([-100, 0, 0, 0, 0, 0]), [-FULL_SCALE / 2; 6]); + } + + #[test] + fn the_users_dead_zone_comes_off_the_bottom_and_full_deflection_stays_full_scale() { + let axis = AxisCalibration { source: 0, reversed: false, rest: 0, dead_zone: 0, full: [350; 2] }; + let calibration = Calibration { dead_zone_share: 0.2, axes: [axis; 6] }; + assert_eq!(calibration.apply([70, 0, 0, 0, 0, 0])[0], 0, "a fifth of the travel is inside it"); + assert_eq!(calibration.apply([210, 0, 0, 0, 0, 0])[0], 175, "60% of the travel is halfway past it"); + assert_eq!(calibration.apply([-350, 0, 0, 0, 0, 0])[0], -FULL_SCALE); + // Out of range or not a number: held to the range, or none. + assert_eq!(Calibration { dead_zone_share: 9.0, ..calibration }.apply([170, 0, 0, 0, 0, 0])[0], 0); + assert_eq!(Calibration { dead_zone_share: f32::NAN, ..calibration }.apply([70, 0, 0, 0, 0, 0])[0], 70); + let solved = record(PRO, STILL).solve().unwrap(); + assert!(Calibration { dead_zone_share: 0.5, ..solved }.is_usable()); + assert!(!Calibration { dead_zone_share: 0.6, ..solved }.is_usable()); + assert!(!Calibration { dead_zone_share: f32::NAN, ..solved }.is_usable()); + assert!(!Calibration { dead_zone_share: -0.1, ..solved }.is_usable()); + } + + #[test] + fn extreme_readings_on_a_short_range_saturate_with_the_right_sign() { + // Six distinct sources, each with a range of one unit: any real reading is far past it. + let axes: [AxisCalibration; 6] = std::array::from_fn(|c| AxisCalibration { + source: (c + 2) % 6, + reversed: c % 2 == 1, + rest: if c < 3 { 0 } else { i16::MIN }, + dead_zone: 0, + full: [1, 1], + }); + for dead_zone_share in [0.0, MAX_DEAD_ZONE_SHARE] { + let calibration = Calibration { dead_zone_share, axes }; + assert!(calibration.is_usable()); + let read = |raw: [i16; 6]| calibration.apply(raw); + for (raw, sign) in [(i16::MAX, 1), (i16::MIN, -1)] { + let out = read([raw; 6]); + for (c, axis) in calibration.axes.iter().enumerate() { + let offset = i32::from(raw) - i32::from(axis.rest); + let expected = if offset == 0 { + 0 + } else { + let positive = (offset > 0) != axis.reversed; + if positive { i16::MAX } else { -i16::MAX } + }; + assert_eq!(out[c], expected, "share {dead_zone_share}, raw {raw} (sign {sign}), axis {c}: {axis:?}"); + } + } + } + } + + #[test] + fn the_dead_zone_set_while_calibrating_goes_with_the_result() { + let mut wizard = Wizard::default(); + wizard.set_dead_zone_share(0.15); + rest_then(&mut wizard); + for reading in PRO { + hold(&mut wizard, reading, 0.5); + hold(&mut wizard, STILL[0], 0.1); + } + assert_eq!(wizard.result().unwrap().unwrap().dead_zone_share, 0.15); + wizard.set_dead_zone_share(f32::NAN); + assert_eq!(wizard.dead_zone_share(), 0.0); + wizard.set_dead_zone_share(2.0); + assert_eq!(wizard.dead_zone_share(), MAX_DEAD_ZONE_SHARE); + } + + #[test] + fn a_device_at_its_raw_rest_reads_no_motion() { + let axis = |source, rest| AxisCalibration { source, reversed: source % 2 == 1, rest, dead_zone: 0, full: [350; 2] }; + let calibration = + Calibration { dead_zone_share: 0.0, axes: [axis(3, 100), axis(0, -40), axis(1, 7), axis(2, 0), axis(5, 1000), axis(4, -1)] }; + assert_eq!(calibration.raw_rest(), [-40, 7, 0, 100, -1, 1000]); + assert_eq!(calibration.apply(calibration.raw_rest()), [0; 6]); + } + + #[test] + fn a_source_the_device_doesnt_have_reads_zero() { + let axis = AxisCalibration { source: 9, reversed: false, rest: 0, dead_zone: 0, full: [350; 2] }; + assert_eq!(Calibration { dead_zone_share: 0.0, axes: [axis; 6] }.apply([350; 6]), [0; 6]); + } + + #[test] + fn a_missing_step_or_rest_is_named() { + let mut recording = record(PRO, STILL); + recording.steps[7] = Samples::default(); + assert_eq!(recording.solve(), Err(Problem::NotRecorded(STEPS[7]))); + assert!(!recording.has_step(7) && recording.has_step(6)); + assert_eq!(Recording::default().solve(), Err(Problem::NoRest)); + } + + #[test] + fn an_axis_that_barely_moves_is_named() { + let mut steps = PRO; + // Twisting did nothing beyond what the cap wanders at rest. + steps[10] = [0, 0, 0, 0, 0, 20]; + steps[11] = [0, 0, 0, 0, 0, -20]; + assert_eq!(record(steps, STILL).solve(), Err(Problem::NoResponse(5))); + } + + /// Feeds `reading` for `seconds`, a frame every 20 ms. + fn hold(wizard: &mut Wizard, reading: [i16; 6], seconds: f64) { + for _ in 0..(seconds / 0.02).round() as usize { + wizard.feed(reading, 0.02); + } + } + + fn rest_then(wizard: &mut Wizard) { + for _ in 0..40 { + hold(wizard, STILL[0], 0.02); + hold(wizard, STILL[1], 0.02); + } + } + + #[test] + fn the_wizard_moves_on_by_itself_and_ends_with_the_calibration() { + let mut wizard = Wizard::default(); + rest_then(&mut wizard); + for (index, reading) in PRO.into_iter().enumerate() { + assert_eq!(wizard.stage(), Stage::Step(index)); + hold(&mut wizard, reading, 0.5); + assert_eq!(wizard.progress(), 1.0); + hold(&mut wizard, STILL[0], 0.1); + } + assert_eq!(wizard.stage(), Stage::Done); + let calibration = wizard.result().unwrap().unwrap(); + assert!(calibration.axes.iter().enumerate().all(|(c, axis)| axis.source == c && !axis.reversed)); + } + + #[test] + fn a_quick_twitch_or_a_hold_without_letting_go_doesnt_finish_a_step() { + let mut wizard = Wizard::default(); + rest_then(&mut wizard); + hold(&mut wizard, PRO[0], 0.2); + hold(&mut wizard, STILL[0], 0.1); + assert_eq!(wizard.stage(), Stage::Step(0)); + hold(&mut wizard, PRO[0], 2.0); + assert_eq!(wizard.stage(), Stage::Step(0)); + // A stalled frame counts as a short one. + let mut stalled = Wizard::default(); + rest_then(&mut stalled); + stalled.feed(PRO[0], 5.0); + assert!(stalled.progress() < 1.0); + } + + #[test] + fn back_records_the_previous_step_again() { + let mut wizard = Wizard::default(); + rest_then(&mut wizard); + for reading in &PRO[..2] { + hold(&mut wizard, *reading, 0.5); + hold(&mut wizard, STILL[0], 0.1); + } + assert_eq!(wizard.stage(), Stage::Step(2)); + wizard.back(); + assert_eq!(wizard.stage(), Stage::Step(1)); + assert!(wizard.recording.has_step(0) && !wizard.recording.has_step(1)); + wizard.back(); + wizard.back(); + assert_eq!(wizard.stage(), Stage::Rest); + assert!(wizard.result().is_none()); + } + + #[test] + fn a_device_whose_rotations_go_a_fifth_as_far_as_its_slides_finishes_and_calibrates() { + let weak = |reading: [i16; 6]| -> [i16; 6] { std::array::from_fn(|r| if r < 3 { reading[r] } else { reading[r] / 5 }) }; + let mut wizard = Wizard::default(); + rest_then(&mut wizard); + for (index, reading) in PRO.map(weak).into_iter().enumerate() { + assert_eq!(wizard.stage(), Stage::Step(index)); + hold(&mut wizard, reading, 0.5); + hold(&mut wizard, STILL[0], 0.1); + } + let calibration = wizard.result().unwrap().unwrap(); + assert!(calibration.axes.iter().enumerate().all(|(c, axis)| axis.source == c && !axis.reversed), "{calibration:?}"); + } + + #[test] + fn two_short_nudges_dont_add_up_to_a_hold() { + let mut wizard = Wizard::default(); + rest_then(&mut wizard); + for _ in 0..2 { + hold(&mut wizard, PRO[0], 0.24); + hold(&mut wizard, STILL[0], 0.1); + } + assert_eq!(wizard.stage(), Stage::Step(0)); + assert_eq!(wizard.progress(), 0.0); + assert!(!wizard.recording.has_step(0)); + } + + #[test] + fn a_device_that_goes_ten_times_further_one_way_finishes_and_calibrates() { + // Slide right goes to +500, slide left only to -50; the other axes as the Pro. + let mut steps = PRO; + steps[0][0] = 500; + steps[1][0] = -50; + let mut wizard = Wizard::default(); + rest_then(&mut wizard); + for (index, reading) in steps.into_iter().enumerate() { + assert_eq!(wizard.stage(), Stage::Step(index)); + hold(&mut wizard, reading, 0.5); + hold(&mut wizard, STILL[0], 0.1); + } + let calibration = wizard.result().unwrap().unwrap(); + assert_eq!((calibration.axes[0].source, calibration.axes[0].full), (0, [50, 500])); + assert_eq!(calibration.apply([-50, 0, 0, 0, 0, 0])[0], -FULL_SCALE); + } + + /// Runs the whole wizard: `rest` alternating for the rest stage, then each step held and let + /// go back to `rest[0]`. + fn walk(rest: [[i16; 6]; 2], steps: [[i16; 6]; 12]) -> Wizard { + let mut wizard = Wizard::default(); + for _ in 0..40 { + hold(&mut wizard, rest[0], 0.02); + hold(&mut wizard, rest[1], 0.02); + } + for (index, reading) in steps.into_iter().enumerate() { + assert_eq!(wizard.stage(), Stage::Step(index), "{rest:?}"); + hold(&mut wizard, reading, 0.5); + hold(&mut wizard, rest[0], 0.1); + } + wizard + } + + /// Where a relative-axis device read through spacenavd stops after each release: its last + /// small report, never zero (#2778). Ours, in the range that issue measured. + const STUCK: [[i16; 6]; 13] = [ + [11, -34, -40, -5, -5, 15], + [0, 0, -60, 0, 0, 0], + [-8, 21, 13, 4, -9, -3], + [25, -6, 0, -12, 7, 2], + [-30, 12, 9, 0, 18, -7], + [4, 38, -15, 6, -2, 0], + [0, -17, 33, -20, 1, 9], + [9, 3, -4, 28, -11, 0], + [-2, -9, 6, -3, 24, -12], + [14, 0, -11, 7, -30, 5], + [-6, 10, 2, 0, 3, 31], + [3, -4, 0, 2, -6, -27], + [0, 0, 0, 0, 0, 0], + ]; + + #[test] + fn a_device_that_stops_short_of_rest_after_each_release_finishes_and_doesnt_creep() { + // Nothing arrives at rest, so the reading stays exactly where the last report left it: + // first wherever the cap was last let go, then after each step a different place. + let mut wizard = Wizard::default(); + hold(&mut wizard, STUCK[0], REST_SECONDS + 0.1); + for (index, reading) in PRO.into_iter().enumerate() { + assert_eq!(wizard.stage(), Stage::Step(index)); + // While the cap hasn't been touched, the last step's stuck reading isn't a hold. + hold(&mut wizard, STUCK[index], 1.0); + assert_eq!((wizard.stage(), wizard.progress()), (Stage::Step(index), 0.0)); + hold(&mut wizard, reading, 0.5); + hold(&mut wizard, STUCK[index + 1], SETTLE_SECONDS + 0.1); + } + assert_eq!(wizard.stage(), Stage::Done); + let calibration = wizard.result().unwrap().unwrap(); + assert!(calibration.axes.iter().enumerate().all(|(c, axis)| axis.source == c && !axis.reversed), "{calibration:?}"); + for stuck in STUCK { + assert_eq!(calibration.apply(stuck), [0; 6], "{stuck:?} {calibration:?}"); + } + // The cap still reaches full speed, and a push past the stuck range still moves. + assert!(calibration.apply(PRO[0])[0] >= FULL_SCALE - 1, "{calibration:?}"); + assert!(calibration.apply([120, 0, 0, 0, 0, 0])[0] > 0); + } + + #[test] + fn a_steady_hold_that_repeats_one_reading_is_still_a_hold() { + // spacenavd sends only on change, so a cap held still at full deflection repeats one + // reading for far longer than SETTLE_SECONDS; it is held, not let go. + let mut wizard = Wizard::default(); + hold(&mut wizard, STUCK[0], REST_SECONDS + 0.1); + hold(&mut wizard, PRO[0], 1.0); + assert_eq!((wizard.stage(), wizard.progress()), (Stage::Step(0), 1.0)); + hold(&mut wizard, STUCK[1], SETTLE_SECONDS + 0.1); + assert_eq!(wizard.stage(), Stage::Step(1)); + } + + /// `reading` and `reading + jitter` in turn, for `seconds`, a frame every 20 ms. + fn jitter(wizard: &mut Wizard, reading: [i16; 6], jitter: [i16; 6], seconds: f64) { + let shaken: [i16; 6] = std::array::from_fn(|r| reading[r] + jitter[r]); + for frame in 0..(seconds / 0.02).round() as usize { + wizard.feed(if frame % 2 == 0 { reading } else { shaken }, 0.02); + } + } + + #[test] + fn a_drifting_device_that_settles_off_centre_after_each_release_finishes_and_doesnt_creep() { + // It keeps reporting, noisily, but after each release settles somewhere off its rest: + // a worn stick, not only spacenavd. The noise stays within its rest wander (`STILL`). + const NOISE: [i16; 6] = [3, -2, 0, 1, 2, 0]; + let mut wizard = Wizard::default(); + rest_then(&mut wizard); + for (index, reading) in PRO.into_iter().enumerate() { + assert_eq!(wizard.stage(), Stage::Step(index)); + if index > 0 { + // Sitting where the last step settled isn't a hold. + jitter(&mut wizard, STUCK[index], NOISE, 1.0); + assert_eq!((wizard.stage(), wizard.progress()), (Stage::Step(index), 0.0)); + } + hold(&mut wizard, reading, 0.5); + jitter(&mut wizard, STUCK[index + 1], NOISE, SETTLE_SECONDS + 0.1); + } + assert_eq!(wizard.stage(), Stage::Done); + let calibration = wizard.result().unwrap().unwrap(); + assert!(calibration.axes.iter().enumerate().all(|(c, axis)| axis.source == c && !axis.reversed), "{calibration:?}"); + for stuck in &STUCK[1..] { + let shaken: [i16; 6] = std::array::from_fn(|r| stuck[r] + NOISE[r]); + assert_eq!((calibration.apply(*stuck), calibration.apply(shaken)), ([0; 6], [0; 6]), "{stuck:?} {calibration:?}"); + } + assert!(calibration.apply(PRO[0])[0] >= FULL_SCALE - 1, "{calibration:?}"); + } + + #[test] + fn both_ends_of_an_odd_width_settled_run_are_untouched_and_one_unit_beyond_is_movement() { + // Silent at rest (no wander) and a 250 push on X: tolerance is max(4, 250 / 50) = 5, odd. + // The release dithers over 10..15, as wide as that, so its middle rounds to 13 and 10 is + // 3 from it, more than half of 5. + let wizard = || { + let mut wizard = Wizard::default(); + hold(&mut wizard, [0; 6], REST_SECONDS + 0.1); + hold(&mut wizard, [250, 0, 0, 0, 0, 0], 0.5); + cycle(&mut wizard, &[[10, 0, 0, 0, 0, 0], [15, 0, 0, 0, 0, 0]], SETTLE_SECONDS + 0.1); + assert_eq!(wizard.stage(), Stage::Step(1)); + wizard + }; + for (x, touched) in [(10, false), (15, false), (9, true), (16, true)] { + let mut wizard = wizard(); + assert_eq!(wizard.tolerance(0), 5.0); + wizard.feed([x, 0, 0, 0, 0, 0], 0.02); + assert_eq!(wizard.progress() > 0.0, touched, "{x}"); + } + } + + #[test] + fn a_reading_still_moving_close_to_rest_doesnt_end_a_step() { + // Past the peak and close to rest, but moving more than the noise: still on the way back. + let mut wizard = Wizard::default(); + rest_then(&mut wizard); + hold(&mut wizard, PRO[0], 0.5); + jitter(&mut wizard, PRO[0].map(|value| value / 5), [20, 0, 0, 0, 0, 0], 1.0); + assert_eq!(wizard.stage(), Stage::Step(0)); + } + + /// `readings` in turn, from the first, for `seconds`, a frame every 20 ms. + fn cycle(wizard: &mut Wizard, readings: &[[i16; 6]], seconds: f64) { + for frame in 0..(seconds / 0.02).round() as usize { + wizard.feed(readings[frame % readings.len()], 0.02); + } + } + + #[test] + fn an_axis_flat_at_rest_that_dithers_once_off_centre_still_settles() { + // Silent at rest, so no wander was measured, but ±2 around where each release stops. + let mut wizard = Wizard::default(); + hold(&mut wizard, [0; 6], REST_SECONDS + 0.1); + let dither = |at: [i16; 6]| [at.map(|value| value - 2), at, at.map(|value| value + 2)]; + for (index, reading) in PRO.into_iter().enumerate() { + assert_eq!(wizard.stage(), Stage::Step(index)); + if index > 0 { + // Dithering where the last step settled doesn't fill this one. + cycle(&mut wizard, &dither(STUCK[index]), 1.0); + assert_eq!((wizard.stage(), wizard.progress()), (Stage::Step(index), 0.0)); + } + hold(&mut wizard, reading, 0.5); + cycle(&mut wizard, &dither(STUCK[index + 1]), SETTLE_SECONDS + 0.1); + } + assert_eq!(wizard.stage(), Stage::Done); + let calibration = wizard.result().unwrap().unwrap(); + for at in &STUCK[1..] { + for still in dither(*at) { + assert_eq!(calibration.apply(still), [0; 6], "{still:?} {calibration:?}"); + } + } + } + + #[test] + fn noise_that_starts_at_one_edge_of_its_spread_is_steady_and_settles_at_its_middle() { + // X wanders -3..+3 at rest; after the release it cycles -3, 0, +3 around +40. + let mut wizard = Wizard::default(); + rest_then(&mut wizard); + hold(&mut wizard, PRO[0], 0.5); + cycle(&mut wizard, &[[37, 0, 0, 0, 0, 0], [40, 0, 0, 0, 0, 0], [43, 0, 0, 0, 0, 0]], SETTLE_SECONDS + 0.1); + assert_eq!(wizard.stage(), Stage::Step(1)); + assert_eq!(wizard.recording.settled[0].mean().map(|mean| mean[0].round()), Some(40.0)); + } + + #[test] + fn the_four_unit_floor_alone_lets_a_two_unit_dither_settle_on_a_short_range() { + // Flat at rest, and the biggest push only reaches 100, so the reach share is 2 and only + // the floor (4, i.e. ±2) lets this ±2 dither count as steady. + let mut wizard = Wizard::default(); + hold(&mut wizard, [0; 6], REST_SECONDS + 0.1); + hold(&mut wizard, [100, 0, 0, 0, 0, 0], 0.5); + cycle(&mut wizard, &[[8, 0, 0, 0, 0, 0], [10, 0, 0, 0, 0, 0], [12, 0, 0, 0, 0, 0]], SETTLE_SECONDS + 0.1); + assert_eq!(wizard.stage(), Stage::Step(1)); + } + + #[test] + fn dither_the_steadiness_check_rejects_isnt_skipped_as_untouched_either() { + // Step 0 settles on a ±2 dither around 10. Sitting there is untouched; ±3 around it is wider + // than the steadiness check calls one position, so it is movement and starts a hold. + let mut wizard = Wizard::default(); + hold(&mut wizard, [0; 6], REST_SECONDS + 0.1); + hold(&mut wizard, [100, 0, 0, 0, 0, 0], 0.5); + cycle(&mut wizard, &[[8, 0, 0, 0, 0, 0], [10, 0, 0, 0, 0, 0], [12, 0, 0, 0, 0, 0]], SETTLE_SECONDS + 0.1); + assert_eq!(wizard.stage(), Stage::Step(1)); + cycle(&mut wizard, &[[8, 0, 0, 0, 0, 0], [10, 0, 0, 0, 0, 0], [12, 0, 0, 0, 0, 0]], 0.2); + assert_eq!(wizard.progress(), 0.0); + cycle(&mut wizard, &[[7, 0, 0, 0, 0, 0], [10, 0, 0, 0, 0, 0], [13, 0, 0, 0, 0, 0]], 0.2); + assert!(wizard.progress() > 0.0); + } + + #[test] + fn a_push_after_a_single_reading_settle_starts_a_hold() { + // One reading back at rest, not a steady run, is all the settle stores; a full push after + // it is still movement. + let mut wizard = Wizard::default(); + hold(&mut wizard, [0; 6], REST_SECONDS + 0.1); + hold(&mut wizard, [100, 0, 0, 0, 0, 0], 0.5); + wizard.feed([0; 6], 0.02); + assert_eq!(wizard.stage(), Stage::Step(1)); + assert_eq!(wizard.settled.map(|settled| settled.count), Some(1)); + hold(&mut wizard, [-100, 0, 0, 0, 0, 0], 0.2); + assert_eq!((wizard.stage(), wizard.progress() > 0.0), (Stage::Step(1), true)); + } + + #[test] + fn a_narrow_settled_run_skips_a_whole_tolerance_either_side_and_the_band_stays_anchored() { + // Flat at rest and a 100 push: tolerance is exactly 4. The release settles flat at 10, so a + // reading 4 either side (6, 14) is untouched, repeated or not; one more unit is movement. + let wizard = || { + let mut wizard = Wizard::default(); + hold(&mut wizard, [0; 6], REST_SECONDS + 0.1); + hold(&mut wizard, [100, 0, 0, 0, 0, 0], 0.5); + hold(&mut wizard, [10, 0, 0, 0, 0, 0], SETTLE_SECONDS + 0.1); + assert_eq!(wizard.stage(), Stage::Step(1)); + assert_eq!(wizard.tolerance(0), 4.0); + wizard + }; + let mut edges = wizard(); + cycle(&mut edges, &[[6, 0, 0, 0, 0, 0], [14, 0, 0, 0, 0, 0]], 0.2); + hold(&mut edges, [14, 0, 0, 0, 0, 0], 0.2); + assert_eq!(edges.progress(), 0.0); + // Skipped readings don't widen the band: after all those 14s, 15 is still movement. + edges.feed([15, 0, 0, 0, 0, 0], 0.02); + assert!(edges.progress() > 0.0); + for x in [5, 15] { + let mut wizard = wizard(); + wizard.feed([x, 0, 0, 0, 0, 0], 0.02); + assert!(wizard.progress() > 0.0, "{x}"); + } + } + + #[test] + fn a_step_settles_on_its_own_axis_when_another_with_a_wider_range_stays_out() { + // The step's own axis only goes to 100; another axis stays 30 out after the release, + // more than a quarter of 100, which mustn't hold the step up. + let mut wizard = Wizard::default(); + hold(&mut wizard, [0; 6], REST_SECONDS + 0.1); + hold(&mut wizard, [100, 0, 0, 0, 0, 0], 0.5); + hold(&mut wizard, [5, 30, 0, 0, 0, 0], SETTLE_SECONDS + 0.1); + assert_eq!(wizard.stage(), Stage::Step(1)); + } + + #[test] + fn a_step_stays_held_when_the_lesser_axis_is_held_while_the_larger_one_relaxes() { + for held in [[100, 5, 0, 0, 0, 0], [100, 60, 0, 0, 0, 0], [100, 200, 0, 0, 0, 0]] { + let mut wizard = Wizard::default(); + hold(&mut wizard, [0; 6], REST_SECONDS + 0.1); + hold(&mut wizard, [100, 200, 0, 0, 0, 0], 0.5); + hold(&mut wizard, held, SETTLE_SECONDS + 0.1); + assert_eq!(wizard.stage(), Stage::Step(0), "{held:?}"); + } + // A plain hold of a single axis. + let mut wizard = Wizard::default(); + hold(&mut wizard, [0; 6], REST_SECONDS + 0.1); + hold(&mut wizard, [100, 0, 0, 0, 0, 0], 0.5); + hold(&mut wizard, [100, 0, 0, 0, 0, 0], SETTLE_SECONDS + 0.1); + assert_eq!(wizard.stage(), Stage::Step(0)); + } + + #[test] + fn a_step_settles_when_cross_talk_moved_another_axis_further_than_its_own() { + // Nula's case: the push moves raw 1 twice as far as raw 0, which may be the one asked + // for. Raw 0 comes back to 5 % and raw 1 stays at 30 %: let go, both steady. + let mut wizard = Wizard::default(); + hold(&mut wizard, [0; 6], REST_SECONDS + 0.1); + hold(&mut wizard, [100, 200, 0, 0, 0, 0], 0.5); + hold(&mut wizard, [5, 60, 0, 0, 0, 0], SETTLE_SECONDS + 0.1); + assert_eq!(wizard.stage(), Stage::Step(1)); + // Still holding the push, with only the lesser axis back, isn't let go. + let mut holding = Wizard::default(); + hold(&mut holding, [0; 6], REST_SECONDS + 0.1); + hold(&mut holding, [100, 200, 0, 0, 0, 0], 0.5); + hold(&mut holding, [5, 200, 0, 0, 0, 0], 1.0); + assert_eq!(holding.stage(), Stage::Step(0)); + } + + #[test] + fn a_lopsided_dither_that_settled_a_step_isnt_movement_in_the_next() { + // Mostly 10 with an occasional 14: spread 4, so steady, but the mean sits near 11 and the 14 + // is the far edge. Sitting there stays untouched; 15 is wider than the steadiness check allows. + let mut wizard = Wizard::default(); + hold(&mut wizard, [0; 6], REST_SECONDS + 0.1); + hold(&mut wizard, [100, 0, 0, 0, 0, 0], 0.5); + let lopsided = [[10, 0, 0, 0, 0, 0], [10, 0, 0, 0, 0, 0], [10, 0, 0, 0, 0, 0], [14, 0, 0, 0, 0, 0]]; + cycle(&mut wizard, &lopsided, SETTLE_SECONDS + 0.1); + assert_eq!(wizard.stage(), Stage::Step(1)); + cycle(&mut wizard, &lopsided, 1.0); + assert_eq!((wizard.stage(), wizard.progress()), (Stage::Step(1), 0.0)); + hold(&mut wizard, [16, 0, 0, 0, 0, 0], 0.2); + assert!(wizard.progress() > 0.0); + } + + #[test] + fn cross_talk_that_leaves_the_bigger_axis_well_out_keeps_the_step_open() { + // The documented limit (Grok's case): raw 0 moved less than half as far as raw 1, so it + // never qualifies, and raw 1 at 90 is above a quarter of its 300 peak. + let mut wizard = Wizard::default(); + hold(&mut wizard, [0; 6], REST_SECONDS + 0.1); + hold(&mut wizard, [100, 300, 0, 0, 0, 0], 0.5); + hold(&mut wizard, [5, 90, 0, 0, 0, 0], SETTLE_SECONDS + 1.0); + assert_eq!(wizard.stage(), Stage::Step(0)); + } + + #[test] + fn a_hand_held_still_close_to_rest_after_the_push_counts_as_let_go() { + // The known limit: held exactly still at a fifth of the way out, on any device, ends the + // step there, and that axis's dead zone widens to cover it. + let low = PRO[0].map(|value| value / 5); + let mut wizard = Wizard::default(); + rest_then(&mut wizard); + hold(&mut wizard, PRO[0], 0.5); + hold(&mut wizard, low, SETTLE_SECONDS + 0.1); + assert_eq!(wizard.stage(), Stage::Step(1)); + assert_eq!((wizard.recording.settled[0].min, wizard.recording.settled[0].max), (low, low)); + // Coming back to its true rest afterwards doesn't undo that: the next step is waiting. + hold(&mut wizard, STILL[0], 0.5); + assert_eq!((wizard.stage(), wizard.progress()), (Stage::Step(1), 0.0)); + // No frame of where it settled went into the step as held. + assert_eq!((wizard.recording.steps[0].min[0], wizard.recording.steps[0].max[4]), (PRO[0][0], PRO[0][4])); + } + + #[test] + fn every_reading_of_a_release_that_was_let_go_falls_in_the_dead_zone() { + // Nula's case: X wanders -4..+4 at rest. Half the releases dither over +8..+16, the other + // half over -16..-8. Keeping one reading of each, padded by the wander, can miss the edges. + let wander = [[-4, 0, 0, 0, 0, 0], [4, 0, 0, 0, 0, 0]]; + let x = |value: i16| [value, 0, 0, 0, 0, 0]; + let (above, below) = ([x(16), x(12), x(8)], [x(-8), x(-12), x(-16)]); + let mut wizard = Wizard::default(); + for _ in 0..40 { + hold(&mut wizard, wander[0], 0.02); + hold(&mut wizard, wander[1], 0.02); + } + for (index, reading) in PRO.into_iter().enumerate() { + assert_eq!(wizard.stage(), Stage::Step(index)); + hold(&mut wizard, reading, 0.5); + cycle(&mut wizard, if index % 2 == 0 { &above } else { &below }, SETTLE_SECONDS + 0.1); + } + let calibration = wizard.result().unwrap().unwrap(); + for still in above.iter().chain(&below).chain(&wander) { + assert_eq!(calibration.apply(*still), [0; 6], "{still:?} {calibration:?}"); + } + } + + #[test] + fn two_steps_in_a_row_that_stop_at_the_same_place_both_finish() { + let mut wizard = Wizard::default(); + hold(&mut wizard, STUCK[0], REST_SECONDS + 0.1); + for reading in &PRO[..2] { + hold(&mut wizard, *reading, 0.5); + hold(&mut wizard, STUCK[1], SETTLE_SECONDS + 0.1); + } + assert_eq!(wizard.stage(), Stage::Step(2)); + } + + #[test] + fn recentring_on_where_the_cap_settled_keeps_the_whole_rest_wander_inside_the_dead_zone() { + // X wanders -4..+4 at rest, and every release settles at +12. + let wander = [[-4, 0, 0, 0, 0, 0], [4, 0, 0, 0, 0, 0]]; + let mut recording = record(PRO, wander); + for index in 0..12 { + recording.settled(index, [12, 0, 0, 0, 0, 0]); + } + let calibration = recording.solve().unwrap(); + for still in [wander[0], wander[1], [12, 0, 0, 0, 0, 0]] { + assert_eq!(calibration.apply(still), [0; 6], "{still:?} {calibration:?}"); + } + } + + #[test] + fn the_dead_zone_shares_are_where_apply_starts_moving() { + // A lopsided, reversed axis with the user's dead zone on top. + let mut calibration = walk(STILL, PRO).result().unwrap().unwrap(); + calibration.axes[0] = AxisCalibration { source: 0, reversed: true, rest: 10, dead_zone: 20, full: [100, 400] }; + calibration.dead_zone_share = 0.1; + let [negative, positive] = calibration.dead_zone_shares()[0]; + // Canonical negative is raw above rest here: 400 of travel, 20 measured. + assert!((negative - (0.05 + 0.95 * 0.1)).abs() < 1e-6 && (positive - (0.2 + 0.8 * 0.1)).abs() < 1e-6); + let at = |raw: i16| [raw, 0, 0, 0, 0, 0]; + let inside = |share: f32, full: f32| (share * full).floor() as i16 - 1; + assert_eq!(calibration.apply(at(10 + inside(negative, 400.0)))[0], 0); + assert!(calibration.apply(at(10 + inside(negative, 400.0) + 3))[0] < 0); + assert_eq!(calibration.apply(at(10 - inside(positive, 100.0)))[0], 0); + assert!(calibration.apply(at(10 - inside(positive, 100.0) - 3))[0] > 0); + // Full deflection is ±1 of travel, the reversed way round. + assert_eq!(calibration.travel(at(410))[0], -1.0); + assert_eq!(calibration.travel(at(-90))[0], 1.0); + } + + #[test] + fn a_device_that_comes_back_to_rest_keeps_its_measured_rest_and_dead_zone() { + let mut settled = record(PRO, STILL); + let plain = settled.solve().unwrap(); + for index in 0..12 { + settled.settled(index, STILL[index % 2]); + } + assert_eq!(settled.solve().unwrap(), plain); + } + + #[test] + fn a_noisy_axis_at_rest_holds_up_neither_itself_nor_a_quiet_one() { + // X wanders ±4 at rest, and goes +500 one way but only -50 the other: the solver accepts + // that, so the wizard has to be able to record it. + let mut steps = PRO; + steps[0][0] = 500; + steps[1][0] = -50; + let noisy_x = [[-4, 0, 0, 0, 0, 0], [4, 0, 0, 0, 0, 0]]; + let calibration = walk(noisy_x, steps).result().unwrap().unwrap(); + assert_eq!((calibration.axes[0].source, calibration.axes[0].dead_zone, calibration.axes[0].full), (0, 4, [50, 500])); + // Rz wanders ±40 at rest: every other axis still records against its own quiet rest. + let noisy_rz = [[0, 0, 0, 0, 0, -40], [0, 0, 0, 0, 0, 40]]; + let calibration = walk(noisy_rz, PRO).result().unwrap().unwrap(); + assert!(calibration.axes.iter().enumerate().all(|(c, axis)| axis.source == c && !axis.reversed), "{calibration:?}"); + } + + #[test] + fn a_step_that_caught_a_resting_hand_instead_of_a_push_is_named() { + // A quiet device (nothing at rest), and slide right recorded only a hand resting on the + // cap: scaled up, a few units would be full speed. + let mut steps = PRO; + steps[0] = [6, 4, 0, 0, 3, 0]; + assert_eq!(record(steps, [[0; 6]; 2]).solve(), Err(Problem::NoResponse(0))); + } + + #[test] + fn a_hand_edited_calibration_that_could_spin_the_view_isnt_usable() { + let solved = record(PRO, STILL).solve().unwrap(); + assert!(solved.is_usable()); + let mut bad = solved; + bad.axes[2].source = 6; + assert!(!bad.is_usable(), "a source the device doesn't have"); + let mut bad = solved; + bad.axes[2].full[0] = bad.axes[2].dead_zone; + assert!(!bad.is_usable(), "any touch past the dead zone would be full speed"); + let mut bad = solved; + bad.axes[2].source = bad.axes[3].source; + assert!(!bad.is_usable(), "two canonical axes from one raw axis"); + } + + #[test] + fn readings_for_a_step_that_doesnt_exist_are_ignored() { + let mut recording = record(PRO, STILL); + recording.step(12, [i16::MAX; 6]); + assert_eq!(recording.solve(), record(PRO, STILL).solve()); + } +} diff --git a/crates/space-mouse/src/lib.rs b/crates/space-mouse/src/lib.rs index 6ab8099db..6a2af5f2e 100644 --- a/crates/space-mouse/src/lib.rs +++ b/crates/space-mouse/src/lib.rs @@ -10,6 +10,10 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] +mod calibration; mod descriptor; +pub use calibration::{ + AxisCalibration, Calibration, HOLD_SECONDS, MAX_DEAD_ZONE_SHARE, MIN_SHARE, Problem, REST_SECONDS, Recording, STEPS, Stage, Step, Wizard, +}; pub use descriptor::{Descriptor, FULL_SCALE, Field, Layout, MAX_BUTTONS, Report}; diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 70e1c9749..d1bf0fc4b 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -13,6 +13,7 @@ solidcraft-engine = { workspace = true } egui = { workspace = true } egui-wgpu = { workspace = true } solidcraft-gpu = { workspace = true } +solidcraft-space-mouse = { workspace = true, features = ["serde"] } serde = { workspace = true } serde_json = { workspace = true } log = { workspace = true } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index b5d2d4f00..89483780d 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -178,6 +178,7 @@ pub mod smart_extrude; #[cfg(test)] mod smart_extrude_ui_tests; pub mod space_mouse; +pub mod space_mouse_calibration; pub mod stand_up; #[cfg(test)] mod sweep_dialog_tests; @@ -415,6 +416,8 @@ pub struct SolveApp { pub flat_view: dialogs_sheet::FlatView, /// The start page. pub home: home::HomeState, + /// The 3D mouse: which device, its reading, and the calibration window. + pub space_mouse: space_mouse::Input, pub file_load: file_load::FileLoad, /// The other open designs (tabs). pub docs: documents::Documents, @@ -507,6 +510,7 @@ impl SolveApp { pending_fit: None, flat_view: Default::default(), home: home::HomeState::default(), + space_mouse: Default::default(), file_load: file_load::FileLoad::default(), docs: documents::Documents::default(), applied_fonts_language: "en".into(), diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index 47963d692..661fd5ebd 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -284,6 +284,10 @@ pub struct Prefs { pub space_mouse_reverse: [bool; 6], /// Per physical axis of the cap, a multiplier on top of `space_mouse_speed`; 0 switches it off. pub space_mouse_axis_speed: [f32; 6], + /// Per 3D mouse (`space_mouse::Input::device`), the calibration that puts its axes on + /// 3Dconnexion's. A device without one is read as it reports. + #[serde(deserialize_with = "calibrations_that_read")] + pub space_mouse_calibrations: std::collections::BTreeMap, /// Anti-aliasing samples (applies on restart). pub msaa: u32, /// Soft contact shading in the GPU viewport; optional and applied immediately. @@ -446,6 +450,7 @@ impl Default for Prefs { space_mouse_speed: 1.0, space_mouse_reverse: [false; 6], space_mouse_axis_speed: [1.0; 6], + space_mouse_calibrations: Default::default(), msaa: 4, ambient_occlusion: false, grid_follows_view: false, @@ -763,6 +768,7 @@ fn defaults(app: &mut SolveApp, page: usize) { p.space_mouse_speed = d.space_mouse_speed; p.space_mouse_reverse = d.space_mouse_reverse; p.space_mouse_axis_speed = d.space_mouse_axis_speed; + // The 3D mice the user calibrated stay: a calibration describes the device. p.look_at_anim = d.look_at_anim; p.look_at_speed = d.look_at_speed; p.middle_double_click = d.middle_double_click; @@ -1079,6 +1085,8 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { } if !app.prefs_window.open { app.prefs_window.snapshot = None; + // Calibration opens from here and ends with it, so the cap moves the view again. + app.space_mouse.calibrating = None; return; } if app.prefs_window.snapshot.is_none() { @@ -1147,6 +1155,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { if let Some(w) = &shown { crate::scenario::publish_rect("prefs:window", w.response.rect); } + crate::space_mouse_calibration::show(app, ctx); if app.preferences.msaa != before.msaa { save_graphics(app); } @@ -1395,6 +1404,42 @@ fn page(app: &mut SolveApp, ui: &mut egui::Ui, t: &Tokens) { }); ui.end_row(); } + ui.label(app.tr("ui.space_mouse_calibration")); + ui.horizontal(|ui| { + let device = app.space_mouse.device.clone(); + let saved = device.as_ref().is_some_and(|device| app.preferences.space_mouse_calibrations.contains_key(device)); + ui.add_enabled_ui(app.preferences.space_mouse_enabled && device.is_some(), |ui| { + if ui.button(app.tr("ui.space_mouse_calibrate")).on_hover_text(app.tr("ui.space_mouse_calibrate_tip")).clicked() { + crate::space_mouse_calibration::start(app); + } + if saved && ui.button(app.tr("ui.space_mouse_forget")).clicked() + && let Some(device) = &device + { + app.preferences.space_mouse_calibrations.remove(device); + } + }); + // With the device it's about, so it's clear which calibration is in use. + ui.label(match (&device, saved) { + (None, _) => app.tr("ui.space_mouse_none").to_owned(), + (Some(device), true) => format!("{} ({device})", app.tr("ui.space_mouse_calibrated")), + (Some(device), false) => format!("{} ({device})", app.tr("ui.space_mouse_not_calibrated")), + }); + }); + ui.end_row(); + // The calibrated device's dead zone, adjustable after calibrating. + let enabled = app.preferences.space_mouse_enabled; + let (label, tip) = (app.tr("ui.space_mouse_dead_zone").to_owned(), app.tr("ui.space_mouse_dead_zone_tip").to_owned()); + let (device, raw) = (app.space_mouse.device.clone(), app.space_mouse.raw.into()); + if let Some(calibration) = device.and_then(|device| app.preferences.space_mouse_calibrations.get_mut(&device)) { + ui.label(label); + ui.add_enabled_ui(enabled, |ui| { + crate::space_mouse_calibration::dead_zone_slider(ui, &mut calibration.dead_zone_share).on_hover_text(tip); + }); + ui.end_row(); + ui.label(""); + crate::space_mouse_calibration::dead_zone_pads(ui, calibration, raw); + ui.end_row(); + } note(ui, crate::i18n::tr_label("Move and rotate the view together; sketches use pan and zoom only.")); } PAGE_DESIGN => { @@ -1704,6 +1749,24 @@ pub fn control(app: &mut SolveApp, p: &serde_json::Value) -> Result>( + saved: D, +) -> Result, D::Error> { + let saved = std::collections::BTreeMap::::deserialize(saved)?; + Ok(saved + .into_iter() + .filter_map(|(device, calibration)| match serde_json::from_value(calibration) { + Ok(calibration) => Some((device, calibration)), + Err(error) => { + log::warn!("preferences: the 3D mouse calibration for `{device}` can't be read ({error}); reading the device as it reports"); + None + } + }) + .collect()) +} + /// Every theme the Theme list offers, as (id, name): the modes, the built-in theme files, then /// the imported ones. fn theme_choices(app: &SolveApp) -> Vec<(String, String)> { @@ -1756,16 +1819,26 @@ fn current_theme_file(app: &SolveApp) -> serde_json::Value { } } -/// Fold a setting an older release kept in its own field into the one this version reads. -/// `orbit_cursor` (`true` = the point under the cursor) became `orbit_around`. /// The cap's physical axes, in the order of `Prefs::space_mouse_reverse`. -const SPACE_MOUSE_AXES: [&str; 6] = ["Push left / right", "Push forward / back", "Lift / press", "Tilt forward / back", "Tilt left / right", "Twist"]; +pub(crate) const SPACE_MOUSE_AXES: [&str; 6] = + ["Push left / right", "Push forward / back", "Lift / press", "Tilt forward / back", "Tilt left / right", "Twist"]; +/// Fold a setting an older release kept in its own field into the one this version reads. +/// `orbit_cursor` (`true` = the point under the cursor) became `orbit_around`. A 3D mouse +/// calibration that can't be used as it is (a hand edit) is dropped, so the device is read as it +/// reports rather than spinning the view. pub fn migrate(mut p: Prefs) -> Prefs { if p.orbit_cursor { p.orbit_around = OrbitAround::Cursor; p.orbit_cursor = false; } + p.space_mouse_calibrations.retain(|device, calibration| { + let usable = calibration.is_usable(); + if !usable { + log::warn!("preferences: the 3D mouse calibration for `{device}` can't be used as it is; reading the device as it reports"); + } + usable + }); p } diff --git a/crates/ui-egui/src/space_mouse.rs b/crates/ui-egui/src/space_mouse.rs index f6663b369..fbd61fc48 100644 --- a/crates/ui-egui/src/space_mouse.rs +++ b/crates/ui-egui/src/space_mouse.rs @@ -8,6 +8,8 @@ use std::time::Duration; use crate::SolveApp; +pub use solidcraft_space_mouse::{AxisCalibration, Calibration}; + /// What a 3Dconnexion device reports at full deflection, in raw units, on every axis. pub const FULL_SCALE: i16 = 350; @@ -26,6 +28,31 @@ impl Axes { } } +impl From for [i16; 6] { + fn from(axes: Axes) -> Self { + let ([x, y, z], [rx, ry, rz]) = (axes.translation, axes.rotation); + [x, y, z, rx, ry, rz] + } +} + +impl From<[i16; 6]> for Axes { + fn from([x, y, z, rx, ry, rz]: [i16; 6]) -> Self { + Self { translation: [x, y, z], rotation: [rx, ry, rz] } + } +} + +/// The 3D mouse as of this frame. +#[derive(Debug, Default)] +pub struct Input { + /// The device being read: where from and its vendor and product ids (`hid 256f:c63a`, + /// `web 256f:c63a`), or where from alone (`spacenavd`). Its calibration is saved under it. + pub device: Option, + /// This frame's reading, before calibration. + pub raw: Axes, + /// The guided calibration while its window is open, and the device it is for. + pub calibrating: Option<(String, solidcraft_space_mouse::Wizard)>, +} + /// Seconds after the cap last moved that wheel events are still taken for 3DxWare's: one can be /// queued just before the cap stops and only reach the next frame. pub const WHEEL_QUIET_S: f64 = 0.15; @@ -134,13 +161,39 @@ pub struct DeviceMotion { pub seconds: f64, } +/// The saved calibration of the device being read, when it has one. +pub fn calibration(app: &SolveApp) -> Option { + app.space_mouse.device.as_ref().and_then(|device| app.preferences.space_mouse_calibrations.get(device)).copied() +} + +/// A reading on 3Dconnexion's axes: through `calibration` when there is one. Whether the cap is +/// moving is asked of this, never of the raw reading, so a device resting off zero isn't "moving" +/// and a short-range one moves as soon as it does. +pub fn calibrated(axes: Axes, calibration: Option) -> Axes { + calibration.map_or(axes, |calibration| calibration.apply(axes.into()).into()) +} + /// Hands one frame of 3D mouse input, `seconds` after the previous frame, to the page showing /// the camera. Nothing happens with navigation switched off, on the start page or while a file -/// picker is open. Returns whether there was motion to hand over; it then asks for the next frame -/// itself. +/// picker is open, or while the reading is inside the dead zone (after calibration, which takes +/// off the device's own rest offset), so a cap resting just off zero doesn't keep redrawing. +/// Returns whether there was motion to hand over; it then asks for the next frame itself. The +/// reading goes through the device's saved calibration first, when it has one; while the +/// calibration window is open, the reading goes to it instead and the view stays put. pub fn navigate_frame(app: &mut SolveApp, ctx: &egui::Context, mapping: DriverMapping, axes: Axes, seconds: f64) -> bool { + app.space_mouse.raw = axes; + if let Some((device, wizard)) = &mut app.space_mouse.calibrating { + if app.space_mouse.device.as_ref() == Some(device) { + wizard.feed(axes.into(), seconds); + ctx.request_repaint_after(Duration::from_millis(16)); + return false; + } + // Another device is being read now, or none: what was recorded isn't its. + app.space_mouse.calibrating = None; + } + let axes = calibrated(axes, calibration(app)); // Only the window with focus: with two windows open, the cap moves the one being used, not both. - if !app.preferences.space_mouse_enabled || app.home.open || app.file_picker_busy() || axes == Axes::default() || !ctx.input(|i| i.focused) { + if !app.preferences.space_mouse_enabled || app.home.open || app.file_picker_busy() || !axes.moving() || !ctx.input(|i| i.focused) { return false; } let speed = f64::from(app.preferences.space_mouse_speed); @@ -467,4 +520,112 @@ mod tests { guard.filter(false, f64::NAN, &mut events); assert_eq!(events.len(), 1); } + + /// A homemade device that sends push forward/back as its fifth axis, the other way round, at + /// ten times 3Dconnexion's range. + fn homemade() -> solidcraft_space_mouse::Calibration { + let axis = |source, reversed| solidcraft_space_mouse::AxisCalibration { source, reversed, rest: 0, dead_zone: 0, full: [3500; 2] }; + solidcraft_space_mouse::Calibration { + dead_zone_share: 0.0, + axes: [axis(0, false), axis(4, true), axis(2, false), axis(3, false), axis(1, false), axis(5, false)], + } + } + + #[test] + fn a_devices_saved_calibration_puts_its_axes_on_3dconnexions() { + let ctx = window(true); + let mut reference = app(); + frame(&mut reference, &ctx, DriverMapping::default(), PUSH, 0.02); + let sent = Axes { translation: [0; 3], rotation: [0, -3500, 0] }; + let mut calibrated = app(); + calibrated.space_mouse.device = Some("hid 1234:5678".into()); + calibrated.preferences.space_mouse_calibrations.insert("hid 1234:5678".into(), homemade()); + assert!(frame(&mut calibrated, &ctx, DriverMapping::default(), sent, 0.02)); + assert_eq!(calibrated.cam, reference.cam); + // Another device's calibration isn't applied: the reading turns the view as it comes. + let mut other = app(); + other.space_mouse.device = Some("hid 256f:c63a".into()); + other.preferences.space_mouse_calibrations.insert("hid 1234:5678".into(), homemade()); + frame(&mut other, &ctx, DriverMapping::default(), sent, 0.02); + assert_ne!(other.cam, reference.cam); + } + + #[test] + fn while_calibrating_the_cap_feeds_the_calibration_and_the_view_stays() { + let ctx = window(true); + let mut app = app(); + crate::space_mouse_calibration::start(&mut app); + assert!(app.space_mouse.calibrating.is_none(), "nothing to calibrate without a device"); + app.space_mouse.device = Some("hid 256f:c63a".into()); + crate::space_mouse_calibration::start(&mut app); + let before = app.cam; + assert!(!frame(&mut app, &ctx, DriverMapping::default(), PUSH, 0.02)); + assert_eq!(app.cam, before); + assert_eq!(app.space_mouse.raw, PUSH); + assert!(app.space_mouse.calibrating.as_ref().is_some_and(|(_, wizard)| wizard.progress() > 0.0)); + // Closing Preferences ends it, so the cap moves the view again. + app.prefs_window.open = false; + crate::prefs::show(&mut app, &ctx); + assert!(app.space_mouse.calibrating.is_none()); + assert!(frame(&mut app, &ctx, DriverMapping::default(), PUSH, 0.02)); + } + + #[test] + fn a_reading_resting_off_zero_is_kept_for_calibration_and_doesnt_move_the_view() { + let ctx = window(true); + // Inside the dead zone and not calibrated: no motion, so no redraw either. + let mut app = app(); + let resting = Axes { translation: [0, 15, 0], rotation: [0; 3] }; + let before = app.cam; + assert!(!frame(&mut app, &ctx, DriverMapping::default(), resting, 0.02)); + assert_eq!(app.cam, before); + // The calibration window gets it as it is, to measure where the cap rests. + app.space_mouse.device = Some("web 1234:5678".into()); + crate::space_mouse_calibration::start(&mut app); + frame(&mut app, &ctx, DriverMapping::default(), resting, 0.02); + assert_eq!(app.space_mouse.raw, resting); + app.space_mouse.calibrating = None; + // A device resting far off zero, calibrated: still at rest, moving when pushed. + let mut offset = homemade(); + for axis in &mut offset.axes { + axis.rest = 1000; + } + app.preferences.space_mouse_calibrations.insert("web 1234:5678".into(), offset); + let at_rest = Axes { translation: [1000; 3], rotation: [1000; 3] }; + assert!(!frame(&mut app, &ctx, DriverMapping::default(), at_rest, 0.02)); + assert_eq!(app.cam, before); + assert!(frame(&mut app, &ctx, DriverMapping::default(), Axes { rotation: [1000, 1000 - 3500, 1000], ..at_rest }, 0.02)); + } + + #[test] + fn another_device_turning_up_mid_calibration_ends_it() { + let ctx = window(true); + let mut app = app(); + app.space_mouse.device = Some("hid 256f:c63a".into()); + crate::space_mouse_calibration::start(&mut app); + frame(&mut app, &ctx, DriverMapping::default(), PUSH, 0.02); + app.space_mouse.device = Some("spacenavd".into()); + assert!(frame(&mut app, &ctx, DriverMapping::default(), PUSH, 0.02), "the new device moves the view"); + assert!(app.space_mouse.calibrating.is_none()); + assert!(app.preferences.space_mouse_calibrations.is_empty()); + } + + #[test] + fn calibrations_are_saved_with_the_preferences() { + let mut prefs = crate::prefs::Prefs::default(); + prefs.space_mouse_calibrations.insert("hid 1234:5678".into(), homemade()); + let mut saved = serde_json::to_value(&prefs).unwrap(); + assert_eq!(crate::prefs::lenient(&saved), prefs); + // One that can't be read, or that could spin the view, is dropped on its own. + let mut spinning = homemade(); + spinning.axes[0].full = [0; 2]; + saved["space_mouse_calibrations"]["spacenavd"] = serde_json::to_value(spinning).unwrap(); + saved["space_mouse_calibrations"]["web 046d:c62b"] = serde_json::json!({ "axes": "garbled" }); + assert_eq!(crate::prefs::lenient(&saved), prefs); + // One saved before the dead zone setting existed reads with none. + let mut older = serde_json::to_value(homemade()).unwrap(); + older.as_object_mut().unwrap().remove("dead_zone_share"); + saved["space_mouse_calibrations"]["hid 1234:5678"] = older; + assert_eq!(crate::prefs::lenient(&saved), prefs); + } } diff --git a/crates/ui-egui/src/space_mouse_calibration.rs b/crates/ui-egui/src/space_mouse_calibration.rs new file mode 100644 index 000000000..078b0621e --- /dev/null +++ b/crates/ui-egui/src/space_mouse_calibration.rs @@ -0,0 +1,157 @@ +//! The 3D mouse calibration window, opened from Preferences › Navigation. It asks the user to +//! leave the cap still, then to move it along each axis both ways, moving on by itself after each +//! (`solidcraft_space_mouse::Wizard`), and saves what it found for the device it started with. +//! The window closes with Preferences, and when another device (or none) is read instead. + +use solidcraft_space_mouse::{Calibration, Problem, Stage, Wizard}; + +use crate::SolveApp; + +/// What each of `solidcraft_space_mouse::STEPS` asks for, in order. +const STEP_PROMPTS: [&str; 12] = [ + "ui.space_mouse_step_slide_right", + "ui.space_mouse_step_slide_left", + "ui.space_mouse_step_pull", + "ui.space_mouse_step_push", + "ui.space_mouse_step_press", + "ui.space_mouse_step_lift", + "ui.space_mouse_step_tilt_back", + "ui.space_mouse_step_tilt_forward", + "ui.space_mouse_step_tilt_left", + "ui.space_mouse_step_tilt_right", + "ui.space_mouse_step_twist_clockwise", + "ui.space_mouse_step_twist_counterclockwise", +]; + +/// The dead zone, as a share of full travel, shown as a percentage. +pub(crate) fn dead_zone_slider(ui: &mut egui::Ui, share: &mut f32) -> egui::Response { + ui.add( + egui::Slider::new(share, 0.0..=solidcraft_space_mouse::MAX_DEAD_ZONE_SHARE) + .step_by(0.01) + .custom_formatter(|v, _| format!("{:.0} %", v * 100.0)), + ) +} + +/// The calibration's dead zones the way a game controller tester shows a stick: per pair of axes, +/// a circle for the full travel, the dead zone shaded inside it (each direction its own size), and +/// a dot where the cap is now, before the dead zone, so it's plain when the view starts to move. +pub(crate) fn dead_zone_pads(ui: &mut egui::Ui, calibration: &Calibration, raw: [i16; 6]) { + const NAMES: [&str; 6] = ["X", "Y", "Z", "Rx", "Ry", "Rz"]; + // (horizontal axis, its positive way on screen, vertical axis, its positive way down), so the + // dot moves as the cap does: slid right and pulled toward you, twisted and pressed, tilted. + const PADS: [(usize, f32, usize, f32); 3] = [(0, 1.0, 1, 1.0), (5, 1.0, 2, 1.0), (4, -1.0, 3, -1.0)]; + const SIZE: f32 = 76.0; + let (shares, travel, moving) = (calibration.dead_zone_shares(), calibration.travel(raw), calibration.apply(raw)); + let visuals = ui.visuals().clone(); + ui.horizontal(|ui| { + for (h, h_way, v, v_way) in PADS { + ui.vertical(|ui| { + let (rect, response) = ui.allocate_exact_size(egui::vec2(SIZE, SIZE), egui::Sense::hover()); + let painter = ui.painter_at(rect); + let (centre, radius) = (rect.center(), SIZE / 2.0 - 2.0); + let faint = visuals.weak_text_color(); + // Which side of an axis's dead zone lies along a way on screen. + let side = |axis: usize, way: f32, screen: f32| shares[axis][usize::from(way * screen > 0.0)]; + let zone: Vec = (0..64) + .map(|i| { + let (sin, cos) = (i as f32 / 64.0 * std::f32::consts::TAU).sin_cos(); + let (x, y) = (side(h, h_way, cos) * cos, side(v, v_way, sin) * sin); + centre + egui::vec2(x, y) * radius + }) + .collect(); + painter.add(egui::Shape::convex_polygon(zone, visuals.selection.bg_fill.gamma_multiply(0.35), egui::Stroke::NONE)); + painter.line_segment( + [centre - egui::vec2(radius, 0.0), centre + egui::vec2(radius, 0.0)], + egui::Stroke::new(1.0, faint.gamma_multiply(0.4)), + ); + painter.line_segment( + [centre - egui::vec2(0.0, radius), centre + egui::vec2(0.0, radius)], + egui::Stroke::new(1.0, faint.gamma_multiply(0.4)), + ); + painter.circle_stroke(centre, radius, egui::Stroke::new(1.0, faint)); + let dot = egui::vec2(h_way * travel[h], v_way * travel[v]); + let dot = if dot.length() > 1.0 { dot.normalized() } else { dot }; + let live = moving[h] != 0 || moving[v] != 0; + painter.circle_filled(centre + dot * radius, 3.5, if live { visuals.selection.stroke.color } else { faint }); + let percent = |axis: usize| format!("{} −{:.0} % +{:.0} %", NAMES[axis], shares[axis][0] * 100.0, shares[axis][1] * 100.0); + response.on_hover_text(format!("{}\n{}", percent(h), percent(v))); + ui.label(egui::RichText::new(format!("{} · {}", NAMES[h], NAMES[v])).small().color(faint)); + }); + } + }); +} + +/// Starts calibrating the device being read, if there is one. +pub fn start(app: &mut SolveApp) { + app.space_mouse.calibrating = app.space_mouse.device.clone().map(|device| (device, Wizard::default())); +} + +pub fn show(app: &mut SolveApp, ctx: &egui::Context) { + let Some((_, wizard)) = &app.space_mouse.calibrating else { return }; + let (stage, progress, result) = (wizard.stage(), wizard.progress(), wizard.result()); + let mut dead_zone = wizard.dead_zone_share(); + let raw: [i16; 6] = app.space_mouse.raw.into(); + let prompt = match (stage, result) { + (Stage::Rest, _) => "ui.space_mouse_step_rest", + (Stage::Step(index), _) => STEP_PROMPTS.get(index).copied().unwrap_or_default(), + (Stage::Done, Some(Ok(_))) => "ui.space_mouse_calibration_done", + (Stage::Done, _) => "ui.space_mouse_calibration_no_response", + }; + // The axis that barely moved, as Preferences names it. + let weak = match result { + Some(Err(Problem::NoResponse(axis))) => crate::prefs::SPACE_MOUSE_AXES.get(axis).copied(), + _ => None, + }; + let counter = match stage { + Stage::Rest => String::new(), + Stage::Step(index) => format!("{} / {}", index + 1, STEP_PROMPTS.len()), + Stage::Done => format!("{0} / {0}", STEP_PROMPTS.len()), + }; + let (mut back, mut over, mut cancel, mut save) = (false, false, false, false); + crate::frame::window(ctx, app.tr("ui.space_mouse_calibrate_title"), crate::frame::Width::Normal) + .id(egui::Id::new("sc_space_mouse_calibration")) + .collapsible(false) + .resizable(false) + .show(ctx, |ui| { + ui.label(app.tr(prompt)); + if let Some(axis) = weak { + ui.label(egui::RichText::new(app.tr_label(axis)).strong()); + } + ui.add_space(6.0); + ui.add(egui::ProgressBar::new(progress as f32).text(counter)); + if let Some(Ok(calibration)) = result { + ui.add_space(6.0); + dead_zone_pads(ui, &Calibration { dead_zone_share: dead_zone, ..calibration }, raw); + } + // The device's six raw axes as they come, so the jitter at rest is there to see. + let reading = raw.map(|value| format!("{value:>6}")).join(" "); + ui.label(egui::RichText::new(format!("{}: {reading}", app.tr("ui.space_mouse_reading"))).monospace()); + ui.horizontal(|ui| { + ui.label(app.tr("ui.space_mouse_dead_zone")); + dead_zone_slider(ui, &mut dead_zone).on_hover_text(app.tr("ui.space_mouse_dead_zone_tip")); + }); + ui.add_space(6.0); + ui.horizontal(|ui| { + back = ui.add_enabled(stage != Stage::Rest, egui::Button::new(app.tr("ui.back"))).clicked(); + over = matches!(result, Some(Err(_))) && ui.button(app.tr("ui.start_over")).clicked(); + cancel = ui.button(app.tr("ui.cancel")).clicked(); + save = matches!(result, Some(Ok(_))) && ui.button(app.tr("ui.save")).clicked(); + }); + }); + if cancel { + app.space_mouse.calibrating = None; + } else if let Some((device, wizard)) = &mut app.space_mouse.calibrating { + wizard.set_dead_zone_share(dead_zone); + let result = wizard.result(); + if save && let Some(Ok(calibration)) = result { + app.preferences.space_mouse_calibrations.insert(std::mem::take(device), calibration); + app.space_mouse.calibrating = None; + } else if over { + // A new recording; the dead zone set so far stays. + *wizard = Wizard::default(); + wizard.set_dead_zone_share(dead_zone); + } else if back { + wizard.back(); + } + } +} From 539c17b42587f247fc6e093bc193e3828ce42ce7 Mon Sep 17 00:00:00 2001 From: NOWN-DEV <257771410+NOWN-DEV@users.noreply.github.com> Date: Mon, 19 Oct 2026 22:07:44 +0200 Subject: [PATCH 083/225] Joint sweep: drive a joint until parts touch, and report where (#1981) Joint sweeps can stop where parts touch and report the contact and remaining room. --- assets/locales/de.json | 1 + assets/locales/en.json | 1 + assets/locales/fr.json | 1 + assets/locales/ja.json | 1 + assets/locales/ko.json | 1 + assets/locales/ru.json | 1 + assets/locales/tr.json | 1 + assets/locales/uk.json | 1 + assets/locales/zh.json | 1 + crates/engine/src/cmd/contact_sweep.rs | 323 ++++++++++++++++++-- crates/engine/src/cmd/joints_tests.rs | 4 + crates/engine/src/cmd/motion.rs | 3 + crates/engine/src/cmd/motion_analysis.rs | 16 +- crates/engine/src/cmd/motion_sweep.rs | 261 ++++++++++++++++ crates/engine/src/cmd/motion_sweep_tests.rs | 307 +++++++++++++++++++ docs/book/src/guide/assemblies.md | 13 + skills/solidcraft-mechanisms/SKILL.md | 1 + 17 files changed, 914 insertions(+), 23 deletions(-) create mode 100644 crates/engine/src/cmd/motion_sweep.rs create mode 100644 crates/engine/src/cmd/motion_sweep_tests.rs diff --git a/assets/locales/de.json b/assets/locales/de.json index 8570b54c6..4562094e6 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -246,6 +246,7 @@ "cmd.joint_rigid_group": "Starrgruppe", "cmd.joint_screw": "Schraube", "cmd.joint_solve": "Gelenke lösen", + "cmd.joint_sweep": "Gelenk bis zum Kontakt durchfahren", "cmd.library_apply": "Lokalen Bibliothekseintrag anwenden", "cmd.library_export": "Designbibliothek exportieren", "cmd.library_inspect": "Lokale Bibliothek prüfen", diff --git a/assets/locales/en.json b/assets/locales/en.json index 26538886b..a948a4e06 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -454,6 +454,7 @@ "cmd.joint_rigid_group": "Rigid Group", "cmd.joint_screw": "Screw", "cmd.joint_solve": "Solve Joints", + "cmd.joint_sweep": "Sweep Joint", "cmd.library_apply": "Apply Local Library Entry", "cmd.library_export": "Export Design Library", "cmd.library_inspect": "Inspect Local Library", diff --git a/assets/locales/fr.json b/assets/locales/fr.json index 319456076..803fba008 100644 --- a/assets/locales/fr.json +++ b/assets/locales/fr.json @@ -448,6 +448,7 @@ "cmd.joint_rigid_group": "Groupe rigide", "cmd.joint_screw": "Vis", "cmd.joint_solve": "Résoudre les liaisons", + "cmd.joint_sweep": "Balayer une liaison", "cmd.library_apply": "Appliquer une entrée de la bibliothèque locale", "cmd.library_export": "Exporter la bibliothèque de la conception", "cmd.library_inspect": "Inspecter la bibliothèque locale", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 02c5e371d..ff55a1600 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -454,6 +454,7 @@ "cmd.joint_rigid_group": "リジッド グループ", "cmd.joint_screw": "ねじ", "cmd.joint_solve": "ジョイントを解決", + "cmd.joint_sweep": "ジョイントをスイープ", "cmd.library_apply": "ローカルライブラリ項目を適用", "cmd.library_export": "デザインライブラリを書き出す", "cmd.library_inspect": "ローカルライブラリを確認", diff --git a/assets/locales/ko.json b/assets/locales/ko.json index 21198a398..d1bb0d9a6 100644 --- a/assets/locales/ko.json +++ b/assets/locales/ko.json @@ -246,6 +246,7 @@ "cmd.joint_rigid_group": "강체 그룹", "cmd.joint_screw": "나사", "cmd.joint_solve": "관절 해석", + "cmd.joint_sweep": "관절 스윕", "cmd.library_apply": "로컬 라이브러리 항목 적용", "cmd.library_export": "설계 라이브러리 내보내기", "cmd.library_inspect": "로컬 라이브러리 확인", diff --git a/assets/locales/ru.json b/assets/locales/ru.json index 9cd04228a..894a42681 100644 --- a/assets/locales/ru.json +++ b/assets/locales/ru.json @@ -397,6 +397,7 @@ "cmd.joint_rigid_group": "Жёсткая группа", "cmd.joint_screw": "Винт", "cmd.joint_solve": "Решить сопряжения", + "cmd.joint_sweep": "Прогон сопряжения", "cmd.material_assign": "Физический материал", "cmd.material_create": "Новый физический материал", "cmd.material_delete": "Удалить физический материал", diff --git a/assets/locales/tr.json b/assets/locales/tr.json index f22c0478b..c6d91825a 100644 --- a/assets/locales/tr.json +++ b/assets/locales/tr.json @@ -407,6 +407,7 @@ "cmd.joint_origin": "Bağlantı orijini", "cmd.joint_rigid_group": "Rijit grup", "cmd.joint_solve": "Bağlantıları çöz", + "cmd.joint_sweep": "Bağlantıyı tara", "cmd.library_apply": "Yerel kitaplık girişini uygula", "cmd.library_export": "Tasarım kitaplığını dışa aktar", "cmd.library_inspect": "Yerel kitaplığı incele", diff --git a/assets/locales/uk.json b/assets/locales/uk.json index ad83c4703..da63577d1 100644 --- a/assets/locales/uk.json +++ b/assets/locales/uk.json @@ -441,6 +441,7 @@ "cmd.joint_rigid_group": "Жорстка група", "cmd.joint_screw": "Гвинт", "cmd.joint_solve": "Розв'язати з'єднання", + "cmd.joint_sweep": "Прогін з'єднання", "cmd.library_apply": "Застосувати елемент локальної бібліотеки", "cmd.library_export": "Експортувати бібліотеку проєкту", "cmd.library_inspect": "Перевірити локальну бібліотеку", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index f36707f37..1a4fd6a17 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -454,6 +454,7 @@ "cmd.joint_rigid_group": "刚性组", "cmd.joint_screw": "螺旋", "cmd.joint_solve": "解算接头", + "cmd.joint_sweep": "扫掠接头", "cmd.library_apply": "应用本地库条目", "cmd.library_export": "导出设计库", "cmd.library_inspect": "检查本地库", diff --git a/crates/engine/src/cmd/contact_sweep.rs b/crates/engine/src/cmd/contact_sweep.rs index 19a0e4cac..7004e9a7e 100644 --- a/crates/engine/src/cmd/contact_sweep.rs +++ b/crates/engine/src/cmd/contact_sweep.rs @@ -1,11 +1,12 @@ //! Bounded, chronological checks of a joint trajectory. This samples tessellated geometry; //! it is deliberately not advertised as exact continuous collision detection. -use std::collections::{BTreeSet, HashMap}; +use std::cell::Cell; +use std::collections::{BTreeMap, BTreeSet, HashMap}; use std::sync::Arc; use solidcraft_doc::joints; -use solidcraft_doc::{IDENTITY, Mat, apply_point, mat_mul}; -use solidcraft_geom::{Aabb3, Mesh, Vec3}; +use solidcraft_doc::{Document, IDENTITY, Mat, apply_point, mat_mul}; +use solidcraft_geom::{Aabb3, Bvh, Mesh, Vec3}; use crate::params::bad; use crate::{Result, Session}; @@ -20,11 +21,15 @@ fn limit(message: &str) -> crate::EngineError { bad("contact.sweep", message) } +#[derive(Clone)] struct CachedBody { path: Vec, offset: Mat, mesh: Arc, size: f64, + /// How far its mesh may stray from its faces: 0 when every face is flat (the mesh is the + /// shape), else the chord tolerance it was tessellated to. + chord: f64, } /// A member of a contact set: (occurrence id, name). @@ -56,7 +61,7 @@ impl ContactGeometry { return Ok(out); } let state = s.model.state(); - let mut meshes: HashMap> = HashMap::new(); + let mut meshes: HashMap, f64)> = HashMap::new(); let mut stack = vec![(0, Vec::::new())]; let mut count = 0; while let Some((component, path)) = stack.pop() { @@ -82,10 +87,11 @@ impl ContactGeometry { if out.bodies.len() >= MAX_BODIES { return Err(limit("too many bodies for a contact sweep")); } - let mesh = if let Some(mesh) = meshes.get(&body.name) { - mesh.clone() + let (mesh, chord) = if let Some(cached) = meshes.get(&body.name) { + cached.clone() } else { - let mesh = body.body.tessellate((body.body.size() * 1e-3).max(1e-3))?; + let tolerance = (body.body.size() * 1e-3).max(1e-3); + let mesh = body.body.tessellate(tolerance)?; if mesh.triangles.len() > MAX_TRIANGLES || mesh.positions.len().saturating_add(mesh.triangles.len().saturating_mul(4)) > 200_000 { return Err(limit("body exceeds contact sweep tessellation budget")); } @@ -118,14 +124,20 @@ impl ContactGeometry { } out.step = out.step.min(thickness * 0.25); let mesh = Arc::new(mesh); - meshes.insert(body.name.clone(), mesh.clone()); - mesh + // Flat faces tessellate exactly; only planes known from how the face was + // made count (an unknown face is taken as curved). + let faces = body.body.face_count(); + let flat = faces <= 1024 && (0..faces).all(|i| body.body.face_plane(i).is_some()); + let chord = if flat { 0.0 } else { tolerance }; + meshes.insert(body.name.clone(), (mesh.clone(), chord)); + (mesh, chord) }; out.bodies.push(CachedBody { path: path.clone(), offset: s.doc.model_body_offset(body).copied().unwrap_or(IDENTITY), mesh, size: body.body.size(), + chord, }); } } @@ -155,6 +167,14 @@ impl ContactGeometry { self.pairs.retain(|(_, _, a, b)| keep(a.0, b.0)); } + /// Move the pairs of set members `take` picks into a geometry of their own (with the same + /// bodies), leaving the rest here. + pub(super) fn take_pairs(&mut self, take: impl Fn(u64, u64) -> bool) -> ContactGeometry { + let (taken, kept) = std::mem::take(&mut self.pairs).into_iter().partition(|(_, _, a, b)| take(a.0, b.0)); + self.pairs = kept; + ContactGeometry { bodies: self.bodies.clone(), pairs: taken, step: self.step } + } + /// How many mesh points are placed for each check. pub(super) fn vertex_count(&self) -> usize { self.bodies.iter().map(|b| b.mesh.positions.len()).fold(0, usize::saturating_add) @@ -166,9 +186,13 @@ impl ContactGeometry { } fn frame(body: &CachedBody, s: &Session) -> Result { + Self::frame_in(body, &s.doc) + } + + fn frame_in(body: &CachedBody, doc: &Document) -> Result { let mut frame = IDENTITY; for id in &body.path { - let occurrence = s.doc.occurrences.iter().find(|o| o.id == *id).ok_or_else(|| limit("contact occurrence disappeared"))?; + let occurrence = doc.occurrences.iter().find(|o| o.id == *id).ok_or_else(|| limit("contact occurrence disappeared"))?; frame = mat_mul(&frame, &occurrence.transform); } Ok(mat_mul(&frame, &body.offset)) @@ -229,6 +253,18 @@ impl ContactGeometry { Ok(required as usize) } + /// Each body's mesh placed where `s` has it. + fn placed(&self, s: &Session) -> Result> { + self.bodies + .iter() + .map(|body| { + let frame = Self::frame(body, s)?; + let positions = body.mesh.positions.iter().map(|p| apply_point(&frame, *p)).collect(); + Ok(Mesh { positions, triangles: body.mesh.triangles.clone(), ..Mesh::default() }) + }) + .collect() + } + pub(super) fn first_hit(&self, s: &Session, work: &mut usize) -> Result> { Ok(self.hits(s, work, MAX_WORK, false)?.into_iter().next().map(|(a, b, depth)| (a.1, b.1, depth))) } @@ -240,15 +276,7 @@ impl ContactGeometry { let mut out: Vec<(Member, Member, f64)> = Vec::new(); // The member pairs found so far (lower id first). let mut found: BTreeSet<(u64, u64)> = BTreeSet::new(); - let meshes: Vec = self - .bodies - .iter() - .map(|body| { - let frame = Self::frame(body, s)?; - let positions = body.mesh.positions.iter().map(|p| apply_point(&frame, *p)).collect(); - Ok(Mesh { positions, triangles: body.mesh.triangles.clone(), ..Mesh::default() }) - }) - .collect::>()?; + let meshes = self.placed(s)?; // Each mesh's box once, not once per pair it is in. let boxes: Vec = meshes.iter().map(Mesh::bounds).collect(); for (a, b, oa, ob) in &self.pairs { @@ -293,6 +321,263 @@ impl ContactGeometry { } } +/// How near two set members come: the bodies under them nearest each other. +pub(super) struct Gap { + pub(super) a: Member, + pub(super) b: Member, + /// 0 where they touch or pass into each other. + pub(super) mm: f64, + /// The nearest points (world), on a's body and on b's. + pub(super) at: (Vec3, Vec3), +} + +impl ContactGeometry { + /// The gap between each pair of set members whose bodies come within `cutoff` of each + /// other in `s` (all pairs with an infinite cutoff), nearest first. Mesh distances: exact + /// for flat faces, within [`ContactGeometry::chord`] for curved ones. `work` adds up the + /// cost, refused past `budget`. + pub(super) fn gaps(&self, s: &Session, cutoff: f64, work: &mut usize, budget: usize) -> Result> { + let meshes = self.placed(s)?; + let tris: Vec> = meshes.iter().map(|m| m.triangles.iter().filter_map(|t| m.tri(t)).collect()).collect(); + let boxes: Vec = meshes.iter().map(Mesh::bounds).collect(); + let mut trees: Vec> = vec![None; meshes.len()]; + let mut nearest: BTreeMap<(u64, u64), Gap> = BTreeMap::new(); + for (a, b, oa, ob) in &self.pairs { + let key = (oa.0.min(ob.0), oa.0.max(ob.0)); + let limit = nearest.get(&key).map_or(cutoff, |g| g.mm.min(cutoff)); + let (Some(ta), Some(tb), Some(ba), Some(bb)) = (tris.get(*a), tris.get(*b), boxes.get(*a), boxes.get(*b)) else { + return Err(limit_error("invalid contact geometry pair")); + }; + if box_distance(ba, bb) > limit { + continue; + } + if trees.get(*b).is_some_and(Option::is_none) + && let Some(slot) = trees.get_mut(*b) + { + *work = work.saturating_add(tb.len()); + *slot = Some(Bvh::new(&tb.iter().map(tri_box).collect::>())); + } + let Some(Some(tree)) = trees.get(*b) else { return Err(limit_error("invalid contact geometry pair")) }; + let Some((mm, pa, pb)) = mesh_gap(ta, tb, tree, ba, bb, limit, work, budget)? else { continue }; + nearest.insert(key, Gap { a: oa.clone(), b: ob.clone(), mm, at: (pa, pb) }); + } + let mut out: Vec = nearest.into_values().collect(); + out.sort_by(|x, y| x.mm.total_cmp(&y.mm)); + Ok(out) + } + + /// The most the gaps can be off: the largest chord tolerance of a curved body (0 when every + /// body is flat-faced, and the mesh distances are exact). + pub(super) fn chord(&self) -> f64 { + self.bodies.iter().map(|b| b.chord).fold(0.0, f64::max) + } + + /// The size of the largest body (at least 1 mm): what tolerances scale with. + pub(super) fn scale(&self) -> f64 { + self.bodies.iter().map(|b| b.size).fold(1.0, f64::max) + } + + /// The furthest any point of the bodies moves between `from` and `to` (bounded by the + /// corners of each body's box, which a rigid move takes furthest). + pub(super) fn travel(&self, from: &Document, to: &Document) -> Result { + let mut most = 0.0_f64; + for body in &self.bodies { + let (fa, fb) = (Self::frame_in(body, from)?, Self::frame_in(body, to)?); + let local = body.mesh.bounds(); + for c in 0..8 { + let pick = |bit: usize, lo: f64, hi: f64| if c & bit == 0 { lo } else { hi }; + let corner = Vec3::new(pick(1, local.min.x, local.max.x), pick(2, local.min.y, local.max.y), pick(4, local.min.z, local.max.z)); + most = most.max(apply_point(&fa, corner).dist(apply_point(&fb, corner))); + } + } + Ok(most) + } +} + +fn limit_error(message: &str) -> crate::EngineError { + limit(message) +} + +fn tri_box(t: &[Vec3; 3]) -> Aabb3 { + let mut b = Aabb3::EMPTY; + for p in t { + b.add(*p); + } + b +} + +/// The distance between two boxes (0 where they overlap). +fn box_distance(a: &Aabb3, b: &Aabb3) -> f64 { + let axis = |a0: f64, a1: f64, b0: f64, b1: f64| (b0 - a1).max(a0 - b1).max(0.0); + let (x, y, z) = (axis(a.min.x, a.max.x, b.min.x, b.max.x), axis(a.min.y, a.max.y, b.min.y, b.max.y), axis(a.min.z, a.max.z, b.min.z, b.max.z)); + (x * x + y * y + z * z).sqrt() +} + +/// The gap between meshes `a` and `b` (their triangles; `tree` over b's) and their nearest +/// points, when within `limit` (None: farther). 0 where their surfaces cross, and where one +/// lies wholly inside the other. +#[allow(clippy::too_many_arguments)] +fn mesh_gap( + a: &[[Vec3; 3]], + b: &[[Vec3; 3]], + tree: &Bvh, + ba: &Aabb3, + bb: &Aabb3, + limit: f64, + work: &mut usize, + budget: usize, +) -> Result> { + let mut best: Option<(f64, Vec3, Vec3)> = None; + // An upper bound to prune with when there is no limit: a vertex of each near the other. + let mut bound = limit; + if !bound.is_finite() { + let centre = bb.center(); + let near = |list: &[[Vec3; 3]], to: Vec3| list.iter().map(|t| t[0]).min_by(|p, q| p.dist(to).total_cmp(&q.dist(to))); + if let Some(pa) = near(a, centre) + && let Some(pb) = near(b, pa) + { + *work = work.saturating_add(a.len() + b.len()); + bound = pa.dist(pb); + best = Some((bound, pa, pb)); + } + } + for ta in a { + let box_a = tri_box(ta); + if box_distance(&box_a, bb) > bound { + continue; + } + // Both callbacks read the bound the other tightens. + let (visits, shared) = (Cell::new(0usize), Cell::new(bound)); + tree.visit( + |node| { + visits.set(visits.get() + 1); + box_distance(node, &box_a) <= shared.get() + }, + |j| { + let Some(tb) = b.get(j as usize) else { return }; + visits.set(visits.get() + 8); + let (d, pa, pb) = tri_distance(ta, tb); + if d <= shared.get() && best.is_none_or(|(x, _, _)| d < x) { + shared.set(d); + best = Some((d, pa, pb)); + } + }, + ); + bound = shared.get(); + let visits = visits.get(); + *work = work.saturating_add(visits); + if *work > budget { + return Err(limit_error("gaps exceed the work budget; check fewer parts or leave out report_gaps")); + } + if bound <= 0.0 { + return Ok(best); + } + } + // Wholly inside, no surface crossing: a vertex of one inside the other. + let overlap = + ba.min.x <= bb.max.x && bb.min.x <= ba.max.x && ba.min.y <= bb.max.y && bb.min.y <= ba.max.y && ba.min.z <= bb.max.z && bb.min.z <= ba.max.z; + if overlap { + *work = work.saturating_add(a.len() + b.len()); + for (p, other) in [(a.first().map(|t| t[0]), b), (b.first().map(|t| t[0]), a)] { + if let Some(p) = p + && super::inside(p, other) + { + return Ok(Some((0.0, p, p))); + } + } + } + Ok(best.filter(|(d, _, _)| *d <= limit)) +} + +/// The distance between triangles `a` and `b`, with their nearest points (0 where they cross). +fn tri_distance(a: &[Vec3; 3], b: &[Vec3; 3]) -> (f64, Vec3, Vec3) { + for (x, y) in [(a, b), (b, a)] { + for i in 0..3 { + if let (Some(p), Some(q)) = (x.get(i), x.get((i + 1) % 3)) + && let Some(hit) = segment_hits_triangle(*p, *q, y) + { + return (0.0, hit, hit); + } + } + } + let mut best = (f64::INFINITY, a[0], b[0]); + let mut keep = |pa: Vec3, pb: Vec3| { + let d = pa.dist(pb); + if d < best.0 { + best = (d, pa, pb); + } + }; + for p in a { + keep(*p, super::closest(*p, b[0], b[1], b[2])); + } + for q in b { + keep(super::closest(*q, a[0], a[1], a[2]), *q); + } + for i in 0..3 { + for j in 0..3 { + let (pa, pb) = segment_closest(a[i], a[(i + 1) % 3], b[j], b[(j + 1) % 3]); + keep(pa, pb); + } + } + best +} + +/// Where segment pq passes through triangle t (None: it misses, or lies in its plane). +fn segment_hits_triangle(p: Vec3, q: Vec3, t: &[Vec3; 3]) -> Option { + let d = q - p; + let (e1, e2) = (t[1] - t[0], t[2] - t[0]); + let h = d.cross(e2); + let det = e1.dot(h); + // Parallel (or degenerate): the vertex and edge distances answer it. + if det.abs() < 1e-12 * e1.len().max(1e-300) * e2.len().max(1e-300) * d.len().max(1e-300) { + return None; + } + let f = 1.0 / det; + let sv = p - t[0]; + let u = f * sv.dot(h); + if !(0.0..=1.0).contains(&u) { + return None; + } + let qv = sv.cross(e1); + let v = f * d.dot(qv); + if v < 0.0 || u + v > 1.0 { + return None; + } + let along = f * e2.dot(qv); + (0.0..=1.0).contains(&along).then(|| p + d * along) +} + +/// The nearest points of segments p1q1 and p2q2. +fn segment_closest(p1: Vec3, q1: Vec3, p2: Vec3, q2: Vec3) -> (Vec3, Vec3) { + let (d1, d2, r) = (q1 - p1, q2 - p2, p1 - p2); + let (a, e, f) = (d1.dot(d1), d2.dot(d2), d2.dot(r)); + let eps = 1e-24; + let (s, t) = if a <= eps && e <= eps { + (0.0, 0.0) + } else if a <= eps { + (0.0, (f / e).clamp(0.0, 1.0)) + } else { + let c = d1.dot(r); + if e <= eps { + ((-c / a).clamp(0.0, 1.0), 0.0) + } else { + let b = d1.dot(d2); + let denom = a * e - b * b; + let mut s = if denom > eps * a * e { ((b * f - c * e) / denom).clamp(0.0, 1.0) } else { 0.0 }; + let mut t = (b * s + f) / e; + if t < 0.0 { + t = 0.0; + s = (-c / a).clamp(0.0, 1.0); + } else if t > 1.0 { + t = 1.0; + s = ((b - c) / a).clamp(0.0, 1.0); + } + (s, t) + } + }; + (p1 + d1 * s, p2 + d2 * t) +} + #[cfg(test)] #[path = "contact_sweep_tests.rs"] mod tests; diff --git a/crates/engine/src/cmd/joints_tests.rs b/crates/engine/src/cmd/joints_tests.rs index adf3df2fc..87a415b06 100644 --- a/crates/engine/src/cmd/joints_tests.rs +++ b/crates/engine/src/cmd/joints_tests.rs @@ -1453,6 +1453,10 @@ mod cam; #[path = "motion_analysis_tests.rs"] mod motion_analysis; +// Joints swept until parts touch: a door, the four-bar above and a Watt six-bar. +#[path = "motion_sweep_tests.rs"] +mod motion_sweep; + /// A pin through a hole of its own radius whose axis is a hair off the hole's (parts placed from /// rounded coordinates): the walls are all but tangent along two lines, which the boolean can't /// intersect. Each offset gets a checked answer: clear on the axis and within the kernel's diff --git a/crates/engine/src/cmd/motion.rs b/crates/engine/src/cmd/motion.rs index 9cb31e417..d84ccb75b 100644 --- a/crates/engine/src/cmd/motion.rs +++ b/crates/engine/src/cmd/motion.rs @@ -20,6 +20,8 @@ mod analysis; mod animation; #[path = "contact_sweep.rs"] mod contact_sweep; +#[path = "motion_sweep.rs"] +mod sweep; macro_rules! trace_doc { () => { @@ -79,6 +81,7 @@ pub static COMMANDS: &[CommandSpec] = &[ )), CommandSpec::new("motion.plot", "Plot Motion Study", analysis::plot).icon("graph").noundo().params(analysis::PLOT_DOC), CommandSpec::new("motion.interference", "Motion Interference", analysis::interference).icon("interference").noundo().params(analysis::INTERFERENCE_DOC), + CommandSpec::new("joint.sweep", "Sweep Joint", sweep::sweep).icon("interference").params(sweep::SWEEP_DOC), CommandSpec::new("motion.list", "List Motion Studies", list_studies).icon("list").noundo(), CommandSpec::new("motion.delete", "Delete Motion Study", delete_study).icon("delete").params("study"), CommandSpec::new("explode.create", "Exploded View", explode_create).at("SOLID", "ASSEMBLE").icon("explode").params( diff --git a/crates/engine/src/cmd/motion_analysis.rs b/crates/engine/src/cmd/motion_analysis.rs index d842d9c9c..ab3c51d3f 100644 --- a/crates/engine/src/cmd/motion_analysis.rs +++ b/crates/engine/src/cmd/motion_analysis.rs @@ -310,10 +310,10 @@ fn ranges(m: &MotionStudy, samples: &[usize], n: usize) -> Vec<[f64; 2]> { out.into_iter().map(|(a, b)| [step_of(m, a, n), step_of(m, b, n)]).collect() } -pub(super) fn interference(s: &mut Session, p: &Value) -> Result { - 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)?; +/// The pairs of parts a check looks at, as `motion.interference` and `joint.sweep` take them: +/// `occurrences` against each other (or each only `against` others), the design's contact sets +/// with `contact_sets`, else every occurrence. +pub(super) fn checked_pairs(s: &Session, p: &Value, cmd: &str) -> Result { let everything = || vec![s.doc.occurrences.iter().map(|o| o.id).collect::>()]; // Each of `occurrences` only against these. let against = match p.get("against") { @@ -354,6 +354,14 @@ pub(super) fn interference(s: &mut Session, p: &Value) -> Result { let a = occurrences(s, p, cmd)?; geometry.keep_pairs(|x, y| (a.contains(&x) && b.contains(&y)) || (a.contains(&y) && b.contains(&x))); } + Ok(geometry) +} + +pub(super) fn interference(s: &mut Session, p: &Value) -> Result { + 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 stop = play(s, &m, n, false, |t, k| { diff --git a/crates/engine/src/cmd/motion_sweep.rs b/crates/engine/src/cmd/motion_sweep.rs new file mode 100644 index 000000000..faca1f5c8 --- /dev/null +++ b/crates/engine/src/cmd/motion_sweep.rs @@ -0,0 +1,261 @@ +//! Sweeping a joint until something touches: `joint.sweep` drives one joint value from `from` +//! toward `to` on a copy of the design (closed loops following on their branch), measures the +//! gaps between parts at each sample and bisects the first contact down to `refine`, so a hinge, +//! door or linkage answers how far it opens, what stops it and how much room each part has. + +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Arc; + +use serde_json::{Value, json}; +use solidcraft_doc::Document; +use solidcraft_geom::Vec3; + +use super::analysis::checked_pairs; +use super::contact_sweep::{ContactGeometry, Gap}; +use super::{drive_with_contact, joint_id, value}; +use crate::params::{bad, bool_}; +use crate::{Result, Session}; + +pub const SWEEP_DOC: &str = "joint: id|name; from, to: its value the sweep runs between (degrees for angles, mm for distances, \ + or expressions); index? (which value, default 0); step? (between samples, in the joint's unit; default: fine enough that \ + no part passes through another between two); refine?: mm (the first contact is bisected until no part moves more than \ + this between the last clear value and the touching one; default 0.01); occurrences?: [ids or names] (checked against \ + each other; default every occurrence), with against?: [ids or names] (the parts that stay: each of `occurrences` only \ + against these), or contact_sets?: true (the pairs of the design's contact sets); report_gaps?: bool (the nearest gap at \ + every sample, default false); apply?: bool (leave the design where the sweep stopped; default false: the design is not \ + changed) → stopped_at (the last value clear of contact, or where a loop or limit stopped it; null: it reached `to`), \ + stopped_by: {a, b, at: [x,y,z] (where they touch, world)} | \"loop\" | \"limit\" | null, samples: [{value, min_gap_mm?, \ + pair?}], min_gap? (report_gaps: {part: {mm, at_value, to}}, the nearest each part came to another), unit, gap_method \ + (\"mesh\": distances between the tessellations), gap_tolerance_mm (how far those can be off: 0 when every face is flat), \ + pairs (checked), touching_at_start: [[a, b]] (pairs already touching at `from`, such as parts joined face to face or a door \ + on its frame: these stop it only once they pass into each other deeper than they start), applied. The parts are tested at the samples and through the bisection; the motion is on a copy (closed loops \ + follow, contact sets do not stop it)"; + +/// Most samples a sweep takes before its bisection: each is a solve. +const MAX_SAMPLES: usize = 4096; +/// Most bisection steps: each halves the bracket around the first contact. +const MAX_BISECTIONS: usize = 64; +/// Most gap work over a whole sweep (see `ContactGeometry::gaps`). +const MAX_WORK: usize = 500_000_000; + +/// The nearest a part came to another along the sweep. +struct Nearest { + mm: f64, + at: f64, + to: String, +} + +pub(super) fn sweep(s: &mut Session, p: &Value) -> Result { + let cmd = "joint.sweep"; + let id = joint_id(s, p.get("joint"), cmd)?; + let joint = s.doc.assembly.joints.iter().find(|j| j.id == id).ok_or_else(|| bad(cmd, "joint"))?; + let (kind, name) = (joint.kind, joint.name.clone()); + let dofs = kind.dofs().len(); + if dofs == 0 { + return Err(bad(cmd, "a rigid joint does not move")); + } + let index = match p.get("index") { + None | Some(Value::Null) => 0, + Some(v) => v + .as_u64() + .and_then(|i| usize::try_from(i).ok()) + .filter(|i| *i < dofs) + .ok_or_else(|| bad(cmd, format!("`index` must be below {dofs}, the joint's value count")))?, + }; + let angle = kind.is_angle(index); + // Shown in degrees for angles, mm for distances. + let shown = |v: f64| if angle { v.to_degrees() } else { v }; + let end = |key: &str| match p.get(key) { + Some(v) => value(s, v, angle, cmd), + None => Err(bad(cmd, format!("give `from` and `to`: the joint's values the sweep runs between (no `{key}`)"))), + }; + let (from, to) = (end("from")?, end("to")?); + let positive = |key: &str, max: f64| -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => v + .as_f64() + .filter(|x| x.is_finite() && *x > 0.0 && *x <= max) + .map(Some) + .ok_or_else(|| bad(cmd, format!("`{key}` must be a number above 0, at most {max}"))), + } + }; + let refine = positive("refine", 1e3)?.unwrap_or(0.01); + let step = positive("step", 1e9)?.map(|x| if angle { x.to_radians() } else { x }); + let report_gaps = bool_(p, "report_gaps").unwrap_or(false); + let apply = bool_(p, "apply").unwrap_or(false); + + let mut geometry = checked_pairs(s, p, cmd)?; + if !geometry.has_pairs() { + return Err(bad(cmd, "no pairs of parts to check: list two or more `occurrences` with bodies, or give `against`")); + } + // On a copy, played from where the parts are placed; contact sets do not stop it. + let mut t = s.scratch(); + t.pending_moves.clear(); + t.doc_mut().assembly.contact_enabled = false; + let given = BTreeSet::from([(id, index)]); + let drive_to = |t: &mut Session, v: f64| -> Result { + let mut q = t.doc.assembly.joints.iter().find(|j| j.id == id).map(|j| j.values.clone()).unwrap_or_default(); + q.resize(q.len().max(dofs), 0.0); + if let Some(x) = q.get_mut(index) { + *x = v; + } + Ok(drive_with_contact(t, &[(id, q)], &given)?.0) + }; + let reached = |t: &Session| t.doc.assembly.joints.iter().find(|j| j.id == id).and_then(|j| j.values.get(index).copied()).unwrap_or(0.0); + + let r = drive_to(&mut t, from)?; + if r["stopped_by_loop"].is_object() { + return Err(bad(cmd, "the joint cannot reach `from`: a closed loop it is in does not close there")); + } + if (reached(&t) - from).abs() > 1e-9 { + return Err(bad(cmd, "`from` is outside the joint's limits")); + } + let scale = geometry.scale(); + // Nearer than this is touching (well below any `refine`). + let touch = 1e-6 * scale; + let mut work = 0usize; + let key = |x: u64, y: u64| (x.min(y), x.max(y)); + // Pairs touching where the sweep starts (parts joined face to face, a door on its frame) + // stop it only when they pass into each other, deeper than they start (by more than their + // meshes can be off): a door resting on its frame cannot sweep through it. + let start: Vec = geometry.gaps(&t, touch, &mut work, MAX_WORK)?; + let touching: BTreeSet<(u64, u64)> = start.iter().map(|g| key(g.a.0, g.b.0)).collect(); + let touching_names: Vec = start.iter().map(|g| json!([g.a.1, g.b.1])).collect(); + let resting = geometry.take_pairs(|x, y| touching.contains(&key(x, y))); + let rest_depth: BTreeMap<(u64, u64), f64> = if resting.has_pairs() { + resting.hits(&t, &mut work, MAX_WORK, true)?.into_iter().map(|(a, b, d)| (key(a.0, b.0), d)).collect() + } else { + BTreeMap::new() + }; + let margin = touch.max(2.0 * resting.chord()); + + // The samples run to where the joint gets: a limit or a loop can stop it short of `to`, and + // the default count is for the motion up to there. One more drive toward `to` then finds + // what stops it. + let (n, sample_to) = match step { + Some(h) => { + let n = ((to - from).abs() / h).ceil(); + if !n.is_finite() || n > MAX_SAMPLES as f64 { + return Err(bad(cmd, format!("`step` makes more than {MAX_SAMPLES} samples: take a larger step"))); + } + (n as usize, to) + } + None => { + let mut end = t.scratch(); + drive_to(&mut end, to)?; + let n = geometry.samples(&t, &end).map_err(|e| match e { + crate::EngineError::BadParams { msg, .. } => bad(cmd, format!("{msg} (or give a `step`)")), + e => e, + })?; + let got = reached(&end); + (n, if (got - to).abs() > 1e-9 && got.is_finite() { got } else { to }) + } + }; + let n = n.max(1); + let targets: Vec = + (1..=n).map(|k| from + (sample_to - from) * k as f64 / n as f64).chain(((sample_to - to).abs() > 1e-9).then_some(to)).collect(); + + let mut samples: Vec = Vec::new(); + let mut nearest: BTreeMap = BTreeMap::new(); + let mut record = |t: &Session, v: f64, work: &mut usize, geometry: &ContactGeometry| -> Result<()> { + if !report_gaps { + samples.push(json!({"value": shown(v)})); + return Ok(()); + } + let gaps = geometry.gaps(t, f64::INFINITY, work, MAX_WORK)?; + match gaps.first() { + Some(g) => samples.push(json!({"value": shown(v), "min_gap_mm": g.mm, "pair": [g.a.1, g.b.1]})), + None => samples.push(json!({"value": shown(v), "min_gap_mm": null, "pair": null})), + } + for g in &gaps { + for (me, other) in [(&g.a.1, &g.b.1), (&g.b.1, &g.a.1)] { + if nearest.get(me).is_none_or(|x| g.mm < x.mm) { + nearest.insert(me.clone(), Nearest { mm: g.mm, at: shown(v), to: other.clone() }); + } + } + } + Ok(()) + }; + let contact = |t: &Session, work: &mut usize, geometry: &ContactGeometry| -> Result> { + if let Some(g) = geometry.gaps(t, touch, work, MAX_WORK)?.into_iter().next() { + return Ok(Some(g)); + } + if !resting.has_pairs() { + return Ok(None); + } + let deeper = + resting.hits(t, work, MAX_WORK, true)?.into_iter().find(|(a, b, d)| *d > rest_depth.get(&key(a.0, b.0)).copied().unwrap_or(0.0) + margin); + let Some((a, b, _)) = deeper else { return Ok(None) }; + // Where: the nearest points of that pair (passing into each other, at no gap). + let k = key(a.0, b.0); + let at = resting.gaps(t, touch, work, MAX_WORK)?.into_iter().find(|g| key(g.a.0, g.b.0) == k).map_or((Vec3::ZERO, Vec3::ZERO), |g| g.at); + Ok(Some(Gap { a, b, mm: 0.0, at })) + }; + + record(&t, from, &mut work, &geometry)?; + let (mut lo_doc, mut lo_v): (Arc, f64) = (t.doc.clone(), from); + let mut stop: Option<(f64, Value)> = None; + for target in targets { + let r = drive_to(&mut t, target)?; + let v = reached(&t); + if let Some(mut hit) = contact(&t, &mut work, &geometry)? { + // Halve the bracket from the last clear value until no part moves more than + // `refine` across it; each try is driven from the clear side, so loops keep their branch. + let (mut hi_doc, mut hi_v) = (t.doc.clone(), v); + for _ in 0..MAX_BISECTIONS { + if geometry.travel(&lo_doc, &hi_doc)? <= refine { + break; + } + let mid = (lo_v + hi_v) / 2.0; + t.doc = lo_doc.clone(); + drive_to(&mut t, mid)?; + match contact(&t, &mut work, &geometry)? { + Some(h) => (hi_doc, hi_v, hit) = (t.doc.clone(), mid, h), + None => (lo_doc, lo_v) = (t.doc.clone(), mid), + } + } + t.doc = lo_doc.clone(); + let at = (hit.at.0 + hit.at.1) * 0.5; + stop = Some((lo_v, json!({"a": hit.a.1, "b": hit.b.1, "at": [at.x, at.y, at.z]}))); + break; + } + // (The drive on toward `to` past a limit stays where the last sample was.) + if (v - lo_v).abs() > 1e-12 { + record(&t, v, &mut work, &geometry)?; + } + if r["stopped_by_loop"].is_object() { + stop = Some((v, json!("loop"))); + break; + } + if (v - target).abs() > 1e-9 { + stop = Some((v, json!("limit"))); + break; + } + (lo_doc, lo_v) = (t.doc.clone(), v); + } + + let applied = apply && !Arc::ptr_eq(&t.doc, &s.doc); + if applied { + let mut doc = (*t.doc).clone(); + doc.assembly.contact_enabled = s.doc.assembly.contact_enabled; + *s.doc_mut() = doc; + } + let mut out = json!({ + "joint": id, "name": name, "index": index, "unit": if angle { "deg" } else { "mm" }, + "from": shown(from), "to": shown(to), + "stopped_at": stop.as_ref().map(|(v, _)| shown(*v)), + "stopped_by": stop.map(|(_, by)| by), + "samples": samples, + "refine_mm": refine, + "gap_method": "mesh", "gap_tolerance_mm": geometry.chord(), + "pairs": geometry.pair_count() + resting.pair_count(), + "touching_at_start": touching_names, + "applied": applied, + }); + if report_gaps { + out["min_gap"] = + nearest.into_iter().map(|(k, g)| (k, json!({"mm": g.mm, "at_value": g.at, "to": g.to}))).collect::>().into(); + } + Ok(out) +} diff --git a/crates/engine/src/cmd/motion_sweep_tests.rs b/crates/engine/src/cmd/motion_sweep_tests.rs new file mode 100644 index 000000000..d5e767d7d --- /dev/null +++ b/crates/engine/src/cmd/motion_sweep_tests.rs @@ -0,0 +1,307 @@ +//! `joint.sweep` against stops worked out by hand: a door swinging into a block, the four-bar's +//! rocker meeting a stop and a Watt six-bar's output link meeting one, each checked against the +//! linkage solved with circle intersections and a separating-axis test of the parts' outlines. + +use serde_json::{Value, json}; +use solidcraft_geom::Vec3; + +use super::{four_bar, meet, occ, part, pin, run}; +use crate::Session; + +/// A part made of one box (`size` from `corner`) in a new component. +fn block(s: &mut Session, name: &str, corner: [f64; 3], size: [f64; 3]) { + run(s, "component.activate", json!({"component": "root"})); + run(s, "component.create", json!({"name": name})); + run(s, "solid.box", json!({"length": size[0], "width": size[1], "height": size[2], "corner": corner})); +} + +/// A 100 × 4 × 50 door hinged about Z at the origin, and a 20 × 20 block from (60, 30) in its +/// way. +fn door() -> Session { + let mut s = Session::default(); + block(&mut s, "Door", [0.0, 0.0, 0.0], [100.0, 4.0, 50.0]); + block(&mut s, "Block", [60.0, 30.0, 0.0], [20.0, 20.0, 50.0]); + let r = run( + &mut s, + "joint.create", + json!({"type": "revolute", "a": {"occurrence": 0, "point": [0, 0, 0]}, "b": {"occurrence": "Door", "point": [0, 0, 0]}, "flip": true, "name": "Hinge"}), + ); + assert_eq!(r["conflicts"].as_array().map(Vec::len), Some(0), "{r}"); + s +} + +fn num(v: &Value) -> f64 { + v.as_f64().unwrap_or(f64::NAN) +} + +fn hinge(s: &Session) -> f64 { + s.doc.assembly.joints.iter().find(|j| j.name == "Hinge").and_then(|j| j.values.first().copied()).unwrap_or(f64::NAN) +} + +/// The door's face 4 mm off its hinge line meets a corner of the block at polar (r, φ) when +/// r·sin(φ − θ) = 4, so at θ = φ − asin(4 / r); the corner (80, 30) is the first. +#[test] +fn a_door_swings_until_it_meets_the_block() { + let mut s = door(); + let corner = |x: f64, y: f64| y.atan2(x) - (4.0 / x.hypot(y)).asin(); + let expected = + [(60.0, 30.0), (80.0, 30.0), (60.0, 50.0), (80.0, 50.0)].iter().map(|(x, y)| corner(*x, *y)).fold(f64::INFINITY, f64::min).to_degrees(); + let before = s.doc.clone(); + let r = run(&mut s, "joint.sweep", json!({"joint": "Hinge", "from": 0, "to": 90, "report_gaps": true})); + assert_eq!(*s.doc, *before, "a sweep leaves the design as it was"); + assert_eq!(r["applied"], false); + let at = num(&r["stopped_at"]); + assert!((at - expected).abs() < 0.01 && at <= expected + 1e-9, "stopped at {at}°, the block is met at {expected}°: {r}"); + let by = &r["stopped_by"]; + let names = [by["a"].as_str(), by["b"].as_str()]; + assert!(names.contains(&Some("Door:1")) && names.contains(&Some("Block:1")), "{by}"); + let touch = Vec3::new(num(&by["at"][0]), num(&by["at"][1]), num(&by["at"][2])); + assert!((touch.x - 80.0).abs() < 0.05 && (touch.y - 30.0).abs() < 0.05 && (0.0..=50.0).contains(&touch.z), "{touch:?}"); + // Flat faces: the gaps are the boxes' own. + assert_eq!((r["gap_method"].as_str(), num(&r["gap_tolerance_mm"])), (Some("mesh"), 0.0)); + let samples = r["samples"].as_array().cloned().unwrap_or_default(); + assert!(samples.len() > 2, "{r}"); + assert!((num(&samples[0]["min_gap_mm"]) - 26.0).abs() < 1e-9, "the door starts 26 mm below the block: {}", samples[0]); + for w in samples.windows(2) { + assert!(num(&w[1]["min_gap_mm"]) < num(&w[0]["min_gap_mm"]) && num(&w[1]["value"]) > num(&w[0]["value"]), "{w:?}"); + } + let nearest = &r["min_gap"]["Door:1"]; + assert!(nearest["to"] == "Block:1" && num(&nearest["mm"]) < 2.0 && num(&nearest["at_value"]) < expected, "{}", r["min_gap"]); + // Kept where it stopped on request. + let r = run(&mut s, "joint.sweep", json!({"joint": "Hinge", "from": 0, "to": 90, "refine": 0.001, "apply": true})); + assert_eq!(r["applied"], true); + assert!((hinge(&s).to_degrees() - expected).abs() < 0.002, "{}° wants {expected}°", hinge(&s).to_degrees()); + run(&mut s, "contact.create", json!({"occurrences": ["Door", "Block"]})); + let r = run(&mut s, "contact.check", json!({})); + assert!(r["collisions"].as_array().is_some_and(Vec::is_empty), "kept clear of the block: {r}"); +} + +/// Swung the other way, nothing is in the way; a limit stops it, and a sweep starting there +/// does not move. +#[test] +fn a_door_swings_free_until_its_limit() { + let mut s = door(); + let r = run(&mut s, "joint.sweep", json!({"joint": "Hinge", "from": 0, "to": -90, "step": 5})); + assert!(r["stopped_at"].is_null() && r["stopped_by"].is_null(), "{r}"); + assert_eq!(r["samples"].as_array().map(Vec::len), Some(19), "{r}"); + run(&mut s, "joint.limits", json!({"joint": "Hinge", "min": -30, "max": 10})); + let r = run(&mut s, "joint.sweep", json!({"joint": "Hinge", "from": 0, "to": -90})); + assert_eq!((r["stopped_by"].as_str(), num(&r["stopped_at"]).round()), (Some("limit"), -30.0), "{r}"); + assert!(s.execute("joint.sweep", &json!({"joint": "Hinge", "from": 20, "to": 0})).is_err(), "`from` is past the limit"); +} + +/// Parts already touching where the sweep starts (a door resting on its frame) do not stop it +/// while they move apart, but they do once they pass into each other: the door cannot sweep +/// through its frame. +#[test] +fn parts_touching_at_the_start_stop_it_only_passing_into_each_other() { + let mut s = door(); + block(&mut s, "Frame", [0.0, -10.0, 0.0], [100.0, 10.0, 50.0]); + let r = run(&mut s, "joint.sweep", json!({"joint": "Hinge", "from": 0, "to": 90})); + let touching = r["touching_at_start"].as_array().cloned().unwrap_or_default(); + assert_eq!(touching.len(), 1, "{r}"); + let by = &r["stopped_by"]; + assert!(by.is_object() && [&by["a"], &by["b"]].contains(&&json!("Block:1")), "the block still stops it: {r}"); + // Swung open, away from the frame: nothing stops it. + let only = json!({"joint": "Hinge", "from": 0, "to": 90, "occurrences": ["Door"], "against": ["Frame"]}); + let r = run(&mut s, "joint.sweep", only); + assert!(r["stopped_by"].is_null() && r["touching_at_start"].as_array().map(Vec::len) == Some(1), "{r}"); + // Swung into the frame: it stops where it starts. + let into = json!({"joint": "Hinge", "from": 0, "to": -90, "occurrences": ["Door"], "against": ["Frame"]}); + let r = run(&mut s, "joint.sweep", into); + let by = &r["stopped_by"]; + assert!(by.is_object() && [&by["a"], &by["b"]].contains(&&json!("Frame:1")), "{r}"); + assert!(num(&r["stopped_at"]).abs() < 0.01, "{r}"); +} + +/// A limit stops the door well short of `to`: the samples are still as fine as the motion up to +/// the limit needs, so a thin plate just inside the limit is met, not stepped over. +#[test] +fn a_thin_part_just_inside_a_limit_is_met() { + let mut s = Session::default(); + block(&mut s, "Door", [0.0, 0.0, 0.0], [100.0, 1.0, 50.0]); + block(&mut s, "Plate", [80.0, -32.0, 0.0], [0.5, 6.0, 50.0]); + run( + &mut s, + "joint.create", + json!({"type": "revolute", "a": {"occurrence": 0, "point": [0, 0, 0]}, "b": {"occurrence": "Door", "point": [0, 0, 0]}, "flip": true, "name": "Hinge"}), + ); + run(&mut s, "joint.limits", json!({"joint": "Hinge", "min": -30, "max": 10})); + // The door's face through the hinge meets the plate's far upper corner (80.5, -26). + let expected = (-26.0f64).atan2(80.5).to_degrees(); + let r = run(&mut s, "joint.sweep", json!({"joint": "Hinge", "from": 0, "to": -1800})); + let by = &r["stopped_by"]; + assert!(by.is_object() && [&by["a"], &by["b"]].contains(&&json!("Plate:1")), "the plate stops it, not the limit: {r}"); + let at = num(&r["stopped_at"]); + assert!((at - expected).abs() < 0.01 && at >= expected - 1e-9, "stopped at {at}°, the plate is met at {expected}°: {r}"); + // The samples are as fine as the motion up to the limit needs (spread over `to`, they were + // sixty times coarser). + let values: Vec = r["samples"].as_array().unwrap().iter().map(|v| num(&v["value"])).collect(); + assert!(values.len() > 100, "{r}"); + for w in values.windows(2) { + assert!((w[1] - w[0]).abs() < 0.5, "samples {}° apart: {r}", (w[1] - w[0]).abs()); + } +} + +#[test] +fn a_sweep_refuses_what_it_cannot_do() { + let mut s = door(); + for p in [ + json!({"joint": "Hinge", "to": 90}), + json!({"joint": "Hinge", "from": 0}), + json!({"joint": "Nope", "from": 0, "to": 90}), + json!({"joint": "Hinge", "from": 0, "to": 90, "index": 3}), + json!({"joint": "Hinge", "from": 0, "to": 90, "refine": 0}), + json!({"joint": "Hinge", "from": 0, "to": 90, "refine": -1}), + json!({"joint": "Hinge", "from": 0, "to": 90, "step": 0}), + json!({"joint": "Hinge", "from": 0, "to": 1e8, "step": 1e-6}), + json!({"joint": "Hinge", "from": "nan", "to": 90}), + json!({"joint": "Hinge", "from": 0, "to": 90, "occurrences": ["Door"]}), + json!({"joint": "Hinge", "from": 0, "to": 90, "against": ["Block"]}), + ] { + assert!(s.execute("joint.sweep", &p).is_err(), "{p}"); + } + run(&mut s, "joint.as_built", json!({"type": "rigid", "a": "Block", "b": "Door", "name": "Lock"})); + assert!(s.execute("joint.sweep", &json!({"joint": "Lock", "from": 0, "to": 1})).is_err(), "a rigid joint does not move"); +} + +/// A point turned about `c` by `a` radians in the XY plane. +fn turn(p: Vec3, c: Vec3, a: f64) -> Vec3 { + let (sin, cos) = a.sin_cos(); + let d = p - c; + Vec3::new(c.x + d.x * cos - d.y * sin, c.y + d.x * sin + d.y * cos, p.z) +} + +/// The XY outline of a 2 × 2 part box from `corner`, turned about `c` by `a`. +fn outline(corner: Vec3, size: f64, c: Vec3, a: f64) -> [Vec3; 4] { + [(0.0, 0.0), (size, 0.0), (size, size), (0.0, size)].map(|(x, y)| turn(corner + Vec3::new(x, y, 0.0), c, a)) +} + +/// Whether two convex outlines overlap (no edge normal of either separates them). +fn overlap(a: &[Vec3; 4], b: &[Vec3; 4]) -> bool { + for poly in [a, b] { + for i in 0..4 { + let e = poly[(i + 1) % 4] - poly[i]; + let n = Vec3::new(-e.y, e.x, 0.0); + let span = |p: &[Vec3; 4]| p.iter().map(|q| q.dot(n)).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), x| (lo.min(x), hi.max(x))); + let ((a0, a1), (b0, b1)) = (span(a), span(b)); + if a1 <= b0 || b1 <= a0 { + return false; + } + } + } + true +} + +/// The crank value (degrees, 0…`hi`) where `clear` first fails, bisected to 1e-9°. +fn first_contact(hi: f64, clear: impl Fn(f64) -> bool) -> f64 { + let (mut lo, mut hi) = (0.0, hi); + assert!(clear(lo) && !clear(hi), "the stop must lie between 0° and {hi}°"); + while hi - lo > 1e-9 { + let mid = (lo + hi) / 2.0; + if clear(mid) { lo = mid } else { hi = mid } + } + lo +} + +/// A part box 3 mm square about `c` (in XY), deep enough for the linkage's boxes (z −5…−3). +fn stop_at(s: &mut Session, c: Vec3) { + block(s, "Stop", [c.x - 1.5, c.y - 1.5, -6.0], [3.0, 3.0, 4.0]); + let id = occ(s, "Stop"); + run(s, "occurrence.ground", json!({"occurrence": id, "grounded": true})); +} + +const O4: Vec3 = Vec3::new(45.0, 0.0, 0.0); + +/// The four-bar's crank driven to `v`°, followed a quarter degree at a time from where it was +/// assembled: the crank pin and the rocker pin. +fn four_bar_at(v: f64, q0: Vec3) -> (Vec3, Vec3) { + let n = ((v.abs() * 4.0).ceil() as usize).max(1); + let (mut p, mut q) = (Vec3::new(0.0, 20.0, 0.0), q0); + for k in 1..=n { + let th = (90.0 + v * k as f64 / n as f64).to_radians(); + p = Vec3::new(20.0 * th.cos(), 20.0 * th.sin(), 0.0); + let [m1, m2] = meet(p, 50.0, O4, 40.0); + q = if m1.dist(q) <= m2.dist(q) { m1 } else { m2 }; + } + (p, q) +} + +fn angle(d: Vec3) -> f64 { + d.y.atan2(d.x) +} + +/// The four-bar's rocker swings into a stop: the crank stops where the rocker's box first +/// overlaps it. +#[test] +fn a_four_bar_rocker_meets_a_stop() { + let (mut s, _, q0) = four_bar(); + let rocker = |v: f64| angle(four_bar_at(v, q0).1 - O4) - angle(q0 - O4); + let corner = Vec3::new(q0.x, q0.y, 0.0); + let centre = turn(corner + Vec3::new(1.0, 1.0, 0.0), O4, rocker(60.0)); + stop_at(&mut s, centre); + let stop = [(-1.5, -1.5), (1.5, -1.5), (1.5, 1.5), (-1.5, 1.5)].map(|(x, y)| centre + Vec3::new(x, y, 0.0)); + let expected = first_contact(60.0, |v| !overlap(&outline(corner, 2.0, O4, rocker(v)), &stop)); + let r = + run(&mut s, "joint.sweep", json!({"joint": "Crank", "from": 0, "to": 90, "refine": 0.001, "occurrences": ["Rocker"], "against": ["Stop"]})); + let at = num(&r["stopped_at"]); + assert!((at - expected).abs() < 0.01, "stopped at {at}°, the rocker meets the stop at {expected}°: {r}"); + let names = [r["stopped_by"]["a"].as_str(), r["stopped_by"]["b"].as_str()]; + assert!(names.contains(&Some("Rocker:1")) && names.contains(&Some("Stop:1")), "{r}"); + assert_eq!(r["pairs"], 1); +} + +/// Driving the four-bar's rocker past its toggle stops where the loop can no longer close +/// (|Q| = 30: about 139.2° from the ground line). +#[test] +fn a_four_bar_sweep_stops_where_its_loop_cannot_close() { + let (mut s, _, q0) = four_bar(); + let limit = ((900.0f64 - 3625.0) / 3600.0).acos().to_degrees() - q0.y.atan2(q0.x - 45.0).to_degrees(); + let r = run(&mut s, "joint.sweep", json!({"joint": "Rocker", "from": 0, "to": 100, "occurrences": ["Rocker"], "against": ["Ground"]})); + assert_eq!(r["stopped_by"].as_str(), Some("loop"), "{r}"); + let at = num(&r["stopped_at"]); + assert!(at > limit - 1.0 && at <= limit + 1e-6, "stopped at {at}°, the loop closes up to {limit}°"); +} + +/// A Watt six-bar: the four-bar above, its rocker a ternary link carrying a pin R0 = Q0 + 15 x, +/// and a second loop R–S–O6 (link 40, output 35, O6 = (90, 0)). The output link's box swings +/// into a stop. +#[test] +fn a_watt_six_bar_output_meets_a_stop() { + let (mut s, _, q0) = four_bar(); + let o6 = Vec3::new(90.0, 0.0, 0.0); + let r0 = q0 + Vec3::new(15.0, 0.0, 0.0); + let [s0, _] = meet(r0, 40.0, o6, 35.0); + for (name, c) in [("Link", (r0 + s0) * 0.5), ("Output", s0)] { + part(&mut s, name, [c.x, c.y, -5.0]); + } + pin(&mut s, "revolute", "Rocker arm", "Rocker", "Link", r0, Vec3::Z); + pin(&mut s, "revolute", "Output pin", "Link", "Output", s0, Vec3::Z); + pin(&mut s, "revolute", "Output", "Ground", "Output", o6, Vec3::Z); + // The output's turn with the crank at `v`°, both loops followed a quarter degree at a time. + let output = |v: f64| { + let n = ((v.abs() * 4.0).ceil() as usize).max(1); + let mut sp = s0; + for k in 1..=n { + let (_, q) = four_bar_at(v * k as f64 / n as f64, q0); + let r = turn(r0, O4, angle(q - O4) - angle(q0 - O4)); + let [m1, m2] = meet(r, 40.0, o6, 35.0); + sp = if m1.dist(sp) <= m2.dist(sp) { m1 } else { m2 }; + } + angle(sp - o6) - angle(s0 - o6) + }; + // Where the solver puts the output at 30° is where the circles say. + let check = run(&mut s.scratch(), "joint.drive", json!({"joint": "Crank", "value": 30})); + assert!(check["stopped_by_loop"].is_null(), "{check}"); + let corner = Vec3::new(s0.x, s0.y, 0.0); + let centre = turn(corner + Vec3::new(1.0, 1.0, 0.0), o6, output(60.0)); + stop_at(&mut s, centre); + let stop = [(-1.5, -1.5), (1.5, -1.5), (1.5, 1.5), (-1.5, 1.5)].map(|(x, y)| centre + Vec3::new(x, y, 0.0)); + let expected = first_contact(60.0, |v| !overlap(&outline(corner, 2.0, o6, output(v)), &stop)); + let r = + run(&mut s, "joint.sweep", json!({"joint": "Crank", "from": 0, "to": 90, "refine": 0.001, "occurrences": ["Output"], "against": ["Stop"]})); + let at = num(&r["stopped_at"]); + assert!((at - expected).abs() < 0.01, "stopped at {at}°, the output meets the stop at {expected}°: {r}"); + let names = [r["stopped_by"]["a"].as_str(), r["stopped_by"]["b"].as_str()]; + assert!(names.contains(&Some("Output:1")) && names.contains(&Some("Stop:1")), "{r}"); +} diff --git a/docs/book/src/guide/assemblies.md b/docs/book/src/guide/assemblies.md index 033451123..39862cff8 100644 --- a/docs/book/src/guide/assemblies.md +++ b/docs/book/src/guide/assemblies.md @@ -240,6 +240,19 @@ sets tell them apart: an occurrence inside a sub-assembly placed twice is one pa copies are not checked against each other. A check takes at most 256 bodies; on a large design, list the `occurrences` to check (an arm, with `against` the parts it must miss). When the work runs out it says `truncated` and the step it `checked_to`. +`joint.sweep {joint, from, to, index?, step?, refine?, occurrences?, against?, contact_sets?, +report_gaps?, apply?}` drives one joint value from `from` toward `to` and answers how far it gets +before parts touch: `stopped_at` (the last value clear of contact), `stopped_by` (the two parts +and the point `at` which they touch, or `"loop"` where a closed loop can no longer close, or +`"limit"`), and with `report_gaps` the nearest gap at every sample and the nearest each part came +to another (`min_gap`). The samples are fine enough that no part passes through another between +two (or `step` apart), and the first contact is bisected until no part moves more than `refine` +(0.01 mm by default) across it. Gaps are distances between the parts' tessellations +(`gap_method: "mesh"`): exact for flat faces, within `gap_tolerance_mm` for curved ones. Pairs +already touching at `from`, such as parts joined face to face or a door resting on its frame, are +listed in `touching_at_start` and stop the sweep only once they pass into each other, deeper than +they start. The sweep runs on a copy (closed loops follow, contact sets don't stop it) and +leaves the design as it was unless `apply` is true. **Insert Design** (`component.insert_design {path, translate?}`, on the **ASSEMBLE** panel and in the **File** menu) adds a component linked to another saved design, so each part can live in diff --git a/skills/solidcraft-mechanisms/SKILL.md b/skills/solidcraft-mechanisms/SKILL.md index a2e3616b4..7f6d7639a 100644 --- a/skills/solidcraft-mechanisms/SKILL.md +++ b/skills/solidcraft-mechanisms/SKILL.md @@ -59,6 +59,7 @@ Written against SolidCraft `main` after 0.11.1, which counts the degrees of free - **Trace:** `motion.trace {"occurrence":..., "point":[x,y,z], "joint":..., "from":0, "to":360}` (or `"study":...` instead of joint, from and to) answers the world path of a point of a part, such as a coupler curve, without changing the design. It ends at `stopped_at` where a loop or contact stops the motion. `motion.trace.keep` with the same params keeps it as a 3D sketch spline. - **Plot:** `motion.plot {"study":..., "joints":[...], "duration":seconds}` answers each joint value's `value`, `velocity` and `acceleration` per sample (finite differences; per step, or per second with a duration), and with `"occurrence"` and `"point"` a point's `position`, `velocity`, `acceleration`, `speed`. Check a follower's rate against the analytic one this way, without changing the design. - **Collisions:** `motion.interference {"study":..., "occurrences":[...], "against":[...]}` plays the study (contact sets don't stop it) and lists each colliding pair with `first_step` and `steps` ranges; `clear: true` when none. It takes at most 256 bodies: on a big design list the moving part as `occurrences` and what it must miss as `against`. Parts joined at a knuckle often overlap by design and show up at every step. +- **Sweep until contact:** `joint.sweep {"joint":..., "from":0, "to":120, "against":[...], "report_gaps":true}` answers how far a hinge, door or linkage opens: `stopped_at` (last clear value, bisected to `refine` mm, default 0.01), `stopped_by` `{a, b, at}` (or `"loop"`, `"limit"`), per-sample `min_gap_mm` and the nearest each part came (`min_gap`). It runs on a copy; `"apply":true` leaves the design at the stop. Pairs touching at `from` (`touching_at_start`) stop it only once they pass into each other. ## Verify - **Each joint:** `execute occurrence.properties {"occurrence":"Wing:1"}` (under 1 KB) gives the world bbox and centre of mass of one occurrence. Joining must not move them. From 473f1e65167402c4ed1df50164c8b583af990bba Mon Sep 17 00:00:00 2001 From: NOWN-DEV <257771410+NOWN-DEV@users.noreply.github.com> Date: Mon, 19 Oct 2026 22:08:01 +0200 Subject: [PATCH 084/225] Sheet metal: readable face names from the sheet itself (#2275) Sheet metal faces get readable names (#2272). --- crates/doc/src/name_lookup.rs | 40 ++++++ crates/doc/src/sheet.rs | 3 + crates/doc/src/sheet_face_names.rs | 131 ++++++++++++++++++ crates/engine/src/cmd/inspect.rs | 11 +- crates/engine/src/cmd/sheet.rs | 4 + .../engine/src/cmd/sheet_face_names_tests.rs | 114 +++++++++++++++ docs/book/src/guide/sheet-metal.md | 9 ++ 7 files changed, 311 insertions(+), 1 deletion(-) create mode 100644 crates/doc/src/sheet_face_names.rs create mode 100644 crates/engine/src/cmd/sheet_face_names_tests.rs diff --git a/crates/doc/src/name_lookup.rs b/crates/doc/src/name_lookup.rs index 2b2465301..72da5f138 100644 --- a/crates/doc/src/name_lookup.rs +++ b/crates/doc/src/name_lookup.rs @@ -260,6 +260,9 @@ impl EdgeHit { /// answering to it (merged into it, or the named piece told apart by the faces around it); else /// the piece of it nearest `p` (`split`). pub fn locate_face(st: &ModelState, name: &str, p: Vec3) -> Option { + if crate::sheet::split_sheet_face_name(name).is_some() { + return sheet_locate(st, name, p); + } // Every body's names are read below: work out the ones not known yet on all cores first // (each body's names are its own, whichever thread works them out). if legacy_name(name).is_none() { @@ -278,6 +281,9 @@ pub fn locate_face(st: &ModelState, name: &str, p: Vec3) -> Option { /// face), or on this body it names a piece of a split face or a merged one. The same face on /// another body (a copy of this one) is not a piece of this body's face. pub(crate) fn locate_face_on_body(st: &ModelState, body: Option<&str>, name: &str, p: Vec3) -> Option { + if crate::sheet::split_sheet_face_name(name).is_some() { + return sheet_locate(st, name, p); + } if legacy_name(name).is_none() && let Some(i) = body.and_then(|n| st.bodies.iter().position(|b| b.name == n)) && let Some(b) = st.bodies.get(i).filter(|b| !b.body.is_mesh()) @@ -290,6 +296,30 @@ pub(crate) fn locate_face_on_body(st: &ModelState, body: Option<&str>, name: &st locate_face(st, name, p) } +/// [`locate_face`] for a sheet face's readable name (`sheet:::`, see +/// [`crate::sheet::body_sheet_face_names`]): the face of that body the sheet names so, else the +/// piece of it nearest `p` (`split`). The sheet itself says which face it is, so the name holds +/// however the faces of the body are numbered. +fn sheet_locate(st: &ModelState, name: &str, p: Vec3) -> Option { + let (body, _) = crate::sheet::split_sheet_face_name(name)?; + let (bi, b) = st.bodies.iter().enumerate().find(|(_, b)| b.name == body && !b.body.is_mesh())?; + let names = crate::sheet::body_sheet_face_names(st, b); + let faces: Vec = names.iter().enumerate().filter(|(_, n)| n.as_deref() == Some(name)).map(|(i, _)| i).collect(); + let m = b.mesh(); + let (distance, face, point) = + faces.iter().filter_map(|f| nearest_on_face(&m, *f, p).map(|(d, q)| (d, *f, q))).min_by(|a, c| a.0.total_cmp(&c.0))?; + Some(FaceHit { + body: bi, + face, + point, + split: faces.len() > 1, + merged: false, + verified: true, + on_point: distance <= (b.body.size() * 1e-3).max(1e-3), + legacy: false, + }) +} + /// [`locate_face`] among `bodies` (with their indices). fn locate_in<'a>(bodies: impl Iterator, name: &str, p: Vec3) -> Option { if let Some(old) = legacy_name(name) { @@ -401,6 +431,16 @@ pub fn locate_one(st: &ModelState, body: Option<&str>, name: &str) -> Result = st.bodies.iter().enumerate().filter(|(_, b)| !b.body.is_mesh() && body.is_none_or(|n| b.name == n)).collect(); // As [`locate_face`]: the names of several bodies are worked out on all cores first. diff --git a/crates/doc/src/sheet.rs b/crates/doc/src/sheet.rs index f209d20f8..22b4ca0d0 100644 --- a/crates/doc/src/sheet.rs +++ b/crates/doc/src/sheet.rs @@ -18,8 +18,11 @@ use crate::{DocError, Document, IDENTITY, Mat, Result, apply_point, apply_vector #[path = "sheet_convert.rs"] mod convert; +#[path = "sheet_face_names.rs"] +mod face_names; pub use convert::{bend_edge_names, convert_body}; pub(crate) use convert::{outline_loop, round_wall}; +pub use face_names::body_sheet_face_names; // Bound the aggregate geometry, including sampled curves and intermediate clipping pieces. // These are work limits, never geometry truncation: a larger input returns a useful error. diff --git a/crates/doc/src/sheet_face_names.rs b/crates/doc/src/sheet_face_names.rs new file mode 100644 index 000000000..3e37736f5 --- /dev/null +++ b/crates/doc/src/sheet_face_names.rs @@ -0,0 +1,131 @@ +//! Readable names of a sheet metal body's faces, from the sheet itself: `:top`, +//! `:bottom` and `:rim.` (the names sketches on sheet faces keep, see +//! [`SheetBody::panel_face_at`]); a bend's curved faces, `:bend.inner` and +//! `:bend.outer`; and where a flange's panel runs on past its bend's ends (toward a +//! neighbouring flange), the rim along the bend there, `:rim.ext0` and `rim.ext1`. A panel is `base` or a flange's tag (`F.`), so the names +//! say what each face is and stay with it when sizes change or other flanges come and go. + +use solidcraft_geom::{Vec2, Vec3}; + +use super::SheetBody; +use crate::{ModelBody, ModelState, apply_point, mat_inverse}; + +/// The share of a face's sample points that must agree on a name for the face to take it. +const AGREE: f64 = 0.8; + +impl SheetBody { + /// The readable name of the face of this sheet a point lies on (sheet coordinates, within + /// `tol`, kept below a quarter of the thickness): a flat face's (see + /// [`panel_face_at`](Self::panel_face_at)), else a bend's inner or outer face. + pub fn face_name_at(&self, p: Vec3, tol: f64) -> Option { + self.panel_face_at(p, tol).map(|(name, _)| name).or_else(|| self.bend_face_at(p, tol)).or_else(|| self.ext_rim_at(p, tol)) + } + + /// The rim of a flange's panel along its bend line, where the panel runs on past the + /// bend's start (`:rim.ext0`) or end (`rim.ext1`). + fn ext_rim_at(&self, p: Vec3, tol: f64) -> Option { + if self.flat { + return None; + } + let tol = tol.min(self.t * 0.25); + for (pi, region) in self.panels() { + let Some(i) = pi else { continue }; + let Some(f) = self.flanges.get(i) else { continue }; + let Some(inverse) = mat_inverse(&self.world(pi)) else { continue }; + let q = apply_point(&inverse, p); + if q.z < -tol || q.z > self.t + tol { + continue; + } + let q2 = Vec2::new(q.x, q.y); + let pts = region.outer.ccw().polyline(1e-3); + let m = pts.len(); + for k in 0..m { + let (Some(&a), Some(&b)) = (pts.get(k), pts.get((k + 1) % m)) else { continue }; + let d = b - a; + if d.len2() < 1e-18 || self.rim_edge(pi, a, b, k).as_deref() != Some("bend") { + continue; + } + let along = (q2 - a).dot(d) / d.len2(); + if !(-1e-9..=1.0 + 1e-9).contains(&along) || ((a + d * along) - q2).len() > tol { + continue; + } + let end = if (q2 - f.p).dot(f.d) < f.len / 2.0 { "ext0" } else { "ext1" }; + return Some(format!("{}:rim.{end}", self.panel_name(pi))); + } + } + None + } + + /// The curved face of a bend a point lies on: `:bend.inner` (the bend's radius) or + /// `:bend.outer` (the radius plus the thickness). + fn bend_face_at(&self, p: Vec3, tol: f64) -> Option { + if self.flat { + return None; + } + let tol = tol.min(self.t * 0.25); + for (i, f) in self.flanges.iter().enumerate() { + let Some((world, o, d, start, toward)) = self.bend_frame(f) else { continue }; + let Some(inverse) = mat_inverse(&world) else { continue }; + let q = apply_point(&inverse, p) - o; + let u = q.dot(d); + let (u0, u1) = self.zone_span(f); + if u < u0 - tol || u > u1 + tol { + continue; + } + let radial = q - d * u; + let rho = radial.len(); + let side = if (rho - f.radius).abs() <= tol { + "inner" + } else if (rho - f.radius - self.t).abs() <= tol { + "outer" + } else { + continue; + }; + let phi = radial.dot(toward).atan2(radial.dot(start)); + if phi < -1e-6 || phi > f.angle.abs() + 1e-6 { + continue; + } + return Some(format!("{}:bend.{side}", self.panel_name(Some(i)))); + } + None + } +} + +/// The readable sheet names of a body's faces (by B-rep face index), as +/// [`sheet_face_name`](super::sheet_face_name)s: `sheet:::`. `None` for a face +/// the sheet does not name (a hole's wall, a pocket's floor) and for every face of a body that is +/// no folded sheet of `st`. +pub fn body_sheet_face_names(st: &ModelState, b: &ModelBody) -> Vec> { + let m = b.mesh(); + let nf = m.tri_face.iter().map(|f| *f as usize + 1).max().unwrap_or(0); + let Some(sheet) = st.sheets.iter().find(|s| s.body == b.name && !s.flat) else { return vec![None; nf] }; + // Triangle centres lie inside a face, off a curved one by its facets' sag: a fifth of the + // thickness takes them and still tells a flat face from the rim beside it. + let tol = sheet.t * 0.2; + let mut votes: Vec> = vec![Vec::new(); nf]; + let mut total = vec![0usize; nf]; + for (t, f) in m.triangles.iter().zip(&m.tri_face) { + let (Some(v), Some(n), Some([a, b2, c])) = (votes.get_mut(*f as usize), total.get_mut(*f as usize), m.tri(t)) else { continue }; + // At most a few dozen points a face: enough to tell its name, cheap on a fine mesh. + if *n >= 48 { + continue; + } + *n += 1; + if let Some(name) = sheet.face_name_at((a + b2 + c) * (1.0 / 3.0), tol) { + match v.iter_mut().find(|(x, _)| *x == name) { + Some(x) => x.1 += 1, + None => v.push((name, 1)), + } + } + } + votes + .into_iter() + .zip(total) + .map(|(v, n)| { + v.into_iter() + .max_by_key(|x| x.1) + .filter(|(_, k)| *k as f64 >= AGREE * n.max(1) as f64) + .map(|(name, _)| super::sheet_face_name(&b.name, &name)) + }) + .collect() +} diff --git a/crates/engine/src/cmd/inspect.rs b/crates/engine/src/cmd/inspect.rs index 6b02a84a6..fc82f8864 100644 --- a/crates/engine/src/cmd/inspect.rs +++ b/crates/engine/src/cmd/inspect.rs @@ -19,7 +19,9 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("model.edges", "List Edges", model_edges).icon("inspect").noundo().params("body: name"), CommandSpec::new("model.faces", "List Faces", model_faces).icon("inspect").noundo().params( "body: name → per face: index, name (what face.delete, sheet.convert `face`, solid.shell … take in place of a point), exact, area, centroid (not always on the face), \ - plane_normal, point (a point on the face that picks it), cylinder? ({origin, axis, radius} of a cylindrical face)", + plane_normal, point (a point on the face that picks it), cylinder? ({origin, axis, radius} of a cylindrical face), \ + sheet_face? (a folded sheet's face: `sheet:::`, panel base or a flange's tag F., side top | bottom | rim. | bend.inner | bend.outer; \ + taken wherever a face name is, and it holds while sizes change and flanges come and go)", ), CommandSpec::new("model.threads", "List Threads", model_threads).icon("inspect").noundo(), CommandSpec::new("material.assign", "Physical Material", physical_material) @@ -291,6 +293,10 @@ fn model_faces(s: &mut Session, p: &Value) -> Result { let names = solidcraft_doc::naming::face_names(b); let tol = (b.body.size() * 2e-3).max(1e-3); let spots = solidcraft_doc::naming::face_spots(b); + // A folded sheet's faces also have the readable names its sheet gives them, worked out in + // the body's own coordinates. + let model = s.model.state(); + let sheet_names = model.body(&b.name).map(|own| solidcraft_doc::sheet::body_sheet_face_names(&model, own)).unwrap_or_default(); let faces: Vec = b .body .faces(tol)? @@ -299,6 +305,9 @@ fn model_faces(s: &mut Session, p: &Value) -> Result { let spot = spots.get(f.index).copied().flatten(); let mut v = json!({"index": f.index, "name": names.get(f.index), "exact": solidcraft_doc::naming::face_name_exact(b, f.index), "area": f.area, "centroid": f.centroid, "plane_normal": f.plane_normal, "point": spot.map(|x| x.point)}); + if let (Some(Some(name)), Some(o)) = (sheet_names.get(f.index), v.as_object_mut()) { + o.insert("sheet_face".into(), json!(name)); + } if let (Some(solidcraft_kernel::FaceSurface::Cylinder { origin, axis, radius }), Some(o)) = (spot.and_then(|x| x.surface), v.as_object_mut()) { diff --git a/crates/engine/src/cmd/sheet.rs b/crates/engine/src/cmd/sheet.rs index 423a5bd96..68c56c3ec 100644 --- a/crates/engine/src/cmd/sheet.rs +++ b/crates/engine/src/cmd/sheet.rs @@ -904,3 +904,7 @@ mod convert_tests; #[cfg(test)] #[path = "sheet_dxf_tests.rs"] mod dxf_tests; + +#[cfg(test)] +#[path = "sheet_face_names_tests.rs"] +mod face_names_tests; diff --git a/crates/engine/src/cmd/sheet_face_names_tests.rs b/crates/engine/src/cmd/sheet_face_names_tests.rs new file mode 100644 index 000000000..6c5d656f3 --- /dev/null +++ b/crates/engine/src/cmd/sheet_face_names_tests.rs @@ -0,0 +1,114 @@ +use serde_json::{Value, json}; +use solidcraft_geom::Vec3; + +use crate::Session; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + match s.execute(id, &p) { + Ok(v) => v, + Err(e) => panic!("{id} {p}: {e}"), + } +} + +/// A tray: a base `w` x 200 (its width a sketch dimension: the parameter returned), 1 mm thick +/// with 1 mm bends, front and back flanges 30 high in one feature, left and right in another, +/// and a 6.6 mm hole in the base: the two flange features' ids. +fn tray(s: &mut Session, w: f64) -> (String, u64, u64) { + run(s, "sheet.manage_rules", json!({"name": "R1", "thickness": "1 mm", "bend_radius": "1 mm", "active": true})); + run(s, "sketch.create", json!({"plane": "XY", "name": "Base"})); + run(s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [w, 200]})); + let d = run(s, "sketch.dimension", json!({"entities": ["l1"], "value": w})); + run(s, "sketch.finish", json!({})); + run(s, "sheet.flange", json!({"sketch": "Base"})); + run(s, "sheet.flange", json!({"edges": [[100, 0, 1], [100, 200, 1]], "height": 30})); + let front_back = s.doc.features.last().map_or(0, |f| f.id); + run(s, "sheet.flange", json!({"edges": [[0, 100, 1], [w, 100, 1]], "height": 30})); + let sides = s.doc.features.last().map_or(0, |f| f.id); + run(s, "solid.hole", json!({"position": [100, 100, 1], "diameter": 6.6})); + let param = d["param"].as_str().or_else(|| d["name"].as_str()).map(str::to_string).unwrap_or_else(|| "d1".into()); + (param, front_back, sides) +} + +/// Each face's readable sheet name, with its centroid and cylinder radius. +fn faces(s: &mut Session) -> Vec<(Option, Vec3, Option)> { + let body = s.model.state().bodies.first().map(|b| b.name.clone()).unwrap_or_default(); + let r = run(s, "model.faces", json!({"body": body})); + r["faces"] + .as_array() + .into_iter() + .flatten() + .map(|f| { + let c = &f["centroid"]; + let at = Vec3::new(c[0].as_f64().unwrap_or(f64::NAN), c[1].as_f64().unwrap_or(f64::NAN), c[2].as_f64().unwrap_or(f64::NAN)); + (f["sheet_face"].as_str().map(str::to_string), at, f["cylinder"]["radius"].as_f64()) + }) + .collect() +} + +fn named<'a>(faces: &'a [(Option, Vec3, Option)], name: &str) -> Vec<&'a (Option, Vec3, Option)> { + faces.iter().filter(|f| f.0.as_deref() == Some(name)).collect() +} + +/// The point on the face with this name, as a command taking a face name finds it. +fn point(s: &Session, name: &str) -> Vec3 { + solidcraft_doc::naming::named_face_point(&s.model.state(), None, name).unwrap_or_else(|e| panic!("{name}: {e}")) +} + +#[test] +fn a_trays_faces_have_readable_sheet_names_that_follow_its_size() { + let mut s = Session::default(); + let (width, fb, sd) = tray(&mut s, 320.0); + let all = faces(&mut s); + // Every face but the hole's wall (two halves) has a sheet name, and no two faces share one. + let unnamed: Vec<_> = all.iter().filter(|f| f.0.is_none()).collect(); + assert!(unnamed.len() == 2 && unnamed.iter().all(|f| f.2.is_some_and(|r| (r - 3.3).abs() < 1e-6)), "only the hole's wall: {unnamed:?}"); + let mut names: Vec<&str> = all.iter().filter_map(|f| f.0.as_deref()).collect(); + names.sort_unstable(); + let n = names.len(); + names.dedup(); + assert_eq!(names.len(), n, "{names:?}"); + for (name, at) in [ + ("sheet:Body1:base:top".to_string(), Vec3::new(160.0, 100.0, 1.0)), + ("sheet:Body1:base:bottom".to_string(), Vec3::new(160.0, 100.0, 0.0)), + (format!("sheet:Body1:F{sd}.1:top"), Vec3::new(319.0, 100.0, 16.0)), + (format!("sheet:Body1:F{sd}.1:bottom"), Vec3::new(320.0, 100.0, 16.0)), + (format!("sheet:Body1:F{sd}.1:rim.far"), Vec3::new(319.5, 100.0, 30.0)), + (format!("sheet:Body1:F{fb}.0:bottom"), Vec3::new(160.0, 0.0, 16.0)), + // The front flange runs on past its bend to the right one, under its corner. + (format!("sheet:Body1:F{fb}.0:rim.ext1"), Vec3::new(319.0, 0.5, 2.0)), + ] { + let f = named(&all, &name); + assert!(f.len() == 1 && f[0].1.dist(at) < 2.5, "{name}: {f:?}"); + } + // A bend's two curved faces: its radius and the radius plus the thickness. + let radius = |name: &str| named(&all, name).first().and_then(|f| f.2); + assert_eq!(radius(&format!("sheet:Body1:F{fb}.0:bend.inner")).map(|r| (r * 1e6).round() / 1e6), Some(1.0)); + assert_eq!(radius(&format!("sheet:Body1:F{fb}.0:bend.outer")).map(|r| (r * 1e6).round() / 1e6), Some(2.0)); + // 80 mm wider: the same names, each on the same face where it now is. + let right = point(&s, &format!("sheet:Body1:F{sd}.1:top")); + assert!((right.x - 319.0).abs() < 1e-3, "{right:?}"); + run(&mut s, "parameters.change", json!({"name": width, "expression": "400"})); + let wider = faces(&mut s); + let mut again: Vec<&str> = wider.iter().filter_map(|f| f.0.as_deref()).collect(); + again.sort_unstable(); + assert_eq!(again, names); + let right = point(&s, &format!("sheet:Body1:F{sd}.1:top")); + assert!((right.x - 399.0).abs() < 1e-3, "{right:?}"); + let far = point(&s, &format!("sheet:Body1:F{fb}.1:rim.far")); + assert!((far.y - 199.5).abs() < 1e-3 && (far.z - 30.0).abs() < 1e-3, "{far:?}"); +} + +#[test] +fn a_flanges_sheet_names_hold_when_another_flange_goes() { + let mut s = Session::default(); + let (_, fb, sd) = tray(&mut s, 320.0); + let right = format!("sheet:Body1:F{sd}.1:top"); + let before = point(&s, &right); + run(&mut s, "timeline.suppress", json!({"feature": fb, "suppressed": true})); + let after = point(&s, &right); + assert!((after.x - 319.0).abs() < 1e-3 && (after.z - before.z).abs() < 16.0, "{before:?} {after:?}"); + // The names of the flanges that went are gone; asking for one says so. + let gone = format!("sheet:Body1:F{fb}.0:top"); + assert!(solidcraft_doc::naming::named_face_point(&s.model.state(), None, &gone).is_err()); + assert!(solidcraft_doc::naming::named_face_point(&s.model.state(), Some("Body2"), &right).is_err()); +} diff --git a/docs/book/src/guide/sheet-metal.md b/docs/book/src/guide/sheet-metal.md index b3ad5f805..25f9c800d 100644 --- a/docs/book/src/guide/sheet-metal.md +++ b/docs/book/src/guide/sheet-metal.md @@ -312,3 +312,12 @@ flat pattern and its DXF have it, and on the bottom face y runs the other way, a below. When the face is gone (its flange is suppressed or deleted) the sketch reports a lost attachment instead of moving to another face; **Redefine Sketch Plane** attaches it to another face. `fixed: true` still freezes the picked plane in space. + +Every face of a folded sheet has a name of that kind, which `model.faces` lists as `sheet_face`: +`:top` and `:bottom`, `:rim.` for a rim (a base sketch line's id, or a +flange's `far`, `side0`, `side1`; `rim.bend0`/`rim.bend1` for a bend's flat ends and +`rim.ext0`/`rim.ext1` where a flange runs on past its bend toward a neighbour), and +`:bend.inner` / `:bend.outer` for a bend's curved faces. A command that takes a +face name takes it too (`sheet:Body1:F3.1:top`), and finds the face from the sheet itself, so the +name stays with that face while the sheet's sizes change and other flanges come and go. Faces the +sheet does not describe (a hole's wall) have none. From e1268c6ad965344ac3785e5665e466987e2c4ed0 Mon Sep 17 00:00:00 2001 From: Colin Faulkingham Date: Mon, 19 Oct 2026 15:08:06 -0500 Subject: [PATCH 085/225] Fix fillets around tiny rounded-rectangle end edges (#2506) Fillets around tiny rounded-rectangle end edges now build (#2498). --- ROADMAP.md | 2 +- crates/kernel/src/blend.rs | 5 +++- crates/kernel/src/tests.rs | 47 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 52 insertions(+), 2 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index fc02e7f62..b4fc0c9c0 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -52,7 +52,7 @@ PCB / Package, Render, Animation, Simulation, Manufacture/CAM, Drawings. | M0 | Vertical slice | done | — | | M1 | Sketch depth: command coverage implemented — projection/intersect/include as linked geometry (auto-project on faces, lost-reference warnings, break link), full SKETCH create/modify set (slots, polygons, tangent arcs/circles, ellipse, fit/control splines, conic, text, trim/extend/break, fillet/chamfer, offset, mirror, patterns, move/scale, blend curve, centerline), constraints incl. curvature and polygon with over-constraint refusal, driven/arc-length/linear-diameter dimensions, AutoConstrain, DXF/SVG insert, 3D sketch curves (Project To Surface, Intersection Curve, Isoparametric Curve, Spun Profile), exact free-form profiles (B-spline/NURBS edges, any spline degree, curves cut by crossings), sweeps and pipes along 3D sketch curves, canvases and decals, curvature combs. Exact free-form Extend and certified associative offsets now preserve geometry and IDs through edits, deletion and reopen. Occurrence-frame 3D wires now store explicit coordinate spaces and retain points and analytic fits through moves, refresh, undo and reopen. Constructive sketch solving (Owen 1991, Fudos & Hoffmann 1997) ahead of the numerical solver: points and rigid clusters are placed on the branch the sketch had, so dimension edits and drags keep their solution; edits that would turn a sketch over are refused; drags re-solve only the sketch per frame. Remaining workflow repairs: mixed offset junctions, legacy natural-spline seams, and damaged legacy wire links lacking frame provenance | in progress | 4 | | M2 | Robust modelling: coplanar booleans in the kernel, holes (placed on faces and on sketch points), threads (cosmetic, then modelled), patterns, mirror, shell, draft, split, construction geometry | in progress | 16 | -| M3 | General fillets and chamfers (curved edges, chains, vertex blends); saddle rolling-ball surfaces now use continuous seam sections and arc-length fitting with shared contact boundaries and bounded accuracy checks | in progress | 30 | +| M3 | General fillets and chamfers (curved edges, chains, vertex blends); saddle rolling-ball surfaces now use continuous seam sections and arc-length fitting with shared contact boundaries and bounded accuracy checks; tiny rim edges remain selected instead of nearby wall seams when filleting (#2498) | in progress | 30 | | M4 | Files: STEP import (done — [docs/step-import.md](docs/step-import.md)), FreeCAD/Rhino solids through cadmpeg (done, desktop and CLI), 3MF export and 3MF/STL import as mesh bodies (done), 3MF with B-rep face tags ([docs/formats/3mf-face-tags.md](docs/formats/3mf-face-tags.md), done), constant-section parametric mesh reconstruction, DXF sketches, OBJ import | in progress | 6 | | M5 | Persistent naming of faces and edges (docs/book/src/dev/naming.md): faces named from their exact kernel-reported history (sketch curve sides, caps, revolve sections, primitive sides, blends, shell inner walls, pattern/mirror copies; split pieces told apart by the faces around them, lumps of a cut body named after their faces), edges by their faces; fillets/chamfers, sketches on faces, shell/draft/offset/replace faces, hole placements, joint origins and face appearances resolve by name first and warn when the entity split or vanished: done. sheet metal edges by base sketch line and flange side, shell inner faces, sweep and loft roles: done. kernel-reported face history: done (merged faces answer to every name; operations without history yet fall back to geometric names, flagged unverified; format 14 keeps older designs' geometric names). Left: history through sheet metal, plastic, surface and emboss features; FaceSource certificates through history | in progress | 20 | | M6 | UI depth: selection feedback and origin (done), timeline editing (done: hover and selection highlight modifier faces, including fillets and chamfers; edit feature, history marker drag, dependency-checked single and multi-item reorder, suppress, rename, delete with dependents, re-resolved references; redefining selections refreshes persistent edge/face references while retaining feature identity and dimension names; optional compact named left feature history with rollback bar, multi-selection and persistent folders above the parts browser), right-docked dialogs (done), live previews for every feature dialog (done), keyboard-first commands with on-canvas value boxes and sketch inline dimensions (done), drag manipulators with automatic join/cut (done: extrude incl. two sides, fillet, shell, hole depth, move, pattern spacing, revolve rotator, extrude taper), dark theme (done), right-click menu with Repeat (done), measure tool (done), section analysis (done), selection filter (done), drag-solve of sketch points (done); appearance controls now preserve body/face/component targeting, named transparent looks, reuse/search and override removal; preferences | in progress | 6 | diff --git a/crates/kernel/src/blend.rs b/crates/kernel/src/blend.rs index 7df495144..484a95e28 100644 --- a/crates/kernel/src/blend.rs +++ b/crates/kernel/src/blend.rs @@ -1756,6 +1756,9 @@ fn loop_split(cur: &Body, pts: &[Vec3]) -> Result>, Vec = solid .face_iter() .filter(|f| matches!(f.oriented_surface(), mt::Surface::Plane(_))) @@ -1769,7 +1772,7 @@ fn loop_split(cur: &Body, pts: &[Vec3]) -> Result>, Vec size * 0.05 + 1e-3 { return Ok(None); } - let near: Vec<&mt::Edge> = dists.iter().filter(|x| x.1 <= best + tol).filter_map(|x| all.get(x.0)).collect(); + let near: Vec<&mt::Edge> = dists.iter().filter(|x| x.1 <= best + tie_tol).filter_map(|x| all.get(x.0)).collect(); let Some(e) = near.iter().find(|e| planar_edge.contains(&e.id())).or(near.first()) else { return Ok(None) }; per.push((*p, e.id())); } diff --git a/crates/kernel/src/tests.rs b/crates/kernel/src/tests.rs index 6b3e321f6..69840f9da 100644 --- a/crates/kernel/src/tests.rs +++ b/crates/kernel/src/tests.rs @@ -1976,6 +1976,53 @@ fn fillet_smooth_arc_and_line_loop_keeps_exact_removal() { assert!(rel(removed, want) < 1e-3, "{removed} vs {want}"); } +#[test] +fn fillet_rounded_rectangle_with_tiny_end_edges() { + // #2498: the 4.29 mm corners leave 0.02 mm straight edges on an 8.6 mm end. + let (w, h, r, height) = (26.4, 8.6, 4.29, 8.4); + let p = |x, y| Vec2::new(10.0 + x, 10.0 + y); + let outline = Loop2 { + segs: vec![ + Seg2::Line { a: p(r, 0.0), b: p(w - r, 0.0) }, + Seg2::Arc { center: p(w - r, r), radius: r, start: -PI / 2.0, sweep: PI / 2.0 }, + Seg2::Line { a: p(w, r), b: p(w, h - r) }, + Seg2::Arc { center: p(w - r, h - r), radius: r, start: 0.0, sweep: PI / 2.0 }, + Seg2::Line { a: p(w - r, h), b: p(r, h) }, + Seg2::Arc { center: p(r, h - r), radius: r, start: PI / 2.0, sweep: PI / 2.0 }, + Seg2::Line { a: p(0.0, h - r), b: p(0.0, r) }, + Seg2::Arc { center: p(r, r), radius: r, start: PI, sweep: PI / 2.0 }, + ], + }; + let body = extrude(&Plane::XY, &[Region2 { outer: outline, holes: vec![] }], 0.0, height).unwrap().pop().unwrap(); + let picks = [ + Vec3::new(23.2, 10.0, 8.4), + Vec3::new(35.14348809129028, 11.25651190870971, 8.4), + Vec3::new(11.256511908709715, 11.256511908709712, 8.4), + Vec3::new(10.0, 14.3, 8.4), + Vec3::new(11.256511908709713, 17.343488091290293, 8.4), + Vec3::new(23.2, 18.6, 8.4), + Vec3::new(35.14348809129028, 17.34348809129029, 8.4), + Vec3::new(36.4, 14.3, 8.4), + ]; + let radius = 2.0; + // Pappus: the removed cross-section swept along the straight sides and four quarters. + let area = radius * radius * (1.0 - PI / 4.0); + let centroid = radius * (10.0 - 3.0 * PI) / (3.0 * (4.0 - PI)); + let removed = area * (2.0 * (w + h - 4.0 * r) + 2.0 * PI * (r - centroid)); + let fine = |b: &Body| b.tessellate_with(1e-4, true).unwrap().measure().volume; + let initial = fine(&body); + // Every rim edge, the tiny end alone (tangent chain), and the opposite selection order. + for selection in [picks.to_vec(), vec![picks[3]], picks.into_iter().rev().collect()] { + let blended = fillet(&body, &selection, radius).unwrap(); + assert!(blended.validity().is_empty(), "{:?}", blended.validity()); + assert_eq!(blended.crossed_face_loops().unwrap(), 0); + assert_eq!((blended.face_count(), blended.edge_count(), blended.vertex_count()), (18, 40, 24)); + let actual = initial - fine(&blended); + assert!(rel(actual, removed) < 1e-3, "{actual} vs {removed}"); + } + assert!(fillet(&body, &picks, 9.0).is_err()); +} + #[test] fn fillet_sharp_arc_and_arc_loop() { use solidcraft_geom::Seg2; From b0b59480eb84d960425c311b5915a5aeada7eb74 Mon Sep 17 00:00:00 2001 From: NOWN-DEV <257771410+NOWN-DEV@users.noreply.github.com> Date: Mon, 19 Oct 2026 22:08:23 +0200 Subject: [PATCH 086/225] Joints: relations that tie part of a placement (#2497) Joints can tie part of a placement: parallel, angle, point on plane and more (#2496). --- .../doc/src/format/pending/joint-relations.rs | 6 + crates/doc/src/joints.rs | 118 ++++++++- crates/doc/src/joints_relations.rs | 130 ++++++++++ crates/engine/src/cmd/joints.rs | 34 ++- .../engine/src/cmd/joints_relations_tests.rs | 238 ++++++++++++++++++ crates/io/src/urdf.rs | 21 +- crates/ui-egui/src/dialogs_assembly.rs | 32 ++- docs/book/src/guide/assemblies.md | 24 +- docs/urdf.md | 2 + 9 files changed, 580 insertions(+), 25 deletions(-) create mode 100644 crates/doc/src/format/pending/joint-relations.rs create mode 100644 crates/doc/src/joints_relations.rs create mode 100644 crates/engine/src/cmd/joints_relations_tests.rs diff --git a/crates/doc/src/format/pending/joint-relations.rs b/crates/doc/src/format/pending/joint-relations.rs new file mode 100644 index 000000000..008ab46b4 --- /dev/null +++ b/crates/doc/src/format/pending/joint-relations.rs @@ -0,0 +1,6 @@ +//! A joint can be a relation that ties only some directions or points of its two parts: +//! `parallel`, `perpendicular`, `angle` (its `angle` is then the tilt between the two z axes), +//! `point_on_plane`, `point_on_line` and `line_on_plane`, each with the values its free motion +//! needs. Several relations between one pair of parts close loops the solver meets together. +//! Older designs need no transformation; the last release asks for an update instead of meeting +//! a joint type it can't read. diff --git a/crates/doc/src/joints.rs b/crates/doc/src/joints.rs index b9520c477..dada884a1 100644 --- a/crates/doc/src/joints.rs +++ b/crates/doc/src/joints.rs @@ -1,11 +1,13 @@ //! Joints between occurrences: joint origins (snap frames on component geometry, re-found on //! every solve so they follow edits), joints (rigid, revolute, slider, cylindrical, pin-slot, -//! planar, ball) with their motion values and limits, motion links (gears, racks and screws are +//! planar, ball, and relations that tie only part of a placement, `joints_relations.rs`) with +//! their motion values and limits, motion links (gears, racks and screws are //! links whose ratio comes from radii or a pitch; a cam's follower follows a table worked out from //! its profile, `joints_cam.rs`), and the solver that places occurrences from the joint graph. //! //! A joint makes B's joint frame coincide with A's frame moved by the joint's motion: -//! `T_B · F_b = T_A · F_a · M(q) · Flip`, so `T_B = T_A · F_a · M(q) · Flip · F_b⁻¹`, where `T` +//! `T_B · F_b = T_A · F_a · M(q) · Flip · Tail(q)`, so `T_B = T_A · F_a · M(q) · Flip · Tail(q) · F_b⁻¹` +//! (`Tail` is a relation's tilt and turns after the mate; the identity for the others), where `T` //! are occurrence world transforms, `F` the joint frames in each component's own frame, and `q` //! the joint's values (angles in radians, distances in mm). The solver walks the graph from //! grounded occurrences (and the root, which never moves). Joints that close a loop (a four-bar @@ -203,6 +205,20 @@ pub enum JointKind { PinSlot, Planar, Ball, + /// B's z stays parallel to A's (against it unless flipped); B moves and turns about z freely. + Parallel, + /// B's z stays square to A's; B moves freely and turns about either z. + Perpendicular, + /// B's z stays at the joint's `angle` from mated (about their common x); B moves freely and + /// turns about either z. + Angle, + /// B's origin stays on A's xy plane (`offset` off it); B slides on it and turns any way. + PointOnPlane, + /// B's origin stays on A's z axis; B slides along it and turns any way. + PointOnLine, + /// B's z axis lies in A's xy plane (`offset` off it: a cylinder's radius makes it tangent); + /// B slides on the plane, turns about A's z and about its own axis. + LineOnPlane, } impl JointKind { @@ -215,6 +231,12 @@ impl JointKind { "pinslot" => JointKind::PinSlot, "planar" => JointKind::Planar, "ball" => JointKind::Ball, + "parallel" => JointKind::Parallel, + "perpendicular" | "square" => JointKind::Perpendicular, + "angle" => JointKind::Angle, + "pointonplane" | "pointonface" => JointKind::PointOnPlane, + "pointonline" | "pointonaxis" => JointKind::PointOnLine, + "lineonplane" | "lineonface" => JointKind::LineOnPlane, _ => return None, }) } @@ -228,10 +250,29 @@ impl JointKind { JointKind::PinSlot => &["angle", "slide"], JointKind::Planar => &["x", "y", "angle"], JointKind::Ball => &["yaw", "pitch", "roll"], + JointKind::Parallel => &["x", "y", "z", "angle"], + JointKind::Perpendicular | JointKind::Angle => &["x", "y", "z", "turn", "spin"], + JointKind::PointOnPlane => &["x", "y", "yaw", "pitch", "roll"], + JointKind::PointOnLine => &["slide", "yaw", "pitch", "roll"], + JointKind::LineOnPlane => &["x", "y", "turn", "spin"], } } pub fn is_angle(self, i: usize) -> bool { - matches!(self.dofs().get(i), Some(&("angle" | "yaw" | "pitch" | "roll"))) + matches!(self.dofs().get(i), Some(&("angle" | "yaw" | "pitch" | "roll" | "turn" | "spin"))) + } + /// A relation that only ties some directions or points (parallel, on a plane…): made where + /// the parts are, its values start as the nearest that meet it, so B moves no more than it + /// must. + pub fn is_relation(self) -> bool { + matches!( + self, + JointKind::Parallel + | JointKind::Perpendicular + | JointKind::Angle + | JointKind::PointOnPlane + | JointKind::PointOnLine + | JointKind::LineOnPlane + ) } } @@ -599,6 +640,10 @@ fn rot_z(a: f64) -> Mat { let (s, c) = a.sin_cos(); [[c, s, 0.0, 0.0], [-s, c, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] } +fn rot_x(a: f64) -> Mat { + let (s, c) = a.sin_cos(); + [[1.0, 0.0, 0.0, 0.0], [0.0, c, s, 0.0], [0.0, -s, c, 0.0], [0.0, 0.0, 0.0, 1.0]] +} fn rot_y(a: f64) -> Mat { let (s, c) = a.sin_cos(); [[c, 0.0, -s, 0.0], [0.0, 1.0, 0.0, 0.0], [s, 0.0, c, 0.0], [0.0, 0.0, 0.0, 1.0]] @@ -620,9 +665,40 @@ pub fn motion(kind: JointKind, q: &[f64]) -> Mat { JointKind::PinSlot => mat_mul(&shift(v(1), 0.0, 0.0), &rot_z(v(0))), JointKind::Planar => mat_mul(&shift(v(0), v(1), 0.0), &rot_z(v(2))), JointKind::Ball => mat_mul(&mat_mul(&rot_z(v(0)), &rot_y(v(1))), &rot_z(v(2))), + JointKind::Parallel => mat_mul(&shift(v(0), v(1), v(2)), &rot_z(v(3))), + JointKind::Perpendicular | JointKind::Angle => mat_mul(&shift(v(0), v(1), v(2)), &rot_z(v(3))), + // Their turn is about B's origin, after the offset (`tail`). + JointKind::PointOnPlane => shift(v(0), v(1), 0.0), + JointKind::PointOnLine => shift(0.0, 0.0, v(0)), + JointKind::LineOnPlane => mat_mul(&shift(v(0), v(1), 0.0), &rot_z(v(2))), } } +fn turn_zyx(yaw: f64, pitch: f64, roll: f64) -> Mat { + mat_mul(&mat_mul(&rot_z(yaw), &rot_y(pitch)), &rot_x(roll)) +} + +/// What follows the mate (`flip_of`) in a joint's link: for a relation that tilts B's z, the tilt +/// and B's turn about its own z (`spin`); for a point relation, B's turn about its origin (yaw, +/// pitch and roll about z, y and x: free of gimbal lock at the start, all 0); nothing for the +/// other joints. +fn tail(j: &Joint, q: &[f64]) -> Mat { + let v = |i: usize| q.get(i).copied().unwrap_or(0.0); + match j.kind { + JointKind::Perpendicular => mat_mul(&rot_x(std::f64::consts::FRAC_PI_2), &rot_z(v(4))), + JointKind::Angle => mat_mul(&rot_x(j.angle), &rot_z(v(4))), + JointKind::LineOnPlane => mat_mul(&rot_y(std::f64::consts::FRAC_PI_2), &rot_z(v(3))), + JointKind::PointOnPlane => turn_zyx(v(2), v(3), v(4)), + JointKind::PointOnLine => turn_zyx(v(1), v(2), v(3)), + _ => IDENTITY, + } +} + +/// B's joint frame in A's for the joint's values: `M(q) · Flip · tail`. +fn link_of(j: &Joint, q: &[f64]) -> Mat { + mat_mul(&mat_mul(&motion(j.kind, q), &flip_of(j)), &tail(j, q)) +} + /// Bodies of a component in the model (its own frame). fn component_bodies<'a>(doc: &Document, st: &'a ModelState, component: u64) -> Vec<&'a crate::ModelBody> { st.bodies.iter().filter(|b| doc.model_body_component(b) == component).collect() @@ -854,14 +930,16 @@ pub fn joint_values(asm: &Assembly) -> BTreeMap> { /// The turn and offset from A's joint frame to B's: mated (B's z against A's, as faces meet) /// unless flipped. fn flip_of(j: &Joint) -> Mat { - let mut m = rot_z(j.angle); + // An angle relation's `angle` is its tilt (`tail`); a perpendicular one has none. + let turn = if matches!(j.kind, JointKind::Angle | JointKind::Perpendicular) { 0.0 } else { j.angle }; + let mut m = rot_z(turn); m[3][2] = j.offset; if !j.flip { mat_mul(&m, &[[1.0, 0.0, 0.0, 0.0], [0.0, -1.0, 0.0, 0.0], [0.0, 0.0, -1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]) } else { m } } /// B's world transform from A's (or A's from B's, going the other way) for the joint's values. fn through(j: &Joint, (fa, fb): &(Mat, Mat), q: &[f64], from_a: bool, t: &Mat) -> Option { - let link = mat_mul(&mat_mul(&motion(j.kind, q), &flip_of(j)), &mat_inverse(fb)?); + let link = mat_mul(&link_of(j, q), &mat_inverse(fb)?); if from_a { Some(mat_mul(&mat_mul(t, fa), &link)) } else { @@ -928,6 +1006,10 @@ impl Tree<'_> { /// on at most: larger ones are only checked. const MAX_LOOP_VALUES: usize = 64; const MAX_LOOPS: usize = 100; +/// Loop-closing joints one solve takes on at most, over all its groups: a part placed by several +/// relations closes a loop with each one after the first, so a panel of parts has many small +/// groups. +const MAX_CLOSING: usize = 5_000; /// Residual evaluations one solve may spend on all its loops. const MAX_LOOP_WORK: usize = 200_000; @@ -984,13 +1066,13 @@ fn held_moves(asm: &Assembly, held: &Held, touches: &BTreeSet<(u64, usize)>, val /// moves; a group that can't close without moving is left to the conflict check). fn close_loops(tree: &Tree, closing: &[u64], asm: &Assembly, held: &Held, vals: &mut Values) -> (Values, BTreeSet) { let (mut changed, mut stuck) = (BTreeMap::new(), BTreeSet::new()); - if closing.len() > MAX_LOOPS { + if closing.len() > MAX_CLOSING { return (Values::new(), stuck); } let linked = set_values(asm); let groups = loop_groups(tree, closing, asm, &linked); let spent = std::cell::Cell::new(0usize); - for (group, around, touches) in &groups { + for (group, around, touches) in groups.iter().filter(|(c, _, _)| c.len() <= MAX_LOOPS) { let moves = held_moves(asm, held, touches, vals); match close_group(tree, group, around, &moves, asm, held, &linked, &spent, vals) { Some(m) => changed.extend(m), @@ -1179,11 +1261,12 @@ fn nearby_pose(tree: &Tree, groups: &[Group], asm: &Assembly, linked: &BTreeSet< /// pose alone counts 0. The tree's count stands where a loop group is over the solver's caps or /// the work runs out. fn loop_dof(tree: &Tree, closing: &[u64], asm: &Assembly, vals: &Values, dof: &mut BTreeMap) { - if closing.len() > MAX_LOOPS { + if closing.len() > MAX_CLOSING { return; } let linked = set_values(asm); - let groups = loop_groups(tree, closing, asm, &linked); + let mut groups = loop_groups(tree, closing, asm, &linked); + groups.retain(|(c, _, _)| c.len() <= MAX_LOOPS); // The joints loops depend on: those around them, those whose values they read, and those a // motion link carries any of these values into. let mut relevant: BTreeSet = groups.iter().flat_map(|(_, a, t)| a.iter().copied().chain(t.iter().map(|(j, _)| *j))).collect(); @@ -1592,8 +1675,18 @@ struct Built<'a> { fn build<'a>(doc: &'a Document, st: &ModelState, vals: &Values, sol: &mut Solution) -> Built<'a> { let asm = &doc.assembly; let joints: Vec<&Joint> = asm.joints.iter().filter(|j| !j.suppressed).take(MAX_JOINTS).collect(); - // Joint frames in component coordinates (errors leave the joint out). + // Joint frames in component coordinates (errors leave the joint out). An origin several joints + // share (a panel face every part sits on) is found once. let mut frames: BTreeMap = BTreeMap::new(); + let mut found: BTreeMap<(u64, String), std::result::Result> = BTreeMap::new(); + let mut resolve = |o: &JointOrigin| -> Result { + let Ok(comp) = component_of(doc, o.occurrence) else { return resolve_origin(doc, st, o) }; + found + .entry((comp, format!("{:?}", o.snap))) + .or_insert_with(|| resolve_origin(doc, st, o).map_err(|e| e.to_string())) + .clone() + .map_err(DocError::Invalid) + }; for j in &joints { // A joint whose expressions can't be worked out (a parameter gone) is left out rather // than placed by numbers that no longer say what it was defined by. @@ -1603,7 +1696,7 @@ fn build<'a>(doc: &'a Document, st: &ModelState, vals: &Values, sol: &mut Soluti sol.errors.push((j.id, j.name.clone(), e.to_string())); continue; } - match (resolve_origin(doc, st, &j.a), resolve_origin(doc, st, &j.b)) { + match (resolve(&j.a), resolve(&j.b)) { (Ok(fa), Ok(fb)) => { frames.insert(j.id, (fa, fb)); } @@ -1735,7 +1828,10 @@ mod reach; #[path = "joints_face.rs"] mod face; pub use face::{end_faces, face_name_at, named_face_spot, pin_end, round_end_at}; +#[path = "joints_relations.rs"] +mod relations; pub use reach::{REACH_TOL, Reach, Reached, reach}; +pub use relations::relation_values; /// The rest angle that turns B least as joint `j` is made, as B sits now: none or a half turn /// about the joint's z. Origins whose x is chosen for them (a face, a circle, a point without diff --git a/crates/doc/src/joints_relations.rs b/crates/doc/src/joints_relations.rs new file mode 100644 index 000000000..f22677a34 --- /dev/null +++ b/crates/doc/src/joints_relations.rs @@ -0,0 +1,130 @@ +//! Relations: joints that tie only some directions or points of two parts (B parallel to A, B's +//! point on A's plane…), so several of them between one pair of parts build up the placement the +//! way a designer thinks of it: on that face, square to that edge, 40 mm from that end. The +//! solver treats them as joints with more values; a second relation between the same parts closes +//! a loop, and the loop solver meets every relation at once (or reports the one that can't be). +//! +//! A relation is made where the parts are: its values start as the nearest that meet it, so B +//! moves no further than the relation needs. + +use super::{Joint, component_bodies, component_of, least_squares, link_of, occurrence_world, resolve_origin}; +use crate::{Document, IDENTITY, Mat, ModelState, mat_inverse, mat_mul}; + +/// Starting turns tried for each angle value: the nearest values may lie a half turn away. +const TURNS: [f64; 4] = [0.0, std::f64::consts::FRAC_PI_2, std::f64::consts::PI, -std::f64::consts::FRAC_PI_2]; + +/// Starts tried at most (angle values beyond the first three start at 0). +const MAX_STARTS: usize = 64; + +/// The values of relation `j` that move B least from where it is now: B's joint frame as it sits +/// in A's, met as nearly as the relation allows (its origin as near as it can be to where it is, +/// and its axes, each weighed as a point a part's size along it). `None` for a joint that is not a relation, or whose +/// origins can't be found. +pub fn relation_values(doc: &Document, st: &ModelState, j: &Joint) -> Option> { + if !j.kind.is_relation() { + return None; + } + let world = |occ: u64| if occ == 0 { IDENTITY } else { occurrence_world(doc, occ) }; + let fa = mat_mul(&world(j.a.occurrence), &resolve_origin(doc, st, &j.a).ok()?); + let fb = mat_mul(&world(j.b.occurrence), &resolve_origin(doc, st, &j.b).ok()?); + // B's joint frame in A's as it is. + let now = mat_mul(&mat_inverse(&fa)?, &fb); + // A turn weighs as far as it moves a point B's size away. + let size = component_of(doc, j.b.occurrence).map(|c| component_bodies(doc, st, c).iter().map(|b| b.body.size()).fold(0.0, f64::max)); + let scale = size.unwrap_or(0.0).clamp(1.0, 1e5); + let n = j.kind.dofs().len(); + let angles: Vec = (0..n).filter(|i| j.kind.is_angle(*i)).collect(); + let mut gaps = |q: &[f64]| -> Option> { + let m: Mat = link_of(j, q); + let mut out = Vec::with_capacity(12); + for (k, (row, want)) in m.iter().zip(&now).enumerate() { + let w = if k == 3 { 1.0 } else { scale }; + out.extend(row.iter().zip(want).take(3).map(|(a, b)| (a - b) * w)); + } + out.iter().all(|v| v.is_finite()).then_some(out) + }; + let cost = |r: &[f64]| r.iter().map(|v| v * v).sum::(); + let bounds = vec![(f64::NEG_INFINITY, f64::INFINITY); n]; + let mut best: Option<(f64, Vec)> = None; + let tried = angles.len().min(3); + for k in 0..TURNS.len().pow(tried as u32).min(MAX_STARTS) { + let mut q = vec![0.0; n]; + let mut code = k; + for i in angles.iter().take(tried) { + if let (Some(slot), Some(t)) = (q.get_mut(*i), TURNS.get(code % TURNS.len())) { + *slot = *t; + } + code /= TURNS.len(); + } + // Tolerance 0: as near as it gets; `q` keeps the best values reached. + least_squares(&mut gaps, &mut q, &bounds, 0.0); + let Some(c) = gaps(&q).map(|r| cost(&r)) else { continue }; + if best.as_ref().is_none_or(|(b, _)| c < *b - 1e-12) { + best = Some((c, q)); + } + } + // Angles within a half turn of 0. + best.map(|(_, mut q)| { + for i in &angles { + if let Some(v) = q.get_mut(*i) { + *v = (*v + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI; + } + } + q + }) +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + use super::*; + use crate::joints::{JointKind, JointOrigin, Snap}; + use solidcraft_geom::Vec3; + + fn joint(kind: JointKind) -> Joint { + let at = |occurrence| JointOrigin { occurrence, snap: Snap::Point { point: Vec3::ZERO, z: None } }; + Joint { + id: 1, + name: "R".into(), + kind, + a: at(0), + b: at(1), + values: Vec::new(), + limits: Vec::new(), + flip: false, + offset: 0.0, + angle: 0.6, + suppressed: false, + exprs: Default::default(), + } + } + + fn z_of(m: &Mat) -> Vec3 { + Vec3::new(m[2][0], m[2][1], m[2][2]) + } + + /// Whatever its values, each relation keeps what it ties. + #[test] + fn relations_keep_what_they_tie() { + let q = [13.0, -7.0, 21.0, 0.7, -1.9]; + let at = |kind| { + let j = joint(kind); + let n = kind.dofs().len(); + link_of(&j, q.get(..n).unwrap()) + }; + // Parallel: z against A's. + assert!((z_of(&at(JointKind::Parallel)).z + 1.0).abs() < 1e-12); + // Perpendicular: z square to A's. + assert!(z_of(&at(JointKind::Perpendicular)).z.abs() < 1e-12); + // Angle: 0.6 from mated. + assert!((z_of(&at(JointKind::Angle)).z + 0.6f64.cos()).abs() < 1e-12); + // Point on plane: the origin on A's plane. + assert!(at(JointKind::PointOnPlane)[3][2].abs() < 1e-12); + // Point on line: on A's z axis. + let m = at(JointKind::PointOnLine); + assert!(m[3][0].abs() < 1e-12 && m[3][1].abs() < 1e-12); + // Line on plane: the origin on the plane and z along it. + let m = at(JointKind::LineOnPlane); + assert!(m[3][2].abs() < 1e-12 && z_of(&m).z.abs() < 1e-12); + } +} diff --git a/crates/engine/src/cmd/joints.rs b/crates/engine/src/cmd/joints.rs index aca98ef1d..856f0454e 100644 --- a/crates/engine/src/cmd/joints.rs +++ b/crates/engine/src/cmd/joints.rs @@ -20,11 +20,13 @@ pub static COMMANDS: &[CommandSpec] = &[ "name?, occurrence?: id|name (default: from the pick, or the named face's component), face: [x,y,z] | \"\" (centre of a planar face) | circle: [x,y,z] | \"\" (centre of a round end: a point on its wall or rim, the end's centre, or the round face's name as model.faces lists it) | edge: [x,y,z] (a point on an edge of a planar face: the edge's middle, z out of the face, y into it; on?: [x,y,z] a point on the face (default: the larger planar face beside the edge); corner?: [x,y,z] near one end: the corner there, x and y along its two edges into the face; found again by name, so it follows the face as it changes size) | point: [x,y,z], z?: [x,y,z]; body?: the named face's body; end?: \"\" (a circle's end: the face across its rim there; default the end nearer the pick); x?: [x,y,z] (a direction, world) | \"\" | {face: [x,y,z]} (the frame's x: a direction, a plane's normal, or the way to another hole's axis; keeps a round origin's turn). Faces are kept by name: the origin follows its face, and a circle its end, when the design changes", ), CommandSpec::new("joint.create", "Joint", joint).at("SOLID", "ASSEMBLE").icon("joint").key("J").params( - "type: rigid|revolute|slider|cylindrical|pin_slot|planar|ball; a, b: joint origins ({occurrence, face|circle|edge|point: [x,y,z] in world, or face|circle: \"\"; end?, x? as joint.origin} | origin name); \ + "type: rigid|revolute|slider|cylindrical|pin_slot|planar|ball, or a relation: parallel|perpendicular|angle|point_on_plane|point_on_line|line_on_plane \ + (ties only some directions or points, made where the parts are; several between two parts add up); a, b: joint origins ({occurrence, face|circle|edge|point: [x,y,z] in world, or face|circle: \"\"; end?, x? as joint.origin} | origin name); \ values?: [angles in deg or expressions, distances]; limits?: [[min, max] | null…]; flip?: bool (default false: the origins are mated, \ b's z against a's as two faces meet; true: b's z along a's, so two origins given at one point with the same z stay as they are); \ - offset?: mm or an expression; angle?: deg or an expression (default: none, or a half turn where that turns b less, so faces that \ - already meet stay as they are); name?; quiet?: bool (leave out dof and fixed). An expression (text) is \ + offset?: mm or an expression; angle?: deg or an expression (an angle relation's tilt from mated; for other joints the default \ + is none, or a half turn where that turns b less, so faces that already meet stay as they are); name?; quiet?: bool (leave \ + out dof and fixed). An expression (text) is \ kept with the joint and worked out again whenever the design changes, so the joint follows the parameters it names; a joint whose \ expression no longer works out (a parameter deleted) is left out of the solve with the reason in its errors", ), @@ -615,7 +617,7 @@ fn joint_origin(s: &mut Session, p: &Value) -> Result { fn kind_param(p: &Value, cmd: &str) -> Result { str_(p, "type") .and_then(JointKind::parse) - .ok_or_else(|| bad(cmd, "`type` must be rigid, revolute, slider, cylindrical, pin_slot, planar or ball")) + .ok_or_else(|| bad(cmd, "`type` must be rigid, revolute, slider, cylindrical, pin_slot, planar, ball, parallel, perpendicular, angle, point_on_plane, point_on_line or line_on_plane")) } fn joint(s: &mut Session, p: &Value) -> Result { @@ -647,9 +649,16 @@ fn joint(s: &mut Session, p: &Value) -> Result { suppressed: false, exprs: JointExprs { offset: typed(p.get("offset")), angle: typed(p.get("angle")), values: value_exprs(p) }, }; + // A relation given no values starts from where its parts are: B moves no further than it must. + if p.get("values").is_none() + && p.get("value").is_none() + && let Some(q) = joints::relation_values(&s.doc, &s.model.state(), &j) + { + j.values = q; + } // No angle given: B keeps its turn about the joint's axis where a half turn would otherwise - // come only from how its origin's x was chosen. - if angle.is_none() { + // come only from how its origin's x was chosen. (An angle relation's angle is its tilt.) + if angle.is_none() && !j.kind.is_relation() { j.angle = joints::least_turn_angle(&s.doc, &s.model.state(), &j); } add_joint(s, j, p) @@ -1224,6 +1233,16 @@ fn edit(s: &mut Session, p: &Value) -> Result { if let Some(n) = str_(p, "name").map(str::trim).filter(|n| !n.is_empty() && n.len() <= 128) { j.name = n.to_string(); } + // A relation whose type, offset, tilt or flip changes starts again from where its parts are. + let reseat = kind.is_some() || offset.is_some() || angle.is_some() || p.get("flip").is_some(); + if reseat { + let edited = s.doc.assembly.joints.iter().find(|j| j.id == id).cloned(); + if let Some(q) = edited.and_then(|j| joints::relation_values(&s.doc, &s.model.state(), &j)) + && let Some(j) = s.doc_mut().assembly.joints.iter_mut().find(|j| j.id == id) + { + j.values = q; + } + } let sol = resolve(s); Ok(sol_json(&sol, p)) } @@ -1367,6 +1386,9 @@ mod frames_tests; #[path = "joints_reach_tests.rs"] mod reach_tests; #[cfg(test)] +#[path = "joints_relations_tests.rs"] +mod relations_tests; +#[cfg(test)] #[path = "joints_tests.rs"] mod tests; #[cfg(test)] diff --git a/crates/engine/src/cmd/joints_relations_tests.rs b/crates/engine/src/cmd/joints_relations_tests.rs new file mode 100644 index 000000000..e858ea0f2 --- /dev/null +++ b/crates/engine/src/cmd/joints_relations_tests.rs @@ -0,0 +1,238 @@ +//! Relations (parallel, perpendicular, angle, point on plane, point on line, line on plane): each +//! ties only part of a placement, several between two parts add up, they start from where the +//! parts are, and they keep holding as the parts change size. + +use serde_json::{Value, json}; +use solidcraft_geom::Vec3; + +use super::tests::{occ, place, run}; +use crate::Session; + +/// A 2 mm panel `W` x 300 (W = 400) in component Panel and a 20 x 10 x 6 bracket in component +/// Bracket off to the side, with named origins on both made where they are; then the bracket is +/// lifted, turned and tilted, as a part dropped in anywhere. +fn panel() -> Session { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "W", "expression": "400 mm"})); + run(&mut s, "component.create", json!({"name": "Panel"})); + run(&mut s, "solid.box", json!({"length": "W", "width": 300, "height": 2, "corner": [0, 0, 0]})); + run(&mut s, "component.activate", json!({"component": "root"})); + run(&mut s, "component.create", json!({"name": "Bracket"})); + run(&mut s, "solid.box", json!({"length": 20, "width": 10, "height": 6, "corner": [0, 500, 0]})); + run(&mut s, "component.activate", json!({"component": "root"})); + let panel = occ(&s, "Panel"); + run(&mut s, "occurrence.ground", json!({"occurrence": panel, "grounded": true})); + for (name, o, k, at) in [ + ("Top", "Panel", "face", [100.0, 100.0, 2.0]), + ("Front", "Panel", "face", [100.0, 0.0, 1.0]), + ("Right", "Panel", "face", [400.0, 100.0, 1.0]), + ("Bottom", "Bracket", "face", [10.0, 505.0, 0.0]), + ("Face", "Bracket", "face", [10.0, 500.0, 3.0]), + ("Corner", "Bracket", "point", [20.0, 500.0, 0.0]), + ] { + run(&mut s, "joint.origin", json!({"name": name, "occurrence": o, k: at})); + } + let b = occ(&s, "Bracket"); + run(&mut s, "occurrence.move", json!({"occurrence": b, "translate": [30, -120, 50]})); + run(&mut s, "occurrence.move", json!({"occurrence": b, "axis": [0, 0, 1], "angle": "25 deg", "origin": [40, 385, 50]})); + run(&mut s, "occurrence.move", json!({"occurrence": b, "axis": [1, 0, 0], "angle": "10 deg", "origin": [40, 385, 50]})); + s +} + +fn relation(s: &mut Session, kind: &str, a: &str, b: &str, extra: Value) -> Value { + let mut p = json!({"type": kind, "a": a, "b": b, "name": format!("{kind} {a}-{b}")}); + if let (Some(p), Some(extra)) = (p.as_object_mut(), extra.as_object()) { + p.extend(extra.clone()); + } + run(s, "joint.create", p) +} + +fn dof(r: &Value, s: &Session) -> Option { + let b = occ(s, "Bracket"); + r["dof"].as_array()?.iter().find(|d| d["occurrence"] == json!(b))?["dof"].as_u64() +} + +fn near(a: Vec3, b: Vec3, tol: f64) -> bool { + a.dist(b) < tol +} + +fn clean(r: &Value) -> bool { + r["conflicts"] == json!([]) && r["errors"] == json!([]) +} + +#[test] +fn stacked_relations_place_a_part_and_follow_the_panel() { + let mut s = panel(); + // Flat on the top (parallel, and a corner on it), its face along the panel's front edge, the + // corner 40 mm in from the front and the right end. + let r = relation(&mut s, "parallel", "Top", "Bottom", json!({})); + assert_eq!(dof(&r, &s), Some(4), "{r}"); + let r = relation(&mut s, "point_on_plane", "Top", "Corner", json!({})); + assert_eq!(dof(&r, &s), Some(3), "{r}"); + let r = relation(&mut s, "parallel", "Front", "Face", json!({"flip": true})); + assert_eq!(dof(&r, &s), Some(2), "{r}"); + let r = relation(&mut s, "point_on_plane", "Front", "Corner", json!({"offset": -40})); + assert_eq!(dof(&r, &s), Some(1), "{r}"); + let r = relation(&mut s, "point_on_plane", "Right", "Corner", json!({"offset": -40})); + assert!(clean(&r), "{r}"); + assert_eq!(dof(&r, &s), Some(0), "{r}"); + for w in [400.0, 650.0, 250.0, 1000.0] { + run(&mut s, "parameters.change", json!({"name": "W", "expression": format!("{w} mm")})); + let r = run(&mut s, "joint.solve", json!({})); + assert!(clean(&r), "W {w}: {r}"); + // The corner, the bracket's other bottom corner along its face, and its top: flat, square + // and 40 mm in. + assert!(near(place(&s, "Bracket", Vec3::new(20.0, 500.0, 0.0)), Vec3::new(w - 40.0, 40.0, 2.0), 1e-6), "W {w}"); + assert!(near(place(&s, "Bracket", Vec3::new(0.0, 500.0, 0.0)), Vec3::new(w - 60.0, 40.0, 2.0), 1e-6), "W {w}"); + assert!(near(place(&s, "Bracket", Vec3::new(20.0, 510.0, 6.0)), Vec3::new(w - 40.0, 50.0, 8.0), 1e-6), "W {w}"); + } +} + +#[test] +fn a_relation_moves_the_part_no_further_than_it_must() { + let mut s = panel(); + let corner = |s: &Session| place(s, "Bracket", Vec3::new(20.0, 500.0, 0.0)); + let along = |s: &Session| place(s, "Bracket", Vec3::new(0.0, 510.0, 6.0)) - corner(s); + let (before, turn) = (corner(&s), along(&s)); + let r = relation(&mut s, "point_on_plane", "Top", "Corner", json!({})); + assert!(clean(&r), "{r}"); + assert_eq!(dof(&r, &s), Some(5), "{r}"); + // Straight down onto the top, turned as it was. + assert!(near(corner(&s), Vec3::new(before.x, before.y, 2.0), 1e-6), "{:?} from {before:?}", corner(&s)); + assert!(near(along(&s), turn, 1e-6), "{:?} from {turn:?}", along(&s)); + // Parallel to the top: it only turns level, about the corner it keeps. + let r = relation(&mut s, "parallel", "Top", "Bottom", json!({})); + assert!(clean(&r), "{r}"); + let up = place(&s, "Bracket", Vec3::new(20.0, 500.0, 6.0)) - corner(&s); + assert!(near(up, Vec3::new(0.0, 0.0, 6.0), 1e-6), "{up:?}"); + assert!((corner(&s).z - 2.0).abs() < 1e-6, "{:?}", corner(&s)); +} + +#[test] +fn an_angle_relation_holds_its_tilt_and_follows_an_edit() { + let mut s = panel(); + relation(&mut s, "point_on_plane", "Top", "Corner", json!({})); + let tilt = |s: &Session| { + let n = place(s, "Bracket", Vec3::new(10.0, 505.0, 0.0)) - place(s, "Bracket", Vec3::new(10.0, 505.0, 1.0)); + n.normalized().map_or(f64::NAN, |n| n.dot(Vec3::Z).acos().to_degrees()) + }; + // 0 deg is mated: the bracket's bottom against the top, its outward normal straight down. + let r = relation(&mut s, "angle", "Top", "Bottom", json!({"angle": "30 deg"})); + assert!(clean(&r), "{r}"); + assert!((tilt(&s) - 150.0).abs() < 1e-6, "{}", tilt(&s)); + run(&mut s, "joint.edit", json!({"joint": "angle Top-Bottom", "angle": "60 deg"})); + assert!((tilt(&s) - 120.0).abs() < 1e-6, "{}", tilt(&s)); + run(&mut s, "joint.edit", json!({"joint": "angle Top-Bottom", "type": "perpendicular"})); + assert!((tilt(&s) - 90.0).abs() < 1e-6, "{}", tilt(&s)); + // The corner stayed on the top through every change. + assert!((place(&s, "Bracket", Vec3::new(20.0, 500.0, 0.0)).z - 2.0).abs() < 1e-6); +} + +#[test] +fn a_rod_lies_tangent_on_the_panel_and_rolls_along_it() { + let mut s = panel(); + run(&mut s, "component.create", json!({"name": "Rod"})); + run(&mut s, "solid.cylinder", json!({"base": [0, 700, 40], "axis": [1, 0, 0], "radius": 5, "height": 80, "operation": "new"})); + run(&mut s, "component.activate", json!({"component": "root"})); + run(&mut s, "joint.origin", json!({"name": "Axis", "occurrence": "Rod", "circle": [0, 700, 40]})); + let r = relation(&mut s, "line_on_plane", "Top", "Axis", json!({"offset": 5})); + assert!(clean(&r), "{r}"); + let rod = occ(&s, "Rod"); + let d = r["dof"].as_array().and_then(|a| a.iter().find(|d| d["occurrence"] == json!(rod))).and_then(|d| d["dof"].as_u64()); + assert_eq!(d, Some(4), "{r}"); + // Its axis level, 5 mm over the top: it touches it along a line. + let (a, b) = (place(&s, "Rod", Vec3::new(0.0, 700.0, 40.0)), place(&s, "Rod", Vec3::new(80.0, 700.0, 40.0))); + assert!((a.z - 7.0).abs() < 1e-6 && (b.z - 7.0).abs() < 1e-6, "{a:?} {b:?}"); + // Rolled along: still tangent. + run(&mut s, "joint.drive", json!({"joint": "line_on_plane Top-Axis", "values": [100, 50, "30 deg", "90 deg"]})); + let (a, b) = (place(&s, "Rod", Vec3::new(0.0, 700.0, 40.0)), place(&s, "Rod", Vec3::new(80.0, 700.0, 40.0))); + assert!((a.z - 7.0).abs() < 1e-6 && (b.z - 7.0).abs() < 1e-6, "{a:?} {b:?}"); +} + +#[test] +fn relations_that_disagree_are_reported_not_forced() { + let mut s = panel(); + relation(&mut s, "point_on_plane", "Right", "Corner", json!({"offset": -40})); + let r = relation(&mut s, "point_on_plane", "Right", "Corner", json!({"offset": -60})); + assert_eq!(r["conflicts"].as_array().map(Vec::len), Some(1), "{r}"); + // A point on the panel's front plane's line: still placed, every number finite. + let r = relation(&mut s, "point_on_line", "Front", "Corner", json!({})); + assert!(r["dof"].is_array(), "{r}"); + let p = place(&s, "Bracket", Vec3::new(20.0, 500.0, 0.0)); + assert!(p.is_finite(), "{p:?}"); + // Saved and read back, the relations are the same. + let saved = serde_json::to_string(&s.doc.assembly.joints).unwrap_or_default(); + let back: Vec = serde_json::from_str(&saved).unwrap_or_default(); + assert_eq!(back, s.doc.assembly.joints); + assert!(saved.contains("\"point_on_plane\"") && saved.contains("\"point_on_line\""), "{saved}"); +} + +/// More parts placed by relations than one group of loops may hold (each relation after a part's +/// first closes a loop): every group is small, so every part is placed. +#[test] +fn a_panel_full_of_parts_placed_by_relations_stays_solved() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "W", "expression": "1500 mm"})); + run(&mut s, "component.create", json!({"name": "Panel"})); + run(&mut s, "solid.box", json!({"length": "W", "width": 300, "height": 2, "corner": [0, 0, 0]})); + run(&mut s, "component.activate", json!({"component": "root"})); + let panel = occ(&s, "Panel"); + run(&mut s, "occurrence.ground", json!({"occurrence": panel, "grounded": true})); + for (name, at) in [("Top", [100.0, 100.0, 2.0]), ("Front", [100.0, 0.0, 1.0]), ("Right", [1500.0, 100.0, 1.0])] { + run(&mut s, "joint.origin", json!({"name": name, "occurrence": "Panel", "face": at})); + } + // 30 brackets, 5 relations each: 120 loops, more than the 100 one group may hold. The joints + // go straight into the design and are solved once (made one by one, each would solve all). + let n = 30usize; + for k in 0..n { + let (c, y) = (format!("B{k}"), 500.0 + 30.0 * k as f64); + run(&mut s, "component.activate", json!({"component": "root"})); + run(&mut s, "component.create", json!({"name": c})); + run(&mut s, "solid.box", json!({"length": 20, "width": 10, "height": 6, "corner": [0, y, 0]})); + run(&mut s, "component.activate", json!({"component": "root"})); + for (o, k2, at) in [("b", "face", [10.0, y + 5.0, 0.0]), ("f", "face", [10.0, y, 3.0]), ("c", "point", [20.0, y, 0.0])] { + run(&mut s, "joint.origin", json!({"name": format!("{c}{o}"), "occurrence": c, k2: at})); + } + let x = 40.0 * (k + 1) as f64; + for (kind, a, b, flip, offset) in [ + ("parallel", "Top", "b", false, 0.0), + ("point_on_plane", "Top", "c", false, 0.0), + ("parallel", "Front", "f", true, 0.0), + ("point_on_plane", "Front", "c", false, -40.0), + ("point_on_plane", "Right", "c", false, -x), + ] { + let origin = |n: &str| s.doc.assembly.origins.iter().find(|o| o.name == n).map(|o| o.origin.clone()); + let (Some(a), Some(b)) = (origin(a), origin(&format!("{c}{b}"))) else { panic!("origins") }; + let id = s.doc.assembly.joints.iter().map(|j| j.id).max().unwrap_or(0) + 1; + let kind = solidcraft_doc::joints::JointKind::parse(kind).unwrap_or(solidcraft_doc::joints::JointKind::Rigid); + let mut j = solidcraft_doc::joints::Joint { + id, + name: format!("R{id}"), + kind, + a, + b, + values: vec![0.0; kind.dofs().len()], + limits: vec![None; kind.dofs().len()], + flip, + offset, + angle: 0.0, + suppressed: false, + exprs: Default::default(), + }; + if let Some(q) = solidcraft_doc::joints::relation_values(&s.doc, &s.model.state(), &j) { + j.values = q; + } + s.doc_mut().assembly.joints.push(j); + } + } + for w in [1500.0, 1800.0] { + run(&mut s, "parameters.change", json!({"name": "W", "expression": format!("{w} mm")})); + let r = run(&mut s, "joint.solve", json!({})); + assert!(clean(&r), "W {w}: {r}"); + for k in [0, n / 2, n - 1] { + let (c, y) = (format!("B{k}"), 500.0 + 30.0 * k as f64); + let at = place(&s, &c, Vec3::new(20.0, y, 0.0)); + assert!(near(at, Vec3::new(w - 40.0 * (k + 1) as f64, 40.0, 2.0), 1e-6), "W {w} {c}: {at:?}"); + } + } +} diff --git a/crates/io/src/urdf.rs b/crates/io/src/urdf.rs index ea5dd9eef..c1ad07b9a 100644 --- a/crates/io/src/urdf.rs +++ b/crates/io/src/urdf.rs @@ -148,9 +148,11 @@ fn rotation(u: Vec3, a: f64) -> Mat { } /// The joint's motion as URDF steps, in order from A's frame: (kind, axis, index of the value). -fn steps(kind: JointKind) -> Vec<(Step, Vec3, usize)> { +/// `None` for a relation whose turns follow a fixed step (a tilt, or the offset off a plane or +/// line): URDF has no fixed step inside a joint's chain. +fn steps(kind: JointKind) -> Option> { use Step::{Prismatic as P, Revolute as R}; - match kind { + Some(match kind { JointKind::Rigid => vec![], JointKind::Revolute => vec![(R, Vec3::Z, 0)], JointKind::Slider => vec![(P, Vec3::Z, 0)], @@ -158,7 +160,9 @@ fn steps(kind: JointKind) -> Vec<(Step, Vec3, usize)> { JointKind::PinSlot => vec![(P, Vec3::X, 1), (R, Vec3::Z, 0)], JointKind::Planar => vec![(P, Vec3::X, 0), (P, Vec3::Y, 1), (R, Vec3::Z, 2)], JointKind::Ball => vec![(R, Vec3::Z, 0), (R, Vec3::Y, 1), (R, Vec3::Z, 2)], - } + JointKind::Parallel => vec![(P, Vec3::X, 0), (P, Vec3::Y, 1), (P, Vec3::Z, 2), (R, Vec3::Z, 3)], + JointKind::Perpendicular | JointKind::Angle | JointKind::PointOnPlane | JointKind::PointOnLine | JointKind::LineOnPlane => return None, + }) } /// `raw` with every character but `[A-Za-z0-9_]` (and `-` in file names) replaced by `_`, so it @@ -378,7 +382,14 @@ impl<'a> Tree<'a> { /// `child` on joint `j` from `p` (already in the tree): the joint's chain and the child's link. fn attach(&mut self, j: &Joint, fa: &Mat, p: u64, child: u64, q: &[f64]) -> Option<()> { - let m = joints::motion(j.kind, q); + // A relation URDF can't write is fixed where it is: the child link's frame is the joint's. + let (chain, m) = match steps(j.kind) { + Some(chain) => (chain, joints::motion(j.kind, q)), + None => { + self.warnings.push(format!("joint `{}` is a {:?} relation, which URDF has no joint for: written fixed as it is", j.name, j.kind)); + (Vec::new(), IDENTITY) + } + }; let child_on_b = j.a.occurrence == p; // (parent-side joint frame, child link frame) in the world. let (jf, lf) = if child_on_b { @@ -390,7 +401,7 @@ impl<'a> Tree<'a> { }; let (parent_index, parent_frame) = self.placed.get(&p).copied()?; let origin = mat_mul(&mat_inverse(&parent_frame)?, &jf); - let mut chain = steps(j.kind); + let mut chain = chain; if !child_on_b { chain.reverse(); for s in &mut chain { diff --git a/crates/ui-egui/src/dialogs_assembly.rs b/crates/ui-egui/src/dialogs_assembly.rs index 0b8fcf5f1..045894c35 100644 --- a/crates/ui-egui/src/dialogs_assembly.rs +++ b/crates/ui-egui/src/dialogs_assembly.rs @@ -26,8 +26,36 @@ mod trace; pub use trace::{TraceForm, picked_point}; /// Joint types in the order the Type box lists them (command names). -pub const TYPES: [&str; 7] = ["rigid", "revolute", "slider", "cylindrical", "pin_slot", "planar", "ball"]; -const TYPE_LABELS: [&str; 7] = ["Rigid", "Revolute", "Slider", "Cylindrical", "Pin-slot", "Planar", "Ball"]; +pub const TYPES: [&str; 13] = [ + "rigid", + "revolute", + "slider", + "cylindrical", + "pin_slot", + "planar", + "ball", + "parallel", + "perpendicular", + "angle", + "point_on_plane", + "point_on_line", + "line_on_plane", +]; +const TYPE_LABELS: [&str; 13] = [ + "Rigid", + "Revolute", + "Slider", + "Cylindrical", + "Pin-slot", + "Planar", + "Ball", + "Parallel", + "Perpendicular", + "Angle", + "Point on plane", + "Point on line", + "Line on plane", +]; /// What a joint origin input accepts (snaps on faces, edges and vertices). pub const SNAPS: u16 = FACES | EDGES | VERTICES; /// Commands whose effect is where occurrences sit (previewed on the placed model). diff --git a/docs/book/src/guide/assemblies.md b/docs/book/src/guide/assemblies.md index 39862cff8..f01041aa5 100644 --- a/docs/book/src/guide/assemblies.md +++ b/docs/book/src/guide/assemblies.md @@ -46,6 +46,28 @@ expression stops working out (say a parameter becomes an angle), the joint is le solve and `joint.solve` gives the reason, instead of placing the part from old numbers. Typing a plain number, or driving the value, drops that expression. +**Relations** are joints that tie only part of a placement, so a part is placed the way a +designer describes it, one relation at a time: `parallel` (z along z, free to move and turn +about it), `perpendicular` and `angle` (z square to z, or at the joint's `angle` from mated), +`point_on_plane` (a point on a face's plane, `offset` off it), `point_on_line` (a point on an +axis) and `line_on_plane` (an axis on a face's plane: a cylinder's radius as `offset` lays it +tangent). A relation is made where the parts are: B moves no further than the relation needs. +Several relations between the same two parts add up; the solver meets them together, each one's +degrees of freedom come off what is left, and one that can't be met is reported, not forced: + +```json +{"command": "joint.create", "params": {"type": "parallel", "a": "Panel top", "b": "Bracket bottom"}} +{"command": "joint.create", "params": {"type": "point_on_plane", "a": "Panel top", "b": "Bracket corner"}} +{"command": "joint.create", "params": {"type": "parallel", "a": "Panel front", "b": "Bracket face", "flip": true}} +{"command": "joint.create", "params": {"type": "point_on_plane", "a": "Panel front", "b": "Bracket corner", "offset": -40}} +{"command": "joint.create", "params": {"type": "point_on_plane", "a": "Panel end", "b": "Bracket corner", "offset": -40}} +``` + +leaves the bracket flat on the panel, square to its front, its corner 40 mm in from the front and +the end, wherever the panel's size takes them. Coincident faces are a `planar` joint, a distance +between faces is `planar` with an `offset`, concentric is `cylindrical` and two points that meet +are `ball`. + The check behind it, `inspect.clearance`, does all of that in one call for any number of bodies, which suits scripts and agents checking a whole assembly: @@ -169,7 +191,7 @@ it where it is), and it moves. with their units and limits, and `moved` says whether any part moved. A joint's origins are mated by default: B's z axis is turned against A's, as two faces meet. `flip: true` lines them up instead, so two origins given at one point with the same z stay as they are. Without an -`angle`, a new joint takes no turn or a half turn about its axis, whichever turns B less: two +`angle`, a new joint (other than a relation, which starts where its parts are) takes no turn or a half turn about its axis, whichever turns B less: two faces that already meet, a plate under a panel, stay as they are instead of B spinning about their shared normal. For scripts that drive many steps, `quiet: true` leaves the per-part degrees of freedom out of joint answers, and diff --git a/docs/urdf.md b/docs/urdf.md index 9f855712f..a245e7414 100644 --- a/docs/urdf.md +++ b/docs/urdf.md @@ -68,6 +68,8 @@ defaults are written and a warning says so. A value that is not a positive numbe | Pin-slot | `prismatic` x, then `revolute` z | | Planar | `prismatic` x, `prismatic` y, then `revolute` z | | Ball | `revolute` z, `revolute` y, then `revolute` z | +| Parallel | `prismatic` x, y and z, then `revolute` z | +| Perpendicular, angle, point on plane, point on line, line on plane | `fixed` where it is, with a warning: their turns follow a fixed tilt or offset, which a URDF chain can't hold | - **Chains:** a joint with several values becomes one URDF joint per value. Between them sit links named `_link1`, `_link2`. The steps before the last are named From c1f92245797d124f736ddd9eb0008d3a0ee1ef01 Mon Sep 17 00:00:00 2001 From: rlartot <94693724+rlartot@users.noreply.github.com> Date: Mon, 19 Oct 2026 22:08:37 +0200 Subject: [PATCH 087/225] Fillet fit: an outside round concentric with a wall's inside round is no longer refused (#2852) * Fillet fit: a round counts only what lies between its edge and its arc The fit check refused a round when any other face of the body reached into the wedge between its edge and its two setback lines. A round changes only the part of that wedge between the edge and its arc: a face on the ball's side of the arc is left as it is. An outside round concentric with the inside round of a 3 mm wall (R18 over R15) was refused as too large (largest 14.21 mm) although it keeps the wall 3 mm thick. The face check now tests a round's fan of prisms from its edge to its arc (Frame::pieces, already used for blends that cross), after the wedge as a quick filter. Chamfers keep the wedge, which is what they change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L15TLCjpXsQdp8ovC4ZacH * Fillet fit: a curved face clears a round's thin end pieces only by a chord (#324) The fan test shrank each piece by the curved faces' tolerance; the thin pieces at the arc's ends vanished, so a hole wall 0.3 mm into a round beside it was missed and the round failed to build instead of offering the radius that fits (issue_324_tests). Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: bherbruck --- crates/kernel/src/blend_fit.rs | 12 +++++- crates/kernel/src/issue_1080_tests.rs | 57 +++++++++++++++++++++++---- 2 files changed, 60 insertions(+), 9 deletions(-) diff --git a/crates/kernel/src/blend_fit.rs b/crates/kernel/src/blend_fit.rs index e0c7a3516..3cb6a4a5d 100644 --- a/crates/kernel/src/blend_fit.rs +++ b/crates/kernel/src/blend_fit.rs @@ -365,13 +365,19 @@ enum Clash { /// `strict`, when it comes within the chord of one (the surface may then be inside it). fn first_clash(sel: &Selection, size: Size, strict: bool) -> Option { let wedges: Vec> = sel.frames.iter().map(|f| f.as_ref().and_then(|f| f.wedge(size))).collect(); + // What each blend changes: for a round only the fan between its edge and its arc, a part of + // the wedge. A face inside the wedge but beyond the arc (the inside round of a wall, when the + // outside one is a concentric round) is on the ball's side, left as it is. + let changes: Vec>> = sel.frames.iter().map(|f| f.as_ref().and_then(|f| f.pieces(size))).collect(); // Planar faces are exact in the mesh; curved ones are within the chord. let flat = (sel.size * 1e-7).max(1e-9); let curved = if strict { -sel.chord } else { sel.chord * 2.0 }; // Planar faces beside an edge lie in its wedge's side planes: outside it means further. let out = (sel.size * 1e-6).max(1e-8); - for (i, (f, w)) in sel.frames.iter().zip(&wedges).enumerate() { + for (i, ((f, w), changed)) in sel.frames.iter().zip(&wedges).zip(&changes).enumerate() { let (Some(f), Some(w)) = (f, w) else { continue }; + // Without its pieces (or for a chamfer, whose one piece is the wedge) the wedge counts. + let changed = changed.as_deref().unwrap_or_default(); let hit = sel.tris.iter().filter(|(_, face)| !f.allowed.contains(face)).any(|(t, face)| { let eps = if sel.planar.get(*face).copied().unwrap_or(false) { flat } else { curved }; // The other blended edges this face runs along or ends them trim it back. @@ -383,7 +389,11 @@ fn first_clash(sel: &Selection, size: Size, strict: bool) -> Option { .filter(|(j, (fj, _))| *j != i && fj.as_ref().is_some_and(|fj| fj.allowed.contains(face))) .filter_map(|(_, (_, wj))| wj.as_ref()) .collect(); + // The pieces near the arc's ends are thin: a curved face only goes clear of them + // when its mesh stays a chord outside, or a sliver into the round is missed (#324). + let fan = if sel.planar.get(*face).copied().unwrap_or(false) { flat } else { -sel.chord }; reaches_inside_beyond(t, &w.planes, eps, &trimmed, out) + && (changed.len() <= 1 || changed.iter().any(|p| reaches_inside_beyond(t, &p.planes, fan, &trimmed, out))) }); if hit { return Some(Clash::Face); diff --git a/crates/kernel/src/issue_1080_tests.rs b/crates/kernel/src/issue_1080_tests.rs index 4d3f66484..e7ac18c55 100644 --- a/crates/kernel/src/issue_1080_tests.rs +++ b/crates/kernel/src/issue_1080_tests.rs @@ -95,21 +95,27 @@ fn a_result_that_removes_more_than_the_blend_is_refused() { assert!(m.contains("more than the chamfer can"), "{m}"); } -/// #1668: a box shelled outward 2 mm, open at the bottom. R5 on its top outer edge alone would -/// reach past the sharp inside corner 2 mm away; with the inside edge rounded in the same -/// fillet, that corner is filled, and the two build as one feature as they do one after the -/// other: the outer round takes (1 - π/4) · 25 mm² along 104 mm, the inner one adds it along -/// 100 mm. +/// #1668: a box shelled outward 2 mm, open at the bottom. R5 on its top outer edge alone leaves +/// the sharp inside corner 2 mm away on its ball's side, 0.76 mm inside the round; it reaches +/// the corner only past 2√2 / (√2 - 1) ≈ 6.83 mm. With the inside edge rounded in the same +/// fillet, the two build as one feature as they do one after the other: the outer round takes +/// (1 - π/4) · 25 mm² along 104 mm, the inner one adds it along 100 mm. #[test] fn rounds_on_both_sides_of_a_wall_build_as_one_fillet() { let outer = box_solid(Vec3::new(-52.0, -32.0, 0.0), Vec3::new(52.0, 32.0, 42.0)).unwrap(); let shelled = cut(&outer, [-50.0, -30.0, -1.0], [50.0, 30.0, 40.0]); let (out_edge, in_edge) = (Vec3::new(0.0, 32.0, 42.0), Vec3::new(0.0, 30.0, 40.0)); - let m = too_large(crate::fillet(&shelled, &[out_edge], 5.0)); - assert!(m.contains("runs past the faces beside the edge"), "{m}"); + let section = (1.0 - std::f64::consts::FRAC_PI_4) * 25.0; + let alone = crate::fillet(&shelled, &[out_edge], 5.0).unwrap(); + assert!(alone.validity().is_empty(), "{:?}", alone.validity()); + let want = shelled.volume_at(0.01).unwrap() - section * 104.0; + assert!((crate::measure(&alone).unwrap().volume - want).abs() < 1e-4 * want); + let m = too_large(crate::fillet(&shelled, &[out_edge], 7.0)); + let largest: f64 = m.rsplit("that fits is ").next().and_then(|t| t.trim_end_matches(" mm").parse().ok()).unwrap_or(0.0); + let limit = 2.0 * 2f64.sqrt() / (2f64.sqrt() - 1.0); + assert!(largest <= limit && largest > limit - 0.5, "{m}"); let both = crate::fillet(&shelled, &[out_edge, in_edge], 5.0).unwrap(); assert!(both.validity().is_empty(), "{:?}", both.validity()); - let section = (1.0 - std::f64::consts::FRAC_PI_4) * 25.0; let want = shelled.volume_at(0.01).unwrap() - section * 104.0 + section * 100.0; let v = crate::measure(&both).unwrap().volume; assert!((v - want).abs() < 1e-4 * want, "{v} vs {want}"); @@ -119,3 +125,38 @@ fn rounds_on_both_sides_of_a_wall_build_as_one_fillet() { let m = too_large(crate::fillet(&shelled, &[out_edge, in_edge], 7.0)); assert!(m.contains("the largest radius that fits"), "{m}"); } + +/// A shell 3 mm thick bent over like an upside-down U: 60 wide, 20 long, 50 high, its top +/// plate from z = 47 to 50 and its walls from x = 0 to 3 and 57 to 60. +fn bent_shell() -> Body { + let b = box_solid(Vec3::new(0.0, 0.0, 0.0), Vec3::new(60.0, 20.0, 50.0)).unwrap(); + cut(&b, [3.0, -1.0, -1.0], [57.0, 21.0, 47.0]) +} + +/// The corner left by a round of radius `r` on a 90° edge, per unit length. +fn corner(r: f64) -> f64 { + r * r * (1.0 - std::f64::consts::FRAC_PI_4) +} + +/// An outside round concentric with the inside one keeps the wall 3 mm thick: the inside round +/// lies inside the outside one's wedge, but on its ball's side of the arc, which the round +/// leaves as it is. It used to be refused as running into other geometry. +#[test] +fn outside_round_concentric_with_the_inside_round_of_a_wall_fits() { + let s = bent_shell(); + let inside = [Vec3::new(3.0, 10.0, 47.0), Vec3::new(57.0, 10.0, 47.0)]; + let outside = [Vec3::new(0.0, 10.0, 50.0), Vec3::new(60.0, 10.0, 50.0)]; + let a = crate::fillet(&s, &inside, 15.0).unwrap(); + let b = crate::fillet(&a, &outside, 18.0).unwrap(); + assert!(b.validity().is_empty(), "{:?}", b.validity()); + // The inside rounds fill their corners, the outside ones take theirs away. + let want = s.volume_at(0.01).unwrap() + 2.0 * 20.0 * (corner(15.0) - corner(18.0)); + let got = b.volume_at(0.01).unwrap(); + assert!((got - want).abs() < 1e-3 * want, "{got} for {want}"); + // Larger, the outside round's centre moves off the inside one's: it runs into the hollow + // where its arc crosses the inside round's, at r = (18√2 - 15) / (√2 - 1) ≈ 25.24 mm. + let m = too_large(crate::fillet(&a, &outside, 30.0)); + let largest: f64 = m.rsplit("that fits is ").next().and_then(|t| t.trim_end_matches(" mm").parse().ok()).unwrap_or(0.0); + let limit = (18.0 * 2f64.sqrt() - 15.0) / (2f64.sqrt() - 1.0); + assert!(largest <= limit && largest > limit - 0.5, "{m}"); +} From 42e991069f2d216be57e522c64ae3c5d39c690f0 Mon Sep 17 00:00:00 2001 From: fkirill Date: Mon, 19 Oct 2026 23:09:11 +0300 Subject: [PATCH 088/225] Fix shelling revolved barrels (#2421) (#2486) * claim: #2421 * claim: #2421 * Fix shelling circular-meridian barrels (#2421) --- ROADMAP.md | 5 +- crates/kernel/src/offset.rs | 12 ++-- crates/kernel/src/polyhedron.rs | 82 ++++++++++++++++++++++++- crates/kernel/src/surface_kind.rs | 2 + crates/kernel/tests/shell_barrel.rs | 92 +++++++++++++++++++++++++++++ 5 files changed, 185 insertions(+), 8 deletions(-) create mode 100644 crates/kernel/tests/shell_barrel.rs diff --git a/ROADMAP.md b/ROADMAP.md index b4fc0c9c0..c0739fc14 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -459,10 +459,11 @@ completed drawings publish atomically. The browser still exports synchronously. and author occurrence paths retain the chosen placements; missing/split faces refuse rather than retarget. General free-form profiles, seams, stepped cylinders and other curved surfaces remain unsupported. STEP round-trip and independent radial/volume checks cover this subset. -- Shell and offset faces work on bodies of planes, cylinders, cones and spheres (convex or not: +- Shell and offset faces work on bodies of planes, cylinders, cones, spheres and tori (convex or not: filleted boxes, bosses, domes, countersinks; corners where four or more planes meet, such as a floor falling to a drain, as long as the corner's edges are all convex or all concave); draft on convex planar bodies and on walls (planes, cylinders → cones) between caps; lofts through three or more sections are smooth (B-spline sides through every section), two - sections ruled. + sections ruled. Circular-meridian barrels retain curved inner walls through either axial + opening (#2421). - Sketch corner tools: fillet and all three chamfer modes pick a connected corner even when its endpoint overlaps the fixed origin or a loose point. Ordinary drawing still snaps to diff --git a/crates/kernel/src/offset.rs b/crates/kernel/src/offset.rs index 7dd0c2490..b5ef68c79 100644 --- a/crates/kernel/src/offset.rs +++ b/crates/kernel/src/offset.rs @@ -28,8 +28,9 @@ pub(crate) enum Surf { /// outward normal points away from the axis. Cone { v: Vec3, a: Vec3, half: f64, convex: bool }, /// Axis point and unit axis, the tube's centre circle (radius `big` at height `h` along the - /// axis) and the tube radius; `convex` when the outward normal points away from the tube's - /// centre. + /// axis) and the tube radius; `big` is negative on the inner sheet of a spindle torus, + /// whose meridian circle's centre lies across the axis. `convex` when the outward normal + /// points away from the tube's centre. Torus { o: Vec3, a: Vec3, big: f64, h: f64, r: f64, convex: bool }, } @@ -292,9 +293,10 @@ fn torus_of(f: &mt::Face, s: &[(Vec3, Vec3)], tol: f64) -> Option { } let x = crate::polyhedron::solve3_pub(m, rhs)?; let (big, h, r) = (x[0], x[1], x[2]); - // (A tube wider than its circle, a spindle torus, is fine: blends use its outer part, where - // each point's tube centre is the one on its own side of the axis.) - if !(big > 1e-9 && r.abs() > 1e-9) { + // A spindle torus also has an inner sheet: a barrel revolved from an arc whose + // centre is across the axis. Its signed ring radius is negative; retain that sign + // so distances, normals and the moved meridian use the centre on the opposite side. + if !(big.abs() > 1e-9 && r.abs() > 1e-9) { return None; } let t = Surf::Torus { o, a, big, h, r: r.abs(), convex: r > 0.0 }; diff --git a/crates/kernel/src/polyhedron.rs b/crates/kernel/src/polyhedron.rs index 35e20477a..94c52b153 100644 --- a/crates/kernel/src/polyhedron.rs +++ b/crates/kernel/src/polyhedron.rs @@ -9,7 +9,7 @@ use solidcraft_geom::{Plane, Vec3}; use truck_modeling::{self as mt, builder}; use crate::body::{Body, Solid, from_p3, p3, v3}; -use crate::history::{EdgeOrigin, FaceOrigin, FaceProv, History}; +use crate::history::{Change, EdgeOrigin, FaceOrigin, FaceProv, History}; use crate::record; use crate::{KernelError, Result, guard}; @@ -490,6 +490,9 @@ fn shell_planar(b: &Body, open: &[Vec3], thickness: f64) -> Result { "the rim would have no thickness: an open face meets a round of radius {r:.4} mm tangentially, and the shell is {thickness:.4} mm thick (make the round smaller than the thickness)" ))); } + if let Some(shell) = shell_barrel(&healed, &opened, thickness)? { + return Ok(record::after(shell, &healed, &record::counts(&[b]))); + } let margin = thickness + size * 0.05; shell_opened(b, &healed, open, &opened, thickness, margin).map_err(|e| match rim_without_thickness(&healed, &opened, thickness, false) { Some(r) => unsupported_shell(&format!( @@ -499,6 +502,83 @@ fn shell_planar(b: &Body, open: &[Vec3], thickness: f64) -> Result { }) } +/// A convex circular-meridian barrel between two axial caps. Sew its exact inset walls +/// to the original walls at annular rims: a Boolean of the two spindle sheets cannot +/// reliably find their cap intersections, and sweeping an inset cap makes a cylindrical +/// lip that cuts away part of the curved wall. +fn shell_barrel(b: &Body, opened: &[usize], thickness: f64) -> Result> { + use crate::offset::Surf; + if b.solid.boundaries().len() != 1 || b.face_count() > 256 { + return Ok(None); + } + let faces: Vec = b.solid.face_iter().cloned().collect(); + let tol = (b.size() * 1e-7).max(1e-9) * 100.0; + let surfs: Option> = faces.iter().map(|f| crate::offset::surf_of(f, tol)).collect(); + let Some(surfs) = surfs else { return Ok(None) }; + let Some((centre, axis, big, radius)) = surfs.iter().find_map(|s| match *s { + Surf::Torus { o, a, big, h, r, convex: true } if big < -tol => Some((o + a * h, a, big, r)), + _ => None, + }) else { + return Ok(None); + }; + let mut caps = Vec::new(); + for (i, s) in surfs.iter().enumerate() { + match *s { + Surf::Torus { o, a, big: ring, h, r, convex: true } + if (o + a * h).dist(centre) < tol && a.dot(axis).abs() > 1.0 - 1e-9 && (ring - big).abs() < tol && (r - radius).abs() < tol => {} + Surf::Plane { n, d } if n.dot(axis).abs() > 1.0 - 1e-9 && faces.get(i).is_some_and(|f| f.boundaries().len() == 1) => { + caps.push((i, (d - n.dot(centre)) / n.dot(axis), n.dot(axis))); + } + _ => return Ok(None), + } + } + if caps.len() != 2 || opened.iter().any(|i| !caps.iter().any(|c| c.0 == *i)) { + return Ok(None); + } + caps.sort_by(|a, b| a.1.total_cmp(&b.1)); + let (Some(&(lower, lo, down)), Some(&(upper, hi, up))) = (caps.first(), caps.get(1)) else { return Ok(None) }; + if down >= 0.0 || up <= 0.0 { + return Ok(None); + } + let lo = lo + if opened.contains(&lower) { 0.0 } else { thickness }; + let hi = hi - if opened.contains(&upper) { 0.0 } else { thickness }; + let inner_radius = radius - thickness; + if lo >= hi || inner_radius <= 0.0 || [lo, hi].iter().any(|z| inner_radius * inner_radius - z * z <= big * big) { + return Err(KernelError::Invalid("shell thickness leaves no barrel cavity".into())); + } + let cavity = offset_planar(b, |i, _| if opened.contains(&i) { 0.0 } else { -thickness })?; + let history = cavity.history().ok_or_else(|| unsupported_shell("the barrel cavity has no face history"))?; + // Every wall must still be the one offset of its source, in source order. No collapsed + // faces or changed topology can be sewn by this construction. + if cavity.face_count() != faces.len() + || history.faces.iter().enumerate().any(|(i, f)| f.origins.as_slice() != [FaceOrigin::Face { operand: 0, face: i }]) + { + return Err(unsupported_shell("the barrel cavity changed topology")); + } + let inner: Vec = cavity.solid.face_iter().cloned().collect(); + let mut out = Vec::new(); + let mut provenance = Vec::new(); + for (i, outer) in faces.iter().enumerate() { + let inset = inner.get(i).ok_or_else(|| unsupported_shell("the barrel cavity lost a face"))?; + if opened.contains(&i) { + let mut wires = outer.absolute_boundaries().to_vec(); + wires.extend(inset.absolute_boundaries().iter().map(|w| w.inverse())); + let mut rim = mt::Face::try_new(wires, outer.surface()).map_err(|e| KernelError::Failed(format!("shell rim: {e}")))?; + if !outer.orientation() { + rim.invert(); + } + out.push(rim); + provenance.push(record::from_face(0, i, Change::Modified)); + } else { + out.extend([outer.clone(), inset.inverse()]); + provenance.extend([record::from_face(0, i, Change::Kept), record::generated(vec![FaceOrigin::Offset { operand: 0, face: i }])]); + } + } + let solid = Solid::try_new(vec![out.into()]).map_err(|e| KernelError::Failed(format!("shell barrel: {e}")))?; + let copies = record::edges_by_identity(&cavity, history).filter_map(|(id, origins)| origins.into_iter().next().map(|o| (id, o))).collect(); + record::attach(Body::new(solid)?, &[record::Operand::new(b)], Some(provenance), copies).map(Some) +} + /// The radius of a convex round (cylinder or torus) that meets an open face tangentially and /// is at least `thickness`: the cavity's wall then passes through the rim where the round meets /// the open face, leaving nothing between them. diff --git a/crates/kernel/src/surface_kind.rs b/crates/kernel/src/surface_kind.rs index ee72bf1cd..c601536a3 100644 --- a/crates/kernel/src/surface_kind.rs +++ b/crates/kernel/src/surface_kind.rs @@ -33,6 +33,8 @@ pub enum FaceSurface { radius: f64, }, /// Centre of the ring, its axis, the ring (major) and tube (minor) radii. + /// `major` is signed: negative on a spindle torus's inner sheet, whose tube centre + /// lies across the axis from the face (a revolved barrel). Torus { center: Vec3, axis: UnitVec3, diff --git a/crates/kernel/tests/shell_barrel.rs b/crates/kernel/tests/shell_barrel.rs new file mode 100644 index 000000000..718d626f3 --- /dev/null +++ b/crates/kernel/tests/shell_barrel.rs @@ -0,0 +1,92 @@ +//! #2421: shelling a circular-meridian barrel must retain its curved wall through the rim. + +use std::f64::consts::PI; + +use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2, Vec3}; +use solidcraft_kernel::history::FaceOrigin; +use solidcraft_kernel::*; + +const RADIUS: f64 = 24.0; +const CENTRE: f64 = -10.0; +const HALF_HEIGHT: f64 = 13.4; + +fn barrel() -> Body { + let angle = (HALF_HEIGHT / RADIUS).asin(); + let end_radius = CENTRE + RADIUS * angle.cos(); + let region = Region2 { + outer: Loop2 { + segs: vec![ + Seg2::Line { a: Vec2::ZERO, b: Vec2::new(end_radius, 0.0) }, + Seg2::Arc { center: Vec2::new(CENTRE, HALF_HEIGHT), radius: RADIUS, start: -angle, sweep: 2.0 * angle }, + Seg2::Line { a: Vec2::new(end_radius, 2.0 * HALF_HEIGHT), b: Vec2::new(0.0, 2.0 * HALF_HEIGHT) }, + Seg2::Line { a: Vec2::new(0.0, 2.0 * HALF_HEIGHT), b: Vec2::ZERO }, + ], + }, + holes: vec![], + }; + let plane = Plane::new(Vec3::ZERO, Vec3::X, Vec3::Z).unwrap(); + revolve(&plane, &[region], Vec2::ZERO, Vec2::Y, 2.0 * PI).unwrap().pop().unwrap() +} + +// Integral of pi * (CENTRE + sqrt(r^2 - (z-HALF_HEIGHT)^2))^2. +fn integral(r: f64, z: f64) -> f64 { + let u = z - HALF_HEIGHT; + PI * ((CENTRE * CENTRE + r * r) * u - u.powi(3) / 3.0 + CENTRE * (u * (r * r - u * u).sqrt() + r * r * (u / r).asin())) +} + +fn check_volume(body: &Body, lo: f64, hi: f64) { + let want = integral(RADIUS, 2.0 * HALF_HEIGHT) - integral(RADIUS, 0.0) - (integral(RADIUS - 2.0, hi) - integral(RADIUS - 2.0, lo)); + let volume = measure(body).unwrap().volume; + assert!((volume - want).abs() < want * 1e-3, "{volume} vs {want}"); +} + +#[test] +fn shell_of_a_revolved_barrel() { + let barrel = barrel(); + let side = (0..barrel.face_count()) + .find_map(|i| match face_surface(&barrel, i) { + Some(s @ FaceSurface::Torus { major, minor, .. }) if (major - CENTRE).abs() < 1e-6 && (minor - RADIUS).abs() < 1e-6 => Some(s), + _ => None, + }) + .expect("barrel side is the inner sheet of a spindle torus"); + assert!(side.nearest(Vec3::new(15.0, 0.0, HALF_HEIGHT)).unwrap().dist(Vec3::new(14.0, 0.0, HALF_HEIGHT)) < 1e-6); + let result = shell(&barrel, &[Vec3::new(0.0, 0.0, 2.0 * HALF_HEIGHT)], 2.0).unwrap(); + assert!(result.validity().is_empty(), "{:?}", result.validity()); + assert_eq!(result.shell_count(), 1); + let mesh = result.tessellate(0.005).unwrap(); + assert!(mesh.contains(Vec3::new(0.0, 0.0, 1.0)), "closed floor"); + assert!(!mesh.contains(Vec3::new(0.0, 0.0, 3.0)), "open cavity"); + assert!(mesh.contains(Vec3::new(13.0, 0.0, HALF_HEIGHT)), "barrel wall"); + assert!(!mesh.contains(Vec3::new(11.0, 0.0, HALF_HEIGHT)), "inside wall"); + assert!(mesh.contains(Vec3::new(8.0, 0.0, 26.7)), "curved wall reaches the rim without a cylindrical lip cutting it away"); + check_volume(&result, 2.0, 2.0 * HALF_HEIGHT); + let history = result.history().expect("exact shell face history"); + assert_eq!(history.operands, 1); + assert_eq!(history.faces.iter().filter(|f| matches!(f.origins.as_slice(), [FaceOrigin::Offset { operand: 0, .. }])).count(), 4); + let step = step_export(&[&result], "barrel shell").unwrap(); + let imported = step_import(&step).unwrap(); + assert_eq!(imported.bodies.len(), 1); + let round_trip = &imported.bodies.first().unwrap().body; + assert!(round_trip.validity().is_empty()); + check_volume(round_trip, 2.0, 2.0 * HALF_HEIGHT); +} + +#[test] +fn barrel_shell_opens_either_or_both_caps_and_refuses_a_vanished_cavity() { + let barrel = barrel(); + for both in [false, true] { + let mut opened = vec![Vec3::ZERO]; + if both { + opened.push(Vec3::new(0.0, 0.0, 2.0 * HALF_HEIGHT)); + } + let result = shell(&barrel, &opened, 2.0).unwrap(); + assert!(result.validity().is_empty()); + let mesh = result.tessellate(0.005).unwrap(); + assert!(!mesh.contains(Vec3::new(0.0, 0.0, 1.0))); + assert_eq!(mesh.contains(Vec3::new(0.0, 0.0, 25.8)), !both); + check_volume(&result, 0.0, 2.0 * HALF_HEIGHT - if both { 0.0 } else { 2.0 }); + } + for thickness in [11.0, 24.0] { + assert!(shell(&barrel, &[Vec3::ZERO], thickness).is_err()); + } +} From 72601e678a02d231fb0bef6885dd3bb2a13ae8f5 Mon Sep 17 00:00:00 2001 From: vandang890615 <107316509+vandang890615@users.noreply.github.com> Date: Tue, 20 Oct 2026 03:09:36 +0700 Subject: [PATCH 089/225] i18n: add Vietnamese (vi) localization support (#2915) * i18n: add Vietnamese (vi) localization support Add Vietnamese (vi) message catalog with 1,583 translated keys covering CAD modeling commands, UI dialogs, timeline, analysis tools, and AI agent chat. Register VIETNAMESE catalog in ui-egui/src/i18n.rs and add unit test verifying translations, labels, and dynamic browser naming. * chore: attribute Vietnamese locale and sort catalog * i18n: fix corrupted and half-English strings in Vietnamese catalog * i18n: polish residual command and UI translations in Vietnamese catalog --- ATTRIBUTION.md | 1 + assets/locales/vi.json | 1585 ++++++++++++++++++++++++++++++++++++ crates/ui-egui/src/i18n.rs | 23 + 3 files changed, 1609 insertions(+) create mode 100644 assets/locales/vi.json diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 3c649e1ae..f07c4e4f9 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -102,6 +102,7 @@ Editable drawing code, native projects and shipped exports are collected under ` | assets/locales/pt-BR.json | DuBearte | Brazilian Portuguese translation of the English catalog, contributed upstream | MIT OR Apache-2.0 | | assets/locales/tr.json | macrulz54 | Turkish translation of the English catalog, contributed upstream | MIT OR Apache-2.0 | | assets/locales/uk.json | Igor Bronovskyi (BrunIF) | Ukrainian translation of the English catalog, contributed upstream | MIT OR Apache-2.0 | +| assets/locales/vi.json | vandang890615 | Vietnamese translation of the English catalog, contributed upstream | MIT OR Apache-2.0 | | assets/locales/zh.json | SolidCraft contributors | Original SolidCraft resource data or drawing code, collected without redesign | MIT OR Apache-2.0 | | assets/materials/library.rs | SolidCraft contributors | Original SolidCraft resource data or drawing code, collected without redesign | MIT OR Apache-2.0 | | assets/platforms/linux/ai.storyteller.solidcraft.desktop | PhotoCraft / SolidCraft contributors | PhotoCraft packaging templates (https://github.com/storytold/photocraft), adapted for SolidCraft | Apache-2.0 | diff --git a/assets/locales/vi.json b/assets/locales/vi.json new file mode 100644 index 000000000..623e5e343 --- /dev/null +++ b/assets/locales/vi.json @@ -0,0 +1,1585 @@ +{ + "0 turns it off": "0: tắt tính năng này", + "1. Open GitHub draft below, then paste the report copied to your clipboard.": "1. Mở bản nháp GitHub bên dưới, sau đó dán báo cáo đã sao chép vào bộ nhớ tạm.", + "1. Open GitHub draft below. Your title and report will be filled in.": "1. Mở bản nháp GitHub bên dưới. Tiêu đề và báo cáo sẽ được tự động điền.", + "2. Attach your screenshot: copy and paste it, or save and upload the PNG.": "2. Đính kèm ảnh chụp màn hình: sao chép và dán, hoặc lưu và tải lên tệp PNG.", + "3. Click Submit new issue on GitHub to send your report.": "3. Nhấp vào 'Submit new issue' trên GitHub để gửi báo cáo.", + "A new configuration, a copy of the active one": "Cấu hình mới, sao chép từ cấu hình hiện tại", + "AI": "AI", + "About SolidCraft": "Giới thiệu SolidCraft", + "Acceleration": "Gia tốc", + "Active": "Đang kích hoạt", + "Active rule": "Quy tắc đang kích hoạt", + "Add": "Thêm", + "Add Key": "Thêm phím tắt", + "Add Mid Radius": "Thêm bán kính giữa", + "Add Row": "Thêm hàng", + "Add condition": "Thêm điều kiện", + "Against": "So với", + "Alignment": "Căn chỉnh", + "All Sketch Points": "Tất cả điểm phác thảo", + "All components": "Tất cả cụm chi tiết", + "All open designs": "Tất cả thiết kế đang mở", + "Allowed expressions, separated by semicolons": "Các biểu thức hợp lệ, phân tách bằng dấu chấm phẩy", + "Also deletes": "Đồng thời xóa", + "Angle 2": "Góc 2", + "Animate": "Mô phỏng chuyển động", + "Appearance name": "Tên vật liệu bề mặt", + "Applied Radius": "Bán kính áp dụng", + "Apply To": "Áp dụng cho", + "Apply to selection": "Áp dụng cho đối tượng đã chọn", + "Arc length": "Chiều dài cung tròn", + "Area": "Diện tích", + "Attachment": "Mối liên kết", + "BOUNDARY SURFACE": "BỀ MẶT BIÊN DẠNG", + "BROWSER": "CÂY ĐỐI TƯỢNG", + "Bend Line Position": "Vị trí đường chấn", + "Bend Position": "Vị trí chấn", + "Bend Radius": "Bán kính chấn uốn", + "Bends": "Các vị trí chấn", + "Body": "Thân khối", + "Boundary": "Biên dạng bao", + "Bounding box": "Hộp bao ngoài", + "CSV or JSON: updates existing parameters, adds new ones": "CSV hoặc JSON: cập nhật tham số hiện có, thêm tham số mới", + "Capture All Positions": "Chụp lại tất cả vị trí", + "Catch Direction": "Hướng chốt gài", + "Cells": "Ô lưới", + "Center X": "Tâm X", + "Center Y": "Tâm Y", + "Center of mass": "Trọng tâm", + "Centre to centre": "Khoảng cách tâm - tâm", + "Chamfer Type": "Kiểu vát mép", + "Check collisions": "Kiểm tra va chạm", + "Checked": "Đã chọn", + "Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.": "Chọn một mặt phẳng mới. Hình học và kích thước phác thảo được giữ nguyên trong hệ tọa độ 2D.", + "Circumference": "Chu vi", + "Close draft": "Đóng bản nháp", + "Collisions": "Va chạm", + "Colour": "Màu sắc", + "Component1": "Cụm chi tiết 1", + "Configuration": "Cấu hình", + "Configuration rules": "Quy tắc cấu hình", + "Construction": "Đường dựng hình (nét đứt)", + "Contact": "Tiếp xúc", + "Contact sets": "Tập hợp tiếp xúc", + "Continuity": "Độ liên tục", + "Copy Error Message": "Sao chép thông báo lỗi", + "Copy Warning Message": "Sao chép thông báo cảnh báo", + "Copy all licences": "Sao chép tất cả giấy phép", + "Copy diagnostic information": "Sao chép thông tin chẩn đoán", + "Copy report": "Sao chép báo cáo", + "Copy screenshot": "Sao chép ảnh chụp màn hình", + "Corner Relief": "Rãnh thoát góc chấn", + "Corner Relief Shape": "Hình dạng rãnh thoát góc chấn", + "Counterbore depth": "Độ sâu lỗ khoét loe (Counterbore)", + "Countersink angle": "Góc vát miệng lỗ (Countersink)", + "Create Issue — review draft": "Tạo Issue — xem lại bản nháp", + "Cross curves": "Đường cong giao cắt", + "Cube": "Khối lập phương", + "Current orthographic view (1:1 mm)": "Góc nhìn trực giao hiện tại (1:1 mm)", + "Current perspective view": "Góc nhìn phối cảnh hiện tại", + "Curvature (G2)": "Độ cong (G2)", + "Customize Toolbar": "Tùy biến thanh công cụ", + "Delete all": "Xóa tất cả", + "Delete rule": "Xóa quy tắc", + "Delete the row": "Xóa hàng", + "Delete the set": "Xóa tập hợp", + "Delete this parameter": "Xóa tham số này", + "Density": "Khối lượng riêng", + "Designs you open or save appear here.": "Các thiết kế bạn mở hoặc lưu sẽ xuất hiện tại đây.", + "Determined by To Object. Choose Angle to edit the angular extent.": "Được xác định theo Đến đối tượng (To Object). Chọn Góc để chỉnh sửa góc mở rộng.", + "Direction": "Hướng", + "Discard": "Hủy bỏ thay đổi", + "Do not export hidden edges": "Không xuất nét khuất", + "Don't ask again": "Không hỏi lại nữa", + "Double-click to rename": "Nhấp đúp để đổi tên", + "Double-clicking the middle button in the view: Home (the home view, framing what is shown), Fit (frame what is shown, keeping the orientation) or nothing": "Nhấp đúp chuột giữa trong khung nhìn: Chuẩn (Home - góc nhìn chuẩn, bao trọn mô hình), Vừa vặn (Fit - bao trọn mô hình, giữ nguyên hướng nhìn) hoặc Không làm gì", + "Drive Joint": "Dẫn động khớp nối", + "Duration": "Thời lượng", + "Edges": "Các cạnh", + "Edit Profile Sketch": "Chỉnh sửa phác thảo biên dạng", + "Enable rule": "Bật quy tắc", + "Enabled": "Đã kích hoạt", + "Explode": "Phân rã", + "Explode Text": "Phân rã văn bản", + "Export Animation…": "Xuất hoạt cảnh…", + "Export Current View as DXF": "Xuất góc nhìn hiện tại dạng DXF", + "Export Current View as DXF…": "Xuất góc nhìn hiện tại dạng DXF…", + "Export DXF…": "Xuất DXF…", + "Export hidden edges as dashed lines": "Xuất nét khuất dưới dạng đường nét đứt", + "Extents": "Phạm vi kéo dài", + "Face": "Bề mặt", + "Face attachment lost": "Mất liên kết bề mặt", + "Faces": "Các bề mặt", + "Faces / edges / vertices": "Bề mặt / Cạnh / Đỉnh", + "Favourite": "Yêu thích", + "Files from many CAD programs have Y up, so they open lying on their back here (Z up).": "Tệp từ nhiều phần mềm CAD có trục Y hướng lên, nên khi mở ở đây (trục Z hướng lên) mô hình sẽ nằm ngang.", + "Filter": "Bộ lọc", + "Find in Browser": "Tìm trong cây đối tượng", + "Flat": "Trải phẳng", + "Flat size": "Kích thước phôi phẳng", + "Follow camera (Look At sketches)": "Đi theo camera (Nhìn vuông góc phác thảo)", + "Follow the camera (Look At sketches)": "Đi theo camera (Nhìn vuông góc phác thảo)", + "Font": "Phông chữ", + "Full Length": "Toàn bộ chiều dài", + "Grid": "Lưới tọa độ", + "Height": "Chiều cao", + "Hidden edges": "Nét khuất", + "Holes": "Lỗ", + "Holes (edges on them)": "Lỗ (các cạnh trên lỗ)", + "Home view": "Góc nhìn chuẩn (Home)", + "In This Design": "Trong thiết kế này", + "In place (surfaces)": "Tại chỗ (các bề mặt)", + "In plane": "Trong mặt phẳng", + "Inside": "Bên trong", + "Interferes": "Giao thoa va chạm", + "Issue title": "Tiêu đề vấn đề", + "Joint Origin1": "Gốc khớp nối 1", + "Keep Tools": "Giữ lại công cụ cắt", + "Later": "Để sau", + "Leave it": "Giữ nguyên", + "Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "Liên kết bề mặt kiểu cũ. Gán lại vào một bề mặt hợp lệ sẽ tạo liên kết chính xác.", + "Length": "Chiều dài", + "Length units": "Đơn vị đo chiều dài", + "Letter Spacing": "Khoảng cách chữ", + "Library": "Thư viện", + "Line Spacing": "Khoảng cách dòng", + "Loop": "Vòng lặp kín", + "Margin": "Lề biên", + "Mass": "Khối lượng", + "Material": "Vật liệu", + "Max": "Tối đa", + "Mid Radius": "Bán kính giữa", + "Middle double-click": "Nhấp đúp chuột giữa", + "Min": "Tối thiểu", + "Mitre": "Góc vát chéo (Mitre)", + "Modeled": "Mô hình hóa", + "More toolbar panels": "Thêm bảng thanh công cụ", + "Motion": "Chuyển động", + "Move Type": "Kiểu di chuyển", + "Move earlier": "Di chuyển lên trước", + "Move later": "Di chuyển xuống sau", + "Name": "Tên", + "Nearest": "Gần nhất", + "New study": "Nghiên cứu mới", + "No crash reports.": "Không có báo cáo sự cố.", + "No matching appearances": "Không có màu sắc/vật liệu phù hợp", + "No visible bodies to export.": "Không có thân khối hiển thị nào để xuất.", + "None": "Không có", + "Normal to sketch": "Vuông góc với phác thảo", + "Not available yet": "Chưa khả dụng", + "Notch": "Rãnh khía chữ V", + "Opacity": "Độ mờ đục", + "Open GitHub draft": "Mở bản nháp trên GitHub", + "Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "Phần mềm CAD 3D tham số mã nguồn mở viết bằng Rust. Giấy phép MIT HOẶC Apache-2.0.", + "Other side": "Phía bên kia", + "Outside": "Bên ngoài", + "Overall length": "Chiều dài tổng thể", + "Parameter values": "Giá trị tham số", + "Pass through": "Đi xuyên qua", + "Path": "Đường dẫn", + "Per Edge": "Theo từng cạnh", + "Pick the tool bodies": "Chọn các thân khối làm công cụ cắt", + "Picked": "Đã chọn", + "Picked point": "Điểm đã chọn", + "Place at the origin instead": "Đặt tại gốc tọa độ", + "Playback": "Phát lại", + "Plot": "Vẽ đồ thị", + "Position": "Vị trí", + "Position (0 to 1)": "Vị trí (0 đến 1)", + "Position (G0)": "Vị trí liên tục (G0)", + "Position along the edge, 0 at the start end, 1 at the other": "Vị trí dọc theo cạnh, 0 tại điểm đầu, 1 tại điểm cuối", + "Preferences › Design turns the offer back on": "Tùy chọn cài đặt › Thiết kế sẽ bật lại lời nhắc này", + "Preview Row": "Xem trước hàng", + "Preview leaves the current design unchanged.": "Xem trước giữ nguyên thiết kế hiện tại không đổi.", + "Profiles/Curves": "Biên dạng / Đường cong", + "Projection": "Phép chiếu", + "Quantity": "Số lượng", + "RECENT": "GẦN ĐÂY", + "RULED SURFACE": "MẶT KẺ (RULED SURFACE)", + "Radius Fit": "Bán kính vừa vặn", + "Ratio": "Tỷ lệ", + "Reattach selected face": "Gắn lại bề mặt đã chọn", + "Recover": "Khôi phục", + "Recover unsaved design?": "Khôi phục thiết kế chưa lưu?", + "Rectangular": "Hình chữ nhật", + "Reference face": "Bề mặt tham chiếu", + "Remove Tools": "Loại bỏ công cụ cắt", + "Remove from list": "Xóa khỏi danh sách", + "Remove override": "Hủy bỏ ghi đè", + "Remove private design details or paths before sharing.": "Xóa chi tiết thiết kế bảo mật hoặc đường dẫn trước khi chia sẻ.", + "Remove screenshot": "Xóa ảnh chụp màn hình", + "Remove the column": "Xóa cột", + "Remove the track": "Xóa rãnh dẫn", + "Remove this point": "Xóa điểm này", + "Report a bug — review a screenshot and open a GitHub draft": "Báo cáo sự cố — xem lại ảnh chụp màn hình và mở bản nháp trên GitHub", + "Reset Toolbar": "Đặt lại thanh công cụ", + "Restore outer boundary": "Khôi phục biên dạng bao ngoài", + "Restore the inherited component or physical material appearance": "Khôi phục vẻ ngoài kế thừa từ cụm chi tiết hoặc vật liệu vật lý", + "Result": "Kết quả", + "Retake screenshot": "Chụp lại màn hình", + "Reverse": "Đảo chiều", + "Reverse Direction": "Đảo ngược hướng", + "Revert": "Hoàn nguyên", + "Revert All Positions": "Hoàn nguyên tất cả vị trí", + "Revert Position": "Hoàn nguyên vị trí", + "Review the report and screenshot before opening GitHub.": "Xem lại báo cáo và ảnh chụp màn hình trước khi mở GitHub.", + "Rim Edge": "Cạnh mép vành", + "Roll History Marker Here": "Cuộn mốc lịch sử tới đây", + "Round": "Bo tròn", + "Rule": "Quy tắc", + "Save Rule": "Lưu quy tắc", + "Save the study as an animated GIF, seen as the viewport shows it": "Lưu nghiên cứu chuyển động thành ảnh GIF động, theo đúng góc nhìn hiện tại", + "Saved preview. Geometry is being checked before editing.": "Đã lưu bản xem trước. Hình học đang được kiểm tra trước khi chỉnh sửa.", + "Scale factor": "Hệ số tỷ lệ", + "Search": "Tìm kiếm", + "Search commands": "Tìm kiếm lệnh", + "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Chọn đối tượng khác: giữ nút chuột trái đứng yên trên mô hình (hoặc nhấp chuột phải › Chọn đối tượng khác…) để liệt kê mọi đối tượng dưới con trỏ; nhấp lại vào cùng vị trí đó để chọn đối tượng kế tiếp. Nhấp đúp chuột giữa để về Góc nhìn chuẩn (Tùy chọn cài đặt › Điều hướng).", + "Select bodies (a face picks its body)": "Chọn thân khối (chọn một mặt sẽ chọn cả thân khối)", + "Select bodies or faces instead": "Chọn thân khối hoặc bề mặt thay thế", + "Selection filter": "Bộ lọc chọn đối tượng", + "Semantic faces share their appearance across instances.": "Các bề mặt ngữ nghĩa dùng chung màu sắc bề mặt giữa các bản thể.", + "Send your report on GitHub": "Gửi báo cáo của bạn trên GitHub", + "Shape": "Hình dạng", + "Show Agent Cursor": "Hiển thị con trỏ của AI Agent", + "Show in folder": "Hiển thị trong thư mục", + "Show the pointer an AI agent moves (#35)": "Hiển thị con trỏ do AI Agent điều khiển (#35)", + "Signed axes": "Các trục có dấu (+/-)", + "Size": "Kích thước", + "Sketch constraints": "Ràng buộc phác thảo", + "Sketch curves": "Đường cong phác thảo", + "Sketch dimensions": "Kích thước phác thảo", + "Sketch geometry and profiles": "Hình học và biên dạng phác thảo", + "Sketch plane has no body-face attachment.": "Mặt phẳng phác thảo không có liên kết với bề mặt thân khối.", + "Sketch points": "Điểm phác thảo", + "Slot width": "Bề rộng rãnh then", + "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft đã đóng trước khi các thiết kế này được lưu. Bạn có thể mở bản tự động lưu gần nhất của chúng.", + "Speed": "Tốc độ", + "Stand it up": "Dựng đứng đối tượng", + "Stand it up: a quarter turn about X, as one Move feature you can undo.": "Dựng đứng đối tượng: xoay 90° quanh trục X, dưới dạng một tính năng Di chuyển có thể hoàn tác.", + "Stand this part up?": "Dựng đứng chi tiết này lên?", + "Step": "Bước", + "Steps": "Các bước", + "Study": "Nghiên cứu", + "Style": "Kiểu hiển thị", + "Suppressed": "Bị tạm nén", + "Swap Ends": "Hoán đổi hai đầu", + "Tangent (G1)": "Tiếp tuyến (G1)", + "Tangent Chain": "Chuỗi tiếp tuyến", + "Tear": "Xé rách mép chấn", + "The dashed sketch is a saved plane guide. Select a new face to repair the attachment.": "Phác thảo nét đứt là đường dẫn mặt phẳng đã lưu. Hãy chọn một bề mặt mới để sửa lại liên kết.", + "The saved author occurrence is missing. Select a valid author placement before rebinding.": "Bản thể tác giả đã lưu bị thiếu. Hãy chọn một vị trí tác giả hợp lệ trước khi gán lại.", + "Then": "Thì", + "These features will be deleted:": "Các tính năng sau sẽ bị xóa:", + "These features will fail:": "Các tính năng này sẽ bị lỗi:", + "Thickness Outside": "Độ dày hướng ra ngoài", + "Thin": "Thành mỏng", + "Thin Extrude": "Đùn thành mỏng", + "This child is shared. Deleting it removes it from every copy of its parent.": "Đối tượng con này được dùng chung. Việc xóa nó sẽ xóa khỏi mọi bản sao của đối tượng cha.", + "This child is shared. Position changes apply to every copy of its parent.": "Đối tượng con này được dùng chung. Thay đổi vị trí sẽ áp dụng cho mọi bản sao của đối tượng cha.", + "This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "Bề mặt này không thể tạo liên kết bền vững. Hãy chọn bề mặt khác hoặc sử dụng mặt phẳng cố định.", + "To Offset": "Tới khoảng dời (Offset)", + "Tolerance": "Dung sai", + "Too close": "Quá gần", + "Turn off section analysis before exporting the view.": "Tắt phân tích mặt cắt trước khi xuất khung nhìn.", + "Type": "Kiểu", + "UNTRIM": "HỦY CẮT TỈA (UNTRIM)", + "Updating the preview": "Đang cập nhật hình xem trước", + "Use active author placement": "Sử dụng vị trí tác giả đang kích hoạt", + "Use fixed plane": "Sử dụng mặt phẳng cố định", + "Use saved fixed plane": "Sử dụng mặt phẳng cố định đã lưu", + "Use selected face as fixed plane": "Sử dụng bề mặt đã chọn làm mặt phẳng cố định", + "VIEW": "GÓC NHÌN", + "Value": "Giá trị", + "Velocity": "Vận tốc", + "Vertices": "Các đỉnh", + "View navigator": "Khối điều hướng góc nhìn", + "Visible bodies only. Curves use line segments (0.01 mm tolerance).": "Chỉ các thân khối hiển thị. Đường cong sử dụng các đoạn thẳng (dung sai 0,01 mm).", + "Volume": "Thể tích", + "Wall": "Thành vách", + "Wall Location": "Vị trí thành vách", + "Wall Thickness": "Độ dày thành vách", + "When": "Khi", + "Width": "Bề rộng", + "Will fail": "Sẽ phát sinh lỗi", + "angle, height": "góc, chiều cao", + "appearance.dielectric_ior": "Chỉ số khúc xạ điện môi (IOR)", + "appearance.metallic": "Độ kim loại", + "appearance.pbr_help": "Xem bề mặt này trong chế độ Kết xuất hoặc ảnh PNG sản phẩm. Không có khúc xạ hay truyền sáng.", + "appearance.pbr_opaque": "PBR không trong suốt", + "appearance.roughness": "Độ nhám bề mặt", + "appearance.surface_response": "Phản hồi bề mặt", + "browser.body_name": "Thân khối{number}", + "browser.component_name": "Cụm chi tiết{number}", + "browser.parameters": "Bảng tham số ({count})", + "browser.precision": "Độ chính xác: {precision}", + "browser.sketch_name": "Phác thảo{number}", + "browser.units": "Đơn vị: {units}", + "cam.flat": "Bề mặt phẳng", + "cam.follower": "Con đội cam", + "cam.knife": "Cạnh sắc (Knife edge)", + "cam.needs_joints": "cần một khớp quay và một khớp trượt hoặc khớp lắc", + "cam.roller": "Con lăn cam", + "cam.roller_pick": "Con lăn cam (tùy chọn)", + "cam.tip_pick": "Đầu tiếp xúc cam (tùy chọn)", + "cmd.appearance_assign": "Vẻ ngoài / Màu sắc", + "cmd.appearance_library": "Thư viện màu sắc bề mặt", + "cmd.appearance_list": "Danh sách màu sắc bề mặt", + "cmd.body_rename": "Đổi tên thân khối", + "cmd.browser_group": "Tạo nhóm mới", + "cmd.browser_move": "Di chuyển mục trong cây đối tượng", + "cmd.browser_order": "Sắp xếp các mục trong cây đối tượng", + "cmd.browser_rename_group": "Đổi tên nhóm", + "cmd.browser_ungroup": "Hủy nhóm", + "cmd.browser_visibility": "Hiển thị/Ẩn", + "cmd.canvas_calibrate": "Hiệu chuẩn hình ảnh Canvas", + "cmd.canvas_decal": "Dán đề can (Decal)", + "cmd.canvas_delete": "Xóa Canvas", + "cmd.canvas_edit": "Chỉnh sửa hình ảnh Canvas", + "cmd.canvas_insert": "Chèn hình ảnh Canvas", + "cmd.component_activate": "Kích hoạt cụm chi tiết", + "cmd.component_break_link": "Ngắt liên kết cụm chi tiết", + "cmd.component_capture_position": "Lưu vị trí cụm chi tiết", + "cmd.component_create": "Tạo mới Cụm chi tiết", + "cmd.component_delete": "Xóa Cụm chi tiết", + "cmd.component_from_bodies": "Tạo cụm chi tiết từ các thân khối", + "cmd.component_insert_design": "Chèn thiết kế vào cụm", + "cmd.component_links": "Danh sách liên kết", + "cmd.component_list": "Danh sách cụm chi tiết", + "cmd.component_move_bodies": "Di chuyển các thân khối vào cụm chi tiết", + "cmd.component_move_sketches": "Di chuyển các phác thảo vào cụm chi tiết", + "cmd.component_paste_new": "Dán Tạo mới", + "cmd.component_properties": "Thuộc tính cơ lý của cụm chi tiết", + "cmd.component_rename": "Đổi tên cụm chi tiết", + "cmd.component_revert_position": "Hoàn nguyên vị trí cụm", + "cmd.component_unlock": "Mở khóa nội dung cụm", + "cmd.component_update_links": "Cập nhật liên kết", + "cmd.config_activate": "Kích hoạt cấu hình", + "cmd.config_column": "Cột cấu hình", + "cmd.config_configure": "Định cấu hình", + "cmd.config_preview": "Xem trước cấu hình", + "cmd.config_row": "Hàng cấu hình", + "cmd.config_rule": "Quy tắc cấu hình", + "cmd.config_rules": "Danh sách quy tắc cấu hình", + "cmd.config_table": "Hiển thị bảng cấu hình", + "cmd.construct_axis_edge": "Trục đi qua cạnh", + "cmd.construct_axis_normal_to_face": "Trục vuông góc với bề mặt", + "cmd.construct_axis_through_cylinder": "Trục qua hình trụ/nón/xuyến", + "cmd.construct_axis_two_planes": "Trục giao giữa hai mặt phẳng", + "cmd.construct_axis_two_points": "Trục đi qua hai điểm", + "cmd.construct_plane_along_path": "Mặt phẳng dọc theo đường dẫn", + "cmd.construct_plane_midplane": "Mặt phẳng ở giữa (Midplane)", + "cmd.construct_plane_perpendicular": "Vuông góc Mặt phẳng", + "cmd.construct_plane_tangent": "Tiếp tuyến Mặt phẳng", + "cmd.construct_plane_three_points": "Mặt phẳng đi qua ba điểm", + "cmd.construct_plane_two_edges": "Mặt phẳng đi qua hai cạnh", + "cmd.construct_point_along_path": "Điểm dọc theo đường dẫn", + "cmd.construct_point_center": "Điểm tại tâm đường tròn/khối cầu/hình xuyến", + "cmd.construct_point_edge_plane": "Điểm giao giữa cạnh và mặt phẳng", + "cmd.construct_point_three_planes": "Điểm giao giữa ba mặt phẳng", + "cmd.construct_point_two_edges": "Điểm giao giữa hai cạnh", + "cmd.construct_point_vertex": "Điểm tại đỉnh", + "cmd.contact_check": "Kiểm tra tiếp xúc", + "cmd.contact_create": "Tập hợp tiếp xúc mới", + "cmd.contact_disable_all": "Tắt tất cả tiếp xúc", + "cmd.contact_edit": "Chỉnh sửa tập hợp tiếp xúc", + "cmd.contact_enable_all": "Bật tất cả tiếp xúc", + "cmd.contact_enable_sets": "Bật tập hợp tiếp xúc", + "cmd.contact_list": "Danh sách tập hợp tiếp xúc", + "cmd.diagnostics_crash_report": "Báo cáo sự cố sập ứng dụng", + "cmd.diagnostics_crash_reports": "Danh sách báo cáo sự cố", + "cmd.diagnostics_crash_reports_clear": "Xóa báo cáo sự cố ứng dụng", + "cmd.diagnostics_crash_test": "Kiểm tra cơ chế sập ứng dụng", + "cmd.doc_recover": "Khôi phục thiết kế", + "cmd.doc_recovery_discard": "Hủy thiết kế khôi phục", + "cmd.doc_recovery_list": "Danh sách thiết kế có thể khôi phục", + "cmd.document_inspect": "Kiểm tra thiết kế", + "cmd.document_metadata": "Thuộc tính thiết kế", + "cmd.document_metadata_remove": "Xóa thuộc tính thiết kế", + "cmd.document_metadata_set": "Thay đổi thuộc tính thiết kế", + "cmd.document_units": "Thay đổi đơn vị thiết kế", + "cmd.edit_checkpoint": "Điểm kiểm tra (Checkpoint)", + "cmd.edit_restore_checkpoint": "Khôi phục điểm kiểm tra", + "cmd.engine_commands": "Danh sách lệnh hệ thống", + "cmd.explode_create": "Tạo chế độ xem phân rã", + "cmd.explode_delete": "Xóa chế độ xem phân rã", + "cmd.explode_list": "Danh sách chế độ xem phân rã", + "cmd.explode_show": "Hiển thị chế độ xem phân rã", + "cmd.expr_evaluate": "Tính giá trị biểu thức", + "cmd.face_delete": "Xóa Bề mặt", + "cmd.file_export": "Xuất tệp", + "cmd.file_insert_mesh": "Chèn lưới đa giác (Mesh)", + "cmd.file_insert_step": "Chèn tệp STEP", + "cmd.file_save_mesh": "Lưu dưới dạng lưới đa giác", + "cmd.file_slicers": "Phần mềm cắt lớp đã cài đặt", + "cmd.inspect_accessibility": "Phân tích khả năng gia công tiếp cận", + "cmd.inspect_center_of_mass": "Trọng tâm", + "cmd.inspect_clearance": "Khoảng cách an toàn", + "cmd.inspect_compare": "So sánh các thân khối", + "cmd.inspect_continuity": "Phân tích độ liên tục mặt", + "cmd.inspect_curvature_comb": "Phân tích lược độ cong (Curvature Comb)", + "cmd.inspect_curvature_map": "Phân tích bản đồ độ cong (Curvature Map)", + "cmd.inspect_draft": "Phân tích góc thoát khuôn", + "cmd.inspect_environment_map": "Phân tích phản chiếu môi trường (Zebra Map)", + "cmd.inspect_interference": "Kiểm tra va chạm", + "cmd.inspect_isocurve": "Phân tích đường đẳng trị (Isocurve)", + "cmd.inspect_minimum_radius": "Phân tích bán kính tối thiểu", + "cmd.inspect_silhouette": "Phân tích đường bao bóng (Silhouette)", + "cmd.inspect_zebra": "Phân tích sọc ngựa vằn (Zebra)", + "cmd.joint_as_built": "Khớp nối theo vị trí hiện trạng", + "cmd.joint_cam": "Khớp Cam", + "cmd.joint_create": "Khớp nối cơ khí", + "cmd.joint_delete": "Xóa Khớp nối cơ khí", + "cmd.joint_drive": "Dẫn động các khớp nối", + "cmd.joint_edit": "Chỉnh sửa khớp nối", + "cmd.joint_gear": "Khớp bánh răng", + "cmd.joint_limits": "Giới hạn chuyển động khớp nối", + "cmd.joint_list": "Danh sách các khớp nối", + "cmd.joint_motion_link": "Liên kết truyền động", + "cmd.joint_origin": "Khớp nối cơ khí Gốc tọa độ", + "cmd.joint_rack_pinion": "Khớp thanh răng - bánh răng", + "cmd.joint_reach": "Điểm vươn tới (Reach Point)", + "cmd.joint_rigid_group": "Nhóm ngàm cứng (Rigid Group)", + "cmd.joint_screw": "Khớp trục vít", + "cmd.joint_solve": "Giải hệ thống khớp nối", + "cmd.library_apply": "Áp dụng mục thư viện cục bộ", + "cmd.library_export": "Xuất thư viện thiết kế", + "cmd.library_inspect": "Kiểm tra thư viện cục bộ", + "cmd.material_assign": "Gán vật liệu vật lý", + "cmd.material_create": "Tạo vật liệu vật lý mới", + "cmd.material_delete": "Xóa vật liệu vật lý", + "cmd.material_edit": "Chỉnh sửa vật liệu vật lý", + "cmd.material_list": "Danh sách vật liệu", + "cmd.material_properties_directional": "Mô đun đàn hồi theo hướng", + "cmd.material_properties_validate": "Xác thực dữ liệu thuộc tính vật liệu", + "cmd.mesh_convert": "Chuyển đổi lưới đa giác (Convert Mesh)", + "cmd.model_edges": "Danh sách các cạnh", + "cmd.model_faces": "Danh sách các bề mặt", + "cmd.model_threads": "Danh sách các đoạn ren", + "cmd.motion_delete": "Xóa nghiên cứu chuyển động", + "cmd.motion_export": "Xuất dữ liệu nghiên cứu chuyển động", + "cmd.motion_export_animation": "Xuất hoạt cảnh chuyển động", + "cmd.motion_interference": "Kiểm tra giao thoa trong chuyển động", + "cmd.motion_list": "Danh sách nghiên cứu chuyển động", + "cmd.motion_play": "Phát mô phỏng chuyển động", + "cmd.motion_plot": "Vẽ đồ thị chuyển động", + "cmd.motion_study": "Nghiên cứu chuyển động", + "cmd.motion_trace": "Quỹ đạo chuyển động", + "cmd.motion_trace_keep": "Giữ lại đường quỹ đạo chuyển động", + "cmd.occurrence_copy": "Dán (Bản thể)", + "cmd.occurrence_ground": "Cố định vị trí đối tượng", + "cmd.occurrence_move": "Di chuyển đối tượng", + "cmd.occurrence_properties": "Thuộc tính cơ lý của bản thể (Occurrence)", + "cmd.parameters_add": "Thêm tham số người dùng", + "cmd.parameters_change": "Thay đổi tham số", + "cmd.parameters_comment": "Thêm chú thích tham số", + "cmd.parameters_complete": "Hoàn tất biểu thức tham số", + "cmd.parameters_delete": "Xóa Tham số", + "cmd.parameters_export": "Xuất tệp Bảng tham số", + "cmd.parameters_favorite": "Đánh dấu tham số yêu thích", + "cmd.parameters_graph": "Biểu đồ quan hệ tham số", + "cmd.parameters_import": "Nhập tệp Bảng tham số", + "cmd.parameters_list": "Danh sách bảng tham số", + "cmd.parameters_move": "Di chuyển tham số", + "cmd.parameters_rename": "Đổi tên tham số", + "cmd.parameters_users": "Các đối tượng sử dụng tham số", + "cmd.parts_fastener": "Chèn chi tiết liên kết (Bu lông / Đai ốc)", + "cmd.parts_insert": "Chèn chi tiết tiêu chuẩn", + "cmd.parts_library": "Thư viện chi tiết tiêu chuẩn", + "cmd.parts_resize": "Đổi kích thước chi tiết", + "cmd.plastic_assign_rule": "Gán quy tắc nhựa kỹ thuật", + "cmd.plastic_boss": "Vấu bắt vít đúc nhựa (Boss)", + "cmd.plastic_lip": "Gờ rãnh khép mép (Lip/Groove)", + "cmd.plastic_manage_rules": "Quản lý quy tắc nhựa kỹ thuật", + "cmd.plastic_rest": "Vấu đỡ nhựa (Rest)", + "cmd.plastic_rules": "Danh sách quy tắc nhựa kỹ thuật", + "cmd.plastic_snap_fit": "Khớp gài bấm (Snap Fit)", + "cmd.render_backends": "Kết xuất hình ảnh Sauends", + "cmd.render_cancel": "Hủy bỏ Kết xuất hình ảnh", + "cmd.render_export": "Xuất hình ảnh kết xuất", + "cmd.render_preflight": "Kiểm tra yêu cầu kết xuất", + "cmd.render_scene": "Kiểm tra Kết xuất hình ảnh Khung cảnh", + "cmd.render_settings_apply": "Áp dụng Kết xuất hình ảnh Góc nhìn máy quay", + "cmd.render_settings_get": "Kết xuất hình ảnh Cài đặt", + "cmd.render_settings_set": "Lưu Kết xuất hình ảnh Cài đặt", + "cmd.render_start": "Bắt đầu kết xuất hình ảnh", + "cmd.render_status": "Tiến độ kết xuất hình ảnh", + "cmd.select_clear": "Hủy chọn tất cả", + "cmd.sheet_convert": "Chuyển thành kim loại tấm", + "cmd.sheet_export_bend_table": "Xuất bảng thông số chấn uốn (Bend Table)", + "cmd.sheet_export_dxf": "Xuất bản trải phẳng dạng DXF", + "cmd.sheet_flange": "Chấn gập mép tôn", + "cmd.sheet_flat_pattern": "Tạo bản trải phẳng", + "cmd.sheet_fold": "Gập tấm kim loại", + "cmd.sheet_hem": "Mép viền gấp đôi", + "cmd.sheet_manage_rules": "Quy tắc kim loại tấm", + "cmd.sheet_perforate": "Đục lỗ tấm kim loại", + "cmd.sheet_refold": "Gập lại tấm kim loại", + "cmd.sheet_rules": "Danh sách quy tắc kim loại tấm", + "cmd.sheet_unfold": "Trải phẳng tạm thời", + "cmd.sketch_arc_center_point": "Cung tròn xác định bởi tâm và điểm", + "cmd.sketch_arc_tangent": "Cung tròn tiếp tuyến", + "cmd.sketch_arc_three_point": "Cung tròn qua 3 điểm", + "cmd.sketch_auto_constrain": "Tự động gán ràng buộc", + "cmd.sketch_auto_constrain_from_datum": "Tự động gán ràng buộc từ chuẩn", + "cmd.sketch_auto_project": "Tự động chiếu các cạnh lên tham chiếu", + "cmd.sketch_blend_curve": "Đường cong nối mượt (Blend Curve)", + "cmd.sketch_chain": "Chuỗi đường phác thảo", + "cmd.sketch_chamfer_distance_angle": "Vát mép theo khoảng cách và góc", + "cmd.sketch_chamfer_equal_distance": "Bằng nhau Khoảng cách Vát mép", + "cmd.sketch_chamfer_two_distance": "Vát mép với 2 khoảng cách", + "cmd.sketch_circle_center": "Đường tròn xác định bởi tâm và đường kính", + "cmd.sketch_circle_three_point": "Đường tròn qua 3 điểm", + "cmd.sketch_circle_three_tangent": "Đường tròn tiếp xúc 3 đối tượng", + "cmd.sketch_circle_two_point": "Đường tròn qua 2 điểm", + "cmd.sketch_circle_two_tangent": "Đường tròn tiếp xúc 2 đối tượng", + "cmd.sketch_constrainer": "Bộ giải ràng buộc phác thảo", + "cmd.sketch_constraint_fix": "Cố định/UnCố định", + "cmd.sketch_constraint_midpoint": "Điểm chính giữa (Midpoint)", + "cmd.sketch_construction": "Nét thường/Đường dựng hình", + "cmd.sketch_copy": "Sao chép các thực thể phác thảo", + "cmd.sketch_cut": "Cắt các thực thể phác thảo", + "cmd.sketch_delete": "Xóa các thực thể phác thảo", + "cmd.sketch_dimension_text": "Di chuyển chữ số kích thước", + "cmd.sketch_drag": "Kéo hình học phác thảo", + "cmd.sketch_drag_end": "Kết thúc kéo phác thảo", + "cmd.sketch_draw_dimensioned": "Vẽ hình học phác thảo kèm kích thước", + "cmd.sketch_edit": "Chỉnh sửa phác thảo", + "cmd.sketch_edit_text": "Chỉnh sửa văn bản", + "cmd.sketch_export_dxf": "Lưu dưới dạng DXF", + "cmd.sketch_finish_auto_constrain": "Hoàn tất với tự động ràng buộc", + "cmd.sketch_fit_curves_to_section": "Khớp đường cong vào mặt cắt lưới", + "cmd.sketch_glyphs": "Biểu tượng ký hiệu ràng buộc", + "cmd.sketch_include_3d": "Bao gồm hình học 3D", + "cmd.sketch_infinite": "Đường thẳng vô hạn", + "cmd.sketch_insert_dxf": "Chèn tệp DXF", + "cmd.sketch_insert_svg": "Chèn tệp SVG", + "cmd.sketch_inspect": "Kiểm tra Phác thảo", + "cmd.sketch_intersection_curve": "Đường cong giao tuyến", + "cmd.sketch_isoparametric_curve": "Đường cong đẳng tham số", + "cmd.sketch_line3d": "Đường thẳng 3D", + "cmd.sketch_line_midpoint": "Đường thẳng từ trung điểm", + "cmd.sketch_loose_ends": "Các đầu mút tự do", + "cmd.sketch_loose_ends_tie": "Khóa các đầu mút tự do", + "cmd.sketch_move": "Di chuyển/Sao chép thực thể phác thảo", + "cmd.sketch_move3d": "Di chuyển điểm 3D", + "cmd.sketch_move_point": "Kéo điểm phác thảo", + "cmd.sketch_offset_break": "Hủy liên kết khoảng dời (Offset)", + "cmd.sketch_options": "Tùy chọn bảng phác thảo", + "cmd.sketch_paste": "Dán các thực thể phác thảo", + "cmd.sketch_point3d": "3D Điểm", + "cmd.sketch_polygon_circumscribed": "Đa giác ngoại tiếp", + "cmd.sketch_polygon_edge": "Đa giác theo cạnh (Edge Polygon)", + "cmd.sketch_polygon_inscribed": "Đa giác nội tiếp", + "cmd.sketch_project_to_surface": "Chiếu lên bề mặt", + "cmd.sketch_rectangle_center": "Hình chữ nhật từ tâm", + "cmd.sketch_rectangle_rounded": "Hình chữ nhật bo tròn góc", + "cmd.sketch_rectangle_three_point": "Hình chữ nhật qua 3 điểm", + "cmd.sketch_rectangle_two_point": "Hình chữ nhật qua 2 điểm", + "cmd.sketch_redefine": "Định nghĩa lại mặt phẳng phác thảo", + "cmd.sketch_slot_arc_center": "Rãnh then cung tròn từ tâm", + "cmd.sketch_slot_arc_three_point": "Rãnh then cung tròn qua 3 điểm", + "cmd.sketch_slot_center_point": "Rãnh then từ tâm", + "cmd.sketch_slot_center_to_center": "Rãnh then tâm - tâm", + "cmd.sketch_slot_overall": "Rãnh then toàn phần", + "cmd.sketch_snap": "Bắt điểm thông minh", + "cmd.sketch_solve": "Giải hệ ràng buộc phác thảo", + "cmd.sketch_spline3d": "Đường cong Spline 3D", + "cmd.sketch_spline_control_point": "Đường cong Spline qua điểm điều khiển", + "cmd.sketch_spline_control_point_5": "Đường cong Spline qua điểm điều khiển (Bậc 5)", + "cmd.sketch_spline_fit_point": "Đường cong Spline qua các điểm", + "cmd.sketch_spun_profile": "Biên dạng xoay tròn (Spun Profile)", + "cmd.sketch_toggle_driven": "Chuyển đổi kích thước tham chiếu (Driven Dimension)", + "cmd.solid_align": "Căn chỉnh thân khối", + "cmd.solid_boundary_fill": "Điền đầy biên dạng khối", + "cmd.solid_bounding_solid": "Tạo khối bao ngoài", + "cmd.solid_emboss": "Dập nổi (Emboss)", + "cmd.solid_move": "Di chuyển/Sao chép", + "cmd.solid_offset_face": "Khoảng dời (Offset) Bề mặt", + "cmd.solid_press_pull": "Kéo/Đẩy trực tiếp (Press Pull)", + "cmd.solid_remove": "Xóa thân khối", + "cmd.solid_replace_face": "Thay thế bề mặt", + "cmd.solid_rib": "Gân tăng cứng (Rib)", + "cmd.solid_split_face": "Chia tách bề mặt", + "cmd.solid_web": "Mạng lưới gân (Web)", + "cmd.surface_blend": "Bo nối mặt cong (Blend Surface)", + "cmd.surface_boundary": "Tạo mặt từ biên dạng (Boundary Surface)", + "cmd.surface_extrude": "Đùn mặt cong (Surface Extrude)", + "cmd.surface_fair": "Làm mịn mặt cong (Fair Surface)", + "cmd.surface_fillet": "Bo tròn mặt cong (Surface Fillet)", + "cmd.surface_loft": "Vuốt nối mặt cong (Surface Loft)", + "cmd.surface_match": "Khớp mặt cong (Match Surface)", + "cmd.surface_offset": "Tạo mặt song song cách đều (Offset Surface)", + "cmd.surface_patch": "Vá mặt cong (Patch)", + "cmd.surface_reverse_normal": "Đảo chiều pháp tuyến mặt", + "cmd.surface_revolve": "Xoay tròn tạo mặt cong (Surface Revolve)", + "cmd.surface_ruled": "Mặt kẻ (Ruled Surface)", + "cmd.surface_stitch": "Khâu mặt cong (Stitch)", + "cmd.surface_sweep": "Quét tạo mặt cong (Surface Sweep)", + "cmd.surface_thicken": "Tạo độ dày cho mặt cong", + "cmd.surface_unstitch": "Hủy khâu mặt cong (Unstitch)", + "cmd.surface_untrim": "Hủy cắt tỉa mặt cong (Untrim)", + "cmd.timeline_add": "Thêm tính năng đã ghi", + "cmd.timeline_compute_all": "Tính toán lại toàn bộ lịch sử", + "cmd.timeline_copy": "Sao chép tính năng", + "cmd.timeline_dependents": "Các tính năng phụ thuộc", + "cmd.timeline_export_script": "Xuất tập lệnh", + "cmd.timeline_inspect": "Kiểm tra tính năng", + "cmd.timeline_paste": "Dán tính năng", + "cmd.timeline_redefine": "Chỉnh sửa tính năng", + "cmd.timeline_rename": "Đổi tên tính năng", + "cmd.timeline_reorder": "Sắp xếp lại tính năng", + "cmd.timeline_roll_to": "Cuộn mốc lịch sử", + "cmd.timeline_rollback": "Di chuyển con trỏ lịch sử thiết kế", + "cmd.timeline_suppress": "Tạm nén tính năng", + "cmd.view_ambient_occlusion": "Đổ bóng che khuất môi trường (AO)", + "cmd.view_apply": "Áp dụng góc nhìn đã lưu", + "cmd.view_delete": "Xóa góc nhìn đã lưu", + "cmd.view_graphics_preset": "Cấu hình đồ họa định sẵn", + "cmd.view_list": "Danh sách góc nhìn đã lưu", + "cmd.view_navigate": "Điều hướng góc nhìn", + "cmd.view_rename": "Đổi tên góc nhìn đã lưu", + "cmd.view_save": "Tạo góc nhìn đã lưu mới", + "command name": "tên lệnh", + "coupling.gear_1": "Bánh răng 1", + "coupling.gear_1_pick": "Bánh răng 1 (tùy chọn)", + "coupling.gear_2": "Bánh răng 2", + "coupling.gear_2_pick": "Bánh răng 2 (tùy chọn)", + "coupling.internal": "Bánh răng trong", + "coupling.needs_turn_and_slide": "cần một khớp quay và một khớp trượt", + "coupling.needs_turns": "cần hai khớp quay", + "coupling.not_round": "không phải là bề mặt tròn", + "coupling.nut": "Đai ốc", + "coupling.picked": "đã chọn", + "coupling.pinion": "Bánh răng nhỏ (Pinion)", + "coupling.pinion_pick": "Bánh răng nhỏ (tùy chọn)", + "coupling.pitch": "Bước răng", + "coupling.rack": "Thanh răng", + "coupling.radius_1": "Bán kính 1", + "coupling.radius_2": "Bán kính 2", + "dialog.bodies_count": "{count} thân khối", + "dialog.clearance_invalid": "khoảng cách an toàn phải có chiều dài từ 0 trở lên", + "dialog.compute": "Tính toán", + "dialog.compute_again": "Tính toán lại", + "dialog.computing": "Đang tính toán… {seconds} s", + "dialog.could_not_be_checked": "không thể kiểm tra", + "dialog.custom_axis": "↖ Trục tùy chỉnh", + "dialog.edit_title": "CHỈNH SỬA {title}", + "dialog.select": "↖ Chọn", + "dialog.selected_count": "↖ {count} đã chọn", + "dialog.selection_guidance": "Chọn một mục đầu vào để thay đổi. Nhấp vào đối tượng đã chọn để bỏ chọn; Ctrl/Cmd-nhấp để bật/tắt chọn. Xem trước kết quả, sau đó nhấn OK.", + "dialog.selection_step": "{step} / {total}: Chọn {input}", + "dialog.step": "Bước", + "document.save_changes": "Lưu các thay đổi đối với {name}?", + "document.unsaved_changes": "{name} có các thay đổi chưa lưu. Nếu không lưu, các thay đổi sẽ bị mất.", + "drive.stopped_by_contact": "Đã dừng tại {value}: {a} sẽ xuyên qua {b}", + "drive.stopped_by_loop": "Đã dừng tại {value}: vòng lặp qua {joint} không thể khép kín thêm được nữa", + "drive.unconnected": "Không di chuyển gì: {part} không được nối với bất kỳ chi tiết cố định nào", + "dxf.cancel_wait": "Đang đợi quá trình xuất dừng…", + "dxf.cancelled": "Đã hủy xuất tệp DXF", + "dxf.cancelling": "Đang hủy xuất tệp DXF", + "dxf.exporting": "Đang xuất tệp DXF", + "dxf.invalid_tolerance": "Dung sai đường cong phải nằm trong khoảng từ 0.0001 đến 1 mm.", + "dxf.progress.index": "Đang chuẩn bị bề mặt (2/5)", + "dxf.progress.meshes": "Đang chuẩn bị lưới đa giác (1/5)", + "dxf.progress.occlusion": "Đang xử lý nét khuất (4/5)", + "dxf.progress.projection": "Đang chiếu hình học (3/5)", + "dxf.progress.write": "Đang ghi tệp DXF (5/5)", + "dxf.tolerance": "Dung sai đường cong", + "dxf.tolerance_help": "Chỉ áp dụng cho các thân khối hiển thị. Đường cong sử dụng các đoạn thẳng. Dung sai nhỏ hơn cho đường cong mịn hơn nhưng tốn nhiều thời gian và bộ nhớ hơn.", + "expression, e.g. 25 mm": "biểu thức, ví dụ: 25 mm", + "fits the face, e.g. M8": "vừa khít bề mặt, ví dụ M8", + "from the rule": "từ quy tắc", + "home.documentation": "Tài liệu hướng dẫn", + "home.in_this_browser": "trong trình duyệt này", + "home.missing": "thiếu", + "home.open": "Mở…", + "home.opened_days_ago": "Đã mở {count} ngày trước", + "home.opened_hours_ago": "Đã mở {count} giờ trước", + "home.opened_just_now": "Vừa mới mở", + "home.opened_minutes_ago": "Đã mở {count} phút trước", + "home.opening": "đang mở…", + "home.recent": "Gần đây", + "home.report_issue": "Báo cáo sự cố", + "home.samples": "Mẫu thiết kế", + "home.whats_new": "Có gì mới", + "install.button_tip": "Cài đặt SolidCraft dưới dạng ứng dụng: mở trong cửa sổ riêng và hoạt động ngoại tuyến", + "install.dock_1": "Chọn Tệp › Thêm vào Dock.", + "install.dock_2": "Nhấp vào Thêm.", + "install.dock_after": "SolidCraft sau đó sẽ mở trong cửa sổ riêng từ thanh Dock và hoạt động ngoại tuyến.", + "install.done": "Hoàn tất", + "install.home_screen_1": "Chạm vào Chia sẻ (trong menu … nếu không có trên thanh công cụ).", + "install.home_screen_2": "Chọn Thêm vào Màn hình chính.", + "install.home_screen_3": "Chạm vào Thêm.", + "install.home_screen_after": "SolidCraft sau đó sẽ mở từ biểu tượng trên Màn hình chính, không có thanh công cụ của Safari và hoạt động ngoại tuyến.", + "install.menu": "Cài đặt ứng dụng…", + "install.steps_intro": "Safari cài đặt ứng dụng web từ menu của chính nó:", + "install.title": "Cài đặt SolidCraft", + "joint.from_bodies_hint": "Mỗi thân khối được chọn sẽ được chuyển thành một cụm chi tiết mới riêng biệt và giữ nguyên vị trí hiện tại.", + "joint.one_body": "Cả hai điểm chọn đều nằm trên {body}. Vui lòng chọn điểm thứ hai trên chi tiết khác.", + "joint.one_component": "Các chi tiết này thuộc cùng một cụm chi tiết: {bodies}. Khớp nối điều khiển một cụm chi tiết so với cụm chi tiết khác, vì vậy mỗi chi tiết cần một cụm chi tiết riêng.", + "motion.checked_to": "Chỉ kiểm tra đến bước {step}: đã hết giới hạn tác vụ", + "motion.collision": "{a} · {b}: bước {steps}", + "motion.duration_hint": "giây (để trống: theo từng bước)", + "motion.no_collisions": "Không có va chạm trong suốt quá trình khảo sát", + "nav.touchpad.help": "Giữ Shift và di chuyển con trỏ để dời góc nhìn; giữ Alt/Option và di chuyển để xoay quanh tâm. Không cần nhấn nút chuột. Cuộn dọc để thu phóng.", + "nav.touchpad.label": "Bàn di chuột (Touchpad)", + "nav.touchpad.orbit": "Xoay quanh tâm (giữ Alt/Option và di chuyển; không cần nhấn chuột)", + "nav.touchpad.pan": "Dời góc nhìn (giữ Shift và di chuyển; không cần nhấn chuột)", + "nav.touchpad.scroll": "Bàn rê cảm ứng dùng thao tác cuộn dọc để thu phóng. Cài đặt dời góc nhìn bằng hai ngón tay được giữ cho các cấu hình khác.", + "nav.touchpad.zoom": "Thu phóng (cuộn dọc hoặc chụm ngón tay)", + "needs two joints": "cần hai khớp nối", + "new configuration": "cấu hình mới", + "new name": "tên mới", + "new parameter": "tham số mới", + "no hole": "không có lỗ", + "no interference": "không có giao thoa", + "no joint that moves yet": "chưa có khớp nối nào có thể chuyển động", + "no picture": "không có ảnh", + "none": "không có", + "pattern.alignment_2": "Căn chỉnh 2", + "pattern.alignment_hint": "Số lượng bao gồm cả bản gốc. Căn giữa sẽ cân bằng các bản sao; Đổi hướng sẽ chọn phía bổ sung cho tổng số chẵn.", + "pattern.direction_1": "Hướng 1", + "pattern.direction_2": "Hướng 2", + "pattern.flip_direction": "Đổi chiều hướng", + "pick a hole to seat it, or OK places it at the origin": "chọn một lỗ để lắp đặt, hoặc nhấn OK để đặt tại gốc tọa độ", + "pick one or two vertices, edges or faces": "chọn một hoặc hai đỉnh, cạnh hoặc bề mặt", + "render.background": "Hình nền khung cảnh", + "render.fit": "Thu phóng vừa sản phẩm", + "render.image_cancel": "Hủy bỏ Kết xuất hình ảnh", + "render.image_cancelled": "Đã hủy kết xuất hình ảnh", + "render.image_cancelling": "Đang hủy…", + "render.image_check": "Kiểm tra yêu cầu kết xuất", + "render.image_completed": "Hình ảnh đã sẵn sàng để xuất", + "render.image_encoding": "Đang mã hóa PNG", + "render.image_export": "Xuất tệp PNG", + "render.image_failed": "Kết xuất hình ảnh thất bại", + "render.image_height": "Chiều cao", + "render.image_help": "Hình xem trước CPU · PNG · độ trong suốt xấp xỉ", + "render.image_overwrite": "Ghi đè tệp hiện có", + "render.image_preparing": "Đang chuẩn bị hình ảnh", + "render.image_queued": "Đang chờ kết xuất", + "render.image_reduce": "Thử giảm kích thước hình ảnh hoặc đơn giản hóa khung cảnh.", + "render.image_running": "Đang kết xuất hình ảnh", + "render.image_stale": "Hình ảnh này sử dụng khung cảnh được chụp trước các thay đổi tiếp theo.", + "render.image_start": "Bắt đầu kết xuất", + "render.image_supported": "Yêu cầu kết xuất được hỗ trợ; hàng đợi và vùng nhớ sẽ được kiểm tra lại khi bắt đầu.", + "render.image_title": "Kết xuất hình ảnh", + "render.image_too_large": "Vượt quá giới hạn hình ảnh: tối đa 4096 pixel mỗi cạnh và 4.194.304 pixel tổng cộng.", + "render.image_transparent": "Nền trong suốt", + "render.image_unknown": "Trạng thái kết xuất không khả dụng", + "render.image_use_largest": "Sử dụng kích thước lớn nhất theo tỷ lệ này:", + "render.image_width": "Bề rộng", + "render.navigation_help": "Camera di chuyển tương tự như trong Thiết kế (Tùy chọn cài đặt › Điều hướng). Lưu thiết lập sẽ ghi lại camera hiện tại.", + "render.opaque_image_summary": "Xem trước PNG · PBR không trong suốt · trộn độ trong suốt", + "render.opaque_preview_help": "PBR không trong suốt và màu sắc đơn giản; trộn độ trong suốt. Khúc xạ, HDRI và kết xuất cuối cùng hiện chưa khả dụng.", + "render.perspective": "Camera phối cảnh", + "render.preview": "Xem trước tích hợp", + "render.preview_help": "Đổ bóng raster và trộn độ trong suốt. Khúc xạ, HDRI và kết xuất cuối cùng hiện chưa khả dụng.", + "render.reload_settings": "Tải lại cài đặt đã lưu", + "render.restore_camera": "Khôi phục camera đã lưu", + "render.return_design": "Quay lại thiết kế", + "render.save_setup": "Lưu thiết lập", + "render.setup_name": "Tên thiết lập", + "render.unavailable_preview": "Thiết lập này yêu cầu cấu hình xem trước hiện không khả dụng.", + "render.unsaved": "Các thay đổi xem trước chưa lưu", + "render.use_preview": "Sử dụng xem trước tích hợp", + "sample.bracket.about": "Mép chấn đáy với các mép chấn cạnh và đường viền gấp cuộn theo quy tắc 2 mm", + "sample.bracket.name": "Giá đỡ kim loại tấm", + "sample.enclosure.about": "Hộp làm mỏng vỏ có gờ chắn, vấu bắt vít, gờ đỡ và khớp gài bấm", + "sample.enclosure.name": "Vỏ hộp nhựa", + "sample.flange.about": "Moay-ơ và mặt bích với mảng xoay tròn được điều khiển bởi tham số", + "sample.flange.name": "Mặt bích bắt bu-lông", + "sample.hinge.about": "Hai cụm chi tiết và một khớp quay, được dẫn động đến 60°", + "sample.hinge.name": "Cụm bản lề", + "sample.plate.about": "Tấm tham số với các góc bo tròn, các lỗ và vấu lồi khoét lỗ", + "sample.plate.name": "Tấm mẫu", + "sample.vents.about": "Các rãnh then trong mảng chữ nhật: số hàng, số cột và bước rãnh là các tham số", + "sample.vents.name": "Tấm khe thông gió", + "settings.display_quality_note": "Mức độ chi tiết cao hơn giúp hiển thị các mặt cong và cạnh mượt mà hơn nhưng tốn nhiều thời gian tạo lưới hơn. Thiết lập này chỉ thay đổi vùng nhìn, không ảnh hưởng đến thiết kế hay dữ liệu xuất tệp.", + "settings.frame_rate_note": "Hiển thị số khung hình trên giây (FPS) ở góc dưới bên phải khung nhìn. Khi bật, khung nhìn sẽ vẽ lại liên tục.", + "settings.measure_axis_distances": "Hiển thị khoảng cách theo trục X/Y/Z", + "settings.measure_axis_distances_help": "Hiển thị kích thước thành phần theo các trục tọa độ cùng với khoảng cách tổng thể khi mở công cụ Đo lường.", + "settings.msaa_applies_on_restart": "Khử răng cưa sẽ áp dụng vào lần khởi động tiếp theo của SolidCraft", + "settings.msaa_reset": "{setting}: Mức {requested}× không được hỗ trợ bởi thiết bị đồ họa này; đã đặt về {reset}× (hỗ trợ: {supported}).", + "settings.msaa_unsupported": "Thiết bị đồ họa này không hỗ trợ", + "settings.reset_intro": "Các cài đặt sau không hoạt động trên máy tính này và có thể khiến SolidCraft không thể khởi động, vì vậy chúng đã được tự động điều chỉnh:", + "settings.reset_title": "Cài đặt đã được thay đổi", + "settings.supersampling_note": "Vẽ khung nhìn ở độ phân giải cao hơn rồi nén lại: giúp các cạnh, đường nét và lưới mượt mà hơn trên màn hình dưới 4K. Tính năng này tiêu tốn tài nguyên GPU: gấp khoảng 2,25 lần số điểm ảnh ở mức 1,5× và 4 lần ở mức 2×.", + "sketch.degrees_of_freedom": "{count} bậc tự do", + "sketch.draw_curves": "Vẽ dưới dạng {linetype}", + "sketch.make_selection": "Chuyển đổi vùng chọn sang {linetype}", + "sketch.open_ends": "Đầu hở: {count}", + "sketch.untied_ends": "Chưa khóa: {count}", + "sketch_text.align_center": "Căn giữa", + "sketch_text.align_left": "Trái", + "sketch_text.align_right": "Phải", + "sketch_text.bold": "In đậm", + "sketch_text.builtin_font": "{family} (tích hợp sẵn)", + "sketch_text.font_search": "Tìm kiếm phông chữ", + "sketch_text.italic": "In nghiêng", + "sketch_text.loading_fonts": "Đang tìm kiếm các phông chữ đã cài đặt…", + "sketch_text.on_path": "Văn bản đi theo đường dẫn: đường cong định vị văn bản", + "sketch_text.path_clear": "Gỡ văn bản khỏi đường cong dẫn", + "sketch_text.path_hint": "Đường cong phác thảo mà văn bản chạy theo: nhấp vào đây, sau đó chọn đường cong", + "sketch_text.use_font_file": "Sử dụng tệp phông chữ {path}", + "solid": "khối đặc", + "the parts library is not available": "thư viện chi tiết tiêu chuẩn hiện không khả dụng", + "thread.automatic_size": "Kích thước tự động", + "thread.designation": "Ký hiệu ren", + "thread.iso_metric": "Hệ mét ISO", + "thread.select_size": "Chọn kích thước", + "timeline.group": "Thư mục tính năng mới", + "timeline.move_many": "Di chuyển các mục trong lịch sử thiết kế", + "timeline.move_to_group": "Chuyển tính năng vào thư mục", + "timeline.rename_group": "Đổi tên thư mục tính năng", + "timeline.reorder_many": "Sắp xếp lại các tính năng", + "timeline.ungroup": "Xóa thư mục tính năng", + "to the face": "tới bề mặt", + "to the next face": "tới bề mặt tiếp theo", + "toolbar.image": "HÌNH ẢNH", + "toolbar.render": "KẾT XUẤT", + "toolbar.render_scene": "BỐI CẢNH", + "trace.points": "{count} điểm dọc theo đường dẫn", + "trace.stopped_by_contact": "Kết thúc tại mẫu {sample}: {a} sẽ xuyên qua {b}", + "trace.stopped_by_loop": "Kết thúc tại mẫu {sample}: vòng lặp qua {joint} không thể khép kín thêm được nữa", + "ui.1_degree_of_freedom": "1 bậc tự do", + "ui.3d_mouse_speed": "Tốc độ chuột 3D", + "ui.3d_mouse_windows": "Chuột 3D", + "ui.3d_sketch": "3D Phác thảo", + "ui.about": "Thông tin phiên bản", + "ui.activate": "Kích hoạt", + "ui.active_component": "Cụm chi tiết đang kích hoạt", + "ui.agent_chat": "Trò chuyện với AI Agent", + "ui.agent_chat_add": "Đính kèm tệp", + "ui.agent_chat_add_file": "Chọn một tệp…", + "ui.agent_chat_allow": "Cho phép", + "ui.agent_chat_allowed": "Đã cho phép", + "ui.agent_chat_answered": "Câu trả lời: {option}", + "ui.agent_chat_approval": "Cho phép AI thực hiện thao tác này?", + "ui.agent_chat_attach_view": "Đính kèm góc nhìn", + "ui.agent_chat_attach_view_tip": "Gửi kèm hình ảnh góc nhìn hiện tại trong tin nhắn", + "ui.agent_chat_attachable": "Hình ảnh, PDF, văn bản và tệp CAD", + "ui.agent_chat_auth_agent": "Đăng nhập với {name}", + "ui.agent_chat_auth_env": "Thiết lập {vars} trong biến môi trường của bạn rồi khởi động lại SolidCraft.", + "ui.agent_chat_auth_needed": "AI Agent yêu cầu bạn đăng nhập. Bạn đăng nhập trực tiếp với dịch vụ của AI; SolidCraft không bao giờ thấy mật khẩu hay khóa API của bạn.", + "ui.agent_chat_auth_none": "AI Agent không cung cấp phương thức đăng nhập tại đây: hãy đăng nhập theo hướng dẫn của dịch vụ đó.", + "ui.agent_chat_auth_retry": "Tôi đã đăng nhập: kết nối lại", + "ui.agent_chat_auth_terminal": "Chạy lệnh này trong cửa sổ dòng lệnh, sau đó nhấp Kết nối lại:", + "ui.agent_chat_auth_title": "Đăng nhập vào AI Agent", + "ui.agent_chat_cancel": "Hủy bỏ", + "ui.agent_chat_changes": "Thay đổi: {n}, trong 1 bước hoàn tác", + "ui.agent_chat_changes_of": "{n}/{limit} thay đổi", + "ui.agent_chat_close": "Đóng", + "ui.agent_chat_command": "Lệnh của AI Agent", + "ui.agent_chat_connect": "Kết nối", + "ui.agent_chat_copy": "Sao chép", + "ui.agent_chat_custom_hint": "Bất kỳ chương trình nào hỗ trợ giao thức Agent Client Protocol qua stdin và stdout. Không chạy qua shell hệ thống.", + "ui.agent_chat_denied": "Đã từ chối", + "ui.agent_chat_deny": "Từ chối", + "ui.agent_chat_desktop_only": "Tính năng trò chuyện với tác tử yêu cầu ứng dụng máy tính (Desktop).", + "ui.agent_chat_detecting": "Đang tìm kiếm AI Agent…", + "ui.agent_chat_dock": "Ghim vào bảng điều khiển bên", + "ui.agent_chat_dock_left": "Ghim sang bên trái", + "ui.agent_chat_dock_right": "Ghim sang bên phải", + "ui.agent_chat_drop_hint": "Thả tệp vào đây để đính kèm vào tin nhắn tiếp theo", + "ui.agent_chat_edit": "Chỉnh sửa", + "ui.agent_chat_exited": "Tác tử đã dừng.", + "ui.agent_chat_failed_start": "AI Agent không thể khởi động: {error}", + "ui.agent_chat_file_cad_not_read": "{name}: tệp CAD được nhập vào thiết kế, không đọc nội dung", + "ui.agent_chat_file_empty_picture": "{name}: tệp ảnh trống", + "ui.agent_chat_file_error": "{name}: {error}", + "ui.agent_chat_file_heic": "{name}: hình ảnh định dạng HEIC không thể đọc tại đây; hãy xuất sang JPEG hoặc PNG trước", + "ui.agent_chat_file_importing": "Đang nhập vào thiết kế…", + "ui.agent_chat_file_loading": "Đang đọc tệp…", + "ui.agent_chat_file_not_a_file": "{name}: không phải là tệp hợp lệ", + "ui.agent_chat_file_not_a_picture": "{name}: không phải là tệp ảnh", + "ui.agent_chat_file_not_utf8": "{name}: không phải văn bản chuẩn UTF-8", + "ui.agent_chat_file_picture_too_big": "{name}: tệp ảnh tối đa {max} MB", + "ui.agent_chat_file_text_too_big": "{name}: tệp văn bản tối đa {max} KB", + "ui.agent_chat_file_too_large": "{name}: kích thước quá lớn", + "ui.agent_chat_file_too_large_to_send": "{name}: quá lớn để gửi, ngay cả khi đã thu nhỏ", + "ui.agent_chat_file_unreadable_picture": "{name}: định dạng ảnh không thể đọc", + "ui.agent_chat_files": "Tệp đính kèm: {files}", + "ui.agent_chat_files_left_out": "Tối đa {max} tệp đính kèm trong một tin nhắn; đã bỏ qua: {files}", + "ui.agent_chat_files_loading": "Đang chờ đọc các tệp đính kèm", + "ui.agent_chat_files_max": "Tối đa {max} tệp trong một tin nhắn", + "ui.agent_chat_import_failed": "{name}: nhập tệp thất bại: {error}", + "ui.agent_chat_intro": "Trò chuyện với tác tử lập trình (AI agent) bạn đang dùng hoặc một điểm cuối mô hình bạn chọn. AI thao tác trên thiết kế đang mở thông qua các công cụ của SolidCraft: các thay đổi hiển thị ngay khi thực hiện và có thể hoàn tác theo từng bước cho mỗi tin nhắn. Các thao tác AI được phép thực hiện mà không cần hỏi được đặt trong Tùy chọn cài đặt > AI.", + "ui.agent_chat_key_in_env": "đã đặt khóa", + "ui.agent_chat_left": "Trái", + "ui.agent_chat_limit": "AI Agent đã đạt giới hạn {limit} thay đổi cho một tin nhắn. Hãy gửi tin nhắn tiếp theo để tiếp tục.", + "ui.agent_chat_minimize": "Thu nhỏ thành thanh công cụ", + "ui.agent_chat_model_tip": "Mô hình AI đang sử dụng. Lựa chọn của bạn sẽ được ghi nhớ cho Agent này.", + "ui.agent_chat_new": "Cuộc trò chuyện mới", + "ui.agent_chat_new_confirm": "Bắt đầu cuộc trò chuyện mới? Cuộc trò chuyện hiện tại sẽ bị xóa.", + "ui.agent_chat_new_yes": "Cuộc trò chuyện mới", + "ui.agent_chat_no_cli": "Không tìm thấy solidcraft-cli cạnh ứng dụng, vì vậy AI Agent không thể truy cập thiết kế.", + "ui.agent_chat_no_control": "Điểm cuối trò chuyện của tác tử không thể khởi động, vì vậy AI Agent không thể truy cập thiết kế.", + "ui.agent_chat_no_images": "AI Agent này không hỗ trợ tiếp nhận hình ảnh", + "ui.agent_chat_no_picture": "Không có hình ảnh trong bộ nhớ tạm", + "ui.agent_chat_none_found": "Không tìm thấy tác tử lập trình nào. Hãy cài đặt một trong các tác tử sau, rồi nhấn Làm mới:", + "ui.agent_chat_none_found_short": "Không tìm thấy tác tử nào", + "ui.agent_chat_not_installed": "Chưa cài đặt", + "ui.agent_chat_not_signed_in": "chưa đăng nhập", + "ui.agent_chat_own_window": "Cửa sổ riêng", + "ui.agent_chat_paste_picture": "Dán hình ảnh", + "ui.agent_chat_permission": "AI Agent yêu cầu thực thi: {title}", + "ui.agent_chat_pick": "AI Agent", + "ui.agent_chat_placeholder": "Yêu cầu AI Agent chỉnh sửa mô hình thiết kế…", + "ui.agent_chat_placeholder_busy": "Xếp hàng tin nhắn khi AI Agent hoàn thành (Ctrl+Enter: gửi ngay)", + "ui.agent_chat_pop_out": "Mở trong cửa sổ riêng để bạn có thể di chuyển sang màn hình khác", + "ui.agent_chat_privacy": "Không có dữ liệu nào được gửi đi bất cứ đâu ngoại trừ tới tác tử bạn chạy, theo tài khoản của chính bạn.", + "ui.agent_chat_privacy_note": "SolidCraft không gửi bất kỳ dữ liệu nào ra ngoài: AI Agent giao tiếp trực tiếp với dịch vụ bằng tài khoản của bạn. SolidCraft không bao giờ thấy hay lưu khóa/mật khẩu.", + "ui.agent_chat_queue": "Hàng đợi", + "ui.agent_chat_queue_full": "Quá nhiều tin nhắn đang chờ: hãy xóa bớt hoặc chờ AI hoàn thành.", + "ui.agent_chat_queued": "Đã vào hàng đợi", + "ui.agent_chat_queued_stopped": "Đã xếp hàng (đã dừng, chưa gửi)", + "ui.agent_chat_refresh": "Làm mới", + "ui.agent_chat_refused": "Không được phép đối với tác tử: {reason}", + "ui.agent_chat_remove": "Xóa khỏi hàng đợi", + "ui.agent_chat_remove_file": "Bỏ tệp này khỏi tin nhắn", + "ui.agent_chat_remove_imported": "Gỡ khỏi tin nhắn này; chi tiết vẫn nằm trong thiết kế (sử dụng Hoàn tác để xóa)", + "ui.agent_chat_right": "Phải (Hình chiếu cạnh)", + "ui.agent_chat_save": "Lưu", + "ui.agent_chat_send": "Gửi", + "ui.agent_chat_send_now": "Gửi ngay", + "ui.agent_chat_send_now_tip": "Dừng bước hiện tại của tác tử và gửi tin nhắn này ngay (Ctrl+Enter)", + "ui.agent_chat_side": "Vị trí bảng trò chuyện AI", + "ui.agent_chat_signed_in": "đã đăng nhập", + "ui.agent_chat_state_auth": "Cần đăng nhập", + "ui.agent_chat_state_busy": "Đang xử lý…", + "ui.agent_chat_state_exited": "Tác tử đã dừng", + "ui.agent_chat_state_off": "Chưa kết nối", + "ui.agent_chat_state_ready": "Sẵn sàng", + "ui.agent_chat_state_starting": "Đang khởi động…", + "ui.agent_chat_stop": "Dừng", + "ui.agent_chat_stop_tip": "Dừng tác tử và mọi tác vụ nó đã bắt đầu", + "ui.agent_chat_stop_turn_tip": "Dừng tác tử (Esc). Tin nhắn trong hàng đợi vẫn được giữ nguyên.", + "ui.agent_chat_turn_limit": "Số thay đổi tối đa mỗi tin nhắn", + "ui.agent_chat_undo_changes": "Hoàn tác các thay đổi này", + "ui.agent_chat_undo_label": "Trò chuyện AI: {message}", + "ui.agent_chat_undone": "(hoàn tácne)", + "ui.agent_chat_view_attached": "Đã đính kèm góc nhìn", + "ui.agent_cursor": "Con trỏ AI", + "ui.agent_cursor_speed": "Tốc độ con trỏ AI", + "ui.ai_add": "Thêm", + "ui.ai_add_agent": "Thêm AI Agent…", + "ui.ai_add_agent_title": "Thêm AI Agent", + "ui.ai_add_api": "API tương thích OpenAI", + "ui.ai_add_custom": "Lệnh tùy chỉnh", + "ui.ai_add_installed": "Tác tử đã cài đặt", + "ui.ai_add_installed_note": "Mục riêng của bạn cho một tác tử đã cài đặt, ví dụ với các tham số bổ sung. Các tác tử đã cài đặt sẽ được liệt kê riêng.", + "ui.ai_added": "đã thêm", + "ui.ai_agent_mode_tip": "Chế độ riêng của tác tử: các công cụ riêng của nó (shell dòng lệnh, sửa tệp) tuân theo chế độ này. Các công cụ của SolidCraft tuân theo quyền hạn trong Tùy chọn cài đặt > AI.", + "ui.ai_agents": "Danh sách AI Agent", + "ui.ai_always_allow": "Luôn cho phép", + "ui.ai_always_allow_tip": "Luôn cho phép công cụ {tool} cho Agent này từ nay về sau, không cần hỏi lại", + "ui.ai_always_allowed": "Luôn được phép", + "ui.ai_always_allowed_none": "Chưa có quyền nào được đặt luôn cho phép. Các câu trả lời 'Luôn cho phép' bạn chọn trong phần trò chuyện sẽ hiển thị tại đây.", + "ui.ai_auto_allowed": "Tự động cho phép: {title} ({why})", + "ui.ai_auto_mode": "cài đặt quyền hạn của bạn", + "ui.ai_auto_ours": "SolidCraft tự kiểm tra các công cụ nội bộ của mình", + "ui.ai_auto_remembered": "bạn đã chọn Luôn cho phép", + "ui.ai_bad_url": "Nhập địa chỉ URL bắt đầu bằng http:// hoặc https://", + "ui.ai_base_url": "URL cơ sở", + "ui.ai_button": "AI", + "ui.ai_copy_suffix": "sao chép", + "ui.ai_custom_url": "URL tùy chỉnh", + "ui.ai_default": "Mặc định", + "ui.ai_http_busy": "điểm cuối đang bận hoặc vượt quá giới hạn; vui lòng thử lại sau", + "ui.ai_http_key": "điểm cuối từ chối khóa API: hãy kiểm tra trong Tùy chọn cài đặt > AI", + "ui.ai_http_not_found": "không tìm thấy điểm cuối hoặc mô hình: hãy kiểm tra URL cơ sở và tên mô hình", + "ui.ai_key": "Khóa API", + "ui.ai_key_hint": "tùy chọn; lưu trữ bảo mật trong chuỗi khóa hệ thống", + "ui.ai_key_needs_https": "Khóa chỉ được gửi qua HTTPS, hoặc trực tiếp trên máy tính này.", + "ui.ai_key_note": "Được lưu an toàn trong Keychain hệ thống, không lưu trong cài đặt của SolidCraft. Để trống nếu dùng máy chủ cục bộ.", + "ui.ai_keychain_error": "Chuỗi khóa hệ thống từ chối: {error}", + "ui.ai_mode_all": "Cho phép tất cả", + "ui.ai_mode_all_note": "Không yêu cầu xác nhận trước. Báo cáo sự cố và các thư mục giới hạn vẫn được bảo vệ.", + "ui.ai_mode_all_warning": "Tác tử có thể lưu, ghi đè, xuất tệp và thay thế thiết kế của bạn mà không cần hỏi. Chỉ sử dụng chế độ này với tác tử bạn tin tưởng và trên các thiết kế đã được lưu.", + "ui.ai_mode_ask": "Hỏi mỗi lần", + "ui.ai_mode_ask_note": "Mọi thay đổi đối với thiết kế và mọi thao tác tệp đều cần bạn xác nhận Cho phép.", + "ui.ai_mode_edits": "Tự động cho phép chỉnh sửa mô hình", + "ui.ai_mode_edits_note": "Các lệnh tạo mô hình sẽ chạy mà không cần hỏi; các hành động lưu, mở, xuất và các thao tác tệp hoặc hủy hoại khác vẫn sẽ hỏi ý kiến bạn.", + "ui.ai_mode_global": "Theo cài đặt bên trên", + "ui.ai_model": "Mô hình AI", + "ui.ai_modes_scope": "Các cài đặt này áp dụng cho các công cụ của SolidCraft. Công cụ riêng của tác tử (shell hệ thống, chỉnh sửa tệp) tuân theo chế độ riêng của tác tử, được chọn trên thanh tiêu đề bảng điều khiển trò chuyện.", + "ui.ai_name": "Tên", + "ui.ai_need_command": "Nhập lệnh khởi chạy AI Agent", + "ui.ai_need_model": "Nhập tên mô hình AI", + "ui.ai_no_answer": "AI Agent không phản hồi kịp thời gian chờ", + "ui.ai_no_http": "Bản dựng này không thể kết nối tới các điểm cuối API", + "ui.ai_no_keychain": "Chuỗi khóa hệ thống không khả dụng nên không thể lưu khóa. Máy chủ cục bộ không cần khóa vẫn hoạt động bình thường.", + "ui.ai_panel": "Bảng điều khiển", + "ui.ai_permissions": "Quyền hạn", + "ui.ai_preset": "Mẫu cấu hình sẵn", + "ui.ai_remove": "Xóa", + "ui.ai_request_limit": "đã dừng sau 24 yêu cầu cho một tin nhắn; gửi tin nhắn khác để tiếp tục", + "ui.ai_reset": "Đặt lại", + "ui.ai_settings": "AI cài đặt…", + "ui.ai_show_features": "Hiển thị các tính năng AI", + "ui.ai_show_features_note": "Trò chuyện với tác tử: bảng điều khiển nơi tác tử lập trình hoặc điểm cuối mô hình thao tác trên thiết kế đang mở. Tắt: ẩn nút AI, phím tắt, menu và bảng điều khiển, không tìm kiếm hay khởi chạy tác tử.", + "ui.ai_switch_tip": "Chuyển đổi AI Agent cho cuộc hội thoại này", + "ui.ai_test": "Kiểm tra", + "ui.ai_test_acp_ok": "Phản hồi: {agent}", + "ui.ai_test_acp_tip": "Khởi động nhanh AI Agent để tạo phiên làm việc; sau đó đóng lại", + "ui.ai_test_api_tip": "Yêu cầu điểm cuối cung cấp danh sách mô hình", + "ui.ai_test_no_model": "Đã kết nối: tìm thấy {count} mô hình, nhưng không có {model}", + "ui.ai_test_ok": "Đã kết nối: tìm thấy {count} mô hình", + "ui.ai_testing": "Đang kiểm tra…", + "ui.ai_tool_done": "hoàn thành", + "ui.ai_tool_failed": "thất bại", + "ui.ai_tool_running": "đang chạy", + "ui.ai_tool_unfold": "Nhấp để xem nội dung trả về", + "ui.ai_tool_waiting": "đang chờ", + "ui.ai_toolbar_button": "Hiển thị nút trên thanh công cụ", + "ui.ai_toolbar_button_note": "Nút AI ở góc phải thanh công cụ. Phím tắt Ctrl+Shift+A và menu Khung nhìn vẫn có thể mở bảng điều khiển.", + "ui.ai_undo_tip": "Hoàn tác mọi thay đổi do tác tử thực hiện cho tin nhắn này, như một bước duy nhất", + "ui.all": "Tất cả", + "ui.ambient_occlusion": "Đổ bóng che khuất môi trường (AO)", + "ui.ambient_occlusion_help": "Hiệu ứng đổ bóng mềm tại nơi các mặt mờ đục tiếp xúc nhau. Yêu cầu khung nhìn GPU.", + "ui.analysis": "Phân tích", + "ui.angle": "Góc", + "ui.angle_decimals": "Số chữ số thập phân cho góc", + "ui.animateJoint": "Mô phỏng chuyển động khớp nối", + "ui.animate_view_changes": "Hiệu ứng chuyển góc nhìn", + "ui.animation": "Hoạt họa", + "ui.animation_speed": "Tốc độ chuyển động", + "ui.anti_aliasing": "Khử răng cưa", + "ui.apply": "Áp dụng", + "ui.arc": "Cung tròn", + "ui.assemble": "Lắp ráp", + "ui.autosave_every": "Tự động lưu sau mỗi", + "ui.axes": "Các trục", + "ui.axis": "Trục", + "ui.base_point": "Điểm chuẩn (Base point)", + "ui.blocked": "Bị chặn", + "ui.bodies": "Các thân khối", + "ui.bodies_all_if_none": "Thân khối (tất cả nếu không chọn)", + "ui.box": "Khối hộp", + "ui.break": "Ngắt", + "ui.calibrate": "Hiệu chuẩn", + "ui.cancel": "Hủy bỏ", + "ui.canvases": "Các ảnh nền Canvas", + "ui.center": "Tâm", + "ui.centerline": "Đường tâm", + "ui.chain": "Chuỗi", + "ui.chamfer": "Vát mép", + "ui.chamfer_type": "Kiểu vát mép", + "ui.change_workspace": "Đổi không gian làm việc", + "ui.chord_length": "Chiều dài dây cung", + "ui.circle": "Hình tròn", + "ui.circular_pattern": "Mảng tròn quanh trục", + "ui.clear": "Xóa", + "ui.clear_recent": "Xóa danh sách gần đây", + "ui.clear_the_selection": "Hủy chọn", + "ui.click_selects_whole_bodies": "Nhấp chuột chọn toàn bộ thân khối", + "ui.click_then_press_key": "Nhấp chuột, sau đó nhấn phím mới", + "ui.close": "Đóng", + "ui.coil": "Lò xo xoắn", + "ui.coincident": "Trùng điểm", + "ui.collapse": "Thu gọn", + "ui.collinear": "Cùng đường thẳng", + "ui.colour_vision": "Thị giác màu sắc", + "ui.colour_vision_deutan": "Mù màu xanh lá (Deutan)", + "ui.colour_vision_deutan_tip": "Dành cho người cảm nhận màu xanh lá yếu hoặc mất hẳn", + "ui.colour_vision_failed": "Thất bại", + "ui.colour_vision_fixed": "Cố định", + "ui.colour_vision_mode": "Chế độ", + "ui.colour_vision_note": "Thay đổi màu sắc mang ý nghĩa biểu thị: trạng thái phác thảo, các trục, đường chấn, phân tích và biểu tượng. Nếu bạn đang dùng bộ lọc màu của Windows, hãy để chế độ này Tắt.", + "ui.colour_vision_off": "Tắt", + "ui.colour_vision_off_tip": "Màu sắc mặc định của giao diện", + "ui.colour_vision_projected": "Đã chiếu", + "ui.colour_vision_protan": "Mù màu đỏ (Protan)", + "ui.colour_vision_protan_tip": "Dành cho người cảm nhận màu đỏ yếu hoặc mất hẳn", + "ui.colour_vision_sample": "Mẫu thử", + "ui.colour_vision_tritan": "Mù màu xanh dương (Tritan)", + "ui.colour_vision_tritan_tip": "Dành cho người cảm nhận màu xanh dương yếu hoặc mất hẳn", + "ui.combine": "Hợp nhất / Cắt khối", + "ui.coming_later": "sắp ra mắt", + "ui.command_done": "Hoàn tất lệnh {command}", + "ui.command_palette_hint": "Nhập một lệnh, ví dụ: {example} — hoặc nhấn S để tìm kiếm", + "ui.concentric": "Đồng tâm", + "ui.configurations": "Các cấu hình", + "ui.conic_curve": "Đường cong Conic", + "ui.constant": "Hằng số", + "ui.constraints_conflict": "Xung đột ràng buộc", + "ui.construct": "Dựng hình", + "ui.construction": "Đường gióng dựng hình", + "ui.context_menu": "Menu ngữ cảnh", + "ui.continuity_g0": "Nếp gập G0", + "ui.continuity_g1": "G1 tiếp tuyến", + "ui.continuity_g2": "G2 độ cong", + "ui.continuity_gap": "Khe hở", + "ui.copy": "Sao chép", + "ui.corner": "Góc", + "ui.corners": "Các góc", + "ui.counterbore": "Lỗ khoét loe (Counterbore)", + "ui.countersink": "Lỗ vát miệng (Countersink)", + "ui.create": "Tạo mới", + "ui.create_copy": "Tạo bản sao", + "ui.create_sketch": "Tạo phác thảo", + "ui.current": "hiện tại", + "ui.curvature": "Độ cong", + "ui.curvature_g2": "Độ cong (G2)", + "ui.curves": "Các đường cong", + "ui.custom_program": "Tùy chỉnh…", + "ui.custom_program_tip": "Chọn chương trình cắt lớp (slicer) để thêm vào danh sách", + "ui.customizeToolbar": "Tùy biến thanh công cụ…", + "ui.cut": "Cắt", + "ui.cylinder": "Hình trụ", + "ui.dark": "Tối", + "ui.default_modelling_orientation": "Hướng mô hình hóa mặc định", + "ui.degrees_of_freedom": "bậc tự do", + "ui.delete": "Xóa", + "ui.depth": "Độ sâu", + "ui.design": "Thiết kế", + "ui.design_properties.author": "Tác giả", + "ui.design_properties.description": "Mô tả", + "ui.design_properties.exports": "Tệp xuất STEP, IGES và 3MF sẽ lưu giữ các thông tin này nếu định dạng đó hỗ trợ.", + "ui.design_properties.license": "Giấy phép bản quyền", + "ui.design_properties.not_text": "Đã lưu dưới dạng dữ liệu không phải văn bản; nhập vào đây sẽ thay thế nội dung đó.", + "ui.design_properties.organization": "Tổ chức / Đơn vị", + "ui.design_properties.others": "Dữ liệu từ công cụ khác", + "ui.design_properties.others_note": "Được giữ nguyên trong thiết kế hiện tại và không bao giờ xuất ra ngoài.", + "ui.design_properties.part_number": "Mã số chi tiết", + "ui.design_properties.project": "Dự án", + "ui.design_properties.revision": "Lần sửa đổi (Revision)", + "ui.diameter": "Đường kính", + "ui.dimension": "Kích thước", + "ui.direction": "Hướng", + "ui.display_quality": "Chất lượng hiển thị", + "ui.display_quality_coarse": "Thô (Nhanh)", + "ui.display_quality_fine": "Mịn", + "ui.display_quality_normal": "Bình thường", + "ui.display_quality_ultra": "Cực mịn (Ultra)", + "ui.distance": "Khoảng cách", + "ui.distance_1": "Khoảng cách 1", + "ui.distance_2": "Khoảng cách 2", + "ui.document_settings": "Cài đặt tài liệu", + "ui.don_t_save": "Không lưu", + "ui.draft": "Độ côn thoát khuôn", + "ui.drawing": "Bản vẽ 2D", + "ui.drill_point": "Đỉnh mũi khoan (Drill Point)", + "ui.edit": "Chỉnh sửa", + "ui.editJointLimits": "Chỉnh sửa giới hạn khớp nối", + "ui.edit_section_analysis": "Chỉnh sửa phân tích mặt cắt", + "ui.ellipse": "Hình elip", + "ui.end_radius": "Bán kính kết thúc", + "ui.end_scale": "Tỷ lệ đầu cuối", + "ui.entities": "Các thực thể", + "ui.equal": "Bằng nhau", + "ui.equivalent_radius": "Bán kính tương đương", + "ui.expand": "Mở rộng", + "ui.exportDxf": "Xuất tệp DXF…", + "ui.export_ellipsis": "Xuất tệp...", + "ui.export_ellipsis_keymap": "Xuất tệp…", + "ui.export_keymap_tip": "Xuất phím tắt, danh sách S box yêu thích và thanh công cụ ra tệp", + "ui.extend": "Kéo dài đường", + "ui.extent_type": "Kiểu giới hạn kéo dài", + "ui.extrude": "Đùn khối", + "ui.factor": "Hệ số", + "ui.feature_history": "Lịch sử tính năng", + "ui.feature_options": "Tùy chọn tính năng", + "ui.features": "Các tính năng", + "ui.file": "Tệp", + "ui.fillet": "Bo tròn mép", + "ui.filter_commands_or_keys": "Lọc lệnh hoặc phím tắt", + "ui.findInTimeline": "Tìm trong lịch sử thiết kế", + "ui.findInWindow": "Tìm trong cửa sổ", + "ui.finish_sketch": "Hoàn tất phác thảo", + "ui.fit": "Vừa vặn (Fit)", + "ui.fix_unfix": "Cố định/Uncố định", + "ui.flat": "Phẳng", + "ui.flip": "Lật mặt", + "ui.format": "Định dạng", + "ui.frame_rate": "Tốc độ khung hình (FPS)", + "ui.front": "Trước (Hình chiếu đứng)", + "ui.fully_constrained": "Ràng buộc hoàn toàn", + "ui.general": "Chung", + "ui.graphics": "Đồ họa", + "ui.graphics_custom": "Tùy biến", + "ui.graphics_performance": "Hiệu năng", + "ui.graphics_preset": "Cấu hình đồ họa sẵn", + "ui.graphics_preset_help": "Chất lượng: đổ bóng mềm (AO), chất lượng hiển thị Mịn và siêu lấy mẫu thích ứng 2×. Hiệu năng: không đổ bóng mềm, chất lượng hiển thị Bình thường và tắt siêu lấy mẫu. Thay đổi thủ công sẽ hiển thị Tùy chỉnh. MSAA giữ nguyên.", + "ui.graphics_quality": "Chất lượng", + "ui.grid_follows_view": "Lưới đi theo góc nhìn", + "ui.grid_follows_view_hint": "Các góc nhìn cạnh hiển thị lưới trên mặt phẳng thẳng đứng hướng về phía camera thay vì trên mặt sàn", + "ui.ground_shadow": "Bóng đổ mặt sàn", + "ui.groupSelected": "Gộp nhóm vùng chọn", + "ui.heading_add_ins": "TIỆN ÍCH MỞ RỘNG", + "ui.heading_assemble": "LẮP RÁP", + "ui.heading_box": "KHỐI HỘP", + "ui.heading_chamfer": "VÁT MÉP", + "ui.heading_circular_pattern": "SAO CHÉP XOAY TRÒN", + "ui.heading_coil": "LÒ XO XOẮN", + "ui.heading_combine": "HỢP NHẤT KHỐI", + "ui.heading_configure": "CẤU HÌNH", + "ui.heading_constraints": "RÀNG BUỘC", + "ui.heading_construct": "DỰNG HÌNH", + "ui.heading_create": "TẠO MỚI", + "ui.heading_create_sketch": "TẠO PHÁC THẢO", + "ui.heading_cylinder": "HÌNH TRỤ", + "ui.heading_design": "THIẾT KẾ", + "ui.heading_draft": "ĐỘ DỐC THOÁT KHUÔN", + "ui.heading_edit": "CHỈNH SỬA", + "ui.heading_extrude": "ĐÙN KHỐI", + "ui.heading_fillet": "BO TRÒN", + "ui.heading_finish_sketch": "HOÀN TẤT PHÁC THẢO", + "ui.heading_front": "HÌNH CHIẾU ĐỨNG", + "ui.heading_hole": "TẠO LỖ", + "ui.heading_home": "GÓC NHÌN CHUẨN", + "ui.heading_insert": "CHÈN", + "ui.heading_inspect": "KIỂM TRA", + "ui.heading_interference": "KIỂM TRA VA CHẠM", + "ui.heading_loft": "CHUYỂN TIẾP BIÊN DẠNG", + "ui.heading_make": "CHẾ TẠO", + "ui.heading_measure": "ĐO LƯỜNG", + "ui.heading_mesh": "LƯỚI ĐA GIÁC", + "ui.heading_mirror": "LẤY ĐỐI XỨNG", + "ui.heading_modify": "HIỆU CHỈNH", + "ui.heading_move": "DI CHUYỂN", + "ui.heading_move_copy": "DI CHUYỂN / SAO CHÉP", + "ui.heading_offset": "OFFSET", + "ui.heading_offset_plane": "MẶT PHẲNG OFFSET", + "ui.heading_ok": "Đồng ý", + "ui.heading_parameters": "BẢNG THAM SỐ", + "ui.heading_pattern": "SAO CHÉP MẪU", + "ui.heading_pattern_on_path": "SAO CHÉP THEO ĐƯỜNG DẪN", + "ui.heading_pipe": "ĐƯỜNG ỐNG", + "ui.heading_plane_at_angle": "MẶT PHẲNG THEO GÓC", + "ui.heading_plastic": "CHI TIẾT NHỰA", + "ui.heading_position": "VỊ TRÍ", + "ui.heading_prepare": "CHUẨN BỊ", + "ui.heading_rectangular_pattern": "SAO CHÉP HÌNH CHỮ NHẬT", + "ui.heading_revolve": "XOAY TRÒN TẠO KHỐI", + "ui.heading_right": "HÌNH CHIẾU CẠNH", + "ui.heading_save_mesh": "LƯU DƯỚI DẠNG LƯỚI ĐA GIÁC", + "ui.heading_scale": "THAY ĐỔI TỶ LỆ", + "ui.heading_section_analysis": "PHÂN TÍCH MẶT CẮT", + "ui.heading_select": "CHỌN ĐỐI TƯỢNG", + "ui.heading_setup": "THIẾT LẬP", + "ui.heading_sheet_metal": "KIM LOẠI TẤM", + "ui.heading_shell": "TẠO VỎ MỎNG", + "ui.heading_sketch": "PHÁC THẢO", + "ui.heading_sketch_palette": "BẢNG ĐIỀU KHIỂN PHÁC THẢO", + "ui.heading_sketch_scale": "TỶ LỆ PHÁC THẢO", + "ui.heading_solid": "KHỐI ĐẶC", + "ui.heading_sphere": "HÌNH CẦU", + "ui.heading_split_body": "TÁCH THÂN KHỐI", + "ui.heading_surface": "MẶT CONG", + "ui.heading_sweep": "QUÉT BIÊN DẠNG", + "ui.heading_thread": "TẠO REN", + "ui.heading_top": "HÌNH CHIẾU BẰNG", + "ui.heading_torus": "HÌNH XUYẾN", + "ui.heading_utilities": "TIỆN ÍCH", + "ui.heading_utility": "TIỆN ÍCH", + "ui.help": "Trợ giúp", + "ui.hide": "Ẩn", + "ui.hideAxes": "Ẩn Các trục", + "ui.hideDimension": "Ẩn Kích thước", + "ui.hideOrigin": "Ẩn Gốc tọa độ", + "ui.hidePlanes": "Ẩn các mặt phẳng", + "ui.hideProfile": "Ẩn biên dạng", + "ui.hole": "Tạo lỗ", + "ui.hole_tap_type": "Kiểu ta-rô ren lỗ", + "ui.hole_type": "Loại lỗ", + "ui.home": "Góc nhìn chuẩn (Home)", + "ui.homeView": "Góc nhìn chuẩn (Home)", + "ui.horizontal_vertical": "Nằm ngang/Thẳng đứng", + "ui.import_ellipsis": "Nhập tệp…", + "ui.infinite": "Vô hạn", + "ui.insert": "Chèn", + "ui.inspect": "Kiểm tra", + "ui.intersect": "Giao nhau", + "ui.isolate": "Cô lập đối tượng", + "ui.join": "Nối liền", + "ui.joints": "Các khớp nối", + "ui.keyboard_shortcuts": "Phím tắt bàn phím", + "ui.language": "Ngôn ngữ (Language)", + "ui.length_decimals": "Số chữ số thập phân cho chiều dài", + "ui.light": "Sáng", + "ui.line": "Đoạn thẳng", + "ui.linetype": "Kiểu đường nét", + "ui.lock": "Khóa", + "ui.loft": "Vuốt nối biên dạng (Loft)", + "ui.look_at": "Nhìn trực diện", + "ui.look_at_anim_desc": "Góc nhìn theo trục, Nhìn thẳng, Chuẩn và Vừa vặn", + "ui.manufacture": "Gia công chế tạo", + "ui.material_review.axes": "Các trục cục bộ của vật liệu; chưa gán hướng cho thân khối.", + "ui.material_review.claims": "Nguồn gốc và giấy phép là thông tin chưa được kiểm chứng. Các giá trị thiếu vẫn ở dạng chưa biết.", + "ui.material_review.compressive_strength": "Độ bền nén", + "ui.material_review.conditions": "Điều kiện đã nêu", + "ui.material_review.density": "Khối lượng riêng", + "ui.material_review.derived": "Mô đun đẳng hướng suy ra", + "ui.material_review.elasticity": "Độ đàn hồi", + "ui.material_review.input": "Dán thẻ vật liệu chuẩn schema-1 (JSON)", + "ui.material_review.limit": "Thẻ này vượt quá giới hạn đầu vào 256 KiB.", + "ui.material_review.moisture_unit": "kg nước / kg vật liệu khô", + "ui.material_review.properties": "Thuộc tính cơ lý", + "ui.material_review.review": "Thẻ đánh giá vật liệu", + "ui.material_review.scope": "Chỉ là ứng viên: chưa được gán hoặc lưu. Kiểm tra số học không thay thế cho chứng nhận kỹ thuật.", + "ui.material_review.shear_strength": "Độ bền cắt", + "ui.material_review.source": "Nguồn tham chiếu", + "ui.material_review.specific_heat": "Nhiệt dung riêng", + "ui.material_review.tensile_strength": "Độ bền kéo", + "ui.material_review.thermal_conductivity": "Độ dẫn nhiệt", + "ui.material_review.thermal_expansion": "Giãn nở nhiệt", + "ui.material_review.title": "Xem xét dữ liệu thuộc tính vật liệu", + "ui.material_review.unknown": "Chưa biết", + "ui.material_review.yield_strength": "Giới hạn chảy", + "ui.measure": "Đo lường", + "ui.mesh_format_3mf": "3MF", + "ui.mesh_format_3mf_tagged": "3MF kèm thẻ bề mặt", + "ui.mesh_format_stl": "STL", + "ui.midpoint": "Trung điểm", + "ui.mirror": "Lấy đối xứng", + "ui.mirror_line": "Đường đối xứng", + "ui.modify": "Hiệu chỉnh", + "ui.move": "Di chuyển", + "ui.multiple": "Nhiều đối tượng", + "ui.named_views": "Các góc nhìn đã đặt tên", + "ui.navigation": "Điều hướng", + "ui.needs_design": "{command}: hãy mở một thiết kế trước", + "ui.newSketchGroup": "Nhóm phác thảo mới", + "ui.new_body": "Tạo mới Thân khối", + "ui.new_design": "Thiết kế mới", + "ui.no_slicer_found": "Không tìm thấy phần mềm cắt lớp (slicer)", + "ui.normal": "Pháp tuyến", + "ui.normalConstruction": "Nét thường / Đường dựng hình", + "ui.not_a_program": "{path} không phải là một chương trình có thể khởi chạy", + "ui.object_type": "Loại đối tượng", + "ui.objects": "Các đối tượng", + "ui.offer_to_stand_up_y_up_files": "Gợi ý dựng đứng các tệp có trục Y hướng lên", + "ui.offset": "Khoảng dời (Offset)", + "ui.offset_plane": "Mặt phẳng song song cách khoảng (Offset Plane)", + "ui.one_side": "Một phía", + "ui.open": "Mở tệp", + "ui.open_ellipsis": "Mở tệp...", + "ui.open_ends_tip": "Không chạm vào đối tượng nào", + "ui.open_preferences": "Mở tệp Tùy chọn cài đặt", + "ui.open_recent": "Mở tệp gần đây", + "ui.operation": "Phép toán hình học", + "ui.options": "Tùy chọn", + "ui.orbit": "Xoay quanh tâm (Orbit)", + "ui.orbit_around": "Xoay quanh", + "ui.orientation": "Định hướng", + "ui.origin": "Gốc tọa độ", + "ui.palette_points": "Điểm", + "ui.palette_profile": "Biên dạng", + "ui.pan": "Dời góc nhìn (Pan)", + "ui.pan_zoom_orbit": "Dời góc nhìn, thu phóng, xoay quanh tâm", + "ui.parallel": "Song song", + "ui.parameters": "Bảng tham số", + "ui.paste": "Dán", + "ui.path": "Đường dẫn", + "ui.pattern_on_path": "Mảng dọc theo đường dẫn", + "ui.perpendicular": "Vuông góc", + "ui.perspective_view": "Góc nhìn phối cảnh", + "ui.pinToShortcuts": "Ghim vào phím tắt", + "ui.pinToToolbar": "Ghim vào thanh công cụ", + "ui.pipe": "Ống", + "ui.placement": "Vị trí đặt", + "ui.plane": "Mặt phẳng", + "ui.plane_at_angle": "Mặt phẳng theo góc", + "ui.point": "Điểm", + "ui.point_under_the_cursor": "Điểm dưới con trỏ", + "ui.points": "Các điểm", + "ui.polygon": "Đa giác", + "ui.preferences": "Tùy chọn cài đặt", + "ui.press_a_key": "nhấn một phím…", + "ui.profile": "Biên dạng", + "ui.profile_plane": "Mặt phẳng biên dạng", + "ui.profiles": "Các biên dạng", + "ui.project": "Chiếu hình học", + "ui.project_face_edges_sketch": "Chiếu các cạnh bề mặt vào phác thảo mới", + "ui.properties": "Thuộc tính cơ lý", + "ui.pull_direction": "Hướng kéo", + "ui.quantity": "Số lượng", + "ui.quantity_2": "Số lượng 2", + "ui.quit": "Thoát ứng dụng", + "ui.radial_context_menu": "Menu ngữ cảnh dạng vòng (Radial)", + "ui.radius": "Bán kính", + "ui.radius_type": "Loại bán kính", + "ui.rail": "Đường ray dẫn hướng", + "ui.rail_fit": "Độ khớp đường dẫn (Rail Fit)", + "ui.reachable": "Có thể tiếp cận", + "ui.rectangle": "Hình chữ nhật", + "ui.rectangular_pattern": "Mảng hình chữ nhật", + "ui.redo": "Làm lại", + "ui.removeFromToolbar": "Xóa khỏi thanh công cụ", + "ui.removeSection": "Xóa mặt cắt", + "ui.render": "Kết xuất hình ảnh", + "ui.renderer": "Trình kết xuất hình ảnh (Renderer)", + "ui.repeat": "Lặp lại", + "ui.report_a_bug": "Báo cáo lỗi", + "ui.reset": "Đặt lại", + "ui.reset_all": "Đặt lại tất cả", + "ui.reset_the_settings_on_this_page": "Đặt lại các cài đặt trên trang này", + "ui.restore": "Khôi phục", + "ui.restore_defaults": "Khôi phục mặc định", + "ui.reverse_horizontal_pan_direction": "Đảo chiều di chuyển góc nhìn ngang", + "ui.reverse_horizontal_pan_tip": "Cuộn hai ngón tay theo phương ngang và con lăn phụ sẽ di chuyển góc nhìn theo chiều ngược lại", + "ui.reverse_zoom_direction": "Đảo chiều thu phóng", + "ui.revolve": "Xoay tròn tạo khối", + "ui.right": "Phải (Hình chiếu cạnh)", + "ui.save": "Lưu", + "ui.save_as": "Lưu thành tệp mới", + "ui.save_as_ellipsis": "Lưu thành...", + "ui.save_mesh_no_slicer": "Không tìm thấy phần mềm cắt lớp (slicer): hãy chọn Tùy chỉnh… và chỉ định chương trình cắt lớp, hoặc tắt tùy chọn Gửi đến slicer", + "ui.save_mesh_pick_bodies": "Chọn các thân khối cần lưu", + "ui.save_mesh_temp_failed": "Không thể tạo thư mục {folder}: {error}", + "ui.saved_to": "Đã lưu {path}", + "ui.sbox_pin": "Ghim lên đầu hộp tìm kiếm phím S", + "ui.sbox_unpin": "Bỏ ghim", + "ui.scale": "Thay đổi tỷ lệ", + "ui.second_rail": "Đường ray dẫn hướng thứ hai", + "ui.section_analysis": "Phân tích mặt cắt", + "ui.select": "Chọn", + "ui.selectOther": "Chọn đối tượng khác…", + "ui.selectTangentChain": "Chọn chuỗi tiếp tuyến", + "ui.select_other_hint": "Chọn đối tượng khác: giữ nút chuột trái đứng yên trên mô hình (hoặc nhấp chuột phải › Chọn đối tượng khác…) để liệt kê mọi đối tượng dưới con trỏ; nhấp lại vào cùng vị trí đó để chọn đối tượng kế tiếp.", + "ui.selection": "Vùng chọn", + "ui.send": "Gửi", + "ui.send_to_slicer": "Gửi sang phần mềm cắt lát (Slicer)", + "ui.sent_to_slicer": "Đã gửi sang {slicer}", + "ui.sheet_gap": "Khe hở tấm", + "ui.shell": "Tạo vỏ mỏng (Shell)", + "ui.show": "Hiển thị", + "ui.showAll": "Hiển thị tất cả", + "ui.showAllBodies": "Hiển thị tất cả thân khối", + "ui.showAxes": "Hiển thị Các trục", + "ui.showDimension": "Hiển thị Kích thước", + "ui.showOrigin": "Hiển thị Gốc tọa độ", + "ui.showPlanes": "Hiển thị các mặt phẳng", + "ui.show_constraints": "Các ràng buộc", + "ui.show_construction_geometries": "Đối tượng dựng hình (nét đứt)", + "ui.show_dimensions": "Các kích thước", + "ui.show_points": "Hiển thị điểm", + "ui.show_profile": "Hiển thị biên dạng", + "ui.show_projected_geometries": "Hình học đã chiếu", + "ui.simple": "Đơn giản", + "ui.simulation": "Mô phỏng", + "ui.single": "Đơn", + "ui.sketch": "Phác thảo", + "ui.sketch_dimension": "Phác thảo Kích thước", + "ui.sketch_grid": "Lưới phác thảo", + "ui.sketch_scale": "Tỷ lệ phác thảo", + "ui.sketch_status": "Trạng thái phác thảo", + "ui.sketches": "Các phác thảo", + "ui.slice": "Cắt lát", + "ui.slicer": "Phần mềm cắt lát (Slicer)", + "ui.slicer_delete_tip": "{program}\nNhấn Delete để xóa khỏi danh sách", + "ui.slot": "Rãnh then", + "ui.smooth": "Nối mượt", + "ui.smooth_wheel_zoom": "Thu phóng mượt bằng con lăn", + "ui.smooth_wheel_zoom_tip": "Tắt tùy chọn này để áp dụng từng sự kiện con lăn ngay lập tức mà không có hiệu ứng làm mượt chuyển động", + "ui.snap": "Bắt điểm", + "ui.space_mouse_hint": "Di chuyển và xoay khung nhìn đồng thời; môi trường phác thảo chỉ sử dụng dời góc nhìn và thu phóng.", + "ui.space_mouse_navigate": "Điều hướng bằng SpaceNavigator / SpaceMouse", + "ui.spacing": "Khoảng cách", + "ui.spacing_2": "Khoảng cách 2", + "ui.sphere": "Hình cầu", + "ui.spline": "Đường cong Spline", + "ui.split_body": "Chia tách khối", + "ui.stand_up_tip": "Sau khi mở tệp STEP hoặc IGES với trục Z hướng lên, đề xuất xoay 90° quanh trục X", + "ui.start": "Bắt đầu", + "ui.start_radius": "Bán kính bắt đầu", + "ui.stretch": "Kéo giãn", + "ui.supersampling": "Khử răng cưa SSAA", + "ui.supersampling_adaptive": "Chỉ khi góc nhìn đứng yên", + "ui.supersampling_off": "Tắt (1×)", + "ui.suppress": "Tạm nén", + "ui.sweep": "Quét theo đường dẫn", + "ui.sweep_follow_direction": "Theo hướng dẫn", + "ui.sweep_keep_as_drawn": "Giữ nguyên như đã vẽ", + "ui.sweep_turn_with_path": "Xoay theo đường dẫn", + "ui.symmetric": "Đối xứng hai phía", + "ui.symmetry": "Đối xứng", + "ui.system": "Hệ thống", + "ui.tangent": "Tiếp tuyến", + "ui.taper_angle": "Góc côn (Taper)", + "ui.tapped": "Ren ta-rô", + "ui.text": "Văn bản", + "ui.theme": "Chủ đề giao diện", + "ui.thickness": "Độ dày", + "ui.thread": "Tạo ren", + "ui.tie_ends": "Khóa mút", + "ui.tie_ends_tip": "Gán ràng buộc cho tất cả các đầu mút tự do", + "ui.timeline_bottom": "Dòng lịch sử thiết kế ở cạnh dưới", + "ui.timeline_left_note": "Bố cục bên trái hiển thị thanh cuộn lui lịch sử ở phía trên cây đối tượng chi tiết và khung cảnh.", + "ui.timeline_left_sidebar": "Thanh bên trái", + "ui.tip_angle": "Góc đỉnh mũi khoan", + "ui.to_object": "Tới đối tượng", + "ui.tool_direction": "Hướng công cụ", + "ui.top": "Trên (Hình chiếu bằng)", + "ui.torus": "Hình xuyến", + "ui.total_angle": "Góc tổng thể", + "ui.trackpad_pan_tip": "Thao tác vuốt bàn rê giúp dời góc nhìn (khi tắt: sẽ thu phóng như con lăn); con lăn chuột thu phóng, con lăn ngón cái dời góc nhìn sang hai bên, thao tác chụm ngón tay luôn thu phóng", + "ui.trim": "Cắt tỉa", + "ui.twist": "Xoắn", + "ui.two_finger_scroll_pans": "Cuộn hai ngón tay để dời góc nhìn", + "ui.two_sides": "Hai phía", + "ui.ui_scale": "Tỷ lệ giao diện người dùng", + "ui.undo": "Hoàn tác", + "ui.unground": "Hủy cố định", + "ui.unisolate": "Hủy cô lập đối tượng", + "ui.units": "Đơn vị đo lường", + "ui.units_of_new_designs": "Đơn vị đo cho các thiết kế mới", + "ui.unlock": "Mở khóa", + "ui.unsuppress": "Hủy tạm nén", + "ui.untied_ends_tip": "Chỉ tiếp xúc theo vị trí", + "ui.untitled": "Chưa đặt tên", + "ui.up_axis_note": "Trục nào hướng lên trên trong các góc nhìn (góc nhìn theo trục, Chuẩn, Nhìn thẳng). Các mô hình thiết kế không bị thay đổi.", + "ui.updateToCurrentView": "Cập nhật theo góc nhìn hiện tại", + "ui.variable": "Biến thiên", + "ui.view_centre": "Tâm góc nhìn", + "ui.visual_shaded_hidden_edges": "Tô bóng kèm nét khuất", + "ui.visual_shaded_with_edges": "Tô bóng kèm hiển thị cạnh", + "ui.visual_style": "Kiểu hiển thị trực quan", + "ui.visual_wireframe": "Khung dây (Wireframe)", + "ui.workspace": "không gian làm việc", + "ui.x_distance": "X Khoảng cách", + "ui.y_distance": "Y Khoảng cách", + "ui.y_up": "Trục Y hướng lên", + "ui.z_up": "Trục Z hướng lên", + "ui.zoom": "Thu phóng", + "ui.zoom_to_cursor_tip": "Con lăn chuột thu phóng về phía điểm dưới con trỏ (khi tắt: thu phóng về tâm khung nhìn)", + "ui.zoom_to_the_cursor": "Thu phóng theo con trỏ chuột", + "update.available": "Đã có phiên bản SolidCraft {version}", + "update.button": "Cập nhật", + "update.button_tip": "Đã có phiên bản SolidCraft {version}", + "update.button_version": "Cập nhật lên {version}", + "update.check_automatically": "Tự động kiểm tra bản cập nhật", + "update.check_now": "Kiểm tra ngay", + "update.checking": "Đang kiểm tra…", + "update.copy": "Sao chép", + "update.dmg_opened": "Ảnh đĩa đã mở và được xác thực: kéo SolidCraft vào thư mục Applications để thay thế bản cũ, sau đó khởi động lại SolidCraft.", + "update.download": "Tải về", + "update.download_open": "Tải về và mở", + "update.downloading": "Đang tải về và xác thực… {done} trên {total} MB", + "update.failed": "Không thể kiểm tra: {error}", + "update.file": "Tải về để nhận {file}.", + "update.install_failed": "Bản cập nhật không thể cài đặt: {error}. Không có gì thay đổi; bạn có thể tải về gói cài đặt để cài thủ công.", + "update.install_msi": "Cài đặt (sẽ đóng SolidCraft)", + "update.installed": "SolidCraft {version} đã được cài đặt. Hãy khởi động lại để sử dụng.", + "update.installer_started": "Trình cài đặt sẽ bắt đầu khi SolidCraft đóng.", + "update.later": "Nhắc tôi sau", + "update.no_notes": "Bản phát hành này không có ghi chú.", + "update.package_hint": "Bản sao này được cài từ {kind}. Hãy tải về gói mới, sau đó cài đặt bằng lệnh:", + "update.prefs_dev": "Đây là bản dựng phát triển ({version}): không tự động kiểm tra bản cập nhật.", + "update.prefs_flatpak": "Flatpak quản lý cập nhật bản sao này ({version}): hãy chạy {command} hoặc dùng trung tâm phần mềm của bạn. SolidCraft không tự kiểm tra.", + "update.prefs_label": "Bản cập nhật", + "update.prefs_note": "Đây là SolidCraft {version} ({kind}). Quá trình kiểm tra gửi yêu cầu đến GitHub để tìm bản mới nhất và không gửi thông tin nào khác.", + "update.release_page": "Mở trang phát hành", + "update.restart": "Khởi động lại ngay", + "update.restart_later": "Để sau", + "update.show": "Xem bản cập nhật lên {version}", + "update.skip": "Bỏ qua phiên bản này", + "update.system_hint": "Bản sao này là dạng {kind}. Cập nhật bằng lệnh:", + "update.title": "Đã có bản cập nhật", + "update.up_to_date": "SolidCraft đã được cập nhật bản mới nhất.", + "update.update_now": "Cập nhật ngay", + "update.you_have": "Bạn đang dùng phiên bản {version}." +} diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 28f8fc906..e95ab63b1 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -47,6 +47,7 @@ static PORTUGUESE_BR: Catalog = static RUSSIAN: Catalog = Catalog::new("ru", "Русский", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/ru.json"))); static TURKISH: Catalog = Catalog::new("tr", "Türkçe", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/tr.json"))); static UKRAINIAN: Catalog = Catalog::new("uk", "Українська", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/uk.json"))); +static VIETNAMESE: Catalog = Catalog::new("vi", "Tiếng Việt", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/vi.json"))); static CHINESE: Catalog = Catalog::new("zh", "中文", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/zh.json"))); /// English first (the fallback), then by language id, one per line so that adding a language /// doesn't edit a line another addition edits. @@ -67,6 +68,7 @@ pub const LOCALES: &[&Catalog] = &[ &RUSSIAN, &TURKISH, &UKRAINIAN, + &VIETNAMESE, &CHINESE, ]; @@ -691,6 +693,27 @@ mod tests { assert_eq!(uk.dynamic("Sketch of bracket"), "Sketch of bracket"); } + #[test] + fn vietnamese_catalog_translates_keys_labels_and_browser_patterns() { + let vi = Locale::for_language("vi"); + assert_eq!(vi.name(), "Tiếng Việt"); + assert!(is_supported("vi")); + assert_eq!(vi.text("ui.preferences"), "Tùy chọn cài đặt"); + assert_eq!(vi.label("Extrude"), "Đùn khối"); + assert_eq!(vi.label("CREATE SKETCH"), "TẠO PHÁC THẢO"); + assert_eq!(vi.label("NonExistentKey"), "NonExistentKey"); + assert_eq!(vi.format("document.save_changes", &[("name", "My {design}")]), "Lưu các thay đổi đối với My {design}?"); + assert_eq!(vi.format("dialog.selected_count", &[("count", "2")]), "↖ 2 đã chọn"); + assert_eq!(vi.dynamic("Sketch1"), "Phác thảo1"); + assert_eq!(vi.dynamic("Body2"), "Thân khối2"); + assert_eq!(vi.dynamic("Component12"), "Cụm chi tiết12"); + assert_eq!(vi.dynamic("Units: mm"), "Đơn vị: mm"); + assert_eq!(vi.dynamic("Precision: 3"), "Độ chính xác: 3"); + assert_eq!(vi.dynamic("Parameters (5)"), "Bảng tham số (5)"); + assert_eq!(vi.dynamic("4 degrees of freedom"), "4 bậc tự do"); + assert_eq!(vi.dynamic("Sketch of bracket"), "Sketch of bracket"); + } + #[test] fn render_scopes_restore_the_previous_language() { let _english = scope("en"); From f68a3dd5d5426fe2cfde8958b7daafd5297a09e1 Mon Sep 17 00:00:00 2001 From: NOWN-DEV <257771410+NOWN-DEV@users.noreply.github.com> Date: Mon, 19 Oct 2026 22:10:10 +0200 Subject: [PATCH 090/225] Joints: an as-built joint at an origin on one of its parts follows it (#2600) `joint.as_built` with `at` an origin on A or B keeps that origin on its side (found again by its face's name on each solve) and holds the frame where it is now on the other, so the joint follows the face or hole as the design changes. Without `at`, or with an origin on another part, both sides hold their frames as before. Co-authored-by: Claude Opus 5.5 (1M context) Co-authored-by: bherbruck --- crates/engine/src/cmd/joints.rs | 25 +++++--- .../engine/src/cmd/joints_as_built_tests.rs | 62 +++++++++++++++++++ 2 files changed, 79 insertions(+), 8 deletions(-) create mode 100644 crates/engine/src/cmd/joints_as_built_tests.rs diff --git a/crates/engine/src/cmd/joints.rs b/crates/engine/src/cmd/joints.rs index 856f0454e..d6d1fc559 100644 --- a/crates/engine/src/cmd/joints.rs +++ b/crates/engine/src/cmd/joints.rs @@ -31,7 +31,7 @@ pub static COMMANDS: &[CommandSpec] = &[ expression no longer works out (a parameter deleted) is left out of the solve with the reason in its errors", ), CommandSpec::new("joint.as_built", "As-Built Joint", as_built).at("SOLID", "ASSEMBLE").icon("as_built").params( - "type, a: occurrence, b: occurrence (stay where they are); at?: joint origin (default: b's origin) — the joint's frame; \ + "type, a: occurrence, b: occurrence (stay where they are); at?: joint origin (default: b's origin) — the joint's frame; one on a or b is kept on its face or hole there, so the joint follows it as the design changes; \ name?; limits?: [[min, max] | null…]; quiet?: bool", ), CommandSpec::new("joint.rigid_group", "Rigid Group", rigid_group).at("SOLID", "ASSEMBLE").icon("rigid_group").params("occurrences: [ids or names] (move together, as they are)"), @@ -669,15 +669,21 @@ fn as_built(s: &mut Session, p: &Value) -> Result { let kind = kind_param(p, cmd)?; let (oa, ob) = (occurrence_id(s, p.get("a"), cmd)?, occurrence_id(s, p.get("b"), cmd)?); // The joint's frame in the world: the given origin, or B's component origin. - let w = match p.get("at") { - Some(v) => { - let o = origin_param(s, Some(v), cmd)?; - s.doc.origin_world(&s.model.state(), &o).map_err(|e| bad(cmd, e.to_string()))? - } + let at = p.get("at").map(|v| origin_param(s, Some(v), cmd)).transpose()?; + let w = match &at { + Some(o) => s.doc.origin_world(&s.model.state(), o).map_err(|e| bad(cmd, e.to_string()))?, None => joints::occurrence_world(&s.doc, ob), }; - let fa = s.doc.frame_in_occurrence(oa, &w).ok_or_else(|| bad(cmd, "occurrence transform"))?; - let fb = s.doc.frame_in_occurrence(ob, &w).ok_or_else(|| bad(cmd, "occurrence transform"))?; + // An origin on A or B is kept as it is on that side, so the joint follows its face or hole + // as the design changes; the other side holds the frame where it is now. + let side = |occ: u64| -> Result { + match &at { + Some(o) if o.occurrence == occ => Ok(o.snap.clone()), + _ => s.doc.frame_in_occurrence(occ, &w).ok_or_else(|| bad(cmd, "occurrence transform")), + } + }; + let fa = side(oa)?; + let fb = side(ob)?; let id = next_joint_id(s, cmd)?; let name = str_(p, "name").map(str::to_string).unwrap_or_else(|| format!("Joint{id}")); let n = kind.dofs().len(); @@ -1370,6 +1376,9 @@ pub(crate) fn overlapping_pairs(boxes: &[Aabb3], limit: usize) -> (Vec<(usize, u (pairs, skipped) } +#[cfg(test)] +#[path = "joints_as_built_tests.rs"] +mod as_built_tests; #[cfg(test)] #[path = "joint_edge_tests.rs"] mod edge_tests; diff --git a/crates/engine/src/cmd/joints_as_built_tests.rs b/crates/engine/src/cmd/joints_as_built_tests.rs new file mode 100644 index 000000000..9acd97e54 --- /dev/null +++ b/crates/engine/src/cmd/joints_as_built_tests.rs @@ -0,0 +1,62 @@ +//! An as-built joint made at an origin on one of its parts follows that origin's face or hole as +//! the design changes, instead of holding the frame where it was made. + +use serde_json::json; +use solidcraft_geom::Vec3; + +use super::tests::{occ, place, run}; +use crate::Session; + +/// A 200 x 60 x 10 plate with a 10 mm hole at x = `X` (X = 50), and a 20 x 20 x 20 latch beside +/// it, off the plate. +fn plate() -> Session { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "X", "expression": "50 mm"})); + run(&mut s, "component.create", json!({"name": "Plate"})); + run(&mut s, "solid.box", json!({"length": 200, "width": 60, "height": 10, "corner": [0, 0, 0]})); + run(&mut s, "solid.cylinder", json!({"base": ["X", 30, 0], "axis": [0, 0, 1], "radius": 5, "height": 10, "operation": "cut"})); + run(&mut s, "component.activate", json!({"component": "root"})); + run(&mut s, "component.create", json!({"name": "Latch"})); + run(&mut s, "solid.box", json!({"length": 20, "width": 20, "height": 20, "corner": [40, 100, 0]})); + run(&mut s, "component.activate", json!({"component": "root"})); + let plate = occ(&s, "Plate"); + run(&mut s, "occurrence.ground", json!({"occurrence": plate, "grounded": true})); + s +} + +#[test] +fn an_as_built_joint_at_a_hole_follows_the_hole() { + let mut s = plate(); + run(&mut s, "joint.origin", json!({"name": "Hole", "occurrence": "Plate", "circle": [55, 30, 8]})); + let r = run(&mut s, "joint.as_built", json!({"type": "rigid", "a": "Plate", "b": "Latch", "at": "Hole", "name": "Latch"})); + assert_eq!(r["conflicts"], json!([]), "{r}"); + let latch = |s: &Session| place(s, "Latch", Vec3::new(40.0, 100.0, 0.0)); + // Made where it is. + assert!(latch(&s).dist(Vec3::new(40.0, 100.0, 0.0)) < 1e-6, "{:?}", latch(&s)); + for x in [80.0, 150.0, 30.0] { + run(&mut s, "parameters.change", json!({"name": "X", "expression": format!("{x} mm")})); + let at = latch(&s); + assert!(at.dist(Vec3::new(40.0 + x - 50.0, 100.0, 0.0)) < 1e-6, "X {x}: {at:?}"); + } + // The plate side keeps the hole (found by its face's name); the latch side holds its frame. + let j = s.doc.assembly.joints.first().cloned(); + assert!(matches!(j.as_ref().map(|j| &j.a.snap), Some(solidcraft_doc::joints::Snap::CircleCenter { face: Some(_), .. })), "{j:?}"); + assert!(matches!(j.as_ref().map(|j| &j.b.snap), Some(solidcraft_doc::joints::Snap::Frame { .. })), "{j:?}"); +} + +#[test] +fn an_as_built_joint_at_no_origin_or_one_elsewhere_holds_its_frame() { + let mut s = plate(); + run(&mut s, "joint.as_built", json!({"type": "rigid", "a": "Plate", "b": "Latch", "name": "Here"})); + let j = s.doc.assembly.joints.first().cloned(); + assert!( + matches!( + j.as_ref().map(|j| (&j.a.snap, &j.b.snap)), + Some((solidcraft_doc::joints::Snap::Frame { .. }, solidcraft_doc::joints::Snap::Frame { .. })) + ), + "{j:?}" + ); + run(&mut s, "parameters.change", json!({"name": "X", "expression": "120 mm"})); + let at = place(&s, "Latch", Vec3::new(40.0, 100.0, 0.0)); + assert!(at.dist(Vec3::new(40.0, 100.0, 0.0)) < 1e-6, "{at:?}"); +} From 26f42ae09b2f236e49bbac54a4cc1b84d0109889 Mon Sep 17 00:00:00 2001 From: Brazz <42916786+acbrazzl@users.noreply.github.com> Date: Mon, 19 Oct 2026 16:10:45 -0400 Subject: [PATCH 091/225] Snapshot: draw a see-through appearance see-through, and show a tool body inside its target (#2329) (#2330) * Snapshot: draw a see-through appearance see-through, and give the CLI --body, --tool and --section A headless picture dropped a body's opacity: the scene carried only a colour, so a design with a translucent appearance was drawn opaque by `solidcraft-cli snapshot`, by MCP screenshots and in a design's thumbnail, although the window has always drawn it as glass. There was then no way to look at the body a cut would remove inside the material it meets: only a volume to measure and reason about, which hides exactly the errors a picture makes obvious (a tool that stops short, or lands in the wrong place). - `SceneMesh` carries the body's opacity; `view::build_scene` takes it from the design (`model_body_opacity`), and a selected body stays solid so the selection colour reads. - The GPU capture routes a see-through body into the scene's glass at its own alpha, as the viewport does; the CPU rasterizer draws the solid bodies first (they own the depth buffer), then the see-through ones blended over them, far sides before near sides and without writing depth, so what lies inside shows and a line between the two is not hidden. - `snapshot --body NAME:opacity=0.3,color=#rrggbb`, `--tool NAME` (that body solid in the tool colour, the rest see-through) and `--section z=27` run the commands the app itself runs (`appearance.assign`, `inspect.section`): the options are shortcuts, not a second renderer. Co-Authored-By: Claude Opus 5 * Tests: measure the tool colour as it is drawn through a see-through target The tool-colour filter was derived on paper and demanded a red more than twice either other channel, which the target in front of it tints away (measured: (200, 108, 85) through opacity 0.3); and the colour check painted the tool, which a solid target hides. Co-Authored-By: Claude Opus 5 * fmt * Snapshot options: strip the colour's # rather than slicing it; README Slicing `value[1..]` on an input-derived string is what the house rules ask us not to write, even where a length check has already made it safe. The error a failed assignment reports now names the body rather than claiming it came from --body, since --tool reaches it too. Co-Authored-By: Claude Opus 5 * --tool: assign the bodies around the tool in groups, not one command at a time Each appearance.assign is an undo step with a document snapshot behind it, so one per body made --tool cost grow with the size of the design for no reason: the bodies around the tool all get the same opacity, and the ones that share a colour can be named in one call. A design whose bodies all wear the default grey now costs two commands whatever its size. Co-Authored-By: Claude Opus 5 * Rasterizer: say where its glass and the GPU's differ Splitting each see-through body by facing orders its own two layers; it does not sort across bodies, which the GPU does. Worth stating rather than leaving a reader to find it. Co-Authored-By: Claude Opus 5 --------- Co-authored-by: Claude Opus 5 Co-authored-by: bherbruck --- ATTRIBUTION.md | 1 + README.md | 4 + apps/solidcraft-cli/src/main.rs | 21 +- apps/solidcraft-cli/src/preview.rs | 286 ++++++++++++++++++ .../tests/snapshot_appearance.rs | 221 ++++++++++++++ crates/engine/src/cmd/file_thumbnail.rs | 3 +- crates/engine/src/view.rs | 5 +- crates/engine/src/view_palette_tests.rs | 28 ++ crates/gpu/src/capture.rs | 73 ++++- crates/gpu/tests/depth.rs | 7 +- crates/mcp/src/tools.rs | 4 +- crates/render/src/lib.rs | 2 +- crates/render/src/raster.rs | 283 +++++++++++------ crates/render/src/scene.rs | 30 ++ crates/ui-egui/src/file_load.rs | 4 +- docs/book/scripts/tool-preview.json | 7 + docs/book/src/guide/getting-started.md | 29 ++ 17 files changed, 903 insertions(+), 105 deletions(-) create mode 100644 apps/solidcraft-cli/src/preview.rs create mode 100644 apps/solidcraft-cli/tests/snapshot_appearance.rs create mode 100644 docs/book/scripts/tool-preview.json diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index f07c4e4f9..4d0a11256 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -45,6 +45,7 @@ Editable drawing code, native projects and shipped exports are collected under ` | docs/book/src/generated/enclosure.png | SolidCraft contributors | rendered by `cargo xtask book` (`solidcraft-cli snapshot docs/book/scripts/enclosure.json`; gitignored) | MIT OR Apache-2.0 | | docs/book/src/generated/revolve.png | SolidCraft contributors | rendered by `cargo xtask book` (`solidcraft-cli snapshot docs/book/scripts/revolve.json`; gitignored) | MIT OR Apache-2.0 | | docs/book/src/generated/sheet-metal.png | SolidCraft contributors | rendered by `cargo xtask book` (`solidcraft-cli snapshot docs/book/scripts/sheet-metal.json`; gitignored) | MIT OR Apache-2.0 | +| docs/book/src/generated/tool-preview.png | SolidCraft contributors | rendered by `cargo xtask book` (`solidcraft-cli snapshot docs/book/scripts/tool-preview.json`; gitignored) | MIT OR Apache-2.0 | | assets/fonts/liberation-sans/LiberationSans-Regular.ttf | Red Hat, Inc. (Liberation Fonts 2.x; digitized data Google) | https://github.com/liberationfonts (Debian fonts-liberation), unmodified; licence text in assets/fonts/liberation-sans/OFL.txt; used for sketch Text outlines | SIL OFL 1.1 | | assets/fonts/biz-udp-gothic/BIZUDPGothic-Regular.ttf | The BIZ UDGothic Project Authors | https://github.com/googlefonts/morisawa-biz-ud-gothic (Google Fonts), unmodified; licence text in assets/fonts/biz-udp-gothic/OFL.txt; used for web UI Japanese font | SIL OFL 1.1 | | tests/oracle/17-loft/reference.stl | SolidCraft contributors | triangulation of our own recipe (tests/oracle/17-loft/recipe.json) built with FreeCAD as an external tool by tools/freecad-oracle | MIT OR Apache-2.0 | diff --git a/README.md b/README.md index f068a6483..bf81adecb 100644 --- a/README.md +++ b/README.md @@ -197,6 +197,9 @@ rebuild with no errors, replayed here at 2× speed. and an optional reviewed screenshot; opening GitHub does not submit the report. - **Headless CLI** `solidcraft-cli`: run command scripts, measure (volume, area, centre of mass, face/edge/vertex counts), export, render PNG snapshots and replay reference recipes. + A snapshot can draw a body see-through and another solid in a colour of its own, and cut + the model at a plane, so a picture shows the body a cut would remove inside the material + it meets. - **MCP server** `solidcraft-cli mcp`: AI agents model, measure and look at parts headless or in the running app (see below). @@ -207,6 +210,7 @@ cargo run --release -p solidcraft -- --sample # desktop app with a samp cargo run --release -p solidcraft-cli -- commands # the command registry cargo run --release -p solidcraft-cli -- run examples/bracket.json --out bracket.step cargo run --release -p solidcraft-cli -- snapshot examples/bracket.json --out bracket.png +cargo run --release -p solidcraft-cli -- snapshot part.solidcraft --out preview.png --tool Pin --section z=12 cargo run --release -p solidcraft-cli -- render examples/render-studio.json --out product.png cargo run --release -p solidcraft -- part.step # open a STEP file as a new design cargo run --release -p solidcraft-cli -- eval part.step # measure an imported STEP file diff --git a/apps/solidcraft-cli/src/main.rs b/apps/solidcraft-cli/src/main.rs index 38af451fb..6adaa8c46 100644 --- a/apps/solidcraft-cli/src/main.rs +++ b/apps/solidcraft-cli/src/main.rs @@ -7,6 +7,7 @@ //! solidcraft-cli bench-open [--parse-only] [--display LEVEL [--edit NAME EXPR]] loading timings as JSON lines //! solidcraft-cli bench-agent [--scale F] [--save F] [--script-out F] a ~1,300-body design built command by command, timed //! solidcraft-cli snapshot [--in design|part.step] --out shot.png [--width W] [--height H] [--view iso|front|top|…|NAME | --camera JSON] [--no-grid] [--no-axes] +//! [--body NAME:opacity=0.3,color=#rrggbb]... [--tool NAME]... [--section z=27] //! solidcraft-cli exec [json-params] run one command on an empty design //! solidcraft-cli commands the command registry as JSON //! solidcraft-cli recipe translate an oracle recipe to a script @@ -23,6 +24,7 @@ mod bench_agent; mod crashes; mod fuzz; mod oracle; +mod preview; mod recipe; mod render; mod spatial; @@ -50,11 +52,18 @@ const USAGE: &str = "usage: solidcraft-cli bench-open [--parse-only] [--display LEVEL [--edit NAME EXPR]] solidcraft-cli bench-agent [--scale F] [--save design.solidcraft] [--script-out script.json] solidcraft-cli snapshot [--in design.solidcraft|part.step] --out shot.png [--width W] [--height H] [--view NAME | --camera JSON] [--no-grid] [--no-axes] + [--body NAME:opacity=0.3,color=#rrggbb]... [--tool NAME]... [--section z=27] solidcraft-cli snapshot --in --out shot.png ... (as with run, --in starts from a design and the script runs on top of it; an option snapshot doesn't take is an error; --view: iso, front, back, top, bottom, left, right, or the name of a view saved in the design with view.save; --camera: {target: [x,y,z], yaw, pitch, distance, fov?} in mm and radians, as the MCP screenshot takes it (docs/mcp.md); - --no-grid and --no-axes leave the ground grid (on Z 0) and the origin's axes out of the picture) + --no-grid and --no-axes leave the ground grid (on Z 0) and the origin's axes out of the picture; + --body: how one body is drawn, as appearance.assign takes it: opacity 0-1 (below 1 is see-through, so what is inside + it shows) and color #rrggbb, either or both, once per body; + --tool: draw this body solid in the tool colour and every other body see-through, so a cut's or a join's tool body + is visible inside the material it meets; a later --body overrides it; + --section: cut the model as inspect.section does, so the inside shows: z=27 (the plane through that world + coordinate, keeping the smaller side), add ,flip to keep the other side, or XY, XZ, YZ, or its own JSON) solidcraft-cli render --out image.png [--setup NAME] [--width W] [--height H] [--transparent] [--overwrite] [--timeout SECONDS] solidcraft-cli exec [json-params] solidcraft-cli commands @@ -405,7 +414,12 @@ fn install_renderer() { fn cmd_snapshot(args: &[String]) -> Result<(), String> { install_renderer(); - known_flags("snapshot", args, &["--in", "--out", "--width", "--height", "--view", "--camera"], &["--no-grid", "--no-axes"])?; + known_flags( + "snapshot", + args, + &["--in", "--out", "--width", "--height", "--view", "--camera", "--body", "--tool", "--section"], + &["--no-grid", "--no-axes"], + )?; if positional(args).is_none() && flag(args, "--in").is_none() { return Err(USAGE.to_string()); } @@ -416,6 +430,9 @@ fn cmd_snapshot(args: &[String]) -> Result<(), String> { }; let (w, h) = (size("--width", 1280)?, size("--height", 800)?); let mut s = open(flag(args, "--in"), positional(args))?; + // How the bodies are drawn and where the model is cut, through the commands the app's + // Appearance dialog and Section Analysis run (`preview`). + preview::apply(&mut s, &flags(args, "--body"), &flags(args, "--tool"), flag(args, "--section"))?; // The camera choices of the MCP `screenshot`, through the same command (`view.apply`): a // standard view, a view saved in the design, or an explicit camera. A script that applies a // view itself sets the camera too; without any, the iso view framing the model. diff --git a/apps/solidcraft-cli/src/preview.rs b/apps/solidcraft-cli/src/preview.rs new file mode 100644 index 000000000..98095fc24 --- /dev/null +++ b/apps/solidcraft-cli/src/preview.rs @@ -0,0 +1,286 @@ +//! What a `snapshot` draws see-through, what it draws in a colour of its own, and where it cuts +//! the model: the `--body`, `--tool` and `--section` options. +//! +//! None of this is a renderer of its own. Each option turns into the command the app itself runs +//! — `appearance.assign` for the Appearance dialog, `inspect.section` for Section Analysis — so +//! a picture of a tool body inside a translucent target is the picture the window would show +//! with the same appearances assigned, and a script can do the same thing without the options. + +use serde_json::{Value, json}; +use solidcraft_engine::Session; + +/// How see-through the bodies around a `--tool` are drawn: enough to read the tool through them, +/// solid enough to keep the shape of the material it meets. +pub const TARGET_OPACITY: f64 = 0.3; + +/// A `--tool` body's colour: the hue the viewport's feature preview uses for removed material, +/// so a cut's tool looks in a picture the way the preview looks in the window. +pub const TOOL_COLOR: &str = "#e8542c"; + +/// The colour of a body with no appearance of its own ([`solidcraft_engine::view::colors::BODY`]), +/// as `appearance.assign` takes it. Giving a body an opacity means giving it a look, and a look +/// carries a colour: this keeps the one it is already drawn in. +fn default_body_hex() -> String { + let c = solidcraft_engine::view::colors::BODY; + format!("#{:02x}{:02x}{:02x}", c.0, c.1, c.2) +} + +/// How one body is drawn: `--body NAME:opacity=0.3,color=#cc3333`. Either key alone is enough; +/// the other keeps what the design already says. +#[derive(Debug, PartialEq)] +pub struct BodyLook { + pub name: String, + pub opacity: Option, + pub color: Option, +} + +/// `NAME:key=value[,key=value]`, or `NAME` on its own (which says nothing and is an error: +/// a body is named here to change how it is drawn). +pub fn parse_body(spec: &str) -> Result { + let (name, rest) = spec + .split_once(':') + .ok_or_else(|| format!("--body `{spec}` must be NAME:key=value (`Target:opacity=0.3`, `Tool:color=#cc3333`, keys separated by commas)"))?; + let name = name.trim(); + if name.is_empty() { + return Err(format!("--body `{spec}` names no body")); + } + let mut look = BodyLook { name: name.to_owned(), opacity: None, color: None }; + for part in rest.split(',') { + let part = part.trim(); + if part.is_empty() { + continue; + } + let (key, value) = part.split_once('=').ok_or_else(|| format!("--body {name}: `{part}` must be key=value (opacity, color)"))?; + let value = value.trim(); + match key.trim().to_ascii_lowercase().as_str() { + "opacity" => { + let o: f64 = value.parse().map_err(|_| format!("--body {name}: opacity must be a number 0 to 1, not `{value}`"))?; + if !o.is_finite() || !(0.0..=1.0).contains(&o) { + return Err(format!("--body {name}: opacity must be 0 to 1, not `{value}`")); + } + look.opacity = Some(o); + } + "color" => { + let digits = value.strip_prefix('#').filter(|h| h.len() == 6 && h.chars().all(|c| c.is_ascii_hexdigit())); + let digits = digits.ok_or_else(|| format!("--body {name}: color must be #rrggbb, not `{value}`"))?; + look.color = Some(format!("#{}", digits.to_ascii_lowercase())); + } + other => return Err(format!("--body {name}: unknown key `{other}` (opacity, color)")), + } + } + if look.opacity.is_none() && look.color.is_none() { + return Err(format!("--body `{spec}` asks for nothing: give opacity, color, or both")); + } + Ok(look) +} + +/// The `inspect.section` parameters a `--section` spec asks for: `z=27` (the plane through that +/// world coordinate, its normal along +Z), `XY` (a named plane through the origin), either with +/// `,flip` to keep the other side, or the command's own JSON object. +pub fn parse_section(spec: &str) -> Result { + let spec = spec.trim(); + if spec.starts_with('{') { + return serde_json::from_str(spec).map_err(|e| format!("--section: not JSON: {e}")); + } + let mut parts = spec.split(',').map(str::trim); + let plane = parts.next().unwrap_or_default(); + let mut flip = false; + for p in parts { + match p.to_ascii_lowercase().as_str() { + "" => {} + "flip" => flip = true, + other => return Err(format!("--section: unknown `{other}` (only `flip` follows the plane)")), + } + } + // A named plane through the world origin, as `inspect.section` takes it. + let mut params = match plane.to_ascii_uppercase().as_str() { + p @ ("XY" | "XZ" | "YZ") => json!({"plane": p}), + _ => { + // AXIS=VALUE: the plane whose normal is that axis, cutting at that world coordinate. + let (axis, at) = plane.split_once('=').ok_or_else(|| { + format!("--section `{spec}` must be z=27 (a world coordinate on an axis), XY, XZ, YZ, or the JSON inspect.section takes") + })?; + let at: f64 = at.trim().parse().map_err(|_| format!("--section {axis}: `{}` is not a number", at.trim()))?; + if !at.is_finite() { + return Err(format!("--section {axis}: `{at}` is not a finite coordinate")); + } + // The plane normal to each axis: Z is XY, Y is XZ, X is YZ. + let named = match axis.trim().to_ascii_lowercase().as_str() { + "x" => "YZ", + "y" => "XZ", + "z" => "XY", + other => return Err(format!("--section: unknown axis `{other}` (x, y or z)")), + }; + json!({"plane": named, "at": at}) + } + }; + if flip { + params["flip"] = json!(true); + } + Ok(params) +} + +/// The design's body names, for an error that says which ones there are. +fn body_names(s: &Session) -> Vec { + s.model.state().bodies.iter().map(|b| b.name.clone()).collect() +} + +/// The colour and opacity a body is drawn with now, as `appearance.assign` takes them: its own +/// appearance, else its component's or material's, else the default body colour. +fn current_look(s: &mut Session, name: &str) -> Result<(String, f64), String> { + let reply = s.execute("appearance.list", &json!({"body": name})).map_err(|e| e.to_string())?; + let body = reply.get("body"); + let look = body.and_then(|b| b.get("appearance")).filter(|a| !a.is_null()); + let hex = look + .and_then(|a| a.get("color")) + .and_then(Value::as_str) + .map(str::to_owned) + // No appearance, but an imported colour: `body.color` is that colour, 0..1 per channel. + .or_else(|| { + let c = body?.get("color")?.as_array()?; + let ch = |i: usize| -> Option { Some((c.get(i)?.as_f64()?.clamp(0.0, 1.0) * 255.0).round() as u8) }; + Some(format!("#{:02x}{:02x}{:02x}", ch(0)?, ch(1)?, ch(2)?)) + }) + .unwrap_or_else(default_body_hex); + let opacity = look.and_then(|a| a.get("opacity")).and_then(Value::as_f64).filter(|o| o.is_finite()).unwrap_or(1.0); + Ok((hex, opacity)) +} + +/// Draw `name` with `look`, keeping whichever of colour and opacity it does not give. +fn assign(s: &mut Session, look: &BodyLook) -> Result<(), String> { + let name = &look.name; + if !body_names(s).iter().any(|b| b == name) { + return Err(format!("no body `{name}` in the design (it has {})", body_list(s))); + } + let (hex, opacity) = current_look(s, name)?; + let params = json!({ + "bodies": [name], + "color": look.color.clone().unwrap_or(hex), + "opacity": look.opacity.unwrap_or(opacity), + }); + s.execute("appearance.assign", ¶ms).map(|_| ()).map_err(|e| format!("drawing `{name}`: {e}")) +} + +/// The design's bodies, named, for an error message. +fn body_list(s: &Session) -> String { + let names = body_names(s); + if names.is_empty() { "no bodies".to_owned() } else { names.join(", ") } +} + +/// Apply the options to the session, in the order a later one overrides an earlier: the `--tool` +/// preview first (it speaks for every body), then each `--body`, then the section. +pub fn apply(s: &mut Session, bodies: &[&str], tools: &[&str], section: Option<&str>) -> Result<(), String> { + // Everything is read before anything is drawn, so a misspelt option is an error rather than + // half a picture. + let looks: Vec = bodies.iter().map(|spec| parse_body(spec)).collect::>()?; + let section = section.map(parse_section).transpose()?; + if !tools.is_empty() { + let names = body_names(s); + for t in tools { + if !names.iter().any(|b| b == t) { + return Err(format!("--tool: no body `{t}` in the design (it has {})", body_list(s))); + } + } + // Everything but the tool see-through, in the colour it already has, so the tool reads + // against the material it meets. Bodies that share a colour are assigned together: a + // design of many bodies then costs a command or two rather than one for each. + let mut around: std::collections::BTreeMap> = std::collections::BTreeMap::new(); + for name in names.iter().filter(|n| !tools.contains(&n.as_str())) { + around.entry(current_look(s, name)?.0).or_default().push(name.clone()); + } + for (hex, sharing_it) in around { + let params = json!({"bodies": sharing_it, "color": hex, "opacity": TARGET_OPACITY}); + s.execute("appearance.assign", ¶ms).map_err(|e| format!("--tool: {e}"))?; + } + // Then the tool itself, solid in the tool colour. + let params = json!({"bodies": tools, "color": TOOL_COLOR, "opacity": 1.0}); + s.execute("appearance.assign", ¶ms).map_err(|e| format!("--tool: {e}"))?; + } + for look in &looks { + assign(s, look)?; + } + if let Some(params) = section { + s.execute("inspect.section", ¶ms).map_err(|e| format!("--section: {e}"))?; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// `--body` names a body and says how it is drawn. Either key alone is enough. + #[test] + fn a_body_spec_is_a_name_and_the_keys_appearance_assign_takes() { + let look = |s: &str| parse_body(s).unwrap(); + assert_eq!(look("Target:opacity=0.3"), BodyLook { name: "Target".into(), opacity: Some(0.3), color: None }); + assert_eq!(look("Tool:color=#CC3333"), BodyLook { name: "Tool".into(), opacity: None, color: Some("#cc3333".into()) }); + assert_eq!(look("Tool: opacity = 1 , color = #00ff00 "), BodyLook { name: "Tool".into(), opacity: Some(1.0), color: Some("#00ff00".into()) }); + // A body name with a space in it, as the browser shows them. + assert_eq!(look("Bracket arm:opacity=0").name, "Bracket arm"); + assert_eq!(look("A:opacity=0").opacity, Some(0.0)); + } + + /// Every way of getting `--body` wrong is an error that says what it takes, never a panic + /// and never a silently ignored option. + #[test] + fn a_bad_body_spec_says_what_it_takes() { + for (spec, expect) in [ + ("Target", "NAME:key=value"), + (":opacity=0.3", "names no body"), + ("Target:", "asks for nothing"), + ("Target:opacity", "key=value"), + ("Target:opacity=high", "0 to 1"), + ("Target:opacity=1.5", "0 to 1"), + ("Target:opacity=-0.2", "0 to 1"), + ("Target:opacity=NaN", "0 to 1"), + ("Target:opacity=inf", "0 to 1"), + ("Target:color=red", "#rrggbb"), + ("Target:color=#ccc", "#rrggbb"), + ("Target:color=#gggggg", "#rrggbb"), + ("Target:alpha=0.3", "unknown key `alpha`"), + ] { + let e = parse_body(spec).err().unwrap_or_else(|| panic!("{spec} was accepted")); + assert!(e.contains(expect), "{spec}: {e}"); + } + } + + /// A `--section` spec is the plane `inspect.section` cuts with: an axis and a world + /// coordinate, a named plane, `flip` for the other side, or the command's own JSON. + #[test] + fn a_section_spec_is_the_plane_inspect_section_takes() { + let p = |s: &str| parse_section(s).unwrap(); + // The plane normal to each axis, cutting at that coordinate. + assert_eq!(p("z=27"), json!({"plane": "XY", "at": 27.0})); + assert_eq!(p("y=-5.5"), json!({"plane": "XZ", "at": -5.5})); + assert_eq!(p("X=0"), json!({"plane": "YZ", "at": 0.0})); + assert_eq!(p("z=27,flip"), json!({"plane": "XY", "at": 27.0, "flip": true})); + // A named plane through the origin, and the command's own parameters. + assert_eq!(p("XY"), json!({"plane": "XY"})); + assert_eq!(p("yz,flip"), json!({"plane": "YZ", "flip": true})); + assert_eq!(p("{\"plane\": \"XY\", \"offset\": 4}"), json!({"plane": "XY", "offset": 4})); + } + + #[test] + fn a_bad_section_spec_says_what_it_takes() { + for (spec, expect) in [ + ("27", "z=27"), + ("w=4", "unknown axis `w`"), + ("z=high", "is not a number"), + ("z=inf", "not a finite coordinate"), + ("z=27,upside-down", "unknown `upside-down`"), + ("{\"plane\":", "not JSON"), + ] { + let e = parse_section(spec).err().unwrap_or_else(|| panic!("{spec} was accepted")); + assert!(e.contains(expect), "{spec}: {e}"); + } + } + + /// The tool colour is the one the options document, in the form `appearance.assign` takes. + #[test] + fn the_tool_colour_is_a_hex_colour_the_command_takes() { + assert_eq!(parse_body(&format!("Tool:color={TOOL_COLOR}")).unwrap().color, Some(TOOL_COLOR.to_owned())); + assert!((0.0..1.0).contains(&TARGET_OPACITY), "a target must be see-through: {TARGET_OPACITY}"); + assert_eq!(default_body_hex(), "#b0bac6"); + } +} diff --git a/apps/solidcraft-cli/tests/snapshot_appearance.rs b/apps/solidcraft-cli/tests/snapshot_appearance.rs new file mode 100644 index 000000000..c02bec4d2 --- /dev/null +++ b/apps/solidcraft-cli/tests/snapshot_appearance.rs @@ -0,0 +1,221 @@ +//! `snapshot --body`, `--tool` and `--section`: a picture of a tool body inside the material it +//! meets, which is the one picture that says whether a cut reaches through. +//! +//! Each option is a shortcut for the command the app itself runs (`appearance.assign`, +//! `inspect.section`), so every test here asserts that the option's picture is the picture of a +//! script that runs those commands — not that the pixels match a stored image. Pictures are +//! compared with a tolerance, and the tests run on whatever renderer the machine has (a GPU, a +//! software adapter, or the CPU rasterizer), because they only ever compare two pictures this +//! same CLI drew. + +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use serde_json::{Value, json}; + +static NEXT: AtomicUsize = AtomicUsize::new(0); + +const SIZE: (u32, u32) = (200, 140); + +/// A PNG's size and RGBA pixels. +fn decode(png: &[u8]) -> (u32, u32, Vec) { + let img = image::load_from_memory_with_format(png, image::ImageFormat::Png).unwrap().to_rgba8(); + (img.width(), img.height(), img.into_raw()) +} + +/// Pixels of two same-sized pictures that differ by more than a little in some channel. +fn differing(a: &[u8], b: &[u8]) -> usize { + let ((wa, ha, a), (wb, hb, b)) = (decode(a), decode(b)); + assert_eq!((wa, ha), (wb, hb), "pictures of different sizes"); + a.as_chunks::<4>().0.iter().zip(b.as_chunks::<4>().0).filter(|(p, q)| p.iter().zip(q.iter()).any(|(x, y)| x.abs_diff(*y) > 16)).count() +} + +/// The same picture: a renderer's output may differ by a few levels or a stray edge pixel. +#[track_caller] +fn assert_same(a: &[u8], b: &[u8], what: &str) { + let (n, total) = (differing(a, b), (SIZE.0 * SIZE.1) as usize); + assert!(n * 500 <= total, "{what}: {n} of {total} pixels differ"); +} + +/// Different pictures: more than stray pixels differ. +#[track_caller] +fn assert_differs(a: &[u8], b: &[u8], what: &str) { + let n = differing(a, b); + assert!(n >= 100, "{what}: only {n} pixels differ"); +} + +/// How much of a picture is the tool colour (`preview::TOOL_COLOR`, #e8542c): a red neither +/// the default body grey nor the background has, still recognisable once a see-through body in +/// front of it has tinted it (measured on this machine: (200, 108, 85) through a target at +/// opacity 0.3, against (164, 173, 184) for the plain grey). +fn tool_pixels(png: &[u8]) -> usize { + let (_, _, px) = decode(png); + px.as_chunks::<4>().0.iter().filter(|p| p[0] > 140 && p[0] > p[1].saturating_add(50) && p[0] > p[2].saturating_add(50)).count() +} + +struct Scratch(PathBuf); + +impl Scratch { + fn new() -> Self { + let dir = + std::env::temp_dir().join(format!("solidcraft-snapshot-appearance-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + std::fs::create_dir(&dir).unwrap(); + Self(dir) + } + + /// A plate with a pin standing in it: the tool body a cut would remove, reaching 6 mm short + /// of the far face, which is exactly what a picture is supposed to show and a volume is not. + /// `more` runs on top. + fn script(&self, name: &str, more: &[Value]) -> PathBuf { + let mut steps = vec![ + json!({"command": "solid.box", "params": {"length": 50, "width": 34, "height": 20, "center": [0, 0, 10], "body_name": "Target"}}), + json!({"command": "solid.cylinder", "params": {"diameter": 12, "height": 14, "base": [0, 0, 0], "operation": "new_body", "body_name": "Tool"}}), + ]; + steps.extend(more.iter().cloned()); + let path = self.0.join(name); + std::fs::write(&path, json!({"commands": steps}).to_string()).unwrap(); + path + } + + fn run(&self, script: &Path, out: &str, extra: &[&str]) -> Output { + let (w, h) = (SIZE.0.to_string(), SIZE.1.to_string()); + Command::new(env!("CARGO_BIN_EXE_solidcraft-cli")) + .arg("snapshot") + .arg(script) + .arg("--out") + .arg(self.0.join(out)) + .args(["--width", &w, "--height", &h, "--no-grid", "--no-axes"]) + .args(extra) + .output() + .unwrap() + } + + /// The PNG `snapshot` writes. + fn snapshot(&self, script: &Path, out: &str, extra: &[&str]) -> Vec { + let output = self.run(script, out, extra); + assert!(output.status.success(), "{extra:?}: {}", String::from_utf8_lossy(&output.stderr)); + let png = std::fs::read(self.0.join(out)).unwrap(); + assert!(png.starts_with(b"\x89PNG"), "{extra:?}"); + png + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// `--body NAME:opacity=…` draws that body see-through, and the picture is the one a script +/// gets by assigning the same appearance itself: the option is the command, not a second way +/// of drawing. +#[test] +fn a_body_drawn_see_through_is_the_picture_of_the_same_appearance_assigned() { + let dir = Scratch::new(); + let plain = dir.script("plain.json", &[]); + let assigned = + dir.script("assigned.json", &[json!({"command": "appearance.assign", "params": {"bodies": ["Target"], "color": "#b0bac6", "opacity": 0.3}})]); + let solid = dir.snapshot(&plain, "solid.png", &[]); + let see_through = dir.snapshot(&plain, "see-through.png", &["--body", "Target:opacity=0.3"]); + assert_differs(&see_through, &solid, "--body opacity was ignored"); + assert_same(&see_through, &dir.snapshot(&assigned, "by-script.png", &[]), "the same appearance assigned by a script"); + + // The option's colour is the design's too. It names the target, not the tool: the tool is + // inside the target, so a solid target hides whatever colour the tool is given. + let painted = + dir.script("painted.json", &[json!({"command": "appearance.assign", "params": {"bodies": ["Target"], "color": "#00aa33", "opacity": 1.0}})]); + let by_option = dir.snapshot(&plain, "painted.png", &["--body", "Target:color=#00aa33"]); + assert_differs(&by_option, &solid, "--body color was ignored"); + assert_same(&by_option, &dir.snapshot(&painted, "painted-script.png", &[]), "the same colour assigned by a script"); +} + +/// `--tool NAME` is the whole point: the tool solid in the tool colour, every other body +/// see-through, so the tool shows inside the material it meets. The tool's colour covers more +/// of the picture than it does without the option, because the target no longer hides it. +#[test] +fn a_tool_shows_through_the_bodies_around_it() { + let dir = Scratch::new(); + let script = dir.script("part.json", &[]); + let plain = dir.snapshot(&script, "plain.png", &["--view", "front"]); + let preview = dir.snapshot(&script, "preview.png", &["--view", "front", "--tool", "Tool"]); + assert_differs(&preview, &plain, "--tool was ignored"); + // Seen from the front the plate hides the pin completely; the preview shows all of it. + assert_eq!(tool_pixels(&plain), 0, "nothing is the tool colour before the option"); + assert!(tool_pixels(&preview) > 200, "the tool shows through the target: {} pixels", tool_pixels(&preview)); + + // It is the two commands it stands for, run in that order. + let by_script = dir.script( + "by-script.json", + &[ + json!({"command": "appearance.assign", "params": {"bodies": ["Target"], "color": "#b0bac6", "opacity": 0.3}}), + json!({"command": "appearance.assign", "params": {"bodies": ["Tool"], "color": "#e8542c", "opacity": 1.0}}), + ], + ); + assert_same(&preview, &dir.snapshot(&by_script, "script.png", &["--view", "front"]), "the appearances --tool assigns"); + + // A later --body overrides what --tool said. + let overridden = dir.snapshot(&script, "override.png", &["--view", "front", "--tool", "Tool", "--body", "Tool:color=#2255cc"]); + assert!(tool_pixels(&overridden) < 50, "--body after --tool decides the tool's colour"); +} + +/// `--section` cuts the model where `inspect.section` would, and the same spec written as the +/// command's own JSON, or as the command in a script, gives the same picture. +#[test] +fn a_section_cuts_the_model_as_inspect_section_does() { + let dir = Scratch::new(); + let script = dir.script("part.json", &[]); + let whole = dir.snapshot(&script, "whole.png", &[]); + let cut = dir.snapshot(&script, "cut.png", &["--section", "z=12"]); + assert_differs(&cut, &whole, "--section was ignored"); + assert_same(&cut, &dir.snapshot(&script, "cut-json.png", &["--section", r#"{"plane": "XY", "at": 12}"#]), "the command's own JSON"); + let by_script = dir.script("sectioned.json", &[json!({"command": "inspect.section", "params": {"plane": "XY", "at": 12}})]); + assert_same(&cut, &dir.snapshot(&by_script, "by-script.png", &[]), "inspect.section in a script"); + + // The other side of the same plane is a different picture. + let flipped = dir.snapshot(&script, "flipped.png", &["--section", "z=12,flip"]); + assert_differs(&flipped, &cut, "flip keeps the other side"); + + // A section through a see-through target still shows the tool inside it. + let both = dir.snapshot(&script, "both.png", &["--section", "z=12", "--tool", "Tool"]); + assert_differs(&both, &cut, "--tool and --section together"); + assert!(tool_pixels(&both) > 100, "the tool is in the cut picture"); +} + +/// Every way of getting the options wrong is an error that says what it takes, and writes no +/// picture: a snapshot that quietly ignored an option would be a lie about the design. +#[test] +fn a_body_tool_or_section_that_cannot_be_used_is_an_error_and_writes_nothing() { + let dir = Scratch::new(); + let script = dir.script("part.json", &[]); + let cases: [(&[&str], &str); 8] = [ + (&["--body", "Nowhere:opacity=0.3"], "no body `Nowhere`"), + (&["--body", "Target"], "NAME:key=value"), + (&["--body", "Target:opacity=3"], "0 to 1"), + (&["--body", "Target:alpha=0.3"], "unknown key `alpha`"), + (&["--body", "Target:color=red"], "#rrggbb"), + (&["--tool", "Nowhere"], "no body `Nowhere`"), + (&["--section", "q=1"], "unknown axis `q`"), + (&["--section", "nonsense"], "z=27"), + ]; + for (extra, expect) in cases { + let output = dir.run(&script, "never.png", extra); + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(1), "{extra:?}: {stderr}"); + assert!(stderr.contains(expect), "{extra:?}: {stderr}"); + assert!(output.stdout.is_empty() && !dir.0.join("never.png").exists(), "{extra:?}"); + } + // An error naming a body says which bodies the design has. + let stderr = String::from_utf8_lossy(&dir.run(&script, "never.png", &["--tool", "Nowhere"]).stderr).to_string(); + assert!(stderr.contains("Target") && stderr.contains("Tool"), "{stderr}"); +} + +/// The usage text says what the options do. +#[test] +fn the_usage_names_the_body_tool_and_section_options() { + let output = Command::new(env!("CARGO_BIN_EXE_solidcraft-cli")).arg("snapshot").output().unwrap(); + let stderr = String::from_utf8_lossy(&output.stderr); + for word in ["--body", "--tool", "--section", "appearance.assign", "inspect.section", "see-through"] { + assert!(stderr.contains(word), "usage lacks {word}: {stderr}"); + } +} diff --git a/crates/engine/src/cmd/file_thumbnail.rs b/crates/engine/src/cmd/file_thumbnail.rs index 30c7f09ca..bc3c4ff95 100644 --- a/crates/engine/src/cmd/file_thumbnail.rs +++ b/crates/engine/src/cmd/file_thumbnail.rs @@ -36,7 +36,8 @@ fn scene(s: &Session) -> Option<(Scene, Camera)> { let color = s.doc.body_color(body).map_or(crate::view::colors::BODY, |[r, g, b]| Rgb(channel(r), channel(g), channel(b))); let face_colors = s.doc.face_colors(body).into_iter().map(|(face, look)| (face as u32, Rgb(look.color[0], look.color[1], look.color[2]))).collect(); - scene.meshes.push(SceneMesh { mesh, color, face_colors }); + let opacity = s.doc.model_body_opacity(body) as f32; + scene.meshes.push(SceneMesh { mesh, color, face_colors, opacity }); } if bounds.is_empty() { return None; diff --git a/crates/engine/src/view.rs b/crates/engine/src/view.rs index f2ebceebe..5e3c19a28 100644 --- a/crates/engine/src/view.rs +++ b/crates/engine/src/view.rs @@ -501,7 +501,10 @@ fn build_scene( } else { s.doc.face_colors(body).into_iter().map(|(f, l)| (f as u32, Rgb(l.color[0], l.color[1], l.color[2]))).collect() }; - sc.meshes.push(SceneMesh { mesh: Arc::clone(&mesh), color, face_colors }); + // A see-through appearance is drawn see-through, as the viewport draws it; a selected + // body is drawn solid, so the selection colour reads. + let opacity = if selected { 1.0 } else { s.doc.model_body_opacity(body) as f32 }; + sc.meshes.push(SceneMesh { mesh: Arc::clone(&mesh), color, face_colors, opacity }); for (i, e) in mesh.edges.iter().enumerate() { if !mesh.shaded_edge_visible(i) { continue; diff --git a/crates/engine/src/view_palette_tests.rs b/crates/engine/src/view_palette_tests.rs index 31d7fdfed..db1a02787 100644 --- a/crates/engine/src/view_palette_tests.rs +++ b/crates/engine/src/view_palette_tests.rs @@ -191,3 +191,31 @@ fn every_scene_colour_comes_from_its_palette_and_appearances_stay() { assert_eq!(mesh(&default, "Plain").0, colors::BODY); assert_eq!(mesh(&default, "Picked").0, colors::BODY_SELECTED); } + +/// A see-through appearance reaches the picture: the scene carries the body's opacity, so the +/// renderers draw it as glass and what is inside it shows. A selected body stays solid, as in +/// the viewport, so the selection colour reads. +#[test] +fn a_see_through_appearance_reaches_the_scene() { + let mut s = Session::default(); + for (name, x) in [("Target", 0.), ("Tool", 20.), ("Picked", 40.)] { + s.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10, "corner": [x, 0, 0], "operation": "new_body", "body_name": name})) + .unwrap(); + } + s.execute("appearance.assign", &json!({"bodies": ["Target"], "color": "#b0bac6", "opacity": 0.3})).unwrap(); + s.execute("appearance.assign", &json!({"bodies": ["Picked"], "color": "#b0bac6", "opacity": 0.3})).unwrap(); + s.selection = vec![Sel::Body { name: "Picked".into() }]; + let cam = home_camera(&s); + let sc = scene(&s, &cam); + let names: Vec = s.world_state().bodies.iter().filter(|b| s.body_visible(&b.name)).map(|b| b.name.clone()).collect(); + let opacity = |name: &str| names.iter().position(|n| n == name).and_then(|i| sc.meshes.get(i)).map(|m| (m.opacity, m.glass())).unwrap(); + + assert_eq!(opacity("Target"), (0.3, true), "the design's opacity is the one the renderers draw"); + assert_eq!(opacity("Tool"), (1.0, false), "a body with no appearance of its own is solid"); + assert_eq!(opacity("Picked"), (1.0, false), "a selected body is drawn solid, so the selection colour reads"); + + // Clearing the appearance makes it solid again. + s.execute("appearance.assign", &json!({"bodies": ["Target"], "color": null})).unwrap(); + let sc = scene(&s, &cam); + assert_eq!(sc.meshes.first().map(|m| m.opacity), Some(1.0)); +} diff --git a/crates/gpu/src/capture.rs b/crates/gpu/src/capture.rs index 8d93c812d..ae762563c 100644 --- a/crates/gpu/src/capture.rs +++ b/crates/gpu/src/capture.rs @@ -350,11 +350,14 @@ fn frame(scene: &Scene, cam: &Camera, [width, height]: [u32; 2], key: u64, acces /// A scene's meshes and lines as the viewport's model scene: faces in their colours (smooth /// normals; a face normal where a vertex has none), lines as wide lines (over everything when -/// `on_top`), the grid under everything. +/// `on_top`), the grid under everything. A body whose appearance is see-through +/// ([`solidcraft_render::SceneMesh::glass`]) goes into the scene's glass, drawn as the viewport +/// draws glass: far sides first, then near sides, so what lies inside it shows through. pub fn scene_geometry(scene: &Scene) -> GpuScene { let mut sc = GpuScene::default(); - let c4 = |c: Rgb| [c.0, c.1, c.2, 255]; for m in &scene.meshes { + let alpha = (m.alpha() * 255.0).round().clamp(0.0, 255.0) as u8; + let c4 = |c: Rgb| [c.0, c.1, c.2, alpha]; let faces: HashMap = m.face_colors.iter().copied().collect(); let mesh = &m.mesh; for (ti, t) in mesh.triangles.iter().enumerate() { @@ -363,10 +366,15 @@ pub fn scene_geometry(scene: &Scene) -> GpuScene { let flat = (b - a).cross(c - a).normalized().unwrap_or(Vec3::Z); for (k, p) in t.iter().zip([a, b, c]) { let n = mesh.normals.get(*k as usize).copied().filter(|n| n.is_finite() && n.len() > 0.5).unwrap_or(flat); - sc.tri(p.to_f32(), n.to_f32(), col); + if m.glass() { + sc.glass_tri(p.to_f32(), n.to_f32(), col); + } else { + sc.tri(p.to_f32(), n.to_f32(), col); + } } } } + let c4 = |c: Rgb| [c.0, c.1, c.2, 255]; for l in &scene.grid { for w in l.points.windows(2) { sc.under_line(w[0].to_f32(), w[1].to_f32(), c4(l.color), l.width as f32); @@ -470,3 +478,62 @@ fn background_pipeline(device: &wgpu::Device, samples: u32, depth: wgpu::Texture cache: None, }) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::view::TRI_SIZE; + use solidcraft_geom::Mesh; + use solidcraft_render::SceneMesh; + use std::sync::Arc; + + /// One triangle facing the camera. + fn sheet() -> Arc { + Arc::new(Mesh { + positions: vec![Vec3::new(-1.0, 0.0, -1.0), Vec3::new(1.0, 0.0, -1.0), Vec3::new(0.0, 0.0, 1.0)], + normals: vec![Vec3::new(0.0, -1.0, 0.0); 3], + triangles: vec![[0, 1, 2]], + tri_face: vec![0], + ..Default::default() + }) + } + + /// The alpha of a triangle `scene_geometry` wrote (the last byte of its first vertex). + fn alpha(bytes: &[u8]) -> Option { + bytes.get(TRI_SIZE - 1).copied() + } + + /// A body the design draws see-through goes into the scene's glass, at its own alpha, and + /// not among the solid triangles: that is how the viewport draws glass, and it is why a + /// headless picture of a translucent target shows the tool inside it. + #[test] + fn a_see_through_body_is_glass_at_its_own_alpha_and_a_solid_one_is_not() { + let mesh = |opacity: f32| SceneMesh { mesh: sheet(), color: Rgb(200, 30, 30), face_colors: Vec::new(), opacity }; + let geometry = |opacity: f32| scene_geometry(&Scene { meshes: vec![mesh(opacity)], ..Default::default() }); + + let solid = geometry(1.0); + assert_eq!((solid.tris.len(), solid.glass.len()), (3 * TRI_SIZE, 0)); + assert_eq!(alpha(&solid.tris), Some(255), "a solid body is drawn opaque"); + + let glass = geometry(0.3); + assert_eq!((glass.tris.len(), glass.glass.len()), (0, 3 * TRI_SIZE), "a see-through body is glass, not a solid triangle"); + assert_eq!(alpha(&glass.glass), Some(77), "0.3 of 255"); + + // The threshold and the floor are the viewport's: an appearance a hair under 1 stays + // solid, and opacity 0 still leaves a trace rather than vanishing. + let almost = geometry(0.9995); + assert_eq!((almost.tris.len(), almost.glass.len()), (3 * TRI_SIZE, 0), "an appearance a hair under 1 is still solid"); + assert_eq!(alpha(&geometry(0.0).glass), Some(13), "0.05 of 255"); + } + + /// A face with a colour of its own is drawn in that colour, and takes its body's opacity: + /// painting one face does not make the body solid again. + #[test] + fn a_painted_face_keeps_its_bodys_opacity() { + let mesh = SceneMesh { mesh: sheet(), color: Rgb(200, 30, 30), face_colors: vec![(0, Rgb(0, 255, 0))], opacity: 0.5 }; + let sc = scene_geometry(&Scene { meshes: vec![mesh], ..Default::default() }); + assert_eq!(sc.tris.len(), 0); + let first = sc.glass.get(TRI_SIZE - 4..TRI_SIZE); + assert_eq!(first, Some(&[0, 255, 0, 128][..]), "the face's own colour at the body's alpha"); + } +} diff --git a/crates/gpu/tests/depth.rs b/crates/gpu/tests/depth.rs index 32e1cbd1a..e95c378b6 100644 --- a/crates/gpu/tests/depth.rs +++ b/crates/gpu/tests/depth.rs @@ -146,12 +146,7 @@ fn sheet(tilt: f64) -> Mesh { /// A front view of `mesh` with `lines`, as part of a design of `radius`, 40 mm high on 200 px. fn front(mesh: Mesh, lines: Vec, radius: f64, fov: f64) -> (Scene, Camera) { - let scene = Scene { - meshes: vec![SceneMesh { mesh: Arc::new(mesh), color: Rgb(160, 165, 175), face_colors: Vec::new() }], - lines, - radius, - ..Default::default() - }; + let scene = Scene { meshes: vec![SceneMesh::solid(Arc::new(mesh), Rgb(160, 165, 175))], lines, radius, ..Default::default() }; let mut cam = Camera { distance: if fov > 0.0 { 25.0 / (fov * 0.5).tan() } else { 62.5 }, fov, ..Default::default() }; cam.set_view(StandardView::Front); (scene, cam) diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index 8f0c457bc..a5d4a9330 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -187,7 +187,9 @@ pub fn tool_definitions() -> Vec { Connected to the app: a screenshot of the window (source \"window\", the default) or a render of the model \ with the app's camera (source \"model\"). Both show an active section (inspect.section) with its cut face \ capped. `view` first turns the camera to a standard view or a saved named view (view.save), `camera` to any camera (as view.apply). \ - `grid: false` and `axes: false` leave the ground grid (on Z 0) and the origin's axes out of a model render.", + `grid: false` and `axes: false` leave the ground grid (on Z 0) and the origin's axes out of a model render. \ + A body whose appearance is see-through (appearance.assign with an `opacity` below 1) is drawn see-through, \ + so what is inside it shows: that is how to look at the body a cut would remove inside the material it meets.", obj( json!({ "view": string( diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 4ccf3315d..4f9e70be7 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -32,4 +32,4 @@ pub use curve_display::{PixelCurveView, SampledPath, SamplingBudget, SamplingQua pub use gif::gif; pub use product::{FaceAppearance, ProductMesh, ProductScene}; pub use raster::{Canvas, render, render_png, render_transparent}; -pub use scene::{Rgb, SECTION_CAP, Scene, SceneLine, SceneMesh, png}; +pub use scene::{MIN_ALPHA, Rgb, SECTION_CAP, SEE_THROUGH, Scene, SceneLine, SceneMesh, png}; diff --git a/crates/render/src/raster.rs b/crates/render/src/raster.rs index a9393ae0f..01ac16f5a 100644 --- a/crates/render/src/raster.rs +++ b/crates/render/src/raster.rs @@ -35,6 +35,40 @@ impl Canvas { } } +/// The order a scene's bodies are drawn in. Solid bodies come first and own the depth buffer; +/// the see-through ones are then blended over them, far sides before near sides, so a +/// translucent body reads like glass and whatever lies inside it shows through. This is the +/// order the GPU viewport draws its own glass in. +/// +/// Splitting each see-through body by facing orders its own two layers, which is what a single +/// translucent body needs. Two see-through bodies that overlap on screen blend in the order the +/// scene lists them, where the GPU sorts its glass triangles back to front: the difference shows +/// only where translucent bodies lie in front of each other, which the CPU rasterizer (a +/// fallback for machines without a GPU) does not try to match. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Pass { + Solid, + GlassFar, + GlassNear, +} + +impl Pass { + /// Does this pass draw the see-through bodies ([`SceneMesh::glass`])? + fn glass(self) -> bool { + self != Pass::Solid + } + + /// Does it draw a triangle whose facing is `inside` (away from the eye)? A solid body draws + /// both: its back faces show only where a section opens it. + fn takes(self, inside: bool) -> bool { + match self { + Pass::Solid => true, + Pass::GlassFar => inside, + Pass::GlassNear => !inside, + } + } +} + pub(crate) fn shade(n: Vec3, view_dir: Vec3, base: [f64; 3]) -> [f64; 3] { let n = if n.dot(view_dir) < 0.0 { -n } else { n }; let key = (view_dir * 0.8 + Vec3::new(-0.3, 0.2, 0.6)).normalized().unwrap_or(view_dir); @@ -79,91 +113,104 @@ pub fn render(scene: &Scene, cam: &Camera, w: usize, h: usize) -> Canvas { // depth test. let mut slope = vec![0f32; sw * sh]; let cap_tint = scene.cap.unwrap_or(SECTION_CAP).f(); - for sm in &scene.meshes { - let m = &sm.mesh; - let body = sm.color.f(); - let pts: Vec> = m.positions.iter().map(|p| project(*p)).collect(); - // 1 / clip w per vertex, for perspective-correct interpolation of world positions (so - // the section cuts along the plane, not a curve, in perspective views). - let inv_w: Vec = m.positions.iter().map(|p| 1.0 / vp.apply(*p)[3].max(1e-9)).collect(); - for (ti, t) in m.triangles.iter().enumerate() { - let face = m.tri_face.get(ti).copied(); - let base = sm.face_colors.iter().find(|(f, _)| Some(*f) == face).map_or(body, |(_, c)| c.f()); - let wp = t.map(|k| m.positions.get(k as usize).copied().unwrap_or_default()); - // Seen from inside (only where a section cuts the body open). - let to_eye = if cam.fov > 0.0 { cam.eye() - wp[0] } else { view_dir }; - let inside = (wp[1] - wp[0]).cross(wp[2] - wp[0]).dot(to_eye) < 0.0; - let iw = t.map(|k| inv_w.get(k as usize).copied().unwrap_or(1.0)); - let (Some(Some(a)), Some(Some(b)), Some(Some(cc))) = (pts.get(t[0] as usize), pts.get(t[1] as usize), pts.get(t[2] as usize)) else { - continue; - }; - let ns: Vec = t.iter().map(|k| m.normals.get(*k as usize).copied().unwrap_or(Vec3::Z)).collect(); - // A curved surface (its normals turn across the triangle) gets a silhouette line - // where it turns away from the eye. - let curved = ns.iter().any(|n| n.dist(ns[0]) > 1e-6); - let (x0, x1) = (a[0].min(b[0]).min(cc[0]).floor().max(0.0), a[0].max(b[0]).max(cc[0]).ceil().min(sw as f64 - 1.0)); - let (y0, y1) = (a[1].min(b[1]).min(cc[1]).floor().max(0.0), a[1].max(b[1]).max(cc[1]).ceil().min(sh as f64 - 1.0)); - if !(x0 <= x1 && y0 <= y1) { - continue; - } - let area = (b[0] - a[0]) * (cc[1] - a[1]) - (b[1] - a[1]) * (cc[0] - a[0]); - if area.abs() < 1e-12 { - continue; - } - let gx = ((b[2] - a[2]) * (cc[1] - a[1]) - (cc[2] - a[2]) * (b[1] - a[1])) / area; - let gy = ((cc[2] - a[2]) * (b[0] - a[0]) - (b[2] - a[2]) * (cc[0] - a[0])) / area; - let tri_slope = gx.hypot(gy) as f32; - for y in y0 as usize..=y1 as usize { - for x in x0 as usize..=x1 as usize { - let (px, py) = (x as f64 + 0.5, y as f64 + 0.5); - let w0 = ((b[0] - px) * (cc[1] - py) - (b[1] - py) * (cc[0] - px)) / area; - let w1 = ((cc[0] - px) * (a[1] - py) - (cc[1] - py) * (a[0] - px)) / area; - let w2 = 1.0 - w0 - w1; - if w0 < -1e-9 || w1 < -1e-9 || w2 < -1e-9 { - continue; - } - let (q0, q1, q2) = (w0 * iw[0], w1 * iw[1], w2 * iw[2]); - let qs = q0 + q1 + q2; - let (p0, p1, p2) = if qs > 1e-12 { (q0 / qs, q1 / qs, q2 / qs) } else { (w0, w1, w2) }; - if let Some((cn, cd)) = scene.clip - && cn.dot(wp[0] * p0 + wp[1] * p1 + wp[2] * p2) > cd - { - continue; - } - let z = (w0 * a[2] + w1 * b[2] + w2 * cc[2]) as f32; - let i = y * sw + x; - if c.depth.get(i).is_some_and(|d| z < *d) { - if let Some(d) = c.depth.get_mut(i) { - *d = z; - } - if let Some(s) = slope.get_mut(i) { - *s = tri_slope; - } - let n = (ns[0] * p0 + ns[1] * p1 + ns[2] * p2).normalized().unwrap_or(Vec3::Z); - let cut = scene.clip.is_some() && inside; - if let Some(d) = cap_depth.get_mut(i) { - *d = match cap_z { - Some([a, b, k]) if cut => ((a * px + b * py + k) as f32).min(z), - _ => f32::INFINITY, - }; - } - if cut { - // The cut: the body's colour tinted toward the cap colour, hatched - // at 45 degrees (as the viewport draws it). - let tinted: [f64; 3] = std::array::from_fn(|k| base[k] + (cap_tint[k] - base[k]) * 0.35); - let k = if ((x + y) / SS) % 9 < 2 { 0.6 } else { 1.0 }; - c.put(x, y, tinted.map(|v| v * k), 1.0); + for pass in [Pass::Solid, Pass::GlassFar, Pass::GlassNear] { + for sm in scene.meshes.iter().filter(|m| m.glass() == pass.glass()) { + let alpha = sm.alpha(); + let m = &sm.mesh; + let body = sm.color.f(); + let pts: Vec> = m.positions.iter().map(|p| project(*p)).collect(); + // 1 / clip w per vertex, for perspective-correct interpolation of world positions (so + // the section cuts along the plane, not a curve, in perspective views). + let inv_w: Vec = m.positions.iter().map(|p| 1.0 / vp.apply(*p)[3].max(1e-9)).collect(); + for (ti, t) in m.triangles.iter().enumerate() { + let face = m.tri_face.get(ti).copied(); + let base = sm.face_colors.iter().find(|(f, _)| Some(*f) == face).map_or(body, |(_, c)| c.f()); + let wp = t.map(|k| m.positions.get(k as usize).copied().unwrap_or_default()); + // Seen from inside: where a section cuts a solid body open, and the far side of + // a see-through one (drawn in the pass before its near side). + let to_eye = if cam.fov > 0.0 { cam.eye() - wp[0] } else { view_dir }; + let inside = (wp[1] - wp[0]).cross(wp[2] - wp[0]).dot(to_eye) < 0.0; + if !pass.takes(inside) { + continue; + } + let iw = t.map(|k| inv_w.get(k as usize).copied().unwrap_or(1.0)); + let (Some(Some(a)), Some(Some(b)), Some(Some(cc))) = (pts.get(t[0] as usize), pts.get(t[1] as usize), pts.get(t[2] as usize)) else { + continue; + }; + let ns: Vec = t.iter().map(|k| m.normals.get(*k as usize).copied().unwrap_or(Vec3::Z)).collect(); + // A curved surface (its normals turn across the triangle) gets a silhouette line + // where it turns away from the eye. + let curved = ns.iter().any(|n| n.dist(ns[0]) > 1e-6); + let (x0, x1) = (a[0].min(b[0]).min(cc[0]).floor().max(0.0), a[0].max(b[0]).max(cc[0]).ceil().min(sw as f64 - 1.0)); + let (y0, y1) = (a[1].min(b[1]).min(cc[1]).floor().max(0.0), a[1].max(b[1]).max(cc[1]).ceil().min(sh as f64 - 1.0)); + if !(x0 <= x1 && y0 <= y1) { + continue; + } + let area = (b[0] - a[0]) * (cc[1] - a[1]) - (b[1] - a[1]) * (cc[0] - a[0]); + if area.abs() < 1e-12 { + continue; + } + let gx = ((b[2] - a[2]) * (cc[1] - a[1]) - (cc[2] - a[2]) * (b[1] - a[1])) / area; + let gy = ((cc[2] - a[2]) * (b[0] - a[0]) - (b[2] - a[2]) * (cc[0] - a[0])) / area; + let tri_slope = gx.hypot(gy) as f32; + for y in y0 as usize..=y1 as usize { + for x in x0 as usize..=x1 as usize { + let (px, py) = (x as f64 + 0.5, y as f64 + 0.5); + let w0 = ((b[0] - px) * (cc[1] - py) - (b[1] - py) * (cc[0] - px)) / area; + let w1 = ((cc[0] - px) * (a[1] - py) - (cc[1] - py) * (a[0] - px)) / area; + let w2 = 1.0 - w0 - w1; + if w0 < -1e-9 || w1 < -1e-9 || w2 < -1e-9 { continue; } - let mut col = shade(n, view_dir, base); - let ndv = n.dot(view_dir).abs(); - if curved && ndv < 0.14 { - let a = 1.0 - ndv / 0.14; - for (k, e) in col.iter_mut().zip([0.07, 0.08, 0.10]) { - *k = *k * (1.0 - a) + e * a; + let (q0, q1, q2) = (w0 * iw[0], w1 * iw[1], w2 * iw[2]); + let qs = q0 + q1 + q2; + let (p0, p1, p2) = if qs > 1e-12 { (q0 / qs, q1 / qs, q2 / qs) } else { (w0, w1, w2) }; + if let Some((cn, cd)) = scene.clip + && cn.dot(wp[0] * p0 + wp[1] * p1 + wp[2] * p2) > cd + { + continue; + } + let z = (w0 * a[2] + w1 * b[2] + w2 * cc[2]) as f32; + let i = y * sw + x; + if c.depth.get(i).is_some_and(|d| z < *d) { + // A see-through body is blended over what is already drawn and + // leaves the depth buffer alone, so bodies inside it stay visible + // and the lines' depth test still answers for the solids. + if !pass.glass() { + if let Some(d) = c.depth.get_mut(i) { + *d = z; + } + if let Some(s) = slope.get_mut(i) { + *s = tri_slope; + } } + let n = (ns[0] * p0 + ns[1] * p1 + ns[2] * p2).normalized().unwrap_or(Vec3::Z); + // A see-through body has no cut face: the interior already shows. + let cut = !pass.glass() && scene.clip.is_some() && inside; + if let Some(d) = cap_depth.get_mut(i).filter(|_| !pass.glass()) { + *d = match cap_z { + Some([a, b, k]) if cut => ((a * px + b * py + k) as f32).min(z), + _ => f32::INFINITY, + }; + } + if cut { + // The cut: the body's colour tinted toward the cap colour, hatched + // at 45 degrees (as the viewport draws it). + let tinted: [f64; 3] = std::array::from_fn(|k| base[k] + (cap_tint[k] - base[k]) * 0.35); + let k = if ((x + y) / SS) % 9 < 2 { 0.6 } else { 1.0 }; + c.put(x, y, tinted.map(|v| v * k), 1.0); + continue; + } + let mut col = shade(n, view_dir, base); + let ndv = n.dot(view_dir).abs(); + if curved && ndv < 0.14 { + let a = 1.0 - ndv / 0.14; + for (k, e) in col.iter_mut().zip([0.07, 0.08, 0.10]) { + *k = *k * (1.0 - a) + e * a; + } + } + c.put(x, y, col, alpha); } - c.put(x, y, col, 1.0); } } } @@ -336,7 +383,7 @@ mod tests { edge_faces: vec![], }; let scene = Scene { - meshes: vec![SceneMesh { mesh: Arc::new(mesh), color: Rgb(200, 30, 30), face_colors: Vec::new() }], + meshes: vec![SceneMesh::solid(Arc::new(mesh), Rgb(200, 30, 30))], lines: vec![], background: None, radius: 20.0, @@ -354,6 +401,71 @@ mod tests { assert_eq!(render(&scene, &cam, 0, usize::MAX).w, 1); } + /// A square panel facing the front camera (which looks along +Y), 20 × 20 about the origin + /// at `y`: nearer the eye the smaller `y` is. + fn panel(y: f64) -> Mesh { + let c = [(-10.0, -10.0), (10.0, -10.0), (10.0, 10.0), (-10.0, 10.0)].map(|(x, z)| Vec3::new(x, y, z)); + Mesh { + positions: c.to_vec(), + normals: vec![Vec3::new(0.0, -1.0, 0.0); 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0, 0], + ..Default::default() + } + } + + /// A front panel over a back one, with a line between them, seen from the front. + fn two_panels(front_opacity: f32) -> (Scene, Camera) { + let glass = SceneMesh { mesh: Arc::new(panel(-5.0)), color: Rgb(255, 0, 0), face_colors: Vec::new(), opacity: front_opacity }; + let scene = Scene { + meshes: vec![SceneMesh::solid(Arc::new(panel(5.0)), Rgb(0, 255, 0)), glass], + lines: vec![SceneLine { + points: vec![Vec3::new(-8.0, 2.0, 0.0), Vec3::new(8.0, 2.0, 0.0)], + color: Rgb(0, 0, 255), + width: 1.4, + on_top: false, + }], + radius: 40.0, + ..Default::default() + }; + let mut cam = Camera { distance: 60.0, ..Default::default() }; + cam.set_view(StandardView::Front); + (scene, cam) + } + + /// A body the design draws see-through lets what is behind it show: the colour of the body + /// behind it comes through, and so does a line between the two, which a solid body in front + /// hides. This is what makes a picture of a cut's tool inside a translucent target readable. + #[test] + fn a_see_through_body_shows_what_is_inside_it() { + let middle = |opacity: f32| { + let (scene, cam) = two_panels(opacity); + let c = render(&scene, &cam, 64, 64); + // Inside both panels and clear of the line across the middle, so this pixel is + // the two panels alone. + let i = (24 * 64 + 24) * 4; + [c.rgba[i], c.rgba[i + 1], c.rgba[i + 2]] + }; + let behind = |opacity: f32| { + let (scene, cam) = two_panels(opacity); + render(&scene, &cam, 64, 64).rgba.chunks(4).filter(|p| p[2] > 150 && p[0] < 120 && p[1] < 120).count() + }; + + let solid = middle(1.0); + assert!(solid[0] > 150 && solid[1] < 60, "a solid panel hides the one behind it: {solid:?}"); + assert_eq!(behind(1.0), 0, "a solid panel hides the line behind it"); + + let glass = middle(0.35); + assert!(glass[1] > solid[1] + 60, "the panel behind shows through: {glass:?} vs {solid:?}"); + assert!(glass[0] < solid[0], "the see-through panel itself is dimmer: {glass:?} vs {solid:?}"); + assert!(behind(0.35) > 20, "the line between the panels shows through the see-through one"); + + // Opacity 0 still leaves a trace of the body rather than an invisible one, and the + // picture changes all the way down. + let faint = middle(0.0); + assert!(faint[0] > 0 && faint[0] < glass[0], "opacity 0 is a trace, not nothing and not glass: {faint:?} vs {glass:?}"); + } + /// A sheet facing the front camera, turned back by `tilt` about X: the plane y = z·tan(tilt) /// over x in ±15, z in ±`h`. fn sheet(tilt: f64, h: f64) -> Mesh { @@ -371,12 +483,7 @@ mod tests { /// A close front view: 40 mm high on 64 px (128 canvas px, 0.3125 mm each), of a design of /// radius `radius`. fn close_view(mesh: Mesh, lines: Vec, radius: f64, fov: f64) -> (Scene, Camera) { - let scene = Scene { - meshes: vec![SceneMesh { mesh: Arc::new(mesh), color: Rgb(160, 165, 175), face_colors: Vec::new() }], - lines, - radius, - ..Default::default() - }; + let scene = Scene { meshes: vec![SceneMesh::solid(Arc::new(mesh), Rgb(160, 165, 175))], lines, radius, ..Default::default() }; let mut cam = Camera { distance: if fov > 0.0 { 20.0 / (fov * 0.5).tan() } else { 50.0 }, fov, ..Default::default() }; cam.set_view(StandardView::Front); (scene, cam) diff --git a/crates/render/src/scene.rs b/crates/render/src/scene.rs index a8700ad31..f7934b894 100644 --- a/crates/render/src/scene.rs +++ b/crates/render/src/scene.rs @@ -23,8 +23,38 @@ pub struct SceneMesh { pub color: Rgb, /// Faces in colours of their own: (B-rep face index, colour). pub face_colors: Vec<(u32, Rgb)>, + /// How opaque the body is (an appearance's opacity): 1 is solid, below [`SEE_THROUGH`] it is + /// drawn see-through, so what lies inside it shows, as the viewport draws glass. A body + /// without an appearance of its own is solid. + pub opacity: f32, } +impl SceneMesh { + /// A solid body in `color`, with no face of its own look. + pub fn solid(mesh: Arc, color: Rgb) -> SceneMesh { + SceneMesh { mesh, color, face_colors: Vec::new(), opacity: 1.0 } + } + + /// Is the body drawn see-through? (Its opacity is below [`SEE_THROUGH`].) + pub fn glass(&self) -> bool { + self.opacity < SEE_THROUGH + } + + /// The alpha the body is blended with: its opacity, never so low that it vanishes + /// altogether, and 1 when it is solid. + pub fn alpha(&self) -> f64 { + if self.glass() { f64::from(self.opacity).clamp(MIN_ALPHA, 1.0) } else { 1.0 } + } +} + +/// At or above this opacity a body is drawn solid: an appearance a hair under 1 is not worth a +/// see-through pass, and the viewport draws the same bodies as glass. +pub const SEE_THROUGH: f32 = 0.999; + +/// The lowest alpha a see-through body is drawn with, so opacity 0 still leaves a trace of the +/// body rather than an invisible one (as the viewport clamps it). +pub const MIN_ALPHA: f64 = 0.05; + pub struct SceneLine { pub points: Vec, pub color: Rgb, diff --git a/crates/ui-egui/src/file_load.rs b/crates/ui-egui/src/file_load.rs index 3e34dfb69..c130370ab 100644 --- a/crates/ui-egui/src/file_load.rs +++ b/crates/ui-egui/src/file_load.rs @@ -587,7 +587,7 @@ fn partial_picture(world: &solidcraft_engine::doc::ModelState, stop: &dyn Fn() - return None; } bounds = bounds.union(&mesh.bounds()); - scene.meshes.push(SceneMesh { mesh, color: Rgb(176, 186, 199), face_colors: Vec::new() }); + scene.meshes.push(SceneMesh::solid(mesh, Rgb(176, 186, 199))); } if bounds.is_empty() { return None; @@ -633,7 +633,7 @@ fn saved_picture(preview: solidcraft_engine::io::DesignPreview) -> Option Date: Mon, 19 Oct 2026 22:11:35 +0200 Subject: [PATCH 092/225] Hole: size the tool by the body it drills, not the largest body (#2904) (#2975) * claim: #2904 Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01X2qZQXd3qSwu9mzaYcB9yW * Hole: size the tool by the bodies its axis meets (#2904) hole_tools_and_prisms sized the tool (reach above the face, depth of a through hole) by the largest body of the whole model, so a large body far away changed a countersink's outline and the volume it removed. Use the largest body the axis meets, falling back to the model as before. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01X2qZQXd3qSwu9mzaYcB9yW --------- Co-authored-by: Claude Sonnet 5.5 --- crates/doc/src/eval.rs | 34 ++++++++++++++++++++- crates/engine/src/cmd/single_hole_tests.rs | 35 ++++++++++++++++++++++ 2 files changed, 68 insertions(+), 1 deletion(-) diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 615dbb2e8..063ce5489 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -2892,6 +2892,38 @@ fn hole_tools( Ok(hole_tools_and_prisms(vals, st, position, dir, diameter, depth, hole)?.into_iter().map(|(tool, _)| tool).collect()) } +/// The scale a hole's tools are sized by: the largest body the hole's axis meets (#2904), so a +/// large body elsewhere in the model changes neither the tool's reach above the face (and so +/// the countersink's outline) nor its depth. A hole whose axis meets no body is sized by the +/// largest body of the model, as before. +fn hole_axis_size(st: &ModelState, position: &Vec3, dir: Vec3) -> f64 { + let along = |b: &ModelBody| { + // The axis (an unbounded line) against the body's box, grown by the display tolerance. + let bb = b.mesh().bounds(); + if bb.is_empty() { + return false; + } + let pad = 2.0 * b.display_tol(); + let (mut lo, mut hi) = (f64::NEG_INFINITY, f64::INFINITY); + for (o, d, min, max) in + [(position.x, dir.x, bb.min.x, bb.max.x), (position.y, dir.y, bb.min.y, bb.max.y), (position.z, dir.z, bb.min.z, bb.max.z)] + { + if d.abs() < 1e-12 { + if o < min - pad || o > max + pad { + return false; + } + } else { + let (a, c) = ((min - pad - o) / d, (max + pad - o) / d); + lo = lo.max(a.min(c)); + hi = hi.min(a.max(c)); + } + } + lo <= hi + }; + let met = st.bodies.iter().filter(|b| along(b)).map(|b| b.body.size()).fold(0.0, f64::max); + if met > 0.0 { met } else { st.bodies.iter().map(|b| b.body.size()).fold(1.0, f64::max) } +} + /// [`hole_tools`], each with its exact geometry when it is a straight cylinder along the axis /// (a plain hole, a counterbore, a drill point left in the air past a through hole), so sheet /// metal can keep it as a flat cut-out or pocket. Each tool's faces are named by the part of the @@ -2910,7 +2942,7 @@ fn hole_tools_and_prisms( if !(r > 1e-6) { return Err(DocError::Invalid("hole diameter must be positive".into())); } - let size = st.bodies.iter().map(|b| b.body.size()).fold(1.0, f64::max); + let size = hole_axis_size(st, position, dir); let top = (size * 0.01).max(0.1); let bottom = match depth { Some(d) => -val(vals, d, Kind::Length)?, diff --git a/crates/engine/src/cmd/single_hole_tests.rs b/crates/engine/src/cmd/single_hole_tests.rs index 52644219c..9249abbee 100644 --- a/crates/engine/src/cmd/single_hole_tests.rs +++ b/crates/engine/src/cmd/single_hole_tests.rs @@ -98,3 +98,38 @@ fn a_single_hole_takes_one_point_and_no_flip() { assert!(s.execute("solid.hole", &p).is_err(), "{p}"); } } + +/// A lid (rounded corners) with a countersunk hole 1.5 mm from its edge, and a second body `far` away from it. +/// Returns the lid's volume (the total less the far body's) after the hole and the bodies the hole changed. +fn lid_with_far_body(far_size: [f64; 3]) -> (f64, Value) { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY", "offset": "7.1 mm"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [-40.2, -9.85], "p1": [40.2, 13.05]})); + run(&mut s, "sketch.fillet", json!({"points": ["l1.start", "l2.start", "l3.start", "l4.start"], "radius": "2 mm"})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"distance": "2 mm", "operation": "new", "body_name": "lid"})); + run( + &mut s, + "solid.box", + json!({"length": far_size[0], "width": far_size[1], "height": far_size[2], "corner": [158, -60, -5.9], "body_name": "far"}), + ); + let r = run( + &mut s, + "solid.hole", + json!({"position": [-38.7, -8.35, 9.1], "diameter": "2.4 mm", "type": "countersink", "cs_diameter": "4.2 mm", "cs_angle": "90 deg"}), + ); + let lid = volume(&mut s) - far_size.iter().product::(); + (lid, r["changed_bodies"].clone()) +} + +/// #2904: the tool of a hole depends on the part it drills, not on how big some other body of the +/// model is: a large body far away leaves the countersink, the volume removed and the bodies +/// changed as they are with a 1 mm cube there. +#[test] +fn a_far_body_does_not_change_a_countersunk_hole() { + let (small, small_changed) = lid_with_far_body([1.0, 1.0, 1.0]); + let (large, large_changed) = lid_with_far_body([178.0, 160.0, 12.5]); + assert!((small - large).abs() < 1e-3, "lid volume {small} with a 1 mm far body, {large} with a large one"); + assert_eq!(small_changed, large_changed, "bodies changed"); + assert_eq!(large_changed, json!(["lid"]), "only the lid is drilled"); +} From 31b41978fca5787b8bbb2665cbf5856faa675b93 Mon Sep 17 00:00:00 2001 From: rlartot <94693724+rlartot@users.noreply.github.com> Date: Mon, 19 Oct 2026 22:11:38 +0200 Subject: [PATCH 093/225] Construction geometry on model vertices follows them when a parameter moves them (#568) (#2409) Thanks @rlartot. --- apps/solidcraft-cli/tests/action_matrix.rs | 1 - crates/doc/src/clipboard.rs | 5 ++ crates/doc/src/construct.rs | 69 +++++++++++++++++-- .../src/format/pending/vertex-edge-names.rs | 4 ++ crates/engine/src/cmd/construct.rs | 2 +- crates/engine/src/construct_tests.rs | 24 +++++++ docs/action-matrix.md | 2 +- tests/action_matrix/baseline.json | 10 +-- 8 files changed, 102 insertions(+), 15 deletions(-) create mode 100644 crates/doc/src/format/pending/vertex-edge-names.rs diff --git a/apps/solidcraft-cli/tests/action_matrix.rs b/apps/solidcraft-cli/tests/action_matrix.rs index 9e634be1b..6a21e2dcd 100644 --- a/apps/solidcraft-cli/tests/action_matrix.rs +++ b/apps/solidcraft-cli/tests/action_matrix.rs @@ -1665,7 +1665,6 @@ fn a_tangent_plane_on_a_drill_tip() { } #[test] -#[ignore = "fails until #568 is fixed"] fn a_plane_on_a_patterned_counterbore_after_a_thickness_change() { let mut c = vec![json!({"command": "parameters.change", "params": {"name": "thick", "expression": "10 mm"}})]; c.extend(rectangle(json!("XY"), [0., 0.], [80., 30.])); diff --git a/crates/doc/src/clipboard.rs b/crates/doc/src/clipboard.rs index 5581892cb..ee2d2b616 100644 --- a/crates/doc/src/clipboard.rs +++ b/crates/doc/src/clipboard.rs @@ -95,6 +95,11 @@ fn remap_geo( } } GeoRef::Face { name: Some(n), .. } | GeoRef::Edge { name: Some(n), .. } => *n = remap_topology(n, ids, bodies), + GeoRef::Vertex { edges: Some(names), .. } => { + for n in names { + *n = remap_topology(n, ids, bodies); + } + } GeoRef::ConstructPoint { name } | GeoRef::Axis { name } => mapped_name(name, names), GeoRef::Plane { plane } => remap_plane(plane, ids, names, bodies, depth + 1)?, _ => {} diff --git a/crates/doc/src/construct.rs b/crates/doc/src/construct.rs index c6abe8867..6c441bf3e 100644 --- a/crates/doc/src/construct.rs +++ b/crates/doc/src/construct.rs @@ -2,8 +2,9 @@ //! points and sketch entities, resolved on each evaluation, and the axes, points and planes //! built from them (the CONSTRUCT panel). //! -//! Face and edge references carry the persistent name of what was picked (see `naming`), so -//! they follow the model when earlier features change; the picked point is the fallback. +//! Face and edge references carry the persistent name of what was picked (see `naming`), and a +//! vertex the names of the edges that meet there, so they follow the model when earlier features +//! change; the picked point is the fallback. use std::collections::BTreeMap; @@ -23,8 +24,13 @@ pub enum GeoRef { Point { p: Vec3 }, /// The design origin. Origin, - /// A body vertex (the one nearest `at`). - Vertex { at: Vec3 }, + /// A body vertex: where the edges named `edges` meet (the end they share), else the one + /// nearest `at`. + Vertex { + at: Vec3, + #[serde(default, skip_serializing_if = "Option::is_none")] + edges: Option>, + }, /// A body edge: the one named `name`, else the one nearest `at`. Edge { at: Vec3, @@ -170,6 +176,33 @@ fn edge_points(st: &ModelState, at: Vec3, name: &Option) -> Result Option { + if names.len() < 2 || names.len() > MAX_VERTEX_EDGES { + return None; + } + let ends: Vec<[Vec3; 2]> = names + .iter() + .map(|n| { + // The edge with that name itself, never the one nearest the old pick. + let on = bodies(st).find_map(|b| crate::naming::find_edge(b, n, at).ok())?.0; + let pts = edge_points(st, on, &None).ok()?; + Some([*pts.first()?, *pts.last()?]) + }) + .collect::>()?; + let (first, rest) = ends.split_first()?; + let tol = |p: Vec3| 1e-6 * (1.0 + p.len()); + first + .iter() + .copied() + .filter(|p| p.is_finite() && rest.iter().all(|e| e.iter().any(|q| q.dist(*p) <= tol(*p)))) + .min_by(|p, q| p.dist(at).total_cmp(&q.dist(at))) +} + /// A polyline that is straight: its line. fn as_line(pts: &[Vec3]) -> Option<(Vec3, Vec3)> { let (a, b) = (*pts.first()?, *pts.last()?); @@ -228,7 +261,10 @@ pub(crate) fn point(ctx: &Ctx, g: &GeoRef) -> Result { match g { GeoRef::Point { p } => Ok(*p), GeoRef::Origin => Ok(Vec3::ZERO), - GeoRef::Vertex { at } => { + GeoRef::Vertex { at, edges } => { + if let Some(v) = edges.as_deref().and_then(|names| named_vertex(ctx.st, *at, names)) { + return Ok(v); + } let mut best: Option<(f64, Vec3)> = None; for b in bodies(ctx.st) { let tol = (b.body.size() * 1e-3).max(1e-3); @@ -553,13 +589,14 @@ impl GeoRef { pub fn map_points(&mut self, pt: &mut dyn FnMut(&mut Vec3), plane: &mut dyn FnMut(&mut PlaneRef)) { match self { GeoRef::Point { p } => pt(p), - GeoRef::Vertex { at } | GeoRef::Edge { at, .. } | GeoRef::Face { at, .. } => pt(at), + GeoRef::Vertex { at, .. } | GeoRef::Edge { at, .. } | GeoRef::Face { at, .. } => pt(at), GeoRef::Plane { plane: p } => plane(p), _ => {} } } - /// Picked faces and edges get their persistent names (and only those still missing one). + /// Picked faces and edges get their persistent names, and picked vertices the names of the + /// edges that meet there (only those still missing them). pub fn name_picks(&mut self, st: &ModelState) { match self { GeoRef::Face { at, name: name @ None } => { @@ -574,6 +611,24 @@ impl GeoRef { } } } + GeoRef::Vertex { at, edges: edges @ None } => { + for b in bodies(st) { + let tol = (b.body.size() * 1e-3).max(1e-3); + let m = b.mesh(); + let ends_here = |e: &Vec| [e.first(), e.last()].into_iter().flatten().any(|q| q.dist(*at) <= tol); + let mut meet: Vec = + m.edges.iter().zip(crate::naming::edge_names(b)).filter(|(e, n)| !n.is_empty() && ends_here(e)).map(|(_, n)| n).collect(); + if meet.is_empty() { + continue; + } + meet.sort(); + meet.dedup(); + if (2..=MAX_VERTEX_EDGES).contains(&meet.len()) { + *edges = Some(meet); + } + break; + } + } GeoRef::Plane { plane } => plane.name_picks(st), _ => {} } diff --git a/crates/doc/src/format/pending/vertex-edge-names.rs b/crates/doc/src/format/pending/vertex-edge-names.rs new file mode 100644 index 000000000..536f4944b --- /dev/null +++ b/crates/doc/src/format/pending/vertex-edge-names.rs @@ -0,0 +1,4 @@ +//! A construction reference to a body vertex saves the names of the edges that meet there +//! (`edges` beside `at`), so a plane, axis or point on a vertex follows it when an earlier change +//! moves it. Older designs need no transformation: a vertex reference without `edges` is the +//! vertex nearest its point, as before. 0.15.x asks for an update instead of reading `edges`. diff --git a/crates/engine/src/cmd/construct.rs b/crates/engine/src/cmd/construct.rs index 4c42c43f1..12ed05e37 100644 --- a/crates/engine/src/cmd/construct.rs +++ b/crates/engine/src/cmd/construct.rs @@ -99,7 +99,7 @@ fn geo(s: &Session, v: Option<&Value>, cmd: &str, what: &str) -> Result } else if let Some(at) = p3("edge") { GeoRef::Edge { at, name: None } } else if let Some(at) = p3("vertex") { - GeoRef::Vertex { at } + GeoRef::Vertex { at, edges: None } } else if let Some(sk) = v.get("sketch") { let sketch = sketch_id(s, Some(sk), cmd, what)?; match (str_(v, "point"), str_(v, "curve")) { diff --git a/crates/engine/src/construct_tests.rs b/crates/engine/src/construct_tests.rs index 373fe2b81..157324a05 100644 --- a/crates/engine/src/construct_tests.rs +++ b/crates/engine/src/construct_tests.rs @@ -282,6 +282,30 @@ fn construction_follows_the_model() { assert!(on_line(o, d, Vec3::new(40.0, 30.0, 50.0)) && on_line(o, d, Vec3::ZERO)); } +/// #568: a plane through three vertices follows them when a parameter moves them. Two of them +/// sit on the box's end at x = 40; the box grows to 100 mm, so the vertices nearest the old +/// picks are the ones at x = 0, on a line with the first: found by the names of the edges that +/// meet there, they are the moved ones. +#[test] +fn a_plane_through_three_vertices_follows_them() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "len", "expression": "40 mm"})); + run(&mut s, "solid.box", json!({"length": "len", "width": 30, "height": 20, "body_name": "Box"})); + run( + &mut s, + "construct.plane.three_points", + json!({"a": {"vertex": [0, 0, 20]}, "b": {"vertex": [40, 0, 20]}, "c": {"vertex": [40, 30, 0]}, "name": "T"}), + ); + run(&mut s, "parameters.change", json!({"name": "len", "expression": "100 mm"})); + let id = s.doc.features.iter().find(|f| f.name == "T").map(|f| f.id).unwrap_or_else(|| panic!("feature T")); + let error = s.model.result(id).and_then(|r| r.error.clone()); + assert_eq!(error, None); + let t = plane(&s, "T"); + for p in [Vec3::new(0.0, 0.0, 20.0), Vec3::new(100.0, 0.0, 20.0), Vec3::new(100.0, 30.0, 0.0)] { + assert!(on_plane(&t, p), "{p:?} is off {t:?}"); + } +} + /// In a component moved 50 mm along X, picks given in the world land on its geometry, and the /// axis and point move with the occurrence. #[test] diff --git a/docs/action-matrix.md b/docs/action-matrix.md index b15c38552..543fdec22 100644 --- a/docs/action-matrix.md +++ b/docs/action-matrix.md @@ -283,10 +283,10 @@ make a legacy face sketch there). | 56 | #563 | Draft and tapered Extrude drop the faces' sources | `face.extrude` 14, `face.offset_plane` 14, `face.press_pull` 14, `face.sketch` 14 | 3 | oracle/05-taper-extrude `Frustum/F2:start` | | 48 | #564 | The rim a Shell leaves has no source | `face.extrude` 12, `face.offset_plane` 12, `face.press_pull` 12, `face.sketch` 12 | 8 | demo/pi-case `Body1/F2:top` | | 18 | #567 | Axis or tangent plane on a drill tip: no face at NaN | `curved.axis` 9, `curved.tangent_plane` 9 | 3 | oracle/18-hole-features `Plate/F5:face:15` | -| 9 | #568 | Construction geometry on model edges, faces and vertices is lost when a parameter moves it | `vertex.plane_three_points+edit` 5, `edge.normal_plane+edit` 2, `face.midplane+edit` 1, `face.shell+edit` 1 | 4 | demo/enclosure_steps `Enclosure/v[F2:top & F4:inner:F2:side:l4 & F4:inner:F3:blend:F2:side:l` | | 9 | | Axis through a face the kernel sees as a cylinder that the command doesn't (sensor enclosure slot ends; not filed yet) | `curved.axis` 9 | 1 | examples/sensor_enclosure `Lid/F15:blend:F14:side:l2\|F14:side:l3` | | 7 | | Other failures in the edit round: the hole cut and blend sizes above, and an extrude from the M0 box's top face whose profile isn't found again (not filed yet) | `face.hole+edit` 3, `face.extrude+edit` 1, `face.press_pull+edit` 1, `edge.chamfer+edit` 1 | 4 | corpus/m0-box-fillet-hole `Body1/F2:top` | | 2 | | A helix edge projected along its axis is a point (expected) | `edge.project` 2 | 1 | oracle/50-sweep-tight-bend `Bend/F3:side:c1#1\|F3:side:c1#2~2` | +| 1 | #566 | Shell after the edit round: a corner whose faces don't meet the same way after the move | `face.shell+edit` 1 | 1 | demo/pi-case `Body1/F4:inner:F2:start#[…]#[F6:side:c2@F7.2]` | Where the face history stands (`crates/kernel/src/history.rs`, [face attachments](face-attachments.md)): a flat face takes an attached sketch when the body carries an exact source certificate for it diff --git a/tests/action_matrix/baseline.json b/tests/action_matrix/baseline.json index 15b924f14..51d3af3c9 100644 --- a/tests/action_matrix/baseline.json +++ b/tests/action_matrix/baseline.json @@ -1704,7 +1704,7 @@ "Enclosure/v[F2:top & F4:inner:F2:side:l3 & F4:inner:F3:blend:F2:side:l2|F2:side:l3]": "vertex.plane_three_points vertex.point", "Enclosure/v[F2:top & F4:inner:F2:side:l3 & F4:inner:F3:blend:F2:side:l3|F2:side:l4]": "vertex.plane_three_points vertex.point", "Enclosure/v[F2:top & F4:inner:F2:side:l4 & F4:inner:F3:blend:F2:side:l1|F2:side:l4]": "vertex.plane_three_points vertex.point", - "Enclosure/v[F2:top & F4:inner:F2:side:l4 & F4:inner:F3:blend:F2:side:l3|F2:side:l4]": "vertex.plane_three_points !vertex.plane_three_points+edit vertex.point", + "Enclosure/v[F2:top & F4:inner:F2:side:l4 & F4:inner:F3:blend:F2:side:l3|F2:side:l4]": "vertex.plane_three_points vertex.plane_three_points+edit vertex.point", "Enclosure/v[F4:inner:F2:side:l1 & F4:inner:F2:start & F4:inner:F3:blend:F2:side:l1|F2:side:l2]": "vertex.plane_three_points vertex.point", "Enclosure/v[F4:inner:F2:side:l1 & F4:inner:F2:start & F4:inner:F3:blend:F2:side:l1|F2:side:l4]": "vertex.plane_three_points vertex.point", "Enclosure/v[F4:inner:F2:side:l2 & F4:inner:F2:start & F4:inner:F3:blend:F2:side:l1|F2:side:l2]": "vertex.plane_three_points vertex.point", @@ -2082,7 +2082,7 @@ "Body1/v[F11:side:l5 & F11:side:l8 & F2:side:l2]": "vertex.plane_three_points vertex.point", "Body1/v[F11:side:l5 & F11:side:l8 & F4:inner:F2:side:l2]": "vertex.plane_three_points vertex.point", "Body1/v[F11:side:l6 & F11:side:l7 & F2:side:l2]": "vertex.plane_three_points vertex.point", - "Body1/v[F11:side:l6 & F11:side:l7 & F4:inner:F2:side:l2]": "vertex.plane_three_points !vertex.plane_three_points+edit vertex.point", + "Body1/v[F11:side:l6 & F11:side:l7 & F4:inner:F2:side:l2]": "vertex.plane_three_points vertex.plane_three_points+edit vertex.point", "Body1/v[F11:side:l7 & F11:side:l8 & F2:side:l2]": "vertex.plane_three_points vertex.point", "Body1/v[F11:side:l7 & F11:side:l8 & F4:inner:F2:side:l2]": "vertex.plane_three_points vertex.point", "Body1/v[F13:side:l5 & F13:side:l6 & F2:start]": "vertex.plane_three_points vertex.point", @@ -2158,7 +2158,7 @@ "Body1/v[F2:top & F4:inner:F2:side:l2 & F4:inner:F3:blend:F2:side:l1|F2:side:l2]": "vertex.plane_three_points vertex.point", "Body1/v[F2:top & F4:inner:F2:side:l2 & F4:inner:F3:blend:F2:side:l2|F2:side:l3]": "vertex.plane_three_points vertex.point", "Body1/v[F2:top & F4:inner:F2:side:l3 & F4:inner:F3:blend:F2:side:l2|F2:side:l3]": "vertex.plane_three_points vertex.point", - "Body1/v[F2:top & F4:inner:F2:side:l3 & F4:inner:F3:blend:F2:side:l3|F2:side:l4]": "vertex.plane_three_points !vertex.plane_three_points+edit vertex.point", + "Body1/v[F2:top & F4:inner:F2:side:l3 & F4:inner:F3:blend:F2:side:l3|F2:side:l4]": "vertex.plane_three_points vertex.plane_three_points+edit vertex.point", "Body1/v[F2:top & F4:inner:F2:side:l4 & F4:inner:F3:blend:F2:side:l1|F2:side:l4]": "vertex.plane_three_points vertex.point vertex.point+edit", "Body1/v[F2:top & F4:inner:F2:side:l4 & F4:inner:F3:blend:F2:side:l3|F2:side:l4]": "vertex.plane_three_points vertex.point", "Body1/v[F4:inner:F2:side:l1 & F4:inner:F2:start#[F4:inner:F2:side:l1,F4:inner:F2:side:l2,F4:inner:F2:side:l3,F4:inner:F2:side:l4,F4:inner:F3:blend:F2:side:l1|F2:side:l2,F4:inner:F3:blend:F2:side:l1|F2:side:l4,F4:inner:F3:blend:F2:side:l2|F2:side:l3,F4:inner:F3:blend:F2:side:l3|F2:side:l4,F6:side:c1]#[F4:inner:F2:side:l1,F4:inner:F2:side:l2,F4:inner:F2:side:l3,F4:inner:F2:side:l4,F4:inner:F3:blend:F2:side:l1|F2:side:l2,F4:inner:F3:blend:F2:side:l1|F2:side:l4,F4:inner:F3:blend:F2:side:l2|F2:side:l3,F4:inner:F3:blend:F2:side:l3|F2:side:l4,F6:side:c1,F6:side:c1@F7.1,F6:side:c1@F7.2,F6:side:c1@F7.3] & F4:inner:F3:blend:F2:side:l1|F2:side:l2]": "vertex.plane_three_points vertex.point", @@ -3591,7 +3591,7 @@ "Lid/F14:side:l4|F15:blend:F14:side:l1|F14:side:l4": "edge.axis edge.axis+edit edge.normal_plane edge.project", "Lid/F14:side:l4|F15:blend:F14:side:l3|F14:side:l4": "edge.axis edge.normal_plane edge.project", "Lid/F14:side:l4|F2:top": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", - "Lid/F14:start": "face.angle_plane face.angle_plane+edit !face.draft_neutral !face.extrude !face.hole face.midplane face.offset_plane !face.press_pull face.shell !face.shell+edit face.sketch face.sketch+edit", + "Lid/F14:start": "face.angle_plane face.angle_plane+edit !face.draft_neutral !face.extrude !face.hole face.midplane face.offset_plane !face.press_pull face.shell face.shell+edit face.sketch face.sketch+edit", "Lid/F14:start|F18:side:a17": "edge.chamfer edge.fillet edge.normal_plane edge.project", "Lid/F14:start|F18:side:a18": "edge.chamfer edge.chamfer+edit edge.fillet edge.normal_plane edge.project", "Lid/F14:start|F18:side:a19": "edge.chamfer edge.fillet edge.normal_plane edge.project edge.project+edit", @@ -3758,7 +3758,7 @@ "Lid/v[F18:side:a18 & F18:side:l19 & F18:top]": "vertex.plane_three_points vertex.point", "Lid/v[F18:side:a19 & F18:side:l19 & F18:top]": "vertex.plane_three_points vertex.point", "Lid/v[F18:side:a19 & F18:side:l20 & F18:top]": "vertex.plane_three_points vertex.point", - "Lid/v[F18:side:a20 & F18:side:l17 & F18:top]": "vertex.plane_three_points !vertex.plane_three_points+edit vertex.point", + "Lid/v[F18:side:a20 & F18:side:l17 & F18:top]": "vertex.plane_three_points vertex.plane_three_points+edit vertex.point", "Lid/v[F18:side:a20 & F18:side:l20 & F18:top]": "vertex.plane_three_points vertex.point", "design": "load" }, From 7ce9c29f957bbf72b79bc1b0fbbfe3a9abcc4921 Mon Sep 17 00:00:00 2001 From: rlartot <94693724+rlartot@users.noreply.github.com> Date: Mon, 19 Oct 2026 22:11:44 +0200 Subject: [PATCH 094/225] French catalog: catch up on 46 new messages (#3136) Adds the 46 missing French messages. --- assets/locales/fr.json | 46 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/assets/locales/fr.json b/assets/locales/fr.json index 803fba008..47905bc05 100644 --- a/assets/locales/fr.json +++ b/assets/locales/fr.json @@ -31,6 +31,7 @@ "Arc length": "Longueur d'arc", "Area": "Aire", "Attachment": "Rattachement", + "BOUNDARY SURFACE": "SURFACE FRONTIÈRE", "BROWSER": "NAVIGATEUR", "Bend Line Position": "Position de la ligne de pli", "Bend Position": "Position du pli", @@ -73,6 +74,7 @@ "Counterbore depth": "Profondeur du lamage", "Countersink angle": "Angle de la fraisure", "Create Issue — review draft": "Créer un ticket — relire le brouillon", + "Cross curves": "Courbes transversales", "Cube": "Cube", "Current orthographic view (1:1 mm)": "Vue orthographique actuelle (1:1 mm)", "Current perspective view": "Vue en perspective actuelle", @@ -566,6 +568,8 @@ "cmd.sketch_isoparametric_curve": "Courbe isoparamétrique", "cmd.sketch_line3d": "Ligne 3D", "cmd.sketch_line_midpoint": "Ligne par point milieu", + "cmd.sketch_loose_ends": "Extrémités libres", + "cmd.sketch_loose_ends_tie": "Faire coïncider les extrémités libres", "cmd.sketch_move": "Déplacer/Copier des entités d'esquisse", "cmd.sketch_move3d": "Déplacer un point 3D", "cmd.sketch_move_point": "Faire glisser un point d'esquisse", @@ -737,9 +741,11 @@ "new configuration": "nouvelle configuration", "new name": "nouveau nom", "new parameter": "nouveau paramètre", + "no hole": "sans perçage", "no interference": "aucune interférence", "no joint that moves yet": "aucune liaison mobile pour l'instant", "no picture": "aucune image", + "none": "aucun", "pattern.alignment_2": "Alignement 2", "pattern.alignment_hint": "La quantité inclut l’original. Le centrage répartit les copies de chaque côté ; si la quantité est paire, l’inversion choisit le côté qui reçoit la copie supplémentaire.", "pattern.direction_1": "Direction 1", @@ -812,6 +818,8 @@ "sketch.degrees_of_freedom": "{count} degrés de liberté", "sketch.draw_curves": "Dessiner en {linetype}", "sketch.make_selection": "Convertir la sélection en {linetype}", + "sketch.open_ends": "{count} ouvertes", + "sketch.untied_ends": "{count} sans coïncidence", "sketch_text.align_center": "Centre", "sketch_text.align_left": "Gauche", "sketch_text.align_right": "Droite", @@ -824,6 +832,7 @@ "sketch_text.path_clear": "Détacher le texte de sa courbe", "sketch_text.path_hint": "Une courbe de l'esquisse que le texte suit : cliquer ici, puis sur la courbe", "sketch_text.use_font_file": "Utiliser le fichier de police {path}", + "solid": "plein (sans paroi)", "the parts library is not available": "la bibliothèque de pièces n'est pas disponible", "thread.automatic_size": "Taille automatique", "thread.designation": "Désignation", @@ -835,6 +844,7 @@ "timeline.rename_group": "Renommer le dossier de fonctions", "timeline.reorder_many": "Réordonner les fonctions", "timeline.ungroup": "Supprimer les dossiers de fonctions", + "to the face": "jusqu'à la face", "to the next face": "jusqu'à la face suivante", "toolbar.image": "IMAGE", "toolbar.render": "RENDU", @@ -850,12 +860,15 @@ "ui.activate": "Activer", "ui.active_component": "Composant actif", "ui.agent_chat": "Chat de l'agent", + "ui.agent_chat_add": "Joindre des fichiers", + "ui.agent_chat_add_file": "Choisir un fichier…", "ui.agent_chat_allow": "Autoriser", "ui.agent_chat_allowed": "Autorisé", "ui.agent_chat_answered": "Réponse : {option}", "ui.agent_chat_approval": "Autoriser l'agent à effectuer cette action ?", "ui.agent_chat_attach_view": "Joindre la vue", "ui.agent_chat_attach_view_tip": "Envoyer une image de la vue actuelle avec le message", + "ui.agent_chat_attachable": "Images, PDF, textes et fichiers de CAO", "ui.agent_chat_auth_agent": "S'authentifier avec {name}", "ui.agent_chat_auth_env": "Définir {vars} dans votre environnement, puis redémarrer SolidCraft.", "ui.agent_chat_auth_needed": "L'agent demande une authentification. Vous vous authentifiez auprès de l'agent lui-même ; SolidCraft ne voit jamais votre mot de passe ni vos clés.", @@ -875,11 +888,32 @@ "ui.agent_chat_deny": "Refuser", "ui.agent_chat_desktop_only": "Le chat de l'agent nécessite l'application de bureau.", "ui.agent_chat_detecting": "Recherche d'agents…", + "ui.agent_chat_dock": "Ancrer dans le panneau latéral", "ui.agent_chat_dock_left": "Ancrer à gauche", "ui.agent_chat_dock_right": "Ancrer à droite", + "ui.agent_chat_drop_hint": "Déposer pour joindre à votre prochain message", "ui.agent_chat_edit": "Modifier", "ui.agent_chat_exited": "L'agent s'est arrêté.", "ui.agent_chat_failed_start": "L'agent n'a pas pu démarrer : {error}", + "ui.agent_chat_file_cad_not_read": "{name} : un fichier de CAO est importé dans la conception, pas lu", + "ui.agent_chat_file_empty_picture": "{name} : image vide", + "ui.agent_chat_file_error": "{name} : {error}", + "ui.agent_chat_file_heic": "{name} : les images HEIC ne peuvent pas être lues ici ; les exporter d'abord en JPEG ou PNG", + "ui.agent_chat_file_importing": "Importation dans la conception…", + "ui.agent_chat_file_loading": "Lecture du fichier…", + "ui.agent_chat_file_not_a_file": "{name} : n'est pas un fichier", + "ui.agent_chat_file_not_a_picture": "{name} : n'est pas une image", + "ui.agent_chat_file_not_utf8": "{name} : n'est pas un texte UTF-8", + "ui.agent_chat_file_picture_too_big": "{name} : une image ne peut pas dépasser {max} Mo", + "ui.agent_chat_file_text_too_big": "{name} : un fichier texte ne peut pas dépasser {max} Ko", + "ui.agent_chat_file_too_large": "{name} : trop volumineux", + "ui.agent_chat_file_too_large_to_send": "{name} : trop volumineux pour être envoyé, même réduit", + "ui.agent_chat_file_unreadable_picture": "{name} : image illisible ici", + "ui.agent_chat_files": "Fichiers : {files}", + "ui.agent_chat_files_left_out": "Un message ne peut contenir que {max} fichiers au plus ; non joints : {files}", + "ui.agent_chat_files_loading": "Lecture des fichiers en cours", + "ui.agent_chat_files_max": "{max} fichiers au plus par message", + "ui.agent_chat_import_failed": "{name} : l'importation a échoué : {error}", "ui.agent_chat_intro": "Discuter avec un agent de programmation que vous utilisez déjà, ou avec un point d'accès de modèle de votre choix. Il travaille sur la conception ouverte avec les outils de SolidCraft : ses modifications apparaissent au fur et à mesure et s'annulent en une seule étape par message. Ce qu'il peut faire sans demander se règle dans Préférences › IA.", "ui.agent_chat_key_in_env": "clé définie", "ui.agent_chat_left": "Gauche", @@ -892,14 +926,18 @@ "ui.agent_chat_no_cli": "solidcraft-cli est introuvable à côté de l'application : l'agent ne peut donc pas accéder à la conception.", "ui.agent_chat_no_control": "Le point d'accès du chat de l'agent n'a pas démarré : l'agent ne peut donc pas accéder à la conception.", "ui.agent_chat_no_images": "Cet agent n'accepte pas les images", + "ui.agent_chat_no_picture": "Il n'y a pas d'image dans le presse-papiers", "ui.agent_chat_none_found": "Aucun agent de programmation trouvé. En installer un parmi ceux-ci, puis appuyer sur Actualiser :", "ui.agent_chat_none_found_short": "Aucun agent trouvé", "ui.agent_chat_not_installed": "Non installé", "ui.agent_chat_not_signed_in": "non authentifié", + "ui.agent_chat_own_window": "Fenêtre séparée", + "ui.agent_chat_paste_picture": "Coller une image", "ui.agent_chat_permission": "L'agent demande à exécuter : {title}", "ui.agent_chat_pick": "Agent", "ui.agent_chat_placeholder": "Demander à l'agent de modifier la conception…", "ui.agent_chat_placeholder_busy": "Mettre un message en file d'attente pour quand l'agent aura terminé (Ctrl+Enter : envoyer maintenant)", + "ui.agent_chat_pop_out": "Ouvrir dans une fenêtre séparée, déplaçable vers un autre écran", "ui.agent_chat_privacy": "Rien n'est envoyé ailleurs qu'à l'agent que vous lancez, sous votre propre compte.", "ui.agent_chat_privacy_note": "SolidCraft n'envoie rien nulle part : l'agent que vous lancez dialogue avec son propre service, sous votre propre compte. SolidCraft ne voit ni ne stocke jamais de clé ni de mot de passe.", "ui.agent_chat_queue": "Mettre en file", @@ -909,6 +947,8 @@ "ui.agent_chat_refresh": "Actualiser", "ui.agent_chat_refused": "Interdit à l'agent : {reason}", "ui.agent_chat_remove": "Retirer de la file d'attente", + "ui.agent_chat_remove_file": "Retirer de ce message", + "ui.agent_chat_remove_imported": "Retirer de ce message ; la pièce reste dans la conception (Annuler la retire)", "ui.agent_chat_right": "Droite", "ui.agent_chat_save": "Enregistrer", "ui.agent_chat_send": "Envoyer", @@ -1327,6 +1367,7 @@ "ui.one_side": "Un côté", "ui.open": "Ouvrir", "ui.open_ellipsis": "Ouvrir...", + "ui.open_ends_tip": "Ne touche rien", "ui.open_preferences": "Ouvrir les préférences", "ui.open_recent": "Ouvrir un fichier récent", "ui.operation": "Opération", @@ -1388,6 +1429,8 @@ "ui.reset_the_settings_on_this_page": "Réinitialiser les réglages de cette page", "ui.restore": "Restaurer", "ui.restore_defaults": "Rétablir les valeurs par défaut", + "ui.reverse_horizontal_pan_direction": "Inverser le sens du panoramique horizontal", + "ui.reverse_horizontal_pan_tip": "Le défilement horizontal à deux doigts et la molette latérale font le panoramique dans l'autre sens", "ui.reverse_zoom_direction": "Inverser le sens du zoom", "ui.revolve": "Révolution", "ui.right": "Droite", @@ -1499,6 +1542,8 @@ "ui.theme": "Thème", "ui.thickness": "Épaisseur", "ui.thread": "Filetage", + "ui.tie_ends": "Coïncider", + "ui.tie_ends_tip": "Ajouter une coïncidence à toutes les extrémités qui n'en ont pas", "ui.timeline_bottom": "Chronologie en bas", "ui.timeline_left_note": "La disposition à gauche affiche la barre de retour en arrière au-dessus du navigateur des pièces et de la scène.", "ui.timeline_left_sidebar": "Barre latérale gauche", @@ -1521,6 +1566,7 @@ "ui.units_of_new_designs": "Unités des nouvelles conceptions", "ui.unlock": "Déverrouiller", "ui.unsuppress": "Réactiver", + "ui.untied_ends_tip": "Ne touche que par la position", "ui.untitled": "Sans titre", "ui.up_axis_note": "Axe orienté vers le haut dans les vues (vue d'axe, Accueil, Vue normale). Les conceptions ne sont pas modifiées.", "ui.updateToCurrentView": "Mettre à jour avec la vue actuelle", From 750e08aab70f0b5bae5939736c177416d9668947 Mon Sep 17 00:00:00 2001 From: rlartot <94693724+rlartot@users.noreply.github.com> Date: Mon, 19 Oct 2026 22:12:10 +0200 Subject: [PATCH 095/225] Sketch palette: a new empty sketch is not "Fully constrained" (#2906) (#3011) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * claim: #2906 Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01X2qZQXd3qSwu9mzaYcB9yW * Sketch palette: an empty sketch says "No geometry yet", not "Fully constrained" (#2906) A new sketch has no degree of freedom (only the fixed origin), so the palette read it as fully constrained. With no drawn curve or 3D curve it now shows "No geometry yet" and not the fully-constrained styling. Adds the message to the English, Japanese and Chinese catalogs. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01X2qZQXd3qSwu9mzaYcB9yW * i18n fr: Aucune géométrie pour l'instant (#2906), à valider avant push Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01X2qZQXd3qSwu9mzaYcB9yW --------- Co-authored-by: Claude Sonnet 5.5 --- assets/locales/en.json | 1 + assets/locales/fr.json | 1 + assets/locales/ja.json | 1 + assets/locales/zh.json | 1 + crates/ui-egui/src/sketch_palette.rs | 44 +++++++++++++++++++++++----- 5 files changed, 40 insertions(+), 8 deletions(-) diff --git a/assets/locales/en.json b/assets/locales/en.json index a948a4e06..1baf03392 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -1370,6 +1370,7 @@ "ui.newSketchGroup": "New Sketch Group", "ui.new_body": "New Body", "ui.new_design": "New Design", + "ui.no_geometry_yet": "No geometry yet", "ui.no_slicer_found": "No slicer found", "ui.normal": "Normal", "ui.normalConstruction": "Normal / Construction", diff --git a/assets/locales/fr.json b/assets/locales/fr.json index 47905bc05..6d303e34d 100644 --- a/assets/locales/fr.json +++ b/assets/locales/fr.json @@ -1355,6 +1355,7 @@ "ui.newSketchGroup": "Nouveau groupe d'esquisses", "ui.new_body": "Nouveau corps", "ui.new_design": "Nouvelle conception", + "ui.no_geometry_yet": "Aucune géométrie pour l'instant", "ui.no_slicer_found": "Aucun slicer trouvé", "ui.normal": "Normal", "ui.normalConstruction": "Normal / Construction", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index ff55a1600..3bce6c952 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -1370,6 +1370,7 @@ "ui.newSketchGroup": "新しいスケッチグループ", "ui.new_body": "新規ボディ", "ui.new_design": "新規デザイン", + "ui.no_geometry_yet": "ジオメトリはまだありません", "ui.no_slicer_found": "スライサーが見つかりません", "ui.normal": "標準", "ui.normalConstruction": "通常 / コンストラクション", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index 1a4fd6a17..0c43a6905 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -1370,6 +1370,7 @@ "ui.newSketchGroup": "新建草图组", "ui.new_body": "新建实体", "ui.new_design": "新建设计", + "ui.no_geometry_yet": "尚无几何图形", "ui.no_slicer_found": "未找到切片软件", "ui.normal": "法向", "ui.normalConstruction": "普通 / 构造", diff --git a/crates/ui-egui/src/sketch_palette.rs b/crates/ui-egui/src/sketch_palette.rs index 57fe403ea..26924ad7d 100644 --- a/crates/ui-egui/src/sketch_palette.rs +++ b/crates/ui-egui/src/sketch_palette.rs @@ -69,10 +69,19 @@ pub const TOGGLES: [(&str, &str); 10] = [ ("sketch_3d", "3D Sketch"), ]; -/// The degrees-of-freedom line: "Fully constrained" or "N degrees of freedom". -pub fn dof_text(dof: usize, ok: bool) -> String { +/// Does the sketch hold any geometry of its own: a drawn curve or a 3D curve? Projected curves +/// and the origin are held in place and do not count. +pub fn has_geometry(sketch: &solidcraft_engine::sketch::Sketch) -> bool { + !sketch.curves.is_empty() || !sketch.wires.is_empty() +} + +/// The degrees-of-freedom line: "No geometry yet" (an empty sketch only has its fixed origin), +/// "Fully constrained" or "N degrees of freedom". +pub fn dof_text(dof: usize, ok: bool, has_geometry: bool) -> String { if !ok { "Constraints conflict".into() + } else if !has_geometry { + "No geometry yet".into() } else if dof == 0 { "Fully constrained".into() } else if dof == 1 { @@ -345,8 +354,8 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { let Some(ss) = app.session.active_sketch.and_then(|s| st.sketch(s)) else { return }; ( ss.sketch.view.clone(), - dof_text(ss.report.dof, ss.report.ok()), - ss.report.ok() && ss.report.dof == 0, + dof_text(ss.report.dof, ss.report.ok(), has_geometry(&ss.sketch)), + ss.report.ok() && ss.report.dof == 0 && has_geometry(&ss.sketch), ss.ends.open.len(), ss.ends.untied.len(), ) @@ -942,9 +951,28 @@ mod tests { #[test] fn dof_readout() { - assert_eq!(dof_text(0, true), "Fully constrained"); - assert_eq!(dof_text(1, true), "1 degree of freedom"); - assert_eq!(dof_text(4, true), "4 degrees of freedom"); - assert_eq!(dof_text(4, false), "Constraints conflict"); + assert_eq!(dof_text(0, true, true), "Fully constrained"); + assert_eq!(dof_text(1, true, true), "1 degree of freedom"); + assert_eq!(dof_text(4, true, true), "4 degrees of freedom"); + assert_eq!(dof_text(4, false, true), "Constraints conflict"); + assert_eq!(dof_text(0, true, false), "No geometry yet"); + } + + /// #2906: a new sketch has no degree of freedom (only the fixed origin), which is not + /// "Fully constrained"; the palette says there is no geometry until a curve is drawn. + #[test] + fn an_empty_sketch_is_not_reported_fully_constrained() { + let mut h = crate::scenario::Harness::new(); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + h.settle(); + let line = |h: &crate::scenario::Harness| { + let st = h.app.session.world_state(); + let ss = h.app.session.active_sketch.and_then(|s| st.sketch(s)).unwrap(); + dof_text(ss.report.dof, ss.report.ok(), has_geometry(&ss.sketch)) + }; + assert_eq!(line(&h), "No geometry yet"); + h.app.run("sketch.rectangle.two_point", json!({"p0":[0,0],"p1":[10,5]})).unwrap(); + h.settle(); + assert_ne!(line(&h), "No geometry yet", "a drawn rectangle is geometry"); } } From 1999e763ab850ba878fbe601010f2b5fb8012618 Mon Sep 17 00:00:00 2001 From: Mariusz Pacek Date: Mon, 19 Oct 2026 22:12:52 +0200 Subject: [PATCH 096/225] Tapered extrude: arcs meeting at corners meet where their moved circles cross (#2810) (#2813) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A loop made only of arcs took the all-arcs shortcut in `offset_loop`, which moves each arc by its radius and keeps its start and sweep angles: exact for arcs on one circle or meeting tangentially, but where arcs of different circles meet at a corner (a circle with lobes) the moved arcs no longer met, and the sides were built through the wrong points without an error. `arc_corners` moves each such corner to where the two moved circles cross, nearest the old corner (`circles_cross`, closed form), and cuts both arcs there. Circles that no longer cross are refused ("not supported yet"), an arc the taper turns around closes the profile. Between the sections the corner is a straight ruling, as for every side in `taper_loop`: on the test profile (2.5 mm at 45°) it stays within 0.015 mm of the exact corner. Test `tapered_extrude_of_arcs_meeting_at_corners`: the volume against the integral of the union of the shrunk circles, 18905.42 mm³ against 18907.67 (was 18975.45). Co-authored-by: Mariusz Pacek Co-authored-by: Claude Opus 5.5 Co-authored-by: bherbruck --- crates/kernel/src/build.rs | 80 ++++++++++++++++++++++++++++++++++++-- crates/kernel/src/tests.rs | 37 ++++++++++++++++++ 2 files changed, 114 insertions(+), 3 deletions(-) diff --git a/crates/kernel/src/build.rs b/crates/kernel/src/build.rs index dc3ed31c0..d4ff0dcd6 100644 --- a/crates/kernel/src/build.rs +++ b/crates/kernel/src/build.rs @@ -633,25 +633,99 @@ fn offset_loop(lp: &Loop2, d: f64) -> Result>> { } let all_arcs = lp.segs.iter().all(|s| matches!(s, Seg2::Arc { .. })); if all_arcs { - return lp + let moved = lp .segs .iter() .map(|s| match *s { Seg2::Arc { center, radius, start, sweep } => { let r = radius + sweep.signum() * d; if r > 1e-6 { - Ok(Some(Seg2::Arc { center, radius: r, start, sweep })) + Ok(Seg2::Arc { center, radius: r, start, sweep }) } else { Err(KernelError::Invalid("the taper closes the profile".into())) } } _ => Err(KernelError::Failed("taper: profile loop".into())), }) - .collect(); + .collect::>>()?; + return arc_corners(lp, moved).map(|arcs| arcs.into_iter().map(Some).collect()); } offset_segments(lp, d) } +/// The moved arcs of an all-arc loop made to meet again: where two arcs of different circles meet +/// at a corner (a circle and the lobes on its sides), their moved circles no longer cross at the +/// arcs' old end angles, so the corner goes to where the moved circles cross, nearest the old +/// corner, and both arcs are cut there. Arcs meeting tangentially (or on one circle) keep their +/// angles: moved along their shared normal, they still meet. +fn arc_corners(lp: &Loop2, moved: Vec) -> Result> { + let bad = || KernelError::Failed("taper: profile loop".into()); + let closes = || KernelError::Invalid("the taper closes the profile".into()); + let n = moved.len(); + // Each arc's start and end angle once moved. + let mut ang: Vec<(f64, f64)> = moved + .iter() + .map(|s| match *s { + Seg2::Arc { start, sweep, .. } => Ok((start, start + sweep)), + _ => Err(bad()), + }) + .collect::>()?; + for i in 0..n { + let k = (i + n - 1) % n; + let (Some(prev), Some(this), Some(Seg2::Arc { center: c1, radius: r1, .. }), Some(Seg2::Arc { center: c2, radius: r2, .. })) = + (lp.segs.get(k), lp.segs.get(i), moved.get(k).copied(), moved.get(i).copied()) + else { + return Err(bad()); + }; + let (tin, tout) = (prev.end_tangent(), this.start_tangent()); + if tin.cross(tout).abs() < 1e-6 && tin.dot(tout) > 0.0 { + continue; + } + let x = circles_cross(c1, r1, c2, r2, this.start()).ok_or_else(|| { + KernelError::Failed("not supported yet: a taper this steep for arcs meeting at a corner (their moved circles part)".into()) + })?; + if let Some(a) = ang.get_mut(k) { + a.1 = (x - c1).angle(); + } + if let Some(a) = ang.get_mut(i) { + a.0 = (x - c2).angle(); + } + } + moved + .iter() + .zip(&ang) + .map(|(s, &(a0, a1))| match *s { + Seg2::Arc { center, radius, sweep, .. } => { + // The same turning sense, the whole-turn equivalent nearest the old sweep. + let tau = std::f64::consts::TAU; + let mut sw = a1 - a0; + sw += ((sweep - sw) / tau).round() * tau; + if sw * sweep <= 0.0 || sw.abs() < 1e-9 { + return Err(closes()); + } + Ok(Seg2::Arc { center, radius, start: a0, sweep: sw }) + } + _ => Err(bad()), + }) + .collect() +} + +/// Where the circles (`c1`, `r1`) and (`c2`, `r2`) cross, the crossing nearest `near`; `None` +/// when they don't (apart, one inside the other, or concentric). +fn circles_cross(c1: Vec2, r1: f64, c2: Vec2, r2: f64, near: Vec2) -> Option { + let d = c1.dist(c2); + if d < 1e-12 || d > r1 + r2 + 1e-9 || d < (r1 - r2).abs() - 1e-9 { + return None; + } + let u = (c2 - c1) * (1.0 / d); + let a = (r1 * r1 - r2 * r2 + d * d) / (2.0 * d); + let h = (r1 * r1 - a * a).max(0.0).sqrt(); + let base = c1 + u * a; + let (p, q) = (base + u.perp() * h, base - u.perp() * h); + let x = if p.dist(near) <= q.dist(near) { p } else { q }; + x.is_finite().then_some(x) +} + /// Where the line through `p` along `tin` and the one through `q` along `tout` meet once each /// has moved `d` to its right (`q` moved, where they run on together). fn mitre(p: Vec2, tin: Vec2, q: Vec2, tout: Vec2, d: f64) -> Vec2 { diff --git a/crates/kernel/src/tests.rs b/crates/kernel/src/tests.rs index 69840f9da..d29152568 100644 --- a/crates/kernel/src/tests.rs +++ b/crates/kernel/src/tests.rs @@ -490,6 +490,43 @@ fn tapered_extrude_of_lines_and_arcs() { assert!(e.to_string().contains("arc meets another edge at a corner"), "{e}"); } +/// A circle with a lobe on each side (four arcs of three circles, meeting at corners: the outline of +/// a scale pocket with finger notches) tapered inward: every circle shrinks by d = z · tan 45°, +/// and the corners go to where the shrunk circles cross, so each section is the union of the +/// shrunk circles. Before, the arcs kept their end angles and the sides missed the corners (#2810). +#[test] +fn tapered_extrude_of_arcs_meeting_at_corners() { + let (r0, w0, c, h, a) = (49.2, 16.2, 41.0, 2.5, 45f64.to_radians()); + let corner = |r: f64, w: f64| { + let x = (r * r - w * w + c * c) / (2.0 * c); + (x, (r * r - x * x).sqrt()) + }; + let (x, y) = corner(r0, w0); + let at = |cx: f64, px: f64, py: f64| (py).atan2(px - cx); + let lobed = Loop2 { + segs: vec![ + Seg2::Arc { center: Vec2::ZERO, radius: r0, start: at(0.0, x, y), sweep: at(0.0, -x, y) - at(0.0, x, y) }, + Seg2::Arc { center: Vec2::new(-c, 0.0), radius: w0, start: at(-c, -x, y), sweep: 2.0 * PI - 2.0 * at(-c, -x, y) }, + Seg2::Arc { center: Vec2::ZERO, radius: r0, start: at(0.0, -x, -y), sweep: at(0.0, x, -y) - at(0.0, -x, -y) }, + Seg2::Arc { center: Vec2::new(c, 0.0), radius: w0, start: at(c, x, -y), sweep: 2.0 * at(c, x, y) }, + ], + }; + let b = extrude_tapered(&Plane::XY, &Region2 { outer: lobed, holes: vec![] }, h, -1.0, -a).unwrap(); + // Union of the circle and two lobes: the circle plus each lobe less its lens with the circle. + let area = |d: f64| { + let (r, w) = (r0 - d, w0 - d); + let lens = r * r * ((c * c + r * r - w * w) / (2.0 * c * r)).acos() + w * w * ((c * c + w * w - r * r) / (2.0 * c * w)).acos() + - 0.5 * ((-c + r + w) * (c + r - w) * (c - r + w) * (c + r + w)).sqrt(); + PI * r * r + 2.0 * (PI * w * w - lens) + }; + let k = 200; + let v: f64 = (0..k).map(|j| area((j as f64 + 0.5) * h / k as f64 * a.tan())).sum::() * h / k as f64; + let m = measure(&b).unwrap(); + assert!(rel(m.volume, v) < 2e-4, "{} vs {v}", m.volume); + assert_eq!(m.merged.faces, 6); + assert!(m.bbox.max.z < 1e-6 && m.bbox.min.z > -h - 1e-6, "{:?}", m.bbox); +} + /// A circle drawn as four conics (the way free curves come, as in text) tapered inward: each /// conic's control polygon moves in by d, which for a circle is the exact smaller circle, so /// the solid is a cone frustum. From 28d67fb5775d3f92a937d6f1017498e43f9fb5c7 Mon Sep 17 00:00:00 2001 From: Erikas <5955795+erkexzcx@users.noreply.github.com> Date: Mon, 19 Oct 2026 23:13:26 +0300 Subject: [PATCH 097/225] Regression tests: a cut short of a face keeps its skin, and the issue's pleats mirror and build at the far end (#1669) (#1730) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Extrude: a profile edge short of a face is not grown through the skin beyond it (#1669) A cut or join profile edge that lies on a face of the target is grown off it by 0.5 % of the body, so that the tool's wall does not lie in the face. Whether it lies on a face was judged half a growth step either side of it: empty just outside, material just inside. An edge 0.25 mm short of a 3.75 mm wall's far face reads the same, and the growth cut through the skin it should leave (55 050 mm³ instead of 56 130 on the test's wall). Now the space just past the edge, 1e-4 of the body out, must already be as the operation wants too. In #1669, the pleat's window built directly at the far end of a case opened through the wall at 3.75 and 4 mm, while its mirror, built without the growth, rightly left the skin and then failed to join the loft through it. Built either way, the window now leaves the skin. Co-Authored-By: Claude Opus 5.5 * Regression tests: the issue's pleats mirror and build at the far end (#1669) The issue's battery case at 3.5 mm: the mirror of the window and the pleat builds (it needed #1670's meshing of twisted faces), and at 3 mm the same window and pleat built directly at the far end of the finished case join it (they needed #1667's end rounds). Co-Authored-By: Claude Opus 5.5 * Far-end pleat test: the direct build matches the mirror's volume Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Erikas Co-authored-by: Claude Opus 5.5 Co-authored-by: bherbruck --- crates/engine/tests/pleat_regressions.rs | 144 ++++++++++++++++++ examples/regressions/battery_case_pleats.json | 39 +++++ 2 files changed, 183 insertions(+) create mode 100644 crates/engine/tests/pleat_regressions.rs create mode 100644 examples/regressions/battery_case_pleats.json diff --git a/crates/engine/tests/pleat_regressions.rs b/crates/engine/tests/pleat_regressions.rs new file mode 100644 index 000000000..edff246f6 --- /dev/null +++ b/crates/engine/tests/pleat_regressions.rs @@ -0,0 +1,144 @@ +//! #1669: a window cut through a battery case's wall and a lofted pleat joined into it, mirrored +//! to the case's far end, and the same features built directly there. + +use serde_json::{Value, json}; +use solidcraft_engine::Session; + +fn replay(script: &str) -> Session { + let mut s = Session::default(); + let script: Value = serde_json::from_str(script).unwrap(); + s.run_script(&script).unwrap(); + s +} + +fn volume(s: &Session, body: &str) -> f64 { + s.model.state().body(body).map(|b| solidcraft_kernel::measure(&b.body).unwrap().volume).unwrap_or(0.0) +} + +/// #1669: an Extrude Cut whose profile stops 0.25 mm short of the far face of a 3.75 mm wall +/// leaves that skin. The profile's edge was taken for one lying on the face (the space half a +/// growth step past it was empty) and grown through the skin, until #1310 asked the faces the +/// growth sweeps instead. A pleat window built so at the far end of a case opened, where its +/// mirror rightly left the skin. +#[test] +fn cut_stopping_short_of_a_face_leaves_the_skin() { + let wall = |width: f64| { + let s = replay( + &json!({"commands": [ + {"command": "solid.box", "params": {"corner": [-100, 0, 0], "length": 200, "width": width, "height": 95, "body_name": "Wall"}}, + {"command": "sketch.create", "params": {"plane": "XY", "offset": -1}}, + {"command": "sketch.rectangle.two_point", "params": {"p0": [-24, -0.5], "p1": [24, 3.5]}}, + {"command": "sketch.finish", "params": {}}, + {"command": "solid.extrude", "params": {"distance": 91, "operation": "cut", "targets": ["Wall"]}} + ]}) + .to_string(), + ); + volume(&s, "Wall") + }; + // 48 wide, 3.5 deep (of the wall's 3.75), 90 high. + let want = 200.0 * 3.75 * 95.0 - 48.0 * 3.5 * 90.0; + let v = wall(3.75); + assert!((v - want).abs() < 1e-6 * want, "{v} vs {want}"); + // A profile ending on the far face still cuts clean through, as before. + let want = 200.0 * 3.5 * 95.0 - 48.0 * 3.5 * 90.0; + let v = wall(3.5); + assert!((v - want).abs() < 1e-6 * want, "{v} vs {want}"); +} + +/// The features of `s` that failed, with their errors. +fn feature_errors(s: &Session) -> Vec<(String, String)> { + s.model.results.iter().filter_map(|r| r.error.clone().map(|e| (r.name.clone(), e))).collect() +} + +/// #1669: a window and a lofted pleat mirrored to the far end of a case shelled 3.5 mm. The +/// pleat's twisted faces were each meshed as two flat triangles (#1666), the joins were checked +/// against those meshes, and the mirror failed ("boolean Union: no result"). +#[test] +fn mirrored_pleat_joins_into_a_thick_case_wall() { + let s = replay(include_str!("../../../examples/regressions/battery_case_pleats.json")); + let errors = feature_errors(&s); + assert!(errors.is_empty(), "{errors:?}"); +} + +/// #1669: at 3 mm, the same window and pleat built directly at the far end of the finished case +/// (a cut and a loft of their own, the mirror suppressed) failed to join as well: the end rounds +/// they meet had folded faces (#1667). +#[test] +fn pleat_built_at_the_far_end_joins_the_finished_case() { + let mut s = replay(include_str!("../../../examples/regressions/battery_case_pleats.json")); + s.execute("parameters.change", &json!({"name": "wall", "expression": "3 mm"})).unwrap(); + let errors = feature_errors(&s); + assert!(errors.is_empty(), "{errors:?}"); + // The case with the mirrored pleat, which the direct build must match. + let mirrored = volume(&s, "Case"); + s.execute("timeline.suppress", &json!({"feature": "PleatFar", "suppressed": true})).unwrap(); + let before = volume(&s, "Case"); + // Mirrored about y = -99: y' = -198 - y. + let far = |points: &[[f64; 2]]| points.iter().map(|[x, y]| json!([x, -198.0 - y])).collect::>(); + let bottom = [ + [-26.0, 3.0], + [-24.76384, 3.0], + [-16.0568, 14.97217], + [-8.0, 4.90117], + [0.0, 14.90117], + [8.0, 4.90117], + [16.0568, 14.97217], + [24.76384, 3.0], + [26.0, 3.0], + [26.0, 0.0], + [23.23616, 0.0], + [15.9432, 10.02783], + [8.0, 0.09883], + [0.0, 10.09883], + [-8.0, 0.09883], + [-15.9432, 10.02783], + [-23.23616, 0.0], + [-26.0, 0.0], + ]; + let top = [ + [-26.0, 3.0], + [-24.0, 3.0], + [-16.0, 3.0], + [-8.0, 3.0], + [0.0, 3.0], + [8.0, 3.0], + [16.0, 3.0], + [24.0, 3.0], + [26.0, 3.0], + [26.0, 0.0], + [24.0, 0.0], + [16.0, 0.0], + [8.0, 0.0], + [0.0, 0.0], + [-8.0, 0.0], + [-16.0, 0.0], + [-24.0, 0.0], + [-26.0, 0.0], + ]; + let steps = json!([ + {"command": "sketch.create", "params": {"plane": "XY", "offset": "-clear", "name": "FarCutSketch"}}, + {"command": "sketch.rectangle.two_point", "params": {"p0": [-24, -197.5], "p1": [24, -201.5]}}, + {"command": "sketch.finish", "params": {}}, + {"command": "solid.extrude", "params": {"sketch": "FarCutSketch", "distance": "pleat_top + clear", "operation": "cut", "targets": ["Case"]}}, + {"command": "sketch.create", "params": {"plane": "XY", "name": "FarBottom"}}, + {"command": "sketch.line", "params": {"closed": true, "infer": false, "connect": false, "points": far(&bottom)}}, + {"command": "sketch.finish", "params": {}}, + {"command": "sketch.create", "params": {"plane": "XY", "offset": "pleat_top + 0.5 mm", "name": "FarTop"}}, + {"command": "sketch.line", "params": {"closed": true, "infer": false, "connect": false, "points": far(&top)}}, + {"command": "sketch.finish", "params": {}}, + {"command": "solid.loft", "params": {"sections": [{"sketch": "FarBottom"}, {"sketch": "FarTop"}], "operation": "join", "targets": ["Case"]}} + ]); + for c in steps.as_array().into_iter().flatten() { + let (id, p) = (c["command"].as_str().unwrap_or_default(), &c["params"]); + if let Err(e) = s.execute(id, p) { + panic!("{id}: {e}"); + } + } + let errors = feature_errors(&s); + assert!(errors.is_empty(), "{errors:?}"); + // The far pleat is the mirror's exact image, so the case comes out as with the mirror (and + // larger than without it: the loft outweighs its window). + let after = volume(&s, "Case"); + assert!(after > before, "{after} after the far pleat, {before} before"); + assert!((after - mirrored).abs() < 1e-6 * mirrored, "{after} built directly, {mirrored} mirrored"); +} diff --git a/examples/regressions/battery_case_pleats.json b/examples/regressions/battery_case_pleats.json new file mode 100644 index 000000000..f9b6171c1 --- /dev/null +++ b/examples/regressions/battery_case_pleats.json @@ -0,0 +1,39 @@ +{ + "description": "A battery case shelled outward 3.5 mm, rounded R5 along its long edges and R1 round both ends (#1669). A window is cut through its front wall and a pleat lofted between an 18-point zig-zag and a flat band is joined into it; the window and the pleat are mirrored to the far end about a plane at half the length. The pleat's twisted ruled faces were meshed off their surfaces along their straight sides, so the meshes the joins are checked on misjudged them: the mirror failed with 'boolean Union: no result', and so did the same window and pleat built directly at the far end of the finished case at 3 mm.", + "commands": [ + {"command": "parameters.add", "params": {"comment": "Battery flat top/bottom width", "expression": "290 mm", "name": "batt_w", "unit": "mm"}}, + {"command": "parameters.add", "params": {"comment": "Side bulge past the top/bottom corners", "expression": "10 mm", "name": "batt_bulge", "unit": "mm"}}, + {"command": "parameters.add", "params": {"comment": "Battery height", "expression": "92 mm", "name": "batt_h", "unit": "mm"}}, + {"command": "parameters.add", "params": {"comment": "Height of the left side's widest point", "expression": "27 mm", "name": "peak_left", "unit": "mm"}}, + {"command": "parameters.add", "params": {"comment": "Height of the right side's widest point", "expression": "batt_h - peak_left", "name": "peak_right", "unit": "mm"}}, + {"command": "parameters.add", "params": {"comment": "Battery length", "expression": "198 mm", "name": "batt_len", "unit": "mm"}}, + {"command": "parameters.add", "params": {"comment": "Connector tab width", "expression": "15 mm", "name": "tab_w", "unit": "mm"}}, + {"command": "parameters.add", "params": {"comment": "Connector tab protrusion", "expression": "5.5 mm", "name": "tab_depth", "unit": "mm"}}, + {"command": "parameters.add", "params": {"comment": "Ramp from tab back to the wall", "expression": "35 mm", "name": "ramp_len", "unit": "mm"}}, + {"command": "parameters.add", "params": {"comment": "Blend radius ramp to wall", "expression": "80 mm", "name": "ramp_blend_wall", "unit": "mm"}}, + {"command": "parameters.add", "params": {"comment": "Blend radius tab to ramp", "expression": "40 mm", "name": "ramp_blend_tab", "unit": "mm"}}, + {"command": "parameters.add", "params": {"comment": "TPU wall thickness", "expression": "3.5 mm", "name": "wall", "unit": "mm"}}, + {"command": "parameters.add", "params": {"comment": "Fillet on the 4 long edges", "expression": "5 mm", "name": "r_big", "unit": "mm"}}, + {"command": "parameters.add", "params": {"comment": "Fillet on all other edges", "expression": "1 mm", "name": "r_small", "unit": "mm"}}, + {"command": "parameters.add", "params": {"comment": "Tool overshoot", "expression": "1 mm", "name": "clear", "unit": "mm"}}, + {"command": "parameters.add", "params": {"comment": "Height where the pleat fades out", "expression": "batt_h - 2 * r_small", "name": "pleat_top", "unit": "mm"}}, + {"command": "timeline.add", "params": {"feature": {"id": 1, "name": "BatteryProfile", "plane": {"plane": {"origin": [0.0, 0.0, 0.0], "x_dir": [1.0, 0.0, 0.0], "y_dir": [-0.0, 0.0, 1.0]}, "type": "custom"}, "sketch": {"constraints": [{"id": "k1", "l": 0, "type": "horizontal"}, {"id": "k2", "l": 3, "type": "horizontal"}, {"a": 3, "b": 6, "id": "k3", "type": "collinear"}, {"id": "k4", "l": 7, "p": 1, "q": 2, "type": "symmetric"}, {"id": "k5", "l": 7, "p": 4, "q": 5, "type": "symmetric"}, {"id": "k6", "l": 0, "param": "d1", "type": "length", "value": 290.0}, {"id": "k7", "l": 3, "param": "d2", "type": "length", "value": 290.0}, {"id": "k8", "p": 1, "param": "d3", "q": 5, "type": "distance_y", "value": 92.0}, {"id": "k9", "p": 2, "param": "d4", "q": 3, "type": "distance_x", "value": 10.0}, {"id": "k10", "p": 4, "param": "d5", "q": 3, "type": "distance_y", "value": 65.0}, {"id": "k11", "p": 5, "param": "d6", "q": 6, "type": "distance_x", "value": 10.0}, {"id": "k12", "p": 5, "param": "d7", "q": 6, "type": "distance_y", "value": 27.0}], "counters": {"j": 2, "k": 12, "l": 8, "p": 4}, "curves": [{"a": 1, "b": 2, "construction": false, "id": "l1", "type": "line"}, {"a": 2, "b": 3, "construction": false, "id": "l2", "type": "line"}, {"a": 3, "b": 4, "construction": false, "id": "l3", "type": "line"}, {"a": 4, "b": 5, "construction": false, "id": "l4", "type": "line"}, {"a": 5, "b": 6, "construction": false, "id": "l5", "type": "line"}, {"a": 6, "b": 1, "construction": false, "id": "l6", "type": "line"}, {"a": 7, "b": 8, "construction": true, "id": "l7", "link": "j1", "type": "line"}, {"a": 9, "b": 10, "construction": true, "id": "l8", "link": "j2", "type": "line"}], "links": [{"id": "j1", "kind": "project", "source": {"name": "x", "type": "sketch_axis"}}, {"id": "j2", "kind": "project", "source": {"name": "y", "type": "sketch_axis"}}], "points": [{"fixed": true, "id": "origin", "pos": [0.0, 0.0]}, {"fixed": false, "id": "l1.start", "pos": [-145.0, 92.0]}, {"fixed": false, "id": "l1.end", "pos": [145.0, 92.0]}, {"fixed": false, "id": "l2.end", "pos": [155.0, 65.0]}, {"fixed": false, "id": "l3.end", "pos": [145.0, 0.0]}, {"fixed": false, "id": "l4.end", "pos": [-145.0, 0.0]}, {"fixed": false, "id": "l5.end", "pos": [-155.0, 27.0]}, {"fixed": true, "id": "p1", "link": "j1", "pos": [-100.0, 0.0]}, {"fixed": true, "id": "p2", "link": "j1", "pos": [100.0, 0.0]}, {"fixed": true, "id": "p3", "link": "j2", "pos": [0.0, -100.0]}, {"fixed": true, "id": "p4", "link": "j2", "pos": [0.0, 100.0]}]}, "suppressed": false, "type": "sketch"}, "params": [{"expression": "batt_w", "name": "d1", "unit": "mm"}, {"expression": "batt_w", "name": "d2", "unit": "mm"}, {"expression": "batt_h", "name": "d3", "unit": "mm"}, {"expression": "batt_bulge", "name": "d4", "unit": "mm"}, {"expression": "peak_right", "name": "d5", "unit": "mm"}, {"expression": "batt_bulge", "name": "d6", "unit": "mm"}, {"expression": "peak_left", "name": "d7", "unit": "mm"}]}}, + {"command": "timeline.add", "params": {"feature": {"body_names": ["Battery"], "extent": {"convention": "total_distance", "direction": "positive", "distance": "batt_len + tab_depth + clear"}, "id": 2, "name": "BatteryStock", "operation": "new_body", "param_names": ["d8"], "profiles": {"type": "all"}, "sketch": 1, "suppressed": false, "type": "extrude"}}}, + {"command": "timeline.add", "params": {"feature": {"id": 3, "name": "PlanOutline", "param_names": ["d9"], "plane": {"base": {"name": "XY", "type": "origin"}, "distance": "-clear", "type": "offset"}, "sketch": {"constraints": [{"id": "k1", "l": 0, "type": "horizontal"}, {"id": "k2", "l": 1, "type": "vertical"}, {"id": "k3", "l": 2, "type": "horizontal"}, {"id": "k4", "l": 4, "type": "horizontal"}, {"id": "k5", "l": 5, "type": "vertical"}, {"id": "k6", "l": 6, "p": 1, "q": 2, "type": "symmetric"}, {"id": "k7", "l": 0, "param": "d10", "type": "length", "value": 320.0}, {"id": "k8", "p": 0, "param": "d11", "q": 1, "type": "distance_y", "value": 1.0}, {"id": "k9", "p": 0, "param": "d12", "q": 3, "type": "distance_y", "value": 198.0}, {"id": "k10", "p": 0, "param": "d13", "q": 5, "type": "distance_y", "value": 203.5}, {"id": "k11", "p": 0, "param": "d14", "q": 5, "type": "distance_x", "value": 130.0}, {"id": "k12", "p": 5, "param": "d15", "q": 4, "type": "distance_x", "value": 35.0}, {"c": 2, "id": "k13", "p": 4, "type": "point_on_curve"}, {"c": 3, "id": "k14", "p": 4, "type": "point_on_curve"}, {"a": 2, "b": 7, "id": "k15", "type": "tangent"}, {"a": 3, "b": 7, "id": "k16", "type": "tangent"}, {"c": 7, "id": "k17", "param": "d16", "type": "radius", "value": 80.0}, {"c": 3, "id": "k18", "p": 5, "type": "point_on_curve"}, {"c": 4, "id": "k19", "p": 5, "type": "point_on_curve"}, {"a": 3, "b": 8, "id": "k20", "type": "tangent"}, {"a": 4, "b": 8, "id": "k21", "type": "tangent"}, {"c": 8, "id": "k22", "param": "d17", "type": "radius", "value": 40.0}], "counters": {"a": 2, "corner": 2, "j": 1, "k": 22, "l": 7, "p": 6}, "curves": [{"a": 1, "b": 2, "construction": false, "id": "l1", "type": "line"}, {"a": 2, "b": 3, "construction": false, "id": "l2", "type": "line"}, {"a": 3, "b": 9, "construction": false, "id": "l3", "type": "line"}, {"a": 10, "b": 12, "construction": false, "id": "l4", "type": "line"}, {"a": 13, "b": 6, "construction": false, "id": "l5", "type": "line"}, {"a": 6, "b": 1, "construction": false, "id": "l6", "type": "line"}, {"a": 7, "b": 8, "construction": true, "id": "l7", "link": "j1", "type": "line"}, {"a": 9, "b": 10, "c": 11, "construction": false, "id": "a1", "type": "arc"}, {"a": 13, "b": 12, "c": 14, "construction": false, "id": "a2", "type": "arc"}], "links": [{"id": "j1", "kind": "project", "source": {"name": "y", "type": "sketch_axis"}}], "points": [{"fixed": true, "id": "origin", "pos": [0.0, 0.0]}, {"fixed": false, "id": "l1.start", "pos": [-160.0, 1.0]}, {"fixed": false, "id": "l1.end", "pos": [160.0, 1.0]}, {"fixed": false, "id": "l2.end", "pos": [160.0, -198.0]}, {"fixed": false, "id": "corner1", "pos": [-95.0, -198.0]}, {"fixed": false, "id": "corner2", "pos": [-130.0, -203.5]}, {"fixed": false, "id": "l5.end", "pos": [-160.0, -203.5]}, {"fixed": true, "id": "p1", "link": "j1", "pos": [0.0, -100.0]}, {"fixed": true, "id": "p2", "link": "j1", "pos": [0.0, 100.0]}, {"fixed": false, "id": "p3", "pos": [-88.75261852925456, -198.0]}, {"fixed": false, "id": "p4", "pos": [-101.17164524862525, -198.96982996764112]}, {"fixed": false, "id": "a1.center", "pos": [-88.75261852925458, -278.0]}, {"fixed": false, "id": "p5", "pos": [-126.91417737568737, -203.01508501617946]}, {"fixed": false, "id": "p6", "pos": [-133.12369073537272, -203.5]}, {"fixed": false, "id": "a2.center", "pos": [-133.12369073537272, -163.5]}]}, "suppressed": false, "type": "sketch"}, "params": [{"expression": "batt_w + 2 * batt_bulge + 10 * clear", "name": "d10", "unit": "mm"}, {"expression": "clear", "name": "d11", "unit": "mm"}, {"expression": "batt_len", "name": "d12", "unit": "mm"}, {"expression": "batt_len + tab_depth", "name": "d13", "unit": "mm"}, {"expression": "batt_w / 2 - tab_w", "name": "d14", "unit": "mm"}, {"expression": "ramp_len", "name": "d15", "unit": "mm"}, {"expression": "ramp_blend_wall", "name": "d16", "unit": "mm"}, {"expression": "ramp_blend_tab", "name": "d17", "unit": "mm"}]}}, + {"command": "timeline.add", "params": {"feature": {"extent": {"convention": "total_distance", "direction": "positive", "distance": "batt_h + 2 * clear"}, "id": 4, "name": "TabAndRamp", "operation": "intersect", "param_names": ["d18"], "profiles": {"type": "all"}, "sketch": 3, "suppressed": false, "targets": ["Battery"], "type": "extrude"}}}, + {"command": "timeline.add", "params": {"feature": {"bodies": ["Battery"], "body_names": ["Case"], "copy": true, "id": 5, "name": "CopyForCase", "param_names": ["d19", "d20", "d21"], "suppressed": false, "translate": ["0", "0", "0"], "type": "move"}}}, + {"command": "timeline.add", "params": {"feature": {"body": "Case", "direction": "outside", "face_names": ["F2:side:l4"], "faces": [[0.0, -100.0, 0.0]], "id": 6, "name": "CaseShell", "param_names": ["d22"], "suppressed": false, "thickness": "wall", "type": "shell"}}}, + {"command": "timeline.add", "params": {"feature": {"id": 7, "name": "PleatCutSketch", "param_names": ["d23"], "plane": {"base": {"name": "XY", "type": "origin"}, "distance": "-clear", "type": "offset"}, "sketch": {"constraints": [{"id": "k1", "l": 0, "type": "horizontal"}, {"id": "k2", "l": 2, "type": "horizontal"}, {"id": "k3", "l": 1, "type": "vertical"}, {"id": "k4", "l": 3, "type": "vertical"}], "counters": {"k": 4, "l": 4, "p": 4}, "curves": [{"a": 1, "b": 2, "construction": false, "id": "l1", "type": "line"}, {"a": 2, "b": 3, "construction": false, "id": "l2", "type": "line"}, {"a": 3, "b": 4, "construction": false, "id": "l3", "type": "line"}, {"a": 4, "b": 1, "construction": false, "id": "l4", "type": "line"}], "points": [{"fixed": true, "id": "origin", "pos": [0.0, 0.0]}, {"fixed": false, "id": "p1", "pos": [-24.0, -0.5]}, {"fixed": false, "id": "p2", "pos": [24.0, -0.5]}, {"fixed": false, "id": "p3", "pos": [24.0, 3.5]}, {"fixed": false, "id": "p4", "pos": [-24.0, 3.5]}]}, "suppressed": false, "type": "sketch"}}}, + {"command": "timeline.add", "params": {"feature": {"extent": {"convention": "total_distance", "direction": "positive", "distance": "pleat_top + clear"}, "id": 8, "name": "PleatCut", "operation": "cut", "param_names": ["d24"], "profiles": {"type": "all"}, "sketch": 7, "suppressed": false, "targets": ["Case"], "type": "extrude"}}}, + {"command": "timeline.add", "params": {"feature": {"id": 9, "name": "PleatBottom", "plane": {"name": "XY", "type": "origin"}, "sketch": {"constraints": [], "counters": {"l": 18}, "curves": [{"a": 1, "b": 2, "construction": false, "id": "l1", "type": "line"}, {"a": 2, "b": 3, "construction": false, "id": "l2", "type": "line"}, {"a": 3, "b": 4, "construction": false, "id": "l3", "type": "line"}, {"a": 4, "b": 5, "construction": false, "id": "l4", "type": "line"}, {"a": 5, "b": 6, "construction": false, "id": "l5", "type": "line"}, {"a": 6, "b": 7, "construction": false, "id": "l6", "type": "line"}, {"a": 7, "b": 8, "construction": false, "id": "l7", "type": "line"}, {"a": 8, "b": 9, "construction": false, "id": "l8", "type": "line"}, {"a": 9, "b": 10, "construction": false, "id": "l9", "type": "line"}, {"a": 10, "b": 11, "construction": false, "id": "l10", "type": "line"}, {"a": 11, "b": 12, "construction": false, "id": "l11", "type": "line"}, {"a": 12, "b": 13, "construction": false, "id": "l12", "type": "line"}, {"a": 13, "b": 14, "construction": false, "id": "l13", "type": "line"}, {"a": 14, "b": 15, "construction": false, "id": "l14", "type": "line"}, {"a": 15, "b": 16, "construction": false, "id": "l15", "type": "line"}, {"a": 16, "b": 17, "construction": false, "id": "l16", "type": "line"}, {"a": 17, "b": 18, "construction": false, "id": "l17", "type": "line"}, {"a": 18, "b": 1, "construction": false, "id": "l18", "type": "line"}], "points": [{"fixed": true, "id": "origin", "pos": [0.0, 0.0]}, {"fixed": false, "id": "l1.start", "pos": [-26.0, 3.0]}, {"fixed": false, "id": "l1.end", "pos": [-24.76384, 3.0]}, {"fixed": false, "id": "l2.end", "pos": [-16.0568, 14.97217]}, {"fixed": false, "id": "l3.end", "pos": [-8.0, 4.90117]}, {"fixed": false, "id": "l4.end", "pos": [0.0, 14.90117]}, {"fixed": false, "id": "l5.end", "pos": [8.0, 4.90117]}, {"fixed": false, "id": "l6.end", "pos": [16.0568, 14.97217]}, {"fixed": false, "id": "l7.end", "pos": [24.76384, 3.0]}, {"fixed": false, "id": "l8.end", "pos": [26.0, 3.0]}, {"fixed": false, "id": "l9.end", "pos": [26.0, 0.0]}, {"fixed": false, "id": "l10.end", "pos": [23.23616, 0.0]}, {"fixed": false, "id": "l11.end", "pos": [15.9432, 10.02783]}, {"fixed": false, "id": "l12.end", "pos": [8.0, 0.09883]}, {"fixed": false, "id": "l13.end", "pos": [0.0, 10.09883]}, {"fixed": false, "id": "l14.end", "pos": [-8.0, 0.09883]}, {"fixed": false, "id": "l15.end", "pos": [-15.9432, 10.02783]}, {"fixed": false, "id": "l16.end", "pos": [-23.23616, 0.0]}, {"fixed": false, "id": "l17.end", "pos": [-26.0, 0.0]}]}, "suppressed": false, "type": "sketch"}}}, + {"command": "timeline.add", "params": {"feature": {"id": 10, "name": "PleatTop", "param_names": ["d25"], "plane": {"base": {"name": "XY", "type": "origin"}, "distance": "pleat_top + 0.5 mm", "type": "offset"}, "sketch": {"constraints": [], "counters": {"l": 18}, "curves": [{"a": 1, "b": 2, "construction": false, "id": "l1", "type": "line"}, {"a": 2, "b": 3, "construction": false, "id": "l2", "type": "line"}, {"a": 3, "b": 4, "construction": false, "id": "l3", "type": "line"}, {"a": 4, "b": 5, "construction": false, "id": "l4", "type": "line"}, {"a": 5, "b": 6, "construction": false, "id": "l5", "type": "line"}, {"a": 6, "b": 7, "construction": false, "id": "l6", "type": "line"}, {"a": 7, "b": 8, "construction": false, "id": "l7", "type": "line"}, {"a": 8, "b": 9, "construction": false, "id": "l8", "type": "line"}, {"a": 9, "b": 10, "construction": false, "id": "l9", "type": "line"}, {"a": 10, "b": 11, "construction": false, "id": "l10", "type": "line"}, {"a": 11, "b": 12, "construction": false, "id": "l11", "type": "line"}, {"a": 12, "b": 13, "construction": false, "id": "l12", "type": "line"}, {"a": 13, "b": 14, "construction": false, "id": "l13", "type": "line"}, {"a": 14, "b": 15, "construction": false, "id": "l14", "type": "line"}, {"a": 15, "b": 16, "construction": false, "id": "l15", "type": "line"}, {"a": 16, "b": 17, "construction": false, "id": "l16", "type": "line"}, {"a": 17, "b": 18, "construction": false, "id": "l17", "type": "line"}, {"a": 18, "b": 1, "construction": false, "id": "l18", "type": "line"}], "points": [{"fixed": true, "id": "origin", "pos": [0.0, 0.0]}, {"fixed": false, "id": "l1.start", "pos": [-26.0, 3.0]}, {"fixed": false, "id": "l1.end", "pos": [-24.0, 3.0]}, {"fixed": false, "id": "l2.end", "pos": [-16.0, 3.0]}, {"fixed": false, "id": "l3.end", "pos": [-8.0, 3.0]}, {"fixed": false, "id": "l4.end", "pos": [0.0, 3.0]}, {"fixed": false, "id": "l5.end", "pos": [8.0, 3.0]}, {"fixed": false, "id": "l6.end", "pos": [16.0, 3.0]}, {"fixed": false, "id": "l7.end", "pos": [24.0, 3.0]}, {"fixed": false, "id": "l8.end", "pos": [26.0, 3.0]}, {"fixed": false, "id": "l9.end", "pos": [26.0, 0.0]}, {"fixed": false, "id": "l10.end", "pos": [24.0, 0.0]}, {"fixed": false, "id": "l11.end", "pos": [16.0, 0.0]}, {"fixed": false, "id": "l12.end", "pos": [8.0, 0.0]}, {"fixed": false, "id": "l13.end", "pos": [0.0, 0.0]}, {"fixed": false, "id": "l14.end", "pos": [-8.0, 0.0]}, {"fixed": false, "id": "l15.end", "pos": [-16.0, 0.0]}, {"fixed": false, "id": "l16.end", "pos": [-24.0, 0.0]}, {"fixed": false, "id": "l17.end", "pos": [-26.0, 0.0]}]}, "suppressed": false, "type": "sketch"}}}, + {"command": "timeline.add", "params": {"feature": {"id": 11, "name": "PleatNear", "operation": "join", "sections": [{"profiles": {"type": "all"}, "sketch": 9}, {"profiles": {"type": "all"}, "sketch": 10}], "suppressed": false, "targets": ["Case"], "type": "loft"}}}, + {"command": "timeline.add", "params": {"feature": {"id": 12, "name": "MidLength", "param_names": ["d26"], "plane": {"base": {"name": "XZ", "type": "origin"}, "distance": "-batt_len / 2", "type": "offset"}, "suppressed": false, "type": "construction_plane"}}}, + {"command": "timeline.add", "params": {"feature": {"features": ["PleatCut", "PleatNear"], "id": 13, "name": "PleatFar", "plane": {"name": "MidLength", "type": "construction"}, "suppressed": false, "type": "mirror"}}}, + {"command": "timeline.add", "params": {"feature": {"body": "Case", "edge_names": ["F2:side:l5@F5.1|F2:side:l6@F5.1", "F2:side:l1@F5.1|F2:side:l6@F5.1", "F2:side:l1@F5.1|F2:side:l2@F5.1", "F2:side:l2@F5.1|F2:side:l3@F5.1", "F6:inner:F2:side:l5@F5.1|F6:inner:F2:side:l6@F5.1", "F6:inner:F2:side:l1@F5.1|F6:inner:F2:side:l6@F5.1", "F6:inner:F2:side:l1@F5.1|F6:inner:F2:side:l2@F5.1", "F6:inner:F2:side:l2@F5.1|F6:inner:F2:side:l3@F5.1"], "edge_refs": [{"dir": [0.0, -1.0, 0.0], "max": [158.08338344416106, 14.97245064486031, 95.00000000000003], "min": [-158.0833834441611, -212.97245548710006, -0.0005980913533997968]}, {"dir": [0.0, -1.0, 0.0], "max": [158.08338344416106, 14.97245064486031, 95.00000000000003], "min": [-158.0833834441611, -212.97245548710006, -0.0005980913533997968]}, {"dir": [0.0, 1.0, 0.0], "max": [158.08338344416106, 14.97245064486031, 95.00000000000003], "min": [-158.0833834441611, -212.97245548710006, -0.0005980913533997968]}, {"dir": [0.0, -1.0, 0.0], "max": [158.08338344416106, 14.97245064486031, 95.00000000000003], "min": [-158.0833834441611, -212.97245548710006, -0.0005980913533997968]}, {"dir": [0.0, 1.0, 0.0], "max": [158.08338344416106, 14.97245064486031, 95.00000000000003], "min": [-158.0833834441611, -212.97245548710006, -0.0005980913533997968]}, {"dir": [0.0, 1.0, 0.0], "max": [158.08338344416106, 14.97245064486031, 95.00000000000003], "min": [-158.0833834441611, -212.97245548710006, -0.0005980913533997968]}, {"dir": [0.0, -1.0, 0.0], "max": [158.08338344416106, 14.97245064486031, 95.00000000000003], "min": [-158.0833834441611, -212.97245548710006, -0.0005980913533997968]}, {"dir": [0.0, 1.0, 0.0], "max": [158.08338344416106, 14.97245064486031, 95.00000000000003], "min": [-158.0833834441611, -212.97245548710006, -0.0005980913533997968]}], "edges": [[-158.0834, -101.75, 26.6874], [-147.5738, -101.75, 95.0], [147.088, -99.0, 95.0], [158.0834, -99.0, 65.3126], [-155.0, -101.75, 27.0], [-145.0, -101.75, 92.0], [145.0, -99.0, 92.0], [155.0, -99.0, 65.0]], "id": 14, "name": "FilletBig", "param_names": ["d27"], "radius": "r_big", "suppressed": false, "type": "fillet"}}}, + {"command": "timeline.add", "params": {"feature": {"body": "Case", "edge_names": ["F2:side:l2@F5.1|F2:start@F5.1", "F2:side:l3@F5.1|F2:start@F5.1", "F2:side:l5@F5.1|F2:start@F5.1", "F2:side:l6@F5.1|F2:start@F5.1", "F2:side:l1@F5.1|F2:start@F5.1"], "edge_refs": [{"dir": [0.34731435582359377, 0.0, -0.9377487607237037], "max": [157.9189160095873, 14.97245064486031, 95.00000000000003], "min": [-157.9189160095873, -212.97245548710006, -0.0005980913533997968]}, {"dir": [-0.1520571842539413, 6.854850442197856e-18, -0.9883716976506173], "max": [157.9189160095873, 14.97245064486031, 95.00000000000003], "min": [-157.9189160095873, -212.97245548710006, -0.0005980913533997968]}, {"dir": [-0.3473143558235947, 0.0, 0.9377487607237034], "max": [157.9189160095873, 14.97245064486031, 95.00000000000003], "min": [-157.9189160095873, -212.97245548710006, -0.0005980913533997968]}, {"dir": [0.15205718425394107, 6.990187846251234e-18, 0.9883716976506172], "max": [157.9189160095873, 14.97245064486031, 95.00000000000003], "min": [-157.9189160095873, -212.97245548710006, -0.0005980913533997968]}, {"dir": [1.0, -1.5479309295511088e-18, 0.0], "max": [157.9189160095873, 14.97245064486031, 95.00000000000003], "min": [-157.9189160095873, -212.97245548710006, -0.0005980913533997968]}], "edges": [[152.5857, 3.0, 80.1563], [153.0593, 3.0, 32.6563], [-153.1413, 3.0, 13.3437], [-152.8286, 3.0, 60.8437], [-80.0, 3.0, 95.0]], "id": 15, "name": "FilletFrontOuter", "param_names": ["d28"], "radius": "r_small", "suppressed": false, "type": "fillet"}}}, + {"command": "timeline.add", "params": {"feature": {"body": "Case", "edge_names": ["F2:side:l3@F5.1|F4:side:l3@F5.1", "F2:side:l2@F5.1|F4:side:l3@F5.1", "F2:side:l5@F5.1|F4:side:l5@F5.1", "F2:side:l6@F5.1|F4:side:l5@F5.1", "F2:side:l1@F5.1|F4:side:l3@F5.1"], "edge_refs": [{"dir": [-0.1520571842539413, 0.0, -0.9883716976506173], "max": [157.92605659069403, 14.97245064486031, 95.00000000000003], "min": [-157.92605659069406, -212.97245548710006, -0.0005980913533997968]}, {"dir": [0.34731435582359377, 0.0, -0.9377487607237037], "max": [157.92605659069403, 14.97245064486031, 95.00000000000003], "min": [-157.92605659069406, -212.97245548710006, -0.0005980913533997968]}, {"dir": [-0.3473143558235947, 0.0, 0.9377487607237034], "max": [157.92605659069403, 14.97245064486031, 95.00000000000003], "min": [-157.92605659069406, -212.97245548710006, -0.0005980913533997968]}, {"dir": [0.15205718425394107, 0.0, 0.9883716976506172], "max": [157.92605659069403, 14.97245064486031, 95.00000000000003], "min": [-157.92605659069406, -212.97245548710006, -0.0005980913533997968]}, {"dir": [1.0, 2.4463450711209976e-16, 0.0], "max": [157.92605659069403, 14.97245064486031, 95.00000000000003], "min": [-157.92605659069406, -212.97245548710006, -0.0005980913533997968]}], "edges": [[153.0593, -201.0, 32.6563], [152.5857, -201.0, 80.1563], [-153.1413, -206.5, 13.3437], [-152.8286, -206.5, 60.8437], [50.0, -201.0, 95.0]], "id": 16, "name": "FilletRearOuter", "param_names": ["d29"], "radius": "r_small", "suppressed": false, "type": "fillet"}}}, + {"command": "timeline.add", "params": {"feature": {"body": "Case", "edge_names": ["F6:inner:F2:side:l3@F5.1|F6:inner:F2:start@F5.1", "F6:inner:F2:side:l2@F5.1|F6:inner:F2:start@F5.1", "F6:inner:F2:side:l1@F5.1|F6:inner:F2:start@F5.1", "F6:inner:F2:side:l6@F5.1|F6:inner:F2:start@F5.1", "F6:inner:F2:side:l5@F5.1|F6:inner:F2:start@F5.1"], "edge_refs": [{"dir": [0.1520571842539411, 0.0, 0.988371697650617], "max": [157.92605659097126, 14.97245064486031, 95.00000000000001], "min": [-157.9260565909712, -212.97245548710006, -0.0005980913533997968]}, {"dir": [-0.34731435582359377, 0.0, 0.9377487607237037], "max": [157.92605659097126, 14.97245064486031, 95.00000000000001], "min": [-157.9260565909712, -212.97245548710006, -0.0005980913533997968]}, {"dir": [-1.0, 0.0, 0.0], "max": [157.92605659097126, 14.97245064486031, 95.00000000000001], "min": [-157.9260565909712, -212.97245548710006, -0.0005980913533997968]}, {"dir": [-0.15205718425394102, 0.0, -0.9883716976506172], "max": [157.92605659097126, 14.97245064486031, 95.00000000000001], "min": [-157.9260565909712, -212.97245548710006, -0.0005980913533997968]}, {"dir": [0.3473143558235949, 0.0, -0.9377487607237033], "max": [157.92605659097126, 14.97245064486031, 95.00000000000001], "min": [-157.9260565909712, -212.97245548710006, -0.0005980913533997968]}], "edges": [[149.9014, 0.0, 31.8594], [150.3792, 0.0, 77.4761], [80.0, 0.0, 92.0], [-150.2276, 0.0, 58.0208], [-149.7749, 0.0, 12.8922]], "id": 17, "name": "FilletFrontInner", "param_names": ["d30"], "radius": "r_small", "suppressed": false, "type": "fillet"}}}, + {"command": "timeline.add", "params": {"feature": {"body": "Case", "edge_names": ["F6:inner:F2:side:l3@F5.1|F6:inner:F4:side:l3@F5.1", "F6:inner:F2:side:l2@F5.1|F6:inner:F4:side:l3@F5.1", "F6:inner:F2:side:l1@F5.1|F6:inner:F4:side:l3@F5.1", "F6:inner:F2:side:l6@F5.1|F6:inner:F4:side:l5@F5.1", "F6:inner:F2:side:l5@F5.1|F6:inner:F4:side:l5@F5.1"], "edge_refs": [{"dir": [0.1520571842539411, 0.0, 0.988371697650617], "max": [157.92605659097126, 14.97245064486031, 95.00000000000001], "min": [-157.9260565909712, -212.97245548710006, -0.0005980913533997968]}, {"dir": [-0.34731435582359377, 0.0, 0.9377487607237037], "max": [157.92605659097126, 14.97245064486031, 95.00000000000001], "min": [-157.9260565909712, -212.97245548710006, -0.0005980913533997968]}, {"dir": [-1.0, -2.4685277687458984e-16, 0.0], "max": [157.92605659097126, 14.97245064486031, 95.00000000000001], "min": [-157.9260565909712, -212.97245548710006, -0.0005980913533997968]}, {"dir": [-0.15205718425394102, 0.0, -0.9883716976506172], "max": [157.92605659097126, 14.97245064486031, 95.00000000000001], "min": [-157.9260565909712, -212.97245548710006, -0.0005980913533997968]}, {"dir": [0.347314355823594, 0.0, -0.9377487607237036], "max": [157.92605659097126, 14.97245064486031, 95.00000000000001], "min": [-157.9260565909712, -212.97245548710006, -0.0005980913533997968]}], "edges": [[149.9014, -198.0, 31.8594], [150.3792, -198.0, 77.4761], [80.0, -198.0, 92.0], [-150.2276, -203.5, 58.0208], [-149.7749, -203.5, 12.8922]], "id": 18, "name": "FilletRearInner", "param_names": ["d31"], "radius": "r_small", "suppressed": false, "type": "fillet"}}} + ] +} From 77c3b1e765f7e6f7514c37632a1f3873558fa4c7 Mon Sep 17 00:00:00 2001 From: takuto-NA Date: Tue, 20 Oct 2026 05:13:51 +0900 Subject: [PATCH 098/225] Sketch: preview slot outlines before committing (#2535) (#2537) * claim: #2535 * claim: #2535 * Sketch: preview all slot sides and caps while choosing width Fix missing temporary slot geometry for all five tools and paint every preview curve with a shared sampling budget. Preserve the arc slot construction guide. Add geometry, painting, invalid-input and interactive typed-width regression coverage. * Sketch: honor typed slot widths below the pointer minimum --------- Co-authored-by: bherbruck --- .../src/sketch_display_preview_tests.rs | 143 +++++++++++++++++- crates/ui-egui/src/sketch_tools.rs | 2 +- crates/ui-egui/src/tools.rs | 98 ++++++++++-- .../ui-egui/tests/scenarios/slot_preview.json | 82 ++++++++++ 4 files changed, 306 insertions(+), 19 deletions(-) create mode 100644 crates/ui-egui/tests/scenarios/slot_preview.json diff --git a/crates/ui-egui/src/sketch_display_preview_tests.rs b/crates/ui-egui/src/sketch_display_preview_tests.rs index c7fc01e00..06e54483b 100644 --- a/crates/ui-egui/src/sketch_display_preview_tests.rs +++ b/crates/ui-egui/src/sketch_display_preview_tests.rs @@ -86,7 +86,7 @@ fn pixel_preview_temporary_curves_match_committed_geometry_and_sampling() { ]; for (command, points, hover, sweep, rho, params) in cases { let tool = tool(command, &points); - let preview = preview_curve(&tool, Vec2::new(hover[0], hover[1]), sweep, rho).unwrap(); + let preview = preview_curve(&tool, Vec2::new(hover[0], hover[1]), sweep, rho, None).unwrap(); let mut h = Harness::new(); h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); h.app.run(command, params).unwrap(); @@ -129,7 +129,7 @@ fn pixel_preview_temporary_curves_match_committed_geometry_and_sampling() { #[test] fn pixel_preview_fully_offscreen_circle_is_clipped_without_false_connections() { - let curve = preview_curve(&tool("sketch.circle.center", &[[0., 0.]]), Vec2::X, None, None).unwrap(); + let curve = preview_curve(&tool("sketch.circle.center", &[[0., 0.]]), Vec2::X, None, None, None).unwrap(); let proj = projection(1000.0); // The viewport half diagonal is about 832px: a 1000px circle never enters it. assert!((proj.rect.width() * 0.5).hypot(proj.rect.height() * 0.5) < 1000.0); @@ -138,10 +138,10 @@ fn pixel_preview_fully_offscreen_circle_is_clipped_without_false_connections() { #[test] fn pixel_preview_rejects_degenerate_and_unbounded_input_without_changing_document() { - assert!(preview_curve(&tool("sketch.circle.center", &[[0., 0.]]), Vec2::new(f64::NAN, 0.), None, None).is_none()); - assert!(preview_curve(&tool("sketch.arc.three_point", &[[0., 0.], [1., 0.]]), Vec2::new(2., 0.), None, None).is_none()); + assert!(preview_curve(&tool("sketch.circle.center", &[[0., 0.]]), Vec2::new(f64::NAN, 0.), None, None, None).is_none()); + assert!(preview_curve(&tool("sketch.arc.three_point", &[[0., 0.], [1., 0.]]), Vec2::new(2., 0.), None, None, None).is_none()); let points = vec![[0., 0.]; 500]; - assert!(preview_curve(&tool("sketch.spline.fit_point", &points), Vec2::X, None, None).is_none()); + assert!(preview_curve(&tool("sketch.spline.fit_point", &points), Vec2::X, None, None, None).is_none()); } #[test] @@ -173,3 +173,136 @@ fn polygon_preview_rejects_invalid_or_unbounded_input() { let t = tool("sketch.polygon.inscribed", &[[f64::INFINITY, 0.0]]); assert!(polygon_outline(&t, Vec2::X, 6.0).is_none()); } + +#[test] +fn slot_preview_matches_every_committed_side_and_cap() { + let cases = [ + ("sketch.slot.center_to_center", vec![[0., 0.], [40., 0.]], [20., 8.], json!({"p0":[0,0],"p1":[40,0],"width":16})), + // Free pointer input retains the final click's minimum width. + ("sketch.slot.center_to_center", vec![[0., 0.], [40., 0.]], [20., 0.], json!({"p0":[0,0],"p1":[40,0],"width":0.001})), + ("sketch.slot.overall", vec![[0., 0.], [40., 0.]], [20., -8.], json!({"p0":[0,0],"p1":[40,0],"width":16})), + ("sketch.slot.center_point", vec![[0., 0.], [20., 0.]], [10., 8.], json!({"center":[0,0],"end":[20,0],"width":16})), + ("sketch.slot.arc_center", vec![[0., 0.], [20., 0.], [0., 20.]], [0., 24.], json!({"center":[0,0],"start":[20,0],"end":[0,20],"width":8})), + ( + "sketch.slot.arc_three_point", + vec![[20., 0.], [0., 20.], [-20., 0.]], + [-20., 4.], + json!({"start":[20,0],"through":[0,20],"end":[-20,0],"width":8}), + ), + // A sloping, reversed axis and the opposite side of a three-point centre arc. + ("sketch.slot.center_to_center", vec![[30., 40.], [0., 0.]], [8., -6.], json!({"p0":[30,40],"p1":[0,0],"width":20})), + ( + "sketch.slot.arc_three_point", + vec![[-20., 0.], [0., 20.], [20., 0.]], + [20., -4.], + json!({"start":[-20,0],"through":[0,20],"end":[20,0],"width":8}), + ), + ]; + for (command, points, hover, params) in cases { + let mut h = Harness::new(); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + let preview = preview_curve(&tool(command, &points), Vec2::new(hover[0], hover[1]), None, None, None) + .unwrap_or_else(|| panic!("{command}: no slot outline before the width click")); + let ctx = egui::Context::default(); + let proj = projection(2.0); + let output = ctx.run_ui(egui::RawInput { screen_rect: Some(proj.rect), ..Default::default() }, |ui| { + super::paint_preview_curve(preview.clone(), &Plane::XY, ui.painter(), &proj, egui::Stroke::new(1.5, egui::Color32::WHITE), 0); + }); + assert_eq!( + output.shapes.iter().filter(|shape| matches!(shape.shape, egui::Shape::Path(_))).count(), + 4, + "{command}: paint all four outline curves" + ); + h.app.run(command, params).unwrap(); + let state = h.app.session.world_state(); + let committed = &state.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch; + assert_eq!(preview.curves.len(), committed.curves.len(), "{command}"); + for index in 0..committed.curves.len() { + let a = preview.exact_segs(index).unwrap_or_else(|| preview.segs(index)); + let b = committed.exact_segs(index).unwrap_or_else(|| committed.segs(index)); + assert_eq!(a.len(), b.len(), "{command}, curve {index}"); + assert_eq!(preview.curves[index].construction, committed.curves[index].construction); + for (a, b) in a.iter().zip(&b) { + for i in 0..=20 { + assert!(a.point_at(f64::from(i) / 20.0).dist(b.point_at(f64::from(i) / 20.0)) < 1e-7, "{command}, curve {index}"); + } + } + } + } +} + +#[test] +fn typed_small_slot_width_preview_matches_the_final_click() { + for (command, length) in [("sketch.slot.center_to_center", 40.0), ("sketch.slot.overall", 40.0), ("sketch.slot.overall", 0.0002)] { + let mut h = Harness::new(); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + let mut t = tool(command, &[[0., 0.], [length, 0.]]); + t.dims = crate::sketch_dims::boxes_for(command, 2); + t.dims[0].value = "0.0002 / 2".into(); + t.dims[0].locked = true; + t.hover = Some((Vec2::new(length * 0.5, 8.), None)); + crate::sketch_dims::validate(&h.app, &t).unwrap(); + + // Zoom into the first cap: the accepted typed width is smaller than the pointer's + // minimum width, and must still produce the same visible outline as the final click. + let ctx = egui::Context::default(); + let proj = projection(2_000_000.0); + let input = || egui::RawInput { screen_rect: Some(proj.rect), ..Default::default() }; + let output = ctx.run_ui(input(), |ui| super::preview(&h.app, &t, ui.painter(), &proj)); + let paths = |output: egui::FullOutput| { + output + .shapes + .into_iter() + .filter_map(|s| match s.shape { + egui::Shape::Path(path) => Some(path.points), + _ => None, + }) + .collect::>() + }; + let preview = paths(output); + assert!(h.app.session.world_state().sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch.curves.is_empty()); + + let click = crate::sketch_dims::placed(&h.app, &t, t.hover.as_ref().unwrap()); + h.app.tool = Some(t); + super::place(&mut h.app, click); + let state = h.app.session.world_state(); + let committed = &state.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch; + assert_eq!(committed.curves.len(), 4, "{command}: final click commits the typed width"); + let solidcraft_engine::geom::Seg2::Arc { radius, .. } = committed.segs(1)[0] else { panic!("missing slot cap") }; + assert!((radius - 0.00005).abs() < 1e-10, "{command}: the typed width determines the cap radius"); + let output = ctx.run_ui(input(), |ui| { + super::paint_preview_curve(committed.clone(), &Plane::XY, ui.painter(), &proj, egui::Stroke::new(1.5, egui::Color32::WHITE), 0); + }); + let expected = paths(output); + assert!(!expected.is_empty(), "{command}: the zoomed cap must be visible"); + assert_eq!(preview.len(), expected.len(), "{command}: preview and committed paths"); + for (preview, expected) in preview.iter().zip(&expected) { + assert_eq!(preview.len(), expected.len(), "{command}: sampled path vertices"); + for (preview, expected) in preview.iter().zip(expected) { + assert!(preview.distance(*expected) < 0.1, "{command}: preview {preview:?}, committed {expected:?}"); + } + } + } +} + +#[test] +fn slot_preview_rejects_invalid_extents() { + let cases = [ + ("sketch.slot.center_to_center", vec![[0., 0.], [0., 0.]], [0., 8.]), + ("sketch.slot.overall", vec![[0., 0.], [10., 0.]], [5., 5.]), + ("sketch.slot.overall", vec![[0., 0.], [10., 0.]], [5., 8.]), + ("sketch.slot.arc_center", vec![[0., 0.], [20., 0.], [0., 20.]], [0., 40.]), + ("sketch.slot.arc_center", vec![[0., 0.], [0., 20.], [0., 0.]], [0., 24.]), + ("sketch.slot.arc_three_point", vec![[0., 0.], [10., 0.], [20., 0.]], [20., 4.]), + ]; + for (command, points, hover) in cases { + assert!(preview_curve(&tool(command, &points), Vec2::new(hover[0], hover[1]), None, None, None).is_none(), "{command}"); + } + let t = tool("sketch.slot.center_to_center", &[[0., 0.], [40., 0.]]); + for hover in [Vec2::new(f64::NAN, 0.), Vec2::new(0., f64::INFINITY), Vec2::new(f64::MAX, f64::MAX)] { + assert!(preview_curve(&t, hover, None, None, None).is_none()); + } + for width in [0.0, -1.0, f64::NAN, f64::INFINITY, f64::MAX] { + assert!(preview_curve(&t, Vec2::new(20., 8.), None, None, Some(width)).is_none()); + } +} diff --git a/crates/ui-egui/src/sketch_tools.rs b/crates/ui-egui/src/sketch_tools.rs index f4edda24f..5f05fb120 100644 --- a/crates/ui-egui/src/sketch_tools.rs +++ b/crates/ui-egui/src/sketch_tools.rs @@ -1033,7 +1033,7 @@ pub fn preview(app: &SolveApp, t: &Tool, painter: &egui::Painter, proj: &Proj) { } } if let Some((h, _)) = t.hover.as_ref() - && let Some(curve) = crate::tools::preview_curve(t, *h, None, crate::sketch_dims::locked_value(app, t, "Rho")) + && let Some(curve) = crate::tools::preview_curve(t, *h, None, crate::sketch_dims::locked_value(app, t, "Rho"), None) { crate::tools::paint_preview_curve(curve, &ss.plane, painter, proj, stroke, crate::sketch_palette::mode(app)); } diff --git a/crates/ui-egui/src/tools.rs b/crates/ui-egui/src/tools.rs index e34e2068e..773e9d074 100644 --- a/crates/ui-egui/src/tools.rs +++ b/crates/ui-egui/src/tools.rs @@ -410,8 +410,10 @@ fn run_shape(app: &mut SolveApp, t: &Tool) -> Result, String> { "sketch.polygon.edge" => json!({"p0": xy(&p[0]), "p1": xy(&p[1]), "sides": sides}), "sketch.slot.center_to_center" | "sketch.slot.overall" => { let dir = (p[1].0 - p[0].0).normalized().unwrap_or(Vec2::X); - let w = 2.0 * dir.cross(p[2].0 - p[0].0).abs(); - json!({"p0": xy(&p[0]), "p1": xy(&p[1]), "width": w.max(1e-3)}) + // Seed the creator with the typed width too: an Overall slot places its cap + // centres from this width before the driving dimension is applied. + let width = crate::sketch_dims::locked_value(app, t, "Width").unwrap_or_else(|| (2.0 * dir.cross(p[2].0 - p[0].0).abs()).max(1e-3)); + json!({"p0": xy(&p[0]), "p1": xy(&p[1]), "width": width}) } "sketch.point" => json!({"point": xy(&p[0])}), _ => return Err(format!("drawing {} is not supported", t.cmd)), @@ -572,9 +574,13 @@ pub(crate) fn paint_preview_curve( let line = matches!(curve.kind, solidcraft_engine::sketch::CurveKind::Line { .. }); curve.centerline = mode == 2 && line; curve.infinite = mode == 3 && line; - curve.construction = mode != 0 && !curve.centerline; + curve.construction |= mode != 0 && !curve.centerline; } - paint_curve(&sketch, 0, plane, painter, proj, stroke, &mut solidcraft_engine::render::SamplingBudget::new(4096, 65_536)); + let mut budget = solidcraft_engine::render::SamplingBudget::new(4096, 65_536); + for index in 0..sketch.curves.len() { + paint_curve(&sketch, index, plane, painter, proj, stroke, &mut budget); + } + crate::scenario::publish_count("tool_preview_curves", sketch.curves.len() as f64); } pub(crate) fn paint_sketch_path(points: &[solidcraft_engine::geom::Vec3], mode: u8, painter: &egui::Painter, proj: &Proj, stroke: Stroke) { @@ -610,7 +616,13 @@ pub(crate) fn paint_curve( /// Temporary analytic geometry uses the same exact span extraction as committed curves. /// It never solves constraints or modifies the document. -pub(crate) fn preview_curve(t: &Tool, hover: Vec2, sweep: Option, rho: Option) -> Option { +pub(crate) fn preview_curve( + t: &Tool, + hover: Vec2, + sweep: Option, + rho: Option, + slot_width: Option, +) -> Option { use solidcraft_engine::sketch::{CurveKind, Sketch}; if !hover.is_finite() || t.pts.len() >= solidcraft_engine::sketch::MAX_SPLINE_POINTS || t.pts.iter().any(|p| !p.0.is_finite()) { return None; @@ -633,13 +645,7 @@ pub(crate) fn preview_curve(t: &Tool, hover: Vec2, sweep: Option, rho: Opti sk.add_line(*m * 2.0 - hover, hover, None, None, None).ok()?; } ("sketch.circle.three_point" | "sketch.arc.three_point", [a, b]) => { - let ab = *b - *a; - let ah = hover - *a; - let d = 2.0 * ab.cross(ah); - if !d.is_finite() || d.abs() < 1e-12 { - return None; - } - let centre = *a + Vec2::new(ah.y * ab.len2() - ab.y * ah.len2(), ab.x * ah.len2() - ah.x * ab.len2()) / d; + let centre = preview_circumcentre(*a, *b, hover)?; if t.cmd == "sketch.circle.three_point" { sk.add_circle(centre, centre.dist(*a), None, None).ok()?; } else { @@ -664,6 +670,55 @@ pub(crate) fn preview_curve(t: &Tool, hover: Vec2, sweep: Option, rho: Opti curve.reversed = sweep < 0.0; } } + ("sketch.slot.center_to_center" | "sketch.slot.overall" | "sketch.slot.center_point", [a, b]) => { + let dir = (*b - *a).normalized()?; + // Typed widths can be smaller than the final click's pointer minimum. + let width = slot_width.unwrap_or_else(|| (2.0 * dir.cross(hover - *a).abs()).max(1e-3)); + if !width.is_finite() || width <= 1e-9 { + return None; + } + let radius = width * 0.5; + let (c0, c1) = match t.cmd { + "sketch.slot.overall" if a.dist(*b) > width => (*a + dir * radius, *b - dir * radius), + "sketch.slot.overall" => return None, + "sketch.slot.center_point" => (*a * 2.0 - *b, *b), + _ => (*a, *b), + }; + let n = dir.perp() * radius; + sk.add_line(c0 - n, c1 - n, None, None, None).ok()?; + sk.add_arc(c1, c1 - n, c1 + n, [None; 3], None).ok()?; + sk.add_line(c1 + n, c0 + n, None, None, None).ok()?; + sk.add_arc(c0, c0 + n, c0 - n, [None; 3], None).ok()?; + } + ("sketch.slot.arc_center" | "sketch.slot.arc_three_point", [a, b, c]) => { + let (centre, start, end, radius, width) = if t.cmd == "sketch.slot.arc_center" { + (*a, *b, *c, a.dist(*b), (2.0 * (hover.dist(*a) - a.dist(*b)).abs()).max(1e-3)) + } else { + let centre = preview_circumcentre(*a, *c, *b)?; + let span = |p: Vec2| ((p - centre).angle() - (*a - centre).angle()).rem_euclid(std::f64::consts::TAU); + let (start, end) = if span(*b) < span(*c) { (*a, *c) } else { (*c, *a) }; + (centre, start, end, centre.dist(*a), (2.0 * hover.dist(*c)).max(1e-3)) + }; + let t0 = (start - centre).angle(); + let sweep = ((end - centre).angle() - t0).rem_euclid(std::f64::consts::TAU); + let half = width * 0.5; + if !radius.is_finite() + || !half.is_finite() + || half >= radius + || end.dist(centre) < 1e-9 + || !(sweep > 1e-6 && sweep < std::f64::consts::TAU - 1e-6) + { + return None; + } + let at = |angle: f64, r: f64| centre + Vec2::from_angle(angle) * r; + let t1 = t0 + sweep; + sk.add_arc(centre, at(t0, radius + half), at(t1, radius + half), [None; 3], None).ok()?; + sk.add_arc(centre, at(t0, radius - half), at(t1, radius - half), [None; 3], None).ok()?; + sk.add_arc(at(t1, radius), at(t1, radius + half), at(t1, radius - half), [None; 3], None).ok()?; + sk.add_arc(at(t0, radius), at(t0, radius - half), at(t0, radius + half), [None; 3], None).ok()?; + let guide = sk.add_arc(centre, at(t0, radius), at(t1, radius), [None; 3], None).ok()?; + sk.curves.get_mut(guide)?.construction = true; + } ("sketch.ellipse", [c, m]) => { let u = (*m - *c).normalized()?; let d = hover - *c; @@ -712,6 +767,17 @@ pub(crate) fn preview_curve(t: &Tool, hover: Vec2, sweep: Option, rho: Opti Some(sk) } +fn preview_circumcentre(a: Vec2, b: Vec2, c: Vec2) -> Option { + let ab = b - a; + let ac = c - a; + let d = 2.0 * ab.cross(ac); + if !d.is_finite() || d.abs() < 1e-12 { + return None; + } + let centre = a + Vec2::new(ac.y * ab.len2() - ab.y * ac.len2(), ab.x * ac.len2() - ac.x * ab.len2()) / d; + centre.is_finite().then_some(centre) +} + /// The polygon's actual straight edges, in the same orientation as the eventual command. /// Keep preview work bounded even while a side-count expression is being edited. pub(crate) fn polygon_outline(t: &Tool, hover: Vec2, sides: f64) -> Option> { @@ -779,7 +845,13 @@ pub fn preview(app: &SolveApp, t: &Tool, painter: &egui::Painter, proj: &Proj) { } } - if let Some(curve) = preview_curve(t, h, crate::sketch_dims::locked_value(app, t, "Sweep"), crate::sketch_dims::locked_value(app, t, "Rho")) { + if let Some(curve) = preview_curve( + t, + h, + crate::sketch_dims::locked_value(app, t, "Sweep"), + crate::sketch_dims::locked_value(app, t, "Rho"), + crate::sketch_dims::locked_value(app, t, "Width"), + ) { paint_preview_curve(curve, &ss.plane, painter, proj, stroke, crate::sketch_palette::mode(app)); return; } diff --git a/crates/ui-egui/tests/scenarios/slot_preview.json b/crates/ui-egui/tests/scenarios/slot_preview.json new file mode 100644 index 000000000..5fc092171 --- /dev/null +++ b/crates/ui-egui/tests/scenarios/slot_preview.json @@ -0,0 +1,82 @@ +[ + {"note":"#2535: show the complete slot outline while choosing its width, without adding document curves until the final click."}, + {"call":"engine.execute","params":{"command":"sketch.create","params":{"plane":"XY"}}}, + {"call":"ui.view","params":{"view":"top"}}, + {"start":"sketch.slot.center_to_center"}, + {"click":{"sketch":[0,0]}}, + {"click":{"sketch":[40,0]}}, + {"move":{"sketch":[20,8]}}, + {"expect":{"count":{"name":"tool_preview_curves","value":4},"sketch_curves":{"own":0},"errors":0}}, + {"text":"16"}, + {"key":"Tab"}, + {"move":{"sketch":[20,20]}}, + {"expect":{"count":{"name":"tool_preview_curves","value":4},"errors":0}}, + {"click":{"sketch":[20,20]}}, + {"expect":{"sketch_curves":{"own":4},"param":{"d1":16},"errors":0}}, + {"key":"Escape"}, + {"start":"sketch.slot.overall"}, + {"click":{"sketch":[0,-30]}}, + {"click":{"sketch":[40,-30]}}, + {"move":{"sketch":[20,-38]}}, + {"expect":{"count":{"name":"tool_preview_curves","value":4},"errors":0}}, + {"click":{"sketch":[20,-38]}}, + {"expect":{"sketch_curves":{"own":8},"errors":0}}, + {"key":"Escape"}, + {"start":"sketch.slot.center_point"}, + {"click":{"sketch":[0,30]}}, + {"click":{"sketch":[20,30]}}, + {"move":{"sketch":[10,38]}}, + {"expect":{"count":{"name":"tool_preview_curves","value":4},"errors":0}}, + {"click":{"sketch":[10,38]}}, + {"expect":{"sketch_curves":{"own":12},"errors":0}}, + {"key":"Escape"}, + {"call":"engine.execute","params":{"command":"sketch.create","params":{"plane":"XY"}}}, + {"call":"ui.view","params":{"view":"top"}}, + {"start":"sketch.slot.arc_center"}, + {"click":{"sketch":[0,0]}}, + {"click":{"sketch":[20,0]}}, + {"click":{"sketch":[0,20]}}, + {"move":{"sketch":[0,24]}}, + {"expect":{"count":{"name":"tool_preview_curves","value":5},"errors":0}}, + {"click":{"sketch":[0,24]}}, + {"expect":{"sketch_curves":{"own":5},"errors":0}}, + {"key":"Escape"}, + {"call":"engine.execute","params":{"command":"sketch.create","params":{"plane":"XY"}}}, + {"call":"ui.view","params":{"view":"top"}}, + {"start":"sketch.slot.arc_three_point"}, + {"click":{"sketch":[20,0]}}, + {"click":{"sketch":[0,20]}}, + {"click":{"sketch":[-20,0]}}, + {"move":{"sketch":[-20,4]}}, + {"expect":{"count":{"name":"tool_preview_curves","value":5},"errors":0}}, + {"click":{"sketch":[-20,4]}}, + {"expect":{"sketch_curves":{"own":5},"errors":0}}, + {"key":"Escape"}, + {"note":"Typed widths below the pointer minimum remain valid for both dimensioned slot tools."}, + {"call":"engine.execute","params":{"command":"sketch.create","params":{"plane":"XY"}}}, + {"call":"ui.view","params":{"view":"top"}}, + {"start":"sketch.slot.center_to_center"}, + {"click":{"sketch":[0,0]}}, + {"click":{"sketch":[40,0]}}, + {"move":{"sketch":[20,8]}}, + {"text":"0.0002 / 2"}, + {"key":"Tab"}, + {"move":{"sketch":[20,20]}}, + {"expect":{"count":{"name":"tool_preview_curves","value":4},"sketch_curves":{"own":0},"errors":0}}, + {"click":{"sketch":[20,20]}}, + {"expect":{"sketch_curves":{"own":4},"param":{"d2":0.0001},"errors":0}}, + {"key":"Escape"}, + {"call":"engine.execute","params":{"command":"sketch.create","params":{"plane":"XY"}}}, + {"call":"ui.view","params":{"view":"top"}}, + {"start":"sketch.slot.overall"}, + {"click":{"sketch":[0,0]}}, + {"click":{"sketch":[40,0]}}, + {"move":{"sketch":[20,8]}}, + {"text":"0.0001"}, + {"key":"Tab"}, + {"move":{"sketch":[20,20]}}, + {"expect":{"count":{"name":"tool_preview_curves","value":4},"sketch_curves":{"own":0},"errors":0}}, + {"click":{"sketch":[20,20]}}, + {"expect":{"sketch_curves":{"own":4},"param":{"d3":0.0001},"errors":0}}, + {"key":"Escape"} +] From 02c77df5f7bda1bf705c8ab1e0d2e06577a44984 Mon Sep 17 00:00:00 2001 From: NOWN-DEV <257771410+NOWN-DEV@users.noreply.github.com> Date: Mon, 19 Oct 2026 22:14:24 +0200 Subject: [PATCH 099/225] inspect.clearance: mesh each body once per check instead of once per pair (#2867) * inspect.clearance: pairs whose bodies did not change are not measured again Each clearance check measured every close pair again, though between two checks usually only a few bodies change or move. Results are now kept per pair, keyed by both bodies' geometry and placement and the check's settings; a pair whose two bodies are unchanged is taken from that cache. With 40 overlapping parts, a check after moving one of them took 0.8 s instead of 23 s (741 of 780 pairs reused). Pairs that could not be worked out are tried again each time. Co-Authored-By: Claude Opus 5.5 (1M context) * inspect.clearance: boxes and placed keys exactly as before the reuse The pair boxes are taken over the mesh's triangles with finite corners, as a distance shape's are, so pruning is unchanged. A placed body's identity now includes its model body's own frame, so two placements are never mistaken for one another. Co-Authored-By: Claude Opus 5.5 (1M context) * inspect.clearance: a large body is meshed once for all its pairs Each pair that touches cuts the larger body down to the pair's region with a kernel boolean, and that boolean meshed the whole body twice: once for its checks and once inside the intersection. A sheet with 600 faces paid about 2.5 s per pair for meshes that were the same every time. A body can now keep its meshes for reuse (Body::keeping_meshes); its booleans take the meshes from there, and the intersection takes its shell meshes from there too (truck-shapeops: and_with_history_meshed). Clearance uses such copies for one check. Results are unchanged to the bit. On a 3 x 2 m sheet with bends and 300 holes, the clip took 0.23 s per pair instead of 2.6 s, and 24 rivets took 5.6 s instead of 16.5 s. Co-Authored-By: Claude Opus 5.5 (1M context) --------- Co-authored-by: Claude Opus 5.5 (1M context) Co-authored-by: bherbruck --- ATTRIBUTION.md | 2 +- crates/doc/src/eval.rs | 22 +++++ crates/engine/src/cmd/clearance.rs | 93 ++++++++++++++++--- crates/engine/src/cmd/clearance_tests.rs | 53 +++++++++++ crates/engine/src/cmd/mod.rs | 2 +- crates/engine/src/lib.rs | 5 + crates/kernel/src/body.rs | 64 ++++++++++++- crates/kernel/src/mesh_memo_tests.rs | 65 +++++++++++++ crates/kernel/src/meshbody.rs | 2 + crates/kernel/src/native.rs | 1 + crates/kernel/src/ops.rs | 10 +- crates/kernel/src/outline.rs | 1 + crates/kernel/src/splitface.rs | 2 + crates/kernel/src/surfaces.rs | 1 + vendor/README.md | 4 + vendor/truck-shapeops/src/lib.rs | 4 +- .../src/transversal/integrate/mod.rs | 44 +++++++-- vendor/truck-shapeops/src/transversal/mod.rs | 2 +- 18 files changed, 346 insertions(+), 31 deletions(-) create mode 100644 crates/kernel/src/mesh_memo_tests.rs diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 4d0a11256..92f415137 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -472,7 +472,7 @@ copied into SolidCraft. |---|---|---|---| | vendor/truck-meshalgo | truck-meshalgo 0.4.0, https://github.com/ricosjp/truck (RICOS Co. Ltd.) | Apache-2.0 | meshing: bounded parameter searches, collapsed-boundary projection, subdivision and provisional fixed-grid previews (vendor/README.md) | | vendor/truck-stepio | truck-stepio 0.3.0, https://github.com/ricosjp/truck (RICOS Co. Ltd.) | Apache-2.0 | STEP writer: intersection-curve surfaces written at unique ids (vendor/README.md) | -| vendor/truck-shapeops | truck-shapeops 0.4.0, https://github.com/ricosjp/truck (RICOS Co. Ltd.) | Apache-2.0 | robust meshing and nearest-parameter fallback in booleans; degenerate intersection-curve rejection; face and edge history of booleans; trace macro; corner choice at vertices several intersection curves end on (vendor/README.md) | +| vendor/truck-shapeops | truck-shapeops 0.4.0, https://github.com/ricosjp/truck (RICOS Co. Ltd.) | Apache-2.0 | robust meshing and nearest-parameter fallback in booleans; degenerate intersection-curve rejection; face and edge history of booleans; trace macro; corner choice at vertices several intersection curves end on; reuse of an operand's meshes (vendor/README.md) | | vendor/truck-geometry | truck-geometry 0.5.0, https://github.com/ricosjp/truck (RICOS Co. Ltd.) | Apache-2.0 | intersection curves divided from their neighbours' surface parameters; surface second derivatives (vendor/README.md) | | vendor/matext4cgmath | matext4cgmath 0.1.0, https://github.com/ricosjp/matext4cgmath (RICOS Co. Ltd.) | Apache-2.0 | root refinement stops after 100 Newton steps (vendor/README.md) | diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 063ce5489..e8be71340 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -55,6 +55,8 @@ pub struct ModelBody { /// [`Body::retained_bytes`] of `body`, measured when a feature made or changed it (0: not /// measured), so the evaluation cache's budget does not walk every body after every feature. bytes: usize, + /// In a world state: the [`ModelBody::geometry_key`] of the model body this one places (0: none). + source_key: u64, } impl ModelBody { @@ -76,8 +78,24 @@ impl ModelBody { transferred: false, imported: None, bytes: 0, + source_key: 0, } } + + /// Identity of this body's geometry where it stands: the same for a body evaluated or + /// placed again from the same inputs at the same place, so work measured on it can be + /// reused (none for a body the evaluation cache does not key). + pub fn geometry_key(&self) -> Option { + use std::hash::{Hash, Hasher}; + let key = if self.key != 0 { self.key } else { self.source_key }; + if key == 0 { + return None; + } + let mut h = std::collections::hash_map::DefaultHasher::new(); + key.hash(&mut h); + self.source_transform.iter().flatten().for_each(|v| v.to_bits().hash(&mut h)); + Some(h.finish()) + } pub fn definition_name(&self) -> &str { self.source_name.as_deref().unwrap_or(&self.name) } @@ -5843,6 +5861,8 @@ pub fn world_state_reusing(doc: &Document, st: &ModelState, placed_before: &mut }; // World states keep their previous display-only evaluation-key semantics. placed.key = 0; + // With the model body's own frame, so its place is told apart from the placement's. + placed.source_key = b.geometry_key().unwrap_or(0); placed.source_name = Some(b.definition_name().to_string()); placed.source_transform = crate::mat_mul(&bm, &b.source_transform); placed.component = comp; @@ -5951,6 +5971,8 @@ mod world_placement_cache_tests { assert!(Arc::ptr_eq(&source.mesh, &first.mesh), "unchanged geometry must retain the shared display mesh cell"); assert_eq!(first.key, 0); assert_eq!(placed.key, 0); + // Each placement has its own geometry identity, for work measured on it. + assert!(first.geometry_key().is_some() && first.geometry_key() != placed.geometry_key()); assert!(!Arc::ptr_eq(&source.mesh, &placed.mesh), "a transformed mesh cannot be reused without mapping coordinates"); assert_eq!(first.source_name.as_deref(), Some("Block")); assert_eq!(placed.source_name.as_deref(), Some("Block")); diff --git a/crates/engine/src/cmd/clearance.rs b/crates/engine/src/cmd/clearance.rs index 14356d0c3..97cf6d13a 100644 --- a/crates/engine/src/cmd/clearance.rs +++ b/crates/engine/src/cmd/clearance.rs @@ -3,7 +3,8 @@ //! by bounding boxes grown by the clearance, then by the bodies' meshes (which lie within their //! chord tolerance of the faces); distances are measured on the exact faces and edges //! ([`solidcraft_kernel::body_distance`]) and overlaps by intersecting the bodies. The pairs -//! that are left run in parallel. +//! that are left run in parallel. A pair whose bodies have not changed or moved since a call +//! with the same settings measured it is not measured again ([`PairCache`]). use std::collections::{BTreeMap, HashMap}; use std::sync::Arc; @@ -25,7 +26,7 @@ pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("inspect.clearance", "C below it is contact, 0) → overlaps: [{a, b, volume_mm3, area_mm2, bbox, center}]; near: [{a, b, distance_mm, from, to, overlap_mm3?: \ a contact's shared volume below min_volume, exact?: false when measured on the meshes}], nearest by body (the same for pairs that overlap: 0); \ nearest: {body: [{body, distance_mm}]}; unchecked: [{a, b, reason}] (pairs whose overlap could not be worked out); pairs_checked; \ - pairs_pruned (ruled out by their boxes); ms. Distances are measured on the exact faces and edges, the meshes only rule pairs out", + pairs_reused (of those, measured by an earlier call: neither body changed or moved since); pairs_pruned (ruled out by their boxes); ms. Distances are measured on the exact faces and edges, the meshes only rule pairs out", )]; /// Most bodies one call takes. @@ -44,8 +45,17 @@ enum SkipWithin { Component, } -/// What one pair came to. +/// Most pairs [`PairCache`] keeps; it starts over when full. +const MAX_CACHED: usize = 2 * MAX_PAIRS; + +/// Pairs measured before, by the two bodies' geometry where they stood +/// ([`solidcraft_doc::ModelBody::geometry_key`]) and the settings that shape the result +/// (clearance, smallest overlap, tolerance). #[derive(Default)] +pub(crate) struct PairCache(HashMap<(u64, u64, [u64; 3]), PairResult>); + +/// What one pair came to. +#[derive(Clone, Default)] struct PairResult { /// Shared volume, area, box and centre. overlap: Option<(f64, f64, Aabb3, solidcraft_geom::Vec3)>, @@ -152,20 +162,40 @@ fn clearance(s: &mut Session, p: &Value) -> Result { } out }; - let shapes: Vec> = (0..n) + // The distance shapes are made only for bodies a pair or a nearest list measures; the boxes + // come from the meshes, grown by the chord tolerance as a shape's are. + let shapes: Vec>> = (0..n).map(|_| std::sync::OnceLock::new()).collect(); + let shape = |i: usize| { + shapes + .get(i)? + .get_or_init(|| match (solid.get(i), meshes.get(i).and_then(Option::as_ref)) { + (Some(b), Some(m)) if flag(&used, i) => Some(DistanceShape::new(&b.body, m, b.display_tol())), + _ => None, + }) + .as_ref() + }; + let boxes: Vec = (0..n) .map(|i| match (solid.get(i), meshes.get(i).and_then(Option::as_ref)) { - (Some(b), Some(m)) if flag(&used, i) => Some(DistanceShape::new(&b.body, m, b.display_tol())), - _ => None, + (Some(b), Some(m)) if flag(&used, i) => { + // Over the triangles with finite corners, as a shape's set of them is. + let mut bx = Aabb3::EMPTY; + for p in m.triangles.iter().filter_map(|t| m.tri(t)).filter(|p| p.iter().all(|v| v.is_finite())) { + p.into_iter().for_each(|v| bx.add(v)); + } + let chord = b.display_tol(); + let g = solidcraft_geom::Vec3::new(1.0, 1.0, 1.0) * if chord.is_finite() && chord > 0.0 { chord } else { 0.0 }; + if bx.is_empty() { bx } else { Aabb3 { min: bx.min - g, max: bx.max + g } } + } + _ => Aabb3::EMPTY, }) .collect(); - let shape = |i: usize| shapes.get(i).and_then(Option::as_ref); - let boxes: Vec = (0..n).map(|i| shape(i).map_or(Aabb3::EMPTY, DistanceShape::bounds)).collect(); // Pairs whose boxes, grown by half the clearance each, meet. let half = solidcraft_geom::Vec3::new(1.0, 1.0, 1.0) * (gap / 2.0); let grown: Vec = boxes.iter().map(|b| if b.is_empty() { *b } else { Aabb3 { min: b.min - half, max: b.max + half } }).collect(); let (close, truncated) = super::joints::overlapping_pairs(&grown, MAX_PAIRS); - let close: Vec<(usize, usize)> = close.into_iter().filter(|&(i, j)| allowed(i, j) && shape(i).is_some() && shape(j).is_some()).collect(); + let has_mesh = |i: usize| meshes.get(i).is_some_and(Option::is_some); + let close: Vec<(usize, usize)> = close.into_iter().filter(|&(i, j)| allowed(i, j) && has_mesh(i) && has_mesh(j)).collect(); let mut total = 0usize; for i in 0..n { for j in i + 1..n { @@ -175,11 +205,45 @@ fn clearance(s: &mut Session, p: &Value) -> Result { } } - let results = solidcraft_kernel::map_with_local_pools(&close, usize::MAX, |&(i, j)| { + // Pairs measured before come from the cache; the rest are measured and kept. + let settings = [gap.to_bits(), min_volume.to_bits(), tolerance.to_bits()]; + let cache_key = |i: usize, j: usize| Some((solid.get(i)?.geometry_key()?, solid.get(j)?.geometry_key()?, settings)); + let mut results: Vec>> = { + let cache = s.clearance_cache.lock().ok(); + close.iter().map(|&(i, j)| cache.as_ref().and_then(|c| c.0.get(&cache_key(i, j)?)).cloned().map(Ok)).collect() + }; + let todo: Vec = (0..close.len()).filter(|&k| results.get(k).is_some_and(Option::is_none)).collect(); + let reused = close.len() - todo.len(); + // A body in many pairs is cut down to each pair's region from the same mesh of it. + let kept: Vec>> = (0..n).map(|_| std::sync::OnceLock::new()).collect(); + let kept_body = |i: usize| kept.get(i)?.get_or_init(|| solid.get(i).map(|b| b.body.keeping_meshes())).as_ref(); + let measured = solidcraft_kernel::map_with_local_pools(&todo, usize::MAX, |&k| { + let Some(&(i, j)) = close.get(k) else { return Ok(PairResult::default()) }; let (Some(a), Some(b)) = (shape(i), shape(j)) else { return Ok(PairResult::default()) }; let (Some(ba), Some(bb)) = (solid.get(i), solid.get(j)) else { return Ok(PairResult::default()) }; - Ok(measure_pair(ba, a, bb, b, gap, min_volume, tolerance)) + let (Some(ka), Some(kb)) = (kept_body(i), kept_body(j)) else { return Ok(PairResult::default()) }; + Ok(measure_pair((ba, ka), a, (bb, kb), b, gap, min_volume, tolerance)) }); + if let Ok(mut cache) = s.clearance_cache.lock() { + for (&k, r) in todo.iter().zip(&measured) { + // A pair that could not be worked out is tried again next time. + let (Ok(r), Some(&(i, j))) = (r, close.get(k)) else { continue }; + if r.unchecked.is_some() { + continue; + } + let Some(key) = cache_key(i, j) else { continue }; + if cache.0.len() >= MAX_CACHED { + cache.0.clear(); + } + cache.0.insert(key, r.clone()); + } + } + for (k, r) in todo.into_iter().zip(measured) { + if let Some(slot) = results.get_mut(k) { + *slot = Some(r); + } + } + let results = results.into_iter().map(|r| r.unwrap_or_else(|| Ok(PairResult::default()))); let mut known: HashMap<(usize, usize), f64> = HashMap::new(); let (mut overlaps, mut near, mut unchecked) = (Vec::new(), Vec::new(), Vec::new()); @@ -240,6 +304,7 @@ fn clearance(s: &mut Session, p: &Value) -> Result { "unchecked": unchecked, "bodies": subjects.len(), "pairs_checked": close.len(), + "pairs_reused": reused, "pairs_pruned": total.saturating_sub(close.len()), "truncated": truncated > 0, "ms": started.elapsed().as_secs_f64() * 1000.0, @@ -249,9 +314,9 @@ fn clearance(s: &mut Session, p: &Value) -> Result { /// One pair: its overlap when the meshes meet or one holds the other, otherwise its distance /// when it may be closer than `gap`. fn measure_pair( - ba: &solidcraft_doc::ModelBody, + (ba, ka): (&solidcraft_doc::ModelBody, &solidcraft_kernel::Body), a: &DistanceShape, - bb: &solidcraft_doc::ModelBody, + (bb, kb): (&solidcraft_doc::ModelBody, &solidcraft_kernel::Body), b: &DistanceShape, gap: f64, min_volume: f64, @@ -275,7 +340,7 @@ fn measure_pair( if touching || holds(ba, bb) || holds(bb, ba) { // A pair whose shared part can't be worked out is reported, not passed as clear. let region = shared_region(a, b); - let (ca, cb) = (clipped(&ba.body, region), clipped(&bb.body, region)); + let (ca, cb) = (clipped(ka, region), clipped(kb, region)); let (shared, report) = solidcraft_kernel::capture_boolean_diagnostics(|| { solidcraft_kernel::boolean(ca.as_ref().unwrap_or(&ba.body), cb.as_ref().unwrap_or(&bb.body), solidcraft_kernel::BoolOp::Intersect) }); diff --git a/crates/engine/src/cmd/clearance_tests.rs b/crates/engine/src/cmd/clearance_tests.rs index 57c25f9ed..a7399ace3 100644 --- a/crates/engine/src/cmd/clearance_tests.rs +++ b/crates/engine/src/cmd/clearance_tests.rs @@ -252,6 +252,59 @@ fn a_small_gap_past_a_corner_is_not_contact() { } } +/// A second call measures only the pairs with a body that changed or moved since the first. +#[test] +fn pairs_whose_bodies_did_not_change_or_move_are_not_measured_again() { + let mut s = Session::default(); + run(&mut s, "component.create", json!({"name": "Bought"})); + cube(&mut s, "Housing", 10.0, [0.0, 0.0, 0.0]); + cube(&mut s, "Insert", 4.0, [8.0, 3.0, 3.0]); + run(&mut s, "component.activate", json!({"component": "root"})); + let bracket = run(&mut s, "component.create", json!({"name": "Bracket"}))["component"].as_u64().unwrap(); + cube(&mut s, "Plate", 10.0, [-9.5, 0.0, 0.0]); + let settings = json!({"clearance": 1}); + let first = run(&mut s, "inspect.clearance", settings.clone()); + assert_eq!((first["pairs_checked"].as_u64(), first["pairs_reused"].as_u64()), (Some(2), Some(0)), "{first}"); + let again = run(&mut s, "inspect.clearance", settings.clone()); + assert_eq!(again["pairs_reused"], 2, "{again}"); + for k in ["overlaps", "near", "unchecked"] { + assert_eq!(again[k], first[k], "{k}"); + } + // Other settings are measured afresh. + assert_eq!(run(&mut s, "inspect.clearance", json!({"clearance": 2}))["pairs_reused"], 0); + // The bracket moves 1 mm away: only its pair is measured again, and it is now near, not over. + let o = s.doc.occurrence_of(bracket).unwrap().id; + run(&mut s, "occurrence.move", json!({"occurrence": o, "translate": [-1, 0, 0], "capture": true})); + let moved = run(&mut s, "inspect.clearance", settings.clone()); + assert_eq!((moved["pairs_checked"].as_u64(), moved["pairs_reused"].as_u64()), (Some(2), Some(1)), "{moved}"); + let overlaps: Vec<[String; 2]> = moved["overlaps"].as_array().into_iter().flatten().map(pair).collect(); + assert_eq!(overlaps, vec![["Housing".to_string(), "Insert".to_string()]], "{moved}"); + assert!((f(&moved["near"][0]["distance_mm"]) - 0.5).abs() < 1e-6, "{moved}"); + let still = run(&mut s, "inspect.clearance", settings); + assert_eq!(still["pairs_reused"], 2, "nothing changed since: {still}"); + assert_eq!(still["near"], moved["near"]); +} + +/// A body rebuilt with other geometry is measured again, not taken from an earlier call. +#[test] +fn a_body_that_changed_shape_is_measured_again() { + let mut s = Session::default(); + cube(&mut s, "A", 10.0, [0.0, 0.0, 0.0]); + cube(&mut s, "B", 10.0, [10.5, 0.0, 0.0]); + let r = run(&mut s, "inspect.clearance", json!({"clearance": 1})); + assert!((f(&r["near"][0]["distance_mm"]) - 0.5).abs() < 1e-6, "{r}"); + let list = run(&mut s, "parameters.list", json!({"filter": "feature"})); + let length = list["parameters"][0]["name"].as_str().unwrap().to_string(); + run(&mut s, "parameters.change", json!({"name": length, "expression": "10.2 mm"})); + let r = run(&mut s, "inspect.clearance", json!({"clearance": 1})); + assert_eq!(r["pairs_reused"], 0, "{r}"); + assert!((f(&r["near"][0]["distance_mm"]) - 0.3).abs() < 1e-6, "{r}"); + // Set back, the first shape's result is the right one again. + run(&mut s, "parameters.change", json!({"name": length, "expression": "10 mm"})); + let r = run(&mut s, "inspect.clearance", json!({"clearance": 1})); + assert!((f(&r["near"][0]["distance_mm"]) - 0.5).abs() < 1e-6, "{r}"); +} + /// The shared volume is checked against the bodies and their union: two 10 mm cubes sharing a /// 3 mm corner cube agree at 27 mm³, and a shared part read as three times that (as a mirrored /// pair once was) does not. diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index c5a1dc0d5..f9673ecf3 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -22,7 +22,7 @@ macro_rules! planned { mod bom; mod browser; -mod clearance; +pub(crate) mod clearance; mod clipboard; mod compare; mod component; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 889509b88..8ba80b51f 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -232,6 +232,9 @@ pub struct Session { world_cache: std::sync::Mutex>, occurrence_visibility_cache: std::sync::Mutex>, removed_later_cache: std::sync::Mutex>, + /// Pairs `inspect.clearance` measured, by the bodies' geometry where they stood (shared with + /// scratch copies): a body that did not change or move is not measured again. + clearance_cache: std::sync::Arc>, /// Features copied with `timeline.copy` (pasted by `timeline.paste`). pub clipboard: Vec, /// Sketch geometry copied with `sketch.copy` (pasted by `sketch.paste`). @@ -370,6 +373,7 @@ impl Session { world_cache: Default::default(), occurrence_visibility_cache: Default::default(), removed_later_cache: Default::default(), + clearance_cache: Default::default(), clipboard: Vec::new(), sketch_clipboard: None, section: None, @@ -841,6 +845,7 @@ impl Session { world_cache: std::sync::Mutex::new(self.world_cache.lock().ok().and_then(|cache| cache.clone())), occurrence_visibility_cache: Default::default(), removed_later_cache: Default::default(), + clearance_cache: self.clearance_cache.clone(), clipboard: self.clipboard.clone(), sketch_clipboard: self.sketch_clipboard.clone(), section: None, diff --git a/crates/kernel/src/body.rs b/crates/kernel/src/body.rs index feea4c25a..4e0946b15 100644 --- a/crates/kernel/src/body.rs +++ b/crates/kernel/src/body.rs @@ -50,8 +50,24 @@ pub struct Body { /// part is tessellated once rather than once per instance. Dropped by anything that changes /// what the body shows (its geometry is never changed in place). pub(crate) display_of: Option, [[f64; 4]; 4])>>, + /// Meshes of this solid kept for reuse, set by [`Body::keeping_meshes`]: a check that + /// intersects one large body with many small ones meshes it at the same tolerance each time. + pub(crate) meshes: Option>, } +/// The meshes made of one solid (see [`Body::keeping_meshes`]), by tolerance, angle and +/// refinement. They answer only for that solid: a copy whose solid was replaced makes its own. +#[derive(Debug)] +pub(crate) struct MeshMemo { + solid: std::sync::Arc, + made: std::sync::Mutex)>>, + /// The meshes a boolean makes of the solid's shells, by tolerance. + shells: std::sync::Mutex>)>>, +} + +/// Meshes a [`MeshMemo`] keeps at most (the oldest goes first). +const MEMO_MESHES: usize = 4; + /// The display mesh of a body that several placed copies show (see `Body::display_of`): the /// body, and its mesh once made. #[derive(Debug)] @@ -62,7 +78,7 @@ pub(crate) struct SharedDisplay { impl SharedDisplay { pub(crate) fn new(original: Body) -> Self { - SharedDisplay { original: Body { display_of: None, ..original }, mesh: std::sync::OnceLock::new() } + SharedDisplay { original: Body { display_of: None, meshes: None, ..original }, mesh: std::sync::OnceLock::new() } } } @@ -593,6 +609,7 @@ impl Body { regularization_protected: false, history: None, display_of: None, + meshes: None, }) } @@ -631,6 +648,7 @@ impl Body { regularization_protected: false, history: None, display_of: None, + meshes: None, }) } @@ -1073,7 +1091,45 @@ impl Body { /// [`Body::tessellate_with`] in which no facet turns more than `angle` radians either /// (infinite: the chord tolerance alone). fn tessellate_within(&self, tol: f64, angle: f64, refine: bool) -> Result { - crate::profile::timed(crate::profile::Kind::Tessellate, || self.tessellate_within_untimed(tol, angle, refine)) + let mesh = || crate::profile::timed(crate::profile::Kind::Tessellate, || self.tessellate_within_untimed(tol, angle, refine)); + let memo = self.meshes.as_ref().filter(|m| std::sync::Arc::ptr_eq(&m.solid, &self.solid)); + // Held while meshing: threads asking for the same mesh wait for it rather than make it too. + let Some(Ok(mut made)) = memo.map(|m| m.made.lock()) else { return mesh() }; + let key = (tol.to_bits(), angle.to_bits(), refine); + if let Some((_, m)) = made.iter().find(|(k, _)| *k == key) { + return Ok(Mesh::clone(m)); + } + let m = mesh()?; + if made.len() >= MEMO_MESHES { + made.remove(0); + } + made.push((key, std::sync::Arc::new(m.clone()))); + Ok(m) + } + + /// A copy of this body that keeps the meshes made of it for reuse, for as long as the copy + /// (or a clone of it) lives: for many operations on one large body at the same tolerance, + /// such as cutting it down to the region of each of many contacts. + pub fn keeping_meshes(&self) -> Body { + let (made, shells) = (std::sync::Mutex::new(Vec::new()), std::sync::Mutex::new(Vec::new())); + Body { meshes: Some(std::sync::Arc::new(MeshMemo { solid: self.solid.clone(), made, shells })), ..self.clone() } + } + + /// The meshes of this body's shells a boolean at `tol` makes, when the body keeps its meshes + /// ([`Body::keeping_meshes`]); `None` otherwise. + pub(crate) fn boolean_meshes(&self, tol: f64) -> Option>> { + let memo = self.meshes.as_ref().filter(|m| std::sync::Arc::ptr_eq(&m.solid, &self.solid))?; + // Held while meshing, as in `tessellate_within`. + let mut shells = memo.shells.lock().ok()?; + if let Some((_, m)) = shells.iter().find(|(k, _)| *k == tol.to_bits()) { + return Some(m.clone()); + } + let made = std::sync::Arc::new(guard("boolean meshes", || Ok(truck_shapeops::meshes(&*self.solid, tol))).ok()?); + if shells.len() >= MEMO_MESHES { + shells.remove(0); + } + shells.push((tol.to_bits(), made.clone())); + Some(made) } fn tessellate_within_untimed(&self, tol: f64, angle: f64, refine: bool) -> Result { @@ -1710,6 +1766,10 @@ impl Body { #[path = "body_lump_tests.rs"] mod lump_tests; +#[cfg(test)] +#[path = "mesh_memo_tests.rs"] +mod mesh_memo_tests; + #[cfg(test)] #[path = "refine_cache_tests.rs"] mod refine_cache_tests; diff --git a/crates/kernel/src/mesh_memo_tests.rs b/crates/kernel/src/mesh_memo_tests.rs new file mode 100644 index 000000000..915b1dcaf --- /dev/null +++ b/crates/kernel/src/mesh_memo_tests.rs @@ -0,0 +1,65 @@ +use super::*; +use crate::{BoolOp, boolean, box_solid, cylinder, measure}; + +/// A plate with a row of holes and a rounded rim along one edge (so that it is no prism the 2D +/// route would take), as a large body many small regions are cut from. +fn plate() -> Body { + let rim = cylinder(Vec3::new(0.0, 0.0, 3.0), Vec3::X, 4.0, 300.0).unwrap(); + let mut plate = box_solid(Vec3::ZERO, Vec3::new(300.0, 200.0, 3.0)).unwrap(); + plate = boolean(&plate, &rim, BoolOp::Union).unwrap().unwrap(); + for k in 0..12 { + let hole = cylinder(Vec3::new(20.0 + 22.0 * k as f64, 100.0, -1.0), Vec3::Z, 2.6, 5.0).unwrap(); + plate = boolean(&plate, &hole, BoolOp::Cut).unwrap().unwrap(); + } + plate +} + +/// Regions cut from a body that keeps its meshes come out as from the body itself, to the bit, +/// and the body is meshed once for all of them. +#[test] +fn regions_cut_from_a_body_keeping_its_meshes_are_unchanged() { + let plate = plate(); + let kept = plate.keeping_meshes(); + for k in [0.0, 3.0, 7.0] { + let x = 20.0 + 22.0 * k; + let region = box_solid(Vec3::new(x - 8.0, 92.0, -2.0), Vec3::new(x + 8.0, 108.0, 5.0)).unwrap(); + let want = boolean(&plate, ®ion, BoolOp::Intersect).unwrap().unwrap(); + let got = boolean(&kept, ®ion, BoolOp::Intersect).unwrap().unwrap(); + let (w, g) = (measure(&want).unwrap(), measure(&got).unwrap()); + assert_eq!(got.face_count(), want.face_count(), "region at {x}"); + assert_eq!(g.volume.to_bits(), w.volume.to_bits(), "region at {x}"); + let cut = boolean(&kept, ®ion, BoolOp::Cut).unwrap().unwrap(); + assert_eq!( + measure(&cut).unwrap().volume.to_bits(), + measure(&boolean(&plate, ®ion, BoolOp::Cut).unwrap().unwrap()).unwrap().volume.to_bits() + ); + } + let memo = kept.meshes.as_ref().unwrap(); + assert_eq!(memo.shells.lock().unwrap().len(), 1, "one tolerance, one meshing"); + assert!(!memo.made.lock().unwrap().is_empty()); + // A mesh from the memo is the mesh made afresh. + let (a, b) = (kept.tessellate_with(0.05, true).unwrap(), plate.tessellate_with(0.05, true).unwrap()); + let (a2, _) = (kept.tessellate_with(0.05, true).unwrap(), ()); + for m in [&a, &a2] { + assert_eq!(m.triangles, b.triangles); + assert!( + m.positions + .iter() + .zip(&b.positions) + .all(|(p, q)| p.x.to_bits() == q.x.to_bits() && p.y.to_bits() == q.y.to_bits() && p.z.to_bits() == q.z.to_bits()) + ); + } +} + +/// A copy whose solid was replaced does not take meshes of the solid it replaced. +#[test] +fn a_copy_with_another_solid_makes_its_own_meshes() { + let kept = plate().keeping_meshes(); + let other = box_solid(Vec3::ZERO, Vec3::new(10.0, 10.0, 10.0)).unwrap(); + let mut swapped = kept.clone(); + swapped.solid = other.solid.clone(); + let _ = kept.tessellate_with(0.5, true).unwrap(); + let m = swapped.tessellate_with(0.5, true).unwrap(); + assert_eq!(m.triangles.len(), other.tessellate_with(0.5, true).unwrap().triangles.len()); + assert!(swapped.boolean_meshes(0.01).is_none()); +} diff --git a/crates/kernel/src/meshbody.rs b/crates/kernel/src/meshbody.rs index 78b76a2ae..170c0273c 100644 --- a/crates/kernel/src/meshbody.rs +++ b/crates/kernel/src/meshbody.rs @@ -113,6 +113,7 @@ pub fn mesh_body(positions: &[Vec3], triangles: &[[u32; 3]]) -> Result { face_sources: None, history: None, display_of: None, + meshes: None, regularization_protected: false, }) } @@ -210,6 +211,7 @@ impl Body { face_sources: None, history: None, display_of: None, + meshes: None, regularization_protected: self.regularization_protected, }) } diff --git a/crates/kernel/src/native.rs b/crates/kernel/src/native.rs index 9fba05180..3afaf3bee 100644 --- a/crates/kernel/src/native.rs +++ b/crates/kernel/src/native.rs @@ -94,6 +94,7 @@ pub fn decode_native_body(bytes: &[u8]) -> Result { face_sources: None, history: None, display_of: None, + meshes: None, regularization_protected: false, }; metadata::apply(&mut body, saved.metadata)?; diff --git a/crates/kernel/src/ops.rs b/crates/kernel/src/ops.rs index 10e7fc481..9e0d51578 100644 --- a/crates/kernel/src/ops.rs +++ b/crates/kernel/src/ops.rs @@ -1515,13 +1515,19 @@ pub(crate) fn truck_boolean(a: &Body, b: &Body, op: BoolOp, shift: Option truck_shapeops::and_with_history_meshed(sa, m, sb, tol), + None => truck_shapeops::and_with_history(sa, sb, tol), + }; let res = match op { BoolOp::Union => truck_shapeops::or_with_history(&sa, &sb, tol), BoolOp::Cut => { sb.not(); - truck_shapeops::and_with_history(&sa, &sb, tol) + and(&sa, &sb) } - BoolOp::Intersect => truck_shapeops::and_with_history(&sa, &sb, tol), + BoolOp::Intersect => and(&sa, &sb), }; let (s, h) = res.ok_or_else(|| KernelError::Failed("no result".into()))?; let h = h.and_then(|h| recorded::shapeops(&h, &sb, tool_edges.as_ref())); diff --git a/crates/kernel/src/outline.rs b/crates/kernel/src/outline.rs index afdd3635a..66c73ace4 100644 --- a/crates/kernel/src/outline.rs +++ b/crates/kernel/src/outline.rs @@ -513,6 +513,7 @@ fn divided(body: &Body, faces: &[usize], other: &[(mt::Edge, Piece)], fr: &Frame history: None, regularization_protected: true, display_of: None, + meshes: None, }; Ok(Some(record::rebuilt_body(split, &[&body.solid], &rec))) } diff --git a/crates/kernel/src/splitface.rs b/crates/kernel/src/splitface.rs index cab1c2110..9e5194c16 100644 --- a/crates/kernel/src/splitface.rs +++ b/crates/kernel/src/splitface.rs @@ -645,6 +645,7 @@ pub(crate) fn split_edges_at(body: &Body, points: &[Vec3]) -> Result { face_sources: None, history: None, display_of: None, + meshes: None, regularization_protected: true, }; Ok(crate::record::rebuilt_body(split, &[&body.solid], &rec)) @@ -1180,6 +1181,7 @@ pub(crate) fn split_any(body: &Body, faces: &[usize], tool: &SplitTool) -> Resul face_sources: None, history: None, display_of: None, + meshes: None, regularization_protected: true, }; Ok((crate::record::rebuilt_body(split, &[&body.solid], &imp.rec), imp)) diff --git a/crates/kernel/src/surfaces.rs b/crates/kernel/src/surfaces.rs index 6031f4859..e625b775f 100644 --- a/crates/kernel/src/surfaces.rs +++ b/crates/kernel/src/surfaces.rs @@ -42,6 +42,7 @@ fn surface_of(shell: mt::Shell) -> Body { face_sources: None, history: None, display_of: None, + meshes: None, regularization_protected: false, } } diff --git a/vendor/README.md b/vendor/README.md index e3a7ff2fb..25ac34228 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -41,6 +41,10 @@ Changes: a moved vertex), across the passes that fold in the operands' extra shells. `and` / `or` are wrappers that drop the history; the `*_with_history` forms return the same solid with the history as an `Option` (`None` where a face or edge went unrecorded). +- `transversal/integrate/mod.rs`: `meshes` and `and_with_history_meshed` take the first + operand's shell meshes made beforehand (copied for each use, since the loops stores cut their + edges): a large body cut down to the regions of many small ones is meshed once, which was most + of each operation's time. ## truck-geometry 0.5.0 (Apache-2.0, © RICOS Co. Ltd., https://github.com/ricosjp/truck) diff --git a/vendor/truck-shapeops/src/lib.rs b/vendor/truck-shapeops/src/lib.rs index 753309c67..9f5b99905 100644 --- a/vendor/truck-shapeops/src/lib.rs +++ b/vendor/truck-shapeops/src/lib.rs @@ -34,8 +34,8 @@ mod healing; pub use healing::{RobustSplitClosedEdgesAndFaces, SplitClosedEdgesAndFaces}; mod transversal; pub use transversal::{ - and, and_with_history, or, or_with_history, EdgeOrigin, FaceIndex, FaceOrigin, History, ShapeOpsCurve, - ShapeOpsSurface, + and, and_with_history, and_with_history_meshed, meshes, or, or_with_history, EdgeOrigin, FaceIndex, FaceOrigin, + History, MeshedShell, ShapeOpsCurve, ShapeOpsSurface, }; // SolidCraft: exercised by kernel regressions in the workspace CI. #[doc(hidden)] diff --git a/vendor/truck-shapeops/src/transversal/integrate/mod.rs b/vendor/truck-shapeops/src/transversal/integrate/mod.rs index dd45a8a40..d0f9c750b 100644 --- a/vendor/truck-shapeops/src/transversal/integrate/mod.rs +++ b/vendor/truck-shapeops/src/transversal/integrate/mod.rs @@ -50,16 +50,31 @@ impl ShapeOpsCurve for C where C: ParametricCurve3D { } +/// SolidCraft: the meshed form of a shell that a set operation works on (see [`meshes`]). +pub type MeshedShell = Shell, Option>; + +/// SolidCraft: the meshes of `solid`'s shells at `tol`, as a set operation makes them: an +/// operand used in many operations at one tolerance (a large body cut down to many small +/// regions) is meshed once and handed to [`and_with_history_meshed`], which is most of what +/// such an operation costs. They fit any copy of `solid` with its faces in the same order. +pub fn meshes, S: ShapeOpsSurface>(solid: &Solid, tol: f64) -> Vec { + solid.boundaries().iter().map(|shell| shell.robust_triangulation(tol)).collect() +} + fn process_one_pair_of_shells, S: ShapeOpsSurface>( shell0: &Shell, + meshed0: Option<&MeshedShell>, shell1: &Shell, tol: f64, lineage: &mut Lineage, ) -> Option<[Shell; 2]> { nonpositive_tolerance!(tol); // SolidCraft: robust meshing (boundaries from earlier operations lie on surfaces only - // within tolerance). - let poly_shell0 = shell0.robust_triangulation(tol); + // within tolerance). A mesh made before is copied: the loops stores cut its edges. + let poly_shell0 = match meshed0 { + Some(m) if m.len() == shell0.len() => m.mapped(|p| *p, |c| c.clone(), |s| s.clone()), + _ => shell0.robust_triangulation(tol), + }; let poly_shell1 = shell1.robust_triangulation(tol); let loops_store::LoopsStoreQuadruple { geom_loops_store0: loops_store0, @@ -113,7 +128,7 @@ pub fn and, S: ShapeOpsSurface>( solid1: &Solid, tol: f64, ) -> Option> { - boolean(solid0, solid1, tol, |[and, _]| and).map(|(solid, _)| solid) + boolean(solid0, None, solid1, tol, |[and, _]| and).map(|(solid, _)| solid) } /// OR operation between two solids. @@ -122,7 +137,7 @@ pub fn or, S: ShapeOpsSurface>( solid1: &Solid, tol: f64, ) -> Option> { - boolean(solid0, solid1, tol, |[_, or]| or).map(|(solid, _)| solid) + boolean(solid0, None, solid1, tol, |[_, or]| or).map(|(solid, _)| solid) } /// SolidCraft: AND operation between two solids, with where each face and edge of the result @@ -134,7 +149,18 @@ pub fn and_with_history, S: ShapeOpsSurface>( solid1: &Solid, tol: f64, ) -> Option<(Solid, Option)> { - boolean(solid0, solid1, tol, |[and, _]| and) + boolean(solid0, None, solid1, tol, |[and, _]| and) +} + +/// SolidCraft: [`and_with_history`] with `solid0` meshed already ([`meshes`] of it, or of a +/// copy of it, at `tol`): the same result. +pub fn and_with_history_meshed, S: ShapeOpsSurface>( + solid0: &Solid, + meshed0: &[MeshedShell], + solid1: &Solid, + tol: f64, +) -> Option<(Solid, Option)> { + boolean(solid0, Some(meshed0), solid1, tol, |[and, _]| and) } /// SolidCraft: OR operation between two solids, with where each face and edge of the result @@ -146,7 +172,7 @@ pub fn or_with_history, S: ShapeOpsSurface>( solid1: &Solid, tol: f64, ) -> Option<(Solid, Option)> { - boolean(solid0, solid1, tol, |[_, or]| or) + boolean(solid0, None, solid1, tol, |[_, or]| or) } /// Combines the operands' first shells, then folds in their other shells one at a time @@ -154,6 +180,7 @@ pub fn or_with_history, S: ShapeOpsSurface>( /// edge of the result was not recorded; the result stands without it. fn boolean, S: ShapeOpsSurface>( solid0: &Solid, + meshed0: Option<&[MeshedShell]>, solid1: &Solid, tol: f64, pick: fn([Shell; 2]) -> Shell, @@ -163,9 +190,10 @@ fn boolean, S: ShapeOpsSurface>( let mut iter1 = solid1.boundaries().iter(); let shell0 = iter0.next()?; let shell1 = iter1.next()?; - let mut shell = pick(crate::tr!(process_one_pair_of_shells(shell0, shell1, tol, &mut lineage), "first shells")); + let meshed0 = meshed0.filter(|m| m.len() == solid0.boundaries().len()).and_then(|m| m.first()); + let mut shell = pick(crate::tr!(process_one_pair_of_shells(shell0, meshed0, shell1, tol, &mut lineage), "first shells")); for other in iter0.chain(iter1) { - shell = pick(crate::tr!(process_one_pair_of_shells(&shell, other, tol, &mut lineage), "another shell")); + shell = pick(crate::tr!(process_one_pair_of_shells(&shell, None, other, tol, &mut lineage), "another shell")); } let solid = crate::tr!(Solid::try_new(components_in_order(&shell)).ok(), "result solid"); let history = lineage.history(&solid); diff --git a/vendor/truck-shapeops/src/transversal/mod.rs b/vendor/truck-shapeops/src/transversal/mod.rs index 1778ad6ac..59a6f1ef4 100644 --- a/vendor/truck-shapeops/src/transversal/mod.rs +++ b/vendor/truck-shapeops/src/transversal/mod.rs @@ -9,4 +9,4 @@ pub use intersection_curve::IntersectionCurveWithParameters; mod loops_store; mod polyline_construction; pub use history::{EdgeOrigin, FaceIndex, FaceOrigin, History}; -pub use integrate::{and, and_with_history, or, or_with_history, ShapeOpsCurve, ShapeOpsSurface}; +pub use integrate::{and, and_with_history, and_with_history_meshed, meshes, or, or_with_history, MeshedShell, ShapeOpsCurve, ShapeOpsSurface}; From 80dcf9de7fd65fd263e3ab0d6f8b4d249c013a8c Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 19 Oct 2026 20:16:40 +0000 Subject: [PATCH 100/225] Regenerate THIRD-PARTY-LICENSES.txt and docs/features.md [skip ci] --- docs/features.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/docs/features.md b/docs/features.md index 2f53897d0..0480f1c31 100644 --- a/docs/features.md +++ b/docs/features.md @@ -242,6 +242,8 @@ SolidCraft's commands by area, generated by `cargo xtask features` from the comm | Insert Design | `component.insert_design` | SOLID › ASSEMBLE | | List Links | `component.links` | – | | List Components | `component.list` | – | +| Part Properties | `component.metadata` | – | +| Change Part Properties | `component.metadata.set` | – | | Move Bodies to Component | `component.move_bodies` | – | | Move Sketches to Component | `component.move_sketches` | – | | Paste New | `component.paste_new` | – | @@ -272,6 +274,7 @@ SolidCraft's commands by area, generated by `cargo xtask features` from the comm | Rigid Group | `joint.rigid_group` | SOLID › ASSEMBLE | | Screw | `joint.screw` | SOLID › ASSEMBLE | | Solve Joints | `joint.solve` | – | +| Sweep Joint | `joint.sweep` | – | ## Configurations @@ -373,6 +376,12 @@ SolidCraft's commands by area, generated by `cargo xtask features` from the comm | Appearance Library | `appearance.library` | – | | List Appearances | `appearance.list` | – | +## `assembly.*` + +| Command | Id | Toolbar | +|---|---|---| +| Bill of Materials | `assembly.bom` | SOLID › INSPECT | + ## `body.*` | Command | Id | Toolbar | From 983fbe2b1468af2ff7ca6113e278fb536f70c06c Mon Sep 17 00:00:00 2001 From: fkirill Date: Mon, 19 Oct 2026 23:34:50 +0300 Subject: [PATCH 101/225] Fix lip and groove on round objects (#2751) (#2790) Thanks @fkirill. --- crates/doc/src/eval_more.rs | 26 ++++-- crates/engine/src/cmd/plastic.rs | 52 +++++++++++ crates/kernel/src/lib.rs | 2 +- crates/kernel/src/lip.rs | 149 +++++++++++++++++++++---------- 4 files changed, 174 insertions(+), 55 deletions(-) diff --git a/crates/doc/src/eval_more.rs b/crates/doc/src/eval_more.rs index 3b4456480..4544df353 100644 --- a/crates/doc/src/eval_more.rs +++ b/crates/doc/src/eval_more.rs @@ -1877,16 +1877,24 @@ pub(super) fn plastic_eval(doc: &Document, vals: &BTreeMap, f: &F // The band along the chosen edge, inside the rim face. A groove's cutter reaches past // the edge into the free side (the cavity, or outside), so no wall coincides. let free = if *groove { bw } else { 0.0 }; - let band = if *outside { - Region2 { - outer: Loop2::polygon(&offset_left(&outer, -free)).ccw(), - holes: vec![Loop2::polygon(&offset_left(&outer, bw)).ccw().reversed()], - } + let (plane, band) = if let Ok(exact) = kernel::rim_band(&mb.body, face.0, bw, free, *outside) { + exact + } else if *outside { + ( + plane, + Region2 { + outer: Loop2::polygon(&offset_left(&outer, -free)).ccw(), + holes: vec![Loop2::polygon(&offset_left(&outer, bw)).ccw().reversed()], + }, + ) } else { - Region2 { - outer: Loop2::polygon(&offset_left(&inner, -bw)).ccw(), - holes: vec![Loop2::polygon(&offset_left(&inner, free)).ccw().reversed()], - } + ( + plane, + Region2 { + outer: Loop2::polygon(&offset_left(&inner, -bw)).ccw(), + holes: vec![Loop2::polygon(&offset_left(&inner, free)).ccw().reversed()], + }, + ) }; let delta = (h * 0.05).clamp(1e-3, 0.5); if *groove { diff --git a/crates/engine/src/cmd/plastic.rs b/crates/engine/src/cmd/plastic.rs index b60121391..6675dcdc0 100644 --- a/crates/engine/src/cmd/plastic.rs +++ b/crates/engine/src/cmd/plastic.rs @@ -338,6 +338,58 @@ mod tests { assert!(g.execute("plastic.lip", &json!({"face": [40, 25, 0], "width": 1, "height": 2})).is_err(), "a face without an inner edge"); } + #[test] + fn round_rim_lips_and_grooves_keep_curved_walls() { + for (obround, tilted) in [(false, false), (true, false), (true, true)] { + for outside in [false, true] { + for groove in [false, true] { + let mut s = Session::default(); + let plane = if tilted { + solidcraft_geom::Plane::new(Vec3::new(7., -3., 5.), Vec3::new(1., -1., 0.), Vec3::new(1., 1., -2.)).unwrap() + } else { + solidcraft_geom::Plane::XY + }; + if obround { + run(&mut s, "sketch.create", json!({"plane": plane, "name": "Rim"})); + run(&mut s, "sketch.slot.center_to_center", json!({"p0": [-20, 0], "p1": [20, 0], "width": 40})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"sketch": "Rim", "distance": 12, "body_name": "Case"})); + } else { + run(&mut s, "solid.cylinder", json!({"radius": 20, "height": 12, "body_name": "Case"})); + } + let top = plane.origin + plane.normal() * 12.0; + run(&mut s, "solid.shell", json!({"faces": [top], "thickness": 2})); + let before = volume(&mut s); + run( + &mut s, + "plastic.lip", + json!({"face": top + plane.y * 19.0, "width": 0.8, "height": 1.5, + "side": if outside { "outside" } else { "inside" }, "type": if groove { "groove" } else { "lip" }, "gap": 0.2}), + ); + let width = if groove { 1.0 } else { 0.8 }; + let area = if outside { PI * (400.0 - (20.0_f64 - width).powi(2)) } else { PI * ((18.0_f64 + width).powi(2) - 324.0) }; + let area = area + if obround { 80.0 * width } else { 0.0 }; + let want = before + if groove { -area * 1.7 } else { area * 1.5 }; + let check = |s: &Session| { + let st = s.model.state(); + let body = &st.body("Case").unwrap().body; + let m = solidcraft_kernel::measure(body).unwrap(); + assert!( + (m.volume - want).abs() < 0.1, + "obround={obround} tilted={tilted} outside={outside} groove={groove}: {} vs {want}", + m.volume + ); + assert!(m.faces < 32, "obround={obround} tilted={tilted} outside={outside} groove={groove}: polygonal walls: {m:?}"); + assert!(m.merged.face_types.get("cylinder").copied().unwrap_or(0) >= 3, "{m:?}"); + assert!(body.validity().is_empty()); + }; + check(&s); + check(&Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap())); + } + } + } + } + #[test] fn lip_on_a_face_that_is_not_a_rim_says_so() { // The Sample Plate's top face (#892): two holes through it and the boss standing on it. diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rs index ae37c3448..e55646f44 100644 --- a/crates/kernel/src/lib.rs +++ b/crates/kernel/src/lib.rs @@ -177,7 +177,7 @@ pub use fill::{PATCH_ANGLE_TOL_DEG, PatchReport, PatchSpec, patch_edges_crowned, pub use helix::{loft_to_point, sweep_helix, sweep_helix_mesh}; pub use iges_in::{MAX_IGES_BYTES, iges_import, iges_to_step}; pub use iges_out::iges_export_bodies; -pub use lip::raise_band; +pub use lip::{raise_band, rim_band}; pub use loft_blend::loft_blend; pub use matchsurf::{match_surface, seam_continuity}; pub use measure::{BodyMeasure, MassMeasure, measure, measure_mass}; diff --git a/crates/kernel/src/lip.rs b/crates/kernel/src/lip.rs index 599a65250..4c3e79b55 100644 --- a/crates/kernel/src/lip.rs +++ b/crates/kernel/src/lip.rs @@ -3,7 +3,7 @@ //! directly from the body's faces (the band's walls continue the walls below, which a boolean //! union can't join: their faces would coincide). -use solidcraft_geom::Vec3; +use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec3}; use truck_modeling::{self as mt, builder}; use crate::body::{Body, Solid, from_p3, p3, v3}; @@ -43,10 +43,12 @@ fn face_at(body: &Body, at: Vec3) -> Result<(usize, Vec3)> { if d > size * 1e-3 { return Err(fail("no face there")); } - let face = body.solid.face_iter().nth(f).ok_or_else(|| fail("face"))?; - let mt::Surface::Plane(pl) = face.oriented_surface() else { return Err(fail("the face must be planar")) }; - let n = pl.normal(); - Ok((f, Vec3::new(n.x, n.y, n.z).normalized().ok_or_else(|| fail("normal"))?)) + guard("rim face", || { + let face = body.solid.face_iter().nth(f).ok_or_else(|| fail("face"))?; + let mt::Surface::Plane(pl) = face.oriented_surface() else { return Err(fail("the face must be planar")) }; + let n = pl.normal(); + Ok((f, Vec3::new(n.x, n.y, n.z).normalized().ok_or_else(|| fail("normal"))?)) + }) } /// The face's loop moved `w` into the face (to the left of its edges, as a face's boundary has @@ -62,15 +64,18 @@ fn offset_loop(pieces: &[Piece], n: Vec3, w: f64, tol: f64) -> Result } Some(m) => { // Each point moves square to the arc (along its radius), to the left. - let (la, lm, lb) = - (left(p.a, m).ok_or_else(|| fail("arc"))?, left(p.a, p.b).ok_or_else(|| fail("arc"))?, left(m, p.b).ok_or_else(|| fail("arc"))?); + let lm = left(p.a, p.b).ok_or_else(|| fail("arc"))?; let c = circle_centre(p.a, m, p.b).ok_or_else(|| fail("arc"))?; - let radial = |q: Vec3, hint: Vec3| { - let r = (q - c).normalized().unwrap_or(hint); - if r.dot(hint) >= 0.0 { r } else { -r } - }; - let _ = (la, lb); - Piece { a: p.a + radial(p.a, lm) * w, b: p.b + radial(p.b, lm) * w, mid: Some(m + radial(m, lm) * w) } + let r = m.dist(c); + let shift = if (m - c).dot(lm) >= 0.0 { w } else { -w }; + if r + shift <= tol { + return Err(fail("the offset closes an arc")); + } + // Use one radial scale for the whole arc. At a semicircle's ends the + // radial is perpendicular to the chord's left, so its dot product cannot + // reliably choose the side independently at each end. + let moved = |q: Vec3| c + (q - c) * ((r + shift) / r); + Piece { a: moved(p.a), b: moved(p.b), mid: Some(moved(m)) } } }); } @@ -120,6 +125,85 @@ fn circle_centre(a: Vec3, m: Vec3, b: Vec3) -> Option { Some(a + (v.cross(w) * u.len2() + w.cross(u) * v.len2()) * (1.0 / d)) } +fn pieces(wire: &mt::Wire, size: f64) -> Result> { + wire.edge_iter() + .map(|e| { + let (a, b) = (from_p3(e.front().point()), from_p3(e.back().point())); + match crate::offset::arc_mid(e, size * 1e-6) { + Some(mid) => Ok(Piece { a, b, mid }), + None => Err(fail("edges must be lines or arcs")), + } + }) + .collect() +} + +/// Signed area ordering including arc midpoints: two semicircles have only two +/// vertices, whose polygon has zero area for both the inner and outer loops. +fn turn(wire: &mt::Wire, n: Vec3) -> f64 { + use mt::{BoundedCurve, ParametricCurve}; + let pts: Vec = wire + .edge_iter() + .flat_map(|e| { + let c = e.oriented_curve(); + let (a, b) = c.range_tuple(); + [from_p3(e.front().point()), from_p3(c.subs((a + b) * 0.5))] + }) + .collect(); + pts.iter().zip(pts.iter().cycle().skip(1)).map(|(a, b)| a.cross(*b).dot(n)).sum() +} + +fn rim_loops(wires: &[mt::Wire], n: Vec3) -> Result<(&mt::Wire, &mt::Wire)> { + let [a, b] = wires else { return Err(fail("the face must have an outer and one inner loop (a rim)")) }; + Ok(if turn(a, n) >= turn(b, n) { (a, b) } else { (b, a) }) +} + +fn profile(pieces: &[Piece], plane: &Plane) -> Result { + use std::f64::consts::TAU; + let segs = pieces + .iter() + .map(|p| { + let (a, b) = (plane.to_local(p.a), plane.to_local(p.b)); + Ok(match p.mid { + None => Seg2::Line { a, b }, + Some(m) => { + let center = plane.to_local(circle_centre(p.a, m, p.b).ok_or_else(|| fail("arc"))?); + let mid = plane.to_local(m); + let start = (a - center).angle(); + let end = (b - center).angle(); + let sweep = (end - start).rem_euclid(TAU); + let sweep = if ((mid - center).angle() - start).rem_euclid(TAU) <= sweep { sweep } else { sweep - TAU }; + Seg2::Arc { center, radius: a.dist(center), start, sweep } + } + }) + }) + .collect::>()?; + Ok(Loop2 { segs }) +} + +/// Exact profile of a band along a planar rim's chosen edge. `width` reaches into +/// the rim; `free` reaches into its free side so a groove cutter crosses the wall. +/// Lines and circular arcs stay analytic, independent of display tessellation. +pub fn rim_band(body: &Body, at: Vec3, width: f64, free: f64, outside: bool) -> Result<(Plane, Region2)> { + body.require_brep("a rim band")?; + if !(width.is_finite() && width > 0.0 && free.is_finite() && free >= 0.0) { + return Err(KernelError::Invalid("invalid rim band width".into())); + } + let (fi, n) = face_at(body, at)?; + guard("rim band", || { + let face = body.solid.face_iter().nth(fi).ok_or_else(|| fail("face"))?; + let wires = face.boundaries(); + let (outer, inner) = rim_loops(&wires, n)?; + let along = if outside { outer } else { inner }; + let p = pieces(along, body.size())?; + let tol = (body.size() * 1e-5).max(1e-7); + let plane = Plane::from_normal(at, n).ok_or_else(|| fail("rim plane"))?; + let into = profile(&offset_loop(&p, n, width, tol)?, &plane)?; + let away = profile(&offset_loop(&p, n, -free, tol)?, &plane)?; + let (outer, inner) = if outside { (away, into) } else { (into, away) }; + Ok((plane, Region2 { outer: outer.ccw(), holes: vec![inner.ccw().reversed()] })) + }) +} + /// Raise the band of the planar face at `at` that runs `width` wide along its outer loop /// (`outside`) or its inner loop, by `height` along the face's normal. pub fn raise_band(body: &Body, at: Vec3, width: f64, height: f64, outside: bool) -> Result { @@ -133,39 +217,14 @@ pub fn raise_band(body: &Body, at: Vec3, width: f64, height: f64, outside: bool) let size = body.size(); let tol = (size * 1e-7).max(1e-9) * 100.0; let (fi, n) = face_at(body, at)?; - let faces: Vec = body.solid.face_iter().cloned().collect(); - let f = faces.get(fi).ok_or_else(|| fail("face"))?; - let wires = f.boundaries(); - if wires.len() != 2 { - return Err(fail("the face must have an outer and one inner loop (a rim)")); - } - // Outer loop: turning positively about n. - let turn = |w: &mt::Wire| -> f64 { - let pts: Vec = w.vertex_iter().map(|v| from_p3(v.point())).collect(); - let mut s = Vec3::ZERO; - for (k, p) in pts.iter().enumerate() { - if let Some(q) = pts.get((k + 1) % pts.len()) { - s += p.cross(*q); - } - } - s.dot(n) - }; - let (w0, w1) = (wires.first().ok_or_else(|| fail("loop"))?, wires.get(1).ok_or_else(|| fail("loop"))?); - let (outer, inner) = if turn(w0) >= turn(w1) { (w0, w1) } else { (w1, w0) }; - let (along, other) = if outside { (outer, inner) } else { (inner, outer) }; - let pieces: Vec = along - .edge_iter() - .map(|e| { - let (a, b) = (from_p3(e.front().point()), from_p3(e.back().point())); - match crate::offset::arc_mid(e, size * 1e-6) { - Some(None) => Ok(Piece { a, b, mid: None }), - Some(Some(m)) => Ok(Piece { a, b, mid: Some(m) }), - None => Err(fail("edges must be lines or arcs")), - } - }) - .collect::>()?; - let moved = offset_loop(&pieces, n, width, tol)?; guard("lip", || { + let faces: Vec = body.solid.face_iter().cloned().collect(); + let f = faces.get(fi).ok_or_else(|| fail("face"))?; + let wires = f.boundaries(); + let (outer, inner) = rim_loops(&wires, n)?; + let (along, other) = if outside { (outer, inner) } else { (inner, outer) }; + let pieces = pieces(along, size)?; + let moved = offset_loop(&pieces, n, width, tol)?; // The band's other edge, on the face. let verts: Vec = moved.iter().map(|p| builder::vertex(p3(p.a))).collect(); let k = verts.len(); From 948c208db9978591a8c802153407afa6fa1c231d Mon Sep 17 00:00:00 2001 From: jyviko <2501648+jyviko@users.noreply.github.com> Date: Mon, 19 Oct 2026 08:48:31 -0400 Subject: [PATCH 102/225] CI: run only what a change needs, on pull requests and on main - Pushes to main use the same code/no-code rule as pull requests (`touches_code` in Select checks): a push changing only documentation, packaging, other workflows or the bots' scripts runs the repository checks only. With the merge queue off, every push to main ran the full suite and the Windows jobs, docs-only ones included. - affected.py: test data under tests/ selects the packages that read it (robustness, hole matrix, projection, taper: solidcraft-engine; oracle: the CLI, the kernel, xtask; action matrix: the CLI, the engine, xtask), and a vendored crate the packages that use it (truck: the kernel and up; egui-wgpu: the UI and the apps), instead of the whole workspace. tests/tools and unknown vendored crates still select everything. - Docker (the web app image) skips pushes touching only docs, test data or bot scripts; Pages skips test data and bot scripts; Generated files runs only when the manifests, lockfile, command registry, CLI or xtask change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QWhMwdqJYQKQq8RCLSL1LT --- .github/workflows/ci.yml | 42 +++++++++++++++++++------ .github/workflows/docker.yml | 3 ++ .github/workflows/generated.yml | 9 ++++++ .github/workflows/pages.yml | 2 ++ scripts/ci/affected.py | 54 ++++++++++++++++++++++++++++++--- scripts/ci/test_affected.py | 35 +++++++++++++++++++++ 6 files changed, 130 insertions(+), 15 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7fc6f0032..6b6d40547 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -11,8 +11,11 @@ # the viewport's GPU glue, the graphics dependencies, their scripts or this file); main and # nightly always run them. Only main saves the build caches; pull requests restore them. # The merge queue runs the full suite on exactly the commit it then puts on main, so a push to -# main that a passing merge-queue run already tested runs only the repository checks; a push -# that skipped the queue still runs everything. Pull requests run the reference tests when the +# main that a passing merge-queue run already tested runs only the repository checks. A push that +# skipped the queue runs everything when it changes code; one that changes only documentation, +# packaging, other workflows or the GitHub bots' scripts (the same rule as pull requests, +# `touches_code` in Select checks) runs only the repository checks. Test data under tests/ and +# vendored crates under vendor/ select the packages that read them (scripts/ci/affected.py). Pull requests run the reference tests when the # command line (or anything it depends on) changes, and doc tests for the affected packages. # Heavy checks wait for review: a pull request without the `approved-for-ci` label runs only # Select checks, the format and repository checks and a quick compile. Adding the label (after @@ -122,6 +125,7 @@ jobs: BASE_SHA: ${{ github.event.pull_request.base.sha }} HEAD_SHA: ${{ github.event.pull_request.head.sha }} PUSH_SHA: ${{ github.sha }} + BEFORE_SHA: ${{ github.event.before }} REPO: ${{ github.repository }} APPROVED: ${{ contains(github.event.pull_request.labels.*.name, 'approved-for-ci') }} GH_TOKEN: ${{ github.token }} @@ -132,6 +136,23 @@ jobs: windows=false full=true packages= + # Whether any of the NUL-separated paths on stdin is something a build or test reads. + # Pull requests and pushes to main share it, so a docs-only change runs no native job + # on either. + touches_code() { + local path + while IFS= read -r -d '' path; do + case "$path" in + .github/workflows/ci.yml) return 0 ;; + *.rs|Cargo.toml|Cargo.lock|*/Cargo.toml|.cargo/*|rust-toolchain*) return 0 ;; + docs/*|*.md|.github/*|packaging/*|LICENSE*|NOTICE|THIRD-PARTY-LICENSES.txt) ;; + # The GitHub bots' scripts: no Rust, tested in this job (Claim and triage bot tests). + scripts/claim/*|scripts/triage/*) ;; + *) return 0 ;; + esac + done + return 1 + } if [ "$EVENT_NAME" = push ]; then # The queue lands the very commit its merge_group run tested. If that run passed, # testing the push again proves nothing new; otherwise (a merge that skipped the @@ -142,7 +163,15 @@ jobs: | grep -o '"total_count": *[0-9]*' | grep -o '[0-9]*$' || echo 0) if [ "${tested:-0}" -gt 0 ]; then echo "The merge queue already tested $PUSH_SHA: repository checks only." + elif [ -n "$BEFORE_SHA" ] && [ "${BEFORE_SHA#0000000}" = "$BEFORE_SHA" ] \ + && git cat-file -e "$BEFORE_SHA^{commit}" 2>/dev/null \ + && git diff --no-renames --name-only -z "$BEFORE_SHA" "$PUSH_SHA" > "$RUNNER_TEMP/ci-paths" \ + && ! touches_code < "$RUNNER_TEMP/ci-paths"; then + # Nothing a build reads changed (documentation, packaging, other workflows, the bots' + # scripts): the code on main is what the last push already tested. + echo "$BEFORE_SHA..$PUSH_SHA changes no code: repository checks only." else + # Code changed (or the push can't be compared): main runs everything. native=true windows=true fi @@ -164,15 +193,8 @@ jobs: crates/gpu/*|apps/solidcraft/*|crates/ui-egui/src/gpu.rs|vendor/egui-wgpu/*) windows=true ;; tools/windows-*.ps1|.github/workflows/ci.yml|rust-toolchain*|.cargo/*) windows=true ;; esac - case "$path" in - .github/workflows/ci.yml) native=true ;; - *.rs|Cargo.toml|Cargo.lock|*/Cargo.toml|.cargo/*|rust-toolchain*) native=true ;; - docs/*|*.md|.github/*|packaging/*|LICENSE*|NOTICE|THIRD-PARTY-LICENSES.txt) ;; - # The GitHub bots' scripts: no Rust, tested in this job (Claim and triage bot tests). - scripts/claim/*|scripts/triage/*) ;; - *) native=true ;; - esac done < "$RUNNER_TEMP/ci-paths" + if touches_code < "$RUNNER_TEMP/ci-paths"; then native=true; fi # A lockfile change that moves the graphics stack (wgpu, naga, egui, winit, windows). if [ "$windows" = false ] && grep -qxz 'Cargo.lock' "$RUNNER_TEMP/ci-paths" \ && git diff "$BASE_SHA...$HEAD_SHA" -- Cargo.lock \ diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 20159e170..08db7fe5d 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -14,6 +14,9 @@ name: Docker on: push: branches: [main] + # The image holds the web app only: documentation, test data and the GitHub bots' scripts can't + # change it, so a push touching only those builds nothing (edge stays at the last code change). + paths-ignore: ["docs/**", "**/*.md", "tests/**", "scripts/claim/**", "scripts/triage/**"] release: types: [published] pull_request: diff --git a/.github/workflows/generated.yml b/.github/workflows/generated.yml index 23a39297b..db4a3d4c1 100644 --- a/.github/workflows/generated.yml +++ b/.github/workflows/generated.yml @@ -6,6 +6,15 @@ name: Generated files on: push: branches: [main] + # THIRD-PARTY-LICENSES.txt follows the manifests and the lockfile; docs/features.md follows the + # command registry (crates/engine), read through solidcraft-cli. Other pushes regenerate nothing. + paths: + - "Cargo.lock" + - "**/Cargo.toml" + - "crates/engine/**" + - "apps/solidcraft-cli/**" + - "xtask/**" + - ".github/workflows/generated.yml" workflow_dispatch: permissions: diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml index d4c9a4262..9b9a69d49 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -6,6 +6,8 @@ name: Pages on: push: branches: [main] + # The site is the book and the web app: test data and the GitHub bots' scripts change neither. + paths-ignore: ["tests/**", "scripts/claim/**", "scripts/triage/**"] workflow_dispatch: inputs: release_tag: diff --git a/scripts/ci/affected.py b/scripts/ci/affected.py index bf1ff20bc..b826086c6 100644 --- a/scripts/ci/affected.py +++ b/scripts/ci/affected.py @@ -12,9 +12,10 @@ Prints and optionally appends to $GITHUB_OUTPUT: packages=a b c the affected packages (empty when full, or when nothing needs building) A changed file maps to the package whose directory holds it. The packages that depend on those -(directly or not, dev-dependencies included) are added. Anything that can change every package, -or that no package owns, selects the full workspace. Only documentation and packaging files are -ignored. +(directly or not, dev-dependencies included) are added. Test data under tests/ maps to the +packages that read it, and a vendored crate (vendor/, a [patch] of a crates.io dependency) to the +packages that use it. Anything that can change every package, or that no package owns, selects +the full workspace. Only documentation and packaging files are ignored. """ import argparse import json @@ -22,7 +23,7 @@ import subprocess import sys # Changes here can affect every package. -FULL_PREFIXES = (".cargo/", ".config/", ".github/", "vendor/", "tests/", "scripts/") +FULL_PREFIXES = (".cargo/", ".config/", ".github/", "scripts/") FULL_FILES = ("Cargo.toml", "Cargo.lock") # Changes here affect no code: documentation and packaging. IGNORED_PREFIXES = ("docs/", "packaging/") @@ -30,6 +31,29 @@ IGNORED_PREFIXES = ("docs/", "packaging/") EMBEDDED = {"ATTRIBUTION.md": "solidcraft-ui-egui"} # Asset folders that only some packages read: the UI embeds the catalogs, xtask checks them. EMBEDDED_PREFIXES = {"assets/locales/": ("solidcraft-ui-egui", "xtask")} +# Test data and the package directories whose tests (or xtask) read it. Any other folder under +# tests/ selects the full workspace. +TEST_DATA = { + "tests/robustness/": ("crates/engine/",), + "tests/hole_matrix/": ("crates/engine/",), + "tests/projection/": ("crates/engine/",), + "tests/taper/": ("crates/engine/",), + "tests/oracle/": ("apps/solidcraft-cli/", "crates/kernel/", "xtask/"), + "tests/action_matrix/": ("apps/solidcraft-cli/", "crates/engine/", "xtask/"), +} +# Vendored crates (vendor//, a [patch] of a crates.io dependency) and the dependency names +# through which workspace packages reach them: the truck crates and their maths crate only through +# truck itself (crates/kernel), egui-wgpu directly or through eframe. Another vendored crate +# selects the full workspace. +TRUCK = lambda dep: dep.startswith("truck-") # noqa: E731 +VENDOR_USES = { + "truck-geometry": TRUCK, + "truck-shapeops": TRUCK, + "truck-stepio": TRUCK, + "truck-meshalgo": TRUCK, + "matext4cgmath": TRUCK, + "egui-wgpu": lambda dep: dep in ("egui-wgpu", "eframe"), +} def load_metadata(path): @@ -69,12 +93,32 @@ def select(meta, paths): if target: dependents[target].add(p["name"]) + def users_of(vendored): + """The workspace packages that depend on a vendored crate (by dependency name).""" + uses = VENDOR_USES.get(vendored) + if uses is None: + return set() + return {p["name"] for p in meta["packages"] if any(uses(d["name"]) for d in p["dependencies"])} + hit = set() for path in paths: if path in FULL_FILES or path.startswith(FULL_PREFIXES) or path.startswith("rust-toolchain"): return True, [] owners = [d for d in by_dir if path.startswith(d)] - if owners: + if path.startswith("vendor/"): + if path == "vendor/README.md": + continue + users = users_of(path.split("/")[1]) + if not users: + return True, [] + hit.update(users) + elif path.startswith("tests/"): + data = next((v for k, v in TEST_DATA.items() if path.startswith(k)), None) + readers = [by_dir[d] for d in data or () if d in by_dir] + if not readers: + return True, [] + hit.update(readers) + elif owners: hit.add(by_dir[max(owners, key=len)]) elif path in EMBEDDED: hit.add(EMBEDDED[path]) diff --git a/scripts/ci/test_affected.py b/scripts/ci/test_affected.py index f31fabc1c..6afb88066 100644 --- a/scripts/ci/test_affected.py +++ b/scripts/ci/test_affected.py @@ -71,6 +71,41 @@ class RealWorkspace(unittest.TestCase): def test_docs_only_selects_nothing(self): self.assertEqual(affected.select(self.meta, ["docs/book/src/dev/testing.md", "CONTRIBUTING.md"]), (False, [])) + def test_goldens_select_the_engine_and_its_dependents_not_the_kernel(self): + full, pk = affected.select(self.meta, ["tests/robustness/goldens.json"]) + self.assertFalse(full) + self.assertIn("solidcraft-engine", pk) + self.assertNotIn("solidcraft-kernel", pk) + self.assertNotIn("solidcraft-render", pk) + + def test_oracle_cases_select_the_cli_and_xtask(self): + full, pk = affected.select(self.meta, ["tests/oracle/box/recipe.json"]) + self.assertFalse(full) + self.assertIn("solidcraft-cli", pk) + self.assertIn("xtask", pk) + + def test_unmapped_test_data_selects_full(self): + self.assertEqual(affected.select(self.meta, ["tests/tools/x.json"]), (True, [])) + + def test_vendored_truck_selects_the_kernel_and_up_not_render(self): + full, pk = affected.select(self.meta, ["vendor/truck-shapeops/src/lib.rs"]) + self.assertFalse(full) + self.assertIn("solidcraft-kernel", pk) + self.assertIn("solidcraft-engine", pk) + self.assertNotIn("solidcraft-render", pk) + self.assertNotIn("solidcraft-geom", pk) + + def test_vendored_egui_wgpu_selects_the_ui_and_apps_not_the_kernel(self): + full, pk = affected.select(self.meta, ["vendor/egui-wgpu/src/winit.rs"]) + self.assertFalse(full) + self.assertIn("solidcraft-ui-egui", pk) + self.assertIn("solidcraft", pk) + self.assertNotIn("solidcraft-kernel", pk) + self.assertNotIn("solidcraft-engine", pk) + + def test_vendor_readme_alone_selects_nothing(self): + self.assertEqual(affected.select(self.meta, ["vendor/README.md"]), (False, [])) + def test_translation_selects_the_ui_and_xtask_not_the_kernel(self): full, pk = affected.select(self.meta, ["assets/locales/ja.json", "assets/locales/it.json"]) self.assertFalse(full) From 7555b34afb83a750d56368c34da43692d5d3efd2 Mon Sep 17 00:00:00 2001 From: jyviko <2501648+jyviko@users.noreply.github.com> Date: Mon, 19 Oct 2026 10:18:41 -0400 Subject: [PATCH 103/225] CI: doc tests in the pull request fast lane; heavy jobs wait for the repository checks Doc tests move to main and nightly, beside the reference tests and the Windows jobs: on pull requests they were the only failing job 3 times in about 7,900 runner-minutes over three days. Build tests, the test shards and the doc tests now start only after the format and repository checks pass; 212 attempts in those three days ran their heavy jobs beside a failed cheap check. Also corrects the header, which still said pull requests run the Windows jobs and the reference tests. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QWhMwdqJYQKQq8RCLSL1LT --- .github/workflows/ci.yml | 37 ++++++++++++++++++++++++------------- 1 file changed, 24 insertions(+), 13 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6b6d40547..1ccc3eed9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -7,16 +7,16 @@ # pushes to main, the nightly run and Run workflow. # Tests are built once and run in shards. A few heavy tests (see .config/nextest.toml) are # skipped on pull requests and run on pushes to main and nightly. The Windows jobs (D3D12 shaders -# and app startup) run on pull requests only when what they test changes (the GPU crate, the app, -# the viewport's GPU glue, the graphics dependencies, their scripts or this file); main and -# nightly always run them. Only main saves the build caches; pull requests restore them. +# and app startup), the reference tests and the doc tests run on main and nightly only, not on +# pull requests (the fast lane, in Select checks); a break there is fixed forward on main. Only +# main saves the build caches; pull requests restore them. The test build, the shards and the doc +# tests start only after the format and repository checks pass. # The merge queue runs the full suite on exactly the commit it then puts on main, so a push to # main that a passing merge-queue run already tested runs only the repository checks. A push that # skipped the queue runs everything when it changes code; one that changes only documentation, # packaging, other workflows or the GitHub bots' scripts (the same rule as pull requests, # `touches_code` in Select checks) runs only the repository checks. Test data under tests/ and -# vendored crates under vendor/ select the packages that read them (scripts/ci/affected.py). Pull requests run the reference tests when the -# command line (or anything it depends on) changes, and doc tests for the affected packages. +# vendored crates under vendor/ select the packages that read them (scripts/ci/affected.py). # Heavy checks wait for review: a pull request without the `approved-for-ci` label runs only # Select checks, the format and repository checks and a quick compile. Adding the label (after # review) runs everything above, and every later push to the PR does too. Pushes to main, merge @@ -111,6 +111,7 @@ jobs: quick: ${{ steps.paths.outputs.quick }} packages: ${{ steps.paths.outputs.packages }} oracle: ${{ steps.paths.outputs.oracle }} + doctests: ${{ steps.paths.outputs.doctests }} # The fast self-hosted runners are kept for main and the merge queue (the pre-merge gate); # pull requests, same-repo ones included, take the GitHub-hosted or untrusted paths. local: ${{ runner.environment == 'self-hosted' && github.event_name != 'pull_request' }} @@ -219,9 +220,12 @@ jobs: if [ "$EVENT_NAME" = pull_request ] && [ "$full" != true ]; then case " $packages " in *" solidcraft-cli "*) ;; *) oracle=false ;; esac fi - # The pull request fast lane: Windows and the reference tests run on main (and the nightly), - # not on every pull request push; a break there is fixed forward on main. - if [ "$EVENT_NAME" = pull_request ]; then windows=false; oracle=false; fi + # The pull request fast lane: Windows, the reference tests and the doc tests run on main + # (and the nightly), not on every pull request push; a break there is fixed forward on + # main. Over three days of pull requests the doc tests were the only failing job 3 times + # in about 7,900 runner-minutes, and the reference tests never were. + doctests=$native + if [ "$EVENT_NAME" = pull_request ]; then windows=false; oracle=false; doctests=false; fi # Until a maintainer adds approved-for-ci, a pull request gets a quick compile instead of # Clippy, the tests, the doc tests and the goldens. quick=false @@ -237,6 +241,7 @@ jobs: echo "goldens=$goldens" echo "windows=$windows" echo "oracle=$oracle" + echo "doctests=$doctests" echo "full=$full" echo "quick=$quick" echo "packages=$packages" @@ -336,7 +341,9 @@ jobs: build-tests: name: Build tests - needs: changes + # Fail fast: the test archive (and so the shards) waits for the repository checks, the most + # common cheap failure; heavy jobs used to run on to the end beside a failed format check. + needs: [changes, checks] # The self-hosted shards (main and the merge queue) build from their warm build directories # instead: downloading the 3 GB archive took them longer than building. if: needs.changes.outputs.native == 'true' && needs.changes.outputs.local != 'true' @@ -385,8 +392,8 @@ jobs: tests: name: Native Linux tests (${{ matrix.shard }}/4) - needs: [changes, build-tests] - if: ${{ !cancelled() && needs.changes.outputs.native == 'true' && (needs.changes.outputs.local == 'true' || needs.build-tests.result == 'success') }} + needs: [changes, checks, build-tests] + if: ${{ !cancelled() && needs.changes.outputs.native == 'true' && needs.checks.result == 'success' && (needs.changes.outputs.local == 'true' || needs.build-tests.result == 'success') }} runs-on: ${{ needs.changes.outputs.local == 'true' && 'self-hosted-fast' || ((github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository && (endsWith(format('{0}', github.event.pull_request.number), '7') || endsWith(format('{0}', github.event.pull_request.number), '8') || endsWith(format('{0}', github.event.pull_request.number), '9'))) && 'self-hosted-untrusted' || 'ubuntu-24.04') }} timeout-minutes: 60 strategy: @@ -572,8 +579,9 @@ jobs: doc-tests: name: Doc tests - needs: changes - if: needs.changes.outputs.native == 'true' + # After the repository checks pass (see Build tests). + needs: [changes, checks] + if: needs.changes.outputs.doctests == 'true' runs-on: ${{ needs.changes.outputs.local == 'true' && 'self-hosted-fast' || 'ubuntu-24.04' }} timeout-minutes: 45 env: @@ -740,6 +748,7 @@ jobs: LOCAL: ${{ needs.changes.outputs.local }} WINDOWS: ${{ needs.changes.outputs.windows }} ORACLE_RUN: ${{ needs.changes.outputs.oracle }} + DOCTESTS: ${{ needs.changes.outputs.doctests }} CLIPPY: ${{ needs.clippy.result }} BUILD: ${{ needs.build-tests.result }} TESTS: ${{ needs.tests.result }} @@ -759,6 +768,8 @@ jobs: # The self-hosted test shards build their own tests (no Build tests job there). [ "$BUILD" = success ] || { [ "$LOCAL" = true ] && [ "$BUILD" = skipped ]; } test "$TESTS" = success + fi + if [ "$DOCTESTS" = true ]; then test "$DOCS" = success fi if [ "$ORACLE_RUN" = true ]; then From b045d9deae969850d3bf6af046c863127234f911 Mon Sep 17 00:00:00 2001 From: jyviko <2501648+jyviko@users.noreply.github.com> Date: Mon, 19 Oct 2026 10:25:33 -0400 Subject: [PATCH 104/225] CI: a push that only merges main into a passing change carries its result Merging main into a pull request (Merge branch 'main', or GitHub's Update branch) restarted the whole run. Over three days 1,241 such merges started 966 runs and about 21,000 runner-minutes, and 872 of the merges brought in nothing that touched the pull request's files. Select checks now recognises the case (scripts/ci/main_merge.py): HEAD is a merge whose other parent is on main, the change's own patch is unchanged (git patch-id), and a ci.yml run of the change before the merge passed with its test shards. Then only the repository checks run, the ci job names the passing run in its summary, and main tests the merged result after it lands. Anything else, or any doubt, runs the full set as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QWhMwdqJYQKQq8RCLSL1LT --- .github/workflows/ci.yml | 28 ++++++++- scripts/ci/main_merge.py | 92 ++++++++++++++++++++++++++++ scripts/ci/test_main_merge.py | 110 ++++++++++++++++++++++++++++++++++ 3 files changed, 229 insertions(+), 1 deletion(-) create mode 100644 scripts/ci/main_merge.py create mode 100644 scripts/ci/test_main_merge.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1ccc3eed9..6084d20c7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,7 +19,9 @@ # vendored crates under vendor/ select the packages that read them (scripts/ci/affected.py). # Heavy checks wait for review: a pull request without the `approved-for-ci` label runs only # Select checks, the format and repository checks and a quick compile. Adding the label (after -# review) runs everything above, and every later push to the PR does too. Pushes to main, merge +# review) runs everything above, and every later push to the PR does too, except a push that only +# merges main into a change that already passed (scripts/ci/main_merge.py): it carries that +# result and runs the repository checks. Pushes to main, merge # groups, the nightly run and Run workflow are not pull requests and always run the full suite. # GitHub cannot filter `labeled` events by label name, so any other label starts a run whose jobs # are all skipped; it gets its own concurrency group (below) so it never cancels the real run. @@ -112,6 +114,8 @@ jobs: packages: ${{ steps.paths.outputs.packages }} oracle: ${{ steps.paths.outputs.oracle }} doctests: ${{ steps.paths.outputs.doctests }} + # The passing run a merge of main carries forward (its URL), when this push is only that. + carried: ${{ steps.paths.outputs.carried }} # The fast self-hosted runners are kept for main and the merge queue (the pre-merge gate); # pull requests, same-repo ones included, take the GitHub-hosted or untrusted paths. local: ${{ runner.environment == 'self-hosted' && github.event_name != 'pull_request' }} @@ -235,6 +239,19 @@ jobs: oracle=false goldens=false fi + # A push that only merges main into the change (Merge branch 'main', Update branch) when + # the change itself already passed: nothing new to test here, and main tests the merged + # result after it lands. Over three days, 872 of 1,241 such merges brought in nothing that + # touched the pull request's files, and each restarted the whole run. + carried= + if [ "$EVENT_NAME" = pull_request ] && [ "$native" = true ]; then + carried=$(python3 -I scripts/ci/main_merge.py --base "$BASE_SHA" --head "$HEAD_SHA" --repo "$REPO" | sed -n 's/^carried=//p') + if [ -n "$carried" ]; then + echo "Only a merge of main into a change that passed in $carried: repository checks only." + native=false + goldens=false + fi + fi { echo "native=$native" echo "kernel=$kernel" @@ -242,6 +259,7 @@ jobs: echo "windows=$windows" echo "oracle=$oracle" echo "doctests=$doctests" + echo "carried=$carried" echo "full=$full" echo "quick=$quick" echo "packages=$packages" @@ -285,6 +303,8 @@ jobs: run: cargo xtask web-offline-test - name: Affected-package selection self-test run: python3 -I scripts/ci/test_affected.py + - name: Merge-of-main detection self-test + run: python3 -I scripts/ci/test_main_merge.py - name: Claim and triage bot tests run: node --test scripts/claim/*.test.js scripts/triage/*.test.js @@ -779,6 +799,12 @@ jobs: test "$WINDOWS_FXC" = success test "$WINDOWS_STARTUP" = success fi + - name: Note a carried result + if: needs.changes.outputs.carried != '' + env: + CARRIED: ${{ needs.changes.outputs.carried }} + run: | + echo "This push only merges main into a change that already passed; the heavy checks were not repeated. Passing run: $CARRIED" >> "$GITHUB_STEP_SUMMARY" wasm: name: Compile WebAssembly (manual) diff --git a/scripts/ci/main_merge.py b/scripts/ci/main_merge.py new file mode 100644 index 000000000..35d0504be --- /dev/null +++ b/scripts/ci/main_merge.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python3 +"""Is this pull request push only a merge of main into a change that already passed CI? + + python3 -I scripts/ci/main_merge.py --base BASE_SHA --head HEAD_SHA --repo OWNER/NAME + +Prints `carried=` when all of these hold, else `carried=`: + - HEAD is a merge commit whose second parent is on main (an ancestor of BASE): "Merge branch + 'main'", or GitHub's Update branch button; + - the pull request's own change is the same before and after the merge (equal `git patch-id`), + so the merge resolved no conflict and brought nothing into the change itself; + - a ci.yml run of the first parent (the change before the merge) passed with the test shards. + +Then the run needs only the repository checks: the change was tested, and main tests the merged +result after it lands. Any doubt (an error, an API failure, an unexpected shape) prints +`carried=` and the full checks run. Reads GH_TOKEN from the environment for the API. +""" +import argparse +import json +import os +import subprocess +import sys +import urllib.request + +API = "https://api.github.com" +SHARD_PREFIX = "Native Linux tests" + + +def git(*args): + return subprocess.run(["git", *args], capture_output=True, text=True, check=True).stdout + + +def patch_id(a, b): + """The stable patch id of `git diff a b` ("" for an empty diff).""" + diff = subprocess.run(["git", "diff", "--no-renames", a, b], capture_output=True, check=True).stdout + if not diff.strip(): + return "" + out = subprocess.run(["git", "patch-id", "--stable"], input=diff, capture_output=True, check=True).stdout + return out.split()[0].decode() if out.split() else "" + + +def merge_of_main(base, head): + """The first parent of HEAD when HEAD only merges main into an unchanged change, else None.""" + parents = git("rev-list", "--parents", "-n", "1", head).split()[1:] + if len(parents) != 2: + return None + change, merged = parents + if subprocess.run(["git", "merge-base", "--is-ancestor", merged, base]).returncode != 0: + return None + fork_point = git("merge-base", change, merged).strip() + before, after = patch_id(fork_point, change), patch_id(merged, head) + return change if before and before == after else None + + +def get(url, token): + req = urllib.request.Request(url, headers={"Accept": "application/vnd.github+json", "Authorization": f"Bearer {token}"}) + with urllib.request.urlopen(req, timeout=20) as r: + return json.load(r) + + +def passing_run(repo, sha, token): + """URL of a successful pull request ci.yml run of `sha` whose test shards all passed.""" + runs = get(f"{API}/repos/{repo}/actions/workflows/ci.yml/runs?head_sha={sha}&event=pull_request&status=success&per_page=10", token) + for run in runs.get("workflow_runs", []): + jobs = get(f"{API}/repos/{repo}/actions/runs/{run['id']}/jobs?per_page=100", token).get("jobs", []) + shards = [j for j in jobs if j.get("name", "").startswith(SHARD_PREFIX)] + if shards and all(j.get("conclusion") == "success" for j in shards): + return run.get("html_url", "") + return "" + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--base", required=True) + ap.add_argument("--head", required=True) + ap.add_argument("--repo", required=True) + a = ap.parse_args() + carried = "" + try: + change = merge_of_main(a.base, a.head) + token = os.environ.get("GH_TOKEN", "") + if change and token: + carried = passing_run(a.repo, change, token) + if carried: + print(f"{a.head} merges main into {change}, which passed: {carried}", file=sys.stderr) + except (subprocess.CalledProcessError, OSError, ValueError, KeyError) as e: + print(f"not carried ({e})", file=sys.stderr) + carried = "" + print(f"carried={carried}") + + +if __name__ == "__main__": + main() diff --git a/scripts/ci/test_main_merge.py b/scripts/ci/test_main_merge.py new file mode 100644 index 000000000..3e883e5b7 --- /dev/null +++ b/scripts/ci/test_main_merge.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python3 +"""Self-test for main_merge.py. Run: python3 -I scripts/ci/test_main_merge.py (from the repo root). + +Builds small throwaway git repositories; needs only git. +""" +import os +import subprocess +import sys +import tempfile +import unittest + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import main_merge # noqa: E402 + + +class Repo: + def __init__(self, root): + self.root = root + self.git("init", "-q", "-b", "main") + self.git("config", "user.email", "t@example.com") + self.git("config", "user.name", "t") + self.git("config", "commit.gpgsign", "false") + + def git(self, *args): + return subprocess.run(["git", *args], cwd=self.root, capture_output=True, text=True, check=True).stdout.strip() + + def write(self, path, text): + with open(os.path.join(self.root, path), "w") as f: + f.write(text) + + def commit(self, msg, **files): + for path, text in files.items(): + self.write(path, text) + self.git("add", "-A") + self.git("commit", "-q", "-m", msg) + return self.git("rev-parse", "HEAD") + + +LINES = "".join(f"line {i}\n" for i in range(40)) + + +class MergeOfMain(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.r = Repo(self.tmp.name) + self.r.commit("base", **{"a.txt": LINES, "b.txt": LINES}) + self.r.git("checkout", "-q", "-b", "pr") + self.change = self.r.commit("pr change", **{"a.txt": LINES.replace("line 5\n", "line five\n")}) + self.cwd = os.getcwd() + os.chdir(self.tmp.name) + + def tearDown(self): + os.chdir(self.cwd) + self.tmp.cleanup() + + def main_commit(self, **files): + self.r.git("checkout", "-q", "main") + sha = self.r.commit("main moves", **files) + self.r.git("checkout", "-q", "pr") + return sha + + def merge_main(self): + self.r.git("merge", "-q", "--no-edit", "main") + return self.r.git("rev-parse", "HEAD") + + def test_clean_merge_of_unrelated_main_change_is_carried(self): + base = self.main_commit(**{"b.txt": LINES.replace("line 30\n", "line thirty\n")}) + head = self.merge_main() + self.assertEqual(main_merge.merge_of_main(base, head), self.change) + + def test_conflict_resolution_is_not_carried(self): + base = self.main_commit(**{"a.txt": LINES.replace("line 5\n", "line 5 on main\n")}) + subprocess.run(["git", "merge", "-q", "main"], cwd=self.tmp.name, capture_output=True) + self.r.write("a.txt", LINES.replace("line 5\n", "line five on both\n")) + self.r.git("add", "-A") + self.r.git("commit", "-q", "--no-edit") + head = self.r.git("rev-parse", "HEAD") + self.assertIsNone(main_merge.merge_of_main(base, head)) + + def test_main_change_next_to_the_change_is_not_carried(self): + # Main edits a context line of the pull request's hunk: the change's patch differs. + base = self.main_commit(**{"a.txt": LINES.replace("line 7\n", "line seven\n")}) + head = self.merge_main() + self.assertIsNone(main_merge.merge_of_main(base, head)) + + def test_ordinary_commit_is_not_carried(self): + head = self.r.commit("more", **{"a.txt": LINES.replace("line 5\n", "line 5b\n")}) + base = self.r.git("rev-parse", "main") + self.assertIsNone(main_merge.merge_of_main(base, head)) + + def test_merge_of_another_branch_is_not_carried(self): + base = self.r.git("rev-parse", "main") + self.r.git("checkout", "-q", "-b", "other", "main") + self.r.commit("other work", **{"c.txt": "x\n"}) + self.r.git("checkout", "-q", "pr") + self.r.git("merge", "-q", "--no-edit", "other") + head = self.r.git("rev-parse", "HEAD") + self.assertIsNone(main_merge.merge_of_main(base, head)) + + def test_change_with_empty_diff_is_not_carried(self): + self.r.git("checkout", "-q", "-b", "empty", "main") + base = self.main_commit(**{"b.txt": LINES.replace("line 30\n", "line thirty\n")}) + self.r.git("checkout", "-q", "empty") + self.r.git("merge", "-q", "--no-ff", "--no-edit", "main") + head = self.r.git("rev-parse", "HEAD") + self.assertIsNone(main_merge.merge_of_main(base, head)) + + +if __name__ == "__main__": + unittest.main() From e9b850572df7afd4585517da844035cb216af80a Mon Sep 17 00:00:00 2001 From: jyviko <2501648+jyviko@users.noreply.github.com> Date: Mon, 19 Oct 2026 10:26:06 -0400 Subject: [PATCH 105/225] Contributing: don't bring main into an open PR, don't re-run unchanged commits The guidance told contributors and agents to keep their branch current with every upstream merge and to re-run CI after integrating. Over three days that meant 1,241 merges of main into pull requests and 730 re-runs: about 45,000 of 79,800 ci runner-minutes, on runners that capped how fast everyone's checks ran. CI already tests each pull request merged with the latest main, and a real failure fails again on the same commit. Now: merge main in only when GitHub reports a conflict, re-run only a job runner trouble cancelled, and maintainers add approved-for-ci when a pull request is ready to merge and merge approved ones in groups by area. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QWhMwdqJYQKQq8RCLSL1LT --- AGENTS.md | 14 ++++++++------ CONTRIBUTING.md | 19 +++++++++++-------- 2 files changed, 19 insertions(+), 14 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 6ef91355d..7c47f7833 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -103,7 +103,7 @@ People trust SolidCraft with their designs; a crash loses their work. **This out - **Publishing**: `origin` is github.com/bherbruck/solidcraft. Changes land through **pull requests**: push a branch, open a PR, and let GitHub CI run. Maintainers (and agents working for them) may merge their own PR as soon as CI is green (`gh pr merge --squash`); a trivial fix (docs, typos) - may be merged right away. Keep each PR to one topic, rebase or merge `main` into it when it + may be merged right away. Keep each PR to one topic, merge `main` into it only when it conflicts, and never force-push `main`. Never commit `plan/`, build dirs (`target*/`) or generated reference data; check `git ls-files` before pushing. - **Never break wasm**: everything below the apps must build for `wasm32-unknown-unknown` @@ -124,11 +124,13 @@ People trust SolidCraft with their designs; a crash loses their work. **This out - Use a small public-safe example and check for private designs, paths, account details or other sensitive content before sharing. Attach media to the issue/PR or link to an accessible recording; do not commit generated screenshots or videos just to provide review evidence. -- Throughout the work and before handoff, check current upstream commits and the relevant - PR's merge status. Keep your branch current with upstream merges, resolve conflicts without - discarding others' work, and re-run validation when integration changes the result. Use - `git pull --rebase origin main` before pushing as above; never force-push. Report the checked - upstream/PR state, any conflicts resolved and the validation performed. If a PR remains open, +- Throughout the work and before handoff, check the relevant PR's merge status. Don't bring + `main` into an open PR to keep it current (no merge of `main`, no Update branch, no rebase): + CI already tests the PR merged with the latest `main`, and every update restarts the whole + run. Only when GitHub reports a conflict, merge `main` in once and resolve it without + discarding others' work; never force-push. Don't re-run CI on an unchanged commit: a real + failure fails again. Re-run only a job that runner trouble cancelled, with "Re-run failed + jobs". Report the PR state you checked and any conflicts resolved. If a PR remains open, keep monitoring it while the task is active and make its pending status clear at handoff; do not claim it merged without checking. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 359341e73..aeb2b314f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -287,8 +287,9 @@ and a fresh CI run: clippy (`-D warnings`), then the tests with the wasm build check alongside. A PR has to pass it. Heavy CI runs after review: a pull request gets the formatting and repository checks and a quick compile (`cargo check`) when you push. Once a maintainer has reviewed it they add the - `approved-for-ci` label, which runs the full CI (build, tests, goldens, Clippy); every push - after that runs the full set again. + `approved-for-ci` label when the PR is ready to merge, which runs the full CI (build, tests, + goldens, Clippy); every push after that runs the full set again. Maintainers merge approved + PRs in groups by area, so PRs that touch the same code meet a conflict at most once. 4. Reference the issue (`Fixes #12`). In the PR, say what you tested and how. For geometry work, include the measured numbers (and the expected ones). @@ -313,12 +314,14 @@ Changes with no useful observable behavior do not need screenshot or video evide small example without private designs or sensitive details; attach the media or link to an accessible recording rather than committing generated review artifacts. -Keep checking upstream commits and the relevant PR's merge status throughout the work and -before handoff. Integrate upstream merges, resolve conflicts without losing others' changes, -and validate the integrated result. Before pushing, run `git pull --rebase origin main`, re-run -CI if it brought changes, and push without force. Report the upstream/PR state you checked, -any conflicts resolved and validation results. While a task remains active, follow an open -PR through its status changes; at handoff, clearly identify anything still awaiting merge. +Keep an eye on your PR's status, but don't bring `main` into it to keep it current: no merge of +`main`, no Update branch button, no rebase. CI already tests your PR merged with the latest +`main`, and every update restarts the whole run for everyone waiting behind it. Only when GitHub +reports a conflict, merge `main` in once and resolve it without losing others' changes; never +force-push. Don't re-run CI on an unchanged commit either: a real failure fails again. Re-run +only a job that runner trouble cancelled, with "Re-run failed jobs". While a task remains active, +follow an open PR through its status changes; at handoff, clearly identify anything still +awaiting merge. Much of SolidCraft so far was written by AI coding agents (Claude) working in parallel, each owning one area, with a human setting direction and reporting bugs. Their working notes are in From 6b4026fd19877c4a53c543b58ed1b3ff88105020 Mon Sep 17 00:00:00 2001 From: jyviko <2501648+jyviko@users.noreply.github.com> Date: Mon, 19 Oct 2026 10:29:56 -0400 Subject: [PATCH 106/225] CI: carry through consecutive merges of main A change that merged main twice in a row ran the full set on every other push: the change before the second merge was itself a carried run, its shards skipped, so it had no passing shards to carry. The script now walks down the first parents through consecutive merges of main that kept the change's patch (each equal to the next), at most 10, to the run where the shards ran. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QWhMwdqJYQKQq8RCLSL1LT --- scripts/ci/main_merge.py | 23 ++++++++++++++++++++--- scripts/ci/test_main_merge.py | 15 +++++++++++++++ 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/scripts/ci/main_merge.py b/scripts/ci/main_merge.py index 35d0504be..825701dfa 100644 --- a/scripts/ci/main_merge.py +++ b/scripts/ci/main_merge.py @@ -8,7 +8,9 @@ Prints `carried=` when all of these hold, else `carried= 'main'", or GitHub's Update branch button; - the pull request's own change is the same before and after the merge (equal `git patch-id`), so the merge resolved no conflict and brought nothing into the change itself; - - a ci.yml run of the first parent (the change before the merge) passed with the test shards. + - a ci.yml run of the change before the merge passed with the test shards. When that change was + itself only a merge of main (a run that carried, its shards skipped), the walk goes on down + the first parents, through at most MAX_CHAIN merges, to the run where the shards ran. Then the run needs only the repository checks: the change was tested, and main tests the merged result after it lands. Any doubt (an error, an API failure, an unexpected shape) prints @@ -23,6 +25,8 @@ import urllib.request API = "https://api.github.com" SHARD_PREFIX = "Native Linux tests" +# Consecutive merges of main followed back to a run whose shards ran. +MAX_CHAIN = 10 def git(*args): @@ -51,6 +55,19 @@ def merge_of_main(base, head): return change if before and before == after else None +def merge_chain(base, head): + """The changes HEAD carries from, nearest first: the first parent of each consecutive merge of + main that left the change's own patch as it was (each one equals the next, so all equal HEAD's).""" + chain, cur = [], head + for _ in range(MAX_CHAIN): + change = merge_of_main(base, cur) + if change is None: + break + chain.append(change) + cur = change + return chain + + def get(url, token): req = urllib.request.Request(url, headers={"Accept": "application/vnd.github+json", "Authorization": f"Bearer {token}"}) with urllib.request.urlopen(req, timeout=20) as r: @@ -76,12 +93,12 @@ def main(): a = ap.parse_args() carried = "" try: - change = merge_of_main(a.base, a.head) token = os.environ.get("GH_TOKEN", "") - if change and token: + for change in merge_chain(a.base, a.head) if token else []: carried = passing_run(a.repo, change, token) if carried: print(f"{a.head} merges main into {change}, which passed: {carried}", file=sys.stderr) + break except (subprocess.CalledProcessError, OSError, ValueError, KeyError) as e: print(f"not carried ({e})", file=sys.stderr) carried = "" diff --git a/scripts/ci/test_main_merge.py b/scripts/ci/test_main_merge.py index 3e883e5b7..0fde86d16 100644 --- a/scripts/ci/test_main_merge.py +++ b/scripts/ci/test_main_merge.py @@ -68,6 +68,21 @@ class MergeOfMain(unittest.TestCase): head = self.merge_main() self.assertEqual(main_merge.merge_of_main(base, head), self.change) + def test_consecutive_merges_of_main_chain_back_to_the_change(self): + self.main_commit(**{"b.txt": LINES.replace("line 30\n", "line thirty\n")}) + first = self.merge_main() + base = self.main_commit(**{"b.txt": LINES.replace("line 30\n", "line thirty\n").replace("line 35\n", "line 35b\n")}) + head = self.merge_main() + self.assertEqual(main_merge.merge_chain(base, head), [first, self.change]) + + def test_chain_stops_at_an_ordinary_commit(self): + self.main_commit(**{"b.txt": LINES.replace("line 30\n", "line thirty\n")}) + self.merge_main() + later = self.r.commit("more work", **{"a.txt": LINES.replace("line 5\n", "line five\n").replace("line 20\n", "line twenty\n")}) + base = self.main_commit(**{"b.txt": LINES.replace("line 30\n", "line thirty\n").replace("line 35\n", "line 35b\n")}) + head = self.merge_main() + self.assertEqual(main_merge.merge_chain(base, head), [later]) + def test_conflict_resolution_is_not_carried(self): base = self.main_commit(**{"a.txt": LINES.replace("line 5\n", "line 5 on main\n")}) subprocess.run(["git", "merge", "-q", "main"], cwd=self.tmp.name, capture_output=True) From 2f92aaee6cf368aaebf03adfd430dfdca5d24884 Mon Sep 17 00:00:00 2001 From: jyviko <2501648+jyviko@users.noreply.github.com> Date: Mon, 19 Oct 2026 10:42:20 -0400 Subject: [PATCH 107/225] CI: one tested rule for code changes; review fixes From the review of this PR: - What counts as code lives only in scripts/ci/affected.py now: nothing selected and not full means no code changed, on pull requests and pushes to main alike. The untested bash copy in Select checks disagreed with it. Root files and folders a crate embeds now select that crate (the licence texts and NOTICE: the engine; skills/: the MCP server's tests), where before a change to them ran no test at all. Other workflows and the bots' scripts select nothing. - A push to main skips the native jobs only when nothing a build reads changed since the last push to main whose run passed. Comparing with the push just before was unsafe: a newer push cancels a waiting run, so that commit may never have been tested. - Fail fast applies to pull requests only. On main, nightly and Run workflow the test build and the shards run regardless of the repository checks, so the action matrix and property tests that hang off Build tests keep their signal. Doc tests (main and nightly only now) no longer wait for the checks. - tests/robustness/ turns on the goldens, so a change to goldens.json runs the seed tests. - tests/oracle/ no longer selects the kernel, which never reads it. - The workflow header and CONTRIBUTING describe what main and pull requests now run. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QWhMwdqJYQKQq8RCLSL1LT --- .github/workflows/ci.yml | 98 +++++++++++++++++-------------------- CONTRIBUTING.md | 10 ++-- scripts/ci/affected.py | 47 ++++++++++++------ scripts/ci/test_affected.py | 18 ++++++- 4 files changed, 99 insertions(+), 74 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6084d20c7..bfea2f6a0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,27 +2,27 @@ # PRs test what they touch; main and nightly test everything. On a pull request the "Select # checks" job maps the changed files to workspace packages (scripts/ci/affected.py), adds the # packages that depend on them, and Clippy, the test archive and the test shards cover only -# those. Changes to the lockfile, root manifest, toolchain/cargo/nextest config, .github/, -# vendor/, tests/, scripts/ or any file no package owns select the whole workspace, as do -# pushes to main, the nightly run and Run workflow. +# those. Test data under tests/, vendored crates under vendor/ and root files a crate embeds +# select the packages that read them. Changes to the lockfile, root manifest, +# toolchain/cargo/nextest config, this workflow, scripts/ or any file no package owns select the +# whole workspace, as do pushes to main that change code, the nightly run and Run workflow. +# Documentation, packaging, the other workflows and the GitHub bots' scripts select nothing: +# no native job runs for them, on pull requests or on main. # Tests are built once and run in shards. A few heavy tests (see .config/nextest.toml) are # skipped on pull requests and run on pushes to main and nightly. The Windows jobs (D3D12 shaders # and app startup), the reference tests and the doc tests run on main and nightly only, not on # pull requests (the fast lane, in Select checks); a break there is fixed forward on main. Only -# main saves the build caches; pull requests restore them. The test build, the shards and the doc -# tests start only after the format and repository checks pass. -# The merge queue runs the full suite on exactly the commit it then puts on main, so a push to -# main that a passing merge-queue run already tested runs only the repository checks. A push that -# skipped the queue runs everything when it changes code; one that changes only documentation, -# packaging, other workflows or the GitHub bots' scripts (the same rule as pull requests, -# `touches_code` in Select checks) runs only the repository checks. Test data under tests/ and -# vendored crates under vendor/ select the packages that read them (scripts/ci/affected.py). +# main saves the build caches; pull requests restore them. On pull requests the test build and the +# shards start only after the format and repository checks pass. +# A push to main runs only the repository checks when a passing merge-queue run tested that very +# commit, or when nothing a build reads changed since the last push to main whose run passed. +# Otherwise it runs everything. # Heavy checks wait for review: a pull request without the `approved-for-ci` label runs only # Select checks, the format and repository checks and a quick compile. Adding the label (after # review) runs everything above, and every later push to the PR does too, except a push that only # merges main into a change that already passed (scripts/ci/main_merge.py): it carries that -# result and runs the repository checks. Pushes to main, merge -# groups, the nightly run and Run workflow are not pull requests and always run the full suite. +# result and runs the repository checks. Merge groups, the nightly run and Run workflow are not +# pull requests and always run the full suite. # GitHub cannot filter `labeled` events by label name, so any other label starts a run whose jobs # are all skipped; it gets its own concurrency group (below) so it never cancels the real run. # Cross-compilation is opt-in through Run workflow; release builds remain in release.yml. @@ -130,7 +130,6 @@ jobs: BASE_SHA: ${{ github.event.pull_request.base.sha }} HEAD_SHA: ${{ github.event.pull_request.head.sha }} PUSH_SHA: ${{ github.sha }} - BEFORE_SHA: ${{ github.event.before }} REPO: ${{ github.repository }} APPROVED: ${{ contains(github.event.pull_request.labels.*.name, 'approved-for-ci') }} GH_TOKEN: ${{ github.token }} @@ -141,42 +140,38 @@ jobs: windows=false full=true packages= - # Whether any of the NUL-separated paths on stdin is something a build or test reads. - # Pull requests and pushes to main share it, so a docs-only change runs no native job - # on either. - touches_code() { - local path - while IFS= read -r -d '' path; do - case "$path" in - .github/workflows/ci.yml) return 0 ;; - *.rs|Cargo.toml|Cargo.lock|*/Cargo.toml|.cargo/*|rust-toolchain*) return 0 ;; - docs/*|*.md|.github/*|packaging/*|LICENSE*|NOTICE|THIRD-PARTY-LICENSES.txt) ;; - # The GitHub bots' scripts: no Rust, tested in this job (Claim and triage bot tests). - scripts/claim/*|scripts/triage/*) ;; - *) return 0 ;; - esac - done - return 1 + # Whether the NUL-separated paths in $1 reach any code: scripts/ci/affected.py selects + # something or the whole workspace. Documentation, packaging, other workflows and the bots' + # scripts select nothing. Pull requests and pushes to main share it. + select_packages() { + python3 -I scripts/ci/affected.py --paths "$1" > "$RUNNER_TEMP/ci-affected" + cat "$RUNNER_TEMP/ci-affected" + full=$(sed -n 's/^full=//p' "$RUNNER_TEMP/ci-affected") + packages=$(sed -n 's/^packages=//p' "$RUNNER_TEMP/ci-affected") } if [ "$EVENT_NAME" = push ]; then # The queue lands the very commit its merge_group run tested. If that run passed, # testing the push again proves nothing new; otherwise (a merge that skipped the # queue, or the API cannot answer) test everything. - # curl and grep only: Select checks of a push runs on the self-hosted runner. + # The API through curl and grep: Select checks of a push runs on the self-hosted runner. tested=$(curl -fsS -H "Authorization: Bearer $GH_TOKEN" -H "Accept: application/vnd.github+json" \ "https://api.github.com/repos/$REPO/actions/workflows/ci.yml/runs?event=merge_group&head_sha=$PUSH_SHA&status=success&per_page=1" \ | grep -o '"total_count": *[0-9]*' | grep -o '[0-9]*$' || echo 0) if [ "${tested:-0}" -gt 0 ]; then echo "The merge queue already tested $PUSH_SHA: repository checks only." - elif [ -n "$BEFORE_SHA" ] && [ "${BEFORE_SHA#0000000}" = "$BEFORE_SHA" ] \ - && git cat-file -e "$BEFORE_SHA^{commit}" 2>/dev/null \ - && git diff --no-renames --name-only -z "$BEFORE_SHA" "$PUSH_SHA" > "$RUNNER_TEMP/ci-paths" \ - && ! touches_code < "$RUNNER_TEMP/ci-paths"; then - # Nothing a build reads changed (documentation, packaging, other workflows, the bots' - # scripts): the code on main is what the last push already tested. - echo "$BEFORE_SHA..$PUSH_SHA changes no code: repository checks only." + elif tested=$(curl -fsS -H "Authorization: Bearer $GH_TOKEN" -H "Accept: application/vnd.github+json" \ + "https://api.github.com/repos/$REPO/actions/workflows/ci.yml/runs?event=push&branch=main&status=success&per_page=1" \ + | grep -o '"head_sha": *"[0-9a-f]*"' | head -n 1 | grep -o '[0-9a-f]\{40\}') \ + && [ -n "$tested" ] && git merge-base --is-ancestor "$tested" "$PUSH_SHA" \ + && git diff --no-renames --name-only -z "$tested" "$PUSH_SHA" > "$RUNNER_TEMP/ci-paths" \ + && select_packages "$RUNNER_TEMP/ci-paths" && [ "$full" != true ] && [ -z "$packages" ]; then + # Nothing a build reads changed since the last push to main whose run passed (the + # push before may never have run: a newer push cancels a waiting one). + echo "$tested..$PUSH_SHA changes no code: repository checks only." else # Code changed (or the push can't be compared): main runs everything. + full=true + packages= native=true windows=true fi @@ -190,7 +185,7 @@ jobs: case "$path" in crates/kernel/*|vendor/truck-*) kernel=true ;; esac # What can change a robustness golden: the kernel and the crates a design is built with. case "$path" in - crates/kernel/*|crates/engine/*|crates/doc/*|crates/sketch/*|crates/geom/*|vendor/truck-*) goldens=true ;; + crates/kernel/*|crates/engine/*|crates/doc/*|crates/sketch/*|crates/geom/*|vendor/truck-*|tests/robustness/*) goldens=true ;; esac # What the Windows D3D12 jobs exercise: the GPU crate and its shaders, the app and # its startup, the viewport's wgpu glue, the vendored egui-wgpu, their scripts. @@ -199,20 +194,16 @@ jobs: tools/windows-*.ps1|.github/workflows/ci.yml|rust-toolchain*|.cargo/*) windows=true ;; esac done < "$RUNNER_TEMP/ci-paths" - if touches_code < "$RUNNER_TEMP/ci-paths"; then native=true; fi # A lockfile change that moves the graphics stack (wgpu, naga, egui, winit, windows). if [ "$windows" = false ] && grep -qxz 'Cargo.lock' "$RUNNER_TEMP/ci-paths" \ && git diff "$BASE_SHA...$HEAD_SHA" -- Cargo.lock \ | grep -Eq '^[ +-]name = "(wgpu[a-z_-]*|naga|egui[a-z_-]*|eframe|winit|windows[a-z_-]*|d3d12)"'; then windows=true fi - # Pull requests build and test the touched packages and their dependents. - python3 -I scripts/ci/affected.py --paths "$RUNNER_TEMP/ci-paths" > "$RUNNER_TEMP/ci-affected" - cat "$RUNNER_TEMP/ci-affected" - full=$(sed -n 's/^full=//p' "$RUNNER_TEMP/ci-affected") - packages=$(sed -n 's/^packages=//p' "$RUNNER_TEMP/ci-affected") - # Code changed but nothing was selected: be safe and test everything. - if [ "$native" = true ] && [ "$full" != true ] && [ -z "$packages" ]; then full=true; fi + # Pull requests build and test the touched packages and their dependents; nothing + # selected means no code changed. + select_packages "$RUNNER_TEMP/ci-paths" + if [ "$full" = true ] || [ -n "$packages" ]; then native=true; fi # The goldens are solidcraft-engine tests: its tests must be in the archive. if [ "$goldens" = true ] && [ "$full" != true ]; then case " $packages " in *" solidcraft-engine "*) ;; *) packages="$packages solidcraft-engine" ;; esac @@ -361,12 +352,14 @@ jobs: build-tests: name: Build tests - # Fail fast: the test archive (and so the shards) waits for the repository checks, the most - # common cheap failure; heavy jobs used to run on to the end beside a failed format check. + # Fail fast on pull requests: the test archive (and so the shards) waits for the repository + # checks, the most common cheap failure; heavy jobs used to run on to the end beside a failed + # format check. Main, nightly and Run workflow build regardless, so the action matrix and the + # property tests that hang off this job keep their signal. needs: [changes, checks] # The self-hosted shards (main and the merge queue) build from their warm build directories # instead: downloading the 3 GB archive took them longer than building. - if: needs.changes.outputs.native == 'true' && needs.changes.outputs.local != 'true' + if: ${{ !cancelled() && needs.changes.result == 'success' && needs.changes.outputs.native == 'true' && needs.changes.outputs.local != 'true' && (github.event_name != 'pull_request' || needs.checks.result == 'success') }} runs-on: ${{ (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository && (endsWith(format('{0}', github.event.pull_request.number), '7') || endsWith(format('{0}', github.event.pull_request.number), '8') || endsWith(format('{0}', github.event.pull_request.number), '9'))) && 'self-hosted-untrusted' || 'ubuntu-24.04' }} # Fork builds compile inside gVisor on shared boxes; give them room to finish and upload. timeout-minutes: ${{ (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository && (endsWith(format('{0}', github.event.pull_request.number), '7') || endsWith(format('{0}', github.event.pull_request.number), '8') || endsWith(format('{0}', github.event.pull_request.number), '9'))) && 90 || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository) && 60 || 45 }} @@ -413,7 +406,7 @@ jobs: tests: name: Native Linux tests (${{ matrix.shard }}/4) needs: [changes, checks, build-tests] - if: ${{ !cancelled() && needs.changes.outputs.native == 'true' && needs.checks.result == 'success' && (needs.changes.outputs.local == 'true' || needs.build-tests.result == 'success') }} + if: ${{ !cancelled() && needs.changes.outputs.native == 'true' && (github.event_name != 'pull_request' || needs.checks.result == 'success') && (needs.changes.outputs.local == 'true' || needs.build-tests.result == 'success') }} runs-on: ${{ needs.changes.outputs.local == 'true' && 'self-hosted-fast' || ((github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository && (endsWith(format('{0}', github.event.pull_request.number), '7') || endsWith(format('{0}', github.event.pull_request.number), '8') || endsWith(format('{0}', github.event.pull_request.number), '9'))) && 'self-hosted-untrusted' || 'ubuntu-24.04') }} timeout-minutes: 60 strategy: @@ -599,8 +592,7 @@ jobs: doc-tests: name: Doc tests - # After the repository checks pass (see Build tests). - needs: [changes, checks] + needs: changes if: needs.changes.outputs.doctests == 'true' runs-on: ${{ needs.changes.outputs.local == 'true' && 'self-hosted-fast' || 'ubuntu-24.04' }} timeout-minutes: 45 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index aeb2b314f..b490d3bbc 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -183,10 +183,12 @@ depend on wall-clock timing. **Ready pull requests test what they touch.** CI maps changed files to workspace packages and runs Clippy, the test build and tests for those and their dependents. The [package selector](scripts/ci/affected.py) and [CI workflow](.github/workflows/ci.yml) define -which changes require native checks; documentation, packaging and bot-script-only PRs can run -repository checks only. Workspace-wide changes, merge-queue groups, nightly runs and Run -workflow select the full workspace. A push to `main` reuses a successful merge-queue run for -the same commit; otherwise it runs the full suite. +which changes require native checks; documentation, packaging, other-workflow and bot-script-only +changes run the repository checks only, on pull requests and on `main`. Workspace-wide changes, +merge-queue groups, nightly runs and Run workflow select the full workspace. A push to `main` +reuses a successful merge-queue run for the same commit, and runs only the repository checks +when no code changed since the last push to `main` that passed; otherwise it runs the full +suite. Doc tests, reference tests and the Windows jobs run on `main` and nightly only. **CI shards the tests.** One job builds them into a cargo-nextest archive; two shards run on pull requests and four during full validation. Every test runs in its own process: don't rely diff --git a/scripts/ci/affected.py b/scripts/ci/affected.py index b826086c6..513db3c85 100644 --- a/scripts/ci/affected.py +++ b/scripts/ci/affected.py @@ -13,24 +13,37 @@ Prints and optionally appends to $GITHUB_OUTPUT: A changed file maps to the package whose directory holds it. The packages that depend on those (directly or not, dev-dependencies included) are added. Test data under tests/ maps to the -packages that read it, and a vendored crate (vendor/, a [patch] of a crates.io dependency) to the -packages that use it. Anything that can change every package, or that no package owns, selects -the full workspace. Only documentation and packaging files are ignored. +packages that read it, a vendored crate (vendor/, a [patch] of a crates.io dependency) to the +packages that use it, and a root file or folder a crate embeds to that crate. Anything that can +change every package, or that no package owns, selects the full workspace. Documentation, +packaging, the other workflows and the GitHub bots' scripts are ignored: when only those change, +nothing is selected and full is false, which CI reads as "no code changed" (on pull requests and +on pushes to main alike). """ import argparse import json import subprocess import sys -# Changes here can affect every package. -FULL_PREFIXES = (".cargo/", ".config/", ".github/", "scripts/") -FULL_FILES = ("Cargo.toml", "Cargo.lock") -# Changes here affect no code: documentation and packaging. -IGNORED_PREFIXES = ("docs/", "packaging/") +# Changes here can affect every package. The CI workflow itself is one; other workflows are not. +FULL_PREFIXES = (".cargo/", ".config/", "scripts/") +FULL_FILES = ("Cargo.toml", "Cargo.lock", ".github/workflows/ci.yml") +# Changes here affect no code: documentation, packaging, the other workflows and GitHub settings, +# and the GitHub bots' scripts (tested in the repository checks). Root *.md files too, unless +# embedded (below). +IGNORED_PREFIXES = ("docs/", "packaging/", ".github/", "scripts/claim/", "scripts/triage/") +IGNORED_FILES = ("vendor/README.md",) # Root files that a crate embeds (include_str!), so they are not ignorable documentation. -EMBEDDED = {"ATTRIBUTION.md": "solidcraft-ui-egui"} -# Asset folders that only some packages read: the UI embeds the catalogs, xtask checks them. -EMBEDDED_PREFIXES = {"assets/locales/": ("solidcraft-ui-egui", "xtask")} +EMBEDDED = { + "ATTRIBUTION.md": "solidcraft-ui-egui", + "LICENSE-MIT": "solidcraft-engine", + "LICENSE-APACHE": "solidcraft-engine", + "NOTICE": "solidcraft-engine", + "THIRD-PARTY-LICENSES.txt": "solidcraft-engine", +} +# Folders that only some packages read: the UI embeds the catalogs and xtask checks them; the MCP +# server's tests read the agent skills. +EMBEDDED_PREFIXES = {"assets/locales/": ("solidcraft-ui-egui", "xtask"), "skills/": ("solidcraft-mcp",)} # Test data and the package directories whose tests (or xtask) read it. Any other folder under # tests/ selects the full workspace. TEST_DATA = { @@ -38,7 +51,7 @@ TEST_DATA = { "tests/hole_matrix/": ("crates/engine/",), "tests/projection/": ("crates/engine/",), "tests/taper/": ("crates/engine/",), - "tests/oracle/": ("apps/solidcraft-cli/", "crates/kernel/", "xtask/"), + "tests/oracle/": ("apps/solidcraft-cli/", "xtask/"), "tests/action_matrix/": ("apps/solidcraft-cli/", "crates/engine/", "xtask/"), } # Vendored crates (vendor//, a [patch] of a crates.io dependency) and the dependency names @@ -102,12 +115,14 @@ def select(meta, paths): hit = set() for path in paths: - if path in FULL_FILES or path.startswith(FULL_PREFIXES) or path.startswith("rust-toolchain"): + if path in FULL_FILES or path.startswith("rust-toolchain"): + return True, [] + if path in IGNORED_FILES or path.startswith(IGNORED_PREFIXES): + continue + if path.startswith(FULL_PREFIXES): return True, [] owners = [d for d in by_dir if path.startswith(d)] if path.startswith("vendor/"): - if path == "vendor/README.md": - continue users = users_of(path.split("/")[1]) if not users: return True, [] @@ -124,7 +139,7 @@ def select(meta, paths): hit.add(EMBEDDED[path]) elif any(path.startswith(p) for p in EMBEDDED_PREFIXES): hit.update(next(v for p, v in EMBEDDED_PREFIXES.items() if path.startswith(p))) - elif path.startswith(IGNORED_PREFIXES) or ("/" not in path and path.endswith(".md")): + elif "/" not in path and path.endswith(".md"): continue else: return True, [] # not owned by any package diff --git a/scripts/ci/test_affected.py b/scripts/ci/test_affected.py index 6afb88066..34f6ded3e 100644 --- a/scripts/ci/test_affected.py +++ b/scripts/ci/test_affected.py @@ -52,6 +52,12 @@ class Synthetic(unittest.TestCase): def test_docs_only_selects_nothing(self): self.assertEqual(affected.select(SYNTH, ["docs/book/a.md", "README.md", "packaging/x.yml"]), (False, [])) + def test_no_code_paths_select_nothing(self): + # What CI reads as "no code changed", on pull requests and pushes to main alike. + for p in [".github/workflows/docker.yml", ".github/ISSUE_TEMPLATE/bug.yml", "scripts/claim/claim.js", + "scripts/triage/triage.test.js", "vendor/README.md", "SECURITY.md"]: + self.assertEqual(affected.select(SYNTH, [p]), (False, []), p) + class RealWorkspace(unittest.TestCase): @classmethod @@ -78,11 +84,21 @@ class RealWorkspace(unittest.TestCase): self.assertNotIn("solidcraft-kernel", pk) self.assertNotIn("solidcraft-render", pk) - def test_oracle_cases_select_the_cli_and_xtask(self): + def test_oracle_cases_select_the_cli_and_xtask_not_the_kernel(self): full, pk = affected.select(self.meta, ["tests/oracle/box/recipe.json"]) self.assertFalse(full) self.assertIn("solidcraft-cli", pk) self.assertIn("xtask", pk) + self.assertNotIn("solidcraft-kernel", pk) + + def test_embedded_root_files_select_their_crate(self): + for path, pkg in [("ATTRIBUTION.md", "solidcraft-ui-egui"), ("LICENSE-MIT", "solidcraft-engine"), + ("NOTICE", "solidcraft-engine"), ("THIRD-PARTY-LICENSES.txt", "solidcraft-engine"), + ("skills/solidcraft-modeling/SKILL.md", "solidcraft-mcp")]: + full, pk = affected.select(self.meta, [path]) + self.assertFalse(full, path) + self.assertIn(pkg, pk, path) + self.assertNotIn("solidcraft-kernel", pk, path) def test_unmapped_test_data_selects_full(self): self.assertEqual(affected.select(self.meta, ["tests/tools/x.json"]), (True, [])) From c41845e6d733416f8547cfdffb205a3cf4445950 Mon Sep 17 00:00:00 2001 From: jyviko <2501648+jyviko@users.noreply.github.com> Date: Mon, 19 Oct 2026 10:42:52 -0400 Subject: [PATCH 108/225] CI: carry only from this pull request's runs, compare patches verbatim From the review: git patch-id --stable ignores whitespace, so a conflict resolution that only respaced the change (inside a string, or Python indentation) counted as no change and was carried; --verbatim compares every byte. And a passing run is now taken only from this pull request (by number, or for a fork, where GitHub lists none on the run, by head repository and branch), not from another pull request with the same head commit. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QWhMwdqJYQKQq8RCLSL1LT --- .github/workflows/ci.yml | 6 +++++- scripts/ci/main_merge.py | 34 ++++++++++++++++++++++++++-------- scripts/ci/test_main_merge.py | 22 ++++++++++++++++++++++ 3 files changed, 53 insertions(+), 9 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bfea2f6a0..41ff9f7e3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -130,6 +130,9 @@ jobs: BASE_SHA: ${{ github.event.pull_request.base.sha }} HEAD_SHA: ${{ github.event.pull_request.head.sha }} PUSH_SHA: ${{ github.sha }} + PR_NUMBER: ${{ github.event.pull_request.number }} + HEAD_REPO: ${{ github.event.pull_request.head.repo.full_name }} + HEAD_REF: ${{ github.event.pull_request.head.ref }} REPO: ${{ github.repository }} APPROVED: ${{ contains(github.event.pull_request.labels.*.name, 'approved-for-ci') }} GH_TOKEN: ${{ github.token }} @@ -236,7 +239,8 @@ jobs: # touched the pull request's files, and each restarted the whole run. carried= if [ "$EVENT_NAME" = pull_request ] && [ "$native" = true ]; then - carried=$(python3 -I scripts/ci/main_merge.py --base "$BASE_SHA" --head "$HEAD_SHA" --repo "$REPO" | sed -n 's/^carried=//p') + carried=$(python3 -I scripts/ci/main_merge.py --base "$BASE_SHA" --head "$HEAD_SHA" --repo "$REPO" \ + --pr "$PR_NUMBER" --head-repo "$HEAD_REPO" --head-ref "$HEAD_REF" | sed -n 's/^carried=//p') if [ -n "$carried" ]; then echo "Only a merge of main into a change that passed in $carried: repository checks only." native=false diff --git a/scripts/ci/main_merge.py b/scripts/ci/main_merge.py index 825701dfa..ca8644aae 100644 --- a/scripts/ci/main_merge.py +++ b/scripts/ci/main_merge.py @@ -1,14 +1,18 @@ #!/usr/bin/env python3 """Is this pull request push only a merge of main into a change that already passed CI? - python3 -I scripts/ci/main_merge.py --base BASE_SHA --head HEAD_SHA --repo OWNER/NAME + python3 -I scripts/ci/main_merge.py --base BASE_SHA --head HEAD_SHA --repo OWNER/NAME \ + --pr NUMBER --head-repo OWNER/NAME --head-ref BRANCH Prints `carried=` when all of these hold, else `carried=`: - HEAD is a merge commit whose second parent is on main (an ancestor of BASE): "Merge branch 'main'", or GitHub's Update branch button; - - the pull request's own change is the same before and after the merge (equal `git patch-id`), - so the merge resolved no conflict and brought nothing into the change itself; - - a ci.yml run of the change before the merge passed with the test shards. When that change was + - the pull request's own change is the same before and after the merge (equal `git patch-id + --verbatim`, whitespace included), so the merge resolved no conflict and brought nothing into + the change itself; + - a ci.yml run of this pull request (by number, or for a fork, where GitHub lists no pull + request on the run, by head repository and branch) for the change before the merge passed + with the test shards. When that change was itself only a merge of main (a run that carried, its shards skipped), the walk goes on down the first parents, through at most MAX_CHAIN merges, to the run where the shards ran. @@ -38,7 +42,8 @@ def patch_id(a, b): diff = subprocess.run(["git", "diff", "--no-renames", a, b], capture_output=True, check=True).stdout if not diff.strip(): return "" - out = subprocess.run(["git", "patch-id", "--stable"], input=diff, capture_output=True, check=True).stdout + # --verbatim: --stable ignores whitespace, which matters in strings and indentation. + out = subprocess.run(["git", "patch-id", "--verbatim"], input=diff, capture_output=True, check=True).stdout return out.split()[0].decode() if out.split() else "" @@ -74,10 +79,20 @@ def get(url, token): return json.load(r) -def passing_run(repo, sha, token): - """URL of a successful pull request ci.yml run of `sha` whose test shards all passed.""" +def same_pull_request(run, pr, head_repo, head_ref): + """Whether a workflow run belongs to this pull request, not another one with the same head.""" + numbers = [p.get("number") for p in run.get("pull_requests") or []] + if numbers: + return pr in numbers + return (run.get("head_repository") or {}).get("full_name") == head_repo and run.get("head_branch") == head_ref + + +def passing_run(repo, sha, token, pr, head_repo, head_ref): + """URL of a successful ci.yml run of this pull request at `sha` whose test shards all passed.""" runs = get(f"{API}/repos/{repo}/actions/workflows/ci.yml/runs?head_sha={sha}&event=pull_request&status=success&per_page=10", token) for run in runs.get("workflow_runs", []): + if not same_pull_request(run, pr, head_repo, head_ref): + continue jobs = get(f"{API}/repos/{repo}/actions/runs/{run['id']}/jobs?per_page=100", token).get("jobs", []) shards = [j for j in jobs if j.get("name", "").startswith(SHARD_PREFIX)] if shards and all(j.get("conclusion") == "success" for j in shards): @@ -90,12 +105,15 @@ def main(): ap.add_argument("--base", required=True) ap.add_argument("--head", required=True) ap.add_argument("--repo", required=True) + ap.add_argument("--pr", required=True, type=int) + ap.add_argument("--head-repo", required=True) + ap.add_argument("--head-ref", required=True) a = ap.parse_args() carried = "" try: token = os.environ.get("GH_TOKEN", "") for change in merge_chain(a.base, a.head) if token else []: - carried = passing_run(a.repo, change, token) + carried = passing_run(a.repo, change, token, a.pr, a.head_repo, a.head_ref) if carried: print(f"{a.head} merges main into {change}, which passed: {carried}", file=sys.stderr) break diff --git a/scripts/ci/test_main_merge.py b/scripts/ci/test_main_merge.py index 0fde86d16..163f72648 100644 --- a/scripts/ci/test_main_merge.py +++ b/scripts/ci/test_main_merge.py @@ -39,6 +39,18 @@ class Repo: LINES = "".join(f"line {i}\n" for i in range(40)) +class SamePullRequest(unittest.TestCase): + def test_listed_pull_request_must_match(self): + self.assertTrue(main_merge.same_pull_request({"pull_requests": [{"number": 7}]}, 7, "x/y", "b")) + self.assertFalse(main_merge.same_pull_request({"pull_requests": [{"number": 8}]}, 7, "x/y", "b")) + + def test_fork_run_matches_by_head_repository_and_branch(self): + run = {"pull_requests": [], "head_repository": {"full_name": "fork/solidcraft"}, "head_branch": "fix"} + self.assertTrue(main_merge.same_pull_request(run, 7, "fork/solidcraft", "fix")) + self.assertFalse(main_merge.same_pull_request(run, 7, "fork/solidcraft", "other")) + self.assertFalse(main_merge.same_pull_request(run, 7, "someone/solidcraft", "fix")) + + class MergeOfMain(unittest.TestCase): def setUp(self): self.tmp = tempfile.TemporaryDirectory() @@ -98,6 +110,16 @@ class MergeOfMain(unittest.TestCase): head = self.merge_main() self.assertIsNone(main_merge.merge_of_main(base, head)) + def test_whitespace_change_in_the_change_is_not_carried(self): + # A conflict resolution that only respaces the change's own line still changes the change. + base = self.main_commit(**{"a.txt": LINES.replace("line 5\n", "line 5 on main\n")}) + subprocess.run(["git", "merge", "-q", "main"], cwd=self.tmp.name, capture_output=True) + self.r.write("a.txt", LINES.replace("line 5\n", "line five\n")) + self.r.git("add", "-A") + self.r.git("commit", "-q", "--no-edit") + head = self.r.git("rev-parse", "HEAD") + self.assertIsNone(main_merge.merge_of_main(base, head)) + def test_ordinary_commit_is_not_carried(self): head = self.r.commit("more", **{"a.txt": LINES.replace("line 5\n", "line 5b\n")}) base = self.r.git("rev-parse", "main") From f1b721b00c9fa3e630ddadcc41cdc3ea11a60d90 Mon Sep 17 00:00:00 2001 From: jyviko <2501648+jyviko@users.noreply.github.com> Date: Mon, 19 Oct 2026 10:43:07 -0400 Subject: [PATCH 109/225] CI: Docker rebuilds for ATTRIBUTION.md; generated files follow licence inputs From the review: the web app embeds ATTRIBUTION.md, so the Docker image's Markdown exclusion now keeps it; and THIRD-PARTY-LICENSES.txt also reads the vendored crates' licence files and the fonts' OFL texts, so changes there regenerate it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QWhMwdqJYQKQq8RCLSL1LT --- .github/workflows/docker.yml | 4 +++- .github/workflows/generated.yml | 7 +++++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 08db7fe5d..0e7d17e09 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -16,7 +16,9 @@ on: branches: [main] # The image holds the web app only: documentation, test data and the GitHub bots' scripts can't # change it, so a push touching only those builds nothing (edge stays at the last code change). - paths-ignore: ["docs/**", "**/*.md", "tests/**", "scripts/claim/**", "scripts/triage/**"] + # ATTRIBUTION.md is the exception among the Markdown files: the app embeds it (Help, About). + # The last matching pattern wins. + paths: ["**", "!docs/**", "!**/*.md", "ATTRIBUTION.md", "!tests/**", "!scripts/claim/**", "!scripts/triage/**"] release: types: [published] pull_request: diff --git a/.github/workflows/generated.yml b/.github/workflows/generated.yml index db4a3d4c1..4f7b62e61 100644 --- a/.github/workflows/generated.yml +++ b/.github/workflows/generated.yml @@ -6,11 +6,14 @@ name: Generated files on: push: branches: [main] - # THIRD-PARTY-LICENSES.txt follows the manifests and the lockfile; docs/features.md follows the - # command registry (crates/engine), read through solidcraft-cli. Other pushes regenerate nothing. + # THIRD-PARTY-LICENSES.txt follows the manifests, the lockfile, the vendored crates' licence + # files and the fonts' licences; docs/features.md follows the command registry (crates/engine), + # read through solidcraft-cli. Other pushes regenerate nothing. paths: - "Cargo.lock" - "**/Cargo.toml" + - "vendor/**" + - "assets/fonts/**" - "crates/engine/**" - "apps/solidcraft-cli/**" - "xtask/**" From fd5795b5ad5dddf6354b0264718d17690daf7b7b Mon Sep 17 00:00:00 2001 From: jyviko <2501648+jyviko@users.noreply.github.com> Date: Mon, 19 Oct 2026 10:43:23 -0400 Subject: [PATCH 110/225] Contributing: catch up with main only when pushing anyway or on a conflict From the review: the guidance said a pull request's run tests it merged with the latest main, which is only main as of that run; a break between two pull requests that land close together shows up in main's own run. It also forbade rebasing. Now: don't push only to catch up; when you push a change anyway or GitHub reports a conflict, rebase onto main (--force-with-lease on your own branch) or merge it in once. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QWhMwdqJYQKQq8RCLSL1LT --- AGENTS.md | 23 ++++++++++++----------- CONTRIBUTING.md | 17 +++++++++-------- 2 files changed, 21 insertions(+), 19 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 7c47f7833..6c01a3ce0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -103,8 +103,8 @@ People trust SolidCraft with their designs; a crash loses their work. **This out - **Publishing**: `origin` is github.com/bherbruck/solidcraft. Changes land through **pull requests**: push a branch, open a PR, and let GitHub CI run. Maintainers (and agents working for them) may merge their own PR as soon as CI is green (`gh pr merge --squash`); a trivial fix (docs, typos) - may be merged right away. Keep each PR to one topic, merge `main` into it only when it - conflicts, and never force-push `main`. Never commit `plan/`, build dirs (`target*/`) or + may be merged right away. Keep each PR to one topic, bring `main` into it only + when you push a change anyway or it conflicts, and never force-push `main`. Never commit `plan/`, build dirs (`target*/`) or generated reference data; check `git ls-files` before pushing. - **Never break wasm**: everything below the apps must build for `wasm32-unknown-unknown` (`cargo xtask wasm`, part of `cargo xtask ci`). @@ -124,15 +124,16 @@ People trust SolidCraft with their designs; a crash loses their work. **This out - Use a small public-safe example and check for private designs, paths, account details or other sensitive content before sharing. Attach media to the issue/PR or link to an accessible recording; do not commit generated screenshots or videos just to provide review evidence. -- Throughout the work and before handoff, check the relevant PR's merge status. Don't bring - `main` into an open PR to keep it current (no merge of `main`, no Update branch, no rebase): - CI already tests the PR merged with the latest `main`, and every update restarts the whole - run. Only when GitHub reports a conflict, merge `main` in once and resolve it without - discarding others' work; never force-push. Don't re-run CI on an unchanged commit: a real - failure fails again. Re-run only a job that runner trouble cancelled, with "Re-run failed - jobs". Report the PR state you checked and any conflicts resolved. If a PR remains open, - keep monitoring it while the task is active and make its pending status clear at handoff; - do not claim it merged without checking. +- Throughout the work and before handoff, check the relevant PR's merge status. Don't push to + an open PR only to catch up with `main` (no merge of `main`, no Update branch, no rebase for + that alone): every push restarts the whole CI run, and `main`'s own run catches what lands in + between, to be fixed forward. When you push a change anyway, or GitHub reports a conflict, + rebase onto the latest `main` (push your own branch with `--force-with-lease`) or merge `main` + in once, and resolve conflicts without discarding others' work; never force-push `main`. + Don't re-run CI on an unchanged commit: a real failure fails again. Re-run only a job that + runner trouble cancelled, with "Re-run failed jobs". Report the PR state you checked and any + conflicts resolved. If a PR remains open, keep monitoring it while the task is active and + make its pending status clear at handoff; do not claim it merged without checking. ## Claim = a draft PR - Before working on issue #N, check nobody has it: `gh pr list -R bherbruck/solidcraft --state open --search "#N"`. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b490d3bbc..d3b01c62c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -316,14 +316,15 @@ Changes with no useful observable behavior do not need screenshot or video evide small example without private designs or sensitive details; attach the media or link to an accessible recording rather than committing generated review artifacts. -Keep an eye on your PR's status, but don't bring `main` into it to keep it current: no merge of -`main`, no Update branch button, no rebase. CI already tests your PR merged with the latest -`main`, and every update restarts the whole run for everyone waiting behind it. Only when GitHub -reports a conflict, merge `main` in once and resolve it without losing others' changes; never -force-push. Don't re-run CI on an unchanged commit either: a real failure fails again. Re-run -only a job that runner trouble cancelled, with "Re-run failed jobs". While a task remains active, -follow an open PR through its status changes; at handoff, clearly identify anything still -awaiting merge. +Keep an eye on your PR's status, but don't push to it only to catch up with `main` (no merge of +`main`, no Update branch button, no rebase for that alone): every push restarts the whole CI +run for everyone waiting behind it, and `main`'s own run catches what lands in between. When you +push a change anyway, or GitHub reports a conflict, rebase onto the latest `main` (push your +branch with `--force-with-lease`) or merge `main` in once, and resolve conflicts without losing +others' changes. Don't re-run CI on an unchanged commit either: a real failure fails again. +Re-run only a job that runner trouble cancelled, with "Re-run failed jobs". While a task remains +active, follow an open PR through its status changes; at handoff, clearly identify anything +still awaiting merge. Much of SolidCraft so far was written by AI coding agents (Claude) working in parallel, each owning one area, with a human setting direction and reporting bugs. Their working notes are in From f945e79278ab18713d474de10e83445b4dd41199 Mon Sep 17 00:00:00 2001 From: jyviko <2501648+jyviko@users.noreply.github.com> Date: Mon, 19 Oct 2026 08:49:40 -0400 Subject: [PATCH 111/225] CI: run the GitHub-hosted Linux jobs on Blacksmith again, sized per job Re-applies #2237 (reverted in #2277 while the Blacksmith account awaited verification) on today's ci.yml: every ubuntu-24.04 job or fallback runs on blacksmith-vcpu-ubuntu-2404, sized as #2237 did (quick-compile, new since, gets 8), and steps that asked runner.environment now tell our own machines apart by runner name, since Blacksmith runners report 'self-hosted' too. The trusted self-hosted routing and the fork routing are unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QWhMwdqJYQKQq8RCLSL1LT --- .github/actionlint.yaml | 5 ++++ .github/workflows/ci.yml | 62 ++++++++++++++++++++++------------------ 2 files changed, 39 insertions(+), 28 deletions(-) diff --git a/.github/actionlint.yaml b/.github/actionlint.yaml index 8f7fae7ae..141df1e27 100644 --- a/.github/actionlint.yaml +++ b/.github/actionlint.yaml @@ -2,3 +2,8 @@ self-hosted-runner: labels: - self-hosted-fast - self-hosted-light + # Blacksmith (Ubuntu 24.04 only; see the top of workflows/ci.yml). + - blacksmith-2vcpu-ubuntu-2404 + - blacksmith-4vcpu-ubuntu-2404 + - blacksmith-8vcpu-ubuntu-2404 + - blacksmith-16vcpu-ubuntu-2404 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 41ff9f7e3..68e6e305d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -40,8 +40,14 @@ # self-hosted machine has a newer glibc, so its binaries wouldn't start on ubuntu-24.04, while the # archive runs there unchanged (same /home/runner/work checkout path). The self-hosted shards # (main and the merge queue) skip the archive and build the tests in their warm build directories. -# Fork pull requests, the nightly run and Run workflow use GitHub's runners only; the self-hosted -# runners refuse any other job. +# Fork pull requests, the nightly run and Run workflow never use our self-hosted runners; the +# self-hosted runners refuse any other job. +# "GitHub's runners" above means Blacksmith's Ubuntu 24.04 runners (blacksmith-vcpu-ubuntu-2404, +# sized per job: 16 vCPU for Build tests and Clippy, 8 for compiles, test shards, doc and +# reference tests, 4 for the light checks, 2 for Select checks and ci). Same image family as +# ubuntu-24.04, so the test archive and recorded goldens behave the same. Windows jobs stay on +# windows-latest. Blacksmith runners report runner.environment == 'self-hosted' as well, so steps +# tell our own machines apart by runner name (minisforum-*, ci-box-*). name: CI on: @@ -82,7 +88,7 @@ jobs: dependency-advisories: name: Dependency advisories if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' - runs-on: ubuntu-24.04 + runs-on: blacksmith-4vcpu-ubuntu-2404 timeout-minutes: 20 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -98,7 +104,7 @@ jobs: # approved-for-ci either (the same skip, for the same reason). if: (github.event_name != 'pull_request' || !github.event.pull_request.draft) && (github.event.action != 'labeled' || github.event.label.name == 'approved-for-ci') # Trusted runs (see the top of this file) use the self-hosted runners. - runs-on: ${{ (github.event_name == 'merge_group' || (github.event_name == 'push' && github.ref == 'refs/heads/main') || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository)) && 'self-hosted-light' || 'ubuntu-24.04' }} + runs-on: ${{ (github.event_name == 'merge_group' || (github.event_name == 'push' && github.ref == 'refs/heads/main') || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository)) && 'self-hosted-light' || 'blacksmith-2vcpu-ubuntu-2404' }} permissions: contents: read # To ask whether the merge queue already tested a commit pushed to main. @@ -118,7 +124,7 @@ jobs: carried: ${{ steps.paths.outputs.carried }} # The fast self-hosted runners are kept for main and the merge queue (the pre-merge gate); # pull requests, same-repo ones included, take the GitHub-hosted or untrusted paths. - local: ${{ runner.environment == 'self-hosted' && github.event_name != 'pull_request' }} + local: ${{ (startsWith(runner.name, 'minisforum-') || startsWith(runner.name, 'ci-box-')) && github.event_name != 'pull_request' }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -263,19 +269,19 @@ jobs: checks: name: Format and repository checks if: (github.event_name != 'pull_request' || !github.event.pull_request.draft) && (github.event.action != 'labeled' || github.event.label.name == 'approved-for-ci') - runs-on: ${{ (github.event_name == 'merge_group' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) && 'self-hosted-fast' || 'ubuntu-24.04' }} + runs-on: ${{ (github.event_name == 'merge_group' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) && 'self-hosted-fast' || 'blacksmith-4vcpu-ubuntu-2404' }} timeout-minutes: 15 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Warm build directory (self-hosted runner) - if: runner.environment == 'self-hosted' && !(github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository) + if: (startsWith(runner.name, 'minisforum-') || startsWith(runner.name, 'ci-box-')) && !(github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository) run: scripts/ci/warm-target.sh checks - uses: dtolnay/rust-toolchain@stable with: components: rustfmt # The trusted self-hosted runners keep their build directory and Cargo home instead; the # untrusted ones (fork pull requests) start empty and restore main's cache, read-only. - - if: runner.environment == 'github-hosted' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository) + - if: ${{ !(startsWith(runner.name, 'minisforum-') || startsWith(runner.name, 'ci-box-')) || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository) }} uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 with: key: repo-checks @@ -308,14 +314,14 @@ jobs: name: Quick compile needs: changes if: needs.changes.outputs.quick == 'true' - runs-on: ${{ needs.changes.outputs.local == 'true' && 'self-hosted-light' || 'ubuntu-24.04' }} + runs-on: ${{ needs.changes.outputs.local == 'true' && 'self-hosted-light' || 'blacksmith-8vcpu-ubuntu-2404' }} timeout-minutes: 30 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Size parallel compiles to the job's memory run: scripts/ci/build-jobs.sh - uses: dtolnay/rust-toolchain@stable - - if: runner.environment == 'github-hosted' + - if: ${{ !(startsWith(runner.name, 'minisforum-') || startsWith(runner.name, 'ci-box-')) }} uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 with: key: quick-compile @@ -327,19 +333,19 @@ jobs: name: Native Linux Clippy needs: changes if: needs.changes.outputs.native == 'true' - runs-on: ${{ needs.changes.outputs.local == 'true' && 'self-hosted-fast' || 'ubuntu-24.04' }} + runs-on: ${{ needs.changes.outputs.local == 'true' && 'self-hosted-fast' || 'blacksmith-16vcpu-ubuntu-2404' }} timeout-minutes: 30 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Warm build directory (self-hosted runner) - if: runner.environment == 'self-hosted' && !(github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository) + if: (startsWith(runner.name, 'minisforum-') || startsWith(runner.name, 'ci-box-')) && !(github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository) run: scripts/ci/warm-target.sh clippy - uses: dtolnay/rust-toolchain@stable with: components: clippy # The trusted self-hosted runners keep their build directory and Cargo home instead; the # untrusted ones (fork pull requests) start empty and restore main's cache, read-only. - - if: runner.environment == 'github-hosted' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository) + - if: ${{ !(startsWith(runner.name, 'minisforum-') || startsWith(runner.name, 'ci-box-')) || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository) }} uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 with: key: native-clippy @@ -364,7 +370,7 @@ jobs: # The self-hosted shards (main and the merge queue) build from their warm build directories # instead: downloading the 3 GB archive took them longer than building. if: ${{ !cancelled() && needs.changes.result == 'success' && needs.changes.outputs.native == 'true' && needs.changes.outputs.local != 'true' && (github.event_name != 'pull_request' || needs.checks.result == 'success') }} - runs-on: ${{ (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository && (endsWith(format('{0}', github.event.pull_request.number), '7') || endsWith(format('{0}', github.event.pull_request.number), '8') || endsWith(format('{0}', github.event.pull_request.number), '9'))) && 'self-hosted-untrusted' || 'ubuntu-24.04' }} + runs-on: ${{ (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository && (endsWith(format('{0}', github.event.pull_request.number), '7') || endsWith(format('{0}', github.event.pull_request.number), '8') || endsWith(format('{0}', github.event.pull_request.number), '9'))) && 'self-hosted-untrusted' || 'blacksmith-16vcpu-ubuntu-2404' }} # Fork builds compile inside gVisor on shared boxes; give them room to finish and upload. timeout-minutes: ${{ (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository && (endsWith(format('{0}', github.event.pull_request.number), '7') || endsWith(format('{0}', github.event.pull_request.number), '8') || endsWith(format('{0}', github.event.pull_request.number), '9'))) && 90 || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository) && 60 || 45 }} env: @@ -411,7 +417,7 @@ jobs: name: Native Linux tests (${{ matrix.shard }}/4) needs: [changes, checks, build-tests] if: ${{ !cancelled() && needs.changes.outputs.native == 'true' && (github.event_name != 'pull_request' || needs.checks.result == 'success') && (needs.changes.outputs.local == 'true' || needs.build-tests.result == 'success') }} - runs-on: ${{ needs.changes.outputs.local == 'true' && 'self-hosted-fast' || ((github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository && (endsWith(format('{0}', github.event.pull_request.number), '7') || endsWith(format('{0}', github.event.pull_request.number), '8') || endsWith(format('{0}', github.event.pull_request.number), '9'))) && 'self-hosted-untrusted' || 'ubuntu-24.04') }} + runs-on: ${{ needs.changes.outputs.local == 'true' && 'self-hosted-fast' || ((github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository && (endsWith(format('{0}', github.event.pull_request.number), '7') || endsWith(format('{0}', github.event.pull_request.number), '8') || endsWith(format('{0}', github.event.pull_request.number), '9'))) && 'self-hosted-untrusted' || 'blacksmith-8vcpu-ubuntu-2404') }} timeout-minutes: 60 strategy: fail-fast: false @@ -428,7 +434,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Install a software Vulkan driver (lavapipe) # Preinstalled on the self-hosted runner, which has no sudo. - if: runner.environment == 'github-hosted' + if: ${{ !(startsWith(runner.name, 'minisforum-') || startsWith(runner.name, 'ci-box-')) }} run: | sudo apt-get update sudo apt-get install -y --no-install-recommends mesa-vulkan-drivers libvulkan1 @@ -510,7 +516,7 @@ jobs: name: Action matrix (${{ matrix.shard }}/16) needs: build-tests if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' - runs-on: ubuntu-24.04 + runs-on: blacksmith-4vcpu-ubuntu-2404 timeout-minutes: 55 strategy: fail-fast: false @@ -552,7 +558,7 @@ jobs: name: Action matrix determinism needs: build-tests if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' - runs-on: ubuntu-24.04 + runs-on: blacksmith-4vcpu-ubuntu-2404 timeout-minutes: 45 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -574,7 +580,7 @@ jobs: name: Property tests (many cases) needs: build-tests if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' - runs-on: ubuntu-24.04 + runs-on: blacksmith-4vcpu-ubuntu-2404 timeout-minutes: 60 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -598,7 +604,7 @@ jobs: name: Doc tests needs: changes if: needs.changes.outputs.doctests == 'true' - runs-on: ${{ needs.changes.outputs.local == 'true' && 'self-hosted-fast' || 'ubuntu-24.04' }} + runs-on: ${{ needs.changes.outputs.local == 'true' && 'self-hosted-fast' || 'blacksmith-8vcpu-ubuntu-2404' }} timeout-minutes: 45 env: CARGO_INCREMENTAL: "0" @@ -610,12 +616,12 @@ jobs: - name: Size parallel compiles to the job's memory run: scripts/ci/build-jobs.sh - name: Warm build directory (self-hosted runner) - if: runner.environment == 'self-hosted' && !(github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository) + if: (startsWith(runner.name, 'minisforum-') || startsWith(runner.name, 'ci-box-')) && !(github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository) run: scripts/ci/warm-target.sh doc-tests - uses: dtolnay/rust-toolchain@stable # The trusted self-hosted runners keep their build directory and Cargo home instead; the # untrusted ones (fork pull requests) start empty and restore main's cache, read-only. - - if: runner.environment == 'github-hosted' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository) + - if: ${{ !(startsWith(runner.name, 'minisforum-') || startsWith(runner.name, 'ci-box-')) || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository) }} uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 with: key: doc-tests @@ -651,7 +657,7 @@ jobs: name: Reference tests needs: changes if: needs.changes.outputs.oracle == 'true' - runs-on: ${{ needs.changes.outputs.local == 'true' && 'self-hosted-fast' || ((github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository && (endsWith(format('{0}', github.event.pull_request.number), '7') || endsWith(format('{0}', github.event.pull_request.number), '8') || endsWith(format('{0}', github.event.pull_request.number), '9'))) && 'self-hosted-untrusted' || 'ubuntu-24.04') }} + runs-on: ${{ needs.changes.outputs.local == 'true' && 'self-hosted-fast' || ((github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository && (endsWith(format('{0}', github.event.pull_request.number), '7') || endsWith(format('{0}', github.event.pull_request.number), '8') || endsWith(format('{0}', github.event.pull_request.number), '9'))) && 'self-hosted-untrusted' || 'blacksmith-8vcpu-ubuntu-2404') }} timeout-minutes: 60 env: CARGO_INCREMENTAL: "0" @@ -663,12 +669,12 @@ jobs: - name: Size parallel compiles to the job's memory run: scripts/ci/build-jobs.sh - name: Warm build directory (self-hosted runner) - if: runner.environment == 'self-hosted' && !(github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository) + if: (startsWith(runner.name, 'minisforum-') || startsWith(runner.name, 'ci-box-')) && !(github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository) run: scripts/ci/warm-target.sh oracle - uses: dtolnay/rust-toolchain@stable # The trusted self-hosted runners keep their build directory and Cargo home instead; the # untrusted ones (fork pull requests) start empty and restore main's cache, read-only. - - if: runner.environment == 'github-hosted' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository) + - if: ${{ !(startsWith(runner.name, 'minisforum-') || startsWith(runner.name, 'ci-box-')) || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository) }} uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 with: key: oracle @@ -752,7 +758,7 @@ jobs: name: ${{ github.event.action == 'labeled' && github.event.label.name != 'approved-for-ci' && 'ci (ignored label)' || 'ci' }} needs: [changes, checks, quick-compile, clippy, build-tests, tests, doc-tests, oracle, windows-fxc, windows-startup] if: always() && (github.event_name != 'pull_request' || !github.event.pull_request.draft) && (github.event.action != 'labeled' || github.event.label.name == 'approved-for-ci') - runs-on: ${{ needs.changes.outputs.local == 'true' && 'self-hosted-light' || 'ubuntu-24.04' }} + runs-on: ${{ needs.changes.outputs.local == 'true' && 'self-hosted-light' || 'blacksmith-2vcpu-ubuntu-2404' }} steps: - name: Verify required checks env: @@ -805,7 +811,7 @@ jobs: wasm: name: Compile WebAssembly (manual) if: github.event_name == 'workflow_dispatch' && inputs.cross_compile - runs-on: ubuntu-24.04 + runs-on: blacksmith-8vcpu-ubuntu-2404 timeout-minutes: 30 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -821,7 +827,7 @@ jobs: riscv64-gates: name: Compile RISC-V (manual) if: github.event_name == 'workflow_dispatch' && inputs.cross_compile - runs-on: ubuntu-24.04 + runs-on: blacksmith-8vcpu-ubuntu-2404 timeout-minutes: 30 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 From 247cf357b6ec054ec69982e5118eef0edb84ccfb Mon Sep 17 00:00:00 2001 From: jyviko <2501648+jyviko@users.noreply.github.com> Date: Mon, 19 Oct 2026 12:37:24 -0400 Subject: [PATCH 112/225] CI: steps tell where they run from the routing, not the runner's name Blacksmith runners report runner.environment == 'self-hosted', and a list of our machines' name prefixes breaks when a box is added or renamed. Select checks already decides where each job runs; its local and untrusted outputs (and the trusted-run condition in the repository checks) now drive the warm build directory, cache and lavapipe steps. Same results as before on every event. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QWhMwdqJYQKQq8RCLSL1LT --- .github/workflows/ci.yml | 30 +++++++++++++++++------------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 68e6e305d..95c60a0ea 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -47,7 +47,8 @@ # reference tests, 4 for the light checks, 2 for Select checks and ci). Same image family as # ubuntu-24.04, so the test archive and recorded goldens behave the same. Windows jobs stay on # windows-latest. Blacksmith runners report runner.environment == 'self-hosted' as well, so steps -# tell our own machines apart by runner name (minisforum-*, ci-box-*). +# don't ask the runner where they run: they read the routing that chose it (Select checks' `local` +# and `untrusted` outputs, or the trusted-run condition in jobs that don't need Select checks). name: CI on: @@ -123,8 +124,11 @@ jobs: # The passing run a merge of main carries forward (its URL), when this push is only that. carried: ${{ steps.paths.outputs.carried }} # The fast self-hosted runners are kept for main and the merge queue (the pre-merge gate); - # pull requests, same-repo ones included, take the GitHub-hosted or untrusted paths. - local: ${{ (startsWith(runner.name, 'minisforum-') || startsWith(runner.name, 'ci-box-')) && github.event_name != 'pull_request' }} + # pull requests, same-repo ones included, take the GitHub-hosted or untrusted paths. Steps + # read these two to know where their job runs (see the top of this file). + local: ${{ github.event_name == 'merge_group' || (github.event_name == 'push' && github.ref == 'refs/heads/main') }} + # Fork pull requests whose Linux jobs run on the self-hosted-untrusted runners. + untrusted: ${{ (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository) && (endsWith(format('{0}', github.event.pull_request.number), '7') || endsWith(format('{0}', github.event.pull_request.number), '8') || endsWith(format('{0}', github.event.pull_request.number), '9')) }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -274,14 +278,14 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Warm build directory (self-hosted runner) - if: (startsWith(runner.name, 'minisforum-') || startsWith(runner.name, 'ci-box-')) && !(github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository) + if: github.event_name == 'merge_group' || (github.event_name == 'push' && github.ref == 'refs/heads/main') run: scripts/ci/warm-target.sh checks - uses: dtolnay/rust-toolchain@stable with: components: rustfmt # The trusted self-hosted runners keep their build directory and Cargo home instead; the # untrusted ones (fork pull requests) start empty and restore main's cache, read-only. - - if: ${{ !(startsWith(runner.name, 'minisforum-') || startsWith(runner.name, 'ci-box-')) || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository) }} + - if: ${{ !(github.event_name == 'merge_group' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) }} uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 with: key: repo-checks @@ -321,7 +325,7 @@ jobs: - name: Size parallel compiles to the job's memory run: scripts/ci/build-jobs.sh - uses: dtolnay/rust-toolchain@stable - - if: ${{ !(startsWith(runner.name, 'minisforum-') || startsWith(runner.name, 'ci-box-')) }} + - if: needs.changes.outputs.local != 'true' uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 with: key: quick-compile @@ -338,14 +342,14 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Warm build directory (self-hosted runner) - if: (startsWith(runner.name, 'minisforum-') || startsWith(runner.name, 'ci-box-')) && !(github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository) + if: needs.changes.outputs.local == 'true' run: scripts/ci/warm-target.sh clippy - uses: dtolnay/rust-toolchain@stable with: components: clippy # The trusted self-hosted runners keep their build directory and Cargo home instead; the # untrusted ones (fork pull requests) start empty and restore main's cache, read-only. - - if: ${{ !(startsWith(runner.name, 'minisforum-') || startsWith(runner.name, 'ci-box-')) || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository) }} + - if: needs.changes.outputs.local != 'true' uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 with: key: native-clippy @@ -434,7 +438,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Install a software Vulkan driver (lavapipe) # Preinstalled on the self-hosted runner, which has no sudo. - if: ${{ !(startsWith(runner.name, 'minisforum-') || startsWith(runner.name, 'ci-box-')) }} + if: needs.changes.outputs.local != 'true' && needs.changes.outputs.untrusted != 'true' run: | sudo apt-get update sudo apt-get install -y --no-install-recommends mesa-vulkan-drivers libvulkan1 @@ -616,12 +620,12 @@ jobs: - name: Size parallel compiles to the job's memory run: scripts/ci/build-jobs.sh - name: Warm build directory (self-hosted runner) - if: (startsWith(runner.name, 'minisforum-') || startsWith(runner.name, 'ci-box-')) && !(github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository) + if: needs.changes.outputs.local == 'true' run: scripts/ci/warm-target.sh doc-tests - uses: dtolnay/rust-toolchain@stable # The trusted self-hosted runners keep their build directory and Cargo home instead; the # untrusted ones (fork pull requests) start empty and restore main's cache, read-only. - - if: ${{ !(startsWith(runner.name, 'minisforum-') || startsWith(runner.name, 'ci-box-')) || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository) }} + - if: needs.changes.outputs.local != 'true' uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 with: key: doc-tests @@ -669,12 +673,12 @@ jobs: - name: Size parallel compiles to the job's memory run: scripts/ci/build-jobs.sh - name: Warm build directory (self-hosted runner) - if: (startsWith(runner.name, 'minisforum-') || startsWith(runner.name, 'ci-box-')) && !(github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository) + if: needs.changes.outputs.local == 'true' run: scripts/ci/warm-target.sh oracle - uses: dtolnay/rust-toolchain@stable # The trusted self-hosted runners keep their build directory and Cargo home instead; the # untrusted ones (fork pull requests) start empty and restore main's cache, read-only. - - if: ${{ !(startsWith(runner.name, 'minisforum-') || startsWith(runner.name, 'ci-box-')) || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository) }} + - if: needs.changes.outputs.local != 'true' uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 with: key: oracle From 69db6ee6e48fe8e7da819b67e2d71b31dbf20208 Mon Sep 17 00:00:00 2001 From: jyviko <2501648+jyviko@users.noreply.github.com> Date: Mon, 19 Oct 2026 13:41:39 -0400 Subject: [PATCH 113/225] CI: fork pull requests run on Blacksmith too The self-hosted-untrusted pool is being retired for CI, so fork PRs whose number ends in 7, 8 or 9 no longer route there. Build tests, the test shards and the reference tests reduce to our own runners for main and the merge queue, Blacksmith for everything else; the build's 90-minute gVisor timeout goes. Blacksmith VMs are ephemeral and fork runs get no secrets. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QWhMwdqJYQKQq8RCLSL1LT --- .github/workflows/ci.yml | 42 ++++++++++++++++++---------------------- 1 file changed, 19 insertions(+), 23 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 95c60a0ea..7804de089 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -32,10 +32,8 @@ # jobs, so they never wait behind a build). For pushes to main and the merge queue only, the # repository checks, Clippy, the doc tests, the reference tests and all four test shards run on the # self-hosted runners (`self-hosted-fast`, warm build directories via scripts/ci/warm-target.sh); -# a pull request runs them on GitHub's runners, so it never holds up the queue. Fork PRs' Linux -# jobs run on the isolated, ephemeral `self-hosted-untrusted` runners (no warm caches) when the -# PR number ends in 7, 8 or 9 (the rest of the fork PRs, and everything else, run on GitHub's -# runners, which have far more free slots). +# a pull request runs them on GitHub's runners, so it never holds up the queue. Fork PRs run +# there too: the runners are ephemeral and fork runs get no secrets. # Where the test shards run on GitHub's runners, the test archive is built there too: the # self-hosted machine has a newer glibc, so its binaries wouldn't start on ubuntu-24.04, while the # archive runs there unchanged (same /home/runner/work checkout path). The self-hosted shards @@ -48,7 +46,7 @@ # ubuntu-24.04, so the test archive and recorded goldens behave the same. Windows jobs stay on # windows-latest. Blacksmith runners report runner.environment == 'self-hosted' as well, so steps # don't ask the runner where they run: they read the routing that chose it (Select checks' `local` -# and `untrusted` outputs, or the trusted-run condition in jobs that don't need Select checks). +# output, or the trusted-run condition in jobs that don't need Select checks). name: CI on: @@ -124,11 +122,9 @@ jobs: # The passing run a merge of main carries forward (its URL), when this push is only that. carried: ${{ steps.paths.outputs.carried }} # The fast self-hosted runners are kept for main and the merge queue (the pre-merge gate); - # pull requests, same-repo ones included, take the GitHub-hosted or untrusted paths. Steps - # read these two to know where their job runs (see the top of this file). + # pull requests, same-repo ones included, run on GitHub's runners. Steps read this to know + # where their job runs (see the top of this file). local: ${{ github.event_name == 'merge_group' || (github.event_name == 'push' && github.ref == 'refs/heads/main') }} - # Fork pull requests whose Linux jobs run on the self-hosted-untrusted runners. - untrusted: ${{ (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository) && (endsWith(format('{0}', github.event.pull_request.number), '7') || endsWith(format('{0}', github.event.pull_request.number), '8') || endsWith(format('{0}', github.event.pull_request.number), '9')) }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -283,8 +279,8 @@ jobs: - uses: dtolnay/rust-toolchain@stable with: components: rustfmt - # The trusted self-hosted runners keep their build directory and Cargo home instead; the - # untrusted ones (fork pull requests) start empty and restore main's cache, read-only. + # The self-hosted runners keep their build directory and Cargo home instead; everything + # else restores main's cache (read-only off main). - if: ${{ !(github.event_name == 'merge_group' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) }} uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 with: @@ -347,8 +343,8 @@ jobs: - uses: dtolnay/rust-toolchain@stable with: components: clippy - # The trusted self-hosted runners keep their build directory and Cargo home instead; the - # untrusted ones (fork pull requests) start empty and restore main's cache, read-only. + # The self-hosted runners keep their build directory and Cargo home instead; everything + # else restores main's cache (read-only off main). - if: needs.changes.outputs.local != 'true' uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 with: @@ -374,9 +370,9 @@ jobs: # The self-hosted shards (main and the merge queue) build from their warm build directories # instead: downloading the 3 GB archive took them longer than building. if: ${{ !cancelled() && needs.changes.result == 'success' && needs.changes.outputs.native == 'true' && needs.changes.outputs.local != 'true' && (github.event_name != 'pull_request' || needs.checks.result == 'success') }} - runs-on: ${{ (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository && (endsWith(format('{0}', github.event.pull_request.number), '7') || endsWith(format('{0}', github.event.pull_request.number), '8') || endsWith(format('{0}', github.event.pull_request.number), '9'))) && 'self-hosted-untrusted' || 'blacksmith-16vcpu-ubuntu-2404' }} - # Fork builds compile inside gVisor on shared boxes; give them room to finish and upload. - timeout-minutes: ${{ (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository && (endsWith(format('{0}', github.event.pull_request.number), '7') || endsWith(format('{0}', github.event.pull_request.number), '8') || endsWith(format('{0}', github.event.pull_request.number), '9'))) && 90 || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository) && 60 || 45 }} + runs-on: blacksmith-16vcpu-ubuntu-2404 + # Fork builds start from main's cache, read-only; give them room to finish and upload. + timeout-minutes: ${{ (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository) && 60 || 45 }} env: CARGO_INCREMENTAL: "0" RUSTC_WRAPPER: sccache @@ -421,7 +417,7 @@ jobs: name: Native Linux tests (${{ matrix.shard }}/4) needs: [changes, checks, build-tests] if: ${{ !cancelled() && needs.changes.outputs.native == 'true' && (github.event_name != 'pull_request' || needs.checks.result == 'success') && (needs.changes.outputs.local == 'true' || needs.build-tests.result == 'success') }} - runs-on: ${{ needs.changes.outputs.local == 'true' && 'self-hosted-fast' || ((github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository && (endsWith(format('{0}', github.event.pull_request.number), '7') || endsWith(format('{0}', github.event.pull_request.number), '8') || endsWith(format('{0}', github.event.pull_request.number), '9'))) && 'self-hosted-untrusted' || 'blacksmith-8vcpu-ubuntu-2404') }} + runs-on: ${{ needs.changes.outputs.local == 'true' && 'self-hosted-fast' || 'blacksmith-8vcpu-ubuntu-2404' }} timeout-minutes: 60 strategy: fail-fast: false @@ -438,7 +434,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Install a software Vulkan driver (lavapipe) # Preinstalled on the self-hosted runner, which has no sudo. - if: needs.changes.outputs.local != 'true' && needs.changes.outputs.untrusted != 'true' + if: needs.changes.outputs.local != 'true' run: | sudo apt-get update sudo apt-get install -y --no-install-recommends mesa-vulkan-drivers libvulkan1 @@ -623,8 +619,8 @@ jobs: if: needs.changes.outputs.local == 'true' run: scripts/ci/warm-target.sh doc-tests - uses: dtolnay/rust-toolchain@stable - # The trusted self-hosted runners keep their build directory and Cargo home instead; the - # untrusted ones (fork pull requests) start empty and restore main's cache, read-only. + # The self-hosted runners keep their build directory and Cargo home instead; everything + # else restores main's cache (read-only off main). - if: needs.changes.outputs.local != 'true' uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 with: @@ -661,7 +657,7 @@ jobs: name: Reference tests needs: changes if: needs.changes.outputs.oracle == 'true' - runs-on: ${{ needs.changes.outputs.local == 'true' && 'self-hosted-fast' || ((github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository && (endsWith(format('{0}', github.event.pull_request.number), '7') || endsWith(format('{0}', github.event.pull_request.number), '8') || endsWith(format('{0}', github.event.pull_request.number), '9'))) && 'self-hosted-untrusted' || 'blacksmith-8vcpu-ubuntu-2404') }} + runs-on: ${{ needs.changes.outputs.local == 'true' && 'self-hosted-fast' || 'blacksmith-8vcpu-ubuntu-2404' }} timeout-minutes: 60 env: CARGO_INCREMENTAL: "0" @@ -676,8 +672,8 @@ jobs: if: needs.changes.outputs.local == 'true' run: scripts/ci/warm-target.sh oracle - uses: dtolnay/rust-toolchain@stable - # The trusted self-hosted runners keep their build directory and Cargo home instead; the - # untrusted ones (fork pull requests) start empty and restore main's cache, read-only. + # The self-hosted runners keep their build directory and Cargo home instead; everything + # else restores main's cache (read-only off main). - if: needs.changes.outputs.local != 'true' uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 with: From edc01b19bf89dacef66a6cb876d94a7265d69178 Mon Sep 17 00:00:00 2001 From: jyviko <2501648+jyviko@users.noreply.github.com> Date: Mon, 19 Oct 2026 13:41:43 -0400 Subject: [PATCH 114/225] README: Blacksmith sponsors the CI minutes Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QWhMwdqJYQKQq8RCLSL1LT --- README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.md b/README.md index bf81adecb..5229cdd14 100644 --- a/README.md +++ b/README.md @@ -322,6 +322,11 @@ sketches, solid features, an editable timeline, parameters and assemblies. See t See [CONTRIBUTING.md](CONTRIBUTING.md): how to build and test, the code map, the clean-room and licence rules, and where help is wanted most. +## Sponsors + +SolidCraft's continuous integration runs on [Blacksmith](https://www.blacksmith.sh), which +sponsors its CI minutes. + ## Licence MIT OR Apache-2.0, at your option. Developed under the From b0c4b6e9397b31ed07c009cdaf2332c77ed33cbc Mon Sep 17 00:00:00 2001 From: Logan Night <96597232+flyboy-byte@users.noreply.github.com> Date: Mon, 19 Oct 2026 14:47:08 -0600 Subject: [PATCH 115/225] Chamfer: a manipulator for Distance 2 with Two Distances (#2711) (#2856) Thanks @flyboy-byte. --- crates/ui-egui/src/blend_arrow_tests.rs | 28 ++++++++++++++++++++++ crates/ui-egui/src/canvas.rs | 32 ++++++++++++++++++++++++- 2 files changed, 59 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/blend_arrow_tests.rs b/crates/ui-egui/src/blend_arrow_tests.rs index a2dbfeec9..9ad9f0d22 100644 --- a/crates/ui-egui/src/blend_arrow_tests.rs +++ b/crates/ui-egui/src/blend_arrow_tests.rs @@ -101,3 +101,31 @@ fn dragging_out_along_the_arrow_grows_fillet_and_chamfer_on_both_kinds_of_edge() } } } + +/// Chamfer Type "Two Distances" (#2711): Distance 1 runs along the face that faces up most (the +/// other one with Flip) and Distance 2 along the remaining face, so the window shows an arrow +/// for each, from the edge into its face. +#[test] +fn two_distances_chamfer_has_an_arrow_along_each_face() { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length": 40, "width": 30, "height": 20})).unwrap(); + // The top front edge: between the top face (up) and the front face (facing -y). + let top_front = Vec3::new(20.0, 0.0, 20.0); + let (along_top, along_front) = (Vec3::new(0.0, 1.0, 0.0), Vec3::new(0.0, 0.0, -1.0)); + for (flip, expected) in [(false, (along_top, along_front)), (true, (along_front, along_top))] { + h.app.session.selection = vec![edge(&h, top_front)]; + h.app.start("solid.chamfer"); + // Equal distances keep the arrow along the bisector, and have no second one. + let d = h.app.dialog.as_ref().unwrap(); + assert!(crate::canvas::chamfer_face_dirs(&h.app, d, top_front).is_none()); + let Some(Kind::Fillet { ctype, flip: f, .. }) = h.app.dialog.as_mut().map(|d| &mut d.kind) else { panic!("a chamfer window") }; + (*ctype, *f) = (1, flip); + let d = h.app.dialog.as_ref().unwrap(); + let (t1, t2) = crate::canvas::chamfer_face_dirs(&h.app, d, top_front).expect("both faces"); + assert!(close(t1, expected.0) && close(t2, expected.1), "flip {flip}: {t1:?} {t2:?}"); + // Distance 1's arrow is the first one. + let dir = anchor(&h.app, d).unwrap().1.unwrap(); + assert!(close(dir, expected.0), "flip {flip}: arrow {dir:?}"); + h.app.dialog = None; + } +} diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index d3cd1bae9..a7178638f 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -119,9 +119,11 @@ pub fn anchor(app: &SolveApp, d: &Dialog) -> Option<(Vec3, Option)> { // Fillet radii and chamfer distances grow the way `blend_grow_dir` gives (into the body // on an outside edge, into the open corner on an inside one); shell thickness grows into // the body. + // A chamfer of two distances measures Distance 1 along its own face, not along the bisector. Kind::Fillet { .. } if matches!(first, Sel::Edge { .. }) => { let Sel::Edge { body, index, .. } = first else { return None }; - (at, st.body(body).and_then(|b| blend_grow_dir(&b.mesh(), *index, at))) + let along_face = chamfer_face_dirs(app, d, at).map(|(first_face, _)| first_face); + (at, along_face.or_else(|| st.body(body).and_then(|b| blend_grow_dir(&b.mesh(), *index, at)))) } Kind::Fillet { .. } | Kind::Shell { .. } => (at, normal.map(|n| -n)), Kind::Sheet(_) => (at, crate::dialogs_sheet::arrow(app, d).or(normal)), @@ -241,6 +243,27 @@ pub(crate) fn blend_grow_dir(m: &Mesh, index: usize, p: Vec3) -> Option { Some(if edge_concave(m, index, p).unwrap_or(false) { n } else { -n }) } +/// The directions Distance 1 and Distance 2 of a chamfer of two distances run from its edge at +/// `at`: along the face that faces up most, or the other one with Flip, and along the remaining +/// face (the kernel's `chamfer_tool_sides` picks them the same way). None for any other dialog. +pub(crate) fn chamfer_face_dirs(app: &SolveApp, d: &Dialog, at: Vec3) -> Option<(Vec3, Vec3)> { + let Kind::Fillet { chamfer: true, ctype: 1, flip, .. } = &d.kind else { return None }; + let Some(Sel::Edge { body, index, .. }) = d.inputs.first()?.items.first() else { return None }; + let st = app.session.world_state(); + let mesh = st.body(body)?.mesh(); + let sides = edge_sides(&mesh, *index, at)?; + let [(n1, c1), (n2, c2)] = sides.as_slice() else { return None }; + let along = n1.cross(*n2).normalized()?; + // From the edge into each face: the way to its centroid, square to the edge. + let into = |c: Vec3| { + let v = c - at; + (v - along * v.dot(along)).normalized() + }; + let (t1, t2) = (into(*c1)?, into(*c2)?); + let up = Vec3::new(1e-6, 1e-3, 1.0); + Some(if (n2.dot(up) > n1.dot(up)) != *flip { (t2, t1) } else { (t1, t2) }) +} + /// Whether a dynamically registered canvas handle owns this point before navigation. pub(crate) fn owns_pointer(app: &SolveApp, proj: &Proj, p: Pos2) -> bool { // The triad only registers an egui hit widget after a handle is under the pointer. @@ -417,6 +440,13 @@ fn draw(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj, { drag_arrow(ui, painter, proj, base, bs, -(n * sign), l2, true, egui::Id::new("sc_manipulator2"), half_height, distance2); } + // A chamfer of two distances: Distance 2 gets its own arrow along the other face. + let faces = chamfer_face_dirs(app, d, base); + if let (Kind::Fillet { distance2, .. }, Some((_, t2))) = (&mut d.kind, faces) + && let Some(l2) = app.session.doc.eval(distance2, ValueKind::Length).ok().filter(|v| v.is_finite()) + { + drag_arrow(ui, painter, proj, base, bs, t2, l2, false, egui::Id::new("sc_manipulator2"), half_height, distance2); + } // A rectangular pattern's second direction gets its own arrow for Spacing 2 (#2462), as the // first direction's arrow sets Spacing. if let Some(n2) = pattern_dir2(app, d) { From a6b44ab0d32ace331e771695b4ab617515758eec Mon Sep 17 00:00:00 2001 From: SS-EN <84559909+SS-EN@users.noreply.github.com> Date: Mon, 19 Oct 2026 17:00:55 -0400 Subject: [PATCH 116/225] Profiles and cap attachments fall back to the best match when a sketch outline changes (#2897) Thanks @SS-EN. --- crates/doc/src/config_certificates.rs | 3 +- crates/doc/src/config_styles.rs | 20 +- crates/doc/src/eval.rs | 23 ++- crates/doc/src/face_anchor.rs | 122 ++++++++++-- crates/doc/src/lib.rs | 2 +- crates/doc/src/profile_refs.rs | 177 ++++++++++++++++- crates/doc/src/project.rs | 3 +- crates/engine/src/lib.rs | 2 + crates/engine/src/profile_fallback_tests.rs | 204 ++++++++++++++++++++ docs/book/src/dev/naming.md | 23 +++ docs/face-attachments.md | 12 +- 11 files changed, 567 insertions(+), 24 deletions(-) create mode 100644 crates/engine/src/profile_fallback_tests.rs diff --git a/crates/doc/src/config_certificates.rs b/crates/doc/src/config_certificates.rs index de7c51df1..5391f5be8 100644 --- a/crates/doc/src/config_certificates.rs +++ b/crates/doc/src/config_certificates.rs @@ -823,7 +823,8 @@ impl Document { let stem = |index: usize| names.faces.get(index).map(|name| crate::naming::strip_piece(name)); let seed: Vec = indices.into_iter().filter(|index| stem(*index).is_some_and(|name| name.starts_with(&own) && !name.contains('@'))).collect(); - let ambiguous = || DocError::Unknown("attached planar face certificate is missing or ambiguous".into()); + let feature = self.feature(origin).map_or_else(|| format!("F{origin}"), |feature| feature.name.clone()); + let ambiguous = || DocError::Invalid(format!("the attached flat face of {feature} on `{}` is missing or ambiguous", body.name)); let first = seed.first().and_then(|index| stem(*index)).ok_or_else(ambiguous)?; if seed.iter().any(|index| stem(*index) != Some(first)) { return Err(ambiguous()); diff --git a/crates/doc/src/config_styles.rs b/crates/doc/src/config_styles.rs index 1987f8c9e..30ef3d7e8 100644 --- a/crates/doc/src/config_styles.rs +++ b/crates/doc/src/config_styles.rs @@ -185,6 +185,24 @@ impl Document { } Ok(()) } + /// A face target for messages: its role on its feature where the certificate tells it, else + /// its name, and its body (`the top cap of E1 on `Body1``). + pub(crate) fn describe_face_target(&self, target: &ConfigFaceTarget) -> String { + let feature = self.feature(target.origin_feature).map_or_else(|| format!("F{}", target.origin_feature), |f| f.name.clone()); + let end = |high: bool| if high { "top" } else { "bottom" }; + let role = match &target.certificate { + Some(super::FaceCertificate::ExtrudeCap { high, .. }) | Some(super::FaceCertificate::CylinderCap { high }) => { + format!("the {} cap", end(*high)) + } + Some(super::FaceCertificate::Box { axis, high }) => { + format!("the {}{} side", if *high { "+" } else { "-" }, ["x", "y", "z"].get(usize::from(*axis)).copied().unwrap_or("?")) + } + Some(super::FaceCertificate::ExtrudeSide { curve, .. }) => format!("the side along `{curve}`"), + _ => format!("face `{}`", target.name), + }; + format!("{role} of {feature} on `{}`", target.body) + } + /// Verify the current named pieces describe one surface, not ambiguous generated roles. pub fn configuration_face_indices(&self, body: &crate::ModelBody, target: &ConfigFaceTarget) -> Result> { self.certify_config_face(target)?; @@ -248,7 +266,7 @@ impl Document { }) .collect(); if indices.is_empty() { - return Err(DocError::Unknown("attached planar face certificate is missing or ambiguous".into())); + return Err(DocError::Invalid(format!("{} no longer exists", self.describe_face_target(target)))); } return self.certified_pieces(body, indices, target.origin_feature); } diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index e8be71340..b250d864b 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -1359,6 +1359,16 @@ impl Model { }), }); if r.is_ok() { + // Profiles picked by curves that no longer bound a profile exactly were found + // by their best match: say which. + let thin = matches!(&f.kind, FeatureKind::Extrude { thin: Some(_), .. }); + for (sketch, sel) in f.kind.profile_sels() { + if let (false, Some(ss)) = (thin, state.sketch(sketch)) { + for note in crate::profile_fallback_notes(ss, sel) { + append_warning(&mut warning, note); + } + } + } if let Some(note) = boolean_diagnostics.warning() { append_warning(&mut warning, note); } @@ -1480,8 +1490,11 @@ pub fn select_profiles(ss: &SolvedSketch, sel: &ProfileSel) -> Result { - crate::profile_selection_indices(ss, sel)? + crate::profile_selection_indices_lenient(ss, sel)? + .0 .into_iter() .map(|index| { ps.get(index) @@ -4832,7 +4845,7 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: None => state_in_frame(doc, st, f.component), }; let (plane, face_warning) = match (anchor, plane) { - (Some(_), plane) => (doc.resolve_attached_plane(vals, plane, f.component, st, &fst)?, None), + (Some(_), plane) => doc.resolve_attached_plane_noted(vals, plane, f.component, st, &fst)?, // A flat face of a sheet: the panel's exact plane, from its flat region and fold. (None, plane) if crate::sheet::plane_sheet_face(plane).is_some() => { (doc.resolve_plane_in(vals, &sheet_face_plane_in_frame(doc, st, f.component, plane)?, 0, Some(&fst))?, None) @@ -4991,7 +5004,11 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: let pl = match crate::face_anchor::plane_face_anchor(plane) { Some(anchor) => { let fst = crate::state_in_face_anchor_frame(doc, st, anchor, f.component)?; - doc.resolve_attached_plane(vals, plane, f.component, st, &fst)? + let (pl, note) = doc.resolve_attached_plane_noted(vals, plane, f.component, st, &fst)?; + if let Some(note) = note { + append_warning(warning, note); + } + pl } // A plane of numbers alone reads no body: placing them all is the design's size. None if plane_is_fixed(plane) => doc.resolve_plane_in(vals, plane, 0, Some(st))?, diff --git a/crates/doc/src/face_anchor.rs b/crates/doc/src/face_anchor.rs index 8d32d9268..38633d2ca 100644 --- a/crates/doc/src/face_anchor.rs +++ b/crates/doc/src/face_anchor.rs @@ -1,4 +1,5 @@ -//! Exact ordinary face attachments. Missing identities never invoke a proximity fallback. +//! Exact ordinary face attachments. Missing identities never invoke a proximity fallback; the one +//! fallback is an extrude cap whose sketch loop changed (`Document::anchored_face_indices`). use crate::config::ConfigFaceTarget; use crate::{DocError, Document, EmbossFace, FeatureKind, Model, ModelBody, ModelState, PlaneRef, Result}; use serde::{Deserialize, Serialize}; @@ -104,22 +105,38 @@ impl Document { state: &ModelState, framed: &ModelState, ) -> Result { - fn replace(doc: &Document, plane: &mut PlaneRef, author: u64, state: &ModelState, depth: usize) -> Result<()> { + self.resolve_attached_plane_noted(vals, plane, author, state, framed).map(|(plane, _)| plane) + } + + /// [`Document::resolve_attached_plane`] with the note of an attachment found by fallback + /// ([`Document::anchored_face_indices`]). + pub fn resolve_attached_plane_noted( + &self, + vals: &std::collections::BTreeMap, + plane: &PlaneRef, + author: u64, + state: &ModelState, + framed: &ModelState, + ) -> Result<(Plane, Option)> { + fn replace(doc: &Document, plane: &mut PlaneRef, author: u64, state: &ModelState, depth: usize) -> Result> { if depth > 64 { return Err(DocError::Invalid("attached plane nesting exceeds budget".into())); } match plane { - PlaneRef::Face { anchor: Some(anchor), .. } => *plane = PlaneRef::Custom { plane: doc.resolve_face_anchor(anchor, author, state)? }, - PlaneRef::Offset { base, .. } | PlaneRef::AtAngle { base, .. } | PlaneRef::Flipped { base, .. } => { - replace(doc, base, author, state, depth + 1)? + PlaneRef::Face { anchor: Some(anchor), .. } => { + let (resolved, note) = doc.resolve_face_anchor_noted(anchor, author, state)?; + *plane = PlaneRef::Custom { plane: resolved }; + Ok(note) } - _ => {} + PlaneRef::Offset { base, .. } | PlaneRef::AtAngle { base, .. } | PlaneRef::Flipped { base, .. } => { + replace(doc, base, author, state, depth + 1) + } + _ => Ok(None), } - Ok(()) } let mut resolved = plane.clone(); - replace(self, &mut resolved, author, state, 0)?; - self.resolve_plane_in(vals, &resolved, 0, Some(framed)) + let note = replace(self, &mut resolved, author, state, 0)?; + Ok((self.resolve_plane_in(vals, &resolved, 0, Some(framed))?, note)) } } @@ -193,11 +210,92 @@ impl Document { Ok(anchor) } + /// The faces an attachment stands for, and a note when they were found by fallback. + /// + /// An extrude's cap is certified by the loop of sketch curves around it, so editing that + /// sketch's outline (a curve that now cuts the profile, a side deleted and drawn again, a + /// notch trimmed into it) leaves no face with the exact certificate. The attachment then + /// takes the cap of the same (solid) extrude, at the same end, from the same sketch, on the + /// same body, whose loop shares the most of the stored curves, at least half of them (a tie + /// is not guessed). It never does while the exact cap is still on another body (profiles + /// reordered: the bodies swapped names). The note names what changed. Every other identity + /// stays exact. + pub(crate) fn anchored_face_indices( + &self, + state: &ModelState, + body: &ModelBody, + target: &ConfigFaceTarget, + ) -> Result<(Vec, Option)> { + let error = match self.configuration_face_indices(body, target) { + Ok(indices) => return Ok((indices, None)), + Err(error) => error, + }; + let Some(crate::config::FaceCertificate::ExtrudeCap { sketch, high, outer, holes }) = &target.certificate else { return Err(error) }; + let exact = |source: &Option| { + matches!(source, Some(solidcraft_kernel::FaceSource::CertifiedExtrudeCap { producer, sketch: from, high: end, outer: around, holes: inside, .. }) + if *producer == target.origin_feature && from == sketch && end == high && around == outer && inside == holes) + }; + if state.bodies.iter().any(|other| other.body.face_sources().is_some_and(|sources| sources.iter().any(exact))) { + return Err(error); + } + // A thin wall's cap is signed by the curves the wall follows: a wall along other curves + // is another wall, whose cap never stands for this one. + let solid = self.feature(target.origin_feature).is_some_and(|feature| matches!(feature.kind, FeatureKind::Extrude { thin: None, .. })); + if !solid || self.certify_config_face(target).is_err() || body.body.is_mesh() || body.definition_name() != target.body { + return Err(error); + } + // The producer's caps at that end, grouped by the loop each was made from. + let mut caps: std::collections::BTreeMap<&Vec, Vec> = std::collections::BTreeMap::new(); + for (index, source) in body.body.face_sources().into_iter().flatten().enumerate() { + if let Some(solidcraft_kernel::FaceSource::CertifiedExtrudeCap { producer, sketch: from, high: end, outer: around, .. }) = source + && *producer == target.origin_feature + && from == sketch + && end == high + { + caps.entry(around).or_default().push(index); + } + } + let stored: std::collections::BTreeSet<&str> = outer.iter().map(String::as_str).collect(); + let shared = |around: &[String]| around.iter().filter(|id| stored.contains(id.as_str())).count(); + let best = caps.keys().map(|around| shared(around)).max().unwrap_or(0); + if best == 0 || best.saturating_mul(2) < stored.len() { + return Err(error); + } + let mut chosen = caps.iter().filter(|(around, _)| shared(around) == best); + let (Some((around, indices)), None) = (chosen.next(), chosen.next()) else { return Err(error) }; + let indices = self.certified_pieces(body, indices.clone(), target.origin_feature).map_err(|_| error)?; + let now: std::collections::BTreeSet<&str> = around.iter().map(String::as_str).collect(); + let list = |ids: Vec<&str>| ids.iter().map(|id| format!("`{id}`")).collect::>().join(", "); + let mut changes = Vec::new(); + let gone: Vec<&str> = stored.difference(&now).copied().collect(); + if !gone.is_empty() { + changes.push(format!("{} no longer around it", list(gone))); + } + let new: Vec<&str> = now.difference(&stored).copied().collect(); + if !new.is_empty() { + changes.push(format!("{} new", list(new))); + } + let feature = self.feature(target.origin_feature).map_or_else(|| format!("F{}", target.origin_feature), |f| f.name.clone()); + let note = format!( + "the face this sketch sits on, {}, changed when its sketch was edited ({}); using the {} cap of {feature} as it is now", + self.describe_face_target(target), + changes.join(", "), + if *high { "top" } else { "bottom" }, + ); + Ok((indices, Some(note))) + } + pub fn resolve_face_anchor(&self, anchor: &FaceAnchor, author: u64, state: &ModelState) -> Result { + self.resolve_face_anchor_noted(anchor, author, state).map(|(plane, _)| plane) + } + + /// [`Document::resolve_face_anchor`] with the note of an attachment found by fallback + /// ([`Document::anchored_face_indices`]). + pub fn resolve_face_anchor_noted(&self, anchor: &FaceAnchor, author: u64, state: &ModelState) -> Result<(Plane, Option)> { anchor.validate()?; let body = state.body(&anchor.target.body).ok_or_else(|| DocError::Unknown(format!("attached body `{}` no longer exists", anchor.target.body)))?; - let indices = self.configuration_face_indices(body, &anchor.target)?; + let (indices, note) = self.anchored_face_indices(state, body, &anchor.target)?; let first = indices.first().copied().ok_or_else(|| DocError::Unknown("attached face no longer exists".into()))?; let certificate = anchor.target.certificate.as_ref(); let plane = self @@ -214,7 +312,9 @@ impl Document { let canonical = map_plane(&anchor.source_to_author(self, author, body)?, &plane)?; let origin = canonical.origin + canonical.x * anchor.coordinates[0] + canonical.y * anchor.coordinates[1]; let x = canonical.x * anchor.x_axis[0] + canonical.y * anchor.x_axis[1]; - Plane::new(origin, x, canonical.normal().cross(x)).ok_or_else(|| DocError::Invalid("attached sketch basis is degenerate".into())) + let plane = + Plane::new(origin, x, canonical.normal().cross(x)).ok_or_else(|| DocError::Invalid("attached sketch basis is degenerate".into()))?; + Ok((plane, note)) } pub fn sketch_face_attachment(&self, feature: u64, model: &Model) -> FaceAttachmentStatus { diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 628499ac0..163a53433 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -44,7 +44,7 @@ mod points; mod profile_refs; pub mod progress; mod walk; -pub use profile_refs::{capture_profile_selection, profile_selection_indices}; +pub use profile_refs::{capture_profile_selection, profile_fallback_notes, profile_selection_indices, profile_selection_indices_lenient}; pub mod plastic; pub mod project; mod project3d; diff --git a/crates/doc/src/profile_refs.rs b/crates/doc/src/profile_refs.rs index 60ebe98a2..88902445f 100644 --- a/crates/doc/src/profile_refs.rs +++ b/crates/doc/src/profile_refs.rs @@ -97,6 +97,124 @@ fn reserved_boundaries(ss: &SolvedSketch) -> Result Result> { + selection_indices(ss, selection, None) +} + +/// [`profile_selection_indices`] for evaluating a feature: an ordinary curve loop that no longer +/// bounds a profile exactly (a curve now cuts the region, or a side was deleted and drawn again) +/// falls back to the profiles that best match it (`fallback_loop`) instead of failing, and says +/// so in the returned notes. Commands still check picks with the exact form. +pub fn profile_selection_indices_lenient(ss: &SolvedSketch, selection: &ProfileSel) -> Result<(Vec, Vec)> { + let mut notes = Vec::new(); + let indices = selection_indices(ss, selection, Some(&mut notes))?; + Ok((indices, notes)) +} + +/// What a feature's profile selection falls back to when evaluated: one note per curve loop that +/// no longer bounds a profile exactly; empty when everything matched exactly (or nothing did). +pub fn profile_fallback_notes(ss: &SolvedSketch, selection: &ProfileSel) -> Vec { + if !matches!(selection, ProfileSel::Curves { .. }) || profile_selection_indices(ss, selection).is_ok() { + return Vec::new(); + } + profile_selection_indices_lenient(ss, selection).map(|(_, notes)| notes).unwrap_or_default() +} + +fn quoted(ids: &[String]) -> String { + ids.iter().map(|id| format!("`{id}`")).collect::>().join(", ") +} + +/// The profiles that best stand for an ordinary curve loop `curves` (the outer loop of a profile +/// when it was picked) that no longer bounds any profile exactly, with a note saying what changed. +/// `None` when nothing plausibly matches. +/// +/// 1. All of its curves are still there and still close a loop on their own, but other curves +/// now cut the region inside: the pieces inside that loop that touch it, whose union is the +/// region that was picked (islands inside it stay holes, as they were). +/// 2. Otherwise the profile whose outer loop shares the most of its curves, at least half of +/// them; a tie goes to the one with the fewest curves the loop did not have, and a tie left +/// after that is not guessed. +/// +/// Loops of offset curves and legacy graph-span multisets (a curve listed once per piece) keep +/// their exact meaning and never fall back. +fn fallback_loop(ss: &SolvedSketch, curves: &[String]) -> Option<(Vec, String)> { + let stored: BTreeSet<&str> = curves.iter().map(String::as_str).collect(); + if stored.is_empty() || stored.len() != curves.len() || curves.len() > 512 || ss.profiles.len() > 10_000 { + return None; + } + let sketch = &ss.sketch; + let offset = + |id: &str| sketch.offsets.iter().any(|offset| offset.owns_output(id)) || sketch.freeform_offsets.iter().any(|offset| offset.output == id); + if stored.iter().any(|id| offset(id)) { + return None; + } + let drawn = |id: &str| sketch.curves.iter().any(|curve| curve.id == id && !curve.construction && !curve.centerline); + let touches = |profile: &solidcraft_sketch::Profile| profile.outer_curves.iter().any(|id| stored.contains(id.as_str())); + // 1. The loop alone still closes: take the pieces of the region it bounds. + if stored.iter().all(|id| drawn(id)) { + let mut alone = sketch.clone(); + for curve in &mut alone.curves { + if !stored.contains(curve.id.as_str()) { + curve.construction = true; + } + } + let loops = solidcraft_sketch::find_profiles(&alone); + if let Ok(index) = solidcraft_sketch::profile_by_curves(&loops, curves) + && let Some(region) = loops.get(index).map(|profile| &profile.region) + { + let pieces: Vec = ss + .profiles + .iter() + .enumerate() + .filter(|(_, profile)| touches(profile) && region.outer.contains(profile.region.interior_point())) + .map(|(index, _)| index) + .collect(); + if !pieces.is_empty() { + let note = format!( + "the profile of {} bounded by {} is cut by another curve now; using the {} pieces inside it", + ss.name, + quoted(curves), + pieces.len() + ); + return Some((pieces, note)); + } + } + } + // 2. The closest loop by the curves it shares. + let count = |profile: &solidcraft_sketch::Profile, inside: bool| { + profile.outer_curves.iter().map(String::as_str).filter(|id| stored.contains(id) == inside).collect::>().len() + }; + let best = ss.profiles.iter().map(|profile| count(profile, true)).max()?; + if best == 0 || best.saturating_mul(2) < stored.len() { + return None; + } + let tied: Vec<&solidcraft_sketch::Profile> = ss.profiles.iter().filter(|profile| count(profile, true) == best).collect(); + let fewest = tied.iter().map(|profile| count(profile, false)).min()?; + let mut chosen = ss.profiles.iter().enumerate().filter(|(_, profile)| count(profile, true) == best && count(profile, false) == fewest); + let (index, profile) = chosen.next()?; + if chosen.next().is_some() { + return None; + } + let now: BTreeSet<&str> = profile.outer_curves.iter().map(String::as_str).collect(); + let gone: Vec = curves.iter().filter(|id| !now.contains(id.as_str())).cloned().collect(); + let new: Vec = solidcraft_sketch::distinct_curves(&profile.outer_curves).into_iter().filter(|id| !stored.contains(id.as_str())).collect(); + let mut changes = Vec::new(); + if !gone.is_empty() { + changes.push(format!("{} no longer on it", quoted(&gone))); + } + if !new.is_empty() { + changes.push(format!("{} new", quoted(&new))); + } + let note = format!( + "no profile of {} is bounded by exactly {} any more ({}); using the profile that shares {best} of its {} curves", + ss.name, + quoted(curves), + changes.join(", "), + curves.len() + ); + Some((vec![index], note)) +} + +fn selection_indices(ss: &SolvedSketch, selection: &ProfileSel, mut notes: Option<&mut Vec>) -> Result> { let indices = match selection { ProfileSel::All => (0..ss.profiles.len()).collect(), ProfileSel::Indices { indices } => indices.clone(), @@ -119,10 +237,25 @@ pub fn profile_selection_indices(ss: &SolvedSketch, selection: &ProfileSel) -> R { return Err(crate::curve_pick_error(solidcraft_sketch::CurvePick::Missing, curves, &ss.name)); } - indices.push( - solidcraft_sketch::profile_by_curves(&ss.profiles, curves) - .map_err(|error| crate::curve_pick_error(error, curves, &ss.name))?, - ); + match solidcraft_sketch::profile_by_curves(&ss.profiles, curves) { + Ok(index) => indices.push(index), + Err(error) => { + let fallback = match (&error, notes.as_deref_mut()) { + (solidcraft_sketch::CurvePick::Missing, Some(notes)) => fallback_loop(ss, curves).map(|found| (found, notes)), + _ => None, + }; + let Some(((found, note), notes)) = fallback else { + return Err(crate::curve_pick_error(error, curves, &ss.name)); + }; + notes.push(note); + // Two loops that fell back to one piece take it once. + for index in found { + if !indices.contains(&index) { + indices.push(index); + } + } + } + } } } indices @@ -385,6 +518,42 @@ mod tests { assert!(profile_selection_indices(&ss, &ProfileSel::Indices { indices: vec![1] }).is_err()); } + fn solved_square(extra: &[(&str, [f64; 4])]) -> SolvedSketch { + let mut sketch = Sketch::new(); + let corners = [Vec2::new(0., 0.), Vec2::new(10., 0.), Vec2::new(10., 10.), Vec2::new(0., 10.)]; + let points: Vec<_> = corners.iter().map(|corner| sketch.add_point(*corner, None).unwrap()).collect(); + for (index, id) in ["a", "b", "c", "d"].iter().enumerate() { + sketch.add_line_pts(points[index], points[(index + 1) % 4], Some(id)).unwrap(); + } + for (id, [x0, y0, x1, y1]) in extra { + let p = sketch.add_point(Vec2::new(*x0, *y0), None).unwrap(); + let q = sketch.add_point(Vec2::new(*x1, *y1), None).unwrap(); + sketch.add_line_pts(p, q, Some(id)).unwrap(); + } + let report = solve(&mut sketch); + let profiles = find_profiles(&sketch); + SolvedSketch { feature: 1, name: "S".into(), plane: Plane::XY, sketch, report, profiles, ends: Default::default() } + } + + #[test] + fn a_split_loop_falls_back_to_its_pieces_only_when_evaluating() { + let loops = ProfileSel::Curves { loops: vec![vec!["a".into(), "b".into(), "c".into(), "d".into()]] }; + let split = solved_square(&[("cut", [4., 0., 4., 10.])]); + assert_eq!(split.profiles.len(), 2); + assert!(profile_selection_indices(&split, &loops).is_err(), "a command's pick stays exact"); + let (indices, notes) = profile_selection_indices_lenient(&split, &loops).unwrap(); + assert_eq!(indices.len(), 2); + assert!(notes[0].contains("cut by another curve now"), "{notes:?}"); + assert_eq!(profile_fallback_notes(&split, &loops), notes); + let area: f64 = crate::select_profiles(&split, &loops).unwrap().iter().map(|region| region.area()).sum(); + assert!((area - 100.).abs() < 1e-9, "{area}"); + // Exact matches have no note; a loop sharing under half its curves matches nothing. + let whole = solved_square(&[]); + assert!(profile_fallback_notes(&whole, &loops).is_empty()); + let few = ProfileSel::Curves { loops: vec![vec!["a".into(), "x".into(), "y".into(), "z".into(), "w".into()]] }; + assert!(crate::select_profiles(&whole, &few).is_err()); + } + #[test] fn periodic_offset_ring_whole_source_survives_adaptive_spans_and_reopen() { let mut sketch = Sketch::new(); diff --git a/crates/doc/src/project.rs b/crates/doc/src/project.rs index 39e556f5c..9c115c3d2 100644 --- a/crates/doc/src/project.rs +++ b/crates/doc/src/project.rs @@ -429,7 +429,8 @@ fn certified_planar_construction(body: &crate::ModelBody, index: usize) -> bool pub fn resolve_anchored_face(doc: &Document, st: &ModelState, plane: &Plane, kind: LinkKind, anchor: &crate::FaceAnchor) -> Result { let body = st.body(&anchor.target.body).ok_or_else(|| lost("anchored projection body"))?; - let indices = doc.configuration_face_indices(body, &anchor.target)?; + // The sketch's plane says when the face was found by fallback; its projection follows it. + let (indices, _) = doc.anchored_face_indices(st, body, &anchor.target)?; resolve_face_indices(st, plane, kind, &body.name, &indices) } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 8ba80b51f..5129dd1fb 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1047,6 +1047,8 @@ mod pattern_suppress_tests; #[cfg(test)] mod profile_curves_tests; #[cfg(test)] +mod profile_fallback_tests; +#[cfg(test)] mod profile_refs_tests; #[cfg(test)] mod sketch_edit_removed_tests; diff --git a/crates/engine/src/profile_fallback_tests.rs b/crates/engine/src/profile_fallback_tests.rs new file mode 100644 index 000000000..34d84db89 --- /dev/null +++ b/crates/engine/src/profile_fallback_tests.rs @@ -0,0 +1,204 @@ +//! A profile picked by the curves around it, and a sketch on the cap such a profile makes, keep +//! working when the sketch's outline is edited so that no profile is bounded by exactly those +//! curves any more: a line that splits the region, a side deleted and drawn again, a notch +//! trimmed into the outline. The feature falls back to the best match and warns; it no longer +//! fails and takes its body (and everything after it) with it. + +use serde_json::{Value, json}; + +use crate::Session; + +const HOLE: f64 = std::f64::consts::PI * 16.0 * 10.0; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + match s.execute(id, &p) { + Ok(v) => v, + Err(e) => panic!("{id} {p}: {e}"), + } +} + +fn volume(s: &Session) -> f64 { + s.model.state().bodies.iter().map(|b| b.body.tessellate(1e-3).unwrap().measure().volume).sum() +} + +fn result(s: &Session, name: &str) -> (Option, Option) { + let id = s.doc.find_feature(name).unwrap().id; + let r = s.model.result(id).unwrap(); + (r.error.clone(), r.warning.clone()) +} + +/// A 40 × 20 plate with a hole: the outline `l1`–`l4` (its width is the parameter `W`) and a +/// circle, the region between them picked by a point and extruded 10 mm. +fn plate() -> Session { + let mut s = Session::default(); + run(&mut s, "parameters.change", json!({"name": "W", "expression": "40 mm"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S1"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 20]})); + run(&mut s, "sketch.circle.center", json!({"center": [30, 10], "radius": 4})); + run(&mut s, "sketch.dimension", json!({"entities": ["l1"], "value": "W"})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"distance": "10 mm", "profiles": [{"point": [10, 10]}], "name": "E1"})); + assert_eq!(result(&s, "E1"), (None, None)); + assert!((volume(&s) - (8000.0 - HOLE)).abs() < 0.5, "{}", volume(&s)); + s +} + +fn edit(s: &mut Session, steps: &[(&str, Value)]) { + run(s, "sketch.edit", json!({"sketch": "S1"})); + for (id, p) in steps { + run(s, id, p.clone()); + } + run(s, "sketch.finish", json!({})); +} + +fn assert_survives(s: &Session, feature: &str, expected: f64, says: &str) { + let (error, warning) = result(s, feature); + assert_eq!(error, None, "{feature} keeps its body"); + let warning = warning.unwrap_or_default(); + assert!(warning.contains(says), "{feature}: {warning}"); + assert_eq!(s.model.state().bodies.len(), 1); + assert!((volume(s) - expected).abs() < 0.5, "{feature}: volume {} (expected {expected})", volume(s)); +} + +/// A line across the picked region cuts it in two: both pieces together are the region that was +/// picked, so the plate keeps its whole volume (with its hole, which stays a hole). +#[test] +fn an_extrude_survives_a_line_splitting_its_profile() { + for x in [20, 15] { + let mut s = plate(); + edit(&mut s, &[("sketch.line", json!({"points": [[x, 0], [x, 20]]}))]); + assert_survives(&s, "E1", 8000.0 - HOLE, "is cut by another curve now; using the 2 pieces inside it"); + } +} + +/// A side deleted and drawn again is a new curve: the profile that shares the other three sides +/// is the plate, and the warning names the side that went and the one that came. +#[test] +fn an_extrude_survives_a_side_deleted_and_drawn_again() { + for (side, line) in [("l2", [[40, 0], [40, 20]]), ("l3", [[40, 20], [0, 20]])] { + let mut s = plate(); + edit(&mut s, &[("sketch.delete", json!({"entities": [side]})), ("sketch.line", json!({"points": line}))]); + assert_survives(&s, "E1", 8000.0 - HOLE, &format!("`{side}` no longer on it")); + assert!(result(&s, "E1").1.unwrap().contains("shares 3 of its 4 curves")); + } +} + +/// A notch trimmed out of the top side adds curves to the outline: the profile still has all four +/// sides and takes the notch with it. +#[test] +fn an_extrude_survives_a_notch_trimmed_into_its_outline() { + let mut s = plate(); + edit( + &mut s, + &[("sketch.line", json!({"points": [[10, 20], [10, 25], [20, 25], [20, 20]]})), ("sketch.trim", json!({"curve": "l3", "at": [15, 20]}))], + ); + assert_survives(&s, "E1", 8000.0 + 500.0 - HOLE, "using the profile that shares 4 of its 4 curves"); +} + +/// Dimension edits still match exactly, with no warning; an outline replaced altogether matches +/// nothing, and that is still an error rather than a guess. +#[test] +fn exact_matches_stay_quiet_and_nothing_plausible_is_an_error() { + let mut s = plate(); + run(&mut s, "parameters.change", json!({"name": "W", "expression": "60 mm"})); + assert_eq!(result(&s, "E1"), (None, None)); + assert!((volume(&s) - (12000.0 - HOLE)).abs() < 0.5); + edit( + &mut s, + &[("sketch.delete", json!({"entities": ["l1", "l2", "l3", "l4"]})), ("sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [50, 20]}))], + ); + let (error, _) = result(&s, "E1"); + assert!(error.is_some_and(|e| e.contains("no profile of S1 is bounded by exactly"))); + assert!(s.model.state().bodies.is_empty()); +} + +/// A block `E1` with a sketch `S2` on its top cap and a hole cut from it, `E2`. +fn block_with_hole() -> Session { + let mut s = Session::default(); + run(&mut s, "parameters.change", json!({"name": "W", "expression": "40 mm"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S1"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 20]})); + run(&mut s, "sketch.dimension", json!({"entities": ["l1"], "value": "W"})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"distance": "10 mm", "name": "E1"})); + run(&mut s, "sketch.create", json!({"plane": {"face": [10, 10, 10]}, "name": "S2"})); + run(&mut s, "sketch.circle.center", json!({"center": [10, 10], "radius": 3})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"distance": "3 mm", "direction": "negative", "operation": "cut", "name": "E2"})); + for f in ["E1", "S2", "E2"] { + assert_eq!(result(&s, f).0, None, "{f}"); + } + s +} + +fn hole_volume() -> f64 { + std::f64::consts::PI * 9.0 * 3.0 +} + +fn assert_hole_follows(s: &Session, block: f64, sketch_warns: bool) { + let (error, warning) = result(s, "S2"); + assert_eq!(error, None, "S2 keeps its face"); + if sketch_warns { + let warning = warning.unwrap_or_default(); + assert!(warning.contains("the face this sketch sits on, the top cap of E1"), "{warning}"); + assert!(warning.contains("using the top cap of E1 as it is now"), "{warning}"); + } + assert_eq!(result(s, "E2").0, None, "the hole after it is still cut"); + let id = s.doc.find_feature("S2").unwrap().id; + let plane = s.model.state().sketch(id).unwrap().plane; + assert!((plane.origin.z - 10.0).abs() < 1e-9, "{plane:?}"); + assert!((volume(s) - (block - hole_volume())).abs() < 0.5, "volume {} (expected {})", volume(s), block - hole_volume()); +} + +/// The base sketch cut by a line still makes one block with one top cap. +#[test] +fn a_sketch_on_a_cap_survives_a_line_splitting_the_base_profile() { + let mut s = block_with_hole(); + edit(&mut s, &[("sketch.line", json!({"points": [[20, 0], [20, 20]]}))]); + assert_hole_follows(&s, 8000.0, false); +} + +/// A side of the base sketch deleted and drawn again: the cap is bounded by a new curve. +#[test] +fn a_sketch_on_a_cap_survives_a_base_side_deleted_and_drawn_again() { + let mut s = block_with_hole(); + edit(&mut s, &[("sketch.delete", json!({"entities": ["l2"]})), ("sketch.line", json!({"points": [[40, 0], [40, 20]]}))]); + assert_hole_follows(&s, 8000.0, true); + assert!(result(&s, "S2").1.unwrap().contains("`l2` no longer around it")); +} + +/// A corner notch trimmed into the base sketch. +#[test] +fn a_sketch_on_a_cap_survives_a_notch_trimmed_into_the_base_outline() { + let mut s = block_with_hole(); + edit( + &mut s, + &[ + ("sketch.line", json!({"points": [[0, 15], [5, 15], [5, 20]]})), + ("sketch.trim", json!({"curve": "l4", "at": [0, 18]})), + ("sketch.trim", json!({"curve": "l3", "at": [2, 20]})), + ], + ); + assert_hole_follows(&s, 8000.0 - 25.0 * 10.0, true); +} + +/// The base extrude picked by a point (stored by its curves) and the sketch on its cap both +/// survive the outline being edited. +#[test] +fn a_picked_profile_and_the_sketch_on_its_cap_survive_together() { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S1"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 20]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"distance": "10 mm", "profiles": [{"point": [10, 10]}], "name": "E1"})); + run(&mut s, "sketch.create", json!({"plane": {"face": [10, 10, 10]}, "name": "S2"})); + run(&mut s, "sketch.circle.center", json!({"center": [10, 10], "radius": 3})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"distance": "3 mm", "direction": "negative", "operation": "cut", "name": "E2"})); + edit(&mut s, &[("sketch.delete", json!({"entities": ["l2"]})), ("sketch.line", json!({"points": [[40, 0], [40, 20]]}))]); + assert!(result(&s, "E1").1.is_some_and(|w| w.contains("`l2` no longer on it"))); + assert_hole_follows(&s, 8000.0, true); + // Saved and opened again, it evaluates the same way. + let reopened = Session::new(solidcraft_doc::format::read(&s.doc.to_json()).unwrap()); + assert_hole_follows(&reopened, 8000.0, true); +} diff --git a/docs/book/src/dev/naming.md b/docs/book/src/dev/naming.md index 43f6e73c5..2ba80c42b 100644 --- a/docs/book/src/dev/naming.md +++ b/docs/book/src/dev/naming.md @@ -98,6 +98,29 @@ surface of a plane, cylinder, cone, sphere or torus), which the feature stores l with the name it then gets as before. Nothing new is stored in the design. `model.faces` lists that point for every face. +### Profiles picked by their curves + +A profile picked by a point or an index is stored by the curve ids of its outer loop +(`ProfileSel::Curves`), so it follows dimension and parameter edits exactly. Editing the outline +itself can leave no profile bounded by exactly those curves; the feature then falls back to the +best match and warns, instead of failing and taking its body and everything after it along +(`profile_refs::fallback_loop`): + +1. all the stored curves are still there and still close a loop on their own, but another curve + now cuts the region: the pieces inside that loop that touch it, which together are the region + that was picked (islands inside stay holes); +2. otherwise the profile whose outer loop shares the most of the stored curves, at least half of + them (a side deleted and drawn again, a notch trimmed in); a tie goes to the one with the + fewest curves the loop did not have, and a tie left after that is an error, as is a loop + that matches nothing. + +Loops of offset curves and legacy graph-span multisets keep their exact meaning. Commands still +check a pick with the exact rule, so a curve list that names no profile is refused when given. +A sketch on such an extrude's cap falls back the same way: its certificate names the loop, and +the cap of the same solid extrude at the same end, from the same sketch and on the same body, +that shares the most (at least half) of its curves stands for it, unless the exact cap is still +on another body (`Document::anchored_face_indices`). + A hole placed by a position on a face is the exception to "the point nearest the reference's point": its position is a place, not a pick. The hole follows its face along its own axis, so it moves with the face when the face moves, and when the face no longer reaches the position it stays diff --git a/docs/face-attachments.md b/docs/face-attachments.md index 6c22b96a9..7c2c2dcd0 100644 --- a/docs/face-attachments.md +++ b/docs/face-attachments.md @@ -75,8 +75,16 @@ the point is in world coordinates. A point-only face request must find a unique source. An unsupported or ambiguous request fails with an explanation instead of creating an attachment with weaker identity. -When a source is suppressed, deleted, replaced, or loses its certificate, the sketch reports -a lost attachment. Its saved plane is only a visible repair guide: it does not produce a +A solid extrude's cap is identified by the curves around its profile, so editing that sketch's +outline (a line that now splits the profile, a side deleted and drawn again, a notch trimmed into +it) leaves no cap with the exact identity. The sketch then sits on the cap of the same extrude, at +the same end, made from the same sketch, on the same body, whose outline shares the most of the +stored curves, at least half of them (a tie is not guessed; a cap whose exact identity is still +on another body is never replaced). It warns, naming the face and the curves +that went or came, until the sketch is placed again with **Redefine Sketch Plane**. + +When a source is suppressed, deleted, replaced, or loses its certificate otherwise, the sketch +reports a lost attachment, naming the face it was on (`the top cap of Extrude1 on `Body1``). Its saved plane is only a visible repair guide: it does not produce a healthy solved sketch or let downstream features build at a substitute face. Use **Redefine Sketch Plane** to select a new supported face explicitly. The draft can be From 0b787f8eae4244cd40f07dddccd2e1b27e4cf9f8 Mon Sep 17 00:00:00 2001 From: amolinari-autotex Date: Mon, 19 Oct 2026 23:07:01 +0200 Subject: [PATCH 117/225] Show and edit standard part configurations (#2680) (#2681) Thanks @amolinari-autotex. --- assets/locales/en.json | 1 + assets/locales/it.json | 1 + assets/locales/ja.json | 1 + assets/locales/zh.json | 1 + crates/engine/src/cmd/parts.rs | 104 ++++- crates/engine/src/frames.rs | 14 + crates/ui-egui/src/browser.rs | 17 +- crates/ui-egui/src/context_menu.rs | 18 + crates/ui-egui/src/dialogs.rs | 7 +- crates/ui-egui/src/dialogs_part_size.rs | 534 ++++++++++++++++++++++++ crates/ui-egui/src/lib.rs | 1 + docs/occurrence-workflows.md | 31 ++ 12 files changed, 721 insertions(+), 9 deletions(-) create mode 100644 crates/ui-egui/src/dialogs_part_size.rs diff --git a/assets/locales/en.json b/assets/locales/en.json index 1baf03392..7557c6b44 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -1398,6 +1398,7 @@ "ui.pan_zoom_orbit": "Pan, zoom, orbit", "ui.parallel": "Parallel", "ui.parameters": "Parameters", + "ui.part_size_shared": "Rebuilds the part, replacing any added features. All occurrences of this component update.", "ui.paste": "Paste", "ui.path": "Path", "ui.pattern_on_path": "Pattern on Path", diff --git a/assets/locales/it.json b/assets/locales/it.json index 05720236e..64e3bc8f9 100644 --- a/assets/locales/it.json +++ b/assets/locales/it.json @@ -1317,6 +1317,7 @@ "ui.pan_zoom_orbit": "Panoramica, zoom, orbita", "ui.parallel": "Parallelo", "ui.parameters": "Parametri", + "ui.part_size_shared": "Ricostruisce la parte, sostituendo le eventuali lavorazioni aggiunte. Si aggiornano tutte le occorrenze del componente.", "ui.paste": "Incolla", "ui.path": "Percorso", "ui.pattern_on_path": "Ripetizione su percorso", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 3bce6c952..ba6fbfe04 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -1398,6 +1398,7 @@ "ui.pan_zoom_orbit": "パン、ズーム、オービット", "ui.parallel": "平行", "ui.parameters": "パラメータ", + "ui.part_size_shared": "パーツを再構築し、追加したフィーチャを置き換えます。このコンポーネントのすべての配置が更新されます。", "ui.paste": "貼り付け", "ui.path": "パス", "ui.pattern_on_path": "パス上のパターン", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index 0c43a6905..8bfb7be4e 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -1398,6 +1398,7 @@ "ui.pan_zoom_orbit": "平移、缩放、环绕", "ui.parallel": "平行", "ui.parameters": "参数", + "ui.part_size_shared": "重新生成零件并替换额外添加的特征。此零部件的所有实例都会更新。", "ui.paste": "粘贴", "ui.path": "路径", "ui.pattern_on_path": "路径阵列", diff --git a/crates/engine/src/cmd/parts.rs b/crates/engine/src/cmd/parts.rs index 36ffcd4fc..f2e29caad 100644 --- a/crates/engine/src/cmd/parts.rs +++ b/crates/engine/src/cmd/parts.rs @@ -26,7 +26,7 @@ pub static COMMANDS: &[CommandSpec] = &[ length? (mm; screws, bolts, set screws, pins; default a standard length near 2.5 d); \ at?: [x,y,z] on a hole's rim or wall (the part seats on the hole's face with a rigid joint) | point?: [x,y,z] with direction?: [x,y,z] (no joint); name?", ), - CommandSpec::new("parts.resize", "Change Part Size", resize).icon("scale") + CommandSpec::new("parts.resize", "Change Part Size", resize_atomic).icon("scale") .params("component: id|name of an inserted part; size?; length? — rebuilds it (joints keep it seated)"), ]; @@ -215,16 +215,20 @@ fn run(s: &mut Session, id: &str, p: Value) -> Result { /// A hex prism (across flats `af`) from z0 to z1, joined or cut. fn hex(s: &mut Session, af: f64, z0: f64, z1: f64, op: &str) -> Result<()> { - run(s, "sketch.create", json!({"plane": "XY", "offset": z0}))?; + run(s, "sketch.create", json!({"plane": "XY", "offset": format!("{z0} mm")}))?; run(s, "sketch.polygon.circumscribed", json!({"center": [0, 0], "radius": af / 2.0, "sides": 6}))?; run(s, "sketch.finish", json!({}))?; let (dist, dir) = if z1 >= z0 { (z1 - z0, "positive") } else { (z0 - z1, "negative") }; - run(s, "solid.extrude", json!({"distance": dist, "direction": dir, "operation": op}))?; + run(s, "solid.extrude", json!({"distance": format!("{dist} mm"), "direction": dir, "operation": op}))?; Ok(()) } fn cyl(s: &mut Session, d: f64, z0: f64, z1: f64, op: &str) -> Result<()> { - run(s, "solid.cylinder", json!({"diameter": d, "height": z1 - z0, "base": [0, 0, z0], "axis": [0, 0, 1], "operation": op}))?; + run( + s, + "solid.cylinder", + json!({"diameter": format!("{d} mm"), "height": format!("{} mm", z1 - z0), "base": [0, 0, z0], "axis": [0, 0, 1], "operation": op}), + )?; Ok(()) } @@ -245,6 +249,7 @@ fn thread(s: &mut Session, d: f64, pitch: f64, at: Vec3) { /// Build a part in the active component. fn build(s: &mut Session, sh: &Shape) -> Result<()> { + let _frame = crate::frames::local_geometry(); match *sh { Shape::Screw { d, pitch, len, head, socket } => { let k = match head { @@ -454,6 +459,19 @@ fn shape_len(sh: &Shape) -> Option { } } +/// Building the replacement runs several feature commands. Keep their intermediate history +/// and any failed build on a scratch session; the outer command records one complete undo. +fn resize_atomic(s: &mut Session, p: &Value) -> Result { + let mut computed = s.scratch(); + let result = resize(&mut computed, p)?; + computed.undo.clear(); + computed.active_component = s.active_component; + computed.active_occurrence_path = s.active_occurrence_path.clone(); + computed.active_sketch = s.active_sketch.filter(|id| computed.doc.feature(*id).is_some()); + s.accept_computed(computed); + Ok(result) +} + fn resize(s: &mut Session, p: &Value) -> Result { let cmd = "parts.resize"; let key = match p.get("component") { @@ -556,5 +574,83 @@ mod tests { run(&mut s, "parts.resize", json!({"component": comp, "size": "M8", "length": 25})); let (lo, hi) = bbox(&s, "SHCS M8x25"); assert!((hi.z - 18.0).abs() < 1e-6 && (lo.z + 15.0).abs() < 1e-6, "{lo:?} {hi:?}"); + assert!(s.model.state().threads.iter().any(|t| t.designation == "M8" && (t.pitch - 1.25).abs() < 1e-9)); + } + + #[test] + fn resizing_placed_parts_uses_local_geometry_and_millimetres_in_every_design_unit() { + for (family, initial, resized, prefix) in [ + ("socket_head_cap_screw", "M6", "M8", "SHCS"), + ("hex_bolt", "M6", "M8", "Hex Bolt"), + ("hex_nut", "M6", "M8", "Hex Nut"), + ("washer", "M6", "M8", "Washer"), + ("set_screw", "M6", "M8", "Set Screw"), + ("dowel_pin", "6", "8", "Dowel Pin"), + ("bearing", "608", "6200", "Bearing"), + ] { + let mut bounds = Vec::new(); + for units in ["mm", "in"] { + let mut s = Session::default(); + run(&mut s, "document.units", json!({"units":units})); + let part = run(&mut s, "parts.insert", json!({"family":family,"size":initial,"length":20,"point":[40,50,60],"direction":[1,0,0]})); + run(&mut s, "parts.resize", json!({"component":part["component"],"size":resized,"length":30})); + assert!(s.model.results.iter().all(|r| r.error.is_none()), "{family} {units}"); + let b = bbox(&s, prefix); + assert!(b.0.x < b.1.x && b.0.y < b.1.y && b.0.z < b.1.z, "{family} {units}: {b:?}"); + if matches!(family, "socket_head_cap_screw" | "hex_bolt" | "hex_nut" | "set_screw") { + assert!(s.model.state().threads.iter().any(|t| t.designation == "M8" && (t.pitch - 1.25).abs() < 1e-9), "{family} {units}"); + } + if family == "dowel_pin" { + assert!(b.0.dist(solidcraft_geom::Vec3::new(10., 46., 56.)) < 1e-6, "{b:?}"); + assert!(b.1.dist(solidcraft_geom::Vec3::new(40., 54., 64.)) < 1e-6, "{b:?}"); + } + bounds.push(b); + } + assert!(bounds[0].0.dist(bounds[1].0) < 1e-6 && bounds[0].1.dist(bounds[1].1) < 1e-6, "{family}: {bounds:?}"); + } + } + + #[test] + fn resizing_a_part_is_one_undo_and_keeps_the_active_occurrence() { + let mut s = Session::default(); + let part = run(&mut s, "parts.insert", json!({"family":"socket_head_cap_screw","size":"M6","length":20})); + let id = part["component"].as_u64().unwrap_or(0); + let copied = run(&mut s, "occurrence.copy", json!({"component":id,"translate":[40,0,0]})); + let path = vec![copied["occurrence"].as_u64().unwrap_or(0)]; + run(&mut s, "component.activate", json!({"component":id,"occurrence":copied["occurrence"],"path":path})); + let before = s.doc.clone(); + let undo = s.undo.len(); + run(&mut s, "parts.resize", json!({"component":id,"size":"M8","length":25})); + assert_eq!(s.undo.len(), undo + 1); + assert_eq!(s.active_component, id); + assert_eq!(s.active_occurrence_path, Some(path.clone())); + let after = s.doc.clone(); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc, before); + let redo = s.redo.len(); + assert!(s.execute("parts.resize", &json!({"component":id,"length":0})).is_err()); + assert_eq!(s.doc, before); + assert_eq!(s.redo.len(), redo); + assert_eq!(s.active_occurrence_path, Some(path)); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.doc, after); + } + + #[test] + fn resizing_a_part_at_the_history_limit_drops_only_one_old_step() { + let mut s = Session::default(); + let part = run(&mut s, "parts.insert", json!({"family":"washer","size":"M6"})); + let Some(snapshot) = s.undo.last().cloned() else { panic!("insert did not record history") }; + s.undo = (0..crate::MAX_UNDO) + .map(|index| { + let mut old = snapshot.clone(); + old.label = format!("Earlier step {index}"); + old + }) + .collect(); + run(&mut s, "parts.resize", json!({"component":part["component"],"size":"M8"})); + assert_eq!(s.undo.len(), crate::MAX_UNDO); + assert_eq!(s.undo.first().map(|step| step.label.as_str()), Some("Earlier step 1")); + assert_eq!(s.undo.last().map(|step| step.label.as_str()), Some("Change Part Size")); } } diff --git a/crates/engine/src/frames.rs b/crates/engine/src/frames.rs index 9d83ff9fb..ec9274e98 100644 --- a/crates/engine/src/frames.rs +++ b/crates/engine/src/frames.rs @@ -310,6 +310,20 @@ pub fn mapped() -> bool { MAPPED.with(std::cell::Cell::get) } +/// Author generated geometry directly in the active component's local frame. +/// Restores the enclosing command's mapping state, including on an error. +pub(crate) fn local_geometry() -> LocalGeometry { + LocalGeometry(MAPPED.with(|m| m.replace(true))) +} + +pub(crate) struct LocalGeometry(bool); + +impl Drop for LocalGeometry { + fn drop(&mut self) { + MAPPED.with(|m| m.set(self.0)); + } +} + /// A command running inside another (its parameters are already in component frames). pub struct Nested; diff --git a/crates/ui-egui/src/browser.rs b/crates/ui-egui/src/browser.rs index 013734fc2..37d1c1f28 100644 --- a/crates/ui-egui/src/browser.rs +++ b/crates/ui-egui/src/browser.rs @@ -709,7 +709,8 @@ fn component_name(app: &SolveApp, id: u64) -> String { let doc = &app.session.doc; let name = doc.components.iter().find(|c| c.id == id).map(|c| c.name.clone()).unwrap_or_default(); let n = doc.occurrences.iter().filter(|o| o.component == id).count(); - if n > 1 { format!("{name} ({n} instances)") } else { format!("{name}:1") } + let name = if n > 1 { format!("{name} ({n} instances)") } else { format!("{name}:1") }; + crate::dialogs_part_size::browser_label(app, id, &name) } fn component_rows(app: &mut SolveApp, ui: &mut egui::Ui, id: u64, depth: usize, acts: &mut Actions) { @@ -766,7 +767,11 @@ fn component_rows(app: &mut SolveApp, ui: &mut egui::Ui, id: u64, depth: usize, } } if r.double { - let _ = app.run("component.activate", json!({ "component": id })); + if app.session.doc.parts.contains_key(&id) { + crate::dialogs_part_size::open(app, id); + } else { + let _ = app.run("component.activate", json!({ "component": id })); + } } if r.hovered { acts.hover_bodies = bodies.clone(); @@ -823,6 +828,7 @@ fn occurrence_rows(app: &mut SolveApp, ui: &mut egui::Ui, path: Vec, depth: let selected = app.session.selection.contains(&Sel::Occurrence { path: path.clone() }); let faded = app.session.active_occurrence_path.as_ref().is_some_and(|p| !path.starts_with(p) && !p.starts_with(&path)); let badges: &[&str] = if placement.grounded { &["pin"] } else { &[] }; + let label = crate::dialogs_part_size::browser_label(app, placement.component, &placement.name); app.tree.order.push(key.clone()); let r = draw_row( ui, @@ -832,7 +838,7 @@ fn occurrence_rows(app: &mut SolveApp, ui: &mut egui::Ui, path: Vec, depth: fold: Some(open), eye: Some(own_visible), icon: "component", - label: &placement.name, + label: &label, name: true, selected, dim: faded || !visible, @@ -869,9 +875,12 @@ fn occurrence_rows(app: &mut SolveApp, ui: &mut egui::Ui, path: Vec, depth: if r.eye { let _ = app.run("browser.visibility", json!({"visible": app.session.occurrence_hidden(&path), "paths": [path]})); } - if r.radio || r.double { + if r.radio || (r.double && !app.session.doc.parts.contains_key(&placement.component)) { let _ = app.run("component.activate", json!({"component": placement.component, "occurrence": placement.occurrence, "path": path})); } + if r.double && app.session.doc.parts.contains_key(&placement.component) { + crate::dialogs_part_size::open(app, placement.component); + } if r.clicked { click_select(app, ui, key.clone(), Some(Sel::Occurrence { path: path.clone() })); } diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index ec50701d7..e02217e2b 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -492,6 +492,11 @@ fn viewport_items(app: &SolveApp) -> Vec { return v; } if !sel.is_empty() { + if !v.iter().any(|item| item.id == "parts.resize") + && let Some(component) = crate::dialogs_part_size::selected_component(app) + { + v.push(cmd(app, "parts.resize", "Change Part Size").with(json!({"component":component}))); + } v.push(Item::sep()); v.push(act("ui.clear", "Clear Selection", "").key("Esc")); } @@ -525,6 +530,9 @@ fn body_items(app: &SolveApp, bodies: &[String], browser: bool) -> Vec { ]; if one { let b = bodies.first().cloned().unwrap_or_default(); + if let Some(component) = crate::dialogs_part_size::component_for_bodies(app, bodies) { + v.push(cmd(app, "parts.resize", "Change Part Size").with(json!({"component":component}))); + } v.push(Item::sep()); if !browser { v.push(act("ui.findBrowser", "Find in Browser", "").with(json!({ "body": b }))); @@ -669,6 +677,9 @@ fn component_items(app: &SolveApp, id: u64) -> Vec { let hidden = !bodies.is_empty() && bodies.iter().all(|b| app.session.visibility.hidden_bodies.contains(b)); let names = json!(bodies); let mut v = Vec::new(); + if doc.parts.contains_key(&id) { + v.push(cmd(app, "parts.resize", "Edit").with(json!({"component":id}))); + } if id != 0 { let grounded = occ.is_some_and(|o| o.grounded); let oid = occ.map(|o| o.id).unwrap_or(0); @@ -880,6 +891,13 @@ pub fn run_item(app: &mut SolveApp, item: &Item, at: Pos2) { let p = item.params.clone().unwrap_or(Value::Null); let bodies = strs(&p, "bodies"); match item.id.as_str() { + "parts.resize" => { + if let Some(component) = id_of(&p, "component") { + crate::dialogs_part_size::open(app, component); + } else { + app.start("parts.resize"); + } + } "ui.repeat" => { if let Some((id, _)) = app.last_command.clone() { app.start(&id); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 8965fdeab..531694cbc 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -348,6 +348,7 @@ pub enum Kind { Motion(crate::dialogs_motion::Mo), /// Insert Part from the standard parts library (`dialogs_parts`). Part(crate::dialogs_parts::Pt), + PartSize(crate::dialogs_part_size::Resize), /// Edit Text: a sketch text's content and placement (`sketch_text`). Text(Box), TextMove(crate::sketch_text_move::TextMove), @@ -716,6 +717,7 @@ impl Dialog { .or_else(|| crate::dialogs_appearance::start(app, id)) .or_else(|| crate::dialogs_motion::start(app, id)) .or_else(|| crate::dialogs_parts::start(app, id)) + .or_else(|| crate::dialogs_part_size::start(app, id)) .or_else(|| crate::sketch_text::start(app, id)) .or_else(|| crate::sketch_text_move::start(app, id)) .or_else(|| crate::sketch_modify_ui::start(app, id))?; @@ -854,7 +856,7 @@ impl Dialog { Kind::Surface(_) => return true, Kind::SketchModify(k) => return k.previews(), Kind::Plastic(k) => return k.previews(), - Kind::Part(_) => return true, + Kind::Part(_) | Kind::PartSize(_) => return true, _ => {} } matches!( @@ -1535,6 +1537,7 @@ fn title(k: &Kind) -> &'static str { Kind::Appearance(_) => "APPEARANCE", Kind::Motion(k) => k.title(), Kind::Part(_) => "INSERT PART", + Kind::PartSize(_) => "Change Part Size", Kind::Text(_) => "EDIT TEXT", Kind::TextMove(_) => "MOVE/COPY TEXT", Kind::SketchModify(k) => k.title(), @@ -3139,6 +3142,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { Kind::Appearance(k) => enter |= crate::dialogs_appearance::rows(app, ui, k, &mut d.inputs), Kind::Motion(k) => enter |= crate::dialogs_motion::rows(app, ui, k, &mut d.inputs), Kind::Part(k) => enter |= crate::dialogs_parts::rows(app, ui, k, &d.inputs), + Kind::PartSize(k) => enter |= crate::dialogs_part_size::rows(app, ui, k), Kind::Text(k) => enter |= crate::sketch_text::rows(ui, k, &mut d.inputs, &mut d.active), Kind::TextMove(k) => enter |= crate::sketch_text_move::rows(ui, k), Kind::ConfirmDelete { with, fail, .. } => { @@ -4474,6 +4478,7 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result, S Kind::Appearance(k) => return Ok(crate::dialogs_appearance::commands(k, &d.inputs)), Kind::Motion(k) => return crate::dialogs_motion::commands(app, k, &d.inputs), Kind::Part(k) => return crate::dialogs_parts::commands(app, k, &d.inputs), + Kind::PartSize(k) => return crate::dialogs_part_size::commands(app, k), Kind::Text(k) => return crate::sketch_text::commands(app, k), Kind::TextMove(k) => return crate::sketch_text_move::commands(app, k), }; diff --git a/crates/ui-egui/src/dialogs_part_size.rs b/crates/ui-egui/src/dialogs_part_size.rs new file mode 100644 index 000000000..9261ad128 --- /dev/null +++ b/crates/ui-egui/src/dialogs_part_size.rs @@ -0,0 +1,534 @@ +//! Change a placed standard part through the existing, undoable `parts.resize` command. + +use std::sync::Arc; + +use egui::RichText; +use serde_json::{Value, json}; +use solidcraft_engine::{Sel, doc::Document}; + +use crate::SolveApp; +use crate::dialogs::{Kind, combo, row_label}; +use crate::dialogs_parts::Family; +use crate::selection::SelInput; + +/// The active catalogue configuration belongs to the shared part, not its placements. +pub(crate) fn configuration(app: &SolveApp, component: u64) -> Option { + let part = app.session.doc.parts.get(&component)?; + let size = part.size.trim(); + if size.is_empty() { + return None; + } + Some(configuration_name(size, part.length)) +} + +fn configuration_name(size: &str, length: Option) -> String { + match length.filter(|length| length.is_finite() && *length > 0.0) { + Some(length) => format!("{size}×{length}"), + None => size.to_owned(), + } +} + +pub(crate) fn browser_label(app: &SolveApp, component: u64, name: &str) -> String { + match configuration(app, component) { + Some(configuration) => format!("{name} [{configuration}]"), + None => name.to_owned(), + } +} + +#[derive(Clone)] +pub struct Resize { + pub component: u64, + pub size: usize, + pub length: Option, + original_size: usize, + family: Family, + source: Arc, +} + +impl std::fmt::Debug for Resize { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Resize") + .field("component", &self.component) + .field("family", &self.family.id) + .field("size", &self.size) + .field("length", &self.length) + .finish_non_exhaustive() + } +} + +/// Resolve a whole definition, including bodies displayed through an occurrence path. +pub fn component_for_bodies(app: &SolveApp, bodies: &[String]) -> Option { + let state = app.session.world_state(); + let mut component = None; + for name in bodies { + let body = state.bodies.iter().find(|b| b.name == *name)?; + let id = app.session.doc.model_body_component(body); + if !app.session.doc.parts.contains_key(&id) || component.is_some_and(|c| c != id) { + return None; + } + component = Some(id); + } + component +} + +pub fn selected_component(app: &SolveApp) -> Option { + if app.session.selection.is_empty() { + let [id] = app.tree.picked_components.as_slice() else { return None }; + return app.session.doc.parts.contains_key(id).then_some(*id); + } + let mut bodies = Vec::new(); + let mut component = None; + for sel in &app.session.selection { + match sel { + Sel::Body { name } => bodies.push(name.clone()), + Sel::Face { body, .. } | Sel::Edge { body, .. } | Sel::Vertex { body, .. } => bodies.push(body.clone()), + Sel::Occurrence { path } => { + let id = app.session.occurrence_placement(path).ok()?.component; + if !app.session.doc.parts.contains_key(&id) || component.is_some_and(|c| c != id) { + return None; + } + component = Some(id); + } + _ => return None, + } + } + if !bodies.is_empty() { + let id = component_for_bodies(app, &bodies)?; + if component.is_some_and(|c| c != id) { + return None; + } + component = Some(id); + } + component +} + +impl Resize { + fn new(app: &SolveApp, component: u64) -> Option { + let part = app.session.doc.parts.get(&component)?; + let response = app.session.scratch().execute("parts.library", &json!({})).ok()?; + let mut family = crate::dialogs_parts::families(&response).into_iter().find(|f| f.id == part.family)?; + for (label, row) in &mut family.sizes { + if let Some(diameter) = row.get("size").and_then(Value::as_f64) { + *label = diameter.to_string(); + } + } + let size = family.sizes.iter().position(|(s, row)| match family.id.as_str() { + "dowel_pin" => part + .size + .trim_start_matches(['d', 'D', 'Ø']) + .trim() + .parse::() + .ok() + .is_some_and(|d| row.get("d").and_then(Value::as_f64) == Some(d)), + "bearing" => s == part.size.trim(), + _ => s.eq_ignore_ascii_case(&part.size), + })?; + Some(Self { component, size, original_size: size, length: part.length, family, source: app.session.doc.clone() }) + } + + fn current(&self, app: &SolveApp) -> Result<(), String> { + if !Arc::ptr_eq(&self.source, &app.session.doc) || !app.session.doc.parts.contains_key(&self.component) { + return Err("The design changed. Reopen Change Part Size for the component.".into()); + } + Ok(()) + } + + fn lengths(&self) -> Option> { + // A future library family may give each size its own lengths. + let row = &self.family.sizes.get(self.size)?.1; + let mut lengths: Vec = match row.get("lengths").and_then(Value::as_array) { + Some(values) => values.iter().filter_map(|v| v.as_f64().or_else(|| v.get("length").and_then(Value::as_f64))).collect(), + None => self.family.lengths.clone()?, + }; + if let Some(current) = self.length { + lengths.push(current); + } + lengths.retain(|l| l.is_finite() && *l > 0.0 && *l <= 2000.0); + lengths.sort_by(f64::total_cmp); + lengths.dedup(); + Some(lengths) + } +} + +pub fn start(app: &SolveApp, id: &str) -> Option<(Kind, Vec)> { + if id != "parts.resize" { + return None; + } + Some((Kind::PartSize(Resize::new(app, selected_component(app)?)?), vec![])) +} + +/// Select the context menu's exact target before using the normal command-start lifecycle. +pub fn open(app: &mut SolveApp, component: u64) { + if Resize::new(app, component).is_none() { + app.set_status("Select an inserted standard part to change its size", true); + return; + } + app.session.selection.clear(); + app.tree.picked_components = vec![component]; + app.start("parts.resize"); +} + +pub fn rows(app: &SolveApp, ui: &mut egui::Ui, k: &mut Resize) -> bool { + row_label(ui, "Type"); + ui.add(egui::Label::new(format!("{} ({})", k.family.name, k.family.standard)).wrap()); + ui.end_row(); + row_label(ui, "Size"); + let sizes: Vec<&str> = k.family.sizes.iter().map(|s| s.0.as_str()).collect(); + combo(ui, "part_resize_size", &sizes, &mut k.size); + ui.end_row(); + if let Some(lengths) = k.lengths() { + let mut index = k.length.and_then(|l| lengths.iter().position(|x| *x == l)).unwrap_or(0); + let labels: Vec = lengths.iter().map(|l| crate::prefs::show_mm(app, *l, 1)).collect(); + let labels: Vec<&str> = labels.iter().map(String::as_str).collect(); + row_label(ui, "Length"); + combo(ui, "part_resize_length", &labels, &mut index); + ui.end_row(); + k.length = lengths.get(index).copied(); + } + if let Some((size, _)) = k.family.sizes.get(k.size) { + row_label(ui, "Configuration"); + ui.label(configuration_name(size, k.length)); + ui.end_row(); + } + row_label(ui, ""); + ui.add(egui::Label::new(RichText::new(crate::i18n::tr("ui.part_size_shared")).color(crate::theme::Tokens::get().text_dim)).wrap()); + ui.end_row(); + false +} + +pub fn commands(app: &SolveApp, k: &Resize) -> Result, String> { + k.current(app)?; + let (size, _) = k.family.sizes.get(k.size).ok_or("Pick a part size")?; + let mut params = json!({"component":k.component,"size":size}); + if let Some(length) = k.length { + if !length.is_finite() || length <= 0.0 || length > 2000.0 { + return Err("Part length must be greater than zero and at most 2000 mm".into()); + } + params["length"] = json!(length); + } + if k.size == k.original_size && k.source.parts.get(&k.component).is_some_and(|part| part.length == k.length) { + return Ok(Vec::new()); + } + Ok(vec![("parts.resize".into(), params)]) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod tests { + use super::*; + use crate::context_menu::{self, Target}; + use solidcraft_engine::{Session, geom::Vec3}; + + fn part(family: &str, size: &str, length: Option) -> (SolveApp, u64) { + let mut app = SolveApp::new(Session::default(), crate::Services::default()); + let mut p = json!({"family":family,"size":size,"point":[10,20,30]}); + if let Some(length) = length { + p["length"] = json!(length); + } + let id = app.run("parts.insert", p).unwrap()["component"].as_u64().unwrap(); + (app, id) + } + + fn menu(app: &mut SolveApp, target: Target) { + let items = context_menu::items(app, &target); + let item = items.iter().find(|i| i.id == "parts.resize").expect("Change Part Size in context menu"); + context_menu::run_item(app, item, egui::Pos2::ZERO); + } + + fn editor(app: &SolveApp) -> &Resize { + let Kind::PartSize(k) = &app.dialog.as_ref().unwrap().kind else { panic!("not a part-size dialog") }; + k + } + + fn change(app: &mut SolveApp, size: &str, length: Option) { + let Kind::PartSize(k) = &mut app.dialog.as_mut().unwrap().kind else { panic!("not a part-size dialog") }; + k.size = k.family.sizes.iter().position(|(s, _)| s == size).unwrap(); + k.length = length; + } + + fn apply(app: &mut SolveApp) { + let commands = crate::dialogs::apply_commands(app, app.dialog.as_ref().unwrap()).unwrap(); + for (id, params) in commands { + app.run(&id, params).unwrap(); + } + crate::dialogs::cancel(app); + } + + #[test] + fn part_size_browser_configuration_edits_the_same_part_and_follows_history_and_reopen() { + let (mut app, component) = part("socket_head_cap_screw", "M6", Some(20.0)); + let first = app.session.doc.occurrence_of(component).unwrap().id; + let second = app.run("occurrence.copy", json!({"occurrence":first,"translate":[40,0,0]})).unwrap()["occurrence"].as_u64().unwrap(); + app.run("joint.create", json!({"name":"Seat","type":"rigid","a":{"occurrence":0,"point":[0,0,0]},"b":{"occurrence":first,"point":[0,0,0]}})) + .unwrap(); + let occurrences = app.session.doc.occurrences.clone(); + let joints = app.session.doc.assembly.joints.clone(); + let before = app.session.doc.clone(); + let undo = app.session.undo.len(); + let mut h = crate::scenario::Harness::new(); + h.app = app; + h.app.home.open = false; + for id in [first, second] { + h.app.tree.collapsed.insert(format!("o:{id}")); + } + h.frames(3); + assert_eq!(crate::browser::drawn_rows().iter().filter(|(label, _, _, _)| label.ends_with("[M6×20]")).count(), 2); + let at = h.call("ui.at", json!({"handle":format!("row:occurrence:{second}")})); + let at = at["result"].as_array().unwrap(); + h.call("ui.click", json!({"x":at[0],"y":at[1],"double":true})); + assert_eq!(editor(&h.app).component, component); + assert_eq!(h.app.session.doc, before, "opening configuration is not a model edit"); + assert_eq!(h.app.session.undo.len(), undo); + crate::dialogs::cancel(&mut h.app); + h.frames(2); + let at = h.call("ui.at", json!({"handle":format!("activate:occurrence:{second}")})); + let at = at["result"].as_array().unwrap(); + h.call("ui.click", json!({"x":at[0],"y":at[1]})); + assert!(h.app.dialog.is_none()); + assert_eq!(h.app.session.active_occurrence_path, Some(vec![second])); + let items = context_menu::items(&h.app, &Target::Occurrence { path: vec![second] }); + let edit = items.iter().find(|item| item.id == "parts.resize").unwrap(); + assert_eq!(edit.label, "Edit"); + context_menu::run_item(&mut h.app, edit, egui::Pos2::ZERO); + change(&mut h.app, "M8", Some(25.0)); + apply(&mut h.app); + h.frames(3); + assert_eq!(crate::browser::drawn_rows().iter().filter(|(label, _, _, _)| label.ends_with("[M8×25]")).count(), 2); + assert_eq!(h.app.session.doc.occurrences, occurrences); + assert_eq!(h.app.session.doc.assembly.joints, joints); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.session.active_occurrence_path, Some(vec![second])); + h.app.run("edit.undo", json!({})).unwrap(); + h.frames(3); + assert_eq!(crate::browser::drawn_rows().iter().filter(|(label, _, _, _)| label.ends_with("[M6×20]")).count(), 2); + h.app.run("edit.redo", json!({})).unwrap(); + assert_eq!(configuration(&h.app, component).as_deref(), Some("M8×25")); + let file = std::env::temp_dir().join(format!("solidcraft-part-configuration-{}.solidcraft", std::process::id())); + h.app.run("file.save", json!({"path":file})).unwrap(); + let mut reopened = Session::default(); + reopened.execute("doc.open", &json!({"path":file})).unwrap(); + let reopened = SolveApp::new(reopened, Default::default()); + assert_eq!(configuration(&reopened, component).as_deref(), Some("M8×25")); + assert_eq!(reopened.session.doc.occurrences, occurrences); + let _ = std::fs::remove_file(&file); + let _ = std::fs::remove_file(file.with_extension("solidcraft.bak")); + } + + #[test] + fn part_size_configuration_names_use_catalogue_dimensions_and_keep_ordinary_labels() { + for (family, size, length, expected) in + [("socket_head_cap_screw", "M6", Some(20.5), "M6×20.5"), ("hex_nut", "M8", None, "M8"), ("bearing", "608", None, "608")] + { + let (mut app, component) = part(family, size, length); + app.run("document.units", json!({"units":"in"})).unwrap(); + assert_eq!(configuration(&app, component).as_deref(), Some(expected)); + assert_eq!(browser_label(&app, component, "Named placement"), format!("Named placement [{expected}]")); + assert_eq!(browser_label(&app, 0, "Assembly"), "Assembly"); + } + } + + #[test] + fn part_size_prefills_actual_values_and_resizes_shared_occurrences_in_one_undo() { + let (mut app, id) = part("socket_head_cap_screw", "M5", Some(20.5)); + app.run("occurrence.copy", json!({"component":id,"translate":[40,0,0]})).unwrap(); + let before = app.session.doc.clone(); + let undo = app.session.undo.len(); + let occurrences = before.occurrences.clone(); + menu(&mut app, Target::Component { id }); + let k = editor(&app); + assert_eq!(k.family.sizes[k.size].0, "M5"); + assert_eq!(k.length, Some(20.5)); + assert!(k.lengths().unwrap().contains(&20.5), "keep non-catalogue lengths on opening"); + assert_eq!(app.session.undo.len(), undo); + change(&mut app, "M6", Some(30.0)); + apply(&mut app); + assert_eq!(app.session.doc.occurrences, occurrences); + assert_eq!(app.session.doc.parts[&id].size, "M6"); + assert_eq!(app.session.doc.parts[&id].length, Some(30.0)); + assert_eq!(app.session.undo.len(), undo + 1); + let after = app.session.doc.clone(); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.doc, before); + app.run("edit.redo", json!({})).unwrap(); + assert_eq!(app.session.doc, after); + } + + #[test] + fn part_size_keeps_the_joint_and_placement_of_a_seated_screw() { + let mut app = SolveApp::new(Session::default(), crate::Services::default()); + app.run("solid.box", json!({"length":40,"width":30,"height":10,"body_name":"Plate"})).unwrap(); + app.run("solid.hole", json!({"position":[20,15,10],"diameter":6.4})).unwrap(); + let out = app.run("parts.insert", json!({"family":"socket_head_cap_screw","size":"M6","length":20,"at":[23.2,15,10]})).unwrap(); + assert!(out["joint"].is_number()); + let id = out["component"].as_u64().unwrap(); + let joints = app.session.doc.assembly.joints.clone(); + let occurrences = app.session.doc.occurrences.clone(); + menu(&mut app, Target::Component { id }); + change(&mut app, "M8", Some(25.0)); + apply(&mut app); + assert_eq!(app.session.doc.assembly.joints, joints); + assert_eq!(app.session.doc.occurrences, occurrences); + let state = app.session.world_state(); + let body = state.bodies.iter().find(|b| app.session.doc.model_body_component(b) == id).unwrap(); + let bounds = body.mesh().bounds(); + assert!((bounds.max.z - 18.0).abs() < 1e-6 && (bounds.min.z + 15.0).abs() < 1e-6); + } + + #[test] + fn part_size_resolves_body_face_and_occurrence_contexts_and_rejects_mixed_targets() { + let (mut app, id) = part("hex_nut", "M5", None); + let body = app.session.world_state().bodies.iter().find(|b| app.session.doc.model_body_component(b) == id).unwrap().name.clone(); + menu(&mut app, Target::Body { name: body.clone() }); + assert_eq!(editor(&app).component, id); + crate::dialogs::cancel(&mut app); + app.session.selection = vec![Sel::Face { body: body.clone(), index: 0, point: Vec3::ZERO }]; + menu(&mut app, Target::Viewport); + assert_eq!(editor(&app).component, id); + crate::dialogs::cancel(&mut app); + let occurrence = app.session.doc.occurrence_of(id).unwrap().id; + menu(&mut app, Target::Occurrence { path: vec![occurrence] }); + assert_eq!(editor(&app).component, id); + assert!(component_for_bodies(&app, &["missing".into()]).is_none()); + app.session.selection = vec![Sel::Body { name: body }, Sel::Plane { name: "XY".into() }]; + assert!(selected_component(&app).is_none()); + assert!(!context_menu::items(&app, &Target::Component { id: 0 }).iter().any(|i| i.id == "parts.resize")); + } + + #[test] + fn part_size_cancel_and_preview_do_not_change_the_design_or_history() { + let (mut app, id) = part("hex_bolt", "M6", Some(20.0)); + let before = app.session.doc.clone(); + let undo = app.session.undo.len(); + menu(&mut app, Target::Component { id }); + change(&mut app, "M8", Some(30.0)); + let commands = crate::dialogs::apply_commands(&app, app.dialog.as_ref().unwrap()).unwrap(); + let mut scratch = app.session.scratch(); + scratch.execute(&commands[0].0, &commands[0].1).unwrap(); + assert_eq!(scratch.doc.parts[&id].size, "M8"); + crate::dialogs::cancel(&mut app); + assert_eq!(app.session.doc, before); + assert_eq!(app.session.undo.len(), undo); + } + + #[test] + fn part_size_refuses_stale_documents_and_invalid_values() { + let (mut app, id) = part("socket_head_cap_screw", "M5", Some(20.0)); + let mut k = Resize::new(&app, id).unwrap(); + for bad in [0.0, -1.0, f64::NAN, f64::INFINITY, 2001.0] { + k.length = Some(bad); + assert!(commands(&app, &k).is_err()); + } + k.length = Some(20.0); + k.size = usize::MAX; + assert!(commands(&app, &k).is_err()); + let k = Resize::new(&app, id).unwrap(); + let (other, other_id) = part("hex_bolt", "M6", Some(20.0)); + assert_eq!(id, other_id, "same numeric id in another document"); + assert!(commands(&other, &k).is_err()); + app.run("document.units", json!({"units":"in"})).unwrap(); + assert!(commands(&app, &k).is_err()); + } + + #[test] + fn part_size_round_trips_all_builtin_families_without_adding_a_length_to_rings() { + for (family, size, length) in [ + ("socket_head_cap_screw", "M5", Some(20.0)), + ("hex_bolt", "M5", Some(20.0)), + ("hex_nut", "M5", None), + ("washer", "M5", None), + ("set_screw", "M5", Some(10.0)), + ("dowel_pin", "6", Some(20.0)), + ("bearing", "608", None), + ] { + let (app, id) = part(family, size, length); + let k = Resize::new(&app, id).unwrap(); + assert_eq!(k.component, id); + assert_eq!(k.family.sizes[k.size].0, size); + assert_eq!(k.length, length); + assert!(commands(&app, &k).unwrap().is_empty(), "confirming unchanged values does not rebuild"); + } + } + + #[test] + fn part_size_unchanged_ok_keeps_added_features_and_has_no_undo_step() { + let (mut app, id) = part("hex_bolt", "M6", Some(20.0)); + app.run("component.activate", json!({"component":id})).unwrap(); + app.run("solid.box", json!({"length":2,"width":3,"height":4,"body_name":"Added lug"})).unwrap(); + let before = app.session.doc.clone(); + let undo = app.session.undo.len(); + menu(&mut app, Target::Component { id }); + apply(&mut app); + assert_eq!(app.session.doc, before); + assert_eq!(app.session.undo.len(), undo); + } + + #[test] + fn part_size_opens_accepted_size_aliases_without_rebuilding_unchanged_parts() { + for (family, size, canonical, length) in [ + ("dowel_pin", "D6", "6", Some(20.0)), + ("dowel_pin", "Ø6", "6", Some(20.0)), + ("dowel_pin", "6.0", "6", Some(20.0)), + ("bearing", " 608 ", "608", None), + ] { + let (mut app, id) = part(family, size, length); + let before = app.session.doc.clone(); + let undo = app.session.undo.len(); + menu(&mut app, Target::Component { id }); + let k = editor(&app); + assert_eq!(k.family.sizes[k.size].0, canonical); + assert!(commands(&app, k).unwrap().is_empty()); + apply(&mut app); + assert_eq!(app.session.doc, before); + assert_eq!(app.session.undo.len(), undo); + assert_eq!(app.session.doc.parts[&id].size, size); + } + } + + #[test] + fn part_size_length_labels_use_design_units_without_rescaling_the_command() { + let (mut app, id) = part("socket_head_cap_screw", "M5", Some(20.5)); + app.run("document.units", json!({"units":"in"})).unwrap(); + let mut h = crate::scenario::Harness::new(); + h.app = app; + h.app.home.open = false; + menu(&mut h.app, Target::Component { id }); + h.frames(3); + let label = crate::prefs::show_mm(&h.app, 20.5, 1); + assert!(label.contains("in"), "a length in inches: {label}"); + assert!(h.widget_near(&label, "Length").is_some()); + change(&mut h.app, "M6", Some(20.5)); + let commands = crate::dialogs::apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap(); + assert_eq!(commands[0].1["length"], 20.5); + } + + #[test] + fn part_size_real_widgets_change_size_length_and_confirm_once() { + let (app, id) = part("socket_head_cap_screw", "M5", Some(20.5)); + let mut h = crate::scenario::Harness::new(); + h.app = app; + h.app.home.open = false; + h.frames(3); + let undo = h.app.session.undo.len(); + menu(&mut h.app, Target::Component { id }); + h.frames(3); + h.step(&json!({"widget":"M5","near":"Size"})).unwrap(); + h.step(&json!({"widget":"M6"})).unwrap(); + let current = crate::prefs::show_mm(&h.app, 20.5, 1); + let shorter = crate::prefs::show_mm(&h.app, 10.0, 1); + h.step(&json!({"widget":current,"near":"Length"})).unwrap(); + h.step(&json!({"widget":shorter})).unwrap(); + assert_eq!(editor(&h.app).length, Some(10.0)); + h.step(&json!({"widget":"OK"})).unwrap(); + for _ in 0..200 { + h.frames(1); + if h.app.dialog.is_none() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert!(h.app.dialog.is_none(), "the operation completed: {:?}", h.app.status); + assert_eq!(h.app.session.doc.parts[&id].size, "M6"); + assert_eq!(h.app.session.doc.parts[&id].length, Some(10.0)); + assert_eq!(h.app.session.undo.len(), undo + 1); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 89483780d..37a7b1d6e 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -31,6 +31,7 @@ pub mod dialogs_coupling; pub mod dialogs_library; pub mod dialogs_motion; pub mod dialogs_move; +pub mod dialogs_part_size; pub mod dialogs_parts; pub mod dialogs_plastic; pub mod dialogs_save_mesh; diff --git a/docs/occurrence-workflows.md b/docs/occurrence-workflows.md index dff1ad317..846911ab5 100644 --- a/docs/occurrence-workflows.md +++ b/docs/occurrence-workflows.md @@ -59,3 +59,34 @@ New face-attached sketches capture the selected body's producer, certified face Use `sketch.redefine` with the sketch ID and a new plane to repair or convert an attachment. Its preview is disposable; Apply records one undo step. An optional `author_path` explicitly repairs a missing author placement. Rebinding a repeated owner from another active component requires that path. Changing the target or converting to a fixed plane detaches only the old automatic face borders, retaining their currently evaluated geometry and entity IDs; unrelated projection links remain live. Pending positions on the involved target and author paths are captured with the edit, while unrelated pending positions remain pending. Paste New remaps internal certified targets and authoring paths to the copied definitions. Timeline paste reports retained external face targets and refuses translating such attachments until an explicit fixed-plane conversion establishes independent geometry. Rename preserves certified body identity; another producer using the same body name cannot repair a lost attachment. + +## Change the size of a standard component + +An inserted standard part is one component with an active catalogue configuration. +Its Browser entry shows that configuration alongside its placement name, for example +`Screw:1 [M6×20]`. Double-click the entry or choose **Edit** to open its configuration +dialog. The activation radio still activates the component; double-clicking ordinary +components keeps its existing activation behavior. The viewport also offers +**Change Part Size** for a picked standard screw, bolt, nut, washer, pin or bearing. +The dialog starts with the +component's current family, size and actual length, including a non-catalogue +length. Choose a size and, for parts with a length, a length, then confirm with OK. +Cancel leaves the design unchanged. + +Resizing regenerates the standard part, replacing any extra features added inside +that component. The dialog warns about this before applying the change. + +This edits the component definition: every occurrence of that component receives +the new size. Its occurrences and their placements and joints are retained. Undo +reverts the size change in one step. Insert another standard part when a separate +component with a different size is needed. + +The dialog uses the same `parts.library` catalogue and `parts.resize` command as +scripts. It is offered only for inserted standard parts. Other component types +retain their usual feature-editing tools. + +The configuration is read from the existing standard-part family, size and length +metadata, so it survives save/reopen and follows undo/redo without renaming any +occurrence. Lengths in the compact configuration name are catalogue millimetres; +the dialog displays lengths in the design's units. General parameter-driven +configurations are outside this change. From 3d105fb281f7b8de8cd6a553c29a0f93ed23e5dc Mon Sep 17 00:00:00 2001 From: NOWN-DEV <257771410+NOWN-DEV@users.noreply.github.com> Date: Mon, 19 Oct 2026 23:22:37 +0200 Subject: [PATCH 118/225] parameters: import evaluates once; parameters.change takes several names (#2777) * parameters: import evaluates once; parameters.change takes several names parameters.import checked every row through change_param, which cloned the design and evaluated every parameter per row: 2000 rows took 9.5 s, 2823 in an assembly minutes. Rows are now checked and applied in one pass with the values carried along, then evaluated once (2000 rows: 0.016 s), still all or nothing; a row may name a parameter defined by a later row. parameters.change {changes: {name: expression, ...}} sets several existing parameters together, rebuilt once and undone in one step. Co-Authored-By: Claude Opus 5.5 (1M context) * parameters.change: the params doc names the `changed` result of `changes` Co-Authored-By: Claude Opus 5.5 (1M context) --------- Co-authored-by: Claude Opus 5.5 (1M context) Co-authored-by: bherbruck --- crates/doc/src/expr.rs | 29 ++++--- crates/doc/src/params.rs | 94 +++++++++++++++++++++-- crates/engine/src/cmd/parameters.rs | 26 ++++++- crates/engine/src/cmd/parameters_tests.rs | 62 +++++++++++++++ 4 files changed, 189 insertions(+), 22 deletions(-) diff --git a/crates/doc/src/expr.rs b/crates/doc/src/expr.rs index 1ccb44018..25c9f89f9 100644 --- a/crates/doc/src/expr.rs +++ b/crates/doc/src/expr.rs @@ -897,10 +897,6 @@ pub fn eval_params(params: &[ParamDef], doc_len: f64) -> (BTreeMap 512 { return Err(DocError::Expr("parameters nested too deeply".into())); } - let Some((kind, _)) = unit_info(&p.unit).or(Some((Kind::Length, 1.0))) else { - return Err(DocError::Expr(format!("unknown unit `{}`", p.unit))); - }; - let defaults = Defaults::for_unit(&p.unit, cx.doc_len); cx.stack.push(name.to_string()); let mut vals: BTreeMap = BTreeMap::new(); let mut err = None; @@ -918,17 +914,7 @@ pub fn eval_params(params: &[ParamDef], doc_len: f64) -> (BTreeMap Err(e), - None => { - eval_with_defaults(&p.expr, &|n| vals.get(n).copied().ok_or_else(|| DocError::Expr(format!("unknown parameter `{n}`"))), defaults) - .and_then(|v| { - let x = v.to_kind_in(kind, defaults)?; - Ok(match kind { - Kind::Length => Value::length(x), - Kind::Angle => Value::angle(x), - Kind::Unitless => Value::num(x), - }) - }) - } + None => eval_def(p, &|n| vals.get(n).copied().ok_or_else(|| DocError::Expr(format!("unknown parameter `{n}`"))), cx.doc_len), }; match &r { Ok(v) => { @@ -949,6 +935,19 @@ pub fn eval_params(params: &[ParamDef], doc_len: f64) -> (BTreeMap Result, doc_len: f64) -> Result { + let (kind, _) = unit_info(&p.unit).unwrap_or((Kind::Length, 1.0)); + let defaults = Defaults::for_unit(&p.unit, doc_len); + let x = eval_with_defaults(&p.expr, lookup, defaults)?.to_kind_in(kind, defaults)?; + Ok(match kind { + Kind::Length => Value::length(x), + Kind::Angle => Value::angle(x), + Kind::Unitless => Value::num(x), + }) +} + /// Dependency edges between parameters: (parameter, parameter it references). pub fn param_edges(params: &[ParamDef]) -> Vec<(String, String)> { let mut out = Vec::new(); diff --git a/crates/doc/src/params.rs b/crates/doc/src/params.rs index 25e0fc2c4..1ec392c43 100644 --- a/crates/doc/src/params.rs +++ b/crates/doc/src/params.rs @@ -463,14 +463,92 @@ impl Document { if rows.len() > 10_000 { return Err(DocError::Invalid("too many parameters".into())); } + // Each row is checked and applied as `change_param` would, but the parameters are + // evaluated once for all of them, not once per row (thousands of rows took minutes). let mut next = self.clone(); - let mut names = Vec::new(); - for (n, e, u, c) in rows { - next.change_param(&n, &e, u.as_deref(), c.as_deref())?; - names.push(n); + let (mut vals, _) = next.param_values(); + for (n, e, u, c) in &rows { + next.import_row(n, e, u.as_deref(), c.as_deref(), &mut vals)?; + } + let (_, errors) = next.param_values(); + if let Some(e) = rows.iter().find_map(|(n, ..)| errors.get(n)) { + return Err(DocError::Expr(e.clone())); } *self = next; - Ok(names) + Ok(rows.into_iter().map(|(n, ..)| n).collect()) + } + + /// One imported row: the checks and change of `change_param` (a feature's parameter) or + /// `set_param` (a user parameter, a new one taking the unit of its value) without evaluating + /// every parameter. `vals` are the values so far, for the units of the rows after it. + fn import_row(&mut self, name: &str, expr_s: &str, unit: Option<&str>, comment: Option<&str>, vals: &mut BTreeMap) -> Result<()> { + if expr_s.len() > 4096 { + return Err(DocError::Expr("expression too long".into())); + } + let hit = self.features.iter().enumerate().find_map(|(i, f)| f.param_names.iter().position(|n| n == name).map(|k| (i, k))); + if let Some((i, k)) = hit { + let kind = self.features.get(i).and_then(|f| f.kind.inputs().get(k).map(|x| x.2)).unwrap_or(Kind::Unitless); + let expr_s = self.with_design_unit(expr_s, kind); + if let Some(f) = self.features.get_mut(i) + && let Some((_, e, _)) = f.kind.inputs_mut().into_iter().nth(k) + { + *e = expr_s.into(); + } + if let Some(c) = comment { + self.param_comments.insert(name.to_string(), c.to_string()); + } + return Ok(()); + } + if let Some(p) = Self::param_name_problem(name) { + return Err(DocError::Invalid(p)); + } + if expr_s.trim().is_empty() { + return Err(DocError::Expr("empty expression".into())); + } + if let Some(u) = unit + && expr::unit_info(u).is_none() + { + return Err(DocError::Expr(format!("unknown unit `{u}` (mm, cm, m, in, ft, deg, rad or none)"))); + } + if comment.is_some_and(|c| c.len() > 4096) { + return Err(DocError::Invalid("comment too long".into())); + } + match self.params.iter_mut().find(|p| p.name == name) { + Some(p) => { + p.expr = expr_s.trim().to_string(); + if let Some(u) = unit { + p.unit = u.trim().to_string(); + } + if let Some(c) = comment { + p.comment = c.to_string(); + } + } + None => { + if self.params.len() >= MAX_PARAMS { + return Err(DocError::Invalid("too many parameters".into())); + } + let unit = match unit { + Some(u) => u.trim().to_string(), + None => Self::infer_unit_in(vals, expr_s), + }; + self.params.push(crate::Param { + name: name.into(), + expr: expr_s.trim().into(), + unit, + comment: comment.unwrap_or_default().into(), + model: false, + }); + } + } + let def = self.params.iter().find(|p| p.name == name).map(|p| ParamDef { name: p.name.clone(), expr: p.expr.clone(), unit: p.unit.clone() }); + let value = def.and_then(|d| { + expr::eval_def(&d, &|n| vals.get(n).copied().ok_or_else(|| DocError::Expr(format!("unknown parameter `{n}`"))), doc_len(&self.units)).ok() + }); + match value { + Some(v) => vals.insert(name.to_string(), v), + None => vals.remove(name), + }; + Ok(()) } } @@ -558,7 +636,11 @@ impl Document { /// The unit for a new parameter with this expression: that of its value; a bare number is /// a length (mm). pub(crate) fn infer_unit(&self, e: &str) -> String { - let (vals, _) = self.param_values(); + Self::infer_unit_in(&self.param_values().0, e) + } + + /// [`Document::infer_unit`] against parameter values already worked out. + fn infer_unit_in(vals: &BTreeMap, e: &str) -> String { let v = expr::eval_with(e, &|n| vals.get(n).copied().ok_or_else(|| DocError::Expr(format!("unknown parameter `{n}`")))); match v.ok().and_then(|v| v.kind()) { Some(Kind::Unitless) if !expr::references(e).is_empty() => String::new(), diff --git a/crates/engine/src/cmd/parameters.rs b/crates/engine/src/cmd/parameters.rs index daa74cbcb..c15b57aca 100644 --- a/crates/engine/src/cmd/parameters.rs +++ b/crates/engine/src/cmd/parameters.rs @@ -12,7 +12,8 @@ use crate::{EngineError, Result, Session}; pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("parameters.change", "Change Parameters", change_param).at("SOLID", "MODIFY").icon("params").params( "name, expression (number or text), unit?: mm|cm|m|in|ft|deg|rad|\"\" (new parameters default to their value's unit), comment?, \ - favorite?: bool, new_name?: rename (references follow); or delete: name → recomputed: features rebuilt, \ + favorite?: bool, new_name?: rename (references follow); or delete: name; or changes: {name: expression, …} (existing \ + parameters, checked together and rebuilt once, all or nothing) → changed?: {name: value} (with changes), recomputed: features rebuilt, \ restored: features whose earlier result for the same inputs was reused (e.g. a value set back)", ), CommandSpec::new("parameters.list", "List Parameters", list).icon("list").noundo().doc_only().params( @@ -82,6 +83,9 @@ fn known(s: &Session, name: &str) -> bool { fn change_param(s: &mut Session, p: &Value) -> Result { let cmd = "parameters.change"; let solved = s.solved_sketches(); + if let Some(changes) = p.get("changes") { + return change_many(s, changes, &solved); + } if let Some(n) = str_(p, "delete") { s.doc_mut().remove_param(n.trim())?; s.settle_value_edit(&solved)?; @@ -129,6 +133,26 @@ fn change_param(s: &mut Session, p: &Value) -> Result { Ok(out) } +/// `parameters.change {changes}`: several existing parameters set at once, so a design is +/// rebuilt once for all of them instead of once per parameter. +fn change_many(s: &mut Session, changes: &Value, solved: &crate::SketchValues) -> Result { + let cmd = "parameters.change"; + let Some(map) = changes.as_object() else { return Err(bad(cmd, "`changes` must be an object of name: expression")) }; + if map.is_empty() { + return Err(bad(cmd, "`changes` is empty")); + } + let mut list = Vec::with_capacity(map.len()); + for (name, e) in map { + let e = expr_arg(&json!({"e": e}), "e").ok_or_else(|| bad(cmd, format!("`changes.{name}` must be a number or text")))?; + list.push((name.trim().to_string(), e)); + } + s.doc_mut().change_params_atomic(&list)?; + s.settle_value_edit(solved)?; + let (vals, _) = s.doc.param_values(); + let values: serde_json::Map = list.iter().map(|(n, _)| (n.clone(), json!(vals.get(n).map(|v| v.v)))).collect(); + Ok(json!({"changed": values, "recomputed": s.model.last_recomputed, "restored": s.model.last_restored, "errors": failing(s)})) +} + fn list(s: &mut Session, p: &Value) -> Result { let filter = match (bool_(p, "favorites"), str_(p, "filter")) { (Some(true), _) => "favorites".to_string(), diff --git a/crates/engine/src/cmd/parameters_tests.rs b/crates/engine/src/cmd/parameters_tests.rs index 1b9601e46..66a88f1ab 100644 --- a/crates/engine/src/cmd/parameters_tests.rs +++ b/crates/engine/src/cmd/parameters_tests.rs @@ -593,3 +593,65 @@ fn moving_a_parameter_refuses_bad_targets() { } assert_eq!(s.doc.to_json(), before); } + +#[test] +fn a_large_import_is_checked_once_and_keeps_each_rows_unit() { + // 3000 parameters, each the one before plus a millimetre, then an angle, a unit-less + // ratio and a row that names a parameter defined further down: all new, in one import. + let mut csv = String::from("name,expression\n"); + csv.push_str("a,later * 2\np0,1 mm\n"); + for i in 1..3000 { + csv.push_str(&format!("p{i},p{} + 1 mm\n", i - 1)); + } + csv.push_str("turn,30 deg\nratio,p10 / p4\nlater,5\n"); + let mut s = Session::default(); + let t = std::time::Instant::now(); + run(&mut s, "parameters.import", json!({"text": csv})); + println!("import of {} rows: {:.2} s", 3005, t.elapsed().as_secs_f64()); + let (vals, errors) = s.doc.param_values(); + assert!(errors.is_empty(), "{errors:?}"); + let unit = |n: &str| s.doc.param(n).map(|p| p.unit.clone()).unwrap_or_default(); + assert_eq!((unit("p2999"), unit("turn"), unit("ratio"), unit("later")), ("mm".into(), "deg".into(), String::new(), "mm".into())); + assert!( + vals.get("p2999").is_some_and(|v| (v.to_kind(solidcraft_doc::expr::Kind::Length).unwrap_or(f64::NAN) - 3000.0).abs() < 1e-9), + "{:?}", + vals.get("p2999") + ); + assert!( + vals.get("a").is_some_and(|v| (v.to_kind(solidcraft_doc::expr::Kind::Length).unwrap_or(f64::NAN) - 10.0).abs() < 1e-9), + "{:?}", + vals.get("a") + ); + // Changing the first moves the whole chain; a row that breaks changes nothing. + run(&mut s, "parameters.import", json!({"text": "name,expression\np0,101 mm\n"})); + assert!( + s.doc + .param_values() + .0 + .get("p2999") + .is_some_and(|v| (v.to_kind(solidcraft_doc::expr::Kind::Length).unwrap_or(f64::NAN) - 3100.0).abs() < 1e-9) + ); + assert!(s.execute("parameters.import", &json!({"text": "name,expression\np0,2 mm\np5,p0 + 1 deg\n"})).is_err()); + assert_eq!(s.doc.param("p0").map(|p| p.expr.as_str()), Some("101 mm")); +} + +#[test] +fn several_parameters_change_in_one_rebuild_and_one_undo() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "h", "expression": "10 mm"})); + block(&mut s); + let d = run(&mut s, "parameters.list", json!({"filter": "feature"}))["parameters"][0]["name"].as_str().unwrap_or_default().to_string(); + run(&mut s, "parameters.change", json!({"name": d, "expression": "h"})); + let r = run(&mut s, "parameters.change", json!({"changes": {"len": "100 mm", "h": 20}})); + assert_eq!(r["errors"].as_array().map(Vec::len), Some(0), "{r}"); + assert_eq!(r["changed"]["len"], 100.0, "{r}"); + assert!(rel(volume(&mut s), 40.0 * 50.0 * 20.0) < 1e-9); + // All or nothing: an unknown name or a broken expression changes nothing. + assert!(err(&mut s, "parameters.change", json!({"changes": {"len": "60 mm", "nope": "1 mm"}})).contains("nope")); + assert!(s.execute("parameters.change", &json!({"changes": {"len": "60 mm", "h": "1 / 0"}})).is_err()); + assert!(s.execute("parameters.change", &json!({"changes": {}})).is_err()); + assert_eq!(expr_of(&mut s, "len"), "100 mm"); + run(&mut s, "edit.undo", json!({})); + assert_eq!((expr_of(&mut s, "len"), expr_of(&mut s, "h")), ("60 mm".to_string(), "10 mm".to_string())); + assert!(rel(volume(&mut s), 40.0 * 30.0 * 10.0) < 1e-9); +} From a1badaed1768d41d29d0786a6c7a02820f4cd33c Mon Sep 17 00:00:00 2001 From: plexi32 <58932224+plexi32@users.noreply.github.com> Date: Mon, 19 Oct 2026 23:22:44 +0200 Subject: [PATCH 119/225] Convert Mesh uses the selected mesh body (#2482) Convert Mesh uses the selected mesh body. --- crates/engine/src/cmd/mesh.rs | 21 +++++++++++++++---- crates/engine/src/tests/mesh_convert.rs | 28 +++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/mesh.rs b/crates/engine/src/cmd/mesh.rs index 702270f73..d7e22bcd9 100644 --- a/crates/engine/src/cmd/mesh.rs +++ b/crates/engine/src/cmd/mesh.rs @@ -9,21 +9,34 @@ use super::{ features::{add_feature, check_expr}, }; use crate::{ - Result, Session, + Result, Sel, Session, params::{bad, expr, str_}, }; pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("mesh.convert", "Convert Mesh", convert) .icon("import") - .params("body: mesh body name; tolerance?: length expression (default 0.05 mm): reconstruct a closed constant-section mechanical mesh as editable planar and cylindrical faces, with a parametric timeline feature; name?"), + .params("body?: mesh body name (default: the selected mesh body); tolerance?: length expression (default 0.05 mm): reconstruct a closed constant-section mechanical mesh as editable planar and cylindrical faces, with a parametric timeline feature; name?"), ]; +/// The mesh body to convert: `body`, else the one selected body. +fn target(s: &Session, p: &Value, cmd: &str) -> Result { + if let Some(name) = str_(p, "body").filter(|b| !b.trim().is_empty()) { + return Ok(name.to_owned()); + } + let selected: Vec<&str> = s.selection.iter().filter_map(|x| if let Sel::Body { name } = x { Some(name.as_str()) } else { None }).collect(); + match selected.as_slice() { + [name] => Ok((*name).to_owned()), + [] => Err(bad(cmd, "select a mesh body")), + _ => Err(bad(cmd, "select one mesh body")), + } +} + fn convert(s: &mut Session, p: &Value) -> Result { let cmd = "mesh.convert"; - let body = str_(p, "body").filter(|b| !b.trim().is_empty()).ok_or_else(|| bad(cmd, "select a mesh body"))?; let state = s.model.state(); - let source = state.body(body).ok_or_else(|| bad(cmd, format!("no body `{body}`")))?; + let body = target(s, p, cmd)?; + let source = state.body(&body).ok_or_else(|| bad(cmd, format!("no body `{body}`")))?; if !source.body.is_mesh() { return Err(bad(cmd, "select a mesh body")); } diff --git a/crates/engine/src/tests/mesh_convert.rs b/crates/engine/src/tests/mesh_convert.rs index 881d4ef39..c7c3e91fe 100644 --- a/crates/engine/src/tests/mesh_convert.rs +++ b/crates/engine/src/tests/mesh_convert.rs @@ -70,6 +70,34 @@ fn failed_mesh_conversions_leave_the_design_unchanged() { } } +#[test] +fn convert_uses_the_selected_mesh_body_when_body_is_omitted() { + let mut s = imported_box(); + s.selection = vec![crate::Sel::Body { name: "Mesh".into() }]; + run(&mut s, "mesh.convert", json!({"tolerance":"0.01 mm"})); + let state = s.model.state(); + let body = &state.body("Mesh").unwrap().body; + assert!(!body.is_mesh()); + assert_eq!(body.faces(0.01).unwrap().len(), 6); +} + +#[test] +fn convert_without_body_or_selection_is_refused() { + let mut s = imported_box(); + let before = s.doc.to_json(); + assert!(s.execute("mesh.convert", &json!({"tolerance":"0.01 mm"})).is_err()); + assert_eq!(s.doc.to_json(), before); + assert!(s.model.state().body("Mesh").unwrap().body.is_mesh()); +} + +#[test] +fn an_explicit_body_wins_over_the_selection() { + let mut s = imported_box(); + s.selection = vec![crate::Sel::Body { name: "Missing".into() }]; + run(&mut s, "mesh.convert", json!({"body":"Mesh","tolerance":"0.01 mm"})); + assert!(!s.model.state().body("Mesh").unwrap().body.is_mesh()); +} + #[test] fn exported_binary_stl_with_a_bore_reconstructs_analytic_faces() { let mut s = Session::default(); From e5291dc8f77de7485b507ae04721f15f43acdb60 Mon Sep 17 00:00:00 2001 From: kezmdor Date: Mon, 19 Oct 2026 23:22:50 +0200 Subject: [PATCH 120/225] Fonts: egui's built-in Hack as the last fallback for symbols (#2956) Fonts: egui's built-in Hack as the last fallback for symbols. --- crates/ui-egui/src/fonts.rs | 81 +++++++++++++++++++++++++++++-------- 1 file changed, 65 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/src/fonts.rs b/crates/ui-egui/src/fonts.rs index 14ec936eb..1e96674c3 100644 --- a/crates/ui-egui/src/fonts.rs +++ b/crates/ui-egui/src/fonts.rs @@ -51,6 +51,21 @@ pub const HANGUL_FALLBACK: &str = "hangul_fallback"; /// Name of the Thai fallback entry in [`egui::FontDefinitions`], last (#1902). pub const THAI_FALLBACK: &str = "thai_fallback"; +/// egui's built-in monospace face, also the last fallback of the Proportional family (#2955). +pub const SYMBOL_FALLBACK: &str = "Hack"; + +/// `fonts` with egui's built-in Hack last in the Proportional family. Ubuntu-Light, NotoEmoji and +/// emoji-icon-font lack common symbols such as ▲ ▼ ↑ ↓ → ⁻, which Hack has, so they no longer +/// show as empty boxes where no system font fills in (#2955). Text the other faces draw keeps them. +pub fn with_symbol_fallback(mut fonts: egui::FontDefinitions) -> egui::FontDefinitions { + if fonts.font_data.contains_key(SYMBOL_FALLBACK) { + let list = fonts.families.entry(egui::FontFamily::Proportional).or_default(); + list.retain(|name| name != SYMBOL_FALLBACK); + list.push(SYMBOL_FALLBACK.to_owned()); + } + fonts +} + /// UI languages whose text needs the CJK font. The web app's bundled font covers Japanese only; /// add Chinese or Korean here together with a font that covers them. pub const CJK_LANGUAGES: &[&str] = &["ja", "zh", "ko"]; @@ -136,7 +151,7 @@ pub fn install_cjk_font_for(ctx: &egui::Context, bytes: Vec, language: &str) if needs_cjk_font(language) { promote_font_to_front(&mut fonts, CJK_FALLBACK); } - ctx.set_fonts(fonts); + ctx.set_fonts(with_symbol_fallback(fonts)); true } None => false, @@ -540,13 +555,12 @@ pub fn setup_fonts_for(ctx: &egui::Context, language: &str, ui_font: &str) { let hangul = HANGUL_FONT_CANDIDATES.iter().find_map(|path| try_read_font(std::path::Path::new(path))); let thai = THAI_FONT_CANDIDATES.iter().find_map(|path| try_read_font(std::path::Path::new(path))); let mut fonts = egui::FontDefinitions::default(); - // Set the fonts also when only the interface font changes, so going back to the default - // takes the chosen one away. - let mut found = !ui_font.trim().is_empty(); if let Some(font) = self::ui_font(ui_font) { fonts = with_ui_font(fonts, font); } let order = fallback_order(language); + // Whether a system fallback was found. + let mut found = false; for name in order { let bytes = match name { CJK_FALLBACK => cjk.clone(), @@ -561,18 +575,18 @@ pub fn setup_fonts_for(ctx: &egui::Context, language: &str, ui_font: &str) { found = true; } } - if found { - if needs_cjk_font(language) && ui_font.trim().is_empty() { - // For a CJK UI (Japanese, Chinese, Korean) without a custom interface font, - // promote the primary CJK font to the front of FontFamily::Proportional. - // This ensures that ASCII characters (digits, units, English words) within mixed - // labels (e.g. "4 個選択中", "2 mm") are drawn with the same font face as the - // CJK glyphs, sharing identical line height, ascender, and baseline (#1070 follow-up). - let primary = order[0]; - promote_font_to_front(&mut fonts, primary); - } - ctx.set_fonts(fonts); + if found && needs_cjk_font(language) && ui_font.trim().is_empty() { + // For a CJK UI (Japanese, Chinese, Korean) without a custom interface font, + // promote the primary CJK font to the front of FontFamily::Proportional. + // This ensures that ASCII characters (digits, units, English words) within mixed + // labels (e.g. "4 個選択中", "2 mm") are drawn with the same font face as the + // CJK glyphs, sharing identical line height, ascender, and baseline (#1070 follow-up). + let primary = order[0]; + promote_font_to_front(&mut fonts, primary); } + // Set the fonts every time: the symbol fallback goes in even when no system fallback is + // found (#2955), and going back to the default interface font takes the chosen one away. + ctx.set_fonts(with_symbol_fallback(fonts)); } /// Configure font definitions with system fallbacks for an English UI (all fallbacks are @@ -609,13 +623,48 @@ fn find_system_chinese_font() -> Option> { #[cfg(target_arch = "wasm32")] pub fn setup_fonts_for(_ctx: &egui::Context, _language: &str, _ui_font: &str) {} +/// On web only the symbol fallback goes in at start (#2955); the Japanese font loads later +/// through [`install_cjk_font`], which keeps it. #[cfg(target_arch = "wasm32")] -pub fn setup_fonts(_ctx: &egui::Context) {} +pub fn setup_fonts(ctx: &egui::Context) { + ctx.set_fonts(with_symbol_fallback(egui::FontDefinitions::default())); +} #[cfg(test)] mod tests { use super::*; + /// Whether a face of the Proportional family has `c`. Checked in the font data: + /// `Fonts::has_glyph` misses a glyph in the face that also gives the replacement glyph. + fn proportional_draws(fonts: &egui::FontDefinitions, c: char) -> bool { + fonts.families[&egui::FontFamily::Proportional] + .iter() + .filter_map(|name| fonts.font_data.get(name)) + .any(|data| ttf_parser::Face::parse(&data.font, data.index).unwrap().glyph_index(c).is_some()) + } + + /// The symbols the built-in Latin faces lack draw through the built-in Hack (#2955), which + /// comes last and once, after the system fallbacks, and goes in with the desktop's fonts. + #[test] + fn symbols_fall_back_to_the_built_in_hack() { + let fonts = with_symbol_fallback(egui::FontDefinitions::default()); + for c in "▲▼↑↓→⁻".chars() { + assert!(proportional_draws(&fonts, c), "{c:?} (U+{:04X}) has a face", c as u32); + } + let mut with_cjk = egui::FontDefinitions::default(); + with_cjk.families.entry(egui::FontFamily::Proportional).or_default().push(CJK_FALLBACK.to_owned()); + let fonts = with_symbol_fallback(with_symbol_fallback(with_cjk)); + let list = &fonts.families[&egui::FontFamily::Proportional]; + assert_eq!(list.last().map(String::as_str), Some(SYMBOL_FALLBACK), "{list:?}"); + assert_eq!(list.iter().filter(|name| *name == SYMBOL_FALLBACK).count(), 1, "{list:?}"); + assert_ne!(list.first().map(String::as_str), Some(SYMBOL_FALLBACK), "{list:?}"); + let ctx = egui::Context::default(); + setup_fonts_for(&ctx, "en", ""); + ctx.run_ui(egui::RawInput::default(), |_| {}).textures_delta.clear(); + let installed = ctx.fonts(|f| f.definitions().families[&egui::FontFamily::Proportional].clone()); + assert_eq!(installed.last().map(String::as_str), Some(SYMBOL_FALLBACK), "{installed:?}"); + } + #[test] fn the_interface_font_comes_first_and_keeps_the_fallbacks() { // #1290: the chosen font leads the Proportional family; the default face stays after it. From 53a9260aeb1c6f550e508cfd022418b2d3b4caa1 Mon Sep 17 00:00:00 2001 From: NOWN-DEV <257771410+NOWN-DEV@users.noreply.github.com> Date: Mon, 19 Oct 2026 23:22:56 +0200 Subject: [PATCH 121/225] Interference: near-coaxial pins after a STEP round trip, with flush heads, in either order (#1984) Interference: near-coaxial pins after a STEP round trip, with flush heads, in either order. --- crates/engine/src/cmd/joints_tests.rs | 39 ++++++ crates/kernel/src/coaxial_overlap.rs | 177 +++++++++++++++++++++++++- crates/kernel/src/step_in/split.rs | 83 ++++++++++-- 3 files changed, 285 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/joints_tests.rs b/crates/engine/src/cmd/joints_tests.rs index 87a415b06..04c25a426 100644 --- a/crates/engine/src/cmd/joints_tests.rs +++ b/crates/engine/src/cmd/joints_tests.rs @@ -1484,3 +1484,42 @@ fn interference_of_a_pin_a_hair_off_its_hole() { assert!((i["interferences"][0]["near_coaxial"]["offset_mm"].as_f64().unwrap_or(0.0) - offset).abs() < 1e-9, "{i}"); } } + +/// The pin's head has the radius of the bush the pin sits in, on nearly its axis but beside it: +/// two walls of one radius that never meet along the axis don't stop the crescent from counting. +#[test] +fn interference_of_a_headed_pin_a_hair_off_a_bush_of_its_heads_radius() { + let crescent = |r: f64, e: f64| std::f64::consts::PI * r * r - (2.0 * r * r * (e / (2.0 * r)).acos() - e / 2.0 * (4.0 * r * r - e * e).sqrt()); + let offset = 5.9e-4; + let mut s = Session::default(); + run(&mut s, "solid.cylinder", json!({"radius": 5.25, "height": 10, "base": [0, 0, 0], "operation": "new", "body_name": "Bush"})); + run(&mut s, "solid.cylinder", json!({"radius": 3, "height": 14, "base": [0, 0, -2], "operation": "cut", "targets": ["Bush"]})); + run(&mut s, "solid.cylinder", json!({"radius": 3, "height": 8, "base": [offset, 0, -3], "operation": "new", "body_name": "Pin"})); + run(&mut s, "solid.cylinder", json!({"radius": 5.25, "height": 2, "base": [offset, 0, -5], "operation": "join", "targets": ["Pin"]})); + let i = run(&mut s, "inspect.interference", json!({"bodies": ["Bush", "Pin"]})); + assert_eq!(i["unchecked"].as_array().map(Vec::len), Some(0), "{i}"); + assert_eq!(i["count"], 1, "{i}"); + let want = 5.0 * crescent(3.0, offset); + let got = i["interferences"][0]["volume_mm3"].as_f64().unwrap_or(0.0); + assert!((got - want).abs() < 1e-6 * want, "{got} against {want}: {i}"); + assert!(i["interferences"][0]["near_coaxial"].is_object(), "{i}"); +} + +/// A headed pin made before the plate it sits in, a hair off the plate's hole: the crescent +/// whichever body comes first. +#[test] +fn interference_of_a_headed_pin_made_before_its_plate() { + let crescent = |r: f64, e: f64| std::f64::consts::PI * r * r - (2.0 * r * r * (e / (2.0 * r)).acos() - e / 2.0 * (4.0 * r * r - e * e).sqrt()); + let offset = 5.6e-4; + let mut s = Session::default(); + run(&mut s, "solid.cylinder", json!({"radius": 3, "height": 12, "base": [offset, 0, -2.35], "operation": "new", "body_name": "Pin"})); + run(&mut s, "solid.cylinder", json!({"radius": 5.25, "height": 3, "base": [offset, 0, -5.35], "operation": "join", "targets": ["Pin"]})); + run(&mut s, "solid.box", json!({"length": 60, "width": 60, "height": 2, "corner": [-30, -30, -2.35], "body_name": "Plate"})); + run(&mut s, "solid.cylinder", json!({"radius": 3, "height": 9, "base": [0, 0, -6], "operation": "cut", "targets": ["Plate"]})); + let i = run(&mut s, "inspect.interference", json!({"bodies": ["Pin", "Plate"]})); + assert_eq!(i["unchecked"].as_array().map(Vec::len), Some(0), "{i}"); + assert_eq!(i["count"], 1, "{i}"); + let want = 2.0 * crescent(3.0, offset); + let got = i["interferences"][0]["volume_mm3"].as_f64().unwrap_or(0.0); + assert!((got - want).abs() < 1e-6 * want, "{got} against {want}: {i}"); +} diff --git a/crates/kernel/src/coaxial_overlap.rs b/crates/kernel/src/coaxial_overlap.rs index 795e479a2..165f0c839 100644 --- a/crates/kernel/src/coaxial_overlap.rs +++ b/crates/kernel/src/coaxial_overlap.rs @@ -74,7 +74,8 @@ pub fn coaxial_overlap(a: &Body, b: &Body) -> Option { if a.is_mesh() || b.is_mesh() { return None; } - crate::guard("near-coaxial overlap", || Ok(overlap(a, b))).ok().flatten() + // The boolean that takes the core can fail in one order of the bodies and not the other. + crate::guard("near-coaxial overlap", || Ok(overlap(a, b).or_else(|| overlap(b, a)))).ok().flatten() } fn overlap(a: &Body, b: &Body) -> Option { @@ -90,6 +91,14 @@ fn overlap(a: &Body, b: &Body) -> Option { if !ca.iter().any(|x| cb.iter().any(|y| close(x, y))) { return None; } + // A wall that runs once round along a seam edge (as STEP files have them) is cut in two + // first: the boolean cannot always intersect it whole. + let (sa, sb) = (crate::step_in::split::split_seams(a), crate::step_in::split::split_seams(b)); + let (ca, cb) = match (&sa, &sb) { + (None, None) => (ca, cb), + _ => (sa.as_ref().map_or(ca, cylinders), sb.as_ref().map_or(cb, cylinders)), + }; + let (a, b) = (sa.as_ref().unwrap_or(a), sb.as_ref().unwrap_or(b)); let (wa, wb) = (walls(a, ca, same)?, walls(b, cb, same)?); let mut pairs = Vec::new(); for x in &wa { @@ -100,8 +109,10 @@ fn overlap(a: &Body, b: &Body) -> Option { let (pin, hole, pin_in_a) = match (x.boss, y.boss) { (true, false) => (x, y, true), (false, true) => (y, x, false), - // Two pins or two holes on nearly one cylinder: not this case. - _ if near(x, y, same).is_some() => return None, + // Two pins or two holes on nearly one cylinder, side by side along it: not this + // case. Apart along the axis (a screw's head beside a bush of its radius), they + // don't meet. + _ if near(x, y, same).is_some() && total(&intersect(&union(&x.spans), &union(&project(y, x)))) > same => return None, _ => continue, }; let Some((toward, offset)) = near(pin, hole, same) else { continue }; @@ -116,6 +127,11 @@ fn overlap(a: &Body, b: &Body) -> Option { if pairs.is_empty() { return None; } + // A pin's face flush against the other body (a rivet's head on the sheet) touches it over + // an area, which the boolean cannot always take: it is pulled back off it by a little. + // Only material outside the other body goes, so the overlap is the same. + let back = pairs.iter().map(|p| p.step).fold(f64::INFINITY, f64::min) * 0.05; + let (fa, fb) = (flush(a, b, same, back), flush(b, a, same, back)); // A pin's faces move together: one step for each of them (the pin's walls do not repeat // across pairs unless one pin is near two holes, which the check below then answers). let shared_at = |k: f64| -> Option<(f64, Option)> { @@ -124,13 +140,21 @@ fn overlap(a: &Body, b: &Body) -> Option { if mine.is_empty() { return Some(body.clone()); } - let shift = |i: usize, _| mine.iter().find(|p| p.pin.faces.contains(&i)).map(|p| p.step * k).unwrap_or(0.0); + let flush = if in_a { &fa } else { &fb }; + let shift = |i: usize, _| match mine.iter().find(|p| p.pin.faces.contains(&i)) { + Some(p) => p.step * k, + None if flush.contains(&i) => -back, + None => 0.0, + }; let m = crate::offset::offset_body(body, shift).ok()?; m.validity().is_empty().then_some(m) }; let (ma, mb) = (moved(a, true)?, moved(b, false)?); let (r, report) = crate::capture_boolean_diagnostics(|| crate::ops::boolean(&ma, &mb, BoolOp::Intersect)); - if report.unverified().is_some() || report.warning().is_some() { + // The core is the answer and must be exact. The wider pins only check the band, to + // 2 % of what it gains: a tool nudged by a hair of the step there is as good. + let nudge = if k > 0.0 { pairs.iter().map(|p| p.step).fold(f64::INFINITY, f64::min) * 1e-2 } else { 0.0 }; + if report.unverified().is_some() || !altered_by_at_most(&report, nudge, size) { return None; } match r.ok()? { @@ -186,6 +210,17 @@ fn overlap(a: &Body, b: &Body) -> Option { Some(CoaxialOverlap { volume: volume.max(0.0), area, centroid, bbox, offset, length }) } +/// Whether every retry of a boolean that can change its result moved the tool by at most +/// `limit` (a rotation counted at the bodies' `size` from its pivot): none for a `limit` of 0. +fn altered_by_at_most(report: &crate::BooleanDiagnostics, limit: f64, size: f64) -> bool { + !report.truncated + && report + .events + .iter() + .filter(|e| e.strategy.alters_result()) + .all(|e| e.strategy == crate::BooleanStrategy::ToolNudge && limit > 0.0 && e.translation_mm + e.rotation_rad * size <= limit) +} + /// The pin's offset to the hole, when the two are nearly on one cylinder but not on the same /// surface: the unit direction from the pin's axis to the hole's (any, for one axis) and the /// distance. @@ -204,6 +239,51 @@ fn near(pin: &Wall, hole: &Wall, same: f64) -> Option<(Vec3, f64)> { Some((toward, offset)) } +/// The planar faces of `x` that lie on a face of `y`'s facing the other way, where the two touch +/// flat: on a plane of `y`'s, with `y` just beyond the face and not just behind it (within +/// `depth`, at every sampled facet of it). A face on such a plane elsewhere (a collar's +/// underside inside the other body, level with a pocket's floor) is not one. +fn flush(x: &Body, y: &Body, same: f64, depth: f64) -> Vec { + let planes = |b: &Body| -> Vec<(usize, Vec3, Vec3)> { + (0..b.face_count()) + .filter_map(|i| match crate::face_surface(b, i)? { + FaceSurface::Plane { normal, point } => Some((i, normal.vec(), point)), + _ => None, + }) + .collect() + }; + let theirs = planes(y); + let level: Vec<(usize, Vec3)> = planes(x) + .into_iter() + .filter(|(_, n, p)| theirs.iter().any(|(_, m, q)| n.dot(*m) < -1.0 + 1e-9 && (*q - *p).dot(*n).abs() <= same)) + .map(|(i, n, _)| (i, n)) + .collect(); + if level.is_empty() || !(depth.is_finite() && depth > 0.0) { + return Vec::new(); + } + let tol = (x.size().max(y.size()) * 2e-3).max(1e-4); + let (Ok(mx), Ok(my)) = (x.tessellate(tol), y.tessellate(tol)) else { return Vec::new() }; + // At most this many facets of a face are sampled. + const SAMPLES: usize = 64; + level + .into_iter() + .filter(|&(i, n)| { + let centres: Vec = mx + .triangles + .iter() + .zip(&mx.tri_face) + .filter(|(_, f)| **f as usize == i) + .filter_map(|(t, _)| mx.tri(t)) + .filter(|[a, b, c]| (*b - *a).cross(*c - *a).len() > 0.0) + .map(|[a, b, c]| (a + b + c) / 3.0) + .collect(); + let stride = centres.len().div_ceil(SAMPLES).max(1); + !centres.is_empty() && centres.iter().step_by(stride).all(|c| my.contains(*c + n * depth) && !my.contains(*c - n * depth)) + }) + .map(|(i, _)| i) + .collect() +} + /// The body's cylindrical faces, each as a wall of its own with no side or extent yet. fn cylinders(b: &Body) -> Vec { (0..b.face_count()) @@ -246,7 +326,9 @@ fn walls(b: &Body, cylinders: Vec, same: f64) -> Option> { let wall = Wall { faces: vec![face], origin, axis, radius, boss, spans: vec![(lo, hi)] }; match out.iter_mut().find(|w| w.boss == boss && on_one_cylinder(w, &wall, same)) { Some(w) => { - let s = (origin - w.origin).dot(w.axis) * if axis.dot(w.axis) < 0.0 { -1.0 } else { 1.0 }; + // Where the face's origin lies along the wall's axis; a face whose axis runs the + // other way measures its span backwards from there. + let s = (origin - w.origin).dot(w.axis); let (a, b) = if axis.dot(w.axis) < 0.0 { (-hi, -lo) } else { (lo, hi) }; w.faces.push(face); w.spans.push((a + s, b + s)); @@ -421,4 +503,87 @@ mod tests { assert!(coaxial_overlap(&plate, &plate_and_pin(3.0, 0.0).1).is_none()); assert!(coaxial_overlap(&plate, &plate_and_pin(3.0, 0.5).1).is_none()); } + + /// A bush and a headed screw whose shank ends inside the bore, both written to STEP and + /// read back: their cylinders come back as one face each that runs once round along a seam + /// edge, which the boolean cannot intersect where the shank's end meets the bore. The + /// walls are cut in two first and the answer is the one of the bodies as built. + #[test] + fn a_screw_in_a_bush_after_a_step_round_trip() { + let e = 0.01; + let outer = crate::cylinder(Vec3::ZERO, Vec3::Z, 5.0, 10.0).unwrap(); + let bore = crate::cylinder(Vec3::new(0.0, 0.0, -1.0), Vec3::Z, 3.0, 12.0).unwrap(); + let bush = crate::boolean(&outer, &bore, BoolOp::Cut).unwrap().unwrap(); + let shank = crate::cylinder(Vec3::new(e, 0.0, -2.0), Vec3::Z, 3.0, 8.0).unwrap(); + let head = crate::cylinder(Vec3::new(e, 0.0, -5.0), Vec3::Z, 5.25, 3.0).unwrap(); + let screw = crate::boolean(&shank, &head, BoolOp::Union).unwrap().unwrap(); + let back = |b: &Body| crate::step_import(&crate::step_export(&[b], "round trip").unwrap()).unwrap().bodies.remove(0).body; + let (bush, screw) = (back(&bush), back(&screw)); + // The shank shares a crescent with the bush over the 6 mm it reaches into the bore. + let want = 6.0 * crescent(3.0, 3.0, e).area; + for (x, y) in [(&bush, &screw), (&screw, &bush)] { + let o = coaxial_overlap(x, y).unwrap(); + assert!((o.volume - want).abs() < 1e-6 * want, "{o:?} {want}"); + assert!((o.length - 6.0).abs() < 1e-6, "{o:?}"); + } + // Cut in two, each wall is a face more and the body keeps its volume. + let split = crate::step_in::split::split_seams(&bush).unwrap(); + assert_eq!(split.face_count(), bush.face_count() + 2); + let (v0, v1) = (crate::measure(&bush).unwrap().volume, crate::measure(&split).unwrap().volume); + assert!((v0 - v1).abs() < 1e-6 * v0, "{v0} {v1}"); + assert!(crate::step_in::split::split_seams(&outer).is_none()); + } + + /// A pin with a Ø7 collar embedded in a block (the collar's underside at z = 0, inside the + /// block's material), a hair off its hole, and a pocket elsewhere in the block whose floor + /// is at z = 0 too, facing the collar's underside: the two are level but don't touch, so the + /// collar is not pulled back, and all of it inside the block counts. + #[test] + fn a_collar_level_with_a_pocket_floor_elsewhere_is_not_pulled_back() { + let e = 0.01; + let mut block = crate::box_solid(Vec3::new(-10.0, -10.0, -5.0), Vec3::new(20.0, 10.0, 3.0)).unwrap(); + let hole = crate::cylinder(Vec3::new(0.0, 0.0, -6.0), Vec3::Z, 2.0, 10.0).unwrap(); + let pocket = crate::box_solid(Vec3::new(10.0, -3.0, 0.0), Vec3::new(14.0, 3.0, 4.0)).unwrap(); + for cut in [&hole, &pocket] { + block = crate::boolean(&block, cut, BoolOp::Cut).unwrap().unwrap(); + } + let shank = crate::cylinder(Vec3::new(e, 0.0, -7.0), Vec3::Z, 2.0, 8.0).unwrap(); + let collar = crate::cylinder(Vec3::new(e, 0.0, 0.0), Vec3::Z, 3.5, 1.0).unwrap(); + let pin = crate::boolean(&shank, &collar, BoolOp::Union).unwrap().unwrap(); + // The collar less the hole, plus the shank's crescent over the 5 mm below the collar. + let want = std::f64::consts::PI * (3.5 * 3.5 - 2.0 * 2.0) + 5.0 * crescent(2.0, 2.0, e).area; + for (x, y) in [(&block, &pin), (&pin, &block)] { + let o = coaxial_overlap(x, y).unwrap(); + assert!((o.volume - want).abs() < 1e-4 * want, "{o:?} {want}"); + } + } + + /// Two rivets with their heads flush on both faces of a sheet, each a hair off its hole, + /// read back from STEP: the heads touch the sheet flat, which the boolean cannot always + /// take, so they are pulled back off it first. Each rivet shares its own crescent. + #[test] + fn two_rivets_flush_on_a_sheet_after_a_step_round_trip() { + let rivet = |x: f64| { + let shank = crate::cylinder(Vec3::new(x, 0.0, -1.0), Vec3::Z, 2.0, 3.5).unwrap(); + let under = crate::cylinder(Vec3::new(x, 0.0, -1.0), Vec3::Z, 3.5, 1.0).unwrap(); + let over = crate::cylinder(Vec3::new(x, 0.0, 1.5), Vec3::Z, 3.5, 1.0).unwrap(); + let r = crate::boolean(&shank, &under, BoolOp::Union).unwrap().unwrap(); + crate::boolean(&r, &over, BoolOp::Union).unwrap().unwrap() + }; + let mut sheet = crate::box_solid(Vec3::new(-20.0, -10.0, 0.0), Vec3::new(20.0, 10.0, 1.5)).unwrap(); + for x in [-4.0, 4.0] { + let drill = crate::cylinder(Vec3::new(x, 0.0, -1.0), Vec3::Z, 2.0, 4.0).unwrap(); + sheet = crate::boolean(&sheet, &drill, BoolOp::Cut).unwrap().unwrap(); + } + let back = |b: &Body| crate::step_import(&crate::step_export(&[b], "round trip").unwrap()).unwrap().bodies.remove(0).body; + let sheet = back(&sheet); + for (x, e) in [(-4.0, 0.004), (4.0, 0.006)] { + let r = back(&rivet(x + e)); + let want = 1.5 * crescent(2.0, 2.0, e).area; + for (p, q) in [(&sheet, &r), (&r, &sheet)] { + let o = coaxial_overlap(p, q).unwrap(); + assert!((o.volume - want).abs() < 1e-6 * want, "{o:?} {want}"); + } + } + } } diff --git a/crates/kernel/src/step_in/split.rs b/crates/kernel/src/step_in/split.rs index 6a5d29731..2a3cb22b5 100644 --- a/crates/kernel/src/step_in/split.rs +++ b/crates/kernel/src/step_in/split.rs @@ -34,17 +34,21 @@ fn coord(d: Dir, uv: (f64, f64)) -> f64 { } } -/// The closed, non-periodic direction of a surface with its range. -fn closed_dirs(s: &mt::Surface) -> Vec<(Dir, f64, f64)> { +/// The closed, non-periodic direction of a surface with its range; with `periodic`, a revolved +/// surface's turn around its axis too. +fn closed_dirs(s: &mt::Surface, periodic: bool) -> Vec<(Dir, f64, f64)> { match s { mt::Surface::RevolutedCurve(p) => { let c = p.entity().entity_curve(); let (t0, t1) = c.range_tuple(); + let mut out = Vec::new(); if c.front().distance(c.back()) < 1e-7 * (1.0 + c.front().to_homogeneous().truncate().magnitude()) { - vec![(Dir::U, t0, t1)] - } else { - vec![] + out.push((Dir::U, t0, t1)); } + if periodic { + out.extend(turn_dir(s)); + } + out } mt::Surface::BSplineSurface(_) | mt::Surface::NurbsSurface(_) => { let ((u0, u1), (v0, v1)) = match s { @@ -76,6 +80,24 @@ fn closed_dirs(s: &mt::Surface) -> Vec<(Dir, f64, f64)> { } } +/// The parameter that turns a revolved surface around its axis, over one turn. +fn turn_dir(s: &mt::Surface) -> Option<(Dir, f64, f64)> { + let mt::Surface::RevolutedCurve(p) = s else { return None }; + let (t0, t1) = p.entity().entity_curve().range_tuple(); + let tau = std::f64::consts::TAU; + let ts: Vec = (0..=4).map(|i| t0 + (t1 - t0) * f64::from(i) / 4.0).collect(); + [Dir::V, Dir::U].into_iter().find_map(|d| { + let at = |w: f64, t: f64| match d { + Dir::V => s.subs(t, w), + Dir::U => s.subs(w, t), + }; + let scale = ts.iter().map(|t| at(0.0, *t).to_homogeneous().truncate().magnitude()).fold(1.0, f64::max); + let closes = ts.iter().all(|t| at(0.0, *t).distance(at(tau, *t)) < scale * 1e-9); + let turns = ts.iter().any(|t| at(0.0, *t).distance(at(std::f64::consts::PI, *t)) > scale * 1e-6); + (closes && turns).then_some((d, 0.0, tau)) + }) +} + fn samples(c: &mt::Curve, n: usize) -> Vec<(f64, mt::Point3)> { let (t0, t1) = c.range_tuple(); (0..=n).map(|i| t0 + (t1 - t0) * i as f64 / n as f64).map(|t| (t, c.subs(t))).collect() @@ -121,6 +143,16 @@ fn crossing(s: &mt::Surface, d: Dir, chain: &[mt::Edge], mid: f64, period: f64) /// Iso-parameter edge curve `w = mid` from `q1` to `q2`. fn iso_curve(s: &mt::Surface, d: Dir, mid: f64, q1: mt::Point3, q2: mt::Point3, seam: &[mt::Point3]) -> R { match s { + // Across the turn of a cylinder or cone: a straight line along it. + mt::Surface::RevolutedCurve(_) if turn_dir(s).is_some_and(|t| t.0 == d) => { + let m = q1 + (q2 - q1) * 0.5; + let on = uv_of(s, m).is_some_and(|(u, v)| s.subs(u, v).distance(m) < 1e-7 * (1.0 + q1.distance(q2))); + if on && q1.distance(q2) > 1e-9 { + Ok(mt::Curve::Line(mt::Line(q1, q2))) + } else { + Err("a revolved face that is not straight along its axis".into()) + } + } mt::Surface::RevolutedCurve(p) => { // A circle around the axis, turning opposite to the seam (which runs from the q2 // side to the q1 side). @@ -260,7 +292,7 @@ struct Plan { faces: (mt::Face, mt::Face), } -fn plan(face: &mt::Face) -> R> { +fn plan(face: &mt::Face, periodic: bool) -> R> { let s = face.surface(); let wires = face.absolute_boundaries().clone(); let mut uses: HashMap = HashMap::new(); @@ -274,7 +306,7 @@ fn plan(face: &mt::Face) -> R> { // The closed direction whose boundary carries the seam. let seam_pts: Vec = wires.iter().flat_map(|w| w.edge_iter()).filter(|e| is_seam(e)).flat_map(|e| samples(&e.curve(), 4).into_iter().map(|x| x.1)).collect(); - let Some((d, w0, w1)) = closed_dirs(&s).into_iter().find(|(d, w0, w1)| { + let Some((d, w0, w1)) = closed_dirs(&s, periodic).into_iter().find(|(d, w0, w1)| { let p = w1 - w0; seam_pts.iter().all(|q| uv_of(&s, *q).map(|uv| coord(*d, uv)).is_some_and(|w| (w - w0).abs().min((w - w1).abs()) < p * 1e-4)) }) else { @@ -456,13 +488,48 @@ fn recut(face: &mt::Face, cuts: &[(mt::Edge, (mt::Edge, mt::Edge))]) -> mt::Face f } +/// A copy of `body` whose faces that run once round a cylinder or cone along a seam edge +/// (as STEP files have them) are each cut in two along the line opposite the seam, the way the +/// kernel builds such walls itself; the boolean cannot always intersect the whole ones. `None` +/// when the body has no such face, or one can't be cut. +pub(crate) fn split_seams(body: &crate::Body) -> Option { + let seamed = |f: &mt::Face| { + let mut seen = std::collections::HashSet::new(); + f.absolute_boundaries().iter().flat_map(|w| w.edge_iter()).any(|e| !seen.insert(e.id())) + }; + if !body.solid.face_iter().any(seamed) { + return None; + } + let mut shells: Vec = Vec::new(); + for sh in body.solid.boundaries() { + let mut faces: Vec = sh.face_iter().cloned().collect(); + let n = faces.len(); + for i in 0..n { + let Some(face) = faces.get(i).cloned() else { continue }; + if !seamed(&face) { + continue; + } + let p = crate::guard("seam split", || plan(&face, true).map_err(crate::KernelError::Failed)).ok()??; + faces = faces.iter().map(|f| recut(f, &p.cuts)).collect(); + if let Some(slot) = faces.get_mut(i) { + *slot = p.faces.0; + } + faces.push(p.faces.1); + } + shells.push(faces.into()); + } + let solid = mt::Solid::try_new(shells).ok()?; + let b = crate::Body::new(solid).ok()?; + b.validity().is_empty().then_some(b) +} + /// Split every band face of a shell (see the module docs). Faces that cannot be split stay as /// they are and are reported. pub(crate) fn split_bands(mut faces: Vec, origin: &mut Vec, warnings: &mut Vec) -> Vec { let n = faces.len(); for i in 0..n { let Some(face) = faces.get(i).cloned() else { continue }; - match crate::guard("step band split", || plan(&face).map_err(crate::KernelError::Failed)) { + match crate::guard("step band split", || plan(&face, false).map_err(crate::KernelError::Failed)) { Ok(Some(p)) => { faces = faces.iter().map(|f| recut(f, &p.cuts)).collect(); if let Some(slot) = faces.get_mut(i) { From 44cbd7ae731baf0f5273fb1524e4ab761436ea98 Mon Sep 17 00:00:00 2001 From: shop-3d Date: Mon, 19 Oct 2026 23:23:00 +0200 Subject: [PATCH 122/225] I18n danish (#2671) I18n danish. --- ATTRIBUTION.md | 1 + assets/locales/da.json | 1585 +++++++++++++++++++++ crates/ui-egui/src/colour_vision_tests.rs | 5 +- crates/ui-egui/src/i18n.rs | 3 + docs/localization.md | 4 +- 5 files changed, 1595 insertions(+), 3 deletions(-) create mode 100644 assets/locales/da.json diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 92f415137..fa1207469 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -89,6 +89,7 @@ Editable drawing code, native projects and shipped exports are collected under ` | assets/icons/ui/source/navigation.rs | SolidCraft contributors | Original SolidCraft resource data or drawing code, collected without redesign | MIT OR Apache-2.0 | | assets/icons/ui/source/pointer.rs | SolidCraft contributors | Original SolidCraft resource data or drawing code, collected without redesign | MIT OR Apache-2.0 | | assets/locales/cs.json | potuzai | Czech translation of the English catalog, contributed upstream | MIT OR Apache-2.0 | +| assets/locales/da.json | SolidCraft contributors | Original Danish translation of SolidCraft's English catalog; no commercial CAD text used | MIT OR Apache-2.0 | | assets/locales/de.json | SolidCraft contributors | Original SolidCraft resource data or drawing code, collected without redesign | MIT OR Apache-2.0 | | assets/locales/en.json | SolidCraft contributors | Original SolidCraft resource data or drawing code, collected without redesign | MIT OR Apache-2.0 | | assets/locales/es.json | jawler | Spanish (Spain) translation of the English catalog, contributed upstream | MIT OR Apache-2.0 | diff --git a/assets/locales/da.json b/assets/locales/da.json new file mode 100644 index 000000000..8f19165f3 --- /dev/null +++ b/assets/locales/da.json @@ -0,0 +1,1585 @@ +{ + "0 turns it off": "0 slår det fra", + "1. Open GitHub draft below, then paste the report copied to your clipboard.": "1. Åbn GitHub-kladden nedenfor, og indsæt rapporten fra udklipsholderen.", + "1. Open GitHub draft below. Your title and report will be filled in.": "1. Åbn GitHub-kladden nedenfor. Titel og rapport udfyldes automatisk.", + "2. Attach your screenshot: copy and paste it, or save and upload the PNG.": "2. Vedhæft dit skærmbillede: Kopiér og indsæt det, eller gem og upload PNG-filen.", + "3. Click Submit new issue on GitHub to send your report.": "3. Klik på Submit new issue på GitHub for at sende rapporten.", + "A new configuration, a copy of the active one": "Opret en ny konfiguration som en kopi af den aktive", + "AI": "AI", + "About SolidCraft": "Om SolidCraft", + "Acceleration": "Acceleration", + "Active": "Aktiv", + "Active rule": "Aktiv regel", + "Add": "Tilføj", + "Add Key": "Tilføj animationspunkt", + "Add Mid Radius": "Tilføj mellemradius", + "Add Row": "Tilføj række", + "Add condition": "Tilføj betingelse", + "Against": "Mod", + "Alignment": "Justering", + "All Sketch Points": "Alle skitsepunkter", + "All components": "Alle komponenter", + "All open designs": "Alle åbne designs", + "Allowed expressions, separated by semicolons": "Tilladte udtryk adskilt af semikolon", + "Also deletes": "Sletter også", + "Angle 2": "Vinkel 2", + "Animate": "Animér", + "Appearance name": "Navn på udseende", + "Applied Radius": "Anvendt radius", + "Apply To": "Anvend på", + "Apply to selection": "Anvend på markering", + "Arc length": "Buelængde", + "Area": "Areal", + "Attachment": "Tilknytning", + "BOUNDARY SURFACE": "AFGRÆNSET OVERFLADE", + "BROWSER": "MODELTRÆ", + "Bend Line Position": "Bukkelinjens placering", + "Bend Position": "Bukningens placering", + "Bend Radius": "Bukkeradius", + "Bends": "Bukninger", + "Body": "Emne", + "Boundary": "Afgrænsning", + "Bounding box": "Omsluttende boks", + "CSV or JSON: updates existing parameters, adds new ones": "CSV eller JSON: Opdaterer eksisterende parametre og tilføjer nye", + "Capture All Positions": "Registrér alle positioner", + "Catch Direction": "Indgrebsretning", + "Cells": "Celler", + "Center X": "Centrum X", + "Center Y": "Centrum Y", + "Center of mass": "Massecentrum", + "Centre to centre": "Centrum til centrum", + "Chamfer Type": "Affasningstype", + "Check collisions": "Kontrollér kollisioner", + "Checked": "Kontrolleret", + "Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.": "Vælg et nyt plan. Skitsegeometri og mål bevarer deres todimensionelle koordinater.", + "Circumference": "Omkreds", + "Close draft": "Luk kladde", + "Collisions": "Kollisioner", + "Colour": "Farve", + "Component1": "Komponent1", + "Configuration": "Konfiguration", + "Configuration rules": "Konfigurationsregler", + "Construction": "Konstruktionsgeometri", + "Contact": "Kontakt", + "Contact sets": "Kontaktsæt", + "Continuity": "Kontinuitet", + "Copy Error Message": "Kopiér fejlmeddelelse", + "Copy Warning Message": "Kopiér advarselsmeddelelse", + "Copy all licences": "Kopiér alle licenser", + "Copy diagnostic information": "Kopiér diagnosticeringsoplysninger", + "Copy report": "Kopiér rapport", + "Copy screenshot": "Kopiér skærmbillede", + "Corner Relief": "Hjørneaflastning", + "Corner Relief Shape": "Hjørneaflastningens form", + "Counterbore depth": "Dybde af cylindrisk forsænkning", + "Countersink angle": "Vinkel på konisk forsænkning", + "Create Issue — review draft": "Opret issue — gennemgå kladde", + "Cross curves": "Tværkurver", + "Cube": "Terning", + "Current orthographic view (1:1 mm)": "Aktuel visning uden perspektiv (1:1 mm)", + "Current perspective view": "Aktuel perspektivvisning", + "Curvature (G2)": "Krumningskontinuitet (G2)", + "Customize Toolbar": "Tilpas værktøjslinje", + "Delete all": "Slet alle", + "Delete rule": "Slet regel", + "Delete the row": "Slet rækken", + "Delete the set": "Slet sættet", + "Delete this parameter": "Slet denne parameter", + "Density": "Densitet", + "Designs you open or save appear here.": "Designs, du åbner eller gemmer, vises her.", + "Determined by To Object. Choose Angle to edit the angular extent.": "Bestemmes af Til objekt. Vælg Vinkel for at ændre vinkeludstrækningen.", + "Direction": "Retning", + "Discard": "Kassér", + "Do not export hidden edges": "Eksportér ikke skjulte kanter", + "Don't ask again": "Spørg ikke igen", + "Double-click to rename": "Dobbeltklik for at omdøbe", + "Double-clicking the middle button in the view: Home (the home view, framing what is shown), Fit (frame what is shown, keeping the orientation) or nothing": "Dobbeltklik på den midterste museknap i visningen: Hjem (hjemmevisningen, der indrammer det viste), Tilpas (indrammer det viste og bevarer orienteringen) eller ingen handling", + "Drive Joint": "Bevæg led", + "Duration": "Varighed", + "Edges": "Kanter", + "Edit Profile Sketch": "Redigér profilskitse", + "Enable rule": "Aktivér regel", + "Enabled": "Aktiveret", + "Explode": "Adskil", + "Explode Text": "Opløs tekst", + "Export Animation…": "Eksportér animation…", + "Export Current View as DXF": "Eksportér aktuel visning som DXF", + "Export Current View as DXF…": "Eksportér aktuel visning som DXF…", + "Export DXF…": "Eksportér DXF…", + "Export hidden edges as dashed lines": "Eksportér skjulte kanter som stiplede linjer", + "Extents": "Udstrækning", + "Face": "Flade", + "Face attachment lost": "Forbindelsen til fladen er mistet", + "Faces": "Flader", + "Faces / edges / vertices": "Flader / kanter / hjørnepunkter", + "Favourite": "Favorit", + "Files from many CAD programs have Y up, so they open lying on their back here (Z up).": "Filer fra mange CAD-programmer har Y opad og åbnes derfor liggende på ryggen her (Z opad).", + "Filter": "Filter", + "Find in Browser": "Find i modeltræ", + "Flat": "Flad", + "Flat size": "Bredde mellem flader", + "Follow camera (Look At sketches)": "Følg kamera (Se på skitser)", + "Follow the camera (Look At sketches)": "Følg kameraet (Se på skitser)", + "Font": "Skrifttype", + "Full Length": "Fuld længde", + "Grid": "Gitter", + "Height": "Højde", + "Hidden edges": "Skjulte kanter", + "Holes": "Huller", + "Holes (edges on them)": "Huller (kanterne omkring dem)", + "Home view": "Hjemmevisning", + "In This Design": "I dette design", + "In place (surfaces)": "På stedet (overflader)", + "In plane": "I planet", + "Inside": "Indvendigt", + "Interferes": "Overlapper", + "Issue title": "Titel på issue", + "Joint Origin1": "Lednulpunkt1", + "Keep Tools": "Behold værktøjsemner", + "Later": "Senere", + "Leave it": "Lad det være", + "Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "Ældre fladetilknytning. Ny tilknytning til en certificeret flade giver en præcis tilknytning.", + "Length": "Længde", + "Length units": "Længdeenheder", + "Letter Spacing": "Tegnafstand", + "Library": "Bibliotek", + "Line Spacing": "Linjeafstand", + "Loop": "Løkke", + "Margin": "Margen", + "Mass": "Masse", + "Material": "Materiale", + "Max": "Maks.", + "Mid Radius": "Mellemradius", + "Middle double-click": "Dobbeltklik med midterste museknap", + "Min": "Min.", + "Mitre": "Gering", + "Modeled": "Modelleret", + "More toolbar panels": "Flere værktøjspaneler", + "Motion": "Bevægelse", + "Move Type": "Flytningstype", + "Move earlier": "Flyt tidligere", + "Move later": "Flyt senere", + "Name": "Navn", + "Nearest": "Nærmeste", + "New study": "Ny analyse", + "No crash reports.": "Ingen nedbrudsrapporter.", + "No matching appearances": "Ingen matchende udseender", + "No visible bodies to export.": "Der er ingen synlige emner at eksportere.", + "None": "Ingen", + "Normal to sketch": "Vinkelret på skitse", + "Not available yet": "Endnu ikke tilgængelig", + "Notch": "Udskæring", + "Opacity": "Opacitet", + "Open GitHub draft": "Åbn GitHub-kladde", + "Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "Parametrisk 3D-CAD i Rust med åben kildekode. Licenseret under MIT OR Apache-2.0.", + "Other side": "Anden side", + "Outside": "Udvendigt", + "Overall length": "Samlet længde", + "Parameter values": "Parameterværdier", + "Pass through": "Gå igennem", + "Path": "Bane", + "Per Edge": "Pr. kant", + "Pick the tool bodies": "Vælg værktøjsemnerne", + "Picked": "Valgt", + "Picked point": "Valgt punkt", + "Place at the origin instead": "Placér ved nulpunktet i stedet", + "Playback": "Afspilning", + "Plot": "Diagram", + "Position": "Position", + "Position (0 to 1)": "Position (0 til 1)", + "Position (G0)": "Positionskontinuitet (G0)", + "Position along the edge, 0 at the start end, 1 at the other": "Position langs kanten: 0 ved den ene ende, 1 ved den anden", + "Preferences › Design turns the offer back on": "Indstillinger › Design slår tilbuddet til igen", + "Preview Row": "Forhåndsvis række", + "Preview leaves the current design unchanged.": "Forhåndsvisning ændrer ikke det aktuelle design.", + "Profiles/Curves": "Profiler/kurver", + "Projection": "Projektion", + "Quantity": "Antal", + "RECENT": "SENESTE", + "RULED SURFACE": "REGELFLADE", + "Radius Fit": "Tilpasning af radius", + "Ratio": "Forhold", + "Reattach selected face": "Tilknyt den valgte flade igen", + "Recover": "Gendan", + "Recover unsaved design?": "Gendan design, der ikke er gemt?", + "Rectangular": "Rektangulær", + "Reference face": "Referenceflade", + "Remove Tools": "Fjern værktøjsemner", + "Remove from list": "Fjern fra liste", + "Remove override": "Fjern tilsidesættelse", + "Remove private design details or paths before sharing.": "Fjern private designoplysninger eller filstier, før du deler.", + "Remove screenshot": "Fjern skærmbillede", + "Remove the column": "Fjern kolonnen", + "Remove the track": "Fjern sporet", + "Remove this point": "Fjern dette punkt", + "Report a bug — review a screenshot and open a GitHub draft": "Rapportér en fejl — gennemgå et skærmbillede, og åbn en GitHub-kladde", + "Reset Toolbar": "Nulstil værktøjslinje", + "Restore outer boundary": "Gendan ydre afgrænsning", + "Restore the inherited component or physical material appearance": "Gendan udseendet fra komponenten eller det fysiske materiale", + "Result": "Resultat", + "Retake screenshot": "Tag skærmbillede igen", + "Reverse": "Vend om", + "Reverse Direction": "Vend retning", + "Revert": "Tilbagefør", + "Revert All Positions": "Tilbagefør alle positioner", + "Revert Position": "Tilbagefør position", + "Review the report and screenshot before opening GitHub.": "Gennemgå rapport og skærmbillede, før du åbner GitHub.", + "Rim Edge": "Randkant", + "Roll History Marker Here": "Flyt tilbagerulningsmarkør hertil", + "Round": "Rund", + "Rule": "Regel", + "Save Rule": "Gem regel", + "Save the study as an animated GIF, seen as the viewport shows it": "Gem undersøgelsen som en animeret GIF med samme visning som i modelvinduet", + "Saved preview. Geometry is being checked before editing.": "Gemt forhåndsvisning. Geometrien kontrolleres før redigering.", + "Scale factor": "Skaleringsfaktor", + "Search": "Søg", + "Search commands": "Søg efter kommandoer", + "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Vælg andet: Hold venstre museknap nede uden at flytte markøren på modellen (eller højreklik › Vælg andet…) for at vise alt under markøren. Klik igen samme sted for at vælge næste objekt. Dobbeltklik på den midterste museknap for at gå til Hjem (Indstillinger › Navigation).", + "Select bodies (a face picks its body)": "Vælg emner (en flade vælger sit emne)", + "Select bodies or faces instead": "Vælg emner eller flader i stedet", + "Selection filter": "Markeringsfilter", + "Semantic faces share their appearance across instances.": "Semantiske flader deler udseende på tværs af instanser.", + "Send your report on GitHub": "Send din rapport på GitHub", + "Shape": "Form", + "Show Agent Cursor": "Vis agentmarkør", + "Show in folder": "Vis i mappe", + "Show the pointer an AI agent moves (#35)": "Vis markøren, som en AI-agent bevæger (#35)", + "Signed axes": "Akser med fortegn", + "Size": "Størrelse", + "Sketch constraints": "Skitsebindinger", + "Sketch curves": "Skitsekurver", + "Sketch dimensions": "Skitsemål", + "Sketch geometry and profiles": "Skitsegeometri og profiler", + "Sketch plane has no body-face attachment.": "Skitseplanet er ikke tilknyttet en flade på et emne.", + "Sketch points": "Skitsepunkter", + "Slot width": "Slidsbredde", + "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft lukkede, før disse designs blev gemt. Den seneste automatiske lagring kan åbnes.", + "Speed": "Hastighed", + "Stand it up": "Stil op", + "Stand it up: a quarter turn about X, as one Move feature you can undo.": "Stil op: En kvart omdrejning om X som én flyttefeature, der kan fortrydes.", + "Stand this part up?": "Stil dette emne op?", + "Step": "Trin", + "Steps": "Trin", + "Study": "Undersøgelse", + "Style": "Stil", + "Suppressed": "Undertrykt", + "Swap Ends": "Ombyt ender", + "Tangent (G1)": "Tangentkontinuitet (G1)", + "Tangent Chain": "Tangentkæde", + "Tear": "Rivning", + "The dashed sketch is a saved plane guide. Select a new face to repair the attachment.": "Den stiplede skitse er en gemt planreference. Vælg en ny flade for at reparere tilknytningen.", + "The saved author occurrence is missing. Select a valid author placement before rebinding.": "Den gemte oprindelige komponentforekomst mangler. Vælg en gyldig oprindelig placering før ny tilknytning.", + "Then": "Så", + "These features will be deleted:": "Disse features slettes:", + "These features will fail:": "Disse features vil fejle:", + "Thickness Outside": "Tykkelse udad", + "Thin": "Tynd", + "Thin Extrude": "Tynd ekstrudering", + "This child is shared. Deleting it removes it from every copy of its parent.": "Dette underobjekt er delt. Sletning fjerner det fra alle kopier af dets overordnede objekt.", + "This child is shared. Position changes apply to every copy of its parent.": "Dette underobjekt er delt. Positionsændringer gælder for alle kopier af dets overordnede objekt.", + "This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "Denne flade kan ikke give en varig tilknytning. Vælg en anden flade, eller vælg udtrykkeligt et fast plan.", + "To Offset": "Til forskydning", + "Tolerance": "Tolerance", + "Too close": "For tæt på", + "Turn off section analysis before exporting the view.": "Slå snitanalyse fra, før visningen eksporteres.", + "Type": "Type", + "UNTRIM": "FJERN BESKÆRING", + "Updating the preview": "Opdaterer forhåndsvisningen", + "Use active author placement": "Brug den aktive komponents placering", + "Use fixed plane": "Brug fast plan", + "Use saved fixed plane": "Brug gemt fast plan", + "Use selected face as fixed plane": "Brug valgt flade som fast plan", + "VIEW": "VISNING", + "Value": "Værdi", + "Velocity": "Hastighed", + "Vertices": "Hjørnepunkter", + "View navigator": "Visningsnavigator", + "Visible bodies only. Curves use line segments (0.01 mm tolerance).": "Kun synlige emner. Kurver består af linjestykker (tolerance: 0,01 mm).", + "Volume": "Volumen", + "Wall": "Væg", + "Wall Location": "Vægplacering", + "Wall Thickness": "Vægtykkelse", + "When": "Når", + "Width": "Bredde", + "Will fail": "Vil fejle", + "angle, height": "vinkel, højde", + "appearance.dielectric_ior": "Dielektrisk brydningsindeks", + "appearance.metallic": "Metallisk", + "appearance.pbr_help": "Se denne overflade i Rendering eller i en billedfil. Lyset brydes ikke og passerer ikke gennem overfladen.", + "appearance.pbr_opaque": "Uigennemsigtig PBR", + "appearance.roughness": "Ruhed", + "appearance.surface_response": "Overfladens reaktion på lys", + "browser.body_name": "Emne{number}", + "browser.component_name": "Komponent{number}", + "browser.parameters": "Parametre ({count})", + "browser.precision": "Præcision: {precision}", + "browser.sketch_name": "Skitse{number}", + "browser.units": "Enheder: {units}", + "cam.flat": "Flad kontaktflade", + "cam.follower": "Følger", + "cam.knife": "Spids følger", + "cam.needs_joints": "kræver et led, der drejer, og et, der glider eller svinger", + "cam.roller": "Rulle", + "cam.roller_pick": "Rulle (valgfri)", + "cam.tip_pick": "Spids (valgfri)", + "cmd.appearance_assign": "Udseende", + "cmd.appearance_library": "Udseendebibliotek", + "cmd.appearance_list": "Vis udseender", + "cmd.body_rename": "Omdøb emne", + "cmd.browser_group": "Ny gruppe", + "cmd.browser_move": "Flyt elementer i modeltræ", + "cmd.browser_order": "Sortér elementer i modeltræ", + "cmd.browser_rename_group": "Omdøb gruppe", + "cmd.browser_ungroup": "Ophæv gruppering", + "cmd.browser_visibility": "Vis/skjul", + "cmd.canvas_calibrate": "Kalibrér referencebillede", + "cmd.canvas_decal": "Dekal", + "cmd.canvas_delete": "Slet referencebillede", + "cmd.canvas_edit": "Redigér referencebillede", + "cmd.canvas_insert": "Referencebillede", + "cmd.component_activate": "Aktivér komponent", + "cmd.component_break_link": "Bryd forbindelse", + "cmd.component_capture_position": "Registrér position", + "cmd.component_create": "Ny komponent", + "cmd.component_delete": "Slet komponent", + "cmd.component_from_bodies": "Opret komponenter fra emner", + "cmd.component_insert_design": "Indsæt design", + "cmd.component_links": "Vis forbindelser", + "cmd.component_list": "Vis komponenter", + "cmd.component_move_bodies": "Flyt emner til komponent", + "cmd.component_move_sketches": "Flyt skitser til komponent", + "cmd.component_paste_new": "Indsæt som ny", + "cmd.component_properties": "Komponentens fysiske egenskaber", + "cmd.component_rename": "Omdøb komponent", + "cmd.component_revert_position": "Tilbagefør position", + "cmd.component_unlock": "Lås indhold op", + "cmd.component_update_links": "Opdatér forbindelser", + "cmd.config_activate": "Aktivér konfiguration", + "cmd.config_column": "Konfigurationskolonne", + "cmd.config_configure": "Konfigurér", + "cmd.config_preview": "Forhåndsvis konfiguration", + "cmd.config_row": "Konfigurationsrække", + "cmd.config_rule": "Konfigurationsregel", + "cmd.config_rules": "Konfigurationsregler", + "cmd.config_table": "Vis konfigurationstabel", + "cmd.construct_axis_edge": "Akse gennem kant", + "cmd.construct_axis_normal_to_face": "Akse vinkelret på flade", + "cmd.construct_axis_through_cylinder": "Akse gennem cylinder/kegle/torus", + "cmd.construct_axis_two_planes": "Akse gennem to planer", + "cmd.construct_axis_two_points": "Akse gennem to punkter", + "cmd.construct_plane_along_path": "Plan langs bane", + "cmd.construct_plane_midplane": "Midterplan", + "cmd.construct_plane_perpendicular": "Vinkelret plan", + "cmd.construct_plane_tangent": "Tangentplan", + "cmd.construct_plane_three_points": "Plan gennem tre punkter", + "cmd.construct_plane_two_edges": "Plan gennem to kanter", + "cmd.construct_point_along_path": "Punkt langs bane", + "cmd.construct_point_center": "Punkt i centrum af cirkel/kugle/torus", + "cmd.construct_point_edge_plane": "Punkt ved kant og plan", + "cmd.construct_point_three_planes": "Punkt gennem tre planer", + "cmd.construct_point_two_edges": "Punkt gennem to kanter", + "cmd.construct_point_vertex": "Punkt ved hjørnepunkt", + "cmd.contact_check": "Kontrollér kontakt", + "cmd.contact_create": "Nyt kontaktsæt", + "cmd.contact_disable_all": "Deaktivér kontakt", + "cmd.contact_edit": "Redigér kontaktsæt", + "cmd.contact_enable_all": "Aktivér al kontakt", + "cmd.contact_enable_sets": "Aktivér kontaktsæt", + "cmd.contact_list": "Vis kontaktsæt", + "cmd.diagnostics_crash_report": "Nedbrudsrapport", + "cmd.diagnostics_crash_reports": "Nedbrudsrapporter", + "cmd.diagnostics_crash_reports_clear": "Slet nedbrudsrapporter", + "cmd.diagnostics_crash_test": "Nedbrudstest", + "cmd.doc_recover": "Gendan design", + "cmd.doc_recovery_discard": "Kassér gendannet design", + "cmd.doc_recovery_list": "Designs, der kan gendannes", + "cmd.document_inspect": "Undersøg design", + "cmd.document_metadata": "Designegenskaber", + "cmd.document_metadata_remove": "Fjern designegenskab", + "cmd.document_metadata_set": "Redigér designegenskaber", + "cmd.document_units": "Skift designets enheder", + "cmd.edit_checkpoint": "Kontrolpunkt", + "cmd.edit_restore_checkpoint": "Gendan kontrolpunkt", + "cmd.engine_commands": "Vis kommandoer", + "cmd.explode_create": "Eksploderet visning", + "cmd.explode_delete": "Slet eksploderet visning", + "cmd.explode_list": "Vis eksploderede visninger", + "cmd.explode_show": "Vis eksploderet visning", + "cmd.expr_evaluate": "Beregn udtryk", + "cmd.face_delete": "Slet flade", + "cmd.file_export": "Eksportér", + "cmd.file_insert_mesh": "Indsæt mesh", + "cmd.file_insert_step": "Indsæt STEP", + "cmd.file_save_mesh": "Gem som mesh", + "cmd.file_slicers": "Installerede slicere", + "cmd.inspect_accessibility": "Tilgængelighedsanalyse", + "cmd.inspect_center_of_mass": "Massecentrum", + "cmd.inspect_clearance": "Frigangskontrol", + "cmd.inspect_compare": "Sammenlign emner", + "cmd.inspect_continuity": "Kontinuitetsanalyse", + "cmd.inspect_curvature_comb": "Krumningskamanalyse", + "cmd.inspect_curvature_map": "Krumningskortanalyse", + "cmd.inspect_draft": "Slipvinkelanalyse", + "cmd.inspect_environment_map": "Analyse med omgivelseskort", + "cmd.inspect_interference": "Overlap", + "cmd.inspect_isocurve": "Isokurveanalyse", + "cmd.inspect_minimum_radius": "Analyse af mindste radius", + "cmd.inspect_silhouette": "Silhuet", + "cmd.inspect_zebra": "Zebraanalyse", + "cmd.joint_as_built": "Led i eksisterende position", + "cmd.joint_cam": "Knast", + "cmd.joint_create": "Led", + "cmd.joint_delete": "Slet led", + "cmd.joint_drive": "Bevæg led", + "cmd.joint_edit": "Redigér led", + "cmd.joint_gear": "Tandhjul", + "cmd.joint_limits": "Bevægelsesgrænser for led", + "cmd.joint_list": "Vis led", + "cmd.joint_motion_link": "Bevægelseskobling", + "cmd.joint_origin": "Lednulpunkt", + "cmd.joint_rack_pinion": "Tandstang og tandhjul", + "cmd.joint_reach": "Nå punkt", + "cmd.joint_rigid_group": "Stiv gruppe", + "cmd.joint_screw": "Skrue", + "cmd.joint_solve": "Beregn led", + "cmd.library_apply": "Brug element fra lokalt bibliotek", + "cmd.library_export": "Eksportér designbibliotek", + "cmd.library_inspect": "Undersøg lokalt bibliotek", + "cmd.material_assign": "Fysisk materiale", + "cmd.material_create": "Nyt fysisk materiale", + "cmd.material_delete": "Slet fysisk materiale", + "cmd.material_edit": "Redigér fysisk materiale", + "cmd.material_list": "Vis materialer", + "cmd.material_properties_directional": "Retningsafhængigt elasticitetsmodul", + "cmd.material_properties_validate": "Validér fysiske materialedata", + "cmd.mesh_convert": "Konvertér mesh", + "cmd.model_edges": "Vis kanter", + "cmd.model_faces": "Vis flader", + "cmd.model_threads": "Vis gevind", + "cmd.motion_delete": "Slet bevægelsesanalyse", + "cmd.motion_export": "Eksportér bevægelsesanalyse", + "cmd.motion_export_animation": "Eksportér bevægelsesanimation", + "cmd.motion_interference": "Overlap under bevægelse", + "cmd.motion_list": "Vis bevægelsesanalyser", + "cmd.motion_play": "Afspil bevægelsesanalyse", + "cmd.motion_plot": "Vis diagram for bevægelsesanalyse", + "cmd.motion_study": "Bevægelsesanalyse", + "cmd.motion_trace": "Bevægelsesspor", + "cmd.motion_trace_keep": "Behold bevægelsesspor", + "cmd.occurrence_copy": "Indsæt (komponentforekomst)", + "cmd.occurrence_ground": "Fastgør", + "cmd.occurrence_move": "Flyt komponentforekomst", + "cmd.occurrence_properties": "Komponentforekomstens fysiske egenskaber", + "cmd.parameters_add": "Tilføj brugerparameter", + "cmd.parameters_change": "Redigér parametre", + "cmd.parameters_comment": "Kommentér parameter", + "cmd.parameters_complete": "Fuldfør udtryk", + "cmd.parameters_delete": "Slet parameter", + "cmd.parameters_export": "Eksportér parametre", + "cmd.parameters_favorite": "Markér parameter som favorit", + "cmd.parameters_graph": "Parametergraf", + "cmd.parameters_import": "Importér parametre", + "cmd.parameters_list": "Vis parametre", + "cmd.parameters_move": "Flyt parameter", + "cmd.parameters_rename": "Omdøb parameter", + "cmd.parameters_users": "Parameterens anvendelser", + "cmd.parts_fastener": "Indsæt befæstelseselement", + "cmd.parts_insert": "Indsæt standarddel", + "cmd.parts_library": "Standarddele", + "cmd.parts_resize": "Skift standarddelens størrelse", + "cmd.plastic_assign_rule": "Tildel plastregel", + "cmd.plastic_boss": "Skruebøsning", + "cmd.plastic_lip": "Læbe", + "cmd.plastic_manage_rules": "Administrér plastregler", + "cmd.plastic_rest": "Understøtning", + "cmd.plastic_rules": "Vis plastregler", + "cmd.plastic_snap_fit": "Snapforbindelse", + "cmd.render_backends": "Renderingsmotorer", + "cmd.render_cancel": "Annullér rendering", + "cmd.render_export": "Eksportér renderet billede", + "cmd.render_preflight": "Kontrollér, om billedet kan renderes", + "cmd.render_scene": "Vis oplysninger om scenen", + "cmd.render_settings_apply": "Brug kamera", + "cmd.render_settings_get": "Renderingsindstillinger", + "cmd.render_settings_set": "Gem renderingsindstillinger", + "cmd.render_start": "Render billede", + "cmd.render_status": "Status for rendering", + "cmd.select_clear": "Ryd markering", + "cmd.sheet_convert": "Konvertér til plade", + "cmd.sheet_export_bend_table": "Eksportér bukketabel", + "cmd.sheet_export_dxf": "Eksportér udfoldning som DXF", + "cmd.sheet_flange": "Flange", + "cmd.sheet_flat_pattern": "Opret udfoldning", + "cmd.sheet_fold": "Buk", + "cmd.sheet_hem": "Ombukning", + "cmd.sheet_manage_rules": "Pladeregler", + "cmd.sheet_perforate": "Perforér", + "cmd.sheet_refold": "Buk tilbage", + "cmd.sheet_rules": "Vis pladeregler", + "cmd.sheet_unfold": "Fold ud", + "cmd.sketch_arc_center_point": "Bue med centrum", + "cmd.sketch_arc_tangent": "Tangentbue", + "cmd.sketch_arc_three_point": "Trepunktsbue", + "cmd.sketch_auto_constrain": "Automatisk binding", + "cmd.sketch_auto_constrain_from_datum": "Automatisk binding ud fra reference", + "cmd.sketch_auto_project": "Projektér referencekanter automatisk", + "cmd.sketch_blend_curve": "Overgangskurve", + "cmd.sketch_chain": "Kæde", + "cmd.sketch_chamfer_distance_angle": "Affasning med afstand og vinkel", + "cmd.sketch_chamfer_equal_distance": "Affasning med ens afstande", + "cmd.sketch_chamfer_two_distance": "Affasning med to afstande", + "cmd.sketch_circle_center": "Cirkel med centrum og diameter", + "cmd.sketch_circle_three_point": "Trepunktscirkel", + "cmd.sketch_circle_three_tangent": "Cirkel med tre tangenter", + "cmd.sketch_circle_two_point": "Topunktscirkel", + "cmd.sketch_circle_two_tangent": "Cirkel med to tangenter", + "cmd.sketch_constrainer": "Skitsebindingsværktøj", + "cmd.sketch_constraint_fix": "Lås fast/frigør", + "cmd.sketch_constraint_midpoint": "Midtpunkt", + "cmd.sketch_construction": "Normal/konstruktionsgeometri", + "cmd.sketch_copy": "Kopiér skitseelementer", + "cmd.sketch_cut": "Klip skitseelementer", + "cmd.sketch_delete": "Slet skitseelementer", + "cmd.sketch_dimension_text": "Flyt måltekst", + "cmd.sketch_drag": "Træk skitsegeometri", + "cmd.sketch_drag_end": "Afslut flytning af skitsen", + "cmd.sketch_draw_dimensioned": "Tegn målsat skitsegeometri", + "cmd.sketch_edit": "Redigér skitse", + "cmd.sketch_edit_text": "Redigér tekst", + "cmd.sketch_export_dxf": "Gem som DXF", + "cmd.sketch_finish_auto_constrain": "Afslut med automatisk binding", + "cmd.sketch_fit_curves_to_section": "Tilpas kurver til snit i mesh", + "cmd.sketch_glyphs": "Bindingssymboler", + "cmd.sketch_include_3d": "Medtag 3D-geometri", + "cmd.sketch_infinite": "Uendelig linje", + "cmd.sketch_insert_dxf": "Indsæt DXF", + "cmd.sketch_insert_svg": "Indsæt SVG", + "cmd.sketch_inspect": "Undersøg skitse", + "cmd.sketch_intersection_curve": "Skæringskurve", + "cmd.sketch_isoparametric_curve": "Isoparametrisk kurve", + "cmd.sketch_line3d": "3D-linje", + "cmd.sketch_line_midpoint": "Linje fra midtpunkt", + "cmd.sketch_loose_ends": "Frie ender", + "cmd.sketch_loose_ends_tie": "Sammenbind frie ender", + "cmd.sketch_move": "Flyt/kopiér skitseelementer", + "cmd.sketch_move3d": "Flyt 3D-punkt", + "cmd.sketch_move_point": "Træk skitsepunkt", + "cmd.sketch_offset_break": "Bryd forskydningstilknytning", + "cmd.sketch_options": "Indstillinger for skitsepalette", + "cmd.sketch_paste": "Indsæt skitseelementer", + "cmd.sketch_point3d": "3D-punkt", + "cmd.sketch_polygon_circumscribed": "Omskrevet polygon", + "cmd.sketch_polygon_edge": "Polygon fra kant", + "cmd.sketch_polygon_inscribed": "Indskrevet polygon", + "cmd.sketch_project_to_surface": "Projektér på overflade", + "cmd.sketch_rectangle_center": "Rektangel fra centrum", + "cmd.sketch_rectangle_rounded": "Afrundet rektangel", + "cmd.sketch_rectangle_three_point": "Trepunktsrektangel", + "cmd.sketch_rectangle_two_point": "Topunktsrektangel", + "cmd.sketch_redefine": "Omdefinér skitseplan", + "cmd.sketch_slot_arc_center": "Bueslids med centrum", + "cmd.sketch_slot_arc_three_point": "Trepunktsbueslids", + "cmd.sketch_slot_center_point": "Slids med centrum", + "cmd.sketch_slot_center_to_center": "Slids fra centrum til centrum", + "cmd.sketch_slot_overall": "Slids med samlet længde", + "cmd.sketch_snap": "Foreslå snap", + "cmd.sketch_solve": "Beregn skitse", + "cmd.sketch_spline3d": "3D-spline", + "cmd.sketch_spline_control_point": "Spline med kontrolpunkter", + "cmd.sketch_spline_control_point_5": "Spline med kontrolpunkter (grad 5)", + "cmd.sketch_spline_fit_point": "Spline gennem punkter", + "cmd.sketch_spun_profile": "Omdrejningsprofil", + "cmd.sketch_toggle_driven": "Skift mellem styrende og afledt mål", + "cmd.solid_align": "Justér", + "cmd.solid_boundary_fill": "Afgrænset udfyldning", + "cmd.solid_bounding_solid": "Omsluttende emne", + "cmd.solid_emboss": "Prægning", + "cmd.solid_move": "Flyt/kopiér", + "cmd.solid_offset_face": "Forskyd flade", + "cmd.solid_press_pull": "Tryk/træk", + "cmd.solid_remove": "Fjern", + "cmd.solid_replace_face": "Erstat flade", + "cmd.solid_rib": "Ribbe", + "cmd.solid_split_face": "Opdel flade", + "cmd.solid_web": "Ribbegitter", + "cmd.surface_blend": "Overgangsflade", + "cmd.surface_boundary": "Afgrænset overflade", + "cmd.surface_extrude": "Overfladeekstrudering", + "cmd.surface_fair": "Udjævn overflade", + "cmd.surface_fillet": "Overfladeafrunding", + "cmd.surface_loft": "Overfladeloft", + "cmd.surface_match": "Tilpas overflade", + "cmd.surface_offset": "Forskyd overflade", + "cmd.surface_patch": "Udfyld med flade", + "cmd.surface_reverse_normal": "Vend normal", + "cmd.surface_revolve": "Overfladeomdrejning", + "cmd.surface_ruled": "Regelflade", + "cmd.surface_stitch": "Sy sammen", + "cmd.surface_sweep": "Overfladesweep", + "cmd.surface_thicken": "Giv tykkelse", + "cmd.surface_unstitch": "Adskil flader", + "cmd.surface_untrim": "Fjern beskæring", + "cmd.timeline_add": "Tilføj registreret feature", + "cmd.timeline_compute_all": "Beregn alle", + "cmd.timeline_copy": "Kopiér features", + "cmd.timeline_dependents": "Afhængige features", + "cmd.timeline_export_script": "Eksportér kommandoscript", + "cmd.timeline_inspect": "Undersøg feature", + "cmd.timeline_paste": "Indsæt features", + "cmd.timeline_redefine": "Redigér feature", + "cmd.timeline_rename": "Omdøb", + "cmd.timeline_reorder": "Flyt feature i rækkefølgen", + "cmd.timeline_roll_to": "Flyt tilbagerulningsmarkør", + "cmd.timeline_rollback": "Flyt tilbagerulningsmarkør", + "cmd.timeline_suppress": "Undertryk feature", + "cmd.view_ambient_occlusion": "Ambient occlusion", + "cmd.view_apply": "Gendan navngiven visning", + "cmd.view_delete": "Slet navngiven visning", + "cmd.view_graphics_preset": "Grafikprofil", + "cmd.view_list": "Vis navngivne visninger", + "cmd.view_navigate": "Navigér i visning", + "cmd.view_rename": "Omdøb navngiven visning", + "cmd.view_save": "Ny navngiven visning", + "command name": "kommandonavn", + "coupling.gear_1": "Tandhjul 1", + "coupling.gear_1_pick": "Tandhjul 1 (valgfrit)", + "coupling.gear_2": "Tandhjul 2", + "coupling.gear_2_pick": "Tandhjul 2 (valgfrit)", + "coupling.internal": "Indvendig fortanding", + "coupling.needs_turn_and_slide": "kræver et led, der drejer, og et, der glider", + "coupling.needs_turns": "kræver to led, der drejer", + "coupling.not_round": "ikke en rund flade", + "coupling.nut": "Møtrik", + "coupling.picked": "valgt", + "coupling.pinion": "Lille tandhjul", + "coupling.pinion_pick": "Lille tandhjul (valgfrit)", + "coupling.pitch": "Deling", + "coupling.rack": "Tandstang", + "coupling.radius_1": "Radius 1", + "coupling.radius_2": "Radius 2", + "dialog.bodies_count": "Antal emner: {count}", + "dialog.clearance_invalid": "afstanden skal være 0 eller større", + "dialog.compute": "Beregn", + "dialog.compute_again": "Beregn igen", + "dialog.computing": "Beregner… {seconds} s", + "dialog.could_not_be_checked": "kunne ikke kontrolleres", + "dialog.custom_axis": "↖ Brugerdefineret akse", + "dialog.edit_title": "REDIGÉR {title}", + "dialog.select": "↖ Vælg", + "dialog.selected_count": "↖ Valgte: {count}", + "dialog.selection_guidance": "Vælg et input for at ændre det. Klik på valgte objekter for at fjerne dem; Ctrl/Cmd-klik skifter også deres valgstatus. Gennemgå forhåndsvisningen, og tryk derefter på OK.", + "dialog.selection_step": "{step} af {total}: Vælg {input}", + "dialog.step": "Trin", + "document.save_changes": "Gem ændringer i {name}?", + "document.unsaved_changes": "{name} har ændringer, der ikke er gemt. De går tabt, hvis du ikke gemmer.", + "drive.stopped_by_contact": "Stoppet ved {value}: {a} ville gå gennem {b}", + "drive.stopped_by_loop": "Stoppet ved {value}: Løkken gennem {joint} kan ikke lukkes yderligere", + "drive.unconnected": "Flytter intet: {part} er ikke forbundet til noget fastgjort", + "dxf.cancel_wait": "Venter på, at eksporten stopper…", + "dxf.cancelled": "DXF-eksport annulleret", + "dxf.cancelling": "Annullerer DXF-eksport", + "dxf.exporting": "Eksporterer DXF", + "dxf.invalid_tolerance": "Kurvetolerancen skal være mellem 0,0001 og 1 mm.", + "dxf.progress.index": "Klargør overflader (2/5)", + "dxf.progress.meshes": "Klargør mesh (1/5)", + "dxf.progress.occlusion": "Beregner skjulte linjer (4/5)", + "dxf.progress.projection": "Projicerer geometri (3/5)", + "dxf.progress.write": "Skriver DXF (5/5)", + "dxf.tolerance": "Kurvetolerance", + "dxf.tolerance_help": "Kun synlige emner. Kurver består af rette linjestykker. En mindre tolerance giver finere kurver og kræver mere tid og hukommelse.", + "expression, e.g. 25 mm": "udtryk, f.eks. 25 mm", + "fits the face, e.g. M8": "passer til fladen, f.eks. M8", + "from the rule": "fra reglen", + "home.documentation": "Dokumentation", + "home.in_this_browser": "i denne webbrowser", + "home.missing": "mangler", + "home.open": "Åbn…", + "home.opened_days_ago": "Åbnet for {count} dage siden", + "home.opened_hours_ago": "Åbnet for {count} t siden", + "home.opened_just_now": "Netop åbnet", + "home.opened_minutes_ago": "Åbnet for {count} min siden", + "home.opening": "åbner…", + "home.recent": "Seneste", + "home.report_issue": "Rapportér et problem", + "home.samples": "Eksempler", + "home.whats_new": "Nyheder", + "install.button_tip": "Installér SolidCraft som en app: Den åbner i sit eget vindue og virker offline", + "install.dock_1": "Vælg Arkiv › Føj til Dock.", + "install.dock_2": "Klik på Tilføj.", + "install.dock_after": "SolidCraft åbner derefter i sit eget vindue fra Dock og virker offline.", + "install.done": "Færdig", + "install.home_screen_1": "Tryk på Del (i menuen …, hvis knappen ikke er på værktøjslinjen).", + "install.home_screen_2": "Vælg Føj til hjemmeskærm.", + "install.home_screen_3": "Tryk på Tilføj.", + "install.home_screen_after": "SolidCraft åbner derefter fra sit ikon på hjemmeskærmen uden Safaris værktøjslinjer og virker offline.", + "install.menu": "Installér app…", + "install.steps_intro": "Safari installerer webapps via sine egne menuer:", + "install.title": "Installér SolidCraft", + "joint.from_bodies_hint": "Hvert valgt emne flyttes til sin egen nye komponent og bliver på sin plads.", + "joint.one_body": "Begge valg er på {body}. Vælg det andet på et andet emne.", + "joint.one_component": "Disse emner tilhører samme komponent: {bodies}. Et led bevæger én komponent i forhold til en anden, så hvert emne skal have sin egen komponent.", + "motion.checked_to": "Kun kontrolleret til trin {step}: Kontrollen nåede sin beregningsgrænse", + "motion.collision": "{a} · {b}: trin {steps}", + "motion.duration_hint": "sekunder (tomt: pr. trin)", + "motion.no_collisions": "Ingen kollisioner under analysen", + "nav.touchpad.help": "Hold Shift nede, og bevæg markøren for at panorere; hold Alt/Option nede, og bevæg den for at rotere visningen. Ingen museknap behøver at være trykket ned. Lodret rulning zoomer.", + "nav.touchpad.label": "Pegefelt", + "nav.touchpad.orbit": "Rotér visning (hold Alt/Option nede og bevæg markøren; ingen museknap)", + "nav.touchpad.pan": "Panorér (hold Shift nede og bevæg markøren; ingen museknap)", + "nav.touchpad.scroll": "Pegefelt bruger lodret rulning til zoom. Din indstilling for panorering med to fingre bevares for andre forudindstillinger.", + "nav.touchpad.zoom": "Zoom (lodret rulning eller knibebevægelse)", + "needs two joints": "kræver to led", + "new configuration": "ny konfiguration", + "new name": "nyt navn", + "new parameter": "ny parameter", + "no hole": "intet hul", + "no interference": "intet overlap", + "no joint that moves yet": "endnu intet bevægeligt led", + "no picture": "intet billede", + "none": "ingen", + "pattern.alignment_2": "Justering 2", + "pattern.alignment_hint": "Antal omfatter originalen. Centrér fordeler kopierne ligeligt; Vend vælger siden med den ekstra kopi ved et lige samlet antal.", + "pattern.direction_1": "Retning 1", + "pattern.direction_2": "Retning 2", + "pattern.flip_direction": "Vend retning", + "pick a hole to seat it, or OK places it at the origin": "vælg et hul til placeringen, eller tryk OK for at placere ved nulpunktet", + "pick one or two vertices, edges or faces": "vælg et eller to hjørnepunkter, kanter eller flader", + "render.background": "Scenebaggrund", + "render.fit": "Tilpas til produkt", + "render.image_cancel": "Annullér rendering", + "render.image_cancelled": "Rendering annulleret", + "render.image_cancelling": "Annullerer", + "render.image_check": "Kontrollér, om billedet kan renderes", + "render.image_completed": "Billedet er klar til eksport", + "render.image_encoding": "Gemmer som PNG", + "render.image_export": "Eksportér PNG", + "render.image_failed": "Rendering mislykkedes", + "render.image_height": "Højde", + "render.image_help": "CPU-forhåndsvisning · PNG · forenklet gengivelse af gennemsigtighed", + "render.image_overwrite": "Erstat eksisterende fil", + "render.image_preparing": "Klargør billede", + "render.image_queued": "Venter på rendering", + "render.image_reduce": "Prøv et mindre billede eller en enklere scene.", + "render.image_running": "Renderer billede", + "render.image_stale": "Dette billede bruger scenen, som den var før efterfølgende ændringer.", + "render.image_start": "Start rendering", + "render.image_supported": "Renderingsanmodningen understøttes; kø og hukommelsespulje kontrolleres igen ved start.", + "render.image_title": "Render billede", + "render.image_too_large": "Over billedgrænsen: 4096 pixels pr. side og 4.194.304 pixels i alt.", + "render.image_transparent": "Gennemsigtig baggrund", + "render.image_unknown": "Renderingsstatus utilgængelig", + "render.image_use_largest": "Brug største størrelse med dette sideforhold:", + "render.image_width": "Bredde", + "render.navigation_help": "Kameraet bevæges som i Design (Indstillinger › Navigation). Gem opsætning gemmer det aktuelle kamera.", + "render.opaque_image_summary": "PNG-forhåndsvisning · uigennemsigtig PBR · blandet gennemsigtighed", + "render.opaque_preview_help": "Uigennemsigtig PBR og enkle farver; blandet gennemsigtighed. Lysbrydning, HDRI og endelig rendering er endnu ikke tilgængelige.", + "render.perspective": "Perspektivkamera", + "render.preview": "Integreret forhåndsvisning", + "render.preview_help": "Rasterbaseret skygning og blandet gennemsigtighed. Lysbrydning, HDRI og endelig rendering er endnu ikke tilgængelige.", + "render.reload_settings": "Genindlæs gemte indstillinger", + "render.restore_camera": "Gendan gemt kamera", + "render.return_design": "Tilbage til Design", + "render.save_setup": "Gem opsætning", + "render.setup_name": "Opsætningsnavn", + "render.unavailable_preview": "Denne opsætning bruger en type forhåndsvisning, der ikke er tilgængelig.", + "render.unsaved": "Ændringer i forhåndsvisning er ikke gemt", + "render.use_preview": "Brug integreret forhåndsvisning", + "sample.bracket.about": "Grundflange med kantflanger og en ombukning efter en regel med 2 mm tykkelse", + "sample.bracket.name": "Pladebeslag", + "sample.enclosure.about": "Udhullet kasse med læbe, skruebøsninger, understøtning og snapforbindelse", + "sample.enclosure.name": "Plastkabinet", + "sample.flange.about": "Nav og flange med et cirkulært mønster styret af en parameter", + "sample.flange.name": "Boltet flange", + "sample.hinge.about": "To komponenter og et drejeled, bevæget til 60°", + "sample.hinge.name": "Hængselsamling", + "sample.plate.about": "Parametrisk plade med afrundinger, huller og en gennemboret bøsning", + "sample.plate.name": "Eksempelplade", + "sample.vents.about": "Slidser i et rektangulært mønster: Rækker, kolonner og deling er parametre", + "sample.vents.name": "Ventilationsplade", + "settings.display_quality_note": "Finere niveauer viser krumme flader og kanter mere jævnt og tager længere tid at opbygge mesh til. Kun modelvisningen ændres, aldrig designet eller eksporten.", + "settings.frame_rate_note": "Viser billeder pr. sekund nederst til højre i modelvisningen. Når dette er slået til, gentegnes visningen løbende.", + "settings.measure_axis_distances": "Vis X/Y/Z-afstande", + "settings.measure_axis_distances_help": "Vis afstanden langs X-, Y- og Z-aksen sammen med den samlede afstand i Mål.", + "settings.msaa_applies_on_restart": "Kantudjævning træder i kraft, næste gang SolidCraft starter", + "settings.msaa_reset": "{setting}: {requested}× understøttes ikke af denne grafikenhed; værdien er nu {reset}× (understøttet: {supported}).", + "settings.msaa_unsupported": "Understøttes ikke af denne grafikenhed", + "settings.reset_intro": "Disse indstillinger virker ikke på denne computer og ville forhindre SolidCraft i at starte. De er derfor ændret:", + "settings.reset_title": "Indstillinger blev ændret", + "settings.supersampling_note": "Tegner visningen med højere opløsning og nedskalerer den: Jævnere kanter, linjer og gitter på skærme under 4K. Det kræver GPU-tid: ca. 2,25× så mange pixels ved 1,5× og 4× ved 2×.", + "sketch.degrees_of_freedom": "Frihedsgrader: {count}", + "sketch.draw_curves": "Tegn som {linetype}", + "sketch.make_selection": "Konvertér markeringen til {linetype}", + "sketch.open_ends": "Åbne ender: {count}", + "sketch.untied_ends": "Ender uden binding: {count}", + "sketch_text.align_center": "Centreret", + "sketch_text.align_left": "Venstre", + "sketch_text.align_right": "Højre", + "sketch_text.bold": "Fed", + "sketch_text.builtin_font": "{family} (indbygget)", + "sketch_text.font_search": "Søg efter skrifttyper", + "sketch_text.italic": "Kursiv", + "sketch_text.loading_fonts": "Søger efter installerede skrifttyper…", + "sketch_text.on_path": "Teksten følger sin bane: Kurven bestemmer placeringen", + "sketch_text.path_clear": "Frigør teksten fra dens kurve", + "sketch_text.path_hint": "En kurve i skitsen, som teksten følger: Klik her og derefter på kurven", + "sketch_text.use_font_file": "Brug skrifttypefilen {path}", + "solid": "massivt emne", + "the parts library is not available": "biblioteket med standarddele er ikke tilgængeligt", + "thread.automatic_size": "Automatisk størrelse", + "thread.designation": "Betegnelse", + "thread.iso_metric": "ISO-metrisk", + "thread.select_size": "Vælg størrelse", + "timeline.group": "Ny featuremappe", + "timeline.move_many": "Flyt elementer i tidslinjen", + "timeline.move_to_group": "Flyt features til mappe", + "timeline.rename_group": "Omdøb featuremappe", + "timeline.reorder_many": "Skift rækkefølge på features", + "timeline.ungroup": "Fjern featuremapper", + "to the face": "til fladen", + "to the next face": "til næste flade", + "toolbar.image": "BILLEDE", + "toolbar.render": "RENDERING", + "toolbar.render_scene": "SCENE", + "trace.points": "Punkter langs banen: {count}", + "trace.stopped_by_contact": "Slutter ved prøve {sample}: {a} ville gå gennem {b}", + "trace.stopped_by_loop": "Slutter ved prøve {sample}: Løkken gennem {joint} kan ikke lukkes yderligere", + "ui.1_degree_of_freedom": "1 frihedsgrad", + "ui.3d_mouse_speed": "3D-musens hastighed", + "ui.3d_mouse_windows": "3D-mus", + "ui.3d_sketch": "3D-skitse", + "ui.about": "Om", + "ui.activate": "Aktivér", + "ui.active_component": "Aktiv komponent", + "ui.agent_chat": "Agentchat", + "ui.agent_chat_add": "Vedhæft filer", + "ui.agent_chat_add_file": "Vælg en fil…", + "ui.agent_chat_allow": "Tillad", + "ui.agent_chat_allowed": "Tilladt", + "ui.agent_chat_answered": "Svar: {option}", + "ui.agent_chat_approval": "Tillad agenten at gøre dette?", + "ui.agent_chat_attach_view": "Vedhæft visning", + "ui.agent_chat_attach_view_tip": "Send et billede af den aktuelle visning sammen med beskeden", + "ui.agent_chat_attachable": "Billeder, PDF-filer, tekst og CAD-filer", + "ui.agent_chat_auth_agent": "Log ind med {name}", + "ui.agent_chat_auth_env": "Indstil {vars} i dit miljø, og genstart SolidCraft.", + "ui.agent_chat_auth_needed": "Agenten beder dig logge ind. Du logger ind hos agenten selv; SolidCraft ser aldrig din adgangskode eller dine nøgler.", + "ui.agent_chat_auth_none": "Agenten tilbyder ingen loginmetode her: Log ind som beskrevet i dens egen dokumentation.", + "ui.agent_chat_auth_retry": "Jeg er logget ind: Forbind igen", + "ui.agent_chat_auth_terminal": "Kør dette i en terminal, og tryk derefter på Forbind igen:", + "ui.agent_chat_auth_title": "Log ind hos agenten", + "ui.agent_chat_cancel": "Annullér", + "ui.agent_chat_changes": "Ændringer: {n}, ét fortrydelsestrin", + "ui.agent_chat_changes_of": "{n}/{limit} ændringer", + "ui.agent_chat_close": "Luk", + "ui.agent_chat_command": "Agentkommando", + "ui.agent_chat_connect": "Forbind", + "ui.agent_chat_copy": "Kopiér", + "ui.agent_chat_custom_hint": "Ethvert program, der bruger Agent Client Protocol via stdin og stdout. Det køres uden en kommandoskal.", + "ui.agent_chat_denied": "Afvist", + "ui.agent_chat_deny": "Afvis", + "ui.agent_chat_desktop_only": "Agentchatten kræver desktopappen.", + "ui.agent_chat_detecting": "Søger efter agenter…", + "ui.agent_chat_dock": "Fastgør i sidepanelet", + "ui.agent_chat_dock_left": "Fastgør til venstre", + "ui.agent_chat_dock_right": "Fastgør til højre", + "ui.agent_chat_drop_hint": "Slip for at vedhæfte til din næste besked", + "ui.agent_chat_edit": "Redigér", + "ui.agent_chat_exited": "Agenten stoppede.", + "ui.agent_chat_failed_start": "Agenten kunne ikke starte: {error}", + "ui.agent_chat_file_cad_not_read": "{name}: En CAD-fil importeres i designet i stedet for at blive læst", + "ui.agent_chat_file_empty_picture": "{name}: Et tomt billede", + "ui.agent_chat_file_error": "{name}: {error}", + "ui.agent_chat_file_heic": "{name}: HEIC-billeder kan ikke læses her; eksportér først som JPEG eller PNG", + "ui.agent_chat_file_importing": "Importerer i designet…", + "ui.agent_chat_file_loading": "Læser filen…", + "ui.agent_chat_file_not_a_file": "{name}: Ikke en fil", + "ui.agent_chat_file_not_a_picture": "{name}: Ikke et billede", + "ui.agent_chat_file_not_utf8": "{name}: Ikke UTF-8-tekst", + "ui.agent_chat_file_picture_too_big": "{name}: Et billede må højst fylde {max} MB", + "ui.agent_chat_file_text_too_big": "{name}: En tekstfil må højst fylde {max} KB", + "ui.agent_chat_file_too_large": "{name}: For stor", + "ui.agent_chat_file_too_large_to_send": "{name}: For stor til at sende, selv efter nedskalering", + "ui.agent_chat_file_unreadable_picture": "{name}: Billedformatet kan ikke læses her", + "ui.agent_chat_files": "Filer: {files}", + "ui.agent_chat_files_left_out": "Højst {max} filer pr. besked; udeladt: {files}", + "ui.agent_chat_files_loading": "Venter på indlæsning af filerne", + "ui.agent_chat_files_max": "Højst {max} filer i én besked", + "ui.agent_chat_import_failed": "{name}: Importen mislykkedes: {error}", + "ui.agent_chat_intro": "Chat med en kodeagent, du allerede bruger, eller en modeltjeneste, du vælger. Den arbejder på det åbne design gennem SolidCrafts værktøjer: Ændringer vises undervejs og fortrydes som ét trin pr. besked. Hvad den må gøre uden at spørge, angives i Indstillinger > AI.", + "ui.agent_chat_key_in_env": "nøgle angivet", + "ui.agent_chat_left": "Venstre", + "ui.agent_chat_limit": "Agenten nåede grænsen på {limit} ændringer for én besked. Send en ny besked for at lade den fortsætte.", + "ui.agent_chat_minimize": "Minimér til en stribe", + "ui.agent_chat_model_tip": "Modellen, som agenten bruger. Dit valg huskes for denne agent.", + "ui.agent_chat_new": "Ny chat", + "ui.agent_chat_new_confirm": "Start en ny chat? Den aktuelle chat ryddes.", + "ui.agent_chat_new_yes": "Ny chat", + "ui.agent_chat_no_cli": "solidcraft-cli blev ikke fundet ved siden af appen, så agenten kan ikke få adgang til designet.", + "ui.agent_chat_no_control": "Agentchattens endepunkt startede ikke, så agenten kan ikke få adgang til designet.", + "ui.agent_chat_no_images": "Denne agent kan ikke modtage billeder", + "ui.agent_chat_no_picture": "Der er intet billede i udklipsholderen", + "ui.agent_chat_none_found": "Ingen kodeagent fundet. Installér en af disse, og tryk derefter på Opdatér:", + "ui.agent_chat_none_found_short": "Ingen agent fundet", + "ui.agent_chat_not_installed": "Ikke installeret", + "ui.agent_chat_not_signed_in": "ikke logget ind", + "ui.agent_chat_own_window": "Eget vindue", + "ui.agent_chat_paste_picture": "Indsæt et billede", + "ui.agent_chat_permission": "Agenten beder om at køre: {title}", + "ui.agent_chat_pick": "Agent", + "ui.agent_chat_placeholder": "Bed agenten om at ændre designet…", + "ui.agent_chat_placeholder_busy": "Sæt en besked i kø til agenten er færdig (Ctrl+Enter: send nu)", + "ui.agent_chat_pop_out": "Åbn i eget vindue, som du kan flytte til en anden skærm", + "ui.agent_chat_privacy": "Intet sendes andre steder end til den agent, du kører, under din egen konto.", + "ui.agent_chat_privacy_note": "SolidCraft sender intet nogen steder: Agenten, du kører, kommunikerer med sin egen tjeneste under din egen konto. SolidCraft ser eller gemmer aldrig en nøgle eller adgangskode.", + "ui.agent_chat_queue": "Sæt i kø", + "ui.agent_chat_queue_full": "For mange beskeder venter: Fjern en, eller vent på agenten.", + "ui.agent_chat_queued": "I kø", + "ui.agent_chat_queued_stopped": "I kø (stoppet, ikke sendt)", + "ui.agent_chat_refresh": "Opdatér", + "ui.agent_chat_refused": "Ikke tilladt for agenten: {reason}", + "ui.agent_chat_remove": "Fjern fra køen", + "ui.agent_chat_remove_file": "Fjern fra denne besked", + "ui.agent_chat_remove_imported": "Fjern fra denne besked; emnet bliver i designet (Fortryd fjerner det)", + "ui.agent_chat_right": "Højre", + "ui.agent_chat_save": "Gem", + "ui.agent_chat_send": "Send", + "ui.agent_chat_send_now": "Send nu", + "ui.agent_chat_send_now_tip": "Stop agentens aktuelle trin, og send denne som den næste (Ctrl+Enter)", + "ui.agent_chat_side": "Agentchattens side", + "ui.agent_chat_signed_in": "logget ind", + "ui.agent_chat_state_auth": "Login kræves", + "ui.agent_chat_state_busy": "Arbejder…", + "ui.agent_chat_state_exited": "Agent stoppet", + "ui.agent_chat_state_off": "Ikke forbundet", + "ui.agent_chat_state_ready": "Klar", + "ui.agent_chat_state_starting": "Starter…", + "ui.agent_chat_stop": "Stop", + "ui.agent_chat_stop_tip": "Stop agenten og alt, hvad den har startet", + "ui.agent_chat_stop_turn_tip": "Stop agenten (Esc). Beskeder i kø bliver i køen.", + "ui.agent_chat_turn_limit": "Ændringer pr. besked", + "ui.agent_chat_undo_changes": "Fortryd disse ændringer", + "ui.agent_chat_undo_label": "Agentchat: {message}", + "ui.agent_chat_undone": "(fortrudt)", + "ui.agent_chat_view_attached": "Visning vedhæftet", + "ui.agent_cursor": "Agentmarkør", + "ui.agent_cursor_speed": "Agentmarkørens hastighed", + "ui.ai_add": "Tilføj", + "ui.ai_add_agent": "Tilføj agent…", + "ui.ai_add_agent_title": "Tilføj agent", + "ui.ai_add_api": "OpenAI-kompatibel API", + "ui.ai_add_custom": "Brugerdefineret kommando", + "ui.ai_add_installed": "Installeret agent", + "ui.ai_add_installed_note": "Din egen opsætning af en installeret agent, f.eks. med andre argumenter. Installerede agenter vises automatisk.", + "ui.ai_added": "tilføjet", + "ui.ai_agent_mode_tip": "Agentens egen tilstand: Dens egne værktøjer (kommandoskal og filredigering) følger denne. SolidCrafts værktøjer følger tilladelserne i Indstillinger > AI.", + "ui.ai_agents": "Agenter", + "ui.ai_always_allow": "Tillad altid", + "ui.ai_always_allow_tip": "Tillad fremover {tool} for denne agent uden at spørge", + "ui.ai_always_allowed": "Altid tilladt", + "ui.ai_always_allowed_none": "Ingen handlinger er indstillet til altid at være tilladt. Dine svar med »Tillad altid« i chatten vises her.", + "ui.ai_auto_allowed": "Automatisk tilladt: {title} ({why})", + "ui.ai_auto_mode": "din indstilling for tilladelser", + "ui.ai_auto_ours": "SolidCraft kontrollerer selv sine egne værktøjer", + "ui.ai_auto_remembered": "du valgte Tillad altid", + "ui.ai_bad_url": "Angiv en URL, der begynder med http:// eller https://", + "ui.ai_base_url": "Basis-URL", + "ui.ai_button": "AI", + "ui.ai_copy_suffix": "kopi", + "ui.ai_custom_url": "Brugerdefineret URL", + "ui.ai_default": "Standard", + "ui.ai_http_busy": "endepunktet er optaget eller har nået sin grænse; prøv igen senere", + "ui.ai_http_key": "endepunktet afviste nøglen: Kontrollér den i Indstillinger > AI", + "ui.ai_http_not_found": "endepunktet eller modellen findes ikke: Kontrollér basis-URL og modelnavn", + "ui.ai_key": "API-nøgle", + "ui.ai_key_hint": "valgfri; gemmes i systemets nøglering", + "ui.ai_key_needs_https": "En nøgle sendes kun via HTTPS eller til denne computer.", + "ui.ai_key_note": "Gemmes i systemets nøglering, aldrig i SolidCrafts indstillinger. Lad feltet være tomt ved en lokal server.", + "ui.ai_keychain_error": "Systemets nøglering afviste anmodningen: {error}", + "ui.ai_mode_all": "Tillad alt", + "ui.ai_mode_all_note": "Intet kræver godkendelse først. Nedbrudsrapporter er stadig utilgængelige, og mappebegrænsningerne gælder fortsat.", + "ui.ai_mode_all_warning": "Agenten kan gemme, overskrive, eksportere og erstatte dit design uden at spørge. Brug kun dette med en agent, du har tillid til, og på designs, du har gemt.", + "ui.ai_mode_ask": "Spørg hver gang", + "ui.ai_mode_ask_note": "Enhver ændring af designet og enhver filhandling venter på din tilladelse.", + "ui.ai_mode_edits": "Tillad automatisk modelændringer", + "ui.ai_mode_edits_note": "Modelleringskommandoer kører uden at spørge; lagring, åbning, eksport og andre filhandlinger eller destruktive handlinger kræver stadig godkendelse.", + "ui.ai_mode_global": "Som angivet ovenfor", + "ui.ai_model": "Model", + "ui.ai_modes_scope": "Disse indstillinger gælder for SolidCrafts værktøjer. Agentens egne værktøjer (kommandoskal og filredigering) følger dens egen tilstand, som du vælger øverst i chatpanelet, hvis agenten har flere tilstande.", + "ui.ai_name": "Navn", + "ui.ai_need_command": "Angiv kommandoen, der starter agenten", + "ui.ai_need_model": "Angiv modelnavnet", + "ui.ai_no_answer": "Agenten svarede ikke i tide", + "ui.ai_no_http": "Denne udgave kan ikke få adgang til API-endepunkter", + "ui.ai_no_keychain": "Systemets nøglering er ikke tilgængelig, så en nøgle kan ikke gemmes. En lokal server uden nøgle virker stadig.", + "ui.ai_panel": "Panel", + "ui.ai_permissions": "Tilladelser", + "ui.ai_preset": "Forudindstilling", + "ui.ai_remove": "Fjern", + "ui.ai_request_limit": "stoppet efter 24 anmodninger for én besked; send en ny besked for at fortsætte", + "ui.ai_reset": "Nulstil", + "ui.ai_settings": "AI-indstillinger…", + "ui.ai_show_features": "Vis AI-funktioner", + "ui.ai_show_features_note": "Agentchatten: Et panel, hvor en kodeagent, du allerede bruger, eller en modeltjeneste, du vælger, arbejder på det åbne design. Slået fra: Ingen AI-knap, genvej, menupunkt eller panel, og der søges ikke efter eller startes noget.", + "ui.ai_switch_tip": "Skift agent for denne samtale", + "ui.ai_test": "Test", + "ui.ai_test_acp_ok": "Svarer: {agent}", + "ui.ai_test_acp_tip": "Starter agenten kortvarigt og anmoder om en session; afslutter den derefter igen", + "ui.ai_test_api_tip": "Henter endepunktets modeller", + "ui.ai_test_no_model": "Forbindelse oprettet: {count} modeller, men ikke {model}", + "ui.ai_test_ok": "Forbindelse oprettet: {count} modeller", + "ui.ai_testing": "Tester…", + "ui.ai_tool_done": "færdig", + "ui.ai_tool_failed": "mislykkedes", + "ui.ai_tool_running": "kører", + "ui.ai_tool_unfold": "Klik for at vise svaret", + "ui.ai_tool_waiting": "venter", + "ui.ai_toolbar_button": "Vis knap på værktøjslinjen", + "ui.ai_toolbar_button_note": "AI-knappen i højre ende af værktøjslinjen. Ctrl+Shift+A og menuen Vis åbner stadig panelet.", + "ui.ai_undo_tip": "Fortryd alt, agenten ændrede for denne besked, som ét trin", + "ui.all": "Alle", + "ui.ambient_occlusion": "Ambient occlusion", + "ui.ambient_occlusion_help": "Bløde skygger, hvor uigennemsigtige overflader mødes. Kræver GPU-visning.", + "ui.analysis": "Analyse", + "ui.angle": "Vinkel", + "ui.angle_decimals": "Vinkeldecimaler", + "ui.animateJoint": "Animér led", + "ui.animate_view_changes": "Animér visningsskift", + "ui.animation": "Animation", + "ui.animation_speed": "Animationshastighed", + "ui.anti_aliasing": "Kantudjævning", + "ui.apply": "Anvend", + "ui.arc": "Bue", + "ui.assemble": "Samling", + "ui.autosave_every": "Gem automatisk hver", + "ui.axes": "Akser", + "ui.axis": "Akse", + "ui.base_point": "Basispunkt", + "ui.blocked": "Blokeret", + "ui.bodies": "Emner", + "ui.bodies_all_if_none": "Emner (alle, hvis ingen er valgt)", + "ui.box": "Boks", + "ui.break": "Bryd", + "ui.calibrate": "Kalibrér", + "ui.cancel": "Annullér", + "ui.canvases": "Referencebilleder", + "ui.center": "Centrum", + "ui.centerline": "Centerlinje", + "ui.chain": "Kæde", + "ui.chamfer": "Affasning", + "ui.chamfer_type": "Affasningstype", + "ui.change_workspace": "Skift arbejdsområde", + "ui.chord_length": "Kordelængde", + "ui.circle": "Cirkel", + "ui.circular_pattern": "Cirkulært mønster", + "ui.clear": "Ryd", + "ui.clear_recent": "Ryd seneste", + "ui.clear_the_selection": "Ryd markeringen", + "ui.click_selects_whole_bodies": "Klik vælger hele emner", + "ui.click_then_press_key": "Klik, og tryk derefter på den nye tast", + "ui.close": "Luk", + "ui.coil": "Spiral", + "ui.coincident": "Sammenfaldende", + "ui.collapse": "Fold sammen", + "ui.collinear": "Kollineær", + "ui.colour_vision": "Farvesyn", + "ui.colour_vision_deutan": "Deutan", + "ui.colour_vision_deutan_tip": "Ved svækket eller manglende følsomhed for grønt", + "ui.colour_vision_failed": "Mislykkedes", + "ui.colour_vision_fixed": "Fikseret", + "ui.colour_vision_mode": "Tilstand", + "ui.colour_vision_note": "Ændrer farver, der formidler betydning: skitsetilstande, akser, bukninger, analyser og ikoner. Slå dette fra, hvis du bruger Windows' farvefiltre.", + "ui.colour_vision_off": "Fra", + "ui.colour_vision_off_tip": "Temaets egne farver", + "ui.colour_vision_projected": "Projiceret", + "ui.colour_vision_protan": "Protan", + "ui.colour_vision_protan_tip": "Ved svækket eller manglende følsomhed for rødt", + "ui.colour_vision_sample": "Eksempel", + "ui.colour_vision_tritan": "Tritan", + "ui.colour_vision_tritan_tip": "Ved svækket eller manglende følsomhed for blåt", + "ui.combine": "Kombinér", + "ui.coming_later": "kommer senere", + "ui.command_done": "{command} udført", + "ui.command_palette_hint": "Skriv en kommando, f.eks. {example} — eller tryk S for at søge", + "ui.concentric": "Koncentrisk", + "ui.configurations": "Konfigurationer", + "ui.conic_curve": "Keglesnitskurve", + "ui.constant": "Konstant", + "ui.constraints_conflict": "Bindinger er i konflikt", + "ui.construct": "Konstruktion", + "ui.construction": "Konstruktionsgeometri", + "ui.context_menu": "Genvejsmenu", + "ui.continuity_g0": "G0-knæk", + "ui.continuity_g1": "G1-tangentkontinuitet", + "ui.continuity_g2": "G2-krumningskontinuitet", + "ui.continuity_gap": "Åbning mellem flader", + "ui.copy": "Kopiér", + "ui.corner": "Hjørne", + "ui.corners": "Hjørner", + "ui.counterbore": "Cylindrisk forsænkning", + "ui.countersink": "Konisk forsænkning", + "ui.create": "Opret", + "ui.create_copy": "Opret kopi", + "ui.create_sketch": "Opret skitse", + "ui.current": "aktuel", + "ui.curvature": "Krumning", + "ui.curvature_g2": "Krumningskontinuitet (G2)", + "ui.curves": "Kurver", + "ui.custom_program": "Brugerdefineret…", + "ui.custom_program_tip": "Vælg et slicerprogram, der skal føjes til listen", + "ui.customizeToolbar": "Tilpas værktøjslinje…", + "ui.cut": "Skær fra", + "ui.cylinder": "Cylinder", + "ui.dark": "Mørk", + "ui.default_modelling_orientation": "Standardorientering for modellering", + "ui.degrees_of_freedom": "frihedsgrader", + "ui.delete": "Slet", + "ui.depth": "Dybde", + "ui.design": "Design", + "ui.design_properties.author": "Forfatter", + "ui.design_properties.description": "Beskrivelse", + "ui.design_properties.exports": "Eksport til STEP, IGES og 3MF medtager disse oplysninger, hvor formatet har plads til dem.", + "ui.design_properties.license": "Licens", + "ui.design_properties.not_text": "Gemt som andet end tekst; indtastning her erstatter værdien.", + "ui.design_properties.organization": "Organisation", + "ui.design_properties.others": "Data fra andre værktøjer", + "ui.design_properties.others_note": "Bevares uændret i designet og eksporteres aldrig.", + "ui.design_properties.part_number": "Emnenummer", + "ui.design_properties.project": "Projekt", + "ui.design_properties.revision": "Revision", + "ui.diameter": "Diameter", + "ui.dimension": "Målsætning", + "ui.direction": "Retning", + "ui.display_quality": "Visningskvalitet", + "ui.display_quality_coarse": "Grov", + "ui.display_quality_fine": "Fin", + "ui.display_quality_normal": "Normal", + "ui.display_quality_ultra": "Ultra", + "ui.distance": "Afstand", + "ui.distance_1": "Afstand 1", + "ui.distance_2": "Afstand 2", + "ui.document_settings": "Designindstillinger", + "ui.don_t_save": "Gem ikke", + "ui.draft": "Slipvinkel", + "ui.drawing": "Tegning", + "ui.drill_point": "Borspids", + "ui.edit": "Redigér", + "ui.editJointLimits": "Redigér ledgrænser", + "ui.edit_section_analysis": "Redigér snitanalyse", + "ui.ellipse": "Ellipse", + "ui.end_radius": "Slutradius", + "ui.end_scale": "Skalering ved slutningen", + "ui.entities": "Elementer", + "ui.equal": "Ens", + "ui.equivalent_radius": "Ækvivalent radius", + "ui.expand": "Fold ud", + "ui.exportDxf": "Eksportér DXF…", + "ui.export_ellipsis": "Eksportér...", + "ui.export_ellipsis_keymap": "Eksportér…", + "ui.export_keymap_tip": "Gem tastaturgenveje, favoritter i S-menuen og værktøjslinjen i en fil", + "ui.extend": "Forlæng", + "ui.extent_type": "Udstrækningstype", + "ui.extrude": "Ekstrudering", + "ui.factor": "Faktor", + "ui.feature_history": "Featuretidslinje", + "ui.feature_options": "Featureindstillinger", + "ui.features": "Features", + "ui.file": "Filer", + "ui.fillet": "Afrunding", + "ui.filter_commands_or_keys": "Filtrér kommandoer eller taster", + "ui.findInTimeline": "Find i tidslinje", + "ui.findInWindow": "Find i vindue", + "ui.finish_sketch": "Afslut skitse", + "ui.fit": "Tilpas", + "ui.fix_unfix": "Lås fast/frigør", + "ui.flat": "Flad", + "ui.flip": "Vend", + "ui.format": "Format", + "ui.frame_rate": "Billedfrekvens", + "ui.front": "Forfra", + "ui.fully_constrained": "Fuldt bundet", + "ui.general": "Generelt", + "ui.graphics": "Grafik", + "ui.graphics_custom": "Brugerdefineret", + "ui.graphics_performance": "Ydeevne", + "ui.graphics_preset": "Grafikprofil", + "ui.graphics_preset_help": "Kvalitet: Ambient occlusion, fin visningskvalitet og adaptiv 2× supersampling. Ydeevne: Ingen ambient occlusion, normal visningskvalitet og supersampling slået fra. Ændrer du indstillingerne manuelt, vises Brugerdefineret. MSAA ændres ikke.", + "ui.graphics_quality": "Kvalitet", + "ui.grid_follows_view": "Gitter følger visningen", + "ui.grid_follows_view_hint": "Sidevisninger viser gitteret på det lodrette plan, der vender mod dem, i stedet for grundplanet", + "ui.ground_shadow": "Skygge på grundplan", + "ui.groupSelected": "Gruppér valgte", + "ui.heading_add_ins": "ADD-INS", + "ui.heading_assemble": "SAMLING", + "ui.heading_box": "BOKS", + "ui.heading_chamfer": "AFFASNING", + "ui.heading_circular_pattern": "CIRKULÆRT MØNSTER", + "ui.heading_coil": "SPIRAL", + "ui.heading_combine": "KOMBINÉR", + "ui.heading_configure": "KONFIGURÉR", + "ui.heading_constraints": "BINDINGER", + "ui.heading_construct": "KONSTRUKTION", + "ui.heading_create": "OPRET", + "ui.heading_create_sketch": "OPRET SKITSE", + "ui.heading_cylinder": "CYLINDER", + "ui.heading_design": "DESIGN", + "ui.heading_draft": "SLIPVINKEL", + "ui.heading_edit": "REDIGÉR", + "ui.heading_extrude": "EKSTRUDERING", + "ui.heading_fillet": "AFRUNDING", + "ui.heading_finish_sketch": "AFSLUT SKITSE", + "ui.heading_front": "FORFRA", + "ui.heading_hole": "HUL", + "ui.heading_home": "HJEM", + "ui.heading_insert": "INDSÆT", + "ui.heading_inspect": "INSPICÉR", + "ui.heading_interference": "OVERLAP", + "ui.heading_loft": "LOFT", + "ui.heading_make": "FREMSTIL", + "ui.heading_measure": "MÅL", + "ui.heading_mesh": "MESH", + "ui.heading_mirror": "SPEJLING", + "ui.heading_modify": "REDIGÉR", + "ui.heading_move": "FLYT", + "ui.heading_move_copy": "FLYT/KOPIÉR", + "ui.heading_offset": "FORSKYDNING", + "ui.heading_offset_plane": "FORSKUDT PLAN", + "ui.heading_ok": "OK", + "ui.heading_parameters": "PARAMETRE", + "ui.heading_pattern": "MØNSTER", + "ui.heading_pattern_on_path": "MØNSTER LANGS BANE", + "ui.heading_pipe": "RØR", + "ui.heading_plane_at_angle": "PLAN I VINKEL", + "ui.heading_plastic": "PLAST", + "ui.heading_position": "POSITION", + "ui.heading_prepare": "KLARGØR", + "ui.heading_rectangular_pattern": "REKTANGULÆRT MØNSTER", + "ui.heading_revolve": "OMDREJNING", + "ui.heading_right": "FRA HØJRE", + "ui.heading_save_mesh": "GEM SOM MESH", + "ui.heading_scale": "SKALERING", + "ui.heading_section_analysis": "SNITANALYSE", + "ui.heading_select": "VÆLG", + "ui.heading_setup": "OPSÆTNING", + "ui.heading_sheet_metal": "PLADE", + "ui.heading_shell": "UDHULNING", + "ui.heading_sketch": "SKITSE", + "ui.heading_sketch_palette": "SKITSEPALETTE", + "ui.heading_sketch_scale": "SKITSESKALERING", + "ui.heading_solid": "MASSIVT EMNE", + "ui.heading_sphere": "KUGLE", + "ui.heading_split_body": "OPDEL EMNE", + "ui.heading_surface": "OVERFLADE", + "ui.heading_sweep": "SWEEP", + "ui.heading_thread": "GEVIND", + "ui.heading_top": "OVENFRA", + "ui.heading_torus": "TORUS", + "ui.heading_utilities": "VÆRKTØJER", + "ui.heading_utility": "VÆRKTØJ", + "ui.help": "Hjælp", + "ui.hide": "Skjul", + "ui.hideAxes": "Skjul akser", + "ui.hideDimension": "Skjul mål", + "ui.hideOrigin": "Skjul nulpunkt", + "ui.hidePlanes": "Skjul planer", + "ui.hideProfile": "Skjul profil", + "ui.hole": "Hul", + "ui.hole_tap_type": "Hullets gevindtype", + "ui.hole_type": "Hultype", + "ui.home": "Hjem", + "ui.homeView": "Hjemmevisning", + "ui.horizontal_vertical": "Vandret/lodret", + "ui.import_ellipsis": "Importér…", + "ui.infinite": "Uendelig", + "ui.insert": "Indsæt", + "ui.inspect": "Inspicér", + "ui.intersect": "Fællesvolumen", + "ui.isolate": "Isolér", + "ui.join": "Foren", + "ui.joints": "Led", + "ui.keyboard_shortcuts": "Tastaturgenveje", + "ui.language": "Sprog", + "ui.length_decimals": "Længdedecimaler", + "ui.light": "Lys", + "ui.line": "Linje", + "ui.linetype": "Linjetype", + "ui.lock": "Lås", + "ui.loft": "Loft", + "ui.look_at": "Se på", + "ui.look_at_anim_desc": "Aksevisning, Se på, Hjem og Tilpas", + "ui.manufacture": "Fremstilling", + "ui.material_review.axes": "Materialets lokale akser; ingen orientering af emnet er tildelt.", + "ui.material_review.claims": "Kilder og licenser er ubekræftede angivelser. Manglende værdier forbliver ukendte.", + "ui.material_review.compressive_strength": "Trykstyrke", + "ui.material_review.conditions": "Angivne betingelser", + "ui.material_review.density": "Densitet", + "ui.material_review.derived": "Afledte isotrope moduler", + "ui.material_review.elasticity": "Elasticitet", + "ui.material_review.input": "Indsæt et materialekort med skemaversion 1 (JSON)", + "ui.material_review.limit": "Kortet overskrider inputgrænsen på 256 KiB.", + "ui.material_review.moisture_unit": "kg vand / kg tørt materiale", + "ui.material_review.properties": "Egenskaber", + "ui.material_review.review": "Gennemgå kort", + "ui.material_review.scope": "Kun et forslag: Ikke tildelt eller gemt. Numerisk validering er ikke en teknisk certificering.", + "ui.material_review.shear_strength": "Forskydningsstyrke", + "ui.material_review.source": "Kilde", + "ui.material_review.specific_heat": "Specifik varmekapacitet", + "ui.material_review.tensile_strength": "Trækstyrke", + "ui.material_review.thermal_conductivity": "Varmeledningsevne", + "ui.material_review.thermal_expansion": "Varmeudvidelse", + "ui.material_review.title": "Gennemgå fysiske materialedata", + "ui.material_review.unknown": "Ukendt", + "ui.material_review.yield_strength": "Flydespænding", + "ui.measure": "Mål", + "ui.mesh_format_3mf": "3MF", + "ui.mesh_format_3mf_tagged": "3MF med flademærker", + "ui.mesh_format_stl": "STL", + "ui.midpoint": "Midtpunkt", + "ui.mirror": "Spejling", + "ui.mirror_line": "Spejlingslinje", + "ui.modify": "Redigér", + "ui.move": "Flyt", + "ui.multiple": "Flere", + "ui.named_views": "Navngivne visninger", + "ui.navigation": "Navigation", + "ui.needs_design": "{command}: Åbn først et design", + "ui.newSketchGroup": "Ny skitsegruppe", + "ui.new_body": "Nyt emne", + "ui.new_design": "Nyt design", + "ui.no_slicer_found": "Ingen slicer fundet", + "ui.normal": "Normal", + "ui.normalConstruction": "Normal / konstruktionsgeometri", + "ui.not_a_program": "{path} er ikke et program, der kan startes", + "ui.object_type": "Objekttype", + "ui.objects": "Objekter", + "ui.offer_to_stand_up_y_up_files": "Tilbyd at stille filer med Y opad på højkant", + "ui.offset": "Forskydning", + "ui.offset_plane": "Forskudt plan", + "ui.one_side": "Én side", + "ui.open": "Åbn", + "ui.open_ellipsis": "Åbn...", + "ui.open_ends_tip": "Berører intet", + "ui.open_preferences": "Åbn indstillinger", + "ui.open_recent": "Åbn seneste", + "ui.operation": "Operation", + "ui.options": "Indstillinger", + "ui.orbit": "Rotér visning", + "ui.orbit_around": "Rotér omkring", + "ui.orientation": "Orientering", + "ui.origin": "Nulpunkt", + "ui.palette_points": "Punkter", + "ui.palette_profile": "Profil", + "ui.pan": "Panorér", + "ui.pan_zoom_orbit": "Panorér, zoom, rotér visning", + "ui.parallel": "Parallel", + "ui.parameters": "Parametre", + "ui.paste": "Indsæt", + "ui.path": "Bane", + "ui.pattern_on_path": "Mønster langs bane", + "ui.perpendicular": "Vinkelret", + "ui.perspective_view": "Perspektivvisning", + "ui.pinToShortcuts": "Fastgør til genveje", + "ui.pinToToolbar": "Fastgør til værktøjslinje", + "ui.pipe": "Rør", + "ui.placement": "Placering", + "ui.plane": "Plan", + "ui.plane_at_angle": "Plan i vinkel", + "ui.point": "Punkt", + "ui.point_under_the_cursor": "Punkt under markøren", + "ui.points": "Punkter", + "ui.polygon": "Polygon", + "ui.preferences": "Indstillinger", + "ui.press_a_key": "tryk på en tast…", + "ui.profile": "Profil", + "ui.profile_plane": "Profilplan", + "ui.profiles": "Profiler", + "ui.project": "Projektér", + "ui.project_face_edges_sketch": "Projektér fladekanter til nye skitser", + "ui.properties": "Egenskaber", + "ui.pull_direction": "Udtræksretning", + "ui.quantity": "Antal", + "ui.quantity_2": "Antal 2", + "ui.quit": "Afslut", + "ui.radial_context_menu": "Radial genvejsmenu", + "ui.radius": "Radius", + "ui.radius_type": "Radiustype", + "ui.rail": "Styrekurve", + "ui.rail_fit": "Tilpasning til styrekurve", + "ui.reachable": "Kan nås", + "ui.rectangle": "Rektangel", + "ui.rectangular_pattern": "Rektangulært mønster", + "ui.redo": "Gentag", + "ui.removeFromToolbar": "Fjern fra værktøjslinje", + "ui.removeSection": "Fjern snit", + "ui.render": "Rendering", + "ui.renderer": "Renderingsmotor", + "ui.repeat": "Gentag", + "ui.report_a_bug": "Rapportér en fejl", + "ui.reset": "Nulstil", + "ui.reset_all": "Nulstil alle", + "ui.reset_the_settings_on_this_page": "Nulstil indstillingerne på denne side", + "ui.restore": "Gendan", + "ui.restore_defaults": "Gendan standarder", + "ui.reverse_horizontal_pan_direction": "Vend vandret panoreringsretning", + "ui.reverse_horizontal_pan_tip": "Vandret rulning med to fingre og tommelfingerhjulet panorerer i den modsatte retning", + "ui.reverse_zoom_direction": "Vend zoomretning", + "ui.revolve": "Omdrejning", + "ui.right": "Fra højre", + "ui.save": "Gem", + "ui.save_as": "Gem som", + "ui.save_as_ellipsis": "Gem som...", + "ui.save_mesh_no_slicer": "Ingen slicer fundet: Vælg Brugerdefineret…, og vælg dit slicerprogram, eller slå Send til slicer fra", + "ui.save_mesh_pick_bodies": "Vælg de emner, der skal gemmes", + "ui.save_mesh_temp_failed": "Kunne ikke oprette {folder}: {error}", + "ui.saved_to": "Gemt: {path}", + "ui.sbox_pin": "Fastgør øverst i S-menuen", + "ui.sbox_unpin": "Fjern fastgørelse", + "ui.scale": "Skalering", + "ui.second_rail": "Anden styrekurve", + "ui.section_analysis": "Snitanalyse", + "ui.select": "Vælg", + "ui.selectOther": "Vælg andet…", + "ui.selectTangentChain": "Vælg tangentkæde", + "ui.select_other_hint": "Vælg andet: Hold venstre museknap nede uden at flytte markøren på modellen (eller højreklik › Vælg andet…) for at vise alt under markøren. Klik igen samme sted for at vælge næste objekt.", + "ui.selection": "Markering", + "ui.send": "Send", + "ui.send_to_slicer": "Send til slicer", + "ui.sent_to_slicer": "Sendt til {slicer}", + "ui.sheet_gap": "Mellemrum", + "ui.shell": "Udhulning", + "ui.show": "Vis", + "ui.showAll": "Vis alle", + "ui.showAllBodies": "Vis alle emner", + "ui.showAxes": "Vis akser", + "ui.showDimension": "Vis mål", + "ui.showOrigin": "Vis nulpunkt", + "ui.showPlanes": "Vis planer", + "ui.show_constraints": "Bindinger", + "ui.show_construction_geometries": "Konstruktionsgeometri", + "ui.show_dimensions": "Mål", + "ui.show_points": "Vis punkter", + "ui.show_profile": "Vis profil", + "ui.show_projected_geometries": "Projiceret geometri", + "ui.simple": "Enkel", + "ui.simulation": "Simulering", + "ui.single": "Enkelt", + "ui.sketch": "Skitse", + "ui.sketch_dimension": "Skitsemål", + "ui.sketch_grid": "Skitsegitter", + "ui.sketch_scale": "Skitseskalering", + "ui.sketch_status": "Skitsestatus", + "ui.sketches": "Skitser", + "ui.slice": "Lagdeling", + "ui.slicer": "Slicer", + "ui.slicer_delete_tip": "{program}\nTryk Delete for at fjerne det fra listen", + "ui.slot": "Slids", + "ui.smooth": "Glat", + "ui.smooth_wheel_zoom": "Jævn zoom med musehjul", + "ui.smooth_wheel_zoom_tip": "Slå fra for at anvende hver hjulbevægelse straks uden efterfølgende udjævning", + "ui.snap": "Fastgør til geometri", + "ui.space_mouse_hint": "Flyt og rotér visningen samtidigt; skitser bruger kun panorering og zoom.", + "ui.space_mouse_navigate": "Navigér med SpaceNavigator / SpaceMouse", + "ui.spacing": "Afstand", + "ui.spacing_2": "Afstand 2", + "ui.sphere": "Kugle", + "ui.spline": "Spline", + "ui.split_body": "Opdel emne", + "ui.stand_up_tip": "Når en STEP- eller IGES-fil åbnes med Z opad, tilbydes en kvart omdrejning om X", + "ui.start": "Start", + "ui.start_radius": "Startradius", + "ui.stretch": "Stræk", + "ui.supersampling": "Supersampling (SSAA)", + "ui.supersampling_adaptive": "Kun når visningen står stille", + "ui.supersampling_off": "Fra (1×)", + "ui.suppress": "Undertryk", + "ui.sweep": "Sweep", + "ui.sweep_follow_direction": "Følg retning", + "ui.sweep_keep_as_drawn": "Behold som tegnet", + "ui.sweep_turn_with_path": "Drej med banen", + "ui.symmetric": "Symmetrisk", + "ui.symmetry": "Symmetri", + "ui.system": "System", + "ui.tangent": "Tangent", + "ui.taper_angle": "Konusvinkel", + "ui.tapped": "Med gevind", + "ui.text": "Tekst", + "ui.theme": "Tema", + "ui.thickness": "Tykkelse", + "ui.thread": "Gevind", + "ui.tie_ends": "Sammenbind", + "ui.tie_ends_tip": "Bind alle ubundne ender", + "ui.timeline_bottom": "Tidslinje nederst", + "ui.timeline_left_note": "Layoutet til venstre viser tilbagerulningslinjen over modeltræet med emner og scene.", + "ui.timeline_left_sidebar": "Venstre sidepanel", + "ui.tip_angle": "Spidsvinkel", + "ui.to_object": "Til objekt", + "ui.tool_direction": "Værktøjsretning", + "ui.top": "Ovenfra", + "ui.torus": "Torus", + "ui.total_angle": "Samlet vinkel", + "ui.trackpad_pan_tip": "Bevægelser på pegefeltet panorerer (slået fra: zoomer som musehjulet); musehjulet zoomer, tommelfingerhjulet panorerer sidelæns, og knibebevægelse zoomer altid", + "ui.trim": "Trim", + "ui.twist": "Vridning", + "ui.two_finger_scroll_pans": "Rulning med to fingre panorerer", + "ui.two_sides": "To sider", + "ui.ui_scale": "Skalering af brugerflade", + "ui.undo": "Fortryd", + "ui.unground": "Ophæv fastgørelse", + "ui.unisolate": "Ophæv isolering", + "ui.units": "Enheder", + "ui.units_of_new_designs": "Enheder for nye designs", + "ui.unlock": "Lås op", + "ui.unsuppress": "Ophæv undertrykkelse", + "ui.untied_ends_tip": "Mødes, men er ikke bundet sammen", + "ui.untitled": "Uden titel", + "ui.up_axis_note": "Hvilken akse der peger opad i visningerne (aksevisning, Hjem, Se på). Designs ændres ikke.", + "ui.updateToCurrentView": "Opdatér til aktuel visning", + "ui.variable": "Variabel", + "ui.view_centre": "Visningens centrum", + "ui.visual_shaded_hidden_edges": "Skyggelagt med skjulte kanter", + "ui.visual_shaded_with_edges": "Skyggelagt med kanter", + "ui.visual_style": "Visuel stil", + "ui.visual_wireframe": "Trådmodel", + "ui.workspace": "arbejdsområde", + "ui.x_distance": "X-afstand", + "ui.y_distance": "Y-afstand", + "ui.y_up": "Y opad", + "ui.z_up": "Z opad", + "ui.zoom": "Zoom", + "ui.zoom_to_cursor_tip": "Musehjulet zoomer mod punktet under markøren (slået fra: mod visningens centrum)", + "ui.zoom_to_the_cursor": "Zoom mod markøren", + "update.available": "SolidCraft {version} er tilgængelig", + "update.button": "Opdatér", + "update.button_tip": "SolidCraft {version} er tilgængelig", + "update.button_version": "Opdatér til {version}", + "update.check_automatically": "Søg automatisk efter opdateringer", + "update.check_now": "Søg nu", + "update.checking": "Søger…", + "update.copy": "Kopiér", + "update.dmg_opened": "Diskbilledet er åbnet og verificeret: Træk SolidCraft til Programmer, erstat den gamle kopi, og genstart SolidCraft.", + "update.download": "Download", + "update.download_open": "Download og åbn", + "update.downloading": "Downloader og verificerer… {done} af {total} MB", + "update.failed": "Kunne ikke søge: {error}", + "update.file": "Download henter {file}.", + "update.install_failed": "Opdateringen blev ikke installeret: {error}. Intet blev ændret; Download henter pakken i stedet.", + "update.install_msi": "Installér (lukker SolidCraft)", + "update.installed": "SolidCraft {version} er installeret. Genstart for at bruge den.", + "update.installer_started": "Installationsprogrammet starter, når SolidCraft lukker.", + "update.later": "Påmind mig senere", + "update.no_notes": "Der er ingen beskrivelse af denne version.", + "update.package_hint": "Denne kopi kom fra en {kind}. Download den nye pakke, og installér den med:", + "update.prefs_dev": "Dette er en udviklingsudgave ({version}): Den søger ikke efter opdateringer.", + "update.prefs_flatpak": "Flatpak opdaterer denne kopi ({version}): Kør {command}, eller brug dit softwarecenter. SolidCraft søger ikke efter opdateringer.", + "update.prefs_label": "Opdateringer", + "update.prefs_note": "Dette er SolidCraft {version} ({kind}). En opdateringskontrol spørger GitHub om den seneste udgivelse og sender intet andet.", + "update.release_page": "Åbn udgivelsesside", + "update.restart": "Genstart nu", + "update.restart_later": "Senere", + "update.show": "Vis opdateringen til {version}", + "update.skip": "Spring denne version over", + "update.system_hint": "Denne kopi er en {kind}. Opdatér den med:", + "update.title": "Opdatering tilgængelig", + "update.up_to_date": "SolidCraft er opdateret.", + "update.update_now": "Opdatér nu", + "update.you_have": "Du har {version}." +} diff --git a/crates/ui-egui/src/colour_vision_tests.rs b/crates/ui-egui/src/colour_vision_tests.rs index c97cde549..9a96b8792 100644 --- a/crates/ui-egui/src/colour_vision_tests.rs +++ b/crates/ui-egui/src/colour_vision_tests.rs @@ -722,6 +722,7 @@ fn the_sections_messages_are_in_every_catalog() { .collect(); for (lang, text) in [ ("cs", include_str!("../../../assets/locales/cs.json")), + ("da", include_str!("../../../assets/locales/da.json")), ("de", include_str!("../../../assets/locales/de.json")), ("ja", include_str!("../../../assets/locales/ja.json")), ("ko", include_str!("../../../assets/locales/ko.json")), @@ -734,7 +735,9 @@ fn the_sections_messages_are_in_every_catalog() { let (Some(en), Some(here)) = (english.get(*id), catalog.get(*id)) else { panic!("{lang}: missing message {id} (English: {})", english.contains_key(*id)); }; - assert!(lang == "de" || here != en, "{lang}: {id} is the English text {en}"); + // Danish uses the same established names for these colour-vision modes. + let shared_name = lang == "da" && ["ui.colour_vision_deutan", "ui.colour_vision_protan", "ui.colour_vision_tritan"].contains(id); + assert!(lang == "de" || shared_name || here != en, "{lang}: {id} is the English text {en}"); } } } diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index e95ab63b1..f91d46675 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -33,6 +33,7 @@ impl Catalog { static ENGLISH: Catalog = Catalog::new("en", "English", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/en.json"))); static CZECH: Catalog = Catalog::new("cs", "Čeština", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/cs.json"))); +static DANISH: Catalog = Catalog::new("da", "Dansk", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/da.json"))); static GERMAN: Catalog = Catalog::new("de", "Deutsch", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/de.json"))); static SPANISH: Catalog = Catalog::new("es", "Español (España)", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/es.json"))); static FRENCH: Catalog = Catalog::new("fr", "Français", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/fr.json"))); @@ -55,6 +56,7 @@ static CHINESE: Catalog = Catalog::new("zh", "中文", include_str!(concat!(env! pub const LOCALES: &[&Catalog] = &[ &ENGLISH, &CZECH, + &DANISH, &GERMAN, &SPANISH, &FRENCH, @@ -348,6 +350,7 @@ mod tests { fn newly_catalogued_command_labels_translate() { let cases = [ ("cs", "Příruba", "Zebra analýza", "Studie pohybu"), + ("da", "Flange", "Zebraanalyse", "Bevægelsesanalyse"), ("zh", "法兰", "斑马纹分析", "运动研究"), ("ja", "フランジ", "ゼブラ解析", "モーション スタディ"), ("de", "Flansch", "Zebra-Analyse", "Bewegungsuntersuchung"), diff --git a/docs/localization.md b/docs/localization.md index ed7575932..3fc072bbf 100644 --- a/docs/localization.md +++ b/docs/localization.md @@ -1,6 +1,6 @@ # UI localization -SolidCraft embeds its translations and works offline. English, Czech, German, Spanish, French, Galician, Italian, +SolidCraft embeds its translations and works offline. English, Czech, Danish, German, Spanish, French, Galician, Italian, Japanese, Korean, Malay, Polish, Brazilian Portuguese, Russian, Turkish, Ukrainian and Chinese are currently registered in `crates/ui-egui/src/i18n.rs`. Adding a language requires an embedded catalog and one registration there; the preferences selector and validation use the same registry. @@ -38,7 +38,7 @@ that looks untranslated. Two guards catch that in the build: - `every_complete_catalog_carries_every_english_message` — adding a key to `en.json` without giving it to a complete catalog fails the tests. English is the source catalog, - Japanese and Chinese are delivered complete; German, Spanish, Galician, Italian, Korean, Malay, Polish, Brazilian Portuguese, Russian, French, Ukrainian and + Japanese and Chinese are delivered complete; Danish, German, Spanish, Galician, Italian, Korean, Malay, Polish, Brazilian Portuguese, Russian, French, Ukrainian and Turkish are partial — their gaps fall back to English and are reported by `cargo xtask i18n` without failing the build. A new label needs en, ja, zh, de and ko; Russian, French, Ukrainian and Malay may follow later. From 4d99d792050296e0506257cdd684250a48ffdc79 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Mon, 19 Oct 2026 17:23:29 -0400 Subject: [PATCH 123/225] README: shorter front page; details move to docs (#3275) * README: shorter front page; details move to docs * Downloads page: drop stray lines --- CONTRIBUTING.md | 2 +- README.md | 305 +++++------------------------- docs/3d-mouse.md | 46 +++++ docs/architecture.md | 13 ++ docs/book/src/dev/architecture.md | 2 +- docs/building.md | 28 +++ docs/capabilities.md | 99 ++++++++++ docs/downloads.md | 44 +++++ docs/scripts.md | 15 ++ docs/showcase.md | 9 + 10 files changed, 306 insertions(+), 257 deletions(-) create mode 100644 docs/3d-mouse.md create mode 100644 docs/architecture.md create mode 100644 docs/building.md create mode 100644 docs/capabilities.md create mode 100644 docs/downloads.md create mode 100644 docs/scripts.md create mode 100644 docs/showcase.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d3b01c62c..55bfb4c99 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -72,7 +72,7 @@ desktop integration and how to distinguish an old executable on `PATH`. ## How the code is laid out -The [README](README.md#architecture) has the layer table. The short version: +The [architecture page](docs/architecture.md) has the layer table. The short version: - `crates/geom`: vectors, planes, meshes, measures. - `crates/sketch`: our own constraint solver, plus profile finding. diff --git a/README.md b/README.md index 5229cdd14..802132430 100644 --- a/README.md +++ b/README.md @@ -46,281 +46,65 @@ ## Download -- **Windows:** download and run the [installer][windows-msi]. - Also for [ARM64][windows-arm64-msi] and [32-bit][windows-x86-msi] PCs, or as a - [portable zip][windows-portable] that runs without installing. - With [WinGet](https://learn.microsoft.com/windows/package-manager/winget/): - `winget install bherbruck.SolidCraft`. -- **macOS:** open the [disk image][macos-dmg] and drag SolidCraft into Applications - (Apple silicon and Intel). -- **Linux:** download the [AppImage][linux-appimage], allow it to run as a program and open it. - Or install the [.deb][linux-deb] (Ubuntu, Debian, Mint) or [.rpm][linux-rpm] (Fedora, - openSUSE), or use [Flatpak](https://docs.solidcraft.io/guide/getting-started.html#linux-flatpak). - With Snap: `sudo snap install solidcraft` ([Snap Store][snap-store], or the [.snap file][linux-snap]). - For ARM64: [AppImage][linux-arm64-appimage], [.deb][linux-arm64-deb], [.rpm][linux-arm64-rpm]. +- **Windows:** the [installer][windows-msi], or `winget install bherbruck.SolidCraft`. +- **macOS:** the [disk image][macos-dmg] (Apple silicon and Intel). +- **Linux:** the [AppImage][linux-appimage], or `sudo snap install solidcraft` ([Snap Store][snap-store]). - **Web:** [try it in your browser][web-app], no install. -The downloads aren't signed yet. On Windows, if SmartScreen warns you, choose **More info**, then -**Run anyway**. On macOS, the first time, right-click SolidCraft in Applications and choose **Open**. - -**On SolidCraft 0.11 to 0.14?** Its **Update now** can't install 0.15.0 or later, because the -releases moved to a new address. Download the new version once from the links above; after that, -updating from inside SolidCraft works again ([details](https://docs.solidcraft.io/guide/updates.html#updating-from-011-to-014)). - -Older versions, checksums and other formats are on the [releases page](https://github.com/tangency-labs/solidcraft/releases). -Install details, upgrading from earlier builds and building from source are in -[Getting started](https://docs.solidcraft.io/guide/getting-started.html). - -[badge-windows]: https://img.shields.io/badge/Windows-Download-0078D6?style=for-the-badge&logo=data%3Aimage%2Fsvg%2Bxml%3Bbase64%2CPHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0id2hpdGUiPjxwYXRoIGQ9Ik0yIDJoOS41djkuNUgyek0xMi41IDJIMjJ2OS41aC05LjV6TTIgMTIuNWg5LjVWMjJIMnpNMTIuNSAxMi41SDIyVjIyaC05LjV6Ii8%2BPC9zdmc%2B -[badge-macos]: https://img.shields.io/badge/macOS-Download-333333?style=for-the-badge&logo=apple&logoColor=white -[badge-linux]: https://img.shields.io/badge/Linux-AppImage-E95420?style=for-the-badge&logo=linux&logoColor=white -[badge-snap]: https://img.shields.io/badge/Snap-Snap_Store-82BEA0?style=for-the-badge&logo=snapcraft&logoColor=white -[badge-web]: https://img.shields.io/badge/Web-Try_in_browser-2EA44F?style=for-the-badge&logo=data%3Aimage%2Fsvg%2Bxml%3Bbase64%2CPHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0ibm9uZSIgc3Ryb2tlPSJ3aGl0ZSIgc3Ryb2tlLXdpZHRoPSIyIj48Y2lyY2xlIGN4PSIxMiIgY3k9IjEyIiByPSIxMCIvPjxwYXRoIGQ9Ik0yIDEyaDIwTTEyIDJhMTUgMTUgMCAwIDEgMCAyME0xMiAyYTE1IDE1IDAgMCAwIDAgMjAiLz48L3N2Zz4%3D -[windows-msi]: https://github.com/tangency-labs/solidcraft/releases/latest/download/solidcraft-windows-x64.msi -[windows-arm64-msi]: https://github.com/tangency-labs/solidcraft/releases/latest/download/solidcraft-windows-arm64.msi -[windows-x86-msi]: https://github.com/tangency-labs/solidcraft/releases/latest/download/solidcraft-windows-x86.msi -[windows-portable]: https://github.com/tangency-labs/solidcraft/releases/latest/download/solidcraft-windows-x64-portable.zip -[macos-dmg]: https://github.com/tangency-labs/solidcraft/releases/latest/download/solidcraft-macos-universal.dmg -[linux-appimage]: https://github.com/tangency-labs/solidcraft/releases/latest/download/solidcraft-linux-x86_64.AppImage -[linux-deb]: https://github.com/tangency-labs/solidcraft/releases/latest/download/solidcraft-linux-x86_64.deb -[linux-rpm]: https://github.com/tangency-labs/solidcraft/releases/latest/download/solidcraft-linux-x86_64.rpm -[linux-arm64-appimage]: https://github.com/tangency-labs/solidcraft/releases/latest/download/solidcraft-linux-aarch64.AppImage -[linux-arm64-deb]: https://github.com/tangency-labs/solidcraft/releases/latest/download/solidcraft-linux-aarch64.deb -[linux-arm64-rpm]: https://github.com/tangency-labs/solidcraft/releases/latest/download/solidcraft-linux-aarch64.rpm -[linux-snap]: https://github.com/tangency-labs/solidcraft/releases/latest/download/solidcraft-linux-x86_64.snap -[snap-store]: https://snapcraft.io/solidcraft -[web-app]: https://solidcraft.io/app - -**Documentation:** the [SolidCraft book](https://docs.solidcraft.io/) (user guide, -developer guide and command reference; sources in [docs/book](docs/book)). - -**Community:** chat with users and contributors on [Discord](https://discord.gg/FtU4NQNVDH). - -**Status: early but usable for simple parts.** 75 of 76 public reference parts -match their analytic or FreeCAD-computed volume, area, centre of mass and bounding box -([docs/oracle.md](docs/oracle.md)); the other is a tracked bug. -These checks do not establish complete geometric or workflow equivalence. The commands SolidCraft has -are listed by area in [docs/features.md](docs/features.md); status and plans are in [ROADMAP.md](ROADMAP.md). -Open work and known bugs are in [GitHub issues](https://github.com/tangency-labs/solidcraft/issues), -and help is welcome: see [CONTRIBUTING.md](CONTRIBUTING.md). - -## Built with SolidCraft - -SELENE, a scientific rover by 0xlillith, assembling itself as the timeline plays through its 3,323 steps in SolidCraft: tub, wheels, electronics, suspension, sampling arm, solar wings, dish and camera turret - -*SELENE, a scientific rover built entirely through SolidCraft's MCP server by -[@0xlillith](https://github.com/0xlillith/solidcraft-rover): 3,323 editable timeline steps that -rebuild with no errors, replayed here at 2× speed. -[Full video](https://github.com/tangency-labs/solidcraft/raw/refs/heads/main/docs/screenshots/rover-build.mp4) -· [download the editable model](https://github.com/0xlillith/solidcraft-rover/releases/tag/v1.0.0).* +ARM64 and 32-bit builds, portable zip, .deb, .rpm, Flatpak and the other packages are on the +[downloads page](docs/downloads.md). The downloads aren't signed yet: on Windows choose +**More info**, then **Run anyway** in SmartScreen; on macOS right-click SolidCraft and choose **Open** +the first time. On SolidCraft 0.11 to 0.14, download once by hand; see +[updating](https://docs.solidcraft.io/guide/updates.html#updating-from-011-to-014). ## What works -- **Current-view DXF export** from File → Export Current View as DXF, with hidden edges - omitted or dashed, shown body placements and the current camera. See [view DXF](docs/view-dxf.md). +Early but usable for simple parts: 75 of 76 public reference parts match their analytic or +FreeCAD-computed volume, area, centre of mass and bounding box ([oracle](docs/oracle.md)); the +other is a tracked bug. -- **Sketches** on origin planes, offset planes or planar faces: lines, rectangles, circles, - arcs, polygons, slots, ellipses, fit/control splines, conics and text; construction geometry, - projection, trimming, fillets and chamfers, including corners at the origin. - New face attachments retain supported construction identities and chosen occurrences; - missing sources expose an explicit plane repair workflow. See [face attachments](docs/face-attachments.md). - Explicitly closed fit splines and closed associative offsets use periodic C2 interpolation. - Supported convex line-and-arc offsets retain their identity when an inset consumes corner - arcs, and linked extrusions follow the current boundary. Breaking the association freezes - the boundary and keeps existing extrusions usable. - Curve drawing and picking adapt together to zoom and display scale, including small circles - at Fit and sketches in placed components. -- **Constraints and dimensions** solved by our own solver. Points the constraints fix relative - to known geometry are placed exactly by construction (loci intersections and rigid-cluster - decomposition, after Owen 1991 and Fudos–Hoffmann 1997); Levenberg–Marquardt solves the rest, - and the rank of its Jacobian gives the remaining degrees of freedom. Constraints: coincident, - point on curve, horizontal/vertical, parallel, perpendicular, tangent, curvature (G2), equal, - concentric, collinear, midpoint, symmetry, fix; linear, aligned, horizontal, vertical, - point-to-line, radius, diameter, angle, arc sweep, arc length and slot length dimensions driven - by parameters. Over-constraining edits are rejected; fully constrained geometry turns black. - Dragging solves the sketch every frame and rebuilds the model once, when the drag ends. - Select a line or its two endpoints, type its dimension and press Enter to commit one undo - step; with Sketch Dimension it's D, click, type, Enter. Fit keeps sketch geometry clear of the palette and navigation controls. -- **Profiles** found automatically, including regions split by lines and holes inside outlines. - Newly captured complete adaptive boundaries retain their outer and hole source identities - when spline span counts change. Partial or ambiguous boundaries do not qualify. -- **Features** on a parametric timeline: extrude, revolve, sweep, loft, fillet/chamfer, - shell, draft, holes, threads, patterns, mirror, split, combine, move and construction geometry. - The timeline rebuilds incrementally; features can be edited, suppressed, renamed, reordered - and deleted. Supported geometry and current limitations are described in [ROADMAP.md](ROADMAP.md). - New revolves preserve symmetric and two-sided angular placement across reversed axes; - older designs retain their saved convention when reopened or edited. -- **Parameters and configurations** with unit-aware expressions (`2 * width + 5 mm`, - `angle / 2`), ordered rules, feature suppression and per-row body materials/appearances. -- **Assemblies** with nested components and occurrences, joints, motion studies, contact sets, - interference and material-aware mass properties. Recorded body transfers preserve modelling - history and world placement; 3D sketch wires retain their coordinate frames through edits. -- **Sheet metal** with flanges, hems, fold/unfold/refold, material cutouts, flat patterns, - retained shallow prismatic pockets, exact line/arc/circle DXF outlines and bend tables; - plastic enclosure features and rules. Pocket depth and side survive unfold/refold and appear - separately from through-hole outlines in the flat preview and DXF. -- **Files**: design containers (`.solidcraft`) with lossless binary mesh payloads; - plain JSON remains supported for opening, Save As and export. Desktop Open can show a saved - provisional picture from warm geometry caches while rebuilding before editing; caches never - replace the parametric design. Export to STEP (AP242 with body names, colours and - components as assemblies; revolved faces as native planes, cylinders, cones, spheres and tori), - IGES 5.3 (manifold solid B-reps with names and colours), 3MF, STL (binary/ASCII) and OBJ, and - assemblies with joints as URDF for robot simulators (docs/urdf.md); - 3MF, STL, OBJ and glTF 2.0 (`.glb`/`.gltf`, its node tree as components and its materials as - appearances) import as mesh bodies (they render, measure, move and export; solid features - need B-rep bodies). The `mesh.convert` command reconstructs supported closed constant-section parts - as parametric solids with planar and circular cylindrical faces; - STEP import (AP203/AP214/AP242 solids, assemblies, units, names, colours) and IGES import - (manifold solid B-reps, or trimmed and bounded surfaces sewn into solids) as a base feature - that later features build on — open a `.step`/`.stp`/`.igs`/`.iges` file, insert one into a - design, or drop it on the window ([docs/step-import.md](docs/step-import.md)); FreeCAD - `.FCStd` and Rhino `.3dm` solids import the same way through - [cadmpeg](https://github.com/cadmpeg/cadmpeg) in the desktop app and CLI. -- **Render:** opaque surfaces can use metal fraction, roughness and dielectric IOR in the - integrated product viewport and CPU preview PNGs. Existing simple colors remain supported. - Fixed direct lighting is a preview; HDRI, refraction and texture maps are not implemented. - See [opaque surfaces](docs/render-opaque-pbr.md). -- **Display meshes** from our own tessellation planner: each face becomes a plan of (u, v) - points and triangles that shares its edge nodes with its neighbours, so the mesh is watertight. - Facets follow the chord tolerance, the facet angle and a longest side, with cells at most 2:1 - along straight directions. Box-bounded and four-cornered faces mesh as structured grids. - Trimmed faces are cut into four-sided patches: squares around holes, butterflies in round - faces, motorcycle traces from concave corners (after Lyon et al. 2019). Each patch then meshes - as a Coons grid. Intersection edges are evaluated by Newton on both surfaces. A compute shader - evaluates the plans for the whole scene in one dispatch, with a CPU fallback when the GPU - can't build it. Planning and evaluating the 78 reference bodies takes about 65 ms, 50–65× - faster than the previous mesher. -- **Desktop app** (egui + wgpu): toolbar with workspace tabs, browser, timeline, 3D viewport with - axis view and navigation bar, sketch tools, feature dialogs, command palette, and a JSON-lines - control channel so agents and tests can drive it. - Feature errors and Help can open an editable **Create Issue** draft with relevant context - and an optional reviewed screenshot; opening GitHub does not submit the report. -- **Headless CLI** `solidcraft-cli`: run command scripts, measure (volume, area, centre of mass, - face/edge/vertex counts), export, render PNG snapshots and replay reference recipes. - A snapshot can draw a body see-through and another solid in a colour of its own, and cut - the model at a plane, so a picture shows the body a cut would remove inside the material - it meets. -- **MCP server** `solidcraft-cli mcp`: AI agents model, measure and look at parts headless or - in the running app (see below). +- **Sketches and constraints:** lines, arcs, splines, text and more, solved by our own constraint solver, with parameter-driven dimensions. +- **Features:** extrude, revolve, sweep, loft, fillet, chamfer, shell, draft, holes, threads, patterns, mirror, split and combine on an editable parametric timeline. +- **Parameters and configurations** with unit-aware expressions. +- **Assemblies** with joints, motion studies, contact sets, interference and mass properties. +- **Sheet metal** with flanges, hems, fold/unfold and flat patterns, and plastic enclosure features. +- **Files:** STEP, IGES, 3MF, STL, OBJ and glTF in and out where supported, URDF export, `.solidcraft` designs. +- **Desktop app, browser app, headless CLI and MCP server**, all running the same commands. -## Build and run +The full list is in [docs/capabilities.md](docs/capabilities.md) and [docs/features.md](docs/features.md); +status and plans are in [ROADMAP.md](ROADMAP.md). See also [what people built](docs/showcase.md), +[3D mouse support](docs/3d-mouse.md) and the [architecture](docs/architecture.md). + +## Build from source ```sh -cargo run --release -p solidcraft -- --sample # desktop app with a sample part -cargo run --release -p solidcraft-cli -- commands # the command registry +cargo run --release -p solidcraft -- --sample # desktop app with a sample part +cargo run --release -p solidcraft-cli -- commands # the command registry cargo run --release -p solidcraft-cli -- run examples/bracket.json --out bracket.step -cargo run --release -p solidcraft-cli -- snapshot examples/bracket.json --out bracket.png -cargo run --release -p solidcraft-cli -- snapshot part.solidcraft --out preview.png --tool Pin --section z=12 -cargo run --release -p solidcraft-cli -- render examples/render-studio.json --out product.png -cargo run --release -p solidcraft -- part.step # open a STEP file as a new design -cargo run --release -p solidcraft-cli -- eval part.step # measure an imported STEP file -cargo xtask ci # fmt, clippy, tests, icons, assets, layers, wasm +cargo xtask ci # fmt, clippy, tests, icons, assets, layers, wasm ``` -UI artwork changes follow the [icon specification](assets/icons/ui/STYLE_GUIDE.md). -The [included review tool](assets/icons/ui/README.md) discovers new icons and keeps -unaccepted artwork Open; run `cargo xtask icons` to check the collection. - -Windows builds: `cargo xwin build --release --target x86_64-pc-windows-msvc -p solidcraft`. - -On Windows, macOS and Linux, SolidCraft detects a connected 3D mouse through its HID multi-axis -controller interface: a 3Dconnexion SpaceNavigator or SpaceMouse, or a homemade device that -declares itself one. Move the cap to pan and zoom, and tilt or twist it to rotate the 3D view. -While editing a sketch, the cap pans and zooms without changing the sketch view. The Navigation -page in Preferences has an on/off switch, a speed control and, for each of the cap's six axes, an -invert switch and a speed for the 3D mouse. The web app reads -it too, through the browser; Firefox needs a 3DxWare setting first (see -[Getting started › 3D mouse in the browser](docs/book/src/guide/getting-started.md#3d-mouse-in-the-browser)). - -With 3DxWare on Windows, SolidCraft follows 3DxWare's profile for it when there is one, and -3DxWare's object mode (tilt to roll, twist to spin) until there is. The mouse-wheel turns that -3DxWare makes from the cap's motion are ignored, so the view doesn't zoom in steps as the cap tilts. - -On Linux SolidCraft reads the 3D mouse through `spacenavd` when that daemon runs (its socket -`/var/run/spnav.sock`), so what you set in `spnavcfg` (swapped or inverted axes, sensitivity, dead -zones) applies as it does in other programs, and no udev rule is needed. With nothing set there, -the motion is the same as without the daemon. Without `spacenavd`, SolidCraft reads `/dev/hidrawN` -directly, so the logged-in user needs access to the device. A udev rule that adds the `uaccess` -tag does that, for example -`/etc/udev/rules.d/70-3d-mouse.rules` for USB devices with 3Dconnexion's vendor id, and for its -Bluetooth ones (where `idVendor` isn't set, so the HID id is matched instead): - -``` -SUBSYSTEM=="hidraw", ATTRS{idVendor}=="256f", TAG+="uaccess" -SUBSYSTEM=="hidraw", KERNELS=="0005:256F:*", TAG+="uaccess" -``` - -Older SpaceNavigators use Logitech's vendor id `046d`, so add a rule with their product id (see -`lsusb`) instead of matching every Logitech device. A homemade device needs a rule with its own -vendor and product id. Reload with `sudo udevadm control --reload && sudo udevadm trigger`, then -replug the device. The Flatpak sandbox does not expose hidraw devices, so the 3D mouse only works -with native builds there for now. - -SolidCraft finds the axes from the device's report descriptor, so it doesn't matter how a device -lays them out: translation and rotation in separate reports (3Dconnexion's wired devices), all six -in one (its wireless ones and most homemade devices), after the buttons, or narrower than 16 bits. -Each axis is scaled from the range the descriptor declares. - -On macOS SolidCraft talks to the 3Dconnexion driver (3DxWare) when it is installed, through the -driver's client API (`crates/threedx-client`; the framework is loaded at run time, never bundled). -The driver keeps the device to itself, and sends it only to a program it can identify: SolidCraft -as an `.app` (the packaged app). Without the driver, or with its helper not running, SolidCraft reads the device through IOKit like on Windows. - -SolidCraft does not follow 3DxWare's profile on macOS. Its default is 3DxWare's object mode. - -In the browser: `cd apps/solidcraft-web && trunk build --release --public-url ./` (WebGPU, or -WebGL2 with `?webgl`; `?sample` opens the sample part). - -Agents can control the document open in a browser tab through `window.solidcraft.execute(...)` -and `window.solidcraft.request(...)`; see the [browser command API](docs/browser-api.md). - -## Scripts - -A script is a JSON list of commands, the same ones the UI runs: - -```json -{"commands": [ - {"command": "sketch.create", "params": {"plane": "XY"}}, - {"command": "sketch.rectangle.two_point", "params": {"p0": [0, 0], "p1": [40, 30]}}, - {"command": "solid.extrude", "params": {"distance": 20}}, - {"command": "solid.fillet", "params": {"edges": [[0, 0, 10]], "radius": 3}} -]} -``` +More commands, the Windows cross-build and the browser build are in [docs/building.md](docs/building.md). ## AI agents (MCP) -`solidcraft-cli mcp` is a [Model Context Protocol](https://modelcontextprotocol.io) server on -stdio. Headless it runs its own design session; with `--connect 127.0.0.1:PORT` it drives the app -started with `solidcraft --control PORT`, so you can watch the agent model. Tools: -`list_commands`, `execute`, `batch`, `inspect_design`, `measure`, `body_topology`, -`set_parameter`, `screenshot` (returns the image), `export`, `crash_reports`, `undo`, `redo`, -`new_design`, `open`, `save`. Tool calls reach files only in the open design's folder (when it lies inside your home -folder, never home itself or a hidden folder), SolidCraft's recovery folder and folders given with -`--allow-path DIR`. Claude Code: `claude mcp add solidcraft -- solidcraft-cli mcp`. Details, client -configuration and an example session: [docs/mcp.md](docs/mcp.md). +`solidcraft-cli mcp` is a [Model Context Protocol](https://modelcontextprotocol.io) server. Headless it +runs its own design session, or with `--connect` it drives the running app so you can watch. +Claude Code: `claude mcp add solidcraft -- solidcraft-cli mcp`. Tools, access rules and an +example session: [docs/mcp.md](docs/mcp.md). -## Architecture +## Scripts - -| Layer | Crates | Role | -|---|---|---| -| L0 | `geom` | vectors, planes, profiles, meshes and their measures | -| L1 | `sketch`, `kernel`, `render` | constraint solver and profiles; the B-rep kernel boundary (truck); view math and the headless scene description | -| L2 | `doc` | parameters, expressions, the feature timeline and its incremental evaluation | -| L3 | `io` | design files, STL/OBJ/STEP/3MF export, STEP and 3MF/STL/OBJ/glTF import features | -| L4 | `engine` | the session and the command registry (everything is a command) | -| L5 | `gpu`, `ui-egui`, `mcp` | compute-shader evaluation of display tessellation plans; the swappable desktop front end; the MCP server (headless or bridged to the app) | -| apps | `solidcraft`, `solidcraft-cli` | desktop app, headless CLI | - +A script is a JSON list of the same commands the UI runs, executed with `solidcraft-cli run`. +Format and example: [docs/scripts.md](docs/scripts.md). Pages can also be driven through the +[browser command API](docs/browser-api.md). ## Contributing -SolidCraft uses a familiar parametric CAD workflow: constrained -sketches, solid features, an editable timeline, parameters and assemblies. See the -[roadmap](ROADMAP.md) for supported operations and current limitations. - -See [CONTRIBUTING.md](CONTRIBUTING.md): how to build and test, the code map, the clean-room -and licence rules, and where help is wanted most. +Help is welcome. [CONTRIBUTING.md](CONTRIBUTING.md) covers how to build and test, the code map, +the clean-room and licence rules, and where help is wanted most. Open work is in +[GitHub issues](https://github.com/tangency-labs/solidcraft/issues); chat is on +[Discord](https://discord.gg/FtU4NQNVDH). ## Sponsors @@ -337,3 +121,14 @@ SolidCraft is independent. Behaviour is designed from public documentation, gene conventions and user feedback. Reference tests use analytic values and open-source tools. SolidCraft is not affiliated with, sponsored by or endorsed by Autodesk. Autodesk and Fusion are trademarks of Autodesk, Inc. + +[badge-windows]: https://img.shields.io/badge/Windows-Download-0078D6?style=for-the-badge&logo=data%3Aimage%2Fsvg%2Bxml%3Bbase64%2CPHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0id2hpdGUiPjxwYXRoIGQ9Ik0yIDJoOS41djkuNUgyek0xMi41IDJIMjJ2OS41aC05LjV6TTIgMTIuNWg5LjVWMjJIMnpNMTIuNSAxMi41SDIyVjIyaC05LjV6Ii8%2BPC9zdmc%2B +[badge-macos]: https://img.shields.io/badge/macOS-Download-333333?style=for-the-badge&logo=apple&logoColor=white +[badge-linux]: https://img.shields.io/badge/Linux-AppImage-E95420?style=for-the-badge&logo=linux&logoColor=white +[badge-snap]: https://img.shields.io/badge/Snap-Snap_Store-82BEA0?style=for-the-badge&logo=snapcraft&logoColor=white +[badge-web]: https://img.shields.io/badge/Web-Try_in_browser-2EA44F?style=for-the-badge&logo=data%3Aimage%2Fsvg%2Bxml%3Bbase64%2CPHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0ibm9uZSIgc3Ryb2tlPSJ3aGl0ZSIgc3Ryb2tlLXdpZHRoPSIyIj48Y2lyY2xlIGN4PSIxMiIgY3k9IjEyIiByPSIxMCIvPjxwYXRoIGQ9Ik0yIDEyaDIwTTEyIDJhMTUgMTUgMCAwIDEgMCAyME0xMiAyYTE1IDE1IDAgMCAwIDAgMjAiLz48L3N2Zz4%3D +[windows-msi]: https://github.com/tangency-labs/solidcraft/releases/latest/download/solidcraft-windows-x64.msi +[macos-dmg]: https://github.com/tangency-labs/solidcraft/releases/latest/download/solidcraft-macos-universal.dmg +[linux-appimage]: https://github.com/tangency-labs/solidcraft/releases/latest/download/solidcraft-linux-x86_64.AppImage +[snap-store]: https://snapcraft.io/solidcraft +[web-app]: https://solidcraft.io/app diff --git a/docs/3d-mouse.md b/docs/3d-mouse.md new file mode 100644 index 000000000..383da9294 --- /dev/null +++ b/docs/3d-mouse.md @@ -0,0 +1,46 @@ +# 3D mouse + +On Windows, macOS and Linux, SolidCraft detects a connected 3D mouse through its HID multi-axis +controller interface: a 3Dconnexion SpaceNavigator or SpaceMouse, or a homemade device that +declares itself one. Move the cap to pan and zoom, and tilt or twist it to rotate the 3D view. +While editing a sketch, the cap pans and zooms without changing the sketch view. The Navigation +page in Preferences has an on/off switch, a speed control and, for each of the cap's six axes, an +invert switch and a speed for the 3D mouse. The web app reads +it too, through the browser; Firefox needs a 3DxWare setting first (see +[Getting started › 3D mouse in the browser](book/src/guide/getting-started.md#3d-mouse-in-the-browser)). + +With 3DxWare on Windows, SolidCraft follows 3DxWare's profile for it when there is one, and +3DxWare's object mode (tilt to roll, twist to spin) until there is. The mouse-wheel turns that +3DxWare makes from the cap's motion are ignored, so the view doesn't zoom in steps as the cap tilts. + +On Linux SolidCraft reads the 3D mouse through `spacenavd` when that daemon runs (its socket +`/var/run/spnav.sock`), so what you set in `spnavcfg` (swapped or inverted axes, sensitivity, dead +zones) applies as it does in other programs, and no udev rule is needed. With nothing set there, +the motion is the same as without the daemon. Without `spacenavd`, SolidCraft reads `/dev/hidrawN` +directly, so the logged-in user needs access to the device. A udev rule that adds the `uaccess` +tag does that, for example +`/etc/udev/rules.d/70-3d-mouse.rules` for USB devices with 3Dconnexion's vendor id, and for its +Bluetooth ones (where `idVendor` isn't set, so the HID id is matched instead): + +``` +SUBSYSTEM=="hidraw", ATTRS{idVendor}=="256f", TAG+="uaccess" +SUBSYSTEM=="hidraw", KERNELS=="0005:256F:*", TAG+="uaccess" +``` + +Older SpaceNavigators use Logitech's vendor id `046d`, so add a rule with their product id (see +`lsusb`) instead of matching every Logitech device. A homemade device needs a rule with its own +vendor and product id. Reload with `sudo udevadm control --reload && sudo udevadm trigger`, then +replug the device. The Flatpak sandbox does not expose hidraw devices, so the 3D mouse only works +with native builds there for now. + +SolidCraft finds the axes from the device's report descriptor, so it doesn't matter how a device +lays them out: translation and rotation in separate reports (3Dconnexion's wired devices), all six +in one (its wireless ones and most homemade devices), after the buttons, or narrower than 16 bits. +Each axis is scaled from the range the descriptor declares. + +On macOS SolidCraft talks to the 3Dconnexion driver (3DxWare) when it is installed, through the +driver's client API (`crates/threedx-client`; the framework is loaded at run time, never bundled). +The driver keeps the device to itself, and sends it only to a program it can identify: SolidCraft +as an `.app` (the packaged app). Without the driver, or with its helper not running, SolidCraft reads the device through IOKit like on Windows. + +SolidCraft does not follow 3DxWare's profile on macOS. Its default is 3DxWare's object mode. diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 000000000..d0e93cc62 --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,13 @@ +# Architecture + + +| Layer | Crates | Role | +|---|---|---| +| L0 | `geom` | vectors, planes, profiles, meshes and their measures | +| L1 | `sketch`, `kernel`, `render` | constraint solver and profiles; the B-rep kernel boundary (truck); view math and the headless scene description | +| L2 | `doc` | parameters, expressions, the feature timeline and its incremental evaluation | +| L3 | `io` | design files, STL/OBJ/STEP/3MF export, STEP and 3MF/STL/OBJ/glTF import features | +| L4 | `engine` | the session and the command registry (everything is a command) | +| L5 | `gpu`, `ui-egui`, `mcp` | compute-shader evaluation of display tessellation plans; the swappable desktop front end; the MCP server (headless or bridged to the app) | +| apps | `solidcraft`, `solidcraft-cli` | desktop app, headless CLI | + diff --git a/docs/book/src/dev/architecture.md b/docs/book/src/dev/architecture.md index 61912142a..72f03d2c6 100644 --- a/docs/book/src/dev/architecture.md +++ b/docs/book/src/dev/architecture.md @@ -3,7 +3,7 @@ SolidCraft is a Cargo workspace in layers. A crate only depends on crates in lower layers, and `cargo xtask layers` fails the build otherwise. -{{#include ../../../../README.md:architecture}} +{{#include ../../../architecture.md:architecture}} The web app, `apps/solidcraft-web`, is the desktop front end compiled to wasm with [trunk](https://trunkrs.dev). `xtask` holds the repository's own tooling: `cargo xtask ci`, diff --git a/docs/building.md b/docs/building.md new file mode 100644 index 000000000..3548b5d9f --- /dev/null +++ b/docs/building.md @@ -0,0 +1,28 @@ +# Building and running + +```sh +cargo run --release -p solidcraft -- --sample # desktop app with a sample part +cargo run --release -p solidcraft-cli -- commands # the command registry +cargo run --release -p solidcraft-cli -- run examples/bracket.json --out bracket.step +cargo run --release -p solidcraft-cli -- snapshot examples/bracket.json --out bracket.png +cargo run --release -p solidcraft-cli -- snapshot part.solidcraft --out preview.png --tool Pin --section z=12 +cargo run --release -p solidcraft-cli -- render examples/render-studio.json --out product.png +cargo run --release -p solidcraft -- part.step # open a STEP file as a new design +cargo run --release -p solidcraft-cli -- eval part.step # measure an imported STEP file +cargo xtask ci # fmt, clippy, tests, icons, assets, layers, wasm +``` + +UI artwork changes follow the [icon specification](../assets/icons/ui/STYLE_GUIDE.md). +The [included review tool](../assets/icons/ui/README.md) discovers new icons and keeps +unaccepted artwork Open; run `cargo xtask icons` to check the collection. + +Windows builds: `cargo xwin build --release --target x86_64-pc-windows-msvc -p solidcraft`. + + +In the browser: `cd apps/solidcraft-web && trunk build --release --public-url ./` (WebGPU, or +WebGL2 with `?webgl`; `?sample` opens the sample part). + +Agents can control the document open in a browser tab through `window.solidcraft.execute(...)` +and `window.solidcraft.request(...)`; see the [browser command API](browser-api.md). + +See [CONTRIBUTING](../CONTRIBUTING.md) for the test and review workflow. diff --git a/docs/capabilities.md b/docs/capabilities.md new file mode 100644 index 000000000..00c98dc42 --- /dev/null +++ b/docs/capabilities.md @@ -0,0 +1,99 @@ +# What works + +The full feature summary, moved out of the README. The commands by area are in [features.md](features.md); status and plans are in [ROADMAP](../ROADMAP.md). + +**Status: early but usable for simple parts.** 75 of 76 public reference parts +match their analytic or FreeCAD-computed volume, area, centre of mass and bounding box +([oracle.md](oracle.md)); the other is a tracked bug. +These checks do not establish complete geometric or workflow equivalence. The commands SolidCraft has +are listed by area in [features.md](features.md); status and plans are in [ROADMAP.md](../ROADMAP.md). +Open work and known bugs are in [GitHub issues](https://github.com/tangency-labs/solidcraft/issues), +and help is welcome: see [CONTRIBUTING.md](../CONTRIBUTING.md). + + +- **Current-view DXF export** from File → Export Current View as DXF, with hidden edges + omitted or dashed, shown body placements and the current camera. See [view DXF](view-dxf.md). + +- **Sketches** on origin planes, offset planes or planar faces: lines, rectangles, circles, + arcs, polygons, slots, ellipses, fit/control splines, conics and text; construction geometry, + projection, trimming, fillets and chamfers, including corners at the origin. + New face attachments retain supported construction identities and chosen occurrences; + missing sources expose an explicit plane repair workflow. See [face attachments](face-attachments.md). + Explicitly closed fit splines and closed associative offsets use periodic C2 interpolation. + Supported convex line-and-arc offsets retain their identity when an inset consumes corner + arcs, and linked extrusions follow the current boundary. Breaking the association freezes + the boundary and keeps existing extrusions usable. + Curve drawing and picking adapt together to zoom and display scale, including small circles + at Fit and sketches in placed components. +- **Constraints and dimensions** solved by our own solver. Points the constraints fix relative + to known geometry are placed exactly by construction (loci intersections and rigid-cluster + decomposition, after Owen 1991 and Fudos–Hoffmann 1997); Levenberg–Marquardt solves the rest, + and the rank of its Jacobian gives the remaining degrees of freedom. Constraints: coincident, + point on curve, horizontal/vertical, parallel, perpendicular, tangent, curvature (G2), equal, + concentric, collinear, midpoint, symmetry, fix; linear, aligned, horizontal, vertical, + point-to-line, radius, diameter, angle, arc sweep, arc length and slot length dimensions driven + by parameters. Over-constraining edits are rejected; fully constrained geometry turns black. + Dragging solves the sketch every frame and rebuilds the model once, when the drag ends. + Select a line or its two endpoints, type its dimension and press Enter to commit one undo + step; with Sketch Dimension it's D, click, type, Enter. Fit keeps sketch geometry clear of the palette and navigation controls. +- **Profiles** found automatically, including regions split by lines and holes inside outlines. + Newly captured complete adaptive boundaries retain their outer and hole source identities + when spline span counts change. Partial or ambiguous boundaries do not qualify. +- **Features** on a parametric timeline: extrude, revolve, sweep, loft, fillet/chamfer, + shell, draft, holes, threads, patterns, mirror, split, combine, move and construction geometry. + The timeline rebuilds incrementally; features can be edited, suppressed, renamed, reordered + and deleted. Supported geometry and current limitations are described in [ROADMAP.md](../ROADMAP.md). + New revolves preserve symmetric and two-sided angular placement across reversed axes; + older designs retain their saved convention when reopened or edited. +- **Parameters and configurations** with unit-aware expressions (`2 * width + 5 mm`, + `angle / 2`), ordered rules, feature suppression and per-row body materials/appearances. +- **Assemblies** with nested components and occurrences, joints, motion studies, contact sets, + interference and material-aware mass properties. Recorded body transfers preserve modelling + history and world placement; 3D sketch wires retain their coordinate frames through edits. +- **Sheet metal** with flanges, hems, fold/unfold/refold, material cutouts, flat patterns, + retained shallow prismatic pockets, exact line/arc/circle DXF outlines and bend tables; + plastic enclosure features and rules. Pocket depth and side survive unfold/refold and appear + separately from through-hole outlines in the flat preview and DXF. +- **Files**: design containers (`.solidcraft`) with lossless binary mesh payloads; + plain JSON remains supported for opening, Save As and export. Desktop Open can show a saved + provisional picture from warm geometry caches while rebuilding before editing; caches never + replace the parametric design. Export to STEP (AP242 with body names, colours and + components as assemblies; revolved faces as native planes, cylinders, cones, spheres and tori), + IGES 5.3 (manifold solid B-reps with names and colours), 3MF, STL (binary/ASCII) and OBJ, and + assemblies with joints as URDF for robot simulators (urdf.md); + 3MF, STL, OBJ and glTF 2.0 (`.glb`/`.gltf`, its node tree as components and its materials as + appearances) import as mesh bodies (they render, measure, move and export; solid features + need B-rep bodies). The `mesh.convert` command reconstructs supported closed constant-section parts + as parametric solids with planar and circular cylindrical faces; + STEP import (AP203/AP214/AP242 solids, assemblies, units, names, colours) and IGES import + (manifold solid B-reps, or trimmed and bounded surfaces sewn into solids) as a base feature + that later features build on — open a `.step`/`.stp`/`.igs`/`.iges` file, insert one into a + design, or drop it on the window ([docs/step-import.md](step-import.md)); FreeCAD + `.FCStd` and Rhino `.3dm` solids import the same way through + [cadmpeg](https://github.com/cadmpeg/cadmpeg) in the desktop app and CLI. +- **Render:** opaque surfaces can use metal fraction, roughness and dielectric IOR in the + integrated product viewport and CPU preview PNGs. Existing simple colors remain supported. + Fixed direct lighting is a preview; HDRI, refraction and texture maps are not implemented. + See [opaque surfaces](render-opaque-pbr.md). +- **Display meshes** from our own tessellation planner: each face becomes a plan of (u, v) + points and triangles that shares its edge nodes with its neighbours, so the mesh is watertight. + Facets follow the chord tolerance, the facet angle and a longest side, with cells at most 2:1 + along straight directions. Box-bounded and four-cornered faces mesh as structured grids. + Trimmed faces are cut into four-sided patches: squares around holes, butterflies in round + faces, motorcycle traces from concave corners (after Lyon et al. 2019). Each patch then meshes + as a Coons grid. Intersection edges are evaluated by Newton on both surfaces. A compute shader + evaluates the plans for the whole scene in one dispatch, with a CPU fallback when the GPU + can't build it. Planning and evaluating the 78 reference bodies takes about 65 ms, 50–65× + faster than the previous mesher. +- **Desktop app** (egui + wgpu): toolbar with workspace tabs, browser, timeline, 3D viewport with + axis view and navigation bar, sketch tools, feature dialogs, command palette, and a JSON-lines + control channel so agents and tests can drive it. + Feature errors and Help can open an editable **Create Issue** draft with relevant context + and an optional reviewed screenshot; opening GitHub does not submit the report. +- **Headless CLI** `solidcraft-cli`: run command scripts, measure (volume, area, centre of mass, + face/edge/vertex counts), export, render PNG snapshots and replay reference recipes. + A snapshot can draw a body see-through and another solid in a colour of its own, and cut + the model at a plane, so a picture shows the body a cut would remove inside the material + it meets. +- **MCP server** `solidcraft-cli mcp`: AI agents model, measure and look at parts headless or + in the running app (see below). diff --git a/docs/downloads.md b/docs/downloads.md new file mode 100644 index 000000000..c784b6cbe --- /dev/null +++ b/docs/downloads.md @@ -0,0 +1,44 @@ +# Downloads + +Every platform and package. The links point at the latest release. + +- **Windows:** download and run the [installer][windows-msi]. + Also for [ARM64][windows-arm64-msi] and [32-bit][windows-x86-msi] PCs, or as a + [portable zip][windows-portable] that runs without installing. + With [WinGet](https://learn.microsoft.com/windows/package-manager/winget/): + `winget install bherbruck.SolidCraft`. +- **macOS:** open the [disk image][macos-dmg] and drag SolidCraft into Applications + (Apple silicon and Intel). +- **Linux:** download the [AppImage][linux-appimage], allow it to run as a program and open it. + Or install the [.deb][linux-deb] (Ubuntu, Debian, Mint) or [.rpm][linux-rpm] (Fedora, + openSUSE), or use [Flatpak](https://docs.solidcraft.io/guide/getting-started.html#linux-flatpak). + With Snap: `sudo snap install solidcraft` ([Snap Store][snap-store], or the [.snap file][linux-snap]). + For ARM64: [AppImage][linux-arm64-appimage], [.deb][linux-arm64-deb], [.rpm][linux-arm64-rpm]. +- **Web:** [try it in your browser][web-app], no install. + + +The downloads aren't signed yet. On Windows, if SmartScreen warns you, choose **More info**, then +**Run anyway**. On macOS, the first time, right-click SolidCraft in Applications and choose **Open**. + +**On SolidCraft 0.11 to 0.14?** Its **Update now** can't install 0.15.0 or later, because the +releases moved to a new address. Download the new version once from the links above; after that, +updating from inside SolidCraft works again ([details](https://docs.solidcraft.io/guide/updates.html#updating-from-011-to-014)). + +Older versions, checksums and other formats are on the [releases page](https://github.com/tangency-labs/solidcraft/releases). +Install details, upgrading from earlier builds and building from source are in + +[Getting started](https://docs.solidcraft.io/guide/getting-started.html). +[windows-msi]: https://github.com/tangency-labs/solidcraft/releases/latest/download/solidcraft-windows-x64.msi +[windows-arm64-msi]: https://github.com/tangency-labs/solidcraft/releases/latest/download/solidcraft-windows-arm64.msi +[windows-x86-msi]: https://github.com/tangency-labs/solidcraft/releases/latest/download/solidcraft-windows-x86.msi +[windows-portable]: https://github.com/tangency-labs/solidcraft/releases/latest/download/solidcraft-windows-x64-portable.zip +[macos-dmg]: https://github.com/tangency-labs/solidcraft/releases/latest/download/solidcraft-macos-universal.dmg +[linux-appimage]: https://github.com/tangency-labs/solidcraft/releases/latest/download/solidcraft-linux-x86_64.AppImage +[linux-deb]: https://github.com/tangency-labs/solidcraft/releases/latest/download/solidcraft-linux-x86_64.deb +[linux-rpm]: https://github.com/tangency-labs/solidcraft/releases/latest/download/solidcraft-linux-x86_64.rpm +[linux-arm64-appimage]: https://github.com/tangency-labs/solidcraft/releases/latest/download/solidcraft-linux-aarch64.AppImage +[linux-arm64-deb]: https://github.com/tangency-labs/solidcraft/releases/latest/download/solidcraft-linux-aarch64.deb +[linux-arm64-rpm]: https://github.com/tangency-labs/solidcraft/releases/latest/download/solidcraft-linux-aarch64.rpm +[linux-snap]: https://github.com/tangency-labs/solidcraft/releases/latest/download/solidcraft-linux-x86_64.snap +[snap-store]: https://snapcraft.io/solidcraft +[web-app]: https://solidcraft.io/app diff --git a/docs/scripts.md b/docs/scripts.md new file mode 100644 index 000000000..fdaa8105a --- /dev/null +++ b/docs/scripts.md @@ -0,0 +1,15 @@ +# Scripts + + +A script is a JSON list of commands, the same ones the UI runs: + +```json +{"commands": [ + {"command": "sketch.create", "params": {"plane": "XY"}}, + {"command": "sketch.rectangle.two_point", "params": {"p0": [0, 0], "p1": [40, 30]}}, + {"command": "solid.extrude", "params": {"distance": 20}}, + {"command": "solid.fillet", "params": {"edges": [[0, 0, 10]], "radius": 3}} +]} +``` + +Run one with `solidcraft-cli run script.json --out part.step`; see [building](building.md) and the [command list](features.md). diff --git a/docs/showcase.md b/docs/showcase.md new file mode 100644 index 000000000..95907585a --- /dev/null +++ b/docs/showcase.md @@ -0,0 +1,9 @@ +# Built with SolidCraft + +SELENE, a scientific rover by 0xlillith, assembling itself as the timeline plays through its 3,323 steps in SolidCraft: tub, wheels, electronics, suspension, sampling arm, solar wings, dish and camera turret + +*SELENE, a scientific rover built entirely through SolidCraft's MCP server by +[@0xlillith](https://github.com/0xlillith/solidcraft-rover): 3,323 editable timeline steps that +rebuild with no errors, replayed here at 2× speed. +[Full video](https://github.com/tangency-labs/solidcraft/raw/refs/heads/main/screenshots/rover-build.mp4) +· [download the editable model](https://github.com/0xlillith/solidcraft-rover/releases/tag/v1.0.0).* From 98c30d28f92bb52fc0ea720202e61ca2f686cf28 Mon Sep 17 00:00:00 2001 From: SS-EN <84559909+SS-EN@users.noreply.github.com> Date: Mon, 19 Oct 2026 17:29:40 -0400 Subject: [PATCH 124/225] Joints: a replaced motion link keeps the driven joint where it is; links count in dof (#2898) Thanks @SS-EN. --- crates/doc/src/joints.rs | 86 +++++++++- crates/engine/src/cmd/joints.rs | 22 +-- .../engine/src/cmd/joints_coupling_tests.rs | 151 +++++++++++++++++- docs/book/src/guide/assemblies.md | 7 +- 4 files changed, 246 insertions(+), 20 deletions(-) diff --git a/crates/doc/src/joints.rs b/crates/doc/src/joints.rs index dada884a1..7f26578f4 100644 --- a/crates/doc/src/joints.rs +++ b/crates/doc/src/joints.rs @@ -846,7 +846,10 @@ pub struct Solution { pub conflicts: Vec<(u64, String, String)>, /// Joints that could not be applied (bad origin…): (joint id, name, why). pub errors: Vec<(u64, String, String)>, - /// Remaining degrees of freedom per occurrence (6 = free, 0 = fixed). + /// Remaining degrees of freedom per occurrence (6 = free, 0 = fixed): how many independent + /// values still move it, from the fixed occurrences, with loops kept closed and a value a + /// motion link sets moving with the values its link chain starts from (a driven gear has its + /// driving gear's one, a screw's travel its turn's). pub dof: BTreeMap, /// Occurrences fixed in place (grounded, or the root's). pub fixed: Vec, @@ -1043,6 +1046,46 @@ fn link_chains(asm: &Assembly, tree: &Tree, around: &BTreeSet, linked: &BTr (feeds, starts) } +/// The values that move each value a motion link sets: the values its link chain starts from, +/// which no link sets (none for a chain that comes back round on itself, which only a hand-edited +/// design has). A driven gear's turn is its driving gear's: one degree of freedom, not two. +fn link_sources(asm: &Assembly) -> BTreeMap<(u64, usize), BTreeSet<(u64, usize)>> { + let mut into: BTreeMap<(u64, usize), Vec<(u64, usize)>> = BTreeMap::new(); + for l in &asm.links { + into.entry((l.b, l.ib)).or_default().push((l.a, l.ia)); + } + let mut sources = BTreeMap::new(); + if into.is_empty() { + return sources; + } + // A link from a value its joint doesn't have (a hand-edited design) moves nothing. + let real: BTreeSet<(u64, usize)> = asm.joints.iter().flat_map(|j| (0..j.kind.dofs().len()).map(|i| (j.id, i))).collect(); + for &v in into.keys() { + // Back along the links, as far as a link chain carries a value (`MAX_LINK_PASSES`). + let (mut from, mut seen) = (BTreeSet::new(), BTreeSet::from([v])); + let mut frontier = vec![v]; + for _ in 0..MAX_LINK_PASSES { + let mut next = Vec::new(); + for w in frontier.iter().filter_map(|w| into.get(w)).flatten() { + if !seen.insert(*w) { + continue; + } + if into.contains_key(w) { + next.push(*w); + } else if real.contains(w) { + from.insert(*w); + } + } + if next.is_empty() { + break; + } + frontier = next; + } + sources.insert(v, from); + } + sources +} + /// The held values among `touches` that move: (joint, index, from, to), `from` within the /// joint's limits. A suppressed joint still sets values through its motion links. fn held_moves(asm: &Assembly, held: &Held, touches: &BTreeSet<(u64, usize)>, vals: &Values) -> Vec<(u64, usize, f64, f64)> { @@ -1725,6 +1768,14 @@ fn build<'a>(doc: &'a Document, st: &ModelState, vals: &Values, sol: &mut Soluti Tree { joints: asm.joints.iter().map(|j| (j.id, j)).collect(), frames, fixed: placed.clone(), parent: BTreeMap::new(), order: Vec::new() }; let mut used: BTreeSet = BTreeSet::new(); let mut queue: VecDeque = placed.keys().copied().collect(); + // An occurrence's degrees of freedom are the distinct values that move it: those of the + // joints on its path, a value a motion link sets standing for the values its link chain + // starts from (a driven gear turns with its driving gear's one value). Kept per occurrence as + // a count of the values no link reads or sets, which no other path value can repeat, and the + // set of the ones that may be repeated (links' sources). + let sources = link_sources(asm); + let shared: BTreeSet<(u64, usize)> = sources.values().flatten().copied().collect(); + let mut moved_by: BTreeMap)> = BTreeMap::new(); // The joints at each occurrence, in the joints' order (a large assembly is not walked joint by // joint for every occurrence). let mut at: BTreeMap> = BTreeMap::new(); @@ -1755,7 +1806,18 @@ fn build<'a>(doc: &'a Document, st: &ModelState, vals: &Values, sol: &mut Soluti placed.insert(other, m); tree.parent.insert(other, (occ, j.id, from_a)); tree.order.push(other); - dof.insert(other, dof.get(&occ).copied().unwrap_or(0) + j.kind.dofs().len()); + let (mut own, mut common) = moved_by.get(&occ).cloned().unwrap_or_default(); + for v in (0..j.kind.dofs().len()).map(|i| (j.id, i)) { + match sources.get(&v) { + Some(from) => common.extend(from.iter().copied()), + None if shared.contains(&v) => { + common.insert(v); + } + None => own += 1, + } + } + dof.insert(other, own + common.len()); + moved_by.insert(other, (own, common)); queue.push_back(other); } } @@ -1892,6 +1954,26 @@ mod tests { Assembly { joints, links, ..Assembly::default() } } + /// A linked value moves with the free value its chain starts from, however the chain is + /// stored; a chain that comes back round on itself, or a link from a value its joint lacks + /// (hand-edited designs), moves it with nothing. + #[test] + fn linked_values_move_with_their_chains_start() { + let mut asm = chain(5, 0.0); + let sources = link_sources(&asm); + for b in 2..=5 { + assert_eq!(sources.get(&(b, 0)), Some(&BTreeSet::from([(1, 0)])), "J{b}: {sources:?}"); + } + assert!(!sources.contains_key(&(1, 0))); + let link = |a: u64, ia: usize, b: u64| MotionLink { a, ia, b, ib: 0, ratio: 1.0, offset: 0.0, coupling: None, lift: Vec::new() }; + asm.links.push(link(5, 0, 1)); + assert!(link_sources(&asm).values().all(BTreeSet::is_empty), "{:?}", link_sources(&asm)); + let mut asm = chain(2, 0.0); + asm.links = vec![link(1, 7, 2)]; + assert_eq!(link_sources(&asm).get(&(2, 0)), Some(&BTreeSet::new())); + assert!(link_sources(&Assembly::default()).is_empty()); + } + /// Links carry a value down a chain stored from its end, each linked value within its limits /// as it is set, and applying them again changes nothing. #[test] diff --git a/crates/engine/src/cmd/joints.rs b/crates/engine/src/cmd/joints.rs index d6d1fc559..6bfccac5d 100644 --- a/crates/engine/src/cmd/joints.rs +++ b/crates/engine/src/cmd/joints.rs @@ -53,21 +53,23 @@ pub static COMMANDS: &[CommandSpec] = &[ "a, b: joints that turn (revolute), b driven by a; ra, rb: the gears' pitch radii (or tooth counts): mm, an expression, or \ {circle: [x,y,z], occurrence?}: the round face there, its radius (read again whenever the design changes, so the ratio follows \ edits); internal?: bool (one is a ring gear: both turn the same way; by default b turns the other way); reverse?: bool; \ - link?: index (replace that motion link) → link, ratio (b's degrees per a's); b keeps where it is", + link?: index (replace that motion link) → link, ratio (b's degrees per a's); b keeps where it is, also when the link replaces \ + another (at the current pose)", ), CommandSpec::new("joint.rack_pinion", "Rack and Pinion", rack_pinion).at("SOLID", "ASSEMBLE").icon("rack_pinion").params( "a, b: a joint that turns (revolute: the pinion) and one that slides (slider: the rack), in either order, b driven by a; \ radius: the pinion's pitch radius (mm, an expression, or {circle: [x,y,z], occurrence?}): the rack travels radius × the turn in \ radians; reverse?: bool; link?: index (replace that motion link) → link, ratio (mm per degree, or degrees per mm); b keeps \ - where it is", + where it is, also when the link replaces another (at the current pose)", ), CommandSpec::new("joint.screw", "Screw", screw).at("SOLID", "ASSEMBLE").icon("screw").params( "joint: a cylindrical joint (its turn drives its travel) | a, b: a joint that turns and one that slides, b driven by a; pitch: \ travel per turn (mm or an expression); reverse?: bool (a left-hand thread); link?: index (replace that motion link) → link, \ - ratio (mm per degree, or degrees per mm); b keeps where it is", + ratio (mm per degree, or degrees per mm); b keeps where it is, also when the link replaces another (at the current \ + pose)", ), CommandSpec::new("joint.cam", "Cam", cam_cmd).at("SOLID", "ASSEMBLE").icon("cam").params( - "a: the cam's joint (revolute); b: the follower's joint, a slider (a translating follower) or a revolute (an oscillating one), b driven by a; profile: {sketch: id|name, index?: the profile (default: the largest)} | {edges: [[x,y,z]…] (points on edges of the cam's bodies forming one closed loop, world), occurrence?}: the cam's outline, in a plane square to its axis, read again whenever the design changes; follower?: knife|roller|flat (default knife; flat: a face square to a slider's line); radius?: the roller's radius (mm, an expression or {circle: [x,y,z], occurrence?}: the roller's round face, which is its tip too); tip?: a joint origin where the follower touches: its knife's point or its roller's centre, such as {circle: [x,y,z]} on the roller (needed for an oscillating follower; a translating one's line runs through it, by default along its slider's axis); flip?: bool (ride the cam from the other side than the one the follower is on now); link?: index (replace that motion link) → link, lift: {min, max, rise, unit} (b's travel over a turn of the cam), reverse (the side it rides from), follower_offset (mm: how far a translating follower's line passes from the cam's axis); b keeps where it is", + "a: the cam's joint (revolute); b: the follower's joint, a slider (a translating follower) or a revolute (an oscillating one), b driven by a; profile: {sketch: id|name, index?: the profile (default: the largest)} | {edges: [[x,y,z]…] (points on edges of the cam's bodies forming one closed loop, world), occurrence?}: the cam's outline, in a plane square to its axis, read again whenever the design changes; follower?: knife|roller|flat (default knife; flat: a face square to a slider's line); radius?: the roller's radius (mm, an expression or {circle: [x,y,z], occurrence?}: the roller's round face, which is its tip too); tip?: a joint origin where the follower touches: its knife's point or its roller's centre, such as {circle: [x,y,z]} on the roller (needed for an oscillating follower; a translating one's line runs through it, by default along its slider's axis); flip?: bool (ride the cam from the other side than the one the follower is on now); link?: index (replace that motion link) → link, lift: {min, max, rise, unit} (b's travel over a turn of the cam), reverse (the side it rides from), follower_offset (mm: how far a translating follower's line passes from the cam's axis); b keeps where it is, also when the link replaces another (at the current pose)", ), CommandSpec::new("joint.limits", "Joint Limits", limits).icon("joint").params("joint; index?: value index (default 0); min?, max? (omit both to clear)"), CommandSpec::new("joint.edit", "Edit Joint", edit) @@ -1092,7 +1094,8 @@ fn cam_profile(s: &Session, p: &Value, cmd: &str) -> Result { } /// Add a coupling's motion link, or put it in place of link `link`: its ratio worked out from its -/// sizes, a new link's offset leaving b where it is (the teeth mesh as they are modelled). +/// sizes, its offset leaving b where it is (the teeth mesh as they are now), for a new link and +/// one put in place of another alike. fn couple(s: &mut Session, p: &Value, cmd: &str, mut l: MotionLink) -> Result { let links = &s.doc.assembly.links; let replace = match p.get("link") { @@ -1124,11 +1127,10 @@ fn couple(s: &mut Session, p: &Value, cmd: &str, mut l: MotionLink) -> Result old.offset, - None => value(l.b, l.ib) - MotionLink { offset: 0.0, ..l.clone() }.follow(value(l.a, l.ia)), - }; + // New or put in place of another (turned the other way, a ring gear now), b keeps where it + // is: the gears stay in mesh at the pose they are in. (A radius edited in the design keeps + // the offset instead, so the gears turn from where they meshed when they were coupled.) + l.offset = value(l.b, l.ib) - MotionLink { offset: 0.0, ..l.clone() }.follow(value(l.a, l.ia)); if !l.offset.is_finite() { return Err(bad(cmd, "the coupling gives the driven joint no value where it is")); } diff --git a/crates/engine/src/cmd/joints_coupling_tests.rs b/crates/engine/src/cmd/joints_coupling_tests.rs index afdbb67e6..f817150b5 100644 --- a/crates/engine/src/cmd/joints_coupling_tests.rs +++ b/crates/engine/src/cmd/joints_coupling_tests.rs @@ -19,10 +19,15 @@ fn close_to(got: f64, want: f64) -> bool { /// A round disc (a gear's pitch circle) of radius `r` about a vertical axis through (x, 0), 5 mm /// thick, in a component of its own, on a revolute joint to the grounded base. fn disc(s: &mut Session, name: &str, x: f64, r: &str) { + loose_disc(s, name, x, r); + pin(s, "revolute", name, "Base", name, Vec3::new(x, 0.0, 0.0), Vec3::Z); +} + +/// The disc alone, on no joint. +fn loose_disc(s: &mut Session, name: &str, x: f64, r: &str) { run(s, "component.activate", json!({"component": "root"})); run(s, "component.create", json!({"name": name})); run(s, "solid.cylinder", json!({"base": [x, 0, 0], "axis": [0, 0, 1], "radius": r, "height": 5})); - pin(s, "revolute", name, "Base", name, Vec3::new(x, 0.0, 0.0), Vec3::Z); } fn base(s: &mut Session) { @@ -80,11 +85,13 @@ fn a_gear_train_of_three_turns_by_its_radii() { run(&mut s, "motion.study", json!({"name": "Spin", "steps": 10, "keys": [{"joint": "G1", "points": [[0, 0], [10, 30]]}]})); run(&mut s, "motion.play", json!({"study": "Spin", "step": 10})); assert!(close_to(shown(&mut s, "G3"), 24.0), "{}", shown(&mut s, "G3")); - // An internal (ring) gear turns its mate the same way; redefining a link keeps its offset. + // An internal (ring) gear turns its mate the same way; the redefined link leaves G3 where it + // is (G2 at -18°), and G1 turning on 30° more turns G2 on -18° and G3 on -24°. let r = run(&mut s, "joint.gear", json!({"a": "G2", "b": "G3", "ra": 20, "rb": 15, "internal": true, "link": 1})); assert_eq!(r["link"], 1, "{r}"); + assert!(close_to(shown(&mut s, "G3"), 24.0), "{}", run(&mut s, "joint.list", json!({}))); run(&mut s, "joint.drive", json!({"joint": "G1", "value": 60})); - assert!(close_to(shown(&mut s, "G2"), -36.0) && close_to(shown(&mut s, "G3"), -48.0), "{}", run(&mut s, "joint.list", json!({}))); + assert!(close_to(shown(&mut s, "G2"), -36.0) && close_to(shown(&mut s, "G3"), 0.0), "{}", run(&mut s, "joint.list", json!({}))); // Undo takes the redefinition back. run(&mut s, "edit.undo", json!({})); run(&mut s, "edit.undo", json!({})); @@ -162,10 +169,10 @@ fn a_screw_advances_its_pitch_per_turn() { let travel = r["values"][1]["value"].as_f64().unwrap_or(f64::NAN); assert!(close_to(travel, 3.0), "{r}"); assert!(near(place(&s, "Nut", Vec3::new(-1.0, -1.0, 0.0)), Vec3::new(-1.0, -1.0, 3.0))); - // A left-hand thread goes the other way. + // A left-hand thread goes the other way, from where the nut is. run(&mut s, "joint.screw", json!({"joint": "Thread", "pitch": 1.5, "reverse": true, "link": 0})); - let r = run(&mut s, "joint.drive", json!({"joint": "Thread", "values": [360]})); - assert!(close_to(r["values"][1]["value"].as_f64().unwrap_or(f64::NAN), -1.5), "{r}"); + let r = run(&mut s, "joint.drive", json!({"joint": "Thread", "values": [1080]})); + assert!(close_to(r["values"][1]["value"].as_f64().unwrap_or(f64::NAN), 1.5), "{r}"); // A revolute joint and a slider, the pitch a parameter: changing it changes the lead. let mut s = Session::default(); run(&mut s, "parameters.add", json!({"name": "lead", "expression": "2 mm"})); @@ -253,3 +260,135 @@ fn couplings_refuse_what_they_cannot_couple() { } assert_eq!(s.doc.assembly, before); } + +/// Gears of radii 10 and 20 on the grounded base, turned to 30° and 40° before they are coupled. +fn meshed_at_30_and_40() -> Session { + let mut s = Session::default(); + base(&mut s); + disc(&mut s, "GA", 0.0, "10 mm"); + disc(&mut s, "GB", 30.0, "20 mm"); + run(&mut s, "joint.drive", json!({"joint": "GA", "value": 30})); + run(&mut s, "joint.drive", json!({"joint": "GB", "value": 40})); + let r = run(&mut s, "joint.gear", json!({"a": "GA", "b": "GB", "ra": 10, "rb": 20})); + assert!(close_to(r["ratio"].as_f64().unwrap_or(f64::NAN), -0.5), "{r}"); + s +} + +/// The first motion link's offset in degrees, and whether its gear is reversed. +fn gear_link(s: &Session) -> (f64, Option) { + let l = s.doc.assembly.links.first(); + let reverse = l.and_then(|l| match &l.coupling { + Some(Coupling::Gear { reverse, .. }) => Some(*reverse), + _ => None, + }); + (l.map(|l| l.offset.to_degrees()).unwrap_or(f64::NAN), reverse) +} + +/// A gear link redefined in place (turned the other way with `reverse`) leaves the driven gear +/// where it is, as a new link does, so the gears stay in mesh at the pose they are in: GB stays +/// at 40° rather than jumping to 70° (the old offset kept, the flip pivoting about GA at 0°). +/// Undo, redo and saving keep each definition with its pose. +#[test] +fn a_redefined_gear_stays_in_mesh_where_it_is() { + let mut s = meshed_at_30_and_40(); + // b = -0.5·a + 55: GB keeps its 40° at GA's 30°. + let (offset, reverse) = gear_link(&s); + assert!(close_to(offset, 55.0) && reverse == Some(false), "{offset} {reverse:?}"); + assert!(close_to(shown(&mut s, "GB"), 40.0), "{}", shown(&mut s, "GB")); + let r = run(&mut s, "joint.gear", json!({"a": "GA", "b": "GB", "ra": 10, "rb": 20, "reverse": true, "link": 0})); + assert!(r["link"] == 0 && close_to(r["ratio"].as_f64().unwrap_or(f64::NAN), 0.5), "{r}"); + // b = 0.5·a + 25. + let (offset, reverse) = gear_link(&s); + assert!(close_to(offset, 25.0) && reverse == Some(true), "{offset} {reverse:?}"); + assert!(close_to(shown(&mut s, "GA"), 30.0) && close_to(shown(&mut s, "GB"), 40.0), "{}", run(&mut s, "joint.list", json!({}))); + assert!(near(rim(&s, "GB", 30.0, 20.0), turned(30.0, 20.0, 40.0)), "{:?}", rim(&s, "GB", 30.0, 20.0)); + // It turns from there, now the same way as GA. + run(&mut s, "joint.drive", json!({"joint": "GA", "value": 0})); + assert!(close_to(shown(&mut s, "GB"), 25.0), "{}", shown(&mut s, "GB")); + assert!(near(rim(&s, "GB", 30.0, 20.0), turned(30.0, 20.0, 25.0)), "{:?}", rim(&s, "GB", 30.0, 20.0)); + // Undo goes back through the drive and the redefinition, redo forward again. + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + let (offset, reverse) = gear_link(&s); + assert!(close_to(offset, 55.0) && reverse == Some(false), "{offset} {reverse:?}"); + assert!(close_to(shown(&mut s, "GA"), 30.0) && close_to(shown(&mut s, "GB"), 40.0), "{}", run(&mut s, "joint.list", json!({}))); + run(&mut s, "edit.redo", json!({})); + let (offset, reverse) = gear_link(&s); + assert!(close_to(offset, 25.0) && reverse == Some(true), "{offset} {reverse:?}"); + assert!(close_to(shown(&mut s, "GB"), 40.0), "{}", shown(&mut s, "GB")); + run(&mut s, "edit.redo", json!({})); + assert!(close_to(shown(&mut s, "GA"), 0.0) && close_to(shown(&mut s, "GB"), 25.0), "{}", run(&mut s, "joint.list", json!({}))); + // Saved and opened again: the same link, the same pose. + let back = solidcraft_doc::format::read(&s.doc.to_json()).unwrap_or_else(|e| panic!("{e}")); + assert_eq!(back.assembly.links, s.doc.assembly.links); + let vals = solidcraft_doc::joints::joint_values(&back.assembly); + let gb = back.assembly.joints.iter().find(|j| j.name == "GB").map(|j| j.id).unwrap_or(0); + assert!(vals.get(&gb).and_then(|q| q.first()).is_some_and(|v| close_to(v.to_degrees(), 25.0)), "{vals:?}"); +} + +/// The other couplings redefined in place keep their driven joint where it is too. +#[test] +fn a_redefined_rack_keeps_the_rack_where_it_is() { + let mut s = rack(); + run(&mut s, "joint.rack_pinion", json!({"a": "Pinion", "b": "Rail", "radius": 8})); + run(&mut s, "joint.drive", json!({"joint": "Pinion", "value": 45})); + let travel = 8.0 * std::f64::consts::FRAC_PI_4; + run(&mut s, "joint.rack_pinion", json!({"a": "Pinion", "b": "Rail", "radius": 4, "reverse": true, "link": 0})); + assert!(close_to(shown(&mut s, "Rail"), travel), "{}", shown(&mut s, "Rail")); + run(&mut s, "joint.drive", json!({"joint": "Pinion", "value": 0})); + assert!(close_to(shown(&mut s, "Rail"), travel + 4.0 * std::f64::consts::FRAC_PI_4), "{}", shown(&mut s, "Rail")); +} + +/// A joint a motion link drives adds no freedom of its own: gears on a grounded base have one +/// between them, each turning (and draggable) with it; a part hinged on the driven gear has one +/// more; a cylindrical joint whose turn drives its travel (a screw) has one, not two. +#[test] +fn a_motion_link_takes_its_driven_joints_freedom_on_a_grounded_base() { + let mut s = Session::default(); + base(&mut s); + disc(&mut s, "GA", 0.0, "10 mm"); + disc(&mut s, "GB", 30.0, "20 mm"); + run(&mut s, "joint.gear", json!({"a": "GA", "b": "GB", "ra": 10, "rb": 20})); + for (part, want) in [("Base", 0), ("GA", 1), ("GB", 1)] { + assert_eq!(dof_of(&mut s, part), want, "{part}"); + } + part(&mut s, "Arm", [45.0, -1.0, 5.0]); + pin(&mut s, "revolute", "Arm", "GB", "Arm", Vec3::new(46.0, 0.0, 5.0), Vec3::Z); + assert_eq!(dof_of(&mut s, "Arm"), 2); + // The arm's hinge driven by GA too: still the one value. + run(&mut s, "joint.motion_link", json!({"a": "GA", "b": "Arm", "ratio": 2})); + assert_eq!(dof_of(&mut s, "Arm"), 1); + let mut s = Session::default(); + base(&mut s); + part(&mut s, "Nut", [-1.0, -1.0, 0.0]); + pin(&mut s, "cylindrical", "Thread", "Base", "Nut", Vec3::ZERO, Vec3::Z); + assert_eq!(dof_of(&mut s, "Nut"), 2); + run(&mut s, "joint.screw", json!({"joint": "Thread", "pitch": 1.5})); + assert_eq!(dof_of(&mut s, "Nut"), 1); +} + +/// With nothing grounded, the first joint's A side stays put. A gear there (its joint to the +/// housing made from the gear) leaves the housing one turn about it, and the driven gear on the +/// housing turns with that same value once the gears are coupled: one, not two. With the +/// housing first, each gear has one. +#[test] +fn a_motion_link_takes_its_driven_joints_freedom_with_nothing_grounded() { + for gear_first in [true, false] { + let mut s = Session::default(); + part(&mut s, "Housing", [-10.0, -10.0, -20.0]); + loose_disc(&mut s, "GA", 0.0, "10 mm"); + loose_disc(&mut s, "GB", 30.0, "20 mm"); + let (a, b) = if gear_first { ("GA", "Housing") } else { ("Housing", "GA") }; + pin(&mut s, "revolute", "JA", a, b, Vec3::ZERO, Vec3::Z); + pin(&mut s, "revolute", "JB", "Housing", "GB", Vec3::new(30.0, 0.0, 0.0), Vec3::Z); + let (fixed, free) = if gear_first { ("GA", "Housing") } else { ("Housing", "GA") }; + assert_eq!(dof_of(&mut s, fixed), 0, "gear first: {gear_first}"); + assert_eq!(dof_of(&mut s, free), 1, "gear first: {gear_first}"); + // Before the link GB turns on JB, and with the housing about GA when GA stays put. + assert_eq!(dof_of(&mut s, "GB"), if gear_first { 2 } else { 1 }, "gear first: {gear_first}"); + run(&mut s, "joint.gear", json!({"a": "JA", "b": "JB", "ra": 10, "rb": 20})); + for (part, want) in [(fixed, 0), (free, 1), ("GB", 1)] { + assert_eq!(dof_of(&mut s, part), want, "{part}, gear first: {gear_first}"); + } + } +} diff --git a/docs/book/src/guide/assemblies.md b/docs/book/src/guide/assemblies.md index f01041aa5..e7888b56d 100644 --- a/docs/book/src/guide/assemblies.md +++ b/docs/book/src/guide/assemblies.md @@ -108,7 +108,9 @@ ratio comes from the parts rather than a typed number: A radius or pitch may be an expression of the design's parameters, and a picked face is found again whenever the design changes. Change the parameter or the gear's diameter, and the ratio follows. The new link leaves the driven joint where it is, so teeth modelled in mesh stay in mesh. -**Reverse** turns the driven joint the other way, for joints whose axes point opposite ways. These +**Reverse** turns the driven joint the other way, for joints whose axes point opposite ways. +Redefining a link (`link: i`, such as turning it the other way with **Reverse**) also leaves the +driven joint where it is, so the gears stay in mesh at the pose they are in. These couplings are motion links, so they work in closed loops, with contact sets and in motion studies: a rack can push the piston of a slider-crank, or a pinion can steer through a rack and its tie rods. Drive the joint that drives the coupling (joint 1, the pinion, or the screw's turn), not the @@ -158,7 +160,8 @@ example driving a rocker beyond its swing, the motion stops at the last position closes, and the drive reports `stopped_by_loop`. A loop that cannot close at all is listed under `conflicts` and nothing in it moves. `joint.list` reports how many degrees of freedom each part still has with its loops closed: the moving parts of a four-bar have one between them, and a -loop locked by a rigid joint has none. The Drive Joints dialog says when a drive stops short and +loop locked by a rigid joint has none. A joint a motion link drives adds no freedom of its own: +two meshed gears on a fixed housing have one between them, each turning with the driving gear. The Drive Joints dialog says when a drive stops short and why. While it previews, a row under the values gives the value the joint reached and the reason (the loop that can't close further, or the two parts a contact set keeps apart), and after OK the status line repeats it. The value box keeps what you typed. The dialog opens on the joint From 66951921a15d8b184251416b96c3262ae7c2c133 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Mon, 19 Oct 2026 17:45:57 -0400 Subject: [PATCH 125/225] README: Blacksmith sponsor banner (#3287) Co-authored-by: Claude Opus 5.5 --- ATTRIBUTION.md | 1 + README.md | 2 ++ docs/sponsors/blacksmith-ci-powered.png | Bin 0 -> 4088 bytes 3 files changed, 3 insertions(+) create mode 100644 docs/sponsors/blacksmith-ci-powered.png diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index fa1207469..fa381d097 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -412,6 +412,7 @@ Editable drawing code, native projects and shipped exports are collected under ` | assets/icons/ui/design/tools/author/lib.py | SolidCraft contributors | icon authoring script (standard-library Python), original SolidCraft code | MIT OR Apache-2.0 | | docs/book/src/og.png | SolidCraft contributors | copy of assets/branding/web/source/og.png staged by cargo xtask book (gitignored) | MIT OR Apache-2.0 | +| docs/sponsors/blacksmith-ci-powered.png | Blacksmith (blacksmith.sh) | "CI powered by Blacksmith" sponsor banner supplied by Blacksmith for the sponsorship credit; used only to credit the sponsor, not part of the application | © Blacksmith, used with permission | ## Code adapted from sibling projects diff --git a/README.md b/README.md index 802132430..bcaf18239 100644 --- a/README.md +++ b/README.md @@ -108,6 +108,8 @@ the clean-room and licence rules, and where help is wanted most. Open work is in ## Sponsors +[![CI powered by Blacksmith](docs/sponsors/blacksmith-ci-powered.png)](https://www.blacksmith.sh) + SolidCraft's continuous integration runs on [Blacksmith](https://www.blacksmith.sh), which sponsors its CI minutes. diff --git a/docs/sponsors/blacksmith-ci-powered.png b/docs/sponsors/blacksmith-ci-powered.png new file mode 100644 index 0000000000000000000000000000000000000000..d21e27dd272a6afd828b89c3597a17b132c8466c GIT binary patch literal 4088 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 Date: Mon, 19 Oct 2026 17:54:10 -0400 Subject: [PATCH 126/225] Trademark notice: name every CAD vendor and product we mention, not only Autodesk (#3294) Co-authored-by: Claude Opus 5.5 --- CONTRIBUTING.md | 2 +- NOTICE | 7 +++++-- README.md | 6 ++++-- docs/book/src/introduction.md | 5 +++-- 4 files changed, 13 insertions(+), 7 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 55bfb4c99..21476b445 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -386,4 +386,4 @@ unchanged. The initial switch to sorted rows is a one-time larger diff. ## Licence By contributing you agree that your contribution is licensed as MIT OR Apache-2.0, like the rest -of SolidCraft. SolidCraft isn't affiliated with Autodesk. Fusion is a trademark of Autodesk, Inc. +of SolidCraft. SolidCraft isn't affiliated with any CAD vendor; product names are trademarks of their owners (see NOTICE). diff --git a/NOTICE b/NOTICE index 4ff0526b2..0d4cfeeb1 100644 --- a/NOTICE +++ b/NOTICE @@ -29,5 +29,8 @@ for sketch text, BIZ UDPGothic for web Japanese display) are licensed under SIL per-file list is in ATTRIBUTION.md. SolidCraft is an independent project and is not affiliated with, sponsored by or endorsed by -Autodesk, Inc. Autodesk and Fusion are trademarks of Autodesk, Inc.; they are used here only to -describe compatibility goals. +Autodesk, Dassault Systèmes, PTC, Siemens, Blender or any other CAD vendor. Fusion, AutoCAD, +Inventor, Alias and Tinkercad are trademarks of Autodesk, Inc.; SolidWorks is a trademark of +Dassault Systèmes; Onshape and Creo are trademarks of PTC; Blender is a trademark of the Blender +Foundation. Product names appear only to describe compatibility, such as the mouse navigation +presets in Preferences › Navigation and file formats from public specifications. diff --git a/README.md b/README.md index bcaf18239..36fef8291 100644 --- a/README.md +++ b/README.md @@ -121,8 +121,10 @@ documented licences and attribution. SolidCraft is independent. Behaviour is designed from public documentation, general CAD conventions and user feedback. Reference tests use analytic values and open-source tools. -SolidCraft is not affiliated with, sponsored by or endorsed by Autodesk. Autodesk and -Fusion are trademarks of Autodesk, Inc. +SolidCraft is not affiliated with, sponsored by or endorsed by Autodesk, Dassault Systèmes, PTC, +Siemens or any other CAD vendor. Fusion, AutoCAD, Inventor, SolidWorks, Onshape, Creo, Blender and +Tinkercad are trademarks of their respective owners, named only to describe compatibility +(see [NOTICE](NOTICE)). [badge-windows]: https://img.shields.io/badge/Windows-Download-0078D6?style=for-the-badge&logo=data%3Aimage%2Fsvg%2Bxml%3Bbase64%2CPHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0id2hpdGUiPjxwYXRoIGQ9Ik0yIDJoOS41djkuNUgyek0xMi41IDJIMjJ2OS41aC05LjV6TTIgMTIuNWg5LjVWMjJIMnpNMTIuNSAxMi41SDIyVjIyaC05LjV6Ii8%2BPC9zdmc%2B [badge-macos]: https://img.shields.io/badge/macOS-Download-333333?style=for-the-badge&logo=apple&logoColor=white diff --git a/docs/book/src/introduction.md b/docs/book/src/introduction.md index bb4ed4e8f..7ba49e961 100644 --- a/docs/book/src/introduction.md +++ b/docs/book/src/introduction.md @@ -32,5 +32,6 @@ generated from the code on every build. SolidCraft is licensed MIT OR Apache-2.0. It is independent: behaviour is designed from public documentation, general CAD conventions and user feedback, and reference tests use analytic -values and open-source tools. SolidCraft is not affiliated with Autodesk; Fusion is a trademark -of Autodesk, Inc. +values and open-source tools. SolidCraft is not affiliated with Autodesk, Dassault Systèmes, +PTC or any other CAD vendor; product names such as Fusion, SolidWorks and Onshape are trademarks of +their respective owners, named only to describe compatibility. From 68ac9976f37099c6bf1cb0588f829382b4951f55 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Mon, 19 Oct 2026 17:57:48 -0400 Subject: [PATCH 127/225] README: CI powered by Blacksmith badge (#3299) Co-authored-by: Claude Opus 5.5 --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 36fef8291..4dcc5562e 100644 --- a/README.md +++ b/README.md @@ -26,6 +26,7 @@ Download · Try it in the browser · Documentation · + CI powered by Blacksmith Discord · SolidCore

From a9f621837ffa9016b9df9d3bc6c170d6339369fb Mon Sep 17 00:00:00 2001 From: phanoob Date: Mon, 19 Oct 2026 23:59:39 +0200 Subject: [PATCH 128/225] Sketch Trim: the hover shows the piece that will go, not the whole curve (#3052) (#3113) * claim: #3052 Co-Authored-By: Claude Opus 5.5 * Sketch Trim: the hover shows the piece a click takes away (#3052) Co-Authored-By: Claude Opus 5.5 * Sketch Trim: the piece is shown in the error colour, thicker Co-Authored-By: Claude Opus 5.5 * Trim hover: preview keeps its doc line; the piece is worked out once a frame The new function had gone between preview's doc line and preview. The cursor's Trim piece is now kept by design revision, sketch, curve and cursor, so the viewport's hover and the preview no longer both intersect the curve with every other curve each frame. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Phanoob Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd/mod.rs | 1 + crates/engine/src/cmd/sketch_modify.rs | 31 ++++++++++++++ crates/engine/src/cmd/sketch_modify_tests.rs | 43 ++++++++++++++++++++ crates/ui-egui/src/sketch_corner_ui_tests.rs | 25 ++++++++++++ crates/ui-egui/src/sketch_tools.rs | 34 ++++++++++++++++ crates/ui-egui/src/viewport.rs | 2 + 6 files changed, 136 insertions(+) diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index f9673ecf3..864bf7827 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -36,6 +36,7 @@ mod face; mod features; mod features_more; pub use features::{auto_operation, extrude_reach}; +pub use sketch_modify::trim_piece; mod component_link; mod config; mod file; diff --git a/crates/engine/src/cmd/sketch_modify.rs b/crates/engine/src/cmd/sketch_modify.rs index 6cc0d8dad..2b57abd26 100644 --- a/crates/engine/src/cmd/sketch_modify.rs +++ b/crates/engine/src/cmd/sketch_modify.rs @@ -307,6 +307,37 @@ fn bracket(sk: &Sketch, ci: usize, tq: f64) -> (Vec<(f64, Vec2, usize)>, bool) { (before.into_iter().chain(after).collect(), false) } +/// The piece of `curve` a trim at `at` takes away, as points along it, for the Trim tool to show +/// under the cursor (#3052): the part between the crossings either side of `at`, as `sketch.trim` +/// cuts it, or the whole curve where nothing crosses it. `None` where trim works otherwise (a +/// free-form or infinite curve) or the curve isn't in the sketch: the tool shows the curve. +pub fn trim_piece(sk: &Sketch, curve: &str, at: Vec2) -> Option> { + let ci = sk.curve_index(curve)?; + let c = sk.curves.get(ci)?; + if c.infinite || c.kind.is_freeform() { + return None; + } + let sh = sk.shape(ci)?; + let tq = sh.param(sh.project(at)); + let (t0, t1) = sh.range(); + let (cuts, full) = bracket(sk, ci, tq); + let (a, b) = match (cuts.as_slice(), full) { + ([], _) => (t0, t1), + // A whole circle: the arc between the two crossings round `at`. + ([x, y], true) => { + if tq > x.0 && tq < y.0 { + (x.0, y.0) + } else { + (y.0, x.0 + TAU) + } + } + (_, true) => return None, + (cuts, false) => (cuts.iter().rev().find(|c| c.0 < tq).map_or(t0, |c| c.0), cuts.iter().find(|c| c.0 > tq).map_or(t1, |c| c.0)), + }; + let n = if matches!(sh, Shape::Line { .. }) { 1 } else { 64 }; + Some((0..=n).map(|i| sh.point(a + (b - a) * f64::from(i) / f64::from(n))).collect()) +} + fn trim(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.trim"; let at = req_vec2(cmd, p, "at")?; diff --git a/crates/engine/src/cmd/sketch_modify_tests.rs b/crates/engine/src/cmd/sketch_modify_tests.rs index 846cd32bd..a560d7f0c 100644 --- a/crates/engine/src/cmd/sketch_modify_tests.rs +++ b/crates/engine/src/cmd/sketch_modify_tests.rs @@ -1619,3 +1619,46 @@ fn trim_keeps_the_rest_of_a_dimensioned_line_where_it_was() { assert!(corner(&s).dist(Vec2::new(40.0, 23.0)) < 1e-6, "the step moved to {:?}", corner(&s)); assert!(forty(&s).is_empty(), "{:?}", forty(&s)); } + +/// #3052: the piece Trim shows under the cursor is the one `sketch.trim` takes away there: its +/// ends lie on the crossings either side of the cursor (or the curve's own end), and after the +/// trim no curve runs through its middle any more. A line crossed twice, its middle and an end +/// piece; a circle crossed by a line, the half round the cursor; a line nothing crosses, whole. +#[test] +fn trim_piece_is_what_a_trim_there_takes_away() { + let near = |a: Vec2, b: [f64; 2]| (a - Vec2::new(b[0], b[1])).len() < 1e-6; + let crossed_line = || { + let mut s = new_sketch(); + let line = ids(&run(&mut s, "sketch.line", json!({"points": [[0,0], [30,0]], "connect": false}))["curves"])[0].clone(); + run(&mut s, "sketch.line", json!({"points": [[10,-5], [10,5]], "connect": false})); + run(&mut s, "sketch.line", json!({"points": [[20,-5], [20,5]], "connect": false})); + (s, line) + }; + let crossed_circle = || { + let mut s = new_sketch(); + let circle = ids(&run(&mut s, "sketch.circle.center", json!({"center": [0,0], "radius": 10}))["curves"])[0].clone(); + run(&mut s, "sketch.line", json!({"points": [[-20,0], [20,0]], "connect": false})); + (s, circle) + }; + let cases: [(&dyn Fn() -> (Session, String), [f64; 2], [[f64; 2]; 2], [f64; 2]); 4] = [ + (&crossed_line, [15.0, 0.0], [[10.0, 0.0], [20.0, 0.0]], [15.0, 0.0]), + (&crossed_line, [4.0, 0.0], [[0.0, 0.0], [10.0, 0.0]], [5.0, 0.0]), + (&crossed_circle, [0.0, 10.0], [[10.0, 0.0], [-10.0, 0.0]], [0.0, 10.0]), + (&crossed_circle, [0.0, -10.0], [[10.0, 0.0], [-10.0, 0.0]], [0.0, -10.0]), + ]; + for (make, at, ends, inside) in cases { + let (mut s, curve) = make(); + let piece = super::trim_piece(&sketch(&s), &curve, Vec2::new(at[0], at[1])).unwrap(); + let (first, last) = (piece[0], piece[piece.len() - 1]); + assert!((near(first, ends[0]) && near(last, ends[1])) || (near(first, ends[1]) && near(last, ends[0])), "{at:?}: {first:?} {last:?}"); + let mid = if piece.len() > 2 { piece[piece.len() / 2] } else { (first + last) * 0.5 }; + assert!(near(mid, inside), "{at:?}: {mid:?}"); + run(&mut s, "sketch.trim", json!({"curve": curve, "at": at})); + let sk = sketch(&s); + assert!(!(0..sk.curves.len()).filter_map(|i| sk.shape(i)).any(|sh| sh.dist(mid) < 1e-6), "the trim at {at:?} took the piece shown away"); + } + let mut s = new_sketch(); + let lone = ids(&run(&mut s, "sketch.line", json!({"points": [[0,0], [8,0]], "connect": false}))["curves"])[0].clone(); + let piece = super::trim_piece(&sketch(&s), &lone, Vec2::new(3.0, 0.0)).unwrap(); + assert!(near(piece[0], [0.0, 0.0]) && near(piece[piece.len() - 1], [8.0, 0.0]), "{piece:?}"); +} diff --git a/crates/ui-egui/src/sketch_corner_ui_tests.rs b/crates/ui-egui/src/sketch_corner_ui_tests.rs index 6b75068c9..25cac7d37 100644 --- a/crates/ui-egui/src/sketch_corner_ui_tests.rs +++ b/crates/ui-egui/src/sketch_corner_ui_tests.rs @@ -595,3 +595,28 @@ fn fillet_chamfer_corner_preview_draws_curves() { let sk = h.app.session.world_state().sketch(sid).unwrap().sketch.clone(); assert_eq!(sk.curves.len(), 2, "chamfer preview must not modify the sketch"); } + +/// #3052: with Trim, the hover over a line crossed by two others is the piece between them, the +/// one a click takes away; the whole line is no longer shown hovered. With another tool, nothing. +#[test] +fn trim_hover_shows_the_piece_a_click_takes_away() { + let mut h = crate::scenario::Harness::new(); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + let line = h.app.run("sketch.line", json!({"points": [[0,0],[30,0]], "connect": false})).unwrap()["curves"][0].as_str().unwrap().to_string(); + h.app.run("sketch.line", json!({"points": [[10,-5],[10,5]], "connect": false})).unwrap(); + h.app.run("sketch.line", json!({"points": [[20,-5],[20,5]], "connect": false})).unwrap(); + h.settle(); + let sid = h.app.session.active_sketch.unwrap(); + h.step(&json!({"start":"sketch.trim"})).unwrap(); + h.step(&json!({"move":{"world":[15,0,0]}})).unwrap(); + assert!(matches!(&h.app.viewport.hover, Some(crate::viewport::Hit::SketchCurve { id, .. }) if *id == line), "{:?}", h.app.viewport.hover); + let piece = trim_hover_piece(&h.app, sid, &line).unwrap(); + let ends = [piece[0], piece[piece.len() - 1]]; + assert!( + ends.iter().all(|p| p.y.abs() < 1e-6) && ends.iter().any(|p| (p.x - 10.0).abs() < 1e-6) && ends.iter().any(|p| (p.x - 20.0).abs() < 1e-6), + "{ends:?}" + ); + h.step(&json!({"key":"Escape"})).unwrap(); + h.step(&json!({"move":{"world":[15,0,0]}})).unwrap(); + assert!(trim_hover_piece(&h.app, sid, &line).is_none(), "only Trim shows a piece"); +} diff --git a/crates/ui-egui/src/sketch_tools.rs b/crates/ui-egui/src/sketch_tools.rs index 5f05fb120..1e9b987df 100644 --- a/crates/ui-egui/src/sketch_tools.rs +++ b/crates/ui-egui/src/sketch_tools.rs @@ -999,6 +999,33 @@ pub fn finish(app: &mut SolveApp, tool: &mut Tool) -> bool { } } +/// The cursor's Trim piece, keyed by design revision, sketch, curve and cursor: the viewport's +/// hover and the preview both ask for it each frame, and it intersects the curve with every other. +type TrimPieceKey = (u64, u64, String, [u64; 2]); + +thread_local! { + static TRIM_PIECE: std::cell::RefCell>)>> = const { std::cell::RefCell::new(None) }; +} + +/// With Trim active and the cursor over curve `id` of `sketch` (the active sketch): the piece a +/// click takes away (#3052), which the hover shows in place of the whole curve. `None` with +/// another tool, or for a curve trim cuts otherwise (`solidcraft_engine::cmd::trim_piece`). +pub(crate) fn trim_hover_piece(app: &SolveApp, sketch: u64, id: &str) -> Option> { + let tool = app.tool.as_ref().filter(|t| t.cmd == "sketch.trim")?; + let (at, _) = tool.hover.as_ref()?; + if active_sketch(app) != Some(sketch) { + return None; + } + let key = (app.session.revision, sketch, id.to_string(), [at.x.to_bits(), at.y.to_bits()]); + if let Some(piece) = TRIM_PIECE.with(|c| c.borrow().as_ref().filter(|(k, _)| *k == key).map(|(_, p)| p.clone())) { + return piece; + } + let st = app.session.world_state(); + let piece = solidcraft_engine::cmd::trim_piece(&st.sketch(sketch)?.sketch, id, *at); + TRIM_PIECE.with(|c| *c.borrow_mut() = Some((key, piece.clone()))); + piece +} + /// Rubber band for point tools and pick markers. pub fn preview(app: &SolveApp, t: &Tool, painter: &egui::Painter, proj: &Proj) { let Some(sid) = active_sketch(app) else { return }; @@ -1006,6 +1033,13 @@ pub fn preview(app: &SolveApp, t: &Tool, painter: &egui::Painter, proj: &Proj) { let Some(ss) = st.sketch(sid) else { return }; let to = |p: Vec2| proj.to_screen(ss.plane.to_world(p)); let tk = crate::theme::Tokens::get(); + if let Some(crate::viewport::Hit::SketchCurve { sketch, id, .. }) = &app.viewport.hover + && let Some(piece) = trim_hover_piece(app, *sketch, id) + { + let world: Vec<_> = piece.iter().map(|p| ss.plane.to_world(*p)).collect(); + // In the error colour, thicker than a hover: it is what the click deletes. + crate::tools::paint_sketch_path(&world, 0, painter, proj, Stroke::new(4.5, tk.error)); + } let stroke = Stroke::new(1.5, tk.rubber_band); if let Some((hp, snap)) = &t.hover && let Some(sp) = to(*hp) diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 8e3264ba4..22661bd6d 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -3172,6 +3172,8 @@ fn hover_highlight(app: &SolveApp, painter: &egui::Painter, proj: &Proj) { let col = Tokens::get().hover_profile_edge; let st = app.session.world_state(); match &app.viewport.hover { + // Trim shows the piece it would take away instead (`sketch_tools::preview`, #3052). + Some(Hit::SketchCurve { sketch, id, .. }) if crate::sketch_tools::trim_hover_piece(app, *sketch, id).is_some() => {} Some(Hit::SketchCurve { sketch, id, .. }) => { if let Some(ss) = st.sketch(*sketch) && let Some(ci) = ss.sketch.curve_index(id) From 54b00fa7b1d3292d0a1bc263a47e96a233347a07 Mon Sep 17 00:00:00 2001 From: fkirill Date: Tue, 20 Oct 2026 01:04:24 +0300 Subject: [PATCH 129/225] Chamfer straight lips at tangent wall junctions (#2408) (#2490) Thanks @fkirill. --- crates/kernel/src/blend.rs | 98 +++++++++++++++++++ crates/kernel/src/curveblend.rs | 9 +- crates/kernel/tests/chamfer_curved_holder.rs | 90 +++++++++++++++++ .../chamfer_curved_holder_top_lip.json | 14 +++ 4 files changed, 210 insertions(+), 1 deletion(-) create mode 100644 crates/kernel/tests/chamfer_curved_holder.rs create mode 100644 examples/regressions/chamfer_curved_holder_top_lip.json diff --git a/crates/kernel/src/blend.rs b/crates/kernel/src/blend.rs index 484a95e28..60f349e4f 100644 --- a/crates/kernel/src/blend.rs +++ b/crates/kernel/src/blend.rs @@ -2187,6 +2187,11 @@ fn chamfer_built(body: &Body, edges: &[Vec3], distance: f64) -> Result { let blend_or_curved = |cur: &Body, p: &Vec3| -> Result { blend(cur, std::slice::from_ref(p), distance, Shape::Flat, "chamfer") .or_else(|e| blend_with(cur, std::slice::from_ref(p), distance, Shape::Flat, "chamfer", true).map_err(|_| e)) + .or_else(|e| { + chamfer_tool_curved(cur, *p, distance) + .and_then(|tool| cut_one(cur, &tool)?.ok_or_else(|| KernelError::Failed("the chamfer removed everything".into()))) + .map_err(|_| e) + }) }; for p in edges { let tool = chamfer_tool(&cur, *p, distance, 0); @@ -2424,6 +2429,99 @@ pub(crate) fn chamfer_tool(cur: &Body, p: Vec3, s: f64, k: usize) -> Result Result { + guard("straight curved chamfer", || { + let size = cur.size(); + let tolerance = (size * 1e-7).max(1e-9); + let (index, gap) = cur.nearest_edge(pick, (size * 2e-3).max(1e-3))?.ok_or_else(|| unsupported("no chamfer edge"))?; + if gap > size * 0.05 + 1e-3 { + return Err(unsupported("no nearby chamfer edge")); + } + let edge = Body::unique_edges(&cur.solid).into_iter().nth(index).ok_or_else(|| unsupported("chamfer edge"))?; + if !crate::curveblend::straight(&edge, tolerance * 10.0) { + return Err(unsupported("a straight plane/cylinder edge is required")); + } + let (p0, p1) = (vtx(edge.absolute_front()), vtx(edge.absolute_back())); + let along = (p1 - p0).normalized().ok_or_else(|| unsupported("zero-length chamfer edge"))?; + let faces: Vec<_> = cur.solid.face_iter().filter(|f| f.edge_iter().any(|e| e.id() == edge.id())).collect(); + let [f1, f2] = faces.as_slice() else { return Err(unsupported("the edge must have two faces")) }; + let kinds = (crate::surface_kind::surface_of(f1, size), crate::surface_kind::surface_of(f2, size)); + let (normal, axis) = match kinds { + (Some(crate::FaceSurface::Plane { normal, .. }), Some(crate::FaceSurface::Cylinder { axis, .. })) + | (Some(crate::FaceSurface::Cylinder { axis, .. }), Some(crate::FaceSurface::Plane { normal, .. })) => (normal, axis), + _ => return Err(unsupported("a straight plane/cylinder edge is required")), + }; + // A boolean intersection can carry slightly displaced ends and supporting surfaces. + // Check angular alignment here, then the swept contacts against the actual surfaces. + if normal.dot(axis).abs() > 1e-5 || axis.cross(along).len() > 1e-5 { + return Err(unsupported("the cylinder must run along the chamfer edge")); + } + let d = if axis.dot(along) < 0.0 { -axis } else { axis }; + let mid = (p0 + p1) * 0.5; + let (n1, n2) = ( + crate::curveblend::project(f1, mid, None).map(|p| p.1).ok_or_else(|| unsupported("chamfer normal"))?, + crate::curveblend::project(f2, mid, None).map(|p| p.1).ok_or_else(|| unsupported("chamfer normal"))?, + ); + let used = f1.boundary_iters().into_iter().flatten().find(|e| e.id() == edge.id()).ok_or_else(|| unsupported("chamfer edge use"))?; + let tangent = (vtx(used.back()) - vtx(used.front())).normalized().ok_or_else(|| unsupported("chamfer tangent"))?; + if tangent.dot(n1.cross(n2)) <= 1e-9 { + return Err(unsupported("a convex chamfer edge is required")); + } + let (a, b) = crate::curveblend::straight_chamfer_contacts(f1, f2, mid, *d, distance, tolerance) + .ok_or_else(|| unsupported("the chamfer section does not fit"))?; + let fit_tolerance = (size * 1e-5).clamp(1e-5, 0.001); + for (face, point) in [(*f1, a), (*f2, b)] { + for along in [-0.5, -0.25, 0.0, 0.25, 0.5] { + let swept = point + d * (along * p0.dist(p1)); + if crate::curveblend::project(face, swept, None).is_none_or(|(q, _, _)| q.dist(swept) > fit_tolerance) { + return Err(unsupported("the chamfer section varies along the edge")); + } + } + } + // Contacts must lie on the trimmed faces, not merely their infinite supports. A + // fine mesh and an inward probe larger than its chord error also reject a bevel that + // has already used up the top face. Reuse that mesh for all cutter clearance probes. + let mesh = cur.tessellate_with(tolerance * 10.0, true)?; + let inset = (tolerance * 100.0).min(distance * 0.01); + for (face, point) in [(*f1, a), (*f2, b)] { + let (_, normal, _) = crate::curveblend::project(face, point, None).ok_or_else(|| unsupported("chamfer contact"))?; + if !mesh.contains(point - normal * inset) { + return Err(too_large("the chamfer runs past a neighbouring face")); + } + } + let outward = (n1 + n2).normalized().ok_or_else(|| unsupported("chamfer direction"))?; + let across = (a - b).normalized().ok_or_else(|| unsupported("chamfer section"))?; + let reach = distance * 4.0 + size * 0.02; + let center = (a + b + mid) / 3.0; + let a = a + across * reach; + let b = b - across * reach; + if mesh.contains(a) || mesh.contains(b) { + return Err(unsupported("the chamfer cutter crosses a neighbouring face")); + } + let extension = (distance * 2.0).max(size * 0.01); + let half = p0.dist(p1) * 0.5; + if [-1.0, 1.0].into_iter().any(|side| mesh.contains(center + d * (side * (half + extension * 0.5)))) { + return Err(unsupported("chamfers ending at a concave corner")); + } + let plane = solidcraft_geom::Plane::from_normal(mid - d * (p0.dist(p1) * 0.5 + extension), d).ok_or_else(|| unsupported("chamfer plane"))?; + let points = [a, b, mid + outward * reach].map(|q| plane.to_local(q)); + let mut profile = solidcraft_geom::Loop2::polygon(&points); + let mut segment = 0; + if profile.signed_area() < 0.0 { + profile = profile.reversed(); + segment = profile.segs.len().saturating_sub(1); + } + let region = solidcraft_geom::Region2 { outer: profile, holes: vec![] }; + let body = + crate::build::extrude(&plane, &[region], 0.0, p0.dist(p1) + 2.0 * extension)?.pop().ok_or_else(|| unsupported("chamfer cutter"))?; + let face = body.history().and_then(|h| h.faces.iter().position(|f| f.origins == [FaceOrigin::Profile { segment }])); + Ok(Cutter { body, face, edge: index, extension_inside: false }) + }) +} + fn chamfer_tool_sides(cur: &Body, p: Vec3, s: f64, sides: Option<(ChamferSide, bool)>, k: usize) -> Result { let (edge, mut f) = edge_frame(cur, p)?; // Setbacks along each face: equal, or by the second side's rule. diff --git a/crates/kernel/src/curveblend.rs b/crates/kernel/src/curveblend.rs index 37b606a54..e01cf5ee6 100644 --- a/crates/kernel/src/curveblend.rs +++ b/crates/kernel/src/curveblend.rs @@ -653,6 +653,13 @@ fn solve_from( None } +/// Contacts of a convex chamfer in a cross-section normal to a straight edge. The caller +/// checks that sweeping the section stays on both supports within the fitting tolerance. +pub(crate) fn straight_chamfer_contacts(f1: &mt::Face, f2: &mt::Face, p: Vec3, d: Vec3, r: f64, tolerance: f64) -> Option<(Vec3, Vec3)> { + let section = solve(&[f1], &[f2], p, d, r, -1.0, 0.0, None, tolerance)?; + Some((section.q1, section.q2)) +} + /// The section whose two contacts are `chord` apart: the ball's radius is `chord / (2 sin(ψ/2))` /// for the `ψ` between the two outward normals where it touches, `|q1 − q2| = 2 r sin(ψ/2)`. The /// normals turn as the ball grows against curved faces, so the width is measured on the solved @@ -931,7 +938,7 @@ fn revolve(ctrl: [mt::Vector4; 3], c: Vec3, axis: Vec3, angle: f64) -> Option bool { +pub(crate) fn straight(e: &mt::Edge, tol: f64) -> bool { use mt::{BoundedCurve, ParametricCurve}; let c = e.curve(); if matches!(c, mt::Curve::Line(_)) { diff --git a/crates/kernel/tests/chamfer_curved_holder.rs b/crates/kernel/tests/chamfer_curved_holder.rs new file mode 100644 index 000000000..00e715efc --- /dev/null +++ b/crates/kernel/tests/chamfer_curved_holder.rs @@ -0,0 +1,90 @@ +//! #2408, reconstructed from the public screenshot (the original design is unavailable). +//! A cylindrical side cut through a rounded bar leaves a very short seam where the top lip +//! meets the tangent junction of the bar's straight and round walls. The chamfer must trim +//! against the round wall instead of extending that short seam outside the solid. + +use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2, Vec3}; +use solidcraft_kernel::{Body, BoolOp, boolean, chamfer, cylinder, extrude}; +use std::f64::consts::PI; + +fn holder() -> Body { + let segs = vec![ + Seg2::Line { a: Vec2::new(0.0, 10.0), b: Vec2::new(0.0, 70.0) }, + Seg2::Arc { center: Vec2::new(10.0, 70.0), radius: 10.0, start: PI, sweep: -PI }, + Seg2::Line { a: Vec2::new(20.0, 70.0), b: Vec2::new(20.0, 10.0) }, + Seg2::Arc { center: Vec2::new(10.0, 10.0), radius: 10.0, start: 0.0, sweep: -PI }, + ]; + let bar = extrude(&Plane::XY, &[Region2 { outer: Loop2 { segs }, holes: vec![] }], 0.0, 60.0).unwrap().pop().unwrap(); + let tool = cylinder(Vec3::new(-1.0, 70.0, 60.0), Vec3::X, 60.0, 22.0).unwrap(); + boolean(&bar, &tool, BoolOp::Cut).unwrap().unwrap() +} + +/// Integrate the removed horizontal strips analytically across the capsule's width, then +/// use Simpson integration in height. The rolling section's centre is 2 below the top and +/// 62 from the cutter's axis; its wall contact is 60/62 of that vector from the axis. +fn expected_removed(distance: f64) -> f64 { + let center_y = 70.0 - ((60.0 + distance).powi(2) - distance.powi(2)).sqrt(); + let contact_y = 70.0 + (center_y - 70.0) * 60.0 / (60.0 + distance); + let depth = distance * 60.0 / (60.0 + distance); + let area = |y: f64| { + let u = (y - 10.0).clamp(-10.0, 0.0); + u * (100.0 - u * u).sqrt() + 100.0 * (u / 10.0).asin() + 20.0 * (y - 10.0).max(0.0) + }; + let n = 4000; + let h = depth / n as f64; + (0..=n) + .map(|i| { + let z = i as f64 * h; + let cut = 70.0 - (3600.0 - z * z).sqrt(); + let bevel = center_y + (contact_y - center_y) * z / depth; + let weight = if i == 0 || i == n { + 1.0 + } else if i % 2 == 0 { + 2.0 + } else { + 4.0 + }; + weight * (area(cut) - area(bevel)) + }) + .sum::() + * h + / 3.0 +} + +#[test] +fn chamfer_the_top_lip_at_a_tangent_wall_junction() { + let body = holder(); + let made = chamfer(&body, &[Vec3::new(10.0, 10.0, 60.0)], 2.0).unwrap(); + assert!(made.validity().is_empty(), "{:?}", made.validity()); + assert_eq!(made.crossed_face_loops().unwrap(), 0); + let history = made.history().expect("the chamfer retains exact face provenance"); + assert!(history.faces.iter().any(|f| f.origins.iter().any(|o| matches!(o, solidcraft_kernel::history::FaceOrigin::Edge { operand: 0, .. })))); + let mesh = |body: &Body| body.tessellate_with(0.0005, true).unwrap(); + let before = mesh(&body).measure().volume; + let after = mesh(&made); + let removed = before - after.measure().volume; + let expected = expected_removed(2.0); + eprintln!("removed {removed:.8} mm³, expected {expected:.8} mm³"); + assert!((removed - expected).abs() < 0.03, "removed {removed}, expected {expected}"); + assert!(!made.contains(Vec3::new(10.0, 9.5, 59.5)), "the old corner was removed"); + assert!(made.contains(Vec3::new(10.0, 7.0, 59.5)), "material behind the bevel remains"); + assert!(made.contains(Vec3::new(10.0, 10.0, 55.0)), "material below the bevel remains"); + // A closed mesh's signed volume is independent of the origin. + let volume_about = |origin: Vec3| { + after + .triangles + .iter() + .map(|t| { + let [a, b, c] = t.map(|i| after.positions[i as usize] - origin); + a.dot(b.cross(c)) / 6.0 + }) + .sum::() + }; + assert!((volume_about(Vec3::ZERO) - volume_about(Vec3::new(-100.0, 50.0, 30.0))).abs() < 0.01); +} + +#[test] +fn a_chamfer_that_uses_up_the_holder_top_is_refused() { + let body = holder(); + assert!(chamfer(&body, &[Vec3::new(10.0, 10.0, 60.0)], 30.0).is_err()); +} diff --git a/examples/regressions/chamfer_curved_holder_top_lip.json b/examples/regressions/chamfer_curved_holder_top_lip.json new file mode 100644 index 000000000..97118f494 --- /dev/null +++ b/examples/regressions/chamfer_curved_holder_top_lip.json @@ -0,0 +1,14 @@ +{ + "description":"Original reconstruction of issue #2408: a 20 mm wide slot, extruded 60 mm, cut with an R60 horizontal cylinder whose top lip meets the slot's tangent junction. Chamfer that top lip by 2 mm.", + "commands":[ + {"command":"sketch.create","params":{"plane":"XY"}}, + {"command":"sketch.slot.center_to_center","params":{"p0":[10,10],"p1":[10,70],"width":20}}, + {"command":"sketch.finish","params":{}}, + {"command":"solid.extrude","params":{"distance":60,"operation":"new"}}, + {"command":"sketch.create","params":{"plane":{"origin":[-1,0,0],"x_dir":[0,1,0],"y_dir":[0,0,1]}}}, + {"command":"sketch.circle.center","params":{"center":[70,60],"radius":60}}, + {"command":"sketch.finish","params":{}}, + {"command":"solid.extrude","params":{"distance":22,"operation":"cut"}}, + {"command":"solid.chamfer","params":{"distance":2,"edges":[[10,10,60]]}} + ] +} From 206fffdd80bbffd3dd865ec2065471c2af016317 Mon Sep 17 00:00:00 2001 From: SiroArt <152216922+SiroArt@users.noreply.github.com> Date: Tue, 20 Oct 2026 00:05:37 +0200 Subject: [PATCH 130/225] Agent chat tests: the two "cap" tests no longer share one folder (#2958) Thanks @SiroArt. --- crates/ui-egui/src/agent_chat/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/agent_chat/tests.rs b/crates/ui-egui/src/agent_chat/tests.rs index e0211bb9d..dc81a3cf8 100644 --- a/crates/ui-egui/src/agent_chat/tests.rs +++ b/crates/ui-egui/src/agent_chat/tests.rs @@ -1015,7 +1015,7 @@ fn files_wait_with_their_message_and_pictures_skip_an_agent_that_takes_none() { #[test] fn at_most_eight_files_on_a_message() { - let d = attachable("cap"); + let d = attachable("eight"); let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); for _ in 0..attach::MAX_FILES { attach_path(&mut app, &at(&d, "brief.md")).unwrap(); From 504d7c948860444ab4968dab62033f34f4f9e6c2 Mon Sep 17 00:00:00 2001 From: amolinari-autotex Date: Tue, 20 Oct 2026 00:07:32 +0200 Subject: [PATCH 131/225] Fix occurrence Move/Copy viewport gizmo input (#3014) (#3015) Thanks @amolinari-autotex. --- crates/ui-egui/src/browser.rs | 30 ++++++--- crates/ui-egui/src/canvas.rs | 6 ++ crates/ui-egui/src/occurrence_gizmo_tests.rs | 67 ++++++++++++++++++++ docs/occurrence-move-arrows.md | 7 ++ 4 files changed, 100 insertions(+), 10 deletions(-) create mode 100644 crates/ui-egui/src/occurrence_gizmo_tests.rs create mode 100644 docs/occurrence-move-arrows.md diff --git a/crates/ui-egui/src/browser.rs b/crates/ui-egui/src/browser.rs index 37d1c1f28..7e666d2e7 100644 --- a/crates/ui-egui/src/browser.rs +++ b/crates/ui-egui/src/browser.rs @@ -10,6 +10,10 @@ #[path = "occurrence_ui_tests.rs"] mod occurrence_ui_tests; +#[cfg(test)] +#[path = "occurrence_gizmo_tests.rs"] +mod occurrence_gizmo_tests; + #[path = "browser_model.rs"] mod model; @@ -1938,7 +1942,6 @@ fn occurrence_panel(app: &mut SolveApp, ui: &mut egui::Ui) { } }); }); - triad(app, ui, &mut m); if (m.translate, m.angles) != before { apply_occurrence_move(app, &m); } @@ -1987,17 +1990,20 @@ pub fn apply_occurrence_move(app: &mut SolveApp, m: &OccMove) { } /// The shared move triad at the occurrence's origin: arrows and squares move it, rings turn it. -fn triad(app: &mut SolveApp, ui: &mut egui::Ui, m: &mut OccMove) { +pub(crate) fn occurrence_triad_model(app: &SolveApp) -> Option { + let movement = app.tree.occurrence_move.as_ref()?; + let center = movement.pivot? + solidcraft_engine::geom::Vec3::new(movement.translate[0], movement.translate[1], movement.translate[2]); + Some(crate::gizmo::Triad { center, translate: true, rotate: true }) +} + +/// Occurrence handles belong to the viewport, not the clipped Move panel's child UI. +pub(crate) fn occurrence_triad(app: &mut SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj: &crate::viewport::Proj) { use crate::gizmo::{self, Change}; - let (Some(rect), Some(pivot)) = (app.viewport.rect, m.pivot) else { return }; - let proj = crate::viewport::projection(app, rect); - let center = pivot + solidcraft_engine::geom::Vec3::new(m.translate[0], m.translate[1], m.translate[2]); - let layer = egui::LayerId::new(egui::Order::Middle, egui::Id::new("sc_occ_triad_layer")); - let mut gui = ui.new_child(egui::UiBuilder::new().layer_id(layer).max_rect(rect)); - let painter = gui.painter().with_clip_rect(rect); - let t = gizmo::Triad { center, translate: true, rotate: true }; + let Some(mut m) = app.tree.occurrence_move.clone() else { return }; + let before = (m.translate, m.angles); + let Some(t) = occurrence_triad_model(app) else { return }; let step = crate::canvas::snap_step(app.cam.half_height()); - let Some(g) = gizmo::show(&mut gui, &painter, &proj, egui::Id::new("sc_occ_triad"), &t, step) else { return }; + let Some(g) = gizmo::show(ui, painter, proj, egui::Id::new("sc_occ_triad"), &t, step) else { return }; if g.started || m.drag0.is_none() { m.drag0 = Some((m.translate, m.angles)); } @@ -2013,6 +2019,10 @@ fn triad(app: &mut SolveApp, ui: &mut egui::Ui, m: &mut OccMove) { if g.done { m.drag0 = None; } + if (m.translate, m.angles) != before { + apply_occurrence_move(app, &m); + } + app.tree.occurrence_move = Some(m); } /// Dimensions of finished sketches whose dimensions are shown (Show Dimensions), drawn over the diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index a7178638f..a6944e88b 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -269,6 +269,9 @@ pub(crate) fn owns_pointer(app: &SolveApp, proj: &Proj, p: Pos2) -> bool { // The triad only registers an egui hit widget after a handle is under the pointer. // Test its geometry before navigation, including the first frame entering a handle. app.dialog.as_ref().and_then(|d| crate::dialogs_move::triad(app, d)).is_some_and(|t| crate::gizmo::contains_pointer(proj, &t, p)) + || (app.dialog.is_none() + && app.tool.is_none() + && crate::browser::occurrence_triad_model(app).is_some_and(|t| crate::gizmo::contains_pointer(proj, &t, p))) } /// Draw the manipulator and the value box (called by the viewport after the model is drawn). @@ -277,6 +280,9 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj if app.applying.is_some() { return; } + if app.dialog.is_none() && app.tool.is_none() { + crate::browser::occurrence_triad(app, ui, painter, proj); + } let Some(mut d) = app.dialog.take() else { return }; if matches!(d.kind, Kind::Assembly(_)) { crate::dialogs_assembly::overlay(app, painter, proj, &mut d); diff --git a/crates/ui-egui/src/occurrence_gizmo_tests.rs b/crates/ui-egui/src/occurrence_gizmo_tests.rs new file mode 100644 index 000000000..bbc237d3b --- /dev/null +++ b/crates/ui-egui/src/occurrence_gizmo_tests.rs @@ -0,0 +1,67 @@ +//! Regression for the existing occurrence Move/Copy arrows, independent of clipboard paste. +use crate::{ + context_menu::{self, Target}, + scenario::Harness, +}; +use serde_json::json; +use solidcraft_engine::{Sel, doc, geom::Vec3}; + +#[test] +fn occurrence_gizmo_drag_matches_numeric_input_and_preserves_joints_capture_and_undo() { + let mut h = Harness::new(); + let part = h.app.run("component.create", json!({"name":"Block"})).unwrap(); + let first = part["occurrence"].as_u64().unwrap(); + h.app.run("solid.box", json!({"length":10,"width":10,"height":10})).unwrap(); + h.app.run("component.activate", json!({"component":0})).unwrap(); + let second = h.app.run("occurrence.copy", json!({"occurrence":first,"translate":[50,0,0]})).unwrap()["occurrence"].as_u64().unwrap(); + h.app + .run( + "joint.create", + json!({"name":"Fixed peer","type":"rigid","flip":true,"a":{"occurrence":0,"point":[50,0,0]},"b":{"occurrence":second,"point":[50,0,0]}}), + ) + .unwrap(); + let joints = serde_json::to_value(&h.app.session.doc.assembly.joints).unwrap(); + let original = h.app.session.doc.to_json(); + let initial = doc::apply_point(&h.app.session.occurrence_placement(&[first]).unwrap().world, Vec3::ZERO); + let peer = doc::apply_point(&h.app.session.occurrence_placement(&[second]).unwrap().world, Vec3::ZERO); + h.app.cam.target = initial; + h.app.cam.distance = 100.; + h.frames(3); + let target = Target::Occurrence { path: vec![first] }; + let item = context_menu::items(&h.app, &target).into_iter().find(|item| item.id == "ui.moveOccurrence").unwrap(); + context_menu::run_item(&mut h.app, &item, egui::Pos2::ZERO); + h.frames(3); + let camera = h.app.cam; + let start = crate::gizmo::handle_point("x", Vec3::ZERO, 60.).unwrap(); + let end = start + Vec3::X * 12.; + h.step(&json!({"drag":[{"world":[start.x,start.y,start.z]},{"world":[end.x,end.y,end.z]}],"steps":12})).unwrap(); + h.frames(3); + let arrow = doc::apply_point(&h.app.session.occurrence_placement(&[first]).unwrap().world, Vec3::ZERO); + assert!(arrow.x > initial.x + 1., "visible arrow must actually move this occurrence: {initial:?}->{arrow:?}"); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.doc.to_json(), original, "drag is a pending position"); + assert_eq!(doc::apply_point(&h.app.session.occurrence_placement(&[second]).unwrap().world, Vec3::ZERO), peer); + assert_eq!(serde_json::to_value(&h.app.session.doc.assembly.joints).unwrap(), joints); + h.app.run("component.revert_position", json!({"occurrences":[first]})).unwrap(); + h.app.tree.occurrence_move.as_mut().unwrap().translate = [0.; 3]; + h.frames(2); + let at = h.call("ui.at", json!({"handle":"occurrence-move:distance:0"})); + h.call("ui.click", json!({"x":at["result"][0],"y":at["result"][1],"double":true})); + h.frames(2); + h.step(&json!({"key":"A","cmd":true})).unwrap(); + h.step(&json!({"text":format!("{}",arrow.x-initial.x)})).unwrap(); + h.step(&json!({"key":"Enter"})).unwrap(); + h.frames(3); + let numeric = doc::apply_point(&h.app.session.occurrence_placement(&[first]).unwrap().world, Vec3::ZERO); + assert!((numeric - arrow).len() < 1e-6, "numeric and arrow routes must agree: {numeric:?}, {arrow:?}"); + let undo = h.app.session.undo.len(); + h.app.run("component.capture_position", json!({})).unwrap(); + h.app.tree.occurrence_move = None; + assert_eq!(h.app.session.undo.len(), undo + 1); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.to_json(), original); + h.app.run("edit.redo", json!({})).unwrap(); + assert!((doc::apply_point(&h.app.session.occurrence_placement(&[first]).unwrap().world, Vec3::ZERO) - numeric).len() < 1e-6); + assert_eq!(serde_json::to_value(&h.app.session.doc.assembly.joints).unwrap(), joints); + assert!(!h.app.session.selection.contains(&Sel::Occurrence { path: vec![second] })); +} diff --git a/docs/occurrence-move-arrows.md b/docs/occurrence-move-arrows.md new file mode 100644 index 000000000..f41cf91bc --- /dev/null +++ b/docs/occurrence-move-arrows.md @@ -0,0 +1,7 @@ +# Occurrence Move/Copy arrows + +Move/Copy draws and processes occurrence translation and rotation handles in the viewport that owns their pointer events. The numeric fields continue to use the same pending placement state. Capture Position commits the placement; Revert Position discards it. + +This repairs ordinary occurrence editing as well as pasted linked designs. It does not change joint definitions or introduce free dragging of arbitrary faces. The clipboard pointer-placement contribution is separate (#2433); the arrow input repair is tracked in #3014 and #3015. + +The regression exercises an ordinary occurrence, compares an actual viewport arrow drag with numeric input, checks that a second constrained occurrence and its joint remain unchanged, and checks capture, undo, and redo. It does not require clipboard functionality. From ee67ed53af9171fde3e37149fdd9974731c0e8ab Mon Sep 17 00:00:00 2001 From: rlartot <94693724+rlartot@users.noreply.github.com> Date: Tue, 20 Oct 2026 01:14:01 +0200 Subject: [PATCH 132/225] STEP export no longer hangs on a box with a screw hole (#1985) (#2243) * claim: #1985 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L15TLCjpXsQdp8ovC4ZacH * STEP export no longer hangs on a box with a screw hole (#1985) The export reads its own STEP text back, and meshing the read-back screw hole never finished. On a seam cylinder the boundary walk projected points to angles up to 5e7 rad apart and moved each by two turns at most, so the 11-point loop spanned millions of turns and the polyline closing it across the seam had 4.3 million points. Each projected parameter is now brought to within half a period of the point before it, whatever the gap. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L15TLCjpXsQdp8ovC4ZacH * Second #1985 regression: the reporter's flanged enclosure The issue's reporter delta-debugged a second design whose STEP export hung on main: a flanged enclosure with two standoffs and no screw hole. It hangs without the get_mindiff change and reads back with 29 faces and the same volume with it. Both tests share the read-back checks. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L15TLCjpXsQdp8ovC4ZacH --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: bherbruck --- crates/engine/src/boolean_regression_tests.rs | 43 +++++++++++++++++++ .../step_export_flanged_enclosure.json | 29 +++++++++++++ .../step_export_screw_hole_enclosure.json | 38 ++++++++++++++++ vendor/README.md | 6 +++ .../src/tessellation/triangulation.rs | 16 ++++--- 5 files changed, 126 insertions(+), 6 deletions(-) create mode 100644 examples/regressions/step_export_flanged_enclosure.json create mode 100644 examples/regressions/step_export_screw_hole_enclosure.json diff --git a/crates/engine/src/boolean_regression_tests.rs b/crates/engine/src/boolean_regression_tests.rs index aca9a1f6e..66dfc17ea 100644 --- a/crates/engine/src/boolean_regression_tests.rs +++ b/crates/engine/src/boolean_regression_tests.rs @@ -45,6 +45,49 @@ fn volume(s: &Session, body: &str) -> f64 { s.model.state().body(body).map(|b| solidcraft_kernel::measure(&b.body).unwrap().volume).unwrap_or(0.0) } +/// #1985: the STEP export of a small enclosure never finished. The export reads its own file +/// back, and meshing the screw hole's seam cylinder never ended: the boundary walk took +/// projected angles millions of turns apart. The file is written, reads back cleanly, and holds +/// the same solid. +#[test] +fn step_export_of_an_enclosure_with_a_screw_hole_finishes_and_reads_back() { + let s = replay(include_str!("../../../examples/regressions/step_export_screw_hole_enclosure.json")); + let state = s.model.state(); + let body = &state.body("Unterteil").unwrap().body; + // 27 faces; the kernel splits each of the three whole turns (the hole, two standoffs) in two. + assert_eq!(body.face_count(), 30); + let (text, file_faces) = read_back(&s, body); + assert_eq!(text.matches("CYLINDRICAL_SURFACE(").count(), 7, "the seven round faces stay cylinders"); + assert_eq!(file_faces, 27); +} + +/// #1985, the reporter's second reproduction: the same walk on a standoff of a flanged +/// enclosure without a screw hole. +#[test] +fn step_export_of_a_flanged_enclosure_finishes_and_reads_back() { + let s = replay(include_str!("../../../examples/regressions/step_export_flanged_enclosure.json")); + let state = s.model.state(); + let (_, file_faces) = read_back(&s, &state.body("Unterteil").unwrap().body); + assert_eq!(file_faces, 29); +} + +/// The body's STEP text, which reads back without warnings as one closed solid of the same +/// volume and area, and the number of faces the file holds. +fn read_back(s: &Session, body: &solidcraft_kernel::Body) -> (String, usize) { + assert!(s.model.results.iter().all(|r| r.error.is_none()), "{:?}", s.model.results); + let text = solidcraft_kernel::step_export(&[body], "SolidCraft").unwrap(); + let imp = solidcraft_kernel::step_import(&text).unwrap(); + assert!(imp.warnings.is_empty(), "{:?}", imp.warnings); + assert_eq!(imp.bodies.len(), 1); + let back = &imp.bodies[0]; + assert!(back.closed); + let (a, b) = (solidcraft_kernel::measure(body).unwrap(), solidcraft_kernel::measure(&back.body).unwrap()); + assert!((a.volume - b.volume).abs() < 1e-3 * a.volume, "volume {} read back as {}", a.volume, b.volume); + assert!((a.area - b.area).abs() < 1e-3 * a.area, "area {} read back as {}", a.area, b.area); + println!("#1985 volume {:.3} / {:.3} mm³; area {:.3} / {:.3} mm²", a.volume, b.volume, a.area, b.area); + (text, back.file_faces) +} + /// #2059: tabs exactly as wide as their supporting ribs share the ribs' side /// planes. The base's remote conical chamfer must not prevent their join. #[test] diff --git a/examples/regressions/step_export_flanged_enclosure.json b/examples/regressions/step_export_flanged_enclosure.json new file mode 100644 index 000000000..e3e98de71 --- /dev/null +++ b/examples/regressions/step_export_flanged_enclosure.json @@ -0,0 +1,29 @@ +{ + "description": "Second reproduction for #1985, delta-debugged by the issue's reporter from the same enclosure with wall_thickness 3: a rounded box with a flange, an inner cut, a corner gusset and two standoffs, no screw hole. Its STEP export hung on main 675c8654 (but not on 0.14.0): the same boundary walk took a standoff's projected angles millions of turns apart.", + "commands": [ + {"command": "parameters.add", "params": {"expression": "74", "name": "interior_width", "unit": "mm"}}, + {"command": "parameters.add", "params": {"expression": "73", "name": "interior_depth", "unit": "mm"}}, + {"command": "parameters.add", "params": {"expression": "30", "name": "interior_height", "unit": "mm"}}, + {"command": "parameters.add", "params": {"expression": "3", "name": "wall_thickness", "unit": "mm"}}, + {"command": "parameters.add", "params": {"expression": "2.5", "name": "bottom_thickness", "unit": "mm"}}, + {"command": "parameters.add", "params": {"expression": "3", "name": "corner_radius", "unit": "mm"}}, + {"command": "parameters.add", "params": {"expression": "8", "name": "gusset_size", "unit": "mm"}}, + {"command": "parameters.add", "params": {"expression": "10", "name": "flange_extend", "unit": "mm"}}, + {"command": "parameters.add", "params": {"expression": "5", "name": "pin_base_d", "unit": "mm"}}, + {"command": "parameters.add", "params": {"expression": "3", "name": "standoff_height", "unit": "mm"}}, + {"command": "parameters.add", "params": {"expression": "interior_width + 2 * wall_thickness", "name": "outer_width", "unit": "mm"}}, + {"command": "parameters.add", "params": {"expression": "interior_depth + 2 * wall_thickness", "name": "outer_depth", "unit": "mm"}}, + {"command": "parameters.add", "params": {"expression": "interior_height + bottom_thickness", "name": "outer_height", "unit": "mm"}}, + {"command": "parameters.add", "params": {"expression": "outer_width + 2 * flange_extend", "name": "flange_total_width", "unit": "mm"}}, + {"command": "parameters.add", "params": {"expression": "(interior_width - 53.34) / 2", "name": "board_offset_x", "unit": "mm"}}, + {"command": "parameters.add", "params": {"expression": "1", "name": "board_offset_y", "unit": "mm"}}, + {"command": "timeline.add", "params": {"feature": {"id": 1, "name": "Koerper_Skizze", "plane": {"name": "XY", "type": "origin"}, "sketch": {"constraints": [{"id": "k1", "l": 0, "type": "horizontal"}, {"id": "k2", "l": 2, "type": "horizontal"}, {"id": "k3", "l": 1, "type": "vertical"}, {"id": "k4", "l": 3, "type": "vertical"}, {"id": "k5", "p": 0, "q": 1, "type": "coincident"}, {"c": 0, "id": "k6", "p": 1, "type": "point_on_curve"}, {"c": 3, "id": "k7", "p": 1, "type": "point_on_curve"}, {"a": 0, "b": 4, "id": "k8", "type": "tangent"}, {"a": 3, "b": 4, "id": "k9", "type": "tangent"}, {"c": 4, "id": "k10", "param": "d1", "type": "radius", "value": 3.0}, {"a": 0, "b": 5, "id": "k11", "type": "tangent"}, {"a": 1, "b": 5, "id": "k12", "type": "tangent"}, {"a": 4, "b": 5, "id": "k13", "type": "equal"}, {"a": 1, "b": 6, "id": "k14", "type": "tangent"}, {"a": 2, "b": 6, "id": "k15", "type": "tangent"}, {"a": 4, "b": 6, "id": "k16", "type": "equal"}, {"a": 2, "b": 7, "id": "k17", "type": "tangent"}, {"a": 3, "b": 7, "id": "k18", "type": "tangent"}, {"a": 4, "b": 7, "id": "k19", "type": "equal"}, {"id": "k20", "l": 0, "param": "d2", "type": "length", "value": 74.0}, {"id": "k21", "l": 3, "param": "d3", "type": "length", "value": 73.0}, {"a": 3, "b": 8, "id": "k22", "type": "collinear"}, {"a": 0, "b": 9, "id": "k23", "type": "collinear"}], "counters": {"a": 4, "corner": 1, "j": 2, "k": 23, "l": 6, "p": 16}, "curves": [{"a": 2, "b": 5, "construction": false, "id": "l1", "type": "line"}, {"a": 6, "b": 8, "construction": false, "id": "l2", "type": "line"}, {"a": 9, "b": 11, "construction": false, "id": "l3", "type": "line"}, {"a": 12, "b": 3, "construction": false, "id": "l4", "type": "line"}, {"a": 3, "b": 2, "c": 4, "construction": false, "id": "a1", "type": "arc"}, {"a": 5, "b": 6, "c": 7, "construction": false, "id": "a2", "type": "arc"}, {"a": 8, "b": 9, "c": 10, "construction": false, "id": "a3", "type": "arc"}, {"a": 11, "b": 12, "c": 13, "construction": false, "id": "a4", "type": "arc"}, {"a": 14, "b": 15, "construction": true, "id": "l5", "link": "j1", "type": "line"}, {"a": 16, "b": 17, "construction": true, "id": "l6", "link": "j2", "type": "line"}], "links": [{"id": "j1", "kind": "project", "source": {"name": "y", "type": "sketch_axis"}}, {"id": "j2", "kind": "project", "source": {"name": "x", "type": "sketch_axis"}}], "points": [{"fixed": true, "id": "origin", "pos": [0.0, 0.0]}, {"fixed": false, "id": "corner1", "pos": [0.0, 0.0]}, {"fixed": false, "id": "p5", "pos": [3.0, 0.0]}, {"fixed": false, "id": "p6", "pos": [0.0, 3.0]}, {"fixed": false, "id": "a1.center", "pos": [3.0, 3.0]}, {"fixed": false, "id": "p7", "pos": [77.0, 0.0]}, {"fixed": false, "id": "p8", "pos": [80.0, 3.0]}, {"fixed": false, "id": "a2.center", "pos": [77.0, 3.0]}, {"fixed": false, "id": "p9", "pos": [80.0, 76.0]}, {"fixed": false, "id": "p10", "pos": [77.0, 79.0]}, {"fixed": false, "id": "a3.center", "pos": [77.0, 76.0]}, {"fixed": false, "id": "p11", "pos": [3.0, 79.0]}, {"fixed": false, "id": "p12", "pos": [0.0, 76.0]}, {"fixed": false, "id": "a4.center", "pos": [3.0, 76.0]}, {"fixed": true, "id": "p13", "link": "j1", "pos": [0.0, -100.0]}, {"fixed": true, "id": "p14", "link": "j1", "pos": [0.0, 100.0]}, {"fixed": true, "id": "p15", "link": "j2", "pos": [-100.0, 0.0]}, {"fixed": true, "id": "p16", "link": "j2", "pos": [100.0, 0.0]}]}, "suppressed": false, "type": "sketch"}, "params": [{"expression": "corner_radius", "name": "d1", "unit": "mm"}, {"expression": "outer_width - 2*corner_radius", "name": "d2", "unit": "mm"}, {"expression": "outer_depth - 2*corner_radius", "name": "d3", "unit": "mm"}]}}, + {"command": "timeline.add", "params": {"feature": {"body_names": ["Unterteil"], "extent": {"convention": "total_distance", "direction": "positive", "distance": "outer_height"}, "id": 2, "name": "Koerper", "operation": "new_body", "param_names": ["d4"], "profiles": {"type": "all"}, "sketch": 1, "suppressed": false, "type": "extrude"}}}, + {"command": "timeline.add", "params": {"feature": {"id": 3, "name": "Flansch_Skizze", "plane": {"name": "XY", "type": "origin"}, "sketch": {"constraints": [{"id": "k1", "l": 0, "type": "horizontal"}, {"id": "k2", "l": 2, "type": "horizontal"}, {"id": "k3", "l": 1, "type": "vertical"}, {"id": "k4", "l": 3, "type": "vertical"}, {"a": 0, "b": 4, "id": "k5", "type": "tangent"}, {"a": 3, "b": 4, "id": "k6", "type": "tangent"}, {"c": 4, "id": "k7", "param": "d5", "type": "radius", "value": 3.0}, {"a": 0, "b": 5, "id": "k8", "type": "tangent"}, {"a": 1, "b": 5, "id": "k9", "type": "tangent"}, {"a": 4, "b": 5, "id": "k10", "type": "equal"}, {"a": 1, "b": 6, "id": "k11", "type": "tangent"}, {"a": 2, "b": 6, "id": "k12", "type": "tangent"}, {"a": 4, "b": 6, "id": "k13", "type": "equal"}, {"a": 2, "b": 7, "id": "k14", "type": "tangent"}, {"a": 3, "b": 7, "id": "k15", "type": "tangent"}, {"a": 4, "b": 7, "id": "k16", "type": "equal"}, {"id": "k17", "l": 0, "param": "d6", "type": "length", "value": 94.0}, {"id": "k18", "l": 3, "param": "d7", "type": "length", "value": 73.0}, {"c": 8, "id": "k19", "p": 1, "type": "point_on_curve"}, {"id": "k20", "p": 0, "param": "d8", "q": 2, "type": "distance_x", "value": 10.0}], "counters": {"a": 4, "j": 1, "k": 20, "l": 5, "p": 14}, "curves": [{"a": 1, "b": 4, "construction": false, "id": "l1", "type": "line"}, {"a": 5, "b": 7, "construction": false, "id": "l2", "type": "line"}, {"a": 8, "b": 10, "construction": false, "id": "l3", "type": "line"}, {"a": 11, "b": 2, "construction": false, "id": "l4", "type": "line"}, {"a": 2, "b": 1, "c": 3, "construction": false, "id": "a1", "type": "arc"}, {"a": 4, "b": 5, "c": 6, "construction": false, "id": "a2", "type": "arc"}, {"a": 7, "b": 8, "c": 9, "construction": false, "id": "a3", "type": "arc"}, {"a": 10, "b": 11, "c": 12, "construction": false, "id": "a4", "type": "arc"}, {"a": 13, "b": 14, "construction": true, "id": "l5", "link": "j1", "type": "line"}], "links": [{"id": "j1", "kind": "project", "source": {"name": "x", "type": "sketch_axis"}}], "points": [{"fixed": true, "id": "origin", "pos": [0.0, 0.0]}, {"fixed": false, "id": "p5", "pos": [-7.000000000421964, -9.639689500501904e-11]}, {"fixed": false, "id": "p6", "pos": [-10.000000000100329, 2.999999999497484]}, {"fixed": false, "id": "a1.center", "pos": [-7.000000000350304, 2.999999999572889]}, {"fixed": false, "id": "p7", "pos": [86.99999999951254, -1.1049218029226348e-10]}, {"fixed": false, "id": "p8", "pos": [89.99999999908958, 2.99999999957527]}, {"fixed": false, "id": "a2.center", "pos": [86.99999999945408, 2.9999999995765445]}, {"fixed": false, "id": "p9", "pos": [89.99999999905073, 75.99999999922994]}, {"fixed": false, "id": "p10", "pos": [86.99999999926114, 78.99999999903463]}, {"fixed": false, "id": "a3.center", "pos": [86.99999999926523, 75.99999999923355]}, {"fixed": false, "id": "p11", "pos": [-7.0000000004280105, 78.99999999906302]}, {"fixed": false, "id": "p12", "pos": [-10.000000000111083, 75.99999999942932]}, {"fixed": false, "id": "a4.center", "pos": [-7.000000000426023, 75.99999999936931]}, {"fixed": true, "id": "p13", "link": "j1", "pos": [-100.0, 0.0]}, {"fixed": true, "id": "p14", "link": "j1", "pos": [100.0, 0.0]}]}, "suppressed": false, "type": "sketch"}, "params": [{"expression": "corner_radius", "name": "d5", "unit": "mm"}, {"expression": "flange_total_width - 2*corner_radius", "name": "d6", "unit": "mm"}, {"expression": "outer_depth - 2*corner_radius", "name": "d7", "unit": "mm"}, {"expression": "flange_extend", "name": "d8", "unit": "mm"}]}}, + {"command": "timeline.add", "params": {"feature": {"extent": {"convention": "total_distance", "direction": "positive", "distance": "bottom_thickness"}, "id": 4, "name": "Flansch", "operation": "join", "param_names": ["d9"], "profiles": {"type": "all"}, "sketch": 3, "suppressed": false, "targets": ["Unterteil"], "type": "extrude"}}}, + {"command": "timeline.add", "params": {"feature": {"corner": ["wall_thickness", "wall_thickness", "bottom_thickness"], "height": "interior_height + 1", "id": 5, "length": "interior_width", "name": "Innenraum", "operation": "cut", "param_names": ["d10", "d11", "d12"], "participants": ["Unterteil"], "suppressed": false, "type": "box", "width": "interior_depth"}}}, + {"command": "timeline.add", "params": {"feature": {"corner": ["wall_thickness + interior_width - gusset_size", "wall_thickness + interior_depth - gusset_size", "bottom_thickness"], "height": "interior_height", "id": 9, "length": "gusset_size", "name": "Gusset_11", "operation": "join", "param_names": ["d22", "d23", "d24"], "participants": ["Unterteil"], "suppressed": false, "type": "box", "width": "gusset_size"}}}, + {"command": "timeline.add", "params": {"feature": {"axis": [0.0, 0.0, 1.0], "base": ["wall_thickness + board_offset_x + 17.78", "wall_thickness + board_offset_y + 66.04", "bottom_thickness"], "height": "standoff_height", "id": 18, "name": "PinSockel_2", "operation": "join", "param_names": ["d41", "d42"], "participants": ["Unterteil"], "radius": "(pin_base_d) / 2", "suppressed": false, "type": "cylinder"}}}, + {"command": "timeline.add", "params": {"feature": {"axis": [0.0, 0.0, 1.0], "base": ["wall_thickness + board_offset_x + 45.72", "wall_thickness + board_offset_y + 66.04", "bottom_thickness"], "height": "standoff_height", "id": 20, "name": "PinSockel_3", "operation": "join", "param_names": ["d45", "d46"], "participants": ["Unterteil"], "radius": "(pin_base_d) / 2", "suppressed": false, "type": "cylinder"}}} + ] +} diff --git a/examples/regressions/step_export_screw_hole_enclosure.json b/examples/regressions/step_export_screw_hole_enclosure.json new file mode 100644 index 000000000..79a595724 --- /dev/null +++ b/examples/regressions/step_export_screw_hole_enclosure.json @@ -0,0 +1,38 @@ +{ + "description": "Reproduction for #1985, from the script in the public issue (a small enclosure: rounded box, inner cut, a corner gusset with a screw hole, two standoffs and a USB cut-out), with interior_height 35 instead of 30. Exporting it as STEP never finished: the export reads its own file back, and meshing the screw hole's seam cylinder never ended, because the boundary walk let projected angles millions of turns apart through.", + "commands": [ + {"command": "parameters.add", "params": {"expression": "74", "name": "interior_width", "unit": "mm"}}, + {"command": "parameters.add", "params": {"expression": "73", "name": "interior_depth", "unit": "mm"}}, + {"command": "parameters.add", "params": {"expression": "35", "name": "interior_height", "unit": "mm"}}, + {"command": "parameters.add", "params": {"expression": "2", "name": "wall_thickness", "unit": "mm"}}, + {"command": "parameters.add", "params": {"expression": "2.5", "name": "bottom_thickness", "unit": "mm"}}, + {"command": "parameters.add", "params": {"expression": "3", "name": "corner_radius", "unit": "mm"}}, + {"command": "parameters.add", "params": {"expression": "2", "name": "lid_thickness", "unit": "mm"}}, + {"command": "parameters.add", "params": {"expression": "1", "name": "lid_pad_height", "unit": "mm"}}, + {"command": "parameters.add", "params": {"expression": "0.3", "name": "lid_pad_gap", "unit": "mm"}}, + {"command": "parameters.add", "params": {"expression": "8", "name": "gusset_size", "unit": "mm"}}, + {"command": "parameters.add", "params": {"expression": "2.5", "name": "gusset_screw_d", "unit": "mm"}}, + {"command": "parameters.add", "params": {"expression": "8", "name": "gusset_screw_depth", "unit": "mm"}}, + {"command": "parameters.add", "params": {"expression": "10", "name": "flange_extend", "unit": "mm"}}, + {"command": "parameters.add", "params": {"expression": "4.5", "name": "flange_hole_d", "unit": "mm"}}, + {"command": "parameters.add", "params": {"expression": "5", "name": "pin_base_d", "unit": "mm"}}, + {"command": "parameters.add", "params": {"expression": "3", "name": "standoff_height", "unit": "mm"}}, + {"command": "parameters.add", "params": {"expression": "2", "name": "pin_d", "unit": "mm"}}, + {"command": "parameters.add", "params": {"expression": "1.6", "name": "pcb_thickness", "unit": "mm"}}, + {"command": "parameters.add", "params": {"expression": "2", "name": "pin_above", "unit": "mm"}}, + {"command": "parameters.add", "params": {"expression": "interior_width + 2 * wall_thickness", "name": "outer_width", "unit": "mm"}}, + {"command": "parameters.add", "params": {"expression": "interior_depth + 2 * wall_thickness", "name": "outer_depth", "unit": "mm"}}, + {"command": "parameters.add", "params": {"expression": "interior_height + bottom_thickness", "name": "outer_height", "unit": "mm"}}, + {"command": "parameters.add", "params": {"expression": "outer_width + 2 * flange_extend", "name": "flange_total_width", "unit": "mm"}}, + {"command": "parameters.add", "params": {"expression": "(interior_width - 53.34) / 2", "name": "board_offset_x", "unit": "mm"}}, + {"command": "parameters.add", "params": {"expression": "1", "name": "board_offset_y", "unit": "mm"}}, + {"command": "timeline.add", "params": {"feature": {"id": 1, "name": "Koerper_Skizze", "plane": {"name": "XY", "type": "origin"}, "sketch": {"constraints": [{"id": "k1", "l": 0, "type": "horizontal"}, {"id": "k2", "l": 2, "type": "horizontal"}, {"id": "k3", "l": 1, "type": "vertical"}, {"id": "k4", "l": 3, "type": "vertical"}, {"id": "k5", "p": 0, "q": 1, "type": "coincident"}, {"c": 0, "id": "k6", "p": 1, "type": "point_on_curve"}, {"c": 3, "id": "k7", "p": 1, "type": "point_on_curve"}, {"a": 0, "b": 4, "id": "k8", "type": "tangent"}, {"a": 3, "b": 4, "id": "k9", "type": "tangent"}, {"c": 4, "id": "k10", "param": "d1", "type": "radius", "value": 3.0}, {"a": 0, "b": 5, "id": "k11", "type": "tangent"}, {"a": 1, "b": 5, "id": "k12", "type": "tangent"}, {"a": 4, "b": 5, "id": "k13", "type": "equal"}, {"a": 1, "b": 6, "id": "k14", "type": "tangent"}, {"a": 2, "b": 6, "id": "k15", "type": "tangent"}, {"a": 4, "b": 6, "id": "k16", "type": "equal"}, {"a": 2, "b": 7, "id": "k17", "type": "tangent"}, {"a": 3, "b": 7, "id": "k18", "type": "tangent"}, {"a": 4, "b": 7, "id": "k19", "type": "equal"}, {"id": "k20", "l": 0, "param": "d2", "type": "length", "value": 74.0}, {"id": "k21", "l": 3, "param": "d3", "type": "length", "value": 73.0}, {"a": 3, "b": 8, "id": "k22", "type": "collinear"}, {"a": 0, "b": 9, "id": "k23", "type": "collinear"}], "counters": {"a": 4, "corner": 1, "j": 2, "k": 23, "l": 6, "p": 16}, "curves": [{"a": 2, "b": 5, "construction": false, "id": "l1", "type": "line"}, {"a": 6, "b": 8, "construction": false, "id": "l2", "type": "line"}, {"a": 9, "b": 11, "construction": false, "id": "l3", "type": "line"}, {"a": 12, "b": 3, "construction": false, "id": "l4", "type": "line"}, {"a": 3, "b": 2, "c": 4, "construction": false, "id": "a1", "type": "arc"}, {"a": 5, "b": 6, "c": 7, "construction": false, "id": "a2", "type": "arc"}, {"a": 8, "b": 9, "c": 10, "construction": false, "id": "a3", "type": "arc"}, {"a": 11, "b": 12, "c": 13, "construction": false, "id": "a4", "type": "arc"}, {"a": 14, "b": 15, "construction": true, "id": "l5", "link": "j1", "type": "line"}, {"a": 16, "b": 17, "construction": true, "id": "l6", "link": "j2", "type": "line"}], "links": [{"id": "j1", "kind": "project", "source": {"name": "y", "type": "sketch_axis"}}, {"id": "j2", "kind": "project", "source": {"name": "x", "type": "sketch_axis"}}], "points": [{"fixed": true, "id": "origin", "pos": [0.0, 0.0]}, {"fixed": false, "id": "corner1", "pos": [0.0, 0.0]}, {"fixed": false, "id": "p5", "pos": [3.0, 0.0]}, {"fixed": false, "id": "p6", "pos": [0.0, 3.0]}, {"fixed": false, "id": "a1.center", "pos": [3.0, 3.0]}, {"fixed": false, "id": "p7", "pos": [77.0, 0.0]}, {"fixed": false, "id": "p8", "pos": [80.0, 3.0]}, {"fixed": false, "id": "a2.center", "pos": [77.0, 3.0]}, {"fixed": false, "id": "p9", "pos": [80.0, 76.0]}, {"fixed": false, "id": "p10", "pos": [77.0, 79.0]}, {"fixed": false, "id": "a3.center", "pos": [77.0, 76.0]}, {"fixed": false, "id": "p11", "pos": [3.0, 79.0]}, {"fixed": false, "id": "p12", "pos": [0.0, 76.0]}, {"fixed": false, "id": "a4.center", "pos": [3.0, 76.0]}, {"fixed": true, "id": "p13", "link": "j1", "pos": [0.0, -100.0]}, {"fixed": true, "id": "p14", "link": "j1", "pos": [0.0, 100.0]}, {"fixed": true, "id": "p15", "link": "j2", "pos": [-100.0, 0.0]}, {"fixed": true, "id": "p16", "link": "j2", "pos": [100.0, 0.0]}]}, "suppressed": false, "type": "sketch"}, "params": [{"expression": "corner_radius", "name": "d1", "unit": "mm"}, {"expression": "outer_width - 2*corner_radius", "name": "d2", "unit": "mm"}, {"expression": "outer_depth - 2*corner_radius", "name": "d3", "unit": "mm"}]}}, + {"command": "timeline.add", "params": {"feature": {"body_names": ["Unterteil"], "extent": {"convention": "total_distance", "direction": "positive", "distance": "outer_height"}, "id": 2, "name": "Koerper", "operation": "new_body", "param_names": ["d4"], "profiles": {"type": "all"}, "sketch": 1, "suppressed": false, "type": "extrude"}}}, + {"command": "timeline.add", "params": {"feature": {"corner": ["wall_thickness", "wall_thickness", "bottom_thickness"], "height": "interior_height + 1", "id": 5, "length": "interior_width", "name": "Innenraum", "operation": "cut", "param_names": ["d10", "d11", "d12"], "participants": ["Unterteil"], "suppressed": false, "type": "box", "width": "interior_depth"}}}, + {"command": "timeline.add", "params": {"feature": {"corner": ["wall_thickness + interior_width - gusset_size", "wall_thickness + interior_depth - gusset_size", "bottom_thickness"], "height": "interior_height", "id": 9, "length": "gusset_size", "name": "Gusset_11", "operation": "join", "param_names": ["d22", "d23", "d24"], "participants": ["Unterteil"], "suppressed": false, "type": "box", "width": "gusset_size"}}}, + {"command": "timeline.add", "params": {"feature": {"axis": [0.0, 0.0, 1.0], "base": ["wall_thickness + interior_width - gusset_size/2", "wall_thickness + interior_depth - gusset_size/2", "outer_height - gusset_screw_depth"], "height": "gusset_screw_depth + 1", "id": 13, "name": "Kernloch_11", "operation": "cut", "param_names": ["d31", "d32"], "participants": ["Unterteil"], "radius": "(gusset_screw_d) / 2", "suppressed": false, "type": "cylinder"}}}, + {"command": "timeline.add", "params": {"feature": {"axis": [0.0, 0.0, 1.0], "base": ["wall_thickness + board_offset_x + 17.78", "wall_thickness + board_offset_y + 66.04", "bottom_thickness"], "height": "standoff_height", "id": 18, "name": "PinSockel_2", "operation": "join", "param_names": ["d41", "d42"], "participants": ["Unterteil"], "radius": "(pin_base_d) / 2", "suppressed": false, "type": "cylinder"}}}, + {"command": "timeline.add", "params": {"feature": {"axis": [0.0, 0.0, 1.0], "base": ["wall_thickness + board_offset_x + 45.72", "wall_thickness + board_offset_y + 66.04", "bottom_thickness"], "height": "standoff_height", "id": 20, "name": "PinSockel_3", "operation": "join", "param_names": ["d45", "d46"], "participants": ["Unterteil"], "radius": "(pin_base_d) / 2", "suppressed": false, "type": "cylinder"}}}, + {"command": "timeline.add", "params": {"feature": {"corner": ["wall_thickness + board_offset_x + 9", -1.0, "bottom_thickness + 2.5"], "height": "6", "id": 22, "length": "10", "name": "Ausschnitt_MicroUSB", "operation": "cut", "param_names": ["d49", "d50", "d51"], "participants": ["Unterteil"], "suppressed": false, "type": "box", "width": "wall_thickness + 2"}}} + ] +} diff --git a/vendor/README.md b/vendor/README.md index 25ac34228..cc622f620 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -131,6 +131,12 @@ Changes: - `tessellation/triangulation.rs`: meshed faces and edges are built unchecked: faces whose loop runs along a seam edge both ways and closed edges (a full circle on one vertex) are valid, but the debug-build checks rejected them (debug builds could not mesh them). +- `tessellation/triangulation.rs`: on a periodic surface, a boundary point's projected parameter + is moved by whole periods to within half a period of the point before it, however many periods + away the search put it (it was moved by two periods at most). A hinted search on a revolved + surface can return an angle millions of turns from its hint; the loop then spanned those turns, + the polyline closing it across the seam had millions of points, and meshing never finished, + which hung the STEP export that reads its own file back (#1985). - `tessellation/triangulation.rs`: parameter searches that land outside a surface's bounded, non-periodic domain are rejected (a hinted B-spline search can run off and extrapolate to thousands of parameter units, and meshing that grid never finishes); the last-resort nearest diff --git a/vendor/truck-meshalgo/src/tessellation/triangulation.rs b/vendor/truck-meshalgo/src/tessellation/triangulation.rs index 60b78731e..0d28b316b 100644 --- a/vendor/truck-meshalgo/src/tessellation/triangulation.rs +++ b/vendor/truck-meshalgo/src/tessellation/triangulation.rs @@ -621,13 +621,17 @@ impl PolyBoundaryPiece { } } -fn abs_diff(previous: f64) -> impl Fn(&f64, &f64) -> std::cmp::Ordering { - let f = move |x: &f64| f64::abs(x - previous); - move |x: &f64, y: &f64| f(x).partial_cmp(&f(y)).unwrap() -} +/// SolidCraft: `u` moved by whole periods `up` to within half a period of `u0`, however many +/// periods away it is (on a tie, the lower one, as before). A hinted search on a revolved +/// surface can return an angle millions of turns from its hint, the same point; moving it by two +/// periods at most left a face's boundary loop spanning those turns, and the polyline that closes +/// it across the seam then had millions of points: meshing it never finished (#1985). fn get_mindiff(u: f64, u0: f64, up: f64) -> f64 { - let closure = |i| u + i as f64 * up; - (-2..=2).map(closure).min_by(abs_diff(u0)).unwrap() + let d = (u - u0).rem_euclid(up); + if !d.is_finite() { + return u; + } + u0 + if d >= 0.5 * up { d - up } else { d } } /// SolidCraft: the second field holds each loop's parameter box, so `include` skips loops that From a108ffac380887196430846468f03eaea96d50fa Mon Sep 17 00:00:00 2001 From: HiroKenEz <59478073+HiroKenEz@users.noreply.github.com> Date: Tue, 20 Oct 2026 01:14:05 +0200 Subject: [PATCH 133/225] Replace Face keeps its body's faces attachable (#1925) Replace Face rebuilt its body with ModelBody::new and dropped the body's lineage, so no face of the result was named exactly: a sketch on any face of it, even one the replacement didn't touch, failed with "this face can't keep an attachment". Each face it moves is now a lineage step, as in Offset Face (which does the same geometry), and the result keeps the lineage. The test of a body without history used Replace Face as its example of an operation that reports none; it now lifts the block with Align instead, the same geometry. Co-authored-by: Claude Opus 5.5 Co-authored-by: bherbruck --- crates/doc/src/eval_more.rs | 12 ++++---- crates/engine/src/naming_history_tests.rs | 35 +++++++++++++++++++++-- 2 files changed, 40 insertions(+), 7 deletions(-) diff --git a/crates/doc/src/eval_more.rs b/crates/doc/src/eval_more.rs index 4544df353..6a4fa7e9c 100644 --- a/crates/doc/src/eval_more.rs +++ b/crates/doc/src/eval_more.rs @@ -97,20 +97,22 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, let tn = tp.normal(); let i = body_at(st, body, &crate::plain(faces))?; let Some(mb) = st.bodies.get(i).cloned() else { return Err(DocError::Invalid("body".into())) }; - let mut b = mb.body.clone(); + // Each face moved is a step of the body's lineage, as Offset Face's is: without it no face of + // the result could take a sketch's attachment. + let mut b = mb.traced(); for p in faces { - let n = - planar_normal_at(&b, p.0).ok_or_else(|| DocError::Invalid("not supported yet: replacing a face that is not planar".into()))?; + let n = planar_normal_at(&b.body, p.0) + .ok_or_else(|| DocError::Invalid("not supported yet: replacing a face that is not planar".into()))?; if n.dot(tn).abs() < 1.0 - 1e-9 { return Err(DocError::Invalid("not supported yet: a target that is not parallel to the face".into())); } let d = (tp.origin - p.0).dot(n); if d.abs() > 1e-9 { - b = kernel::offset_faces(&b, &[p.0], d)?; + b = Traced::step(kernel::offset_faces(&b.body, &[p.0], d)?, &[&b]); } } if let Some(slot) = st.bodies.get_mut(i) { - *slot = ModelBody::new(mb.name, b, mb.feature); + *slot = ModelBody::traced_new(mb.name, b, mb.feature); } Ok(()) } diff --git a/crates/engine/src/naming_history_tests.rs b/crates/engine/src/naming_history_tests.rs index 67b8c6e1b..fdc57f661 100644 --- a/crates/engine/src/naming_history_tests.rs +++ b/crates/engine/src/naming_history_tests.rs @@ -226,8 +226,9 @@ fn a_name_of_a_body_without_history_is_found_by_geometry_and_says_so_once_it_mov run(&mut s, "sketch.dimension", json!({"entities": ["l1"], "value": "len"})); run(&mut s, "sketch.finish", json!({})); run(&mut s, "solid.extrude", json!({"distance": 10, "name": "Block"})); - // Replacing the top by a plane: an operation that reports no history. - run(&mut s, "solid.replace_face", json!({"faces": [[20, 15, 10]], "target": {"origin": [0, 0, 12], "normal": [0, 0, 1]}, "name": "Lift"})); + // Lifting it 2 mm with Align: an operation that reports no history (Replace Face, used here + // before, keeps it now). The top ends at z = 12 as it did. + run(&mut s, "solid.align", json!({"bodies": ["Body1"], "from": [0, 0, 0], "to": [0, 0, 2], "name": "Lift"})); let state = s.model.state(); let body = state.bodies.first().unwrap(); assert!((0..solidcraft_doc::naming::face_names(body).len()).all(|i| !solidcraft_doc::naming::face_name_exact(body, i))); @@ -242,6 +243,36 @@ fn a_name_of_a_body_without_history_is_found_by_geometry_and_says_so_once_it_mov assert!(!solid_at(&s, [49.9, 15.0, 11.9])); } +/// Replace Face keeps the body's history, as Offset Face does: every face of the result is named +/// exactly, and a sketch takes an attachment on the replaced face (before, no face could: "this +/// face can't keep an attachment") and follows it when the target moves. +#[test] +fn a_sketch_on_a_replaced_face_follows_it() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "top", "expression": "15 mm"})); + block(&mut s); + run(&mut s, "solid.replace_face", json!({"faces": [[20, 15, 10]], "target": {"origin": [0, 0, "top"], "normal": [0, 0, 1]}, "name": "Lift"})); + assert!(names(&s, "Body1").iter().all(|(_, exact)| *exact), "{:?}", names(&s, "Body1")); + // A side the replacement only stretched takes an attachment too. + run(&mut s, "sketch.create", json!({"plane": {"face": [0, 15, 5]}, "name": "Side"})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "sketch.create", json!({"plane": {"face": [20, 15, 15]}, "name": "OnTop"})); + run(&mut s, "sketch.circle.center", json!({"center": [0, 0], "radius": 3})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"sketch": "OnTop", "distance": 5, "operation": "join", "name": "Boss"})); + // The boss stands on the replaced top wherever the circle's centre lands on it. + let (lo, hi) = { + let state = s.model.state(); + let b = state.body("Body1").unwrap().mesh().bounds(); + (b.min.z, b.max.z) + }; + assert!((lo - 0.0).abs() < 1e-6 && (hi - 20.0).abs() < 1e-6, "{lo} {hi}"); + change(&mut s, "top", "18 mm"); + assert_eq!(error(&s, "Boss"), None); + let hi = s.model.state().body("Body1").unwrap().mesh().bounds().max.z; + assert!((hi - 23.0).abs() < 1e-6, "the boss follows the top to z = 18: {hi}"); +} + #[test] fn a_sketch_on_a_certified_face_survives_a_fillet_and_a_cut_upstream_of_it() { let mut s = Session::default(); From d90ec9586cd3cc3bd11f6259d2fcc31f42e81e23 Mon Sep 17 00:00:00 2001 From: weyne chen Date: Tue, 20 Oct 2026 07:14:09 +0800 Subject: [PATCH 134/225] Delete Face: a face that only loses whole loops keeps its own surface (#1927) Deleting a pocket or a boss from an imported part failed with "face N cannot close: cannot attach a plane to a wire that is not on one plane". The face around the gap only loses an inner loop, but it was rebuilt as a new plane through its outer boundary, and an imported boundary is often a few 1e-5 mm off the plane: within the planar test, too far for a plane fitted to it. Such a face now keeps its surface and only drops the loop. Co-authored-by: Claude Opus 5.5 Co-authored-by: bherbruck --- crates/kernel/src/delete_face.rs | 54 ++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/crates/kernel/src/delete_face.rs b/crates/kernel/src/delete_face.rs index 3817463df..f8a46a5a2 100644 --- a/crates/kernel/src/delete_face.rs +++ b/crates/kernel/src/delete_face.rs @@ -213,6 +213,28 @@ pub fn delete_faces(body: &Body, faces: &[usize]) -> Result { } let pos = |v: &mt::Vertex| moved.get(&v.id()).copied().unwrap_or_else(|| from_p3(v.point())); let gap = |e: &mt::Edge| efaces.get(&e.id()).is_some_and(|fs| fs.iter().any(|x| del.contains(x))); + // A face that only loses whole loops (a hole's rim, a pocket's opening) and has no + // corner moving keeps its own surface: rebuilding a plane from its outer boundary + // fails when imported edges are not exactly on one plane. + let mut stays = f.vertex_iter().all(|v| !moved.contains_key(&v.id())); + let mut kept: Vec = Vec::new(); + for w in f.absolute_boundaries() { + let gaps = w.edge_iter().filter(|e| gap(e)).count(); + if gaps == 0 { + kept.push(w.clone()); + } else if gaps != w.len() { + stays = false; + } + } + if stays && !kept.is_empty() { + let mut face = mt::Face::try_new(kept, f.surface()).map_err(|e| fail(format!("face {fi} cannot close: {e}")))?; + if !f.orientation() { + face.invert(); + } + rec.face(&face, f); + out.push(face); + continue; + } let mut wires: Vec = Vec::new(); for w in f.boundaries() { let edges: Vec = w.edge_iter().cloned().collect(); @@ -359,6 +381,38 @@ mod tests { assert!(restored.contains(Vec3::new(0.1, 0.1, 0.1))); } + #[test] + fn delete_pocket_keeps_an_imported_face_around_it() { + use truck_modeling as mt; + // A shallow round pocket in the top of a plate whose top edges bow 5e-5 mm off the + // plane, as the edges of an imported part do: within the planar test, but too far for a + // plane rebuilt from them. The top only loses its inner loop, so it keeps its surface. + let plate = box_solid(Vec3::ZERO, Vec3::new(100.0, 100.0, 10.0)).unwrap(); + let tool = cylinder(Vec3::new(50.0, 50.0, 9.5), Vec3::Z, 7.5, 2.0).unwrap(); + let pocketed = boolean(&plate, &tool, BoolOp::Cut).unwrap().unwrap(); + let pocket = faces_where(&pocketed, |p| (p.x - 50.0).hypot(p.y - 50.0) < 7.5 + 1e-3 && p.z > 9.5 - 1e-6); + assert!(!pocket.is_empty()); + let mut bowed = 0; + for e in pocketed.solid.edge_iter() { + let (a, b) = (e.front().point(), e.back().point()); + if let mt::Curve::Line(_) = e.curve() + && (a.z - 10.0).abs() < 1e-9 + && (b.z - 10.0).abs() < 1e-9 + { + let lift = mt::Vector3::new(0.0, 0.0, 1e-4); + let mid = mt::Point3::new((a.x + b.x) / 2.0, (a.y + b.y) / 2.0, 10.0) + lift; + let c = if e.orientation() { vec![a, mid, b] } else { vec![b, mid, a] }; + e.set_curve(mt::Curve::BSplineCurve(mt::BSplineCurve::new(mt::KnotVec::bezier_knot(2), c))); + bowed += 1; + } + } + assert_eq!(bowed, 4); + let filled = delete_faces(&pocketed, &pocket).unwrap(); + assert_eq!(filled.face_count(), 6); + assert_eq!(filled.unmeshed_faces(), 0); + assert!((volume(&filled) - 100000.0).abs() < 1e-3, "{}", volume(&filled)); + } + #[test] fn delete_fillet_chamfer_hole_and_boss_faces() { let sharp = 24000.0; From 803ae6d5bee9125602dc1566dd21a7497c73bc9a Mon Sep 17 00:00:00 2001 From: Vodmordia Date: Mon, 19 Oct 2026 19:14:12 -0400 Subject: [PATCH 135/225] Script replay keeps a feature name another feature has (#1990) (#1997) A sketch and the feature built from it may share a name, and the sample and oracle designs do. `timeline.add` refused such a recorded name, so a design's own exported script failed to replay. `Document::insert_feature` now keeps the name, as `add_feature` does; a blank name still gets a fresh one. Co-authored-by: bherbruck --- apps/solidcraft-cli/tests/script_roundtrip.rs | 39 +++++++++++++++++ crates/doc/src/document.rs | 9 ++-- crates/engine/src/cmd/script.rs | 4 +- crates/engine/src/cmd/script_tests.rs | 43 ++++++++++++++++++- 4 files changed, 87 insertions(+), 8 deletions(-) diff --git a/apps/solidcraft-cli/tests/script_roundtrip.rs b/apps/solidcraft-cli/tests/script_roundtrip.rs index fe1d5a05d..568c4bdb3 100644 --- a/apps/solidcraft-cli/tests/script_roundtrip.rs +++ b/apps/solidcraft-cli/tests/script_roundtrip.rs @@ -84,3 +84,42 @@ fn corpus_designs_replay_from_their_scripts() { } assert!(replayed >= 7, "replayed {replayed} corpus designs"); } + +/// #1990: a sketch and its extrude may share a name, and the design's script still replays, +/// keeping the names: the replayed design's own script has the same steps. +#[test] +fn a_design_naming_a_sketch_and_its_extrude_alike_replays_from_its_script() { + let dir = std::env::temp_dir().join(format!("solidcraft-shared-names-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let cli = |args: &[&std::ffi::OsStr]| { + let out = std::process::Command::new(env!("CARGO_BIN_EXE_solidcraft-cli")).args(args).output().unwrap(); + assert!( + out.status.success(), + "{}: {}", + args.iter().map(|a| a.to_string_lossy()).collect::>().join(" "), + String::from_utf8_lossy(&out.stderr) + ); + }; + let script = dir.join("mini.json"); + let saved = dir.join("mini.solidcraft"); + let exported = dir.join("rt.json"); + let replayed = dir.join("rt.solidcraft"); + let again = dir.join("rt2.json"); + let commands = json!({"commands": [ + {"command": "sketch.create", "params": {"plane": "XY", "name": "Block"}}, + {"command": "sketch.rectangle.two_point", "params": {"p0": [0, 0], "p1": [20, 10]}}, + {"command": "sketch.finish", "params": {}}, + {"command": "solid.extrude", "params": {"distance": "5", "name": "Block"}}, + ]}); + std::fs::write(&script, commands.to_string()).unwrap(); + cli(&["run".as_ref(), script.as_ref(), "--save".as_ref(), saved.as_ref()]); + cli(&["script".as_ref(), saved.as_ref(), "--out".as_ref(), exported.as_ref()]); + cli(&["run".as_ref(), exported.as_ref(), "--save".as_ref(), replayed.as_ref()]); + cli(&["script".as_ref(), replayed.as_ref(), "--out".as_ref(), again.as_ref()]); + let first: Value = serde_json::from_str(&std::fs::read_to_string(&exported).unwrap()).unwrap(); + let second: Value = serde_json::from_str(&std::fs::read_to_string(&again).unwrap()).unwrap(); + let _ = std::fs::remove_dir_all(&dir); + let names: Vec<&str> = first["commands"].as_array().unwrap().iter().filter_map(|c| c["params"]["feature"]["name"].as_str()).collect(); + assert_eq!(names, ["Block", "Block"], "{first:#}"); + assert_eq!(second["commands"], first["commands"], "the replayed design's script has the same steps"); +} diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index ca0479a30..76e9a2f5b 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -2916,9 +2916,10 @@ impl Document { /// Insert a feature as given, keeping its id, name, parameter names and stored edge and /// face names, at the marker (or the end), with the model parameters its sketch dimensions /// use: a feature replayed from a script (`timeline.add`) is the feature the design had. - /// An id of 0 or an empty name gets a new one. Refused, changing nothing, when the id, the - /// name or a parameter name is already used, or the feature belongs to a component this - /// design does not have. + /// An id of 0 or an empty name gets a new one. The name is kept even when another feature + /// has it, as a sketch and the feature built from it often share one (#1990). Refused, + /// changing nothing, when the id or a parameter name is already used, or the feature + /// belongs to a component this design does not have. pub fn insert_feature(&mut self, mut f: Feature, params: Vec) -> Result { if self.features.len() >= MAX_FEATURES { return Err(DocError::Invalid("too many features".into())); @@ -2933,8 +2934,6 @@ impl Document { f.name = f.name.trim().to_string(); if f.name.is_empty() { f.name = self.unique_name(f.kind.base_name()); - } else if self.features.iter().any(|x| x.name == f.name) { - return Err(DocError::Invalid(format!("a feature named `{}` already exists", f.name))); } if f.component != 0 && !self.components.iter().any(|c| c.id == f.component) { return Err(DocError::Invalid(format!("feature `{}` belongs to an unknown component", f.name))); diff --git a/crates/engine/src/cmd/script.rs b/crates/engine/src/cmd/script.rs index 5eb55b508..d5ff1f00a 100644 --- a/crates/engine/src/cmd/script.rs +++ b/crates/engine/src/cmd/script.rs @@ -15,8 +15,8 @@ use crate::{EngineError, Result, Session}; pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("timeline.add", "Add Recorded Feature", add).icon("new").params( - "feature: a feature as the design file and timeline.inspect hold it ({type, name?, id?, …}; id and name are kept when free, \ - so later steps can refer to them); params?: [{name, expression, unit?, comment?}] (the model parameters its sketch \ + "feature: a feature as the design file and timeline.inspect hold it ({type, name?, id?, …}; the name is kept even when another \ + feature has it, the id is kept and refused when another feature has it, so later steps can refer to them); params?: [{name, expression, unit?, comment?}] (the model parameters its sketch \ dimensions use); the feature goes at the marker → feature, name, error, warning", ), CommandSpec::new("timeline.export_script", "Export Command Script", export_script).icon("export").noundo().doc_only().params( diff --git a/crates/engine/src/cmd/script_tests.rs b/crates/engine/src/cmd/script_tests.rs index b7c34c28c..359973b6c 100644 --- a/crates/engine/src/cmd/script_tests.rs +++ b/crates/engine/src/cmd/script_tests.rs @@ -188,7 +188,6 @@ fn a_recorded_feature_that_does_not_fit_is_refused_and_changes_nothing() { }; let refused = [ ("id taken", with(&extrude, &["feature", "name"], json!("Other"))), - ("name taken", with(&extrude, &["feature", "id"], json!(0))), ("id out of range", with(&with(&extrude, &["feature", "id"], json!(1u64 << 60)), &["feature", "name"], json!("X"))), ("parameter taken", with(&with(&sketch, &["feature", "id"], json!(0)), &["feature", "name"], json!("S2"))), ( @@ -251,3 +250,45 @@ fn replayed_features_claiming_the_same_body_name_do_not_crash() { let m = run(&mut s, "inspect.measure", json!({})); assert!(m["body_count"].as_u64().is_some_and(|n| n >= 1), "{m}"); } + +/// #1990: a sketch and the extrude built from it may share a name, as the sample and oracle +/// designs do; the design's script replays into the same design, names included. +#[test] +fn a_design_naming_a_sketch_and_its_extrude_alike_replays() { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Block"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [20, 10]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"distance": "5", "name": "Block"})); + let names = |t: &Session| t.doc.features.iter().map(|f| f.name.clone()).collect::>(); + assert_eq!(names(&s), ["Block", "Block"]); + let written = script(&mut s); + assert_eq!(commands(&written), ["timeline.add", "timeline.add"]); + let mut t = replay(&written); + same(&mut s, &mut t); + assert_eq!(names(&t), ["Block", "Block"], "the replay keeps both names"); + assert_eq!(volume(&mut t), 1000.0); + // The replay's own script is the same script. + assert_eq!(script(&mut t), written); +} + +/// #1990: `timeline.add` keeps a recorded name another feature has, as `solid.extrude` does. +#[test] +fn a_replayed_feature_keeps_a_name_another_feature_has() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": "5", "width": "5", "height": "5", "name": "Twin"})); + let r = run( + &mut s, + "timeline.add", + json!({"feature": {"type": "box", "name": "Twin", "length": "5", "width": "5", "height": "5", "corner": [20, 0, 0]}}), + ); + assert_eq!(r["name"], "Twin"); + assert_eq!(s.doc.features.iter().filter(|f| f.name == "Twin").count(), 2); + // A blank recorded name still gets a fresh one. + let r = run( + &mut s, + "timeline.add", + json!({"feature": {"type": "box", "name": " ", "length": "5", "width": "5", "height": "5", "corner": [40, 0, 0]}}), + ); + assert_eq!(r["name"], "Box1"); +} From 65e6d9dafd3680d6566844bac24ac24fa2019972 Mon Sep 17 00:00:00 2001 From: HiroKenEz <59478073+HiroKenEz@users.noreply.github.com> Date: Tue, 20 Oct 2026 01:14:16 +0200 Subject: [PATCH 136/225] Sketch: dragging part of a selection moves the whole selection (#2621) (#2720) * claim: #2621 * Sketch: dragging part of a selection moves the whole selection (#2621) A drag that started on a selected sketch line or point moved only that entity; the rest of the selection was left to the solver, so geometry that kept only its length (the reporter's 5 mm tail) trailed behind like a string and chamfers stretched. - sketch.drag takes `with`: the rest of a selection dragged by `entity`. Every free point of all of it slides by the cursor's move and the held solves keep them all (circles and ellipses keep their radii), so the selection moves as one (`plan_group`). `with` is checked and capped like the other parameters. - The viewport sends the rest of the selection when the drag starts on a selected point or curve. A curve's own points, picked with it by a window, are not a group: a circle grabbed on its edge still takes its radius. - Snapping looks at all the moving points. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd/sketch.rs | 21 +++++- crates/engine/src/cmd/sketch_drag.rs | 43 +++++++++++-- .../engine/src/cmd/sketch_drag_live_tests.rs | 34 ++++++++++ crates/ui-egui/src/sketch_drag_ui_tests.rs | 64 +++++++++++++++++++ crates/ui-egui/src/viewport.rs | 50 ++++++++++++++- 5 files changed, 201 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rs index e2ca211ab..38b96a4f7 100644 --- a/crates/engine/src/cmd/sketch.rs +++ b/crates/engine/src/cmd/sketch.rs @@ -179,7 +179,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .params("entities: [curve, point or constraint ids]"), CommandSpec::new("sketch.move_point", "Drag Sketch Point", move_point).icon("sketch_move").enabled(in_sketch).params("point: ref, to: [x,y]"), CommandSpec::new("sketch.drag", "Drag Sketch Geometry", drag).icon("sketch_move").enabled(in_sketch).live(drag_live).params( - "entity: point or curve, from: [x,y] where it was grabbed, to: [x,y], live?: bool: a point moves toward `to` within the design constraints; when exact cursor placement is impossible, bounded feasible steps minimize cursor distance while keeping design constraints mandatory. A line (spline, conic) slides by to - from; a circle or arc grabbed on its edge takes the radius to `to`. Long moves use continuation to retain the solution branch, and a step that would sweep an arc through its start is rejected. Returns `reached`: progress along the requested move (0..1; feasible point motion projects its actual displacement onto that move), and `at`: where the grabbed spot went (`from` moved as the dragged points did), the `from` of the next move. `live: true` solves the sketch and leaves later features stale until `sketch.drag_end` or a command that reads the model; `dof` is then the one from before the drag", + "entity: point or curve, from: [x,y] where it was grabbed, to: [x,y], live?: bool: a point moves toward `to` within the design constraints; when exact cursor placement is impossible, bounded feasible steps minimize cursor distance while keeping design constraints mandatory. A line (spline, conic) slides by to - from; a circle or arc grabbed on its edge takes the radius to `to`. `with?`: [point or curve ids]: the rest of a selection dragged by `entity`, which all slides by to - from as one (circles keep their radii). Long moves use continuation to retain the solution branch, and a step that would sweep an arc through its start is rejected. Returns `reached`: progress along the requested move (0..1; feasible point motion projects its actual displacement onto that move), and `at`: where the grabbed spot went (`from` moved as the dragged points did), the `from` of the next move. `live: true` solves the sketch and leaves later features stale until `sketch.drag_end` or a command that reads the model; `dof` is then the one from before the drag", ), CommandSpec::new("sketch.drag_end", "End Sketch Drag", drag_end).icon("sketch_move").enabled(in_sketch).doc_only().params( "constraint?: {command: a sketch.constraint.* id, params}: ends a drag made of `sketch.drag` `live: true` frames: adds the constraint it let go on (not kept if it over-constrains the sketch), then evaluates the whole model once; returns the constraint's result and the sketch's solved state and degrees of freedom", @@ -2397,7 +2397,7 @@ fn move_point(s: &mut Session, p: &Value) -> Result { let id = target_sketch(s, p, cmd)?; let (_, rep) = edit_solved(s, id, false, |sk, _| { let q = point_ref(sk, p.get("point"), cmd, "point")?; - Ok(((), drag_entity(sk, Ent::Point(q), to, to, false).1.solve_again())) + Ok(((), drag_entity(sk, Ent::Point(q), &[], to, to, false).1.solve_again())) })?; Ok(json!({"sketch": rep.as_ref().map(report_json)})) } @@ -2424,6 +2424,21 @@ fn drag_frame(s: &mut Session, p: &Value, live: bool) -> Result<(Value, Option Vec::new(), + Some(v) => { + let ids = v.as_array().ok_or_else(|| bad(cmd, "`with` must be a list of sketch point or curve ids"))?; + if ids.len() > sk.points.len() + sk.curves.len() { + return Err(bad(cmd, "`with` lists more entities than the sketch has")); + } + ids.iter() + .map(|v| { + let r = v.as_str().ok_or_else(|| bad(cmd, "`with` must be a list of sketch point or curve ids"))?; + ent(sk, r).ok_or_else(|| bad(cmd, format!("unknown sketch entity `{r}`"))) + }) + .collect::>>()? + } + }; if let Some(link) = super::sketch_create::text_link(sk, r).map(str::to_owned) { let moving = sk.link_points(&link).into_iter().filter_map(|i| sk.point(i).map(|p| (i, p))).collect(); super::sketch_create::move_text(sk, &link, to - from, 0.0, Vec2::ZERO, false)?; @@ -2431,7 +2446,7 @@ fn drag_frame(s: &mut Session, p: &Value, live: bool) -> Result<(Value, Option (Dragged, Left) { - let Some((path, hold, n, short)) = prepare(sk, e, from, to) else { +pub(super) fn drag_entity(sk: &mut Sketch, e: Ent, with: &[Ent], from: Vec2, to: Vec2, live: bool) -> (Dragged, Left) { + let Some((path, hold, n, short)) = prepare(sk, e, with, from, to) else { return (Dragged { reached: 0.0, moving: Vec::new() }, Left::Unsolved); }; #[cfg(test)] @@ -383,16 +386,16 @@ impl Geometry { /// `drag_entity` runs, for tests. #[cfg(test)] pub(super) fn drag_steps(sk: &Sketch, e: Ent, from: Vec2, to: Vec2) -> usize { - prepare(sk, e, from, to).map_or(0, |(_, _, n, _)| n) + prepare(sk, e, &[], from, to).map_or(0, |(_, _, n, _)| n) } /// A drag's path, what its solves hold and its number of steps (and of short steps, see /// `SHORT_STEP_FRACTION`), or `None` if it cannot move. -fn prepare(sk: &Sketch, e: Ent, from: Vec2, to: Vec2) -> Option<(Path, Hold, usize, usize)> { +fn prepare(sk: &Sketch, e: Ent, with: &[Ent], from: Vec2, to: Vec2) -> Option<(Path, Hold, usize, usize)> { if !(from.is_finite() && to.is_finite()) { return None; } - let (path, hold) = plan(sk, e, from, to)?; + let (path, hold) = if with.is_empty() { plan(sk, e, from, to)? } else { plan_group(sk, e, with, to - from)? }; let n = step_count(sk, &hold, path.length(), STEP_FRACTION); let short = step_count(sk, &hold, path.length(), SHORT_STEP_FRACTION); Some((path, hold, n, short)) @@ -503,6 +506,36 @@ fn plan(sk: &Sketch, e: Ent, from: Vec2, to: Vec2) -> Option<(Path, Hold)> { Some((path, hold)) } +/// A selection dragged by one of its entities (`e`, the rest `with`): every free point of all of +/// them slides by `d` and the solves hold them all (circles and ellipses keep their radii), so +/// the selection moves as one instead of its free ends trailing behind the grabbed entity. +fn plan_group(sk: &Sketch, e: Ent, with: &[Ent], d: Vec2) -> Option<(Path, Hold)> { + let mut hold = Hold::default(); + for e in std::iter::once(&e).chain(with) { + match *e { + Ent::Point(q) => hold.points.push(q), + Ent::Curve(c) => { + let Some(kind) = sk.curves.get(c).map(|x| &x.kind) else { continue }; + hold.points.extend(kind.point_ids()); + if matches!(kind, CurveKind::Circle { .. } | CurveKind::Ellipse { .. }) { + hold.radii.push(c); + } + } + } + } + hold.points.sort_unstable(); + hold.points.dedup(); + hold.radii.sort_unstable(); + hold.radii.dedup(); + let locked = sk.locked_points(); + let pts: Vec<(usize, Vec2)> = + hold.points.iter().filter(|q| !locked.get(**q).copied().unwrap_or(true)).filter_map(|&q| Some((q, sk.point(q)?))).collect(); + if pts.is_empty() { + return None; + } + Some((Path::Slide { pts, d }, hold)) +} + /// Steps for a move of `length`: enough that none is longer than `fraction` of the smallest /// size of the geometry the solve moves with what it holds (at least `MIN_STEP`), at most /// `MAX_STEPS`. A move short next to every size in the sketch (a normal mouse frame) is one diff --git a/crates/engine/src/cmd/sketch_drag_live_tests.rs b/crates/engine/src/cmd/sketch_drag_live_tests.rs index 268b7d6ba..8139899ef 100644 --- a/crates/engine/src/cmd/sketch_drag_live_tests.rs +++ b/crates/engine/src/cmd/sketch_drag_live_tests.rs @@ -288,3 +288,37 @@ fn letting_go_on_a_snap_or_undoing_evaluates_once() { assert!(r["constraint"]["error"].is_string(), "{r}"); assert!(!s.model.is_stale()); } + +#[test] +fn a_drag_with_the_rest_of_a_selection_moves_it_as_one() { + // A vertical line and a 5 mm tail hanging off its top that keeps only its length (#2621). + let start = || { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY"})); + run(&mut s, "sketch.line", json!({"points": [[10, 10], [10, 50], [14, 47]]})); + run(&mut s, "sketch.constraint.horizontal_vertical", json!({"line": "l1"})); + run(&mut s, "sketch.dimension", json!({"entities": ["l2"], "value": 5})); + run(&mut s, "sketch.circle.center", json!({"center": [40, 10], "radius": 3, "id": "c1"})); + s + }; + let v = solidcraft_geom::Vec2::new; + for live in [false, true] { + // Dragged alone, the line leaves the tail's free end where it was as far as it can. + let mut s = start(); + run(&mut s, "sketch.drag", json!({"entity": "l1", "from": [10, 30], "to": [20, 20], "live": live})); + assert!(pt(&s, "l2.end").dist(v(24.0, 37.0)) > 1.0, "{:?}", pt(&s, "l2.end")); + // Dragged with the tail and the circle, all of it slides by the cursor's move. + let mut s = start(); + let r = run(&mut s, "sketch.drag", json!({"entity": "l1", "with": ["l2", "c1"], "from": [10, 30], "to": [20, 20], "live": live})); + assert_eq!((&r["reached"], &r["at"]), (&json!(1.0), &json!([20.0, 20.0])), "{r}"); + for (p, at) in [("l1.start", v(20.0, 0.0)), ("l1.end", v(20.0, 40.0)), ("l2.end", v(24.0, 37.0)), ("c1.center", v(50.0, 0.0))] { + assert!(pt(&s, p).dist(at) < 1e-6, "{p}: {:?}", pt(&s, p)); + } + let sk = s.doc.sketch(s.active_sketch.expect("sketch mode")).expect("the sketch"); + assert_eq!(sk.radius(sk.curve_index("c1").expect("the circle")), Some(3.0)); + } + let mut s = start(); + for with in [json!("l2"), json!([7]), json!(["nope"])] { + assert!(s.execute("sketch.drag", &json!({"entity": "l1", "with": with, "from": [10, 30], "to": [20, 20]})).is_err(), "{with}"); + } +} diff --git a/crates/ui-egui/src/sketch_drag_ui_tests.rs b/crates/ui-egui/src/sketch_drag_ui_tests.rs index 96c57de76..281cafda0 100644 --- a/crates/ui-egui/src/sketch_drag_ui_tests.rs +++ b/crates/ui-egui/src/sketch_drag_ui_tests.rs @@ -2,6 +2,7 @@ //! brings the model up to date in the drag's one undo step, and the grab stays on the geometry. use serde_json::{Value, json}; +use solidcraft_engine::Sel; use solidcraft_engine::geom::Vec2; use crate::scenario::Harness; @@ -244,3 +245,66 @@ fn associated_spline_offset_hides_fit_nodes_and_follows_a_source_drag_live() { let sk = &state.sketch(sid).unwrap().sketch; assert!(sk.curves[derived].kind.point_ids().iter().all(|i| !solidcraft_engine::view::sketch_point_visible(sk, *i))); } + +#[test] +fn dragging_a_selected_line_moves_the_whole_selection() { + let mut h = Harness::new(); + run(&mut h, "sketch.create", json!({"plane": "XY"})); + // An L with a chamfered corner and a short tail (#2621): the tail keeps only its length, so + // dragged on its own the L would leave the tail's free end behind like a string. + run(&mut h, "sketch.line", json!({"points": [[10, 10], [10, 50], [15, 55], [50, 55], [54, 52]]})); + run(&mut h, "sketch.constraint.horizontal_vertical", json!({"line": "l1"})); + run(&mut h, "sketch.constraint.horizontal_vertical", json!({"line": "l3"})); + run(&mut h, "sketch.dimension", json!({"entities": ["l4"], "value": 5})); + run(&mut h, "sketch.line", json!({"points": [[80, 10], [80, 30]], "connect": false})); + let sid = h.app.session.active_sketch.expect("sketch mode"); + let before = h.app.session.world_state().sketch(sid).expect("the sketch").sketch.clone(); + let lines = ["l1", "l2", "l3", "l4"]; + let mut selected: Vec = lines.iter().flat_map(|l| before.curves[before.curve_index(l).unwrap()].kind.point_ids()).collect(); + selected.sort_unstable(); + selected.dedup(); + h.app.session.selection = lines.iter().map(|l| Sel::SketchCurve { id: (*l).into() }).collect(); + h.app.session.selection.extend(selected.iter().map(|&p| Sel::SketchPoint { id: before.points[p].id.clone() })); + h.call("ui.view", json!({"view": "top"})); + h.app.cam.distance = 150.0; + h.frames(3); + let a = screen(&mut h, 10.0, 30.0); + let b = screen(&mut h, 20.0, 20.0); + let mut path = vec![a]; + path.extend(steps(a, b, 8)); + press_and_move(&mut h, &path); + release(&mut h, b); + let after = &h.app.session.world_state().sketch(sid).expect("the sketch").sketch.clone(); + for &p in &selected { + let moved = after.points[p].pos - before.points[p].pos; + assert!(moved.dist(Vec2::new(10.0, -10.0)) < 0.05, "{} moved by {moved:?}", before.points[p].id); + } + let other = before.curves[before.curve_index("l5").unwrap()].kind.point_ids(); + for p in other { + assert!(after.points[p].pos.dist(before.points[p].pos) < 1e-9, "the unselected line stays"); + } +} + +#[test] +fn a_window_selected_circle_still_takes_its_radius_from_a_drag_on_its_edge() { + let mut h = Harness::new(); + run(&mut h, "sketch.create", json!({"plane": "XY"})); + run(&mut h, "sketch.circle.center", json!({"center": [20, 20], "radius": 10, "id": "c1"})); + // A window around the circle picks it and its centre: not a group to move. + h.app.session.selection = vec![Sel::SketchCurve { id: "c1".into() }, Sel::SketchPoint { id: "c1.center".into() }]; + h.call("ui.view", json!({"view": "top"})); + h.app.cam.distance = 150.0; + h.frames(3); + let a = screen(&mut h, 30.0, 20.0); + let b = screen(&mut h, 35.0, 20.0); + let mut path = vec![a]; + path.extend(steps(a, b, 6)); + press_and_move(&mut h, &path); + release(&mut h, b); + assert!(point(&h, "c1.center").dist(Vec2::new(20.0, 20.0)) < 1e-9); + let sid = h.app.session.active_sketch.expect("sketch mode"); + let st = h.app.session.world_state(); + let sk = &st.sketch(sid).expect("the sketch").sketch; + let r = sk.radius(sk.curve_index("c1").expect("the circle")).expect("a radius"); + assert!((r - 15.0).abs() < 0.05, "{r}"); +} diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 22661bd6d..0267a2d42 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -2662,7 +2662,10 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { let active = app.session.active_sketch; match hit { Some(Hit::SketchPoint { sketch, id, .. }) if Some(sketch) == active => { - app.viewport.point_drag = Some((id, app.session.undo.len(), None)) + // A point dragged with the rest of a selection slides with it, from where it + // was grabbed, rather than going to the cursor. + let grab = if dragged_with(app, &id).is_empty() { None } else { on_plane(app, a) }; + app.viewport.point_drag = Some((id, app.session.undo.len(), grab)) } Some(Hit::SketchCurve { sketch, id, .. }) if Some(sketch) == active => { app.viewport.point_drag = on_plane(app, a).map(|q| (id, app.session.undo.len(), Some(q))); @@ -2697,12 +2700,19 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { && let Some(mut q) = hover.and_then(|p| on_plane(app, p)) { let from = grab.unwrap_or(q); + let with = dragged_with(app, &id); // Snap the dragged point (or the line's ends) to other geometry, like drawing. let snap = { let st = app.session.world_state(); app.session.active_sketch.and_then(|s| st.sketch(s)).and_then(|ss| { let sk = &ss.sketch; - let (own, exclude) = crate::drag_snap::moving_points(sk, &id); + let (mut own, mut exclude) = crate::drag_snap::moving_points(sk, &id); + for (o, x) in with.iter().map(|w| crate::drag_snap::moving_points(sk, w)) { + own.extend(o); + exclude.extend(x); + } + own.sort_unstable(); + own.dedup(); if own.iter().any(|&p| sk.point_locked(p)) { return crate::drag_snap::find(sk, &[], &[], 0.0); } @@ -2719,7 +2729,8 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { q += s.offset; } // Each frame re-solves the sketch only (`live`); the model follows when the drag ends. - let at = match app.session.execute("sketch.drag", &json!({"entity": id, "from": [from.x, from.y], "to": [q.x, q.y], "live": true})) { + let params = json!({"entity": id, "with": with, "from": [from.x, from.y], "to": [q.x, q.y], "live": true}); + let at = match app.session.execute("sketch.drag", ¶ms) { Ok(r) => { app.session.undo.truncate(depth + 1); r.get("at").and_then(solidcraft_engine::params::vec2).unwrap_or(q) @@ -2908,6 +2919,39 @@ pub(crate) fn select(app: &mut SolveApp, sel: Option, add: bool, toggle: bo } } +/// The rest of the selected sketch geometry when the point or curve `id` is part of it (#2621): +/// a drag that starts on a selected entity moves the whole selection with it. +fn dragged_with(app: &SolveApp, id: &str) -> Vec { + fn geometry(s: &Sel) -> Option<&str> { + match s { + Sel::SketchPoint { id } | Sel::SketchCurve { id } => Some(id.as_str()), + _ => None, + } + } + let selected = || app.session.selection.iter().filter_map(geometry); + if !selected().any(|s| s == id) { + return Vec::new(); + } + let rest: Vec = selected().filter(|s| *s != id).map(str::to_owned).collect(); + // A curve's own points, selected with it by a window, are not a group: a circle grabbed on + // its edge still takes its radius from the drag. + let st = app.session.world_state(); + let own: Vec<&str> = app + .session + .active_sketch + .and_then(|s| st.sketch(s)) + .and_then(|ss| { + let sk = &ss.sketch; + let c = sk.curves.get(sk.curve_index(id)?)?; + Some(c.kind.point_ids().into_iter().filter_map(|p| sk.points.get(p).map(|p| p.id.as_str())).collect()) + }) + .unwrap_or_default(); + if rest.iter().all(|r| own.contains(&r.as_str())) { + return Vec::new(); + } + rest +} + /// What a click on `sel` picks: its pieces ([`grouped_selection`]), and for a letter of a sketch /// text the whole text, unless Shift is held (Shift picks the one letter). pub(crate) fn picked_selection(s: &solidcraft_engine::Session, sel: &Sel) -> Vec { From 843726a8cb872d808cedc210ae6c391949b6fbf4 Mon Sep 17 00:00:00 2001 From: Irakli Kourtis Date: Mon, 19 Oct 2026 20:26:39 -0400 Subject: [PATCH 137/225] CI: merge-queue groups run on Blacksmith, test shards on 16 vCPU (#3343) * CI: merge-queue groups run on Blacksmith, test shards on 16 vCPU The merge queue builds up to three groups at once, but every group's checks, Clippy, doc and reference tests and all four shards ran on the one self-hosted machine, so the groups waited for each other. Merge groups now run on Blacksmith like pull requests (test archive built once, shards on 16 vCPU). Pushes to main keep the self-hosted runners and their warm build directories, and a push the queue already tested still runs only the repository checks. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QWhMwdqJYQKQq8RCLSL1LT * CI: every job on Blacksmith: pushes to main and the Windows jobs too Pushes to main ran on the one self-hosted machine and the Windows jobs on GitHub's runners. Both move to Blacksmith (Windows Server 2025, 8 vCPU), so nothing in ci.yml depends on a single box any more. With no self-hosted job left, the local routing goes: no warm build directories, every run builds the test archive once and the shards run it, and main saves the build caches every other run restores. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QWhMwdqJYQKQq8RCLSL1LT --------- Co-authored-by: jyviko <2501648+jyviko@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- .github/actionlint.yaml | 3 +- .github/workflows/ci.yml | 138 +++++++++++---------------------------- 2 files changed, 39 insertions(+), 102 deletions(-) diff --git a/.github/actionlint.yaml b/.github/actionlint.yaml index 141df1e27..df9c4742e 100644 --- a/.github/actionlint.yaml +++ b/.github/actionlint.yaml @@ -2,8 +2,9 @@ self-hosted-runner: labels: - self-hosted-fast - self-hosted-light - # Blacksmith (Ubuntu 24.04 only; see the top of workflows/ci.yml). + # Blacksmith (see the top of workflows/ci.yml). - blacksmith-2vcpu-ubuntu-2404 - blacksmith-4vcpu-ubuntu-2404 - blacksmith-8vcpu-ubuntu-2404 - blacksmith-16vcpu-ubuntu-2404 + - blacksmith-8vcpu-windows-2025 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7804de089..9ef14f956 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,27 +26,15 @@ # GitHub cannot filter `labeled` events by label name, so any other label starts a run whose jobs # are all skipped; it gets its own concurrency group (below) so it never cancels the real run. # Cross-compilation is opt-in through Run workflow; release builds remain in release.yml. -# Trusted runs use both pools: pushes to main, merge-queue groups and pull requests from a branch -# of this repository (people with write access; fork pull requests never run on this machine). -# There, Select checks and ci run on the self-hosted light runner (`self-hosted-light`, quick -# jobs, so they never wait behind a build). For pushes to main and the merge queue only, the -# repository checks, Clippy, the doc tests, the reference tests and all four test shards run on the -# self-hosted runners (`self-hosted-fast`, warm build directories via scripts/ci/warm-target.sh); -# a pull request runs them on GitHub's runners, so it never holds up the queue. Fork PRs run -# there too: the runners are ephemeral and fork runs get no secrets. -# Where the test shards run on GitHub's runners, the test archive is built there too: the -# self-hosted machine has a newer glibc, so its binaries wouldn't start on ubuntu-24.04, while the -# archive runs there unchanged (same /home/runner/work checkout path). The self-hosted shards -# (main and the merge queue) skip the archive and build the tests in their warm build directories. -# Fork pull requests, the nightly run and Run workflow never use our self-hosted runners; the -# self-hosted runners refuse any other job. -# "GitHub's runners" above means Blacksmith's Ubuntu 24.04 runners (blacksmith-vcpu-ubuntu-2404, -# sized per job: 16 vCPU for Build tests and Clippy, 8 for compiles, test shards, doc and -# reference tests, 4 for the light checks, 2 for Select checks and ci). Same image family as -# ubuntu-24.04, so the test archive and recorded goldens behave the same. Windows jobs stay on -# windows-latest. Blacksmith runners report runner.environment == 'self-hosted' as well, so steps -# don't ask the runner where they run: they read the routing that chose it (Select checks' `local` -# output, or the trusted-run condition in jobs that don't need Select checks). +# Every Linux job runs on Blacksmith's Ubuntu 24.04 runners (blacksmith-vcpu-ubuntu-2404), sized +# per job: 16 vCPU for Build tests, Clippy and the merge queue's test shards, 8 for compiles, the +# other test shards, doc and reference tests, 4 for the light checks, 2 for Select checks and ci. +# The Windows jobs run on Blacksmith's Windows Server 2025 runners (blacksmith-8vcpu-windows-2025). +# Pull requests, forks included, the merge queue, pushes to main and the nightly run all use them: +# the runners are ephemeral, fork runs get no secrets, and main saves the build caches that every +# other run restores read-only. The tests are built once (Build tests) into an archive the shards +# run; Blacksmith's image matches ubuntu-24.04, so the archive and the recorded goldens behave the +# same. name: CI on: @@ -102,8 +90,7 @@ jobs: # Not on a draft: every other check needs this one, so they skip too. Not on a label other than # approved-for-ci either (the same skip, for the same reason). if: (github.event_name != 'pull_request' || !github.event.pull_request.draft) && (github.event.action != 'labeled' || github.event.label.name == 'approved-for-ci') - # Trusted runs (see the top of this file) use the self-hosted runners. - runs-on: ${{ (github.event_name == 'merge_group' || (github.event_name == 'push' && github.ref == 'refs/heads/main') || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository)) && 'self-hosted-light' || 'blacksmith-2vcpu-ubuntu-2404' }} + runs-on: blacksmith-2vcpu-ubuntu-2404 permissions: contents: read # To ask whether the merge queue already tested a commit pushed to main. @@ -121,10 +108,6 @@ jobs: doctests: ${{ steps.paths.outputs.doctests }} # The passing run a merge of main carries forward (its URL), when this push is only that. carried: ${{ steps.paths.outputs.carried }} - # The fast self-hosted runners are kept for main and the merge queue (the pre-merge gate); - # pull requests, same-repo ones included, run on GitHub's runners. Steps read this to know - # where their job runs (see the top of this file). - local: ${{ github.event_name == 'merge_group' || (github.event_name == 'push' && github.ref == 'refs/heads/main') }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -162,7 +145,7 @@ jobs: # The queue lands the very commit its merge_group run tested. If that run passed, # testing the push again proves nothing new; otherwise (a merge that skipped the # queue, or the API cannot answer) test everything. - # The API through curl and grep: Select checks of a push runs on the self-hosted runner. + # The API through curl and grep, which every runner image has. tested=$(curl -fsS -H "Authorization: Bearer $GH_TOKEN" -H "Accept: application/vnd.github+json" \ "https://api.github.com/repos/$REPO/actions/workflows/ci.yml/runs?event=merge_group&head_sha=$PUSH_SHA&status=success&per_page=1" \ | grep -o '"total_count": *[0-9]*' | grep -o '[0-9]*$' || echo 0) @@ -269,20 +252,15 @@ jobs: checks: name: Format and repository checks if: (github.event_name != 'pull_request' || !github.event.pull_request.draft) && (github.event.action != 'labeled' || github.event.label.name == 'approved-for-ci') - runs-on: ${{ (github.event_name == 'merge_group' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) && 'self-hosted-fast' || 'blacksmith-4vcpu-ubuntu-2404' }} + runs-on: blacksmith-4vcpu-ubuntu-2404 timeout-minutes: 15 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - name: Warm build directory (self-hosted runner) - if: github.event_name == 'merge_group' || (github.event_name == 'push' && github.ref == 'refs/heads/main') - run: scripts/ci/warm-target.sh checks - uses: dtolnay/rust-toolchain@stable with: components: rustfmt - # The self-hosted runners keep their build directory and Cargo home instead; everything - # else restores main's cache (read-only off main). - - if: ${{ !(github.event_name == 'merge_group' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) }} - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 + # Main saves the cache; every other run restores it, read-only. + - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 with: key: repo-checks save-if: ${{ github.ref == 'refs/heads/main' }} @@ -314,15 +292,14 @@ jobs: name: Quick compile needs: changes if: needs.changes.outputs.quick == 'true' - runs-on: ${{ needs.changes.outputs.local == 'true' && 'self-hosted-light' || 'blacksmith-8vcpu-ubuntu-2404' }} + runs-on: blacksmith-8vcpu-ubuntu-2404 timeout-minutes: 30 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Size parallel compiles to the job's memory run: scripts/ci/build-jobs.sh - uses: dtolnay/rust-toolchain@stable - - if: needs.changes.outputs.local != 'true' - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 + - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 with: key: quick-compile save-if: ${{ github.ref == 'refs/heads/main' }} @@ -333,20 +310,15 @@ jobs: name: Native Linux Clippy needs: changes if: needs.changes.outputs.native == 'true' - runs-on: ${{ needs.changes.outputs.local == 'true' && 'self-hosted-fast' || 'blacksmith-16vcpu-ubuntu-2404' }} + runs-on: blacksmith-16vcpu-ubuntu-2404 timeout-minutes: 30 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - name: Warm build directory (self-hosted runner) - if: needs.changes.outputs.local == 'true' - run: scripts/ci/warm-target.sh clippy - uses: dtolnay/rust-toolchain@stable with: components: clippy - # The self-hosted runners keep their build directory and Cargo home instead; everything - # else restores main's cache (read-only off main). - - if: needs.changes.outputs.local != 'true' - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 + # Main saves the cache; every other run restores it, read-only. + - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 with: key: native-clippy save-if: ${{ github.ref == 'refs/heads/main' }} @@ -367,9 +339,7 @@ jobs: # format check. Main, nightly and Run workflow build regardless, so the action matrix and the # property tests that hang off this job keep their signal. needs: [changes, checks] - # The self-hosted shards (main and the merge queue) build from their warm build directories - # instead: downloading the 3 GB archive took them longer than building. - if: ${{ !cancelled() && needs.changes.result == 'success' && needs.changes.outputs.native == 'true' && needs.changes.outputs.local != 'true' && (github.event_name != 'pull_request' || needs.checks.result == 'success') }} + if: ${{ !cancelled() && needs.changes.result == 'success' && needs.changes.outputs.native == 'true' && (github.event_name != 'pull_request' || needs.checks.result == 'success') }} runs-on: blacksmith-16vcpu-ubuntu-2404 # Fork builds start from main's cache, read-only; give them room to finish and upload. timeout-minutes: ${{ (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository) && 60 || 45 }} @@ -416,8 +386,8 @@ jobs: tests: name: Native Linux tests (${{ matrix.shard }}/4) needs: [changes, checks, build-tests] - if: ${{ !cancelled() && needs.changes.outputs.native == 'true' && (github.event_name != 'pull_request' || needs.checks.result == 'success') && (needs.changes.outputs.local == 'true' || needs.build-tests.result == 'success') }} - runs-on: ${{ needs.changes.outputs.local == 'true' && 'self-hosted-fast' || 'blacksmith-8vcpu-ubuntu-2404' }} + if: ${{ !cancelled() && needs.changes.outputs.native == 'true' && (github.event_name != 'pull_request' || needs.checks.result == 'success') && needs.build-tests.result == 'success' }} + runs-on: ${{ github.event_name == 'merge_group' && 'blacksmith-16vcpu-ubuntu-2404' || 'blacksmith-8vcpu-ubuntu-2404' }} timeout-minutes: 60 strategy: fail-fast: false @@ -433,35 +403,20 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Install a software Vulkan driver (lavapipe) - # Preinstalled on the self-hosted runner, which has no sudo. - if: needs.changes.outputs.local != 'true' run: | sudo apt-get update sudo apt-get install -y --no-install-recommends mesa-vulkan-drivers libvulkan1 - uses: taiki-e/install-action@1168f6810a3cb30a3514bf5756a3b7f0422c6df8 # v2.87.28 with: tool: cargo-nextest - # On the self-hosted runners each shard builds the tests in its warm build directory (a few - # minutes for what changed); elsewhere it runs the archive the Build tests job made. - - name: Size parallel compiles to the job's memory - if: needs.changes.outputs.local == 'true' - run: scripts/ci/build-jobs.sh - - name: Warm build directory (self-hosted runner) - if: needs.changes.outputs.local == 'true' - run: scripts/ci/warm-target.sh build-tests - - if: needs.changes.outputs.local == 'true' - uses: dtolnay/rust-toolchain@stable - - if: needs.changes.outputs.local != 'true' - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + # Each shard runs the archive the Build tests job made. + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: nextest-archive - name: Run tests env: EVENT_NAME: ${{ github.event_name }} GOLDENS: ${{ needs.changes.outputs.goldens }} - LOCAL: ${{ needs.changes.outputs.local }} - FULL: ${{ needs.changes.outputs.full }} - PACKAGES: ${{ needs.changes.outputs.packages }} SHARD: ${{ matrix.shard }} SHARDS: ${{ github.event_name == 'pull_request' && 2 || 4 }} # The robustness golden seeds a pull request skips: each takes one to twenty minutes under @@ -481,17 +436,10 @@ jobs: filter=(--ignore-default-filter -E "default() | (package(solidcraft-engine) & test(/^tests::robustness_goldens::/) & not test(/^tests::robustness_goldens::seed_($SLOW_SEEDS)\$/))") fi junit=${CARGO_TARGET_DIR:-target}/nextest/ci/junit.xml - # The warm build directory keeps the last run's junit.xml: never upload that one. rm -f "$junit" - if [ "$LOCAL" = true ]; then - scope=(--workspace) - if [ "$FULL" != true ]; then scope=(); for p in $PACKAGES; do scope+=(-p "$p"); done; fi - run=(cargo nextest run "${scope[@]}" --cargo-profile ci --locked) - else - # Extract into ./target: tests that run a built binary (env!("CARGO_BIN_EXE_*")) have - # the build job's path, which is the same checkout path here. - run=(cargo nextest run --archive-file tests.tar.zst --workspace-remap . --extract-to . --extract-overwrite) - fi + # Extract into ./target: tests that run a built binary (env!("CARGO_BIN_EXE_*")) have + # the build job's path, which is the same checkout path here. + run=(cargo nextest run --archive-file tests.tar.zst --workspace-remap . --extract-to . --extract-overwrite) if ! "${run[@]}" --profile ci --partition "slice:$SHARD/$SHARDS" --no-tests=pass "${filter[@]}"; then # A failed golden gets the hint to re-record it (junit.xml lists the failures). if [ -f "$junit" ] && tr '\n' ' ' < "$junit" | grep -q ']*>[[:space:]]* Date: Mon, 19 Oct 2026 21:06:05 -0400 Subject: [PATCH 138/225] CI: Windows app startup smoke back on windows-latest (#3355) Blacksmith's Windows runners start the app but never present a frame (no interactive desktop), so the startup smoke failed on main after #3343. The shader job stays on Blacksmith. Co-authored-by: Claude Opus 5.5 --- .github/workflows/ci.yml | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9ef14f956..7ec8a8b4a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -29,7 +29,8 @@ # Every Linux job runs on Blacksmith's Ubuntu 24.04 runners (blacksmith-vcpu-ubuntu-2404), sized # per job: 16 vCPU for Build tests, Clippy and the merge queue's test shards, 8 for compiles, the # other test shards, doc and reference tests, 4 for the light checks, 2 for Select checks and ci. -# The Windows jobs run on Blacksmith's Windows Server 2025 runners (blacksmith-8vcpu-windows-2025). +# The Windows shader job runs on Blacksmith's Windows Server 2025 runners (blacksmith-8vcpu-windows-2025); +# the Windows app startup smoke stays on windows-latest, which has a desktop session that presents frames. # Pull requests, forks included, the merge queue, pushes to main and the nightly run all use them: # the runners are ephemeral, fork runs get no secrets, and main saves the build caches that every # other run restores read-only. The tests are built once (Build tests) into an archive the shards @@ -669,7 +670,9 @@ jobs: name: Windows app startup needs: changes if: needs.changes.outputs.windows == 'true' - runs-on: blacksmith-8vcpu-windows-2025 + # GitHub-hosted: the startup smoke needs an interactive desktop that presents frames; on + # Blacksmith's Windows runners the window never presents ("no frame was presented"). + runs-on: windows-latest timeout-minutes: 60 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 From b2622325a1a67f52884443ac13e3cce477a5264a Mon Sep 17 00:00:00 2001 From: amolinari-autotex Date: Mon, 19 Oct 2026 23:56:17 +0000 Subject: [PATCH 139/225] i18n: fill missing Italian catalog entries (#2389) Translate 21 messages while keeping Italian partial and preserving existing translations and catalog guards. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- assets/locales/it.json | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/assets/locales/it.json b/assets/locales/it.json index 64e3bc8f9..2c5b2ff8b 100644 --- a/assets/locales/it.json +++ b/assets/locales/it.json @@ -31,6 +31,7 @@ "Arc length": "Lunghezza dell'arco", "Area": "Area", "Attachment": "Collegamento", + "BOUNDARY SURFACE": "SUPERFICIE DA CONTORNI", "BROWSER": "STRUTTURA", "Bend Line Position": "Posizione della linea di piega", "Bend Position": "Posizione della piega", @@ -73,6 +74,7 @@ "Counterbore depth": "Profondità della lamatura", "Countersink angle": "Angolo di svasatura", "Create Issue — review draft": "Crea segnalazione — rivedi bozza", + "Cross curves": "Curve trasversali", "Cube": "Cubo", "Current orthographic view (1:1 mm)": "Vista ortografica corrente (1:1 mm)", "Current perspective view": "Vista prospettica corrente", @@ -86,6 +88,7 @@ "Density": "Densità", "Designs you open or save appear here.": "I progetti aperti o salvati vengono visualizzati qui.", "Determined by To Object. Choose Angle to edit the angular extent.": "Determinato da Fino all'oggetto. Scegli Angolo per modificare l'estensione angolare.", + "Direction": "Direzione", "Discard": "Scarta", "Do not export hidden edges": "Non esportare gli spigoli nascosti", "Don't ask again": "Non chiedere più", @@ -127,6 +130,7 @@ "Home view": "Vista iniziale", "In This Design": "In questo progetto", "In place (surfaces)": "In posizione (superfici)", + "In plane": "Nel piano", "Inside": "Interno", "Interferes": "Interferisce", "Issue title": "Titolo della segnalazione", @@ -162,6 +166,7 @@ "No matching appearances": "Nessun aspetto corrispondente", "No visible bodies to export.": "Nessun corpo visibile da esportare.", "None": "Nessuno", + "Normal to sketch": "Normale allo schizzo", "Not available yet": "Non ancora disponibile", "Notch": "Intaglio", "Opacity": "Opacità", @@ -420,6 +425,7 @@ "cmd.inspect_interference": "Interferenza", "cmd.inspect_isocurve": "Analisi delle isocurve", "cmd.inspect_minimum_radius": "Analisi del raggio minimo", + "cmd.inspect_silhouette": "Silhouette", "cmd.inspect_zebra": "Analisi zebrata", "cmd.joint_as_built": "Giunto in posizione", "cmd.joint_cam": "Camma", @@ -554,6 +560,8 @@ "cmd.sketch_isoparametric_curve": "Curva isoparametrica", "cmd.sketch_line3d": "Linea 3D", "cmd.sketch_line_midpoint": "Linea dal punto medio", + "cmd.sketch_loose_ends": "Estremità libere", + "cmd.sketch_loose_ends_tie": "Vincola estremità libere", "cmd.sketch_move": "Sposta/Copia entità dello schizzo", "cmd.sketch_move3d": "Sposta punto 3D", "cmd.sketch_move_point": "Trascina punto dello schizzo", @@ -802,6 +810,8 @@ "sketch.degrees_of_freedom": "{count} gradi di libertà", "sketch.draw_curves": "Disegna come {linetype}", "sketch.make_selection": "Converti la selezione in {linetype}", + "sketch.open_ends": "Aperte {count}", + "sketch.untied_ends": "Non vincolate {count}", "sketch_text.align_center": "Centro", "sketch_text.align_left": "Sinistra", "sketch_text.align_right": "Destra", @@ -1065,6 +1075,9 @@ "ui.construct": "Costruisci", "ui.construction": "Costruzione", "ui.context_menu": "Menu contestuale", + "ui.continuity_g0": "G0 spigolo vivo", + "ui.continuity_g1": "G1 tangenza", + "ui.continuity_g2": "G2 curvatura", "ui.continuity_gap": "Gioco", "ui.copy": "Copia", "ui.corner": "Angolo", @@ -1153,6 +1166,8 @@ "ui.fully_constrained": "Completamente vincolato", "ui.general": "Generali", "ui.graphics": "Grafica", + "ui.grid_follows_view": "La griglia segue la vista", + "ui.grid_follows_view_hint": "Le viste laterali mostrano la griglia sul piano verticale rivolto verso di esse anziché sul piano di appoggio", "ui.ground_shadow": "Ombra sul piano di appoggio", "ui.groupSelected": "Raggruppa selezionati", "ui.heading_add_ins": "COMPONENTI AGGIUNTIVI", @@ -1303,6 +1318,7 @@ "ui.one_side": "Un lato", "ui.open": "Apri", "ui.open_ellipsis": "Apri...", + "ui.open_ends_tip": "Non tocca altre curve", "ui.open_preferences": "Apri preferenze", "ui.open_recent": "Apri recenti", "ui.operation": "Operazione", @@ -1370,6 +1386,8 @@ "ui.reset_the_settings_on_this_page": "Reimposta le impostazioni di questa pagina", "ui.restore": "Ripristina", "ui.restore_defaults": "Ripristina valori predefiniti", + "ui.reverse_horizontal_pan_direction": "Inverti direzione della panoramica orizzontale", + "ui.reverse_horizontal_pan_tip": "Lo scorrimento orizzontale a due dita e la rotella del pollice eseguono la panoramica nella direzione opposta", "ui.reverse_zoom_direction": "Inverti direzione dello zoom", "ui.revolve": "Rivoluzione", "ui.right": "Destra", @@ -1481,6 +1499,8 @@ "ui.theme": "Tema", "ui.thickness": "Spessore", "ui.thread": "Filettatura", + "ui.tie_ends": "Vincola", + "ui.tie_ends_tip": "Vincola tutte le estremità che si toccano solo per posizione", "ui.timeline_bottom": "Sequenza temporale in basso", "ui.timeline_left_note": "La disposizione a sinistra mostra la barra di ripristino sopra la struttura delle parti e della scena.", "ui.timeline_left_sidebar": "Barra laterale sinistra", @@ -1503,6 +1523,7 @@ "ui.units_of_new_designs": "Unità dei nuovi progetti", "ui.unlock": "Sblocca", "ui.unsuppress": "Riattiva", + "ui.untied_ends_tip": "Tocca un'altra curva solo per posizione, senza vincoli", "ui.untitled": "Senza titolo", "ui.up_axis_note": "L'asse verticale nelle viste (viste degli assi, Vista iniziale, Vista normale). I progetti restano invariati.", "ui.updateToCurrentView": "Aggiorna alla vista corrente", From 91753051a1120c41063175638ca68c482f00b0c5 Mon Sep 17 00:00:00 2001 From: Matt Ruhland Date: Mon, 19 Oct 2026 23:56:19 +0000 Subject: [PATCH 140/225] docs(skills): multi-body primitives, mirror body names, unit suffixes, set_parameter call (#2964) Add body_name and targets to the solid.box and solid.cylinder rows, the bodies form of solid.mirror and the names its bodies get, unit-suffixed parameter values, and the set_parameter argument shape. --- skills/solidcraft-modeling/reference.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/skills/solidcraft-modeling/reference.md b/skills/solidcraft-modeling/reference.md index 27624cdfe..31352761e 100644 --- a/skills/solidcraft-modeling/reference.md +++ b/skills/solidcraft-modeling/reference.md @@ -3,6 +3,7 @@ These are the shapes of the commands a part build needs, so an agent rarely has to call `list_commands`. The worked example at the end runs in CI (`skill_reference_example_builds_as_documented` in `crates/mcp/src/tests.rs`). - Lengths are in mm. +- Lengths take a unit suffix, in parameters and in feature fields: `"16 in"` is 406.4 mm, and `length:"1 in"` works in `solid.box`. `measure` still reports mm. - Angles inside expressions take units: `"30 deg"`. - Any numeric field can be an expression that names parameters: `"w/2 - wall - 6"`. @@ -70,15 +71,15 @@ Distances are unsigned. Draw the geometry on the correct side first, and the dim | Command | Minimal params | Traps | |---|---|---| | `solid.extrude` | `distance` | `profiles` defaults to **every region**, so two concentric circles give a solid disc. Pick regions with `[{"point":[x,y]}]` or `[index]`. Other options: `operation` (new/join/cut/intersect/auto), `direction` (positive/negative/symmetric), `through_all: true`, `start_offset`. A cut that misses reports success. | -| `solid.box` | `length`, `width`, `height` | `center:[x,y,z]` or `corner`. The quickest way to block out a part. | -| `solid.cylinder` | `radius` or `diameter`, `height` | `base` is the centre of the bottom (default origin), `axis` defaults to `Z`. Expressions work in `base`. Always pass `operation`. | +| `solid.box` | `length`, `width`, `height` | `center:[x,y,z]` or `corner`. The quickest way to block out a part. `body_name` names the body it makes. With `operation:"cut"`, `targets:["Top"]` cuts only the bodies listed, so the cutter can pass through other bodies. | +| `solid.cylinder` | `radius` or `diameter`, `height` | `base` is the centre of the bottom (default origin), `axis` defaults to `Z`. Expressions work in `base`. Always pass `operation`. `body_name` and `targets` work as for `solid.box`. | | `sketch.slot.overall` / `sketch.slot.center_to_center` | `p0`, `p1` (overall ends / arc centres), `width` | Ids and dof are in the "Ids" section above. | | `solid.fillet` / `solid.chamfer` | `edges:[[x,y,z]]`, `radius` / `distance` | The pick snaps to the **nearest** edge, with no distance limit and no error, so check that the face count changed. One pick takes the whole tangent chain: a rounded rim needs 1 point, not 8. | | `solid.shell` | `faces:[[x,y,z]]`, `thickness` | A point on each face to remove, or its name from `body_topology`. Fillet first, except an edge of a removed face (see Order in `SKILL.md`). | | `solid.hole` | `position:[x,y,z]` on a face (numbers or length expressions such as `["40", "width/2", "t"]`, which the hole then follows) + `diameter`, or `sketch` (+ `points`) | `clearance:"M3"`. `depth` defaults to through all. `type` is one of simple/drilled/counterbore/countersink. A `countersink` needs `cs_diameter` and `cs_angle`; a `counterbore` needs `cb_diameter` and `cb_depth`. `position` is a fixed point. | | `solid.pattern.rectangular` | `features`, `dir1`, `count1`, `spacing1` (+ `dir2`, `count2`, `spacing2`) | Spacing takes expressions and follows parameters. | | `solid.pattern.circular` | `features`, `axis` (`"Z"` or `{origin, dir}`), `count` | `angle` defaults to 360 deg. A full pattern keeps the COM on the axis, so check its radius with a top-view screenshot. | -| `solid.mirror` | `features:[names]`, `plane` (`XY`/`XZ`/`YZ`, a construction plane, or `{origin, normal}` whose origin may use length expressions) | Follows parameters. Mirror and pattern features cannot be mirrored or patterned again. | +| `solid.mirror` | `features:[names]` or `bodies:[names]`, `plane` (`XY`/`XZ`/`YZ`, a construction plane, or `{origin, normal}` whose origin may use length expressions) | Follows parameters. A mirror or pattern feature cannot be listed in `features` of another mirror or pattern, but `bodies` can mirror the body it made. The mirror is a new body with the first free default name: `Body1`, `Body2` from `features`, and `Side (2)`, `Side (3)` from `bodies:["Side"]`. Read the name from `created_bodies`. With `combine:true`, a mirror that overlaps the original joins it and makes no new body. `features` copies only the features listed, so a later cut is left out unless you list it too. `bodies` copies the finished body. To name the mirror, use `body.rename {"body":"Side (2)","name":"Side_L"}`. The new name stays when parameters change. | - **Names:** name every feature (`"name":"Standoff"`) and keep names unique across sketches and features. `timeline.roll_to {"feature":"Plate"}` picks the first match, which can be the sketch. - **Counts as parameters:** `parameters.add {"name":"n","expression":"6","unit":""}` creates a unitless parameter, and `"count":"n"` uses it in a pattern. @@ -87,7 +88,7 @@ Distances are unsigned. Draw the geometry on the correct side first, and the dim 2. Repeat it with `solid.pattern.circular {"features":["BoltHole"],"axis":"Z","count":"n"}`. Both the radius and the count follow their parameters. -- **Several parameter changes:** use one `batch` of `parameters.change` steps instead of one `set_parameter` call each. +- **Parameter changes:** for one change, call `set_parameter {"name":"L","value":"120 mm"}`. For several, use one `batch` of `parameters.change` steps instead of one `set_parameter` call each. - **Primitive booleans:** a `solid.box` or `solid.cylinder` cut that touches curved faces of the target can fail with `the exact fallback ... takes planar faces only`. Use a sketch profile and an extrude cut instead, for example a slot sketch rather than a box plus 2 cylinders. ## Worked example: parametric plate with 4 counterbored holes (1 batch) From 68c72082030a999c9090c174a571b64e8244f9e8 Mon Sep 17 00:00:00 2001 From: NOWN-DEV <257771410+NOWN-DEV@users.noreply.github.com> Date: Mon, 19 Oct 2026 23:56:22 +0000 Subject: [PATCH 141/225] sketch.edit_text: batch several text edits into one rebuild (#2793) * sketch.edit_text: several texts in one edit, one rebuild Re-texting the labels of a design took one sketch.edit_text per label, and each one rebuilt every feature after the sketch (seconds per label in a large assembly). sketch.edit_text {edits: [{link, text, ...}, ...]} changes them together in one command: one rebuild and one undo step, all or nothing. Co-Authored-By: Claude Opus 5.5 (1M context) * sketch.edit_text: a live frame takes the edits list too The live path (live: true) still read one text's link and refused a list. Both paths now go through one helper. Co-Authored-By: Claude Opus 5.5 (1M context) --------- Co-authored-by: Claude Opus 5.5 (1M context) Co-authored-by: bherbruck --- crates/engine/src/cmd/sketch_create.rs | 27 ++++++++++++++++-- crates/engine/src/cmd/sketch_modify_tests.rs | 29 ++++++++++++++++++++ 2 files changed, 53 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/sketch_create.rs b/crates/engine/src/cmd/sketch_create.rs index 0fb17162b..0a080a7f2 100644 --- a/crates/engine/src/cmd/sketch_create.rs +++ b/crates/engine/src/cmd/sketch_create.rs @@ -112,7 +112,8 @@ pub static COMMANDS: &[CommandSpec] = &[ .params(concat!( "link: the text's link id (or entity: one of its curves), text?, at?, height?, angle?: deg (numbers or expressions as in sketch.text; a number replaces an expression, and so does moving the text), font?: family or file path (empty: the built-in font), ", text_style_doc!(), - " (each kept when left out); live?: bool: one frame of an interactive change (the sketch is solved, the features after it stay as they were until `sketch.drag_end`)", + " (each kept when left out); or edits: [{link or entity, text?, at?, …}]: several texts changed together, the design rebuilt once \ + (all or nothing; returns edits: each one's result); live?: bool: one frame of an interactive change (the sketch is solved, the features after it stay as they were until `sketch.drag_end`)", created_doc!() )), ]; @@ -344,6 +345,9 @@ pub(super) fn move_text(sk: &mut Sketch, link: &str, translate: Vec2, rotation: Ok(sk.link_curves(&link)) } +/// The most texts one `sketch.edit_text {edits}` changes. +const MAX_TEXT_EDITS: usize = 1000; + fn edit_text(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.edit_text"; let id = s.active_sketch.ok_or_else(|| bad(cmd, "no sketch is being edited"))?; @@ -352,7 +356,7 @@ fn edit_text(s: &mut Session, p: &Value) -> Result { // The numbers its expressions give now (a parameter may have changed since the sketch was // last stored); one that cannot be evaluated is left as it was, to be replaced by this edit. let _ = doc.apply_text_values(&doc.param_values().0, &mut sk); - let out = apply_text_edit(&mut sk, &doc, p)?; + let out = apply_text_edits(&mut sk, &doc, p)?; *doc.sketch_mut(id)? = sk; *s.doc_mut() = doc; Ok(out) @@ -363,10 +367,27 @@ fn edit_text(s: &mut Session, p: &Value) -> Result { fn edit_text_live(s: &mut Session, p: &Value) -> Result<(Value, Option)> { let cmd = "sketch.edit_text"; let id = s.active_sketch.ok_or_else(|| bad(cmd, "no sketch is being edited"))?; - let (out, report) = super::sketch::edit_solved(s, id, false, |sk, doc| Ok((apply_text_edit(sk, doc, p)?, super::sketch::Left::Unsolved)))?; + let (out, report) = super::sketch::edit_solved(s, id, false, |sk, doc| Ok((apply_text_edits(sk, doc, p)?, super::sketch::Left::Unsolved)))?; Ok((out, report.map(|report| crate::LiveEdit { sketch: id, report }))) } +/// `sketch.edit_text`'s change: one text's (`link` or `entity`), or each of `edits` in turn. +/// One command, so the features after the sketch are rebuilt once for all of them. +fn apply_text_edits(sk: &mut Sketch, doc: &solidcraft_doc::Document, p: &Value) -> Result { + let cmd = "sketch.edit_text"; + match p.get("edits") { + None | Some(Value::Null) => apply_text_edit(sk, doc, p), + Some(Value::Array(edits)) => { + if edits.is_empty() || edits.len() > MAX_TEXT_EDITS { + return Err(bad(cmd, format!("`edits` must hold 1 to {MAX_TEXT_EDITS} edits"))); + } + let outs = edits.iter().map(|e| apply_text_edit(sk, doc, e)).collect::>>()?; + Ok(json!({"edits": outs})) + } + Some(_) => Err(bad(cmd, "`edits` must be a list of edits")), + } +} + /// `sketch.edit_text`'s change to its sketch: the text source's new values and its outlines /// regenerated from them. fn apply_text_edit(sk: &mut Sketch, doc: &solidcraft_doc::Document, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/sketch_modify_tests.rs b/crates/engine/src/cmd/sketch_modify_tests.rs index a560d7f0c..b8a1f21b3 100644 --- a/crates/engine/src/cmd/sketch_modify_tests.rs +++ b/crates/engine/src/cmd/sketch_modify_tests.rs @@ -1586,6 +1586,35 @@ fn offset_driver_format18_offsets_keep_fixed_distances_on_upgrade() { assert_eq!(ids(&result["curves"]).len(), sk.offsets[0].outputs.len()); } +#[test] +fn several_texts_edit_in_one_rebuild() { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Labels"})); + let a = run(&mut s, "sketch.text", json!({"text": "I", "at": [0, 0], "height": 10}))["link"].as_str().unwrap().to_string(); + let b = run(&mut s, "sketch.text", json!({"text": "I", "at": [30, 0], "height": 10}))["link"].as_str().unwrap().to_string(); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"sketch": "Labels", "distance": 2})); + let volume = |s: &mut Session| run(s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64().unwrap(); + let v0 = volume(&mut s); + run(&mut s, "sketch.edit", json!({"sketch": "Labels"})); + let (before, steps) = (s.evaluations, s.undo.len()); + let r = run(&mut s, "sketch.edit_text", json!({"edits": [{"link": a, "text": "II"}, {"link": b, "text": "II"}]})); + assert_eq!(s.evaluations, before + 1, "one rebuild for both texts"); + assert_eq!(s.undo.len(), steps + 1, "one undo step for both texts"); + assert_eq!(r["edits"][1]["link"], json!(b), "{r}"); + // All or nothing: a bad second edit leaves the first text as it was. + assert!(s.execute("sketch.edit_text", &json!({"edits": [{"link": a, "text": "III"}, {"link": "nope", "text": "I"}]})).is_err()); + assert!(s.execute("sketch.edit_text", &json!({"edits": []})).is_err()); + // A live frame takes the same list. + let r = run(&mut s, "sketch.edit_text", json!({"edits": [{"link": a, "height": 12}, {"link": b, "height": 12}], "live": true})); + assert_eq!(r["edits"][0]["link"], json!(a), "{r}"); + run(&mut s, "sketch.edit_text", json!({"edits": [{"link": a, "height": 10}, {"link": b, "height": 10}], "live": true})); + run(&mut s, "sketch.drag_end", json!({})); + run(&mut s, "sketch.finish", json!({})); + let v1 = volume(&mut s); + assert!((v1 / v0 - 2.0).abs() < 0.05, "two bars per label now: {v0} -> {v1}"); +} + #[test] fn trim_keeps_the_rest_of_a_dimensioned_line_where_it_was() { // A 40 x 40 square, its right side dimensioned with the Dimension tool (a line length). From d55521aa3e8cf70d3b77ab8119e0b8be675e0825 Mon Sep 17 00:00:00 2001 From: kezmdor Date: Mon, 19 Oct 2026 23:56:26 +0000 Subject: [PATCH 142/225] Parameters window: the add row lines up with the table's columns (#2920) (#2932) * claim: #2920 Co-Authored-By: Claude Opus 5.5 * Parameters window: the add row lines up with the table's columns (#2920) The add row was a row of its own under the User Parameters table, so its fields did not sit under the headings, least of all before the first user parameter, when the headings had no rows to size their columns. It is now the table's last row. Its text boxes take the rows' widths, since a grid cell otherwise gives them only the column's width so far. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: kezmdor <15539254+kezmdor@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/params_dialog.rs | 155 ++++++++++++++++++---------- 1 file changed, 98 insertions(+), 57 deletions(-) diff --git a/crates/ui-egui/src/params_dialog.rs b/crates/ui-egui/src/params_dialog.rs index fbea97f99..475a08e42 100644 --- a/crates/ui-egui/src/params_dialog.rs +++ b/crates/ui-egui/src/params_dialog.rs @@ -191,7 +191,6 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { section(ui, &t, "User Parameters"); let users: Vec<&Row> = visible.iter().copied().filter(|r| r.source == "user").collect(); table(app, ui, &mut d, &users, "user"); - add_row(app, ui, &mut d); section(ui, &t, "Model Parameters"); let mut groups: Vec = Vec::new(); for r in visible.iter().filter(|r| r.source != "user") { @@ -258,7 +257,8 @@ fn table(app: &mut SolveApp, ui: &mut egui::Ui, d: &mut ParamsDialog, rows: &[&R let t = Tokens::get(); egui::Grid::new(("ptable", salt)).num_columns(7).striped(true).spacing([10.0, 4.0]).show(ui, |ui| { for h in ["", "Name", "Unit", "Expression", "Value", "Comment", ""] { - ui.label(RichText::new(h).color(t.text_dim).small()); + let resp = ui.label(RichText::new(h).color(t.text_dim).small()); + crate::scenario::publish_rect(&format!("param:heading:{salt}:{h}"), resp.rect); } ui.end_row(); // Only the rows in view are laid out (#2723); the others take their height, so the @@ -407,6 +407,11 @@ fn table(app: &mut SolveApp, ui: &mut egui::Ui, d: &mut ParamsDialog, rows: &[&R } ui.end_row(); } + // The add row is the user table's last row, so its fields sit under the headings, + // with or without user parameters (#2920). + if salt == "user" { + add_row(app, ui, d); + } }); } @@ -429,69 +434,79 @@ fn enter_for(ui: &mut egui::Ui, focused: bool) -> bool { }) } +/// The add row, one cell per column of the user table it ends. fn add_row(app: &mut SolveApp, ui: &mut egui::Ui, d: &mut ParamsDialog) { let t = Tokens::get(); - ui.horizontal(|ui| { - let name_id = ui.make_persistent_id("pnew_name"); - let expr_id = ui.make_persistent_id("pnew_expr"); - let comment_id = ui.make_persistent_id("pnew_comment"); - let focused_id = ui.memory(|m| [name_id, expr_id, comment_id].into_iter().find(|id| m.has_focus(*id))); - let name = - ui.add(egui::TextEdit::singleline(&mut d.new_name).id(name_id).hint_text(crate::i18n::tr_label("new parameter")).desired_width(120.0)); - crate::scenario::publish_handle("param:new:name", name.rect.center()); - let unit_response = egui::ComboBox::from_id_salt("pnew_unit") - .width(56.0) - .selected_text(unit_label(UNITS.get(d.new_unit).copied().unwrap_or("mm"))) - .show_ui(ui, |ui| { - for (i, u) in UNITS.iter().enumerate() { - ui.selectable_value(&mut d.new_unit, i, unit_label(u)); - } - }); - crate::scenario::publish_handle("param:new:unit", unit_response.response.rect.center()); - let unit = UNITS.get(d.new_unit).copied().unwrap_or("mm"); - let bad = new_check(app, d, unit).is_err(); - let mut te = egui::TextEdit::singleline(&mut d.new_expr).id(expr_id).desired_width(170.0); - if bad { - te = te.text_color(t.error); + let name_id = ui.make_persistent_id("pnew_name"); + let expr_id = ui.make_persistent_id("pnew_expr"); + let comment_id = ui.make_persistent_id("pnew_comment"); + let focused_id = ui.memory(|m| [name_id, expr_id, comment_id].into_iter().find(|id| m.has_focus(*id))); + // The column of the favourite and move buttons. + ui.label(""); + // Sized like the rows' boxes: in a grid cell a text box only gets the column's width so far. + let name = ui.add_sized( + [120.0, 20.0], + egui::TextEdit::singleline(&mut d.new_name).id(name_id).hint_text(crate::i18n::tr_label("new parameter")).desired_width(120.0), + ); + crate::scenario::publish_handle("param:new:name", name.rect.center()); + crate::scenario::publish_rect("param:new:name", name.rect); + let unit_response = egui::ComboBox::from_id_salt("pnew_unit") + .width(56.0) + .selected_text(unit_label(UNITS.get(d.new_unit).copied().unwrap_or("mm"))) + .show_ui(ui, |ui| { + for (i, u) in UNITS.iter().enumerate() { + ui.selectable_value(&mut d.new_unit, i, unit_label(u)); + } + }); + crate::scenario::publish_handle("param:new:unit", unit_response.response.rect.center()); + crate::scenario::publish_rect("param:new:unit", unit_response.response.rect); + let unit = UNITS.get(d.new_unit).copied().unwrap_or("mm"); + let bad = new_check(app, d, unit).is_err(); + let mut te = egui::TextEdit::singleline(&mut d.new_expr).id(expr_id).desired_width(170.0); + if bad { + te = te.text_color(t.error); + } + let resp = ui.add_sized([170.0, 20.0], te); + crate::scenario::publish_handle("param:new:expression", resp.rect.center()); + crate::scenario::publish_rect("param:new:expression", resp.rect); + let completed = complete(ui, &resp, &mut d.new_expr); + let live = new_check(app, d, unit); + let value = match &live { + Ok(v) => ui.label(RichText::new(v).color(t.text_dim)), + Err(m) => ui.label(RichText::new(m).color(t.error)), + }; + crate::scenario::publish_rect("param:new:value", value.rect); + let comment = + ui.add_sized([150.0, 20.0], egui::TextEdit::singleline(&mut d.new_comment).id(comment_id).hint_text("comment").desired_width(150.0)); + crate::scenario::publish_handle("param:new:comment", comment.rect.center()); + crate::scenario::publish_rect("param:new:comment", comment.rect); + let submit = !completed && enter_for(ui, focused_id.is_some()); + let ok = !d.new_name.trim().is_empty() && live.is_ok(); + if ui.add_enabled(ok, egui::Button::new(crate::i18n::tr_label("Add"))).clicked() || submit { + if let Err(error) = &live { + d.error = Some(error.clone()); + if let Some(id) = focused_id { + ui.memory_mut(|m| m.request_focus(id)); + } + return; } - let resp = ui.add(te); - crate::scenario::publish_handle("param:new:expression", resp.rect.center()); - let completed = complete(ui, &resp, &mut d.new_expr); - let live = new_check(app, d, unit); - match &live { - Ok(v) => ui.label(RichText::new(v).color(t.text_dim)), - Err(m) => ui.label(RichText::new(m).color(t.error)), - }; - let comment = ui.add(egui::TextEdit::singleline(&mut d.new_comment).id(comment_id).hint_text("comment").desired_width(120.0)); - crate::scenario::publish_handle("param:new:comment", comment.rect.center()); - let submit = !completed && enter_for(ui, focused_id.is_some()); - let ok = !d.new_name.trim().is_empty() && live.is_ok(); - if ui.add_enabled(ok, egui::Button::new(crate::i18n::tr_label("Add"))).clicked() || submit { - if let Err(error) = &live { - d.error = Some(error.clone()); + let p = json!({"name": d.new_name.trim(), "expression": d.new_expr, "unit": unit, "comment": d.new_comment}); + match app.run("parameters.add", p) { + Ok(_) => { + d.new_name.clear(); + d.new_expr = NEW_EXPR.into(); + d.new_comment.clear(); + d.error = None; + name.request_focus(); + } + Err(e) => { + d.error = Some(e); if let Some(id) = focused_id { ui.memory_mut(|m| m.request_focus(id)); } - return; - } - let p = json!({"name": d.new_name.trim(), "expression": d.new_expr, "unit": unit, "comment": d.new_comment}); - match app.run("parameters.add", p) { - Ok(_) => { - d.new_name.clear(); - d.new_expr = NEW_EXPR.into(); - d.new_comment.clear(); - d.error = None; - name.request_focus(); - } - Err(e) => { - d.error = Some(e); - if let Some(id) = focused_id { - ui.memory_mut(|m| m.request_focus(id)); - } - } } } - }); + } } /// A completion offered under an expression box. @@ -679,4 +694,30 @@ mod tests { let d = h.app.params.as_ref().unwrap(); assert!(d.listed.as_ref().unwrap().1.iter().any(|r| r.name == "p1" && r.comment == "hello")); } + + /// The add row's fields start where their headings do (#2920): before the first user + /// parameter, when the headings stood over nothing, and with one. Its text boxes keep + /// the rows' widths, so "new parameter" is not cut short. + #[test] + fn the_add_row_lines_up_with_the_headings() { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.step(&json!({"start": "parameters.change"})).unwrap(); + let aligned = |case: &str| { + for (heading, field) in [("Name", "name"), ("Unit", "unit"), ("Expression", "expression"), ("Value", "value"), ("Comment", "comment")] { + let head = crate::scenario::rect_of(&format!("param:heading:user:{heading}")).unwrap(); + let cell = crate::scenario::rect_of(&format!("param:new:{field}")).unwrap(); + assert!((head.left() - cell.left()).abs() < 0.5, "{case}: {heading} heading at x {}, its field at x {}", head.left(), cell.left()); + } + for (field, width) in [("name", 120.0), ("expression", 170.0), ("comment", 150.0)] { + let cell = crate::scenario::rect_of(&format!("param:new:{field}")).unwrap(); + assert!(cell.width() >= width - 0.5, "{case}: the {field} box is {} wide", cell.width()); + } + }; + h.frames(3); + aligned("no user parameter"); + h.app.run("parameters.add", json!({"name": "width", "expression": "40 mm", "unit": "mm"})).unwrap(); + h.frames(3); + aligned("one user parameter"); + } } From 57b52d8a49bd57b3b15aa73d1dc7d88bdb9a2c80 Mon Sep 17 00:00:00 2001 From: N3MI-DG <129717180+N3MI-DG@users.noreply.github.com> Date: Mon, 19 Oct 2026 23:56:28 +0000 Subject: [PATCH 143/225] Browser: light the rows of what is selected or hovered in the 3D view (#3009) * Browser model: find the placement a body is in Model::body_path maps a placed body (by its world name) to the occurrence path of the placement holding it, as the browser's occurrence rows nest. Every placement is walked once per model, from the placements the browser already caches, so asking it every frame stays cheap. The next commits use it to mark the rows leading to a body. Co-Authored-By: Claude Opus 5.5 * Browser: rows can carry a mark for a lit item and its branch A row's Mark draws a bar down its left edge: a solid one on a lit item's own row (which also takes the hover colour unless it is selected), and a thinner, fainter one on each row leading to it, so the bars trace the item's branch through the tree. Nothing sets a mark yet. Co-Authored-By: Claude Opus 5.5 * Browser: light the rows of what is selected or hovered in the 3D view The tree now follows the 3D view. Whatever is selected (in the tree or in the view) or under the pointer in the view lights its row: the selection colour when selected, the hover colour when hovered, with a solid bar; each row leading to it gets a faint bar, also when the folders are closed. - A body lights for itself and for a selected or hovered face, edge or vertex of it. - A sketch lights for its curves, points and profiles, including those of the sketch being edited. - Construction planes, and the origin planes and axes, light their rows; the Origin folder carries the faint bar. - The rows leading to an item are the design, the placements above it (by the placement path of a body; for a sketch or plane, every placement of its component), its folder and its group. A row's own selected flag, which drag and the context menu go by, is unchanged: the selection colour for things picked in the view is drawn separately. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/browser.rs | 204 +++++++++++++++++++++++++--- crates/ui-egui/src/browser_model.rs | 33 +++++ 2 files changed, 220 insertions(+), 17 deletions(-) diff --git a/crates/ui-egui/src/browser.rs b/crates/ui-egui/src/browser.rs index 7e666d2e7..40f19acae 100644 --- a/crates/ui-egui/src/browser.rs +++ b/crates/ui-egui/src/browser.rs @@ -291,6 +291,19 @@ pub(crate) struct Row<'a> { pub(crate) radio: Option, /// Trailing badges: "lock", "pin". pub(crate) badges: &'a [&'a str], + /// Lit by the selection or the 3D view's pointer: the item's own row, or a row leading to it. + pub(crate) mark: Mark, +} + +/// How a row relates to what the selection and the 3D view's pointer light. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum Mark { + #[default] + None, + /// A row a lit item is inside (its component, placement, folder or group): a faint bar. + Branch, + /// A lit item's own row: a solid bar, and the hover colour unless it is selected. + Here, } /// What happened on a row. @@ -328,9 +341,19 @@ pub(crate) fn draw_row(ui: &mut egui::Ui, id: egui::Id, row: &Row) -> RowResp { let mut out = RowResp { rect: Some(r), hovered: resp.hovered() || dragged_over, ..Default::default() }; if row.selected { ui.painter().rect_filled(r, 3.0, t.accent_soft); - } else if resp.hovered() { + } else if resp.hovered() || row.mark == Mark::Here { ui.painter().rect_filled(r, 3.0, t.hover); } + // A lit item (selected, or under the pointer in the 3D view): a bar down the left of its row, + // and a fainter, thinner one on each row leading to it, so the bars trace its branch. + let bar = match row.mark { + Mark::None => None, + Mark::Branch => Some((2.0, t.accent.gamma_multiply(0.4))), + Mark::Here => Some((3.0, t.accent)), + }; + if let Some((w, colour)) = bar { + ui.painter().rect_filled(Rect::from_min_size(r.left_top() + vec2(0.0, 2.0), vec2(w, r.height() - 4.0)), 1.0, colour); + } let mut x = r.left() + 2.0 + row.depth as f32 * INDENT; let cy = r.center().y; // The row is one widget: where a click lands decides what it does (the fold arrow with @@ -491,6 +514,128 @@ struct Actions { menu: Option<(Pos2, Target)>, hover_bodies: Vec, drop: Option, + /// What the selection and the 3D view's pointer light in the tree. + lit: Lit, +} + +/// Something in the 3D view with a row in the tree. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +enum Thing { + Body(String), + /// A sketch, by feature id. + Sketch(u64), + /// An origin or construction plane, by name. + Plane(String), + /// An origin axis. + Axis(String), +} + +/// What the tree lights for the selection and the 3D view's pointer: each lit item's row (in +/// the selection colour when selected, the hover colour when under the pointer, with a bar +/// down its left), and a faint bar on each row leading to it. +#[derive(Default)] +struct Lit { + /// Selected, or part of something selected: a body for its faces, edges and vertices, a + /// sketch for its curves, points and profiles. + selected: std::collections::HashSet, + /// Under the pointer in the 3D view. + hovered: Option, + /// The placements holding a lit body, and the components holding a lit sketch or plane. + paths: Vec>, + components: Vec, +} + +impl Lit { + fn of(app: &mut SolveApp) -> Lit { + use crate::viewport::Hit; + let mut selected = std::collections::HashSet::new(); + for s in &app.session.selection { + selected.insert(match s { + Sel::Body { name } | Sel::Face { body: name, .. } | Sel::Edge { body: name, .. } | Sel::Vertex { body: name, .. } => { + Thing::Body(name.clone()) + } + Sel::Feature { id } => Thing::Sketch(*id), + Sel::Profile { sketch, .. } | Sel::ExternalSketchCurve { sketch, .. } | Sel::ExternalSketchPoint { sketch, .. } => { + Thing::Sketch(*sketch) + } + Sel::SketchCurve { .. } | Sel::SketchPoint { .. } | Sel::SketchConstraint { .. } => match app.session.active_sketch { + Some(id) => Thing::Sketch(id), + None => continue, + }, + Sel::Plane { name } => Thing::Plane(name.clone()), + Sel::Axis { name } => Thing::Axis(name.clone()), + Sel::Occurrence { .. } => continue, + }); + } + let hovered = match &app.viewport.hover { + Some(Hit::Face { body, .. } | Hit::Edge { body, .. } | Hit::Vertex { body, .. }) => Some(Thing::Body(body.clone())), + Some(Hit::SketchPoint { sketch, .. } | Hit::SketchCurve { sketch, .. } | Hit::Profile { sketch, .. }) => Some(Thing::Sketch(*sketch)), + Some(Hit::Plane { name, .. }) => Some(Thing::Plane(name.clone())), + Some(Hit::Axis { name }) => Some(Thing::Axis(name.clone())), + None => None, + }; + let doc = app.session.doc.clone(); + let (mut paths, mut components) = (Vec::new(), Vec::new()); + for thing in selected.iter().chain(&hovered) { + match thing { + Thing::Body(b) => { + if let Some(path) = app.tree.model.as_mut().and_then(|model| model.body_path(&app.session, b)) { + paths.push(path); + } + } + Thing::Sketch(id) => { + components.extend(doc.features.iter().find(|f| f.id == *id && matches!(f.kind, FeatureKind::Sketch { .. })).map(|f| f.component)) + } + Thing::Plane(name) => components.extend( + doc.features.iter().find(|f| f.name == *name && matches!(f.kind, FeatureKind::ConstructionPlane { .. })).map(|f| f.component), + ), + Thing::Axis(_) => {} + } + } + Lit { selected, hovered, paths, components } + } + + fn any(&self) -> bool { + !self.selected.is_empty() || self.hovered.is_some() + } + + /// Whether `thing` is lit: (selected, under the pointer). + fn thing(&self, thing: &Thing) -> (bool, bool) { + (self.selected.contains(thing), self.hovered.as_ref() == Some(thing)) + } + + /// The things a folder entry stands for. + fn entry_things(folder: &str, e: &Entry) -> Vec { + match folder { + "bodies" => e.bodies.iter().cloned().map(Thing::Body).collect(), + "sketches" => e.key.parse().ok().map(Thing::Sketch).into_iter().collect(), + _ => vec![Thing::Plane(e.label.clone())], + } + } + + /// Whether a folder entry is lit: (selected, under the pointer). Its own `selected` (picked + /// in the tree, or the sketch being edited) counts as selected. + fn entry(&self, folder: &str, e: &Entry) -> (bool, bool) { + let things = Lit::entry_things(folder, e); + (e.selected || things.iter().any(|t| self.selected.contains(t)), things.iter().any(|t| self.hovered.as_ref() == Some(t))) + } + + /// The mark of a row holding these entries: a faint bar when any of them is lit. + fn branch<'e>(&self, folder: &str, entries: impl IntoIterator) -> Mark { + if entries.into_iter().any(|e| self.entry(folder, e) != (false, false)) { Mark::Branch } else { Mark::None } + } + + /// The mark of a placement row: a faint bar when a lit body is placed in it or below it, or + /// a lit sketch or plane belongs to its component or one inside it. + fn placement(&self, doc: &solidcraft_engine::doc::Document, path: &[u64], component: u64) -> Mark { + let below = self.paths.iter().any(|p| p.starts_with(path)) || self.components.iter().any(|c| doc.component_within(*c, component)); + if below { Mark::Branch } else { Mark::None } + } +} + +/// A lit row's look: `(selected, under the pointer)` to the row's selection flag and mark. +fn lit_row((selected, hovered): (bool, bool)) -> (bool, Mark) { + (selected, if selected || hovered { Mark::Here } else { Mark::None }) } pub fn browser(app: &mut SolveApp, ui: &mut egui::Ui) { @@ -682,6 +827,7 @@ fn browser_rows_hugging(app: &mut SolveApp, ui: &mut egui::Ui, acts: &mut Action fn rows_scrolling(app: &mut SolveApp, ui: &mut egui::Ui, acts: &mut Actions, shrink_height: bool) { prepare_model(app); + acts.lit = Lit::of(app); egui::ScrollArea::vertical() .auto_shrink([false, shrink_height]) .scroll_source(egui::scroll_area::ScrollSource { scroll_bar: true, mouse_wheel: true, ..egui::scroll_area::ScrollSource::NONE }) @@ -739,6 +885,8 @@ fn component_rows(app: &mut SolveApp, ui: &mut egui::Ui, id: u64, depth: usize, dim: faded, radio: Some(active), badges, + // The design holds everything the tree lists. + mark: if id == 0 && acts.lit.any() { Mark::Branch } else { Mark::None }, ..Default::default() }; let r = draw_row(ui, ui.id().with(("comp", id)), &row); @@ -796,7 +944,7 @@ fn component_rows(app: &mut SolveApp, ui: &mut egui::Ui, id: u64, depth: usize, if id == 0 { doc_settings(app, ui, d); named_view_rows(app, ui, d, acts); - origin_rows(app, ui, d); + origin_rows(app, ui, d, acts); canvas_rows(app, ui, d, acts); analysis_rows(app, ui, d, acts); } @@ -848,6 +996,7 @@ fn occurrence_rows(app: &mut SolveApp, ui: &mut egui::Ui, path: Vec, depth: dim: faded || !visible, radio: Some(active), badges, + mark: acts.lit.placement(&app.session.doc, &path, placement.component), ..Default::default() }, ); @@ -953,9 +1102,25 @@ fn doc_settings(app: &mut SolveApp, ui: &mut egui::Ui, depth: usize) { } } -fn origin_rows(app: &mut SolveApp, ui: &mut egui::Ui, depth: usize) { +/// The origin point, axes and planes, as `(key, icon, thing lit for it)`. +fn origin_things() -> [(&'static str, &'static str, Option); 7] { + let (axis, plane) = (|k: &str| Some(Thing::Axis(k.into())), |k: &str| Some(Thing::Plane(k.into()))); + [ + ("O", "point", None), + ("X", "axis", axis("X")), + ("Y", "axis", axis("Y")), + ("Z", "axis", axis("Z")), + ("XY", "plane", plane("XY")), + ("XZ", "plane", plane("XZ")), + ("YZ", "plane", plane("YZ")), + ] +} + +fn origin_rows(app: &mut SolveApp, ui: &mut egui::Ui, depth: usize, acts: &Actions) { let key = "origin"; let open = is_open(app, key, false); + let lit = |thing: &Option| thing.as_ref().map_or((false, false), |t| acts.lit.thing(t)); + let items = origin_things(); let r = draw_row( ui, ui.id().with(key), @@ -966,6 +1131,7 @@ fn origin_rows(app: &mut SolveApp, ui: &mut egui::Ui, depth: usize) { icon: "origin", label: "Origin", dim: !app.ui.show_origin, + mark: if items.iter().any(|(_, _, thing)| lit(thing) != (false, false)) { Mark::Branch } else { Mark::None }, ..Default::default() }, ); @@ -981,28 +1147,20 @@ fn origin_rows(app: &mut SolveApp, ui: &mut egui::Ui, depth: usize) { if !open { return; } - let items = [ - ("O", "point", "O"), - ("X", "axis", "X"), - ("Y", "axis", "Y"), - ("Z", "axis", "Z"), - ("XY", "plane", "XY"), - ("XZ", "plane", "XZ"), - ("YZ", "plane", "YZ"), - ]; - for (k, icon, label) in items { + for (k, icon, thing) in items { + let label = k; let visible = !app.session.visibility.hidden_origin.iter().any(|h| h == k); let sel = match icon { "plane" => Some(Sel::Plane { name: k.into() }), "axis" => Some(Sel::Axis { name: k.into() }), _ => None, }; - let selected = sel.as_ref().is_some_and(|x| app.session.selection.contains(x)); + let (selected, mark) = lit_row(lit(&thing)); let r = draw_row( ui, ui.id().with(("o", k)), // Faded when hidden itself or with the whole Origin. - &Row { depth: depth + 1, eye: Some(visible), icon, label, selected, dim: !visible || !app.ui.show_origin, ..Default::default() }, + &Row { depth: depth + 1, eye: Some(visible), icon, label, selected, dim: !visible || !app.ui.show_origin, mark, ..Default::default() }, ); if r.eye { if visible { @@ -1629,7 +1787,16 @@ fn folder_rows_at(app: &mut SolveApp, ui: &mut egui::Ui, comp: u64, path: Option let r = draw_row( ui, ui.id().with(&key), - &Row { depth, fold: Some(open), eye: Some(shown), icon: "folder", label: folder_label(folder), dim: folder_faded, ..Default::default() }, + &Row { + depth, + fold: Some(open), + eye: Some(shown), + icon: "folder", + label: folder_label(folder), + dim: folder_faded, + mark: acts.lit.branch(folder, &all), + ..Default::default() + }, ); if r.fold || r.clicked { toggle(app, &key, true); @@ -1671,6 +1838,7 @@ fn folder_rows_at(app: &mut SolveApp, ui: &mut egui::Ui, comp: u64, path: Option label: &label, name: true, dim: group_faded, + mark: acts.lit.branch(folder, items), ..Default::default() }, ); @@ -1725,6 +1893,7 @@ fn entry_row( let pattern_key = format!("{}/patterns", e.row_key); let patterns_open = is_open(app, &pattern_key, true); let badges: &[&str] = if e.locked { &["lock"] } else { &[] }; + let (selected, mark) = lit_row(acts.lit.entry(folder, e)); let r = draw_row( ui, ui.id().with(("item", &e.row_key)), @@ -1735,10 +1904,11 @@ fn entry_row( icon: e.icon, label: &e.label, name: true, - selected: e.selected, + selected, dim: !e.visible || parent_hidden, color: e.color, badges, + mark, ..Default::default() }, ); diff --git a/crates/ui-egui/src/browser_model.rs b/crates/ui-egui/src/browser_model.rs index 5505d8175..b1316dfa3 100644 --- a/crates/ui-egui/src/browser_model.rs +++ b/crates/ui-egui/src/browser_model.rs @@ -19,6 +19,8 @@ pub(super) struct Model { pub planes: HashMap>, pub children: HashMap>, placements: HashMap, Option>>, + /// Each placed body's placement path, by the body's world name (built on first use). + body_paths: Option>>, } impl Model { @@ -51,6 +53,7 @@ impl Model { planes, children, placements: HashMap::new(), + body_paths: None, } } @@ -61,4 +64,34 @@ impl Model { pub fn placement(&mut self, session: &Session, path: &[u64]) -> Option> { self.placements.entry(path.to_vec()).or_insert_with(|| session.occurrence_placement(path).ok().map(Arc::new)).clone() } + + /// The placement a placed body (by its world name) belongs to, as the browser's occurrence + /// rows nest; `None` for a body of the top-level design. Every placement is walked once per + /// model, as deep and as far as the browser draws them. + pub fn body_path(&mut self, session: &Session, body: &str) -> Option> { + if self.body_paths.is_none() { + let mut paths: HashMap> = HashMap::new(); + let mut stack: Vec> = self.children.get(&0).into_iter().flatten().map(|o| vec![*o]).collect(); + let mut walked = 0; + while let Some(path) = stack.pop() { + walked += 1; + if walked > 100_000 { + break; + } + let Some(placement) = self.placement(session, &path) else { continue }; + for b in &placement.bodies { + paths.entry(b.world.clone()).or_insert_with(|| path.clone()); + } + if path.len() < 64 { + for child in self.children.get(&placement.component).into_iter().flatten() { + let mut next = path.clone(); + next.push(*child); + stack.push(next); + } + } + } + self.body_paths = Some(paths); + } + self.body_paths.as_ref()?.get(body).cloned() + } } From af436493a241c5ec7e3b9fb97ad5e8c30186a5d5 Mon Sep 17 00:00:00 2001 From: NOWN-DEV <257771410+NOWN-DEV@users.noreply.github.com> Date: Mon, 19 Oct 2026 23:56:32 +0000 Subject: [PATCH 144/225] Joints: a point origin keeps the x it is given (#2597) (#2598) * Joints: a point origin keeps the x it is given `joint.origin` and `joint.create` take `x` for a point origin (a direction, laid square to z) and the point snap saves it. Two origins given at one point with the same z and x now meet as they are: a part turned a quarter turn about z no longer turns back (and moves) when rigid-joined there. A point origin without x takes its x from z alone, as before. An x along z, or of no length, is refused. Co-Authored-By: Claude Opus 5.5 (1M context) * Joint relations test: a point origin has an x too Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01Aac7mP9rthK3WsPpPRvCsF --------- Co-authored-by: Claude Opus 5.5 (1M context) Co-authored-by: bherbruck --- .../format/pending/joint-origin-point-x.rs | 4 ++ crates/doc/src/joints.rs | 11 ++-- crates/doc/src/joints_cam.rs | 2 +- crates/doc/src/joints_relations.rs | 2 +- .../src/cmd/component_clone_assembly_tests.rs | 2 +- crates/engine/src/cmd/joints.rs | 24 ++++++-- crates/engine/src/cmd/joints_face_tests.rs | 9 ++- crates/engine/src/cmd/joints_point_x_tests.rs | 59 +++++++++++++++++++ 8 files changed, 99 insertions(+), 14 deletions(-) create mode 100644 crates/doc/src/format/pending/joint-origin-point-x.rs create mode 100644 crates/engine/src/cmd/joints_point_x_tests.rs diff --git a/crates/doc/src/format/pending/joint-origin-point-x.rs b/crates/doc/src/format/pending/joint-origin-point-x.rs new file mode 100644 index 000000000..e2f18f0f8 --- /dev/null +++ b/crates/doc/src/format/pending/joint-origin-point-x.rs @@ -0,0 +1,4 @@ +//! A point joint origin (`Snap::Point`) can save `x`, the direction its frame's x takes (laid +//! square to z). Older designs need no transformation: a point origin without `x` takes its x +//! from z alone, as before; the last release asks for an update instead of dropping the `x` and +//! turning the part. diff --git a/crates/doc/src/joints.rs b/crates/doc/src/joints.rs index 7f26578f4..9b9942b59 100644 --- a/crates/doc/src/joints.rs +++ b/crates/doc/src/joints.rs @@ -76,11 +76,14 @@ pub enum Snap { #[serde(default, skip_serializing_if = "Option::is_none")] corner: Option, }, - /// A point, z along `z` (default +Z). + /// A point, z along `z` (default +Z) and x toward `x` laid square to z (default: one chosen + /// from z alone). Point { point: Vec3, #[serde(default, skip_serializing_if = "Option::is_none")] z: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + x: Option, }, } @@ -175,7 +178,7 @@ impl Snap { match self { Snap::Frame { origin, z, x } => origin.is_finite() && z.is_finite() && x.is_none_or(|x| x.is_finite()), Snap::FaceCenter { pick, x, .. } | Snap::CircleCenter { pick, x, .. } => pick.is_finite() && x_ok(x), - Snap::Point { point, z } => point.is_finite() && z.is_none_or(|z| z.is_finite()), + Snap::Point { point, z, x } => point.is_finite() && z.is_none_or(|z| z.is_finite()) && x.is_none_or(|x| x.is_finite()), Snap::Edge { pick, .. } => pick.is_finite(), } } @@ -749,7 +752,7 @@ pub fn resolve_origin(doc: &Document, st: &ModelState, o: &JointOrigin) -> Resul let bad = || DocError::Invalid("joint origin: degenerate frame".into()); match &o.snap { Snap::Frame { origin, z, x } => frame(*origin, *z, *x).ok_or_else(bad), - Snap::Point { point, z } => frame(*point, z.unwrap_or(Vec3::Z), None).ok_or_else(bad), + Snap::Point { point, z, x } => frame(*point, z.unwrap_or(Vec3::Z), *x).ok_or_else(bad), Snap::FaceCenter { pick, face, x } => { // A named planar face gives its own centre and normal; another face (or none) the // planar face nearest the point. @@ -1932,7 +1935,7 @@ mod tests { /// Revolute joints 1…n (joint 1 at `start`, the others at 0) linked 1 → 2 → … → n with /// ratio 2, the links stored from the end of the chain; joint 3 limited to ±50. fn chain(n: u64, start: f64) -> Assembly { - let origin = JointOrigin { occurrence: 0, snap: Snap::Point { point: Vec3::ZERO, z: None } }; + let origin = JointOrigin { occurrence: 0, snap: Snap::Point { point: Vec3::ZERO, z: None, x: None } }; let joints = (1..=n) .map(|id| Joint { id, diff --git a/crates/doc/src/joints_cam.rs b/crates/doc/src/joints_cam.rs index e0ad1095d..16fafc6f5 100644 --- a/crates/doc/src/joints_cam.rs +++ b/crates/doc/src/joints_cam.rs @@ -954,7 +954,7 @@ mod tests { /// a guide only on the cam's own side is refused. #[test] fn the_guide_is_the_side_fewer_moving_joints_from_the_frame() { - let origin = JointOrigin { occurrence: 0, snap: super::super::Snap::Point { point: Vec3::ZERO, z: None } }; + let origin = JointOrigin { occurrence: 0, snap: super::super::Snap::Point { point: Vec3::ZERO, z: None, x: None } }; let joint = |id: u64, kind: JointKind, a: u64, b: u64| super::super::Joint { id, name: format!("J{id}"), diff --git a/crates/doc/src/joints_relations.rs b/crates/doc/src/joints_relations.rs index f22677a34..cd3f5fe0f 100644 --- a/crates/doc/src/joints_relations.rs +++ b/crates/doc/src/joints_relations.rs @@ -82,7 +82,7 @@ mod tests { use solidcraft_geom::Vec3; fn joint(kind: JointKind) -> Joint { - let at = |occurrence| JointOrigin { occurrence, snap: Snap::Point { point: Vec3::ZERO, z: None } }; + let at = |occurrence| JointOrigin { occurrence, snap: Snap::Point { point: Vec3::ZERO, z: None, x: None } }; Joint { id: 1, name: "R".into(), diff --git a/crates/engine/src/cmd/component_clone_assembly_tests.rs b/crates/engine/src/cmd/component_clone_assembly_tests.rs index cb0a2e08e..14475aaad 100644 --- a/crates/engine/src/cmd/component_clone_assembly_tests.rs +++ b/crates/engine/src/cmd/component_clone_assembly_tests.rs @@ -6,7 +6,7 @@ use solidcraft_doc::{IDENTITY, Occurrence}; use solidcraft_geom::Vec3; fn at(occurrence: u64) -> JointOrigin { - JointOrigin { occurrence, snap: Snap::Point { point: Vec3::ZERO, z: None } } + JointOrigin { occurrence, snap: Snap::Point { point: Vec3::ZERO, z: None, x: None } } } fn joint(id: u64, a: u64, b: u64) -> Joint { diff --git a/crates/engine/src/cmd/joints.rs b/crates/engine/src/cmd/joints.rs index 6bfccac5d..8481682ee 100644 --- a/crates/engine/src/cmd/joints.rs +++ b/crates/engine/src/cmd/joints.rs @@ -17,11 +17,11 @@ use crate::{EngineError, Result, Session}; pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("joint.origin", "Joint Origin", joint_origin).at("SOLID", "CREATE").icon("joint_origin").params( - "name?, occurrence?: id|name (default: from the pick, or the named face's component), face: [x,y,z] | \"\" (centre of a planar face) | circle: [x,y,z] | \"\" (centre of a round end: a point on its wall or rim, the end's centre, or the round face's name as model.faces lists it) | edge: [x,y,z] (a point on an edge of a planar face: the edge's middle, z out of the face, y into it; on?: [x,y,z] a point on the face (default: the larger planar face beside the edge); corner?: [x,y,z] near one end: the corner there, x and y along its two edges into the face; found again by name, so it follows the face as it changes size) | point: [x,y,z], z?: [x,y,z]; body?: the named face's body; end?: \"\" (a circle's end: the face across its rim there; default the end nearer the pick); x?: [x,y,z] (a direction, world) | \"\" | {face: [x,y,z]} (the frame's x: a direction, a plane's normal, or the way to another hole's axis; keeps a round origin's turn). Faces are kept by name: the origin follows its face, and a circle its end, when the design changes", + "name?, occurrence?: id|name (default: from the pick, or the named face's component), face: [x,y,z] | \"\" (centre of a planar face) | circle: [x,y,z] | \"\" (centre of a round end: a point on its wall or rim, the end's centre, or the round face's name as model.faces lists it) | edge: [x,y,z] (a point on an edge of a planar face: the edge's middle, z out of the face, y into it; on?: [x,y,z] a point on the face (default: the larger planar face beside the edge); corner?: [x,y,z] near one end: the corner there, x and y along its two edges into the face; found again by name, so it follows the face as it changes size) | point: [x,y,z], z?: [x,y,z]; body?: the named face's body; end?: \"\" (a circle's end: the face across its rim there; default the end nearer the pick); x?: [x,y,z] (a direction, world) | \"\" | {face: [x,y,z]} (the frame's x: a direction, a plane's normal, or the way to another hole's axis; keeps a round origin's turn; a point's x is a direction, laid square to its z, default: chosen from z alone). Faces are kept by name: the origin follows its face, and a circle its end, when the design changes", ), CommandSpec::new("joint.create", "Joint", joint).at("SOLID", "ASSEMBLE").icon("joint").key("J").params( "type: rigid|revolute|slider|cylindrical|pin_slot|planar|ball, or a relation: parallel|perpendicular|angle|point_on_plane|point_on_line|line_on_plane \ - (ties only some directions or points, made where the parts are; several between two parts add up); a, b: joint origins ({occurrence, face|circle|edge|point: [x,y,z] in world, or face|circle: \"\"; end?, x? as joint.origin} | origin name); \ + (ties only some directions or points, made where the parts are; several between two parts add up); a, b: joint origins ({occurrence, face|circle|edge|point: [x,y,z] in world, or face|circle: \"\"; z? for a point, end?, x? as joint.origin} | origin name); \ values?: [angles in deg or expressions, distances]; limits?: [[min, max] | null…]; flip?: bool (default false: the origins are mated, \ b's z against a's as two faces meet; true: b's z along a's, so two origins given at one point with the same z stay as they are); \ offset?: mm or an expression; angle?: deg or an expression (an angle relation's tilt from mated; for other joints the default \ @@ -346,7 +346,20 @@ fn origin_param(s: &Session, v: Option<&Value>, cmd: &str) -> Result Snap::Point { point: local(world), z: v.get("z").and_then(vec3).map(local_dir) }, + "point" => { + let z = v.get("z").and_then(vec3).map(local_dir); + let x = match v.get("x") { + None | Some(Value::Null) => None, + Some(x) => Some(vec3(x).map(local_dir).ok_or_else(|| bad(cmd, "a point origin's `x` is a direction [x, y, z]"))?), + }; + // An x along z (or no direction at all) would leave the frame's turn to chance. + if let Some(x) = x + && (!x.is_finite() || x.cross(z.unwrap_or(Vec3::Z)).len() <= 1e-9 * x.len().max(1.0)) + { + return Err(bad(cmd, "a point origin's `x` must be a direction off its z axis")); + } + Snap::Point { point: local(world), z, x } + } _ => { let f = v.get("frame").cloned().unwrap_or_default(); let z = f.get("z").and_then(vec3).ok_or_else(|| bad(cmd, "`frame` needs a z axis"))?; @@ -463,7 +476,7 @@ fn circle_centre(s: &Session, occurrence: u64, pick: Vec3) -> Option { .find_map(|b| solidcraft_doc::kernel::cylinder_end_at(&b.body, pick))?; let along = (pick - c.axis_point).dot(c.axis); let (at, dir) = if (along - c.start).abs() <= (c.end - along).abs() { (c.start, -1.0) } else { (c.end, 1.0) }; - Some(Snap::Point { point: c.axis_point + c.axis * at, z: Some(c.axis * dir) }) + Some(Snap::Point { point: c.axis_point + c.axis * at, z: Some(c.axis * dir), x: None }) } pub(crate) fn joint_id(s: &Session, v: Option<&Value>, cmd: &str) -> Result { @@ -1394,6 +1407,9 @@ mod face_tests; #[path = "joint_frames_tests.rs"] mod frames_tests; #[cfg(test)] +#[path = "joints_point_x_tests.rs"] +mod point_x_tests; +#[cfg(test)] #[path = "joints_reach_tests.rs"] mod reach_tests; #[cfg(test)] diff --git a/crates/engine/src/cmd/joints_face_tests.rs b/crates/engine/src/cmd/joints_face_tests.rs index 9ef057f72..002c6fddd 100644 --- a/crates/engine/src/cmd/joints_face_tests.rs +++ b/crates/engine/src/cmd/joints_face_tests.rs @@ -51,7 +51,7 @@ fn on_the_hole(s: &Session, w: f64) { fn origin(s: &Session, joint: &str, a: bool) -> Snap { let j = s.doc.assembly.joints.iter().find(|j| j.name == joint).map(|j| if a { &j.a } else { &j.b }); - j.map(|o| o.snap.clone()).unwrap_or(Snap::Point { point: Vec3::ZERO, z: None }) + j.map(|o| o.snap.clone()).unwrap_or(Snap::Point { point: Vec3::ZERO, z: None, x: None }) } #[test] @@ -179,8 +179,11 @@ fn a_face_centre_by_name_follows_its_face() { #[test] fn an_origin_without_an_end_or_turn_opens_as_before() { // A design saved before origins named their end and turn: the snap reads without them. - let snap: Snap = serde_json::from_value(json!({"type": "circle_center", "pick": [1, 2, 3], "face": "F1:side"})) - .unwrap_or(Snap::Point { point: Vec3::ZERO, z: None }); + let snap: Snap = serde_json::from_value(json!({"type": "circle_center", "pick": [1, 2, 3], "face": "F1:side"})).unwrap_or(Snap::Point { + point: Vec3::ZERO, + z: None, + x: None, + }); assert_eq!(snap, Snap::CircleCenter { pick: Vec3::new(1.0, 2.0, 3.0), face: Some("F1:side".into()), end: None, x: None }); let back: Value = serde_json::to_value(&snap).unwrap_or_default(); assert_eq!(back, json!({"type": "circle_center", "pick": [1.0, 2.0, 3.0], "face": "F1:side"})); diff --git a/crates/engine/src/cmd/joints_point_x_tests.rs b/crates/engine/src/cmd/joints_point_x_tests.rs new file mode 100644 index 000000000..c74b0b8bd --- /dev/null +++ b/crates/engine/src/cmd/joints_point_x_tests.rs @@ -0,0 +1,59 @@ +//! A point joint origin keeps the x it is given: two origins given at one point with the same z +//! and x meet as they are, whichever way their parts are turned. + +use serde_json::json; +use solidcraft_geom::Vec3; + +use super::tests::{occ, place, run}; +use crate::Session; + +/// A 100 x 20 x 10 base at the origin and an 80 x 20 x 10 block on it, the block turned a quarter +/// turn about z (about (60, 10)). +fn blocks() -> Session { + let mut s = Session::default(); + run(&mut s, "component.create", json!({"name": "Base"})); + run(&mut s, "solid.box", json!({"length": 100, "width": 20, "height": 10, "corner": [0, 0, 0]})); + run(&mut s, "component.activate", json!({"component": "root"})); + run(&mut s, "component.create", json!({"name": "Block"})); + run(&mut s, "solid.box", json!({"length": 80, "width": 20, "height": 10, "corner": [20, 0, 10]})); + run(&mut s, "component.activate", json!({"component": "root"})); + let (base, block) = (occ(&s, "Base"), occ(&s, "Block")); + run(&mut s, "occurrence.ground", json!({"occurrence": base, "grounded": true})); + run(&mut s, "occurrence.move", json!({"occurrence": block, "axis": [0, 0, 1], "angle": "90 deg", "origin": [60, 10, 10]})); + s +} + +#[test] +fn origins_given_the_same_x_meet_as_they_are() { + let mut s = blocks(); + let corner = |s: &Session| place(s, "Block", Vec3::new(20.0, 0.0, 10.0)); + let before = corner(&s); + // Both origins at the block's base centre, z up and x along world X: the block is already there. + let at = |o: &str| json!({"occurrence": o, "point": [60, 10, 10], "z": [0, 0, 1], "x": [1, 0, 0]}); + let r = run(&mut s, "joint.create", json!({"type": "rigid", "a": at("Base"), "b": at("Block"), "flip": true})); + assert_eq!(r["conflicts"], json!([]), "{r}"); + assert!(corner(&s).dist(before) < 1e-9, "the block moved from {before:?} to {:?}", corner(&s)); + // Saved and read back, the x stays. + let saved = serde_json::to_string(&s.doc.assembly.joints).unwrap_or_default(); + assert!(saved.contains("\"x\""), "{saved}"); + let back: Vec = serde_json::from_str(&saved).unwrap_or_default(); + assert_eq!(back, s.doc.assembly.joints); +} + +#[test] +fn a_point_origin_without_x_is_placed_as_before_and_a_bad_x_is_refused() { + let mut s = blocks(); + // No x: the frame's x comes from z alone, as designs made before had it (the turned block + // turns back a quarter turn to line its frame up with the base's). + let at = |o: &str| json!({"occurrence": o, "point": [60, 10, 10], "z": [0, 0, 1]}); + run(&mut s, "joint.create", json!({"type": "rigid", "a": at("Base"), "b": at("Block"), "flip": true, "name": "J"})); + let snap = s.doc.assembly.joints.first().map(|j| j.b.snap.clone()); + assert!(matches!(snap, Some(solidcraft_doc::joints::Snap::Point { x: None, .. })), "{snap:?}"); + let far = place(&s, "Block", Vec3::new(100.0, 10.0, 10.0)); + assert!(far.dist(Vec3::new(100.0, 10.0, 10.0)) < 1e-9, "{far:?}"); + // An x along z, or no direction at all, is refused. + for x in [json!([0, 0, 5]), json!([0, 0, -1]), json!([0, 0, 0])] { + let p = json!({"name": "O", "occurrence": "Base", "point": [60, 10, 10], "z": [0, 0, 1], "x": x}); + assert!(s.execute("joint.origin", &p).is_err(), "{p}"); + } +} From f97a84c100be908d3b74592b85080be4b5449a08 Mon Sep 17 00:00:00 2001 From: Loohi <78334654+Loohi@users.noreply.github.com> Date: Mon, 19 Oct 2026 23:56:34 +0000 Subject: [PATCH 145/225] inspect.clearance: measure the 0.2 mm gap on trimmed faces (#2283) (#2337) * claim: #2283 * inspect.clearance: a point straight past an edge's end no longer passes as on the face (#2283) A witness point on a face's surface is kept only if it lies on the face itself; near the face's boundary the nearest edge decides which side it is on. A point straight past the end of an edge (on the line through it) was meant to be left to the other edge meeting there, but "straight" was an absolute 1e-9 of the body size. With a slightly tilted axis (1.5e-6 rad, as a STEP round trip leaves it) a point 0.2 mm past the end of a knuckle's seam edge is 4.5e-6 mm off that line, so its side came down to rounding and the point on the knuckle's extended cylinder, level with the frame band's rim, was taken as contact (0.000) at some angles. Straight along is now relative to the distance from the edge (1e-3 of it), so the rim edge meeting there decides. Regression test: a hinge knuckle turned 30-80 degrees between two bands reads 0.2 mm at every angle, with both witness points on the bodies (41 degrees read 0.0 before). Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd/clearance_tests.rs | 40 ++++++++++++++++++++++++ crates/kernel/src/distance.rs | 9 ++++-- 2 files changed, 47 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/clearance_tests.rs b/crates/engine/src/cmd/clearance_tests.rs index a7399ace3..3b057094f 100644 --- a/crates/engine/src/cmd/clearance_tests.rs +++ b/crates/engine/src/cmd/clearance_tests.rs @@ -252,6 +252,46 @@ fn a_small_gap_past_a_corner_is_not_contact() { } } +/// #2283: a knuckle (Ø6, z 3.7 to 8.3, with a 150 mm arm) turning between two frame bands (Ø6, +/// z -1.5 to 3.5 and 8.5 to 13.5) on a shared axis is 0.2 mm from them at every angle. Its axis +/// tilted 1.5e-6 rad (as a STEP round trip leaves it), the band's rim lies on the knuckle's +/// cylinder extended past its end, and a point there was taken for a point of the knuckle at +/// some angles: contact (0) at a point off the body. +#[test] +fn a_hinge_gap_is_measured_on_the_trimmed_faces_at_every_angle() { + let mut s = Session::default(); + let part = |s: &mut Session, cmd: &str, mut p: Value, name: &str, join: bool| { + p["body_name"] = json!(name); + p["operation"] = json!(if join { "join" } else { "new" }); + if join { + p["targets"] = json!([name]); + } + run(s, cmd, p); + }; + part(&mut s, "solid.cylinder", json!({"radius": 3, "height": 5, "base": [0, 0, -1.5]}), "Frame", false); + part(&mut s, "solid.cylinder", json!({"radius": 3, "height": 5, "base": [0, 0, 8.5]}), "Frame", true); + for z in [-1.5, 8.5] { + part(&mut s, "solid.box", json!({"length": 137.5, "width": 4, "height": 5, "corner": [-140, -2, z]}), "Frame", true); + } + part(&mut s, "solid.box", json!({"length": 5, "width": 4, "height": 15, "corner": [-145, -2, -1.5]}), "Frame", true); + part(&mut s, "solid.cylinder", json!({"radius": 3, "height": 4.6, "base": [0, 0, 3.7]}), "Temple", false); + part(&mut s, "solid.box", json!({"length": 150, "width": 2, "height": 4.6, "corner": [0, -1, 3.7]}), "Temple", true); + run(&mut s, "solid.move", json!({"bodies": ["Temple"], "axis": [1, 0, 0], "angle": "1.5e-6 rad"})); + run(&mut s, "solid.move", json!({"bodies": ["Temple"], "axis": [0, 0, 1], "angle": "29 deg"})); + for deg in 30..=80 { + run(&mut s, "solid.move", json!({"bodies": ["Temple"], "axis": [0, 0, 1], "angle": "1 deg"})); + let r = run(&mut s, "inspect.clearance", json!({"bodies": ["Temple"], "against": ["Frame"], "clearance": 0.5, "nearest": 1})); + let near = &r["near"][0]; + assert!((f(&near["distance_mm"]) - 0.2).abs() < 1e-4, "{deg}°: {r}"); + assert!((f(&r["nearest"]["Temple"][0]["distance_mm"]) - 0.2).abs() < 1e-4, "{deg}°: {r}"); + // The witness points lie on the bodies: the frame's at a band end, the knuckle's at one + // of its ends. + let (from, to) = (f(&near["from"][2]), f(&near["to"][2])); + assert!([3.5, 8.5].iter().any(|z| (from - z).abs() < 1e-4), "{deg}°: the frame's point {from} is at a band end: {r}"); + assert!([3.7, 8.3].iter().any(|z| (to - z).abs() < 1e-4), "{deg}°: the knuckle's point {to} is at a knuckle end: {r}"); + } +} + /// A second call measures only the pairs with a body that changed or moved since the first. #[test] fn pairs_whose_bodies_did_not_change_or_move_are_not_measured_again() { diff --git a/crates/kernel/src/distance.rs b/crates/kernel/src/distance.rs index 29cd59208..4db0128f6 100644 --- a/crates/kernel/src/distance.rs +++ b/crates/kernel/src/distance.rs @@ -50,6 +50,9 @@ pub struct DistanceShape<'a> { const MAX_FACE_PAIRS: usize = 24; /// Most projection rounds for one pair of features. const MAX_ROUNDS: usize = 400; +/// A point less than this fraction of its distance from an edge off the line through it is +/// straight along the edge (see [`DistanceShape::on_face`]). +const ALONG: f64 = 1e-3; impl<'a> DistanceShape<'a> { /// `mesh` is `body`'s mesh, within `chord` (mm) of its faces. @@ -149,9 +152,11 @@ impl<'a> DistanceShape<'a> { continue; } // `p` straight along the edge (past its end, on the line through it) says nothing - // about which side it is on: another edge meeting there decides. + // about which side it is on: another edge meeting there decides. Straight along is + // relative to how far `p` is: past the end, what is left across the edge is the + // edge's own tilt and rounding, and its side is chance (#2283). let off = across(p); - if off.len() <= tiny { + if off.len() <= tiny.max(ALONG * at.dist(p)) { continue; } decided = true; From c8283f2196103dcc25ab262c6808a7dc4e262c0b Mon Sep 17 00:00:00 2001 From: DuBearte <130190089+DuBearte@users.noreply.github.com> Date: Mon, 19 Oct 2026 23:56:36 +0000 Subject: [PATCH 146/225] Thread: a hole too narrow (or a shaft too thick) says so, and what to drill (#2688) (#2853) An M8 modelled thread in a 6 mm hole, narrower than M8's minor diameter, was refused as "the face is too far from the thread's diameter". It now says what is wrong and what fits, as a hole that is too wide already does (#995): "this 6 mm hole is too narrow for a modelled M8 thread (its teeth would fill the hole); drill 6.75 mm for M8", with the thread that fits this hole when there is one. A shaft too thick for its thread gets "make the shaft 8 mm for M8". Fixes #2688 Co-authored-by: Claude Opus 5.5 Co-authored-by: bherbruck --- crates/doc/src/eval.rs | 16 +++++++++++++++- crates/engine/src/thread_tests.rs | 21 +++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index b250d864b..6af265511 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -382,7 +382,21 @@ fn thread_groove(t: &ThreadInfo, radius: f64, open: (bool, bool)) -> Result= p * 0.98 { - return Err(DocError::Invalid("the face is too far from the thread's diameter".into())); + // The groove would be wider than a pitch: the face is far inside the thread (a hole + // narrower than its minor diameter, a shaft thicker than its major one, #2688). + let (m, dia) = (&t.designation, 2.0 * radius); + let alt = thread_for(dia, t.internal).map(|(n, q)| format_thread(n, q)).filter(|a| a != m); + let shown = show_mm(dia); + return Err(DocError::Invalid(if t.internal { + let alt = alt.map(|a| format!(", or thread this hole {a}")).unwrap_or_default(); + format!( + "this {shown} mm hole is too narrow for a modelled {m} thread (its teeth would fill the hole); drill {} mm for {m}{alt}", + show_mm(d - p) + ) + } else { + let alt = alt.map(|a| format!(", or thread this shaft {a}")).unwrap_or_default(); + format!("this {shown} mm shaft is too thick for a modelled {m} thread; make the shaft {} mm for {m}{alt}", show_mm(d)) + })); } let k = t.axis; let u = k.cross(if k.x.abs() < 0.9 { Vec3::new(1.0, 0.0, 0.0) } else { Vec3::new(0.0, 1.0, 0.0) }); diff --git a/crates/engine/src/thread_tests.rs b/crates/engine/src/thread_tests.rs index 3b725197b..533042c72 100644 --- a/crates/engine/src/thread_tests.rs +++ b/crates/engine/src/thread_tests.rs @@ -102,6 +102,27 @@ fn a_modelled_thread_that_would_cut_nothing_is_refused() { assert!(e.contains("this 17.2 mm shaft") && e.contains("make the shaft 20 mm for M20") && e.contains("thread this shaft M18"), "{e}"); } +/// Issue 2688: an M8 modelled thread in a 6 mm hole (narrower than its 6.65 mm minor diameter) +/// was refused as "the face is too far from the thread's diameter". It says what is wrong and +/// what to drill, as a hole that is too wide does; and the same for a shaft that is too thick. +#[test] +fn a_hole_too_narrow_or_a_shaft_too_thick_says_which_and_what_fits() { + let mut s = hex_nut(6.0); + let before = volume(&mut s, "Nut"); + let e = s.execute("solid.thread", &json!({"face": [3.0, 0, 2], "designation": "M8", "modeled": true})).err().map(|e| e.to_string()); + let e = e.unwrap_or_default(); + assert!(e.contains("this 6 mm hole is too narrow for a modelled M8 thread") && e.contains("drill 6.75 mm for M8"), "{e}"); + assert!(!e.contains("too far"), "{e}"); + assert!((volume(&mut s, "Nut") - before).abs() < 1e-9); + + let mut s = Session::default(); + // 9 mm is close enough to M8 to be offered it, too thick to cut it. + run(&mut s, "solid.cylinder", json!({"radius": 4.5, "height": 10, "body_name": "Shaft"})); + let e = s.execute("solid.thread", &json!({"face": [4.5, 0, 5], "designation": "M8", "modeled": true})).err().map(|e| e.to_string()); + let e = e.unwrap_or_default(); + assert!(e.contains("this 9 mm shaft is too thick for a modelled M8 thread") && e.contains("make the shaft 8 mm for M8"), "{e}"); +} + /// The limit is a quarter of the basic depth 5H/8: a hole up to 4.78 mm for M5 (4.86 mm for /// M5x0.5) still takes a modelled thread, a wider one is refused with that pitch's drill. #[test] From 62b49f9f89e8a1386123786bb4e2d5d6b5521838 Mon Sep 17 00:00:00 2001 From: NOWN-DEV <257771410+NOWN-DEV@users.noreply.github.com> Date: Mon, 19 Oct 2026 23:56:40 +0000 Subject: [PATCH 147/225] Boolean: a pin in a bore of its size is clear at every placement (#2714) (#2715) * Boolean: a pin in a bore of its own size is clear of it, whatever its facets A pin whose wall is in other faces than the bore's (turned from a profile: three faces; the bore two) is faceted at other angles. Where one body's faces end on the shared cylinder (the pin's wall through the end face of the tube, the pin's end inside the bore) the facets cross by the facetings' error, so the sampled shortcut doubted its own "apart" answer, every retry failed on the coincident walls, and the result came back unverified after seconds: inspect.clearance left such pairs unchecked ("could not be intersected there"). The shortcut now leaves out crossings that lie on a cylinder both bodies have faces on (axes and radii within the kernel's same-surface tolerance, where both faces run). A pin a hair off its hole's axis, or one pushed into a narrower bore, is still not taken for apart. Co-Authored-By: Claude Opus 5.5 (1M context) * Boolean: skip only the shared cylinder's own crossings, not a flat along it The shortcut left out every crossing near a cylinder both bodies have faces on, from any face: a pin through a D-bore whose flat is 0.022 mm inside it came back as contact. Mesh::crosses_except now hands the predicate the two triangles' faces, and only crossings between the faces on the shared cylinder, or between one of them and an end face across its axis that keeps to its body's side of the cylinder (within the facetings' error), are left out. The D-bore's end face reaches into the cylinder to the flat, so the pin's wall through it counts again; a flat, key or rib along the axis always counts. Co-Authored-By: Claude Opus 5.5 (1M context) * Boolean: a pin in a bore of its size is clear at every placement The sampled shortcut's check that no facet has material under it on the wrong side of the other body still caught the facetings of a shared cylinder. A facet of a pin's end inside the bore (or of the bore part's end face round the pin) with all three corners on the rim has its middle just inside the cylinder. Where the other body's chords reach further in at that angle, the point under it lies inside the other mesh, though the bodies only touch. Which facets do so depends on the face splits and the placement, so the same pair read as clear at one placement and as "not verified" at another. Such points are no evidence now when they lie on the shared cylinder, under a facet of one of its end faces: the end faces and band the crossing check already leaves out. A pin 0.02 mm larger is no shared cylinder, and its overlap is still found. Co-Authored-By: Claude Opus 5.5 (1M context) --------- Co-authored-by: Claude Opus 5.5 (1M context) Co-authored-by: bherbruck --- crates/engine/src/cmd/clearance_tests.rs | 50 ++++ crates/geom/src/mesh.rs | 68 +++-- crates/geom/src/tests.rs | 12 + crates/kernel/src/ops.rs | 337 ++++++++++++++++++++++- 4 files changed, 437 insertions(+), 30 deletions(-) diff --git a/crates/engine/src/cmd/clearance_tests.rs b/crates/engine/src/cmd/clearance_tests.rs index 3b057094f..901f4a74a 100644 --- a/crates/engine/src/cmd/clearance_tests.rs +++ b/crates/engine/src/cmd/clearance_tests.rs @@ -415,3 +415,53 @@ fn a_roller_pressed_into_a_large_plate_is_reported() { let want = (r * r * ((r - depth) / r).acos() - (r - depth) * (r * r - (r - depth) * (r - depth)).sqrt()) * length; assert!((f(&overlaps[0]["volume_mm3"]) - want).abs() < 0.01 * want, "{want} {res}"); } + +/// A pin turned from a profile (its wall in three faces) in the bore of a tube of its own size +/// (in two faces), its end inside the bore, a hair off the axis, and a slit tube with the pin +/// through it: touching, not overlapping. Their facets cross where one body's faces end on the +/// shared cylinder, and the pairs were left unchecked ("could not be intersected there"). +#[test] +fn a_turned_pin_in_a_bore_of_its_size_is_contact() { + let mut s = Session::default(); + let pin = |s: &mut Session, name: &str, off: [f64; 3], z0: f64, z1: f64| { + run(s, "sketch.create", json!({"plane": {"origin": off, "x_dir": [1, 0, 0], "y_dir": [0, 0, 1]}})); + run(s, "sketch.rectangle.two_point", json!({"p0": [0, z0], "p1": [3, z1]})); + run(s, "solid.revolve", json!({"axis": "y", "body_name": name})); + }; + let tube = |s: &mut Session, name: &str, x: f64| { + run(s, "solid.cylinder", json!({"radius": 5.25, "height": 19.55, "base": [x, 0, 0], "body_name": name})); + run(s, "solid.cylinder", json!({"radius": 3, "height": 19.55, "base": [x, 0, 0], "operation": "cut", "targets": [name]})); + }; + pin(&mut s, "Pin", [2.2e-8, 4.7e-7, 0.0], -2.35, 9.65); + tube(&mut s, "Tube", 0.0); + pin(&mut s, "Through", [30.0, 0.0, 0.0], -3.0, 22.0); + tube(&mut s, "Slit", 30.0); + run(&mut s, "solid.box", json!({"length": 8, "width": 0.1, "height": 21, "corner": [22, -0.05, -1], "operation": "cut", "targets": ["Slit"]})); + let r = run(&mut s, "inspect.clearance", json!({"bodies": ["Pin", "Through"], "against": ["Tube", "Slit"], "clearance": 1e-6})); + assert_eq!(r["unchecked"].as_array().map(Vec::len), Some(0), "{r}"); + assert_eq!(r["overlaps"].as_array().map(Vec::len), Some(0), "{r}"); + let near = r["near"].as_array().cloned().unwrap_or_default(); + assert_eq!(near.iter().map(pair).collect::>(), [["Pin", "Tube"], ["Slit", "Through"]], "{r}"); + assert!(near.iter().all(|n| f(&n["distance_mm"]) == 0.0 && n.get("overlap_mm3").is_none()), "{r}"); +} + +/// A pin of a bore's size through a D-bore whose flat is 0.022 mm inside the pin shares a +/// sliver with the tube along the whole bore (the circular segment beyond the flat, 0.21 mm³): +/// an overlap, not contact. Only the facetings of the shared cylinder may cross unseen; the flat +/// reaches into it. +#[test] +fn a_pin_through_a_d_bore_of_its_size_overlaps_the_flat() { + let (r, flat, length) = (3.0_f64, 2.978_f64, 19.55); + let mut s = Session::default(); + run(&mut s, "solid.cylinder", json!({"radius": 5.25, "height": length, "base": [0, 0, 0], "body_name": "Tube"})); + run(&mut s, "solid.cylinder", json!({"radius": r, "height": length, "base": [0, 0, 0], "operation": "cut", "targets": ["Tube"]})); + run(&mut s, "solid.box", json!({"length": 1, "width": 2, "height": length, "corner": [flat, -1, 0], "operation": "join", "targets": ["Tube"]})); + run(&mut s, "solid.cylinder", json!({"radius": r, "height": length + 6.0, "base": [0, 0, -3], "operation": "new", "body_name": "Pin"})); + let res = run(&mut s, "inspect.clearance", json!({"bodies": ["Pin"], "against": ["Tube"], "clearance": 1e-6})); + let want = (r * r * (flat / r).acos() - flat * (r * r - flat * flat).sqrt()) * length; + let overlaps = res["overlaps"].as_array().cloned().unwrap_or_default(); + assert!(res["near"].as_array().is_none_or(|n| n.is_empty()), "{res}"); + assert_eq!(res["unchecked"].as_array().map(Vec::len), Some(0), "{res}"); + assert_eq!(overlaps.len(), 1, "{res}"); + assert!((f(&overlaps[0]["volume_mm3"]) - want).abs() < 0.05 * want, "{want} {res}"); +} diff --git a/crates/geom/src/mesh.rs b/crates/geom/src/mesh.rs index 92339a0ab..45dd94161 100644 --- a/crates/geom/src/mesh.rs +++ b/crates/geom/src/mesh.rs @@ -100,7 +100,8 @@ pub fn find_close_pair( test: impl FnMut(&BoxedTriangle, &BoxedTriangle) -> bool, ) -> Option { let work = std::cell::Cell::new(*budget); - let found = find_close_pair_within(a, b, gap, &work, test); + let mut test = test; + let found = find_close_pair_within(a, b, gap, &work, |(_, t), (_, u)| test(t, u)); *budget = work.get(); found } @@ -110,7 +111,7 @@ fn find_close_pair_within( b: &[BoxedTriangle], gap: f64, work: &std::cell::Cell, - mut test: impl FnMut(&BoxedTriangle, &BoxedTriangle) -> bool, + mut test: impl FnMut((usize, &BoxedTriangle), (usize, &BoxedTriangle)) -> bool, ) -> Option { let spend = |n: usize| -> Option<()> { work.set(work.get().checked_sub(n)?); @@ -125,7 +126,7 @@ fn find_close_pair_within( && x.min.z <= y.max.z + gap && y.min.z <= x.max.z + gap }; - let mut call = |t: &BoxedTriangle, u: &BoxedTriangle| -> Option { + let mut call = |t: (usize, &BoxedTriangle), u: (usize, &BoxedTriangle)| -> Option { spend(1)?; Some(test(t, u)) }; @@ -179,7 +180,7 @@ fn find_close_pair_within( for &j in &big { if let Some(u) = b.get(j).filter(|u| close(&t.1, &u.1)) { seen[j] = i + 1; - if call(t, u)? { + if call((i, t), (j, u))? { return Some(true); } } @@ -187,7 +188,7 @@ fn find_close_pair_within( let Some([x, y, z]) = span(&t.1, 0.0) else { // A large triangle of `a`: against all of `b`. for (j, u) in b.iter().enumerate() { - if seen[j] != i + 1 && close(&t.1, &u.1) && call(t, u)? { + if seen[j] != i + 1 && close(&t.1, &u.1) && call((i, t), (j, u))? { return Some(true); } } @@ -203,7 +204,7 @@ fn find_close_pair_within( continue; } *mark = i + 1; - if close(&t.1, &u.1) && call(t, u)? { + if close(&t.1, &u.1) && call((i, t), (j as usize, u))? { return Some(true); } } @@ -215,7 +216,9 @@ fn find_close_pair_within( } /// Two triangles that pass through each other (see [`Mesh::crosses`]). -fn triangles_cross(t: &[Vec3; 3], u: &[Vec3; 3], tol: f64) -> bool { +/// Where two triangles pass through each other by more than `tol` (see [`Mesh::crosses`]): the +/// middle of the stretch of the line their planes share that both span, or `None`. +fn triangles_cross(t: &[Vec3; 3], u: &[Vec3; 3], tol: f64) -> Option { // Signed distances of one triangle's corners from the other's plane, when they lie more // than `tol` to both sides of it. let sides = |tri: &[Vec3; 3], plane: &[Vec3; 3]| -> Option<(Vec3, [f64; 3])> { @@ -224,24 +227,31 @@ fn triangles_cross(t: &[Vec3; 3], u: &[Vec3; 3], tol: f64) -> bool { let (lo, hi) = d.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), v| (lo.min(*v), hi.max(*v))); (lo < -tol && hi > tol).then_some((n, d)) }; - let (Some((nu, dt)), Some((nt, du))) = (sides(t, u), sides(u, t)) else { return false }; - let Some(line) = nt.cross(nu).normalized() else { return false }; + let (Some((nu, dt)), Some((nt, du))) = (sides(t, u), sides(u, t)) else { return None }; + let line = nt.cross(nu).normalized()?; // Where a triangle's edges pass through the other's plane, measured along the line the // two planes share. - let reach = |tri: &[Vec3; 3], d: &[f64; 3]| -> (f64, f64) { - let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY); + // With the points there, for the middle of the stretch both span. + let reach = |tri: &[Vec3; 3], d: &[f64; 3]| -> ((f64, Vec3), (f64, Vec3)) { + let (mut lo, mut hi) = ((f64::INFINITY, Vec3::ZERO), (f64::NEG_INFINITY, Vec3::ZERO)); for (i, j) in [(0, 1), (1, 2), (2, 0)] { let (p, q, dp, dq) = (tri[i], tri[j], d[i], d[j]); if (dp < 0.0) != (dq < 0.0) && dp != dq { - let at = line.dot(p + (q - p) * (dp / (dp - dq))); - lo = lo.min(at); - hi = hi.max(at); + let x = p + (q - p) * (dp / (dp - dq)); + let at = line.dot(x); + if at < lo.0 { + lo = (at, x); + } + if at > hi.0 { + hi = (at, x); + } } } (lo, hi) }; let ((t0, t1), (u0, u1)) = (reach(t, &dt), reach(u, &du)); - t1.min(u1) - t0.max(u0) > tol + let (from, to) = (if t0.0 > u0.0 { t0 } else { u0 }, if t1.0 < u1.0 { t1 } else { u1 }); + (to.0 - from.0 > tol).then(|| (from.1 + to.1) * 0.5) } /// Mass properties of a closed mesh. @@ -523,6 +533,14 @@ impl Mesh { /// can still overlap without crossing: one inside the other, or sharing a slab between /// faces that are parallel or in one plane. pub fn crosses(&self, o: &Mesh, tol: f64) -> bool { + self.crosses_except(o, tol, |_, _, _| false) + } + + /// [`Mesh::crosses`], leaving out the crossings for which `ignored` holds, asked with the + /// middle of the stretch the two triangles share and the faces of this mesh's and `o`'s + /// triangle (`u32::MAX` where a mesh has no face for it): where both meshes stand for one + /// surface of both bodies, and their facets cross by the facetings' error alone. + pub fn crosses_except(&self, o: &Mesh, tol: f64, ignored: impl Fn(Vec3, u32, u32) -> bool) -> bool { if !tol.is_finite() { return false; } @@ -532,23 +550,29 @@ impl Mesh { if region.is_empty() { return false; } - let near = |m: &Mesh| -> Vec<([Vec3; 3], Aabb3)> { + // The triangles near the other mesh, with their faces. + let near = |m: &Mesh| -> (Vec, Vec) { m.triangles .iter() - .filter_map(|t| { + .enumerate() + .filter_map(|(i, t)| { let t = m.tri(t)?; let mut bx = Aabb3::EMPTY; t.iter().for_each(|p| bx.add(*p)); - (!bx.is_empty() && boxes_meet(&bx, ®ion)).then_some((t, bx)) + (!bx.is_empty() && boxes_meet(&bx, ®ion)).then(|| ((t, bx), m.tri_face.get(i).copied().unwrap_or(u32::MAX))) }) - .collect() + .unzip() }; - let (ta, tb) = (near(self), near(o)); + let ((ta, fa), (tb, fb)) = (near(self), near(o)); if ta.is_empty() || tb.is_empty() { return false; } - let mut unlimited = usize::MAX; - find_close_pair(&ta, &tb, 0.0, &mut unlimited, |(t, _), (u, _)| triangles_cross(t, u, tol)).unwrap_or(false) + let work = std::cell::Cell::new(usize::MAX); + let face = |faces: &[u32], i: usize| faces.get(i).copied().unwrap_or(u32::MAX); + find_close_pair_within(&ta, &tb, 0.0, &work, |(i, (t, _)), (j, (u, _))| { + triangles_cross(t, u, tol).is_some_and(|at| !ignored(at, face(&fa, i), face(&fb, j))) + }) + .unwrap_or(false) } /// Closest intersection of a ray with the mesh: (distance along `dir`, triangle index). diff --git a/crates/geom/src/tests.rs b/crates/geom/src/tests.rs index 39010d872..7b8513aca 100644 --- a/crates/geom/src/tests.rs +++ b/crates/geom/src/tests.rs @@ -287,6 +287,8 @@ fn box_mesh(min: Vec3, max: Vec3, n: usize) -> Mesh { let k = m.positions.len() as u32; m.positions.extend([corner(i, j), corner(i + 1, j), corner(i + 1, j + 1), corner(i, j + 1)]); m.triangles.extend(if side > 0.0 { [[k, k + 1, k + 2], [k, k + 2, k + 3]] } else { [[k, k + 2, k + 1], [k, k + 3, k + 2]] }); + // Faces: 2 * axis, plus one on the far side. + m.tri_face.extend([(2 * axis) as u32 + side as u32; 2]); } } } @@ -318,6 +320,16 @@ fn meshes_cross_only_where_their_surfaces_pass_through_each_other() { // Passing through by less than the tolerance doesn't count. assert!(!a.crosses(&cube(9.995, 3.0, 1), 0.01)); assert!(!a.crosses(&cube(9.85, 3.0, 1), f64::NAN)); + // Crossings left out where the caller knows better: only those, by where they are. + let corner = cube(9.85, 9.85, 2); + assert!(!a.crosses_except(&corner, 0.01, |_, _, _| true)); + assert!(!a.crosses_except(&corner, 0.01, |p, _, _| p.x > 9.8 && p.y > 9.8)); + assert!(a.crosses_except(&corner, 0.01, |p, _, _| p.x < 9.8)); + // And by the faces that cross: `a`'s side at x = 10 through the corner's at y = 9.85, and + // `a`'s at y = 10 through the corner's at x = 9.85. + assert!(!a.crosses_except(&corner, 0.01, |_, f, g| matches!((f, g), (1, 2) | (3, 0)))); + assert!(a.crosses_except(&corner, 0.01, |_, f, g| (f, g) == (1, 2))); + assert!(a.crosses_except(&corner, 0.01, |_, f, g| (f, g) == (3, 0))); } /// A closed box mesh `[x0, x0+a] x [y0, y0+b] x [z0, z0+c]`, outward-facing. diff --git a/crates/kernel/src/ops.rs b/crates/kernel/src/ops.rs index 9e0d51578..eb6f1479e 100644 --- a/crates/kernel/src/ops.rs +++ b/crates/kernel/src/ops.rs @@ -281,6 +281,8 @@ fn overlap( /// Whether some facet of `m` has material just under it (`depth` in from its middle) that is /// inside the other body (`inside`) or outside it. With `within`, only facets in that box. +/// Points for which `ignored` holds, asked with the point and the facet's face (`u32::MAX` +/// where the mesh has none), are no evidence either. fn under_surface( m: &solidcraft_geom::Mesh, own: &solidcraft_geom::InsideIndex, @@ -288,42 +290,213 @@ fn under_surface( depth: f64, inside: bool, within: Option<&solidcraft_geom::Aabb3>, + ignored: &dyn Fn(Vec3, u32) -> bool, ) -> bool { - m.triangles.iter().filter_map(|t| m.tri(t)).any(|[p, q, r]| { + m.triangles.iter().enumerate().filter_map(|(i, t)| Some((m.tri(t)?, m.tri_face.get(i).copied().unwrap_or(u32::MAX)))).any(|([p, q, r], face)| { let Some(n) = (q - p).cross(r - p).normalized() else { return false }; let c = (p + q + r) * (1.0 / 3.0) - n * depth; let near = within.is_none_or(|b| c.x >= b.min.x && c.x <= b.max.x && c.y >= b.min.y && c.y <= b.max.y && c.z >= b.min.z && c.z <= b.max.z); // A wall thinner than `depth` puts the point outside its own body: no evidence. - near && other.contains(c) == inside && own.contains(c) + near && other.contains(c) == inside && own.contains(c) && !ignored(c, face) }) } /// Whether the bodies' facetings show that the samples' answer (see [`trivial`]) is wrong: /// their surfaces pass through each other, or a facet of one has material under it on the -/// wrong side of the other. Overlaps and gaps shallower than `tol` are not seen. +/// wrong side of the other. Overlaps and gaps shallower than `tol` are not seen, nor surfaces +/// that pass through each other only on a cylinder both bodies have faces on, there between +/// those faces or one of them and an end face across its axis, nor material under such an end +/// face's facets at the cylinder (`shared`, asked only when the facetings disagree). fn contradicted( (ma, ia): (&solidcraft_geom::Mesh, &solidcraft_geom::InsideIndex), (mb, ib): (&solidcraft_geom::Mesh, &solidcraft_geom::InsideIndex), (disjoint, b_in_a, a_in_b): (bool, bool, bool), tol: f64, + shared: &dyn Fn() -> SharedCylinders, ) -> bool { if !(disjoint || b_in_a || a_in_b) { return false; } + let cylinders = std::cell::OnceCell::new(); + let shared = || cylinders.get_or_init(shared); if ma.crosses(mb, tol) { - return true; + let shared = shared(); + if shared.cylinders.is_empty() || ma.crosses_except(mb, tol, |p, fa, fb| shared.ignores(p, fa, fb, tol)) { + return true; + } } + // The end faces of a shared cylinder end on it at their own faceting: a facet of a pin's end + // inside the hole, or of the hole part's end face round the pin, has its middle within the + // facetings' error of the cylinder, where the other body's facets can reach over it. + let (under_a, under_b) = (|p: Vec3, f: u32| shared().under_cap(p, f, true, tol), |p: Vec3, f: u32| shared().under_cap(p, f, false, tol)); if disjoint { let (ba, bb) = (ma.bounds(), mb.bounds()); - let shared = solidcraft_geom::Aabb3 { min: ba.min.max(bb.min), max: ba.max.min(bb.max) }; - return !shared.is_empty() && (under_surface(ma, ia, ib, tol, true, Some(&shared)) || under_surface(mb, ib, ia, tol, true, Some(&shared))); + let meet = solidcraft_geom::Aabb3 { min: ba.min.max(bb.min), max: ba.max.min(bb.max) }; + return !meet.is_empty() + && (under_surface(ma, ia, ib, tol, true, Some(&meet), &under_a) || under_surface(mb, ib, ia, tol, true, Some(&meet), &under_b)); } - (a_in_b && under_surface(ma, ia, ib, tol, false, None)) || (b_in_a && !a_in_b && under_surface(mb, ib, ia, tol, false, None)) + (a_in_b && under_surface(ma, ia, ib, tol, false, None, &under_a)) || (b_in_a && !a_in_b && under_surface(mb, ib, ia, tol, false, None, &under_b)) } /// Sampled overlap fraction below which two bodies share no material. const NONE: f64 = 0.003; +/// A cylinder both bodies have faces on (a pin in a hole of its own size, a bore drilled again), +/// and where along its axis both do. The two facetings of it are chords of one circle at +/// different angles: where one body's facets end on it (a pin's wall through the end face of the +/// hole's part, the pin's end inside the hole) they cross the other's by up to the facetings' +/// error, though the surfaces only touch. +struct SharedCylinder { + origin: Vec3, + axis: Vec3, + radius: f64, + span: (f64, f64), + /// The faces on it: of the first body, of the second. + faces: (usize, usize), + /// The end faces across its axis that keep to their body's side of it (a hole part's end + /// face round the hole, a pin's end inside it), within the facetings' error: of the first + /// body, of the second. A D-bore's end face, which reaches into the cylinder to the flat, + /// is not one. + caps: (Vec, Vec), +} + +impl SharedCylinder { + /// Whether `p` lies on the cylinder, within `tol`, where both bodies have faces on it. + fn holds(&self, p: Vec3, tol: f64) -> bool { + let v = p - self.origin; + let along = v.dot(self.axis); + ((v - self.axis * along).len() - self.radius).abs() <= tol && along >= self.span.0 - tol && along <= self.span.1 + tol + } +} + +/// The cylinders both bodies have faces on (see [`shared_cylinders`]). +#[derive(Default)] +struct SharedCylinders { + cylinders: Vec, +} + +impl SharedCylinders { + /// Whether a crossing at `p` of the first body's face `fa` with the second's `fb` is only + /// the facetings of a shared cylinder: on it, between the two faces on it, or between one of + /// them and one of its end faces (a pin's wall through the hole part's end face, the pin's + /// end inside the hole). A flat, key or rib along the axis still counts. + fn ignores(&self, p: Vec3, fa: u32, fb: u32, tol: f64) -> bool { + let (fa, fb) = (fa as usize, fb as usize); + self.cylinders.iter().any(|c| { + let (on_a, on_b) = (fa == c.faces.0, fb == c.faces.1); + ((on_a && on_b) || (on_a && c.caps.1.contains(&fb)) || (c.caps.0.contains(&fa) && on_b)) && c.holds(p, tol) + }) + } + + /// Whether `p`, just under a facet of the first body's face `face` (`first`) or the second's, + /// lies within `tol` of a shared cylinder with that face one of its end faces: material the + /// other body's facets of the cylinder can cover there, though the surfaces only touch. + fn under_cap(&self, p: Vec3, face: u32, first: bool, tol: f64) -> bool { + let face = face as usize; + self.cylinders.iter().any(|c| (if first { &c.caps.0 } else { &c.caps.1 }).contains(&face) && c.holds(p, tol)) + } +} + +/// The cylinders on which both `a` and `b` have faces: axes parallel and within `same` of each +/// other, radii within `same` (a pin a hair off its hole's axis shares a crescent, which this +/// tolerance leaves far below any volume worth reporting). Spans from the meshes `ma`, `mb`. +fn shared_cylinders(a: &Body, b: &Body, ma: &solidcraft_geom::Mesh, mb: &solidcraft_geom::Mesh, same: f64) -> SharedCylinders { + let cylinders = |body: &Body| -> Vec<(usize, Vec3, Vec3, f64)> { + (0..body.face_count()) + .filter_map(|i| match crate::face_surface(body, i)? { + crate::FaceSurface::Cylinder { origin, axis, radius } if origin.is_finite() && radius.is_finite() && radius > 0.0 => { + Some((i, origin, axis.normalized()?, radius)) + } + _ => None, + }) + .collect() + }; + let (ca, cb) = (cylinders(a), cylinders(b)); + if ca.is_empty() || cb.is_empty() { + return SharedCylinders::default(); + } + // Where a face's facets reach along an axis. + let span = |m: &solidcraft_geom::Mesh, face: usize, origin: Vec3, axis: Vec3| -> Option<(f64, f64)> { + let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY); + for (t, f) in m.triangles.iter().zip(&m.tri_face) { + if *f as usize != face { + continue; + } + for p in m.tri(t)? { + let s = (p - origin).dot(axis); + lo = lo.min(s); + hi = hi.max(s); + } + } + (lo <= hi).then_some((lo, hi)) + }; + // A face's facets. + fn facets(m: &solidcraft_geom::Mesh, face: usize) -> impl Iterator + '_ { + m.triangles.iter().zip(&m.tri_face).filter(move |(_, f)| **f as usize == face).filter_map(|(t, _)| m.tri(t)) + } + // How near to and far from an axis a face's facets reach (nearest on their edges), and + // whether its material is inside the cylinder there (its normals point away from the axis). + let reach = |m: &solidcraft_geom::Mesh, face: usize, origin: Vec3, axis: Vec3| -> (f64, f64, bool) { + let radial = |p: Vec3| { + let v = p - origin; + v - axis * v.dot(axis) + }; + let (mut near, mut far, mut out) = (f64::INFINITY, 0.0f64, 0.0); + for t in facets(m, face) { + for (p, q) in [(t[0], t[1]), (t[1], t[2]), (t[2], t[0])] { + let (p, q) = (radial(p), radial(q)); + let d = q - p; + let s = if d.dot(d) > 0.0 { (-p.dot(d) / d.dot(d)).clamp(0.0, 1.0) } else { 0.0 }; + near = near.min((p + d * s).len()); + far = far.max(p.len()); + } + out += (t[1] - t[0]).cross(t[2] - t[0]).dot(radial((t[0] + t[1] + t[2]) * (1.0 / 3.0))); + } + (near, far, out > 0.0) + }; + let planes = |body: &Body| -> Vec<(usize, Vec3)> { + (0..body.face_count()) + .filter_map(|i| match crate::face_surface(body, i)? { + crate::FaceSurface::Plane { normal, .. } => Some((i, normal.normalized()?)), + _ => None, + }) + .collect() + }; + let (pa, pb) = (planes(a), planes(b)); + let mut out = Vec::new(); + for &(fa, oa, xa, ra) in &ca { + for &(fb, ob, xb, rb) in &cb { + let d = ob - oa; + if xa.dot(xb).abs() <= 1.0 - 1e-9 || (ra - rb).abs() > same || (d - xa * d.dot(xa)).len() > same { + continue; + } + let (Some(sa), Some(sb)) = (span(ma, fa, oa, xa), span(mb, fb, oa, xa)) else { continue }; + let (lo, hi) = (sa.0.max(sb.0), sa.1.min(sb.1)); + if lo > hi { + continue; + } + // The facetings' error on the cylinder: how far inside it their chords pass. + let ((na, _, boss_a), (nb, _, boss_b)) = (reach(ma, fa, oa, xa), reach(mb, fb, oa, xa)); + let error = 2.0 * (ra - na).max(ra - nb).max(0.0) + same; + // End faces across the axis that keep to their body's side of the cylinder. + let caps = |m: &solidcraft_geom::Mesh, planes: &[(usize, Vec3)], boss: bool| -> Vec { + planes + .iter() + .filter(|(_, n)| n.dot(xa).abs() >= 1.0 - 1e-6) + .filter(|(i, _)| { + let (near, far, _) = reach(m, *i, oa, xa); + near <= far && if boss { far <= ra + error } else { near >= ra - error } + }) + .map(|(i, _)| *i) + .collect() + }; + let caps = (caps(ma, &pa, boss_a), caps(mb, &pb, boss_b)); + out.push(SharedCylinder { origin: oa, axis: xa, radius: ra, span: (lo, hi), faces: (fa, fb), caps }); + } + } + SharedCylinders { cylinders: out } +} + /// Booleans that need no intersection: one body clear of the other, or inside it. These are /// common with coincident curved faces (a hole drilled where one already is, a body joined /// with itself), which the intersection can't handle. `counts`: the operands' faces and edges. @@ -351,7 +524,10 @@ fn trivial( // The samples only say that nearly all of one body is clear of, or inside, the other. A // small part can still be on the wrong side (a peg overlapping a rib, a chamfer taken off // one edge), and then the bodies have to be intersected. - let sure = !contradicted((ma, &ia), (mb, &ib), (disjoint, b_in_a > ALL, a_in_b > ALL), tol); + // The same surface as the kernel takes it elsewhere (see `coaxial_overlap`). + let same = (a.size().max(b.size()) * 1e-7).max(1e-9) * 10.0; + let shared = || shared_cylinders(a, b, ma, mb, same); + let sure = !contradicted((ma, &ia), (mb, &ib), (disjoint, b_in_a > ALL, a_in_b > ALL), tol, &shared); let answer = match op { // Sampling only selects this candidate. Validate every shell boundary and the // complete material/void nesting before preserving a disconnected union. @@ -505,6 +681,151 @@ mod shortcut_tests { assert!(trivial(&outer, &protruding, BoolOp::Cut, &mesh, &protruding_mesh, &counts, 0.09).is_none()); } + /// A pin turned from a profile (its wall in three faces) in the bore of a tube (its wall in + /// two): one cylinder, faceted at different angles, so the pin's facets cross the tube's end + /// face and the bore's facets cross the pin's end by the facetings' error. The pin is still + /// clear of the tube, exactly on its axis or a hair off it (parts placed from rounded + /// coordinates), with the pin's end inside the bore or through it, and with a slit along + /// the tube: answered at once, without the boolean's retries. + #[test] + fn a_pin_in_a_bore_of_its_size_is_clear_of_it_whatever_the_facets() { + use solidcraft_geom::{Loop2, Plane, Region2, Vec2}; + let rect = |x1: f64, y0: f64, y1: f64| Region2 { + outer: Loop2::polygon(&[Vec2::new(0.0, y0), Vec2::new(x1, y0), Vec2::new(x1, y1), Vec2::new(0.0, y1)]), + holes: vec![], + }; + let pin = |off: Vec3, z0: f64, z1: f64| { + let plane = Plane { origin: off, x: Vec3::X, y: Vec3::Z }; + crate::revolve(&plane, &[rect(3.0, z0, z1)], Vec2::ZERO, Vec2::new(0.0, 1.0), std::f64::consts::TAU).unwrap().pop().unwrap() + }; + let outer = crate::cylinder(Vec3::ZERO, Vec3::Z, 5.25, 19.55).unwrap(); + let bore = crate::cylinder(Vec3::new(0.0, 0.0, -1.0), Vec3::Z, 3.0, 21.55).unwrap(); + let tube = boolean(&outer, &bore, BoolOp::Cut).unwrap().unwrap(); + let slit = crate::box_solid(Vec3::new(-6.0, -0.05, -1.0), Vec3::new(0.0, 0.05, 21.0)).unwrap(); + let slit_tube = boolean(&tube, &slit, BoolOp::Cut).unwrap().unwrap(); + let tube_volume = crate::measure(&tube).unwrap().volume; + for off in [Vec3::ZERO, Vec3::new(2.2e-8, 4.7e-7, 0.0)] { + for (p, t) in [(pin(off, -2.35, 9.65), &tube), (pin(off, -3.0, 22.0), &tube), (pin(off, -2.35, 9.65), &slit_tube)] { + assert_eq!(p.face_count(), 5); + for (x, y) in [(&p, t), (t, &p)] { + let (r, report) = crate::capture_boolean_diagnostics(|| boolean(x, y, BoolOp::Intersect)); + assert!(r.unwrap().is_none() && report.events.is_empty(), "{off:?} {report:?}"); + } + let cut = boolean(&tube, &p, BoolOp::Cut).unwrap().unwrap(); + assert!((crate::measure(&cut).unwrap().volume - tube_volume).abs() < 1e-6 * tube_volume); + } + } + // Off the axis by 0.01 mm the pin shares a crescent with the tube: not taken for apart. + let (ma, mb) = (pin(Vec3::new(0.01, 0.0, 0.0), -2.35, 9.65), tube.clone()); + let counts = record::counts(&[&ma, &mb]); + let (sa, sb) = (ma.tessellate_with(0.009, true).unwrap(), mb.tessellate_with(0.009, true).unwrap()); + assert!(trivial(&ma, &mb, BoolOp::Intersect, &sa, &sb, &counts, 0.027).is_none_or(|(_, sure)| !sure)); + } + + /// A pin turned from a profile (its wall in three faces) and a plate with a bore of the pin's + /// size (its wall in two), the pin's end inside the bore: turned about the pin's axis and + /// the pair placed and tilted. + fn pin_in_plate_bore(radius: f64, turn: f64, (to, axis, angle): (Vec3, Vec3, f64)) -> (Body, Body) { + use solidcraft_geom::{Loop2, Plane, Region2, Vec2}; + let profile = Region2 { + outer: Loop2::polygon(&[Vec2::new(0.0, -2.35), Vec2::new(radius, -2.35), Vec2::new(radius, 9.65), Vec2::new(0.0, 9.65)]), + holes: vec![], + }; + let plane = Plane { origin: Vec3::ZERO, x: Vec3::X, y: Vec3::Z }; + let pin = crate::revolve(&plane, &[profile], Vec2::ZERO, Vec2::new(0.0, 1.0), std::f64::consts::TAU).unwrap().pop().unwrap(); + let pin = crate::transform(&pin, Vec3::ZERO, Vec3::ZERO, Vec3::Z, turn).unwrap(); + let block = crate::box_solid(Vec3::new(-8.0, -8.0, 0.0), Vec3::new(8.0, 8.0, 19.5)).unwrap(); + let bore = crate::cylinder(Vec3::new(0.0, 0.0, -1.0), Vec3::Z, 3.0, 21.5).unwrap(); + let plate = boolean(&block, &bore, BoolOp::Cut).unwrap().unwrap(); + let place = |b: &Body| crate::transform(b, to, Vec3::ZERO, axis, angle).unwrap(); + (place(&pin), place(&plate)) + } + + /// Placements of the pair: as built, far off the origin on its side, and tilted two ways. + const PLACEMENTS: [(Vec3, Vec3, f64); 4] = [ + (Vec3::ZERO, Vec3::Z, 0.0), + (Vec3::new(-270.0, 267.1, 546.7), Vec3::Y, -std::f64::consts::FRAC_PI_2), + (Vec3::new(120.0, -40.0, 15.0), Vec3::new(1.0, 1.0, 0.0), 0.7), + (Vec3::new(-35.0, 80.0, -60.0), Vec3::new(0.3, -0.5, 1.0), 2.1), + ]; + + /// The pin's end lies on the bore's rim at its own faceting, the plate's end face round the + /// pin at the bore's: the middle of a facet there can be just under the other body's facets + /// of the cylinder, so the material under it looked inside the other body though the two + /// only touch (the pin turned 9 steps and the pair tilted about x = y did, the boolean then + /// fell back on its retries and called its answer unverified). At every turn and placement + /// the pin is clear of the plate, answered at once. + #[test] + fn a_pin_in_a_plate_bore_of_its_size_is_clear_of_it_at_any_placement() { + for k in 0..12 { + for placement in PLACEMENTS { + let (pin, plate) = pin_in_plate_bore(3.0, k as f64 * 0.13, placement); + for (x, y) in [(&pin, &plate), (&plate, &pin)] { + let (r, report) = crate::capture_boolean_diagnostics(|| boolean(x, y, BoolOp::Intersect)); + assert!(matches!(r, Ok(None)) && report.events.is_empty(), "{k} {placement:?} {r:?} {report:?}"); + } + } + } + } + + /// The same pin 0.02 mm larger than the bore shares a ring with the plate along the length + /// it is in it: an overlap, at the placements above too. + #[test] + fn a_pin_slightly_larger_than_its_plate_bore_still_overlaps_it() { + let want = std::f64::consts::PI * (3.02f64.powi(2) - 9.0) * 9.65; + for k in [0, 3, 6, 9] { + for placement in PLACEMENTS { + let (pin, plate) = pin_in_plate_bore(3.02, k as f64 * 0.13, placement); + let (r, report) = crate::capture_boolean_diagnostics(|| boolean(&pin, &plate, BoolOp::Intersect)); + let shared = r.unwrap().map(|b| crate::measure(&b).unwrap().volume); + assert!(shared.is_some_and(|v| (v - want).abs() < 0.05 * want), "{k} {placement:?} {shared:?} {want} {report:?}"); + } + } + } + + /// A pin of the bore's size pushed 0.05 mm on past the bore, into a narrower one, shares a + /// ring with the tube there (0.2 % of the pin, under what the samples see): the crossings on + /// the shared cylinder are left out, those of the pin's end with the narrow bore are not. + #[test] + fn a_pin_pushed_into_a_narrower_bore_is_not_taken_for_clear() { + let outer = crate::cylinder(Vec3::ZERO, Vec3::Z, 5.25, 19.55).unwrap(); + let wide = crate::cylinder(Vec3::new(0.0, 0.0, -1.0), Vec3::Z, 3.0, 10.0).unwrap(); + let narrow = crate::cylinder(Vec3::new(0.0, 0.0, -1.0), Vec3::Z, 2.0, 21.55).unwrap(); + let tube = boolean(&boolean(&outer, &wide, BoolOp::Cut).unwrap().unwrap(), &narrow, BoolOp::Cut).unwrap().unwrap(); + let pin = crate::cylinder(Vec3::new(0.0, 0.0, -2.0), Vec3::Z, 3.0, 11.05).unwrap(); + let counts = record::counts(&[&pin, &tube]); + let (ma, mb) = (pin.tessellate_with(0.009, true).unwrap(), tube.tessellate_with(0.009, true).unwrap()); + for op in [BoolOp::Intersect, BoolOp::Cut] { + assert!(trivial(&pin, &tube, op, &ma, &mb, &counts, 0.027).is_none_or(|(_, sure)| !sure), "{op:?}"); + } + } + + /// A pin of the bore's size through a D-bore whose flat is 0.022 mm inside the pin (a sliver + /// of 0.21 mm³ along the bore): the pin's wall passes through the tube's end faces where the + /// flat reaches into the cylinder, near the shared cylinder but deeper than its facetings' + /// error. That is real overlap, and must not be taken for the facetings of the cylinder. + #[test] + fn a_pin_through_a_d_bore_of_its_size_still_overlaps_the_flat() { + let (r, flat, length) = (3.0, 2.978, 19.55); + let outer = crate::cylinder(Vec3::ZERO, Vec3::Z, 5.25, length).unwrap(); + let bore = crate::cylinder(Vec3::new(0.0, 0.0, -1.0), Vec3::Z, r, length + 2.0).unwrap(); + let keep = crate::box_solid(Vec3::new(-4.0, -4.0, -2.0), Vec3::new(flat, 4.0, length + 2.0)).unwrap(); + let d_bore = boolean(&bore, &keep, BoolOp::Intersect).unwrap().unwrap(); + let tube = boolean(&outer, &d_bore, BoolOp::Cut).unwrap().unwrap(); + let pin = crate::cylinder(Vec3::new(0.0, 0.0, -3.0), Vec3::Z, r, length + 6.0).unwrap(); + // Faceted as the boolean does for bodies of this size (0.015 mm deep crossings seen). + let counts = record::counts(&[&pin, &tube]); + let (ma, mb) = (pin.tessellate_with(0.005, true).unwrap(), tube.tessellate_with(0.005, true).unwrap()); + for op in [BoolOp::Intersect, BoolOp::Cut] { + assert!(trivial(&pin, &tube, op, &ma, &mb, &counts, 0.015).is_none_or(|(_, sure)| !sure), "{op:?}"); + } + // Nor does the boolean pass them as clear without saying so: the shortcut it falls back + // on is reported unverified (the bodies can't be intersected along the shared walls), + // and the caller measures the overlap another way. + let (shared, report) = crate::capture_boolean_diagnostics(|| boolean(&pin, &tube, BoolOp::Intersect)); + assert!(shared.unwrap().is_some() || report.unverified().is_some(), "{report:?}"); + } + /// Bodies sharing less than the samples can see still meet: no shortcut, and the boolean /// gives the shared part. #[test] From e984e7d7389064e335f6b64811f7473080950944 Mon Sep 17 00:00:00 2001 From: amolinari-autotex Date: Mon, 19 Oct 2026 23:56:42 +0000 Subject: [PATCH 148/225] Resolve picked-face feature actions and reveal the creator in Browser (#2301) (#2431) * claim: #2301 * fix: resolve face context actions from persistent face provenance * test: cover feature targeting from picked faces * fix: reveal picked face creators in the Browser --------- Co-authored-by: bherbruck --- crates/ui-egui/src/browser.rs | 12 +- crates/ui-egui/src/browser/features.rs | 186 +++++++++++++++++++++++++ crates/ui-egui/src/browser_model.rs | 4 + crates/ui-egui/src/context_menu.rs | 50 ++++++- crates/ui-egui/src/menu_tests.rs | 53 +++++++ docs/picked-face-navigation.md | 7 + 6 files changed, 305 insertions(+), 7 deletions(-) create mode 100644 crates/ui-egui/src/browser/features.rs create mode 100644 docs/picked-face-navigation.md diff --git a/crates/ui-egui/src/browser.rs b/crates/ui-egui/src/browser.rs index 40f19acae..42adc5cff 100644 --- a/crates/ui-egui/src/browser.rs +++ b/crates/ui-egui/src/browser.rs @@ -17,6 +17,12 @@ mod occurrence_gizmo_tests; #[path = "browser_model.rs"] mod model; +mod features; + +pub(crate) fn reveal_feature(app: &mut SolveApp, id: u64, body: &str) { + features::reveal(app, id, body); +} + #[cfg(test)] #[path = "browser_model_tests.rs"] mod model_tests; @@ -61,6 +67,8 @@ pub struct TreeState { pub expanded: BTreeSet, /// Scroll to this body's row and open its folders (Find in Browser). pub reveal: Option, + /// A native feature to reveal in its placed component's Features folder. + pub(super) reveal_feature: Option, /// The Move/Copy panel of an occurrence. pub occurrence_move: Option, /// The Redefine Sketch Plane panel (sketch id). @@ -488,7 +496,7 @@ fn sel_of_key(k: &str) -> Option { if let Some(b) = k.strip_prefix("b:") { return Some(Sel::Body { name: b.to_string() }); } - if let Some(s) = k.strip_prefix("s:") { + if let Some(s) = k.strip_prefix("s:").or_else(|| k.strip_prefix("f:")) { return s.parse().ok().map(|id| Sel::Feature { id }); } None @@ -952,6 +960,7 @@ fn component_rows(app: &mut SolveApp, ui: &mut egui::Ui, id: u64, depth: usize, for folder in ["bodies", "sketches", "construction"] { folder_rows(app, ui, id, folder, d, acts); } + features::rows(app, ui, id, &[], d, acts); if id == 0 { crate::dialogs_assembly::browser_joints(app, ui, d); } @@ -1057,6 +1066,7 @@ fn occurrence_rows(app: &mut SolveApp, ui: &mut egui::Ui, path: Vec, depth: for folder in ["bodies", "sketches", "construction"] { occurrence_folder_rows(app, ui, placement.component, &path, folder, depth + 1, acts); } + features::rows(app, ui, placement.component, &path, depth + 1, acts); let children = model_children(app, placement.component); if path.len() < 64 { for occurrence in children { diff --git a/crates/ui-egui/src/browser/features.rs b/crates/ui-egui/src/browser/features.rs new file mode 100644 index 000000000..3cb44fc01 --- /dev/null +++ b/crates/ui-egui/src/browser/features.rs @@ -0,0 +1,186 @@ +//! Native feature rows in the component browser, separate from timeline layout and order. + +use super::*; + +#[derive(Clone, Debug)] +pub(crate) struct Reveal { + pub id: u64, + pub path: Vec, +} + +/// Reveal the actual creating feature without changing the active component or history marker. +pub(crate) fn reveal(app: &mut SolveApp, id: u64, body: &str) { + let Some(feature) = app.session.doc.feature(id) else { return }; + let component = feature.component; + let state = app.session.model.state(); + let world = app.session.world_state(); + let Some(selected) = world.body(body) else { return }; + let source = selected.definition_name(); + let Some((_, path, _)) = app + .session + .doc + .placements() + .into_iter() + .find(|(owner, path, _)| *owner == component && app.session.doc.world_body_name(&state, source, component, path) == body) + else { + return; + }; + app.ui.show_browser = true; + app.preferences.timeline_left_browser_collapsed = false; + app.tree.reveal = None; + app.tree.collapsed.remove("c0"); + for depth in 1..=path.len() { + app.tree.collapsed.remove(&occurrence_key(&path[..depth])); + } + let scope = if path.is_empty() { format!("c{component}") } else { occurrence_key(&path) }; + app.tree.expanded.insert(format!("{scope}/features")); + app.tree.reveal_feature = Some(Reveal { id, path }); + let _ = app.run("select.set", json!({"items":[Sel::Feature { id }]})); +} + +pub(super) fn rows(app: &mut SolveApp, ui: &mut egui::Ui, component: u64, path: &[u64], depth: usize, acts: &mut Actions) { + let has_features = match app.tree.model.as_ref().filter(|m| m.matches(&app.session)) { + Some(model) => model.features.get(&component).is_some_and(|features| !features.is_empty()), + None => app.session.doc.features.iter().any(|feature| feature.component == component), + }; + if !has_features { + return; + } + let scope = if path.is_empty() { format!("c{component}") } else { occurrence_key(path) }; + let key = format!("{scope}/features"); + let open = is_open(app, &key, false); + let r = draw_row(ui, ui.id().with(&key), &Row { depth, fold: Some(open), icon: "folder", label: "Features", ..Default::default() }); + if r.fold || r.clicked { + toggle(app, &key, false); + } + if !open { + return; + } + let indices = match app.tree.model.as_ref().filter(|m| m.matches(&app.session)) { + Some(model) => model.features.get(&component).cloned().unwrap_or_default(), + None => app.session.doc.features.iter().enumerate().filter_map(|(i, f)| (f.component == component).then_some(i)).collect(), + }; + for index in indices { + let Some(feature) = app.session.doc.features.get(index) else { continue }; + let (id, label, icon) = (feature.id, feature.name.clone(), crate::timeline::icon_of(&feature.kind)); + let selected = app.session.selection.contains(&Sel::Feature { id }); + app.tree.order.push(format!("f:{id}")); + let r = draw_row(ui, ui.id().with(("browser_feature", id)), &Row { depth: depth + 1, icon, label: &label, selected, ..Default::default() }); + if let Some(rect) = r.rect { + crate::scenario::publish_handle(&format!("row:browser-feature:{scope}:{id}"), rect.center()); + if app.tree.reveal_feature.as_ref().is_some_and(|target| target.id == id && target.path == path) { + ui.scroll_to_rect(rect, Some(egui::Align::Center)); + app.tree.reveal_feature = None; + } + } + if r.double { + if !path.is_empty() { + let _ = app.run("component.activate", json!({"component":component,"occurrence":path.last(),"path":path})); + } + app.edit_feature(id); + } else if r.clicked { + click_select(app, ui, format!("f:{id}"), Some(Sel::Feature { id })); + } + if let Some(at) = r.secondary { + acts.menu = Some((at, Target::Feature { id })); + } + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod tests { + use super::*; + use crate::scenario::Harness; + + fn find(app: &mut SolveApp, feature: u64, body: &str) { + let state = app.session.world_state(); + let model_body = state.body(body).unwrap(); + let names = solidcraft_engine::doc::naming::face_names(model_body); + let index = names.iter().position(|name| name.starts_with(&format!("F{feature}:"))).unwrap(); + app.session.selection = vec![Sel::Face { body: body.into(), index, point: solidcraft_engine::geom::Vec3::ZERO }]; + let item = crate::context_menu::items(app, &Target::Viewport).into_iter().find(|item| item.id == "ui.findBrowser").unwrap(); + assert!(item.enabled); + crate::context_menu::run_item(app, &item, pos2(0.0, 0.0)); + assert_eq!(app.session.selection, [Sel::Feature { id: feature }]); + } + + #[test] + fn browser_feature_reveal_opens_the_picked_placement_and_survives_reopen() { + let mut h = Harness::new(); + let assembly = h.app.run("component.create", json!({"name":"Assembly"})).unwrap(); + let component = h.app.run("component.create", json!({"name":"Part"})).unwrap(); + let base = h.app.run("solid.box", json!({"length":40,"width":30,"height":20,"body_name":"Plate"})).unwrap()["feature"].as_u64().unwrap(); + let hole = h.app.run("solid.hole", json!({"position":[20,15,20],"diameter":8})).unwrap()["feature"].as_u64().unwrap(); + let fillet = h.app.run("solid.fillet", json!({"edges":[[0,0,10]],"radius":2})).unwrap()["feature"].as_u64().unwrap(); + h.app.run("solid.hole", json!({"position":[32,20,20],"diameter":4})).unwrap(); + let copy = h.app.run("occurrence.copy", json!({"occurrence":assembly["occurrence"],"translate":[70,25,10]})).unwrap(); + h.app.run("occurrence.move", json!({"occurrence":copy["occurrence"],"axis":[0,0,1],"angle":"35 deg","capture":true})).unwrap(); + let path = vec![copy["occurrence"].as_u64().unwrap(), component["occurrence"].as_u64().unwrap()]; + h.app.run("component.activate", json!({"component":0})).unwrap(); + let world_body = h.app.session.occurrence_bodies(&path, false).unwrap()[0].clone(); + let saved = h.app.session.doc.to_json(); + h.app.session = solidcraft_engine::Session::new(solidcraft_engine::doc::Document::from_json(&saved).unwrap()); + h.app.tree.collapsed.insert("c0".into()); + h.app.tree.collapsed.insert(occurrence_key(&path)); + h.app.preferences.timeline_left_browser_collapsed = true; + let undo = h.app.session.undo.len(); + for id in [base, hole, fillet] { + find(&mut h.app, id, &world_body); + assert_eq!(h.app.tree.reveal_feature.as_ref().unwrap().path, path); + assert!(!h.app.tree.collapsed.contains("c0")); + assert!(!h.app.tree.collapsed.contains(&occurrence_key(&path))); + assert!(!h.app.preferences.timeline_left_browser_collapsed); + h.frames(2); + assert!(h.app.tree.reveal_feature.is_none(), "the actual feature row was drawn and scrolled to"); + let at = h.call("ui.at", json!({"handle":format!("row:browser-feature:{}:{id}",occurrence_key(&path))})); + assert!(at["ok"].as_bool().unwrap_or(false), "{at}"); + } + assert_eq!(h.app.session.doc.to_json(), saved); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(h.app.session.active_component, 0); + } + + #[test] + fn browser_feature_body_only_and_stale_targets_keep_their_meaning() { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":10,"height":10,"body_name":"Plate"})).unwrap(); + h.app.session.selection = vec![Sel::Body { name: "Plate".into() }]; + let item = crate::context_menu::items(&h.app, &Target::Viewport).into_iter().find(|item| item.id == "ui.findBrowser").unwrap(); + crate::context_menu::run_item(&mut h.app, &item, pos2(0.0, 0.0)); + assert_eq!(h.app.tree.reveal.as_deref(), Some("Plate")); + assert!(h.app.tree.reveal_feature.is_none()); + let before = h.app.session.selection.clone(); + reveal(&mut h.app, u64::MAX, "Plate"); + reveal(&mut h.app, 1, "Missing"); + assert_eq!(h.app.session.selection, before); + } + + #[test] + fn browser_feature_imported_source_ids_never_reveal_an_unrelated_native_feature() { + struct Source(std::path::PathBuf); + impl Drop for Source { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } + } + let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let source = Source(std::env::temp_dir().join(format!("solidcraft-browser-import-{}-{stamp}.solidcraft", std::process::id()))); + let mut saved = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + saved.run("solid.box", json!({"length":10,"width":10,"height":10,"body_name":"Imported"})).unwrap(); + saved.run("file.save", json!({"path":source.0.to_string_lossy()})).unwrap(); + let mut h = Harness::new(); + let base = h.app.run("solid.box", json!({"length":5,"width":5,"height":5,"body_name":"Native"})).unwrap()["feature"].as_u64().unwrap(); + let inserted = h.app.run("component.insert_design", json!({"path":source.0.to_string_lossy()})).unwrap(); + let path = vec![inserted["occurrence"].as_u64().unwrap()]; + let name = h.app.session.occurrence_bodies(&path, false).unwrap()[0].clone(); + let state = h.app.session.world_state(); + let owner = state.body(&name).unwrap().feature; + assert_ne!(owner, base); + h.app.session.selection = vec![Sel::Face { body: name, index: 0, point: solidcraft_engine::geom::Vec3::ZERO }]; + for id in ["ui.findBrowser", "ui.findTimeline", "ui.editFeature"] { + let item = crate::context_menu::items(&h.app, &Target::Viewport).into_iter().find(|item| item.id == id).unwrap(); + assert!(!item.enabled || item.params.as_ref().unwrap()["feature"] == json!(owner), "{id}: {item:?}"); + } + } +} diff --git a/crates/ui-egui/src/browser_model.rs b/crates/ui-egui/src/browser_model.rs index b1316dfa3..8eb41ba30 100644 --- a/crates/ui-egui/src/browser_model.rs +++ b/crates/ui-egui/src/browser_model.rs @@ -17,6 +17,7 @@ pub(super) struct Model { pub bodies: HashMap>, pub sketches: HashMap>, pub planes: HashMap>, + pub features: HashMap>, pub children: HashMap>, placements: HashMap, Option>>, /// Each placed body's placement path, by the body's world name (built on first use). @@ -32,7 +33,9 @@ impl Model { } let mut sketches: HashMap> = HashMap::new(); let mut planes: HashMap> = HashMap::new(); + let mut features: HashMap> = HashMap::new(); for (i, feature) in session.doc.features.iter().enumerate() { + features.entry(feature.component).or_default().push(i); let index = match feature.kind { FeatureKind::Sketch { .. } => &mut sketches, FeatureKind::ConstructionPlane { .. } => &mut planes, @@ -51,6 +54,7 @@ impl Model { bodies, sketches, planes, + features, children, placements: HashMap::new(), body_paths: None, diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index e02217e2b..0c1d9e4a5 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -37,6 +37,10 @@ pub enum Target { Plane { id: u64, }, + /// A native feature row in a component's Features folder. + Feature { + id: u64, + }, /// An origin plane (XY, XZ or YZ). OriginPlane { name: String, @@ -270,6 +274,7 @@ pub fn target_bodies(app: &SolveApp, target: &Target) -> Vec { Target::Occurrence { path } => app.session.occurrence_bodies(path, true).unwrap_or_default(), Target::Group { id, .. } => crate::browser::group_bodies(app, *id), Target::Sketch { .. } + | Target::Feature { .. } | Target::Plane { .. } | Target::OriginPlane { .. } | Target::Folder { .. } @@ -329,6 +334,10 @@ pub fn items(app: &SolveApp, target: &Target) -> Vec { Target::Viewport => viewport_items(app), Target::Body { name } => body_items(app, std::slice::from_ref(name), true), Target::Sketch { id } => sketch_items(app, *id), + Target::Feature { id } => vec![ + act("ui.editFeature", "Edit Feature", "").with(json!({"feature":id})).on(app.session.doc.feature(*id).is_some()), + act("ui.findTimeline", "Find in Timeline", "").with(json!({"feature":id})).on(app.session.doc.feature(*id).is_some()), + ], Target::Plane { id } => plane_items(app, *id), Target::OriginPlane { name } => origin_plane_items(app, name), Target::Component { id } => component_items(app, *id), @@ -373,9 +382,30 @@ pub fn items(app: &SolveApp, target: &Target) -> Vec { v } -/// The feature a body was made by, and that feature's sketch if it has one. -fn body_feature_and_sketch(app: &SolveApp, body: &str) -> (Option, Option) { - let f = body_feature(app, body); +/// Resolve the picked face's creator, rather than the feature that first made its body. +/// Persistent face names retain their creator through later trims and placements. +fn picked_face_feature(app: &SolveApp) -> Option { + let (body, index) = app.session.selection.iter().find_map(|s| match s { + Sel::Face { body, index, .. } => Some((body, *index)), + _ => None, + })?; + let state = app.session.world_state(); + let body = state.body(body)?; + let names = solidcraft_engine::doc::naming::face_names(body); + let name = names.get(index)?; + let (creator, _) = name.strip_prefix('F')?.split_once(':')?; + let id = creator.parse::().ok()?; + let owner = app.session.doc.feature(body.feature)?; + if matches!(owner.kind, solidcraft_engine::doc::FeatureKind::Import { .. } | solidcraft_engine::doc::FeatureKind::MeshImport { .. }) + && id != owner.id + { + return None; + } + app.session.doc.feature(id).filter(|f| f.component == app.session.doc.model_body_component(body)).map(|f| f.id) +} + +/// A feature and its profile sketch, if it has one. +fn feature_and_sketch(app: &SolveApp, f: Option) -> (Option, Option) { let sketch = f .and_then(|f| app.session.doc.feature(f)) .and_then(|f| serde_json::to_value(&f.kind).ok()) @@ -421,7 +451,7 @@ fn viewport_items(app: &SolveApp) -> Vec { v.extend(sketch_items(app, sketch)); } else if has(|s| matches!(s, Sel::Face { .. })) { let face = sel.iter().find_map(|s| if let Sel::Face { body, .. } = s { Some(body.clone()) } else { None }).unwrap_or_default(); - let (feature, sketch) = body_feature_and_sketch(app, &face); + let (feature, sketch) = feature_and_sketch(app, picked_face_feature(app)); let hidden = app.session.visibility.hidden_bodies.contains(&face); v.push(cmd(app, "sketch.create", "Create Sketch")); v.push(cmd(app, "solid.extrude", "Extrude")); @@ -437,8 +467,8 @@ fn viewport_items(app: &SolveApp) -> Vec { v.push(act("ui.delete", "Delete", "delete").key("Del")); v.push(act(if hidden { "ui.show" } else { "ui.hide" }, "Show/Hide", "eye").key("V").with(json!({ "bodies": [face] }))); v.push(Item::sep()); - v.push(act("ui.findBrowser", "Find in Browser", "").with(json!({ "body": face }))); - v.push(act("ui.findTimeline", "Find in Timeline", "").with(json!({ "body": face }))); + v.push(act("ui.findBrowser", "Find in Browser", "").with(json!({ "body": face, "feature": feature })).on(feature.is_some())); + v.push(act("ui.findTimeline", "Find in Timeline", "").with(json!({ "feature": feature })).on(feature.is_some())); v.push(Item::sep()); v.push(cmd(app, "solid.press_pull", "Press Pull")); v.push(cmd(app, "inspect.measure", "Measure")); @@ -1000,8 +1030,16 @@ pub fn run_item(app: &mut SolveApp, item: &Item, at: Pos2) { app.pick_save_command(&format!("{name}.step"), &["step", "stp", "igs", "stl", "3mf", "obj"], "file.export", json!({"bodies": bodies})); } "ui.findBrowser" => { + if let Some(feature) = id_of(&p, "feature") { + if let Some(body) = p.get("body").and_then(Value::as_str) { + crate::browser::reveal_feature(app, feature, body); + } + return; + } if let Some(b) = p.get("body").and_then(Value::as_str) { app.ui.show_browser = true; + app.preferences.timeline_left_browser_collapsed = false; + app.tree.reveal_feature = None; app.tree.reveal = Some(b.to_string()); let _ = app.run("select.set", json!({"items": [{"type": "body", "name": b}]})); } diff --git a/crates/ui-egui/src/menu_tests.rs b/crates/ui-egui/src/menu_tests.rs index ad09152be..cfe1c4792 100644 --- a/crates/ui-egui/src/menu_tests.rs +++ b/crates/ui-egui/src/menu_tests.rs @@ -805,3 +805,56 @@ fn menus_near_the_window_corner_open_inward() { } } } + +#[test] +fn contribution_picked_faces_open_their_own_feature_after_later_modifiers() { + use solidcraft_engine::{Sel, geom::Vec3}; + for expected in [1, 2, 3] { + let mut app = SolveApp::new(Session::default(), Services::default()); + app.run("solid.box", json!({"length":40,"width":30,"height":20,"body_name":"Plate"})).unwrap(); + app.run("solid.hole", json!({"position":[20,15,20],"diameter":8})).unwrap(); + app.run("solid.fillet", json!({"edges":[[0,0,10]],"radius":2})).unwrap(); + app.run("solid.hole", json!({"position":[32,20,20],"diameter":4})).unwrap(); + let state = app.session.world_state(); + let b = state.body("Plate").unwrap(); + let names = solidcraft_engine::doc::naming::face_names(b); + let index = names.iter().position(|n| n.starts_with(&format!("F{expected}:"))).unwrap(); + let mesh = b.mesh(); + let point = mesh + .triangles + .iter() + .enumerate() + .find_map(|(i, t)| (mesh.tri_face.get(i).copied() == Some(index as u32)).then(|| mesh.tri(t)).flatten()) + .map(|t| (t[0] + t[1] + t[2]) / 3.0) + .unwrap_or(Vec3::ZERO); + let pick = Sel::Face { body: "Plate".into(), index, point }; + app.session.selection = vec![pick.clone()]; + let items = context_menu::items(&app, &Target::Viewport); + for label in ["Edit Feature", "Find in Timeline", "Find in Browser"] { + let item = find(&items, label); + assert!(item.enabled, "{label}, {expected}: {names:?}"); + assert_eq!(item.params.as_ref().unwrap()["feature"], json!(expected)); + } + act(&mut app, &Target::Viewport, "Find in Timeline"); + assert_eq!(app.session.selection, vec![Sel::Feature { id: expected }]); + app.session.selection = vec![pick.clone()]; + act(&mut app, &Target::Viewport, "Find in Browser"); + assert_eq!(app.session.selection, vec![Sel::Feature { id: expected }]); + assert_eq!(app.tree.reveal_feature.as_ref().unwrap().id, expected); + app.session.selection = vec![pick]; + act(&mut app, &Target::Viewport, "Edit Feature"); + assert_eq!(app.dialog.as_ref().unwrap().editing.unwrap().0, expected); + } +} + +#[test] +fn contribution_unresolvable_face_does_not_edit_the_body_creator() { + let mut app = SolveApp::new(Session::default(), Services::default()); + app.run("solid.box", json!({"length":10,"width":10,"height":10,"body_name":"Plate"})).unwrap(); + app.session.selection = + vec![solidcraft_engine::Sel::Face { body: "Plate".into(), index: usize::MAX, point: solidcraft_engine::geom::Vec3::ZERO }]; + let items = context_menu::items(&app, &Target::Viewport); + assert!(!find(&items, "Edit Feature").enabled); + assert!(!find(&items, "Find in Timeline").enabled); + assert!(!find(&items, "Find in Browser").enabled); +} diff --git a/docs/picked-face-navigation.md b/docs/picked-face-navigation.md new file mode 100644 index 000000000..70dac8b5b --- /dev/null +++ b/docs/picked-face-navigation.md @@ -0,0 +1,7 @@ +# Picked-face navigation + +A face selected in the viewport uses its persistent creating feature for **Edit Feature**, **Find in Timeline** and **Find in Browser**. Later holes, blends and trims do not redirect the action to the feature that originally created the whole body. + +The Browser contains a **Features** folder for each native component with history. Find in Browser opens the ancestors and this folder in the selected body's actual occurrence, selects the creating feature and scrolls its row into view. Double-clicking the row opens its editor. This leaves the timeline layout, active component and history marker unchanged until an edit is requested. + +Selecting a whole body keeps the existing body navigation. A face with an unavailable creator does not fall back to the body's base feature. Imported source identifiers do not acquire an unrelated editable native history. From 33d7a86d500b0fb5eff429876bcd9064098589d3 Mon Sep 17 00:00:00 2001 From: DuBearte <130190089+DuBearte@users.noreply.github.com> Date: Mon, 19 Oct 2026 23:56:46 +0000 Subject: [PATCH 149/225] Extrude: a tapered side drawn in collinear pieces is one face too (#1788) (#2583) #1949 joined the straight runs of a profile into one side face for straight extrudes; tapered extrudes (extrude_tapered, extrude_tapered_between) still sloped each piece as its own face, so a drafted mirrored profile kept the edge. They now join the runs the same way (NumberedLoop::merged_lines), the sloped side generated by every piece under it. Co-authored-by: Claude Opus 5.5 Co-authored-by: bherbruck --- crates/engine/src/tests.rs | 12 ++++++++++++ crates/kernel/src/build.rs | 4 +++- crates/kernel/src/history_tests.rs | 25 +++++++++++++++++++++++++ 3 files changed, 40 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e65bd328d..9d99288cd 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -3778,3 +3778,15 @@ fn a_sketch_on_one_piece_stays_attached_when_the_side_joins() { let sketch = run(&mut s, "timeline.inspect", json!({"feature": "Sketch2"})); assert!(sketch["error"].is_null() && sketch["warning"].is_null(), "{sketch}"); } + +/// With a taper too, a side drawn in two collinear pieces extrudes into one face (#1788). +#[test] +fn a_tapered_side_drawn_in_two_collinear_pieces_is_one_face() { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY"})); + run(&mut s, "sketch.line", json!({"points": [[0, 0], [10, 0], [20, 0], [20, 10], [0, 10], [0, 0]]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"distance": 5, "taper": "5 deg"})); + let m = run(&mut s, "inspect.measure", json!({})); + assert_eq!(m["bodies"][0]["kernel"]["faces"], 6, "{m}"); +} diff --git a/crates/kernel/src/build.rs b/crates/kernel/src/build.rs index d4ff0dcd6..7d306b371 100644 --- a/crates/kernel/src/build.rs +++ b/crates/kernel/src/build.rs @@ -1328,7 +1328,9 @@ pub fn extrude_tapered_between(plane: &Plane, region: &Region2, from: f64, to: f region_ok(region)?; let (t, sign) = (taper.tan(), dir_sign.signum()); let (bottom_plane, top_plane) = (plane.offset(from * sign), plane.offset(to * sign)); - let loops0 = oriented(region)?; + // A side drawn in collinear pieces slopes as one face over all of them, as a straight + // extrude's does (#1788). + let loops0 = oriented(region)?.map_loops(|l| l.merged_lines(continues_straight)); let split: Vec<(Loop2, Vec)> = loops0.loops().map(|l| offset_splits(&l.lp, from.abs().max(to.abs()) * t)).collect(); let ends = |h: f64| split.iter().map(|(lp, _)| offset_loop(lp, h * t)).collect::>>(); let (bottoms, tops) = (ends(from)?, ends(to)?); diff --git a/crates/kernel/src/history_tests.rs b/crates/kernel/src/history_tests.rs index 25e2a58f0..7ce1c10ce 100644 --- a/crates/kernel/src/history_tests.rs +++ b/crates/kernel/src/history_tests.rs @@ -277,3 +277,28 @@ fn collinear_profile_lines_extrude_into_one_side_face() { let body = crate::extrude_whole_sides(&Plane::XY, &[Region2 { outer: Loop2::polygon(&step), holes: vec![] }], 0.0, 5.0).unwrap().pop().unwrap(); assert_eq!(body.face_count(), 8); } + +/// A tapered extrude joins a side drawn in collinear pieces as the straight extrude does +/// (#1788): one sloped face generated by both pieces, and the same solid as a side in one piece. +#[test] +fn collinear_profile_lines_taper_into_one_side_face() { + use solidcraft_geom::{Loop2, Plane, Region2, Vec2}; + let polygon = + |pts: &[(f64, f64)]| Region2 { outer: Loop2::polygon(&pts.iter().map(|&(x, y)| Vec2::new(x, y)).collect::>()), holes: vec![] }; + let split = polygon(&[(0.0, 0.0), (10.0, 0.0), (20.0, 0.0), (20.0, 10.0), (0.0, 10.0)]); + let whole = polygon(&[(0.0, 0.0), (20.0, 0.0), (20.0, 10.0), (0.0, 10.0)]); + let taper = 5f64.to_radians(); + for (from, to, foot) in [(0.0, 5.0, 0.0), (-1.0, 5.0, 1.0)] { + let body = crate::extrude_tapered_between(&Plane::XY, &split, from, to, foot, 1.0, taper).unwrap(); + let reference = crate::extrude_tapered_between(&Plane::XY, &whole, from, to, foot, 1.0, taper).unwrap(); + assert_eq!(body.face_count(), reference.face_count(), "{from}..{to} foot {foot}: as many faces as one piece"); + let (v, w) = (crate::measure(&body).unwrap().volume, crate::measure(&reference).unwrap().volume); + assert!((v - w).abs() < 1e-9 * w, "{v} vs {w}"); + let h = body.history().unwrap(); + h.check(&body, &[]).unwrap(); + assert!( + h.faces.iter().any(|f| f.origins == vec![FaceOrigin::Profile { segment: 0 }, FaceOrigin::Profile { segment: 1 }]), + "the bottom side is generated by both its pieces" + ); + } +} From 07be3f885226a4123ca2d66d708570969ff68419 Mon Sep 17 00:00:00 2001 From: amolinari-autotex Date: Mon, 19 Oct 2026 23:56:48 +0000 Subject: [PATCH 150/225] Paste saved linked designs at the viewport pointer (#2430) (#2433) * claim: #2430 * feat: copy saved designs between documents as linked components * fix: keep occurrence movement controls with their document tab * test: cover linked design clipboard across tabs * fix: place linked design pastes at the viewport pointer --------- Co-authored-by: bherbruck --- crates/engine/src/cmd/component.rs | 4 +- crates/engine/src/cmd/component_link.rs | 15 +- crates/ui-egui/src/context_menu.rs | 3 + crates/ui-egui/src/documents.rs | 4 +- crates/ui-egui/src/edit_clipboard.rs | 75 ++++++++- crates/ui-egui/src/edit_clipboard_tests.rs | 182 +++++++++++++++++++++ crates/ui-egui/src/lib.rs | 3 + docs/linked-design-paste.md | 9 + 8 files changed, 288 insertions(+), 7 deletions(-) create mode 100644 docs/linked-design-paste.md diff --git a/crates/engine/src/cmd/component.rs b/crates/engine/src/cmd/component.rs index 847737fc4..bbd341e45 100644 --- a/crates/engine/src/cmd/component.rs +++ b/crates/engine/src/cmd/component.rs @@ -107,7 +107,7 @@ pub(super) fn valid_position(m: &Mat) -> bool { && (m[3][3] - 1.0).abs() < 1e-9 } -fn new_component(s: &mut Session, p: &Value) -> Result { +pub(super) fn new_component(s: &mut Session, p: &Value) -> Result { let cmd = "component.create"; let parent = if p.get("parent").is_some() { component(s, p, "parent", cmd)? } else { s.active_component }; let parent_path = if let Some(value) = p.get("parent_path") { @@ -312,7 +312,7 @@ fn move_sketches(s: &mut Session, p: &Value) -> Result { Ok(json!({"sketches": ids, "component": to})) } -fn copy_occurrence(s: &mut Session, p: &Value) -> Result { +pub(super) fn copy_occurrence(s: &mut Session, p: &Value) -> Result { let cmd = "occurrence.copy"; let selected = if p.get("occurrence").is_some() { let o = occurrence(s, p, cmd)?; diff --git a/crates/engine/src/cmd/component_link.rs b/crates/engine/src/cmd/component_link.rs index 343c67491..95f029e3f 100644 --- a/crates/engine/src/cmd/component_link.rs +++ b/crates/engine/src/cmd/component_link.rs @@ -23,7 +23,8 @@ mod relink_tests; pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("component.insert_design", "Insert Design", insert_design).at("SOLID", "ASSEMBLE").icon("component").params( "path: a .solidcraft design → a new component linked to it, holding its solid bodies as placed in that design; \ - name? (default: the design's name); parent?: component id or name (default: the active one); translate?: [x,y,z]", + name? (default: the design's name); parent?: component id or name (default: the active one); translate?: [x,y,z]; \ + reuse?: bool (default false): insert another occurrence of an existing link to the same file", ), CommandSpec::new("component.update_links", "Update Links", update_links).icon("update").params( "component?: id or name (default: every linked component) — reads the linked designs again and replaces their bodies where they changed", @@ -147,13 +148,23 @@ fn insert_design(s: &mut Session, p: &Value) -> Result { Some(v) => vec3(v).filter(|t| t.is_finite() && t.len() < 1e9).ok_or_else(|| bad(cmd, "`translate` must be [x, y, z] in mm"))?, }; let file = absolute(Path::new(given)); + if s.path.as_deref().is_some_and(|own| absolute(Path::new(own)) == file) { + return Err(bad(cmd, "a design can't be linked into itself")); + } + if p.get("reuse").and_then(Value::as_bool).unwrap_or(false) { + let existing = s.doc.links.iter().find(|(_, link)| absolute(&resolve(s.path.as_deref(), &link.path)) == file).map(|(id, _)| *id); + if let Some(component) = existing { + let parent = p.get("parent").cloned().unwrap_or_else(|| json!(s.active_component)); + return super::component::copy_occurrence(s, &json!({"component": component, "parent": parent, "translate": translate})); + } + } let (design_name, sf) = linked_bodies(&file, s.path.as_deref())?; let name = str_(p, "name").filter(|n| !n.trim().is_empty()).map(str::to_string).unwrap_or(design_name); let mut create = json!({"name": name, "activate": false}); if let Some(parent) = p.get("parent") { create["parent"] = parent.clone(); } - let made = s.execute("component.create", &create)?; + let made = super::component::new_component(s, &create)?; let comp = made["component"].as_u64().ok_or_else(|| bad(cmd, "the component was not created"))?; let occ = made["occurrence"].as_u64(); let id = s.doc_mut().add_feature(sf.kind, Some(&name))?; diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index 0c1d9e4a5..b71b08e23 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -733,6 +733,8 @@ fn component_items(app: &SolveApp, id: u64) -> Vec { } v.push(cmd(app, "component.create", "New Component").with(json!({ "parent": id }))); if id == 0 { + v.push(act("ui.copyDesign", "Copy", "").key("Ctrl+C")); + v.push(act("ui.paste", "Paste", "").key("Ctrl+V").on(crate::edit_clipboard::can_paste(app))); v.push(cmd(app, "component.from_bodies", "Create Components from Bodies").with(json!({ "bodies": names })).on(!bodies.is_empty())); } v.push(Item::sep()); @@ -945,6 +947,7 @@ pub fn run_item(app: &mut SolveApp, item: &Item, at: Pos2) { } } "ui.copy" => drop(crate::edit_clipboard::copy(app)), + "ui.copyDesign" => drop(crate::edit_clipboard::copy_design(app)), "ui.cut" => drop(crate::edit_clipboard::cut(app)), "ui.paste" => drop(crate::edit_clipboard::paste(app, Some(at))), "ui.editSketchPattern" => { diff --git a/crates/ui-egui/src/documents.rs b/crates/ui-egui/src/documents.rs index fced2be8a..5b869b279 100644 --- a/crates/ui-egui/src/documents.rs +++ b/crates/ui-egui/src/documents.rs @@ -22,6 +22,7 @@ pub struct DocSlot { pre_sketch_cam: Option, pre_sketch_marker: Option>, view: DocView, + occurrence_move: Option, } /// The per-design part of the UI state (what is hidden, shown or locked). @@ -36,7 +37,7 @@ struct DocView { impl DocSlot { fn new(session: Session) -> DocSlot { - DocSlot { session, cam: Camera::default(), pre_sketch_cam: None, pre_sketch_marker: None, view: DocView::default() } + DocSlot { session, cam: Camera::default(), pre_sketch_cam: None, pre_sketch_marker: None, view: DocView::default(), occurrence_move: None } } } @@ -111,6 +112,7 @@ fn swap_in(app: &mut SolveApp, slot: DocSlot) -> DocSlot { pre_sketch_cam: std::mem::replace(&mut app.pre_sketch_cam, slot.pre_sketch_cam), pre_sketch_marker: std::mem::replace(&mut app.pre_sketch_marker, slot.pre_sketch_marker), view: take_view(app), + occurrence_move: std::mem::replace(&mut app.tree.occurrence_move, slot.occurrence_move), }; put_view(app, slot.view); // Preferences the session holds go with the user, not the tab (#680). diff --git a/crates/ui-egui/src/edit_clipboard.rs b/crates/ui-egui/src/edit_clipboard.rs index 3806474e6..312167a4e 100644 --- a/crates/ui-egui/src/edit_clipboard.rs +++ b/crates/ui-egui/src/edit_clipboard.rs @@ -42,16 +42,39 @@ fn sketch_selection(app: &SolveApp) -> Vec { /// Is there something Copy would copy? pub fn can_copy(app: &SolveApp) -> bool { - if app.session.active_sketch.is_some() { !sketch_selection(app).is_empty() } else { !crate::timeline::selected_feature_ids(app).is_empty() } + if app.session.active_sketch.is_some() { + !sketch_selection(app).is_empty() + } else { + app.tree.picked_components == [0] || !crate::timeline::selected_feature_ids(app).is_empty() + } } /// Is there something Paste would paste here? pub fn can_paste(app: &SolveApp) -> bool { - if app.session.active_sketch.is_some() { app.session.sketch_clipboard.is_some() } else { !app.session.clipboard.is_empty() } + if app.session.active_sketch.is_some() { + app.session.sketch_clipboard.is_some() + } else { + app.linked_design_clipboard.is_some() || !app.session.clipboard.is_empty() + } +} + +/// Copy the saved root design. The path stays in this app, outside per-document sessions. +pub fn copy_design(app: &mut SolveApp) -> bool { + let Some(path) = app.session.path.clone().filter(|_| !app.session.is_dirty()) else { + app.set_status("Save this design before copying it as a linked component", true); + return false; + }; + app.linked_design_clipboard = Some(path); + leave_text(format!("SolidCraft linked design: {}", app.session.doc.name)); + app.set_status("Copied design: switch to the assembly and paste to insert a linked component", false); + true } /// Copy the selection: sketch geometry in a sketch, otherwise timeline features. pub fn copy(app: &mut SolveApp) -> bool { + if app.session.active_sketch.is_none() && app.tree.picked_components == [0] { + return copy_design(app); + } if app.session.active_sketch.is_some() { let entities = sketch_selection(app); if entities.is_empty() { @@ -59,6 +82,7 @@ pub fn copy(app: &mut SolveApp) -> bool { return false; } let Ok(out) = app.run("sketch.copy", json!({ "entities": entities })) else { return false }; + app.linked_design_clipboard = None; let n = out.get("curves").and_then(Value::as_u64).unwrap_or(0) + out.get("points").and_then(Value::as_u64).unwrap_or(0); let k = out.get("constraints").and_then(Value::as_u64).unwrap_or(0); let text = format!("SolidCraft sketch geometry: {n} entities, {k} constraints and dimensions"); @@ -72,6 +96,7 @@ pub fn copy(app: &mut SolveApp) -> bool { return false; } let Ok(out) = app.run("timeline.copy", json!({ "features": features })) else { return false }; + app.linked_design_clipboard = None; let names: Vec<&str> = out.get("copied").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default(); app.set_status(format!("Copied {}", names.join(", ")), false); leave_text(format!("SolidCraft features: {}", names.join(", "))); @@ -90,6 +115,7 @@ pub fn cut(app: &mut SolveApp) -> bool { return false; } let Ok(out) = app.run("sketch.cut", json!({ "entities": entities })) else { return false }; + app.linked_design_clipboard = None; let n = out.get("curves").and_then(Value::as_u64).unwrap_or(0) + out.get("points").and_then(Value::as_u64).unwrap_or(0); app.set_status(format!("Cut {n} sketch entities"), false); leave_text(format!("SolidCraft sketch geometry: {n} entities")); @@ -125,6 +151,19 @@ pub fn paste(app: &mut SolveApp, at: Option) -> bool { app.set_status(format!("Pasted {n} sketch entities (selected: drag them, or press M to move them)"), false); return true; } + if let Some(path) = app.linked_design_clipboard.clone() { + let (parent_path, translate) = paste_placement(app, at); + let Ok(out) = app.run("component.insert_design", json!({"path": path, "reuse": true, "translate":translate})) else { return false }; + if let Some(id) = out.get("occurrence").and_then(Value::as_u64) { + let mut movement = crate::browser::OccMove::new(id); + movement.path = parent_path; + movement.path.push(id); + movement.baseline = app.session.doc.occurrences.iter().find(|o| o.id == id).map(|o| o.transform); + app.tree.occurrence_move = Some(movement); + } + app.set_status("Pasted linked component: use Move/Copy to position it", false); + return true; + } if app.session.clipboard.is_empty() { app.set_status("Nothing to paste: copy timeline features first", true); return false; @@ -132,6 +171,38 @@ pub fn paste(app: &mut SolveApp, at: Option) -> bool { app.run("timeline.paste", json!({})).is_ok() } +/// Place the copied design's origin on the pointed solid surface, otherwise its parent's +/// XY plane. With no viewport point or a parallel/behind-camera ray, use the parent origin. +fn paste_placement(app: &SolveApp, at: Option) -> (Vec, [f64; 3]) { + use solidcraft_engine::{doc, geom::Vec3}; + let path = app.session.active_occurrence_path.clone().unwrap_or_else(|| app.session.doc.first_path(app.session.active_component)); + let frame = app.session.occurrence_placement(&path).map(|p| p.world).unwrap_or(doc::IDENTITY); + let origin = doc::apply_point(&frame, Vec3::ZERO); + let at = at.zip(app.viewport.rect).filter(|(point, rect)| rect.contains(*point)); + let point = at + .and_then(|(at, rect)| { + let projection = crate::viewport::projection(app, rect); + if let Some(point) = crate::viewport::pick_all(app, &projection, at).into_iter().find_map(|hit| match hit { + crate::viewport::Hit::Face { point, .. } => Some(point), + _ => None, + }) { + return point.is_finite().then_some(point); + } + let (ray_origin, ray_direction) = projection.ray(at); + let normal = doc::apply_vector(&frame, Vec3::Z); + let denominator = ray_direction.dot(normal); + if denominator.abs() < 1e-9 { + return None; + } + let distance = (origin - ray_origin).dot(normal) / denominator; + let point = ray_origin + ray_direction * distance; + (distance >= 0.0 && point.is_finite()).then_some(point) + }) + .unwrap_or(origin); + let local = doc::mat_inverse(&frame).map(|inverse| doc::apply_point(&inverse, point)).filter(|p| p.is_finite()).unwrap_or(Vec3::ZERO); + (path, [local.x, local.y, local.z]) +} + /// The frame's Copy, Cut and Paste events (and Ctrl+C / Ctrl+X / Ctrl+V sent as key presses), plus any /// clipboard text a menu's Copy left. Called by the global shortcuts when no text field has the /// keyboard. diff --git a/crates/ui-egui/src/edit_clipboard_tests.rs b/crates/ui-egui/src/edit_clipboard_tests.rs index b0967aaf3..a12d571a7 100644 --- a/crates/ui-egui/src/edit_clipboard_tests.rs +++ b/crates/ui-egui/src/edit_clipboard_tests.rs @@ -162,3 +162,185 @@ fn ctrl_x_cuts_the_sketch_selection_and_ctrl_v_brings_it_back() { let labels: Vec<&str> = menu["result"]["items"].as_array().unwrap().iter().filter_map(|i| i["label"].as_str()).collect(); assert!(labels.contains(&"Cut"), "{labels:?}"); } + +struct ContributionPart(std::path::PathBuf); +impl ContributionPart { + fn new() -> Self { + let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + Self(std::env::temp_dir().join(format!("solidcraft-linked-clipboard-{}-{stamp}.solidcraft", std::process::id()))) + } +} +impl Drop for ContributionPart { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } +} +fn contribution_saved_part(file: &ContributionPart) -> crate::SolveApp { + let mut app = crate::SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + app.run("solid.box", json!({"length":20,"width":10,"height":5,"body_name":"Plate"})).unwrap(); + app.run("file.save", json!({"path":file.0.to_string_lossy()})).unwrap(); + app.tree.picked_components = vec![0]; + app +} + +#[test] +fn contribution_linked_design_clipboard_crosses_tabs_reuses_links_and_undoes_once() { + let file = ContributionPart::new(); + let mut app = contribution_saved_part(&file); + assert!(super::can_copy(&app)); + assert!(super::copy(&mut app)); + crate::documents::open_tab(&mut app, solidcraft_engine::Session::default()).unwrap(); + assert!(super::can_paste(&app)); + for n in 1..=2 { + assert!(super::paste(&mut app, None), "{:?}", app.status); + assert_eq!(app.session.doc.components.len(), 1); + assert_eq!(app.session.doc.links.len(), 1); + assert_eq!(app.session.doc.features.len(), 1); + assert_eq!(app.session.doc.occurrences.len(), n); + assert_eq!(app.session.undo.len(), n); + assert!(app.session.doc.occurrences.iter().all(|o| !o.grounded)); + assert!(app.tree.occurrence_move.is_some()); + } + app.tree.occurrence_move = None; + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.doc.occurrences.len(), 1); + app.run("edit.undo", json!({})).unwrap(); + assert!(app.session.doc.links.is_empty()); + assert!(app.session.doc.components.is_empty()); + app.run("edit.redo", json!({})).unwrap(); + assert_eq!(app.session.doc.links.len(), 1); + crate::documents::switch(&mut app, 0); + assert_eq!(app.session.doc.features.len(), 1, "the source is untouched"); +} + +#[test] +fn contribution_occurrence_move_panel_belongs_to_its_document() { + let file = ContributionPart::new(); + let mut app = contribution_saved_part(&file); + assert!(super::copy(&mut app)); + crate::documents::open_tab(&mut app, solidcraft_engine::Session::default()).unwrap(); + assert!(super::paste(&mut app, None)); + let id = app.tree.occurrence_move.as_ref().unwrap().occurrence; + app.run("occurrence.move", json!({"occurrence":id,"translate":[10,0,0],"capture":false})).unwrap(); + let pending = app.session.pending_moves.clone(); + crate::documents::switch(&mut app, 0); + assert!(app.tree.occurrence_move.is_none()); + assert!(app.session.doc.occurrences.is_empty()); + crate::documents::switch(&mut app, 1); + assert_eq!(app.tree.occurrence_move.as_ref().unwrap().occurrence, id); + assert_eq!(app.session.pending_moves, pending); +} + +#[test] +fn contribution_linked_paste_uses_the_pointer_and_pending_numeric_move() { + use solidcraft_engine::geom::Vec3; + let file = ContributionPart::new(); + let mut h = crate::scenario::Harness::new(); + h.app = contribution_saved_part(&file); + assert!(super::copy(&mut h.app)); + crate::documents::open_tab(&mut h.app, solidcraft_engine::Session::default()).unwrap(); + h.app.run("solid.box", json!({"length":80,"width":50,"height":8,"body_name":"Destination"})).unwrap(); + h.app.fit_view(); + h.frames(3); + let projection = crate::viewport::projection(&h.app, h.app.viewport.rect.unwrap()); + let pointed = Vec3::new(40., 25., 8.); + let at = projection.to_screen(pointed).unwrap(); + let undo = h.app.session.undo.len(); + assert!(super::paste(&mut h.app, Some(at))); + h.frames(3); + let path = h.app.tree.occurrence_move.as_ref().unwrap().path.clone(); + let initial = solidcraft_engine::doc::apply_point(&h.app.session.occurrence_placement(&path).unwrap().world, Vec3::ZERO); + assert!((initial - pointed).len() < 1e-5, "{initial:?}"); + assert_eq!(h.app.session.undo.len(), undo + 1); + let camera = h.app.cam; + let field = h.call("ui.at", json!({"handle":"occurrence-move:distance:0"})); + h.call("ui.click", json!({"x":field["result"][0],"y":field["result"][1],"double":true})); + h.frames(2); + h.step(&json!({"key":"A","cmd":true})).unwrap(); + h.step(&json!({"text":"12"})).unwrap(); + h.step(&json!({"key":"Enter"})).unwrap(); + h.frames(3); + let moved = solidcraft_engine::doc::apply_point(&h.app.session.occurrence_placement(&path).unwrap().world, Vec3::ZERO); + assert!(moved.x > initial.x + 10., "numeric move must retain the pasted occurrence: {initial:?} -> {moved:?}"); + assert_eq!(h.app.cam, camera, "numeric editing does not move the camera"); + let movement = h.app.tree.occurrence_move.as_ref().unwrap(); + assert!((movement.translate[0] - (moved.x - initial.x)).abs() < 1e-5); + assert_eq!(h.app.session.undo.len(), undo + 1, "pending movement does not split the initial paste undo"); + h.app.run("edit.undo", json!({})).unwrap(); + h.frames(3); + assert!(h.app.session.doc.links.is_empty()); + assert!(h.app.tree.occurrence_move.is_none()); + crate::documents::switch(&mut h.app, 0); + assert_eq!(h.app.session.doc.features.len(), 1, "source geometry stays untouched"); +} + +#[test] +fn contribution_paste_pointer_uses_parent_coordinates_and_safe_fallbacks() { + use solidcraft_engine::{doc, geom::Vec3}; + let mut h = crate::scenario::Harness::new(); + let parent = h.app.run("component.create", json!({"name":"Parent"})).unwrap(); + h.app + .run("occurrence.move", json!({"occurrence":parent["occurrence"],"translate":[20,30,10],"axis":[1,0,0],"angle":"45 deg","capture":true})) + .unwrap(); + h.frames(3); + let path = vec![parent["occurrence"].as_u64().unwrap()]; + h.app.run("component.activate", json!({"component":parent["component"],"occurrence":parent["occurrence"],"path":path})).unwrap(); + let (actual, zero) = super::paste_placement(&h.app, None); + assert_eq!(actual, path); + assert_eq!(zero, [0.; 3]); + assert_eq!(super::paste_placement(&h.app, Some(egui::pos2(-100., -100.))).1, [0.; 3]); + let frame = h.app.session.occurrence_placement(&path).unwrap().world; + let target = doc::apply_point(&frame, Vec3::new(5., 7., 0.)); + h.app.cam.target = target; + h.app.cam.distance = 100.; + h.frames(2); + let projection = crate::viewport::projection(&h.app, h.app.viewport.rect.unwrap()); + let at = projection.to_screen(target).unwrap(); + let (_, local) = super::paste_placement(&h.app, Some(at)); + assert!((Vec3::new(local[0], local[1], local[2]) - Vec3::new(5., 7., 0.)).len() < 1e-5, "{local:?}"); +} + +#[test] +fn contribution_linked_clipboard_refuses_unsaved_dirty_self_and_missing_sources() { + let file = ContributionPart::new(); + let mut app = crate::SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + assert!(!super::copy_design(&mut app)); + app = contribution_saved_part(&file); + assert!(super::copy_design(&mut app)); + let doc = app.session.doc.clone(); + assert!(!super::paste(&mut app, None)); + assert_eq!(app.session.doc, doc); + app.run("solid.box", json!({"length":2,"width":2,"height":2,"corner":[30,0,0]})).unwrap(); + assert!(!super::copy_design(&mut app)); + crate::documents::open_tab(&mut app, solidcraft_engine::Session::default()).unwrap(); + std::fs::remove_file(&file.0).unwrap(); + assert!(!super::paste(&mut app, None)); + assert!(app.session.doc.features.is_empty()); + assert!(app.session.undo.is_empty()); +} + +#[test] +fn contribution_feature_copy_replaces_the_linked_design_clipboard() { + let file = ContributionPart::new(); + let mut app = contribution_saved_part(&file); + assert!(super::copy(&mut app)); + app.tree.picked_components.clear(); + app.session.selection = vec![Sel::Feature { id: app.session.doc.features[0].id }]; + assert!(super::copy(&mut app)); + assert!(app.linked_design_clipboard.is_none()); + assert!(!app.session.clipboard.is_empty()); +} + +#[test] +fn contribution_native_copy_paste_events_insert_the_saved_design_in_another_tab() { + let file = ContributionPart::new(); + let mut h = Harness::new(); + h.app = contribution_saved_part(&file); + h.frames(3); + clipboard_event(&mut h, egui::Event::Copy, None); + assert!(h.app.linked_design_clipboard.is_some()); + crate::documents::open_tab(&mut h.app, solidcraft_engine::Session::default()).unwrap(); + clipboard_event(&mut h, egui::Event::Paste("SolidCraft linked design".into()), None); + assert_eq!(h.app.session.doc.links.len(), 1, "{:?}", h.app.status); + assert_eq!(h.app.session.undo.len(), 1); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 37a7b1d6e..9b17c23ca 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -327,6 +327,8 @@ pub struct SolveApp { pub menu: context_menu::MenuState, /// Browser tree state (reveal, groups being edited, occurrence moves). pub tree: browser::TreeState, + /// A saved design copied for insertion into another open document. + pub linked_design_clipboard: Option, /// The S box (command search at the cursor): recent and pinned commands. pub sbox: shortcut_box::ShortcutBox, /// Keyboard shortcuts the user changed. @@ -461,6 +463,7 @@ impl SolveApp { palette: palette::Palette::default(), menu: context_menu::MenuState::default(), tree: browser::TreeState::default(), + linked_design_clipboard: None, sbox: shortcut_box::ShortcutBox::default(), keymap: keymap::Keymap::default(), help: help::HelpState::default(), diff --git a/docs/linked-design-paste.md b/docs/linked-design-paste.md new file mode 100644 index 000000000..30cc690e1 --- /dev/null +++ b/docs/linked-design-paste.md @@ -0,0 +1,9 @@ +# Pasting a linked design + +Save the source design without pending changes, select its root in the Browser and copy it. Switch to the destination document and paste. The result is an ungrounded occurrence linked to the saved source; repeated pastes reuse that component definition. The source design is not modified. + +The copied design's origin is placed on the solid surface under the viewport pointer. Over empty space, the view ray is intersected with the active parent component's XY plane. If there is no viewport pointer, or that ray is parallel, behind the camera or invalid, placement uses the parent origin. World points are converted into the parent's coordinates, including a rotated or nested parent. Keyboard and viewport context-menu paste use this same rule. + +Initial placement is part of the paste's single undo step. Move/Copy numeric fields adjust pending distances and angles after insertion. Capture All Positions and Revert All Positions retain their existing pending-position behavior. A document's Move/Copy context stays with its own tab. + +The pre-existing occurrence arrow input repair is proposed separately in #3015 (issue #3014). Pointer placement does not include or duplicate that shared viewport patch. Combined trials include both changes; this clipboard PR remains independently scoped. From 26dd2548b718b310ea29bef996588ef93dc0f971 Mon Sep 17 00:00:00 2001 From: Colin Faulkingham Date: Mon, 19 Oct 2026 23:57:03 +0000 Subject: [PATCH 151/225] Preview modeled threads using the desktop background worker (#2264) Co-authored-by: bherbruck --- ROADMAP.md | 3 ++ crates/ui-egui/src/dialogs.rs | 2 + crates/ui-egui/src/preselect_tests.rs | 66 +++++++++++++++++++++++++-- 3 files changed, 68 insertions(+), 3 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index c0739fc14..b6268cd7c 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -89,6 +89,9 @@ completed drawings publish atomically. The browser still exports synchronously. ## Interactive modelling +- Modelled threads preview their cut before OK using the background worker on desktop. + Browser users apply the cut with OK to avoid blocking on every edit. + - Thread resolves a suggested metric size when a cylindrical face is picked. Diameter and pitch selectors expose the existing metric designation parameter; custom designations stay editable, and Automatic size returns to the face's suggestion. Cosmetic/modelled and diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 531694cbc..87538992e 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -857,6 +857,8 @@ impl Dialog { Kind::SketchModify(k) => return k.previews(), Kind::Plastic(k) => return k.previews(), Kind::Part(_) | Kind::PartSize(_) => return true, + // Web previews run synchronously; a modelled thread can take seconds. + Kind::Thread { .. } => return !cfg!(target_arch = "wasm32") && self.extra.get("modeled").and_then(Value::as_bool).unwrap_or(false), _ => {} } matches!( diff --git a/crates/ui-egui/src/preselect_tests.rs b/crates/ui-egui/src/preselect_tests.rs index 033a1f9a9..c1d0a8af8 100644 --- a/crates/ui-egui/src/preselect_tests.rs +++ b/crates/ui-egui/src/preselect_tests.rs @@ -127,15 +127,26 @@ fn feature_pattern_controls_preview_without_committing_and_cancel_cleanly() { } } +#[track_caller] fn wait_feature_preview(h: &mut crate::scenario::Harness) { - for _ in 0..300 { + // A large faceted thread can outlive 300 UI frames on a busy CI host. This checks + // completion, not preview speed; use a bounded wall-clock wait for the worker. + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120); + while std::time::Instant::now() < deadline { h.frames(2); - if h.app.preview.active && !h.app.preview.busy { + if !h.app.preview.busy && (h.app.preview.active || h.app.preview.error.is_some()) { break; } std::thread::sleep(std::time::Duration::from_millis(10)); } - assert!(h.app.preview.active && !h.app.preview.busy, "preview failed: {:?}", h.app.preview.error); + assert!( + h.app.preview.active && !h.app.preview.busy, + "preview failed: active={} busy={} error={:?} dialog={:?}", + h.app.preview.active, + h.app.preview.busy, + h.app.preview.error, + h.app.dialog + ); assert!(h.app.preview.error.is_none()); } @@ -1270,6 +1281,55 @@ fn thread_choices_can_start_without_a_face_and_recover_from_invalid_text() { assert!(apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).is_err(), "a face is still required"); } +#[test] +fn modelled_thread_preview_updates_reports_errors_and_cancels_without_changes() { + fn designation(h: &mut crate::scenario::Harness, text: &str) { + h.step(&json!({"click":{"handle":"dialog:thread_size"}})).unwrap(); + h.step(&json!({"key":"A","cmd":true})).unwrap(); + h.step(&json!({"text":text})).unwrap(); + } + let mut h = crate::scenario::Harness::new(); + h.app.run("solid.cylinder", json!({"radius":4,"height":2})).unwrap(); + let saved = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + h.app.session.selection = vec![thread_face(&h.app, "Body1")]; + h.step(&json!({"start":"solid.thread"})).unwrap(); + designation(&mut h, "M8x1"); + h.step(&json!({"click":{"handle":"dialog:Modeled"}})).unwrap(); + assert_eq!(h.app.dialog.as_ref().unwrap().extra.get("modeled"), Some(&json!(true)), "{:?}", h.app.dialog); + assert!(crate::dialogs::preview_commands(&h.app, h.app.dialog.as_ref().unwrap()).is_ok(), "{:?}", h.app.dialog); + wait_feature_preview(&mut h); + assert_eq!(h.app.preview.replaced, ["Body1"]); + let first_key = h.app.preview.key; + designation(&mut h, "M8x1.3"); + wait_feature_preview(&mut h); + assert_ne!(h.app.preview.key, first_key, "changing pitch updates the preview before OK"); + designation(&mut h, "M6x1.3"); + for _ in 0..500 { + h.frames(2); + if !h.app.preview.busy && h.app.preview.error.is_some() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + } + 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"); + wait_feature_preview(&mut h); + assert!(h.app.preview.error.is_none()); + assert_eq!(h.app.session.doc.to_json(), saved); + assert_eq!(h.app.session.undo.len(), undo); + h.step(&json!({"click":{"handle":"dialog:Modeled"}})).unwrap(); + h.frames(2); + assert!(!h.app.preview.active && h.app.preview.replaced.is_empty(), "cosmetic threads leave the original body visible"); + h.step(&json!({"click":{"handle":"dialog:Modeled"}})).unwrap(); + wait_feature_preview(&mut h); + h.step(&json!({"key":"Escape"})).unwrap(); + h.frames(2); + assert!(h.app.dialog.is_none() && !h.app.preview.active && h.app.preview.replaced.is_empty()); + assert_eq!(h.app.session.doc.to_json(), saved); + assert_eq!(h.app.session.undo.len(), undo); +} + #[test] fn newer_options_reach_their_commands() { let mut app = boxed(); From 3ffd8efffc877397290f9032ae121f704bb70110 Mon Sep 17 00:00:00 2001 From: fkirill Date: Mon, 19 Oct 2026 23:57:07 +0000 Subject: [PATCH 152/225] Loft: preserve holes through matching sketch sections (#2435) (#2447) Rebase the complete PR change onto current main, preserving changes previously stored in merge commits. --- ROADMAP.md | 4 +- crates/doc/src/eval.rs | 16 ++- crates/doc/src/eval_surface.rs | 2 +- crates/doc/src/lineage.rs | 15 ++- crates/engine/src/cmd/features.rs | 2 +- crates/engine/src/tests/loft_ring.rs | 70 ++++++++++-- crates/kernel/src/build.rs | 146 ++++++++++++++++++++++++- crates/kernel/src/lib.rs | 4 +- crates/kernel/src/loft_region_tests.rs | 121 ++++++++++++++++++++ examples/regressions/loft_rings.json | 100 +++++++++++++++++ 10 files changed, 449 insertions(+), 31 deletions(-) create mode 100644 crates/kernel/src/loft_region_tests.rs create mode 100644 examples/regressions/loft_rings.json diff --git a/ROADMAP.md b/ROADMAP.md index b6268cd7c..02ae22f30 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -466,7 +466,9 @@ completed drawings publish atomically. The browser still exports synchronously. filleted boxes, bosses, domes, countersinks; corners where four or more planes meet, such as a floor falling to a drain, as long as the corner's edges are all convex or all concave); draft on convex planar bodies and on walls (planes, cylinders → cones) between caps; lofts through three or more sections are smooth (B-spline sides through every section), two sections ruled. Circular-meridian barrels retain curved inner walls through either axial - opening (#2421). + opening (#2421). Solid lofts preserve holes through sections with matching hole counts + (#2435), including inner walls and caps with openings; a hole cannot appear or disappear + between sections, and sections with holes cannot collapse to a point. - Sketch corner tools: fillet and all three chamfer modes pick a connected corner even when its endpoint overlaps the fixed origin or a loose point. Ordinary drawing still snaps to diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 6af265511..0167c1825 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -1472,15 +1472,12 @@ pub(crate) fn val(vals: &BTreeMap, e: &str, k: Kind) -> Result Result<()> { if r.holes.is_empty() { return Ok(()); } - Err(DocError::Invalid( - "not supported yet: a loft section with a hole; loft the outline and the hole as two bodies and cut one from the other".into(), - )) + Err(DocError::Invalid("not supported yet: lofting a section with holes to a point".into())) } pub fn select_profiles(ss: &SolvedSketch, sel: &ProfileSel) -> Result> { @@ -3808,14 +3805,15 @@ fn feature_tools_with_constructor( .ok_or_else(|| DocError::Unknown(format!("sketch {} (it must come earlier in the timeline)", sec.sketch)))?; let regions = solidcraft_sketch::merge_regions(&select_profiles(ss, &sec.profiles)?); let [r] = ®ions[..] else { return Err(DocError::Invalid("each loft section must be one profile".into())) }; - refuse_loft_holes(r)?; - secs.push((ss.plane, r.outer.clone())); + secs.push((ss.plane, r.clone())); sketches.push(ss); } // Its caps are the first and last sections, its sides named by the curves they run // between. - let body = kernel::loft(&secs)?; - let roles = crate::lineage::SectionRoles { sections: sketches.into_iter().zip(secs.iter().map(|(_, lp)| lp)).collect() }; + let body = kernel::loft_regions(&secs)?; + let roles = crate::lineage::SectionRoles { + sections: sketches.into_iter().zip(secs.iter().map(|(_, r)| std::iter::once(&r.outer).chain(&r.holes).collect())).collect(), + }; Ok(vec![roles.tool(body)]) } FeatureKind::Sweep { sketch, profiles, path_sketch, path, orientation, twist, scale, rails, rail_fit, .. } => { diff --git a/crates/doc/src/eval_surface.rs b/crates/doc/src/eval_surface.rs index b59d557fc..c8c3145fb 100644 --- a/crates/doc/src/eval_surface.rs +++ b/crates/doc/src/eval_surface.rs @@ -420,7 +420,7 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, let body = kernel::loft_sheet(&secs)?; // Each wall named by the section curves it runs between, as a loft's sides are. let loops: Vec = secs.iter().map(|(_, c)| solidcraft_geom::Loop2 { segs: c.clone() }).collect(); - let traced = crate::lineage::SectionRoles { sections: sketches.iter().zip(&loops).collect() }.tool(body); + let traced = crate::lineage::SectionRoles { sections: sketches.iter().zip(&loops).map(|(s, lp)| (s, vec![lp])).collect() }.tool(body); push_sheet(st, f, traced); Ok(()) } diff --git a/crates/doc/src/lineage.rs b/crates/doc/src/lineage.rs index d55f7c57e..ce548df89 100644 --- a/crates/doc/src/lineage.rs +++ b/crates/doc/src/lineage.rs @@ -302,8 +302,8 @@ impl ChainRoles<'_> { /// the section with the most segments (the one each side spans exactly one segment of) and /// answering to the others; its caps `start` and `end`. pub(crate) struct SectionRoles<'a> { - /// Each section's sketch and the loop lofted through it, in the order given. - pub sections: Vec<(&'a SolvedSketch, &'a solidcraft_geom::Loop2)>, + /// Each section's sketch and loops (outer, then holes), in the order given. + pub sections: Vec<(&'a SolvedSketch, Vec<&'a solidcraft_geom::Loop2>)>, } impl SectionRoles<'_> { @@ -316,14 +316,19 @@ impl SectionRoles<'_> { fn of(&self, history: &History) -> Vec> { // Each profile segment (numbered through the sections in order): its section and role. let mut segments: Vec<(usize, Option)> = Vec::new(); - for (k, (sketch, lp)) in self.sections.iter().enumerate() { + for (k, (sketch, loops)) in self.sections.iter().enumerate() { let curves = crate::config::ExactSketchCurves::new(sketch); - for seg in &lp.segs { + for seg in loops.iter().flat_map(|lp| &lp.segs) { let role = curves.find_along(seg).map(|id| if k == 0 { format!("side:{id}") } else { format!("side:s{k}.{id}") }); segments.push((k, role)); } } - let lead = self.sections.iter().enumerate().max_by_key(|(k, (_, lp))| (lp.segs.len(), std::cmp::Reverse(*k))).map_or(0, |(k, _)| k); + let lead = self + .sections + .iter() + .enumerate() + .max_by_key(|(k, (_, loops))| (loops.iter().map(|lp| lp.segs.len()).sum::(), std::cmp::Reverse(*k))) + .map_or(0, |(k, _)| k); history .faces .iter() diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs index 1b517e1a1..bfe0f3c91 100644 --- a/crates/engine/src/cmd/features.rs +++ b/crates/engine/src/cmd/features.rs @@ -27,7 +27,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .at("SOLID", "CREATE") .icon("sweep") .params("sketch: profile sketch; profiles?; path_sketch: sketch; path: [curve ids in order]; orientation?: perpendicular (default: square to the path, turning with it) | parallel (as drawn: the profile moves without turning; the path must keep crossing its plane) | [x,y,z] (square to the path, its turn about the path fixed by this direction); twist?: angle expr (the profile turns this much about the path over its length; within 4 turns); scale?: expr (the profile's scale at the end, linear along the path; 0.01…100); rails?: [{sketch?: sketch (default path_sketch), curves: [curve ids in order]}] (guide rails, one or two, each meeting every plane square to the path once along it, from the end nearest the path's start: one rail turns the profile so its point where the rail starts stays on the rail and scales it with the rail's distance from the path; two rails carry it between them, its points where they start staying on both; rails take the default orientation, no twist and no scale, and a path without sharp corners); rail_fit?: scale (default: the profile grows and shrinks evenly) | stretch (only across to the rail, between the rails); operation?, targets?, name?, body_name?"), - CommandSpec::new("solid.loft", "Loft", loft).at("SOLID", "CREATE").icon("loft").params("sections: [{sketch, profiles?} | {sketch, point: id} (an apex)] (2 or more, in order); operation?, targets?, name?, body_name?"), + CommandSpec::new("solid.loft", "Loft", loft).at("SOLID", "CREATE").icon("loft").params("sections: [{sketch, profiles?} | {sketch, point: id} (an apex)] (2…50, in order; matching hole counts, no holes at an apex); operation?, targets?, name?, body_name?"), CommandSpec::new("solid.box", "Box", prim_box).at("SOLID", "CREATE").icon("box").params("length, width, height: expr; corner?: [x,y,z] | center?: [x,y,z] (numbers in mm or length expressions; default: the origin); operation?, targets?: [body], name?, body_name?"), CommandSpec::new("solid.cylinder", "Cylinder", prim_cylinder).at("SOLID", "CREATE").icon("cylinder").params("radius | diameter, height: expr; base?: [x,y,z] (centre of the bottom: numbers in mm or length expressions; default: the origin); axis?: X|Y|Z|[x,y,z] (default Z); operation?, targets?: [body], name?, body_name?"), CommandSpec::new("solid.sphere", "Sphere", prim_sphere).at("SOLID", "CREATE").icon("sphere").params("radius | diameter: expr; center?: [x,y,z] (numbers in mm or length expressions; default: the origin); operation?, targets?: [body], name?, body_name?"), diff --git a/crates/engine/src/tests/loft_ring.rs b/crates/engine/src/tests/loft_ring.rs index 723714eac..8438829da 100644 --- a/crates/engine/src/tests/loft_ring.rs +++ b/crates/engine/src/tests/loft_ring.rs @@ -1,5 +1,5 @@ -//! A loft section that is a ring (a profile with a hole) is refused (#1184): the loft builds each -//! section from its outline, so it used to fill the hole and report success. +//! A loft section that is a ring keeps its passage (#2435); incompatible sections +//! are refused atomically rather than silently filling the hole (#1184). use super::*; @@ -11,24 +11,42 @@ fn ring(s: &mut Session, name: &str, z: f64) { run(s, "sketch.finish", json!({})); } -fn refused(s: &mut Session, sections: Value) { +fn refused(s: &mut Session, sections: Value, message: &str) { let saved = s.doc.to_json(); let err = s.execute("solid.loft", &json!({"sections": sections, "operation": "new"})).err().map(|e| e.to_string()); - assert!(err.as_deref().is_some_and(|e| e.contains("not supported yet: a loft section with a hole")), "{err:?}"); + assert!(err.as_deref().is_some_and(|e| e.contains(message)), "{err:?}"); assert_eq!(s.doc.to_json(), saved); } #[test] -fn a_ring_section_is_refused_not_filled() { +fn a_ring_section_keeps_its_hole_and_rejects_a_disc() { let mut s = Session::default(); ring(&mut s, "A", 0.0); ring(&mut s, "B", 20.0); let ring_at = |n: &str| json!({"sketch": n, "profiles": [{"point": [16, 0]}]}); - refused(&mut s, json!([ring_at("A"), ring_at("B")])); + let sections = json!([ring_at("A"), ring_at("B")]); + run(&mut s, "solid.loft", json!({"sections": sections, "operation": "new"})); + let want = PI * (400.0 - 144.0) * 20.0; + assert!(rel(volume(&mut s), want) < 1e-3); + let reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); + assert!(reopened.model.results.iter().all(|r| r.error.is_none())); + let st = reopened.model.state(); + let body = &st.bodies[0]; + assert!(body.body.validity().is_empty()); + assert_eq!(body.body.shell_count(), 1); + for face in 0..body.body.face_count() { + assert!(solidcraft_doc::naming::face_name_exact(body, face), "face {face} lost its sketch-curve provenance"); + } + assert!(!body.body.tessellate(0.001).unwrap().contains(solidcraft_geom::Vec3::new(0.0, 0.0, 10.0))); + run(&mut s, "edit.undo", json!({})); + assert!(s.model.state().bodies.is_empty()); + run(&mut s, "edit.redo", json!({})); + assert!(rel(volume(&mut s), want) < 1e-3); + run(&mut s, "edit.undo", json!({})); // A ring and a plain disc, in either order. let disc_b = json!({"sketch": "B", "profiles": [{"point": [0, 0]}]}); - refused(&mut s, json!([ring_at("A"), disc_b])); - refused(&mut s, json!([disc_b, ring_at("A")])); + refused(&mut s, json!([ring_at("A"), disc_b]), "same number of holes"); + refused(&mut s, json!([disc_b, ring_at("A")]), "same number of holes"); // The discs inside the holes still loft into a cylinder of radius 12. run(&mut s, "solid.loft", json!({"sections": [{"sketch": "A", "profiles": [{"point": [0, 0]}]}, disc_b], "operation": "new"})); let want = std::f64::consts::PI * 12.0 * 12.0 * 20.0; @@ -47,5 +65,39 @@ fn a_ring_lofted_to_a_point_is_refused() { run(&mut s, "sketch.create", json!({"plane": "XY", "offset": 20, "name": "Top"})); run(&mut s, "sketch.point", json!({"point": [0, 0], "id": "apex"})); run(&mut s, "sketch.finish", json!({})); - refused(&mut s, json!([{"sketch": "A", "profiles": [{"point": [16, 0]}]}, {"sketch": "Top", "point": "apex"}])); + refused( + &mut s, + json!([{"sketch": "A", "profiles": [{"point": [16, 0]}]}, {"sketch": "Top", "point": "apex"}]), + "lofting a section with holes to a point", + ); +} + +#[test] +fn a_ring_loft_joins_cuts_and_intersects_without_filling_the_hole() { + for operation in ["join", "cut", "intersect"] { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 50, "width": 50, "height": 10, "corner": [-25, -25, -5]})); + ring(&mut s, "A", 0.0); + ring(&mut s, "B", 20.0); + let sections = json!([{"sketch": "A", "profiles": [{"point": [16, 0]}]}, {"sketch": "B", "profiles": [{"point": [16, 0]}]}]); + run(&mut s, "solid.loft", json!({"sections": sections, "operation": operation})); + let area = PI * (400.0 - 144.0); + let want = match operation { + "join" => 25000.0 + area * 15.0, + "cut" => 25000.0 - area * 5.0, + _ => area * 5.0, + }; + assert!(rel(volume(&mut s), want) < 1e-3, "{operation}"); + for b in &s.model.state().bodies { + assert!(b.body.validity().is_empty(), "{operation}: {:?}", b.body.validity()); + } + } +} + +#[test] +fn tapered_ring_loft_reproduction() { + let mut s = Session::default(); + s.run_script(&serde_json::from_str(include_str!("../../../../examples/regressions/loft_rings.json")).unwrap()).unwrap(); + let want = PI * 30.0 / 3.0 * ((400.0 + 280.0 + 196.0) - (144.0 + 96.0 + 64.0)); + assert!(rel(volume(&mut s), want) < 1e-3); } diff --git a/crates/kernel/src/build.rs b/crates/kernel/src/build.rs index 7d306b371..a1c097df6 100644 --- a/crates/kernel/src/build.rs +++ b/crates/kernel/src/build.rs @@ -1816,10 +1816,135 @@ pub fn loft(sections: &[(Plane, Loop2)]) -> Result { }) } +/// A loft through regions with matching hole counts. Hole walls are built alongside the +/// outline and share the end caps, so the result is one shell with open passages. +/// Holes are paired by their positions relative to the outline, independently of sketch +/// curve order. A hole cannot appear or disappear partway through a loft. +pub fn loft_regions(sections: &[(Plane, Region2)]) -> Result { + if !(2..=50).contains(§ions.len()) { + return Err(KernelError::Invalid("a loft needs 2…50 sections".into())); + } + let holes = sections.first().map_or(0, |(_, r)| r.holes.len()); + if sections.iter().any(|(_, r)| r.holes.len() != holes) { + return Err(KernelError::Invalid("every loft section must have the same number of holes".into())); + } + // Bound the quadratic matching work as well as the geometry built per section. + if holes > 128 || sections.iter().any(|(_, r)| numbered::profile_loops(std::slice::from_ref(r)).map(|l| l.segs.len()).sum::() > MAX_SEGS) { + return Err(KernelError::Invalid("too many loops or segments in a loft section".into())); + } + for (_, r) in sections { + region_ok(r)?; + } + if holes == 0 { + return loft(§ions.iter().map(|(p, r)| (*p, r.outer.clone())).collect::>()); + } + let regions: Vec = sections.iter().map(|(_, r)| r.clone()).collect(); + let mut numbered = numbered::number_regions(®ions); + let outlines: Vec<_> = sections.iter().map(|(p, _)| *p).zip(numbered.iter().map(|r| r.outer.clone())).collect(); + let reversed = loft_reversed(§ions.iter().map(|(p, r)| (*p, r.outer.clone())).collect::>())?; + // Match in canonical section order, so reversing the input cannot change the pairing. + if reversed { + numbered.reverse(); + } + let planes: Vec<_> = if reversed { sections.iter().rev().map(|(p, _)| *p).collect() } else { sections.iter().map(|(p, _)| *p).collect() }; + let mut previous: Vec = Vec::new(); + for (p, r) in planes.iter().zip(&mut numbered) { + let centre = r.outer.lp.centroid(); + let scale = r.outer.lp.signed_area().abs().sqrt().max(1e-9); + let position = |l: &NumberedLoop| { + let d = l.lp.centroid() - centre; + (p.x * d.x + p.y * d.y) * (1.0 / scale) + }; + if !previous.is_empty() { + let positions: Vec<_> = r.holes.iter().map(position).collect(); + let mut used = vec![false; positions.len()]; + let mut order = Vec::new(); + for point in &previous { + let (k, distance) = positions + .iter() + .enumerate() + .map(|(k, p)| (k, p.dist(*point))) + .min_by(|(_, a), (_, b)| a.total_cmp(b)) + .ok_or_else(|| KernelError::Invalid("missing loft hole".into()))?; + let occupied = used.get_mut(k).ok_or_else(|| KernelError::Invalid("missing loft hole".into()))?; + if *occupied + || !distance.is_finite() + || positions.iter().enumerate().any(|(j, p)| j != k && (p.dist(*point) - distance).abs() <= 1e-9) + { + return Err(KernelError::Invalid("loft hole correspondence is ambiguous; each hole needs a unique nearest match".into())); + } + *occupied = true; + order.push(k); + } + let mut remaining: Vec<_> = std::mem::take(&mut r.holes).into_iter().map(Some).collect(); + for k in order { + r.holes.push(remaining.get_mut(k).and_then(Option::take).ok_or_else(|| KernelError::Invalid("missing loft hole".into()))?); + } + } + previous = r.holes.iter().map(position).collect(); + } + // Matching resamples each loop family to its largest section. Different holes can + // be the large one in different sketches: bound the combined result, not just each + // input section, before allocating the wires. + let mut counts = vec![0usize; holes + 1]; + for r in &numbered { + for (count, lp) in counts.iter_mut().zip(r.loops()) { + *count = (*count).max(lp.lp.segs.len()); + } + } + if counts.iter().sum::() > MAX_SEGS { + return Err(KernelError::Invalid("matching loft sections would create too many segments".into())); + } + guard("loft with holes", || { + let mut loops = vec![loft_numbered_wires(&outlines, reversed)?]; + for i in 0..holes { + let secs = planes + .iter() + .zip(&numbered) + .map(|(p, r)| r.holes.get(i).cloned().map(|h| (*p, h)).ok_or_else(|| KernelError::Invalid("missing loft hole".into()))) + .collect::>>()?; + // The holes have already been ordered with the outline. + loops.push(loft_numbered_wires(&secs, false)?); + } + let close = |smooth: bool| { + let mut sides = Vec::new(); + let mut first = Vec::new(); + let mut last = Vec::new(); + for (i, (wires, sources)) in loops.iter().enumerate() { + let faces = if smooth { smooth_loft_faces(wires, sources, true)? } else { ruled_loft_faces(wires, sources)? }; + let (Some(a), Some(b)) = (wires.first(), wires.last()) else { return Err(KernelError::Invalid("no loft sections".into())) }; + if i == 0 { + sides.extend(faces); + first.push(a.clone()); + last.push(b.clone()); + } else { + sides.extend(faces.into_iter().map(|(f, source)| (f.inverse(), source))); + first.push(a.inverse()); + last.push(b.inverse()); + } + } + cap_and_close(sides, &first, &last, reversed) + }; + if sections.len() >= 3 + && let Ok(body) = guard("smooth loft with holes", || close(true)) + { + return Ok(body); + } + close(false) + }) +} + /// The wires of a loft's closed sections, matched: oriented alike, resampled to the same /// segment count and turned to start alike; with the profile segments under each wire edge, and /// whether the sections were turned round into the canonical order. pub(crate) fn loft_wires(sections: &[(Plane, Loop2)]) -> Result<(Vec, Vec>>, bool)> { + let reversed = loft_reversed(sections)?; + let ordered = sections.iter().map(|(p, _)| *p).zip(numbered::number_loops(sections.iter().map(|(_, l)| l))).collect::>(); + let (wires, sources) = guard("loft sections", || loft_numbered_wires(&ordered, reversed))?; + Ok((wires, sources, reversed)) +} + +fn loft_reversed(sections: &[(Plane, Loop2)]) -> Result { if sections.len() < 2 || sections.len() > 50 { return Err(KernelError::Invalid("a loft needs 2…50 sections".into())); } @@ -1836,10 +1961,16 @@ pub(crate) fn loft_wires(sections: &[(Plane, Loop2)]) -> Result<(Vec, let (Some(first), Some(last)) = (sections.first(), sections.last()) else { return Err(KernelError::Invalid("no sections".into())) }; let step = centre(last) - centre(first); let big = [step.x, step.y, step.z].into_iter().max_by(|a, b| a.abs().total_cmp(&b.abs())).unwrap_or(0.0); - let reversed = big < 0.0; + Ok(big < 0.0) +} + +fn loft_numbered_wires(sections: &[(Plane, NumberedLoop)], reversed: bool) -> Result<(Vec, Vec>>)> { + let n = sections.iter().map(|(_, l)| l.lp.segs.len()).max().unwrap_or(0); + if n == 0 || n > MAX_SEGS { + return Err(KernelError::Invalid("empty section".into())); + } // The sections' segments are numbered in the order given. - let mut ordered: Vec<(Plane, NumberedLoop)> = - sections.iter().map(|(p, _)| *p).zip(numbered::number_loops(sections.iter().map(|(_, l)| l))).collect(); + let mut ordered = sections.to_vec(); if reversed { ordered.reverse(); } @@ -1847,6 +1978,7 @@ pub(crate) fn loft_wires(sections: &[(Plane, Loop2)]) -> Result<(Vec, // turns the solid outward), then match segment counts and starting points to the section // with the most segments. let n0 = ordered.first().map(|(p, _)| p.normal()).unwrap_or(Vec3::Z); + let parallel = ordered.iter().all(|(p, _)| p.normal().dot(n0).abs() > 1.0 - 1e-9); let oriented: Vec<(Plane, NumberedLoop)> = ordered .iter() .map(|(p, l)| { @@ -1865,6 +1997,12 @@ pub(crate) fn loft_wires(sections: &[(Plane, Loop2)]) -> Result<(Vec, // Break angles: the lead section's vertex directions seen in this plane. let angles: Vec = lead_dirs.iter().map(|d| Vec2::new(d.dot(p.x), d.dot(p.y)).angle()).collect(); let mut r = l.resample(n, &angles); + // Circle resampling creates increasing local angles. An antiparallel sketch + // plane must run clockwise locally to keep the same winding in world space. + // Curving a run through a right angle does not reverse a section's winding. + if parallel && p.normal().dot(n0) < 0.0 { + r = r.oriented(true); + } // Start where every vertex lines up best with the lead's vertex of the same number (the // largest sum of dot products of their directions from the centroids). The one vertex // closest in direction to the lead's first vertex twisted non-convex sections (#881): a @@ -1880,7 +2018,7 @@ pub(crate) fn loft_wires(sections: &[(Plane, Loop2)]) -> Result<(Vec, wires.push(uniform_wire(p, &r.lp)?); edge_sources.push(r.from); } - Ok((wires, edge_sources, reversed)) + Ok((wires, edge_sources)) } /// Ruled faces between each two neighbouring section wires; each comes from the section edges diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rs index e55646f44..f6e71389d 100644 --- a/crates/kernel/src/lib.rs +++ b/crates/kernel/src/lib.rs @@ -81,6 +81,8 @@ mod issue_871_tests; mod join_between_caps_tests; mod lip; pub mod loft_blend; +#[cfg(test)] +mod loft_region_tests; mod loopblend; mod matchsurf; mod measure; @@ -157,7 +159,7 @@ pub use boundary::{Boundary, boundary_patch}; pub use boundary_network::{BoundaryCurve, CurveSource, MAX_CHAIN_CURVES, MAX_EDGE_PICKS, boundary_join, boundary_surface}; pub use bridge::{Continuity, Frame, blend_between, bridge, chain, chain_closes, frames, frames_across, sample_grid}; pub use build::{ - PathSeg, box_solid, canonical_revolve_axis, cylinder, extrude, extrude_tapered, extrude_tapered_between, extrude_whole_sides, loft, + PathSeg, box_solid, canonical_revolve_axis, cylinder, extrude, extrude_tapered, extrude_tapered_between, extrude_whole_sides, loft, loft_regions, path_polyline, revolve, revolve_whole, sphere, sweep, sweep_with, torus, }; pub use clearance::{Clearance, Occupancy}; diff --git a/crates/kernel/src/loft_region_tests.rs b/crates/kernel/src/loft_region_tests.rs new file mode 100644 index 000000000..462ea8217 --- /dev/null +++ b/crates/kernel/src/loft_region_tests.rs @@ -0,0 +1,121 @@ +//! Analytic regressions for lofted passages (#2435). + +use std::f64::consts::PI; + +use solidcraft_geom::{Loop2, Plane, Region2, Vec2, Vec3}; + +use crate::{Body, loft_regions, measure, step_export, step_import}; + +fn square(half: f64) -> Loop2 { + Loop2::polygon(&[Vec2::new(-half, -half), Vec2::new(half, -half), Vec2::new(half, half), Vec2::new(-half, half)]) +} + +fn check(body: &Body, volume: f64, tol: f64) { + assert!(body.validity().is_empty(), "{:?}", body.validity()); + assert_eq!(body.shell_count(), 1); + let got = measure(body).unwrap().volume; + assert!((got - volume).abs() < tol * volume, "{got} vs {volume}"); +} + +#[test] +fn loft_regions_preserve_a_tapered_round_passage_and_step() { + let ring = |r, h| Region2 { outer: Loop2::circle(Vec2::ZERO, r), holes: vec![Loop2::circle(Vec2::ZERO, h)] }; + let secs = [(Plane::XY, ring(20.0, 12.0)), (Plane::XY.offset(30.0), ring(14.0, 8.0))]; + let want = PI * 30.0 / 3.0 * ((400.0 + 280.0 + 196.0) - (144.0 + 96.0 + 64.0)); + for secs in [secs.to_vec(), secs.into_iter().rev().collect()] { + let body = loft_regions(&secs).unwrap(); + check(&body, want, 1e-3); + assert!(!body.tessellate(0.001).unwrap().contains(Vec3::new(0.0, 0.0, 10.0)), "passage was filled"); + let imported = step_import(&step_export(&[&body], "SolidCraft").unwrap()).unwrap(); + assert_eq!(imported.bodies.len(), 1); + check(&imported.bodies[0].body, want, 1e-3); + } +} + +#[test] +fn loft_regions_smooth_inner_and_outer_walls_together() { + // Half-width 10 + 10 (2t-1)²; the hole is half as wide. Integral of the + // material cross-section over 40 mm is 40 * 3 * (100 + 200/3 + 100/5). + let ring = |r| Region2 { outer: square(r), holes: vec![square(r * 0.5)] }; + let secs = [(Plane::XY, ring(20.0)), (Plane::XY.offset(20.0), ring(10.0)), (Plane::XY.offset(40.0), ring(20.0))]; + for secs in [secs.to_vec(), secs.into_iter().rev().collect()] { + let b = loft_regions(&secs).unwrap(); + check(&b, 22400.0, 1e-4); + assert!(!b.tessellate(0.001).unwrap().contains(Vec3::new(0.0, 0.0, 10.0)), "passage was filled"); + assert_eq!(measure(&b).unwrap().merged.faces, 10, "four outer walls, four inner walls, two caps"); + } +} + +#[test] +fn loft_regions_match_holes_in_opposite_curve_orders_and_facing_planes() { + let holes = vec![Loop2::circle(Vec2::new(-8.0, 0.0), 3.0), Loop2::circle(Vec2::new(8.0, 0.0), 5.0)]; + let a = Region2 { outer: square(20.0), holes: holes.clone() }; + // Reversing the plane's x direction mirrors local x. Opposite normals must + // leave the same physical holes and inward-facing walls. + let down = Plane::new(Vec3::new(0.0, 0.0, 20.0), -Vec3::X, Vec3::Y).unwrap(); + let b = Region2 { outer: square(20.0), holes: vec![Loop2::circle(Vec2::new(-8.0, 0.0), 5.0), Loop2::circle(Vec2::new(8.0, 0.0), 3.0)] }; + let secs = [(Plane::XY, a), (down, b)]; + for secs in [secs.to_vec(), secs.into_iter().rev().collect()] { + let body = loft_regions(&secs).unwrap(); + check(&body, (1600.0 - PI * 34.0) * 20.0, 1e-3); + let mesh = body.tessellate(0.001).unwrap(); + assert!(!mesh.contains(Vec3::new(-8.0, 0.0, 10.0))); + assert!(!mesh.contains(Vec3::new(8.0, 0.0, 10.0))); + assert!(mesh.contains(Vec3::new(0.0, 12.0, 10.0))); + let history = body.history().unwrap(); + // Both holes keep the original section/segment numbering, even after pairing. + for segment in 0..(8 + holes.iter().map(|h| h.segs.len()).sum::() * 2) { + assert!(history.faces.iter().any(|f| f.origins.contains(&crate::history::FaceOrigin::Profile { segment })), "{segment}"); + } + } +} + +#[test] +fn loft_regions_refuse_missing_holes_and_hostile_sections() { + let a = Region2 { outer: square(20.0), holes: vec![square(10.0)] }; + let b = Region2 { outer: square(20.0), holes: vec![] }; + for secs in [vec![], vec![(Plane::XY, a.clone())], vec![(Plane::XY, a.clone()); 51]] { + assert!(loft_regions(&secs).is_err()); + } + assert!(loft_regions(&[(Plane::XY, a.clone()), (Plane::XY.offset(20.0), b)]).unwrap_err().to_string().contains("same number of holes")); + let many = Region2 { outer: square(20.0), holes: vec![square(1.0); 129] }; + assert!(loft_regions(&[(Plane::XY, many.clone()), (Plane::XY.offset(20.0), many)]).is_err()); + let bad = Region2 { outer: square(20.0), holes: vec![Loop2::circle(Vec2::ZERO, f64::NAN)] }; + assert!(loft_regions(&[(Plane::XY, a), (Plane::XY.offset(20.0), bad)]).is_err()); +} + +#[test] +fn loft_regions_bound_segments_after_matching() { + // Each sketch fits the input budget, but independently resampling both holes + // would exceed it in every section. Refuse before allocating the topology. + let circle = |x, n| Loop2 { + segs: (0..n) + .map(|i| solidcraft_geom::Seg2::Arc { + center: Vec2::new(x, 0.0), + radius: 1.0, + start: i as f64 * std::f64::consts::TAU / n as f64, + sweep: std::f64::consts::TAU / n as f64, + }) + .collect(), + }; + let a = Region2 { outer: square(20.0), holes: vec![circle(-8.0, 10_001), circle(8.0, 2)] }; + let b = Region2 { outer: square(20.0), holes: vec![circle(-8.0, 2), circle(8.0, 10_001)] }; + let err = loft_regions(&[(Plane::XY, a), (Plane::XY.offset(20.0), b)]).unwrap_err().to_string(); + assert!(err.contains("matching loft sections would create too many segments"), "{err}"); +} + +#[test] +fn loft_regions_refuse_ambiguous_hole_pairings_in_any_draw_order() { + let ring = |centres: [Vec2; 2]| Region2 { outer: square(20.0), holes: centres.into_iter().map(|c| Loop2::circle(c, 1.0)).collect() }; + let a = ring([Vec2::new(-5.0, 0.0), Vec2::new(5.0, 0.0)]); + // Ties, and two source holes whose unique nearest candidate is the same hole. + for centres in [[Vec2::new(0.0, -5.0), Vec2::new(0.0, 5.0)], [Vec2::new(4.0, 0.0), Vec2::new(10.0, 0.0)]] { + for centres in [centres, [centres[1], centres[0]]] { + let secs = [(Plane::XY, a.clone()), (Plane::XY.offset(20.0), ring(centres))]; + for secs in [secs.to_vec(), secs.into_iter().rev().collect()] { + let err = loft_regions(&secs).unwrap_err().to_string(); + assert!(err.contains("hole correspondence is ambiguous"), "{err}"); + } + } + } +} diff --git a/examples/regressions/loft_rings.json b/examples/regressions/loft_rings.json new file mode 100644 index 000000000..ca2e9be9d --- /dev/null +++ b/examples/regressions/loft_rings.json @@ -0,0 +1,100 @@ +{ + "description": "#2435: a 30 mm loft from radii 20/12 to 14/8 keeps its tapered passage. Expected volume: 5720*pi mm^3. Previously refused every section containing a hole.", + "commands": [ + { + "command": "sketch.create", + "params": { + "plane": "XY", + "offset": 0, + "name": "Bottom" + } + }, + { + "command": "sketch.circle.center", + "params": { + "center": [ + 0, + 0 + ], + "radius": 20 + } + }, + { + "command": "sketch.circle.center", + "params": { + "center": [ + 0, + 0 + ], + "radius": 12 + } + }, + { + "command": "sketch.finish", + "params": {} + }, + { + "command": "sketch.create", + "params": { + "plane": "XY", + "offset": 30, + "name": "Top" + } + }, + { + "command": "sketch.circle.center", + "params": { + "center": [ + 0, + 0 + ], + "radius": 14 + } + }, + { + "command": "sketch.circle.center", + "params": { + "center": [ + 0, + 0 + ], + "radius": 8 + } + }, + { + "command": "sketch.finish", + "params": {} + }, + { + "command": "solid.loft", + "params": { + "sections": [ + { + "sketch": "Bottom", + "profiles": [ + { + "point": [ + 16, + 0 + ] + } + ] + }, + { + "sketch": "Top", + "profiles": [ + { + "point": [ + 11, + 0 + ] + } + ] + } + ], + "operation": "new", + "name": "Hollow loft" + } + } + ] +} From b622a46624f0947c9b47bac9e426c6ad7c17dd64 Mon Sep 17 00:00:00 2001 From: Colin Faulkingham Date: Tue, 20 Oct 2026 00:06:44 +0000 Subject: [PATCH 153/225] Fix large modeled threads and thin crest reconstruction (#2209) * Fix large modeled threads and thin crest reconstruction Helix stations follow the pitch (radial chord error under 1% of it, 48 to 720 stations), and the faceted rebuild retries at the BSP's precision when the usual weld tolerance collapses a thin crest facet. Rebased onto main as one commit (the branch's own commits touched UI files that later moved to #2263 and #2264). Adapted to main's UnitVec3 thread axis: `*k` in thread_groove and `*cylinder.axis` in the new flange test. * Fix icon review revisions for same-timestamp edits --- ROADMAP.md | 2 + assets/icons/ui/design/tools/icon_status.py | 7 +- crates/doc/src/eval.rs | 15 ++++- crates/engine/src/thread_tests.rs | 72 ++++++++++++++++++++- crates/kernel/src/polybool.rs | 28 ++++++-- tests/tools/test_icon_review.py | 10 ++- 6 files changed, 121 insertions(+), 13 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 02ae22f30..6f102acf5 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -101,6 +101,8 @@ completed drawings publish atomically. The browser still exports synchronously. drag continues, then catch up to the exact final value. Changes to the selected geometry, operation or feature still discard obsolete results. Distance arrows and their value boxes follow the current frame's input. +- Large fine modelled threads use pitch-based helix resolution and tighter faceted + reconstruction fallbacks, preserving thin crests and closed shells on large shafts. ## Physical material data diff --git a/assets/icons/ui/design/tools/icon_status.py b/assets/icons/ui/design/tools/icon_status.py index b69275654..f0c9fbaab 100644 --- a/assets/icons/ui/design/tools/icon_status.py +++ b/assets/icons/ui/design/tools/icon_status.py @@ -37,8 +37,11 @@ def art_rev(): paths += glob.glob(HERE + '/*.py') paths += [D + '/palette.toml', D + '/aliases.toml', __file__] for path in sorted(paths): - st = os.stat(path) - h.update(('%s %d %d;' % (os.path.relpath(path, ROOT), st.st_mtime_ns, st.st_size)).encode()) + # Equal-length edits can share an mtime. Only the content identifies what + # the reviewer saw; file metadata must never authorize stale acceptance. + h.update(os.path.relpath(path, ROOT).replace(os.sep, '/').encode() + b'\0') + with open(path, 'rb') as source: + h.update(hashlib.sha256(review_state.lf(source.read())).digest()) return h.hexdigest()[:16] diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 0167c1825..dcf95e176 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -407,8 +407,19 @@ fn thread_groove(t: &ThreadInfo, radius: f64, open: (bool, bool)) -> Result 720.0 { + return Err(DocError::Invalid("the modelled thread is too fine for this diameter; use a cosmetic thread".into())); + } + Ok(kernel::sweep_helix_mesh(&plane, §ion, base, *k, p, (s1 - s0) / p, stations as usize)?) } /// A constant fillet of `edges`; with [`FilletFit::Reduce`](crate::FilletFit::Reduce), a radius too diff --git a/crates/engine/src/thread_tests.rs b/crates/engine/src/thread_tests.rs index 533042c72..5f12c78fc 100644 --- a/crates/engine/src/thread_tests.rs +++ b/crates/engine/src/thread_tests.rs @@ -1,4 +1,5 @@ -//! Modelled threads: the ISO metric profile cut along a helix, M3 to M20, outside and inside. +//! Modelled threads: the ISO metric profile cut along a helix, inside and outside, +//! including fine pitches on large shafts and the sample flange. use std::f64::consts::PI; @@ -22,6 +23,75 @@ fn volume(s: &mut Session, b: &str) -> f64 { const SIZES: [(f64, f64); 9] = [(3.0, 0.5), (4.0, 0.7), (5.0, 0.8), (6.0, 1.0), (8.0, 1.25), (10.0, 1.5), (12.0, 1.75), (16.0, 2.0), (20.0, 2.5)]; +/// Keep the original 48-station reproduction of the shell error even though new fine +/// threads now use more stations. The same cut polygons must rebuild as a closed solid. +#[test] +fn faceted_flange_thread_preserves_thin_crest_boundaries() { + use crate::geom::{Plane, Vec2, Vec3}; + use crate::kernel; + + let mut s = Session::default(); + let sample = crate::sample::samples().into_iter().find(|s| s.name == "Bolted Flange").unwrap(); + s.run_script(&(sample.script)()).unwrap(); + let state = s.model.state(); + let body = &state.body("Flange").unwrap().body; + let face = Vec3::new(-19.034766861657907, -11.03075929038123, 19.574640342897094); + let cylinder = kernel::cylinder_face_at(body, face).unwrap(); + let pitch = 1.5; + let height = pitch * 3f64.sqrt() / 2.0; + let root = 22.0 - 5.0 * height / 8.0; + let outer = 22.0 + 0.05 * pitch; + let half_width = (pitch / 4.0 + 2.0 * (outer - root) * (PI / 6.0).tan()) / 2.0; + let section = [Vec2::new(root, -pitch / 8.0), Vec2::new(outer, -half_width), Vec2::new(outer, half_width), Vec2::new(root, pitch / 8.0)]; + let (start, end) = (cylinder.start - pitch, cylinder.end + pitch); + let base = cylinder.axis_point + cylinder.axis * start; + let plane = Plane { origin: base, x: cylinder.axis.cross(Vec3::new(1.0, 0.0, 0.0)).normalized().unwrap(), y: *cylinder.axis }; + let groove = kernel::sweep_helix_mesh(&plane, §ion, base, *cylinder.axis, pitch, (end - start) / pitch, 48).unwrap(); + let cut = kernel::faceted_boolean(body, &groove, kernel::BoolOp::Cut, pitch * 0.005).unwrap().unwrap(); + assert!(cut.validity().is_empty(), "{:?}", cut.validity()); + let before = body.tessellate(0.001).unwrap().measure().volume; + let after = cut.tessellate(0.001).unwrap().measure().volume; + assert!(before - after > 700.0 && before - after < 1800.0, "removed {}", before - after); +} + +#[test] +fn modelled_full_length_m44_flange_thread() { + let mut s = Session::default(); + let sample = crate::sample::samples().into_iter().find(|s| s.name == "Bolted Flange").unwrap(); + s.run_script(&(sample.script)()).unwrap(); + let before = volume(&mut s, "Flange"); + run( + &mut s, + "solid.thread", + json!({ + "face": [-19.034766861657907, -11.03075929038123, 19.574640342897094], + "designation": "M44x1.5", "modeled": true + }), + ); + let state = s.model.state(); + let body = &state.body("Flange").unwrap().body; + assert!(body.validity().is_empty(), "{:?}", body.validity()); + let removed = before - volume(&mut s, "Flange"); + assert!(removed > 700.0 && removed < 1800.0, "a full-length helical cut removes material: {removed}"); +} + +#[test] +fn modelled_full_length_fine_threads_on_large_shafts() { + for (d, p, len) in [(44.0, 1.0, 5.0), (44.0, 1.5, 16.0), (100.0, 1.5, 6.0)] { + let mut s = Session::default(); + run(&mut s, "solid.cylinder", json!({"radius":d / 2.0,"height":len,"body_name":"Shaft"})); + let before = volume(&mut s, "Shaft"); + run(&mut s, "solid.thread", json!({"face":[d / 2.0,0,len / 2.0],"designation":format!("M{d}x{p}"),"modeled":true})); + let state = s.model.state(); + let body = &state.body("Shaft").unwrap().body; + assert!(body.validity().is_empty(), "M{d}x{p}: {:?}", body.validity()); + let root = d / 2.0 - 5.0 * p * 3f64.sqrt() / 16.0; + let want = per_turn(root, d / 2.0, |r| p / 4.0 + 2.0 * (r - root) * (PI / 6.0).tan()) * len / p; + let got = before - volume(&mut s, "Shaft"); + assert!((got - want).abs() < want * 0.04, "M{d}x{p}: removed {got}, ISO profile {want}"); + } +} + #[test] fn non_finite_thread_designations_are_refused_without_changing_the_design() { let mut s = Session::default(); diff --git a/crates/kernel/src/polybool.rs b/crates/kernel/src/polybool.rs index 665765c1b..bff22d0e5 100644 --- a/crates/kernel/src/polybool.rs +++ b/crates/kernel/src/polybool.rs @@ -398,10 +398,25 @@ fn faceted_boolean_untimed(a: &Body, b: &Mesh, op: BoolOp, tol: f64) -> Result return Ok(Some(b)), Err(e) => last = e, } + // Thin facets at a thread crest can be narrower than the usual reconstruction + // tolerance. Welding/splitting at that coarser tolerance collapses their boundaries + // into a non-manifold edge. Retry the same volume-checked polygons at the BSP's + // finer precision. Allow a small margin for points classified on either side of + // a splitter, then try the exact BSP tolerance if that still collapses a facet. + // Never return a shell that fails the closed-solid check. + for precision in [3.0 * eps, eps] { + if precision < weld { + match rebuild(&out, size, precision, &sources) { + Ok(b) => return Ok(Some(b)), + Err(e) => last = e, + } + } + } } Err(last) } @@ -685,7 +700,7 @@ fn polys_boolean(pa: Vec, pb: Vec, size: f64, op: BoolOp, eps: f64, if polys.is_empty() { return Ok(None); } - rebuild(polys, size, sources).map(Some) + rebuild(&polys, size, size * 1e-7, sources).map(Some) } /// What a rebuilt body's history is over: each operand's face and edge counts and, where it is @@ -837,8 +852,7 @@ fn key(p: Vec3, q: f64) -> (i64, i64, i64) { /// Its history over the operands the polygons are pieces of (`sources`): each face the /// operand faces whose pieces it joins (pieces joined across the edges between them), each edge /// what the pieces either side of it say (see [`Sources::edge`]). -fn rebuild(polys: Vec, size: f64, sources: &Sources) -> Result { - let q = size * 1e-7; +fn rebuild(polys: &[Poly], size: f64, q: f64, sources: &Sources) -> Result { // Global vertex table. let mut index: BTreeMap<(i64, i64, i64), usize> = BTreeMap::new(); let mut verts: Vec = Vec::new(); @@ -862,7 +876,7 @@ fn rebuild(polys: Vec, size: f64, sources: &Sources) -> Result { }; let mut loops: Vec<(PlaneEq, Vec)> = Vec::new(); let mut srcs: Vec = Vec::new(); - for p in &polys { + for p in polys { let mut l: Vec = p.v.iter().map(|v| id(*v, &mut verts)).collect(); l.dedup(); if l.first() == l.last() && l.len() > 1 { @@ -905,7 +919,7 @@ fn rebuild(polys: Vec, size: f64, sources: &Sources) -> Result { let (Some(&pa), Some(&pb)) = (verts.get(a), verts.get(b)) else { continue }; let d = pb - pa; let len2 = d.len2(); - let (lo, hi) = (ckey(pa.min(pb) - Vec3::new(tol, tol, tol)), ckey(pa.max(pb) + Vec3::new(tol, tol, tol))); + let (lo, hi) = (ckey(pa.min(pb) - Vec3::new(q, q, q)), ckey(pa.max(pb) + Vec3::new(q, q, q))); let cells = (hi.0 - lo.0 + 1) * (hi.1 - lo.1 + 1) * (hi.2 - lo.2 + 1); let candidates: Vec = if cells > 4096 { (0..verts.len()).collect() @@ -928,7 +942,7 @@ fn rebuild(polys: Vec, size: f64, sources: &Sources) -> Result { .filter_map(|k| { let v = verts.get(k)?; let t = (*v - pa).dot(d) / len2.max(1e-300); - (t > 1e-9 && t < 1.0 - 1e-9 && v.dist_to_segment(pa, pb) < tol).then_some((t, k)) + (t > 1e-9 && t < 1.0 - 1e-9 && v.dist_to_segment(pa, pb) < q).then_some((t, k)) }) .collect(); on.sort_by(|x, y| x.0.total_cmp(&y.0)); diff --git a/tests/tools/test_icon_review.py b/tests/tools/test_icon_review.py index bcdf256d8..dcd50f857 100644 --- a/tests/tools/test_icon_review.py +++ b/tests/tools/test_icon_review.py @@ -1,6 +1,7 @@ """Long-term discovery and acceptance behavior of the repository-owned review app.""" import contextlib import json +import os import re from pathlib import Path import shutil @@ -247,7 +248,14 @@ class IconReviewTest(unittest.TestCase): self.assertNotIn('box', changed['final']) self.assertIn('changed since acceptance', get('/')) self.assertEqual(old_hash, json.loads((design / 'review.json').read_text(encoding='utf-8'))['final']['box']) - (design / 'svg/model/box.svg').write_text(SVG.replace('r="20"', 'r="17"'), encoding='utf-8') + artwork = design / 'svg/model/box.svg' + before = artwork.stat() + artwork.write_text(SVG.replace('r="20"', 'r="17"'), encoding='utf-8') + # Equal-length edits can share a filesystem timestamp on fast CI hosts. + # Reproduce that deterministically: acceptance must track the content. + os.utime(artwork, ns=(before.st_atime_ns, before.st_mtime_ns)) + self.assertEqual(artwork.stat().st_size, before.st_size) + self.assertEqual(artwork.stat().st_mtime_ns, before.st_mtime_ns) with self.assertRaises(urllib.error.HTTPError) as error: post(changed, final=['box']) self.assertEqual(error.exception.code, 400) From e661e6f809a94a94632bb61f7f3eb0b800cef3d7 Mon Sep 17 00:00:00 2001 From: NOWN-DEV <257771410+NOWN-DEV@users.noreply.github.com> Date: Tue, 20 Oct 2026 00:09:50 +0000 Subject: [PATCH 154/225] inspect.clearance: pins on one cylinder with their hole are answered or reported in seconds (#3027) * inspect.clearance: pairs whose bodies did not change are not measured again Each clearance check measured every close pair again, though between two checks usually only a few bodies change or move. Results are now kept per pair, keyed by both bodies' geometry and placement and the check's settings; a pair whose two bodies are unchanged is taken from that cache. With 40 overlapping parts, a check after moving one of them took 0.8 s instead of 23 s (741 of 780 pairs reused). Pairs that could not be worked out are tried again each time. Co-Authored-By: Claude Opus 5.5 (1M context) * inspect.clearance: boxes and placed keys exactly as before the reuse The pair boxes are taken over the mesh's triangles with finite corners, as a distance shape's are, so pruning is unchanged. A placed body's identity now includes its model body's own frame, so two placements are never mistaken for one another. Co-Authored-By: Claude Opus 5.5 (1M context) * inspect.clearance: a large body is meshed once for all its pairs Each pair that touches cuts the larger body down to the pair's region with a kernel boolean, and that boolean meshed the whole body twice: once for its checks and once inside the intersection. A sheet with 600 faces paid about 2.5 s per pair for meshes that were the same every time. A body can now keep its meshes for reuse (Body::keeping_meshes); its booleans take the meshes from there, and the intersection takes its shell meshes from there too (truck-shapeops: and_with_history_meshed). Clearance uses such copies for one check. Results are unchanged to the bit. On a 3 x 2 m sheet with bends and 300 holes, the clip took 0.23 s per pair instead of 2.6 s, and 24 rivets took 5.6 s instead of 16.5 s. Co-Authored-By: Claude Opus 5.5 (1M context) * inspect.clearance: pins on one cylinder with their hole are answered or reported in seconds A pin seated line to line in its hole, on its axis, and with a blend running into its wall (a fillet under a head) sent the boolean through minutes of retries that ended unchecked; a pin a hair off its hole's axis was passed as clear. Clearance now asks first whether the pair holds such a pin (from the faces' surfaces alone). On its axis the boolean gets a few tries, which answer plain pins at once; a hair off, or when those tries fail, the shared volume is worked out apart by coaxial_overlap, which now also takes the zero-offset, equal-radius case, moves the hole's wall when a blend keeps the pin's from moving, and checks its band more tightly. What neither answers is reported as unchecked, naming the pin. The kernel gains with_attempt_budget: the booleans run inside it get a number of tries of the kernel's own intersection between them, the same on every machine. Co-Authored-By: Claude Opus 5.5 (1M context) * inspect.clearance: the pin tests sit beside the other measured pairs, not at the file's end Co-Authored-By: Claude Opus 5.5 (1M context) * inspect.clearance: the bodies left whole meet their booleans with their meshes kept A body that meets several others at one size (a bracket with balls pressed into it) was meshed again for each pair's intersect: only the clipping used the copies that keep their meshes. The intersect, the pin work and the union check now take those copies too. Co-Authored-By: Claude Opus 5.5 (1M context) * Near-coaxial overlap: ten tries per intersection, enough for a flush head pulled back #1984's headed pin made before its plate needs more than eight. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01Aac7mP9rthK3WsPpPRvCsF --------- Co-authored-by: Claude Opus 5.5 (1M context) Co-authored-by: bherbruck --- crates/engine/src/cmd/clearance.rs | 123 +++++++++++++---- crates/engine/src/cmd/clearance_tests.rs | 58 ++++++++ crates/kernel/src/coaxial_overlap.rs | 169 ++++++++++++++++++----- crates/kernel/src/lib.rs | 4 +- crates/kernel/src/ops.rs | 37 +++++ crates/kernel/src/tests.rs | 17 +++ 6 files changed, 341 insertions(+), 67 deletions(-) diff --git a/crates/engine/src/cmd/clearance.rs b/crates/engine/src/cmd/clearance.rs index 97cf6d13a..2ef36228f 100644 --- a/crates/engine/src/cmd/clearance.rs +++ b/crates/engine/src/cmd/clearance.rs @@ -47,6 +47,9 @@ enum SkipWithin { /// Most pairs [`PairCache`] keeps; it starts over when full. const MAX_CACHED: usize = 2 * MAX_PAIRS; +/// The kernel's tries at intersecting a pin with its hole on one cylinder (each about a second +/// on real parts; a plain pin on its axis needs one or two). +const PIN_ATTEMPTS: usize = 4; /// Pairs measured before, by the two bodies' geometry where they stood /// ([`solidcraft_doc::ModelBody::geometry_key`]) and the settings that shape the result @@ -341,40 +344,73 @@ fn measure_pair( // A pair whose shared part can't be worked out is reported, not passed as clear. let region = shared_region(a, b); let (ca, cb) = (clipped(ka, region), clipped(kb, region)); - let (shared, report) = solidcraft_kernel::capture_boolean_diagnostics(|| { - solidcraft_kernel::boolean(ca.as_ref().unwrap_or(&ba.body), cb.as_ref().unwrap_or(&bb.body), solidcraft_kernel::BoolOp::Intersect) - }); - match shared { - Err(e) => { - out.unchecked = Some(e.to_string()); - return out; + // A pin of one in a hole of the other of its own size. On its very axis the boolean takes + // the two walls as one and answers plain ones at once, but with blends next to them it + // tries for minutes and gives up; a hair off the axis it cannot intersect them at all + // (and may pass the pin as clear). So a pin on its axis gets a few tries of the boolean + // first, and what the walls share is otherwise worked out apart, with a few tries of the + // boolean left for when that declines. The body left whole is cut down to where the + // other's piece is first, so that both meet only the faces there. + let candidate = solidcraft_kernel::coaxial_candidate(ca.as_ref().unwrap_or(ka), cb.as_ref().unwrap_or(kb)); + let pin = candidate.is_some(); + let (ca, cb) = match (ca, cb) { + (Some(x), None) if pin => { + let y = narrowed(kb, &x); + (Some(x), y) } - Ok(shared) => { - if let Some(reason) = report.unverified() { - out.unchecked = Some(reason); + (None, Some(y)) if pin => (narrowed(ka, &y), Some(y)), + other => other, + }; + // A body left whole is the copy that keeps its meshes: meeting several others at one + // size, it is meshed once for the booleans of all of them. + let (pa, pb) = (ca.as_ref().unwrap_or(ka), cb.as_ref().unwrap_or(kb)); + let intersect = || { + solidcraft_kernel::capture_boolean_diagnostics(|| { + let run = || solidcraft_kernel::boolean(pa, pb, solidcraft_kernel::BoolOp::Intersect); + if pin { solidcraft_kernel::with_attempt_budget(PIN_ATTEMPTS, run) } else { run() } + }) + }; + let first = (candidate != Some(false)).then(intersect); + let answered = first.as_ref().is_some_and(|(r, report)| r.is_ok() && report.unverified().is_none()); + let coaxial = if pin && !answered { solidcraft_kernel::coaxial_overlap(pa, pb) } else { None }; + if let Some(o) = coaxial { + if o.volume > 0.0 { + out.overlap = Some((o.volume, o.area, o.bbox, o.centroid)); + } + } else { + let (shared, report) = first.unwrap_or_else(intersect); + let failed = + |why: String| if pin { format!("a pin on one cylinder with its hole, whose walls could not be intersected ({why})") } else { why }; + let shared = match shared { + Err(e) => { + out.unchecked = Some(failed(e.to_string())); return out; } - if let Some(o) = shared { - match measure_near_origin(&o, region.center()) { - Ok(m) if !plausible(m.volume, m.centroid, m.bbox) => { - out.unchecked = Some(format!( - "the shared part came out malformed ({:.4} mm³ with its centre outside its own box), so it is not measured", - m.volume - )); - return out; - } - Ok(m) => { - let (wa, wb) = (ca.as_ref().unwrap_or(&ba.body), cb.as_ref().unwrap_or(&bb.body)); - if let Some(reason) = union_disagrees(wa, wb, m.volume, region.center()) { - out.unchecked = Some(reason); - return out; - } - out.overlap = Some((m.volume, m.area, m.bbox, m.centroid)); - } - Err(e) => { - out.unchecked = Some(e.to_string()); + Ok(shared) => shared, + }; + if let Some(reason) = report.unverified() { + out.unchecked = Some(failed(reason)); + return out; + } + if let Some(o) = shared { + match measure_near_origin(&o, region.center()) { + Ok(m) if !plausible(m.volume, m.centroid, m.bbox) => { + out.unchecked = Some(format!( + "the shared part came out malformed ({:.4} mm³ with its centre outside its own box), so it is not measured", + m.volume + )); + return out; + } + Ok(m) => { + if let Some(reason) = union_disagrees(pa, pb, m.volume, region.center()) { + out.unchecked = Some(reason); return out; } + out.overlap = Some((m.volume, m.area, m.bbox, m.centroid)); + } + Err(e) => { + out.unchecked = Some(e.to_string()); + return out; } } } @@ -435,6 +471,35 @@ fn clipped(body: &solidcraft_kernel::Body, region: Aabb3) -> Option Option { + let bounds = |b: &solidcraft_kernel::Body| b.tessellate_with((b.size() * 1e-3).max(1e-4), false).ok().map(|m| m.bounds()); + let (x, y) = (bounds(body)?, bounds(piece)?); + let (min, max) = (x.min.max(y.min), x.max.min(y.max)); + if x.is_empty() || y.is_empty() || !(min.x <= max.x && min.y <= max.y && min.z <= max.z) { + return None; + } + let grow = 1.0 + 0.05 * min.dist(max); + let g = solidcraft_geom::Vec3::new(grow, grow, grow); + let region = Aabb3 { min: min - g, max: max + g }; + if region.min.x <= x.min.x + && region.min.y <= x.min.y + && region.min.z <= x.min.z + && x.max.x <= region.max.x + && x.max.y <= region.max.y + && x.max.z <= region.max.z + { + return None; + } + let cut = solidcraft_kernel::box_solid(region.min, region.max).ok()?; + let (r, report) = solidcraft_kernel::capture_boolean_diagnostics(|| solidcraft_kernel::boolean(body, &cut, solidcraft_kernel::BoolOp::Intersect)); + match r { + Ok(Some(c)) if report.unverified().is_none() => Some(c), + _ => None, + } +} + /// [`solidcraft_kernel::measure`] of `body` moved by `-at` and back: far from the origin, the /// centre of a thin part loses its precision (its moments are large numbers that nearly cancel). fn measure_near_origin(body: &solidcraft_kernel::Body, at: solidcraft_geom::Vec3) -> solidcraft_kernel::Result { diff --git a/crates/engine/src/cmd/clearance_tests.rs b/crates/engine/src/cmd/clearance_tests.rs index 901f4a74a..16bc3fda7 100644 --- a/crates/engine/src/cmd/clearance_tests.rs +++ b/crates/engine/src/cmd/clearance_tests.rs @@ -345,6 +345,64 @@ fn a_body_that_changed_shape_is_measured_again() { assert!((f(&r["near"][0]["distance_mm"]) - 0.5).abs() < 1e-6, "{r}"); } +/// A flanged bushing and a headed pin seated in it line to line, on its very axis, the head on +/// the flange. Plain, they touch and share nothing; sunk 0.2 into the flange, the head shares the +/// ring under it. With a fillet under the head against the bore's sharp edge, the fillet's ring +/// is in the flange (about 0.49 mm³), next to walls that lie on one another: the boolean tried +/// for minutes there and gave up; now it is reported as such within seconds. +#[test] +fn a_pin_seated_line_to_line_in_its_bushing_is_measured() { + let ring = std::f64::consts::PI * (7.0f64.powi(2) - 4.0f64.powi(2)) * 0.2; + for (sunk, fillet) in [(0.0, false), (0.2, false), (0.0, true)] { + let mut s = Session::default(); + run(&mut s, "solid.cylinder", json!({"radius": 5, "height": 12, "base": [100, 0, 0], "operation": "new", "body_name": "Bush"})); + run(&mut s, "solid.cylinder", json!({"radius": 7.5, "height": 1, "base": [100, 0, 12], "operation": "join", "targets": ["Bush"]})); + run(&mut s, "solid.cylinder", json!({"radius": 4, "height": 20, "base": [100, 0, -3], "operation": "cut", "targets": ["Bush"]})); + let z = 13.0 - sunk; + run(&mut s, "solid.cylinder", json!({"radius": 4, "height": z + 2.0, "base": [100, 0, -2], "operation": "new", "body_name": "Pin"})); + run(&mut s, "solid.cylinder", json!({"radius": 7, "height": 1.5, "base": [100, 0, z], "operation": "join", "targets": ["Pin"]})); + if fillet { + run(&mut s, "solid.fillet", json!({"edges": [[104, 0, z]], "radius": 0.3, "body": "Pin"})); + run(&mut s, "solid.fillet", json!({"edges": [[107, 0, z + 1.5]], "radius": 0.5, "body": "Pin"})); + } + let started = std::time::Instant::now(); + let r = run(&mut s, "inspect.clearance", json!({"bodies": ["Pin"], "against": ["Bush"], "min_volume": 0.01, "clearance": 1e-6})); + assert!(started.elapsed().as_secs_f64() < 30.0, "sunk {sunk}: {:?}", started.elapsed()); + if fillet { + assert!(r["unchecked"][0]["reason"].as_str().is_some_and(|w| w.contains("pin on one cylinder")), "{r}"); + continue; + } + assert_eq!(r["unchecked"], json!([]), "sunk {sunk}: {r}"); + if sunk == 0.0 { + assert_eq!(r["overlaps"].as_array().map(Vec::len), Some(0), "{r}"); + assert_eq!(f(&r["near"][0]["distance_mm"]), 0.0, "{r}"); + } else { + let v = f(&r["overlaps"][0]["volume_mm3"]); + assert!((v - ring).abs() <= 1e-3 * ring, "{v} {ring}: {r}"); + } + } +} + +/// A chamfered pin through a hole of its own radius, its axis a hair off the hole's: the boolean +/// cannot intersect walls all but tangent along two lines and once passed the pair as clear. +/// The crescent the pin shares with the plate is reported, against the lens of two circles. +#[test] +fn a_pin_a_hair_off_its_hole_shares_its_crescent() { + let crescent = |r: f64, e: f64| std::f64::consts::PI * r * r - (2.0 * r * r * (e / (2.0 * r)).acos() - e / 2.0 * (4.0 * r * r - e * e).sqrt()); + for offset in [5.9e-4, 1e-2] { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 20, "width": 20, "height": 5, "corner": [-10, -10, 0], "body_name": "Plate"})); + run(&mut s, "solid.cylinder", json!({"radius": 3, "height": 9, "base": [0, 0, -2], "operation": "cut", "targets": ["Plate"]})); + run(&mut s, "solid.cylinder", json!({"radius": 3, "height": 9, "base": [offset, 0, -2], "operation": "new", "body_name": "Pin"})); + run(&mut s, "solid.chamfer", json!({"edges": [[offset + 3.0, 0, 7]], "distance": 0.5, "body": "Pin"})); + let r = run(&mut s, "inspect.clearance", json!({"min_volume": 1e-9})); + assert_eq!(r["unchecked"], json!([]), "{offset}: {r}"); + let want = 5.0 * crescent(3.0, offset); + let got = f(&r["overlaps"][0]["volume_mm3"]); + assert!((got - want).abs() < 1e-6 * want, "{offset}: {got} against {want}: {r}"); + } +} + /// The shared volume is checked against the bodies and their union: two 10 mm cubes sharing a /// 3 mm corner cube agree at 27 mm³, and a shared part read as three times that (as a mirrored /// pair once was) does not. diff --git a/crates/kernel/src/coaxial_overlap.rs b/crates/kernel/src/coaxial_overlap.rs index 165f0c839..c7331f18b 100644 --- a/crates/kernel/src/coaxial_overlap.rs +++ b/crates/kernel/src/coaxial_overlap.rs @@ -1,10 +1,11 @@ //! The shared volume of a pin in a hole of (nearly) its own size whose axis is a hair off the -//! hole's (parts placed from rounded coordinates). +//! hole's (parts placed from rounded coordinates), or on it: a pin seated line to line. //! //! The pin's wall and the hole's wall then meet along two lines where they are all but tangent, -//! which the boolean cannot intersect, and the facets of the two walls pass through each other +//! or lie on one another, which the boolean cannot intersect, and the facets of the two walls pass through each other //! by less than the boolean's sampled shortcuts can see. So the overlap is worked out in two -//! parts instead. The pin's wall is moved off the hole's by a clear step (`offset_body`) and the +//! parts instead. The pin's wall is moved off the hole's by a clear step (`offset_body`; where a +//! blend running into the pin's wall keeps it from moving, the hole's wall is moved instead) and the //! bodies are intersected as they then are, which the boolean can do: narrowed, that gives the //! overlap away from the walls (the core). In the band the move swept, what the two walls //! share is a crescent in every section, whose area follows from the two circles alone. The @@ -36,6 +37,10 @@ pub struct CoaxialOverlap { const NEAR: f64 = 0.01; /// The step the pin's wall is moved by, as a share of its radius. const STEP: f64 = 0.1; +/// The tries each intersection here gets: with a wall moved clear it takes one or two, and a +/// few more where a flush face is pulled back or the tool is nudged by a hair; one that needs +/// more than that meets something this work does not cover. +const ATTEMPTS: usize = 10; /// The faces of one body on one cylinder, the side its material is on and their extent along /// the axis. @@ -66,8 +71,8 @@ struct Pair { } /// The overlap of `a` and `b` when a pin of one sits in a hole of the other on nearly the same -/// cylinder (axes parallel, offset plus radius difference within 1 % of the radius, but not on -/// the same surface), worked out as the module says. `None` when there is no such pin, or the +/// cylinder (axes parallel, offset plus radius difference within 1 % of the radius, none for a +/// pin seated line to line), worked out as the module says. `None` when there is no such pin, or the /// bodies hold more than the pin and the hole where the work assumes they don't: the caller /// then takes the general boolean. pub fn coaxial_overlap(a: &Body, b: &Body) -> Option { @@ -78,16 +83,51 @@ pub fn coaxial_overlap(a: &Body, b: &Body) -> Option { crate::guard("near-coaxial overlap", || Ok(overlap(a, b).or_else(|| overlap(b, a)))).ok().flatten() } +/// Whether a cylinder of `a` and one of `b` are on one cylinder or nearly (what +/// [`coaxial_overlap`] asks first, from the faces' surfaces alone): a cheap test for whether +/// it is worth preparing the bodies for it. `Some(true)` when every such pair is on one cylinder +/// within the kernel's same-surface tolerance, which the boolean takes as one wall; `Some(false)` +/// when one is a hair off, which it cannot intersect and may even pass as clear. +pub fn coaxial_candidate(a: &Body, b: &Body) -> Option { + if a.is_mesh() || b.is_mesh() { + return None; + } + crate::guard("near-coaxial candidate", || { + let same = same_surface(a.size().max(b.size())); + let (ca, cb) = (cylinders(a), cylinders(b)); + let mut found = None; + for x in &ca { + for y in &cb { + if x.axis.dot(y.axis).abs() <= 1.0 - 1e-9 { + continue; + } + if let Some((_, offset)) = near(x, y) { + let one = offset + (x.radius - y.radius).abs() <= same; + found = Some(found.unwrap_or(true) && one); + } + } + } + Ok(found) + }) + .ok() + .flatten() +} + +/// The distance within which the kernel takes two surfaces as one, for bodies of `size`. +fn same_surface(size: f64) -> f64 { + (size * 1e-7).max(1e-9) * 10.0 +} + fn overlap(a: &Body, b: &Body) -> Option { let size = a.size().max(b.size()); if !(size.is_finite() && size > 0.0) { return None; } // The same surface as the kernel takes it elsewhere: walls that close are one wall. - let same = (size * 1e-7).max(1e-9) * 10.0; + let same = same_surface(size); // Meshed only when two cylinders are close enough to be asked about. let (ca, cb) = (cylinders(a), cylinders(b)); - let close = |x: &Wall, y: &Wall| x.axis.dot(y.axis).abs() > 1.0 - 1e-9 && near(x, y, same).is_some(); + let close = |x: &Wall, y: &Wall| x.axis.dot(y.axis).abs() > 1.0 - 1e-9 && near(x, y).is_some(); if !ca.iter().any(|x| cb.iter().any(|y| close(x, y))) { return None; } @@ -112,16 +152,24 @@ fn overlap(a: &Body, b: &Body) -> Option { // Two pins or two holes on nearly one cylinder, side by side along it: not this // case. Apart along the axis (a screw's head beside a bush of its radius), they // don't meet. - _ if near(x, y, same).is_some() && total(&intersect(&union(&x.spans), &union(&project(y, x)))) > same => return None, + _ if near(x, y).is_some() && total(&intersect(&union(&x.spans), &union(&project(y, x)))) > same => return None, _ => continue, }; - let Some((toward, offset)) = near(pin, hole, same) else { continue }; + let Some((toward, offset)) = near(pin, hole) else { continue }; let shared = intersect(&union(&pin.spans), &union(&project(hole, pin))); if total(&shared) <= same { continue; } let step = (pin.radius * STEP).min(size * 0.02); - pairs.push(Pair { pin: pin.clone(), pin_in_a, hole: hole.clone(), toward, offset, shared, step }); + // Within the kernel's same-surface tolerance the two walls are one: no crescent. + let mut hole = hole.clone(); + let offset = if offset + (pin.radius - hole.radius).abs() <= same { + hole.radius = pin.radius; + 0.0 + } else { + offset + }; + pairs.push(Pair { pin: pin.clone(), pin_in_a, hole, toward, offset, shared, step }); } } if pairs.is_empty() { @@ -131,26 +179,58 @@ fn overlap(a: &Body, b: &Body) -> Option { // an area, which the boolean cannot always take: it is pulled back off it by a little. // Only material outside the other body goes, so the overlap is the same. let back = pairs.iter().map(|p| p.step).fold(f64::INFINITY, f64::min) * 0.05; - let (fa, fb) = (flush(a, b, same, back), flush(b, a, same, back)); - // A pin's faces move together: one step for each of them (the pin's walls do not repeat - // across pairs unless one pin is near two holes, which the check below then answers). + let flat = (flush(a, b, same, back), flush(b, a, same, back), back); + // The pin's wall is moved where its neighbours let it; where they don't (a blend running + // into it), the hole's wall is moved away from the pin instead. + let stuck = std::cell::Cell::new(false); + answer(a, b, &pairs, size, &flat, false, &stuck).or_else(|| if stuck.get() { answer(a, b, &pairs, size, &flat, true, &stuck) } else { None }) +} + +/// The overlap of the `pairs` worked out with each pin's wall moved by steps, or each hole's +/// (`move_hole`); `stuck` set when a body could not be moved. `flat` holds the faces of `a` +/// and of `b` that touch the other flat, and how far they are pulled back off it. +fn answer( + a: &Body, + b: &Body, + pairs: &[Pair], + size: f64, + flat: &(Vec, Vec, f64), + move_hole: bool, + stuck: &std::cell::Cell, +) -> Option { + let (fa, fb, back) = (&flat.0, &flat.1, flat.2); + // The pin's and the hole's radius with the moved wall `k` steps toward the other. + let radii = |p: &Pair, k: f64| if move_hole { (p.pin.radius, p.hole.radius - p.step * k) } else { (p.pin.radius + p.step * k, p.hole.radius) }; + // A wall's faces move together: one step for each of them (a wall does not repeat across + // pairs unless one pin is near two holes, which the check below then answers). let shared_at = |k: f64| -> Option<(f64, Option)> { let moved = |body: &Body, in_a: bool| -> Option { - let mine: Vec<&Pair> = pairs.iter().filter(|p| p.pin_in_a == in_a).collect(); + let mine: Vec<(&Wall, f64)> = pairs + .iter() + .filter_map(|p| match (move_hole, p.pin_in_a == in_a) { + (false, true) => Some((&p.pin, p.step)), + (true, false) => Some((&p.hole, p.step)), + _ => None, + }) + .collect(); if mine.is_empty() { return Some(body.clone()); } - let flush = if in_a { &fa } else { &fb }; - let shift = |i: usize, _| match mine.iter().find(|p| p.pin.faces.contains(&i)) { - Some(p) => p.step * k, + let flush = if in_a { fa } else { fb }; + let shift = |i: usize, _| match mine.iter().find(|(w, _)| w.faces.contains(&i)) { + Some((_, step)) => step * k, None if flush.contains(&i) => -back, None => 0.0, }; - let m = crate::offset::offset_body(body, shift).ok()?; - m.validity().is_empty().then_some(m) + let m = crate::offset::offset_body(body, shift).ok().filter(|m| m.validity().is_empty()); + if m.is_none() { + stuck.set(true); + } + m }; let (ma, mb) = (moved(a, true)?, moved(b, false)?); - let (r, report) = crate::capture_boolean_diagnostics(|| crate::ops::boolean(&ma, &mb, BoolOp::Intersect)); + let (r, report) = + crate::capture_boolean_diagnostics(|| crate::ops::with_attempt_budget(ATTEMPTS, || crate::ops::boolean(&ma, &mb, BoolOp::Intersect))); // The core is the answer and must be exact. The wider pins only check the band, to // 2 % of what it gains: a tool nudged by a hair of the step there is as good. let nudge = if k > 0.0 { pairs.iter().map(|p| p.step).fold(f64::INFINITY, f64::min) * 1e-2 } else { 0.0 }; @@ -162,14 +242,17 @@ fn overlap(a: &Body, b: &Body) -> Option { Some(body) => Some((crate::measure(&body).ok()?.volume, Some(body))), } }; - // The crescents' volume with every pin grown by `k` steps. - let crescents = - |k: f64| -> f64 { pairs.iter().map(|p| total(&p.shared) * crescent(p.pin.radius + p.step * k, p.hole.radius, p.offset).area).sum() }; + // The crescents' area along each pair with the moved walls `k` steps toward each other. + let crescent_at = |p: &Pair, k: f64| { + let (r, h) = radii(p, k); + crescent(r, h, p.offset).area + }; + let crescents = |k: f64| -> f64 { pairs.iter().map(|p| total(&p.shared) * crescent_at(p, k)).sum() }; let (core, core_body) = shared_at(-1.0)?; for k in [0.5, 1.0] { let (v, _) = shared_at(k)?; let gain = crescents(k) - crescents(-1.0); - if !((v - core - gain).abs() <= 0.02 * gain + 1e-4 * v.abs() + 1e-12 * size.powi(3)) { + if !((v - core - gain).abs() <= 0.002 * gain + 1e-4 * v.abs() + 1e-12 * size.powi(3)) { return None; } } @@ -186,11 +269,11 @@ fn overlap(a: &Body, b: &Body) -> Option { bbox = m.bbox; volume = m.volume; } - for p in &pairs { + for p in pairs { let c = crescent(p.pin.radius, p.hole.radius, p.offset); let length = total(&p.shared); - // Less what the narrowed pin already reached (nothing, unless the hole is the smaller). - let v = length * c.area - length * crescent(p.pin.radius - p.step, p.hole.radius, p.offset).area; + // Less what the moved walls already shared (nothing, unless the hole is the smaller). + let v = length * (c.area - crescent_at(p, -1.0)); let mid = p.shared.iter().map(|(s, t)| (s + t) * 0.5 * (t - s)).sum::() / length; let side = p.toward.cross(p.pin.axis); moment += (p.pin.origin + p.pin.axis * mid + p.toward * c.centroid) * v; @@ -221,17 +304,13 @@ fn altered_by_at_most(report: &crate::BooleanDiagnostics, limit: f64, size: f64) .all(|e| e.strategy == crate::BooleanStrategy::ToolNudge && limit > 0.0 && e.translation_mm + e.rotation_rad * size <= limit) } -/// The pin's offset to the hole, when the two are nearly on one cylinder but not on the same -/// surface: the unit direction from the pin's axis to the hole's (any, for one axis) and the -/// distance. -fn near(pin: &Wall, hole: &Wall, same: f64) -> Option<(Vec3, f64)> { +/// The pin's offset to the hole, when the two are on one cylinder or nearly: the unit direction +/// from the pin's axis to the hole's (any, for one axis) and the distance. +fn near(pin: &Wall, hole: &Wall) -> Option<(Vec3, f64)> { let d = hole.origin - pin.origin; let across = d - pin.axis * d.dot(pin.axis); let offset = across.len(); let gap = (pin.radius - hole.radius).abs(); - if offset <= same && gap <= same { - return None; - } if !(offset + gap <= NEAR * pin.radius.min(hole.radius)) { return None; } @@ -499,11 +578,29 @@ mod tests { let slot = crate::box_solid(Vec3::new(2.5, -1.0, -1.0), Vec3::new(4.0, 1.0, 6.0)).unwrap(); let slotted = crate::boolean(&plate, &slot, BoolOp::Cut).unwrap().unwrap(); assert!(coaxial_overlap(&slotted, &pin).is_none()); - // Pins on the very axis, or far off it, aren't asked about. - assert!(coaxial_overlap(&plate, &plate_and_pin(3.0, 0.0).1).is_none()); + // So it is for a pin on the very axis; one far off it isn't asked about. + assert!(coaxial_overlap(&slotted, &plate_and_pin(3.0, 0.0).1).is_none()); assert!(coaxial_overlap(&plate, &plate_and_pin(3.0, 0.5).1).is_none()); } + /// A pin seated line to line, on the hole's very axis: the walls share nothing, and a head + /// sunk 0.2 into the plate's face shares the ring under it. + #[test] + fn a_pin_seated_line_to_line_shares_only_what_its_head_sinks() { + let (plate, pin) = plate_and_pin(3.0, 0.0); + for (x, y) in [(&plate, &pin), (&pin, &plate)] { + let o = coaxial_overlap(x, y).unwrap(); + assert!(o.volume < 1e-9 && o.offset < 1e-9 && (o.length - 5.0).abs() < 1e-9, "{o:?}"); + } + let head = crate::cylinder(Vec3::new(0.0, 0.0, 4.8), Vec3::Z, 5.0, 2.0).unwrap(); + let headed = crate::boolean(&pin, &head, BoolOp::Union).unwrap().unwrap(); + let want = std::f64::consts::PI * (5.0f64.powi(2) - 3.0f64.powi(2)) * 0.2; + let o = coaxial_overlap(&plate, &headed).unwrap(); + // Measured off the core's mesh, as a boolean's result is. + assert!((o.volume - want).abs() < 1e-4 * want, "{o:?} {want}"); + assert!((o.centroid.z - 4.9).abs() < 1e-6, "{o:?}"); + } + /// A bush and a headed screw whose shank ends inside the bore, both written to STEP and /// read back: their cylinders come back as one face each that runs once round along a seam /// edge, which the boolean cannot intersect where the shank's end meets the bore. The diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rs index f6e71389d..ece2cdc96 100644 --- a/crates/kernel/src/lib.rs +++ b/crates/kernel/src/lib.rs @@ -163,7 +163,7 @@ pub use build::{ path_polyline, revolve, revolve_whole, sphere, sweep, sweep_with, torus, }; pub use clearance::{Clearance, Occupancy}; -pub use coaxial_overlap::{CoaxialOverlap, coaxial_overlap}; +pub use coaxial_overlap::{CoaxialOverlap, coaxial_candidate, coaxial_overlap}; pub use continuity::{ ContinuityReport, ContinuityTolerances, EdgePick, MAX_SAMPLES, MIN_SAMPLES, SeamReport, SeamVerdict, SeamWorst, pick_edges, seam_diagnostics, }; @@ -189,7 +189,7 @@ pub use native::{decode_native_body, encode_native_body, native_preview_mesh}; pub use offset::with_same_surface; pub use ops::{ BoolOp, boolean, can_join_all_touching_faces, can_join_touching_faces, compound_disjoint_extrusions, half_space, is_planar, join_apart, - split_by_plane, transform, transform_matrix, union_apart, + split_by_plane, transform, transform_matrix, union_apart, with_attempt_budget, }; pub use polybool::{faceted_boolean, planar_boolean}; pub use polyhedron::{HalfSpace, convex_polyhedron, draft, offset_faces, shell}; diff --git a/crates/kernel/src/ops.rs b/crates/kernel/src/ops.rs index eb6f1479e..865786867 100644 --- a/crates/kernel/src/ops.rs +++ b/crates/kernel/src/ops.rs @@ -874,6 +874,40 @@ thread_local! { static APART: std::cell::Cell = const { std::cell::Cell::new(false) }; /// Set while a union runs with a bore narrowed off a common cylinder (no second round). static BORES: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// The intersections left to the booleans running under [`with_attempt_budget`], if any. + static ATTEMPTS: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// `f`, with the booleans it runs on this thread allowed `attempts` of the kernel's own +/// intersections between them (each try of a boolean takes one): past those, a boolean fails at +/// once instead of trying on. For a caller that would rather report a pair it could not answer +/// than wait on bodies the boolean cannot take, and the same on every machine. A budget inside +/// another takes the smaller and uses up the outer one's too. +pub fn with_attempt_budget(attempts: usize, f: impl FnOnce() -> T) -> T { + struct Restore(Option, usize); + impl Drop for Restore { + fn drop(&mut self) { + let left = ATTEMPTS.with(|c| c.get()).unwrap_or(0); + ATTEMPTS.with(|c| c.set(self.0.map(|outer| outer.saturating_sub(self.1.saturating_sub(left))))); + } + } + let outer = ATTEMPTS.with(|c| c.get()); + let mine = outer.map_or(attempts, |o| o.min(attempts)); + ATTEMPTS.with(|c| c.set(Some(mine))); + let _restore = Restore(outer, mine); + f() +} + +/// Takes one of the attempts left under [`with_attempt_budget`]; false when none is left. +fn take_attempt() -> bool { + ATTEMPTS.with(|c| match c.get() { + None => true, + Some(0) => false, + Some(n) => { + c.set(Some(n - 1)); + true + } + }) } /// Boolean of two bodies. The result may be empty (`Ok(None)`) for a cut that removes @@ -1829,6 +1863,9 @@ pub(crate) fn nudged(r: Body, nb: &Body, counts: &[(usize, usize)]) -> Body { /// copies) keep the operands' face and edge order, and so does moving the result back, so the /// history truck records holds for the operands themselves. pub(crate) fn truck_boolean(a: &Body, b: &Body, op: BoolOp, shift: Option, tol: f64) -> Result<(Solid, Option)> { + if !take_attempt() { + return Err(KernelError::Failed("no result in the tries it was given".into())); + } guard("boolean", || { let (mut sa, mut sb) = (a.deep_copy(), b.deep_copy()); if let Some(shift) = shift { diff --git a/crates/kernel/src/tests.rs b/crates/kernel/src/tests.rs index d29152568..bd668d78e 100644 --- a/crates/kernel/src/tests.rs +++ b/crates/kernel/src/tests.rs @@ -2963,3 +2963,20 @@ fn loft_pairs_the_vertices_of_matching_non_convex_sections() { assert!(rel(m.volume, want) < 5e-3, "{} vs {want}", m.volume); assert!(m.centroid.x.abs() < 0.05, "centre of mass x {}", m.centroid.x); } + +/// Two cylinders crossing at right angles need the kernel's own intersection: with no tries +/// left the boolean fails at once, a budget inside another uses the outer one's up, and none +/// lingers after. +#[test] +fn an_attempt_budget_stops_the_boolean_and_is_shared_by_nesting() { + let a = cylinder(Vec3::new(0.0, 0.0, -10.0), Vec3::Z, 3.0, 20.0).unwrap(); + let b = cylinder(Vec3::new(-10.0, 0.0, 0.0), Vec3::X, 2.0, 20.0).unwrap(); + assert!(with_attempt_budget(0, || boolean(&a, &b, BoolOp::Intersect)).is_err()); + // The inner budget asks for more than the outer has left: it gets what is left. + let (inner, after) = with_attempt_budget(1, || { + let inner = with_attempt_budget(10, || boolean(&a, &b, BoolOp::Intersect).is_ok()); + (inner, boolean(&a, &b, BoolOp::Intersect).is_ok()) + }); + assert!(inner && !after); + assert!(boolean(&a, &b, BoolOp::Intersect).unwrap().is_some()); +} From 9e7a7b260b96a47ac2b3bdf55ad4cdd6f144770c Mon Sep 17 00:00:00 2001 From: bherbruck Date: Tue, 20 Oct 2026 00:19:29 +0000 Subject: [PATCH 155/225] perf: Save and Save As write on a worker thread (#3044) (#3146) Save ran on the window's thread: about 130 ms on the Prusa Core One design, and more than a second once saves keep the evaluated model. The toolbar's Save and Save As now run the command on a scratch copy of the session on a worker; the design waits for it as it waits for a file picker (commands are refused meanwhile), and the outcome is taken up as running the command here would have left it: the name and links the save gave the design, its file, its saved state (`Session::adopt_save`), the echo, the error status, the recent files and the home thumbnail. A tab closing or the app quitting after Save waits for the write, as does the app's exit. Scripts, the control channel and the browser build still save in place. Co-authored-by: Claude Opus 5.5 --- apps/solidcraft/src/main.rs | 2 + crates/engine/src/cmd/file.rs | 44 ++++++++++++++ crates/ui-egui/src/documents.rs | 2 + crates/ui-egui/src/file_picker.rs | 5 +- crates/ui-egui/src/lib.rs | 20 ++++++- crates/ui-egui/src/save_job.rs | 95 +++++++++++++++++++++++++++++++ crates/ui-egui/src/scenario.rs | 4 +- crates/ui-egui/src/toolbar.rs | 11 +++- 8 files changed, 174 insertions(+), 9 deletions(-) create mode 100644 crates/ui-egui/src/save_job.rs diff --git a/apps/solidcraft/src/main.rs b/apps/solidcraft/src/main.rs index d346b1f2d..c4489c6fb 100644 --- a/apps/solidcraft/src/main.rs +++ b/apps/solidcraft/src/main.rs @@ -91,6 +91,8 @@ impl eframe::App for App { fn on_exit(&mut self) { // The agent chat's agent and everything it started end with the app. solidcraft_ui_egui::agent_chat::shutdown(&mut self.solve); + // A save still being written ends before the app does. + solidcraft_ui_egui::save_job::tick(&mut self.solve, true); solidcraft_ui_egui::recovery_ui::close(&mut self.solve); solidcraft_engine::crash::end_session(); // An update asked to restart into the new version or to run its installer. diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index efc83fda1..9d336559e 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -382,6 +382,22 @@ fn write_bytes( } impl Session { + /// Take up a save that ran on `done`, a [`Session::scratch`] copy of this session that + /// `file.save` or `file.save_as` ran on (on another thread, so the window keeps drawing) + /// while this one did not change: the name and link paths the save gave the design, its + /// file, and its saved state, as running the command here would have left them. + pub fn adopt_save(&mut self, done: &Session) { + if done.doc.name != self.doc.name { + let (from, to) = (self.doc.name.clone(), done.doc.name.clone()); + rename_design(self, &from, &to); + } + if done.doc.links != self.doc.links { + self.doc_mut().links.clone_from(&done.doc.links); + } + self.path.clone_from(&done.path); + self.mark_saved(); + } + /// Container bytes for desktop and browser saves. Only already evaluated bodies /// and warm meshes are eligible; saving never forces evaluation or tessellation. pub fn design_container(&self, compression: solidcraft_io::DesignCompression, preview: bool, cache: bool) -> solidcraft_io::Result> { @@ -645,6 +661,34 @@ mod urdf_tests; mod tests { use super::*; + /// #3044: a save run on a scratch copy of the session (on a worker, so the window keeps + /// drawing) and taken up with `adopt_save` leaves the session as saving it directly does: + /// the design named after its first file, its file, and nothing unsaved; undo keeps the name. + #[test] + fn a_save_run_on_a_copy_and_adopted_matches_saving_directly() { + let dir = std::env::temp_dir().join(format!("solidcraft-adopt-save-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let mut direct = Session::default(); + direct.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10})).unwrap(); + let mut adopted = Session::new((*direct.doc).clone()); + adopted.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10})).unwrap(); + let a = dir.join("Bracket.solidcraft"); + let b = dir.join("Bracket copy.solidcraft"); + direct.execute("file.save_as", &json!({"path": a.to_string_lossy()})).unwrap(); + let mut copy = adopted.scratch(); + copy.path.clone_from(&adopted.path); + copy.execute("file.save_as", &json!({"path": b.to_string_lossy()})).unwrap(); + assert!(adopted.is_dirty(), "nothing taken up yet"); + adopted.adopt_save(©); + assert!(!adopted.is_dirty()); + assert_eq!(adopted.path.as_deref(), b.to_str()); + assert_eq!(adopted.doc.name, "Bracket copy"); + assert_eq!(direct.doc.name, "Bracket"); + assert_eq!(adopted.undo.iter().map(|u| u.doc.name.clone()).collect::>(), vec!["Bracket copy".to_string(); adopted.undo.len()]); + assert_eq!(solidcraft_io::read_design(&std::fs::read(&b).unwrap()).unwrap(), *adopted.doc); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] #[ignore = "manual warmed engine save and provisional-open benchmark"] fn benchmark_warm_design_save_with_preview() { diff --git a/crates/ui-egui/src/documents.rs b/crates/ui-egui/src/documents.rs index 5b869b279..6f240ecd3 100644 --- a/crates/ui-egui/src/documents.rs +++ b/crates/ui-egui/src/documents.rs @@ -761,6 +761,7 @@ mod tests { assert_eq!(a.docs.closing, Some(0), "the first unsaved design is asked about first"); assert_eq!(a.docs.active, 0, "and shown"); answer_prompt(&mut a, Answer::Save); + crate::save_job::tick(&mut a, true); assert!(!dirty(&a, 0), "saved"); assert_eq!( std::fs::read(&file).ok().and_then(|b| solidcraft_engine::io::read_design(&b).ok()).map(|d| d.features.len()), @@ -802,6 +803,7 @@ mod tests { answer_prompt(&mut a, Answer::Save); assert!(!a.quit_requested && a.file_picker_busy()); crate::file_picker::tick(&mut a, &egui::Context::default()); + crate::save_job::tick(&mut a, true); assert!(a.quit_requested && file.exists()); let _ = std::fs::remove_file(&file); } diff --git a/crates/ui-egui/src/file_picker.rs b/crates/ui-egui/src/file_picker.rs index 3ec09ab65..afd683ddd 100644 --- a/crates/ui-egui/src/file_picker.rs +++ b/crates/ui-egui/src/file_picker.rs @@ -29,8 +29,9 @@ impl Wake for Repaint { impl SolveApp { /// Keep the target design and editors unchanged until the picker answers. + /// (A save being written keeps it unchanged too, see [`crate::save_job`].) pub fn file_picker_busy(&self) -> bool { - self.file_picker.is_some() + self.file_picker.is_some() || self.saving.is_some() } pub(crate) fn pick_open(&mut self, complete: impl FnOnce(&mut SolveApp, Option) + 'static) { @@ -175,6 +176,8 @@ mod tests { waker.wake(); } tick(app, &egui::Context::default()); + // A save the answer started is written on a worker: wait for it. + crate::save_job::tick(app, true); assert!(!app.file_picker_busy()); } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 9b17c23ca..3d344ca6b 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -141,6 +141,7 @@ pub mod render_workspace; mod revolve_edit_tests; #[cfg(test)] mod revolve_manipulator_tests; +pub mod save_job; pub mod scenario; pub mod select_other; pub mod selection; @@ -311,6 +312,8 @@ pub struct SolveApp { pub pre_sketch_marker: Option>, pub services: Services, file_picker: Option, + /// A Save or Save As being written on a worker (see [`save_job`]). + saving: Option, pub viewport: viewport::ViewportState, pub render_workspace: render_workspace::State, pub tool: Option, @@ -452,6 +455,7 @@ impl SolveApp { pre_sketch_marker: None, services, file_picker: None, + saving: None, viewport: viewport::ViewportState::default(), render_workspace, tool: None, @@ -652,7 +656,7 @@ impl SolveApp { /// Run a command programmatically (JSON parameters, no dialogs). pub fn run(&mut self, id: &str, params: Value) -> Result { - if self.file_load.busy() || self.file_picker.is_some() { + if self.file_load.busy() || self.file_picker.is_some() || self.saving.is_some() { return Err("a file operation is in progress".into()); } let t0 = now_ms(); @@ -683,7 +687,14 @@ impl SolveApp { // Curves drawn in construction (or centerline) mode take that line type. sketch_palette::apply_mode(self, id, v); } - match &r { + self.finish_command(id, &r); + r + } + + /// What follows a command's run, whether it ran here or on a worker (a save): its echo, + /// the status line when it failed, what opening and saving update, and the toolbar tab. + pub(crate) fn finish_command(&mut self, id: &str, r: &Result) { + match r { Ok(v) => { // Programmatic callers (the control channel, scripts) run outside a render // language scope, so resolve the echo from the saved preference instead of the @@ -735,7 +746,6 @@ impl SolveApp { self.ui.tab = "SOLID".into(); self.tool = None; } - r } /// Start a command the way a toolbar click does: interactive tools and dialogs for commands @@ -1295,6 +1305,10 @@ impl SolveApp { render_workspace::sync_backend(self); render_workspace::tick(self, ctx); file_load::tick(self, ctx); + save_job::tick(self, false); + if self.saving.is_some() { + ctx.request_repaint_after(std::time::Duration::from_millis(16)); + } self.esc_handled = false; prefs::apply(self, ctx); if !self.styled || theme::is_dark() != self.ui.dark || theme::vision() != self.preferences.color_vision { diff --git a/crates/ui-egui/src/save_job.rs b/crates/ui-egui/src/save_job.rs new file mode 100644 index 000000000..fe54eb283 --- /dev/null +++ b/crates/ui-egui/src/save_job.rs @@ -0,0 +1,95 @@ +//! Save and Save As off the window's thread (#3044): writing a large design (and the model a +//! save keeps with it) takes long enough that the window must keep drawing meanwhile. The +//! command runs on a copy of the session on a worker; the design waits for it like it waits for +//! a file picker, and the outcome is taken up as running the command here would have left it. + +use serde_json::Value; +use solidcraft_engine::Session; + +use crate::SolveApp; + +/// A save being written on a worker thread. +pub struct Saving { + command: &'static str, + done: std::sync::mpsc::Receiver<(Session, Result)>, +} + +/// Run `file.save` or `file.save_as` with `params`. On the desktop it runs on a worker and is +/// taken up by [`tick`] (true: it is under way); in the browser, or when no thread can start, it +/// runs here and is finished on return (false). +pub fn start(app: &mut SolveApp, command: &'static str, params: Value) -> bool { + #[cfg(not(target_arch = "wasm32"))] + if app.saving.is_none() && app.file_picker.is_none() && !app.file_load.busy() { + let mut copy = app.session.scratch(); + // The copy has no file: the command saves to this session's (and names the design after it). + copy.path.clone_from(&app.session.path); + let (tx, rx) = std::sync::mpsc::channel(); + let given = params.clone(); + let job = std::thread::Builder::new().name("save".into()).spawn(move || { + let r = copy.execute(command, &given).map_err(|e| e.to_string()); + let _ = tx.send((copy, r)); + }); + if job.is_ok() { + app.saving = Some(Saving { command, done: rx }); + return true; + } + // No thread to write on: save here, as before. + } + let _ = app.run(command, params); + false +} + +/// Take up a finished save (`wait`: wait for a running one). +pub fn tick(app: &mut SolveApp, wait: bool) { + let Some(saving) = app.saving.as_ref() else { return }; + let outcome = if wait { + saving.done.recv().ok() + } else { + match saving.done.try_recv() { + Ok(outcome) => Some(outcome), + Err(std::sync::mpsc::TryRecvError::Empty) => return, + Err(std::sync::mpsc::TryRecvError::Disconnected) => None, + } + }; + let Some(Saving { command, .. }) = app.saving.take() else { return }; + let r = match outcome { + Some((copy, Ok(v))) => { + app.session.adopt_save(©); + Ok(v) + } + Some((_, Err(e))) => Err(e), + None => Err(format!("{command}: the save stopped")), + }; + app.finish_command(command, &r); + crate::documents::saved_for_close(app); +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + /// #3044: Save writes on a worker while the window keeps drawing; the design waits (commands + /// are refused) until the save is taken up, which leaves it saved under its file, in the + /// recent files, with the command echoed, as a save run here does. + #[test] + fn save_writes_on_a_worker_and_is_taken_up_like_a_save_here() { + let mut h = crate::scenario::Harness::new(); + h.app.run("solid.box", json!({"length": 10, "width": 10, "height": 10})).unwrap(); + let path = h.dir.join("Plate.solidcraft"); + assert!(super::start(&mut h.app, "file.save_as", json!({"path": path.to_string_lossy()})), "under way on a worker"); + assert!(h.app.file_picker_busy() && h.app.run("solid.sphere", json!({"diameter": 4})).is_err(), "the design waits for it"); + h.frame(); + h.settle(); + assert!(h.app.saving.is_none() && !h.app.session.is_dirty()); + assert_eq!(h.app.session.path.as_deref(), path.to_str()); + assert_eq!(h.app.session.doc.name, "Plate"); + assert!(h.app.home.recent.iter().any(|r| r.as_str() == path.to_str().unwrap()), "{:?}", h.app.home.recent); + assert!(h.app.session.log.iter().any(|l| l.contains("Save As")), "{:?}", h.app.session.log); + // A failing save reports why, and leaves the changes unsaved. + h.app.run("solid.sphere", json!({"diameter": 4})).unwrap(); + let bad = h.dir.join("missing").join("x.solidcraft"); + super::start(&mut h.app, "file.save_as", json!({"path": bad.to_string_lossy()})); + super::tick(&mut h.app, true); + assert!(h.app.session.is_dirty() && h.app.status.as_ref().is_some_and(|(_, _, error)| *error)); + } +} diff --git a/crates/ui-egui/src/scenario.rs b/crates/ui-egui/src/scenario.rs index 3a83a0b96..04a56dac0 100644 --- a/crates/ui-egui/src/scenario.rs +++ b/crates/ui-egui/src/scenario.rs @@ -254,9 +254,9 @@ impl Harness { } self.frame(); } - // A file opening or recovering in the background: wait for it (as a person would). + // A file opening, recovering or saving in the background: wait for it (as a person would). let began = std::time::Instant::now(); - while !self.app.file_load.idle() && began.elapsed() < std::time::Duration::from_secs(120) { + while (!self.app.file_load.idle() || self.app.saving.is_some()) && began.elapsed() < std::time::Duration::from_secs(120) { self.frame(); std::thread::sleep(std::time::Duration::from_millis(1)); } diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index e6aeb9bab..e9650a944 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -596,7 +596,7 @@ pub fn save(app: &mut SolveApp) { return; } if app.session.path.is_some() { - let _ = app.run("file.save", json!({})); + crate::save_job::start(app, "file.save", json!({})); } else { save_as(app); } @@ -609,8 +609,11 @@ fn save_as(app: &mut SolveApp) { fn save_as_with_extension(app: &mut SolveApp, extension: &str) { let name = format!("{}.{extension}", app.session.doc.name); app.pick_save(&name, &[solidcraft_engine::io::DESIGN_EXT, "json"], |app, path| { - if let Some(path) = path { - let _ = app.run("file.save_as", json!({"path": path})); + // A save under way answers a closing tab when it ends. + if let Some(path) = path + && crate::save_job::start(app, "file.save_as", json!({"path": path})) + { + return; } crate::documents::saved_for_close(app); }); @@ -1467,6 +1470,8 @@ mod header_report_tests { h.frames(3); h.step(&json!({"click":{"handle":"appbar:folder"}})).unwrap(); h.step(&json!({"widget":"Save As JSON…"})).unwrap(); + // Written on a worker: the window keeps drawing until it is done. + h.settle(); let saved = h.app.session.path.clone().unwrap(); let bytes = std::fs::read(&saved).unwrap(); assert!(!solidcraft_engine::io::is_design_container(&bytes)); From 74af4a3471128118351faff245baa2b45ba96cf7 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Tue, 20 Oct 2026 00:21:38 +0000 Subject: [PATCH 156/225] test: the agent chat's long-message layout check waits for agent detection (#3349) `a_long_message_keeps_the_buttons_in_the_window` failed now and then on CI (Send 914.5 -> 888.5, also on #2893): looking for agents runs on its own thread, and what it finds (and the status it reports) can land between the two measurements and change what is around the panel. The test now waits for the search to finish and measures the buttons from the panel's bottom, which is what the box growing upwards keeps fixed. Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/agent_chat/tests.rs | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/agent_chat/tests.rs b/crates/ui-egui/src/agent_chat/tests.rs index dc81a3cf8..97bf62975 100644 --- a/crates/ui-egui/src/agent_chat/tests.rs +++ b/crates/ui-egui/src/agent_chat/tests.rs @@ -1414,24 +1414,35 @@ fn an_agents_markdown_is_drawn_as_blocks() { } /// A long message scrolls inside its box: the buttons under the box stay in the window (#2224). +/// Measured against the panel's bottom once the agents on this machine have been looked for: +/// what that finds (and the status it reports) arrives in its own time and may change what is +/// around the panel, which is not what this checks. #[test] fn a_long_message_keeps_the_buttons_in_the_window() { let mut h = crate::scenario::Harness::new(); h.call("ui.resize", json!({"width": 1600.0, "height": 1000.0})); h.call("ui.agent_chat", json!({"open": true})); h.frames(8); + let began = std::time::Instant::now(); + while h.app.agent_chat.detecting.is_some() && began.elapsed() < std::time::Duration::from_secs(30) { + h.frame(); + std::thread::sleep(std::time::Duration::from_millis(5)); + } + h.frames(4); + let bottom = |h: &crate::scenario::Harness| f64::from(h.app.agent_chat.panel_rect.map(|r| r.bottom()).expect("the panel is drawn")); let [_, rest] = h.widget("Send").expect("the Send button is drawn"); - let box_before = h.app.agent_chat.panel_rect.map(|r| r.bottom()); + let rest = bottom(&h) - rest; h.app.agent_chat.input = "Please make the plate thicker and then add a fillet on every outside edge.\n".repeat(60); h.frames(8); let window = 1000.0; for name in ["Send", "Attach view"] { let [_, y] = h.widget(name).unwrap_or_else(|| panic!("{name} is drawn")); assert!(y < window, "{name} is at {y}, below the window's bottom at {window}"); - // The box is pinned to the bottom and grows upwards: the buttons do not move. - assert!((y - rest).abs() < 1.0, "{name} moved from {rest} to {y}"); + // The box is pinned to the bottom and grows upwards: the buttons stay where they were + // above the panel's bottom. + let above = bottom(&h) - y; + assert!((above - rest).abs() < 1.0, "{name} moved from {rest} to {above} above the panel's bottom"); } - assert_eq!(h.app.agent_chat.panel_rect.map(|r| r.bottom()), box_before, "the panel keeps its size"); } fn test_png(colour: [u8; 4], width: u32) -> Vec { From 0a328a3d0a0ce64740f60adaf7021ca23abea41e Mon Sep 17 00:00:00 2001 From: bherbruck Date: Tue, 20 Oct 2026 00:22:36 +0000 Subject: [PATCH 157/225] perf: placed parts draw their definition's display plan, moved (#3044) (#3127) World placement already shares a part's reference mesh between its occurrences (#2924), but the display plan the GPU viewport draws was made again for every occurrence from its placed B-rep: planning every face of every instance of the part. A placement now carries the definition's plan cells too, and a placed body's plan (and its CPU mesh) is the definition's, moved by the placement's matrix (`TessPlan::transformed`): the part is planned once however often it is placed. Co-authored-by: Claude Opus 5.5 --- crates/doc/src/eval.rs | 21 +++---- crates/doc/src/placed_mesh.rs | 112 ++++++++++++++++++++++++++++++++-- crates/geom/src/tess.rs | 111 +++++++++++++++++++++++++++++++++ 3 files changed, 229 insertions(+), 15 deletions(-) diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index dcf95e176..eb7a1e5c3 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -123,16 +123,12 @@ impl ModelBody { /// The display plan at a given display quality, made once per level. pub fn display_plan_at(&self, q: crate::display_quality::DisplayQuality) -> Option> { - self.plan - .get(q.index())? - .get_or_init(|| match self.body.display_plan_angular(q.chord(self.body.size()), q.angle()) { - Ok(plan) => Some(Arc::new(plan)), - Err(e) => { - log::debug!("{}: no display plan ({e})", self.name); - None - } - }) - .clone() + let cell = self.plan.get(q.index())?; + match self.mesh_placement.as_deref() { + // A placed part shows its definition's plan, moved (planned once for every placement). + Some(placed) => cell.get_or_init(|| placed.plan(q, &self.name)).clone(), + None => placed_mesh::definition_plan(&self.body, cell, q, &self.name), + } } /// The display plan's mesh, evaluated on the CPU once per level: the same triangles a GPU @@ -147,7 +143,10 @@ impl ModelBody { pub fn plan_mesh_at(&self, q: crate::display_quality::DisplayQuality) -> Option> { self.plan_mesh .get(q.index())? - .get_or_init(|| self.display_plan_at(q).and_then(|plan| self.body.display_mesh_of(&plan).ok()).map(Arc::new)) + .get_or_init(|| match self.mesh_placement.as_deref() { + Some(placed) => placed.plan_mesh(q, &self.name), + None => self.display_plan_at(q).and_then(|plan| self.body.display_mesh_of(&plan).ok()).map(Arc::new), + }) .clone() } diff --git a/crates/doc/src/placed_mesh.rs b/crates/doc/src/placed_mesh.rs index 76c7243a4..f07d48e0c 100644 --- a/crates/doc/src/placed_mesh.rs +++ b/crates/doc/src/placed_mesh.rs @@ -2,6 +2,7 @@ //! source mesh and map it into each pose; retain the exact placed B-rep separately in ModelBody. use std::sync::{Arc, OnceLock}; +use solidcraft_geom::tess::TessPlan; use solidcraft_geom::{Mesh, Vec3}; use solidcraft_kernel::{self as kernel, Body}; @@ -11,6 +12,10 @@ use super::ModelBody; pub(super) struct PlacedMesh { body: Body, mesh: Arc>>, + /// The definition's display plans and their meshes by display quality (its own cells): + /// each placement draws them moved, so a part is planned once however often it is placed. + plans: Arc<[OnceLock>>; 4]>, + plan_meshes: Arc<[OnceLock>>; 4]>, transform: crate::Mat, pub(super) tolerance: f64, } @@ -26,16 +31,47 @@ impl PlacedMesh { Some(original) => Self { body: original.body.clone(), mesh: original.mesh.clone(), + plans: original.plans.clone(), + plan_meshes: original.plan_meshes.clone(), transform: crate::mat_mul(transform, &original.transform), tolerance: original.tolerance, }, - None => Self { body: source.body.clone(), mesh: source.mesh.clone(), transform: *transform, tolerance: source.display_tol() }, + None => Self { + body: source.body.clone(), + mesh: source.mesh.clone(), + plans: source.plan.clone(), + plan_meshes: source.plan_mesh.clone(), + transform: *transform, + tolerance: source.display_tol(), + }, }) } pub(super) fn mesh(&self) -> Arc { - let source = reference_mesh(&self.body, &self.mesh, self.tolerance); - Arc::new(Mesh { + Arc::new(self.moved(&reference_mesh(&self.body, &self.mesh, self.tolerance))) + } + + /// The definition's display plan at quality `q` (made once, in its own cell), moved here. + pub(super) fn plan(&self, q: crate::display_quality::DisplayQuality, name: &str) -> Option> { + let source = definition_plan(&self.body, self.plans.get(q.index())?, q, name)?; + Some(Arc::new(source.transformed(&self.transform))) + } + + /// The definition's display plan mesh at quality `q`, moved here. + pub(super) fn plan_mesh(&self, q: crate::display_quality::DisplayQuality, name: &str) -> Option> { + let cell = self.plan_meshes.get(q.index())?; + let source = cell + .get_or_init(|| { + let plan = definition_plan(&self.body, self.plans.get(q.index())?, q, name)?; + self.body.display_mesh_of(&plan).ok().map(Arc::new) + }) + .clone()?; + Some(Arc::new(self.moved(&source))) + } + + /// `source` (in the definition's place) moved by this placement. + fn moved(&self, source: &Mesh) -> Mesh { + Mesh { positions: source.positions.iter().map(|p| crate::apply_point(&self.transform, *p)).collect(), normals: source.normals.iter().map(|n| crate::apply_vector(&self.transform, *n)).collect(), edges: source.edges.iter().map(|edge| edge.iter().map(|p| crate::apply_point(&self.transform, *p)).collect()).collect(), @@ -45,10 +81,27 @@ impl PlacedMesh { seams: source.seams.clone(), smooth_edges: source.smooth_edges.clone(), sharp_edges: source.sharp_edges.clone(), - }) + } } } +/// The display plan of a definition `body` at quality `q`, made once in `cell`. +pub(super) fn definition_plan( + body: &Body, + cell: &OnceLock>>, + q: crate::display_quality::DisplayQuality, + name: &str, +) -> Option> { + cell.get_or_init(|| match body.display_plan_angular(q.chord(body.size()), q.angle()) { + Ok(plan) => Some(Arc::new(plan)), + Err(e) => { + log::debug!("{name}: no display plan ({e})"); + None + } + }) + .clone() +} + pub(super) fn reference_mesh(body: &Body, mesh: &OnceLock>, tolerance: f64) -> Arc { mesh.get_or_init(|| Arc::new(body.reference_display_mesh_angular(tolerance, kernel::DISPLAY_ANGLE).unwrap_or_default())).clone() } @@ -97,6 +150,57 @@ mod tests { assert!(Arc::ptr_eq(&mesh, &nested.mesh())); } + /// Placed parts share their definition's display plan (#3044): the definition is planned + /// once, every placement moves that plan, and a moved plan evaluates to the definition's + /// points moved, on every kind of surface (planes, revolved and spline surfaces). + #[test] + fn placed_parts_are_planned_once_and_draw_the_moved_plan() { + use crate::display_quality::DisplayQuality; + let q = DisplayQuality::parse("normal").unwrap(); + for body in [ + kernel::box_solid(Vec3::ZERO, Vec3::new(2., 3., 4.)).unwrap(), + kernel::cylinder(Vec3::new(1., 0., 0.), Vec3::Z, 2., 8.).unwrap(), + kernel::torus(Vec3::ZERO, 6., 1.5).unwrap(), + kernel::sphere(Vec3::new(0., 1., 2.), 3.).unwrap(), + ] { + let source = ModelBody::new("Part".into(), body, 1); + let a = crate::rigid(Vec3::new(10., 20., 30.), Vec3::ZERO, Vec3::Z, 0.7); + let b = crate::rigid(Vec3::new(-4., 5., 1.), Vec3::new(1., 1., 0.), Vec3::X, 1.1); + let placed: Vec = [a, b] + .iter() + .map(|m| { + let mut p = ModelBody::new("Copy".into(), kernel::transform_matrix(&source.body, *m).unwrap(), 1); + p.mesh_placement = Some(Arc::new(PlacedMesh::new(&source, m).unwrap())); + p + }) + .collect(); + assert!(source.plan.get(q.index()).unwrap().get().is_none()); + let plans: Vec<_> = placed.iter().map(|p| p.display_plan_at(q).unwrap()).collect(); + assert!(source.plan.get(q.index()).unwrap().get().is_some(), "placing plans the definition, in its own cell"); + let own = source.display_plan_at(q).unwrap(); + let local = own.evaluate(); + for (m, plan) in [a, b].iter().zip(&plans) { + assert!(!Arc::ptr_eq(plan, &own)); + let moved = plan.evaluate(); + assert_eq!(moved.triangles, local.triangles); + for (p, q) in local.positions.iter().zip(&moved.positions) { + assert!(crate::apply_point(m, *p).dist(*q) < 1e-9, "{p:?} -> {q:?}"); + } + for (n, k) in local.normals.iter().zip(&moved.normals) { + assert!(crate::apply_vector(m, *n).dist(*k) < 1e-9); + } + } + for (m, p) in [a, b].iter().zip(&placed) { + let mesh = p.plan_mesh_at(q).unwrap(); + let base = source.plan_mesh_at(q).unwrap(); + assert_eq!(mesh.triangles, base.triangles); + for (x, y) in base.positions.iter().zip(&mesh.positions) { + assert!(crate::apply_point(m, *x).dist(*y) < 1e-9); + } + } + } + } + #[test] fn world_instances_warm_one_definition_and_an_edit_replaces_it() { let mut doc = crate::Document::new("instances"); diff --git a/crates/geom/src/tess.rs b/crates/geom/src/tess.rs index 94d23b944..3bb3e47ac 100644 --- a/crates/geom/src/tess.rs +++ b/crates/geom/src/tess.rs @@ -109,6 +109,70 @@ impl TessPlan { pub fn vertex_count(&self) -> usize { self.faces.iter().map(|f| f.uv.len()).sum() } + + /// This plan for the body moved by the rotation and translation `m` (by columns, the + /// translation in `m[3]`): the same parameters and triangles on the moved surfaces, so a + /// part placed many times is planned once. Only for proper rigid motions (a reflection + /// would turn the triangles inside out; the caller checks). + pub fn transformed(&self, m: &[[f64; 4]; 4]) -> TessPlan { + let vector = |v: Vec3| { + Vec3::new( + m[0][0] * v.x + m[1][0] * v.y + m[2][0] * v.z, + m[0][1] * v.x + m[1][1] * v.y + m[2][1] * v.z, + m[0][2] * v.x + m[1][2] * v.y + m[2][2] * v.z, + ) + }; + let point = |p: Vec3| vector(p) + Vec3::new(m[3][0], m[3][1], m[3][2]); + let surfaces = self + .surfaces + .iter() + .map(|s| match s { + EvalSurface::Plane { origin, du, dv } => EvalSurface::Plane { origin: point(*origin), du: vector(*du), dv: vector(*dv) }, + EvalSurface::Nurbs { degree, knots, count, ctrl } => EvalSurface::Nurbs { + degree: *degree, + knots: knots.clone(), + count: *count, + // Homogeneous: the translation scales with the weight. + ctrl: ctrl + .iter() + .map(|c| { + let q = vector(Vec3::new(c[0], c[1], c[2])) + Vec3::new(m[3][0], m[3][1], m[3][2]) * c[3]; + [q.x, q.y, q.z, c[3]] + }) + .collect(), + }, + EvalSurface::Revolved { profile, origin, axis, transform, swap } => { + // `m` (as rows) after the surface's own affine map. + let r = |i: usize| [m[0][i], m[1][i], m[2][i], m[3][i]]; + let rows = [r(0), r(1), r(2)]; + let t = transform; + let composed = rows.map(|row| { + let mut out = [0.0; 4]; + for (j, slot) in out.iter_mut().enumerate() { + *slot = (0..3).map(|k| row[k] * t[k][j]).sum::() + if j == 3 { row[3] } else { 0.0 }; + } + out + }); + EvalSurface::Revolved { profile: profile.clone(), origin: *origin, axis: *axis, transform: composed, swap: *swap } + } + }) + .collect(); + let faces = self + .faces + .iter() + .map(|f| FacePlan { + fixed: f.fixed.iter().map(|p| point(*p)).collect(), + normals: f.normals.iter().map(|n| vector(*n)).collect(), + ..f.clone() + }) + .collect(); + TessPlan { + surfaces, + faces, + edges: self.edges.iter().map(|e| e.iter().map(|p| point(*p)).collect()).collect(), + edge_faces: self.edge_faces.clone(), + } + } } impl EvalCurve { @@ -312,6 +376,53 @@ mod tests { a.dist(b) <= tol } + /// A moved plan evaluates to the plan's points moved, on a rational spline surface (the + /// translation scales with each weight) and a revolved one (composed with its own map). + #[test] + fn a_transformed_plan_evaluates_to_the_moved_points() { + let (c, s) = (0.6f64.cos(), 0.6f64.sin()); + // Turned about z by 0.6 rad, then moved: by columns. + let m = [[c, s, 0.0, 0.0], [-s, c, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [5.0, -2.0, 7.0, 1.0]]; + let apply = |p: Vec3| Vec3::new(c * p.x - s * p.y + 5.0, s * p.x + c * p.y - 2.0, p.z + 7.0); + let w = std::f64::consts::FRAC_1_SQRT_2; + let nurbs = EvalSurface::Nurbs { + degree: [2, 1], + knots: [vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0], vec![0.0, 0.0, 1.0, 1.0]], + count: [3, 2], + ctrl: vec![[1.0, 0.0, 0.0, 1.0], [w, w, 0.0, w], [0.0, 1.0, 0.0, 1.0], [1.0, 0.0, 2.0, 1.0], [w, w, 2.0 * w, w], [0.0, 1.0, 2.0, 1.0]], + }; + let revolved = EvalSurface::Revolved { + profile: line(Vec3::new(2.0, 0.0, 0.0), Vec3::new(3.0, 0.0, 1.0)), + origin: Vec3::ZERO, + axis: Vec3::Z, + transform: [[1.0, 0.0, 0.0, 1.0], [0.0, 0.0, -1.0, 2.0], [0.0, 1.0, 0.0, 3.0]], + swap: false, + }; + let face = |i: u32| FacePlan { + face: i, + surface: Some(i), + uv: vec![[0.1, 0.2], [0.7, 0.4], [0.3, 0.9]], + fixed: vec![Vec3::new(1.0, 2.0, 3.0)], + triangles: vec![[0, 1, 2]], + ..Default::default() + }; + let plan = TessPlan { + surfaces: vec![nurbs, revolved], + faces: vec![face(0), face(1)], + edges: vec![vec![Vec3::new(1.0, 1.0, 1.0)]], + edge_faces: vec![vec![0, 1]], + }; + let (a, b) = (plan.evaluate(), plan.transformed(&m).evaluate()); + assert_eq!(a.triangles, b.triangles); + for (p, q) in a.positions.iter().zip(&b.positions) { + assert!(close(apply(*p), *q, 1e-12), "{p:?} -> {q:?}"); + } + for (n, k) in a.normals.iter().zip(&b.normals) { + assert!(close(apply(*n) - apply(Vec3::ZERO), *k, 1e-12)); + } + assert!(close(apply(a.edges[0][0]), b.edges[0][0], 1e-12)); + } + fn line(a: Vec3, b: Vec3) -> EvalCurve { EvalCurve { degree: 1, knots: vec![0.0, 0.0, 1.0, 1.0], ctrl: vec![[a.x, a.y, a.z, 1.0], [b.x, b.y, b.z, 1.0]] } } From adaac4d1b64bb7dafe8eee09fa7e1de0408c9bf5 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Tue, 20 Oct 2026 00:26:36 +0000 Subject: [PATCH 158/225] perf: STEP import reads and orients distinct parts in parallel (#2814) (#3046) Converting an assembly went one occurrence at a time: a part's solid was read from the file and oriented on the calling thread, and only runs of four or more solids in one representation used the workers. Each step now takes the next solids across occurrences and parts (up to 64, stopping where a part not yet oriented comes back), and the workers read and orient the new parts side by side, each taking the next one when it is done. Later instances still only place the part their first instance oriented. Co-authored-by: Claude Opus 5.5 --- crates/kernel/src/step_in/mod.rs | 133 ++++++++++++-------------- crates/kernel/src/step_in/parallel.rs | 113 +++++++++++++--------- crates/kernel/src/step_in/tests.rs | 86 +++++++++++++---- 3 files changed, 198 insertions(+), 134 deletions(-) diff --git a/crates/kernel/src/step_in/mod.rs b/crates/kernel/src/step_in/mod.rs index f40e44770..f95bee134 100644 --- a/crates/kernel/src/step_in/mod.rs +++ b/crates/kernel/src/step_in/mod.rs @@ -32,6 +32,8 @@ const MAX_BODIES: usize = 10_000; /// Most product occurrences and mapped representations visited (a shared sub-assembly used /// twice at every level would otherwise grow exponentially). const MAX_VISITS: usize = 100_000; +/// Most planned solids converted in one go (bounds the geometry held at once). +const MAX_WINDOW: usize = 64; /// Most representation entries walked while deciding which items are converted exactly once. A /// larger file keeps every conversion instead of paying for the walk. const MAX_CLOSURE_WORK: usize = 1 << 16; @@ -239,10 +241,6 @@ fn rigid_inverse(m: &mt::Matrix4) -> mt::Matrix4 { m.invert().unwrap_or_else(mt::Matrix4::identity) } -/// One converted representation item: the truck solid, whether its shells are closed, the -/// faces the file had, and the file face of each kernel face (band faces split into two). -type SolidEntry = (mt::Solid, bool, usize, Vec); - struct Reader { ex: Arc, units: HashMap, @@ -261,18 +259,18 @@ struct Reader { colors: HashMap, /// Opacity of styled items with a transparency (1 = opaque). opacity: HashMap, - /// Converted items (brep id → entry, or the error). Held behind `Arc` so the conversion is - /// handed on without copying wherever the file cannot ask for the item a second time. - solids: HashMap, String>>, - /// Items the file converts exactly once (see `index`): keeping their solids would hold a + /// Items that gave no part: reported once when the file could not be read, else (the + /// body could not be made) at every instance, as the message says. + unreadable: HashMap>, + /// Items the file converts exactly once (see `index`): keeping their parts would hold a /// second copy of the whole import for nothing. once: HashSet, /// An item placed more than once: its first instance's display, shared by the later ones /// (with the placement that first instance had), so the part is meshed once. shown: HashMap, mt::Matrix4)>, - /// An item placed more than once: its body oriented where the file defines it, so each + /// An item placed more than once: read and oriented where the file defines it, so each /// later instance is only placed (orienting meshes the whole part). - oriented: HashMap, + oriented: HashMap>, used_items: HashSet, /// Items already instanced for the product being read. node_items: HashSet, @@ -312,7 +310,7 @@ impl Reader { placements: HashMap::new(), colors: HashMap::new(), opacity: HashMap::new(), - solids: HashMap::new(), + unreadable: HashMap::new(), once: HashSet::new(), shown: HashMap::new(), oriented: HashMap::new(), @@ -598,38 +596,6 @@ impl Reader { mapped.map(|rep| self.rep_closure(&[rep])).unwrap_or_default() } - fn item_solid(&mut self, item: u64, u: Units) -> Option> { - if let Some(r) = self.solids.get(&item) { - return r.as_ref().ok().cloned(); - } - let cx = Ctx { ex: &self.ex, len: u.len, ang: u.ang, tol: u.tol }; - let r = match guard("step brep", || brep::read_item(&cx, item).map_err(KernelError::Failed)) { - Ok(out) => { - let label = self.label(item); - for f in &out.failed { - self.warn(format!("{label}: {f}")); - } - if !out.closed { - self.warn(format!("{label}: imported as an open body (the shell is not closed)")); - } - Ok((out.solid, out.closed, out.file_faces, out.face_origin)) - } - Err(e) => { - let label = self.label(item); - let msg = e.to_string().trim_start_matches("the operation failed: ").to_string(); - self.warn(format!("{label}: not imported: {msg}")); - Err(msg) - } - }; - let entry = r.map(Arc::new); - // An item the file converts exactly once hands its only reference on and keeps no copy; - // anything it may ask for again keeps its conversion. - if !self.once.contains(&item) { - self.solids.insert(item, entry.clone()); - } - entry.ok() - } - fn label(&self, item: u64) -> String { let name = self.ex.get(item).and_then(|e| e.params().first()).and_then(Param::as_str).unwrap_or("").trim().to_string(); if name.is_empty() { format!("solid #{item}") } else { format!("solid '{name}'") } @@ -726,43 +692,66 @@ impl Reader { return false; } let first = self.converted; - let id = self.plan[first].batch; + // The next solids, across instances and parts, converted together: parts still to + // orient are shared out between the workers. A part that comes back within the window + // waits for the next one, which places the orientation its first instance found. let mut last = first + 1; - while !single && last < self.plan.len() && self.plan[last].batch == id { - last += 1; + if !single { + let mut fresh: HashSet = self.plan.get(first).map(|p| p.item).into_iter().collect(); + while let Some(p) = self.plan.get(last) + && last - first < MAX_WINDOW + { + if !self.oriented.contains_key(&p.item) && !fresh.insert(p.item) { + break; + } + last += 1; + } } self.converted = last; let ex = self.ex.clone(); let mut sources = Vec::new(); - let mut solids = Vec::new(); + let mut jobs = Vec::new(); for i in first..last { - let (item, u) = (self.plan[i].item, self.plan[i].units); self.made.push(None); - let Some(entry) = self.item_solid(item, u) else { continue }; - // A one-use item is the only reference to its entry, so the solid moves - // out; an item whose conversion is cached for a later instance needs its - // own copy. - let (solid, closed, file_faces, face_origin) = match Arc::try_unwrap(entry) { - Ok(entry) => entry, - Err(shared) => (*shared).clone(), - }; - sources.push((i, item, closed, file_faces, face_origin)); + let Some(p) = self.plan.get(i) else { continue }; + let (item, units) = (p.item, p.units); + if let Some(again) = self.unreadable.get(&item) { + if let Some(msg) = again.clone() { + let label = self.label(item); + self.warn(format!("{label}: not imported: {msg}")); + } + continue; + } let source = match self.oriented.get(&item) { - Some(body) => parallel::Source::Oriented(body.clone()), - None => parallel::Source::Solid(solid), + Some(part) => parallel::Source::Oriented(part.clone()), + None => parallel::Source::Item { item, units }, }; - solids.push(parallel::Job { source, check_mesh: !self.unmeshed_checked.contains(&item) }); + let placement = self.batches.get(p.batch).map_or(mt::Matrix4::from_scale(1.0), |b| b.m); + sources.push((i, item)); + jobs.push(parallel::Job { source, placement, check_mesh: !self.unmeshed_checked.contains(&item) }); } - let Some(batch) = self.batches.get(id) else { return true }; - let (m, path, product, instance) = (batch.m, batch.path.clone(), batch.product.clone(), batch.instance.clone()); - let prepared = parallel::bodies(&solids, &m, self.workers); - for ((i, item, closed, file_faces, face_origin), body) in sources.into_iter().zip(prepared) { + // Reading and orienting new parts is shared out between the workers. + let prepared = parallel::bodies(&ex, &jobs, self.workers); + for ((i, item), made) in sources.into_iter().zip(prepared) { let Some(e) = ex.get(item) else { continue }; - match body { - Ok((body, missing, oriented)) => { - if !self.once.contains(&item) { - self.oriented.entry(item).or_insert(oriented); + let Some(batch) = self.plan.get(i).and_then(|p| self.batches.get(p.batch)) else { continue }; + let (m, path, product, instance) = (batch.m, batch.path.clone(), batch.product.clone(), batch.instance.clone()); + match made { + Ok(parallel::Made { body, missing, part, read }) => { + // What the read of the item found, reported once. + if let Some(failed) = read { + let label = self.label(item); + for f in &failed { + self.warn(format!("{label}: {f}")); + } + if !part.closed { + self.warn(format!("{label}: imported as an open body (the shell is not closed)")); + } } + if !self.once.contains(&item) { + self.oriented.entry(item).or_insert_with(|| part.clone()); + } + let (closed, file_faces, face_origin) = (part.closed, part.file_faces, part.face_origin.clone()); let own = e.params().first().and_then(Param::as_str).unwrap_or("").trim().to_string(); let name = if own.is_empty() { product.clone() } else { own }; // Faces the mesher gives up on (or that the budget cut short) are reported. @@ -811,9 +800,13 @@ impl Reader { face_origin, }); } - Err(err) => { + Err(parallel::Failure { read, msg }) => { let label = self.label(item); - self.warn(format!("{label}: not imported: {err}")); + self.warn(format!("{label}: not imported: {msg}")); + // Later instances don't read the item again. + if !self.oriented.contains_key(&item) { + self.unreadable.insert(item, (!read).then_some(msg)); + } } } } diff --git a/crates/kernel/src/step_in/parallel.rs b/crates/kernel/src/step_in/parallel.rs index 2d9854eb6..c8327ac98 100644 --- a/crates/kernel/src/step_in/parallel.rs +++ b/crates/kernel/src/step_in/parallel.rs @@ -1,21 +1,51 @@ //! Bounded desktop preparation of independent imported bodies, collected in file order. -use super::{Body, Result, guard, mt}; +use std::sync::Arc; + +use super::{Body, Ctx, Exchange, KernelError, Units, brep, guard, mt}; pub(super) struct Job { pub source: Source, + /// Where the body goes (its instance's placement in the assembly). + pub placement: mt::Matrix4, pub check_mesh: bool, } -/// What a job places: a solid read from the file (oriented here), or a body an earlier -/// instance of the same item already oriented. +/// What a job places: a solid item to read from the file (and orient), or a part an earlier +/// instance of the same item already read and oriented. pub(super) enum Source { - Solid(mt::Solid), - Oriented(Body), + Item { item: u64, units: Units }, + Oriented(Arc), } -/// The placed body, its faces the mesher missed, and the body oriented where the file defines -/// it (for later instances of the same item). -type Prepared = Result<(Body, usize, Body)>; +/// A solid item read and oriented where the file defines it, placed by each of its instances. +pub(super) struct Part { + pub body: Body, + /// The shells are closed. + pub closed: bool, + /// Faces the file had. + pub file_faces: usize, + /// The file face of each kernel face. + pub face_origin: Vec, +} + +/// A prepared instance. +pub(super) struct Made { + /// The part, placed. + pub body: Body, + /// Faces the mesher missed (counted when the job asked). + pub missing: usize, + pub part: Arc, + /// This job read the item: the faces the read left out, with the reason. + pub read: Option>, +} + +/// Why a job made no body: the item could not be read (`read`), or its body not made. +pub(super) struct Failure { + pub read: bool, + pub msg: String, +} + +type Prepared = std::result::Result; pub(super) fn workers() -> usize { #[cfg(not(target_arch = "wasm32"))] @@ -28,49 +58,40 @@ pub(super) fn workers() -> usize { } } -fn prepare(job: &Job, placement: &mt::Matrix4) -> Prepared { +fn prepare(ex: &Exchange, job: &Job) -> Prepared { + let (part, read) = match &job.source { + Source::Oriented(part) => (part.clone(), None), + Source::Item { item, units } => { + let cx = Ctx { ex, len: units.len, ang: units.ang, tol: units.tol }; + let out = guard("step brep", || brep::read_item(&cx, *item).map_err(KernelError::Failed)) + .map_err(|e| Failure { read: true, msg: e.to_string().trim_start_matches("the operation failed: ").to_string() })?; + // Orient once where the file defines the solid; each placement then takes its + // orientation from the matrix instead of meshing the whole part again. + let body = guard("STEP body preparation", || Body::new(out.solid)).map_err(|e| Failure { read: false, msg: e.to_string() })?; + (Arc::new(Part { body, closed: out.closed, file_faces: out.file_faces, face_origin: out.face_origin }), Some(out.failed)) + } + }; guard("STEP body preparation", || { - // Orient once where the file defines the solid; each placement then takes its - // orientation from the matrix instead of meshing the whole part again. - let oriented = match &job.source { - Source::Solid(solid) => Body::new(solid.clone())?, - Source::Oriented(body) => body.clone(), - }; - let body = oriented.placed(placement)?; + let body = part.body.placed(&job.placement)?; // Counted where the orientation mesh already counted them (a placement meshes the // same faces). - let missing = if job.check_mesh { oriented.unmeshed_faces() } else { 0 }; - Ok((body, missing, oriented)) + let missing = if job.check_mesh { part.body.unmeshed_faces() } else { 0 }; + Ok((body, missing)) }) + .map(|(body, missing)| Made { body, missing, part, read }) + .map_err(|e| Failure { read: false, msg: e.to_string() }) } -pub(super) fn bodies(solids: &[Job], placement: &mt::Matrix4, workers: usize) -> Vec { - #[cfg(not(target_arch = "wasm32"))] - if solids.len() >= 4 && workers > 1 { - return std::thread::scope(|scope| { - let size = solids.len().div_ceil(workers.min(8)); - let mut pending = Vec::new(); - for chunk in solids.chunks(size) { - let handle = std::thread::Builder::new() - .name("step-body".into()) - .spawn_scoped(scope, move || chunk.iter().map(|solid| prepare(solid, placement)).collect::>()) - .ok(); - pending.push((chunk, handle)); - } - let mut output = Vec::with_capacity(solids.len()); - for (chunk, handle) in pending { - match handle { - Some(handle) => match handle.join() { - Ok(results) => output.extend(results), - Err(_) => output.extend(chunk.iter().map(|_| Err(crate::KernelError::Internal("STEP body worker panicked".into())))), - }, - // Resource exhaustion must not lose an import: use the serial path. - None => output.extend(chunk.iter().map(|solid| prepare(solid, placement))), - } - } - output - }); +/// Prepare `jobs`, the results in the jobs' order. Solids still to read and orient (the slow +/// part) are shared out between up to `workers` threads, each taking the next job when it is +/// done with one, so one large part does not hold up the rest. +pub(super) fn bodies(ex: &Exchange, jobs: &[Job], workers: usize) -> Vec { + let to_orient = jobs.iter().filter(|j| matches!(j.source, Source::Item { .. })).count(); + if to_orient > 1 && workers > 1 { + return crate::par::map_on_threads(jobs, workers.min(8).min(to_orient), |job| prepare(ex, job)) + .into_iter() + .map(|r| r.unwrap_or_else(|| Err(Failure { read: false, msg: "STEP body worker panicked".into() }))) + .collect(); } - let _ = workers; - solids.iter().map(|solid| prepare(solid, placement)).collect() + jobs.iter().map(|job| prepare(ex, job)).collect() } diff --git a/crates/kernel/src/step_in/tests.rs b/crates/kernel/src/step_in/tests.rs index 2f7791915..bba7fbf4b 100644 --- a/crates/kernel/src/step_in/tests.rs +++ b/crates/kernel/src/step_in/tests.rs @@ -240,20 +240,30 @@ fn parallel_import_retains_units_order_sources_and_partial_failure_across_batche #[test] fn parallel_body_preparation_reports_errors_in_place_and_preserves_placement() { let body = cylinder(Vec3::new(2.0, 2.0, 0.0), Vec3::Z, 2.0, 4.0).unwrap(); - let solids = vec![body.solid.as_ref().clone(), mt::Solid::new(Vec::new()), body.solid.as_ref().clone(), body.solid.as_ref().clone()]; + let ex = p21::parse(&step_export(&[&body], "test").unwrap()).unwrap(); + let solid = *ex.entities.iter().find(|(_, e)| e.name() == "MANIFOLD_SOLID_BREP").map(|(id, _)| id).unwrap(); + let units = DEFAULT_UNITS; let placement = mt::Matrix4::from_translation(mt::Vector3::new(10.0, 20.0, 30.0)); - let jobs: Vec<_> = solids.into_iter().map(|solid| parallel::Job { source: parallel::Source::Solid(solid), check_mesh: true }).collect(); - let serial = parallel::bodies(&jobs, &placement, 1); - let threaded = parallel::bodies(&jobs, &placement, 4); + // The second item is not in the file. + let jobs: Vec<_> = [solid, 999_999_999, solid, solid] + .into_iter() + .map(|item| parallel::Job { source: parallel::Source::Item { item, units }, placement, check_mesh: true }) + .collect(); + let serial = parallel::bodies(&ex, &jobs, 1); + let threaded = parallel::bodies(&ex, &jobs, 4); assert_eq!(serial.len(), 4); assert_eq!(threaded.len(), 4); for (index, (a, b)) in serial.iter().zip(&threaded).enumerate() { if index == 1 { - assert_eq!(a.as_ref().unwrap_err(), b.as_ref().unwrap_err()); + let (Err(a), Err(b)) = (a, b) else { panic!("job 1 has no item") }; + assert!(a.read && b.read); + assert_eq!(a.msg, b.msg); } else { - assert_eq!(a.as_ref().unwrap().1, b.as_ref().unwrap().1); - let a = measure(&a.as_ref().unwrap().0).unwrap(); - let b = measure(&b.as_ref().unwrap().0).unwrap(); + let (Ok(a), Ok(b)) = (a, b) else { panic!("job {index} failed") }; + assert_eq!(a.missing, b.missing); + assert!(a.read.is_some() && b.read.is_some(), "each job read its item"); + let a = measure(&a.body).unwrap(); + let b = measure(&b.body).unwrap(); assert_same_measure(&a, &b); // Curved bounds come from the measurement tessellation, not analytic extrema. assert!(a.bbox.min.dist(Vec3::new(10.0, 20.0, 30.0)) < 1e-3); @@ -296,14 +306,14 @@ fn parallel_import_does_not_prepare_past_body_budget_with_duplicates_or_mapped_i reader.node_items.insert(2000); let mut out = Vec::new(); reader.rep_bodies(60, &mt::Matrix4::from_scale(1.0), &[], "Budget", None, &mut out, 0); - assert!(reader.solids.is_empty(), "the walk only plans the solids"); + assert!(reader.oriented.is_empty() && reader.unreadable.is_empty(), "the walk only plans the solids"); while reader.convert_next(workers == 1) {} let out = reader.remap(&out); assert_eq!(reader.bodies.len(), MAX_BODIES); assert_eq!(out, vec![MAX_BODIES - 2, MAX_BODIES - 1]); assert_eq!(reader.bodies.last().unwrap().name, "Second"); - assert_eq!(reader.solids.len(), 2); - assert!(!reader.solids.contains_key(&2003)); + assert_eq!(reader.oriented.len(), 2); + assert!(!reader.oriented.contains_key(&2003) && !reader.unreadable.contains_key(&2003)); assert!(!reader.used_items.contains(&3000)); assert_eq!(reader.warnings.len(), 1); assert!(reader.warnings.keys().next().unwrap().contains("more than")); @@ -656,29 +666,44 @@ fn hand_written_assembly() { /// The cube part (in cm) placed `n` times in a millimetre assembly, each instance moved along X /// and turned about Z. fn instanced_assembly(n: u64) -> String { + instanced_assembly_of(1, n) +} + +/// [`instanced_assembly`] with `parts` distinct parts (the cube solid under different items and +/// products), instance `k` placing part `k % parts`. +fn instanced_assembly_of(parts: u64, n: u64) -> String { let mut t = String::from(HEAD); t += "#8=PRODUCT_DEFINITION_CONTEXT('part definition',#9,'design');\n#9=APPLICATION_CONTEXT('');\n"; t += &cube_entities(); t += &context(20, "(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.CENTI.,.METRE.))"); t += &context(30, "(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.))"); - t += &product(50, "Block"); t += &product(70, "Assembly"); - t += "#60=ADVANCED_BREP_SHAPE_REPRESENTATION('',(#101,#65),#20);\n#61=SHAPE_DEFINITION_REPRESENTATION(#54,#60);\n"; - t += "#65=AXIS2_PLACEMENT_3D('',#66,$,$);\n#66=CARTESIAN_POINT('',(0.,0.,0.));\n"; + for p in 0..parts { + let pd = 1000 + p * 100; + t += &product(pd, if p == 0 { "Block".to_string() } else { format!("Block{p}") }.as_str()); + let item = if p == 0 { 101 } else { pd + 20 }; + if p > 0 { + t += &format!("#{item}=MANIFOLD_SOLID_BREP('Cube{p}',#100);\n"); + } + t += &format!("#{}=ADVANCED_BREP_SHAPE_REPRESENTATION('',(#{item},#{}),#20);\n", pd + 10, pd + 15); + t += &format!("#{}=SHAPE_DEFINITION_REPRESENTATION(#{},#{});\n", pd + 11, pd + 4, pd + 10); + t += &format!("#{}=AXIS2_PLACEMENT_3D('',#{},$,$);\n#{}=CARTESIAN_POINT('',(0.,0.,0.));\n", pd + 15, pd + 16, pd + 16); + } let items: Vec = (0..n).map(|k| format!("#{}", 3000 + k * 10)).collect(); t += &format!("#80=SHAPE_REPRESENTATION('',({}),#30);\n#88=SHAPE_DEFINITION_REPRESENTATION(#74,#80);\n", items.join(",")); for k in 0..n { - let (a, turn) = (3000 + k * 10, k as f64 * 0.7); + let (a, turn, pd) = (3000 + k * 10, k as f64 * 0.7, 1000 + (k % parts) * 100); t += &format!("#{a}=AXIS2_PLACEMENT_3D('',#{},#{},#{});\n", a + 1, a + 2, a + 3); t += &format!("#{}=CARTESIAN_POINT('',({}.,0.,0.));\n", a + 1, 50 * k); t += &format!("#{}=DIRECTION('',(0.,0.,1.));\n#{}=DIRECTION('',({},{},0.));\n", a + 2, a + 3, turn.cos(), turn.sin()); let u = 6000 + k * 10; - t += &format!("#{u}=NEXT_ASSEMBLY_USAGE_OCCURRENCE('{k}','Block:{k}','',#70,#50,$);\n"); + t += &format!("#{u}=NEXT_ASSEMBLY_USAGE_OCCURRENCE('{k}','Block:{k}','',#70,#{pd},$);\n"); t += &format!("#{}=PRODUCT_DEFINITION_SHAPE('','',#{u});\n", u + 1); - t += &format!("#{}=ITEM_DEFINED_TRANSFORMATION('','',#65,#{a});\n", u + 2); + t += &format!("#{}=ITEM_DEFINED_TRANSFORMATION('','',#{},#{a});\n", u + 2, pd + 15); t += &format!( - "#{}=(REPRESENTATION_RELATIONSHIP('','',#60,#80)REPRESENTATION_RELATIONSHIP_WITH_TRANSFORMATION(#{})SHAPE_REPRESENTATION_RELATIONSHIP());\n", + "#{}=(REPRESENTATION_RELATIONSHIP('','',#{},#80)REPRESENTATION_RELATIONSHIP_WITH_TRANSFORMATION(#{})SHAPE_REPRESENTATION_RELATIONSHIP());\n", u + 3, + pd + 10, u + 2 ); t += &format!("#{}=CONTEXT_DEPENDENT_SHAPE_REPRESENTATION(#{},#{});\n", u + 4, u + 3, u + 1); @@ -710,6 +735,31 @@ fn instanced_parts_are_oriented_once() { assert_same_import(&imp, &step_import_with_workers(&t, 8).unwrap()); } +/// Distinct parts are oriented together, not one occurrence at a time: an assembly placing +/// two parts in turn converts in a few steps of many solids (the first finds both parts' +/// orientations side by side on the workers, the next places every other instance), where +/// converting instance by instance took one step each. +#[test] +fn distinct_parts_convert_together_across_instances() { + let n = 24; + let t = instanced_assembly_of(2, n); + let mut reading = StepReading::with_workers(&t, 8).unwrap(); + let mut steps = 0; + while reading.step() { + steps += 1; + } + assert_eq!(steps, 2, "both parts in the first step, every other instance in the second"); + let threaded = reading.finish().unwrap(); + assert_eq!(threaded.bodies.len(), n as usize); + assert!(threaded.warnings.is_empty(), "{:?}", threaded.warnings); + crate::body::ORIENTED.with(|c| c.set(0)); + let serial = step_import_with_workers(&t, 1).unwrap(); + assert_eq!(crate::body::ORIENTED.with(|c| c.get()), 2, "two parts"); + assert_same_import(&serial, &threaded); + assert_eq!(threaded.bodies[1].name, "Cube1"); + assert_eq!(threaded.bodies[1].path, vec!["Assembly".to_string(), "Block1".to_string()]); +} + /// A part an assembly places twice is meshed once: the second instance shows the first one's /// display mesh, placed (the same triangles and faces, at its own place), and keeps its own /// placed geometry for everything else. From 2de99c728e2cde33ca7ffc850d873cc523c5f007 Mon Sep 17 00:00:00 2001 From: JEREMY Date: Tue, 20 Oct 2026 01:28:34 +0000 Subject: [PATCH 159/225] Sheet metal: a corner relief no longer depends on the order the corners are cut in (#3280) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Sheet metal: a corner relief no longer depends on the order the corners are cut in The corner reliefs are planned against the base as it is before any of them is cut, and the two reliefs at the ends of one edge are compared with each other. Before, every relief was cut into the base as it went, so the corner after it saw the relief of the corner before it: the square relief reaches further from its corner than the round one does (4 / cos(α / 2) against 4), so on a short edge it was left out where the round one was cut, and which of the two corners kept its relief depended on the order the flanges were made in. The reliefs themselves are unchanged: a round about the corner through the angle the base fills there, or the square with that side (a kite where the corner is not square, its cuts square to the two edges). What is new is that they are planned first and cut together, so that a corner's relief depends on the base and on the other reliefs, and not on the order they are cut in. Two reliefs that would overlap are still refused, now with a note that says so. Covered: the four relief shapes at corners of 60° and 120°, with the flanges of equal and of unequal height, through the kernel and through the engine (where the flat pattern and the DXF keep one clean loop). Co-Authored-By: Claude Code * Sheet metal: cover the corner reliefs at a corner that is not square The engine and the UI had no test at all for a base whose corners are 60° and 120°: the flat pattern, the DXF, the unfold and the rule manager's own square relief were all untested there. They work; this says so. Co-Authored-By: Claude Code * Sheet metal: say what happens when a corner relief is left out The guide now says that the reliefs at the corners of one edge are cut together, and that two of them that would overlap leave the second one out. A relief that cannot be cut is reported, not dropped. Co-Authored-By: Claude Code * Sheet metal: write the corner relief's expected corners out The engine test hard-coded the corners of the trimmed base; it works them out instead, and the numbers the test and the sketch share are written with the precision they need. Co-Authored-By: Claude Code --------- Co-authored-by: jeremymiribung-blip Co-authored-by: Claude Code --- crates/doc/src/sheet.rs | 298 ++++++++++++++++++++-- crates/engine/src/cmd/sheet_tests.rs | 132 ++++++++++ crates/ui-egui/src/dialogs_sheet_tests.rs | 59 +++++ docs/book/src/guide/sheet-metal.md | 4 +- 4 files changed, 472 insertions(+), 21 deletions(-) diff --git a/crates/doc/src/sheet.rs b/crates/doc/src/sheet.rs index 22b4ca0d0..c59b150ae 100644 --- a/crates/doc/src/sheet.rs +++ b/crates/doc/src/sheet.rs @@ -740,6 +740,10 @@ const MIN_CORNER_RELIEF: f64 = 0.01; /// The narrowest bend relief that is cut: a narrower one would leave hairline edges. const MIN_BEND_RELIEF: f64 = 0.01; +/// How many straight pieces a round corner relief's arc is measured in, when the region it takes +/// out of the base is worked out (see [`SheetBody::plan_relief`]). +const RELIEF_ARC_STEPS: usize = 64; + /// Two bends on the base meeting at a corner (see [`SheetBody::corners`]): flanges `a` and `b`, /// which end of each (false = the end at `p`), and the corner point (flat coordinates). #[derive(Clone, Copy, Debug)] @@ -756,6 +760,16 @@ fn corners_of(r: &Region2) -> Vec { dedup(&r.outer.ccw().polyline(1e-3)) } +/// A corner relief planned but not yet cut (see [`SheetBody::plan_relief`]): the corner it is +/// for, the segments that cut the base's corner, and the region they take out of it (the +/// polygon, counter-clockwise, the two reliefs of two corners are compared on). +#[derive(Clone, Debug)] +struct PlannedRelief { + corner: Corner, + segs: Vec, + cut: Vec, +} + /// The area two convex counter-clockwise polygons share. fn convex_overlap(a: &[Vec2], b: &[Vec2]) -> f64 { let mut poly = a.to_vec(); @@ -771,6 +785,16 @@ fn convex_overlap(a: &[Vec2], b: &[Vec2]) -> f64 { signed_area(&poly).abs() } +/// A polygon counter-clockwise, so that the two of them can be compared (see +/// [`convex_overlap`]). +fn ccw(p: &[Vec2]) -> Vec { + let mut q = p.to_vec(); + if signed_area(&q) < 0.0 { + q.reverse(); + } + q +} + /// How wide a strip two flat pieces may share and still only touch. A flange's bend starts on /// its parent's far edge at a point snapped to the 1e-9 mm grid, so where that edge runs at a /// slant to the axes the two share a sliver whose area grows with the edge's length. @@ -2821,9 +2845,38 @@ impl SheetBody { ReliefShape::Notch => {} // The reliefs come last: they move the bends' ends, which is how the corners were found. ReliefShape::Round | ReliefShape::Rectangular => { + // Every corner's relief is planned against the base as it is now, before any of + // them is cut, so that a corner's relief does not depend on the order the corners + // are cut in. + let mut planned = Vec::with_capacity(corners.len()); for k in corners { - if let Err(why) = self.relieve_corner(k, corners, shape, size) { - notes.push(format!("no corner relief at {}: {why}", self.shown(k.c))); + match self.plan_relief(k, corners, shape, size) { + Ok(Some(p)) => planned.push(p), + Ok(None) => {} + Err(why) => notes.push(format!("no corner relief at {}: {why}", self.shown(k.c))), + } + } + // The reliefs at the two ends of one edge must not overlap: the one planned later + // is left out, with a note. + let mut kept: Vec = Vec::with_capacity(planned.len()); + for p in planned { + let mut clash = None; + for q in &kept { + if convex_overlap(&q.cut, &p.cut) > 1e-9 { + clash = Some(q.corner.c); + break; + } + } + match clash { + Some(at) => { + notes.push(format!("no corner relief at {}: it would overlap the relief at {}", self.shown(p.corner.c), self.shown(at))) + } + None => kept.push(p), + } + } + for p in &kept { + if let Err(why) = self.cut_relief(p) { + notes.push(format!("no corner relief at {}: {why}", self.shown(p.corner.c))); } } } @@ -2998,17 +3051,16 @@ impl SheetBody { Ok(()) } - /// Cut a relief `size` across where two bends meet at a corner of the base, `size / 2` - /// from the corner along both edges: a round about the corner through the angle the base - /// fills there, or the square with that side (a kite where the corner isn't square, its - /// cuts square to the two edges). The base's edges then start that far from the corner, so - /// both bends stop there, cut straight across (`zone_span`): their ends stay exact arcs, - /// the round runs on into them tangentially, and the bend table gets the shorter bends. - /// The flange panels keep the ends `close_corner` gave them. A relief too small to cut, one - /// that would leave nothing of an edge it starts on (with the relief at that edge's other - /// end, where there is one), or one reaching as far from the corner as another edge of the - /// base is, is refused with the reason. - fn relieve_corner(&mut self, k: &Corner, corners: &[Corner], shape: ReliefShape, size: f64) -> std::result::Result<(), String> { + /// Plan the relief of size `size` at the corner `k`: the segments that cut the base's corner + /// and the region they take out of it. A relief `size` across is cut `size / 2` from the + /// corner along both edges: a round about the corner through the angle the base fills there, + /// or the square with that side (a kite where the corner isn't square, its cuts square to the + /// two edges). `None` where the corner is not one of the base's (the flanges turn away from + /// each other), and the reason why no relief is cut where none fits: a relief too small to + /// cut, one that would leave nothing of an edge it starts on (with the relief at that edge's + /// other end, where there is one), or one reaching as far from the corner as another edge of + /// the base is. + fn plan_relief(&self, k: &Corner, corners: &[Corner], shape: ReliefShape, size: f64) -> std::result::Result, String> { if !(size >= MIN_CORNER_RELIEF) { return Err(format!("the relief size {size:.4} mm is below {MIN_CORNER_RELIEF} mm")); } @@ -3030,7 +3082,7 @@ impl SheetBody { let alpha = db.cross(da).atan2(db.dot(da)); if !(alpha > 1e-6 && alpha < std::f64::consts::PI - 1e-6) { // An inside corner of the base: the flanges turn away from each other. - return Ok(()); + return Ok(None); } // Both bends must keep some length. An edge whose far end is another of the corners has // to hold a relief there too, so the reliefs at its two ends fit or are left out together. @@ -3041,14 +3093,13 @@ impl SheetBody { // The relief from the edge that ends at the corner to the one that starts there, and // how far from the corner it reaches. let (relief, reach) = match shape { - ReliefShape::Notch | ReliefShape::Tear => return Ok(()), + ReliefShape::Notch | ReliefShape::Tear => return Ok(None), ReliefShape::Round => (vec![Seg2::Arc { center: c, radius: r, start: da.angle(), sweep: -alpha }], r), ReliefShape::Rectangular => { let x = snap(c + (da + db) * (r / (1.0 + da.dot(db)))); (vec![Seg2::Line { a: snap(c + da * r), b: x }, Seg2::Line { a: x, b: snap(c + db * r) }], x.dist(c)) } }; - let (Some(start), Some(end)) = (relief.first().map(Seg2::start), relief.last().map(Seg2::end)) else { return Ok(()) }; // The rest of the outline must stay clear of it. let clear = segs.iter().enumerate().filter(|(e, _)| *e != i && *e != j).all(|(_, s)| { s.polyline(1e-3).windows(2).all(|w| { @@ -3060,13 +3111,45 @@ impl SheetBody { if !clear { return Err(format!("a relief {size:.3} mm across reaches {reach:.3} mm from the corner, where another edge of the base is nearer")); } - let mut outer = Vec::with_capacity(n + relief.len()); + // The region the relief takes out of the base: the corner, the two edges it takes along + // and the cut between them. The round one is a sector of the circle about the corner, the + // square one the kite with that side. + let cut = match shape { + ReliefShape::Round => { + let mut poly = vec![c, c + da * r]; + for k in 1..RELIEF_ARC_STEPS { + poly.push(c + Vec2::from_angle(da.angle() - alpha * (k as f64) / (RELIEF_ARC_STEPS as f64)) * r); + } + poly.push(c + db * r); + poly + } + _ => vec![c, c + da * r, snap(c + (da + db) * (r / (1.0 + da.dot(db)))), c + db * r], + }; + Ok(Some(PlannedRelief { corner: *k, segs: relief, cut: ccw(&cut) })) + } + + /// Cut a planned relief into the base: its edges then start that far from the corner, so + /// both bends stop there, cut straight across (`zone_span`): their ends stay exact arcs, the + /// round runs on into them tangentially, and the bend table gets the shorter bends. The + /// flange panels keep the ends `close_corner` gave them. + fn cut_relief(&mut self, p: &PlannedRelief) -> std::result::Result<(), String> { + let k = &p.corner; + let segs = self.base.outer.ccw().segs; + let n = segs.len(); + let at_corner = + |i: usize| segs.get(i).is_some_and(|s| s.end().dist(k.c) < 1e-6) && segs.get((i + 1) % n).is_some_and(|s| s.start().dist(k.c) < 1e-6); + let Some(i) = (0..n).find(|&i| at_corner(i)) else { return Err("the bends don't meet at a corner of the base".into()) }; + let j = (i + 1) % n; + let (Some(start), Some(end)) = (p.segs.first().map(Seg2::start), p.segs.last().map(Seg2::end)) else { + return Err("the relief has no cut".into()); + }; + let mut outer = Vec::with_capacity(n + p.segs.len()); for (e, s) in segs.iter().enumerate() { if e == i { - outer.push(Seg2::Line { a: pa, b: start }); - outer.extend(relief.iter().copied()); + outer.push(Seg2::Line { a: s.start(), b: start }); + outer.extend(p.segs.iter().copied()); } else if e == j { - outer.push(Seg2::Line { a: end, b: pb }); + outer.push(Seg2::Line { a: end, b: s.end() }); } else { outer.push(*s); } @@ -5421,6 +5504,181 @@ mod tests { } } + /// A rhombus of 120 and 90 long sides whose corners are 60° and 120°: the two at 60° and the + /// two at 120°, the origin among them. + fn rhombus() -> Region2 { + let u = Vec2::from_angle(std::f64::consts::FRAC_PI_3); + let pts = [Vec2::new(0.0, 0.0), Vec2::new(120.0, 0.0), Vec2::new(120.0, 0.0) + u * 90.0, u * 90.0]; + Region2 { outer: Loop2::polygon(&pts).ccw(), holes: vec![] } + } + + /// The rhombus' four flanges, one on each edge, at `angles` (degrees) and `heights`. + fn rhombus_flanges(rv: &RuleValues, angles: [f64; 4], heights: [f64; 4]) -> (SheetBody, Vec) { + let u = Vec2::from_angle(std::f64::consts::FRAC_PI_3); + let picks = [ + Vec3::new(60.0, 0.0, 2.0), + Vec3::new(120.0 + u.x * 45.0, u.y * 45.0, 2.0), + Vec3::new(60.0 + u.x * 90.0, u.y * 90.0, 2.0), + Vec3::new(u.x * 45.0, u.y * 45.0, 2.0), + ]; + let each: Vec = (0..4).map(|i| EdgeFlange { pick: picks[i], height: heights[i], angle: angles[i].to_radians() }).collect(); + flanges_each(rhombus(), rv, &each) + } + + /// The corner of the trimmed base at the corner `c` of the base, whose edges leave it in the + /// directions `dirs`: the two bend lines, each `s0` in from its edge, meet there. + fn trimmed_corner(c: Vec2, dirs: [Vec2; 2], s0: f64) -> Vec2 { + let alpha = dirs[1].cross(dirs[0]).atan2(dirs[1].dot(dirs[0])).abs(); + let bisector = (dirs[0] + dirs[1]).normalized().unwrap_or(Vec2::X); + c + bisector * (s0 / (alpha / 2.0).sin()) + } + + /// The corner reliefs at the corners that are not square: a 60° and a 120° one, each of the + /// four shapes. The relief is cut `size / 2` from the corner along both edges, the bends stop + /// there, and the flat pattern keeps one clean loop. + #[test] + fn corner_reliefs_at_acute_and_obtuse_corners() { + use std::f64::consts::FRAC_PI_3; + let rv = alu(); + let s0 = 3.0; + let u = Vec2::from_angle(FRAC_PI_3); + // The corners of the trimmed base, with the directions their two edges leave in (the edge + // that ends at the corner first): the 60° one at the origin, the 120° one at the far end + // of the slanted side. + let corners = [ + (trimmed_corner(Vec2::new(0.0, 0.0), [u, Vec2::new(1.0, 0.0)], s0), [u, Vec2::new(1.0, 0.0)], FRAC_PI_3), + (trimmed_corner(u * 90.0, [Vec2::new(1.0, 0.0), -u], s0), [Vec2::new(1.0, 0.0), -u], 2.0 * FRAC_PI_3), + ]; + // The notch's corners: a relief moves the bends' ends, so the corners are the notch's. + let (notch, _) = rhombus_flanges(&rv, [90.0; 4], [38.6; 4]); + let closed = notch.corners(&[0, 1, 2, 3]); + assert_eq!(closed.len(), 4, "the notch's corners"); + for shape in [ReliefShape::Notch, ReliefShape::Round, ReliefShape::Rectangular, ReliefShape::Tear] { + let what = format!("{shape:?} at 60° and 120°"); + let (s, notes) = rhombus_flanges(&RuleValues { corner_relief_shape: shape, ..rv }, [90.0; 4], [38.6; 4]); + assert!(notes.is_empty(), "{what}: {notes:?}"); + // The corners are closed with the gap, and the flanges keep clear of each other. + ends_are_gap_apart(&s, &closed, rv.gap, &what); + for k in &closed { + flanges_keep_clear(&s, k, &what); + } + let segs = &s.base.outer.segs; + match shape { + ReliefShape::Notch => { + // The notch cuts nothing: the base keeps its four corners. + assert_eq!(segs.len(), 4, "{what}: {segs:?}"); + } + ReliefShape::Round => { + // A round about each corner, through the angle the base fills there. + for (c, [d1, d2], alpha) in corners { + let found = segs.iter().any(|g| { + matches!(g, Seg2::Arc { center, radius, sweep, .. } + if center.dist(c) < 1e-8 && (radius - 4.0).abs() < 1e-12 && (sweep + alpha).abs() < 1e-9) + && g.start().dist(c + d1 * 4.0) < 1e-8 + && g.end().dist(c + d2 * 4.0) < 1e-8 + }); + assert!(found, "{what}: no round relief of radius 4 about {c:?}: {segs:?}"); + } + // The bends stop 4 mm short of the corners at both their ends. + for f in &s.flanges { + let (u0, u1) = s.zone_span(f); + assert!((u0 - 4.0).abs() < 1e-9 && (u1 - (f.len - 4.0)).abs() < 1e-9, "{what}: {u0} {u1} of {}", f.len); + } + } + ReliefShape::Rectangular => { + // A kite at each corner: its cuts square to the two edges, meeting + // 4 / cos(α / 2) from the corner on the bisector. + for (c, [d1, d2], alpha) in corners { + let x = c + (d1 + d2) * (4.0 / (1.0 + d1.dot(d2))); + let line = |a: Vec2, b: Vec2| { + segs.iter().any(|g| matches!(g, Seg2::Line { .. }) && g.start().dist(a) < 1e-8 && g.end().dist(b) < 1e-8) + }; + assert!(line(c + d1 * 4.0, x), "{what}: no kite at {c:?}: {segs:?}"); + assert!(line(x, c + d2 * 4.0), "{what}: no kite at {c:?}: {segs:?}"); + // The cuts are square to the edges they start on, and the kite's far corner + // is 4 / cos(α / 2) from the corner, on the bisector. + assert!((x - (c + d1 * 4.0)).dot(d1).abs() < 1e-9 && (x - (c + d2 * 4.0)).dot(d2).abs() < 1e-9, "{what}"); + assert!((x.dist(c) - 4.0 / (alpha / 2.0).cos()).abs() < 1e-9, "{what}"); + } + for f in &s.flanges { + let (u0, u1) = s.zone_span(f); + assert!((u0 - 4.0).abs() < 1e-9 && (u1 - (f.len - 4.0)).abs() < 1e-9, "{what}: {u0} {u1} of {}", f.len); + } + } + ReliefShape::Tear => { + // The tear cuts the bend ends, not the base: the base keeps its four corners. + assert_eq!(segs.len(), 4, "{what}: {segs:?}"); + assert_eq!(s.flanges.iter().map(|f| f.tear.0 as usize + f.tear.1 as usize).sum::(), 8, "{what}"); + } + } + // The flat pattern is one piece without hairline edges, and the folded part holds the + // same material. + holds_the_flat_material(&s, &what); + } + } + + /// The corner reliefs at a corner that is not square, with the flanges of unequal height: + /// the ends are still closed with the gap and the flanges still keep clear of each other. + #[test] + fn corner_reliefs_at_acute_and_obtuse_corners_with_unequal_heights() { + let rv = alu(); + let heights = [38.6, 25.0, 45.0, 30.0]; + let (notch, _) = rhombus_flanges(&rv, [90.0; 4], heights); + let closed = notch.corners(&[0, 1, 2, 3]); + assert_eq!(closed.len(), 4, "the notch's corners"); + for shape in [ReliefShape::Notch, ReliefShape::Round, ReliefShape::Rectangular, ReliefShape::Tear] { + let what = format!("{shape:?} at 60° and 120°, flanges of unequal height"); + let (s, notes) = rhombus_flanges(&RuleValues { corner_relief_shape: shape, ..rv }, [90.0; 4], heights); + assert!(notes.is_empty(), "{what}: {notes:?}"); + ends_are_gap_apart(&s, &closed, rv.gap, &what); + for k in &closed { + flanges_keep_clear(&s, k, &what); + } + // The relief cuts the base only: the flanges are the ones the closing left. + assert_eq!( + s.flanges.iter().map(|f| (f.ext, f.slope)).collect::>(), + notch.flanges.iter().map(|f| (f.ext, f.slope)).collect::>(), + "{what}" + ); + holds_the_flat_material(&s, &what); + } + } + + /// The reliefs at the two corners of one short edge: both fit, and the corners do not depend + /// on the order the flanges were made in. + #[test] + fn the_reliefs_at_two_corners_of_one_edge_do_not_depend_on_their_order() { + // A quadrilateral with a 120° corner at the origin and a 90° one 9 mm along the edge + // between them, and flanges on the three edges that meet there. The two corners are + // 4.27 mm apart in the trimmed base: a relief 4 mm across fits at both of them. + let pts = [Vec2::new(0.0, 0.0), Vec2::new(9.0, 0.0), Vec2::new(9.0, 40.0), Vec2::new(-20.0, 20.0 * 3.0f64.sqrt())]; + let base = || Region2 { outer: Loop2::polygon(&pts).ccw(), holes: vec![] }; + let picks = [Vec3::new(-10.0, 17.32, 2.0), Vec3::new(4.5, 0.0, 2.0), Vec3::new(9.0, 20.0, 2.0)]; + let flange = |i: usize| EdgeFlange { pick: picks[i], height: 38.6, angle: 90f64.to_radians() }; + for shape in [ReliefShape::Round, ReliefShape::Rectangular] { + let what = format!("{shape:?} at both ends of a short edge"); + let rv = RuleValues { corner_relief_shape: shape, corner_relief: 4.0, ..alu() }; + // The same three flanges, made in another order. + for order in [[0, 1, 2], [2, 1, 0]] { + let each: Vec = order.iter().map(|&i| flange(i)).collect(); + let (s, notes) = flanges_each(base(), &rv, &each); + assert!(notes.is_empty(), "{what}: {notes:?}"); + // Both corners are relieved: the round one cuts an arc at each, the square one a + // kite, and the base keeps a piece of the edge between them. + let want = match shape { + ReliefShape::Round => 6, + _ => 8, + }; + assert_eq!(s.base.outer.segs.len(), want, "{what}: {order:?}: {:?}", s.base.outer.segs); + // The bend on the short edge is what is left between the two reliefs. + let short = s.flanges.iter().find(|f| f.d.dist(Vec2::new(1.0, 0.0)) < 1e-9).expect("the bend on the short edge"); + let (u0, u1) = s.zone_span(short); + assert!((u0 - 2.0).abs() < 1e-9 && (u1 - (short.len - 2.0)).abs() < 1e-9, "{what}: {u0} {u1} of {}", short.len); + holds_the_flat_material(&s, &what); + } + } + } + #[test] fn a_relief_that_does_not_fit_is_left_out_with_a_note() { let closed = tray(&alu(), 72.0, 38.6).0; diff --git a/crates/engine/src/cmd/sheet_tests.rs b/crates/engine/src/cmd/sheet_tests.rs index 0e30dcaa6..881b047f5 100644 --- a/crates/engine/src/cmd/sheet_tests.rs +++ b/crates/engine/src/cmd/sheet_tests.rs @@ -3034,6 +3034,138 @@ fn corner_reliefs_of_the_rule_reach_the_part_the_flat_pattern_and_the_dxf() { } } +/// The height of the rhombus of [`rhombus_sheet`]: 90 · sin 60°. +const RHOMBUS_Y: f64 = 77.9422863406; +/// Half of it, where the picks on the slanted sides lie. +const RHOMBUS_Y_HALF: f64 = 38.9711431703; + +/// A base flange on a rhombus whose corners are 60° and 120°, with a flange on each of its +/// four edges: the two flanges of a corner meet there, and their bends stop short of it. +fn rhombus_sheet(s: &mut Session, rule: Value) { + let mut r = json!({"name": "AL2", "thickness": "2 mm", "k_factor": 0.5, "bend_radius": "1 mm", "gap": "0.5 mm", "active": true}); + if let (Some(r), Some(extra)) = (r.as_object_mut(), rule.as_object()) { + r.extend(extra.clone()); + } + run(s, "sheet.manage_rules", r); + run(s, "sketch.create", json!({"plane": "XY", "name": "Base"})); + run(s, "sketch.line", json!({"points": [[0, 0], [120, 0], [165, RHOMBUS_Y], [45, RHOMBUS_Y]], "closed": true})); + run(s, "sketch.finish", json!({})); + run(s, "sheet.flange", json!({"sketch": "Base"})); + run( + s, + "sheet.flange", + json!({"edges": [[60, 0, 2], [142.5, RHOMBUS_Y_HALF, 2], [105, RHOMBUS_Y, 2], [22.5, RHOMBUS_Y_HALF, 2]], "height": 38.6, "angle": "90 deg"}), + ); +} + +/// The corner of the trimmed base at the corner `c` of the base, whose edges leave it in the +/// directions `dirs`: the two bend lines, each `s0` in from its edge, meet there. +fn trimmed_corner(c: (f64, f64), dirs: [(f64, f64); 2], s0: f64) -> (f64, f64) { + let (d0, d1) = (dirs[0], dirs[1]); + let alpha = (d0.0 * d1.1 - d0.1 * d1.0).atan2(d0.0 * d1.0 + d0.1 * d1.1).abs(); + let (bx, by) = (d0.0 + d1.0, d0.1 + d1.1); + let k = s0 / (alpha / 2.0).sin() / (bx * bx + by * by).sqrt(); + (c.0 + bx * k, c.1 + by * k) +} + +/// The far corner of the square relief at a corner of the base: `4 / (1 + cos α)` from the +/// corner, on the bisector of its two edges. +fn kite_vertex(c: (f64, f64), d1: (f64, f64), d2: (f64, f64)) -> (f64, f64) { + let k = 4.0 / (1.0 + d1.0 * d2.0 + d1.1 * d2.1); + (c.0 + (d1.0 + d2.0) * k, c.1 + (d1.1 + d2.1) * k) +} + +/// The corner reliefs at corners that are not square: a 60° and a 120° one, each of the four +/// shapes. The relief is cut `size / 2` from the corner along both edges, the bends stop there, +/// and the flat pattern and the DXF keep one clean loop. +#[test] +fn corner_reliefs_at_non_orthogonal_corners_reach_the_flat_pattern_and_the_dxf() { + // The corners of the trimmed base: the two at 60° (6 mm from their corner, on the bisector) + // and the two at 120° (3.464 mm from theirs), with the directions their edges leave in. + let u = (0.5, RHOMBUS_Y / 90.0); + let corners = [ + (trimmed_corner((0.0, 0.0), [(1.0, 0.0), u], 3.0), [(1.0, 0.0), u]), + (trimmed_corner((120.0, 0.0), [(-1.0, 0.0), u], 3.0), [(-1.0, 0.0), u]), + (trimmed_corner((165.0, RHOMBUS_Y), [(-u.0, -u.1), (-1.0, 0.0)], 3.0), [(-u.0, -u.1), (-1.0, 0.0)]), + (trimmed_corner((45.0, RHOMBUS_Y), [(1.0, 0.0), (-u.0, -u.1)], 3.0), [(1.0, 0.0), (-u.0, -u.1)]), + ]; + let mut notch = Session::default(); + rhombus_sheet(&mut notch, json!({})); + assert!(no_errors_or_warnings(¬ch), "{:?}", notch.model.results); + let area0 = flat_area(&flat(&mut notch)); + for shape in ["notch", "round", "rectangular", "tear"] { + let mut s = Session::default(); + rhombus_sheet(&mut s, json!({"corner_relief_shape": shape, "corner_relief": "8 mm"})); + assert!(no_errors_or_warnings(&s), "{shape}: {:?}", s.model.results); + // The flat pattern is one loop with no cut-outs. + let f = flat(&mut s); + assert_eq!(f["outline"].as_array().map(Vec::len), Some(1), "{shape}: {f}"); + assert_eq!(f["cutouts"], json!([]), "{shape}: {f}"); + // No hairline edges in it: no degenerate face. + let shortest = f["outline"][0].as_array().map(|l| { + l.windows(2) + .map(|w| { + let (x, y) = ( + w[1][0].as_f64().unwrap_or(f64::NAN) - w[0][0].as_f64().unwrap_or(f64::NAN), + w[1][1].as_f64().unwrap_or(f64::NAN) - w[0][1].as_f64().unwrap_or(f64::NAN), + ); + (x * x + y * y).sqrt() + }) + .fold(f64::MAX, f64::min) + }); + assert!(shortest.is_some_and(|d| d > 1e-3), "{shape}: the shortest edge of the flat pattern is {shortest:?}"); + // The folded part holds the flat pattern's material (K = 0.5 keeps the volume). + let (v, area) = (volume(&mut s), flat_area(&f)); + assert!((v - area * 2.0).abs() < 1e-3 * v, "{shape}: {v} vs {}", area * 2.0); + // The DXF: the relief at each of the four corners. + let (arcs, ends) = relief_drawing(&mut s); + match shape { + "round" => { + // A round about each corner, of radius 4. + assert_eq!(arcs.len(), 4, "{shape}: {arcs:?}"); + for (c, _) in corners { + assert!( + arcs.iter().any(|(a, r)| (a.x - c.0).abs() < 1e-6 && (a.y - c.1).abs() < 1e-6 && (r - 4.0).abs() < 1e-6), + "{shape}: {arcs:?}" + ); + } + // The base loses a sector of radius 4 at each corner and 4 mm of each of the two + // bends there: 2 corners at 60° and 2 at 120°. + let ba = std::f64::consts::PI; + let want = 2.0 * (16.0 * (PI / 3.0) / 2.0) + 2.0 * (16.0 * (2.0 * PI / 3.0) / 2.0) + 4.0 * 2.0 * 4.0 * ba; + assert!((area0 - area - want).abs() < 0.1, "{shape}: {} vs {want}", area0 - area); + } + "rectangular" => { + // A kite at each corner, meeting 4 / cos(α / 2) from it on the bisector. + assert!(arcs.is_empty(), "{shape}: {arcs:?}"); + for (c, [d1, d2]) in corners { + let x = kite_vertex(c, d1, d2); + assert!(ends.iter().any(|p| (p.x - x.0).abs() < 1e-6 && (p.y - x.1).abs() < 1e-6), "{shape}: no kite at {c:?}: {ends:?}"); + } + let ba = std::f64::consts::PI; + let want = 2.0 * (16.0 * (PI / 6.0).tan()) + 2.0 * (16.0 * (PI / 3.0).tan()) + 4.0 * 2.0 * 4.0 * ba; + assert!((area0 - area - want).abs() < 0.1, "{shape}: {} vs {want}", area0 - area); + } + "tear" => { + // The tear cuts the bend ends, not the base: no arc, and the base keeps its corners. + assert!(arcs.is_empty(), "{shape}: {arcs:?}"); + assert!(area > area0, "{shape}: the tear takes nothing out of the base"); + } + _ => { + // The notch cuts nothing. + assert!(arcs.is_empty(), "{shape}: {arcs:?}"); + assert!((area - area0).abs() < 1e-6, "{shape}: {area} vs {area0}"); + } + } + // Unfolding and refolding keep it. + run(&mut s, "sheet.unfold", json!({})); + run(&mut s, "sheet.refold", json!({})); + assert!((volume(&mut s) - v).abs() < 1e-6 * v, "{shape}"); + let mut reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); + assert!((volume(&mut reopened) - v).abs() < 1e-6 * v, "{shape}"); + } +} + #[test] fn a_tear_of_the_rule_reaches_the_part_the_flat_pattern_and_the_dxf() { use std::f64::consts::SQRT_2; diff --git a/crates/ui-egui/src/dialogs_sheet_tests.rs b/crates/ui-egui/src/dialogs_sheet_tests.rs index 1265e4ab1..7d2d714db 100644 --- a/crates/ui-egui/src/dialogs_sheet_tests.rs +++ b/crates/ui-egui/src/dialogs_sheet_tests.rs @@ -365,6 +365,65 @@ fn rules_dialog_picks_the_corner_relief_shape() { assert_eq!((rounds(&h.app), torn), (Some(0), Some(4))); } +/// The rule manager's rectangular relief, on a base whose corners are not square: the shape and +/// the size the dialog shows reach the part, the bends and the flat pattern. +#[test] +fn the_rule_manager_relieves_a_corner_that_is_not_square() { + let mut h = crate::scenario::Harness::new(); + h.app + .run( + "sheet.manage_rules", + json!({"name": "AL2", "thickness": "2 mm", "k_factor": 0.5, "bend_radius": "1 mm", "gap": "0.5 mm", "corner_relief": "8 mm", "active": true}), + ) + .unwrap(); + // A rhombus whose corners are 60° and 120°, with a flange on each of its four edges. + h.app.run("sketch.create", json!({"plane": "XY", "name": "Base"})).unwrap(); + h.app.run("sketch.line", json!({"points": [[0, 0], [120, 0], [165, 77.9422863406], [45, 77.9422863406]], "closed": true})).unwrap(); + h.app.run("sketch.finish", json!({})).unwrap(); + h.app.run("sheet.flange", json!({"sketch": "Base"})).unwrap(); + h.app + .run( + "sheet.flange", + json!({"edges": [[60, 0, 2], [142.5, 38.9711431703, 2], [105, 77.9422863406, 2], [22.5, 38.9711431703, 2]], "height": 38.6, "angle": "90 deg"}), + ) + .unwrap(); + // The base of the notch has its four corners, and the bends run the whole length of the edges. + let base = |app: &SolveApp| { + let state = app.session.model.state(); + state.sheets.last().map(|s| (s.base.outer.segs.len(), s.flanges.iter().map(|f| s.zone_span(f).1 - s.zone_span(f).0).collect::>())) + }; + let shown = |app: &SolveApp| match app.dialog.as_ref().map(|d| &d.kind) { + Some(Kind::Sheet(Sm::Rules { relief, .. })) => Some(*relief), + _ => None, + }; + let (segs, notch_bends) = base(&h.app).expect("the sheet"); + assert_eq!(segs, 4, "the notch cuts nothing out of the base"); + h.step(&json!({"start": "sheet.manage_rules"})).unwrap(); + h.frames(3); + assert_eq!(shown(&h.app), Some(0), "a rule starts with the notch"); + // The rectangular relief: the shape the dialog offers, and the size the rule carries. + h.step(&json!({"click": {"handle": "dialog:Corner Relief Shape"}})).unwrap(); + h.step(&json!({"click": {"handle": "dialog:Corner Relief Shape:Rectangular"}})).unwrap(); + assert_eq!(shown(&h.app), Some(2)); + h.frames(3); + assert!(h.app.preview.error.is_none(), "the preview: {:?}", h.app.preview.error); + h.step(&json!({"widget": "OK"})).unwrap(); + assert!(h.app.dialog.is_none(), "{:?}", h.app.dialog); + assert_eq!(h.app.session.doc.sheet_rule(None).corner_relief_shape, "rectangular"); + assert_eq!(h.app.session.doc.sheet_rule(None).corner_relief, "8 mm"); + // A kite at each of the four corners: two more edges than the notch's four. + let (segs, relieved) = base(&h.app).expect("the sheet"); + assert_eq!(segs, 12, "a kite at each corner of the base"); + for (was, now) in notch_bends.iter().zip(&relieved) { + assert!((was - now - 8.0).abs() < 1e-6, "{notch_bends:?} and {relieved:?}: the bends are 8 mm shorter"); + } + // The flat pattern is one loop, and the part folds. + let flat = h.app.session.execute("sheet.flat_pattern", &json!({})).expect("the flat pattern"); + assert_eq!(flat["outline"].as_array().map(Vec::len), Some(1), "{flat}"); + assert_eq!(flat["cutouts"], json!([]), "{flat}"); + assert!(h.app.preview.error.is_none(), "{:?}", h.app.preview.error); +} + /// The Flange dialog's relief rows: Rule (the default) and an empty size leave the relief to the rule, /// a shape and a size reach the feature, Edit Feature shows them again, and Rule takes them back. #[test] diff --git a/docs/book/src/guide/sheet-metal.md b/docs/book/src/guide/sheet-metal.md index 25f9c800d..e3a7c1988 100644 --- a/docs/book/src/guide/sheet-metal.md +++ b/docs/book/src/guide/sheet-metal.md @@ -57,7 +57,9 @@ square the round follows the angle of the base and the square becomes a kite, it square to the edges. Changing the shape in a rule changes the parts made with that rule. A relief that doesn't fit (under 0.01 mm across, leaving nothing of a bend, or reaching as far from its corner as another edge of the base is) is left out, and the flange feature reports a -warning saying where. +warning saying where. The reliefs at the corners of one edge are cut together, so a corner's +relief does not depend on the order the corners are cut in; two of them that would overlap +leave the second one out, with a warning. ```json {"command":"sheet.manage_rules","params":{"name":"Sheet 2 mm","thickness":"2 mm","k_factor":0.5, From 80719744cfe7ee1df28e4e18f2e07d5f1acc751b Mon Sep 17 00:00:00 2001 From: Artem Sushchev Date: Tue, 20 Oct 2026 02:11:23 +0000 Subject: [PATCH 160/225] Union: when the slab past pushed-apart coplanar faces can't be cut off, trim it by editing faces (#2801) --- crates/engine/src/boolean_regression_tests.rs | 28 +++++++++++++++++++ crates/kernel/src/coplanar.rs | 13 +++++++-- tests/robustness/goldens.json | 5 ++-- 3 files changed, 41 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/boolean_regression_tests.rs b/crates/engine/src/boolean_regression_tests.rs index 66dfc17ea..1b751b81f 100644 --- a/crates/engine/src/boolean_regression_tests.rs +++ b/crates/engine/src/boolean_regression_tests.rs @@ -945,3 +945,31 @@ fn combine_of_a_piece_a_cut_used_to_split_off_takes_the_body_it_is_part_of() { assert!(r.is_err(), "{target} {operation} {tools}: {r:?}"); } } + +/// A triangular prism and a thin slab sharing their bottom plane, the prism's edge in that plane +/// lying in the slab's end face, the slab's corners rounded nearly to half its width (so its flat +/// end is narrower than the prism). +#[test] +fn prism_edge_in_a_round_cornered_slab_end_face_joins() { + for r in [4.5, 4.9] { + let mut s = Session::default(); + let mut run = |c: &str, p: Value| s.execute(c, &p).unwrap(); + run("sketch.create", json!({"plane": {"origin": [-45.6, 0, 0], "x_dir": [0, 1, 0], "y_dir": [0, 0, 1]}})); + run("sketch.line", json!({"points": [[-63, 0], [-3, 0], [-63, 60]], "closed": true})); + run("sketch.finish", json!({})); + run("solid.extrude", json!({"distance": 1.2, "operation": "new", "body_name": "Prism"})); + run("sketch.create", json!({"plane": "XY"})); + run("sketch.rectangle.rounded", json!({"p0": [-50, -67], "p1": [-40, -3], "radius": r})); + run("sketch.finish", json!({})); + run("solid.extrude", json!({"distance": 0.4, "operation": "new", "body_name": "Slab"})); + let (prism, slab) = (volume(&s, "Prism"), volume(&s, "Slab")); + s.execute("solid.combine", &json!({"target": "Prism", "tools": ["Slab"], "operation": "join"})).unwrap(); + let join = s.model.results.last().unwrap(); + assert_eq!(join.error.as_deref(), None, "r {r}"); + // The prism inside the slab: 1.2 wide, 0.4 high and 60 long, less the 0.4 x 0.4 triangle the + // sloped face leaves empty at the slab's end. + let shared = 1.2 * 0.4 * 60.0 - 1.2 * 0.4 * 0.4 / 2.0; + let got = volume(&s, "Prism"); + assert!((got - (prism + slab - shared)).abs() < 1e-3 * got, "r {r}: {got} vs {}", prism + slab - shared); + } +} diff --git a/crates/kernel/src/coplanar.rs b/crates/kernel/src/coplanar.rs index da0ffd69c..f7afd3383 100644 --- a/crates/kernel/src/coplanar.rs +++ b/crates/kernel/src/coplanar.rs @@ -905,12 +905,19 @@ fn apart_with(a: &Body, b: &Body, op: BoolOp, grow: bool) -> Option { + match crate::ops::boolean(&r, &slab, BoolOp::Cut) { + Ok(Some(x)) => { h = h.and_then(|h| trimmed(&x, h, &slab, [a, b], *n, *d, tol)); r = x; } - None => return Ok(None), + Ok(None) => return Ok(None), + // An edge of the union can lie in the plane, where a pushed side crosses a side + // of the other body (a prism's edge in the plane lying in a slab's end face): + // the cut along it fails, and the same trim is made by editing the faces. + Err(e) => { + r = trim_exact(&r, *n, *d).map_err(|_| e)?; + h = None; + } } } } diff --git a/tests/robustness/goldens.json b/tests/robustness/goldens.json index 56d799e33..ac24656ea 100644 --- a/tests/robustness/goldens.json +++ b/tests/robustness/goldens.json @@ -71,7 +71,7 @@ "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}, "68": {"area":7338.675126,"bodies":1,"edges":36,"error":null,"faces":14,"outcome":"ok","rejected":2,"shells":1,"steps":["extruded profile","hole","hole","rectangular pattern","rectangular pattern","fillet","circular pattern"],"unsupported":0,"volume":29780.741772}, "69": {"area":6451.122767,"bodies":1,"edges":60,"error":"offset: a corner whose faces don't meet the same way after t","faces":27,"outcome":"failed","rejected":0,"shells":3,"steps":["revolved section","join box","shell","shell"],"unsupported":0,"volume":4761.477515}, - "70": {"area":3682.669157,"bodies":1,"edges":24,"error":"lumps: shell boundaries intersect or touch; cavity ownership","faces":12,"outcome":"failed","rejected":0,"shells":2,"steps":["extruded profile","join box","hole"],"unsupported":1,"volume":9155.027162}, + "70": {"area":5638.09657,"bodies":1,"edges":48,"error":"lumps: shell boundaries intersect or touch; cavity ownership","faces":23,"outcome":"failed","rejected":0,"shells":3,"steps":["extruded profile","join box","shell","hole"],"unsupported":0,"volume":4120.897175}, "71": {"area":3980.574721,"bodies":1,"edges":52,"error":null,"faces":20,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","cut box","cut cylinder","hole","join cylinder"],"unsupported":0,"volume":15749.927814}, "72": {"area":5770.270336,"bodies":1,"edges":44,"error":null,"faces":20,"outcome":"ok","rejected":1,"shells":2,"steps":["box","join cylinder","hole","join box","join box","cut box","cut cylinder","cut cylinder"],"unsupported":0,"volume":16081.801492}, "73": {"area":6868.162117,"bodies":1,"edges":40,"error":"offset: a corner whose faces don't meet the same way after t","faces":18,"outcome":"failed","rejected":0,"shells":1,"steps":["extruded profile","join box","shell"],"unsupported":1,"volume":36461.939381}, @@ -142,6 +142,7 @@ {"reason":"#2064 (multi-profile extrusion) merges coplanar faces the boolean used to leave split. Seed 67 has one face/two edges fewer from its first cut on, at the same volume at every step; seed 94's last box cut leaves one face/two edges more, same volume and area. Seed 13's second cylinder cut leaves 35 faces/84 edges instead of 37/88 at the same volume, so its random fillet (edges picked by index) rounds different edges: 2688.99 instead of 2675.18 mm3 after the fillet; the hole after it removes the same 278.2 mm3. Every step passes the validity and volume-direction checks. Pull request CI ran only every 8th seed, so main was the first run to see these.","seeds":[13,67,94]}, {"reason":"#2247: a cut no longer splits the separate pieces of a body into bodies of their own, so these seeds keep one body (bodies N -> 1). The generator looks at the model, so after the first such cut some seeds build different steps: seed 33 joins and patterns a box instead of chamfering (volume 13858 -> 24911 mm3), seed 18 now builds (its hole pattern failed with no result), and seed 54 picks a shell that fails the same way on main before #2247 (offset corner). Every step passes the validity and volume-direction checks.","seeds":[7,9,12,16,18,22,27,31,33,45,50,54,67,72,81,93]}, {"reason":"Reseam rotationally symmetric drill cutters after failed cuts (#2387): seed 86 now drills its hole, so its following pattern, shell and sphere cut complete with the fuzz validity and material checks.","seeds":[86]}, - {"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":"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]} ] } From d0afc31632da64340c45a6142da9dd92b0e74799 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Tue, 20 Oct 2026 02:31:08 +0000 Subject: [PATCH 161/225] Save the evaluated model with every design: exact, stored once, scaled caps (#3053) (#3093) * Model cache written by default: exact bodies, stored once, scaled caps (#3053) Co-Authored-By: Claude Opus 5.5 * bench-open: say why bodies were not kept * Exact planes and revolutions; budgets for large bodies (#3053) Co-Authored-By: Claude Opus 5.5 * Native B-rep: rebuild shells as the kernel made them (closed and seam edges) (#3053) Co-Authored-By: Claude Opus 5.5 * docs: the model cache and the exact native B-rep (#3053) Co-Authored-By: Claude Opus 5.5 * bench-open: time a save without the cache too * Model cache entries are Deflate-compressed (#3053) Co-Authored-By: Claude Opus 5.5 * Model cache: one that does not fit the design file is left out, never a failed save (#3053) Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- Cargo.lock | 1 + apps/solidcraft-cli/src/main.rs | 41 ++- crates/doc/src/eval.rs | 17 ++ crates/engine/src/cmd/file.rs | 44 ++- crates/engine/tests/save_as_cache.rs | 31 +- crates/geom/src/brep.rs | 180 +++++++++-- crates/io/Cargo.toml | 1 + crates/io/build.rs | 20 ++ crates/io/src/design.rs | 146 ++++++--- crates/io/src/design/native_cache.rs | 281 +++++++++++++----- crates/io/src/lib.rs | 7 +- crates/kernel/src/body.rs | 36 +++ crates/kernel/src/lib.rs | 2 +- crates/kernel/src/native.rs | 50 +++- crates/kernel/src/native/adapter.rs | 260 +++++++++------- crates/kernel/src/native/fit.rs | 85 ------ ...{box-fillet-v3.json => box-fillet-v4.json} | 142 +++++---- docs/design-container.md | 86 +++--- docs/native-brep.md | 96 +++--- 19 files changed, 1018 insertions(+), 508 deletions(-) create mode 100644 crates/io/build.rs delete mode 100644 crates/kernel/src/native/fit.rs rename crates/kernel/src/native/fixtures/{box-fillet-v3.json => box-fillet-v4.json} (95%) diff --git a/Cargo.lock b/Cargo.lock index c421d34bc..96705531d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4199,6 +4199,7 @@ dependencies = [ "cadmpeg-ir", "cadmpeg-registry", "gltf", + "log", "quick-xml", "rustix 1.1.5", "serde", diff --git a/apps/solidcraft-cli/src/main.rs b/apps/solidcraft-cli/src/main.rs index 6adaa8c46..5be417c49 100644 --- a/apps/solidcraft-cli/src/main.rs +++ b/apps/solidcraft-cli/src/main.rs @@ -4,7 +4,7 @@ //! solidcraft-cli run [--in design|part.step|mesh.3mf] [--out FILE]... [--save FILE] [--quiet] [--results] [--timings] [--profile] [--json-out FILE] [--allow-errors] //! solidcraft-cli eval [--json-out FILE] (alias: inspect) measurements as JSON //! solidcraft-cli script [--out script.json] the design's history as a command script -//! solidcraft-cli bench-open [--parse-only] [--display LEVEL [--edit NAME EXPR]] loading timings as JSON lines +//! solidcraft-cli bench-open [--parse-only] [--save OUT.solidcraft] [--display LEVEL [--edit NAME EXPR]] loading timings as JSON lines //! solidcraft-cli bench-agent [--scale F] [--save F] [--script-out F] a ~1,300-body design built command by command, timed //! solidcraft-cli snapshot [--in design|part.step] --out shot.png [--width W] [--height H] [--view iso|front|top|…|NAME | --camera JSON] [--no-grid] [--no-axes] //! [--body NAME:opacity=0.3,color=#rrggbb]... [--tool NAME]... [--section z=27] @@ -49,7 +49,7 @@ const USAGE: &str = "usage: as plain UTF-8: a shell's > can re-encode it, e.g. Windows PowerShell adds a byte-order mark) solidcraft-cli script [--out script.json] (the design's history as a command script that eval and run replay) - solidcraft-cli bench-open [--parse-only] [--display LEVEL [--edit NAME EXPR]] + solidcraft-cli bench-open [--parse-only] [--save OUT.solidcraft] [--display LEVEL [--edit NAME EXPR]] solidcraft-cli bench-agent [--scale F] [--save design.solidcraft] [--script-out script.json] solidcraft-cli snapshot [--in design.solidcraft|part.step] --out shot.png [--width W] [--height H] [--view NAME | --camera JSON] [--no-grid] [--no-axes] [--body NAME:opacity=0.3,color=#rrggbb]... [--tool NAME]... [--section z=27] @@ -655,10 +655,45 @@ pub(crate) fn cmd_bench_open(args: &[String]) -> Result<(), String> { "{}", json!({"step": "mesh", "ms": t.elapsed().as_secs_f64() * 1000.0, "place_ms": place_ms, "bodies": st.bodies.len(), "triangles": triangles}) ); + let flag = |name: &str| args.iter().position(|a| a == name); + // `--save PATH`: save the opened design without its model cache (to PATH.plain.solidcraft) and + // as the app does, with it, then read the cache back. + let s = match flag("--save").and_then(|i| args.get(i + 1)) { + Some(out) => { + let mut s = s; + // Without the cache first, for comparison. + let plain = format!("{out}.plain.solidcraft"); + let t = std::time::Instant::now(); + s.execute("file.save_as", &json!({"path": plain, "cache": false})).map_err(|e| e.to_string())?; + let plain_ms = t.elapsed().as_secs_f64() * 1000.0; + let plain_bytes = std::fs::metadata(&plain).map(|m| m.len()).unwrap_or(0); + let t = std::time::Instant::now(); + s.execute("file.save_as", &json!({"path": out})).map_err(|e| e.to_string())?; + let save_ms = t.elapsed().as_secs_f64() * 1000.0; + let bytes = std::fs::read(out).map_err(|e| format!("{out}: {e}"))?; + let t = std::time::Instant::now(); + let cached = solidcraft_engine::io::read_design_geometry(&bytes).map(|m| m.bodies.len()); + let read_ms = t.elapsed().as_secs_f64() * 1000.0; + // Why bodies could not be kept exactly, when the cache was left out. + let mut refused = std::collections::BTreeMap::::new(); + if cached.is_none() { + for b in &s.model.state().bodies { + if let Err(e) = solidcraft_engine::kernel::encode_native_body(&b.body) { + *refused.entry(e.to_string()).or_default() += 1; + } + } + } + println!( + "{}", + json!({"step": "save", "ms": save_ms, "bytes": bytes.len(), "plain_ms": plain_ms, "plain_bytes": plain_bytes, "cached_bodies": cached, "cache_read_ms": read_ms, "refused": refused}) + ); + s + } + None => s, + }; // `--display LEVEL`: the display plans the viewport draws at that display quality, made as // the GPU viewport makes them; `--edit NAME EXPR` then changes a parameter and times the // evaluation and the plans of the bodies it changed. - let flag = |name: &str| args.iter().position(|a| a == name); let Some(level) = flag("--display").and_then(|i| args.get(i + 1)) else { return Ok(()) }; let q = solidcraft_engine::doc::display_quality::DisplayQuality::parse(level).ok_or("--display: coarse, normal, fine or ultra")?; let plans = |st: &solidcraft_engine::doc::ModelState| { diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index eb7a1e5c3..3c254beb5 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -1240,6 +1240,23 @@ impl Model { }) } + /// Whether the results are `doc`'s evaluation: one per feature, each on the inputs `doc` + /// gives it, none stale, so [`Model::evaluate`] would keep every one of them. A document + /// changed without an evaluation since is not. + pub fn is_current(&self, doc: &Document) -> bool { + if self.results.len() != doc.features.len() || self.is_stale() { + return false; + } + let vals = evaluation_values(doc).0; + let steps = StepDigests::of(doc, &self.step_digests); + let marker = doc.marker.unwrap_or(usize::MAX); + let mut prev = 0; + doc.features.iter().zip(&self.results).enumerate().all(|(i, (f, r))| { + prev = chain_fingerprint(doc, &vals, f, prev, i >= marker, &steps); + r.id == f.id && r.fingerprint == prev + }) + } + /// Re-evaluate the document, reusing results up to the first changed feature. pub fn evaluate(&mut self, doc: &Document) { let (vals, perr) = evaluation_values(doc); diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 9d336559e..100c6435b 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -33,11 +33,11 @@ pub static COMMANDS: &[CommandSpec] = &[ .icon("save") .key("Ctrl+S") .noundo() - .params("path? (default: current file); format?: container|json (default: json for .json, otherwise container); compression?: fast|compact (default: fast); cache?: bool (warm native geometry, default: false); preview?: bool (saved display meshes, default: false)"), + .params("path? (default: current file); format?: container|json (default: json for .json, otherwise container); compression?: fast|compact (default: fast); cache?: bool (the evaluated model, so the design opens without rebuilding; default: true); preview?: bool (saved display meshes, default: false)"), CommandSpec::new("file.save_as", "Save As", save_as) .icon("save") .noundo() - .params("path; format?: container|json (default: json for .json, otherwise container); compression?: fast|compact (default: fast); cache?: bool (warm native geometry, default: false); preview?: bool (saved display meshes, default: false)"), + .params("path; format?: container|json (default: json for .json, otherwise container); compression?: fast|compact (default: fast); cache?: bool (the evaluated model, so the design opens without rebuilding; default: true); preview?: bool (saved display meshes, default: false)"), CommandSpec::new("doc.recovery_list", "Recoverable Designs", recovery_list).icon("restore") .noundo() .params("dir? (default: the recovery folder) → designs autosaved by apps that crashed or closed with unsaved changes"), @@ -401,23 +401,21 @@ impl Session { /// Container bytes for desktop and browser saves. Only already evaluated bodies /// and warm meshes are eligible; saving never forces evaluation or tessellation. pub fn design_container(&self, compression: solidcraft_io::DesignCompression, preview: bool, cache: bool) -> solidcraft_io::Result> { - let geometry = cache.then(|| saved_geometry(self)).flatten(); + let design = self.design(); + let geometry = cache.then(|| saved_geometry(self, &design)).flatten(); let preview = preview.then(|| saved_preview(self)).flatten(); let thumbnail = cache.then(|| thumbnail::saved(self)).flatten(); - solidcraft_io::write_design_container_with_thumbnail(&self.design(), compression, preview.as_ref(), geometry.as_deref(), thumbnail.as_deref()) + solidcraft_io::write_design_container_with_thumbnail(&design, compression, preview.as_ref(), geometry.as_deref(), thumbnail.as_deref()) } } -fn saved_geometry(s: &Session) -> Option> { - if s.active_sketch.is_some() || !s.pending_moves.is_empty() || s.model.results.iter().any(|r| r.error.is_some()) { +/// The evaluated model a save keeps, so opening need not rebuild it: only the finished evaluation +/// of `design`, the document saved (no sketch being edited, no uncaptured moves, no feature errors). +fn saved_geometry(s: &Session, design: &Document) -> Option> { + if s.active_sketch.is_some() || !s.pending_moves.is_empty() || s.model.results.iter().any(|r| r.error.is_some()) || !s.model.is_current(design) { return None; } - let world = s.cached_world_state()?; - if world.bodies.is_empty() || world.bodies.len() > 4096 { - return None; - } - let painted = s.doc.painted(&world); - Some(painted.bodies.iter().map(|b| solidcraft_io::DesignGeometry { name: b.name.clone(), body: b.body.clone() }).collect()) + Some(s.model.state()).filter(|st| !st.bodies.is_empty()) } /// Cache only warm display geometry. A save never waits for an unevaluated mesh. @@ -461,7 +459,7 @@ fn save(s: &mut Session, p: &Value) -> Result { str_(p, "format").unwrap_or(default_design_format(&path)), str_(p, "compression").unwrap_or("fast"), bool_(p, "preview").unwrap_or(false), - bool_(p, "cache").unwrap_or(false), + bool_(p, "cache").unwrap_or(true), ) } @@ -477,7 +475,7 @@ fn save_as(s: &mut Session, p: &Value) -> Result { str_(p, "format").unwrap_or(default_design_format(&path)), str_(p, "compression").unwrap_or("fast"), bool_(p, "preview").unwrap_or(false), - bool_(p, "cache").unwrap_or(false), + bool_(p, "cache").unwrap_or(true), ) } @@ -744,7 +742,7 @@ mod tests { let save_path = std::env::temp_dir().join(format!("solidcraft-preview-save-{}.solidcraft", std::process::id())); s.execute("file.save", &json!({"path":save_path})).unwrap(); let saved = std::fs::read(&save_path).unwrap(); - assert!(solidcraft_io::read_design_geometry(&saved).is_none(), "ordinary saves omit native geometry caches"); + assert!(solidcraft_io::read_design_geometry(&saved).is_some(), "ordinary saves keep the evaluated model"); assert!(!saved.windows(b"cache/preview.bin".len()).any(|s| s == b"cache/preview.bin"), "ordinary saves omit redundant display meshes"); s.execute("file.save", &json!({"path":save_path,"preview":true})).unwrap(); assert!(solidcraft_io::read_design_preview(&std::fs::read(&save_path).unwrap()).is_some()); @@ -788,7 +786,7 @@ mod tests { } *s.world_cache.lock().unwrap() = None; assert!(saved_preview(&s).is_none()); - assert!(saved_geometry(&s).is_none()); + assert!(saved_geometry(&s, &s.doc).is_some(), "the timeline's bodies need no placement"); assert!(s.world_cache.lock().unwrap().is_none(), "saving must not prepare cold placements"); for body in &s.world_state().bodies { body.mesh(); @@ -800,7 +798,7 @@ mod tests { } assert!(!s.pending_moves.is_empty()); assert!(saved_preview(&s).is_none(), "uncaptured positions are not in the saved document"); - assert!(saved_geometry(&s).is_none()); + assert!(saved_geometry(&s, &s.doc).is_none()); s.execute("component.capture_position", &json!({})).unwrap(); for body in &s.world_state().bodies { body.mesh(); @@ -815,11 +813,11 @@ mod tests { } assert!(editing.active_sketch.is_some()); assert!(saved_preview(&editing).is_none()); - assert!(saved_geometry(&editing).is_none()); + assert!(saved_geometry(&editing, &editing.doc).is_none()); } #[test] - fn save_and_save_as_require_explicit_native_cache_opt_in() { + fn save_and_save_as_keep_the_model_unless_opted_out() { // Thumbnails are drawn by the renderer the host installs. crate::capture::install_test_renderer(); let mut session = Session::new(Document::new("Cache opt-in")); @@ -837,8 +835,8 @@ mod tests { } session.execute(command, ¶ms).unwrap(); let bytes = std::fs::read(&path).unwrap(); - assert_eq!(solidcraft_io::read_design_geometry(&bytes).is_some(), cache == Some(true), "{command}: {cache:?}"); - assert_eq!(solidcraft_io::read_design_thumbnail(&bytes).is_some(), cache == Some(true), "{command}: {cache:?}"); + assert_eq!(solidcraft_io::read_design_geometry(&bytes).is_some(), cache != Some(false), "{command}: {cache:?}"); + assert_eq!(solidcraft_io::read_design_thumbnail(&bytes).is_some(), cache != Some(false), "{command}: {cache:?}"); assert!( !bytes.windows(b"cache/preview.bin".len()).any(|entry| entry == b"cache/preview.bin"), "display meshes require preview: true" @@ -856,14 +854,14 @@ mod tests { session.execute("solid.box", &json!({"length":10,"width":20,"height":30})).unwrap(); let world = session.world_state(); assert!(world.bodies.iter().all(|b| b.cached_mesh().is_none())); - let mut cached = saved_geometry(&session).unwrap(); + let mut cached = (*saved_geometry(&session, &session.doc).unwrap()).clone(); let bytes = session.design_container(solidcraft_io::DesignCompression::Fast, false, true).unwrap(); assert!(world.bodies.iter().all(|b| b.cached_mesh().is_none()), "saving native geometry must not triangulate"); assert!(solidcraft_io::read_design_geometry(&bytes).is_some()); assert!( solidcraft_io::read_design_geometry(&session.design_container(solidcraft_io::DesignCompression::Fast, false, false).unwrap()).is_none() ); - cached[0].body = solidcraft_kernel::box_solid(solidcraft_geom::Vec3::ZERO, solidcraft_geom::Vec3::new(100., 100., 100.)).unwrap(); + cached.bodies[0].body = solidcraft_kernel::box_solid(solidcraft_geom::Vec3::ZERO, solidcraft_geom::Vec3::new(100., 100., 100.)).unwrap(); let bytes = solidcraft_io::write_design_container_with_cache(&session.doc, solidcraft_io::DesignCompression::Fast, None, Some(&cached)).unwrap(); let path = std::env::temp_dir().join(format!("solidcraft-native-forged-{}.solidcraft", std::process::id())); diff --git a/crates/engine/tests/save_as_cache.rs b/crates/engine/tests/save_as_cache.rs index 5506002b4..5bfd1f4e1 100644 --- a/crates/engine/tests/save_as_cache.rs +++ b/crates/engine/tests/save_as_cache.rs @@ -1,5 +1,6 @@ -//! Optional save caches survive a filename-driven rename, without warming or -//! certifying placements that do not match the document being saved. +//! Save caches survive a filename-driven rename. Display caches are never warmed for a save +//! nor certified for placements that do not match the document being saved; the model cache +//! (the timeline's bodies, before placement) needs no warm display. use serde_json::json; use solidcraft_doc::Document; use solidcraft_engine::Session; @@ -27,6 +28,11 @@ fn save(session: &mut Session, label: &str) -> Vec { bytes } +/// Whether the file holds saved display meshes (a picture is also drawn from the model cache). +fn saved_display(bytes: &[u8]) -> bool { + bytes.windows(b"cache/preview.bin".len()).any(|entry| entry == b"cache/preview.bin") +} + #[test] fn a_filename_rename_preserves_opted_in_warm_assembly_caches() { let mut session = assembly(); @@ -34,8 +40,8 @@ fn a_filename_rename_preserves_opted_in_warm_assembly_caches() { for label in ["first-warm", "renamed-warm"] { let bytes = save(&mut session, label); let geometry = solidcraft_io::read_design_geometry(&bytes).expect("warm geometry survives the rename"); - assert_eq!(geometry.len(), 1); - assert!((solidcraft_kernel::measure(&geometry[0].body).unwrap().volume - 24.0).abs() < 1e-9); + assert_eq!(geometry.bodies.len(), 1); + assert!((solidcraft_kernel::measure(&geometry.bodies[0].body).unwrap().volume - 24.0).abs() < 1e-9); assert!(solidcraft_io::read_design_preview(&bytes).is_some(), "warm display meshes survive the rename"); warm(&session); } @@ -46,13 +52,22 @@ fn naming_a_design_does_not_warm_cold_or_revalidate_stale_placements() { let original = assembly(); let mut cold = Session::new((*original.doc).clone()); let bytes = save(&mut cold, "cold"); - assert!(solidcraft_io::read_design_geometry(&bytes).is_none()); - assert!(solidcraft_io::read_design_preview(&bytes).is_none()); + assert!(solidcraft_io::read_design_geometry(&bytes).is_some(), "the model needs no warm display"); + assert!(!saved_display(&bytes)); let mut stale = assembly(); warm(&stale); stale.doc_mut().occurrences.first_mut().unwrap().transform[3][0] = 25.0; let bytes = save(&mut stale, "stale"); - assert!(solidcraft_io::read_design_geometry(&bytes).is_none(), "old placements must not be certified for a changed document"); - assert!(solidcraft_io::read_design_preview(&bytes).is_none()); + assert!(solidcraft_io::read_design_geometry(&bytes).is_some(), "a placement is not part of the timeline's bodies"); + assert!(!saved_display(&bytes), "old placements must not be certified for a changed document"); + + // A document edited without an evaluation since is not saved with the old one's bodies. + let mut edited = assembly(); + let feature = edited.doc.features.last().unwrap().id; + if let solidcraft_doc::FeatureKind::Box { length, .. } = &mut edited.doc_mut().features.iter_mut().find(|f| f.id == feature).unwrap().kind { + *length = "20".into(); + } + let bytes = save(&mut edited, "edited"); + assert!(solidcraft_io::read_design_geometry(&bytes).is_none(), "bodies of another document must not be saved as this one's"); } diff --git a/crates/geom/src/brep.rs b/crates/geom/src/brep.rs index 2e01e680e..f8875ad87 100644 --- a/crates/geom/src/brep.rs +++ b/crates/geom/src/brep.rs @@ -5,8 +5,8 @@ use serde::{Deserialize, Serialize}; pub mod envelope; -pub const VERSION: u32 = 2; -pub const MAX_ITEMS: usize = 100_000; +pub const VERSION: u32 = 3; +pub const MAX_ITEMS: usize = 1_000_000; const MAX_DEPTH: usize = 16; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -58,26 +58,113 @@ pub struct Frame { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] pub enum Curve { - Line { start: [f64; 3], end: [f64; 3] }, - CircleArc { frame: Frame, radius: f64, angle: [f64; 2] }, - EllipseArc { frame: Frame, radii: [f64; 2], angle: [f64; 2] }, - Polyline { points: Vec<[f64; 3]> }, - Spline { knots: Vec, points: Vec<[f64; 3]> }, - RationalSpline { knots: Vec, homogeneous: Vec<[f64; 4]> }, - Intersection { knots: Vec, points: Vec<[f64; 3]>, fitting_tolerance: f64, faces: Option<[u32; 2]> }, + Line { + start: [f64; 3], + end: [f64; 3], + }, + CircleArc { + frame: Frame, + radius: f64, + angle: [f64; 2], + }, + EllipseArc { + frame: Frame, + radii: [f64; 2], + angle: [f64; 2], + }, + Polyline { + points: Vec<[f64; 3]>, + }, + Spline { + knots: Vec, + points: Vec<[f64; 3]>, + }, + RationalSpline { + knots: Vec, + homogeneous: Vec<[f64; 4]>, + }, + Intersection { + knots: Vec, + points: Vec<[f64; 3]>, + fitting_tolerance: f64, + faces: Option<[u32; 2]>, + }, + /// The intersection of two surfaces, traced from `leader` (a polyline or spline near it) + /// to within `tolerance`: the procedural curve itself, exactly as its producer holds it. + SurfaceIntersection { + surfaces: [Box; 2], + leader: Box, + tolerance: f64, + }, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] pub enum Surface { - Plane { origin: [f64; 3], u_axis: [f64; 3], v_axis: [f64; 3] }, - Cylinder { frame: Frame, radius: f64, angle: [f64; 2], height: [f64; 2] }, - Cone { frame: Frame, radius_at_origin: f64, half_angle: f64, angle: [f64; 2], height: [f64; 2] }, - Sphere { frame: Frame, radius: f64, longitude: [f64; 2], latitude: [f64; 2] }, - Torus { frame: Frame, major_radius: f64, minor_radius: f64, longitude: [f64; 2], meridian: [f64; 2] }, - Spline { u_knots: Vec, v_knots: Vec, points: Vec> }, - RationalSpline { u_knots: Vec, v_knots: Vec, homogeneous: Vec> }, - Revolution { profile: Box, origin: [f64; 3], axis: [f64; 3], angle: [f64; 2] }, + Plane { + origin: [f64; 3], + u_axis: [f64; 3], + v_axis: [f64; 3], + }, + /// The plane through three points, parameter (1, 0) at `u_point` and (0, 1) at `v_point`: + /// the points themselves, as its producer holds them (axes worked out from them would round). + PlaneThrough { + origin: [f64; 3], + u_point: [f64; 3], + v_point: [f64; 3], + }, + Cylinder { + frame: Frame, + radius: f64, + angle: [f64; 2], + height: [f64; 2], + }, + Cone { + frame: Frame, + radius_at_origin: f64, + half_angle: f64, + angle: [f64; 2], + height: [f64; 2], + }, + Sphere { + frame: Frame, + radius: f64, + longitude: [f64; 2], + latitude: [f64; 2], + }, + Torus { + frame: Frame, + major_radius: f64, + minor_radius: f64, + longitude: [f64; 2], + meridian: [f64; 2], + }, + Spline { + u_knots: Vec, + v_knots: Vec, + points: Vec>, + }, + RationalSpline { + u_knots: Vec, + v_knots: Vec, + homogeneous: Vec>, + }, + Revolution { + profile: Box, + origin: [f64; 3], + axis: [f64; 3], + angle: [f64; 2], + }, + /// A full revolution of `profile` about `origin` and unit `axis`, then mapped by the + /// column-major affine `matrix`, with the normal reversed unless `forward`: the + /// revolution exactly as its producer holds it, nothing baked into the profile. + PlacedRevolution { + profile: Box, + origin: [f64; 3], + axis: [f64; 3], + matrix: [[f64; 4]; 4], + forward: bool, + }, } #[derive(Clone, Debug, thiserror::Error)] @@ -190,6 +277,27 @@ fn curve(c: &Curve, depth: usize, budget: &mut Budget) -> Result<()> { knots(k, p.len(), budget)?; points(p, budget) } + Curve::SurfaceIntersection { surfaces, leader, tolerance } => { + require(tolerance.is_finite() && (0.0..=1e3).contains(tolerance), "intersection tolerance")?; + for s in surfaces { + surface(s, depth + 1, budget)?; + } + // The leader is only a starting guess for the trace: its knots are the producer's, + // and a traced polyline may repeat a point. + require(depth < MAX_DEPTH, "geometry depth")?; + budget.add(1)?; + match &**leader { + Curve::Polyline { points: p } => { + require(p.len() >= 2, "empty intersection leader")?; + points(p, budget) + } + Curve::Spline { knots: k, points: p } => { + knots(k, p.len(), budget)?; + points(p, budget) + } + _ => Err(Invalid("intersection leader")), + } + } } } fn surface(s: &Surface, depth: usize, budget: &mut Budget) -> Result<()> { @@ -200,6 +308,11 @@ fn surface(s: &Surface, depth: usize, budget: &mut Budget) -> Result<()> { points(&[*origin, *u_axis, *v_axis], budget)?; require(vector(*u_axis).cross(vector(*v_axis)).len() > 1e-12, "degenerate plane") } + Surface::PlaneThrough { origin, u_point, v_point } => { + points(&[*origin, *u_point, *v_point], budget)?; + let o = vector(*origin); + require((vector(*u_point) - o).cross(vector(*v_point) - o).len() > 1e-12, "degenerate plane") + } Surface::Cylinder { frame: f, radius: r, angle: a, height } => { frame(f, budget)?; radius(*r)?; @@ -243,6 +356,14 @@ fn surface(s: &Surface, depth: usize, budget: &mut Budget) -> Result<()> { angle(a)?; curve(profile, depth + 1, budget) } + Surface::PlacedRevolution { profile, origin, axis, matrix, .. } => { + points(&[*origin, *axis], budget)?; + require((vector(*axis).len() - 1.0).abs() <= 1e-8, "revolution axis is not unit length")?; + points(matrix, budget)?; + let [x, y, z, _] = matrix.map(|c| vector([c[0], c[1], c[2]])); + require(x.cross(y).dot(z).abs() > 1e-12, "singular revolution placement")?; + curve(profile, depth + 1, budget) + } } } @@ -363,6 +484,31 @@ mod tests { assert!(Budget(MAX_ITEMS).add(1).is_err()); } + #[test] + fn exact_procedural_records_are_validated_and_round_trip() { + let plane = |z: f64| Box::new(Surface::Plane { origin: [0., 0., z], u_axis: [1., 0., 0.], v_axis: [0., 1., 0.] }); + let leader = Box::new(Curve::Polyline { points: vec![[0.; 3], [0.; 3], [1., 0., 0.]] }); + let c = Curve::SurfaceIntersection { surfaces: [plane(0.), plane(1.)], leader: leader.clone(), tolerance: 1e-6 }; + curve(&c, 0, &mut Budget(0)).unwrap(); + assert_eq!(serde_json::from_str::(&serde_json::to_string(&c).unwrap()).unwrap(), c); + let line = Box::new(Curve::Line { start: [0.; 3], end: [1.; 3] }); + for bad in [ + Curve::SurfaceIntersection { surfaces: [plane(0.), plane(1.)], leader: line.clone(), tolerance: 1e-6 }, + Curve::SurfaceIntersection { surfaces: [plane(0.), plane(1.)], leader: leader.clone(), tolerance: f64::NAN }, + Curve::SurfaceIntersection { surfaces: [plane(f64::INFINITY), plane(1.)], leader, tolerance: 1e-6 }, + ] { + assert!(curve(&bad, 0, &mut Budget(0)).is_err()); + } + let identity = [[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]]; + let s = Surface::PlacedRevolution { profile: line.clone(), origin: [0.; 3], axis: [0., 0., 1.], matrix: identity, forward: false }; + surface(&s, 0, &mut Budget(0)).unwrap(); + assert_eq!(serde_json::from_str::(&serde_json::to_string(&s).unwrap()).unwrap(), s); + let mut flat = identity; + flat[2] = [0.; 4]; + let bad = Surface::PlacedRevolution { profile: line, origin: [0.; 3], axis: [0., 0., 1.], matrix: flat, forward: true }; + assert!(surface(&bad, 0, &mut Budget(0)).is_err()); + } + #[test] fn analytic_records_have_independent_frames_and_domains() { use std::f64::consts::{FRAC_PI_2, TAU}; diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index de4a2ef07..aaf73e5d6 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -13,6 +13,7 @@ solidcraft-geom = { workspace = true } solidcraft-kernel = { workspace = true } solidcraft-doc = { workspace = true } thiserror = { workspace = true } +log = { workspace = true } zip = { workspace = true } quick-xml = { workspace = true } gltf = { workspace = true } diff --git a/crates/io/build.rs b/crates/io/build.rs new file mode 100644 index 000000000..45c77eed4 --- /dev/null +++ b/crates/io/build.rs @@ -0,0 +1,20 @@ +//! The commit the model cache is keyed by (`SOLIDCRAFT_SOURCE_COMMIT`): a cache is only the +//! result of evaluating its design when the same source computed it. "unknown" without git (a +//! source tarball), which never trusts a cache. + +use std::process::Command; + +fn git(args: &[&str]) -> Option { + let out = Command::new("git").args(args).output().ok()?; + out.status.success().then(|| String::from_utf8_lossy(&out.stdout).trim().to_string()).filter(|s| !s.is_empty()) +} + +fn main() { + let commit = git(&["rev-parse", "HEAD"]).unwrap_or_else(|| "unknown".into()); + println!("cargo:rustc-env=SOLIDCRAFT_SOURCE_COMMIT={commit}"); + // A new commit in this checkout (or worktree) restamps the build. + if let Some(dir) = git(&["rev-parse", "--git-dir"]) { + println!("cargo:rerun-if-changed={dir}/logs/HEAD"); + } + println!("cargo:rerun-if-changed=build.rs"); +} diff --git a/crates/io/src/design.rs b/crates/io/src/design.rs index e3fbf151d..50a457fe2 100644 --- a/crates/io/src/design.rs +++ b/crates/io/src/design.rs @@ -1,12 +1,13 @@ -//! Versioned design packages. Geometry is rebuilt from authoritative inputs; no -//! evaluated cache is trusted here. Entries are never extracted to filesystem paths. +//! Versioned design packages. Entries are never extracted to filesystem paths. The optional +//! model cache is only read back by the build that wrote it, for the exact document it was +//! written with. use std::collections::{BTreeMap, BTreeSet}; use std::io::{Cursor, Read, Seek, SeekFrom, Write}; use std::sync::Arc; mod native_cache; mod thumbnail; -pub use native_cache::{DesignGeometry, read_design_geometry}; +pub use native_cache::read_design_geometry; pub use thumbnail::{THUMBNAIL_SIZE, read_design_thumbnail, read_design_thumbnail_file}; use serde_json::{Map, Value, json}; @@ -105,13 +106,14 @@ pub fn write_design_container_with_preview(doc: &Document, compression: DesignCo write_design_container_with_cache(doc, compression, preview, None) } -/// Save an optional warm native cache without making document saving depend on it. -/// Display meshes remain separately opt-in; no evaluation or meshing happens here. +/// Save an optional model cache (the evaluated timeline's bodies) without making document +/// saving depend on it. Display meshes remain separately opt-in; no evaluation or meshing +/// happens here. pub fn write_design_container_with_cache( doc: &Document, compression: DesignCompression, preview: Option<&DesignPreview>, - geometry: Option<&[DesignGeometry]>, + geometry: Option<&solidcraft_doc::ModelState>, ) -> Result> { write_design_container_with_thumbnail(doc, compression, preview, geometry, None) } @@ -122,8 +124,21 @@ pub fn write_design_container_with_thumbnail( doc: &Document, compression: DesignCompression, preview: Option<&DesignPreview>, - geometry: Option<&[DesignGeometry]>, + geometry: Option<&solidcraft_doc::ModelState>, thumbnail: Option<&[u8]>, +) -> Result> { + write_container(doc, compression, preview, geometry, thumbnail, MAX_DESIGN_BYTES) +} + +/// [`write_design_container_with_thumbnail`] within `budget` bytes for the optional caches (the +/// container's budget; tests pass less). +fn write_container( + doc: &Document, + compression: DesignCompression, + preview: Option<&DesignPreview>, + geometry: Option<&solidcraft_doc::ModelState>, + thumbnail: Option<&[u8]>, + budget: usize, ) -> Result> { let mut writer = PackageWriter { zip: zip::ZipWriter::new(Cursor::new(Vec::new())), names: BTreeSet::new(), expanded: 0, resolved: 0 }; let mut features = Vec::with_capacity(doc.features.len()); @@ -172,18 +187,28 @@ pub fn write_design_container_with_thumbnail( let metadata = serde_json::to_vec(&metadata).map_err(invalid)?; writer.part("document.json", &metadata, true)?; writer.part("container.json", &serde_json::to_vec(&json!({"format": VERSION})).map_err(invalid)?, false)?; - if let Some((manifest, data)) = geometry.and_then(|g| native_cache::encode_geometry(g, &metadata).ok()) - && writer.names.len().saturating_add(2) <= MAX_ENTRIES - && writer - .expanded - .saturating_add(manifest.len()) - .saturating_add(data.len()) - .saturating_add(writer.names.len().saturating_mul(256)) - .saturating_add(65_536) - <= MAX_DESIGN_BYTES - { - writer.part("cache/key.json", &manifest, false)?; - writer.part("cache/brep.bin", &data, compression == DesignCompression::Compact)?; + // The model cache is optional: one that does not fit the container is left out, never a + // failed save. + let cache = geometry.and_then(|g| native_cache::encode_model(g, &metadata).ok()).filter(|(manifest, data)| { + let fits = writer.names.len().saturating_add(2) <= MAX_ENTRIES + && writer + .expanded + .saturating_add(manifest.len()) + .saturating_add(data.len()) + .saturating_add(writer.names.len().saturating_mul(256)) + .saturating_add(65_536) + <= budget; + if !fits { + log::info!("the model cache ({} MB) does not fit the design file: saved without it", (manifest.len() + data.len()) >> 20); + } + fits + }); + if let Some((manifest, data)) = cache { + let [manifest_entry, payload_entry] = native_cache::ENTRIES; + // Deflated whatever the policy: the encoded bodies shrink about fourfold to tenfold, faster + // than the extra bytes would be written and read. + writer.part(manifest_entry, &manifest, true)?; + writer.part(payload_entry, &data, true)?; } if let Some((manifest, data)) = preview.and_then(|p| encode_preview(p, &metadata).ok()) && writer.names.len().saturating_add(2) <= MAX_ENTRIES @@ -193,7 +218,7 @@ pub fn write_design_container_with_thumbnail( .saturating_add(data.len()) .saturating_add(writer.names.len().saturating_mul(256)) .saturating_add(65_536) - <= MAX_DESIGN_BYTES + <= budget { writer.part("cache/preview.json", &manifest, false)?; writer.part("cache/preview.bin", &data, false)?; @@ -483,7 +508,10 @@ impl DesignContainerReader { pub fn preview(&mut self) -> Option { // An explicitly saved mesh avoids tessellation. Native cache is the default // fallback, generating a bounded provisional mesh without source imports. - read_preview(&mut self.reader).ok().or_else(|| native_cache::geometry_preview(self.geometry()?).ok()) + read_preview(&mut self.reader).ok().or_else(|| { + let document = self.reader.document(16 << 20).ok()?; + native_cache::geometry_preview(&document, self.geometry()?).ok() + }) } /// Portable PNG picture only; no source blobs or geometry are evaluated. @@ -491,8 +519,8 @@ impl DesignContainerReader { thumbnail::read(&mut self.reader).ok() } - /// Native geometry is provisional, never a substitute for rebuilding the document. - pub fn geometry(&mut self) -> Option> { + /// The cached model state, when this build wrote it for exactly this document. + pub fn geometry(&mut self) -> Option { let document = self.reader.document(16 << 20).ok()?; native_cache::read_geometry_with(&mut self.reader, &document).ok() } @@ -693,11 +721,11 @@ mod tests { assert!(result.is_err_and(|e| e.to_string().contains("not a regular file"))); } - fn native_geometry() -> Vec { - vec![DesignGeometry { - name: "Cube".into(), - body: solidcraft_kernel::box_solid(solidcraft_geom::Vec3::ZERO, solidcraft_geom::Vec3::new(10., 20., 30.)).unwrap(), - }] + fn native_geometry() -> solidcraft_doc::ModelState { + let cube = solidcraft_kernel::box_solid(solidcraft_geom::Vec3::ZERO, solidcraft_geom::Vec3::new(10., 20., 30.)).unwrap(); + let mut state = solidcraft_doc::ModelState::default(); + state.bodies.push(solidcraft_doc::ModelBody::new("Cube".into(), cube, 1)); + state } #[test] @@ -709,9 +737,9 @@ mod tests { let bodies = native_geometry(); let bytes = write_design_container_with_cache(&doc, DesignCompression::Fast, None, Some(&bodies)).unwrap(); let entries = parts(&bytes); - assert!(entries.contains_key("cache/brep.bin")); + assert!(entries.contains_key("cache/bodies.bin")); assert!(!entries.contains_key("cache/preview.bin")); - assert_eq!(read_design_geometry(&bytes).unwrap()[0].body.face_count(), bodies[0].body.face_count()); + assert_eq!(read_design_geometry(&bytes).unwrap().bodies[0].body.face_count(), bodies.bodies[0].body.face_count()); assert_eq!(bytes, write_design_container_with_cache(&doc, DesignCompression::Fast, None, Some(&bodies)).unwrap()); let count = std::rc::Rc::new(std::cell::Cell::new(0)); let mut reader = DesignContainerReader::new(CountingReader { source: Cursor::new(bytes), count: count.clone() }).unwrap(); @@ -721,23 +749,73 @@ mod tests { assert!(count.get() >= step.len()); } + #[test] + fn model_cache_stores_repeated_parts_once_and_keeps_placed_copies() { + use solidcraft_geom::Vec3; + let part = solidcraft_kernel::box_solid(Vec3::ZERO, Vec3::new(10., 20., 30.)).unwrap(); + let share = solidcraft_kernel::DisplayShare::new(part.clone()); + let t = [[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [50., 0., 0., 1.]]; + let mut state = solidcraft_doc::ModelState::default(); + state.body_counter = 7; + for (i, body) in [part.clone(), part.clone()].into_iter().enumerate() { + state.bodies.push(solidcraft_doc::ModelBody::new(format!("Part {i}"), body, 1)); + } + for x in [50., 90.] { + let moved = solidcraft_kernel::transform(&part, Vec3::new(x, 0., 0.), Vec3::ZERO, Vec3::Z, 0.).unwrap(); + let mut t = t; + t[3][0] = x; + let mut b = solidcraft_doc::ModelBody::new(format!("Copy {x}"), moved.with_display_share(&share, t), 2); + b.component = 3; + b.source_name = Some("Part".into()); + state.bodies.push(b); + } + let doc = document(); + let bytes = write_design_container_with_cache(&doc, DesignCompression::Fast, None, Some(&state)).unwrap(); + let manifest: Value = serde_json::from_slice(&parts(&bytes)["cache/model.json"]).unwrap(); + assert_eq!(manifest["bodies"].as_array().unwrap().len(), 3, "the part and each placed copy, once each"); + let read = read_design_geometry(&bytes).unwrap(); + assert_eq!(read.body_counter, 7); + assert_eq!(read.bodies.iter().map(|b| b.name.as_str()).collect::>(), ["Part 0", "Part 1", "Copy 50", "Copy 90"]); + let copies: Vec<_> = read.bodies[2..].iter().map(|b| b.body.display_share().unwrap()).collect(); + assert_eq!(copies[0].0.id(), copies[1].0.id(), "copies show one display again"); + assert_eq!(copies[1].1[3][0], 90.); + assert_eq!((read.bodies[3].component, read.bodies[3].source_name.as_deref(), read.bodies[3].feature), (3, Some("Part"), 2)); + for (a, b) in state.bodies.iter().zip(&read.bodies) { + assert_eq!(solidcraft_kernel::encode_native_body(&a.body).unwrap(), solidcraft_kernel::encode_native_body(&b.body).unwrap()); + } + } + + /// A model cache that does not fit the design file is left out: the save succeeds, and the + /// design reads back as saved. + #[test] + fn a_model_cache_too_big_for_the_file_is_left_out_not_a_failed_save() { + let doc = document(); + let bytes = write_container(&doc, DesignCompression::Fast, None, Some(&native_geometry()), None, 70_000).unwrap(); + assert!(!parts(&bytes).contains_key("cache/model.json") && !parts(&bytes).contains_key("cache/bodies.bin")); + assert!(read_design_geometry(&bytes).is_none()); + assert_eq!(crate::read_design(&bytes).unwrap().to_json(), doc.to_json()); + // With room for it, the same model is kept. + let bytes = write_container(&doc, DesignCompression::Fast, None, Some(&native_geometry()), None, MAX_DESIGN_BYTES).unwrap(); + assert!(read_design_geometry(&bytes).is_some()); + } + #[test] fn native_cache_mismatch_is_only_a_cache_miss() { let doc = document(); let bytes = write_design_container_with_cache(&doc, DesignCompression::Fast, None, Some(&native_geometry())).unwrap(); let original = parts(&bytes); - for key in ["format", "producer", "app", "document", "payload"] { + for key in ["format", "producer", "app", "build", "document", "payload"] { let mut entries = original.clone(); - let mut manifest: Value = serde_json::from_slice(&entries["cache/key.json"]).unwrap(); + let mut manifest: Value = serde_json::from_slice(&entries["cache/model.json"]).unwrap(); manifest[key] = json!("unsupported-or-stale"); - entries.insert("cache/key.json".into(), serde_json::to_vec(&manifest).unwrap()); + entries.insert("cache/model.json".into(), serde_json::to_vec(&manifest).unwrap()); let bytes = package(&entries); assert!(read_design_geometry(&bytes).is_none()); assert!(read_design_preview(&bytes).is_none()); assert_eq!(crate::read_design(&bytes).unwrap().to_json(), doc.to_json()); } let mut entries = original; - entries.get_mut("cache/brep.bin").unwrap()[0] ^= 1; + entries.get_mut("cache/bodies.bin").unwrap()[0] ^= 1; let bytes = package(&entries); assert!(read_design_geometry(&bytes).is_none()); assert_eq!(crate::read_design(&bytes).unwrap().to_json(), doc.to_json()); diff --git a/crates/io/src/design/native_cache.rs b/crates/io/src/design/native_cache.rs index bfa6b42e4..3450e7c1a 100644 --- a/crates/io/src/design/native_cache.rs +++ b/crates/io/src/design/native_cache.rs @@ -1,105 +1,250 @@ -//! Optional native cache. Its SolidCraft schema is independent of the producing kernel. +//! The model cache: the evaluated bodies of a design's timeline, saved with it so opening need +//! not rebuild them. Its SolidCraft schema is independent of the producing kernel; its key ties it +//! to the exact document, build and platform that computed it (docs/design-container.md). use super::*; -const PRODUCER: &str = "solidcraft-truck-adapter/2"; -/// Provisional evaluated geometry. Never an editable document state. -#[derive(Clone)] -pub struct DesignGeometry { - pub name: String, - pub body: solidcraft_kernel::Body, +use solidcraft_doc::{ModelBody, ModelState}; + +const FORMAT: &str = "solidcraft-model-cache/1"; +const PRODUCER: &str = "solidcraft-truck-adapter/3"; +const MANIFEST: &str = "cache/model.json"; +const PAYLOAD: &str = "cache/bodies.bin"; +/// Body records (a placed copy is one record; its part is stored once). +const MAX_RECORDS: usize = 200_000; +/// Distinct stored bodies. +const MAX_UNIQUE: usize = 100_000; +const MAX_MANIFEST: usize = 32 << 20; + +/// The build that computed a cache: the same source, compiled for the same platform, computes the +/// same numbers, so only its own caches are its results. +fn build() -> String { + format!("{}/{}-{}", env!("SOLIDCRAFT_SOURCE_COMMIT"), std::env::consts::ARCH, std::env::consts::OS) } -pub(super) fn encode_geometry(bodies: &[DesignGeometry], document: &[u8]) -> Result<(Vec, Vec)> { - if bodies.is_empty() || bodies.len() > 4096 { - return Err(invalid("native body count")); + +/// A 4 x 4 matrix as its 16 numbers, in storage order. +fn matrix(t: &[[f64; 4]; 4]) -> Vec { + t.iter().flatten().copied().collect() +} + +fn look(look: &solidcraft_doc::appearance::ImportedLook) -> Value { + let faces: Vec = look.faces.iter().map(|(name, (color, opacity))| json!([name, color, opacity])).collect(); + json!({"color": look.color, "opacity": look.opacity, "faces": faces}) +} + +fn load_look(v: &Value) -> Result { + let unit = |x: f32| x.is_finite() && (0.0..=1.0).contains(&x); + let color = |v: &Value| -> Result> { + let c: Option<[f32; 3]> = serde_json::from_value(v.clone()).map_err(invalid)?; + if c.is_some_and(|c| !c.iter().copied().all(unit)) { + return Err(invalid("cached colour")); + } + Ok(c) + }; + let opacity: Option = serde_json::from_value(v.get("opacity").cloned().unwrap_or(Value::Null)).map_err(invalid)?; + if opacity.is_some_and(|o| !unit(o)) { + return Err(invalid("cached opacity")); } + let mut faces = BTreeMap::new(); + for f in v.get("faces").and_then(Value::as_array).ok_or_else(|| invalid("cached face looks"))? { + let name = f.get(0).and_then(Value::as_str).filter(|n| n.len() <= 1024).ok_or_else(|| invalid("cached face name"))?; + let c = color(f.get(1).unwrap_or(&Value::Null))?.ok_or_else(|| invalid("cached face colour"))?; + let o = f.get(2).and_then(Value::as_f64).map(|o| o as f32).filter(|o| unit(*o)).ok_or_else(|| invalid("cached face opacity"))?; + faces.insert(name.to_owned(), (c, o)); + } + Ok(solidcraft_doc::appearance::ImportedLook { color: color(v.get("color").unwrap_or(&Value::Null))?, opacity, faces }) +} + +/// Encode a model state's bodies. Identical bodies (the same part placed many times, a body a +/// feature passed through) are stored once; a placed copy of a part records the part and its +/// matrix, so it shows that part's display as it did before saving. +pub(super) fn encode_model(state: &ModelState, document: &[u8]) -> Result<(Vec, Vec)> { + if state.bodies.is_empty() || state.bodies.len() > MAX_RECORDS { + return Err(invalid("cached body count")); + } + // What to encode: every body, and the part every placed copy shows. + let mut shares: Vec = Vec::new(); + let mut share_index = std::collections::HashMap::new(); + for b in &state.bodies { + if let Some((share, _)) = b.body.display_share() { + share_index.entry(share.id()).or_insert_with(|| { + shares.push(share.clone()); + shares.len() - 1 + }); + } + } + let bodies: Vec<&solidcraft_kernel::Body> = state.bodies.iter().map(|b| &b.body).chain(shares.iter().map(|s| s.original())).collect(); + let encoded = solidcraft_kernel::map_on_threads(&bodies, 16, |b| solidcraft_kernel::encode_native_body(b).ok()); let mut data = Vec::new(); - let mut entries = Vec::new(); - let mut faces = 0usize; - for entry in bodies { - faces = faces.saturating_add(entry.body.face_count()); - if faces > 100_000 || entry.name.len() > 1024 { - return Err(invalid("native geometry budget")); + let mut slices = Vec::new(); + let mut by_digest = std::collections::HashMap::new(); + let mut index = Vec::with_capacity(encoded.len()); + for bytes in encoded { + let bytes = bytes.flatten().ok_or_else(|| invalid("body not stored exactly"))?; + let next = slices.len(); + let i = *by_digest.entry(Sha256::digest(&bytes)).or_insert(next); + if i == next { + if data.len().saturating_add(bytes.len()) > MAX_DESIGN_BYTES || slices.len() >= MAX_UNIQUE { + return Err(invalid("model cache size")); + } + slices.push(json!([data.len(), bytes.len()])); + data.extend(bytes); } - let bytes = solidcraft_kernel::encode_native_body(&entry.body).map_err(invalid)?; - let offset = data.len(); - if offset.saturating_add(bytes.len()) > 64 << 20 { - return Err(invalid("native cache size")); + index.push(i); + } + let (body_index, share_body) = index.split_at(state.bodies.len()); + let mut records = Vec::with_capacity(state.bodies.len()); + for (b, i) in state.bodies.iter().zip(body_index) { + if b.name.len() > 1024 { + return Err(invalid("cached body name")); } - entries.push(json!({"name":entry.name,"offset":offset,"length":bytes.len()})); - data.extend(bytes); + let mut r = json!({"name": b.name, "body": i, "feature": b.feature, "component": b.component}); + if let Some(source) = &b.source_name { + r["source_name"] = json!(source); + } + if b.source_transform != solidcraft_doc::IDENTITY { + r["source_transform"] = json!(matrix(&b.source_transform)); + } + if b.transferred { + r["transferred"] = json!(true); + } + if let Some(l) = &b.imported { + r["imported"] = look(l); + } + if let Some((share, t)) = b.body.display_share() { + let s = share_index.get(&share.id()).ok_or_else(|| invalid("display share"))?; + r["share"] = json!([s, matrix(&t)]); + } + records.push(r); } let manifest = serde_json::to_vec(&json!({ - "format":"solidcraft-brep-cache/1", "producer":PRODUCER, - "app":env!("CARGO_PKG_VERSION"), "document":digest(document), "payload":digest(&data), "bodies":entries + "format": FORMAT, "producer": PRODUCER, "app": env!("CARGO_PKG_VERSION"), "build": build(), + "document": digest(document), "payload": digest(&data), + "bodies": slices, "shares": share_body, "body_counter": state.body_counter, "state": records, })) .map_err(invalid)?; - if manifest.len() > 1 << 20 { - return Err(invalid("native manifest size")); + if manifest.len() > MAX_MANIFEST { + return Err(invalid("model cache manifest size")); } Ok((manifest, data)) } -/// Read only metadata and the native cache. Original blobs are not read/decompressed -/// until the authoritative document reader needs them for background reconstruction. -/// Any optional geometry failure is a miss, never a document error. -pub fn read_design_geometry(bytes: &[u8]) -> Option> { +/// The cached model state of a design, when it holds one this build computed for exactly this +/// document. Any failure is a miss, never a document error. +pub fn read_design_geometry(bytes: &[u8]) -> Option { if bytes.len() > MAX_DESIGN_BYTES || !is_design_container(bytes) { return None; } DesignContainerReader::new(Cursor::new(bytes)).ok()?.geometry() } -pub(super) fn read_geometry_with(reader: &mut PackageReader, document: &[u8]) -> Result> { + +/// Whether `manifest` is a model cache this build wrote for `document`. +fn current(manifest: &Value, document: &[u8]) -> bool { + let is = |key: &str, value: &str| manifest.get(key).and_then(Value::as_str) == Some(value); + is("format", FORMAT) + && is("producer", PRODUCER) + && is("app", env!("CARGO_PKG_VERSION")) + && is("build", &build()) + && is("document", &digest(document)) + // A development build of unknown source never trusts a cache. + && env!("SOLIDCRAFT_SOURCE_COMMIT") != "unknown" +} + +pub(super) fn read_geometry_with(reader: &mut PackageReader, document: &[u8]) -> Result { let container: Value = serde_json::from_slice(&reader.limited_part("container.json", 4096)?).map_err(invalid)?; if container.get("format").and_then(Value::as_str) != Some(VERSION) { return Err(invalid("container version")); } - let manifest: Value = serde_json::from_slice(&reader.limited_part("cache/key.json", 1 << 20)?).map_err(invalid)?; - if manifest.get("format").and_then(Value::as_str) != Some("solidcraft-brep-cache/1") - || manifest.get("producer").and_then(Value::as_str) != Some(PRODUCER) - || manifest.get("app").and_then(Value::as_str) != Some(env!("CARGO_PKG_VERSION")) - { - return Err(invalid("native cache version")); + let manifest: Value = serde_json::from_slice(&reader.limited_part(MANIFEST, MAX_MANIFEST)?).map_err(invalid)?; + if !current(&manifest, document) { + return Err(invalid("model cache key")); } - - if manifest.get("document").and_then(Value::as_str) != Some(digest(document).as_str()) { - return Err(invalid("native document key")); - } - // Validate the small parametric metadata before showing a provisional model. + // Validate the small parametric metadata before decoding any geometry. Document::from_json(std::str::from_utf8(document).map_err(invalid)?)?; - let data = reader.limited_part("cache/brep.bin", 64 << 20)?; + let data = reader.limited_part(PAYLOAD, MAX_DESIGN_BYTES)?; if manifest.get("payload").and_then(Value::as_str) != Some(digest(&data).as_str()) { - return Err(invalid("native payload key")); + return Err(invalid("model cache payload key")); } - let entries = - manifest.get("bodies").and_then(Value::as_array).filter(|b| !b.is_empty() && b.len() <= 4096).ok_or_else(|| invalid("native bodies"))?; - let mut bodies = Vec::new(); + let count = |v: &Value| v.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or_else(|| invalid("model cache number")); + let slices = manifest + .get("bodies") + .and_then(Value::as_array) + .filter(|b| !b.is_empty() && b.len() <= MAX_UNIQUE) + .ok_or_else(|| invalid("cached bodies"))?; let mut end = 0usize; - let mut faces = 0usize; - for entry in entries { - let n = |key| entry.get(key).and_then(Value::as_u64).and_then(|n| usize::try_from(n).ok()).ok_or_else(|| invalid("native slice")); - let offset = n("offset")?; - let length = n("length")?; + let mut parts = Vec::with_capacity(slices.len()); + for s in slices { + let (offset, length) = (count(s.get(0).unwrap_or(&Value::Null))?, count(s.get(1).unwrap_or(&Value::Null))?); if offset != end { - return Err(invalid("overlapping native bodies")); + return Err(invalid("overlapping cached bodies")); } - end = end.checked_add(length).ok_or_else(|| invalid("native length overflow"))?; - let name = entry.get("name").and_then(Value::as_str).filter(|n| n.len() <= 1024).ok_or_else(|| invalid("native body name"))?.to_owned(); - let body = solidcraft_kernel::decode_native_body(data.get(offset..end).ok_or_else(|| invalid("truncated native body"))?).map_err(invalid)?; - faces = faces.saturating_add(body.face_count()); - if faces > 100_000 { - return Err(invalid("native face budget")); - } - bodies.push(DesignGeometry { name, body }); + end = end.checked_add(length).ok_or_else(|| invalid("cached body length"))?; + parts.push(data.get(offset..end).ok_or_else(|| invalid("truncated cached body"))?); } if end != data.len() { - return Err(invalid("trailing native data")); + return Err(invalid("trailing cached data")); } - Ok(bodies) + let decoded = solidcraft_kernel::map_on_threads(&parts, 16, |bytes| solidcraft_kernel::decode_native_body(bytes).ok()); + let bodies = decoded.into_iter().map(Option::flatten).collect::>>().ok_or_else(|| invalid("cached body"))?; + let body = |v: &Value| bodies.get(count(v)?).ok_or_else(|| invalid("cached body index")); + let shares = manifest + .get("shares") + .and_then(Value::as_array) + .filter(|s| s.len() <= MAX_UNIQUE) + .ok_or_else(|| invalid("cached shares"))? + .iter() + .map(|i| Ok(solidcraft_kernel::DisplayShare::new(body(i)?.clone()))) + .collect::>>()?; + let records = + manifest.get("state").and_then(Value::as_array).filter(|s| !s.is_empty() && s.len() <= MAX_RECORDS).ok_or_else(|| invalid("cached state"))?; + let mut state = ModelState::default(); + state.body_counter = count(manifest.get("body_counter").unwrap_or(&Value::Null))?; + for r in records { + let name = r.get("name").and_then(Value::as_str).filter(|n| n.len() <= 1024).ok_or_else(|| invalid("cached body name"))?; + let mut kernel_body = body(r.get("body").unwrap_or(&Value::Null))?.clone(); + if let Some(share) = r.get("share") { + let s = shares.get(count(share.get(0).unwrap_or(&Value::Null))?).ok_or_else(|| invalid("cached share index"))?; + let numbers: Vec = serde_json::from_value(share.get(1).cloned().unwrap_or(Value::Null)).map_err(invalid)?; + let t = matrix_of(&numbers)?; + kernel_body = kernel_body.with_display_share(s, t); + } + let feature = r.get("feature").and_then(Value::as_u64).ok_or_else(|| invalid("cached body feature"))?; + let mut b = ModelBody::new(name.to_owned(), kernel_body, feature); + b.component = r.get("component").and_then(Value::as_u64).ok_or_else(|| invalid("cached body component"))?; + b.source_name = match r.get("source_name") { + None => None, + Some(v) => Some(v.as_str().filter(|n| n.len() <= 1024).ok_or_else(|| invalid("cached source name"))?.to_owned()), + }; + if let Some(v) = r.get("source_transform") { + let numbers: Vec = serde_json::from_value(v.clone()).map_err(invalid)?; + b.source_transform = matrix_of(&numbers)?; + } + b.transferred = r.get("transferred").and_then(Value::as_bool).unwrap_or(false); + if let Some(l) = r.get("imported") { + b.imported = Some(Arc::new(load_look(l)?)); + } + state.bodies.push(b); + } + Ok(state) } -pub(super) fn geometry_preview(bodies: Vec) -> Result { + +/// A 4 x 4 matrix from its 16 numbers in storage order, finite. +fn matrix_of(numbers: &[f64]) -> Result<[[f64; 4]; 4]> { + if numbers.len() != 16 || numbers.iter().any(|x| !x.is_finite() || x.abs() > 1e12) { + return Err(invalid("cached matrix")); + } + let mut t = [[0.0; 4]; 4]; + for (slot, x) in t.iter_mut().flatten().zip(numbers) { + *slot = *x; + } + Ok(t) +} + +pub(super) fn geometry_preview(document: &[u8], state: ModelState) -> Result { + let doc = Document::from_json(std::str::from_utf8(document).map_err(invalid)?)?; + let world = solidcraft_doc::world_state(&doc, &state); let mut preview = DesignPreview::default(); let mut triangles = 0usize; let mut display_bytes = 0usize; - let faces: usize = bodies.iter().map(|b| b.body.face_count()).sum(); + let faces: usize = world.bodies.iter().map(|b| b.body.face_count()).sum(); let detail = if faces > 20_000 { 1 } else if faces > 4_000 { @@ -108,7 +253,7 @@ pub(super) fn geometry_preview(bodies: Vec) -> Result) -> Result) -> Result); + +impl DisplayShare { + pub fn new(original: Body) -> Self { + DisplayShare(std::sync::Arc::new(SharedDisplay::new(original))) + } + /// The body whose display the copies show. + pub fn original(&self) -> &Body { + &self.0.original + } + /// Identity: copies that show the same display have the same id. + pub fn id(&self) -> usize { + std::sync::Arc::as_ptr(&self.0) as usize + } +} + /// `m` placed by the rigid matrix `t` (by columns, translation in `t[3]`, as the kernel's /// transforms take it): positions, normals and edge polylines move, everything indexed stays. /// `None` for anything but a rotation and translation (a reflection would turn the triangles @@ -976,6 +995,23 @@ impl Body { self } + /// The display this body shows placed by a matrix (by columns), when it is a placed copy of + /// another body. + pub fn display_share(&self) -> Option<(DisplayShare, [[f64; 4]; 4])> { + self.display_of.as_deref().map(|(shared, t)| (DisplayShare(shared.clone()), *t)) + } + + /// The same body showing `share`'s display placed by `t` (see [`Body::display_share`]). + pub fn with_display_share(self, share: &DisplayShare, t: [[f64; 4]; 4]) -> Body { + self.with_display_of(share.0.clone(), t) + } + + /// Identity of the solid: clones of a body (and bodies a feature passed through unchanged) + /// share it. + pub fn solid_id(&self) -> usize { + std::sync::Arc::as_ptr(&self.solid) as usize + } + pub fn with_split_lines(mut self, s: Option>>>) -> Body { self.splits = s.filter(|l| !l.is_empty()); // Split lines are drawn: the shared mesh does not have them. diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rs index ece2cdc96..a49cb3ced 100644 --- a/crates/kernel/src/lib.rs +++ b/crates/kernel/src/lib.rs @@ -153,7 +153,7 @@ pub mod watch; pub use blend::{ChamferSide, chamfer, chamfer_sides, fillet, fillet_each, fillet_g2, fillet_g2_corners, fillet_max, fillet_max_each}; pub use blend_corner::fillet_radii; pub use blend_variable::{RadiusSpline, Taper, fillet_chord, fillet_tapered, fillet_variable, fillet_variable_points, fillet_variable_spline, taper}; -pub use body::{Body, CapSignature, DISPLAY_ANGLE, EdgeInfo, FaceInfo, FacePaint, FaceSource, Paint}; +pub use body::{Body, CapSignature, DISPLAY_ANGLE, DisplayShare, EdgeInfo, FaceInfo, FacePaint, FaceSource, Paint}; pub use boolean_diagnostics::{BooleanDiagnostics, BooleanFallback, BooleanStrategy, capture_boolean_diagnostics}; pub use boundary::{Boundary, boundary_patch}; pub use boundary_network::{BoundaryCurve, CurveSource, MAX_CHAIN_CURVES, MAX_EDGE_PICKS, boundary_join, boundary_surface}; diff --git a/crates/kernel/src/native.rs b/crates/kernel/src/native.rs index 3afaf3bee..0b1af58a5 100644 --- a/crates/kernel/src/native.rs +++ b/crates/kernel/src/native.rs @@ -1,5 +1,5 @@ //! SolidCraft native, versioned binary geometry. No STEP conversion or display meshes. -//! A cache remains provisional until the document is rebuilt; hashes are not trust. +//! Exact: a decoded body is the encoded one, number for number, for the same producer. use crate::{Body, KernelError, Result, guard}; use serde::{Deserialize, Serialize}; use serde_json::{Map, Number, Value}; @@ -11,23 +11,38 @@ mod metadata; mod preview; pub use preview::native_preview_mesh; -// 01/02 were development-only prototypes; independent metadata records start at 03. -const MAGIC: &[u8; 8] = b"SCBREP03"; -const MAX_BYTES: usize = 64 << 20; -const MAX_ITEMS: usize = 100_000; +// 01/02 were development-only prototypes; independent metadata records start at 03; 04 stores +// procedural intersections and placed revolutions exactly, and the measured runtime values. +const MAGIC: &[u8; 8] = b"SCBREP04"; +// A body's own limits. A design's cache holds many bodies within the container's budgets, and +// decoding is linear in the bytes, so one large part (an imported casting) fits. +const MAX_BYTES: usize = 256 << 20; +const MAX_ITEMS: usize = 1_000_000; +const MAX_VALUES: usize = 20_000_000; #[derive(Serialize, Deserialize)] #[serde(deny_unknown_fields)] struct SavedBody { solid: solidcraft_geom::brep::Brep, metadata: solidcraft_geom::brep::envelope::Metadata, + runtime: Runtime, +} + +/// What a body measured about itself that later operations read: kept so a decoded body works +/// to the same tolerances as the one encoded, without measuring again. +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Runtime { + /// [`Body::size`] as stored (0: not measured). + size: f64, + /// The orientation mesh's missing-face count at its tolerance. + coarse_missing: Option<(f64, u64)>, } fn invalid(detail: impl std::fmt::Display) -> KernelError { KernelError::Invalid(format!("native B-rep: {detail}")) } -/// Explicit topology, spatial geometry, construction certificates and history. -/// Procedural intersections use bounded fitting for provisional cache display. +/// Explicit topology, spatial geometry, construction certificates and history, exactly. /// Failure is a cache miss at the IO boundary, never a failed document save. pub fn encode_native_body(body: &Body) -> Result> { guard("encode native B-rep", || { @@ -51,12 +66,13 @@ pub fn encode_native_body(body: &Body) -> Result> { if body.mesh.is_some() { return Err(invalid("mesh bodies are source blobs, not B-rep")); } - let saved = SavedBody { solid: adapter::encode(&body.solid)?, metadata: metadata::encode(body)? }; + let runtime = Runtime { size: body.size, coarse_missing: body.coarse_missing.map(|(tol, n)| (tol, n as u64)) }; + let saved = SavedBody { solid: adapter::encode(&body.solid)?, metadata: metadata::encode(body)?, runtime }; // Structural validation does not invoke another geometric reconstruction. validate_topology(&saved)?; let value = serde_json::to_value(saved).map_err(invalid)?; validate_value(&value, 0)?; - if value_nodes(&value) > 2_000_000 { + if value_nodes(&value) > MAX_VALUES { return Err(invalid("value budget")); } let mut out = MAGIC.to_vec(); @@ -66,14 +82,14 @@ pub fn encode_native_body(body: &Body) -> Result> { } /// Decode bounded untrusted data. Validate indices before topology extraction. -/// Callers must not treat the decoded body as authoritative editing geometry. +/// Only a caller that has checked who produced the data may treat it as evaluated geometry. pub fn decode_native_body(bytes: &[u8]) -> Result { if bytes.len() > MAX_BYTES || bytes.get(..8) != Some(MAGIC.as_slice()) { return Err(invalid("version or size")); } guard("decode native B-rep", || { let mut input = bytes.get(8..).ok_or_else(|| invalid("header"))?; - let mut remaining = 2_000_000usize; + let mut remaining = MAX_VALUES; let value = binary::read(&mut input, 0, &mut remaining)?; if !input.is_empty() { return Err(invalid("trailing data")); @@ -82,11 +98,15 @@ pub fn decode_native_body(bytes: &[u8]) -> Result { let saved: SavedBody = serde_json::from_value(value).map_err(invalid)?; validate_topology(&saved)?; let solid = adapter::decode(saved.solid)?; + let Runtime { size, coarse_missing } = saved.runtime; + if !(size.is_finite() && size >= 0.0) || coarse_missing.is_some_and(|(tol, n)| !tol.is_finite() || n > MAX_ITEMS as u64) { + return Err(invalid("runtime values")); + } let mut body = Body { solid: Arc::new(solid), - size: 0.0, + size, volume: Some(std::sync::Arc::new(std::sync::Mutex::new(None))), - coarse_missing: None, + coarse_missing: coarse_missing.map(|(tol, n)| (tol, n as usize)), mesh: None, color: None, paint: None, @@ -233,7 +253,7 @@ mod tests { .iter() .map(|body| { let bytes = encode_native_body(body).unwrap(); - assert_eq!(&bytes[..8], b"SCBREP03"); + assert_eq!(&bytes[..8], b"SCBREP04"); let mut raw = &bytes[8..]; let value = binary::read(&mut raw, 0, &mut 2_000_000).unwrap(); assert!(raw.is_empty()); @@ -241,7 +261,7 @@ mod tests { }) .collect(); let actual = serde_json::json!(records); - let expected: Value = serde_json::from_str(include_str!("native/fixtures/box-fillet-v3.json")).unwrap(); + let expected: Value = serde_json::from_str(include_str!("native/fixtures/box-fillet-v4.json")).unwrap(); compare_wire(&expected, &actual); } diff --git a/crates/kernel/src/native/adapter.rs b/crates/kernel/src/native/adapter.rs index ba661ec87..800724439 100644 --- a/crates/kernel/src/native/adapter.rs +++ b/crates/kernel/src/native/adapter.rs @@ -1,17 +1,12 @@ //! The truck adapter. Persisted data belongs to solidcraft_geom::brep, never truck. use super::{Result, invalid}; -use mt::{BoundedCurve, EuclideanSpace, InnerSpace, Invertible, ParametricCurve, Transform, Transformed}; +use mt::Invertible; use solidcraft_geom::brep as b; use truck_modeling as mt; -use truck_topology::compress as t; -type Packed = t::CompressedSolid; #[path = "analytic.rs"] mod analytic; -#[path = "fit.rs"] -mod fit; use analytic::{arc, full_turn, load_analytic, revolved}; -use fit::fit_intersection; fn point(p: mt::Point3) -> [f64; 3] { [p.x, p.y, p.z] } @@ -51,6 +46,8 @@ fn compatible_curve(c: &b::Curve) -> Result<()> { b::Curve::Spline { knots, points } => clamped(knots, points.len()), b::Curve::RationalSpline { knots, homogeneous } => clamped(knots, homogeneous.len()), b::Curve::Intersection { knots, points, .. } => clamped(knots, points.len()), + // The producer's own trace: its surfaces must load; its leader is kept as it was. + b::Curve::SurfaceIntersection { surfaces, .. } => surfaces.iter().try_for_each(|s| compatible_surface(s)), _ => Ok(()), } } @@ -75,6 +72,8 @@ fn compatible_surface(s: &b::Surface) -> Result<()> { full_turn(angle)?; compatible_curve(profile) } + b::Surface::PlaneThrough { .. } => Ok(()), + b::Surface::PlacedRevolution { profile, .. } => compatible_curve(profile), b::Surface::Cylinder { angle, .. } | b::Surface::Cone { angle, .. } => full_turn(angle), b::Surface::Sphere { longitude, .. } | b::Surface::Torus { longitude, .. } => full_turn(longitude), } @@ -93,19 +92,18 @@ fn compatible(body: &b::Brep) -> Result<()> { pub(super) fn encode(solid: &mt::Solid) -> Result { let mut shells = Vec::new(); - let mut fitting_budget = 4096usize; for shell in solid.compress().boundaries { let vertices = shell.vertices.into_iter().map(point).collect(); let edges = shell .edges .into_iter() - .map(|e| Ok(b::Edge { vertices: [index(e.vertices.0)?, index(e.vertices.1)?], curve: save_curve(&e.curve, 0, &mut fitting_budget)? })) + .map(|e| Ok(b::Edge { vertices: [index(e.vertices.0)?, index(e.vertices.1)?], curve: save_curve(&e.curve, 0)? })) .collect::>()?; let faces = shell .faces .into_iter() .map(|f| { - let (surface, normal_flip) = save_surface(&f.surface, 0, &mut fitting_budget)?; + let surface = save_surface(&f.surface, 0)?; Ok(b::Face { loops: f .boundaries @@ -123,7 +121,7 @@ pub(super) fn encode(solid: &mt::Solid) -> Result { }) .collect::>()?, surface, - forward: f.orientation != normal_flip, + forward: f.orientation, }) }) .collect::>()?; @@ -137,60 +135,60 @@ pub(super) fn encode(solid: &mt::Solid) -> Result { pub(super) fn decode(body: b::Brep) -> Result { body.validate().map_err(invalid)?; compatible(&body)?; - if body.shells.iter().flat_map(|s| &s.edges).any(|e| e.vertices[0] == e.vertices[1]) { - return Err(invalid("closed single-vertex edges are unsupported by this adapter")); - } - let packed = Packed { - boundaries: body - .shells - .into_iter() - .map(|s| { - Ok(t::CompressedShell { - vertices: s.vertices.into_iter().map(p).collect(), - edges: s - .edges - .into_iter() - .map(|e| Ok(t::CompressedEdge { vertices: (e.vertices[0] as usize, e.vertices[1] as usize), curve: load_curve(e.curve)? })) - .collect::>()?, - faces: s - .faces - .into_iter() - .map(|f| { - let mut loops = f.loops; - if !f.forward { - for wire in &mut loops { - reverse_wire(wire); - } - } - Ok(t::CompressedFace { - boundaries: loops - .into_iter() - .map(|w| { - w.into_iter().map(|e| t::CompressedEdgeIndex { index: e.edge as usize, orientation: e.forward }).collect() - }) - .collect(), - orientation: f.forward, - surface: load_surface(f.surface)?, - }) - }) - .collect::>()?, - }) - }) - .collect::>()?, - }; - let shells = packed.boundaries.into_iter().map(mt::Shell::extract).collect::, _>>().map_err(invalid)?; + let shells = body.shells.into_iter().map(shell).collect::>>()?; if shells.iter().any(|s| s.shell_condition() == mt::ShellCondition::Irregular) { return Err(invalid("non-manifold shell")); } Ok(mt::Solid::new_unchecked(shells)) } +/// A shell's topology as recorded, references already checked: built as the kernel built it, +/// without truck's checks for wires that touch themselves (a seam edge used twice, a closed edge +/// on one vertex), which imported and modelled faces have. +fn shell(s: b::Shell) -> Result { + let vertices: Vec = s.vertices.into_iter().map(|v| mt::Vertex::new(p(v))).collect(); + let vertex = |i: u32| vertices.get(i as usize).ok_or_else(|| invalid("edge vertices")); + let edges = s + .edges + .into_iter() + .map(|e| Ok(mt::Edge::new_unchecked(vertex(e.vertices[0])?, vertex(e.vertices[1])?, load_curve(e.curve)?))) + .collect::>>()?; + s.faces + .into_iter() + .map(|f| { + let mut loops = f.loops; + if !f.forward { + for wire in &mut loops { + reverse_wire(wire); + } + } + let wires = loops + .into_iter() + .map(|w| { + w.into_iter() + .map(|u| { + let e = edges.get(u.edge as usize).ok_or_else(|| invalid("edge reference"))?; + Ok(if u.forward { e.clone() } else { e.inverse() }) + }) + .collect::>() + }) + .collect::>>()?; + let mut face = mt::Face::new_unchecked(wires, load_surface(f.surface)?); + if !f.forward { + face.invert(); + } + Ok(face) + }) + .collect() +} fn reverse_wire(wire: &mut [b::EdgeUse]) { wire.reverse(); for edge in wire { edge.forward = !edge.forward; } } -fn save_curve(c: &mt::Curve, d: usize, fitting_budget: &mut usize) -> Result { +/// Exact: every record holds the producer's own numbers, so loading it gives back the same +/// curve, never a refit. +fn save_curve(c: &mt::Curve, d: usize) -> Result { depth(d)?; Ok(match c { mt::Curve::Line(c) => b::Curve::Line { start: point(c.0), end: point(c.1) }, @@ -201,14 +199,56 @@ fn save_curve(c: &mt::Curve, d: usize, fitting_budget: &mut usize) -> Result fit_intersection(c, fitting_budget)?, + mt::Curve::IntersectionCurve(c) => { + let leader = match c.leader() { + mt::Leader::Polyline(p) => b::Curve::Polyline { points: p.0.iter().copied().map(point).collect() }, + mt::Leader::BSpline(c) => b::Curve::Spline { + knots: c.knot_vec().iter().copied().collect(), + points: c.control_points().iter().copied().map(point).collect(), + }, + }; + b::Curve::SurfaceIntersection { + surfaces: [Box::new(save_surface(c.surface0(), d + 1)?), Box::new(save_surface(c.surface1(), d + 1)?)], + leader: Box::new(leader), + tolerance: c.tolerance(), + } + } }) } -fn save_surface(s: &mt::Surface, d: usize, fitting_budget: &mut usize) -> Result<(b::Surface, bool)> { +/// A plane as truck holds it: three points. +#[derive(serde::Serialize, serde::Deserialize)] +struct PlanePoints { + o: mt::Point3, + p: mt::Point3, + q: mt::Point3, +} + +/// A revolution as truck holds it, built from its parts as they are (its constructors normalize +/// the axis and compose the placement with the identity, either of which can round). +#[derive(serde::Serialize)] +struct PlacedRevolution { + entity: Revolved, + transform: mt::Matrix4, + orientation: bool, +} +#[derive(serde::Serialize)] +struct Revolved { + curve: mt::Curve, + revolution: Axis, +} +#[derive(serde::Serialize)] +struct Axis { + origin: mt::Point3, + axis: mt::Vector3, +} + +fn save_surface(s: &mt::Surface, d: usize) -> Result { depth(d)?; - let mut normal_flip = false; - let saved = match s { - mt::Surface::Plane(s) => b::Surface::Plane { origin: point(s.origin()), u_axis: vector(s.u_axis()), v_axis: vector(s.v_axis()) }, + Ok(match s { + mt::Surface::Plane(s) => { + let PlanePoints { o, p, q } = serde_json::from_value(serde_json::to_value(s).map_err(invalid)?).map_err(invalid)?; + b::Surface::PlaneThrough { origin: point(o), u_point: point(p), v_point: point(q) } + } mt::Surface::BSplineSurface(s) => b::Surface::Spline { u_knots: s.uknot_vec().iter().copied().collect(), v_knots: s.vknot_vec().iter().copied().collect(), @@ -220,39 +260,16 @@ fn save_surface(s: &mt::Surface, d: usize, fitting_budget: &mut usize) -> Result homogeneous: s.control_points().iter().map(|r| r.iter().copied().map(vector4).collect()).collect(), }, mt::Surface::RevolutedCurve(s) => { - let m = s.transform(); - let (x, y, z) = (m.x.truncate(), m.y.truncate(), m.z.truncate()); - let scale = x.magnitude(); - let tolerance = scale * 1e-10; - if !scale.is_finite() - || scale <= 1e-12 - || (y.magnitude() - scale).abs() > tolerance - || (z.magnitude() - scale).abs() > tolerance - || x.dot(y).abs() > scale * tolerance - || x.dot(z).abs() > scale * tolerance - || y.dot(z).abs() > scale * tolerance - || m.x.w != 0. - || m.y.w != 0. - || m.z.w != 0. - || m.w.w != 1. - { - return Err(invalid("non-similarity revolution transform needs an exact spline conversion")); - } - // Bake a similarity into the geometry, never into persisted processor data. - // An improper rotation reverses the oriented axis in the rotation identity. - let sign = if x.dot(y.cross(z)) < 0. { -1. } else { 1. }; - let axis = m.transform_vector(s.entity().axis()).normalize() * sign; - let profile = s.entity().entity_curve().transformed(*m); - normal_flip = !s.orientation(); - b::Surface::Revolution { - profile: Box::new(save_curve(&profile, d + 1, fitting_budget)?), - origin: point(m.transform_point(s.entity().origin())), - axis: vector(axis), - angle: [0., std::f64::consts::TAU], + let m = *s.transform(); + b::Surface::PlacedRevolution { + profile: Box::new(save_curve(s.entity().entity_curve(), d + 1)?), + origin: point(s.entity().origin()), + axis: vector(s.entity().axis()), + matrix: [m.x, m.y, m.z, m.w].map(vector4), + forward: s.orientation(), } } - }; - Ok((saved, normal_flip)) + }) } fn load_curve(c: b::Curve) -> Result { Ok(match c { @@ -269,6 +286,17 @@ fn load_curve(c: b::Curve) -> Result { b::Curve::Intersection { knots, points, .. } => { mt::Curve::BSplineCurve(mt::BSplineCurve::try_new(knots.into(), points.into_iter().map(p).collect()).map_err(invalid)?) } + b::Curve::SurfaceIntersection { surfaces: [s0, s1], leader, tolerance } => { + let leader = match *leader { + b::Curve::Polyline { points } => mt::Leader::Polyline(mt::PolylineCurve(points.into_iter().map(p).collect())), + b::Curve::Spline { knots, points } => { + mt::Leader::BSpline(mt::BSplineCurve::try_new(knots.into(), points.into_iter().map(p).collect()).map_err(invalid)?) + } + _ => return Err(invalid("intersection leader")), + }; + let (s0, s1) = (load_surface(*s0)?, load_surface(*s1)?); + mt::Curve::IntersectionCurve(mt::IntersectionCurve::new_unchecked(Box::new(s0), Box::new(s1), leader, tolerance)) + } }) } fn load_surface(s: b::Surface) -> Result { @@ -286,6 +314,15 @@ fn load_surface(s: b::Surface) -> Result { full_turn(&angle)?; revolved(load_curve(*profile)?, p(origin), v(axis), false) } + b::Surface::PlaneThrough { origin, u_point, v_point } => mt::Surface::Plane(mt::Plane::new(p(origin), p(u_point), p(v_point))), + b::Surface::PlacedRevolution { profile, origin, axis, matrix: [x, y, z, w], forward } => { + let placed = PlacedRevolution { + entity: Revolved { curve: load_curve(*profile)?, revolution: Axis { origin: p(origin), axis: v(axis) } }, + transform: mt::Matrix4::from_cols(v4(x), v4(y), v4(z), v4(w)), + orientation: forward, + }; + mt::Surface::RevolutedCurve(serde_json::from_value(serde_json::to_value(placed).map_err(invalid)?).map_err(invalid)?) + } analytic => load_analytic(analytic)?, }) } @@ -293,6 +330,7 @@ fn load_surface(s: b::Surface) -> Result { #[cfg(test)] mod tests { use super::*; + use mt::{BoundedCurve, InnerSpace, ParametricCurve, Transformed}; #[test] fn refuses_domain_or_axis_changes_instead_of_approximating() { @@ -342,28 +380,42 @@ mod tests { } #[test] - fn intersection_fit_is_spatial_bounded_and_independent_of_surface_solvers() { - use mt::MetricSpace; + fn intersections_and_revolutions_reload_exactly() { use solidcraft_geom::Vec3; let cyl = crate::cylinder(Vec3::ZERO, Vec3::Z, 5., 40.).unwrap(); let block = crate::box_solid(Vec3::new(-20., -20., 20.), Vec3::new(20., 20., 60.)).unwrap(); let block = crate::transform(&block, Vec3::ZERO, Vec3::new(0., 0., 20.), Vec3::X, 0.4).unwrap(); let cut = crate::boolean(&cyl, &block, crate::BoolOp::Cut).unwrap().unwrap(); let curve = cut.solid.edge_iter().map(|e| e.curve()).find(|c| matches!(c, mt::Curve::IntersectionCurve(_))).unwrap(); - assert!(save_curve(&curve, 0, &mut 0).is_err()); - let record = save_curve(&curve, 0, &mut 4096).unwrap(); - let encoded = serde_json::to_string(&record).unwrap(); - assert!(!encoded.contains("leader") && !encoded.contains("surfaces")); - let b::Curve::Intersection { fitting_tolerance, .. } = &record else { panic!("explicit fitted record required") }; - let tolerance = *fitting_tolerance; - let restored = load_curve(record).unwrap(); + let record = save_curve(&curve, 0).unwrap(); + assert!(matches!(record, b::Curve::SurfaceIntersection { .. }), "the procedural curve itself, not a fit"); + let restored = load_curve(record.clone()).unwrap(); let (a, b) = curve.range_tuple(); - for i in 0..=512 { - let t = a + (b - a) * i as f64 / 512.; - assert!(curve.subs(t).distance(restored.subs(t)) <= tolerance * 1.1, "sample {i}: error {}", curve.subs(t).distance(restored.subs(t))); + for i in 0..=64 { + let t = a + (b - a) * i as f64 / 64.; + assert_eq!(curve.subs(t), restored.subs(t), "sample {i}"); + } + assert_eq!(save_curve(&restored, 0).unwrap(), record); + // The whole body: the same records again, and the same volume to the last bit. + let bytes = crate::encode_native_body(&cut).unwrap(); + let decoded = crate::decode_native_body(&bytes).unwrap(); + assert_eq!(crate::encode_native_body(&decoded).unwrap(), bytes); + assert_eq!(crate::measure(&decoded).unwrap().volume, crate::measure(&cut).unwrap().volume); + // A revolution keeps its own placement, reversed normal included. + let line = mt::Curve::Line(mt::Line(mt::Point3::new(2., 0., 0.), mt::Point3::new(2.5, 0., 3.))); + let mt::Surface::RevolutedCurve(mut placed) = revolved(line, mt::Point3::new(0., 1., 0.), mt::Vector3::new(0., 0., 1.), true) else { + panic!("a revolution") + }; + placed.transform_by(mt::Matrix4::from_translation(mt::Vector3::new(1., 2., 3.)) * mt::Matrix4::from_angle_x(mt::Rad(0.3))); + let placed = mt::Surface::RevolutedCurve(placed); + let record = save_surface(&placed, 0).unwrap(); + assert!(matches!(record, b::Surface::PlacedRevolution { forward: false, .. })); + let restored = load_surface(record.clone()).unwrap(); + assert_eq!(save_surface(&restored, 0).unwrap(), record); + use mt::{ParametricSurface, ParametricSurface3D}; + for (u, v) in [(0., 0.), (1.3, 0.4), (4., 1.)] { + assert_eq!(placed.subs(u, v), restored.subs(u, v)); + assert_eq!(placed.normal(u, v), restored.normal(u, v)); } - let decoded = crate::decode_native_body(&crate::encode_native_body(&cut).unwrap()).unwrap(); - let original = crate::measure(&cut).unwrap().volume; - assert!((crate::measure(&decoded).unwrap().volume - original).abs() < original * 1e-5); } } diff --git a/crates/kernel/src/native/fit.rs b/crates/kernel/src/native/fit.rs deleted file mode 100644 index f51c08b6e..000000000 --- a/crates/kernel/src/native/fit.rs +++ /dev/null @@ -1,85 +0,0 @@ -//! Bounded export of procedural intersections as ordinary spatial cubic splines. -//! The stored tolerance is the fitting target; the result is always provisional. -use super::*; - -fn point_at(c: &mt::Curve, t: f64, budget: &mut usize) -> Result { - *budget = budget.checked_sub(1).ok_or_else(|| invalid("intersection fitting budget"))?; - let p = c.subs(t); - if !p.x.is_finite() || !p.y.is_finite() || !p.z.is_finite() { - return Err(invalid("intersection sample")); - } - Ok(p) -} -pub(super) fn fit_intersection(c: &mt::Curve, budget: &mut usize) -> Result { - let tolerance = 1e-4; - let (start, end) = c.range_tuple(); - if !start.is_finite() || !end.is_finite() || start >= end { - return Err(invalid("intersection range")); - } - // Fit each smooth parameter interval using spatial samples, without backend derivative conventions. - // Only the resulting spatial spline crosses the persisted format boundary. - let mt::Curve::IntersectionCurve(intersection) = c else { - return Err(invalid("expected intersection")); - }; - let mut breaks = vec![start, end]; - match intersection.leader() { - mt::Leader::Polyline(points) => { - if points.len() > 4096 { - return Err(invalid("intersection parameter budget")); - } - breaks.extend((0..points.len()).map(|i| i as f64).filter(|t| *t > start && *t < end)); - } - mt::Leader::BSpline(curve) => { - if curve.knot_vec().len() > 4096 { - return Err(invalid("intersection parameter budget")); - } - breaks.extend(curve.knot_vec().iter().copied().filter(|t| *t > start && *t < end)); - } - } - breaks.sort_by(f64::total_cmp); - breaks.dedup(); - let mut stack = Vec::new(); - for pair in breaks.windows(2).rev() { - let (a, b) = (pair[0], pair[1]); - stack.push((a, b, point_at(c, a, budget)?, point_at(c, b, budget)?, 0u8)); - } - let mut pieces = Vec::new(); - while let Some((a, b, pa, pb, depth)) = stack.pop() { - let p1 = point_at(c, a + (b - a) / 3., budget)?.to_vec(); - let p2 = point_at(c, a + (b - a) * 2. / 3., budget)?.to_vec(); - let x = p1 * 27. - pa.to_vec() * 8. - pb.to_vec(); - let y = p2 * 27. - pa.to_vec() - pb.to_vec() * 8.; - let controls = [pa, mt::Point3::from_vec((x * 2. - y) / 18.), mt::Point3::from_vec((y * 2. - x) / 18.), pb]; - let mut fits = true; - for fraction in [0.125, 0.25, 0.5, 0.75, 0.875] { - let actual = point_at(c, a + (b - a) * fraction, budget)?; - let u = 1. - fraction; - let fitted = controls[0].to_vec() * u * u * u - + controls[1].to_vec() * 3. * u * u * fraction - + controls[2].to_vec() * 3. * u * fraction * fraction - + controls[3].to_vec() * fraction * fraction * fraction; - if (actual.to_vec() - fitted).magnitude() > tolerance * 0.1 { - fits = false; - } - } - if fits { - pieces.push((a, b, controls)); - } else { - if depth >= 12 || pieces.len() + stack.len() >= 1023 { - return Err(invalid("intersection fit did not converge")); - } - let middle = a + (b - a) / 2.; - let pm = point_at(c, middle, budget)?; - stack.push((middle, b, pm, pb, depth + 1)); - stack.push((a, middle, pa, pm, depth + 1)); - } - } - let first = pieces.first().ok_or_else(|| invalid("empty intersection fit"))?; - let mut points = vec![point(first.2[0])]; - let mut knots = vec![start; 4]; - for (i, (_, b, controls)) in pieces.iter().enumerate() { - points.extend(controls.iter().skip(1).copied().map(point)); - knots.extend(std::iter::repeat_n(*b, if i + 1 == pieces.len() { 4 } else { 3 })); - } - Ok(b::Curve::Intersection { knots, points, fitting_tolerance: tolerance, faces: None }) -} diff --git a/crates/kernel/src/native/fixtures/box-fillet-v3.json b/crates/kernel/src/native/fixtures/box-fillet-v4.json similarity index 95% rename from crates/kernel/src/native/fixtures/box-fillet-v3.json rename to crates/kernel/src/native/fixtures/box-fillet-v4.json index fa1d6aedf..cb6f314ed 100644 --- a/crates/kernel/src/native/fixtures/box-fillet-v3.json +++ b/crates/kernel/src/native/fixtures/box-fillet-v4.json @@ -292,6 +292,13 @@ "preserve_boundaries": false, "version": 1 }, + "runtime": { + "coarse_missing": [ + 0.5099019513592785, + 0 + ], + "size": 50.99019513592785 + }, "solid": { "shells": [ { @@ -549,20 +556,20 @@ ] ], "surface": { - "kind": "plane", + "kind": "plane_through", "origin": [ 40.0, 30.0, 0.0 ], - "u_axis": [ - -40.0, + "u_point": [ 0.0, + 30.0, 0.0 ], - "v_axis": [ + "v_point": [ + 40.0, 0.0, - -30.0, 0.0 ] } @@ -590,18 +597,18 @@ ] ], "surface": { - "kind": "plane", + "kind": "plane_through", "origin": [ 0.0, 0.0, 0.0 ], - "u_axis": [ + "u_point": [ 40.0, 0.0, 0.0 ], - "v_axis": [ + "v_point": [ 0.0, 0.0, 10.0 @@ -631,19 +638,19 @@ ] ], "surface": { - "kind": "plane", + "kind": "plane_through", "origin": [ 40.0, 0.0, 0.0 ], - "u_axis": [ - 0.0, + "u_point": [ + 40.0, 30.0, 0.0 ], - "v_axis": [ - 0.0, + "v_point": [ + 40.0, 0.0, 10.0 ] @@ -672,20 +679,20 @@ ] ], "surface": { - "kind": "plane", + "kind": "plane_through", "origin": [ 40.0, 30.0, 0.0 ], - "u_axis": [ - -40.0, + "u_point": [ 0.0, + 30.0, 0.0 ], - "v_axis": [ - 0.0, - 0.0, + "v_point": [ + 40.0, + 30.0, 10.0 ] } @@ -713,20 +720,20 @@ ] ], "surface": { - "kind": "plane", + "kind": "plane_through", "origin": [ 0.0, 30.0, 0.0 ], - "u_axis": [ + "u_point": [ + 0.0, 0.0, - -30.0, 0.0 ], - "v_axis": [ - 0.0, + "v_point": [ 0.0, + 30.0, 10.0 ] } @@ -754,21 +761,21 @@ ] ], "surface": { - "kind": "plane", + "kind": "plane_through", "origin": [ 40.0, 30.0, 10.0 ], - "u_axis": [ - -40.0, + "u_point": [ 0.0, - 0.0 + 30.0, + 10.0 ], - "v_axis": [ + "v_point": [ + 40.0, 0.0, - -30.0, - 0.0 + 10.0 ] } } @@ -817,7 +824,7 @@ ] } ], - "version": 2 + "version": 3 } }, { @@ -1157,6 +1164,13 @@ "preserve_boundaries": false, "version": 1 }, + "runtime": { + "coarse_missing": [ + 0.5099019513592785, + 0 + ], + "size": 50.99019513592785 + }, "solid": { "shells": [ { @@ -1549,20 +1563,20 @@ ] ], "surface": { - "kind": "plane", + "kind": "plane_through", "origin": [ 40.0, 30.0, 0.0 ], - "u_axis": [ - -40.0, + "u_point": [ 0.0, + 30.0, 0.0 ], - "v_axis": [ + "v_point": [ + 40.0, 0.0, - -30.0, 0.0 ] } @@ -1590,18 +1604,18 @@ ] ], "surface": { - "kind": "plane", + "kind": "plane_through", "origin": [ 0.0, 0.0, 0.0 ], - "u_axis": [ + "u_point": [ 40.0, 0.0, 0.0 ], - "v_axis": [ + "v_point": [ 0.0, 0.0, 10.0 @@ -1635,19 +1649,19 @@ ] ], "surface": { - "kind": "plane", + "kind": "plane_through", "origin": [ 40.0, 0.0, 0.0 ], - "u_axis": [ - 0.0, + "u_point": [ + 40.0, 30.0, 0.0 ], - "v_axis": [ - 0.0, + "v_point": [ + 40.0, 0.0, 10.0 ] @@ -1676,20 +1690,20 @@ ] ], "surface": { - "kind": "plane", + "kind": "plane_through", "origin": [ 40.0, 30.0, 0.0 ], - "u_axis": [ - -40.0, + "u_point": [ 0.0, + 30.0, 0.0 ], - "v_axis": [ - 0.0, - 0.0, + "v_point": [ + 40.0, + 30.0, 10.0 ] } @@ -1721,20 +1735,20 @@ ] ], "surface": { - "kind": "plane", + "kind": "plane_through", "origin": [ 0.0, 30.0, 0.0 ], - "u_axis": [ + "u_point": [ + 0.0, 0.0, - -30.0, 0.0 ], - "v_axis": [ - 0.0, + "v_point": [ 0.0, + 30.0, 10.0 ] } @@ -1762,21 +1776,21 @@ ] ], "surface": { - "kind": "plane", + "kind": "plane_through", "origin": [ 40.0, 30.0, 10.0 ], - "u_axis": [ - -40.0, + "u_point": [ 0.0, - 0.0 + 30.0, + 10.0 ], - "v_axis": [ + "v_point": [ + 40.0, 0.0, - -30.0, - 0.0 + 10.0 ] } }, @@ -1956,7 +1970,7 @@ ] } ], - "version": 2 + "version": 3 } } ] diff --git a/docs/design-container.md b/docs/design-container.md index d84f43db6..29cddc747 100644 --- a/docs/design-container.md +++ b/docs/design-container.md @@ -87,8 +87,8 @@ design remains intact until the complete rebuilt session is ready. Cancellation any change of active document/revision discards both preview and completion. Normal design reading, CLI and browser opening still rebuild authoritatively. -Native B-rep caches can supply provisional display as described below; they never -supply evaluated session state. The saved picture is not an interactive viewport. +The model cache can supply provisional display as described below. The saved +picture is not an interactive viewport. ## Seekable reader (phase 2, first increment) @@ -110,45 +110,52 @@ stored blob; deferral means not loading or decoding the complete payload, not ze physical reads of its byte range. Optional cache metadata is capped at 16 MiB; larger metadata misses the cache and uses the normal authoritative part-size budget. -## Native evaluated cache +## Model cache -Engine Save/Save As can include `cache/key.json` and `cache/brep.bin` when -explicitly requested with `cache: true` and geometry is warm. The default is -`cache: false`, including browser downloads, to avoid extra save time and file size. -JSON and recovery/autosave -remain independent of the native cache. Saving never forces cold placement, -evaluation or tessellation. Active sketches, uncaptured moves, errors, mesh bodies, -unsupported adapter representations and exceeded budgets omit the cache. +Engine Save/Save As write the evaluated model with the design by default +(`cache: true`; `cache: false` leaves it out): `cache/model.json` and +`cache/bodies.bin`. Plain JSON, recovery/autosave and browser downloads do not +carry it. Saving never forces placement, evaluation or tessellation: the model is +the session's own evaluation, and only when it is the evaluation of the document +being saved (`Model::is_current`). An active sketch, uncaptured moves, feature +errors, mesh bodies or exceeded budgets leave the cache out; the design saves as +before. -The manifest records `solidcraft-brep-cache/1`, the package version, the explicit -producer revision `solidcraft-truck-adapter/2`, exact document/payload SHA-256 hashes -and contiguous named body slices. The producer revision is deliberately maintained -when adapter semantics change; it is not a source-tree fingerprint or build script. -The binary data uses [SolidCraft's portable B-rep schema and codec](native-brep.md), -including topology, curves/surfaces, face-source certificates, appearances and -operation history. Truck's serialized structures are never stored. A different -kernel can implement the same schema; until its adapter is tested it conservatively -misses this producer's cache and rebuilds the authoritative document. +Both entries are Deflate-compressed (level one) under either compression policy: the +encoded bodies shrink about fourfold (an imported assembly) to tenfold (modelled parts), +for a few tens of milliseconds. -Native caches cap 4,096 bodies, 100,000 total faces, a 1 MiB manifest and 64 MiB -binary payload. Individual bodies have the schema/codec's additional limits. -The reader validates metadata, manifest, slices and bodies before requesting a -bounded provisional mesh. Original STEP/image/mesh blobs are resolved afterwards. -No redundant display mesh is stored by default: `preview: true` remains a separate -opt-in for already warm display meshes, which take precedence when present. +`cache/bodies.bin` holds every distinct body once, in +[SolidCraft's native B-rep encoding](native-brep.md), as contiguous slices. The +encoding is exact: a decoded body is the body that was saved, number for number +(procedural intersection curves, placed revolutions and planes are stored as the +kernel holds them, never refitted). Identical bodies share one slice (keyed by the +SHA-256 of their encoding), and a placed copy of a repeated part (an instance from +a STEP assembly) records the part and its matrix, so it shows that part's display +again instead of being meshed on its own. -Every failure in the optional cache is a miss. Even a checksum-valid forged body -never becomes editable state: Open builds a fresh session from the document and -original blobs, then replaces the provisional picture. Picking, measurements, -persistent names and subsequent modelling use that rebuilt session. Existing -cancellation/document-revision guards also apply. The web build retains synchronous -authoritative rebuilding; portability does not imply background web evaluation. +`cache/model.json` records `solidcraft-model-cache/1`, the producer revision +`solidcraft-truck-adapter/3`, the application version, the build (source commit, +CPU architecture and OS), the SHA-256 of the exact `document.json` (whose blob +references pin every STEP, mesh and image payload) and of `cache/bodies.bin`, the +slices, and the bodies' records: name, feature, component, placement source, +imported look and display share. A cache is read back only when every one of these +matches: the same source compiled for the same platform computes the same numbers, +so another build's cache is a miss. A build of unknown source (a tarball without +git) never reads a cache. -A counting-reader regression uses a 2.6 MB stored source blob and obtains the saved -preview with fewer than 256 KiB read, then verifies the authoritative document is -identical after resolving its source. Corrupt-source and preview-miss regressions, -and truncation/seeded mutations through the combined reader, protect the boundary. -This is an IO-volume test, not a geometry or first-frame benchmark. +The fixed budgets of earlier caches (4,096 bodies, 100,000 faces, 64 MiB) scale +with the design now: up to 200,000 body records, 100,000 distinct bodies, a 32 MiB +manifest and a payload within the container's part budget (256 MiB), leaving room +for the document. Individual bodies keep the codec's own limits. The archive-wide +budgets (256 MiB per part, 512 MiB expanded, 10,000 entries) are unchanged, and the +cache is left out when it would push the container near them. Decoding runs under +`kernel::guard` and is linear in the payload's bytes. + +Opening still rebuilds the design from its timeline; the cache supplies the +provisional picture (a bounded mesh of the placed bodies) before that finishes. +Any failure in it is a miss, never a failed open. Earlier `cache/key.json` and +`cache/brep.bin` entries are ignored. ## Review increments and kernel independence @@ -188,7 +195,7 @@ run standalone wasm validation on each published code revision. ## Portable thumbnail -A warm save with `cache: true` may add `cache/thumbnail.png` and its small +A warm save (with `cache`, the default) may add `cache/thumbnail.png` and its small `cache/thumbnail.json` key. The picture is a 240 x 150 PNG, bounded to 256 KiB, keyed by `solidcraft-thumbnail/1`, application version, exact document SHA-256 and PNG SHA-256. It contains an isometric view of visible solid bodies with their @@ -200,9 +207,8 @@ work at four million supersampled pixels and face-color lookups at one million, so overlapping triangles cannot make a small picture arbitrarily expensive. It never evaluates or tessellates a cold model for a picture. Active edits, pending moves, model errors, absent warm -geometry or exceeded limits omit the picture. Ordinary saves and browser downloads -default to `cache: false` and omit the PNG; `cache: true` explicitly opts in. Plain JSON -never contains the PNG. The same writer is used by desktop and browser saves. +geometry or exceeded limits omit the picture, as does `cache: false`. Browser +downloads omit the PNG. Plain JSON never contains the PNG. The same writer is used by desktop and browser saves. The seekable thumbnail reader checks the small key, retained document metadata, PNG size/header and hashes without resolving source blobs. The Home/Recent Files diff --git a/docs/native-brep.md b/docs/native-brep.md index 2142583a0..e60ea5aef 100644 --- a/docs/native-brep.md +++ b/docs/native-brep.md @@ -1,11 +1,11 @@ -# Portable native B-rep, schema 2 +# Native B-rep, schema 3 -This is SolidCraft's geometry interchange data model in `solidcraft_geom::brep`. -It has no modelling-backend dependency. It is the basis for #303's disposable -native cache; it is not an editable-session snapshot or a STEP replacement for -external interchange. The container reader, binary codec and kernel adapters are -separate layers. Warm application saves can emit it as the optional native cache -described in [the container format](design-container.md#native-evaluated-cache). +This is SolidCraft's geometry data model in `solidcraft_geom::brep`. It has no +modelling-backend dependency. It is the body encoding of a design's model cache +([the container format](design-container.md#model-cache)); it is not a STEP +replacement for external interchange. The container reader, binary codec and +kernel adapters are separate layers. The truck adapter writes it exactly: a body +decoded by the producer that encoded it is that body, number for number. ## Geometry and topology @@ -38,7 +38,12 @@ Curves are tagged mathematical records: - `intersection`: an explicit ordinary 3D polynomial spline (knots and Cartesian control points), positive fitting tolerance in millimetres, and optional two shell-local face references as hints. No supporting surfaces, leader, backend - solver or parameter-search convention is required to evaluate it. + solver or parameter-search convention is required to evaluate it. (Read only; + schema 3 writers store the intersection itself, below.) +- `surface_intersection`: the intersection of two surface records, traced from a + `leader` (a polyline or spline near it, its knots as the producer holds them) to + within `tolerance` mm. The curve is the procedural one, not a fit: a different + kernel must trace it again. Surfaces include planes (origin and independent parameter axes), polynomial and rational tensor-product splines, and explicit analytic records. Analytic frames @@ -51,7 +56,14 @@ store origin and orthonormal x/y axes; z is x cross y. Angular ranges are radian - torus: major/minor radii, longitude and meridian ranges; - revolution: profile, origin, unit axis and angular range. Rotate the profile around that axis using the right-hand rule. There is no persisted affine matrix - or backend orientation/parameter-swap flag. + or backend orientation/parameter-swap flag. (Read only in schema 3.) +- placed revolution: a full revolution of a profile about an origin and unit axis, + then mapped by a column-major affine `matrix` (non-singular), with the normal + reversed unless `forward`. Nothing is baked into the profile. + +A `plane_through` record is a plane given by three points: parameter (0, 0) at +`origin`, (1, 0) at `u_point` and (0, 1) at `v_point`. Writers use it rather than +the axis form, whose axes would be rounded differences of the points. Cylinder/cone positions are origin + h*z + r(h)*(cos(u)*x + sin(u)*y). Sphere positions are origin + r*(cos(v)*(cos(u)*x + sin(u)*y) + sin(v)*z). @@ -62,7 +74,7 @@ when its runtime uses a different parameterization. ## Validation and trust -Schema 2 caps 1,024 shells, 100,000 combined topology/geometry items, geometry +Schema 3 caps 1,024 shells, 1,000,000 combined topology/geometry items, geometry nesting at 16, spline degree at 16 and control points per spline dimension at 4,096. Numbers must be finite and bounded in magnitude by 1e12. Knot order, active spline domain, multiplicities, rectangular grids, positive rational weights, @@ -84,14 +96,17 @@ floating-point comparisons. A decoded cache remains provisional until authoritat re-evaluation finishes. The document and original blobs remain sufficient to reopen when a cache, representation, producer or adapter is unsupported. -## Body binary envelope, version 3 +## Body binary envelope, version 4 -`SCBREP03` is the eight-byte envelope signature. Geometry schema 2 is nested in -`solid`; metadata schema 1 is nested in `metadata`. These are separate version -numbers because each contract can evolve independently. Signatures 01 and 02 -were development prototypes; 02 introduced the explicit geometry schema while -03 also separates metadata from runtime Rust types. Unsupported versions are -cache misses, not design-file migration failures. +`SCBREP04` is the eight-byte envelope signature. Geometry schema 3 is nested in +`solid`; metadata schema 1 is nested in `metadata`; `runtime` holds what the body +measured about itself that later operations read (its size, from which kernel +tolerances follow, and the orientation mesh's missing-face count), so a decoded +body works to the same tolerances. These are separate version numbers because +each contract can evolve independently. Signatures 01 and 02 were development +prototypes; 02 introduced the explicit geometry schema while 03 also separated +metadata from runtime Rust types and 04 made the encoding exact. Unsupported +versions are cache misses, not design-file migration failures. The envelope uses its own explicitly versioned records for color, paint, authored boundaries, face-source certificates, operation history and boundary protection. @@ -99,41 +114,36 @@ Plane, region and segment records are also owned by the wire schema. Exhaustive manual adapter conversions separate these from runtime FaceSource, History, FaceProv, EdgeProv, Paint, Seg2, Region2 and Plane types. Their serde derives or internal refactors cannot silently redefine the saved fields. No truck serde -record, pointer, tessellation or STEP string is written. Changing field semantics +struct, pointer, tessellation or STEP string is written. Changing field semantics requires a format version change, even if a Rust type keeps its name. Values use tags: null=0, false=1, true=2, signed integer=3, unsigned integer=4, binary64=5, UTF-8 string=6, array=7, object=8. Numbers use eight little-endian bytes. Strings and collections use unsigned 32-bit little-endian lengths; object keys are length-prefixed UTF-8, emitted lexicographically. Readers reject duplicate -keys, unknown tags, non-finite numbers and trailing bytes. Limits are 64 MiB, -2,000,000 values, depth 48, 100,000 entries per collection and 1 MiB per string. +keys, unknown tags, non-finite numbers and trailing bytes. Limits per body are +256 MiB, 20,000,000 values, depth 48, 1,000,000 entries per collection and 1 MiB per +string; a design's cache bounds the total (see the container format). -The truck adapter converts these records into runtime topology only after -validation. It refuses single-vertex closed edges, standalone polylines, -unclamped spline domains, non-full angular carrier surfaces and conversions that -would change plane axes. Circle/ellipse arcs use exact rational quadratic loci; -the adapter may reparameterize them. Similarity transforms on revolutions are -baked into their profile, origin and axis (including reflections). Non-similarity -transforms are refused until an exact independent spline conversion exists. -Normal flips and backend boundary orientation are converted separately. +The truck adapter writes every curve and surface as truck holds it: lines, +B-spline and NURBS coefficients, the three points of a plane, a revolution's +profile, axis, matrix and orientation, and an intersection's two surfaces, leader +and tolerance. Decoding builds the same structures without the constructors that +would round them (normalizing an axis, composing a matrix with the identity), and +rebuilds each shell's topology as recorded, including closed edges on one vertex +and seam edges a wire uses twice. On reading it refuses standalone polylines, +unclamped spline domains and non-full angular carrier surfaces in the portable +records it does not write. Circle/ellipse arcs use exact rational quadratic loci; +the adapter may reparameterize them. Normal flips and backend boundary orientation +are converted separately. -Procedural intersections are exported with a bounded spatial cubic fit: 1e-4 mm -fitting target, 4,096 evaluations shared across the body, at most 1,023 pieces and -12 subdivisions per source interval. The target is checked at sampled positions; -it is not a certified maximum error between samples. Failure to fit within these -limits refuses the cache. A decoded fitted curve is an ordinary spatial spline; -re-export may therefore use the `spline` record rather than retain its optional -intersection annotation. This approximation is suitable only for the provisional -cache, never authoritative modelling state. +Hashes prove which document and payload a cache belongs to, not who wrote it: the +container's key ties a cache to the producer, application build and platform that +computed it, and the decoder applies the structural and resource checks above to +every body. A second backend needs its own tested adapter before cross-kernel +interoperability can be claimed. -Decoded bodies remain provisional; the application must never use an untrusted -cache as its editable model. Application integration keeps it provisional while -rebuilding the document and original sources. A second -backend needs its own tested adapter before cross-kernel interoperability can be -claimed. - -The box-and-fillet golden JSON fixture pins the decoded version-3 envelope, +The box-and-fillet golden JSON fixture pins the decoded version-4 envelope, field names, tags, topology, geometry and metadata. Integer and structural values are exact; floating coefficients allow 1e-10 relative/absolute platform rounding. The signature is asserted separately. This protects the wire contract against From ca9c363a9808a78e349020e839aeca5e98442885 Mon Sep 17 00:00:00 2001 From: HiroKenEz <59478073+HiroKenEz@users.noreply.github.com> Date: Tue, 20 Oct 2026 02:32:23 +0000 Subject: [PATCH 162/225] Sketch: a click that moves on the way places its point (#2448) (#2449) * claim: #2448 * Sketch: a click that moves on the way places its point (#2448) egui reports a press that moves past its click distance, or is held past its click time, as a drag, not a click. The viewport only placed points on clicks, so a hand that moved while clicking placed nothing with the Slot, Line, arc, three-point, Ellipse, Spline and the other tools, and on the first point of a Rectangle, Circle or Polygon the few pixels became the press-drag-release gesture of #1630 and drew a sliver. - Any tool's press that turns into a drag (no navigation, no Select Other hold) clicks where the button is let go. - A Rectangle, Circle or Polygon drag let go within 24 screen points of its press is such a click too: the first point goes where it was let go and the shape goes on by clicks. A longer drag still draws the shape (#1630). Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: bherbruck --- crates/ui-egui/src/lib.rs | 2 + .../ui-egui/src/sketch_moving_click_tests.rs | 90 +++++++++++++++++++ crates/ui-egui/src/viewport.rs | 44 +++++++-- 3 files changed, 130 insertions(+), 6 deletions(-) create mode 100644 crates/ui-egui/src/sketch_moving_click_tests.rs diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 3d344ca6b..799369a19 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -168,6 +168,8 @@ mod sketch_guidance_ui_tests; pub mod sketch_modify_ui; #[cfg(test)] mod sketch_modify_ui_tests; +#[cfg(test)] +mod sketch_moving_click_tests; pub mod sketch_palette; mod sketch_pattern_tree; #[cfg(test)] diff --git a/crates/ui-egui/src/sketch_moving_click_tests.rs b/crates/ui-egui/src/sketch_moving_click_tests.rs new file mode 100644 index 000000000..effeafe5f --- /dev/null +++ b/crates/ui-egui/src/sketch_moving_click_tests.rs @@ -0,0 +1,90 @@ +//! A sketch tool's click that moves on the way (#2448): egui takes a press that moves past its +//! click distance as a drag, which the tools dropped, so a hand that moved while clicking placed +//! nothing. + +use crate::scenario::Harness; +use serde_json::json; +use solidcraft_engine::sketch::CurveKind; + +fn harness(command: &str) -> Harness { + let mut h = Harness::new(); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + h.app.cam.distance = 120.0; + h.settle(); + h.step(&json!({"start":command})).unwrap(); + h +} + +/// Press `dx` screen points left of sketch point `at`, move there and let go. +fn moving_click(h: &mut Harness, at: [f64; 2], dx: f64) { + let p = h.call("ui.at", json!({"sketch":at}))["result"].clone(); + let (x, y) = (p[0].as_f64().unwrap(), p[1].as_f64().unwrap()); + h.call("ui.drag", json!({"x0":x - dx,"y0":y,"x1":x,"y1":y,"steps":4})); +} + +fn curves(h: &Harness) -> usize { + let sid = h.app.session.active_sketch.unwrap(); + h.app.session.model.state().sketch(sid).unwrap().sketch.curves.len() +} + +#[test] +fn clicks_that_move_place_their_points() { + for (command, points, finish) in [ + ("sketch.slot.center_to_center", vec![[-20.0, 0.0], [20.0, 0.0], [0.0, 8.0]], None), + ("sketch.line", vec![[-20.0, 0.0], [20.0, 5.0]], Some("Escape")), + ("sketch.arc.three_point", vec![[-20.0, 0.0], [20.0, 0.0], [0.0, 10.0]], None), + ("sketch.rectangle.three_point", vec![[-20.0, 0.0], [20.0, 0.0], [20.0, 10.0]], None), + ("sketch.circle.three_point", vec![[-20.0, 0.0], [20.0, 0.0], [0.0, 20.0]], None), + ("sketch.ellipse", vec![[0.0, 0.0], [25.0, 0.0], [0.0, 10.0]], None), + ("sketch.spline.fit_point", vec![[-20.0, 0.0], [0.0, 10.0], [20.0, 0.0]], Some("right")), + ] { + let mut h = harness(command); + for at in &points { + moving_click(&mut h, *at, 12.0); + } + match finish { + Some("right") => { + let p = h.call("ui.at", json!({"sketch":points[points.len() - 1]}))["result"].clone(); + h.call("ui.click", json!({"x":p[0],"y":p[1],"button":"right"})); + } + Some(key) => h.step(&json!({"key":key})).unwrap(), + None => {} + } + h.settle(); + assert!(curves(&h) > 0, "{command}: nothing drawn; {:?} {:?}", h.app.tool, h.app.status); + // The points went where the button was let go: the first one is at its spot. + let sid = h.app.session.active_sketch.unwrap(); + let sk = h.app.session.model.state().sketch(sid).unwrap().sketch.clone(); + let first = solidcraft_engine::geom::Vec2::new(points[0][0], points[0][1]); + // (A three-point circle keeps only its centre: through all three, its radius is 20.) + let through = sk.curves.iter().any(|c| matches!(c.kind, CurveKind::Circle { r, .. } if (r - 20.0).abs() < 0.5)); + assert!(sk.points.iter().any(|p| (p.pos - first).len() < 0.5) || through, "{command}: no point at {first:?}"); + } +} + +#[test] +fn a_short_drag_starts_a_rectangle_circle_or_polygon_by_clicks() { + for (command, second, count) in [ + ("sketch.rectangle.two_point", [20.0, 10.0], 4), + ("sketch.rectangle.center", [20.0, 10.0], 6), + ("sketch.circle.center", [15.0, 0.0], 1), + ("sketch.polygon.inscribed", [15.0, 0.0], 7), + ] { + let mut h = harness(command); + // A press that moves 12 points (past egui's click distance, short of a drawn shape) is + // the first point, not a sliver of a shape. + moving_click(&mut h, [0.0, 0.0], 12.0); + h.settle(); + assert_eq!(curves(&h), 0, "{command}: a short drag drew a shape"); + assert_eq!(h.app.tool.as_ref().unwrap().pts.len(), 1, "{command}"); + moving_click(&mut h, second, 12.0); + h.settle(); + assert_eq!(curves(&h), count, "{command}: {:?}", h.app.status); + let sid = h.app.session.active_sketch.unwrap(); + let sk = h.app.session.model.state().sketch(sid).unwrap().sketch.clone(); + let far = solidcraft_engine::geom::Vec2::new(second[0], second[1]); + let circle = |c: &solidcraft_engine::sketch::Curve| matches!(c.kind, CurveKind::Circle { r, .. } if (r - far.len()).abs() < 0.5); + let on_shape = sk.points.iter().any(|p| (p.pos - far).len() < 0.5) || sk.curves.iter().any(circle); + assert!(on_shape, "{command}: the second click wasn't where it was let go"); + } +} diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 0267a2d42..8e8a177a9 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -40,9 +40,14 @@ pub enum NavMode { #[derive(Default)] pub struct ViewportState { - /// A two-point drawing tool's first point was placed by a press that became a drag: the - /// release places the second (#1630). - pub(crate) draw_drag: bool, + /// A two-point drawing tool's first point was placed by a press (here) that became a drag: + /// the release places the second (#1630), unless it lands within [`DRAW_DRAG_MIN`] of the + /// press. Such a drag was a click that moved on the way (#2448): the release places the + /// first point instead and the shape goes on by clicks, rather than a sliver of a shape. + pub(crate) draw_drag: Option, + /// A tool's click moved on the way (#2448): egui takes a press that moves past its + /// click distance, or is held past its click time, as a drag, so its release is the click. + pub(crate) tool_click: bool, /// Per-body boxes of one world state, held (not just its address, which a later state can /// reuse once the old one is freed, so stale boxes would come back). pick_bounds: std::sync::Mutex>, @@ -398,6 +403,10 @@ fn supersampling(app: &mut SolveApp, ctx: &egui::Context, view_proj: [[f32; 4]; /// How long the view holds still before adaptive supersampling draws it at full quality (s). const SS_SETTLE: f64 = 0.25; +/// How far (screen points) a press must be dragged for its release to draw a rectangle, circle +/// or polygon (#1630); a shorter drag is a click that moved on the way (#2448). +const DRAW_DRAG_MIN: f32 = 24.0; + /// The display plan the model scene draws `b` from on the GPU, or `None` when its faces are built /// here from the reference mesh. Opaque shaded bodies (`opaque`: not faded, and no see-through /// body or face) are drawn from their plans where the device evaluates them; faded and @@ -2472,15 +2481,34 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { crate::frame_rate::paint(app, ui.ctx(), &painter, rect); // ---- interaction ---- + // A tool's click that moved on the way (#2448) clicks where the button is let go. + if app.viewport.tool_click && resp.drag_stopped() { + app.viewport.tool_click = false; + if let Some(p) = ui.input(|i| i.pointer.latest_pos()).filter(|p| rect.contains(*p)) + && app.tool.is_some() + { + crate::tools::on_hover(app, &proj, p); + crate::tools::on_click(app, &proj, p); + } + } // A two-point shape being dragged out (#1630) follows the pointer and ends where it is let go, // even over the shape's own dimension box, which rides along beside the pointer. - if app.viewport.draw_drag { + if let Some(from) = app.viewport.draw_drag { let at = ui.input(|i| i.pointer.latest_pos()).filter(|p| rect.contains(*p)); if resp.drag_stopped() { - app.viewport.draw_drag = false; + app.viewport.draw_drag = None; if let Some(p) = at && app.tool.as_ref().is_some_and(|t| t.pts.len() == 1) { + // Let go close to the press, it was a click that moved on the way (#2448): the + // first point goes where it was let go, as for the other tools, and the shape + // goes on by clicks. + if p.distance(from) < DRAW_DRAG_MIN + && let Some(t) = app.tool.as_mut() + { + t.pts.clear(); + crate::sketch_dims::reset(t); + } crate::tools::on_hover(app, &proj, p); crate::tools::on_click(app, &proj, p); } @@ -2507,7 +2535,11 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { && let Some(a) = ui.input(|i| i.pointer.press_origin()) { crate::tools::on_click(app, &proj, a); - app.viewport.draw_drag = app.tool.as_ref().is_some_and(|t| t.pts.len() == 1); + app.viewport.draw_drag = app.tool.as_ref().is_some_and(|t| t.pts.len() == 1).then_some(a); + } else if app.tool.is_some() && !held && primary_nav.is_none() && mode.is_none() && resp.drag_started_by(egui::PointerButton::Primary) { + // Any other press of a tool that turns into a drag is a click that moved on the way + // (#2448): its release clicks. + app.viewport.tool_click = true; } let reference_pick = (resp.clicked() || resp.double_clicked()) && !held From 46a0b2528054519f6ba7c622f7cf93f1fda6e34c Mon Sep 17 00:00:00 2001 From: Rifqi Al Fatih Date: Tue, 20 Oct 2026 02:32:50 +0000 Subject: [PATCH 163/225] STEP import: CJK names read back whole (#2344) (#2347) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adjacent \X2\...\X0\ runs, as step_out writes one per character, now decode: the backslash opening the next run was pushed as a literal, so a name exported as 圆角 came back as 圆\X2\89D2\X0\ (also every linked component insert, which round-trips through STEP). STEP and IGES bytes that are not UTF-8 are decoded in their detected legacy encoding (chardetng + encoding_rs) instead of from_utf8_lossy, so GBK or Shift_JIS names from vendor files no longer turn into U+FFFD. Co-authored-by: bherbruck --- Cargo.lock | 13 ++++++++ Cargo.toml | 5 +++ crates/io/Cargo.toml | 2 ++ crates/io/src/lib.rs | 52 +++++++++++++++++++++++++++++++- crates/kernel/src/step_in/p21.rs | 27 +++++++++++------ crates/kernel/src/step_out.rs | 5 +++ 6 files changed, 93 insertions(+), 11 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 96705531d..38e204204 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -813,6 +813,17 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "chardetng" +version = "0.1.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14b8f0b65b7b08ae3c8187e8d77174de20cb6777864c6b832d8ad365999cf1ea" +dependencies = [ + "cfg-if", + "encoding_rs", + "memchr", +] + [[package]] name = "chrono" version = "0.4.45" @@ -4198,6 +4209,8 @@ dependencies = [ "cadmpeg-core", "cadmpeg-ir", "cadmpeg-registry", + "chardetng", + "encoding_rs", "gltf", "log", "quick-xml", diff --git a/Cargo.toml b/Cargo.toml index 0f04f71a1..fa02d7829 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -55,6 +55,11 @@ rayon = "1.12" # packages (3MF) zip = { version = "9", default-features = false, features = ["deflate"] } quick-xml = "0.41" +# STEP text in a legacy encoding (GBK, Shift_JIS, …) instead of Part 21 escapes (#2344): detect +# and decode it. Both MIT OR Apache-2.0 (encoding_rs adds BSD-3-Clause data); encoding_rs is +# already in the tree through cadmpeg-codec-step. +chardetng = "0.1" +encoding_rs = "0.8" # glTF 2.0 import (MIT OR Apache-2.0): the document model and GLB container only; buffers are # read by crates/io itself, so no image decoding or file access comes with it. gltf = { version = "1.4", default-features = false, features = ["names"] } diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index aaf73e5d6..fac7296ff 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -20,6 +20,8 @@ gltf = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } sha2 = { workspace = true } +chardetng = { workspace = true } +encoding_rs = { workspace = true } # A plain fsync where a network share refuses Apple's full flush (src/safe_write.rs); already in # the tree through tempfile. diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 060cc9107..25e25e067 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -155,6 +155,35 @@ pub struct StepFeature { pub import: std::sync::Arc, } +/// Bytes the encoding detector sees at most: the lines with 8-bit bytes, which in a STEP or IGES +/// file are the names and descriptions. +const ENCODING_SAMPLE_BYTES: usize = 64 << 10; + +/// STEP or IGES bytes as text. UTF-8 stays as it is. Some exporters write names in the system's +/// legacy encoding instead of Part 21 escapes (GBK from Chinese vendors, Shift_JIS from Japanese +/// ones): that encoding is detected from the lines holding 8-bit bytes and the file decoded with +/// it, so a name reads `圆角` rather than U+FFFD noise (#2344). The syntax itself is ASCII in every +/// such encoding. +fn step_text(bytes: &[u8]) -> String { + if let Ok(text) = std::str::from_utf8(bytes) { + return text.to_owned(); + } + let mut detector = chardetng::EncodingDetector::new(); + let mut fed = 0; + for line in bytes.split(|b| *b == b'\n').filter(|line| !line.is_ascii()) { + if fed >= ENCODING_SAMPLE_BYTES { + break; + } + let line = line.get(..line.len().min(ENCODING_SAMPLE_BYTES - fed)).unwrap_or_default(); + detector.feed(line, false); + detector.feed(b"\n", false); + fed += line.len() + 1; + } + detector.feed(&[], true); + let encoding = detector.guess(None, false); + encoding.decode_without_bom_handling(bytes).0.into_owned() +} + /// Read STEP bytes (`file` is the source file name) into an Import base feature. The file is /// read once here to fail early and collect names; the feature holds the STEP text. pub fn step_import_feature(bytes: &[u8], file: &str) -> Result { @@ -171,7 +200,7 @@ pub fn step_import_feature_named(bytes: &[u8], file: &str, names: StepNames) -> let (text, iges_warnings) = if is_native_cad_path(file) { native_cad_to_step(bytes, file).map_err(IoError::Invalid)? } else { - let text = String::from_utf8_lossy(bytes).into_owned(); + let text = step_text(bytes); if is_iges_path(file) { solidcraft_kernel::iges_to_step(&text).map_err(IoError::Invalid)? } else { (text, Vec::new()) } }; let imp = solidcraft_kernel::step_import_shared(&text)?; @@ -748,6 +777,27 @@ mod tests { assert!(!model_xml(export(&m.state(), &[], Format::ThreeMf, "t").unwrap()).contains("Title")); } + #[test] + fn step_names_in_a_legacy_encoding() { + // Exporters that write names in the system encoding instead of Part 21 escapes (#2344). + let (_, m) = model(); + let step = export(&m.state(), &[], Format::Step, "t").unwrap(); + let at = step.windows(7).position(|w| w == b"'Body1'").unwrap(); + for (encoding, name) in [(encoding_rs::GBK, "圆角20"), (encoding_rs::SHIFT_JIS, "ネジ穴の面取り"), (encoding_rs::WINDOWS_1252, "Gehäuse")] + { + let mut bytes = step[..at + 1].to_vec(); + bytes.extend_from_slice(&encoding.encode(name).0); + bytes.extend_from_slice(&step[at + 6..]); + assert!(std::str::from_utf8(&bytes).is_err(), "{name}: the test file is not UTF-8"); + assert_eq!(step_import_feature(&bytes, "t.step").unwrap().body_names, [name], "{}", encoding.name()); + } + // UTF-8 names are read as they are. + let mut bytes = step[..at + 1].to_vec(); + bytes.extend_from_slice("圆角".as_bytes()); + bytes.extend_from_slice(&step[at + 6..]); + assert_eq!(step_import_feature(&bytes, "t.step").unwrap().body_names, ["圆角"]); + } + #[test] fn step_and_design() { let (doc, m) = model(); diff --git a/crates/kernel/src/step_in/p21.rs b/crates/kernel/src/step_in/p21.rs index e749f40b8..29e6595ca 100644 --- a/crates/kernel/src/step_in/p21.rs +++ b/crates/kernel/src/step_in/p21.rs @@ -348,6 +348,7 @@ fn decode_string(raw: &[u8]) -> String { i += 5; continue; } + let mut run = false; for (tag, width) in [(&b"\\X2\\"[..], 4usize), (&b"\\X4\\"[..], 8)] { if rest.starts_with(tag) && let Some(end) = rest.windows(4).position(|w| w == b"\\X0\\") @@ -361,20 +362,23 @@ fn decode_string(raw: &[u8]) -> String { out.extend(units.iter().map(|u| char::from_u32(*u).unwrap_or('?'))); } i += end + 4; + run = true; break; } } - if i < raw.len() && raw.get(i) == Some(&b'\\') { - if rest.starts_with(b"\\S\\") - && let Some(&ch) = rest.get(3) - { - out.push(char::from_u32(ch as u32 + 128).unwrap_or('?')); - i += 4; - continue; - } - out.push('\\'); - i += 1; + // A run may be followed straight away by the backslash of the next escape (#2344). + if run { + continue; } + if rest.starts_with(b"\\S\\") + && let Some(&ch) = rest.get(3) + { + out.push(char::from_u32(ch as u32 + 128).unwrap_or('?')); + i += 4; + continue; + } + out.push('\\'); + i += 1; continue; } // Plain bytes: keep UTF-8 runs intact. @@ -556,5 +560,8 @@ mod tests { assert_eq!(decode_string(b"\\X\\E9"), "\u{e9}"); assert_eq!(decode_string(b"a\\X2\\00E900E8\\X0\\b"), "a\u{e9}\u{e8}b"); assert_eq!(decode_string(b"\\"), "\\"); + // One run per character, as `step_out` writes them (#2344). + assert_eq!(decode_string(b"\\X2\\5706\\X0\\\\X2\\89D2\\X0\\20"), "\u{5706}\u{89d2}20"); + assert_eq!(decode_string(b"\\X4\\0001F600\\X0\\\\X2\\00E9\\X0\\\\S\\a"), "\u{1f600}\u{e9}\u{e1}"); } } diff --git a/crates/kernel/src/step_out.rs b/crates/kernel/src/step_out.rs index b7c9d378b..0342a4040 100644 --- a/crates/kernel/src/step_out.rs +++ b/crates/kernel/src/step_out.rs @@ -1854,6 +1854,11 @@ mod tests { let p = ex.get(1).unwrap().params(); assert_eq!(p[0].as_str(), Some("a'b\\é")); assert_eq!(p[1].as_f64(), Some(1e-6)); + // Names of several non-ASCII characters in a row read back whole (#2344). + for name in ["圆角", "凸台-拉伸7", "ネジ穴", "Gehäuse 😀"] { + let ex = p21::parse(&format!("ISO-10303-21;DATA;#1=A({});ENDSEC;END-ISO-10303-21;", string(name))).unwrap(); + assert_eq!(ex.get(1).unwrap().params()[0].as_str(), Some(name)); + } } #[test] From b4520d265e548816b98a3ae8b30fafbc26c35911 Mon Sep 17 00:00:00 2001 From: cronos Date: Tue, 20 Oct 2026 02:33:35 +0000 Subject: [PATCH 164/225] perf(ui): show sample thumbnails immediately and reuse Recent previews (#2944) --- ATTRIBUTION.md | 7 + assets/samples/README.md | 19 ++ assets/samples/exports/0.png | Bin 0 -> 75955 bytes assets/samples/exports/1.png | Bin 0 -> 67147 bytes assets/samples/exports/2.png | Bin 0 -> 87821 bytes assets/samples/exports/3.png | Bin 0 -> 64133 bytes assets/samples/exports/4.png | Bin 0 -> 65735 bytes assets/samples/exports/5.png | Bin 0 -> 69254 bytes assets/samples/exports/scripts.json | 8 + crates/ui-egui/src/control.rs | 1 + crates/ui-egui/src/file_load.rs | 2 +- crates/ui-egui/src/home.rs | 331 ++++++++++++++++++++++++---- 12 files changed, 318 insertions(+), 50 deletions(-) create mode 100644 assets/samples/README.md create mode 100644 assets/samples/exports/0.png create mode 100644 assets/samples/exports/1.png create mode 100644 assets/samples/exports/2.png create mode 100644 assets/samples/exports/3.png create mode 100644 assets/samples/exports/4.png create mode 100644 assets/samples/exports/5.png create mode 100644 assets/samples/exports/scripts.json diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index fa381d097..c39715f38 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -28,6 +28,13 @@ Editable drawing code, native projects and shipped exports are collected under ` | docs/screenshots/class-a-crown.png | SolidCraft contributors | screenshot of SolidCraft itself: a patch crowned with `surface.patch crown=0.3` over a saddle rim (`solidcraft-cli snapshot`) | MIT OR Apache-2.0 | | docs/screenshots/class-a-boundary.png | SolidCraft contributors | screenshot of SolidCraft itself: a patch through two sketch lines built by `surface.boundary` with `crown: 0.4` (`solidcraft-cli snapshot`) | MIT OR Apache-2.0 | | docs/screenshots/sample-plate.png | SolidCraft contributors | screenshot of SolidCraft itself (`solidcraft --sample`) | MIT OR Apache-2.0 | +| assets/samples/exports/0.png | SolidCraft contributors | original Sample Plate from `crates/engine/src/sample.rs`, exported by the SolidCraft thumbnail renderer | MIT OR Apache-2.0 | +| assets/samples/exports/1.png | SolidCraft contributors | original Sheet Metal Bracket from `crates/engine/src/sample.rs`, exported by the SolidCraft thumbnail renderer | MIT OR Apache-2.0 | +| assets/samples/exports/2.png | SolidCraft contributors | original Hinge Assembly from `crates/engine/src/sample.rs`, exported by the SolidCraft thumbnail renderer | MIT OR Apache-2.0 | +| assets/samples/exports/3.png | SolidCraft contributors | original Plastic Enclosure from `crates/engine/src/sample.rs`, exported by the SolidCraft thumbnail renderer | MIT OR Apache-2.0 | +| assets/samples/exports/4.png | SolidCraft contributors | original Bolted Flange from `crates/engine/src/sample.rs`, exported by the SolidCraft thumbnail renderer | MIT OR Apache-2.0 | +| assets/samples/exports/5.png | SolidCraft contributors | original Vent Plate from `crates/engine/src/sample.rs`, exported by the SolidCraft thumbnail renderer | MIT OR Apache-2.0 | +| assets/samples/exports/scripts.json | SolidCraft contributors | SHA-256 fingerprints of the original sample scripts, generated with the shipped thumbnails | MIT OR Apache-2.0 | | docs/screenshots/demo-0.8.gif | SolidCraft contributors | original screen recording of the actual SolidCraft 0.8 English desktop UI modelling an original Raspberry Pi 4 case (no logos or branding; the engraved text is set in the system's DejaVu Sans Bold), generated with examples/demo/record_ui.sh and its original animated pointer overlay (9× playback) | MIT OR Apache-2.0 | | docs/screenshots/demo-0.8.mp4 | SolidCraft contributors | original screen recording of the actual SolidCraft 0.8 English desktop UI modelling an original Raspberry Pi 4 case (no logos or branding; the engraved text is set in the system's DejaVu Sans Bold), generated with examples/demo/record_ui.sh and its original animated pointer overlay (9× playback) | MIT OR Apache-2.0 | | docs/screenshots/rover-build.gif | 0xlillith (model); SolidCraft contributors (recording) | screen recording of the actual SolidCraft desktop UI replaying the timeline of the SELENE rover (`Rover-recorded.solidcraft` from https://github.com/0xlillith/solidcraft-rover, an original model by 0xlillith built through SolidCraft MCP); the model's lettering follows Ubuntu Light outlines (Canonical Ltd., Ubuntu Font Licence 1.0, as noted in that repository); the emblem is the SolidCraft project icon (2× playback) | MIT OR Apache-2.0 | diff --git a/assets/samples/README.md b/assets/samples/README.md new file mode 100644 index 000000000..01ea15e68 --- /dev/null +++ b/assets/samples/README.md @@ -0,0 +1,19 @@ +# Sample previews + +The editable authority is the built-in command scripts in +`crates/engine/src/sample.rs`. The six 240 × 150 PNGs in `exports/` are generated +by SolidCraft's thumbnail renderer from those original designs, using the same +isometric camera as Recent. They are embedded by `home.rs`, so displaying Home +does not evaluate sample geometry or read pixels back from the GPU. Selecting a +sample builds its editable design through the normal commands. + +Regenerate after changing a sample script: + +```sh +cargo test --profile ci -p solidcraft-ui-egui --lib home::tests::regenerate_sample_thumbnails -- --ignored --exact --nocapture +``` + +`exports/scripts.json` records SHA-256 hashes of the scripts. The regular tests +check the hashes and decode all six pictures with the same bounds as Recent. +The generated PNGs and hash file are necessary shipped exports; benchmark +screenshots and other review output stay outside the asset tree. diff --git a/assets/samples/exports/0.png b/assets/samples/exports/0.png new file mode 100644 index 0000000000000000000000000000000000000000..cbe0b69c15077cb4027aef60958e32797dd5c5c9 GIT binary patch literal 75955 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%0D!_SDE~tD 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 literal 0 HcmV?d00001 diff --git a/assets/samples/exports/2.png b/assets/samples/exports/2.png new file mode 100644 index 0000000000000000000000000000000000000000..637896f5a5172e195020809477170c2042a31531 GIT binary patch literal 87821 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

pHqdJr+PN5q; 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 sDL-T6%ECc@Ej1H1m7SJ-``b&(< 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

wrb}pa2#^Z! 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%0DsU=+oUWz3lR7HVxy+ z6viedOy>+p#{cFeQFpB9w$Vs~kjaevaRG-;LB#b@lZIwFf z--PXp`vWygF`cyc={Dd|u1tABk4)t!tVSZL(1Gu_U+q%g(n)rq79R3`Rp6?M08pzk9F z)`ObXS!>qn_H}JswOJE;`qEmIX*i!j?adONdMJ9It$#c2kgHo;yG|Eb%pY*}(~6K4 znKR`70pn4TqVk>VC#_$uj|{|cqO*%7Si`Akx?DJkoF>5&W?dZnJS9D&z0R; zv-WPNs5CFA4?*0&e0Vh}9en^Yz65fu*?gr;m0GS6Pb3EjXVw&pPejurWR<;4l~wAY z8~5z>z_K0*Ihef+>JV5)aD|l4j$7|h@`V91#c=>TV*u%@h{uhZP+izWFA5I0Tcg24YYp)Oc(?y=DB?2rmq)AZ#Qag#!r8;^1I!?! z-jwRMpvFx|>W2N}c@?L(aHom`j_IMwli^ftEia`yP_Y!pjlZh$AQ#de}@sqLEqpp-v zYms6b%NHQXxIjw_mAWJAn40IqyFoKB)UZ*)Eg!92xKwC8(B?C-olg%6L{d`yx>Z^q zd^)dq^WQQ8RY%|0E3fxW(P92uoiC+#y~Eb@xFH4Uu;f4&Vdi zx0_9Mr4&lB+ilg#g9+tO|A`Lyuu$kKBowMwK&R2v3~je?7c_k*c#&zvFD)Uf30R^7 z5c(RrEMZyQ3_h||MYnt^s5^~-_{csk%GoV^@QOMJ#w2QY?h$}vUR|y?+#NGgiJW%y zFCV<=;x0G=Tkn?coV10d7s(CsQzf+LKDoDS zp^^QxtbD||q;=17(&7W^38XIB#%|lQr%M6vXqBUCJ#^msuA3!pV)gCWb_2LvYD6D< z&m26sjDyaA1|pC#7qU?*D&_1S%wCGEj)Y-X0OF4R>O7RUR{~-H+BgoRh`$MPkkO(m zi~OOa#aJm~C;dQHl&{_*ki`eM1x)yrGWU7&PEsWnou#Aq!w-lBQs~~vU2xF7ILaB~ z32v#`w<8Y;?s>@5R7IQncSU2S{2stCZiDDp63%*PQzq`k*rDBEOB_C-oCP`>Co+sh z#>1$rkp6JWxR1e$U*_;j5A#B>hU}PmHnRIzvZv9re6HvEV{Nohgs@c5Ury=I7nTR_ z;DY;8L?$jy`Y`ky&Y!i*LnYuTyLMQYCrRmGqcn-o(Z9Z>FY7bwx(Oi(av zVkOMb2?YJ&kcZn!f1t^F|%DNJ_~e=m?re9~1GTKSg~DD7RS$ zQCvFoqR1))dlz-Nd7{2jH2;Ey^w|3scbEpq=>m|c08zFb5A!nJEYZ#JbfHVB-D$f< z>Yw4=V%fIG(;Gkgfvy%8MpdJn1?~s!R@k}&CNKAHh+L91cytpI+8Q*YQPVfJk4&ip zj>KbRWH2ctXwiNNg~&o-sP*s(YhE3_O|Zh?J7KJ$m`AWe`0}&a8s_@M|Q^vo1YCS{TnHhA50bb*_}&9-~#D{bA;I8`@Mocwm& zPnXsL8Xg3k+ZB0aU3zH|7^eGyV zeG~_~&YN%R{v&_%Y4J!Kb*iYZ|DiB$u0jhE?KJFfT+_%*X1HJ+(~GhGdNEh|5;>f( z3TPh%zOxi2hDd5(n|}w2Ws?_BgdSUi*6!LR@Al+a>;;%6(NL_Ys69oB6d36(N$#bR zSmb9<;58g1FqTHNCnKMUdt;lf0h9I&L{u{gUOM-6-b@FM&**c+# zfcDhmrX<#eXcn;cf!oe>oKvijjBJ9_H2OL#nv^`4j0#M8PpFhrmgb@=!TM{mmYnWT zS7`UuP|K+Cd7?2FQEtxcg{(`9@MiIF_Xt{FkG?4xu9DiAiTtbI{ zbTu>|*b9s&?IYx;#!F8xotQwXGV~tII|f2jNSBYwK z79&5W{H69udu?x$`=tVB9cXZ=-KAtQw=lGpf7odfndp!J-U1UOmUjp%A#oS?6I*7@ zfFAubd5in!XO_&k=uJJw|3SU?=WRH0Db<3vLZpvD38s0m{Qa?*~SRGl2?sr=@P0w0`pMCLw_w%0H zrAK{fMgz{llIHR#s8@a1?2~R%5WIM#h8L4JcBd^@)Kids!s;sJ$!yNM26cGx$019Hbyy3!=0kvH>% zH`P6#=6b3CL*c)8j#C}CRtPyt6pnd*>^qYk1jtz5+`lkianE5z6=RFTmfFTkS+R zjwR@risYsgXVA=QnT{w~Aqx*=mo&7JT1Zy!Qe4Oi!ecA9EVn+aAhMNH_MJ`#F z+!mcG89qYHcU5FBN1Z}Z6s1eS5rS#>xePygVf%_vnTI~ZM)adHrZs*#Bn8BGDzCU$ zwXQp`ClXu&(pKkiM`x>6@jm#F@En0pch!UMYz(~4y^-tv_p)27j{f;7(z4)7&uP2^ z#0N@$W)f+f{C?z;BD8$;nnwLv$CmxPfyXDP90|+2iTyQ@FMqUC6#Ov#@_F87fk8QEfi@v$z?Q+QCh9xl*pm z$v@@C9qJ9(>EaTJwjg&tBBSND{124qfuJrW{DRqoFsAF0W641Zf5y+YAxtwVo_vxC zKXS>9_IP;)x^k7ZeuMFRLZH&G=S1`!7G__n zt88#4c^0dmw7|8EmbGWg1J0Jan6y%Su*0{rQVuC60R&xaQ0(d%^B{mD?+CR#>Xd4# zloSem>b&`Zf8r)YRacwT@@ay)LR4tSGevOEzhYuMKGrcaB>! z=r99P#x&thLM+rj}Ks2MyNsF6nYUQKWX{EOiAdz>lv?zpacL{|j&Ys=72kBHt-k{C&p#g3$ zz>f!*w4%Y;7B}8){Jg`ZwOCpD9~^9)a}eCY#22A?A7$yldXNP;!uNYdN)pI-VNu0V z78WT?slG)tomvAui{lCq(PeH=F?#3!)uH<*heQ2-G5rW%kv}Em_Vt-q4+KfGXAAV2NBi@?6#+)R*P2-?;iKlI0e3P9g?nzUX@zA6@Hp+Rsn{gMXe2SNvY zGL9@nVRPA%mLf-phZtM3?iX>!3TbTMO6|Ug<8ky0ZKX@#k^OjlaDYG5hV0FV^ifrC zMaqiWWfhs2;!CMdTq;70cz0WZI`zM{b%$~8EpS{8Cev`J@_ z1=Sf}guV~ngM40!vcPZ9kkdbsEgiQkcM$3@&xnHZJ<{g4HT-8J46aX@jgG}RG0Z(3 zJFl!7lHaT`PoGT>SBdUE8Y`EhCkC@8v^OY%Ts+pqXHm8B$Y*gNeXH)7_~kyou6K0r zLMH!A#*b^-LI@zRlupD^jt(4`MekEu86<_giS77(l{c{EE33?rL{Gnqh*ROYu&g?C zBAm}pf0a_}h^+&x``V^oETj4~2(hqmE^b>3}y*g3 zCM5)iG8J%>3jV)buh%%Hs}eQ?a0lBNu;^5;B`o^!5cUYS<@6hly_Tp(Ks_(zGH#iL z?jBy^ewtr9OAz0di^bM)`$NO$`((O06&keDg1#!%sad_9clOM(%8oc7- z7XGQ!cGJ&gw|@1>N5JwPen|rd6)wWCp3^a-;+S;U0qh%ubSSfT58Z~nwxj$Df;61% zoxHS`+NB?9%&VxarN)Z*$%%y@kUKyrV8SsK6djSNIp z@S7%nIGZb?Xp1N|Jbdni`zMxy8Y<4GC%~QRAgB$$I(Ur#jB#K9xZni`+2;x_2pQ+$ zhX9BJChR8@G1iwb{;l=kdFu_xDUse9Wx~GMXkz0iIE>tlUlc#HG9Yal5er7z9mi4L z8Eigz5^_8LM73ArT>G0|FHfUk-US2e8<|e~9Ex(mvB4PD3;<0LJ^CT8u^X!~Y5dFy z@n{H+st(M}x6^xydH;b<0TBUz0~pT=o!!Dw2z3lh-Es~)kV1)bu2y_A#ET*gnBfin zDg6QC#kFt~kk1J61jPo2gyI&QK5^|*qJsw5;8k5UtdAP~q*JOC3-MAz?Qjv#3u*dq zp{#p{@bIV7BnJ(AId1L5b!ZxD&8YFDpC3a-By=jLLR|f(%w1wQiK~+-0+R=MDqTU+ zQ5|G;Lj0mL|I(KqEMJcU?fDd*ulCQ|J5uI3vYshB7u+5pIuao|w6*D3Ab!l$Ow^$* z8ZH;*pvlA=@nRW%;l(-&&9f$3-P_;v`w|XUPpW7@J!5=W5|e&V)g$$>GpS!u*#d=R z@FNnKOolAb-9UD$w8f$Sn)}nbi>%GGFfu6D^!GxIXM}7z? zsM7|=-X_PLB3cwWq+a<$`-qZjqT;scwGqDjT&Ts@<$-6*n{oO(GL$g#7J81v$llvO zHsXKs-cpArpF138=^B#JR!KvVxkqC+e5$tgcJJ3=9fHx^+Nt08h~)r7l+`BI+%QY+y$;5O%yL zmM`@0DT(H>WHN?bcXDbrA5&c zvLt32&14%n$C5ScRE*LP(t?8wis3MXj5#rmDN91OGEod_Oq3;xkeQHdY5za3`%|AX zXU_Nk`##Qhe5&{7{eIuqec#u0-PiTHUYEoSMdx(w&5FPHz*6p~ra@vh0RaJ7C5QJI z92nDSOsA&RjH!G2u-p?~1K&QjGMjFYI@RIM{a{BklTLD3dGmB!wz^3~i8-Iv) z<3$z*$DZCyCn|4Sht+<-mQKAZ-Ri>^#24-h>#TU|7;Uln)NUO)`VsSw-%qCofCOkR zVvY@EY1p%uu&m*^zjFXm;ex#?7gy!SYXk<-KqkteR1y_^B>tY#64@26CK)`F)nDnU z%&bJdG+nMWFD)_;ZFcfqKFo~ocTep0l4@@qqUf;N6Vbc2-qD~=Ze%Iz-oYZ^P14xT zo0Y5TpS`eIZL6TaAU;3l#IdKxTQ1nLd0}$_W@h9n&en{4%aA8ehPrkJ-ku~?a<^{L zE3XqoqWCw#mFt2sh`oNeJA+@qAZXv&85GB`uofX!bJJJcO1UKe=cnV^d~jv^h&%s`k-%996!D2c((h;~8i^@OzUO zHeK=Re0=?8W5ea>{Zm2nj5bM&jCV%PE1RRDf*%E3JbK@fm8u{B$0|x%7B7!1AFC9C zC?EOzza!~GB$cH(FP!qzRbZf^{UV9v_AmGAADO>DLC0?{P=m@{FY;0gQ_#|7a+Df3 zuCMN!QvasvaI}iDw2C!Om9b7!XXaUnT!q5=V#3cIpH+jhP5zi^!^`5yfSkCWwS4tY zDa27A;UIzP;rLrxALTokOdb=?N-BK5mj41~-*WhBI&Y zYnnvmHC)bscnV(R-L44z1Ut)Oaiztxh=f-ybu>7)^uP*>m!SyJMQBfI{jMfz*w|5M z6V~i;+Ah_9Y9dr@Y^TI*$jOB%=e}4~W5mbKgrU^9x<64x`vrQZTTjSiATfrY(|0`o zdksm?!mm^gB;xe%5zmt6l+8eBxZ@=+O{r-tohX$*6ksg`Dn5l{g@d$978#0zcL$nj z05!;fjg0rk;%x{s-!M6(*Ot!?wtDLJgwKlCS(H9Xy8|CmTr#M#Wd@&kUwHjmAsA7} z@%cNH&|Y3>%#!cX6Kz6;C+^Ak7&7~86O~(6ra2?u;62$;?%w?hFAO*N#BO`A~Ek!v? z8G-8HhiblGtk($#n+1F*5Lya`wGJcXjN%zx2t!$&6)fQ*o2Vv~vZh}Z(EntsK>)@s z2s`H~Tig*~g&m@Pb;n7;mzYKn#jPHRrbK%)>Fn@#qg%Je5ig*I%~YoD>7rlKMdt@<$<5H3jIq^1!K6=U~;hXhRW51|6N|7+@rEPz=6%WmBhQY?=r>_Vf=0 z0njT-X?tFm@y7ToWpiGO&0Ek!pDa-HxG>*7pOzzvLak3hEmj{mYXG_`r>3A@qL1-U z*5GSaT%sQ7!sgMMp_{#A6&DtV2^eX^|MNkcJ(_mF04se5xv&-v? zl*Mbzk&8N%$a|Ynr%cnI8G$a@MO1FZy$noa7y=|w%5Z#e=i!T=r)%s}0p3SP55-~? z1Il1|7W6GSog$i9CxMdFCJ0Y^8M|W<1jnpo4bM+@gzC=GzJKxWWyO>5c*7T+{X}ku z4(ANn46`3bbvH_cFR;#aY9o04tK#}P!f_*UO9*4tPh3V%FRUMBbGd~_w^r8IJ9o0r zvkFS`=iF}wfy2V;D5CniAR=h!f`TZHeD%BX$|Xc{v9gEy$NO|@J^{g35h`|w<99Fk zxKl-vQ%+etTS5YhdbGt`(iAHyI0C(_KaD#TXG-Y5nZoBty>`~TBH>S)C*1y2t4lqm zs>wX|w1uS2WyI%8%HF}BZXm?K2$ISjA-uDZwoC=BF!t|gqBHK?F@}bD^;Hh2-H=p9 zl2+=I=~!golQb_=%2)X&>XVQNOuZPlG2zN~Nl*aVR!-s@N@vfR)9oi0(G@do@;!2( zp5+n`M-DeK)0LTeETODdmGRQ#K(0v0^pR`H=&YR(+~@>O8+ zc5XZu`S~Qh?#Vji!H89^FB)fIq;xm-4^rH_%s?;tr=r27!jV^LkU1fV>zchu$kQbh zX^In{tv_w}%Ar{o&5+}WFph#6tXXg>0&Njo`BB;Mxo`sRDEoK&Lve8`LMqO2ZTf7s zZ4N1%5Bl~^`OEew*cwZ$5JYjfzc*~d*oMhpP zE9+t{twCbhvTQ>Y0b!xVXD_l+tM}E_3yoR5fr2uhTh1b5*rME0>EZ)T+-InYd1-;N zogF2UE^Nsl)QMcMLJj5O3=sFw$V`j;q~vs7Nq&q0L?=&$C5ps+Ov2L^$do|Qv@sTC zlU|8~B(_~|+Ev6;U{@WE!RW^2U_8-+yv_Ekz z>zq;I3O)&PwyuGV)HN|#$$PQTu%3=^@r?+M-5XNa-mou8Y`us^(~U%7}B(e_)c?r5jUOBw_Xu5!` zUfo2ppW?TuEOtmuf2Z0Ko%naLFpIPO15MP?u{z_Yff&FusscRf)EG zgIBkc!hj2V{Pe0LQ?D{iGH1O-u)XNTe=kln34Am2=nz_8 z<~*xw_AWG8fte#*zmKaE`oQbcRUc>jAI@MK_*%odVPYnbUi++h1!GwRdmE=nFrdi* zn1MSrC0wLYbr0rcp`po%qjSZtuM|Mm!nbe%M~?cxc{Qncx;`9MPhWe4cU~(H`HpJP zniup(d!-dr%1-H45`O)Dl_0!IZp$`5U2r17NF5SR+ABxku5Y-Jihv${L7e^Tug}7f z9MkuyvHY%V+;%7bFcm;!KQ+o6?`K2AMmUzF8BS`FZG{i`Vg*%@L}SdU*L|RP>{2KP zhJKIlTFg8+=2@#JF(;l*@h-L6vp+tJ#w0?jsEN3;=WTTRQjYwfe>EDG+J_z93-e@> z!*BjJog16I+ie3R7mKWkShAQQRXS)p=&NI|%`kpv=f>}v?slih$mwP5@Es1r)b=Mi z>)wk9C_jY=9m3o=_>f}b;y%wV;>1Opb74}UB&~4>*!IEMxD;QBR&li>C%k9+4;z1; z@*(@x+&tXDq2I2JKS!2dOF#B?#a_$_<})`6Wh$V@wBk<-%PAd zCZ`e2Q!8S#=4DP8?_b{FfR0QX@w4!x*0QxB9_t8hmu;JSpNg<=N#EfUx;_ z`Zo)a^LC5<#aj{6x0SQ}Z_jIH5q!4IvAes+u`Z`kEBVJ+-~S;mD;EJec|gGC<0A_` z$pQ9~m7uGduUOCi5e)tP67Mwnf;;`w!%7;0O}BEH5twptYTv^doV}l)Y4v(U25MjPyk8)Ub9(}ll5JvqYFU}v0^fG`g*ET*>)6P_57W@9?hM{e0&D!9MjNcs}G zLsvW5)&_j3&?NY|vHAQt4*t!o8apj{P42(tf{UbjT%Ebd)`O zu%G)}Hb*UXUB#9Gw8FAl79+E)32OiTEJvq=l1MlXKH-J7Drv96{Z z2{ zd@_0cbMu0diIIV~<1+D%qME#Z{o3=!_1;H5$u5Fs3@(ChMJ#qQ$WQ5r(3jAvzn9uJ3uvM zLOU}rbK<%JV#OM<)wgCVZ%f zK^)d-Acb*3B_B=^-$nc!mYM@~iXy!Q3!Jm(eI1xW^%V#4yZ5@tX@Fj3%@JU4hko~h z0yD1^*&vHGNp%Ng`cn=B58BLlWWO=I?7QJ_9&e8xYNn_+IO|{Y8k*@(Rg9}0hm+ey zJEqfh@av0f`OE17t7J=q3E2j`h}N0urLN1Z-mQoThYj!!BG8R)a%f<#o!)F{?^9(b zMmq)*H>xVG{GXB30F~(#4P@{}kcBD}M(w>gRXc7e*NRNzrr--`38lIuZc6Z#bjnBpB_e7L5TI{Zt5o<*8|-R#cnE&KmCK>FIzhn1?RRkJ$!wFw zk7hrWRrP>(XFQZs;#=!b&766gBt z$bEoPfoh48LPYqa3od{-mN}&C<19Vy`=U)=xB4pgx8gnG$NF5WFFUSmrtR##~$8YTg81Q`0j46C&kDfTB7k{L+!72PTH{5A*P_4pBb0<7OVK zxY?a#`>H*Tx$})>tBOSH2z)QumoApKDRW7Yx;9o4yde)&^FYG*+=9eoLo~yOC8v!f z<~MEdux$=2D*kA-;~{@M9%D2aP!y>`S=zG7+16C^aWqS#Ajmk;e$C6k6v~2D;t882 z)lEc!$YfAAdo(_NV75Q1!Z#r%A59_??-KlK^uc4L!xUP+7P7rA2P!I!#bwdMB(>^D zc3s4)>-44|$Lc&#SyvyLR&i_{nEP85L=egA*goW(Ws;Lt`8bW*D#My;S$+Ivg9=vf zFFn3L^!J#=uXQhn&urqUGLJ%1zWtVvLOHn5nbE=H|%P?}mLCN(4#vTkT<0N3?C>OUvOE zCtj5OoL13E4=(*ji;kLTf=r=H!HK zXdg~ng22oV*R;VXARUd*=KKQqn2U^jMNIzntm`{%5fQcM6u!F9${G#xh_{00FaupqfaE(2C-1~S;E;(qar~-gp{Zp^8KG1!!o+%gpzMzjLsL3P;iHwb2 z{CM=4h%%$>7kh%w3@>{VURW<}!3QFxH!n;a*X)~kOnkcP!0Frs6=GH~=^%-`7^ssv z=EVl{15P9R4`phwJWq>6q9%)^>5hm^9bcG;?~{uQk$ z9`EiIODeGuzjXX@=oi2;gObD~1Wpp`9gZ%U^SJM_ia!b>|M1vmwPJ}xKrzXND|~kq ze4tIp_PwjhR@uz&uHsb7Q`xbGldalg@|&$mIuE)R07sI;!T9){1$~e>9eC4soWT-W z1V36RP(@OG;8pj^ zzXE%tUBiTX)d3k&Eu^q>=S?blwV?E9aKO{dS2lr}>{es3%kSi%*4~Y=N;VY`X*1e| zr3L04d%86pXfv|mq_4KQ!xjI30UZ^|$fZI-)2|;O-_I9j7A>w!J1wML2QL%hxvl`bHM z+`C9lR26xv&dRZ$!B2Wa%at+eJDQOVCgllojNIO11~W3ps;nOotn9-E`S04G`(9`n+cg$ zUfCo$bPH=dVYFS_M6*)>7znq^6Co}MVM)(8=8Wjn|pwMWN)!KP^t8?4Fw zEOQ?BG)lB6&#{17|K%qqog0j@2rw33;7`?uz^}ITo2M#st1!@2of9M!tINq4sl=cx z-rCDDND?n%r!;-qMbQseFIy4v@PJ=NF5D@qLjV_Lb6zNaHre}RJ6cy3e9oA&{Ih!# z^tgU~jCcgv_1m|nTDzb)h2eq43NGrmc|^hBa6r1vQ&#y}|9(6yV$N~fklVK%pZddK zp%vZsH~(C6Fo^WZq>A#94eY}jYv?BQ5aqMU$xD5=ft5t4D_vY*Cy?$nAN4wxcRH57 zkG;F9Y-iS+lmMG^dp(O8(G(Lo;?aJU7LIMVe(QBYXfO_+c=^4Vp)#Y zy_La_RxZd~_(0Ot!4*4K`d(Z8@c%q9=&71j=|?7p;>JiIP~jtFDMtKd2q6oOIX+@ zkVD#|6Kb7OM@T7{CzYku0;n5;H&kCr_XZ-+A4LNlrk$KNfpho##<>o#b9*p3<{`e@ zWTEb3oBPtK`IwLI=9qodqb4n~5?lunVrX`fr~xp7BibTFCiItbr7R|lmaixM(00OT zgJ-u+wwdD;c5+^rY7i0m;-kvMHlrHr7Vsp&4g7aHtbSrwF4m*Vm1&f@P)?Ml@?e_e z5n7(S(z5U^@rp4d)>pg3y+n#$IF&+Rc})3oM2skTP;gQK29(YD$jnF}$3Vu*<7QsZ z%F02Kg#(luq3K3)FoGV{($**iz82}M47Gx90owWX)^t1)NlN49iNEJ?)XyY1J= zvTKbOKfZ3R7R$M>Zl6B*xJU-{Q zD92>qd(_kRop1o0nQ46em`PO7>nQUk}I9l*>7M0jTQ4*TokEI2N-W=A{ z8)>zE_ZPY9MgQ0DD!M9ZPAr)|F{~({vS_NepHT<}gEX|2ovBevNZ)MQ49=%1Hu%6? z(VJ8rrtAM!^#cvsX5*}4=+D3|T)*}gS3du~RpEz`j_iJLxD0%wn}dUcan7SJ(KJ+_ zC;Lu8nqiwXN<2TAF_%*TiAHHYJAv|lu+_I;2CkH{byqveuDfmEEhc0h6ljYh3MJQJ z{TA}#hTKBqM*Sm4xZcglAuH_j{AJIRS0YZ@5%A8%LLF5xN&(0IC-}x&;2{ME5`S37 zp+7<3-V#*#{Y3M>KxPV;0_9%`7gJMxIo=xj)IQ%{4BiWSlYz>nX+m` zcv`m&m;RmKM@f}s?Q4xPE?zt+bDr>sOPK?C9|-TiVJQ>j6h*nsA=r0w#H8{t~QfY2mT z+o!KrxGANCq6c9lxIvG{i9ckQZ%B9n(UXA>TYTFf*|Mp<(4-VAT7;}Uw-iYUJvkXM z1L1k$B!?xWJ)`tVVc0i*jeJ%FljO=XdSEjLXJ%u6N7 z&_$!L$We|e{0${?aA$rW;;ofo2_^dy?zImpOVOi&VisNbAC-QgRVudzU8vOt4anI` zmaOC;HRY}8PpqTM1zxqku*Loh0Th9=-HYz{hxxYny>v&+sA1MlbrPdaIcmpm9z1wZ zW3$rm%~a|IMS~IPen=e$jW&CzLh!)>0ovDbQ>RWfNIX@veX3Vu4G^VG$rGoNajk4^ ze4oD|B(R4b4h|m6H(|qZB+4w!LC*p|!`KAHfp)sAr(o1r(Z$KD~h(eS3VD5z}2PbbGT zuTFSYzwEq4WkXGWn*B%D<9YzblIr8bHwrCvy)akN(bl*|de~H@-pQZ0aKlG|ek7mL zd$@V004Sj(HwAMkDS#epS)a+ihPa*=AAC#X)nOPB47w=axs30}&RJ3Ye%k!`^JU2- zc(xeZsj2KyT890w_;LHi&u3aBC30RmOgmWY3jIz!jVF71uV!&V5h2in*BN!7k(lC# zhE7WQq;)+@wrHJ1`=2fhQQ{FkC-&)lTJqrUN|3>7MNh%iEBaWoHdGj=a8B$41zPGh zv0VBG=r7EjKJoSR1t&PnP%Yt9vdk%me%~#}zv|i-{u4!E6{H~962wAD-~KfFvP7N# zoXx2;sY(sBSxB$9HLv@Oz?HLKwhw+~+_h=_<1urw+Hi;yGue{9=h5+c0^t=p zaw&dP^c)1UDV)4TFAv?V~1jG!!|)Xn>d9H_kpZ=&#i*#1LV;=uu+KU3D%xN zn68NFtGB*MV)wPdk8y|C5|ih^j_=+PwXFrcSs4`Cs`zfJht=>%ym>vHk%H~1tY^6@ z`IVFCs#?VBmG{M6U$8cF!O%P9j(3*fqfwv%Yv**?PYh|<`*_~e1VMS>Ph$pu11TfI zwL!hHXXvW1^zE-u0_C|CV?gPxSM^`iGcn59L9Y&m}M~8-cV{6?tO!c-8l7?cJszFh{*AgBJ2u++v z1!UG8X!ITAg0Efs#UTvM-ecHRdRUH+IhOtUVLMLT;e_(KpA>MiXd!UZPxP9(%1^)Cxzk^{(ClfPVMCY!T2fc%lg;T+`V_T{Xo0CXt??01Ii|f#vYI8Z^H56)ERMRrl8Pxd%l_>)u9)UO>%%xe- zxhVrP|H0eDk2m~v9zPkdKoFX|thyfzK(_%Xd}8}`ccPw3b^mFttbQn{BZv8ARA$h2 zmK~$tG*514vuV^s=p3fE8AX1~Dw-GAD@W9cd78oC1 zgti)0b9Yr*qn@`n6EJmb{6Xc>7Dc4Z81H|%Ie`a=UQ~NrmYyt*ztMT&a|{|Y;@M)$ zZc9#DqKoFn-+y+VI68;Y_FSlA95;OZH=iyrT_ybhP;=$t+d7C~o=lJ|vs(a18D7N6-y>8#t-d*5t-bV*uK$7grU&~(7Tqs%;|+6m1f)Ty zeO82OX^67m)JV1!Xj#_6k4SH{L9NK;TXz3aemn-B^uWI}%xTKulF4*nuv&ODI3LJcJlBh*+_6K+FSAN57~h?X56!%m`yl!sMD7W4#= zJzn-C_hO1{WhK!Eap4~SpqaR7?St>7D8hvr511uOWAn;u$%W;r9BbueFF0 zXXIc)uqHbl^`@o%Zpicx@uNwS;TQRAY1!-bL)_bgI}V}a)V7$8W=UJIUCqjW-e0*s z4bAf~xejeMr4=p8!hLL)(byE&g{4mx47*^6SRaAe^nMYp;usCqciL@5v-l|ec7%d! zI(%KA!n*^vHUU8xP@i>lj-If*j#sp(H!`iLZL5^9C)k4c@eq@0aic`0d1;f>p6f2F z``{UQ*{$tlkB_3HVBfWG+&il4)D8--IB!98+HTm6K9{9tKW5Re;4yK25 zVT2#c`((2B^REgjo~n^ZL4<6dE#3DJVrTB<*$BbC@8T|WGc(c}O=|~x#ef;D zeQy*_O@Y{g>{J(cXot^$+A5Czp}s|pgfb=LVLSAYbE8JUBb^&sa>N-uHhPq^aoi}p zA4oKUdPo9yXhe&IqP_`6y2H$kr^m|YKYYU>qd5I8ibb|ny}nP1Dv4;jvKYYgA#_PZRsFp8`i3CGI582jpotv znQ{!TxLp~)NaY6`jP4Az1m%1#t>YXU-GId8^3#uLWh$r~gp3tq|+FO>^C~x0b zsAyvIQc?U`&ZR9QB_t&ENv5bq-S$OWvdow-_h`kXMnAuya-i4kk;pfNt@2!g@2@mi zP;J;NoJwpk#D6i-$>7@6dVpOL&j!lvt zeQ#aym#EId7!bwE?}Zo58p}#18XDHL?{XTfxl8whBb;KdUV4*COZ`$~oA*{)^&m*SzR7|Ma8CG_`Pa*RU$-?S$GECh}eX1kG{PT{u`p zUkR}Ru~{%KwcY^ot+-LVLHboZ1<_m4qYxt4XJZ<7uxUGui5``;KjRl^-Up>-#g10x z>s#HeR##Im0_?@S2z z?a67MyRFlEtS5WImNU1|ZN~_=}oC z4!ZsH75j-e6%0xsR{A~u-r`}<=K1usfBfddr~c|iP$pS7jdNB8<(Ry=5c$SeAB(EI zSnH~>C~OZQb1JJR&AK>^NL^6FD>RvYPtQ+1cW7*4myG!^hr4})=+wF`f< zUn>l(`0YwusGgc}{PwghkXfhX@-E|#g;qSCv*WRQM}TSzzIOIrOC;0PPPf%vF17`? zroqwrP2DT*KWzNid+m)`I)wn()2*J`*zZ(-#DMxy0w_@!Fj&1JAoz`Qhrd32^@+{G zfWj`Hf};j^hD2)VO?JgSHz@YT8qclACdrMHNx@im-n`9W{u;?->$Hab8ltPFA>H>3 zvwRQMGQ2oQ!;}_)j-%E`^~ymnU4p(7Hm;gYpTP0A))_M4VeL(y)c17troR^?mYBV) zxqEMP!)4*4{&^xtMg|j8AKp1)cidg0frM3-|V~Fl-;z3dUR;rj6FRiol06!QqSrLGmt&;6;K} zR)fUlC767HW5~=jcoK-5i9?u>(ITqJ)6w2h;FjOP+*6$10*@VN7n9!$*Q@G#pYQG+ zK(iOpSis!W!wLuBbo}aWgq?G>L;J$z;d(b{PU-wP!@bwG?|;|y&mf`~Du66z=-kA| z=V&faT1R>GPz|BYevC6zvs>;JeK?~-6x;v7*}|!_Iz6QNyl+AO6k4`O3iomG3ymWE zc?9vw)d(>eCR_2gGFsq3j&L0qTy*x<;spyR7f0At4OQCf5=p||Vt~0K)#lY1fW+Jc z0;6=k04|2e)#nl39)5m}-}+46K)x?2ICTTUkkhudVC_jb_3qvG(y#s~3~i=jJZ){& z4KSXzwy^7xMe&Ljj?=!vP@rkIHh`0m#KdSR4*VQE#SqJuCMP^-AVT*weMQ{Gu9Y*NnBF^IR?UE0_feC zB;^?(j+Sr90$Z`@)b5O*S*k^Sl^h7aF!#vBIr!z~@S<70e#rP`QQQniGbo*n6o;`* zXIZ9_i$7gJR90w+_HVg7L)++%J)a13`c3D~|AK{e5p9)5MpR$X+dUc-K`u=pB>PXP zv2=B`Ys;TGaqg$j!0cU{ewhWgrn`}SoT==W2v}jZ-k4Qqz~1HV9rLC4qsmMZ!V&Tp z&P0+42bUi@L)D!D$Qg*Gzc$Ea=*X>g8nV?%I<8(w)`hUJR5y~c@QOH0_oseRE-;)Txky6Uz??U}g0+ixDKeE$#P{to_x zicmw)_0QIs+`hz{7WAPVimn_OQU@VAl4X9?J^s=c6mSjd%mLv8D_1+^qxR}4#39s# zi@ss;@O5W;iybR^+#41Q_O3Ck4C>@Cc>30MyFJl)+~Cr5cCGh2T9U5j7M6S)@q1uG zoPFo@lLhG?1^7|s9<(*GRk6X1=^ z9QQ*Nqwn24ue!8?}@qp^SZR6bA&Q`hM8-O~q@|qs2P{3ZOH$mB&HaEj#Wvu~Tdk!kv>6hiRk` zFPEEJSa?R09IMhbf>Je2Jh%FUvQhal@hjG@eFtv&m4`E~U%$SSqm*OO9T%~baB?-! z{h@;pL&*$~*>?AyHEY%vxG0`S`!Az+(SzMBb#{EgXYwUcBA`bDH#WNJ)|=u6*{+am zz!8TTR8)9Q8rD9m_KFB+1d_c1Sf}VFNt*!4HAb) zo}x~h{1xSe#yWArBoRwz*Op_I(rVsoUoE;!PEOsy>D30OGvVcr!k>}Gt*6RNVC50+ z9P7S8+rWR`Et}&j{RD(DC*}0@)i2Bo-h}llyBnTECKSd{2tws>tGU|AyGoqMr#xRJ!H)%M)|* zuEKwY-1qjpDL%~AZ14PaHq4qG?U{ZS z?id0?my;j1i)z9+qDIMelv5*eUFQAh(GGFl;HGYe&*1*y7p@*&4MN;HMvWqhX*Mfhl#^K7prjc(hoIE@DRFj(9$Ur2LhW_)4y7~*jD;i2`lGy-g z{cU<|^Ex+s7<}P%F7Xa*1Zk5*Gs1J%L)}2>akq|I6fH5nOvmwd>$rODJAv6FS|3~R zd!t*oZq1tYRjqpqFvFu60VyG=Es1E~FUbYaJagvSnd6VGxaU77gF0jlVnvi<@w&_E zIJ|d+t5S-0V6VT|_Nik)7~3mi&S`@XR^B?7u^PH~Lwj!nei(T%(l4%<916VBA&d5i|j+0>F4VW2GY9oRIv#_jcaN;;q zylbYNAVE|3TU(98iy7%%zB1eEF9cFEQqgp?Kz8&$SH2@Ce>TV0%alnZCmYIxU%CVr zF4*j*6ho0Wgua(W6X4N^bAvV#=U6$)VlcaozYj43u|5fn4P2EIq|PII$Tt_AdZ_!W97u>6^lDn4^dAu{K>;Y%0nw}dzCd#ktz!_?4_`&7Rw6C`^I-<0 z8zeY{ey}%t8Ho4qR!<(U4mDlN%F+sRonHS?152xHETqW>oSyT*LON77rt!(}yPm@r zeh?mbu$j*8ze#E}&~CYiSf?6G<1$zyJi+LiXk!m6D#qonatNYEeb2BR(hD4_AX8Uk zLKD0`tB|briY2EDJmp}r#NC@C)GRbvy#Bx_gchu47zIbRA1?Lp`q%#(F;H<qnoCFwee@Xo9U!!$YIE_ld?f>B)o*wP(?MVbv-8;&PbSZVm6pTDRZ=A zgzXWI*&AkTEiTJw0nGz~)uEF<##mv|0AIP)V~G)>Ccatq-Ur7B z_0z=knirLG5oEODp;g~gKNMNut1=g!`Y0zQ__0fIboQH`HDT3B^D!PmTQj%(RpyKS z1(gF&mR(Hfhhu}WOLxy*!YLOGh!_|aqC^ey6sg{XEw&?<8OyMMjMj)lCJAvUsz+B3 z{8hf@sgtT!>uyyN(PoiHmVF10SL2fW6sM$%KeW+GP$=~v_+wMry^L+HB`vyaZ>DwX z)r+_A$qv-%h7Ijuv3Or##Hby&4^qNg8BHFuzxfJ-kaNj(qMEFDwKbzfbWa+rF^6Mp zZ47wv$jcy=PYD}d^w9Bsmz%RC#OTN>NGU|~Fvfm;40lFemeIgN2u+r!o_Jym#WcjsI1O>vA z{fneMg-|ES3KG`jyD~9)Bv-|rH*e(v+DkoAHA-tvrFp^mTM4;+eJkLZwJ>)GdTa&T z*IOgB%AmQPHW|OuZn?*)-LfQ1iJpphk_)S=Kk7jmPR&@H9 z{lBY^g4H2nFKDWOhfVZ)PjC$=#s7K(&vfU#|LUbzx>BdSw=GhGJp2#io`(1kEJo3B z2G2yv>7lokx8FV<4yzq~KiKv4l*P~YEN+2{9pUPsm>RmwrD~Ri!`={S-9uOZw-iDw z)uV%EtsI-}OXOzcV5W9wK>&+?j>(yy=|M)W`-?0=(-Ji{X?+`Iy%`Kpb<2v|buB3Ldl@FPhPUMIuI|SA~cv zqs0+XWMh2FuAA?B^$jV2MwaBhBn2XdI#n(hu!~1o}w{P}(k4kfo<8O`Z!dXQP|d3WHlj z_x(^DOx@lnpR_=*biF?6C8$^yA7yxwIaZtiN{Y*=2hH&2S~^_N_Rj)Onpe)8hZu;l zUt4qzl8(4(emd2H#p2#dc^+WOVn&G=Nj;4id{@UhE^{SOx9xrgSYbuw4+x$fMr~P8G&p-MsRgzVwoU9K@I_I{O#vv2RfR?;#!&)3qC-KL z;IhDKbYgQCLb?`${h2|nja3~+h`)esdob4&+eTTg1IAo7CB-5(IHkh%gsMF#YDngg zfH0<75gQ4VEvktS@max;h=LpQg{xAX#f7a(N7Te=%->3b1;gq+*p+Dm`)rj^@c6V>_ zu^K4$Ew(U3BJ3L;jcsHX>JW9HF491#Dc5nb)F=Dek;m{eX@-BFQOD1Sp8sz-XG-lu|3F6irJr+e9| zU>whEC@TTwhGSZXIT!zcWgvTrMMj$2>2i4G^>BUpN7?9-x9s1(+C_G1{-jHiEHIU0 z;8a&H$zDvX_`W9aZ(MDmqsH1Hxx&GGlsw^O zVVbKHDrWq zBve`ACd-QxNia8}q_c6<^g(x!XeB#3EbpLHjzLIFfkCL7)k=d9UM%sGR);8r87#t^ zkPQ!)sc>^byCsMXkP!fz%~-=CKj;4z47@NDIC@x(IU?kCK-M@?H|sK9f`b%Tu)i}} z>_hv-6s&R!bwm2xi7C-6WHUZo{Z7e?gn<8~cxdm6rbUXv_9v%}^tG9>pvzY*nT5N~ ze9O{X7j4i`DZ70SzAe4ntUjsAcgGnaQJrF}FKlBZ5S7kA)asVCu8|4ELo1%bOLRtZtM_R398>;WB^T8@~DY@Ho7e*?Yt#iS<-wFUarR!(&ddg|5IYs!RQztz> zCo*Y(Jnck9+`#Wfium9n3f<#**`f$0i+Y_2a(w;jc;O-z9P7s%m2w;fXqfo_BOZh@ z_b%Bd z9kbSke(e1H&<18VT3EglGHb1eqfbKU$1|pmvDoOA`0G5!=$<#PQl10o55V4((>Y{w zCyU;FcNcF=2z;9N*AqDT_UdUr&D*(2>w2@jHg=fitvNSI_8^p@(2Xys>zzn8aSe9+rnK+281)J$g4ETW~K*1BG< zeMo$#Sj!RGmm`fnIWj2om2;1qR}@WMz{?t~LX9`|4cBpC1YCu3d`cBUB+igs1mB079V5T@*676k2iiM&&2_ zs_Qw2$HDsaUTd~2nwqK|1M!aG-;%-}V)+^03P6U-tX=2^C*K5-Lg^)ZZnAv0h`&d- z)nn(EuRbBQmLSqlw1q!_%v2a&J-8?M@Y~z)x7u+ml?^G}ey2H70TZeyJ^eP|H>vkC zpm0a0B(|91oQsKc2vZLxs!+7OuZaq}-nwCs^V=O;9G<~dL-(}?Uy~=+DSFgKHzXye zU;XP7j({yoXC08VyEh~$hw#=Q8)KqyGr<83$RulPLHhGvQ0*zZBBhe2#z*s>#yR&_ zH3rd^?6Gq?z;8IO!5F~G^&TlH;?kenv3Du2?6ADiz|0~l2?kumR`qeUTZ21xr$5Dq z^oj9Bqn~jw1H!MH*<;{7OjfQG#CqGMm=qM;Cd?&sE~aG@HHGqN$+DzR!Zr~`+u?9# z%7-(p>$taLUWgm9&t)jApwv|JDA~={F1wnz8c)DUU>XIMWN`h~Ek#MWq5UvGc+K^< z{eOS7zQwRRm^KmyxIXxdWr!pqe(X5Sd)qR)7*)y@% zdzOuk7<6b0IK4+t;&}?t_svdcZC&*G=qugqEDw9OeqT`Kz}64NAI#a>eUEf-8tHx2 z-PH8fMzPI?O{ET=}St802o8xn2V=sk}JTw?#bhPgd_h3oCsIOn<{dwaSX z&)!JO4@?mReUK%_ZwC1;2IiBnN%=&wp}a zrMC+S#Gz~Hux7&PVT=0@&XZgEp1ayYh5?tHU$ZXu!x~G9kZx4kjTW6ZG#be1+?FJL z^0Z2M1sC}1t4_1?Yn?z(NpiWM@@c``+w(qpwxrd|Gbdk-OMsl&-|+^=a7*ek zIV4S<`eFNY0sj8eIlD*(s&PVJ7rn%JmG`)mPY+qT+>mSaLxO>ahy+y&V>tLx(lVcEwvjcZwU~c<9 z1cY8|tK>VvyY2fpH1{9JgUbpHdT_Kd3-Au-dLq!Rcd@R8YwkT!dKeG7ogAJuWaM1H zZ|IDlGCQ^gx??TC_8TwqG%#sN>^cop4EDkUja*xGzJ6T<(hVwwh4+kWUE-5B!9R9< z^f7Kp@f_+CxIt(KQLI%Dh%%m#DXZS)VsekRRj*c~0l~%?(LXj_aJ6W+Eo(!;8<|YD zHgO-UR5q$)O)l+^uhL#-Th*YxaK#X^K4bIJ415;PT)ACoK$#SsewBeMZKf%ZQDnv5 znpF0iqPOFF(bYHt`FC6bZA`-oUZ$dUtx_yQiWi$>gkCNBRD|J|u=+$Zg9CR_nHqp2 zrHRDC3f%eCr*WC9FmmflYWrZX>k`Jn&R=-;H8_wC!43X%cd z)fS>^>cqMpO-Qj{L%lg}1C2OGP3xtbGK%7btBn0iOS~o}8xj`nO7VSvmnP4%N?DSD zca2i94>KxS-2q$@@2Qk>Ne`J0of04>rPseEPn(TUmut~&<%;fMM$v7H@{fmMfrXKd zqFaonXlM^>6VBoEoD9c9@OysNG}#vw-MXIczHMT!xa%xQvTsh1B_}xX!E&ChgOqFc z#+~_#xEe=LiWe9VbqZ?KI`fcX5RySEI3~Y&$`W7eRUI}q`g%gz^3~1asR8EeaN!+~ zAx7a~&S@9Gsx6h{c}#}x4t4`GU#-d25MiyG#pExbJ#}Jkt0IfCv*DFidV8L5?k&B( ze_nMQo`3H=eUiQ8Xh5m|G;0&heXy(P@tB#`CdvOTT%Wu5bQ=4mXVr^gxxl^{idB6X z=rZGnxGHm*n^=y3nk4(~j^H{St+JixM|Q$9qE!`PTjhc{g+3A=n51mK!nDY=md2PW|g?_b^B?o=*w zx)(dp*|f>7=|=C)Zn7)RbU7*R6(4KY+qu$F4(KTdbyRhoQTaXPd_@e5hD2VYfo!ap z-Q?$9BY5zXhzzysfPg)1R3aY9kn>W@QU6eaR5+HJ~*?Ong0Zsfc% zXUT7a-gA%mqAqCL4#pv~cQyHV3b)$5b_mQ^k{jNB%iN5(%Gq?*vSYKh zwy5`gLyl6NTfV!?Sn9YQKc2O|7nJ;6>lxfDBP*)3Awub}d{cv4&ZgR~Cfe@3mTkYB z{qcKz@QCQJWOnMd_!ShQTYh#%;)aF#z~X-2lqW~KD{9I2b**&YtfVsD_W8P%&kb6= zIRmY1LZ8}WtrOZ|$;XFhY5!jP@!?*)7Cy`79rZn{=7SQ4B+_-x>lX-?FLUujXEOhuM(sA!K zz}eKcgKlyjc||$Dn}hp2qHaT}AF>(*=Y+@1nXAdgGXXDG23I(wJ@nHKiEXw#Gpm1I zP(Etgd)o5HPBo6>@KZSc$nlsd=g%vjT%{A;ts6jaYl0O zI#Jb7@8B4tOd%sM34tiL!AIjw5*Nj_?ymdG4au>|t^E=nTv55^4y4BPH-k^XmQ@RS z85FWP=QxsS&h`-)otj(lo~4&-zq%CD_|ow}1KANzY?bKksA=tFP$ryzPE7;=UHkId zBP~lT3T&0|roK~(TIX=d*yl5uv!-SE3C^4Cplh8cW7jZiZH?T zewQ<2pIvAXKDFVH-6z?1TAWUo!o@c>X4LqTRf^hXLZ&6UzfDm`OWmqGGDw_rsnrd0 zHpUlFe-;0o*1?oNqQ-sY;Du+1qHV3a_xs~O{1&5$cxgGQ5ipaFRi9`rAdSm~$Mxbh z1nwV?13=do-5cHyYP+=RdIBoP!+fo`B(D$EI6UCz&rI7fGv3`7m}pPlTB+&1 z4*?A|Dt>Ud3eA$7O>J%GUjBWgvmJhbL)ehq&(2XY(8RU_(Vgy|oq6NX4$e*Ni4}C2 znDtJMV#DP80daqT-v(Nz=Eej#_?9`OgwNg(UD#z(t-w6W-O$C~AP(3Nt6MxW$#aYqU_%_+{1 z08r5L_Cag(u(|A9sXms>ZTP~+Q;WaZU*;taO74_Y9x%UjyFlacUY5N_SSK;$d*^kv zq)8^ZSyy;tD4Qg$XLc(hVpf-jLq_Jp%{TYn8(#oSb^OMPX;<%K`HmT$onaj_dh)F?DMT61Rq==0&>&^`a@8{u4`+K9mZMFa@7m z{^0fG#|b7vMt*^-NA4MBAb}`v`C=Zu?LM9HTiOigCba%>q5*QC^d6^Kl(yTKdT4d? z944pru}+QIqvnYRCa&M&Y+OF8_9u)X4ZS4&4k^3t4${>91)IHTWJY?48O-!py1%9c8_h3eJP-rvGx)`hptK zhflH#w=dxEZWbaEBuCA{E-fvc){8<`8Ow@SVpI{I)~zL(TlEkK!x^!Kl$_ki$}+Bz zU=Cxs>K@vGI!WD(=!&Rce`ckkP+Wn6w}hatH% znSo#@mXja7f%@#mO2ry5Mf{=1T8vIy{;{t;BUhg|0W7>ZaL|oJa@V$DxrToHgsWkV zSEm9j+3&8hFVD}q8pH8Pe+jDX!M&$lq}R7rJ}b3H7)9{T+82NB6sn)AG02sXmiIS%DI%|PHv*6az02AB7P?v5)+gKV5c+#hJy>th| zbvJ&T;NpCj^=%$*E>@sQUR6R}-`RkWV+xx>lox~8l3Xn{^=0kH2`N#7OGQOg&z5r& zC8H6#86e#=7&a80+-3Rm4VNSLm+UgeOdFA)ozU62iC5-_B98_kGS|C3@6&Dme?O5m zTqU!T^n`_nV%yT33y`T&V)Qa-;Q}|6d*9>?Aj!=_(8DCeZ_dNEaA-xWVV9Ee6`DM4 z)>bX2xfCJlN48$f2TQ7IJ@8%XzgZt!)_US0C>@g0BTSYQv(DEqB|G$#qRa2n;3Gl7MB3e2-uSlkT1=Z*hKjZ)tRdQ(mE3)8o2pByh9w&BNbD!_ zm2`)>WDhn@ZsEc?7E#O7$(yh0aH*LeV2va9gGMZ^QnLj00SxTbU8COc{47ST1|$P0 zR&Co$_5^)fZB7i|s{DA%u_*5~=b{7+m_(htv|YxUO!$_oH~F2X^@Ukk{!jZww2Y96 zy)=jyiOZ+K1fE*`#D~e0{0(L7KaIv9vNIX6UI^(9-G;4|8hx?AI;n|dt;Xe6**_RY z*@8FDZ_3*L-;#%Zdk6PsHw>FGwFReh*?s~&KXHPodU%~6&xoa-*71{MTckFAPM!5PrM zZ`h&l2xw$LEEfteOw)flmVIF2hAm<{s0e=1j2hFSYq{D`?jpJX!Y}!8-Igkg>5Ii| zr}Vucn!g>Vn-ZXZFY>y6;r-q&sm)JRrm4P|rf;i9N$~;JP#z@XO)i&|--~mGA(5On zatp(Qt;2(}a#b0*G$V%lL{rqASAVd*EGV(U?^612s(#p-(gyiGw|wptVQDFFucG{! z-Lazy19Zw9N``BYJyS{oV?a|56WAVQY>m|?u_nz~SOBqgvSRPVjjFOB?+f7sa;|a# z-mm#aQA-hAP_H(vb%Il$@218V{ZbfG#hU6b2|c zR_=ST27h`+(w40KSHmu?=svP^Vbiu~IB_h3jf-Vdt2LVu~2YP^#N0r3Knj>CzDSQ=Tfs#RW4_`*w5 z7e*+fao)wJ*3h?ozSpK|>@q5bN8Y|W#4(5T!=g!6RK~|u_iPP8je$?QZ+2#cdA5j; z6sg2s*}V$fx#e;O_L%x##K8D8RPmtbcXapL?RoZX8H7T#rfpkAt#U2~^TdhGl1D;` zu5qtFduxX{!-gYpBsGV|pF&pDV{KO277>q6J2ISK7=QDw6#invceI-M?G_S|IYYE2 z1DzX=2(7!#R5&^u8uNQeUya(=bKkXZ$jL444?|evsxPBQ92$pUb+=tG`n1W@J=8E0 zQ&`+TZ%J#znfHct+h8)coyJ4Bu7lyHa*ENo?~JKv2kOx&5~oa?Or7OB+NV4DF4L7W zWJg5z3qx$rZ_zp|4b3TD)j_>Nzje$wvCZn+aC>aD)GyUP{jy`iCKIRo-=9p)KV{JB zxn-+!Q*BGfw62$GJb+4T%jKboTey{$xW!?^rTa^e)ECBSv-?L9#pWDkoO*W4v|dm1 zhS+xa)8ILwZ;@J4?@{~yMqxR@;Sk>88x41UXI&*Ejm@!TEsHmgidi9RRQJ0dWVxif mZ@VoQjCwcLbYrftjQ^#4bjs;vMH>J2`KQC2V?Lg|^#21IY5pDn literal 0 HcmV?d00001 diff --git a/assets/samples/exports/4.png b/assets/samples/exports/4.png new file mode 100644 index 0000000000000000000000000000000000000000..0edfac48f0f1531e5b6aa423c5c7f32debb92a3d GIT binary patch literal 65735 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∈x85m^r`(leNb!5McBcfCcCZ zn#4^C9f;8xA7xW_8~j9`%*Km_d|w(GH@Wt$(JZUUlz4&i9d&c)CsGhK$zE`XB=`O4pNLf+<-)%o=94kwZr8Af?H{hrmSs9bQ9__Cn|ux6Ya z?~lRV0oq=S&Xbbgsp(@m0WYG2h^Or>{Rkj~-EK#nB1b}6U^yPH4qm!Bj2q9Ey9I)1 zXo2p?+9-elR}JzZDQZ&fYETu|jp+2H-(1p=r4zzspa;OM8AYpZB^MPD zG{Th)4D;6aCkTvmab10vzyOy6y#QG9_6a4#A0mgWl71tQFIXad_$4Y-Qe_z4So)B; z#fb`V!Q8fNCKbXRvw{wx)j`A%gn67$js7O1NdfT$5Pa*f0gswM?s28V;gSNlh2c;s72up9BbF zrsen-^iId!3Z*=q=Y^I7cunF#t1n`PaFphK29u;L`_rnhQ(SqJ*!T^l#ox6K+yQg$Lmjlpb=^4B`&@bZ=E z+5G5M2OVTt!n|F5vZ_x`YB8YtRO;U?<|xvw9DUsUEOqg@TqaT1^6y18cr;m?Id}7R zVZNIkKtdd>(bx=>VGwchpXDSb8up>dqp`zj3p(nY-G{lK7hA;_|D3?``l2lYcoS2g zfG?4a5s>qREx(QpA-#+@YWmPd^q@BJ%o`J9K=*FEc$Q9FiQp`1e1E9TDYkje%bIw)>(35vmtbQ32Y5|TSaub0&L<+e2(&}^e zQo*<8NOnM!VfgUwA2AOrN5E)KqsOo^0|IJ6oy@-v11K8HzQja*nb=zip=H6xEwg6N zR^We>L01WU0$#k!WK2crim4G>Q+d^mB=49l_xi8gl zL7XpL?AKP89HPAIC47D^$n&MYr1f?pbOX!v!aUK=>Cr+UX(%{@Q4NRoBP(#4KM)@K z!v*%|V&Nv{e(3F^MfaF(E$D~`kw%t(%#sw7adL79yPqmJJJ@OBP|Cm6t-Bl_pV5Tw zLZB9Q1n2^!gQPR898pv7t$78l&9`H(aIv;gHt-Q+hS2*r!rCQ=yuBOM`6l=(OblpG z@oAD^FBtynyfuj5#t#ShOQE^mzP3biB)DUi3@C$i2#non@&y4(*A@u{A%p@Y1DsR_ z!undl>$zrd2nSu;c<>ym1merR$SwgxhX5sDmq-Xz3#>?r%qzSSmz(RAo=eQesK*q5 z$OBvh8i%dJT#t}%nn6hF2A6MjD)DKYN8K|yn<&r5iHs2T@H=SEv|Ti^z0zz}sAByM z(6!C%dA5ZdB$|WBlUMAVmNWNl)+Q;m{;@x7*SyTqC=|vFU0sDFCbBx%lu5v@@%S`Z zgrxgSq;l;rh;~p8 zfSil`19~wA;+eE`>xy%N=cu5eK{}kkH1s%!XU@}ZMuB6yC$UL7<@ciZlPEn`U>-i! zTuNL8<1Ip>3ZY!VMF=#iTZgGPS6J z=B@$w2}55j#5}-h@)=n<_OF@2&*%hlApj~yFi;%9y#eWsOd}9uVJM^PJo z4;T;`Rj7#(%=M6F@8)IYI58-2e9Zac;__azip!7!9{(j2($0&kw&kFx;(Yhx$IZ+r z#75t1`Cex@F8s5V@|HLTJiDhBGX#?n8%t;4JI5?nK>FIXCxw(sa;$M(+z&m|lp>?> zHKHDS<^MdCoNVtOU-{uZS4U#*q;lAMF!xPT9KV<<#J#5%TVF|il0Rs@F1{RD`QU-7?UXL8N~ zOrF5RF~CM+d<cB|#Zk&JurD$24VCI#=3R%9x<4R|O2zwgDI0PUp=$Z!HSW0+=04dR1i z>!#S*#&gk$*^CuQ$pdaE5=MYX{0p1lG0X8W9PltTlpq3xipFO1`d{Wj7Da!RB9RN( z8}H@ol_G)K6>56ImABDQ!hEW|7^xs{Q2HF!2cs~LD8`fN*jIYJd#t1;qY-r(t%=8XuSI;HD zqS2%k#|-K5E7?#TA6g?YsgyV%!4qyA@&c-~wwC+K*?`b+&R||xcVr1T~-xBR!9J1a|d*8n$$w zKelemmBwB0V0507A;)OA#oo^jV#of#A{lR!bb}*Yv;YoA3&p0&24F7{7)DMkKBg8I z)a)HQ1pCuqLdFooQT9nfYAkI%U;}u5g2zE%Nwlt0$G(y;69|>yO_-6?dP1&6Hwvs# zKtj=TW=KamSqJ|EaFn(b>*q8%5ip;cgGdg;a7CBO13 zs7xAl9vGF}O@{z~FbAp~^ze1JEjdB8=iw3QC=u8T?aA5TIix&^P^($oY4u@xH)B1w zEpjkLxCT_(L6jVBd?_<~-JM+;NpCJ05zoOQmiwCPkqg|c4>5lv!lJ*x1z1oJP3H_vnwfX_)AVw9*CYcC?KCLXCL-+&u z6ua*MH-SlrE$}&1uZqyR4665k@mf2imt(FRZO6KJ4wLxXT%d$y&K0A^p&bPj*oPHD zy*JmiMHXrjuRv44Ic5_}t+$s>Q4ubMnit|b4>akg1f+>mrY-YeR?t+Hpx(IOk1yn^ z{Cm+#P{INmUA*Ep3S}5Qi=f>xC}AuLFt$?wqwBxF_4~=NwbhT1nFTRb0-e`tD}kCl z2+fhq_Jf=AifIHvx&x}5QppD-4X=Yl>+6L)Wit&pm@p9Xu=L&=7%7a#G43W)R{v49B!0NgFMjWnjpY-8cG1`z!K=311$^1dCTAs zdVjuw%_cp$-jUl*YPWhPwip>JBu6JnC$)S(DTFg6P1TeD4PUl9zPv@Y{ly^C@*mGN)S2KkI9edIM6P-k%P<=g!65=+2H1dCEH z+WAt0j$u8fXP3B2;Vuz6GHPMSWCZ>!;ID6}rhXQsg=4YX|WR~Lv<6ZR_NQ($^I(ihZv z`P`mo3aKO;G*v6VAgK*)36ayz6bxiG;oc5N6WM4S?+#U(6ups;KO1bVK6&+1Bzsdp zEG@NO28$%oJ}@322lyID4C99%O$q+CpSnKK$9Q`Li?LDnq%)oX4vofjr|s5Dpo8f* z#$`{yWugouLBn!4;oL*c9%ARPfjE+Uazy#3g0fi7Gv!DX6z{GL)km zl%tUmxj(R}Y)js6(BRhKv|T3`>ahY_I?5RIm;WgDrkJA#Oos@uBmx>1b$$nEI^+tN z(^IApL_k6cIqCcPL&V8n1YIBsl+VwPyMC-1Tz1q|T?w@8+ib-4rH-)Pz_etNpc={H zYWvBu=S!^MI$Z_34IYQwdATZnpZUbQe%PEvsF?xT$s3W+6^Hn#!ErV0^rnFU=|^U# z>41lw9i(>gINE>m`lw>pCl&;)h-?Fvyux&>Bn04$FtiIc0G$s@oE*Z)(&Wf_a5`^QiWKNhzx!#r(ues^Ntv_X2EB4gtGYN!<5x?O_8k}p z{{|VoNWKzKTo(n*Kw>bsI~6zD)pW|r2BZhQh01*ch07M2E0T$lQNUoisU9O6B?yZ= z>Ii4678SCY&~?)5g$FFz2*@jF%SEnB6yC6Gp+VwPDgef~g};5a6saf?)kKrGrL&M( zGdGvgROKTd>wSgvr*!#xM^imYmWjgr5%QTt2@|v&i8en)^~o^LS=K1gulW1WIDYL) z9A*BccZ=$hndzeb(9(Gw**4J|*v>!Uc z2Fp>;TXlTMssWFbp?KUFd?=G~i&;@KTp94@pf8J>;cVRc)f7q=M;}z{v7caz@IkYd zpYL%<5vs3pgeT|)5{*qf-$`H?(Kf+4iR`8;+JuWhW7t&y=FvD8W}F-X=KJ5hO->F1 z>V;F3L>a26TcgK06HFA00#MK1=+sAo$bZPx4^Y}50TMX+Y&o=lNO4gSG8$Ny32_Y5 zHZxbWE_3+=nTR@YQD86eP1F;RZbP+q#M=0ur>O|>p-bA|7aKr?>YkYV$VE;}%n{j{5KEDp}?%Lk8s8WQwNEjf}APrFT zQ?;7?#~(v43NjYhRJwaj9Ae(*N?f%ppc1VJ0ZyR`AlJnx8E}u5Xmgt;F@{6&I%0Nf zNFBQ2V^VSoCj4(bMoLK4JxT5YMyiYP1fBreEK11IxM=0z$a2&Yb(ikIcfs6}$&sN0OQT8VkE!)c&jKky$iZmHE?y?^DX@qlKp&JjtA$K8{M(?P9tcnk64xN8 ztbn35c@Q~(MMNk5dW;(>pD~V6OxqLw4CZHPes{;5yxKpq{87`nE%!zKu|eCdarDZ; z8EYG`E94v9Wb!eEX+f6e+`y$E_oDykj66B;2rk3d8&W{Ma1i`}BA5|sk&2^6hC%;Q zNxdf-r{Hl=;!p_{&~=b$01e<}P5BtAVUH<5X%Wo!A8(2~T`m+ScGc}pc78Z>*=V?B z*EV<4Scp`2#^u2G2j=e6UiOpp#<fmQP_&W2C!COG78U(Be#caX{N8@S^z?lbw#nqse&DROrXsX8n zN)nj8u9QMR4hJ@J)zze12YEK)uxkOji8ar!L^=f=4?qj>UOp0SXn{BD|MrStcyPK) z!MCz9kqWon8jTg1ZaF!G1I4Z*&4SQ!vvy}>k>@9QqDU1v67B29O(9cu+R7KkSQn|q zkWZ5@vP?!1>y5%q55_NLGsaYDF&CgSM-#g>la$amAYS9YEJE9GtU=l8wmPr{)qK#a z5JHI+{%xUXPmZe3|Ib%(BqUF=tWoxIhqU74?>_Mk7&~Ozz#sZ2v3*f|n>Ak>$sSS?jj$mAAcix`t#`cW1Y#~BWFR6` zH6YA5P~ZWx;^9ah=ZWp()rBAsr5KFgSACqeBJ_rnp{{vF%lDWYl=rbenp}#ko6oP3 zuDD%Y>YTYlY+M74IDQ{$N4;QeL;FzFxEfFsr(x0!!_{y$V)UMds}@rTB>`T!0lONw zZ{TK0WYimnUQlfK)87VKU}_K!?*iBdnr3tbv9vE~2WzacS2-Z+aU0Xr4!4CPg7lnT z0z8fbmhd^M?NY3cgqkWQP(prOa-EILN7jD6Sn&Lg3ywe6tZ(`Ufo8 z62Rw}H5;3JqRJLoO`OMyxaC|afZtiIkSK6bWp5-w;>A$C^DoWo@pS0H&X-#wUmjmT zK?GE%>aT=hf%@DqmFNG!whfHq6?@&cKWR4jp6WOssOL@}GrTVD_JXHYNDc>ZSh^yHYN(J6^uCQG4k+=^` z7V-C`u(iUAP?XP;-`b0dut$}DTM#+EJbx;qic~HZIkGjE=8R#)j3Rlu;kjg_;x=??sX^6RHwF^Z&n)et1b+${GI%#=6_G*Lv1 z26kKMj7=KaG^;roDB=Fe&~aW7bSTjRFD^~O3K%{Jj1hG2c$7Dr)qQ79hHv0f@(u*! z$B=^nb|d&BZjqER6lC9S3d%%C;*yeYp>pn*LIrRwr5v47%}gtx3Z`16N!wWCS;%~qjxo-&#pliayz=u1;mv7_Z zPWY{(S?z3;`e@&9!c7#)_GDI!fCw+5xVWhuK?%vzRF~=prNvL7Uiqg6s}+D)4W(1H z=t@pHJh8^@qmkkGz*bRS4f;0aHYKE`E!k)rrl}Pk4#A9ExzQF{jV3-WVM>55mxyis zXf`F=5}&lUG;xHGfV`DzJ8$o(+u74+5U54dv;f`E0l1{AZn@zEO@s?Uev*nnl2F6N z`zmQtTb&2MoNMA_`}t*dcFxT-0IUpAz-##}-BAkcdC1vqC3>EFp4U}puXG*b&99w3 zs&78e69sX?kqJj89RwI1XyBDt!$A>J2MC;%(4lKK2Q816f-&vE;DGCZ_~|?ckvNRA z@f1zRUR!Vmf_z#sI$>!tq=U9>R9}qriFc7I0Cp%PQjnqi_^YPB>>N%?NX|GA7!JW5 z(V(Sg0H-%Ski*+?=hzFY5yIC1Nl|NqcR7HUe#SBp5yC`29^kZuaVG{q^kya6?2RX% zCF_wjit6rwRB*|#4)$QaNa5RL6(8&YWY?ic(EW<@s|9!SP%MpYsGZFn|LrrpK|wCf z`J!!U4|jYZ1@t>fB5E5}uAiBo zwvLn#utokY5z1lNN9;8Z_6B|niKhHjC=vPj4OpL;*B)8}t7#|&ON`{V+9f=j8YO?w zm#7sb6?%ZfExr2|`Cd>dM2!(Y?(KP(Mkfd`g9Cri!)@R68HJk%O*1;$prZmQ4D37V za00Ow;vzRTire<aL6b*Ss{E8WuR_}z` zz>-(t+)osz^*|laRs&3c*aQ;ua0ku?n>5X^%dA#`Iih#)Ml~EXNNQBKlO^{oI}(bF zVd&;9;F`nlsXKq8FnZ6y-swK>tH&bJgMXu$mI&cQP*zZ=*2+IC|2W80NlgIfz_h_6 zCvbBD`gKQW0@qBHQ0_?kd<#@CH^aed><4tO*y9v%pxl=+-f9KvC!3Ip6|Id7K8U|f zxb0#D+{4^}S(OD0nFdw6v~u^*1E?dvFk{pn<(rG9YUORj4_0x@8KyQM&@z9o=bElA zLfp$o&{PU=wBpjAr!5Zfs89C87En_To$=-ahnXsJ4>Z*>gx~a`k?g~8obQcem6fFV zQS($(BqCe+Ork=S@6=!@8Pmg3H8t^NOeI{)<&JgnhAB}~*4+O7cC~n%a3HLSyD zYT|JBXe9Vh1tgXduGP<>PdZyEcYP6??rbc_UK{v& z^X*wwTOKjAIEKn%+pu{N3(gJ)ML{-{S)y8HG7^sngarhpDnA9N|Bd%gt9|pWBeayg zA}qu0UoCWh#J_FUrH?kaHV;A?VkIp6p-fGmxG3Z>Yf8q_pXuM2oghN~^!uj|T24sZ ziSA4(s7(U2zZGAwv@Olb2&3Q(N{U5biL)LsAsa8v#P zB$ih46H-nW{VsUkN*UB@b|-tEJ}UthJgOWpae(_WGiS(=8p$Or8I2bS`lxO=zhih=oV$zU#3H z_!yL{hFV*4e|k{&$)X`&epnvc;VMD4O>V~(uWYI+`a>xSO7DBoI*fk-M=NHtd;cuv9J&CZJ|yAc z@&+1_E{YehN-ELsHx^y-g34g;d_a`$+<*-QNH8zSn!b?{$@8 zLZ18ZJ$$~$`_8UEE?GG7$*E6r95?aZ-@W}Fez)W2z!T%}|GM6>w>XDMi{E|w*Z(bb zXe)9$`qBpnN;-xl`n{LS(xVrJp4eP{#`@p-J&FUr&s4lV=LLP=www*I-z52Lyp^ff zdzL#5+zGKbxkyZ$v@a!Q_7b7CUR5LMaZFnH+N9(IqNZPaom8Ew>x=21qi<+mcjYbN z7N^u{6BNpH|3(k)#C-8b<$K4f)i;z;E?nv~G2ZxGr&AB!cgxMqb1u4CShhQ=vv-oZ z?VdV!ckx#*<56Mf(P>hd-Y0Imxnkv*y5|LFx6=@91z9fMqQEHW=_dPIm@gsBGkWA( z#{vqEq}RqebAq_`#i9q#dl?5rmggi6k>!UbZwj9wl_>`I5qPWOZ_cbG2hVN^k;Q5h#YC6f?|JB z{V^_06t&0fDxCRT>8{D8Irs9uKO#|%T_qNuw}7RZn5qxvd9{F8xkh~!w<+8sSBu$v z3=6Kdl%y3L-_v*zFU!lvntVio(YlpkcR+_qmiEXiqnGR;y}TnFl(oJs*rL5N0sER8wuHkrJ_IG4NX8qzqxiMi7EIEW zr=NedSQtOqJ=xGM2$24YvrSkM)o`(6bN`8GT}_z7ZB0;QAs&;|ZauKEBJHT*SCZO< zDT$-WhAl>=L8!k|sp>{7Is9z>)NK;eeCr=vwwZd(rT$|Rr)By$C2}uKF+OL?GdviJ z`M#NU!hyB{5;>p6Ta%LC*K8@C+qJT}eckwv3R)TGFhx{+YQgab!3$PRU&!c2JFoxz zA>MmD(09;=-1iwG8@Gl@?`KH3$j*zi72|z7)=OfC>OM`ciFFnvkY1hl5*O~yiwnA) zfALa{FKGPtw^xUTR?JNg=zP<3B#$eCz-Q?^zB@Hrcld^T%u%Rv-S&O^-cOsKK!AYt zYsOY6@-82`;m&z42#jj!8V~7)kceHpuC=%89&|H^5^&LrP7hxU`s+OkLHI+HVR{$rQO)!kip2|J)!3TcOU zSyGaQ{e`JlHkI8Yz+oJK902?#K)LV^KHbjKXz={=0eRh%g#C4?(%U;CT4VwF-P?r! z`p=YCD?14ujI2i=>d_|t`c#SBsoQX&!zEV zhpXOnb47%1eNOH9x7^|TY)i&ek+4%6v^nbZ0j%>3AkNVT>Bj zdqi(JJ*Mt_j;6>c)~a?-cb(}VZJ+7YJ}_N4b3T~I2@0CW!NvgSY3rB>B3KVelZHbo z2K7+^t0Ar=D8e2Pm);D|ZwqHMgN(Kh3=~gRlmO25?j4J@pC3Jo#zU{~xVgfxDsJQC z#D%^CzZUsp0L8XeSB+R3V`Eo?3ZTRm18F7U6B8b`ZkA-JW`~7_o~L;qIRFj z19)ehI#oxcgUywE_7y~x5w{w8O-5x?#Ae6#eu zuRoaxf^j5=(CRz4mq(W0o6Kn>U_LnJP-I;mvw2a#f1u72Mc992;fjd735m|yXeW-S zLu?aukzI7wjw#|7Y|~AwK`*flyKvzmn@WND4^+FYJhLsqx-B9SkS!Xk27Wjuk_?X2 z;s$U_rNu(XlF%^LEk2eU5Z;l*b73UKhPU?cY8`na_(}QR`OrwK08E=Ufo*LhzhI@{XE~CfaP)76 zs#Dl{ZItICficVkGiQSr4@btfk!s65N(o-vuUMfJ>(>})o?Ko=Y&PRa-eoJkGXa1_ zxAFl*Ai1!DAY0SJoWJ;xr1Gq>j!Ylk5@on7BJpsH+;Z9~AJTB!FhP>?S5M@(yg^tY zhV3HJf40as7u zXIqKOEYA}~*RMa52*W_S24`OX0tCcnPjuTrf08M(zke4L>`L% zX-aNhDFGk3yO2OKN+cK`ibE@Sg{pIS!fD)7)2Gh_kUE|O^tG@1*a7c6`?n{+;h(pz z{t%X9LSEdnvsM)atzH!x>X1l(KKL4(2ypy1fGG0xMS8DCFe#?&D_3y z(23t1f`=#R9dB<^U_zVv>z@>V^$Qv*aa2iSJVwUPa}nM+#`lNPms z-bz%h89jH~+;k~c?of9nAa8G+-Y1#J%<}~c9b@CmqnrvtbV0&NKd}7as(Z2f+_dLG zjh0W~i`Yo`W!i7jxQ`s@{$2jI*szc}{2@XL>Zcuc~P4YiEX0Lvnqp$nB z;Os7PADCT|!--l#x+23+W9s185uPmwJavkxs0Et$L=nJC`Xi}am3uC4uV3(>=VrM{jm?65mZY(X4pnJ<{aH4`-$0NRy zrwIp`rRsyh+e!`}hi6HRETj()ubOD~=w>vTl^1R(q7Zc_TqC`6Dx&pab74!4(2i;G z#m%4dWaR3|xcV}xk~y<3{?Jl#q&bFJ>(#k%^Y6Ywz814K1MgI%Enx2M$Ti#jZIcf< zg+xa3YH2035HkBwg&?CNO=D$c`K6C&$L#Hsr)E3XJ?PuL$zuxb%j`?;%1HKy=UY4g zj5M=jBJrb#UkFhWGbUYq85@M}=kU;e2QFzv`w$}f}MfdU3utu~^7mp+PSm+NClVeJ|NQmqpE%dV`@&aHC|5)jrhfI+F9c`%VqvUAIry|D%9Nmq z)5Z|5Jv$C283#16<{EC3M+;Ge9~AtCkO})vu8_(=k#NLu5Z;*f@+$t*h&q5b#=6u@ zU0;k<2d?x~zLMD$?O8D)nqOzbuf0Oluur;euwCxH-SapakgS(ZS6OXn`QN$kMn&%y zPPoO`y(zpb#Ld;wc?i)NP=%xU6g7jD@$hW5e+==CEgUaJ5C)uhQbYk zoy&KOd8D<-iELHRM@|GGH1b7XFEUT}KeJf-XQT))6sfwaFeCS5Ug_ehkVV=*>vLO! zIf|H&ba;)jL#eyxdj-pPLN*XtvQgmYC&xA1cy{M!Nt$S_p`7tWO^hNyL#ILrUZqk{a;=AOTW7 zHTg~@QEO-~%uCnr3TXVMHM5?;uRE5AU|V^sA`21;=c-k;WxW#1ggojc($ftm;wrvV z9TYcqhatB#`u*t6+mk#yZYPPQ(u*Mj<&6#`YXo_pMIFwqKRf3M$~!=RNP7`X2u&B$ zXFv6#Kz_M=di9-#+AJ63a1ht?TJPZ%B-!~tMdjt0&d5@I@=ODwrLjC?N3GL7>v;=> znYr$Mdsjajb9tuMtX7}VVltuVMPck5cs(%LybOs6|WWWVl@0ihJTI^R_etXG!L*&IHD*NjGQxGTEeig|*YTYvGq zN1JQpdP8EU&x+~VJ1yIZC1>ZPtDxMumWnv^2*}L z4L{U65Jt>vp$AnM-diF|iAp2UgSaWG$x=cDIZ_ziHkctKeIDrbVr(H2=ry@?oAfBS zX;S#AS4xzB5r^(*&GaolHn}t={5L^A`qW|k(rstF3$n^F877~-Z!$Kt&#=j;`D^ZJ z2||}oP8?@*m-j0c#W@F^J6&4YG7etU?!G{LuAINLlf{On+$BK2n}J(Hl;R{E+pLu6IPJmixh*Z{hA4Y`&u zk{rQ~CmET}Ks6u4b| zyJ6U;(4+hV;3Cu;ISk*%NvMnX#2_o)M6NF!1FD)h+GLJKu_}^nB$jGq!bU0!u8f#v z_-|OjbdMCcz?cP60dJD|;a1ld9vhYgoacR4kc(C#yh}@XcunK~-L^CaxbrkCTuw*} zKm{Hdv;m@dBYhtUCR}8;N^(J=2LxUG|y!MXvu+0*M7GF7QJOAXf$Tv?X?Aqd-7E;E^8Ss-t0vJw#pjqVVi#ua)^Y)k#FokDv1SAuHQQ0(~0o1ArBzVh;7jW6-TtqUB?

cc+kWwN6fKL{vabgXl@^yC#QSt+pau|&{H{9QDMf9iO1s>^1nufF-4#W!2_sN@@(jy z*;aMJyI(bvXsp>YyX09ha&F)i-h^Zza$=u!@obCg_(52jyxA!dzu9~6UPurKrh+{1 zVCWvodGnDDo`(ElijsqfO2CpO$^}U5OsCv3d)QPBPV?GFD{XK6Q6W zPcEp(9_ML~NO)3Fee^DxrmP-WF{}*|36-WLhazSquEKwKn-!=MylWD%`^0-KUGY>jqG6k-;L0!5Q-8eVP*LE)x=co*4&$b9p#I$~}Dp@y%0 z_qkP%tHbXRiyXC{$B~*RYntEIk@PR&HqAg<%VrRWt`qW7DEjXRt)A{*P!5HIg-v4g z83vYhs)k6FZI$DR{UdlfYN7=>ajO*fG<_>M;uQ7+iP(FIK5p^>I-57oXdxiR2n5uH zBt<-EFa3Qx6n=aW8VX*dBnG{@VngMixR#$YU7D=}nrI9dUoYvu8Ab2{dc!9rg{RRR zhm~2wNmgLb}UTmz*vOV<;LNsPo{njq0=p%*P8} zn)wJ;Z)MYNVk*I)ZB4Wsn)J~<^7u@j+h+FVG||Sb8Uq%7J$me$uQJ=ik+057%_Gaf z@`r^|FM%E4$PnOh{Kd*&BCbm!krex0htwODq$(`5AQ_K?+9lJg>-+kW+(lo;sTH~(=cG$dE%e``(_w&mMpS+b z6$bETF%UmScwVE>8jh&$El?-{JJRoOgge*O3-S+<102qp7Jzr|``RLlyTiPrHX#c# zKA_+ii3|N3&Y$}w(!K&fL3)6YWJ%<2eGSg#Xtubj)s*VZc=_uw$GnkR0}V8+vitn^rhTyIvHQO^D_nkHWKvFpb<@%_S$}A4qW#tb%>yNX}eFnq*@# z=7!Wb!1r~C#0T`I6uDWt&9lw;x@X@y;v9s6=`)3yc$`$XI!!7$+iYbp8X;wvC~nqSN? zngyO91Txi16zSS+?gCZwZz()wAVkBGZZI)rKxOj5$9eqALY!?=Z5dVzje&^sP{Q;@ zr3E$*+|v4OM~3D_1{Xes6Brg>nw|)lCD}(JL_+~6nkh3+PQpRS z>XaMq$)qR@QJC;COyOCKeUDf&hKF-Rpd*v_`&exBTN@s#T*Qj+N_NsBZ1 zsGWS_2RTAMqIkD8j8|GafAH8}@D_*-LO*^J#4h~>_`FOfIFc{I2L_ad5vqQuGXVskG6m2HTp53OTiqt%By?qJ{&! z!`6&%(tZX(uO-4TRnRG35FWQKMKw0XX=J(@=B!2!+@8cfW?JE~ENuZ3Pjef&9eTgK zl%9j#z6j{8?>jFb6FxKLwIxU3g{`S@qSdnvqxb}i!>_-2;Nz9QA5WPX^epUUR`v0V z>mpl|kyCR8Z4aLXKDql6X^~MwBv_>ia)>knSLju<45VGkILNl?7->EtabmG*M=0_m z*pDVc6%=)!Dfei)WAOk2=tT_CalU+Y%2M~_te_Lic~xLLYL33NW;TfSG|xf&8#_^L zM$o$4V;MP2qMX1TUm=W2jX1ZDN_=7;C>e)OyD$$SMf%{y4?LEMn(yUMTgQa&f=+N4 zU*r#&0c$yI3_7nngTHBg_3u(f&bSx#J>c$USZNTDF^m=&UKK3BXH>#!j;U*zmf1)`sN2S)CjRWnq#aq-h1er(Ttp~}r!F6Y z_OJvPMh3`&zHpFr8fY{AS{SF4g#w3)mA9K^00(DM#Idy4W|_|8fn#KUQxsVRpa7al zp`UPUxwO2Kz|j4$9>Bfk=<;LxOW^^~D>zN=$xZ}RgBM<2azs=@+0`3RS}5*rYAPWF zCxgP$jX(en6aPgOl(oFf8y11gif0fsJ_^&)pCJ5;Pz2qBQM2OKE6E0MYzVjN7R|>i z4_uwQ`x5<8%+EMw_j7CyutVzr30+qjX|2$ymYY{XN%DZ=)V9OAp*~#^KBkTz1X>;% zieeUC0aHbjieQFjq-?Zp0I%Tj#!OG7`GFNK)Z!zIzPgvE1jQ$7DuDET6H>glc0LPU zaiAUGgOLD)f}7+muYZPLt5Z8cYGt*)fjYF_3RiswYh!fr0LO_2^eDvPgBfetlt^;9 zkft0kAF)#XPX1{%NIE%@3>ORifa@?P;N4H`X7thm3fq>Toy&u@Ks6nhMvG(a7bMrl z(KWLhK|Hdsg^{~1ttqiF8_SHk-!vOEs?dL(ppaElh>jr;x{*=G9zn{-Jj$lvMr?0B zPp601Vw?XFiNY4IHXmN1dWqPq`Cu78K`l`${%4rL)o;jRiD1i3z}&F_Pms ziK-v+sE$xlS_!(Q0hZXt+5|PEnhG!q$|<@e@*9qkDLT8V9Z>62KrE3(yG( zZ0bF=SyA04shv>7(_G}w^WTBCg(ZN*Xn|V^lA%R8CtEdN%7cp27 zUKcq{d}B6)@JC2N#Dw*^lpVID1Fd$eXko5QfW{~Ce1ltBFu~k%2+GfcZ*%n6B5*q9 zXw4$?K)2R+I}#15z7q7^;$4=br(G>C<4Ac(u+S=^F+jP23Y%uE!yb;L5&U>ztLZ2=9`EME>}{Cm&f$@aQKf#Y$U%rg>B5aFE@LAT@-< zTd)P*&cds6GZvG$k?aykcD||ee1I52Y$XF*<6yr*Q3SmS?tfXhc;iIkuJKI>xy@rE zNpBQg8%CY0%}?4tMED*$n+%=ZB*5|diAAaZI@pz|tV0L5mF3hBuC_Cy_Hc^q zUP{Yff?K{Ow~N;Ssw);6?GPM_G%54SY(%hf+WG+G7fcgVuczHIb}TVBt?=a4>o&Wu(%Lph^9P==Lc7U_*u-3T7-Ope))-*-?6z-i z*pgF^TO|RR%|4PdOZ=kwO4gLDnXTiMe^?SQ#l!0+F&*|}Kw{X;Qb;T$Wo_KX{a@KE z2_u=qe|;SZmi|LK_*G#?LYNvyTb7D?{v>Etfkiqxvru3l9KZcmcuOC-yk9j>Wfobd zPS6$71{?x_g+)F`0jB))G`{JGuNs_z zSL*wP?hJWdI0S>p=+&2{|F@7})DqGEqHlswKtlJ1=Qn=qg*rB*mYR>y{4D8RrjkUUb?QRAIOm|_IY$RY{s+W*aI6fD(RQSg<4Fglc zf#!ADEjM?OQw@6o7sU*l(ZXzoBWV-0Ep=dvbPC}zfp13Trm`>y8C$r~#WU*uMM7N~ zY2Xrk{3t>sK5}Syndb`;A+3<@op6f&`#L!s=?YX-1Lc>Wcwb|H z*ugN9$G0dbSBmgtT+zsZ=Y$vTh9gN~5?TSbv#1l!&C9}d@H;3(W*&QV_L|vBGW~2^ z4g=3<5mT5T_IZd46!58YEgr0D^lL9|5rqPizjP*+fqg+gR#OHKU4i4s5$XGYjTC&4 zr{`EiCj8js5g@@?(75 z_mzMDWX6bFvE^~+)aH((&i;QL`dwzumD_!{tU(z=xC#?QTeJ05)WbfENNb=ojFF(1lmFTsSc)kl@Z|v8tGoHi<*~ zQJ@zV0l=oz12~N)k`@Zt`LPMItTVCaICA$?frM+|wDpx$k{|gKDJ~r&1?Is6>MbVz zHYLgb>h9Mu{#?t(LJ!7T`56Y+&*k_X3Dfj%VZNV9W-yT>%4wnq^tJ%>U^x~M5I&Vi zPH0dDuZPp=6)N=yPYHiZm|%mMX^G@`hiPOkB(jtQ0I*rD2b7ZqRTF^EIJ!vc0NSln zAwGfTFoN^4!LOTm0YSkFl3*B02O=Q&0DQOZ99|$W4JZ=|zLFMEW9dXIK9Mb4AE6BO zsU{;$K^|a(EFC2xtj{^sVRw)q9^#zo6%YXK68v7M2e0`5Y0)F3#HP(QY~-v#IBy@kV2>yYF5)qlkkwF=a2heQy+(t~5m#;yf-qJ@hL6 zMHQHJP@Q{kC!97S=Eu8{n7G%!k>D#8_a}Bt#*~vOejhoxSZUcitB|I5Ae7M~)UKO6O)mg&jX5;Ny2- zg=v3@W~(QJf`J9UZ2&rP*l0utB)3Wup``wG!WUHyxfYE*c?g~Vd9E?9z!Vk|SN`g} zDHCW_h~P4_ud?z9q?Vf|rmZ1ZDNSiTH#tm~f^G0rx3ewZ3dhOdsYq9gf$ zR8`RJ3Q&F7Ju4cAL2fUfvHV0O$Y@&=hzF?>SNWP8A|KqIXWM?$uFyX$4ISS9?8TE& zq#O&)JB;-*vSFu4;#}YQWz+`l=85P+!it=l7%!3#1O{lR9o}bU>vqbo|ImWS;a6Pg zzRiqK{9@5ASUdQ9<4xiV6%hb|}ap!zG@2pPqvhfct9>IW7-zAFM4ybR4fmcXhnc_&5!NV46 zm`4{qvWEK^qU56J1B>Qx@}QbG(fBkY3I{ic#sX#FO9}4+nz^^f0IR}T6FiBu1pqRp z2<{Q@Z!J-HmpJ)CCP~VTM^iJ?4?J14*DI))k#B;F$vb9^GnrXfrsXr%;-Eb#O>XIx z$v)h`bvMha{^mLU<&%}YW0+S?-qk<=v*E)|71{9b4ysjXYDC%?Tj+Qbi$rMyQb0|n z4$^DoRP>l<%EL!oJoEtUN!*Ctk{blhdC_qNL~kE>RFT0!YLhl|(Sl9$o+i?c+ed8A z`XSoM_{6`}J(r`MSVSi(C^e@gR9jxA`r==go9`WJng>uo6T~hst(dWvIUe*dkivoFw0!_Ok{NSkDfUcFX5WuiFUol<5{U!LB~Z!l)RD~``p&1t$cVAgs&REC(@xa)VMIlRg@hbtUQzup z$=HT?ongeFB6n9pX?K;P1&SbgczWkIO=)=_l1xJeAk$dVQ;D`QQ0kgX!ioGBMzmUW z+&%%-q0=}Hi9Uw20;23V`y+Y@&=`-w!ostN;$QHB?$A!OLVRTW+_UF*WCMoPhfT{b zg4l=$um(IWbPsqymo3mr>|zbsy#y^trG7vn!sumkjQ$V~^0rB$-TFRrs}Ga6q%*6^ z+-l}#Pn4N*Wc#(2Hf__Nl4IXUj_vv?#$b{KK(5CXjnp#Y8~6$ji7vHpB2dDz45Do}{$OYl*D)RJB#6kz#BYVtb%tb6k}jC~g4I8=q6RkyN1L9nM!hdXad&Cp6)X-#XkE z&(MjUS(6>;G)t*wTHi(@fzF$9wCCdp`nv>8Vuqg*6Q&;M4jGyl((`pl8D&h!5~nb1 zUWVLj|6-24F(QQ$!!juMj@0hrk17*Pl7f?|q8`9Ceol2eaUe%U?7Ow0+_EGMNa)wN zo!oKFw$d89RfF0Ayg{INej&8@5gVrS0&tcD=v!hUtf*#W%&08W5f_G^v2B=`i3X~0 zx|{>1m7F2cyQ@J0^AVY!@F*agFjv%mTa&xg?L#SVzpYl%|$L>1u zzGBD44cTk`l&H+Vo$)bw4CQNm(O~%LAx*nJ+VkD*cn6fEis6SI$k`bWelU!(5 zx=>hYbF5O_{p!cZ-&z(w{|p9@&ZUDJDvUh_tk7k|2(5%-&8RLhS!dgogm zPM5vT8czZzup|XMr5!uo`sNr5et$y-2ag8W zo4qzWaE?;V+8A=mJ`CHq|8I3@lbe`G;r7wy4SN&&;(wd*<@&=EF3=q!Xvr|0%*uaf z*=t!Js3}s1v+L}fgk|;!_WdiHEsdY$#?60a|07Qw{JNU_TT;{#khbB{BCCY(t_y*{ ziOQgJ(p|iuA;0uTsiA2>-Z!8 z#DIWd1xUx|EN3en+R4$j9#=ssq`=VE=s)<_C^(yfUk1YT4`F|Ml0)QrNy`58CB`Oq zzt2WxzwDQ@&56-#=br8eMHU{NA??OEhj=vIw^@0JQPF%tG<1IBd`C=6yQ~hkqpD= zKOy-AXW&26N+s=h#vSn!a*+1Dki`T|$JLSNOHP3eh#%rSp_7)_*9vbUx4wU)^p!29 zJ1dPGIg#l01{6)KQr3@Ewd%9rribSaK85H{*MqSk##wOG0n+!M7PPQi%bLJK=syGh zK6->>f_J-~y&yN=_#AaC>U1aa)a2#kGOI`nD(&umeedJOjP3pd`Pvq`TjwFOyP?p$ zqVS4guqPtAq3K;=&&i}H{8seeOef|qligb8RQGN`{0jlHhRF;K9t+RH?td*b{@`hO zkDnB$o326|K{oV_N`I|CYn}nQn0CUy7`Ut=m;Qqc7MmEKOOCy`BSuEG&L^mg+KC`i zMh|e{Hrz;r#{AP(dOfn=T>%AO+ENBL(WGe#=pyVJZ+y|wH$cGR!n zU{qoAhQ+(6+wQ|xa7=VcVkkN7n{f;pjZ#+tq{UweJ66434hrxeF30_E2r|6IEiWC1 zYHlcxho6p_aB`9 zae7r!PJC)kBPAy0%Lc{_eaUpzVAdN}MHrs(9BlBcC>9PzPT7q!@}9w~@&lu8l;?1f zg99-hY5szuMfqh{J0rS}CW-!96@R3vc~^kc(Z9<{Tl&Ua;vxj^5cX|oxa3=MEUKmK zU5<|4a>h$=kIvI{*dNWo?Q_L30~o)6*zf1yfO_ZA72&JG;&#Ig;~wFl*?A$t zaw}H`2cKS1ow_L^;=4e&X_aLza}?t(#rwmJ@qVGqkT5q12U<8_2%Vh3X-!C>6K+SM z$o`<3G65)U(MeHq2G|eoc>qE z;1i}5Cn^c?$#VguIl!6fZPO0=vV`L$!b-gQzZ4g9Hn!5*fU*&0hAJK!LVj{1N52M zO2pf^weg@jjBazWeS)q6qaPf_#Hm7>gnroJqLHh393#jYSl4}`@(YtCQDAv+Ys2DY zuTcunAN+?&z$)lf4)!{D{^=VxIow?Iu0q)zyDDEur#F$7VVyh9f6L8O2y5Gn0UUQ-DPs#BwMGTZgj45gytap=sye$3~ zjC16Bx!vpSm@K;cyuhJunY=lr_qto((~~Cclio{_y^6d;j0_$Nd@4v2y$XjZ0oftz zz!!GQLagt}U;#PuNX$_tPPh)v0f{7bMk2^w$|EnHKmRmnLw!&K2=${PBQIj3jCMf3 z4-Zepz-Xdimp+18-Z+E%qFc`@h0?O)MW`)64oadsb5P9?Z5&JFVlhvl?lmz{5nG*) zc!W63s{|bmql-MCNLJCu`v68T2AaX)gHSXvK13s6KO8>gR78;l{oqu9nttft)-o3a z1`ZT}(Fh$h0o&=sCz&cnnduU0Pvm)X$JW(%*&qiHvSf2eBF><+n@ ze*T#(#+eb^5fB5gS^_|1?yUnl)bWhw;e{A&=LRe!oLgw#o08g`jY9gMX+>EW07^l( zz2VA9fCW)293JAYjB0i=MSBU#ymZq2s(c7Gk%~Z z`KaGc%kgZRqwLlgpj8x%Iv^PJ;&5TdOb*h7!I|C67Cu}08J#Fcqs=~=)%h%@+~7M) z+5G^CcH}kKa72SZL0OpZ@$RDdNA(zxE`4)kUC8W@wueJwh6#Kv$$t;bUv$TX zvBCGh4*tXxn`x?xE6|yHQw#g11sk(NQkdJLZ6MaNk`DcYcxSKo^zqRRDL6Bi)Jhnm zHpL76&uta{i0B$bRCJAJer+*&UrPbS#M1URAw4*+_1sQ}cOSI5A%eX`IA|Ho1Vwd? zNdY_Fij)rqn%r-8_bVp5kkaFjJNV-bO#}-w*o`9qnr|ze-1lup_?)XH$b8`=aA{g1 z*o0)u3bb;cht#+(mu|O0SYD4tr$$tAsJ75D2i_9-0nW(eJK^9_ z0**N$l@Uc(v0@U43|t(%%^1njyQ9(3y>B?QOo=^~;#d~}AVrU!Y~{nT2f?q4XHebE zdrQ;&B?=azl3(1H({CGN|3csU*G2cQC%5=&jlN`^{-^g!fO{*p?&7J z(A)hR15o+Iz>pC-nzp2Y_P-Gji$Jq;vhwoAf}YmS!7=rAD)iVb}# zbFG+9AXJ6K9j05R62`#^!u44DaeI~E(GP&>$kIYF?!KzdEd`ltph&p&tzL#{dA@@e zFjxX)q$Ii8uk)Sg6bu($&=H$<#ez>dAoEIX5RjMN4p-Q^+h`a;B^!sFi!FMUX*x&U zRXv)qcut7N7K9hvi`D1ATx{@-M3oBjm|f|!c(ivvp(XVdF|;f-pL1h97CsJ?PSlId6xz6JSze-=C99Ne-)GqLr>qVS$ zaK2JqSZc4t@P!!oI_Ep+8e}{EYo)#wO|sHt0|)4!_7}i8?g-4wi?iZAqYr9ClM-7` z_%btx9(sm$<%DV2$np$llqZlB5f?JD!9YQ`Ko!UU{>*vHaAi^rEE$f6`J!`vt0w+N zH;k4;BqlPg$f)F*_$WVMU$C%9Ga?PT_yxz1qHuc4>EVU)iivG;7zkw-SUKVcmT|VR zc6ZAms1*5Pw_<^{IKU70HxJX0!DtS}A8uZa^DsJ475gSqJzO z4{a2eqW$-_ZD*t%rJ|4Q!}B5oKOc%?r?T@|3;DV7qEl@%e^^^-ve6O}k*npk0UQte zNBo0Qd1sjM583a(-wHkzZODf)nyoCyy{R$%n<*kHyRx5(Cyl5n_%Gea-3+|_qo%3v zP@vP%$_te(uc$Xyn%*AM+I<;jF>vGb>e?37;-!tw@^XdBxo(JZ;!F3 zZS)d&E`#-kA;pml*Wk8WAx9?YDp1z6EDI8sZ#~ysea_Xh`*qK&9gXhj5VU1+#YG!!>?vpFdBuch6}Z2!JaZvV@T|{>+7y?n zo40uH`VIWPRT)XRM8|VYaYfG*>O_d2*SH<#?|Ap&TN}_z0qH%cUMtE$huns_Cj&D{ zRKrl{K-ZWQlW>b}o7@P`bCKW<#TQM}*zO?j6~vXNXE1R~kOgX&m} zNhK|a0R58+7xaS$YFGN9KOsd3;ovo&VPbp7Q$9A2(CoIiR zymO)7{XcP{d%FUft{^MQ89Mw7r7Wn+umfmMj|aZrfIT-VCDTsMzv%v-l3S?!`9Ve% zLtci->S2S)RL!TL(dTtk)1WdiXXr5njj&@UYP7XNf_;l%2|hP15%2RrhYx01vDU8< z9yQ0H#cnV<7EpIIK0yZ}s1$_ZVWp@=k$iRm9lLTx8kUG8Aedz&2l|5CM#SNmhpI&r ziymU7N^4(|?W3gpHUJ=p|KIEdiuk5~e^%kWIq6Fx`@7zy1@)=gPsMNMbp#4veU<+(Ejv0vX!{uEHI;Tpl0cB3k=H^R7`gfJv*8qAQmsxb#}ImX)~taHhd5GpMOM2q%JM%8a(nRDo4E`!+p4uwpnt(=plI zo3iXvsdtQ0d0b)tYlRmB2AcwqP@}*C=A`3Io&jiyoA}Jqjm)MYgPct`bTjZ!V5oKX z>(iv|JHr3@m(G8tYo4?d6kUfnc5`X5SFrQ?Zz>_U6q$+d{ot3?w5-Q6J){g3pIC~|%Z!AG=7P$JhDquwxgmeK@pXRTsSa@^Iu24AHZL^_Fd;Y{x85zW?;PDWiZD<9#bd&}KD_z#=1J3RY6uXXx6e>F-K6CTL9w_V}Fd$NVP?-l_hq(z?etxZ^0G-}c8$ zG;<^{N5Q(H!@!;exG#~ndLiH(T+G^jDOfz$@LGW*_D}bdf^IN?GH_R=jjv@qxw8kJ z3p-1R5}YsKW=?83;WRu@oi87ak1eVlbYL**Q@uhH0jorAJJajfa#Cxas6?T#?5WE$ zt47T8L1tCiT7=LFDDQmI-AyGHYpV}3o0t(UOnmJeWqGca{A9>Z@nWx_QYhzO{rG^@ zD15lYbrr|Fvc+8EQs%@w;;1U$2b&^JAxl68SiB;mitf^F$x`4}0KiRPCfzs!UpR~3 zn&!rSwYg$@PTZ02s|&-&QfYcDC1C)nsLbUXrpw`uTzw>07Sd)X<&ref6$B5n=(oiq zIJao2vj4y7cig$sIIjIMy!^(_ONN{q@>>Wh8J`Q$T$F%n1*(+v4?#k2F`7(X3Xu2T z@Q%6v2KVm^leHbL+RyH6B1IJWQ`ZJZry(GsYIQz573PZIEI;B%H_M$6CrYK@BAI#w zirox8aRUK@;fG()Wg#|-z^kNtQxLJCQ?(@vRw!a9Q7*l(l)HVWw&9Y{5-Ci?{kuc& zDkq-Ikpn$t(^^;4B|Bpi(E;pCw_7q1NlIEs7gnIbmYfsHh#?aLjh-Y(hL7%Dn%s6W zPyl!}UsY%=$4f%pp3y{hehR&$r*60h%v!vcd}HKU;G4M(UUxGt*7oj2gg*F&XU{X9 zDD{+AM-B9jAN1iv1$B*Nj&^xuXVbgH83v`NQ96=H%{e+smGowZnEx#6UMAmbk}6HZ z<;FleD3=DL)uAXcut?bTX%cfq)BT!XJx75ifu**A34}^H`0fiIxyUTlk=!42FB8JN$|o#KvtZvN-_HWChG4e9>sADp~)zp$owaof?;EE@r!h|2yXS5 zKHcMk3}!t59QSC?Hc>d`Av)RUlPdL-%@o~rg!AXjXA?dAqt0ED>a7UFmujNU^Vpm=N@hP z&hIn(Hw-()qf}LZ6uVNu;N&CdK@u*x?l&FYH|OZIzQicKNMiUo+POSx|gC84DmG z+=A1P>LZex(%5Hn^@nf3wnP)D)=o=A;P^Tc`42XAXwb3FLiJp$|5 z=s5LTYYtB}eh`rH@w~Y-+8cXb#P^T6Wfg>>3-L(XOnUDoBRh_Iq8-BRY}*NA%OO@( z$2?dIiv8dy_1-`-gu=V{g0aThES&?@HT4oY>c+aLaAGW5nA{}108LrK-j0&18aq`RM7A48pKOa{zNb(z4Eqbt8;9OTF zYhEU8UY77@@TPpfqW5jZz(ssr#c*;>$S~7>X1J?f(70L<=Pl@>(r>zN^RaVHiwa)y z?0(Pl3d{85$ju{^Qa-{uvR=qW-`XRvX|O;z)&qKwzxIKk2sKau78#<7dDP8F$3J*U zk96gzOb3O4p8)X7f+eZixHb!bB4DsYE-2gx`k_oBe_9AG0ko_rHh&z=fPY~EcnzQ} z<@eyzY&!$A179d1hC^F2%t3x(s+}$&I6{*g-s8k{k zN?*eG2?1FRycIg3Llx+g=wpnpMBW-#yaBrBh9Lmz7U}O@(aEbWSLZLO2U8s*ao&OB z6VW|i`F}s0`dSvp_b0Y`Q4z;^MAmH1sH~ZhN=8UU*Nd)YTE5S02blejv;_%=jk=1C zCU@V@@Y^`d%J*44WjyV@TFp91RP5{EJZjmsR*Hj6mjDB^xI^T zN`wP-Nu7O4lWKG%!F!k-OT-NKH4Yb!YP5|tRN1!l^azL+?DWMc1n5UL)3-zFn9OhB zwM4K5gzS!e^O@GwtK>tUwzVzBq1pumN_dx7qp67?>!wO^VRtM`sFg3zr~=$(F+|f# zC?M0p4WQFHh{$Ve9ei;AIjI*^02;V9OPGi!=doh@oWB<)T*y$U*HU*o{}#2%IKzmBIMpl3ae=Y3zCt5_^{X2GXBb>&zmQ6__Mj{NPKs>yXve{= z**+^Zqat#9hdk9q1x<@Og@z7cJVHV@0HqvfbM2KPmSeT&!$&~y!!>w1Hv+=g|CEHPjxO|8@3A5{^znK#{bVirz!}IP!+(9^s2Tt zw@6)$3FxqU@U3t7c3n~{ixb!N&-9vRFcDc$=q`KGk?#3Nuy(s=3Umfm z3IISs9VX`R6zf_jTkA`Rf5V7+QQ`TNp;hf`Gk=t3EnCmU59$&;AWSjI zrWpUhte>($rfq_Vi^Tf?0@5Stog&S*7cZV_Mu z7A`eLEH0?ad!@D~dqRYH!N>S~!H~I7S=g6aSnpe_v-GOF?9t96{(*Yvfm(VcCH`HY zp7yYMNTVJL4_@{JGm-Ky?6jnOGWymgxTw%#q-@`%ETb&tV{VAxTZ{-LS)0mmy!I2q zr7_SFyc1fUN{+wz6|VczPnQoQ$)7-8#(LSo!^dv8+Im;*(~0oPK}hGoOlPnVibH7< z73nVEPS4&G zyK)lR90lgtvd$j2adjHqi4oYe&W=qZd)!AEqJplg1z!|eQVW~Sg+u0tdgPz7Ki^5Y z2nJA(lyDwmhAMyfeu15=gN)FXN=oSad{T7nKd8C2I7nw4`O13xKEq{RF1Hg8VmYE4 z_(H|fqmXvI0!@YEaLZmr#T3EmU;*VK0gFfmt8COinh#hyXC_;u59H`kd^^EP4rs@* zpbh*4JF^O$S0U0x(azkvA|Et|4+2PpVX}IC7zKvx_MJOx-~x8f;-$gqBx(Z|jEV0S z;&Bo>i(nqUqfsAsXN9spPu~1<(Sy>u)&3=+`|`aP7S8E_#}Ib&1d>a(g7#O#nRm(x z_bro-9mOY-$Iq5YKTgq^3k_y+Hti<}?qnI&?QBn%X` zvkf$cb2$n1nOKe&d~!`974ao`jUYZV%P)_ft}f<~L$+FYT`SvYck)Zg6d9^?BIeOUyoU>|*Fu*nDCmV~c( z5W9RpQo(=in0(+xd0CbJU^DTtI>;!k)$jF74j8x?&~PO{_Dt1Exo?2{#~VzA>}|6{ zPYkONgSfIR=0@eh^v8k4E?OjmSg|dz8DGi^2{IjwsQLC?7bGzklKD znw7zQe-7Dewsg1+I-q)|BW#w^Ee?gZ{gwk4 z$#K&W16_Wr*JRHH!9{;(u-|j&bL5daUk>SinHwlF4RI@~tA`sA3NNvUmf9E|w5?o| z9mIlL>VR-$Ibrz~$}d&LQZTNQ-FH`6&V;o$U|P|GdO_H!rrgpF3mjn4{n?%+ z_H6fStk;672@butLi%22UpIv4p2!0~4d3a5Z(MzEf}Ldc_i#Kk%1-k(gIlN9Q2X0J z*LzFdaaSpf;6ISVfS<$j0&M$mG%uWsaIeBzdXM|#hI$!%lhX&N$K27^vM;OU5Y+tH z$`>u)I;~osj3X$pm&8M$uW4H4i_mH^sK~Q%MJpv*`mWey*~Pc+)Ydl1&;+|j4p_>2 zweO1^+f!mxDSweixV_VU8OJ@`eLHrs9N#dYzQ`h?J?Z}Fb;Z%@(P`n~(im&{BDCcO z2h@XmyyC9rG(E=S8+yVXSI|F1Kat7eC@h;$G>p4(%-glE;_m|av(z?E4vu^DSZ1V8^0+2Y{(Nv-jdo(EM>hh^L3>VTLEadn}6xBFqQ78ut+{V=Omt*qVpRyW)lkr~+)`&^ z%_jqO8ycF9Ev1ChL#-vl!IK+nL+4>{RDf$wUE!j6YtKS?ZRbpt)@`WX4dGqP$hg5C zO+Qkeqo}ZhqBaI+sH`pR+in+{j!V}5+S(BZOHW}Qd;&-5u6{u5t{D*Qgk5|)`Tny@p(j>2@BWE1+6}u zl=SnFnrdEtb)G}JlYhI@=&aU=tTC=Gfa$YaG2T&P>$08nrGBL})`m;+6Y~SwZ}%&E z-yR`8!-aDGa#TrNjwCcJ4w2R@5_nP)xQ#?eaFgSeN(ZIVPYpje7)V|X#q5q0Y#H20 z@xC=sr6*3+sxaeJ+(wEJ;AMdGxE_NT1i<6~f+!2HN32Y+I<;toCzjj|80vp_+`(?w z>S|<6%x33rlNgKI2awmvhq-mc7niU!nz&l)zsh$HM^M`uC%hXW?{)60cI$gy7CEQLXuu|(oT4c|P1^+i2kMVJIKE;-Y9>bR+vU1`V=}oqb+_3vJ(x;;Q z7iFIpYfWYS``Vy^)r0VrJc2%a_O~3cFp!Rs9c9dY0s%4L3;{8SN>@MO8nIN40It#` z%CT6SDvO^eVgjI3!BCzQ{+8=Xms{Re_bYIHGsYpiwH?68yvQ)zg@6-eXL7t^j^^nL zlJoScWL#}VC0&la35Vv}h5a9to)kJ@j;8H!q6P<_XI^-6Fei4e$u89d2Xbf*W2A`G_UGsOuIkjbS*b z9BGw~4(GAd%=@9bQRIl@)O=GX8PREybg44|W(0yw@D$*-Dc@92;rowf=K<7Y#Q*rD+m0O=` zecHFJ$6PiCEOR6TjeV9mB%zfiO$1;y>}gTQl>n;AE%a@8p1s9$^In)Mv=sR`B)9cB zm<`?udeLA2$+{+}u?SA4(HeKi`@9%VQk$`~2{7m6Yww#JLGXJ7ZVcsYZb8h^|F5}s zfvYiH`^TS7a!ztcM_W#faV*IcH8X9^M2>r7B1w@BD4~)L%s5TTHjIX-hKcdctY}y& zQIU$F7LzF{N{d!@v^pRi{lC}!tW#w6`+490@Avub&u5QXJ?nn%`@W9%bzj%_BKOXg zjtB}U7y|sJFo;qm*%c`aQn|D{zeZJNS-=^wYVMsI2mbO@k@nuLhMkSuxq4WvAo28kxEP!gq#uG{aXi7cqllrt2asa!z|I&OnF5A+_ZBN z#r4q^@0u3d;({Z-4DpuKVK*Rp{9%DVT3`N|WK<79U{s;MQ;sDMK5JKYiC6`9W0=JM zDQX>ym|Nv2x2jP%owqF`H5;QMugZ8G-FJuF_}nzFEGx%``m|hcLOi7~p(06YL)i!K z{D!_qf5$G9C<1t)pGbs2%dlMskey-y1H;XDb&+Jt)M!dy4M@kYyAQbQ*R;ih6db;l z-WHD>ht5mBuwAw8;0xb_ZHi}KhM}$)jIk`Pe1m=u0JQxo#Wx{*(2rK>6_fhPq%@vN|%dkXv7=-PL7z`;pR= zvJy%%U&~mX@^*4CcBz6Y_(OkYmwOCF@jtX=Mj(onW}*w`HSi$dyv zRURe^TORRnDq2!ZrJct2OM!kU4JEQt3xOkd_IEzt(7LNO`A4Y@zW%H&Ui*QawI_QN z$wRTVXESygCTHxTPoDs1M<8(Co3(Y<8mh5X{Po>ws&-( z9_zn`+>v5A2%Hrxy1D_7Y-#K&&n0aO=QdV495)?X(>#}uq)0o^q7BnCj8~y!n6r=d@eCA0hytm}g zI&mHT4;;~+_7%;PD_{=*_`W$DP-8O=>2#jk-}=1RV7QYx%oMd-ZYzvGEqwCwrXJDS zcAA=Cs*CT-uzBNmF6^yiSsMz(Ucpq3fBK`ONqx<7CgDF}6(q?uEJ{Vva@f(ay;ItW zCNNY9h3qwu%^)(XHOfvE1qsyvfR{uu$dJe;iKs!>w5frGAY|!qnbOYwvUE5~(%}(0 z8Wv7$n!?-yqAun3h^L^A3hB$tE`Bga-(ct;4)nouQzQ=F}-ybSWZnq1@d4%6#H)1kPQ@P=QwhM z)90Y1s#m9w4OmZkLhWz%cjyCh>JKcy@8coZTHw+a8-!JyPgz=Du6dz&tzdzZyGKf8 zdO>Rpu)f{(DZ_zRgeGhCXVuw+#y{Qo_llsJGpP@KBgq-ekWRnFpnedQI3rHLquFIPZ zuv!6;60VY)*f4P7)d~bB8@KYM=w}uJSJ^Frfe9dvxq<7PY^)_hbu z_>V;!o>o>4h;+1lewBo?ynlbFW?S{jCws;4Py%hBru7{;6eB%ri;)2C)0JyY_JHE< z^7Cs_ji5~DaPBWj!^4s>$C<=Ou9=h<*JxM?w|lvDL`>IQ9uuWek)O}XrHX_3-q_$? zAkB&$Odm=+>!i#kvAZ(<_{9#06aP!`W@S1`ml%lr`aMK7HjSAC0Fvh&cT`DF9w~s# z9HAVZmfFOZ0qjhBwk&(&WX5(dXakQx!@F~*T9-ZfwN4yx8oKQk9#_`)j3nCzWHy)4VI^uzO9o~^!nVvkRu%o|NdZu?t+SfSviiXr zl~6q|uPrZn*&cUm$#vuSoW)Y6{}bAtC5#-wG8@;YHK02UyvXpkK@qWW>o4zZew(dR z^}0-2iAu%ZCCdYiO&cbgib%P3c2#KFSBv6X|52COG-2k8BD=3MrEjj9wtqUr5Eo}C zmSdTHe1?x*^CG*O6`il#0E&jBOE%Ofig*W~i4FOR&poEw0rnh2#6mgciuPQ$9l5L2 zvU8(`Em2aZlImO{lfl9 znu4jVnUd|h+&$9?d*3_>@GENtcbjp`3HJer&v^WdUOvi>&m&H;u5nJy*|(3qt^Av> zcu~Q=1wK>v$I}7$ARWI0i+sn|IiK^Aqy34swdP8Q5JC~+J4paojA0G;z-deJ0r6;qY>%iv0cjY z-tkGH?C2nGW`ej`*A%j0UHqV1S=YwZ+Y=~D@PkG1z1bIlf|cJAC{co$@j>lvlsxA4 zGS}_)?910@`}_NoX8{32!W4GU_Ks{TAx3=w7K?6L*l4aVO6tF&TK&ExPEztoP$R#w zLr5*C9PB!7WqF|`(>#BC03fr>=8tnGAxMOlBq+^fDiA<|g-sTH&9ry#W`Zs8(w{Y9 zc{v?9=r5Glf&zCm)_Azh46m?F%|cOWB~^>E)YWb%qjEt0ow%9hD-u=Szf0{jezZL{ zG(DC%+>~|rPSFL6JS|Y>ek-A)cIb4uNu(C>JVWuOiw_EYzpKd#Y!cv0>-p_THJ6M=)6d+(Hut+VGC9)`G zs*u{2(9SWG09dINlo7N+nW3+ev!YoE$6iU)4$2fG2S+s*R&g2BCCQ9Vm-4jB*r2c_6h`~b zv~{~FB`GLvF_w9tKKIJHqbg|lWRVm0fH(5O@SA17;pgy z?z-lDkT7({fvOv(^|CZPXXtcx8Fl~KLGmcjt zl#mHaQDZ=d5u}@nnCJY*D{W#bG@3P!Z~tk`Z$e>?@+#mL;sT~J-%m|x90-@w_Q{Vr z;%DA@nbBF+N6@1Id${V)!i;LAH08bOvPcw1vT?Z?ITzenfkI@O9aZ zi%CtlH=IhRP+{NRiO3V%GcYI;7e(?vSD0Xjp69B!CU#6-*?>eNd1i8<5`ux8dbMow z>eW<|Rdp3q*Q}%y!tLXM$HDi0`Vls-S|-GMLr5Cy%n z!K|$()G$B|9kzf#46i;Pq!fvOS-Mj*tR&zCxhD|A>rBb+WerKLG=D6aSf>sk%V}h@ z0&Vab{aJYdPu?_m;QLL14OOEQzXi6D@d~dY;wY{-!l`b)y`|}$j078nvqxd7ZVG?p z-lih{+%>o_nECenOyfva=k#uMz~x&Rnd7*>-tev=EfGV*QH1fMvaUxpq3UC=Bf>G; z9uE!EB@k8hmDpf-^(cRB{umfThq2ivo#(Wh+6n8q?KqIdB@*Zu(20AwB;u`QP*^^% z=KQnVji%e$o{)Zm{RgGkNZOy!UOM{0?`zJ0uTd_=cj1wjm#;LM#o@u=#L&7Kw*aN_ z^pbBOMJqe-VOqtc7^Vkda30^)jWaZa8kLPt3=p6{-S(4JfgWFj0qUmhGlRGC(luWM zOuMGfu_LxsNa8(!;J(gF`OToJLE72H5WJV>MulXRyKM(WE=%aNd?&D1tH>-sg9Ie% zH(qD>!7RW3sq3Tfhep6T*$w7sY0GM}VL2U42$ViOA1{%eq~%=}->86Ma5^D1pQm;1 zG6afSr!TIkAAOq|x;v;6`<7W-(;5??uXewjsh8d5f#i{AyzcuMnVEWfY(rl$S!nSj z^>gXzS2c`HOeXI$V}^TA{L7aa1s3=uAozl3pod!aq`7|UC)8xbw6Ul3!j`D%=j|;h z(1MU;$!H?JSpg(xhfLbQ^rY*1!F=3wTRm?Yo+k4)VXL42j&p;Mky$q2U;EPu5!mbCqG@ zlS*&C<5As<+j zO??_&}G!&1Gj1g5yX z`QS(ye6P~i%ToG!M16+m1SQI+J??B8djCrBfz;5ppvu8WfSexEu3zFBx=XT!EQTaA zkRnI$nw={)+onR@JbZYv_LJ6RnE0!KhIt1FtPJ}|Lc`VUotIU{iLEz+e`|?lh=G3FtWliQ=%KBxL?sGN3cHN^%9HVG=5vCxXB{r8QGXD)hxLI3r}LjK*A| zSE^-0Ld4c7>FJ5JpHPkaCoaFGq(IMVLXbix$A@MZE2UN7gT{5abWZ&jKia389MXu2C@&O$$)31{1A(HJAWG9ahh!9NK z(HH7UnvGpc8p=r->gVreZ-qCnvtK{ISETYckQt|Dbnznb?YM*3u3h`*cGoG8!^+6) z$eD?NZ#d)=x6nvu!&uNLlcm%XTCf+ zGo$vSBu#avK_*{hThHC(y86lrJzW@bjcD-~w|+XbQub@$K%h>buabV=0XQRgQAlEd z5sGV_dT}nZ$tvXqcnVF%jv70PgE^B}#h4v|lpxG5PLCG%+>`tZhcN?f0$*$f-bt20 zj?YaxVBjA0r8oMV&McsmG!FdVX%xvIaYAPhW*G&Dz8W7(ysA;PJECTH@JkQ3W2xJK zM^8u)%UBSN;2gemU^%|!n@e1o^dF$6Bo5b~x`Szog!;8+dRZC($&exLYybspF!tpXk( zhi4( z4|;7Ywq6y7+lzP!ppRy7my$g^JgznYH^@Y6jZS|a`RHc>L=O)#f*YUThet!5&=I@j z07o%n8T`al)6O4FdC@|gLMxl(u=@~FEZH9>M^~=QR@O=@?yo2d5HSfp8{^`|Ey|1v zB?>Fc=TN3`$OGlSV}qlb$eRH^OXuKsN1;Mw0ZeLtEwtUC9_>{Qpz_NImX05aP#rh$&;fvL&H9G z(_+jpI8VI0cLzp7ED2-81dSJ8fFt0fenc|M%(NIC30bMLG@$)9-Rq#^pXbVfS;?YA!jIY-R=@ zo*nGj(V}noKml#6vGMp}`3JB=-ES;51WGQz=-H(hJkxBLe}J@EZ&)@Ce+nM`GB)Dv zKZ0CWlR&^R(AmUqFTb0_0{r+Fs8bqOvVx)S)CDoAq{0pPz&e}A>1@snTpn8BU5yHP zk~A2^VflNB^mq~yn+W>S3@{ORD)x8>OU06Xi%_8CuV=zaT9&!+gy--fGAdJaRKjoX zB?_|ydq$9!WtoGS$0L{*VZeBRRRfzTk7Xo{xZAoxcV_qIwQXX-eBz{c(z`EqFaE08 zI7C6FYH1f4j-m?Z+ukA8PX1+|*rDW~%(DZu7fBB)+T#BOADeMKnvfbfLK4`2Ab~Uz zy19_6ZshoKOvEcqjZH#Qa)H>`lTR_=7NRRtj-juOD2WZ_zJo*}5()!CN&r?pbvB(v zw_#&qjKy?HD~A`qHr*3`>5x8)>)M|W4 zaLK&^8bAe$c4#OPguBh>{%>GRZ0j7lO^w7xqyxBP)&*R7ZSj>NHv8mwMT;x?cD%Jg z!kDsY0Pmi3Bg?F^h5{*+f`L<7s${TR!{89wE87>vWn`#Y5$=I*gNt_K?#5pBOKfCI zO_!F3;NI9Hg(Gc)mf$gm_Z9U-QMGY=0=Qaish$WR2#fN~#^CD1w?;*=edF-UDR0k| zrFYopr@VhECaQ91PHY9sNF6!d>A)q^dpJvZrZ4|(>Blvf`m25>lTA3REDXE}E=Ug& zMfjT&V(&djNx`gY*7ky)Rma&)^|PCn(d_ROrwJ9sLseRwCeOcS?ahtpm>1ScU&Ui+ zgaRJ?(C6f7zBypp$wDJ^kwG46hx~Z1tAZo2pIz2GeD zzMb5KaLg?B&t{R@LCg=LBmfn7lEHs*x6GT&xpYRu4Xq}2zAhD%{9i7dUWhPA`u(%*AeeOiLB!Ffp`?xcHCi=6WmH?aA{Ws0*I8YQzc z4XIQ)!--yWq1rq711zLL2MgZm<56+Q9#Kh|2IYKwM3>x!QCHyU0l_M$9i@FUl-gD` zMy34J4voxYonb$0*NUJOX>3eBw9XdUONdTXTSB$4ttqlpKSvV4_D*x<(OEznrE@I- zA7;c(2*8ch(vOG0GSSk1TaHMGlfW2G12TR)&jcOyGRQ{@QN+92)(!qE}s7d6( z{QXGOp~u!5je&e}=*M^|`DE=!WN|!?j`k6tJ3QK3(-So$5YC=Q0bUzNEdxp5?GY(i zKH-dTinE?@G3kUmh z-g7|@)=u}ojx+M;)I<`7V?FUTsIebr@EzctAqqi}WuW2qpOQRf%^Kd$RXB?uyd$Pa z3%mYs8OPSoGkp_ba_i-z=RL%TpF9{}KVO%*W0o;`U}BeX&1K+G`R@FNYzgu;3yv%z zKL8bffC7^}Gp8o?ZOw*ljc)>I`)z<>wZUjip0{SUHzSa*=orP&+l!#e8Xr4H ze0^04JiTTcmkDZU`wchd>BgJyeiUHv%*V0hpLIdf(m?Y6OO8#?y(!Lz5@Z@}W7f&1 z-+3SV*)>=7HPE|R~ah2>MC^@P9R_0NGLgR<;`4$$lvZUlz( zi8(y`RKP0IEhU&Piz@{Ivu^+x#Ssv-%`L1pCa8Boz;`K zd>lL5XG!T&a+x>Yw48e{`8Sw^)Ks19LUa-{gxhF98*lA0;Yi+I(m(&?K&u$!@=Bo0 z0QTms+?DU;lmk|nQR_pyPMiHjUz`Hu1Q29^zGE_>ZbjAg1`j%M*xH4Lw#_MW5PX09 z_`3K65OrhviQ?b!PLarZ?sKVhk?(3R>Kcd+!GHT~lhEuqsbA3xsB-kS){Znhn-znF zpknb#*eP#xV?Mw1V-#GxetqQBUYBv;tan}@eVZv2kBO+t4|)IMxqC_J5}j&pqq3#B z3Da{}NQMq{bZe<{;QlLborIc^iB+VF?<%672J`39)#3RSLR7O=vzoLo^kg+JJ0aE`65zs1P9$ z9duSkxbxid32M;NB;w5J!RumYqX8}*K=yhYoDo9v-h#85yXq>5So(5=0r2z2bj`%# z7=*@DW@OqT6Si)sr;wa)ph})>D0|M zrOt)r6VfZJ=Q3s3Xb;NcIL7N$`cp`vi_N9vMthJlA1gbLfEtKMIuwL$qR06@w(QOT zQkIB?fnX;Xub@@?1T_|F#^}^}{Yf}hK(_n$j_@bDBXISFo_Z`A_`cw&kghk08#_j; zhPf1oesra_d4;qe5Io|4SDe}u$Vu;b``zD46Zx0`YCH^jZA6UAhw}&l468-s4CpzU|Iq?I1iPNOig>l;@Db0^u1gRJ_+4YO z>*}MUAv8xv(~13i^p4OITTgb@BZu?%z_?R;1CCMD8K4&?HMwr>xgm%FnIksZo}18N zKD01_oO~d;t65WSaOw>4v-aO7cB=Ep6C&oli#qPjL*6^@3yLwuD3WD{U4$&ogx?8T zdS;cG-FJ2!2koi}n4fuo3djc@-Z9Yb)j<}#q$|v)ZjT3lMT1au>}@?R=V*{eZ#8EA zYudJx)1I^pgI^JF4B8MkP*($Q&6#o#YG9M=)9u)+_ZJ8)nEVU=n(kb5-Foh!frkd7 zQW+Lv?ajv&`9vW(%Ud4sEQCkDfQ3Zn2z4+K>kNR?>R-#l(1E+CTpYZJ-#Vi46R*cnSy4*oL)3XM*g{p= z>(d_hc!ZYmM}~$r425m`;I4S#mgn}fMI?y)_IKR@EE4;&^!6E{`Z??|{>Xs_bS;xq z+#8gs3WpL@0Sav3LD2hxC>aFUfVSZ-hjR5zdq0~+5A|o!D0mrWasdp==>rI#AMb;sXbymwm}U z(aCtj(a~Tp;bNj34x&JiAwMatg2@DR^Ms+-`F9n*eLVaFvF|4xn=lmL3^rbGME z2sFLanc^)_ueNVKou=EHz0J}YF4ng|o=%Vu`IM)GcM=|1ZZ)6$uArYu%>QE|H(&dH~|nZlF6B0?4yU7a^=L)+_g(z7H#yi}XZ+WOS&+Sr(Ua+sjaf{T z@43KQzB`3N6ke$)B$@_0r;z(P4k3aefpyJhcI`RTmv$1}DNyq+n78Wi|8Q&GrUFK% zj2lw`nG&`b_=omZs!l43Z~VuK=OBL2*3&`N2$SWe(@KXQKSogubVg61J5THr9P?v9 zen3Ssz;?RQ8I(-oQY=X6n4n!qw^WWTt3obl$q55bcSKSLnomFEd*R z4?|`M3xRbT@rQA>+9~g<%1VgzvSq;hD6$ObyrzZF=*$EnY`z96tzHO$Y z1vxHSkeuS;A+XLhdorZyL(wyLf55-d;y&T)uQlpYg~HsXK;-?i$O@{aT;g&1St?je ziTe%hQ1(}^stFfgym&D<9Os*~w)jwJ$ksvmTebwR$IJcwIkXM%nwiklj>3g)c6Kd# zc7^X}Gq7fcT@dAX;p_e3V}qiczAQB~bVc1$w|L1GSoMd^<$aLBlyAMcaimCu$u*Zf zctEWP<3sljI8xnOoBXr|%=f2{RyM5~r#H4At9^Z=kfJEt0y08=Uc1S6)7I9$=Yqge zf+&Q0**x#kLvjRM1ZRYk5=0os`zU&IOQ=#|0O8%|KAeq<)Y5W_++M9ly!TI^TuVZ6 zM|ZVf26HfcZGy$)PMv|f0ugr+@Lwjn&IsC$x02SzgXk6`AwxDK&eiCq0ClJG zcBT~hc8ky;y(5V%#rIq=9cae7X$c}VxM9@Emx=;@`Lj3X*FPKn7i1is$V+%4L+~Ja zw@*h8z{O~VJu_i}?`ok7byiP@mgSpe5m@S*-4Sm>Sv%5h92RBnR|Q(3@RxKSzSyRQ zz&4phHfXQ)e_`#;f}ONzat3B5X!t`PVyijQx9}slK18jX;5{NGM z4Q?~9+7@k_d9wI-4G;_+4B^o+GMd!LsAaezE#|9=1tdvi&XC@Bw%7><^&+UHLx}x4 z6s+5J3z-$fY?f1f#?#nkG?}9YRCUIp#nh~luGWC#L;L>}or2*v9)-7yP6;mKsI4!x zEvIJGE2_|0lO~V$QHyQo3%)1shUn!S-Lh?#;Ct;>G(BgIrRIN3G9JV5<`hNq-IU$t zLeGW3*o|TOj$R3j1{>+6-MAsq$$UCmz7pXOaFBc+E`7k_k}c%D$7f_C0Sk=>!MJeB z?)V6y$QHqXsV)k9Kd%#>9CY6-jJUW$exU zOn)bb0-ZojdQjLIp1~9NsJ3?)&yrV84Gcvgi8&`n!CYt)-~i}NGXrscI5kV41z9LW zqaSen$zpXVC<&cZe1xY~ZwzQ27-!gr92pr^H$Zol7slHV%%e5@9-I?7NJvN`n-EDU zT9)D&d!`pi=AZ{?L}Mc(7ENw{GOyjbn;ULU>8{)5cBv1fN;H*TX(>ZP10KCBcyugw z>$6y_t;v43<7~`GC;N5rXiQeN|C61gUHXuU>28((e=Mw5$HRl`r-{IkB)VAmR^h38 z*RWKyZ=QN>#Z*a)LMdE0GdT|W zTD=|}MstAL-`=wuax!XCjVsIkuILIV(rvdVuZTKH!zx_0{6DxW_sbtVQIHjmzjHL( zX|Cg;-iB#9=m3kZT$I`>lT{aAP_DXqv~Y2J87Ny?Rzbi>2gl5v@B6eRUGk_cEiH6! z(doHl-{KQ;az5wKTmuiYAAu_Y#YjIgUlzj-Ba;};7QZy^Wzf9K4{eK} z*;qdkcvM-$)-r)0ak;XFI=1i@yTsSYoX&oA?U02}NETSO&3Or84^{Ukw`QWlpz@YJ0Q@F> z9gxN3j(-VvB*g+Q8>$-2__@qA}1Waac&3w z>07n03?kj$w4n7ZoDEKSc|%Zbx{>don4MDOcYN4SUvX?&XjH1Fuf!T%tjI=`OA%cw zZG!3vc&<;ittuObNkIBZTTuOpCIVdt$#6rzkxdp%1;-Xy(lj@vLkhOc79y%2G*tbw@1jLh;xn8gleYuZSkk5*J1oG>s*D*#rG`w_Z7Q z2%fqaQ<#eOwAj$3e^3LUO>i4zuRKlX#3NJ?BGt`!9aW)K7>mj+=OBYTDUdBjT%S8BX@-AgUJiQL+4hUHBW*k z9E=Sp=x_nX9ZGX)W&-C!3)NJ|f3>y1&q^avxVO{~j!9bw4rD#;(0=CH`>ubNL}q2# z*L&zYbp3Yue$*9fY5iR34GMe(g8wG?%Xl5>AcQ3h_28d{*)g$DyYt|>pA~#K_;^!m zUmY#=>tXM!2acp8te_YU+ck2_pf|9fe)fW$)a3VP;YK#@h2^+y<7jxgPp+vpls|;* zSM%?wx0PVAZ(Yd)2gNTgabuIz6D!^pWlbYlvPx)Z|8qs&m0@elx}N++Ad)V-2O- z^5}|vW7&%!b-DsROjYw}ayn-n)lgv=>Vw$}H2}`+#Kx=ZMmn*fVG+7KffLe?!$zC7 z-8Frj8ZItT$lHg*Ab%Z(T8Dxe6xM`Ii%%G1+h9%!Y;-*t);dzOj_CsA$j8x-#806od9 z2-pv);II*l+#o(LhetiVcfWQf#irw!^r>(Ok=v`W{1|Y}2WX`B`fV74lnk)3fip0QAKI(mxi6LH9 zz5%^Ik!}M0$&mtu8!ahxtCXozs1S8bj4>%B29xC#JLDGbOtC@IARk&<-8B9KwwRL$ zvGTN}HQ}o+<7j65+chX}2&>|(!~Q)otG>zZ)_zDK_t&{!N>~=U^HG%WcDd^@e$;S0 zcz4jYG1v*F=CP$DC30`-C=ki4;+cI{E;%#!%&P?*qEXwFiCGX*Z+A@KAImO;DH zVh7U_U*x&5FfACBWxWuM>(N`v>^;OZYHLS;W$d`FC?RB(3Qh8UK;2c<+^53_H5C{d znle;^-U?Ge0~QAdp0EE6sKWcvh

5r>+TA7oI=-F0DPLFm&0;!D<< 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 YbeWsLJxra$|GxbDT!-Y(R_^%!0Q?lnv;Y7A literal 0 HcmV?d00001 diff --git a/assets/samples/exports/scripts.json b/assets/samples/exports/scripts.json new file mode 100644 index 000000000..3d1f13510 --- /dev/null +++ b/assets/samples/exports/scripts.json @@ -0,0 +1,8 @@ +[ + "1911ce16bbcc8a961b013f53f184fa556705779dbebee2d89f7508463f60da15", + "394116b0b022dcf8f1bb469f486f9d3443d5e6abb0fb947b6946264f998f4b76", + "13f68dd015a1efd9dd9c720d94796048671579de49958821d003be5ae17b9d59", + "4a98200a71f7301a2e289ef4df34e3527e5acc4535671b5f955606712583fdb1", + "0d5fd0fd99d606215845a625ac56c8899a407527ef289a427424f064872ab25b", + "54d29037a7d599a07602e8884a628b52ccbb055a8c870c9b7ce7cc5c7390247a" +] \ No newline at end of file diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index c22f9b87f..a96f0c5c1 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -304,6 +304,7 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) -> "preview": {"active": app.preview.active, "busy": app.preview.busy, "error": app.preview.error, "ms": app.preview.ms, "replaced": app.preview.replaced}, "home": app.home.open, "recent_thumbnails_ready": app.home.ready_recents(), + "sample_thumbnails_ready": app.home.ready_samples(), "documents": app.docs.count(), "quit_requested": app.quit_requested, "quitting": app.docs.quitting.is_some(), diff --git a/crates/ui-egui/src/file_load.rs b/crates/ui-egui/src/file_load.rs index c130370ab..a66472230 100644 --- a/crates/ui-egui/src/file_load.rs +++ b/crates/ui-egui/src/file_load.rs @@ -802,7 +802,7 @@ pub fn tick(app: &mut SolveApp, ctx: &egui::Context) { if request.kind == Kind::Open { app.home.add_recent(&request.path); if made.thumbnail { - crate::home::remember_session(&mut app.home, &app.session); + crate::home::remember_source(&mut app.home, &app.session, &request.path); } } } diff --git a/crates/ui-egui/src/home.rs b/crates/ui-egui/src/home.rs index a0e493369..f9738b972 100644 --- a/crates/ui-egui/src/home.rs +++ b/crates/ui-egui/src/home.rs @@ -14,6 +14,14 @@ use crate::theme::Tokens; /// Recent designs kept. pub const MAX_RECENT: usize = 12; const THUMB: [usize; 2] = solidcraft_engine::io::THUMBNAIL_SIZE; +const SAMPLE_PICTURES: [&[u8]; 6] = [ + include_bytes!("../../../assets/samples/exports/0.png"), + include_bytes!("../../../assets/samples/exports/1.png"), + include_bytes!("../../../assets/samples/exports/2.png"), + include_bytes!("../../../assets/samples/exports/3.png"), + include_bytes!("../../../assets/samples/exports/4.png"), + include_bytes!("../../../assets/samples/exports/5.png"), +]; /// What a background job makes: a key ("sample:N" or a path), the picture, and for samples the /// built design (opened at once when picked). @@ -31,6 +39,9 @@ pub struct HomeState { queued: Vec, #[cfg(not(target_arch = "wasm32"))] rx: Option>, + /// Building a selected sample must not wait for a cold recent file. + #[cfg(not(target_arch = "wasm32"))] + sample_rx: Option>, #[cfg(not(target_arch = "wasm32"))] remembering: Option>, /// A sample picked before its design was ready. @@ -42,8 +53,14 @@ impl HomeState { self.recent.iter().filter(|p| self.thumbs.get(*p).is_some_and(Option::is_some)).count() } + pub fn ready_samples(&self) -> usize { + (0..solidcraft_engine::sample::samples().len()).filter(|i| self.thumbs.get(&format!("sample:{i}")).is_some_and(Option::is_some)).count() + } + pub fn show(&mut self, _rev: u64) { self.open = true; + // Returning from another document cancels an earlier, unfinished sample selection. + self.wanted = None; } /// Put a design at the top of the recent list. @@ -115,21 +132,25 @@ fn decode_thumbnail(bytes: Vec) -> Option { .then(|| egui::ColorImage::from_rgba_unmultiplied(THUMB, image.as_raw())) } -/// Render from the model already built by Open/Save, rather than evaluating its file again. -pub(crate) fn remember(s: &Session) -> Option { +/// Imported STEP/mesh files open as unsaved designs, with no session path. Cache their +/// pictures under the source file identity too, so Home need not reimport them on each launch. +pub(crate) fn remember_file(s: &Session, key: &str) -> Option { #[cfg(not(target_arch = "wasm32"))] - let identity = s.path.as_deref().and_then(cache_path); + let identity = cache_path(key); remember_at( s, + key, #[cfg(not(target_arch = "wasm32"))] identity, ) } -fn remember_at(s: &Session, #[cfg(not(target_arch = "wasm32"))] identity: Option) -> Option { +fn remember_at(s: &Session, key: &str, #[cfg(not(target_arch = "wasm32"))] identity: Option) -> Option { + #[cfg(target_arch = "wasm32")] + let _ = key; let img = thumbnail(s)?; #[cfg(not(target_arch = "wasm32"))] - if let Some(path) = identity.filter(|p| s.path.as_deref().and_then(cache_path).as_ref() == Some(p)) { + if let Some(path) = identity.filter(|p| cache_path(key).as_ref() == Some(p)) { let rgba: Vec = img.pixels.iter().flat_map(|c| c.to_srgba_unmultiplied()).collect(); if let Some(bytes) = solidcraft_engine::render::png(THUMB[0], THUMB[1], rgba) && let Some(dir) = path.parent() @@ -148,45 +169,67 @@ pub(crate) fn remembering(h: &HomeState) -> bool { } pub(crate) fn remember_session(h: &mut HomeState, s: &Session) { + if let Some(path) = s.path.as_deref() { + remember_source(h, s, path); + } +} + +/// Draw an opened file's picture after adoption, including imports with no save path. +pub(crate) fn remember_source(h: &mut HomeState, s: &Session, key: &str) { #[cfg(not(target_arch = "wasm32"))] - if let Some(path) = &s.path { - let identity = cache_path(path); - let mut snapshot = s.scratch(); - snapshot.path = Some(path.clone()); - let key = path.clone(); + { + let identity = cache_path(key); + let snapshot = s.scratch(); + let source = key.to_owned(); let (tx, rx) = std::sync::mpsc::channel(); if std::thread::Builder::new() .name("saved-thumbnail".into()) .spawn(move || { - let img = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| remember_at(&snapshot, identity))).ok().flatten(); - let _ = tx.send((key, img, None)); + let img = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| remember_at(&snapshot, &source, identity))).ok().flatten(); + let _ = tx.send((source, img, None)); }) .is_ok() { h.remembering = Some(rx); - h.queued.retain(|k| k != path); - h.thumbs.insert(path.clone(), None); + h.queued.retain(|k| k != key); + h.thumbs.insert(key.to_owned(), None); } } #[cfg(target_arch = "wasm32")] { - let _ = (h, s); + let _ = (h, s, key); } } +pub(crate) fn install(h: &mut HomeState, ctx: &egui::Context, key: &str, img: Option) { + let tex = img.map(|i| ctx.load_texture(format!("thumb:{key}"), i, egui::TextureOptions::LINEAR)); + h.thumbs.insert(key.to_string(), tex); +} + +/// Read a disposable picture without evaluating, importing or meshing a model. +fn picture(key: &str) -> Option { + #[cfg(not(target_arch = "wasm32"))] + if let Some(img) = cached(key) { + return Some(img); + } + solidcraft_engine::io::read_design_thumbnail_file(key).and_then(decode_thumbnail) +} + +/// A sample's shipped picture. Its model is built only when the sample is selected. +fn sample_picture(i: usize) -> Option { + decode_thumbnail(SAMPLE_PICTURES.get(i)?.to_vec()) +} + /// Build what a key stands for (runs off the UI thread where threads exist). fn make(key: &str) -> Made { - #[cfg(not(target_arch = "wasm32"))] - if let Some(img) = cached(key) { - return (key.to_string(), Some(img), None); - } - if !key.starts_with("sample:") - && let Some(img) = solidcraft_engine::io::read_design_thumbnail_file(key).and_then(decode_thumbnail) + let sample = key.strip_prefix("sample:").and_then(|i| i.parse::().ok()); + if sample.is_none() + && let Some(img) = picture(key) { return (key.to_string(), Some(img), None); } let mut s = Session::default(); - let built = match key.strip_prefix("sample:").and_then(|i| i.parse::().ok()) { + let built = match sample { Some(i) => solidcraft_engine::sample::samples().get(i).is_some_and(|smp| { let ok = s.run_script(&(smp.script)()).is_ok(); s.doc_mut().name = smp.name.to_string(); @@ -199,8 +242,29 @@ fn make(key: &str) -> Made { if !built { return (key.to_string(), None, None); } - let img = remember(&s); - (key.to_string(), img, key.starts_with("sample:").then_some(s)) + if sample.is_some() { + // Keep the first viewport frame warm even though the preview needs no new render. + s.world_state().warm_meshes(|| true); + } + let img = match sample { + Some(i) => sample_picture(i), + None => remember_file(&s, key), + }; + (key.to_string(), img, sample.map(|_| s)) +} + +/// Send every readable picture before starting any cold model work. A portable picture in a +/// later file must not wait for an earlier STEP import or legacy design rebuild. +#[cfg(not(target_arch = "wasm32"))] +fn read_pictures(keys: Vec, tx: &std::sync::mpsc::Sender) -> Option> { + let mut cold = Vec::new(); + for key in keys { + match std::panic::catch_unwind(|| picture(&key)).ok().flatten() { + Some(img) => tx.send((key, Some(img), None)).ok()?, + None => cold.push(key), + } + } + Some(cold) } #[cfg(not(target_arch = "wasm32"))] @@ -209,20 +273,12 @@ fn start_jobs(h: &mut HomeState) { return; } let mut keys = std::mem::take(&mut h.queued); - // Cached recents first, then cold recents, then samples. A sample must never hold up - // pictures of the user's work; a cold file must not hold up already cached pictures. - keys.sort_by_key(|k| { - if k.starts_with("sample:") { - 2 - } else if cache_path(k).is_some_and(|p| p.exists()) { - 0 - } else { - 1 - } - }); let (tx, rx) = std::sync::mpsc::channel(); let spawned = std::thread::Builder::new().name("thumbnails".into()).spawn(move || { - for k in keys { + // Prefer local PNGs; even the metadata checks belong off the window thread. + keys.sort_by_key(|k| !cache_path(k).is_some_and(|p| p.exists())); + let Some(cold) = read_pictures(keys, &tx) else { return }; + for k in cold { let made = std::panic::catch_unwind(|| make(&k)).unwrap_or((k, None, None)); if tx.send(made).is_err() { return; @@ -234,6 +290,26 @@ fn start_jobs(h: &mut HomeState) { } } +#[cfg(not(target_arch = "wasm32"))] +fn start_sample(h: &mut HomeState) { + let Some(i) = h.wanted.filter(|i| !h.samples.contains_key(i)) else { return }; + if h.sample_rx.is_some() { + return; + } + let (tx, rx) = std::sync::mpsc::channel(); + if std::thread::Builder::new() + .name("selected-sample".into()) + .spawn(move || { + let key = format!("sample:{i}"); + let made = std::panic::catch_unwind(|| make(&key)).unwrap_or((key, None, None)); + let _ = tx.send(made); + }) + .is_ok() + { + h.sample_rx = Some(rx); + } +} + /// Take finished pictures and designs (one job per frame on the web, where there are no /// threads). fn poll(app: &mut SolveApp, ctx: &egui::Context) { @@ -242,6 +318,17 @@ fn poll(app: &mut SolveApp, ctx: &egui::Context) { let mut remembered = None; #[cfg(not(target_arch = "wasm32"))] { + start_sample(&mut app.home); + if let Some(rx) = &app.home.sample_rx { + match rx.try_recv() { + Ok(m) => { + done.push(m); + app.home.sample_rx = None; + } + Err(std::sync::mpsc::TryRecvError::Disconnected) => app.home.sample_rx = None, + Err(std::sync::mpsc::TryRecvError::Empty) => ctx.request_repaint_after(std::time::Duration::from_millis(16)), + } + } if let Some(rx) = &app.home.remembering { match rx.try_recv() { Ok(m) => { @@ -280,9 +367,12 @@ fn poll(app: &mut SolveApp, ctx: &egui::Context) { } } #[cfg(target_arch = "wasm32")] - if !app.home.queued.is_empty() { - let k = app.home.queued.remove(0); - done.push(make(&k)); + if let Some(i) = app.home.wanted { + done.push(make(&format!("sample:{i}"))); + ctx.request_repaint(); + } else if !app.home.queued.is_empty() { + let key = app.home.queued.remove(0); + done.push(make(&key)); ctx.request_repaint(); } for (key, img, session) in done { @@ -290,8 +380,10 @@ fn poll(app: &mut SolveApp, ctx: &egui::Context) { app.home.wanted = None; app.set_status(format!("the sample could not be built ({key})"), true); } - let tex = img.map(|i| ctx.load_texture(format!("thumb:{key}"), i, egui::TextureOptions::LINEAR)); - app.home.thumbs.insert(key.clone(), tex); + // A failed sample build does not discard its shipped preview. + if img.is_some() || !app.home.thumbs.contains_key(&key) { + install(&mut app.home, ctx, &key, img); + } if let (Some(s), Some(i)) = (session, key.strip_prefix("sample:").and_then(|i| i.parse::().ok())) { app.home.samples.insert(i, s); } @@ -301,6 +393,9 @@ fn poll(app: &mut SolveApp, ctx: &egui::Context) { { app.home.wanted = None; open_sample(app, i); + } else if app.home.wanted.is_some() { + // A selection can change while another sample finishes; schedule the next build. + ctx.request_repaint_after(std::time::Duration::from_millis(16)); } } @@ -321,10 +416,11 @@ pub fn open_sample(app: &mut SolveApp, i: usize) { crate::documents::adopt(app, copy); app.home.open = false; } - None => { + None if i < solidcraft_engine::sample::samples().len() => { + app.home.open = true; app.home.wanted = Some(i); - want(&mut app.home, &format!("sample:{i}")); } + None => {} } } @@ -342,11 +438,12 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { poll(app, ui.ctx()); let t = Tokens::get(); let samples = solidcraft_engine::sample::samples(); - // In the browser a picture blocks the page while it builds (no threads) and a kernel - // failure there can't be caught: samples are built when they are opened. - if !cfg!(target_arch = "wasm32") { - for i in 0..samples.len() { - want(&mut app.home, &format!("sample:{i}")); + // Embedded previews are available on the first frame, including on the web. No model + // scripts, filesystem reads or GPU readbacks are needed to show the sample cards. + for i in 0..samples.len() { + let key = format!("sample:{i}"); + if !app.home.thumbs.contains_key(&key) { + install(&mut app.home, ui.ctx(), &key, sample_picture(i)); } } let recent = app.home.recent.clone(); @@ -569,6 +666,46 @@ fn card(ui: &mut egui::Ui, pic: Pic, name: &str, sub: &str, dim: bool) -> egui:: mod tests { use super::*; + #[test] + fn shipped_sample_pictures_are_bounded_and_match_the_current_scripts() { + use sha2::{Digest, Sha256}; + let hashes: Vec = serde_json::from_str(include_str!("../../../assets/samples/exports/scripts.json")).unwrap(); + let samples = solidcraft_engine::sample::samples(); + assert_eq!(samples.len(), SAMPLE_PICTURES.len()); + assert_eq!(hashes.len(), samples.len()); + for (i, sample) in samples.iter().enumerate() { + let script = serde_json::to_vec(&(sample.script)()).unwrap(); + assert_eq!(hashes.get(i).unwrap(), &format!("{:x}", Sha256::digest(script)), "regenerate the preview for {}", sample.name); + assert_eq!(sample_picture(i).unwrap().size, THUMB); + } + assert!(sample_picture(samples.len()).is_none()); + } + + /// Rebuild the shipped pictures from the authoritative sample command scripts. + #[cfg(not(target_arch = "wasm32"))] + #[test] + #[ignore = "asset authoring: writes assets/samples/exports"] + fn regenerate_sample_thumbnails() { + use sha2::{Digest, Sha256}; + assert!(crate::gpu::test_picture_renderer()); + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/samples/exports"); + std::fs::create_dir_all(&dir).unwrap(); + let mut hashes = Vec::new(); + for (i, sample) in solidcraft_engine::sample::samples().into_iter().enumerate() { + let began = std::time::Instant::now(); + let script = (sample.script)(); + let mut session = Session::default(); + session.run_script(&script).unwrap(); + let image = thumbnail(&session).unwrap(); + let rgba = image.pixels.iter().flat_map(|p| p.to_srgba_unmultiplied()).collect(); + let png = solidcraft_engine::render::png(THUMB[0], THUMB[1], rgba).unwrap(); + std::fs::write(dir.join(format!("{i}.png")), png).unwrap(); + hashes.push(format!("{:x}", Sha256::digest(serde_json::to_vec(&script).unwrap()))); + eprintln!("{}: {:.3} s", sample.name, began.elapsed().as_secs_f64()); + } + std::fs::write(dir.join("scripts.json"), serde_json::to_vec_pretty(&hashes).unwrap()).unwrap(); + } + #[cfg(not(target_arch = "wasm32"))] #[test] fn cached_recent_uses_a_separate_png_without_reading_or_changing_design_json() { @@ -584,7 +721,7 @@ mod tests { let mut s = Session::default(); s.execute("solid.box", &serde_json::json!({"length":10,"width":10,"height":10})).unwrap(); s.path = Some(key.clone()); - let image = remember(&s).unwrap(); + let image = remember_file(&s, &key).unwrap(); let png = cache_path(&key).unwrap(); assert_eq!(std::fs::read(&path).unwrap(), bytes); let (_, cached_image, session) = make(&key); @@ -625,6 +762,102 @@ mod tests { assert!(decode_thumbnail(vec![0; 24]).is_none()); } + /// STEP opens deliberately have no save path, but their source still gets a cache entry. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn imported_step_picture_is_cached_under_its_source_without_a_save_path() { + if !crate::gpu::test_picture_renderer() { + return; + } + let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let path = std::env::temp_dir().join(format!("solidcraft-import-thumb-{}-{nonce}.step", std::process::id())); + let key = path.to_string_lossy().into_owned(); + let mut part = Session::default(); + part.execute("solid.box", &serde_json::json!({"length":10,"width":20,"height":30})).unwrap(); + part.execute("file.export", &serde_json::json!({"path":key})).unwrap(); + let original = std::fs::read(&path).unwrap(); + let mut opened = Session::default(); + opened.execute("doc.open", &serde_json::json!({"path":key})).unwrap(); + assert!(opened.path.is_none(), "an imported file is an unsaved design"); + let mut home = HomeState::default(); + remember_source(&mut home, &opened, &key); + let (made_key, image, rebuilt) = home.remembering.take().unwrap().recv_timeout(std::time::Duration::from_secs(30)).unwrap(); + assert_eq!(made_key, key); + assert!(rebuilt.is_none()); + let image = image.unwrap(); + assert!(opened.path.is_none(), "caching must not turn Save into an overwrite of the STEP source"); + let png = cache_path(&key).unwrap(); + assert_eq!(cached(&key).unwrap().pixels, image.pixels); + assert_eq!(std::fs::read(&path).unwrap(), original); + let (_, picture, rebuilt) = make(&key); + assert!(rebuilt.is_none()); + assert_eq!(picture.unwrap().pixels, image.pixels); + std::fs::write(&path, b"file replaced").unwrap(); + assert!(cached(&key).is_none()); + std::fs::remove_file(path).unwrap(); + std::fs::remove_file(png).unwrap(); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn portable_pictures_are_sent_before_any_cold_recent_is_built() { + if !crate::gpu::test_picture_renderer() { + return; + } + let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let path = std::env::temp_dir().join(format!("solidcraft-fast-thumb-{}-{nonce}.solidcraft", std::process::id())); + let key = path.to_string_lossy().into_owned(); + let mut s = Session::default(); + s.execute("solid.box", &serde_json::json!({"length":10,"width":20,"height":30})).unwrap(); + for b in &s.world_state().bodies { + b.mesh(); + } + let bytes = s.design_container(solidcraft_engine::io::DesignCompression::Fast, false, true).unwrap(); + std::fs::write(&path, bytes).unwrap(); + let cold = format!("missing-cold-file-{nonce}.step"); + let (tx, rx) = std::sync::mpsc::channel(); + let misses = read_pictures(vec![cold.clone(), key.clone()], &tx).unwrap(); + assert_eq!(misses, vec![cold]); + let (ready, picture, rebuilt) = rx.try_recv().unwrap(); + assert_eq!(ready, key); + assert!(picture.is_some() && rebuilt.is_none()); + assert!(cached(&key).is_none(), "the portable picture did not rebuild the design"); + std::fs::remove_file(path).unwrap(); + } + + #[test] + fn first_home_frame_shows_all_samples_without_building_any_models() { + let mut h = crate::scenario::Harness::new(); + h.app.home.show(0); + h.frames(1); + assert_eq!(h.app.home.ready_samples(), solidcraft_engine::sample::samples().len()); + assert!(h.app.home.samples.is_empty()); + assert!(h.app.home.queued.is_empty()); + #[cfg(not(target_arch = "wasm32"))] + assert!(h.app.home.sample_rx.is_none() && h.app.home.rx.is_none()); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn selecting_a_sample_does_not_wait_for_a_running_cold_recent() { + let mut app = SolveApp::new(Session::default(), Default::default()); + let (_blocked_worker, rx) = std::sync::mpsc::channel(); + app.home.rx = Some(rx); + app.home.open = false; + let ctx = egui::Context::default(); + open_sample(&mut app, 1); + assert!(app.home.open, "a programmatic selection from a document must start the sample job too"); + let began = std::time::Instant::now(); + while app.home.open && began.elapsed() < std::time::Duration::from_secs(30) { + poll(&mut app, &ctx); + std::thread::sleep(std::time::Duration::from_millis(10)); + } + assert!(!app.home.open, "the recent worker is still blocked, but the sample must open"); + assert!(app.home.rx.is_some()); + assert_eq!(app.session.doc.name, "Sheet Metal Bracket"); + assert!(!app.session.is_dirty()); + } + #[test] fn recent_list_is_newest_first_and_bounded() { let mut h = HomeState::default(); From bdfaf690d70d869dd349af3b8fdfb8f33b14d579 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Tue, 20 Oct 2026 03:32:45 +0000 Subject: [PATCH 165/225] Regenerate THIRD-PARTY-LICENSES.txt and docs/features.md [skip ci] --- THIRD-PARTY-LICENSES.txt | 81 ++++++++++++++++++++++++---------------- 1 file changed, 48 insertions(+), 33 deletions(-) diff --git a/THIRD-PARTY-LICENSES.txt b/THIRD-PARTY-LICENSES.txt index 47dd4f925..e4e5d94d2 100644 --- a/THIRD-PARTY-LICENSES.txt +++ b/THIRD-PARTY-LICENSES.txt @@ -1,6 +1,6 @@ Third-party software in SolidCraft -SolidCraft (the desktop app, solidcraft-cli and the web app) is built from the 552 crates below. +SolidCraft (the desktop app, solidcraft-cli and the web app) is built from the 553 crates below. Generated by `cargo xtask licences` from Cargo.lock and the crates' own licence files. SolidCraft's own licence is in LICENSE-MIT and LICENSE-APACHE, and NOTICE. @@ -75,6 +75,7 @@ cbc 0.1.2 (MIT OR Apache-2.0) cfg-if 1.0.5 (MIT OR Apache-2.0) cgl 0.3.2 (MIT / Apache-2.0) cgmath 0.18.0 (Apache-2.0) +chardetng 0.1.17 (Apache-2.0 OR MIT) chrono 0.4.45 (MIT OR Apache-2.0) cipher 0.4.4 (MIT OR Apache-2.0) clipboard-win 5.4.1 (BSL-1.0) @@ -1821,8 +1822,8 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================================================ approx 0.4.0, as-raw-xcb-connection 1.0.1, atspi 0.29.0, atspi-common 0.13.0, atspi-proxies 0.13.0, -cgmath 0.18.0, codespan-reporting 0.13.1, encoding_rs 0.8.42, kurbo 0.13.1, multiversion_no_op -1.0.0, nohash-hasher 0.2.0, peniko 0.6.1, polycool 0.4.0, raw-window-metal 1.1.0, +cgmath 0.18.0, chardetng 0.1.17, codespan-reporting 0.13.1, encoding_rs 0.8.42, kurbo 0.13.1, +multiversion_no_op 1.0.0, nohash-hasher 0.2.0, peniko 0.6.1, polycool 0.4.0, raw-window-metal 1.1.0, rustls-platform-verifier 0.7.1, self_cell 1.3.0, siphasher 1.0.4, spade 2.15.1, static_assertions 1.1.0, ureq 3.4.2, ureq-proto 0.6.4, utf8_iter 1.0.4, x11rb 0.13.2, x11rb-protocol 0.13.2, zeroize 1.9.1, zeroize_derive 1.5.0, zune-core 0.5.3, zune-jpeg 0.5.15 @@ -3324,6 +3325,50 @@ http://www.apache.org/licenses/LICENSE-2.0> or the MIT license option. All files in the project carrying such notice may not be copied, modified, or distributed except according to those terms. +================================================================================ +chardetng 0.1.17 +================================================================================ + +chardetng is copyright Mozilla Foundation. + +Licensed under the Apache License, Version 2.0 + or the MIT +license , +at your option. All files in the project carrying such +notice may not be copied, modified, or distributed except +according to those terms. + +================================================================================ +chardetng 0.1.17, encoding_rs 0.8.42, multiversion_no_op 1.0.0, utf8_iter 1.0.4 +================================================================================ + +Copyright Mozilla Foundation + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + ================================================================================ chrono 0.4.45 ================================================================================ @@ -5010,36 +5055,6 @@ source code, are licensed under the BSD 3-Clause License Test code within encoding_rs is dedicated to the Public Domain when so designated (see the individual files for PD/CC0-dedicated sections). -================================================================================ -encoding_rs 0.8.42, multiversion_no_op 1.0.0, utf8_iter 1.0.4 -================================================================================ - -Copyright Mozilla Foundation - -Permission is hereby granted, free of charge, to any -person obtaining a copy of this software and associated -documentation files (the "Software"), to deal in the -Software without restriction, including without -limitation the rights to use, copy, modify, merge, -publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software -is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice -shall be included in all copies or substantial portions -of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF -ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED -TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT -SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR -IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. - ================================================================================ enumflags2 0.7.12 ================================================================================ From 14b75294652e06ee7b9e18748005a00d60ec9f15 Mon Sep 17 00:00:00 2001 From: Irakli Kourtis Date: Tue, 20 Oct 2026 03:22:30 +0000 Subject: [PATCH 166/225] Loft guide rails (#201) (#3371) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * kernel: loft guide rails (#201) A loft follows one or two guide rails between its sections: stations are added between each two sections, each the plain loft there moved so that the point a rail guides lands where the rail crosses the station's plane — turned about the loft's direction and scaled (or stretched across to the rail) with one rail, carried, turned and sized between two. The sections and caps stay exact; the smooth loft runs through sections and stations. Solid and sheet lofts. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LGeCa5jWWdroMWvXxN3LLM * doc, engine: solid.loft and surface.loft take guide rails (#201) `rails` (one or two {sketch, curves}) and `rail_fit` (scale | stretch), stored on Loft and SurfaceLoft (one pending format note), parsed by the sweep's rail parser (now shared) and built through the kernel's railed loft. Rails on a loft to a point, or on a surface loft with edge sections or end continuity, are refused as not supported yet. The rails' sketches are walked as the feature's references and their components placed like a sweep's. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LGeCa5jWWdroMWvXxN3LLM * ui: Rail, Second Rail and Rail Fit in the Loft and Surface Loft dialogs (#201) The rail inputs and fit row the sweep dialogs have, shared through dialogs_sweep; Edit Feature brings the rails back. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LGeCa5jWWdroMWvXxN3LLM * docs(roadmap): loft guide rails (#201) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LGeCa5jWWdroMWvXxN3LLM * loft rails: review clean-ups (#201) - Sweep and loft rails share one turn-and-size map (`sweep_path::rail_frame`). - A station's middle and the loft's direction come from one curve through the sections' middles (exact derivative) instead of two more plain-loft evaluations per station; at most 33 wires, so railed faces stay light. - Nearest points on a section use `param_on` (kept only where the search comes nearer); the size uses `Aabb3`; one B-spline builder; anchors keep their nudge. - The railed and plain lofts share one path in `loft_with_rails` and `loft_sheet_with_rails`. - The engine leaves the not-yet-supported refusals to the design's evaluation; both lofts start their rails from the first section's first point. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LGeCa5jWWdroMWvXxN3LLM * loft rails: refuse rails on sections with holes, with a test (#201) Main's lofts now take sections with holes (#2447); rails shape only the outlines, so a railed loft of rings is refused until the rails carry the holes too. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LGeCa5jWWdroMWvXxN3LLM --------- Co-authored-by: jyviko <2501648+jyviko@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- ROADMAP.md | 2 +- crates/doc/src/document.rs | 16 +- crates/doc/src/eval.rs | 66 ++-- crates/doc/src/eval_surface.rs | 14 +- crates/doc/src/feature_walk_tests/fixtures.rs | 5 +- .../src/feature_walk_tests/golden_refs.txt | 8 +- .../src/format/pending/loft-guide-rails.rs | 3 + crates/engine/src/cmd/features.rs | 45 ++- crates/engine/src/cmd/loft_rails_tests.rs | 163 ++++++++ crates/engine/src/cmd/surface.rs | 5 +- crates/kernel/src/build.rs | 38 +- crates/kernel/src/curveblend.rs | 2 +- crates/kernel/src/curvecorner.rs | 4 +- crates/kernel/src/lib.rs | 9 +- crates/kernel/src/loft_rails.rs | 349 ++++++++++++++++++ crates/kernel/src/loft_rails_tests.rs | 169 +++++++++ crates/kernel/src/surfaces.rs | 28 +- crates/kernel/src/sweep_path.rs | 34 +- crates/ui-egui/src/dialogs.rs | 25 +- crates/ui-egui/src/dialogs_surface.rs | 30 +- crates/ui-egui/src/dialogs_sweep.rs | 51 ++- crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/loft_rails_dialog_tests.rs | 85 +++++ 23 files changed, 1034 insertions(+), 119 deletions(-) create mode 100644 crates/doc/src/format/pending/loft-guide-rails.rs create mode 100644 crates/engine/src/cmd/loft_rails_tests.rs create mode 100644 crates/kernel/src/loft_rails.rs create mode 100644 crates/kernel/src/loft_rails_tests.rs create mode 100644 crates/ui-egui/src/loft_rails_dialog_tests.rs diff --git a/ROADMAP.md b/ROADMAP.md index 6f102acf5..327201486 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -57,7 +57,7 @@ PCB / Package, Render, Animation, Simulation, Manufacture/CAM, Drawings. | M5 | Persistent naming of faces and edges (docs/book/src/dev/naming.md): faces named from their exact kernel-reported history (sketch curve sides, caps, revolve sections, primitive sides, blends, shell inner walls, pattern/mirror copies; split pieces told apart by the faces around them, lumps of a cut body named after their faces), edges by their faces; fillets/chamfers, sketches on faces, shell/draft/offset/replace faces, hole placements, joint origins and face appearances resolve by name first and warn when the entity split or vanished: done. sheet metal edges by base sketch line and flange side, shell inner faces, sweep and loft roles: done. kernel-reported face history: done (merged faces answer to every name; operations without history yet fall back to geometric names, flagged unverified; format 14 keeps older designs' geometric names). Left: history through sheet metal, plastic, surface and emboss features; FaceSource certificates through history | in progress | 20 | | M6 | UI depth: selection feedback and origin (done), timeline editing (done: hover and selection highlight modifier faces, including fillets and chamfers; edit feature, history marker drag, dependency-checked single and multi-item reorder, suppress, rename, delete with dependents, re-resolved references; redefining selections refreshes persistent edge/face references while retaining feature identity and dimension names; optional compact named left feature history with rollback bar, multi-selection and persistent folders above the parts browser), right-docked dialogs (done), live previews for every feature dialog (done), keyboard-first commands with on-canvas value boxes and sketch inline dimensions (done), drag manipulators with automatic join/cut (done: extrude incl. two sides, fillet, shell, hole depth, move, pattern spacing, revolve rotator, extrude taper), dark theme (done), right-click menu with Repeat (done), measure tool (done), section analysis (done), selection filter (done), drag-solve of sketch points (done); appearance controls now preserve body/face/component targeting, named transparent looks, reuse/search and override removal; preferences | in progress | 6 | | M7 | Thin extrude (walls along open or closed curves: centre, inside, outside or two sides; mitred corners, crossing walls joined; #721), sweep, loft (incl. to a point), rib and web (to next / depth), emboss (planar faces and exact radial emboss/deboss of bounded orthogonal profiles on complete exterior cylinders/sleeves), thread (cosmetic, and modelled M3–M20 outside and inside: the ISO profile screwed in as a faceted cut), coil (smooth B-spline helical walls), pipe, pattern on path, patterns of bodies and components, replace face (parallel), align, remove, feature copy/paste: done. Unique eligible cylindrical targets are inferred for new Emboss features. Left: general curved-face emboss and exact (unfaceted) modelled threads | in progress | 12 | -| M8 | Surface workspace (#772). Done: Patch (sketch regions; edge loops filled G0, plus `crown`), Stitch, Thicken (planes and cylinders), Extend (straight edges of planar surfaces), Trim (by a plane, a face or sketch curves swept onto the surface, keeping a side or the picked regions; mutual trim of two surfaces, extended to meet and stitched, #767), Delete Face (healing), Boundary Fill, zebra/draft/curvature-map analysis, Surface Extrude/Revolve/Sweep/Loft from open and closed curves, Offset, Unstitch and Reverse Normal; the continuity-driven core (`kernel/src/bridge.rs`, G0–G3 Hermite rows) with **Blend** (`surface.blend`, #764), **Match** (`surface.match`), **Boundary** (`surface.boundary`, #763 — two sketch curves exact with G0–G3, three or four as the flat patch of their loop, and curve networks: Coons and Gordon surfaces through sketch, 3D-sketch or edge curves, a point for a three-sided side, G1/G2 against the faces along one direction's edges, joined into their body on request; G1/G2 on two sides that meet at a corner waits for the Gregory-type corner), **Fair** (`surface.fair`, CV fairing), **continuity analysis** (`inspect.continuity`, #770; a toolbar tool with edge markers and a legend, and curvature combs along face isocurves) and a multi-section **loft** with per-end continuity and crown. Also in the Class-A pass: G1…G4 blend curves in the sketch, chord and variable-radius fillets on curved edges (with honest refusals where the fit cannot hold), and a G2 corner patch where filleted edges meet (kernel; the command refuses until the patch's sections can be sewn to the blends' contacts). Left: bias/form-factor fillet sections (design recorded), a Gregory-type corner, surface Fillet between separate surface bodies (#769), Ruled (#762), Untrim (#761), curved-face Extend (#760), loft guide rails (#201; sweep guide rails and two-rail sweeps are done, #771), and every remaining #757–#772 item | deferred | — | +| M8 | Surface workspace (#772). Done: Patch (sketch regions; edge loops filled G0, plus `crown`), Stitch, Thicken (planes and cylinders), Extend (straight edges of planar surfaces), Trim (by a plane, a face or sketch curves swept onto the surface, keeping a side or the picked regions; mutual trim of two surfaces, extended to meet and stitched, #767), Delete Face (healing), Boundary Fill, zebra/draft/curvature-map analysis, Surface Extrude/Revolve/Sweep/Loft from open and closed curves, Offset, Unstitch and Reverse Normal; the continuity-driven core (`kernel/src/bridge.rs`, G0–G3 Hermite rows) with **Blend** (`surface.blend`, #764), **Match** (`surface.match`), **Boundary** (`surface.boundary`, #763 — two sketch curves exact with G0–G3, three or four as the flat patch of their loop, and curve networks: Coons and Gordon surfaces through sketch, 3D-sketch or edge curves, a point for a three-sided side, G1/G2 against the faces along one direction's edges, joined into their body on request; G1/G2 on two sides that meet at a corner waits for the Gregory-type corner), **Fair** (`surface.fair`, CV fairing), **continuity analysis** (`inspect.continuity`, #770; a toolbar tool with edge markers and a legend, and curvature combs along face isocurves) and a multi-section **loft** with per-end continuity and crown, and guide rails on solid and surface lofts (one or two, scaling or stretching the sections between; #201). Also in the Class-A pass: G1…G4 blend curves in the sketch, chord and variable-radius fillets on curved edges (with honest refusals where the fit cannot hold), and a G2 corner patch where filleted edges meet (kernel; the command refuses until the patch's sections can be sewn to the blends' contacts). Left: bias/form-factor fillet sections (design recorded), a Gregory-type corner, surface Fillet between separate surface bodies (#769), Ruled (#762), Untrim (#761), curved-face Extend (#760), and every remaining #757–#772 item | deferred | — | | M9 | Components and assemblies: New Component / Create Components from Bodies, active component, per-component origin/bodies/sketches/timeline entries, occurrences with transforms, Copy/Paste vs Paste New, nested Browser tree with visibility and isolate; Ground, Move/Copy of occurrences, joints (rigid, revolute, slider, cylindrical, pin-slot, planar, ball) by joint origins with limits and Drive Joints, closed kinematic loops (four-bar, slider-crank: the loop's other joints follow the driven one on its branch, and driving stops where a loop can no longer close), cams (`joint.cam`: a revolute cam drives a slider or revolute follower along a closed sketch profile or the cam's edges, knife, roller or flat followers, worked out again when the profile changes; drives, studies, closed loops, contact sets), As-built Joint, Rigid Group, Contact Sets (driving and motion studies stop where bodies in a set would pass through each other), Motion Study (joint values keyed along a timeline, playback, export of occurrence positions as JSON/CSV), motion analysis (joint values and a point's path charted over a study as value, velocity and acceleration; the parts that collide along a study, with the steps where they do), Exploded views (automatic or by hand, shown without changing placements); interference, per-component physical properties; STEP with assembly structure; URDF export for robot simulators (links with meshes, mass and inertia; joint chains whose values match Drive Joints; docs/urdf.md). Physical properties now measure material-aware component/occurrence placements, descendants and repeated instances, including pending moves and body reassignment offsets; contact geometry and automatic exploded centres respect those offsets. Groundwork done: component tree, occurrences with transforms (instances, Paste New), world placement, active component as authoring frame, ground, Capture/Revert Position, moving bodies and sketches. UI: ASSEMBLE panel dialogs for New Component, Joint (snaps on faces, edges, circles and vertices; animated motion preview; offsets, flip, limits), As-built Joint, Joint Origin, Rigid Group, Drive Joints (live slider), Motion Link, Cam and Interference (overlaps shown red); joints in the timeline and the Browser | in progress | 32 | | M10 | Sheet metal: flange (base, edge, contour), hem, unfold/refold, convert, flat pattern + DXF, rules: done. PLASTIC enclosure subset: Boss, Rib, Web, Lip/Groove, Snap Fit, Rest, Plastic Rules (library, edit, assign; rule draft and clearance as feature defaults): done, tested against hand-computed geometry. UI: SHEET METAL and PLASTIC tabs with dialogs (live preview, Edit Feature, pre-selection) for Flange, Hem, Unfold/Refold, Convert, Sheet Metal Rules, Create Flat Pattern (flat view with bend lines, bend table CSV/JSON and DXF export with exact circle/arc/line cutouts), Boss, Lip/Groove, Snap Fit, Rest, Manage and Assign Plastic Rules; Fold (bend along a sketch line); flanges meeting at a corner closed at any angle with the rule's gap; edge flanges with their own angle and height per edge in one feature; corner reliefs (notch, round, rectangular, tear) chosen by the rule; Convert to Sheet Metal from a solid or shelled body by its bend edges (flat faces, sharp bends) | in progress | 36 | | M11 | 2D drawings | deferred | — | diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 76e9a2f5b..6e4906c86 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -301,8 +301,8 @@ impl SweepOrientation { } } -/// A sweep's guide rail: a chain of curves of a sketch, followed from the end nearest the path's -/// start. +/// A sweep's or a loft's guide rail: a chain of curves of a sketch, followed from the end nearest +/// the path's start (the loft's first section). #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, solidcraft_derive::Walk)] pub struct SweepRail { pub sketch: SketchId, @@ -742,6 +742,12 @@ pub enum FeatureKind { operation: Operation, #[serde(default, skip_serializing_if = "Vec::is_empty")] targets: Vec, + /// Guide rails (one or two) the loft follows between its sections. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + rails: Vec, + /// How the rails reshape the sections between. + #[serde(default, skip_serializing_if = "RailFit::is_scale")] + rail_fit: RailFit, }, /// Sweep profiles along a chain of sketch curves. Sweep { @@ -1374,6 +1380,12 @@ pub enum FeatureKind { continuity: [Continuity; 2], #[serde(default, skip_serializing_if = "loft_crown_is_plain")] crown: [f64; 2], + /// Guide rails (one or two) the loft follows between its sections. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + rails: Vec, + /// How the rails reshape the sections between. + #[serde(default, skip_serializing_if = "RailFit::is_scale")] + rail_fit: RailFit, }, /// The faces at `faces` copied out at a signed `distance` along their normals as a new /// surface body (0 copies them); `chain` takes each pick's whole smooth chain of faces; diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 3c254beb5..4d7a7c69e 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -1071,23 +1071,26 @@ fn placement_digest(doc: &Document, f: &Feature) -> u64 { }; let wired = |id: &crate::SketchId| doc.sketch(id.0).is_ok_and(|sketch| !sketch.wires.is_empty()); let rails: &[crate::SweepRail] = match &f.kind { - FeatureKind::Sweep { rails, .. } | FeatureKind::SurfaceSweep { rails, .. } => rails, + FeatureKind::Sweep { rails, .. } + | FeatureKind::SurfaceSweep { rails, .. } + | FeatureKind::Loft { rails, .. } + | FeatureKind::SurfaceLoft { rails, .. } => rails, _ => &[], }; - if let Some(path) = path - && (wired(&path) || rails.iter().any(|r| wired(&r.sketch))) - { + if path.as_ref().is_some_and(wired) || rails.iter().any(|r| wired(&r.sketch)) { let mut hash = std::collections::hash_map::DefaultHasher::new(); - let owner = doc.feature(path.0).map(|feature| feature.component).unwrap_or(0); + let owner = path.and_then(|path| doc.feature(path.0)).map(|feature| feature.component).unwrap_or(0); for frame in [doc.component_transform(f.component), doc.component_transform(owner)] { frame.iter().flatten().for_each(|value| value.to_bits().hash(&mut hash)); } - if let FeatureKind::Sweep { sketch, rails, .. } | FeatureKind::SurfaceSweep { sketch, rails, .. } = &f.kind { - // The profile's and the rails' components place them too. - for sketch in std::iter::once(sketch).chain(rails.iter().map(|r| &r.sketch)) { - let owner = doc.feature(sketch.0).map(|feature| feature.component).unwrap_or(0); - doc.component_transform(owner).iter().flatten().for_each(|value| value.to_bits().hash(&mut hash)); - } + // A sweep's profile and the rails' components place them too. + let profile = match &f.kind { + FeatureKind::Sweep { sketch, .. } | FeatureKind::SurfaceSweep { sketch, .. } => Some(sketch), + _ => None, + }; + for sketch in profile.into_iter().chain(rails.iter().map(|r| &r.sketch)) { + let owner = doc.feature(sketch.0).map(|feature| feature.component).unwrap_or(0); + doc.component_transform(owner).iter().flatten().for_each(|value| value.to_bits().hash(&mut hash)); } return hash.finish(); } @@ -3769,8 +3772,11 @@ fn feature_tools_with_constructor( let m = crate::rigid(Vec3::ZERO, origin_w, axis_w, -start); regions.iter().zip(bodies).map(|(r, body)| Ok(tool(r, kernel::transform_matrix(&body, m)?, Some(&body)))).collect() } - FeatureKind::Loft { sections, .. } if sections.iter().any(|s| s.point.is_some()) => { + FeatureKind::Loft { sections, rails, .. } if sections.iter().any(|s| s.point.is_some()) => { // A profile lofted to a sketch point (an apex). + if !rails.is_empty() { + return Err(DocError::Invalid("not supported yet: guide rails on a loft to a point".into())); + } let [a, b] = §ions[..] else { return Err(DocError::Invalid("not supported yet: a point section in a loft of more than two".into())) }; let (prof, pt) = if a.point.is_some() { (b, a) } else { (a, b) }; let ss = st.sketch(prof.sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {}", prof.sketch)))?; @@ -3823,7 +3829,7 @@ fn feature_tools_with_constructor( let pitch = if *clockwise { -p } else { p }; Ok(unnamed(vec![kernel::sweep_helix(&plane, ®ion, *base, axis, pitch, n)?])) } - FeatureKind::Loft { sections, .. } => { + FeatureKind::Loft { sections, rails, rail_fit, .. } => { let mut secs = Vec::new(); let mut sketches = Vec::new(); for sec in sections { @@ -3837,7 +3843,19 @@ fn feature_tools_with_constructor( } // Its caps are the first and last sections, its sides named by the curves they run // between. - let body = kernel::loft_regions(&secs)?; + let body = if rails.is_empty() { + kernel::loft_regions(&secs)? + } else { + // Rails shape the sections' outlines; sections with holes wait for rails that + // carry the holes too. + if secs.iter().any(|(_, r)| !r.holes.is_empty()) { + return Err(DocError::Invalid("not supported yet: guide rails on a loft whose sections have holes".into())); + } + let outlines: Vec<_> = secs.iter().map(|(p, r)| (*p, r.outer.clone())).collect(); + // The rails run from the end at the first section. + let start = outlines.first().and_then(|(p, lp)| lp.segs.first().map(|seg| p.to_world(seg.start()))).unwrap_or_default(); + kernel::loft_with_rails(&outlines, &rail_polylines(doc, st, rails, f.component, start)?, kernel_rail_fit(*rail_fit))? + }; let roles = crate::lineage::SectionRoles { sections: sketches.into_iter().zip(secs.iter().map(|(_, r)| std::iter::once(&r.outer).chain(&r.holes).collect())).collect(), }; @@ -3950,20 +3968,24 @@ pub(crate) fn sweep_control( Some(k) => val(vals, k, Kind::Unitless)?, None => 1.0, }; - let rail_fit = match rail_fit { - crate::RailFit::Scale => kernel::RailFit::Scale, - crate::RailFit::Stretch => kernel::RailFit::Stretch, - }; - let ctl = kernel::SweepControl { orientation, twist, scale, rails, rail_fit }; + let ctl = kernel::SweepControl { orientation, twist, scale, rails, rail_fit: kernel_rail_fit(rail_fit) }; ctl.check()?; Ok(ctl) } -/// A sweep's guide rails as polylines in the feature's frame, each a chain of its sketch's curves -/// (planar or 3D) from the end nearest `start`, the start of the path. +/// How guide rails reshape a sweep's profile or a loft's sections, for the kernel. +pub(crate) fn kernel_rail_fit(fit: crate::RailFit) -> kernel::RailFit { + match fit { + crate::RailFit::Scale => kernel::RailFit::Scale, + crate::RailFit::Stretch => kernel::RailFit::Stretch, + } +} + +/// A sweep's or a loft's guide rails as polylines in the feature's frame, each a chain of its sketch's curves +/// (planar or 3D) from the end nearest `start` (the start of the path, the loft's first section). pub(crate) fn rail_polylines(doc: &Document, st: &ModelState, rails: &[crate::SweepRail], consumer: u64, start: Vec3) -> Result>> { if rails.len() > 2 { - return Err(DocError::Invalid("a sweep takes one or two guide rails".into())); + return Err(DocError::Invalid("a sweep or a loft takes one or two guide rails".into())); } rails .iter() diff --git a/crates/doc/src/eval_surface.rs b/crates/doc/src/eval_surface.rs index c8c3145fb..b9d53cfc8 100644 --- a/crates/doc/src/eval_surface.rs +++ b/crates/doc/src/eval_surface.rs @@ -388,11 +388,14 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, push_sheet(st, f, traced); Ok(()) } - FeatureKind::SurfaceLoft { sections, continuity, crown } => { + FeatureKind::SurfaceLoft { sections, continuity, crown, rails, rail_fit } => { // A loft with edge chains for sections, or one that has to leave its ends a particular // way, is built through `loft_blend` from the frames of every section; the plain one // (sketch chains only, both ends G0) is the loft of old. if *continuity != [kernel::Continuity::G0, kernel::Continuity::G0] || sections.iter().any(|s| s.body.is_some()) { + if !rails.is_empty() { + return Err(DocError::Invalid("not supported yet: guide rails on a loft with edge sections or end continuity".into())); + } return loft_blend(st, f, sections, *continuity, *crown, doc); } let mut secs = Vec::with_capacity(sections.len()); @@ -417,7 +420,14 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, secs.push((ss.plane, chain)); sketches.push(ss); } - let body = kernel::loft_sheet(&secs)?; + let body = if rails.is_empty() { + kernel::loft_sheet(&secs)? + } else { + // The rails run from the end at the first section. + let start = secs.first().and_then(|(p, c)| c.first().map(|seg| p.to_world(seg.start()))).unwrap_or_default(); + let rails = crate::eval::rail_polylines(doc, st, rails, f.component, start)?; + kernel::loft_sheet_with_rails(&secs, &rails, crate::eval::kernel_rail_fit(*rail_fit))? + }; // Each wall named by the section curves it runs between, as a loft's sides are. let loops: Vec = secs.iter().map(|(_, c)| solidcraft_geom::Loop2 { segs: c.clone() }).collect(); let traced = crate::lineage::SectionRoles { sections: sketches.iter().zip(&loops).map(|(s, lp)| (s, vec![lp])).collect() }.tool(body); diff --git a/crates/doc/src/feature_walk_tests/fixtures.rs b/crates/doc/src/feature_walk_tests/fixtures.rs index ba9d31fdb..28c2da3e6 100644 --- a/crates/doc/src/feature_walk_tests/fixtures.rs +++ b/crates/doc/src/feature_walk_tests/fixtures.rs @@ -220,10 +220,11 @@ pub(super) fn with_refs(name: &str, mut v: Value) -> Value { "combine" => json!({"target": "B", "tools": ["B"]}), "pattern_rectangular" | "pattern_circular" | "pattern_path" | "mirror" => json!({"bodies": ["B"]}), "hole_simple" | "hole_drilled" | "hole_counterbore" | "hole_countersink" => json!({"points": {"sketch": 3, "ids": ["p"]}}), - "loft" => json!({"sections": [{"sketch": 4, "profiles": {"type": "all"}}, {"sketch": 5, "profiles": {"type": "all"}}], "targets": ["B"]}), + "loft" => json!({"sections": [{"sketch": 4, "profiles": {"type": "all"}}, {"sketch": 5, "profiles": {"type": "all"}}], "targets": ["B"], + "rails": [{"sketch": 6, "curves": ["l1"]}]}), "split" | "surface_trim" => json!({"tool": tool}), "split_line" => json!({"sketch": 6, "line": "l1"}), - "surface_loft" => json!({"sections": [{"sketch": 4}, {"sketch": 5}]}), + "surface_loft" => json!({"sections": [{"sketch": 4}, {"sketch": 5}], "rails": [{"sketch": 6, "curves": ["l1"]}]}), "split_face" => json!({"body": "B", "tool": tool, "sketch": 6}), "emboss" => json!({"face": {"body": "B", "at": o}, "targets": ["B"]}), "sheet_fold" => json!({"sketch": 7, "body": "B"}), diff --git a/crates/doc/src/feature_walk_tests/golden_refs.txt b/crates/doc/src/feature_walk_tests/golden_refs.txt index 5eeaff421..e6c3fcbdf 100644 --- a/crates/doc/src/feature_walk_tests/golden_refs.txt +++ b/crates/doc/src/feature_walk_tests/golden_refs.txt @@ -60,8 +60,8 @@ hole_countersink remap_refs: points.sketch thread loft - sketches: [4, 5] - remap_refs: sections[0].sketch, sections[1].sketch + sketches: [4, 5, 6] + remap_refs: rails[0].sketch, sections[0].sketch, sections[1].sketch remap_bodies: targets[0] sweep sketches: [1, 2] @@ -171,8 +171,8 @@ surface_sweep_options sketches: [1, 2] remap_refs: path_sketch, sketch surface_loft - sketches: [4, 5] - remap_refs: sections[0].sketch, sections[1].sketch + sketches: [4, 5, 6] + remap_refs: rails[0].sketch, sections[0].sketch, sections[1].sketch surface_blend remap_bodies: from.body surface_offset diff --git a/crates/doc/src/format/pending/loft-guide-rails.rs b/crates/doc/src/format/pending/loft-guide-rails.rs new file mode 100644 index 000000000..ab9457533 --- /dev/null +++ b/crates/doc/src/format/pending/loft-guide-rails.rs @@ -0,0 +1,3 @@ +//! Lofts (`Loft`, `SurfaceLoft`) take guide rails: `rails` (one or two `{sketch, curves}` chains, +//! as a sweep's) and `rail_fit` (`scale` or `stretch`). Both default to none and `scale`, so older +//! designs read unchanged. diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs index bfe0f3c91..4d5c01f8d 100644 --- a/crates/engine/src/cmd/features.rs +++ b/crates/engine/src/cmd/features.rs @@ -27,7 +27,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .at("SOLID", "CREATE") .icon("sweep") .params("sketch: profile sketch; profiles?; path_sketch: sketch; path: [curve ids in order]; orientation?: perpendicular (default: square to the path, turning with it) | parallel (as drawn: the profile moves without turning; the path must keep crossing its plane) | [x,y,z] (square to the path, its turn about the path fixed by this direction); twist?: angle expr (the profile turns this much about the path over its length; within 4 turns); scale?: expr (the profile's scale at the end, linear along the path; 0.01…100); rails?: [{sketch?: sketch (default path_sketch), curves: [curve ids in order]}] (guide rails, one or two, each meeting every plane square to the path once along it, from the end nearest the path's start: one rail turns the profile so its point where the rail starts stays on the rail and scales it with the rail's distance from the path; two rails carry it between them, its points where they start staying on both; rails take the default orientation, no twist and no scale, and a path without sharp corners); rail_fit?: scale (default: the profile grows and shrinks evenly) | stretch (only across to the rail, between the rails); operation?, targets?, name?, body_name?"), - CommandSpec::new("solid.loft", "Loft", loft).at("SOLID", "CREATE").icon("loft").params("sections: [{sketch, profiles?} | {sketch, point: id} (an apex)] (2…50, in order; matching hole counts, no holes at an apex); operation?, targets?, name?, body_name?"), + CommandSpec::new("solid.loft", "Loft", loft).at("SOLID", "CREATE").icon("loft").params("sections: [{sketch, profiles?} | {sketch, point: id} (an apex)] (2…50, in order; matching hole counts, no holes at an apex); rails?: [{sketch, curves: [ids in order]}] (one or two guide rails from the first section to the last, through every section's outline: the loft follows them between the sections; not with sections that have holes); rail_fit?: scale|stretch (default scale: with one rail the sections grow evenly with the rail's distance from their middle, with two with the distance between the rails; stretch: only that way); operation?, targets?, name?, body_name?"), CommandSpec::new("solid.box", "Box", prim_box).at("SOLID", "CREATE").icon("box").params("length, width, height: expr; corner?: [x,y,z] | center?: [x,y,z] (numbers in mm or length expressions; default: the origin); operation?, targets?: [body], name?, body_name?"), CommandSpec::new("solid.cylinder", "Cylinder", prim_cylinder).at("SOLID", "CREATE").icon("cylinder").params("radius | diameter, height: expr; base?: [x,y,z] (centre of the bottom: numbers in mm or length expressions; default: the origin); axis?: X|Y|Z|[x,y,z] (default Z); operation?, targets?: [body], name?, body_name?"), CommandSpec::new("solid.sphere", "Sphere", prim_sphere).at("SOLID", "CREATE").icon("sphere").params("radius | diameter: expr; center?: [x,y,z] (numbers in mm or length expressions; default: the origin); operation?, targets?: [body], name?, body_name?"), @@ -1985,6 +1985,20 @@ pub(super) fn sweep_options(s: &Session, p: &Value, cmd: &str) -> Result<(SweepO /// rails, each a sketch (default: the path's) and 1…1000 of its curves; a fit of scale or /// stretch; and no orientation, twist or scale besides, since the rails set those. pub(super) fn sweep_rails(s: &Session, p: &Value, cmd: &str, path_sketch: u64) -> Result<(Vec, RailFit)> { + let (rails, rail_fit) = guide_rails(s, p, cmd, "sweep", Some(path_sketch))?; + if !rails.is_empty() { + for key in ["orientation", "twist", "scale"] { + if p.get(key).is_some_and(|v| !v.is_null()) { + return Err(bad(cmd, format!("guide rails set the profile's turn and size along the path: leave out `{key}`"))); + } + } + } + Ok((rails, rail_fit)) +} + +/// A sweep's or a loft's (`what`) `rails` (one or two `{sketch?, curves}`, each rail's sketch +/// `default_sketch` when it names none) and `rail_fit` (scale | stretch). +pub(super) fn guide_rails(s: &Session, p: &Value, cmd: &str, what: &str, default_sketch: Option) -> Result<(Vec, RailFit)> { let rail_fit = match p.get("rail_fit") { None | Some(Value::Null) => RailFit::Scale, Some(Value::String(f)) if f.eq_ignore_ascii_case("scale") => RailFit::Scale, @@ -1994,21 +2008,17 @@ pub(super) fn sweep_rails(s: &Session, p: &Value, cmd: &str, path_sketch: u64) - let given = match p.get("rails") { None | Some(Value::Null) => return Ok((Vec::new(), rail_fit)), Some(Value::Array(a)) => a, - Some(_) => return Err(bad(cmd, "`rails` must list one or two rails: [{sketch?, curves: [ids]}]")), + Some(_) => return Err(bad(cmd, "`rails` must list one or two rails: [{sketch, curves: [ids]}]")), }; if !(1..=2).contains(&given.len()) { - return Err(bad(cmd, "a sweep takes one or two guide rails")); - } - for key in ["orientation", "twist", "scale"] { - if p.get(key).is_some_and(|v| !v.is_null()) { - return Err(bad(cmd, format!("guide rails set the profile's turn and size along the path: leave out `{key}`"))); - } + return Err(bad(cmd, format!("a {what} takes one or two guide rails"))); } let mut rails = Vec::with_capacity(given.len()); for rail in given { - let sketch = match rail.get("sketch") { - None | Some(Value::Null) => path_sketch, - Some(_) => sketch_id(s, rail.get("sketch"), cmd, "rails[].sketch")?, + let sketch = match (rail.get("sketch").filter(|v| !v.is_null()), default_sketch) { + (None, Some(sketch)) => sketch, + (None, None) => return Err(bad(cmd, "each rail needs the `sketch` its curves are in")), + (Some(_), _) => sketch_id(s, rail.get("sketch"), cmd, "rails[].sketch")?, }; let curves = string_list(rail, "curves"); if curves.is_empty() || curves.len() > 1000 { @@ -2043,10 +2053,17 @@ fn loft(s: &mut Session, p: &Value) -> Result { } sections.push(solidcraft_doc::LoftSection { sketch: SketchId(sketch), profiles: profiles(sec, cmd)?, point: None }); } + let (rails, rail_fit) = guide_rails(s, p, cmd, "loft", None)?; add_feature( s, p, - FeatureKind::Loft { sections, operation: operation(p, cmd)?, targets: string_list(p, "targets").into_iter().map(BodyName).collect() }, + FeatureKind::Loft { + sections, + operation: operation(p, cmd)?, + targets: string_list(p, "targets").into_iter().map(BodyName).collect(), + rails, + rail_fit, + }, ) } @@ -2160,6 +2177,10 @@ mod patterns_tests; #[path = "prism_local_tests.rs"] mod prism_local_tests; +#[cfg(test)] +#[path = "loft_rails_tests.rs"] +mod loft_rails_tests; + #[cfg(test)] #[path = "revolve_convention_tests.rs"] mod revolve_convention_tests; diff --git a/crates/engine/src/cmd/loft_rails_tests.rs b/crates/engine/src/cmd/loft_rails_tests.rs new file mode 100644 index 000000000..eca940d01 --- /dev/null +++ b/crates/engine/src/cmd/loft_rails_tests.rs @@ -0,0 +1,163 @@ +//! Guide rails through the loft commands (#201): solid.loft and surface.loft with a rail, +//! scaling or stretching, checked against analytic values; editing, naming, saving and hostile +//! values. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::f64::consts::PI; + +use serde_json::{Value, json}; + +use crate::Session; + +fn run(s: &mut Session, cmd: &str, p: Value) -> Value { + s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}")) +} + +/// The arc rail's radius (chord 40, bulging 5) and where its centre sits off the Z axis: the +/// rail is at x = r(z) = C + √(R² − (z − 20)²), from 10 at both ends to 15 halfway. (The sketch +/// hands the arc on as chords within 0.01 mm, hence the 2e-3 on the measures.) +const R: f64 = 42.5; +const C: f64 = 15.0 - R; + +/// ∫ √(R² − u²) du over the rail's height (u from −20 to 20). +fn root_integral() -> f64 { + 20.0 * (R * R - 400.0).sqrt() + R * R * (20.0 / R).asin() +} + +/// Circles `Base` (z = 0) and `Top` (z = 40) of radius 10, lines `Low` and `High` across them +/// from x = −10 to 10, rings `RingLow` and `RingHigh` (radius 10 round a hole of 5) there, and +/// in `Rail` on XZ the arc `arc` from (10, 0, 0) to (10, 0, 40) bulging out to x = 15 halfway, +/// and a straight `short` one that stops at z = 30. +fn setup() -> Session { + let mut s = Session::default(); + for (name, z) in [("Base", 0), ("Top", 40)] { + run(&mut s, "sketch.create", json!({"name": name, "plane": {"origin": [0, 0, z], "x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}})); + run(&mut s, "sketch.circle.center", json!({"center": [0, 0], "radius": 10, "id": "c"})); + run(&mut s, "sketch.finish", json!({})); + } + for (name, z) in [("Low", 0), ("High", 40)] { + run(&mut s, "sketch.create", json!({"name": name, "plane": {"origin": [0, 0, z], "x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}})); + run(&mut s, "sketch.line", json!({"points": [[-10, 0], [10, 0]], "ids": ["l"]})); + run(&mut s, "sketch.finish", json!({})); + } + for (name, z) in [("RingLow", 0), ("RingHigh", 40)] { + run(&mut s, "sketch.create", json!({"name": name, "plane": {"origin": [0, 0, z], "x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}})); + run(&mut s, "sketch.circle.center", json!({"center": [0, 0], "radius": 10})); + run(&mut s, "sketch.circle.center", json!({"center": [0, 0], "radius": 5})); + run(&mut s, "sketch.finish", json!({})); + } + run(&mut s, "sketch.create", json!({"plane": "XZ", "name": "Rail"})); + // The XZ sketch's y runs down world Z. + run(&mut s, "sketch.arc.three_point", json!({"start": [10, 0], "end": [10, -40], "through": [15, -20], "id": "arc"})); + run(&mut s, "sketch.line", json!({"points": [[-10, 0], [-10, -30]], "ids": ["short"]})); + run(&mut s, "sketch.finish", json!({})); + s +} + +fn measure(s: &Session, body: &str) -> solidcraft_kernel::BodyMeasure { + solidcraft_kernel::measure(&s.world_state().body(body).unwrap().body).unwrap() +} + +fn loft(s: &mut Session, body: &str, extra: Value) -> Result { + let mut p = json!({"sections": [{"sketch": "Base"}, {"sketch": "Top"}], "operation": "new", "body_name": body}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + s.execute("solid.loft", &p).map_err(|e| e.to_string()) +} + +fn face_names(s: &mut Session, body: &str) -> Vec { + let f = run(s, "model.faces", json!({ "body": body })); + let mut n: Vec = f["faces"] + .as_array() + .into_iter() + .flatten() + .filter_map(|x| x["name"].as_str()) + .map(|x| x.split_once(':').map_or(x, |(_, rest)| rest).to_string()) + .collect(); + n.sort(); + n +} + +/// The arc rail turns the loft between the circles into the arc's solid of revolution +/// (π∫r² dz); its faces keep the plain loft's names; the rail is saved with the feature; and +/// switching the fit to stretch is an edit (the circles then widen only toward the rail, into +/// ellipses π · 10 · r). +#[test] +fn a_rail_turns_a_loft_into_its_solid_of_revolution_and_stretching_is_an_edit() { + let mut s = setup(); + let rail = json!([{"sketch": "Rail", "curves": ["arc"]}]); + loft(&mut s, "Plain", json!({})).unwrap(); + loft(&mut s, "Vase", json!({"rails": rail, "name": "Railed"})).unwrap(); + let volume = PI * (40.0 * C * C + 2.0 * C * root_integral() + 40.0 * R * R - 2.0 * 8000.0 / 3.0); + let m = measure(&s, "Vase"); + assert!((m.volume - volume).abs() < 2e-3 * volume, "volume {} vs {volume}", m.volume); + assert!((m.bbox.max.x - 15.0).abs() < 1e-2, "{:?}", m.bbox); + assert_eq!(face_names(&mut s, "Plain"), face_names(&mut s, "Vase")); + + let doc = solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap(); + let reopened = Session::new(doc); + assert!((measure(&reopened, "Vase").volume - m.volume).abs() < 1e-9 * volume); + + run(&mut s, "timeline.edit", json!({"feature": "Railed", "set": {"rail_fit": "stretch"}})); + let stretched = measure(&s, "Vase"); + let elliptic = 10.0 * PI * (40.0 * C + root_integral()); + assert!((stretched.volume - elliptic).abs() < 2e-3 * elliptic, "stretched {} vs {elliptic}", stretched.volume); + assert!((stretched.bbox.max.y - 10.0).abs() < 1e-3, "{:?}", stretched.bbox); +} + +/// A sheet lofted between the two lines with the arc rail from one end: the lines between grow +/// about their middles, 2r long; area 2∫r dz. +#[test] +fn a_surface_loft_follows_its_rail() { + let mut s = setup(); + run( + &mut s, + "surface.loft", + json!({"sections": [{"sketch": "Low", "curves": ["l"]}, {"sketch": "High", "curves": ["l"]}], "rails": [{"sketch": "Rail", "curves": ["arc"]}], "body_name": "Sail"}), + ); + let m = measure(&s, "Sail"); + let area = 2.0 * (40.0 * C + root_integral()); + assert!((m.area - area).abs() < 2e-3 * area, "area {} vs {area}", m.area); + assert!((m.bbox.min.x + 15.0).abs() < 1e-2, "{:?}", m.bbox); +} + +/// Hostile rails are refused with an error and leave the design as it was. +#[test] +fn hostile_rails_are_refused() { + let mut s = setup(); + let before = s.doc.features.len(); + let rail = json!([{"sketch": "Rail", "curves": ["arc"]}]); + for bad in [ + json!({"rails": "arc"}), + json!({"rails": []}), + json!({"rails": [{"sketch": "Rail", "curves": ["arc"]}, {"sketch": "Rail", "curves": ["arc"]}, {"sketch": "Rail", "curves": ["arc"]}]}), + json!({"rails": [{"sketch": "Rail", "curves": []}]}), + // A loft has no path whose sketch a rail could default to. + json!({"rails": [{"curves": ["arc"]}]}), + json!({"rails": [{"sketch": "Rail", "curves": ["nope"]}]}), + json!({"rails": [{"sketch": "Nowhere", "curves": ["arc"]}]}), + json!({"rails": rail, "rail_fit": "wobble"}), + // A rail that stops short of the top section. + json!({"rails": [{"sketch": "Rail", "curves": ["short"]}]}), + // Two rails meeting the sections at one point. + json!({"rails": [{"sketch": "Rail", "curves": ["arc"]}, {"sketch": "Rail", "curves": ["arc"]}]}), + ] { + assert!(loft(&mut s, "Bad", bad.clone()).is_err(), "{bad}"); + let mut p = json!({"sections": [{"sketch": "Low", "curves": ["l"]}, {"sketch": "High", "curves": ["l"]}]}); + p.as_object_mut().unwrap().extend(bad.as_object().unwrap().clone()); + assert!(s.execute("surface.loft", &p).is_err(), "surface {bad}"); + } + // Rails on what the railed loft does not build yet. + let apex = json!({"sections": [{"sketch": "Base"}, {"sketch": "Rail", "point": "arc.start"}], "rails": rail}); + assert!(s.execute("solid.loft", &apex).is_err()); + // Rings (a circle with a hole) loft without rails, not with them yet. + let ring = |name: &str| json!({"sketch": name, "profiles": [{"point": [7.5, 0]}]}); + let rings = json!({"sections": [ring("RingLow"), ring("RingHigh")], "operation": "new", "rails": rail}); + let refused = s.execute("solid.loft", &rings).unwrap_err().to_string(); + assert!(refused.contains("not supported yet") && refused.contains("holes"), "{refused}"); + let g1 = + json!({"sections": [{"sketch": "Low", "curves": ["l"]}, {"sketch": "High", "curves": ["l"]}], "rails": rail, "continuity": ["g1", "g0"]}); + let refused = s.execute("surface.loft", &g1).unwrap_err().to_string(); + assert!(refused.contains("not supported yet"), "{refused}"); + assert_eq!(s.doc.features.len(), before, "nothing was added"); +} diff --git a/crates/engine/src/cmd/surface.rs b/crates/engine/src/cmd/surface.rs index 32fb50bc1..e12b6aea6 100644 --- a/crates/engine/src/cmd/surface.rs +++ b/crates/engine/src/cmd/surface.rs @@ -51,7 +51,7 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("surface.loft", "Surface Loft", surface_loft) .at("SURFACE", "CREATE") .icon("surface_loft") - .params("sections: [{sketch, curves?: [curve ids], profiles?} | {body, edges: [[x,y,z]]}] (2…50 in order; each one chain: a profile without holes, or curves meeting end to end; all open or all closed; a body edge chain takes the face the chain bounds as the surface the end repeats); continuity?: [g0|g1|g2|g3, g0|g1|g2|g3] (each end, default g0: how much of the surface at the first and last section the loft repeats — the tangent plane, the curvature, or how that curvature changes); crown?: [number, number] (default 0: how full each end leaves, -0.9 flattest to 3 fullest); name?, body_name? (a surface body: ruled between two sections, smooth through three or more; no caps)"), + .params("sections: [{sketch, curves?: [curve ids], profiles?} | {body, edges: [[x,y,z]]}] (2…50 in order; each one chain: a profile without holes, or curves meeting end to end; all open or all closed; a body edge chain takes the face the chain bounds as the surface the end repeats); continuity?: [g0|g1|g2|g3, g0|g1|g2|g3] (each end, default g0: how much of the surface at the first and last section the loft repeats — the tangent plane, the curvature, or how that curvature changes); crown?: [number, number] (default 0: how full each end leaves, -0.9 flattest to 3 fullest); rails?, rail_fit? (as solid.loft; sketch sections only, both ends g0); name?, body_name? (a surface body: ruled between two sections, smooth through three or more; no caps)"), CommandSpec::new("surface.offset", "Offset Surface", offset) .at("SURFACE", "CREATE") .icon("surface_offset") @@ -431,7 +431,8 @@ fn surface_loft(s: &mut Session, p: &Value) -> Result { [one(list.first())?, one(list.get(1))?] } }; - add_feature(s, p, FeatureKind::SurfaceLoft { sections, continuity, crown }) + let (rails, rail_fit) = super::features::guide_rails(s, p, cmd, "loft", None)?; + add_feature(s, p, FeatureKind::SurfaceLoft { sections, continuity, crown, rails, rail_fit }) } fn offset(s: &mut Session, p: &Value) -> Result { diff --git a/crates/kernel/src/build.rs b/crates/kernel/src/build.rs index a1c097df6..e781e7f37 100644 --- a/crates/kernel/src/build.rs +++ b/crates/kernel/src/build.rs @@ -8,6 +8,7 @@ use crate::body::{Body, Solid, from_p3, p3, v3}; use crate::history::FaceProv; use crate::numbered::{self, NumberedLoop, NumberedRegion}; use crate::record::{self, Side}; +use crate::sweep_path::RailFit; use crate::{KernelError, Result, guard}; const MAX_SEGS: usize = 20_000; @@ -1797,21 +1798,34 @@ pub(crate) fn close_sweep(sides: Vec) -> Result { /// Ruled loft through two or more planar sections (outer loops only). The sections and the /// same sections in reverse order give the same body. pub fn loft(sections: &[(Plane, Loop2)]) -> Result { + loft_with_rails(sections, &[], RailFit::Scale) +} + +/// [`loft`] following one or two guide rails (polylines from the first section to the last, +/// through every section's curve; see [`crate::loft_rails`]), `fit` saying how they reshape the +/// sections between. Without rails, the plain loft. +pub fn loft_with_rails(sections: &[(Plane, Loop2)], rails: &[Vec], fit: RailFit) -> Result { let (wires, edge_sources, reversed) = loft_wires(sections)?; + let (Some(first), Some(last)) = (wires.first(), wires.last()) else { return Err(KernelError::Failed("loft: sections".into())) }; + let mut planes: Vec = sections.iter().map(|(p, _)| *p).collect(); + if reversed { + planes.reverse(); + } + let all = guard("loft", || crate::loft_rails::railed_wires(&planes, &wires, true, rails, fit))?; // The wires run from the first section given, or (turned round) the last. - // Three sections or more: one smooth surface through them all for each segment. - if wires.len() >= 3 - && let Ok(b) = guard("loft", || { - let faces = smooth_loft_faces(&wires, &edge_sources, true)?; - let (Some(w0), Some(w1)) = (wires.first(), wires.last()) else { return Err(KernelError::Failed("smooth loft: sections".into())) }; - cap_and_close(faces, std::slice::from_ref(w0), std::slice::from_ref(w1), reversed) - }) - { - return Ok(b); + // Three wires or more: one smooth surface through them all for each segment. A plain loft + // falls back to ruled faces where that fails; a railed one has to follow its rails. + if all.len() >= 3 { + let smooth = guard("loft", || { + let faces = smooth_loft_faces(&all, &edge_sources, true)?; + cap_and_close(faces, std::slice::from_ref(first), std::slice::from_ref(last), reversed) + }); + if smooth.is_ok() || !rails.is_empty() { + return smooth; + } } guard("loft", || { let sides = ruled_loft_faces(&wires, &edge_sources)?; - let (Some(first), Some(last)) = (wires.first(), wires.last()) else { return Err(KernelError::Failed("loft".into())) }; cap_and_close(sides, std::slice::from_ref(first), std::slice::from_ref(last), reversed) }) } @@ -2039,7 +2053,7 @@ pub(crate) fn ruled_loft_faces(wires: &[mt::Wire], edge_sources: &[Vec Option> { +pub(crate) fn across(pts: &[Vec3], u: &[f64]) -> Option> { match pts { [a, b, c] => { // The quadratic Bezier through `b` at t = u[1]. @@ -2059,7 +2073,7 @@ fn across(pts: &[Vec3], u: &[f64]) -> Option> { /// them. At a uniform parameter a section close to its neighbour makes the surface overshoot /// between the others (by several times the section's size when the spacing differs tenfold). /// Evenly spaced sections give the uniform parameters. -fn section_parameters(edges: &[Vec]) -> Vec { +pub(crate) fn section_parameters(edges: &[Vec]) -> Vec { let m = edges.len(); let uniform = || (0..m).map(|i| i as f64 / (m.max(2) - 1) as f64).collect::>(); let corners: Vec> = edges.iter().map(|es| es.iter().map(|e| from_p3(e.front().point())).collect()).collect(); diff --git a/crates/kernel/src/curveblend.rs b/crates/kernel/src/curveblend.rs index e01cf5ee6..1051cae30 100644 --- a/crates/kernel/src/curveblend.rs +++ b/crates/kernel/src/curveblend.rs @@ -2243,7 +2243,7 @@ fn curve_blend_sized(solid: &Solid, ids: &[mt::EdgeID], size: f64, size_law: Siz #[path = "curvecorner.rs"] mod corner; -pub(crate) use corner::corner_blend_style; +pub(crate) use corner::{corner_blend_style, param_on}; // The planar corner builder the G2 corner work left in place of `corner_blend_style`'s sphere. #[allow(unused_imports)] pub(crate) use corner::corner_blend; diff --git a/crates/kernel/src/curvecorner.rs b/crates/kernel/src/curvecorner.rs index affabdaab..a3dbc8892 100644 --- a/crates/kernel/src/curvecorner.rs +++ b/crates/kernel/src/curvecorner.rs @@ -214,7 +214,9 @@ fn radius_along(e: &mt::Edge, axis: Vec3, tol: f64) -> Option { (0..=16).map(|i| at(i as f64 / 16.0)).all(|p| (p.dist(o) - rho).abs() <= tol).then_some(rho) } -fn param_on(c: &mt::Curve, x: Vec3) -> Option { +/// The parameter of `c`'s point nearest `x`: the nearest of 65 samples, refined where that +/// comes nearer. +pub(crate) fn param_on(c: &mt::Curve, x: Vec3) -> Option { use mt::{BoundedCurve, ParametricCurve, SearchNearestParameter}; let (lo, hi) = c.range_tuple(); let d = |t: f64| from_p3(c.subs(t)).dist(x); diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rs index a49cb3ced..6f852793d 100644 --- a/crates/kernel/src/lib.rs +++ b/crates/kernel/src/lib.rs @@ -81,6 +81,9 @@ mod issue_871_tests; mod join_between_caps_tests; mod lip; pub mod loft_blend; +mod loft_rails; +#[cfg(test)] +mod loft_rails_tests; #[cfg(test)] mod loft_region_tests; mod loopblend; @@ -160,7 +163,7 @@ pub use boundary_network::{BoundaryCurve, CurveSource, MAX_CHAIN_CURVES, MAX_EDG pub use bridge::{Continuity, Frame, blend_between, bridge, chain, chain_closes, frames, frames_across, sample_grid}; pub use build::{ PathSeg, box_solid, canonical_revolve_axis, cylinder, extrude, extrude_tapered, extrude_tapered_between, extrude_whole_sides, loft, loft_regions, - path_polyline, revolve, revolve_whole, sphere, sweep, sweep_with, torus, + loft_with_rails, path_polyline, revolve, revolve_whole, sphere, sweep, sweep_with, torus, }; pub use clearance::{Clearance, Occupancy}; pub use coaxial_overlap::{CoaxialOverlap, coaxial_candidate, coaxial_overlap}; @@ -209,8 +212,8 @@ pub use surface_ruled::{Ruled, RuledCorners, RuledMode, ruled_surface}; pub use surface_trim::{TrimKeep, mutual_trim, trim, trim_keep}; pub use surface_untrim::{UntrimHoles, untrim}; pub use surfaces::{ - copy_faces, extend, extrude_sheet, loft_sheet, patch_edges, patch_region, remove_faces, reverse_faces, revolve_sheet, stitch, sweep_sheet, - sweep_sheet_points, sweep_sheet_points_with, sweep_sheet_with, thicken, unstitch, + copy_faces, extend, extrude_sheet, loft_sheet, loft_sheet_with_rails, patch_edges, patch_region, remove_faces, reverse_faces, revolve_sheet, + stitch, sweep_sheet, sweep_sheet_points, sweep_sheet_points_with, sweep_sheet_with, thicken, unstitch, }; pub use sweep_path::{RailFit, SweepControl, SweepOrientation, sweep_path, sweep_path_with}; pub use topo::{CylinderFace, cylinder_end_at, cylinder_face, cylinder_face_at}; diff --git a/crates/kernel/src/loft_rails.rs b/crates/kernel/src/loft_rails.rs new file mode 100644 index 000000000..72acd5e6e --- /dev/null +++ b/crates/kernel/src/loft_rails.rs @@ -0,0 +1,349 @@ +//! Guide rails for a loft (#201): curves the loft follows between its sections. A rail runs from +//! the first section to the last and passes through every section's curve. Between each two +//! sections, stations are added: each is the plain loft there, moved so that the point of it a +//! rail guides lands on the rail. With one rail the station turns about the loft's direction +//! there and grows or shrinks about its middle (stretches across to the rail, with +//! [`RailFit::Stretch`]), shifted along the loft as far as the rail leads or lags; with two it +//! moves with the first rail, turns with the line between the rails and sizes with their distance +//! (stretches along that line), leaning to follow the second. At the sections the move is none, +//! so the sections and the loft's caps stay exactly as drawn; the loft's smooth surfaces then run +//! through the sections and the stations together. + +use mt::{BoundedCurve, ParametricCurve}; +use solidcraft_geom::{Plane, Vec3}; +use truck_modeling as mt; + +use crate::body::{from_p3, p3}; +use crate::sweep_path::RailFit; +use crate::{KernelError, Result}; + +/// Most wires a railed loft is skinned through, sections and stations together. +const MAX_WIRES: usize = 33; +/// Most stations between two sections. +const MAX_PER_SPAN: usize = 15; + +type Curve = mt::BSplineCurve; + +/// Where a rail meets a section: the point of the section's wire it guides (as a wire parameter: +/// the edge's index plus how far along the edge), that point, how far it is from where the rail +/// crosses the section's plane (the nudge onto it), and how far along the rail that crossing is +/// (segment and fraction). +struct Anchor { + g: f64, + on: Vec3, + nudge: Vec3, + at: (usize, f64), +} + +/// A rail as a polyline from the first section, and where it meets each section. +struct Rail { + pts: Vec, + anchors: Vec, +} + +/// An affine move: `x` goes to `to + m·(x − from)` (`m` by columns). +struct Affine { + from: Vec3, + to: Vec3, + m: [Vec3; 3], +} + +impl Affine { + fn apply(&self, x: Vec3) -> Vec3 { + let d = x - self.from; + self.to + self.m[0] * d.x + self.m[1] * d.y + self.m[2] * d.z + } +} + +/// The loft's wires with stations added between the sections so that the loft follows `rails` +/// (polylines; see the module notes). `planes` are the sections' planes, `wires` their matched +/// wires (as [`crate::build::loft_wires`] or a sheet loft makes them: the k-th edges of every +/// wire are B-splines on one knot vector), both in loft order; `closed` whether the wires close. +/// Without rails the wires come back as they are. +pub(crate) fn railed_wires(planes: &[Plane], wires: &[mt::Wire], closed: bool, rails: &[Vec], fit: RailFit) -> Result> { + if rails.is_empty() { + return Ok(wires.to_vec()); + } + if rails.len() > 2 { + return Err(KernelError::Invalid("a loft takes one or two guide rails".into())); + } + let fail = |m: &str| KernelError::Failed(format!("loft rails: {m}")); + let count = wires.len(); + if count < 2 || planes.len() != count { + return Err(fail("sections")); + } + // Each section's edge curves, and the knot vector the k-th edges share. + let curves: Vec> = wires + .iter() + .map(|w| { + w.edge_iter() + .map(|e| match e.curve() { + mt::Curve::BSplineCurve(c) if e.orientation() => Some(c), + _ => None, + }) + .collect::>>() + }) + .collect::>() + .ok_or_else(|| fail("section curves"))?; + let first = curves.first().ok_or_else(|| fail("sections"))?; + let n = first.len(); + let knots: Vec = first.iter().map(|c| c.knot_vec().clone()).collect(); + let sizes: Vec = first.iter().map(|c| c.control_points().len()).collect(); + if n == 0 + || curves + .iter() + .any(|cs| cs.len() != n || cs.iter().zip(&knots).zip(&sizes).any(|((c, k), m)| c.knot_vec() != k || c.control_points().len() != *m)) + { + return Err(fail("sections parameterised differently")); + } + let ctrl: Vec>> = + curves.iter().map(|cs| cs.iter().map(|c| c.control_points().iter().map(|p| from_p3(*p)).collect()).collect()).collect(); + let edges: Vec> = wires.iter().map(|w| w.edge_iter().cloned().collect()).collect(); + let along = crate::build::section_parameters(&edges); + let mut bounds = solidcraft_geom::Aabb3::EMPTY; + for p in ctrl.iter().flatten().flatten() { + if !p.is_finite() { + return Err(fail("sections")); + } + bounds.add(*p); + } + let size = bounds.diagonal(); + let tol = (size * 1e-4).max(1e-6); + let start = centroid(ctrl.first().ok_or_else(|| fail("sections"))?); + let rails: Vec = rails.iter().map(|r| rail(r, start, planes, &curves, tol)).collect::>()?; + if let [a, b] = &rails[..] + && a.anchors.iter().zip(&b.anchors).any(|(p, q)| p.on.dist(q.on) <= tol) + { + return Err(KernelError::Invalid("the two guide rails meet a section at the same point".into())); + } + // The plain loft between the sections: each control point across them, straight between two + // sections, the smooth loft's curve through three or more. + let across: Vec>> = if count == 2 { + Vec::new() + } else { + (0..n) + .map(|k| { + (0..sizes.get(k).copied().unwrap_or(0)) + .map(|j| { + let pts: Vec = ctrl.iter().filter_map(|s| s.get(k).and_then(|e| e.get(j)).copied()).collect(); + crate::build::across(&pts, &along) + }) + .collect() + }) + .collect() + }; + let plain = |v: f64| -> Result>> { + let (Some(a), Some(b)) = (ctrl.first(), ctrl.last()) else { return Err(fail("sections")) }; + if count == 2 { + return Ok(a.iter().zip(b).map(|(ea, eb)| ea.iter().zip(eb).map(|(p, q)| p.lerp(*q, v)).collect()).collect()); + } + across.iter().map(|cs| cs.iter().map(|c| c.as_ref().map(|c| from_p3(c.subs(v))).ok_or_else(|| fail("the plain loft"))).collect()).collect() + }; + // The middle of the plain loft (the middles of the sections' control points, across them as + // the control points are: the middle is linear in them) and its direction. + let middles: Vec = ctrl.iter().map(|s| centroid(s)).collect(); + let middle_curve = if count == 2 { None } else { Some(crate::build::across(&middles, &along).ok_or_else(|| fail("the plain loft"))?) }; + let middle = |v: f64| -> Result<(Vec3, Vec3)> { + let (p, d) = match (&middle_curve, middles.first(), middles.last()) { + (Some(c), ..) => { + let d = c.der(v); + (from_p3(c.subs(v)), Vec3::new(d.x, d.y, d.z)) + } + (None, Some(a), Some(b)) => (a.lerp(*b, v), *b - *a), + _ => return Err(fail("sections")), + }; + let d = d.normalized().ok_or_else(|| KernelError::Invalid("two loft sections sit on top of each other".into()))?; + Ok((p, d)) + }; + // The sections' normals, turned to agree with the first's. + let mut normals: Vec = Vec::with_capacity(count); + for p in planes { + let n = p.normal(); + let prev = normals.last().copied().unwrap_or(n); + normals.push(if n.dot(prev) < 0.0 { n * -1.0 } else { n }); + } + let spans = count - 1; + let per = (MAX_WIRES.saturating_sub(count) / spans).clamp(1, MAX_PER_SPAN); + let mut out = Vec::with_capacity(count + spans * per); + for i in 0..spans { + out.push(wires.get(i).cloned().ok_or_else(|| fail("sections"))?); + let (Some(&v0), Some(&v1), Some(&n0), Some(&n1)) = (along.get(i), along.get(i + 1), normals.get(i), normals.get(i + 1)) else { + return Err(fail("sections")); + }; + // Each rail's anchors at the span's two sections, and where its walk has got to. + let mut spans_of: Vec<(&Rail, &Anchor, &Anchor, (usize, f64))> = Vec::with_capacity(rails.len()); + for r in &rails { + let (Some(a0), Some(a1)) = (r.anchors.get(i), r.anchors.get(i + 1)) else { return Err(fail("rail")) }; + spans_of.push((r, a0, a1, a0.at)); + } + for q in 1..=per { + let f = q as f64 / (per + 1) as f64; + let v = v0 + f * (v1 - v0); + let station = plain(v)?; + let (mid, dir) = middle(v)?; + // The station's plane turns from one section's to the next's. + let normal = n0.lerp(n1, f).normalized().ok_or_else(|| fail("section planes"))?; + let mut pairs = Vec::with_capacity(rails.len()); + for (r, a0, a1, cursor) in &mut spans_of { + let anchor = wire_point(&station, &knots, interpolate_g(a0.g, a1.g, f, n, closed))?; + // Where the rail crosses the station's plane through the point it guides, nudged + // so that at each section it is the section's own point (a rail drawn a hair off + // a section moves nothing there). + let Some((hit, at)) = crate::sweep_path::rail_crossing(&r.pts, anchor, normal, *cursor, tol) else { + return Err(KernelError::Invalid(format!( + "a guide rail turns back between sections {} and {}: it has to run on from one section to the next", + i + 1, + i + 2 + ))); + }; + *cursor = at; + let target = hit + a0.nudge * (1.0 - f) + a1.nudge * f; + pairs.push((anchor, target)); + } + let map = station_map(&pairs, mid, dir, fit, size)?; + let moved: Vec> = station.iter().map(|e| e.iter().map(|p| map.apply(*p)).collect()).collect(); + out.push(wire_of(&moved, &knots, closed)?); + } + } + out.push(wires.last().cloned().ok_or_else(|| fail("sections"))?); + Ok(out) +} + +/// The rail `pts` from its end nearer `start` (the first section's middle), where it meets each +/// section: across the section's plane, on the section's curve within `tol`. +fn rail(pts: &[Vec3], start: Vec3, planes: &[Plane], curves: &[Vec], tol: f64) -> Result { + let mut pts = + crate::sweep_path::clean(pts).map_err(|_| KernelError::Invalid("a guide rail needs 2…100000 finite points along its length".into()))?; + if let (Some(a), Some(b)) = (pts.first(), pts.last()) + && b.dist(start) < a.dist(start) + { + pts.reverse(); + } + let mut cursor = (0usize, 0.0f64); + let mut anchors = Vec::with_capacity(planes.len()); + for (i, (plane, section)) in planes.iter().zip(curves).enumerate() { + let Some((hit, at)) = crate::sweep_path::rail_crossing(&pts, plane.origin, plane.normal(), cursor, tol) else { + return Err(KernelError::Invalid(format!( + "a guide rail does not reach section {}: a rail has to run from the first section to the last, through every one", + i + 1 + ))); + }; + cursor = at; + let (g, on, d) = nearest_on(section, hit).ok_or_else(|| KernelError::Failed("loft rails: section".into()))?; + if d > tol { + return Err(KernelError::Invalid(format!( + "a guide rail crosses section {}'s plane {d:.3} mm from its curves: a rail has to pass through every section", + i + 1 + ))); + } + anchors.push(Anchor { g, on, nudge: on - hit, at }); + } + Ok(Rail { pts, anchors }) +} + +/// The point of a section's wire (its edge curves) nearest `p`: as a wire parameter, the point, +/// and how far it is. +fn nearest_on(section: &[Curve], p: Vec3) -> Option<(f64, Vec3, f64)> { + let mut best: Option<(f64, Vec3, f64)> = None; + for (k, c) in section.iter().enumerate() { + let (t0, t1) = c.range_tuple(); + let t = crate::curveblend::param_on(&mt::Curve::BSplineCurve(c.clone()), p)?; + let q = from_p3(c.subs(t)); + let d = q.dist(p); + if best.as_ref().is_none_or(|b| d < b.2) { + best = Some((k as f64 + (t - t0) / (t1 - t0).max(1e-300), q, d)); + } + } + best +} + +/// A wire parameter `f` of the way from `g0` to `g1`; round a closed wire of `n` edges the +/// shorter way. +fn interpolate_g(g0: f64, g1: f64, f: f64, n: usize, closed: bool) -> f64 { + let n = n as f64; + if !closed { + return (g0 + f * (g1 - g0)).clamp(0.0, n); + } + let mut d = g1 - g0; + if d > n / 2.0 { + d -= n; + } else if d < -n / 2.0 { + d += n; + } + (g0 + f * d).rem_euclid(n) +} + +/// The point at wire parameter `g` of a wire given by its edges' control points on `knots`. +fn wire_point(ctrl: &[Vec], knots: &[mt::KnotVec], g: f64) -> Result { + let n = ctrl.len(); + let k = (g.floor().max(0.0) as usize).min(n.saturating_sub(1)); + let (Some(pts), Some(kv)) = (ctrl.get(k), knots.get(k)) else { return Err(KernelError::Failed("loft rails: wire".into())) }; + let c = edge_curve(kv, pts)?; + let (t0, t1) = c.range_tuple(); + let f = (g - k as f64).clamp(0.0, 1.0); + Ok(from_p3(c.subs(t0 + (t1 - t0) * f))) +} + +/// The middle of a wire's control points. +fn centroid(ctrl: &[Vec]) -> Vec3 { + let (sum, n) = ctrl.iter().flatten().fold((Vec3::ZERO, 0usize), |(s, n), p| (s + *p, n + 1)); + sum * (1.0 / n.max(1) as f64) +} + +/// The move that puts a station's guided points onto the rails (`pairs`: each point with its +/// rail's point), the station's middle `middle`, the loft's direction there `dir` (unit); `size` +/// the loft's size. One rail: turned about `dir` and sized about the middle, shifted along `dir`; +/// two: carried with the first, turned and sized with the line between them, leaning along `dir`. +fn station_map(pairs: &[(Vec3, Vec3)], middle: Vec3, dir: Vec3, fit: RailFit, size: f64) -> Result { + let (from, to, a, r, two) = match pairs { + [(p, q)] => (middle, middle, *p - middle, *q - middle, false), + [(p1, q1), (p2, q2)] => (*p1, *q1, *p2 - *p1, *q2 - *q1, true), + _ => return Err(KernelError::Invalid("a loft takes one or two guide rails".into())), + }; + let flat = |v: Vec3| v - dir * v.dot(dir); + let (ap, rp) = (flat(a), flat(r)); + let tiny = 1e-6 * size.max(1e-9); + let (Some(u0), Some(u1)) = (ap.normalized().filter(|_| ap.len() > tiny), rp.normalized().filter(|_| rp.len() > tiny)) else { + return Err(KernelError::Invalid(if two { + "the two guide rails come together between the sections: the loft would shrink to nothing".into() + } else { + "a guide rail runs through the middle of the loft: it has to guide a point of the sections away from their middle".into() + })); + }; + // Turned about the loft's direction and sized as the sweep's rails size its profile. + let mut m = crate::sweep_path::rail_frame(dir, u0, dir, u1, rp.len() / ap.len(), fit); + // Whatever the rails ask along the loft: one rail shifts the station that far, two lean it, + // in step with the way across. + let lead = (r - a).dot(dir); + if two { + let lean = lead / ap.len(); + for (col, e) in m.iter_mut().zip([Vec3::X, Vec3::Y, Vec3::Z]) { + *col += dir * (lean * e.dot(u0)); + } + } + let shift = if two { Vec3::ZERO } else { dir * lead }; + Ok(Affine { from, to: to + shift, m }) +} + +/// A wire of B-spline edges with these control points on these knots, joined end to end +/// (closing back on its first edge's start when `closed`). +fn wire_of(ctrl: &[Vec], knots: &[mt::KnotVec], closed: bool) -> Result { + let fail = || KernelError::Failed("loft rails: station".into()); + let n = ctrl.len(); + let mut verts: Vec = ctrl.iter().map(|e| e.first().map(|p| mt::Vertex::new(p3(*p)))).collect::>().ok_or_else(fail)?; + if !closed { + verts.push(mt::Vertex::new(p3(*ctrl.last().and_then(|e| e.last()).ok_or_else(fail)?))); + } + let mut edges = Vec::with_capacity(n); + for (i, (pts, kv)) in ctrl.iter().zip(knots).enumerate() { + let (Some(a), Some(b)) = (verts.get(i), verts.get(if closed { (i + 1) % n } else { i + 1 })) else { return Err(fail()) }; + let c = edge_curve(kv, pts)?; + edges.push(mt::Edge::new(a, b, mt::Curve::BSplineCurve(c))); + } + Ok(edges.into()) +} + +/// An edge's B-spline from its control points on its knots. +fn edge_curve(kv: &mt::KnotVec, pts: &[Vec3]) -> Result { + Curve::try_new(kv.clone(), pts.iter().map(|p| p3(*p)).collect()).map_err(|e| KernelError::Failed(format!("loft rails: {e}"))) +} diff --git a/crates/kernel/src/loft_rails_tests.rs b/crates/kernel/src/loft_rails_tests.rs new file mode 100644 index 000000000..4755dfee2 --- /dev/null +++ b/crates/kernel/src/loft_rails_tests.rs @@ -0,0 +1,169 @@ +//! Guide rails on lofts (#201), checked against analytic solids: a rail bulging out from a loft +//! between two equal circles makes the solid of revolution of the rail, a stretching rail widens +//! squares one way only, two rails carry the sections between them, a sheet loft of lines follows +//! its rail; and rails the loft cannot follow are refused. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::f64::consts::PI; + +use solidcraft_geom::{Loop2, Plane, Seg2, Vec2, Vec3}; + +use crate::{KernelError, RailFit, loft, loft_sheet_with_rails, loft_with_rails, measure}; + +fn at(z: f64) -> Plane { + Plane { origin: Vec3::new(0.0, 0.0, z), x: Vec3::X, y: Vec3::Y } +} + +fn circle(r: f64) -> Loop2 { + Loop2::circle(Vec2::ZERO, r) +} + +fn square(h: f64) -> Loop2 { + Loop2::polygon(&[Vec2::new(-h, -h), Vec2::new(h, -h), Vec2::new(h, h), Vec2::new(-h, h)]) +} + +/// The bulge of the rails: 0 at both ends, 1 halfway up the 40 mm loft. +fn bulge(z: f64) -> f64 { + (PI * z / 40.0).sin() +} + +/// A rail in the XZ plane at `x(z)`, from z = 0 to z = 40. +fn rail(x: impl Fn(f64) -> f64) -> Vec { + (0..=80).map(|i| f64::from(i) * 0.5).map(|z| Vec3::new(x(z), 0.0, z)).collect() +} + +fn close(a: f64, b: f64, rel: f64) -> bool { + (a - b).abs() <= rel * b.abs() +} + +/// The body's volume from a fine mesh. +fn volume(b: &crate::Body) -> f64 { + b.volume_at(1e-4).unwrap() +} + +/// How far `p` is from the nearest face of the body. +fn off(b: &crate::Body, p: Vec3) -> f64 { + use truck_modeling::{ParametricSurface, SearchNearestParameter}; + b.solid + .face_iter() + .filter_map(|f| { + let s = f.surface(); + let (u, v) = s.search_nearest_parameter(crate::body::p3(p), None, 100)?; + Some(crate::body::from_p3(s.subs(u, v)).dist(p)) + }) + .fold(f64::INFINITY, f64::min) +} + +/// A rail straight up the side of a loft between equal circles changes nothing: the plain loft +/// (the cylinder, to the accuracy of its fitted circles). +#[test] +fn a_straight_rail_up_a_cylinder_leaves_it_a_cylinder() { + let sections = [(at(0.0), circle(10.0)), (at(40.0), circle(10.0))]; + let b = loft_with_rails(§ions, &[rail(|_| 10.0)], RailFit::Scale).unwrap(); + let m = measure(&b).unwrap(); + let plain = measure(&loft(§ions).unwrap()).unwrap(); + assert!(close(m.volume, 4000.0 * PI, 1e-3), "volume {} vs {}", m.volume, 4000.0 * PI); + assert!(close(m.volume, plain.volume, 1e-6), "{} vs the plain loft's {}", m.volume, plain.volume); +} + +/// A rail bulging out to radius 15 halfway up turns the loft into the rail's solid of +/// revolution: circles of radius r = 10 + 5 sin(πz/40), volume π∫r² = 4500π + 8000. The sections +/// stay exactly as drawn, and three sections give the same solid. +#[test] +fn a_bulging_rail_makes_the_solid_of_revolution_of_the_rail() { + let want = 4500.0 * PI + 8000.0; + let r = rail(|z| 10.0 + 5.0 * bulge(z)); + for sections in + [vec![(at(0.0), circle(10.0)), (at(40.0), circle(10.0))], vec![(at(0.0), circle(10.0)), (at(20.0), circle(15.0)), (at(40.0), circle(10.0))]] + { + let b = loft_with_rails(§ions, std::slice::from_ref(&r), RailFit::Scale).unwrap(); + let m = measure(&b).unwrap(); + assert!(close(volume(&b), want, 1e-4), "{} sections: volume {} vs {want}", sections.len(), volume(&b)); + // The loft runs through the rail. + let worst = r.iter().map(|p| off(&b, *p)).fold(0.0, f64::max); + assert!(worst < 1e-3, "{} sections: the rail is {worst} mm off the loft", sections.len()); + assert!((m.bbox.max.x - 15.0).abs() < 1e-2 && (m.bbox.max.y - 15.0).abs() < 1e-2, "{:?}", m.bbox); + assert!(m.bbox.min.z.abs() < 1e-9 && (m.bbox.max.z - 40.0).abs() < 1e-9, "{:?}", m.bbox); + } + // The sections given the other way round: the same solid. + let flipped = [(at(40.0), circle(10.0)), (at(0.0), circle(10.0))]; + let v = volume(&loft_with_rails(&flipped, &[r], RailFit::Scale).unwrap()); + assert!(close(v, want, 1e-4), "reversed: volume {v} vs {want}"); +} + +/// A rail from the middle of a square's side bulging out by 5: stretching widens the squares +/// only across to the rail (sections 2w × 10 with w = 5 + 5 sin, volume 4000 + 8000/π); scaling +/// grows them both ways (sections (2w)², volume 6000 + 16000/π). +#[test] +fn a_stretching_rail_widens_squares_one_way_and_a_scaling_one_both() { + let sections = [(at(0.0), square(5.0)), (at(40.0), square(5.0))]; + let r = rail(|z| 5.0 + 5.0 * bulge(z)); + let b = loft_with_rails(§ions, std::slice::from_ref(&r), RailFit::Stretch).unwrap(); + let stretched = measure(&b).unwrap(); + let want = 4000.0 + 8000.0 / PI; + assert!(close(volume(&b), want, 1e-4), "stretched: volume {} vs {want}", volume(&b)); + assert!((stretched.bbox.max.x - 10.0).abs() < 1e-2 && (stretched.bbox.max.y - 5.0).abs() < 1e-6, "{:?}", stretched.bbox); + let b = loft_with_rails(§ions, &[r], RailFit::Scale).unwrap(); + let scaled = measure(&b).unwrap(); + let want = 6000.0 + 16000.0 / PI; + assert!(close(volume(&b), want, 1e-4), "scaled: volume {} vs {want}", volume(&b)); + assert!((scaled.bbox.max.y - 10.0).abs() < 1e-2, "{:?}", scaled.bbox); +} + +/// Two rails, one straight up a square's side and one bulging out from the opposite side: the +/// sections run between them, 10 + 5 sin wide. Stretching keeps their depth (volume +/// 4000 + 4000/π); scaling sizes it too (sections (10 + 5 sin)², volume 4500 + 8000/π). +#[test] +fn two_rails_carry_the_sections_between_them() { + let sections = [(at(0.0), square(5.0)), (at(40.0), square(5.0))]; + let rails = [rail(|_| -5.0), rail(|z| 5.0 + 5.0 * bulge(z))]; + let b = loft_with_rails(§ions, &rails, RailFit::Stretch).unwrap(); + let stretched = measure(&b).unwrap(); + let want = 4000.0 + 4000.0 / PI; + assert!(close(volume(&b), want, 1e-4), "stretched: volume {} vs {want}", volume(&b)); + for r in &rails { + let worst = r.iter().map(|p| off(&b, *p)).fold(0.0, f64::max); + assert!(worst < 1e-3, "a rail is {worst} mm off the loft"); + } + assert!((stretched.bbox.min.x + 5.0).abs() < 1e-6 && (stretched.bbox.max.x - 10.0).abs() < 1e-2, "{:?}", stretched.bbox); + let v = volume(&loft_with_rails(§ions, &rails, RailFit::Scale).unwrap()); + let want = 4500.0 + 8000.0 / PI; + assert!(close(v, want, 1e-4), "scaled: volume {v} vs {want}"); +} + +/// A sheet lofted between two 20 mm lines with a rail from one end bulging out by 5: the lines +/// between grow about their middles, 2(10 + 5 sin) long; area 800 + 800/π. +#[test] +fn a_sheet_loft_of_lines_follows_its_rail() { + let line = vec![Seg2::Line { a: Vec2::new(-10.0, 0.0), b: Vec2::new(10.0, 0.0) }]; + let sections = [(at(0.0), line.clone()), (at(40.0), line)]; + let b = loft_sheet_with_rails(§ions, &[rail(|z| 10.0 + 5.0 * bulge(z))], RailFit::Scale).unwrap(); + let m = measure(&b).unwrap(); + let want = 800.0 + 800.0 / PI; + let worst = rail(|z| 10.0 + 5.0 * bulge(z)).iter().map(|p| off(&b, *p)).fold(0.0, f64::max); + assert!(worst < 1e-3, "the rail is {worst} mm off the sheet"); + assert!(close(m.area, want, 1e-3), "area {} vs {want}", m.area); + assert!((m.bbox.max.x - 15.0).abs() < 1e-2 && (m.bbox.min.x + 15.0).abs() < 1e-2, "{:?}", m.bbox); +} + +/// Rails the loft cannot follow are refused, saying why: one that starts off the first section, +/// one that stops short of the last, three rails, and one up the middle of a sheet loft's lines. +#[test] +fn rails_the_loft_cannot_follow_are_refused() { + let sections = [(at(0.0), circle(10.0)), (at(40.0), circle(10.0))]; + let refused = |rails: &[Vec]| match loft_with_rails(§ions, rails, RailFit::Scale) { + Err(KernelError::Invalid(m)) => m, + other => panic!("{other:?}"), + }; + assert!(refused(&[rail(|_| 12.0)]).contains("section 1"), "{}", refused(&[rail(|_| 12.0)])); + let short: Vec = rail(|_| 10.0).into_iter().filter(|p| p.z <= 30.0).collect(); + let m = refused(&[short]); + assert!(m.contains("does not reach section 2"), "{m}"); + assert!(refused(&[rail(|_| 10.0), rail(|_| -10.0), rail(|_| 10.0)]).contains("one or two")); + let line = vec![Seg2::Line { a: Vec2::new(-10.0, 0.0), b: Vec2::new(10.0, 0.0) }]; + match loft_sheet_with_rails(&[(at(0.0), line.clone()), (at(40.0), line)], &[rail(|_| 0.0)], RailFit::Scale) { + Err(KernelError::Invalid(m)) => assert!(m.contains("middle"), "{m}"), + other => panic!("{other:?}"), + } +} diff --git a/crates/kernel/src/surfaces.rs b/crates/kernel/src/surfaces.rs index e625b775f..f47fd0d0d 100644 --- a/crates/kernel/src/surfaces.rs +++ b/crates/kernel/src/surfaces.rs @@ -324,6 +324,13 @@ fn far_wire(swept: &mt::Shell, start: &mt::Wire, map: &dyn Fn(Vec3) -> Vec3) -> /// split to the same number of segments (longest first) and each turned to run the way the one /// before it does. Walls only, no caps; the history has no operands: every face is new. pub fn loft_sheet(sections: &[(Plane, Vec)]) -> Result { + loft_sheet_with_rails(sections, &[], crate::RailFit::Scale) +} + +/// [`loft_sheet`] following one or two guide rails (polylines from the first section to the last, +/// through every section's curve; see [`crate::loft_rails`]), `fit` saying how they reshape the +/// sections between. Without rails, the plain sheet loft. +pub fn loft_sheet_with_rails(sections: &[(Plane, Vec)], rails: &[Vec], fit: crate::RailFit) -> Result { if sections.len() < 2 || sections.len() > 50 { return Err(KernelError::Invalid("a loft needs 2…50 sections".into())); } @@ -345,10 +352,9 @@ pub fn loft_sheet(sections: &[(Plane, Vec)]) -> Result { } crate::build::chain_wire(plane, chain)?; } - let (wires, sources) = if all_closed { + let (wires, sources, reversed) = if all_closed { let loops: Vec<(Plane, solidcraft_geom::Loop2)> = sections.iter().map(|(p, c)| (*p, solidcraft_geom::Loop2 { segs: c.clone() })).collect(); - let (wires, sources, _) = crate::build::loft_wires(&loops)?; - (wires, sources) + crate::build::loft_wires(&loops)? } else { let n = sections.iter().map(|(_, c)| c.len()).max().unwrap_or(0); let mut wires = Vec::with_capacity(sections.len()); @@ -378,13 +384,21 @@ pub fn loft_sheet(sections: &[(Plane, Vec)]) -> Result { wires.push(crate::build::uniform_chain_wire(plane, &pieces, false)?); sources.push(segs.iter().map(|(_, k)| vec![*k]).collect::>()); } - (wires, sources) + (wires, sources, false) }; + let mut planes: Vec = sections.iter().map(|(p, _)| *p).collect(); + if reversed { + planes.reverse(); + } let faces = guard("surface loft", || { - let smooth = if wires.len() >= 3 { crate::build::smooth_loft_faces(&wires, &sources, all_closed).ok() } else { None }; + let all = crate::loft_rails::railed_wires(&planes, &wires, all_closed, rails, fit)?; + // A plain loft falls back to ruled faces where the smooth one fails; a railed one has to + // follow its rails. + let smooth = if all.len() >= 3 { Some(crate::build::smooth_loft_faces(&all, &sources, all_closed)) } else { None }; match smooth { - Some(f) => Ok(f), - None => crate::build::ruled_loft_faces(&wires, &sources), + Some(Ok(f)) => Ok(f), + Some(Err(e)) if !rails.is_empty() => Err(e), + _ => crate::build::ruled_loft_faces(&wires, &sources), } })?; sheet_body(faces) diff --git a/crates/kernel/src/sweep_path.rs b/crates/kernel/src/sweep_path.rs index f2e9292fb..08fb3a95b 100644 --- a/crates/kernel/src/sweep_path.rs +++ b/crates/kernel/src/sweep_path.rs @@ -152,7 +152,7 @@ impl Station { } } -fn clean(path: &[Vec3]) -> Result> { +pub(crate) fn clean(path: &[Vec3]) -> Result> { if path.len() < 2 || path.len() > MAX_PATH_POINTS { return Err(KernelError::Invalid("a sweep path needs 2…100000 points".into())); } @@ -365,7 +365,7 @@ fn controlled_stations(plane: &Plane, pts: &[Vec3], tangents: &[Vec3], mitre: &[ /// after `from` (segment index and fraction along it), with the position it was found at, so a /// walk along the path finds each rail point after the last. Within `tol` of the plane a rail's /// first and last points count as on it (a rail drawn to end where the path ends). -fn rail_crossing(rail: &[Vec3], p: Vec3, t: Vec3, from: (usize, f64), tol: f64) -> Option<(Vec3, (usize, f64))> { +pub(crate) fn rail_crossing(rail: &[Vec3], p: Vec3, t: Vec3, from: (usize, f64), tol: f64) -> Option<(Vec3, (usize, f64))> { let f = |q: Vec3| (q - p).dot(t); let (k0, u0) = from; if k0 == 0 && u0 == 0.0 && rail.first().is_some_and(|q| f(*q).abs() <= tol) { @@ -437,10 +437,7 @@ fn railed_stations(pts: &[Vec3], tangents: &[Vec3], mitre: &[Option<(Vec3, f64)> "the two guide rails start at the same point".into() })); } - let (u0, w0) = { - let u = d0.normalized().ok_or_else(|| KernelError::Invalid("guide rail".into()))?; - (u, t0.cross(u)) - }; + let u0 = d0.normalized().ok_or_else(|| KernelError::Invalid("guide rail".into()))?; let mut out = Vec::with_capacity(pts.len()); for ((anchor, d), t) in across.iter().zip(tangents) { if near(*d) { @@ -450,17 +447,8 @@ fn railed_stations(pts: &[Vec3], tangents: &[Vec3], mitre: &[Option<(Vec3, f64)> format!("the guide rails meet near ({:.3}, {:.3}, {:.3}): the profile would shrink to nothing", anchor.x, anchor.y, anchor.z) })); } - let k = d.len() / d0.len(); - let k_other = match ctl.rail_fit { - RailFit::Scale => k, - RailFit::Stretch => 1.0, - }; let u = d.normalized().ok_or_else(|| KernelError::Invalid("guide rail".into()))?; - let w = t.cross(u); - // Along the path stays along it; across to the rail turns onto the rail and sizes with - // it; the third way follows, scaled evenly or kept. - let map = |v: Vec3| *t * v.dot(t0) + u * (k * v.dot(u0)) + w * (k_other * v.dot(w0)); - let m = [map(Vec3::X), map(Vec3::Y), map(Vec3::Z)]; + let m = rail_frame(t0, u0, *t, u, d.len() / d0.len(), ctl.rail_fit); let st = Station { at: Vec3::default(), m }; // The anchor's start position lands on the anchor. out.push(Station { at: *anchor - st.apply(a0 - s0), m }); @@ -468,6 +456,20 @@ fn railed_stations(pts: &[Vec3], tangents: &[Vec3], mitre: &[Option<(Vec3, f64)> Ok(out) } +/// How guide rails turn and size a section (by columns): the way `along` (unit) turns onto +/// `along_to`, the way across to the rail `across` (unit, square to `along`) turns onto +/// `across_to` and sizes by `k`; the third way follows, sized by `k` as well ([`RailFit::Scale`]) +/// or kept ([`RailFit::Stretch`]). A sweep's stations and a loft's share it. +pub(crate) fn rail_frame(along: Vec3, across: Vec3, along_to: Vec3, across_to: Vec3, k: f64, fit: RailFit) -> [Vec3; 3] { + let k_other = match fit { + RailFit::Scale => k, + RailFit::Stretch => 1.0, + }; + let (w0, w1) = (along.cross(across), along_to.cross(across_to)); + let map = |v: Vec3| along_to * v.dot(along) + across_to * (k * v.dot(across)) + w1 * (k_other * v.dot(w0)); + [map(Vec3::X), map(Vec3::Y), map(Vec3::Z)] +} + /// The volume a profile of `area` on `plane` sweeps through the stations: each station's /// section area times how squarely the path crosses it, summed along the path (trapezoids). fn swept_volume(plane: &Plane, area: f64, st: &[Station], tangents: &[Vec3]) -> f64 { diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 87538992e..532279f4e 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -158,9 +158,11 @@ pub enum Kind { count: String, angle: String, }, - /// Loft through profiles of different sketches, in pick order. + /// Loft through profiles of different sketches, in pick order; `rail_fit` how its guide + /// rails reshape the sections (an index into the sweep dialog's rail fits). Loft { operation: usize, + rail_fit: usize, }, /// Sweep a profile along a path of sketch curves. Sweep { @@ -644,7 +646,10 @@ impl Dialog { Kind::PatternCirc { count: "6".into(), angle: "360 deg".into() }, vec![SelInput::new("Objects", BODIES, true), SelInput::new("Axis", AXES, false)], ), - "solid.loft" => Dialog::new(Kind::Loft { operation: usize::from(has_bodies) }, vec![SelInput::new("Profiles", PROFILES, true)]), + "solid.loft" => Dialog::new(Kind::Loft { operation: usize::from(has_bodies), rail_fit: 0 }, { + let [rail, rail2] = crate::dialogs_sweep::rail_inputs(); + vec![SelInput::new("Profiles", PROFILES, true), rail, rail2] + }), "solid.sweep" => Dialog::new(Kind::Sweep { operation: usize::from(has_bodies), opts: crate::dialogs_sweep::SweepOpts::default() }, { let [rail, rail2] = crate::dialogs_sweep::rail_inputs(); vec![ @@ -2993,7 +2998,8 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { feature_pattern_alignment_row(ui, &mut d.extra, 0); } } - Kind::Loft { operation } => { + Kind::Loft { operation, rail_fit } => { + crate::dialogs_sweep::rail_fit_row(ui, "lf", rail_fit); row_label(ui, "Operation"); combo(ui, "lf_op", &OP_LABELS, operation); ui.end_row(); @@ -4086,7 +4092,7 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result, S pattern_objects(s, sels(d, 0), &mut p); ("solid.pattern.circular", p) } - Kind::Loft { operation } => { + Kind::Loft { operation, rail_fit } => { need(0, "profiles of two or more sketches")?; // One section per sketch, in the order the sketches were first picked. let mut sections: Vec<(u64, Vec)> = Vec::new(); @@ -4102,7 +4108,9 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result, S return Err("pick profiles in two or more sketches".into()); } let sections: Vec = sections.into_iter().map(|(sk, v)| json!({"sketch": sk, "profiles": v})).collect(); - ("solid.loft", json!({"sections": sections, "operation": OPS.get(*operation).copied().unwrap_or("new")})) + let mut p = json!({"sections": sections, "operation": OPS.get(*operation).copied().unwrap_or("new")}); + crate::dialogs_sweep::rail_params(app, *rail_fit, [sels(d, 1), sels(d, 2)], &mut p)?; + ("solid.loft", p) } Kind::Sweep { operation, opts } => { need(0, "a profile")?; @@ -5344,9 +5352,12 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option { + FeatureKind::Loft { sections, operation, targets, rails, rail_fit } => { let mut d = start("solid.loft")?; - d.kind = Kind::Loft { operation: op_index(operation) }; + d.kind = Kind::Loft { operation: op_index(operation), rail_fit: crate::dialogs_sweep::rail_fit_index(*rail_fit) }; + for (inp, items) in d.inputs.iter_mut().skip(1).zip(crate::dialogs_sweep::rail_sels(rails)) { + inp.items = items; + } if let Some(inp) = d.inputs.first_mut() { inp.items = sections .iter() diff --git a/crates/ui-egui/src/dialogs_surface.rs b/crates/ui-egui/src/dialogs_surface.rs index 397ce0fa8..36a23f96c 100644 --- a/crates/ui-egui/src/dialogs_surface.rs +++ b/crates/ui-egui/src/dialogs_surface.rs @@ -27,7 +27,11 @@ pub enum Surf { axis: Option, }, Sweep(crate::dialogs_sweep::SweepOpts), - Loft, + /// `rail_fit`: how the guide rails reshape the sections (an index into the sweep dialog's + /// rail fits). + Loft { + rail_fit: usize, + }, /// `continuity`: an index into [`PATCH_CONTINUITY`] (for a loop of sketch curves, how much of /// the sketch's plane each side repeats; for picked edges, how the surface meets the faces /// beside them); `join`: sew the surface into the body of its edges. @@ -86,7 +90,7 @@ impl Surf { Surf::Extrude { .. } => "SURFACE EXTRUDE", Surf::Revolve { .. } => "SURFACE REVOLVE", Surf::Sweep(_) => "SURFACE SWEEP", - Surf::Loft => "SURFACE LOFT", + Surf::Loft { .. } => "SURFACE LOFT", Surf::Boundary { .. } => "BOUNDARY SURFACE", Surf::Patch { .. } => "PATCH", Surf::Unstitch => "UNSTITCH", @@ -144,7 +148,10 @@ fn inputs(k: &Surf) -> Vec { rail2, ] } - Surf::Loft => vec![SelInput::new("Sections (one sketch each)", PROFILES | CURVES, true)], + Surf::Loft { .. } => { + let [rail, rail2] = crate::dialogs_sweep::rail_inputs(); + vec![SelInput::new("Sections (one sketch each)", PROFILES | CURVES, true), rail, rail2] + } Surf::Boundary { .. } => vec![SelInput::new("Curves", CURVES | EDGES, true), SelInput::new("Cross curves", CURVES | EDGES, true)], Surf::Patch { .. } => vec![SelInput::new("Boundary", PROFILES | EDGES, true), SelInput::new("Pass through", VERTICES | FACES, true)], Surf::Unstitch => vec![SelInput::new("Body, or faces to take out", BODIES | FACES, true)], @@ -174,7 +181,7 @@ pub fn start(_app: &SolveApp, id: &str) -> Option<(Kind, Vec)> { "surface.extrude" => Surf::Extrude { distance: "10 mm".into(), direction: 0 }, "surface.revolve" => Surf::Revolve { angle: "360 deg".into(), symmetric: false, axis: None }, "surface.sweep" => Surf::Sweep(crate::dialogs_sweep::SweepOpts::default()), - "surface.loft" => Surf::Loft, + "surface.loft" => Surf::Loft { rail_fit: 0 }, "surface.boundary" => Surf::Boundary { continuity: 1, join: false }, "surface.patch" => Surf::Patch { continuity: 0 }, "surface.unstitch" => Surf::Unstitch, @@ -304,7 +311,8 @@ pub fn rows(ui: &mut egui::Ui, k: &mut Surf) -> bool { ui.end_row(); } Surf::Sweep(opts) => enter |= crate::dialogs_sweep::rows(ui, opts, "ss"), - Surf::SplitFace | Surf::Unstitch | Surf::ReverseNormal | Surf::Loft => {} + Surf::Loft { rail_fit } => crate::dialogs_sweep::rail_fit_row(ui, "sl", rail_fit), + Surf::SplitFace | Surf::Unstitch | Surf::ReverseNormal => {} } enter } @@ -510,7 +518,7 @@ pub fn commands(app: &SolveApp, k: &Surf, inputs: &[SelInput], extra: &Map { + Surf::Loft { rail_fit } => { need(0, "the sections, one sketch each")?; // One section per sketch, in the order the sketches were first picked. let st = app.session.world_state(); @@ -536,7 +544,9 @@ pub fn commands(app: &SolveApp, k: &Surf, inputs: &[SelInput], extra: &Map>()?; - ("surface.loft", json!({ "sections": sections })) + let mut p = json!({ "sections": sections }); + crate::dialogs_sweep::rail_params(app, *rail_fit, [items(inputs, 1), items(inputs, 2)], &mut p)?; + ("surface.loft", p) } Surf::Boundary { continuity, join } => { need(0, "the curves (sketch curves or edges)")?; @@ -876,8 +886,10 @@ pub fn for_feature(app: &SolveApp, kind: &FeatureKind, frame: &Mat) -> Option<(K let index = PATCH_CONTINUITY.iter().position(|(_, w)| *w == g.as_str()).unwrap_or(0); (Surf::Boundary { continuity: index, join: *operation == solidcraft_engine::doc::Operation::Join }, vec![sels(u), sels(v)]) } - FeatureKind::SurfaceLoft { sections, .. } => { - (Surf::Loft, vec![sections.iter().flat_map(|sec| sheet_sels(app, sec.sketch.0, sec.profiles.as_ref(), &sec.curves)).collect()]) + FeatureKind::SurfaceLoft { sections, rails, rail_fit, .. } => { + let [rail, rail2] = crate::dialogs_sweep::rail_sels(rails); + let picked = sections.iter().flat_map(|sec| sheet_sels(app, sec.sketch.0, sec.profiles.as_ref(), &sec.curves)).collect(); + (Surf::Loft { rail_fit: crate::dialogs_sweep::rail_fit_index(*rail_fit) }, vec![picked, rail, rail2]) } FeatureKind::SurfaceExtrude { sketch, profiles, curves, extent } => { let sels = sheet_sels(app, sketch.0, profiles.as_ref(), curves); diff --git a/crates/ui-egui/src/dialogs_sweep.rs b/crates/ui-egui/src/dialogs_sweep.rs index cc3a716e7..7528e0588 100644 --- a/crates/ui-egui/src/dialogs_sweep.rs +++ b/crates/ui-egui/src/dialogs_sweep.rs @@ -1,6 +1,6 @@ //! The options Sweep and Surface Sweep share (#771): how the profile turns along the path, a //! twist over the path's length, the profile's scale at the end, and guide rails with how they -//! reshape the profile. +//! reshape the profile. Loft and Surface Loft take the same guide rails (#201). use serde_json::{Value, json}; use solidcraft_engine::Sel; @@ -55,7 +55,7 @@ impl SweepOpts { let mut o = SweepOpts { twist: twist.as_ref().map_or_else(|| NO_TWIST.into(), |t| t.to_string()), scale: scale.as_ref().map_or_else(|| NO_SCALE.into(), |k| k.to_string()), - rail_fit: usize::from(rail_fit == RailFit::Stretch), + rail_fit: rail_fit_index(rail_fit), ..SweepOpts::default() }; let mut pick = None; @@ -110,17 +110,25 @@ pub fn rows(ui: &mut egui::Ui, o: &mut SweepOpts, id: &str) -> bool { row_label(ui, "End Scale"); enter |= field(ui, &mut o.scale); ui.end_row(); - row_label(ui, "Rail Fit"); - combo(ui, &format!("{id}_rail_fit"), &RAIL_FITS, &mut o.rail_fit); - ui.end_row(); + rail_fit_row(ui, id, &mut o.rail_fit); enter } -/// The options as command parameters, added to `p`: the orientation, and the twist and end -/// scale when they change anything; with rails picked, the rails (each in the sketch its curves -/// are in) and the fit instead. `picked` is the direction input's selection, `rails` the rail -/// inputs'. -pub fn params(app: &SolveApp, o: &SweepOpts, picked: Option<&Sel>, rails: [&[Sel]; 2], p: &mut Value) -> Result<(), String> { +/// The Rail Fit row: `fit` an index into [`RAIL_FITS`]. +pub fn rail_fit_row(ui: &mut egui::Ui, id: &str, fit: &mut usize) { + row_label(ui, "Rail Fit"); + combo(ui, &format!("{id}_rail_fit"), &RAIL_FITS, fit); + ui.end_row(); +} + +/// A stored rail fit as an index into [`RAIL_FITS`]. +pub fn rail_fit_index(fit: RailFit) -> usize { + usize::from(fit == RailFit::Stretch) +} + +/// The picked rails (each in the sketch its curves are in) and the fit (`fit`, an index into +/// [`RAIL_FITS`]), added to `p`; whether any rail was picked. +pub fn rail_params(app: &SolveApp, fit: usize, rails: [&[Sel]; 2], p: &mut Value) -> Result { let mut given = Vec::new(); for sels in rails { let curves: Vec = sels.iter().filter_map(|x| if let Sel::SketchCurve { id } = x { Some(id.clone()) } else { None }).collect(); @@ -130,12 +138,23 @@ pub fn params(app: &SolveApp, o: &SweepOpts, picked: Option<&Sel>, rails: [&[Sel let sketch = crate::dialogs::curves_sketch(app, &curves, None).ok_or("each rail's curves must be in one sketch")?; given.push(json!({"sketch": sketch, "curves": curves})); } - if !given.is_empty() { - // Rails set the profile's turn and size: the other options don't apply. - p["rails"] = json!(given); - if o.rail_fit == 1 { - p["rail_fit"] = json!("stretch"); - } + if given.is_empty() { + return Ok(false); + } + p["rails"] = json!(given); + if fit == 1 { + p["rail_fit"] = json!("stretch"); + } + Ok(true) +} + +/// The options as command parameters, added to `p`: the orientation, and the twist and end +/// scale when they change anything; with rails picked, the rails (each in the sketch its curves +/// are in) and the fit instead. `picked` is the direction input's selection, `rails` the rail +/// inputs'. +pub fn params(app: &SolveApp, o: &SweepOpts, picked: Option<&Sel>, rails: [&[Sel]; 2], p: &mut Value) -> Result<(), String> { + // Rails set the profile's turn and size: the other options don't apply. + if rail_params(app, o.rail_fit, rails, p)? { return Ok(()); } match o.orientation { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 799369a19..595a674c7 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -72,6 +72,8 @@ pub mod issue_report; pub mod joint_drag; pub mod keymap; mod linked_source; +#[cfg(test)] +mod loft_rails_dialog_tests; mod material_card_review; #[cfg(test)] mod measurement_ui_tests; diff --git a/crates/ui-egui/src/loft_rails_dialog_tests.rs b/crates/ui-egui/src/loft_rails_dialog_tests.rs new file mode 100644 index 000000000..03076e087 --- /dev/null +++ b/crates/ui-egui/src/loft_rails_dialog_tests.rs @@ -0,0 +1,85 @@ +//! The Loft and Surface Loft dialogs' guide rails (#201): rails picked in the dialog reach the +//! commands with their sketches and the fit, and editing the loft brings them back and keeps them. +use crate::dialogs::Kind; +use crate::dialogs_surface::Surf; +use crate::scenario::Harness; +use serde_json::json; +use solidcraft_engine::Sel; +use solidcraft_engine::doc::{FeatureKind, RailFit, SketchId, SweepRail}; + +/// Circles `Base` (z = 0) and `Top` (z = 40) and in `R` on XZ a rail `out` from (10, 0, 0) out to +/// x = 15 halfway and back to (10, 0, 40); the circles' and the rail's sketch ids. +fn setup(h: &mut Harness) -> (u64, u64, u64) { + for (name, z) in [("Base", 0), ("Top", 40)] { + h.app.run("sketch.create", json!({"name": name, "plane": {"origin": [0, 0, z], "x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}})).unwrap(); + h.app.run("sketch.circle.center", json!({"center": [0, 0], "radius": 10})).unwrap(); + h.app.run("sketch.finish", json!({})).unwrap(); + } + h.app.run("sketch.create", json!({"plane": "XZ", "name": "R"})).unwrap(); + h.app.run("sketch.arc.three_point", json!({"start": [10, 0], "end": [10, -40], "through": [15, -20], "id": "out"})).unwrap(); + h.app.run("sketch.finish", json!({})).unwrap(); + let id = |h: &Harness, n: &str| h.app.session.doc.find_feature(n).unwrap().id; + (id(h, "Base"), id(h, "Top"), id(h, "R")) +} + +fn ok(h: &mut Harness) { + h.frames(2); + h.step(&json!({"widget":"OK"})).unwrap(); + assert!(h.app.dialog.is_none(), "{:?} {:?}", h.app.dialog.as_ref().map(|d| &d.error), h.app.session.log); +} + +#[test] +fn a_rail_picked_in_the_loft_dialog_is_kept_through_an_edit() { + let mut h = Harness::new(); + let (base, top, rail_sketch) = setup(&mut h); + h.step(&json!({"call":"ui.start","params":{"command":"solid.loft"}})).unwrap(); + h.frames(3); + assert!(h.widget("Rail").is_some() && h.widget("Rail Fit").is_some()); + let d = h.app.dialog.as_mut().unwrap(); + d.inputs[0].items = vec![Sel::Profile { sketch: base, index: 0 }, Sel::Profile { sketch: top, index: 0 }]; + d.inputs[1].items = vec![Sel::SketchCurve { id: "out".into() }]; + let Kind::Loft { rail_fit, .. } = &mut d.kind else { panic!("{:?}", d.kind) }; + *rail_fit = 1; + ok(&mut h); + let name = h.app.session.doc.features.last().unwrap().name.clone(); + let rails = |h: &Harness| match &h.app.session.doc.find_feature(&name).unwrap().kind { + FeatureKind::Loft { rails, rail_fit, .. } => (rails.clone(), *rail_fit), + k => panic!("{k:?}"), + }; + let (stored, fit) = rails(&h); + assert_eq!(stored, vec![SweepRail { sketch: SketchId(rail_sketch), curves: vec!["out".into()] }]); + assert_eq!(fit, RailFit::Stretch); + h.step(&json!({"call":"ui.editFeature","params":{"feature":name}})).unwrap(); + h.frames(8); + let d = h.app.dialog.as_ref().unwrap(); + assert_eq!(d.inputs[1].items, vec![Sel::SketchCurve { id: "out".into() }]); + assert!(matches!(d.kind, Kind::Loft { rail_fit: 1, .. }), "{:?}", d.kind); + ok(&mut h); + assert_eq!(rails(&h), (stored, fit)); +} + +#[test] +fn a_rail_picked_in_the_surface_loft_dialog_is_kept_through_an_edit() { + let mut h = Harness::new(); + let (base, top, rail_sketch) = setup(&mut h); + h.step(&json!({"call":"ui.start","params":{"command":"surface.loft"}})).unwrap(); + h.frames(3); + assert!(h.widget("Rail").is_some() && h.widget("Rail Fit").is_some()); + let d = h.app.dialog.as_mut().unwrap(); + d.inputs[0].items = vec![Sel::Profile { sketch: base, index: 0 }, Sel::Profile { sketch: top, index: 0 }]; + d.inputs[1].items = vec![Sel::SketchCurve { id: "out".into() }]; + ok(&mut h); + let name = h.app.session.doc.features.last().unwrap().name.clone(); + let rails = |h: &Harness| match &h.app.session.doc.find_feature(&name).unwrap().kind { + FeatureKind::SurfaceLoft { rails, rail_fit, .. } => (rails.clone(), *rail_fit), + k => panic!("{k:?}"), + }; + assert_eq!(rails(&h), (vec![SweepRail { sketch: SketchId(rail_sketch), curves: vec!["out".into()] }], RailFit::Scale)); + h.step(&json!({"call":"ui.editFeature","params":{"feature":name}})).unwrap(); + h.frames(8); + let d = h.app.dialog.as_ref().unwrap(); + assert!(matches!(d.kind, Kind::Surface(Surf::Loft { rail_fit: 0 })), "{:?}", d.kind); + assert_eq!(d.inputs[1].items, vec![Sel::SketchCurve { id: "out".into() }]); + ok(&mut h); + assert_eq!(rails(&h).0.len(), 1); +} From 759e22b5824907ad138edd18f43573f3c3dcd54d Mon Sep 17 00:00:00 2001 From: Karl Von Richter Date: Tue, 20 Oct 2026 03:25:02 +0000 Subject: [PATCH 167/225] Try exact local cuts after invalid empty numerical results (#1765) (#1858) Two empty numerical cut attempts stopped the boolean retry sequence before the exact geometric strategies ran. When the result guard refuses that empty candidate, the exact strategies (sliced planar, pushed walls, local prism, sphere lens, seam halves) now try the cut first; if none recovers it, the original empty candidate and diagnostics are kept, before any displaced numerical retry. Rebased onto main as one commit (the branch's own changes, its merges of main dropped). The only conflict was the new engine regression test next to main's #1985 STEP export tests in boolean_regression_tests.rs; both are kept. --- crates/engine/src/boolean_regression_tests.rs | 24 ++++++ crates/kernel/src/empty_retry_tests.rs | 83 +++++++++++++++++++ crates/kernel/src/ops.rs | 29 ++++++- .../shallow_cuts_after_earlier_pocket.json | 19 +++++ 4 files changed, 152 insertions(+), 3 deletions(-) create mode 100644 crates/kernel/src/empty_retry_tests.rs create mode 100644 examples/regressions/shallow_cuts_after_earlier_pocket.json diff --git a/crates/engine/src/boolean_regression_tests.rs b/crates/engine/src/boolean_regression_tests.rs index 1b751b81f..59a28da74 100644 --- a/crates/engine/src/boolean_regression_tests.rs +++ b/crates/engine/src/boolean_regression_tests.rs @@ -88,6 +88,30 @@ fn read_back(s: &Session, body: &solidcraft_kernel::Body) -> (String, usize) { (text, back.file_faces) } +/// The timeline insertion from #1765 on a small part with analytic material. The kernel test +/// separately forces the empty numerical attempts, without needing the reporter's design. +#[test] +fn shallow_cuts_rebuild_after_inserting_an_earlier_pocket() { + let s = replay(include_str!("../../../examples/regressions/shallow_cuts_after_earlier_pocket.json")); + let rounded_plate = 40.0 * 30.0 * 10.0 - (4.0 - std::f64::consts::PI) * 40.0; + // Half of each circle overlaps the existing 0.75 mm pocket. + let expected = rounded_plate - 30.0 * 10.0 * 0.75 - 2.0 * std::f64::consts::PI * 25.0 * (1.5 - 0.75 / 2.0); + let reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); + for session in [s, reopened] { + assert!(session.model.results.iter().all(|r| r.error.is_none())); + assert_eq!(session.model.state().bodies.len(), 1); + let body = &session.model.state().bodies[0].body; + assert!(body.validity().is_empty(), "{:?}", body.validity()); + let actual = volume(&session, "Plate"); + assert!((actual - expected).abs() < 0.02, "{actual} vs {expected}"); + let mesh = body.tessellate(0.001).unwrap(); + assert!(!mesh.contains(solidcraft_geom::Vec3::new(12.0, 14.0, 9.0))); + assert!(mesh.contains(solidcraft_geom::Vec3::new(12.0, 14.0, 8.0))); + assert!(!mesh.contains(solidcraft_geom::Vec3::new(20.0, 20.0, 9.5))); + assert!(mesh.contains(solidcraft_geom::Vec3::new(20.0, 20.0, 9.0))); + } +} + /// #2059: tabs exactly as wide as their supporting ribs share the ribs' side /// planes. The base's remote conical chamfer must not prevent their join. #[test] diff --git a/crates/kernel/src/empty_retry_tests.rs b/crates/kernel/src/empty_retry_tests.rs new file mode 100644 index 000000000..318bbe87a --- /dev/null +++ b/crates/kernel/src/empty_retry_tests.rs @@ -0,0 +1,83 @@ +//! A shallow circular cut after a pocket (#1765): repeated empty numerical answers must not +//! stop the later geometric strategies. Inject the numerical failure on a real small part; +//! the exact rounding and ray classification of the original design are not available. + +use super::*; +use crate::{box_solid, cylinder, fillet, measure, sphere, step_export, step_import}; +use std::cell::Cell; +use std::f64::consts::PI; + +#[test] +fn shallow_cut_after_a_pocket_recovers_from_empty_numerical_attempts() { + let plate = box_solid(Vec3::ZERO, Vec3::new(40.0, 30.0, 10.0)).unwrap(); + let plate = fillet(&plate, &[Vec3::new(20.0, 0.0, 10.0)], 2.0).unwrap(); + let pocket = box_solid(Vec3::new(5.0, 15.0, 9.25), Vec3::new(35.0, 25.0, 10.25)).unwrap(); + let target = boolean(&plate, &pocket, BoolOp::Cut).unwrap().unwrap(); + let tool = cylinder(Vec3::new(12.0, 15.0, 8.5), Vec3::Z, 5.0, 1.75).unwrap(); + let attempts = Cell::new(0); + let empty = |_: &Body, _: &Body, _: BoolOp, _: Option, _: f64| { + attempts.set(attempts.get() + 1); + Ok((Solid::new_unchecked(Vec::new()), None)) + }; + let (result, diagnostics) = + capture_boolean_diagnostics(|| boolean_via(&target, &tool, BoolOp::Cut, &|a, b, op| boolean_whole_with(a, b, op, false, &empty))); + assert!(attempts.get() >= 2, "the first two numerical tries must really have failed"); + let cut = result.unwrap().expect("a shallow cut leaves the plate"); + assert!(cut.validity().is_empty(), "{:?}", cut.validity()); + assert_eq!(cut.lumps().unwrap().len(), 1); + // Half of the circle overlaps the existing 0.75 mm pocket. + let expected = 40.0 * 30.0 * 10.0 - (4.0 - PI) * 40.0 - 30.0 * 10.0 * 0.75 - PI * 25.0 * (1.5 - 0.75 / 2.0); + let actual = measure(&cut).unwrap().volume; + assert!((actual - expected).abs() < 0.02, "{actual} vs {expected}"); + assert!(diagnostics.events.iter().all(|e| e.strategy != BooleanStrategy::RefinedTolerance)); +} + +#[test] +fn step_seam_cut_recovers_from_empty_numerical_attempts() { + let pin = cylinder(Vec3::new(-5.0, 0.0, 0.0), Vec3::X, 4.5, 10.0).unwrap(); + let target = step_import(&step_export(&[&pin], "seam regression").unwrap()).unwrap().bodies.remove(0).body; + let tool = sphere(Vec3::new(-5.0, 0.0, 0.0), 6.0).unwrap(); + assert!(crate::seam_faces::needed(&target, &tool)); + let attempts = Cell::new(0); + let shifted_attempts = Cell::new(0); + let empty = |_: &Body, _: &Body, _: BoolOp, shift: Option, _: f64| { + attempts.set(attempts.get() + 1); + if shift.is_some() { + shifted_attempts.set(shifted_attempts.get() + 1); + } + Ok((Solid::new_unchecked(Vec::new()), None)) + }; + let (result, diagnostics) = + capture_boolean_diagnostics(|| boolean_via(&target, &tool, BoolOp::Cut, &|a, b, op| boolean_whole_with(a, b, op, false, &empty))); + assert!(attempts.get() >= 2, "the initial numerical tries must really have failed"); + assert_eq!(shifted_attempts.get(), 0, "seam recovery must precede displaced retries"); + let cut = result.unwrap().expect("the spherical cut leaves the end of the pin"); + assert!(cut.validity().is_empty(), "{:?}", cut.validity()); + assert_eq!(cut.lumps().unwrap().len(), 1); + assert!(cut.history().is_some()); + // Along the common axis, integrate min(pi*4.5^2, pi*(6^2-x^2)) from 0 to 6. + let full_radius_end = (6.0_f64.powi(2) - 4.5_f64.powi(2)).sqrt(); + let removed = PI * (4.5_f64.powi(2) * full_radius_end + 36.0 * (6.0 - full_radius_end) - (216.0 - full_radius_end.powi(3)) / 3.0); + let expected = PI * 4.5_f64.powi(2) * 10.0 - removed; + let actual = measure(&cut).unwrap().volume; + assert!((actual - expected).abs() < expected * 1e-3, "{actual} vs {expected}"); + assert!(diagnostics.warning().is_none(), "{:?}", diagnostics.warning()); +} + +#[test] +fn unrecovered_empty_attempts_keep_refusal_without_displacing_tool() { + // These spheres keep fine_tols empty, isolating retries after the exact local strategies. + let target = sphere(Vec3::ZERO, 10.0).unwrap(); + let tool = sphere(Vec3::new(8.0, 0.0, 0.0), 5.0).unwrap(); + let shifted_attempts = Cell::new(0); + let empty = |_: &Body, _: &Body, _: BoolOp, shift: Option, _: f64| { + if shift.is_some() { + shifted_attempts.set(shifted_attempts.get() + 1); + } + Ok((Solid::new_unchecked(Vec::new()), None)) + }; + let result = boolean_via(&target, &tool, BoolOp::Cut, &|a, b, op| boolean_whole_with(a, b, op, false, &empty)); + assert_eq!(shifted_attempts.get(), 0, "unrecovered empty attempts must not enable displaced retries"); + let error = result.unwrap_err(); + assert!(error.to_string().contains("it came out empty"), "{error}"); +} diff --git a/crates/kernel/src/ops.rs b/crates/kernel/src/ops.rs index 865786867..a69977cbb 100644 --- a/crates/kernel/src/ops.rs +++ b/crates/kernel/src/ops.rs @@ -1214,6 +1214,15 @@ fn boolean_whole(a: &Body, b: &Body, op: BoolOp) -> Result> { } fn boolean_whole_with_refinement(a: &Body, b: &Body, op: BoolOp, refine: bool) -> Result> { + boolean_whole_with(a, b, op, refine, &truck_boolean) +} + +/// The whole-body strategies with the numerical intersection supplied separately, so tests +/// can reproduce an empty numerical attempt without depending on a particular ray seed. +fn boolean_whole_with(a: &Body, b: &Body, op: BoolOp, refine: bool, intersect: &F) -> Result> +where + F: Fn(&Body, &Body, BoolOp, Option, f64) -> Result<(Solid, Option)>, +{ if let Some(body) = swept_prism(a, b, op) { return Ok(Some(body)); } @@ -1316,7 +1325,7 @@ fn boolean_whole_with_refinement(a: &Body, b: &Body, op: BoolOp, refine: bool) - // Bounded to two finer meshes; no tool displacement or relaxed acceptance tests. for k in [1e-5, 1e-6] { let tol = (size * k).max(1e-6); - if let Ok((solid, history)) = truck_boolean(a, b, op, None, tol) + if let Ok((solid, history)) = intersect(a, b, op, None, tol) && !solid.boundaries().is_empty() && let Ok(body) = guard("refined boolean result", || recorded::truck_result(solid, history, size, &keep, &counts)) && check(&body).0 @@ -1486,7 +1495,7 @@ fn boolean_whole_with_refinement(a: &Body, b: &Body, op: BoolOp, refine: bool) - for (attempt, j) in JITTER.iter().enumerate().take(2) { let shift = mt::Vector3::new(j[0], j[1], j[2]) * (feature * 0.01); for &tol in &fine_tols { - match truck_boolean(a, b, op, if attempt > 0 { Some(shift) } else { None }, tol) { + match intersect(a, b, op, if attempt > 0 { Some(shift) } else { None }, tol) { Ok((s, _)) if s.boundaries().is_empty() || s.face_iter().next().is_none() => *last = "empty result".into(), Ok((s, h)) => match guard("boolean result", || recorded::truck_result(s, h, size, &keep, &counts)) { Ok(body) => { @@ -1575,10 +1584,17 @@ fn boolean_whole_with_refinement(a: &Body, b: &Body, op: BoolOp, refine: bool) - return Ok(r); } } + // An implausible empty result from the unshifted numerical tries must still give + // the exact strategies above a chance (#1765), including seam-face recovery. If none + // recovers it, keep the original candidate for the outer guard, before displaced retries. + if empty_votes >= 2 && op != BoolOp::Union { + merge(empty_diagnostics); + return Ok(None); + } let shift = mt::Vector3::new(j[0], j[1], j[2]) * (size * 0.01); for k in [2e-3, 5e-4] { let tol = (size * k).max(1e-5); - let r = truck_boolean(a, b, op, if attempt > 0 { Some(shift) } else { None }, tol); + let r = intersect(a, b, op, if attempt > 0 { Some(shift) } else { None }, tol); match r { Ok((s, _)) if s.boundaries().is_empty() || s.face_iter().next().is_none() => { empty_votes += 1; @@ -1622,6 +1638,9 @@ fn boolean_whole_with_refinement(a: &Body, b: &Body, op: BoolOp, refine: bool) - if let Some(body) = fine(&mut last) { return Ok(Some(body)); } + if attempt == 0 && crate::boolean_guard::check_retry(a, b, op, None).is_err() { + continue; + } merge(empty_diagnostics); return Ok(None); } @@ -2339,6 +2358,10 @@ pub(crate) fn half_box(body: &Body, plane: &solidcraft_geom::Plane, positive: bo crate::build::extrude(plane, std::slice::from_ref(&sq), lo, hi)?.pop().ok_or_else(|| KernelError::Failed("half space".into())) } +#[cfg(test)] +#[path = "empty_retry_tests.rs"] +mod empty_retry_tests; + #[cfg(test)] #[path = "prism_fast_path_tests.rs"] mod prism_fast_path_tests; diff --git a/examples/regressions/shallow_cuts_after_earlier_pocket.json b/examples/regressions/shallow_cuts_after_earlier_pocket.json new file mode 100644 index 000000000..1ba14c351 --- /dev/null +++ b/examples/regressions/shallow_cuts_after_earlier_pocket.json @@ -0,0 +1,19 @@ +{ + "description": "Public-safe companion for #1765: a 40 x 30 x 10 plate with a 2 mm round on its top-front edge and two radius-5 circular cuts 1.5 mm deep. Roll back before the circles, insert a 30 x 10 pocket 0.75 mm deep across their upper halves, restore the timeline and redefine the circular cut. This part checks the rebuild and analytic material; empty numerical attempts are injected separately in the kernel regression, since the original design is unavailable.", + "commands": [ + {"command": "solid.box", "params": {"length": 40, "width": 30, "height": 10, "body_name": "Plate", "name": "Plate"}}, + {"command": "solid.fillet", "params": {"edges": [[20, 0, 10]], "radius": 2, "name": "Rim"}}, + {"command": "sketch.create", "params": {"plane": "XY", "offset": 10, "name": "Circles"}}, + {"command": "sketch.circle.center", "params": {"center": [12, 15], "radius": 5}}, + {"command": "sketch.circle.center", "params": {"center": [28, 15], "radius": 5}}, + {"command": "sketch.finish", "params": {}}, + {"command": "solid.extrude", "params": {"sketch": "Circles", "distance": -1.5, "operation": "cut", "name": "ShallowCuts"}}, + {"command": "timeline.rollback", "params": {"position": 2}}, + {"command": "sketch.create", "params": {"plane": "XY", "offset": 10, "name": "PocketOutline"}}, + {"command": "sketch.rectangle.two_point", "params": {"p0": [5, 15], "p1": [35, 25]}}, + {"command": "sketch.finish", "params": {}}, + {"command": "solid.extrude", "params": {"sketch": "PocketOutline", "distance": -0.75, "operation": "cut", "name": "EarlierPocket"}}, + {"command": "timeline.rollback", "params": {}}, + {"command": "timeline.redefine", "params": {"feature": "ShallowCuts", "command": "solid.extrude", "params": {"sketch": "Circles", "profiles": [0, 1], "distance": "-1.5", "direction": "positive", "convention": "total_distance", "operation": "cut"}}} + ] +} From fa3ada19838cf666fb7bcf3a626834b0e7ca4570 Mon Sep 17 00:00:00 2001 From: Colin Faulkingham Date: Tue, 20 Oct 2026 03:25:05 +0000 Subject: [PATCH 168/225] claim: #2708 (#2739) Co-authored-by: bherbruck --- ROADMAP.md | 7 +- crates/engine/src/cmd/edit_tests.rs | 52 ++++++++++ crates/engine/src/cmd/features.rs | 2 +- crates/kernel/src/blend.rs | 154 ++++++++++++++++++++++++---- docs/book/src/guide/features.md | 5 +- 5 files changed, 192 insertions(+), 28 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 327201486..2c06fcd4f 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -347,9 +347,10 @@ completed drawings publish atomically. The browser still exports synchronously. - Associative shell-face sketches require a unique certified planar source. Nested shell attachments and ambiguous coincident sources remain unsupported. -- G2 fillets: exact quintic blends of straight edges between planar faces, with one perpendicular - planar end face at each end. The UI and `solid.fillet` expose `curvature` (alias `g2`); the size - is an equivalent circular setback. Curved faces/edges, sloped ends and corner junctions remain unsupported. +- G2 fillets: exact quintic blends of straight edges between planar faces, with one planar + end face at each end, including sloped ends (#2708). The UI and `solid.fillet` expose + `curvature` (alias `g2`); the size is an equivalent circular setback. Curved faces/edges, + multi-face ends and corner junctions remain unsupported. - Fillets and chamfers: constant, variable-radius and chord-length fillets; a radius per edge, rounds next to earlier rounds of another radius, and smooth corner patches where three rounds meet (a sphere for equal radii); perpendicular corner fillets after a closed ring of earlier diff --git a/crates/engine/src/cmd/edit_tests.rs b/crates/engine/src/cmd/edit_tests.rs index 9e78e2a14..d4acb82ae 100644 --- a/crates/engine/src/cmd/edit_tests.rs +++ b/crates/engine/src/cmd/edit_tests.rs @@ -52,6 +52,58 @@ fn g2_fillet_survives_edit_undo_and_reopen() { assert!(s.execute("solid.fillet", &json!({"edges": [[0, 0, 10]], "radius": 2, "type": "curvature", "fit": "reduce"})).is_err()); } +#[test] +fn redefining_a_fillet_as_g2_on_sloped_ends_survives_undo_and_reopen() { + use solidcraft_doc::{Document, FeatureKind, FilletStyle}; + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY"})); + run(&mut s, "sketch.line", json!({"points": [[0, 0], [40, 0], [30, 20], [10, 20]], "closed": true})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"distance": 20})); + run(&mut s, "solid.fillet", json!({"edges": [[20, 0, 20]], "radius": 5, "name": "Fillet1"})); + let original = s.doc.clone(); + let id = s.doc.find_feature("Fillet1").unwrap().id; + // #2708: changing an existing constant fillet to Curvature (G2) in Edit Feature. + run( + &mut s, + "timeline.redefine", + json!({"feature": id, "command": "solid.fillet", "params": {"edges": [[20, 0, 20]], "radius": "5", "type": "curvature"}}), + ); + let f = s.doc.find_feature("Fillet1").unwrap(); + assert_eq!(f.id, id); + assert!(matches!(&f.kind, FeatureKind::Fillet { style: FilletStyle::Curvature, .. })); + // Use a fixed fine chord tolerance for the analytic comparison; Measure's + // adaptive display tolerance is coarser and need not satisfy this bound. + let volume = |s: &Session| { + let bodies = &s.model.state().bodies; + assert_eq!(bodies.len(), 1); + bodies.first().unwrap().body.tessellate(0.0001).unwrap().measure().volume + }; + let expected = |r: f64| 12000.0 - 40.0 * 113.0 / 756.0 * r.powi(2) + 13711.0 / 486486.0 * r.powi(3); + let actual = volume(&s); + assert!((actual - expected(5.0)).abs() < 0.05, "{actual} vs {}", expected(5.0)); + let edited = s.doc.clone(); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc, original); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.doc, edited); + let mut reopened = Session::new(Document::from_json(&s.doc.to_json()).unwrap()); + assert!((volume(&reopened) - expected(5.0)).abs() < 0.05); + run(&mut reopened, "timeline.edit", json!({"feature": id, "set": {"radius": "3"}})); + assert!((volume(&reopened) - expected(3.0)).abs() < 0.05); + let before = reopened.doc.clone(); + assert!( + reopened + .execute( + "timeline.redefine", + &json!({"feature": id, "command": "solid.fillet", "params": {"edges": [[20, 0, 20]], "radius": 100, "type": "curvature"}}) + ) + .is_err() + ); + assert_eq!(reopened.doc, before); + assert!((volume(&reopened) - expected(3.0)).abs() < 0.05); +} + #[test] fn redefining_a_blend_replaces_persistent_edge_selection_and_survives_resize() { let mut s = Session::default(); diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs index 4d5c01f8d..ec9d9748e 100644 --- a/crates/engine/src/cmd/features.rs +++ b/crates/engine/src/cmd/features.rs @@ -36,7 +36,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .at("SOLID", "MODIFY") .icon("fillet") .key("F") - .params("edges: [[x,y,z] point on edge | {body, index}]; radius: expr; body?; type?: constant|curvature (alias g2: curvature-continuous quintic between planar faces along straight edges, one perpendicular planar end face at each end; radius sets the equivalent circular setback, not constant curvature; exact fit only)|chord (radius is the width across)|variable (radius at the end nearest start, radius2 at the other; one end may be 0, where the round closes to the corner)|spline (the radius along the edge is a clamped B-spline from the end nearest start: radius is its first control radius, radii the rest, knots its knot vector from 0 to 1; one end may be 0); radius2?; start?: [x,y,z]; radii?: [expr, …]; knots?: [number, …]; mid?: [[position 0…1 from start, radius expr], …] (variable radii between the ends); smooth?: bool (smooth instead of straight between the radii); corner?: rolling|g2 (rolling, the default: the corners where three blended edges meet are pieces of the rolling ball's sphere, tangent to each blend; g2: a patch repeating each blend's surface up to the second order, constant-radius exact fillets only, refused where it cannot be built); fit?: exact|reduce|taper (exact, the default: a radius too large for the geometry around the edges is refused; reduce: where it doesn't fit it is reduced to the largest that does, one radius for edges sharing a face; the smallest used is returned as `radius_applied`, each edge's as `radii_applied: [{edge: [x,y,z], radius}]`, and noted in the feature's warning; taper: along each straight edge between planar faces where it doesn't fit, the radius follows the room there as a smooth spline, down to 0 where a face closes to a point, noted in the feature's warning)"), + .params("edges: [[x,y,z] point on edge | {body, index}]; radius: expr; body?; type?: constant|curvature (alias g2: curvature-continuous quintic between planar faces along straight edges, one planar end face at each end (including sloped ends); radius sets the equivalent circular setback, not constant curvature; exact fit only)|chord (radius is the width across)|variable (radius at the end nearest start, radius2 at the other; one end may be 0, where the round closes to the corner)|spline (the radius along the edge is a clamped B-spline from the end nearest start: radius is its first control radius, radii the rest, knots its knot vector from 0 to 1; one end may be 0); radius2?; start?: [x,y,z]; radii?: [expr, …]; knots?: [number, …]; mid?: [[position 0…1 from start, radius expr], …] (variable radii between the ends); smooth?: bool (smooth instead of straight between the radii); corner?: rolling|g2 (rolling, the default: the corners where three blended edges meet are pieces of the rolling ball's sphere, tangent to each blend; g2: a patch repeating each blend's surface up to the second order, constant-radius exact fillets only, refused where it cannot be built); fit?: exact|reduce|taper (exact, the default: a radius too large for the geometry around the edges is refused; reduce: where it doesn't fit it is reduced to the largest that does, one radius for edges sharing a face; the smallest used is returned as `radius_applied`, each edge's as `radii_applied: [{edge: [x,y,z], radius}]`, and noted in the feature's warning; taper: along each straight edge between planar faces where it doesn't fit, the radius follows the room there as a smooth spline, down to 0 where a face closes to a point, noted in the feature's warning)"), CommandSpec::new("solid.chamfer", "Chamfer", chamfer).at("SOLID", "MODIFY").icon("chamfer").params("edges: [[x,y,z] | {body, index}]; distance: expr; distance2?: expr (along the second face) | angle?: expr (from the first face); flip?: bool (which face is first: by default the one facing up most); body?"), CommandSpec::new("solid.combine", "Combine", combine).at("SOLID", "MODIFY").icon("combine").params("target: body; tools: [body]; operation?: join|cut|intersect; keep_tools?: bool; new_component?: bool (the result goes into a new component; component_name?)"), CommandSpec::new("solid.pattern.rectangular", "Rectangular Pattern", pattern_rect) diff --git a/crates/kernel/src/blend.rs b/crates/kernel/src/blend.rs index 60f349e4f..66a2d3d17 100644 --- a/crates/kernel/src/blend.rs +++ b/crates/kernel/src/blend.rs @@ -1,9 +1,9 @@ //! Edge fillets and chamfers as a local B-rep operation. //! //! Supported locally: a straight edge between two planar faces whose two end vertices each -//! touch exactly one more planar face. Fillets require perpendicular end faces; chamfers -//! intersect their offset rails with the end planes, including sloped walls. The end faces get an arc -//! (fillet) or a line (chamfer) at the corner, and a cylindrical (or planar) face is inserted. +//! touch exactly one more planar face. The offset rails intersect the end planes, including +//! sloped walls. The end faces get an arc (round fillet), a quintic (G2 fillet) or a line +//! (chamfer) at the corner, and a cylindrical, quintic or planar face is inserted. //! The result is exact. Edges meeting at an already blended corner, curved edges and other //! configurations are reported as not supported yet. @@ -468,10 +468,8 @@ fn blend_geometry( [x, y] if shared(i1, y).is_some() && shared(i2, x).is_some() => (y, x), _ => return Err(unsupported("each end of the edge must touch exactly one more face")), }; - if shape == Shape::Curvature - && (others.len() != 1 || faces.get(ga).and_then(|f| plane_normal(f)).is_none_or(|n| n.dot(d).abs() < 1.0 - 1e-12)) - { - return Err(unsupported("G2 fillets require one planar end face perpendicular to the edge at each end")); + if shape == Shape::Curvature && (others.len() != 1 || faces.get(ga).and_then(|f| plane_normal(f)).is_none()) { + return Err(unsupported("G2 fillets require one planar end face at each end")); } // An end face that is not a plane, or meets the side faces in curves: the rails end where // they reach its surface, and the blend's end is where its surface meets the end face @@ -879,6 +877,11 @@ fn blend_geometry( let rail_a = used_up(i1, &end0.ca, &end1.ca)?; let rail_b = used_up(i2, &end0.cb, &end1.cb)?; let vertex = |c: &Option, p: Vec3| c.clone().unwrap_or_else(|| builder::vertex(p3(p))); + // Projection along the edge is affine, so projecting the six controls gives + // the exact quintic on an oblique end plane. The end-plane check above has + // already refused planes parallel to d. Use these same controls for the + // surface below, including where an outward slope extends past the old edge. + let g2_section = |p: Vec3, (o, n): (Vec3, Vec3)| g2_controls(p, t1, t2, s).map(|q| q - d * ((q - o).dot(n) / d.dot(n))); // Corner curves on the end faces (A → B): the blend's cross-section through the end vertex, // slid along the edge onto each end plane (an ellipse arc; the circle itself on a square // end face). @@ -887,7 +890,7 @@ fn blend_geometry( return Ok(builder::line(va, vb)); } if shape == Shape::Curvature { - let controls = g2_controls(p, t1, t2, s); + let controls = g2_section(p, plane); return Ok(builder::bezier(va, vb, controls.into_iter().skip(1).take(4).map(p3).collect())); } let c = centre(p); @@ -1028,8 +1031,17 @@ fn blend_geometry( let blend_face = match shape { Shape::Flat => builder::try_attach_plane(&[wire]).map_err(|e| KernelError::Failed(format!("chamfer face: {e}")))?, Shape::Curvature => { - let controls = g2_controls(p0, t1, t2, s); - let ctrl = controls.into_iter().map(|p| vec![p3(p), p3(p + p1 - p0)]).collect(); + let ([plane0], [plane1]) = (&end0.planes[..], &end1.planes[..]) else { + return Err(unsupported("G2 fillets require one planar end face at each end")); + }; + let (start, end) = (g2_section(p0, *plane0), g2_section(p1, *plane1)); + // A ruled patch between the two sections stays on the quintic's + // extrusion: corresponding controls differ only along d. Positive + // spans throughout their convex hull keep the surface from folding. + if start.iter().zip(&end).any(|(a, b)| !a.is_finite() || !b.is_finite() || (*b - *a).dot(d) <= tol) { + return Err(too_large("the blend is larger than the neighbouring faces")); + } + let ctrl = start.into_iter().zip(end).map(|(a, b)| vec![p3(a), p3(b)]).collect(); let bsp = mt::BSplineSurface::new((mt::KnotVec::bezier_knot(5), mt::KnotVec::bezier_knot(1)), ctrl); let mut surf = mt::Surface::BSplineSurface(bsp); use mt::ParametricSurface3D; @@ -1096,7 +1108,7 @@ fn g2_controls(p: Vec3, t1: Vec3, t2: Vec3, setback: f64) -> [Vec3; 6] { /// Curvature-continuous (G2) fillets between planar faces along straight edges. /// `radius` sets the same setback as a circular fillet; the profile is not circular. -/// Each end must meet one planar face perpendicular to the edge. Unsupported +/// Each end must meet one planar face, which may be oblique to the edge. Unsupported /// configurations are refused, never replaced with a G1 circular fillet. pub fn fillet_g2(body: &Body, edges: &[Vec3], radius: f64) -> Result { body.require_brep("G2 fillet")?; @@ -2694,6 +2706,115 @@ mod tests { } } + #[test] + fn g2_fillet_meets_sloped_planar_ends_with_zero_rail_curvature() { + use mt::{InnerSpace, ParametricCurve, ParametricSurface, SearchParameter}; + // Inward and outward sloping ends, and one square end, in two orientations. + // Outward slopes need end curves beyond the old edge's axial range (#2708). + for plane in [Plane::XY, Plane::XZ] { + for (left, right) in [(-0.5, -0.5), (0.5, 0.5), (0.0, 0.5), (-0.25, 0.5)] { + let region = Region2 { + outer: Loop2::polygon(&[Vec2::ZERO, Vec2::new(40.0, 0.0), Vec2::new(40.0 - right * 20.0, 20.0), Vec2::new(left * 20.0, 20.0)]), + holes: vec![], + }; + let body = crate::extrude(&plane, &[region], 0.0, 20.0).unwrap().pop().unwrap(); + let pick = plane.to_world(Vec2::new(20.0, 0.0)) + plane.normal() * 20.0; + let out = fillet_g2(&body, &[pick], 5.0).unwrap(); + assert!(out.validity().is_empty(), "{:?}", out.validity()); + assert_eq!(out.crossed_face_loops().unwrap(), 0); + assert_eq!(out.face_count(), 7); + let solid = out.deep_copy(); + let face = solid.face_iter().find(|f| matches!(f.surface(), mt::Surface::BSplineSurface(_))).unwrap(); + let surf = face.surface(); + let mut sections = 0; + for edge in face.edge_iter() { + if let mt::Curve::BSplineCurve(c) = edge.curve() { + for k in 0..=20 { + let q = c.subs(f64::from(k) / 20.0); + let uv = plane.to_local(from_p3(q)); + assert!((uv.x - left * uv.y).abs() < 1e-8 || (uv.x + right * uv.y - 40.0).abs() < 1e-8); + let (u, v) = surf.search_parameter(q, None, 100).expect("end curve on the G2 surface"); + assert!((surf.subs(u, v) - q).magnitude() < 1e-8); + } + sections += 1; + } + } + assert_eq!(sections, 2); + // A parameter swap on inversion is allowed; identify the rails by + // the original side planes and check the whole second fundamental form. + for along in [0.1, 0.5, 0.9] { + let mut rails = 0; + for (u, v) in [(0.0, along), (1.0, along), (along, 0.0), (along, 1.0)] { + let q = from_p3(surf.subs(u, v)); + let y = plane.to_local(q).y; + let z = (q - plane.origin).dot(plane.normal()); + let expected = if y.abs() < 1e-8 { + plane.y + } else if (z - 20.0).abs() < 1e-8 { + plane.normal() + } else { + continue; + }; + let n = surf.uder(u, v).cross(surf.vder(u, v)).normalize(); + assert!(n.cross(v3(expected)).magnitude() < 1e-8); + for second in [surf.uuder(u, v), surf.uvder(u, v), surf.vvder(u, v)] { + assert!(second.dot(n).abs() < 1e-8); + } + rails += 1; + } + assert_eq!(rails, 2); + } + // Analytic volume: the removed section has area 113 r² / 756 + // and first moment ∫y dA = 13711 r³ / 486486, obtained by integrating + // the quintic's x(t)y'(t) and x(t)y(t)y'(t). Axial length is 40−(left+right)y. + let removed = 40.0 * 113.0 / 756.0 * 25.0 - (left + right) * 13711.0 / 486486.0 * 125.0; + let expected = 16000.0 - 4000.0 * (left + right) - removed; + let volume = out.tessellate(0.0001).unwrap().measure().volume; + assert!((volume - expected).abs() < 0.05, "{volume} vs {expected}"); + } + } + } + + #[test] + fn g2_fillet_on_concave_edge_meets_caps_sloped_in_both_directions() { + use mt::{ParametricCurve, ParametricSurface, SearchParameter}; + let region = Region2 { + outer: Loop2::polygon(&[ + Vec2::ZERO, + Vec2::new(20.0, 0.0), + Vec2::new(20.0, 10.0), + Vec2::new(10.0, 10.0), + Vec2::new(10.0, 20.0), + Vec2::new(0.0, 20.0), + ]), + holes: vec![], + }; + let body = crate::extrude(&Plane::XY, &[region], 0.0, 20.0).unwrap().pop().unwrap(); + // z -> z + 0.3x + 0.4y tilts both caps while leaving the vertical edge + // and its side planes unchanged. This shear preserves volume. + let body = crate::transform_matrix(&body, [[1.0, 0.0, 0.3, 0.0], [0.0, 1.0, 0.4, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]).unwrap(); + let out = fillet_g2(&body, &[Vec3::new(10.0, 10.0, 17.0)], 2.0).unwrap(); + assert!(out.validity().is_empty(), "{:?}", out.validity()); + assert_eq!(out.crossed_face_loops().unwrap(), 0); + let solid = out.deep_copy(); + let face = solid.face_iter().find(|f| matches!(f.surface(), mt::Surface::BSplineSurface(_))).unwrap(); + let surf = face.surface(); + for edge in face.edge_iter() { + if let mt::Curve::BSplineCurve(c) = edge.curve() { + for k in 0..=20 { + let q = c.subs(f64::from(k) / 20.0); + let height = q.z - 0.3 * q.x - 0.4 * q.y; + assert!(height.abs() < 1e-8 || (height - 20.0).abs() < 1e-8); + let (u, v) = surf.search_parameter(q, None, 100).unwrap(); + assert!(from_p3(surf.subs(u, v)).dist(from_p3(q)) < 1e-8); + } + } + } + let volume = out.tessellate(0.0001).unwrap().measure().volume; + let expected = 6000.0 + 113.0 / 756.0 * 4.0 * 20.0; + assert!((volume - expected).abs() < 0.02, "{volume} vs {expected}"); + } + #[test] fn g2_fillet_refuses_invalid_and_unsupported_geometry() { let body = crate::build::box_solid(Vec3::ZERO, Vec3::new(20.0, 20.0, 20.0)).unwrap(); @@ -2714,17 +2835,6 @@ mod tests { fillet_g2(&boss, &[Vec3::new(40.0, 4.0, 20.0)], 0.8), Err(KernelError::Failed(message)) if message.contains("G2 fillets require one planar end face") )); - for slope in [-0.5, 0.5] { - let region = Region2 { - outer: Loop2::polygon(&[Vec2::ZERO, Vec2::new(40.0, 0.0), Vec2::new(40.0 - slope * 20.0, 20.0), Vec2::new(slope * 20.0, 20.0)]), - holes: vec![], - }; - let sloped = crate::extrude(&Plane::XY, &[region], 0.0, 20.0).unwrap().pop().unwrap(); - assert!(matches!( - fillet_g2(&sloped, &[Vec3::new(20.0, 0.0, 20.0)], 2.0), - Err(KernelError::Failed(message)) if message.contains("G2 fillets require one planar end face") - )); - } } #[test] diff --git a/docs/book/src/guide/features.md b/docs/book/src/guide/features.md index 40485f110..6d91b167b 100644 --- a/docs/book/src/guide/features.md +++ b/docs/book/src/guide/features.md @@ -98,8 +98,9 @@ ball). See the roadmap's known limitations for the rest. **Curvature (G2)** in the Fillet dialog's **Radius Type** blends straight edges between two planar faces with an exact quintic section. The tangent plane and curvature match each side face: curvature goes to zero at both contact rails, unlike a circular G1 fillet. Each end -must meet one planar face perpendicular to the edge. Curved edges/faces, sloped or multi-face -ends, and intersecting corner blends are not supported; they return an error, not a G1 fallback. +must meet one planar face; perpendicular and sloped planar ends are supported. Curved +edges/faces, multi-face ends, and intersecting corner blends are not supported; they return +an error, not a G1 fallback. **Equivalent Radius** sets the same contact setback as a circular fillet (for a right angle, setback equals the entered value); it is not a constant curvature radius. Reduce/Taper to Fit are unavailable for this type. From 25ea9e6419e2848dd0fb814234fab4842ebf2c1d Mon Sep 17 00:00:00 2001 From: Nathan Dane Date: Tue, 20 Oct 2026 03:25:17 +0000 Subject: [PATCH 169/225] icons: add the silhouette master and wire it to inspect.silhouette (#2102) Co-authored-by: bherbruck --- ATTRIBUTION.md | 1 + assets/icons/ui/design/review.json | 1 + assets/icons/ui/design/svg/model/silhouette.svg | 10 ++++++++++ crates/engine/src/cmd/silhouette.rs | 2 +- 4 files changed, 13 insertions(+), 1 deletion(-) create mode 100644 assets/icons/ui/design/svg/model/silhouette.svg diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index c39715f38..d109bb129 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -280,6 +280,7 @@ Editable drawing code, native projects and shipped exports are collected under ` | assets/icons/ui/design/svg/model/pattern_rect.svg | SolidCraft contributors | two-tone modelling icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 | | assets/icons/ui/design/svg/model/perforate.svg | SolidCraft contributors | two-tone modelling icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 | | assets/icons/ui/design/svg/model/pipe.svg | SolidCraft contributors | two-tone modelling icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 | +| assets/icons/ui/design/svg/model/silhouette.svg | SolidCraft contributors | original icon master (64 grid) | MIT OR Apache-2.0 | | assets/icons/ui/design/svg/model/placeholder.svg | SolidCraft contributors | two-tone modelling icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 | | assets/icons/ui/design/svg/model/plane.svg | SolidCraft contributors | two-tone modelling icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 | | assets/icons/ui/design/svg/model/plane_angle.svg | SolidCraft contributors | two-tone modelling icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 | diff --git a/assets/icons/ui/design/review.json b/assets/icons/ui/design/review.json index bfca6a81b..e8381d42c 100644 --- a/assets/icons/ui/design/review.json +++ b/assets/icons/ui/design/review.json @@ -218,6 +218,7 @@ "sheet": "774e30923ef6f37dd9c0b2bc3e45705e83b3a76700bf071cd41155a365d0daa4", "sheet_rules": "b8c3a67c82be20fc00c109decc566e8755d70167e04e0a9fb92941f7b27aa993", "shell": "a1959ea0d0441a479bf654b6e549e2e44a0bfdc9cda4eb46fe1fbfd884de7e38", + "silhouette": "2a848aed2f247b1c0439f830a34a513c93bc5493c40044c821d493d863ad996e", "sketch": "b52e5862b1709a9a7e3ca00d7436d126fbfc01b38080006fa4e17dc581dfa103", "sketch_break": "430582243311f304dbab397ce58c8c9aef9c78ed88d3e921a57e584ddb95d94c", "sketch_chamfer": "80ab27a9929f9cf0ab2f827757e007173d74ddca6c19af238931c40d4cd874b4", diff --git a/assets/icons/ui/design/svg/model/silhouette.svg b/assets/icons/ui/design/svg/model/silhouette.svg new file mode 100644 index 000000000..9522a808b --- /dev/null +++ b/assets/icons/ui/design/svg/model/silhouette.svg @@ -0,0 +1,10 @@ + + Silhouette + + + + + + + + diff --git a/crates/engine/src/cmd/silhouette.rs b/crates/engine/src/cmd/silhouette.rs index 1f482f5d8..f44a9f02f 100644 --- a/crates/engine/src/cmd/silhouette.rs +++ b/crates/engine/src/cmd/silhouette.rs @@ -12,7 +12,7 @@ const CMD: &str = "inspect.silhouette"; const MAX_PIXELS: usize = 4 * 1024 * 1024; // For agents comparing the model with a picture; nothing to show a person, so no toolbar button. -pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new(CMD, "Silhouette", run).icon("project").noundo().params( +pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new(CMD, "Silhouette", run).noundo().icon("silhouette").params( "view?: front|back|left|right|top|bottom|iso (default front); or camera?: {target: [x,y,z], yaw, pitch, distance, fov?} (mm, radians; fov 0 means parallel); bodies?: [world body names] (default visible bodies, named hidden bodies included); rows?: mask height in pixels (default 240, clamped to 16..1024) → tightly framed run-length mask, box_mm, mm_per_px, right/up, projection, body and triangle counts", )]; From b168750fb3f4ecc68419525450406bcb54108ba6 Mon Sep 17 00:00:00 2001 From: phanoob Date: Tue, 20 Oct 2026 03:28:11 +0000 Subject: [PATCH 170/225] Viewport: the ground grid stays when zoomed in close (#3087) (#3124) * claim: #3087 Co-Authored-By: Claude Opus 5.5 * Viewport: the ground grid is centred where the view's axis meets the ground (#3087) Co-Authored-By: Claude Opus 5.5 * Grid: its centre stays within reach of the point under the target At a grazing slant in perspective, where the view's axis meets the ground runs far off, and the ground in front of the camera had no grid. The centre now moves no further than the grid's half-size from the point under the target (review of #3124). Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Phanoob Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/viewport.rs | 83 +++++++++++++++++++++++++++++++++- 1 file changed, 81 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 8e8a177a9..033aa3e91 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -749,7 +749,7 @@ fn build_sketch_scene(app: &SolveApp, proj: &Proj) -> GpuScene { let sketch_plane = solidcraft_engine::view::open_sketch_plane(s); if sketch_plane.is_some() || (app.ui.show_grid && !active_view(app).hide_grid) { let (minor, major) = grid_step(app.cam.half_height()); - let ext = (app.cam.half_height() * 3.0 / major).ceil() * major; + let mut ext = (app.cam.half_height() * 3.0 / major).ceil() * major; // An open sketch always has its grid on its own plane; otherwise the ground plane: XY with // Z up, XZ with Y up (laid out in the camera's Z-up frame), or the upright origin plane // facing the view when the ground is seen edge-on. @@ -768,7 +768,17 @@ fn build_sketch_scene(app: &SolveApp, proj: &Proj) -> GpuScene { } else { (Vec3::X, Vec3::Y) }; - let snap = |a: Vec3| a * ((tf.dot(a) / major).round() * major); + // Centred where the view's axis meets the ground, the part of the ground in the middle + // of the view (#3087): the camera's target may lie off the ground (above a part, or + // below the ground after an orbit), and zoomed in, a grid round the point under the + // target was off screen. Seen at a slant the ground stretches across the view, so the + // grid reaches further. + let back = app.cam.to_frame(app.cam.back()); + let n = u.cross(v); + let slant = back.dot(n); + ext = (ext / slant.abs().max(0.25) / major).ceil() * major; + let centre = grid_centre(tf, back, n, ext); + let snap = |a: Vec3| a * ((centre.dot(a) / major).round() * major); (snap(u) + snap(v), u, v, Box::new(|p| app.cam.from_frame(p).to_f32())) }; let n = ((ext / minor) as i64).clamp(1, 300); @@ -3243,6 +3253,21 @@ fn points_2d(app: &SolveApp, painter: &egui::Painter, proj: &Proj) { } } +/// Where the ground grid is centred: where the view's axis (`back`, through the camera's target +/// `tf`) meets the plane through the origin with normal `n`, so the middle of the view has grid +/// (#3087). At a grazing slant that point runs far off, and the ground in front of the camera +/// would have none: it stays within `ext` (the grid's half-size) of the point under the target. +fn grid_centre(tf: Vec3, back: Vec3, n: Vec3, ext: f64) -> Vec3 { + let under = tf - n * tf.dot(n); + let slant = back.dot(n); + if slant.abs() <= 1e-3 { + return under; + } + let along = tf - back * (tf.dot(n) / slant) - under; + let len = along.len(); + if len > ext && len > 0.0 { under + along * (ext / len) } else { under + along } +} + /// Hover feedback for the active sketch's points and curves (drawn on top of everything). fn hover_highlight(app: &SolveApp, painter: &egui::Painter, proj: &Proj) { let col = Tokens::get().hover_profile_edge; @@ -6493,6 +6518,60 @@ mod grid_plane_tests { assert_eq!(*app.viewport.grid_plane.lock().unwrap(), GridPlane::Ground, "a clear turn off the ground returns"); } + /// The grid's centre is where the view's axis meets the ground, but at a grazing slant (a + /// camera 10 mm above the ground, looking almost along it) no further than the grid's + /// half-size from the point under the target, so the ground in front of the camera keeps + /// its grid. + #[test] + fn the_grid_centre_stays_within_reach_of_the_point_under_the_target() { + let n = Vec3::Z; + // Looking down at 45 degrees at a target 10 above the ground: the axis meets it 10 ahead. + let tf = Vec3::new(0.0, 0.0, 10.0); + let back = Vec3::new(0.0, -1.0, 1.0).normalized().unwrap(); + let c = grid_centre(tf, back, n, 100.0); + assert!((c - Vec3::new(0.0, 10.0, 0.0)).len() < 1e-9, "{c:?}"); + // Grazing: the axis meets the ground 1 m ahead, the grid is 120 wide. + let back = Vec3::new(0.0, -1.0, 0.01).normalized().unwrap(); + let c = grid_centre(tf, back, n, 120.0); + assert!(c.z.abs() < 1e-9 && (c - Vec3::new(0.0, 0.0, 0.0)).len() <= 120.0 + 1e-9, "{c:?}"); + assert!(c.y > 0.0, "still toward where the view looks: {c:?}"); + // Edge-on: under the target. + let c = grid_centre(tf, Vec3::Y, n, 120.0); + assert!(c.len() < 1e-9, "{c:?}"); + } + + /// #3087: zoomed in on a target below the ground (an orbit left it there), seen at a slant, + /// the grid still covers the ground in the middle of the view: where the view's axis meets + /// it, some fifty millimetres from the point under the target, round which it was drawn. + #[test] + fn the_grid_covers_the_middle_of_the_view_when_the_target_is_off_the_ground() { + let rect = Rect::from_min_size(Pos2::ZERO, egui::vec2(1280.0, 720.0)); + let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + app.ui.show_grid = true; + app.ui.perspective = false; + // The camera of the report. + app.cam.target = Vec3::new(-38.888, -34.247, -28.617); + app.cam.yaw = -2.288; + app.cam.pitch = 0.504; + app.cam.distance = 25.563; + let back = app.cam.back(); + let mid = app.cam.target - back * (app.cam.target.z / back.z); + assert!(mid.z.abs() < 1e-9 && (mid - app.cam.target).len() > 40.0, "{mid:?}"); + let under = build_sketch_scene(&app, &projection(&app, rect)).under; + let points: Vec<[f32; 3]> = under + .as_chunks::<32>() + .0 + .iter() + .flat_map(|l| [&l[0..12], &l[12..24]]) + .map(|b| [0, 4, 8].map(|i| f32::from_le_bytes(b[i..i + 4].try_into().unwrap()))) + .collect(); + let (lo, hi) = points + .iter() + .fold(([f32::MAX; 2], [f32::MIN; 2]), |(lo, hi), p| ([lo[0].min(p[0]), lo[1].min(p[1])], [hi[0].max(p[0]), hi[1].max(p[1])])); + let (x, y) = (mid.x as f32, mid.y as f32); + assert!(x > lo[0] && x < hi[0] && y > lo[1] && y < hi[1], "the grid spans {lo:?}..{hi:?}, the middle of the view is at {mid:?}"); + } + /// An open sketch always has its grid, on its own plane, whatever the Grid switch and the /// follow-the-view preference say; outside a sketch the switch decides. #[test] From 59b6eea516f2403483f478cf646dabcf39079749 Mon Sep 17 00:00:00 2001 From: fkirill Date: Tue, 20 Oct 2026 03:31:55 +0000 Subject: [PATCH 171/225] Support tapered extrusions at line/arc corners (#2754) (#2788) * claim: #2752 * claim: #2754 * claim: #2751 * claim: #2752 * claim: #2754 * claim: #2751 From 1b6c10f6e0e9e61728fac652281683f246a0ec38 Mon Sep 17 00:00:00 2001 From: Igor Bronovskyi Date: Tue, 20 Oct 2026 03:36:01 +0000 Subject: [PATCH 172/225] Translate the Ukrainian catalog messages added after #1632 (#2569) --- assets/locales/uk.json | 96 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 96 insertions(+) diff --git a/assets/locales/uk.json b/assets/locales/uk.json index da63577d1..b7a102a5b 100644 --- a/assets/locales/uk.json +++ b/assets/locales/uk.json @@ -31,6 +31,7 @@ "Arc length": "Довжина дуги", "Area": "Площа", "Attachment": "Прив'язка", + "BOUNDARY SURFACE": "ПОВЕРХНЯ ЗА МЕЖАМИ", "BROWSER": "БРАУЗЕР", "Bend Line Position": "Положення лінії згину", "Bend Position": "Положення згину", @@ -73,6 +74,7 @@ "Counterbore depth": "Глибина циліндричного розширення", "Countersink angle": "Кут зенкування", "Create Issue — review draft": "Створити повідомлення про проблему — перегляд чернетки", + "Cross curves": "Поперечні криві", "Cube": "Куб", "Current orthographic view (1:1 mm)": "Поточний ортографічний вид (1:1 mm)", "Current perspective view": "Поточний перспективний вид", @@ -89,6 +91,7 @@ "Direction": "Напрямок", "Discard": "Відхилити", "Do not export hidden edges": "Не експортувати приховані ребра", + "Don't ask again": "Більше не питати", "Double-click to rename": "Двічі клацніть, щоб перейменувати", "Double-clicking the middle button in the view: Home (the home view, framing what is shown), Fit (frame what is shown, keeping the orientation) or nothing": "Подвійне клацання середньою кнопкою у виді: головний (головний вид, що охоплює показане), вписування (охопити показане, зберігаючи орієнтацію) або нічого", "Drive Joint": "Керувати з'єднанням", @@ -98,6 +101,7 @@ "Enable rule": "Увімкнути правило", "Enabled": "Увімкнено", "Explode": "Рознести", + "Explode Text": "Розібрати текст", "Export Animation…": "Експортувати анімацію…", "Export Current View as DXF": "Експортувати поточний вид як DXF", "Export Current View as DXF…": "Експортувати поточний вид як DXF…", @@ -159,6 +163,7 @@ "Move earlier": "Перемістити раніше", "Move later": "Перемістити пізніше", "Name": "Назва", + "Nearest": "Найближчі", "New study": "Нове дослідження", "No crash reports.": "Немає звітів про збої.", "No matching appearances": "Немає відповідних виглядів", @@ -188,6 +193,7 @@ "Position (0 to 1)": "Положення (від 0 до 1)", "Position (G0)": "Положення (G0)", "Position along the edge, 0 at the start end, 1 at the other": "Положення вздовж ребра: 0 на початку, 1 на іншому кінці", + "Preferences › Design turns the offer back on": "Налаштування › Дизайн повертає пропозицію", "Preview Row": "Рядок перегляду", "Preview leaves the current design unchanged.": "Попередній перегляд не змінює поточний проєкт.", "Profiles/Curves": "Профілі/криві", @@ -281,6 +287,7 @@ "This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "Ця грань не може забезпечити надійну прив'язку. Виберіть іншу грань або явно використайте фіксовану площину.", "To Offset": "До зсуву", "Tolerance": "Допуск", + "Too close": "Занадто близько", "Trimming tool (plane, face or curves)": "Інструмент обрізання (площина, грань або криві)", "Turn off section analysis before exporting the view.": "Вимкніть аналіз перерізу перед експортом виду.", "Type": "Тип", @@ -415,6 +422,7 @@ "cmd.file_slicers": "Встановлені слайсери", "cmd.inspect_accessibility": "Аналіз доступності", "cmd.inspect_center_of_mass": "Центр мас", + "cmd.inspect_clearance": "Зазор", "cmd.inspect_compare": "Порівняти тіла", "cmd.inspect_continuity": "Аналіз неперервності", "cmd.inspect_curvature_comb": "Аналіз гребеня кривизни", @@ -424,6 +432,7 @@ "cmd.inspect_interference": "Перевірка перетинів", "cmd.inspect_isocurve": "Аналіз ізокривих", "cmd.inspect_minimum_radius": "Аналіз мінімального радіуса", + "cmd.inspect_silhouette": "Силует", "cmd.inspect_zebra": "Зебра-аналіз", "cmd.joint_as_built": "З'єднання за поточним положенням", "cmd.joint_cam": "Кулачок", @@ -559,6 +568,8 @@ "cmd.sketch_isoparametric_curve": "Ізопараметрична крива", "cmd.sketch_line3d": "3D-пряма", "cmd.sketch_line_midpoint": "Пряма за середньою точкою", + "cmd.sketch_loose_ends": "Вільні кінці", + "cmd.sketch_loose_ends_tie": "Зв'язати вільні кінці", "cmd.sketch_move": "Перемістити/копіювати елементи ескізу", "cmd.sketch_move3d": "Перемістити 3D-точку", "cmd.sketch_move_point": "Перетягнути точку ескізу", @@ -603,8 +614,10 @@ "cmd.surface_blend": "Сполучна поверхня", "cmd.surface_boundary": "Поверхня за межами", "cmd.surface_extrude": "Видавлювання поверхні", + "cmd.surface_fair": "Згладжування поверхні", "cmd.surface_fillet": "Заокруглення поверхні", "cmd.surface_loft": "Лофт поверхні", + "cmd.surface_match": "Вирівнювання поверхні", "cmd.surface_offset": "Зсунута поверхня", "cmd.surface_patch": "Латка", "cmd.surface_reverse_normal": "Обернути нормаль", @@ -628,8 +641,10 @@ "cmd.timeline_roll_to": "Перемістити маркер історії", "cmd.timeline_rollback": "Перемістити маркер часового ланцюжка", "cmd.timeline_suppress": "Придушити операцію", + "cmd.view_ambient_occlusion": "Окружне затінення", "cmd.view_apply": "Відновити іменований вид", "cmd.view_delete": "Видалити іменований вид", + "cmd.view_graphics_preset": "Набір графіки", "cmd.view_list": "Список іменованих видів", "cmd.view_navigate": "Навігація видом", "cmd.view_rename": "Перейменувати іменований вид", @@ -651,7 +666,12 @@ "coupling.rack": "Рейка", "coupling.radius_1": "Радіус 1", "coupling.radius_2": "Радіус 2", + "dialog.bodies_count": "Тіл: {count}", + "dialog.clearance_invalid": "зазор має бути довжиною 0 або більше", + "dialog.compute": "Обчислити", + "dialog.compute_again": "Обчислити знову", "dialog.computing": "Обчислення… {seconds} с", + "dialog.could_not_be_checked": "не вдалося перевірити", "dialog.custom_axis": "↖ Власна вісь", "dialog.edit_title": "РЕДАГУВАННЯ {title}", "dialog.select": "↖ Вибрати", @@ -664,6 +684,18 @@ "drive.stopped_by_contact": "Зупинка на {value}: {a} пройшло б крізь {b}", "drive.stopped_by_loop": "Зупинка на {value}: контур через {joint} далі не замикається", "drive.unconnected": "Нічого не рухається: {part} не з'єднано ні з чим закріпленим", + "dxf.cancel_wait": "Очікування зупинки експорту…", + "dxf.cancelled": "Експорт DXF скасовано", + "dxf.cancelling": "Скасування експорту DXF", + "dxf.exporting": "Експортування DXF", + "dxf.invalid_tolerance": "Допуск кривої має бути від 0,0001 до 1 мм.", + "dxf.progress.index": "Підготовка поверхонь (2/5)", + "dxf.progress.meshes": "Підготовка сіток (1/5)", + "dxf.progress.occlusion": "Обчислення невидимих ліній (4/5)", + "dxf.progress.projection": "Проєктування геометрії (3/5)", + "dxf.progress.write": "Запис DXF (5/5)", + "dxf.tolerance": "Допуск кривої", + "dxf.tolerance_help": "Лише видимі тіла. Криві подаються відрізками. Менший допуск дає точніші криві, але потребує більше часу й пам'яті.", "expression, e.g. 25 mm": "вираз, напр. 25 mm", "fits the face, e.g. M8": "відповідає грані, напр. M8", "from the rule": "з правила", @@ -709,9 +741,11 @@ "new configuration": "нова конфігурація", "new name": "нова назва", "new parameter": "новий параметр", + "no hole": "без отвору", "no interference": "немає перетинів", "no joint that moves yet": "ще немає рухомого з'єднання", "no picture": "немає зображення", + "none": "немає", "pattern.alignment_2": "Вирівнювання 2", "pattern.alignment_hint": "Кількість включає оригінал. Центрування розподіляє копії з обох боків; за парної кількості зміна напрямку визначає бік із додатковою копією.", "pattern.direction_1": "Напрямок 1", @@ -784,6 +818,8 @@ "sketch.degrees_of_freedom": "{count} ступенів вільності", "sketch.draw_curves": "Малювати як {linetype}", "sketch.make_selection": "Перетворити виділене на {linetype}", + "sketch.open_ends": "Відкритих: {count}", + "sketch.untied_ends": "Незв'язаних: {count}", "sketch_text.align_center": "По центру", "sketch_text.align_left": "Ліворуч", "sketch_text.align_right": "Праворуч", @@ -796,13 +832,19 @@ "sketch_text.path_clear": "Зняти текст з його кривої", "sketch_text.path_hint": "Крива ескізу, якої дотримується текст: клацніть тут, а потім на кривій", "sketch_text.use_font_file": "Використати файл шрифту {path}", + "solid": "суцільне", "the parts library is not available": "бібліотека деталей недоступна", + "thread.automatic_size": "Автоматичний розмір", + "thread.designation": "Позначення", + "thread.iso_metric": "Метрична ISO", + "thread.select_size": "Вибрати розмір", "timeline.group": "Нова тека операцій", "timeline.move_many": "Перемістити елементи часового ланцюжка", "timeline.move_to_group": "Перемістити операції до теки", "timeline.rename_group": "Перейменувати теку операцій", "timeline.reorder_many": "Перевпорядкувати операції", "timeline.ungroup": "Прибрати теки операцій", + "to the face": "до грані", "to the next face": "до наступної грані", "toolbar.image": "ЗОБРАЖЕННЯ", "toolbar.render": "РЕНДЕР", @@ -818,12 +860,15 @@ "ui.activate": "Активувати", "ui.active_component": "Активний компонент", "ui.agent_chat": "Чат з агентом", + "ui.agent_chat_add": "Прикріпити файли", + "ui.agent_chat_add_file": "Вибрати файл…", "ui.agent_chat_allow": "Дозволити", "ui.agent_chat_allowed": "Дозволено", "ui.agent_chat_answered": "Відповідь: {option}", "ui.agent_chat_approval": "Дозволити агенту це зробити?", "ui.agent_chat_attach_view": "Прикріпити вид", "ui.agent_chat_attach_view_tip": "Надіслати знімок поточного виду разом із повідомленням", + "ui.agent_chat_attachable": "Зображення, текст і CAD-файли", "ui.agent_chat_auth_agent": "Увійти через {name}", "ui.agent_chat_auth_env": "Задайте {vars} у своєму середовищі та перезапустіть SolidCraft.", "ui.agent_chat_auth_needed": "Агент просить вас увійти. Ви входите через сам агент; SolidCraft ніколи не бачить вашого пароля чи ключів.", @@ -843,11 +888,32 @@ "ui.agent_chat_deny": "Відхилити", "ui.agent_chat_desktop_only": "Чат з агентом потребує настільної програми.", "ui.agent_chat_detecting": "Пошук агентів…", + "ui.agent_chat_dock": "Закріпити на бічній панелі", "ui.agent_chat_dock_left": "Закріпити ліворуч", "ui.agent_chat_dock_right": "Закріпити праворуч", + "ui.agent_chat_drop_hint": "Перетягніть, щоб прикріпити до наступного повідомлення", "ui.agent_chat_edit": "Редагувати", "ui.agent_chat_exited": "Агент зупинився.", "ui.agent_chat_failed_start": "Не вдалося запустити агента: {error}", + "ui.agent_chat_file_cad_not_read": "{name}: CAD-файл імпортується в проєкт, а не читається", + "ui.agent_chat_file_empty_picture": "{name}: порожнє зображення", + "ui.agent_chat_file_error": "{name}: {error}", + "ui.agent_chat_file_heic": "{name}: зображення HEIC тут не читаються; спершу експортуйте його як JPEG або PNG", + "ui.agent_chat_file_importing": "Імпортування в проєкт…", + "ui.agent_chat_file_loading": "Читання файлу…", + "ui.agent_chat_file_not_a_file": "{name}: не файл", + "ui.agent_chat_file_not_a_picture": "{name}: не зображення", + "ui.agent_chat_file_not_utf8": "{name}: не текст UTF-8", + "ui.agent_chat_file_picture_too_big": "{name}: зображення може бути щонайбільше {max} МБ", + "ui.agent_chat_file_text_too_big": "{name}: текстовий файл може бути щонайбільше {max} КБ", + "ui.agent_chat_file_too_large": "{name}: завеликий", + "ui.agent_chat_file_too_large_to_send": "{name}: завеликий для надсилання, навіть зменшеним", + "ui.agent_chat_file_unreadable_picture": "{name}: не зображення, яке це може прочитати", + "ui.agent_chat_files": "Файли: {files}", + "ui.agent_chat_files_left_out": "З одним повідомленням надсилається щонайбільше {max} файлів; пропущено: {files}", + "ui.agent_chat_files_loading": "Очікування читання файлів", + "ui.agent_chat_files_max": "Щонайбільше {max} файлів на одне повідомлення", + "ui.agent_chat_import_failed": "{name}: не вдалося імпортувати: {error}", "ui.agent_chat_intro": "Спілкуйтеся з агентом для програмування, яким уже користуєтеся, або з обраною вами модельною кінцевою точкою. Він працює з відкритим проєктом через інструменти SolidCraft: його зміни з'являються в міру виконання й скасовуються одним кроком на повідомлення. Що він може робити без запиту, задано в Налаштування > ШІ.", "ui.agent_chat_key_in_env": "ключ задано", "ui.agent_chat_left": "Ліворуч", @@ -860,14 +926,18 @@ "ui.agent_chat_no_cli": "solidcraft-cli не знайдено поруч із програмою, тож агент не може дістатися до проєкту.", "ui.agent_chat_no_control": "Кінцева точка чату з агентом не запустилася, тож агент не може дістатися до проєкту.", "ui.agent_chat_no_images": "Цей агент не приймає зображень", + "ui.agent_chat_no_picture": "У буфері обміну немає зображення", "ui.agent_chat_none_found": "Агента для програмування не знайдено. Установіть один із цих, а потім натисніть «Оновити»:", "ui.agent_chat_none_found_short": "Агента не знайдено", "ui.agent_chat_not_installed": "Не встановлено", "ui.agent_chat_not_signed_in": "не виконано вхід", + "ui.agent_chat_own_window": "Власне вікно", + "ui.agent_chat_paste_picture": "Вставити зображення", "ui.agent_chat_permission": "Агент просить виконати: {title}", "ui.agent_chat_pick": "Агент", "ui.agent_chat_placeholder": "Попросіть агента змінити проєкт…", "ui.agent_chat_placeholder_busy": "Поставте повідомлення в чергу, доки агент завершить (Ctrl+Enter: надіслати зараз)", + "ui.agent_chat_pop_out": "Відкрити у власному вікні, яке можна перемістити на інший екран", "ui.agent_chat_privacy": "Нічого нікуди не надсилається, крім агента, який ви запускаєте, під вашим власним обліковим записом.", "ui.agent_chat_privacy_note": "SolidCraft нічого нікуди не надсилає: агент, який ви запускаєте, спілкується з власним сервісом під вашим обліковим записом. SolidCraft ніколи не бачить і не зберігає ключ чи пароль.", "ui.agent_chat_queue": "У чергу", @@ -877,6 +947,8 @@ "ui.agent_chat_refresh": "Оновити", "ui.agent_chat_refused": "Не дозволено для агента: {reason}", "ui.agent_chat_remove": "Прибрати з черги", + "ui.agent_chat_remove_file": "Прибрати з цього повідомлення", + "ui.agent_chat_remove_imported": "Прибрати з цього повідомлення; деталь залишається в проєкті (скасування її прибирає)", "ui.agent_chat_right": "Праворуч", "ui.agent_chat_save": "Зберегти", "ui.agent_chat_send": "Надіслати", @@ -974,6 +1046,8 @@ "ui.ai_toolbar_button_note": "Кнопка ШІ в правому кінці панелі інструментів. Ctrl+Shift+A і меню «Вид» усе одно відкривають панель.", "ui.ai_undo_tip": "Скасувати все, що агент змінив для цього повідомлення, одним кроком", "ui.all": "Усі", + "ui.ambient_occlusion": "Окружне затінення", + "ui.ambient_occlusion_help": "М'яке затінення в місцях, де стикаються непрозорі поверхні. Потребує вікна перегляду на GPU.", "ui.analysis": "Аналіз", "ui.angle": "Кут", "ui.angle_decimals": "Знаки після коми для кутів", @@ -992,6 +1066,7 @@ "ui.base_point": "Базова точка", "ui.blocked": "Заблоковані", "ui.bodies": "Тіла", + "ui.bodies_all_if_none": "Тіла (усі, якщо не вибрано)", "ui.box": "Куб", "ui.break": "Розірвати", "ui.calibrate": "Калібрувати", @@ -1043,6 +1118,9 @@ "ui.construct": "Побудувати", "ui.construction": "Конструкційна", "ui.context_menu": "Контекстне меню", + "ui.continuity_g0": "G0 злам", + "ui.continuity_g1": "G1 дотичність", + "ui.continuity_g2": "G2 кривина", "ui.continuity_gap": "Проміжок", "ui.copy": "Копіювати", "ui.corner": "Кут", @@ -1131,6 +1209,13 @@ "ui.fully_constrained": "Повністю визначений", "ui.general": "Загальні", "ui.graphics": "Графіка", + "ui.graphics_custom": "Власний", + "ui.graphics_performance": "Продуктивність", + "ui.graphics_preset": "Набір графіки", + "ui.graphics_preset_help": "Якість: окружне затінення, висока якість відображення та адаптивна наддискретизація 2×. Продуктивність: без окружного затінення, звичайна якість відображення та вимкнена наддискретизація. Ручні зміни показують «Власний». MSAA не змінюється.", + "ui.graphics_quality": "Якість", + "ui.grid_follows_view": "Сітка слідує за видом", + "ui.grid_follows_view_hint": "Бічні види показують сітку на вертикальній площині, повернутій до них, а не на землі", "ui.ground_shadow": "Тінь на землі", "ui.groupSelected": "Згрупувати виділене", "ui.heading_add_ins": "НАДБУДОВИ", @@ -1157,6 +1242,7 @@ "ui.heading_home": "ГОЛОВНА", "ui.heading_insert": "ВСТАВИТИ", "ui.heading_inspect": "ПЕРЕВІРКА", + "ui.heading_interference": "ПЕРЕТИНИ", "ui.heading_loft": "ЛОФТ", "ui.heading_make": "ВИГОТОВЛЕННЯ", "ui.heading_measure": "ВИМІРЮВАННЯ", @@ -1281,6 +1367,7 @@ "ui.one_side": "Один бік", "ui.open": "Відкрити", "ui.open_ellipsis": "Відкрити...", + "ui.open_ends_tip": "Нічого не торкається", "ui.open_preferences": "Відкрити налаштування", "ui.open_recent": "Відкрити недавні", "ui.operation": "Операція", @@ -1325,6 +1412,8 @@ "ui.radial_context_menu": "Кругове контекстне меню", "ui.radius": "Радіус", "ui.radius_type": "Тип радіуса", + "ui.rail": "Напрямна", + "ui.rail_fit": "Підгонка за напрямною", "ui.reachable": "Досяжні", "ui.rectangle": "Прямокутник", "ui.rectangular_pattern": "Прямокутний масив", @@ -1340,6 +1429,8 @@ "ui.reset_the_settings_on_this_page": "Скинути налаштування на цій сторінці", "ui.restore": "Відновити", "ui.restore_defaults": "Відновити типові", + "ui.reverse_horizontal_pan_direction": "Обернути напрямок горизонтального панорамування", + "ui.reverse_horizontal_pan_tip": "Горизонтальна прокрутка двома пальцями та бічне колесо панорамують у зворотний бік", "ui.reverse_zoom_direction": "Змінити напрямок масштабування", "ui.revolve": "Обертання", "ui.right": "Справа", @@ -1353,6 +1444,7 @@ "ui.sbox_pin": "Закріпити вгорі поля S", "ui.sbox_unpin": "Відкріпити", "ui.scale": "Масштаб", + "ui.second_rail": "Друга напрямна", "ui.section_analysis": "Аналіз перерізу", "ui.select": "Вибрати", "ui.selectOther": "Вибрати інше…", @@ -1431,6 +1523,7 @@ "ui.start": "Початок", "ui.start_over": "Почати спочатку", "ui.start_radius": "Початковий радіус", + "ui.stretch": "Розтягнути", "ui.supersampling": "Наддискретизація (SSAA)", "ui.supersampling_adaptive": "Лише коли вид нерухомий", "ui.supersampling_off": "Вимкнено (1×)", @@ -1449,6 +1542,8 @@ "ui.theme": "Тема", "ui.thickness": "Товщина", "ui.thread": "Різьба", + "ui.tie_ends": "Зв'язати", + "ui.tie_ends_tip": "Обмежити всі незв'язані кінці", "ui.timeline_bottom": "Часовий ланцюжок знизу", "ui.timeline_left_note": "Ліве компонування показує смугу відкату над браузером деталей і сцени.", "ui.timeline_left_sidebar": "Ліва бічна панель", @@ -1471,6 +1566,7 @@ "ui.units_of_new_designs": "Одиниці нових проєктів", "ui.unlock": "Розблокувати", "ui.unsuppress": "Скасувати придушення", + "ui.untied_ends_tip": "Торкається лише за положенням", "ui.untitled": "Без назви", "ui.up_axis_note": "Яка вісь спрямована вгору у видах (вид осі, головний, наведення). Проєкти не змінюються.", "ui.updateToCurrentView": "Оновити до поточного виду", From de7fabc3bc64fc119dfb9c30c9c066a7f2f08f03 Mon Sep 17 00:00:00 2001 From: Thodoris Tsagkogeorgas Date: Tue, 20 Oct 2026 03:38:47 +0000 Subject: [PATCH 173/225] Preferences: a Plugins page lists installed plugin folders (#2718) * Preferences: a Plugins page lists installed plugin folders Each folder under the per-user plugins directory that has a plugin.json appears in Preferences. Turning one off is saved with the other settings. The page reads the manifest and does not run any code from the folder. * Retrigger checks after the cancelled run The required ci check failed because the workflow was cancelled before any job started. This commit does not change the plugins page. --- assets/locales/en.json | 6 + assets/locales/ja.json | 6 + assets/locales/zh.json | 6 + crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/plugins.rs | 256 ++++++++++++++++++++++++++++++++++ crates/ui-egui/src/prefs.rs | 31 +++- 6 files changed, 302 insertions(+), 4 deletions(-) create mode 100644 crates/ui-egui/src/plugins.rs diff --git a/assets/locales/en.json b/assets/locales/en.json index 7557c6b44..54d6af143 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -1410,6 +1410,12 @@ "ui.placement": "Placement", "ui.plane": "Plane", "ui.plane_at_angle": "Plane at Angle", + "ui.plugins": "Plugins", + "ui.plugins_desktop": "Plugins are available in the desktop app.", + "ui.plugins_empty": "No plugins installed.", + "ui.plugins_note": "Each plugin is a folder inside {path} with a plugin.json. SolidCraft reads that file and does not run any code from the folder. Turning a plugin off keeps it installed.", + "ui.plugins_skipped": "{count} folder(s) could not be read.", + "ui.plugins_version": "{version}", "ui.point": "Point", "ui.point_under_the_cursor": "Point under the cursor", "ui.points": "Points", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index ba6fbfe04..d2413d628 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -1410,6 +1410,12 @@ "ui.placement": "配置", "ui.plane": "平面", "ui.plane_at_angle": "傾斜平面", + "ui.plugins": "プラグイン", + "ui.plugins_desktop": "プラグインはデスクトップ版で使えます。", + "ui.plugins_empty": "プラグインは入っていません。", + "ui.plugins_note": "プラグインは {path} の中のフォルダで、plugin.json を置きます。SolidCraft はそのファイルを読むだけで、フォルダのコードは実行しません。オフにしてもインストールは残ります。", + "ui.plugins_skipped": "{count} 個のフォルダを読めませんでした。", + "ui.plugins_version": "{version}", "ui.point": "点", "ui.point_under_the_cursor": "カーソル下の点", "ui.points": "点", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index 8bfb7be4e..822647cbc 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -1410,6 +1410,12 @@ "ui.placement": "放置", "ui.plane": "平面", "ui.plane_at_angle": "角度平面", + "ui.plugins": "插件", + "ui.plugins_desktop": "插件仅在桌面版中可用。", + "ui.plugins_empty": "尚未安装插件。", + "ui.plugins_note": "每个插件是 {path} 里的一个文件夹,其中有 plugin.json。SolidCraft 只读取该文件,不运行文件夹里的代码。关闭插件仍会保留安装。", + "ui.plugins_skipped": "有 {count} 个文件夹无法读取。", + "ui.plugins_version": "{version}", "ui.point": "点", "ui.point_under_the_cursor": "光标下的点", "ui.points": "点", diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 595a674c7..90c09fe69 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -130,6 +130,7 @@ pub mod palette; pub mod params_dialog; pub(crate) mod pick_buffer; pub(crate) mod pick_index; +pub(crate) mod plugins; pub mod prefs; #[cfg(test)] mod preselect_tests; diff --git a/crates/ui-egui/src/plugins.rs b/crates/ui-egui/src/plugins.rs new file mode 100644 index 000000000..7a42066f5 --- /dev/null +++ b/crates/ui-egui/src/plugins.rs @@ -0,0 +1,256 @@ +//! Preferences › Plugins: packages installed under the per-user data folder. +//! +//! A plugin is a directory of `{data}/plugins//plugin.json`. This page reads that file and +//! records which ids are turned off. It does not load or run anything from the folder. Running a +//! plugin (the wasm host in docs/plugins.md) is a later step; it will honour `disabled_plugins`. + +use std::path::{Path, PathBuf}; + +use egui::RichText; +use serde::Deserialize; + +use crate::SolveApp; + +/// How many turned-off ids a preferences file may name. +pub const MAX_DISABLED: usize = 256; +/// `plugin.json` larger than this is refused. +const MAX_MANIFEST_BYTES: u64 = 16 * 1024; + +/// One installed plugin, as its manifest describes it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Plugin { + pub id: String, + pub name: String, + pub version: String, + pub description: String, +} + +/// A folder under the plugins directory that is not a plugin. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Skipped { + pub folder: String, + pub reason: String, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Manifest { + id: String, + name: String, + version: String, + #[serde(default)] + description: String, +} + +/// The plugins directory: `$XDG_DATA_HOME/solidcraft/plugins` (and the platform equivalents of +/// [`solidcraft_engine::recovery::data_dir`]). `None` when that folder cannot be named. +pub fn plugins_dir() -> Option { + solidcraft_engine::recovery::data_dir().map(|d| d.join("plugins")) +} + +/// An id a folder and a manifest may share: 1–64 characters, lowercase letters, digits and +/// hyphens, not starting or ending with a hyphen. +pub fn valid_id(id: &str) -> bool { + let b = id.as_bytes(); + (1..=64).contains(&b.len()) + && b.iter().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || *c == b'-') + && b[0] != b'-' + && *b.last().unwrap_or(&b'-') != b'-' +} + +fn plain(text: &str, max: usize) -> bool { + !text.is_empty() && text.chars().count() <= max && text.chars().all(|c| !c.is_control()) +} + +fn check(m: Manifest, folder: &str) -> Result { + if m.id != folder { + return Err(format!("plugin.json id `{}` does not match the folder `{folder}`", m.id)); + } + if !valid_id(&m.id) { + return Err("the id must be 1–64 lowercase letters, digits and hyphens".into()); + } + let name = m.name.trim(); + if !plain(name, 80) { + return Err("the name must be 1–80 characters with no line breaks".into()); + } + let version = m.version.trim(); + if !plain(version, 32) || !version.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '+')) { + return Err("the version must be 1–32 letters, digits, dots, hyphens or plus signs".into()); + } + let description = m.description.trim(); + if description.chars().count() > 240 || description.chars().any(|c| c.is_control()) { + return Err("the description must be at most 240 characters with no line breaks".into()); + } + Ok(Plugin { id: m.id, name: name.to_string(), version: version.to_string(), description: description.to_string() }) +} + +fn read_plugin(dir: &Path, folder: &str) -> Result { + let path = dir.join("plugin.json"); + let meta = std::fs::metadata(&path).map_err(|_| "no plugin.json".to_string())?; + if !meta.is_file() || meta.len() > MAX_MANIFEST_BYTES { + return Err("plugin.json is missing or larger than 16 KiB".into()); + } + let text = std::fs::read_to_string(&path).map_err(|e| format!("plugin.json could not be read ({e})"))?; + let manifest: Manifest = serde_json::from_str(&text).map_err(|e| format!("plugin.json is not a plugin manifest ({e})"))?; + check(manifest, folder) +} + +/// The plugins in `dir`, and the folders that were not. A missing directory is an empty list. +pub fn scan(dir: &Path) -> (Vec, Vec) { + let mut plugins = Vec::new(); + let mut skipped = Vec::new(); + let Ok(entries) = std::fs::read_dir(dir) else { + return (plugins, skipped); + }; + for entry in entries.flatten() { + let Ok(kind) = entry.file_type() else { continue }; + if !kind.is_dir() { + continue; + } + let Some(folder) = entry.file_name().into_string().ok() else { + skipped.push(Skipped { folder: String::new(), reason: "the folder name is not text".into() }); + continue; + }; + if folder.starts_with('.') { + continue; + } + match read_plugin(&entry.path(), &folder) { + Ok(plugin) => plugins.push(plugin), + Err(reason) => skipped.push(Skipped { folder, reason }), + } + } + plugins.sort_by(|a, b| a.name.cmp(&b.name).then(a.id.cmp(&b.id))); + skipped.sort_by(|a, b| a.folder.cmp(&b.folder)); + (plugins, skipped) +} + +/// Whether an installed plugin is offered. Unknown ids are on; an id in `disabled_plugins` is off. +pub fn enabled(app: &SolveApp, id: &str) -> bool { + !app.preferences.disabled_plugins.contains(id) +} + +/// The Plugins page. Desktop only: the browser build has no per-user plugin folder. +pub fn page(app: &mut SolveApp, ui: &mut egui::Ui) { + let t = crate::theme::Tokens::get(); + if cfg!(target_arch = "wasm32") { + ui.label(crate::i18n::tr("ui.plugins_desktop")); + return; + } + let Some(dir) = plugins_dir() else { + ui.label(crate::i18n::tr("ui.plugins_desktop")); + return; + }; + let path = dir.display().to_string(); + ui.add(egui::Label::new(RichText::new(crate::i18n::format("ui.plugins_note", &[("path", &path)])).size(11.0).color(t.text_dim)).wrap()); + ui.add_space(8.0); + if ui.button(crate::i18n::tr_label("Show in folder")).clicked() { + // `show_in_folder` opens the parent of the path it is given, so the argument is a name + // inside the plugins directory (it need not exist). + if let Err(e) = std::fs::create_dir_all(&dir) { + app.set_status(format!("Could not create the plugins folder: {e}"), true); + } else if let Some(show) = &app.services.show_in_folder { + show(&dir.join("plugin.json").display().to_string()); + } + } + ui.add_space(8.0); + let (plugins, skipped) = scan(&dir); + if plugins.is_empty() { + ui.label(crate::i18n::tr("ui.plugins_empty")); + } + for plugin in &plugins { + let mut on = enabled(app, &plugin.id); + ui.horizontal(|ui| { + let check = ui.checkbox(&mut on, ""); + crate::scenario::publish_handle(&format!("prefs:plugin:{}", plugin.id), check.rect.center()); + if check.changed() { + if on { + app.preferences.disabled_plugins.remove(&plugin.id); + } else if app.preferences.disabled_plugins.len() < MAX_DISABLED { + app.preferences.disabled_plugins.insert(plugin.id.clone()); + } + } + ui.vertical(|ui| { + ui.label(RichText::new(&plugin.name).strong()); + ui.label(RichText::new(crate::i18n::format("ui.plugins_version", &[("version", &plugin.version)])).size(11.0).color(t.text_dim)); + if !plugin.description.is_empty() { + ui.label(RichText::new(&plugin.description).size(11.0).color(t.text_dim)); + } + }); + }); + ui.separator(); + } + if !skipped.is_empty() { + ui.add_space(6.0); + ui.label(RichText::new(crate::i18n::format("ui.plugins_skipped", &[("count", &skipped.len().to_string())])).size(11.0).color(t.text_dim)); + for skip in skipped.iter().take(8) { + let who = if skip.folder.is_empty() { "folder" } else { skip.folder.as_str() }; + ui.label(RichText::new(format!("{who}: {}", skip.reason)).size(11.0).color(t.text_dim)); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn write(dir: &Path, folder: &str, body: &str) { + let d = dir.join(folder); + std::fs::create_dir_all(&d).unwrap(); + std::fs::write(d.join("plugin.json"), body).unwrap(); + } + + #[test] + fn a_folder_with_plugin_json_is_listed_and_a_bad_one_is_skipped() { + let dir = std::env::temp_dir().join(format!("solidcraft-plugins-scan-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + write( + &dir, + "ftc-frc-parts", + r#"{"id":"ftc-frc-parts","name":"FTC and FRC parts","version":"0.1.0","description":"Commercial robot parts."}"#, + ); + write(&dir, "broken", r#"{"id":"other","name":"Nope","version":"1"}"#); + std::fs::create_dir_all(dir.join("notes")).unwrap(); + let (plugins, skipped) = scan(&dir); + assert_eq!(plugins.len(), 1); + assert_eq!(plugins[0].id, "ftc-frc-parts"); + assert_eq!(plugins[0].name, "FTC and FRC parts"); + assert!(skipped.iter().any(|s| s.folder == "broken" && s.reason.contains("does not match"))); + assert!(skipped.iter().any(|s| s.folder == "notes" && s.reason.contains("no plugin.json"))); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn ids_and_manifests_refuse_what_would_not_fit_on_the_page() { + assert!(valid_id("a")); + assert!(valid_id("ftc-frc-parts")); + assert!(!valid_id("")); + assert!(!valid_id("-a")); + assert!(!valid_id("a-")); + assert!(!valid_id("FTC")); + assert!(!valid_id(&"a".repeat(65))); + let bad = Manifest { id: "gear".into(), name: "Gear\nbox".into(), version: "1".into(), description: String::new() }; + assert!(check(bad, "gear").is_err()); + let big = Manifest { id: "gear".into(), name: "Gear".into(), version: "1".into(), description: "x".repeat(241) }; + assert!(check(big, "gear").unwrap_err().contains("240")); + } + + #[test] + fn turning_a_plugin_off_is_saved_and_restore_defaults_turns_it_back_on() { + use serde_json::json; + let mut app = crate::SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + assert!(enabled(&app, "ftc-frc-parts")); + crate::prefs::set(&mut app, &json!({"disabled_plugins": ["ftc-frc-parts"]})).unwrap(); + assert!(!enabled(&app, "ftc-frc-parts")); + let err = crate::prefs::set(&mut app, &json!({"disabled_plugins": ["Bad Id"]})).unwrap_err(); + assert!(err.contains("disabled_plugins"), "{err}"); + assert!(!enabled(&app, "ftc-frc-parts"), "a refused list leaves the previous choice"); + let mut other = crate::SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + other.load_prefs(&app.prefs()); + assert!(!enabled(&other, "ftc-frc-parts")); + crate::prefs::control(&mut app, &json!({"open": "Plugins", "button": "defaults"})).unwrap(); + assert_eq!(app.prefs_window.section, crate::prefs::PAGE_PLUGINS); + assert!(enabled(&app, "ftc-frc-parts")); + assert!(crate::prefs::control(&mut app, &json!({"open": "NoSuch"})).is_err()); + } +} diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index 661fd5ebd..af70af216 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -208,8 +208,9 @@ pub fn nav_preset(id: &str) -> &'static NavPreset { NAV_PRESETS.iter().find(|p| p.id == id).unwrap_or(&NAV_PRESETS[0]) } /// The dialog's pages, in order. -pub const PAGES: [&str; 8] = ["General", "Navigation", "Keyboard Shortcuts", "Design", "Graphics", "Sketch", "Selection", "AI"]; +pub const PAGES: [&str; 9] = ["General", "Navigation", "Keyboard Shortcuts", "Design", "Graphics", "Sketch", "Selection", "AI", "Plugins"]; pub const PAGE_AI: usize = 7; +pub const PAGE_PLUGINS: usize = 8; pub const PAGE_SHORTCUTS: usize = 2; pub const PAGE_DESIGN: usize = 3; pub const PAGE_GRAPHICS: usize = 4; @@ -406,6 +407,8 @@ pub struct Prefs { /// When true: Shift+click adds without removing; Primary toggles. /// When false (default): Shift and Primary both toggle. pub selection_shift_add_only: bool, + /// Plugin ids turned off (Preferences › Plugins). An installed plugin whose id is absent is on. + pub disabled_plugins: std::collections::BTreeSet, } /// What a middle-button double-click in the view does. @@ -506,6 +509,7 @@ impl Default for Prefs { suppress_sketch_snap: ModifierCombo::CTRL_ALT, manipulator_free_alt: true, selection_shift_add_only: false, + disabled_plugins: std::collections::BTreeSet::new(), } } } @@ -740,6 +744,7 @@ fn defaults(app: &mut SolveApp, page: usize) { app.autosave_minutes = 5.0; set_autosave(app); } + PAGE_PLUGINS => p.disabled_plugins.clear(), PAGE_AI => { // The agents the user added and their "always allow" answers stay. p.ai_features = d.ai_features; @@ -1221,6 +1226,10 @@ fn page(app: &mut SolveApp, ui: &mut egui::Ui, t: &Tokens) { crate::agent_chat::settings::page(app, ui); return; } + if app.prefs_window.section == PAGE_PLUGINS { + crate::plugins::page(app, ui); + return; + } egui::Grid::new(("sc_prefs_grid", app.prefs_window.section)).num_columns(2).spacing([16.0, 8.0]).show(ui, |ui| match app.prefs_window.section { 0 => { ui.label(app.tr("ui.language")); @@ -1842,12 +1851,23 @@ pub fn migrate(mut p: Prefs) -> Prefs { p } +/// Drop plugin ids this page would not show, and keep at most [`crate::plugins::MAX_DISABLED`], +/// so a hand-edited preferences file cannot carry a huge or nonsense list. `set` still refuses +/// those instead of dropping them. +fn limit_disabled_plugins(mut p: Prefs) -> Prefs { + p.disabled_plugins.retain(|id| crate::plugins::valid_id(id)); + if p.disabled_plugins.len() > crate::plugins::MAX_DISABLED { + p.disabled_plugins = p.disabled_plugins.into_iter().take(crate::plugins::MAX_DISABLED).collect(); + } + p +} + /// Saved preferences, keeping every one that still reads. A value this version doesn't /// understand (a setting a newer or older release saved differently, a hand edit) falls back to /// its default on its own instead of discarding all of them. pub fn lenient(saved: &serde_json::Value) -> Prefs { if let Ok(p) = serde_json::from_value::(saved.clone()) { - return migrate(p); + return limit_disabled_plugins(migrate(p)); } let Ok(mut cur) = serde_json::to_value(Prefs::default()) else { return Prefs::default() }; if let (Some(o), Some(src)) = (cur.as_object_mut(), saved.as_object()) { @@ -1861,7 +1881,7 @@ pub fn lenient(saved: &serde_json::Value) -> Prefs { } } } - serde_json::from_value(cur).map(migrate).unwrap_or_default() + serde_json::from_value(cur).map(migrate).map(limit_disabled_plugins).unwrap_or_default() } /// Set preferences from JSON (control channel); returns them all. @@ -1904,6 +1924,9 @@ pub fn set(app: &mut SolveApp, p: &serde_json::Value) -> Result crate::plugins::MAX_DISABLED || new.disabled_plugins.iter().any(|id| !crate::plugins::valid_id(id)) { + return Err(format!("`disabled_plugins` must be at most {} ids of lowercase letters, digits and hyphens", crate::plugins::MAX_DISABLED)); + } if !(0.5..=2.5).contains(&new.ui_scale) || !(0.25..=4.0).contains(&new.look_at_speed) { return Err("`ui_scale` must be 0.5…2.5 and `look_at_speed` 0.25…4".into()); } @@ -2478,7 +2501,7 @@ mod tests { let mut out = ctx.run_ui(Default::default(), |ui| show(&mut app, ui.ctx())); out.textures_delta.clear(); assert!(app.prefs_window.open && app.prefs_window.section == PAGE_SHORTCUTS && !app.keymap.open); - assert!(control(&mut app, &json!({"open": "Plugins"})).is_err()); + assert!(control(&mut app, &json!({"open": "NoSuch"})).is_err()); assert!(set(&mut app, &json!({"up_axis": "x"})).is_err()); assert!(set(&mut app, &json!({"theme": "sepia"})).is_err()); assert!(set(&mut app, &json!({"language": "xx"})).is_err()); From e27d43553c53b00ef16a0d20338d3266576539fb Mon Sep 17 00:00:00 2001 From: leValdemar19 Date: Tue, 20 Oct 2026 03:44:16 +0000 Subject: [PATCH 174/225] Sketch Dimension: line to circle/arc edge (#1803) (#1863) A line and a circle or arc can now be dimensioned to the circle's edge (ConstraintKind::LineCircleDistance, saved as line_circle_distance): the gap while the line misses the circle (0 is tangency), or how far the edge reaches past the line when it cuts through (stored as `inside`). Rebased onto main as one commit (the branch's own changes; its merges of main dropped). Conflicts resolved: the test mod lines in cmd/sketch.rs (both kept, sorted), and README.md, whose feature list main moved to docs/capabilities.md; the line-to-circle dimension is listed there now. Claude-Session: https://claude.ai/code/session_01QWhMwdqJYQKQq8RCLSL1LT Co-authored-by: jyviko Co-authored-by: Claude Opus 5.5 --- ROADMAP.md | 3 + .../format/pending/line-circle-distance.rs | 5 + crates/engine/src/cmd/sketch.rs | 16 ++- crates/engine/src/cmd/sketch_constraints.rs | 1 + .../src/cmd/sketch_line_circle_tests.rs | 115 +++++++++++++++ crates/sketch/src/dims.rs | 12 ++ crates/sketch/src/lib.rs | 2 + crates/sketch/src/line_circle_tests.rs | 136 ++++++++++++++++++ crates/sketch/src/loci.rs | 8 ++ crates/sketch/src/model.rs | 26 +++- crates/sketch/src/solver.rs | 20 ++- .../sketch_dimension_line_to_circle_edge.json | 19 +++ docs/book/src/guide/sketching.md | 10 +- docs/capabilities.md | 2 +- skills/solidcraft-modeling/reference.md | 3 + 15 files changed, 373 insertions(+), 5 deletions(-) create mode 100644 crates/doc/src/format/pending/line-circle-distance.rs create mode 100644 crates/engine/src/cmd/sketch_line_circle_tests.rs create mode 100644 crates/sketch/src/line_circle_tests.rs create mode 100644 crates/ui-egui/tests/scenarios/sketch_dimension_line_to_circle_edge.json diff --git a/ROADMAP.md b/ROADMAP.md index 2c06fcd4f..ab228a469 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -229,6 +229,9 @@ completed drawings publish atomically. The browser still exports synchronously. Type a value and press Enter to commit one undo step; rejected values remain editable and cancellation leaves the sketch unchanged. Fit keeps geometry clear of the Sketch Palette and navigation controls, including enlarged displays and nested pending placements. +- Sketch Dimension takes a line and a circle or arc (#1803): it measures from the line to the + circle's edge (the gap, 0 when tangent, or how far the edge reaches past a line that cuts + it), drives it like any other dimension and keeps the circle on its side of the line. - Sketch annotations, live drawing lengths and Measure use document units. Inches show three decimals and retain a meaningful fourth digit. Bare length dimension entry captures the current design unit; changing units leaves existing geometry and expressions intact. diff --git a/crates/doc/src/format/pending/line-circle-distance.rs b/crates/doc/src/format/pending/line-circle-distance.rs new file mode 100644 index 000000000..8a0599271 --- /dev/null +++ b/crates/doc/src/format/pending/line-circle-distance.rs @@ -0,0 +1,5 @@ +//! A sketch can hold a `line_circle_distance` dimension (#1803): the distance from a line `l` to +//! the edge of a circle or arc `c`, saved with its `value` and, when the line cuts the circle, +//! `inside` (the value is then how far the edge reaches past the line). Older designs need no +//! transformation: they have no such dimension; 0.16.x (which reads up to 27) asks for an update +//! instead of meeting a constraint type it doesn't know. diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rs index 38b96a4f7..c50b0f2d5 100644 --- a/crates/engine/src/cmd/sketch.rs +++ b/crates/engine/src/cmd/sketch.rs @@ -111,7 +111,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .params(concat!("p0, p1: overall ends, width", connect_doc!(), created_doc!())), CommandSpec::new("sketch.point", "Point", draw_point).at("SKETCH", "CREATE").icon("point").enabled(in_sketch).params(concat!("point: [x,y] (each a number or an expression over the design's parameters: the point is then fixed where it comes to and follows them), id?", connect_doc!(), created_doc!())), CommandSpec::new("sketch.dimension", "Sketch Dimension", dimension).at("SKETCH", "CREATE").icon("dimension").key("D").enabled(in_sketch).params( - "entities: [refs], type?: auto|distance|horizontal|vertical|length|radius|diameter|angle, value?: number or expression (default: current; a bare number is in the design's units, e.g. 2 means 2 in in an inch design; give a unit such as \"50 mm\" to override); text_at?: [x, y]. Two points or a line off the axes: with auto, text_at across from them is the distance between them, above or below them horizontal, beside them vertical. Two lines: the angle between them (acute, or 180° − it when the value is nearer that) unless text_at picks a sector. A dimension the sketch already determines is refused (naming what determines it); if_redundant?: \"driven\" places it as a driven (reference) dimension instead. scale_sketch?: bool (the dimension tool sends true): when this is the sketch's first length dimension and nothing in the sketch fixes a size (no other driving length dimension, nothing fixed or projected), the whole sketch scales about its origin to the value instead of distorting. Returns measured in unit (mm or deg), and scaled: the factor when the sketch was scaled", + "entities: [refs], type?: auto|distance|horizontal|vertical|length|radius|diameter|angle, value?: number or expression (default: current; a bare number is in the design's units, e.g. 2 means 2 in in an inch design; give a unit such as \"50 mm\" to override); text_at?: [x, y]. Two points or a line off the axes: with auto, text_at across from them is the distance between them, above or below them horizontal, beside them vertical. Two lines: the angle between them (acute, or 180° − it when the value is nearer that) unless text_at picks a sector. A line and a circle or arc: the distance from the line to its edge (the gap, or how far the edge reaches past a line that cuts it; 0 is tangent); dimension the centre point for the distance to the centre. A dimension the sketch already determines is refused (naming what determines it); if_redundant?: \"driven\" places it as a driven (reference) dimension instead. scale_sketch?: bool (the dimension tool sends true): when this is the sketch's first length dimension and nothing in the sketch fixes a size (no other driving length dimension, nothing fixed or projected), the whole sketch scales about its origin to the value instead of distorting. Returns measured in unit (mm or deg), and scaled: the factor when the sketch was scaled", ), CommandSpec::new("sketch.constraint.horizontal_vertical", "Horizontal/Vertical", c_horizontal_vertical) .at("SKETCH", "CONSTRAINTS") @@ -1976,6 +1976,7 @@ fn dimension(s: &mut Session, p: &Value) -> Result { }; let is_line = |c: usize| matches!(sk.curves.get(c).map(|c| &c.kind), Some(CurveKind::Line { .. })); let is_circle = |c: usize| matches!(sk.curves.get(c).map(|c| &c.kind), Some(CurveKind::Circle { .. })); + let is_round = |c: usize| matches!(sk.curves.get(c).map(|c| &c.kind), Some(CurveKind::Circle { .. } | CurveKind::Arc { .. })); // The other reading of an angle between two lines (see below). let mut alt: Option<(ConstraintKind, f64)> = None; let (mut k, mut cur): (ConstraintKind, f64) = match (e0, e1) { @@ -2085,6 +2086,16 @@ fn dimension(s: &mut Session, p: &Value) -> Result { } } } + // A line and a circle or arc: the distance from the line to its edge (#1803). + ((None, Some(l)), Some((None, Some(c)))) | ((None, Some(c)), Some((None, Some(l)))) if is_line(l) && is_round(c) => { + let (a, b) = line_pts(sk, l).unwrap_or_default(); + let (centre, r) = sk.center(c).zip(sk.radius(c)).ok_or_else(|| bad(cmd, "cannot dimension that curve"))?; + let d = (b - a).normalized().map(|u| u.cross(centre - a).abs()).ok_or_else(|| bad(cmd, "that line has no length"))?; + // A line that cuts the circle measures how far its edge reaches past the line. + let inside = d < r; + let gap = (d - r).abs(); + (ConstraintKind::LineCircleDistance { l, c, value: gap, inside }, gap) + } _ => return Err(bad(cmd, "cannot dimension that combination of entities")), }; let is_angle = k.is_angle(); @@ -2598,6 +2609,9 @@ mod ids_tests; #[path = "sketch_infinite_tests.rs"] mod infinite_tests; #[cfg(test)] +#[path = "sketch_line_circle_tests.rs"] +mod line_circle_tests; +#[cfg(test)] #[path = "sketch_point_expr_tests.rs"] mod point_expr_tests; #[cfg(test)] diff --git a/crates/engine/src/cmd/sketch_constraints.rs b/crates/engine/src/cmd/sketch_constraints.rs index 862dcd533..59617b741 100644 --- a/crates/engine/src/cmd/sketch_constraints.rs +++ b/crates/engine/src/cmd/sketch_constraints.rs @@ -448,6 +448,7 @@ fn anchor(sk: &Sketch, k: &ConstraintKind) -> Option { } Distance { p, q, .. } | DistanceX { p, q, .. } | DistanceY { p, q, .. } => Some((pt(p)? + pt(q)?) * 0.5), PointLineDistance { p, .. } | LinearDiameter { p, .. } => pt(p), + LineCircleDistance { c, .. } => sk.center(c), Length { l, .. } | LineAngle { l, .. } => mid(l), Radius { c, .. } | Diameter { c, .. } | ArcLength { c, .. } | ArcSweep { c, .. } => mid(c), SlotOverallLength { a, b, .. } => Some((sk.center(a)? + sk.center(b)?) * 0.5), diff --git a/crates/engine/src/cmd/sketch_line_circle_tests.rs b/crates/engine/src/cmd/sketch_line_circle_tests.rs new file mode 100644 index 000000000..df8ac2d24 --- /dev/null +++ b/crates/engine/src/cmd/sketch_line_circle_tests.rs @@ -0,0 +1,115 @@ +//! Sketch Dimension from a line to the edge of a circle or arc (#1803): `sketch.dimension` with +//! a line and a circle or arc measures the gap to the edge (or how far the edge reaches past a +//! line that cuts it), drives it, follows its parameter, and survives undo and reopening. + +use serde_json::{Value, json}; +use solidcraft_geom::Vec2; + +use crate::Session; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + match s.execute(id, &p) { + Ok(v) => v, + Err(e) => panic!("{id} {p}: {e}"), + } +} + +fn sketch(s: &Session) -> solidcraft_sketch::Sketch { + s.model.state().sketch(s.active_sketch.unwrap()).unwrap().sketch.clone() +} + +fn point(s: &Session, id: &str) -> Vec2 { + let sk = sketch(s); + sk.resolve_point(id).and_then(|p| sk.point(p)).unwrap() +} + +/// A fixed line along x from (0, 0) to (40, 0) (`l1`) and a circle of diameter 10 at `centre` +/// (`c1`). +fn line_and_circle(centre: [f64; 2]) -> Session { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY"})); + run(&mut s, "sketch.line", json!({"points": [[0, 0], [40, 0]]})); + run(&mut s, "sketch.constraint.fix", json!({"entities": ["l1"]})); + run(&mut s, "sketch.circle.center", json!({"center": centre, "radius": 5})); + run(&mut s, "sketch.dimension", json!({"entities": ["c1"], "type": "diameter", "value": 10})); + s +} + +#[test] +fn a_line_and_a_circle_dimension_to_its_edge() { + let mut s = line_and_circle([20.0, 15.0]); + // Centre 15 above the line, radius 5: the gap to the edge is 10. + let r = run(&mut s, "sketch.dimension", json!({"entities": ["l1", "c1"]})); + assert_eq!(r["type"], "LinearDimension", "{r}"); + assert_eq!(r["measured"], 10.0, "{r}"); + let param = r["param"].as_str().unwrap().to_string(); + assert_eq!(r["expression"], "10 mm", "{r}"); + // The parameter drives the gap: 7 puts the centre 7 + 5 = 12 above the line. + run(&mut s, "parameters.change", json!({"name": param, "expression": "7 mm"})); + assert!(point(&s, "c1.center").dist(Vec2::new(20.0, 12.0)) < 1e-7, "{:?}", point(&s, "c1.center")); + // The circle and the line in the other order, with a value. + let mut s = line_and_circle([20.0, 15.0]); + let r = run(&mut s, "sketch.dimension", json!({"entities": ["c1", "l1"], "value": 3})); + assert_eq!(r["measured"], 3.0, "{r}"); + assert!(point(&s, "c1.center").dist(Vec2::new(20.0, 8.0)) < 1e-7, "{:?}", point(&s, "c1.center")); +} + +#[test] +fn a_line_that_cuts_the_circle_dimensions_how_far_the_edge_reaches_past_it() { + // Centre 3 above the line, radius 5: the edge reaches 2 below the line. + let mut s = line_and_circle([20.0, 3.0]); + let r = run(&mut s, "sketch.dimension", json!({"entities": ["l1", "c1"]})); + assert_eq!(r["measured"], 2.0, "{r}"); + let param = r["param"].as_str().unwrap().to_string(); + run(&mut s, "parameters.change", json!({"name": param, "expression": "4"})); + // Reaching 4 past the line leaves the centre 1 above it; it never crosses the line. + assert!(point(&s, "c1.center").dist(Vec2::new(20.0, 1.0)) < 1e-7, "{:?}", point(&s, "c1.center")); +} + +#[test] +fn an_arc_dimensions_to_its_circle() { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY"})); + run(&mut s, "sketch.line", json!({"points": [[0, 0], [40, 0]]})); + run(&mut s, "sketch.arc.center_point", json!({"center": [20, 20], "start": [26, 20], "end": [14, 20]})); + let r = run(&mut s, "sketch.dimension", json!({"entities": ["a1", "l1"]})); + assert_eq!(r["measured"], 14.0, "{r}"); +} + +#[test] +fn the_dimension_undoes_and_reopens() { + let mut s = line_and_circle([20.0, 15.0]); + let before = sketch(&s).constraints.len(); + run(&mut s, "sketch.dimension", json!({"entities": ["l1", "c1"], "value": 6})); + let saved = s.doc.to_json(); + assert!(saved.contains("\"line_circle_distance\""), "not saved"); + let mut reopened = Session::new(solidcraft_doc::Document::from_json(&saved).unwrap()); + run(&mut reopened, "sketch.edit", json!({"sketch": "Sketch1"})); + assert!(point(&reopened, "c1.center").dist(Vec2::new(20.0, 11.0)) < 1e-7, "{:?}", point(&reopened, "c1.center")); + let kinds = |s: &Session| sketch(s).constraints.iter().map(|c| c.kind.clone()).collect::>(); + assert_eq!(kinds(&reopened), kinds(&s)); + run(&mut s, "edit.undo", json!({})); + assert_eq!(sketch(&s).constraints.len(), before); +} + +#[test] +fn a_gap_the_sketch_already_has_is_refused_or_driven() { + // A tangent circle already has a gap of zero. + let mut s = line_and_circle([20.0, 5.0]); + run(&mut s, "sketch.constraint.tangent", json!({"a": "l1", "b": "c1"})); + let err = s.execute("sketch.dimension", &json!({"entities": ["l1", "c1"]})).unwrap_err().to_string(); + assert!(err.contains("already determined"), "{err}"); + let r = run(&mut s, "sketch.dimension", json!({"entities": ["l1", "c1"], "if_redundant": "driven"})); + assert_eq!(r["driven"], true, "{r}"); + assert!(r["measured"].as_f64().unwrap().abs() < 1e-7, "{r}"); +} + +#[test] +fn a_line_and_a_curve_that_is_not_round_is_still_refused() { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY"})); + run(&mut s, "sketch.line", json!({"points": [[0, 0], [40, 0]]})); + run(&mut s, "sketch.ellipse", json!({"center": [20, 20], "major": [30, 20], "minor_radius": 4})); + let err = s.execute("sketch.dimension", &json!({"entities": ["l1", "e1"]})).unwrap_err().to_string(); + assert!(err.contains("cannot dimension that combination"), "{err}"); +} diff --git a/crates/sketch/src/dims.rs b/crates/sketch/src/dims.rs index 9d9d9eca2..7d4acb808 100644 --- a/crates/sketch/src/dims.rs +++ b/crates/sketch/src/dims.rs @@ -92,6 +92,17 @@ pub fn dim_frame(sk: &Sketch, k: &ConstraintKind) -> Option { let p0 = if matches!(k, LinearDiameter { .. }) { foot * 2.0 - q } else { foot }; DimFrame::Linear { p0, p1: q, dir: unit(q - foot, d.perp()) } } + LineCircleDistance { l, c, .. } => { + // From the line to the circle's edge point nearest it (beyond it when the line cuts + // the circle), along the line's normal. + let (a, b) = line_ends(sk, l)?; + let (centre, r) = (sk.center(c)?, sk.radius(c)?); + let d = unit(b - a, Vec2::X); + let normal = unit(centre - (a + d * (centre - a).dot(d)), d.perp()); + let p1 = centre - normal * r; + let p0 = a + d * (p1 - a).dot(d); + DimFrame::Linear { p0, p1, dir: unit(p1 - p0, normal) } + } Radius { c, .. } | Diameter { c, .. } => { let radius = match sk.curves.get(c)?.kind { CurveKind::Ellipse { r, .. } => r, @@ -187,6 +198,7 @@ pub fn dim_reach(sk: &Sketch, k: &ConstraintKind) -> [Option<(Vec2, Vec2)>; 2] { let (p, l, to_line) = match *k { PointLineDistance { p, l, .. } => (p, l, true), LinearDiameter { p, l, .. } => (p, l, false), + LineCircleDistance { l, .. } => return [line_ends(sk, l), None], _ => return [None, None], }; let Some((a, b)) = line_ends(sk, l) else { return [None, None] }; diff --git a/crates/sketch/src/lib.rs b/crates/sketch/src/lib.rs index 9ddf30210..34d597cfe 100644 --- a/crates/sketch/src/lib.rs +++ b/crates/sketch/src/lib.rs @@ -83,6 +83,8 @@ mod font_tests; #[cfg(test)] mod least_motion_tests; #[cfg(test)] +mod line_circle_tests; +#[cfg(test)] mod tests; #[cfg(test)] mod thin_tests; diff --git a/crates/sketch/src/line_circle_tests.rs b/crates/sketch/src/line_circle_tests.rs new file mode 100644 index 000000000..0acbc3b4d --- /dev/null +++ b/crates/sketch/src/line_circle_tests.rs @@ -0,0 +1,136 @@ +//! The distance from a line to the edge of a circle or arc (#1803): solved numerically and by +//! construction, measured, kept on its side of the line through edits, and refused on other +//! kinds of curve. + +use solidcraft_geom::Vec2; + +use crate::tests::v; +use crate::*; + +/// A fixed line along x from (0, 0) to (40, 0) and a circle of radius `r` at `centre` (its +/// centre free, its radius set by a dimension). The line, the circle and the centre point. +fn line_and_circle(centre: Vec2, r: f64) -> (Sketch, usize, usize, usize) { + let mut sk = Sketch::new(); + let l = sk.add_line(v(0.0, 0.0), v(40.0, 0.0), None, None, None).unwrap(); + let (a, b) = sk.curves[l].kind.ends().unwrap(); + for p in [a, b] { + sk.add_constraint(ConstraintKind::Fix { p }, None).unwrap(); + } + let c = sk.add_circle(centre, r, None, None).unwrap(); + let CurveKind::Circle { c: ci, .. } = sk.curves[c].kind else { panic!("not a circle") }; + sk.add_constraint(ConstraintKind::Radius { c, value: r }, None).unwrap(); + (sk, l, c, ci) +} + +fn kind_at(sk: &Sketch, k: usize) -> ConstraintKind { + sk.constraints[k].kind.clone() +} + +#[test] +fn a_line_to_circle_distance_places_the_circle_its_gap_from_the_line() { + let (mut sk, l, c, ci) = line_and_circle(v(20.0, 15.0), 5.0); + let k = sk.constraints.len(); + sk.add_constraint(ConstraintKind::LineCircleDistance { l, c, value: 10.0, inside: false }, None).unwrap(); + // As drawn the gap is 15 − 5 = 10: the sketch already holds it. + assert!((solver::measure_dimension(&sk, &kind_at(&sk, k)).unwrap() - 10.0).abs() < 1e-9); + assert!(solve(&mut sk).ok()); + // A gap of 7 puts the centre 7 + 5 = 12 from the line, on the side it was drawn on. + sk.constraints[k].kind.set_value(7.0); + let rep = solve(&mut sk); + assert!(rep.ok(), "{rep:?}"); + let centre = sk.points[ci].pos; + assert!((centre.y - 12.0).abs() < 1e-7, "{centre:?}"); + assert!((solver::measure_dimension(&sk, &kind_at(&sk, k)).unwrap() - 7.0).abs() < 1e-7); + // Tangent: a gap of zero. + sk.constraints[k].kind.set_value(0.0); + assert!(solve(&mut sk).ok()); + assert!((sk.points[ci].pos.y - 5.0).abs() < 1e-7, "{:?}", sk.points[ci].pos); +} + +#[test] +fn a_circle_below_the_line_stays_below_it() { + let (mut sk, l, c, ci) = line_and_circle(v(20.0, -15.0), 5.0); + let k = sk.constraints.len(); + sk.add_constraint(ConstraintKind::LineCircleDistance { l, c, value: 10.0, inside: false }, None).unwrap(); + assert!(solve(&mut sk).ok()); + sk.constraints[k].kind.set_value(3.0); + assert!(solve(&mut sk).ok()); + assert!((sk.points[ci].pos.y + 8.0).abs() < 1e-7, "{:?}", sk.points[ci].pos); +} + +#[test] +fn a_line_that_cuts_the_circle_measures_how_far_its_edge_reaches_past_it() { + // Centre 3 above the line, radius 5: the edge reaches 5 − 3 = 2 below the line. + let (mut sk, l, c, ci) = line_and_circle(v(20.0, 3.0), 5.0); + let k = sk.constraints.len(); + sk.add_constraint(ConstraintKind::LineCircleDistance { l, c, value: 2.0, inside: true }, None).unwrap(); + assert!((solver::measure_dimension(&sk, &kind_at(&sk, k)).unwrap() - 2.0).abs() < 1e-9); + assert!(solve(&mut sk).ok()); + // Reaching 4 past the line leaves the centre 5 − 4 = 1 above it. + sk.constraints[k].kind.set_value(4.0); + let rep = solve(&mut sk); + assert!(rep.ok(), "{rep:?}"); + assert!((sk.points[ci].pos.y - 1.0).abs() < 1e-7, "{:?}", sk.points[ci].pos); +} + +#[test] +fn an_arc_is_measured_to_its_circle() { + let mut sk = Sketch::new(); + let l = sk.add_line(v(0.0, 0.0), v(40.0, 0.0), None, None, None).unwrap(); + let a = sk.add_arc(v(20.0, 20.0), v(26.0, 20.0), v(14.0, 20.0), [None; 3], None).unwrap(); + let k = sk.constraints.len(); + sk.add_constraint(ConstraintKind::LineCircleDistance { l, c: a, value: 14.0, inside: false }, None).unwrap(); + // Centre 20 above the line, radius 6. + assert!((solver::measure_dimension(&sk, &kind_at(&sk, k)).unwrap() - 14.0).abs() < 1e-9); +} + +#[test] +fn the_dimension_needs_a_line_and_a_circle_or_arc() { + let mut sk = Sketch::new(); + let l = sk.add_line(v(0.0, 0.0), v(40.0, 0.0), None, None, None).unwrap(); + let m = sk.add_line(v(0.0, 10.0), v(40.0, 10.0), None, None, None).unwrap(); + let c = sk.add_circle(v(20.0, 20.0), 5.0, None, None).unwrap(); + for (l, c) in [(m, l), (c, c), (c, l)] { + assert!(sk.add_constraint(ConstraintKind::LineCircleDistance { l, c, value: 1.0, inside: false }, None).is_err(), "{l} {c}"); + } + for value in [-1.0, f64::NAN, f64::INFINITY] { + assert!(sk.add_constraint(ConstraintKind::LineCircleDistance { l, c, value, inside: false }, None).is_err(), "{value}"); + } +} + +#[test] +fn the_dimension_survives_a_round_trip_and_a_renumbering() { + let (mut sk, l, c, _) = line_and_circle(v(20.0, 3.0), 5.0); + sk.add_constraint(ConstraintKind::LineCircleDistance { l, c, value: 2.0, inside: true }, None).unwrap(); + let json = serde_json::to_value(&sk).unwrap(); + let saved = json["constraints"].as_array().unwrap().last().unwrap().clone(); + assert_eq!(saved["type"], "line_circle_distance", "{saved}"); + assert_eq!(saved["inside"], true, "{saved}"); + let back: Sketch = serde_json::from_value(json).unwrap(); + assert_eq!(back.constraints, sk.constraints); + // `inside` is left out when false. + let outside = ConstraintKind::LineCircleDistance { l, c, value: 2.0, inside: false }; + assert!(serde_json::to_value(&outside).unwrap().get("inside").is_none()); + let mut k = outside; + assert!(k.remap(&|p| Some(p), &|i| Some(i + 10))); + assert_eq!(k.indices(), (vec![], vec![l + 10, c + 10])); + assert!(!k.remap(&|p| Some(p), &|_| None)); +} + +/// With the centre's x set too, the seed places the centre exactly (its offset line from the +/// dimension crossing the line of its x), before the numerical solver runs. +#[test] +fn the_seed_places_the_centre_by_construction() { + for (drawn, inside, value, want) in [(v(20.0, 15.0), false, 7.0, v(20.0, 12.0)), (v(20.0, 3.0), true, 4.0, v(20.0, 1.0))] { + let (mut sk, l, c, ci) = line_and_circle(drawn, 5.0); + let (a, _) = sk.curves[l].kind.ends().unwrap(); + sk.add_constraint(ConstraintKind::DistanceX { p: a, q: ci, value: 20.0 }, None).unwrap(); + sk.add_constraint(ConstraintKind::LineCircleDistance { l, c, value, inside }, None).unwrap(); + let out = crate::tests::seed_of(&sk); + assert!(out.placed_by[ci].is_some_and(crate::construct::Placement::anchors), "{out:?}"); + assert!(out.pos[ci].unwrap().dist(want) < 1e-9, "{out:?}"); + let rep = solve(&mut sk); + assert!(rep.ok() && rep.dof == 0, "{rep:?}"); + assert!(sk.points[ci].pos.dist(want) < 1e-9, "{:?}", sk.points[ci].pos); + } +} diff --git a/crates/sketch/src/loci.rs b/crates/sketch/src/loci.rs index 37ec3a775..cc61a08e6 100644 --- a/crates/sketch/src/loci.rs +++ b/crates/sketch/src/loci.rs @@ -887,6 +887,14 @@ pub(crate) fn read(sk: &Sketch, before: &dyn Fn(usize) -> Option, on_curve ties.push(Tie::Offset { p, l, len: Len::Value(d) }); } } + // The centre lies radius ± the gap from the line, on its side in the reference. + LineCircleDistance { l, c, value, inside } if line(l).is_some() => { + if let (Some(rd), Some(r)) = (round(c), r_of(c)) + && let Some(d) = dim(if inside { r - value } else { r + value }) + { + ties.push(Tie::Offset { p: rd.c, l, len: Len::Value(d) }); + } + } Tangent { a, b } => { let (l, curve) = if line(a).is_some() { (a, b) } else { (b, a) }; if line(l).is_some() diff --git a/crates/sketch/src/model.rs b/crates/sketch/src/model.rs index 82ce56d89..9a737038d 100644 --- a/crates/sketch/src/model.rs +++ b/crates/sketch/src/model.rs @@ -303,6 +303,17 @@ pub enum ConstraintKind { l: usize, value: f64, }, + /// Distance from line `l` to the edge of circle or arc `c`, along the line's normal: the + /// gap `|distance from the centre to the line| − radius` while the line misses the circle, + /// or, `inside`, how far the edge reaches past the line, `radius − |distance|`, while the + /// line cuts it. Zero is tangency either way. An arc is measured to its whole circle. + LineCircleDistance { + l: usize, + c: usize, + value: f64, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + inside: bool, + }, Length { l: usize, value: f64, @@ -380,6 +391,7 @@ impl ConstraintKind { | DistanceX { value, .. } | DistanceY { value, .. } | PointLineDistance { value, .. } + | LineCircleDistance { value, .. } | Length { value, .. } | LineAngle { value, .. } | ArcSweep { value, .. } @@ -400,6 +412,7 @@ impl ConstraintKind { | DistanceX { value, .. } | DistanceY { value, .. } | PointLineDistance { value, .. } + | LineCircleDistance { value, .. } | Length { value, .. } | LineAngle { value, .. } | ArcSweep { value, .. } @@ -433,7 +446,9 @@ impl ConstraintKind { Midpoint { .. } => "MidPoint", Symmetric { .. } => "Symmetry", Fix { .. } => "Fix", - Distance { .. } | DistanceX { .. } | DistanceY { .. } | PointLineDistance { .. } | Length { .. } => "LinearDimension", + Distance { .. } | DistanceX { .. } | DistanceY { .. } | PointLineDistance { .. } | LineCircleDistance { .. } | Length { .. } => { + "LinearDimension" + } Radius { .. } => "RadialDimension", Diameter { .. } => "DiameterDimension", Angle { .. } | LineAngle { .. } | ArcSweep { .. } => "AngularDimension", @@ -466,6 +481,7 @@ impl ConstraintKind { } Angle { a, b, .. } | SlotOverallLength { a, b, .. } => (vec![], vec![a, b]), Midpoint { p, l } | PointLineDistance { p, l, .. } => (vec![p], vec![l]), + LineCircleDistance { l, c, .. } => (vec![], vec![l, c]), Symmetric { p, q, l } => (vec![p, q], vec![l]), Fix { p } => (vec![p], vec![]), Smooth { a, b } => (vec![], vec![a, b]), @@ -529,6 +545,10 @@ impl ConstraintKind { fp(p); fc(l); } + LineCircleDistance { l, c, .. } => { + fc(l); + fc(c); + } Symmetric { p, q, l } => { fp(p); fp(q); @@ -969,6 +989,10 @@ impl Sketch { return Err(SketchError::Invalid("overall slot length must exceed its width".into())); } } + LineCircleDistance { l, c, .. } => { + need_line(l)?; + need_round(c)?; + } Tangent { a, b } => { let free = |i: usize| self.curves.get(i).is_some_and(|c| c.kind.is_freeform()); if !(is_round(a) || is_round(b) || free(a) || free(b)) { diff --git a/crates/sketch/src/solver.rs b/crates/sketch/src/solver.rs index 3c1dfa825..af0b61ee1 100644 --- a/crates/sketch/src/solver.rs +++ b/crates/sketch/src/solver.rs @@ -347,6 +347,14 @@ impl State<'_> { let sweep = ((self.p(b) - self.p(cp)).angle() - (self.p(a) - self.p(cp)).angle()).rem_euclid(std::f64::consts::TAU); if curve.reversed { -sweep } else { sweep } } + /// What a line-to-circle distance measures: the gap from line `l` to the edge of circle or + /// arc `c`, or (`inside`) how far the edge reaches past the line. + fn line_circle_gap(&self, l: usize, c: usize, inside: bool) -> f64 { + let (a, b) = self.line(l); + let (cc, r) = self.round(c); + let d = line_dist(cc, a, b).abs(); + if inside { r - d } else { d - r } + } fn slot_length(&self, a: usize, b: usize) -> f64 { let (ca, ra) = self.round(a); let (cb, rb) = self.round(b); @@ -547,6 +555,7 @@ fn residuals(s: &State, k: &ConstraintKind, out: &mut Vec) { let (a, b) = s.line(l); out.push(line_dist(s.p(p), a, b).abs() - value); } + LineCircleDistance { l, c, value, inside } => out.push(s.line_circle_gap(l, c, inside) - value), Length { l, value } => { let (a, b) = s.line(l); out.push(a.dist(b) - value); @@ -609,6 +618,7 @@ fn measure(s: &State, k: &ConstraintKind) -> Option { let (a, b) = s.line(l); line_dist(s.p(p), a, b).abs() } + LineCircleDistance { l, c, inside, .. } => s.line_circle_gap(l, c, inside), Length { l, .. } => { let (a, b) = s.line(l); a.dist(b) @@ -814,6 +824,7 @@ fn block_refs(sk: &Sketch, b: &Block) -> Vec { | DistanceY { p, q, .. } => vec![P(p), P(q)], PointOnCurve { p, c } => vec![P(p), C(c)], Midpoint { p, l } | PointLineDistance { p, l, .. } | LinearDiameter { p, l, .. } => vec![P(p), L(l)], + LineCircleDistance { l, c, .. } => vec![L(l), R(c)], Horizontal { l } | Vertical { l } | Length { l, .. } | LineAngle { l, .. } => vec![L(l)], // Another kind reads a constant value, whatever its points: as good as any. ArcSweep { c, .. } | Radius { c, .. } | Diameter { c, .. } | ArcLength { c, .. } => vec![C(c)], @@ -1579,7 +1590,8 @@ enum Orient { SideX(usize, usize, f64), /// The same along y (`DistanceY`). SideY(usize, usize, f64), - /// Which side of line `l` the point `p` is on (`PointLineDistance`, `LinearDiameter`). + /// Which side of line `l` the point `p` is on (`PointLineDistance`, `LinearDiameter`, a + /// circle's centre for `LineCircleDistance`). OfLine(usize, usize, f64), } @@ -1748,6 +1760,12 @@ fn orients(s: &State, sub: &[(Block, Vec)]) -> Vec<(Orient, Vec)> ConstraintKind::DistanceY { p, q, value } if free(p) || free(q) => out.push((Orient::SideY(p, q, value), vec![*ci])), ConstraintKind::PointLineDistance { p, l, value } => out.push((Orient::OfLine(p, l, value), vec![*ci])), ConstraintKind::LinearDiameter { p, l, value } => out.push((Orient::OfLine(p, l, value / 2.0), vec![*ci])), + // The circle stays on its side of the line: the distance is unsigned. + ConstraintKind::LineCircleDistance { l, c, value, .. } => { + if let Some(CurveKind::Circle { c: centre, .. } | CurveKind::Arc { c: centre, .. }) = s.sk.curves.get(c).map(|x| &x.kind) { + out.push((Orient::OfLine(*centre, l, value + s.round(c).1), vec![*ci])); + } + } _ => {} } } diff --git a/crates/ui-egui/tests/scenarios/sketch_dimension_line_to_circle_edge.json b/crates/ui-egui/tests/scenarios/sketch_dimension_line_to_circle_edge.json new file mode 100644 index 000000000..82ea20a1d --- /dev/null +++ b/crates/ui-egui/tests/scenarios/sketch_dimension_line_to_circle_edge.json @@ -0,0 +1,19 @@ +[ + {"call": "engine.execute", "params": {"command": "sketch.create", "params": {"plane": "XY"}}}, + {"call": "engine.execute", "params": {"command": "sketch.line", "params": {"points": [[0, 0], [40, 0]]}}}, + {"call": "engine.execute", "params": {"command": "sketch.constraint.fix", "params": {"entities": ["l1"]}}}, + {"call": "engine.execute", "params": {"command": "sketch.circle.center", "params": {"center": [20, 15], "radius": 5}}}, + {"call": "engine.execute", "params": {"command": "sketch.dimension", "params": {"entities": ["c1"], "type": "diameter", "value": 10, "text_at": [30, 22]}}}, + {"call": "ui.view", "params": {"view": "top"}}, + {"call": "ui.view", "params": {"view": "fit"}}, + {"start": "sketch.dimension"}, + {"click": {"sketch": [8, 0]}}, + {"click": {"sketch": [20, 10]}}, + {"text": "7"}, + {"key": "Enter"}, + {"key": "Escape"}, + {"expect": {"errors": 0}}, + {"expect": {"param": {"d2": 7}}}, + {"expect": {"query": {"command": "sketch.inspect", "path": ["curves", 1, "center_at", 1], "value": 12}}}, + {"expect": {"query": {"command": "sketch.inspect", "path": ["curves", 1, "center_at", 0], "value": 20}}} +] diff --git a/docs/book/src/guide/sketching.md b/docs/book/src/guide/sketching.md index d01540dbb..c9595d0ce 100644 --- a/docs/book/src/guide/sketching.md +++ b/docs/book/src/guide/sketching.md @@ -177,7 +177,8 @@ or vertical alignment from their current positions. Esc cancels a pending first The solver is SolidCraft's own (damped Gauss–Newton with degree-of-freedom analysis). Constraints: coincident, horizontal/vertical, parallel, perpendicular, tangent, equal, concentric, collinear, midpoint, symmetry, fix, curvature (G2) and polygon. **Sketch Dimension** (D) adds linear, -aligned, horizontal, vertical, radius, diameter and angle dimensions. Each is a parameter +aligned, horizontal, vertical, point-to-line, line-to-circle, radius, diameter and angle +dimensions. Each is a parameter (`d1`, `d2`, …), so it can hold an expression. Press D, click what you want to measure and type the value: as soon as the click settles the @@ -197,6 +198,13 @@ Between two points, or on a line, that don't line up with an axis, where you pla dimension picks what it measures: across from them, the distance between them; above or below them, the horizontal distance; beside them, the vertical distance. +A line and a circle or arc (click the line, then the circle's edge, or the other way round) +measure from the line to the circle's edge, square to the line: the gap between them, 0 when +the circle touches the line. When the line cuts through the circle, the dimension measures how +far the edge reaches past the line instead. An arc is measured to the circle it lies on. For +the distance to the centre, click the centre point instead of the edge. In scripts: +`{"command": "sketch.dimension", "params": {"entities": ["l1", "c1"], "value": 5}}`. + A dimension the sketch can't take, because the geometry is already fixed by other constraints and dimensions, is added as a driven (reference) dimension instead: it is shown in parentheses, measures the sketch, and has no value to edit. diff --git a/docs/capabilities.md b/docs/capabilities.md index 00c98dc42..9a93a4624 100644 --- a/docs/capabilities.md +++ b/docs/capabilities.md @@ -31,7 +31,7 @@ and help is welcome: see [CONTRIBUTING.md](../CONTRIBUTING.md). and the rank of its Jacobian gives the remaining degrees of freedom. Constraints: coincident, point on curve, horizontal/vertical, parallel, perpendicular, tangent, curvature (G2), equal, concentric, collinear, midpoint, symmetry, fix; linear, aligned, horizontal, vertical, - point-to-line, radius, diameter, angle, arc sweep, arc length and slot length dimensions driven + point-to-line, line-to-circle, radius, diameter, angle, arc sweep, arc length and slot length dimensions driven by parameters. Over-constraining edits are rejected; fully constrained geometry turns black. Dragging solves the sketch every frame and rebuilds the model once, when the drag ends. Select a line or its two endpoints, type its dimension and press Enter to commit one undo diff --git a/skills/solidcraft-modeling/reference.md b/skills/solidcraft-modeling/reference.md index 31352761e..aaba13f93 100644 --- a/skills/solidcraft-modeling/reference.md +++ b/skills/solidcraft-modeling/reference.md @@ -47,8 +47,11 @@ These are the shapes of the commands a part build needs, so an agent rarely has {"command":"sketch.dimension","params":{"entities":["origin","c1.center"],"type":"horizontal","value":"w/2 - wall - 6"}} {"command":"sketch.dimension","params":{"entities":["c1"],"type":"diameter","value":"6"}} {"command":"sketch.dimension","params":{"entities":["l1"],"value":"w"}} +{"command":"sketch.dimension","params":{"entities":["l1","c1"],"value":"2"}} ``` +A line with a circle or arc measures from the line to its edge (0 is tangent); give the centre point (`c1.center`) for the distance to the centre. + Distances are unsigned. Draw the geometry on the correct side first, and the dimension keeps it there. `sketch.draw.dimensioned` creates a shape and its dimensions in one undo step. The dimension roles depend on the creator: From fe3b14e798f4cdf71f672605561232204a4ec7e9 Mon Sep 17 00:00:00 2001 From: JIJINBEI <87472238+jijinbei@users.noreply.github.com> Date: Tue, 20 Oct 2026 03:44:49 +0000 Subject: [PATCH 175/225] refactor: Aabb2 and point-built Aabb3 for every hand-rolled box (#2428) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Iterate instead of indexing in nine loops Replace index loops that look up neighbours by position with enumerate, zip(cycle().skip(1)) for wrap-around pairs and zip(skip(1)) for consecutive pairs. No behaviour change. Co-Authored-By: Claude Opus 5.5 * geom: ring_edges for the edges of a closed ring Every walk over a polygon's edges, the last back to the first, spelled x.iter().zip(x.iter().cycle().skip(1)); eighteen of them now call geom::ring_edges. Three redundant take(len) calls go with them. Co-Authored-By: Claude Opus 5.5 * geom: Ring, a closed ring that knows it is closed A Ring holds items in order around a closed polygon, loop or fan; edges() walks each with the next and the last with the first, corners() each with both neighbours. Ring has signed_area and even-odd contains. Loop2::polyline returns a Ring, as do doc's face_loops and boundary_loops, kernel's coplanar wire samples, CapLoop's segments, tess pieces' rings, the gizmo's plane quads and the navigation cube's facets. Their walks take edges() or corners() instead of wrapping an index; sketch's text-hole test and doc's poly_area become contains and signed_area. Loop2::joints pairs each segment with the next. Replaces the ring_edges free function. Co-Authored-By: Claude Opus 5.5 * geom: Chain, Ring and Path; bounds for a chain of points Ring becomes Chain beside Path = Chain: edges() closes a ring and stops at a path's end, Path::close makes the ring, and bounds() (the empty box for no points) serves both. Eight hand-rolled min/max folds over a loop's polyline call bounds(); doc's flat_polyline returns a Ring. Co-Authored-By: Claude Opus 5.5 * geom: area and inside on Ring for any planar point Ring's signed_area and contains take any Planar point (Vec2 or [f64; 2]). The cam profile in joints_cam is a Ring: its own even-odd test goes, and its edge walks, gap and area take edges(). face_params' loop area, the text path's winding, tess pieces' ring area and the copies in three tests call signed_area or contains; the formulas are the same term for term. Co-Authored-By: Claude Opus 5.5 * doc: sheet's closed outlines go through Ring dedup takes and returns a Ring (dropping a last point back on the first is what makes it a ring's), near_outline walks a Ring's edges, and the copy of it beside fold checks calls it. point_in goes: its callers ask the Ring. Its formula anchored each crossing on the other end of the edge, so the two can differ only for a point on an edge to the last digit; one caller sets such points aside first, the others test a region's interior point, a cut's midpoint or another outline's corners. Co-Authored-By: Claude Opus 5.5 * doc: cam tests build their outlines with Ring::from Co-Authored-By: Claude Opus 5.5 * geom: area_vector on Ring; three Newell sums use it Ring::area_vector is half the sum of a × b round the ring. heal's loop_area, lip's outer-loop turning and the revolve's loop orientation summed it by hand with a wrapped index; they take it from the Ring (the half is exact, and two of them only read its sign). Co-Authored-By: Claude Opus 5.5 * geom: Aabb3 from points; boxes built and asked through it Aabb3 collects from points (skipping non-finite ones, as add does) and gains inflated, contains and meets. Fifteen hand-rolled min/max folds over points or boxes in kernel, doc and engine become collect or union, and their "within tol of the box" tests become inflated(tol).contains. blend's refused-edge boxes and naming's face index hold an Aabb3. A NaN point is now outside every box, where the old negated comparisons let it in; an infinite point no longer stretches a box. Co-Authored-By: Claude Opus 5.5 * geom: Aabb2, the plane's box; 2D folds and box tuples use it Aabb2 mirrors Aabb3 (collect, add, union, inflated, contains, meets) and adds relative, a point's place in the box. sketch's link and link_loops each had that formula; link_loops' boundaries, prism's segment and loop boxes, profiles' shape boxes and grid, and ends' segment box hold an Aabb2 instead of a (low, high) pair. Folds in the cam, sketch bounds, sheet's perforation grid and the sketch clipboard collect one. Boxes are built from the same terms (a round's box keeps c - r - tol). As with Aabb3, a NaN point is outside every box and an infinite point no longer stretches one. Co-Authored-By: Claude Opus 5.5 * kernel: prism's segment boxes are plain Aabb2s The SegBox alias named a (low, high) pair; Aabb2 says it itself. Co-Authored-By: Claude Opus 5.5 * geom: Chain::bounds is an Aabb2; the boxes #2382 left as pairs follow Chain::bounds returns an Aabb2. Its callers keep it: sheet's hole and cut boxes (loop_box), letter boxes, island outlines and line-near-cut test use meets, contains and inflated; profile's outline overlap and max_clearance, profiles' box tests and the cam test read its corners. flat_size and the flat pattern's JSON size are the union of the loops' boxes (0 × 0 for no loop, where the pair fold gave -∞). Co-Authored-By: Claude Opus 5.5 * geom: Aabb3::intersection; hand-grown and hand-met boxes use the box Aabb3::intersection is the box both hold. ops' four overlap boxes of a boolean's operands take it, and seven boxes grown by hand (ops' body boxes, the distance set's bounds, coplanar's face box, eval_more's padded mesh box, compare's group and region boxes) call inflated with the same amount on every side. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: bherbruck --- assets/icons/ui/source/navigation.rs | 6 +- crates/doc/src/eval.rs | 7 +- crates/doc/src/eval_more.rs | 31 +-- crates/doc/src/joints.rs | 19 +- crates/doc/src/joints_cam.rs | 78 ++---- crates/doc/src/naming.rs | 25 +- crates/doc/src/project.rs | 9 +- crates/doc/src/project_order.rs | 7 +- crates/doc/src/sheet.rs | 168 ++++--------- crates/doc/src/sheet_convert.rs | 11 +- crates/engine/src/cmd/component_properties.rs | 10 +- crates/engine/src/cmd/motion.rs | 12 +- crates/engine/src/cmd/parts.rs | 13 +- crates/engine/src/cmd/sheet.rs | 12 +- crates/engine/src/cmd/sketch_clipboard.rs | 17 +- crates/engine/src/cmd/sketch_inspect.rs | 12 +- crates/engine/src/tests/import_component.rs | 9 +- crates/geom/src/aabb2.rs | 104 ++++++++ crates/geom/src/chain.rs | 223 ++++++++++++++++++ crates/geom/src/compare.rs | 7 +- crates/geom/src/fill.rs | 13 +- crates/geom/src/lib.rs | 4 + crates/geom/src/mesh.rs | 48 +++- crates/geom/src/profile.rs | 77 +++--- crates/geom/src/tests.rs | 15 ++ crates/kernel/src/blend.rs | 32 +-- crates/kernel/src/body.rs | 12 +- crates/kernel/src/build.rs | 11 +- crates/kernel/src/coplanar.rs | 13 +- crates/kernel/src/curveblend_tests.rs | 2 +- crates/kernel/src/delete_face.rs | 18 +- crates/kernel/src/distance.rs | 7 +- crates/kernel/src/face_params.rs | 13 +- crates/kernel/src/fill.rs | 16 +- crates/kernel/src/heal.rs | 15 +- crates/kernel/src/lip.rs | 6 +- crates/kernel/src/ops.rs | 11 +- crates/kernel/src/polybool.rs | 8 +- crates/kernel/src/prism.rs | 59 ++--- crates/kernel/src/prism_measure.rs | 21 +- crates/kernel/src/provenance.rs | 21 +- crates/kernel/src/sew.rs | 5 +- crates/kernel/src/step_in/geom.rs | 5 +- crates/kernel/src/tess/cutgrid.rs | 12 +- crates/kernel/src/tess/mod.rs | 9 +- crates/kernel/src/tess/pieces.rs | 36 +-- crates/kernel/src/tess/seam.rs | 3 +- crates/kernel/src/tests.rs | 2 +- crates/sketch/src/ends.rs | 17 +- crates/sketch/src/link.rs | 7 +- crates/sketch/src/link_loops.rs | 38 +-- crates/sketch/src/model.rs | 17 +- crates/sketch/src/profiles.rs | 67 ++---- crates/sketch/src/tests.rs | 5 +- crates/sketch/src/text.rs | 5 +- crates/ui-egui/src/gizmo.rs | 11 +- crates/ui-egui/src/navigation_cube.rs | 10 +- crates/ui-egui/src/preview.rs | 4 +- 58 files changed, 762 insertions(+), 693 deletions(-) create mode 100644 crates/geom/src/aabb2.rs create mode 100644 crates/geom/src/chain.rs diff --git a/assets/icons/ui/source/navigation.rs b/assets/icons/ui/source/navigation.rs index 234b7e245..54e6ca980 100644 --- a/assets/icons/ui/source/navigation.rs +++ b/assets/icons/ui/source/navigation.rs @@ -1,10 +1,10 @@ //! Navigation drawing definitions. Camera projection and picking remain in the UI widgets. use crate::theme::Tokens; use egui::{Align2, Color32, FontId, Pos2, Rect, Shape, Stroke, pos2, vec2}; -use solidcraft_engine::geom::Vec3; +use solidcraft_engine::geom::{Ring, Vec3}; pub(crate) struct Facet { pub(crate) direction: Vec3, - pub(crate) points: Vec, + pub(crate) points: Ring, pub(crate) outer_edges: Vec, pub(crate) centre: Pos2, pub(crate) label: String, @@ -89,7 +89,7 @@ pub(crate) fn paint_cube(painter: &egui::Painter, faces: &[Facet], hovered: Opti for &p in &face.points { fill_mesh.colored_vertex(p, fill); } - for (j, (&a, &b)) in face.points.iter().zip(face.points.iter().cycle().skip(1)).take(face.points.len()).enumerate() { + for (j, (&a, &b)) in face.points.edges().enumerate() { fill_mesh.add_triangle(centre, centre + 1 + j as u32, centre + 1 + ((j + 1) % face.points.len()) as u32); // Coplanar picking regions have no visible seams. Only actual cube // edges and the hovered target's boundary receive an outline. diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 4d7a7c69e..052bf9241 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -1944,12 +1944,7 @@ pub fn through_all_distance(st: &ModelState, plane: &Plane, targets: &[String]) /// Sample points inside a region (sketch coordinates). fn region_samples(r: &Region2) -> Vec { let mut out = vec![r.interior_point()]; - let pts = r.outer.polyline(1e-2); - let (mut lo, mut hi) = (Vec2::new(f64::INFINITY, f64::INFINITY), Vec2::new(f64::NEG_INFINITY, f64::NEG_INFINITY)); - for p in &pts { - lo = Vec2::new(lo.x.min(p.x), lo.y.min(p.y)); - hi = Vec2::new(hi.x.max(p.x), hi.y.max(p.y)); - } + let solidcraft_geom::Aabb2 { min: lo, max: hi } = r.outer.polyline(1e-2).bounds(); for i in 0..5 { for j in 0..5 { let p = Vec2::new(lo.x + (hi.x - lo.x) * (0.1 + 0.2 * i as f64), lo.y + (hi.y - lo.y) * (0.1 + 0.2 * j as f64)); diff --git a/crates/doc/src/eval_more.rs b/crates/doc/src/eval_more.rs index 6a4fa7e9c..5d1356f32 100644 --- a/crates/doc/src/eval_more.rs +++ b/crates/doc/src/eval_more.rs @@ -5,7 +5,7 @@ use super::*; use crate::EmbossFace; use crate::apply_point; use crate::sheet; -use solidcraft_geom::{Aabb3, Loop2, Seg2}; +use solidcraft_geom::{Aabb3, Loop2, Ring, Seg2}; pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, st: &mut ModelState) -> Result<()> { match &f.kind { @@ -775,11 +775,6 @@ pub(super) fn sheet_eval( } } -fn poly_area(p: &[Vec2]) -> f64 { - let m = p.len(); - (0..m).filter_map(|i| Some(p.get(i)?.cross(*p.get((i + 1) % m)?))).sum::() / 2.0 -} - /// Current unmodified extrusion caps, including placement, certify the tool's depth. /// Tessellation can drift in thickness at distant coordinates and cannot certify a slab. fn sheet_tool_span(body: &Body, source: &Plane) -> Option<(f64, f64, f64, Option<(Plane, Region2)>)> { @@ -1363,9 +1358,7 @@ fn mesh_box(mb: &ModelBody) -> Option { fn padded_box(mesh: &solidcraft_geom::Mesh, tol: f64) -> Option { let b = mesh.bounds(); - let pad = 2.0 * tol + 1e-6; - let pad = Vec3::new(pad, pad, pad); - (!b.is_empty() && b.min.is_finite() && b.max.is_finite()).then(|| Aabb3 { min: b.min - pad, max: b.max + pad }) + (!b.is_empty() && b.min.is_finite() && b.max.is_finite()).then(|| b.inflated(2.0 * tol + 1e-6)) } /// Whether two boxes are known to be apart (an unknown box is never apart). @@ -1405,7 +1398,7 @@ fn parted_note(sh: &sheet::SheetBody, material: &[Region2], before: &sheet::Shee /// Outline loops (in `plane` coordinates) of the mesh triangles lying in the plane at distance /// `level` from `at` along `n`: the edges used by one of them only, chained. -fn face_loops(mesh: &solidcraft_geom::Mesh, plane: &Plane, at: Vec3, n: Vec3, level: f64, tol: f64) -> Vec> { +fn face_loops(mesh: &solidcraft_geom::Mesh, plane: &Plane, at: Vec3, n: Vec3, level: f64, tol: f64) -> Vec> { face_outline(mesh, plane, at, n, level, tol).into_iter().map(|l| l.into_iter().map(|(p, _)| p).collect()).collect() } @@ -1443,7 +1436,7 @@ fn face_outline(mesh: &solidcraft_geom::Mesh, plane: &Plane, at: Vec3, n: Vec3, } /// The loops (in `plane` coordinates) that bound the triangles `on` of the mesh. -fn boundary_loops(mesh: &solidcraft_geom::Mesh, plane: &Plane, on: &[[u32; 3]]) -> Vec> { +fn boundary_loops(mesh: &solidcraft_geom::Mesh, plane: &Plane, on: &[[u32; 3]]) -> Vec> { chain_loops(mesh, plane, on, |_, _| None).into_iter().map(|l| l.into_iter().map(|(p, _)| p).collect()).collect() } @@ -1640,7 +1633,7 @@ fn plate_recesses(body: &Body, mesh: &Mesh, plane: &Plane, at: Vec3, n: Vec3, (l for (f, d, ..) in &floors { let on: Vec<[u32; 3]> = fine.triangles.iter().zip(&fine.tri_face).filter(|(_, g)| **g as usize == *f).map(|(tri, _)| *tri).collect(); let mut loops = boundary_loops(&fine, plane, &on); - loops.sort_by(|a, b| poly_area(b).abs().total_cmp(&poly_area(a).abs())); + loops.sort_by(|a, b| b.signed_area().abs().total_cmp(&a.signed_area().abs())); let mut it = loops.into_iter(); let Some(outline) = it.next() else { continue }; let region = Region2 { outer: Loop2::polygon(&outline).ccw(), holes: it.map(|l| Loop2::polygon(&l).ccw().reversed()).collect() }; @@ -1837,24 +1830,24 @@ pub(super) fn plastic_eval(doc: &Document, vals: &BTreeMap, f: &F let tol = (mb.body.size() * 1e-3).max(1e-3); let mesh = mb.body.tessellate(tol)?; let mut loops = face_loops(&mesh, &plane, face.0, n, 0.0, tol); - loops.sort_by(|a, b| poly_area(b).abs().total_cmp(&poly_area(a).abs())); - let ccw = |l: &[Vec2]| if poly_area(l) < 0.0 { l.iter().rev().copied().collect::>() } else { l.to_vec() }; + loops.sort_by(|a, b| b.signed_area().abs().total_cmp(&a.signed_area().abs())); + let ccw = |l: &Ring| if l.signed_area() < 0.0 { l.iter().rev().copied().collect::>() } else { l.clone() }; // The inner edge is an opening (the cavity under a rim): not the foot of a boss or a // wall standing on the face, whose side the band would run against. - let opening = |l: &[Vec2]| { + let opening = |l: &Ring| { let eps = (tol * 4.0).max(1e-3); - l.iter().zip(l.iter().cycle().skip(1)).filter_map(|(a, b)| Some(((*a + *b) * 0.5, (*b - *a).normalized()?))).take(3).any(|(m, t)| { + l.edges().filter_map(|(a, b)| Some(((*a + *b) * 0.5, (*b - *a).normalized()?))).take(3).any(|(m, t)| { // Just over the face, inside the loop (to the left of a ccw loop's edges). let q = plane.to_world(m + Vec2::new(-t.y, t.x) * eps) + n * eps; !mesh.contains(q) }) }; - let outer = loops.first().map(|l| ccw(l)); - let openings: Vec> = loops.iter().skip(1).map(|l| ccw(l)).filter(|l| opening(l)).collect(); + let outer = loops.first().map(ccw); + let openings: Vec> = loops.iter().skip(1).map(ccw).filter(|l| opening(l)).collect(); // A rim runs round one opening, the cavity; smaller ones (a screw hole) may sit in it. // Openings alike in size (a plate's holes) leave no edge that is the rim's. let alike = match openings.as_slice() { - [a, b, ..] => poly_area(b).abs() > 0.5 * poly_area(a).abs(), + [a, b, ..] => b.signed_area().abs() > 0.5 * a.signed_area().abs(), _ => false, }; let (Some(outer), Some(inner), false) = (outer, openings.first().cloned(), alike) else { diff --git a/crates/doc/src/joints.rs b/crates/doc/src/joints.rs index 9b9942b59..a099d7963 100644 --- a/crates/doc/src/joints.rs +++ b/crates/doc/src/joints.rs @@ -17,7 +17,7 @@ use std::collections::{BTreeMap, BTreeSet, VecDeque}; use serde::{Deserialize, Serialize}; -use solidcraft_geom::Vec3; +use solidcraft_geom::{Aabb3, Vec3}; use solidcraft_sketch::linalg; @@ -1209,15 +1209,14 @@ fn limit_bounds(tree: &Tree, vars: &[(u64, usize)]) -> Vec<(f64, f64)> { /// The loops' size: the diagonal of the box around their joints' A frames, 1 mm to 1 km. Points /// that far apart weigh turns like moves. fn loop_scale(tree: &Tree, around: &BTreeSet, vals: &Values) -> f64 { - let (mut lo, mut hi) = (Vec3::new(f64::MAX, f64::MAX, f64::MAX), Vec3::new(f64::MIN, f64::MIN, f64::MIN)); - for id in around { - let (Some(j), Some((fa, _))) = (tree.joints.get(id), tree.frames.get(id)) else { continue }; - let Some(t) = tree.world(j.a.occurrence, vals) else { continue }; - let p = apply_point(&mat_mul(&t, fa), Vec3::ZERO); - lo = Vec3::new(lo.x.min(p.x), lo.y.min(p.y), lo.z.min(p.z)); - hi = Vec3::new(hi.x.max(p.x), hi.y.max(p.y), hi.z.max(p.z)); - } - if lo.x <= hi.x { (hi - lo).len().clamp(1.0, 1e6) } else { 1.0 } + let joints: Aabb3 = around + .iter() + .filter_map(|id| { + let (j, (fa, _)) = (tree.joints.get(id)?, tree.frames.get(id)?); + Some(apply_point(&mat_mul(&tree.world(j.a.occurrence, vals)?, fa), Vec3::ZERO)) + }) + .collect(); + if joints.is_empty() { 1.0 } else { joints.diagonal().clamp(1.0, 1e6) } } /// How far each closing joint is from meeting: three points of B's joint frame, `scale` apart, diff --git a/crates/doc/src/joints_cam.rs b/crates/doc/src/joints_cam.rs index 16fafc6f5..54e57fba3 100644 --- a/crates/doc/src/joints_cam.rs +++ b/crates/doc/src/joints_cam.rs @@ -15,7 +15,7 @@ use std::f64::consts::TAU; use serde::{Deserialize, Serialize}; -use solidcraft_geom::{Vec2, Vec3}; +use solidcraft_geom::{Aabb2, Aabb3, Ring, Vec2, Vec3}; use super::{JointKind, JointOrigin, MotionLink, Size, component_bodies, component_of, flip_of, occurrence_world, size_of}; use crate::{DocError, Document, IDENTITY, Mat, ModelState, Result, apply_point, apply_vector, mat_inverse, mat_mul}; @@ -108,7 +108,7 @@ fn rot(v: Vec2, a: f64) -> Vec2 { /// Where a translating follower coming along `-d` from far along its line through `g` first /// touches the closed polygon `poly`: the largest `t` of its point `g + t·d` (its roller's centre /// for `r > 0`; for `flat`, its face square to `d`). `None` when it misses the profile. -pub fn first_contact_along(poly: &[Vec2], g: Vec2, d: Vec2, r: f64, flat: bool) -> Option { +pub fn first_contact_along(poly: &Ring, g: Vec2, d: Vec2, r: f64, flat: bool) -> Option { let n = d.perp(); let mut best: Option = None; let mut take = |t: f64| { @@ -122,9 +122,7 @@ pub fn first_contact_along(poly: &[Vec2], g: Vec2, d: Vec2, r: f64, flat: bool) } return best; } - let count = poly.len(); - for i in 0..count { - let (Some(&p), Some(&q)) = (poly.get(i), poly.get((i + 1) % count)) else { continue }; + for (&p, &q) in poly.edges() { let (a, b) = ((p - g).dot(n), (q - g).dot(n)); // Edges wholly outside the band the follower sweeps. if a.min(b) > r || a.max(b) < -r { @@ -167,10 +165,8 @@ pub fn first_contact_along(poly: &[Vec2], g: Vec2, d: Vec2, r: f64, flat: bool) /// The angles in [0, 2π) where an oscillating follower's tip touches the closed polygon `poly`: /// its tip (a roller's centre for `r > 0`) at `arm` from the pivot `pivot`, turned from the angle /// `start` the way `turn` says (+1 counter-clockwise), sorted. -fn touches_turning(poly: &[Vec2], pivot: Vec2, arm: f64, r: f64, start: f64, turn: f64) -> Vec { +fn touches_turning(poly: &Ring, pivot: Vec2, arm: f64, r: f64, start: f64, turn: f64) -> Vec { let tip = |a: f64| pivot + Vec2::from_angle(a) * arm; - let count = poly.len(); - let edge = |i: usize| Some((*poly.get(i)?, *poly.get((i + 1) % count)?)); let mut out = Vec::new(); let mut take = |a: f64, keep: &dyn Fn(Vec2) -> bool| { let turned = (turn * (a - start)).rem_euclid(TAU); @@ -187,7 +183,7 @@ fn touches_turning(poly: &[Vec2], pivot: Vec2, arm: f64, r: f64, start: f64, tur let (base, spread) = (w.angle(), (h / len).clamp(-1.0, 1.0).acos()); vec![base + spread, base - spread] }; - for (p, q) in (0..count).filter_map(edge) { + for (&p, &q) in poly.edges() { let near = dist_to_segment(pivot, p, q); let far = (p - pivot).len().max((q - pivot).len()); if near > arm + r || far < arm - r { @@ -216,19 +212,17 @@ fn touches_turning(poly: &[Vec2], pivot: Vec2, arm: f64, r: f64, start: f64, tur /// Whether an oscillating follower's tip, turned `turned` from `start` the way `turn` says, /// overlaps the profile by more than `slack`. -fn overlaps_turning(poly: &[Vec2], pivot: Vec2, arm: f64, r: f64, (start, turn): (f64, f64), turned: f64, slack: f64) -> bool { +fn overlaps_turning(poly: &Ring, pivot: Vec2, arm: f64, r: f64, (start, turn): (f64, f64), turned: f64, slack: f64) -> bool { let at = pivot + Vec2::from_angle(start + turn * turned) * arm; - let n = poly.len(); - let gap = - (0..n).filter_map(|i| Some((*poly.get(i)?, *poly.get((i + 1) % n)?))).map(|(p, q)| dist_to_segment(at, p, q)).fold(f64::INFINITY, f64::min); + let gap = poly.edges().map(|(p, q)| dist_to_segment(at, *p, *q)).fold(f64::INFINITY, f64::min); // Inside counts only clear of the boundary: a knife on an edge touches it. - gap < r - slack || (gap > slack && inside(poly, at)) + gap < r - slack || (gap > slack && poly.contains(at)) } /// Where an oscillating follower first touches the closed polygon `poly` turning from `start` /// (the angle it turns through, in (0, 2π)): see `touches_turning`. `None` when it misses the /// profile or starts on it. -pub fn first_contact_turning(poly: &[Vec2], pivot: Vec2, arm: f64, r: f64, start: f64, turn: f64) -> Option { +pub fn first_contact_turning(poly: &Ring, pivot: Vec2, arm: f64, r: f64, start: f64, turn: f64) -> Option { if overlaps_turning(poly, pivot, arm, r, (start, turn), 0.0, -f64::EPSILON) { return None; } @@ -239,7 +233,7 @@ pub fn first_contact_turning(poly: &[Vec2], pivot: Vec2, arm: f64, r: f64, start /// after the cam turned on a little: pushed back to where the profile now lets it be when its tip /// overlaps the profile (by more than `slack`), else on to where it next touches. It stays on the /// part of the profile it rides, however the profile crosses its tip's circle elsewhere. -pub fn next_contact_turning(poly: &[Vec2], pivot: Vec2, arm: f64, r: f64, (start, turn): (f64, f64), from: f64, slack: f64) -> Option { +pub fn next_contact_turning(poly: &Ring, pivot: Vec2, arm: f64, r: f64, (start, turn): (f64, f64), from: f64, slack: f64) -> Option { let touches = touches_turning(poly, pivot, arm, r, start, turn); // A touch where the tip is clear of the rest of the profile (a roller inside the profile is a // radius from the parallels of the edges near the one it overlaps too). @@ -257,23 +251,10 @@ fn dist_to_segment(x: Vec2, p: Vec2, q: Vec2) -> f64 { x.dist(p + d * t) } -/// Even-odd containment in a closed polygon. -fn inside(poly: &[Vec2], x: Vec2) -> bool { - let n = poly.len(); - let mut inside = false; - for i in 0..n { - let (Some(a), Some(b)) = (poly.get(i), poly.get((i + 1) % n)) else { continue }; - if (a.y > x.y) != (b.y > x.y) && x.x < a.x + (x.y - a.y) / (b.y - a.y) * (b.x - a.x) { - inside = !inside; - } - } - inside -} - /// Everything a cam's table is worked out from, in the cam's fixed frame C. struct Setup { /// The profile at cam value 0. - poly: Vec, + poly: Ring, /// +1 when the cam turns by +value about C's z (it is the joint's b side), −1 otherwise. turn: f64, /// A translating follower's line (a point and its unit direction, the slider's +z), or an @@ -517,19 +498,11 @@ fn sampled(lp: &solidcraft_geom::Loop2, tol: f64) -> Option> { /// The diagonal of the box around some points (0 for none). fn extent<'a>(pts: impl Iterator) -> f64 { - let (lo, hi) = pts.fold((Vec3::new(f64::MAX, f64::MAX, f64::MAX), Vec3::new(f64::MIN, f64::MIN, f64::MIN)), |(lo, hi), p| { - (Vec3::new(lo.x.min(p.x), lo.y.min(p.y), lo.z.min(p.z)), Vec3::new(hi.x.max(p.x), hi.y.max(p.y), hi.z.max(p.z))) - }); - if lo.x <= hi.x { (hi - lo).len() } else { 0.0 } + pts.copied().collect::().diagonal() } fn bounds_2d(pts: &[Vec2]) -> f64 { - let (mut lo, mut hi) = (Vec2::new(f64::MAX, f64::MAX), Vec2::new(f64::MIN, f64::MIN)); - for p in pts { - lo = Vec2::new(lo.x.min(p.x), lo.y.min(p.y)); - hi = Vec2::new(hi.x.max(p.x), hi.y.max(p.y)); - } - if lo.x <= hi.x { (hi - lo).len() } else { 0.0 } + pts.iter().copied().collect::().diagonal() } /// The chord error a profile is sampled to: 0.1 µm per 100 mm of its size, at least 0.1 µm. @@ -569,7 +542,7 @@ fn setup(doc: &Document, st: &ModelState, l: &MotionLink, c: &Cam) -> Result 1e-6 * size + 1e-9) { return Err(bad("the profile must lie in a plane square to the cam's axis")); } - let poly: Vec = v.iter().map(|p| Vec2::new(p.x, p.y)).collect(); + let poly: Ring = v.iter().map(|p| Vec2::new(p.x, p.y)).collect(); if !poly.iter().all(|p| p.is_finite()) || area(&poly).abs() <= 1e-12 * size * size { return Err(bad("the profile encloses no area")); } @@ -709,9 +682,9 @@ fn follower_is_b(doc: &Document, cam_joint: &super::Joint, fol: &super::Joint, ( /// A polygon's signed area, from its first point (so a small profile far from the axis keeps its /// digits). -fn area(poly: &[Vec2]) -> f64 { - let (n, o) = (poly.len(), poly.first().copied().unwrap_or(Vec2::ZERO)); - (0..n).filter_map(|i| Some((*poly.get(i)? - o).cross(*poly.get((i + 1) % n)? - o))).sum::() / 2.0 +fn area(poly: &Ring) -> f64 { + let o = poly.first().copied().unwrap_or(Vec2::ZERO); + poly.edges().map(|(p, q)| (*p - o).cross(*q - o)).sum::() / 2.0 } /// The follower's places at the samples 0 ..= `CAM_SAMPLES` of a turn, `place(u, prev)` giving @@ -816,7 +789,7 @@ mod tests { use super::*; /// A circle of radius `r` about `c` as a polygon of `n` points (its sag is r·(1 − cos π/n)). - fn circle(c: Vec2, r: f64, n: usize) -> Vec { + fn circle(c: Vec2, r: f64, n: usize) -> Ring { (0..n).map(|k| c + Vec2::from_angle(TAU * k as f64 / n as f64) * r).collect() } @@ -874,10 +847,9 @@ mod tests { } // Followed on from where it touches, it stays on the part of the profile it rides: a C // whose two arms both cross the tip's circle, the tip resting on the second arm. - let c: Vec = [(-10.0, 20.0), (30.0, 20.0), (30.0, 14.0), (-4.0, 14.0), (-4.0, -14.0), (30.0, -14.0), (30.0, -20.0), (-10.0, -20.0)] - .into_iter() - .map(|(x, y)| Vec2::new(x, y)) - .collect(); + let c = Ring::from( + [[-10.0, 20.0], [30.0, 20.0], [30.0, 14.0], [-4.0, 14.0], [-4.0, -14.0], [30.0, -14.0], [30.0, -20.0], [-10.0, -20.0]].map(Vec2::from), + ); let (pv, l) = (Vec2::new(40.0, 0.0), 22.0); let touches = touches_turning(&c, pv, l, 0.0, 0.0, 1.0); let on = |t: f64| (pv + Vec2::from_angle(t) * l).y; @@ -887,12 +859,12 @@ mod tests { let stay = next_contact_turning(&c, pv, l, 0.0, (0.0, 1.0), second, 1e-9).unwrap_or(f64::NAN); assert!((stay - second).abs() < 1e-12, "{stay} vs {second}"); // A knife on an edge touches it, it doesn't overlap it; just inside, it does. - let square: Vec = [(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)].into_iter().map(|(x, y)| Vec2::new(x, y)).collect(); + let square = Ring::from([[-1.0, -1.0], [1.0, -1.0], [1.0, 1.0], [-1.0, 1.0]].map(Vec2::from)); let (pv, l) = (Vec2::new(0.0, -4.0), 3.0); let up = std::f64::consts::FRAC_PI_2; assert!(!overlaps_turning(&square, pv, l, 0.0, (up, 1.0), 0.0, 1e-9)); assert!(overlaps_turning(&square, pv, l + 0.01, 0.0, (up, 1.0), 0.0, 1e-9)); - assert!((area(&square.iter().map(|p| *p * 0.004 + Vec2::new(524_288.0, 524_288.0)).collect::>()) - 6.4e-5).abs() < 1e-12); + assert!((area(&square.iter().map(|p| *p * 0.004 + Vec2::new(524_288.0, 524_288.0)).collect::>()) - 6.4e-5).abs() < 1e-12); // An arm that can't reach, and one that starts on the cam. let poly = circle(Vec2::new(e, 0.0), r, 512); assert_eq!(first_contact_turning(&poly, pivot, 5.0, 0.0, start, 1.0), None); @@ -903,7 +875,7 @@ mod tests { /// comes back after the turn: refused. On the eccentric circle it follows smoothly. #[test] fn a_follower_that_jumps_is_refused() { - let arm_round = |poly: &[Vec2], pivot: Vec2, arm: f64| { + let arm_round = |poly: &Ring, pivot: Vec2, arm: f64| { let start = pivot.angle(); let place = |u: f64, prev: Option| -> Result { let q = -TAU * u / CAM_SAMPLES as f64; @@ -916,7 +888,7 @@ mod tests { }; round(&place, true, 1e-6) }; - let lobes: Vec = (0..240) + let lobes: Ring = (0..240) .map(|k| { let t = TAU * f64::from(k) / 240.0; Vec2::from_angle(t) * (28.0 + 2.0 / 3.0 + 13.0 * (3.0 * t).cos()) diff --git a/crates/doc/src/naming.rs b/crates/doc/src/naming.rs index 6b1f302eb..263b4bb6b 100644 --- a/crates/doc/src/naming.rs +++ b/crates/doc/src/naming.rs @@ -17,7 +17,7 @@ use std::sync::{Arc, OnceLock}; -use solidcraft_geom::{Mesh, Seg2, Vec2, Vec3}; +use solidcraft_geom::{Aabb3, Mesh, Seg2, Vec2, Vec3}; use crate::history_names::Names; use crate::lineage::Lineage; @@ -156,20 +156,16 @@ pub(crate) fn closest(p: Vec3, a: Vec3, b: Vec3, c: Vec3) -> Vec3 { /// A body's faces as triangle lists with bounding boxes, for "does this point lie on face f". struct FaceIndex { - faces: Vec<(Vec3, Vec3, Vec<[Vec3; 3]>)>, + faces: Vec<(Aabb3, Vec<[Vec3; 3]>)>, } impl FaceIndex { fn new(m: &Mesh, nf: usize) -> FaceIndex { - let mut faces: Vec<(Vec3, Vec3, Vec<[Vec3; 3]>)> = - vec![(Vec3::new(f64::MAX, f64::MAX, f64::MAX), Vec3::new(f64::MIN, f64::MIN, f64::MIN), Vec::new()); nf]; + let mut faces: Vec<(Aabb3, Vec<[Vec3; 3]>)> = vec![(Aabb3::EMPTY, Vec::new()); nf]; for (t, f) in m.triangles.iter().zip(&m.tri_face) { if let (Some(slot), Some(tri)) = (faces.get_mut(*f as usize), m.tri(t)) { - for p in tri { - slot.0 = Vec3::new(slot.0.x.min(p.x), slot.0.y.min(p.y), slot.0.z.min(p.z)); - slot.1 = Vec3::new(slot.1.x.max(p.x), slot.1.y.max(p.y), slot.1.z.max(p.z)); - } - slot.2.push(tri); + slot.0.extend(tri); + slot.1.push(tri); } } FaceIndex { faces } @@ -178,8 +174,8 @@ impl FaceIndex { /// The face a point lies on (within `tol`). fn face_at(&self, p: Vec3, tol: f64) -> Option { let mut best: Option<(f64, usize)> = None; - for (i, (lo, hi, tris)) in self.faces.iter().enumerate() { - if p.x < lo.x - tol || p.y < lo.y - tol || p.z < lo.z - tol || p.x > hi.x + tol || p.y > hi.y + tol || p.z > hi.z + tol { + for (i, (bounds, tris)) in self.faces.iter().enumerate() { + if !bounds.inflated(tol).contains(p) { continue; } let d = tris.iter().map(|[a, b, c]| closest(p, *a, *b, *c).dist(p)).fold(f64::MAX, f64::min); @@ -392,7 +388,7 @@ fn behind(ps: &[Vec3], ns: &[Vec3], inputs: &[(&ModelBody, FaceIndex, Arc = None; for (_, idx, nm) in inputs { - for (fi, (_, _, tris)) in idx.faces.iter().enumerate() { + for (fi, (_, tris)) in idx.faces.iter().enumerate() { for [a, b, c] in tris { if let Some(t) = ray_hit(*p, d, *a, *b, *c) && t > 1e-9 @@ -497,10 +493,7 @@ fn number_pieces(names: &mut [String], pts: &[Vec], mark: char) { ps.iter().fold(Vec3::ZERO, |a, p| a + *p) * (1.0 / ps.len().max(1) as f64) }; let cs: Vec<(usize, Vec3)> = same.iter().map(|j| (*j, centre(*j))).collect(); - let (lo, hi) = cs.iter().fold((Vec3::new(f64::MAX, f64::MAX, f64::MAX), Vec3::new(f64::MIN, f64::MIN, f64::MIN)), |(l, h), (_, c)| { - (Vec3::new(l.x.min(c.x), l.y.min(c.y), l.z.min(c.z)), Vec3::new(h.x.max(c.x), h.y.max(c.y), h.z.max(c.z))) - }); - let ext = hi - lo; + let ext = cs.iter().map(|(_, c)| *c).collect::().size(); let key = |c: Vec3| { if ext.x >= ext.y && ext.x >= ext.z { (c.x, c.y, c.z) diff --git a/crates/doc/src/project.rs b/crates/doc/src/project.rs index 9c115c3d2..a71f4a4d5 100644 --- a/crates/doc/src/project.rs +++ b/crates/doc/src/project.rs @@ -767,14 +767,13 @@ fn merge_split_circles(geom: Vec) -> Vec { const TOL: f64 = 1e-6; let near = |p: Vec2, q: Vec2| p.dist(q) <= TOL * (1.0 + p.len().max(q.len())); let mut out = geom.clone(); - for i in 0..geom.len() { - let Some(LinkGeom::Arc { c, a, b }) = geom.get(i).cloned() else { continue }; - for j in i + 1..geom.len() { - if let Some(LinkGeom::Arc { c: c2, a: a2, b: b2 }) = geom.get(j).cloned() + for (i, first) in geom.iter().enumerate() { + let LinkGeom::Arc { c, a, b } = *first else { continue }; + for (second, slot) in geom.iter().zip(out.iter_mut()).skip(i + 1) { + if let LinkGeom::Arc { c: c2, a: a2, b: b2 } = *second && near(c, c2) && near(a, a2) && near(b, b2) - && let Some(slot) = out.get_mut(j) { *slot = LinkGeom::Arc { c, a: b, b: a }; } diff --git a/crates/doc/src/project_order.rs b/crates/doc/src/project_order.rs index d98164d1c..2964468c1 100644 --- a/crates/doc/src/project_order.rs +++ b/crates/doc/src/project_order.rs @@ -3,7 +3,7 @@ use std::collections::{BTreeMap, BTreeSet}; -use solidcraft_geom::{Mesh, Plane, Vec3}; +use solidcraft_geom::{Aabb3, Mesh, Plane, Vec3}; use crate::{DocError, Result}; @@ -68,9 +68,8 @@ fn boundary_edges(mesh: &Mesh, mut edges: Vec, faces: &BTreeSet, p } let geometry_key = |e: usize| { let pts = mesh.edges.get(e).map(Vec::as_slice).unwrap_or_default(); - let lo = pts.iter().copied().fold(Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY), Vec3::min); - let hi = pts.iter().copied().fold(Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY), Vec3::max); - (key(lo), key(hi)) + let b: Aabb3 = pts.iter().copied().collect(); + (key(b.min), key(b.max)) }; edges.sort_by_key(|e| geometry_key(*e)); let mut at: BTreeMap> = BTreeMap::new(); diff --git a/crates/doc/src/sheet.rs b/crates/doc/src/sheet.rs index c59b150ae..d3e5c82ce 100644 --- a/crates/doc/src/sheet.rs +++ b/crates/doc/src/sheet.rs @@ -10,7 +10,7 @@ //! together; the flat solid is the outline extruded through the thickness. use serde::{Deserialize, Serialize}; -use solidcraft_geom::{LINEAR_TOL, Loop2, Plane, Region2, Seg2, Vec2, Vec3}; +use solidcraft_geom::{Aabb2, LINEAR_TOL, Loop2, Plane, Region2, Ring, Seg2, Vec2, Vec3}; use solidcraft_kernel::{self as kernel, Body, EdgeSpec, FaceSpec, SurfSpec}; use crate::expr::{self, Kind, Value}; @@ -62,7 +62,7 @@ impl FlatWork { } } -fn flat_polyline(lp: &Loop2) -> Result> { +fn flat_polyline(lp: &Loop2) -> Result> { if lp.segs.len() > MAX_FLAT_POINTS { return Err(flat_budget_error()); } @@ -75,7 +75,7 @@ fn flat_polyline(lp: &Loop2) -> Result> { } points.extend(p.iter().take(add)); } - Ok(points) + Ok(Ring::new(points)) } fn flat_points(polys: &[Vec]) -> Result { @@ -181,17 +181,13 @@ fn regions_complexity<'a>(regions: impl Iterator) -> Result< /// them (the result is the same: a cut-out clear of a tool's box can't change what it meets). pub(crate) struct NearHoles<'a> { region: &'a Region2, - boxes: Vec<(Vec2, Vec2)>, + boxes: Vec, } /// A loop's bounding box, a little larger than its chords so arcs stay inside. -fn loop_box(lp: &Loop2) -> Result<(Vec2, Vec2)> { - let pts = flat_polyline(lp)?; - let (lo, hi) = pts.iter().fold((Vec2::new(f64::MAX, f64::MAX), Vec2::new(f64::MIN, f64::MIN)), |(lo, hi), p| { - (Vec2::new(lo.x.min(p.x), lo.y.min(p.y)), Vec2::new(hi.x.max(p.x), hi.y.max(p.y))) - }); - let pad = 1e-3 + 1e-9 * (lo.x.abs() + lo.y.abs() + hi.x.abs() + hi.y.abs()); - Ok((lo - Vec2::new(pad, pad), hi + Vec2::new(pad, pad))) +fn loop_box(lp: &Loop2) -> Result { + let b = flat_polyline(lp)?.bounds(); + Ok(b.inflated(1e-3 + 1e-9 * (b.min.x.abs() + b.min.y.abs() + b.max.x.abs() + b.max.y.abs()))) } impl<'a> NearHoles<'a> { @@ -204,15 +200,8 @@ impl<'a> NearHoles<'a> { if self.region.holes.is_empty() { return Ok(self.region.clone()); } - let (lo, hi) = loop_box(&tool.outer)?; - let holes = self - .region - .holes - .iter() - .zip(&self.boxes) - .filter(|(_, (a, b))| a.x <= hi.x && b.x >= lo.x && a.y <= hi.y && b.y >= lo.y) - .map(|(h, _)| h.clone()) - .collect(); + let near = loop_box(&tool.outer)?; + let holes = self.region.holes.iter().zip(&self.boxes).filter(|(_, b)| b.meets(&near)).map(|(h, _)| h.clone()).collect(); Ok(Region2 { outer: self.region.outer.clone(), holes }) } } @@ -599,7 +588,9 @@ fn bezier_at(c: &[Vec3], t: f64) -> Vec3 { w.first().copied().unwrap_or(Vec3::ZERO) } -fn dedup(p: &[Vec2]) -> Vec { +/// `p` without repeated points: a point on the one before it goes, and so does a last point back +/// on the first. +fn dedup(p: &Ring) -> Ring { let mut v: Vec = Vec::new(); for q in p { if v.last().is_none_or(|l| l.dist(*q) > 1e-9) { @@ -609,7 +600,7 @@ fn dedup(p: &[Vec2]) -> Vec { if v.len() > 1 && v.first().zip(v.last()).is_some_and(|(a, b)| a.dist(*b) < 1e-9) { v.pop(); } - v + Ring::new(v) } /// How a flat edge of a bend zone folds: along the bend to a line, across it to an arc, or @@ -757,7 +748,7 @@ struct Corner { /// The corners of a straight-edged region (counter-clockwise). fn corners_of(r: &Region2) -> Vec { - dedup(&r.outer.ccw().polyline(1e-3)) + dedup(&r.outer.ccw().polyline(1e-3)).into_vec() } /// A corner relief planned but not yet cut (see [`SheetBody::plan_relief`]): the corner it is @@ -1174,13 +1165,8 @@ impl SheetBody { // Each piece meets only the cut-outs near it: arranging every cut-out of the sheet (a // label's letters on its base) against each flange and bend zone too would charge the // budget for all of them once per piece. - let (lo, hi) = loop_box(&panel.outer)?; - let near: Vec = cuts - .iter() - .zip(&cut_boxes) - .filter(|(_, (a, b))| a.x <= hi.x && b.x >= lo.x && a.y <= hi.y && b.y >= lo.y) - .map(|(c, _)| c.clone()) - .collect(); + let panel_box = loop_box(&panel.outer)?; + let near: Vec = cuts.iter().zip(&cut_boxes).filter(|(_, b)| b.meets(&panel_box)).map(|(c, _)| c.clone()).collect(); let material = if near.is_empty() { vec![panel] } else { material_boolean(&[panel], &near, kernel::BoolOp::Cut, work)? }; for region in material { points = points.saturating_add(region_complexity(std::slice::from_ref(®ion))?.1); @@ -1708,14 +1694,11 @@ impl SheetBody { .labels .iter() .map(|r| { - let (mut lo, mut hi) = (Vec2::new(f64::MAX, f64::MAX), Vec2::new(f64::MIN, f64::MIN)); - for p in r.outer.polyline(1e-3) { - lo = Vec2::new(lo.x.min(p.x), lo.y.min(p.y)); - hi = Vec2::new(hi.x.max(p.x), hi.y.max(p.y)); - } // A polyline of 0.001 mm chords is within 0.001 mm of the curve. - let pad = Vec2::new(0.01, 0.01); - (lo - pad, hi + pad, std::iter::once(&r.outer).chain(&r.holes).flat_map(|lp| lp.segs.iter().copied()).collect()) + ( + r.outer.polyline(1e-3).bounds().inflated(0.01), + std::iter::once(&r.outer).chain(&r.holes).flat_map(|lp| lp.segs.iter().copied()).collect(), + ) }) .collect(); Letters { regions } @@ -1812,19 +1795,18 @@ impl SheetBody { Ok(common.iter().map(Region2::area).sum::() > TOUCH_AREA) }; // The cheap test first: a piece inside another's outline is an island, whatever it holds. - let outlines: Vec<(Vec, Vec2, Vec2)> = after + let outlines: Vec<(Ring, Aabb2)> = after .iter() .map(|r| { let pts = r.outer.polyline(1e-3); - let lo = pts.iter().fold(Vec2::new(f64::MAX, f64::MAX), |a, p| Vec2::new(a.x.min(p.x), a.y.min(p.y))); - let hi = pts.iter().fold(Vec2::new(f64::MIN, f64::MIN), |a, p| Vec2::new(a.x.max(p.x), a.y.max(p.y))); - (pts, lo, hi) + let b = pts.bounds(); + (pts, b) }) .collect(); let (mut open, mut islands) = (Vec::new(), Vec::new()); for (i, piece) in after.iter().enumerate() { let p = piece.interior_point(); - let inside = |(pts, lo, hi): &(Vec, Vec2, Vec2)| (lo.x..=hi.x).contains(&p.x) && (lo.y..=hi.y).contains(&p.y) && point_in(pts, p); + let inside = |(pts, b): &(Ring, Aabb2)| b.contains(p) && pts.contains(p); if outlines.iter().enumerate().any(|(j, o)| j != i && inside(o)) { islands.push(piece); } else { @@ -1874,11 +1856,11 @@ impl SheetBody { if self.flanges.len().saturating_mul(2).saturating_add(1) > MAX_FLAT_PIECES { return Err(flat_budget_error()); } - let mut polys: Vec> = vec![dedup(&flat_polyline(&self.base.outer.ccw())?)]; + let mut polys: Vec> = vec![dedup(&flat_polyline(&self.base.outer.ccw())?).into_vec()]; for f in &self.flanges { - polys.push(dedup(&flat_polyline(&self.zone(f).outer.ccw())?)); + polys.push(dedup(&flat_polyline(&self.zone(f).outer.ccw())?).into_vec()); if f.leg > 1e-9 { - polys.push(dedup(&flat_polyline(&self.panel(f).outer.ccw())?)); + polys.push(dedup(&flat_polyline(&self.panel(f).outer.ccw())?).into_vec()); } flat_points(&polys)?; } @@ -1940,10 +1922,8 @@ impl SheetBody { let mut segs: Vec<(Vec2, Vec2)> = Vec::new(); let mut add = |l: &Loop2| { let pts = l.polyline(1e-3); - for k in 0..pts.len() { - if let (Some(&a), Some(&b)) = (pts.get(k), pts.get((k + 1) % pts.len())) { - segs.push((a, b)); - } + for (&a, &b) in pts.edges() { + segs.push((a, b)); } }; for r in ®ions { @@ -1951,11 +1931,7 @@ impl SheetBody { r.holes.iter().for_each(&mut add); } zones.iter().for_each(|z| add(&z.outer)); - let (mut lo, mut hi) = (Vec2::new(f64::MAX, f64::MAX), Vec2::new(f64::MIN, f64::MIN)); - for (a, _) in &segs { - lo = Vec2::new(lo.x.min(a.x), lo.y.min(a.y)); - hi = Vec2::new(hi.x.max(a.x), hi.y.max(a.y)); - } + let Aabb2 { min: lo, max: hi } = segs.iter().map(|(a, _)| *a).collect(); if !(lo.x <= hi.x) || !(p.pitch > 0.0) { return Ok(Vec::new()); } @@ -2039,13 +2015,8 @@ impl SheetBody { /// Bounding size of the flat pattern (x, y in the flat frame). pub fn flat_size(&self) -> Result<(f64, f64)> { - let loops: Vec> = self.flat_regions()?.iter().map(|r| r.outer.polyline(1e-3)).collect(); - let (mut lo, mut hi) = (Vec2::new(f64::MAX, f64::MAX), Vec2::new(f64::MIN, f64::MIN)); - for p in loops.iter().flatten() { - lo = Vec2::new(lo.x.min(p.x), lo.y.min(p.y)); - hi = Vec2::new(hi.x.max(p.x), hi.y.max(p.y)); - } - Ok((hi.x - lo.x, hi.y - lo.y)) + let size = self.flat_regions()?.iter().fold(Aabb2::EMPTY, |b, r| b.union(&r.outer.polyline(1e-3).bounds())).size(); + Ok((size.x, size.y)) } /// Panels with their regions and world placements: (flange index or None, region). @@ -2073,7 +2044,7 @@ impl SheetBody { } let q2 = Vec2::new(q.x, q.y); let pts = dedup(&r.outer.ccw().polyline(1e-3)); - if !point_in(&pts, q2) && !near_outline(&pts, q2, TOL) { + if !pts.contains(q2) && !near_outline(&pts, q2, TOL) { continue; } // Panels `before` did not have yet came out of their parent's (bounded walk). @@ -3254,7 +3225,7 @@ impl SheetBody { } let pts = dedup(&r.outer.ccw().polyline(1e-3)); let (a2, b2) = (Vec2::new(fa.x, fa.y), Vec2::new(fb.x, fb.y)); - if point_in(&pts, (a2 + b2) * 0.5) || polys_cross(&pts, &[a2, b2, (a2 + b2) * 0.5]) { + if pts.contains((a2 + b2) * 0.5) || polys_cross(&pts, &[a2, b2, (a2 + b2) * 0.5]) { found = Some((pi, inv, a2, b2, pts)); break; } @@ -3283,20 +3254,10 @@ impl SheetBody { let q2 = Vec2::new(q.x, q.y); // A point in the panel's slab must be on material: inside the outline and // outside every cut-out (a side face of either counts as material). - let near = |poly: &[Vec2]| { - let m = poly.len(); - (0..m).any(|i| match (poly.get(i), poly.get((i + 1) % m)) { - (Some(&a), Some(&b)) => { - let d = b - a; - let t = if d.len2() > 1e-18 { ((q2 - a).dot(d) / d.len2()).clamp(0.0, 1.0) } else { 0.0 }; - (a + d * t).dist(q2) < 1e-3 - } - _ => false, - }) - }; + let near = |poly: &Ring| near_outline(poly, q2, 1e-3); let in_slab = q.z > -1e-4 && q.z < self.t + 1e-4; let in_hole = self.holes.iter().any(|h| h.contains(q2) && !near(&h.outer.ccw().polyline(1e-3))); - if in_slab && ((!point_in(&pts, q2) && !near(&pts)) || in_hole) { + if in_slab && ((!pts.contains(q2) && !near(&pts)) || in_hole) { *warning = Some(format!("{FOLD_FIXED_OFF_SHEET} at ({:.3}, {:.3}, {:.3}); the side of the fold line it lies on stays", p.x, p.y, p.z)); } @@ -3476,11 +3437,11 @@ impl SheetBody { // What stays: the panel short of the zone plus the zone pieces (and what hangs from // them) that don't fold. let mut keep = vec![clip(pts, n * s0, n * -1.0)]; - for i in 0..strips.len() { + for (i, strip) in strips.iter().enumerate() { if chosen.contains(&i) { continue; } - keep.extend(strips.get(i).cloned()); + keep.push(strip.clone()); keep.extend(hangs.get(i).into_iter().flatten().filter_map(|&k| beyond.get(k).cloned())); } let fixed = match merge_loops(&keep, &mut work)?.as_slice() { @@ -3503,8 +3464,7 @@ impl SheetBody { } // Flanges already on this panel: those beyond a folding tab move with it. let mut moves = Vec::new(); - for k in 0..self.flanges.len() { - let Some(f) = self.flanges.get(k) else { continue }; + for (k, f) in self.flanges.iter().enumerate() { if f.parent != panel { continue; } @@ -3683,9 +3643,7 @@ impl SheetBody { let mut out = Vec::new(); for (pi, region) in self.panels() { let pts = dedup(®ion.outer.ccw().polyline(1e-3)); - let m = pts.len(); - for i in 0..m { - let (Some(&a), Some(&b)) = (pts.get(i), pts.get((i + 1) % m)) else { continue }; + for (i, (&a, &b)) in pts.edges().enumerate() { if a.dist(b) < 1e-9 { continue; } @@ -3920,18 +3878,6 @@ impl SheetBody { } } -fn point_in(poly: &[Vec2], p: Vec2) -> bool { - let mut inside = false; - let m = poly.len(); - for i in 0..m { - let (Some(&a), Some(&b)) = (poly.get(i), poly.get((i + m - 1) % m)) else { continue }; - if (a.y > p.y) != (b.y > p.y) && p.x < (b.x - a.x) * (p.y - a.y) / (b.y - a.y) + a.x { - inside = !inside; - } - } - inside -} - /// The boundary of a union of counter-clockwise polygons that meet edge to edge: edges are /// split where corners touch them, edges running both ways cancel, the rest chain into loops /// (outer loops counter-clockwise, holes clockwise; straight runs merged). @@ -4015,15 +3961,11 @@ fn merge_loops(polys: &[Vec], work: &mut FlatWork) -> Result } /// Whether `q` lies within `tol` of the closed polygon `poly`'s outline. -fn near_outline(poly: &[Vec2], q: Vec2, tol: f64) -> bool { - let m = poly.len(); - (0..m).any(|i| match (poly.get(i), poly.get((i + 1) % m)) { - (Some(&a), Some(&b)) => { - let d = b - a; - let t = if d.len2() > 1e-18 { ((q - a).dot(d) / d.len2()).clamp(0.0, 1.0) } else { 0.0 }; - (a + d * t).dist(q) < tol - } - _ => false, +fn near_outline(poly: &Ring, q: Vec2, tol: f64) -> bool { + poly.edges().any(|(&a, &b)| { + let d = b - a; + let t = if d.len2() > 1e-18 { ((q - a).dot(d) / d.len2()).clamp(0.0, 1.0) } else { 0.0 }; + (a + d * t).dist(q) < tol }) } @@ -4077,19 +4019,9 @@ fn clear_of(a: Vec2, d: Vec2, len: f64, cuts: &[Region2]) -> Vec<(f64, f64)> { return Vec::new(); } let b = a + d * len; - let (lo, hi) = (Vec2::new(a.x.min(b.x) - 1e-6, a.y.min(b.y) - 1e-6), Vec2::new(a.x.max(b.x) + 1e-6, a.y.max(b.y) + 1e-6)); + let line = Aabb2 { min: Vec2::new(a.x.min(b.x), a.y.min(b.y)), max: Vec2::new(a.x.max(b.x), a.y.max(b.y)) }.inflated(1e-6); // Only cut-outs whose box the line enters can hold or cross it. - let near: Vec<&Region2> = cuts - .iter() - .filter(|r| { - let pts = r.outer.polyline(1e-3); - let (mut p0, mut p1) = (Vec2::new(f64::MAX, f64::MAX), Vec2::new(f64::MIN, f64::MIN)); - for p in &pts { - (p0, p1) = (Vec2::new(p0.x.min(p.x), p0.y.min(p.y)), Vec2::new(p1.x.max(p.x), p1.y.max(p.y))); - } - p0.x <= hi.x && lo.x <= p1.x && p0.y <= hi.y && lo.y <= p1.y - }) - .collect(); + let near: Vec<&Region2> = cuts.iter().filter(|r| r.outer.polyline(1e-3).bounds().meets(&line)).collect(); let mut at = vec![0.0, len]; for e in near.iter().flat_map(|r| std::iter::once(&r.outer).chain(&r.holes)).flat_map(|l| &l.segs) { line_hits(a, d, e, &mut at); @@ -4242,8 +4174,8 @@ pub fn loop_lies_on(lp: &Loop2, curves: &[Seg2]) -> bool { /// Tells which loops of a sheet's flat pattern are letters (see [`SheetBody::letters`]). #[derive(Clone, Debug)] pub struct Letters { - /// Each text region's corners (lowest, highest) and the segments of its outlines. - regions: Vec<(Vec2, Vec2, Vec)>, + /// Each text region's box and the segments of its outlines. + regions: Vec<(Aabb2, Vec)>, } impl Letters { @@ -4251,7 +4183,7 @@ impl Letters { /// counters. pub fn is_letter(&self, lp: &Loop2) -> bool { let Some(p) = lp.segs.first().map(Seg2::start) else { return false }; - self.regions.iter().any(|(lo, hi, curves)| p.x >= lo.x && p.x <= hi.x && p.y >= lo.y && p.y <= hi.y && loop_lies_on(lp, curves)) + self.regions.iter().any(|(b, curves)| b.contains(p) && loop_lies_on(lp, curves)) } } diff --git a/crates/doc/src/sheet_convert.rs b/crates/doc/src/sheet_convert.rs index f64dc4f36..9628047ff 100644 --- a/crates/doc/src/sheet_convert.rs +++ b/crates/doc/src/sheet_convert.rs @@ -50,10 +50,10 @@ use std::collections::BTreeMap; use std::f64::consts::{FRAC_PI_2, PI, TAU}; -use solidcraft_geom::{Loop2, Mesh, Plane, Region2, Seg2, UnitVec3, Vec2, Vec3}; +use solidcraft_geom::{Loop2, Mesh, Plane, Region2, Ring, Seg2, UnitVec3, Vec2, Vec3}; use solidcraft_kernel::{Body, FaceSurface, face_surface}; -use super::{FlatWork, ReliefOverride, RuleValues, SheetBody, SheetFlange, base_flange, point_in, polys_cross, signed_area, snap}; +use super::{FlatWork, ReliefOverride, RuleValues, SheetBody, SheetFlange, base_flange, polys_cross, signed_area, snap}; use crate::{DocError, ModelBody, Result, apply_point, mat_inverse}; const MAX_BENDS: usize = 1000; @@ -788,7 +788,8 @@ pub fn convert_body(mb: &ModelBody, rule: &str, rv: &RuleValues, face: Vec3, ben } // The flat frame: on the fixed face, x along its longest edge, z into the material. let Some(base) = panels.get(&f0) else { return err("fixed face") }; - let corners = base.face.pts.iter().zip(base.face.pts.iter().cycle().skip(1)); + let base_ring = Ring::from(base.face.pts.clone()); + let corners = base_ring.edges(); let straight = corners.zip(&base.face.round).filter(|(_, r)| r.is_none()).map(|(c, _)| c); let longest = straight.max_by(|x, y| x.0.dist(*x.1).total_cmp(&y.0.dist(*y.1))); let frame = longest @@ -889,7 +890,7 @@ pub fn convert_body(mb: &ModelBody, rule: &str, rv: &RuleValues, face: Vec3, ben }; let back = skin_behind.get(&pf).and_then(|g| outline(b, &mesh, *g, tol).ok()); let skins: Vec<(&Face, bool)> = std::iter::once((&panel.face, true)).chain(back.as_ref().map(|f| (f, false))).collect(); - let bound = if skins.iter().all(|(f, _)| f.holes.is_empty()) { Vec::new() } else { region.outer.ccw().polyline(1e-3) }; + let bound = if skins.iter().all(|(f, _)| f.holes.is_empty()) { Ring::default() } else { region.outer.ccw().polyline(1e-3) }; for (face, front) in skins { for (h, walls) in &face.holes { let p = face.plane.to_world(h.centroid()); @@ -900,7 +901,7 @@ pub fn convert_body(mb: &ModelBody, rule: &str, rv: &RuleValues, face: Vec3, ben } let cut = sh.region_to_flat(fl, &face.plane, &Region2 { outer: h.clone(), holes: Vec::new() })?; let ring = cut.outer.polyline(1e-3); - if !ring.iter().all(|q| point_in(&bound, *q)) || polys_cross(&bound, &ring) { + if !ring.iter().all(|q| bound.contains(*q)) || polys_cross(&bound, &ring) { let kind = if through { "hole" } else { "pocket" }; return err(format!("not supported yet: the {kind} at {} reaches into a bend (cut it after converting)", at(p))); } diff --git a/crates/engine/src/cmd/component_properties.rs b/crates/engine/src/cmd/component_properties.rs index d26e89000..764afed3c 100644 --- a/crates/engine/src/cmd/component_properties.rs +++ b/crates/engine/src/cmd/component_properties.rs @@ -1,7 +1,7 @@ //! Physical properties of an assembly placement, with original body material assignments. use serde_json::{Value, json}; use solidcraft_doc::{Document, Mat}; -use solidcraft_geom::Vec3; +use solidcraft_geom::{Aabb3, Vec3}; use crate::params::bad; use crate::{Result, Session}; @@ -90,8 +90,7 @@ fn properties(s: &Session, doc: &Document, selected: &[u64], descendants: bool, let mut bodies = Vec::new(); let (mut volume, mut area, mut mass) = (0.0, 0.0, 0.0); let mut moment = Vec3::ZERO; - let (mut min, mut max) = - (Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY), Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY)); + let mut bounds = Aabb3::EMPTY; let (mut faces, mut edges, mut vertices) = (0, 0, 0); let mut placement_count = 0; let selected_placements = if selected.is_empty() { @@ -126,8 +125,7 @@ fn properties(s: &Session, doc: &Document, selected: &[u64], descendants: bool, area += measured.area; mass += body_mass; moment += measured.centroid * body_mass; - min = Vec3::new(min.x.min(measured.bbox.min.x), min.y.min(measured.bbox.min.y), min.z.min(measured.bbox.min.z)); - max = Vec3::new(max.x.max(measured.bbox.max.x), max.y.max(measured.bbox.max.y), max.z.max(measured.bbox.max.z)); + bounds = bounds.union(&measured.bbox); faces += measured.merged.faces; edges += measured.merged.edges; vertices += measured.merged.vertices; @@ -145,7 +143,7 @@ fn properties(s: &Session, doc: &Document, selected: &[u64], descendants: bool, if centroid.is_some_and(|point| !point.is_finite()) { return Err(bad(cmd, "center of mass exceeds supported numeric range")); } - let bbox = if bodies.is_empty() { Value::Null } else { json!({"min": min, "max": max}) }; + let bbox = if bodies.is_empty() { Value::Null } else { json!({"min": bounds.min, "max": bounds.max}) }; Ok(json!({"path": selected, "coordinate_frame": "world", "descendants": descendants, "placement_count": placement_count, "body_count": bodies.len(), "bodies": bodies, "total": {"volume_mm3": volume, "area_mm2": area, "mass_g": mass, diff --git a/crates/engine/src/cmd/motion.rs b/crates/engine/src/cmd/motion.rs index d84ccb75b..d83094a84 100644 --- a/crates/engine/src/cmd/motion.rs +++ b/crates/engine/src/cmd/motion.rs @@ -6,7 +6,7 @@ use serde_json::{Value, json}; use solidcraft_doc::Mat; use solidcraft_doc::joints::{self, JointKind}; use solidcraft_doc::motion::{ContactSet, ExplodedView, MotionStudy, StudyKey}; -use solidcraft_geom::Vec3; +use solidcraft_geom::{Aabb3, Vec3}; use solidcraft_kernel::Body; use super::CommandSpec; @@ -904,16 +904,14 @@ fn centres(s: &Session) -> Vec<(u64, Vec3)> { let bodies = placed(s); let mut out = Vec::new(); for o in s.doc.occurrences.iter().filter(|o| o.parent == 0) { - let (mut lo, mut hi) = (Vec3::new(f64::MAX, f64::MAX, f64::MAX), Vec3::new(f64::MIN, f64::MIN, f64::MIN)); + let mut bounds = Aabb3::EMPTY; for (_, b) in bodies.iter().filter(|(path, _)| path.first() == Some(&o.id)) { if let Ok(m) = b.tessellate((b.size() * 1e-2).max(1e-2)) { - let bb = m.bounds(); - lo = Vec3::new(lo.x.min(bb.min.x), lo.y.min(bb.min.y), lo.z.min(bb.min.z)); - hi = Vec3::new(hi.x.max(bb.max.x), hi.y.max(bb.max.y), hi.z.max(bb.max.z)); + bounds = bounds.union(&m.bounds()); } } - if lo.x <= hi.x { - out.push((o.id, (lo + hi) * 0.5)); + if !bounds.is_empty() { + out.push((o.id, bounds.center())); } } out diff --git a/crates/engine/src/cmd/parts.rs b/crates/engine/src/cmd/parts.rs index f2e29caad..5ded0ce29 100644 --- a/crates/engine/src/cmd/parts.rs +++ b/crates/engine/src/cmd/parts.rs @@ -523,13 +523,12 @@ mod tests { fn bbox(s: &Session, prefix: &str) -> (solidcraft_geom::Vec3, solidcraft_geom::Vec3) { let st = s.world_state(); let comp = s.doc.components.iter().find(|c| c.name.starts_with(prefix)).map(|c| c.id).unwrap_or(0); - let (mut lo, mut hi) = (solidcraft_geom::Vec3::new(f64::MAX, f64::MAX, f64::MAX), solidcraft_geom::Vec3::new(f64::MIN, f64::MIN, f64::MIN)); - for b in st.bodies.iter().filter(|b| s.doc.model_body_component(b) == comp) { - let m = b.mesh().bounds(); - lo = solidcraft_geom::Vec3::new(lo.x.min(m.min.x), lo.y.min(m.min.y), lo.z.min(m.min.z)); - hi = solidcraft_geom::Vec3::new(hi.x.max(m.max.x), hi.y.max(m.max.y), hi.z.max(m.max.z)); - } - (lo, hi) + let b = st + .bodies + .iter() + .filter(|b| s.doc.model_body_component(b) == comp) + .fold(solidcraft_geom::Aabb3::EMPTY, |a, b| a.union(&b.mesh().bounds())); + (b.min, b.max) } #[test] diff --git a/crates/engine/src/cmd/sheet.rs b/crates/engine/src/cmd/sheet.rs index 68c56c3ec..58db634ab 100644 --- a/crates/engine/src/cmd/sheet.rs +++ b/crates/engine/src/cmd/sheet.rs @@ -7,7 +7,7 @@ use solidcraft_doc::sheet::{self, SheetBody, SheetRule}; use solidcraft_doc::{BodyName, SketchId}; use solidcraft_doc::{FacePick, Position}; use solidcraft_doc::{FeatureKind, FlangeEdge}; -use solidcraft_geom::{Vec2, Vec3}; +use solidcraft_geom::{Aabb2, Ring, Vec2, Vec3}; use super::CommandSpec; use super::features::{add_feature, check_expr, feature_sketch, profiles, sketch_id}; @@ -494,13 +494,9 @@ fn loop_shape(lp: &solidcraft_geom::Loop2) -> Value { fn flat_json(sh: &SheetBody) -> Result { let regions = sh.flat_regions()?; - let loops: Vec> = regions.iter().map(|r| r.outer.polyline(1e-3)).collect(); - let (mut lo, mut hi) = (Vec2::new(f64::MAX, f64::MAX), Vec2::new(f64::MIN, f64::MIN)); - for p in loops.iter().flatten() { - lo = Vec2::new(lo.x.min(p.x), lo.y.min(p.y)); - hi = Vec2::new(hi.x.max(p.x), hi.y.max(p.y)); - } - let (w, h) = (hi.x - lo.x, hi.y - lo.y); + let loops: Vec> = regions.iter().map(|r| r.outer.polyline(1e-3)).collect(); + let size = loops.iter().fold(Aabb2::EMPTY, |b, l| b.union(&l.bounds())).size(); + let (w, h) = (size.x, size.y); let pt = |v: &Vec2| json!([v.x, v.y]); let outline: Vec = loops.iter().map(|l| Value::Array(l.iter().map(pt).collect())).collect(); let holes: Vec = regions.iter().flat_map(|r| &r.holes).map(|h| Value::Array(h.polyline(1e-3).iter().map(pt).collect())).collect(); diff --git a/crates/engine/src/cmd/sketch_clipboard.rs b/crates/engine/src/cmd/sketch_clipboard.rs index fb9c4d198..a0363bfbc 100644 --- a/crates/engine/src/cmd/sketch_clipboard.rs +++ b/crates/engine/src/cmd/sketch_clipboard.rs @@ -8,7 +8,7 @@ use std::collections::BTreeMap; use serde_json::{Value, json}; -use solidcraft_geom::Vec2; +use solidcraft_geom::{Aabb2, Vec2}; use solidcraft_sketch::{ConstraintKind, CurveKind, LinkKind, LinkSource, Sketch}; use super::sketch::{edit, target_sketch}; @@ -175,12 +175,8 @@ fn copy(s: &mut Session, p: &Value) -> Result { clip.texts.push((src, path)); } // Bounds of everything copied, as drawn. - let mut lo = Vec2::new(f64::INFINITY, f64::INFINITY); - let mut hi = Vec2::new(f64::NEG_INFINITY, f64::NEG_INFINITY); - let mut add = |q: Vec2| { - lo = Vec2::new(lo.x.min(q.x), lo.y.min(q.y)); - hi = Vec2::new(hi.x.max(q.x), hi.y.max(q.y)); - }; + let mut bounds = Aabb2::EMPTY; + let mut add = |q: Vec2| bounds.add(q); let mut drawn: Vec = cs.clone(); for t in &texts { drawn.extend(sk.link_curves(t)); @@ -193,11 +189,12 @@ fn copy(s: &mut Session, p: &Value) -> Result { add(*q); } } - if !(lo.x.is_finite() && hi.x.is_finite()) { + if bounds.is_empty() { return Err(bad(cmd, "nothing to copy")); } - clip.center = (lo + hi) * 0.5; - clip.extent = (hi.x - lo.x).max(hi.y - lo.y); + clip.center = bounds.center(); + let size = bounds.size(); + clip.extent = size.x.max(size.y); let out = json!({ "curves": clip.curves.len() + texts.iter().map(|t| sk.link_curves(t).len()).sum::(), "points": clip.lone.len(), diff --git a/crates/engine/src/cmd/sketch_inspect.rs b/crates/engine/src/cmd/sketch_inspect.rs index 10e63152b..3222e8fc6 100644 --- a/crates/engine/src/cmd/sketch_inspect.rs +++ b/crates/engine/src/cmd/sketch_inspect.rs @@ -2,7 +2,7 @@ //! centre of mass of bodies. use serde_json::{Value, json}; -use solidcraft_geom::{Seg2, Vec2, Vec3}; +use solidcraft_geom::{Aabb3, Seg2, Vec2, Vec3}; use super::CommandSpec; use crate::params::{bad, num, string_list, vec3}; @@ -135,12 +135,10 @@ fn curvature_comb(s: &mut Session, p: &Value) -> Result { } // One scale for all combs: the longest tooth is a fifth of the largest curve's size. let kmax = combs.iter().flat_map(|c| c.1.iter().map(|t| t.1.abs())).fold(0.0_f64, f64::max); - let size = combs.iter().flat_map(|c| c.1.iter().map(|t| t.0)).fold( - (Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY), Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY)), - |(lo, hi), q| (lo.min(q), hi.max(q)), - ); - let diag = (size.1 - size.0).len(); - let scale = num(p, "scale").filter(|x| *x > 0.0).unwrap_or(if kmax > 1e-12 && diag.is_finite() { 0.2 * diag / kmax } else { 1.0 }); + let bounds: Aabb3 = combs.iter().flat_map(|c| c.1.iter().map(|t| t.0)).collect(); + let diag = bounds.diagonal(); + let scale = + num(p, "scale").filter(|x| *x > 0.0).unwrap_or(if kmax > 1e-12 && !bounds.is_empty() && diag.is_finite() { 0.2 * diag / kmax } else { 1.0 }); let out: Vec = combs .iter() .map(|(id, teeth)| { diff --git a/crates/engine/src/tests/import_component.rs b/crates/engine/src/tests/import_component.rs index 6fb58874d..84fa22a02 100644 --- a/crates/engine/src/tests/import_component.rs +++ b/crates/engine/src/tests/import_component.rs @@ -5,7 +5,7 @@ //! imports sit loose in a component open and rebuild as they did. use serde_json::{Value, json}; -use solidcraft_geom::Vec3; +use solidcraft_geom::{Aabb3, Vec3}; use solidcraft_kernel::{ExportBody, ExportProduct, StepHeader, box_solid, step_export_products}; use super::run; @@ -113,12 +113,7 @@ fn corner_of(s: &Session, occurrence: &str) -> Vec3 { let names = s.occurrence_bodies(&path, true).unwrap(); assert!(!names.is_empty()); let world = s.world_state(); - let mut lo = Vec3::new(f64::MAX, f64::MAX, f64::MAX); - for b in world.bodies.iter().filter(|b| names.contains(&b.name)) { - let bb = solidcraft_kernel::measure(&b.body).unwrap().bbox; - lo = Vec3::new(lo.x.min(bb.min.x), lo.y.min(bb.min.y), lo.z.min(bb.min.z)); - } - lo + world.bodies.iter().filter(|b| names.contains(&b.name)).fold(Aabb3::EMPTY, |a, b| a.union(&solidcraft_kernel::measure(&b.body).unwrap().bbox)).min } fn close(a: Vec3, b: Vec3) -> bool { diff --git a/crates/geom/src/aabb2.rs b/crates/geom/src/aabb2.rs new file mode 100644 index 000000000..8726d24a9 --- /dev/null +++ b/crates/geom/src/aabb2.rs @@ -0,0 +1,104 @@ +//! A box in the plane, the 2D [`crate::Aabb3`]. + +use crate::Vec2; + +/// Axis-aligned box in the plane; [`Aabb2::EMPTY`] (low +∞, high −∞) holds nothing. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Aabb2 { + pub min: Vec2, + pub max: Vec2, +} + +impl Default for Aabb2 { + fn default() -> Self { + Aabb2::EMPTY + } +} + +impl Aabb2 { + pub const EMPTY: Aabb2 = Aabb2 { min: Vec2::new(f64::INFINITY, f64::INFINITY), max: Vec2::new(f64::NEG_INFINITY, f64::NEG_INFINITY) }; + pub fn is_empty(&self) -> bool { + !(self.min.x <= self.max.x && self.min.y <= self.max.y) + } + /// Grow to hold `p`; a point that is not finite is skipped. + pub fn add(&mut self, p: Vec2) { + if p.is_finite() { + self.min = Vec2::new(self.min.x.min(p.x), self.min.y.min(p.y)); + self.max = Vec2::new(self.max.x.max(p.x), self.max.y.max(p.y)); + } + } + pub fn union(&self, o: &Aabb2) -> Aabb2 { + if self.is_empty() { + return *o; + } + if o.is_empty() { + return *self; + } + Aabb2 { min: Vec2::new(self.min.x.min(o.min.x), self.min.y.min(o.min.y)), max: Vec2::new(self.max.x.max(o.max.x), self.max.y.max(o.max.y)) } + } + pub fn center(&self) -> Vec2 { + if self.is_empty() { Vec2::ZERO } else { (self.min + self.max) * 0.5 } + } + pub fn size(&self) -> Vec2 { + if self.is_empty() { Vec2::ZERO } else { self.max - self.min } + } + pub fn diagonal(&self) -> f64 { + self.size().len() + } + /// The box grown by `by` on every side; an empty box stays empty. + pub fn inflated(&self, by: f64) -> Aabb2 { + if self.is_empty() { + return *self; + } + let d = Vec2::new(by, by); + Aabb2 { min: self.min - d, max: self.max + d } + } + /// Whether `p` lies in the box, its sides included (never in an empty box, never for NaN). + pub fn contains(&self, p: Vec2) -> bool { + p.x >= self.min.x && p.y >= self.min.y && p.x <= self.max.x && p.y <= self.max.y + } + /// Whether the two boxes share a point (never when either is empty). + pub fn meets(&self, o: &Aabb2) -> bool { + self.min.x <= o.max.x && o.min.x <= self.max.x && self.min.y <= o.max.y && o.min.y <= self.max.y + } + /// Where `p` sits in the box: (0, 0) at `min`, (1, 1) at `max`, each side taken as at least + /// 1e-9 long so a flat box still divides. + pub fn relative(&self, p: Vec2) -> Vec2 { + Vec2::new((p.x - self.min.x) / (self.max.x - self.min.x).max(1e-9), (p.y - self.min.y) / (self.max.y - self.min.y).max(1e-9)) + } +} + +/// The box around the finite points (non-finite ones are skipped, as [`Aabb2::add`] does). +impl FromIterator for Aabb2 { + fn from_iter>(points: I) -> Aabb2 { + let mut b = Aabb2::EMPTY; + b.extend(points); + b + } +} + +impl Extend for Aabb2 { + fn extend>(&mut self, points: I) { + for p in points { + self.add(p); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_box_from_points_holds_them_and_grows() { + let b: Aabb2 = [Vec2::new(1.0, 2.0), Vec2::new(-1.0, 0.0), Vec2::new(f64::INFINITY, 0.0)].into_iter().collect(); + assert_eq!((b.min, b.max), (Vec2::new(-1.0, 0.0), Vec2::new(1.0, 2.0)), "the infinite point is skipped"); + assert!(b.contains(Vec2::new(0.0, 1.0)) && !b.contains(Vec2::new(0.0, 3.0)) && !b.contains(Vec2::new(f64::NAN, 1.0))); + assert!(b.inflated(1.0).contains(Vec2::new(0.0, 3.0))); + assert!(Aabb2::EMPTY.inflated(1e9).is_empty() && !Aabb2::EMPTY.contains(Vec2::ZERO)); + let far = Aabb2 { min: Vec2::new(2.0, 0.0), max: Vec2::new(3.0, 1.0) }; + assert!(!b.meets(&far) && b.inflated(1.0).meets(&far) && !b.meets(&Aabb2::EMPTY)); + assert_eq!(b.union(&far).max, Vec2::new(3.0, 2.0)); + assert_eq!(b.relative(Vec2::new(0.0, 1.0)), Vec2::new(0.5, 0.5)); + } +} diff --git a/crates/geom/src/chain.rs b/crates/geom/src/chain.rs new file mode 100644 index 000000000..87795a33b --- /dev/null +++ b/crates/geom/src/chain.rs @@ -0,0 +1,223 @@ +//! Chains of items in order: a [`Ring`] closes back on its first item (a polygon's corners, a +//! loop of segments, a fan of rays), a [`Path`] has two ends (a polyline, a sweep path). Which one +//! a chain is lives in its type, so code that walks its edges never wraps an index by hand, and +//! what only a closed chain has (an area, an inside) is only asked of a ring. + +use std::marker::PhantomData; +use std::ops::Deref; + +use crate::{Aabb2, Vec2, Vec3}; + +/// Whether a chain's last item joins its first. +pub trait Ends: sealed::Sealed { + const CLOSED: bool; +} + +/// The last item joins the first: a [`Ring`]. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct Closed; + +/// The first and last items are ends: a [`Path`]. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct Open; + +impl Ends for Closed { + const CLOSED: bool = true; +} + +impl Ends for Open { + const CLOSED: bool = false; +} + +mod sealed { + pub trait Sealed {} + impl Sealed for super::Closed {} + impl Sealed for super::Open {} +} + +/// Items in order, closed or open by `E`; as a slice it is the items once each. +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] +pub struct Chain { + items: Vec, + ends: PhantomData, +} + +/// A closed chain: the last item joins the first. +pub type Ring = Chain; + +/// An open chain from its first item to its last. +pub type Path = Chain; + +impl Chain { + pub fn new(items: Vec) -> Chain { + Chain { items, ends: PhantomData } + } + + /// Each item with the next: as many edges as items around a ring (the last with the first; + /// a lone item pairs with itself), one fewer along a path. + pub fn edges(&self) -> impl Iterator + Clone { + let n = if E::CLOSED { self.items.len() } else { self.items.len().saturating_sub(1) }; + self.items.iter().zip(self.items.iter().cycle().skip(1)).take(n) + } + + pub fn into_vec(self) -> Vec { + self.items + } +} + +impl Ring { + /// Each item with the one before and the one after it: `(previous, item, next)`, once per + /// item. + pub fn corners(&self) -> impl Iterator + Clone { + let before = self.items.iter().cycle().skip(self.items.len().saturating_sub(1)); + before.zip(self.edges()).map(|(p, (c, x))| (p, c, x)) + } +} + +impl Path { + /// The ring through the same items: the last joined back to the first. + pub fn close(self) -> Ring { + Chain::new(self.items) + } +} + +impl Chain { + /// The smallest box holding every item (empty for an empty chain). + pub fn bounds(&self) -> Aabb2 { + self.items.iter().copied().collect() + } +} + +/// A point in a plane, whichever type holds it. +pub trait Planar: Copy { + fn xy(self) -> (f64, f64); +} + +impl Planar for Vec2 { + fn xy(self) -> (f64, f64) { + (self.x, self.y) + } +} + +impl Planar for [f64; 2] { + fn xy(self) -> (f64, f64) { + (self[0], self[1]) + } +} + +impl Ring

{ + /// The area the ring encloses, positive when it runs counter-clockwise. + pub fn signed_area(&self) -> f64 { + 0.5 * self + .edges() + .map(|(a, b)| { + let ((ax, ay), (bx, by)) = (a.xy(), b.xy()); + ax * by - ay * bx + }) + .sum::() + } + + /// Even-odd containment: whether a ray from `p` along +x crosses the ring an odd number of + /// times. + pub fn contains(&self, p: P) -> bool { + let (px, py) = p.xy(); + let mut inside = false; + for (a, b) in self.edges() { + let ((ax, ay), (bx, by)) = (a.xy(), b.xy()); + if (ay > py) != (by > py) && px < ax + (py - ay) / (by - ay) * (bx - ax) { + inside = !inside; + } + } + inside + } +} + +impl Ring { + /// The ring's vector area (Newell's method): its direction the normal the ring turns about, + /// its length the area it encloses when flat; `area_vector().dot(n)` is the area seen along + /// the unit vector `n`, positive when the ring runs counter-clockwise about it. + pub fn area_vector(&self) -> Vec3 { + self.edges().fold(Vec3::ZERO, |s, (a, b)| s + a.cross(*b)) * 0.5 + } +} + +/// [`Ring::edges`] of items held elsewhere, for a type that keeps a closed ring in a field of its +/// own ([`crate::Loop2::joints`]). +pub(crate) fn around(items: &[T]) -> impl Iterator + Clone { + items.iter().zip(items.iter().cycle().skip(1)) +} + +impl Deref for Chain { + type Target = [T]; + fn deref(&self) -> &[T] { + &self.items + } +} + +impl IntoIterator for Chain { + type Item = T; + type IntoIter = std::vec::IntoIter; + fn into_iter(self) -> std::vec::IntoIter { + self.items.into_iter() + } +} + +impl<'a, T, E> IntoIterator for &'a Chain { + type Item = &'a T; + type IntoIter = std::slice::Iter<'a, T>; + fn into_iter(self) -> std::slice::Iter<'a, T> { + self.items.iter() + } +} + +impl From> for Chain { + fn from(items: Vec) -> Chain { + Chain::new(items) + } +} + +impl From<[T; N]> for Chain { + fn from(items: [T; N]) -> Chain { + Chain::new(items.into()) + } +} + +impl FromIterator for Chain { + fn from_iter>(items: I) -> Chain { + Chain::new(items.into_iter().collect()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_ring_closes_and_a_path_does_not() { + assert_eq!(Ring::from([1, 2, 3]).edges().collect::>(), vec![(&1, &2), (&2, &3), (&3, &1)]); + assert_eq!(Path::from([1, 2, 3]).edges().collect::>(), vec![(&1, &2), (&2, &3)]); + assert_eq!(Path::from([1, 2, 3]).close().edges().count(), 3); + assert_eq!(Ring::from([7]).edges().collect::>(), vec![(&7, &7)]); + assert_eq!(Path::from([7]).edges().count(), 0); + assert_eq!(Ring::::default().edges().count(), 0); + assert_eq!(Path::::default().edges().count(), 0); + assert_eq!(Ring::from([1, 2, 3]).corners().collect::>(), vec![(&3, &1, &2), (&1, &2, &3), (&2, &3, &1)]); + assert_eq!(Ring::::default().corners().count(), 0); + } + + #[test] + fn a_square_encloses_its_area_and_its_inside() { + let square = Ring::from([Vec2::new(0.0, 0.0), Vec2::new(2.0, 0.0), Vec2::new(2.0, 2.0), Vec2::new(0.0, 2.0)]); + assert_eq!(square.signed_area(), 4.0); + assert_eq!(square.iter().rev().copied().collect::>().signed_area(), -4.0); + assert!(square.contains(Vec2::new(1.0, 1.0))); + assert!(!square.contains(Vec2::new(3.0, 1.0))); + let uv = Ring::from([[0.0, 0.0], [2.0, 0.0], [2.0, 2.0], [0.0, 2.0]]); + assert_eq!(uv.signed_area(), 4.0); + let tilted = Ring::from([Vec3::new(0.0, 0.0, 1.0), Vec3::new(2.0, 0.0, 1.0), Vec3::new(2.0, 2.0, 1.0), Vec3::new(0.0, 2.0, 1.0)]); + assert_eq!(tilted.area_vector(), Vec3::new(0.0, 0.0, 4.0)); + assert!(uv.contains([1.0, 1.0]) && !uv.contains([3.0, 1.0])); + assert_eq!(square.bounds(), Aabb2 { min: Vec2::new(0.0, 0.0), max: Vec2::new(2.0, 2.0) }); + assert!(Path::::default().bounds().is_empty()); + } +} diff --git a/crates/geom/src/compare.rs b/crates/geom/src/compare.rs index e79995790..74e4b20fd 100644 --- a/crates/geom/src/compare.rs +++ b/crates/geom/src/compare.rs @@ -644,7 +644,6 @@ fn clusters(pts: &[Pt], cell: f64) -> Vec> { } } let groups_of = |parent: &mut [usize]| -> Vec { of_point.iter().map(|&c| find(parent, c)).collect() }; - let grow = Vec3::new(cell, cell, cell); // Join groups of one side whose grown boxes overlap, until none do (sort and sweep along X). for _ in 0..16 { let groups = groups_of(&mut parent); @@ -652,8 +651,7 @@ fn clusters(pts: &[Pt], cell: f64) -> Vec> { for (pt, g) in pts.iter().zip(&groups) { boxes.entry(*g).or_insert((pt.side, Aabb3::EMPTY)).1.add(pt.off.p); } - let mut list: Vec<(usize, Side, Aabb3)> = - boxes.into_iter().map(|(g, (s, b))| (g, s, Aabb3 { min: b.min - grow, max: b.max + grow })).collect(); + let mut list: Vec<(usize, Side, Aabb3)> = boxes.into_iter().map(|(g, (s, b))| (g, s, b.inflated(cell))).collect(); list.sort_by(|a, b| a.2.min.x.total_cmp(&b.2.min.x).then(a.0.cmp(&b.0))); let mut joined = false; for (k, (ga, sa, ba)) in list.iter().enumerate() { @@ -887,10 +885,9 @@ pub fn compare(a: &Mesh, b: &Mesh, o: &CompareOptions, each: Each) -> Comparison found.sort_by(|x, y| y.weight.total_cmp(&x.weight).then(y.max.total_cmp(&x.max))); let unlisted = found.len().saturating_sub(o.max_regions); found.truncate(o.max_regions); - let grow = Vec3::new(cell, cell, cell); let measured = gather(found.len(), each, |i| { let f = found.get(i)?; - region_volume([&ta, &tb], &Aabb3 { min: f.bbox.min - grow, max: f.bbox.max + grow }, f.side, o.max_lines) + region_volume([&ta, &tb], &f.bbox.inflated(cell), f.side, o.max_lines) }); let mut regions: Vec = found .into_iter() diff --git a/crates/geom/src/fill.rs b/crates/geom/src/fill.rs index 7169a1856..1ce368fa0 100644 --- a/crates/geom/src/fill.rs +++ b/crates/geom/src/fill.rs @@ -878,17 +878,8 @@ mod tests { /// The farthest the surface is from `z` over the polygon's inside (sampled on a grid). fn off_inside(f: &LoopFill, corners: &[[f64; 2]], z: &dyn Fn(f64, f64) -> f64) -> f64 { - let inside = |x: f64, y: f64| { - let n = corners.len(); - let mut w = false; - for k in 0..n { - let (a, b) = (corners[k], corners[(k + 1) % n]); - if (a[1] > y) != (b[1] > y) && x < a[0] + (y - a[1]) / (b[1] - a[1]) * (b[0] - a[0]) { - w = !w; - } - } - w - }; + let polygon = crate::Ring::from(corners.to_vec()); + let inside = |x: f64, y: f64| polygon.contains([x, y]); let s = &f.surface; let [du, dv] = s.domain(); let mut worst = 0.0f64; diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index a3f253494..7864c1ba3 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -9,11 +9,13 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] +mod aabb2; mod arcfit; pub mod blend; pub mod brep; pub mod bspline; mod bvh; +mod chain; pub mod compare; pub mod env; pub mod fill; @@ -31,9 +33,11 @@ pub mod tspline; mod unit_vec3; mod vec; +pub use aabb2::Aabb2; pub use arcfit::MAX_FIT_PIECES; pub use blend::hermite_bezier; pub use bvh::{Bvh, MeshIndex}; +pub use chain::{Chain, Closed, Ends, Open, Path, Planar, Ring}; pub use grid::Grid; pub use mesh::{Aabb3, BoxedTriangle, InsideIndex, MassProperties, Mesh, MeshMeasure, find_close_pair}; pub use plane::Plane; diff --git a/crates/geom/src/mesh.rs b/crates/geom/src/mesh.rs index 45dd94161..f6234320d 100644 --- a/crates/geom/src/mesh.rs +++ b/crates/geom/src/mesh.rs @@ -47,6 +47,48 @@ impl Aabb3 { pub fn diagonal(&self) -> f64 { self.size().len() } + /// The box grown by `by` on every side; an empty box stays empty. + pub fn inflated(&self, by: f64) -> Aabb3 { + if self.is_empty() { + return *self; + } + let d = Vec3::new(by, by, by); + Aabb3 { min: self.min - d, max: self.max + d } + } + /// Whether `p` lies in the box, its sides included (never in an empty box, never for NaN). + pub fn contains(&self, p: Vec3) -> bool { + p.x >= self.min.x && p.y >= self.min.y && p.z >= self.min.z && p.x <= self.max.x && p.y <= self.max.y && p.z <= self.max.z + } + /// The box both hold: empty when they do not meet. + pub fn intersection(&self, o: &Aabb3) -> Aabb3 { + Aabb3 { min: self.min.max(o.min), max: self.max.min(o.max) } + } + /// Whether the two boxes share a point (never when either is empty). + pub fn meets(&self, o: &Aabb3) -> bool { + self.min.x <= o.max.x + && o.min.x <= self.max.x + && self.min.y <= o.max.y + && o.min.y <= self.max.y + && self.min.z <= o.max.z + && o.min.z <= self.max.z + } +} + +/// The box around the finite points (non-finite ones are skipped, as [`Aabb3::add`] does). +impl FromIterator for Aabb3 { + fn from_iter>(points: I) -> Aabb3 { + let mut b = Aabb3::EMPTY; + b.extend(points); + b + } +} + +impl Extend for Aabb3 { + fn extend>(&mut self, points: I) { + for p in points { + self.add(p); + } + } } /// An indexed triangle mesh with per-vertex normals, a face id per triangle (the B-rep face it @@ -76,10 +118,6 @@ pub struct Mesh { pub edge_faces: Vec>, } -fn boxes_meet(a: &Aabb3, b: &Aabb3) -> bool { - a.min.x <= b.max.x && b.min.x <= a.max.x && a.min.y <= b.max.y && b.min.y <= a.max.y && a.min.z <= b.max.z && b.min.z <= a.max.z -} - /// A triangle with its bounding box, as [`find_close_pair`] takes them. pub type BoxedTriangle = ([Vec3; 3], Aabb3); @@ -559,7 +597,7 @@ impl Mesh { let t = m.tri(t)?; let mut bx = Aabb3::EMPTY; t.iter().for_each(|p| bx.add(*p)); - (!bx.is_empty() && boxes_meet(&bx, ®ion)).then(|| ((t, bx), m.tri_face.get(i).copied().unwrap_or(u32::MAX))) + (!bx.is_empty() && bx.meets(®ion)).then(|| ((t, bx), m.tri_face.get(i).copied().unwrap_or(u32::MAX))) }) .unzip() }; diff --git a/crates/geom/src/profile.rs b/crates/geom/src/profile.rs index e1117898c..7edc5985f 100644 --- a/crates/geom/src/profile.rs +++ b/crates/geom/src/profile.rs @@ -6,7 +6,7 @@ use std::f64::consts::TAU; use serde::{Deserialize, Serialize}; -use crate::Vec2; +use crate::{Aabb2, Ring, Vec2}; /// One boundary segment in sketch coordinates. #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] @@ -530,29 +530,26 @@ impl Loop2 { pub fn ccw(&self) -> Loop2 { if self.is_ccw() { self.clone() } else { self.reversed() } } - pub fn polyline(&self, tol: f64) -> Vec { - let mut out = Vec::new(); - for s in &self.segs { - let p = s.polyline(tol); - out.extend(p.iter().take(p.len().saturating_sub(1))); - } - out + /// Each segment with the next and the last with the first: the loop's joints, where one + /// segment should end on the start of the next. + pub fn joints(&self) -> impl Iterator + Clone { + crate::chain::around(&self.segs) + } + /// The loop as a polyline within `tol`: each segment's points but its last, which the next + /// segment starts on. + pub fn polyline(&self, tol: f64) -> Ring { + self.segs + .iter() + .flat_map(|s| { + let p = s.polyline(tol); + let n = p.len().saturating_sub(1); + p.into_iter().take(n) + }) + .collect() } /// Even-odd point containment against the polyline approximation. pub fn contains(&self, p: Vec2) -> bool { - let poly = self.polyline(1e-3); - let n = poly.len(); - let mut inside = false; - for i in 0..n { - let (Some(a), Some(b)) = (poly.get(i), poly.get((i + 1) % n)) else { continue }; - if (a.y > p.y) != (b.y > p.y) { - let x = a.x + (p.y - a.y) / (b.y - a.y) * (b.x - a.x); - if p.x < x { - inside = !inside; - } - } - } - inside + self.polyline(1e-3).contains(p) } /// Area-weighted centroid (of the polyline approximation). pub fn centroid(&self) -> Vec2 { @@ -634,25 +631,20 @@ impl Region2 { /// before they meet (a taper going in closes it there). Found by a grid search refined /// around the best point, to about `tol`. pub fn inradius(&self, tol: f64) -> f64 { - let loops: Vec> = std::iter::once(&self.outer).chain(&self.holes).map(|l| l.polyline(tol)).collect(); + let loops: Vec> = std::iter::once(&self.outer).chain(&self.holes).map(|l| l.polyline(tol)).collect(); max_clearance(&loops) } } /// The largest distance from a point inside `loops` (even-odd) to their sides, by a grid search /// over their box refined around the best point. Zero for an empty or degenerate outline. -fn max_clearance(loops: &[Vec]) -> f64 { - let sides: Vec<(Vec2, Vec2)> = loops - .iter() - .flat_map(|pl| (0..pl.len()).filter_map(move |i| Some((*pl.get(i)?, *pl.get((i + 1) % pl.len())?)))) - .filter(|(a, b)| a.dist(*b) > 0.0) - .collect(); - let (Some(lo), Some(hi)) = ( - sides.iter().map(|s| s.0).reduce(|a, b| Vec2::new(a.x.min(b.x), a.y.min(b.y))), - sides.iter().map(|s| s.0).reduce(|a, b| Vec2::new(a.x.max(b.x), a.y.max(b.y))), - ) else { +fn max_clearance(loops: &[Ring]) -> f64 { + let sides: Vec<(Vec2, Vec2)> = loops.iter().flat_map(|pl| pl.edges().map(|(a, b)| (*a, *b))).filter(|(a, b)| a.dist(*b) > 0.0).collect(); + let corners: Aabb2 = sides.iter().map(|s| s.0).collect(); + if corners.is_empty() { return 0.0; - }; + } + let Aabb2 { min: lo, max: hi } = corners; let inside = |p: Vec2| { let mut odd = false; for (a, b) in &sides { @@ -782,26 +774,24 @@ pub fn regions_apart(regions: &[Region2], gap: f64) -> bool { let tol = gap / 4.0; let reach = gap + 2.0 * tol; struct Outline { - loops: Vec>, - lo: Vec2, - hi: Vec2, + loops: Vec>, + bounds: Aabb2, inside: Vec2, } let mut outlines = Vec::with_capacity(regions.len()); for r in regions { - let loops: Vec> = std::iter::once(&r.outer).chain(&r.holes).map(|l| l.polyline(tol)).collect(); + let loops: Vec> = std::iter::once(&r.outer).chain(&r.holes).map(|l| l.polyline(tol)).collect(); let Some(outer) = loops.first().filter(|l| l.len() >= 2) else { return false }; if outer.iter().any(|p| !p.is_finite()) { return false; } - let lo = outer.iter().fold(Vec2::new(f64::MAX, f64::MAX), |m, p| Vec2::new(m.x.min(p.x), m.y.min(p.y))); - let hi = outer.iter().fold(Vec2::new(f64::MIN, f64::MIN), |m, p| Vec2::new(m.x.max(p.x), m.y.max(p.y))); + let bounds = outer.bounds(); let Some(inside) = outer.first().copied() else { return false }; - outlines.push(Outline { loops, lo, hi, inside }); + outlines.push(Outline { loops, bounds, inside }); } let mut order: Vec = (0..outlines.len()).collect(); order.sort_by(|&i, &j| { - let x = |k: usize| outlines.get(k).map(|o| o.lo.x).unwrap_or(0.0); + let x = |k: usize| outlines.get(k).map(|o| o.bounds.min.x).unwrap_or(0.0); x(i).total_cmp(&x(j)) }); let mut work = 0usize; @@ -809,10 +799,11 @@ pub fn regions_apart(regions: &[Region2], gap: f64) -> bool { let Some(a) = outlines.get(i) else { return false }; for &j in order.iter().skip(k + 1) { let Some(b) = outlines.get(j) else { return false }; - if b.lo.x > a.hi.x + reach { + let (a_box, b_box) = (a.bounds, b.bounds); + if b_box.min.x > a_box.max.x + reach { break; } - if b.lo.y > a.hi.y + reach || a.lo.y > b.hi.y + reach { + if b_box.min.y > a_box.max.y + reach || a_box.min.y > b_box.max.y + reach { continue; } // A boundary point of one inside the other: one holds the other (boundaries that do diff --git a/crates/geom/src/tests.rs b/crates/geom/src/tests.rs index 7b8513aca..a2b494349 100644 --- a/crates/geom/src/tests.rs +++ b/crates/geom/src/tests.rs @@ -730,3 +730,18 @@ mod blend { assert_eq!(d[0], Vec2::ZERO); } } + +#[test] +fn a_box_from_points_holds_them_and_grows() { + let b: Aabb3 = [Vec3::new(1.0, 2.0, 3.0), Vec3::new(-1.0, 0.0, 5.0), Vec3::new(f64::INFINITY, 0.0, 0.0)].into_iter().collect(); + assert_eq!((b.min, b.max), (Vec3::new(-1.0, 0.0, 3.0), Vec3::new(1.0, 2.0, 5.0)), "the infinite point is skipped"); + assert!(b.contains(Vec3::new(0.0, 1.0, 4.0)) && !b.contains(Vec3::new(0.0, 1.0, 6.0))); + assert!(!b.contains(Vec3::new(f64::NAN, 1.0, 4.0))); + assert!(b.inflated(1.0).contains(Vec3::new(0.0, 1.0, 6.0))); + assert!(Aabb3::EMPTY.inflated(1e9).is_empty() && !Aabb3::EMPTY.contains(Vec3::ZERO)); + let far = Aabb3 { min: Vec3::new(2.0, 0.0, 3.0), max: Vec3::new(3.0, 1.0, 4.0) }; + assert!(!b.meets(&far) && b.inflated(1.0).meets(&far) && !b.meets(&Aabb3::EMPTY)); + let both = b.intersection(&b.inflated(1.0).intersection(&Aabb3 { min: Vec3::new(0.0, 1.0, 4.0), max: Vec3::new(9.0, 9.0, 9.0) })); + assert_eq!((both.min, both.max), (Vec3::new(0.0, 1.0, 4.0), Vec3::new(1.0, 2.0, 5.0))); + assert!(b.intersection(&far).is_empty()); +} diff --git a/crates/kernel/src/blend.rs b/crates/kernel/src/blend.rs index 66a2d3d17..5d8b87b00 100644 --- a/crates/kernel/src/blend.rs +++ b/crates/kernel/src/blend.rs @@ -9,7 +9,7 @@ use std::collections::HashMap; -use solidcraft_geom::Vec3; +use solidcraft_geom::{Aabb3, Vec3}; use truck_modeling::{self as mt, builder}; use crate::body::{Body, Solid, from_p3, p3, v3}; @@ -1295,7 +1295,7 @@ fn blend_each(mut cur: Body, edges: &[Vec3], r: f64, shape: Shape, what: &str, c // edge, the refusal). A blend only changes the body near the edges it rounds, so an edge // refused away from every later blend would be refused the same way again: it is not tried // again (a refusal costs a rolling-ball attempt, seconds each on a long curved edge). - let mut refused: Vec<(Vec3, (Vec3, Vec3), KernelError)> = Vec::new(); + let mut refused: Vec<(Vec3, Aabb3, KernelError)> = Vec::new(); // A chain runs on along the edges smooth with a selected one in the body as given, not along // a round this blend has made meanwhile (which would take in edges nobody selected, or not, // by the order the edges come in). @@ -1333,13 +1333,13 @@ fn blend_each(mut cur: Body, edges: &[Vec3], r: f64, shape: Shape, what: &str, c && let Ok(b) = guard(what, || Ok(res)).and_then(|res| record::rebuilt(res, &[&solid], &rec)) { let near = edges_box(&solid, &ids, r + tol); - refused.retain(|(_, b, _)| !boxes_meet(*b, near)); + refused.retain(|(_, b, _)| !boxes_meet(b, &near)); cur = record::after(b, &cur, &counts); todo.retain(|p| !covered.iter().any(|q| q.dist(*p) < 1e-12)); continue; } let mut first_err: Option = None; - let mut done: Option<(Body, Vec, (Vec3, Vec3))> = None; + let mut done: Option<(Body, Vec, Aabb3)> = None; for (j, p) in todo.iter().enumerate() { if let Some((_, _, e)) = refused.iter().find(|(q, _, _)| q.dist(*p) < 1e-12) { if first_err.is_none() || (matches!(e, KernelError::TooLarge(_)) && !matches!(first_err, Some(KernelError::TooLarge(_)))) { @@ -1455,7 +1455,7 @@ fn blend_each(mut cur: Body, edges: &[Vec3], r: f64, shape: Shape, what: &str, c } match done { Some((b, js, near)) => { - refused.retain(|(_, b2, _)| !boxes_meet(*b2, near)); + refused.retain(|(_, b2, _)| !boxes_meet(b2, &near)); cur = record::after(b, &cur, &counts); let mut k = 0; todo.retain(|_| { @@ -1477,27 +1477,19 @@ thread_local! { } /// The box around these edges of `solid` (their ends and middles), grown by `margin`. -fn edges_box(solid: &Solid, ids: &[mt::EdgeID], margin: f64) -> (Vec3, Vec3) { +fn edges_box(solid: &Solid, ids: &[mt::EdgeID], margin: f64) -> Aabb3 { use mt::{BoundedCurve, ParametricCurve}; - let mut lo = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY); - let mut hi = -lo; - for e in Body::unique_edges(solid).iter().filter(|e| ids.contains(&e.id())) { + let points = Body::unique_edges(solid).into_iter().filter(|e| ids.contains(&e.id())).flat_map(|e| { let c = e.curve(); let (t0, t1) = c.range_tuple(); - for k in 0..=8 { - let q = from_p3(c.subs(t0 + (t1 - t0) * f64::from(k) / 8.0)); - lo = lo.min(q); - hi = hi.max(q); - } - } - let m = Vec3::new(margin, margin, margin); - (lo - m, hi + m) + (0..=8).map(move |k| from_p3(c.subs(t0 + (t1 - t0) * f64::from(k) / 8.0))) + }); + points.collect::().inflated(margin) } /// Whether two boxes overlap (an empty box meets every box: nothing is known about it). -fn boxes_meet(a: (Vec3, Vec3), b: (Vec3, Vec3)) -> bool { - let empty = |x: (Vec3, Vec3)| !(x.0.x <= x.1.x && x.0.y <= x.1.y && x.0.z <= x.1.z); - empty(a) || empty(b) || (a.0.x <= b.1.x && b.0.x <= a.1.x && a.0.y <= b.1.y && b.0.y <= a.1.y && a.0.z <= b.1.z && b.0.z <= a.1.z) +fn boxes_meet(a: &Aabb3, b: &Aabb3) -> bool { + a.is_empty() || b.is_empty() || a.meets(b) } /// Neighbouring edges along one boundary loop of a planar face that between them hold at least diff --git a/crates/kernel/src/body.rs b/crates/kernel/src/body.rs index 6cbb7578a..55627e628 100644 --- a/crates/kernel/src/body.rs +++ b/crates/kernel/src/body.rs @@ -1,5 +1,5 @@ use serde::Serialize; -use solidcraft_geom::{Mesh, Vec3}; +use solidcraft_geom::{Aabb3, Mesh, Vec3}; use truck_meshalgo::prelude::*; use truck_modeling as mt; @@ -542,14 +542,8 @@ fn orientation_tolerance(span: f64) -> f64 { /// Bounding-box diagonal of a solid's vertices (1 when it has no finite extent). fn span_of(solid: &Solid) -> f64 { - let mut lo = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY); - let mut hi = -lo; - for v in solid.vertex_iter() { - let p = from_p3(v.point()); - lo = Vec3::new(lo.x.min(p.x), lo.y.min(p.y), lo.z.min(p.z)); - hi = Vec3::new(hi.x.max(p.x), hi.y.max(p.y), hi.z.max(p.z)); - } - if lo.x.is_finite() { (hi - lo).len() } else { 1.0 } + let bounds: Aabb3 = solid.vertex_iter().map(|v| from_p3(v.point())).collect(); + if bounds.is_empty() { 1.0 } else { bounds.diagonal() } } /// Equal shared values: the same allocation (a clone of the body), else equal contents. diff --git a/crates/kernel/src/build.rs b/crates/kernel/src/build.rs index e781e7f37..1595f050e 100644 --- a/crates/kernel/src/build.rs +++ b/crates/kernel/src/build.rs @@ -1,7 +1,7 @@ //! Building bodies: extrude and revolve planar regions, primitives. use mt::builder; -use solidcraft_geom::{Grid, Loop2, Plane, Region2, Seg2, Vec2, Vec3}; +use solidcraft_geom::{Grid, Loop2, Plane, Region2, Ring, Seg2, Vec2, Vec3}; use truck_modeling as mt; use crate::body::{Body, Solid, from_p3, p3, v3}; @@ -1584,8 +1584,7 @@ fn revolve_on_axis(plane: &Plane, numbered: &NumberedLoop, axis_origin: Vec2, d: } }; // The loop's turning (Newell) against the surface normal halfway round. - let mut nw = Vec3::ZERO; - let poly: Vec = wire + let poly: Ring = wire .edge_iter() .flat_map(|ed| { let c = ed.oriented_curve(); @@ -1593,11 +1592,7 @@ fn revolve_on_axis(plane: &Plane, numbered: &NumberedLoop, axis_origin: Vec2, d: (0..8).map(move |j| from_p3(c.subs(t0 + (t1 - t0) * j as f64 / 8.0))).collect::>() }) .collect(); - for (j, p) in poly.iter().enumerate() { - if let Some(q) = poly.get((j + 1) % poly.len()) { - nw += p.cross(*q); - } - } + let nw = poly.area_vector(); let probe = turn(&half, plane.to_world(sg.mid())); let sn = surface.search_nearest_parameter(p3(probe), None, 100).map(|(u, v)| surface.normal(u, v)); if sn.is_some_and(|m| nw.dot(Vec3::new(m.x, m.y, m.z)) < 0.0) { diff --git a/crates/kernel/src/coplanar.rs b/crates/kernel/src/coplanar.rs index f7afd3383..201d3bb1a 100644 --- a/crates/kernel/src/coplanar.rs +++ b/crates/kernel/src/coplanar.rs @@ -24,7 +24,7 @@ use std::collections::HashMap; -use solidcraft_geom::{Aabb3, UnitVec3, Vec3}; +use solidcraft_geom::{Aabb3, Ring, UnitVec3, Vec3}; use truck_modeling::{self as mt, builder}; use crate::body::shell_groups::boxes_separate; @@ -1098,7 +1098,7 @@ fn faces_box(body: &Body, faces: &[usize], gap: f64) -> Option { bb.add(b.min); bb.add(b.max); } - (!bb.is_empty()).then(|| Aabb3 { min: bb.min - Vec3::new(gap, gap, gap), max: bb.max + Vec3::new(gap, gap, gap) }) + (!bb.is_empty()).then(|| bb.inflated(gap)) } /// `body` (with its history `h` over its operand) with its faces in the plane (n, d) split @@ -1396,7 +1396,7 @@ fn inset_into(outer: &Body, inner: &Body, outer_operand: usize) -> Option Option> { + let sample = |w: &mt::Wire| -> Option> { if w.len() > 1000 { return None; } @@ -1406,7 +1406,7 @@ fn inset_into(outer: &Body, inner: &Body, outer_operand: usize) -> Option = outer.solid.face_iter().collect(); let fi: Vec<&mt::Face> = inner.solid.face_iter().collect(); @@ -1423,7 +1423,7 @@ fn inset_into(outer: &Body, inner: &Body, outer_operand: usize) -> Option>>()) else { continue; }; - let outer_count: usize = outer_loops.iter().map(Vec::len).sum(); + let outer_count: usize = outer_loops.iter().map(|l| l.len()).sum(); if inner_pts.len().saturating_mul(outer_count) > MAX_WORK { continue; } @@ -1436,8 +1436,7 @@ fn inset_into(outer: &Body, inner: &Body, outer_operand: usize) -> Option = outer_loops.iter().map(|l| flat(l)).collect(); let inner_poly = flat(&inner_pts); let in_outer = |p: Vec3| outer_polys.iter().filter(|l| l.contains(flat_point(p))).count() % 2 == 1; - let near_outer = - |p: Vec3| outer_loops.iter().any(|l| l.iter().zip(l.iter().cycle().skip(1)).any(|(s, t)| p.dist_to_segment(*s, *t) < clear)); + let near_outer = |p: Vec3| outer_loops.iter().any(|l| l.edges().any(|(s, t)| p.dist_to_segment(*s, *t) < clear)); let fits = inner_pts.iter().all(|p| in_outer(*p) && !near_outer(*p)) && outer_loops.iter().flatten().all(|p| !inner_poly.contains(flat_point(*p))); if !fits { diff --git a/crates/kernel/src/curveblend_tests.rs b/crates/kernel/src/curveblend_tests.rs index 12fc36b10..ae70fc7c3 100644 --- a/crates/kernel/src/curveblend_tests.rs +++ b/crates/kernel/src/curveblend_tests.rs @@ -286,7 +286,7 @@ fn gap(c1: Vec3, r1: f64, c2: Vec3, r2: f64, corner: Vec3, r: f64) -> Gap { ring.push(c + Vec3::new(t.cos(), t.sin(), 0.0) * rr); } } - let area = ring.iter().zip(ring.iter().cycle().skip(1)).map(|(p, q)| p.x * q.y - q.x * p.y).sum::().abs() * 0.5; + let area = ring.iter().map(|p| solidcraft_geom::Vec2::new(p.x, p.y)).collect::>().signed_area().abs(); let (p, q) = ((t1 - f).normalized().unwrap(), (t2 - f).normalized().unwrap()); let arc = (0..=8).map(|i| angles[2] * i as f64 / 8.0).map(|t| f + (p * ((angles[2] - t).sin()) + q * t.sin()) * (r / angles[2].sin())).collect(); Gap { arc, angles, area } diff --git a/crates/kernel/src/delete_face.rs b/crates/kernel/src/delete_face.rs index f8a46a5a2..e7cc07de6 100644 --- a/crates/kernel/src/delete_face.rs +++ b/crates/kernel/src/delete_face.rs @@ -12,7 +12,7 @@ use std::collections::{BTreeSet, HashMap}; -use solidcraft_geom::Vec3; +use solidcraft_geom::{Aabb3, Vec3}; use truck_modeling::{self as mt, builder}; use crate::body::{Body, Solid, from_p3, p3}; @@ -117,19 +117,9 @@ pub fn delete_faces(body: &Body, faces: &[usize]) -> Result { } } // Corners across the gap: three neighbour planes meeting near the deleted faces. - let (mut lo, mut hi) = - (Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY), Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY)); - for &f in &del { - for v in all.get(f).into_iter().flat_map(|x| x.vertex_iter()) { - let p = from_p3(v.point()); - lo = lo.min(p); - hi = hi.max(p); - } - } - let reach = (hi - lo).len().max(size * 1e-3); - let near = |p: Vec3| { - p.x >= lo.x - reach && p.y >= lo.y - reach && p.z >= lo.z - reach && p.x <= hi.x + reach && p.y <= hi.y + reach && p.z <= hi.z + reach - }; + let gap: Aabb3 = del.iter().flat_map(|f| all.get(*f).into_iter().flat_map(|x| x.vertex_iter())).map(|v| from_p3(v.point())).collect(); + let near_gap = gap.inflated(gap.diagonal().max(size * 1e-3)); + let near = |p: Vec3| near_gap.contains(p); let on = |p: Vec3, f: usize| planes.get(&f).is_some_and(|(n, d)| (n.dot(p) - d).abs() <= size * 1e-6); let nb: Vec = neighbours.iter().copied().collect(); let mut corners: Vec = Vec::new(); diff --git a/crates/kernel/src/distance.rs b/crates/kernel/src/distance.rs index 4db0128f6..86a648012 100644 --- a/crates/kernel/src/distance.rs +++ b/crates/kernel/src/distance.rs @@ -67,12 +67,7 @@ impl<'a> DistanceShape<'a> { /// The box around the body: its mesh's, grown by the chord tolerance. pub fn bounds(&self) -> Aabb3 { - let b = self.set.bounds(); - if b.is_empty() { - return b; - } - let g = Vec3::new(1.0, 1.0, 1.0) * self.chord; - Aabb3 { min: b.min - g, max: b.max + g } + self.set.bounds().inflated(self.chord) } /// How far the mesh may lie from the faces (mm). diff --git a/crates/kernel/src/face_params.rs b/crates/kernel/src/face_params.rs index d09515317..5011a1bdf 100644 --- a/crates/kernel/src/face_params.rs +++ b/crates/kernel/src/face_params.rs @@ -7,8 +7,8 @@ //! its holes first. use mt::{BoundedCurve, Cut, InnerSpace, Invertible, MetricSpace, ParametricCurve, ParametricSurface, SearchNearestParameter, Transformed}; -use solidcraft_geom::Vec3; use solidcraft_geom::tess::EvalSurface; +use solidcraft_geom::{Ring, Vec3}; use truck_modeling as mt; use crate::body::from_p3; @@ -30,20 +30,13 @@ pub(crate) struct LoopSamples { impl LoopSamples { /// The loop as a polygon in parameters (each edge's samples but its last, which the next /// edge starts on). - pub(crate) fn polygon(&self) -> Vec<[f64; 2]> { + pub(crate) fn polygon(&self) -> Ring<[f64; 2]> { self.edges.iter().flat_map(|(_, s)| s.iter().take(s.len().saturating_sub(1)).map(|x| x.2)).collect() } /// Signed area of the loop in parameters (positive: counter-clockwise). pub(crate) fn area(&self) -> f64 { - let poly = self.polygon(); - let n = poly.len(); - (0..n) - .filter_map(|i| { - let (a, b) = (poly.get(i)?, poly.get((i + 1) % n)?); - Some(0.5 * (a[0] * b[1] - b[0] * a[1])) - }) - .sum() + self.polygon().signed_area() } /// How far `p` is from the loop (from its samples). diff --git a/crates/kernel/src/fill.rs b/crates/kernel/src/fill.rs index 29ea2b2fa..ce2b8e05c 100644 --- a/crates/kernel/src/fill.rs +++ b/crates/kernel/src/fill.rs @@ -505,21 +505,11 @@ mod tests { /// vanishes on the rim, so cells across it add little error). fn gained(fill: &Body, corners: &[Vec2]) -> f64 { let s = fill.solid.face_iter().next().unwrap().surface(); - let (lo, hi) = corners.iter().fold((Vec2::new(f64::MAX, f64::MAX), Vec2::new(f64::MIN, f64::MIN)), |(lo, hi), p| { - (Vec2::new(lo.x.min(p.x), lo.y.min(p.y)), Vec2::new(hi.x.max(p.x), hi.y.max(p.y))) - }); + let polygon = solidcraft_geom::Ring::from(corners.to_vec()); + let solidcraft_geom::Aabb2 { min: lo, max: hi } = polygon.bounds(); let n = 300; let (dx, dy) = ((hi.x - lo.x) / n as f64, (hi.y - lo.y) / n as f64); - let inside = |x: f64, y: f64| { - let mut w = false; - for k in 0..corners.len() { - let (a, b) = (corners[k], corners[(k + 1) % corners.len()]); - if (a.y > y) != (b.y > y) && x < a.x + (y - a.y) / (b.y - a.y) * (b.x - a.x) { - w = !w; - } - } - w - }; + let inside = |x: f64, y: f64| polygon.contains(Vec2::new(x, y)); let mut sum = 0.0; let mut start = None; for i in 0..n { diff --git a/crates/kernel/src/heal.rs b/crates/kernel/src/heal.rs index 5d7cd8f7f..6d0f5995a 100644 --- a/crates/kernel/src/heal.rs +++ b/crates/kernel/src/heal.rs @@ -3,7 +3,7 @@ use std::collections::{BTreeSet, HashMap}; -use solidcraft_geom::Vec3; +use solidcraft_geom::{Ring, Vec3}; use truck_modeling::{self as mt, builder}; use crate::body::{Solid, from_p3}; @@ -51,15 +51,7 @@ fn samples(e: &mt::Edge) -> Vec { } fn loop_area(edges: &[mt::Edge], n: Vec3) -> f64 { - let pts: Vec = edges.iter().flat_map(samples).collect(); - let k = pts.len(); - let mut s = Vec3::ZERO; - for i in 0..k { - if let (Some(a), Some(b)) = (pts.get(i), pts.get((i + 1) % k)) { - s += a.cross(*b); - } - } - s.dot(n) * 0.5 + edges.iter().flat_map(samples).collect::>().area_vector().dot(n) } fn inside(p: Vec3, edges: &[mt::Edge], n: Vec3) -> bool { @@ -680,7 +672,8 @@ mod tests { .map(|k| builder::vertex(mt::Point3::new(k as f64, 0.0, 0.0))) .chain([builder::vertex(mt::Point3::new(n as f64, 3.0, 0.0)), builder::vertex(mt::Point3::new(0.0, 3.0, 0.0))]) .collect(); - let edges: Vec = pts.iter().zip(pts.iter().cycle().skip(1)).map(|(a, b)| builder::line(a, b)).collect(); + let pts: solidcraft_geom::Ring = pts.into(); + let edges: Vec = pts.edges().map(|(a, b)| builder::line(a, b)).collect(); let face = builder::try_attach_plane(&[mt::Wire::from(edges)]).expect("a plane"); builder::tsweep(&face, mt::Vector3::new(0.0, 0.0, 2.0)) } diff --git a/crates/kernel/src/lip.rs b/crates/kernel/src/lip.rs index 4c3e79b55..7faed0fb3 100644 --- a/crates/kernel/src/lip.rs +++ b/crates/kernel/src/lip.rs @@ -3,7 +3,7 @@ //! directly from the body's faces (the band's walls continue the walls below, which a boolean //! union can't join: their faces would coincide). -use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec3}; +use solidcraft_geom::{Loop2, Plane, Region2, Ring, Seg2, Vec3}; use truck_modeling::{self as mt, builder}; use crate::body::{Body, Solid, from_p3, p3, v3}; @@ -141,7 +141,7 @@ fn pieces(wire: &mt::Wire, size: f64) -> Result> { /// vertices, whose polygon has zero area for both the inner and outer loops. fn turn(wire: &mt::Wire, n: Vec3) -> f64 { use mt::{BoundedCurve, ParametricCurve}; - let pts: Vec = wire + let ring: Ring = wire .edge_iter() .flat_map(|e| { let c = e.oriented_curve(); @@ -149,7 +149,7 @@ fn turn(wire: &mt::Wire, n: Vec3) -> f64 { [from_p3(e.front().point()), from_p3(c.subs((a + b) * 0.5))] }) .collect(); - pts.iter().zip(pts.iter().cycle().skip(1)).map(|(a, b)| a.cross(*b).dot(n)).sum() + ring.area_vector().dot(n) } fn rim_loops(wires: &[mt::Wire], n: Vec3) -> Result<(&mt::Wire, &mt::Wire)> { diff --git a/crates/kernel/src/ops.rs b/crates/kernel/src/ops.rs index a69977cbb..8d95b7904 100644 --- a/crates/kernel/src/ops.rs +++ b/crates/kernel/src/ops.rs @@ -331,7 +331,7 @@ fn contradicted( let (under_a, under_b) = (|p: Vec3, f: u32| shared().under_cap(p, f, true, tol), |p: Vec3, f: u32| shared().under_cap(p, f, false, tol)); if disjoint { let (ba, bb) = (ma.bounds(), mb.bounds()); - let meet = solidcraft_geom::Aabb3 { min: ba.min.max(bb.min), max: ba.max.min(bb.max) }; + let meet = ba.intersection(&bb); return !meet.is_empty() && (under_surface(ma, ia, ib, tol, true, Some(&meet), &under_a) || under_surface(mb, ib, ia, tol, true, Some(&meet), &under_b)); } @@ -1136,7 +1136,7 @@ fn meeting_size(a: &Body, b: &Body) -> f64 { bb }; let (ba, bb) = (bbox(a), bbox(b)); - let s = solidcraft_geom::Aabb3 { min: ba.min.max(bb.min), max: ba.max.min(bb.max) }.size(); + let s = ba.intersection(&bb).size(); // A closed sweep's section seams need not span its geometry. Roundoff in a flat // vertex box is not a thin meeting region: refining for it // makes millions of triangles and skips the bounded containment shortcut (#2005). @@ -1149,7 +1149,7 @@ fn meeting_size(a: &Body, b: &Body) -> f64 { /// on its seam, so its vertex box says nothing about where its side reaches. fn mesh_meeting_size(a: &solidcraft_geom::Mesh, b: &solidcraft_geom::Mesh) -> f64 { let (ba, bb) = (a.bounds(), b.bounds()); - let s = solidcraft_geom::Aabb3 { min: ba.min.max(bb.min), max: ba.max.min(bb.max) }.size(); + let s = ba.intersection(&bb).size(); if s.x > 0.0 && s.y > 0.0 && s.z > 0.0 { s.x.min(s.y).min(s.z) } else { f64::INFINITY } } @@ -1477,7 +1477,7 @@ where let fine_tols: Vec = match &meshes { (Some(ma), Some(mb)) if a.solid.boundaries().len() == 1 && b.solid.boundaries().len() == 1 => { let (ba, bb) = (ma.bounds(), mb.bounds()); - let s = solidcraft_geom::Aabb3 { min: ba.min.max(bb.min), max: ba.max.min(bb.max) }.size(); + let s = ba.intersection(&bb).size(); // The thinner operand's thickness (twice its volume over its area: a plate's // thickness, a rod's radius) bounds what the tolerance must resolve as well. let thickness = |m: &solidcraft_geom::Mesh| { @@ -2005,8 +2005,7 @@ fn union_apart_untimed(bodies: &[Body]) -> Result> { if bb.is_empty() { return Ok(None); } - let pad = Vec3::new(1.0, 1.0, 1.0) * (2.0 * tol); - boxes.push(solidcraft_geom::Aabb3 { min: bb.min - pad, max: bb.max + pad }); + boxes.push(bb.inflated(2.0 * tol)); } // Sweep along x: only boxes whose x ranges overlap are compared. let mut order: Vec = (0..boxes.len()).collect(); diff --git a/crates/kernel/src/polybool.rs b/crates/kernel/src/polybool.rs index bff22d0e5..ca72b5930 100644 --- a/crates/kernel/src/polybool.rs +++ b/crates/kernel/src/polybool.rs @@ -5,7 +5,7 @@ use std::collections::{BTreeMap, BTreeSet, HashMap}; -use solidcraft_geom::{Mesh, Vec3}; +use solidcraft_geom::{Aabb3, Mesh, Vec3}; use truck_modeling::{self as mt, builder}; use crate::body::{Body, Solid, edge_order, from_p3, p3}; @@ -365,11 +365,7 @@ fn faceted_boolean_untimed(a: &Body, b: &Mesh, op: BoolOp, tol: f64) -> Result MAX_POLYS { return Err(KernelError::Failed("the bodies are too detailed to facet".into())); } - let (lo, hi) = b - .positions - .iter() - .fold((Vec3::new(f64::MAX, f64::MAX, f64::MAX), Vec3::new(f64::MIN, f64::MIN, f64::MIN)), |(l, h), p| (l.min(*p), h.max(*p))); - let size = if b.positions.is_empty() { a.size() } else { a.size().max((hi - lo).len()) }; + let size = if b.positions.is_empty() { a.size() } else { a.size().max(b.positions.iter().copied().collect::().diagonal()) }; // Fine facets of curved faces meet at shallow angles, where the coplanar test decides // whether the pieces' boundaries come out consistent: try a few tolerances, and take the // first whose result is watertight and agrees with the complementary boolean (A − B and diff --git a/crates/kernel/src/prism.rs b/crates/kernel/src/prism.rs index 9fb54fd4a..68590a4f4 100644 --- a/crates/kernel/src/prism.rs +++ b/crates/kernel/src/prism.rs @@ -8,7 +8,7 @@ use std::borrow::Cow; -use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2, Vec3}; +use solidcraft_geom::{Aabb2, Loop2, Plane, Region2, Seg2, Vec2, Vec3}; use truck_modeling as mt; use crate::body::{Body, from_p3}; @@ -903,11 +903,10 @@ fn inside_loop(lp: &Loop2, p: Vec2) -> bool { let scale = 1.0 + p.x.abs().max(p.y.abs()); // A point clear of the loop's box (by more than the ray shifts below) is outside it: skip // the costly tests, which a region with a thousand cut-outs runs for every probe (#732). - if let Some((lo, hi)) = loop_box(lp) { - let m = scale * 1e-6; - if p.x < lo.x - m || p.x > hi.x + m || p.y < lo.y - m || p.y > hi.y + m { - return false; - } + if let Some(b) = loop_box(lp) + && !b.inflated(scale * 1e-6).contains(p) + { + return false; } // A point on the loop keeps the half-open answer. if lp.segs.iter().any(|s| s.point_at(closest_param(s, p)).dist(p) < scale * 1e-9) { @@ -928,21 +927,16 @@ fn inside_loop(lp: &Loop2, p: Vec2) -> bool { } /// A box holding a loop of lines and arcs (an arc's whole circle); None for other curves. -fn loop_box(lp: &Loop2) -> Option<(Vec2, Vec2)> { - let mut lo = Vec2::new(f64::MAX, f64::MAX); - let mut hi = Vec2::new(f64::MIN, f64::MIN); - let mut add = |a: Vec2, b: Vec2| { - lo = Vec2::new(lo.x.min(a.x), lo.y.min(a.y)); - hi = Vec2::new(hi.x.max(b.x), hi.y.max(b.y)); - }; +fn loop_box(lp: &Loop2) -> Option { + let mut b = Aabb2::EMPTY; for seg in &lp.segs { - match *seg { - Seg2::Line { a, b } => add(Vec2::new(a.x.min(b.x), a.y.min(b.y)), Vec2::new(a.x.max(b.x), a.y.max(b.y))), - Seg2::Arc { center, radius, .. } => add(center - Vec2::new(radius.abs(), radius.abs()), center + Vec2::new(radius.abs(), radius.abs())), + b = b.union(&match *seg { + Seg2::Line { a, b } => Aabb2 { min: Vec2::new(a.x.min(b.x), a.y.min(b.y)), max: Vec2::new(a.x.max(b.x), a.y.max(b.y)) }, + Seg2::Arc { center, radius, .. } => Aabb2 { min: center, max: center }.inflated(radius.abs()), _ => return None, - } + }); } - (lo.x <= hi.x && lo.y <= hi.y && [lo.x, lo.y, hi.x, hi.y].iter().all(|v| v.is_finite())).then_some((lo, hi)) + (!b.is_empty() && b.min.is_finite() && b.max.is_finite()).then_some(b) } /// [`inside_loop`] with the ray along +x from `p` taken as given. @@ -1071,12 +1065,9 @@ fn dist_to(regions: &[Region2], p: Vec2) -> f64 { } /// The bounding box of a line or an arc, grown by twice the tolerance (and by the rounding of -/// its own corners): (min, max). Whatever lies within the tolerance of the segment lies in the -/// box. `None` for other segments and for values that are not finite: no box, and nothing is -/// skipped for it. -type SegBox = (Vec2, Vec2); - -fn seg_box(s: &Seg2, tol: f64) -> Option { +/// its own corners). Whatever lies within the tolerance of the segment lies in the box. `None` +/// for other segments and for values that are not finite: no box, and nothing is skipped for it. +fn seg_box(s: &Seg2, tol: f64) -> Option { let mut pts = vec![s.start(), s.end()]; match *s { Seg2::Line { .. } => {} @@ -1093,31 +1084,29 @@ fn seg_box(s: &Seg2, tol: f64) -> Option { } _ => return None, } - let lo = pts.iter().fold(Vec2::new(f64::INFINITY, f64::INFINITY), |m, p| Vec2::new(m.x.min(p.x), m.y.min(p.y))); - let hi = pts.iter().fold(Vec2::new(f64::NEG_INFINITY, f64::NEG_INFINITY), |m, p| Vec2::new(m.x.max(p.x), m.y.max(p.y))); let g = tol * 2.0 + 1e-12 * pts.iter().fold(0.0, |m: f64, p| m.max(p.x.abs()).max(p.y.abs())); - (pts.iter().all(|p| p.is_finite()) && g.is_finite()).then_some((Vec2::new(lo.x - g, lo.y - g), Vec2::new(hi.x + g, hi.y + g))) + (pts.iter().all(|p| p.is_finite()) && g.is_finite()).then(|| pts.iter().copied().collect::().inflated(g)) } -fn boxes_meet(a: Option, b: Option) -> bool { +fn boxes_meet(a: Option, b: Option) -> bool { match (a, b) { - (Some((a0, a1)), Some((b0, b1))) => a0.x <= b1.x && b0.x <= a1.x && a0.y <= b1.y && b0.y <= a1.y, + (Some(a), Some(b)) => a.meets(&b), _ => true, } } -fn box_holds(b: Option, p: Vec2) -> bool { - b.is_none_or(|(lo, hi)| p.x >= lo.x && p.x <= hi.x && p.y >= lo.y && p.y <= hi.y) +fn box_holds(b: Option, p: Vec2) -> bool { + b.is_none_or(|b| b.contains(p)) } /// Distance from `p` to the nearest of `segs` whose box holds it: infinite when none does (no /// segment is within the tolerance of `p` then). -fn near_dist(segs: &[Seg2], boxes: &[Option], p: Vec2) -> f64 { +fn near_dist(segs: &[Seg2], boxes: &[Option], p: Vec2) -> f64 { segs.iter().zip(boxes).filter(|(_, b)| box_holds(**b, p)).map(|(s, _)| s.point_at(closest_param(s, p)).dist(p)).fold(f64::INFINITY, f64::min) } /// Direction of the first of `segs` through `p` (within `tol`), as it runs. -fn near_dir(segs: &[Seg2], boxes: &[Option], p: Vec2, tol: f64) -> Option { +fn near_dir(segs: &[Seg2], boxes: &[Option], p: Vec2, tol: f64) -> Option { let (s, t) = segs .iter() .zip(boxes) @@ -3194,10 +3183,10 @@ mod planar_tests { let r = 10.0 * std::f64::consts::FRAC_1_SQRT_2; let arc = Seg2::Arc { center: Vec2::ZERO, radius: 10.0, start: std::f64::consts::FRAC_PI_4, sweep: std::f64::consts::FRAC_PI_2 }; for s in [arc, arc.reversed()] { - let (lo, hi) = seg_box(&s, 1e-3).unwrap(); + let Aabb2 { min: lo, max: hi } = seg_box(&s, 1e-3).unwrap(); assert!(lo.dist(Vec2::new(-r - 2e-3, r - 2e-3)) < 1e-9 && hi.dist(Vec2::new(r + 2e-3, 10.0 + 2e-3)) < 1e-9, "{lo:?} {hi:?}"); } - let (lo, hi) = seg_box(&Seg2::Line { a: Vec2::new(3.0, -1.0), b: Vec2::new(-2.0, 4.0) }, 0.5).unwrap(); + let Aabb2 { min: lo, max: hi } = seg_box(&Seg2::Line { a: Vec2::new(3.0, -1.0), b: Vec2::new(-2.0, 4.0) }, 0.5).unwrap(); assert!(lo.dist(Vec2::new(-3.0, -2.0)) < 1e-9 && hi.dist(Vec2::new(4.0, 5.0)) < 1e-9, "{lo:?} {hi:?}"); // A line 3 tolerances above the arc's top meets its box (each is grown by two); one // 5 tolerances above does not. No box (a free-form segment, a value that is not diff --git a/crates/kernel/src/prism_measure.rs b/crates/kernel/src/prism_measure.rs index 3f17768bb..f0cf64f58 100644 --- a/crates/kernel/src/prism_measure.rs +++ b/crates/kernel/src/prism_measure.rs @@ -1,7 +1,7 @@ //! Independent current-geometry intervals for uniform prisms. //! These are not mesh measurements or certificates of construction history. use crate::body::from_p3; -use solidcraft_geom::{Plane, Seg2, Vec2, Vec3}; +use solidcraft_geom::{Plane, Ring, Seg2, Vec2, Vec3}; use truck_modeling as mt; #[derive(Clone, Copy, Debug)] @@ -46,7 +46,7 @@ fn green_interval(segment: &Seg2, tolerance: f64) -> Option { } struct CapLoop { - segments: Vec, + segments: Ring, area: Interval, } @@ -331,15 +331,15 @@ fn wall_supports_cap(surface: &mt::Surface, edge: &mt::Edge, plane: &Plane, leve let Some(fit) = crate::prism_curve::segment(&support, plane, tol, work) else { continue; }; - let fit_loop = CapLoop { segments: fit.clone(), area: Interval::enclosing(0., 0.)? }; + let fit_loop = CapLoop { segments: Ring::from(fit.clone()), area: Interval::enclosing(0., 0.)? }; if let Some((center, radius)) = circle(&fit_loop, tol * 8.) && cap.iter().all(|s| matches!(*s,Seg2::Arc {center:c,radius:r,..} if c.dist(center)+(r-radius).abs()<=tol*8.)) { return Some(true); } let same = loops_same( - &CapLoop { segments: cap.clone(), area: Interval::enclosing(0., 0.)? }, - &CapLoop { segments: fit, area: Interval::enclosing(0., 0.)? }, + &CapLoop { segments: Ring::from(cap.clone()), area: Interval::enclosing(0., 0.)? }, + &CapLoop { segments: Ring::from(fit), area: Interval::enclosing(0., 0.)? }, tol * 8., work, )?; @@ -442,11 +442,10 @@ fn separated_material(loops: &[CapLoop], clearance: f64, work: &mut usize) -> Op } let mut turn = 0.; let mut angular_error = 0.; - for (i, s) in outer.segments.iter().enumerate() { + for (i, (s, next)) in outer.segments.edges().enumerate() { let Seg2::Line { a, b } = *s else { return None; }; - let next = outer.segments.get((i + 1) % outer.segments.len())?; let x = b - a; let y = next.end() - next.start(); turn += x.cross(y).atan2(x.dot(y)); @@ -735,8 +734,9 @@ fn cap_loop(wire: &mt::Wire, plane: &Plane, tolerance: f64, work: &mut usize) -> } // Curve endpoints already agree with actual shared vertices in the // whole-span proof. Check the fitted representation's continuity too. - for i in 0..segments.len() { - if segments.get(i)?.end().dist(segments.get((i + 1) % segments.len())?.start()) > 2. * tolerance { + let segments = Ring::new(segments); + for (a, b) in segments.edges() { + if a.end().dist(b.start()) > 2. * tolerance { return None; } } @@ -872,7 +872,8 @@ mod tests { #[test] fn winding_retracing_and_uncertain_material_do_not_get_certificates() { let arc = Seg2::Arc { center: Vec2::ZERO, radius: 6., start: 0., sweep: std::f64::consts::TAU }; - let retraced = CapLoop { segments: vec![arc, arc.reversed(), arc], area: Interval::enclosing(36. * std::f64::consts::PI, 1e-8).unwrap() }; + let retraced = + CapLoop { segments: Ring::from([arc, arc.reversed(), arc]), area: Interval::enclosing(36. * std::f64::consts::PI, 1e-8).unwrap() }; assert!(circle(&retraced, 1e-6).is_none()); let region = solidcraft_geom::Loop2::polygon(&[Vec2::ZERO, Vec2::new(20., 0.), Vec2::new(20., 20.), Vec2::new(0., 20.)]); let doubled = CapLoop { segments: region.segs.iter().chain(®ion.segs).copied().collect(), area: Interval::enclosing(800., 1e-8).unwrap() }; diff --git a/crates/kernel/src/provenance.rs b/crates/kernel/src/provenance.rs index 354625b63..844a203d1 100644 --- a/crates/kernel/src/provenance.rs +++ b/crates/kernel/src/provenance.rs @@ -10,7 +10,7 @@ use std::collections::BTreeSet; -use solidcraft_geom::{Mesh, Plane, Region2, Seg2, Vec2, Vec3}; +use solidcraft_geom::{Aabb3, Mesh, Plane, Region2, Seg2, Vec2, Vec3}; use crate::Result; use crate::body::Body; @@ -22,30 +22,19 @@ const SAMPLES: usize = 24; /// A face's triangles with their unit normals, and its box. struct FaceTris { tris: Vec<([Vec3; 3], Vec3)>, - lo: Vec3, - hi: Vec3, + bounds: Aabb3, area: f64, } fn face_tris(m: &Mesh) -> Vec { let n = m.tri_face.iter().copied().max().map(|x| x as usize + 1).unwrap_or(0); - let mut out: Vec = (0..n) - .map(|_| FaceTris { - tris: Vec::new(), - lo: Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY), - hi: Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY), - area: 0.0, - }) - .collect(); + let mut out: Vec = (0..n).map(|_| FaceTris { tris: Vec::new(), bounds: Aabb3::EMPTY, area: 0.0 }).collect(); for (t, f) in m.triangles.iter().zip(&m.tri_face) { let (Some(slot), Some(p)) = (out.get_mut(*f as usize), m.tri(t)) else { continue }; let c = (p[1] - p[0]).cross(p[2] - p[0]); let Some(nrm) = c.normalized() else { continue }; slot.area += c.len() * 0.5; - for q in p { - slot.lo = slot.lo.min(q); - slot.hi = slot.hi.max(q); - } + slot.bounds.extend(p); slot.tris.push((p, nrm)); } out @@ -85,7 +74,7 @@ fn closest_on_tri(p: Vec3, [a, b, c]: [Vec3; 3]) -> Vec3 { /// Does point `p` with normal `n` lie on the face (within `tol`, normals along each other)? fn on_face(f: &FaceTris, p: Vec3, n: Vec3, tol: f64) -> bool { - if p.x < f.lo.x - tol || p.y < f.lo.y - tol || p.z < f.lo.z - tol || p.x > f.hi.x + tol || p.y > f.hi.y + tol || p.z > f.hi.z + tol { + if !f.bounds.inflated(tol).contains(p) { return false; } // Either side: a cut's tool faces come out turned inside out. diff --git a/crates/kernel/src/sew.rs b/crates/kernel/src/sew.rs index c8c26b8b7..ce9123dcb 100644 --- a/crates/kernel/src/sew.rs +++ b/crates/kernel/src/sew.rs @@ -9,7 +9,7 @@ use std::collections::HashMap; use std::sync::Arc; use mt::builder; -use solidcraft_geom::Vec3; +use solidcraft_geom::{Ring, Vec3}; use truck_modeling as mt; use crate::body::{Body, Solid, p3, v3}; @@ -428,7 +428,8 @@ fn edge_sheets(faces: &[FaceSpec], group: &[(EdgeUse, Vec3, Vec3)]) -> Result<[[ j -= 1; } } - let wedges: Vec<_> = rays.iter().zip(rays.iter().cycle().skip(1)).collect(); + let rays = Ring::new(rays); + let wedges: Vec<_> = rays.edges().collect(); // Each wedge's faces must use the edge in opposite directions, and be told apart (faces // leaving the same way and turning alike lie on each other). let same_way = |p: f64, q: f64| { diff --git a/crates/kernel/src/step_in/geom.rs b/crates/kernel/src/step_in/geom.rs index ad024c1ab..c0ecd7c26 100644 --- a/crates/kernel/src/step_in/geom.rs +++ b/crates/kernel/src/step_in/geom.rs @@ -10,6 +10,7 @@ use std::f64::consts::{FRAC_PI_2, PI, TAU}; use mt::{BoundedCurve, Cut, InnerSpace, Invertible, MetricSpace, ParametricCurve, ParametricSurface3D, SearchNearestParameter}; +use solidcraft_geom::Ring; use truck_modeling as mt; use super::Ctx; @@ -711,8 +712,8 @@ fn largest_gap(angles: &[f64]) -> Option<(f64, f64)> { } a.sort_by(f64::total_cmp); let (mut best, mut mid) = (0.0, 0.0); - for i in 0..a.len() { - let (Some(&x), Some(&y)) = (a.get(i), a.get((i + 1) % a.len())) else { continue }; + let a = Ring::new(a); + for (i, (&x, &y)) in a.edges().enumerate() { let gap = if i + 1 == a.len() { y + TAU - x } else { y - x }; if gap > best { best = gap; diff --git a/crates/kernel/src/tess/cutgrid.rs b/crates/kernel/src/tess/cutgrid.rs index 2c53dc8a7..5c8f11099 100644 --- a/crates/kernel/src/tess/cutgrid.rs +++ b/crates/kernel/src/tess/cutgrid.rs @@ -5,6 +5,8 @@ //! added. The boundary stays exactly the shared edge nodes, so the face meets its neighbours //! exactly, and only the band next to the boundary is irregular (cut-cell meshing). +use solidcraft_geom::Ring; + use super::cdt; use super::motorcycle::Trace; @@ -196,6 +198,7 @@ pub(crate) fn cut_grid( across.push(c); } } + let poly = Ring::new(poly); if poly.len() == 4 { let [a, b, c, d] = [*poly.first()?, *poly.get(1)?, *poly.get(2)?, *poly.get(3)?]; tris.push([a, b, c]); @@ -205,14 +208,13 @@ pub(crate) fn cut_grid( let centre = [0.5 * (lu.at.get(i0)? + lu.at.get(i1)?), 0.5 * (lv.at.get(j0)? + lv.at.get(j1)?)]; let m = u32::try_from(n + extra.len()).ok()?; extra.push(centre); - for k in 0..poly.len() { - tris.push([m, *poly.get(k)?, *poly.get((k + 1) % poly.len())?]); + for (&a, &b) in poly.edges() { + tris.push([m, a, b]); } } - for k in 0..poly.len() { - let (ci, cj) = *across.get(k)?; + for ((&a, &b), &(ci, cj)) in poly.edges().zip(&across) { if !kept(ci, cj) { - stairs.push((*poly.get(k)?, *poly.get((k + 1) % poly.len())?)); + stairs.push((a, b)); } } } diff --git a/crates/kernel/src/tess/mod.rs b/crates/kernel/src/tess/mod.rs index 8c1cfc731..8d87a199b 100644 --- a/crates/kernel/src/tess/mod.rs +++ b/crates/kernel/src/tess/mod.rs @@ -469,7 +469,7 @@ fn plan_pieces(f: &Region) -> Option<(Vec<[f64; 2]>, Vec<[u32; 3]>)> { let mut tris: Vec<[u32; 3]> = Vec::new(); for pc in &pieces { // The patch's own loops, numbered from zero. - let mut ids: Vec = pc.ring.clone(); + let mut ids: Vec = pc.ring.to_vec(); let mut ranges = vec![std::ops::Range { start: 0, end: pc.ring.len() }]; for hole in &pc.holes { ranges.push(ids.len()..ids.len() + hole.len()); @@ -494,12 +494,7 @@ fn plan_pieces(f: &Region) -> Option<(Vec<[f64; 2]>, Vec<[u32; 3]>)> { a >= n || b >= n || !f.ranges.iter().any(|r| r.contains(&a) && r.contains(&b) && (a.abs_diff(b) == 1 || a.abs_diff(b) == r.len() - 1)) }; let ring = &pc.ring; - let switches: Vec = (0..ring.len()) - .filter(|&k| { - let (p, c, x) = (ring.get((k + ring.len() - 1) % ring.len()), ring.get(k), ring.get((k + 1) % ring.len())); - matches!((p, c, x), (Some(&p), Some(&c), Some(&x)) if is_cut(p, c) != is_cut(c, x)) - }) - .collect(); + let switches: Vec = ring.corners().enumerate().filter(|&(_, (&p, &c, &x))| is_cut(p, c) != is_cut(c, x)).map(|(k, _)| k).collect(); // The patch is a rectangle in (u, v) with corners cut by free boundary (Lyon et al. §4; // completed virtually in §4.2): its bounding box. A grid needs four real sides, so each // corner is the node furthest out towards the box's corner (in the box's own diff --git a/crates/kernel/src/tess/pieces.rs b/crates/kernel/src/tess/pieces.rs index 9aa76273c..c2a9bbbb9 100644 --- a/crates/kernel/src/tess/pieces.rs +++ b/crates/kernel/src/tess/pieces.rs @@ -8,6 +8,8 @@ use std::collections::HashMap; +use solidcraft_geom::Ring; + /// Where a cut segment ends. #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) enum End { @@ -33,8 +35,8 @@ pub(crate) struct Segment { /// by the cut nodes, counter-clockwise (holes clockwise) in (u, v). #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct Piece { - pub ring: Vec, - pub holes: Vec>, + pub ring: Ring, + pub holes: Vec>, } /// Cut the face bounded by `loops` (ranges of `boundary`) along `segments`, measured in the @@ -233,7 +235,7 @@ pub(crate) fn cut( before.map(|(_, e)| *e).or_else(|| list.iter().find(|(_, e)| half.get(*e).is_some_and(|x| x.1 == u)).map(|(_, e)| *e)) }; let mut seen = vec![false; half.len()]; - let mut rings: Vec> = Vec::new(); + let mut rings: Vec> = Vec::new(); for h0 in 0..half.len() { if *seen.get(h0)? { continue; @@ -251,18 +253,11 @@ pub(crate) fn cut( return None; } } - rings.push(ring); + rings.push(Ring::new(ring)); } - let area = |ring: &[u32]| -> Option { - let mut s = 0.0; - for k in 0..ring.len() { - let (a, b) = (pos(*ring.get(k)?)?, pos(*ring.get((k + 1) % ring.len())?)?); - s += a[0] * b[1] - b[0] * a[1]; - } - Some(0.5 * s) - }; + let area = |ring: &Ring| -> Option { Some(ring.iter().map(|&k| pos(k)).collect::>>()?.signed_area()) }; let mut pieces: Vec = Vec::new(); - let mut holes: Vec> = Vec::new(); + let mut holes: Vec> = Vec::new(); for r in rings { if area(&r)? > 0.0 { pieces.push(Piece { ring: r, holes: Vec::new() }); @@ -273,10 +268,10 @@ pub(crate) fn cut( // A loop no cut reached is a hole of the patch around it. for h in holes { let p = pos(*h.first()?)?; - let contains = |ring: &[u32]| { + let contains = |ring: &Ring| { let mut odd = false; - for k in 0..ring.len() { - let (Some(a), Some(b)) = (ring.get(k).and_then(|x| pos(*x)), ring.get((k + 1) % ring.len()).and_then(|x| pos(*x))) else { continue }; + for (&a, &b) in ring.edges() { + let (Some(a), Some(b)) = (pos(a), pos(b)) else { continue }; if (a[1] > p[1]) != (b[1] > p[1]) && p[0] < a[0] + (p[1] - a[1]) / (b[1] - a[1]) * (b[0] - a[0]) { odd = !odd; } @@ -296,13 +291,8 @@ pub(crate) fn cut( mod tests { use super::*; - fn area(all: &[[f64; 2]], ring: &[u32]) -> f64 { - (0..ring.len()) - .map(|k| { - let (a, b) = (all[ring[k] as usize], all[ring[(k + 1) % ring.len()] as usize]); - 0.5 * (a[0] * b[1] - b[0] * a[1]) - }) - .sum() + fn area(all: &[[f64; 2]], ring: &Ring) -> f64 { + ring.iter().map(|&k| all[k as usize]).collect::>().signed_area() } /// A square cut by four segments meeting at its centre (one point inside the face, shared) diff --git a/crates/kernel/src/tess/seam.rs b/crates/kernel/src/tess/seam.rs index 21cb6ef13..13b516158 100644 --- a/crates/kernel/src/tess/seam.rs +++ b/crates/kernel/src/tess/seam.rs @@ -302,8 +302,7 @@ fn crosses(uv: &[[f64; 2]], x0: f64, x1: f64) -> bool { fn clip(path: &[[f64; 2]], pts: &[Vec3], x0: f64, x1: f64, out: &mut Vec) { let inside = |q: &[f64; 2]| q[0] > x0 && q[0] < x1; let mut cur: Option = None; - for k in 0..path.len().saturating_sub(1) { - let (Some(a), Some(b), Some(pa), Some(pb)) = (path.get(k), path.get(k + 1), pts.get(k), pts.get(k + 1)) else { break }; + for ((a, b), (pa, pb)) in path.iter().zip(path.iter().skip(1)).zip(pts.iter().zip(pts.iter().skip(1))) { let at = |x: f64| { let t = ((x - a[0]) / (b[0] - a[0])).clamp(0.0, 1.0); ([x, a[1] + (b[1] - a[1]) * t], *pa + (*pb - *pa) * t) diff --git a/crates/kernel/src/tests.rs b/crates/kernel/src/tests.rs index bd668d78e..2aaa7738e 100644 --- a/crates/kernel/src/tests.rs +++ b/crates/kernel/src/tests.rs @@ -621,7 +621,7 @@ fn tapered_extrude_swallows_a_short_tip() { let meet = |(p0, t0): (Vec2, Vec2), (p1, t1): (Vec2, Vec2)| p0 + t0 * ((p1 - p0).cross(t1) / t0.cross(t1)); let (low, high, left) = (moved(pts[0], pts[1]), moved(pts[2], pts[3]), moved(pts[3], pts[0])); let top = [meet(left, low), meet(low, high), meet(high, left)]; - let area = |q: &[Vec2]| 0.5 * q.iter().zip(q.iter().cycle().skip(1)).map(|(a, b)| a.cross(*b)).sum::(); + let area = |q: &[Vec2]| solidcraft_geom::Ring::from(q.to_vec()).signed_area(); // Halfway up, each side edge's midpoint (the two tip corners both run to the top's tip). let mid = [pts[0].lerp(top[0], 0.5), pts[1].lerp(top[1], 0.5), pts[2].lerp(top[1], 0.5), pts[3].lerp(top[2], 0.5)]; let v = h / 6.0 * (area(&pts) + 4.0 * area(&mid) + area(&top)); diff --git a/crates/sketch/src/ends.rs b/crates/sketch/src/ends.rs index f1838b878..f63328141 100644 --- a/crates/sketch/src/ends.rs +++ b/crates/sketch/src/ends.rs @@ -9,7 +9,7 @@ //! An end is tied when it is shared with another curve's end, joined to one by coincident //! constraints, or held on a curve (point on curve, midpoint). -use solidcraft_geom::{Seg2, Vec2}; +use solidcraft_geom::{Aabb2, Seg2, Vec2}; use crate::model::{ConstraintKind, CurveKind, Sketch}; use crate::union_find::{find, union}; @@ -59,18 +59,11 @@ fn profile_curve(sk: &Sketch, ci: usize) -> bool { } /// A box around a segment (conservative for curved ones). -fn seg_box(s: &Seg2) -> (Vec2, Vec2) { - let hull = |pts: &[Vec2]| { - pts.iter().fold((Vec2::new(f64::INFINITY, f64::INFINITY), Vec2::new(f64::NEG_INFINITY, f64::NEG_INFINITY)), |(lo, hi), p| { - (Vec2::new(lo.x.min(p.x), lo.y.min(p.y)), Vec2::new(hi.x.max(p.x), hi.y.max(p.y))) - }) - }; +fn seg_box(s: &Seg2) -> Aabb2 { + let hull = |pts: &[Vec2]| pts.iter().copied().collect::(); match *s { Seg2::Line { a, b } => hull(&[a, b]), - Seg2::Arc { center, radius, .. } => { - let r = Vec2::new(radius.abs(), radius.abs()); - (center - r, center + r) - } + Seg2::Arc { center, radius, .. } => Aabb2 { min: center, max: center }.inflated(radius.abs()), Seg2::Cubic { p0, p1, p2, p3 } => hull(&[p0, p1, p2, p3]), Seg2::Conic { a, apex, b, .. } => hull(&[a, apex, b]), Seg2::Bezier { n, p } => hull(p.get(..=usize::from(n)).unwrap_or(p.as_slice())), @@ -151,7 +144,7 @@ pub fn loose_ends(sk: &Sketch) -> EndReport { } let curve_ends = c.kind.ends(); for seg in sk.segs(ci) { - let (lo, hi) = seg_box(&seg); + let Aabb2 { min: lo, max: hi } = seg_box(&seg); let first = free.partition_point(|f| f.2.x < lo.x - END_TOL); for (k, &(p, own, at)) in free.iter().enumerate().skip(first) { if at.x > hi.x + END_TOL { diff --git a/crates/sketch/src/link.rs b/crates/sketch/src/link.rs index 2490d74f1..2690f934f 100644 --- a/crates/sketch/src/link.rs +++ b/crates/sketch/src/link.rs @@ -7,7 +7,7 @@ //! constants; they still bound profiles and take constraints and dimensions like any curve. use serde::{Deserialize, Serialize}; -use solidcraft_geom::{Vec2, Vec3}; +use solidcraft_geom::{Aabb2, Vec2, Vec3}; use crate::model::{Curve, CurveKind, Result, Sketch, SketchError, in_range, radius_in_range}; @@ -822,9 +822,8 @@ impl Sketch { { let old: Vec = points.iter().filter_map(|i| self.point(*i)).collect(); let normalized = |ps: &[Vec2]| -> Vec { - let lo = ps.iter().fold(Vec2::new(f64::INFINITY, f64::INFINITY), |a, p| Vec2::new(a.x.min(p.x), a.y.min(p.y))); - let hi = ps.iter().fold(Vec2::new(f64::NEG_INFINITY, f64::NEG_INFINITY), |a, p| Vec2::new(a.x.max(p.x), a.y.max(p.y))); - ps.iter().map(|p| Vec2::new((p.x - lo.x) / (hi.x - lo.x).max(1e-9), (p.y - lo.y) / (hi.y - lo.y).max(1e-9))).collect() + let b: Aabb2 = ps.iter().copied().collect(); + ps.iter().map(|p| b.relative(*p)).collect() }; let loop_roles_required = self.link(id).is_some_and(|l| matches!(l.source, LinkSource::Face { .. })) && cur.iter().chain(&lay.curves).all(|c| matches!(c, LCurve::Line(..) | LCurve::Arc(..) | LCurve::Circle(..))) diff --git a/crates/sketch/src/link_loops.rs b/crates/sketch/src/link_loops.rs index 9f669f205..0125ed95e 100644 --- a/crates/sketch/src/link_loops.rs +++ b/crates/sketch/src/link_loops.rs @@ -2,14 +2,13 @@ //! Endpoint walks exclude support centres. Crossings/touches refuse before nesting. use super::{LCurve, curve_points}; use crate::{Shape, intersections}; -use solidcraft_geom::Vec2; +use solidcraft_geom::{Aabb2, Vec2}; use std::f64::consts::TAU; struct Boundary { curves: Vec, shapes: Vec, - lo: Vec2, - hi: Vec2, + bounds: Aabb2, depth: usize, signature: [usize; 3], } @@ -180,8 +179,7 @@ fn boundaries(curves: &[LCurve], pts: &[Vec2]) -> Option> { pending.extend(incidence.get(b)?); } } - let mut lo = Vec2::new(f64::INFINITY, f64::INFINITY); - let mut hi = Vec2::new(f64::NEG_INFINITY, f64::NEG_INFINITY); + let mut bounds = Aabb2::EMPTY; let mut signature = [0; 3]; let mut bound_shapes = Vec::new(); for i in &members { @@ -195,10 +193,7 @@ fn boundaries(curves: &[LCurve], pts: &[Vec2]) -> Option> { } } } - for p in candidates { - lo = Vec2::new(lo.x.min(p.x), lo.y.min(p.y)); - hi = Vec2::new(hi.x.max(p.x), hi.y.max(p.y)); - } + bounds.extend(candidates); signature[match curves.get(*i)? { LCurve::Line(..) => 0, LCurve::Arc(..) => 1, @@ -206,9 +201,9 @@ fn boundaries(curves: &[LCurve], pts: &[Vec2]) -> Option> { }] += 1; bound_shapes.push(shape); } - out.push(Boundary { curves: members, shapes: bound_shapes, lo, hi, depth: 0, signature }); + out.push(Boundary { curves: members, shapes: bound_shapes, bounds, depth: 0, signature }); } - let scale = out.iter().map(|b| (b.hi - b.lo).len()).fold(1.0, f64::max); + let scale = out.iter().map(|b| b.bounds.diagonal()).fold(1.0, f64::max); let tol = (scale * 1e-10).max(1e-7); let mut work = 0usize; for i in 0..out.len() { @@ -260,27 +255,20 @@ fn boundaries(curves: &[LCurve], pts: &[Vec2]) -> Option> { pub(super) fn valid(curves: &[LCurve], points: &[Vec2]) -> bool { boundaries(curves, points).is_some() } -fn normalize(p: Vec2, lo: Vec2, hi: Vec2) -> Vec2 { - Vec2::new((p.x - lo.x) / (hi.x - lo.x).max(1e-9), (p.y - lo.y) / (hi.y - lo.y).max(1e-9)) -} pub(super) fn roles(old_curves: &[LCurve], a: &[Vec2], fresh_curves: &[LCurve], b: &[Vec2]) -> Option { let (previous, incoming) = (boundaries(old_curves, a)?, boundaries(fresh_curves, b)?); if previous.len() != incoming.len() { return None; } - let bounds = |loops: &[Boundary]| { - loops.iter().fold((Vec2::new(f64::INFINITY, f64::INFINITY), Vec2::new(f64::NEG_INFINITY, f64::NEG_INFINITY)), |(lo, hi), x| { - (Vec2::new(lo.x.min(x.lo.x), lo.y.min(x.lo.y)), Vec2::new(hi.x.max(x.hi.x), hi.y.max(x.hi.y))) - }) - }; - let ((alo, ahi), (blo, bhi)) = (bounds(&previous), bounds(&incoming)); + let bounds = |loops: &[Boundary]| loops.iter().fold(Aabb2::EMPTY, |a, x| a.union(&x.bounds)); + let (outer_a, outer_b) = (bounds(&previous), bounds(&incoming)); let mut mapping = Vec::new(); for x in &previous { let mut candidates: Vec<_> = incoming .iter() .enumerate() .filter(|(_, y)| x.depth == y.depth && x.signature == y.signature) - .map(|(i, y)| (i, normalize((x.lo + x.hi) * 0.5, alo, ahi).dist(normalize((y.lo + y.hi) * 0.5, blo, bhi)))) + .map(|(i, y)| (i, outer_a.relative(x.bounds.center()).dist(outer_b.relative(y.bounds.center())))) .collect(); candidates.sort_by(|x, y| x.1.total_cmp(&y.1)); let (i, d) = *candidates.first()?; @@ -290,8 +278,8 @@ pub(super) fn roles(old_curves: &[LCurve], a: &[Vec2], fresh_curves: &[LCurve], let y = incoming.get(i)?; // Preserve the conservative bound on relative boundary changes. This does // not mistake a stationary hole's coordinates for the outer loop's scaling. - let old_size = normalize(x.hi, alo, ahi) - normalize(x.lo, alo, ahi); - let new_size = normalize(y.hi, blo, bhi) - normalize(y.lo, blo, bhi); + let old_size = outer_a.relative(x.bounds.max) - outer_a.relative(x.bounds.min); + let new_size = outer_b.relative(y.bounds.max) - outer_b.relative(y.bounds.min); if old_size.dist(new_size) >= 0.1 { return None; } @@ -306,7 +294,7 @@ pub(super) fn roles(old_curves: &[LCurve], a: &[Vec2], fresh_curves: &[LCurve], for p in curve_points(curves.get(*curve)?) { if !roles.get(p)?.contains(&target) { roles.get_mut(p)?.push(target); - *coordinates.get_mut(p)? += normalize(*pts.get(p)?, loop_.lo, loop_.hi); + *coordinates.get_mut(p)? += loop_.bounds.relative(*pts.get(p)?); } } } @@ -325,7 +313,7 @@ pub(super) fn roles(old_curves: &[LCurve], a: &[Vec2], fresh_curves: &[LCurve], let line_roles = |loops: &[Boundary], curves: &[LCurve], pts: &[Vec2]| -> Option>> { let mut roles = vec![Vec::new(); pts.len()]; for loop_ in loops { - let size = loop_.hi - loop_.lo; + let size = loop_.bounds.max - loop_.bounds.min; for i in &loop_.curves { if let LCurve::Line(a, b) = *curves.get(*i)? { let d = *pts.get(b)? - *pts.get(a)?; diff --git a/crates/sketch/src/model.rs b/crates/sketch/src/model.rs index 9a737038d..605937df5 100644 --- a/crates/sketch/src/model.rs +++ b/crates/sketch/src/model.rs @@ -1,5 +1,5 @@ use serde::{Deserialize, Serialize}; -use solidcraft_geom::{Seg2, Vec2, Vec3}; +use solidcraft_geom::{Aabb2, Seg2, Vec2, Vec3}; use crate::union_find::{find, union}; @@ -1594,18 +1594,7 @@ impl Sketch { /// Axis-aligned bounds of all geometry (for views). pub fn bounds(&self) -> Option<(Vec2, Vec2)> { - let mut lo = Vec2::new(f64::INFINITY, f64::INFINITY); - let mut hi = Vec2::new(f64::NEG_INFINITY, f64::NEG_INFINITY); - let mut any = false; - for i in 0..self.curves.len() { - for s in self.segs(i) { - for p in s.polyline(0.5) { - lo = Vec2::new(lo.x.min(p.x), lo.y.min(p.y)); - hi = Vec2::new(hi.x.max(p.x), hi.y.max(p.y)); - any = true; - } - } - } - any.then_some((lo, hi)) + let b: Aabb2 = (0..self.curves.len()).flat_map(|i| self.segs(i)).flat_map(|s| s.polyline(0.5)).collect(); + (!b.is_empty()).then_some((b.min, b.max)) } } diff --git a/crates/sketch/src/profiles.rs b/crates/sketch/src/profiles.rs index 80346b946..553e9c043 100644 --- a/crates/sketch/src/profiles.rs +++ b/crates/sketch/src/profiles.rs @@ -10,7 +10,7 @@ use std::f64::consts::TAU; use serde::{Deserialize, Serialize}; -use solidcraft_geom::{Loop2, Region2, Seg2, Vec2}; +use solidcraft_geom::{Loop2, Region2, Ring, Seg2, Vec2}; use crate::model::{CurveKind, Sketch}; use crate::shape::{Shape, intersections_within}; @@ -423,12 +423,9 @@ struct Grid { } impl Grid { - fn new(boxes: &[(Vec2, Vec2)]) -> Grid { - let (mut lo, mut hi) = (Vec2::new(f64::INFINITY, f64::INFINITY), Vec2::new(f64::NEG_INFINITY, f64::NEG_INFINITY)); - for (a, b) in boxes { - lo = Vec2::new(lo.x.min(a.x), lo.y.min(a.y)); - hi = Vec2::new(hi.x.max(b.x), hi.y.max(b.y)); - } + fn new(boxes: &[solidcraft_geom::Aabb2]) -> Grid { + let all = boxes.iter().fold(solidcraft_geom::Aabb2::EMPTY, |a, b| a.union(b)); + let (lo, hi) = (all.min, all.max); if !(lo.is_finite() && hi.is_finite()) { return Grid { lo: Vec2::ZERO, size: 1.0 }; } @@ -440,8 +437,8 @@ impl Grid { (((p.x - self.lo.x) / self.size).floor() as i64, ((p.y - self.lo.y) / self.size).floor() as i64) } /// Cells a box covers; None for boxes spanning too many (they are checked against all). - fn cells(&self, b: &(Vec2, Vec2)) -> Option> { - let (c0, c1) = (self.cell(b.0), self.cell(b.1)); + fn cells(&self, b: &solidcraft_geom::Aabb2) -> Option> { + let (c0, c1) = (self.cell(b.min), self.cell(b.max)); if (c1.0 - c0.0 + 1).saturating_mul(c1.1 - c0.1 + 1) > 2048 { return None; } @@ -497,27 +494,9 @@ pub fn without_text_counters(sk: &Sketch, profiles: Vec) -> Vec> = profiles.iter().map(|p| p.region.outer.polyline(1e-3)).collect(); - let boxes: Vec<(Vec2, Vec2)> = polys - .iter() - .map(|pl| { - pl.iter().fold((Vec2::new(f64::INFINITY, f64::INFINITY), Vec2::new(f64::NEG_INFINITY, f64::NEG_INFINITY)), |(lo, hi), p| { - (Vec2::new(lo.x.min(p.x), lo.y.min(p.y)), Vec2::new(hi.x.max(p.x), hi.y.max(p.y))) - }) - }) - .collect(); + let polys: Vec> = profiles.iter().map(|p| p.region.outer.polyline(1e-3)).collect(); + let boxes: Vec = polys.iter().map(|pl| pl.bounds()).collect(); let areas: Vec = profiles.iter().map(|p| p.region.outer.signed_area().abs()).collect(); - let inside = |pl: &[Vec2], p: Vec2| { - let n = pl.len(); - let mut odd = false; - for i in 0..n { - let (Some(a), Some(b)) = (pl.get(i), pl.get((i + 1) % n)) else { continue }; - if (a.y > p.y) != (b.y > p.y) && p.x < a.x + (p.y - a.y) / (b.y - a.y) * (b.x - a.x) { - odd = !odd; - } - } - odd - }; let keep: Vec = (0..profiles.len()) .map(|i| { if !text_only.get(i).copied().unwrap_or(false) { @@ -530,8 +509,8 @@ pub fn without_text_counters(sk: &Sketch, profiles: Vec) -> Vec ai - && boxes.get(j).is_some_and(|(lo, hi)| probe.x >= lo.x && probe.x <= hi.x && probe.y >= lo.y && probe.y <= hi.y) - && polys.get(j).is_some_and(|pl| inside(pl, probe)) + && boxes.get(j).is_some_and(|b| b.contains(probe)) + && polys.get(j).is_some_and(|pl| pl.contains(probe)) }) .count(); depth % 2 == 0 @@ -627,15 +606,19 @@ fn find_profiles_bounded(sk: &Sketch, max_edges: usize) -> Vec { } } // Bounding boxes, and a uniform grid over them: only shapes sharing a cell can meet. - let boxes: Vec<(Vec2, Vec2)> = shapes + let boxes: Vec = shapes .iter() .map(|(_, sh)| match *sh { - Shape::Line { a, b } => (Vec2::new(a.x.min(b.x) - tol, a.y.min(b.y) - tol), Vec2::new(a.x.max(b.x) + tol, a.y.max(b.y) + tol)), - Shape::Round { c, r, .. } => (Vec2::new(c.x - r - tol, c.y - r - tol), Vec2::new(c.x + r + tol, c.y + r + tol)), + Shape::Line { a, b } => { + solidcraft_geom::Aabb2 { min: Vec2::new(a.x.min(b.x), a.y.min(b.y)), max: Vec2::new(a.x.max(b.x), a.y.max(b.y)) }.inflated(tol) + } + Shape::Round { c, r, .. } => { + solidcraft_geom::Aabb2 { min: Vec2::new(c.x - r - tol, c.y - r - tol), max: Vec2::new(c.x + r + tol, c.y + r + tol) } + } }) .collect(); let overlap = |i: usize, j: usize| match (boxes.get(i), boxes.get(j)) { - (Some((a0, a1)), Some((b0, b1))) => a0.x <= b1.x && b0.x <= a1.x && a0.y <= b1.y && b0.y <= a1.y, + (Some(a), Some(b)) => a.meets(b), _ => false, }; let grid = Grid::new(&boxes); @@ -711,8 +694,7 @@ fn find_profiles_bounded(sk: &Sketch, max_edges: usize) -> Vec { let mut anchors: Vec = Vec::new(); if shapes.len() <= 50_000 { let mut whole: Vec = shapes.iter().map(|(_, s)| s.is_full()).collect(); - for i in 0..shapes.len() { - let Some((ci, x)) = shapes.get(i) else { continue }; + for (i, (ci, x)) in shapes.iter().enumerate() { if carrier.get(i) != Some(&i) || !analytic(*ci) { continue; } @@ -1029,15 +1011,8 @@ fn find_profiles_bounded(sk: &Sketch, max_edges: usize) -> Vec { // Nesting: parent = smallest containing loop from another component. Bounding boxes rule // out most pairs before the point-in-loop test. let areas: Vec = loops.iter().map(|(l, _, _, _)| l.signed_area().abs()).collect(); - let boxes: Vec<(Vec2, Vec2)> = loops - .iter() - .map(|(l, _, _, _)| { - l.polyline(1e-3).iter().fold((Vec2::new(f64::INFINITY, f64::INFINITY), Vec2::new(f64::NEG_INFINITY, f64::NEG_INFINITY)), |(lo, hi), p| { - (Vec2::new(lo.x.min(p.x), lo.y.min(p.y)), Vec2::new(hi.x.max(p.x), hi.y.max(p.y))) - }) - }) - .collect(); - let inside_box = |j: usize, p: Vec2| boxes.get(j).is_some_and(|(lo, hi)| p.x >= lo.x && p.x <= hi.x && p.y >= lo.y && p.y <= hi.y); + let boxes: Vec = loops.iter().map(|(l, _, _, _)| l.polyline(1e-3).bounds()).collect(); + let inside_box = |j: usize, p: Vec2| boxes.get(j).is_some_and(|b| b.contains(p)); let mut parent_of: Vec> = vec![None; loops.len()]; for (i, (li, _, ci, _)) in loops.iter().enumerate() { let probe = li.segs.first().map(Seg2::mid).unwrap_or_default(); diff --git a/crates/sketch/src/tests.rs b/crates/sketch/src/tests.rs index c489d0c4e..c77a1bae1 100644 --- a/crates/sketch/src/tests.rs +++ b/crates/sketch/src/tests.rs @@ -840,10 +840,7 @@ fn long_connected_chain_solves() { fn exact_profiles_for_high_degree_and_cut_free_form_curves() { use solidcraft_geom::Seg2; let exact_loop = |p: &Profile| p.region.outer.segs.iter().all(|s| !matches!(s, Seg2::Line { .. }) || s.length() > 1.0); - let closed = |p: &Profile| { - let s = &p.region.outer.segs; - s.iter().zip(s.iter().cycle().skip(1)).all(|(a, b)| a.end().dist(b.start()) < 1e-9) - }; + let closed = |p: &Profile| p.region.outer.joints().all(|(a, b)| a.end().dist(b.start()) < 1e-9); // Degree 5 over six points, closed by a line. let mut sk = Sketch::default(); let ids: Vec = [v(0.0, 0.0), v(4.0, 10.0), v(10.0, 12.0), v(16.0, 12.0), v(22.0, 10.0), v(26.0, 0.0)] diff --git a/crates/sketch/src/text.rs b/crates/sketch/src/text.rs index 4b8d62877..5e218294e 100644 --- a/crates/sketch/src/text.rs +++ b/crates/sketch/src/text.rs @@ -7,7 +7,7 @@ //! ATTRIBUTION.md); [`crate::fonts`] finds others by file path or installed family name. use serde::{Deserialize, Serialize}; -use solidcraft_geom::Vec2; +use solidcraft_geom::{Ring, Vec2}; use crate::fonts::font_data_styled; use crate::link::{LinkGeom, LinkKind, LinkSource, MAX_LINK_ENTITIES}; @@ -303,8 +303,7 @@ impl Path { let closed = first.dist(last) <= 1e-9 * length.max(1.0); let readable = if closed { // Clockwise: the text stands on the outside. - let area: f64 = pts.iter().zip(pts.iter().skip(1)).map(|(a, b)| a.cross(*b)).sum::() + last.cross(first); - area <= 0.0 + Ring::from(pts.clone()).signed_area() <= 0.0 } else { last.x >= first.x - 1e-9 * length }; diff --git a/crates/ui-egui/src/gizmo.rs b/crates/ui-egui/src/gizmo.rs index ebc4d23e1..a1e125f11 100644 --- a/crates/ui-egui/src/gizmo.rs +++ b/crates/ui-egui/src/gizmo.rs @@ -7,7 +7,7 @@ use std::cell::RefCell; use egui::{Color32, Pos2, Rect, Sense, Shape, Stroke, vec2}; -use solidcraft_engine::geom::Vec3; +use solidcraft_engine::geom::{Ring, Vec3}; use crate::theme::Tokens; use crate::viewport::{Proj, projected_polygon}; @@ -121,13 +121,12 @@ fn seg_dist(p: Pos2, a: Pos2, b: Pos2) -> f32 { (a + ab * t).distance(p) } -fn in_quad(p: Pos2, q: &[Pos2]) -> bool { +fn in_quad(p: Pos2, q: &Ring) -> bool { if q.len() < 3 { return false; } let mut sign = 0.0f32; - for i in 0..q.len() { - let (a, b) = (q[i], q[(i + 1) % q.len()]); + for (&a, &b) in q.edges() { let c = (b - a).x * (p - a).y - (b - a).y * (p - a).x; if c.abs() < 1e-6 { continue; @@ -166,7 +165,7 @@ fn along(proj: &Proj, pos: Pos2, o: Vec3, d: Vec3) -> Option { /// The triad's shapes: (handle, screen polygon or polyline, is it a filled area). struct Shapes { arrows: Vec<(usize, Pos2, Pos2)>, - planes: Vec<(usize, Vec)>, + planes: Vec<(usize, Ring)>, rings: Vec<(usize, Vec)>, ball: Pos2, } @@ -183,7 +182,7 @@ fn shapes(proj: &Proj, t: &Triad, l: f64) -> Option { } for i in 0..3 { let (e1, e2) = ring_basis(i); - let q: Vec = [(0.25, 0.25), (0.45, 0.25), (0.45, 0.45), (0.25, 0.45)] + let q: Ring = [(0.25, 0.25), (0.45, 0.25), (0.45, 0.45), (0.25, 0.45)] .iter() .filter_map(|(a, b)| proj.to_screen(c + e1 * (a * l) + e2 * (b * l))) .collect(); diff --git a/crates/ui-egui/src/navigation_cube.rs b/crates/ui-egui/src/navigation_cube.rs index 876e6db7c..fa7f4ff38 100644 --- a/crates/ui-egui/src/navigation_cube.rs +++ b/crates/ui-egui/src/navigation_cube.rs @@ -1,6 +1,7 @@ //! Original, code-drawn navigation cube. Flat faces share invisible picking regions. use super::*; use crate::icons::navigation::{Facet, arrow, curved_arrow, paint_cube}; +use solidcraft_engine::geom::Ring; pub(super) const SIZE: f32 = 112.0; // Paint and picking use the same original coordinate space, scaled as a group. @@ -49,10 +50,9 @@ fn facets(cam: &Camera, c: Pos2, half: f64) -> Vec { let b = project(cam, *b - centre, half); a.y.atan2(a.x).total_cmp(&b.y.atan2(b.x)) }); + let vertices = Ring::new(vertices); let outer_edges = vertices - .iter() - .zip(vertices.iter().cycle().skip(1)) - .take(vertices.len()) + .edges() .map(|(a, b)| [(a.x, b.x), (a.y, b.y), (a.z, b.z)].into_iter().filter(|(a, b)| a.abs() == 1.0 && a == b).count() >= 2) .collect(); let points = vertices.into_iter().map(|v| c + project(cam, v, half)).collect(); @@ -92,12 +92,12 @@ fn facets(cam: &Camera, c: Pos2, half: f64) -> Vec { out } -fn contains(points: &[Pos2], p: Pos2) -> bool { +fn contains(points: &Ring, p: Pos2) -> bool { if !p.is_finite() || points.len() < 3 { return false; } let mut sign = 0.0_f32; - for (a, b) in points.iter().zip(points.iter().cycle().skip(1)).take(points.len()) { + for (a, b) in points.edges() { let edge = *b - *a; let offset = p - *a; let cross = edge.x * offset.y - edge.y * offset.x; diff --git a/crates/ui-egui/src/preview.rs b/crates/ui-egui/src/preview.rs index 633d6e7db..f89ec21c9 100644 --- a/crates/ui-egui/src/preview.rs +++ b/crates/ui-egui/src/preview.rs @@ -15,7 +15,7 @@ use std::sync::mpsc::{Receiver, TryRecvError}; use serde_json::Value; use solidcraft_engine::Session; use solidcraft_engine::doc::ModelState; -use solidcraft_engine::geom::{Aabb3, Mesh, Vec3}; +use solidcraft_engine::geom::{Aabb3, Mesh, Ring, Vec3}; use crate::SolveApp; use crate::gpu::{GpuScene, SceneSlot}; @@ -560,7 +560,7 @@ pub fn build(before: &ModelState, after: &ModelState, c: Colors) -> Built { sc.xray_tri(p.to_f32(), plane.normal().to_f32(), color); } } - for (a, b) in quad.iter().zip(quad.iter().cycle().skip(1)).take(4) { + for (a, b) in Ring::from(quad).edges() { sc.line(a.to_f32(), b.to_f32(), c.added, 1.3, true); } } From 58303ba036c990dd14c331c458c62a73e1a417fc Mon Sep 17 00:00:00 2001 From: phanoob Date: Tue, 20 Oct 2026 03:50:52 +0000 Subject: [PATCH 176/225] Preview: nothing is drawn once the current inputs fail (#3254) (#3256) * claim: #3254 Co-Authored-By: Claude Opus 5.5 * Preview: nothing is drawn once the current inputs fail (#3254) The last good preview stayed up when the current inputs made the feature fail, so the view contradicted the dialog (Extrude at 0 mm still showed the 1 mm extrusion beside its error). Once the result for the current inputs is an error, the preview scene is hidden and the bodies it stood in for come back; while the next preview computes, the last good one still stays up as before. Co-Authored-By: Claude Opus 5.5 * Extrude preview: a zero distance is refused at once (#3254) The straight extrusion feedback gave up on a zero distance, so the preview built a whole scratch design only for the kernel to refuse it, and the old preview hung on until then. It now returns the extrusion's own error straight away. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Phanoob Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/extrude_preview.rs | 28 ++++++++++++++++++++++++++- crates/ui-egui/src/preview.rs | 27 ++++++++++++++++++-------- 2 files changed, 46 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/extrude_preview.rs b/crates/ui-egui/src/extrude_preview.rs index 762749351..105693709 100644 --- a/crates/ui-egui/src/extrude_preview.rs +++ b/crates/ui-egui/src/extrude_preview.rs @@ -79,7 +79,7 @@ impl StraightPreview { if direction == "negative" { distance = -distance; } - if !distance.is_finite() || distance.abs() < 1e-9 || distance.abs() > 1e6 { + if !distance.is_finite() || distance.abs() > 1e6 { return None; } let operation = params.get("operation").and_then(Value::as_str).unwrap_or("new"); @@ -90,6 +90,11 @@ impl StraightPreview { if inputs.is_empty() || inputs.len() > 1024 { return None; } + // Zero makes no extrusion. Say so now rather than building the scratch design only + // for the kernel to refuse it: that wait was a visible lag (#3254). + if distance.abs() < 1e-9 { + return Some(Err(solidcraft_engine::kernel::KernelError::Invalid("extrude distance is zero".into()).to_string())); + } if self .cached .as_ref() @@ -362,6 +367,27 @@ mod tests { assert!(preview.compute(&h.app, &commands, colors).is_none()); } + /// #3254: a zero distance is refused at once, with the error the extrusion itself gives, + /// instead of after a full scratch preview. + #[test] + fn zero_distance_is_refused_without_a_scratch_preview() { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":4,"width":3,"height":5,"body_name":"Stock"})).unwrap(); + let world = h.app.session.world_state(); + let face = + world.body("Stock").unwrap().body.faces(0.001).unwrap().into_iter().find(|face| face.plane_normal.is_some_and(|n| n.z > 0.99)).unwrap(); + h.app.session.selection = vec![Sel::Face { body: "Stock".into(), index: face.index, point: face.centroid }]; + h.app.start("solid.extrude"); + if let Kind::Extrude { distance, .. } = &mut h.app.dialog.as_mut().unwrap().kind { + *distance = "0 mm".into(); + } + let commands = crate::dialogs::apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap(); + let colors = Colors::from_tokens(&crate::theme::Tokens::get()); + let Some(Err(error)) = StraightPreview::default().compute(&h.app, &commands, colors) else { panic!("no immediate error") }; + let engine = h.app.session.preview(&commands).unwrap_err().to_string(); + assert_eq!(error, engine, "the same error as the extrusion's own"); + } + #[test] fn profile_feedback_keeps_holes_and_skips_unsupported_curves() { let mut harness = Harness::new(); diff --git a/crates/ui-egui/src/preview.rs b/crates/ui-egui/src/preview.rs index f89ec21c9..06be133f0 100644 --- a/crates/ui-egui/src/preview.rs +++ b/crates/ui-egui/src/preview.rs @@ -2,7 +2,8 @@ //! scratch copy of the session ([`solidcraft_engine::Session::preview`]), off the UI thread //! where threads exist, and the result is drawn in place of the bodies it changes: new surface //! tinted, removed material as a translucent ghost. The last good preview stays up while the -//! next one computes or when an input makes the feature fail (the error shows in the dialog). +//! next one computes; once the current inputs make the feature fail, nothing is previewed and +//! the error shows in the dialog (#3254). //! Nothing here touches the document or the undo history. //! //! A feature that adds or removes a tool body (join, cut, intersect) shows only its tool. That @@ -83,7 +84,7 @@ pub struct PreviewState { /// Is a preview scene up? pub active: bool, pub sketches: Vec, - /// Why the current inputs don't make a feature (the last good preview stays up). + /// Why the current inputs don't make a feature (nothing is previewed then). pub error: Option, /// A preview is being computed. pub busy: bool, @@ -114,6 +115,16 @@ impl PreviewState { self.active && !self.rolled_back } + /// Stop drawing the preview scene and give the bodies it stood in for back to the model. + fn hide_scene(&mut self) { + if self.active || !self.replaced.is_empty() { + self.active = false; + self.bounds = Aabb3::EMPTY; + self.replaced.clear(); + self.set_scene(GpuScene::default()); + } + } + fn clear(&mut self) { self.straight.clear(); self.running = None; @@ -127,12 +138,7 @@ impl PreviewState { self.sketches.clear(); self.busy = false; self.rolled_back = false; - if self.active || !self.replaced.is_empty() { - self.active = false; - self.bounds = Aabb3::EMPTY; - self.replaced.clear(); - self.set_scene(GpuScene::default()); - } + self.hide_scene(); } /// Drop the preview of a design that leaves the window. Its scene goes too: the viewport @@ -166,7 +172,10 @@ impl PreviewState { self.tapered = b.tapered; self.set_scene(b.scene); } + // The current inputs make no feature: the last good geometry would contradict + // them (a 1 mm extrusion still drawn at 0 mm), so nothing is drawn. Err(e) => { + self.hide_scene(); self.sketches.clear(); self.error = Some(e); self.applied = None; @@ -838,6 +847,8 @@ mod tests { pv.poll(2, None); assert_eq!(pv.error.as_deref(), Some("current invalid expression")); assert_eq!(pv.shown_key, Some(2)); + assert!(!pv.active && pv.replaced.is_empty(), "the current inputs failed: nothing is previewed (#3254)"); + assert_ne!(pv.key, 9, "the viewport takes the empty scene"); pv.poll(2, None); assert_eq!(pv.error.as_deref(), Some("current invalid expression"), "current errors still prevent invalid Apply"); } From c400188778c807803f2b4ca679d4686c86c1b794 Mon Sep 17 00:00:00 2001 From: Victor Santos Oliveira <56417388+Vittuu@users.noreply.github.com> Date: Tue, 20 Oct 2026 04:01:10 +0000 Subject: [PATCH 177/225] fix(ci): normalize Windows Cargo metadata paths (#3164) --- scripts/ci/affected.py | 6 +++--- scripts/ci/test_affected.py | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 3 deletions(-) diff --git a/scripts/ci/affected.py b/scripts/ci/affected.py index 513db3c85..43d61f697 100644 --- a/scripts/ci/affected.py +++ b/scripts/ci/affected.py @@ -87,10 +87,10 @@ def read_paths(src): def select(meta, paths): """Return (full, sorted package names).""" - root = meta["workspace_root"].rstrip("/") + "/" + root = meta["workspace_root"].replace("\\", "/").rstrip("/") + "/" pkgs = {} for p in meta["packages"]: - manifest = p["manifest_path"] + manifest = p["manifest_path"].replace("\\", "/") assert manifest.startswith(root), manifest pkgs[p["name"]] = manifest[len(root):].rsplit("/", 1)[0] + "/" by_dir = {d: n for n, d in pkgs.items()} @@ -101,7 +101,7 @@ def select(meta, paths): path = d.get("path") if not path: continue - rel = path.rstrip("/") + "/" + rel = path.replace("\\", "/").rstrip("/") + "/" target = by_dir.get(rel[len(root):]) if rel.startswith(root) else None if target: dependents[target].add(p["name"]) diff --git a/scripts/ci/test_affected.py b/scripts/ci/test_affected.py index 34f6ded3e..239045f40 100644 --- a/scripts/ci/test_affected.py +++ b/scripts/ci/test_affected.py @@ -3,6 +3,7 @@ Uses a small synthetic workspace, then the real one (`cargo metadata --no-deps`). """ +import copy import os import sys import unittest @@ -32,6 +33,18 @@ SYNTH = { } +def windows_metadata(root): + meta = copy.deepcopy(SYNTH) + meta["workspace_root"] = root + prefix = root.rstrip("\\/") + for p in meta["packages"]: + p["manifest_path"] = prefix + "\\" + p["manifest_path"][len(R) + 1:] + for d in p["dependencies"]: + if "path" in d: + d["path"] = prefix.replace("\\", "/") + "/" + d["path"][len(R) + 1:].replace("/", "\\") + return meta + + class Synthetic(unittest.TestCase): def test_leaf_selects_only_itself(self): self.assertEqual(affected.select(SYNTH, ["apps/top/src/main.rs"]), (False, ["top"])) @@ -58,6 +71,26 @@ class Synthetic(unittest.TestCase): "scripts/triage/triage.test.js", "vendor/README.md", "SECURITY.md"]: self.assertEqual(affected.select(SYNTH, [p]), (False, []), p) + def test_windows_metadata_selects_packages_and_preserves_triggers(self): + for root in [r"C:\work space\solidcraft", r"\\server\shared work\solidcraft"]: + for trailing in ["", "\\", "/"]: + with self.subTest(root=root, trailing=trailing): + meta = windows_metadata(root + trailing) + self.assertEqual(affected.select(meta, ["apps/top/src/main.rs"]), (False, ["top"])) + self.assertEqual(affected.select(meta, ["crates/base/src/lib.rs"]), (False, ["base", "mid", "top"])) + self.assertEqual(affected.select(meta, ["docs/book/a.md", "README.md"]), (False, [])) + for path in ["Cargo.lock", ".github/workflows/ci.yml", "unknown.txt"]: + self.assertEqual(affected.select(meta, [path]), (True, []), path) + + def test_windows_metadata_rejects_a_manifest_in_a_sibling_workspace(self): + for root in [r"C:\work space\solidcraft", r"\\server\shared work\solidcraft"]: + with self.subTest(root=root): + meta = windows_metadata(root + "\\") + sibling = root.replace("\\", "/") + "-sibling/crates/base/Cargo.toml" + meta["packages"][0]["manifest_path"] = sibling + with self.assertRaises(AssertionError): + affected.select(meta, ["crates/base/src/lib.rs"]) + class RealWorkspace(unittest.TestCase): @classmethod From 926a7353a377e342d2718971fb259fae517d1ddd Mon Sep 17 00:00:00 2001 From: Peppe Bergqvist Date: Tue, 20 Oct 2026 04:02:20 +0000 Subject: [PATCH 178/225] Sheet metal: possible to create flange on a flange (#3274) --- crates/doc/src/sheet.rs | 303 ++++++++++++++++-- crates/engine/src/cmd/sheet_tests.rs | 52 +++ docs/book/src/guide/sheet-metal.md | 11 + .../regressions/sheet-side-flange-corner.json | 9 + 4 files changed, 341 insertions(+), 34 deletions(-) create mode 100644 examples/regressions/sheet-side-flange-corner.json diff --git a/crates/doc/src/sheet.rs b/crates/doc/src/sheet.rs index d3e5c82ce..ee1492a3e 100644 --- a/crates/doc/src/sheet.rs +++ b/crates/doc/src/sheet.rs @@ -943,27 +943,32 @@ impl SheetBody { /// The part of a bend along its parent's edge: where a later flange trimmed that edge back /// (a corner) or a corner relief cut into it, the bend stops and the flange panel runs on - /// alone. + /// alone. A setback on the flange panel's side also limits the bend to that panel's edge. pub fn zone_span(&self, f: &SheetFlange) -> (f64, f64) { - if f.parent.is_some() { - return (0.0, f.len); - } - let pts = self.base.outer.ccw().polyline(1e-3); - let m = pts.len(); - let mut span: Option<(f64, f64)> = None; - for k in 0..m { - let (Some(&a), Some(&b)) = (pts.get(k), pts.get((k + 1) % m)) else { continue }; - let on = (a - f.p).dot(f.n).abs() < 1e-6 && (b - f.p).dot(f.n).abs() < 1e-6; - if !on { - continue; - } - let (ua, ub) = ((a - f.p).dot(f.d), (b - f.p).dot(f.d)); - let (lo, hi) = (ua.min(ub).max(0.0), ua.max(ub).min(f.len)); - if hi > lo + 1e-9 { - span = Some(span.map_or((lo, hi), |(x, y)| (x.min(lo), y.max(hi)))); + let edge_span = |pts: &[Vec2], origin: Vec2| { + let m = pts.len(); + let mut span: Option<(f64, f64)> = None; + for k in 0..m { + let (Some(&a), Some(&b)) = (pts.get(k), pts.get((k + 1) % m)) else { continue }; + let on = (a - origin).dot(f.n).abs() < 1e-6 && (b - origin).dot(f.n).abs() < 1e-6; + if !on { + continue; + } + let (ua, ub) = ((a - f.p).dot(f.d), (b - f.p).dot(f.d)); + let (lo, hi) = (ua.min(ub).max(0.0), ua.max(ub).min(f.len)); + if hi > lo + 1e-9 { + span = Some(span.map_or((lo, hi), |(x, y)| (x.min(lo), y.max(hi)))); + } } + span + }; + let span = if f.parent.is_none() { edge_span(&self.base.outer.ccw().polyline(1e-3), f.p) } else { None }.unwrap_or((0.0, f.len)); + if let Some(shape) = &f.shape + && let Some((lo, hi)) = edge_span(shape, f.p + f.n * self.allowance(f)) + { + return (span.0.max(lo), span.1.min(hi)); } - span.unwrap_or((0.0, f.len)) + span } fn frame_mat(&self) -> Mat { @@ -2175,15 +2180,37 @@ impl SheetBody { self.base = Region2 { outer: exact.unwrap_or_else(|| Loop2::polygon(&cut).ccw()), holes: self.base.holes.clone() }; } Some(i) => { - // A flange panel: its far edge shortens the leg; side edges are not trimmed. + let original = self.flanges.get(i).ok_or_else(|| DocError::Invalid("flange".into()))?; + let side = inward.dot(original.n * -1.0) <= 0.99; + if inward.dot(original.n) > 0.99 { + return Err(DocError::Invalid("pick a free panel edge, not its connection to the existing bend".into())); + } + if side && (cut_at.0 || cut_at.1) { + return Err(DocError::Invalid("not supported yet: a partial side-edge flange beside a cut-out".into())); + } + let clipped = if side || original.shape.is_some() || original.exact.is_some() { + let region = self.panel(original); + if !region.outer.segs.iter().all(|s| matches!(s, Seg2::Line { .. })) { + return Err(DocError::Invalid("not supported yet: a flange setback on a curved flange panel".into())); + } + let points = clip(®ion.outer.ccw().polyline(1e-3), a + inward * by, inward); + if points.len() < 3 { + return Err(DocError::Invalid("the flange's setback removes the whole panel".into())); + } + Some(points) + } else { + None + }; let Some(f) = self.flanges.get_mut(i) else { return Err(DocError::Invalid("flange".into())) }; - if inward.dot(f.n * -1.0) > 0.99 { + if !side { f.leg -= by; if f.leg < -1e-9 { return Err(DocError::Invalid("the flange's setback is longer than the panel".into())); } - } else { - return Err(DocError::Invalid("not supported yet: a flange on the side of another flange".into())); + } + if let Some(points) = clipped { + f.shape = Some(points); + f.exact = None; } } } @@ -2310,21 +2337,28 @@ impl SheetBody { .copied() .ok_or_else(|| DocError::Invalid("the flange's edge was trimmed away".into()))? } - Some(i) => { + Some(i) if self.flanges.get(i).is_some_and(|f| d.dot(f.d) > 1.0 - 1e-9 && f.shape.is_none()) => { let f = self.flanges.get(i).ok_or_else(|| DocError::Invalid("flange".into()))?; let tip = f.p + f.n * (self.allowance(f) + f.leg); - if f.shape.is_some() { - let u0 = (line_o - f.p).dot(f.d).clamp(0.0, f.len); - (tip + f.d * u0, f.len) - } else { - // The panel's far edge, end to end: where a closed corner ran the panel on - // or cut it back (slanted or not), the flange on it follows. - let (lo, hi) = self.far_edge(f); - if !(hi - lo > 1e-9) { - return Err(DocError::Invalid("the flange's edge was trimmed away".into())); - } - (tip + f.d * lo, hi - lo) + let (lo, hi) = self.far_edge(f); + if !(hi - lo > 1e-9) { + return Err(DocError::Invalid("the flange's edge was trimmed away".into())); } + (tip + f.d * lo, hi - lo) + } + Some(i) => { + let f = self.flanges.get(i).ok_or_else(|| DocError::Invalid("flange".into()))?; + let points = self.panel(f).outer.ccw().polyline(1e-3); + let count = points.len(); + (0..count) + .filter_map(|index| { + let (p0, p1) = (*points.get(index)?, *points.get((index + 1) % count)?); + let edge = p1 - p0; + let on = (p0 - line_o).dot(outward).abs() < 1e-6 && (p1 - line_o).dot(outward).abs() < 1e-6; + (on && edge.dot(d) > 1e-9).then_some((p0, edge.len())) + }) + .find(|(p0, len)| (p0.dot(d) + len).min(b.dot(d)) - p0.dot(d).max(a.dot(d)) > 1e-9) + .ok_or_else(|| DocError::Invalid("the flange's edge was trimmed away".into()))? } }; // Where a cut-out ends the edge, the flange ends with it. @@ -2367,9 +2401,103 @@ impl SheetBody { } notes.extend(self.close_corners(&made, relief)); notes.extend(self.close_return_corners(&made)); + notes.extend(self.close_side_corners(&made, relief)); Ok((made, notes)) } + fn close_side_corners(&mut self, made: &[usize], relief: ReliefOverride) -> Vec { + let mut pairs = Vec::new(); + for &child in made { + let Some(flange) = self.flanges.get(child) else { continue }; + let Some(parent) = flange.parent.and_then(|index| self.flanges.get(index)) else { continue }; + if flange.d.dot(parent.d).abs() > 1e-6 { + continue; + } + let allowance = self.allowance(parent); + for (child_end, cb) in [(false, flange.p), (true, flange.p + flange.d * flange.len)] { + if ((cb - parent.p).dot(parent.n) - allowance).abs() > 1e-6 { + continue; + } + let ca = cb - parent.n * allowance; + for &other in made { + let Some(neighbour) = self.flanges.get(other) else { continue }; + if other == child || neighbour.parent != parent.parent || neighbour.d.dot(parent.d).abs() > 1e-6 { + continue; + } + for (other_end, end) in [(false, neighbour.p), (true, neighbour.p + neighbour.d * neighbour.len)] { + if end.dist(ca) < 1e-6 { + pairs.push(ReturnCorner { a: other, a_end: other_end, b: child, b_end: child_end, ca, cb }); + } + } + } + } + } + let mut notes = Vec::new(); + for corner in pairs { + match self.close_returns(&corner) { + Ok(true) => { + if let Err(why) = self.relieve_side_corner(&corner, relief) { + notes.push(format!("no corner relief at {}: {why}", self.shown(corner.ca))); + } + } + Ok(false) => {} + Err(why) => notes.push(format!("the flanges at {} are left open: {why}", self.shown(corner.ca))), + } + } + notes + } + + fn relieve_side_corner(&mut self, corner: &ReturnCorner, relief: ReliefOverride) -> std::result::Result<(), String> { + let shape = relief.shape.unwrap_or(self.relief); + if shape == ReliefShape::Notch { + return Ok(()); + } + if shape == ReliefShape::Tear { + return Err("a tear across an existing bend is not supported yet; the corner keeps its notch".into()); + } + let size = relief.size.unwrap_or(self.relief_size); + if !(size >= MIN_CORNER_RELIEF && size.is_finite()) { + return Err(format!("the relief size {size:.4} mm is below {MIN_CORNER_RELIEF} mm or is not finite")); + } + let (Some(first), Some(second)) = (self.flanges.get(corner.a), self.flanges.get(corner.b)) else { + return Err("a flange is missing".into()); + }; + let Some(parent) = second.parent.and_then(|index| self.flanges.get(index)) else { + return Err("the supporting bend is missing".into()); + }; + let radius = size / 2.0; + if radius >= first.len.min(second.len).min(parent.leg) - 1e-6 { + return Err(format!("a relief {size:.3} mm across would take a whole bend or panel away")); + } + let (start, end, along, across) = (corner.ca, corner.cb, parent.n, parent.d); + let outer = match shape { + ReliefShape::Round => Loop2 { + segs: vec![ + Seg2::Line { a: start - across * radius, b: end - across * radius }, + Seg2::Arc { center: end, radius, start: (across * -1.0).angle(), sweep: std::f64::consts::PI }, + Seg2::Line { a: end + across * radius, b: start + across * radius }, + Seg2::Arc { center: start, radius, start: across.angle(), sweep: std::f64::consts::PI }, + ], + } + .ccw(), + ReliefShape::Rectangular => Loop2::polygon(&[ + start - across * radius - along * radius, + end - across * radius + along * radius, + end + across * radius + along * radius, + start + across * radius - along * radius, + ]) + .ccw(), + ReliefShape::Notch | ReliefShape::Tear => return Ok(()), + }; + let mut relieved = self.clone(); + relieved.holes.push(Region2 { outer, holes: Vec::new() }); + if relieved.flat_regions().map_err(|error| error.to_string())?.len() != 1 { + return Err("the relief would split the flat pattern".into()); + } + self.holes = relieved.holes; + Ok(()) + } + /// Where the bend of flange `i` on the base ends beside more of the base (the flange's edge /// ends at an inside corner and the base runs on past it), cut the rule's bend relief into /// the base there: a slot `relief_width` wide beside the bend's end, from `relief_depth` @@ -5662,6 +5790,113 @@ mod tests { holds_the_flat_material(&s, "the triangle"); } + #[test] + fn edge_flange_on_a_folded_panels_side_keeps_its_flat_material() { + let base = rect(Vec2::new(0.0, 0.0), Vec2::new(120.0, 0.0), Vec2::new(120.0, 90.0), Vec2::new(0.0, 90.0)); + let mut s = base_flange("Body1", "AL2", &alu(), Plane::XY, base); + let angle = std::f64::consts::FRAC_PI_2; + let wall = s.add_flange(Vec3::new(60.0, 0.0, 2.0), 30.0, angle, 1.0, "inside", false).unwrap(); + let parent = s.flanges.get(wall).unwrap().clone(); + let flat = parent.p + parent.d * parent.len + parent.n * (s.allowance(&parent) + parent.leg * 0.5); + let pick = apply_point(&s.world(Some(wall)), Vec3::new(flat.x, flat.y, s.t)); + let child = s.add_flange(pick, 20.0, angle, 1.0, "inside", false).unwrap(); + let flange = s.flanges.get(child).unwrap(); + assert_eq!(flange.parent, Some(wall)); + assert!(flange.d.dot(parent.n).abs() > 0.99); + assert!((flange.len - parent.leg).abs() < 1e-6); + holds_the_flat_material(&s, "a flange on a folded panel's side"); + } + + #[test] + fn edge_flanges_across_an_existing_bend_close_their_corner() { + for position in ["inside", "outside", "middle"] { + for reverse in [false, true] { + for flip in [false, true] { + for right in [false, true] { + for wall_angle in [60.0_f64, 90.0, 120.0] { + let base = rect(Vec2::new(0.0, 0.0), Vec2::new(120.0, 0.0), Vec2::new(120.0, 90.0), Vec2::new(0.0, 90.0)); + let mut s = base_flange("Body1", "AL2", &alu(), Plane::XY, base); + let angle = std::f64::consts::FRAC_PI_2; + let wall = s.add_flange(Vec3::new(60.0, 0.0, 2.0), 60.0, wall_angle.to_radians(), 1.0, "inside", false).unwrap(); + let parent = s.flanges.get(wall).unwrap(); + let flat = + parent.p + parent.d * if right { parent.len } else { 0.0 } + parent.n * (s.allowance(parent) + parent.leg * 0.5); + let side = apply_point(&s.world(Some(wall)), Vec3::new(flat.x, flat.y, s.t)); + let mut picks = [Vec3::new(if right { 120.0 } else { 0.0 }, 45.0, 2.0), side]; + if reverse { + picks.reverse(); + } + let what = format!("{position}, reverse={reverse}, flip={flip}, right={right}, wall={wall_angle}"); + let (made, notes) = s.add_flanges_noted(&picks, 20.0, angle, 1.0, position, flip).unwrap(); + if flip && !notes.is_empty() { + assert!( + notes.iter().all(|note| note.contains("overlap in the flat pattern") || note.contains("cut a panel away")), + "{what}: {notes:?}" + ); + holds_the_flat_material(&s, &what); + continue; + } + assert!(notes.is_empty(), "{what}: {notes:?}"); + assert!( + made.iter().any(|&index| { + let flange = s.flanges.get(index).unwrap(); + flange.slope.0.abs() > 0.1 || flange.slope.1.abs() > 0.1 + }), + "the corner was not mitred: {what}" + ); + holds_the_flat_material(&s, &what); + } + } + } + } + } + } + + #[test] + fn a_side_flange_setback_also_limits_the_existing_bend() { + for (position, right) in [("middle", false), ("middle", true), ("inside", false), ("inside", true)] { + let base = rect(Vec2::new(-110.0, -214.0), Vec2::new(110.0, -214.0), Vec2::new(110.0, 73.22), Vec2::new(-110.0, 73.22)); + let rule = RuleValues { thickness: 5.0, bend_radius: 5.0, gap: 5.0, k_factor: 0.44, ..alu() }; + let mut s = base_flange("Body1", "AL2", &rule, Plane::XY, base); + let angle = std::f64::consts::FRAC_PI_2; + let wall = s.add_flange(Vec3::new(0.0, -214.0, 5.0), 550.0, angle, 5.0, "middle", false).unwrap(); + s.add_flanges(&[Vec3::new(110.0, -50.0, 0.0), Vec3::new(-110.0, -50.0, 0.0)], 50.0, angle, 5.0, "middle", false).unwrap(); + let parent = s.flanges.get(wall).unwrap(); + let point = parent.p + parent.d * if right { parent.len } else { 0.0 } + parent.n * (s.allowance(parent) + parent.leg * 0.5); + let side = apply_point(&s.world(Some(wall)), Vec3::new(point.x, point.y, 0.0)); + let (_, notes) = s.add_flanges_noted(&[side], 40.0, angle, 5.0, position, false).unwrap(); + assert!(notes.is_empty(), "{notes:?}"); + let parent = s.flanges.get(wall).unwrap(); + let panel = s.panel(parent).outer.ccw().polyline(1e-3); + let panel_start = panel.iter().map(|point| (*point - parent.p).dot(parent.d)).fold(f64::INFINITY, f64::min); + let panel_end = panel.iter().map(|point| (*point - parent.p).dot(parent.d)).fold(f64::NEG_INFINITY, f64::max); + let (bend_start, bend_end) = s.zone_span(parent); + assert!(bend_start >= panel_start - 1e-6, "{position}: bend starts at {bend_start}, before panel at {panel_start}"); + assert!(bend_end <= panel_end + 1e-6, "{position}: bend ends at {bend_end}, beyond panel at {panel_end}"); + assert!(s.solid().is_ok()); + assert_eq!(s.flat_regions().unwrap().len(), 1); + } + } + + #[test] + fn corners_across_a_bend_cut_the_selected_relief_in_the_flat_material() { + for shape in [ReliefShape::Round, ReliefShape::Rectangular] { + let base = rect(Vec2::new(0.0, 0.0), Vec2::new(120.0, 0.0), Vec2::new(120.0, 90.0), Vec2::new(0.0, 90.0)); + let mut s = base_flange("Body1", "AL2", &alu(), Plane::XY, base); + let angle = std::f64::consts::FRAC_PI_2; + let wall = s.add_flange(Vec3::new(60.0, 0.0, 2.0), 30.0, angle, 1.0, "inside", false).unwrap(); + let parent = s.flanges.get(wall).unwrap(); + let point = parent.p + parent.d * parent.len + parent.n * (s.allowance(parent) + parent.leg * 0.5); + let side = apply_point(&s.world(Some(wall)), Vec3::new(point.x, point.y, s.t)); + let edges = [Vec3::new(120.0, 45.0, 2.0), side].map(|pick| EdgeFlange { pick, height: 20.0, angle }); + let (_, notes) = s.add_flanges_each(&edges, 1.0, "inside", false, ReliefOverride { shape: Some(shape), size: Some(4.0) }).unwrap(); + assert!(notes.is_empty(), "{shape:?}: {notes:?}"); + assert_eq!(s.holes.len(), 1); + assert!(!s.flat_regions().unwrap().iter().any(|region| region.contains(Vec2::new(116.0, 1.5)))); + holds_the_flat_material(&s, &format!("{shape:?} relief across a bend")); + } + } + #[test] fn a_corner_with_a_flange_of_an_earlier_feature_gets_no_relief() { // Like the closing, the relief belongs to the corners between the flanges of one feature. diff --git a/crates/engine/src/cmd/sheet_tests.rs b/crates/engine/src/cmd/sheet_tests.rs index 881b047f5..0efb477b5 100644 --- a/crates/engine/src/cmd/sheet_tests.rs +++ b/crates/engine/src/cmd/sheet_tests.rs @@ -37,6 +37,58 @@ fn rectangle_tool(s: &mut Session, name: &str, p0: [f64; 2], p1: [f64; 2]) { run(s, "sketch.finish", json!({})); } +#[test] +fn side_edge_flanges_across_a_bend_keep_their_relief_through_rebuild_and_reopen() { + use solidcraft_geom::Vec3; + + for shape in ["round", "rectangular"] { + for reverse in [false, true] { + let mut s = Session::default(); + run( + &mut s, + "sheet.manage_rules", + json!({"name":"AL2","thickness":"2 mm","k_factor":0.5,"bend_radius":"1 mm","gap":"0.5 mm","active":true}), + ); + base(&mut s, 120.0, 90.0); + run(&mut s, "sheet.flange", json!({"edges":[[60,0,2]],"height":"30 mm","angle":"90 deg"})); + let sheet = &s.model.state().sheets[0]; + let parent = &sheet.flanges[0]; + let point = parent.p + parent.d * parent.len + parent.n * (sheet.allowance(parent) + parent.leg * 0.5); + let side = solidcraft_doc::apply_point(&sheet.world(Some(0)), Vec3::new(point.x, point.y, sheet.t)); + let mut edges = vec![json!([120, 45, 2]), json!([side.x, side.y, side.z])]; + if reverse { + edges.reverse(); + } + let before = s.doc.to_json(); + run( + &mut s, + "sheet.flange", + json!({"edges":edges,"height":"20 mm","angle":"90 deg","position":"inside","corner_relief_shape":shape,"corner_relief":"4 mm"}), + ); + assert!(no_errors_or_warnings(&s), "{shape}, reverse={reverse}: {:?}", s.model.results); + let formed = volume(&mut s); + let pattern = flat(&mut s); + assert_eq!(s.model.state().sheets[0].holes.len(), 1); + let body = &s.model.state().bodies[0].body; + assert!(body.validity().is_empty() && body.shell_count() == 1); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.to_json(), before); + run(&mut s, "edit.redo", json!({})); + assert!((volume(&mut s) - formed).abs() < 1e-6); + for command in ["sheet.unfold", "sheet.refold"] { + run(&mut s, command, json!({})); + assert!((volume(&mut s) - formed).abs() < formed * 1e-3); + } + let mut reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); + assert!(no_errors_or_warnings(&reopened), "{:?}", reopened.model.results); + assert!((volume(&mut reopened) - formed).abs() < 1e-6); + assert_eq!(flat(&mut reopened), pattern); + let dxf = run(&mut reopened, "sheet.export_dxf", json!({}))["dxf"].as_str().unwrap().to_owned(); + assert!(!solidcraft_io::read_dxf(&dxf).unwrap().is_empty()); + } + } +} + #[test] fn shallow_sheet_pocket_preserves_material_depth_export_undo_and_reopen() { let mut s = Session::default(); diff --git a/docs/book/src/guide/sheet-metal.md b/docs/book/src/guide/sheet-metal.md index e3a7c1988..60374d983 100644 --- a/docs/book/src/guide/sheet-metal.md +++ b/docs/book/src/guide/sheet-metal.md @@ -136,6 +136,17 @@ are, so the returns on them close over a relieved or torn corner as over a whole (The four returns of a 120 x 90 tray in 2 mm sheet with 90° walls 20 high: each point is the middle of a wall's far edge on its inner face, so the returns turn in over the base.) +A flange can stand on a straight side edge of an existing flange as well. Select that edge +and the adjoining edge of its supporting panel in one feature to close the new flanges across +the existing bend. The panels are mitred with the rule's gap; `round` and `rectangular` corner +reliefs cut a rounded or rectangular slot across the existing bend zone in the flat material. +The slot's width is `corner_relief`, and it survives unfolding, refolding and DXF export. +`notch` keeps the gap without another cut. A `tear` across an existing bend is not supported +yet and leaves the notch with a warning. A mitre that would overlap the flat pattern stays +open with a warning. Side-edge setbacks on curved panels or on only part of an edge left by +a cut-out are not supported yet. The edge connecting a panel to its existing bend is not a +free edge. See `examples/regressions/sheet-side-flange-corner.json` for a small reproduction. + **Convert** also takes a solid or a shelled body: pick the face that stays fixed and the sharp edges that become bends (`bends`; Bend Edges in the dialog). The flat faces reached from the fixed face across those edges become the sheet. A shelled body keeps its walls and their diff --git a/examples/regressions/sheet-side-flange-corner.json b/examples/regressions/sheet-side-flange-corner.json new file mode 100644 index 000000000..49eec7084 --- /dev/null +++ b/examples/regressions/sheet-side-flange-corner.json @@ -0,0 +1,9 @@ +{"commands": [ + {"command": "sheet.manage_rules", "params": {"name": "Sheet 2 mm", "thickness": "2 mm", "k_factor": 0.5, "bend_radius": "1 mm", "gap": "0.5 mm", "active": true}}, + {"command": "sketch.create", "params": {"plane": "XY", "name": "Base"}}, + {"command": "sketch.rectangle.two_point", "params": {"p0": [0, 0], "p1": [120, 90]}}, + {"command": "sketch.finish", "params": {}}, + {"command": "sheet.flange", "params": {"sketch": "Base"}}, + {"command": "sheet.flange", "params": {"edges": [[60, 0, 2]], "height": "30 mm", "angle": "90 deg"}}, + {"command": "sheet.flange", "params": {"edges": [[120, 45, 2], [120, 2, 16.5]], "height": "20 mm", "angle": "90 deg", "position": "inside", "corner_relief_shape": "round", "corner_relief": "4 mm"}} +]} \ No newline at end of file From 9e15995a74ffd96d7aa69f3e7993480a3e4cf309 Mon Sep 17 00:00:00 2001 From: Erlis Vidal Date: Tue, 20 Oct 2026 04:15:37 +0000 Subject: [PATCH 179/225] A cut ending in a face of its target no longer leaves the hole closed by a skin (#2827) A cut whose tool ends exactly on a face of the target (a hole cut from a pocket's floor up to the plate's top face) could come out of the general boolean with the target's face whole over the hole and the tool's end face under it: a skin of no thickness that keeps the hole closed. No volume shows it and the sampled membership checks see the hole either way, so the result was kept. The result check now refuses a body with a planar face lying back to back on another of its own planar faces with nothing behind part of it (`coplanar::has_skin`), and the retries take the cut. Co-authored-by: Claude Opus 5.5 --- crates/engine/src/boolean_regression_tests.rs | 35 + crates/kernel/src/coplanar.rs | 38 + crates/kernel/src/ops.rs | 5 +- .../cut_up_to_face_leaves_skin.json | 2936 +++++++++++++++++ 4 files changed, 3012 insertions(+), 2 deletions(-) create mode 100644 examples/regressions/cut_up_to_face_leaves_skin.json diff --git a/crates/engine/src/boolean_regression_tests.rs b/crates/engine/src/boolean_regression_tests.rs index 59a28da74..1cacb72b6 100644 --- a/crates/engine/src/boolean_regression_tests.rs +++ b/crates/engine/src/boolean_regression_tests.rs @@ -997,3 +997,38 @@ fn prism_edge_in_a_round_cornered_slab_end_face_joins() { assert!((got - (prism + slab - shared)).abs() < 1e-3 * got, "r {r}: {got} vs {}", prism + slab - shared); } } + +/// A cut from a face up to the plate's top face, its tool's end lying in that face: the boolean +/// of the bodies as they lie left the hole closed by a skin of no thickness (the plate's top face +/// whole over the hole, the tool's end face under it), which no volume shows and which was kept. +/// The hole is open, and the cut takes the whole tool: the circle of radius 3.04 the two +/// profiles make, from the barrel cut's floor at z 1.6 up to the plate's top at z 2.8. +#[test] +fn cut_up_to_the_plate_top_face_opens_the_hole() { + let mut script: Value = serde_json::from_str(include_str!("../../../examples/regressions/cut_up_to_face_leaves_skin.json")).unwrap(); + let s = replay_value(&script); + assert!(s.model.results.iter().all(|r| r.error.is_none()), "{:?}", s.model.results); + let state = s.model.state(); + let body = &state.body("Body7").unwrap().body; + assert!(body.validity().is_empty(), "{:?}", body.validity()); + let skin: Vec = body + .faces(1e-4) + .unwrap() + .into_iter() + .filter(|f| f.plane_normal.is_some_and(|n| n.z < -0.999) && (f.centroid.z - 2.8).abs() < 1e-6) + .map(|f| f.area) + .collect(); + assert!(skin.is_empty(), "faces at z 2.8 facing down, areas {skin:?} mm²"); + // The same design without the cut. + script["commands"].as_array_mut().unwrap().pop(); + let before = replay_value(&script); + let fine = |s: &Session| s.model.state().body("Body7").unwrap().body.tessellate(1e-5).unwrap().measure().volume; + let (removed, want) = (fine(&before) - fine(&s), std::f64::consts::PI * 3.04 * 3.04 * 1.2); + assert!((removed - want).abs() < 0.01, "removed {removed} mm³, want {want}"); +} + +fn replay_value(script: &Value) -> Session { + let mut s = Session::default(); + s.run_script(script).unwrap(); + s +} diff --git a/crates/kernel/src/coplanar.rs b/crates/kernel/src/coplanar.rs index 201d3bb1a..9f4059210 100644 --- a/crates/kernel/src/coplanar.rs +++ b/crates/kernel/src/coplanar.rs @@ -999,6 +999,44 @@ pub(crate) fn faces_touch(a: &Body, b: &Body) -> bool { }) } +/// Does `r` hold a skin of no thickness: a planar face lying on another of its planar faces that +/// faces the other way, with no material behind part of it? A cut whose tool ends exactly on a +/// face of the target can come out with the target's face whole over the hole and the tool's end +/// face under it, closing the hole. No volume shows that, and points sampled off the surface see +/// the hole either way. Faces back to back in one plane with material behind both (the top of a +/// step beside the underside of an overhang) are not this. `mesh` is `r`'s mesh; what counts is +/// an area of the faces with nothing behind it, so that the few triangles along an edge where the +/// mesh of a curved neighbour cuts the corner don't. +pub(crate) fn has_skin(r: &Body, mesh: &solidcraft_geom::Mesh) -> bool { + let size = r.size(); + let tol = (size * 1e-7).max(1e-9) * 10.0; + let p = planes(r); + if p.len() > MAX_SKIN_FACES { + return false; + } + let paired: HashMap = p + .iter() + .filter(|(i, x)| p.iter().any(|(j, y)| i != j && x.n.dot(y.n) < -1.0 + 1e-9 && (x.d + y.d).abs() < tol)) + .map(|(i, x)| (*i, x.n)) + .collect(); + if paired.is_empty() { + return false; + } + let inside = mesh.inside_index(); + let depth = (size * 1e-4).max(1e-6); + let mut open = 0.0; + for (t, face) in mesh.triangles.iter().zip(&mesh.tri_face).take(100_000) { + let (Some(n), Some([a, b, c])) = (paired.get(&(*face as usize)), mesh.tri(t)) else { continue }; + if !inside.contains((a + b + c) / 3.0 - *n * depth) { + open += (b - a).cross(c - a).len() * 0.5; + } + } + open > (size * size * 1e-6).max(1e-9) +} + +/// The most planar faces [`has_skin`] pairs up (every pair is compared). +const MAX_SKIN_FACES: usize = 2000; + /// The triangles of `tool`'s faces in the plane (`m`, `d`), `m` their outward normal, each with /// how far its face reaches past it sideways. A face bounded by straight edges is its /// triangles; they are drawn in by `skin`, so that faces of the other body lying against the diff --git a/crates/kernel/src/ops.rs b/crates/kernel/src/ops.rs index 8d95b7904..9309b6336 100644 --- a/crates/kernel/src/ops.rs +++ b/crates/kernel/src/ops.rs @@ -1295,7 +1295,8 @@ where // nothing to cut, so it returns both operands side by side (#396). Volume and point // sampling cannot see that; the shell grouping can. Only contact over an area counts // (bodies tangent along a line stay two lumps), and operands already like that, saved - // before this was caught, stay joinable. + // before this was caught, stay joinable. Nor can they see a skin of no thickness left over + // a hole by a tool ending in a face of the target ([`crate::coplanar::has_skin`]). let unfused = |r: &Body| { op == BoolOp::Union && r.shell_count() > 1 @@ -1311,7 +1312,7 @@ where if !bounds { return (false, v); } - if unfused(r) { + if unfused(r) || crate::coplanar::has_skin(r, &mr) { return (false, v); } let consistent = match &meshes { diff --git a/examples/regressions/cut_up_to_face_leaves_skin.json b/examples/regressions/cut_up_to_face_leaves_skin.json new file mode 100644 index 000000000..90957bbbd --- /dev/null +++ b/examples/regressions/cut_up_to_face_leaves_skin.json @@ -0,0 +1,2936 @@ +{ + "description": "A housing: a 2.8 mm plate (z 0..2.8) with walls to z 15, a centre column, a barrel cut 1.6 mm deep from the bottom, a lid recess and two tapered pockets. Extrude1 then cuts two circle profiles of `housing pellet exit` from the barrel cut's floor (the face at z 1.6) up to the plate's top face (z 2.8). It reports no error, but the hole stays closed: the top face at z 2.8 keeps its area over the hole, and a 28.28 mm2 face at z 2.8 faces down under it, a zero-thickness skin. The sketches are added as a design stores them: solved again, their points move by up to 1e-6 mm and the same cut opens the hole, so the stored positions are part of the case. Result: no face at z 2.8 faces down.", + "commands": [ + { + "command": "parameters.add", + "params": { + "name": "total_height", + "expression": "15 mm", + "unit": "mm" + } + }, + { + "command": "parameters.add", + "params": { + "name": "housing_bottom_thickness", + "expression": "2.8 mm", + "unit": "mm" + } + }, + { + "command": "parameters.add", + "params": { + "name": "caliber_deltha", + "expression": "0.55 mm - 0.07 mm", + "unit": "mm" + } + }, + { + "command": "parameters.add", + "params": { + "name": "housing_barrel_cut_depth", + "expression": "1.6 mm", + "unit": "mm" + } + }, + { + "command": "parameters.add", + "params": { + "name": "housing_barrel_cut_length", + "expression": "17 mm", + "unit": "mm" + } + }, + { + "command": "parameters.add", + "params": { + "name": "follower_wall_thickness", + "expression": "3.1 mm", + "unit": "mm" + } + }, + { + "command": "parameters.add", + "params": { + "name": "housing_barrel_cut_width", + "expression": "9.7 mm", + "unit": "mm" + } + }, + { + "command": "parameters.add", + "params": { + "name": "housing_center_diameter", + "expression": "11.423 mm", + "unit": "mm" + } + }, + { + "command": "parameters.add", + "params": { + "name": "follower_spring_diameter", + "expression": "26 mm", + "unit": "mm" + } + }, + { + "command": "parameters.add", + "params": { + "name": "lid_diameter", + "expression": "20 mm", + "unit": "mm" + } + }, + { + "command": "parameters.add", + "params": { + "name": "hole_diameter", + "expression": "3.38 mm", + "unit": "mm" + } + }, + { + "command": "parameters.add", + "params": { + "name": "housing_nut_depth", + "expression": "7.5 mm", + "unit": "mm" + } + }, + { + "command": "parameters.add", + "params": { + "name": "print_extrusion_width", + "expression": "0.45 mm", + "unit": "mm" + } + }, + { + "command": "parameters.add", + "params": { + "name": "print_layer_multiplier", + "expression": "( 0.15 * ( 1 - 3.141592653 / 4 ) ) * 1 mm", + "unit": "mm" + } + }, + { + "command": "parameters.add", + "params": { + "name": "housing_spring_guide_from_top", + "expression": "1.7 mm", + "unit": "mm" + } + }, + { + "command": "parameters.add", + "params": { + "name": "housing_barrel_cut_edge_separation", + "expression": "6 mm", + "unit": "mm" + } + }, + { + "command": "parameters.add", + "params": { + "name": "follower_diameter", + "expression": "49 mm", + "unit": "mm" + } + }, + { + "command": "parameters.add", + "params": { + "name": "screw_diameter", + "expression": "3.380 mm", + "unit": "mm" + } + }, + { + "command": "parameters.add", + "params": { + "name": "pellet_max_height", + "expression": "10 mm", + "unit": "mm" + } + }, + { + "command": "parameters.add", + "params": { + "name": "caliber22_shots", + "expression": "17 + 1", + "unit": "" + } + }, + { + "command": "parameters.add", + "params": { + "name": "caliber25_shots", + "expression": "15 + 1", + "unit": "" + } + }, + { + "command": "parameters.add", + "params": { + "name": "caliber30_shots", + "expression": "13 + 1", + "unit": "" + } + }, + { + "command": "parameters.add", + "params": { + "name": "caliber177_shots", + "expression": "21 + 1", + "unit": "" + } + }, + { + "command": "parameters.add", + "params": { + "name": "magnet_depth", + "expression": "3.5 mm", + "unit": "mm" + } + }, + { + "command": "parameters.add", + "params": { + "name": "pelletpath_depth", + "expression": "0.6 mm", + "unit": "mm" + } + }, + { + "command": "parameters.add", + "params": { + "name": "housing_step_size", + "expression": "2 mm", + "unit": "mm" + } + }, + { + "command": "parameters.add", + "params": { + "name": "lid_height_panthera", + "expression": "4.4 mm", + "unit": "mm" + } + }, + { + "command": "parameters.add", + "params": { + "name": "caliber357_shots", + "expression": "11 + 1", + "unit": "" + } + }, + { + "command": "parameters.add", + "params": { + "name": "follower_label_depth", + "expression": "0.36 mm", + "unit": "mm" + } + }, + { + "command": "parameters.add", + "params": { + "name": "caliber25", + "expression": "6.35 mm + caliber_deltha + 0.07 mm", + "unit": "mm" + } + }, + { + "command": "parameters.add", + "params": { + "name": "caliber30", + "expression": "7.62 mm + caliber_deltha", + "unit": "mm" + } + }, + { + "command": "parameters.add", + "params": { + "name": "three_lines", + "expression": "3 * print_extrusion_width - 2 * print_layer_multiplier", + "unit": "mm" + } + }, + { + "command": "parameters.add", + "params": { + "name": "two_lines", + "expression": "2 * print_extrusion_width - 1 * print_layer_multiplier", + "unit": "mm" + } + }, + { + "command": "parameters.add", + "params": { + "name": "follower_height", + "expression": "total_height - housing_bottom_thickness - 1 mm", + "unit": "mm" + } + }, + { + "command": "parameters.add", + "params": { + "name": "four_lines", + "expression": "4 * print_extrusion_width - 3 * print_layer_multiplier", + "unit": "mm" + } + }, + { + "command": "parameters.add", + "params": { + "name": "follower_hole_diameter", + "expression": "housing_center_diameter + 0.4 mm", + "unit": "mm" + } + }, + { + "command": "parameters.add", + "params": { + "name": "lid_height", + "expression": "total_height - pellet_max_height - housing_bottom_thickness", + "unit": "mm" + } + }, + { + "command": "parameters.add", + "params": { + "name": "caliber22", + "expression": "5.6 mm + caliber_deltha", + "unit": "mm" + } + }, + { + "command": "parameters.add", + "params": { + "name": "housing_center_height", + "expression": "total_height - 4 mm", + "unit": "mm" + } + }, + { + "command": "parameters.add", + "params": { + "name": "caliber177", + "expression": "4.5 mm + caliber_deltha", + "unit": "mm" + } + }, + { + "command": "parameters.add", + "params": { + "name": "six_lines", + "expression": "6 * print_extrusion_width - 5 * print_layer_multiplier", + "unit": "mm" + } + }, + { + "command": "parameters.add", + "params": { + "name": "caliberX_shots", + "expression": "caliber22_shots", + "unit": "" + } + }, + { + "command": "parameters.add", + "params": { + "name": "caliber357", + "expression": "9.07 mm + caliber_deltha", + "unit": "mm" + } + }, + { + "command": "parameters.add", + "params": { + "name": "housing_wall_thickness", + "expression": "four_lines", + "unit": "mm" + } + }, + { + "command": "parameters.add", + "params": { + "name": "two_and_half_lines", + "expression": "two_lines + ( 0.45 / 2 ) * 1 mm", + "unit": "mm" + } + }, + { + "command": "parameters.add", + "params": { + "name": "follower_lid_depth", + "expression": "follower_height - lid_height - 1 mm", + "unit": "mm" + } + }, + { + "command": "parameters.add", + "params": { + "name": "housing_lid_recess", + "expression": "lid_height + 0.3 mm", + "unit": "mm" + } + }, + { + "command": "parameters.add", + "params": { + "name": "caliberX", + "expression": "caliber22", + "unit": "mm" + } + }, + { + "command": "timeline.add", + "params": { + "feature": { + "id": 30, + "name": "housing", + "plane": { + "name": "XY", + "type": "origin" + }, + "sketch": { + "constraints": [ + { + "id": "k1", + "output": "c8", + "param": "d1", + "reverse": true, + "type": "offset_distance", + "value": 1.2856194489750001 + }, + { + "id": "k2", + "output": "c9", + "param": "d2", + "reverse": false, + "type": "offset_distance", + "value": 0.8678097244875 + }, + { + "a": 27, + "b": 28, + "id": "k3", + "type": "equal" + }, + { + "a": 28, + "b": 29, + "id": "k4", + "type": "equal" + }, + { + "a": 29, + "b": 30, + "id": "k5", + "type": "equal" + }, + { + "a": 30, + "b": 31, + "id": "k6", + "type": "equal" + }, + { + "a": 31, + "b": 32, + "id": "k7", + "type": "equal" + }, + { + "c": 44, + "id": "k8", + "p": 49, + "type": "point_on_curve" + }, + { + "c": 44, + "id": "k9", + "p": 50, + "type": "point_on_curve" + }, + { + "c": 44, + "id": "k10", + "p": 51, + "type": "point_on_curve" + }, + { + "c": 44, + "id": "k11", + "p": 52, + "type": "point_on_curve" + }, + { + "c": 44, + "id": "k12", + "p": 53, + "type": "point_on_curve" + }, + { + "c": 44, + "id": "k13", + "p": 54, + "type": "point_on_curve" + }, + { + "a": 34, + "b": 35, + "id": "k14", + "type": "equal" + }, + { + "a": 35, + "b": 36, + "id": "k15", + "type": "equal" + }, + { + "a": 36, + "b": 37, + "id": "k16", + "type": "equal" + }, + { + "a": 37, + "b": 38, + "id": "k17", + "type": "equal" + }, + { + "a": 38, + "b": 39, + "id": "k18", + "type": "equal" + }, + { + "c": 45, + "id": "k19", + "p": 57, + "type": "point_on_curve" + }, + { + "c": 45, + "id": "k20", + "p": 58, + "type": "point_on_curve" + }, + { + "c": 45, + "id": "k21", + "p": 59, + "type": "point_on_curve" + }, + { + "c": 45, + "id": "k22", + "p": 60, + "type": "point_on_curve" + }, + { + "c": 45, + "id": "k23", + "p": 61, + "type": "point_on_curve" + }, + { + "c": 45, + "id": "k24", + "p": 62, + "type": "point_on_curve" + }, + { + "id": "k25", + "p": 1, + "q": 0, + "type": "coincident" + }, + { + "a": 3, + "b": 0, + "id": "k26", + "type": "concentric" + }, + { + "a": 4, + "b": 3, + "id": "k27", + "type": "concentric" + }, + { + "a": 5, + "b": 4, + "id": "k28", + "type": "concentric" + }, + { + "a": 13, + "b": 0, + "id": "k29", + "type": "concentric" + }, + { + "c": 3, + "id": "k30", + "p": 9, + "type": "point_on_curve" + }, + { + "a": 0, + "b": 6, + "id": "k31", + "type": "tangent" + }, + { + "c": 2, + "id": "k32", + "p": 9, + "type": "point_on_curve" + }, + { + "a": 7, + "b": 8, + "id": "k33", + "type": "parallel" + }, + { + "c": 9, + "id": "k34", + "p": 10, + "type": "point_on_curve" + }, + { + "a": 8, + "b": 11, + "id": "k35", + "type": "tangent" + }, + { + "a": 7, + "b": 11, + "id": "k36", + "type": "tangent" + }, + { + "c": 11, + "id": "k37", + "p": 13, + "type": "point_on_curve" + }, + { + "c": 11, + "id": "k38", + "p": 11, + "type": "point_on_curve" + }, + { + "a": 11, + "b": 6, + "id": "k39", + "type": "concentric" + }, + { + "a": 10, + "b": 12, + "id": "k40", + "type": "tangent" + }, + { + "a": 9, + "b": 12, + "id": "k41", + "type": "tangent" + }, + { + "a": 10, + "b": 13, + "id": "k42", + "type": "tangent" + }, + { + "c": 12, + "id": "k43", + "p": 69, + "type": "point_on_curve" + }, + { + "id": "k44", + "l": 46, + "p": 14, + "q": 16, + "type": "symmetric" + }, + { + "a": 9, + "b": 13, + "id": "k45", + "type": "tangent" + }, + { + "c": 9, + "id": "k46", + "p": 12, + "type": "point_on_curve" + }, + { + "id": "k47", + "l": 14, + "type": "horizontal" + }, + { + "a": 14, + "b": 11, + "id": "k48", + "type": "tangent" + }, + { + "a": 15, + "b": 8, + "id": "k49", + "type": "parallel" + }, + { + "c": 15, + "id": "k50", + "p": 5, + "type": "point_on_curve" + }, + { + "c": 8, + "id": "k51", + "p": 25, + "type": "point_on_curve" + }, + { + "c": 8, + "id": "k52", + "p": 27, + "type": "point_on_curve" + }, + { + "c": 8, + "id": "k53", + "p": 26, + "type": "point_on_curve" + }, + { + "a": 16, + "b": 11, + "id": "k54", + "type": "tangent" + }, + { + "id": "k55", + "l": 15, + "p": 27, + "q": 29, + "type": "symmetric" + }, + { + "id": "k56", + "l": 15, + "p": 26, + "q": 30, + "type": "symmetric" + }, + { + "id": "k57", + "l": 15, + "p": 25, + "q": 28, + "type": "symmetric" + }, + { + "a": 16, + "b": 17, + "id": "k58", + "type": "equal" + }, + { + "a": 21, + "b": 18, + "id": "k59", + "type": "tangent" + }, + { + "c": 18, + "id": "k60", + "p": 38, + "type": "point_on_curve" + }, + { + "a": 22, + "b": 20, + "id": "k61", + "type": "tangent" + }, + { + "c": 20, + "id": "k62", + "p": 40, + "type": "point_on_curve" + }, + { + "a": 14, + "b": 24, + "id": "k63", + "type": "tangent" + }, + { + "a": 9, + "b": 24, + "id": "k64", + "type": "tangent" + }, + { + "a": 10, + "b": 23, + "id": "k65", + "type": "tangent" + }, + { + "a": 14, + "b": 23, + "id": "k66", + "type": "tangent" + }, + { + "c": 10, + "id": "k67", + "p": 43, + "type": "point_on_curve" + }, + { + "c": 14, + "id": "k68", + "p": 44, + "type": "point_on_curve" + }, + { + "c": 14, + "id": "k69", + "p": 46, + "type": "point_on_curve" + }, + { + "c": 9, + "id": "k70", + "p": 47, + "type": "point_on_curve" + }, + { + "a": 26, + "b": 4, + "id": "k71", + "type": "concentric" + }, + { + "id": "k72", + "l": 31, + "type": "horizontal" + }, + { + "id": "k73", + "l": 33, + "type": "vertical" + }, + { + "id": "k74", + "p": 55, + "q": 19, + "type": "coincident" + }, + { + "c": 33, + "id": "k75", + "p": 67, + "type": "point_on_curve" + }, + { + "c": 13, + "id": "k76", + "p": 41, + "type": "point_on_curve" + }, + { + "a": 22, + "b": 13, + "id": "k77", + "type": "tangent" + }, + { + "c": 13, + "id": "k78", + "p": 37, + "type": "point_on_curve" + }, + { + "a": 21, + "b": 13, + "id": "k79", + "type": "tangent" + }, + { + "a": 20, + "b": 13, + "id": "k80", + "type": "tangent" + }, + { + "c": 13, + "id": "k81", + "p": 35, + "type": "point_on_curve" + }, + { + "c": 13, + "id": "k82", + "p": 32, + "type": "point_on_curve" + }, + { + "a": 18, + "b": 13, + "id": "k83", + "type": "tangent" + }, + { + "a": 19, + "b": 20, + "id": "k84", + "type": "tangent" + }, + { + "a": 19, + "b": 18, + "id": "k85", + "type": "tangent" + }, + { + "a": 40, + "b": 13, + "id": "k86", + "type": "tangent" + }, + { + "a": 35, + "b": 40, + "id": "k87", + "type": "parallel" + }, + { + "c": 41, + "id": "k88", + "p": 68, + "type": "point_on_curve" + }, + { + "c": 41, + "id": "k89", + "p": 33, + "type": "point_on_curve" + }, + { + "a": 41, + "b": 40, + "id": "k90", + "type": "perpendicular" + }, + { + "c": 4, + "id": "k91", + "param": "d3", + "type": "diameter", + "value": 11.423 + }, + { + "c": 5, + "id": "k92", + "param": "d4", + "type": "diameter", + "value": 3.38 + }, + { + "c": 3, + "id": "k93", + "param": "d5", + "type": "diameter", + "value": 40.0 + }, + { + "c": 6, + "id": "k94", + "param": "d6", + "type": "diameter", + "value": 6.08 + }, + { + "id": "k95", + "l": 7, + "p": 12, + "param": "d7", + "type": "point_line_distance", + "value": 9.7 + }, + { + "id": "k96", + "l": 7, + "p": 16, + "param": "d8", + "type": "point_line_distance", + "value": 6.0 + }, + { + "c": 12, + "id": "k97", + "param": "d9", + "type": "radius", + "value": 4.0 + }, + { + "id": "k98", + "p": 5, + "param": "d10", + "q": 69, + "type": "distance_y", + "value": 14.0 + }, + { + "a": 9, + "b": 10, + "flip": true, + "id": "k99", + "param": "d11", + "type": "angle", + "value": 1.5707963267948966 + }, + { + "c": 16, + "id": "k100", + "param": "d12", + "type": "radius", + "value": 0.4 + }, + { + "c": 21, + "id": "k101", + "param": "d13", + "type": "radius", + "value": 2.0 + }, + { + "c": 23, + "id": "k102", + "param": "d14", + "type": "radius", + "value": 2.266 + }, + { + "c": 24, + "id": "k103", + "param": "d15", + "type": "radius", + "value": 2.266 + }, + { + "id": "k104", + "l": 32, + "p": 67, + "param": "d16", + "type": "point_line_distance", + "value": 2.89 + }, + { + "id": "k105", + "l": 31, + "p": 21, + "param": "d17", + "type": "point_line_distance", + "value": 1.0928097244875001 + }, + { + "c": 22, + "id": "k106", + "param": "d18", + "type": "radius", + "value": 2.0 + }, + { + "c": 19, + "id": "k107", + "param": "d19", + "type": "radius", + "value": 4.0 + }, + { + "id": "k108", + "l": 39, + "p": 68, + "param": "d20", + "type": "point_line_distance", + "value": 2.89 + }, + { + "id": "k109", + "l": 35, + "p": 63, + "param": "d21", + "type": "point_line_distance", + "value": 1.2856194489750001 + }, + { + "a": 20, + "b": 18, + "id": "k110", + "param": "d22", + "type": "angle", + "value": 1.53588974175501 + } + ], + "counters": { + "a": 9, + "c": 11, + "k": 110 + }, + "curves": [ + { + "c": 1, + "construction": false, + "id": "c1", + "r": 23.039999999993093, + "type": "circle" + }, + { + "a": 2, + "b": 3, + "construction": false, + "fixed": true, + "id": "f1", + "type": "line" + }, + { + "a": 4, + "b": 5, + "construction": false, + "fixed": true, + "id": "f2", + "type": "line" + }, + { + "c": 6, + "construction": true, + "id": "c2", + "r": 20.0, + "type": "circle" + }, + { + "c": 7, + "construction": false, + "id": "c3", + "r": 5.7115, + "type": "circle" + }, + { + "c": 8, + "construction": false, + "id": "c4", + "r": 1.69, + "type": "circle" + }, + { + "c": 9, + "construction": false, + "id": "c5", + "r": 3.04, + "type": "circle" + }, + { + "a": 10, + "b": 11, + "construction": false, + "id": "f8", + "type": "line" + }, + { + "a": 12, + "b": 13, + "construction": false, + "id": "f9", + "type": "line" + }, + { + "a": 14, + "b": 15, + "construction": false, + "id": "f10", + "type": "line" + }, + { + "a": 16, + "b": 17, + "construction": false, + "id": "f11", + "type": "line" + }, + { + "c": 18, + "construction": false, + "id": "c6", + "r": 4.85000000031336, + "type": "circle" + }, + { + "a": 14, + "b": 16, + "c": 19, + "construction": false, + "id": "a1", + "type": "arc" + }, + { + "a": 17, + "b": 15, + "c": 20, + "construction": false, + "id": "a2", + "type": "arc" + }, + { + "a": 21, + "b": 22, + "construction": true, + "id": "f15", + "type": "line" + }, + { + "a": 23, + "b": 24, + "construction": true, + "id": "f16", + "type": "line" + }, + { + "a": 26, + "b": 27, + "c": 25, + "construction": false, + "id": "a3", + "type": "arc" + }, + { + "a": 29, + "b": 30, + "c": 28, + "construction": false, + "id": "a4", + "type": "arc" + }, + { + "a": 31, + "b": 32, + "construction": false, + "id": "f19", + "type": "line" + }, + { + "a": 31, + "b": 34, + "c": 33, + "construction": false, + "id": "a5", + "type": "arc" + }, + { + "a": 34, + "b": 35, + "construction": false, + "fixed": true, + "id": "f21", + "type": "line" + }, + { + "a": 37, + "b": 38, + "c": 36, + "construction": false, + "id": "a6", + "type": "arc" + }, + { + "a": 40, + "b": 41, + "c": 39, + "construction": false, + "id": "a7", + "type": "arc" + }, + { + "a": 43, + "b": 44, + "c": 42, + "construction": false, + "id": "a8", + "type": "arc" + }, + { + "a": 46, + "b": 47, + "c": 45, + "construction": false, + "id": "a9", + "type": "arc" + }, + { + "a": 44, + "b": 46, + "construction": false, + "id": "f26", + "type": "line" + }, + { + "c": 48, + "construction": false, + "id": "c7", + "r": 4.769278, + "type": "circle" + }, + { + "a": 49, + "b": 50, + "construction": false, + "id": "f29", + "type": "line" + }, + { + "a": 50, + "b": 51, + "construction": false, + "id": "f30", + "type": "line" + }, + { + "a": 51, + "b": 52, + "construction": false, + "id": "f31", + "type": "line" + }, + { + "a": 52, + "b": 53, + "construction": false, + "id": "f32", + "type": "line" + }, + { + "a": 53, + "b": 54, + "construction": false, + "id": "f33", + "type": "line" + }, + { + "a": 54, + "b": 49, + "construction": false, + "id": "f34", + "type": "line" + }, + { + "a": 55, + "b": 56, + "construction": true, + "id": "f35", + "type": "line" + }, + { + "a": 57, + "b": 58, + "construction": false, + "id": "f36", + "type": "line" + }, + { + "a": 58, + "b": 59, + "construction": false, + "id": "f37", + "type": "line" + }, + { + "a": 59, + "b": 60, + "construction": false, + "id": "f38", + "type": "line" + }, + { + "a": 60, + "b": 61, + "construction": false, + "id": "f39", + "type": "line" + }, + { + "a": 61, + "b": 62, + "construction": false, + "id": "f40", + "type": "line" + }, + { + "a": 62, + "b": 57, + "construction": false, + "id": "f41", + "type": "line" + }, + { + "a": 63, + "b": 64, + "construction": true, + "id": "f42", + "type": "line" + }, + { + "a": 65, + "b": 66, + "construction": true, + "id": "f43", + "type": "line" + }, + { + "c": 8, + "construction": false, + "id": "c8", + "r": 2.9756194489750003, + "type": "circle" + }, + { + "c": 48, + "construction": false, + "id": "c9", + "r": 3.9014682755125, + "type": "circle" + }, + { + "c": 67, + "construction": true, + "id": "c10", + "r": 3.3370845559221345, + "type": "circle" + }, + { + "c": 68, + "construction": true, + "id": "c11", + "r": 3.3370845559321887, + "type": "circle" + }, + { + "a": 19, + "b": 69, + "construction": true, + "id": "m13", + "type": "line" + } + ], + "offsets": [ + { + "closed": true, + "distance": -1.2856194489750001, + "outputs": [ + "c8" + ], + "sources": [ + [ + "c4", + true + ] + ] + }, + { + "closed": true, + "distance": 0.8678097244875, + "outputs": [ + "c9" + ], + "sources": [ + [ + "c7", + true + ] + ] + } + ], + "points": [ + { + "fixed": true, + "id": "origin", + "pos": [ + 0.0, + 0.0 + ] + }, + { + "fixed": false, + "id": "c1.center", + "pos": [ + 0.0, + 0.0 + ] + }, + { + "fixed": false, + "id": "f1.start", + "pos": [ + 20.0, + 0.0 + ] + }, + { + "fixed": false, + "id": "f1.end", + "pos": [ + 2.5, + 0.0 + ] + }, + { + "fixed": false, + "id": "f2.start", + "pos": [ + 0.0, + 2.5 + ] + }, + { + "fixed": false, + "id": "f2.end", + "pos": [ + 0.0, + 20.0 + ] + }, + { + "fixed": false, + "id": "c2.center", + "pos": [ + 0.0, + 0.0 + ] + }, + { + "fixed": false, + "id": "c3.center", + "pos": [ + 0.0, + 0.0 + ] + }, + { + "fixed": false, + "id": "c4.center", + "pos": [ + 0.0, + 0.0 + ] + }, + { + "fixed": false, + "id": "c5.center", + "pos": [ + 0.0, + 20.0 + ] + }, + { + "fixed": false, + "id": "f8.start", + "pos": [ + 4.7440572709653415, + 31.34676111743593 + ] + }, + { + "fixed": false, + "id": "f8.end", + "pos": [ + -3.3742393513795776, + 23.48382100606391 + ] + }, + { + "fixed": false, + "id": "f9.start", + "pos": [ + 11.492535932480322, + 24.37911906613869 + ] + }, + { + "fixed": false, + "id": "f9.end", + "pos": [ + 3.374239351627148, + 16.51617899409599 + ] + }, + { + "fixed": false, + "id": "f10.start", + "pos": [ + 3.3526183880788305, + 32.783388327578905 + ] + }, + { + "fixed": false, + "id": "f10.end", + "pos": [ + 18.113191685694147, + 17.543451096209797 + ] + }, + { + "fixed": false, + "id": "f11.start", + "pos": [ + -2.303513864705641, + 32.873764983207224 + ] + }, + { + "fixed": false, + "id": "f11.end", + "pos": [ + -17.543451096200045, + 18.11319168577141 + ] + }, + { + "fixed": false, + "id": "c6.center", + "pos": [ + 0.0, + 20.0 + ] + }, + { + "fixed": false, + "id": "a1.center", + "pos": [ + 0.4793639339100286, + 30.00051052899045 + ] + }, + { + "fixed": false, + "id": "a2.center", + "pos": [ + 0.0, + 0.0 + ] + }, + { + "fixed": false, + "id": "f15.start", + "pos": [ + 16.847551000017898, + 24.850000000311898 + ] + }, + { + "fixed": false, + "id": "f15.end", + "pos": [ + -16.623546999998876, + 24.85000000030438 + ] + }, + { + "fixed": false, + "id": "f16.start", + "pos": [ + 9.422256926787238, + 29.12588507090988 + ] + }, + { + "fixed": false, + "id": "f16.end", + "pos": [ + -5.157321843942895, + 15.004898848851603 + ] + }, + { + "fixed": false, + "id": "a3.center", + "pos": [ + 4.8180318380452976, + 17.914557789966715 + ] + }, + { + "fixed": false, + "id": "a3.start", + "pos": [ + 5.105357281825366, + 18.192845571526597 + ] + }, + { + "fixed": false, + "id": "a3.end", + "pos": [ + 4.530706394275853, + 17.63627000839571 + ] + }, + { + "fixed": false, + "id": "a4.center", + "pos": [ + -1.9304468658272427, + 24.88219980154129 + ] + }, + { + "fixed": false, + "id": "a4.start", + "pos": [ + -2.2177723095694275, + 24.603912019942214 + ] + }, + { + "fixed": false, + "id": "a4.end", + "pos": [ + -1.643121422091574, + 25.160487583147514 + ] + }, + { + "fixed": false, + "id": "f19.start", + "pos": [ + -18.22442760289246, + -28.043102894816247 + ] + }, + { + "fixed": false, + "id": "f19.end", + "pos": [ + -24.249511090231813, + -6.915316428320679 + ] + }, + { + "fixed": false, + "id": "a5.center", + "pos": [ + -14.377782739897706, + -26.94614195750076 + ] + }, + { + "fixed": false, + "id": "a5.end", + "pos": [ + -13.14724407183456, + -30.75216016376323 + ] + }, + { + "fixed": false, + "id": "f21.end", + "pos": [ + 7.757399536659945, + -23.993397880386595 + ] + }, + { + "fixed": false, + "id": "a6.center", + "pos": [ + -18.431106633933677, + -20.02547844408478 + ] + }, + { + "fixed": false, + "id": "a6.start", + "pos": [ + -17.076688481394942, + -18.553897162683164 + ] + }, + { + "fixed": false, + "id": "a6.end", + "pos": [ + -20.354429065319973, + -20.57395891270366 + ] + }, + { + "fixed": false, + "id": "a7.center", + "pos": [ + -6.3722554037222405, + -26.459777771923452 + ] + }, + { + "fixed": false, + "id": "a7.start", + "pos": [ + -5.756986069698662, + -28.362786875025243 + ] + }, + { + "fixed": false, + "id": "a7.end", + "pos": [ + -5.903987352160198, + -24.515369113302228 + ] + }, + { + "fixed": false, + "id": "a8.center", + "pos": [ + -4.991207836430458, + 27.116000000282124 + ] + }, + { + "fixed": false, + "id": "a8.start", + "pos": [ + -6.5677081093051095, + 28.74369864854841 + ] + }, + { + "fixed": false, + "id": "a8.end", + "pos": [ + -4.991207836431011, + 24.850000000301 + ] + }, + { + "fixed": false, + "id": "a9.center", + "pos": [ + 5.687131136239809, + 27.116000000296875 + ] + }, + { + "fixed": false, + "id": "a9.start", + "pos": [ + 5.687131136241227, + 24.85000000030553 + ] + }, + { + "fixed": false, + "id": "a9.end", + "pos": [ + 7.314829784503578, + 28.692500273173373 + ] + }, + { + "fixed": false, + "id": "c7.center", + "pos": [ + 0.0, + 0.0 + ] + }, + { + "fixed": false, + "id": "f29.start", + "pos": [ + 3.816448489842134, + 28.832809725100045 + ] + }, + { + "fixed": false, + "id": "f29.end", + "pos": [ + 2.1479062119469194, + 31.722809725139882 + ] + }, + { + "fixed": false, + "id": "f30.end", + "pos": [ + -1.1891783439734689, + 31.72280972521438 + ] + }, + { + "fixed": false, + "id": "f31.end", + "pos": [ + -2.8577206219999844, + 28.832809725246687 + ] + }, + { + "fixed": false, + "id": "f32.end", + "pos": [ + -1.1891783441055306, + 25.942809725201045 + ] + }, + { + "fixed": false, + "id": "f33.end", + "pos": [ + 2.1479062118179804, + 25.942809725129404 + ] + }, + { + "fixed": false, + "id": "f35.start", + "pos": [ + 0.4793639339148472, + 30.00051052899103 + ] + }, + { + "fixed": false, + "id": "f35.end", + "pos": [ + 0.4793639339176719, + 28.099835000004717 + ] + }, + { + "fixed": false, + "id": "f36.start", + "pos": [ + -10.884207425092901, + -27.370019276197922 + ] + }, + { + "fixed": false, + "id": "f36.end", + "pos": [ + -11.15004687559625, + -24.04354024875941 + ] + }, + { + "fixed": false, + "id": "f37.end", + "pos": [ + -14.1637819437734, + -22.61052445251943 + ] + }, + { + "fixed": false, + "id": "f38.end", + "pos": [ + -16.911677561437795, + -24.50398768371017 + ] + }, + { + "fixed": false, + "id": "f39.end", + "pos": [ + -16.645838110929827, + -27.830466711150418 + ] + }, + { + "fixed": false, + "id": "f40.end", + "pos": [ + -13.632103042753231, + -29.263482507393416 + ] + }, + { + "fixed": false, + "id": "f42.start", + "pos": [ + -20.122238683726938, + -18.353752325108776 + ] + }, + { + "fixed": false, + "id": "f42.end", + "pos": [ + 7.132273151961092, + -31.313134976753147 + ] + }, + { + "fixed": false, + "id": "f43.start", + "pos": [ + -17.758870146527276, + -34.05681144040707 + ] + }, + { + "fixed": false, + "id": "f43.end", + "pos": [ + -12.402122358346736, + -22.79118637850851 + ] + }, + { + "fixed": false, + "id": "c10.center", + "pos": [ + 0.47936393392077803, + 28.832809725170332 + ] + }, + { + "fixed": false, + "id": "c11.center", + "pos": [ + -13.897942493266378, + -25.937003479957074 + ] + }, + { + "fixed": false, + "id": "q21", + "pos": [ + 0.5432698799540695, + 34.0000000001017 + ] + } + ] + }, + "suppressed": false, + "type": "sketch" + }, + "params": [ + { + "name": "d1", + "expression": "three_lines", + "unit": "mm" + }, + { + "name": "d10", + "expression": "14 mm", + "unit": "mm" + }, + { + "name": "d11", + "expression": "90 deg", + "unit": "deg" + }, + { + "name": "d12", + "expression": "0.4 mm", + "unit": "mm" + }, + { + "name": "d13", + "expression": "2 mm", + "unit": "mm" + }, + { + "name": "d14", + "expression": "2.266 mm", + "unit": "mm" + }, + { + "name": "d15", + "expression": "2.266 mm", + "unit": "mm" + }, + { + "name": "d16", + "expression": "2.89 mm", + "unit": "mm" + }, + { + "name": "d17", + "expression": "two_and_half_lines", + "unit": "mm" + }, + { + "name": "d18", + "expression": "2 mm", + "unit": "mm" + }, + { + "name": "d19", + "expression": "4 mm", + "unit": "mm" + }, + { + "name": "d2", + "expression": "two_lines", + "unit": "mm" + }, + { + "name": "d20", + "expression": "2.89 mm", + "unit": "mm" + }, + { + "name": "d21", + "expression": "three_lines", + "unit": "mm" + }, + { + "name": "d22", + "expression": "88 deg", + "unit": "deg" + }, + { + "name": "d3", + "expression": "housing_center_diameter", + "unit": "mm" + }, + { + "name": "d4", + "expression": "screw_diameter", + "unit": "mm" + }, + { + "name": "d5", + "expression": "40 mm", + "unit": "mm" + }, + { + "name": "d6", + "expression": "caliberX", + "unit": "mm" + }, + { + "name": "d7", + "expression": "housing_barrel_cut_width", + "unit": "mm" + }, + { + "name": "d8", + "expression": "housing_barrel_cut_edge_separation", + "unit": "mm" + }, + { + "name": "d9", + "expression": "4 mm", + "unit": "mm" + } + ] + } + }, + { + "command": "timeline.add", + "params": { + "feature": { + "body_names": [ + "Body7" + ], + "extent": { + "convention": "total_distance", + "direction": "positive", + "distance": "housing_bottom_thickness" + }, + "id": 34, + "name": "base", + "operation": "new_body", + "param_names": [ + "d31" + ], + "profiles": { + "indices": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29 + ], + "type": "indices" + }, + "sketch": 30, + "suppressed": false, + "type": "extrude" + } + } + }, + { + "command": "timeline.add", + "params": { + "feature": { + "extent": { + "convention": "total_distance", + "direction": "positive", + "distance": "total_height" + }, + "id": 35, + "name": "housing walls", + "operation": "join", + "param_names": [ + "d32" + ], + "profiles": { + "loops": [ + [ + "c1", + "c6", + "f8", + "f8", + "f26", + "a8", + "f11", + "a2", + "a2", + "a2", + "a2", + "a2", + "f10", + "f9" + ], + [ + "c1", + "f9", + "f10", + "a9", + "f26", + "c6" + ], + [ + "c1", + "c6", + "c6", + "c6", + "c6", + "c1" + ], + [ + "f8", + "f10", + "a1", + "f11", + "a8", + "f26", + "f8", + "f8", + "f33", + "f32", + "f31", + "f30", + "f29" + ], + [ + "f8", + "f29", + "f34", + "f33", + "f8", + "a4", + "f26", + "f26", + "a9", + "f10" + ], + [ + "f8", + "f29", + "f30", + "f31", + "f32", + "f33" + ], + [ + "f8", + "f33", + "f34", + "f29" + ], + [ + "f8", + "a4", + "a4", + "f26" + ], + [ + "f8", + "c6", + "a4" + ], + [ + "f8", + "f26", + "a4" + ], + [ + "c6", + "f26", + "a4" + ], + [ + "a2", + "a6", + "f19", + "a5", + "f21", + "a7" + ], + [ + "a2", + "a7", + "f21" + ], + [ + "a2", + "f19", + "a6" + ], + [ + "f36", + "f37", + "f38", + "f39", + "f40", + "f41" + ] + ], + "type": "curves" + }, + "sketch": 30, + "suppressed": false, + "targets": [ + "Body7" + ], + "type": "extrude" + } + } + }, + { + "command": "timeline.add", + "params": { + "feature": { + "extent": { + "convention": "total_distance", + "direction": "positive", + "distance": "housing_center_height" + }, + "id": 36, + "name": "housing center", + "operation": "join", + "param_names": [ + "d33" + ], + "profiles": { + "indices": [ + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 29 + ], + "type": "indices" + }, + "sketch": 30, + "suppressed": false, + "targets": [ + "Body7" + ], + "type": "extrude" + } + } + }, + { + "command": "timeline.add", + "params": { + "feature": { + "extent": { + "convention": "total_distance", + "direction": "positive", + "distance": "housing_barrel_cut_depth" + }, + "id": 38, + "name": "barrel cut", + "operation": "cut", + "param_names": [ + "d35" + ], + "profiles": { + "loops": [ + [ + "c1", + "f9", + "f10", + "a9", + "f26", + "c6" + ], + [ + "c1", + "c6", + "f2", + "c5" + ], + [ + "c1", + "c5", + "f2", + "c6", + "c6", + "c6" + ], + [ + "c1", + "c6", + "c6", + "c6", + "c6", + "c1" + ], + [ + "c1", + "c6", + "a3", + "f9" + ], + [ + "c5", + "c5" + ], + [ + "f8", + "f29", + "f34", + "f33", + "f8", + "a4", + "f26", + "f26", + "a9", + "f10" + ], + [ + "f8", + "f33", + "f34", + "f29" + ], + [ + "f8", + "a4", + "a4", + "f26" + ], + [ + "f8", + "c6", + "a4" + ], + [ + "f8", + "f26", + "a4" + ], + [ + "f9", + "a3", + "a3" + ], + [ + "f9", + "a3", + "c6" + ], + [ + "c6", + "f26", + "a4" + ] + ], + "type": "curves" + }, + "sketch": 30, + "suppressed": false, + "targets": [ + "Body7" + ], + "type": "extrude" + } + } + }, + { + "command": "timeline.add", + "params": { + "feature": { + "extent": { + "convention": "total_distance", + "direction": "negative", + "distance": "housing_lid_recess", + "from": [ + -2.931496, + 23.94939, + 15.0 + ] + }, + "face_names": [ + "F35:top" + ], + "id": 41, + "name": "lid recess", + "operation": "cut", + "param_names": [ + "d39" + ], + "profiles": { + "loops": [ + [ + "c1", + "c6", + "f8", + "f8", + "f26", + "a8", + "f11", + "a2", + "a2", + "a2", + "a2", + "a2", + "f10", + "f9" + ], + [ + "c1", + "f9", + "f10", + "a9", + "f26", + "c6" + ], + [ + "c1", + "c6", + "c6", + "c6", + "c6", + "c1" + ], + [ + "f8", + "f10", + "a1", + "f11", + "a8", + "f26", + "f8", + "f8", + "f33", + "f32", + "f31", + "f30", + "f29" + ], + [ + "f8", + "f29", + "f34", + "f33", + "f8", + "a4", + "f26", + "f26", + "a9", + "f10" + ], + [ + "f8", + "f29", + "f30", + "f31", + "f32", + "f33" + ], + [ + "f8", + "f33", + "f34", + "f29" + ], + [ + "f8", + "a4", + "a4", + "f26" + ], + [ + "f8", + "c6", + "a4" + ], + [ + "f8", + "f26", + "a4" + ], + [ + "c6", + "f26", + "a4" + ], + [ + "a2", + "a6", + "f19", + "a5", + "f21", + "a7" + ], + [ + "a2", + "a7", + "f21" + ], + [ + "a2", + "f19", + "a6" + ], + [ + "f36", + "f37", + "f38", + "f39", + "f40", + "f41" + ] + ], + "type": "curves" + }, + "sketch": 30, + "suppressed": false, + "targets": [ + "Body7" + ], + "type": "extrude" + } + } + }, + { + "command": "timeline.add", + "params": { + "feature": { + "extent": { + "convention": "total_distance", + "direction": "negative", + "distance": "magnet_depth", + "from": [ + -11.736601, + -22.705797, + 10.5 + ], + "taper": "3 deg" + }, + "face_names": [ + "F47:top#[F34:side:a5,F34:side:f19,F34:side:f21,F47:side:a2,F47:side:a6,F47:side:a7]" + ], + "id": 48, + "name": "Extrude13", + "operation": "cut", + "param_names": [ + "d42", + "d43" + ], + "profiles": { + "loops": [ + [ + "f8", + "f29", + "f30", + "f31", + "f32", + "f33" + ], + [ + "f8", + "f33", + "f34", + "f29" + ], + [ + "f36", + "f37", + "f38", + "f39", + "f40", + "f41" + ] + ], + "type": "curves" + }, + "sketch": 30, + "suppressed": false, + "targets": [ + "Body7" + ], + "type": "extrude" + } + } + }, + { + "command": "timeline.add", + "params": { + "feature": { + "id": 57, + "name": "housing pellet exit", + "plane": { + "name": "XY", + "type": "origin" + }, + "sketch": { + "constraints": [ + { + "c": 0, + "id": "k1", + "p": 3, + "type": "point_on_curve" + }, + { + "a": 2, + "b": 3, + "id": "k2", + "type": "equal" + }, + { + "c": 0, + "id": "k3", + "p": 5, + "type": "point_on_curve" + }, + { + "a": 3, + "b": 4, + "id": "k4", + "type": "equal" + }, + { + "a": 4, + "b": 3, + "id": "k5", + "type": "tangent" + }, + { + "id": "k6", + "p": 3, + "param": "d55", + "q": 4, + "type": "distance_x", + "value": 6.58 + } + ], + "counters": { + "c": 5, + "k": 6 + }, + "curves": [ + { + "c": 1, + "construction": false, + "fixed": true, + "id": "c1", + "r": 20.0, + "type": "circle" + }, + { + "c": 2, + "construction": false, + "fixed": true, + "id": "c2", + "r": 23.04, + "type": "circle" + }, + { + "c": 3, + "construction": false, + "id": "c3", + "r": 3.04, + "type": "circle" + }, + { + "c": 4, + "construction": false, + "fixed": true, + "id": "c4", + "r": 3.04, + "type": "circle" + }, + { + "c": 5, + "construction": false, + "id": "c5", + "r": 3.04, + "type": "circle" + } + ], + "points": [ + { + "fixed": true, + "id": "origin", + "pos": [ + 0.0, + 0.0 + ] + }, + { + "fixed": false, + "id": "c1.center", + "pos": [ + 0.0, + 0.0 + ] + }, + { + "fixed": false, + "id": "c2.center", + "pos": [ + 0.0, + 0.0 + ] + }, + { + "fixed": false, + "id": "c3.center", + "pos": [ + 6.58, + 18.88659842322063 + ] + }, + { + "fixed": false, + "id": "c4.center", + "pos": [ + 0.0, + 20.0 + ] + }, + { + "fixed": false, + "id": "c5.center", + "pos": [ + -6.009353400691293, + 19.07584 + ] + } + ] + }, + "suppressed": false, + "type": "sketch" + }, + "params": [ + { + "name": "d55", + "expression": "caliberX + 0.5 mm", + "unit": "mm" + } + ] + } + }, + { + "command": "timeline.add", + "params": { + "feature": { + "extent": { + "convention": "total_distance", + "direction": "positive", + "distance": "0", + "from": [ + 2.317238, + 22.24435, + 1.6 + ], + "to": [ + 2.317238, + 22.24435, + 2.8 + ] + }, + "face_names": [ + "F34:top", + "F38:top" + ], + "id": 68, + "name": "Extrude1", + "operation": "cut", + "param_names": [ + "d77" + ], + "profiles": { + "indices": [ + 3, + 6 + ], + "type": "indices" + }, + "sketch": 57, + "suppressed": false, + "targets": [ + "Body7" + ], + "type": "extrude" + } + } + } + ] +} From 37a8402cae2380af08035bf00f4839a1c3154a1f Mon Sep 17 00:00:00 2001 From: Irakli Kourtis Date: Tue, 20 Oct 2026 04:26:12 +0000 Subject: [PATCH 180/225] surface.blend: seam alignment, chain-topology refusal and a dialog (#764) (#2488) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * kernel: a blend runs along chains of several faces and lines closed rims up (#764) A blend's chain may run along the boundaries of several faces (a tube's rim along the halves of its wall): each edge continues from its own best-facing face, read station by station. Before, a chain had to be the edges of one face, so every rim of a revolved or cylindrical surface was refused. Two closed chains blend from matching seams: the second chain's start (searched by arclength, then narrowed) and direction are the ones that put each station closest to its partner, so rims whose seams sit apart no longer twist. A picked `seam` point on each chain fixes the start instead. A closed chain against an open one is refused. Closed chains leave towards each other's centroid, not a point on the rim. Stations are read on the edges' own curves, not on the chords of the length table (they sat up to the chord's sagitta inside a curved edge), and the reported gap is measured to the curves. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LGeCa5jWWdroMWvXxN3LLM * kernel: closed blend chains run round the same way; Hermite strip and seam tests (#764) The second of two closed chains runs round the same way as the first (by their area vectors), so a picked seam turns the blend by just the angle between the seams instead of folding it over. The nearer pairing decides only when the loops stand almost at right angles. Tests for the issue's gates: the blend between two offset box rims is the analytic cubic Hermite strip (control points from the chord) and keeps the top faces' normal along both seams; picked seams a quarter apart turn the blend a quarter round. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LGeCa5jWWdroMWvXxN3LLM * surface.blend: `seam` picks where each chain's stations start (#764) A point on each chain, saved with the feature (one pending format change), moved with the design like `align`, and refused when it is not two points. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LGeCa5jWWdroMWvXxN3LLM * surface.blend: a test between two tube rims, their seams picked and saved (#764) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LGeCa5jWWdroMWvXxN3LLM * Blend dialog: edges at each end, continuity and bulge per end, stitch (#764) SURFACE › CREATE › Blend Surface opens a dialog: the edges the blend leaves and the ones it arrives at, each end's continuity (G0–G3) and bulge, and Stitch to both bodies. Edit Feature brings it back and keeps what the dialog does not show (align and seam points). Labels in every locale catalog. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LGeCa5jWWdroMWvXxN3LLM * ROADMAP: M8 Blend runs along several faces, pairs closed rims and has a dialog (#764) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LGeCa5jWWdroMWvXxN3LLM * kernel: a blend station on the vertex between two support faces is read on the neighbour (#764) A station where a tube wall's two halves meet sits at a corner of one half's parameters; with a leave direction that turns round the wall (tubes off each other's axis) the shape could not be read there and the blend was refused. The neighbouring chain edge's face holds the same point and reads it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LGeCa5jWWdroMWvXxN3LLM * blend: review clean-ups (#764) - ChainLine keeps one list of samples instead of four parallel lists. - frames_on and boundary_gap take the chain's ChainLine instead of rebuilding it. - A station is read on the neighbouring face only when it sits on the vertex the two edges share, each face once, and each face keeps its own walk. - The seam rule (a closed chain starts at it, an open one runs from the nearer end) lives in ChainLine::start_at_seam; pair_with reuses the start of its both-ways search. - support_faces projects with curveblend::project; loop_area sits with plane_through. - surface.blend parses `align` and `seam` through one point_pair; the Blend and Ruled dialogs share body_and_edges. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LGeCa5jWWdroMWvXxN3LLM --------- Co-authored-by: jyviko <2501648+jyviko@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- ROADMAP.md | 2 +- assets/locales/cs.json | 4 + assets/locales/de.json | 4 + assets/locales/en.json | 9 + assets/locales/es.json | 4 + assets/locales/fr.json | 4 + assets/locales/gl.json | 4 + assets/locales/it.json | 4 + assets/locales/ja.json | 9 + assets/locales/ko.json | 4 + assets/locales/pt-BR.json | 4 + assets/locales/ru.json | 4 + assets/locales/tr.json | 4 + assets/locales/uk.json | 4 + assets/locales/zh.json | 9 + crates/doc/src/document.rs | 5 + crates/doc/src/eval_surface.rs | 3 +- crates/doc/src/feature_walk_tests/fixtures.rs | 10 +- .../feature_walk_tests/golden_geometry.txt | 4 +- .../src/format/pending/surface-blend-seam.rs | 4 + crates/engine/src/cmd/surface.rs | 75 +++- crates/engine/src/tests.rs | 1 + crates/kernel/src/bridge.rs | 419 +++++++++++++----- crates/kernel/src/bridge_tests.rs | 138 ++++++ crates/kernel/src/plane_fit.rs | 11 + crates/ui-egui/src/blend_dialog_tests.rs | 82 ++++ crates/ui-egui/src/dialogs_surface.rs | 91 +++- crates/ui-egui/src/lib.rs | 2 + 28 files changed, 792 insertions(+), 126 deletions(-) create mode 100644 crates/doc/src/format/pending/surface-blend-seam.rs create mode 100644 crates/ui-egui/src/blend_dialog_tests.rs diff --git a/ROADMAP.md b/ROADMAP.md index ab228a469..c7b5de281 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -57,7 +57,7 @@ PCB / Package, Render, Animation, Simulation, Manufacture/CAM, Drawings. | M5 | Persistent naming of faces and edges (docs/book/src/dev/naming.md): faces named from their exact kernel-reported history (sketch curve sides, caps, revolve sections, primitive sides, blends, shell inner walls, pattern/mirror copies; split pieces told apart by the faces around them, lumps of a cut body named after their faces), edges by their faces; fillets/chamfers, sketches on faces, shell/draft/offset/replace faces, hole placements, joint origins and face appearances resolve by name first and warn when the entity split or vanished: done. sheet metal edges by base sketch line and flange side, shell inner faces, sweep and loft roles: done. kernel-reported face history: done (merged faces answer to every name; operations without history yet fall back to geometric names, flagged unverified; format 14 keeps older designs' geometric names). Left: history through sheet metal, plastic, surface and emboss features; FaceSource certificates through history | in progress | 20 | | M6 | UI depth: selection feedback and origin (done), timeline editing (done: hover and selection highlight modifier faces, including fillets and chamfers; edit feature, history marker drag, dependency-checked single and multi-item reorder, suppress, rename, delete with dependents, re-resolved references; redefining selections refreshes persistent edge/face references while retaining feature identity and dimension names; optional compact named left feature history with rollback bar, multi-selection and persistent folders above the parts browser), right-docked dialogs (done), live previews for every feature dialog (done), keyboard-first commands with on-canvas value boxes and sketch inline dimensions (done), drag manipulators with automatic join/cut (done: extrude incl. two sides, fillet, shell, hole depth, move, pattern spacing, revolve rotator, extrude taper), dark theme (done), right-click menu with Repeat (done), measure tool (done), section analysis (done), selection filter (done), drag-solve of sketch points (done); appearance controls now preserve body/face/component targeting, named transparent looks, reuse/search and override removal; preferences | in progress | 6 | | M7 | Thin extrude (walls along open or closed curves: centre, inside, outside or two sides; mitred corners, crossing walls joined; #721), sweep, loft (incl. to a point), rib and web (to next / depth), emboss (planar faces and exact radial emboss/deboss of bounded orthogonal profiles on complete exterior cylinders/sleeves), thread (cosmetic, and modelled M3–M20 outside and inside: the ISO profile screwed in as a faceted cut), coil (smooth B-spline helical walls), pipe, pattern on path, patterns of bodies and components, replace face (parallel), align, remove, feature copy/paste: done. Unique eligible cylindrical targets are inferred for new Emboss features. Left: general curved-face emboss and exact (unfaceted) modelled threads | in progress | 12 | -| M8 | Surface workspace (#772). Done: Patch (sketch regions; edge loops filled G0, plus `crown`), Stitch, Thicken (planes and cylinders), Extend (straight edges of planar surfaces), Trim (by a plane, a face or sketch curves swept onto the surface, keeping a side or the picked regions; mutual trim of two surfaces, extended to meet and stitched, #767), Delete Face (healing), Boundary Fill, zebra/draft/curvature-map analysis, Surface Extrude/Revolve/Sweep/Loft from open and closed curves, Offset, Unstitch and Reverse Normal; the continuity-driven core (`kernel/src/bridge.rs`, G0–G3 Hermite rows) with **Blend** (`surface.blend`, #764), **Match** (`surface.match`), **Boundary** (`surface.boundary`, #763 — two sketch curves exact with G0–G3, three or four as the flat patch of their loop, and curve networks: Coons and Gordon surfaces through sketch, 3D-sketch or edge curves, a point for a three-sided side, G1/G2 against the faces along one direction's edges, joined into their body on request; G1/G2 on two sides that meet at a corner waits for the Gregory-type corner), **Fair** (`surface.fair`, CV fairing), **continuity analysis** (`inspect.continuity`, #770; a toolbar tool with edge markers and a legend, and curvature combs along face isocurves) and a multi-section **loft** with per-end continuity and crown, and guide rails on solid and surface lofts (one or two, scaling or stretching the sections between; #201). Also in the Class-A pass: G1…G4 blend curves in the sketch, chord and variable-radius fillets on curved edges (with honest refusals where the fit cannot hold), and a G2 corner patch where filleted edges meet (kernel; the command refuses until the patch's sections can be sewn to the blends' contacts). Left: bias/form-factor fillet sections (design recorded), a Gregory-type corner, surface Fillet between separate surface bodies (#769), Ruled (#762), Untrim (#761), curved-face Extend (#760), and every remaining #757–#772 item | deferred | — | +| M8 | Surface workspace (#772). Done: Patch (sketch regions; edge loops filled G0, plus `crown`), Stitch, Thicken (planes and cylinders), Extend (straight edges of planar surfaces), Trim (by a plane, a face or sketch curves swept onto the surface, keeping a side or the picked regions; mutual trim of two surfaces, extended to meet and stitched, #767), Delete Face (healing), Boundary Fill, zebra/draft/curvature-map analysis, Surface Extrude/Revolve/Sweep/Loft from open and closed curves, Offset, Unstitch and Reverse Normal; the continuity-driven core (`kernel/src/bridge.rs`, G0–G3 Hermite rows) with **Blend** (`surface.blend`, #764: edge chains along one or several faces, closed rims paired seam to seam or from picked seams, a dialog), **Match** (`surface.match`), **Boundary** (`surface.boundary`, #763 — two sketch curves exact with G0–G3, three or four as the flat patch of their loop, and curve networks: Coons and Gordon surfaces through sketch, 3D-sketch or edge curves, a point for a three-sided side, G1/G2 against the faces along one direction's edges, joined into their body on request; G1/G2 on two sides that meet at a corner waits for the Gregory-type corner), **Fair** (`surface.fair`, CV fairing), **continuity analysis** (`inspect.continuity`, #770; a toolbar tool with edge markers and a legend, and curvature combs along face isocurves) and a multi-section **loft** with per-end continuity and crown, and guide rails on solid and surface lofts (one or two, scaling or stretching the sections between; #201). Also in the Class-A pass: G1…G4 blend curves in the sketch, chord and variable-radius fillets on curved edges (with honest refusals where the fit cannot hold), and a G2 corner patch where filleted edges meet (kernel; the command refuses until the patch's sections can be sewn to the blends' contacts). Left: bias/form-factor fillet sections (design recorded), a Gregory-type corner, surface Fillet between separate surface bodies (#769), Ruled (#762), Untrim (#761), curved-face Extend (#760), and every remaining #757–#772 item | deferred | — | | M9 | Components and assemblies: New Component / Create Components from Bodies, active component, per-component origin/bodies/sketches/timeline entries, occurrences with transforms, Copy/Paste vs Paste New, nested Browser tree with visibility and isolate; Ground, Move/Copy of occurrences, joints (rigid, revolute, slider, cylindrical, pin-slot, planar, ball) by joint origins with limits and Drive Joints, closed kinematic loops (four-bar, slider-crank: the loop's other joints follow the driven one on its branch, and driving stops where a loop can no longer close), cams (`joint.cam`: a revolute cam drives a slider or revolute follower along a closed sketch profile or the cam's edges, knife, roller or flat followers, worked out again when the profile changes; drives, studies, closed loops, contact sets), As-built Joint, Rigid Group, Contact Sets (driving and motion studies stop where bodies in a set would pass through each other), Motion Study (joint values keyed along a timeline, playback, export of occurrence positions as JSON/CSV), motion analysis (joint values and a point's path charted over a study as value, velocity and acceleration; the parts that collide along a study, with the steps where they do), Exploded views (automatic or by hand, shown without changing placements); interference, per-component physical properties; STEP with assembly structure; URDF export for robot simulators (links with meshes, mass and inertia; joint chains whose values match Drive Joints; docs/urdf.md). Physical properties now measure material-aware component/occurrence placements, descendants and repeated instances, including pending moves and body reassignment offsets; contact geometry and automatic exploded centres respect those offsets. Groundwork done: component tree, occurrences with transforms (instances, Paste New), world placement, active component as authoring frame, ground, Capture/Revert Position, moving bodies and sketches. UI: ASSEMBLE panel dialogs for New Component, Joint (snaps on faces, edges, circles and vertices; animated motion preview; offsets, flip, limits), As-built Joint, Joint Origin, Rigid Group, Drive Joints (live slider), Motion Link, Cam and Interference (overlaps shown red); joints in the timeline and the Browser | in progress | 32 | | M10 | Sheet metal: flange (base, edge, contour), hem, unfold/refold, convert, flat pattern + DXF, rules: done. PLASTIC enclosure subset: Boss, Rib, Web, Lip/Groove, Snap Fit, Rest, Plastic Rules (library, edit, assign; rule draft and clearance as feature defaults): done, tested against hand-computed geometry. UI: SHEET METAL and PLASTIC tabs with dialogs (live preview, Edit Feature, pre-selection) for Flange, Hem, Unfold/Refold, Convert, Sheet Metal Rules, Create Flat Pattern (flat view with bend lines, bend table CSV/JSON and DXF export with exact circle/arc/line cutouts), Boss, Lip/Groove, Snap Fit, Rest, Manage and Assign Plastic Rules; Fold (bend along a sketch line); flanges meeting at a corner closed at any angle with the rule's gap; edge flanges with their own angle and height per edge in one feature; corner reliefs (notch, round, rectangular, tear) chosen by the rule; Convert to Sheet Metal from a solid or shelled body by its bend edges (flat faces, sharp bends) | in progress | 36 | | M11 | 2D drawings | deferred | — | diff --git a/assets/locales/cs.json b/assets/locales/cs.json index ba131237d..8c4d47f64 100644 --- a/assets/locales/cs.json +++ b/assets/locales/cs.json @@ -73,6 +73,7 @@ "Current orthographic view (1:1 mm)": "Aktuální pravoúhlý pohled (1:1 mm)", "Current perspective view": "Aktuální perspektivní pohled", "Curvature (G2)": "Křivost (G2)", + "Curvature change (G3)": "Změna křivosti (G3)", "Customize Toolbar": "Přizpůsobit panel nástrojů", "Delete all": "Smazat vše", "Delete rule": "Smazat pravidlo", @@ -113,6 +114,7 @@ "Follow camera (Look At sketches)": "Sledovat kameru (náčrty natočené k pohledu)", "Follow the camera (Look At sketches)": "Sledovat kameru (náčrty natočené k pohledu)", "Font": "Písmo", + "From edges": "Výchozí hrany", "Full Length": "Celá délka", "Grid": "Mřížka", "Height": "Výška", @@ -250,6 +252,7 @@ "Step": "Krok", "Steps": "Kroky", "Stitch the kept pieces": "Sešít ponechané části", + "Stitch to both bodies": "Sešít s oběma tělesy", "Style": "Styl", "Suppressed": "Potlačeno", "Surface": "Plocha", @@ -270,6 +273,7 @@ "This child is shared. Position changes apply to every copy of its parent.": "Tento potomek je sdílený. Změny polohy se projeví ve všech kopiích jeho rodiče.", "This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "Tato plocha nemůže poskytnout trvalé připojení. Zvolte jinou plochu nebo výslovně použijte pevnou rovinu.", "To Offset": "Odsazení k objektu", + "To edges": "Cílové hrany", "Tolerance": "Tolerance", "Trimming tool (plane, face or curves)": "Ořezávací nástroj (rovina, plocha nebo křivky)", "Turn off section analysis before exporting the view.": "Před exportem pohledu vypněte analýzu řezu.", diff --git a/assets/locales/de.json b/assets/locales/de.json index 4562094e6..8be6072b1 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -26,6 +26,7 @@ "Current orthographic view (1:1 mm)": "Aktuelle orthogonale Ansicht (1:1 mm)", "Current perspective view": "Aktuelle perspektivische Ansicht", "Curvature (G2)": "Krümmung (G2)", + "Curvature change (G3)": "Krümmungsänderung (G3)", "Direction": "Richtung", "Do not export hidden edges": "Verdeckte Kanten nicht exportieren", "Don't ask again": "Nicht mehr fragen", @@ -44,6 +45,7 @@ "Faces": "Flächen", "Find in Browser": "Im Browser suchen", "Flat": "Flach", + "From edges": "Ausgangskanten", "Hidden edges": "Verdeckte Kanten", "Holes": "Löcher", "Holes (edges on them)": "Löcher (ihre Kanten)", @@ -92,6 +94,7 @@ "Sketch points": "Skizzenpunkte", "Slot width": "Langlochbreite", "Stitch the kept pieces": "Behaltene Teile vernähen", + "Stitch to both bodies": "Mit beiden Körpern vernähen", "Study": "Untersuchung", "Surface": "Flächenkörper", "TRIM": "TRIMMEN", @@ -100,6 +103,7 @@ "Thickness Outside": "Dicke außen", "Thin": "Dünnwandig", "Thin Extrude": "Dünnwandig extrudieren", + "To edges": "Zielkanten", "Trimming tool (plane, face or curves)": "Trimmwerkzeug (Ebene, Fläche oder Kurven)", "Turn off section analysis before exporting the view.": "Deaktivieren Sie die Schnittanalyse, bevor Sie die Ansicht exportieren.", "Type": "Typ", diff --git a/assets/locales/en.json b/assets/locales/en.json index 54d6af143..1419c4bb2 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -31,6 +31,7 @@ "Arc length": "Arc length", "Area": "Area", "Attachment": "Attachment", + "BLEND SURFACE": "BLEND SURFACE", "BOUNDARY SURFACE": "BOUNDARY SURFACE", "BROWSER": "BROWSER", "Bend Line Position": "Bend Line Position", @@ -79,6 +80,7 @@ "Current orthographic view (1:1 mm)": "Current orthographic view (1:1 mm)", "Current perspective view": "Current perspective view", "Curvature (G2)": "Curvature (G2)", + "Curvature change (G3)": "Curvature change (G3)", "Customize Toolbar": "Customize Toolbar", "Delete all": "Delete all", "Delete rule": "Delete rule", @@ -100,6 +102,8 @@ "Edit Profile Sketch": "Edit Profile Sketch", "Enable rule": "Enable rule", "Enabled": "Enabled", + "End bulge": "End bulge", + "End continuity": "End continuity", "Explode": "Explode", "Explode Text": "Explode Text", "Export Animation…": "Export Animation…", @@ -122,6 +126,7 @@ "Follow camera (Look At sketches)": "Follow camera (Look At sketches)", "Follow the camera (Look At sketches)": "Follow the camera (Look At sketches)", "Font": "Font", + "From edges": "From edges", "Full Length": "Full Length", "Grid": "Grid", "Height": "Height", @@ -262,9 +267,12 @@ "Stand it up": "Stand it up", "Stand it up: a quarter turn about X, as one Move feature you can undo.": "Stand it up: a quarter turn about X, as one Move feature you can undo.", "Stand this part up?": "Stand this part up?", + "Start bulge": "Start bulge", + "Start continuity": "Start continuity", "Step": "Step", "Steps": "Steps", "Stitch the kept pieces": "Stitch the kept pieces", + "Stitch to both bodies": "Stitch to both bodies", "Study": "Study", "Style": "Style", "Suppressed": "Suppressed", @@ -286,6 +294,7 @@ "This child is shared. Position changes apply to every copy of its parent.": "This child is shared. Position changes apply to every copy of its parent.", "This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.", "To Offset": "To Offset", + "To edges": "To edges", "Tolerance": "Tolerance", "Too close": "Too close", "Trimming tool (plane, face or curves)": "Trimming tool (plane, face or curves)", diff --git a/assets/locales/es.json b/assets/locales/es.json index 3097988a8..feb3db124 100644 --- a/assets/locales/es.json +++ b/assets/locales/es.json @@ -77,6 +77,7 @@ "Current orthographic view (1:1 mm)": "Vista ortográfica actual (1:1 mm)", "Current perspective view": "Vista en perspectiva actual", "Curvature (G2)": "Curvatura (G2)", + "Curvature change (G3)": "Cambio de curvatura (G3)", "Customize Toolbar": "Personalizar barra de herramientas", "Delete all": "Eliminar todo", "Delete rule": "Eliminar regla", @@ -120,6 +121,7 @@ "Follow camera (Look At sketches)": "Seguir cámara (orientar hacia los bocetos)", "Follow the camera (Look At sketches)": "Seguir la cámara (orientar hacia los bocetos)", "Font": "Fuente", + "From edges": "Aristas de origen", "Full Length": "Longitud total", "Grid": "Cuadrícula", "Height": "Altura", @@ -263,6 +265,7 @@ "Step": "Paso", "Steps": "Pasos", "Stitch the kept pieces": "Coser las piezas conservadas", + "Stitch to both bodies": "Coser a ambos cuerpos", "Study": "Estudio", "Style": "Estilo", "Suppressed": "Suprimido", @@ -284,6 +287,7 @@ "This child is shared. Position changes apply to every copy of its parent.": "Este elemento secundario es compartido. Los cambios de posición se aplican a todas las copias de su elemento principal.", "This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "Esta cara no permite una vinculación persistente. Elige otra cara o utiliza expresamente un plano fijo.", "To Offset": "Hasta desfase", + "To edges": "Aristas de destino", "Tolerance": "Tolerancia", "Too close": "Demasiado cerca", "Trimming tool (plane, face or curves)": "Herramienta de recorte (plano, cara o curvas)", diff --git a/assets/locales/fr.json b/assets/locales/fr.json index 6d303e34d..193312cf1 100644 --- a/assets/locales/fr.json +++ b/assets/locales/fr.json @@ -79,6 +79,7 @@ "Current orthographic view (1:1 mm)": "Vue orthographique actuelle (1:1 mm)", "Current perspective view": "Vue en perspective actuelle", "Curvature (G2)": "Courbure (G2)", + "Curvature change (G3)": "Variation de courbure (G3)", "Customize Toolbar": "Personnaliser la barre d'outils", "Delete all": "Tout supprimer", "Delete rule": "Supprimer la règle", @@ -122,6 +123,7 @@ "Follow camera (Look At sketches)": "Suivre la caméra (vue normale aux esquisses)", "Follow the camera (Look At sketches)": "Suivre la caméra (vue normale aux esquisses)", "Font": "Police", + "From edges": "Arêtes de départ", "Full Length": "Longueur totale", "Grid": "Grille", "Height": "Hauteur", @@ -265,6 +267,7 @@ "Step": "Étape", "Steps": "Étapes", "Stitch the kept pieces": "Coudre les parties conservées", + "Stitch to both bodies": "Coudre aux deux corps", "Study": "Étude", "Style": "Style", "Suppressed": "Désactivé", @@ -286,6 +289,7 @@ "This child is shared. Position changes apply to every copy of its parent.": "Cet enfant est partagé. Les changements de position s'appliquent à toutes les copies de son parent.", "This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "Cette face ne peut pas fournir de rattachement durable. Choisissez une autre face ou utilisez explicitement un plan fixe.", "To Offset": "Jusqu'au décalage", + "To edges": "Arêtes d'arrivée", "Tolerance": "Tolérance", "Too close": "Trop proches", "Trimming tool (plane, face or curves)": "Outil d'ajustement (plan, face ou courbes)", diff --git a/assets/locales/gl.json b/assets/locales/gl.json index c3a8e6a4d..2d5ec53fb 100644 --- a/assets/locales/gl.json +++ b/assets/locales/gl.json @@ -73,6 +73,7 @@ "Current orthographic view (1:1 mm)": "Vista ortográfica actual (1:1 mm)", "Current perspective view": "Vista en perspectiva actual", "Curvature (G2)": "Curvatura (G2)", + "Curvature change (G3)": "Cambio de curvatura (G3)", "Customize Toolbar": "Personalizar a barra de ferramentas", "Delete all": "Eliminar todo", "Delete rule": "Eliminar a regra", @@ -113,6 +114,7 @@ "Follow camera (Look At sketches)": "Seguir a cámara (Mirar cara aos bosquexos)", "Follow the camera (Look At sketches)": "Seguir a cámara (Mirar cara aos bosquexos)", "Font": "Tipo de letra", + "From edges": "Arestas de orixe", "Full Length": "Lonxitude completa", "Grid": "Grella", "Height": "Altura", @@ -250,6 +252,7 @@ "Step": "Paso", "Steps": "Pasos", "Stitch the kept pieces": "Coser as pezas mantidas", + "Stitch to both bodies": "Coser aos dous corpos", "Style": "Estilo", "Suppressed": "Suprimida", "Surface": "Superficie", @@ -270,6 +273,7 @@ "This child is shared. Position changes apply to every copy of its parent.": "Este fillo está compartido. Os cambios de posición aplícanse a todas as copias do seu pai.", "This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "Esta cara non pode ofrecer unha ancoraxe duradeira. Escolle outra cara ou usa expresamente un plano fixo.", "To Offset": "Ata o desprazamento", + "To edges": "Arestas de destino", "Tolerance": "Tolerancia", "Trimming tool (plane, face or curves)": "Ferramenta de recorte (plano, cara ou curvas)", "Turn off section analysis before exporting the view.": "Desactiva a análise de sección antes de exportar a vista.", diff --git a/assets/locales/it.json b/assets/locales/it.json index 2c5b2ff8b..b2e7bfd7e 100644 --- a/assets/locales/it.json +++ b/assets/locales/it.json @@ -79,6 +79,7 @@ "Current orthographic view (1:1 mm)": "Vista ortografica corrente (1:1 mm)", "Current perspective view": "Vista prospettica corrente", "Curvature (G2)": "Curvatura (G2)", + "Curvature change (G3)": "Variazione di curvatura (G3)", "Customize Toolbar": "Personalizza barra degli strumenti", "Delete all": "Elimina tutto", "Delete rule": "Elimina regola", @@ -121,6 +122,7 @@ "Follow camera (Look At sketches)": "Segui la camera (Vista normale agli schizzi)", "Follow the camera (Look At sketches)": "Segui la camera (Vista normale agli schizzi)", "Font": "Carattere", + "From edges": "Spigoli di partenza", "Full Length": "Lunghezza totale", "Grid": "Griglia", "Height": "Altezza", @@ -260,6 +262,7 @@ "Stand this part up?": "Raddrizzare questa parte?", "Step": "Passo", "Steps": "Passi", + "Stitch to both bodies": "Cuci a entrambi i corpi", "Study": "Studio", "Style": "Stile", "Suppressed": "Sospeso", @@ -279,6 +282,7 @@ "This child is shared. Position changes apply to every copy of its parent.": "Questo elemento figlio è condiviso. Le modifiche alla posizione si applicano a ogni copia del padre.", "This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "Questa faccia non consente un collegamento persistente. Scegli un'altra faccia o usa esplicitamente un piano fisso.", "To Offset": "Fino a una distanza", + "To edges": "Spigoli di arrivo", "Tolerance": "Tolleranza", "Too close": "Troppo vicini", "Turn off section analysis before exporting the view.": "Disattiva l'analisi in sezione prima di esportare la vista.", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index d2413d628..09499f014 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -31,6 +31,7 @@ "Arc length": "円弧の長さ", "Area": "表面積", "Attachment": "アタッチメント", + "BLEND SURFACE": "ブレンドサーフェス", "BOUNDARY SURFACE": "境界サーフェス", "BROWSER": "ブラウザ", "Bend Line Position": "曲げ線位置", @@ -79,6 +80,7 @@ "Current orthographic view (1:1 mm)": "現在の平行投影(実寸・mm)", "Current perspective view": "現在の透視投影", "Curvature (G2)": "曲率 (G2)", + "Curvature change (G3)": "曲率変化 (G3)", "Customize Toolbar": "ツールバーのカスタマイズ", "Delete all": "すべて削除", "Delete rule": "ルールを削除", @@ -100,6 +102,8 @@ "Edit Profile Sketch": "プロファイルスケッチを編集", "Enable rule": "ルールを有効化", "Enabled": "有効", + "End bulge": "終了側の膨らみ", + "End continuity": "終了側の連続性", "Explode": "分解", "Explode Text": "テキストを分解", "Export Animation…": "アニメーションをエクスポート…", @@ -122,6 +126,7 @@ "Follow camera (Look At sketches)": "カメラ追従(スケッチを正面視)", "Follow the camera (Look At sketches)": "カメラ追従(スケッチを正面視)", "Font": "フォント", + "From edges": "開始側エッジ", "Full Length": "全長", "Grid": "グリッド", "Height": "高さ", @@ -262,9 +267,12 @@ "Stand it up": "正立させる", "Stand it up: a quarter turn about X, as one Move feature you can undo.": "正立させる: 取り消し可能な1つの移動フィーチャーとして、X軸周りに90度回転します。", "Stand this part up?": "このパーツを正立させますか?", + "Start bulge": "開始側の膨らみ", + "Start continuity": "開始側の連続性", "Step": "ステップ", "Steps": "ステップ数", "Stitch the kept pieces": "残した部分をステッチ", + "Stitch to both bodies": "両方のボディにステッチ", "Study": "スタディ", "Style": "スタイル", "Suppressed": "抑制", @@ -286,6 +294,7 @@ "This child is shared. Position changes apply to every copy of its parent.": "この子要素は共有されています。位置の変更は親のすべてのコピーに適用されます。", "This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "この面は安定したアタッチメントを提供できません。別の面を選択するか、固定平面を明示的に使用してください。", "To Offset": "オフセットまで", + "To edges": "終了側エッジ", "Tolerance": "公差", "Too close": "近すぎる", "Trimming tool (plane, face or curves)": "トリムツール(平面、面、または曲線)", diff --git a/assets/locales/ko.json b/assets/locales/ko.json index d1bb0d9a6..221e56a14 100644 --- a/assets/locales/ko.json +++ b/assets/locales/ko.json @@ -26,6 +26,7 @@ "Current orthographic view (1:1 mm)": "현재 직교 투영 뷰 (1:1 mm)", "Current perspective view": "현재 원근 투영 뷰", "Curvature (G2)": "곡률 (G2)", + "Curvature change (G3)": "곡률 변화 (G3)", "Direction": "방향", "Do not export hidden edges": "숨겨진 모서리 내보내지 않기", "Don't ask again": "다시 묻지 않기", @@ -44,6 +45,7 @@ "Faces": "면", "Find in Browser": "브라우저에서 찾기", "Flat": "플랫", + "From edges": "시작 모서리", "Hidden edges": "숨겨진 모서리", "Holes": "구멍", "Holes (edges on them)": "구멍 (구멍의 모서리)", @@ -92,6 +94,7 @@ "Sketch points": "스케치 점", "Slot width": "슬롯 폭", "Stitch the kept pieces": "유지한 부분 재봉", + "Stitch to both bodies": "두 바디에 재봉", "Study": "연구", "Surface": "곡면", "TRIM": "트림", @@ -100,6 +103,7 @@ "Thickness Outside": "바깥쪽 두께", "Thin": "얇은 벽", "Thin Extrude": "얇은 벽 돌출", + "To edges": "끝 모서리", "Trimming tool (plane, face or curves)": "트림 도구(평면, 면 또는 곡선)", "Turn off section analysis before exporting the view.": "뷰를 내보내기 전에 단면 분석을 끄세요.", "Type": "유형", diff --git a/assets/locales/pt-BR.json b/assets/locales/pt-BR.json index 0bc5944f9..eef1e243b 100644 --- a/assets/locales/pt-BR.json +++ b/assets/locales/pt-BR.json @@ -73,6 +73,7 @@ "Current orthographic view (1:1 mm)": "Vista ortográfica atual (1:1 mm)", "Current perspective view": "Vista em perspectiva atual", "Curvature (G2)": "Curvatura (G2)", + "Curvature change (G3)": "Variação de curvatura (G3)", "Customize Toolbar": "Personalizar barra de ferramentas", "Delete all": "Excluir tudo", "Delete rule": "Excluir regra", @@ -113,6 +114,7 @@ "Follow camera (Look At sketches)": "Seguir a câmera (Olhar para os esboços)", "Follow the camera (Look At sketches)": "Seguir a câmera (Olhar para os esboços)", "Font": "Fonte", + "From edges": "Arestas de origem", "Full Length": "Comprimento total", "Grid": "Grade", "Height": "Altura", @@ -250,6 +252,7 @@ "Step": "Passo", "Steps": "Passos", "Stitch the kept pieces": "Costurar as partes mantidas", + "Stitch to both bodies": "Costurar aos dois corpos", "Style": "Estilo", "Suppressed": "Suprimido", "Surface": "Superfície", @@ -270,6 +273,7 @@ "This child is shared. Position changes apply to every copy of its parent.": "Este filho é compartilhado. Mudanças de posição se aplicam a todas as cópias do pai.", "This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "Esta face não pode fornecer uma fixação duradoura. Escolha outra face ou use explicitamente um plano fixo.", "To Offset": "Deslocamento final", + "To edges": "Arestas de destino", "Tolerance": "Tolerância", "Trimming tool (plane, face or curves)": "Ferramenta de aparo (plano, face ou curvas)", "Turn off section analysis before exporting the view.": "Desative a análise de seção antes de exportar a vista.", diff --git a/assets/locales/ru.json b/assets/locales/ru.json index 894a42681..dcabf2861 100644 --- a/assets/locales/ru.json +++ b/assets/locales/ru.json @@ -67,6 +67,7 @@ "Create Issue — review draft": "Создать Issue — проверить черновик", "Cube": "Куб", "Curvature (G2)": "Кривизна (G2)", + "Curvature change (G3)": "Изменение кривизны (G3)", "Customize Toolbar": "Настроить панель инструментов", "Delete all": "Удалить все", "Delete rule": "Удалить правило", @@ -102,6 +103,7 @@ "Follow camera (Look At sketches)": "Следовать за камерой (эскизы «Взгляд на»)", "Follow the camera (Look At sketches)": "Следовать за камерой (эскизы «Взгляд на»)", "Font": "Шрифт", + "From edges": "Начальные рёбра", "Full Length": "Полная длина", "Grid": "Сетка", "Height": "Высота", @@ -223,6 +225,7 @@ "Step": "Шаг", "Steps": "Шаги", "Stitch the kept pieces": "Сшить оставленные части", + "Stitch to both bodies": "Сшить с обоими телами", "Study": "Исследование", "Style": "Стиль", "Suppressed": "Подавлено", @@ -241,6 +244,7 @@ "This child is shared. Position changes apply to every copy of its parent.": "Этот дочерний объект общий. Изменения положения применятся ко всем копиям родителя.", "This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "Эта грань не может обеспечить надёжную привязку. Выберите другую грань или явно используйте фиксированную плоскость.", "To Offset": "До смещения", + "To edges": "Конечные рёбра", "Tolerance": "Допуск", "Trimming tool (plane, face or curves)": "Инструмент обрезки (плоскость, грань или кривые)", "Type": "Тип", diff --git a/assets/locales/tr.json b/assets/locales/tr.json index c6d91825a..cb505510b 100644 --- a/assets/locales/tr.json +++ b/assets/locales/tr.json @@ -71,6 +71,7 @@ "Countersink angle": "Konik havşa açısı", "Create Issue — review draft": "Sorun oluştur — taslağı gözden geçirin", "Cube": "Küp", + "Curvature change (G3)": "Eğrilik değişimi (G3)", "Customize Toolbar": "Araç çubuğunu özelleştir", "Delete all": "Tümünü sil", "Delete rule": "Kuralı sil", @@ -107,6 +108,7 @@ "Follow camera (Look At sketches)": "Kamera takibi (eskizlerde Bak)", "Follow the camera (Look At sketches)": "Kamera takibi (eskizlerde Bak)", "Font": "Yazı tipi", + "From edges": "Başlangıç kenarları", "Full Length": "Tam uzunluk", "Grid": "Izgara", "Height": "Yükseklik", @@ -241,6 +243,7 @@ "Step": "Adım", "Steps": "Adımlar", "Stitch the kept pieces": "Korunan parçaları dik", + "Stitch to both bodies": "Her iki gövdeye dik", "Study": "Etüt", "Style": "Stil", "Suppressed": "Bastırılmış", @@ -260,6 +263,7 @@ "This child is shared. Position changes apply to every copy of its parent.": "Bu alt öğe paylaşılıyor. Konum değişiklikleri üst öğesinin tüm kopyalarına uygulanır.", "This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "Bu yüz kalıcı bir bağlama sağlayamaz. Başka bir yüz seçin veya açıkça sabit bir düzlem kullanın.", "To Offset": "Ofsete kadar", + "To edges": "Bitiş kenarları", "Tolerance": "Tolerans", "Trimming tool (plane, face or curves)": "Kırpma aracı (düzlem, yüz veya eğriler)", "Type": "Tür", diff --git a/assets/locales/uk.json b/assets/locales/uk.json index b7a102a5b..5957aee15 100644 --- a/assets/locales/uk.json +++ b/assets/locales/uk.json @@ -79,6 +79,7 @@ "Current orthographic view (1:1 mm)": "Поточний ортографічний вид (1:1 mm)", "Current perspective view": "Поточний перспективний вид", "Curvature (G2)": "Кривина (G2)", + "Curvature change (G3)": "Зміна кривини (G3)", "Customize Toolbar": "Налаштувати панель інструментів", "Delete all": "Видалити все", "Delete rule": "Видалити правило", @@ -122,6 +123,7 @@ "Follow camera (Look At sketches)": "Стежити за камерою (ескізи наведення)", "Follow the camera (Look At sketches)": "Стежити за камерою (ескізи наведення)", "Font": "Шрифт", + "From edges": "Початкові ребра", "Full Length": "Повна довжина", "Grid": "Сітка", "Height": "Висота", @@ -265,6 +267,7 @@ "Step": "Крок", "Steps": "Кроки", "Stitch the kept pieces": "Зшити залишені частини", + "Stitch to both bodies": "Зшити з обома тілами", "Study": "Дослідження", "Style": "Стиль", "Suppressed": "Придушено", @@ -286,6 +289,7 @@ "This child is shared. Position changes apply to every copy of its parent.": "Цей дочірній об'єкт спільний. Зміни положення застосовуються до кожної копії батьківського.", "This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "Ця грань не може забезпечити надійну прив'язку. Виберіть іншу грань або явно використайте фіксовану площину.", "To Offset": "До зсуву", + "To edges": "Кінцеві ребра", "Tolerance": "Допуск", "Too close": "Занадто близько", "Trimming tool (plane, face or curves)": "Інструмент обрізання (площина, грань або криві)", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index 822647cbc..cee0926dd 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -31,6 +31,7 @@ "Arc length": "弧长", "Area": "面积", "Attachment": "附着", + "BLEND SURFACE": "混合曲面", "BOUNDARY SURFACE": "边界曲面", "BROWSER": "浏览器", "Bend Line Position": "弯折线位置", @@ -79,6 +80,7 @@ "Current orthographic view (1:1 mm)": "当前正交视图(1:1毫米)", "Current perspective view": "当前透视视图", "Curvature (G2)": "曲率 (G2)", + "Curvature change (G3)": "曲率变化 (G3)", "Customize Toolbar": "自定义工具栏", "Delete all": "全部删除", "Delete rule": "删除规则", @@ -100,6 +102,8 @@ "Edit Profile Sketch": "编辑轮廓草图", "Enable rule": "启用规则", "Enabled": "已启用", + "End bulge": "终止鼓度", + "End continuity": "终止连续性", "Explode": "爆炸", "Explode Text": "分解文字", "Export Animation…": "导出动画…", @@ -122,6 +126,7 @@ "Follow camera (Look At sketches)": "跟随相机(注视草图)", "Follow the camera (Look At sketches)": "跟随相机(注视草图)", "Font": "字体", + "From edges": "起始边", "Full Length": "全长", "Grid": "网格", "Height": "高度", @@ -262,9 +267,12 @@ "Stand it up": "将其立起", "Stand it up: a quarter turn about X, as one Move feature you can undo.": "将其立起:绕 X 轴旋转四分之一周,作为一个可撤销的移动特征。", "Stand this part up?": "立起此零件?", + "Start bulge": "起始鼓度", + "Start continuity": "起始连续性", "Step": "步骤", "Steps": "步数", "Stitch the kept pieces": "缝合保留的部分", + "Stitch to both bodies": "缝合到两个实体", "Study": "研究", "Style": "样式", "Suppressed": "已抑制", @@ -286,6 +294,7 @@ "This child is shared. Position changes apply to every copy of its parent.": "此子项是共享的。位置更改会应用到其父项的每个副本。", "This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "此面无法提供持久附着。请选择其他面或显式使用固定平面。", "To Offset": "偏移", + "To edges": "终止边", "Tolerance": "公差", "Too close": "过近", "Trimming tool (plane, face or curves)": "修剪工具(平面、面或曲线)", diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 6e4906c86..a6025acd1 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -1455,6 +1455,11 @@ pub enum FeatureKind { /// Points the blend leaves towards, when the faces at the picks do not say: [from, to]. #[serde(default, skip_serializing_if = "Option::is_none")] align: Option<[Position; 2]>, + /// Where each chain's stations start, when two closed chains should not pair the way + /// that keeps the blend from twisting: a point on each chain, [from, to]. An open chain + /// starts at the end nearer its point. + #[serde(default, skip_serializing_if = "Option::is_none")] + seam: Option<[Position; 2]>, /// Sew the blend onto its two bodies where the boundaries meet. #[serde(default, skip_serializing_if = "std::ops::Not::not")] stitch: bool, diff --git a/crates/doc/src/eval_surface.rs b/crates/doc/src/eval_surface.rs index b9d53cfc8..ef141b29d 100644 --- a/crates/doc/src/eval_surface.rs +++ b/crates/doc/src/eval_surface.rs @@ -141,7 +141,7 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, } Ok(()) } - FeatureKind::SurfaceBlend { from, to, continuity, bulge, align, stitch } => { + FeatureKind::SurfaceBlend { from, to, continuity, bulge, align, seam, stitch } => { let a = st.body(&from.body).ok_or_else(|| DocError::Unknown(format!("body `{}`", from.body)))?.body.clone(); let b = st.body(&to.body).ok_or_else(|| DocError::Unknown(format!("body `{}`", to.body)))?.body.clone(); if from.edges.is_empty() || to.edges.is_empty() { @@ -155,6 +155,7 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, *continuity, *bulge, align.map(|[p, q]| [p.0, q.0]), + seam.map(|[p, q]| [p.0, q.0]), BLEND_STATIONS, *stitch, )?; diff --git a/crates/doc/src/feature_walk_tests/fixtures.rs b/crates/doc/src/feature_walk_tests/fixtures.rs index 28c2da3e6..1e262b68c 100644 --- a/crates/doc/src/feature_walk_tests/fixtures.rs +++ b/crates/doc/src/feature_walk_tests/fixtures.rs @@ -159,10 +159,16 @@ pub(super) fn fixtures() -> Vec<(&'static str, Value)> { "orientation": "parallel", "twist": "surface_sweep.twist", "scale": "surface_sweep.scale"}), ), ("surface_loft", json!({"type": "surface_loft", "sections": []})), - ("surface_blend", json!({"type": "surface_blend", "from": {"body": "B", "edges": [o]}, "to": {"body": "C", "edges": [o]}, "align": [o, o]})), + ( + "surface_blend", + json!({"type": "surface_blend", "from": {"body": "B", "edges": [o]}, "to": {"body": "C", "edges": [o]}, "align": [o, o], "seam": [o, o]}), + ), ("surface_offset", json!({"type": "surface_offset", "faces": [o], "distance": "soff.distance", "tolerance": "soff.tolerance"})), // The Class-A surface family (surface.blend/boundary/match/fair). - ("surface_blend", json!({"type": "surface_blend", "from": {"body": "B", "edges": [o]}, "to": {"body": "C", "edges": [o]}, "align": [o, o]})), + ( + "surface_blend", + json!({"type": "surface_blend", "from": {"body": "B", "edges": [o]}, "to": {"body": "C", "edges": [o]}, "align": [o, o], "seam": [o, o]}), + ), ("surface_boundary", json!({"type": "surface_boundary", "sketch": 1, "curves": ["l1", "l2"]})), ( "surface_network", diff --git a/crates/doc/src/feature_walk_tests/golden_geometry.txt b/crates/doc/src/feature_walk_tests/golden_geometry.txt index af2ef727d..9d223eb92 100644 --- a/crates/doc/src/feature_walk_tests/golden_geometry.txt +++ b/crates/doc/src/feature_walk_tests/golden_geometry.txt @@ -150,12 +150,12 @@ surface_sweep surface_sweep_options surface_loft surface_blend - moves: align[0][0], align[0][1], align[0][2], align[1][0], align[1][1], align[1][2], from.edges[0][0], from.edges[0][1], from.edges[0][2], to.edges[0][0], to.edges[0][1], to.edges[0][2] + moves: align[0][0], align[0][1], align[0][2], align[1][0], align[1][1], align[1][2], from.edges[0][0], from.edges[0][1], from.edges[0][2], seam[0][0], seam[0][1], seam[0][2], seam[1][0], seam[1][1], seam[1][2], to.edges[0][0], to.edges[0][1], to.edges[0][2] surface_offset moves: faces[0][0], faces[0][1], faces[0][2] face points: [0, 0, 0] surface_blend - moves: align[0][0], align[0][1], align[0][2], align[1][0], align[1][1], align[1][2], from.edges[0][0], from.edges[0][1], from.edges[0][2], to.edges[0][0], to.edges[0][1], to.edges[0][2] + moves: align[0][0], align[0][1], align[0][2], align[1][0], align[1][1], align[1][2], from.edges[0][0], from.edges[0][1], from.edges[0][2], seam[0][0], seam[0][1], seam[0][2], seam[1][0], seam[1][1], seam[1][2], to.edges[0][0], to.edges[0][1], to.edges[0][2] surface_boundary surface_network moves: u[1].edges[0][0], u[1].edges[0][1], u[1].edges[0][2], v[1].point[0], v[1].point[1], v[1].point[2] diff --git a/crates/doc/src/format/pending/surface-blend-seam.rs b/crates/doc/src/format/pending/surface-blend-seam.rs new file mode 100644 index 000000000..044eb4f0c --- /dev/null +++ b/crates/doc/src/format/pending/surface-blend-seam.rs @@ -0,0 +1,4 @@ +//! A `SurfaceBlend` (Blend Surface, #764) may save `seam`: a point on each of its two edge chains +//! where their stations start. Older designs need no transformation: a blend without `seam` pairs +//! its chains by itself; the last release asks for an update instead of meeting a seam it can't +//! read. diff --git a/crates/engine/src/cmd/surface.rs b/crates/engine/src/cmd/surface.rs index e12b6aea6..39a1d6806 100644 --- a/crates/engine/src/cmd/surface.rs +++ b/crates/engine/src/cmd/surface.rs @@ -63,7 +63,7 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("surface.blend", "Blend Surface", blend) .at("SURFACE", "CREATE") .icon("surface_blend") - .params("from, to: {body, edges: [[x,y,z]]} (points on the edges of one chain of each body: two picks on the same edge is that one edge, more chain up); continuity?: [g0|g1|g2|g3, g0|g1|g2|g3] (each end, default g1: how much of the surface at the picked edges the blend repeats — the tangent plane, the curvature, or how that curvature changes); bulge?: [number, number] (default 0: how full each end leaves, -0.9 flattest to 3 fullest); align?: [[x,y,z], [x,y,z]] (a point each end leaves towards, when the faces at the picks do not say); stitch?: bool (sew the blend onto its two bodies where the boundaries meet, replacing them); name?, body_name?"), + .params("from, to: {body, edges: [[x,y,z]]} (points on the edges of one chain of each body: two picks on the same edge is that one edge, more chain up); continuity?: [g0|g1|g2|g3, g0|g1|g2|g3] (each end, default g1: how much of the surface at the picked edges the blend repeats — the tangent plane, the curvature, or how that curvature changes); bulge?: [number, number] (default 0: how full each end leaves, -0.9 flattest to 3 fullest); align?: [[x,y,z], [x,y,z]] (a point each end leaves towards, when the faces at the picks do not say); seam?: [[x,y,z], [x,y,z]] (a point on each chain its stations start from: two closed chains otherwise pair the way that keeps the blend from twisting; an open chain starts at the end nearer its point; a closed chain blends only to a closed chain); stitch?: bool (sew the blend onto its two bodies where the boundaries meet, replacing them); name?, body_name?"), CommandSpec::new("surface.untrim", "Untrim", untrim) .at("SURFACE", "MODIFY") .icon("surface_untrim") @@ -237,18 +237,18 @@ fn blend(s: &mut Session, p: &Value) -> Result { [one(list.first())?, one(list.get(1))?] } }; - let align = match p.get("align") { - None | Some(Value::Null) => None, - Some(v) => { - let list = v.as_array().filter(|a| a.len() == 2).ok_or_else(|| bad(cmd, "`align` must be two points, one per end"))?; - let point = |x: Option<&Value>| -> Result { - x.and_then(vec3).ok_or_else(|| bad(cmd, "each `align` entry must be a point [x,y,z]")) - }; - Some([Position(point(list.first())?), Position(point(list.get(1))?)]) - } - }; + let align = point_pair(p, cmd, "align", "one per end")?; + let seam = point_pair(p, cmd, "seam", "one on each chain")?; let stitch = bool_(p, "stitch").unwrap_or(false); - add_feature(s, p, FeatureKind::SurfaceBlend { from, to, continuity, bulge, align, stitch }) + add_feature(s, p, FeatureKind::SurfaceBlend { from, to, continuity, bulge, align, seam, stitch }) +} + +/// An optional pair of points `key` (`null` as none): `which` says what each one is. +fn point_pair(p: &Value, cmd: &str, key: &str, which: &str) -> Result> { + let Some(v) = p.get(key).filter(|v| !v.is_null()) else { return Ok(None) }; + let list = v.as_array().filter(|a| a.len() == 2).ok_or_else(|| bad(cmd, format!("`{key}` must be two points, {which}")))?; + let point = |x: Option<&Value>| x.and_then(vec3).map(Position).ok_or_else(|| bad(cmd, format!("each `{key}` entry must be a point [x,y,z]"))); + Ok(Some([point(list.first())?, point(list.get(1))?])) } fn surface_extrude(s: &mut Session, p: &Value) -> Result { @@ -1807,6 +1807,57 @@ mod tests { ); } + /// `surface.blend` between two tube rims: each rim runs along both halves of its tube's wall + /// (two faces), the rims are closed, and the blend is the wall between them, straight up the + /// axis. Picked `seam` points turn it, are saved with the design, and a closed rim does not + /// blend to an open edge. + #[test] + fn surface_blend_bridges_two_tube_rims() { + let mut s = Session::default(); + run(&mut s, "solid.cylinder", json!({"radius": 10, "height": 30, "body_name": "Low"})); + run(&mut s, "surface.unstitch", json!({"body": "Low", "faces": [[0, 0, 30]]})); + run(&mut s, "solid.cylinder", json!({"radius": 10, "height": 30, "base": [0, 0, 40], "body_name": "High"})); + run(&mut s, "surface.unstitch", json!({"body": "High", "faces": [[0, 0, 40]]})); + let rim = |z: f64| -> Value { + json!((0..8).map(|k| f64::from(k) * 0.785 + 0.1).map(|a| json!([10.0 * a.cos(), 10.0 * a.sin(), z])).collect::>()) + }; + // Unstitching keeps the wall under the body's own name. + let blend = json!({"from": {"body": "Low", "edges": rim(30.0)}, "to": {"body": "High", "edges": rim(40.0)}, "continuity": ["g1", "g1"], "body_name": "Neck"}); + run(&mut s, "surface.blend", blend.clone()); + // The wall between: radius 10 and straight up, so 2π·10·10 of area. + let want = 2.0 * std::f64::consts::PI * 100.0; + assert!((area(&s, "Neck") - want).abs() < want * 1e-3, "{} vs {want}", area(&s, "Neck")); + let turn = |s: &Session, name: &str| { + let grid = solidcraft_kernel::sample_grid(&s.world_state().body(name).unwrap().body, 17, 5).unwrap(); + grid.iter() + .map(|row| { + let (a, b) = (row[0], row[row.len() - 1]); + (a.y.atan2(a.x) - b.y.atan2(b.x)).rem_euclid(std::f64::consts::TAU).to_degrees() + }) + .map(|d| d.min(360.0 - d)) + .fold(0.0, f64::max) + }; + assert!(turn(&s, "Neck") < 0.1, "straight up the axis: {}°", turn(&s, "Neck")); + // Seams a quarter apart: the blend turns a quarter round, and reads back the same. + let mut turned = blend.clone(); + turned["seam"] = json!([[10, 0, 30], [0, 10, 40]]); + turned["body_name"] = json!("Twist"); + run(&mut s, "surface.blend", turned); + assert!((turn(&s, "Twist") - 90.0).abs() < 0.1, "{}°", turn(&s, "Twist")); + assert!(s.doc.to_json().contains("\"seam\""), "the seam is saved"); + let cold = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); + assert!((turn(&cold, "Twist") - 90.0).abs() < 0.1, "read back: {}°", turn(&cold, "Twist")); + // A closed rim does not blend to an open edge; a seam that is not two points is refused. + run(&mut s, "solid.box", json!({"length": 40, "width": 10, "height": 10, "corner": [-20, 30, 30], "body_name": "Block"})); + let open = s.execute("surface.blend", &json!({"from": {"body": "Low", "edges": rim(30.0)}, "to": {"body": "Block", "edges": [[0, 30, 40]]}})); + assert!(open.as_ref().is_err_and(|e| e.to_string().contains("closed chain")), "{open:?}"); + for seam in [json!([[0, 0, 0]]), json!("x"), json!([[0, 0, 0], "y"])] { + let mut bad = blend.clone(); + bad["seam"] = seam.clone(); + assert!(s.execute("surface.blend", &bad).is_err(), "{seam}"); + } + } + /// A tube whose top face is taken off (`surface.unstitch`), and points round its rim. fn open_tube() -> (Session, Value) { let mut s = Session::default(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 9d99288cd..d7aafdc3d 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -803,6 +803,7 @@ fn hostile_params_never_panic() { "kind", "prefix", "orientation", + "seam", "twist", "scale", "continuity", diff --git a/crates/kernel/src/bridge.rs b/crates/kernel/src/bridge.rs index 23db38744..d13685cfb 100644 --- a/crates/kernel/src/bridge.rs +++ b/crates/kernel/src/bridge.rs @@ -137,49 +137,161 @@ pub fn chain_closes(chain: &[mt::Edge]) -> bool { first.front().id() == last.back().id() } -/// The stations of a chain of edges, `count` of them evenly along its length, and the length -/// itself. A chain that closes is sampled with its last station back on its first. -fn chain_samples(edges: &[mt::Edge], count: usize) -> Result<(Vec, f64)> { - /// Samples per edge used for the length table. - const PER_EDGE: usize = 64; - let mut poly: Vec = Vec::with_capacity(edges.len() * (PER_EDGE + 1)); - for e in edges { - let c = e.curve(); - let (t0, t1) = c.range_tuple(); - if !(t1 > t0) || ![t0, t1].into_iter().all(f64::is_finite) { - return Err(KernelError::Invalid("an edge has no parameter range".into())); +/// A point of a [`ChainLine`]'s polyline: where it is, its arclength along the chain, the chain +/// edge (its index) the segment from it runs along, and that edge's curve parameter there. +#[derive(Clone, Copy)] +struct Sample { + p: Vec3, + s: f64, + edge: usize, + t: f64, +} + +/// A chain of edges measured by arclength through a fine polyline on it, so that a station is read +/// on the edge's own curve, not on a chord. A chain that closes ends back on its first point. +struct ChainLine { + curves: Vec, + samples: Vec, + closed: bool, +} + +impl ChainLine { + fn of(edges: &[mt::Edge]) -> Result { + /// Samples per edge used for the length table. + const PER_EDGE: usize = 64; + let mut samples: Vec = Vec::with_capacity(edges.len() * (PER_EDGE + 1) + 1); + let mut curves = Vec::with_capacity(edges.len()); + let push = |samples: &mut Vec, p: Vec3, edge: usize, t: f64| { + let s = samples.last().map_or(0.0, |last| last.s + last.p.dist(p)); + samples.push(Sample { p, s, edge, t }); + }; + for (i, e) in edges.iter().enumerate() { + let c = e.curve(); + let (t0, t1) = c.range_tuple(); + if !(t1 > t0) || ![t0, t1].into_iter().all(f64::is_finite) { + return Err(KernelError::Invalid("an edge has no parameter range".into())); + } + for k in 0..=PER_EDGE { + // The segment that starts at this point: along this edge, or the zero-length join + // to the next edge. + let t = t0 + (t1 - t0) * k as f64 / PER_EDGE as f64; + push(&mut samples, from_p3(c.subs(t)), i, t); + } + curves.push(c); } - for k in 0..=PER_EDGE { - poly.push(from_p3(c.subs(t0 + (t1 - t0) * k as f64 / PER_EDGE as f64))); + let closed = chain_closes(edges); + if closed && let Some(first) = samples.first().copied() { + push(&mut samples, first.p, edges.len().saturating_sub(1), first.t); } + let line = ChainLine { curves, samples, closed }; + let total = line.length(); + if !(total > 1e-9) || !total.is_finite() { + return Err(KernelError::Invalid("the edge chain has no length".into())); + } + Ok(line) } - if chain_closes(edges) - && let Some(first) = poly.first().copied() - { - poly.push(first); + + fn length(&self) -> f64 { + self.samples.last().map_or(0.0, |x| x.s) } - let mut cum = Vec::with_capacity(poly.len()); - cum.push(0.0); - for w in poly.windows(2) { - let (Some(a), Some(b)) = (w.first(), w.get(1)) else { continue }; - let Some(last) = cum.last().copied() else { break }; - cum.push(last + a.dist(*b)); + + /// The point at arclength `s` (wrapped round a closed chain, clamped on an open one), on its + /// edge's own curve, and the chain edge it is on. + fn at(&self, s: f64) -> Result<(Vec3, usize)> { + let total = self.length(); + let s = if self.closed { s.rem_euclid(total) } else { s.clamp(0.0, total) }; + let hi = self.samples.partition_point(|x| x.s < s).clamp(1, self.samples.len().saturating_sub(1)); + let fail = || KernelError::Failed("bridge: sample".into()); + let (lo, hi) = (self.samples.get(hi - 1).ok_or_else(fail)?, self.samples.get(hi).ok_or_else(fail)?); + let curve = self.curves.get(lo.edge).ok_or_else(fail)?; + let span = hi.s - lo.s; + if !(span > 1e-12) { + // The zero-length join between two edges: the end of the edge it belongs to. + return Ok((from_p3(curve.subs(lo.t)), lo.edge)); + } + let f = ((s - lo.s) / span).clamp(0.0, 1.0); + Ok((from_p3(curve.subs(lo.t + (hi.t - lo.t) * f)), lo.edge)) } - let total = cum.last().copied().unwrap_or(0.0); - if !(total > 1e-9) || !total.is_finite() { - return Err(KernelError::Invalid("the edge chain has no length".into())); + + /// `count` stations evenly along the chain, from arclength `start` (a closed chain's seam; an + /// open chain always runs end to end), forwards or backwards. A closed chain's last station is + /// back on its first. + fn stations(&self, count: usize, start: f64, backwards: bool) -> Result> { + let total = self.length(); + let start = if self.closed { + start + } else if backwards { + total + } else { + 0.0 + }; + let sign = if backwards { -1.0 } else { 1.0 }; + (0..count).map(|i| self.at(start + sign * total * i as f64 / (count.max(2) - 1) as f64)).collect() } - let mut out = Vec::with_capacity(count); - for i in 0..count { - let s = total * i as f64 / (count.max(2) - 1) as f64; - let hi = cum.partition_point(|x| *x < s).clamp(1, poly.len().saturating_sub(1)); - let (Some(a), Some(b)) = (poly.get(hi - 1), poly.get(hi)) else { return Err(KernelError::Failed("bridge: sample".into())) }; - let (Some(&lo), Some(&hi_s)) = (cum.get(hi - 1), cum.get(hi)) else { return Err(KernelError::Failed("bridge: sample".into())) }; - let span = hi_s - lo; - let t = if span > 1e-12 { (s - lo) / span } else { 0.0 }; - out.push(*a + (*b - *a) * t); + + /// The chain edges `p` (a station on chain edge `edge`) lies on: that edge, and the edge before + /// or after it when `p` is on the vertex they share. + fn edges_at(&self, p: Vec3, edge: usize) -> [Option; 3] { + let count = self.curves.len(); + let tol = self.length() * 1e-9 + 1e-12; + let Some(curve) = self.curves.get(edge) else { return [Some(edge), None, None] }; + let (t0, t1) = curve.range_tuple(); + let at = |t: f64| from_p3(curve.subs(t)).dist(p) <= tol; + let before = at(t0).then(|| edge.checked_sub(1).or(self.closed.then(|| count.saturating_sub(1)))).flatten(); + let after = at(t1).then(|| Some(edge + 1).filter(|e| *e < count).or(self.closed.then_some(0))).flatten(); + [Some(edge), before, after] + } + + /// Where stations start from `seam` (a point on the chain), and whether they run backwards: a + /// closed chain starts at it, an open one runs from the end it is nearer. + fn start_at_seam(&self, seam: Vec3) -> (f64, bool) { + let s = self.nearest(seam); + if self.closed { (s, false) } else { (0.0, s > self.length() / 2.0) } + } + + /// The arclength of the chain's point nearest `p`, and how far `p` is from the chain: the + /// nearest point of the fine polyline, then refined on that edge's own curve. + fn nearest_with_distance(&self, p: Vec3) -> (f64, f64) { + let mut best = (f64::INFINITY, 0.0, 0usize, 0.0); + for w in self.samples.windows(2) { + let (Some(a), Some(b)) = (w.first(), w.get(1)) else { continue }; + let len = a.p.dist(b.p); + let f = if len > 1e-12 { ((p - a.p).dot(b.p - a.p) / (len * len)).clamp(0.0, 1.0) } else { 0.0 }; + let d = p.dist(a.p + (b.p - a.p) * f); + if d < best.0 { + best = (d, a.s + len * f, a.edge, a.t + (b.t - a.t) * f); + } + } + let (chord, s, edge, hint) = best; + let on_curve = self.curves.get(edge).and_then(|c| { + let (t0, t1) = c.range_tuple(); + let t = c.search_nearest_parameter(p3(p), Some(hint), 100)?; + (t0..=t1).contains(&t).then(|| from_p3(c.subs(t)).dist(p)) + }); + (s, on_curve.map_or(chord, |d| d.min(chord))) + } + + /// The arclength of the chain's point nearest `p`. + fn nearest(&self, p: Vec3) -> f64 { + self.nearest_with_distance(p).0 + } + + /// The middle of the chain: a closed chain's centroid (what it surrounds), an open chain's + /// point halfway along. + fn middle(&self) -> Result { + if !self.closed { + return Ok(self.at(self.length() / 2.0)?.0); + } + let mut sum = Vec3::ZERO; + let mut weight = 0.0; + for w in self.samples.windows(2) { + let (Some(a), Some(b)) = (w.first(), w.get(1)) else { continue }; + let len = a.p.dist(b.p); + sum += (a.p + b.p) * (0.5 * len); + weight += len; + } + Ok(sum * (1.0 / weight.max(1e-300))) } - Ok((out, total)) } /// The support surface's frames along `edges` (a chain of its own edges), for a bridge that @@ -188,19 +300,61 @@ pub fn frames(face: &mt::Face, edges: &[mt::Edge], leave: Vec3, count: usize) -> if !(2..=4097).contains(&count) { return Err(KernelError::Invalid("a bridge needs 2 to 4097 stations".into())); } + let line = ChainLine::of(edges)?; + let stations = line.stations(count, 0.0, false)?; + frames_on(&vec![face.clone(); edges.len()], &stations, &line, leave) +} + +/// The frames at `stations` (points on `line`, each with the index of the chain edge it is on), +/// each read on the support face of its own edge (`faces`, one per chain edge): a chain may run +/// along the boundaries of several faces, a tube's rim along the halves of its wall. A station on +/// the vertex where two of those faces meet sits at a corner of one face's parameters, where the +/// shape may not be readable along the leave direction; it is then read on the other face, which +/// holds the same point. +fn frames_on(faces: &[mt::Face], stations: &[(Vec3, usize)], line: &ChainLine, leave: Vec3) -> Result> { let leave = leave.normalized().filter(|l| l.is_finite()).ok_or_else(|| KernelError::Invalid("the leave direction must be a finite vector".into()))?; - let (pts, length) = chain_samples(edges, count)?; - let support = Support::of(face, length)?; - let mut walk = Walk::new(length); let along = |n: Vec3| -> Result { (leave - n * leave.dot(n)) .normalized() .ok_or_else(|| KernelError::Invalid("the leave direction is normal to the support surface: it has no tangent plane there".to_string())) }; - let mut out = Vec::with_capacity(pts.len()); - for p in &pts { - out.push(support.station(*p, &along, &mut walk, true)?.0); + let length = line.length(); + // One support per distinct face, each with its own walk (a parameter hint means nothing on + // another surface). + let mut supports: Vec<(mt::FaceID, Support, Walk)> = Vec::new(); + let mut out = Vec::with_capacity(stations.len()); + 'stations: for (p, edge) in stations { + let mut tried: Vec = Vec::with_capacity(2); + let mut refusal: Option = None; + for e in line.edges_at(*p, *edge).into_iter().flatten() { + let Some(face) = faces.get(e) else { continue }; + let id = face.id(); + if tried.contains(&id) { + continue; + } + tried.push(id); + let k = match supports.iter().position(|(f, _, _)| *f == id) { + Some(k) => k, + None => { + supports.push((id, Support::of(face, length)?, Walk::new(length))); + supports.len() - 1 + } + }; + let Some((_, support, walk)) = supports.get_mut(k) else { continue }; + match support.station(*p, &along, walk, true) { + Ok((frame, _)) => { + out.push(frame); + continue 'stations; + } + // The station's own face's refusal is the one reported when the other cannot read + // it either. + Err(err) => { + refusal.get_or_insert(err); + } + } + } + return Err(refusal.unwrap_or_else(|| KernelError::Failed("bridge: a station's edge has no support face".into()))); } Ok(out) } @@ -595,72 +749,133 @@ pub fn sample_grid(body: &Body, along: usize, across: usize) -> Result Result { +fn boundary_gap(made: &Body, line: &ChainLine, at_end: bool) -> Result { let face = made.solid.face_iter().next().ok_or_else(|| KernelError::Failed("bridge: no face".into()))?; let surf = face.surface(); let (Some((u0, u1)), Some((v0, v1))) = surf.try_range_tuple() else { return Err(KernelError::Failed("bridge: the surface is unbounded".into())); }; let v = if at_end { v1 } else { v0 }; - let (poly, _) = chain_samples(chain, 257)?; let mut worst: f64 = 0.0; for i in 0..=256 { let u = u0 + (u1 - u0) * i as f64 / 256.0; - let p = from_p3(surf.subs(u, v)); - let mut best = f64::INFINITY; - for w in poly.windows(2) { - let (Some(a), Some(b)) = (w.first(), w.get(1)) else { continue }; - let t = if b.dist(*a) > 1e-12 { ((p - *a).dot(*b - *a) / b.dist(*a).powi(2)).clamp(0.0, 1.0) } else { 0.0 }; - best = best.min(p.dist(*a + (*b - *a) * t)); - } - worst = worst.max(best); + worst = worst.max(line.nearest_with_distance(from_p3(surf.subs(u, v))).1); } Ok(worst) } -/// The midpoint of a chain of edges. -fn chain_mid(edges: &[mt::Edge]) -> Result { - let (pts, _) = chain_samples(edges, 3)?; - pts.get(1).copied().ok_or_else(|| KernelError::Failed("bridge: no chain".into())) +/// Which face of `body` the blend continues from along each edge of a chain (one per edge, in +/// chain order): of the faces each edge bounds, the one whose tangent plane holds as much of +/// `leave` as possible there. A chain may run along several faces (a tube's rim along the halves +/// of its wall). +fn support_faces(body: &Body, chain: &[mt::Edge], leave: Vec3) -> Result> { + let mut out = Vec::with_capacity(chain.len()); + for edge in chain { + let curve = edge.curve(); + let (t0, t1) = curve.range_tuple(); + let mid = from_p3(curve.subs(0.5 * (t0 + t1))); + let mut best: Option<(f64, mt::Face)> = None; + for face in body.solid.face_iter() { + if !face.edge_iter().any(|f| f.id() == edge.id()) { + continue; + } + let Some((q, n, _)) = crate::curveblend::project(face, mid, None) else { continue }; + if q.dist(mid) > body.size() * 1e-6 + 1e-9 { + continue; + } + let score = (leave - n * leave.dot(n)).len(); + if best.as_ref().is_none_or(|(b, _)| score > *b) { + best = Some((score, face.clone())); + } + } + let (score, face) = best.ok_or_else(|| KernelError::Invalid("no face of the body holds a picked edge".into()))?; + if score < 0.2 { + return Err(KernelError::Invalid( + "the direction towards the other boundary lies in no face at the picked edges: give `align` points to leave by".into(), + )); + } + out.push(face); + } + Ok(out) } -/// Which face of `body` the blend should continue from a chain, and the direction it leaves in: -/// the face whose tangent plane holds as much of `leave` as possible. -fn support_face(body: &Body, chain: &[mt::Edge], leave: Vec3) -> Result<(mt::Face, Vec3)> { - let mut best: Option<(f64, mt::Face)> = None; - for face in body.solid.face_iter() { - if !chain.iter().all(|e| face.edge_iter().any(|f| f.id() == e.id())) { - continue; - } - let mid = chain_mid(chain)?; - let surf = face.surface(); - let Some((u, v)) = surf.search_nearest_parameter(p3(mid), None, 100) else { continue }; - if from_p3(surf.subs(u, v)).dist(mid) > body.size() * 1e-6 + 1e-9 { - continue; - } - let normal = surf.normal(u, v); - let n = Vec3::new(normal.x, normal.y, normal.z).normalized().unwrap_or(Vec3::ZERO); - let in_plane = leave - n * leave.dot(n); - let score = in_plane.len(); - if best.as_ref().is_none_or(|(b, _)| score > *b) { - best = Some((score, face.clone())); +/// Where the second chain's stations start, and which way they run, so that they pair with the +/// first chain's `a` station by station. An open chain runs from the end `seam` (a point on it) +/// is nearer, or else the way that puts its ends nearer their partners. A closed chain runs round +/// the same way as the first (by their area vectors; the nearer pairing when they stand almost +/// at right angles), from `seam` when given, or else from the start that puts each station +/// closest to its partner: two rims whose seams sit apart would otherwise give a twisted blend. +fn pair_with(a: &[(Vec3, usize)], line: &ChainLine, seam: Option) -> Result> { + let count = a.len(); + let cost = |start: f64, backwards: bool| -> Result { + Ok(line.stations(count, start, backwards)?.iter().zip(a).map(|((q, _), (p, _))| p.dist(*q)).sum()) + }; + // The least-cost start and way round among `starts` × `directions`. + let best_of = |starts: &[f64], directions: &[bool]| -> Result<(f64, bool)> { + let mut best = (0.0, false, f64::INFINITY); + for &start in starts { + for &backwards in directions { + let c = cost(start, backwards)?; + if c < best.2 { + best = (start, backwards, c); + } + } } + Ok((best.0, best.1)) + }; + if !line.closed { + let backwards = match seam { + Some(p) => line.start_at_seam(p).1, + None => cost(0.0, true)? < cost(0.0, false)?, + }; + return line.stations(count, 0.0, backwards); } - let (score, face) = best.ok_or_else(|| KernelError::Invalid("no face of the body holds the picked edges".into()))?; - if score < 0.2 { - return Err(KernelError::Invalid( - "the direction towards the other boundary lies in no face at the picked edges: give `align` points to leave by".into(), - )); + let total = line.length(); + let spacing = total / (count.max(2) - 1) as f64; + let coarse: Vec = (0..4 * (count.max(2) - 1)).map(|k| k as f64 * spacing / 4.0).collect(); + // The way round: the same sense as the first loop, unless the two loops stand almost at right + // angles (then the area vectors cannot say, and the nearer pairing does, with its start). + let ring = + |pts: &[(Vec3, usize)]| crate::plane_fit::loop_area(&pts.iter().take(pts.len().saturating_sub(1)).map(|(p, _)| *p).collect::>()); + let (area_a, area_b) = (ring(a), ring(&line.stations(count, 0.0, false)?)); + let agree = area_a.dot(area_b); + let (backwards, nearest_start) = if agree.abs() > 0.2 * area_a.len() * area_b.len() { + (agree < 0.0, None) + } else { + let (start, backwards) = best_of(&coarse, &[false, true])?; + (backwards, Some(start)) + }; + if let Some(p) = seam { + return line.stations(count, line.start_at_seam(p).0, backwards); } - Ok((face, leave)) + // The best of starts four to a station spacing, narrowed down to a thousandth of a spacing + // (the cost is smooth near its least). + let mut start = match nearest_start { + Some(start) => start, + None => best_of(&coarse, &[backwards])?.0, + }; + let (mut lo, mut hi) = (start - spacing / 4.0, start + spacing / 4.0); + while hi - lo > spacing * 1e-3 { + let (m1, m2) = (lo + (hi - lo) / 3.0, hi - (hi - lo) / 3.0); + if cost(m1, backwards)? <= cost(m2, backwards)? { + hi = m2; + } else { + lo = m1; + } + start = 0.5 * (lo + hi); + } + line.stations(count, start, backwards) } /// A blend surface between two picked edge chains of two bodies: the surfaces the blend leaves -/// and arrives at are the faces the chains bound (the best-facing one at each side), and each -/// side repeats that surface up to its requested continuity. `align` overrides the direction -/// each side leaves in (points in world space); `crown` how full each side is; `stitch` sews the -/// blend to its two bodies where their boundaries meet. The reply's `gap`, if any, is how far the -/// blend's own boundary lay from the chains it was built on. +/// and arrives at are the faces the chains bound (along each edge, the best-facing one), and each +/// side repeats that surface up to its requested continuity. Two closed chains blend station to +/// station from their seams — `seam` (a point on each chain) when given, otherwise the pairing +/// that keeps the blend from twisting; a closed chain does not blend to an open one. `align` +/// overrides the direction each side leaves in (points in world space); `crown` how full each side +/// is; `stitch` sews the blend to its two bodies where their boundaries meet. The reply's `gap`, if +/// any, is how far the blend's own boundary lay from the chains it was built on. +#[allow(clippy::too_many_arguments)] pub fn blend_between( a: &Body, picks_a: &[Vec3], @@ -669,6 +884,7 @@ pub fn blend_between( orders: [Continuity; 2], crown: [f64; 2], align: Option<[Vec3; 2]>, + seam: Option<[Vec3; 2]>, samples: usize, stitch: bool, ) -> Result<(Body, f64)> { @@ -677,9 +893,16 @@ pub fn blend_between( if !(5..=401).contains(&samples) { return Err(KernelError::Invalid("a blend needs 5 to 401 stations".into())); } + if align.iter().chain(&seam).flatten().any(|p| !p.is_finite()) { + return Err(KernelError::Invalid("`align` and `seam` points must be finite".into())); + } let chain_a = chain(a, picks_a)?; let chain_b = chain(b, picks_b)?; - let (mid_a, mid_b) = (chain_mid(&chain_a)?, chain_mid(&chain_b)?); + let (line_a, line_b) = (ChainLine::of(&chain_a)?, ChainLine::of(&chain_b)?); + if line_a.closed != line_b.closed { + return Err(KernelError::Invalid("a closed chain blends only to a closed chain, and an open one only to an open one".into())); + } + let (mid_a, mid_b) = (line_a.middle()?, line_b.middle()?); let (leave_a, leave_b) = match align { Some([p, q]) => ( (p - mid_a).normalized().ok_or_else(|| KernelError::Invalid("`align` must not sit on the boundary".into()))?, @@ -690,19 +913,15 @@ pub fn blend_between( (mid_a - mid_b).normalized().ok_or_else(|| KernelError::Invalid("the two boundaries coincide: there is nothing to blend".into()))?, ), }; - let (face_a, leave_a) = support_face(a, &chain_a, leave_a)?; - let (face_b, leave_b) = support_face(b, &chain_b, leave_b)?; - let frames_a = frames(&face_a, &chain_a, leave_a, samples)?; - let mut frames_b = frames(&face_b, &chain_b, leave_b, samples)?; - // The two chains are sampled from their own starts: turn one round when that pairs the - // stations better (the blend is built station to station). - let direct: f64 = frames_a.iter().zip(&frames_b).map(|(x, y)| x.p.dist(y.p)).sum(); - let reversed: f64 = frames_a.iter().zip(frames_b.iter().rev()).map(|(x, y)| x.p.dist(y.p)).sum(); - if reversed < direct { - frames_b.reverse(); - } + let faces_a = support_faces(a, &chain_a, leave_a)?; + let faces_b = support_faces(b, &chain_b, leave_b)?; + let (start_a, backwards_a) = seam.map_or((0.0, false), |[p, _]| line_a.start_at_seam(p)); + let stations_a = line_a.stations(samples, start_a, backwards_a)?; + let stations_b = pair_with(&stations_a, &line_b, seam.map(|[_, q]| q))?; + let frames_a = frames_on(&faces_a, &stations_a, &line_a, leave_a)?; + let frames_b = frames_on(&faces_b, &stations_b, &line_b, leave_b)?; let made = bridge(&frames_a, &frames_b, orders, crown)?; - let gap = boundary_gap(&made, &chain_a, false)?.max(boundary_gap(&made, &chain_b, true)?); + let gap = boundary_gap(&made, &line_a, false)?.max(boundary_gap(&made, &line_b, true)?); let faces: Vec = made.solid.face_iter().cloned().collect(); let mut rec = crate::record::Rebuild::default(); for f in &faces { diff --git a/crates/kernel/src/bridge_tests.rs b/crates/kernel/src/bridge_tests.rs index 0b6c9c5ac..82966612b 100644 --- a/crates/kernel/src/bridge_tests.rs +++ b/crates/kernel/src/bridge_tests.rs @@ -242,3 +242,141 @@ fn continuity_parses_its_words() { assert_eq!(Continuity::parse(""), None); assert_eq!([Continuity::G0, Continuity::G1, Continuity::G2, Continuity::G3].map(Continuity::conditions), [1, 2, 3, 4]); } + +/// A radius-10 tube along z from `z0` to `z0 + 30`, turned `turn` radians about its axis (which +/// moves where its rim's seam sits), with the end face at `open_at` taken off: a surface body +/// whose rim there is a closed chain. +fn open_tube(z0: f64, turn: f64, open_at: f64) -> Body { + let c = cylinder(Vec3::new(0.0, 0.0, z0), Vec3::Z, 10.0, 30.0).unwrap(); + let c = crate::transform(&c, Vec3::ZERO, Vec3::ZERO, Vec3::Z, turn).unwrap(); + let (_, rest) = crate::surfaces::unstitch(&c, &[Vec3::new(0.0, 0.0, open_at)]).unwrap(); + rest.unwrap() +} + +/// Points round a radius-10 rim at height `z`. +fn rim_at(z: f64) -> Vec { + (0..8).map(|k| f64::from(k) * std::f64::consts::FRAC_PI_4 + 0.1).map(|a| Vec3::new(10.0 * a.cos(), 10.0 * a.sin(), z)).collect() +} + +/// How far a blend between two coaxial rims turns round the axis: the most, over its stations, +/// of the angle between where a cross-section starts and where it ends (zero for straight +/// rulings parallel to the axis). +fn worst_turn(body: &Body) -> f64 { + let grid = sample_grid(body, 33, 9).unwrap(); + grid.iter() + .map(|row| { + let (a, b) = (row[0], row[row.len() - 1]); + angle_deg(Vec3::new(a.x, a.y, 0.0), Vec3::new(b.x, b.y, 0.0)) + }) + .fold(0.0, f64::max) +} + +#[test] +fn a_blend_between_closed_rims_lines_their_seams_up() { + // Two coaxial tubes 10 apart, the upper one turned a quarter round: its rim's seam is 90° + // from the lower rim's. The blend between them is the cylinder wall between: every ruling + // straight up the axis, none turning round it. + let low = open_tube(0.0, 0.0, 30.0); + let high = open_tube(40.0, std::f64::consts::FRAC_PI_2, 40.0); + for orders in [[Continuity::G0, Continuity::G0], [Continuity::G1, Continuity::G1], [Continuity::G2, Continuity::G2]] { + let (made, gap) = blend_between(&low, &rim_at(30.0), &high, &rim_at(40.0), orders, [0.0, 0.0], None, None, 65, false).unwrap(); + let turn = worst_turn(&made); + // The boundary is a cubic through the stations on the rim: between them it strays by the + // interpolation error of a circle at 65 stations (about 2e-5 mm here). + assert!(gap < 1e-4, "{orders:?}: the boundary stays on the rims: {gap}"); + assert!(turn < 0.1, "{orders:?}: the blend turns {turn}° round the axis"); + // The wall between: radius 10 everywhere (G1 and G2 repeat a straight wall). + for row in sample_grid(&made, 17, 9).unwrap() { + for p in row { + assert!((Vec3::new(p.x, p.y, 0.0).len() - 10.0).abs() < 1e-5, "{orders:?}: off the wall at {p:?}"); + } + } + } +} + +#[test] +fn a_closed_chain_blends_only_to_a_closed_chain() { + // The tube's closed rim against one open edge of a box's top. + let tube = open_tube(0.0, 0.0, 30.0); + let b = box_solid(Vec3::new(-20.0, 30.0, 30.0), Vec3::new(20.0, 40.0, 40.0)).unwrap(); + let err = blend_between(&tube, &rim_at(30.0), &b, &[Vec3::new(0.0, 30.0, 40.0)], [Continuity::G1; 2], [0.0, 0.0], None, None, 33, false); + assert!(matches!(&err, Err(KernelError::Invalid(m)) if m.contains("closed chain")), "{err:?}"); + let err = blend_between(&b, &[Vec3::new(0.0, 30.0, 40.0)], &tube, &rim_at(30.0), [Continuity::G1; 2], [0.0, 0.0], None, None, 33, false); + assert!(matches!(&err, Err(KernelError::Invalid(m)) if m.contains("closed chain")), "{err:?}"); +} + +#[test] +fn a_blend_between_offset_strips_is_the_cubic_hermite_strip() { + // Two 40-long boxes 10 apart in y, the second standing 5 higher: the blend from the first's + // top rim (y = 10, z = 10) to the second's (y = 20, z = 15), G1 at both ends. Every + // cross-section is the cubic Bézier that leaves each top face along it, at the speed chord/3 + // (chord = |(10, 5)|): control points (10, 10), (10 + chord/9, 10), (20 - chord/9, 15), + // (20, 15) in (y, z), the same at every x. + let a = box_solid(Vec3::new(0.0, 0.0, 0.0), Vec3::new(40.0, 10.0, 10.0)).unwrap(); + let b = box_solid(Vec3::new(0.0, 20.0, 5.0), Vec3::new(40.0, 30.0, 15.0)).unwrap(); + let (made, gap) = + blend_between(&a, &[Vec3::new(20.0, 10.0, 10.0)], &b, &[Vec3::new(20.0, 20.0, 15.0)], [Continuity::G1; 2], [0.0, 0.0], None, None, 9, false) + .unwrap(); + assert!(gap < 1e-9, "straight rims: the boundary is on them exactly: {gap}"); + let chord = 125f64.sqrt(); + let control = [(10.0, 10.0), (10.0 + chord / 9.0, 10.0), (20.0 - chord / 9.0, 15.0), (20.0, 15.0)]; + let bezier = |t: f64| { + let w = [(1.0 - t).powi(3), 3.0 * t * (1.0 - t).powi(2), 3.0 * t * t * (1.0 - t), t.powi(3)]; + control.iter().zip(w).fold((0.0, 0.0), |(y, z), ((cy, cz), w)| (y + cy * w, z + cz * w)) + }; + let across = 11; + for row in sample_grid(&made, 9, across).unwrap() { + for (j, p) in row.iter().enumerate() { + let (y, z) = bezier(j as f64 / (across - 1) as f64); + assert!((p.y - y).abs() < 1e-9 && (p.z - z).abs() < 1e-9, "at v = {j}/{}: {p:?} vs the Hermite strip ({y}, {z})", across - 1); + } + } + // G1 at both seams: the blend's normal is the top faces' (±z) all along each rim. + let face = made.solid.face_iter().next().unwrap(); + let surf = face.surface(); + let (Some((u0, u1)), Some((v0, v1))) = surf.try_range_tuple() else { panic!("unbounded") }; + for i in 0..=16 { + let u = u0 + (u1 - u0) * i as f64 / 16.0; + for v in [v0, v1] { + let n = surf.normal(u, v); + let worst = angle_deg(Vec3::new(n.x, n.y, n.z), Vec3::Z).min(angle_deg(Vec3::new(n.x, n.y, n.z), Vec3::Z * -1.0)); + assert!(worst < 0.01, "at u = {u}, v = {v}: the normal is {worst}° off the top faces'"); + } + } +} + +#[test] +fn a_picked_seam_sets_where_a_closed_blend_starts() { + // The same coaxial rims as above, but the upper chain told to start a quarter round from where + // the lower one starts: the blend then turns a quarter round the axis, as asked. + let low = open_tube(0.0, 0.0, 30.0); + let high = open_tube(40.0, 0.0, 40.0); + let free = blend_between(&low, &rim_at(30.0), &high, &rim_at(40.0), [Continuity::G1; 2], [0.0, 0.0], None, None, 65, false).unwrap().0; + assert!(worst_turn(&free) < 0.1, "unpicked: no turn ({}°)", worst_turn(&free)); + let first = sample_grid(&free, 2, 2).unwrap()[0][0]; + let quarter = Vec3::new(-first.y, first.x, 40.0); + let seams = Some([Vec3::new(first.x, first.y, 30.0), quarter]); + let turned = blend_between(&low, &rim_at(30.0), &high, &rim_at(40.0), [Continuity::G1; 2], [0.0, 0.0], None, seams, 65, false).unwrap().0; + let turn = worst_turn(&turned); + assert!((turn - 90.0).abs() < 0.1, "the picked seams turn the blend a quarter round: {turn}°"); + // Seam points that are not numbers are refused. + let bad = Some([Vec3::new(f64::NAN, 0.0, 30.0), quarter]); + assert!(blend_between(&low, &rim_at(30.0), &high, &rim_at(40.0), [Continuity::G1; 2], [0.0, 0.0], None, bad, 65, false).is_err()); +} + +#[test] +fn a_blend_between_offset_tubes_reads_stations_on_the_walls_seams() { + // A radius-10 tube and a radius-6 one standing 8 off its axis: the blend leaves each rim at an + // angle, so a station on the vertex where a wall's two halves meet is at a corner of one + // half's parameters. It is read on the other half, and the blend builds at every order. + let low = open_tube(0.0, 0.0, 30.0); + let high = cylinder(Vec3::new(8.0, 0.0, 50.0), Vec3::Z, 6.0, 25.0).unwrap(); + let (_, high) = crate::surfaces::unstitch(&high, &[Vec3::new(8.0, 0.0, 50.0)]).unwrap(); + let high = high.unwrap(); + let rim6: Vec = rim_at(50.0).into_iter().map(|p| Vec3::new(8.0 + p.x * 0.6, p.y * 0.6, 50.0)).collect(); + for orders in [[Continuity::G1; 2], [Continuity::G2; 2], [Continuity::G3; 2]] { + let made = blend_between(&low, &rim_at(30.0), &high, &rim6, orders, [0.0, 0.0], None, None, 41, false); + let (_, gap) = made.unwrap_or_else(|e| panic!("{orders:?}: {e:?}")); + assert!(gap < 1e-3, "{orders:?}: {gap}"); + } +} diff --git a/crates/kernel/src/plane_fit.rs b/crates/kernel/src/plane_fit.rs index bfb118bdb..f44b7f316 100644 --- a/crates/kernel/src/plane_fit.rs +++ b/crates/kernel/src/plane_fit.rs @@ -37,6 +37,17 @@ pub(crate) fn plane_through(pts: &[mt::Point3]) -> Option { Some(mt::Plane::new(o, o + x, o + y)) } +/// The area vector of a closed polygon (Newell's method): normal to the loop, as long as the area +/// it encloses, pointing the way the loop runs round by the right-hand rule. +pub(crate) fn loop_area(points: &[Vec3]) -> Vec3 { + let mut n = Vec3::ZERO; + for (i, p) in points.iter().enumerate() { + let Some(q) = points.get((i + 1) % points.len()) else { continue }; + n += Vec3::new((p.y - q.y) * (p.z + q.z), (p.z - q.z) * (p.x + q.x), (p.x - q.x) * (p.y + q.y)); + } + n * 0.5 +} + /// The point of `c` at `t` (`None` where an intersection curve cannot find it). fn curve_point(c: &mt::Curve, t: f64) -> Option { let p = match c { diff --git a/crates/ui-egui/src/blend_dialog_tests.rs b/crates/ui-egui/src/blend_dialog_tests.rs new file mode 100644 index 000000000..09aaa8a5f --- /dev/null +++ b/crates/ui-egui/src/blend_dialog_tests.rs @@ -0,0 +1,82 @@ +//! The Blend Surface dialog (#764): edges at each end, the continuity and bulge of each end and +//! the stitch toggle become `surface.blend`, and Edit Feature brings them back with what the +//! dialog does not show (the seams) kept as they were. +use crate::dialogs::Kind; +use crate::dialogs_surface::Surf; +use crate::scenario::Harness; +use serde_json::json; +use solidcraft_engine::doc::{FeatureKind, kernel::Continuity}; +use solidcraft_engine::geom::Vec3; + +fn ok(h: &mut Harness) { + h.frames(2); + h.step(&json!({"widget":"OK"})).unwrap(); + // An edit is applied off the UI thread: give it the frames it takes. + for _ in 0..200 { + if h.app.dialog.is_none() { + break; + } + h.frames(1); + } + assert!(h.app.dialog.is_none(), "{:?} {:?} {:?}", h.app.preview.error, h.app.dialog.as_ref().map(|d| (&d.error, &d.inputs)), h.app.session.log); +} + +/// What the blend feature `name` was made with: the bodies at each end, continuity, bulge, seams +/// and stitch. +#[allow(clippy::type_complexity)] +fn blend(h: &Harness, name: &str) -> (String, String, [Continuity; 2], [f64; 2], Option<[Vec3; 2]>, bool) { + match &h.app.session.doc.find_feature(name).unwrap().kind { + FeatureKind::SurfaceBlend { from, to, continuity, bulge, seam, stitch, .. } => { + (from.body.to_string(), to.body.to_string(), *continuity, *bulge, seam.map(|[p, q]| [p.0, q.0]), *stitch) + } + k => panic!("{k:?}"), + } +} + +#[test] +fn edges_at_each_end_make_a_blend_and_come_back_in_an_edit() { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length": 40, "width": 10, "height": 10, "corner": [0, 0, 0], "body_name": "A"})).unwrap(); + h.app.run("solid.box", json!({"length": 40, "width": 10, "height": 10, "corner": [0, 20, 5], "body_name": "B"})).unwrap(); + let from = crate::dialogs::edge_sel(&h.app.session, Vec3::new(20.0, 10.0, 10.0)).unwrap(); + let to = crate::dialogs::edge_sel(&h.app.session, Vec3::new(20.0, 20.0, 15.0)).unwrap(); + h.step(&json!({"call":"ui.start","params":{"command":"surface.blend"}})).unwrap(); + h.frames(3); + assert!(h.widget("From edges").is_some() && h.widget("Start continuity").is_some() && h.widget("End bulge").is_some()); + let d = h.app.dialog.as_mut().unwrap(); + d.inputs[0].items = vec![from]; + d.inputs[1].items = vec![to]; + let Kind::Surface(Surf::Blend { continuity, bulge, .. }) = &mut d.kind else { panic!("{:?}", d.kind) }; + *continuity = [2, 1]; + *bulge = [0.5, 0.0]; + ok(&mut h); + let name = h.app.session.doc.features.last().unwrap().name.clone(); + let (a, b, continuity, bulge, seam, stitch) = blend(&h, &name); + assert_eq!((a.as_str(), b.as_str()), ("A", "B")); + assert_eq!(continuity, [Continuity::G2, Continuity::G1]); + assert_eq!((bulge, seam, stitch), ([0.5, 0.0], None, false)); + assert_eq!(h.app.session.world_state().bodies.len(), 3, "a new surface body beside the boxes"); + // A blend made by the command with a seam the dialog does not show: an edit keeps it. + h.app.session.execute("edit.undo", &json!({})).unwrap(); + h.app + .run( + "surface.blend", + json!({"from": {"body": "A", "edges": [[20, 10, 10]]}, "to": {"body": "B", "edges": [[20, 20, 15]]}, + "continuity": ["g2", "g1"], "seam": [[0, 10, 10], [0, 20, 15]]}), + ) + .unwrap(); + let name = h.app.session.doc.features.last().unwrap().name.clone(); + h.step(&json!({"call":"ui.editFeature","params":{"feature":name}})).unwrap(); + h.frames(8); + let d = h.app.dialog.as_mut().unwrap(); + assert!(matches!(d.kind, Kind::Surface(Surf::Blend { continuity: [2, 1], stitch: false, .. })), "{:?}", d.kind); + assert_eq!((d.inputs[0].items.len(), d.inputs[1].items.len()), (1, 1), "{:?}", d.inputs); + let Kind::Surface(Surf::Blend { stitch, .. }) = &mut d.kind else { panic!() }; + *stitch = true; + ok(&mut h); + let (_, _, continuity, _, seam, stitch) = blend(&h, &name); + assert_eq!(continuity, [Continuity::G2, Continuity::G1]); + assert_eq!(seam, Some([Vec3::new(0.0, 10.0, 10.0), Vec3::new(0.0, 20.0, 15.0)])); + assert!(stitch); + assert_eq!(h.app.session.world_state().bodies.len(), 1, "stitched onto both boxes"); +} diff --git a/crates/ui-egui/src/dialogs_surface.rs b/crates/ui-egui/src/dialogs_surface.rs index 36a23f96c..d5ba285e6 100644 --- a/crates/ui-egui/src/dialogs_surface.rs +++ b/crates/ui-egui/src/dialogs_surface.rs @@ -1,5 +1,5 @@ //! Dialogs for the surface tools and face splitting (#19): Surface Extrude, Revolve, Sweep and -//! Loft, Offset and Ruled Surface, Boundary Surface, Patch, Stitch, Thicken, Extend, Trim, Untrim +//! Loft, Offset and Ruled Surface, Blend and Boundary Surface, Patch, Stitch, Thicken, Extend, Trim, Untrim //! and Split Face. Each has a live preview and Edit Feature. use serde_json::{Map, Value, json}; @@ -32,6 +32,13 @@ pub enum Surf { Loft { rail_fit: usize, }, + /// `continuity`: an index into [`BLEND_CONTINUITY`] for each end, [from, to]; `bulge`: how + /// full each end leaves (0 is the plain bridge); `stitch`: sew the blend onto both bodies. + Blend { + continuity: [usize; 2], + bulge: [f64; 2], + stitch: bool, + }, /// `continuity`: an index into [`PATCH_CONTINUITY`] (for a loop of sketch curves, how much of /// the sketch's plane each side repeats; for picked edges, how the surface meets the faces /// beside them); `join`: sew the surface into the body of its edges. @@ -91,6 +98,7 @@ impl Surf { Surf::Revolve { .. } => "SURFACE REVOLVE", Surf::Sweep(_) => "SURFACE SWEEP", Surf::Loft { .. } => "SURFACE LOFT", + Surf::Blend { .. } => "BLEND SURFACE", Surf::Boundary { .. } => "BOUNDARY SURFACE", Surf::Patch { .. } => "PATCH", Surf::Unstitch => "UNSTITCH", @@ -122,6 +130,11 @@ impl Surf { /// How a patch on edges meets the faces beside its loop (labels, and the `continuity` parameter). const PATCH_CONTINUITY: [(&str, &str); 3] = [("Position (G0)", "g0"), ("Tangent (G1)", "g1"), ("Curvature (G2)", "g2")]; +/// How much of the surface at its edges each end of a blend repeats (labels, and the +/// `continuity` words). +const BLEND_CONTINUITY: [(&str, &str); 4] = + [("Position (G0)", "g0"), ("Tangent (G1)", "g1"), ("Curvature (G2)", "g2"), ("Curvature change (G3)", "g3")]; + /// What a boundary surface becomes: a body of its own, or part of the body of its edges. const BOUNDARY_OPS: [&str; 2] = ["New Body", "Join"]; @@ -152,6 +165,7 @@ fn inputs(k: &Surf) -> Vec { let [rail, rail2] = crate::dialogs_sweep::rail_inputs(); vec![SelInput::new("Sections (one sketch each)", PROFILES | CURVES, true), rail, rail2] } + Surf::Blend { .. } => vec![SelInput::new("From edges", EDGES, true), SelInput::new("To edges", EDGES, true)], Surf::Boundary { .. } => vec![SelInput::new("Curves", CURVES | EDGES, true), SelInput::new("Cross curves", CURVES | EDGES, true)], Surf::Patch { .. } => vec![SelInput::new("Boundary", PROFILES | EDGES, true), SelInput::new("Pass through", VERTICES | FACES, true)], Surf::Unstitch => vec![SelInput::new("Body, or faces to take out", BODIES | FACES, true)], @@ -182,6 +196,7 @@ pub fn start(_app: &SolveApp, id: &str) -> Option<(Kind, Vec)> { "surface.revolve" => Surf::Revolve { angle: "360 deg".into(), symmetric: false, axis: None }, "surface.sweep" => Surf::Sweep(crate::dialogs_sweep::SweepOpts::default()), "surface.loft" => Surf::Loft { rail_fit: 0 }, + "surface.blend" => Surf::Blend { continuity: [1, 1], bulge: [0.0, 0.0], stitch: false }, "surface.boundary" => Surf::Boundary { continuity: 1, join: false }, "surface.patch" => Surf::Patch { continuity: 0 }, "surface.unstitch" => Surf::Unstitch, @@ -292,6 +307,26 @@ pub fn rows(ui: &mut egui::Ui, k: &mut Surf) -> bool { combo(ui, "pa_cont", &PATCH_CONTINUITY.map(|(label, _)| label), continuity); ui.end_row(); } + Surf::Blend { continuity, bulge, stitch } => { + // One row per end, so the dialog keeps its docked width. + let [from, to] = continuity; + let [from_bulge, to_bulge] = bulge; + row_label(ui, "Start continuity"); + combo(ui, "bl_cont0", &BLEND_CONTINUITY.map(|(label, _)| label), from); + ui.end_row(); + row_label(ui, "Start bulge"); + ui.add(egui::DragValue::new(from_bulge).range(-0.9..=3.0).speed(0.01).max_decimals(2)); + ui.end_row(); + row_label(ui, "End continuity"); + combo(ui, "bl_cont1", &BLEND_CONTINUITY.map(|(label, _)| label), to); + ui.end_row(); + row_label(ui, "End bulge"); + ui.add(egui::DragValue::new(to_bulge).range(-0.9..=3.0).speed(0.01).max_decimals(2)); + ui.end_row(); + row_label(ui, "Stitch to both bodies"); + ui.checkbox(stitch, ""); + ui.end_row(); + } Surf::Boundary { continuity, join } => { row_label(ui, "Continuity"); combo(ui, "bo_cont", &PATCH_CONTINUITY.map(|(label, _)| label), continuity); @@ -343,6 +378,17 @@ fn body_and_faces(picks: &[Sel]) -> Result<(String, Vec), String> { Ok((body, faces)) } +/// The body of picked edges (all of one body) and a point on each edge. +fn body_and_edges(picks: &[Sel]) -> Result<(String, Vec), String> { + let body_of = |x: &Sel| if let Sel::Edge { body, .. } = x { Some(body.clone()) } else { None }; + let body = picks.iter().find_map(body_of).ok_or("pick edges of a body")?; + if picks.iter().any(|x| body_of(x).as_ref() != Some(&body)) { + return Err("pick edges of one body".into()); + } + let edges = picks.iter().filter_map(|x| if let Sel::Edge { point, .. } = x { Some(pt(*point)) } else { None }).collect(); + Ok((body, edges)) +} + /// The sketch, profiles and curves of a surface builder's picks (all in one sketch). fn sheet_picks(app: &SolveApp, picks: &[Sel]) -> Result { let profiles: Vec<(u64, usize)> = @@ -548,6 +594,25 @@ pub fn commands(app: &SolveApp, k: &Surf, inputs: &[SelInput], extra: &Map { + need(0, "the edges the blend leaves")?; + need(1, "the edges the blend arrives at")?; + let side = |i: usize| -> Result { + let (body, edges) = body_and_edges(items(inputs, i))?; + Ok(json!({"body": body, "edges": edges})) + }; + let word = |i: usize| BLEND_CONTINUITY.get(i).map_or("g1", |(_, w)| *w); + let mut p = json!({ + "from": side(0)?, + "to": side(1)?, + "continuity": [word(continuity[0]), word(continuity[1])], + "bulge": bulge, + }); + if *stitch { + p["stitch"] = json!(true); + } + ("surface.blend", p) + } Surf::Boundary { continuity, join } => { need(0, "the curves (sketch curves or edges)")?; let word = PATCH_CONTINUITY.get(*continuity).map_or("g0", |(_, w)| *w); @@ -632,13 +697,7 @@ pub fn commands(app: &SolveApp, k: &Surf, inputs: &[SelInput], extra: &Map { need(0, "the edges to rule from")?; - let edge_body = |x: &Sel| if let Sel::Edge { body, .. } = x { Some(body.clone()) } else { None }; - let body = items(inputs, 0).iter().find_map(edge_body).ok_or("pick edges of a body")?; - if items(inputs, 0).iter().any(|x| edge_body(x).as_ref() != Some(&body)) { - return Err("pick edges of one body".into()); - } - let edges: Vec = - items(inputs, 0).iter().filter_map(|x| if let Sel::Edge { point, .. } = x { Some(pt(*point)) } else { None }).collect(); + let (body, edges) = body_and_edges(items(inputs, 0))?; let mode = RULED_MODES.get(*mode).map_or("normal", |(_, m)| *m); let mut p = json!({"body": body, "edges": edges, "distance": distance, "mode": mode}); if mode == "angle" { @@ -846,6 +905,22 @@ pub fn for_feature(app: &SolveApp, kind: &FeatureKind, frame: &Mat) -> Option<(K ], ) } + FeatureKind::SurfaceBlend { from, to, continuity, bulge, align, seam, stitch } => { + let index = |c: &solidcraft_engine::doc::kernel::Continuity| BLEND_CONTINUITY.iter().position(|(_, w)| *w == c.as_str()).unwrap_or(1); + let k = Surf::Blend { continuity: continuity.each_ref().map(index), bulge: *bulge, stitch: *stitch }; + // What the dialog does not show is kept as it was: the leave directions and the seams. + let mut extra = Map::new(); + for (key, points) in [("align", align), ("seam", seam)] { + if let Some([p, q]) = points { + extra.insert(key.into(), json!([pt(p.0), pt(q.0)])); + } + } + let mut ins = inputs(&k); + for (inp, side) in ins.iter_mut().zip([from, to]) { + inp.items = side.edges.iter().filter_map(edge).collect(); + } + return Some((Kind::Surface(k), ins, extra)); + } FeatureKind::SurfaceBoundary { curves, orders, crown, samples, .. } => { let first = orders.first().copied().unwrap_or(solidcraft_engine::doc::kernel::Continuity::G1); let index = PATCH_CONTINUITY.iter().position(|(_, w)| *w == first.as_str()); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 90c09fe69..b269fe356 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -119,6 +119,8 @@ pub use file_picker::FilePickerFuture; #[cfg(test)] mod blend_arrow_tests; #[cfg(test)] +mod blend_dialog_tests; +#[cfg(test)] mod boundary_dialog_tests; pub(crate) mod display_lod; #[cfg(test)] From e9b1a077d7e33420791791c651f2e293962a2da1 Mon Sep 17 00:00:00 2001 From: fugazister Date: Tue, 20 Oct 2026 06:37:50 +0000 Subject: [PATCH 181/225] Delete: check what a delete breaks off the window thread (#2678) (#2679) * claim: #2678 Co-Authored-By: Claude Opus 5.5 * WIP: timeline.dependents shares the evaluation cache (#2678) The check before a delete evaluated the edited design on a fresh model: it recomputed the whole timeline and left nothing for the delete. It now evaluates on a copy of the session's model. Adds Ahead::replies for running such checks off the window thread (the UI part is still to come). Co-Authored-By: Claude Opus 5.5 * Delete: check what a delete breaks off the window thread (#2678) Both checks a delete makes first (timeline.dependents for the timeline's Delete, the selection.delete dry run for Delete on the selection) evaluate the history after the deleted feature, on the window thread. A part with a slow feature froze the window for as long as everything after it took (5.9 s in the report). They now compute off the window thread like undo and the history marker: within the app's 150 ms wait they carry on at once, otherwise the window says it computes and the delete (or the confirmation) follows when the report is in. A design changed meanwhile is checked again; a second Delete meanwhile is left out. Co-Authored-By: Claude Opus 5.5 * ci: run the checks again (the run for 3b94e8e0 was cancelled when the PR left draft) Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: bherbruck --- crates/engine/src/cmd/edit.rs | 7 +- crates/engine/src/cmd/edit_tests.rs | 20 ++++ crates/engine/src/lib.rs | 7 ++ crates/ui-egui/src/deferred.rs | 113 +++++++++++++++++- crates/ui-egui/src/delete.rs | 12 +- .../ui-egui/src/history_off_thread_tests.rs | 72 ++++++++++- crates/ui-egui/src/lib.rs | 5 + crates/ui-egui/src/timeline.rs | 13 +- 8 files changed, 238 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index fc8e4b45a..04b39f5ef 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1075,7 +1075,7 @@ fn reorder(s: &mut Session, p: &Value) -> Result { sort_group_features(&mut next); require_contiguous_groups(&next, cmd)?; // Everything that evaluated before must still evaluate. - let mut after = solidcraft_doc::Model::new(); + let mut after = s.model.clone(); after.evaluate(&next); let broken = newly_broken(&s.model, &after); if !broken.is_empty() { @@ -1338,7 +1338,10 @@ fn dependents(s: &mut Session, p: &Value) -> Result { let id = feature_id(s, p.get("feature"), cmd)?; let mut next = (*s.doc).clone(); let gone = next.delete_feature(id)?; - let mut after = solidcraft_doc::Model::new(); + // On a copy of the session's model, which shares its evaluation cache (#2678): the features + // before this one are reused rather than recomputed, and the delete that usually follows + // finds the ones after it already computed. + let mut after = s.model.clone(); after.evaluate(&next); let names = |ids: &[u64]| -> Vec { ids.iter().filter(|x| **x != id).filter_map(|x| s.doc.feature(*x).map(|f| f.name.clone())).collect() }; let broken: Vec = newly_broken(&s.model, &after).into_iter().map(|(n, _)| n).collect(); diff --git a/crates/engine/src/cmd/edit_tests.rs b/crates/engine/src/cmd/edit_tests.rs index d4acb82ae..e29aede83 100644 --- a/crates/engine/src/cmd/edit_tests.rs +++ b/crates/engine/src/cmd/edit_tests.rs @@ -597,6 +597,26 @@ fn edit_refuses_unknown_fields() { assert_eq!(def["combine"], json!(true), "{def}"); } +/// The check before a delete (`timeline.dependents`) evaluates on the session's model, so it +/// shares the evaluation cache (#2678): the delete that follows finds the features after the +/// deleted one already computed instead of computing them again. (What it reports is covered by +/// the timeline tests in `tests.rs`.) +#[test] +fn the_dependents_check_leaves_the_delete_its_results() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 60, "width": 20, "height": 10, "name": "Base"})); + run(&mut s, "solid.box", json!({"corner": [5, 5, 10], "length": 10, "width": 10, "height": 5, "operation": "join", "name": "Boss"})); + run(&mut s, "solid.cylinder", json!({"base": [40, 10, -1], "radius": 2, "height": 20, "operation": "cut", "name": "Hole"})); + let report = run(&mut s, "timeline.dependents", json!({"feature": "Boss"})); + assert_eq!(report, json!({"deleted_with_it": [], "would_fail": []})); + let hits = |s: &Session| s.model.cache.lock().map(|c| c.hits).unwrap_or(0); + let before = hits(&s); + run(&mut s, "timeline.delete", json!({"features": ["Boss"]})); + assert!(hits(&s) > before, "the delete takes the hole the check computed from the cache"); + let volume = run(&mut s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64().unwrap(); + assert!((volume - (12000.0 - std::f64::consts::PI * 4.0 * 10.0)).abs() < 1.0, "{volume}"); +} + fn suppressed(s: &Session, name: &str) -> bool { s.doc.find_feature(name).unwrap().suppressed } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 5129dd1fb..9f1fc0bba 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -165,6 +165,13 @@ impl Ahead { pub fn evaluate(self, commands: &[(String, Value)]) -> Result<()> { self.0.preview_in_place(commands).map(|_| ()) } + + /// Run `commands` one after another, each reply or error in turn (what they evaluate stays + /// in the shared evaluation cache): the checks a front end makes before a command, such as + /// what a delete takes with it (#2678), computed off its window thread. + pub fn replies(mut self, commands: &[(String, Value)]) -> Vec> { + commands.iter().map(|(id, params)| self.0.execute(id, params)).collect() + } } /// What some commands would make, evaluated on a scratch copy of a session diff --git a/crates/ui-egui/src/deferred.rs b/crates/ui-egui/src/deferred.rs index 12140f866..4a9104631 100644 --- a/crates/ui-egui/src/deferred.rs +++ b/crates/ui-egui/src/deferred.rs @@ -11,6 +11,12 @@ //! its features in the cache. Commands asked for meanwhile wait their turn; a marker moved again //! replaces the move still waiting, so a drag computes where it ends rather than every slot it //! crossed. +//! +//! A delete first checks what it takes with it and what it would make fail (#2678): the +//! timeline's Delete asks `timeline.dependents`, Delete on the selection runs `selection.delete` +//! as a dry run. Each check evaluates the history after the deleted feature, so it is computed +//! the same way ([`DeleteCheck`]): the window goes on while it computes, then the delete runs, or +//! the confirmation opens, with the check's results already in the cache. use serde_json::Value; @@ -32,6 +38,54 @@ impl Deferred { } } +/// A delete's check computing off the window thread: each check command's reply, in order. +pub struct DeleteCheck { + done: std::sync::mpsc::Receiver>>, + /// When it started (ms). + pub(crate) started: f64, + then: AfterCheck, + /// The design's revision it was computed for: a design changed meanwhile checks again. + revision: u64, +} + +/// What a delete does once its check is in. +#[derive(Clone, Debug)] +pub(crate) enum AfterCheck { + /// The timeline's Delete of these features (a `timeline.dependents` report for each). + Timeline(Vec), + /// Delete with these `selection.delete` parameters (the report of its dry run). + Selection(Value), +} + +impl AfterCheck { + /// Check again, for the design as it is now. + fn restart(self, app: &mut SolveApp) { + match self { + AfterCheck::Timeline(ids) => { + let ids: Vec = ids.into_iter().filter(|id| app.session.doc.feature(*id).is_some()).collect(); + if !ids.is_empty() { + crate::timeline::delete_features(app, ids); + } + } + AfterCheck::Selection(params) => crate::delete::request(app, params), + } + } + + /// Carry on with the check's replies. + fn finish(self, app: &mut SolveApp, replies: Vec>) { + match self { + AfterCheck::Timeline(ids) => { + let reports: Vec = replies.into_iter().map(Result::unwrap_or_default).collect(); + crate::timeline::delete_checked_features(app, ids, &reports); + } + AfterCheck::Selection(params) => { + let report = replies.into_iter().next().unwrap_or_else(|| Err("the delete was not checked".into())); + crate::delete::checked(app, params, report); + } + } + } +} + /// Commands a later one of the same kind replaces while they wait: where the marker ends is all /// that counts. fn replaced_by_a_later_one(id: &str) -> bool { @@ -59,9 +113,64 @@ impl SolveApp { } } - /// Since when a command has been computing off the window thread (ms), if one is. + /// Since when a command, or a delete's check, has been computing off the window thread (ms), + /// if one is. pub fn computing_since(&self) -> Option { - self.deferred.as_ref().map(|d| d.started) + let started = [self.deferred.as_ref().map(|d| d.started), self.delete_check.as_ref().map(|c| c.started)]; + started.into_iter().flatten().reduce(f64::min) + } + + /// Run a delete's check `commands` and carry on with `then` once their replies are in: off + /// the window thread when it takes longer than the app's wait (see the module notes), + /// otherwise right away. A Delete while another delete is being checked is left out. + pub(crate) fn check_delete(&mut self, commands: Vec<(String, Value)>, then: AfterCheck) { + if self.delete_check.is_some() { + return; + } + #[cfg(not(target_arch = "wasm32"))] + if let Some(wait) = self.apply_off_thread + && !self.file_load.busy() + && self.file_picker.is_none() + { + let ahead = self.session.ahead(); + let (tx, rx) = std::sync::mpsc::channel(); + let checks = commands.clone(); + let spawned = std::thread::Builder::new().name("delete check".into()).spawn(move || { + let replies = ahead.replies(&checks).into_iter().map(|r| r.map_err(|e| e.to_string())).collect(); + let _ = tx.send(replies); + }); + if spawned.is_ok() { + let check = DeleteCheck { done: rx, started: crate::now_ms(), then, revision: self.session.revision }; + // As with the history's commands, zero always leaves it for a later frame. + match (wait.is_zero(), check.done.recv_timeout(wait)) { + (false, Ok(replies)) => check.then.finish(self, replies), + _ => self.delete_check = Some(check), + } + return; + } + } + let replies = commands.iter().map(|(id, params)| self.session.execute(id, params).map_err(|e| e.to_string())).collect(); + then.finish(self, replies); + } + + /// Each frame: a delete whose check is in carries on (checked again when the design changed + /// meanwhile). + pub(crate) fn poll_delete_check(&mut self, ctx: &egui::Context) { + let Some(check) = &self.delete_check else { return }; + let replies = match check.done.try_recv() { + Err(std::sync::mpsc::TryRecvError::Empty) => { + ctx.request_repaint_after(std::time::Duration::from_millis(100)); + return; + } + Err(std::sync::mpsc::TryRecvError::Disconnected) => None, + Ok(replies) => Some(replies), + }; + let Some(check) = self.delete_check.take() else { return }; + match replies { + None => self.set_status("the delete could not be checked", true), + Some(_) if check.revision != self.session.revision => check.then.restart(self), + Some(replies) => check.then.finish(self, replies), + } } /// Each frame: a command whose evaluation is in runs, then the next one waiting starts. diff --git a/crates/ui-egui/src/delete.rs b/crates/ui-egui/src/delete.rs index 0781dde99..1f1260152 100644 --- a/crates/ui-egui/src/delete.rs +++ b/crates/ui-egui/src/delete.rs @@ -50,17 +50,23 @@ pub fn delete_selection(app: &mut SolveApp) { } /// Delete `params` (as `selection.delete` takes them): at once, or after a confirmation when -/// other features go with it or would fail. +/// other features go with it or would fail. The dry run that finds out evaluates the history +/// after what is deleted, so it may compute off the window thread (#2678). pub fn request(app: &mut SolveApp, params: Value) { if is_empty(¶ms) { return; } let mut dry = params.clone(); dry["dry_run"] = json!(true); - let report = match app.session.execute("selection.delete", &dry) { + app.check_delete(vec![("selection.delete".to_string(), dry)], crate::deferred::AfterCheck::Selection(params)); +} + +/// [`request`] once its dry run's report is in. +pub(crate) fn checked(app: &mut SolveApp, params: Value, report: Result) { + let report = match report { Ok(r) => r, Err(e) => { - app.set_status(e.to_string().replace("selection.delete: ", ""), true); + app.set_status(e.replace("selection.delete: ", ""), true); return; } }; diff --git a/crates/ui-egui/src/history_off_thread_tests.rs b/crates/ui-egui/src/history_off_thread_tests.rs index 99f98a773..c06c16576 100644 --- a/crates/ui-egui/src/history_off_thread_tests.rs +++ b/crates/ui-egui/src/history_off_thread_tests.rs @@ -27,7 +27,7 @@ fn block_boss_hole() -> Harness { /// Frames until nothing computes or waits (a few seconds at most). fn until_settled(h: &mut Harness) { for _ in 0..500 { - if h.app.deferred.is_none() && h.app.deferred_queue.is_empty() { + if h.app.deferred.is_none() && h.app.deferred_queue.is_empty() && h.app.delete_check.is_none() { break; } h.frames(1); @@ -98,3 +98,73 @@ fn a_design_changed_while_a_move_computes_is_computed_again() { assert!(h.app.session.revision > revision, "the move ran after the change"); assert_eq!(marker(&h), Some(2)); } + +fn feature_ids(h: &Harness) -> Vec { + h.app.session.doc.features.iter().map(|f| f.id).collect() +} + +/// Volume of the block with the hole through it, once the boss is deleted. +fn block_with_hole() -> f64 { + 12000.0 - std::f64::consts::PI * 4.0 * 10.0 +} + +fn volume(h: &mut Harness) -> f64 { + h.app.run("inspect.measure", json!({})).unwrap()["total"]["volume_mm3"].as_f64().unwrap() +} + +/// The timeline's Delete checks what the delete breaks off the window thread (#2678): the design +/// is as it was while it checks, and the feature goes once the check is in. +#[test] +fn the_timelines_delete_checks_off_the_window_thread() { + let mut h = block_boss_hole(); + let boss = feature_ids(&h)[1]; + crate::timeline::delete_features(&mut h.app, vec![boss]); + assert!(h.app.computing_since().is_some(), "checking"); + assert!(h.app.session.doc.feature(boss).is_some(), "the design is as it was while it checks"); + until_settled(&mut h); + assert!(h.app.session.doc.feature(boss).is_none(), "deleted once the check is in"); + assert!(h.app.dialog.is_none(), "nothing breaks, so nothing to confirm"); + assert!((volume(&mut h) - block_with_hole()).abs() < 1.0); +} + +/// Delete on the selection (the Delete key) runs its dry run off the window thread too. +#[test] +fn delete_on_the_selection_checks_off_the_window_thread() { + let mut h = block_boss_hole(); + let boss = feature_ids(&h)[1]; + h.app.session.selection = vec![solidcraft_engine::Sel::Feature { id: boss }]; + let params = crate::delete::selection_params(&h.app); + crate::delete::request(&mut h.app, params); + assert!(h.app.computing_since().is_some(), "checking"); + assert!(h.app.session.doc.feature(boss).is_some()); + until_settled(&mut h); + assert!(h.app.session.doc.feature(boss).is_none()); + assert!(h.app.menu.confirm.is_none()); + assert!((volume(&mut h) - block_with_hole()).abs() < 1.0); +} + +/// A design changed while its delete is checked is checked again before anything is deleted, and +/// a second Delete meanwhile is left out. +#[test] +fn a_design_changed_while_a_delete_is_checked_is_checked_again() { + let mut h = block_boss_hole(); + let ids = feature_ids(&h); + crate::timeline::delete_features(&mut h.app, vec![ids[1]]); + crate::timeline::delete_features(&mut h.app, vec![ids[2]]); + h.app.run("solid.box", json!({"corner": [100, 0, 0], "length": 10, "width": 10, "height": 10})).unwrap(); + until_settled(&mut h); + assert!(h.app.session.doc.feature(ids[1]).is_none(), "the boss is deleted"); + assert!(h.app.session.doc.feature(ids[2]).is_some(), "the second Delete was left out"); + assert!((volume(&mut h) - (block_with_hole() + 1000.0)).abs() < 1.0, "the box added meanwhile stays"); +} + +/// Without a wait (headless use, tests) the check runs in place, as before. +#[test] +fn without_a_wait_the_delete_checks_in_place() { + let mut h = block_boss_hole(); + h.app.apply_off_thread = None; + let boss = feature_ids(&h)[1]; + crate::timeline::delete_features(&mut h.app, vec![boss]); + assert!(h.app.delete_check.is_none()); + assert!(h.app.session.doc.feature(boss).is_none()); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index b269fe356..437f9fed0 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -370,6 +370,9 @@ pub struct SolveApp { /// thread, and those asked for meanwhile ([`deferred`]). pub deferred: Option, pub deferred_queue: Vec<(String, Value)>, + /// A delete's check of what it takes with it or breaks, computing off the window thread + /// ([`deferred::DeleteCheck`], #2678). + pub delete_check: Option, /// How long OK waits for a feature before computing it off the window thread, saying so; /// `None`: it waits as long as it takes (headless use, tests). The desktop app sets it. pub apply_off_thread: Option, @@ -492,6 +495,7 @@ impl SolveApp { applying: None, deferred: None, deferred_queue: Vec::new(), + delete_check: None, apply_off_thread: None, last_command: None, esc_handled: false, @@ -1430,6 +1434,7 @@ impl SolveApp { fn cad_ui(&mut self, ui: &mut egui::Ui, report_input: &mut Option) { scenario::clear_handles(); self.poll_deferred(ui.ctx()); + self.poll_delete_check(ui.ctx()); toolbar::app_bar(self, ui); issue_report::CadInput::block(self, ui, report_input); file_load::show(self, ui.ctx()); diff --git a/crates/ui-egui/src/timeline.rs b/crates/ui-egui/src/timeline.rs index 82940ec67..1b8745302 100644 --- a/crates/ui-egui/src/timeline.rs +++ b/crates/ui-egui/src/timeline.rs @@ -2,7 +2,7 @@ pub(crate) use crate::icons::glyphs::transport_glyph; use egui::{Rect, Sense, Stroke, UiBuilder, pos2, vec2}; -use serde_json::json; +use serde_json::{Value, json}; use solidcraft_engine::doc::{ FeatureKind, PlaneRef, SketchId, construct::{AxisDef, PointDef}, @@ -150,11 +150,18 @@ pub(crate) fn delete_feature(app: &mut SolveApp, id: u64) { delete_features(app, vec![id]); } +/// Check what deleting `ids` takes with it or makes fail (off the window thread when that takes a +/// while, #2678), then delete them or ask first. pub(crate) fn delete_features(app: &mut SolveApp, ids: Vec) { + let checks = ids.iter().map(|id| ("timeline.dependents".to_string(), json!({ "feature": id }))).collect(); + app.check_delete(checks, crate::deferred::AfterCheck::Timeline(ids)); +} + +/// [`delete_features`] once each feature's `timeline.dependents` report is in. +pub(crate) fn delete_checked_features(app: &mut SolveApp, ids: Vec, reports: &[Value]) { let mut with = std::collections::BTreeSet::new(); let mut fail = std::collections::BTreeSet::new(); - for id in &ids { - let deps = app.session.execute("timeline.dependents", &json!({ "feature": id })).unwrap_or_default(); + for deps in reports { for (key, output) in [("deleted_with_it", &mut with), ("would_fail", &mut fail)] { output .extend(deps.get(key).and_then(|value| value.as_array()).into_iter().flatten().filter_map(|value| value.as_str().map(String::from))); From 8a562f2719ebe362399f5512296dea2cccb1a14e Mon Sep 17 00:00:00 2001 From: Mateusz Sych <151755914+SychPL@users.noreply.github.com> Date: Tue, 20 Oct 2026 08:28:21 +0000 Subject: [PATCH 182/225] Mesh faces whose boundary touches itself within tolerance (#1648) (#1850) A face pinched to a point, where its boundary touches itself or another of its loops within TOLERANCE (a sphere touching a box's edge leaves one on the box), had a constraint refused by the CDT, and the fallback cut across the face: it came out with no triangles or without those at the pinch. When a constraint is refused, the vendored truck-meshalgo now puts every boundary point within TOLERANCE of a segment into it (at most 8192) and triangulates the face again. Faces whose segments all go in mesh as before. The regression tests live in crates/kernel/src/thin_face_tests.rs, and the #1648 property test in boolean_props.rs is no longer ignored. Robustness seeds 20 and 55 are recorded with their Linux values. Co-authored-by: MateuszSychXpl <151755914+MateuszSychXpl@users.noreply.github.com> --- crates/kernel/src/thin_face_tests.rs | 59 ++++++++++++++++ crates/kernel/tests/boolean_props.rs | 4 +- tests/robustness/goldens.json | 7 +- vendor/README.md | 8 +++ .../src/tessellation/triangulation.rs | 68 ++++++++++++++++++- 5 files changed, 138 insertions(+), 8 deletions(-) diff --git a/crates/kernel/src/thin_face_tests.rs b/crates/kernel/src/thin_face_tests.rs index 105df4152..faef716b9 100644 --- a/crates/kernel/src/thin_face_tests.rs +++ b/crates/kernel/src/thin_face_tests.rs @@ -1,11 +1,17 @@ //! A face thinner than the tolerance still meshes: the lens of a sphere's patch that pokes out //! of a box's side has two edges that, sampled coarsely, run along one line in its parameters. //! The shell's mesh had a hole there. +//! +//! So does a face pinched to a point, where its boundary touches itself within the tolerance (a +//! sphere touching a box's edge leaves one on the box, #1648). use std::collections::HashMap; use solidcraft_geom::Vec3; +use truck_meshalgo::prelude::*; +use truck_modeling as mt; +use crate::body::p3; use crate::{BoolOp, build::box_solid, build::sphere, ops::boolean}; /// Triangle sides in the mesh with no triangle on the other side of them, with the points @@ -41,3 +47,56 @@ fn a_lens_thinner_than_the_tolerance_is_meshed() { assert_eq!(open_sides(&mesh), 0, "open sides at {tol}"); } } + +/// Twice the signed area of a closed polyline in the XY plane. +fn area2(points: &[mt::Point3]) -> f64 { + points.iter().zip(points.iter().cycle().skip(1)).map(|(p, q)| p.x * q.y - q.x * p.y).sum() +} + +/// A face in the XY plane between y = 0 and an arch from (5, h) to (0, h) whose middle dips +/// 2.8e-7 below y = 0, as the intersection curve does in the union of #1648. Its loop starts +/// along the bottom, so the bottom goes into the triangulation before the arch. +#[test] +fn a_face_touching_its_own_edge_meshes() { + let (h, dip) = (0.3175, 2.8e-7); + let v = |x: f64, y: f64| mt::builder::vertex(p3(Vec3::new(x, y, 0.0))); + let (lb, rb, rt, lt) = (v(0.0, 0.0), v(5.0, 0.0), v(5.0, h), v(0.0, h)); + let control = vec![p3(Vec3::new(5.0, h, 0.0)), p3(Vec3::new(2.5, -h - 2.0 * dip, 0.0)), p3(Vec3::new(0.0, h, 0.0))]; + let arch = mt::BSplineCurve::new(mt::KnotVec::bezier_knot(2), control); + let arch = mt::Edge::new(&rt, <, mt::Curve::BSplineCurve(arch)); + let wire: mt::Wire = vec![mt::builder::line(&lb, &rb), mt::builder::line(&rb, &rt), arch, mt::builder::line(<, &lb)].into(); + let plane = mt::Plane::new(p3(Vec3::ZERO), p3(Vec3::X), p3(Vec3::Y)); + 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 face = meshed.face_iter().next().unwrap(); + let boundary: Vec = face.boundaries()[0].edge_iter().flat_map(|e| e.oriented_curve().0.into_iter().skip(1)).collect(); + let mesh = face.surface().unwrap(); + let area: f64 = mesh + .faces() + .triangle_iter() + .map(|t| { + let [a, b, c] = [0, 1, 2].map(|i| mesh.positions()[t[i].pos]); + (b - a).cross(c - a).magnitude() / 2.0 + }) + .sum(); + // The triangles cover the face's boundary polygon, the parts on both sides of the pinch. + let polygon = area2(&boundary).abs() / 2.0; + assert!((area - polygon).abs() < 1e-5, "at {tol}: triangles cover {area}, the boundary {polygon}"); + } +} + +/// The union of #1648: the sphere touches the box's bottom edge at (2.5, 7.5, 17.5). +#[test] +fn sphere_touching_a_box_edge_unites_soundly() { + let a = sphere(Vec3::new(2.5, 15.0, 27.5), 12.5).unwrap(); + let b = box_solid(Vec3::new(0.0, 0.0, 17.5), Vec3::new(5.0, 7.5, 22.5)).unwrap(); + let union = boolean(&a, &b, BoolOp::Union).unwrap().unwrap(); + assert!(union.validity().is_empty(), "{:?}", union.validity()); + let size = union.size(); + for tol in [size * 1e-2, size * 2.5e-3, size * 6e-4] { + let faces: std::collections::HashSet = union.tessellate(tol).unwrap().tri_face.into_iter().collect(); + assert_eq!(faces.len(), union.face_count(), "at {tol}"); + } +} diff --git a/crates/kernel/tests/boolean_props.rs b/crates/kernel/tests/boolean_props.rs index 7fb11c31a..d6d67474a 100644 --- a/crates/kernel/tests/boolean_props.rs +++ b/crates/kernel/tests/boolean_props.rs @@ -312,9 +312,9 @@ fn generic_box_cylinder_intersect() { check(identity(&a, &b)); } -/// A sphere and a box on the grid: the union has a face that does not mesh. +/// A sphere and a box on the grid: the sphere touches the box's bottom edge, so the union has a +/// face pinched to a point there, which did not mesh (#1648). #[test] -#[ignore = "kernel bug, #1648"] fn grid_sphere_box_union_is_sound() { let a = Prim::Sph { at: [2.5, 15.0, 27.5], r: 12.5 }; let b = Prim::Box { at: [0.0, 0.0, 17.5], size: [5.0, 7.5, 5.0] }; diff --git a/tests/robustness/goldens.json b/tests/robustness/goldens.json index ac24656ea..c6c7c32e8 100644 --- a/tests/robustness/goldens.json +++ b/tests/robustness/goldens.json @@ -21,7 +21,7 @@ "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":5726.92956,"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":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}, "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}, @@ -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.974648,"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":24740.927218}, + "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}, "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}, @@ -143,6 +143,7 @@ {"reason":"#2247: a cut no longer splits the separate pieces of a body into bodies of their own, so these seeds keep one body (bodies N -> 1). The generator looks at the model, so after the first such cut some seeds build different steps: seed 33 joins and patterns a box instead of chamfering (volume 13858 -> 24911 mm3), seed 18 now builds (its hole pattern failed with no result), and seed 54 picks a shell that fails the same way on main before #2247 (offset corner). Every step passes the validity and volume-direction checks.","seeds":[7,9,12,16,18,22,27,31,33,45,50,54,67,72,81,93]}, {"reason":"Reseam rotationally symmetric drill cutters after failed cuts (#2387): seed 86 now drills its hole, so its following pattern, shell and sphere cut complete with the fuzz validity and material checks.","seeds":[86]}, {"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":"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]} ] } diff --git a/vendor/README.md b/vendor/README.md index cc622f620..600e40be3 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -190,6 +190,14 @@ Changes: 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 direction left undivided along the rulings of a face ruled one way also gets a grid line diff --git a/vendor/truck-meshalgo/src/tessellation/triangulation.rs b/vendor/truck-meshalgo/src/tessellation/triangulation.rs index 0d28b316b..1428376c9 100644 --- a/vendor/truck-meshalgo/src/tessellation/triangulation.rs +++ b/vendor/truck-meshalgo/src/tessellation/triangulation.rs @@ -881,8 +881,9 @@ impl PolyBoundary { .unwrap_or(false) } - /// Inserts points and adds constraint into triangulation. - fn insert_to(&self, triangulation: &mut Cdt) { + /// 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() @@ -894,6 +895,7 @@ impl PolyBoundary { .collect(); let mut prev: Option = None; let mut counter = 0; + let mut complete = true; self.0 .iter() .map(Vec::len) @@ -915,13 +917,63 @@ impl PolyBoundary { if triangulation.can_add_constraint(vi, vj) { triangulation.add_constraint(vi, vj); } else { + complete = false; prev = Some(i); } } }); + 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]) -> Option>> { + if loops.iter().map(Vec::len).sum::() > MAX_PINCH_POINTS { + return None; + } + let mut extra: Vec>> = 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; + } + } + extra.sort_by(|a, b| a.0.total_cmp(&b.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 spade_round(x: f64) -> f64 { match f64::abs(x) < MIN_ALLOWED_VALUE { true => 0.0, @@ -963,7 +1015,17 @@ pub(super) fn preview_face(surface: &S, loops: &[Vec

(surface: &S, polyboundary: &PolyBoundary, tol: Deflection, cap: usize, steps: Option) -> PolygonMesh { let mut triangulation = Cdt::new(); - polyboundary.insert_to(&mut triangulation); + // 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); + } + } insert_surface(&mut triangulation, surface, polyboundary, tol, cap, steps); let mut mesh = triangulation_into_polymesh( triangulation.vertices(), From ae2ab87b9901eeb1117856c8f818abab4ec129b0 Mon Sep 17 00:00:00 2001 From: Artem Sushchev Date: Tue, 20 Oct 2026 10:30:13 +0000 Subject: [PATCH 183/225] Cut: a body with a sealed void no longer comes out empty (#3175) truck placed a face that no intersection divides (every face of a shell that meets nothing of the other) by counting the faces a ray crosses, taking each face's surface as stored. A revolved body's reversed faces counted the wrong way, and an inward shell (a void, a cut's inverted tool) was read as a solid: a cut beside a sealed void came out empty, refused or, with a tool whose bounding box covers the target, taken with the body gone. Intersections of such bodies came out empty as well. In an AND the crossings now count as each face is oriented, and an inward shell holds what lies outside it. An OR keeps truck's count. The corrected cut let a folded offset through: an arc edge next to a face it meets tangentially had its ends moved past its middle, and the arc went the long way round (robustness seed 73's shell). The offset refuses an arc whose middle crossed its chord, as it does a straight edge that turned round. Goldens: seeds 0, 45 and 77 had a cut refused as empty that now takes what it should; their volumes are checked by hand in the PR. --- crates/engine/src/boolean_regression_tests.rs | 59 +++++++++++++++++ crates/kernel/src/offset.rs | 7 +++ tests/robustness/goldens.json | 9 +-- vendor/README.md | 6 ++ .../src/transversal/integrate/mod.rs | 63 ++++++++++++------- 5 files changed, 119 insertions(+), 25 deletions(-) diff --git a/crates/engine/src/boolean_regression_tests.rs b/crates/engine/src/boolean_regression_tests.rs index 1cacb72b6..1ecbe4773 100644 --- a/crates/engine/src/boolean_regression_tests.rs +++ b/crates/engine/src/boolean_regression_tests.rs @@ -1032,3 +1032,62 @@ fn replay_value(script: &Value) -> Session { s.run_script(script).unwrap(); s } + +/// A revolved cylinder (r 24) with a sealed spherical void (r 2) on its axis, cut over its bottom +/// edge. The cut came out empty: refused for a box tool, and taken silently, the body gone, for a +/// large rotated box whose bounding box covers the target. Both keep the body and its void, and an +/// intersection with the box keeps the segment. +#[test] +fn cut_beside_a_sealed_void_keeps_the_body() { + use std::f64::consts::PI; + let r: f64 = 24.0; + // The circle's segment beyond a chord at `d` from the centre, and its integral over `d`. + let segment = |d: f64| r * r * (d / r).acos() - d * (r * r - d * d).sqrt(); + let wedge = |d: f64| r * r * (d * (d / r).acos() - (r * r - d * d).sqrt()) + (r * r - d * d).powf(1.5) / 3.0; + let sphere = 4.0 / 3.0 * PI * 8.0; + let combine = |z: [f64; 2], tool: &[(&str, Value)], operation: &str| { + let mut s = Session::default(); + s.execute("sketch.create", &json!({"plane": "YZ"})).unwrap(); + s.execute("sketch.rectangle.two_point", &json!({"p0": [0, z[0]], "p1": [r, z[1]]})).unwrap(); + s.execute("sketch.finish", &json!({})).unwrap(); + s.execute("solid.revolve", &json!({"axis": "y", "operation": "new", "body_name": "B"})).unwrap(); + let mid = (z[0] + z[1]) / 2.0; + s.execute("solid.sphere", &json!({"radius": 2, "center": [0, 0, mid], "operation": "new", "body_name": "V"})).unwrap(); + s.execute("solid.combine", &json!({"target": "B", "tools": ["V"], "operation": "cut"})).unwrap(); + for (command, params) in tool { + s.execute(command, params).unwrap(); + } + s.execute("solid.combine", &json!({"target": "B", "tools": ["K"], "operation": operation})).unwrap_or_else(|e| panic!("{e}")); + let state = s.model.state(); + let body = &state.body("B").unwrap().body; + assert_eq!(body.shell_count(), if operation == "cut" { 2 } else { 1 }); + assert!(body.validity().is_empty(), "{:?}", body.validity()); + // The revolved side's mesh stays 0.3 mm³ under its cylinder at any finer tolerance. + body.tessellate(1e-5).unwrap().measure().volume + }; + // A box over the bottom edge: the segment beyond x = 15, 5 high. + let edge_box = [("solid.box", json!({"length": 15, "width": 60, "height": 10, "corner": [15, -30, -5], "operation": "new", "body_name": "K"}))]; + let got = combine([0.0, 60.0], &edge_box, "cut"); + let want = PI * r * r * 60.0 - sphere - 5.0 * segment(15.0); + println!("box beside a void: {got:.6} mm³, expected {want:.6}"); + assert!((got - want).abs() < 1e-5 * want, "{got} vs {want}"); + let got = combine([0.0, 60.0], &edge_box, "intersect"); + let want = 5.0 * segment(15.0); + println!("box beside a void, intersected: {got:.6} mm³, expected {want:.6}"); + assert!((got - want).abs() < 1e-5 * want, "{got} vs {want}"); + // A 600 mm box rotated 45° about Y, its face on x - z = 116: the wedge beyond chords from + // x = 10 (z = -106) to x = 24 (z = -92). + let shift = (300.0 + 116.0 / 2f64.sqrt()) / 2f64.sqrt(); + let got = combine( + [-106.0, -43.5], + &[ + ("solid.box", json!({"length": 600, "width": 600, "height": 600, "center": [0, 0, 0], "operation": "new", "body_name": "K"})), + ("solid.move", json!({"bodies": ["K"], "axis": [0, 1, 0], "angle": -45})), + ("solid.move", json!({"bodies": ["K"], "translate": [shift, 0, -shift]})), + ], + "cut", + ); + let want = PI * r * r * 62.5 - sphere - (wedge(r) - wedge(10.0)); + println!("rotated box beside a void: {got:.6} mm³, expected {want:.6}"); + assert!((got - want).abs() < 1e-5 * want, "{got} vs {want}"); +} diff --git a/crates/kernel/src/offset.rs b/crates/kernel/src/offset.rs index b5ef68c79..264b82387 100644 --- a/crates/kernel/src/offset.rs +++ b/crates/kernel/src/offset.rs @@ -1090,6 +1090,13 @@ pub(crate) fn offset_body(b: &Body, shift: impl Fn(usize, Vec3) -> f64) -> Resul let (o, s, n) = pick(fs); let m2 = move_point(m, &o, &s, &n, size * 1e-6).ok_or_else(|| fail("an edge whose faces don't meet the same way after the move"))?; + // An arc turned round: its ends moved past its middle (next to a face it meets + // tangentially), so the arc through them goes the long way round its circle. + let (a0, c0, a1, c1) = + (from_p3(e.absolute_front().point()), from_p3(e.absolute_back().point()), from_p3(a.point()), from_p3(c.point())); + if (m - a0).cross(c0 - a0).dot((m2 - a1).cross(c1 - a1)) < 0.0 { + return Err(fail("not supported yet: the move is larger than a wall or step is thick (faces would cross)")); + } builder::circle_arc(a, c, p3(m2)) } }; diff --git a/tests/robustness/goldens.json b/tests/robustness/goldens.json index c6c7c32e8..1c882fbd0 100644 --- a/tests/robustness/goldens.json +++ b/tests/robustness/goldens.json @@ -1,7 +1,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":4785.573759,"bodies":1,"edges":78,"error":null,"faces":29,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","hole","circular pattern","circular pattern","cut sphere","join cylinder","cut cylinder","fillet"],"unsupported":1,"volume":13461.708496}, + "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}, "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}, @@ -46,7 +46,7 @@ "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}, "44": {"area":7972.435566,"bodies":1,"edges":36,"error":null,"faces":15,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","shell","cut sphere"],"unsupported":0,"volume":7622.184366}, - "45": {"area":14203.130789,"bodies":1,"edges":60,"error":"boolean Union: implausible result volume ","faces":29,"outcome":"failed","rejected":0,"shells":3,"steps":["revolved section","join cylinder","fillet","shell","cut box","join box"],"unsupported":1,"volume":14081.565595}, + "45": {"area":14308.150092,"bodies":1,"edges":63,"error":"boolean Union: implausible result volume ","faces":30,"outcome":"failed","rejected":0,"shells":3,"steps":["revolved section","join cylinder","fillet","shell","hole","cut box","join box"],"unsupported":0,"volume":13544.638725}, "46": {"area":3445.162934,"bodies":1,"edges":99,"error":null,"faces":31,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","join cylinder","hole","cut cylinder","rectangular pattern","cut box","cut cylinder"],"unsupported":0,"volume":6232.317935}, "47": {"area":3098.575625,"bodies":1,"edges":42,"error":null,"faces":16,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","fillet","cut sphere","fillet"],"unsupported":0,"volume":8834.297438}, "48": {"area":9651.031297,"bodies":1,"edges":66,"error":null,"faces":28,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","hole","circular pattern","join box","shell","cut box"],"unsupported":2,"volume":7044.773463}, @@ -78,7 +78,7 @@ "74": {"area":9294.57311,"bodies":1,"edges":18,"error":null,"faces":9,"outcome":"ok","rejected":0,"shells":1,"steps":["box","hole"],"unsupported":0,"volume":55866.183074}, "75": {"area":7890.438301,"bodies":1,"edges":31,"error":null,"faces":13,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","cut cylinder","chamfer","rectangular pattern","rectangular pattern","cut box"],"unsupported":0,"volume":38753.33959}, "76": {"area":853.668183,"bodies":1,"edges":32,"error":null,"faces":14,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","chamfer","cut cylinder"],"unsupported":1,"volume":1680.708844}, - "77": {"area":10824.299347,"bodies":1,"edges":60,"error":null,"faces":26,"outcome":"ok","rejected":3,"shells":1,"steps":["revolved section","fillet","cut cylinder","rectangular pattern","cut box","cut cylinder"],"unsupported":1,"volume":57744.413197}, + "77": {"area":9671.786688,"bodies":1,"edges":42,"error":null,"faces":19,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","fillet","hole","circular pattern","rectangular pattern","circular pattern"],"unsupported":0,"volume":63910.630446}, "78": {"area":2423.235496,"bodies":1,"edges":34,"error":"offset: a corner whose faces don't meet the same way after t","faces":14,"outcome":"failed","rejected":0,"shells":1,"steps":["revolved section","cut cylinder","cut box","shell"],"unsupported":0,"volume":3707.429306}, "79": {"area":13585.252616,"bodies":1,"edges":27,"error":null,"faces":12,"outcome":"ok","rejected":0,"shells":1,"steps":["box","cut cylinder","join cylinder"],"unsupported":0,"volume":104810.763072}, "80": {"area":8652.533342,"bodies":1,"edges":20,"error":null,"faces":9,"outcome":"ok","rejected":0,"shells":1,"steps":["box","fillet","fillet"],"unsupported":0,"volume":37387.449469}, @@ -144,6 +144,7 @@ {"reason":"Reseam rotationally symmetric drill cutters after failed cuts (#2387): seed 86 now drills its hole, so its following pattern, shell and sphere cut complete with the fuzz validity and material checks.","seeds":[86]}, {"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":"#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]} ] } diff --git a/vendor/README.md b/vendor/README.md index 600e40be3..726783874 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -45,6 +45,12 @@ Changes: operand's shell meshes made beforehand (copied for each use, since the loops stores cut their edges): a large body cut down to the regions of many small ones is meshed once, which was most of each operation's time. +- `transversal/integrate/mod.rs`: in an AND, a face no intersection divides (a shell that meets + nothing of the other) is placed by the crossings of a ray with the other shell counted as each + face is oriented, not by its surface alone, and an inward shell (a void, a cut's inverted tool) + holds what lies outside it. Faces with reversed surfaces (a revolved body's) counted the wrong + way, and a void dropped every face outside it: a cut beside a sealed void came out empty or + with the body gone. An OR keeps truck's count. ## truck-geometry 0.5.0 (Apache-2.0, © RICOS Co. Ltd., https://github.com/ricosjp/truck) diff --git a/vendor/truck-shapeops/src/transversal/integrate/mod.rs b/vendor/truck-shapeops/src/transversal/integrate/mod.rs index d0f9c750b..3d9e4f796 100644 --- a/vendor/truck-shapeops/src/transversal/integrate/mod.rs +++ b/vendor/truck-shapeops/src/transversal/integrate/mod.rs @@ -61,12 +61,40 @@ pub fn meshes, S: ShapeOpsSurface>(solid: &Solid Option { + let mut volume = 0.0; + for face in shell.face_iter() { + let v = face.surface()?.volume(); + volume += if face.orientation() { v } else { -v }; + } + Some(volume < 0.0) +} + +/// SolidCraft: whether `pt` is inside the closed `shell`, by the faces a ray from it crosses. +/// For an AND (`and`) each face counts as it is oriented, and a shell facing inward (`inward`, +/// see [`faces_inward`]) holds what lies outside it: the crossings count 0 there and -1 inside. +/// An OR keeps truck's count, by the faces' surfaces alone: it folds a solid's voids in as if +/// they were solids of their own, which is no union with voids whichever way they are counted. +fn inside_shell(shell: &MeshedShell, pt: Point3, and: bool, inward: bool) -> Option { + let dir = hash::take_one_unit(pt); + let mut count = 0; + for face in shell.face_iter() { + let sign = if face.orientation() || !and { 1 } else { -1 }; + count += sign * face.surface()?.signed_crossing_faces(pt, dir); + } + Some(if inward { count >= 0 } else { count >= 1 }) +} + fn process_one_pair_of_shells, S: ShapeOpsSurface>( shell0: &Shell, meshed0: Option<&MeshedShell>, shell1: &Shell, tol: f64, lineage: &mut Lineage, + and: bool, ) -> Option<[Shell; 2]> { nonpositive_tolerance!(tol); // SolidCraft: robust meshing (boundaries from earlier operations lie on surfaces only @@ -86,15 +114,11 @@ fn process_one_pair_of_shells, S: ShapeOpsSurface>( let mut cls1 = crate::tr!(divide_face::divide_faces(shell1, &loops_store1, tol, lineage), "divide faces 1"); cls1.integrate_by_component(); let [mut and0, mut or0, unknown0] = cls0.and_or_unknown(); + let inward1 = and && !unknown0.is_empty() && faces_inward(&poly_shell1)?; unknown0.into_iter().try_for_each(|face| { // SolidCraft: no panics (wasm can't catch them). let pt = face.boundaries().first()?.vertex_iter().next()?.point(); - let dir = hash::take_one_unit(pt); - let count = poly_shell1.iter().try_fold(0, |count, face| { - let poly = face.surface()?; - Some(count + poly.signed_crossing_faces(pt, dir)) - })?; - if count >= 1 { + if inside_shell(&poly_shell1, pt, and, inward1)? { and0.push(face); } else { or0.push(face); @@ -102,15 +126,11 @@ fn process_one_pair_of_shells, S: ShapeOpsSurface>( Some(()) })?; let [mut and1, mut or1, unknown1] = cls1.and_or_unknown(); + let inward0 = and && !unknown1.is_empty() && faces_inward(&poly_shell0)?; unknown1.into_iter().try_for_each(|face| { // SolidCraft: no panics (wasm can't catch them). let pt = face.boundaries().first()?.vertex_iter().next()?.point(); - let dir = hash::take_one_unit(pt); - let count = poly_shell0.iter().try_fold(0, |count, face| { - let poly = face.surface()?; - Some(count + poly.signed_crossing_faces(pt, dir)) - })?; - if count >= 1 { + if inside_shell(&poly_shell0, pt, and, inward0)? { and1.push(face); } else { or1.push(face); @@ -128,7 +148,7 @@ pub fn and, S: ShapeOpsSurface>( solid1: &Solid, tol: f64, ) -> Option> { - boolean(solid0, None, solid1, tol, |[and, _]| and).map(|(solid, _)| solid) + boolean(solid0, None, solid1, tol, true).map(|(solid, _)| solid) } /// OR operation between two solids. @@ -137,7 +157,7 @@ pub fn or, S: ShapeOpsSurface>( solid1: &Solid, tol: f64, ) -> Option> { - boolean(solid0, None, solid1, tol, |[_, or]| or).map(|(solid, _)| solid) + boolean(solid0, None, solid1, tol, false).map(|(solid, _)| solid) } /// SolidCraft: AND operation between two solids, with where each face and edge of the result @@ -149,7 +169,7 @@ pub fn and_with_history, S: ShapeOpsSurface>( solid1: &Solid, tol: f64, ) -> Option<(Solid, Option)> { - boolean(solid0, None, solid1, tol, |[and, _]| and) + boolean(solid0, None, solid1, tol, true) } /// SolidCraft: [`and_with_history`] with `solid0` meshed already ([`meshes`] of it, or of a @@ -160,7 +180,7 @@ pub fn and_with_history_meshed, S: ShapeOpsSurface>( solid1: &Solid, tol: f64, ) -> Option<(Solid, Option)> { - boolean(solid0, Some(meshed0), solid1, tol, |[and, _]| and) + boolean(solid0, Some(meshed0), solid1, tol, true) } /// SolidCraft: OR operation between two solids, with where each face and edge of the result @@ -172,28 +192,29 @@ pub fn or_with_history, S: ShapeOpsSurface>( solid1: &Solid, tol: f64, ) -> Option<(Solid, Option)> { - boolean(solid0, None, solid1, tol, |[_, or]| or) + boolean(solid0, None, solid1, tol, false) } /// Combines the operands' first shells, then folds in their other shells one at a time -/// (`pick` chooses the AND or the OR shell of each pass). The history is `None` when a face or +/// (`and` chooses the AND or the OR shell of each pass). The history is `None` when a face or /// edge of the result was not recorded; the result stands without it. fn boolean, S: ShapeOpsSurface>( solid0: &Solid, meshed0: Option<&[MeshedShell]>, solid1: &Solid, tol: f64, - pick: fn([Shell; 2]) -> Shell, + and: bool, ) -> Option<(Solid, Option)> { + let pick = |[and_shell, or_shell]: [Shell; 2]| if and { and_shell } else { or_shell }; let mut lineage = Lineage::new([solid0, solid1]); let mut iter0 = solid0.boundaries().iter(); let mut iter1 = solid1.boundaries().iter(); let shell0 = iter0.next()?; let shell1 = iter1.next()?; let meshed0 = meshed0.filter(|m| m.len() == solid0.boundaries().len()).and_then(|m| m.first()); - let mut shell = pick(crate::tr!(process_one_pair_of_shells(shell0, meshed0, shell1, tol, &mut lineage), "first shells")); + let mut shell = pick(crate::tr!(process_one_pair_of_shells(shell0, meshed0, shell1, tol, &mut lineage, and), "first shells")); for other in iter0.chain(iter1) { - shell = pick(crate::tr!(process_one_pair_of_shells(&shell, None, other, tol, &mut lineage), "another shell")); + shell = pick(crate::tr!(process_one_pair_of_shells(&shell, None, other, tol, &mut lineage, and), "another shell")); } let solid = crate::tr!(Solid::try_new(components_in_order(&shell)).ok(), "result solid"); let history = lineage.history(&solid); From 953fd7d5f8fed25d2fcda2d2ad1130c377ddf768 Mon Sep 17 00:00:00 2001 From: Matthew Knutson Date: Tue, 20 Oct 2026 10:45:08 +0000 Subject: [PATCH 184/225] Typed parameter contracts and JSON Schemas for solid.box and solid.extrude (#2829) (#2611) * Spike: typed parameter contracts and JSON Schemas for solid.box and solid.extrude The schema RFC's spike (plan/schema-spike.md). solid.box and solid.extrude get typed contracts with generated JSON Schemas (2020-12), checked in front of the unchanged handlers by a per-session level: off (the default, which changes nothing), warn (the call runs and gains param_warnings) or strict (the call is refused and the design left alone). Also engine.describe and the MCP tool describe_command, `solidcraft-cli mcp --param-check off|warn|strict`, a FeatureResult type for feature replies, and an env-var audit recorder (SOLIDCRAFT_PARAM_AUDIT) used to check the contracts against every test. Local spike branch; not for upstream as is (see the results report). Co-Authored-By: Claude Opus 5.5 * Parameter contracts: put the audit recorder behind a feature; drop two ignored test keys The audit recorder is now on only in a build with the engine's `param-audit` feature and `SOLIDCRAFT_PARAM_AUDIT` set. Its code is still compiled, linted and tested without the feature. `scripts/param_audit.py` summarises a test run's audit logs, and the schema module's docs give the steps for converting a further command. Two tests passed keys their command ignores, which the audit found: `position` on `solid.box` (`hole_face_tests.rs`) and `symmetric` on `solid.extrude` (`face_tests.rs`). Both are removed, so the tests build what they always did. Comments no longer call the contracts a spike. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: bherbruck --- Cargo.lock | 75 +++ Cargo.toml | 3 + apps/solidcraft-cli/src/main.rs | 42 +- apps/solidcraft-cli/tests/mcp_param_check.rs | 50 ++ assets/locales/en.json | 1 + assets/locales/ja.json | 1 + assets/locales/zh.json | 1 + crates/engine/Cargo.toml | 7 + crates/engine/src/cmd/face_tests.rs | 2 +- crates/engine/src/cmd/features.rs | 32 +- crates/engine/src/cmd/inspect.rs | 24 + crates/engine/src/cmd/mod.rs | 21 +- crates/engine/src/hole_face_tests.rs | 2 +- crates/engine/src/lib.rs | 24 +- crates/engine/src/schema/check.rs | 270 ++++++++ crates/engine/src/schema/commands.rs | 220 +++++++ crates/engine/src/schema/mod.rs | 54 ++ crates/engine/src/schema/record.rs | 96 +++ crates/engine/src/schema/record_wasm.rs | 12 + crates/engine/src/schema/tests.rs | 633 +++++++++++++++++++ crates/engine/src/schema/types.rs | 585 +++++++++++++++++ crates/mcp/src/server.rs | 2 +- crates/mcp/src/tests.rs | 24 +- crates/mcp/src/tools.rs | 12 + crates/ui-egui/src/agent_chat/gate.rs | 3 +- docs/mcp.md | 21 +- scripts/param_audit.py | 88 +++ 27 files changed, 2279 insertions(+), 26 deletions(-) create mode 100644 apps/solidcraft-cli/tests/mcp_param_check.rs create mode 100644 crates/engine/src/schema/check.rs create mode 100644 crates/engine/src/schema/commands.rs create mode 100644 crates/engine/src/schema/mod.rs create mode 100644 crates/engine/src/schema/record.rs create mode 100644 crates/engine/src/schema/record_wasm.rs create mode 100644 crates/engine/src/schema/tests.rs create mode 100644 crates/engine/src/schema/types.rs create mode 100644 scripts/param_audit.py diff --git a/Cargo.lock b/Cargo.lock index 38e204204..1df6cfe09 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1175,6 +1175,12 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" +[[package]] +name = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + [[package]] name = "ecolor" version = "0.36.2" @@ -3514,6 +3520,26 @@ dependencies = [ "bitflags 2.13.2", ] +[[package]] +name = "ref-cast" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + [[package]] name = "regex-syntax" version = "0.8.11" @@ -3741,6 +3767,31 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "schemars" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e" +dependencies = [ + "dyn-clone", + "ref-cast", + "schemars_derive", + "serde", + "serde_json", +] + +[[package]] +name = "schemars_derive" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1c3a92094fa7d61aa124645844facb6b554dfc797136d0f5fd1f890e2bffc69" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals", + "syn 3.0.6", +] + [[package]] name = "scoped-tls" version = "1.0.1" @@ -3860,6 +3911,17 @@ dependencies = [ "syn 3.0.6", ] +[[package]] +name = "serde_derive_internals" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f852137cce035d6a4df67ccce505ff6b3e9fd3a10e3e52b24dc71e650bb1a9bd" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + [[package]] name = "serde_json" version = "1.0.151" @@ -3873,6 +3935,17 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + [[package]] name = "serde_repr" version = "0.1.21" @@ -4164,8 +4237,10 @@ name = "solidcraft-engine" version = "0.16.2" dependencies = [ "log", + "schemars", "serde", "serde_json", + "serde_path_to_error", "solidcraft-doc", "solidcraft-geom", "solidcraft-io", diff --git a/Cargo.toml b/Cargo.toml index fa02d7829..a4cecf4f3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,6 +36,9 @@ proc-macro2 = "1" quote = "1" syn = { version = "2", features = ["full"] } serde_json = { version = "1", features = ["float_roundtrip"] } +# command parameter and result schemas +schemars = "1.2" +serde_path_to_error = "0.1" log = "0.4" sha2 = "0.10" moxcms = { version = "0.8.1", default-features = false, features = ["extended_range"] } diff --git a/apps/solidcraft-cli/src/main.rs b/apps/solidcraft-cli/src/main.rs index 5be417c49..dec00af12 100644 --- a/apps/solidcraft-cli/src/main.rs +++ b/apps/solidcraft-cli/src/main.rs @@ -13,6 +13,7 @@ //! solidcraft-cli recipe translate an oracle recipe to a script //! solidcraft-cli oracle ... replay recipes and compare with expected.json //! solidcraft-cli mcp [--in design|script] [--connect HOST:PORT [--token T]] [--allow-path DIR]... [--allow-any-path] +//! [--param-check off|warn|strict] //! MCP server on stdio (docs/mcp.md) //! solidcraft-cli licences SolidCraft's licence and the third-party licences //! solidcraft-cli icon --out F.png|F.ico [--size N] the app icon (packaging; drawn, not a file) @@ -71,6 +72,7 @@ const USAGE: &str = "usage: solidcraft-cli oracle ... [--json] solidcraft-cli fuzz [--from N] [--count N] [--jobs J] [--timeout S] [--steps N] [--minimise] [--out DIR] [--report FILE] solidcraft-cli mcp [--in design.solidcraft|script.json] [--connect 127.0.0.1:PORT [--token T]] [--allow-path DIR]... [--allow-any-path] + [--param-check off|warn|strict] solidcraft-cli crashes [list [--json] | show | replay | dir | clear []] solidcraft-cli licences solidcraft-cli gpu [--policy auto|hardware|software|cpu] @@ -154,7 +156,14 @@ pub fn read_json(path: &str) -> Result { /// A session from a design file, a STEP/3MF/STL file, a command script, or an oracle recipe. pub fn load(path: &str) -> Result { + load_checked(path, solidcraft_engine::schema::ParamCheck::Off) +} + +/// `load`, with scripts and recipes run at the parameter-check level `check`, which the +/// session keeps. +fn load_checked(path: &str, check: solidcraft_engine::schema::ParamCheck) -> Result { let mut s = Session::default(); + s.param_check = check; if solidcraft_engine::io::is_step_path(path) || solidcraft_engine::io::is_mesh_path(path) { s.execute("doc.open", &json!({"path": path})).map_err(|e| e.to_string())?; return Ok(s); @@ -164,16 +173,22 @@ pub fn load(path: &str) -> Result { let doc = solidcraft_engine::io::read_design(&bytes).map_err(|e| format!("{path}: {e}"))?; let mut session = Session::new(doc); session.path = Some(path.to_owned()); + session.param_check = check; return Ok(session); } let v: Value = serde_json::from_slice(&bytes).map_err(|e| format!("{path}: {e}"))?; if v.get("format").and_then(Value::as_str).is_some_and(|f| solidcraft_engine::doc::format::version_of(f).is_some()) { s.execute("doc.open", &json!({"path": path})).map_err(|e| e.to_string())?; - } else if v.get("features").is_some() && v.get("commands").is_none() { - let script = recipe::to_script(&v)?; - s.run_script(&script).map_err(|e| e.to_string())?; } else { - s.run_script(&v).map_err(|e| e.to_string())?; + let script = if v.get("features").is_some() && v.get("commands").is_none() { recipe::to_script(&v)? } else { v }; + // Warn level: each step's `param_warnings` as it completes, even when a later step fails + // (stderr, so stdout stays the caller's). + let mut warn = |step: usize, r: &Value| { + for w in r.get("param_warnings").and_then(Value::as_array).into_iter().flatten() { + eprintln!("{path}: step {}: {}", step + 1, w.as_str().unwrap_or_default()); + } + }; + s.run_script_each(&script, &mut warn).map_err(|e| e.to_string())?; } Ok(s) } @@ -536,6 +551,17 @@ fn cmd_mcp(args: &[String]) -> Result<(), String> { eprintln!("solidcraft mcp: the design's folder is left out because {why}; add it with --allow-path if you mean it"); } } + // How a headless session treats calls that break a command's parameter contract (docs/mcp.md). + let param_check = match flag(args, "--param-check") { + None if args.iter().any(|a| a == "--param-check") => return Err("mcp: --param-check wants off, warn or strict".into()), + None => solidcraft_engine::schema::ParamCheck::Off, + Some(v) => { + solidcraft_engine::schema::ParamCheck::parse(v).ok_or_else(|| format!("mcp: --param-check wants off, warn or strict, not `{v}`"))? + } + }; + if param_check != solidcraft_engine::schema::ParamCheck::Off && flag(args, "--connect").is_some() { + eprintln!("solidcraft mcp: --param-check applies to headless sessions; calls to the app are not checked yet"); + } let backend: Box = match (flag(args, "--connect"), flag(args, "--in")) { (Some(_), Some(_)) => return Err("mcp: use either --connect or --in, not both".into()), (Some(addr), None) => { @@ -552,8 +578,12 @@ fn cmd_mcp(args: &[String]) -> Result<(), String> { } Box::new(remote) } - (None, Some(path)) => Box::new(solidcraft_mcp::Headless::new(load(path)?)), - (None, None) => Box::new(solidcraft_mcp::Headless::default()), + (None, Some(path)) => Box::new(solidcraft_mcp::Headless::new(load_checked(path, param_check)?)), + (None, None) => { + let mut headless = solidcraft_mcp::Headless::default(); + headless.session.param_check = param_check; + Box::new(headless) + } }; let stdin = std::io::stdin(); let stdout = std::io::stdout(); diff --git a/apps/solidcraft-cli/tests/mcp_param_check.rs b/apps/solidcraft-cli/tests/mcp_param_check.rs new file mode 100644 index 000000000..0dab92924 --- /dev/null +++ b/apps/solidcraft-cli/tests/mcp_param_check.rs @@ -0,0 +1,50 @@ +//! `mcp --in script --param-check `: the level applies to the script the session starts +//! from too, so a misspelled key in it is refused (strict) or reported on stderr (warn) instead of +//! silently ignored. + +use std::process::{Command, Stdio}; + +#[test] +fn param_check_applies_to_the_starting_script() { + let dir = std::env::temp_dir().join(format!("solidcraft-mcp-param-check-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let script = dir.join("typo.json"); + let box_ = r#"{"command": "solid.box", "params": {"length": 5, "width": 5, "height": 5, "operaton": "cut"}}"#; + std::fs::write(&script, format!(r#"{{"commands": [{box_}]}}"#)).unwrap(); + let run = |level: &str| { + Command::new(env!("CARGO_BIN_EXE_solidcraft-cli")) + .args(["mcp", "--in", script.to_str().unwrap(), "--param-check", level]) + .stdin(Stdio::null()) + .output() + .unwrap() + }; + let strict = run("strict"); + let stderr = String::from_utf8_lossy(&strict.stderr); + assert!(!strict.status.success(), "{stderr}"); + assert!(stderr.contains("unknown key `operaton`; did you mean `operation`?"), "{stderr}"); + // Warn: the script runs, and its warnings go to stderr. + let warn = run("warn"); + let stderr = String::from_utf8_lossy(&warn.stderr); + assert!(warn.status.success(), "{stderr}"); + assert!(stderr.contains("step 1: unknown key `operaton`; did you mean `operation`?"), "{stderr}"); + // A warned step's warning is printed even when a later step fails. + let failing = dir.join("typo_then_failure.json"); + std::fs::write(&failing, format!(r#"{{"commands": [{box_}, {{"command": "no.such_command"}}]}}"#)).unwrap(); + let out = Command::new(env!("CARGO_BIN_EXE_solidcraft-cli")) + .args(["mcp", "--in", failing.to_str().unwrap(), "--param-check", "warn"]) + .stdin(Stdio::null()) + .output() + .unwrap(); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(!out.status.success(), "{stderr}"); + assert!(stderr.contains("step 1: unknown key `operaton`") && stderr.contains("step 2"), "{stderr}"); + // Off: the script runs as before, and the server ends with its input. + let off = run("off"); + assert!(off.status.success(), "{}", String::from_utf8_lossy(&off.stderr)); + assert!(!String::from_utf8_lossy(&off.stderr).contains("operaton")); + // A bare flag is an error, not off. + let bare = Command::new(env!("CARGO_BIN_EXE_solidcraft-cli")).args(["mcp", "--param-check"]).stdin(Stdio::null()).output().unwrap(); + assert!(!bare.status.success()); + assert!(String::from_utf8_lossy(&bare.stderr).contains("--param-check wants off, warn or strict")); + std::fs::remove_dir_all(&dir).ok(); +} diff --git a/assets/locales/en.json b/assets/locales/en.json index 1419c4bb2..77c030df3 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -422,6 +422,7 @@ "cmd.edit_checkpoint": "Checkpoint", "cmd.edit_restore_checkpoint": "Restore Checkpoint", "cmd.engine_commands": "List Commands", + "cmd.engine_describe": "Describe Command", "cmd.explode_create": "Exploded View", "cmd.explode_delete": "Delete Exploded View", "cmd.explode_list": "List Exploded Views", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 09499f014..d6f0ace30 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -422,6 +422,7 @@ "cmd.edit_checkpoint": "チェックポイント", "cmd.edit_restore_checkpoint": "チェックポイントを復元", "cmd.engine_commands": "コマンドを一覧表示", + "cmd.engine_describe": "コマンドの詳細を表示", "cmd.explode_create": "分解図", "cmd.explode_delete": "分解図を削除", "cmd.explode_list": "分解図を一覧表示", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index cee0926dd..f236bdb8d 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -422,6 +422,7 @@ "cmd.edit_checkpoint": "检查点", "cmd.edit_restore_checkpoint": "恢复检查点", "cmd.engine_commands": "列出命令", + "cmd.engine_describe": "描述命令", "cmd.explode_create": "爆炸图", "cmd.explode_delete": "删除爆炸图", "cmd.explode_list": "列出爆炸图", diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 58ab39c2a..3080f1b8c 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -17,6 +17,13 @@ solidcraft-io = { workspace = true } solidcraft-render = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } +schemars = { workspace = true } +serde_path_to_error = { workspace = true } thiserror = { workspace = true } log = { workspace = true } web-time = { workspace = true } + +[features] +# Turns on the parameter-contract audit recorder (`SOLIDCRAFT_PARAM_AUDIT`, see +# `src/schema/record.rs`), for checking a new contract against the whole test suite. +param-audit = [] diff --git a/crates/engine/src/cmd/face_tests.rs b/crates/engine/src/cmd/face_tests.rs index 5ff74c3a3..73c02e39b 100644 --- a/crates/engine/src/cmd/face_tests.rs +++ b/crates/engine/src/cmd/face_tests.rs @@ -260,7 +260,7 @@ fn join_keeps_exact_face_attachments_from_both_operands() { run(&mut s, "sketch.create", json!({"plane":"YZ"})); run(&mut s, "sketch.circle.center", json!({"center":[0,20],"radius":5})); run(&mut s, "sketch.finish", json!({})); - run(&mut s, "solid.extrude", json!({"distance":20,"symmetric":true,"operation":"join"})); + run(&mut s, "solid.extrude", json!({"distance":20,"operation":"join"})); run(&mut s, "sketch.create", json!({"plane":{"face":[0,0,40]}})); run(&mut s, "sketch.circle.center", json!({"center":[0,0],"radius":4})); run(&mut s, "sketch.finish", json!({})); diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs index ec9d9748e..ceba6a01d 100644 --- a/crates/engine/src/cmd/features.rs +++ b/crates/engine/src/cmd/features.rs @@ -11,13 +11,19 @@ use solidcraft_geom::Vec3; use super::{CommandSpec, not_in_sketch}; use crate::params::{bad, bool_, expr, req_expr, str_, string_list, vec2, vec3}; +use crate::schema::{BoxParams, ExtrudeParams, FeatureResult, TypedContract, output_schema_for}; use crate::{EngineError, Result, Session}; +const BOX_CONTRACT: TypedContract = TypedContract::new(); +const EXTRUDE_CONTRACT: TypedContract = TypedContract::new(); + pub static COMMANDS: &[CommandSpec] = &[ - CommandSpec::new("solid.extrude", "Extrude", extrude) + CommandSpec::new("solid.extrude", "Extrude", crate::checked!("solid.extrude", EXTRUDE_CONTRACT, extrude)) .at("SOLID", "CREATE") .icon("extrude") .key("E") + .contract(&EXTRUDE_CONTRACT) + .output(output_schema_for::) .params("distance: expr (or through_all: true); taper?: angle expr; sketch?: id|name (default: active or last sketch); profiles?: all | [index] | [{curves: [ids]}] (the profile whose outer loop is made of exactly these curves, or pieces of them; found again on every recompute, so it follows parameter changes; islands inside are its holes; an error when no profile or several match) | [{point:[x,y]}] (index and point picks are stored by their curves when that finds the same profile); face?: [x,y,z] (extrude a planar body face instead of a sketch profile); faces?: [[x,y,z],…] (coplanar faces of one body); face_body?: name (whose face, where faces of several bodies meet at the point); direction?: positive|negative|symmetric (distance is total thickness, split evenly around the start plane); convention?: total_distance|legacy_per_side (default total_distance; legacy preserves older symmetric extents); distance2?: expr (Two Sides: a second distance the other way from the first side, which may be through_all or to; with direction: negative the first side goes against the normal and distance2 along it); start_offset?: expr (along the sketch normal, also with direction: negative); to?: [x,y,z] (To Object: a face, vertex or point; to_offset?: expr past it); from?: [x,y,z] (From Object: start at that face or point); operation?: new|join|cut|intersect|auto (cut into a body, otherwise join existing solids; new in an empty component); targets?: [body] (Join from a face, or from a sketch on a body's face, defaults to that face's body; explicit targets or participants override); name?; body_name?; thin?: true (Thin: a wall along sketch curves instead of the profiles) with curves?: [curve ids] (open chains and closed loops, joined where they meet end to end; default: every drawn curve of the sketch), thickness: expr, side?: center|inside|outside|two_sides (a closed loop's inside is the area it encloses, an open chain's the side it bends toward, a straight line's the left of its first curve as drawn; default center), thickness2?: expr (two_sides: the thickness outside); corners are mitred, crossing walls are one"), CommandSpec::new("solid.revolve", "Revolve", revolve) .at("SOLID", "CREATE") @@ -28,7 +34,12 @@ pub static COMMANDS: &[CommandSpec] = &[ .icon("sweep") .params("sketch: profile sketch; profiles?; path_sketch: sketch; path: [curve ids in order]; orientation?: perpendicular (default: square to the path, turning with it) | parallel (as drawn: the profile moves without turning; the path must keep crossing its plane) | [x,y,z] (square to the path, its turn about the path fixed by this direction); twist?: angle expr (the profile turns this much about the path over its length; within 4 turns); scale?: expr (the profile's scale at the end, linear along the path; 0.01…100); rails?: [{sketch?: sketch (default path_sketch), curves: [curve ids in order]}] (guide rails, one or two, each meeting every plane square to the path once along it, from the end nearest the path's start: one rail turns the profile so its point where the rail starts stays on the rail and scales it with the rail's distance from the path; two rails carry it between them, its points where they start staying on both; rails take the default orientation, no twist and no scale, and a path without sharp corners); rail_fit?: scale (default: the profile grows and shrinks evenly) | stretch (only across to the rail, between the rails); operation?, targets?, name?, body_name?"), CommandSpec::new("solid.loft", "Loft", loft).at("SOLID", "CREATE").icon("loft").params("sections: [{sketch, profiles?} | {sketch, point: id} (an apex)] (2…50, in order; matching hole counts, no holes at an apex); rails?: [{sketch, curves: [ids in order]}] (one or two guide rails from the first section to the last, through every section's outline: the loft follows them between the sections; not with sections that have holes); rail_fit?: scale|stretch (default scale: with one rail the sections grow evenly with the rail's distance from their middle, with two with the distance between the rails; stretch: only that way); operation?, targets?, name?, body_name?"), - CommandSpec::new("solid.box", "Box", prim_box).at("SOLID", "CREATE").icon("box").params("length, width, height: expr; corner?: [x,y,z] | center?: [x,y,z] (numbers in mm or length expressions; default: the origin); operation?, targets?: [body], name?, body_name?"), + CommandSpec::new("solid.box", "Box", crate::checked!("solid.box", BOX_CONTRACT, prim_box)) + .at("SOLID", "CREATE") + .icon("box") + .contract(&BOX_CONTRACT) + .output(output_schema_for::) + .params("length, width, height: expr; corner?: [x,y,z] | center?: [x,y,z] (numbers in mm or length expressions; default: the origin); operation?, targets?: [body], name?, body_name?"), CommandSpec::new("solid.cylinder", "Cylinder", prim_cylinder).at("SOLID", "CREATE").icon("cylinder").params("radius | diameter, height: expr; base?: [x,y,z] (centre of the bottom: numbers in mm or length expressions; default: the origin); axis?: X|Y|Z|[x,y,z] (default Z); operation?, targets?: [body], name?, body_name?"), CommandSpec::new("solid.sphere", "Sphere", prim_sphere).at("SOLID", "CREATE").icon("sphere").params("radius | diameter: expr; center?: [x,y,z] (numbers in mm or length expressions; default: the origin); operation?, targets?: [body], name?, body_name?"), CommandSpec::new("solid.torus", "Torus", prim_torus).at("SOLID", "CREATE").icon("torus").params("major, minor: expr (radii); center?: [x,y,z] (numbers in mm or length expressions; default: the origin); operation?, targets?: [body], name?, body_name?"), @@ -334,7 +345,7 @@ pub(super) fn stable_profiles(s: &Session, kind: &mut FeatureKind) -> Result<()> Ok(()) } -pub(super) fn profiles(p: &Value, cmd: &str) -> Result { +pub(crate) fn profiles(p: &Value, cmd: &str) -> Result { let Some(v) = p.get("profiles") else { return Ok(ProfileSel::All) }; match v { Value::Object(fields) => { @@ -560,8 +571,19 @@ fn add_feature_in(s: &mut Session, p: &Value, kind: FeatureKind, world: bool) -> // A warning (a Boolean that needed a retry, a reference found again elsewhere) is part of // the reply: a script or an agent sees it without asking the timeline (#616). let warning = r.as_ref().and_then(|r| r.warning.clone()); - Ok(json!({"feature": id, "name": fname, "bodies": bodies, "created_bodies": created, "changed_bodies": changed, - "removed_bodies": removed, "warning": warning, "ms": r.map(|r| r.ms)})) + let owned = |names: Vec<&str>| names.into_iter().map(str::to_string).collect(); + let reply = FeatureResult { + feature: id, + name: fname, + bodies: owned(bodies), + created_bodies: owned(created), + changed_bodies: owned(changed), + removed_bodies: owned(removed), + warning, + ms: r.map(|r| r.ms), + param_warnings: Vec::new(), + }; + serde_json::to_value(reply).map_err(|e| EngineError::Other(e.to_string())) } fn extrude(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/inspect.rs b/crates/engine/src/cmd/inspect.rs index fc82f8864..db25052dc 100644 --- a/crates/engine/src/cmd/inspect.rs +++ b/crates/engine/src/cmd/inspect.rs @@ -44,6 +44,13 @@ pub static COMMANDS: &[CommandSpec] = &[ .doc_only() .params("→ the built-in materials, then the design's own (user: true, with their look)"), CommandSpec::new("engine.commands", "List Commands", commands).icon("list").noundo(), + CommandSpec::new("engine.describe", "Describe Command", crate::checked!("engine.describe", DESCRIBE_CONTRACT, describe)) + .icon("list") + .noundo() + .doc_only() + .contract(&DESCRIBE_CONTRACT) + .output(crate::schema::output_schema_for::) + .params("command: a command id. Returns {id, label, params, input, output} (and param_warnings in the warn parameter-check mode): the command's parameter documentation and, once the command has a typed contract, the JSON Schemas (2020-12) of its parameters and of a successful result (null otherwise). Read-only."), ]; pub fn measure_json(b: &solidcraft_doc::ModelBody) -> Value { @@ -319,6 +326,23 @@ fn model_faces(s: &mut Session, p: &Value) -> Result { Ok(json!({"body": b.name, "faces": faces})) } +const DESCRIBE_CONTRACT: crate::schema::TypedContract = crate::schema::TypedContract::new(); + +/// A command's prose documentation and, for converted commands, its schemas. +fn describe(_s: &mut Session, p: &Value) -> Result { + let id = p.get("command").and_then(Value::as_str).ok_or_else(|| crate::params::bad("engine.describe", "`command` must be a command id"))?; + let spec = super::find_command(id).ok_or_else(|| crate::EngineError::UnknownCommand(id.to_string()))?; + let reply = crate::schema::DescribeResult { + id: spec.id.to_string(), + label: spec.label.to_string(), + params: spec.params.to_string(), + input: spec.contract.map(|c| c.input_schema().to_value()), + output: spec.output.map(|f| f().to_value()), + param_warnings: Vec::new(), + }; + serde_json::to_value(reply).map_err(|e| crate::EngineError::Other(e.to_string())) +} + fn commands(s: &mut Session, _p: &Value) -> Result { Ok(Value::Array(crate::command_specs().iter().map(|c| serde_json::to_value(c.info(s)).unwrap_or_default()).collect())) } diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index 864bf7827..9e8f0623e 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -35,6 +35,7 @@ mod edit; mod face; mod features; mod features_more; +pub(crate) use features::profiles as feature_profiles; pub use features::{auto_operation, extrude_reach}; pub use sketch_modify::trim_piece; mod component_link; @@ -96,6 +97,7 @@ pub type Run = fn(&mut Session, &Value) -> Result; /// evaluate as usual). pub type LiveRun = fn(&mut Session, &Value) -> Result<(Value, Option)>; pub type Enabled = fn(&Session) -> std::result::Result<(), String>; +pub type SchemaFn = fn() -> schemars::Schema; pub struct CommandSpec { pub id: &'static str, @@ -120,6 +122,11 @@ pub struct CommandSpec { pub reads_model: bool, /// Registered but not built yet (see `planned!`): the GitHub issue number that tracks it. pub planned: Option<&'static str>, + /// The command's typed parameter contract, which carries its input schema; `None` until + /// the command is converted (see `crate::schema`). + pub contract: Option<&'static dyn crate::schema::Contract>, + /// The JSON Schema of a successful result; `None` until described. + pub output: Option, } impl CommandSpec { @@ -138,6 +145,8 @@ impl CommandSpec { live: None, reads_model: true, planned: None, + contract: None, + output: None, } } /// Not built yet; `issue` tracks building it. @@ -168,6 +177,16 @@ impl CommandSpec { self.shortcut = Some(k); self } + /// The command's typed parameter contract (see `crate::schema`). + pub const fn contract(mut self, c: &'static dyn crate::schema::Contract) -> Self { + self.contract = Some(c); + self + } + /// The JSON Schema of a successful result. + pub const fn output(mut self, f: SchemaFn) -> Self { + self.output = Some(f); + self + } pub const fn params(mut self, p: &'static str) -> Self { self.params = p; self @@ -325,7 +344,7 @@ pub(crate) fn did_you_mean(id: &str) -> String { } /// Levenshtein distance: the single-character edits that turn `a` into `b`. -fn edit_distance(a: &str, b: &str) -> usize { +pub(crate) fn edit_distance(a: &str, b: &str) -> usize { let b: Vec = b.chars().collect(); let mut row: Vec = (0..=b.len()).collect(); for (i, ca) in a.chars().enumerate() { diff --git a/crates/engine/src/hole_face_tests.rs b/crates/engine/src/hole_face_tests.rs index 43d6499e1..ededdd431 100644 --- a/crates/engine/src/hole_face_tests.rs +++ b/crates/engine/src/hole_face_tests.rs @@ -92,7 +92,7 @@ fn a_slanted_hole_stays_on_its_axis_when_its_face_moves() { // part: a 40 x 40 x 20 box at z 0..20 (32000 mm³). fn box_part(s: &mut Session) { - run(s, "solid.box", json!({"length": 40, "width": 40, "height": 20, "name": "Part", "position": [20, 20, 0]})); + run(s, "solid.box", json!({"length": 40, "width": 40, "height": 20, "name": "Part"})); } /// A sketch named `Pts` on the XY plane lifted to `z`, holding the given points (ids p0, p1, ...). diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 9f1fc0bba..a11fba4af 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -20,6 +20,7 @@ pub mod product_scene; pub mod recovery; pub mod render_jobs; pub mod sample; +pub mod schema; mod slicer_icon; pub mod slicers; pub mod timing; @@ -230,6 +231,9 @@ pub struct Session { pub revision: u64, /// Project a face's edges into a sketch created on it (the default; `sketch.auto_project`). pub auto_project: bool, + /// How calls that break a command's parameter contract are treated (off by default). It + /// belongs to the session, not the design, so it survives opening and starting designs. + pub param_check: schema::ParamCheck, /// The component new sketches and features go into (0 = the root). pub active_component: u64, /// The placement used when authoring shared component geometry. @@ -374,6 +378,7 @@ impl Session { log: Vec::new(), revision: 1, auto_project: true, + param_check: schema::ParamCheck::Off, active_component: 0, active_occurrence_path: None, pending_moves: Default::default(), @@ -403,10 +408,12 @@ impl Session { /// are the user's rather than the design's: `auto_project` is a preference (#680). pub fn replace_design(&mut self, fresh: Session) { let auto_project = self.auto_project; + let param_check = self.param_check; let render_viewport = self.render_viewport.clone(); let render_jobs = self.render_jobs.scratch(); *self = fresh; self.auto_project = auto_project; + self.param_check = param_check; self.render_viewport = render_viewport; self.render_jobs = render_jobs; } @@ -846,6 +853,7 @@ impl Session { log: Vec::new(), revision: self.revision, auto_project: self.auto_project, + param_check: self.param_check, active_component: self.active_component, active_occurrence_path: self.active_occurrence_path.clone(), pending_moves: self.pending_moves.clone(), @@ -976,18 +984,24 @@ impl Session { /// Run a script: a JSON array of `{"command": id, "params": {...}}` (or an object with a /// `commands` array). Stops at the first error. Returns each command's result. pub fn run_script(&mut self, script: &Value) -> Result> { - Ok(self.run_script_with(script, None)?.0) + Ok(self.run_script_with(script, None, &mut |_, _| {})?.0) + } + + /// [`Session::run_script`], calling `each(index, result)` as each command succeeds, so a + /// caller sees the steps before a later one fails. + pub fn run_script_each(&mut self, script: &Value, each: &mut dyn FnMut(usize, &Value)) -> Result> { + Ok(self.run_script_with(script, None, each)?.0) } /// [`Session::run_script`], timing each command (#1833): the results and /// `{"timings": [{"index", "command", "ms", "profile"?}], "total_ms"}`, with `profile` the /// kernel's share of each command ([`timing`]). pub fn run_script_timed(&mut self, script: &Value, profile: bool) -> Result<(Vec, Value)> { - let (results, timings) = self.run_script_with(script, Some(profile))?; + let (results, timings) = self.run_script_with(script, Some(profile), &mut |_, _| {})?; Ok((results, timings.unwrap_or(Value::Null))) } - fn run_script_with(&mut self, script: &Value, profile: Option) -> Result<(Vec, Option)> { + fn run_script_with(&mut self, script: &Value, profile: Option, each: &mut dyn FnMut(usize, &Value)) -> Result<(Vec, Option)> { let list = match script { Value::Array(a) => a.clone(), Value::Object(o) => { @@ -1016,7 +1030,9 @@ impl Session { } None => self.execute(id, &p), }; - out.push(r.map_err(|e| EngineError::Other(format!("step {} ({id}): {e}", i + 1)))?); + let r = r.map_err(|e| EngineError::Other(format!("step {} ({id}): {e}", i + 1)))?; + each(i, &r); + out.push(r); } let timings = profile.map(|_| serde_json::json!({"timings": steps, "total_ms": timing::round_ms(clock.ms())})); Ok((out, timings)) diff --git a/crates/engine/src/schema/check.rs b/crates/engine/src/schema/check.rs new file mode 100644 index 000000000..a98883e84 --- /dev/null +++ b/crates/engine/src/schema/check.rs @@ -0,0 +1,270 @@ +//! Contracts, the unknown-key check and the adapter that runs a converted command. + +use std::any::TypeId; +use std::collections::{BTreeSet, HashMap}; +use std::marker::PhantomData; +use std::sync::{Arc, Mutex, OnceLock}; + +use schemars::generate::SchemaSettings; +use schemars::{JsonSchema, Schema}; +use serde::de::DeserializeOwned; +use serde_json::{Map, Value, json}; + +use super::record; +use crate::cmd::Run; +use crate::params::bad; +use crate::{Result, Session}; + +/// How a session treats calls that break a command's contract. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum ParamCheck { + /// Nothing is checked; commands behave as they always have. + #[default] + Off, + /// The call runs, and a successful object result gains `param_warnings`. + Warn, + /// The call is refused, and nothing runs. + Strict, +} + +impl ParamCheck { + pub fn parse(s: &str) -> Option { + match s.trim().to_ascii_lowercase().as_str() { + "off" => Some(ParamCheck::Off), + "warn" => Some(ParamCheck::Warn), + "strict" => Some(ParamCheck::Strict), + _ => None, + } + } +} + +/// The JSON Schema (2020-12) of what deserializes into `T`: a command's parameters. +pub fn input_schema_for() -> Schema { + SchemaSettings::draft2020_12().for_deserialize().into_generator().into_root_schema_for::() +} + +/// The JSON Schema (2020-12) of what `T` serializes to: a command's result. +pub fn output_schema_for() -> Schema { + SchemaSettings::draft2020_12().for_serialize().into_generator().into_root_schema_for::() +} + +/// One way a call breaks a contract. +#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct Issue { + /// Where: a top-level key (each field type reads its whole value); empty for the whole call. + pub path: String, + /// The message, in the engine's style (without the `invalid parameters for …` prefix). + pub message: String, + /// For an unknown key, the closest key the command takes. + pub suggestion: Option, +} + +/// A command's typed parameter contract. +pub trait Contract: Sync { + /// The parameters' JSON Schema. + fn input_schema(&self) -> Schema; + /// The top-level keys the command takes. + fn allowed_keys(&self) -> Arc>; + /// Unknown keys and badly shaped parameters in `params`, without running anything. + fn check(&self, params: &Value) -> Vec; +} + +/// The contract "the parameters deserialize into `P`". Stateless; `fn() -> P` keeps it +/// `Send + Sync` whatever `P` is. +pub struct TypedContract

(PhantomData P>); + +impl

TypedContract

{ + pub const fn new() -> Self { + TypedContract(PhantomData) + } +} + +impl

Default for TypedContract

{ + fn default() -> Self { + Self::new() + } +} + +/// Allowed keys per contract type, worked out once from its schema. +static KEYS: OnceLock>>>> = OnceLock::new(); + +impl Contract for TypedContract

{ + fn input_schema(&self) -> Schema { + input_schema_for::

() + } + + fn allowed_keys(&self) -> Arc> { + let keys = KEYS.get_or_init(Default::default); + let mut keys = keys.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + keys.entry(TypeId::of::

()).or_insert_with(|| Arc::new(schema_keys(input_schema_for::

().as_value()))).clone() + } + + fn check(&self, params: &Value) -> Vec { + let object = match params { + // `Session::execute` reads `null` as `{}`. + Value::Null => return Vec::new(), + Value::Object(o) => o, + _ => return vec![Issue { path: String::new(), message: "parameters must be an object".into(), suggestion: None }], + }; + let mut issues = unknown_keys(object, &self.allowed_keys()); + if let Err(e) = serde_path_to_error::deserialize::<_, P>(params) { + issues.push(parse_issue(&e)); + } + issues + } +} + +/// The most keys of one call that are looked at, and the longest key given a suggestion. +const MAX_KEYS: usize = 64; +const MAX_KEY_LEN: usize = 64; +const MAX_MESSAGE_LEN: usize = 300; +const MAX_WHOLE_LEN: usize = 4096; + +/// Marks a deserializer's message as complete as it is (a handler's own wording, such as +/// ``unknown operation `bogus` (…)``), so [`parse_issue`] doesn't put the key in front. +const WHOLE: char = '\u{1}'; + +/// `message`, marked as complete (see [`WHOLE`]). +pub(crate) fn whole(message: impl std::fmt::Display) -> String { + format!("{WHOLE}{message}") +} + +/// The top-level property names of a schema, following `allOf`/`anyOf`/`oneOf` and `$ref`s +/// into the root's `$defs`. +pub(crate) fn schema_keys(root: &Value) -> BTreeSet { + fn walk(root: &Value, node: &Value, out: &mut BTreeSet, depth: usize) { + if depth > 16 { + return; + } + if let Some(props) = node.get("properties").and_then(Value::as_object) { + out.extend(props.keys().cloned()); + } + for k in ["allOf", "anyOf", "oneOf"] { + for branch in node.get(k).and_then(Value::as_array).into_iter().flatten() { + walk(root, branch, out, depth + 1); + } + } + if let Some(name) = node.get("$ref").and_then(Value::as_str).and_then(|r| r.strip_prefix("#/$defs/")) + && let Some(target) = root.get("$defs").and_then(|d| d.get(name)) + { + walk(root, target, out, depth + 1); + } + } + let mut out = BTreeSet::new(); + walk(root, root, &mut out, 0); + out +} + +/// The keys of `params` that `allowed` doesn't list, each with the closest allowed key. +fn unknown_keys(params: &Map, allowed: &BTreeSet) -> Vec { + let mut issues: Vec = params + .keys() + .take(MAX_KEYS) + .filter(|k| !allowed.contains(*k)) + .map(|k| { + let suggestion = nearest(k, allowed); + // A hostile key is cut, so errors and warnings stay small. + let k = truncate(k, MAX_KEY_LEN); + let message = match &suggestion { + Some(s) => format!("unknown key `{k}`; did you mean `{s}`?"), + None => format!("unknown key `{k}`"), + }; + Issue { path: k, message, suggestion } + }) + .collect(); + if params.len() > MAX_KEYS { + issues.push(Issue { path: String::new(), message: format!("too many parameters ({}; at most {MAX_KEYS})", params.len()), suggestion: None }); + } + issues +} + +/// `s` cut to at most `max` bytes, on a character boundary, with `…` when cut. +pub(crate) fn truncate(s: &str, max: usize) -> String { + if s.len() <= max { + return s.to_string(); + } + let mut end = max; + while end > 0 && !s.is_char_boundary(end) { + end -= 1; + } + format!("{}…", s.get(..end).unwrap_or_default()) +} + +/// The allowed key closest to `key`, when it is close enough to be a likely typo. Keys are +/// short, so short keys may be one edit away at most (`x` is not a typo of `to`). +fn nearest(key: &str, allowed: &BTreeSet) -> Option { + if key.len() > MAX_KEY_LEN { + return None; + } + let key = key.to_ascii_lowercase(); + let near = (key.chars().count() / 3).max(1); + allowed + .iter() + .map(|a| (crate::cmd::edit_distance(&key, &a.to_ascii_lowercase()), a)) + .filter(|(d, _)| *d <= near) + .min_by_key(|(d, _)| *d) + .map(|(_, a)| a.clone()) +} + +/// A deserialization failure as an issue, in the engine's style. +fn parse_issue(e: &serde_path_to_error::Error) -> Issue { + let path = e.path().to_string(); + let path = if path == "." { String::new() } else { path }; + let inner = e.inner().to_string(); + if let Some(complete) = inner.strip_prefix(WHOLE) { + // The handler's own message, which names the caller's value: in full up to a generous + // cap, since the contract also checks keys the handler ignores (`side` without `thin`). + return Issue { path, message: truncate(complete, MAX_WHOLE_LEN), suggestion: None }; + } + let message = if let Some(field) = inner.strip_prefix("missing field `").and_then(|r| r.split('`').next()) { + let at = if path.is_empty() { field.to_string() } else { format!("{path}.{field}") }; + return Issue { path: at.clone(), message: format!("`{at}` is required"), suggestion: None }; + } else if path.is_empty() { + inner + } else if inner.starts_with("must ") { + format!("`{path}` {inner}") + } else if let Some((_, expected)) = inner.strip_prefix("invalid type: ").and_then(|r| r.rsplit_once(", expected ")) { + // serde's wording for the plain types, in the engine's (`thin` must be true or false). + let expected = match expected { + "a boolean" => "true or false", + "a string" => "text", + other => other, + }; + format!("`{path}` must be {expected}") + } else { + format!("`{path}`: {inner}") + }; + // serde quotes the caller's value, which may be long. + Issue { path, message: truncate(&message, MAX_MESSAGE_LEN), suggestion: None } +} + +/// Run `handler` as the command `id`, checking the call against `contract` as the session's +/// [`ParamCheck`] level asks (see the module docs). With the level off and no audit recorder, +/// this is exactly `handler(s, p)`. +pub fn run_checked(s: &mut Session, p: &Value, id: &str, contract: &dyn Contract, handler: Run) -> Result { + let level = s.param_check; + let recording = record::enabled(); + if level == ParamCheck::Off && !recording { + return handler(s, p); + } + let issues = contract.check(p); + if level == ParamCheck::Strict + && let Some(first) = issues.first() + { + if recording { + record::note(id, &issues, None, p); + } + return Err(bad(id, first.message.clone())); + } + let result = handler(s, p); + if recording && !issues.is_empty() { + record::note(id, &issues, Some(&result), p); + } + match result { + Ok(Value::Object(mut o)) if level == ParamCheck::Warn && !issues.is_empty() => { + o.insert("param_warnings".into(), json!(issues.iter().map(|i| i.message.as_str()).collect::>())); + Ok(Value::Object(o)) + } + other => other, + } +} diff --git a/crates/engine/src/schema/commands.rs b/crates/engine/src/schema/commands.rs new file mode 100644 index 000000000..c9d7920d0 --- /dev/null +++ b/crates/engine/src/schema/commands.rs @@ -0,0 +1,220 @@ +//! The converted commands' parameter contracts and result types. +//! +//! Field doc comments are the schemas' descriptions. Keys the handlers read only in some +//! situations (`sketch` without `face`, the thin-wall keys with `thin: true`) are optional +//! fields whose descriptions say so; the contracts don't check the combinations, and the +//! handlers ignore those keys otherwise. + +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use super::types::{ + AngleExpr, ConventionParam, DirectionParam, ExtentKeyword, ExtrudeOperation, FacesParam, FromPoint, IdOrName, LengthExpr, OperationParam, Point3, + PointExpr3, ProfilesParam, StringList, ThinSideParam, ToPoint, present, +}; + +/// Add a box primitive. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct BoxParams { + /// Size along X. + pub length: LengthExpr, + /// Size along Y. + pub width: LengthExpr, + /// Size along Z. + pub height: LengthExpr, + /// The box's minimum corner. Default: the origin. When both `corner` and `center` are given, + /// `corner` is used. + #[serde(default, deserialize_with = "present")] + #[schemars(with = "PointExpr3")] + pub corner: Option, + /// The box's centre, instead of `corner`. + #[serde(default, deserialize_with = "present")] + #[schemars(with = "PointExpr3")] + pub center: Option, + /// How the box combines with existing bodies. Default: new. + #[serde(default)] + pub operation: Option, + /// The bodies a join, cut or intersect works on. Default: the bodies the box meets. + #[serde(default)] + pub targets: Option, + /// The bodies taking part (the same as `targets` for a primitive). + #[serde(default)] + pub participants: Option, + /// The feature's name in the timeline. + #[serde(default)] + pub name: Option, + /// The new body's name. + #[serde(default)] + pub body_name: Option, + /// Names for the new bodies, in order. + #[serde(default)] + pub body_names: Option, +} + +/// Extrude sketch profiles (or a planar body face) into a solid. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct ExtrudeParams { + /// How far: the length one way; with `direction: symmetric`, the total thickness (per side + /// with `convention: legacy_per_side`); with `distance2`, the first side's length. Required + /// unless `through_all` or `to` is given. + #[serde(default)] + pub distance: Option, + /// The sketch to extrude, by id or name. Default: the active sketch, else the last one. + /// Ignored when `face` is given. + #[serde(default, deserialize_with = "present")] + #[schemars(with = "IdOrName")] + pub sketch: Option, + /// Which of the sketch's profiles to extrude. Default: all of them. Ignored when `face` is + /// given; not allowed with `thin`. + #[serde(default, deserialize_with = "present")] + #[schemars(with = "ProfilesParam")] + pub profiles: Option, + /// A point on a planar body face to extrude instead of a sketch profile. + #[serde(default)] + pub face: Option, + /// Several coplanar faces of one body to extrude together, by a point on each. Not with + /// `face`, `sketch` or `profiles`. + #[serde(default, deserialize_with = "present")] + #[schemars(with = "FacesParam")] + pub faces: Option, + /// The body whose face to use, where faces of several bodies meet at `face` (or `faces`). + #[serde(default)] + pub face_body: Option, + /// With `face`, among placed instances: the body whose placement `face` is read in (read by + /// the engine's frame mapping, before the command runs). Default: `face_body`, else the + /// body nearest the point. + #[serde(default)] + pub body: Option, + /// Extrude through everything in the way. + #[serde(default)] + pub through_all: Option, + /// `"through_all"`, the same as `through_all: true`. + #[serde(default)] + pub extent: Option, + /// Draft angle of the side walls. + #[serde(default)] + pub taper: Option, + /// Which way to extrude. Default: positive. + #[serde(default)] + pub direction: Option, + /// Two Sides: a second distance the other way from the first side, which may be + /// `through_all` or `to`; with `direction: negative` the first side goes against the normal + /// and `distance2` along it. + #[serde(default)] + pub distance2: Option, + /// Start this far from the sketch plane, along its normal. + #[serde(default)] + pub start_offset: Option, + /// How a symmetric distance is read. Default: total_distance. + #[serde(default, deserialize_with = "present")] + #[schemars(with = "ConventionParam")] + pub convention: Option, + /// Extrude up to this face, vertex or point (To Object). + #[serde(default, deserialize_with = "present")] + #[schemars(with = "ToPoint")] + pub to: Option, + /// How far past `to` to go. + #[serde(default)] + pub to_offset: Option, + /// Start at this face or point (From Object). + #[serde(default, deserialize_with = "present")] + #[schemars(with = "FromPoint")] + pub from: Option, + /// How the extrusion combines with existing bodies. Default: new. + #[serde(default)] + pub operation: Option, + /// The bodies a join, cut or intersect works on. Default for a join from a body's face: + /// that body. + #[serde(default)] + pub targets: Option, + /// The bodies taking part; overrides the default scope. + #[serde(default)] + pub participants: Option, + /// The feature's name in the timeline. + #[serde(default)] + pub name: Option, + /// The new body's name. + #[serde(default)] + pub body_name: Option, + /// Names for the new bodies, in order. + #[serde(default)] + pub body_names: Option, + /// A thin wall along sketch curves instead of solid profiles. + // `skip_serializing_if` keeps schemars from writing `default: null`, which `bool` refuses. + #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")] + #[schemars(with = "bool")] + pub thin: Option, + /// With `thin`: the curves the wall follows. Default: every drawn curve of the sketch. + #[serde(default)] + pub curves: Option, + /// With `thin`: the wall's thickness. + #[serde(default)] + pub thickness: Option, + /// With `thin`: which side of the curves the wall lies on. Default: center. + #[serde(default)] + pub side: Option, + /// With `thin` and `side: two_sides`: the thickness outside. + #[serde(default)] + pub thickness2: Option, +} + +/// Which command to describe. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct DescribeParams { + /// The command's id, such as `solid.extrude`. + #[serde(deserialize_with = "command_id")] + pub command: String, +} + +/// A command id, with the `engine.describe` handler's message for anything else. +fn command_id<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + match Value::deserialize(d)? { + Value::String(s) => Ok(s), + _ => Err(serde::de::Error::custom("must be a command id")), + } +} + +/// What `engine.describe` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct DescribeResult { + pub id: String, + pub label: String, + /// The command's parameter documentation, as prose. + pub params: String, + /// The parameters' JSON Schema, or `null` when the command has no contract yet. + pub input: Option, + /// The successful result's JSON Schema, or `null` when not described yet. + pub output: Option, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// What a feature command returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct FeatureResult { + /// The new feature's id. + pub feature: u64, + /// The new feature's name. + pub name: String, + /// Every body after the feature. + pub bodies: Vec, + /// The bodies the feature made. + pub created_bodies: Vec, + /// Bodies that were there before and now have other geometry. + pub changed_bodies: Vec, + /// Bodies that are gone. + pub removed_bodies: Vec, + /// A warning from the evaluation (a Boolean that needed a retry, a reference found again + /// elsewhere), or `null`. + pub warning: Option, + /// How long the feature took to evaluate, in milliseconds. + pub ms: Option, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs new file mode 100644 index 000000000..3ca510527 --- /dev/null +++ b/crates/engine/src/schema/mod.rs @@ -0,0 +1,54 @@ +//! Typed parameter contracts for commands. +//! +//! A converted command declares a [`Contract`]: a Rust type its parameters must deserialize +//! into, from which the input JSON Schema is generated. The contract is checked *in front of* +//! the unchanged handler, which still reads the raw parameters, so a command's behaviour does +//! not change unless the session's [`ParamCheck`] level asks for warnings or refusals. +//! +//! - **Off** (the default): nothing is parsed or checked; the handler runs as before. +//! - **Warn**: the handler runs; a successful object result gains `param_warnings`. +//! - **Strict**: a call with an unknown key or a parameter of the wrong shape is refused, and +//! nothing runs. +//! +//! Unknown keys are the top-level keys a call sends that the contract's schema does not list. +//! Keys the engine reads around a command count too: `frames::to_local` reads `body` for +//! commands with picks (extrude's `face`), which the extrude contract declares; it otherwise +//! rewrites only keys a call already has. `live` is read only for commands with `.live(…)`, and +//! `timeline.redefine` adds only `convention` and `participants`, which the contracts declare. +//! +//! The shared field types in [`types`] decide acceptance by calling the same helpers the +//! handlers use (`params::vec3`, `params::expr`, `Operation::parse`, `features::profiles`…), so +//! "the contract accepts it" means "the handler's own reader accepts it". Where the handler is +//! more lenient (a value of the wrong type read as if the key were absent), the contract is the +//! stricter of the two; that difference is what warn and strict surface. +//! +//! To convert a command: declare its parameters type in `commands.rs` (and its reply type, for +//! an output schema), give its `CommandSpec` `checked!(…)`, `.contract(…)` and `.output(…)` as +//! `solid.extrude` does, and add it to `schemas_and_the_key_check_agree` and, for messages it +//! already gives, `strict_keeps_todays_errors`. Then run the whole test suite with the audit +//! recorder (see `record.rs`): a call that succeeds today but breaks the contract is either a +//! form the contract is missing or a caller's mistake. + +mod check; +mod commands; +#[cfg_attr(target_arch = "wasm32", path = "record_wasm.rs")] +mod record; +mod types; + +#[cfg(test)] +mod tests; + +pub use check::{Contract, Issue, ParamCheck, TypedContract, input_schema_for, output_schema_for, run_checked}; +pub use commands::{BoxParams, DescribeParams, DescribeResult, ExtrudeParams, FeatureResult}; +pub use types::*; + +/// A command's `run` that checks the call against `$contract` before running `$handler` +/// (see [`run_checked`]). Expands to a non-capturing closure, which coerces to the registry's +/// `Run` function pointer. +#[macro_export] +#[doc(hidden)] +macro_rules! checked { + ($id:literal, $contract:path, $handler:path) => { + |s: &mut $crate::Session, p: &serde_json::Value| $crate::schema::run_checked(s, p, $id, &$contract, $handler) + }; +} diff --git a/crates/engine/src/schema/record.rs b/crates/engine/src/schema/record.rs new file mode 100644 index 000000000..ed7894c39 --- /dev/null +++ b/crates/engine/src/schema/record.rs @@ -0,0 +1,96 @@ +//! The audit recorder, for checking a new contract against every caller the tests have: in a +//! build with the `param-audit` feature, when `SOLIDCRAFT_PARAM_AUDIT` names a directory, every +//! call to a command with a contract that breaks it is recorded, with what the command did, so a +//! test run shows which callers the contracts would warn about or refuse. Without the feature it +//! is compiled (so it is linted and tested) but never on. +//! +//! ```text +//! SOLIDCRAFT_PARAM_AUDIT=$PWD/audit cargo test --workspace --no-fail-fast --features solidcraft-engine/param-audit +//! python3 scripts/param_audit.py audit +//! ``` +//! +//! A line whose outcome is `ok` is a call that works today and that strict would refuse: a form +//! the contract is missing, or a mistake the handler silently ignores. +//! +//! Records are aggregated per process by signature (command, issues, outcome, test thread) and +//! written to `

/audit-.jsonl` when a signature is first seen and again each time its +//! count reaches a power of two; readers keep the highest `count` per signature in each file +//! and add the files up. A process keeps at most 4096 signatures and counts later new ones +//! under one `dropped` line. Writing never fails a command. + +use std::collections::HashMap; +use std::io::Write; +use std::path::PathBuf; +use std::sync::{Mutex, OnceLock}; + +use serde_json::{Value, json}; + +use super::check::{Issue, truncate}; +use crate::Result; + +static DIR: OnceLock> = OnceLock::new(); +static SEEN: OnceLock>> = OnceLock::new(); + +/// The most signatures a process keeps; later new ones are dropped, and one line says so. +const MAX_SIGNATURES: usize = 4096; + +fn dir() -> Option<&'static PathBuf> { + DIR.get_or_init(|| std::env::var_os("SOLIDCRAFT_PARAM_AUDIT").filter(|v| !v.is_empty()).map(PathBuf::from)).as_ref() +} + +/// Whether the recorder is on: built with `param-audit` and the variable set (read once per +/// process). +pub fn enabled() -> bool { + cfg!(feature = "param-audit") && dir().is_some() +} + +/// Count one more call with signature `key`. A new signature beyond `max` is counted under +/// one `dropped` entry instead. Returns whether it was dropped and the count, when the count is +/// a power of two (a line is due). +pub(crate) fn tally(seen: &mut HashMap, key: String, max: usize) -> Option<(bool, u64)> { + let dropped = seen.len() >= max && !seen.contains_key(&key); + let count = seen.entry(if dropped { "dropped".into() } else { key }).or_insert(0); + *count += 1; + count.is_power_of_two().then_some((dropped, *count)) +} + +/// One line of the audit file; `sample_params` is cut to 1 KB (empty for `null`). +pub(crate) fn line(command: &str, issues: &[impl serde::Serialize], outcome: &str, source: &str, count: u64, params: &Value) -> Value { + let sample = if params.is_null() { String::new() } else { truncate(¶ms.to_string(), 1024) }; + json!({"command": command, "issues": issues, "outcome": outcome, "source": source, "count": count, "sample_params": sample}) +} + +/// What a call did, for its audit line: `ok`, `error: …` from the handler, or `refused` when +/// strict refused it before the handler ran (`None`). +pub(crate) fn outcome_text(outcome: Option<&Result>) -> String { + match outcome { + None => "refused".to_string(), + Some(Ok(_)) => "ok".to_string(), + Some(Err(e)) => format!("error: {}", truncate(&e.to_string(), 200)), + } +} + +/// Record one call of `command` that broke its contract with `issues`, and what it did +/// (`None`: refused before the handler ran). +pub fn note(command: &str, issues: &[Issue], outcome: Option<&Result>, params: &Value) { + let Some(dir) = dir().filter(|_| enabled()) else { return }; + // A handler's own message names the caller's value, which may be long. + let mut messages: Vec = issues.iter().map(|i| truncate(&i.message, 300)).collect(); + messages.sort_unstable(); + messages.dedup(); + let outcome = outcome_text(outcome); + let source = std::thread::current().name().unwrap_or("unnamed").to_string(); + let key = json!([command, messages, outcome, source]).to_string(); + let seen = SEEN.get_or_init(Default::default); + // The lock is held while writing, so this process's lines never interleave. + let mut seen = seen.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let line = match tally(&mut seen, key, MAX_SIGNATURES) { + None => return, + Some((true, count)) => line("*", &["too many signatures; later new ones dropped"], "dropped", "*", count, &Value::Null), + Some((false, count)) => line(command, &messages, &outcome, &source, count, params), + }; + let path = dir.join(format!("audit-{}.jsonl", std::process::id())); + if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(path) { + let _ = f.write_all(format!("{line}\n").as_bytes()); + } +} diff --git a/crates/engine/src/schema/record_wasm.rs b/crates/engine/src/schema/record_wasm.rs new file mode 100644 index 000000000..32d618f1b --- /dev/null +++ b/crates/engine/src/schema/record_wasm.rs @@ -0,0 +1,12 @@ +//! The audit recorder is native-only; in the browser it is never on. + +use serde_json::Value; + +use super::check::Issue; +use crate::Result; + +pub fn enabled() -> bool { + false +} + +pub fn note(_command: &str, _issues: &[Issue], _outcome: Option<&Result>, _params: &Value) {} diff --git a/crates/engine/src/schema/tests.rs b/crates/engine/src/schema/tests.rs new file mode 100644 index 000000000..390c4eaab --- /dev/null +++ b/crates/engine/src/schema/tests.rs @@ -0,0 +1,633 @@ +use serde::de::DeserializeOwned; +use serde_json::{Value, json}; + +use super::check::schema_keys; +use super::*; +use crate::Session; + +fn parse(v: Value) -> Option { + serde_json::from_value(v).ok() +} + +fn box_contract() -> TypedContract { + TypedContract::new() +} + +fn messages(issues: &[Issue]) -> Vec { + issues.iter().map(|i| i.message.clone()).collect() +} + +#[test] +fn expressions_accept_what_params_expr_accepts() { + for v in [json!(5), json!(-2.5), json!("w / 2"), json!(" 30 mm "), json!(999_999_999.0)] { + let want = crate::params::expr(&json!({ "v": v.clone() }), "v"); + assert_eq!(parse::(v.clone()).map(|e| e.0), want, "{v}"); + assert!(want.is_some(), "{v}"); + } + let long = "x".repeat(4097); + // The cap is in bytes: 2049 two-byte characters are too long (the schema's maxLength counts + // characters, so it can't say this). + let wide = "é".repeat(2049); + for v in [json!(true), json!(null), json!(""), json!(" "), json!(1e9), json!(-1e9), json!([1]), json!({}), json!(long), json!(wide)] { + assert!(crate::params::expr(&json!({ "v": v.clone() }), "v").is_none(), "{v}"); + assert!(parse::(v.clone()).is_none(), "{v}"); + assert!(parse::(v.clone()).is_none(), "{v}"); + } +} + +#[test] +fn points_accept_what_the_point_readers_accept() { + assert!(parse::(json!([1, 2, 3])).is_some()); + assert!(parse::(json!({"x": 1, "y": 2, "z": 3, "label": "extra keys are fine"})).is_some()); + for v in [json!([1, 2]), json!([1, 2, 3, 4]), json!(["a", 2, 3]), json!(null), json!({"x": 1, "y": 2}), json!([1e9, 0, 0])] { + assert!(parse::(v.clone()).is_none(), "{v}"); + } + assert!(parse::(json!([1, 2])).is_some()); + assert!(parse::(json!([1, 2, 3])).is_none()); + assert!(parse::(json!([1, "w / 2", 3])).is_some()); + assert!(parse::(json!({"x": "a", "y": 0, "z": "b + 1"})).is_some()); + for v in [json!([1, 2]), json!(null), json!([true, 1, 2]), json!({"x": 1, "y": 2}), json!("origin")] { + assert!(parse::(v.clone()).is_none(), "{v}"); + } +} + +#[test] +fn names_and_lists() { + assert_eq!(parse::(json!("A")).map(|l| l.0), Some(vec!["A".to_string()])); + assert_eq!(parse::(json!(["A", "B"])).map(|l| l.0), Some(vec!["A".to_string(), "B".to_string()])); + let too_many: Vec<&str> = vec!["x"; 10_001]; + for v in [json!([1]), json!(5), json!(null), json!(too_many.clone())] { + assert!(parse::(v.clone()).is_none(), "{v}"); + } + let c = TypedContract::::new(); + assert_eq!(messages(&c.check(&json!({"distance": 5, "targets": too_many}))), vec!["`targets` must have at most 10000 items"]); + assert!(parse::(json!(3)).is_some()); + assert!(parse::(json!("Base")).is_some()); + assert!(parse::(json!(null)).is_none()); +} + +#[test] +fn operations_match_operation_parse() { + for s in [ + "new", + "join", + "cut", + "intersect", + "newbody", + "newcomponent", + "union", + "add", + "subtract", + "difference", + "intersection", + "New Body", + "NEW-body", + "Cut", + ] { + assert!(parse::(json!(s)).is_some(), "{s}"); + assert!(parse::(json!(s)).is_some(), "{s}"); + } + assert!(parse::(json!("auto")).is_none(), "box takes no auto"); + assert!(parse::(json!("AUTO")).is_some()); + assert!(parse::(json!(" auto")).is_none(), "auto is matched without trimming"); + for v in [json!("bogus"), json!(5), json!(null)] { + assert!(parse::(v.clone()).is_none(), "{v}"); + } +} + +#[test] +fn extrude_keywords() { + assert!(parse::(json!("SYMMETRIC")).is_some()); + assert!(parse::(json!("flip")).is_some()); + assert!(parse::(json!(" symmetric")).is_none(), "not trimmed"); + assert!(parse::(json!("Through_All")).is_some()); + assert!(parse::(json!("to_next")).is_none()); + assert!(parse::(json!("total_distance")).is_some()); + assert!(parse::(json!("Total_Distance")).is_none(), "serde, case-sensitive"); + assert!(parse::(json!(" Two-Sides ")).is_some(), "ThinSide::parse trims and maps '-'"); + assert!(parse::(json!("middle")).is_none()); +} + +#[test] +fn profiles_match_features_profiles() { + for v in [json!("all"), json!("ALL"), json!(0), json!([0, 1]), json!([{"point": [1, 2]}]), json!([["l1", "l2"]]), json!([{"curves": ["l1"]}])] { + assert!(parse::(v.clone()).is_some(), "{v}"); + } + for v in [json!("none"), json!([]), json!([true]), json!(null), json!(-1), json!([0, {"point": [1, 2]}])] { + assert!(parse::(v.clone()).is_none(), "{v}"); + } + let c = TypedContract::::new(); + let issue = |profiles: Value| messages(&c.check(&json!({"distance": 5, "profiles": profiles}))); + assert_eq!(issue(json!([])), vec!["`profiles` is empty"]); + assert_eq!(issue(json!(1.5)), vec!["`profiles` must be \"all\", an index or a list"]); + assert_eq!(issue(json!(vec![0; 10_001])), vec!["`profiles` must have at most 10000 items"]); +} + +#[test] +fn unknown_keys_get_suggestions() { + let c = box_contract(); + let issues = c.check(&json!({"length": 5, "width": 5, "height": 5, "operaton": "cut", "colour": "red"})); + assert_eq!(messages(&issues), vec!["unknown key `colour`", "unknown key `operaton`; did you mean `operation`?"]); + assert_eq!(issues.iter().find(|i| i.path == "operaton").and_then(|i| i.suggestion.clone()), Some("operation".into())); + // A hostile key is cut in the message. + let issues = c.check(&json!({"length": 5, "width": 5, "height": 5, "k".repeat(100_000): 1})); + assert_eq!(messages(&issues), vec![format!("unknown key `{}…`", "k".repeat(64))]); + // Short keys get a suggestion only one edit away. + let issues = TypedContract::::new().check(&json!({"distance": 5, "x": 1, "p0": 1, "ids": 1, "sid": "inside"})); + assert_eq!(messages(&issues), vec!["unknown key `ids`", "unknown key `p0`", "unknown key `sid`; did you mean `side`?", "unknown key `x`"]); +} + +#[test] +fn shape_problems_are_issues() { + let c = box_contract(); + assert_eq!(messages(&c.check(&json!({"width": 5, "height": 5}))), vec!["`length` is required"]); + assert_eq!(messages(&c.check(&json!({"length": true, "width": 5, "height": 5}))), vec!["`length` must be a number or an expression"]); + assert_eq!( + messages(&c.check(&json!({"length": 5, "width": 5, "height": 5, "corner": null}))), + vec!["`corner` must be a point [x, y, z] of numbers or length expressions"] + ); + assert_eq!(messages(&c.check(&json!({"length": 5, "width": 5, "height": 5, "name": 7}))), vec!["`name` must be text"]); + let e = TypedContract::::new(); + assert_eq!(messages(&e.check(&json!({"distance": 5, "thin": "true"}))), vec!["`thin` must be true or false"]); + // serde quotes the caller's value: split at the last ", expected ", and cap the message. + assert_eq!(messages(&e.check(&json!({"distance": 5, "through_all": "x, expected y"}))), vec!["`through_all` must be true or false"]); + let long = messages(&e.check(&json!({"distance": 5, "through_all": format!("{}, expected y", "a".repeat(100_000))}))); + assert_eq!(long, vec!["`through_all` must be true or false"]); + assert_eq!(messages(&c.check(&json!([1, 2, 3]))), vec!["parameters must be an object"]); + assert!(c.check(&json!(null)).is_empty(), "null is read as {{}}, which the handler then judges"); + let many: serde_json::Map = (0..70).map(|i| (format!("k{i}"), json!(1))).collect(); + assert!(messages(&c.check(&Value::Object(many))).iter().any(|m| m.starts_with("too many parameters"))); +} + +#[test] +fn schemas_and_the_key_check_agree() { + for (schema, fields) in [ + ( + input_schema_for::(), + vec!["body_name", "body_names", "center", "corner", "height", "length", "name", "operation", "participants", "targets", "width"], + ), + ( + input_schema_for::(), + vec![ + "body", + "body_name", + "body_names", + "convention", + "curves", + "direction", + "distance", + "distance2", + "extent", + "face", + "face_body", + "faces", + "from", + "name", + "operation", + "participants", + "profiles", + "side", + "sketch", + "start_offset", + "taper", + "targets", + "thickness", + "thickness2", + "thin", + "through_all", + "to", + "to_offset", + ], + ), + ] { + let v = schema.as_value(); + assert_eq!(schema_keys(v).into_iter().collect::>(), fields); + assert_eq!(v.get("additionalProperties"), Some(&json!(false)), "the schema refuses unknown keys too"); + assert_eq!(v.get("$schema").and_then(Value::as_str), Some("https://json-schema.org/draft/2020-12/schema")); + } +} + +#[test] +fn present_null_is_refused_but_absent_is_fine() { + let base = json!({"length": 5, "width": 5, "height": 5}); + assert!(box_contract().check(&base).is_empty()); + let c: TypedContract = TypedContract::new(); + assert!(c.check(&json!({"distance": 5})).is_empty()); + // `body` picks the placed instance `face` is read in (frames::to_local), so it is a key. + assert!(c.check(&json!({"distance": 5, "face": [0, 0, 0], "body": "Part"})).is_empty()); + for key in ["sketch", "profiles", "faces", "convention", "to", "from", "thin"] { + let mut p = json!({"distance": 5}); + p[key] = Value::Null; + assert_eq!(c.check(&p).len(), 1, "{key}: null"); + } + // Keys today's reader treats `null` like absence stay optional. + for key in ["taper", "direction", "face", "operation", "name"] { + let mut p = json!({"distance": 5}); + p[key] = Value::Null; + assert!(c.check(&p).is_empty(), "{key}: null"); + } +} + +fn sketch_rectangle(s: &mut Session) { + for (id, p) in [ + ("sketch.create", json!({"plane": "XY"})), + ("sketch.rectangle.center", json!({"center": [0, 0], "corner": [10, 10]})), + ("sketch.finish", json!({})), + ] { + if let Err(e) = s.execute(id, &p) { + panic!("{id}: {e}"); + } + } +} + +fn features(s: &Session) -> usize { + s.doc.features.len() +} + +#[test] +fn off_runs_the_handler_untouched() { + let mut s = Session::default(); + assert_eq!(s.param_check, ParamCheck::Off); + let r = s.execute("solid.box", &json!({"length": 5, "width": 5, "height": 5, "operaton": "cut"})); + let r = r.unwrap_or_else(|e| panic!("{e}")); + assert!(r.get("param_warnings").is_none()); + assert_eq!(r["created_bodies"], json!(["Body1"]), "the typo is ignored, as before: a new body"); +} + +#[test] +fn warn_runs_and_reports() { + let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() }; + let r = s.execute("solid.box", &json!({"length": 5, "width": 5, "height": 5, "operaton": "cut"})).unwrap_or_else(|e| panic!("{e}")); + assert_eq!(r["param_warnings"], json!(["unknown key `operaton`; did you mean `operation`?"])); + assert_eq!(features(&s), 1); + let r = s.execute("solid.box", &json!({"length": 5, "width": 5, "height": 5, "corner": [20, 0, 0]})).unwrap_or_else(|e| panic!("{e}")); + assert!(r.get("param_warnings").is_none(), "a clean call carries no warnings"); +} + +#[test] +fn strict_refuses_and_leaves_the_design_alone() { + let mut s = Session { param_check: ParamCheck::Strict, ..Session::default() }; + let e = s.execute("solid.box", &json!({"length": 5, "width": 5, "height": 5, "operaton": "cut"})).err().map(|e| e.to_string()); + assert_eq!(e.as_deref(), Some("invalid parameters for `solid.box`: unknown key `operaton`; did you mean `operation`?")); + assert_eq!(features(&s), 0); + sketch_rectangle(&mut s); + let before = features(&s); + let e = s.execute("solid.extrude", &json!({"distance": 5, "tapper": "10 deg"})).err().map(|e| e.to_string()); + assert_eq!(e.as_deref(), Some("invalid parameters for `solid.extrude`: unknown key `tapper`; did you mean `taper`?")); + let e = s.execute("solid.extrude", &json!({"distance": 5, "operation": 5})).err().map(|e| e.to_string()); + assert!(e.as_deref().is_some_and(|e| e.contains("`operation` must be one of")), "{e:?}"); + assert_eq!(features(&s), before); + s.execute("solid.extrude", &json!({"distance": 5, "direction": "symmetric"})).unwrap_or_else(|e| panic!("{e}")); + assert_eq!(features(&s), before + 1); +} + +#[test] +fn nested_runs_are_checked_too() { + let mut s = Session::default(); + sketch_rectangle(&mut s); + s.execute("solid.extrude", &json!({"distance": 5, "name": "Slab"})).unwrap_or_else(|e| panic!("{e}")); + s.param_check = ParamCheck::Strict; + let e = s + .execute("timeline.redefine", &json!({"feature": "Slab", "command": "solid.extrude", "params": {"distance": 8, "directon": "symmetric"}})) + .err() + .map(|e| e.to_string()); + assert!(e.as_deref().is_some_and(|e| e.contains("unknown key `directon`; did you mean `direction`?")), "{e:?}"); +} + +#[test] +fn the_level_survives_a_new_design() { + let mut s = Session { param_check: ParamCheck::Strict, ..Session::default() }; + s.execute("file.new", &json!({})).unwrap_or_else(|e| panic!("{e}")); + assert_eq!(s.param_check, ParamCheck::Strict); + assert_eq!(s.scratch().param_check, ParamCheck::Strict); +} + +#[test] +fn feature_result_serializes_like_the_old_reply() { + for (warning, ms) in [(None, None), (Some("a Boolean needed a retry".to_string()), Some(12.5)), (None, Some(0.0)), (None, Some(1.0 / 3.0))] { + let old = json!({"feature": 7, "name": "Box1", "bodies": ["A", "B"], "created_bodies": ["B"], "changed_bodies": [], + "removed_bodies": ["C"], "warning": warning, "ms": ms}); + let new = FeatureResult { + feature: 7, + name: "Box1".into(), + bodies: vec!["A".into(), "B".into()], + created_bodies: vec!["B".into()], + changed_bodies: vec![], + removed_bodies: vec!["C".into()], + warning: warning.clone(), + ms, + param_warnings: vec![], + }; + assert_eq!(serde_json::to_value(&new).ok(), Some(old)); + } +} + +/// Whether `v` conforms to `node` of the schema `root`, for the keywords these schemas use +/// apart from `pattern`: `type`, `properties`, `required`, `additionalProperties: false`, +/// `items`, `minItems`, `maxItems`, `uniqueItems`, `enum`, `minLength`, `maxLength`, `minimum`, +/// `maximum`, `exclusiveMinimum`, `exclusiveMaximum`, `anyOf`, `not` and `$ref`. (`integer` +/// here is what serde reads as one, so `1.0` is not.) +fn conforms(root: &Value, node: &Value, v: &Value) -> bool { + if let Some(name) = node.get("$ref").and_then(Value::as_str).and_then(|r| r.strip_prefix("#/$defs/")) { + return root.get("$defs").and_then(|d| d.get(name)).is_some_and(|t| conforms(root, t, v)); + } + if let Some(branches) = node.get("anyOf").and_then(Value::as_array) + && !branches.iter().any(|b| conforms(root, b, v)) + { + return false; + } + if node.get("not").is_some_and(|n| conforms(root, n, v)) { + return false; + } + let is = |t: &str| match t { + "null" => v.is_null(), + "boolean" => v.is_boolean(), + "integer" => v.is_u64() || v.is_i64(), + "number" => v.is_number(), + "string" => v.is_string(), + "array" => v.is_array(), + "object" => v.is_object(), + _ => false, + }; + let typed = match node.get("type") { + Some(Value::String(t)) => is(t), + Some(Value::Array(ts)) => ts.iter().filter_map(Value::as_str).any(is), + _ => true, + }; + if !typed { + return false; + } + if let (Some(items), Some(a)) = (node.get("items"), v.as_array()) + && !a.iter().all(|x| conforms(root, items, x)) + { + return false; + } + let bound = |k: &str| node.get(k).and_then(Value::as_u64).map(|n| n as usize); + if let Some(a) = v.as_array() { + let unique = a.iter().enumerate().all(|(i, x)| !a.iter().skip(i + 1).any(|y| y == x)); + if bound("minItems").is_some_and(|n| a.len() < n) + || bound("maxItems").is_some_and(|n| a.len() > n) + || (node.get("uniqueItems") == Some(&json!(true)) && !unique) + { + return false; + } + } + if let Some(s) = v.as_str() { + let n = s.chars().count(); + if bound("minLength").is_some_and(|m| n < m) || bound("maxLength").is_some_and(|m| n > m) { + return false; + } + } + if let Some(x) = v.as_f64() { + let limit = |k: &str| node.get(k).and_then(Value::as_f64); + if limit("minimum").is_some_and(|m| x < m) + || limit("maximum").is_some_and(|m| x > m) + || limit("exclusiveMinimum").is_some_and(|m| x <= m) + || limit("exclusiveMaximum").is_some_and(|m| x >= m) + { + return false; + } + } + if let Some(values) = node.get("enum").and_then(Value::as_array) + && !values.contains(v) + { + return false; + } + if let Some(o) = v.as_object() { + let props = node.get("properties").and_then(Value::as_object); + let mut required = node.get("required").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str); + if !required.all(|k| o.contains_key(k)) { + return false; + } + for (k, x) in o { + match props.and_then(|p| p.get(k)) { + Some(p) if !conforms(root, p, x) => return false, + None if node.get("additionalProperties") == Some(&json!(false)) => return false, + _ => {} + } + } + } + true +} + +#[test] +fn replies_match_the_output_schema() { + let schema = output_schema_for::(); + let schema = schema.as_value(); + let required: Vec<&str> = schema.get("required").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).collect(); + assert!(!required.contains(&"param_warnings")); + let mut s = Session::default(); + sketch_rectangle(&mut s); + s.param_check = ParamCheck::Warn; + let replies = [ + s.execute("solid.box", &json!({"length": 5, "width": 5, "height": 5, "corner": [20, 0, 0]})), + s.execute("solid.extrude", &json!({"distance": 5, "operation": "join"})), + s.execute("solid.box", &json!({"length": 5, "width": 5, "height": 5, "colour": "red"})), + ]; + for r in replies { + let r = r.unwrap_or_else(|e| panic!("{e}")); + assert!(conforms(schema, schema, &r), "{r} doesn't match {schema}"); + } + // The check itself catches a wrong type, a wrong item type and a missing key. (The output + // schema leaves other keys open, so a new result key doesn't break clients.) + let ok = json!({"feature": 1, "name": "Box1", "bodies": [], "created_bodies": [], "changed_bodies": [], "removed_bodies": [], "warning": null, "ms": null}); + assert!(conforms(schema, schema, &ok)); + for (k, v) in [("feature", json!("1")), ("bodies", json!([1])), ("warning", json!(5)), ("ms", json!("1"))] { + let mut bad = ok.clone(); + bad[k] = v; + assert!(!conforms(schema, schema, &bad), "{bad}"); + } + let mut bad = ok.clone(); + bad.as_object_mut().map(|o| o.remove("name")); + assert!(!conforms(schema, schema, &bad), "{bad}"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn the_recorder_keeps_a_bounded_number_of_signatures() { + use super::record::tally; + let mut seen = std::collections::HashMap::new(); + // Lines are due at counts 1, 2, 4, … + assert_eq!(tally(&mut seen, "a".into(), 2), Some((false, 1))); + assert_eq!(tally(&mut seen, "a".into(), 2), Some((false, 2))); + assert_eq!(tally(&mut seen, "a".into(), 2), None); + assert_eq!(tally(&mut seen, "b".into(), 2), Some((false, 1))); + // Full: new signatures are counted under one entry; known ones still count. + assert_eq!(tally(&mut seen, "c".into(), 2), Some((true, 1))); + assert_eq!(tally(&mut seen, "d".into(), 2), Some((true, 2))); + assert_eq!(tally(&mut seen, "a".into(), 2), Some((false, 4))); + assert_eq!(seen.len(), 3); +} + +#[test] +fn describe_returns_both_schemas() { + let mut s = Session::default(); + let d = s.execute("engine.describe", &json!({"command": "solid.box"})).unwrap_or_else(|e| panic!("{e}")); + assert_eq!(d["id"], "solid.box"); + assert!(d["input"]["properties"].get("length").is_some()); + assert!(d["output"]["properties"].get("created_bodies").is_some()); + // Its own output schema lists the warnings warn mode can add. + let own = s.execute("engine.describe", &json!({"command": "engine.describe"})).unwrap_or_else(|e| panic!("{e}")); + assert!(own["output"]["properties"].get("param_warnings").is_some(), "{own}"); + let d = s.execute("engine.describe", &json!({"command": "solid.revolve"})).unwrap_or_else(|e| panic!("{e}")); + assert!(d["input"].is_null() && d["output"].is_null(), "unconverted commands have no schemas yet"); + let e = s.execute("engine.describe", &json!({"command": "solid.extrud"})).err().map(|e| e.to_string()); + assert!(e.as_deref().is_some_and(|e| e.contains("did you mean `solid.extrude`")), "{e:?}"); +} + +/// The profiles schema and the contract agree on every listed case; the schema is deliberately +/// narrower on non-text curve ids and loops past the outer one (and describes the app's +/// `whole_boundaries` selection only by its `type`). +#[test] +fn the_profiles_schema_matches_the_contract() { + let root = input_schema_for::(); + let root = root.as_value(); + let node = &root["properties"]["profiles"]; + let accepted = |v: &Value| parse::(v.clone()).is_some(); + for v in [ + json!(3), + json!(-1), + json!([]), + json!([0, 1]), + json!([0, {"point": [1, 2]}]), + json!([{"point": [1, 2]}, {"point": [3, 4]}]), + json!([{"point": [1e9, 2]}]), + json!([["l1"]]), + json!([[]]), + json!([{"curves": "l1"}, ["l2"]]), + json!([{"curves": []}]), + json!([{"loops": []}]), + json!([{"loops": [5]}]), + json!([{"loops": [{"curves": ["l1"]}]}]), + json!({}), + json!({"offset_boundaries": ["a"]}), + json!({"offset_boundaries": []}), + json!({"offset_boundaries": ["a", "a"]}), + json!({"type": "offset_boundaries", "associations": ["a", "b"]}), + json!({"type": "something"}), + serde_json::from_str("18446744073709551616").unwrap_or_default(), + // The helper's precedence: all items with `point` are points; `curves` before `loops`; + // `offset_boundaries` before `type`. + json!([{"point": null, "curves": ["l1"]}]), + json!([{"point": [1, 2], "curves": ["l1"]}]), + json!([{"curves": [], "loops": [{"curves": ["l1"]}]}]), + json!([{"point": [0, 0], "curves": ["l1"]}, ["l2"]]), + json!([{"point": [1, 2], "curves": ["a"]}, {"curves": ["b"]}]), + json!([{"point": [0, 0], "loops": [{"curves": ["l1"]}]}, {"curves": "l2"}]), + json!({"type": "offset_boundaries", "associations": ["a"], "offset_boundaries": []}), + ] { + assert_eq!(conforms(root, node, &v), accepted(&v), "{v}"); + } + // An index is bounded to what the helper reads as a u64. (`conforms` refuses 2^64 above on + // type alone, so the bound itself is checked here.) + let index = |b: &Value| b.get("type") == Some(&json!("integer")); + let bounds: Vec<&Value> = root["$defs"]["Profiles"]["anyOf"] + .as_array() + .into_iter() + .flatten() + .flat_map(|b| [b, &b["items"]]) + .filter(|b| index(b)) + .map(|b| &b["maximum"]) + .collect(); + assert_eq!(bounds, [&json!(u64::MAX), &json!(u64::MAX)]); + // Where the schema is deliberately narrower: non-text ids and loops past the outer one. + for v in [json!([["l1", 5]]), json!([{"loops": [{"curves": ["l1"]}, 5]}])] { + assert!(accepted(&v) && !conforms(root, node, &v), "{v}"); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn recorder_lines_have_the_documented_shape() { + let l = super::record::line("solid.box", &["unknown key `x`"], "ok", "a_test", 4, &json!({"x": "y".repeat(5000)})); + let keys: Vec<&str> = l.as_object().into_iter().flat_map(|o| o.keys().map(String::as_str)).collect(); + assert_eq!(keys, ["command", "count", "issues", "outcome", "sample_params", "source"]); + assert_eq!((l["command"].clone(), l["count"].clone(), l["outcome"].clone()), (json!("solid.box"), json!(4), json!("ok"))); + assert!(l["sample_params"].as_str().is_some_and(|s| s.len() <= 1024 + "…".len() && s.ends_with('…')), "{l}"); + // A strict refusal is told apart from a handler's error. + use super::record::outcome_text; + assert_eq!(outcome_text(None), "refused"); + assert_eq!(outcome_text(Some(&Ok(json!({})))), "ok"); + assert_eq!(outcome_text(Some(&Err(crate::EngineError::Other("boom".into())))), "error: boom"); + // The recorder is on exactly when built with `param-audit` and the variable names a directory. + let set = std::env::var_os("SOLIDCRAFT_PARAM_AUDIT").is_some_and(|v| !v.is_empty()); + assert_eq!(super::record::enabled(), cfg!(feature = "param-audit") && set); +} + +/// A call that already fails gets the same error in strict as with the check off, apart from +/// the missing-key, missing-instead-of-wrong-type, non-object, profile-index, 10,000-item and +/// over-4-KB messages the report lists. +#[test] +fn strict_keeps_todays_errors() { + let cases = [ + ("solid.box", json!({"length": 5, "width": 5, "height": 5, "operation": "bogus"})), + ("solid.box", json!({"length": true, "width": 5, "height": 5})), + ("solid.box", json!({"length": 5, "width": 5, "height": 5, "corner": [1, 2]})), + ("solid.extrude", json!({"distance": 5, "operation": "bogus"})), + ("solid.extrude", json!({"distance": 5, "direction": "sideways"})), + ("solid.extrude", json!({"distance": 5, "direction": "SIDEWAYS"})), + ("solid.extrude", json!({"distance": 5, "profiles": [{"point": [1]}]})), + ("solid.extrude", json!({"distance": 5, "profiles": [["l1"], 7]})), + ("solid.extrude", json!({"distance": 5, "profiles": []})), + ("solid.extrude", json!({"distance": 5, "profiles": [true]})), + ("solid.extrude", json!({"distance": 5, "faces": []})), + ("solid.extrude", json!({"distance": 5, "faces": null})), + ("solid.extrude", json!({"distance": 5, "faces": [[1, 2]]})), + ("solid.extrude", json!({"distance": 5, "profiles": {"offset_boundaries": ["a", "a"]}})), + ("solid.extrude", json!({"distance": 5, "thin": true, "thickness": 1, "side": "middle"})), + ("solid.extrude", json!({"distance": 5, "thin": "true"})), + ("solid.extrude", json!({"distance": 5, "to": [1, 2]})), + ("solid.extrude", json!({"distance": 5, "from": "x"})), + ("solid.extrude", json!({"distance": 5, "sketch": true})), + ("solid.extrude", json!({"distance": 5, "convention": "per_side"})), + ("solid.extrude", json!({"distance": " "})), + ("solid.extrude", json!({"distance": 5, "operation": "x".repeat(1000)})), + ("engine.describe", json!({"command": 5})), + ("engine.describe", json!({"command": null})), + ("engine.describe", json!({"command": "solid.extrud"})), + ]; + for (id, p) in cases { + let error = |level: ParamCheck| { + let mut s = Session { param_check: level, ..Session::default() }; + sketch_rectangle(&mut s); + s.execute(id, &p).err().map(|e| e.to_string()) + }; + let off = error(ParamCheck::Off); + assert!(off.is_some(), "{p} should fail today"); + assert_eq!(error(ParamCheck::Strict), off, "{p}"); + } +} + +/// Every `default` in the input schemas is a value its own property schema allows. +#[test] +fn schema_defaults_are_valid() { + for root in [input_schema_for::(), input_schema_for::()] { + let root = root.as_value(); + for (key, property) in root["properties"].as_object().into_iter().flatten() { + if let Some(d) = property.get("default") { + assert!(conforms(root, property, d), "`{key}`: default {d} doesn't match {property}"); + } + } + } +} + +/// The expression schema's "not blank" pattern uses exactly the whitespace Rust's `trim` does. +#[test] +fn the_blank_pattern_matches_trim() { + let listed = |c: char| super::types::WHITESPACE.iter().any(|&(a, b)| (a..=b).contains(&c)); + for c in (0..=0x10_ffff).filter_map(char::from_u32) { + assert_eq!(listed(c), c.is_whitespace(), "U+{:04X}", c as u32); + } + assert_eq!(super::types::not_blank_pattern(), r"[^\u0009-\u000d\u0020\u0085\u00a0\u1680\u2000-\u200a\u2028-\u2029\u202f\u205f\u3000]"); + assert!(parse::(json!("\u{85}")).is_none() && parse::(json!("\u{feff}")).is_some()); +} + +/// A handler-worded message for a key the handler ignores stays bounded in a warning. +#[test] +fn long_values_in_handler_messages_are_capped() { + let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() }; + sketch_rectangle(&mut s); + let r = s.execute("solid.extrude", &json!({"distance": 5, "side": "x".repeat(1_000_000)})).unwrap_or_else(|e| panic!("{e}")); + let w = r["param_warnings"][0].as_str().unwrap_or_default(); + assert!(w.starts_with("unknown side `xxx") && w.len() <= 4096 + "…".len(), "{} bytes", w.len()); +} diff --git a/crates/engine/src/schema/types.rs b/crates/engine/src/schema/types.rs new file mode 100644 index 000000000..519641f58 --- /dev/null +++ b/crates/engine/src/schema/types.rs @@ -0,0 +1,585 @@ +//! Shared parameter types. Each one decides acceptance with the helper the handlers already +//! use, applied to the raw JSON value, so a contract can never accept a value its handler's own +//! reader would refuse. Their schemas describe the accepted forms. + +use std::borrow::Cow; + +use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema}; +use serde::de::Error as _; +use serde::{Deserialize, Deserializer}; +use serde_json::{Value, json}; +use solidcraft_doc::{Expr, Operation, ThinSide}; +use solidcraft_geom::{Vec2, Vec3}; + +use super::check::whole; +use crate::params; + +/// For optional fields whose key may be absent but not `null`: absent is `None` (with +/// `#[serde(default)]`), a present value, `null` included, goes to `T`'s deserializer. Pair it +/// with `#[schemars(with = "T")]` so the schema has no `null` branch. +pub fn present<'de, D: Deserializer<'de>, T: Deserialize<'de>>(d: D) -> Result, D::Error> { + T::deserialize(d).map(Some) +} + +/// A coordinate's schema: a number below 1e9 in size, as `params::finite` requires. +fn coordinate() -> Value { + json!({"type": "number", "exclusiveMinimum": -1e9, "exclusiveMaximum": 1e9}) +} + +/// The characters Rust's `trim` removes (Unicode `White_Space`), as ranges. A regex's `\s` +/// differs (it has U+FEFF and lacks U+0085), so the expression schema spells them out. +pub(crate) const WHITESPACE: [(char, char); 10] = [ + ('\u{9}', '\u{d}'), + (' ', ' '), + ('\u{85}', '\u{85}'), + ('\u{a0}', '\u{a0}'), + ('\u{1680}', '\u{1680}'), + ('\u{2000}', '\u{200a}'), + ('\u{2028}', '\u{2029}'), + ('\u{202f}', '\u{202f}'), + ('\u{205f}', '\u{205f}'), + ('\u{3000}', '\u{3000}'), +]; + +/// A pattern for text that isn't blank once trimmed: a character outside [`WHITESPACE`]. +pub(crate) fn not_blank_pattern() -> String { + let u = |c: char| format!("\\u{:04x}", c as u32); + let class: String = WHITESPACE.iter().map(|&(a, b)| if a == b { u(a) } else { format!("{}-{}", u(a), u(b)) }).collect(); + format!("[^{class}]") +} + +/// `v` as the only key of an object, for the helpers that read `p.get(key)`. +fn wrap(v: Value) -> Value { + json!({ "v": v }) +} + +macro_rules! expr_type { + ($(#[$doc:meta])* $name:ident, $title:literal, $description:literal) => { + $(#[$doc])* + #[derive(Clone, Debug, PartialEq)] + pub struct $name(pub Expr); + + impl<'de> Deserialize<'de> for $name { + fn deserialize>(d: D) -> Result { + params::expr(&wrap(Value::deserialize(d)?), "v").map($name).ok_or_else(|| D::Error::custom("must be a number or an expression")) + } + } + + impl JsonSchema for $name { + fn schema_name() -> Cow<'static, str> { + $title.into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({ + "description": $description, + "anyOf": [ + {"type": "number", "exclusiveMinimum": -1e9, "exclusiveMaximum": 1e9}, + {"type": "string", "minLength": 1, "maxLength": 4096, "pattern": not_blank_pattern()} + ] + }) + } + } + }; +} + +expr_type!( + /// A length: a number, read in the design's length unit, or an expression such as + /// `"w / 2"` or `"30 mm"`. + LengthExpr, + "LengthExpr", + "A length: a number in the design's length unit, or an expression such as \"w / 2\" or \"30 mm\"." +); +expr_type!( + /// An angle: a number of degrees, or an expression such as `"30 deg"` or `"a / 2"`. + AngleExpr, + "AngleExpr", + "An angle: a number of degrees, or an expression such as \"30 deg\" or \"a / 2\"." +); + +/// A point in mm: `[x, y, z]` or `{x, y, z}` of finite numbers (read by `params::vec3`). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Point3(pub Vec3); + +impl<'de> Deserialize<'de> for Point3 { + fn deserialize>(d: D) -> Result { + params::vec3(&Value::deserialize(d)?).map(Point3).ok_or_else(|| D::Error::custom("must be a point [x, y, z] of numbers")) + } +} + +impl JsonSchema for Point3 { + fn schema_name() -> Cow<'static, str> { + "Point3".into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + let c = coordinate(); + json_schema!({ + "description": "A point in mm: [x, y, z] or {\"x\", \"y\", \"z\"}.", + "anyOf": [ + {"type": "array", "items": c, "minItems": 3, "maxItems": 3}, + {"type": "object", "properties": {"x": c, "y": c, "z": c}, "required": ["x", "y", "z"]} + ] + }) + } +} + +macro_rules! target_point { + ($(#[$doc:meta])* $name:ident, $message:literal) => { + $(#[$doc])* + #[derive(Clone, Copy, Debug, PartialEq)] + pub struct $name(pub Vec3); + + impl<'de> Deserialize<'de> for $name { + fn deserialize>(d: D) -> Result { + params::vec3(&Value::deserialize(d)?).map($name).ok_or_else(|| D::Error::custom($message)) + } + } + + impl JsonSchema for $name { + fn schema_name() -> Cow<'static, str> { + stringify!($name).into() + } + fn inline_schema() -> bool { + true + } + fn json_schema(generator: &mut SchemaGenerator) -> Schema { + generator.subschema_for::() + } + } + }; +} + +target_point!( + /// Extrude's `to`: a [`Point3`], with the handler's message. + ToPoint, + "must be a point [x, y, z] on the face, vertex or point to extrude to" +); +target_point!( + /// Extrude's `from`: a [`Point3`], with the handler's message. + FromPoint, + "must be a point [x, y, z] on the face or point to start from" +); + +/// Extrude's `faces`: 1 to 1024 points on coplanar faces of one body, read as the handler reads +/// them, with its messages. +#[derive(Clone, Debug, PartialEq)] +pub struct FacesParam(pub Vec); + +impl<'de> Deserialize<'de> for FacesParam { + fn deserialize>(d: D) -> Result { + let v = Value::deserialize(d)?; + let faces = v + .as_array() + .filter(|faces| !faces.is_empty() && faces.len() <= 1024) + .ok_or_else(|| D::Error::custom(whole("faces must contain between 1 and 1024 points")))?; + faces + .iter() + .map(params::vec3) + .collect::>>() + .map(FacesParam) + .ok_or_else(|| D::Error::custom(whole("faces must be points [x,y,z]"))) + } +} + +impl JsonSchema for FacesParam { + fn schema_name() -> Cow<'static, str> { + "Faces".into() + } + fn json_schema(generator: &mut SchemaGenerator) -> Schema { + let point = generator.subschema_for::(); + json_schema!({ + "description": "Points in mm, one on each of the coplanar faces of one body to extrude together.", + "type": "array", "items": point, "minItems": 1, "maxItems": 1024 + }) + } +} + +/// A sketch point in mm: `[x, y]` or `{x, y}` of finite numbers (read by `params::vec2`). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Point2(pub Vec2); + +impl<'de> Deserialize<'de> for Point2 { + fn deserialize>(d: D) -> Result { + params::vec2(&Value::deserialize(d)?).map(Point2).ok_or_else(|| D::Error::custom("must be a point [x, y] of numbers")) + } +} + +impl JsonSchema for Point2 { + fn schema_name() -> Cow<'static, str> { + "Point2".into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + let c = coordinate(); + json_schema!({ + "description": "A sketch point in mm: [x, y] or {\"x\", \"y\"}.", + "anyOf": [ + {"type": "array", "items": c, "minItems": 2, "maxItems": 2}, + {"type": "object", "properties": {"x": c, "y": c}, "required": ["x", "y"]} + ] + }) + } +} + +/// A placement point: `[x, y, z]` or `{x, y, z}`, each a number (mm) or a length expression, +/// as `features::point_param` reads it. Whether the expressions evaluate is checked by the +/// handler, which has the design. +#[derive(Clone, Debug, PartialEq)] +pub struct PointExpr3(pub [Expr; 3]); + +impl<'de> Deserialize<'de> for PointExpr3 { + fn deserialize>(d: D) -> Result { + let v = Value::deserialize(d)?; + let coords: Option> = match &v { + Value::Array(a) if a.len() == 3 => Some(a.iter().collect()), + Value::Object(o) => ["x", "y", "z"].iter().map(|k| o.get(*k)).collect(), + _ => None, + }; + coords + .and_then(|c| c.into_iter().map(|c| params::expr(&wrap(c.clone()), "v")).collect::>>()) + .and_then(|c| <[Expr; 3]>::try_from(c).ok()) + .map(PointExpr3) + .ok_or_else(|| D::Error::custom("must be a point [x, y, z] of numbers or length expressions")) + } +} + +impl JsonSchema for PointExpr3 { + fn schema_name() -> Cow<'static, str> { + "PointExpr3".into() + } + fn json_schema(generator: &mut SchemaGenerator) -> Schema { + let c = generator.subschema_for::(); + json_schema!({ + "description": "A point: [x, y, z] or {\"x\", \"y\", \"z\"}, each a number in mm or a length expression.", + "anyOf": [ + {"type": "array", "items": c, "minItems": 3, "maxItems": 3}, + {"type": "object", "properties": {"x": c, "y": c, "z": c}, "required": ["x", "y", "z"]} + ] + }) + } +} + +/// A feature referred to by its id (a number) or its name (a string). +#[derive(Clone, Debug, PartialEq)] +pub struct IdOrName(pub String); + +impl<'de> Deserialize<'de> for IdOrName { + fn deserialize>(d: D) -> Result { + match Value::deserialize(d)? { + Value::Number(n) => Ok(IdOrName(n.to_string())), + Value::String(s) => Ok(IdOrName(s)), + _ => Err(D::Error::custom("must be an id or name")), + } + } +} + +impl JsonSchema for IdOrName { + fn schema_name() -> Cow<'static, str> { + "IdOrName".into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"description": "A feature's id (a number) or its name.", "type": ["number", "string"]}) + } +} + +/// One name or a list of names, at most 10 000. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct StringList(pub Vec); + +impl<'de> Deserialize<'de> for StringList { + fn deserialize>(d: D) -> Result { + let fail = || D::Error::custom("must be a name or a list of names"); + match Value::deserialize(d)? { + Value::String(s) => Ok(StringList(vec![s])), + Value::Array(a) if a.len() > 10_000 => Err(D::Error::custom("must have at most 10000 items")), + Value::Array(a) => a + .into_iter() + .map(|v| if let Value::String(s) = v { Some(s) } else { None }) + .collect::>>() + .map(StringList) + .ok_or_else(fail), + _ => Err(fail()), + } + } +} + +impl JsonSchema for StringList { + fn schema_name() -> Cow<'static, str> { + "StringList".into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({ + "description": "A name, or a list of names.", + "anyOf": [{"type": "string"}, {"type": "array", "items": {"type": "string"}, "maxItems": 10000}] + }) + } +} + +/// The spellings `Operation::parse` accepts, canonical ones first (it also ignores case, spaces, +/// '_' and '-', which an enum can't say). +const OPERATIONS: [&str; 13] = [ + "new", + "join", + "cut", + "intersect", + "new_body", + "newbody", + "new_component", + "newcomponent", + "union", + "add", + "subtract", + "difference", + "intersection", +]; + +/// A string `ok` accepts. A string it refuses gets `unknown(s)` (the handler's own message, +/// marked [`whole`]); anything else, which the handlers ignore, "must be one of `expected`". +fn string_matching<'de, D: Deserializer<'de>>( + d: D, + ok: impl Fn(&str) -> bool, + expected: &str, + unknown: impl Fn(&str) -> String, +) -> Result { + match Value::deserialize(d)? { + Value::String(s) if ok(&s) => Ok(s), + Value::String(s) => Err(D::Error::custom(unknown(&s))), + _ => Err(D::Error::custom(format!("must be one of {expected}"))), + } +} + +/// `features::operation`'s message for an operation it doesn't know. +fn unknown_operation(s: &str) -> String { + whole(format!("unknown operation `{s}` (new, join, cut, intersect)")) +} + +fn enum_schema(values: &[&str], description: &str) -> Schema { + json_schema!({"description": description, "type": "string", "enum": values}) +} + +/// How a feature combines with existing bodies, as `features::operation` reads it. +#[derive(Clone, Debug, PartialEq)] +pub struct OperationParam(pub Operation); + +impl<'de> Deserialize<'de> for OperationParam { + fn deserialize>(d: D) -> Result { + let s = string_matching(d, |s| Operation::parse(s).is_some(), "new, join, cut or intersect", unknown_operation)?; + Operation::parse(&s).map(OperationParam).ok_or_else(|| D::Error::custom("must be one of new, join, cut or intersect")) + } +} + +impl JsonSchema for OperationParam { + fn schema_name() -> Cow<'static, str> { + "Operation".into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + enum_schema( + &OPERATIONS, + "How the feature combines with existing bodies: new, join, cut or intersect. The others are aliases. Matching ignores case, spaces, '_' and '-'.", + ) + } +} + +/// Extrude's operation: the above or `auto` (matched with `eq_ignore_ascii_case`, as the +/// handler does). +#[derive(Clone, Debug, PartialEq)] +pub struct ExtrudeOperation(pub String); + +impl<'de> Deserialize<'de> for ExtrudeOperation { + fn deserialize>(d: D) -> Result { + let ok = |s: &str| s.eq_ignore_ascii_case("auto") || Operation::parse(s).is_some(); + string_matching(d, ok, "new, join, cut, intersect or auto", unknown_operation).map(ExtrudeOperation) + } +} + +impl JsonSchema for ExtrudeOperation { + fn schema_name() -> Cow<'static, str> { + "ExtrudeOperation".into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + let mut values = vec!["auto"]; + values.extend(OPERATIONS); + enum_schema( + &values, + "How the extrusion combines with existing bodies: auto (cut into a body, otherwise join; new in an empty component), new, join, cut or intersect. The others are aliases. Matching ignores case, spaces, '_' and '-' (only case for auto).", + ) + } +} + +const DIRECTIONS: [&str; 6] = ["positive", "negative", "symmetric", "one_side", "reverse", "flip"]; + +/// Extrude's direction, as `extent_param` reads it (lowercased, not trimmed). +#[derive(Clone, Debug, PartialEq)] +pub struct DirectionParam(pub String); + +impl<'de> Deserialize<'de> for DirectionParam { + fn deserialize>(d: D) -> Result { + let ok = |s: &str| DIRECTIONS.contains(&s.to_ascii_lowercase().as_str()); + // The handler names the direction lowercased. + let unknown = |s: &str| whole(format!("unknown direction `{}`", s.to_ascii_lowercase())); + string_matching(d, ok, "positive, negative or symmetric", unknown).map(DirectionParam) + } +} + +impl JsonSchema for DirectionParam { + fn schema_name() -> Cow<'static, str> { + "Direction".into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + enum_schema( + &DIRECTIONS, + "Which way to extrude: positive (the default), negative, or symmetric (the distance is the total thickness, split evenly around the start plane). one_side is an alias of positive; reverse and flip of negative. Matching ignores case.", + ) + } +} + +/// The `extent` keyword: only `through_all` (ignoring case) is meaningful. +#[derive(Clone, Debug, PartialEq)] +pub struct ExtentKeyword; + +impl<'de> Deserialize<'de> for ExtentKeyword { + fn deserialize>(d: D) -> Result { + match Value::deserialize(d)? { + Value::String(s) if s.eq_ignore_ascii_case("through_all") => Ok(ExtentKeyword), + _ => Err(D::Error::custom("must be through_all")), + } + } +} + +impl JsonSchema for ExtentKeyword { + fn schema_name() -> Cow<'static, str> { + "ExtentKeyword".into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + enum_schema(&["through_all"], "\"through_all\" (any case) is the same as through_all: true.") + } +} + +/// Extrude's distance convention, as `extent_param` reads it (serde, case-sensitive). +#[derive(Clone, Debug, PartialEq)] +pub struct ConventionParam(pub solidcraft_doc::ExtrudeConvention); + +impl<'de> Deserialize<'de> for ConventionParam { + fn deserialize>(d: D) -> Result { + serde_json::from_value(Value::deserialize(d)?).map(ConventionParam).map_err(|_| D::Error::custom("must be total_distance or legacy_per_side")) + } +} + +impl JsonSchema for ConventionParam { + fn schema_name() -> Cow<'static, str> { + "ExtrudeConvention".into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + enum_schema( + &["total_distance", "legacy_per_side"], + "total_distance (the default): a symmetric distance is the total thickness. legacy_per_side keeps older designs' per-side meaning.", + ) + } +} + +/// A thin wall's side, as `ThinSide::parse` reads it. +#[derive(Clone, Debug, PartialEq)] +pub struct ThinSideParam(pub ThinSide); + +impl<'de> Deserialize<'de> for ThinSideParam { + fn deserialize>(d: D) -> Result { + let s = string_matching( + d, + |s| ThinSide::parse(s).is_some(), + "center, inside, outside or two_sides", + |s| whole(format!("unknown side `{s}` (center, inside, outside or two_sides)")), + )?; + ThinSide::parse(&s).map(ThinSideParam).ok_or_else(|| D::Error::custom("must be one of center, inside, outside or two_sides")) + } +} + +impl JsonSchema for ThinSideParam { + fn schema_name() -> Cow<'static, str> { + "ThinSide".into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + enum_schema( + &["center", "inside", "outside", "two_sides", "centre", "centered", "centred", "symmetric", "side1", "side_1", "side2", "side_2", "both"], + "Which side of the curves the wall lies on: center (the default), inside, outside or two_sides. The others are aliases. Matching ignores case and surrounding spaces, and reads ' ' and '-' as '_'.", + ) + } +} + +/// Which sketch profiles a feature uses. Accepted exactly when `features::profiles` accepts +/// it; kept as the raw value for the handler. +#[derive(Clone, Debug, PartialEq)] +pub struct ProfilesParam(pub Value); + +impl<'de> Deserialize<'de> for ProfilesParam { + fn deserialize>(d: D) -> Result { + let v = Value::deserialize(d)?; + match crate::cmd::feature_profiles(&json!({ "profiles": v }), "profiles") { + Ok(_) => Ok(ProfilesParam(v)), + // The helper's messages as they are, apart from two terse ones, which get the + // contract's `must be` wording. + Err(crate::EngineError::BadParams { msg, .. }) => Err(D::Error::custom(match msg.as_str() { + "profile index" => "must be \"all\", an index or a list".to_string(), + "too many profiles" => "must have at most 10000 items".to_string(), + _ => whole(msg), + })), + Err(e) => Err(D::Error::custom(e.to_string())), + } + } +} + +impl JsonSchema for ProfilesParam { + fn schema_name() -> Cow<'static, str> { + "Profiles".into() + } + fn json_schema(generator: &mut SchemaGenerator) -> Schema { + let point = generator.subschema_for::(); + let curves = json!({"type": "array", "items": {"type": "string"}, "minItems": 1}); + let named = json!({"anyOf": [{"type": "string"}, curves]}); + let list = |items: Value| json!({"type": "array", "minItems": 1, "maxItems": 10000, "items": items}); + // An index is what the helper reads as a u64. + let index = json!({"type": "integer", "minimum": 0, "maximum": u64::MAX}); + let loops = json!({"type": "array", "minItems": 1, "items": { + "type": "object", "properties": {"outer": {"type": "boolean"}, "curves": named}, "required": ["curves"] + }}); + let associations = json!({ + "type": "array", "minItems": 1, "maxItems": 128, "uniqueItems": true, + "items": {"type": "string", "minLength": 1, "maxLength": 512} + }); + // A list is all indices, all points, or all curve selections, as the helper reads it; + // the `not`s give its precedence (a list whose items all have `point` is points, an + // item's `curves` wins over its `loops`; `type: whole_boundaries` wins over an + // `offset_boundaries` key, which wins over `type: offset_boundaries`). Narrower than + // the helper in one way: every curve id and every loop must be well formed, where the + // helper drops non-text ids and reads only the outer loop. + let curve_object = json!({"type": "object", "properties": {"curves": named}, "required": ["curves"]}); + let loops_object = json!({ + "type": "object", "properties": {"loops": loops}, "required": ["loops"], "not": {"required": ["curves"]} + }); + let curve_list = json!({ + "type": "array", "minItems": 1, "maxItems": 10000, "items": {"anyOf": [curves, curve_object, loops_object]}, + "not": {"items": {"type": "object", "required": ["point"]}} + }); + json_schema!({ + "description": "Which sketch profiles to use: \"all\" (the default, any case), an index, or a list of indices, of {\"point\": [x, y]} inside a profile, or of curve selections (a list of curve ids, {\"curves\": [ids]} or {\"loops\": [...]}). Picks by index or point are stored by the curves around the profile.", + "anyOf": [ + {"type": "string", "pattern": "^[Aa][Ll][Ll]$"}, + index.clone(), + list(index), + list(json!({"type": "object", "properties": {"point": point}, "required": ["point"]})), + curve_list, + { + "description": "Internal selections written by the app.", + "anyOf": [ + {"type": "object", "properties": {"type": {"enum": ["whole_boundaries"]}}, "required": ["type"]}, + { + "type": "object", "properties": {"offset_boundaries": associations}, "required": ["offset_boundaries"], + "not": {"properties": {"type": {"enum": ["whole_boundaries"]}}, "required": ["type"]} + }, + { + "type": "object", "properties": {"type": {"enum": ["offset_boundaries"]}, "associations": associations}, + "required": ["type", "associations"], "not": {"required": ["offset_boundaries"]} + } + ] + } + ] + }) + } +} diff --git a/crates/mcp/src/server.rs b/crates/mcp/src/server.rs index b3091ef31..584f5b4f9 100644 --- a/crates/mcp/src/server.rs +++ b/crates/mcp/src/server.rs @@ -31,7 +31,7 @@ and degrees in expressions (internally radians), Z is up. Model like this: `sket and dimension (`sketch.dimension {entities, value}`; values may name parameters), `sketch.finish`, then features \ (`solid.extrude {distance, operation?: new|join|cut|intersect}`, `solid.revolve`, `solid.fillet {edges: [[x,y,z] point on \ edge], radius}`, `solid.chamfer`, patterns, mirror, primitives). Use `batch` for several steps at once, \ -`list_commands` for ids and parameter docs, `inspect_design` / `measure` to verify, `body_topology` to find edge points, \ +`list_commands` for ids and parameter docs, `describe_command` for a command's schemas, `inspect_design` / `measure` to verify, `body_topology` to find edge points, \ `set_parameter` to drive the design and `screenshot` to look at it."; pub struct Server { diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index e60ef2aae..98ea3b515 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -88,6 +88,7 @@ fn handshake_and_tools_list() { let names: Vec<&str> = tools["result"]["tools"].as_array().unwrap().iter().map(|t| t["name"].as_str().unwrap()).collect(); for want in [ "list_commands", + "describe_command", "execute", "batch", "inspect_design", @@ -1479,7 +1480,7 @@ fn tool_annotations_tell_the_whole_truth() { for name in ["execute", "batch", "save", "export", "open", "screenshot"] { assert_eq!(hints(name), (false, true, true), "{name}"); } - for name in ["list_commands", "inspect_design", "measure", "body_topology", "crash_reports"] { + for name in ["list_commands", "describe_command", "inspect_design", "measure", "body_topology", "crash_reports"] { assert_eq!(hints(name), (true, false, false), "{name}"); } assert_eq!(hints("new_design"), (false, true, false)); @@ -1547,3 +1548,24 @@ fn batch_reports_timings_and_profile() { assert_eq!(body["timings"][0]["command"], "a.one", "{body}"); assert!(body["timings"][0].get("profile").is_none(), "{body}"); } + +/// `describe_command` serves a converted command's schemas, and a headless session set to strict +/// refuses a misspelt key through `execute` without touching the design. +#[test] +fn describe_command_and_strict_parameter_checking() { + let mut s = server(); + let d = tool(&mut s, "describe_command", json!({"id": "solid.box"})); + assert!(d["input"]["properties"].get("operation").is_some(), "{d}"); + assert!(d["output"]["properties"].get("created_bodies").is_some(), "{d}"); + + let mut headless = Headless::default(); + headless.session.param_check = solidcraft_engine::schema::ParamCheck::Strict; + let mut s = Server::new(Box::new(headless)); + call(&mut s, 1, "initialize", json!({"protocolVersion": PROTOCOL_VERSION, "capabilities": {}, "clientInfo": {"name": "t", "version": "1"}})); + let r = raw_tool(&mut s, "execute", json!({"command": "solid.box", "params": {"length": 5, "width": 5, "height": 5, "operaton": "cut"}})); + assert_eq!(r["result"]["isError"], json!(true), "{r}"); + let text = r["result"]["content"][0]["text"].as_str().unwrap_or_default(); + assert!(text.contains("unknown key `operaton`; did you mean `operation`?"), "{text}"); + let m = tool(&mut s, "measure", json!({})); + assert_eq!(m["body_count"], json!(0), "{m}"); +} diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index a5d4a9330..750a43c1e 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -72,6 +72,14 @@ pub fn tool_definitions() -> Vec { obj(json!({"filter": string("Substring to match, e.g. \"sketch\", \"fillet\", \"pattern\"")}), &[]), Effect::ReadOnly, ), + tool( + "describe_command", + "Describe a command", + "One command's parameter docs and, for commands with a typed contract (solid.box, solid.extrude and engine.describe so far), the \ + JSON Schemas (2020-12) of its parameters (`input`) and of a successful result (`output`); null for the others.", + obj(json!({"id": string("Command id, e.g. \"solid.extrude\"")}), &["id"]), + Effect::ReadOnly, + ), tool( "execute", "Execute a command", @@ -388,6 +396,10 @@ fn dispatch(b: &mut dyn Backend, name: &str, a: &Map) -> Result { + let id = str_arg(a, "id").ok_or("`id` is required")?; + exec(b, "engine.describe", json!({"command": id})) + } "execute" => { let id = str_arg(a, "command").ok_or("`command` is required")?; let v = exec(b, id, a.get("params").cloned().filter(Value::is_object).unwrap_or(json!({})))?; diff --git a/crates/ui-egui/src/agent_chat/gate.rs b/crates/ui-egui/src/agent_chat/gate.rs index 2eb4141c5..ecf49851a 100644 --- a/crates/ui-egui/src/agent_chat/gate.rs +++ b/crates/ui-egui/src/agent_chat/gate.rs @@ -64,7 +64,7 @@ fn reads_only(id: &str) -> bool { || id.starts_with("model.") || id.ends_with(".inspect") || id.ends_with(".list") - || matches!(id, "edit.checkpoint" | "render.status" | "render.backends" | "render.settings.get" | "file.slicers") + || matches!(id, "edit.checkpoint" | "render.status" | "render.backends" | "render.settings.get" | "file.slicers" | "engine.describe") } /// Commands that read or write a file by their nature: any string they are given in a path @@ -235,6 +235,7 @@ mod tests { assert_eq!(exec("sketch.inspect", json!({"sketch": 1})), Verdict::Run { change: false }); assert_eq!(exec("inspect.measure", json!({})), Verdict::Run { change: false }); assert_eq!(request("document.inspect", &json!({}), 0), Verdict::Run { change: false }); + assert_eq!(exec("engine.describe", json!({"command": "solid.box"})), Verdict::Run { change: false }); } #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 7b15492b2..71c033616 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -47,6 +47,16 @@ A `batch` that could not be sent says the app is not running, so it is safe to s stdout carries only protocol messages; errors go to stderr. Bridged screenshots are written to a temporary file by the app and read back by the server, so both must run on the same machine. +### Parameter checking + +Commands with a typed parameter contract (`solid.box`, `solid.extrude` and `engine.describe` +so far; `describe_command` shows a command's schemas) can be checked as they are called. +`--param-check off|warn|strict` sets the level for a headless session, including a script or +recipe given with `--in`; the default is `off`, which changes nothing. `warn` runs the call and +adds `param_warnings` to its result, such as ``unknown key `operaton`; did you mean +`operation`?`` (a starting script's warnings go to stderr). `strict` refuses the call, and the +design is left as it was. Calls bridged to the app are not checked yet. + ### Which files the agent can reach Tool calls read, write and delete files only inside the server's folders: @@ -99,11 +109,11 @@ file dialogs are never limited. ### Tool annotations Each tool says what it may do, for clients that ask before running tools (or auto-approve on -these hints). `list_commands`, `inspect_design`, `measure`, `body_topology` and `crash_reports` -are read-only. `set_parameter`, `undo` and `redo` change the design undoably. `new_design` -replaces it (destructive). `execute`, `batch`, `open`, `save`, `export` and `screenshot` (whose -`path` writes a file) can read, write, overwrite or delete files: they are not read-only, -`destructiveHint` and `openWorldHint` are true. +these hints). `list_commands`, `describe_command`, `inspect_design`, `measure`, `body_topology` +and `crash_reports` are read-only. `set_parameter`, `undo` and `redo` change the design undoably. +`new_design` replaces it (destructive). `execute`, `batch`, `open`, `save`, `export` and +`screenshot` (whose `path` writes a file) can read, write, overwrite or delete files: they are +not read-only, `destructiveHint` and `openWorldHint` are true. ### Client configuration @@ -143,6 +153,7 @@ They cover the workflow, the command shapes, how to verify with `measure`, and t | Tool | Arguments | What it does | |---|---|---| | `list_commands` | `filter?` | The command catalog: id, label, tab/panel, shortcut, parameter docs, enabled now. `filter` matches id, label, tab and panel. | +| `describe_command` | `id` | One command's parameter docs (`params`) and, for commands with a typed contract (`solid.box`, `solid.extrude` and `engine.describe` so far), the JSON Schemas (2020-12) of its parameters (`input`) and of a successful result (`output`); `null` for the others. The same as `execute` `engine.describe {command}`. | | `execute` | `command`, `params?`, `verbose?` (default true) | Run any command with JSON parameters (`list_commands` shows them). Failures leave the design unchanged. A feature command replies with the feature (`feature`, `name`), every body (`bodies`) and the bodies it created, changed and removed (`created_bodies`, `changed_bodies`, `removed_bodies`). `verbose: false` uses the same compact reply as `batch`. | | `batch` | `commands: [{command, params}]`, `rollback?` (default true), `verbose?` (default true), `timings?`, `profile?` (default false) | Run steps in order, stop at the first error and undo the completed steps. The reply names the failing step (`failed.index`, `failed.command`, `failed.error`) and every result before it. `verbose: false` keeps the reply small in large designs: feature steps leave out the full body list (`created_bodies`, `changed_bodies`, `removed_bodies` stay) and sketch steps the ids they repeat outside `created`. Bridged to an app that has `engine.batch`, the whole batch is one control request (one frame of the app). Older apps, and apps showing the agent cursor, get the steps one by one. `timings: true` adds `timings: [{index, command, ms}]` for every step run, the failing one included, and `total_ms`. `profile: true` also adds each step's `profile: {boolean_ms, tessellate_ms, other_ms}`, its time in kernel booleans, in tessellation and the rest. Steps are timed where they run: in the app when bridged. An app without `engine.batch` is timed step by step, without `profile`. | | `inspect_design` | `measure?` (default true), `sketches?` (default true) | Design properties (`metadata`: project, author… and other tools' keys; set them with `execute` `document.metadata.set`), parameters, timeline (type, suppressed, rolled back, error, warning, timing), bodies (volume, area, centre of mass, bbox, face/edge/vertex counts, visible; `removed_later: true` while a sketch is being edited on a rolled-back timeline and a later feature deletes the body, which is then not shown), sketches (curves, points, constraints, profiles, DOF, solve status, visible), selection, undo depth. Hide helper sketches, bodies or construction planes with `execute` `browser.visibility` (`{items, visible}` or `{folder, visible}`), and joint glyphs with `{joints: [id or name], visible}` or `{folder: "joints", visible}` (a hidden joint still constrains and drives; `joint.list` reports each joint's `visible`). | diff --git a/scripts/param_audit.py b/scripts/param_audit.py new file mode 100644 index 000000000..1140e1603 --- /dev/null +++ b/scripts/param_audit.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python3 +"""Summarise a parameter-contract audit: the calls that break a command's contract, by issue. + +Usage: param_audit.py AUDIT_DIR [OUT_JSON] + +AUDIT_DIR is the directory `SOLIDCRAFT_PARAM_AUDIT` named for a test run built with the engine's +`param-audit` feature (see crates/engine/src/schema/record.rs). Each process writes one +audit-.jsonl, repeating a signature's line as its count grows, so this keeps the highest +count per signature in each file and adds the files up. + +The report has three parts: + SUCCEEDS TODAY calls that work now and that strict would refuse: a form the contract is + missing (fix the contract) or a mistake the handler ignores (fix the caller) + ALREADY FAILS calls the handler rejects anyway + REFUSED calls strict refused (tests that run with strict on) + +OUT_JSON, when given, receives every signature with its summed count. +""" +import json +import sys +from collections import Counter, defaultdict +from pathlib import Path + + +def load(audit_dir): + signatures = {} + malformed = [] + files = sorted(audit_dir.glob("audit-*.jsonl")) + for f in files: + per_file = {} + for n, line in enumerate(f.read_text(encoding="utf-8", errors="replace").splitlines(), 1): + if not line.strip(): + continue + try: + r = json.loads(line) + key = json.dumps([r["command"], r["issues"], r["outcome"], r["source"]]) + except (json.JSONDecodeError, KeyError) as e: + malformed.append(f"{f.name}:{n}: {e}") + continue + if key not in per_file or r["count"] > per_file[key]["count"]: + per_file[key] = r + for key, r in per_file.items(): + if key in signatures: + signatures[key] = {**signatures[key], "count": signatures[key]["count"] + r["count"]} + else: + signatures[key] = dict(r) + return files, signatures, malformed + + +def by_issue(records): + counts = Counter() + examples = defaultdict(list) + for r in records: + for issue in r["issues"]: + counts[(r["command"], issue)] += r["count"] + if len(examples[(r["command"], issue)]) < 3: + examples[(r["command"], issue)].append(f"{r['source']}: {r['sample_params'][:300]}") + return counts, examples + + +def main(): + if len(sys.argv) not in (2, 3): + sys.exit(__doc__.split("\n\n")[1]) + files, signatures, malformed = load(Path(sys.argv[1])) + records = list(signatures.values()) + parts = [ + ("SUCCEEDS TODAY, STRICT WOULD REFUSE", [r for r in records if r["outcome"] == "ok"], True), + ("ALREADY FAILS TODAY", [r for r in records if r["outcome"] not in ("ok", "refused")], False), + ("REFUSED BY STRICT", [r for r in records if r["outcome"] == "refused"], False), + ] + print(f"files: {len(files)} signatures: {len(signatures)} malformed lines: {len(malformed)}") + for m in malformed[:10]: + print(" malformed:", m) + for label, part, show_examples in parts: + counts, examples = by_issue(part) + print(f"\n== {label}: {len(part)} signatures, at least {sum(r['count'] for r in part)} calls") + for (command, issue), n in counts.most_common(): + print(f" {n:>7} {command:14} {issue}") + if show_examples: + for e in examples[(command, issue)]: + print(f" e.g. {e}") + if len(sys.argv) == 3: + out = {"signatures": records, "malformed": malformed} + Path(sys.argv[2]).write_text(json.dumps(out, indent=1), encoding="utf-8") + + +if __name__ == "__main__": + main() From ac757960dcc23d5beb521033d2c581c3ab9ef86c Mon Sep 17 00:00:00 2001 From: SS-EN <84559909+SS-EN@users.noreply.github.com> Date: Tue, 20 Oct 2026 10:45:27 +0000 Subject: [PATCH 185/225] Boolean retries: a candidate whose edges run far outside the operands is discarded unmeshed (#3020) (#3185) The retries in boolean_whole_inner mesh every candidate to compare its volume. A nudged union at the coarse tolerance could come out with a face on a cone whose trim loop ran metres along the cone's continuation (edges up to 12.7 m outside a 155 mm part); meshing it took seconds to minutes per face and once never finished, though its volume (+-1e10 mm3) failed the check anyway. check() first samples the candidate's edges (16 per edge) and discards a candidate with a point further outside the operands' mesh box than 5% of their size (or a non-finite point): no edge of a union, cut or intersection can lie there. The reason goes into the new BooleanDiagnostics::rejected (omitted from JSON when empty). Results of sound candidates are unchanged. On the reporting design the PitchTail join drops from 18.7 s to 4.3 s with the same result; the regression tests synthesize a cone face whose loop runs off its surface. Co-authored-by: Claude Opus 5.5 --- crates/kernel/src/boolean_diagnostics.rs | 51 +++++++++ crates/kernel/src/candidate_reach.rs | 127 +++++++++++++++++++++ crates/kernel/src/candidate_reach_tests.rs | 106 +++++++++++++++++ crates/kernel/src/lib.rs | 1 + crates/kernel/src/ops.rs | 9 +- docs/robustness.md | 5 + 6 files changed, 298 insertions(+), 1 deletion(-) create mode 100644 crates/kernel/src/candidate_reach.rs create mode 100644 crates/kernel/src/candidate_reach_tests.rs diff --git a/crates/kernel/src/boolean_diagnostics.rs b/crates/kernel/src/boolean_diagnostics.rs index dc3e0100e..b160980fb 100644 --- a/crates/kernel/src/boolean_diagnostics.rs +++ b/crates/kernel/src/boolean_diagnostics.rs @@ -77,6 +77,11 @@ impl BooleanFallback { pub struct BooleanDiagnostics { pub events: Vec, pub truncated: bool, + /// Why candidates of the retries that led to the result were discarded before they were + /// measured (#3020: a coarse candidate whose edges run far outside the operands, which + /// meshing never finished). Left out of the report when there are none. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub rejected: Vec, } impl BooleanDiagnostics { @@ -88,6 +93,18 @@ impl BooleanDiagnostics { } } + fn push_rejected(&mut self, reason: String) { + // A candidate checked twice (picked, then taken) is noted once. + if self.rejected.contains(&reason) { + return; + } + if self.rejected.len() < MAX_EVENTS { + self.rejected.push(reason); + } else { + self.truncated = true; + } + } + /// Why the result is not verified, when it ignores a place where the bodies seem to pass /// through each other ([`BooleanStrategy::UnverifiedShortcut`]). pub fn unverified(&self) -> Option { @@ -163,10 +180,24 @@ pub(crate) fn record(event: BooleanFallback) { }); } +/// Note a candidate discarded before it was measured, and why. +pub(crate) fn reject(reason: String) { + REPORT.with(|cell| { + if let Ok(mut report) = cell.try_borrow_mut() + && let Some(report) = report.as_mut() + { + report.push_rejected(reason); + } + }); +} + pub(crate) fn merge(report: BooleanDiagnostics) { for event in report.events { record(event); } + for reason in report.rejected { + reject(reason); + } if report.truncated { REPORT.with(|cell| { if let Ok(mut report) = cell.try_borrow_mut() @@ -197,6 +228,26 @@ mod tests { assert!(capture_boolean_diagnostics(|| {}).1.events.is_empty()); } + /// Candidates discarded unmeasured (#3020) are reported with the attempt that led to the + /// result, once each, and not at all when there are none. + #[test] + fn rejected_candidates_follow_the_accepted_attempt() { + let (_, report) = capture_boolean_diagnostics(|| { + let (_, discarded) = capture_boolean_diagnostics(|| reject("from a discarded attempt".into())); + assert_eq!(discarded.rejected.len(), 1); + let (_, accepted) = capture_boolean_diagnostics(|| { + reject("runaway edge".into()); + reject("runaway edge".into()); + record(BooleanFallback::new(BooleanStrategy::ToolNudge)); + }); + merge(accepted); + }); + assert_eq!(report.rejected, vec!["runaway edge".to_string()]); + assert!(serde_json::to_string(&report).unwrap().contains("\"rejected\":[\"runaway edge\"]")); + let plain = capture_boolean_diagnostics(|| record(BooleanFallback::new(BooleanStrategy::ToolNudge))).1; + assert!(!serde_json::to_string(&plain).unwrap().contains("rejected")); + } + /// Only retries whose result can differ from the exact one make a warning; the summary /// lists every retry. #[test] diff --git a/crates/kernel/src/candidate_reach.rs b/crates/kernel/src/candidate_reach.rs new file mode 100644 index 000000000..75992c4ff --- /dev/null +++ b/crates/kernel/src/candidate_reach.rs @@ -0,0 +1,127 @@ +//! A boolean candidate whose edges run far outside its operands is discarded before it is +//! meshed (#3020). +//! +//! The retries of a boolean mesh every candidate to measure its volume. A candidate made at a +//! coarse tolerance can come out with an edge that leaves the body altogether: in the design of +//! #3020, a face of a revolved dovetail (a cone) got a trim loop several metres long on a part +//! 155 mm across, its points kilometres from the cone, and meshing that face never finished. +//! Its volume (±1e10 mm³) would have failed the check anyway; only measuring it hung. +//! +//! Every edge of a union, a cut or an intersection lies on the operands' faces, within the +//! boolean's tolerance (a small fraction of their size). So a candidate with a point of an edge +//! further outside the box the operands span than [`MARGIN`] of their size is not a result of +//! the operation, whatever its faces are, and it is discarded without meshing it. That needs no +//! search for the edge's points on its faces' surfaces, which is the very thing that runs away +//! on such a face. + +use std::collections::HashSet; + +use solidcraft_geom::{Aabb3, Mesh, Vec3}; +use truck_modeling as mt; + +use crate::body::{Body, from_p3}; + +#[cfg(test)] +#[path = "candidate_reach_tests.rs"] +mod tests; + +/// Samples along each edge, ends included: a runaway edge leaves the body over a good part of +/// its length (the loop of #3020 was thousands of times the body's size). +const EDGE_SAMPLES: u32 = 16; + +/// How far an edge of a candidate may run outside the box of the operands' meshes, as a fraction +/// of the operands' size: well above any boolean tolerance (2e-3 of the size at the coarsest) and +/// the temporary face shifts of the retries (1.4e-2 of it), well below the metres a runaway edge +/// spans. +pub(crate) const MARGIN: f64 = 0.05; + +/// Where a candidate's edges may run when the operands could not be meshed: their edges only +/// bound them loosely (a sphere's seam spans half of it), so the box of those grows by their +/// whole size. +const MARGIN_UNMESHED: f64 = 1.0; + +/// The box the operands of a boolean span, grown by the room a result's edges may take. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Reach { + bounds: Aabb3, + margin: f64, +} + +impl Reach { + /// The reach of operands `a` and `b` of size `size`, from their meshes where both were made + /// (`meshes`), else from their edges. `None` when neither gives a finite box. + pub(crate) fn new(a: &Body, b: &Body, meshes: (Option<&Mesh>, Option<&Mesh>), size: f64) -> Option { + let mut bounds = Aabb3::EMPTY; + let margin = match meshes { + (Some(ma), Some(mb)) => { + ma.positions.iter().chain(&mb.positions).for_each(|p| bounds.add(*p)); + MARGIN * size + } + _ => { + for body in [a, b] { + edge_points(body, |p| { + bounds.add(p); + true + })?; + } + MARGIN_UNMESHED * size + } + }; + (!bounds.is_empty() && margin.is_finite() && margin > 0.0).then_some(Reach { bounds, margin }) + } + + /// Why `candidate` cannot be a result of a boolean of these operands: an edge of it runs + /// further outside them than the margin, or has a point that is not finite. `None` when its + /// edges stay within reach, and when they could not be sampled (it is then meshed and + /// checked as before). + pub(crate) fn runaway(&self, candidate: &Body) -> Option { + let (lo, hi) = (self.bounds.min, self.bounds.max); + let mut worst = 0.0f64; + let mut infinite = false; + edge_points(candidate, |p| { + if !p.is_finite() { + infinite = true; + return false; + } + let outside = Vec3::new(excess(p.x, lo.x, hi.x), excess(p.y, lo.y, hi.y), excess(p.z, lo.z, hi.z)).len(); + worst = worst.max(outside); + true + })?; + if infinite { + Some("a result whose edge has points that are not finite".into()) + } else if worst > self.margin { + Some(format!("a result whose edge runs {worst:.4e} mm outside the operands (more than {:.4e} mm), not meshed to measure it", self.margin)) + } else { + None + } + } +} + +/// How far `x` lies outside `[lo, hi]`. +fn excess(x: f64, lo: f64, hi: f64) -> f64 { + (lo - x).max(x - hi).max(0.0) +} + +/// Visits [`EDGE_SAMPLES`] points along each edge of `body` (once per edge) until `visit` says +/// stop. `None` when the curves could not be evaluated. +fn edge_points(body: &Body, mut visit: impl FnMut(Vec3) -> bool) -> Option<()> { + crate::guard("candidate edges", || { + use mt::{BoundedCurve, ParametricCurve}; + let mut seen = HashSet::new(); + for edge in body.solid.edge_iter() { + if !seen.insert(edge.id()) { + continue; + } + let curve = edge.curve(); + let (t0, t1) = curve.range_tuple(); + for i in 0..=EDGE_SAMPLES { + let t = t0 + (t1 - t0) * f64::from(i) / f64::from(EDGE_SAMPLES); + if !visit(from_p3(curve.subs(t))) { + return Ok(()); + } + } + } + Ok(()) + }) + .ok() +} diff --git a/crates/kernel/src/candidate_reach_tests.rs b/crates/kernel/src/candidate_reach_tests.rs new file mode 100644 index 000000000..e237b6b6d --- /dev/null +++ b/crates/kernel/src/candidate_reach_tests.rs @@ -0,0 +1,106 @@ +//! A boolean candidate with a trim loop that runs off its surface is discarded fast (#3020). +//! +//! In the design of #3020 a coarse candidate of a nudged union came out with a face on a cone +//! (a revolved line: its profile parameter bounded to [0, 1], its angle periodic) whose trim +//! loop left the cone and ran thousands of profile lengths along its continuation, kilometres +//! from the part. Meshing that face to measure the candidate never finished. Here such a face +//! is made on purpose: the check finds its edge outside the operands without meshing it. + +use std::time::{Duration, Instant}; + +use solidcraft_geom::Vec3; +use truck_modeling::{self as mt, ParametricSurface, builder}; + +use super::{MARGIN, Reach}; +use crate::body::Body; + +/// The cone of the report: a profile line 2 mm out and 4 mm up from radius 20 mm (its length, +/// √20 mm, is the |∂S/∂u| measured on the runaway face), turned about Z. +fn cone() -> mt::Surface { + let profile = mt::Curve::Line(mt::Line(mt::Point3::new(20.0, 0.0, 0.0), mt::Point3::new(22.0, 0.0, 4.0))); + mt::Surface::RevolutedCurve(mt::Processor::new(mt::RevolutedCurve::by_revolution(profile, mt::Point3::new(0.0, 0.0, 0.0), mt::Vector3::unit_z()))) +} + +/// A solid of one face of `surface` bounded by straight edges through `corners`, given in the +/// surface's parameters and moved `off` mm off it along its normal. +fn face_body(surface: &mt::Surface, corners: &[(f64, f64, f64)]) -> Body { + use mt::ParametricSurface3D; + let vertices: Vec = corners.iter().map(|&(u, v, off)| builder::vertex(surface.subs(u, v) + surface.normal(u, v) * off)).collect(); + let edges: Vec = (0..vertices.len()).map(|i| builder::line(&vertices[i], &vertices[(i + 1) % vertices.len()])).collect(); + let face = mt::Face::new(vec![edges.into_iter().collect()], surface.clone()); + let solid = mt::Solid::new_unchecked(vec![vec![face].into()]); + Body::new(solid).unwrap() +} + +/// The operands: a plate and the cone's own patch, which spans u in [0, 1] (radius 20-22 mm, +/// 4 mm high) over a quarter turn. +fn operands() -> (Body, Body) { + let plate = crate::box_solid(Vec3::new(-30.0, -30.0, -6.0), Vec3::new(30.0, 30.0, 0.0)).unwrap(); + let patch = face_body(&cone(), &[(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 1.5, 0.0), (0.0, 1.5, 0.0)]); + (plate, patch) +} + +fn reach(a: &Body, b: &Body) -> Reach { + let size = a.size().max(b.size()); + let meshes = (a.tessellate_with(size * 5e-4, true).unwrap(), b.tessellate_with(size * 5e-4, true).unwrap()); + Reach::new(a, b, (Some(&meshes.0), Some(&meshes.1)), size).unwrap() +} + +/// The runaway face: on the cone, its loop leaves the patch at u = 0 and follows the cone's +/// continuation out to u = -2450 (as the logged loop did, -2452 … 1349), 1.5 mm off it, and +/// back. +fn runaway() -> Body { + face_body(&cone(), &[(1.0, 0.2, 0.0), (1.0, 1.3, 0.0), (0.0, 1.3, 0.0), (-2450.0, 0.9, 1.5), (-2450.0, 0.6, 1.5), (0.0, 0.2, 0.0)]) +} + +#[test] +fn a_candidate_with_a_trim_loop_off_its_surface_is_rejected_fast() { + let (a, b) = operands(); + let reach = reach(&a, &b); + let candidate = runaway(); + let start = Instant::now(); + let reason = reach.runaway(&candidate); + let took = start.elapsed(); + let reason = reason.expect("an edge kilometres outside the operands"); + assert!(reason.contains("outside the operands"), "{reason}"); + assert!(took < Duration::from_secs(1), "{took:?}"); +} + +#[test] +fn sound_candidates_stay_within_reach() { + let (a, b) = operands(); + let reach = reach(&a, &b); + // The operands themselves, and a union of the plate with a cylinder standing on it. + assert_eq!(reach.runaway(&a), None); + assert_eq!(reach.runaway(&b), None); + let post = crate::cylinder(Vec3::new(0.0, 0.0, -1.0), Vec3::Z, 5.0, 20.0).unwrap(); + let reach = self::reach(&a, &post); + let union = crate::boolean(&a, &post, crate::BoolOp::Union).unwrap().unwrap(); + assert_eq!(reach.runaway(&union), None); +} + +#[test] +fn an_edge_just_past_the_margin_is_out_of_reach() { + let (a, b) = operands(); + let size = a.size().max(b.size()); + let reach = reach(&a, &b); + // A box reaching past the plate's side by twice the margin, and one within it. + let top = Vec3::new(30.0, 30.0, 0.0); + let past = crate::box_solid(Vec3::new(0.0, 0.0, -6.0), top + Vec3::X * (2.0 * MARGIN * size)).unwrap(); + let within = crate::box_solid(Vec3::new(0.0, 0.0, -6.0), top + Vec3::X * (0.5 * MARGIN * size)).unwrap(); + assert!(reach.runaway(&past).is_some()); + assert_eq!(reach.runaway(&within), None); +} + +/// The bound on a loop's span is in lengths of a bounded parameter's range: a plane's unit box +/// is only a chart, so a plate thousands of millimetres across (its loops thousands of units +/// wide) still meshes, as does a long cylinder. +#[test] +fn large_faces_still_mesh() { + let plate = crate::box_solid(Vec3::new(-2500.0, -2500.0, 0.0), Vec3::new(2500.0, 2500.0, 3.0)).unwrap(); + let rod = crate::cylinder(Vec3::ZERO, Vec3::Z, 0.5, 3000.0).unwrap(); + for body in [plate, rod] { + assert!(!body.tessellate_with(0.05, true).unwrap().triangles.is_empty()); + assert_eq!(body.unmeshed_faces(), 0); + } +} diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rs index 6f852793d..b68810477 100644 --- a/crates/kernel/src/lib.rs +++ b/crates/kernel/src/lib.rs @@ -28,6 +28,7 @@ mod boundary; mod boundary_network; mod bridge; mod build; +mod candidate_reach; #[cfg(test)] mod chamfer_sides_curved_tests; mod clearance; diff --git a/crates/kernel/src/ops.rs b/crates/kernel/src/ops.rs index 9309b6336..3339aa851 100644 --- a/crates/kernel/src/ops.rs +++ b/crates/kernel/src/ops.rs @@ -7,7 +7,7 @@ use truck_modeling as mt; use std::collections::HashMap; use crate::body::{Body, Solid, from_p3}; -use crate::boolean_diagnostics::{BooleanFallback, BooleanStrategy, capture_boolean_diagnostics, merge, record}; +use crate::boolean_diagnostics::{BooleanFallback, BooleanStrategy, capture_boolean_diagnostics, merge, record, reject}; use crate::boolean_record::{self as recorded, Traced}; use crate::{KernelError, Result, guard, record}; @@ -1289,6 +1289,9 @@ where _ => (volume(a), volume(b)), }; let slack = 2e-3 * (va + vb) + 1e-9; + // Where a result's edges can run: a candidate with an edge far outside the operands is + // discarded before it is meshed (#3020), as meshing such a face may never finish. + let reach = crate::candidate_reach::Reach::new(a, b, (meshes.0.as_ref(), meshes.1.as_ref()), size); // Volume bounds, then membership against the operands (catches misclassified pieces), on // one mesh of the result. Returns (plausible, volume). // Shells that touch were never fused: coincident back-to-back faces leave the intersection @@ -1306,6 +1309,10 @@ where && crate::coplanar::faces_touch(a, b) }; let check = |r: &Body| -> (bool, f64) { + if let Some(reason) = reach.as_ref().and_then(|reach| reach.runaway(r)) { + reject(reason); + return (false, f64::NAN); + } let Ok(mr) = r.tessellate_with(tol_m, true) else { return (false, f64::NAN) }; let v = mr.measure().volume; let bounds = plausible(v, op, va, vb, slack); diff --git a/docs/robustness.md b/docs/robustness.md index 168601cea..ebb88d888 100644 --- a/docs/robustness.md +++ b/docs/robustness.md @@ -99,6 +99,11 @@ tolerances and leaves the exact result, so it is recorded but not warned about. `timeline.inspect` and `doc.inspect` expose every retry in the feature's `boolean_diagnostics`, including the strategy and the applied translation, rotation, face offset and tessellation tolerance in millimetres/radians. +Candidates those retries discarded before measuring them are listed in its +`rejected`, with the reason: a candidate with an edge further outside the +operands than 5% of their size cannot be their union, cut or intersection, +and meshing one (a trim loop running metres along a cone's continuation) +could take minutes or never finish (#3020). A common shift of both operands is reversed on the result. Coincident-face separation and bore offsets describe temporary working geometry; they are not From a3f28c0b89dccf9da07bd2cc21d40ac4a485c057 Mon Sep 17 00:00:00 2001 From: fugazister Date: Tue, 20 Oct 2026 10:47:26 +0000 Subject: [PATCH 186/225] Look At frames the sketch's geometry, not its plane's origin (#3198) (#3199) * claim: #3198 Co-Authored-By: Claude Opus 5.5 * Look At frames the sketch's geometry, not its plane's origin (#3198) Look At on a sketch (its menu, Ctrl+8, the navigation bar, entering a sketch) centred the view on the sketch plane's origin and kept the zoom, so a sketch drawn away from it - an imported part placed far from the origin - ended up out of view. Both paths now share onto_sketch: centred on the sketch's bounds, zoomed out when they would not fit (never in); an empty sketch keeps the plane's origin. Co-Authored-By: Claude Opus 5.5 * Register the Look At tests Co-Authored-By: Claude Opus 5.5 * Look At tests: Vec3::len Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/context_menu.rs | 3 +- crates/ui-egui/src/dialogs.rs | 24 ++++++++++- crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/look_at_tests.rs | 62 +++++++++++++++++++++++++++++ 4 files changed, 87 insertions(+), 4 deletions(-) create mode 100644 crates/ui-egui/src/look_at_tests.rs diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index b71b08e23..871e4e600 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -1233,8 +1233,7 @@ pub fn run_item(app: &mut SolveApp, item: &Item, at: Pos2) { "ui.lookAt" => { let st = app.session.world_state(); if let Some(ss) = id_of(&p, "sketch").and_then(|id| st.sketch(id)) { - let mut to = app.cam.looking_from(ss.plane.normal()); - to.target = ss.plane.origin; + let to = crate::dialogs::onto_sketch(app.cam.looking_from(ss.plane.normal()), ss); app.animate_to(to); } } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 532279f4e..a815204a5 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -3689,11 +3689,31 @@ fn look_at_sketch_from(app: &mut SolveApp, again: bool) { let x = ss.plane.x; to.yaw = if n.z > 0.0 { (-x.y).atan2(x.x) } else { x.y.atan2(x.x) }; } - to.target = ss.plane.origin; - app.animate_to(to); + app.animate_to(onto_sketch(to, ss)); } } +/// `to` (already facing the sketch) moved onto sketch `ss` (#3198): centred on its geometry, and +/// zoomed out when that would not fit in the view; it never zooms in, so a zoom the user chose +/// stays. A sketch without geometry keeps its plane's origin. Centring on the origin alone left a +/// sketch drawn away from it (a part placed far from the origin, as imports often are) out of view. +pub(crate) fn onto_sketch(mut to: solidcraft_engine::render::Camera, ss: &solidcraft_engine::doc::SolvedSketch) -> solidcraft_engine::render::Camera { + let Some((lo, hi)) = ss.sketch.bounds() else { + to.target = ss.plane.origin; + return to; + }; + let mut b = Aabb3::default(); + for p in [lo, hi, solidcraft_engine::geom::Vec2::new(lo.x, hi.y), solidcraft_engine::geom::Vec2::new(hi.x, lo.y)] { + b.add(ss.plane.to_world(p)); + } + let keep = to.distance; + to.fit(&b); + if keep.is_finite() && keep > to.distance { + to.distance = keep; + } + to +} + /// The side to look from at a plane with normal `n`: its own side, or with `again` the other /// side when the view already looks from `n`, so a second Look At turns the view round (#1886). pub(crate) fn facing(app: &SolveApp, n: Vec3, again: bool) -> Vec3 { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 437f9fed0..60870c71f 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -74,6 +74,8 @@ pub mod keymap; mod linked_source; #[cfg(test)] mod loft_rails_dialog_tests; +#[cfg(test)] +mod look_at_tests; mod material_card_review; #[cfg(test)] mod measurement_ui_tests; diff --git a/crates/ui-egui/src/look_at_tests.rs b/crates/ui-egui/src/look_at_tests.rs new file mode 100644 index 000000000..753f8422c --- /dev/null +++ b/crates/ui-egui/src/look_at_tests.rs @@ -0,0 +1,62 @@ +//! Look At on a sketch (#3198): it faces the sketch and frames its geometry, not its plane's +//! origin, so a sketch drawn far from the origin (an imported part placed there) stays in view. + +use serde_json::json; +use solidcraft_engine::geom::Vec3; + +use crate::scenario::Harness; + +/// A 20 × 30 rectangle at x 330–350, y 475–505 on the XY plane raised 8 mm, as an imported part +/// rebuilt where it was placed; the camera jumps straight to where Look At sends it. +fn far_sketch() -> (Harness, u64) { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.preferences.look_at_anim = false; + h.app.run("sketch.create", json!({"plane": "XY", "offset": 8, "name": "Far"})).unwrap(); + h.app.run("sketch.rectangle.two_point", json!({"p0": [330, 475], "p1": [350, 505]})).unwrap(); + h.app.run("sketch.finish", json!({})).unwrap(); + let id = h.app.session.doc.find_feature("Far").map(|f| f.id).unwrap(); + (h, id) +} + +fn near(a: Vec3, b: Vec3) -> bool { + (a - b).len() < 1e-6 +} + +/// The camera's view half-width (mm) the rectangle needs: its half diagonal. +const HALF_DIAGONAL: f64 = 18.027_756_377_319_946; + +#[test] +fn the_menus_look_at_frames_a_sketch_far_from_the_origin() { + let (mut h, id) = far_sketch(); + h.app.cam.distance = 20.0; + let items = crate::context_menu::items(&h.app, &crate::context_menu::Target::Sketch { id }); + let look = items.iter().find(|i| i.id == "ui.lookAt").cloned().expect("the sketch menu has Look At"); + crate::context_menu::run_item(&mut h.app, &look, egui::Pos2::ZERO); + assert!(near(h.app.cam.target, Vec3::new(340.0, 490.0, 8.0)), "centred on the rectangle, not the plane's origin: {:?}", h.app.cam.target); + assert!((h.app.cam.back() - Vec3::new(0.0, 0.0, 1.0)).len() < 1e-6, "facing the sketch from above"); + let need = HALF_DIAGONAL / 0.4 * 1.15; + assert!(h.app.cam.distance >= need - 1e-6, "zoomed out to fit it: {} < {need}", h.app.cam.distance); +} + +#[test] +fn look_at_on_the_active_sketch_keeps_a_wider_zoom() { + let (mut h, id) = far_sketch(); + h.app.session.active_sketch = Some(id); + h.app.cam.distance = 5000.0; + crate::dialogs::look_at_sketch(&mut h.app); + assert!(near(h.app.cam.target, Vec3::new(340.0, 490.0, 8.0)), "{:?}", h.app.cam.target); + assert_eq!(h.app.cam.distance, 5000.0, "it never zooms in on a zoom the user chose"); +} + +#[test] +fn an_empty_sketch_keeps_its_planes_origin() { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.preferences.look_at_anim = false; + h.app.run("sketch.create", json!({"plane": "XY", "offset": 8})).unwrap(); + h.app.cam.distance = 123.0; + crate::dialogs::look_at_sketch(&mut h.app); + assert!(near(h.app.cam.target, Vec3::new(0.0, 0.0, 8.0)), "{:?}", h.app.cam.target); + assert_eq!(h.app.cam.distance, 123.0); +} From 83ecf91ae71ee38cd91854d56132ac2286d14603 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Tue, 20 Oct 2026 11:00:11 +0000 Subject: [PATCH 187/225] perf: autosave writes on a worker thread (#3044) (#3139) Autosave serialised and wrote the whole design on the window's thread: about 120 ms on the Prusa Core One assembly (its 61 MB STEP text inside), a hitch once per interval after every change, and more once saves keep the evaluated model. A tick now takes a snapshot of the design (its Arc and what is hidden) and writes it on a worker; a later tick takes up the outcome, and no new write starts while one runs. Crash replays rebase onto the autosave only when the design is still the one written. Save and close still wait for the write, and dropping the autosaver lets a running write end. Co-authored-by: Claude Opus 5.5 --- crates/engine/src/recovery.rs | 189 ++++++++++++++++++++++++++++++---- 1 file changed, 171 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/recovery.rs b/crates/engine/src/recovery.rs index dcda910e0..a61161557 100644 --- a/crates/engine/src/recovery.rs +++ b/crates/engine/src/recovery.rs @@ -174,6 +174,61 @@ pub struct Autosaver { last: Option<(Arc, crate::Visibility)>, last_at: Instant, has_entry: bool, + /// The autosave being written on a worker thread: the design and what was hidden as it + /// started, and the outcome once the thread ends. A large design takes long enough to write + /// (and longer with its evaluated model) that the window must not wait for it. + writing: Option, +} + +/// An autosaver going away with a write still running (the app quit without closing it) lets the +/// write end first, so the entry it leaves is whole. +impl Drop for Autosaver { + fn drop(&mut self) { + if let Some(w) = self.writing.take() { + let _ = w.done.recv(); + } + } +} + +/// An autosave a worker thread is writing. +struct Writing { + doc: Arc, + visibility: crate::Visibility, + done: std::sync::mpsc::Receiver>, +} + +/// What one autosave writes, taken from the session in an instant. +struct Snapshot { + dir: PathBuf, + id: String, + doc: Arc, + visibility: crate::Visibility, + path: Option, +} + +impl Snapshot { + /// Write the design and its entry (the slow part: serialising and compressing the design). + fn write(&self) -> Result<()> { + let io = |e: std::io::Error| EngineError::Other(format!("autosave: {e}")); + let bytes = if self.visibility.is_empty() { + solidcraft_io::write_design_container(&self.doc)? + } else { + let mut doc = (*self.doc).clone(); + doc.visibility = self.visibility.clone(); + solidcraft_io::write_design_container(&doc)? + }; + solidcraft_io::write_atomic(&file(&self.dir, &self.id, solidcraft_io::DESIGN_EXT), &bytes, false).map_err(io)?; + let entry = Entry { + id: self.id.clone(), + path: self.path.clone(), + name: self.doc.name.clone(), + saved_at: unix_now(), + features: self.doc.features.len(), + }; + let meta = serde_json::to_vec_pretty(&entry).map_err(|e| EngineError::Other(e.to_string()))?; + solidcraft_io::write_atomic(&file(&self.dir, &self.id, "json"), &meta, false).map_err(io)?; + Ok(()) + } } impl Autosaver { @@ -198,12 +253,62 @@ impl Autosaver { let id = format!("{}-{}-{seq}", unix_now(), std::process::id()); let lock = OpenOptions::new().create(true).truncate(false).write(true).open(file(dir, &id, "lock")).map_err(io)?; lock.lock().map_err(io)?; - Ok(Autosaver { dir: dir.to_path_buf(), id, interval, lock: Some(lock), last: None, last_at: Instant::now(), has_entry: false }) + Ok(Autosaver { dir: dir.to_path_buf(), id, interval, lock: Some(lock), last: None, last_at: Instant::now(), has_entry: false, writing: None }) } /// Autosave now if the design has unsaved changes not written yet (and drop the entry when - /// nothing is unsaved). Returns whether it wrote. + /// nothing is unsaved), waiting for the write. Returns whether it wrote. pub fn save(&mut self, s: &Session) -> Result { + self.finish(s, true)?; + let Some(snapshot) = self.begin(s) else { return Ok(false) }; + let written = snapshot.write(); + self.written(s, snapshot.doc, snapshot.visibility, written)?; + Ok(true) + } + + /// Autosave when the interval has passed, or right away after a big operation. The design + /// is written on a worker thread; true when this call started a write. + pub fn tick(&mut self, s: &Session, big: bool) -> Result { + // A write still running: nothing new starts until it has ended. + if !self.finish(s, false)? { + return Ok(false); + } + if !big && self.last_at.elapsed() < self.interval { + return Ok(false); + } + let Some(snapshot) = self.begin(s) else { return Ok(false) }; + #[cfg(not(target_arch = "wasm32"))] + { + let (tx, rx) = std::sync::mpsc::channel(); + let (doc, visibility) = (snapshot.doc.clone(), snapshot.visibility.clone()); + let started = std::thread::Builder::new().name("autosave".into()).spawn(move || { + let _ = tx.send(snapshot.write()); + }); + match started { + Ok(_) => { + self.writing = Some(Writing { doc, visibility, done: rx }); + Ok(true) + } + // No thread to write on: write here, as before. + Err(_) => { + let snapshot = Snapshot { dir: self.dir.clone(), id: self.id.clone(), doc, visibility, path: s.path.clone() }; + let written = snapshot.write(); + self.written(s, snapshot.doc, snapshot.visibility, written)?; + Ok(true) + } + } + } + #[cfg(target_arch = "wasm32")] + { + let written = snapshot.write(); + self.written(s, snapshot.doc, snapshot.visibility, written)?; + Ok(true) + } + } + + /// What the next autosave writes: `None` when there is nothing to write (and, with nothing + /// unsaved, the entry has been dropped). + fn begin(&mut self, s: &Session) -> Option { self.last_at = Instant::now(); if !s.is_dirty() { if self.has_entry { @@ -215,28 +320,45 @@ impl Autosaver { self.last = None; // Crash replays start from the saved file (or a new design) from here. crate::crash::rebased(s, s.path.as_deref().map(Path::new), false); - return Ok(false); + return None; } if self.last.as_ref().is_some_and(|(l, v)| (Arc::ptr_eq(l, &s.doc) || **l == *s.doc) && *v == s.visibility) { - return Ok(false); + return None; } - let io = |e: std::io::Error| EngineError::Other(format!("autosave: {e}")); - let bytes = solidcraft_io::write_design_container(&s.design())?; - solidcraft_io::write_atomic(&file(&self.dir, &self.id, solidcraft_io::DESIGN_EXT), &bytes, false).map_err(io)?; - let entry = - Entry { id: self.id.clone(), path: s.path.clone(), name: s.doc.name.clone(), saved_at: unix_now(), features: s.doc.features.len() }; - let meta = serde_json::to_vec_pretty(&entry).map_err(|e| EngineError::Other(e.to_string()))?; - solidcraft_io::write_atomic(&file(&self.dir, &self.id, "json"), &meta, false).map_err(io)?; - self.last = Some((s.doc.clone(), s.visibility.clone())); - self.has_entry = true; - // Crash replays start from this autosave from here. - crate::crash::rebased(s, Some(&file(&self.dir, &self.id, solidcraft_io::DESIGN_EXT)), true); + Some(Snapshot { dir: self.dir.clone(), id: self.id.clone(), doc: s.doc.clone(), visibility: s.visibility.clone(), path: s.path.clone() }) + } + + /// The running write's outcome, once it has one (`wait`: wait for it). True when no write + /// is running any more. + fn finish(&mut self, s: &Session, wait: bool) -> Result { + let Some(w) = self.writing.take() else { return Ok(true) }; + let outcome = if wait { + w.done.recv().unwrap_or_else(|_| Err(EngineError::Other("autosave: the writer stopped".into()))) + } else { + match w.done.try_recv() { + Ok(r) => r, + Err(std::sync::mpsc::TryRecvError::Empty) => { + self.writing = Some(w); + return Ok(false); + } + Err(std::sync::mpsc::TryRecvError::Disconnected) => Err(EngineError::Other("autosave: the writer stopped".into())), + } + }; + self.written(s, w.doc, w.visibility, outcome)?; Ok(true) } - /// Autosave when the interval has passed, or right away after a big operation. - pub fn tick(&mut self, s: &Session, big: bool) -> Result { - if big || self.last_at.elapsed() >= self.interval { self.save(s) } else { Ok(false) } + /// A write of `doc` (with `visibility`) ended with `outcome`. + fn written(&mut self, s: &Session, doc: Arc, visibility: crate::Visibility, outcome: Result<()>) -> Result<()> { + outcome?; + self.has_entry = true; + // Crash replays start from this autosave from here, unless the design changed while it + // was written: the journal then keeps the commands since its older start. + if Arc::ptr_eq(&s.doc, &doc) { + crate::crash::rebased(s, Some(&file(&self.dir, &self.id, solidcraft_io::DESIGN_EXT)), true); + } + self.last = Some((doc, visibility)); + Ok(()) } /// Closing the app: with nothing unsaved the entry goes; otherwise it stays for the next @@ -311,6 +433,37 @@ mod tests { let _ = fs::remove_dir_all(&d); } + /// A tick doesn't wait for the autosave (#3044): it starts the write on a worker and + /// returns; the outcome is taken up by a later tick, and nothing new starts meanwhile. The + /// entry is the design as it was when the write started, even when it changed since. + #[test] + fn autosave_writes_on_a_worker_and_a_later_tick_takes_it_up() { + let d = dir("worker"); + let mut s = Session::default(); + let mut a = Autosaver::new(&d, Duration::ZERO).unwrap(); + s.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10})).unwrap(); + let written = s.doc.clone(); + assert!(a.tick(&s, false).unwrap(), "a write started"); + assert!(a.writing.is_some(), "and runs on its own thread"); + s.execute("solid.box", &json!({"length": 5, "width": 5, "height": 5, "center": [20, 0, 2.5], "operation": "new"})).unwrap(); + // Ticks while it runs start nothing; the one that finds it ended takes it up and, + // the design having changed since, starts the next write. + let began = Instant::now(); + while !a.tick(&s, false).unwrap() { + assert!(a.writing.is_some(), "nothing new starts while the write runs"); + assert!(began.elapsed() < Duration::from_secs(30)); + std::thread::sleep(Duration::from_millis(1)); + } + assert!(a.has_entry); + assert!(a.last.as_ref().is_some_and(|(doc, _)| Arc::ptr_eq(doc, &written)), "the first write was the design as it started"); + assert!(a.writing.as_ref().is_some_and(|w| Arc::ptr_eq(&w.doc, &s.doc)), "the next one writes the changed design"); + drop(a); + let found = orphans(&d); + assert_eq!(found.len(), 1); + assert_eq!(load(&d, &found[0].id).unwrap().0, *s.doc, "dropping the autosaver lets its write end"); + let _ = fs::remove_dir_all(&d); + } + #[test] fn an_app_restarted_in_the_same_second_still_offers_the_crashed_ones_work() { let d = dir("restart"); From f6cf8ceaad27a1aa0bf87ab59697af5a1967f723 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Tue, 20 Oct 2026 11:01:50 +0000 Subject: [PATCH 188/225] perf: an instanced STEP part's first instance shares its display mesh (#2814) (#3047) Later instances of a part showed a mesh shared through the first instance, but the first instance meshed its own, so every repeated part was meshed twice. The first instance of a part placed more than once now shows the shared mesh too; a part placed once keeps its own (no second copy). Co-authored-by: Claude Opus 5.5 --- crates/kernel/src/step_in/mod.rs | 19 ++++++++++++------- crates/kernel/src/step_in/tests.rs | 4 +++- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/crates/kernel/src/step_in/mod.rs b/crates/kernel/src/step_in/mod.rs index f95bee134..6889e3d0c 100644 --- a/crates/kernel/src/step_in/mod.rs +++ b/crates/kernel/src/step_in/mod.rs @@ -265,9 +265,11 @@ struct Reader { /// Items the file converts exactly once (see `index`): keeping their parts would hold a /// second copy of the whole import for nothing. once: HashSet, - /// An item placed more than once: its first instance's display, shared by the later ones + /// An item placed more than once: its first instance's display, shared by every instance /// (with the placement that first instance had), so the part is meshed once. shown: HashMap, mt::Matrix4)>, + /// How many planned solids place each item. + uses: HashMap, /// An item placed more than once: read and oriented where the file defines it, so each /// later instance is only placed (orienting meshes the whole part). oriented: HashMap>, @@ -313,6 +315,7 @@ impl Reader { unreadable: HashMap::new(), once: HashSet::new(), shown: HashMap::new(), + uses: HashMap::new(), oriented: HashMap::new(), used_items: HashSet::new(), node_items: HashSet::new(), @@ -650,6 +653,7 @@ impl Reader { // The node lists the planned solid; it becomes a body index once converted. out.push(self.plan.len()); self.plan.push(Planned { item, units: u, batch: id }); + *self.uses.entry(item).or_default() += 1; } } "MAPPED_ITEM" => { @@ -778,15 +782,16 @@ impl Reader { .map(|face| Some(crate::FaceSource::Imported { item, face: *face, payload_sha256: None, producer: None })) .collect(); let body = body.with_face_sources(Some(std::sync::Arc::new(identities))); - // A later instance of an item shows its first instance's mesh, placed. + // Every instance of a part placed more than once shows its first instance's + // mesh, placed (the first one too: meshing its own would mesh the part twice). let body = match self.shown.get(&item) { Some((shared, first)) => body.with_display_of(shared.clone(), to_array(&mat_mul(&m, &rigid_inverse(first)))), - None => { - if !self.once.contains(&item) { - self.shown.insert(item, (Arc::new(crate::body::SharedDisplay::new(body.clone())), m)); - } - body + None if self.uses.get(&item).is_some_and(|n| *n > 1) => { + let shared = Arc::new(crate::body::SharedDisplay::new(body.clone())); + self.shown.insert(item, (shared.clone(), m)); + body.with_display_of(shared, to_array(&mt::Matrix4::from_scale(1.0))) } + None => body, }; self.bodies.push(ImportedBody { name, diff --git a/crates/kernel/src/step_in/tests.rs b/crates/kernel/src/step_in/tests.rs index bba7fbf4b..80cfb0d5e 100644 --- a/crates/kernel/src/step_in/tests.rs +++ b/crates/kernel/src/step_in/tests.rs @@ -767,7 +767,9 @@ fn distinct_parts_convert_together_across_instances() { fn later_instances_show_the_first_instances_mesh_placed() { let imp = step_import(&two_instance_assembly()).unwrap(); let (first, second) = (&imp.bodies[0].body, &imp.bodies[1].body); - assert!(first.display_of.is_none() && second.display_of.is_some()); + // The first instance shows the shared mesh as well (meshing its own would mesh the part twice). + let (Some(a), Some(b)) = (first.display_of.as_deref(), second.display_of.as_deref()) else { panic!("both instances share a display") }; + assert!(std::sync::Arc::ptr_eq(&a.0, &b.0)); let a = first.reference_display_mesh_angular(0.01, crate::DISPLAY_ANGLE).unwrap(); let b = second.reference_display_mesh_angular(0.01, crate::DISPLAY_ANGLE).unwrap(); assert_eq!(a.triangles, b.triangles); From 349a6c6fc4424430b2a78a1e451ca09042c56274 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Tue, 20 Oct 2026 11:01:56 +0000 Subject: [PATCH 189/225] perf: a copy placed for showing doesn't turn its revolved faces again (#3044) (#3104) Moving an occurrence places every body under it again, and each placed copy searched every revolved face for where it sits to turn it away from its seam, although its source had been turned already. On the Prusa Core One assembly that search was most of the 12.7 s a move of the top occurrence took. A body now records that its revolved faces are turned, and world placement (`place_matrix`) skips the search for such a body. Modelling moves (pattern copies, hole tools) keep `transform_matrix`, which still turns them in the copy's own frame: where a face wraps all the way round the turn it finds depends on those coordinates, and later booleans depend on it. Co-authored-by: Claude Opus 5.5 --- crates/doc/src/eval.rs | 2 +- crates/kernel/src/body.rs | 15 +++++++++++++-- crates/kernel/src/fair.rs | 1 + crates/kernel/src/lib.rs | 2 +- crates/kernel/src/meshbody.rs | 2 ++ crates/kernel/src/native.rs | 1 + crates/kernel/src/ops.rs | 14 ++++++++++++++ crates/kernel/src/outline.rs | 1 + crates/kernel/src/record.rs | 3 ++- crates/kernel/src/splitface.rs | 2 ++ crates/kernel/src/surfaces.rs | 1 + crates/kernel/src/tests.rs | 32 ++++++++++++++++++++++++++++++++ 12 files changed, 71 insertions(+), 5 deletions(-) diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 052bf9241..82ccad82d 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -5854,7 +5854,7 @@ impl PlacedBodies { fresh.plan_mesh = placed.plan_mesh.clone(); fresh } - None => match kernel::transform_matrix(&b.body, *m) { + None => match kernel::place_matrix(&b.body, *m) { Ok(body) => { let mut fresh = ModelBody::new(name, body, b.feature); fresh.mesh_placement = placed_mesh::PlacedMesh::new(b, m).map(Arc::new); diff --git a/crates/kernel/src/body.rs b/crates/kernel/src/body.rs index 55627e628..be11a1199 100644 --- a/crates/kernel/src/body.rs +++ b/crates/kernel/src/body.rs @@ -53,6 +53,10 @@ pub struct Body { /// Meshes of this solid kept for reuse, set by [`Body::keeping_meshes`]: a check that /// intersects one large body with many small ones meshes it at the same tolerance each time. pub(crate) meshes: Option>, + /// Its revolved faces were turned away from their seams (see `rephase_revolved`), so a + /// placed copy, which keeps them where they are, need not turn them again: searching every + /// revolved face of every placed occurrence was most of the time moving an assembly took. + pub(crate) phased: bool, } /// The meshes made of one solid (see [`Body::keeping_meshes`]), by tolerance, angle and @@ -413,6 +417,8 @@ fn refined_with_cache(pm: &PolygonMesh, surf: &mt::Surface, tol: f64, memoize: b /// (same geometry) so the face sits around angle π, well away from the wrap. fn rephase_revolved(solid: Solid) -> Solid { use mt::{BoundedCurve, ParametricCurve, SearchNearestParameter}; + #[cfg(test)] + REPHASED.with(|n| n.set(n.get() + 1)); let r = guard("rephase", || { let mut changed = false; let mut shells = Vec::new(); @@ -531,6 +537,8 @@ fn polyline_mid(pts: &[Vec3]) -> (Vec3, f64) { thread_local! { /// Solids [`Body::new`] meshed on this thread to orient them (tests count the work an import does). pub(crate) static ORIENTED: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Solids `rephase_revolved` searched on this thread. + pub(crate) static REPHASED: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Deflection the orientation mesh uses: coarse enough for a large solid, fine enough that a @@ -623,6 +631,7 @@ impl Body { history: None, display_of: None, meshes: None, + phased: true, }) } @@ -631,11 +640,12 @@ impl Body { /// unless it mirrors them, so its orientation is read from the matrix rather than meshed /// again. Only for closed solids; `coarse` is the input's cached missing-face count, which a /// rigid placement preserves exactly. - pub(crate) fn new_placed(solid: Solid, flip: bool, coarse: Option<(f64, usize)>) -> Result { + /// `phased`: the solid was placed from a body whose revolved faces are turned already. + pub(crate) fn new_placed(solid: Solid, flip: bool, coarse: Option<(f64, usize)>, phased: bool) -> Result { if solid.boundaries().is_empty() { return Err(KernelError::Failed("empty result".into())); } - Body::placed_as_is(rephase_revolved(solid), flip, coarse) + Body::placed_as_is(if phased { solid } else { rephase_revolved(solid) }, flip, coarse) } /// [`Body::new_placed`] for a solid whose revolved faces were already turned away from @@ -662,6 +672,7 @@ impl Body { history: None, display_of: None, meshes: None, + phased: true, }) } diff --git a/crates/kernel/src/fair.rs b/crates/kernel/src/fair.rs index 2c65620b1..95bbfa533 100644 --- a/crates/kernel/src/fair.rs +++ b/crates/kernel/src/fair.rs @@ -920,6 +920,7 @@ pub fn fair_faces(body: &Body, faces: &[usize], opts: &FairOptions) -> Result<(B result.volume = Some(std::sync::Arc::new(std::sync::Mutex::new(None))); result.coarse_missing = None; result.history = None; + result.phased = false; let faces: Vec = (0..all.len()).map(|i| crate::record::from_face(0, i, if picked.contains(&i) { Change::Modified } else { Change::Kept })).collect(); let result = crate::record::attach(result, &[crate::record::Operand::new(body)], Some(faces), std::collections::HashMap::new())?; diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rs index b68810477..4d01043c1 100644 --- a/crates/kernel/src/lib.rs +++ b/crates/kernel/src/lib.rs @@ -193,7 +193,7 @@ pub use native::{decode_native_body, encode_native_body, native_preview_mesh}; pub use offset::with_same_surface; pub use ops::{ BoolOp, boolean, can_join_all_touching_faces, can_join_touching_faces, compound_disjoint_extrusions, half_space, is_planar, join_apart, - split_by_plane, transform, transform_matrix, union_apart, with_attempt_budget, + place_matrix, split_by_plane, transform, transform_matrix, union_apart, with_attempt_budget, }; pub use polybool::{faceted_boolean, planar_boolean}; pub use polyhedron::{HalfSpace, convex_polyhedron, draft, offset_faces, shell}; diff --git a/crates/kernel/src/meshbody.rs b/crates/kernel/src/meshbody.rs index 170c0273c..07436cf3e 100644 --- a/crates/kernel/src/meshbody.rs +++ b/crates/kernel/src/meshbody.rs @@ -114,6 +114,7 @@ pub fn mesh_body(positions: &[Vec3], triangles: &[[u32; 3]]) -> Result { history: None, display_of: None, meshes: None, + phased: false, regularization_protected: false, }) } @@ -212,6 +213,7 @@ impl Body { history: None, display_of: None, meshes: None, + phased: false, regularization_protected: self.regularization_protected, }) } diff --git a/crates/kernel/src/native.rs b/crates/kernel/src/native.rs index 0b1af58a5..97a3bc60f 100644 --- a/crates/kernel/src/native.rs +++ b/crates/kernel/src/native.rs @@ -115,6 +115,7 @@ pub fn decode_native_body(bytes: &[u8]) -> Result { history: None, display_of: None, meshes: None, + phased: false, regularization_protected: false, }; metadata::apply(&mut body, saved.metadata)?; diff --git a/crates/kernel/src/ops.rs b/crates/kernel/src/ops.rs index 3339aa851..238ee378b 100644 --- a/crates/kernel/src/ops.rs +++ b/crates/kernel/src/ops.rs @@ -2095,6 +2095,19 @@ pub(crate) fn rigid_placement(m: &[[f64; 4]; 4]) -> bool { /// Affine transform by a column-major 4x4 matrix (rotations, translations, reflections). pub fn transform_matrix(body: &Body, m: [[f64; 4]; 4]) -> Result { + transform_matrix_keeping(body, m, false) +} + +/// [`transform_matrix`] for showing a body where an assembly places it (world placement): the +/// revolved faces stay turned the way the body has them instead of being searched again for +/// every placed copy (#3044). A modelling operation keeps using [`transform_matrix`]: where a +/// face wraps all the way round, the turn it finds depends on the copy's own coordinates, and +/// booleans on the copy depend on that. +pub fn place_matrix(body: &Body, m: [[f64; 4]; 4]) -> Result { + transform_matrix_keeping(body, m, body.phased) +} + +fn transform_matrix_keeping(body: &Body, m: [[f64; 4]; 4], phased: bool) -> Result { if m.iter().flatten().any(|x| !x.is_finite()) { return Err(KernelError::Invalid("non-finite transform".into())); } @@ -2129,6 +2142,7 @@ pub fn transform_matrix(body: &Body, m: [[f64; 4]; 4]) -> Result { edges.as_ref(), det3(&m) < 0.0, rigid_placement(&m).then_some(body.coarse_missing).flatten(), + phased, )?; Ok(placed.with_color(body.color()).with_paint(body.paint().cloned()).with_face_sources(sources).inherit_regularization_protection(body)) }) diff --git a/crates/kernel/src/outline.rs b/crates/kernel/src/outline.rs index 66c73ace4..e65d9331f 100644 --- a/crates/kernel/src/outline.rs +++ b/crates/kernel/src/outline.rs @@ -514,6 +514,7 @@ fn divided(body: &Body, faces: &[usize], other: &[(mt::Edge, Piece)], fr: &Frame regularization_protected: true, display_of: None, meshes: None, + phased: false, }; Ok(Some(record::rebuilt_body(split, &[&body.solid], &rec))) } diff --git a/crates/kernel/src/record.rs b/crates/kernel/src/record.rs index 5f6e2702c..f05de1c58 100644 --- a/crates/kernel/src/record.rs +++ b/crates/kernel/src/record.rs @@ -146,8 +146,9 @@ pub(crate) fn build_placed( edges: Option<&HashMap>>, flip: bool, coarse: Option<(f64, usize)>, + phased: bool, ) -> Result { - Ok(traced(Body::new_placed(solid, flip, coarse)?, counts, faces, edges)) + Ok(traced(Body::new_placed(solid, flip, coarse, phased)?, counts, faces, edges)) } /// The origins of `body`'s edges by identity, from its history `h` (edges in its edge order). diff --git a/crates/kernel/src/splitface.rs b/crates/kernel/src/splitface.rs index 9e5194c16..6575c2c5b 100644 --- a/crates/kernel/src/splitface.rs +++ b/crates/kernel/src/splitface.rs @@ -646,6 +646,7 @@ pub(crate) fn split_edges_at(body: &Body, points: &[Vec3]) -> Result { history: None, display_of: None, meshes: None, + phased: false, regularization_protected: true, }; Ok(crate::record::rebuilt_body(split, &[&body.solid], &rec)) @@ -1182,6 +1183,7 @@ pub(crate) fn split_any(body: &Body, faces: &[usize], tool: &SplitTool) -> Resul history: None, display_of: None, meshes: None, + phased: false, regularization_protected: true, }; Ok((crate::record::rebuilt_body(split, &[&body.solid], &imp.rec), imp)) diff --git a/crates/kernel/src/surfaces.rs b/crates/kernel/src/surfaces.rs index f47fd0d0d..87be14147 100644 --- a/crates/kernel/src/surfaces.rs +++ b/crates/kernel/src/surfaces.rs @@ -43,6 +43,7 @@ fn surface_of(shell: mt::Shell) -> Body { history: None, display_of: None, meshes: None, + phased: false, regularization_protected: false, } } diff --git a/crates/kernel/src/tests.rs b/crates/kernel/src/tests.rs index 2aaa7738e..d7546cbc5 100644 --- a/crates/kernel/src/tests.rs +++ b/crates/kernel/src/tests.rs @@ -2980,3 +2980,35 @@ fn an_attempt_budget_stops_the_boolean_and_is_shared_by_nesting() { assert!(inner && !after); assert!(boolean(&a, &b, BoolOp::Intersect).unwrap().is_some()); } + +/// Moving an assembly places every body of it again: a copy placed for showing keeps its +/// revolved faces where its source turned them, so placing searches none of them again (that search was most +/// of the time an occurrence move took on a large assembly, #3044), and the copy is the same +/// solid as placing a freshly turned one. +#[test] +fn placing_a_body_does_not_turn_its_revolved_faces_again() { + let body = cylinder(Vec3::new(1.0, 2.0, 0.0), Vec3::Z, 3.0, 5.0).unwrap(); + assert!(body.phased); + let m = [[0.0, 1.0, 0.0, 0.0], [-1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [10.0, 20.0, 30.0, 1.0]]; + crate::body::REPHASED.with(|c| c.set(0)); + let mut placed = body.clone(); + for _ in 0..10 { + placed = crate::place_matrix(&placed, m).unwrap(); + } + assert_eq!(crate::body::REPHASED.with(|c| c.get()), 0, "no placement searched the revolved faces again"); + // A modelling move (a pattern's copy, a hole's tool) still turns them in its own frame. + let _ = crate::transform_matrix(&body, m).unwrap(); + assert_eq!(crate::body::REPHASED.with(|c| c.get()), 1); + crate::body::REPHASED.with(|c| c.set(0)); + assert!(placed.phased); + let unphased = Body { phased: false, ..body.clone() }; + let mut turned = unphased; + for _ in 0..10 { + turned = crate::place_matrix(&turned, m).unwrap(); + } + assert!(crate::body::REPHASED.with(|c| c.get()) > 0, "a body not known to be turned still is"); + let (a, b) = (measure(&placed).unwrap(), measure(&turned).unwrap()); + assert!((a.volume - b.volume).abs() < 1e-9 * a.volume && (a.area - b.area).abs() < 1e-9 * a.area); + assert_eq!(a.faces, b.faces); + assert!(a.bbox.min.dist(b.bbox.min) < 1e-9 && a.bbox.max.dist(b.bbox.max) < 1e-9); +} From c83446c6c959230986b4f69c240175f075fe3705 Mon Sep 17 00:00:00 2001 From: AlF Date: Tue, 20 Oct 2026 11:07:50 +0000 Subject: [PATCH 190/225] Fix issue 3120, import of STEP file not correct (#3208) --- crates/kernel/src/step_in/conic_tests.rs | 41 ++++++++++++++++++++++++ crates/kernel/src/step_in/geom.rs | 19 ++++++++++- crates/kernel/src/step_in/tests.rs | 37 +++++++++++++++++++++ docs/step-import.md | 5 +++ 4 files changed, 101 insertions(+), 1 deletion(-) diff --git a/crates/kernel/src/step_in/conic_tests.rs b/crates/kernel/src/step_in/conic_tests.rs index f5942541a..05d4ddf47 100644 --- a/crates/kernel/src/step_in/conic_tests.rs +++ b/crates/kernel/src/step_in/conic_tests.rs @@ -18,6 +18,47 @@ const CONTEXT: &str = "#90=ADVANCED_BREP_SHAPE_REPRESENTATION('',(#81),#91);\n#9 /// Height of the cone pieces: the 45° cone `x² + y² = z²` up to `z = H`. const H: f64 = 10.0; +#[test] +fn extruded_ellipse_seam_uses_profile_angles_for_oblique_sweeps() { + use mt::{MetricSpace, ParametricSurface}; + + let text = format!( + "{HEAD} +#1=CARTESIAN_POINT('',(10.,-20.,3.)); +#2=DIRECTION('',(0.,0.,1.)); +#3=DIRECTION('',(1.,0.,0.)); +#4=AXIS2_PLACEMENT_3D('',#1,#2,#3); +#5=ELLIPSE('',#4,9.,4.); +#6=DIRECTION('',(0.5,0.25,1.)); +#7=VECTOR('',#6,1.); +#8=SURFACE_OF_LINEAR_EXTRUSION('',#5,#7); +{TAIL}" + ); + let ex = p21::parse(&text).unwrap(); + let cx = Ctx { ex: &ex, len: 1.0, ang: 1.0, tol: 1e-6 }; + let origin = mt::Point3::new(10.0, -20.0, 3.0); + let d = mt::Vector3::new(0.5, 0.25, 1.0).normalize(); + let point = |angle: f64, h: f64| origin + mt::Vector3::new(9.0 * angle.cos(), 4.0 * angle.sin(), 0.0) + d * h; + let extent: Vec<_> = [-0.04, 0.0, 0.04].into_iter().flat_map(|a| [point(a, 0.0), point(a, 10.0)]).collect(); + for seam in [Vec::new(), vec![point(-0.04, 0.0), point(-0.04, 10.0)]] { + let surface = geom::surface(&cx, 8, &extent, &seam, true, 0).unwrap(); + for i in 0..=16 { + for j in 0..=4 { + let q = surface.subs(i as f64 / 16.0, j as f64 / 4.0) - origin; + let q = q - d * (q.z / d.z); + assert!(((q.x / 9.0).powi(2) + (q.y / 4.0).powi(2) - 1.0).abs() < 1e-12); + } + } + let start = surface.subs(0.0, 0.5); + let q = start - d * ((start.z - origin.z) / d.z); + if seam.is_empty() { + assert!(q.distance(point(std::f64::consts::PI, 0.0)) < 1e-9); + } else { + assert!(q.distance(point(-0.04, 0.0)) < 1e-9); + } + } +} + fn rel(a: f64, b: f64) -> f64 { (a - b).abs() / b.abs().max(1e-9) } diff --git a/crates/kernel/src/step_in/geom.rs b/crates/kernel/src/step_in/geom.rs index c0ecd7c26..f61bb09dc 100644 --- a/crates/kernel/src/step_in/geom.rs +++ b/crates/kernel/src/step_in/geom.rs @@ -1126,7 +1126,24 @@ pub(crate) fn surface(cx: &Ctx, id: u64, extent: &[mt::Point3], seam: &[mt::Poin let g = curve(cx, p.get(1).and_then(Param::as_ref_id).ok_or("extrusion without profile")?, depth + 1)?; let (_, v) = ent_of(cx, p.get(2), "extrusion vector")?; let d = direction(cx, v.params().get(1).and_then(Param::as_ref_id).ok_or("VECTOR without direction")?)?; - let nurbs: mt::NurbsCurve = match bounded_curve(&g, extent)? { + let profile = match &g { + CurveGeo::Conic { f, a, b } if d.dot(f.z).abs() > 1e-12 => { + // Keep the closed profile's parameter seam outside the trim. Otherwise a + // tooth tip crossing it can mesh as almost the whole extruded ellipse. + let dz = d.dot(f.z); + let angle = |p: &mt::Point3| { + let q = p - f.o; + let q = q - d * (q.dot(f.z) / dz); + (q.dot(f.y) / b).atan2(q.dot(f.x) / a) + }; + let start = common_angle(seam.iter().map(angle)) + .or_else(|| largest_gap(&extent.iter().map(angle).collect::>()).map(|(mid, _)| mid)) + .unwrap_or(0.0); + mt::Curve::NurbsCurve(conic_arc(f, *a, *b, start, TAU)) + } + _ => bounded_curve(&g, extent)?, + }; + let nurbs: mt::NurbsCurve = match profile { mt::Curve::Line(l) => mt::BSplineCurve::new(mt::KnotVec::bezier_knot(1), vec![l.0, l.1]).into(), mt::Curve::BSplineCurve(c) => c.into(), mt::Curve::NurbsCurve(c) => c, diff --git a/crates/kernel/src/step_in/tests.rs b/crates/kernel/src/step_in/tests.rs index 80cfb0d5e..c7c294c3a 100644 --- a/crates/kernel/src/step_in/tests.rs +++ b/crates/kernel/src/step_in/tests.rs @@ -1709,3 +1709,40 @@ fn explicit_outer_bound_crossing_a_closed_nurbs_seam_stays_trimmed() { assert!((mesh.measure().area - 42.0).abs() < 0.01, "sense={sense}: area {}", mesh.measure().area); } } + +#[test] +fn extruded_ellipse_patch_crossing_profile_seam_stays_trimmed() { + for (sense, outer) in [(true, true), (false, true), (true, false)] { + for radius in [9.0, 3000.0] { + let text = shallow_cylinder_patch_at_radius(sense, outer, radius); + let old = format!("#5=CYLINDRICAL_SURFACE('',#4,{radius});"); + let angle = 3.0 / radius; + let surface = format!( + "#5=SURFACE_OF_LINEAR_EXTRUSION('',#35,#18); +#35=ELLIPSE('',#36,{radius},{radius}); +#36=AXIS2_PLACEMENT_3D('',#1,#2,#37); +#37=DIRECTION('',({},{},0.));", + angle.cos(), + angle.sin() + ); + assert!(text.contains(&old)); + let text = text.replacen(&old, &surface, 1); + let imported = step_import(&text).unwrap(); + assert_eq!(imported.warnings, ["solid 'Strip': imported as an open body (the shell is not closed)"]); + assert_eq!(imported.bodies.len(), 1); + let body = &imported.bodies[0].body; + assert_eq!(imported.bodies[0].file_faces, 1); + let plan = body.display_plan(0.01).unwrap(); + for mesh in [ + plan.evaluate(), + body.display_mesh_angular(0.01, crate::DISPLAY_ANGLE).unwrap(), + body.reference_display_mesh_angular(0.01, crate::DISPLAY_ANGLE).unwrap(), + body.tessellate(0.01).unwrap(), + ] { + assert!(!mesh.triangles.is_empty()); + assert!(mesh.bounds().diagonal() < 10.0, "radius={radius}, sense={sense}, outer={outer}: {:?}", mesh.bounds()); + assert!((mesh.measure().area - 42.0).abs() < 0.1, "radius={radius}, sense={sense}, outer={outer}: area {}", mesh.measure().area); + } + } + } +} diff --git a/docs/step-import.md b/docs/step-import.md index 3e7ef7dc1..c87d84b39 100644 --- a/docs/step-import.md +++ b/docs/step-import.md @@ -36,6 +36,11 @@ Designs saved before imports made components keep their Import where it is (no c Read: manifold solid breps (with voids), faceted breps, shell-based surface models; planes, cylinders, cones, spheres, tori, B-spline and rational B-spline surfaces (with knots, Bézier, uniform, quasi-uniform), surfaces of revolution and linear extrusion, trimmed surfaces; lines, circles, ellipses, hyperbolas and parabolas (as exact rational curves, which export writes back as exact rational B-splines), B-spline curves, polylines, trimmed/surface/seam curves; length and angle units (SI prefixes, conversion-based units such as inches); product names (body names come from the solid's name, else the product's; `names` below chooses); surface colours; assemblies (next-assembly-usage occurrences placed by item-defined transformations, and mapped items) — the product tree is kept in the feature and becomes the import's components (above). Files are untrusted: sizes, entity counts and nesting are capped and every kernel call is guarded. What cannot be read becomes a warning on the feature (a face left out gives an open body); not read yet: offset surfaces, pcurve-only edges. +Extruded circular and elliptical faces keep their profile's parameter seam outside +the face trim, or on an explicit seam edge. Narrow faces such as rounded gear tooth +tips therefore stay narrow through the full thickness instead of wrapping around +the supporting ellipse in the middle. + ## Files from other CAD systems Files from different systems differ in which way is up and in what they call their solids. `doc.open`, `file.insert_step` and the MCP `open` tool take two options for STEP and IGES files; without them a file comes in as written. From 2ace233cd47daa3740594a3dd693ed036a53ab1e Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Tue, 20 Oct 2026 11:33:11 +0000 Subject: [PATCH 191/225] Regenerate THIRD-PARTY-LICENSES.txt and docs/features.md [skip ci] --- THIRD-PARTY-LICENSES.txt | 76 +++++++++++++++++++++++++++++----------- docs/features.md | 1 + 2 files changed, 57 insertions(+), 20 deletions(-) diff --git a/THIRD-PARTY-LICENSES.txt b/THIRD-PARTY-LICENSES.txt index e4e5d94d2..8791710f1 100644 --- a/THIRD-PARTY-LICENSES.txt +++ b/THIRD-PARTY-LICENSES.txt @@ -1,6 +1,6 @@ Third-party software in SolidCraft -SolidCraft (the desktop app, solidcraft-cli and the web app) is built from the 553 crates below. +SolidCraft (the desktop app, solidcraft-cli and the web app) is built from the 560 crates below. Generated by `cargo xtask licences` from Cargo.lock and the crates' own licence files. SolidCraft's own licence is in LICENSE-MIT and LICENSE-APACHE, and NOTICE. @@ -114,6 +114,7 @@ dlib 0.5.3 (MIT) document-features 0.2.12 (MIT OR Apache-2.0) downcast-rs 1.2.1 (MIT/Apache-2.0) dpi 0.1.2 (Apache-2.0 AND MIT) +dyn-clone 1.0.20 (MIT OR Apache-2.0) ecolor 0.36.2 (MIT OR Apache-2.0) eframe 0.36.2 (MIT OR Apache-2.0) egui 0.36.2 (MIT OR Apache-2.0) @@ -332,6 +333,8 @@ read-fonts 0.41.0 (MIT OR Apache-2.0) redox_syscall 0.4.1 (MIT) redox_syscall 0.5.18 (MIT) redox_syscall 0.9.4 (MIT) +ref-cast 1.0.27 (MIT OR Apache-2.0) +ref-cast-impl 1.0.27 (MIT OR Apache-2.0) renderdoc-sys 1.1.0 (MIT OR Apache-2.0) rfd 0.17.2 (MIT) ring 0.17.14 (Apache-2.0 AND ISC) @@ -350,6 +353,8 @@ rustls-platform-verifier-android 0.2.0 (MIT OR Apache-2.0) rustls-webpki 0.103.15 (ISC) rustversion 1.0.23 (MIT OR Apache-2.0) schannel 0.1.29 (MIT) +schemars 1.2.3 (MIT) +schemars_derive 1.2.3 (MIT) scoped-tls 1.0.1 (MIT/Apache-2.0) scopeguard 1.2.0 (MIT OR Apache-2.0) secret-service 4.0.0 (MIT OR Apache-2.0) @@ -362,7 +367,9 @@ serde 1.0.229 (MIT OR Apache-2.0) serde-value 0.7.0 (MIT) serde_core 1.0.229 (MIT OR Apache-2.0) serde_derive 1.0.229 (MIT OR Apache-2.0) +serde_derive_internals 0.30.0 (MIT OR Apache-2.0) serde_json 1.0.151 (MIT OR Apache-2.0) +serde_path_to_error 0.1.20 (MIT OR Apache-2.0) serde_repr 0.1.21 (MIT OR Apache-2.0) serde_spanned 1.1.2 (MIT OR Apache-2.0) sha1 0.10.7 (MIT OR Apache-2.0) @@ -579,19 +586,21 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. adler2 2.0.1, allocator-api2 0.2.21, async-channel 2.5.0, async-executor 1.14.0, async-fs 2.2.0, async-io 2.6.0, async-lock 3.4.2, async-process 2.5.0, async-recursion 1.2.0, async-signal 0.2.14, async-task 4.7.1, async-trait 0.1.92, atomic-waker 1.1.2, blocking 1.7.0, concurrent-queue 2.5.0, -displaydoc 0.2.7, endi 1.1.1, enumn 0.1.14, event-listener 5.4.2, event-listener-strategy 0.5.4, -fastrand 2.5.0, futures-lite 2.6.1, glow 0.17.0, hermit-abi 0.5.3, itoa 1.0.18, khronos-egl 6.0.0, -lazy_static 1.5.1, linux-raw-sys 0.12.1, linux-raw-sys 0.4.15, num_enum 0.7.6, num_enum_derive -0.7.6, once_cell 1.21.4, ordered-stream 0.2.0, parking 2.2.1, pin-project 1.1.13, -pin-project-internal 1.1.13, pin-project-lite 0.2.17, piper 0.2.5, polling 3.11.0, portable-atomic -1.15.0, portable-atomic-util 0.2.8, proc-macro-crate 3.5.0, proc-macro2 1.0.107, quote 1.0.47, -rustc-hash 1.1.0, rustc-hash 2.1.3, rustix 0.38.44, rustix 1.1.5, rustversion 1.0.23, semver 1.0.28, -serde 1.0.229, serde_core 1.0.229, serde_derive 1.0.229, serde_json 1.0.151, serde_repr 0.1.21, -simd_cesu8 1.2.0, smol_str 0.2.2, syn 1.0.109, syn 2.0.119, syn 3.0.6, thiserror 1.0.69, thiserror -2.0.21, thiserror-impl 1.0.69, thiserror-impl 2.0.21, typed-path 0.12.3, typeid 1.0.3, unicode-ident -1.0.26, utf8-zero 0.8.1, wasi 0.11.1+wasi-snapshot-preview1, wasip2 1.0.4+wasi-0.2.12, wit-bindgen -0.57.1, x11-dl 2.21.0, xdg-home 1.3.0, zbus-lockstep 0.5.2, zbus-lockstep-macros 0.5.2, zbus_names -3.0.0, zmij 1.0.23, zvariant_utils 2.1.0, zvariant_utils 4.2.0 +displaydoc 0.2.7, dyn-clone 1.0.20, endi 1.1.1, enumn 0.1.14, event-listener 5.4.2, +event-listener-strategy 0.5.4, fastrand 2.5.0, futures-lite 2.6.1, glow 0.17.0, hermit-abi 0.5.3, +itoa 1.0.18, khronos-egl 6.0.0, lazy_static 1.5.1, linux-raw-sys 0.12.1, linux-raw-sys 0.4.15, +num_enum 0.7.6, num_enum_derive 0.7.6, once_cell 1.21.4, ordered-stream 0.2.0, parking 2.2.1, +pin-project 1.1.13, pin-project-internal 1.1.13, pin-project-lite 0.2.17, piper 0.2.5, polling +3.11.0, portable-atomic 1.15.0, portable-atomic-util 0.2.8, proc-macro-crate 3.5.0, proc-macro2 +1.0.107, quote 1.0.47, ref-cast 1.0.27, ref-cast-impl 1.0.27, rustc-hash 1.1.0, rustc-hash 2.1.3, +rustix 0.38.44, rustix 1.1.5, rustversion 1.0.23, semver 1.0.28, serde 1.0.229, serde_core 1.0.229, +serde_derive 1.0.229, serde_derive_internals 0.30.0, serde_json 1.0.151, serde_path_to_error 0.1.20, +serde_repr 0.1.21, simd_cesu8 1.2.0, smol_str 0.2.2, syn 1.0.109, syn 2.0.119, syn 3.0.6, thiserror +1.0.69, thiserror 2.0.21, thiserror-impl 1.0.69, thiserror-impl 2.0.21, typed-path 0.12.3, typeid +1.0.3, unicode-ident 1.0.26, utf8-zero 0.8.1, wasi 0.11.1+wasi-snapshot-preview1, wasip2 +1.0.4+wasi-0.2.12, wit-bindgen 0.57.1, x11-dl 2.21.0, xdg-home 1.3.0, zbus-lockstep 0.5.2, +zbus-lockstep-macros 0.5.2, zbus_names 3.0.0, zmij 1.0.23, zvariant_utils 2.1.0, zvariant_utils +4.2.0 ================================================================================ Permission is hereby granted, free of charge, to any @@ -1324,12 +1333,13 @@ See the License for the specific language governing permissions and limitations under the License. ================================================================================ -allocator-api2 0.2.21, async-trait 0.1.92, enumn 0.1.14, glifo 0.2.0, itoa 1.0.18, libc 0.2.190, -litrs 1.0.0, num_enum 0.7.6, num_enum_derive 0.7.6, proc-macro2 1.0.107, quote 1.0.47, rustc-hash -2.1.3, rustversion 1.0.23, semver 1.0.28, serde 1.0.229, serde_core 1.0.229, serde_derive 1.0.229, -serde_json 1.0.151, serde_repr 0.1.21, syn 2.0.119, syn 3.0.6, thiserror 1.0.69, thiserror 2.0.21, -thiserror-impl 1.0.69, thiserror-impl 2.0.21, typed-path 0.12.3, typeid 1.0.3, unicode-ident 1.0.26, -utf8-zero 0.8.1 +allocator-api2 0.2.21, async-trait 0.1.92, dyn-clone 1.0.20, enumn 0.1.14, glifo 0.2.0, itoa 1.0.18, +libc 0.2.190, litrs 1.0.0, num_enum 0.7.6, num_enum_derive 0.7.6, proc-macro2 1.0.107, quote 1.0.47, +ref-cast 1.0.27, ref-cast-impl 1.0.27, rustc-hash 2.1.3, rustversion 1.0.23, semver 1.0.28, serde +1.0.229, serde_core 1.0.229, serde_derive 1.0.229, serde_derive_internals 0.30.0, serde_json +1.0.151, serde_path_to_error 0.1.20, serde_repr 0.1.21, syn 2.0.119, syn 3.0.6, thiserror 1.0.69, +thiserror 2.0.21, thiserror-impl 1.0.69, thiserror-impl 2.0.21, typed-path 0.12.3, typeid 1.0.3, +unicode-ident 1.0.26, utf8-zero 0.8.1 ================================================================================ Apache License @@ -11783,6 +11793,32 @@ The above copyright notice and this permission notice shall be included in all c THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +================================================================================ +schemars 1.2.3, schemars_derive 1.2.3 +================================================================================ + +MIT License + +Copyright (c) 2019 Graham Esau + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + ================================================================================ scopeguard 1.2.0 ================================================================================ diff --git a/docs/features.md b/docs/features.md index 0480f1c31..bc64de564 100644 --- a/docs/features.md +++ b/docs/features.md @@ -445,6 +445,7 @@ SolidCraft's commands by area, generated by `cargo xtask features` from the comm | Command | Id | Toolbar | |---|---|---| | List Commands | `engine.commands` | – | +| Describe Command | `engine.describe` | – | ## `explode.*` From d60b438f42f35a617feda4664077a009eed68751 Mon Sep 17 00:00:00 2001 From: DuBearte <130190089+DuBearte@users.noreply.github.com> Date: Tue, 20 Oct 2026 11:21:26 +0000 Subject: [PATCH 192/225] A finished sketch shows its standalone points (#3267) (#3304) * claim: #3267 * fix(view): a finished sketch shows its standalone points (#3267) Points were drawn only for the sketch being edited, so a point placed for a hole vanished once the sketch was finished although it could still be picked. The standalone points of every finished sketch shown are now drawn. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/viewport.rs | 55 ++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 033aa3e91..1686c59ce 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -3296,6 +3296,33 @@ fn hover_highlight(app: &SolveApp, painter: &egui::Painter, proj: &Proj) { } } +/// The standalone points of the finished sketches shown (placed with Point, not a curve's +/// ends or centres), in world space: they can still be picked (a hole's centre), so they are +/// drawn too (#3267). Not the sketch's origin, projected points, or a sketch's points while it +/// hides them. +pub(crate) fn standalone_points(app: &SolveApp) -> Vec { + let st = app.session.world_state(); + let mut out = Vec::new(); + for sid in visible_sketches(app) { + if app.session.active_sketch == Some(sid) { + continue; + } + let Some(ss) = st.sketch(sid) else { continue }; + let sk = &ss.sketch; + if sk.view.hide_points { + continue; + } + let used: std::collections::HashSet = sk.curves.iter().flat_map(|c| c.kind.point_ids()).collect(); + let visible = solidcraft_engine::view::SketchPointVisibility::new(sk); + for (i, p) in sk.points.iter().enumerate().skip(1) { + if !used.contains(&i) && p.link.is_none() && visible.takes(p) { + out.push(ss.plane.to_world(p.pos)); + } + } + } + out +} + /// Sketch points and the status of the active sketch (constraint glyphs: `sketch_tools`). fn overlays(app: &SolveApp, painter: &egui::Painter, proj: &Proj) { let t = Tokens::get(); @@ -3309,6 +3336,11 @@ fn overlays(app: &SolveApp, painter: &egui::Painter, proj: &Proj) { painter.circle_stroke(pos, 6.0, Stroke::new(2.0, t.sel_edge)); } } + for p in standalone_points(app) { + if let Some(sp) = proj.to_screen(p) { + painter.rect_filled(Rect::from_center_size(sp, vec2(4.0, 4.0)), 0.0, t.sketch); + } + } let Some(sid) = app.session.active_sketch else { return }; let Some(ss) = st.sketch(sid) else { return }; let sk = &ss.sketch; @@ -6651,3 +6683,26 @@ mod grid_plane_tests { assert!(!preview_should_roll_back(&app, primary, true), "Primary must not roll the preview back while a manipulator arrow is dragged"); } } + +#[cfg(test)] +mod standalone_point_tests { + use super::*; + + /// #3267: a finished sketch's standalone points stay drawn (they can be picked for a hole); + /// its curves' ends are not added, the open sketch draws its own points, and a hidden + /// sketch draws none. + #[test] + fn a_finished_sketch_shows_its_standalone_points() { + let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + app.run("sketch.create", json!({"plane": "XY"})).unwrap(); + app.run("sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [20, 10]})).unwrap(); + app.run("sketch.point", json!({"point": [5, 4]})).unwrap(); + assert!(standalone_points(&app).is_empty(), "the open sketch draws its own points"); + app.run("sketch.finish", json!({})).unwrap(); + let points = standalone_points(&app); + assert_eq!(points.len(), 1, "only the placed point, not the rectangle's corners: {points:?}"); + assert!(points[0].dist(Vec3::new(5.0, 4.0, 0.0)) < 1e-9, "{points:?}"); + app.ui.show_sketches = false; + assert!(standalone_points(&app).is_empty(), "sketches hidden"); + } +} From 3855c4c7e28e7d5417d0042a0922b15d3af4e4e6 Mon Sep 17 00:00:00 2001 From: JEREMY Date: Tue, 20 Oct 2026 11:21:29 +0000 Subject: [PATCH 193/225] Sheet metal: two corner reliefs that would overlap are both left out (#3421) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The two reliefs that would overlap are still resolved one after the other: the second one is left out, with a note. The corners come out in flange-index order, so which of the two keeps its relief depends on the order the flanges were made in. Two corners that share an edge never come this far: each relief reaches exactly r along that edge, and a relief is refused unless 2r fits in it. Two corners that do not share one can: the square relief at a corner of 120° reaches 2r from it along the bisector, so at the two 120° corners opposite each other in a rhombus the two reach each other. Two reliefs that would overlap are now left out together, each with a note naming the other, so that which of them is cut does not depend on the order the flanges were made in. Fixes #3417. Co-authored-by: jeremymiribung-blip Co-authored-by: Claude Code --- crates/doc/src/sheet.rs | 76 ++++++++++++++++++++++++------ docs/book/src/guide/sheet-metal.md | 6 +-- 2 files changed, 65 insertions(+), 17 deletions(-) diff --git a/crates/doc/src/sheet.rs b/crates/doc/src/sheet.rs index ee1492a3e..af1653bf0 100644 --- a/crates/doc/src/sheet.rs +++ b/crates/doc/src/sheet.rs @@ -2955,22 +2955,22 @@ impl SheetBody { Err(why) => notes.push(format!("no corner relief at {}: {why}", self.shown(k.c))), } } - // The reliefs at the two ends of one edge must not overlap: the one planned later - // is left out, with a note. + // Two reliefs must not overlap. Two corners that share an edge never come here: + // each relief reaches exactly `r` along that edge, and `plan_relief` refuses + // unless `2r` fits in it. Two corners that do not share one can: the square + // relief at a corner of 120° reaches `2r` from it, along the bisector. Two that + // would overlap are left out together, each with a note naming the other, so + // that which of them is cut does not depend on the order the corners come in. let mut kept: Vec = Vec::with_capacity(planned.len()); - for p in planned { - let mut clash = None; - for q in &kept { - if convex_overlap(&q.cut, &p.cut) > 1e-9 { - clash = Some(q.corner.c); - break; - } - } + for (i, p) in planned.iter().enumerate() { + let clash = planned.iter().enumerate().find(|(j, q)| *j != i && convex_overlap(&q.cut, &p.cut) > 1e-9); match clash { - Some(at) => { - notes.push(format!("no corner relief at {}: it would overlap the relief at {}", self.shown(p.corner.c), self.shown(at))) - } - None => kept.push(p), + Some((_, q)) => notes.push(format!( + "no corner relief at {}: it would overlap the relief at {}", + self.shown(p.corner.c), + self.shown(q.corner.c) + )), + None => kept.push(p.clone()), } } for p in &kept { @@ -5593,6 +5593,54 @@ mod tests { c + bisector * (s0 / (alpha / 2.0).sin()) } + /// Two corner reliefs that would overlap are both left out. The two corners do not share an + /// edge: they are the 120° ones opposite each other in a rhombus, and the square relief at + /// each reaches 2r from it along the bisector, so the two reach each other. + #[test] + fn two_reliefs_that_would_overlap_are_both_left_out() { + // A rhombus of 120° and 60° corners, with a flange on each of its four edges. The two + // 120° corners are 12 mm apart in the trimmed base; a square relief 8 mm across reaches + // 4 mm along the edge it starts on and 8 mm along the bisector, so the two meet. + let l = 12.0 + 4.0 * 3.0f64.sqrt(); + let u = Vec2::from_angle(std::f64::consts::FRAC_PI_3); + let pts = [Vec2::new(0.0, 0.0), Vec2::new(l / 2.0, l * u.y), Vec2::new(l, 0.0), Vec2::new(l / 2.0, -l * u.y)]; + let base = || Region2 { outer: Loop2::polygon(&pts).ccw(), holes: vec![] }; + let picks = [ + Vec3::new(l / 4.0, l * u.y / 2.0, 2.0), + Vec3::new(l * 0.75, l * u.y / 2.0, 2.0), + Vec3::new(l * 0.75, -l * u.y / 2.0, 2.0), + Vec3::new(l / 4.0, -l * u.y / 2.0, 2.0), + ]; + let flange = |i: usize| EdgeFlange { pick: picks[i], height: 38.6, angle: 90f64.to_radians() }; + // The round relief reaches r from its corner and the two are 12 mm apart: it fits at both. + for shape in [ReliefShape::Round, ReliefShape::Rectangular] { + let what = format!("{shape:?} at two corners opposite each other"); + let rv = RuleValues { corner_relief_shape: shape, corner_relief: 8.0, ..alu() }; + // The same four flanges, made in another order: the corners that keep their relief + // must not depend on it. + for order in [[0, 1, 2, 3], [3, 2, 1, 0]] { + let each: Vec = order.iter().map(|&i| flange(i)).collect(); + let (s, notes) = flanges_each(base(), &rv, &each); + if shape == ReliefShape::Round { + assert!(notes.is_empty(), "{what}: {order:?}: {notes:?}"); + // A round at each of the four corners. + assert_eq!(s.base.outer.segs.len(), 8, "{what}: {order:?}: {:?}", s.base.outer.segs); + continue; + } + // The two reliefs that would overlap are both left out, each with a note naming + // the other. + assert_eq!(notes.len(), 2, "{what}: {order:?}: {notes:?}"); + for n in ¬es { + assert!(n.starts_with("no corner relief at (") && n.contains("it would overlap the relief at ("), "{what}: {notes:?}"); + } + // The two kites at the 60° corners are cut, the ones at the 120° corners are + // not: the base keeps four of its edges and gains the two kites. + assert_eq!(s.base.outer.segs.len(), 8, "{what}: {order:?}: {:?}", s.base.outer.segs); + holds_the_flat_material(&s, &what); + } + } + } + /// The corner reliefs at the corners that are not square: a 60° and a 120° one, each of the /// four shapes. The relief is cut `size / 2` from the corner along both edges, the bends stop /// there, and the flat pattern keeps one clean loop. diff --git a/docs/book/src/guide/sheet-metal.md b/docs/book/src/guide/sheet-metal.md index 60374d983..813927f0b 100644 --- a/docs/book/src/guide/sheet-metal.md +++ b/docs/book/src/guide/sheet-metal.md @@ -57,9 +57,9 @@ square the round follows the angle of the base and the square becomes a kite, it square to the edges. Changing the shape in a rule changes the parts made with that rule. A relief that doesn't fit (under 0.01 mm across, leaving nothing of a bend, or reaching as far from its corner as another edge of the base is) is left out, and the flange feature reports a -warning saying where. The reliefs at the corners of one edge are cut together, so a corner's -relief does not depend on the order the corners are cut in; two of them that would overlap -leave the second one out, with a warning. +warning saying where. The reliefs at all the corners are cut together, so a corner's relief +does not depend on the order the corners are cut in; two of them that would overlap are both +left out, each with a warning saying which the other is. ```json {"command":"sheet.manage_rules","params":{"name":"Sheet 2 mm","thickness":"2 mm","k_factor":0.5, From c5b637600c6355dca499ebd80530ac09a729e465 Mon Sep 17 00:00:00 2001 From: rlartot <94693724+rlartot@users.noreply.github.com> Date: Tue, 20 Oct 2026 11:21:32 +0000 Subject: [PATCH 194/225] Chamfer: one pick follows a straight edge's curved tangent chain at any part size (#2672) (#3295) * claim: #2672 Co-Authored-By: Claude Sonnet 5.5 * Chamfer: one pick follows a straight edge's curved tangent chain at any size (#2672) chamfer_tool built a single-edge cutter for a straight edge even when the edge runs on tangentially into an arc (a slot side into its end). The cutter's overshoot (max(2*distance, 1% of the part size)) is probed for material beyond the edge ends; on a small part the probe hit the arc's material and the cutter was refused, so the blend followed the whole chain. Past a bounding-box diagonal of about 200 mm the overshoot cleared the arc, the cutter was accepted, and only the straight edge was chamfered, silently. A straight edge whose smooth chain contains a curved edge no longer gets a cutter; it takes the chain-following blend, as at small sizes and as a fillet does. Co-Authored-By: Claude Sonnet 5.5 --------- Co-authored-by: Claude Sonnet 5.5 --- crates/kernel/src/blend.rs | 15 ++++++++- crates/kernel/tests/chamfer_curved_holder.rs | 32 ++++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/crates/kernel/src/blend.rs b/crates/kernel/src/blend.rs index 5d8b87b00..cf85cbf82 100644 --- a/crates/kernel/src/blend.rs +++ b/crates/kernel/src/blend.rs @@ -2430,7 +2430,20 @@ impl Cutter { } pub(crate) fn chamfer_tool(cur: &Body, p: Vec3, s: f64, k: usize) -> Result { - chamfer_tool_sides(cur, p, s, None, k) + let tool = chamfer_tool_sides(cur, p, s, None, k)?; + // A straight edge that runs on into a curved one (a slot's side into its end arc) is one + // tangent chain: the cutter would chamfer the straight part only, and whether its overshoot + // reaches the next edge's material depends on the size of the part (#2672). The blend + // follows the whole chain, as it does for a fillet. + let all = Body::unique_edges(&cur.solid); + let curved_chain = all + .get(tool.edge) + .and_then(|e| smooth_chain(&cur.solid, e)) + .is_some_and(|ids| all.iter().any(|e| ids.contains(&e.id()) && !matches!(e.curve(), mt::Curve::Line(_)))); + if curved_chain { + return Err(unsupported("a straight edge continued by a curved one is chamfered with its chain")); + } + Ok(tool) } /// A straight plane/cylinder edge has one constant chamfer section. Sweep its cutter diff --git a/crates/kernel/tests/chamfer_curved_holder.rs b/crates/kernel/tests/chamfer_curved_holder.rs index 00e715efc..b1616a372 100644 --- a/crates/kernel/tests/chamfer_curved_holder.rs +++ b/crates/kernel/tests/chamfer_curved_holder.rs @@ -88,3 +88,35 @@ fn a_chamfer_that_uses_up_the_holder_top_is_refused() { let body = holder(); assert!(chamfer(&body, &[Vec3::new(10.0, 10.0, 60.0)], 30.0).is_err()); } + +/// A plate of side `plate` with a 50 x 10 mm stadium boss, 10 mm tall, joined on top. +fn plate_with_stadium(plate: f64) -> Body { + let base = solidcraft_kernel::box_solid(Vec3::new(-plate / 2.0, -plate / 2.0, 0.0), Vec3::new(plate / 2.0, plate / 2.0, 10.0)).unwrap(); + let segs = vec![ + Seg2::Line { a: Vec2::new(-20.0, -5.0), b: Vec2::new(20.0, -5.0) }, + Seg2::Arc { center: Vec2::new(20.0, 0.0), radius: 5.0, start: -PI / 2.0, sweep: PI }, + Seg2::Line { a: Vec2::new(20.0, 5.0), b: Vec2::new(-20.0, 5.0) }, + Seg2::Arc { center: Vec2::new(-20.0, 0.0), radius: 5.0, start: PI / 2.0, sweep: PI }, + ]; + let plane = Plane::XY.offset(10.0); + let boss = extrude(&plane, &[Region2 { outer: Loop2 { segs }, holes: vec![] }], 0.0, 10.0).unwrap().pop().unwrap(); + boolean(&base, &boss, BoolOp::Union).unwrap().unwrap() +} + +/// #2672: one pick on a straight edge that runs on into an arc chamfers the whole tangent +/// chain, whatever the size of the part (it used to stop at the straight edge once the +/// bounding-box diagonal passed about 200 mm). +#[test] +fn one_chamfer_pick_follows_the_tangent_chain_at_any_part_size() { + for plate in [140.0, 145.0, 250.0] { + let body = plate_with_stadium(plate); + let made = chamfer(&body, &[Vec3::new(0.0, 5.0, 20.0)], 1.0).unwrap(); + assert!(made.validity().is_empty(), "{:?}", made.validity()); + // Two straight edges (c^2/2 * 40 each) and both end arcs (Pappus, c^2/2 * 2 pi (R - c/3)). + let expected = 40.0 + 0.5 * 2.0 * PI * (5.0 - 1.0 / 3.0); + let volume = |b: &Body| b.tessellate(1e-4).unwrap().measure().volume; + let removed = volume(&body) - volume(&made); + assert!((removed - expected).abs() < 0.3, "plate {plate}: removed {removed}, expected {expected}"); + assert_eq!(made.face_count(), body.face_count() + 4, "plate {plate}: one chamfer face per rim edge"); + } +} From 9dfa9e2d529db4943195d7d4c813859eab0d390a Mon Sep 17 00:00:00 2001 From: Jakobonly <149584042+DundreDE@users.noreply.github.com> Date: Tue, 20 Oct 2026 11:33:03 +0000 Subject: [PATCH 195/225] Timeline: the mouse wheel scrolls the horizontal timeline (#3356) (#3409) * claim: #3356 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0158is7fBbAVh538YmVF3MpZ * Timeline: the mouse wheel scrolls the horizontal timeline (#3356) The horizontal timeline is a horizontal-only scroll area, which egui scrolls only with Shift + wheel or a sideways trackpad swipe, so with a plain mouse wheel a history wider than the window could not be scrolled at all. The strip now takes the vertical wheel as sideways scrolling. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0158is7fBbAVh538YmVF3MpZ --------- Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/timeline.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/crates/ui-egui/src/timeline.rs b/crates/ui-egui/src/timeline.rs index 1b8745302..e3b831980 100644 --- a/crates/ui-egui/src/timeline.rs +++ b/crates/ui-egui/src/timeline.rs @@ -287,6 +287,8 @@ pub fn timeline(app: &mut SolveApp, ui: &mut egui::Ui) { // The features scroll horizontally in the space right of the playback controls. let strip = Rect::from_min_max(pos2(x, r.top()), r.right_bottom()); ui.scope_builder(UiBuilder::new().max_rect(strip), |ui| { + // A plain mouse wheel scrolls the strip sideways too, not only Shift + wheel (#3356). + ui.style_mut().always_scroll_the_only_direction = true; egui::ScrollArea::horizontal().auto_shrink([false, false]).show(ui, |ui| { let p = ui.painter().clone(); let mut x = ui.max_rect().left(); @@ -624,6 +626,25 @@ mod tests { h } + /// A timeline wider than the window scrolls with a plain mouse wheel (#3356). + #[test] + fn the_mouse_wheel_scrolls_a_long_timeline() { + let mut h = Harness::new(); + for i in 0..80 { + h.app.run("sketch.create", json!({"plane": "XY", "name": format!("S{i}")})).unwrap(); + h.app.run("sketch.finish", json!({})).unwrap(); + } + h.frames(4); + let first = crate::scenario::handle_at("timeline:S0").unwrap(); + let last = crate::scenario::handle_at("timeline:S79").unwrap(); + assert!(last.x > 1600.0, "the timeline runs past the 1600-point window: {last:?}"); + h.call("ui.scroll", json!({"x": first.x + 200.0, "y": first.y, "delta": -400.0})); + h.frames(30); + let moved = crate::scenario::handle_at("timeline:S0").unwrap(); + assert!(moved.x < first.x - 100.0, "the wheel scrolled the timeline: {first:?} → {moved:?}"); + assert_eq!(moved.y, first.y); + } + #[test] fn the_feature_menu_edits_its_profile_sketch_in_both_timelines() { for left in [false, true] { From 9506336829fc427de9456db16dc77202c0309ecd Mon Sep 17 00:00:00 2001 From: yadi choudhary <84007868+Priyanshu-choudhary@users.noreply.github.com> Date: Tue, 20 Oct 2026 11:33:06 +0000 Subject: [PATCH 196/225] Fonts: find a Chinese fallback font on Linux and Windows (#3376) (#3466) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * claim: #3376 * Fonts: find a Chinese fallback font on Linux and Windows (#3376) The Chinese fallback was searched for at a few fixed paths, and in the font folders only on macOS. On Linux and Windows a Chinese font anywhere else (Fedora's NotoSansCJK-VF.ttc, WenQuanYi under truetype/wqy/, Source Han Sans, a per-user font) was never found, so a Japanese CJK font drew the Chinese interface alone and its simplified characters (设, 语, 实) showed as boxes. Search the system and per-user font folders on every desktop system, three folders deep, and take a font only when it draws simplified Chinese, so a Japanese-only file with a matching name is skipped. The "sourcehanss" keyword matched no real file; match SourceHanSans* and SourceHanSerif*, and Noto Serif CJK/SC. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/fonts.rs | 156 +++++++++++++++++++++++++++++++++--- 1 file changed, 147 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/fonts.rs b/crates/ui-egui/src/fonts.rs index 1e96674c3..da556f400 100644 --- a/crates/ui-egui/src/fonts.rs +++ b/crates/ui-egui/src/fonts.rs @@ -203,8 +203,11 @@ pub const CHINESE_FONT_KEYWORDS: &[&str] = &[ "wenquanyi", "notosanscjk", "notosanssc", + "notoserifcjk", + "notoserifsc", "droidsansfallback", - "sourcehanss", + "sourcehansans", + "sourcehanserif", "siyuan", ]; @@ -421,6 +424,12 @@ fn try_read_font(path: &std::path::Path) -> Option> { /// Recursively search for matching font files up to a bounded depth, testing names with `matches`. #[cfg(not(target_arch = "wasm32"))] fn scan_dir_for_font(dir: &std::path::Path, depth_remaining: usize, matches: fn(&str) -> bool) -> Option> { + scan_dir_for_font_where(dir, depth_remaining, matches, |_| true) +} + +/// [`scan_dir_for_font`] that also skips a font whose bytes `accept` refuses. +#[cfg(not(target_arch = "wasm32"))] +fn scan_dir_for_font_where(dir: &std::path::Path, depth_remaining: usize, matches: fn(&str) -> bool, accept: fn(&[u8]) -> bool) -> Option> { if depth_remaining == 0 { return None; } @@ -435,6 +444,7 @@ fn scan_dir_for_font(dir: &std::path::Path, depth_remaining: usize, matches: fn( if is_font && matches(&name) && let Some(bytes) = try_read_font(&p) + && accept(&bytes) { return Some(bytes); } @@ -444,7 +454,7 @@ fn scan_dir_for_font(dir: &std::path::Path, depth_remaining: usize, matches: fn( } for sub in subdirs { - if let Some(bytes) = scan_dir_for_font(&sub, depth_remaining.saturating_sub(1), matches) { + if let Some(bytes) = scan_dir_for_font_where(&sub, depth_remaining.saturating_sub(1), matches, accept) { return Some(bytes); } } @@ -606,16 +616,63 @@ fn find_system_chinese_font() -> Option> { return Some(bytes); } } - #[cfg(target_os = "macos")] + find_chinese_font_in(&chinese_font_dirs()) +} + +/// A character only fonts covering simplified Chinese draw: 设 (as in 设置, "settings"), boxed in +/// the report of #3376. Japanese fonts (Meiryo, Yu Gothic, BIZ UDPGothic, IPA) lack it. +#[cfg(not(target_arch = "wasm32"))] +const SIMPLIFIED_CHINESE_PROBE: char = '设'; + +/// Whether the font's first face draws simplified Chinese (see [`SIMPLIFIED_CHINESE_PROBE`]). +#[cfg(not(target_arch = "wasm32"))] +fn draws_simplified_chinese(bytes: &[u8]) -> bool { + ttf_parser::Face::parse(bytes, 0).is_ok_and(|face| face.glyph_index(SIMPLIFIED_CHINESE_PROBE).is_some()) +} + +/// The system and per-user font folders searched for a Chinese font when no candidate path has +/// one, on every desktop system (#3376: Linux and Windows searched only the fixed paths, so a +/// Japanese CJK font drew the Chinese UI alone and its simplified characters showed as boxes). +#[cfg(not(target_arch = "wasm32"))] +fn chinese_font_dirs() -> Vec { + let mut dirs = Vec::new(); + #[cfg(target_os = "windows")] { - let dirs = ["/System/Library/Fonts", "/System/Library/Fonts/Supplemental", "/Library/Fonts"]; - for d in dirs { - if let Some(bytes) = scan_dir_for_font(std::path::Path::new(d), 2, is_chinese_font_name) { - return Some(bytes); - } + if let Ok(windir) = std::env::var("WINDIR").or_else(|_| std::env::var("SystemRoot")) { + dirs.push(std::path::PathBuf::from(windir).join("Fonts")); + } + if let Ok(local) = std::env::var("LOCALAPPDATA") { + dirs.push(std::path::PathBuf::from(local).join("Microsoft").join("Windows").join("Fonts")); } } - None + #[cfg(target_os = "macos")] + { + for d in ["/System/Library/Fonts", "/System/Library/Fonts/Supplemental", "/Library/Fonts"] { + dirs.push(std::path::PathBuf::from(d)); + } + if let Ok(home) = std::env::var("HOME") { + dirs.push(std::path::PathBuf::from(home).join("Library/Fonts")); + } + } + #[cfg(target_os = "linux")] + { + dirs.push(std::path::PathBuf::from("/usr/share/fonts")); + dirs.push(std::path::PathBuf::from("/usr/local/share/fonts")); + if let Ok(home) = std::env::var("HOME") { + dirs.push(std::path::PathBuf::from(&home).join(".local/share/fonts")); + dirs.push(std::path::PathBuf::from(home).join(".fonts")); + } + } + dirs +} + +/// The first font in `dirs` (searched three folders deep, which reaches +/// `/usr/share/fonts/truetype/wqy/`) with a Chinese font's name that draws simplified Chinese. +/// The drawing check keeps out a Japanese-only file whose name matches, such as a +/// `SourceHanSansJP` subset, and Windows' SimSun extension fonts. +#[cfg(not(target_arch = "wasm32"))] +fn find_chinese_font_in(dirs: &[std::path::PathBuf]) -> Option> { + dirs.iter().find_map(|dir| scan_dir_for_font_where(dir, 3, is_chinese_font_name, draws_simplified_chinese)) } /// On web, setup_fonts does not perform synchronous disk reads. @@ -795,6 +852,87 @@ mod tests { } } + #[test] + fn chinese_font_names_match_the_files_distributions_install() { + // #3376: Source Han Sans ships as SourceHanSans*.ttc/otf, which "sourcehanss" never matched. + for chinese in [ + "msyh.ttc", + "simsun.ttc", + "wqy-microhei.ttc", + "wqy-zenhei.ttc", + "NotoSansCJK-Regular.ttc", + "NotoSansCJK-VF.ttc", + "NotoSansSC-Regular.otf", + "NotoSerifCJK-Regular.ttc", + "SourceHanSans.ttc", + "SourceHanSansSC-Regular.otf", + "SourceHanSerifSC-Regular.otf", + "DroidSansFallbackFull.ttf", + ] { + assert!(is_chinese_font_name(chinese), "{chinese} is a Chinese font"); + } + for other in ["meiryo.ttc", "YuGothM.ttc", "msgothic.ttc", "NotoSansJP-Regular.ttf", "BIZUDPGothic-Regular.ttf", "ipag.ttf", "DejaVuSans.ttf"] + { + assert!(!is_chinese_font_name(other), "{other} is not a Chinese font"); + } + } + + /// A temporary font folder, removed when dropped. + struct FontFolder(std::path::PathBuf); + + impl FontFolder { + fn new(name: &str) -> FontFolder { + let dir = std::env::temp_dir().join(format!("solidcraft-ui-font-tests-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + FontFolder(dir) + } + } + + impl Drop for FontFolder { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + fn japanese_font_bytes() -> Vec { + std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/fonts/biz-udp-gothic/BIZUDPGothic-Regular.ttf")).unwrap() + } + + #[test] + fn a_japanese_font_does_not_count_as_the_chinese_fallback() { + // #3376: characters Japanese shares with Chinese drew, simplified-only ones were boxes. + let japanese = japanese_font_bytes(); + let face = ttf_parser::Face::parse(&japanese, 0).unwrap(); + for shared in "文件原点".chars() { + assert!(face.glyph_index(shared).is_some(), "BIZ UDPGothic draws {shared}"); + } + assert!(face.glyph_index(SIMPLIFIED_CHINESE_PROBE).is_none(), "BIZ UDPGothic lacks simplified 设"); + assert!(!draws_simplified_chinese(&japanese)); + assert!(!draws_simplified_chinese(&latin_font_bytes())); + assert!(!draws_simplified_chinese(b"not a font")); + } + + #[test] + fn the_chinese_font_search_scans_font_folders_and_checks_what_the_font_draws() { + // #3376: a Chinese font in a font folder but at none of the fixed paths, such as + // /usr/share/fonts/truetype/wqy/wqy-microhei.ttc, is found by the folder scan, three + // folders deep, on every desktop system. + let folder = FontFolder::new("chinese-scan"); + let wqy = folder.0.join("truetype").join("wqy"); + std::fs::create_dir_all(&wqy).unwrap(); + std::fs::write(folder.0.join("notes.txt"), "not a font").unwrap(); + std::fs::write(wqy.join("wqy-broken.ttc"), "not a font either").unwrap(); + // The Japanese font under a Chinese font's name: the scan reaches it… + let japanese = japanese_font_bytes(); + std::fs::write(wqy.join("wqy-microhei.ttc"), &japanese).unwrap(); + assert_eq!(scan_dir_for_font_where(&folder.0, 3, is_chinese_font_name, |_| true), Some(japanese.clone())); + assert_eq!(scan_dir_for_font_where(&folder.0, 2, is_chinese_font_name, |_| true), None, "three folders deep, no deeper"); + // …but it doesn't draw simplified Chinese, so it isn't taken as the Chinese fallback. + assert_eq!(find_chinese_font_in(std::slice::from_ref(&folder.0)), None); + assert_eq!(find_chinese_font_in(&[folder.0.join("missing")]), None); + } + #[test] fn web_font_is_fetched_only_for_a_cjk_language() { let mut loader = CjkFontLoader::default(); From 9666c0be562b68aacd9ddeaedbe76075f29aa437 Mon Sep 17 00:00:00 2001 From: raykholo Date: Tue, 20 Oct 2026 11:43:07 +0000 Subject: [PATCH 197/225] Convert to Sheet Metal keeps a plate where it is (#3316) * claim: Convert to Sheet Metal keeps a plate where it is * Convert to Sheet Metal keeps a plate where it is Converted without bend edges, a plate moved by one thickness: a 100 x 60 x 2 plate on XY came out at z -2..0 picked on its top face, 2..4 picked on its bottom. The sheet's frame (its base panel's bottom face, thickness along its normal) was put on the plate's far face facing away from the picked face, so the material grew out into empty space. The frame now lies on the picked face with z into the material, as Convert with bend edges does. The sheet is the old one moved back by the thickness: same orientation, flat pattern, flange directions and pocket layers. A test converts the plate from either face and checks its bounding box; the engraved-plate test now checks the plate's position, not only its thickness. --- crates/doc/src/eval_more.rs | 6 ++++-- crates/engine/src/cmd/sheet_convert_tests.rs | 22 ++++++++++++++++++-- 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/crates/doc/src/eval_more.rs b/crates/doc/src/eval_more.rs index 5d1356f32..5ff8810e3 100644 --- a/crates/doc/src/eval_more.rs +++ b/crates/doc/src/eval_more.rs @@ -741,8 +741,10 @@ pub(super) fn sheet_eval( let t = hi - lo; // The face outline: boundary edges of the triangles on that face's plane, where it runs // along a round wall an arc of the wall's circle (not chords: the plate check below - // compares its area with the exact volume). - let plane = Plane::from_normal(face.0 + n * lo, n * -1.0).ok_or_else(|| DocError::Invalid("face".into()))?; + // compares its area with the exact volume). The sheet's frame lies on the picked face + // (its outer level, `hi`) with z into the material, as with bend edges, so the sheet + // takes the plate's place: its thickness runs from `hi` back to `lo`. + let plane = Plane::from_normal(face.0 + n * hi, n * -1.0).ok_or_else(|| DocError::Invalid("face".into()))?; // Recesses in one face (an engraved label) become pockets; the outline is the other face's. let recesses = plate_recesses(&mb.body, &mesh, &plane, face.0, n, (lo, hi), tol)?; let mut walls = std::collections::HashMap::new(); diff --git a/crates/engine/src/cmd/sheet_convert_tests.rs b/crates/engine/src/cmd/sheet_convert_tests.rs index aada56c2e..50a477c2f 100644 --- a/crates/engine/src/cmd/sheet_convert_tests.rs +++ b/crates/engine/src/cmd/sheet_convert_tests.rs @@ -985,6 +985,24 @@ fn convert_box(l: f64, w: f64, t: f64, holes: &[([f64; 2], f64)]) -> Session { s } +/// A converted plate stays where the plate was, whichever of its faces is picked: the sheet +/// takes the plate's two faces, not the space one thickness beyond the face picked (a 100 x 60 x 2 +/// plate on XY used to come out at z −2…0 picked on top, and 2…4 picked underneath). +#[test] +fn a_converted_plate_stays_where_the_plate_was() { + for pick in [[40.0, 15.0, 2.0], [40.0, 15.0, 0.0]] { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 100, "width": 60, "height": 2, "body_name": "Plate"})); + let before = bbox(&mut s); + run(&mut s, "sheet.convert", json!({"body": "Plate", "face": pick})); + assert!(!s.model.state().sheets.is_empty(), "{pick:?}"); + let after = bbox(&mut s); + let moved = before.0.iter().chain(&before.1).zip(after.0.iter().chain(&after.1)).any(|(a, b)| (a - b).abs() > 1e-9); + assert!(!moved, "{pick:?}: {before:?} became {after:?}"); + assert!((volume(&mut s) - 12_000.0).abs() < 1e-6, "{pick:?}: {}", volume(&mut s)); + } +} + /// A long thin strip converts. 1200 x 100 x 1 was refused with "no outline on that face": the /// outline's tolerance was a thousandth of the body's size (1.2), more than the thickness, so the /// far side's triangles counted as the picked face's and no boundary was left. @@ -1087,9 +1105,9 @@ fn a_plate_with_an_engraving_converts_with_the_engraving_as_a_pocket() { let m = run(&mut s, "inspect.measure", json!({})); assert!((m["total"]["volume_mm3"].as_f64().unwrap_or(f64::NAN) - 2380.0).abs() < 1e-6, "{pick:?}: {m}"); assert!((m["total"]["area_mm2"].as_f64().unwrap_or(f64::NAN) - 5006.0).abs() < 1e-6, "{pick:?}: {m}"); - // It stays in the face it was cut into (the converted plate is as thick, wherever it lies). + // It stays in the face it was cut into, and the plate where it was (z 0…1). let (lo, hi) = bbox(&mut s); - assert!((hi[2] - lo[2] - 1.0).abs() < 1e-9, "{pick:?}: {lo:?} {hi:?}"); + assert!(lo[2].abs() < 1e-9 && (hi[2] - 1.0).abs() < 1e-9, "{pick:?}: {lo:?} {hi:?}"); assert!(!contains(&s, [20.0, 15.0, hi[2] - 0.05]) && contains(&s, [20.0, 15.0, hi[2] - 0.15]), "{pick:?}"); assert!(contains(&s, [45.0, 30.0, hi[2] - 0.05]), "{pick:?}"); // The flat pattern: the whole plate, no cut-out, and the engraving as a pocket 0.1 deep. From ebada963a4b7d686f04554051df523545a7fcb93 Mon Sep 17 00:00:00 2001 From: jb69 Date: Tue, 20 Oct 2026 11:43:10 +0000 Subject: [PATCH 198/225] Parameters: walk through a flipped plane to its base's expressions (#3481) `PlaneRef::walk_exprs` stopped at `Flipped`, so a sketch created with `flip` on an offset plane (`{plane: "XZ", offset: "d", flip: "x"}`) did not list the offset as an input. Changing `d` rebuilt nothing that read the sketch, and the model went stale. `Flipped` now continues to its base, as `Offset` and `AtAngle` do, in both `walk_exprs` and `walk_exprs_mut`. Test: a loft between XZ and a flipped XZ plane offset by `d` has the volume for d = 30, and for d = 50 after `parameters.change`. Co-authored-by: Claude Opus 5.5 --- crates/doc/src/walk.rs | 6 ++++++ crates/engine/src/cmd/parameters_tests.rs | 18 ++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/crates/doc/src/walk.rs b/crates/doc/src/walk.rs index fa09250a5..aabbf8a8b 100644 --- a/crates/doc/src/walk.rs +++ b/crates/doc/src/walk.rs @@ -332,6 +332,9 @@ impl Walk for PlaneRef { p = base; } PlaneRef::AlongPath { t, .. } => return f(("Distance (0 to 1)", t, Kind::Unitless, ExprRole::Input)), + // A plane seen from behind keeps its base's expressions (a sketch made with + // `flip` on an offset plane did not follow the offset's parameter). + PlaneRef::Flipped { base, .. } => p = base, PlaneRef::Placed { origin, .. } => { for (label, e) in ["X", "Y", "Z"].into_iter().zip(origin) { f((label, e, Kind::Length, ExprRole::Placement)); @@ -355,6 +358,9 @@ impl Walk for PlaneRef { p = base; } PlaneRef::AlongPath { t, .. } => return f(("Distance (0 to 1)", t, Kind::Unitless, ExprRole::Input)), + // A plane seen from behind keeps its base's expressions (a sketch made with + // `flip` on an offset plane did not follow the offset's parameter). + PlaneRef::Flipped { base, .. } => p = base, PlaneRef::Placed { origin, .. } => { for (label, e) in ["X", "Y", "Z"].into_iter().zip(origin) { f((label, e, Kind::Length, ExprRole::Placement)); diff --git a/crates/engine/src/cmd/parameters_tests.rs b/crates/engine/src/cmd/parameters_tests.rs index 66a88f1ab..422b3cfd6 100644 --- a/crates/engine/src/cmd/parameters_tests.rs +++ b/crates/engine/src/cmd/parameters_tests.rs @@ -655,3 +655,21 @@ fn several_parameters_change_in_one_rebuild_and_one_undo() { assert_eq!((expr_of(&mut s, "len"), expr_of(&mut s, "h")), ("60 mm".to_string(), "10 mm".to_string())); assert!(rel(volume(&mut s), 40.0 * 30.0 * 10.0) < 1e-9); } + +/// A sketch made with `flip` on an offset plane follows the offset's parameter (the parameter +/// walk stopped at the flipped plane, so a change rebuilt nothing). +#[test] +fn flipped_offset_sketch_plane_follows_its_parameter() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "d", "expression": "30 mm"})); + run(&mut s, "sketch.create", json!({"plane": "XZ", "name": "Near"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [-10, -10], "p1": [10, 10]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "sketch.create", json!({"plane": "XZ", "offset": "d", "flip": "x", "name": "Far"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [-10, -10], "p1": [10, 10]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.loft", json!({"sections": [{"sketch": "Near"}, {"sketch": "Far"}]})); + assert!((volume(&mut s) - 400.0 * 30.0).abs() < 1e-6); + run(&mut s, "parameters.change", json!({"name": "d", "expression": "50 mm"})); + assert!((volume(&mut s) - 400.0 * 50.0).abs() < 1e-6, "{}", volume(&mut s)); +} From e44dd4ff9e33a4455388f801dd050c3168a3e09b Mon Sep 17 00:00:00 2001 From: jb69 Date: Tue, 20 Oct 2026 11:43:14 +0000 Subject: [PATCH 199/225] Loft: refuse consecutive sections that lie in one plane (#3412) A loft through two sketches on the same plane built a flat body of zero volume and reported success, so the mistake surfaced later, if at all (a measure of 0, or a boolean that did nothing). `loft_wires` now checks each pair of consecutive sections: parallel planes with the second section's centroid in the first's plane are refused with "loft sections i and i+1 lie in the same plane (no volume between them)". The tolerance scales with the section's distance from its plane's origin. Test: two circles on XY; the loft fails with that message and leaves no body. Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd/features_more_tests.rs | 15 +++++++++++++++ crates/kernel/src/build.rs | 12 ++++++++++++ 2 files changed, 27 insertions(+) diff --git a/crates/engine/src/cmd/features_more_tests.rs b/crates/engine/src/cmd/features_more_tests.rs index ee30cf0c3..ced142f4a 100644 --- a/crates/engine/src/cmd/features_more_tests.rs +++ b/crates/engine/src/cmd/features_more_tests.rs @@ -1552,3 +1552,18 @@ fn text_cut_through_a_large_plate_is_one_exact_boolean() { // material in either plate (measured on meshes, which are coarser on the larger one). assert!(small > 10.0 && rel(large, small) < 5e-2, "{small} {large}"); } + +/// A loft between two sections in one plane is refused (it used to build a flat body of zero +/// volume and report success). +#[test] +fn loft_through_coplanar_sections_is_refused() { + let mut s = Session::default(); + for name in ["A", "B"] { + run(&mut s, "sketch.create", json!({"plane": "XY", "name": name})); + run(&mut s, "sketch.circle.center", json!({"center": [0, 0], "radius": 10})); + run(&mut s, "sketch.finish", json!({})); + } + let e = s.execute("solid.loft", &json!({"sections": [{"sketch": "A"}, {"sketch": "B"}]})).unwrap_err().to_string(); + assert!(e.contains("same plane"), "{e}"); + assert!(s.model.state().bodies.is_empty()); +} diff --git a/crates/kernel/src/build.rs b/crates/kernel/src/build.rs index 1595f050e..654bdee2c 100644 --- a/crates/kernel/src/build.rs +++ b/crates/kernel/src/build.rs @@ -1967,6 +1967,18 @@ fn loft_reversed(sections: &[(Plane, Loop2)]) -> Result { // loft touches the body along an edge: an internal panic, or "shell not oriented and // closed"). let centre = |(p, l): &(Plane, Loop2)| p.to_world(l.centroid()); + // Two consecutive sections in one plane span no volume between them: a loft through them + // used to build a flat, zero-volume body and report success. + for (i, w) in sections.windows(2).enumerate() { + let (a, b) = (&w[0], &w[1]); + let n = a.0.normal(); + let size = (centre(a) - a.0.origin).len().max((centre(b) - b.0.origin).len()).max(1.0); + let parallel = n.cross(b.0.normal()).len() < 1e-9; + let in_plane = (centre(b) - centre(a)).dot(n).abs() < 1e-9 * size; + if parallel && in_plane { + return Err(KernelError::Invalid(format!("loft sections {} and {} lie in the same plane (no volume between them)", i + 1, i + 2))); + } + } let (Some(first), Some(last)) = (sections.first(), sections.last()) else { return Err(KernelError::Invalid("no sections".into())) }; let step = centre(last) - centre(first); let big = [step.x, step.y, step.z].into_iter().max_by(|a, b| a.abs().total_cmp(&b.abs())).unwrap_or(0.0); From ca9ebb44db4f6a6add1dab943a3b6cefe573ebbe Mon Sep 17 00:00:00 2001 From: raykholo Date: Tue, 20 Oct 2026 12:07:24 +0000 Subject: [PATCH 200/225] Sheet metal: refuse a flat pattern that no longer matches the body (#3324) (#3325) * claim: #3324 * Sheet metal: refuse a flat pattern that no longer matches the body A feature that is not sheet metal can change a sheet body's material without its sheet model knowing: a mirror combined into it, an extrude joined onto it, a fillet or chamfer on a corner. The flat pattern, the DXF and the bend table then wrote the sheet as it was before, a part other than the one in the design, with no warning. The evaluator now notes, per sheet, the first such feature: one that changes the body's shape while its sheet model stays the same. That feature warns, and sheet.flat_pattern, sheet.export_dxf (also with per_body) and sheet.export_bend_table refuse with "not supported yet", naming it. A sheet metal feature, or machining the sheet keeps as cut-outs, rebuilds the body from the model: it clears the note and warns that the change is not kept. Moving the body, splitting its faces and cosmetic threads leave the flat pattern as it is. * Sheet metal: a modelled thread is refused in the flat pattern too Only a cosmetic thread leaves a sheet body's material as it is. A modelled thread cuts the thread profile into the hole, which the flat pattern does not have, and a later sheet metal feature dropped it without a word. It now marks the sheet like a fillet does: it warns, the flat pattern, DXF and bend table refuse naming it, and the feature that rebuilds the body says the thread is not kept. --- crates/doc/src/eval.rs | 47 ++++++++++++ crates/doc/src/sheet.rs | 23 ++++++ crates/engine/src/cmd/sheet.rs | 11 ++- crates/engine/src/cmd/sheet_tests.rs | 104 +++++++++++++++++++++++++++ crates/kernel/src/body.rs | 15 ++-- docs/book/src/guide/sheet-metal.md | 8 +++ 6 files changed, 202 insertions(+), 6 deletions(-) diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 82ccad82d..e9832fdb7 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -1416,6 +1416,7 @@ impl Model { if let Some(note) = boolean_diagnostics.warning() { append_warning(&mut warning, note); } + track_altered_sheets(&state, &mut next, f, &mut warning); } else { boolean_diagnostics = Default::default(); } @@ -1622,6 +1623,52 @@ fn copy_body_name(state: &ModelState, f: &Feature, k: usize, source: &str) -> St unique_body_name(state, base) } +/// Keeps each sheet metal body's flat pattern true to the body (see `SheetBody::altered_by`). +/// A feature that changes a sheet body's material but not its sheet model (a fillet, a join, a +/// mirror combined into it) marks the sheet with its name, and says so. A feature that rebuilds +/// the body from the model (a sheet metal feature, or machining the model keeps as cut-outs, +/// which changes the model) clears the mark, and says that the change it drops is not kept. +/// Features that move whole bodies or only mark their faces (a cosmetic thread, not a modelled +/// one, which cuts material) leave the flat pattern as it was. +fn track_altered_sheets(before: &ModelState, after: &mut ModelState, f: &Feature, warning: &mut Option) { + if matches!( + f.kind, + FeatureKind::Move { .. } + | FeatureKind::Align { .. } + | FeatureKind::Rest { .. } + | FeatureKind::BodyTransfer { .. } + | FeatureKind::SplitFace { .. } + | FeatureKind::Thread { modeled: false, .. } + ) { + return; + } + let ModelState { sheets, bodies, .. } = after; + for sh in sheets.iter_mut() { + let Some(old) = before.sheets.iter().find(|s| s.body == sh.body) else { continue }; + let (Some(was), Some(now)) = (before.body(&sh.body), bodies.iter().find(|b| b.name == sh.body)) else { continue }; + if was.body.same_shape(&now.body) { + continue; + } + if f.kind.is_sheet() || sh != old { + if let Some(lost) = sh.altered_by.take() { + append_warning( + warning, + format!("`{}` is rebuilt from its sheet metal features: what {lost} changed is not kept (not supported yet)", sh.body), + ); + } + } else if sh.altered_by.is_none() { + sh.altered_by = Some(f.name.clone()); + append_warning( + warning, + format!( + "`{}` is sheet metal: its flat pattern, DXF and bend table can't include this change yet and are refused; a later sheet metal feature rebuilds the body without it", + sh.body + ), + ); + } + } +} + /// Add tool bodies to the model according to the operation. fn sheet_boolean_unchanged(body: &Body, tools: &[Body], op: Operation) -> Result<()> { if sheet_boolean_changes(body, tools, op)? { diff --git a/crates/doc/src/sheet.rs b/crates/doc/src/sheet.rs index af1653bf0..15ba85342 100644 --- a/crates/doc/src/sheet.rs +++ b/crates/doc/src/sheet.rs @@ -513,6 +513,13 @@ pub struct SheetBody { /// The base sketch's lines (id, ends in flat coordinates), naming the base panel's edges. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub base_curves: Vec<(String, Vec2, Vec2)>, + /// The feature (its name) that changed this body's material without changing its sheet + /// model: a fillet or chamfer, a join, a mirror combined into it, any feature that is not + /// sheet metal machining. The flat pattern, its DXF and the bend table no longer describe the + /// body while it is set, so they are refused. Cleared when a sheet metal feature rebuilds the + /// body from the model. Derived from feature history, like `pockets`. + #[serde(skip_serializing_if = "Option::is_none")] + pub altered_by: Option, } /// A straight round bore of one panel (None = the base), in flat coordinates: a cylinder from @@ -849,6 +856,20 @@ struct ReturnCorner { } impl SheetBody { + /// Whether the flat pattern still describes the body: refused, naming the feature, once a + /// feature that is not sheet metal changed the body's material (see `altered_by`). The flat + /// pattern, its DXF and the bend table all check it, so none of them makes a part other than + /// the one in the design. + pub fn flat_matches_body(&self) -> Result<()> { + match &self.altered_by { + None => Ok(()), + Some(feature) => Err(DocError::Invalid(format!( + "not supported yet: the flat pattern of `{}` can't include {feature}, which changed the body after its sheet metal features, so the flat pattern, DXF and bend table would not match the part; remove or suppress {feature}, or make that shape with sheet metal features", + self.body + ))), + } + } + /// Bend allowance of a flange. pub fn allowance(&self, f: &SheetFlange) -> f64 { f.angle.abs() * (f.radius + self.k * self.t) @@ -4343,6 +4364,7 @@ pub fn base_flange(body: &str, rule: &str, rv: &RuleValues, plane: Plane, region relief_size: rv.corner_relief, bend_relief: (rv.relief_width, rv.relief_depth), base_curves: Vec::new(), + altered_by: None, } } @@ -4401,6 +4423,7 @@ pub fn contour_flange(body: &str, rule: &str, rv: &RuleValues, plane: &Plane, pt relief_size: rv.corner_relief, bend_relief: (rv.relief_width, rv.relief_depth), base_curves: Vec::new(), + altered_by: None, }; let (y0, y1) = if ysign > 0.0 { (0.0, width) } else { (-width, 0.0) }; // First segment: the base panel. diff --git a/crates/engine/src/cmd/sheet.rs b/crates/engine/src/cmd/sheet.rs index 58db634ab..9d693d3de 100644 --- a/crates/engine/src/cmd/sheet.rs +++ b/crates/engine/src/cmd/sheet.rs @@ -558,6 +558,7 @@ fn flat_json(sh: &SheetBody) -> Result { fn flat_pattern(s: &mut Session, p: &Value) -> Result { let sh = sheet_of(s, p, "sheet.flat_pattern")?; + sh.flat_matches_body()?; flat_json(&sh) } @@ -818,7 +819,13 @@ fn export_dxf(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, "there is no sheet metal body")); } // Every file is made before the first is written. - let texts = sheets.iter().map(|sh| flat_dxf(sh, &options)).collect::>>()?; + let texts = sheets + .iter() + .map(|sh| { + sh.flat_matches_body()?; + flat_dxf(sh, &options) + }) + .collect::>>()?; let paths = path.map(|path| body_paths(path, &sheets.iter().map(|sh| sh.body.clone()).collect::>())); let mut files = Vec::new(); for (i, (sh, text)) in sheets.iter().zip(&texts).enumerate() { @@ -833,6 +840,7 @@ fn export_dxf(s: &mut Session, p: &Value) -> Result { return Ok(json!({"files": files})); } let sh = sheet_of(s, p, cmd)?; + sh.flat_matches_body()?; let text = flat_dxf(&sh, &options)?; if let Some(path) = path { solidcraft_io::vfs::write(path, text.as_bytes()).map_err(|e| EngineError::Other(format!("{path}: {e}")))?; @@ -848,6 +856,7 @@ fn export_bend_table(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, "`format` must be csv or json")); } let sh = sheet_of(s, p, cmd)?; + sh.flat_matches_body()?; let table = flat_json(&sh)?; let text = if format == "json" { serde_json::to_string_pretty(&table).map_err(|e| EngineError::Other(e.to_string()))? diff --git a/crates/engine/src/cmd/sheet_tests.rs b/crates/engine/src/cmd/sheet_tests.rs index 0efb477b5..334e3fd2e 100644 --- a/crates/engine/src/cmd/sheet_tests.rs +++ b/crates/engine/src/cmd/sheet_tests.rs @@ -4755,3 +4755,107 @@ fn a_hole_that_parts_a_flange_from_the_base_names_it() { assert_eq!(out["warning"], json!(last_warning(&s))); assert_eq!(flat_pieces(&s).len(), 2); } + +/// The three exports of a sheet's flat pattern: its JSON, the DXF (of this body and of every +/// body) and the bend table, each as its error if it is refused. +fn flat_exports(s: &mut Session) -> Vec> { + let calls = [ + ("sheet.flat_pattern", json!({})), + ("sheet.export_dxf", json!({})), + ("sheet.export_dxf", json!({"per_body": true})), + ("sheet.export_bend_table", json!({})), + ]; + calls.iter().map(|(id, p)| s.execute(id, p).map_err(|e| e.to_string())).collect() +} + +/// A mirror combined into a sheet, or a tab extruded onto it and joined, makes a part its +/// flat pattern does not have (the mirrored half, the tab): the flat pattern, the DXF and the +/// bend table are refused with the feature's name instead of writing the sheet without it. +#[test] +fn a_mirror_or_a_join_into_a_sheet_refuses_its_flat_pattern_naming_the_feature() { + let mut s = Session::default(); + base(&mut s, 100.0, 60.0); + run(&mut s, "sheet.flange", json!({"edges": [[50, 0, 2.5]], "height": 20})); + let body = s.model.state().sheets[0].body.clone(); + let out = run(&mut s, "solid.mirror", json!({"bodies": [body], "plane": "YZ", "combine": true})); + assert!(out["warning"].as_str().unwrap_or_default().contains("is sheet metal: its flat pattern, DXF and bend table"), "{out}"); + for result in flat_exports(&mut s) { + let error = result.expect_err("a mirrored half the flat pattern lacks"); + assert!(error.contains("not supported yet: the flat pattern of") && error.contains("can't include Mirror1"), "{error}"); + } + + let mut s = Session::default(); + base(&mut s, 100.0, 60.0); + rectangle_tool(&mut s, "Tab", [40.0, 60.0], [60.0, 75.0]); + run(&mut s, "solid.extrude", json!({"sketch": "Tab", "distance": 2.5, "operation": "join"})); + for result in flat_exports(&mut s) { + let error = result.expect_err("a joined tab the flat pattern lacks"); + assert!(error.contains("can't include Extrude1"), "{error}"); + } +} + +/// A fillet on a sheet's corner is refused in the flat pattern until a sheet metal feature +/// rebuilds the body from its sheet features; that feature says the round is not kept, and the +/// flat pattern describes the body again. +#[test] +fn a_fillet_on_a_sheet_corner_is_refused_until_a_sheet_feature_rebuilds_the_body() { + let mut s = Session::default(); + base(&mut s, 100.0, 60.0); + let out = run(&mut s, "solid.fillet", json!({"edges": [[100, 60, 1.25]], "radius": 10})); + assert!(out["warning"].as_str().is_some_and(|w| w.contains("is sheet metal")), "{out}"); + let error = s.execute("sheet.export_dxf", &json!({})).unwrap_err().to_string(); + assert!(error.contains("can't include Fillet1"), "{error}"); + let out = run(&mut s, "sheet.flange", json!({"edges": [[50, 0, 2.5]], "height": 20})); + assert!(out["warning"].as_str().is_some_and(|w| w.contains("what Fillet1 changed is not kept")), "{out}"); + assert!(flat_exports(&mut s).into_iter().all(|r| r.is_ok())); + assert_eq!(s.model.state().sheets[0].altered_by, None); +} + +/// A cosmetic thread in a sheet's hole leaves its flat pattern as it is; a modelled thread cuts +/// material the flat pattern lacks, so it is refused like a fillet until a sheet feature rebuilds +/// the body and says the thread is not kept. +#[test] +fn a_modelled_thread_in_a_sheet_hole_is_refused_but_a_cosmetic_one_is_not() { + let mut s = Session::default(); + base(&mut s, 100.0, 60.0); + run(&mut s, "solid.hole", json!({"position": [30, 30, 2.5], "diameter": 4.2})); + let drilled = volume(&mut s); + run(&mut s, "solid.thread", json!({"face": [32.1, 30, 1.25], "designation": "M5"})); + assert_eq!(last_warning(&s), ""); + assert!(flat_exports(&mut s).into_iter().all(|r| r.is_ok())); + run(&mut s, "solid.thread", json!({"face": [32.1, 30, 1.25], "designation": "M5", "modeled": true})); + assert!(volume(&mut s) < drilled - 0.05, "the modelled thread cuts material"); + assert!(last_warning(&s).contains("is sheet metal"), "{}", last_warning(&s)); + for result in flat_exports(&mut s) { + let error = result.expect_err("a modelled thread the flat pattern lacks"); + assert!(error.contains("can't include Thread2"), "{error}"); + } + let out = run(&mut s, "sheet.flange", json!({"edges": [[50, 0, 2.5]], "height": 20})); + assert!(out["warning"].as_str().is_some_and(|w| w.contains("what Thread2 changed is not kept")), "{out}"); + assert!(flat_exports(&mut s).into_iter().all(|r| r.is_ok())); +} + +/// A sheet built and machined with sheet features (flanges, a hem, a hole and a cut across a +/// bend while unfolded, refolded, then moved) keeps its flat pattern and exports. +#[test] +fn a_sheet_made_of_sheet_features_and_flat_cuts_still_exports_its_flat_pattern() { + let mut s = Session::default(); + base(&mut s, 100.0, 60.0); + run(&mut s, "sheet.flange", json!({"edges": [[50, 0, 2.5], [100, 30, 2.5]], "height": 20})); + run(&mut s, "sheet.hem", json!({"edges": [[0, 30, 2.5]], "length": 8})); + run(&mut s, "solid.hole", json!({"position": [30, 30, 2.5], "diameter": 6})); + run(&mut s, "sheet.unfold", json!({})); + rectangle_tool(&mut s, "Slot", [45.0, -10.0], [55.0, 10.0]); + run(&mut s, "solid.extrude", json!({"sketch": "Slot", "through_all": true, "direction": "symmetric", "operation": "cut"})); + run(&mut s, "sheet.refold", json!({})); + let body = s.model.state().sheets[0].body.clone(); + run(&mut s, "solid.move", json!({"bodies": [body], "translate": [10, 0, 0]})); + let flagged = |w: &str| w.contains("flat pattern, DXF and bend table") || w.contains("is not kept"); + assert!(s.model.results.iter().all(|r| r.error.is_none() && !r.warning.as_deref().is_some_and(flagged)), "{:?}", s.model.results); + assert_eq!(s.model.state().sheets[0].altered_by, None); + for result in flat_exports(&mut s) { + let value = result.expect("a sheet the flat pattern describes"); + assert!(value.is_object(), "{value}"); + } + assert_eq!(flat(&mut s)["cutouts"].as_array().map(Vec::len), Some(2)); +} diff --git a/crates/kernel/src/body.rs b/crates/kernel/src/body.rs index be11a1199..33db86eeb 100644 --- a/crates/kernel/src/body.rs +++ b/crates/kernel/src/body.rs @@ -568,17 +568,22 @@ impl Body { /// operation made it) is not part of it: an operation that leaves a body as it is (a cut by /// a tool clear of it) gives the same body, with that operation's history. pub fn same(&self, other: &Body) -> bool { + self.same_shape(other) + && self.color == other.color + && same_shared(&self.paint, &other.paint) + && same_shared(&self.splits, &other.splits) + && same_shared(&self.face_sources, &other.face_sources) + && self.regularization_protected == other.regularization_protected + } + + /// The very same shape (shared solid or mesh), whatever its colour, paint or face splits. + pub fn same_shape(&self, other: &Body) -> bool { std::sync::Arc::ptr_eq(&self.solid, &other.solid) && match (&self.mesh, &other.mesh) { (Some(a), Some(b)) => std::sync::Arc::ptr_eq(a, b), (None, None) => true, _ => false, } - && self.color == other.color - && same_shared(&self.paint, &other.paint) - && same_shared(&self.splits, &other.splits) - && same_shared(&self.face_sources, &other.face_sources) - && self.regularization_protected == other.regularization_protected } pub(crate) fn new(solid: Solid) -> Result { diff --git a/docs/book/src/guide/sheet-metal.md b/docs/book/src/guide/sheet-metal.md index 813927f0b..8e8f3a4b3 100644 --- a/docs/book/src/guide/sheet-metal.md +++ b/docs/book/src/guide/sheet-metal.md @@ -314,6 +314,14 @@ but a pocket crossing a bend zone cannot yet be refolded. Machining folded bend tapered sheet cuts and other unsupported 3D sheet Cut/Intersect operations report an error before changing the design; they cannot silently restore removed material during a later sheet rebuild. +Other features that change a sheet body's material without the sheet knowing it (a fillet or +chamfer on a corner, an extrude joined onto it, a Mirror or Combine joined into it) are not in +the flat pattern yet. Such a feature warns, and while the body carries its change the flat +pattern, the DXF and the bend table are refused with an error that names it, rather than writing +a part that does not match the body. A later sheet metal feature rebuilds the body from its sheet +features and says that the change is not kept. Moving the body, splitting its faces and cosmetic +threads leave the flat pattern as it is. + A sketch can be drawn on a flat face of the sheet: the base or a flange, on either side. Pick the face (or give `sketch.create` the point `plane: {face: [x, y, z]}`) and the sketch attaches to that panel instead of to a certified source face. It keeps the face's name, From 47108fa0632cbe5e004adf7c12c5879339f42182 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Tue, 20 Oct 2026 12:27:42 +0000 Subject: [PATCH 201/225] Open: show a design as its bodies are meshed (#3053) (#3178) * Open: show the design as its bodies are meshed, off the UI thread (#3053) Co-Authored-By: Claude Opus 5.5 * Open: hold screenshots until the design is meshed; profile lines * Tests: time-bounded opens * Open: a Loading parts n/N note while bodies are meshed * Open: frame the design from outlines while it goes into the window * Outline bounds: vertices and edges only; test * Frame watch: the window thread's frame times by open phase (SOLIDCRAFT_PROFILE_FRAMES) * Open: the picture grows in mesh order and stays once complete; refreshes pace themselves; named frame steps; watchdog test * Open: outlines measured on the file worker and kept per body * Open: draw the Home picture under the opened file's own key once meshed * Format the open wait --------- Co-authored-by: Claude Opus 5.5 --- crates/doc/src/eval.rs | 13 ++ crates/engine/src/view.rs | 13 +- crates/kernel/src/body.rs | 46 +++++ crates/kernel/src/display_mesh_tests.rs | 21 ++ crates/ui-egui/src/file_load.rs | 39 +++- crates/ui-egui/src/file_load_ui_tests.rs | 155 +++++++++++++- crates/ui-egui/src/frame_watch.rs | 62 ++++++ crates/ui-egui/src/lib.rs | 30 ++- crates/ui-egui/src/open_meshing.rs | 249 +++++++++++++++++++++++ crates/ui-egui/src/scenario.rs | 4 +- crates/ui-egui/src/viewport.rs | 59 +++--- 11 files changed, 650 insertions(+), 41 deletions(-) create mode 100644 crates/ui-egui/src/frame_watch.rs create mode 100644 crates/ui-egui/src/open_meshing.rs diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index e9832fdb7..8fa1512ee 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -57,6 +57,9 @@ pub struct ModelBody { bytes: usize, /// In a world state: the [`ModelBody::geometry_key`] of the model body this one places (0: none). source_key: u64, + /// [`Body::outline_bounds`] of `body` (with the body it was measured on), worked out once + /// and shared by clones. + outline: Arc>, } impl ModelBody { @@ -79,6 +82,16 @@ impl ModelBody { imported: None, bytes: 0, source_key: 0, + outline: Arc::new(OnceLock::new()), + } + } + + /// A box around the body without meshing it ([`Body::outline_bounds`]), worked out once. + pub fn outline_bounds(&self) -> solidcraft_geom::Aabb3 { + match self.outline.get_or_init(|| (self.body.clone(), self.body.outline_bounds())) { + (measured, b) if measured.same(&self.body) => *b, + // The body was replaced in this cell's holder since: measure it again. + _ => self.body.outline_bounds(), } } diff --git a/crates/engine/src/view.rs b/crates/engine/src/view.rs index 5e3c19a28..4ce7ec792 100644 --- a/crates/engine/src/view.rs +++ b/crates/engine/src/view.rs @@ -110,10 +110,21 @@ pub fn bounds(s: &Session) -> Aabb3 { /// [`bounds`], with the browser's Sketches folder shown (`sketches`) or hidden. pub fn visible_bounds(s: &Session, sketches: bool) -> Aabb3 { + bounds_by(s, sketches, |body| body.mesh().bounds()) +} + +/// [`visible_bounds`] without meshing anything: a body not meshed yet counts with its outline +/// ([`solidcraft_kernel::Body::outline_bounds`]), which a face curving out past all of its edges +/// can exceed. Frames a design whose bodies are still being meshed. +pub fn unmeshed_bounds(s: &Session, sketches: bool) -> Aabb3 { + bounds_by(s, sketches, |body| body.cached_mesh().map(|m| m.bounds()).unwrap_or_else(|| body.outline_bounds())) +} + +fn bounds_by(s: &Session, sketches: bool, of: impl Fn(&solidcraft_doc::ModelBody) -> Aabb3) -> Aabb3 { let st = s.world_state(); let mut b = Aabb3::EMPTY; for body in st.bodies.iter().filter(|x| s.body_visible(&x.name)) { - b = b.union(&body.mesh().bounds()); + b = b.union(&of(body)); } for ss in st.sketches.iter().filter(|x| sketch_drawn(s, x.feature, sketches)) { // All four corners: on a tilted plane two opposite ones don't span the rectangle. diff --git a/crates/kernel/src/body.rs b/crates/kernel/src/body.rs index 33db86eeb..5b082e649 100644 --- a/crates/kernel/src/body.rs +++ b/crates/kernel/src/body.rs @@ -1077,6 +1077,52 @@ impl Body { if d.is_finite() && d > 0.0 { d } else { 1.0 } } + /// A box around the body worked out without meshing it: its vertices and its edges' control + /// points (a spline lies in the hull of its controls; a face's surface does not count, as an + /// imported face is often trimmed from a far larger one). A face curving out beyond all of + /// its edges (a dome on a circle) can reach past it, so it frames a view while the body is + /// still being meshed; [`Mesh::bounds`] is the exact one. + /// A mesh body's box is its triangles'. + pub fn outline_bounds(&self) -> solidcraft_geom::Aabb3 { + crate::guard("outline bounds", || Ok(self.outline_bounds_unguarded())).unwrap_or(solidcraft_geom::Aabb3::EMPTY) + } + + fn outline_bounds_unguarded(&self) -> solidcraft_geom::Aabb3 { + use mt::BoundedCurve; + let mut b = solidcraft_geom::Aabb3::EMPTY; + if let Some(m) = &self.mesh { + for p in &m.positions { + b.add(*p); + } + return b; + } + let homogeneous = |b: &mut solidcraft_geom::Aabb3, v: mt::Vector4| { + if v.w > 0.0 { + b.add(Vec3::new(v.x / v.w, v.y / v.w, v.z / v.w)); + } + }; + for v in self.solid.vertex_iter() { + b.add(from_p3(v.point())); + } + for e in self.solid.edge_iter() { + match e.curve() { + mt::Curve::Line(l) => { + b.add(from_p3(l.0)); + b.add(from_p3(l.1)); + } + mt::Curve::BSplineCurve(c) => c.control_points().iter().for_each(|p| b.add(from_p3(*p))), + mt::Curve::NurbsCurve(c) => c.control_points().iter().for_each(|p| homogeneous(&mut b, *p)), + mt::Curve::IntersectionCurve(c) => { + let (t0, t1) = c.range_tuple(); + for i in 0..=8 { + b.add(from_p3(mt::ParametricCurve::subs(&e.curve(), t0 + (t1 - t0) * f64::from(i) / 8.0))); + } + } + } + } + b + } + /// The body's volume from a mesh at `tol`, measured once per (solid, tolerance): clones of /// a body share the measurement, so an operand a later boolean takes again is not meshed /// twice for the same number. `None` when the body cannot be meshed. diff --git a/crates/kernel/src/display_mesh_tests.rs b/crates/kernel/src/display_mesh_tests.rs index ca5d94a41..c1cf7d45a 100644 --- a/crates/kernel/src/display_mesh_tests.rs +++ b/crates/kernel/src/display_mesh_tests.rs @@ -389,3 +389,24 @@ fn a_cylinder_wall_split_along_its_seam_meshes_round() { } } } + +/// A body's outline box, made without meshing, holds its display mesh and is not much larger. +#[test] +fn outline_bounds_hold_the_display_mesh() { + let cube = crate::box_solid(Vec3::ZERO, Vec3::new(40., 30., 10.)).unwrap(); + let rounded = crate::fillet(&cube, &[Vec3::new(20., 0., 10.)], 3.).unwrap(); + let rod = crate::cylinder(Vec3::new(5., 5., 0.), Vec3::Z, 4., 25.).unwrap(); + for body in [cube, rounded, rod] { + let outline = body.outline_bounds(); + let mesh = body.reference_display_mesh_angular(body.size() * 1e-3, crate::DISPLAY_ANGLE).unwrap().bounds(); + let slack = body.size() * 1e-6; + for (lo, hi, m_lo, m_hi) in [ + (outline.min.x, outline.max.x, mesh.min.x, mesh.max.x), + (outline.min.y, outline.max.y, mesh.min.y, mesh.max.y), + (outline.min.z, outline.max.z, mesh.min.z, mesh.max.z), + ] { + assert!(lo <= m_lo + slack && hi >= m_hi - slack, "outline {outline:?} holds the mesh {mesh:?}"); + } + assert!(outline.diagonal() <= mesh.diagonal() * 1.5, "and is not much larger"); + } +} diff --git a/crates/ui-egui/src/file_load.rs b/crates/ui-egui/src/file_load.rs index a66472230..bff9b92c6 100644 --- a/crates/ui-egui/src/file_load.rs +++ b/crates/ui-egui/src/file_load.rs @@ -737,13 +737,14 @@ fn compute( phase.store(1, Ordering::Relaxed); let world = session.world_state(); let placement_ms = view_began.elapsed().as_secs_f64() * 1000.0; - let mesh_began = std::time::Instant::now(); - // Fit, picking and the first viewport frame must not trigger cold tessellation on the UI. - world.warm_meshes(|| !progress.is_cancelled()); - if progress.is_cancelled() { - return cancelled(); - } - let tessellation_ms = mesh_began.elapsed().as_secs_f64() * 1000.0; + // The display meshes are made once the design is in the window, which shows its bodies as + // they come ([`crate::open_meshing`]): framing, picking and drawing never mesh on the UI. + // Its outlines frame it in the window until it is meshed: measured here, not there. + solidcraft_engine::kernel::for_each_on_threads(&world.bodies, 16, |b| { + let _ = b.outline_bounds(); + }); + drop(world); + let tessellation_ms = 0.0; phase.store(2, Ordering::Relaxed); let view_ms = view_began.elapsed().as_secs_f64() * 1000.0; if profile { @@ -794,6 +795,9 @@ pub fn tick(app: &mut SolveApp, ctx: &egui::Context) { } _ if running.cancelled() => request.answer(Err("file operation cancelled".into())), Ok(made) if running.matches(&app.session) => { + // Not meshed yet: framing it while it goes in must not mesh it here. + app.open_meshing_next = true; + crate::frame_watch::step(app, "before the open"); if request.insert() { app.session.accept_computed(made.session); app.big_operation = true; @@ -801,17 +805,19 @@ pub fn tick(app: &mut SolveApp, ctx: &egui::Context) { crate::documents::adopt(app, made.session); if request.kind == Kind::Open { app.home.add_recent(&request.path); - if made.thumbnail { - crate::home::remember_source(&mut app.home, &app.session, &request.path); - } } } app.home.open = false; - app.fit_view(); + crate::frame_watch::step(app, "adopt the design"); + // Shown as its bodies are meshed, framed from their outlines meanwhile; its Home + // picture is drawn once they all are. + crate::open_meshing::start(app, (request.kind == Kind::Open && made.thumbnail).then(|| request.path.clone())); + crate::frame_watch::step(app, "start meshing and frame"); // A caller that said which way is up has been answered: no offer to stand the part up. if (request.kind == Kind::Open || request.insert()) && !request.options.contains_key("up") { crate::stand_up::offer(app, &request.path, &running.before, Some(&made.result)); } + crate::frame_watch::step(app, "stand-up offer"); let warnings = made.result.get("warnings").and_then(Value::as_array); if let Kind::Recover { .. } = request.kind { recovered(app, request); @@ -855,6 +861,17 @@ pub fn tick(app: &mut SolveApp, ctx: &egui::Context) { /// The light overlay over everything under the title bar while a file loads. The title bar, /// its window buttons and the window's resize edges stay live; the design underneath takes no /// pointer input until the file is in. +/// What a file operation under way is doing (for the frame watch), if one is. +pub(crate) fn phase(app: &SolveApp) -> Option<&'static str> { + let r = app.file_load.running.as_ref()?; + Some(match (r.staged.is_some(), r.phase.load(Ordering::Relaxed)) { + (true, 0) => "reading the file (staged)", + (_, 0) => "reading the file", + (_, 1) => "preparing the view", + _ => "finishing the open", + }) +} + pub fn show(app: &mut SolveApp, ctx: &egui::Context) { let Some(r) = &app.file_load.running else { return }; let cancelled = r.cancelled(); diff --git a/crates/ui-egui/src/file_load_ui_tests.rs b/crates/ui-egui/src/file_load_ui_tests.rs index c2d7635f5..d6aa945f0 100644 --- a/crates/ui-egui/src/file_load_ui_tests.rs +++ b/crates/ui-egui/src/file_load_ui_tests.rs @@ -211,7 +211,10 @@ fn a_control_open_answers_after_loading_without_freezing_the_window() { assert_eq!(reply["ok"], true, "{reply}"); assert_eq!(reply["result"], expected); assert!(count_rx.try_recv().is_ok(), "inspection answered while the file loaded"); - // Its Home picture is drawn after it opened, not before. + // Its bodies are meshed after it opened, and its Home picture drawn then, off the UI thread. + while crate::open_meshing::active(&w.app) { + w.frame(vec![]); + } assert!(crate::home::remembering(&w.app.home), "the Home picture is drawn off the UI thread"); for _ in 0..3 { w.frame(vec![]); @@ -267,3 +270,153 @@ fn a_control_import_passes_up_and_names_on() { assert!(size[1] > 39.9 && !offered, "{size:?} {offered}"); let _ = std::fs::remove_dir_all(&dir); } + +/// An opened design is in the window before its bodies are meshed: the view draws the bodies +/// meshed so far (never meshing one itself), framed from their outlines, until all are. +#[test] +fn an_opened_design_shows_its_bodies_as_they_are_meshed() { + let dir = scratch("progressive"); + let path = large_design(&dir, 24); + let mut w = Win::new(); + let (tx, rx) = std::sync::mpsc::channel(); + w.app.control_rx = Some(rx); + let (open, open_rx) = crate::control::ControlRequest::new("engine.execute", json!({"command": "doc.open", "params": {"path": path}})); + tx.send(open).unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120); + while open_rx.try_recv().is_err() { + w.frame(vec![]); + std::thread::sleep(std::time::Duration::from_millis(1)); + assert!(std::time::Instant::now() < deadline, "the open answers"); + } + let mut seen = Vec::new(); + while crate::open_meshing::active(&w.app) { + let shown = crate::open_meshing::shown_world(&w.app); + assert!(shown.bodies.iter().all(|b| b.cached_mesh().is_some()), "only meshed bodies are drawn"); + let (done, total) = crate::open_meshing::progress(&w.app).unwrap(); + assert!(done <= total && total == w.app.session.world_state().bodies.len(), "Loading parts {done}/{total}"); + seen.push(shown.bodies.len()); + w.frame(vec![]); + } + assert!(seen.windows(2).all(|p| p[0] <= p[1]), "the picture only grows: {seen:?}"); + let world = w.app.session.world_state(); + // Then the whole design (in the order its bodies came, kept until the design changes). + let names = |st: &solidcraft_engine::doc::ModelState| { + let mut n: Vec = st.bodies.iter().map(|b| b.name.clone()).collect(); + n.sort(); + n + }; + assert_eq!(names(&crate::open_meshing::shown_world(&w.app)), names(&world), "then the whole design"); + assert!(world.bodies.iter().all(|b| b.cached_mesh().is_some())); + // Framed from the meshes now, as a synchronous open frames it. + let framed = w.app.cam; + w.app.fit_view(); + assert_eq!(w.app.cam, framed); + // An edit after that: the viewport draws the session's world again. + w.app.session.execute("solid.box", &json!({"length": 5, "width": 5, "height": 5, "operation": "new"})).unwrap(); + w.frame(vec![]); + assert!(std::sync::Arc::ptr_eq(&crate::open_meshing::shown_world(&w.app), &w.app.session.world_state())); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A screenshot asked for right after an open shows the whole design: it waits for the meshing, +/// and what was asked after it waits for it. +#[test] +fn a_screenshot_after_an_open_waits_for_the_whole_design() { + let dir = scratch("progressive-shot"); + let path = large_design(&dir, 24); + let mut w = Win::new(); + let (tx, rx) = std::sync::mpsc::channel(); + w.app.control_rx = Some(rx); + let (open, open_rx) = crate::control::ControlRequest::new("engine.execute", json!({"command": "doc.open", "params": {"path": path}})); + tx.send(open).unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120); + while open_rx.try_recv().is_err() { + w.frame(vec![]); + std::thread::sleep(std::time::Duration::from_millis(1)); + assert!(std::time::Instant::now() < deadline, "the open answers"); + } + if !crate::open_meshing::active(&w.app) { + return; // Meshed already: nothing to wait for on this machine. + } + let (shot, _shot_rx) = crate::control::ControlRequest::new("ui.screenshot", json!({})); + let (count, count_rx) = crate::control::ControlRequest::new("document.inspect", json!({})); + tx.send(shot).unwrap(); + tx.send(count).unwrap(); + w.frame(vec![]); + if crate::open_meshing::active(&w.app) { + assert!(count_rx.try_recv().is_err(), "a request after the screenshot waits for it"); + } + while crate::open_meshing::active(&w.app) { + w.frame(vec![]); + } + for _ in 0..3 { + w.frame(vec![]); + } + assert!(count_rx.try_recv().is_ok(), "answered once the design is meshed"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// An assembly of a few rounded parts placed many times, as a STEP file: an import that takes a +/// while to read, place and mesh. +fn step_assembly(dir: &std::path::Path) -> String { + let mut s = Session::default(); + // Distinct parts (each meshed on its own), each placed a few times (placed copies share it). + for k in 0..40 { + let len = 30.0 + k as f64; + let part = s.execute("component.create", &json!({"name": format!("Bracket {k}")})).unwrap()["component"].as_u64().unwrap(); + s.execute("solid.box", &json!({"length": len, "width": 20, "height": 8, "operation": "new"})).unwrap(); + s.execute("solid.cylinder", &json!({"radius": 6, "height": 20, "base": [10, 10, 0], "operation": "join"})).unwrap(); + s.execute("solid.cylinder", &json!({"radius": 2.5, "height": 40, "base": [len - 10.0, 10, -10], "operation": "cut"})).unwrap(); + s.execute("solid.fillet", &json!({"edges": [[len / 2.0, 0, 8]], "radius": 3})).unwrap(); + s.execute("solid.sphere", &json!({"radius": 4, "center": [10, 10, 24], "operation": "join"})).unwrap(); + s.execute("component.activate", &json!({"component": 0})).unwrap(); + for i in 1..5 { + s.execute("occurrence.copy", &json!({"component": part, "translate": [i as f64 * 80.0, k as f64 * 40.0, 0]})).unwrap(); + } + } + let path = dir.join("assembly.step").to_string_lossy().to_string(); + s.execute("file.export", &json!({"path": path})).unwrap(); + path +} + +/// Open `path` through the window as a person would, every frame timed, until it is in and meshed. +/// The slowest frame: ms and the phase it was in. +fn open_timed(path: &str) -> (Win, (f64, &'static str)) { + let mut w = Win::new(); + w.app.frame_watch.slowest = (0.0, "idle"); + let (tx, rx) = std::sync::mpsc::channel(); + w.app.control_rx = Some(rx); + let (open, open_rx) = crate::control::ControlRequest::new("engine.execute", json!({"command": "doc.open", "params": {"path": path}})); + tx.send(open).unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(300); + let mut answered = false; + while !answered || crate::open_meshing::active(&w.app) || !w.app.file_load.idle() { + w.frame(vec![]); + answered |= open_rx.try_recv().is_ok(); + std::thread::sleep(std::time::Duration::from_millis(1)); + assert!(std::time::Instant::now() < deadline, "{path} opens"); + } + let slowest = w.app.frame_watch.slowest; + eprintln!("{path}: slowest frame {:.1} ms while {}, {} bodies", slowest.0, slowest.1, w.app.session.world_state().bodies.len()); + (w, slowest) +} + +/// The window stays responsive through every phase of opening a design: a STEP assembly imported, +/// the design saved with its model and opened again, and saved without it and opened again. No +/// frame on the window thread takes longer than 250 ms (the test names the phase that did). +#[test] +fn opening_a_large_design_never_stalls_the_window() { + const BUDGET_MS: f64 = 250.0; + let dir = scratch("watchdog"); + let step = step_assembly(&dir); + let (mut w, (ms, phase)) = open_timed(&step); + assert!(ms < BUDGET_MS, "STEP import: a {ms:.0} ms frame while {phase}"); + assert!(w.app.session.world_state().bodies.len() >= 200); + for (name, cache) in [("cached.solidcraft", true), ("plain.solidcraft", false)] { + let path = dir.join(name).to_string_lossy().to_string(); + w.app.session.execute("file.save_as", &json!({"path": path, "cache": cache})).unwrap(); + let (_, (ms, phase)) = open_timed(&path); + assert!(ms < BUDGET_MS, "{name}: a {ms:.0} ms frame while {phase}"); + } + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/ui-egui/src/frame_watch.rs b/crates/ui-egui/src/frame_watch.rs new file mode 100644 index 000000000..0c3e74231 --- /dev/null +++ b/crates/ui-egui/src/frame_watch.rs @@ -0,0 +1,62 @@ +//! How long the window thread spends on each frame, by what the app is doing (#3053): the window +//! must stay responsive through every phase of opening a design. `SOLIDCRAFT_PROFILE_FRAMES=1` +//! logs every frame slower than [`SLOW_MS`] with its phase; tests read [`Watch::slowest`]. + +use crate::SolveApp; + +/// A frame slower than this is logged (ms). +pub(crate) const SLOW_MS: f64 = 50.0; + +#[derive(Default)] +pub(crate) struct Watch { + began: Option, + phase: &'static str, + /// This frame's named steps so far, and when the last one ended (ms). + steps: Vec<(&'static str, f64)>, + last: f64, + /// The slowest frame so far: ms, and the phase it was in. + pub slowest: (f64, &'static str), +} + +/// What the app is doing this frame, as far as opening a design goes. +pub(crate) fn phase(app: &SolveApp) -> &'static str { + if let Some(p) = crate::file_load::phase(app) { + return p; + } + if crate::open_meshing::active(app) { "loading parts" } else { "idle" } +} + +/// The frame starts (before any of its work). +pub(crate) fn begin(app: &mut SolveApp) { + let now = crate::now_ms(); + app.frame_watch.began = Some(now); + app.frame_watch.last = now; + app.frame_watch.steps.clear(); + app.frame_watch.phase = phase(app); +} + +/// A named step of this frame's work ended: a slow frame is logged with them. +pub(crate) fn step(app: &mut SolveApp, name: &'static str) { + let now = crate::now_ms(); + let w = &mut app.frame_watch; + if w.began.is_some() && w.steps.len() < 32 { + w.steps.push((name, now - w.last)); + } + w.last = now; +} + +/// The frame's work is done. +pub(crate) fn end(app: &mut SolveApp) { + step(app, "the rest of the frame"); + let Some(began) = app.frame_watch.began.take() else { return }; + let ms = crate::now_ms() - began; + // The phase the frame started in names it (a frame that finishes an open did that work). + let phase = app.frame_watch.phase; + if ms > app.frame_watch.slowest.0 { + app.frame_watch.slowest = (ms, phase); + } + if ms > SLOW_MS && solidcraft_engine::geom::env::var_os("PROFILE_FRAMES").is_some() { + let steps: Vec = app.frame_watch.steps.iter().filter(|(_, t)| *t >= 1.0).map(|(n, t)| format!("{n} {t:.0}")).collect(); + eprintln!("SolidCraft slow frame: {ms:.0} ms ({phase}) [{}]", steps.join(", ")); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 60870c71f..5fbbe848a 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -115,6 +115,7 @@ mod extrude_edit_tests; mod extrude_preview; mod file_load; mod file_picker; +pub(crate) mod frame_watch; #[cfg(test)] mod history_off_thread_tests; pub use file_picker::FilePickerFuture; @@ -130,6 +131,7 @@ mod file_load_ui_tests; #[cfg(test)] mod fillet_spline_handle_tests; pub(crate) mod navigation; +pub(crate) mod open_meshing; pub mod palette; pub mod params_dialog; pub(crate) mod pick_buffer; @@ -437,6 +439,12 @@ pub struct SolveApp { /// The 3D mouse: which device, its reading, and the calibration window. pub space_mouse: space_mouse::Input, pub file_load: file_load::FileLoad, + /// An opened design's bodies still being meshed, off the UI thread. + pub(crate) open_meshing: Option, + /// A design is being put in the window and will be meshed after it: framing it uses outlines. + pub(crate) open_meshing_next: bool, + /// How long each frame takes on the window thread, by phase. + pub(crate) frame_watch: frame_watch::Watch, /// The other open designs (tabs). pub docs: documents::Documents, /// The language the installed font fallback chain is ordered for (`fonts::fallback_order`); @@ -533,6 +541,9 @@ impl SolveApp { home: home::HomeState::default(), space_mouse: Default::default(), file_load: file_load::FileLoad::default(), + open_meshing: None, + open_meshing_next: false, + frame_watch: Default::default(), docs: documents::Documents::default(), applied_fonts_language: "en".into(), applied_ui_font: String::new(), @@ -1314,6 +1325,7 @@ impl SolveApp { /// Per-frame logic before layout. pub fn logic(&mut self, ctx: &egui::Context) { + frame_watch::begin(self); file_picker::tick(self, ctx); render_workspace::sync_backend(self); render_workspace::tick(self, ctx); @@ -1322,6 +1334,8 @@ impl SolveApp { if self.saving.is_some() { ctx.request_repaint_after(std::time::Duration::from_millis(16)); } + open_meshing::tick(self, ctx); + open_meshing::refresh(self, ctx.input(|i| i.time)); self.esc_handled = false; prefs::apply(self, ctx); if !self.styled || theme::is_dark() != self.ui.dark || theme::vision() != self.preferences.color_vision { @@ -1431,6 +1445,7 @@ impl SolveApp { ui.ctx().request_repaint_after(std::time::Duration::from_millis(50)); } self.frame_ms = now_ms() - t0; + frame_watch::end(self); } fn cad_ui(&mut self, ui: &mut egui::Ui, report_input: &mut Option) { @@ -1440,6 +1455,7 @@ impl SolveApp { toolbar::app_bar(self, ui); issue_report::CadInput::block(self, ui, report_input); file_load::show(self, ui.ctx()); + open_meshing::show(self, ui.ctx()); documents::prompt(self, ui.ctx()); update::show(self, ui.ctx()); install::show(self, ui.ctx()); @@ -1524,13 +1540,25 @@ impl SolveApp { break; } // Held requests go first, in order, once the file is in. - let held = if self.file_load.busy() || self.file_picker.is_some() { None } else { self.control_held.pop_front() }; + // A screenshot waiting for an opened design to be meshed holds what came after it. + let shot_waits = open_meshing::active(self) && self.control_held.front().is_some_and(|r| r.method == "ui.screenshot"); + let held = if self.file_load.busy() || self.file_picker.is_some() || shot_waits { None } else { self.control_held.pop_front() }; let Some(req) = held.or_else(|| rx.as_ref().and_then(|rx| rx.try_recv().ok())) else { break }; + if shot_waits { + if self.control_held.len() < MAX_HELD { + self.control_held.push_back(req); + } else { + let _ = req.reply.send(json!({"ok": false, "error": "a file operation is in progress"})); + } + continue; + } // A file is loading: commands that change the design wait for it (the window, // inspection and screenshots still answer). if ((self.file_load.busy() || self.file_picker.is_some()) && matches!(req.method.as_str(), "engine.execute" | "command" | "engine.script" | "engine.batch")) || (self.file_picker_busy() && matches!(req.method.as_str(), "ui.file" | "ui.home")) + // A screenshot shows the whole design: it waits until an opened one is meshed. + || (open_meshing::active(self) && req.method == "ui.screenshot") { if self.control_held.len() < MAX_HELD { self.control_held.push_back(req); diff --git a/crates/ui-egui/src/open_meshing.rs b/crates/ui-egui/src/open_meshing.rs new file mode 100644 index 000000000..7843ceef8 --- /dev/null +++ b/crates/ui-egui/src/open_meshing.rs @@ -0,0 +1,249 @@ +//! A design that has just opened shows its parts as they are meshed (#3053). +//! +//! Opening hands the design to the window once its timeline is evaluated (or taken from its +//! file) and placed; the display meshes are made afterwards, off the UI thread. Until they all +//! are, the viewport draws the bodies already meshed ([`shown_world`]), so the first parts show +//! within moments and the window stays responsive while the rest come in. The first placement of +//! every part is meshed first: its other placements only move that mesh. The view is framed from +//! the bodies' outlines meanwhile, and framed again from the meshes when they are all made, unless +//! the camera was moved in between. Editing the design meanwhile meshes the new world instead. +//! +//! The picture lists the bodies in the order they were meshed, and is kept once complete until +//! the design changes: the viewport's scene keeps the blocks it built for the bodies already +//! shown and builds only the new ones, and finishing does not build the whole scene again. It is +//! remade at most every [`REFRESH`] seconds, and less often while a remake takes longer. +//! +//! Display only: commands, picking of what is drawn and exports read the session's world as ever. + +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; + +use solidcraft_engine::doc::ModelState; + +use crate::SolveApp; + +/// How often a growing picture is remade at most (s). +const REFRESH: f64 = 0.25; +/// A remake waits this many times as long as the last scene build took, so remakes take at most +/// a small share of the window thread. +const REFRESH_SHARE: f64 = 6.0; + +pub(crate) struct Meshing { + /// The world being meshed (the session's when it started). + world: Arc, + /// The bodies of `world` whose display (mesh, and plans when drawn from them) is made, in + /// the order they were made. + ready: Arc>>, + done: Arc, + /// All are meshed and framed: the picture is kept until the design changes. + complete: bool, + stop: Arc, + /// The picture so far: the bodies shown, and how many were ready when it was made. + shown: Option<(usize, Arc)>, + shown_at: f64, + /// The camera the outline framing left (a refit at the end only replaces that one). + framed: Option, + /// Draw the design's Home picture when all is meshed. + remember: Option, + /// When it started, and whether the first bodies have been shown (`SOLIDCRAFT_PROFILE_OPEN`). + began: Option, + first_shown: bool, +} + +impl Meshing { + fn start(world: Arc, plans: bool) -> Meshing { + let n = world.bodies.len(); + let ready = Arc::new(Mutex::new(Vec::with_capacity(n))); + let (done, stop) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicBool::new(false))); + // The first placement of each part first: the others only move its mesh. + let mut seen = std::collections::HashSet::new(); + let (mut first, mut rest) = (Vec::new(), Vec::new()); + for (i, b) in world.bodies.iter().enumerate() { + if seen.insert(b.definition_name().to_string()) { first.push(i) } else { rest.push(i) } + } + first.extend(rest); + let job = (world.clone(), ready.clone(), done.clone(), stop.clone()); + let spawned = std::thread::Builder::new().name("open-meshing".into()).spawn(move || { + let (world, ready, done, stop) = job; + solidcraft_engine::kernel::for_each_on_threads(&first, 16, |&i| { + if stop.load(Ordering::Relaxed) { + return; + } + if let Some(b) = world.bodies.get(i) { + let _ = b.mesh(); + if plans { + let _ = b.display_plan(); + let _ = b.plan_mesh(); + } + } + if let Ok(mut r) = ready.lock() { + r.push(i); + } + done.fetch_add(1, Ordering::Release); + }); + }); + if spawned.is_err() { + // No thread: the viewport meshes as it draws, as before. + done.store(n, Ordering::Release); + } + Meshing { + world, + ready, + done, + stop, + complete: false, + shown: None, + shown_at: f64::NEG_INFINITY, + framed: None, + remember: None, + began: None, + first_shown: false, + } + } + + fn finished(&self) -> bool { + self.done.load(Ordering::Acquire) >= self.world.bodies.len() + } +} + +impl Drop for Meshing { + fn drop(&mut self) { + self.stop.store(true, Ordering::Relaxed); + } +} + +/// Start meshing the session's world off the UI thread (an opened design), framing the view from +/// the bodies' outlines; `remember`: then draw the Home picture of that file. +pub(crate) fn start(app: &mut SolveApp, remember: Option) { + app.open_meshing_next = false; + let plans = app.viewport.gpu.is_some_and(|g| g.tess); + let mut meshing = Meshing::start(app.session.world_state(), plans); + meshing.remember = remember; + app.open_meshing = Some(meshing); + app.fit_view(); + if let Some(m) = app.open_meshing.as_mut() { + m.framed = Some(app.cam); + } +} + +/// How far the meshing is: bodies done, and of how many. +pub(crate) fn progress(app: &SolveApp) -> Option<(usize, usize)> { + app.open_meshing.as_ref().filter(|m| !m.complete).map(|m| (m.done.load(Ordering::Acquire).min(m.world.bodies.len()), m.world.bodies.len())) +} + +/// A small "Loading parts n/N" note at the foot of the viewport while bodies are being meshed: +/// a part not drawn yet can't be picked yet either, and this says why. +pub(crate) fn show(app: &SolveApp, ctx: &egui::Context) { + let (Some((done, total)), Some(view)) = (progress(app), app.viewport.rect) else { return }; + let t = crate::theme::Tokens::get(); + let at = egui::pos2(view.left() + 12.0, view.bottom() - 12.0); + egui::Area::new(egui::Id::new("open_meshing")) + .order(egui::Order::Foreground) + .pivot(egui::Align2::LEFT_BOTTOM) + .fixed_pos(at) + .interactable(false) + .show(ctx, |ui| { + egui::Frame::popup(ui.style()).fill(t.panel).show(ui, |ui| { + ui.horizontal(|ui| { + ui.spinner(); + ui.label(egui::RichText::new(format!("Loading parts {done}/{total}")).color(t.text)); + }); + }); + }); +} + +/// Whether bodies are still being meshed after an open. +pub(crate) fn active(app: &SolveApp) -> bool { + app.open_meshing.as_ref().is_some_and(|m| !m.complete) +} + +/// Whether the view is framed from outlines: bodies being meshed, or about to be. +pub(crate) fn framing(app: &SolveApp) -> bool { + active(app) || app.open_meshing_next +} + +/// Per frame: follow the session's world, show more as it is meshed, and frame the finished +/// picture. +pub(crate) fn tick(app: &mut SolveApp, ctx: &egui::Context) { + let Some(m) = app.open_meshing.as_ref() else { return }; + let world = app.session.world_state(); + if !Arc::ptr_eq(&world, &m.world) { + if m.complete { + // The design changed after its open: the viewport draws it as ever. + app.open_meshing = None; + return; + } + // The design changed (an edit, an undo): mesh the new world; what is made is kept. + let (framed, remember) = (m.framed, m.remember.clone()); + let plans = app.viewport.gpu.is_some_and(|g| g.tess); + let mut next = Meshing::start(world.clone(), plans); + (next.framed, next.remember) = (framed, remember); + app.open_meshing = Some(next); + } + let Some(m) = app.open_meshing.as_ref().filter(|m| !m.complete) else { return }; + if m.finished() && m.shown.as_ref().is_some_and(|(n, _)| *n >= m.world.bodies.len()) { + let (framed, remember, began) = (m.framed, m.remember.clone(), m.began); + if let Some(m) = app.open_meshing.as_mut() { + m.complete = true; + } + if profiling() { + let ms = began.map_or(0.0, |t| (ctx.input(|i| i.time) - t) * 1000.0); + eprintln!("SolidCraft open meshing: all {} bodies shown after {ms:.0} ms", world.bodies.len()); + } + // Framed from outlines and not moved since: frame the meshes. + if framed == Some(app.cam) { + app.fit_view(); + } + crate::frame_watch::step(app, "frame the meshes"); + if let Some(key) = remember { + crate::home::remember_source(&mut app.home, &app.session, &key); + } + crate::frame_watch::step(app, "home picture"); + return; + } + ctx.request_repaint(); +} + +/// The world the viewport draws: while an opened design is being meshed, the bodies meshed so +/// far (the picture grows a few times a second), then all of them, in the order they came, until +/// the design changes; otherwise the session's. +pub(crate) fn shown_world(app: &SolveApp) -> Arc { + let Some(m) = app.open_meshing.as_ref() else { return app.session.world_state() }; + if !Arc::ptr_eq(&app.session.world_state(), &m.world) { + return app.session.world_state(); + } + m.shown.as_ref().map(|(_, st)| st.clone()).unwrap_or_else(|| Arc::new(ModelState::default())) +} + +/// Remake the picture so far, at most every [`REFRESH`] seconds and no sooner than +/// [`REFRESH_SHARE`] times the last scene build (the bodies shown before keep their place, so the +/// viewport builds only the new ones). +pub(crate) fn refresh(app: &mut SolveApp, now: f64) { + let build_s = app.viewport.build_ms / 1000.0; + let Some(m) = app.open_meshing.as_mut().filter(|m| !m.complete) else { return }; + let order: Vec = match m.ready.lock() { + Ok(r) => r.clone(), + Err(_) => return, + }; + let done = order.len(); + let all = done >= m.world.bodies.len(); + let wait = REFRESH.max(build_s * REFRESH_SHARE); + if m.shown.as_ref().is_some_and(|(n, _)| *n == done) || (now - m.shown_at < wait && !all) { + return; + } + let began = *m.began.get_or_insert(now); + let mut st = (*m.world).clone(); + st.bodies = order.iter().filter_map(|&i| m.world.bodies.get(i).cloned()).collect(); + if !m.first_shown && !st.bodies.is_empty() { + m.first_shown = true; + if profiling() { + eprintln!("SolidCraft open meshing: first {} bodies shown after {:.0} ms", st.bodies.len(), (now - began) * 1000.0); + } + } + m.shown = Some((done, Arc::new(st))); + m.shown_at = now; +} + +fn profiling() -> bool { + solidcraft_engine::geom::env::var_os("PROFILE_OPEN").is_some() +} diff --git a/crates/ui-egui/src/scenario.rs b/crates/ui-egui/src/scenario.rs index 04a56dac0..6a002fa82 100644 --- a/crates/ui-egui/src/scenario.rs +++ b/crates/ui-egui/src/scenario.rs @@ -256,7 +256,9 @@ impl Harness { } // A file opening, recovering or saving in the background: wait for it (as a person would). let began = std::time::Instant::now(); - while (!self.app.file_load.idle() || self.app.saving.is_some()) && began.elapsed() < std::time::Duration::from_secs(120) { + while (!self.app.file_load.idle() || self.app.saving.is_some() || crate::open_meshing::active(&self.app)) + && began.elapsed() < std::time::Duration::from_secs(120) + { self.frame(); std::thread::sleep(std::time::Duration::from_millis(1)); } diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 1686c59ce..c23cbbb75 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -284,20 +284,24 @@ pub fn projection(app: &SolveApp, rect: Rect) -> Proj { /// Sketches drawn in the viewport: the active one, and finished ones not yet used by a feature. pub(crate) fn visible_sketches(app: &SolveApp) -> Vec { - let st = app.session.world_state(); + let st = crate::open_meshing::shown_world(app); st.sketches.iter().filter(|s| solidcraft_engine::view::sketch_drawn(&app.session, s.feature, app.ui.show_sketches)).map(|s| s.feature).collect() } /// What Home, Fit and the orbit pivot frame: the bodies and sketches shown now, where they are /// now (see [`solidcraft_engine::view::visible_bounds`]). pub fn view_bounds(app: &SolveApp) -> solidcraft_engine::geom::Aabb3 { + // Bodies still being meshed after an open frame the view by their outlines. + if crate::open_meshing::framing(app) { + return solidcraft_engine::view::unmeshed_bounds(&app.session, app.ui.show_sketches); + } solidcraft_engine::view::visible_bounds(&app.session, app.ui.show_sketches) } fn scene_key(app: &SolveApp) -> u64 { let mut h = std::collections::hash_map::DefaultHasher::new(); app.session.revision.hash(&mut h); - (std::sync::Arc::as_ptr(&app.session.world_state()) as usize).hash(&mut h); + (std::sync::Arc::as_ptr(&crate::open_meshing::shown_world(app)) as usize).hash(&mut h); app.ui.show_grid.hash(&mut h); app.ui.visual_style.hash(&mut h); app.ui.ground_shadow.hash(&mut h); @@ -331,7 +335,7 @@ fn sketch_scene_key(app: &SolveApp, proj: &Proj) -> u64 { // The grid this scene draws follows the view when the preference says so (#1470): turning it // on or off redraws even while the camera holds still. app.preferences.grid_follows_view.hash(&mut h); - (std::sync::Arc::as_ptr(&app.session.world_state()) as usize).hash(&mut h); + (std::sync::Arc::as_ptr(&crate::open_meshing::shown_world(app)) as usize).hash(&mut h); crate::sketch_display::projection_key(proj, app.viewport.pixels_per_point()).hash(&mut h); h.finish() } @@ -499,7 +503,7 @@ fn update_refinement(app: &mut SolveApp, ctx: &egui::Context, proj: &Proj) { } let t0 = crate::now_ms(); app.viewport.lod_view = view; - let st = app.session.world_state(); + let st = crate::open_meshing::shown_world(app); let ppp = f64::from(app.viewport.pixels_per_point()); let lens = crate::display_lod::Lens::new(&proj.cam, f64::from(proj.rect.height()) * ppp); let bounds = body_bounds(app, &st); @@ -642,7 +646,7 @@ fn build_scene(app: &SolveApp) -> GpuScene { let mut sc = GpuScene::default(); let s = &app.session; // Bodies where their occurrences place them. - let st = s.world_state(); + let st = crate::open_meshing::shown_world(app); let active_bodies = s.active_occurrence_path.as_ref().and_then(|p| s.occurrence_bodies(p, true).ok()); let (shaded, edges) = match app.ui.visual_style { 1 => (true, false), @@ -744,7 +748,7 @@ fn build_sketch_scene(app: &SolveApp, proj: &Proj) -> GpuScene { let tk = Tokens::get(); let mut sc = GpuScene::default(); let s = &app.session; - let st = s.world_state(); + let st = crate::open_meshing::shown_world(app); let mut fill_budget = 131_072; let sketch_plane = solidcraft_engine::view::open_sketch_plane(s); if sketch_plane.is_some() || (app.ui.show_grid && !active_view(app).hide_grid) { @@ -1065,7 +1069,7 @@ type BodyBounds = (std::sync::Arc, std::sync /// The model's extent: bodies (from the cached boxes) and sketches. pub fn model_bounds(app: &SolveApp) -> solidcraft_engine::geom::Aabb3 { - let st = app.session.world_state(); + let st = crate::open_meshing::shown_world(app); let mut b = body_bounds(app, &st).iter().fold(solidcraft_engine::geom::Aabb3::EMPTY, |a, (_, x)| a.union(x)); for ss in &st.sketches { if let Some((lo, hi)) = ss.sketch.bounds() { @@ -1139,7 +1143,7 @@ pub(crate) fn pick_cached(app: &mut SolveApp, proj: &Proj, pos: Pos2) -> Vec Near { fn pick_hits(app: &SolveApp, proj: &Proj, pos: Pos2, other_sketch_points: bool, all: bool) -> Vec { let s = &app.session; - let st = s.world_state(); + let st = crate::open_meshing::shown_world(app); let bounds = body_bounds(app, &st); let mut hits = Vec::new(); let (o, d) = proj.ray(pos); @@ -1466,7 +1470,7 @@ fn pick_hits(app: &SolveApp, proj: &Proj, pos: Pos2, other_sketch_points: bool, /// The section cut shown now: the open Section Analysis dialog's plane, else the session's. /// The active sketch's display options (defaults when not sketching). pub fn active_view(app: &SolveApp) -> solidcraft_engine::sketch::SketchView { - let st = app.session.world_state(); + let st = crate::open_meshing::shown_world(app); app.session.active_sketch.and_then(|s| st.sketch(s)).map(|ss| ss.sketch.view.clone()).unwrap_or_default() } @@ -1480,7 +1484,7 @@ pub fn section_plane(app: &SolveApp) -> Option<(Vec3, Vec3)> { } // Slice (Sketch Palette): cut the model at the plane of the sketch being edited. if app.session.section.is_none() { - let st = app.session.world_state(); + let st = crate::open_meshing::shown_world(app); if let Some(ss) = app.session.active_sketch.and_then(|s| st.sketch(s)).filter(|ss| ss.sketch.view.slice) { return Some((ss.plane.origin, ss.plane.normal())); } @@ -1496,7 +1500,7 @@ fn feature_geometry(app: &SolveApp, id: u64) -> Vec { if !app.session.model.result(id).is_some_and(|r| !r.skipped && r.error.is_none()) { return Vec::new(); } - let st = app.session.world_state(); + let st = crate::open_meshing::shown_world(app); let prefix = format!("F{id}:"); let mut out = Vec::new(); for b in &st.bodies { @@ -1541,7 +1545,7 @@ fn displayed_selection(app: &SolveApp, item: &Sel) -> Vec { /// The box around what is selected (bodies, faces, edges, vertices, sketch curves and the /// bodies of selected features), where it is shown. pub fn selection_bounds(app: &SolveApp) -> Option { - let st = app.session.world_state(); + let st = crate::open_meshing::shown_world(app); let mut b = solidcraft_engine::geom::Aabb3::EMPTY; for s in app.session.selection.iter().flat_map(|item| displayed_selection(app, item)) { match &s { @@ -1851,7 +1855,7 @@ fn hidden_face_outline(sc: &mut GpuScene, m: &solidcraft_engine::geom::Mesh, fac } pub(crate) fn profile_fill(sc: &mut GpuScene, app: &SolveApp, sketch: u64, index: usize, fill: Color32, edge: Color32) { - let st = app.session.world_state(); + let st = crate::open_meshing::shown_world(app); let Some(ss) = st.sketch(sketch) else { return }; let Some(p) = ss.profiles.get(index) else { return }; let plane = match crate::dialogs::emboss_profile_plane(app, sketch) { @@ -1908,7 +1912,7 @@ fn highlight_geometry_key(app: &SolveApp) -> u64 { let mut h = std::collections::hash_map::DefaultHasher::new(); let selected = app.highlighted(); app.session.revision.hash(&mut h); - (std::sync::Arc::as_ptr(&app.session.world_state()) as usize).hash(&mut h); + (std::sync::Arc::as_ptr(&crate::open_meshing::shown_world(app)) as usize).hash(&mut h); serde_json::to_string(&selected).unwrap_or_default().hash(&mut h); format!("{:?}", app.viewport.hover).hash(&mut h); app.viewport.hover_feature.hash(&mut h); @@ -1960,7 +1964,7 @@ struct HoverBlock { fn build_highlight(app: &SolveApp) -> GpuScene { let t = Tokens::get(); let mut sc = GpuScene::default(); - let st = app.session.world_state(); + let st = crate::open_meshing::shown_world(app); let s = &app.session; let active_bodies = s.active_occurrence_path.as_ref().and_then(|p| s.occurrence_bodies(p, true).ok()); // Faces lit over the model use the triangles the model shows them with. @@ -2250,7 +2254,7 @@ fn body_color(doc: &solidcraft_engine::doc::Document, b: &solidcraft_engine::doc /// A body's display colour (else the theme's) as RGB. fn body_rgb(app: &SolveApp, name: &str) -> (u8, u8, u8) { - let st = app.session.world_state(); + let st = crate::open_meshing::shown_world(app); let c = st.body(name).and_then(|b| body_color(&app.session.doc, b)).unwrap_or(Tokens::get().body); (c.r(), c.g(), c.b()) } @@ -2280,7 +2284,7 @@ fn seg_dist(p: Pos2, a: Pos2, b: Pos2) -> f32 { /// id of the sketch point it snapped to. pub fn sketch_point_at(app: &SolveApp, proj: &Proj, pos: Pos2) -> Option<(Vec2, Option)> { let sid = app.session.active_sketch?; - let st = app.session.world_state(); + let st = crate::open_meshing::shown_world(app); let ss = st.sketch(sid)?; for h in pick(app, proj, pos) { if let Hit::SketchPoint { sketch, id, at } = h @@ -2372,7 +2376,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { } let proj = projection(app, rect); if let Ok(mut cache) = app.viewport.display.lock() { - cache.prepare(app.session.world_state(), &proj, app.viewport.pixels_per_point()); + cache.prepare(crate::open_meshing::shown_world(app), &proj, app.viewport.pixels_per_point()); } // Suppress hover for the whole navigation gesture, including frames between pointer // events. Testing delta made the highlight reappear whenever a held drag paused. @@ -2420,7 +2424,9 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { painter.add(Shape::mesh(mesh)); // ---- model ---- + crate::frame_watch::step(app, "viewport before the model"); update_refinement(app, ui.ctx(), &proj); + crate::frame_watch::step(app, "display refinement"); let key = scene_key(app); let t0 = crate::now_ms(); // Drawn on the GPU; without one (the headless harness, tests) the model is not drawn. @@ -2432,6 +2438,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { } app.viewport.key = key; app.viewport.build_ms = crate::now_ms() - t0; + crate::frame_watch::step(app, "model scene"); } let sk = sketch_scene_key(app, &proj); if sk != app.viewport.sketch_key { @@ -2562,7 +2569,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { if let Some((hit, Some(sel))) = cand { dialog_pick(app, &hit, sel); } else if let Some(mut dialog) = app.dialog.take() { - let state = app.session.world_state(); + let state = crate::open_meshing::shown_world(app); if let Some(sketch) = app.session.active_sketch.and_then(|id| state.sketch(id)) { let (origin, direction) = proj.ray(p); if let Some(point) = sketch.plane.intersect_ray(origin, direction) { @@ -2637,7 +2644,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { && app.tool.is_none() && app.dialog.is_none() && let Some(Hit::Edge { body, index, .. }) = app.viewport.hover.clone() - && let Some(b) = app.session.world_state().body(&body).cloned() + && let Some(b) = crate::open_meshing::shown_world(app).body(&body).cloned() { let m = b.mesh(); let items: Vec = m @@ -2658,7 +2665,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { // Dragging a sketch point of the active sketch moves it; the solver keeps the constraints. if app.tool.is_none() && app.dialog.is_none() && primary_nav.is_none() && mode.is_none() && app.session.active_sketch.is_some() && !held { let on_plane = |app: &SolveApp, p: Pos2| { - let ss = app.session.active_sketch.and_then(|sid| app.session.world_state().sketch(sid).cloned())?; + let ss = app.session.active_sketch.and_then(|sid| crate::open_meshing::shown_world(app).sketch(sid).cloned())?; let (o, d) = proj.ray(p); ss.plane.intersect_ray(o, d).map(|w| ss.plane.to_local(w)) }; @@ -2745,7 +2752,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { let with = dragged_with(app, &id); // Snap the dragged point (or the line's ends) to other geometry, like drawing. let snap = { - let st = app.session.world_state(); + let st = crate::open_meshing::shown_world(app); app.session.active_sketch.and_then(|s| st.sketch(s)).and_then(|ss| { let sk = &ss.sketch; let (mut own, mut exclude) = crate::drag_snap::moving_points(sk, &id); @@ -3083,7 +3090,7 @@ fn box_select(app: &mut SolveApp, proj: &Proj, bx: BoxSel, add: bool) { if app.applying.is_some() { return; } - let st = app.session.world_state(); + let st = crate::open_meshing::shown_world(app); let mut out: Vec = Vec::new(); let to2 = |pts: &[Vec3]| -> Vec { pts.iter().filter_map(|p| proj.to_screen(*p)).collect() }; let sketch_dialog = app.dialog.as_ref().is_some_and(|d| matches!(d.kind, crate::dialogs::Kind::SketchModify(_))); @@ -3271,7 +3278,7 @@ fn grid_centre(tf: Vec3, back: Vec3, n: Vec3, ext: f64) -> Vec3 { /// Hover feedback for the active sketch's points and curves (drawn on top of everything). fn hover_highlight(app: &SolveApp, painter: &egui::Painter, proj: &Proj) { let col = Tokens::get().hover_profile_edge; - let st = app.session.world_state(); + let st = crate::open_meshing::shown_world(app); match &app.viewport.hover { // Trim shows the piece it would take away instead (`sketch_tools::preview`, #3052). Some(Hit::SketchCurve { sketch, id, .. }) if crate::sketch_tools::trim_hover_piece(app, *sketch, id).is_some() => {} @@ -3326,7 +3333,7 @@ pub(crate) fn standalone_points(app: &SolveApp) -> Vec { /// Sketch points and the status of the active sketch (constraint glyphs: `sketch_tools`). fn overlays(app: &SolveApp, painter: &egui::Painter, proj: &Proj) { let t = Tokens::get(); - let st = app.session.world_state(); + let st = crate::open_meshing::shown_world(app); for item in &app.session.selection { if let Sel::ExternalSketchPoint { sketch, id } = item && let Some(ss) = st.sketch(*sketch) From 876d57a67b4d1c6755bb4a1ecb0c68e6bf1fb286 Mon Sep 17 00:00:00 2001 From: Georgette Date: Tue, 20 Oct 2026 12:28:11 +0000 Subject: [PATCH 202/225] Mouse gestures: ring of tools on the right button, per studio and customizable (#2934) (#2936) * Mouse gestures: a ring of tools on the right button, per studio and customizable Preferences > Navigation gets a Mouse gestures switch and a Customize window (number of tools and their place, per studio). Gestures need the SolidWorks mouse mode and turn the right-drag orbit off. The ring is 280/350 pt, one zone per tool, alternating tints (three when the count is odd). The radial context menu is unchanged. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Dwcq9eNUMZ1jNeKvWd1bcZ * Mouse gestures: the ring opens on the right-button press; the right-click menus are off while gestures are on The ring opens at once on the press, even while a tool or dialog is active. While gestures are active the viewport's right-click context menu, the right-click that finishes a tool and the radial context menu no longer fire. With gestures off nothing changes. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Dwcq9eNUMZ1jNeKvWd1bcZ * Mouse gestures: the ring opens after 4 px with the right button held; a plain right-click keeps its menu The ring no longer opens on the press. It opens where the button went down once the pointer has moved 4 points with the button held, even while a tool is in progress. A right-click that does not move opens the usual context menu (or finishes the tool) again; the release that ends a gesture opens no menu. The radial menu stays off while gestures are active. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Dwcq9eNUMZ1jNeKvWd1bcZ * Re-trigger CI (the run was cancelled when approved-for-ci was added) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Dwcq9eNUMZ1jNeKvWd1bcZ --------- Co-authored-by: Claude --- crates/ui-egui/src/context_menu.rs | 8 +- crates/ui-egui/src/lib.rs | 6 + crates/ui-egui/src/mouse_gesture.rs | 1201 +++++++++++++++++++++++++++ crates/ui-egui/src/prefs.rs | 9 + crates/ui-egui/src/viewport.rs | 3 +- docs/book/src/guide/ui-tour.md | 9 + 6 files changed, 1231 insertions(+), 5 deletions(-) create mode 100644 crates/ui-egui/src/mouse_gesture.rs diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index 871e4e600..46429a9c5 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -129,7 +129,7 @@ impl Item { pub fn on_if(self, enabled: bool) -> Item { self.on(enabled) } - fn on(mut self, enabled: bool) -> Item { + pub(crate) fn on(mut self, enabled: bool) -> Item { self.enabled &= enabled; self } @@ -140,7 +140,7 @@ impl Item { } /// A command entry: label, icon, shortcut and enablement come from the registry. -fn cmd(app: &SolveApp, id: &str, label: &str) -> Item { +pub(crate) fn cmd(app: &SolveApp, id: &str, label: &str) -> Item { let info = solidcraft_engine::find_command(id).map(|c| c.info(&app.session)); let shortcut = match id { "edit.undo" => "Ctrl+Z".to_string(), @@ -158,7 +158,7 @@ fn cmd(app: &SolveApp, id: &str, label: &str) -> Item { } /// A view action (`ui.*`). -fn act(id: &str, label: &str, icon: &str) -> Item { +pub(crate) fn act(id: &str, label: &str, icon: &str) -> Item { Item { id: id.into(), label: label.into(), shortcut: String::new(), enabled: true, icon: icon.into(), params: None } } @@ -1604,7 +1604,7 @@ fn slot_rect(c: Pos2, k: usize, size: Vec2) -> Rect { /// Press-and-hold of the right button in the viewport opens the menu; releasing over a /// direction picks it. fn track_hold(app: &mut SolveApp, ctx: &egui::Context) { - if !app.preferences.radial_context_menu { + if !app.preferences.radial_context_menu || crate::mouse_gesture::active(app) { app.menu.press = None; app.menu.flick = false; app.menu.radial = false; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5fbbe848a..1b3b9a446 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -77,6 +77,7 @@ mod loft_rails_dialog_tests; #[cfg(test)] mod look_at_tests; mod material_card_review; + #[cfg(test)] mod measurement_ui_tests; #[cfg(test)] @@ -130,6 +131,7 @@ pub(crate) mod display_lod; mod file_load_ui_tests; #[cfg(test)] mod fillet_spline_handle_tests; +pub mod mouse_gesture; pub(crate) mod navigation; pub(crate) mod open_meshing; pub mod palette; @@ -339,6 +341,8 @@ pub struct SolveApp { pub palette: palette::Palette, /// Context menus, rename box and Properties window. pub menu: context_menu::MenuState, + /// Mouse gestures: the ring of tools and its customization window. + pub gesture: mouse_gesture::State, /// Browser tree state (reveal, groups being edited, occurrence moves). pub tree: browser::TreeState, /// A saved design copied for insertion into another open document. @@ -486,6 +490,7 @@ impl SolveApp { material_card_review: None, palette: palette::Palette::default(), menu: context_menu::MenuState::default(), + gesture: mouse_gesture::State::default(), tree: browser::TreeState::default(), linked_design_clipboard: None, sbox: shortcut_box::ShortcutBox::default(), @@ -1514,6 +1519,7 @@ impl SolveApp { stand_up::show(self, ui.ctx()); prefs::show_reset_notice(self, ui.ctx()); context_menu::show(self, ui.ctx()); + mouse_gesture::show(self, ui.ctx()); delete::show(self, ui.ctx()); shortcut_box::show(self, ui.ctx()); prefs::show(self, ui.ctx()); diff --git a/crates/ui-egui/src/mouse_gesture.rs b/crates/ui-egui/src/mouse_gesture.rs new file mode 100644 index 000000000..55c8f9594 --- /dev/null +++ b/crates/ui-egui/src/mouse_gesture.rs @@ -0,0 +1,1201 @@ +//! Mouse gestures: a ring of tools that opens under the pointer when the right button is held and +//! the pointer moves [`OPEN_DRAG`] points, a different set in each studio, taken by touching a +//! tool's zone. +//! +//! Gestures work with the SolidWorks mouse mode only (the wheel orbits, Ctrl + wheel pans). While +//! they are on, the right button no longer orbits the view (`prefs::nav_mode`) and the optional +//! radial menu is off (`context_menu::track_hold` asks [`active`]). A right-click that does not +//! move still opens the usual context menu (or finishes the tool in progress); one that moves +//! far enough opens the ring instead, even while a tool is in progress, and the click that ends +//! it opens no menu ([`took_press`]). With gestures off nothing changes. +//! +//! The ring is 280 points across inside and 350 outside. Every tool has a zone, and only tools +//! have zones: five tools make five equal parts of the circle. Zones alternate between two tints, +//! with a third one on the last zone when their number is odd, so no two zones side by side +//! share a tint ([`tint`]). A tool is taken as soon as the pointer leaves the hub into its zone +//! ([`entered`]); the zones reach outward without limit. +//! +//! A [`Studio`] is the part of the application the person is working in: a tab of the Design +//! workspace, a sketch being edited, or the Render workspace. Each has its own default tools, and +//! [`Config`] (kept with the preferences, edited in [`editor`]) holds the person's own list for +//! any of them: how many tools and in which place, clockwise from the top. + +use std::collections::BTreeMap; + +use egui::{Align2, Color32, FontId, Mesh, Painter, Pos2, Rect, Sense, Shape, Stroke, Vec2, pos2, vec2}; +use serde::{Deserialize, Serialize}; + +use crate::SolveApp; +use crate::context_menu::{Item, act, cmd}; +use crate::theme::Tokens; + +/// Most tools one ring may hold. +pub(crate) const MAX_TOOLS: usize = 12; +/// Radius of the hub: the ring is 280 points across inside. +pub(crate) const HUB: f32 = 140.0; +/// Outer radius: 350 points across. The zones themselves continue outward. +pub(crate) const RING: f32 = 175.0; +/// Space between two drawn zones, in degrees. +const GAP: f32 = 1.5; +/// Points sampled along one frame's pointer move when looking for the zone it touched. +const SAMPLES: usize = 48; +/// The only mouse mode gestures work with. +pub(crate) const MOUSE_MODE: &str = "solidworks"; + +// --------------------------------------------------------------------------------------------- +// Studios and their tools +// --------------------------------------------------------------------------------------------- + +/// Where the person is working. Each studio has its own ring. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(crate) enum Studio { + /// The Solid tab (and the tabs that have no ring of their own). + Part, + /// A sketch is being edited. + Sketch, + Surface, + SheetMetal, + Plastic, + Mesh, + /// The Render workspace. + Render, +} + +const PART: [&str; 8] = ["repeat", "delete", "solid.press_pull", "solid.hole", "sketch.create", "solid.extrude", "undo", "solid.move"]; +const SKETCH: [&str; 8] = + ["repeat", "delete", "sketch.line", "sketch.rectangle.two_point", "ui.finishSketch", "sketch.circle.center", "undo", "sketch.dimension"]; +const SURFACE: [&str; 8] = ["repeat", "delete", "surface.extrude", "surface.loft", "sketch.create", "surface.patch", "undo", "surface.trim"]; +const SHEET_METAL: [&str; 8] = ["repeat", "delete", "sheet.flange", "sheet.hem", "sketch.create", "sheet.fold", "undo", "sheet.flat_pattern"]; +const PLASTIC: [&str; 8] = ["repeat", "delete", "plastic.boss", "plastic.lip", "sketch.create", "plastic.snap_fit", "undo", "plastic.rest"]; +const MESH: [&str; 8] = ["repeat", "delete", "file.save_mesh", "inspect.measure", "inspect.section", "solid.move", "undo", "inspect.interference"]; +const RENDER: [&str; 8] = ["render.start", "render.scene", "ui.fit", "ui.home", "ui.workspace.design", "repeat", "undo", "ui.clear"]; + +impl Studio { + pub(crate) const ALL: [Studio; 7] = + [Studio::Part, Studio::Sketch, Studio::Surface, Studio::SheetMetal, Studio::Plastic, Studio::Mesh, Studio::Render]; + + /// The studio the application is in now. + pub(crate) fn of(app: &SolveApp) -> Studio { + if crate::render_workspace::active(app) { + Studio::Render + } else if app.session.active_sketch.is_some() { + Studio::Sketch + } else { + match app.ui.tab.as_str() { + "SURFACE" => Studio::Surface, + "SHEET METAL" => Studio::SheetMetal, + "PLASTIC" => Studio::Plastic, + "MESH" => Studio::Mesh, + _ => Studio::Part, + } + } + } + + /// The name the preferences keep this studio's list under. + pub(crate) fn key(self) -> &'static str { + match self { + Studio::Part => "part", + Studio::Sketch => "sketch", + Studio::Surface => "surface", + Studio::SheetMetal => "sheet_metal", + Studio::Plastic => "plastic", + Studio::Mesh => "mesh", + Studio::Render => "render", + } + } + + pub(crate) fn label(self) -> &'static str { + match self { + Studio::Part => "Part", + Studio::Sketch => "Sketch", + Studio::Surface => "Surface", + Studio::SheetMetal => "Sheet Metal", + Studio::Plastic => "Plastic", + Studio::Mesh => "Mesh", + Studio::Render => "Render", + } + } + + /// The studio's tools as shipped, clockwise from the top. + pub(crate) fn defaults(self) -> &'static [&'static str] { + match self { + Studio::Part => &PART, + Studio::Sketch => &SKETCH, + Studio::Surface => &SURFACE, + Studio::SheetMetal => &SHEET_METAL, + Studio::Plastic => &PLASTIC, + Studio::Mesh => &MESH, + Studio::Render => &RENDER, + } + } +} + +/// Tools that are not commands: what they are called in a list of tools. +const SPECIALS: [(&str, &str); 3] = [("repeat", "Repeat"), ("delete", "Delete"), ("undo", "Undo")]; +/// View actions (`ui.*`): id, label, icon. +const ACTIONS: [(&str, &str, &str); 5] = [ + ("ui.fit", "Fit", "fit"), + ("ui.home", "Home View", "home"), + ("ui.finishSketch", "Finish Sketch", "finish"), + ("ui.workspace.design", "Design Workspace", "box"), + ("ui.clear", "Clear Selection", ""), +]; + +/// A command's label without its shortcut hint: `Line (L)` is `Line`. +fn short(label: &str) -> &str { + label.split(" (").next().unwrap_or(label).trim() +} + +/// What a tool is called, or none when `id` is not a tool. +pub(crate) fn label_of(id: &str) -> Option { + if let Some((_, label)) = SPECIALS.iter().find(|(i, _)| *i == id) { + return Some((*label).to_string()); + } + if let Some((_, label, _)) = ACTIONS.iter().find(|(i, _, _)| *i == id) { + return Some((*label).to_string()); + } + solidcraft_engine::find_command(id).map(|spec| short(spec.label).to_string()) +} + +/// The tool `id` as a menu item (its state follows the design), or none for an unknown id. +pub(crate) fn item(app: &SolveApp, id: &str) -> Option { + match id { + "repeat" => Some(match &app.last_command { + Some((_, label)) => act("ui.repeat", &format!("Repeat {label}"), "redo"), + None => act("ui.repeat", "Repeat", "redo").on(false), + }), + "delete" => Some(act("ui.delete", "Delete", "delete").key("Del").on(!app.session.selection.is_empty())), + "undo" => Some(cmd(app, "edit.undo", "Undo").on(!app.session.undo.is_empty())), + _ => match ACTIONS.iter().find(|(i, _, _)| *i == id) { + Some((i, label, icon)) => Some(act(i, label, icon)), + None => solidcraft_engine::find_command(id).map(|spec| cmd(app, spec.id, short(spec.label))), + }, + } +} + +/// Every tool a ring can hold, as (id, label): the specials and view actions, then the commands +/// that sit on the toolbar. +pub(crate) fn catalog() -> Vec<(String, String)> { + let mut v: Vec<(String, String)> = SPECIALS.iter().map(|(i, l)| ((*i).to_string(), (*l).to_string())).collect(); + v.extend(ACTIONS.iter().map(|(i, l, _)| ((*i).to_string(), (*l).to_string()))); + for spec in solidcraft_engine::command_specs() { + if !spec.tab.is_empty() && spec.planned.is_none() && !v.iter().any(|(i, _)| i == spec.id) { + v.push((spec.id.to_string(), short(spec.label).to_string())); + } + } + v +} + +// --------------------------------------------------------------------------------------------- +// The person's settings +// --------------------------------------------------------------------------------------------- + +/// The gesture settings, kept with the preferences. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Config { + /// Gestures are on (they also need the SolidWorks mouse mode, see [`active`]). + pub enabled: bool, + /// A studio's own list of tool ids, clockwise from the top, by [`Studio::key`]. A studio + /// without an entry uses its default tools. + pub wheels: BTreeMap>, +} + +impl Config { + /// The tool ids of `studio`: the person's list cleaned of unknown and repeated ids and cut + /// to [`MAX_TOOLS`], or the studio's defaults when nothing usable is left. + pub(crate) fn tools(&self, studio: Studio) -> Vec { + let mut out: Vec = Vec::new(); + for id in self.wheels.get(studio.key()).into_iter().flatten() { + if out.len() < MAX_TOOLS && label_of(id).is_some() && !out.contains(id) { + out.push(id.clone()); + } + } + if out.is_empty() { studio.defaults().iter().map(|s| (*s).to_string()).collect() } else { out } + } + + /// Whether `studio` has a list of its own. + pub(crate) fn is_custom(&self, studio: Studio) -> bool { + self.wheels.contains_key(studio.key()) + } + + pub(crate) fn set_tools(&mut self, studio: Studio, tools: Vec) { + self.wheels.insert(studio.key().to_string(), tools); + } + + /// Puts `studio` back to its default tools. + pub(crate) fn reset(&mut self, studio: Studio) { + self.wheels.remove(studio.key()); + } +} + +/// Gestures are on and the mouse mode allows them. +pub(crate) fn active(app: &SolveApp) -> bool { + app.preferences.mouse_gestures.enabled && app.preferences.nav == MOUSE_MODE +} + +/// The ring's tools in `studio` as menu items, unknown ids dropped. +pub(crate) fn items(app: &SolveApp, studio: Studio) -> Vec { + app.preferences.mouse_gestures.tools(studio).iter().filter_map(|id| item(app, id)).collect() +} + +// --------------------------------------------------------------------------------------------- +// Geometry +// --------------------------------------------------------------------------------------------- + +/// The zone of an `n`-tool ring a pointer offset from its centre is in: none inside the hub. +/// Zone 0 is centred on the top and the rest follow clockwise (screen y points down); each takes +/// `360 / n` degrees. +pub(crate) fn sector(d: Vec2, n: usize) -> Option { + if n == 0 || !d.is_finite() || d.length() < HUB { + return None; + } + let step = 360.0 / n as f32; + let a = d.x.atan2(-d.y).to_degrees(); + let k = ((a + 360.0 + step / 2.0) / step).floor() as i64; + Some(k.rem_euclid(n as i64) as usize) +} + +/// The enabled tool whose zone the pointer touched moving straight from `from` to `to` around a +/// ring centred at `c` with `enabled.len()` tools: the first one on the way, so a fast stroke +/// between two frames still takes the tool it began toward. Zones that are off are passed over. +pub(crate) fn entered(c: Pos2, from: Pos2, to: Pos2, enabled: &[bool]) -> Option { + if !(c.is_finite() && from.is_finite() && to.is_finite()) { + return None; + } + let n = enabled.len(); + let on = |p: Pos2| sector(p - c, n).filter(|k| enabled.get(*k).copied().unwrap_or(false)); + let (f, d) = (from - c, to - from); + // Leaving the hub: the zone is the one at the exit point, which a sample could step past. + let a = d.dot(d); + if f.length() < HUB && a > 1e-9 { + let (b, cc) = (2.0 * f.dot(d), f.dot(f) - HUB * HUB); + let disc = b * b - 4.0 * a * cc; + if disc >= 0.0 { + let t = (-b + disc.sqrt()) / (2.0 * a); + if (0.0..=1.0).contains(&t) { + // A hair past the edge, so rounding can't leave the point in the hub. + if let Some(k) = on(c + (f + d * t) * 1.001) { + return Some(k); + } + } + } + } + (1..=SAMPLES).find_map(|i| on(from + d * (i as f32 / SAMPLES as f32))) +} + +/// Which of the three tints zone `k` of `n` takes: 0 and 1 alternate, and when `n` is odd the +/// last zone takes 2, so it differs from both its neighbours (the one before it and zone 0). +pub(crate) fn tint(n: usize, k: usize) -> usize { + if n % 2 == 1 && n > 1 && k == n - 1 { 2 } else { k % 2 } +} + +/// The three tints, from the theme. +fn palette(t: &Tokens) -> [Color32; 3] { + [t.panel, t.panel.lerp_to_gamma(t.text, 0.30), t.panel.lerp_to_gamma(t.text, 0.55)] +} + +/// How far (points) the pointer moves with the right button held before the ring opens; a press +/// that stays inside this is a right-click. +pub(crate) const OPEN_DRAG: f32 = 4.0; + +/// Where a ring opened by a press at `at` is centred: there, or as near as keeps it on screen. +fn centre_for(at: Pos2, screen: Rect) -> Pos2 { + let m = RING + 6.0; + let x = if screen.width() > 2.0 * m { at.x.clamp(screen.left() + m, screen.right() - m) } else { screen.center().x }; + let y = if screen.height() > 2.0 * m { at.y.clamp(screen.top() + m, screen.bottom() - m) } else { screen.center().y }; + pos2(x, y) +} + +// --------------------------------------------------------------------------------------------- +// Drawing +// --------------------------------------------------------------------------------------------- + +/// Draws the ring centred at `c`, `scale` times its real size: one zone per tool, tinted +/// alternately, the zone the pointer is in lit, an icon in each, and in the hub the lit tool's +/// name (the studio's when none is). +pub(crate) fn paint(painter: &Painter, c: Pos2, scale: f32, studio: Studio, items: &[Item], pointer: Option, t: Tokens) { + let n = items.len(); + if n == 0 { + return; + } + let (hub, ring) = (HUB * scale, RING * scale); + let hot = pointer.and_then(|p| sector((p - c) / scale, n)); + let tints = palette(&t); + let step = 360.0 / n as f32; + let gap = if n > 1 { GAP } else { 0.0 }; + painter.circle(c, hub, t.panel.gamma_multiply(0.5), Stroke::new(1.0, t.border)); + for (k, item) in items.iter().enumerate() { + let lit = item.enabled && hot == Some(k); + let base = tints[tint(n, k)]; + let (fill, edge) = match (item.enabled, lit) { + (_, true) => (t.accent_soft, t.accent), + (true, false) => (base, t.border), + (false, false) => (base.gamma_multiply(0.6), t.border.gamma_multiply(0.7)), + }; + let mid = k as f32 * step; + zone(painter, c, hub, ring, mid - step / 2.0 + gap / 2.0, mid + step / 2.0 - gap / 2.0, fill, edge); + if !item.icon.is_empty() { + let a = mid.to_radians(); + let at = c + vec2(a.sin(), -a.cos()) * (hub + ring) / 2.0; + let ink = if item.enabled { t.icon } else { t.border }; + let side = (24.0 * scale).max(12.0); + crate::icons::paint(painter, Rect::from_center_size(at, vec2(side, side)), &item.icon, ink, t.icon_fill, t.accent); + } + } + match hot.and_then(|k| items.get(k)).filter(|i| i.enabled) { + Some(item) => { + painter.text(c, Align2::CENTER_CENTER, crate::i18n::tr_label(&item.label), FontId::proportional((20.0 * scale).max(9.0)), t.text) + } + None => { + painter.text(c, Align2::CENTER_CENTER, crate::i18n::tr_label(studio.label()), FontId::proportional((16.0 * scale).max(9.0)), t.text_dim) + } + }; +} + +/// One zone of the ring, between `a0` and `a1` degrees clockwise from the top. +fn zone(painter: &Painter, c: Pos2, inner: f32, outer: f32, a0: f32, a1: f32, fill: Color32, edge: Color32) { + let at = |deg: f32, r: f32| { + let a = deg.to_radians(); + c + vec2(a.sin(), -a.cos()) * r + }; + let steps = (((a1 - a0) / 3.0).ceil() as usize).clamp(2, 120); + let mut mesh = Mesh::default(); + let mut outline: Vec = Vec::with_capacity(2 * (steps + 1)); + for i in 0..=steps { + let deg = a0 + (a1 - a0) * i as f32 / steps as f32; + mesh.colored_vertex(at(deg, inner), fill); + mesh.colored_vertex(at(deg, outer), fill); + outline.push(at(deg, outer)); + if i < steps { + let k = 2 * i as u32; + mesh.add_triangle(k, k + 1, k + 2); + mesh.add_triangle(k + 1, k + 3, k + 2); + } + } + for i in (0..=steps).rev() { + outline.push(at(a0 + (a1 - a0) * i as f32 / steps as f32, inner)); + } + painter.add(Shape::mesh(mesh)); + painter.add(Shape::closed_line(outline, Stroke::new(1.0, edge))); +} + +// --------------------------------------------------------------------------------------------- +// The gesture +// --------------------------------------------------------------------------------------------- + +/// What gestures keep between frames. +#[derive(Default)] +pub struct State { + /// The ring that is open. + wheel: Option, + /// Where the right button went down, until the pointer has moved [`OPEN_DRAG`] from it. + press: Option, + /// The right button that is down (or was last) opened a ring: its release is no click. + used: bool, + /// The customization window. + pub(crate) editor: Editor, +} + +struct Wheel { + centre: Pos2, + studio: Studio, + /// The pointer on the last frame: the move since then is what may touch a zone. + from: Pos2, + /// The pointer has been in the hub since the ring opened, so a zone it is in is one it moved + /// into (a ring pushed off the screen's edge opens with the pointer outside its hub). + armed: bool, +} + +/// One frame of gestures: opens, runs and closes the ring, draws it, and shows the editor. +pub fn show(app: &mut SolveApp, ctx: &egui::Context) { + track(app, ctx); + paint_open(app, ctx); + editor(app, ctx); +} + +/// The right button last pressed opened the ring, so letting go of it is not a right-click. +pub(crate) fn took_press(app: &SolveApp) -> bool { + app.gesture.used +} + +/// Whether a ring is open. +#[cfg(test)] +pub(crate) fn is_open(app: &SolveApp) -> bool { + app.gesture.wheel.is_some() +} + +fn track(app: &mut SolveApp, ctx: &egui::Context) { + if !active(app) { + app.gesture.wheel = None; + app.gesture.press = None; + app.gesture.used = false; + return; + } + let (pressed, down, pos, esc) = ctx.input(|i| { + ( + i.pointer.button_pressed(egui::PointerButton::Secondary), + i.pointer.secondary_down(), + i.pointer.latest_pos(), + i.key_pressed(egui::Key::Escape), + ) + }); + // Letting go, or Esc, leaves nothing half-way. + if !down || esc { + app.gesture.wheel = None; + app.gesture.press = None; + return; + } + let Some(pos) = pos else { return }; + // A press in the viewport waits to see whether it is a click or the start of a gesture. + if pressed { + app.gesture.used = false; + app.gesture.press = (app.gesture.wheel.is_none() && app.viewport.mouse.is_some()).then_some(pos); + } + // Held and moved far enough: the ring opens where the button went down, whatever the pointer + // carries (a tool or a dialog in progress included). + if let Some(at) = app.gesture.press + && (pos - at).length() >= OPEN_DRAG + { + app.gesture.press = None; + let studio = Studio::of(app); + if !items(app, studio).is_empty() { + let centre = centre_for(at, ctx.content_rect()); + app.gesture.wheel = Some(Wheel { centre, studio, from: at, armed: (at - centre).length() < HUB }); + app.gesture.used = true; + } + } + let Some((centre, studio, from, armed)) = app.gesture.wheel.as_mut().map(|w| { + let from = w.from; + w.from = pos; + w.armed |= (from - w.centre).length() < HUB; + (w.centre, w.studio, from, w.armed) + }) else { + return; + }; + if !armed { + return; + } + let list = items(app, studio); + let enabled: Vec = list.iter().map(|i| i.enabled).collect(); + if let Some(k) = entered(centre, from, pos, &enabled) + && let Some(tool) = list.get(k) + { + app.gesture.wheel = None; + crate::context_menu::run_item(app, tool, centre); + } +} + +fn paint_open(app: &SolveApp, ctx: &egui::Context) { + let Some(wheel) = &app.gesture.wheel else { return }; + let list = items(app, wheel.studio); + let t = Tokens::get(); + let pointer = ctx.input(|i| i.pointer.latest_pos()); + let area = Rect::from_center_size(wheel.centre, vec2(2.0 * (RING + 6.0), 2.0 * (RING + 6.0))); + crate::frame::area(egui::Id::new("sc_mouse_gesture")).fixed_pos(area.min).order(egui::Order::Foreground).show(ctx, |ui| { + let (r, _) = ui.allocate_exact_size(area.size(), Sense::hover()); + paint(&ui.painter_at(r.expand(4.0)), wheel.centre, 1.0, wheel.studio, &list, pointer, t); + }); +} + +// --------------------------------------------------------------------------------------------- +// Customization +// --------------------------------------------------------------------------------------------- + +/// The customization window's state. +pub(crate) struct Editor { + pub(crate) open: bool, + pub(crate) studio: Studio, +} + +impl Default for Editor { + fn default() -> Self { + Editor { open: false, studio: Studio::Part } + } +} + +/// A change to a list of tools. +#[derive(Clone, Debug, PartialEq)] +enum Op { + Up(usize), + Down(usize), + Remove(usize), + Add, + Set(usize, String), +} + +/// The first tool of the catalog that `list` doesn't hold. +fn next_unused(list: &[String]) -> Option { + catalog().into_iter().map(|(id, _)| id).find(|id| !list.contains(id)) +} + +/// Applies `op` to `list`; false when it was refused (a ring keeps 1 to [`MAX_TOOLS`] tools, each +/// of them known and none twice). +fn apply(list: &mut Vec, op: Op) -> bool { + match op { + Op::Up(i) if i > 0 && i < list.len() => { + list.swap(i, i - 1); + true + } + Op::Down(i) if i + 1 < list.len() => { + list.swap(i, i + 1); + true + } + Op::Remove(i) if list.len() > 1 && i < list.len() => { + list.remove(i); + true + } + Op::Add if list.len() < MAX_TOOLS => match next_unused(list) { + Some(id) => { + list.push(id); + true + } + None => false, + }, + Op::Set(i, id) if i < list.len() && label_of(&id).is_some() && !list.contains(&id) => { + list[i] = id; + true + } + _ => false, + } +} + +/// The rows of Preferences › Navigation that belong to gestures: the switch, the button that +/// opens the editor, and what the mouse mode has to be. +pub(crate) fn nav_rows(app: &mut SolveApp, ui: &mut egui::Ui, t: &Tokens) { + let note = |ui: &mut egui::Ui, s: &str| { + ui.label(""); + ui.add(egui::Label::new(egui::RichText::new(crate::i18n::tr_label(s)).size(11.0).color(t.text_dim)).wrap()); + ui.end_row(); + }; + ui.label(crate::i18n::tr_label("Mouse gestures")); + ui.horizontal(|ui| { + ui.checkbox(&mut app.preferences.mouse_gestures.enabled, crate::i18n::tr_label("Ring of tools on the right button")); + if ui.button(crate::i18n::tr_label("Customize…")).clicked() { + app.gesture.editor.open = true; + app.gesture.editor.studio = Studio::of(app); + } + }); + ui.end_row(); + if app.preferences.nav != MOUSE_MODE { + ui.label(""); + ui.horizontal_wrapped(|ui| { + ui.colored_label( + t.warning, + crate::i18n::tr_label("Mouse gestures only work with the SolidWorks mouse mode (the wheel orbits, Ctrl + wheel pans)."), + ); + if ui.button(crate::i18n::tr_label("Use the SolidWorks mouse mode")).clicked() { + app.preferences.nav = MOUSE_MODE.to_string(); + app.preferences.zoom_reverse = crate::prefs::nav_preset(MOUSE_MODE).reverse_zoom; + } + }); + ui.end_row(); + } else if app.preferences.mouse_gestures.enabled { + note( + ui, + "With gestures on, the right button no longer orbits the view: hold it and move to open the ring, then touch a tool's zone. A plain right-click still opens the menu.", + ); + } +} + +/// The customization window: pick a studio, then how many tools its ring holds, which, and in +/// which place (clockwise from the top), with a preview of the ring. +fn editor(app: &mut SolveApp, ctx: &egui::Context) { + if !app.gesture.editor.open { + return; + } + let t = Tokens::get(); + let mut open = true; + let mut studio = app.gesture.editor.studio; + let mut config = app.preferences.mouse_gestures.clone(); + crate::frame::window(ctx, crate::i18n::tr_label("Mouse gestures"), crate::frame::Width::Wide) + .id(egui::Id::new("sc_gesture_editor")) + .open(&mut open) + .show(ctx, |ui| { + ui.checkbox(&mut config.enabled, crate::i18n::tr_label("Ring of tools on the right button")); + if app.preferences.nav != MOUSE_MODE { + ui.colored_label( + t.warning, + crate::i18n::tr_label("Mouse gestures only work with the SolidWorks mouse mode (the wheel orbits, Ctrl + wheel pans)."), + ); + } + ui.horizontal(|ui| { + ui.label(crate::i18n::tr_label("Studio")); + egui::ComboBox::from_id_salt("gesture_studio").selected_text(crate::i18n::tr_label(studio.label())).show_ui(ui, |ui| { + for s in Studio::ALL { + ui.selectable_value(&mut studio, s, crate::i18n::tr_label(s.label())); + } + }); + if ui.add_enabled(config.is_custom(studio), egui::Button::new(crate::i18n::tr_label("Restore this studio's tools"))).clicked() { + config.reset(studio); + } + }); + ui.separator(); + let mut list = config.tools(studio); + let catalog = catalog(); + let mut op: Option = None; + ui.horizontal_top(|ui| { + ui.vertical(|ui| { + ui.set_min_width(330.0); + ui.label( + egui::RichText::new(format!("{} {}/{}", crate::i18n::tr_label("Tools, clockwise from the top"), list.len(), MAX_TOOLS)) + .size(11.0) + .color(t.text_dim), + ); + for i in 0..list.len() { + ui.horizontal(|ui| { + ui.label(format!("{}", i + 1)); + let shown = label_of(&list[i]).unwrap_or_default(); + egui::ComboBox::from_id_salt(("gesture_tool", i)).selected_text(shown).width(200.0).show_ui(ui, |ui| { + let filter_id = ui.id().with("filter"); + let mut filter: String = ui.data_mut(|d| d.get_temp(filter_id).unwrap_or_default()); + ui.add(egui::TextEdit::singleline(&mut filter).hint_text(crate::i18n::tr_label("Filter…"))); + ui.data_mut(|d| d.insert_temp(filter_id, filter.clone())); + let needle = filter.trim().to_lowercase(); + egui::ScrollArea::vertical().max_height(260.0).show(ui, |ui| { + for (id, label) in &catalog { + if !needle.is_empty() && !label.to_lowercase().contains(&needle) && !id.to_lowercase().contains(&needle) { + continue; + } + let taken = list.contains(id) && *id != list[i]; + let r = ui.add_enabled(!taken, egui::Button::selectable(*id == list[i], label.as_str())); + if r.clicked() { + op = Some(Op::Set(i, id.clone())); + ui.close(); + } + } + }); + }); + if ui.add_enabled(i > 0, egui::Button::new("↑")).clicked() { + op = Some(Op::Up(i)); + } + if ui.add_enabled(i + 1 < list.len(), egui::Button::new("↓")).clicked() { + op = Some(Op::Down(i)); + } + if ui.add_enabled(list.len() > 1, egui::Button::new("×")).clicked() { + op = Some(Op::Remove(i)); + } + }); + } + if ui.add_enabled(list.len() < MAX_TOOLS, egui::Button::new(crate::i18n::tr_label("Add a tool"))).clicked() { + op = Some(Op::Add); + } + }); + ui.separator(); + // The ring as it will look, a little smaller. + let scale = 0.62; + let side = 2.0 * RING * scale + 8.0; + let (r, _) = ui.allocate_exact_size(vec2(side, side), Sense::hover()); + // Every tool as available, whatever the design allows now. + let preview: Vec = list + .iter() + .filter_map(|id| item(app, id)) + .map(|mut i| { + i.enabled = true; + i + }) + .collect(); + paint(&ui.painter_at(r), r.center(), scale, studio, &preview, None, t); + }); + if let Some(op) = op + && apply(&mut list, op) + { + config.set_tools(studio, list); + } + }); + app.gesture.editor.studio = studio; + app.preferences.mouse_gestures = config; + app.gesture.editor.open = open; +} + +#[cfg(test)] +mod tests { + use super::*; + use egui::pos2; + + fn app() -> SolveApp { + SolveApp::new(solidcraft_engine::Session::default(), Default::default()) + } + + fn on(n: usize) -> Vec { + vec![true; n] + } + + #[test] + fn the_ring_is_280_inside_and_350_outside() { + assert_eq!(HUB * 2.0, 280.0); + assert_eq!(RING * 2.0, 350.0); + } + + #[test] + fn a_ring_of_n_tools_is_n_equal_parts_of_the_circle() { + for n in 1..=MAX_TOOLS { + let mut seen = vec![0usize; n]; + // Walk the whole circle: every zone is met, none is missing, and each is the same size. + for deg in 0..3600 { + let a = (deg as f32 / 10.0).to_radians(); + let k = sector(vec2(a.sin(), -a.cos()) * (HUB + 10.0), n).expect("outside the hub"); + seen[k] += 1; + } + let (lo, hi) = (seen.iter().min().copied().unwrap_or(0), seen.iter().max().copied().unwrap_or(0)); + assert!(lo > 0, "{n} tools: a part of the circle has no tool: {seen:?}"); + assert!(hi - lo <= 2, "{n} tools: parts of different sizes: {seen:?}"); + } + } + + #[test] + fn zones_are_centred_clockwise_from_the_top_and_the_hub_has_none() { + let far = |x: f32, y: f32| vec2(x, y) * 400.0; + for (n, expect) in [(4, [0, 1, 2, 3]), (8, [0, 2, 4, 6])] { + let got = [sector(far(0.0, -1.0), n), sector(far(1.0, 0.0), n), sector(far(0.0, 1.0), n), sector(far(-1.0, 0.0), n)]; + let want: Vec> = if n == 4 { expect.iter().map(|k| Some(*k)).collect() } else { expect.iter().map(|k| Some(*k)).collect() }; + assert_eq!(got.to_vec(), want, "{n} tools"); + } + assert_eq!(sector(vec2(0.0, -(HUB - 1.0)), 5), None); + assert_eq!(sector(vec2(0.0, -(HUB + 1.0)), 5), Some(0)); + assert_eq!(sector(vec2(f32::NAN, 200.0), 5), None); + assert_eq!(sector(vec2(0.0, -200.0), 0), None, "no tools, no zones"); + assert_eq!(sector(vec2(0.0, -9000.0), 5), Some(0), "a zone reaches outward without limit"); + // Five tools: 72 degrees each, so the zone to the right (90 degrees) is the second. + assert_eq!(sector(far(1.0, 0.0), 5), Some(1)); + } + + #[test] + fn no_two_zones_side_by_side_share_a_tint() { + for n in 2..=MAX_TOOLS { + for k in 0..n { + assert_ne!(tint(n, k), tint(n, (k + 1) % n), "{n} tools: zones {k} and {} match", (k + 1) % n); + } + let used = (0..n).map(|k| tint(n, k)).collect::>().len(); + assert_eq!(used, if n % 2 == 1 { 3 } else { 2 }, "{n} tools: two tints, three when odd"); + } + assert_eq!((0..5).map(|k| tint(5, k)).collect::>(), [0, 1, 0, 1, 2]); + assert_eq!((0..3).map(|k| tint(3, k)).collect::>(), [0, 1, 2]); + assert_eq!(tint(1, 0), 0); + } + + #[test] + fn the_three_tints_are_three_different_colours() { + for t in [Tokens::dark(), Tokens::light()] { + let p = palette(&t); + assert!(p[0] != p[1] && p[1] != p[2] && p[0] != p[2], "{p:?}"); + } + } + + #[test] + fn touching_a_zone_takes_it_as_the_pointer_leaves_the_hub() { + let c = pos2(500.0, 500.0); + assert_eq!(entered(c, c, c + vec2(0.0, HUB - 2.0), &on(8)), None, "still in the hub"); + assert_eq!(entered(c, c, c + vec2(0.0, HUB + 2.0), &on(8)), Some(4), "two points past the hub's edge"); + assert_eq!(entered(c, c, c + vec2(HUB + 2.0, 0.0), &on(5)), Some(1)); + } + + #[test] + fn a_fast_stroke_takes_the_zone_it_left_the_hub_into() { + let c = pos2(0.0, 0.0); + assert_eq!(entered(c, c, pos2(900.0, -300.0), &on(8)), Some(2), "the exit point decides, not the far end"); + assert_eq!(entered(c, c, pos2(300.0, -900.0), &on(8)), Some(0)); + assert_eq!(entered(c, c, pos2(-900.0, 900.0), &on(8)), Some(5)); + assert_eq!(entered(c, pos2(-10.0, 0.0), pos2(-600.0, 40.0), &on(8)), Some(6)); + } + + #[test] + fn a_zone_that_is_off_is_passed_over() { + let c = pos2(0.0, 0.0); + let mut flags = on(8); + flags[4] = false; + assert_eq!(entered(c, c, pos2(0.0, 400.0), &flags), None, "straight down is off"); + // Sliding round the ring from the off zone into an enabled one takes the enabled one. + assert_eq!(entered(c, pos2(0.0, 180.0), pos2(-180.0, 180.0), &flags), Some(5)); + assert_eq!(entered(c, c, pos2(0.0, 400.0), &[]), None); + } + + #[test] + fn hostile_numbers_touch_nothing() { + let c = pos2(0.0, 0.0); + for p in [pos2(f32::NAN, 0.0), pos2(f32::INFINITY, 5.0), pos2(0.0, f32::NEG_INFINITY)] { + assert_eq!(entered(c, c, p, &on(8)), None); + assert_eq!(entered(c, p, c, &on(8)), None); + assert_eq!(entered(p, c, pos2(0.0, 400.0), &on(8)), None); + } + assert_eq!(entered(c, c, c, &on(8)), None, "a pointer that did not move"); + } + + #[test] + fn studios_are_read_from_the_application() { + let mut app = app(); + assert_eq!(Studio::of(&app), Studio::Part); + for (tab, studio) in [ + ("SOLID", Studio::Part), + ("SURFACE", Studio::Surface), + ("MESH", Studio::Mesh), + ("SHEET METAL", Studio::SheetMetal), + ("PLASTIC", Studio::Plastic), + ("UTILITIES", Studio::Part), + ] { + app.ui.tab = tab.into(); + assert_eq!(Studio::of(&app), studio, "{tab}"); + } + app.ui.tab = "SURFACE".into(); + app.session.execute("sketch.create", &serde_json::json!({"plane": "XY"})).expect("a sketch opens"); + assert_eq!(Studio::of(&app), Studio::Sketch, "a sketch being edited beats the tab"); + } + + #[test] + fn every_studio_ships_distinct_tools_that_exist() { + let app = app(); + let mut sets = Vec::new(); + for studio in Studio::ALL { + let ids = studio.defaults(); + let mut sorted = ids.to_vec(); + sorted.sort_unstable(); + sorted.dedup(); + assert_eq!(sorted.len(), ids.len(), "{studio:?}: no tool twice"); + for id in ids { + assert!(label_of(id).is_some() && item(&app, id).is_some(), "{studio:?}: `{id}` is not a tool"); + } + assert_eq!(items(&app, studio).len(), ids.len()); + sets.push(ids.to_vec()); + } + for (i, a) in sets.iter().enumerate() { + for b in &sets[i + 1..] { + assert_ne!(a, b, "two studios share one ring"); + } + } + let keys: std::collections::BTreeSet<_> = Studio::ALL.iter().map(|s| s.key()).collect(); + assert_eq!(keys.len(), Studio::ALL.len(), "studio keys are unique"); + } + + #[test] + fn repeat_delete_and_undo_follow_the_state_of_the_design() { + let mut app = app(); + assert!(!item(&app, "repeat").expect("a tool").enabled, "nothing to repeat yet"); + assert!(!item(&app, "delete").expect("a tool").enabled, "nothing selected"); + assert!(!item(&app, "undo").expect("a tool").enabled, "nothing to undo"); + app.session.execute("solid.box", &serde_json::json!({"length": 10, "width": 10, "height": 10})).expect("a box"); + assert!(item(&app, "undo").expect("a tool").enabled, "a command ran: undo is on"); + assert!(item(&app, "no.such.tool").is_none()); + } + + #[test] + fn a_studio_uses_its_defaults_until_the_person_changes_them() { + let mut config = Config::default(); + assert!(!config.enabled, "gestures start off"); + assert_eq!(config.tools(Studio::Part), PART.iter().map(|s| s.to_string()).collect::>()); + assert!(!config.is_custom(Studio::Part)); + config.set_tools(Studio::Part, vec!["solid.extrude".into(), "undo".into(), "solid.hole".into(), "delete".into(), "repeat".into()]); + assert_eq!(config.tools(Studio::Part).len(), 5, "five tools: five parts of the circle"); + assert_eq!(config.tools(Studio::Part)[0], "solid.extrude"); + assert!(config.is_custom(Studio::Part) && !config.is_custom(Studio::Sketch)); + assert_eq!(config.tools(Studio::Sketch).len(), 8, "other studios keep their own"); + config.reset(Studio::Part); + assert_eq!(config.tools(Studio::Part).len(), 8); + } + + #[test] + fn a_hand_edited_list_is_cleaned_before_it_is_used() { + let mut config = Config::default(); + let many: Vec = (0..40).map(|_| "undo".to_string()).chain(catalog().into_iter().map(|(id, _)| id)).collect(); + config.set_tools(Studio::Mesh, many); + let tools = config.tools(Studio::Mesh); + assert!(tools.len() <= MAX_TOOLS, "{} tools", tools.len()); + let mut sorted = tools.clone(); + sorted.sort_unstable(); + sorted.dedup(); + assert_eq!(sorted.len(), tools.len(), "no tool twice"); + config.set_tools(Studio::Mesh, vec!["nonsense".into(), "".into(), "also.not.a.tool".into()]); + assert_eq!(config.tools(Studio::Mesh), MESH.iter().map(|s| s.to_string()).collect::>(), "nothing usable: the defaults"); + config.set_tools(Studio::Mesh, vec![]); + assert_eq!(config.tools(Studio::Mesh).len(), 8); + } + + #[test] + fn settings_round_trip_and_older_preferences_load() { + let mut config = Config { enabled: true, ..Default::default() }; + config.set_tools(Studio::Sketch, vec!["sketch.line".into(), "undo".into(), "sketch.circle.center".into()]); + let json = serde_json::to_string(&config).expect("serializes"); + assert_eq!(serde_json::from_str::(&json).expect("loads"), config); + let none: Config = serde_json::from_str("{}").expect("an empty value is the default"); + assert_eq!(none, Config::default()); + assert!( + serde_json::from_str::(r#"{"enabled":true,"wheels":{"part":["undo"],"future":["x"]}}"#).is_ok(), + "unknown studios are kept, not fatal" + ); + } + + #[test] + fn the_editor_changes_how_many_tools_and_where_they_sit() { + let mut list: Vec = ["solid.extrude", "undo", "solid.hole"].iter().map(|s| s.to_string()).collect(); + assert!(apply(&mut list, Op::Down(0))); + assert_eq!(list, ["undo", "solid.extrude", "solid.hole"]); + assert!(apply(&mut list, Op::Up(2))); + assert_eq!(list, ["undo", "solid.hole", "solid.extrude"]); + assert!(!apply(&mut list, Op::Up(0)) && !apply(&mut list, Op::Down(2)), "can't move past the ends"); + assert!(apply(&mut list, Op::Add) && list.len() == 4, "a tool is added"); + assert!(!list[3].is_empty() && !list[..3].contains(&list[3]), "one the ring doesn't hold yet"); + assert!(apply(&mut list, Op::Set(0, "solid.fillet".into()))); + assert_eq!(list[0], "solid.fillet"); + assert!(!apply(&mut list, Op::Set(1, "solid.fillet".into())), "no tool twice"); + assert!(!apply(&mut list, Op::Set(1, "not.a.tool".into())), "only real tools"); + assert!(!apply(&mut list, Op::Set(9, "undo".into())), "no such place"); + assert!(apply(&mut list, Op::Remove(0)) && list.len() == 3); + while list.len() > 1 { + assert!(apply(&mut list, Op::Remove(0))); + } + assert!(!apply(&mut list, Op::Remove(0)), "a ring keeps at least one tool"); + while list.len() < MAX_TOOLS { + assert!(apply(&mut list, Op::Add)); + } + assert!(!apply(&mut list, Op::Add), "and at most {MAX_TOOLS}"); + } + + #[test] + fn the_catalog_offers_real_tools_once_each() { + let catalog = catalog(); + assert!(catalog.len() > 50); + let mut ids: Vec<&str> = catalog.iter().map(|(i, _)| i.as_str()).collect(); + ids.sort_unstable(); + let before = ids.len(); + ids.dedup(); + assert_eq!(ids.len(), before, "no tool twice"); + assert!(catalog.iter().all(|(id, label)| label_of(id).as_deref() == Some(label.as_str()))); + for studio in Studio::ALL { + for id in studio.defaults() { + assert!(catalog.iter().any(|(i, _)| i == id), "{studio:?}: `{id}` is not offered in the editor"); + } + } + } + + // ---- the gesture itself ---- + + /// A right-button drag through `show`, one pointer position per frame (the first presses). + /// The button stays down unless `release` is set. + fn drag(app: &mut SolveApp, path: &[Pos2], release: bool) { + let ctx = egui::Context::default(); + let screen = Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 1000.0)); + app.viewport.mouse = path.first().copied(); + let secondary = + |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Secondary, pressed, modifiers: egui::Modifiers::NONE }; + let frame = |app: &mut SolveApp, k: usize, events: Vec| { + let raw = egui::RawInput { time: Some(k as f64 * 0.02), screen_rect: Some(screen), events, ..Default::default() }; + let mut output = ctx.run_ui(raw, |ui| show(app, ui.ctx())); + output.textures_delta.clear(); + }; + for (k, p) in path.iter().enumerate() { + let mut events = vec![egui::Event::PointerMoved(*p)]; + if k == 0 { + events.push(secondary(*p, true)); + } + frame(app, k, events); + } + if release { + let last = path.last().copied().unwrap_or(Pos2::ZERO); + frame(app, path.len(), vec![secondary(last, false)]); + } + } + + fn gesture_app() -> SolveApp { + let mut app = app(); + app.preferences.nav = MOUSE_MODE.into(); + app.preferences.mouse_gestures.enabled = true; + app + } + + const PRESS: Pos2 = pos2(800.0, 500.0); + + #[test] + fn gestures_need_both_the_switch_and_the_solidworks_mouse_mode() { + let mut app = app(); + assert!(!active(&app), "off by default"); + app.preferences.mouse_gestures.enabled = true; + for nav in ["fusion", "inventor", "alias", "blender", "tinkercad", "openscad", "touchpad"] { + app.preferences.nav = nav.into(); + assert!(!active(&app), "{nav}: gestures only work with the SolidWorks mouse mode"); + } + app.preferences.nav = MOUSE_MODE.into(); + assert!(active(&app)); + app.preferences.mouse_gestures.enabled = false; + assert!(!active(&app)); + } + + #[test] + fn the_ring_opens_after_four_points_with_the_button_held_where_it_went_down() { + let mut app = gesture_app(); + drag(&mut app, &[PRESS], false); + assert!(!is_open(&app), "a press alone is not a gesture"); + drag(&mut app, &[PRESS, PRESS + vec2(OPEN_DRAG - 1.0, 0.0)], false); + assert!(!is_open(&app), "three points is still a click"); + let mut app = gesture_app(); + drag(&mut app, &[PRESS, PRESS + vec2(OPEN_DRAG - 1.0, 0.0), PRESS + vec2(OPEN_DRAG, 0.0)], false); + assert!(is_open(&app), "four points opens it"); + assert_eq!(app.gesture.wheel.as_ref().map(|w| w.centre), Some(PRESS), "centred where the button went down"); + assert!(app.tool.is_none() && app.dialog.is_none(), "nothing is taken inside the hub"); + } + + #[test] + fn a_plain_right_click_leaves_the_menu_to_the_viewport_and_a_gesture_does_not() { + let mut app = gesture_app(); + drag(&mut app, &[PRESS], true); + assert!(!is_open(&app) && !took_press(&app), "no move: a right-click, the usual menu opens"); + let mut app = gesture_app(); + drag(&mut app, &[PRESS, PRESS + vec2(10.0, 0.0)], true); + assert!(!is_open(&app) && took_press(&app), "a gesture's release is no click, so no menu"); + // The next press starts afresh. + drag(&mut app, &[PRESS], true); + assert!(!took_press(&app)); + } + + #[test] + fn touching_a_zone_takes_the_tool_and_puts_the_ring_away() { + let mut app = gesture_app(); + // Past the hub's edge, below: the bottom zone (Create Sketch). + drag(&mut app, &[PRESS, PRESS + vec2(0.0, 20.0), PRESS + vec2(0.0, HUB + 3.0)], false); + assert!(!is_open(&app)); + assert!(app.tool.is_some() || app.dialog.is_some(), "Create Sketch started"); + } + + #[test] + fn a_fast_flick_cannot_skip_the_tool_between_frames() { + let mut app = gesture_app(); + drag(&mut app, &[PRESS, PRESS + vec2(0.0, 12.0), PRESS + vec2(0.0, 420.0)], false); + assert!(!is_open(&app) && (app.tool.is_some() || app.dialog.is_some())); + } + + #[test] + fn a_tool_that_is_off_is_not_taken_and_the_ring_stays_up() { + let mut app = gesture_app(); + // Repeat, straight up, has nothing to repeat yet. + drag(&mut app, &[PRESS, PRESS + vec2(0.0, -20.0), PRESS + vec2(0.0, -300.0)], false); + assert!(is_open(&app) && app.tool.is_none() && app.dialog.is_none()); + } + + #[test] + fn letting_go_puts_the_ring_away() { + let mut app = gesture_app(); + drag(&mut app, &[PRESS, PRESS + vec2(0.0, 20.0)], true); + assert!(!is_open(&app)); + assert!(app.tool.is_none() && app.dialog.is_none()); + } + + #[test] + fn a_ring_of_five_takes_the_tool_in_the_direction_of_its_zone() { + let mut app = gesture_app(); + app.preferences + .mouse_gestures + .set_tools(Studio::Part, ["undo", "delete", "sketch.create", "solid.extrude", "solid.move"].map(String::from).to_vec()); + assert_eq!(items(&app, Studio::Part).len(), 5); + // 72 degrees a zone: the second (Delete) is centred at 72 degrees, to the right and up a + // little. Delete needs a selection, so it is off: nothing is taken and the ring stays. + let dir = vec2((72.0_f32).to_radians().sin(), -(72.0_f32).to_radians().cos()); + drag(&mut app, &[PRESS, PRESS + dir * 20.0, PRESS + dir * 200.0], false); + assert!(is_open(&app), "the zone's tool is off"); + // The third (Create Sketch) is centred at 144 degrees: to the right and down. + let dir = vec2((144.0_f32).to_radians().sin(), -(144.0_f32).to_radians().cos()); + let mut app = gesture_app(); + app.preferences + .mouse_gestures + .set_tools(Studio::Part, ["undo", "delete", "sketch.create", "solid.extrude", "solid.move"].map(String::from).to_vec()); + drag(&mut app, &[PRESS, PRESS + dir * 20.0, PRESS + dir * 200.0], false); + assert!(!is_open(&app) && (app.tool.is_some() || app.dialog.is_some()), "Create Sketch started"); + } + + #[test] + fn nothing_opens_while_gestures_are_off_or_the_mouse_mode_is_wrong() { + let drag_down = [PRESS, PRESS + vec2(0.0, 20.0), PRESS + vec2(0.0, 300.0)]; + let mut app = gesture_app(); + app.preferences.mouse_gestures.enabled = false; + drag(&mut app, &drag_down, false); + assert!(!is_open(&app) && app.tool.is_none() && app.dialog.is_none()); + let mut app = gesture_app(); + app.preferences.nav = "fusion".into(); + drag(&mut app, &drag_down, false); + assert!(!is_open(&app) && app.tool.is_none() && app.dialog.is_none()); + } + + #[test] + fn the_ring_opens_even_while_a_tool_is_in_progress() { + let mut app = gesture_app(); + app.start("sketch.create"); + assert!(app.tool.is_some() || app.dialog.is_some()); + drag(&mut app, &[PRESS, PRESS + vec2(OPEN_DRAG + 1.0, 0.0)], false); + assert!(is_open(&app), "a tool in the pointer doesn't keep the right button while gestures are on"); + } + + #[test] + fn the_radial_menu_is_off_only_while_gestures_are_active() { + let held = |app: &mut SolveApp| { + let ctx = egui::Context::default(); + let screen = Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 1000.0)); + app.viewport.mouse = Some(PRESS); + for k in 0..40 { + let events = if k == 0 { + vec![ + egui::Event::PointerMoved(PRESS), + egui::Event::PointerButton { + pos: PRESS, + button: egui::PointerButton::Secondary, + pressed: true, + modifiers: egui::Modifiers::NONE, + }, + ] + } else { + vec![egui::Event::PointerMoved(PRESS)] + }; + let raw = egui::RawInput { time: Some(k as f64 * 0.02), screen_rect: Some(screen), events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + crate::context_menu::show(app, ui.ctx()); + show(app, ui.ctx()); + }); + out.textures_delta.clear(); + } + }; + // Held 0.8 s with the radial menu on, the usual way opens its menu... + let mut app = app(); + app.preferences.nav = MOUSE_MODE.into(); + app.preferences.radial_context_menu = true; + held(&mut app); + assert!(app.viewport.context_menu.is_some(), "gestures off: the radial menu opens as before"); + // ...with gestures on, only the ring. + let mut app = gesture_app(); + app.preferences.radial_context_menu = true; + held(&mut app); + assert!(app.viewport.context_menu.is_none(), "gestures on: no radial menu"); + assert!(!is_open(&app), "held without moving: no ring either"); + } + + #[test] + fn each_studio_opens_its_own_ring() { + let mut app = gesture_app(); + let ids = |app: &SolveApp| items(app, Studio::of(app)).into_iter().map(|i| i.id).collect::>(); + assert!(ids(&app).contains(&"solid.extrude".to_string())); + app.ui.tab = "SHEET METAL".into(); + let sheet = ids(&app); + assert!(sheet.contains(&"sheet.flange".to_string()) && !sheet.contains(&"solid.extrude".to_string())); + app.ui.tab = "PLASTIC".into(); + assert!(ids(&app).contains(&"plastic.snap_fit".to_string())); + } + + #[test] + fn the_right_button_stops_orbiting_only_while_gestures_are_active() { + use crate::prefs::{NavButton, nav_mode}; + let none = egui::Modifiers::NONE; + let mut app = app(); + app.preferences.nav = MOUSE_MODE.into(); + assert!(nav_mode(&app, NavButton::Right, none).is_some(), "gestures off: the right button orbits as before"); + app.preferences.mouse_gestures.enabled = true; + assert_eq!(nav_mode(&app, NavButton::Right, none), None, "gestures on: it opens the ring"); + assert_eq!(nav_mode(&app, NavButton::Middle, none), nav_mode(&gesture_app_off(), NavButton::Middle, none), "the other buttons are untouched"); + app.preferences.nav = "fusion".into(); + assert_eq!( + nav_mode(&app, NavButton::Right, none), + crate::prefs::nav_preset("fusion").mode(NavButton::Right, none), + "other mouse modes keep theirs" + ); + } + + fn gesture_app_off() -> SolveApp { + let mut app = app(); + app.preferences.nav = MOUSE_MODE.into(); + app + } +} diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index af70af216..d56bdf027 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -268,6 +268,8 @@ pub struct Prefs { pub navigator_style: NavigatorStyle, /// Show the radial ring and enable hold/flick gestures for viewport context menus. pub radial_context_menu: bool, + /// Mouse gestures: a ring of tools on the right button (SolidWorks mouse mode only). + pub mouse_gestures: crate::mouse_gesture::Config, /// The wheel zooms out when turned forward. pub zoom_reverse: bool, /// What an orbit turns around. @@ -446,6 +448,7 @@ impl Default for Prefs { nav: "fusion".into(), navigator_style: NavigatorStyle::default(), radial_context_menu: false, + mouse_gestures: Default::default(), zoom_reverse: false, orbit_around: OrbitAround::default(), orbit_cursor: false, @@ -762,6 +765,7 @@ fn defaults(app: &mut SolveApp, page: usize) { p.nav = d.nav; p.navigator_style = d.navigator_style; p.radial_context_menu = d.radial_context_menu; + p.mouse_gestures = d.mouse_gestures; p.zoom_reverse = d.zoom_reverse; p.zoom_to_cursor = d.zoom_to_cursor; p.smooth_wheel_zoom = d.smooth_wheel_zoom; @@ -885,6 +889,10 @@ pub fn set_autosave(app: &mut SolveApp) { /// Which navigation dragging `button` with `mods` held does under the preset. pub fn nav_mode(app: &SolveApp, button: NavButton, mods: Modifiers) -> Option { + // With mouse gestures on, the right button opens the ring of tools instead of orbiting. + if button == NavButton::Right && crate::mouse_gesture::active(app) { + return None; + } nav_preset(&app.preferences.nav).mode(button, mods) } @@ -1326,6 +1334,7 @@ fn page(app: &mut SolveApp, ui: &mut egui::Ui, t: &Tokens) { ui.label(crate::i18n::tr_label("Context menu")); ui.checkbox(&mut app.preferences.radial_context_menu, crate::i18n::tr_label("Radial context menu")); ui.end_row(); + crate::mouse_gesture::nav_rows(app, ui, t); ui.label(crate::i18n::tr_label("View navigator")); let picker = egui::ComboBox::from_id_salt("pref_navigator_style").selected_text(crate::i18n::tr_label(app.preferences.navigator_style.label())).show_ui(ui, |ui| { diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index c23cbbb75..01cbbf47d 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -2654,7 +2654,8 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { .collect(); let _ = app.run("select.set", json!({ "items": items, "add": add })); } - if resp.secondary_clicked() && delta == egui::Vec2::ZERO { + // A right-click, unless the same press opened the mouse gestures' ring. + if resp.secondary_clicked() && delta == egui::Vec2::ZERO && !crate::mouse_gesture::took_press(app) { if app.tool.is_some() { crate::tools::finish(app); } else if app.dialog.is_none() { diff --git a/docs/book/src/guide/ui-tour.md b/docs/book/src/guide/ui-tour.md index ea8ff9c88..16c5d2808 100644 --- a/docs/book/src/guide/ui-tour.md +++ b/docs/book/src/guide/ui-tour.md @@ -32,6 +32,15 @@ in the default and Inventor presets. In every preset, Ctrl+left drag (Cmd on macOS) that starts on empty space orbits; a Ctrl+click still adds to the selection. Shift+right-drag snaps to the nearest standard or diagonal view; Shift does not request snapping when the preset already requires it to orbit. + **Mouse gestures** (Preferences › Navigation, off by default) work with the SolidWorks mouse preset + only (the wheel orbits, Ctrl + wheel pans) and take over the right button, which then no longer + orbits: hold it and move the pointer 4 pt to open a ring of tools (280 pt inside, 350 pt outside), even + while a tool is active, and touch a tool's zone to take it. A right-click that does not move still + opens the usual context menu. Each studio has its own + tools, and **Customize…** sets how many tools a studio's ring holds and in which place. Zones + alternate between two tints, three when the number of tools is odd. The optional radial context + menu is a separate setting, and gestures take the right button from it while they are on. + With **Touchpad** selected in Preferences › Navigation, hold **Shift** and move the pointer to pan, or hold **Alt** (**Option** on macOS) and move it to orbit—no mouse button is needed. Vertical two-finger scrolling zooms in this preset, regardless of the saved two-finger pan From a7bc7fe2ff6be61812213bbf295128ac6111a038 Mon Sep 17 00:00:00 2001 From: Irakli Kourtis Date: Tue, 20 Oct 2026 12:28:22 +0000 Subject: [PATCH 203/225] AGENTS.md: merge queue, no merges of main, check open work before starting (#3559) - The repository is tangency-labs/solidcraft (origin and the claim check pointed at the old one). - PRs land through the merge queue (`gh pr merge N --squash --auto`) after a maintainer adds approved-for-ci; merging your own PR straight away is gone. - A PR is rebased onto main, never merged with it. - New "Before you start": an authenticated gh, the full open PR and issue lists, and a look for the same feature or the same files before opening a second PR for one change. Claude-Session: https://claude.ai/code/session_01QWhMwdqJYQKQq8RCLSL1LT Co-authored-by: jyviko <2501648+jyviko@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- AGENTS.md | 28 +++++++++++++++++++--------- 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 6c01a3ce0..c4063d8cd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -100,12 +100,13 @@ People trust SolidCraft with their designs; a crash loses their work. **This out Keep them minimal; `cargo xtask web-offline-test` covers the service worker. - **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings, tests, assets, layers). Commit after every feature arc that builds. -- **Publishing**: `origin` is github.com/bherbruck/solidcraft. Changes land through **pull requests**: - push a branch, open a PR, and let GitHub CI run. Maintainers (and agents working for them) may - merge their own PR as soon as CI is green (`gh pr merge --squash`); a trivial fix (docs, typos) - may be merged right away. Keep each PR to one topic, bring `main` into it only - when you push a change anyway or it conflicts, and never force-push `main`. Never commit `plan/`, build dirs (`target*/`) or - generated reference data; check `git ls-files` before pushing. +- **Publishing**: the repository is github.com/tangency-labs/solidcraft. Changes land through + **pull requests** and the **merge queue**: push a branch and open a PR. The heavy CI jobs start + when a maintainer adds `approved-for-ci` after reviewing the code. Approved PRs go into the queue + with `gh pr merge N -R tangency-labs/solidcraft --squash --auto`; the queue runs the full suite + on each group before it lands on `main`. Keep each PR to one topic and one issue, and never + force-push `main`. Never commit `plan/`, build dirs (`target*/`) or generated reference data; + check `git ls-files` before pushing. - **Never break wasm**: everything below the apps must build for `wasm32-unknown-unknown` (`cargo xtask wasm`, part of `cargo xtask ci`). @@ -128,15 +129,24 @@ People trust SolidCraft with their designs; a crash loses their work. **This out an open PR only to catch up with `main` (no merge of `main`, no Update branch, no rebase for that alone): every push restarts the whole CI run, and `main`'s own run catches what lands in between, to be fixed forward. When you push a change anyway, or GitHub reports a conflict, - rebase onto the latest `main` (push your own branch with `--force-with-lease`) or merge `main` - in once, and resolve conflicts without discarding others' work; never force-push `main`. + rebase onto the latest `main` (push your own branch with `--force-with-lease`); never merge + `main` into a PR. Resolve conflicts without discarding others' work; never force-push `main`. Don't re-run CI on an unchanged commit: a real failure fails again. Re-run only a job that runner trouble cancelled, with "Re-run failed jobs". Report the PR state you checked and any conflicts resolved. If a PR remains open, keep monitoring it while the task is active and make its pending status clear at handoff; do not claim it merged without checking. +## Before you start: look at what is already open +- Work with an authenticated GitHub CLI (`gh auth status`) and `git`; the checks below need both. +- Pull the whole list, not one search: `gh pr list -R tangency-labs/solidcraft --state open --limit 500` + (drafts included) and `gh issue list -R tangency-labs/solidcraft --state open --limit 500`. Look for + work on the same issue, the same feature under another number, and PRs that change the files + you are about to change (`gh pr list ... --json number,title,files`). +- If someone already has it, comment on their PR or issue instead of opening a second one. Two + PRs for one change can't both land, and one of them is wasted work and CI. + ## Claim = a draft PR -- Before working on issue #N, check nobody has it: `gh pr list -R bherbruck/solidcraft --state open --search "#N"`. +- Before working on issue #N, check nobody has it: `gh pr list -R tangency-labs/solidcraft --state open --search "#N"`. - If none, branch from the latest `origin/main`, `git commit --allow-empty -m "claim: #N"`, push, and open a **draft** PR titled ` (#N)` right away. **The lowest-numbered open PR for an issue wins**; if yours lost, close it. Opening the PR is the claim: the bot assigns you and From 3f7959b536aacd20a36280aa47a80f56e5adbc52 Mon Sep 17 00:00:00 2001 From: Nathan Charles Date: Tue, 20 Oct 2026 12:34:23 +0000 Subject: [PATCH 204/225] Canvas and Decal: the file picker opens on PNG and JPEG images (#3266) * Canvas and Decal: the file picker opens on PNG and JPEG images canvas.insert and canvas.decal opened the general Open dialog with no file type, so it started on "Designs, CAD files and meshes" and PNG/JPEG files were greyed out. Offer the image types first, as Insert SVG/DXF do (#1801). * Canvas and Decal: rustfmt the file-picker test --- crates/ui-egui/src/file_picker.rs | 8 +++++++- crates/ui-egui/src/sketch_tools.rs | 3 ++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/file_picker.rs b/crates/ui-egui/src/file_picker.rs index afd683ddd..56d0dcf59 100644 --- a/crates/ui-egui/src/file_picker.rs +++ b/crates/ui-egui/src/file_picker.rs @@ -310,7 +310,13 @@ mod tests { Box::pin(std::future::ready(None)) })); h.app.run("sketch.create", json!({"plane": "XY"})).unwrap(); - for (command, want) in [("sketch.insert_svg", vec!["svg"]), ("sketch.insert_dxf", vec!["dxf"]), ("file.insert_step", vec![])] { + for (command, want) in [ + ("sketch.insert_svg", vec!["svg"]), + ("sketch.insert_dxf", vec!["dxf"]), + ("file.insert_step", vec![]), + ("canvas.insert", vec!["png", "jpg", "jpeg"]), + ("canvas.decal", vec!["png", "jpg", "jpeg"]), + ] { h.app.start(command); tick(&mut h.app, &h.ctx); assert_eq!(asked.borrow().last().cloned(), Some(want.iter().map(|e| e.to_string()).collect::>()), "{command}"); diff --git a/crates/ui-egui/src/sketch_tools.rs b/crates/ui-egui/src/sketch_tools.rs index 1e9b987df..bedd33883 100644 --- a/crates/ui-egui/src/sketch_tools.rs +++ b/crates/ui-egui/src/sketch_tools.rs @@ -276,7 +276,8 @@ pub fn start_hook(app: &mut SolveApp, id: &str) -> bool { return true; } let command = id.to_string(); - app.pick_open(move |app, path| { + // Offer the image types first: the default Open filter lists only designs and meshes. + app.pick_open_for(&["png", "jpg", "jpeg"], move |app, path| { if let Some(path) = path { IMAGE.with(|i| *i.borrow_mut() = Some(path)); app.last_command = solidcraft_engine::find_command(&command).map(|spec| (spec.id.into(), spec.label.into())); From 689038d187a9cfadd193968a7e18085222d152f8 Mon Sep 17 00:00:00 2001 From: rlartot <94693724+rlartot@users.noreply.github.com> Date: Tue, 20 Oct 2026 12:35:30 +0000 Subject: [PATCH 205/225] Delete Face asks for its faces instead of failing (#2167) (#3296) * claim: #2167 Co-Authored-By: Claude Sonnet 5.5 * Delete Face asks for its faces instead of failing (#2167) Clicking Delete Face in the toolbar ran face.delete with no parameters and reported "`faces` must be a list of points or face names", ignoring any preselected face. It now opens a dialog with a Faces input, like Shell, Draft and Offset Face, takes the preselected faces, and reopens from the timeline. Co-Authored-By: Claude Sonnet 5.5 --------- Co-authored-by: Claude Sonnet 5.5 --- crates/ui-egui/src/dialogs.rs | 22 ++++++++++++++++++- crates/ui-egui/src/preselect_tests.rs | 31 +++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index a815204a5..89a5b5e1f 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -232,6 +232,8 @@ pub enum Kind { }, /// Move planar faces onto a target plane or face. ReplaceFace, + /// Take faces off a body; the neighbouring faces close the gap (#2167). + DeleteFaces, /// Boundary Fill: the cells the tool bodies make (a point inside, a description, filled /// or not), found again when the tools change. BoundaryFill { @@ -576,6 +578,7 @@ impl Dialog { Kind::ReplaceFace, vec![SelInput::new("Faces", PLANAR_FACES, true), SelInput::new("Target", PLANES | PLANAR_FACES, false)], ), + "face.delete" => Dialog::new(Kind::DeleteFaces, vec![SelInput::new("Faces", FACES, true)]), "solid.boundary_fill" => { Dialog::new(Kind::BoundaryFill { operation: 0, cells: Vec::new(), of: Vec::new() }, vec![SelInput::new("Tools", BODIES, true)]) } @@ -878,6 +881,7 @@ impl Dialog { | Kind::Rib { .. } | Kind::Emboss { .. } | Kind::ReplaceFace + | Kind::DeleteFaces | Kind::Align { .. } | Kind::Remove | Kind::PathPattern { .. } @@ -1505,6 +1509,7 @@ fn title(k: &Kind) -> &'static str { Kind::Rib { web: true, .. } => "WEB", Kind::Emboss { .. } => "EMBOSS", Kind::ReplaceFace => "REPLACE FACE", + Kind::DeleteFaces => "DELETE FACE", Kind::Align { .. } => "ALIGN", Kind::BoundaryFill { .. } => "BOUNDARY FILL", Kind::Remove => "REMOVE", @@ -2835,7 +2840,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { enter |= field(ui, t); ui.end_row(); } - Kind::Split | Kind::ReplaceFace | Kind::Remove | Kind::Midplane | Kind::Construct { t: None, .. } => {} + Kind::Split | Kind::ReplaceFace | Kind::DeleteFaces | Kind::Remove | Kind::Midplane | Kind::Construct { t: None, .. } => {} Kind::MeshConvert { tolerance } => { row_label(ui, "Tolerance"); enter |= field(ui, tolerance); @@ -4247,6 +4252,10 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result, S } ("solid.replace_face", p) } + Kind::DeleteFaces => { + need(0, "faces")?; + ("face.delete", json!({"faces": face_points(0)})) + } Kind::Align { flip } => { need(0, "bodies")?; need(1, "what to move from")?; @@ -5589,6 +5598,17 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option { + let mut d = start("face.delete")?; + if let Some(inp) = d.inputs.first_mut() { + inp.items = faces.iter().filter_map(|p| face_sel(s, p.0)).collect(); + } + if let Some(b) = body { + d.extra.insert("body".into(), json!(b)); + } + d.extra.insert("heal".into(), json!(heal)); + d + } FeatureKind::Remove { bodies } => { let mut d = start("solid.remove")?; if let Some(inp) = d.inputs.first_mut() { diff --git a/crates/ui-egui/src/preselect_tests.rs b/crates/ui-egui/src/preselect_tests.rs index c1d0a8af8..5f6ef6172 100644 --- a/crates/ui-egui/src/preselect_tests.rs +++ b/crates/ui-egui/src/preselect_tests.rs @@ -1946,6 +1946,37 @@ fn every_construct_tool_opens_a_dialog_instead_of_failing() { } } +/// #2167: Delete Face asks for its faces instead of failing with "`faces` must be a list of +/// points or face names". Started with nothing selected it opens a dialog; with a face picked +/// first it takes that face, and OK takes the fillet off. +#[test] +fn delete_face_asks_for_faces_and_takes_the_preselected_one() { + let mut h = crate::scenario::Harness::new(); + h.app.run("solid.box", json!({"length":40,"width":30,"height":20,"body_name":"B"})).unwrap(); + h.app.run("solid.fillet", json!({"edges":[[40,15,20]],"radius":5})).unwrap(); + let volume = |h: &crate::scenario::Harness| h.app.session.world_state().body("B").unwrap().mesh().measure().volume; + let filleted = volume(&h); + + h.app.session.selection.clear(); + h.app.start("face.delete"); + h.frames(1); + let status = h.app.status.as_ref().map(|s| s.0.clone()).unwrap_or_default(); + assert!(!status.contains("must be a list"), "{status}"); + assert!(h.app.dialog.as_ref().is_some_and(|d| !d.inputs.is_empty()), "Delete Face opens a dialog that asks for faces"); + crate::dialogs::cancel(&mut h.app); + + // A point on the fillet's surface, 45 degrees round from its axis (35, y, 15). + let r = 5.0 * std::f64::consts::FRAC_1_SQRT_2; + let point = Vec3::new(35.0 + r, 15.0, 15.0 + r); + h.app.session.selection = vec![crate::dialogs::face_sel(&h.app.session, point).expect("the fillet face")]; + h.app.start("face.delete"); + h.frames(1); + assert_eq!(h.app.dialog.as_ref().unwrap().inputs[0].items.len(), 1, "the selected face fills the input"); + h.step(&json!({"key":"Enter"})).unwrap(); + assert!(h.app.dialog.is_none(), "{:?}", h.app.dialog.as_ref().and_then(|d| d.error.clone())); + assert!(volume(&h) > filleted + 1.0, "the rounded edge is square again"); +} + /// #2494: two planes selected first, Axis Through Two Planes takes both and makes the axis /// where they meet. #[test] From 9a0e6f8ae0c3aaa167694fde0868819e7ab4ff5b Mon Sep 17 00:00:00 2001 From: phanoob Date: Tue, 20 Oct 2026 12:36:37 +0000 Subject: [PATCH 206/225] A body dropped on a component's Bodies folder moves into that component (#3270) (#3347) * claim: #3270 Co-Authored-By: Claude Opus 5.5 * A body dropped on a component's Bodies folder moves into that component (#3270) The Bodies (and Sketches) folder row only took items of its own component, to take them out of groups. A body dragged there from another component was refused, though the folder looks like the place to drop it, so moving a body back to a parent seemed impossible. Items of the same folder from another component now move into the folder's component, as a drop on the component's own row does. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Phanoob Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/browser.rs | 12 ++++++++--- crates/ui-egui/src/occurrence_ui_tests.rs | 26 +++++++++++++++++++++++ 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/browser.rs b/crates/ui-egui/src/browser.rs index 42adc5cff..04c457275 100644 --- a/crates/ui-egui/src/browser.rs +++ b/crates/ui-egui/src/browser.rs @@ -1820,11 +1820,17 @@ fn folder_rows_at(app: &mut SolveApp, ui: &mut egui::Ui, comp: u64, path: Option if let Some(p) = r.secondary { acts.menu = Some((p, Target::Folder { component: comp, folder: fstatic.to_string(), scope: prefix.clone() })); } - // Dropping on the folder row takes items out of their groups, to the end. + // Dropping on the folder row takes items out of their groups, to the end. Bodies or sketches + // from another component's folder move into this component, as a drop on its row does + // (#3270: the Bodies folder looked like the place to drop a body, and took nothing). if let Some(resp) = &r.resp - && let Some(d) = drop_target(ui, resp, |d: &Drag| d.comp == comp && d.folder == fstatic, DropMark::Box) + && let Some(d) = drop_target(ui, resp, |d: &Drag| d.folder == fstatic && (d.comp == comp || d.folder != "construction"), DropMark::Box) { - acts.drop = Some(DropAction::Move { comp, folder: fstatic, keys: d.keys.clone(), group: None, before: None }); + acts.drop = Some(if d.comp == comp { + DropAction::Move { comp, folder: fstatic, keys: d.keys.clone(), group: None, before: None } + } else { + DropAction::Component { to: comp, folder: d.folder, keys: d.keys.clone() } + }); } if !open { return; diff --git a/crates/ui-egui/src/occurrence_ui_tests.rs b/crates/ui-egui/src/occurrence_ui_tests.rs index 0c1c698d5..18e3df738 100644 --- a/crates/ui-egui/src/occurrence_ui_tests.rs +++ b/crates/ui-egui/src/occurrence_ui_tests.rs @@ -230,3 +230,29 @@ fn occurrence_distance_editor_reads_inches_and_keeps_four_digits_in_model_space( crate::browser::revert_occurrence_dialog(&mut h.app, &movement); assert!(h.app.session.pending_moves.is_empty()); } + +/// #3270: a body dragged from a child component onto the parent's Bodies folder moves back into +/// the parent, as a drop on the parent's own row does. +#[test] +fn a_body_dropped_on_a_bodies_folder_moves_into_that_component() { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.run("solid.box", json!({"length":10,"width":10,"height":10,"body_name":"Plate"})).unwrap(); + h.app.run("solid.box", json!({"corner":[20,0,0],"length":5,"width":5,"height":5,"body_name":"Lid"})).unwrap(); + let part = h.app.run("component.create", json!({"name":"Part"})).unwrap()["component"].as_u64().unwrap(); + h.app.run("solid.box", json!({"corner":[40,0,0],"length":5,"width":5,"height":5,"body_name":"Pin"})).unwrap(); + h.app.run("component.activate", json!({"component":0})).unwrap(); + h.frames(4); + let owner = |h: &Harness, name: &str| { + let state = h.app.session.model.state(); + h.app.session.doc.model_body_component(state.body(name).unwrap()) + }; + assert_eq!(owner(&h, "Pin"), part); + let at = |h: &mut Harness, handle: &str| h.at(&json!({"handle": handle})).unwrap(); + let (plate, lid, pin) = (at(&mut h, "row:Plate"), at(&mut h, "row:Lid"), at(&mut h, "row:Pin")); + // The root's Bodies folder row sits one row above its first body. + let folder = [plate[0], plate[1] - (lid[1] - plate[1])]; + h.step(&json!({"drag": [pin, folder], "steps": 12})).unwrap(); + h.frames(3); + assert_eq!(owner(&h, "Pin"), 0, "Pin moved back into the root component"); +} From c64a611818a48817159bc7424ff6e0ca5986fbb2 Mon Sep 17 00:00:00 2001 From: rlartot <94693724+rlartot@users.noreply.github.com> Date: Tue, 20 Oct 2026 12:37:43 +0000 Subject: [PATCH 207/225] Boolean: fail an unverifiable intersection instead of keeping what it should trim (#3244) (#3344) * claim: #3244 Co-Authored-By: Claude Opus 5.5 * Fail an unverifiable intersection instead of keeping what it should trim (#3244) When every route of the general boolean fails, it falls back on the sampled answer (one body whole, or nothing) with a "not verified ... that part is ignored" warning, even when the bodies' facets cross well past their faceting error. For an intersection that keeps exactly the material it was asked to trim: teeth standing 0.27 mm out of a trimming cylinder came back untrimmed, and `solidcraft-cli run` exited 0 with a part 16.918 mm in radius. An intersection whose sampled answer is contradicted by facets crossing by more than twice the depth the warning reports (6 x the check mesh tolerance, three times the faceting error of two meshes) now fails, and the model is kept. Cuts and unions keep the fallback: shelling a body in two pieces relies on it (a cavity tool grazing the other piece), with the same depth and ignored volume as this case. Fixes #3244 Co-Authored-By: Claude Opus 5.5 * Leave an empty unverified intersection as it was (#3244) Only a doubted intersection that keeps one body whole is refused. An empty one ("the bodies are apart") stays a result reported unverified: the clearance and interference checks rely on it, and main's new a_pin_through_a_d_bore_of_its_size_still_overlaps_the_flat (#2714) expects it. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/boolean_regression_tests.rs | 28 +++++++++++++++++++ crates/kernel/src/ops.rs | 15 ++++++++++ 2 files changed, 43 insertions(+) diff --git a/crates/engine/src/boolean_regression_tests.rs b/crates/engine/src/boolean_regression_tests.rs index 1ecbe4773..8cf79c6f1 100644 --- a/crates/engine/src/boolean_regression_tests.rs +++ b/crates/engine/src/boolean_regression_tests.rs @@ -34,6 +34,34 @@ fn check_partial_face_contact_pattern() { println!("#674 volume {volume:.6} / {expected_volume:.6} mm³; area {area:.6} / {expected_area:.6} mm²; {shells} shells"); } +/// A cylinder intersected with a disc carrying a tooth whose corners stand 0.27 mm out of it +/// (radius 16.92 for 16.65): the general boolean can't intersect them, and the sampled answer +/// (the disc is inside the cylinder) used to be kept with a warning, corners and all. The +/// intersection must trim them or fail and leave the body as it was (#3244). +#[test] +fn intersection_never_keeps_material_outside_the_trimming_cylinder() { + let mut s = Session::default(); + let (a, b) = ([-0.1706475844770042, 7.63270030627277], [0.1706475844770042, 7.63270030627277]); + for (command, params) in [ + ("solid.cylinder", json!({"radius": 16.65, "height": 5, "body_name": "Base"})), + ("sketch.create", json!({"plane": {"origin": [0, 0, 0], "x_dir": [-1, 0, 0], "y_dir": [0, 0, 1]}})), + ("sketch.line", json!({"points": [a, [-3, 4.99], [3, 4.99], b]})), + ("sketch.arc.three_point", json!({"start": b, "through": [0, 7.7], "end": a})), + ("sketch.finish", json!({})), + ("solid.extrude", json!({"distance": 1.6875953835063608, "start_offset": 14.962404616493638, "operation": "join", "targets": ["Base"]})), + ] { + s.execute(command, ¶ms).unwrap(); + } + let before = volume(&s, "Base"); + let r = s.execute("solid.cylinder", &json!({"radius": 16.65, "height": 14.59, "operation": "intersect", "targets": ["Base"]})); + let state = s.model.state(); + let reach = state.body("Base").unwrap().body.tessellate(1e-3).unwrap().positions.iter().map(|p| p.x.hypot(p.y)).fold(0.0, f64::max); + match r { + Ok(_) => assert!(reach < 16.65 + 1e-2, "kept material out to radius {reach}"), + Err(e) => assert!((volume(&s, "Base") - before).abs() < 1e-9 && reach > 16.9, "{e}"), + } +} + fn replay(script: &str) -> Session { let mut s = Session::default(); let script: Value = serde_json::from_str(script).unwrap(); diff --git a/crates/kernel/src/ops.rs b/crates/kernel/src/ops.rs index 238ee378b..b591fe960 100644 --- a/crates/kernel/src/ops.rs +++ b/crates/kernel/src/ops.rs @@ -1799,6 +1799,21 @@ where if let Some(body) = fine(&mut last) { return Ok(Some(body)); } + // An intersection keeps what lies in both bodies: when the sampled answer keeps one of them + // whole and is contradicted by facets that cross well past their faceting error, keeping it + // would keep exactly what the intersection was asked to trim (#3244: teeth standing 0.27 mm + // out of a trimming cylinder came back untrimmed). It fails instead, and the model is kept. + // An empty answer stays reported as unverified: the clearance checks measure it another way. + let deep = 2.0 * 3.0 * tol_m; + if op == BoolOp::Intersect + && matches!(doubted, Some(Some(_))) + && let (Some(ma), Some(mb)) = &meshes + && ma.crosses(mb, deep) + { + return Err(KernelError::Failed(format!( + "boolean {op:?}: the bodies pass through each other by more than {deep:.3e} mm where they could not be intersected; {last}" + ))); + } match doubted { Some(r) => { let mut event = BooleanFallback::new(BooleanStrategy::UnverifiedShortcut); From b3811168fc82428b0e5a4f2862d81930af0c0da5 Mon Sep 17 00:00:00 2001 From: Igor Bronovskyi Date: Tue, 20 Oct 2026 12:38:27 +0000 Subject: [PATCH 208/225] fix(web): keep the CJK face a fallback for a non-CJK UI (#3535) BIZ UDPGothic's Cyrillic glyphs are full-width (1.0 em), so promoting the CJK font to the front of Proportional made Ukrainian text look wide with large gaps between letters, broke word wrapping, and truncated UI labels. When CJK text loaded on the web, install_cjk_font hard-coded "ja" and stayed promoted after switching to Ukrainian or English. Pass the live UI language to install_cjk_font_for so the CJK face only leads a CJK UI. Keep fetched CJK font bytes on the web shell and re-apply fonts when the language changes, and add a regression test that a non-CJK UI keeps the CJK face as the last fallback. --- apps/solidcraft-web/src/main.rs | 30 ++++++++++++++++++++++++- crates/ui-egui/src/fonts.rs | 39 +++++++++++++++++++++++++-------- 2 files changed, 59 insertions(+), 10 deletions(-) diff --git a/apps/solidcraft-web/src/main.rs b/apps/solidcraft-web/src/main.rs index b134903b7..4b4819f65 100644 --- a/apps/solidcraft-web/src/main.rs +++ b/apps/solidcraft-web/src/main.rs @@ -101,6 +101,10 @@ mod web { /// On-demand CJK font: fetched only when a CJK language is selected. font: solidcraft_ui_egui::fonts::CjkFontLoader, font_result: FontLoadResult, + /// The fetched CJK font's bytes: kept so a language change can re-order the fallbacks. + cjk_bytes: Option>, + /// The language the fonts were last set up for (a CJK UI leads with the CJK face). + font_language: String, space_mouse: SpaceMouse, } @@ -375,7 +379,10 @@ mod web { let done = self.font_result.borrow_mut().take(); if let Some(res) = done { let installed = match res { - Ok(bytes) => solidcraft_ui_egui::fonts::install_cjk_font(ctx, bytes), + Ok(bytes) => { + self.cjk_bytes = Some(bytes); + true + } Err(err) => { log::warn!("failed to fetch CJK font from {JAPANESE_FONT_PATH}: {err}"); false @@ -387,11 +394,29 @@ mod web { log::warn!("CJK font unavailable; showing English for this session"); } self.font.finished(installed, &mut self.app.preferences.language); + self.apply_fonts(ctx); ctx.request_repaint(); } if self.font.tick(&mut self.app.preferences.language) { self.fetch_font(ctx); } + // The CJK face leads only a CJK UI: its Cyrillic glyphs are full-width, so switching + // to Ukrainian (or English) must put the Latin face back in front. + if self.app.preferences.language != self.font_language { + self.apply_fonts(ctx); + } + } + + /// Set up the UI fonts for the live language, keeping the fetched CJK font as a fallback + /// (it leads only for a CJK UI, see [`solidcraft_ui_egui::fonts::install_cjk_font_for`]). + fn apply_fonts(&mut self, ctx: &egui::Context) { + match self.cjk_bytes.clone() { + Some(bytes) => { + solidcraft_ui_egui::fonts::install_cjk_font_for(ctx, bytes, &self.app.preferences.language); + } + None => solidcraft_ui_egui::fonts::setup_fonts(ctx), + } + self.font_language.clone_from(&self.app.preferences.language); } /// CJK text on screen with no CJK font yet (an English UI showing a Japanese name): @@ -549,6 +574,7 @@ mod web { app.home.show(rev); } let api = Api::install(sender, cc.egui_ctx.clone()).map_err(|e| format!("SolidCraft browser API: {e:?}"))?; + let font_language = app.preferences.language.clone(); Ok(Box::new(Shell { app, api, @@ -560,6 +586,8 @@ mod web { recents_synced: false, font: Default::default(), font_result: Rc::new(std::cell::RefCell::new(None)), + cjk_bytes: None, + font_language, space_mouse: SpaceMouse::default(), })) }), diff --git a/crates/ui-egui/src/fonts.rs b/crates/ui-egui/src/fonts.rs index da556f400..bc54ccc14 100644 --- a/crates/ui-egui/src/fonts.rs +++ b/crates/ui-egui/src/fonts.rs @@ -137,14 +137,11 @@ fn promote_font_to_front(fonts: &mut egui::FontDefinitions, name: &str) { } } -/// Install font bytes as fallback for Proportional and Monospace font families. -/// For CJK languages, promotes the font to the front of Proportional so digits and labels share one baseline. +/// Install font bytes as a fallback for the Proportional and Monospace families for `language`. +/// For a CJK language the font is promoted to the front of Proportional so digits and labels share +/// one baseline with the CJK glyphs; for any other language it stays a fallback (its Cyrillic can +/// be full-width, so it must not draw the Latin or Cyrillic UI text). /// Returns true if the font was parsed and installed successfully. -pub fn install_cjk_font(ctx: &egui::Context, bytes: Vec) -> bool { - install_cjk_font_for(ctx, bytes, "ja") -} - -/// Install font bytes for `language`. pub fn install_cjk_font_for(ctx: &egui::Context, bytes: Vec, language: &str) -> bool { match with_cjk_fallback(egui::FontDefinitions::default(), bytes) { Some(mut fonts) => { @@ -680,8 +677,8 @@ fn find_chinese_font_in(dirs: &[std::path::PathBuf]) -> Option> { #[cfg(target_arch = "wasm32")] pub fn setup_fonts_for(_ctx: &egui::Context, _language: &str, _ui_font: &str) {} -/// On web only the symbol fallback goes in at start (#2955); the Japanese font loads later -/// through [`install_cjk_font`], which keeps it. +/// On web only the symbol fallback goes in at start (#2955); the CJK font loads later through +/// [`install_cjk_font_for`], which keeps it as a fallback unless the UI is a CJK language. #[cfg(target_arch = "wasm32")] pub fn setup_fonts(ctx: &egui::Context) { ctx.set_fonts(with_symbol_fallback(egui::FontDefinitions::default())); @@ -819,6 +816,30 @@ mod tests { assert!(prop.contains(&defaults.families[&egui::FontFamily::Proportional][0]), "Latin font remains in the fallback chain"); } + /// A Ukrainian UI drew Cyrillic wide and loose: the bundled CJK face (BIZ UDPGothic) sets every + /// Cyrillic glyph in a full em, so it may only draw a non-CJK UI's text when nothing else has + /// the glyph. A CJK UI still leads with it, so its digits share the CJK baseline. + #[test] + fn a_non_cjk_ui_keeps_the_cjk_face_as_a_fallback() { + let installed = |language: &str| { + let ctx = egui::Context::default(); + assert!(install_cjk_font_for(&ctx, latin_font_bytes(), language), "{language}: the font installs"); + ctx.run_ui(egui::RawInput::default(), |_| {}).textures_delta.clear(); + ctx.fonts(|f| f.definitions().families[&egui::FontFamily::Proportional].clone()) + }; + let latin = egui::FontDefinitions::default().families[&egui::FontFamily::Proportional][0].clone(); + for language in ["uk", "en", "de"] { + let list = installed(language); + assert_eq!(list.first(), Some(&latin), "{language} keeps the Latin face first: {list:?}"); + assert_eq!(list.last().map(String::as_str), Some(SYMBOL_FALLBACK), "{language} ends with the symbol fallback: {list:?}"); + assert!(list.iter().position(|name| name == CJK_FALLBACK).is_some_and(|at| at > 0), "{language} keeps CJK behind Latin: {list:?}"); + } + for language in ["ja", "zh", "ko"] { + let list = installed(language); + assert_eq!(list.first().map(String::as_str), Some(CJK_FALLBACK), "{language} leads with the CJK face: {list:?}"); + } + } + #[test] fn hangul_font_falls_back_after_the_cjk_font() { let defaults = egui::FontDefinitions::default(); From e37a8fa6bb69bfdc5939443b0cd03b6da3778358 Mon Sep 17 00:00:00 2001 From: Lucas Montenegro Carvalhaes Date: Tue, 20 Oct 2026 12:38:48 +0000 Subject: [PATCH 209/225] Fillet: skip smooth seams in tangent chain and restore picked edges when unticked (#3370) (#3437) * claim: #3370 * fillet: stop tangent chains at smooth seams and sync chain toggle (#3370) --- crates/geom/src/mesh.rs | 33 ++++++- crates/geom/src/tests.rs | 12 +++ crates/ui-egui/src/dialogs.rs | 119 ++++++++++++++++++++------ crates/ui-egui/src/preselect_tests.rs | 48 +++++++++++ 4 files changed, 185 insertions(+), 27 deletions(-) diff --git a/crates/geom/src/mesh.rs b/crates/geom/src/mesh.rs index f6234320d..eea0cd305 100644 --- a/crates/geom/src/mesh.rs +++ b/crates/geom/src/mesh.rs @@ -448,6 +448,34 @@ impl Mesh { rim.sort_unstable(); rim } + /// Whether the two faces at edge `i` meet tangentially there (a smooth seam, with no corner). + fn smooth_seam(&self, i: usize, cos: f64) -> bool { + if self.sharp_edges.get(i).copied().unwrap_or(false) { + return false; + } + if self.smooth_edges.get(i).copied().unwrap_or(false) { + return true; + } + let Some([a, b]) = self.edge_faces.get(i).map(Vec::as_slice) else { return false }; + if a == b { + return false; + } + let Some(p) = self.edges.get(i) else { return false }; + let (Some(&first), Some(&mid)) = (p.first(), p.get(p.len() / 2)) else { return false }; + let normal_near = |f: u32, q: Vec3| -> Option { + self.triangles + .iter() + .zip(&self.tri_face) + .filter(|(_, tf)| **tf == f) + .flat_map(|(t, _)| t.iter().copied()) + .filter_map(|v| Some((self.positions.get(v as usize)?.dist(q), *self.normals.get(v as usize)?))) + .min_by(|x, y| x.0.total_cmp(&y.0)) + .and_then(|(_, n)| n.normalized()) + }; + let both = [first, mid]; + let sample = if p.len() == 2 { &both[..] } else { std::slice::from_ref(&mid) }; + sample.iter().all(|&q| matches!((normal_near(*a, q), normal_near(*b, q)), (Some(na), Some(nb)) if na.dot(nb) > cos)) + } /// The edges reached from `e` through vertices where the next edge continues smoothly /// (angle between the end tangents below `max_angle`), including `e` itself. pub fn tangent_chain(&self, e: usize, max_angle: f64) -> Vec { @@ -473,11 +501,14 @@ impl Mesh { let tol = size * 1e-7; let cos = max_angle.cos(); let mut chain = vec![e]; + if self.smooth_seam(e, cos) { + return chain; + } let mut todo = vec![e]; while let Some(cur) = todo.pop() { let Some(ce) = ends(cur) else { continue }; for (i, _) in self.edges.iter().enumerate() { - if chain.contains(&i) || !self.edge_pickable(i) { + if chain.contains(&i) || !self.edge_pickable(i) || self.smooth_seam(i, cos) { continue; } let Some(ne) = ends(i) else { continue }; diff --git a/crates/geom/src/tests.rs b/crates/geom/src/tests.rs index a2b494349..a50384a86 100644 --- a/crates/geom/src/tests.rs +++ b/crates/geom/src/tests.rs @@ -150,6 +150,18 @@ fn tangent_chains_follow_smooth_edges() { assert_eq!(c, vec![0, 1]); assert_eq!(m.tangent_chain(2, 5f64.to_radians()), vec![2]); assert_eq!(m.face_edges(1), vec![1, 2]); + // A smooth seam where two faces share the same normal along the edge is not a corner to round, + // so tangent chaining stops at it. + let seam = Mesh { + positions: vec![Vec3::new(0.0, 0.0, 0.0), Vec3::new(10.0, 0.0, 0.0), Vec3::new(20.0, 0.0, 0.0), Vec3::new(15.0, 5.0, 0.0)], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 3], [1, 2, 3], [1, 2, 3]], + tri_face: vec![0, 1, 2], + edges: vec![vec![Vec3::new(0.0, 0.0, 0.0), Vec3::new(10.0, 0.0, 0.0)], vec![Vec3::new(10.0, 0.0, 0.0), Vec3::new(20.0, 0.0, 0.0)]], + edge_faces: vec![vec![0], vec![1, 2]], + ..Default::default() + }; + assert_eq!(seam.tangent_chain(0, 5f64.to_radians()), vec![0]); } #[test] diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 89a5b5e1f..aeaa2115d 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -408,6 +408,10 @@ pub struct Dialog { pub refused: Option, /// Create Sketch opened by a sketch tool's shortcut: that tool starts once the sketch is open. pub then_start: Option<&'static str>, + /// Edges picked by hand in a Fillet or Chamfer dialog, before tangent-chain expansion. + pub(crate) picked_edges: Vec, + /// Whether `inputs[0]` currently includes the tangent chains of `picked_edges`. + pub(crate) chain_applied: bool, } /// OK computing off the window thread: the dialog's commands evaluated on a scratch copy of the @@ -507,6 +511,7 @@ impl Dialog { } pub(crate) fn new(kind: Kind, inputs: Vec) -> Dialog { + let chain_applied = matches!(kind, Kind::Fillet { chain: true, .. }); Dialog { kind, inputs, @@ -519,6 +524,8 @@ impl Dialog { extra: serde_json::Map::new(), refused: None, then_start: None, + picked_edges: Vec::new(), + chain_applied, } } @@ -766,20 +773,16 @@ impl Dialog { fits(i.accept, sel) && (i.multi || i.items.is_empty()) && (planar_ok || i.accept & FACES != 0 || !matches!(sel, Sel::Face { .. })) }; if let Some(inp) = d.inputs.iter_mut().find(|i| takes(i)) { + if matches!(d.kind, Kind::Fillet { .. }) { + for x in crate::viewport::grouped_selection(s, sel) { + if !d.picked_edges.iter().any(|y| selection::same_item(y, &x)) { + d.picked_edges.push(x); + } + } + } // Fillets and chamfers take an edge with its tangent chain, as a pick does. let picked = match (&d.kind, sel) { - (Kind::Fillet { chain: true, .. }, Sel::Edge { body, index, .. }) => s - .model - .state() - .body(body) - .map(|b| { - let m = b.mesh(); - m.tangent_chain(*index, 2f64.to_radians()) - .into_iter() - .filter_map(|i| m.edges.get(i).map(|e| Sel::Edge { body: body.clone(), index: i, point: polyline_mid(e) })) - .collect::>() - }) - .unwrap_or_else(|| vec![sel.clone()]), + (Kind::Fillet { chain, .. }, _) => fillet_edges(s, sel, *chain), (Kind::Measure { .. }, _) => vec![crate::viewport::measurement_selection(s, sel)], _ if inp.multi => crate::viewport::grouped_selection(s, sel), _ => vec![sel.clone()], @@ -1045,20 +1048,10 @@ impl Dialog { let measure = matches!(self.kind, Kind::Measure { .. }); let sel = if measure { crate::viewport::measurement_selection(s, &sel) } else { sel }; let chain = matches!(self.kind, Kind::Fillet { chain: true, .. }); - let mut picked = + let single = if !measure && self.active_input().is_some_and(|i| i.multi) { crate::viewport::picked_selection(s, &sel) } else { vec![sel.clone()] }; // Tangent chain: an edge brings the edges that continue it smoothly. - if chain - && let Sel::Edge { body, index, .. } = &sel - && let Some(b) = s.world_state().body(body) - { - let m = b.mesh(); - picked = m - .tangent_chain(*index, 2f64.to_radians()) - .into_iter() - .filter_map(|i| m.edges.get(i).map(|e| Sel::Edge { body: body.clone(), index: i, point: polyline_mid(e) })) - .collect(); - } + let picked = if chain { fillet_edges(s, &sel, true) } else { single.clone() }; // Extrude and revolve take profiles of one sketch. if let Sel::Profile { sketch, .. } = &sel && !matches!(self.kind, Kind::Loft { .. }) @@ -1066,7 +1059,20 @@ impl Dialog { { inp.items.retain(|x| !matches!(x, Sel::Profile { sketch: s2, .. } if s2 != sketch)); } + let is_fillet = matches!(self.kind, Kind::Fillet { .. }) && self.active == 0; let Some(inp) = self.inputs.get_mut(self.active) else { return }; + if is_fillet { + self.chain_applied = chain; + if picked.iter().all(|p| inp.items.iter().any(|x| selection::same_item(x, p))) { + self.picked_edges.retain(|x| !picked.iter().any(|p| selection::same_item(x, p))); + } else { + for p in single { + if !self.picked_edges.iter().any(|x| selection::same_item(x, &p)) { + self.picked_edges.push(p); + } + } + } + } inp.toggle(picked); self.focus = true; // A measurement is between two items: a third pick starts over from the last one. @@ -1091,6 +1097,11 @@ impl Dialog { self.profile_selection_changed = true; } let measure = matches!(self.kind, Kind::Measure { .. }); + let is_fillet = matches!(self.kind, Kind::Fillet { .. }) && self.active == 0; + let chain = matches!(self.kind, Kind::Fillet { chain: true, .. }); + if is_fillet && !add { + self.picked_edges.clear(); + } let Some(inp) = self.inputs.get_mut(self.active) else { return }; if !add { inp.items.clear(); @@ -1105,12 +1116,62 @@ impl Dialog { inp.items.push(x); break; } - if !inp.items.iter().any(|y| selection::same_item(y, &x)) { + if is_fillet { + if !self.picked_edges.iter().any(|y| selection::same_item(y, &x)) { + self.picked_edges.push(x.clone()); + } + for y in fillet_edges(s, &x, chain) { + if !inp.items.iter().any(|z| selection::same_item(z, &y)) { + inp.items.push(y); + } + } + } else if !inp.items.iter().any(|y| selection::same_item(y, &x)) { inp.items.push(x); } } self.sync_thread(s); } + + /// Rebuild a Fillet or Chamfer dialog's edge input from the edges that were picked when + /// Tangent Chain is ticked or unticked. + pub fn sync_fillet_chain(&mut self, s: &Session) { + let Kind::Fillet { chain, .. } = &self.kind else { return }; + if *chain == self.chain_applied { + return; + } + self.chain_applied = *chain; + let Some(inp) = self.inputs.first_mut() else { return }; + let mut items = Vec::new(); + for pick in &self.picked_edges { + for x in fillet_edges(s, pick, *chain) { + if !items.iter().any(|y| selection::same_item(y, &x)) { + items.push(x); + } + } + } + inp.items = items; + self.error = None; + } +} + +/// The edges a Fillet or Chamfer pick stands for: its tangent chain when `chain` is on, else +/// the picked edge (both halves of a split circular rim). +fn fillet_edges(s: &Session, sel: &Sel, chain: bool) -> Vec { + let mut picked = crate::viewport::picked_selection(s, sel); + if chain + && let Sel::Edge { body, index, .. } = sel + && let Some(b) = s.world_state().body(body) + { + let m = b.mesh(); + for i in m.tangent_chain(*index, 2f64.to_radians()) { + if !picked.iter().any(|x| matches!(x, Sel::Edge { index: j, .. } if *j == i)) + && let Some(e) = m.edges.get(i) + { + picked.push(Sel::Edge { body: body.clone(), index: i, point: polyline_mid(e) }); + } + } + } + picked } /// Profiles of the sketch a feature would use, when there is just one: the active sketch's, else @@ -1864,6 +1925,7 @@ fn input_rows_range(d: &mut Dialog, ui: &mut egui::Ui, s: &Session, range: std:: inp.items.clear(); if i == 0 { d.profile_selection_changed = true; + d.picked_edges.clear(); } d.active = i; } @@ -2432,6 +2494,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { ui.label(tr("dialog.selection_guidance")); ui.end_row(); } + d.sync_fillet_chain(&app.session); input_rows(&mut d, ui, &app.session); match &mut d.kind { Kind::Sketch => { @@ -2787,7 +2850,8 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { d.extra.insert("radii".into(), json!(radii)); } row_label(ui, "Tangent Chain"); - ui.checkbox(chain, ""); + let r = ui.checkbox(chain, ""); + publish_row(&r); ui.end_row(); } Kind::Shell { thickness } => { @@ -3171,6 +3235,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { } } } + d.sync_fillet_chain(&app.session); error_rows(app, ctx, &mut d, ui, false); }); }); @@ -5103,7 +5168,9 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option { diff --git a/crates/ui-egui/src/preselect_tests.rs b/crates/ui-egui/src/preselect_tests.rs index 5f6ef6172..9afc5cf45 100644 --- a/crates/ui-egui/src/preselect_tests.rs +++ b/crates/ui-egui/src/preselect_tests.rs @@ -660,6 +660,54 @@ fn edges_then_fillet_takes_them_with_chains() { assert_eq!(d.inputs[0].items.len(), 2, "box edges are not tangent to others"); let cmds = apply_commands(&app, &d).unwrap(); assert_eq!(cmds[0].1["edges"].as_array().unwrap().len(), 2); + + // #3370: on a bar with rounded ends and a slot whose wall lies on the seam between the flat + // top and the rounded end, picking the slot's sharp top edge must not chain the two smooth + // seams that continue it in a straight line. + let mut h = crate::scenario::Harness::new(); + for (cmd, p) in [ + ("sketch.create", json!({"plane": "YZ", "name": "Stadium"})), + ("sketch.line", json!({"points": [[0, -9.5], [25, -9.5]]})), + ("sketch.arc.center_point", json!({"center": [25, 0], "start": [25, -9.5], "end": [25, 9.5]})), + ("sketch.line", json!({"points": [[25, 9.5], [0, 9.5]]})), + ("sketch.arc.center_point", json!({"center": [0, 0], "start": [0, 9.5], "end": [0, -9.5]})), + ("sketch.finish", json!({})), + ("solid.extrude", json!({"sketch": "Stadium", "distance": 14})), + ("solid.box", json!({"corner": [3.5, -12, -10], "length": 6, "width": 12, "height": 20, "operation": "cut"})), + ] { + h.app.run(cmd, p).unwrap(); + } + let slot_top = crate::viewport::grouped_selection(&h.app.session, &edge(&h.app, Vec3::new(6.5, 0.0, 9.5))); + h.app.session.selection = slot_top.clone(); + h.app.start("solid.fillet"); + assert_eq!(h.app.dialog.as_ref().unwrap().inputs[0].items, slot_top, "smooth stadium seams are not chained onto a sharp slot edge"); + + // On a rounded slot extrusion, picking one straight top edge chains the 4 tangent top edges; + // unticking Tangent Chain leaves only the picked edge, and ticking it again re-chains all 4. + let mut h = crate::scenario::Harness::new(); + for (cmd, p) in [ + ("sketch.create", json!({"plane":"XY"})), + ("sketch.slot.center_to_center", json!({"p0":[-20,0],"p1":[20,0],"width":20})), + ("sketch.finish", json!({})), + ("solid.extrude", json!({"distance":10})), + ] { + h.app.run(cmd, p).unwrap(); + } + let top_line = crate::viewport::grouped_selection(&h.app.session, &edge(&h.app, Vec3::new(0.0, 10.0, 10.0))); + h.app.session.selection = top_line.clone(); + h.app.start("solid.fillet"); + h.frames(2); + assert_eq!(h.app.dialog.as_ref().unwrap().inputs[0].items.len(), 4); + h.step(&json!({"click":{"handle":"dialog:Tangent Chain"}})).unwrap(); + assert_eq!(h.app.dialog.as_ref().unwrap().inputs[0].items, top_line); + h.step(&json!({"click":{"handle":"dialog:Tangent Chain"}})).unwrap(); + assert_eq!(h.app.dialog.as_ref().unwrap().inputs[0].items.len(), 4); + // Picking while Tangent Chain is off adds only that edge; unpicking with Tangent Chain on removes its chain. + h.step(&json!({"click":{"handle":"dialog:Tangent Chain"}})).unwrap(); + assert_eq!(h.app.dialog.as_ref().unwrap().inputs[0].items, top_line); + h.step(&json!({"click":{"handle":"dialog:Tangent Chain"}})).unwrap(); + h.app.dialog.as_mut().unwrap().pick(&h.app.session, top_line[0].clone()); + assert!(h.app.dialog.as_ref().unwrap().inputs[0].items.is_empty()); } #[test] From 2061ad1694fb6a22a9adf23ab026c3c5e878d156 Mon Sep 17 00:00:00 2001 From: shop-3d Date: Tue, 20 Oct 2026 12:39:11 +0000 Subject: [PATCH 210/225] i18n: add missing Danish translations (#3028) * i18n: add Danish (da) UI translation * i18n: refine Danish part properties wording * i18n: sort Danish catalog in canonical key order --- assets/locales/da.json | 81 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) diff --git a/assets/locales/da.json b/assets/locales/da.json index 8f19165f3..5ffc6bb2f 100644 --- a/assets/locales/da.json +++ b/assets/locales/da.json @@ -31,6 +31,7 @@ "Arc length": "Buelængde", "Area": "Areal", "Attachment": "Tilknytning", + "BLEND SURFACE": "OVERGANGSFLADE", "BOUNDARY SURFACE": "AFGRÆNSET OVERFLADE", "BROWSER": "MODELTRÆ", "Bend Line Position": "Bukkelinjens placering", @@ -79,6 +80,7 @@ "Current orthographic view (1:1 mm)": "Aktuel visning uden perspektiv (1:1 mm)", "Current perspective view": "Aktuel perspektivvisning", "Curvature (G2)": "Krumningskontinuitet (G2)", + "Curvature change (G3)": "Ændring i krumning (G3)", "Customize Toolbar": "Tilpas værktøjslinje", "Delete all": "Slet alle", "Delete rule": "Slet regel", @@ -100,6 +102,8 @@ "Edit Profile Sketch": "Redigér profilskitse", "Enable rule": "Aktivér regel", "Enabled": "Aktiveret", + "End bulge": "Udbuling ved slutningen", + "End continuity": "Overgang ved slutningen", "Explode": "Adskil", "Explode Text": "Opløs tekst", "Export Animation…": "Eksportér animation…", @@ -107,6 +111,7 @@ "Export Current View as DXF…": "Eksportér aktuel visning som DXF…", "Export DXF…": "Eksportér DXF…", "Export hidden edges as dashed lines": "Eksportér skjulte kanter som stiplede linjer", + "Extend to meet": "Forlæng, til de mødes", "Extents": "Udstrækning", "Face": "Flade", "Face attachment lost": "Forbindelsen til fladen er mistet", @@ -121,6 +126,7 @@ "Follow camera (Look At sketches)": "Følg kamera (Se på skitser)", "Follow the camera (Look At sketches)": "Følg kameraet (Se på skitser)", "Font": "Skrifttype", + "From edges": "Fra kanter", "Full Length": "Fuld længde", "Grid": "Gitter", "Height": "Højde", @@ -135,7 +141,9 @@ "Interferes": "Overlapper", "Issue title": "Titel på issue", "Joint Origin1": "Lednulpunkt1", + "Keep (points on it)": "Behold (punkter på fladen)", "Keep Tools": "Behold værktøjsemner", + "Keep of the other surface": "Behold fra den anden overflade", "Later": "Senere", "Leave it": "Lad det være", "Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "Ældre fladetilknytning. Ny tilknytning til en certificeret flade giver en præcis tilknytning.", @@ -173,6 +181,7 @@ "Open GitHub draft": "Åbn GitHub-kladde", "Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "Parametrisk 3D-CAD i Rust med åben kildekode. Licenseret under MIT OR Apache-2.0.", "Other side": "Anden side", + "Other surface (mutual trim)": "Anden overflade (trim begge)", "Outside": "Udvendigt", "Overall length": "Samlet længde", "Parameter values": "Parameterværdier", @@ -258,12 +267,18 @@ "Stand it up": "Stil op", "Stand it up: a quarter turn about X, as one Move feature you can undo.": "Stil op: En kvart omdrejning om X som én flyttefeature, der kan fortrydes.", "Stand this part up?": "Stil dette emne op?", + "Start bulge": "Udbuling ved starten", + "Start continuity": "Overgang ved starten", "Step": "Trin", "Steps": "Trin", + "Stitch the kept pieces": "Sammenføj de bevarede dele", + "Stitch to both bodies": "Sammenføj med begge emner", "Study": "Undersøgelse", "Style": "Stil", "Suppressed": "Undertrykt", + "Surface": "Overflade", "Swap Ends": "Ombyt ender", + "TRIM": "TRIM", "Tangent (G1)": "Tangentkontinuitet (G1)", "Tangent Chain": "Tangentkæde", "Tear": "Rivning", @@ -279,8 +294,10 @@ "This child is shared. Position changes apply to every copy of its parent.": "Dette underobjekt er delt. Positionsændringer gælder for alle kopier af dets overordnede objekt.", "This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "Denne flade kan ikke give en varig tilknytning. Vælg en anden flade, eller vælg udtrykkeligt et fast plan.", "To Offset": "Til forskydning", + "To edges": "Til kanter", "Tolerance": "Tolerance", "Too close": "For tæt på", + "Trimming tool (plane, face or curves)": "Trim med plan, flade eller kurver", "Turn off section analysis before exporting the view.": "Slå snitanalyse fra, før visningen eksporteres.", "Type": "Type", "UNTRIM": "FJERN BESKÆRING", @@ -325,6 +342,7 @@ "cmd.appearance_assign": "Udseende", "cmd.appearance_library": "Udseendebibliotek", "cmd.appearance_list": "Vis udseender", + "cmd.assembly_bom": "Stykliste", "cmd.body_rename": "Omdøb emne", "cmd.browser_group": "Ny gruppe", "cmd.browser_move": "Flyt elementer i modeltræ", @@ -346,10 +364,13 @@ "cmd.component_insert_design": "Indsæt design", "cmd.component_links": "Vis forbindelser", "cmd.component_list": "Vis komponenter", + "cmd.component_metadata": "Egenskaber for delen", + "cmd.component_metadata_set": "Redigér delens egenskaber", "cmd.component_move_bodies": "Flyt emner til komponent", "cmd.component_move_sketches": "Flyt skitser til komponent", "cmd.component_paste_new": "Indsæt som ny", "cmd.component_properties": "Komponentens fysiske egenskaber", + "cmd.component_relink": "Skift kilde", "cmd.component_rename": "Omdøb komponent", "cmd.component_revert_position": "Tilbagefør position", "cmd.component_unlock": "Lås indhold op", @@ -401,6 +422,7 @@ "cmd.edit_checkpoint": "Kontrolpunkt", "cmd.edit_restore_checkpoint": "Gendan kontrolpunkt", "cmd.engine_commands": "Vis kommandoer", + "cmd.engine_describe": "Beskriv kommando", "cmd.explode_create": "Eksploderet visning", "cmd.explode_delete": "Slet eksploderet visning", "cmd.explode_list": "Vis eksploderede visninger", @@ -442,6 +464,7 @@ "cmd.joint_rigid_group": "Stiv gruppe", "cmd.joint_screw": "Skrue", "cmd.joint_solve": "Beregn led", + "cmd.joint_sweep": "Gennemløb leddets bevægelse", "cmd.library_apply": "Brug element fra lokalt bibliotek", "cmd.library_export": "Eksportér designbibliotek", "cmd.library_inspect": "Undersøg lokalt bibliotek", @@ -718,6 +741,15 @@ "joint.from_bodies_hint": "Hvert valgt emne flyttes til sin egen nye komponent og bliver på sin plads.", "joint.one_body": "Begge valg er på {body}. Vælg det andet på et andet emne.", "joint.one_component": "Disse emner tilhører samme komponent: {bodies}. Et led bevæger én komponent i forhold til en anden, så hvert emne skal have sin egen komponent.", + "messages.ago_h": "For {n} timer siden", + "messages.ago_min": "For {n} min. siden", + "messages.ago_s": "For {n} sek. siden", + "messages.chip_hint": "Klik for at se alle beskeder fra denne session", + "messages.clear": "Ryd", + "messages.copy_all": "Kopiér alle", + "messages.menu": "Beskeder…", + "messages.none": "Ingen beskeder endnu.", + "messages.title": "Beskeder", "motion.checked_to": "Kun kontrolleret til trin {step}: Kontrollen nåede sin beregningsgrænse", "motion.collision": "{a} · {b}: trin {steps}", "motion.duration_hint": "sekunder (tomt: pr. trin)", @@ -1053,6 +1085,7 @@ "ui.autosave_every": "Gem automatisk hver", "ui.axes": "Akser", "ui.axis": "Akse", + "ui.back": "Tilbage", "ui.base_point": "Basispunkt", "ui.blocked": "Blokeret", "ui.bodies": "Emner", @@ -1306,6 +1339,8 @@ "ui.loft": "Loft", "ui.look_at": "Se på", "ui.look_at_anim_desc": "Aksevisning, Se på, Hjem og Tilpas", + "ui.manipulator_free_alt": "Brug også Alt/Option til at trække frit", + "ui.manipulator_free_alt_tip": "Slået til: Hold Alt/Option eller Ctrl/Cmd nede, mens du trækker i pilene ved ekstrudering eller flytning, for at undgå faste værditrin. Slået fra: Kun Ctrl/Cmd.", "ui.manufacture": "Fremstilling", "ui.material_review.axes": "Materialets lokale akser; ingen orientering af emnet er tildelt.", "ui.material_review.claims": "Kilder og licenser er ubekræftede angivelser. Manglende værdier forbliver ukendte.", @@ -1345,6 +1380,7 @@ "ui.newSketchGroup": "Ny skitsegruppe", "ui.new_body": "Nyt emne", "ui.new_design": "Nyt design", + "ui.no_geometry_yet": "Der er ikke tegnet noget endnu", "ui.no_slicer_found": "Ingen slicer fundet", "ui.normal": "Normal", "ui.normalConstruction": "Normal / konstruktionsgeometri", @@ -1372,6 +1408,7 @@ "ui.pan_zoom_orbit": "Panorér, zoom, rotér visning", "ui.parallel": "Parallel", "ui.parameters": "Parametre", + "ui.part_size_shared": "Genopbygger delen og erstatter alle tilføjede features. Alle forekomster af komponenten opdateres.", "ui.paste": "Indsæt", "ui.path": "Bane", "ui.pattern_on_path": "Mønster langs bane", @@ -1383,6 +1420,12 @@ "ui.placement": "Placering", "ui.plane": "Plan", "ui.plane_at_angle": "Plan i vinkel", + "ui.plugins": "Plugins", + "ui.plugins_desktop": "Plugins er tilgængelige i desktopappen.", + "ui.plugins_empty": "Ingen plugins installeret.", + "ui.plugins_note": "Hvert plugin ligger i sin egen mappe under {path} og indeholder en plugin.json-fil. SolidCraft læser filen uden at køre kode fra mappen. Et plugin forbliver installeret, når du slår det fra.", + "ui.plugins_skipped": "Kunne ikke læse {count} mapper.", + "ui.plugins_version": "{version}", "ui.point": "Punkt", "ui.point_under_the_cursor": "Punkt under markøren", "ui.points": "Punkter", @@ -1408,6 +1451,11 @@ "ui.rectangle": "Rektangel", "ui.rectangular_pattern": "Rektangulært mønster", "ui.redo": "Gentag", + "ui.relink_design_changed": "Samlingen blev ændret, mens du valgte en kilde. Start Skift kilde igen.", + "ui.relink_done": "Kilden er ændret for alle forekomster.", + "ui.relink_not_linked": "Denne komponent er ikke knyttet til et kildedesign.", + "ui.relink_select_one": "Vælg først en tilknyttet komponent eller en af dens forekomster.", + "ui.relink_source_all": "Skift kilde for alle forekomster…", "ui.removeFromToolbar": "Fjern fra værktøjslinje", "ui.removeSection": "Fjern snit", "ui.render": "Rendering", @@ -1441,6 +1489,9 @@ "ui.selectTangentChain": "Vælg tangentkæde", "ui.select_other_hint": "Vælg andet: Hold venstre museknap nede uden at flytte markøren på modellen (eller højreklik › Vælg andet…) for at vise alt under markøren. Klik igen samme sted for at vælge næste objekt.", "ui.selection": "Markering", + "ui.selection_modifiers": "Taster ved markering", + "ui.selection_shift_add_only": "Shift+klik tilføjer uden at fjerne", + "ui.selection_shift_add_only_tip": "Slået til: Shift tilføjer til markeringen. Ctrl/Cmd tilføjer eller fjerner. Slået fra (standard): Både Shift og Ctrl/Cmd tilføjer eller fjerner.", "ui.send": "Send", "ui.send_to_slicer": "Send til slicer", "ui.sent_to_slicer": "Sendt til {slicer}", @@ -1465,6 +1516,7 @@ "ui.sketch": "Skitse", "ui.sketch_dimension": "Skitsemål", "ui.sketch_grid": "Skitsegitter", + "ui.sketch_modifiers": "Taster i skitser", "ui.sketch_scale": "Skitseskalering", "ui.sketch_status": "Skitsestatus", "ui.sketches": "Skitser", @@ -1476,8 +1528,34 @@ "ui.smooth_wheel_zoom": "Jævn zoom med musehjul", "ui.smooth_wheel_zoom_tip": "Slå fra for at anvende hver hjulbevægelse straks uden efterfølgende udjævning", "ui.snap": "Fastgør til geometri", + "ui.space_mouse_calibrate": "Kalibrér…", + "ui.space_mouse_calibrate_tip": "Bevæg knoppen som vist i vinduet, så SolidCraft kan registrere retningen og bevægelsesområdet for hver akse. Indstillingerne gemmes til denne 3D-mus.", + "ui.space_mouse_calibrate_title": "Kalibrér 3D-mus", + "ui.space_mouse_calibrated": "Kalibreret", + "ui.space_mouse_calibration": "Kalibrering af 3D-mus", + "ui.space_mouse_calibration_done": "Færdig. Gem indstillingerne, så de bruges, hver gang denne 3D-mus tilsluttes.", + "ui.space_mouse_calibration_no_response": "En af akserne bevægede sig for lidt til at kunne kalibreres. Start forfra, og bevæg knoppen længere hver gang.", + "ui.space_mouse_dead_zone": "Dødzone", + "ui.space_mouse_dead_zone_tip": "Hvor langt knoppen skal bevæges, før visningen reagerer, angivet som en andel af dens fulde bevægelse. Øg værdien, hvis visningen bevæger sig, når du ikke rører knoppen.", + "ui.space_mouse_forget": "Nulstil kalibrering", "ui.space_mouse_hint": "Flyt og rotér visningen samtidigt; skitser bruger kun panorering og zoom.", "ui.space_mouse_navigate": "Navigér med SpaceNavigator / SpaceMouse", + "ui.space_mouse_none": "Ingen 3D-mus fundet", + "ui.space_mouse_not_calibrated": "Ikke kalibreret", + "ui.space_mouse_reading": "Aflæser", + "ui.space_mouse_step_lift": "Løft knoppen op, hold den dér, og slip.", + "ui.space_mouse_step_press": "Tryk knoppen ned, hold den dér, og slip.", + "ui.space_mouse_step_pull": "Træk knoppen mod dig, hold den dér, og slip.", + "ui.space_mouse_step_push": "Skub knoppen væk fra dig, hold den dér, og slip.", + "ui.space_mouse_step_rest": "Fjern hånden fra knoppen, og lad den stå stille.", + "ui.space_mouse_step_slide_left": "Skub knoppen mod venstre, hold den dér, og slip.", + "ui.space_mouse_step_slide_right": "Skub knoppen mod højre, hold den dér, og slip.", + "ui.space_mouse_step_tilt_back": "Vip knoppen bagud (forkanten op), hold den dér, og slip.", + "ui.space_mouse_step_tilt_forward": "Vip knoppen fremad (forkanten ned), hold den dér, og slip.", + "ui.space_mouse_step_tilt_left": "Vip knoppen mod venstre (venstre kant ned), hold den dér, og slip.", + "ui.space_mouse_step_tilt_right": "Vip knoppen mod højre (højre kant ned), hold den dér, og slip.", + "ui.space_mouse_step_twist_clockwise": "Drej knoppen med uret, hold den dér, og slip.", + "ui.space_mouse_step_twist_counterclockwise": "Drej knoppen mod uret, hold den dér, og slip.", "ui.spacing": "Afstand", "ui.spacing_2": "Afstand 2", "ui.sphere": "Kugle", @@ -1485,12 +1563,15 @@ "ui.split_body": "Opdel emne", "ui.stand_up_tip": "Når en STEP- eller IGES-fil åbnes med Z opad, tilbydes en kvart omdrejning om X", "ui.start": "Start", + "ui.start_over": "Start forfra", "ui.start_radius": "Startradius", "ui.stretch": "Stræk", "ui.supersampling": "Supersampling (SSAA)", "ui.supersampling_adaptive": "Kun når visningen står stille", "ui.supersampling_off": "Fra (1×)", "ui.suppress": "Undertryk", + "ui.suppress_auto_snap": "Slå automatisk snapping fra, mens du tegner eller trækker", + "ui.suppress_auto_snap_note": "Som standard kan både Ctrl/Cmd og Alt/Option slå snapping fra i skitser. Vælg én tast, hvis kun den skal bruges.", "ui.sweep": "Sweep", "ui.sweep_follow_direction": "Følg retning", "ui.sweep_keep_as_drawn": "Behold som tegnet", From 9c26f6dbc933c21fdfb9cb8061358c9a1c726b64 Mon Sep 17 00:00:00 2001 From: SS-EN <84559909+SS-EN@users.noreply.github.com> Date: Tue, 20 Oct 2026 12:41:05 +0000 Subject: [PATCH 211/225] Agent cursor: bound the show per request; run engine.batch while shown (#2900) Every engine.execute was acted out stop by stop (0.45 s glide + 0.25 s click per toolbar button and per on-screen point), so a 720-point sketch.line took minutes while the app answered no other control request. Now the pointer visits the toolbar button and at most three picks (a long point list is summarised by its first, middle and last point on screen), and a request is acted out within 1.5 s whatever its size (the legs get shorter). engine.batch is no longer refused while the cursor is shown: the pointer acts out a short summary (the toolbar buttons of up to four of its distinct commands, within the same budget), then the whole batch runs in one request. A failed engine.batch now says whether the design really went back (rolled_back). (cherry picked from commit 55535e01af45cc9ee7555320863ff5ddcd7c151f) Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/agent_cursor.rs | 187 +++++++++++++++++++++++++---- crates/ui-egui/src/control.rs | 52 ++++++-- 2 files changed, 204 insertions(+), 35 deletions(-) diff --git a/crates/ui-egui/src/agent_cursor.rs b/crates/ui-egui/src/agent_cursor.rs index 676ab5e0a..7844ad6b3 100644 --- a/crates/ui-egui/src/agent_cursor.rs +++ b/crates/ui-egui/src/agent_cursor.rs @@ -6,6 +6,12 @@ //! waits for the animation, so an agent's timing stays honest. With "follow camera" on, a new //! sketch turns the view to face it and finishing the sketch turns back. //! +//! The show is bounded, whatever the request's size: besides the toolbar button the pointer +//! visits at most [`MAX_PICK_STOPS`] picks (a long point list is summarised by its first, middle +//! and last point on screen), and one request is acted out in at most [`TIME_BUDGET`] seconds +//! (the legs get shorter when there are many). An `engine.batch` is acted out the same way, as +//! one request: the toolbar buttons of a few of its commands, then the whole batch runs. +//! //! The pointer is drawn by the app, so screen recordings capture it. It is off by default (View //! settings on the navigation bar, or `ui.agent_cursor {show, speed, follow_camera}`); a call //! with `"animate": false` skips it. @@ -62,7 +68,7 @@ impl Speed { } } /// Seconds to glide to a stop, and to click there. - fn times(self) -> (f64, f64) { + pub(crate) fn times(self) -> (f64, f64) { match self { Speed::Instant => (0.0, 0.0), Speed::Times(x) => { @@ -119,6 +125,9 @@ pub struct Job { params: Value, reply: Sender, stops: VecDeque, + /// Seconds per glide and per click for this request (within [`TIME_BUDGET`] in all). + glide: f64, + click: f64, /// The leg under way: where it started and when. from: Pos2, started: f64, @@ -144,26 +153,75 @@ impl AgentCursor { } } +/// Most picks the pointer visits for one command, besides its toolbar button. More are +/// summarised by evenly spaced ones (the first, the middle and the last of three). +pub const MAX_PICK_STOPS: usize = 3; + +/// Most toolbar buttons the pointer visits for one `engine.batch` (of its distinct commands, +/// evenly spaced). +pub const MAX_BATCH_STOPS: usize = 4; + +/// Longest the pointer may take to act out one request (a command or a whole batch), in +/// seconds, whatever its size: the app answers no other control request meanwhile. +pub const TIME_BUDGET: f64 = 1.5; + +/// At most `n` of `items`, evenly spaced, keeping the first and (for two or more) the last. +fn summarise(items: &[T], n: usize) -> Vec { + if items.len() <= n { + return items.to_vec(); + } + if n <= 1 { + return items.iter().take(n).copied().collect(); + } + let last = items.len() - 1; + (0..n).filter_map(|i| items.get(i * last / (n - 1)).copied()).collect() +} + +/// Seconds per glide and per click for `stops` stops at `speed`: the speed's own, shortened so +/// the whole request takes at most [`TIME_BUDGET`]. +pub fn leg_times(speed: Speed, stops: usize) -> (f64, f64) { + let (glide, click) = speed.times(); + let total = stops as f64 * (glide + click); + if total > TIME_BUDGET { + let k = TIME_BUDGET / total; + (glide * k, click * k) + } else { + (glide, click) + } +} + /// Keys whose [x, y, z] values are directions or amounts, not places to point at. const NOT_PLACES: [&str; 14] = ["translate", "dir1", "dir2", "axis", "direction", "normal", "pull", "color", "x_dir", "y_dir", "scale", "values", "limits", "size"]; -/// Where the pointer goes for a command: its toolbar button (or its panel), then each pick. +/// A command's toolbar button, or its panel when the button sits in a drop-down. +fn button(command: &str) -> Option { + let spec = solidcraft_engine::find_command(command)?; + crate::scenario::handle_at(&format!("toolbar:{}", spec.id)).or_else(|| crate::scenario::handle_at(&format!("panel:{}:{}", spec.tab, spec.panel))) +} + +/// Where the pointer goes for a command: its toolbar button (or its panel), then its picks on +/// screen, at most [`MAX_PICK_STOPS`] of them. pub fn stops(app: &SolveApp, command: &str, params: &Value) -> Vec { - let mut out = Vec::new(); - if let Some(spec) = solidcraft_engine::find_command(command) { - let button = crate::scenario::handle_at(&format!("toolbar:{}", spec.id)) - .or_else(|| crate::scenario::handle_at(&format!("panel:{}:{}", spec.tab, spec.panel))); - out.extend(button); - } + let mut out: Vec = button(command).into_iter().collect(); let Some(rect) = app.viewport.rect else { return out }; let proj = crate::viewport::projection(app, rect); - for w in picks(app, command, params) { - if let Some(p) = proj.to_screen(w).filter(|p| rect.contains(*p)) { - out.push(p); + let on_screen: Vec = picks(app, command, params).into_iter().filter_map(|w| proj.to_screen(w).filter(|p| rect.contains(*p))).collect(); + out.extend(summarise(&on_screen, MAX_PICK_STOPS)); + out +} + +/// Where the pointer goes for an `engine.batch`: the toolbar buttons of its distinct commands, in +/// the order they first come, at most [`MAX_BATCH_STOPS`] of them. +pub fn batch_stops(steps: &[Value]) -> Vec { + let mut seen: Vec<&str> = Vec::new(); + for c in steps.iter().filter_map(crate::control::batch_step_command) { + if !seen.contains(&c) { + seen.push(c); } } - out + let buttons: Vec = seen.into_iter().filter_map(button).collect(); + summarise(&buttons, MAX_BATCH_STOPS) } /// The places a command's parameters pick, in the world: [x, y, z] points (faces, edges, @@ -230,15 +288,22 @@ fn walk<'a>(v: &'a Value, key: Option<&'a str>, f: &mut dyn FnMut(Option<&'a str /// back when it should simply run. pub fn intercept(app: &mut SolveApp, method: &str, params: &Value, reply: &Sender) -> bool { let s = app.ui.agent_cursor; - if !s.show || !matches!(method, "engine.execute" | "command") { + if !s.show || params.get("animate").and_then(Value::as_bool) == Some(false) { return false; } - if params.get("animate").and_then(Value::as_bool) == Some(false) { - return false; - } - let Some(cmd) = params.get("command").or(params.get("id")).and_then(Value::as_str) else { return false }; - let inner = params.get("params").cloned().unwrap_or(json!({})); - let stops: VecDeque = stops(app, cmd, &inner).into(); + let stops: VecDeque = match method { + "engine.execute" | "command" => { + let Some(cmd) = params.get("command").or(params.get("id")).and_then(Value::as_str) else { return false }; + let inner = params.get("params").cloned().unwrap_or(json!({})); + stops(app, cmd, &inner).into() + } + // A batch is acted out as one request; one the app refuses is answered at once. + "engine.batch" => match params.get("commands").and_then(Value::as_array) { + Some(steps) if crate::control::batch_refusal(steps).is_none() => batch_stops(steps).into(), + _ => return false, + }, + _ => return false, + }; if s.speed == Speed::Instant { // No animation: the command runs now; the pointer jumps to where it acted. if let Some(last) = stops.back() { @@ -251,8 +316,18 @@ pub fn intercept(app: &mut SolveApp, method: &str, params: &Value, reply: &Sende return false; } let from = app.cursor_start(); - app.agent.job = - Some(Job { method: method.to_string(), params: params.clone(), reply: reply.clone(), stops, from, started: app.now, clicked: false }); + let (glide, click) = leg_times(s.speed, stops.len()); + app.agent.job = Some(Job { + method: method.to_string(), + params: params.clone(), + reply: reply.clone(), + stops, + glide, + click, + from, + started: app.now, + clicked: false, + }); true } @@ -275,8 +350,8 @@ pub fn step(app: &mut SolveApp, ctx: &egui::Context) { if !app.agent.ripples.is_empty() { ctx.request_repaint(); } - let (glide, click) = app.ui.agent_cursor.speed.times(); let Some(job) = app.agent.job.as_mut() else { return }; + let (glide, click) = (job.glide, job.click); ctx.request_repaint(); let Some(&to) = job.stops.front() else { finish(app, ctx); @@ -391,6 +466,74 @@ mod tests { assert!(stops(&a, "solid.hole", &json!({"position": [1e6, 0, 0]})).iter().all(|p| rect.contains(*p))); } + /// A ring of points around the box's top, `n` of them, in active-sketch coordinates. + fn ring(n: usize) -> Vec<[f64; 2]> { + (0..n) + .map(|i| { + let t = i as f64 / n as f64 * std::f64::consts::TAU; + [20.0 + 12.0 * t.cos(), 15.0 + 12.0 * t.sin()] + }) + .collect() + } + + /// A 720-point line is not acted out point by point (that took minutes): the pointer visits + /// at most a few representative points. + #[test] + fn long_point_lists_are_summarised() { + let mut a = app(); + a.session.execute("sketch.create", &json!({"plane": "XY"})).unwrap(); + let p = json!({"points": ring(720), "closed": true}); + assert!(picks(&a, "sketch.line", &p).len() >= 700, "every point is still a pick"); + let s = stops(&a, "sketch.line", &p); + assert!(s.len() >= MAX_PICK_STOPS && s.len() <= 1 + MAX_PICK_STOPS, "{s:?}"); + // Few points are all visited. + assert_eq!(stops(&a, "sketch.line", &json!({"points": ring(2)})).iter().filter(|p| a.viewport.rect.unwrap().contains(**p)).count(), 2); + assert_eq!(summarise(&[1, 2, 3, 4, 5, 6, 7], 3), vec![1, 4, 7]); + assert_eq!(summarise(&[1, 2], 3), vec![1, 2]); + assert_eq!(summarise(&[1, 2, 3], 1), vec![1]); + assert!(summarise(&[1, 2, 3], 0).is_empty()); + } + + /// However many stops, one request is acted out within the time budget; a short one keeps + /// the speed's own pace. + #[test] + fn one_request_is_acted_out_within_the_time_budget() { + for speed in [Speed::Times(1.0), Speed::Times(2.5), Speed::Times(5.0), Speed::Instant] { + for n in 0..=12 { + let (g, c) = leg_times(speed, n); + assert!(n as f64 * (g + c) <= TIME_BUDGET + 1e-9, "{speed:?} {n}: {g} {c}"); + assert!(g >= 0.0 && c >= 0.0); + } + } + assert_eq!(leg_times(Speed::Times(1.0), 1), Speed::Times(1.0).times()); + assert_eq!(leg_times(Speed::Times(5.0), 4), Speed::Times(5.0).times()); + } + + /// End to end: with the cursor shown, a 720-point line and a batch are each answered within + /// the time budget (in frames of 1/60 s), and the batch runs instead of being refused. + #[test] + fn big_requests_and_batches_are_acted_out_quickly() { + let mut h = crate::scenario::Harness::new(); + assert_eq!(h.call("ui.agent_cursor", json!({"show": true, "speed": 1}))["ok"], true); + assert_eq!(h.call("engine.execute", json!({"command": "sketch.create", "params": {"plane": "XY"}}))["ok"], true); + let most = (TIME_BUDGET * 60.0) as usize + 2 * (2 + MAX_PICK_STOPS) + 8; + let (r, frames) = h.call_queued("engine.execute", json!({"command": "sketch.line", "params": {"points": ring(720), "closed": true}})); + assert_eq!(r["ok"], true, "{r}"); + assert!(frames <= most, "{frames} frames (at most {most})"); + assert_eq!(h.call("engine.execute", json!({"command": "sketch.finish"}))["ok"], true); + let steps = json!([ + {"command": "solid.box", "params": {"length": 10, "width": 10, "height": 10, "corner": [60, 0, 0]}}, + {"command": "solid.sphere", "params": {"radius": 3, "center": [80, 0, 0]}}, + ]); + let (r, frames) = h.call_queued("engine.batch", json!({"commands": steps})); + assert_eq!((&r["ok"], &r["result"]["completed"]), (&json!(true), &json!(2)), "{r}"); + assert!(frames <= most, "{frames} frames (at most {most})"); + // A batch the app refuses is answered at once, without a show. + let (r, frames) = h.call_queued("engine.batch", json!({"commands": [{"command": "doc.open", "params": {"path": "x.solidcraft"}}]})); + assert!(r["error"].as_str().is_some_and(|e| e.starts_with("engine.batch unavailable")), "{r}"); + assert!(frames <= 3, "{frames}"); + } + #[test] fn speeds_read_old_and_new_settings() { // Saved settings from before #79: slow and normal are 1×, instant stays. diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index a96f0c5c1..4720d5a7a 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -5,8 +5,9 @@ //! - `engine.script {commands: [...]}`: run a command script //! - `engine.batch {commands: [...], rollback?}`: the steps in one request, each as //! `engine.execute` runs it; stops at the first failure and goes back to the checkpoint -//! (per-step results, `failed`, `undone`). Refused (`engine.batch unavailable: …`) while the -//! agent cursor is shown or when a step loads a file +//! (per-step results, `failed`, `undone`, `rolled_back`). Refused (`engine.batch unavailable: …`) +//! when a step loads a file; with the agent cursor shown, the pointer acts out a short summary +//! of it first //! - `engine.commands`: every command with tab, panel, params and enablement //! - `document.inspect {measure?}`: the design (parameters, timeline, bodies, sketches) //! - `ui.inspect`: UI state, viewport rect, camera, tool and dialog @@ -122,6 +123,18 @@ const MAX_BATCH: usize = 10_000; /// bypass. const LOADS_A_FILE: [&str; 3] = ["doc.open", "file.insert_step", "file.insert_mesh"]; +/// Why `engine.batch` refuses these steps before running any: a step loads a file (send such +/// steps one by one). +pub(crate) fn batch_refusal(steps: &[Value]) -> Option { + let (i, c) = steps.iter().enumerate().find_map(|(i, step)| command(step).filter(|c| LOADS_A_FILE.contains(c)).map(|c| (i, c)))?; + Some(format!("engine.batch unavailable: step {i} ({c}) loads a file")) +} + +/// A batch step's command id (the agent cursor points at its toolbar button). +pub(crate) fn batch_step_command(step: &Value) -> Option<&str> { + command(step) +} + /// `engine.batch {commands, rollback?, timings?, profile?}`: the steps in one request, so in one /// frame (#743). With `timings` the reply adds each step's time and `total_ms`, with `profile` /// each step's kernel share too (`solidcraft_engine::timing`, #1833). Each @@ -133,12 +146,10 @@ fn batch(app: &mut SolveApp, p: &Value) -> Outcome { let Some(steps) = p.get("commands").and_then(Value::as_array).filter(|s| s.len() <= MAX_BATCH) else { return err(format!("engine.batch: commands must be an array of at most {MAX_BATCH} steps")); }; - // The agent cursor acts out each `engine.execute` on its own. - if app.ui.agent_cursor.show { - return err("engine.batch unavailable: the agent cursor is shown"); - } - if let Some((i, c)) = steps.iter().enumerate().find_map(|(i, step)| command(step).filter(|c| LOADS_A_FILE.contains(c)).map(|c| (i, c))) { - return err(format!("engine.batch unavailable: step {i} ({c}) loads a file")); + // (With the agent cursor shown, the pointer has already acted out a short summary of the + // batch: `agent_cursor::intercept`.) + if let Some(why) = batch_refusal(steps) { + return err(why); } let rollback = p.get("rollback").and_then(Value::as_bool).unwrap_or(true); let profile = p.get("profile").and_then(Value::as_bool).unwrap_or(false); @@ -160,7 +171,9 @@ fn batch(app: &mut SolveApp, p: &Value) -> Outcome { Err(e) => { let restored = checkpoint.is_some_and(|id| app.run("edit.restore_checkpoint", json!({"checkpoint": id})).is_ok()); let failed = json!({"index": i, "command": command(step), "error": e}); - let reply = json!({"completed": i, "results": results, "failed": failed, "undone": if restored { i } else { 0 }}); + // `rolled_back`: the design really is back at its checkpoint. + let reply = + json!({"completed": i, "results": results, "failed": failed, "undone": if restored { i } else { 0 }, "rolled_back": restored}); return ok(with_timings(reply, timed, rows, clock.ms())); } } @@ -1225,13 +1238,26 @@ mod tests { } #[test] - fn engine_batch_is_refused_while_the_agent_cursor_is_shown() { + fn engine_batch_runs_while_the_agent_cursor_is_shown() { let mut h = crate::scenario::Harness::new(); assert_eq!(h.call("ui.agent_cursor", json!({"show": true}))["ok"], true); let v = batch(&mut h, json!({"commands": [{"command": "solid.box", "params": {"length": 10, "width": 10, "height": 10}}]})); - assert_eq!(v["ok"], false, "{v}"); - assert!(v["error"].as_str().is_some_and(|e| e.starts_with("engine.batch unavailable")), "{v}"); - assert_eq!(inspect(&mut h)["bodies"].as_array().map(Vec::len), Some(0)); + assert_eq!(v["ok"], true, "{v}"); + assert_eq!(v["result"]["completed"], 1, "{v}"); + assert_eq!(inspect(&mut h)["bodies"].as_array().map(Vec::len), Some(1)); + } + + /// A failed batch says whether the design really went back (`rolled_back`), not just whether + /// it was asked to. + #[test] + fn engine_batch_reports_whether_it_rolled_back() { + let mut h = crate::scenario::Harness::new(); + let steps = json!([{"command": "solid.box", "params": {"length": 10, "width": 10, "height": 10}}, {"command": "NoSuchCommand"}]); + let v = batch(&mut h, json!({"commands": steps.clone()})); + assert_eq!((&v["result"]["rolled_back"], &v["result"]["undone"]), (&json!(true), &json!(1)), "{v}"); + let v = batch(&mut h, json!({"commands": steps, "rollback": false})); + assert_eq!((&v["result"]["rolled_back"], &v["result"]["undone"]), (&json!(false), &json!(0)), "{v}"); + assert_eq!(inspect(&mut h)["bodies"].as_array().map(Vec::len), Some(1)); } /// Every step of a batch from an MCP server stays inside the agent's folders (#205), as an From 7c6845da9529a339ec47470c7b53d3f474450e56 Mon Sep 17 00:00:00 2001 From: cronos Date: Tue, 20 Oct 2026 12:42:43 +0000 Subject: [PATCH 212/225] Paste: the file-link test builds proper file URLs on Windows too (#3348) (#3494) The test turned a temp path into a link with `file://` + the path, which on Windows gives `file://C:\Users\...`, not a file URL, so the test failed there. It now builds `file:///C:/Users/.../my%20part.stl` on Windows (what Explorer and browsers put on the clipboard) and `file:///tmp/...` on Linux and macOS, as before. `files_in_text` already reads Windows file URLs correctly; the fixed test now checks that on Windows. Co-authored-by: Ray --- crates/ui-egui/src/agent_chat/paste.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/agent_chat/paste.rs b/crates/ui-egui/src/agent_chat/paste.rs index 2d722ca9e..0dd8c5c27 100644 --- a/crates/ui-egui/src/agent_chat/paste.rs +++ b/crates/ui-egui/src/agent_chat/paste.rs @@ -201,7 +201,11 @@ mod tests { std::fs::write(&spaced, b"solid").unwrap(); let plain = d.join("brief.md"); std::fs::write(&plain, b"x").unwrap(); - let link = |p: &Path| format!("file://{}", p.to_string_lossy().replace(' ', "%20")); + // A proper file URL on every system: `file:///tmp/a%20b`, `file:///C:/Users/a%20b`. + let link = |p: &Path| { + let path = p.to_string_lossy().replace(std::path::MAIN_SEPARATOR, "/").replace(' ', "%20"); + format!("file://{}{path}", if path.starts_with('/') { "" } else { "/" }) + }; let list = format!("# copied\n{}\r\n{}\n", link(&spaced), link(&plain)); assert_eq!(files_in_text(&list), vec![spaced.clone(), plain.clone()]); assert!(matches!(decide(Some(&list), &mut Fake::default()), Paste::Files(f) if f.len() == 2)); From d8eb65d26e36af74fc573c094f3106d0626fbcb6 Mon Sep 17 00:00:00 2001 From: takuto-NA Date: Tue, 20 Oct 2026 12:43:59 +0000 Subject: [PATCH 213/225] Make constrained sketch edges follow the cursor (#3360) (#3362) * claim: #3360 * Fix constrained sketch edge following and final drag coordinates --- crates/engine/src/cmd/sketch.rs | 13 +- crates/engine/src/cmd/sketch_drag.rs | 104 +++++++++--- .../engine/src/cmd/sketch_drag_live_tests.rs | 40 +++-- crates/engine/src/cmd/sketch_ux_tests.rs | 57 +++++++ crates/engine/tests/sketch_drag_target.rs | 157 ++++++++++++++++++ crates/sketch/src/cursor.rs | 79 +++++++-- crates/sketch/src/lib.rs | 4 +- crates/sketch/src/solver.rs | 4 +- crates/sketch/tests/cursor_target.rs | 27 ++- crates/ui-egui/src/sketch_drag_ui_tests.rs | 66 ++++++++ crates/ui-egui/src/viewport.rs | 7 +- 11 files changed, 491 insertions(+), 67 deletions(-) diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rs index c50b0f2d5..a906c9807 100644 --- a/crates/engine/src/cmd/sketch.rs +++ b/crates/engine/src/cmd/sketch.rs @@ -179,7 +179,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .params("entities: [curve, point or constraint ids]"), CommandSpec::new("sketch.move_point", "Drag Sketch Point", move_point).icon("sketch_move").enabled(in_sketch).params("point: ref, to: [x,y]"), CommandSpec::new("sketch.drag", "Drag Sketch Geometry", drag).icon("sketch_move").enabled(in_sketch).live(drag_live).params( - "entity: point or curve, from: [x,y] where it was grabbed, to: [x,y], live?: bool: a point moves toward `to` within the design constraints; when exact cursor placement is impossible, bounded feasible steps minimize cursor distance while keeping design constraints mandatory. A line (spline, conic) slides by to - from; a circle or arc grabbed on its edge takes the radius to `to`. `with?`: [point or curve ids]: the rest of a selection dragged by `entity`, which all slides by to - from as one (circles keep their radii). Long moves use continuation to retain the solution branch, and a step that would sweep an arc through its start is rejected. Returns `reached`: progress along the requested move (0..1; feasible point motion projects its actual displacement onto that move), and `at`: where the grabbed spot went (`from` moved as the dragged points did), the `from` of the next move. `live: true` solves the sketch and leaves later features stale until `sketch.drag_end` or a command that reads the model; `dof` is then the one from before the drag", + "entity: point or curve, from: [x,y] where it was grabbed, to: [x,y], live?: bool: points and the material point grabbed on a line move toward `to` within the design constraints. When exact placement is impossible, bounded feasible steps minimize cursor distance. Splines slide by to - from; a circle or arc grabbed on its edge takes the radius to `to`. `with?`: [point or curve ids] moves the rest of a selection with the entity as one translation (circles keep their radii). Long moves retain the solution branch; arcs cannot sweep through their starts. Returns `reached`: progress projected onto the requested move (0..1), `at`: the grabbed position for the next frame, and `retry`: budget-limited progress can continue in another frame. `live: true` shares a work budget across held-solve decomposition and cursor correction; ordinary recovery and the final model evaluation retain their existing limits, not a wall-clock deadline. Later features stay stale until `sketch.drag_end`; `dof` stays from before the drag", ), CommandSpec::new("sketch.drag_end", "End Sketch Drag", drag_end).icon("sketch_move").enabled(in_sketch).doc_only().params( "constraint?: {command: a sketch.constraint.* id, params}: ends a drag made of `sketch.drag` `live: true` frames: adds the constraint it let go on (not kept if it over-constrains the sketch), then evaluates the whole model once; returns the constraint's result and the sketch's solved state and degrees of freedom", @@ -2453,7 +2453,7 @@ fn drag_frame(s: &mut Session, p: &Value, live: bool) -> Result<(Value, Option Result<(Value, Option = d.moving.iter().filter_map(|&(q, was)| Some(sk.point(q)? - was)).collect(); - let at = from + moves.iter().fold(Vec2::ZERO, |a, m| a + *m) * (1.0 / moves.len().max(1) as f64); + let at = d.at(sk, from); let rep = rep.or_else(|| last.map(|last| SolveReport { status: solidcraft_sketch::SolveStatus::Solved, failing: Vec::new(), ..last })); - let out = json!({"sketch": rep.as_ref().map(report_json), "reached": d.reached, "at": [at.x, at.y]}); + let out = json!({"sketch": rep.as_ref().map(report_json), "reached": d.reached, "at": [at.x, at.y], "retry": d.retry}); Ok((out, rep.filter(|_| live).map(|report| crate::LiveEdit { sketch: id, report }))) } diff --git a/crates/engine/src/cmd/sketch_drag.rs b/crates/engine/src/cmd/sketch_drag.rs index 3f5cb7f6e..f495c7ee2 100644 --- a/crates/engine/src/cmd/sketch_drag.rs +++ b/crates/engine/src/cmd/sketch_drag.rs @@ -104,21 +104,21 @@ impl Path { } } -/// Drag: the grabbed entity follows the cursor where possible (a point moves toward it; a line or spline -/// slides by the cursor's move; a circle or arc grabbed on its edge changes radius about its +/// Drag: the grabbed entity follows the cursor where possible (a point or a material point on a +/// line moves toward it; a spline slides by the cursor's move; a circle or arc changes radius about its /// centre; a conic grabbed on its curve reads its fullness, `rho`, off the cursor) and the rest /// of the sketch moves as little as it can, staying on the /// solution it started on. Fixed geometry stays. A step that cannot be solved with the entity /// held (the path crosses where the geometry cannot reach) is approached by halving the way to /// it, and the next steps are tried from the last solved state, the last of them being the whole -/// remaining move. A point whose exact pin fails instead minimizes cursor distance in the -/// design's remaining freedom, retaining only corrected, feasible poses. For other entities, +/// remaining move. A point or line whose exact pin fails instead minimizes cursor distance in +/// the design's remaining freedom, retaining only corrected, feasible poses. For other entities, /// when none past it solves, the first failed step stays placed but unsolved: /// the edit's ordinary, non-strict solve that follows (seeded on the last solved state, see /// [`Left::MovedFrom`]) then pulls it back (fully constrained geometry) or leaves the sketch /// unsolved for the user to see. A step that would sweep an arc through its own start is undone /// and the drag ends there. Returns how far it got and what it leaves for the edit's solve -/// ([`Left::Solved`]: the held solve of the last step it kept left the sketch solved). +/// ([`Left::Solved`]: the retained pose satisfies the design constraints, even without progress). /// /// `with`: the rest of a selection dragged by one of its entities; all of it slides by the /// cursor's move as one (see [`plan_group`]). @@ -127,11 +127,13 @@ impl Path { /// one frame's work budget ([`Budget::frame`]); otherwise each has a solve's own. pub(super) fn drag_entity(sk: &mut Sketch, e: Ent, with: &[Ent], from: Vec2, to: Vec2, live: bool) -> (Dragged, Left) { let Some((path, hold, n, short)) = prepare(sk, e, with, from, to) else { - return (Dragged { reached: 0.0, moving: Vec::new() }, Left::Unsolved); + return (Dragged::default(), Left::Unsolved); }; #[cfg(test)] let (n, short) = (n.min(step_cap::get()), short.min(step_cap::get())); let moving: Vec<_> = path.points().filter_map(|q| Some((q, sk.point(q)?))).collect(); + let line_grab = if with.is_empty() { LineGrab::new(sk, e, from) } else { None }; + let start = line_grab.and_then(|g| g.point(sk)).or_else(|| if let Ent::Point(q) = e { sk.point(q) } else { None }); let mut frame = live.then(frame_budget); // Only success matters to these solves: the degrees of freedom of a sketch with the entity // held are not the sketch's. Each is seeded on the last solved state (`last`), so what the @@ -167,6 +169,7 @@ pub(super) fn drag_entity(sk: &mut Sketch, e: Ent, with: &[Ent], from: Vec2, to: // short steps. let (mut base, mut dt, mut k, mut t) = (0.0, 1.0 / n as f64, 0, 0.0); let mut shortened = false; + let mut wrapped = false; 'walk: while t < 1.0 { if solves.cut && !shortened { shortened = true; @@ -189,11 +192,18 @@ pub(super) fn drag_entity(sk: &mut Sketch, e: Ent, with: &[Ent], from: Vec2, to: continue; } Step::Wrapped => { + wrapped = true; failed = None; break 'walk; } Step::Failed => {} } + // Translating both ends can be impossible although a link can rotate. Do not spend + // the frame walking more impossible pins: optimize the point actually grabbed. + if line_grab.is_some() { + failed = Some(t); + break 'walk; + } if failed.is_none() { // Halve the way to the failed step, so the state the next steps start from (and are // seeded on) is as close to it as the geometry follows. The shortest move is tried @@ -209,7 +219,10 @@ pub(super) fn drag_entity(sk: &mut Sketch, e: Ent, with: &[Ent], from: Vec2, to: good = mid; last.take(sk); } - Step::Wrapped => break 'walk, + Step::Wrapped => { + wrapped = true; + break 'walk; + } Step::Failed => miss = mid, } } @@ -219,19 +232,26 @@ pub(super) fn drag_entity(sk: &mut Sketch, e: Ent, with: &[Ent], from: Vec2, to: // First retain held continuation across unreachable stretches of an otherwise reachable // path (for example an arm dragged through the hole around its shoulder). If it cannot // arrive, optimize the full cursor target without relaxing the design constraints. - if failed.is_some() - && let Ent::Point(q) = e + if !wrapped + && with.is_empty() + && (matches!(e, Ent::Point(_)) || line_grab.is_some()) + && (failed.is_some() || line_grab.and_then(|g| g.point(sk)).is_some_and(|at| at.dist(to) > 1e-7)) { let (points, radii) = sk.coupled(&hold.points, &hold.radii); let size = smallest_size(sk, &hold, Some(Group { points: &points, radii: &radii })); let max_step = (size * SHORT_STEP_FRACTION).min(path.length()).max(MIN_STEP); #[cfg(test)] let spent = frame.as_ref().map_or(0, Budget::spent); - let followed = solidcraft_sketch::move_point_towards(sk, q, to, max_step, frame.as_mut(), |before, after| { + let valid = |before: &Sketch, after: &Sketch| { let mut geometry = Geometry::default(); geometry.take(before); !geometry.sweep_wrapped(after) - }); + }; + let followed = match (e, line_grab) { + (Ent::Point(q), _) => solidcraft_sketch::move_point_towards(sk, q, to, max_step, frame.as_mut(), valid), + (_, Some(g)) => solidcraft_sketch::move_line_towards(sk, g.curve, g.local, to, max_step, frame.as_mut(), valid), + _ => false, + }; #[cfg(test)] if let Some(budget) = &frame { solves.work += budget.spent() - spent; @@ -240,15 +260,13 @@ pub(super) fn drag_entity(sk: &mut Sketch, e: Ent, with: &[Ent], from: Vec2, to: if followed { #[cfg(test)] last_drag::set(solves); - let reached = moving - .iter() - .find(|(p, _)| *p == q) - .and_then(|(_, start)| { - let d = to - *start; - sk.point(q).map(|at| if at.dist(to) < 1e-6 || d.dot(d) == 0.0 { 1.0 } else { ((at - *start).dot(d) / d.dot(d)).clamp(0.0, 1.0) }) - }) - .unwrap_or(0.0); - return (Dragged { reached, moving }, Left::Solved); + let at = line_grab.and_then(|g| g.point(sk)).or_else(|| if let Ent::Point(q) = e { sk.point(q) } else { None }); + let reached = start.zip(at).map_or(0.0, |(start, at)| { + let d = to - start; + if at.dist(to) < 1e-6 || d.dot(d) == 0.0 { 1.0 } else { ((at - start).dot(d) / d.dot(d)).clamp(0.0, 1.0) } + }); + let retry = frame.as_ref().is_some_and(Budget::exhausted) && start.zip(at).is_some_and(|(a, b)| a.dist(b) > 1e-9); + return (Dragged { reached, moving, line_grab, retry }, Left::Solved); } } #[cfg(test)] @@ -262,7 +280,7 @@ pub(super) fn drag_entity(sk: &mut Sketch, e: Ent, with: &[Ent], from: Vec2, to: None if good > 0.0 => Left::Solved, None => Left::Unsolved, }; - (Dragged { reached: good, moving }, left) + (Dragged { reached: good, moving, line_grab, retry: false }, left) } /// The held solves of one drag: how many, their shared work (including cursor correction), @@ -333,12 +351,54 @@ enum Step { } /// How far a drag got. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, Default, PartialEq)] pub(super) struct Dragged { /// The part of the way from where it was grabbed to the cursor the geometry followed (0..1). pub reached: f64, /// The points the drag moves (not the fixed ones it holds), where they were before it. pub moving: Vec<(usize, Vec2)>, + pub line_grab: Option, + /// Cursor work stopped at its budget after making progress; another frame can continue. + pub retry: bool, +} + +impl Dragged { + pub(super) fn at(&self, sk: &Sketch, from: Vec2) -> Vec2 { + if let Some(at) = self.line_grab.and_then(|g| g.point(sk)) { + return at; + } + let moves: Vec<_> = self.moving.iter().filter_map(|&(q, was)| Some(sk.point(q)? - was)).collect(); + from + moves.iter().fold(Vec2::ZERO, |a, m| a + *m) * (1.0 / moves.len().max(1) as f64) + } +} + +/// The grabbed position in a line's frame, retained through rotation and constraint correction. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) struct LineGrab { + curve: usize, + a: usize, + b: usize, + local: Vec2, +} + +impl LineGrab { + fn new(sk: &Sketch, e: Ent, from: Vec2) -> Option { + let Ent::Curve(curve) = e else { return None }; + let CurveKind::Line { a, b } = sk.curves.get(curve)?.kind else { return None }; + let pa = sk.point(a)?; + let d = sk.point(b)? - pa; + let len2 = d.dot(d); + if !(len2 > 1e-18) { + return None; + } + Some(Self { curve, a, b, local: Vec2::new((from - pa).dot(d) / len2, d.cross(from - pa) / len2) }) + } + + fn point(self, sk: &Sketch) -> Option { + let a = sk.point(self.a)?; + let d = sk.point(self.b)? - a; + Some(a + d * self.local.x + Vec2::new(-d.y, d.x) * self.local.y) + } } /// The geometry a step changes (point positions; curves, for radii and the arc ends a solve diff --git a/crates/engine/src/cmd/sketch_drag_live_tests.rs b/crates/engine/src/cmd/sketch_drag_live_tests.rs index 8139899ef..1cd021c6c 100644 --- a/crates/engine/src/cmd/sketch_drag_live_tests.rs +++ b/crates/engine/src/cmd/sketch_drag_live_tests.rs @@ -136,28 +136,27 @@ fn a_scripted_drag_still_evaluates_the_whole_model() { #[test] fn a_drag_reports_how_far_the_geometry_followed() { - let mut s = Session::default(); - run(&mut s, "sketch.create", json!({"plane": "XY"})); - run(&mut s, "sketch.line", json!({"points": [[10, 10], [40, 10]]})); - run(&mut s, "sketch.line", json!({"points": [[10, 30], [40, 30]]})); - run(&mut s, "sketch.constraint.fix", json!({"entities": ["l1.start"]})); - run(&mut s, "sketch.dimension", json!({"entities": ["l1"], "value": 30})); for live in [false, true] { - // A line of fixed length with a fixed end cannot slide: the sketch's own solve only - // turns it a little toward the cursor, and the grab follows its free end. - let before = pt(&s, "l1.end"); + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY"})); + run(&mut s, "sketch.line", json!({"points": [[10, 10], [40, 10]]})); + run(&mut s, "sketch.line", json!({"points": [[10, 30], [40, 30]]})); + run(&mut s, "sketch.constraint.fix", json!({"entities": ["l1.start"]})); + run(&mut s, "sketch.dimension", json!({"entities": ["l1"], "value": 30})); + // The grabbed midpoint follows a 15 mm circle around the fixed start. let r = run(&mut s, "sketch.drag", json!({"entity": "l1", "from": [25, 10], "to": [25, 20], "live": live})); - assert_eq!(r["reached"], json!(0.0), "{r}"); - let moved = pt(&s, "l1.end") - before; let at = crate::params::vec2(&r["at"]).expect("`at`"); - assert!(at.dist(solidcraft_geom::Vec2::new(25.0, 10.0) + moved) < 1e-9 && at.y < 20.0, "{r}"); - let to = 40 + 10 * usize::from(live); - let r = run(&mut s, "sketch.drag", json!({"entity": "l2", "from": [25, to - 10], "to": [25, to]})); - assert_eq!((&r["reached"], &r["at"]), (&json!(1.0), &json!([25.0, to as f64])), "{r}"); + let base = solidcraft_geom::Vec2::new(10.0, 10.0); + let expected = base + solidcraft_geom::Vec2::new(15.0, 10.0).normalized().unwrap() * 15.0; + assert!(at.dist(expected) < 1e-4, "{r}"); + assert!(at.dist((pt(&s, "l1.start") + pt(&s, "l1.end")) * 0.5) < 1e-6); + assert!((r["reached"].as_f64().unwrap() - (at.y - 10.0) / 10.0).abs() < 1e-6); + assert!((pt(&s, "l1.end").dist(base) - 30.0).abs() < 1e-6); + let r = run(&mut s, "sketch.drag", json!({"entity": "l2", "from": [25, 30], "to": [25, 40]})); + assert_eq!((&r["reached"], &r["at"]), (&json!(1.0), &json!([25.0, 40.0])), "{r}"); + let r = run(&mut s, "sketch.drag", json!({"entity": "l1.start", "from": [10, 10], "to": [0, 0], "live": true})); + assert_eq!(r["reached"], json!(0.0)); } - // A point that cannot move at all. - let r = run(&mut s, "sketch.drag", json!({"entity": "l1.start", "from": [10, 10], "to": [0, 0], "live": true})); - assert_eq!(r["reached"], json!(0.0)); } #[test] @@ -192,14 +191,13 @@ fn ui_frames(s: &mut Session, entity: &str, grab: [f64; 2], moves: &[[f64; 2]]) #[test] fn the_grab_follows_the_points_that_move() { - // A line with a fixed end, dragged by its middle: only the free end moves, and it keeps the - // cursor's offset frame after frame. + // With one end fixed, the free end moves twice as far as its grabbed midpoint. let mut s = Session::default(); run(&mut s, "sketch.create", json!({"plane": "XY"})); run(&mut s, "sketch.line", json!({"points": [[10, 10], [30, 10]]})); run(&mut s, "sketch.constraint.fix", json!({"entities": ["l1.start"]})); ui_frames(&mut s, "l1", [20.0, 10.0], &[[0.0, 1.0]; 6]); - assert!(pt(&s, "l1.end").dist(solidcraft_geom::Vec2::new(30.0, 16.0)) < 1e-9, "{:?}", pt(&s, "l1.end")); + assert!(pt(&s, "l1.end").dist(solidcraft_geom::Vec2::new(30.0, 22.0)) < 1e-6, "{:?}", pt(&s, "l1.end")); assert!(pt(&s, "l1.start").dist(solidcraft_geom::Vec2::new(10.0, 10.0)) < 1e-12); } diff --git a/crates/engine/src/cmd/sketch_ux_tests.rs b/crates/engine/src/cmd/sketch_ux_tests.rs index c637d3bd7..b3d2c040b 100644 --- a/crates/engine/src/cmd/sketch_ux_tests.rs +++ b/crates/engine/src/cmd/sketch_ux_tests.rs @@ -1543,3 +1543,60 @@ fn cursor_fallback_respects_an_exhausted_live_frame_budget() { run(&mut s, "sketch.drag", json!({"entity": "crank.end", "from": [at.x, at.y], "to": [target.x, target.y], "live": false})); assert!(pt(&s, "crank.end").dist(nearest) < 1e-4, "scripted motion retains the full cursor objective"); } + +fn four_bar_drag_sketch() -> Session { + let mut s = new_sketch(); + let x = -10.0 + (1600.0 - 400.0 + 52.0 * 52.0) / 104.0; + let y = -(1600.0_f64 - (x + 10.0) * (x + 10.0)).sqrt(); + run(&mut s, "sketch.line", json!({"points":[[0,0],[-10,0],[x,y],[42,0]],"ids":["crank","coupler","rocker"],"infer":false})); + run(&mut s, "sketch.line", json!({"points":["crank.start","rocker.end"],"ids":["ground"],"infer":false})); + for (line, len) in [("crank", 10), ("coupler", 40), ("rocker", 20), ("ground", 42)] { + run(&mut s, "sketch.dimension", json!({"entities":[line],"value":len})); + } + run(&mut s, "sketch.constraint.horizontal_vertical", json!({"line":"ground"})); + s +} + +#[test] +fn releasing_a_budget_limited_four_bar_drag_finishes_with_a_bounded_budget() { + for (entity, fraction) in [("crank.end", 1.0), ("crank", 0.7)] { + let mut s = four_bar_drag_sketch(); + let target = v(-10.0, 16.0) * fraction; + let nearest = target * (10.0 * fraction / target.len()); + super::drag::last_drag::with_frame_work(0, || { + run(&mut s, "sketch.drag", json!({"entity":entity,"from":[-10.0*fraction,0],"to":[target.x,target.y],"live":true})); + let at = pt(&s, "crank.end") * fraction; + assert!(at.dist(nearest) > 0.5); + }); + // The release is a new frame, with the same normal frame budget, not an unbounded + // final solve. The pointer has not moved since the budget-limited frame. + let at = pt(&s, "crank.end") * fraction; + run(&mut s, "sketch.drag", json!({"entity":entity,"from":[at.x,at.y],"to":[target.x,target.y],"live":true})); + assert!((pt(&s, "crank.end") * fraction).dist(nearest) < 1e-4); + run(&mut s, "sketch.drag_end", json!({})); + assert!((pt(&s, "crank.end") * fraction).dist(nearest) < 1e-4); + } +} + +#[test] +fn budget_limited_cursor_progress_requests_a_frame_with_the_same_target() { + let mut exercised = false; + for budget in [2048, 4096, 8192, 16384, 32768] { + let mut s = four_bar_drag_sketch(); + let target = v(-7.0, 11.2); + let nearest = target * (7.0 / target.len()); + let r = super::drag::last_drag::with_frame_work(budget, || { + run(&mut s, "sketch.drag", json!({"entity":"crank","from":[-7,0],"to":[target.x,target.y],"live":true})) + }); + if r["retry"] != true { + continue; + } + exercised = true; + let at = pt(&s, "crank.end") * 0.7; + assert!(at.dist(target) < v(-7.0, 0.0).dist(target)); + let r = run(&mut s, "sketch.drag", json!({"entity":"crank","from":[at.x,at.y],"to":[target.x,target.y],"live":true})); + assert!((pt(&s, "crank.end") * 0.7).dist(nearest) < 1e-4); + assert_eq!(r["retry"], false); + } + assert!(exercised, "exercise continuation after budget-limited progress"); +} diff --git a/crates/engine/tests/sketch_drag_target.rs b/crates/engine/tests/sketch_drag_target.rs index e7d1a9ca9..a122b0611 100644 --- a/crates/engine/tests/sketch_drag_target.rs +++ b/crates/engine/tests/sketch_drag_target.rs @@ -105,3 +105,160 @@ fn four_bar_other_joint_follows_the_rocker_arc_and_its_limits() { assert!(four_bar::point(&s, "coupler.end").unwrap().dist(nearest) < 1e-4); } } + +fn grab(s: &solidcraft_engine::Session, line: &str, fraction: f64) -> Vec2 { + let a = four_bar::point(s, &format!("{line}.start")).unwrap(); + let b = four_bar::point(s, &format!("{line}.end")).unwrap(); + a + (b - a) * fraction +} + +#[test] +fn a_free_line_grabbed_slightly_off_its_edge_still_translates_rigidly() { + for from in [Vec2::new(15.0, 12.0), Vec2::new(32.0, 11.0)] { + let mut s = solidcraft_engine::Session::default(); + s.execute("sketch.create", &json!({"plane":"XZ"})).unwrap(); + s.execute("sketch.line", &json!({"points":[[10,10],[30,10]],"ids":["free"],"infer":false})).unwrap(); + let to = from + Vec2::new(3.0, 5.0); + let r = s.execute("sketch.drag", &json!({"entity":"free","from":[from.x,from.y],"to":[to.x,to.y],"live":true})).unwrap(); + assert!(four_bar::point(&s, "free.start").unwrap().dist(Vec2::new(13.0, 15.0)) < 1e-6); + assert!(four_bar::point(&s, "free.end").unwrap().dist(Vec2::new(33.0, 15.0)) < 1e-6); + let at = Vec2::new(r["at"][0].as_f64().unwrap(), r["at"][1].as_f64().unwrap()); + assert!(at.dist(to) < 1e-6); + } +} + +#[test] +fn an_offset_edge_grab_rotates_with_the_link_and_does_not_drift() { + for local in [Vec2::new(0.7, 0.1), Vec2::new(0.7, -0.1)] { + let mut s = four_bar::session().unwrap(); + let target = Vec2::new(-7.0, 11.2); + let closest = target * (10.0 * local.len() / target.len()); + let attached = |s: &solidcraft_engine::Session| { + let a = four_bar::point(s, "crank.start").unwrap(); + let d = four_bar::point(s, "crank.end").unwrap() - a; + a + d * local.x + Vec2::new(-d.y, d.x) * local.y + }; + let mut from = attached(&s); + for _ in 0..8 { + let r = s.execute("sketch.drag", &json!({"entity":"crank","from":[from.x,from.y],"to":[target.x,target.y],"live":true})).unwrap(); + from = Vec2::new(r["at"][0].as_f64().unwrap(), r["at"][1].as_f64().unwrap()); + assert!(from.dist(attached(&s)) < 1e-6); + assert!(attached(&s).dist(closest) < 1e-4); + assert!(four_bar::length_error(&s).unwrap() < 1e-6); + assert_eq!(four_bar::branch(&s).unwrap(), -1.0); + } + } +} + +#[test] +fn crank_edge_large_drag_reaches_the_nearest_material_point() { + for fraction in [0.2, 0.5, 0.8] { + let mut s = four_bar::session().unwrap(); + let side = four_bar::branch(&s).unwrap(); + let from = grab(&s, "crank", fraction); + let target = Vec2::new(-10.0, 16.0) * fraction; + let nearest = target * (10.0 * fraction / target.len()); + let result = s.execute("sketch.drag", &json!({"entity":"crank", "from":[from.x,from.y], "to":[target.x,target.y], "live":true})).unwrap(); + let actual = grab(&s, "crank", fraction); + assert!(four_bar::length_error(&s).unwrap() < 1e-6); + assert_eq!(four_bar::branch(&s).unwrap(), side); + assert!(actual.dist(nearest) < 1e-4, "fraction {fraction}: {actual:?}, expected {nearest:?}"); + let at = Vec2::new(result["at"][0].as_f64().unwrap(), result["at"][1].as_f64().unwrap()); + assert!(at.dist(actual) < 1e-6, "reported grab {at:?}, actual {actual:?}"); + s.execute("sketch.drag_end", &json!({})).unwrap(); + assert!(grab(&s, "crank", fraction).dist(nearest) < 1e-4); + } +} + +#[test] +fn rocker_edge_keeps_its_material_point_and_motion_limits() { + let base = Vec2::new(42.0, 0.0); + let lo = -(-1264.0_f64 / 1680.0).acos(); + let hi = -(0.2_f64).acos(); + for fraction in [0.2, 0.5, 0.8] { + for angle in [-2.6_f64, -2.1, -1.5, -1.1] { + let mut s = four_bar::session().unwrap(); + let from = grab(&s, "rocker", fraction); + let target = base + Vec2::new(angle.cos(), angle.sin()) * (60.0 * (1.0 - fraction)); + let closest = base + Vec2::new(angle.clamp(lo, hi).cos(), angle.clamp(lo, hi).sin()) * (20.0 * (1.0 - fraction)); + s.execute("sketch.drag", &json!({"entity":"rocker","from":[from.x,from.y],"to":[target.x,target.y],"live":true})).unwrap(); + assert!( + grab(&s, "rocker", fraction).dist(closest) < 1e-4, + "fraction {fraction}, angle {angle}, actual {:?}, expected {closest:?}", + grab(&s, "rocker", fraction) + ); + assert!(four_bar::length_error(&s).unwrap() < 1e-6); + assert_eq!(four_bar::branch(&s).unwrap(), -1.0); + } + } +} + +#[test] +fn an_off_centre_edge_grab_agrees_for_one_move_split_moves_and_holding_still() { + for fraction in [0.2, 0.5, 0.8] { + for frames in [1, 16] { + let mut s = four_bar::session().unwrap(); + let start = grab(&s, "crank", fraction); + let target = Vec2::new(-10.0, 16.0) * fraction; + let mut from = start; + for i in 1..=frames + 8 { + let to = start + (target - start) * (i.min(frames) as f64 / frames as f64); + let result = s.execute("sketch.drag", &json!({"entity":"crank","from":[from.x,from.y],"to":[to.x,to.y],"live":true})).unwrap(); + from = Vec2::new(result["at"][0].as_f64().unwrap(), result["at"][1].as_f64().unwrap()); + assert!(from.dist(grab(&s, "crank", fraction)) < 1e-6); + assert!(four_bar::length_error(&s).unwrap() < 1e-6); + } + let closest = target * (10.0 * fraction / target.len()); + assert!(grab(&s, "crank", fraction).dist(closest) < 1e-4); + } + } +} + +fn coupler_point(angle: f64, along: f64) -> Vec2 { + let a = Vec2::new(angle.cos(), angle.sin()) * 10.0; + let d = Vec2::new(42.0, 0.0) - a; + let len = d.len(); + let u = d * (1.0 / len); + let x = (40.0 * 40.0 - 20.0 * 20.0 + len * len) / (2.0 * len); + let c = a + u * x + Vec2::new(u.y, -u.x) * (1600.0 - x * x).sqrt(); + a + (c - a) * along +} + +fn closest_coupler_point(target: Vec2, along: f64) -> Vec2 { + // Independent one-dimensional oracle: sample the full crank revolution, then refine + // the best interval. Both circle intersections keep the reported linkage's branch. + let step = std::f64::consts::TAU / 4096.0; + let best = (0..4096) + .min_by(|a, b| coupler_point(*a as f64 * step, along).dist(target).total_cmp(&coupler_point(*b as f64 * step, along).dist(target))) + .unwrap(); + let (mut lo, mut hi) = ((best as f64 - 1.0) * step, (best as f64 + 1.0) * step); + for _ in 0..80 { + let a = (2.0 * lo + hi) / 3.0; + let b = (lo + 2.0 * hi) / 3.0; + if coupler_point(a, along).dist(target) < coupler_point(b, along).dist(target) { + hi = b; + } else { + lo = a; + } + } + coupler_point((lo + hi) * 0.5, along) +} + +#[test] +fn the_coupler_edge_follows_with_both_ends_free_to_rotate() { + for along in [0.2, 0.5, 0.8] { + for angle in [1.8, 2.3, 3.8] { + let mut s = four_bar::session().unwrap(); + let from = grab(&s, "coupler", along); + let target = coupler_point(angle, along) + Vec2::new(-3.0, 4.0); + let closest = closest_coupler_point(target, along); + let result = s.execute("sketch.drag", &json!({"entity":"coupler","from":[from.x,from.y],"to":[target.x,target.y],"live":true})).unwrap(); + let actual = grab(&s, "coupler", along); + assert!(actual.dist(closest) < 1e-4, "along {along}, angle {angle}, actual {actual:?}, closest {closest:?}"); + let at = Vec2::new(result["at"][0].as_f64().unwrap(), result["at"][1].as_f64().unwrap()); + assert!(at.dist(actual) < 1e-6); + assert!(four_bar::length_error(&s).unwrap() < 1e-6); + assert_eq!(four_bar::branch(&s).unwrap(), -1.0); + } + } +} diff --git a/crates/sketch/src/cursor.rs b/crates/sketch/src/cursor.rs index 36bdf923d..099d772c8 100644 --- a/crates/sketch/src/cursor.rs +++ b/crates/sketch/src/cursor.rs @@ -28,6 +28,44 @@ pub fn move_point_towards( point: usize, target: Vec2, max_step: f64, + budget: Option<&mut Budget>, + valid: impl Fn(&Sketch, &Sketch) -> bool, +) -> bool { + move_cursor_towards(sk, &[(point, Vec2::X)], target, max_step, budget, valid) +} + +/// Move a grabbed position attached to a line toward the cursor. `grab.x` is its fraction +/// along the line (0 at its start, 1 at its end); `grab.y` is the signed perpendicular offset, +/// also divided by the line's length. The offset rotates and scales with the line. +/// The line may rotate: its endpoints are not independently pinned to a translation. +/// Feasibility, work limits and the return value have the same meaning as [`move_point_towards`]. +pub fn move_line_towards( + sk: &mut Sketch, + line: usize, + grab: Vec2, + target: Vec2, + max_step: f64, + budget: Option<&mut Budget>, + valid: impl Fn(&Sketch, &Sketch) -> bool, +) -> bool { + if !grab.is_finite() { + return false; + } + let Some(CurveKind::Line { a, b }) = sk.curves.get(line).map(|c| &c.kind) else { return false }; + let (Some(pa), Some(pb)) = (sk.point(*a), sk.point(*b)) else { return false }; + let d = pb - pa; + if !(d.dot(d) > 1e-18 && crate::model::in_range(pa + weighted(d, grab))) { + return false; + } + move_cursor_towards(sk, &[(*a, Vec2::new(1.0 - grab.x, -grab.y)), (*b, grab)], target, max_step, budget, valid) +} + +// Both callers' endpoint weights sum to (1, 0): translating the anchors translates the grab. +fn move_cursor_towards( + sk: &mut Sketch, + points: &[(usize, Vec2)], + target: Vec2, + max_step: f64, mut budget: Option<&mut Budget>, valid: impl Fn(&Sketch, &Sketch) -> bool, ) -> bool { @@ -40,10 +78,15 @@ pub fn move_point_towards( } let problem = sk.clone(); let lay = layout(&problem, &Hold::default()); - let Some(px) = lay.pvar.get(point).copied().flatten() else { return false }; + let active: Vec<_> = + points.iter().filter(|(_, w)| w.x != 0.0 || w.y != 0.0).filter_map(|(p, w)| Some((lay.pvar.get(*p).copied().flatten()?, *w))).collect(); + let Some(&(px, _)) = active.first() else { return false }; let (blocks, _) = build_blocks(&problem, &lay, &points_on_curves(&problem)); let mut parent: Vec = (0..lay.n).collect(); - union(&mut parent, px, px + 1); + for &(v, _) in &active { + union(&mut parent, px, v); + union(&mut parent, px, v + 1); + } for (_, vars) in &blocks { if let Some(&first) = vars.first() { for &v in vars.iter().skip(1) { @@ -70,7 +113,13 @@ pub fn move_point_towards( } let mut col = vec![usize::MAX; lay.n]; columns(&mut col, &vars, &vars); - let (Some(ix), Some(iy)) = (vars.iter().position(|v| *v == px), vars.iter().position(|v| *v == px + 1)) else { return false }; + let axes: Vec<_> = active.iter().filter_map(|(v, w)| Some((vars.binary_search(v).ok()?, *w))).collect(); + let position = |x: &[f64]| { + let state = State { sk: &problem, lay: &lay, x }; + // Relative coordinates avoid cancellation when a small line is far from the origin. + let base = points.first().map_or(Vec2::ZERO, |(p, _)| state.p(*p)); + points.iter().fold(base, |at, (p, w)| at + weighted(state.p(*p) - base, *w)) + }; let mut best = problem.clone(); let mut spent = 0; // Held feasibility solves accept up to ACCEPT. A tiny, nearly feasible hard pin can @@ -91,7 +140,7 @@ pub fn move_point_towards( } let mut gain = 1.0_f64; for _ in 0..MAX_STEPS { - let at = State { sk: &problem, lay: &lay, x: &x }.p(point); + let at = position(&x); let error = target - at; if error.len() < 1e-7 || spent >= TOTAL_CORRECTION_ITERS { break; @@ -110,7 +159,7 @@ pub fn move_point_towards( if z.is_empty() { break; } - let mut direction = target_step(&z, ix, iy, error); + let mut direction = target_step(&z, &axes, error); let norm = length(&direction); // Adapt to curvature of the reachable locus. Inside a circle the Gauss-Newton // cursor step can be arbitrarily small although useful freedom remains. @@ -122,7 +171,7 @@ pub fn move_point_towards( // A cursor across a circular locus has (nearly) zero first derivative at the // farthest point. If line search stalls, probe both tangent directions. Testing // only an exactly zero gradient would strand reversed drags after rounding. - let influence = |v: &&Vec| v.get(ix).copied().unwrap_or(0.0).hypot(v.get(iy).copied().unwrap_or(0.0)); + let influence = |v: &&Vec| cursor_direction(v, &axes).len(); let mut probes: Vec<_> = z.iter().collect(); probes.sort_by(|a, b| influence(b).total_cmp(&influence(a))); for v in probes.into_iter().take(2) { @@ -165,7 +214,7 @@ pub fn move_point_towards( } continue; } - let next = State { sk: &problem, lay: &lay, x: &trial }.p(point); + let next = position(&trial); let cost = (target - next).dot(target - next); if !cost.is_finite() || cost >= old_cost - 1e-14 * old_cost.max(1.0) { continue; @@ -248,13 +297,21 @@ fn null_space(mut j: Mat) -> Vec> { z } -fn target_step(z: &[Vec], ix: usize, iy: usize, error: Vec2) -> Vec { +/// The second weight component multiplies a 90-degree rotation of the endpoint. +fn weighted(v: Vec2, w: Vec2) -> Vec2 { + if w.y == 0.0 { v * w.x } else { Vec2::new(v.x * w.x - v.y * w.y, v.y * w.x + v.x * w.y) } +} + +fn cursor_direction(v: &[f64], axes: &[(usize, Vec2)]) -> Vec2 { + axes.iter().fold(Vec2::ZERO, |at, (i, w)| at + weighted(Vec2::new(v.get(*i).copied().unwrap_or(0.0), v.get(*i + 1).copied().unwrap_or(0.0)), *w)) +} + +fn target_step(z: &[Vec], axes: &[(usize, Vec2)], error: Vec2) -> Vec { let mut a = 0.0; let mut b = 0.0; let mut c = 0.0; for q in z { - let x = q.get(ix).copied().unwrap_or(0.0); - let y = q.get(iy).copied().unwrap_or(0.0); + let Vec2 { x, y } = cursor_direction(q, axes); a += x * x; b += x * y; c += y * y; @@ -269,7 +326,7 @@ fn target_step(z: &[Vec], ix: usize, iy: usize, error: Vec2) -> Vec { } let mut step = vec![0.0; z.first().map_or(0, Vec::len)]; for q in z { - let d = q.get(ix).copied().unwrap_or(0.0) * u.x + q.get(iy).copied().unwrap_or(0.0) * u.y; + let d = cursor_direction(q, axes).dot(u); for (x, v) in step.iter_mut().zip(q) { *x += d * v; } diff --git a/crates/sketch/src/lib.rs b/crates/sketch/src/lib.rs index 34d597cfe..80c32b996 100644 --- a/crates/sketch/src/lib.rs +++ b/crates/sketch/src/lib.rs @@ -63,8 +63,8 @@ pub use profiles::{ }; pub use shape::{Shape, intersections}; pub use solver::{ - Analysis, CONSISTENT, DrivingValues, Hold, SolveReport, SolveStatus, constraint_residual, determined_by, measure_dimension, move_point_towards, - solve, solve_after_edit, solve_after_value_edit, solve_holding, solve_with, + Analysis, CONSISTENT, DrivingValues, Hold, SolveReport, SolveStatus, constraint_residual, determined_by, measure_dimension, move_line_towards, + move_point_towards, solve, solve_after_edit, solve_after_value_edit, solve_holding, solve_with, }; pub use text::{MAX_TEXT_CHARS, TextAlign, TextStyle, text_geometry, text_geometry_in, text_geometry_styled}; pub use thin::{MAX_THIN_SEGMENTS, thin_wall_regions}; diff --git a/crates/sketch/src/solver.rs b/crates/sketch/src/solver.rs index af0b61ee1..d5165ae6d 100644 --- a/crates/sketch/src/solver.rs +++ b/crates/sketch/src/solver.rs @@ -23,7 +23,7 @@ use crate::union_find::{find, union}; #[path = "cursor.rs"] mod cursor; -pub use cursor::move_point_towards; +pub use cursor::{move_line_towards, move_point_towards}; #[path = "redundancy.rs"] mod redundancy; @@ -2036,7 +2036,7 @@ fn solve_inner( // start (the seeded one is where the pinned solve failed), or to its own start when // the seed did not move it. let reseeded = unseeded.as_ref().filter(|plain| vars.iter().any(|v| plain.get(*v).is_some_and(Option::is_some))); - if !solved && !(pinned_failed && reseeded.is_some()) { + if !(solved || pinned_failed && reseeded.is_some()) { let (its, r) = lm(sk, &lay, &sub, vars, &mut x, &col); iterations += its; residual = r; diff --git a/crates/sketch/tests/cursor_target.rs b/crates/sketch/tests/cursor_target.rs index ae2fc8b44..df9272028 100644 --- a/crates/sketch/tests/cursor_target.rs +++ b/crates/sketch/tests/cursor_target.rs @@ -1,6 +1,6 @@ //! Analytic cursor oracle plus feasibility checks on every accepted continuation step. use solidcraft_geom::Vec2; -use solidcraft_sketch::{ConstraintKind, Sketch, move_point_towards, solve}; +use solidcraft_sketch::{ConstraintKind, Sketch, move_line_towards, move_point_towards, solve}; fn linkage() -> (Sketch, usize, usize) { let mut sk = Sketch::new(); @@ -16,6 +16,31 @@ fn linkage() -> (Sketch, usize, usize) { (sk, a, c) } +#[test] +fn a_material_point_on_a_link_follows_without_relaxing_its_length() { + for along in [0.2, 0.5, 0.8] { + for target in [Vec2::new(-10.0, 16.0), Vec2::new(20.0, 0.0), Vec2::new(1000.0, -1000.0)] { + let (mut sk, a, c) = linkage(); + let line = sk.add_line_pts(0, a, None).unwrap(); + let target = target * along; + assert!(move_line_towards(&mut sk, line, Vec2::new(along, 0.0), target, 1.25, None, |before, after| { + assert!((after.points[a].pos.len() - 10.0).abs() < 1e-9); + assert!((after.points[a].pos.dist(after.points[c].pos) - 40.0).abs() < 1e-9); + assert!((after.points[c].pos.dist(Vec2::new(42.0, 0.0)) - 20.0).abs() < 1e-9); + assert!((after.points[a].pos * along).dist(target) < (before.points[a].pos * along).dist(target)); + (Vec2::new(42.0, 0.0) - after.points[a].pos).cross(after.points[c].pos - after.points[a].pos) < 0.0 + })); + let closest = target * (10.0 * along / target.len()); + assert!((sk.points[a].pos * along).dist(closest) < 1e-4); + let before = sk.clone(); + for invalid in [Vec2::new(f64::NAN, 0.0), Vec2::new(0.5, f64::INFINITY), Vec2::new(1e300, 1e300)] { + assert!(!move_line_towards(&mut sk, line, invalid, target, 1.25, None, |_, _| true)); + assert_eq!(sk, before); + } + } + } +} + #[test] fn circle_oracle_all_directions_and_large_targets() { for radius in [1.0, 12.8, 28.3, 100.0, 1000.0] { diff --git a/crates/ui-egui/src/sketch_drag_ui_tests.rs b/crates/ui-egui/src/sketch_drag_ui_tests.rs index 281cafda0..517174714 100644 --- a/crates/ui-egui/src/sketch_drag_ui_tests.rs +++ b/crates/ui-egui/src/sketch_drag_ui_tests.rs @@ -97,6 +97,72 @@ fn steps(a: egui::Pos2, b: egui::Pos2, n: usize) -> Vec { (1..=n).map(|k| a + (b - a) * (k as f32 / n as f32)).collect() } +fn four_bar() -> Harness { + let mut h = Harness::new(); + h.app.home.open = false; + run(&mut h, "sketch.create", json!({"plane":"XZ"})); + let x = -10.0 + (1600.0 - 400.0 + 52.0 * 52.0) / 104.0; + let y = -(1600.0_f64 - (x + 10.0) * (x + 10.0)).sqrt(); + run(&mut h, "sketch.line", json!({"points":[[0,0],[-10,0],[x,y],[42,0]],"ids":["crank","coupler","rocker"],"infer":false})); + run(&mut h, "sketch.line", json!({"points":["crank.start","rocker.end"],"ids":["ground"],"infer":false})); + for (line, length) in [("crank", 10), ("coupler", 40), ("rocker", 20), ("ground", 42)] { + run(&mut h, "sketch.dimension", json!({"entities":[line],"value":length})); + } + run(&mut h, "sketch.constraint.horizontal_vertical", json!({"line":"ground"})); + run(&mut h, "sketch.options", json!({"snap":false,"show_dimensions":false,"show_constraints":false})); + h.settle(); + h +} + +#[test] +fn a_four_bar_edge_follows_a_stationary_pointer_and_keeps_the_grab() { + let mut h = four_bar(); + let a = screen(&mut h, -7.0, 0.0); + let b = screen(&mut h, -7.0, 11.2); + let undo = h.app.session.undo.len(); + press_and_move(&mut h, &[a, b]); + assert_eq!(h.app.viewport.point_drag.as_ref().map(|(id, _, _)| id.as_str()), Some("crank"), "grabbed the edge, not an endpoint"); + h.frames(8); + let nearest = Vec2::new(-10.0, 16.0).normalized().unwrap() * 10.0; + assert!(point(&h, "crank.end").dist(nearest) < 0.05, "{:?}", point(&h, "crank.end")); + release(&mut h, b); + assert!(point(&h, "crank.end").dist(nearest) < 0.05); + assert_eq!(h.app.session.undo.len(), undo + 1); + run(&mut h, "edit.undo", json!({})); + assert!(point(&h, "crank.end").dist(Vec2::new(-10.0, 0.0)) < 1e-7); +} + +#[test] +fn a_four_bar_release_uses_the_final_pointer_position() { + let mut h = four_bar(); + let a = screen(&mut h, -10.0, 0.0); + let b = screen(&mut h, -10.0, 3.0); + let end = screen(&mut h, -10.0, 16.0); + press_and_move(&mut h, &[a, b]); + h.frames(8); + assert_eq!(h.app.viewport.point_drag.as_ref().map(|(id, _, _)| id.as_str()), Some("crank.end")); + release(&mut h, end); + let nearest = Vec2::new(-10.0, 16.0).normalized().unwrap() * 10.0; + assert!(point(&h, "crank.end").dist(nearest) < 0.05, "release left {:?}", point(&h, "crank.end")); + assert!(!h.app.session.model.is_stale()); +} + +#[test] +fn a_four_bar_edge_grab_keeps_its_pick_offset_when_rotating() { + let mut h = four_bar(); + let a = screen(&mut h, -7.0, 0.25); + let b = screen(&mut h, -7.0, 11.2); + press_and_move(&mut h, &[a, b]); + assert_eq!(h.app.viewport.point_drag.as_ref().map(|(id, _, _)| id.as_str()), Some("crank")); + h.frames(8); + release(&mut h, b); + let local = Vec2::new(0.7, -0.025); + let target = Vec2::new(-7.0, 11.2); + let closest = target * (10.0 * local.len() / target.len()); + let end = (closest * local.x - Vec2::new(-closest.y, closest.x) * local.y) * (1.0 / local.dot(local)); + assert!(point(&h, "crank.end").dist(end) < 0.05, "{:?}, expected {end:?}", point(&h, "crank.end")); +} + #[test] fn a_viewport_drag_solves_the_sketch_live_and_rebuilds_the_model_on_release() { let mut h = Harness::new(); diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 01cbbf47d..dc0a5aa12 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -2746,7 +2746,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { } } if let Some((id, depth, grab)) = app.viewport.point_drag.clone() - && resp.dragged_by(egui::PointerButton::Primary) + && (resp.dragged_by(egui::PointerButton::Primary) || resp.drag_stopped()) && let Some(mut q) = hover.and_then(|p| on_plane(app, p)) { let from = grab.unwrap_or(q); @@ -2783,6 +2783,11 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { let at = match app.session.execute("sketch.drag", ¶ms) { Ok(r) => { app.session.undo.truncate(depth + 1); + // Budget-limited progress continues even when the mouse stops. A stalled + // search asks for no more frames; release gets one bounded final attempt. + if r.get("retry").and_then(serde_json::Value::as_bool) == Some(true) && !resp.drag_stopped() { + ui.ctx().request_repaint(); + } r.get("at").and_then(solidcraft_engine::params::vec2).unwrap_or(q) } Err(_) => from, From 95de388ba1f5b5a43f9d63485cf471b9e6bf88fa Mon Sep 17 00:00:00 2001 From: rlartot <94693724+rlartot@users.noreply.github.com> Date: Tue, 20 Oct 2026 12:46:10 +0000 Subject: [PATCH 214/225] Sheet metal: refuse an edge flange on a bend line (#3234) (#3273) * claim: #3234 Co-Authored-By: Claude Sonnet 5.5 * Sheet metal: refuse an edge flange on a flange's bend line (#3234) A pick on the edge where a bend meets the plate (or the flange panel) found a panel edge that is already a bend line and made a second flange on it, leaving a gap and a sheet of two shells. add_flanges_each now refuses such an edge before anything moves. Co-Authored-By: Claude Sonnet 5.5 --------- Co-authored-by: Claude Sonnet 5.5 --- crates/doc/src/sheet.rs | 19 +++++++++++++++++++ crates/engine/src/cmd/sheet_tests.rs | 19 +++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/crates/doc/src/sheet.rs b/crates/doc/src/sheet.rs index 15ba85342..b4bfd40af 100644 --- a/crates/doc/src/sheet.rs +++ b/crates/doc/src/sheet.rs @@ -2320,6 +2320,25 @@ impl SheetBody { return Err(DocError::Invalid("pick an edge of the sheet's top or bottom face".into())); } let d = (b - a).normalized().ok_or_else(|| DocError::Invalid("edge".into()))?; + // A bend line is no free edge: the base's or the parent panel's edge where a flange + // starts, or the flange panel's edge where its bend ends. + let outward = Vec2::new(d.y, -d.x); + let on_bend = self.flanges.iter().enumerate().any(|(i, f)| { + let (at, facing) = if panel == f.parent { + (f.p, 1.0) + } else if panel == Some(i) { + (f.p + f.n * self.allowance(f), -1.0) + } else { + return false; + }; + let along = |p: Vec2| p.dot(f.d); + outward.dot(f.n) * facing > 0.99 + && (a - at).dot(f.n).abs() < 1e-6 + && along(a).max(along(b)).min(along(f.p) + f.len) - along(a).min(along(b)).max(along(f.p)) > 1e-6 + }); + if on_bend { + return Err(DocError::Invalid(format!("{}that edge is the bend line of a flange; pick a free edge of the sheet", on(k)))); + } let (s0, s1) = self .edge_left(panel, a, b, e.pick, &cuts) .ok_or_else(|| DocError::Invalid(format!("{}a cut-out has taken that edge away; pick an edge the sheet still has", on(k))))?; diff --git a/crates/engine/src/cmd/sheet_tests.rs b/crates/engine/src/cmd/sheet_tests.rs index 334e3fd2e..6db0520ab 100644 --- a/crates/engine/src/cmd/sheet_tests.rs +++ b/crates/engine/src/cmd/sheet_tests.rs @@ -1494,6 +1494,25 @@ fn an_edge_flange_on_a_flange_runs_along_what_a_flat_cut_left_of_its_far_edge() assert!(contains(&s, [130.0, 6.0, 42.0]) && !contains(&s, [30.0, 6.0, 42.0])); } +#[test] +fn an_edge_flange_is_refused_on_the_bend_line_of_a_flange() { + // The flange's bend runs between the plate's edge (y = 5) and the panel's edge (y = 2.5, + // z = 5). Either is a bend line, not a free edge: a flange there left a second flange with a + // gap and a sheet of two shells. + let mut s = Session::default(); + plate_with_flange(&mut s); + let before = volume(&mut s); + for pick in [[50.0, 5.0, 2.5], [50.0, 5.0, 0.0], [50.0, 2.5, 5.0], [50.0, 0.0, 5.0]] { + let e = s.execute("sheet.flange", &json!({"edges": [pick], "height": 10})); + assert!(e.as_ref().is_err_and(|e| e.to_string().contains("bend line")), "{pick:?}: {e:?}"); + assert!(rel(volume(&mut s), before) < 1e-9, "{pick:?} changed the sheet"); + } + // A free edge still takes one, and the sheet stays in one piece. + run(&mut s, "sheet.flange", json!({"edges": [[50, 60, 2.5]], "height": 10})); + assert!(no_errors_or_warnings(&s), "{:?}", s.model.results); + assert!(volume(&mut s) > before); +} + #[test] fn a_flange_bent_inside_keeps_the_base_sketchs_arcs_in_the_flat_pattern_and_the_dxf() { // A 200 x 100 plate with its corners rounded 8, drawn as arcs, and a 40 high flange on its From 50da77abc4b2d2b0c218525b01fee085c7fff8df Mon Sep 17 00:00:00 2001 From: Irakli Kourtis Date: Tue, 20 Oct 2026 14:09:49 +0000 Subject: [PATCH 215/225] CI: a run another label starts reports the commit's real result as ci (#3596) The merge queue reads the required ci check from the newest run of a commit. Adding any label but approved-for-ci starts a run whose jobs all skip, and its ci job was skipped too (as 'ci (ignored label)'), so a pull request that had passed could not enter the queue (#1850, #3182, #3252). On such a run the ci job now waits for the commit's other runs to finish and passes only when the newest one that ran its checks passed. Claude-Session: https://claude.ai/code/session_01QWhMwdqJYQKQq8RCLSL1LT Co-authored-by: jyviko <2501648+jyviko@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- .github/workflows/ci.yml | 43 +++++++++++++++++++++++++++++++++++----- 1 file changed, 38 insertions(+), 5 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7ec8a8b4a..8d6d2f3f4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -24,7 +24,9 @@ # result and runs the repository checks. Merge groups, the nightly run and Run workflow are not # pull requests and always run the full suite. # GitHub cannot filter `labeled` events by label name, so any other label starts a run whose jobs -# are all skipped; it gets its own concurrency group (below) so it never cancels the real run. +# are all skipped; it gets its own concurrency group (below) so it never cancels the real run. Its +# `ci` job still runs and reports the commit's real result (see the `ci` job): the merge queue +# reads `ci` from the newest run of a commit, so a run without it would block a PR that passed. # Cross-compilation is opt-in through Run workflow; release builds remain in release.yml. # Every Linux job runs on Blacksmith's Ubuntu 24.04 runners (blacksmith-vcpu-ubuntu-2404), sized # per job: 16 vCPU for Build tests, Clippy and the merge queue's test shards, 8 for compiles, the @@ -694,14 +696,45 @@ jobs: # Preserve the existing check name for branch protection, including docs-only PRs. ci: - # On the skipped run another label starts, this job is named differently, so that skipped job - # can never stand in for the required `ci` check of the pull request's real run. - name: ${{ github.event.action == 'labeled' && github.event.label.name != 'approved-for-ci' && 'ci (ignored label)' || 'ci' }} + # On a run another label starts (every other job skipped), this job reports the result of the + # commit's real run instead: the merge queue reads `ci` from the newest run of a commit, so a + # run without a passing `ci` would block a pull request that passed (#1850, #3182, #3252). + name: ci needs: [changes, checks, quick-compile, clippy, build-tests, tests, doc-tests, oracle, windows-fxc, windows-startup] - if: always() && (github.event_name != 'pull_request' || !github.event.pull_request.draft) && (github.event.action != 'labeled' || github.event.label.name == 'approved-for-ci') + if: always() && (github.event_name != 'pull_request' || !github.event.pull_request.draft) runs-on: blacksmith-2vcpu-ubuntu-2404 + permissions: + contents: read + # To read the commit's other runs of this workflow. + actions: read steps: + - name: Report the commit's real result (a run another label started) + if: github.event.action == 'labeled' && github.event.label.name != 'approved-for-ci' + env: + GH_TOKEN: ${{ github.token }} + REPO: ${{ github.repository }} + SHA: ${{ github.event.pull_request.head.sha }} + RUN_ID: ${{ github.run_id }} + run: | + # The other runs of ci.yml for this commit. While one is still going, wait for it (at + # most 90 minutes); then pass only when the newest one that ran its checks passed. + deadline=$((SECONDS + 5400)) + while :; do + runs=$(gh api "repos/$REPO/actions/workflows/ci.yml/runs?head_sha=$SHA&event=pull_request&per_page=100" \ + --jq "[.workflow_runs[] | select(.id != $RUN_ID)]") + pending=$(jq '[.[] | select(.status != "completed")] | length' <<<"$runs") + if [ "$pending" -eq 0 ] || [ "$SECONDS" -ge "$deadline" ]; then break; fi + echo "Waiting for $pending run(s) of this commit to finish." + sleep 30 + done + # Runs with every job skipped (labels, before this job reported) are not a result. + latest=$(jq -r '[.[] | select(.status == "completed" and .conclusion != "skipped")] + | sort_by(.created_at) | last | "\(.conclusion) \(.html_url)"' <<<"$runs") + echo "The commit's latest run: $latest" + echo "A label started this run: \`ci\` repeats the commit's latest result ($latest)." >> "$GITHUB_STEP_SUMMARY" + test "${latest%% *}" = success - name: Verify required checks + if: github.event.action != 'labeled' || github.event.label.name == 'approved-for-ci' env: CHANGES: ${{ needs.changes.result }} CHECKS: ${{ needs.checks.result }} From 843c0bf97a4d6287542631501703460acc3c2640 Mon Sep 17 00:00:00 2001 From: takuto-NA Date: Tue, 20 Oct 2026 13:55:25 +0000 Subject: [PATCH 216/225] Reduce repeated sketch diagnostics and enable normal-CI profiling regressions (#2355) (#2359) Co-authored-by: bherbruck --- crates/doc/src/document.rs | 28 +- crates/engine/Cargo.toml | 25 +- .../engine/examples/sketch_analysis_bench.rs | 124 ++++++ crates/engine/examples/sketch_drag_bench.rs | 116 +++++ crates/engine/examples/sketch_target_bench.rs | 53 +++ crates/engine/src/cmd/sketch.rs | 29 +- crates/engine/src/cmd/sketch_constraints.rs | 9 +- .../src/cmd/sketch_constraints_tests.rs | 29 ++ crates/engine/src/cmd/sketch_create.rs | 4 +- crates/engine/src/cmd/sketch_modify.rs | 2 +- crates/engine/tests/sketch_analysis.rs | 174 ++++++++ crates/sketch/Cargo.toml | 8 + crates/sketch/examples/solve_profile.rs | 306 +++++++++++++ crates/sketch/src/lib.rs | 3 + crates/sketch/src/profiling.rs | 406 ++++++++++++++++++ crates/sketch/src/redundancy.rs | 100 ++++- crates/sketch/src/redundancy_tests.rs | 184 ++++++++ crates/sketch/src/solver.rs | 100 ++++- crates/sketch/tests/analysis_levels.rs | 68 +++ crates/sketch/tests/cursor_target.rs | 27 ++ 20 files changed, 1747 insertions(+), 48 deletions(-) create mode 100644 crates/engine/examples/sketch_analysis_bench.rs create mode 100644 crates/engine/examples/sketch_drag_bench.rs create mode 100644 crates/engine/examples/sketch_target_bench.rs create mode 100644 crates/engine/tests/sketch_analysis.rs create mode 100644 crates/sketch/examples/solve_profile.rs create mode 100644 crates/sketch/src/profiling.rs create mode 100644 crates/sketch/src/redundancy_tests.rs create mode 100644 crates/sketch/tests/analysis_levels.rs diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index a6025acd1..02afec755 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -3372,14 +3372,36 @@ impl Document { sk: &mut Sketch, stored: &solidcraft_sketch::DrivingValues, moved_from: Option<&Sketch>, + ) -> Result { + self.solve_sketch_with_analysis(vals, sk, stored, moved_from, solidcraft_sketch::Analysis::Full) + } + + /// [`Self::solve_sketch`] with the diagnostics needed by an internal edit. Parameter + /// application, continuation and offset refreshes run regardless of the requested level. + /// Model evaluation uses `solve_sketch` so its published report always has full diagnostics. + pub fn solve_sketch_with_analysis( + &self, + vals: &std::collections::BTreeMap, + sk: &mut Sketch, + stored: &solidcraft_sketch::DrivingValues, + moved_from: Option<&Sketch>, + analysis: solidcraft_sketch::Analysis, ) -> Result { self.apply_dimension_values(vals, sk)?; let was = |sk: &Sketch| moved_from.and_then(|from| sk.positions_in(from)); - let mut report = solidcraft_sketch::solve_after_edit(sk, stored, was(sk).as_deref()); - if !sk.offsets.is_empty() || !sk.freeform_offsets.is_empty() { + let offsets = !sk.offsets.is_empty() || !sk.freeform_offsets.is_empty(); + // Offsets always require another solve after refresh. Only that last report is + // published; the first report only decides which state the second solve starts from. + let first_analysis = if offsets { solidcraft_sketch::Analysis::StatusOnly } else { analysis }; + let mut report = solidcraft_sketch::solve_after_edit_with_analysis(sk, stored, was(sk).as_deref(), first_analysis); + if offsets { // Source dimensions may have moved curves during the solve. sk.refresh_offsets()?; - report = if report.ok() { solidcraft_sketch::solve(sk) } else { solidcraft_sketch::solve_after_edit(sk, stored, was(sk).as_deref()) }; + report = if report.ok() { + solidcraft_sketch::solve_with(sk, &solidcraft_sketch::Hold::default(), None, analysis, None) + } else { + solidcraft_sketch::solve_after_edit_with_analysis(sk, stored, was(sk).as_deref(), analysis) + }; } Ok(report) } diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 3080f1b8c..1c5ec0fae 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -8,6 +8,24 @@ license.workspace = true [lints] workspace = true +[features] +# Turns on the parameter-contract audit recorder (`SOLIDCRAFT_PARAM_AUDIT`, see +# `src/schema/record.rs`), for checking a new contract against the whole test suite. +param-audit = [] +solver-profiling = ["solidcraft-sketch/solver-profiling"] + +[[example]] +name = "sketch_analysis_bench" +required-features = ["solver-profiling"] + +[[example]] +name = "sketch_drag_bench" +required-features = ["solver-profiling"] + +[[example]] +name = "sketch_target_bench" +required-features = ["solver-profiling"] + [dependencies] solidcraft-geom = { workspace = true } solidcraft-sketch = { workspace = true } @@ -23,7 +41,6 @@ thiserror = { workspace = true } log = { workspace = true } web-time = { workspace = true } -[features] -# Turns on the parameter-contract audit recorder (`SOLIDCRAFT_PARAM_AUDIT`, see -# `src/schema/record.rs`), for checking a new contract against the whole test suite. -param-audit = [] +[dev-dependencies] +# Normal CI exercises profiling assertions without enabling the production feature. +solidcraft-sketch = { workspace = true, features = ["solver-profiling"] } diff --git a/crates/engine/examples/sketch_analysis_bench.rs b/crates/engine/examples/sketch_analysis_bench.rs new file mode 100644 index 000000000..e7a10daaa --- /dev/null +++ b/crates/engine/examples/sketch_analysis_bench.rs @@ -0,0 +1,124 @@ +//! Time the actual AutoConstrain command on the solve_profile grid, with no UI or test-only solves. + +use std::{error::Error, io::Write, path::PathBuf, sync::Arc, time::Instant}; + +use serde_json::{Value, json}; +use solidcraft_engine::Session; +use solidcraft_geom::Vec2; +use solidcraft_sketch::{ConstraintKind, Sketch, profiling::capture}; + +type Result = std::result::Result>; + +fn grid(size: usize) -> Result { + let mut sk = Sketch::new(); + let mut points = Vec::new(); + let mut seed = 99u64; + let mut jitter = || { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (seed >> 11) as f64 / (1u64 << 53) as f64 * 2.0 - 1.0 + }; + for y in 0..size { + for x in 0..size { + let p = sk.add_point(Vec2::new(x as f64 * 10.0 + jitter(), y as f64 * 10.0 + jitter()), None)?; + points.push(p); + if x == 0 && y == 0 { + sk.add_constraint(ConstraintKind::Fix { p }, None)?; + } + for (other, horizontal) in [((x > 0).then(|| points.len() - 2), true), ((y > 0).then(|| points.len() - 1 - size), false)] { + if let Some(q) = other.and_then(|i| points.get(i)).copied() { + let l = sk.add_line_pts(q, p, None)?; + sk.add_constraint(if horizontal { ConstraintKind::Horizontal { l } } else { ConstraintKind::Vertical { l } }, None)?; + sk.add_constraint(ConstraintKind::Distance { p, q, value: 10.0 }, None)?; + } + } + } + } + Ok(sk) +} + +fn prepare(size: usize) -> Result { + let mut s = Session::default(); + s.execute("sketch.create", &json!({"plane": "XY"}))?; + let id = s.active_sketch.ok_or("missing active sketch")?; + *Arc::make_mut(&mut s.doc).sketch_mut(id)? = grid(size)?; + Ok(s) +} + +fn run(s: &mut Session) -> Result { + Ok(s.execute("sketch.auto_constrain", &json!({"dimensions": false}))?) +} + +fn percentile(samples: &[u64], percent: usize) -> u64 { + let mut sorted = samples.to_vec(); + sorted.sort_unstable(); + sorted.get((sorted.len() * percent).div_ceil(100).saturating_sub(1)).copied().unwrap_or(0) +} + +fn main() -> Result<()> { + let mut size = 10usize; + let mut repeats = 10usize; + let mut warmup = 2usize; + let mut out: Option = None; + let mut args = std::env::args().skip(1); + while let Some(key) = args.next() { + if key == "--help" { + println!("sketch_analysis_bench [--size 2..20] [--repeats 1..100] [--warmup 0..10] [--out FILE]"); + return Ok(()); + } + let value = args.next().ok_or_else(|| format!("missing value for {key}"))?; + match key.as_str() { + "--size" => size = value.parse()?, + "--repeats" => repeats = value.parse()?, + "--warmup" => warmup = value.parse()?, + "--out" => out = Some(value.into()), + _ => return Err(format!("unknown option {key}").into()), + } + } + if !(2..=20).contains(&size) || !(1..=100).contains(&repeats) || warmup > 10 { + return Err("size, repeats or warmup outside supported range (see --help)".into()); + } + for _ in 0..warmup { + run(&mut prepare(size)?)?; + } + let mut samples = Vec::new(); + let mut times = Vec::new(); + let mut reference = None; + for _ in 0..repeats { + // Session creation, fixture generation and serialization are outside the timer. + let mut session = prepare(size)?; + let start = Instant::now(); + let (response, profile) = capture(|| run(&mut session)); + let elapsed_ns = start.elapsed().as_nanos().min(u64::MAX as u128) as u64; + let response = response?; + if response["dof"] != 0 || response["added"] != json!([]) || response["sketch"]["solved"] != true { + return Err(format!("unexpected AutoConstrain result: {response}").into()); + } + let id = session.active_sketch.ok_or("missing active sketch")?; + let final_sketch = session.doc.sketch(id)?; + if let Some(expected) = &reference { + if final_sketch != expected { + return Err("AutoConstrain geometry changed between samples".into()); + } + } else { + reference = Some(final_sketch.clone()); + } + times.push(elapsed_ns); + let state = session.model.state(); + let published_report = &state.sketch(id).ok_or("missing published sketch")?.report; + samples.push(json!({"elapsed_ns": elapsed_ns, "response": response, "profile": profile, "published_report": published_report})); + } + let output = json!({ + "schema": "solidcraft/sketch-analysis-bench/1", "command": "sketch.auto_constrain", + "params": {"dimensions": false}, "size": size, "seed": 99, "repeats": repeats, "warmup": warmup, + "median_ns": percentile(×, 50), "p95_ns": percentile(×, 95), + "final_sketch": reference, "samples": samples, + }); + let mut writer: Box = match out { + Some(path) => Box::new(std::io::BufWriter::new(std::fs::File::create(path)?)), + None => Box::new(std::io::stdout().lock()), + }; + serde_json::to_writer_pretty(&mut writer, &output)?; + writeln!(writer)?; + writer.flush()?; + Ok(()) +} diff --git a/crates/engine/examples/sketch_drag_bench.rs b/crates/engine/examples/sketch_drag_bench.rs new file mode 100644 index 000000000..df15c6975 --- /dev/null +++ b/crates/engine/examples/sketch_drag_bench.rs @@ -0,0 +1,116 @@ +//! Engine time for live frames and release, independent of rendering/input scheduling. +use std::{error::Error, io::Write, path::PathBuf, sync::Arc, time::Instant}; + +use serde_json::{Value, json}; +use solidcraft_engine::Session; +use solidcraft_geom::Vec2; +use solidcraft_sketch::{Analysis, ConstraintKind, Hold, Sketch, profiling::capture, solve_with}; + +type Result = std::result::Result>; + +fn prepare(size: usize, pinned: bool, cold: bool) -> Result { + let mut s = Session::default(); + s.execute("sketch.create", &json!({"plane": "XY"}))?; + let id = s.active_sketch.ok_or("missing sketch")?; + let mut sk = Sketch::new(); + let mut points = Vec::new(); + let mut seed = 99u64; + let mut jitter = || { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (seed >> 11) as f64 / (1u64 << 53) as f64 * 2.0 - 1.0 + }; + for y in 0..size { + for x in 0..size { + let p = sk.add_point(Vec2::new((x + 1) as f64 * 10.0 + jitter(), (y + 1) as f64 * 10.0 + jitter()), None)?; + points.push(p); + if pinned && x == 0 && y == 0 { + sk.add_constraint(ConstraintKind::Fix { p }, None)?; + } + for (other, horizontal) in [((x > 0).then(|| points.len() - 2), true), ((y > 0).then(|| points.len() - 1 - size), false)] { + if let Some(q) = other.and_then(|i| points.get(i)).copied() { + let l = sk.add_line_pts(q, p, None)?; + sk.add_constraint(if horizontal { ConstraintKind::Horizontal { l } } else { ConstraintKind::Vertical { l } }, None)?; + sk.add_constraint(ConstraintKind::Distance { p, q, value: 10.0 }, None)?; + } + } + } + } + if !solve_with(&mut sk, &Hold::default(), None, Analysis::StatusOnly, None).ok() { + return Err("grid preparation failed".into()); + } + *Arc::make_mut(&mut s.doc).sketch_mut(id)? = sk; + if cold { + s.model = Default::default(); + } else { + s.refresh(); + } + Ok(s) +} + +fn frame(s: &mut Session) -> Result { + let id = s.active_sketch.ok_or("missing sketch")?; + let sk = s.doc.sketch(id)?; + let p = sk.points.get(1).ok_or("missing point")?; + let params = json!({"entity": p.id, "from": [p.pos.x, p.pos.y], "to": [p.pos.x + 0.25, p.pos.y], "live": true}); + Ok(s.execute("sketch.drag", ¶ms)?) +} + +fn main() -> Result<()> { + let mut size = 14usize; + let mut repeats = 10usize; + let mut out: Option = None; + let mut args = std::env::args().skip(1); + while let Some(key) = args.next() { + let value = args.next().ok_or("missing option value")?; + match key.as_str() { + "--size" => size = value.parse()?, + "--repeats" => repeats = value.parse()?, + "--out" => out = Some(value.into()), + _ => return Err(format!("unknown option {key}").into()), + } + } + // The floating variant must stay within the solver's 400-variable redundancy cap so + // that this benchmark can require and compare nonempty published diagnostics. + if !(2..=14).contains(&size) || !(1..=100).contains(&repeats) { + return Err("size must be in 2..14 and repeats in 1..100".into()); + } + let mut cases = Vec::new(); + for (name, pinned, cold, release) in [ + ("live-floating", false, false, false), + ("live-pinned", true, false, false), + ("release-floating", false, false, true), + ("first-frame", false, true, false), + ] { + let mut samples = Vec::new(); + for i in 0..repeats + 2 { + let mut s = prepare(size, pinned, cold)?; + if release { + frame(&mut s)?; + } + let start = Instant::now(); + let (response, profile) = capture(|| if release { s.execute("sketch.drag_end", &json!({})).map_err(Into::into) } else { frame(&mut s) }); + let elapsed_ns = start.elapsed().as_nanos().min(u64::MAX as u128) as u64; + let response: Value = response?; + let id = s.active_sketch.ok_or("missing sketch")?; + let state = s.world_state(); + let report = &state.sketch(id).ok_or("missing published sketch")?.report; + if !report.ok() || report.redundant.is_empty() { + return Err(format!("{name}: missing full diagnostics: {report:?}; response {response}; counters {:?}", profile.counters).into()); + } + if i >= 2 { + samples + .push(json!({"elapsed_ns": elapsed_ns, "response": response, "profile": profile, "report": report, "sketch": s.doc.sketch(id)?})); + } + } + cases.push(json!({"case": name, "samples": samples})); + } + let output = json!({"schema": "solidcraft/sketch-drag-bench/1", "size": size, "seed": 99, "repeats": repeats, "warmup": 2, "cases": cases}); + let mut writer: Box = match out { + Some(path) => Box::new(std::io::BufWriter::new(std::fs::File::create(path)?)), + None => Box::new(std::io::stdout().lock()), + }; + serde_json::to_writer_pretty(&mut writer, &output)?; + writeln!(writer)?; + writer.flush()?; + Ok(()) +} diff --git a/crates/engine/examples/sketch_target_bench.rs b/crates/engine/examples/sketch_target_bench.rs new file mode 100644 index 000000000..b07f66126 --- /dev/null +++ b/crates/engine/examples/sketch_target_bench.rs @@ -0,0 +1,53 @@ +//! Matched command timings and analytic cursor-distance error for the reported four-bar. +#[path = "../tests/support/four_bar.rs"] +mod four_bar; +use four_bar::Result; +use serde_json::json; +use solidcraft_geom::Vec2; +use solidcraft_sketch::profiling::capture; +use std::{io::Write, time::Instant}; + +fn main() -> Result<()> { + let mut args = std::env::args().skip(1); + let path = args.next().ok_or("usage: sketch_target_bench OUTPUT.json [REPEATS]")?; + let repeats: usize = args.next().map(|v| v.parse()).transpose()?.unwrap_or(10); + if !(1..=100).contains(&repeats) { + return Err("repeats must be in 1..100".into()); + } + let mut cases = Vec::new(); + for target in [Vec2::new(-10.0, 8.0), Vec2::new(-10.0, -8.0), Vec2::new(20.0, 20.0), Vec2::new(20.0, 0.0), Vec2::new(-8.0, 6.0)] { + for events in [1, 16] { + let mut samples = Vec::new(); + for i in 0..repeats + 2 { + let mut s = four_bar::session()?; + let from = four_bar::point(&s, "crank.end")?; + let side = four_bar::branch(&s)?; + let start = Instant::now(); + let (result, profile) = capture(|| -> Result<()> { + for k in 1..=events { + let q = from + (target - from) * (k as f64 / events as f64); + let at = four_bar::point(&s, "crank.end")?; + s.execute("sketch.drag", &json!({"entity":"crank.end","from":[at.x,at.y],"to":[q.x,q.y],"live":true}))?; + } + Ok(()) + }); + let elapsed_ns = start.elapsed().as_nanos().min(u64::MAX as u128) as u64; + result?; + let actual = four_bar::point(&s, "crank.end")?; + let error = four_bar::length_error(&s)?; + if error > 1e-6 || four_bar::branch(&s)? != side { + return Err("length or branch violation".into()); + } + if i >= 2 { + samples.push(json!({"elapsed_ns":elapsed_ns,"actual":[actual.x,actual.y],"length_error":error,"cursor_distance":actual.dist(target),"nearest_error":actual.dist(target*(10.0/target.len())),"profile":profile})); + } + } + cases.push(json!({"target":[target.x,target.y],"events":events,"samples":samples})); + } + } + let mut out = std::io::BufWriter::new(std::fs::File::create(path)?); + serde_json::to_writer_pretty(&mut out, &json!({"schema":"solidcraft/sketch-target-bench/1","repeats":repeats,"warmup":2,"cases":cases}))?; + writeln!(out)?; + out.flush()?; + Ok(()) +} diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rs index a906c9807..bbee1a0e5 100644 --- a/crates/engine/src/cmd/sketch.rs +++ b/crates/engine/src/cmd/sketch.rs @@ -230,7 +230,7 @@ pub(super) fn edit( f: impl FnOnce(&mut Sketch, &mut solidcraft_doc::Document) -> Result, ) -> Result<(T, Value)> { let id = target_sketch(s, p, cmd)?; - let (out, rep) = edit_solved(s, id, strict, |sk, doc| Ok((f(sk, doc)?, Left::Unsolved)))?; + let (out, rep) = edit_solved(s, id, strict, Analysis::Freedom, |sk, doc| Ok((f(sk, doc)?, Left::Unsolved)))?; Ok((out, rep.map(|rep| report_json(&rep)).unwrap_or(Value::Null))) } @@ -263,10 +263,13 @@ impl Left { /// `edit` of sketch `id` for a step that may solve the sketch itself: when it returns /// [`Left::Solved`] (and offsets need not be recomputed) the sketch is not solved again and the /// report is `None`. +/// `analysis` must be `Full` when the report is published without a model evaluation (a live +/// drag); command JSON only consumes freedom, and its later model evaluation publishes a full report. pub(super) fn edit_solved( s: &mut Session, id: u64, strict: bool, + analysis: Analysis, f: impl FnOnce(&mut Sketch, &mut solidcraft_doc::Document) -> Result<(T, Left)>, ) -> Result<(T, Option)> { let mut doc = (*s.doc).clone(); @@ -287,10 +290,11 @@ pub(super) fn edit_solved( doc.apply_dimension_values(&doc.param_values().0, &mut sk)?; sk.refresh_offsets()?; let unsolved = sk.clone(); - let mut rep = counted_solve(&mut sk, &Hold::default(), Some(&reference), Analysis::Full, None); + let first_analysis = if offsets { Analysis::StatusOnly } else { analysis }; + let mut rep = counted_solve(&mut sk, &Hold::default(), Some(&reference), first_analysis, None); if offsets { sk.refresh_offsets()?; - rep = counted_solve(&mut sk, &Hold::default(), Some(&reference), Analysis::Full, None); + rep = counted_solve(&mut sk, &Hold::default(), Some(&reference), analysis, None); } Some(settle(strict, rep, &mut sk, unsolved)?) } @@ -300,8 +304,8 @@ pub(super) fn edit_solved( sk.refresh_offsets()?; let unsolved = sk.clone(); #[cfg(test)] - solve_counts::record(Analysis::Full); - let rep = doc.solve_sketch(&vals, &mut sk, &stored, None)?; + solve_counts::record(analysis); + let rep = doc.solve_sketch_with_analysis(&vals, &mut sk, &stored, None, analysis)?; Some(settle(strict, rep, &mut sk, unsolved)?) } }; @@ -343,7 +347,7 @@ pub(super) fn counted_solve( pub(super) fn solve_current(sk: &mut Sketch, doc: &solidcraft_doc::Document) -> Result { let stored = sk.driving_values(); let (values, _) = doc.param_values(); - Ok(doc.solve_sketch(&values, sk, &stored, None)?) + Ok(doc.solve_sketch_with_analysis(&values, sk, &stored, None, Analysis::Freedom)?) } /// Solves run on this thread by [`counted_solve`] and the edit's own solve: (all of them, those @@ -361,7 +365,7 @@ pub(super) mod solve_counts { pub fn record(analysis: Analysis) { COUNTS.with(|c| { let (n, full) = c.get(); - c.set((n + 1, full + usize::from(analysis == Analysis::Full))); + c.set((n + 1, full + usize::from(analysis != Analysis::StatusOnly))); }); } @@ -1515,7 +1519,7 @@ pub(super) fn apply_in_order(sk: &mut Sketch, rep: &SolveReport, first: &[Ent], driven: false, text: None, })); - let ok = solve_with(&mut trial, &h, None, Analysis::Full, None).ok(); + let ok = solve_with(&mut trial, &h, None, Analysis::StatusOnly, None).ok(); trial.constraints.retain(|c| c.id != TEMP); if ok && !collapsed(sk, &trial) { *sk = trial; @@ -1525,7 +1529,7 @@ pub(super) fn apply_in_order(sk: &mut Sketch, rep: &SolveReport, first: &[Ent], // Both could move but holding either one leads nowhere: solve as usual. if !first_locked && !second_locked { let mut trial = sk.clone(); - if solve(&mut trial).ok() { + if solve_with(&mut trial, &Hold::default(), None, Analysis::StatusOnly, None).ok() { *sk = trial; return Ok(()); } @@ -1535,7 +1539,7 @@ pub(super) fn apply_in_order(sk: &mut Sketch, rep: &SolveReport, first: &[Ent], /// Degrees of freedom of a sketch as it is. pub(super) fn dof_now(sk: &Sketch) -> usize { - solve(&mut sk.clone()).dof + solve_with(&mut sk.clone(), &Hold::default(), None, Analysis::Freedom, None).dof } /// A constraint just added that removes no degree of freedom (`before` → the edit's `info`) is @@ -2406,7 +2410,7 @@ fn move_point(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.move_point"; let to = req_vec2(cmd, p, "to")?; let id = target_sketch(s, p, cmd)?; - let (_, rep) = edit_solved(s, id, false, |sk, _| { + let (_, rep) = edit_solved(s, id, false, Analysis::Freedom, |sk, _| { let q = point_ref(sk, p.get("point"), cmd, "point")?; Ok(((), drag_entity(sk, Ent::Point(q), &[], to, to, false).1.solve_again())) })?; @@ -2432,7 +2436,8 @@ fn drag_frame(s: &mut Session, p: &Value, live: bool) -> Result<(Value, Option (Vec, usize) { +fn run_auto(sk: &mut Sketch, doc: &mut solidcraft_doc::Document, p: &Value, datum: usize, mut dof: usize) -> (Vec, usize) { use ConstraintKind::*; let tol = num(p, "tolerance").filter(|t| *t > 0.0).unwrap_or(0.01); let atol = num(p, "angle_tolerance").filter(|t| *t > 0.0).unwrap_or(1.0).to_radians(); let dims = crate::params::bool_(p, "dimensions").unwrap_or(true); let n0 = sk.constraints.len(); - let mut dof = dof_now(sk); let mut trials = 0; let mut attempt = |sk: &mut Sketch, doc: &mut solidcraft_doc::Document, k: ConstraintKind, dim: bool, dof: &mut usize| { if *dof == 0 || trials >= MAX_TRIALS { @@ -258,7 +257,9 @@ fn auto(s: &mut Session, p: &Value, cmd: &str) -> Result { if !rep.keeps_orientation() { return Err(bad(cmd, rep.failure(|f| format!("the sketch constraints conflict ({f})")))); } - Ok(run_auto(sk, doc, p, datum)) + // This is the exact state just solved for the current parameter values. Trials update + // its freedom whenever they change constraints; no separate initial solve is needed. + Ok(run_auto(sk, doc, p, datum, rep.dof)) })?; Ok(json!({"added": added, "dof": dof, "sketch": info})) } diff --git a/crates/engine/src/cmd/sketch_constraints_tests.rs b/crates/engine/src/cmd/sketch_constraints_tests.rs index c68343ff9..56063ccdc 100644 --- a/crates/engine/src/cmd/sketch_constraints_tests.rs +++ b/crates/engine/src/cmd/sketch_constraints_tests.rs @@ -155,6 +155,35 @@ fn auto_constrain_fully_constrains_a_rough_sketch() { assert!(r["added"].as_array().unwrap().len() >= 3, "{r}"); } +#[test] +fn internal_freedom_queries_skip_redundancy_and_keep_constraint_acceptance() { + use solidcraft_sketch::{ConstraintKind, Sketch, profiling::capture}; + + let mut sk = Sketch::new(); + let q = sk.add_point(Vec2::new(10.0, 2.0), None).unwrap(); + let k = ConstraintKind::Distance { p: 0, q, value: 10.0 }; + sk.add_constraint(k.clone(), None).unwrap(); + let redundant = sk.add_constraint(k.clone(), None).unwrap(); + let (dof, profile) = capture(|| super::dof_now(&sk)); + assert_eq!(dof, 1); + assert_eq!(profile.counters.redundancy_checks, 0); + + let mut doc = solidcraft_doc::Document::default(); + let before = sk.clone(); + let (rejected, profile) = capture(|| super::try_add(&mut sk, &mut doc, k, dof, false)); + assert_eq!(rejected, None, "a duplicate must not be accepted as a DOF reduction"); + assert_eq!(sk, before); + assert_eq!(profile.counters.redundancy_checks, 0); + + let (accepted, profile) = capture(|| super::try_add(&mut sk, &mut doc, ConstraintKind::DistanceX { p: 0, q, value: 6.0 }, dof, false)); + assert_eq!(accepted, Some(0)); + assert_eq!(profile.counters.redundancy_checks, 0); + let full = solidcraft_sketch::solve(&mut sk); + assert!(full.ok()); + assert_eq!(full.dof, 0); + assert!(full.redundant.contains(&redundant), "the final full report must retain diagnostics"); +} + #[test] fn drawing_infers_tangent_and_perpendicular() { let mut s = new_sketch(); diff --git a/crates/engine/src/cmd/sketch_create.rs b/crates/engine/src/cmd/sketch_create.rs index 0a080a7f2..dc5423593 100644 --- a/crates/engine/src/cmd/sketch_create.rs +++ b/crates/engine/src/cmd/sketch_create.rs @@ -367,7 +367,9 @@ fn edit_text(s: &mut Session, p: &Value) -> Result { fn edit_text_live(s: &mut Session, p: &Value) -> Result<(Value, Option)> { let cmd = "sketch.edit_text"; let id = s.active_sketch.ok_or_else(|| bad(cmd, "no sketch is being edited"))?; - let (out, report) = super::sketch::edit_solved(s, id, false, |sk, doc| Ok((apply_text_edits(sk, doc, p)?, super::sketch::Left::Unsolved)))?; + let (out, report) = super::sketch::edit_solved(s, id, false, solidcraft_sketch::Analysis::Full, |sk, doc| { + Ok((apply_text_edits(sk, doc, p)?, super::sketch::Left::Unsolved)) + })?; Ok((out, report.map(|report| crate::LiveEdit { sketch: id, report }))) } diff --git a/crates/engine/src/cmd/sketch_modify.rs b/crates/engine/src/cmd/sketch_modify.rs index 2b57abd26..1561ed31f 100644 --- a/crates/engine/src/cmd/sketch_modify.rs +++ b/crates/engine/src/cmd/sketch_modify.rs @@ -527,7 +527,7 @@ fn extend(s: &mut Session, p: &Value) -> Result { pin(sk, end, oi)?; let before = sk.points.iter().map(|p| p.pos).collect::>(); let hold = solidcraft_sketch::Hold { points: (0..sk.points.len()).filter(|i| *i != end).collect(), radii: (0..sk.curves.len()).collect() }; - if !solidcraft_sketch::solve_with(sk, &hold, None, solidcraft_sketch::Analysis::Full, None).ok() + if !solidcraft_sketch::solve_with(sk, &hold, None, solidcraft_sketch::Analysis::StatusOnly, None).ok() || sk.point(end).is_none_or(|point| point.dist(q) > TOL) || sk.points.iter().enumerate().any(|(i, point)| i != end && point.pos.dist(before[i]) > TOL) { diff --git a/crates/engine/tests/sketch_analysis.rs b/crates/engine/tests/sketch_analysis.rs new file mode 100644 index 000000000..337062c64 --- /dev/null +++ b/crates/engine/tests/sketch_analysis.rs @@ -0,0 +1,174 @@ +//! Command-level diagnostic work, including the report ultimately published to the model. + +use std::sync::Arc; + +use serde_json::json; +use solidcraft_engine::Session; +use solidcraft_geom::Vec2; +use solidcraft_sketch::{Analysis, ConstraintKind, Sketch, profiling::capture}; + +fn session(horizontal: bool) -> (Session, u64, String) { + let mut s = Session::default(); + s.execute("sketch.create", &json!({"plane": "XY"})).unwrap(); + let id = s.active_sketch.unwrap(); + let mut sk = Sketch::new(); + let q = sk.add_point(Vec2::new(10.0, 0.0), None).unwrap(); + let l = sk.add_line_pts(0, q, None).unwrap(); + let k = ConstraintKind::Distance { p: 0, q, value: 10.0 }; + sk.add_constraint(k.clone(), None).unwrap(); + let redundant = sk.add_constraint(k, None).unwrap(); + if horizontal { + sk.add_constraint(ConstraintKind::Horizontal { l }, None).unwrap(); + } + *Arc::make_mut(&mut s.doc).sketch_mut(id).unwrap() = sk; + (s, id, redundant) +} + +#[test] +fn auto_constrain_computes_redundancy_once_and_publishes_full_diagnostics() { + let (mut s, id, redundant) = session(true); + let before = s.doc.sketch(id).unwrap().clone(); + let (response, profile) = capture(|| s.execute("sketch.auto_constrain", &json!({"dimensions": false}))); + let response = response.unwrap(); + assert_eq!(response["added"], json!([])); + assert_eq!(response["sketch"], json!({"solved": true, "dof": 0})); + assert_eq!(*s.doc.sketch(id).unwrap(), before); + let state = s.model.state(); + let shown = state.sketch(id).unwrap(); + assert!(shown.report.ok()); + assert_eq!(shown.report.dof, 0); + assert!(shown.report.redundant.contains(&redundant)); + assert!(shown.report.point_determined.iter().all(|d| *d)); + assert_eq!(profile.counters.redundancy_checks, 1, "only the published model report needs redundant IDs"); + assert_eq!(profile.counters.solve_calls, 3, "reuse the preparation solve's DOF"); +} + +#[test] +fn auto_constrain_reuses_real_freedom_and_keeps_accepted_trial_diagnostics() { + let (mut s, id, redundant) = session(false); + let (response, profile) = capture(|| s.execute("sketch.auto_constrain", &json!({"dimensions": false}))); + let response = response.unwrap(); + assert_eq!(response["added"].as_array().unwrap().len(), 1, "one angular degree of freedom must be removed"); + assert_eq!(response["dof"], 0); + assert_eq!(response["sketch"], json!({"solved": true, "dof": 0})); + let state = s.model.state(); + let shown = state.sketch(id).unwrap(); + assert!(shown.report.redundant.contains(&redundant)); + assert!(shown.report.ok()); + assert_eq!(profile.counters.redundancy_checks, 1); +} + +#[test] +fn a_live_drag_keeps_full_diagnostics_when_it_publishes_without_evaluation() { + for horizontal in [false, true] { + let (mut s, id, redundant) = session(horizontal); + // The fixture edits the document directly. Establish a valid full report before + // testing its reuse; a no-op solve is not required to rebuild an unchanged model. + s.model.evaluate(&s.doc); + s.execute("sketch.solve", &json!({})).unwrap(); + assert!( + s.model.state().sketch(id).unwrap().report.redundant.contains(&redundant), + "the pre-drag model must contain the fixture's full diagnostics" + ); + let endpoint = s.doc.sketch(id).unwrap().points[1].id.clone(); + s.execute("sketch.drag", &json!({"entity": endpoint, "from": [10, 0], "to": [12, 8], "live": true})).unwrap(); + let state = s.model.state(); + let shown = state.sketch(id).unwrap(); + assert!(shown.report.redundant.contains(&redundant)); + assert_eq!(shown.report.dof, usize::from(!horizontal)); + if !horizontal { + assert!(s.doc.sketch(id).unwrap().points[1].pos.dist(Vec2::new(10.0, 0.0)) > 1.0, "exercise publication of changed geometry"); + } + } +} + +#[test] +fn a_live_text_edit_keeps_full_diagnostics_when_it_publishes_without_evaluation() { + let (mut s, id, redundant) = session(false); + let text = s.execute("sketch.text", &json!({"text": "T", "at": [30, 20], "height": 5})).unwrap(); + assert!(s.model.state().sketch(id).unwrap().report.redundant.contains(&redundant)); + s.execute("sketch.edit_text", &json!({"link": text["link"], "height": 8, "live": true})).unwrap(); + let state = s.model.state(); + let shown = state.sketch(id).unwrap(); + assert!(shown.report.ok()); + assert!(shown.report.redundant.contains(&redundant), "live publication must retain redundant IDs for unrelated geometry"); +} + +#[test] +fn a_live_text_batch_keeps_full_diagnostics_when_it_publishes_without_evaluation() { + let (mut s, id, redundant) = session(false); + let a = s.execute("sketch.text", &json!({"text": "T", "at": [30, 20], "height": 5})).unwrap(); + let b = s.execute("sketch.text", &json!({"text": "I", "at": [50, 20], "height": 5})).unwrap(); + let out = + s.execute("sketch.edit_text", &json!({"edits": [{"link": a["link"], "height": 8}, {"link": b["link"], "height": 9}], "live": true})).unwrap(); + assert_eq!(out["edits"][0]["link"], a["link"]); + assert_eq!(out["edits"][1]["link"], b["link"]); + let state = s.model.state(); + let shown = state.sketch(id).unwrap(); + let expected = solidcraft_sketch::solve(&mut s.doc.sketch(id).unwrap().clone()); + assert!(shown.report.ok()); + assert!(shown.report.redundant.contains(&redundant)); + assert_eq!(serde_json::to_value(&shown.report).unwrap(), serde_json::to_value(expected).unwrap()); +} + +fn compare_document_levels(doc: &solidcraft_doc::Document, id: u64, expected_ok: bool) { + let input = doc.sketch(id).unwrap(); + let stored = input.driving_values(); + let values = doc.param_values().0; + let mut full_geometry = input.clone(); + let (full, profile) = capture(|| doc.solve_sketch(&values, &mut full_geometry, &stored, Some(input)).unwrap()); + assert_eq!(full.ok(), expected_ok); + assert!(profile.counters.redundancy_checks > 0, "the default document API retains full diagnostics"); + if expected_ok { + let (_, last_only) = capture(|| solidcraft_sketch::solve(&mut full_geometry.clone())); + assert_eq!(profile.counters.redundancy_checks, last_only.counters.redundancy_checks, "only the last offset solve needs redundant IDs"); + } + for analysis in [Analysis::Freedom, Analysis::StatusOnly] { + let mut geometry = input.clone(); + let (report, profile) = capture(|| doc.solve_sketch_with_analysis(&values, &mut geometry, &stored, Some(input), analysis).unwrap()); + assert_eq!(geometry, full_geometry, "parameter application, offset refresh and rollback must match"); + assert_eq!(profile.counters.redundancy_checks, 0, "offset retries must retain the requested level"); + let mut expected = full.clone(); + expected.redundant.clear(); + if analysis == Analysis::StatusOnly { + expected.dof = 0; + expected.point_determined.clear(); + expected.curve_determined.clear(); + } + assert_eq!(serde_json::to_value(report).unwrap(), serde_json::to_value(expected).unwrap()); + } +} + +#[test] +fn document_analysis_levels_survive_parameter_application_and_offset_retries() { + for freeform in [false, true] { + let (mut s, id, _) = session(false); + let curve = if freeform { + s.execute("sketch.ellipse", &json!({"center": [30, 30], "major": [40, 30], "minor_radius": 5})).unwrap()["curves"][0] + .as_str() + .unwrap() + .to_owned() + } else { + s.doc.sketch(id).unwrap().curves[0].id.clone() + }; + s.execute("sketch.offset", &json!({"curves": [curve], "distance": -1, "chain": false})).unwrap(); + let sk = s.doc.sketch(id).unwrap(); + assert!(if freeform { !sk.freeform_offsets.is_empty() } else { !sk.offsets.is_empty() }); + compare_document_levels(&s.doc, id, true); + + // Both original distances must follow the edited parameter before analyzing freedom. + let doc = Arc::make_mut(&mut s.doc); + let param = doc.new_model_param("20 mm", "mm"); + for c in &mut doc.sketch_mut(id).unwrap().constraints { + if matches!(c.kind, ConstraintKind::Distance { .. }) { + c.param = Some(param.clone()); + } + } + compare_document_levels(doc, id, true); + // One conflicting dimension makes the first solve fail, exercising the offset retry. + let conflict = doc.new_model_param("11 mm", "mm"); + doc.sketch_mut(id).unwrap().constraints.iter_mut().find(|c| matches!(c.kind, ConstraintKind::Distance { .. })).unwrap().param = + Some(conflict); + compare_document_levels(doc, id, false); + } +} diff --git a/crates/sketch/Cargo.toml b/crates/sketch/Cargo.toml index 76fa295c2..eba000b5a 100644 --- a/crates/sketch/Cargo.toml +++ b/crates/sketch/Cargo.toml @@ -8,6 +8,14 @@ license.workspace = true [lints] workspace = true +[features] +# Opt-in developer instrumentation; normal builds contain no collection or clocks. +solver-profiling = [] + +[[example]] +name = "solve_profile" +required-features = ["solver-profiling"] + [dependencies] solidcraft-geom = { workspace = true } serde = { workspace = true } diff --git a/crates/sketch/examples/solve_profile.rs b/crates/sketch/examples/solve_profile.rs new file mode 100644 index 000000000..f41e12af6 --- /dev/null +++ b/crates/sketch/examples/solve_profile.rs @@ -0,0 +1,306 @@ +//! Reproducible numerical traces and paired wall-time samples. Use `--help` for cases and bounds. + +use std::{error::Error, io::Write, path::PathBuf, time::Instant}; + +use serde::Serialize; +use solidcraft_geom::Vec2; +use solidcraft_sketch::{ + Analysis, ConstraintKind, DrivingValues, Hold, Sketch, SolveReport, + profiling::{Counters, SolveProfile, Timings, capture}, + solve_after_value_edit, solve_with, +}; + +type Result = std::result::Result>; +const CASES: [&str; 6] = ["distance-zero", "distance-offset", "x-zero", "linkage", "linkage-edit", "grid"]; + +struct Options { + case: String, + repeats: usize, + warmup: usize, + size: usize, + seed: u64, + scale: f64, + offset: f64, + analysis: Analysis, + cpu_loops: Option, + out: Option, +} + +impl Options { + fn read() -> Result> { + let mut opt = Self { + case: "all".into(), + repeats: 5, + warmup: 1, + size: 10, + seed: 99, + scale: 1.0, + offset: 0.0, + analysis: Analysis::Full, + cpu_loops: None, + out: None, + }; + let mut args = std::env::args().skip(1); + while let Some(key) = args.next() { + if key == "--help" { + println!( + "solve_profile [--case all|{}] [--repeats 1..100] [--warmup 0..10] [--size 2..30] [--seed U64] [--scale 1e-6..1e6] [--offset MM] [--analysis full|freedom|status] [--cpu-loops 1..1000000] [--out FILE]", + CASES.join("|") + ); + return Ok(None); + } + let value = args.next().ok_or_else(|| format!("missing value for {key}"))?; + match key.as_str() { + "--case" => opt.case = value, + "--repeats" => opt.repeats = value.parse()?, + "--warmup" => opt.warmup = value.parse()?, + "--size" => opt.size = value.parse()?, + "--seed" => opt.seed = value.parse()?, + "--cpu-loops" => opt.cpu_loops = Some(value.parse()?), + "--scale" => opt.scale = value.parse()?, + "--offset" => opt.offset = value.parse()?, + "--analysis" => match value.as_str() { + "full" => opt.analysis = Analysis::Full, + "freedom" => opt.analysis = Analysis::Freedom, + "status" => opt.analysis = Analysis::StatusOnly, + _ => return Err("analysis must be full, freedom or status".into()), + }, + "--out" => opt.out = Some(value.into()), + _ => return Err(format!("unknown option {key}").into()), + } + } + if !(1..=100).contains(&opt.repeats) || opt.warmup > 10 || !(2..=30).contains(&opt.size) { + return Err("repeats, warmup or size outside supported range (see --help)".into()); + } + if opt.cpu_loops.is_some_and(|n| !(1..=1_000_000).contains(&n)) { + return Err("cpu-loops must be in 1..1000000".into()); + } + if !opt.scale.is_finite() || !(1e-6..=1e6).contains(&opt.scale) || !opt.offset.is_finite() || opt.offset.abs() > 1e8 { + return Err("scale must be finite in 1e-6..1e6 and offset finite within +/-1e8 mm".into()); + } + if opt.case != "all" && !CASES.contains(&opt.case.as_str()) { + return Err(format!("unknown case {}", opt.case).into()); + } + if opt.analysis != Analysis::Full && (opt.case == "all" || opt.case == "linkage-edit") { + return Err("linkage-edit uses full analysis; select another --case for reduced analysis".into()); + } + Ok(Some(opt)) + } + + fn at(&self, x: f64, y: f64) -> Vec2 { + Vec2::new(self.offset + x * self.scale, self.offset + y * self.scale) + } +} + +struct Lcg(u64); +impl Lcg { + fn next(&mut self) -> f64 { + self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (self.0 >> 11) as f64 / (1u64 << 53) as f64 * 2.0 - 1.0 + } +} + +struct Case { + sketch: Sketch, + old: Option, +} + +fn make_case(name: &str, opt: &Options) -> Result { + let mut sk = Sketch::new(); + let mut old = None; + let mut rnd = Lcg(opt.seed); + if name == "grid" { + let mut points = Vec::new(); + for y in 0..opt.size { + for x in 0..opt.size { + let p = sk.add_point(opt.at(x as f64 * 10.0 + rnd.next(), y as f64 * 10.0 + rnd.next()), None)?; + points.push(p); + if x == 0 && y == 0 { + sk.add_constraint(ConstraintKind::Fix { p }, None)?; + } + for (other, horizontal) in [((x > 0).then(|| points.len() - 2), true), ((y > 0).then(|| points.len() - 1 - opt.size), false)] { + if let Some(q) = other.and_then(|i| points.get(i)).copied() { + let l = sk.add_line_pts(q, p, None)?; + sk.add_constraint(if horizontal { ConstraintKind::Horizontal { l } } else { ConstraintKind::Vertical { l } }, None)?; + sk.add_constraint(ConstraintKind::Distance { p, q, value: 10.0 * opt.scale }, None)?; + } + } + } + } + } else if name.starts_with("linkage") { + let truth = [(0.0, 0.0), (40.0, 0.0), (18.0, 30.0), (8.0, 55.0), (52.0, 48.0), (30.0, 80.0)]; + let mut ids = Vec::new(); + for (i, (x, y)) in truth.iter().copied().enumerate() { + let jitter = if i == 0 { (0.0, 0.0) } else { (rnd.next() * 2.0, rnd.next() * 2.0) }; + ids.push(sk.add_point(opt.at(x + jitter.0, y + jitter.1), None)?); + } + let p = *ids.first().ok_or("missing base point")?; + let q = *ids.get(1).ok_or("missing base endpoint")?; + sk.add_constraint(ConstraintKind::Fix { p }, None)?; + let l = sk.add_line_pts(p, q, None)?; + sk.add_constraint(ConstraintKind::Horizontal { l }, None)?; + for (a, b) in [(0, 1), (1, 2), (2, 0), (3, 4), (4, 5), (5, 3), (0, 3), (1, 4), (2, 5)] { + let (ax, ay) = *truth.get(a).ok_or("missing endpoint")?; + let (bx, by) = *truth.get(b).ok_or("missing endpoint")?; + let p = *ids.get(a).ok_or("missing point")?; + let q = *ids.get(b).ok_or("missing point")?; + sk.add_constraint(ConstraintKind::Distance { p, q, value: (ax - bx).hypot(ay - by) * opt.scale }, None)?; + } + if name == "linkage-edit" { + let report = solve_with(&mut sk, &Hold::default(), None, Analysis::Full, None); + if !report.ok() { + return Err("could not prepare the solved linkage for the dimension edit".into()); + } + old = Some(sk.driving_values()); + for c in &mut sk.constraints { + if let Some(value) = c.kind.value() { + c.kind.set_value(value * (1.0 + rnd.next() * 0.15)); + } + } + } + } else { + let p = sk.add_point(opt.at(0.0, 0.0), None)?; + let q = sk.add_point(opt.at(if name == "distance-offset" { 1e-5 } else { 0.0 }, if name == "x-zero" { 5.0 } else { 0.0 }), None)?; + sk.add_constraint(ConstraintKind::Fix { p }, None)?; + let k = if name == "x-zero" { + ConstraintKind::DistanceX { p, q, value: 10.0 * opt.scale } + } else { + ConstraintKind::Distance { p, q, value: 10.0 * opt.scale } + }; + sk.add_constraint(k, None)?; + } + Ok(Case { sketch: sk, old }) +} + +fn solve(case: &Case, sk: &mut Sketch, opt: &Options) -> SolveReport { + match &case.old { + Some(old) => solve_after_value_edit(sk, old), + None => solve_with(sk, &Hold::default(), None, opt.analysis, None), + } +} + +#[derive(Serialize)] +struct Sample { + elapsed_ns: u64, + report: SolveReport, + counters: Counters, + timings_ns: Timings, +} + +#[derive(Serialize)] +struct CaseResult { + case: String, + points: usize, + constraints: usize, + profiled_median_ns: u64, + profiled_p95_ns: u64, + uncaptured_median_ns: u64, + uncaptured_p95_ns: u64, + uncaptured_samples_ns: Vec, + samples: Vec, + last_run_trace: SolveProfile, +} + +fn elapsed(t: Instant) -> u64 { + t.elapsed().as_nanos().min(u64::MAX as u128) as u64 +} + +fn percentile(samples: &[u64], percent: usize) -> u64 { + let mut sorted = samples.to_vec(); + sorted.sort_unstable(); + sorted.get((sorted.len() * percent).div_ceil(100).saturating_sub(1)).copied().unwrap_or(0) +} + +fn measure(name: &str, opt: &Options) -> Result { + let case = make_case(name, opt)?; + for _ in 0..opt.warmup { + solve(&case, &mut case.sketch.clone(), opt); + } + let mut samples = Vec::new(); + let mut baseline = Vec::new(); + let mut last = SolveProfile::default(); + for i in 0..opt.repeats { + // Clones and comparison are outside both timers; alternate ordering to reduce drift. + let mut measured = case.sketch.clone(); + let mut plain = case.sketch.clone(); + let unprofiled = |sk: &mut Sketch| { + let t = Instant::now(); + let r = solve(&case, sk, opt); + (r, elapsed(t)) + }; + let profiled = |sk: &mut Sketch| { + let t = Instant::now(); + let (r, p) = capture(|| solve(&case, sk, opt)); + (r, p, elapsed(t)) + }; + let ((a, plain_ns), (b, profile, ns)) = if i % 2 == 0 { + let a = unprofiled(&mut plain); + (a, profiled(&mut measured)) + } else { + let b = profiled(&mut measured); + (unprofiled(&mut plain), b) + }; + if measured != plain || serde_json::to_value(&a)? != serde_json::to_value(&b)? { + return Err(format!("instrumentation changed the result for {name}").into()); + } + baseline.push(plain_ns); + samples.push(Sample { elapsed_ns: ns, report: b, counters: profile.counters.clone(), timings_ns: profile.timings_ns.clone() }); + last = profile; + } + let times: Vec<_> = samples.iter().map(|s| s.elapsed_ns).collect(); + Ok(CaseResult { + case: name.into(), + points: case.sketch.points.len(), + constraints: case.sketch.constraints.len(), + profiled_median_ns: percentile(×, 50), + profiled_p95_ns: percentile(×, 95), + uncaptured_median_ns: percentile(&baseline, 50), + uncaptured_p95_ns: percentile(&baseline, 95), + uncaptured_samples_ns: baseline, + samples, + last_run_trace: last, + }) +} + +fn main() -> Result<()> { + let Some(opt) = Options::read()? else { return Ok(()) }; + let names = if opt.case == "all" { CASES.to_vec() } else { vec![opt.case.as_str()] }; + let cases: Vec = names + .iter() + .map(|name| { + if let Some(loops) = opt.cpu_loops { + // Sampling profilers see a sustained workload without trace allocation, rho + // calculation or JSON serialization in the hot loop. Each solve starts fresh. + let case = make_case(name, &opt)?; + for _ in 0..opt.warmup { + solve(&case, &mut case.sketch.clone(), &opt); + } + let (mut solved, mut failed) = (0usize, 0usize); + let t = Instant::now(); + for _ in 0..loops { + let report = std::hint::black_box(solve(&case, &mut case.sketch.clone(), &opt)); + if report.ok() { solved += 1 } else { failed += 1 } + } + Ok(serde_json::json!({ "case": name, "loops": loops, "solved": solved, "failed": failed, "elapsed_ns": elapsed(t) })) + } else { + Ok(serde_json::to_value(measure(name, &opt)?)?) + } + }) + .collect::>()?; + let output = serde_json::json!({ + "schema": "solidcraft/sketch-profile/1", "package_version": env!("CARGO_PKG_VERSION"), + "os": std::env::consts::OS, "arch": std::env::consts::ARCH, "debug_assertions": cfg!(debug_assertions), + "seed": opt.seed, "scale": opt.scale, "offset_mm": opt.offset, "size": opt.size, + "repeats": opt.repeats, "warmup": opt.warmup, "analysis": match opt.analysis { Analysis::Full => "full", Analysis::Freedom => "freedom", Analysis::StatusOnly => "status" }, + "mode": if opt.cpu_loops.is_some() { "cpu" } else { "trace" }, + "cases": cases, + }); + let mut writer: Box = match opt.out { + Some(path) => Box::new(std::io::BufWriter::new(std::fs::File::create(path)?)), + None => Box::new(std::io::stdout().lock()), + }; + serde_json::to_writer_pretty(&mut writer, &output)?; + writeln!(writer)?; + writer.flush()?; + Ok(()) +} diff --git a/crates/sketch/src/lib.rs b/crates/sketch/src/lib.rs index 80c32b996..aada4300c 100644 --- a/crates/sketch/src/lib.rs +++ b/crates/sketch/src/lib.rs @@ -32,6 +32,8 @@ mod offset_topology; mod pattern; mod periodic; mod profiles; +#[cfg(feature = "solver-profiling")] +pub mod profiling; mod shape; mod solver; mod text; @@ -62,6 +64,7 @@ pub use profiles::{ without_text_counters, }; pub use shape::{Shape, intersections}; +pub use solver::solve_after_edit_with_analysis; pub use solver::{ Analysis, CONSISTENT, DrivingValues, Hold, SolveReport, SolveStatus, constraint_residual, determined_by, measure_dimension, move_line_towards, move_point_towards, solve, solve_after_edit, solve_after_value_edit, solve_holding, solve_with, diff --git a/crates/sketch/src/profiling.rs b/crates/sketch/src/profiling.rs new file mode 100644 index 000000000..b8987b8ab --- /dev/null +++ b/crates/sketch/src/profiling.rs @@ -0,0 +1,406 @@ +//! Opt-in, per-thread solver measurements (`solver-profiling` feature). +//! +//! Wrap a public solve in [`capture`]. Collection never changes solver decisions. Timings are +//! inclusive (LM includes Jacobian and linear solve time), not additive. On wasm the counters +//! and trace work but clocks are disabled: `std::time::Instant` is unavailable there. + +use std::cell::Cell; + +use serde::Serialize; + +/// Bounds retained records, independently of how many solves the closure performs. +pub const MAX_RUNS: usize = 1024; +pub const MAX_TRIALS: usize = 10_000; + +/// Inclusive phase wall times in nanoseconds. Empty phases stay zero. +#[derive(Clone, Debug, Default, Serialize)] +pub struct Timings { + pub solve: u64, + pub seed: u64, + pub lm: u64, + pub residual_system: u64, + pub jacobian: u64, + pub normal_equations: u64, + pub linear_solve: u64, + pub analysis: u64, + /// Dependency classification, including its Jacobian and optional explanation. + pub redundancy: u64, + /// Jacobian construction within dependency classification (also included in `jacobian`). + pub redundancy_jacobian: u64, + /// Ordered, twice-reorthogonalized row classification, including row storage. + pub redundancy_classification: u64, + /// Optional `determined_by` explanation; ordinary solve reports do not request it. + pub redundancy_support: u64, +} + +/// Work counts include all actual calls in the captured closure, including retries and +/// continuation. A residual block evaluation is one constraint/implicit-curve block, not one row. +#[derive(Clone, Debug, Default, Serialize)] +pub struct Counters { + pub solve_calls: u64, + pub components: u64, + pub oversized_components: u64, + pub constructed_variables: u64, + pub residual_system_evaluations: u64, + pub residual_block_evaluations: u64, + pub jacobian_evaluations: u64, + pub lm_runs: u64, + pub outer_iterations: u64, + pub linear_solves: u64, + pub linear_failures: u64, + pub accepted_trials: u64, + pub rejected_trials: u64, + pub plain_start_retries: u64, + pub continuation_runs: u64, + pub redundancy_checks: u64, +} + +/// Why this invocation of LM returned. This is distinct from the final solve's acceptance +/// tolerance, and does not certify that inconsistent constraints have no solution. +#[derive(Clone, Copy, Debug, Serialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum StopReason { + ResidualTolerance, + NoImprovement, + IterationLimit, + /// The shared frame-work budget was exhausted after evaluating the initial residual. + WorkBudget, +} + +#[derive(Clone, Copy, Debug, Serialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum Decision { + Accepted, + Rejected, + LinearFailure, +} + +/// One LM call, identified even when the caller retries the same component. +#[derive(Debug, Serialize)] +pub struct LmRun { + pub id: u64, + pub variables: usize, + pub residual_rows: usize, + pub iteration_limit: usize, + pub initial_cost: Option, + pub final_max_residual: Option, + pub stop_reason: Option, +} + +/// One damping trial. `None` means unavailable or non-finite. Cost is sum(r²), without 1/2. +/// Predicted reduction uses the undamped residual model; rho is observational only. +#[derive(Debug, Serialize)] +pub struct Trial { + pub run: u64, + pub iteration: usize, + pub attempt: usize, + pub lambda: f64, + pub cost_before: Option, + pub cost_after: Option, + pub gradient_inf: Option, + pub step_norm: Option, + pub predicted_reduction: Option, + pub actual_reduction: Option, + pub rho: Option, + pub decision: Decision, +} + +#[derive(Debug, Default, Serialize)] +pub struct SolveProfile { + pub timings_available: bool, + pub timings_ns: Timings, + pub counters: Counters, + pub runs: Vec, + pub trials: Vec, + pub dropped_runs: u64, + pub dropped_trials: u64, +} + +thread_local! { + static ACTIVE: Cell> = const { Cell::new(None) }; +} + +struct CaptureGuard(Option); + +impl Drop for CaptureGuard { + fn drop(&mut self) { + ACTIVE.set(self.0.take()); + } +} + +/// Measure only the closure on the current thread. Nested captures are isolated and the outer +/// collector resumes afterwards. Unwinding restores the previous collector as well. +pub fn capture(f: impl FnOnce() -> T) -> (T, SolveProfile) { + let previous = ACTIVE.replace(Some(SolveProfile { timings_available: !cfg!(target_arch = "wasm32"), ..SolveProfile::default() })); + let guard = CaptureGuard(previous); + let result = f(); + let profile = ACTIVE.take().unwrap_or_default(); + drop(guard); + (result, profile) +} + +fn update(f: impl FnOnce(&mut SolveProfile)) { + if let Some(mut profile) = ACTIVE.take() { + f(&mut profile); + ACTIVE.set(Some(profile)); + } +} + +pub(crate) fn count(f: impl FnOnce(&mut Counters)) { + update(|p| f(&mut p.counters)); +} + +pub(crate) fn finite(x: f64) -> Option { + x.is_finite().then_some(x) +} + +pub(crate) fn record_trial( + run: u64, + iteration: usize, + attempt: usize, + lambda: f64, + before: f64, + after: Option, + gradient: &[f64], + j: &crate::linalg::Mat, + step: Option<&[f64]>, + decision: Decision, +) { + // Keep the extra matrix-vector product out of uncaptured timing baselines. + let active = ACTIVE.with(|cell| { + let p = cell.take(); + let active = p.is_some(); + cell.set(p); + active + }); + if !active { + return; + } + let predicted = step.map(|step| { + let gp: f64 = gradient.iter().zip(step).map(|(g, s)| g * s).sum(); + let jp2: f64 = (0..j.rows).map(|row| step.iter().enumerate().map(|(c, s)| j.get(row, c) * s).sum::().powi(2)).sum(); + -2.0 * gp - jp2 + }); + let actual = after.map(|after| before - after); + trial(Trial { + run, + iteration, + attempt, + lambda, + cost_before: finite(before), + cost_after: after.and_then(finite), + gradient_inf: finite(gradient.iter().fold(0.0_f64, |m, g| if g.is_finite() { m.max(g.abs()) } else { f64::INFINITY })), + step_norm: step.and_then(|s| finite(s.iter().fold(0.0_f64, |n, x| n.hypot(*x)))), + predicted_reduction: predicted.and_then(finite), + actual_reduction: actual.and_then(finite), + rho: predicted.filter(|p| *p > 0.0).zip(actual).and_then(|(p, a)| finite(a / p)), + decision, + }); +} + +pub(crate) enum Phase { + Solve, + Seed, + Lm, + ResidualSystem, + Jacobian, + NormalEquations, + LinearSolve, + Analysis, + Redundancy, + RedundancyJacobian, + RedundancyClassification, + RedundancySupport, +} + +pub(crate) struct Timer { + phase: Phase, + #[cfg(not(target_arch = "wasm32"))] + start: Option, +} + +pub(crate) fn timer(phase: Phase) -> Timer { + Timer { + phase, + #[cfg(not(target_arch = "wasm32"))] + start: ACTIVE.with(|cell| { + let profile = cell.take(); + let active = profile.is_some(); + cell.set(profile); + active.then(std::time::Instant::now) + }), + } +} + +impl Drop for Timer { + fn drop(&mut self) { + #[cfg(not(target_arch = "wasm32"))] + let ns = self.start.map(|s| s.elapsed().as_nanos().min(u64::MAX as u128) as u64).unwrap_or(0); + #[cfg(target_arch = "wasm32")] + let ns = 0; + update(|p| { + let slot = match self.phase { + Phase::Solve => &mut p.timings_ns.solve, + Phase::Seed => &mut p.timings_ns.seed, + Phase::Lm => &mut p.timings_ns.lm, + Phase::ResidualSystem => &mut p.timings_ns.residual_system, + Phase::Jacobian => &mut p.timings_ns.jacobian, + Phase::NormalEquations => &mut p.timings_ns.normal_equations, + Phase::LinearSolve => &mut p.timings_ns.linear_solve, + Phase::Analysis => &mut p.timings_ns.analysis, + Phase::Redundancy => &mut p.timings_ns.redundancy, + Phase::RedundancyJacobian => &mut p.timings_ns.redundancy_jacobian, + Phase::RedundancyClassification => &mut p.timings_ns.redundancy_classification, + Phase::RedundancySupport => &mut p.timings_ns.redundancy_support, + }; + *slot = slot.saturating_add(ns); + }); + } +} + +pub(crate) fn start_run(variables: usize, residual_rows: usize, iteration_limit: usize, cost: f64) -> u64 { + let mut id = 0; + update(|p| { + id = p.counters.lm_runs; + p.counters.lm_runs = p.counters.lm_runs.saturating_add(1); + if p.runs.len() < MAX_RUNS { + p.runs.push(LmRun { + id, + variables, + residual_rows, + iteration_limit, + initial_cost: finite(cost), + final_max_residual: None, + stop_reason: None, + }); + } else { + p.dropped_runs = p.dropped_runs.saturating_add(1); + } + }); + id +} + +pub(crate) fn finish_run(id: u64, reason: StopReason, residual: f64) { + update(|p| { + if let Some(run) = p.runs.iter_mut().find(|r| r.id == id) { + run.stop_reason = Some(reason); + run.final_max_residual = finite(residual); + } + }); +} + +pub(crate) fn trial(record: Trial) { + update(|p| { + let c = &mut p.counters; + c.linear_solves = c.linear_solves.saturating_add(1); + match record.decision { + Decision::Accepted => c.accepted_trials = c.accepted_trials.saturating_add(1), + Decision::Rejected => c.rejected_trials = c.rejected_trials.saturating_add(1), + Decision::LinearFailure => c.linear_failures = c.linear_failures.saturating_add(1), + } + if p.trials.len() < MAX_TRIALS { + p.trials.push(record); + } else { + p.dropped_trials = p.dropped_trials.saturating_add(1); + } + }); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{Analysis, ConstraintKind, Hold, Sketch, solve_with}; + use solidcraft_geom::Vec2; + + fn distance(x: f64) -> Sketch { + let mut sk = Sketch::new(); + let q = sk.add_point(Vec2::new(x, 0.0), None).unwrap(); + sk.add_constraint(ConstraintKind::Distance { p: 0, q, value: 10.0 }, None).unwrap(); + sk + } + + #[test] + fn measurements_preserve_geometry_and_explain_a_stalled_solve() { + for x in [0.0, 1e-5] { + let mut plain = distance(x); + let mut measured = plain.clone(); + let run = |sk: &mut Sketch| solve_with(sk, &Hold::default(), None, Analysis::StatusOnly, None); + let a = run(&mut plain); + let (b, profile) = crate::construct::switch::without_differential(|| capture(|| run(&mut measured))); + assert_eq!(serde_json::to_value(a).unwrap(), serde_json::to_value(b).unwrap()); + assert_eq!(plain, measured); + assert_eq!(profile.counters.solve_calls, 1); + assert_eq!(profile.counters.lm_runs, 1); + assert_eq!( + profile.counters.linear_solves, + profile.counters.accepted_trials + profile.counters.rejected_trials + profile.counters.linear_failures + ); + assert!(profile.counters.residual_block_evaluations > profile.counters.residual_system_evaluations); + let first = profile.trials.first().unwrap(); + if x == 0.0 { + assert_eq!(profile.runs[0].stop_reason, Some(StopReason::NoImprovement)); + assert_eq!(first.gradient_inf, Some(0.0)); + assert_eq!(first.step_norm, Some(0.0)); + assert_eq!(profile.counters.accepted_trials, 0); + } else { + assert_eq!(profile.runs[0].stop_reason, Some(StopReason::ResidualTolerance)); + assert!(profile.counters.accepted_trials > 0); + assert!((first.rho.unwrap() - 1.0).abs() < 1e-6, "the positive radial step is a linear residual"); + } + serde_json::to_string(&profile).unwrap(); + } + } + + #[test] + fn freedom_and_status_queries_do_not_run_dependency_analysis() { + let mut sk = distance(10.0); + sk.add_constraint(ConstraintKind::Distance { p: 0, q: 1, value: 10.0 }, None).unwrap(); + for analysis in [Analysis::Full, Analysis::Freedom, Analysis::StatusOnly] { + let (report, profile) = + crate::construct::switch::without_differential(|| capture(|| solve_with(&mut sk.clone(), &Hold::default(), None, analysis, None))); + assert!(report.ok()); + if analysis == Analysis::Full { + assert_eq!(profile.counters.redundancy_checks, 1); + assert_eq!(report.redundant.len(), 1); + } else { + assert_eq!(profile.counters.redundancy_checks, 0); + assert_eq!(profile.timings_ns.redundancy, 0); + assert!(report.redundant.is_empty()); + } + assert_eq!(report.dof, usize::from(analysis != Analysis::StatusOnly)); + } + } + + #[test] + fn nested_captures_and_unwinds_restore_the_outer_collector() { + let (_, outer) = capture(|| { + count(|c| c.solve_calls += 1); + let (_, inner) = capture(|| count(|c| c.solve_calls += 2)); + assert_eq!(inner.counters.solve_calls, 2); + let unwind = std::panic::catch_unwind(|| capture(|| panic!("test unwind"))); + assert!(unwind.is_err()); + count(|c| c.solve_calls += 3); + }); + assert_eq!(outer.counters.solve_calls, 4); + assert!(ACTIVE.take().is_none()); + } + + #[test] + fn run_storage_is_bounded_but_counts_are_not_truncated() { + let (_, p) = capture(|| { + for _ in 0..MAX_RUNS + 3 { + start_run(2, 1, 500, f64::INFINITY); + } + for _ in 0..MAX_TRIALS + 2 { + record_trial(0, 0, 0, 1.0, f64::INFINITY, None, &[], &crate::linalg::Mat::zeros(0, 0), None, Decision::LinearFailure); + } + }); + assert_eq!(p.runs.len(), MAX_RUNS); + assert_eq!(p.dropped_runs, 3); + assert_eq!(p.counters.lm_runs, (MAX_RUNS + 3) as u64); + assert_eq!(p.runs[0].initial_cost, None); + assert_eq!(p.trials.len(), MAX_TRIALS); + assert_eq!(p.dropped_trials, 2); + assert_eq!(p.counters.linear_failures, (MAX_TRIALS + 2) as u64); + } +} diff --git a/crates/sketch/src/redundancy.rs b/crates/sketch/src/redundancy.rs index 9af067718..f070de0d3 100644 --- a/crates/sketch/src/redundancy.rs +++ b/crates/sketch/src/redundancy.rs @@ -13,14 +13,20 @@ use super::{Block, Hold, Layout, State, block_residuals, build_blocks, columns, initial_x, layout, local_system, max_abs, points_on_curves}; use crate::linalg::{Mat, solve as lin_solve}; use crate::model::Sketch; +#[cfg(feature = "solver-profiling")] +use crate::profiling::{self, Phase}; use crate::union_find::{find, union}; +#[cfg(test)] +#[path = "redundancy_tests.rs"] +mod tests; + /// A row is dependent on the rows before it when what is left of it, once their directions are /// taken out, is below this share of its length (the rank analysis' pivot tolerance is 1e-7 on /// rows of a comparable scale). const DEPENDENT: f64 = 1e-6; /// Variables in one component past which its constraints are not checked for redundancy: the -/// check is dense, rows × rank × variables. +/// worst case is still dense, rows × rank × variables. pub(super) const MAX_REDUNDANCY_VARS: usize = 400; /// A constraint's residual (mm, or radians for angles) below which it holds. pub const CONSISTENT: f64 = 1e-6; @@ -37,6 +43,43 @@ fn dot(a: &[f64], b: &[f64]) -> f64 { a.iter().zip(b).map(|(x, y)| x * y).sum() } +/// Keep exact nonzeros in column order; never drop a small coefficient. Dense directions +/// retain the contiguous loop when indexing a sparse representation would cost more. +enum Direction { + Dense(Vec), + Sparse(Vec<(usize, f64)>), +} + +impl Direction { + fn new(w: &[f64], length: f64) -> Self { + let dense: Vec = w.iter().map(|v| v / length).collect(); + let nonzero = dense.iter().filter(|v| **v != 0.0).count(); + if nonzero < dense.len() / 2 { Self::Sparse(dense.into_iter().enumerate().filter(|(_, v)| *v != 0.0).collect()) } else { Self::Dense(dense) } + } + + fn remove_from(&self, w: &mut [f64]) { + match self { + Self::Dense(q) => { + let d = dot(q, w); + for (wk, qk) in w.iter_mut().zip(q) { + *wk -= d * qk; + } + } + Self::Sparse(q) => { + // Same reduction order as the dense dot product, omitting only exact zeros. + let d: f64 = q.iter().filter_map(|(i, v)| w.get(*i).map(|wk| v * wk)).sum(); + if d != 0.0 { + for &(i, v) in q { + if let Some(wk) = w.get_mut(i) { + *wk -= d * v; + } + } + } + } + } + } +} + /// Per block of `blocks` (in order, over the variables `vars`): whether every one of its rows /// is a combination of the rows before it. With `support`, also for the block at that index /// (when redundant) the earlier blocks its rows combine. @@ -48,28 +91,44 @@ pub(super) fn dependent_blocks( x: &mut [f64], support: Option, ) -> (Vec, Vec) { + #[cfg(feature = "solver-profiling")] + let _timer = { + profiling::count(|c| c.redundancy_checks += 1); + profiling::timer(Phase::Redundancy) + }; let mut col = vec![usize::MAX; lay.n]; columns(&mut col, vars, vars); - let (_, j, owner) = local_system(sk, lay, blocks, x, &col, vars.len()); + let (_, j, owner) = { + #[cfg(feature = "solver-profiling")] + let _timer = profiling::timer(Phase::RedundancyJacobian); + local_system(sk, lay, blocks, x, &col, vars.len()) + }; + classify_rows(&j, &owner, blocks.len(), support) +} + +fn classify_rows(j: &Mat, owner: &[usize], block_count: usize, support: Option) -> (Vec, Vec) { + #[cfg(feature = "solver-profiling")] + let classification_timer = profiling::timer(Phase::RedundancyClassification); let n = j.cols; - let row = |k: usize| -> Vec { j.data.get(k * n..(k + 1) * n).map(<[f64]>::to_vec).unwrap_or_default() }; + let row = |k: usize| -> &[f64] { j.data.get(k * n..(k + 1) * n).unwrap_or_default() }; // Orthonormal directions of the independent rows so far, and those rows with their block. - let mut q: Vec> = Vec::new(); + let mut q: Vec = Vec::new(); let mut basis: Vec<(Vec, usize)> = Vec::new(); - let mut has_rows = vec![false; blocks.len()]; - let mut adds_rank = vec![false; blocks.len()]; + let mut has_rows = vec![false; block_count]; + let mut adds_rank = vec![false; block_count]; let mut target_rows: Vec> = Vec::new(); for k in 0..j.rows { let Some(&b) = owner.get(k) else { continue }; let v = row(k); - let norm = dot(&v, &v).sqrt(); - let mut w = v.clone(); - // Twice, for the orthogonality lost to rounding. - for _ in 0..2 { - for qi in &q { - let d = dot(qi, &w); - for (wk, qk) in w.iter_mut().zip(qi) { - *wk -= d * qk; + let norm = dot(v, v).sqrt(); + let mut w = v.to_vec(); + // A non-finite or zero norm cannot add rank, regardless of its projections. Skipping + // those rows also keeps non-finite inputs out of the exact-zero sparse fast path. + if norm.is_finite() && norm > 0.0 { + // Twice, for the orthogonality lost to rounding. Preserve row/direction order. + for _ in 0..2 { + for qi in &q { + qi.remove_from(&mut w); } } } @@ -78,16 +137,23 @@ pub(super) fn dependent_blocks( *h = true; } if norm.is_finite() && left.is_finite() && norm > 0.0 && left > DEPENDENT * norm { - q.push(w.iter().map(|wk| wk / left).collect()); - basis.push((v, b)); + q.push(Direction::new(&w, left)); + // Original rows are used only by explanation queries, never ordinary reports. + if support.is_some() { + basis.push((v.to_vec(), b)); + } if let Some(a) = adds_rank.get_mut(b) { *a = true; } } else if Some(b) == support { - target_rows.push(v); + target_rows.push(v.to_vec()); } } let dependent: Vec = has_rows.iter().zip(&adds_rank).map(|(h, a)| *h && !*a).collect(); + #[cfg(feature = "solver-profiling")] + drop(classification_timer); + #[cfg(feature = "solver-profiling")] + let _support_timer = profiling::timer(Phase::RedundancySupport); let mut by = Vec::new(); if let Some(t) = support && dependent.get(t).copied().unwrap_or(false) diff --git a/crates/sketch/src/redundancy_tests.rs b/crates/sketch/src/redundancy_tests.rs new file mode 100644 index 000000000..3b284b52f --- /dev/null +++ b/crates/sketch/src/redundancy_tests.rs @@ -0,0 +1,184 @@ +//! Frozen ordered dense MGS reference for numerical equivalence tests. +use super::*; + +fn compare(rows: &[Vec], owners: &[usize], blocks: usize) { + let cols = rows.first().map_or(0, Vec::len); + let j = Mat { rows: rows.len(), cols, data: rows.iter().flatten().copied().collect() }; + for support in std::iter::once(None).chain((0..blocks).map(Some)) { + assert_eq!(classify_rows(&j, owners, blocks, support), dense_reference(&j, owners, blocks, support), "{rows:?}, support {support:?}"); + } +} + +#[test] +fn exact_zero_projection_preserves_every_nonzero_result_bit() { + for scale in [f64::from_bits(1), 1e-150, 1.0, 1e150] { + for q in [vec![0.0, -0.0, 0.6, 0.0, 0.8, 0.0, 0.0, 0.0], vec![0.125; 8]] { + for sign in [-1.0, 0.0, 1.0] { + let input: Vec = (0..8).map(|i| sign * scale * (i as f64 - 3.0)).collect(); + let mut expected = input.clone(); + let d = dot(&q, &expected); + for (wk, qk) in expected.iter_mut().zip(&q) { + *wk -= d * qk; + } + let mut actual = input; + Direction::new(&q, 1.0).remove_from(&mut actual); + for (a, b) in actual.iter().zip(&expected) { + assert!((*a == 0.0 && *b == 0.0) || a.to_bits() == b.to_bits(), "{a} != {b}"); + } + } + } + } +} + +#[test] +fn ordered_ids_and_explanations_match_dense_mgs_at_the_threshold() { + // The repeated target and the partially dependent two-row block must retain their owners. + for scale in [1e-150, 1e-6, 1.0, 1e6, 1e150] { + for epsilon in [0.0, DEPENDENT * (1.0 - 1e-10), DEPENDENT, DEPENDENT * (1.0 + 1e-10), 1e-5] { + let rows = vec![ + vec![scale, 0.0, 0.0, -0.0, 0.0, 0.0], + vec![scale, scale * epsilon, 0.0, 0.0, 0.0, 0.0], + vec![0.0, 0.0, scale, 0.0, 0.0, 0.0], + vec![scale, scale * epsilon, 0.0, 0.0, 0.0, 0.0], + vec![0.0; 6], + ]; + compare(&rows, &[0, 1, 1, 2, 3], 5); + } + } + for hostile in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, f64::MAX, f64::MIN_POSITIVE, f64::from_bits(1)] { + compare(&[vec![1.0, 0.0, 0.0, 0.0], vec![0.0, hostile, 0.0, 0.0], vec![1.0, 1.0, 0.0, 0.0]], &[0, 1, 2], 3); + } + compare(&[], &[], 2); +} + +#[test] +fn sparse_and_dense_rows_match_over_seeded_mixed_rank_matrices() { + let mut seed = 99u64; + let mut next = || { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (seed >> 11) as f64 / (1u64 << 53) as f64 * 2.0 - 1.0 + }; + for cols in [2, 3, 8, 17, 32] { + for density in [0.05, 0.3, 1.0] { + for _ in 0..20 { + let mut rows: Vec> = Vec::new(); + for k in 0..cols * 2 { + let row = if k > 0 && k % 3 == 0 { + rows[k / 3].iter().map(|v| v * 2.0).collect() + } else { + (0..cols).map(|_| if next().abs() < density { next() } else { 0.0 }).collect() + }; + rows.push(row); + } + let owners: Vec = (0..rows.len()).map(|k| k / 2).collect(); + compare(&rows, &owners, cols + 1); + } + } + } +} + +#[test] +fn real_sketch_jacobians_keep_redundant_blocks_and_support() { + use crate::ConstraintKind; + use solidcraft_geom::Vec2; + + for seed in 0..8 { + let mut sk = Sketch::new(); + let mut points = vec![0]; + for i in 1..10 { + let p = sk.add_point(Vec2::new(i as f64 * 3.0, (i * seed % 7) as f64), None).unwrap(); + let q = points[i - 1]; + points.push(p); + let l = sk.add_line_pts(q, p, None).unwrap(); + for k in [ConstraintKind::Horizontal { l }, ConstraintKind::Distance { p, q, value: 3.0 }, ConstraintKind::Horizontal { l }] { + sk.add_constraint(k, None).unwrap(); + } + if i % 3 == 0 { + sk.add_constraint(ConstraintKind::Coincident { p, q }, None).unwrap(); + } + } + let lay = layout(&sk, &Hold::default()); + let mut x = initial_x(&sk, &lay); + let (blocks, _) = build_blocks(&sk, &lay, &points_on_curves(&sk)); + let vars: Vec = (0..lay.n).collect(); + let mut col = vec![usize::MAX; lay.n]; + columns(&mut col, &vars, &vars); + let (_, j, owner) = local_system(&sk, &lay, &blocks, &mut x, &col, vars.len()); + for support in std::iter::once(None).chain((0..blocks.len()).map(Some)) { + assert_eq!(classify_rows(&j, &owner, blocks.len(), support), dense_reference(&j, &owner, blocks.len(), support)); + } + } +} + +fn dense_reference(j: &Mat, owner: &[usize], block_count: usize, support: Option) -> (Vec, Vec) { + #[cfg(feature = "solver-profiling")] + let classification_timer = profiling::timer(Phase::RedundancyClassification); + let n = j.cols; + let row = |k: usize| -> Vec { j.data.get(k * n..(k + 1) * n).map(<[f64]>::to_vec).unwrap_or_default() }; + // Orthonormal directions of the independent rows so far, and those rows with their block. + let mut q: Vec> = Vec::new(); + let mut basis: Vec<(Vec, usize)> = Vec::new(); + let mut has_rows = vec![false; block_count]; + let mut adds_rank = vec![false; block_count]; + let mut target_rows: Vec> = Vec::new(); + for k in 0..j.rows { + let Some(&b) = owner.get(k) else { continue }; + let v = row(k); + let norm = dot(&v, &v).sqrt(); + let mut w = v.clone(); + // Twice, for the orthogonality lost to rounding. + for _ in 0..2 { + for qi in &q { + let d = dot(qi, &w); + for (wk, qk) in w.iter_mut().zip(qi) { + *wk -= d * qk; + } + } + } + let left = dot(&w, &w).sqrt(); + if let Some(h) = has_rows.get_mut(b) { + *h = true; + } + if norm.is_finite() && left.is_finite() && norm > 0.0 && left > DEPENDENT * norm { + q.push(w.iter().map(|wk| wk / left).collect()); + basis.push((v, b)); + if let Some(a) = adds_rank.get_mut(b) { + *a = true; + } + } else if Some(b) == support { + target_rows.push(v); + } + } + let dependent: Vec = has_rows.iter().zip(&adds_rank).map(|(h, a)| *h && !*a).collect(); + #[cfg(feature = "solver-profiling")] + drop(classification_timer); + #[cfg(feature = "solver-profiling")] + let _support_timer = profiling::timer(Phase::RedundancySupport); + let mut by = Vec::new(); + if let Some(t) = support + && dependent.get(t).copied().unwrap_or(false) + && !basis.is_empty() + { + // The combination of the independent rows that gives each of the target's rows: the + // least-squares solution of Bᵀ a = v, from (B Bᵀ) a = B v (B has full row rank). + let m = basis.len(); + let mut g = Mat::zeros(m, m); + for (r, (br, _)) in basis.iter().enumerate() { + for (c, (bc, _)) in basis.iter().enumerate() { + g.set(r, c, dot(br, bc)); + } + } + for v in &target_rows { + let rhs: Vec = basis.iter().map(|(b, _)| dot(b, v)).collect(); + let Some(a) = lin_solve(g.clone(), rhs) else { continue }; + let big = a.iter().fold(0.0_f64, |m, x| m.max(x.abs())); + for (ak, (_, b)) in a.iter().zip(&basis) { + if ak.abs() > 1e-6 * big && !by.contains(b) { + by.push(*b); + } + } + } + by.sort_unstable(); + } + (dependent, by) +} diff --git a/crates/sketch/src/solver.rs b/crates/sketch/src/solver.rs index d5165ae6d..d9f77d5c3 100644 --- a/crates/sketch/src/solver.rs +++ b/crates/sketch/src/solver.rs @@ -19,6 +19,8 @@ use solidcraft_geom::{Seg2, Vec2}; use crate::decompose::Budget; use crate::linalg::{Mat, determined_vars, solve as lin_solve}; use crate::model::{ConstraintKind, CurveKind, Sketch}; +#[cfg(feature = "solver-profiling")] +use crate::profiling::{self, Decision, Phase, StopReason}; use crate::union_find::{find, union}; #[path = "cursor.rs"] @@ -673,6 +675,8 @@ fn copy_block<'a>(b: &Block<'a>) -> Block<'a> { } fn block_residuals(s: &State, b: &Block, out: &mut Vec) { + #[cfg(feature = "solver-profiling")] + profiling::count(|c| c.residual_block_evaluations = c.residual_block_evaluations.saturating_add(1)); match b { Block::Closure { a, b } => { let d = s.p(*a) - s.p(*b); @@ -846,6 +850,15 @@ fn block_refs(sk: &Sketch, b: &Block) -> Vec { /// Residual vector and Jacobian (rows × all n vars) for the given blocks. fn system(sk: &Sketch, lay: &Layout, blocks: &[(Block, Vec)], x: &mut [f64], with_j: bool) -> (Vec, Option, Vec) { + #[cfg(feature = "solver-profiling")] + let _timer = profiling::timer(Phase::ResidualSystem); + #[cfg(feature = "solver-profiling")] + profiling::count(|c| { + c.residual_system_evaluations = c.residual_system_evaluations.saturating_add(1); + if with_j { + c.jacobian_evaluations = c.jacobian_evaluations.saturating_add(1); + } + }); let mut r = Vec::new(); let mut owner = Vec::new(); for (bi, (b, _)) in blocks.iter().enumerate() { @@ -856,6 +869,8 @@ fn system(sk: &Sketch, lay: &Layout, blocks: &[(Block, Vec)], x: &mut [f6 if !with_j { return (r, None, owner); } + #[cfg(feature = "solver-profiling")] + let _jacobian_timer = profiling::timer(Phase::Jacobian); let mut j = Mat::zeros(r.len(), lay.n); let mut row = 0; let mut plus = Vec::new(); @@ -901,6 +916,10 @@ fn local_system( col: &[usize], ncols: usize, ) -> (Vec, Mat, Vec) { + #[cfg(feature = "solver-profiling")] + let _timer = profiling::timer(Phase::Jacobian); + #[cfg(feature = "solver-profiling")] + profiling::count(|c| c.jacobian_evaluations = c.jacobian_evaluations.saturating_add(1)); let (r, _, owner) = system(sk, lay, blocks, x, false); let mut j = Mat::zeros(r.len(), ncols); let mut row = 0; @@ -976,6 +995,8 @@ fn lm_capped_with_budget( max_iters: usize, mut budget: Option<&mut Budget>, ) -> Option<(usize, f64)> { + #[cfg(feature = "solver-profiling")] + let _timer = profiling::timer(Phase::Lm); let evaluation_work = if budget.is_some() { residual_work(lay, blocks) } else { 0 }; if !within_budget(&mut budget, evaluation_work) { return None; @@ -986,17 +1007,27 @@ fn lm_capped_with_budget( let mut lambda = 1e-3; let (mut r, _, _) = system(sk, lay, blocks, x, false); let mut f = norm2(&r); + #[cfg(feature = "solver-profiling")] + let run = profiling::start_run(n, r.len(), max_iters, f); for it in 0..max_iters { if max_abs(&r) < TOL { + #[cfg(feature = "solver-profiling")] + profiling::finish_run(run, StopReason::ResidualTolerance, max_abs(&r)); return Some((it, max_abs(&r))); } let normal_work = n.saturating_mul(n).saturating_mul(r.len()).saturating_add(evaluation_work.saturating_mul(n.saturating_mul(2).saturating_add(1))); if !within_budget(&mut budget, normal_work) { + #[cfg(feature = "solver-profiling")] + profiling::finish_run(run, StopReason::WorkBudget, max_abs(&r)); return Some((it, max_abs(&r))); } + #[cfg(feature = "solver-profiling")] + profiling::count(|c| c.outer_iterations = c.outer_iterations.saturating_add(1)); let (_, j, _) = local_system(sk, lay, blocks, x, col, n); // Normal equations of this component. + #[cfg(feature = "solver-profiling")] + let normal_timer = profiling::timer(Phase::NormalEquations); let mut a = Mat::zeros(n, n); let mut g = vec![0.0; n]; for row in 0..j.rows { @@ -1011,6 +1042,8 @@ fn lm_capped_with_budget( } } } + #[cfg(feature = "solver-profiling")] + drop(normal_timer); let mut improved = false; // Damping by distance moved, not by JᵀJ's diagonal (Marquardt): of the steps that fit the // residuals equally well it takes the shortest, so what the constraints leave free moves @@ -1022,6 +1055,8 @@ fn lm_capped_with_budget( for _attempt in 0..30 { let linear_work = n.saturating_mul(n).saturating_mul(n).saturating_add(evaluation_work); if !within_budget(&mut budget, linear_work) { + #[cfg(feature = "solver-profiling")] + profiling::finish_run(run, StopReason::WorkBudget, max_abs(&r)); return Some((it, max_abs(&r))); } let mut m = a.clone(); @@ -1029,7 +1064,14 @@ fn lm_capped_with_budget( m.add(i, i, lambda * w + 1e-12); } let rhs: Vec = g.iter().map(|v| -v).collect(); - let Some(step) = lin_solve(m, rhs) else { + #[cfg(feature = "solver-profiling")] + let linear_timer = profiling::timer(Phase::LinearSolve); + let step = lin_solve(m, rhs); + #[cfg(feature = "solver-profiling")] + drop(linear_timer); + let Some(step) = step else { + #[cfg(feature = "solver-profiling")] + profiling::record_trial(run, it, _attempt, lambda, f, None, &g, &j, None, Decision::LinearFailure); lambda *= 10.0; continue; }; @@ -1041,6 +1083,19 @@ fn lm_capped_with_budget( } let (rt, _, _) = system(sk, lay, blocks, &mut trial, false); let ft = norm2(&rt); + #[cfg(feature = "solver-profiling")] + profiling::record_trial( + run, + it, + _attempt, + lambda, + f, + Some(ft), + &g, + &j, + Some(&step), + if ft.is_finite() && ft < f { Decision::Accepted } else { Decision::Rejected }, + ); if ft.is_finite() && ft < f { *x = trial; r = rt; @@ -1055,9 +1110,13 @@ fn lm_capped_with_budget( } } if !improved { + #[cfg(feature = "solver-profiling")] + profiling::finish_run(run, StopReason::NoImprovement, max_abs(&r)); return Some((it, max_abs(&r))); } } + #[cfg(feature = "solver-profiling")] + profiling::finish_run(run, StopReason::IterationLimit, max_abs(&r)); Some((max_iters, max_abs(&r))) } @@ -1343,9 +1402,12 @@ pub fn solve_holding(sk: &mut Sketch, hold: &Hold) -> SolveReport { /// What a solve works out besides placing the geometry. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Analysis { - /// Degrees of freedom and which geometry the constraints determine: a rank analysis of the - /// Jacobian, the costly part of solving an already solved sketch. + /// Freedom analysis plus redundant constraint IDs. This is the complete diagnostic report + /// used by the public solve helpers and final sketch evaluation. Full, + /// Degrees of freedom and which geometry the constraints determine, with the same rank + /// analysis as `Full`, but no redundant constraint search (`redundant` is empty). + Freedom, /// Only whether it solved: the report's `dof` is 0 and its determined flags are empty. For /// solves whose report is only checked with [`SolveReport::ok`] (the frames of a drag). StatusOnly, @@ -1389,8 +1451,14 @@ pub fn solve_after_value_edit(sk: &mut Sketch, old: &DrivingValues) -> SolveRepo /// before an interactive move. Read where the links are now, a point dimensioned from a /// projected line is on the far side of it as soon as the source moves the line past the point. pub fn solve_after_edit(sk: &mut Sketch, old: &DrivingValues, stored: Option<&[Vec2]>) -> SolveReport { + solve_after_edit_with_analysis(sk, old, stored, Analysis::Full) +} + +/// [`solve_after_edit`] with only the requested diagnostics. Continuation, branch checks and +/// geometry restoration are identical at every analysis level. +pub fn solve_after_edit_with_analysis(sk: &mut Sketch, old: &DrivingValues, stored: Option<&[Vec2]>, analysis: Analysis) -> SolveReport { let old_values: Vec> = sk.constraints.iter().map(|c| old.get(&c.id).copied()).collect(); - solve_from(sk, &Hold::default(), stored, Analysis::Full, Some(&old_values), &mut Budget::full()) + solve_from(sk, &Hold::default(), stored, analysis, Some(&old_values), &mut Budget::full()) } impl Sketch { @@ -1836,6 +1904,8 @@ fn continue_values( x: &mut [f64], edit: &ValueEdit, ) -> (usize, bool) { + #[cfg(feature = "solver-profiling")] + profiling::count(|c| c.continuation_runs = c.continuation_runs.saturating_add(1)); // Every sub-step lands on a sixty-fourth: the changed constraints at each, built once. let arena: Vec> = (0..=SUBSTEPS).map(|j| edit.kinds_at(j)).collect(); let mut blocks: Vec<(Block, Vec)> = sub.iter().map(|(b, v)| (copy_block(b), v.clone())).collect(); @@ -1870,6 +1940,10 @@ fn solve_inner( old_values: Option<&[Option]>, budget: &mut Budget, ) -> SolveReport { + #[cfg(feature = "solver-profiling")] + let _timer = profiling::timer(Phase::Solve); + #[cfg(feature = "solver-profiling")] + profiling::count(|c| c.solve_calls = c.solve_calls.saturating_add(1)); sk.prune_patterns(); sk.refresh_pattern_shapes(); let mut orientation_before = Vec::new(); @@ -1905,7 +1979,11 @@ fn solve_inner( // applies edits: also the one after linked geometry moved, whose reference is the // stored state. let edits = reference.is_none() || old_values.is_some(); + #[cfg(feature = "solver-profiling")] + let seed_timer = profiling::timer(Phase::Seed); let seeded = crate::construct::seed(sk, &given, reference, edits, &on_curve, budget); + #[cfg(feature = "solver-profiling")] + drop(seed_timer); for (i, (at, how)) in seeded.pos.iter().zip(&seeded.placed_by).enumerate() { if let (Some(at), Some(how), Some(v)) = (at, how, lay.pvar.get(i).copied().flatten()) && how.anchors() @@ -1990,6 +2068,12 @@ fn solve_inner( let mut folded: Vec = Vec::new(); let all_blocks = blocks; let oversized = |vars: &[usize]| vars.len() > MAX_COMPONENT_VARS; + #[cfg(feature = "solver-profiling")] + profiling::count(|c| { + c.components = c.components.saturating_add(comps.len() as u64); + c.oversized_components = c.oversized_components.saturating_add(comps.iter().filter(|(_, v, b)| !b.is_empty() && oversized(v)).count() as u64); + c.constructed_variables = c.constructed_variables.saturating_add(constructed.iter().filter(|v| **v).count() as u64); + }); let blocks_of = |bis: &mut dyn Iterator| -> Vec<(Block, Vec)> { bis.filter_map(|bi| all_blocks.get(bi).map(|(b, v)| (copy_block(b), v.clone()))).collect() }; @@ -2044,6 +2128,8 @@ fn solve_inner( if !(residual < ACCEPT) && let Some(plain) = reseeded { + #[cfg(feature = "solver-profiling")] + profiling::count(|c| c.plain_start_retries = c.plain_start_retries.saturating_add(1)); for (&v, s0) in vars.iter().zip(&start) { if let Some(s) = x.get_mut(v) { *s = plain.get(v).copied().flatten().unwrap_or(*s0); @@ -2104,6 +2190,8 @@ fn solve_inner( // Final residuals and analysis, component by component (the Jacobian is block diagonal: // its rank is the sum of the components' ranks). + #[cfg(feature = "solver-profiling")] + let _analysis_timer = profiling::timer(Phase::Analysis); let mut max_residual = 0.0_f64; let mut failing: Vec = Vec::new(); let mut det = vec![false; lay.n]; @@ -2152,7 +2240,7 @@ fn solve_inner( let comp_rank = pin_flags.iter().filter(|p| **p).count() + rest_rank; rank += comp_rank; // More rows than rank: some constraint may be implied by the others. - if r.len() > comp_rank && vars.len() <= redundancy::MAX_REDUNDANCY_VARS { + if analysis == Analysis::Full && r.len() > comp_rank && vars.len() <= redundancy::MAX_REDUNDANCY_VARS { let (dependent, _) = redundancy::dependent_blocks(sk, &lay, &sub, vars, &mut x, None); for ((b, _), d) in sub.iter().zip(dependent) { if d && let Some(c) = redundancy::block_constraint(b).and_then(|ci| sk.constraints.get(ci)) @@ -2283,7 +2371,7 @@ fn solve_inner( }; refresh_driven_dimensions(sk); let (dof, point_determined, curve_determined) = match analysis { - Analysis::Full => ( + Analysis::Full | Analysis::Freedom => ( lay.n.saturating_sub(rank), (0..sk.points.len()).map(pdet).collect(), sk.curves.iter().enumerate().map(|(i, c)| c.kind.point_ids().into_iter().all(pdet) && vdet(lay.rvar.get(i).copied().flatten())).collect(), diff --git a/crates/sketch/tests/analysis_levels.rs b/crates/sketch/tests/analysis_levels.rs new file mode 100644 index 000000000..a65f76f2b --- /dev/null +++ b/crates/sketch/tests/analysis_levels.rs @@ -0,0 +1,68 @@ +//! Reduced diagnostics must preserve placement, rollback, feasibility and exact freedom results. + +use solidcraft_geom::Vec2; +use solidcraft_sketch::{Analysis, ConstraintKind, Hold, Sketch, solve_with}; + +fn compare(sketch: &Sketch, hold: &Hold) { + let mut full_geometry = sketch.clone(); + let mut freedom_geometry = sketch.clone(); + let mut status_geometry = sketch.clone(); + let mut full = solve_with(&mut full_geometry, hold, None, Analysis::Full, None); + let freedom = solve_with(&mut freedom_geometry, hold, None, Analysis::Freedom, None); + let status = solve_with(&mut status_geometry, hold, None, Analysis::StatusOnly, None); + assert_eq!(freedom_geometry, full_geometry); + assert_eq!(status_geometry, full_geometry); + assert!(freedom.redundant.is_empty(), "freedom queries must not compute redundant IDs"); + full.redundant.clear(); + assert_eq!(serde_json::to_value(&freedom).unwrap(), serde_json::to_value(&full).unwrap()); + full.dof = 0; + full.point_determined.clear(); + full.curve_determined.clear(); + assert_eq!(serde_json::to_value(&status).unwrap(), serde_json::to_value(&full).unwrap()); +} + +#[test] +fn analysis_levels_preserve_results_on_anchored_floating_failed_and_held_geometry() { + let mut anchored = Sketch::new(); + let q = anchored.add_point(Vec2::new(12.0, 3.0), None).unwrap(); + let k = ConstraintKind::Distance { p: 0, q, value: 10.0 }; + anchored.add_constraint(k.clone(), None).unwrap(); + let redundant = anchored.add_constraint(k, None).unwrap(); + let full = solve_with(&mut anchored.clone(), &Hold::default(), None, Analysis::Full, None); + assert!(full.ok()); + assert_eq!(full.dof, 1); + assert!(full.redundant.contains(&redundant)); + compare(&anchored, &Hold::default()); + compare(&anchored, &Hold { points: vec![q], radii: vec![] }); + + let mut conflict = anchored.clone(); + conflict.add_constraint(ConstraintKind::Distance { p: 0, q, value: 11.0 }, None).unwrap(); + assert!(!solve_with(&mut conflict.clone(), &Hold::default(), None, Analysis::Full, None).ok()); + compare(&conflict, &Hold::default()); + + let mut floating = Sketch::new(); + let l = floating.add_line(Vec2::new(5.0, 5.0), Vec2::new(14.0, 6.0), None, None, None).unwrap(); + floating.add_constraint(ConstraintKind::Horizontal { l }, None).unwrap(); + floating.add_constraint(ConstraintKind::Horizontal { l }, None).unwrap(); + floating.add_constraint(ConstraintKind::Length { l, value: 10.0 }, None).unwrap(); + compare(&floating, &Hold::default()); + + let mut blocks = Sketch::new(); + let p = blocks.add_point(Vec2::new(4.0, 1.0), None).unwrap(); + let q = blocks.add_point(Vec2::new(5.0, 2.0), None).unwrap(); + blocks.add_constraint(ConstraintKind::Coincident { p, q }, None).unwrap(); + blocks.add_constraint(ConstraintKind::Coincident { p, q }, None).unwrap(); + let c = blocks.add_circle(Vec2::new(20.0, 30.0), 5.0, None, None).unwrap(); + blocks.add_constraint(ConstraintKind::Radius { c, value: 5.0 }, None).unwrap(); + blocks.add_constraint(ConstraintKind::Radius { c, value: 5.0 }, None).unwrap(); + blocks.add_constraint(ConstraintKind::Distance { p: 0, q: p, value: 999.0 }, None).unwrap(); + blocks.constraints.last_mut().unwrap().driven = true; + compare(&blocks, &Hold::default()); + compare(&blocks, &Hold { points: vec![p], radii: vec![c] }); + + let mut constants = Sketch::new(); + let q = constants.add_point(Vec2::new(5.0, 0.0), None).unwrap(); + constants.points[q].fixed = true; + constants.add_constraint(ConstraintKind::Distance { p: 0, q, value: 10.0 }, None).unwrap(); + compare(&constants, &Hold::default()); +} diff --git a/crates/sketch/tests/cursor_target.rs b/crates/sketch/tests/cursor_target.rs index df9272028..1e15ee33a 100644 --- a/crates/sketch/tests/cursor_target.rs +++ b/crates/sketch/tests/cursor_target.rs @@ -149,6 +149,33 @@ fn zero_cursor_budget_does_not_start_optimization() { assert!(budget.exhausted()); } +#[cfg(feature = "solver-profiling")] +#[test] +fn profiling_preserves_budgeted_cursor_motion_and_records_budget_stops() { + use solidcraft_sketch::profiling::{StopReason, capture}; + + let target = Vec2::new(-10.0, 16.0); + let mut saw_budget_stop = false; + for work in [0, 128, 256, 512, 1024, 2048, 4096, 8192, 16384] { + let (mut plain, a, _) = linkage(); + let mut measured = plain.clone(); + let mut plain_budget = solidcraft_sketch::Budget::new(work); + let mut measured_budget = solidcraft_sketch::Budget::new(work); + let expected = move_point_towards(&mut plain, a, target, 1.25, Some(&mut plain_budget), |_, _| true); + let (actual, profile) = capture(|| move_point_towards(&mut measured, a, target, 1.25, Some(&mut measured_budget), |_, _| true)); + assert_eq!(actual, expected); + assert_eq!(measured, plain); + assert_eq!(measured_budget.spent(), plain_budget.spent()); + assert_eq!(measured_budget.exhausted(), plain_budget.exhausted()); + assert!(profile.runs.iter().all(|run| run.stop_reason.is_some() && run.final_max_residual.is_some())); + saw_budget_stop |= profile.runs.iter().any(|run| run.stop_reason == Some(StopReason::WorkBudget)); + if work == 0 { + assert_eq!(profile.counters.lm_runs, 0); + } + } + assert!(saw_budget_stop, "exercise LM returning at its shared work limit"); +} + #[test] fn a_cursor_budget_stop_keeps_the_best_corrected_pose_and_reference_dimensions() { let target = Vec2::new(-10.0, 16.0); From fb811fbf21f28c8dc56062f3289fc8863cb23401 Mon Sep 17 00:00:00 2001 From: SS-EN <84559909+SS-EN@users.noreply.github.com> Date: Tue, 20 Oct 2026 14:20:12 +0000 Subject: [PATCH 217/225] Sketch trim: drag a path across curves to trim every piece it crosses (#3182) `sketch.trim.path {points, dry_run?}` walks a polyline and, at each place it crosses a curve trim may change, removes that piece exactly as `sketch.trim` would there, in the order crossed and in one undo step. A piece already gone is not trimmed again; projected geometry, infinite lines, offset outputs and pieces trim refuses are passed over (reported in `skipped`). It returns each trim's result and each removed piece as a polyline; `dry_run` reports them without changing the design. With Trim on, a press and drag in the viewport draws that path: the pieces it would remove light up (a dry run of the command) and letting go runs it. A click still trims the one piece under it. Co-authored-by: Claude Opus 5.5 --- assets/locales/en.json | 1 + assets/locales/ja.json | 1 + assets/locales/zh.json | 1 + crates/engine/src/cmd/sketch_freeform.rs | 7 +- crates/engine/src/cmd/sketch_modify.rs | 248 ++++++++++++++---- .../engine/src/cmd/sketch_trim_path_tests.rs | 192 ++++++++++++++ crates/ui-egui/src/sketch_tools.rs | 90 ++++++- .../ui-egui/src/sketch_trim_drag_ui_tests.rs | 151 +++++++++++ crates/ui-egui/src/viewport.rs | 41 ++- docs/book/src/guide/sketching.md | 4 +- 10 files changed, 678 insertions(+), 58 deletions(-) create mode 100644 crates/engine/src/cmd/sketch_trim_path_tests.rs create mode 100644 crates/ui-egui/src/sketch_trim_drag_ui_tests.rs diff --git a/assets/locales/en.json b/assets/locales/en.json index 77c030df3..c00d6af87 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -613,6 +613,7 @@ "cmd.sketch_spline_fit_point": "Fit Point Spline", "cmd.sketch_spun_profile": "Spun Profile", "cmd.sketch_toggle_driven": "Toggle Driven Dimension", + "cmd.sketch_trim_path": "Trim Along Path", "cmd.solid_align": "Align", "cmd.solid_boundary_fill": "Boundary Fill", "cmd.solid_bounding_solid": "Bounding Solid", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index d6f0ace30..97bff3386 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -613,6 +613,7 @@ "cmd.sketch_spline_fit_point": "通過点スプライン", "cmd.sketch_spun_profile": "回転プロファイル", "cmd.sketch_toggle_driven": "従動寸法の切り替え", + "cmd.sketch_trim_path": "パスに沿ってトリム", "cmd.solid_align": "整列", "cmd.solid_boundary_fill": "境界フィル", "cmd.solid_bounding_solid": "バウンディング ソリッド", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index f236bdb8d..c31f08a81 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -613,6 +613,7 @@ "cmd.sketch_spline_fit_point": "拟合点样条曲线", "cmd.sketch_spun_profile": "旋转轮廓", "cmd.sketch_toggle_driven": "切换被驱动尺寸", + "cmd.sketch_trim_path": "沿路径修剪", "cmd.solid_align": "对齐", "cmd.solid_boundary_fill": "边界填充", "cmd.solid_bounding_solid": "包围实体", diff --git a/crates/engine/src/cmd/sketch_freeform.rs b/crates/engine/src/cmd/sketch_freeform.rs index cd47682c7..6d8763a33 100644 --- a/crates/engine/src/cmd/sketch_freeform.rs +++ b/crates/engine/src/cmd/sketch_freeform.rs @@ -280,8 +280,13 @@ fn modify(sk: &mut Sketch, ci: usize, at: Vec2, remove: bool, points: Option<&[V } } let ids: Vec = made.iter().filter_map(|c| sk.curves.get(*c).map(|c| c.id.clone())).collect(); + // The removed piece, for previews (`sketch.trim.path`). + let removed: Vec<[f64; 2]> = gone + .and_then(|k| intervals.get(k)) + .map(|(a, b, ..)| span(&segs, *a, *b).iter().flat_map(|s| s.polyline(1e-3)).map(|q| [q.x, q.y]).collect()) + .unwrap_or_default(); sk.remove_curves(&[ci]); let unused: Vec = cut_pt.iter().map(|x| x.1).filter(|pi| !sk.curves.iter().any(|c| c.kind.uses(*pi))).collect(); sk.remove_points(&unused); - Ok(json!({"curves": ids})) + Ok(json!({"curves": ids, "removed": removed})) } diff --git a/crates/engine/src/cmd/sketch_modify.rs b/crates/engine/src/cmd/sketch_modify.rs index 1561ed31f..bf74a90d7 100644 --- a/crates/engine/src/cmd/sketch_modify.rs +++ b/crates/engine/src/cmd/sketch_modify.rs @@ -59,6 +59,13 @@ pub static COMMANDS: &[CommandSpec] = &[ .key("T") .enabled(in_sketch) .params(concat!("curve: id, at: [x,y] (the piece to remove: between the nearest intersections around it)", created_doc!())), + CommandSpec::new("sketch.trim.path", "Trim Along Path", trim_path) + .icon("trim") + .enabled(in_sketch) + .params(concat!( + "points: [[x,y]…] (2…2000 positions: a path drawn across the sketch). Every piece the path crosses is removed as `sketch.trim` removes the piece at that crossing, in the order the path crosses them; a piece crossed again after it is gone is not trimmed twice; projected geometry, infinite lines, offset outputs and pieces trim refuses are passed over (why in `skipped`). dry_run?: bool (report without changing the design). One undo step → trimmed: [each trim's result], removed: [[[x,y]…]] (each removed piece as a polyline)", + created_doc!() + )), CommandSpec::new("sketch.extend", "Extend", extend) .at("SKETCH", "MODIFY") .icon("extend") @@ -343,65 +350,194 @@ fn trim(s: &mut Session, p: &Value) -> Result { let at = req_vec2(cmd, p, "at")?; let (out, info) = edit(s, p, cmd, false, |sk, doc| { let ci = curve_arg(sk, p, cmd)?; - let id = sk.curves.get(ci).map(|c| c.id.clone()).unwrap_or_default(); - if sk.curves.get(ci).is_some_and(|c| c.infinite) { - return Err(bad(cmd, "an infinite line has no ends to trim back to: make it a normal line first")); - } - if sk.curves.get(ci).is_some_and(|c| c.kind.is_freeform()) { - let r = super::sketch_freeform::trim_or_break(sk, ci, at, true, cmd)?; - doc.prune_model_params(); - return Ok(json!({"trimmed": id, "pieces": r["curves"]})); - } - let sh = sk.shape(ci).ok_or_else(|| bad(cmd, "curve"))?; - let tq = sh.param(sh.project(at)); - let (cuts, full) = bracket(sk, ci, tq); - if cuts.is_empty() { - // Nothing crosses it: the whole curve goes. - sk.remove_curves(&[ci]); - doc.prune_model_params(); - return Ok(json!({"deleted": id})); - } - release_extent(sk, ci); - let ts: Vec = cuts.iter().map(|c| c.0).collect(); - let (pieces, pts) = split_at(sk, ci, &ts)?; - // The piece containing tq. - let k = if full { - let (a, b) = (ts[0], ts[1]); - if tq > a && tq < b { 0 } else { 1 } - } else { - ts.iter().filter(|t| **t < tq).count() - }; - for (pi, c) in pts.iter().zip(&cuts) { - pin(sk, *pi, c.2)?; - } - let gone = pieces.get(k).copied().ok_or_else(|| bad(cmd, "piece"))?; - let keep: Vec = pieces.iter().copied().filter(|x| *x != gone).collect(); - // The original curve keeps its id (and constraints): swap geometry into it if needed. - let gone = match keep.first() { - Some(&other) if gone == ci => { - let ka = sk.curves.get(ci).map(|c| c.kind.clone()); - let kb = sk.curves.get(other).map(|c| c.kind.clone()); - if let (Some(ka), Some(kb)) = (ka, kb) { - if let Some(c) = sk.curves.get_mut(ci) { - c.kind = kb; - } - if let Some(c) = sk.curves.get_mut(other) { - c.kind = ka; - } - } - other - } - _ => gone, - }; - let keep: Vec = pieces.iter().copied().filter(|x| *x != gone).collect(); - tie(sk, &keep)?; - sk.remove_curves(&[gone]); + let (out, _) = remove_piece(sk, ci, at, cmd)?; doc.prune_model_params(); - Ok(json!({"trimmed": id})) + Ok(out) })?; Ok(json!({"result": out, "sketch": info})) } +/// Remove the piece of curve `ci` around `at`: between the nearest intersections on either +/// side, or the whole curve when nothing crosses it. Returns what `sketch.trim` reports and the +/// removed piece as a polyline. +fn remove_piece(sk: &mut Sketch, ci: usize, at: Vec2, cmd: &str) -> Result<(Value, Vec)> { + let id = sk.curves.get(ci).map(|c| c.id.clone()).unwrap_or_default(); + if sk.curves.get(ci).is_some_and(|c| c.infinite) { + return Err(bad(cmd, "an infinite line has no ends to trim back to: make it a normal line first")); + } + if sk.curves.get(ci).is_some_and(|c| c.kind.is_freeform()) { + let whole = sk.polyline(ci); + let r = super::sketch_freeform::trim_or_break(sk, ci, at, true, cmd)?; + let removed = match r.get("removed").and_then(Value::as_array) { + Some(pts) => pts.iter().filter_map(|q| Some(Vec2::new(q.get(0)?.as_f64()?, q.get(1)?.as_f64()?))).collect(), + None => whole, + }; + return Ok((json!({"trimmed": id, "pieces": r["curves"]}), removed)); + } + let sh = sk.shape(ci).ok_or_else(|| bad(cmd, "curve"))?; + let tq = sh.param(sh.project(at)); + let (cuts, full) = bracket(sk, ci, tq); + if cuts.is_empty() { + // Nothing crosses it: the whole curve goes. + let removed = sk.polyline(ci); + sk.remove_curves(&[ci]); + return Ok((json!({"deleted": id}), removed)); + } + release_extent(sk, ci); + let ts: Vec = cuts.iter().map(|c| c.0).collect(); + let (pieces, pts) = split_at(sk, ci, &ts)?; + // The piece containing tq. + let k = if full { + let (a, b) = (ts[0], ts[1]); + if tq > a && tq < b { 0 } else { 1 } + } else { + ts.iter().filter(|t| **t < tq).count() + }; + for (pi, c) in pts.iter().zip(&cuts) { + pin(sk, *pi, c.2)?; + } + let gone = pieces.get(k).copied().ok_or_else(|| bad(cmd, "piece"))?; + let keep: Vec = pieces.iter().copied().filter(|x| *x != gone).collect(); + // The original curve keeps its id (and constraints): swap geometry into it if needed. + let gone = match keep.first() { + Some(&other) if gone == ci => { + let ka = sk.curves.get(ci).map(|c| c.kind.clone()); + let kb = sk.curves.get(other).map(|c| c.kind.clone()); + if let (Some(ka), Some(kb)) = (ka, kb) { + if let Some(c) = sk.curves.get_mut(ci) { + c.kind = kb; + } + if let Some(c) = sk.curves.get_mut(other) { + c.kind = ka; + } + } + other + } + _ => gone, + }; + let keep: Vec = pieces.iter().copied().filter(|x| *x != gone).collect(); + tie(sk, &keep)?; + let removed = sk.polyline(gone); + sk.remove_curves(&[gone]); + Ok((json!({"trimmed": id}), removed)) +} + +/// Most crossings one `sketch.trim.path` trims (each one splits a curve, so this also caps the +/// work a hostile path can ask for). +const MAX_PATH_TRIMS: usize = 500; +/// Most positions in a trim path. +const MAX_PATH_POINTS: usize = 2_000; + +/// The first place along `path` after `after` (segment, parameter along it) where the path +/// crosses a curve that a trim may change: (segment, parameter, curve, the crossing point). Crossings are found on the +/// curves' display polylines; the trim projects them onto the exact curve. +fn next_crossing(sk: &Sketch, path: &[Vec2], after: (usize, f64)) -> Option<(usize, f64, usize, Vec2)> { + let bounds = |pts: &[Vec2]| { + pts.iter().fold((Vec2::new(f64::INFINITY, f64::INFINITY), Vec2::new(f64::NEG_INFINITY, f64::NEG_INFINITY)), |(lo, hi), q| { + (Vec2::new(lo.x.min(q.x), lo.y.min(q.y)), Vec2::new(hi.x.max(q.x), hi.y.max(q.y))) + }) + }; + let trimmable: Vec<(usize, Vec, (Vec2, Vec2))> = (0..sk.curves.len()) + .filter(|ci| curve_ok(sk, *ci)) + .map(|ci| { + let poly = sk.polyline(ci); + let b = bounds(&poly); + (ci, poly, b) + }) + .collect(); + for (si, w) in path.windows(2).enumerate().skip(after.0) { + let (a, b) = (w[0], w[1]); + let from = if si == after.0 { after.1 } else { f64::NEG_INFINITY }; + let (lo, hi) = bounds(&[a, b]); + let mut best: Option<(f64, usize, Vec2)> = None; + for (ci, poly, (plo, phi)) in &trimmable { + if plo.x > hi.x || plo.y > hi.y || phi.x < lo.x || phi.y < lo.y { + continue; + } + for e in poly.windows(2) { + let Some((t, q)) = seg_cross(a, b, e[0], e[1]) else { continue }; + if t > from + 1e-9 && best.is_none_or(|x| t < x.0) { + best = Some((t, *ci, q)); + } + } + } + if let Some((t, ci, q)) = best { + return Some((si, t, ci, q)); + } + } + None +} + +/// Whether trim may change curve `ci` (what [`curve_arg`] accepts, and not an infinite line). +fn curve_ok(sk: &Sketch, ci: usize) -> bool { + let Some(c) = sk.curves.get(ci) else { return false }; + !c.infinite + && !sk.is_linked_curve(ci) + && !sk.freeform_offsets.iter().any(|offset| offset.output == c.id) + && !sk.offsets.iter().filter_map(|offset| offset.topology.as_ref()).any(|topology| topology.roles.iter().any(|role| role.output == c.id)) +} + +/// Where segment `a`–`b` crosses segment `c`–`d`: the parameter along `a`–`b` and the point. +fn seg_cross(a: Vec2, b: Vec2, c: Vec2, d: Vec2) -> Option<(f64, Vec2)> { + let (r, s) = (b - a, d - c); + let den = r.cross(s); + if den.abs() <= 1e-15 * r.len2().max(s.len2()).max(1e-30) { + return None; + } + let t = (c - a).cross(s) / den; + let u = (c - a).cross(r) / den; + ((0.0..=1.0).contains(&t) && (0.0..=1.0).contains(&u)).then(|| (t, a + r * t)) +} + +fn trim_path(s: &mut Session, p: &Value) -> Result { + let cmd = "sketch.trim.path"; + let path = vec2_list(cmd, p, "points", MAX_PATH_POINTS)?; + if path.len() < 2 { + return Err(bad(cmd, "`points` needs at least two positions")); + } + if bool_(p, "dry_run").unwrap_or(false) { + let mut t = s.scratch(); + let mut q = p.clone(); + if let Some(o) = q.as_object_mut() { + o.remove("dry_run"); + } + let mut out = trim_path(&mut t, &q)?; + out["dry_run"] = json!(true); + return Ok(out); + } + let ((trimmed, removed, skipped), info) = edit(s, p, cmd, false, |sk, doc| { + let mut trimmed: Vec = Vec::new(); + let mut removed: Vec = Vec::new(); + let mut skipped: Vec = Vec::new(); + let mut after = (0, f64::NEG_INFINITY); + for _ in 0..MAX_PATH_TRIMS { + let Some((si, t, ci, q)) = next_crossing(sk, &path, after) else { break }; + after = (si, t); + // A piece trim refuses (a closed spline crossed once) stays as it was. + let before = sk.clone(); + match remove_piece(sk, ci, q, cmd) { + Ok((out, gone)) => { + trimmed.push(out); + removed.push(json!(gone.iter().map(|v| [v.x, v.y]).collect::>())); + } + Err(e) => { + *sk = before; + let why = e.to_string().replace(&format!("{cmd}: "), ""); + if !skipped.contains(&why) { + skipped.push(why); + } + } + } + } + if trimmed.is_empty() { + return Err(bad(cmd, skipped.first().cloned().unwrap_or_else(|| "the path crosses no curve that can be trimmed".into()))); + } + doc.prune_model_params(); + Ok((trimmed, removed, skipped)) + })?; + Ok(json!({"trimmed": trimmed, "removed": removed, "skipped": skipped, "sketch": info})) +} + fn break_cmd(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.break"; let points = if p.get("points").is_some() { Some(vec2_list(cmd, p, "points", 1000)?) } else { None }; @@ -1884,3 +2020,7 @@ mod robust_tests; #[cfg(test)] #[path = "sketch_corner_tests.rs"] mod corner_tests; + +#[cfg(test)] +#[path = "sketch_trim_path_tests.rs"] +mod trim_path_tests; diff --git a/crates/engine/src/cmd/sketch_trim_path_tests.rs b/crates/engine/src/cmd/sketch_trim_path_tests.rs new file mode 100644 index 000000000..91e8b94bd --- /dev/null +++ b/crates/engine/src/cmd/sketch_trim_path_tests.rs @@ -0,0 +1,192 @@ +//! `sketch.trim.path`: dragging across curves trims each piece the path crosses, as clicking it +//! with `sketch.trim` would, in one undo step. + +use serde_json::{Value, json}; +use solidcraft_geom::Vec2; +use solidcraft_sketch::Shape; + +use crate::Session; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + match s.execute(id, &p) { + Ok(v) => v, + Err(e) => panic!("{id} {p}: {e}"), + } +} + +fn ids(v: &Value) -> Vec { + v.as_array().map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()).unwrap_or_default() +} + +fn sketch(s: &Session) -> solidcraft_sketch::Sketch { + let id = s.active_sketch.unwrap(); + s.model.state().sketch(id).unwrap().sketch.clone() +} + +fn new_sketch() -> Session { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY"})); + s +} + +fn line(s: &mut Session, points: Value) -> Vec { + ids(&run(s, "sketch.line", json!({"points": points}))["curves"]) +} + +/// A 40 x 40 square with a step cut across its top right corner (as in the single trim's +/// dimension test), the right side dimensioned. +fn square_with_step() -> (Session, String, String) { + let mut s = new_sketch(); + let sq = ids(&run(&mut s, "sketch.line", json!({"points": [[0, 0], [40, 0], [40, 40], [0, 40]], "closed": true, "infer": true}))["curves"]); + let (right, top) = (sq[1].clone(), sq[2].clone()); + run(&mut s, "sketch.dimension", json!({"entities": [right]})); + let step = ids(&run(&mut s, "sketch.line", json!({"points": [[23, 40], [23, 23], [40, 23]], "infer": true}))["curves"]); + run(&mut s, "sketch.constraint.coincident", json!({"a": format!("{}.start", step[0]), "b": top})); + run(&mut s, "sketch.constraint.coincident", json!({"a": format!("{}.end", step[1]), "b": right})); + (s, right, top) +} + +#[test] +fn a_path_trims_what_clicking_each_crossed_piece_would() { + // Clicks: the right side above the step, then the top side right of it. + let (mut clicked, right, top) = square_with_step(); + run(&mut clicked, "sketch.trim", json!({"curve": right, "at": [40, 30]})); + run(&mut clicked, "sketch.trim", json!({"curve": top, "at": [30, 40]})); + + // One drag from outside the right side, across the corner, out through the top. + let (mut dragged, ..) = square_with_step(); + let before = sketch(&dragged); + let undo_before = dragged.undo.len(); + let out = run(&mut dragged, "sketch.trim.path", json!({"points": [[45, 30], [30, 30], [30, 45]]})); + assert_eq!(out["trimmed"].as_array().map(Vec::len), Some(2), "{out}"); + assert_eq!(out["removed"].as_array().map(Vec::len), Some(2), "{out}"); + assert_eq!(sketch(&dragged), sketch(&clicked), "the drag and the two clicks leave the same sketch"); + + // One undo step brings everything back. + assert_eq!(dragged.undo.len(), undo_before + 1); + run(&mut dragged, "edit.undo", json!({})); + assert_eq!(sketch(&dragged), before); +} + +#[test] +fn a_piece_crossed_twice_is_trimmed_once() { + let mut s = new_sketch(); + line(&mut s, json!([[0, 0], [20, 0]])); + line(&mut s, json!([[0, 10], [20, 10]])); + let v = line(&mut s, json!([[10, -5], [10, 15]]))[0].clone(); + // A zigzag across the middle piece of the vertical line, three times. + let out = run(&mut s, "sketch.trim.path", json!({"points": [[5, 3], [15, 4], [5, 5], [15, 6]]})); + assert_eq!(out["trimmed"].as_array().map(Vec::len), Some(1), "{out}"); + let removed = out["removed"][0].as_array().unwrap(); + let ends: Vec = + [removed.first().unwrap(), removed.last().unwrap()].iter().map(|q| Vec2::new(q[0].as_f64().unwrap(), q[1].as_f64().unwrap())).collect(); + assert!(ends.iter().any(|q| q.dist(Vec2::new(10.0, 0.0)) < 1e-6) && ends.iter().any(|q| q.dist(Vec2::new(10.0, 10.0)) < 1e-6), "{ends:?}"); + // The two outer pieces of the vertical line stay, the original id on the lower one. + let sk = sketch(&s); + assert_eq!(sk.curves.len(), 4); + let lower = sk.shape(sk.curve_index(&v).unwrap()).unwrap(); + assert!(matches!(lower, Shape::Line { a, b } if a.dist(Vec2::new(10.0, -5.0)) < 1e-6 && b.dist(Vec2::new(10.0, 0.0)) < 1e-6), "{lower:?}"); +} + +/// A scene built twice: trimmed once along `path` and once by clicking `clicks` (curve index +/// in the scene's curves, where) in turn; both must leave the same sketch. +fn same_as_clicks(build: fn(&mut Session) -> Vec, path: Value, clicks: &[(usize, [f64; 2])]) { + let mut clicked = new_sketch(); + let curves = build(&mut clicked); + for (k, at) in clicks { + run(&mut clicked, "sketch.trim", json!({"curve": curves[*k], "at": at})); + } + let mut dragged = new_sketch(); + build(&mut dragged); + let out = run(&mut dragged, "sketch.trim.path", json!({"points": path})); + assert_eq!(out["trimmed"].as_array().map(Vec::len), Some(clicks.len()), "{out}"); + assert!(out["removed"].as_array().unwrap().iter().all(|r| r.as_array().is_some_and(|r| r.len() >= 2)), "{out}"); + assert_eq!(sketch(&dragged), sketch(&clicked), "{path}"); +} + +#[test] +fn circles_arcs_and_splines_trim_along_a_path() { + // A circle across a line: the lower half goes, the rest is an arc. + same_as_clicks( + |s| { + let c = ids(&run(s, "sketch.circle.center", json!({"center": [0, 0], "radius": 10}))["curves"]); + [c, line(s, json!([[-20, 0], [20, 0]]))].concat() + }, + json!([[0, -15], [0, -5]]), + &[(0, [0.0, -10.0])], + ); + // An arc cut by a line through its middle: the left part goes. + same_as_clicks( + |s| { + let a = ids(&run(s, "sketch.arc.three_point", json!({"start": [-10, 0], "through": [0, 10], "end": [10, 0]}))["curves"]); + [a, line(s, json!([[0, -5], [0, 15]]))].concat() + }, + json!([[-10, 8], [-3, 8]]), + &[(0, [-6.0, 8.0])], + ); + // A spline over a line: its hump goes, then the line's piece under it. + same_as_clicks( + |s| { + let sp = + ids(&run(s, "sketch.spline.fit_point", json!({"points": [[-20, -20], [-10, 5], [10, 5], [20, -20]], "connect": false}))["curves"]); + [sp, line(s, json!([[-30, 0], [30, 0]]))].concat() + }, + json!([[0, 10], [0, -1]]), + &[(0, [0.0, 10.0]), (1, [0.0, 0.0])], + ); +} + +#[test] +fn a_dry_run_reports_the_pieces_without_changing_the_design() { + let (mut s, ..) = square_with_step(); + let before = sketch(&s); + let (undo, revision) = (s.undo.len(), s.revision); + let path = json!([[45, 30], [30, 30], [30, 45]]); + let dry = run(&mut s, "sketch.trim.path", json!({"points": path, "dry_run": true})); + assert_eq!(dry["dry_run"], true); + assert_eq!(sketch(&s), before); + assert_eq!((s.undo.len(), s.revision), (undo, revision), "a dry run is no step"); + let real = run(&mut s, "sketch.trim.path", json!({"points": path})); + assert_eq!(dry["removed"], real["removed"]); + assert_eq!(dry["trimmed"], real["trimmed"]); +} + +#[test] +fn curves_trim_cannot_change_are_passed_over() { + let mut s = new_sketch(); + let inf = line(&mut s, json!([[0, -10], [0, 10]]))[0].clone(); + run(&mut s, "sketch.infinite", json!({"curves": [inf]})); + let h = line(&mut s, json!([[-20, 0], [20, 0]]))[0].clone(); + // Crossing the infinite line leaves it alone; the horizontal line's right part goes. + let out = run(&mut s, "sketch.trim.path", json!({"points": [[-5, 5], [10, 5], [10, -5]]})); + assert_eq!(out["trimmed"].as_array().map(Vec::len), Some(1), "{out}"); + let sk = sketch(&s); + assert!(sk.curves[sk.curve_index(&inf).unwrap()].infinite); + let rest = sk.shape(sk.curve_index(&h).unwrap()).unwrap(); + assert!(matches!(rest, Shape::Line { a, b } if a.dist(Vec2::new(-20.0, 0.0)) < 1e-6 && b.dist(Vec2::new(0.0, 0.0)) < 1e-6), "{rest:?}"); +} + +#[test] +fn hostile_paths_fail_cleanly() { + let mut s = new_sketch(); + line(&mut s, json!([[0, 0], [10, 0]])); + let before = sketch(&s); + let long: Vec<[f64; 2]> = (0..2_001).map(|i| [i as f64, 1.0]).collect(); + for p in [ + json!({}), + json!({"points": []}), + json!({"points": [[0, 1]]}), + json!({"points": "x"}), + json!({"points": [[0, 1], ["a", 2]]}), + json!({"points": long}), + json!({"points": [[50, 50], [60, 60]]}), + json!({"points": [[1e308, -1e308], [-1e308, 1e308]]}), + json!({"points": [[5, 1], [5, 1]]}), + ] { + assert!(s.execute("sketch.trim.path", &p).is_err(), "{p}"); + assert_eq!(sketch(&s), before, "{p}"); + } + // Outside a sketch. + let mut none = Session::default(); + assert!(none.execute("sketch.trim.path", &json!({"points": [[0, -1], [0, 1]]})).is_err()); +} diff --git a/crates/ui-egui/src/sketch_tools.rs b/crates/ui-egui/src/sketch_tools.rs index bedd33883..2e702599b 100644 --- a/crates/ui-egui/src/sketch_tools.rs +++ b/crates/ui-egui/src/sketch_tools.rs @@ -86,6 +86,78 @@ thread_local! { static ISO: RefCell>> = const { RefCell::new(Vec::new()) }; /// Center of Mass has just started: measure everything on the next frame. static DEFERRED: Cell = const { Cell::new(false) }; + /// A Trim drag: the pieces its path would remove (sketch polylines), and where the path's + /// last point is on screen. + static TRIM_REMOVED: RefCell>> = const { RefCell::new(Vec::new()) }; + static TRIM_LAST: Cell> = const { Cell::new(None) }; +} + +/// Screen distance the pointer moves before a Trim drag's path takes another point. +const TRIM_STEP_PX: f32 = 4.0; + +/// The sketch-plane position under screen position `pos`. +fn on_sketch_plane(app: &SolveApp, proj: &Proj, pos: Pos2) -> Option { + let st = app.session.world_state(); + let ss = st.sketch(active_sketch(app)?)?; + let (o, d) = proj.ray(pos); + ss.plane.intersect_ray(o, d).map(|w| ss.plane.to_local(w)) +} + +/// A press and drag with Trim draws a path from `press`; true when it started one. Each piece +/// the path crosses is trimmed when it is let go (`sketch.trim.path`). +pub fn trim_drag_start(app: &mut SolveApp, proj: &Proj, press: Pos2) -> bool { + let Some(q) = on_sketch_plane(app, proj, press) else { return false }; + let Some(tool) = app.tool.as_mut().filter(|t| t.cmd == "sketch.trim") else { return false }; + tool.pts = vec![(q, None)]; + TRIM_LAST.with(|c| c.set(Some(press))); + TRIM_REMOVED.with(|r| r.borrow_mut().clear()); + true +} + +/// The Trim drag's path reaches `pos`: the pieces it would remove light up (a dry run of the +/// command the release runs). +pub fn trim_drag_to(app: &mut SolveApp, proj: &Proj, pos: Pos2) { + if TRIM_LAST.with(Cell::get).is_some_and(|last| last.distance(pos) < TRIM_STEP_PX) { + return; + } + let Some(q) = on_sketch_plane(app, proj, pos) else { return }; + let Some(tool) = app.tool.as_mut().filter(|t| t.cmd == "sketch.trim" && !t.pts.is_empty()) else { return }; + if tool.pts.len() >= TRIM_PATH_MAX { + return; + } + tool.pts.push((q, None)); + TRIM_LAST.with(|c| c.set(Some(pos))); + let points: Vec<[f64; 2]> = tool.pts.iter().map(|p| [p.0.x, p.0.y]).collect(); + let removed = app + .session + .execute("sketch.trim.path", &json!({"points": points, "dry_run": true})) + .map(|v| { + v["removed"] + .as_array() + .into_iter() + .flatten() + .map(|piece| piece.as_array().into_iter().flatten().filter_map(solidcraft_engine::params::vec2).collect()) + .collect() + }) + .unwrap_or_default(); + TRIM_REMOVED.with(|r| *r.borrow_mut() = removed); +} + +/// Most points a Trim drag's path keeps (the command's limit). +const TRIM_PATH_MAX: usize = 2_000; + +/// The Trim drag is let go: trim every piece its path crossed, in one undo step. False when the +/// path crossed nothing (the caller takes the release as a click). +pub fn trim_drag_end(app: &mut SolveApp) -> bool { + TRIM_LAST.with(|c| c.set(None)); + let crossed = TRIM_REMOVED.with(|r| !std::mem::take(&mut *r.borrow_mut()).is_empty()); + let Some(tool) = app.tool.as_mut().filter(|t| t.cmd == "sketch.trim") else { return false }; + let points: Vec<[f64; 2]> = std::mem::take(&mut tool.pts).iter().map(|p| [p.0.x, p.0.y]).collect(); + if !crossed || points.len() < 2 { + return false; + } + let _ = app.run("sketch.trim.path", json!({"points": points})); + true } /// Commands registered on one panel that another panel also lists: the analyses (sketch @@ -528,7 +600,7 @@ pub fn hint(id: &str) -> Option { "inspect.continuity" => "Continuity: click an edge for its numbers (the button again turns the colours off)", "canvas.insert" => "Canvas: click a plane or a planar face where the image's centre goes", "canvas.decal" => "Decal: click a planar face where the image's centre goes", - "sketch.trim" => "Trim: click the piece of a curve to remove", + "sketch.trim" => "Trim: click the piece of a curve to remove, or drag across the pieces to remove", "sketch.extend" => "Extend: click a curve near the end to extend", "sketch.break" => "Break: click a curve where it should split", "sketch.line.midpoint" => "Midpoint line: click the middle, then an end", @@ -1042,6 +1114,18 @@ pub fn preview(app: &SolveApp, t: &Tool, painter: &egui::Painter, proj: &Proj) { crate::tools::paint_sketch_path(&world, 0, painter, proj, Stroke::new(4.5, tk.error)); } let stroke = Stroke::new(1.5, tk.rubber_band); + // A Trim drag: the pieces it will remove, then the path drawn so far. + if t.cmd == "sketch.trim" && !t.pts.is_empty() { + TRIM_REMOVED.with(|r| { + for piece in r.borrow().iter() { + let line: Vec = piece.iter().filter_map(|p| to(*p)).collect(); + painter.add(egui::Shape::line(line, Stroke::new(4.0, tk.error.gamma_multiply(0.8)))); + } + }); + let path: Vec = t.pts.iter().filter_map(|p| to(p.0)).collect(); + painter.add(egui::Shape::line(path, stroke)); + return; + } if let Some((hp, snap)) = &t.hover && let Some(sp) = to(*hp) { @@ -1320,3 +1404,7 @@ mod corner_ui_tests; #[cfg(test)] #[path = "sketch_continuity_tests.rs"] mod continuity_tests; + +#[cfg(test)] +#[path = "sketch_trim_drag_ui_tests.rs"] +mod trim_drag_ui_tests; diff --git a/crates/ui-egui/src/sketch_trim_drag_ui_tests.rs b/crates/ui-egui/src/sketch_trim_drag_ui_tests.rs new file mode 100644 index 000000000..a0a56c02a --- /dev/null +++ b/crates/ui-egui/src/sketch_trim_drag_ui_tests.rs @@ -0,0 +1,151 @@ +//! Trim by dragging: with Trim on, a press and drag draws a path, the pieces it crosses light +//! up, and letting go trims them all (`sketch.trim.path`) in one undo step. A click still trims +//! the one piece under it. + +use serde_json::{Value, json}; +use solidcraft_engine::geom::Vec2; +use solidcraft_engine::sketch::Shape; + +use crate::scenario::Harness; + +/// Two horizontal lines crossed by a vertical one, seen from the top, with Trim on. Returns the +/// vertical line's id. +fn ladder() -> (Harness, String) { + let mut h = Harness::new(); + h.app.home.open = false; + run(&mut h, "sketch.create", json!({"plane": "XY"})); + run(&mut h, "sketch.line", json!({"points": [[0, 0], [20, 0]], "connect": false})); + run(&mut h, "sketch.line", json!({"points": [[0, 10], [20, 10]], "connect": false})); + let v = run(&mut h, "sketch.line", json!({"points": [[10, -5], [10, 15]], "connect": false}))["curves"][0].as_str().unwrap().to_string(); + h.call("ui.view", json!({"view": "top"})); + h.app.cam.distance = 60.0; + h.frames(3); + h.call("ui.start", json!({"command": "sketch.trim"})); + h.frames(2); + (h, v) +} + +#[test] +fn dragging_across_pieces_trims_them_all_in_one_undo_step() { + let (mut h, v) = ladder(); + let before = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + // A zigzag across the vertical line's middle piece, three times, then down across the + // lower line's right half. + let a = screen(&mut h, 5.0, 8.0); + let b = screen(&mut h, 15.0, 7.0); + let c = screen(&mut h, 5.0, 5.0); + let d = screen(&mut h, 15.0, -3.0); + let mut path = vec![a]; + path.extend(steps(a, b, 8)); + path.extend(steps(b, c, 8)); + path.extend(steps(c, d, 8)); + press_and_move(&mut h, &path); + + // While dragging: nothing has changed yet, and the two pieces to go light up (the middle + // piece once). + assert!(h.app.viewport.trim_drag); + assert_eq!(h.app.session.doc.to_json(), before, "a drag changes nothing before it is let go"); + assert_eq!(h.app.session.undo.len(), undo); + let lit = super::TRIM_REMOVED.with(|r| r.borrow().clone()); + assert_eq!(lit.len(), 2, "{lit:?}"); + + release(&mut h, d); + assert!(!h.app.viewport.trim_drag); + assert!(super::TRIM_REMOVED.with(|r| r.borrow().is_empty())); + assert_eq!(h.app.session.undo.len(), undo + 1, "one undo step"); + // The vertical line keeps its ends; the lower line its left half. + let sk = sketch(&h); + let rest: Vec = (0..sk.curves.len()).filter_map(|ci| sk.shape(ci)).collect(); + assert_eq!(rest.len(), 4, "{rest:?}"); + assert!(rest.iter().all(|s| s.dist(Vec2::new(10.0, 5.0)) > 1e-3 && s.dist(Vec2::new(15.0, 0.0)) > 1e-3), "{rest:?}"); + let lower = sk.shape(sk.curve_index(&v).unwrap()).unwrap(); + assert!(matches!(lower, Shape::Line { a, b } if a.dist(Vec2::new(10.0, -5.0)) < 1e-6 && b.dist(Vec2::new(10.0, 0.0)) < 1e-6), "{lower:?}"); + // Trim stays on for the next piece. + assert_eq!(h.app.tool.as_ref().map(|t| t.cmd), Some("sketch.trim")); + + run(&mut h, "edit.undo", json!({})); + assert_eq!(h.app.session.doc.to_json(), before); +} + +#[test] +fn a_click_still_trims_one_piece_and_an_empty_drag_nothing() { + let (mut h, v) = ladder(); + let undo = h.app.session.undo.len(); + // A drag that crosses nothing leaves the design alone. + let a = screen(&mut h, 1.0, 3.0); + let b = screen(&mut h, 8.0, 7.0); + let mut path = vec![a]; + path.extend(steps(a, b, 6)); + press_and_move(&mut h, &path); + release(&mut h, b); + assert_eq!(h.app.session.undo.len(), undo); + + // A click on the vertical line's middle piece trims just that piece. + h.step(&json!({"click": {"sketch": [10, 5]}})).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + let sk = sketch(&h); + assert_eq!(sk.curves.len(), 4); + assert!((0..sk.curves.len()).all(|ci| sk.shape(ci).is_some_and(|s| s.dist(Vec2::new(10.0, 5.0)) > 1e-3))); + assert!(sk.curve_index(&v).is_some()); +} + +#[test] +fn a_click_that_moves_along_a_piece_still_trims_it() { + // A press that moves on the way (#2448) beside the vertical line's middle piece, crossing + // nothing: the release is the click, and trims the piece under it. + let (mut h, _) = ladder(); + let undo = h.app.session.undo.len(); + let a = screen(&mut h, 10.0, 3.0) + egui::vec2(3.0, 0.0); + let b = screen(&mut h, 10.0, 7.0) + egui::vec2(3.0, 0.0); + let mut path = vec![a]; + path.extend(steps(a, b, 6)); + press_and_move(&mut h, &path); + release(&mut h, b); + assert_eq!(h.app.session.undo.len(), undo + 1, "one trim"); + let sk = sketch(&h); + assert_eq!(sk.curves.len(), 4); + assert!((0..sk.curves.len()).all(|ci| sk.shape(ci).is_some_and(|s| s.dist(Vec2::new(10.0, 5.0)) > 1e-3))); +} + +fn run(h: &mut Harness, id: &str, p: Value) -> Value { + match h.app.run(id, p.clone()) { + Ok(v) => v, + Err(e) => panic!("{id} {p}: {e}"), + } +} + +fn sketch(h: &Harness) -> solidcraft_engine::sketch::Sketch { + let sid = h.app.session.active_sketch.expect("sketch mode"); + h.app.session.world_state().sketch(sid).expect("the sketch").sketch.clone() +} + +fn screen(h: &mut Harness, x: f64, y: f64) -> egui::Pos2 { + let [sx, sy] = h.at(&json!({"sketch": [x, y]})).expect("on screen"); + egui::pos2(sx as f32, sy as f32) +} + +fn steps(a: egui::Pos2, b: egui::Pos2, n: usize) -> Vec { + (1..=n).map(|i| a + (b - a) * (i as f32 / n as f32)).collect() +} + +/// Press at `path[0]` and move through the rest, one frame per event. +fn press_and_move(h: &mut Harness, path: &[egui::Pos2]) { + let Some(&a) = path.first() else { return }; + h.app.synthetic.push(egui::Event::PointerMoved(a)); + h.app.synthetic.push(egui::Event::PointerButton { pos: a, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }); + h.app.synthetic.extend(path.iter().skip(1).map(|&p| egui::Event::PointerMoved(p))); + play(h); +} + +fn release(h: &mut Harness, at: egui::Pos2) { + h.app.synthetic.push(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }); + play(h); +} + +fn play(h: &mut Harness) { + while !h.app.synthetic.is_empty() { + h.frame(); + } + h.frames(2); +} diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index dc0a5aa12..61d18726f 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -48,6 +48,8 @@ pub struct ViewportState { /// A tool's click moved on the way (#2448): egui takes a press that moves past its /// click distance, or is held past its click time, as a drag, so its release is the click. pub(crate) tool_click: bool, + /// A Trim drag is drawing its path (`sketch_tools::trim_drag_*`). + pub(crate) trim_drag: bool, /// Per-body boxes of one world state, held (not just its address, which a later state can /// reuse once the old one is freed, so stale boxes would come back). pick_bounds: std::sync::Mutex>, @@ -2533,6 +2535,23 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { crate::tools::on_hover(app, &proj, p); } } + // A Trim drag's path follows the pointer; letting go trims what it crossed. A path that + // crossed nothing was a click that moved on the way (#2448): the release clicks. + if app.viewport.trim_drag { + let at = ui.input(|i| i.pointer.latest_pos()).filter(|p| rect.contains(*p)); + if resp.drag_stopped() || !ui.input(|i| i.pointer.primary_down()) { + app.viewport.trim_drag = false; + if !crate::sketch_tools::trim_drag_end(app) + && let Some(p) = at + && app.tool.is_some() + { + crate::tools::on_hover(app, &proj, p); + crate::tools::on_click(app, &proj, p); + } + } else if let Some(p) = at { + crate::sketch_tools::trim_drag_to(app, &proj, p); + } + } // Selection chords via resolve (add-only Shift is a preference; default both toggle). let held_mods = crate::tool_modifiers::Held::from_modifiers(mods); let (add, allow_toggle) = crate::tool_modifiers::selection_click(held_mods, app.preferences.selection_shift_add_only); @@ -2541,6 +2560,20 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { if app.tool.is_some() { crate::tools::on_hover(app, &proj, p); } + // Trim also trims by press and drag across the pieces to remove (its own release handling, + // so not a click that moved on the way below). + if app.tool.as_ref().is_some_and(|t| t.cmd == "sketch.trim") + && !held + && primary_nav.is_none() + && mode.is_none() + && resp.drag_started_by(egui::PointerButton::Primary) + && let Some(a) = ui.input(|i| i.pointer.press_origin()) + { + app.viewport.trim_drag = crate::sketch_tools::trim_drag_start(app, &proj, a); + if app.viewport.trim_drag { + crate::sketch_tools::trim_drag_to(app, &proj, p); + } + } // Rectangles, circles and polygons also draw by press, drag and release (#1630): the press // places the first point as a click there would, the release the second. let two_point_start = app.tool.as_ref().is_some_and(|t| matches!(t.kind, crate::tools::Kind::Draw(2)) && t.pts.is_empty()); @@ -2553,7 +2586,13 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { { crate::tools::on_click(app, &proj, a); app.viewport.draw_drag = app.tool.as_ref().is_some_and(|t| t.pts.len() == 1).then_some(a); - } else if app.tool.is_some() && !held && primary_nav.is_none() && mode.is_none() && resp.drag_started_by(egui::PointerButton::Primary) { + } else if app.tool.is_some() + && !app.viewport.trim_drag + && !held + && primary_nav.is_none() + && mode.is_none() + && resp.drag_started_by(egui::PointerButton::Primary) + { // Any other press of a tool that turns into a drag is a click that moved on the way // (#2448): its release clicks. app.viewport.tool_click = true; diff --git a/docs/book/src/guide/sketching.md b/docs/book/src/guide/sketching.md index c9595d0ce..c74d2c301 100644 --- a/docs/book/src/guide/sketching.md +++ b/docs/book/src/guide/sketching.md @@ -30,7 +30,9 @@ Lines and polylines (L), rectangles (two-point R, three-point, centre), circles two-point, three-point, tangent), arcs (three-point, centre, tangent), polygons, slots, ellipses, fit-point and control-point splines, conics, points and text. **Construction** (X) turns curves into reference geometry that doesn't form profiles. Modify tools include trim (T), extend, break, -fillet, chamfer, offset (O), mirror, patterns, move/copy and scale. +fillet, chamfer, offset (O), mirror, patterns, move/copy and scale. With trim on, click a +piece to remove it, or press and drag a path across several pieces: the ones it crosses light up +and all go when you let go, in one undo step (`sketch.trim.path`). The Sketch Palette's **Construction Geometries** option hides construction curves while you work. A hidden construction curve cannot be picked by a click or by a box. Nothing invisible From c7bd467be769709ffd73739c5dd92a794802e174 Mon Sep 17 00:00:00 2001 From: SS-EN <84559909+SS-EN@users.noreply.github.com> Date: Tue, 20 Oct 2026 14:21:54 +0000 Subject: [PATCH 218/225] joint.inspect: show agents what each joint is attached to (#3453) * joint.inspect: what each joint is attached to, for agents A read-only `joint.inspect {joint?}` gives each joint's definition: for each side the occurrence, its component and path, the snap as saved, and what each persistent face/edge name refers to (the feature that made it, and the sketch and curve a swept side came from), whether the origin resolves and why not; plus kind, offset, angle, flip, values with limits, expressions, the motion links it is in, and its solve errors and conflicts. Its id ends in `.inspect`, so agent gates treat it as reading only. MCP `inspect_design` includes the definitions when the design has joints (`joints: false` leaves them out). joint.list and joint.inspect share the motion-link JSON. Co-Authored-By: Claude Opus 5.5 * i18n: catalog entries for Inspect Joint (en, ja, zh) Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- assets/locales/en.json | 1 + assets/locales/ja.json | 1 + assets/locales/zh.json | 1 + crates/engine/src/cmd/joints.rs | 63 ++++--- crates/engine/src/cmd/joints_inspect.rs | 227 ++++++++++++++++++++++++ crates/engine/src/cmd/joints_tests.rs | 119 +++++++++++++ crates/mcp/src/tests.rs | 25 +++ crates/mcp/src/tools.rs | 12 +- docs/control-protocol.md | 2 +- docs/mcp.md | 2 +- 10 files changed, 423 insertions(+), 30 deletions(-) create mode 100644 crates/engine/src/cmd/joints_inspect.rs diff --git a/assets/locales/en.json b/assets/locales/en.json index c00d6af87..7ca850eec 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -455,6 +455,7 @@ "cmd.joint_drive": "Drive Joints", "cmd.joint_edit": "Edit Joint", "cmd.joint_gear": "Gear", + "cmd.joint_inspect": "Inspect Joint", "cmd.joint_limits": "Joint Limits", "cmd.joint_list": "List Joints", "cmd.joint_motion_link": "Motion Link", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 97bff3386..f75b515ed 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -455,6 +455,7 @@ "cmd.joint_drive": "ジョイントを駆動", "cmd.joint_edit": "ジョイントを編集", "cmd.joint_gear": "ギア", + "cmd.joint_inspect": "ジョイントを検査", "cmd.joint_limits": "ジョイントの制限", "cmd.joint_list": "ジョイントを一覧表示", "cmd.joint_motion_link": "モーション リンク", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index c31f08a81..d7b941bac 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -455,6 +455,7 @@ "cmd.joint_drive": "驱动接头", "cmd.joint_edit": "编辑接头", "cmd.joint_gear": "齿轮", + "cmd.joint_inspect": "检查接头", "cmd.joint_limits": "接头限制", "cmd.joint_list": "列出接头", "cmd.joint_motion_link": "运动关联", diff --git a/crates/engine/src/cmd/joints.rs b/crates/engine/src/cmd/joints.rs index 8481682ee..e7c071c45 100644 --- a/crates/engine/src/cmd/joints.rs +++ b/crates/engine/src/cmd/joints.rs @@ -15,6 +15,9 @@ use super::CommandSpec; use crate::params::{bad, bool_, num, str_, vec3}; use crate::{EngineError, Result, Session}; +#[path = "joints_inspect.rs"] +mod inspect; + pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("joint.origin", "Joint Origin", joint_origin).at("SOLID", "CREATE").icon("joint_origin").params( "name?, occurrence?: id|name (default: from the pick, or the named face's component), face: [x,y,z] | \"\" (centre of a planar face) | circle: [x,y,z] | \"\" (centre of a round end: a point on its wall or rim, the end's centre, or the round face's name as model.faces lists it) | edge: [x,y,z] (a point on an edge of a planar face: the edge's middle, z out of the face, y into it; on?: [x,y,z] a point on the face (default: the larger planar face beside the edge); corner?: [x,y,z] near one end: the corner there, x and y along its two edges into the face; found again by name, so it follows the face as it changes size) | point: [x,y,z], z?: [x,y,z]; body?: the named face's body; end?: \"\" (a circle's end: the face across its rim there; default the end nearer the pick); x?: [x,y,z] (a direction, world) | \"\" | {face: [x,y,z]} (the frame's x: a direction, a plane's normal, or the way to another hole's axis; keeps a round origin's turn; a point's x is a direction, laid square to its z, default: chosen from z alone). Faces are kept by name: the origin follows its face, and a circle its end, when the design changes", @@ -80,6 +83,15 @@ pub static COMMANDS: &[CommandSpec] = &[ "→ joints (type, occurrences, values, limits; expressions: {offset?, angle?, values?} when they were typed as expressions), origins, links, degrees of freedom, conflicts, floating: [{occurrences, joints}] \ (joint chains joined to nothing grounded: the solver places none of them, so driving them moves nothing)", ), + CommandSpec::new("joint.inspect", "Inspect Joint", inspect::inspect).icon("inspect").noundo().params( + "joint?: id|name (default: every joint) → joints: [{id, name, type, suppressed, visible, flip, offset (mm), angle (deg), values: as joint.list \ + gives them, dofs, expressions?: {offset?, angle?, values?}, a, b: {occurrence, occurrence_name, component, component_name, path \ + (occurrence names from the top, `/` between), snap (as saved: type, pick, face, end, edge, corner, x, point, z, in the component's \ + coordinates), references: [{role: face|end|x|edge|corner, name, role_in_feature?: (top, side:c1…), feature?: {id, name, type} (the feature that made the face; \ + error when it is gone), sketch?: {id, name, curve, curve_type} (a face swept from a sketch curve), faces?: [an edge's two faces], \ + unverified?: a name saved before exact names}], resolves, frame?: {origin, z, x} in the world, error?: why the origin is lost}, \ + links: [{index, role: driver|driven, …as joint.list}], errors, conflicts}] (reads only: nothing changes)", + ), CommandSpec::new("joint.solve", "Solve Joints", solve_cmd).icon("compute").params("re-place the occurrences from the joints → conflicts, errors, dof"), CommandSpec::new("inspect.interference", "Interference", super::interference::interference).at("SOLID", "INSPECT").icon("interference").noundo().params( "bodies?: [names] (default: all, in world placement); budget_s?: seconds (default 240, at most 86400: pairs not finished by then are listed in unchecked as \"not checked: the time budget … ran out\" and the call returns) → interferences: pairs that overlap with the overlap volume, area, bounding box and centre (a pin a hair off the axis of a hole of its size also has near_coaxial: {offset_mm, length_mm}, its volume the crescent the walls share); unchecked: pairs that could not be checked, with the reason. Bodies are pruned by bounding box first, then by their display meshes (pairs whose meshes stay apart by more than their chord tolerances, neither inside the other, are clear without a boolean), so any number of bodies is fine; the pairs left are intersected exactly, in parallel on desktop, the slowest first; at most 20000 pairs whose boxes overlap are intersected per call (truncated: true and skipped_pairs: n say when more were left out). Also: pairs_candidate (boxes overlap), pairs_cleared (by the meshes), pairs_intersected, pairs_not_checked, budget_exceeded, threads (worker threads; 0: on the calling thread), boolean_ms and tessellate_ms (kernel time summed over the pairs), slowest: [{a, b, ms, boolean_ms, tessellate_ms}] and ms", @@ -1319,33 +1331,7 @@ fn list(s: &mut Session, p: &Value) -> Result { out }) .collect(); - let links: Vec = s - .doc - .assembly - .links - .iter() - .map(|l| { - let angle = is_angle(s, l.b, l.ib); - let offset = if angle { l.offset.to_degrees() } else { l.offset }; - let ratio = l.ratio / ratio_scale(s, l.a, l.ia, l.b, l.ib); - let mut v = - json!({"a": l.a, "ia": l.ia, "b": l.b, "ib": l.ib, "ratio": ratio, "offset": offset, "unit": if angle { "deg" } else { "mm" }}); - if let Some(c) = &l.coupling { - v["coupling"] = json!(c); - if let Some(Err(e)) = joints::coupling_values(&s.doc, &st, l) { - v["error"] = json!(e.to_string()); - } - } - // A cam's follower follows its table, not a ratio: its travel instead. - if matches!(l.coupling, Some(Coupling::Cam(_))) - && let Some(o) = v.as_object_mut() - { - o.remove("ratio"); - o.insert("lift".into(), lift_json(l, angle)); - } - v - }) - .collect(); + let links: Vec = s.doc.assembly.links.iter().map(|l| link_json(s, &st, l)).collect(); let origins: Vec = s.doc.assembly.origins.iter().map(|o| json!({"name": o.name, "occurrence": o.origin.occurrence})).collect(); let mut out = sol_json(&sol, p); out["joints"] = json!(js); @@ -1355,6 +1341,29 @@ fn list(s: &mut Session, p: &Value) -> Result { Ok(out) } +/// A motion link as `joint.list` and `joint.inspect` give it: ratio per degree, offset in b's +/// units, a coupling's definition (and why it can't be worked out), a cam's lift in place of a ratio. +fn link_json(s: &Session, st: &solidcraft_doc::ModelState, l: &MotionLink) -> Value { + let angle = is_angle(s, l.b, l.ib); + let offset = if angle { l.offset.to_degrees() } else { l.offset }; + let ratio = l.ratio / ratio_scale(s, l.a, l.ia, l.b, l.ib); + let mut v = json!({"a": l.a, "ia": l.ia, "b": l.b, "ib": l.ib, "ratio": ratio, "offset": offset, "unit": if angle { "deg" } else { "mm" }}); + if let Some(c) = &l.coupling { + v["coupling"] = json!(c); + if let Some(Err(e)) = joints::coupling_values(&s.doc, st, l) { + v["error"] = json!(e.to_string()); + } + } + // A cam's follower follows its table, not a ratio: its travel instead. + if matches!(l.coupling, Some(Coupling::Cam(_))) + && let Some(o) = v.as_object_mut() + { + o.remove("ratio"); + o.insert("lift".into(), lift_json(l, angle)); + } + v +} + fn solve_cmd(s: &mut Session, p: &Value) -> Result { let sol = resolve(s); Ok(sol_json(&sol, p)) diff --git a/crates/engine/src/cmd/joints_inspect.rs b/crates/engine/src/cmd/joints_inspect.rs new file mode 100644 index 000000000..87e4caf57 --- /dev/null +++ b/crates/engine/src/cmd/joints_inspect.rs @@ -0,0 +1,227 @@ +//! Inspect Joint (`joint.inspect`): what each joint is defined by and attached to — its two +//! origins (the occurrence, the snap as saved, and the feature, face, edge or sketch curve each +//! persistent name refers to), whether each origin is found today and why not, its kind, offset, +//! angle, flip, limits, values, expressions and the motion links it takes part in. Reads only. + +use serde_json::{Value, json}; +use solidcraft_doc::joints::{self, Joint, JointOrigin, Snap, XRef}; +use solidcraft_doc::naming::{legacy_name, strip_piece}; +use solidcraft_doc::{Document, MAX_PLACEMENT_DEPTH, ModelState}; + +use super::{component_of, joint_id, link_json, named_values, occurrence_name}; +use crate::{Result, Session}; + +pub(super) fn inspect(s: &mut Session, p: &Value) -> Result { + let cmd = "joint.inspect"; + let ids: Vec = match p.get("joint") { + None | Some(Value::Null) => s.doc.assembly.joints.iter().map(|j| j.id).collect(), + v => vec![joint_id(s, v, cmd)?], + }; + let st = s.model.state(); + let sol = joints::solve(&s.doc, &st); + let vals = joints::joint_values(&s.doc.assembly); + let out: Vec = ids + .iter() + .filter_map(|id| s.doc.assembly.joints.iter().find(|j| j.id == *id)) + .map(|j| { + let q = vals.get(&j.id).map(Vec::as_slice).unwrap_or(&j.values); + joint_json(s, &st, &sol, j, q) + }) + .collect(); + Ok(json!({ "joints": out })) +} + +fn joint_json(s: &Session, st: &ModelState, sol: &joints::Solution, j: &Joint, q: &[f64]) -> Value { + let links: Vec = s + .doc + .assembly + .links + .iter() + .enumerate() + .filter(|(_, l)| l.a == j.id || l.b == j.id) + .map(|(i, l)| { + let mut v = link_json(s, st, l); + v["index"] = json!(i); + v["role"] = json!(if l.b == j.id { "driven" } else { "driver" }); + v + }) + .collect(); + let why = |list: &[(u64, String, String)]| list.iter().filter(|(id, ..)| *id == j.id).map(|(.., why)| why.clone()).collect::>(); + let mut v = json!({ + "id": j.id, + "name": j.name, + "type": j.kind, + "suppressed": j.suppressed, + "visible": s.joint_visible(j.id), + "flip": j.flip, + "offset": j.offset, + "angle": j.angle.to_degrees(), + "values": named_values(j, q), + "dofs": j.kind.dofs(), + "a": side_json(s, st, &j.a), + "b": side_json(s, st, &j.b), + "links": links, + "errors": why(&sol.errors), + "conflicts": why(&sol.conflicts), + }); + if !j.exprs.is_empty() { + v["expressions"] = json!(j.exprs); + } + v +} + +/// One of a joint's origins: what it sits on, what it refers to, and where it is now. +fn side_json(s: &Session, st: &ModelState, o: &JointOrigin) -> Value { + let component = component_of(s, o.occurrence); + let component_name = if component == 0 { + "root".to_string() + } else { + s.doc.components.iter().find(|c| c.id == component).map(|c| c.name.clone()).unwrap_or_default() + }; + let occurrence_name = if o.occurrence == 0 { "root".to_string() } else { occurrence_name(s, o.occurrence) }; + let mut v = json!({ + "occurrence": o.occurrence, + "occurrence_name": occurrence_name, + "component": component, + "component_name": component_name, + "path": occurrence_path(&s.doc, o.occurrence), + "snap": o.snap, + "references": references(&s.doc, &o.snap), + }); + match s.doc.origin_world(st, o) { + Ok(m) => { + v["resolves"] = json!(true); + v["frame"] = json!({"origin": [m[3][0], m[3][1], m[3][2]], "z": [m[2][0], m[2][1], m[2][2]], "x": [m[0][0], m[0][1], m[0][2]]}); + } + Err(e) => { + v["resolves"] = json!(false); + v["error"] = json!(e.to_string()); + } + } + v +} + +/// The occurrence names from the top of the assembly down to `occurrence` (`/` between); a +/// nested component's parent is taken at its first placement. Empty for the root. +fn occurrence_path(doc: &Document, occurrence: u64) -> String { + let mut names = Vec::new(); + let mut id = occurrence; + for _ in 0..=MAX_PLACEMENT_DEPTH { + let Some(o) = doc.occurrences.iter().find(|o| o.id == id) else { break }; + names.push(o.name.as_str()); + let Some(parent) = (o.parent != 0).then(|| doc.occurrence_of(o.parent)).flatten() else { break }; + id = parent.id; + } + names.reverse(); + names.join("/") +} + +/// Every persistent name the snap holds, with what it refers to. +fn references(doc: &Document, snap: &Snap) -> Vec { + let mut out = Vec::new(); + let mut face = |role: &str, name: &Option| { + if let Some(n) = name { + out.push(with_role(role, face_ref(doc, n))); + } + }; + match snap { + Snap::FaceCenter { face: f, x, .. } => { + face("face", f); + if let Some(XRef::Face { face: n, .. }) = x { + face("x", &Some(n.clone())); + } + } + Snap::CircleCenter { face: f, end, x, .. } => { + face("face", f); + face("end", end); + if let Some(XRef::Face { face: n, .. }) = x { + face("x", &Some(n.clone())); + } + } + Snap::Edge { edge, face: f, corner, .. } => { + if let Some(e) = edge { + out.push(with_role("edge", edge_ref(doc, e))); + } + if let Some(n) = f { + out.push(with_role("face", face_ref(doc, n))); + } + if let Some(e) = corner { + out.push(with_role("corner", edge_ref(doc, e))); + } + } + Snap::Frame { .. } | Snap::Point { .. } => {} + } + out +} + +fn with_role(role: &str, mut v: Value) -> Value { + v["role"] = json!(role); + v +} + +/// What a face's persistent name refers to: `F:` names the feature that made the +/// face, and a side `side:` (or a later profile's `side:s.`) the sketch curve +/// it was swept from. Names of another form are given as they are. +fn face_ref(doc: &Document, name: &str) -> Value { + let mut v = json!({ "name": name }); + let bare = match legacy_name(name) { + Some(n) => { + v["unverified"] = json!(true); + n + } + None => name, + }; + let stem = strip_piece(bare); + let Some((fid, role)) = stem.strip_prefix('F').and_then(|r| r.split_once(':')).and_then(|(id, role)| Some((id.parse::().ok()?, role))) + else { + return v; + }; + v["role_in_feature"] = json!(role); + let Some(f) = doc.feature(fid) else { + v["feature"] = json!({"id": fid, "error": format!("feature {fid} is gone")}); + return v; + }; + v["feature"] = json!({"id": f.id, "name": f.name, "type": f.kind.type_name()}); + if let Some(curve) = role.strip_prefix("side:") { + // A later profile's side is `s.`. + let curve = curve + .split_once('.') + .filter(|(k, _)| k.strip_prefix('s').is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))) + .map_or(curve, |(_, c)| c); + let found = f.kind.input_sketches().into_iter().find_map(|id| { + let sk = doc.sketch(id).ok()?; + let c = sk.curves.iter().find(|c| c.id == curve)?; + let curve_type = serde_json::to_value(&c.kind).ok().and_then(|k| k.get("type").cloned()).unwrap_or(Value::Null); + let name = doc.feature(id).map(|f| f.name.clone()).unwrap_or_default(); + Some(json!({"id": id, "name": name, "curve": curve, "curve_type": curve_type})) + }); + v["sketch"] = found.unwrap_or_else(|| json!({"curve": curve, "error": format!("no sketch of {} has a curve `{curve}`", f.name)})); + } + v +} + +/// An edge's persistent name (`|`, `~k` for one of several between them) with +/// what each of its faces refers to. +fn edge_ref(doc: &Document, name: &str) -> Value { + let bare = legacy_name(name).unwrap_or(name); + let bare = bare.rsplit_once('~').filter(|(_, k)| !k.is_empty() && k.bytes().all(|b| b.is_ascii_digit())).map_or(bare, |(e, _)| e); + // Split at the `|` outside a piece's `#[…]`. + let mut depth = 0i32; + let split = bare.char_indices().find(|(_, c)| { + match c { + '[' => depth += 1, + ']' => depth -= 1, + _ => {} + } + *c == '|' && depth == 0 + }); + let faces: Vec = match split { + Some((i, _)) => [bare.get(..i), bare.get(i + 1..)].into_iter().flatten().map(|f| face_ref(doc, f)).collect(), + None => Vec::new(), + }; + let mut v = json!({"name": name, "faces": faces}); + if legacy_name(name).is_some() { + v["unverified"] = json!(true); + } + v +} diff --git a/crates/engine/src/cmd/joints_tests.rs b/crates/engine/src/cmd/joints_tests.rs index 04c25a426..af2590786 100644 --- a/crates/engine/src/cmd/joints_tests.rs +++ b/crates/engine/src/cmd/joints_tests.rs @@ -1523,3 +1523,122 @@ fn interference_of_a_headed_pin_made_before_its_plate() { let got = i["interferences"][0]["volume_mm3"].as_f64().unwrap_or(0.0); assert!((got - want).abs() < 1e-6 * want, "{got} against {want}: {i}"); } + +/// A grounded Base (a 40 x 40 x 10 box), a Pin extruded 20 mm from the sketch circle `c1` of +/// `PinSketch` (r5 at x = 100) and a Cap box; a revolute Hinge from the Base's top to the Pin's +/// top rim, its offset the parameter `gap`, and a rigid Fix between two points of Base and Cap. +fn hinge_and_fix() -> Session { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "gap", "expression": "2 mm"})); + run(&mut s, "component.create", json!({"name": "Base"})); + run(&mut s, "solid.box", json!({"length": 40, "width": 40, "height": 10, "corner": [0, 0, 0]})); + let base = occ(&s, "Base"); + run(&mut s, "occurrence.ground", json!({"occurrence": base, "grounded": true})); + run(&mut s, "component.activate", json!({"component": "root"})); + run(&mut s, "component.create", json!({"name": "Pin"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "PinSketch"})); + run(&mut s, "sketch.circle.center", json!({"center": [100, 0], "radius": 5, "id": "c1"})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"distance": 20})); + run(&mut s, "component.activate", json!({"component": "root"})); + run(&mut s, "component.create", json!({"name": "Cap"})); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 5, "corner": [200, 0, 0]})); + let r = run( + &mut s, + "joint.create", + json!({"type": "revolute", "name": "Hinge", "offset": "gap", "limits": [[-90, 90]], + "a": {"occurrence": "Base", "face": [20, 20, 10]}, "b": {"occurrence": "Pin", "circle": [105, 0, 20]}}), + ); + assert_eq!(r["errors"].as_array().map(Vec::len), Some(0), "{r}"); + run( + &mut s, + "joint.create", + json!({"type": "rigid", "name": "Fix", "a": {"occurrence": "Base", "point": [0, 0, 0]}, "b": {"occurrence": "Cap", "point": [200, 0, 0]}}), + ); + s +} + +/// The reference of `role` on side `side` of an inspected joint. +fn reference<'a>(j: &'a Value, side: &str, role: &str) -> &'a Value { + j[side]["references"].as_array().and_then(|r| r.iter().find(|r| r["role"] == role)).unwrap_or(&Value::Null) +} + +/// `joint.inspect` gives each joint's definition: its kind, offset (and the expression it +/// follows), limits and values, and for each side the occurrence and component, the snap as +/// saved, and what its face names refer to: a circle's wall back to the extrude and the sketch +/// curve it was swept from. +#[test] +fn joint_inspect_gives_what_each_joint_is_attached_to() { + let mut s = hinge_and_fix(); + let all = run(&mut s, "joint.inspect", json!({})); + let joints = all["joints"].as_array().cloned().unwrap_or_default(); + assert_eq!(joints.iter().map(|j| j["name"].clone()).collect::>(), [json!("Hinge"), json!("Fix")], "{all}"); + + let hinge = run(&mut s, "joint.inspect", json!({"joint": "Hinge"}))["joints"][0].clone(); + assert_eq!((&hinge["type"], &hinge["offset"], &hinge["expressions"]["offset"]), (&json!("revolute"), &json!(2.0), &json!("gap")), "{hinge}"); + assert_eq!(hinge["values"][0]["limits"], json!([-90.0, 90.0]), "{hinge}"); + assert_eq!(hinge["dofs"], json!(["angle"])); + assert_eq!((&hinge["a"]["occurrence_name"], &hinge["a"]["component_name"]), (&json!("Base:1"), &json!("Base")), "{hinge}"); + assert_eq!(hinge["a"]["path"], hinge["a"]["occurrence_name"]); + assert_eq!((&hinge["a"]["snap"]["type"], &hinge["b"]["snap"]["type"]), (&json!("face_center"), &json!("circle_center")), "{hinge}"); + assert_eq!((&hinge["a"]["resolves"], &hinge["b"]["resolves"]), (&json!(true), &json!(true)), "{hinge}"); + assert_eq!(hinge["b"]["component_name"], "Pin"); + // The Pin's wall: the extrude's side swept from PinSketch's c1. + let wall = reference(&hinge, "b", "face"); + assert_eq!(wall["feature"]["type"], "ExtrudeFeature", "{hinge}"); + assert_eq!( + (&wall["sketch"]["name"], &wall["sketch"]["curve"], &wall["sketch"]["curve_type"]), + (&json!("PinSketch"), &json!("c1"), &json!("circle")), + "{hinge}" + ); + assert_eq!(wall["name"].as_str().map(|n| n.contains(":side:c1")), Some(true), "{hinge}"); + // The rim's end face is the extrude's top. + assert_eq!(reference(&hinge, "b", "end")["feature"], wall["feature"], "{hinge}"); + // The Base's top: a face of its box, no sketch. + assert!(reference(&hinge, "a", "face")["feature"]["id"].is_u64() && reference(&hinge, "a", "face")["sketch"].is_null(), "{hinge}"); + + let fix = &joints[1]; + assert_eq!((&fix["type"], &fix["values"], &fix["dofs"]), (&json!("rigid"), &json!([]), &json!([])), "{fix}"); + assert_eq!((&fix["b"]["snap"]["type"], &fix["b"]["snap"]["point"]), (&json!("point"), &json!([200.0, 0.0, 0.0])), "{fix}"); + assert_eq!(fix["b"]["references"], json!([])); + assert!(fix.get("expressions").is_none(), "{fix}"); + + // A joint that isn't there is an error. + assert!(s.execute("joint.inspect", &json!({"joint": "Nope"})).is_err()); +} + +/// A joint whose sketch circle is replaced: its origin's face is gone, so it no longer +/// resolves; the inspection says why and that its curve is no longer in the sketch. +#[test] +fn joint_inspect_reports_a_lost_origin() { + let mut s = hinge_and_fix(); + run(&mut s, "sketch.edit", json!({"sketch": "PinSketch"})); + run(&mut s, "sketch.delete", json!({"entities": ["c1"]})); + run(&mut s, "sketch.circle.center", json!({"center": [100, 0], "radius": 5, "id": "c2"})); + run(&mut s, "sketch.finish", json!({})); + let hinge = run(&mut s, "joint.inspect", json!({"joint": "Hinge"}))["joints"][0].clone(); + assert_eq!(hinge["b"]["resolves"], false, "{hinge}"); + let wall = reference(&hinge, "b", "face"); + let name = wall["name"].as_str().unwrap_or_default(); + assert!(hinge["b"]["error"].as_str().is_some_and(|e| e.contains(name)), "{hinge}"); + assert_eq!(wall["sketch"]["curve"], "c1", "{hinge}"); + assert!(wall["sketch"]["error"].is_string(), "{hinge}"); + assert!(!hinge["errors"].as_array().is_none_or(Vec::is_empty), "the solve says so too: {hinge}"); + // The Base side is still found. + assert_eq!(hinge["a"]["resolves"], true); +} + +/// `joint.inspect` reads only: no undo step, the design unchanged, and the id agents' gates +/// treat as reading (`*.inspect`). +#[test] +fn joint_inspect_reads_only() { + let mut s = hinge_and_fix(); + let spec = crate::cmd::command_specs().into_iter().find(|c| c.id == "joint.inspect"); + assert!(spec.is_some_and(|c| !c.undoable && c.tab.is_empty())); + let undo = run(&mut s, "document.inspect", json!({}))["undo"].clone(); + let before = serde_json::to_value(&s.doc).unwrap_or_default(); + run(&mut s, "joint.inspect", json!({})); + run(&mut s, "joint.inspect", json!({"joint": "Fix"})); + assert_eq!(run(&mut s, "document.inspect", json!({}))["undo"], undo); + assert_eq!(serde_json::to_value(&s.doc).unwrap_or_default(), before); +} diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 98ea3b515..8ac811edd 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -294,6 +294,31 @@ fn parameters_drive_the_design() { assert!(d["params"].as_array().unwrap().iter().any(|p| p["name"] == "len" && p["value"] == 50.0), "{d}"); } +/// `inspect_design` gives each joint's definition (as `joint.inspect`) when the design has +/// joints, leaves the key out when it has none, and `joints: false` leaves them out. +#[test] +fn inspect_design_lists_joint_definitions() { + let mut s = server(); + let d = tool(&mut s, "inspect_design", json!({"measure": false, "sketches": false})); + assert!(d.get("joints").is_none(), "{d}"); + for (name, corner) in [("A", [0, 0, 0]), ("B", [20, 0, 0])] { + tool(&mut s, "execute", json!({"command": "component.activate", "params": {"component": "root"}})); + tool(&mut s, "execute", json!({"command": "component.create", "params": {"name": name}})); + tool(&mut s, "execute", json!({"command": "solid.box", "params": {"length": 10, "width": 10, "height": 10, "corner": corner}})); + } + tool( + &mut s, + "execute", + json!({"command": "joint.create", "params": {"type": "rigid", "name": "Glue", "a": {"occurrence": "A:1", "face": [5, 5, 10]}, "b": {"occurrence": "B:1", "face": [25, 5, 0]}}}), + ); + let d = tool(&mut s, "inspect_design", json!({"measure": false, "sketches": false})); + assert_eq!(d["joints"][0]["name"], "Glue", "{d}"); + assert_eq!(d["joints"][0]["a"]["snap"]["type"], "face_center", "{d}"); + assert_eq!(d["joints"][0]["b"]["resolves"], true, "{d}"); + let d = tool(&mut s, "inspect_design", json!({"measure": false, "sketches": false, "joints": false})); + assert!(d.get("joints").is_none(), "{d}"); +} + /// `set_parameter` takes the new value as `value` or as `expression` (the name parameters.change /// uses), which it used to refuse instead of forwarding. #[test] diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index 750a43c1e..ef720a0e1 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -132,11 +132,14 @@ pub fn tool_definitions() -> Vec { "The whole design: user parameters (expression, value, errors), the timeline (features with type, suppressed, \ rolled back, error, warning, timing), bodies (volume, area, centre of mass, bounding box, face/edge/vertex \ counts), sketches (curves with ids and coordinates, points, constraints, profiles, degrees of freedom, solve \ - status), the active sketch, selection and undo depth.", + status), assembly joints (what each origin is attached to: occurrence, the feature, face, edge or sketch \ + curve its face names refer to, whether it resolves and why not; `execute` `joint.inspect {joint}` gives one), \ + the active sketch, selection and undo depth.", obj( json!({ "measure": {"type": "boolean", "description": "Measure bodies (default true)"}, "sketches": {"type": "boolean", "description": "Full sketch contents (default true; false = summary only)"}, + "joints": {"type": "boolean", "description": "Joint definitions as joint.inspect gives them, when the design has joints (default true)"}, }), &[], ), @@ -416,6 +419,13 @@ fn dispatch(b: &mut dyn Backend, name: &str, a: &Map) -> Result { diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 57281fe09..12bffc15f 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -76,7 +76,7 @@ MCP server sends its folders this way on every request ([mcp.md](mcp.md)). Witho | `engine.script` | `commands`: `[{command, params}, …]` | results, stops at the first error | | `engine.batch` | `commands`: `[{command, params}, …]` (at most 10 000), `rollback?`: bool (default true), `timings?`, `profile?`: bool (default false) | `{completed, results, undone}`, plus `failed: {index, command, error}` when a step fails, and with `timings` `timings: [{index, command, ms}]` (the failing step included) and `total_ms`; `profile` adds each step's `profile: {boolean_ms, tessellate_ms, other_ms}`. Runs the steps in one request, so within one frame, each as `engine.execute` runs it. The first failure stops the batch, and with `rollback` the design goes back to how it was before it (`undone`: the steps taken back). Refused before anything runs, with an error starting `engine.batch unavailable`, while the agent cursor is shown or when a step loads a file (`doc.open`, `file.insert_step`, `file.insert_mesh`). Send such steps one by one. Answered when done, for up to 3600 s | | `engine.commands` | — | every command: id, label, tab, panel, icon, shortcut, params doc, enabled | -| `document.inspect` | `measure?`: bool | parameters, timeline (errors, timings), bodies, sketches, selection | +| `document.inspect` | `measure?`: bool | parameters, timeline (errors, timings), bodies, sketches, selection (assembly joints: `engine.execute` `joint.inspect {joint?}`, which reads only: each joint's two origins with the occurrence, the snap as saved, the feature, face, edge or sketch curve its names refer to, and whether it resolves or why not; kind, offset, angle, flip, values, limits, expressions and motion links) | Commands never open dialogs when run this way. `solidcraft-cli commands` prints the same registry. diff --git a/docs/mcp.md b/docs/mcp.md index 71c033616..c6db0875f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -156,7 +156,7 @@ They cover the workflow, the command shapes, how to verify with `measure`, and t | `describe_command` | `id` | One command's parameter docs (`params`) and, for commands with a typed contract (`solid.box`, `solid.extrude` and `engine.describe` so far), the JSON Schemas (2020-12) of its parameters (`input`) and of a successful result (`output`); `null` for the others. The same as `execute` `engine.describe {command}`. | | `execute` | `command`, `params?`, `verbose?` (default true) | Run any command with JSON parameters (`list_commands` shows them). Failures leave the design unchanged. A feature command replies with the feature (`feature`, `name`), every body (`bodies`) and the bodies it created, changed and removed (`created_bodies`, `changed_bodies`, `removed_bodies`). `verbose: false` uses the same compact reply as `batch`. | | `batch` | `commands: [{command, params}]`, `rollback?` (default true), `verbose?` (default true), `timings?`, `profile?` (default false) | Run steps in order, stop at the first error and undo the completed steps. The reply names the failing step (`failed.index`, `failed.command`, `failed.error`) and every result before it. `verbose: false` keeps the reply small in large designs: feature steps leave out the full body list (`created_bodies`, `changed_bodies`, `removed_bodies` stay) and sketch steps the ids they repeat outside `created`. Bridged to an app that has `engine.batch`, the whole batch is one control request (one frame of the app). Older apps, and apps showing the agent cursor, get the steps one by one. `timings: true` adds `timings: [{index, command, ms}]` for every step run, the failing one included, and `total_ms`. `profile: true` also adds each step's `profile: {boolean_ms, tessellate_ms, other_ms}`, its time in kernel booleans, in tessellation and the rest. Steps are timed where they run: in the app when bridged. An app without `engine.batch` is timed step by step, without `profile`. | -| `inspect_design` | `measure?` (default true), `sketches?` (default true) | Design properties (`metadata`: project, author… and other tools' keys; set them with `execute` `document.metadata.set`), parameters, timeline (type, suppressed, rolled back, error, warning, timing), bodies (volume, area, centre of mass, bbox, face/edge/vertex counts, visible; `removed_later: true` while a sketch is being edited on a rolled-back timeline and a later feature deletes the body, which is then not shown), sketches (curves, points, constraints, profiles, DOF, solve status, visible), selection, undo depth. Hide helper sketches, bodies or construction planes with `execute` `browser.visibility` (`{items, visible}` or `{folder, visible}`), and joint glyphs with `{joints: [id or name], visible}` or `{folder: "joints", visible}` (a hidden joint still constrains and drives; `joint.list` reports each joint's `visible`). | +| `inspect_design` | `measure?` (default true), `sketches?` (default true), `joints?` (default true) | Design properties (`metadata`: project, author… and other tools' keys; set them with `execute` `document.metadata.set`), parameters, timeline (type, suppressed, rolled back, error, warning, timing), bodies (volume, area, centre of mass, bbox, face/edge/vertex counts, visible; `removed_later: true` while a sketch is being edited on a rolled-back timeline and a later feature deletes the body, which is then not shown), sketches (curves, points, constraints, profiles, DOF, solve status, visible), joints when the design has any (as `joint.inspect` gives them: each origin's occurrence, component and path, the snap as saved, the feature, face, edge or sketch curve (`sketch: {id, name, curve}`) its persistent names refer to, `resolves` and the `error` when it is lost; kind, offset, angle, flip, values, limits, expressions, motion links; `execute` `joint.inspect {joint}` gives one joint), selection, undo depth. Hide helper sketches, bodies or construction planes with `execute` `browser.visibility` (`{items, visible}` or `{folder, visible}`), and joint glyphs with `{joints: [id or name], visible}` or `{folder: "joints", visible}` (a hidden joint still constrains and drives; `joint.list` reports each joint's `visible`). | | `measure` | `body?` or `items?` | Volume (mm³), area (mm²), centre of mass, bbox and topology counts per body, with totals. With `items` (one or two selections as `execute` takes them: `face`, `edge`, `vertex`, `sketch_curve`, `profile`), the picked geometry instead: see below. | | `body_topology` | `body` | Edges (index, midpoint, length, ends) and faces (index, name, area, centroid, normal, `point`, and for a cylindrical face its `cylinder`: `origin`, `axis`, `radius`). An edge midpoint is the `[x,y,z]` that picks that edge for fillet and chamfer. A face's `point` lies on it and picks it (its centroid may not: that of a face with a hole is in the hole); a face's `name` picks it for the commands that take faces (`face.delete`, `solid.shell`, `solid.draft`, `solid.offset_face`, `solid.split_face`, `solid.replace_face`, and `face` of `sheet.convert`). | | `set_parameter` | `name`, `value` or `expression` (number or expression), `unit?`, `comment?` | Create or change a user parameter and recompute. `expression` is another name for `value` (the one `parameters.change` uses): give one of them, or both only when they agree; neither, or two that differ, is an error. Reports `recomputed` (features rebuilt), `restored` (features whose earlier result for the same inputs was reused, e.g. a value set back) and features that now fail. | From 885d2aafbb0194ab7a2d96c13604a0711c64936a Mon Sep 17 00:00:00 2001 From: rlartot <94693724+rlartot@users.noreply.github.com> Date: Tue, 20 Oct 2026 14:24:18 +0000 Subject: [PATCH 219/225] sketch.create: reject a non-numeric custom plane origin (#3248) (#3252) * claim: #3248 Co-Authored-By: Claude Sonnet 5.5 * sketch.create: reject a custom plane origin that is not three numbers A custom plane {origin, x_dir, y_dir} whose origin was given as an expression ("w/2") or a number with a unit ("20 mm") silently became [0, 0, 0], while a bad x_dir or y_dir was an error. A missing origin is still the world origin; one that is present but is not three numbers now returns a clear error. Expressions are not evaluated, so the saved format is unchanged. Fixes #3248 Co-Authored-By: Claude Sonnet 5.5 --------- Co-authored-by: Claude Sonnet 5.5 --- crates/engine/src/cmd/sketch.rs | 10 +++++++-- crates/engine/src/cmd/sketch_face_tests.rs | 25 ++++++++++++++++++++++ 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rs index bbee1a0e5..96d9bc5b0 100644 --- a/crates/engine/src/cmd/sketch.rs +++ b/crates/engine/src/cmd/sketch.rs @@ -29,7 +29,7 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("sketch.create", "Create Sketch", create_sketch) .at("SOLID", "CREATE") .icon("sketch") - .params("plane: XY|XZ|YZ | construction plane name or id | {origin, x_dir, y_dir} | {face: [world x,y,z], body?: exact world body, index?: face index, path?: complete occurrence ids, fixed?: bool}; new face attachments require a unique certified source (a flat face of a sheet metal body attaches to its panel instead, in the flat pattern's coordinates), fixed:true explicitly freezes the selected plane; offset?: expr, flip?: bool | \"x\" | \"y\" (not on a face: sketch the plane from its other side, so the normal and the default extrude direction are reversed; a half turn about the plane's own x or y axis, true picks the one keeping the sketch's y axis upward; offset still moves along the unflipped normal), project_edges?: bool, name?"), + .params("plane: XY|XZ|YZ | construction plane name or id | {origin?: [x,y,z] numbers in mm, default [0,0,0] (not an expression), x_dir, y_dir} | {face: [world x,y,z], body?: exact world body, index?: face index, path?: complete occurrence ids, fixed?: bool}; new face attachments require a unique certified source (a flat face of a sheet metal body attaches to its panel instead, in the flat pattern's coordinates), fixed:true explicitly freezes the selected plane; offset?: expr, flip?: bool | \"x\" | \"y\" (not on a face: sketch the plane from its other side, so the normal and the default extrude direction are reversed; a half turn about the plane's own x or y axis, true picks the one keeping the sketch's y axis upward; offset still moves along the unflipped normal), project_edges?: bool, name?"), CommandSpec::new("sketch.edit", "Edit Sketch", edit_sketch).noundo().icon("sketch").params("sketch: id or name"), CommandSpec::new("sketch.finish", "Finish Sketch", finish_sketch).at("SKETCH", "FINISH SKETCH").icon("finish").enabled(in_sketch).noundo(), CommandSpec::new("sketch.line", "Line", draw_line) @@ -626,7 +626,13 @@ pub(super) fn plane_ref(s: &Session, p: &Value, cmd: &str) -> Result { if o.contains_key("face") { face::capture(s, v, cmd)? } else { - let origin = v.get("origin").and_then(vec3).unwrap_or(Vec3::ZERO); + // A missing origin is the world origin; one that is given but is not three numbers + // (an expression, a number with a unit) is an error, not a silent [0, 0, 0]. + let origin = match v.get("origin") { + None | Some(Value::Null) => Vec3::ZERO, + Some(o) => vec3(o) + .ok_or_else(|| bad(cmd, "plane `origin` must be three numbers [x, y, z] in mm (expressions are not evaluated here)"))?, + }; let x = v.get("x_dir").and_then(vec3).ok_or_else(|| bad(cmd, "plane needs x_dir"))?; let y = v.get("y_dir").and_then(vec3).ok_or_else(|| bad(cmd, "plane needs y_dir"))?; PlaneRef::Custom { plane: Plane::new(origin, x, y).ok_or_else(|| bad(cmd, "degenerate plane"))? } diff --git a/crates/engine/src/cmd/sketch_face_tests.rs b/crates/engine/src/cmd/sketch_face_tests.rs index 42a0e129b..23ee3ee47 100644 --- a/crates/engine/src/cmd/sketch_face_tests.rs +++ b/crates/engine/src/cmd/sketch_face_tests.rs @@ -698,3 +698,28 @@ fn a_face_next_to_plane_is_refused_not_ignored() { let r = run(&mut s, "sketch.create", json!({"plane": {"face": [10, 10, 10]}})); assert_eq!(r["attachment"], "exact_face", "{r}"); } + +/// #3248: a custom plane's `origin` that is present but not three numbers (an expression such as +/// "w/2", a number with a unit, too few values) became [0, 0, 0] without a word. It is refused, +/// like a bad `x_dir`, and nothing is added. A missing origin is still the world origin. +#[test] +fn a_custom_plane_origin_that_is_not_numbers_is_refused_not_zeroed() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "w", "expression": "40 mm"})); + let features = s.doc.features.len(); + for origin in [json!(["w/2", 0, 0]), json!(["20 mm", 0, 0]), json!([20, 0]), json!("w"), json!([20, 0, null])] { + let p = json!({"plane": {"origin": origin, "x_dir": [0, 1, 0], "y_dir": [0, 0, 1]}}); + let e = s.execute("sketch.create", &p).unwrap_err().to_string(); + assert!(e.contains("origin"), "{p}: {e}"); + } + assert_eq!(s.doc.features.len(), features); + assert!(s.active_sketch.is_none()); + let origin_of = |s: &mut Session, plane: Value| { + run(s, "sketch.create", json!({"plane": plane})); + let r = run(s, "sketch.inspect", json!({})); + run(s, "sketch.finish", json!({})); + r["plane"]["origin"].clone() + }; + assert_eq!(origin_of(&mut s, json!({"origin": [20, 0, 0], "x_dir": [0, 1, 0], "y_dir": [0, 0, 1]})), json!([20.0, 0.0, 0.0])); + assert_eq!(origin_of(&mut s, json!({"x_dir": [0, 1, 0], "y_dir": [0, 0, 1]})), json!([0.0, 0.0, 0.0])); +} From af32243df1c14754cfe5f04033dae28c0dcab23d Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Tue, 20 Oct 2026 14:48:13 +0000 Subject: [PATCH 220/225] Regenerate THIRD-PARTY-LICENSES.txt and docs/features.md [skip ci] --- docs/features.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/features.md b/docs/features.md index bc64de564..a4d8d8843 100644 --- a/docs/features.md +++ b/docs/features.md @@ -111,6 +111,7 @@ SolidCraft's commands by area, generated by `cargo xtask features` from the comm | Text | `sketch.text` | SKETCH › CREATE | | Toggle Driven Dimension | `sketch.toggle_driven` | – | | Trim (T) | `sketch.trim` | SKETCH › MODIFY | +| Trim Along Path | `sketch.trim.path` | – | ## Solid modelling @@ -265,6 +266,7 @@ SolidCraft's commands by area, generated by `cargo xtask features` from the comm | Drive Joints | `joint.drive` | SOLID › ASSEMBLE | | Edit Joint | `joint.edit` | – | | Gear | `joint.gear` | SOLID › ASSEMBLE | +| Inspect Joint | `joint.inspect` | – | | Joint Limits | `joint.limits` | – | | List Joints | `joint.list` | – | | Motion Link | `joint.motion_link` | SOLID › ASSEMBLE | From e98e065584c6639b68f3c1d7321667a34d51ee62 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Tue, 20 Oct 2026 14:24:34 +0000 Subject: [PATCH 221/225] Open saved designs from the model they were saved with (#3053) (#3102) * WIP: adopt the saved model on open (#3053) Co-Authored-By: Claude Opus 5.5 * WIP: tests * WIP: bench-open opens as Open does * docs: opening from the saved model * Tests: an edit after opening evaluates from the feature it changes * clippy * Read SOLIDCRAFT_NO_MODEL_CACHE through the env helper * Open: no picture from the model when the model itself opens; cancel test evaluates * Saved model: bodies passed through found without writing their record; states list runs of bodies * Adopted results go into the evaluation cache: an undone edit, or the marker rolled forward, takes them again * Model cache size guard: the saved model's writer --------- Co-authored-by: Claude Opus 5.5 --- apps/solidcraft-cli/src/main.rs | 15 +- apps/solidcraft-cli/tests/model_cache.rs | 209 +++++++++++ crates/doc/src/construct.rs | 4 +- crates/doc/src/eval.rs | 9 +- crates/doc/src/lib.rs | 8 +- crates/doc/src/model_cache.rs | 424 +++++++++++++++++++++++ crates/doc/src/naming.rs | 16 + crates/doc/src/sheet.rs | 20 +- crates/engine/src/cmd/file.rs | 52 +-- crates/engine/src/lib.rs | 19 +- crates/io/src/design.rs | 93 ++--- crates/io/src/design/native_cache.rs | 158 +++------ crates/kernel/src/blend_variable.rs | 4 +- crates/kernel/src/boolean_diagnostics.rs | 8 +- docs/design-container.md | 60 +++- 15 files changed, 880 insertions(+), 219 deletions(-) create mode 100644 apps/solidcraft-cli/tests/model_cache.rs create mode 100644 crates/doc/src/model_cache.rs diff --git a/apps/solidcraft-cli/src/main.rs b/apps/solidcraft-cli/src/main.rs index dec00af12..9030066b9 100644 --- a/apps/solidcraft-cli/src/main.rs +++ b/apps/solidcraft-cli/src/main.rs @@ -654,24 +654,27 @@ pub(crate) fn cmd_bench_open(args: &[String]) -> Result<(), String> { let t = std::time::Instant::now(); // The file as read, held until the timeline has evaluated it (as the import command does). let mut read = None; - let doc = if step { + let (doc, saved) = if step { let imported = solidcraft_engine::io::step_import_feature(&bytes, path).map_err(|e| e.to_string())?; let mut doc = solidcraft_engine::doc::Document::new(&imported.name); doc.add_feature(imported.kind, Some(&imported.name)).map_err(|e| e.to_string())?; read = Some(imported.import); - doc + (doc, None) } else { - solidcraft_engine::io::read_design(&bytes).map_err(|e| e.to_string())? + // As Open reads it: with the model the file keeps. + solidcraft_engine::io::read_design_file(path, None::).map_err(|e| e.to_string())? }; let parse_ms = t.elapsed().as_secs_f64() * 1000.0; - println!("{}", json!({"step": "parse", "ms": parse_ms, "features": doc.features.len()})); + println!("{}", json!({"step": "parse", "ms": parse_ms, "features": doc.features.len(), "saved_model": saved.is_some()})); if args.iter().any(|a| a == "--parse-only") { return Ok(()); } let t = std::time::Instant::now(); - let s = Session::new(doc); + let s = Session::opened(doc, saved.as_ref()); drop(read); - println!("{}", json!({"step": "evaluate", "ms": t.elapsed().as_secs_f64() * 1000.0})); + // Taken from the file: nothing evaluated (SOLIDCRAFT_NO_MODEL_CACHE evaluates anyway). + let adopted = saved.is_some() && s.model.last_recomputed == 0; + println!("{}", json!({"step": "evaluate", "ms": t.elapsed().as_secs_f64() * 1000.0, "adopted": adopted})); for r in &s.model.results { println!("{}", json!({"step": "feature", "id": r.id, "name": r.name, "ms": r.ms, "error": r.error})); } diff --git a/apps/solidcraft-cli/tests/model_cache.rs b/apps/solidcraft-cli/tests/model_cache.rs new file mode 100644 index 000000000..6d4bab4eb --- /dev/null +++ b/apps/solidcraft-cli/tests/model_cache.rs @@ -0,0 +1,209 @@ +//! A design opened from the model its file keeps is the design evaluated again: the same +//! results, the same bodies (to the bit), the same face names and volumes after every feature, +//! and the same after an edit made to both. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use serde_json::{Value, json}; +use solidcraft_engine::Session; +use solidcraft_engine::doc::{ModelBody, ModelState}; + +fn corpus() -> Vec { + let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/corpus"); + let mut v: Vec = + std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "solidcraft")).collect(); + v.sort(); + v +} + +fn temp(name: &str) -> PathBuf { + std::env::temp_dir().join(format!("solidcraft-model-cache-{}-{name}.solidcraft", std::process::id())) +} + +fn open(path: &Path) -> Session { + let mut s = Session::default(); + s.execute("doc.open", &json!({"path": path.to_string_lossy()})).unwrap_or_else(|e| panic!("{}: {e}", path.display())); + s +} + +fn body(name: &str, b: &ModelBody) -> Value { + let measured = solidcraft_engine::kernel::measure(&b.body).ok(); + json!({ + "name": b.name, "feature": b.feature, "component": b.component, "source": b.source_name, "transferred": b.transferred, + "brep": solidcraft_engine::kernel::encode_native_body(&b.body).map(|bytes| format!("{:x}", sha(&bytes))).unwrap_or_else(|e| format!("{name}: {e}")), + "faces": *solidcraft_engine::doc::naming::face_names(b), + "volume": measured.as_ref().map(|m| m.volume.to_bits()), "area": measured.as_ref().map(|m| m.area.to_bits()), + "look": b.imported.as_ref().map(|l| format!("{l:?}")), + }) +} + +fn sha(bytes: &[u8]) -> u128 { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + bytes.hash(&mut h); + let a = h.finish(); + bytes.len().hash(&mut h); + (u128::from(a) << 64) | u128::from(h.finish()) +} + +fn state(name: &str, st: &Arc) -> Value { + json!({ + "bodies": st.bodies.iter().map(|b| body(name, b)).collect::>(), + "sketches": st.sketches.iter().map(|s| json!([s.feature, s.name, s.plane, s.sketch, s.report, s.profiles.len()])).collect::>(), + "counter": st.body_counter, "sheets": st.sheets, "threads": st.threads, "construct": format!("{:?}", st.construct), + }) +} + +/// Everything a model holds that the rest of the app reads. +fn model(name: &str, s: &Session) -> Value { + let results: Vec = s + .model + .results + .iter() + .map(|r| json!({"id": r.id, "name": r.name, "error": r.error, "warning": r.warning, "skipped": r.skipped, "state": state(name, &r.state)})) + .collect(); + json!({"results": results, "world": state(name, &s.world_state())}) +} + +/// The same edit on both: a parameter's value when the design has one, else a new body. +fn edit(s: &mut Session) { + let param = s.doc.params.first().map(|p| (p.name.clone(), p.expr.clone())); + match param { + Some((name, expr)) => { + s.execute("parameters.change", &json!({"name": name, "expression": format!("({expr}) * 1.05")})).unwrap(); + } + None => { + s.execute("solid.box", &json!({"length": 7, "width": 8, "height": 9, "operation": "new"})).unwrap(); + } + } +} + +fn check(name: &str, mut built: Session) { + let path = temp(name); + built.execute("file.save_as", &json!({"path": path.to_string_lossy()})).unwrap(); + let bytes = std::fs::read(&path).unwrap(); + assert!(solidcraft_engine::io::read_design_geometry(&bytes).is_some(), "{name}: the save keeps the model"); + let mut cached = open(&path); + assert_eq!(cached.model.last_recomputed, 0, "{name}: opened without evaluating"); + let mut rebuilt = Session::new(solidcraft_engine::io::read_design(&bytes).unwrap()); + assert!(rebuilt.model.last_recomputed > 0); + assert_eq!(model(name, &cached), model(name, &rebuilt), "{name}: opened from the file's model"); + edit(&mut cached); + edit(&mut rebuilt); + assert_eq!(model(name, &cached), model(name, &rebuilt), "{name}: after the same edit"); + cached.execute("edit.undo", &json!({})).unwrap(); + rebuilt.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(model(name, &cached), model(name, &rebuilt), "{name}: after undoing it"); + let _ = std::fs::remove_file(&path); + let _ = std::fs::remove_file(format!("{}.bak", path.display())); +} + +#[test] +fn corpus_designs_open_from_their_model_as_evaluated() { + for p in corpus() { + let name = p.file_stem().unwrap_or_default().to_string_lossy().to_string(); + let s = open(&p); + // Names saved before format 14 are found again through names worked out from geometry on + // demand, which a saved model does not keep. + let legacy = s.doc.to_json().contains(&format!("\"{}", solidcraft_engine::doc::naming::LEGACY_MARK)); + if s.model.results.iter().any(|r| r.error.is_some()) || legacy { + // Not kept: a model with errors, or names saved before format 14. + let path = temp(&name); + let mut s = s; + s.execute("file.save_as", &json!({"path": path.to_string_lossy()})).unwrap(); + assert!(solidcraft_engine::io::read_design_geometry(&std::fs::read(&path).unwrap()).is_none(), "{name}"); + let _ = std::fs::remove_file(&path); + let _ = std::fs::remove_file(format!("{}.bak", path.display())); + continue; + } + check(&name, s); + } +} + +#[test] +fn sample_designs_open_from_their_model_as_evaluated() { + for sample in solidcraft_engine::sample::samples() { + let mut s = Session::default(); + for c in (sample.script)()["commands"].as_array().unwrap() { + s.execute(c["command"].as_str().unwrap(), &c["params"]).unwrap_or_else(|e| panic!("{}: {e}", sample.name)); + } + check(sample.name, s); + } +} + +#[test] +fn imported_assemblies_open_from_their_model_as_evaluated() { + // A STEP assembly of the hinge sample: parts placed several times. + let mut source = Session::default(); + let hinge = solidcraft_engine::sample::samples().into_iter().find(|s| s.name == "Hinge Assembly").unwrap(); + for c in (hinge.script)()["commands"].as_array().unwrap() { + source.execute(c["command"].as_str().unwrap(), &c["params"]).unwrap(); + } + let step = std::env::temp_dir().join(format!("solidcraft-model-cache-{}-hinge.step", std::process::id())); + source.execute("file.export", &json!({"path": step.to_string_lossy()})).unwrap(); + let mut s = Session::default(); + s.execute("file.insert_step", &json!({"path": step.to_string_lossy()})).unwrap(); + s.execute("file.insert_step", &json!({"path": step.to_string_lossy(), "matrix": [1, 0, 0, 200, 0, 1, 0, 0, 0, 0, 1, 0]})).unwrap(); + let _ = std::fs::remove_file(&step); + check("imported hinge", s); +} + +/// Opened from its model, a design evaluates only from the first feature an edit changes: the +/// saved states before it are kept as they were read (the same states, not evaluated again). +#[test] +fn an_edit_after_opening_evaluates_from_the_feature_it_changes() { + let plate = solidcraft_engine::sample::samples().into_iter().find(|s| s.name == "Sample Plate").unwrap(); + let mut built = Session::default(); + for c in (plate.script)()["commands"].as_array().unwrap() { + built.execute(c["command"].as_str().unwrap(), &c["params"]).unwrap(); + } + let path = temp("incremental"); + built.execute("file.save_as", &json!({"path": path.to_string_lossy()})).unwrap(); + let n = built.doc.features.len(); + assert!(n >= 4); + let mut s = open(&path); + assert_eq!(s.model.last_recomputed, 0); + let read: Vec> = s.model.results.iter().map(|r| r.state.clone()).collect(); + // How many of the first features still have the states read from the file. + let kept = |s: &Session| s.model.results.iter().zip(&read).take_while(|(r, st)| Arc::ptr_eq(&r.state, st)).count(); + // The marker moved back and forth: the features before it are as read. + s.execute("timeline.rollback", &json!({"position": n - 2})).unwrap(); + assert_eq!(kept(&s), n - 2, "rolled back"); + s.execute("timeline.rollback", &json!({})).unwrap(); + assert_eq!(kept(&s), n, "rolled forward: the features after the marker take their saved results again"); + // Suppressing the second-to-last feature keeps every state before it. + let k = s.doc.features[n - 2].id; + s.execute("timeline.suppress", &json!({"feature": k, "suppressed": true})).unwrap(); + assert_eq!(kept(&s), n - 2, "evaluated from the suppressed feature on"); + s.execute("edit.undo", &json!({})).unwrap(); + // A new feature at the end starts from the final state read from the file. + let mut s = open(&path); + let read: Vec> = s.model.results.iter().map(|r| r.state.clone()).collect(); + s.execute("solid.box", &json!({"length": 3, "width": 3, "height": 3, "operation": "new"})).unwrap(); + assert_eq!(s.model.results.len(), n + 1); + assert!(s.model.results.iter().zip(&read).all(|(r, st)| Arc::ptr_eq(&r.state, st)), "only the new feature evaluated"); + let _ = std::fs::remove_file(&path); + let _ = std::fs::remove_file(format!("{}.bak", path.display())); +} + +/// An edit made after opening and undone finds the saved results again: undo evaluates nothing. +#[test] +fn undoing_an_edit_after_opening_reuses_the_saved_results() { + let plate = solidcraft_engine::sample::samples().into_iter().find(|s| s.name == "Sample Plate").unwrap(); + let mut built = Session::default(); + for c in (plate.script)()["commands"].as_array().unwrap() { + built.execute(c["command"].as_str().unwrap(), &c["params"]).unwrap(); + } + let path = temp("undo"); + built.execute("file.save_as", &json!({"path": path.to_string_lossy()})).unwrap(); + let mut s = open(&path); + let read: Vec> = s.model.results.iter().map(|r| r.state.clone()).collect(); + let first = s.doc.features[1].id; + s.execute("timeline.suppress", &json!({"feature": first, "suppressed": true})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.model.last_recomputed, 0, "taken from the saved results"); + assert!(s.model.results.iter().zip(&read).all(|(r, st)| Arc::ptr_eq(&r.state, st)), "the very states read from the file"); + let _ = std::fs::remove_file(&path); + let _ = std::fs::remove_file(format!("{}.bak", path.display())); +} diff --git a/crates/doc/src/construct.rs b/crates/doc/src/construct.rs index 6c441bf3e..e5f589bb2 100644 --- a/crates/doc/src/construct.rs +++ b/crates/doc/src/construct.rs @@ -92,14 +92,14 @@ pub enum PointDef { } /// Resolved construction geometry, kept in the model state by feature. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ConstructGeom { Plane(Plane), Axis { origin: Vec3, dir: Vec3 }, Point(Vec3), } -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Construct { pub feature: u64, pub name: String, diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 8fa1512ee..82dd4c7db 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -7,7 +7,7 @@ use std::collections::BTreeMap; use std::hash::{Hash, Hasher}; use std::sync::{Arc, OnceLock}; -use serde::Serialize; +use serde::{Deserialize, Serialize}; use solidcraft_geom::tess::TessPlan; use solidcraft_geom::{Mesh, Plane, Region2, UnitVec3, Vec2, Vec3, regions_apart}; use solidcraft_kernel::{self as kernel, Body, BoolOp}; @@ -208,7 +208,7 @@ pub struct SolvedSketch { } /// A cosmetic thread: on which cylinder, its size, and the threaded part of the axis. -#[derive(Clone, Debug, PartialEq, Serialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ThreadInfo { pub feature: u64, pub body: String, @@ -615,7 +615,7 @@ impl ModelState { /// [`quantize`]); the rest keep theirs. fn stamp(&mut self, before: &Arc, f: &Feature, key: u64, mats: Vec) { let feature = f.id; - let depth = before.bodies.iter().filter_map(|b| b.names.origin.as_ref().map(|o| o.depth)).max().unwrap_or(0) + 1; + let depth = before.bodies.iter().filter_map(|b| b.names.depth()).max().unwrap_or(0) + 1; let sheets = if f.kind.is_sheet() { self.sheets.clone() } else { Vec::new() }; let origin = Arc::new(crate::naming::NamingOrigin { feature: f.clone(), before: before.clone(), depth, mats, sheets }); // Pieces a cut left are named after their faces, not the kernel's shell order (unless @@ -4596,8 +4596,11 @@ fn replay( Ok(()) } +#[path = "model_cache.rs"] +mod model_cache; #[path = "eval_more.rs"] mod more; +pub use model_cache::SavedModel; #[path = "eval_surface.rs"] mod surface; diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 163a53433..38bbb4505 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -58,10 +58,10 @@ pub use assembly::{ }; pub use document::*; pub use eval::{ - EdgeRef, FeatureResult, Model, ModelBody, ModelState, PlacedBodies, RevolveExtent, SolvedSketch, ThreadInfo, curve_pick_error, edge_names_for, - edge_refs, face_point_names, face_point_state, hole_direction_at, import_body_names, metric_thread_sizes, object_height, parse_metric_thread, - pattern_matrices, revolve_extent, revolve_extent_with_convention, select_profiles, sketch_hole_direction, sketch_line_plane, state_in_frame, - state_in_frame_at, suggested_thread, through_all_distance, world_state, world_state_reusing, + EdgeRef, FeatureResult, Model, ModelBody, ModelState, PlacedBodies, RevolveExtent, SavedModel, SolvedSketch, ThreadInfo, curve_pick_error, + edge_names_for, edge_refs, face_point_names, face_point_state, hole_direction_at, import_body_names, metric_thread_sizes, object_height, + parse_metric_thread, pattern_matrices, revolve_extent, revolve_extent_with_convention, select_profiles, sketch_hole_direction, sketch_line_plane, + state_in_frame, state_in_frame_at, suggested_thread, through_all_distance, world_state, world_state_reusing, }; pub use expr::Expr; pub use names::{BodyName, FeatureName, SketchId}; diff --git a/crates/doc/src/model_cache.rs b/crates/doc/src/model_cache.rs new file mode 100644 index 000000000..fbd49f87b --- /dev/null +++ b/crates/doc/src/model_cache.rs @@ -0,0 +1,424 @@ +//! A model as a design file keeps it: every feature's result and the state after it, so a design +//! opens without evaluating its timeline again (docs/design-container.md, "Model cache"). +//! +//! The records are JSON; the kernel bodies they hold are a separate list ([`SavedModel::bodies`]), +//! which the file stores in SolidCraft's exact native B-rep encoding. A body that several states +//! hold (one that later features pass through unchanged) is recorded once, as are its face names +//! and the solved sketches the states share. Face names are kept as worked out, not as the +//! history they were worked out from: a model taken from a file names every face as the model +//! that was saved did. + +use super::*; +use crate::history_names::{FaceInfo, Names}; +use serde_json::{Value as Json, json}; +use std::collections::HashMap; + +/// A model's results and states as records, and the kernel bodies they refer to by index. +pub struct SavedModel { + pub records: Json, + pub bodies: Vec, +} + +/// Records refer to these at most. +const MAX_ITEMS: usize = 1_000_000; +/// Bodies and sketches all the states hold together, at most (a state is a list of clones). +const MAX_HELD: usize = 50_000_000; + +fn hex(v: u64) -> String { + format!("{v:016x}") +} + +fn unhex(v: &Json) -> Result { + v.as_str().and_then(|s| u64::from_str_radix(s, 16).ok()).ok_or_else(|| bad("saved model: key")) +} + +fn bad(what: &str) -> DocError { + DocError::Invalid(what.into()) +} + +/// A design whose stored face or edge names were saved before format 14 (marked +/// [`crate::naming::LEGACY_MARK`]) finds them through names worked out from geometry on demand, +/// which a saved model does not keep. +fn has_legacy_names(doc: &Document) -> bool { + let mark = format!("\"{}", crate::naming::LEGACY_MARK); + doc.features.iter().any(|f| match &f.kind { + FeatureKind::Import { .. } => f.face_names.iter().any(|n| n.starts_with(crate::naming::LEGACY_MARK)), + _ => serde_json::to_string(f).is_ok_and(|j| j.contains(&mark)), + }) +} + +/// What tells two model bodies apart in a record: a body a feature passes through unchanged is a +/// clone sharing its mesh cell and names, so this finds it without writing its record again. +#[derive(PartialEq, Eq, Hash)] +struct BodyKey { + mesh: usize, + names: usize, + imported: usize, + key: u64, + feature: u64, + component: u64, + transferred: bool, + name: String, + source_name: Option, + source_transform: [u64; 16], +} + +impl BodyKey { + fn of(b: &ModelBody) -> Self { + let mut source_transform = [0; 16]; + for (bits, v) in source_transform.iter_mut().zip(b.source_transform.iter().flatten()) { + *bits = v.to_bits(); + } + BodyKey { + mesh: Arc::as_ptr(&b.mesh) as usize, + names: b.names.id(), + imported: b.imported.as_ref().map_or(0, |l| Arc::as_ptr(l) as usize), + key: b.key, + feature: b.feature, + component: b.component, + transferred: b.transferred, + name: b.name.clone(), + source_name: b.source_name.clone(), + source_transform, + } + } +} + +/// Indices as runs of consecutive ones (`[first, count]`): a state lists mostly the bodies of the +/// state before it, in order. +fn runs(indices: &[usize]) -> Vec<[usize; 2]> { + let mut out: Vec<[usize; 2]> = Vec::new(); + for &i in indices { + match out.last_mut() { + Some([first, count]) if *first + *count == i => *count += 1, + _ => out.push([i, 1]), + } + } + out +} + +#[derive(Default)] +struct Writer { + bodies: Vec, + model_bodies: Vec, + model_body_index: HashMap, + names: Vec, + names_index: HashMap, + sketches: Vec, + sketch_index: HashMap, + states: Vec, + state_index: HashMap, +} + +impl Writer { + fn names(&mut self, b: &ModelBody) -> usize { + let id = b.names.id(); + if let Some(i) = self.names_index.get(&id) { + return *i; + } + let names = crate::naming::names(b); + let info: Vec = names.info.iter().map(|i| json!([i.aliases, i.bounds, i.verified])).collect(); + self.names.push(json!({"faces": *names.faces, "info": info})); + self.names_index.insert(id, self.names.len() - 1); + self.names.len() - 1 + } + + fn model_body(&mut self, b: &ModelBody) -> Option { + if b.body.is_mesh() { + return None; + } + let key = BodyKey::of(b); + if let Some(i) = self.model_body_index.get(&key) { + return Some(*i); + } + let names = self.names(b); + let mut r = json!({ + "name": b.name, "feature": b.feature, "component": b.component, "key": hex(b.key), "names": names, + }); + if let Some(depth) = b.names.depth() { + r["depth"] = json!(depth); + } + if let Some(source) = &b.source_name { + r["source_name"] = json!(source); + } + if b.source_transform != crate::IDENTITY { + r["source_transform"] = json!(b.source_transform); + } + if b.transferred { + r["transferred"] = json!(true); + } + if let Some(look) = &b.imported { + let faces: Vec = look.faces.iter().map(|(name, (color, opacity))| json!([name, color, opacity])).collect(); + r["imported"] = json!({"color": look.color, "opacity": look.opacity, "faces": faces}); + } + r["body"] = json!(self.bodies.len()); + self.bodies.push(b.body.clone()); + self.model_bodies.push(r); + self.model_body_index.insert(key, self.model_bodies.len() - 1); + Some(self.model_bodies.len() - 1) + } + + fn sketch(&mut self, s: &Arc) -> Option { + let id = Arc::as_ptr(s) as usize; + if let Some(i) = self.sketch_index.get(&id) { + return Some(*i); + } + let r = json!({ + "feature": s.feature, "name": s.name, "plane": serde_json::to_value(s.plane).ok()?, + "sketch": serde_json::to_value(&s.sketch).ok()?, "report": serde_json::to_value(&s.report).ok()?, + }); + self.sketches.push(r); + self.sketch_index.insert(id, self.sketches.len() - 1); + Some(self.sketches.len() - 1) + } + + fn state(&mut self, st: &Arc) -> Option { + let id = Arc::as_ptr(st) as usize; + if let Some(i) = self.state_index.get(&id) { + return Some(*i); + } + let bodies = st.bodies.iter().map(|b| self.model_body(b)).collect::>>()?; + let sketches = st.sketches.iter().map(|s| self.sketch(s)).collect::>>()?; + let r = json!({ + "bodies": runs(&bodies), "sketches": runs(&sketches), "body_counter": st.body_counter, + "sheets": serde_json::to_value(&st.sheets).ok()?, "construct": serde_json::to_value(&st.construct).ok()?, + "threads": serde_json::to_value(&st.threads).ok()?, + "sketch_keys": st.sketch_keys.iter().map(|(f, k)| json!([f, hex(*k)])).collect::>(), + "blend_edges": serde_json::to_value(&st.blend_edges).ok()?, "fitted": serde_json::to_value(&st.fitted).ok()?, + "tapered": serde_json::to_value(&st.tapered).ok()?, + }); + self.states.push(r); + self.state_index.insert(id, self.states.len() - 1); + Some(self.states.len() - 1) + } +} + +impl Model { + /// The model as a design file keeps it: `None` unless it is `doc`'s evaluation without an + /// error, holds no mesh bodies, and `doc` keeps no names saved before format 14. Works out + /// the face names not asked for yet (a saved model keeps them as worked out). + pub fn saved(&self, doc: &Document) -> Option { + if self.results.is_empty() || self.results.iter().any(|r| r.error.is_some()) || !self.is_current(doc) || has_legacy_names(doc) { + return None; + } + kernel::guard("save the model", || { + let mut w = Writer::default(); + let mut features = Vec::with_capacity(self.results.len()); + for r in &self.results { + let state = w.state(&r.state).ok_or_else(|| kernel::KernelError::Invalid("not kept".into()))?; + let mut f = json!({"id": r.id, "fingerprint": hex(r.fingerprint), "ms": r.ms, "skipped": r.skipped, "state": state}); + if let Some(w) = &r.warning { + f["warning"] = json!(w); + } + if r.boolean_diagnostics != kernel::BooleanDiagnostics::default() { + f["diagnostics"] = serde_json::to_value(&r.boolean_diagnostics).map_err(|e| kernel::KernelError::Invalid(e.to_string()))?; + } + features.push(f); + } + let records = json!({ + "features": features, "states": w.states, "model_bodies": w.model_bodies, "names": w.names, "sketches": w.sketches, + }); + Ok(SavedModel { records, bodies: w.bodies }) + }) + .ok() + } +} + +impl SavedModel { + /// The states the records hold, every record checked. + fn states(&self) -> Result>> { + let (records, bodies) = (&self.records, &self.bodies); + let list = |key: &str| records.get(key).and_then(Json::as_array).filter(|l| l.len() <= MAX_ITEMS).ok_or_else(|| bad("saved model: list")); + let index = |v: Option<&Json>, len: usize| { + v.and_then(Json::as_u64).and_then(|i| usize::try_from(i).ok()).filter(|i| *i < len).ok_or_else(|| bad("saved model: index")) + }; + let text = + |v: Option<&Json>| v.and_then(Json::as_str).filter(|s| s.len() <= 1 << 16).map(str::to_owned).ok_or_else(|| bad("saved model: text")); + let parse = |v: Option<&Json>| v.cloned().ok_or_else(|| bad("saved model: missing")); + let mut names = Vec::new(); + for n in list("names")? { + let faces: Vec = serde_json::from_value(parse(n.get("faces"))?).map_err(|_| bad("saved model: names"))?; + let info: Vec<(Vec, std::collections::BTreeSet, bool)> = + serde_json::from_value(parse(n.get("info"))?).map_err(|_| bad("saved model: names"))?; + if info.len() != faces.len() { + return Err(bad("saved model: names")); + } + let info = info.into_iter().map(|(aliases, bounds, verified)| FaceInfo { aliases, bounds, verified }).collect(); + names.push(Arc::new(Names { faces: Arc::new(faces), info })); + } + let mut sketches = Vec::new(); + for s in list("sketches")? { + let sketch: solidcraft_sketch::Sketch = serde_json::from_value(parse(s.get("sketch"))?).map_err(|_| bad("saved model: sketch"))?; + sketches.push(Arc::new(SolvedSketch { + feature: s.get("feature").and_then(Json::as_u64).ok_or_else(|| bad("saved model: sketch"))?, + name: text(s.get("name"))?, + plane: serde_json::from_value(parse(s.get("plane"))?).map_err(|_| bad("saved model: sketch"))?, + report: serde_json::from_value(parse(s.get("report"))?).map_err(|_| bad("saved model: sketch"))?, + profiles: find_profiles(&sketch), + ends: solidcraft_sketch::loose_ends(&sketch), + sketch, + })); + } + let mut model_bodies = Vec::new(); + for r in list("model_bodies")? { + let body = bodies.get(index(r.get("body"), bodies.len())?).cloned().ok_or_else(|| bad("saved model: body"))?; + let mut b = + ModelBody::new(text(r.get("name"))?, body, r.get("feature").and_then(Json::as_u64).ok_or_else(|| bad("saved model: feature"))?); + b.component = r.get("component").and_then(Json::as_u64).ok_or_else(|| bad("saved model: component"))?; + b.key = unhex(r.get("key").unwrap_or(&Json::Null))?; + let depth = + r.get("depth").map(|d| d.as_u64().and_then(|d| usize::try_from(d).ok()).ok_or_else(|| bad("saved model: depth"))).transpose()?; + b.names = crate::naming::NameCell::saved( + names.get(index(r.get("names"), names.len())?).cloned().ok_or_else(|| bad("saved model: names"))?, + depth, + ); + b.source_name = r.get("source_name").map(|s| text(Some(s))).transpose()?; + if let Some(m) = r.get("source_transform") { + let m: crate::Mat = serde_json::from_value(m.clone()).map_err(|_| bad("saved model: transform"))?; + if m.iter().flatten().any(|x| !x.is_finite()) { + return Err(bad("saved model: transform")); + } + b.source_transform = m; + } + b.transferred = r.get("transferred").and_then(Json::as_bool).unwrap_or(false); + // Measured once here, so every state holding it adds it up for the cache's budget. + b.bytes = b.body.retained_bytes(); + if let Some(look) = r.get("imported") { + let faces: Vec<(String, [f32; 3], f32)> = serde_json::from_value(parse(look.get("faces"))?).map_err(|_| bad("saved model: look"))?; + b.imported = Some(Arc::new(crate::appearance::ImportedLook { + color: serde_json::from_value(parse(look.get("color"))?).map_err(|_| bad("saved model: look"))?, + opacity: serde_json::from_value(parse(look.get("opacity"))?).map_err(|_| bad("saved model: look"))?, + faces: faces.into_iter().map(|(name, color, opacity)| (name, (color, opacity))).collect(), + })); + } + model_bodies.push(b); + } + let mut states = Vec::new(); + let mut held = 0usize; + for s in list("states")? { + // Runs of consecutive indices, each within the list it indexes. + let ids = |key: &str, len: usize| -> Result> { + let mut out = Vec::new(); + for run in s.get(key).and_then(Json::as_array).ok_or_else(|| bad("saved model: state"))? { + let first = index(run.get(0), len)?; + let count = run.get(1).and_then(Json::as_u64).and_then(|n| usize::try_from(n).ok()).ok_or_else(|| bad("saved model: run"))?; + if first.checked_add(count).is_none_or(|end| end > len) || out.len().saturating_add(count) > MAX_ITEMS { + return Err(bad("saved model: run")); + } + out.extend(first..first + count); + } + Ok(out) + }; + let field = |key: &str| parse(s.get(key)); + let invalid = |_| bad("saved model: state"); + let mut sketch_keys = BTreeMap::new(); + for k in s.get("sketch_keys").and_then(Json::as_array).ok_or_else(|| bad("saved model: state"))? { + sketch_keys + .insert(k.get(0).and_then(Json::as_u64).ok_or_else(|| bad("saved model: state"))?, unhex(k.get(1).unwrap_or(&Json::Null))?); + } + let st = ModelState { + bodies: ids("bodies", model_bodies.len())?.into_iter().filter_map(|i| model_bodies.get(i).cloned()).collect(), + sketches: ids("sketches", sketches.len())?.into_iter().filter_map(|i| sketches.get(i).cloned()).collect(), + body_counter: index(s.get("body_counter"), usize::MAX)?, + sheets: serde_json::from_value(field("sheets")?).map_err(invalid)?, + construct: serde_json::from_value(field("construct")?).map_err(invalid)?, + threads: serde_json::from_value(field("threads")?).map_err(invalid)?, + sketch_keys, + blend_edges: serde_json::from_value(field("blend_edges")?).map_err(invalid)?, + fitted: serde_json::from_value(field("fitted")?).map_err(invalid)?, + tapered: serde_json::from_value(field("tapered")?).map_err(invalid)?, + }; + held = held.saturating_add(st.bodies.len()).saturating_add(st.sketches.len()); + if held > MAX_HELD { + return Err(bad("saved model: states")); + } + states.push(Arc::new(st)); + } + Ok(states) + } + + /// The model's final state (what a picture of it shows), without checking that it is a + /// document's evaluation. + pub fn final_state(&self) -> Result> { + let states = self.states()?; + let features = self.records.get("features").and_then(Json::as_array).ok_or_else(|| bad("saved model: features"))?; + let last = features.iter().rev().find(|f| f.get("skipped").and_then(Json::as_bool) == Some(false)); + match last { + Some(f) => f + .get("state") + .and_then(Json::as_u64) + .and_then(|i| states.get(usize::try_from(i).ok()?)) + .cloned() + .ok_or_else(|| bad("saved model: state")), + None => Ok(Arc::new(ModelState::default())), + } + } +} + +impl Model { + /// The model a design file kept for `doc` ([`Model::saved`]), taken as `doc`'s evaluation: + /// every feature's result as saved, nothing evaluated. Refused (an error) unless every + /// feature's fingerprint is the one `doc` gives it now, and every record is well formed. + pub fn adopt(doc: &Document, saved: &SavedModel) -> Result { + let states = saved.states()?; + let records = &saved.records; + let index = |v: Option<&Json>, len: usize| { + v.and_then(Json::as_u64).and_then(|i| usize::try_from(i).ok()).filter(|i| *i < len).ok_or_else(|| bad("saved model: index")) + }; + let text = + |v: Option<&Json>| v.and_then(Json::as_str).filter(|s| s.len() <= 1 << 16).map(str::to_owned).ok_or_else(|| bad("saved model: text")); + let features = records.get("features").and_then(Json::as_array).ok_or_else(|| bad("saved model: features"))?; + if features.len() != doc.features.len() { + return Err(bad("saved model: features")); + } + let (vals, param_errors) = evaluation_values(doc); + let step_digests = StepDigests::of(doc, &StepDigests::default()); + let marker = doc.marker.unwrap_or(usize::MAX); + let ctx = context_digest(doc, &vals); + let mut cache = EvalCache::default(); + let mut before = Arc::new(ModelState::default()); + let mut prev = 0; + let mut results = Vec::with_capacity(features.len()); + for (i, (f, r)) in doc.features.iter().zip(features).enumerate() { + prev = chain_fingerprint(doc, &vals, f, prev, i >= marker, &step_digests); + if r.get("id").and_then(Json::as_u64) != Some(f.id) || unhex(r.get("fingerprint").unwrap_or(&Json::Null))? != prev { + return Err(bad("saved model: the document changed")); + } + let ms = r.get("ms").and_then(Json::as_f64).filter(|ms| ms.is_finite()).ok_or_else(|| bad("saved model: time"))?; + let result = FeatureResult { + id: f.id, + name: f.name.clone(), + error: None, + warning: r.get("warning").map(|w| text(Some(w))).transpose()?, + boolean_diagnostics: match r.get("diagnostics") { + Some(d) => serde_json::from_value(d.clone()).map_err(|_| bad("saved model: diagnostics"))?, + None => Default::default(), + }, + ms, + skipped: r.get("skipped").and_then(Json::as_bool).ok_or_else(|| bad("saved model: skipped"))?, + stale: false, + fingerprint: prev, + state: states.get(index(r.get("state"), states.len())?).cloned().ok_or_else(|| bad("saved model: state"))?, + }; + // Each result where an evaluation would have put it, so an edit undone (or set back) + // finds it again rather than evaluating the feature anew. + if !result.skipped { + let local = fingerprint(0, f, &vals, false, &step_digests) ^ placement_digest(doc, f); + cache.put( + cache_key(f, prev, local, ctx, &before), + CachedEval { + error: None, + warning: result.warning.clone(), + boolean_diagnostics: result.boolean_diagnostics.clone(), + ms, + bytes: result.state.retained_bytes(), + state: result.state.clone(), + }, + ); + before = result.state.clone(); + } + results.push(result); + } + Ok(Model { results, param_errors, step_digests, cache: Arc::new(std::sync::Mutex::new(cache)), ..Model::default() }) + } +} diff --git a/crates/doc/src/naming.rs b/crates/doc/src/naming.rs index 263b4bb6b..71d32e6ee 100644 --- a/crates/doc/src/naming.rs +++ b/crates/doc/src/naming.rs @@ -46,6 +46,9 @@ pub struct NameCell { legacy: Arc>>>, /// The body this one is a moved copy of (its legacy names are that body's). copy_of: Option>, + /// How deep the chain of features that named it is, for names taken from a saved model + /// (which has no origin): see [`NameCell::depth`]. + saved_depth: Option, } impl NameCell { @@ -69,6 +72,19 @@ impl NameCell { pub fn same(body: &ModelBody) -> Self { NameCell { copy_of: Some(Arc::new(body.clone())), ..NameCell::default() } } + /// Names a saved model kept (worked out when it was saved), at `depth` in the chain of + /// features that named them. + pub(crate) fn saved(names: Arc, depth: Option) -> Self { + NameCell { saved_depth: depth, ..Self::shared(names) } + } + /// How deep the chain of features that named the body is (`None`: not made by a feature). + pub(crate) fn depth(&self) -> Option { + self.origin.as_ref().map(|o| o.depth).or(self.saved_depth) + } + /// Identity of the names: clones of a cell share them. + pub(crate) fn id(&self) -> usize { + Arc::as_ptr(&self.names) as usize + } fn shared(names: Arc) -> Self { let cell = OnceLock::new(); let _ = cell.set(names); diff --git a/crates/doc/src/sheet.rs b/crates/doc/src/sheet.rs index b4bfd40af..130e26547 100644 --- a/crates/doc/src/sheet.rs +++ b/crates/doc/src/sheet.rs @@ -316,7 +316,7 @@ impl SheetSettings { /// The shape of the relief cut where two bends meet at a corner of the base (a rule's /// `corner_relief_shape`). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum ReliefShape { /// Nothing is cut: the bends end square at the corner. @@ -418,7 +418,7 @@ impl Document { } /// A flange: a bend along a panel edge and the flat panel past it (flat coordinates). -#[derive(Clone, Debug, PartialEq, Serialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SheetFlange { /// The flange it hangs off (None = the base panel). pub parent: Option, @@ -469,7 +469,7 @@ pub struct EdgeFlange { } /// A sheet metal body (see the module docs). -#[derive(Clone, Debug, PartialEq, Serialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SheetBody { pub body: String, pub rule: String, @@ -483,21 +483,21 @@ pub struct SheetBody { pub holes: Vec, /// Planar machining in flat coordinates, with depths measured from the flat bottom. /// Derived from feature history; these records are not a document schema change. - #[serde(skip_serializing_if = "Vec::is_empty")] + #[serde(default, skip_serializing_if = "Vec::is_empty")] pub pockets: Vec, /// Straight bores drilled into a panel along its plane (a hole into a rim), in flat /// coordinates, each kept inside its own panel's material so the folded part and its flat /// pattern both carry it (#560). Derived from feature history, like `pockets`. - #[serde(skip_serializing_if = "Vec::is_empty")] + #[serde(default, skip_serializing_if = "Vec::is_empty")] pub bores: Vec, /// Perforation fields (#732), flat coordinates; their holes are computed on demand and never cut into the B-rep. - #[serde(skip_serializing_if = "Vec::is_empty")] + #[serde(default, skip_serializing_if = "Vec::is_empty")] pub perforations: Vec, /// Regions (flat coordinates) that text cut or machined, letters with their counters as /// holes: a record of where the sheet's text went, so that its DXF can write the letters on /// layers of their own (see [`SheetBody::letters`]). The cut-outs and pockets themselves are /// in `holes` and `pockets`. Derived from feature history, like `pockets`. - #[serde(skip_serializing_if = "Vec::is_empty")] + #[serde(default, skip_serializing_if = "Vec::is_empty")] pub labels: Vec, /// Unfolded. pub flat: bool, @@ -524,7 +524,7 @@ pub struct SheetBody { /// A straight round bore of one panel (None = the base), in flat coordinates: a cylinder from /// `base` along the unit `axis` for `height`, cut only from that panel's material. -#[derive(Clone, Copy, Debug, PartialEq, Serialize)] +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] pub struct SheetBore { pub panel: Option, pub base: Vec3, @@ -534,7 +534,7 @@ pub struct SheetBore { } /// A perforation field from a `sheet.perforate` feature (#732). -#[derive(Clone, Debug, PartialEq, Serialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SheetPerforation { pub feature: u64, pub diameter: f64, @@ -543,7 +543,7 @@ pub struct SheetPerforation { pub square: bool, } -#[derive(Clone, Debug, PartialEq, Serialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SheetPocket { pub region: Region2, pub z0: f64, diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 100c6435b..73d3daa66 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -267,11 +267,11 @@ fn open(s: &mut Session, p: &Value) -> Result { } return Ok(out); } - let mut doc = solidcraft_io::read_design_file(path, s.open_preview.take()).map_err(|e| EngineError::Other(format!("{path}: {e}")))?; + let (mut doc, saved) = solidcraft_io::read_design_file(path, s.open_preview.take()).map_err(|e| EngineError::Other(format!("{path}: {e}")))?; if let Some(stem) = default_name_for(&doc.name, path) { doc.name = stem; } - s.replace_design(Session::new(doc)); + s.replace_design(Session::opened(doc, saved.as_ref())); s.path = Some(path.to_string()); let errors = s.model.results.iter().filter(|r| r.error.is_some()).count(); Ok(json!({"path": path, "features": s.doc.features.len(), "errors": errors, "name": s.doc.name})) @@ -405,17 +405,17 @@ impl Session { let geometry = cache.then(|| saved_geometry(self, &design)).flatten(); let preview = preview.then(|| saved_preview(self)).flatten(); let thumbnail = cache.then(|| thumbnail::saved(self)).flatten(); - solidcraft_io::write_design_container_with_thumbnail(&design, compression, preview.as_ref(), geometry.as_deref(), thumbnail.as_deref()) + solidcraft_io::write_design_container_with_thumbnail(&design, compression, preview.as_ref(), geometry.as_ref(), thumbnail.as_deref()) } } /// The evaluated model a save keeps, so opening need not rebuild it: only the finished evaluation /// of `design`, the document saved (no sketch being edited, no uncaptured moves, no feature errors). -fn saved_geometry(s: &Session, design: &Document) -> Option> { - if s.active_sketch.is_some() || !s.pending_moves.is_empty() || s.model.results.iter().any(|r| r.error.is_some()) || !s.model.is_current(design) { +fn saved_geometry(s: &Session, design: &Document) -> Option { + if s.active_sketch.is_some() || !s.pending_moves.is_empty() || s.model.state().bodies.is_empty() { return None; } - Some(s.model.state()).filter(|st| !st.bodies.is_empty()) + s.model.saved(design) } /// Cache only warm display geometry. A save never waits for an unevaluated mesh. @@ -849,36 +849,37 @@ mod tests { } #[test] - fn native_cache_does_not_force_meshes_or_supply_editing_state() { - let mut session = Session::new(Document::new("Native cache authority")); + fn saved_model_needs_no_meshes_and_is_adopted_only_for_its_document() { + let mut session = Session::new(Document::new("Saved model")); session.execute("solid.box", &json!({"length":10,"width":20,"height":30})).unwrap(); let world = session.world_state(); assert!(world.bodies.iter().all(|b| b.cached_mesh().is_none())); - let mut cached = (*saved_geometry(&session, &session.doc).unwrap()).clone(); let bytes = session.design_container(solidcraft_io::DesignCompression::Fast, false, true).unwrap(); - assert!(world.bodies.iter().all(|b| b.cached_mesh().is_none()), "saving native geometry must not triangulate"); + assert!(world.bodies.iter().all(|b| b.cached_mesh().is_none()), "saving the model must not triangulate"); assert!(solidcraft_io::read_design_geometry(&bytes).is_some()); assert!( solidcraft_io::read_design_geometry(&session.design_container(solidcraft_io::DesignCompression::Fast, false, false).unwrap()).is_none() ); - cached.bodies[0].body = solidcraft_kernel::box_solid(solidcraft_geom::Vec3::ZERO, solidcraft_geom::Vec3::new(100., 100., 100.)).unwrap(); - let bytes = - solidcraft_io::write_design_container_with_cache(&session.doc, solidcraft_io::DesignCompression::Fast, None, Some(&cached)).unwrap(); - let path = std::env::temp_dir().join(format!("solidcraft-native-forged-{}.solidcraft", std::process::id())); - std::fs::write(&path, bytes).unwrap(); - let seen = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); - let callback_seen = seen.clone(); - let mut reopened = Session { - open_preview: Some(Box::new(move |p| { - callback_seen.store(!p.meshes.is_empty(), std::sync::atomic::Ordering::Relaxed); - })), - ..Session::default() - }; + let path = std::env::temp_dir().join(format!("solidcraft-saved-model-{}.solidcraft", std::process::id())); + std::fs::write(&path, &bytes).unwrap(); + let mut reopened = Session::default(); reopened.execute("doc.open", &json!({"path":path})).unwrap(); - assert!(seen.load(std::sync::atomic::Ordering::Relaxed)); assert_eq!(reopened.doc, session.doc); + assert!(reopened.model.results.iter().all(|r| r.ms == session.model.results[0].ms), "taken from the file, not evaluated"); let measured = reopened.execute("inspect.measure", &json!({})).unwrap(); assert!((measured["bodies"][0]["volume_mm3"].as_f64().unwrap() - 6000.).abs() < 1e-6); + // The model of another document (a value edited in the file) is not taken: the design is + // evaluated. + let mut changed = (*session.doc).clone(); + if let Some(solidcraft_doc::FeatureKind::Box { length, .. }) = changed.features.last_mut().map(|f| &mut f.kind) { + *length = "20".into(); + } + let saved = saved_geometry(&session, &session.doc).unwrap(); + let other = solidcraft_io::write_design_container_with_cache(&changed, solidcraft_io::DesignCompression::Fast, None, Some(&saved)).unwrap(); + std::fs::write(&path, other).unwrap(); + reopened.execute("doc.open", &json!({"path":path})).unwrap(); + let measured = reopened.execute("inspect.measure", &json!({})).unwrap(); + assert!((measured["bodies"][0]["volume_mm3"].as_f64().unwrap() - 12000.).abs() < 1e-6); std::fs::remove_file(path).unwrap(); } @@ -1061,7 +1062,8 @@ mod tests { for x in [0, 20, 40] { s.execute("solid.box", &json!({"length":10,"width":10,"height":10,"corner":[x,0,0]})).unwrap(); } - s.execute("file.save", &json!({"path":path})).unwrap(); + // Without its model: the timeline is evaluated (and watched) as it opens. + s.execute("file.save", &json!({"path":path, "cache": false})).unwrap(); let progress = Arc::new(Progress::default()); let mut opened = Session::default(); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index a11fba4af..e34aeb615 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -359,12 +359,25 @@ impl Default for Session { } impl Session { - pub fn new(mut doc: Document) -> Self { + pub fn new(doc: Document) -> Self { + Self::opened(doc, None) + } + + /// A session on `doc` whose evaluation is the model its file kept (`saved`), when that is + /// `doc`'s evaluation ([`Model::adopt`]); otherwise the timeline is evaluated. + /// `SOLIDCRAFT_NO_MODEL_CACHE` set always evaluates. + pub fn opened(mut doc: Document, saved: Option<&solidcraft_doc::SavedModel>) -> Self { // The session keeps what is hidden (not an undo step); the design file carries it. let visibility = std::mem::take(&mut doc.visibility); let doc = Arc::new(doc); - let mut model = Model::new(); - model.evaluate(&doc); + let adopted = saved + .filter(|_| solidcraft_geom::env::var_os("NO_MODEL_CACHE").is_none()) + .and_then(|saved| Model::adopt(&doc, saved).map_err(|e| log::info!("the saved model is not used: {e}")).ok()); + let model = adopted.unwrap_or_else(|| { + let mut model = Model::new(); + model.evaluate(&doc); + model + }); Session { saved: doc.clone(), doc, diff --git a/crates/io/src/design.rs b/crates/io/src/design.rs index 50a457fe2..510d800d7 100644 --- a/crates/io/src/design.rs +++ b/crates/io/src/design.rs @@ -113,7 +113,7 @@ pub fn write_design_container_with_cache( doc: &Document, compression: DesignCompression, preview: Option<&DesignPreview>, - geometry: Option<&solidcraft_doc::ModelState>, + geometry: Option<&solidcraft_doc::SavedModel>, ) -> Result> { write_design_container_with_thumbnail(doc, compression, preview, geometry, None) } @@ -124,7 +124,7 @@ pub fn write_design_container_with_thumbnail( doc: &Document, compression: DesignCompression, preview: Option<&DesignPreview>, - geometry: Option<&solidcraft_doc::ModelState>, + geometry: Option<&solidcraft_doc::SavedModel>, thumbnail: Option<&[u8]>, ) -> Result> { write_container(doc, compression, preview, geometry, thumbnail, MAX_DESIGN_BYTES) @@ -136,7 +136,7 @@ fn write_container( doc: &Document, compression: DesignCompression, preview: Option<&DesignPreview>, - geometry: Option<&solidcraft_doc::ModelState>, + geometry: Option<&solidcraft_doc::SavedModel>, thumbnail: Option<&[u8]>, budget: usize, ) -> Result> { @@ -510,7 +510,7 @@ impl DesignContainerReader { // fallback, generating a bounded provisional mesh without source imports. read_preview(&mut self.reader).ok().or_else(|| { let document = self.reader.document(16 << 20).ok()?; - native_cache::geometry_preview(&document, self.geometry()?).ok() + native_cache::geometry_preview(&document, &self.geometry()?).ok() }) } @@ -519,8 +519,8 @@ impl DesignContainerReader { thumbnail::read(&mut self.reader).ok() } - /// The cached model state, when this build wrote it for exactly this document. - pub fn geometry(&mut self) -> Option { + /// The saved model, when this build wrote it for exactly this document. + pub fn geometry(&mut self) -> Option { let document = self.reader.document(16 << 20).ok()?; native_cache::read_geometry_with(&mut self.reader, &document).ok() } @@ -536,9 +536,11 @@ pub(super) fn read(bytes: &[u8]) -> Result { } /// Open from disk (or browser VFS), publishing only provisional display before -/// authoritative blob hydration. Desktop keeps one seekable file handle instead -/// of buffering the complete archive. JSON continues through the normal migrations. -pub fn read_design_file(path: &str, notify: Option) -> Result { +/// authoritative blob hydration, with the model the file keeps when this build saved it for +/// exactly this document ([`solidcraft_doc::Model::adopt`] takes it as the evaluation). Desktop +/// keeps one seekable file handle instead of buffering the complete archive. JSON continues +/// through the normal migrations. +pub fn read_design_file(path: &str, notify: Option) -> Result<(Document, Option)> { #[cfg(not(target_arch = "wasm32"))] let mut source = { crate::vfs::check(path).map_err(invalid)?; @@ -569,16 +571,19 @@ pub fn read_design_file(path: &str, notify: Option) source.seek(SeekFrom::Start(0)).map_err(invalid)?; if is_design_container(&prefix) { let mut reader = DesignContainerReader::new(source)?; + // A design with its model opens without a picture first: the model is the session. + let model = reader.geometry(); if let Some(notify) = notify - && let Some(preview) = reader.preview() + && model.is_none() + && let Ok(preview) = read_preview(&mut reader.reader) { notify(preview); } - reader.read_document() + Ok((reader.read_document()?, model)) } else { let mut bytes = Vec::new(); source.take(MAX_DESIGN_BYTES as u64 + 1).read_to_end(&mut bytes).map_err(invalid)?; - crate::read_design(&bytes) + Ok((crate::read_design(&bytes)?, None)) } } @@ -717,15 +722,31 @@ mod tests { #[test] fn file_reader_refuses_nonfiles_before_notifying_preview() { let directory = std::env::temp_dir(); - let result = read_design_file(directory.to_str().unwrap(), Some(|_| panic!("non-file supplied a preview"))); + let result = read_design_file(directory.to_str().unwrap(), Some(|_| panic!("non-file supplied a preview"))).map(|(doc, _)| doc); assert!(result.is_err_and(|e| e.to_string().contains("not a regular file"))); } - fn native_geometry() -> solidcraft_doc::ModelState { - let cube = solidcraft_kernel::box_solid(solidcraft_geom::Vec3::ZERO, solidcraft_geom::Vec3::new(10., 20., 30.)).unwrap(); - let mut state = solidcraft_doc::ModelState::default(); - state.bodies.push(solidcraft_doc::ModelBody::new("Cube".into(), cube, 1)); - state + /// A saved model of one state holding `bodies` (no document evaluated it: enough for the + /// container, which stores whatever model it is given). + fn saved_model(bodies: Vec) -> solidcraft_doc::SavedModel { + let records: Vec = (0..bodies.len()) + .map(|i| json!({"name": format!("Body{i}"), "feature": 1, "component": 0, "key": "0000000000000001", "names": 0, "body": i})) + .collect(); + let state = json!({ + "bodies": [[0, bodies.len()]], "sketches": [], "body_counter": 7, "sheets": [], "construct": [], "threads": [], + "sketch_keys": [], "blend_edges": {}, "fitted": {}, "tapered": {}, + }); + solidcraft_doc::SavedModel { + records: json!({ + "features": [{"id": 1, "fingerprint": "0000000000000000", "ms": 0.0, "skipped": false, "state": 0}], + "states": [state], "model_bodies": records, "names": [{"faces": [], "info": []}], "sketches": [], + }), + bodies, + } + } + + fn native_geometry() -> solidcraft_doc::SavedModel { + saved_model(vec![solidcraft_kernel::box_solid(solidcraft_geom::Vec3::ZERO, solidcraft_geom::Vec3::new(10., 20., 30.)).unwrap()]) } #[test] @@ -739,7 +760,7 @@ mod tests { let entries = parts(&bytes); assert!(entries.contains_key("cache/bodies.bin")); assert!(!entries.contains_key("cache/preview.bin")); - assert_eq!(read_design_geometry(&bytes).unwrap().bodies[0].body.face_count(), bodies.bodies[0].body.face_count()); + assert_eq!(read_design_geometry(&bytes).unwrap().bodies[0].body.face_count(), bodies.bodies[0].face_count()); assert_eq!(bytes, write_design_container_with_cache(&doc, DesignCompression::Fast, None, Some(&bodies)).unwrap()); let count = std::rc::Rc::new(std::cell::Cell::new(0)); let mut reader = DesignContainerReader::new(CountingReader { source: Cursor::new(bytes), count: count.clone() }).unwrap(); @@ -754,34 +775,26 @@ mod tests { use solidcraft_geom::Vec3; let part = solidcraft_kernel::box_solid(Vec3::ZERO, Vec3::new(10., 20., 30.)).unwrap(); let share = solidcraft_kernel::DisplayShare::new(part.clone()); - let t = [[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [50., 0., 0., 1.]]; - let mut state = solidcraft_doc::ModelState::default(); - state.body_counter = 7; - for (i, body) in [part.clone(), part.clone()].into_iter().enumerate() { - state.bodies.push(solidcraft_doc::ModelBody::new(format!("Part {i}"), body, 1)); - } + let mut bodies = vec![part.clone(), part.clone()]; for x in [50., 90.] { let moved = solidcraft_kernel::transform(&part, Vec3::new(x, 0., 0.), Vec3::ZERO, Vec3::Z, 0.).unwrap(); - let mut t = t; - t[3][0] = x; - let mut b = solidcraft_doc::ModelBody::new(format!("Copy {x}"), moved.with_display_share(&share, t), 2); - b.component = 3; - b.source_name = Some("Part".into()); - state.bodies.push(b); + let t = [[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [x, 0., 0., 1.]]; + bodies.push(moved.with_display_share(&share, t)); } + let model = saved_model(bodies); let doc = document(); - let bytes = write_design_container_with_cache(&doc, DesignCompression::Fast, None, Some(&state)).unwrap(); + let bytes = write_design_container_with_cache(&doc, DesignCompression::Fast, None, Some(&model)).unwrap(); let manifest: Value = serde_json::from_slice(&parts(&bytes)["cache/model.json"]).unwrap(); - assert_eq!(manifest["bodies"].as_array().unwrap().len(), 3, "the part and each placed copy, once each"); - let read = read_design_geometry(&bytes).unwrap(); - assert_eq!(read.body_counter, 7); - assert_eq!(read.bodies.iter().map(|b| b.name.as_str()).collect::>(), ["Part 0", "Part 1", "Copy 50", "Copy 90"]); - let copies: Vec<_> = read.bodies[2..].iter().map(|b| b.body.display_share().unwrap()).collect(); + assert_eq!(manifest["slices"].as_array().unwrap().len(), 3, "the part and each placed copy, once each"); + let read = DesignContainerReader::new(Cursor::new(&bytes)).unwrap().geometry().unwrap(); + assert_eq!(read.records, model.records); + assert_eq!(read_design_geometry(&bytes).unwrap().body_counter, 7); + let copies: Vec<_> = read.bodies[2..].iter().map(|b| b.display_share().unwrap()).collect(); assert_eq!(copies[0].0.id(), copies[1].0.id(), "copies show one display again"); assert_eq!(copies[1].1[3][0], 90.); - assert_eq!((read.bodies[3].component, read.bodies[3].source_name.as_deref(), read.bodies[3].feature), (3, Some("Part"), 2)); - for (a, b) in state.bodies.iter().zip(&read.bodies) { - assert_eq!(solidcraft_kernel::encode_native_body(&a.body).unwrap(), solidcraft_kernel::encode_native_body(&b.body).unwrap()); + assert!(read.bodies[0].display_share().is_none()); + for (a, b) in model.bodies.iter().zip(&read.bodies) { + assert_eq!(solidcraft_kernel::encode_native_body(a).unwrap(), solidcraft_kernel::encode_native_body(b).unwrap()); } } diff --git a/crates/io/src/design/native_cache.rs b/crates/io/src/design/native_cache.rs index 3450e7c1a..7005349f0 100644 --- a/crates/io/src/design/native_cache.rs +++ b/crates/io/src/design/native_cache.rs @@ -1,10 +1,11 @@ -//! The model cache: the evaluated bodies of a design's timeline, saved with it so opening need -//! not rebuild them. Its SolidCraft schema is independent of the producing kernel; its key ties it -//! to the exact document, build and platform that computed it (docs/design-container.md). +//! The model cache: a design's evaluated timeline (every feature's result and the state after +//! it, [`SavedModel`]), saved with it so opening need not evaluate it again. Bodies use +//! SolidCraft's exact native B-rep encoding; the key ties the cache to the exact document, build +//! and platform that computed it (docs/design-container.md). use super::*; -use solidcraft_doc::{ModelBody, ModelState}; +use solidcraft_doc::{ModelState, SavedModel}; -const FORMAT: &str = "solidcraft-model-cache/1"; +const FORMAT: &str = "solidcraft-model-cache/2"; const PRODUCER: &str = "solidcraft-truck-adapter/3"; const MANIFEST: &str = "cache/model.json"; const PAYLOAD: &str = "cache/bodies.bin"; @@ -25,53 +26,25 @@ fn matrix(t: &[[f64; 4]; 4]) -> Vec { t.iter().flatten().copied().collect() } -fn look(look: &solidcraft_doc::appearance::ImportedLook) -> Value { - let faces: Vec = look.faces.iter().map(|(name, (color, opacity))| json!([name, color, opacity])).collect(); - json!({"color": look.color, "opacity": look.opacity, "faces": faces}) -} - -fn load_look(v: &Value) -> Result { - let unit = |x: f32| x.is_finite() && (0.0..=1.0).contains(&x); - let color = |v: &Value| -> Result> { - let c: Option<[f32; 3]> = serde_json::from_value(v.clone()).map_err(invalid)?; - if c.is_some_and(|c| !c.iter().copied().all(unit)) { - return Err(invalid("cached colour")); - } - Ok(c) - }; - let opacity: Option = serde_json::from_value(v.get("opacity").cloned().unwrap_or(Value::Null)).map_err(invalid)?; - if opacity.is_some_and(|o| !unit(o)) { - return Err(invalid("cached opacity")); - } - let mut faces = BTreeMap::new(); - for f in v.get("faces").and_then(Value::as_array).ok_or_else(|| invalid("cached face looks"))? { - let name = f.get(0).and_then(Value::as_str).filter(|n| n.len() <= 1024).ok_or_else(|| invalid("cached face name"))?; - let c = color(f.get(1).unwrap_or(&Value::Null))?.ok_or_else(|| invalid("cached face colour"))?; - let o = f.get(2).and_then(Value::as_f64).map(|o| o as f32).filter(|o| unit(*o)).ok_or_else(|| invalid("cached face opacity"))?; - faces.insert(name.to_owned(), (c, o)); - } - Ok(solidcraft_doc::appearance::ImportedLook { color: color(v.get("color").unwrap_or(&Value::Null))?, opacity, faces }) -} - -/// Encode a model state's bodies. Identical bodies (the same part placed many times, a body a -/// feature passed through) are stored once; a placed copy of a part records the part and its -/// matrix, so it shows that part's display as it did before saving. -pub(super) fn encode_model(state: &ModelState, document: &[u8]) -> Result<(Vec, Vec)> { - if state.bodies.is_empty() || state.bodies.len() > MAX_RECORDS { +/// Encode a saved model. Identical bodies (the same part placed many times) are stored once; a +/// placed copy of a part records the part and its matrix, so it shows that part's display as it +/// did before saving. +pub(super) fn encode_model(model: &SavedModel, document: &[u8]) -> Result<(Vec, Vec)> { + if model.bodies.is_empty() || model.bodies.len() > MAX_RECORDS { return Err(invalid("cached body count")); } // What to encode: every body, and the part every placed copy shows. let mut shares: Vec = Vec::new(); let mut share_index = std::collections::HashMap::new(); - for b in &state.bodies { - if let Some((share, _)) = b.body.display_share() { + for b in &model.bodies { + if let Some((share, _)) = b.display_share() { share_index.entry(share.id()).or_insert_with(|| { shares.push(share.clone()); shares.len() - 1 }); } } - let bodies: Vec<&solidcraft_kernel::Body> = state.bodies.iter().map(|b| &b.body).chain(shares.iter().map(|s| s.original())).collect(); + let bodies: Vec<&solidcraft_kernel::Body> = model.bodies.iter().chain(shares.iter().map(|s| s.original())).collect(); let encoded = solidcraft_kernel::map_on_threads(&bodies, 16, |b| solidcraft_kernel::encode_native_body(b).ok()); let mut data = Vec::new(); let mut slices = Vec::new(); @@ -90,35 +63,18 @@ pub(super) fn encode_model(state: &ModelState, document: &[u8]) -> Result<(Vec 1024 { - return Err(invalid("cached body name")); - } - let mut r = json!({"name": b.name, "body": i, "feature": b.feature, "component": b.component}); - if let Some(source) = &b.source_name { - r["source_name"] = json!(source); - } - if b.source_transform != solidcraft_doc::IDENTITY { - r["source_transform"] = json!(matrix(&b.source_transform)); - } - if b.transferred { - r["transferred"] = json!(true); - } - if let Some(l) = &b.imported { - r["imported"] = look(l); - } - if let Some((share, t)) = b.body.display_share() { - let s = share_index.get(&share.id()).ok_or_else(|| invalid("display share"))?; - r["share"] = json!([s, matrix(&t)]); - } - records.push(r); + let (body_index, share_body) = index.split_at(model.bodies.len()); + let mut table = Vec::with_capacity(model.bodies.len()); + for (b, i) in model.bodies.iter().zip(body_index) { + table.push(match b.display_share() { + Some((share, t)) => json!([i, share_index.get(&share.id()).ok_or_else(|| invalid("display share"))?, matrix(&t)]), + None => json!([i]), + }); } let manifest = serde_json::to_vec(&json!({ "format": FORMAT, "producer": PRODUCER, "app": env!("CARGO_PKG_VERSION"), "build": build(), "document": digest(document), "payload": digest(&data), - "bodies": slices, "shares": share_body, "body_counter": state.body_counter, "state": records, + "slices": slices, "shares": share_body, "bodies": table, "model": model.records, })) .map_err(invalid)?; if manifest.len() > MAX_MANIFEST { @@ -127,13 +83,13 @@ pub(super) fn encode_model(state: &ModelState, document: &[u8]) -> Result<(Vec Option { +pub fn read_design_geometry(bytes: &[u8]) -> Option> { if bytes.len() > MAX_DESIGN_BYTES || !is_design_container(bytes) { return None; } - DesignContainerReader::new(Cursor::new(bytes)).ok()?.geometry() + DesignContainerReader::new(Cursor::new(bytes)).ok()?.geometry()?.final_state().ok() } /// Whether `manifest` is a model cache this build wrote for `document`. @@ -148,12 +104,12 @@ fn current(manifest: &Value, document: &[u8]) -> bool { && env!("SOLIDCRAFT_SOURCE_COMMIT") != "unknown" } -pub(super) fn read_geometry_with(reader: &mut PackageReader, document: &[u8]) -> Result { +pub(super) fn read_geometry_with(reader: &mut PackageReader, document: &[u8]) -> Result { let container: Value = serde_json::from_slice(&reader.limited_part("container.json", 4096)?).map_err(invalid)?; if container.get("format").and_then(Value::as_str) != Some(VERSION) { return Err(invalid("container version")); } - let manifest: Value = serde_json::from_slice(&reader.limited_part(MANIFEST, MAX_MANIFEST)?).map_err(invalid)?; + let mut manifest: Value = serde_json::from_slice(&reader.limited_part(MANIFEST, MAX_MANIFEST)?).map_err(invalid)?; if !current(&manifest, document) { return Err(invalid("model cache key")); } @@ -163,16 +119,16 @@ pub(super) fn read_geometry_with(reader: &mut PackageReader, if manifest.get("payload").and_then(Value::as_str) != Some(digest(&data).as_str()) { return Err(invalid("model cache payload key")); } - let count = |v: &Value| v.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or_else(|| invalid("model cache number")); + let count = |v: Option<&Value>| v.and_then(Value::as_u64).and_then(|n| usize::try_from(n).ok()).ok_or_else(|| invalid("model cache number")); let slices = manifest - .get("bodies") + .get("slices") .and_then(Value::as_array) .filter(|b| !b.is_empty() && b.len() <= MAX_UNIQUE) .ok_or_else(|| invalid("cached bodies"))?; let mut end = 0usize; let mut parts = Vec::with_capacity(slices.len()); for s in slices { - let (offset, length) = (count(s.get(0).unwrap_or(&Value::Null))?, count(s.get(1).unwrap_or(&Value::Null))?); + let (offset, length) = (count(s.get(0))?, count(s.get(1))?); if offset != end { return Err(invalid("overlapping cached bodies")); } @@ -183,47 +139,33 @@ pub(super) fn read_geometry_with(reader: &mut PackageReader, return Err(invalid("trailing cached data")); } let decoded = solidcraft_kernel::map_on_threads(&parts, 16, |bytes| solidcraft_kernel::decode_native_body(bytes).ok()); - let bodies = decoded.into_iter().map(Option::flatten).collect::>>().ok_or_else(|| invalid("cached body"))?; - let body = |v: &Value| bodies.get(count(v)?).ok_or_else(|| invalid("cached body index")); + let unique = decoded.into_iter().map(Option::flatten).collect::>>().ok_or_else(|| invalid("cached body"))?; + let body = |v: Option<&Value>| unique.get(count(v)?).ok_or_else(|| invalid("cached body index")); let shares = manifest .get("shares") .and_then(Value::as_array) .filter(|s| s.len() <= MAX_UNIQUE) .ok_or_else(|| invalid("cached shares"))? .iter() - .map(|i| Ok(solidcraft_kernel::DisplayShare::new(body(i)?.clone()))) + .map(|i| Ok(solidcraft_kernel::DisplayShare::new(body(Some(i))?.clone()))) .collect::>>()?; - let records = - manifest.get("state").and_then(Value::as_array).filter(|s| !s.is_empty() && s.len() <= MAX_RECORDS).ok_or_else(|| invalid("cached state"))?; - let mut state = ModelState::default(); - state.body_counter = count(manifest.get("body_counter").unwrap_or(&Value::Null))?; - for r in records { - let name = r.get("name").and_then(Value::as_str).filter(|n| n.len() <= 1024).ok_or_else(|| invalid("cached body name"))?; - let mut kernel_body = body(r.get("body").unwrap_or(&Value::Null))?.clone(); - if let Some(share) = r.get("share") { - let s = shares.get(count(share.get(0).unwrap_or(&Value::Null))?).ok_or_else(|| invalid("cached share index"))?; - let numbers: Vec = serde_json::from_value(share.get(1).cloned().unwrap_or(Value::Null)).map_err(invalid)?; - let t = matrix_of(&numbers)?; - kernel_body = kernel_body.with_display_share(s, t); + let table = manifest + .get("bodies") + .and_then(Value::as_array) + .filter(|s| !s.is_empty() && s.len() <= MAX_RECORDS) + .ok_or_else(|| invalid("cached body table"))?; + let mut bodies = Vec::with_capacity(table.len()); + for entry in table { + let mut b = body(entry.get(0))?.clone(); + if let Some(share) = entry.get(1) { + let s = shares.get(count(Some(share))?).ok_or_else(|| invalid("cached share index"))?; + let numbers: Vec = serde_json::from_value(entry.get(2).cloned().unwrap_or(Value::Null)).map_err(invalid)?; + b = b.with_display_share(s, matrix_of(&numbers)?); } - let feature = r.get("feature").and_then(Value::as_u64).ok_or_else(|| invalid("cached body feature"))?; - let mut b = ModelBody::new(name.to_owned(), kernel_body, feature); - b.component = r.get("component").and_then(Value::as_u64).ok_or_else(|| invalid("cached body component"))?; - b.source_name = match r.get("source_name") { - None => None, - Some(v) => Some(v.as_str().filter(|n| n.len() <= 1024).ok_or_else(|| invalid("cached source name"))?.to_owned()), - }; - if let Some(v) = r.get("source_transform") { - let numbers: Vec = serde_json::from_value(v.clone()).map_err(invalid)?; - b.source_transform = matrix_of(&numbers)?; - } - b.transferred = r.get("transferred").and_then(Value::as_bool).unwrap_or(false); - if let Some(l) = r.get("imported") { - b.imported = Some(Arc::new(load_look(l)?)); - } - state.bodies.push(b); + bodies.push(b); } - Ok(state) + let records = manifest.get_mut("model").map(Value::take).ok_or_else(|| invalid("cached model"))?; + Ok(SavedModel { records, bodies }) } /// A 4 x 4 matrix from its 16 numbers in storage order, finite. @@ -238,9 +180,9 @@ fn matrix_of(numbers: &[f64]) -> Result<[[f64; 4]; 4]> { Ok(t) } -pub(super) fn geometry_preview(document: &[u8], state: ModelState) -> Result { +pub(super) fn geometry_preview(document: &[u8], model: &SavedModel) -> Result { let doc = Document::from_json(std::str::from_utf8(document).map_err(invalid)?)?; - let world = solidcraft_doc::world_state(&doc, &state); + let world = solidcraft_doc::world_state(&doc, &*model.final_state()?); let mut preview = DesignPreview::default(); let mut triangles = 0usize; let mut display_bytes = 0usize; diff --git a/crates/kernel/src/blend_variable.rs b/crates/kernel/src/blend_variable.rs index 8aafc19da..337408aa5 100644 --- a/crates/kernel/src/blend_variable.rs +++ b/crates/kernel/src/blend_variable.rs @@ -63,7 +63,7 @@ pub fn fillet_variable(body: &Body, edge_at: Vec3, start: Vec3, r0: f64, r1: f64 /// A fillet radius along an edge: a clamped B-spline of the position along it (0 at one end, 1 /// at the other), given by its degree, knots and control radii. The radius is a smooth curve /// shaped by its control radii, each pulling it toward itself near its Greville position. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] pub struct RadiusSpline { pub degree: usize, pub knots: Vec, @@ -503,7 +503,7 @@ const TAPER_SHARE: f64 = 0.9; const TAPER_SPANS: usize = 8; /// The radius a taper gives one edge: its positions from `start`. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] pub struct Taper { pub start: Vec3, pub spline: RadiusSpline, diff --git a/crates/kernel/src/boolean_diagnostics.rs b/crates/kernel/src/boolean_diagnostics.rs index b160980fb..e2a4b79cc 100644 --- a/crates/kernel/src/boolean_diagnostics.rs +++ b/crates/kernel/src/boolean_diagnostics.rs @@ -3,11 +3,11 @@ use std::cell::RefCell; -use serde::Serialize; +use serde::{Deserialize, Serialize}; const MAX_EVENTS: usize = 1024; -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum BooleanStrategy { RefinedTolerance, @@ -29,7 +29,7 @@ pub enum BooleanStrategy { /// Numerical adjustments used by a successful retry, in millimetres/radians. /// Operand shifts are reversed on the result; face shifts are temporary working /// offsets. A tool nudge, in contrast, changes the relative operand placement. -#[derive(Clone, Debug, PartialEq, Serialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct BooleanFallback { pub strategy: BooleanStrategy, pub translation_mm: f64, @@ -73,7 +73,7 @@ impl BooleanFallback { } } -#[derive(Clone, Debug, Default, PartialEq, Serialize)] +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct BooleanDiagnostics { pub events: Vec, pub truncated: bool, diff --git a/docs/design-container.md b/docs/design-container.md index 29cddc747..c435fdc58 100644 --- a/docs/design-container.md +++ b/docs/design-container.md @@ -86,9 +86,10 @@ geometry, used for measurements, or used to seed evaluated model state. The orig design remains intact until the complete rebuilt session is ready. Cancellation or any change of active document/revision discards both preview and completion. -Normal design reading, CLI and browser opening still rebuild authoritatively. -The model cache can supply provisional display as described below. The saved -picture is not an interactive viewport. +Desktop Open takes the evaluation from the model cache when the file keeps one for +this document and build (see below); otherwise it evaluates the timeline, as +design reading in the CLI and browser does. The saved picture is not an +interactive viewport. ## Seekable reader (phase 2, first increment) @@ -121,6 +122,17 @@ being saved (`Model::is_current`). An active sketch, uncaptured moves, feature errors, mesh bodies or exceeded budgets leave the cache out; the design saves as before. +The model is the whole evaluation: every feature's result (warning, boolean +diagnostics, whether it was skipped, its fingerprint) and the state after it +(bodies, solved sketches, construction geometry, sheet metal bodies, threads and +the blend records later features read). States share what they share: a body that +later features pass through unchanged, its face names and a solved sketch are each +recorded once. Face names are kept as worked out (saving works out any not asked +for yet), so a body taken from the file is named exactly as when it was saved. +A design whose stored names predate format 14 (marked `?`) finds them through +names worked out from geometry on demand, which the cache does not keep: it saves +without a model. + Both entries are Deflate-compressed (level one) under either compression policy: the encoded bodies shrink about fourfold (an imported assembly) to tenfold (modelled parts), for a few tens of milliseconds. @@ -134,15 +146,14 @@ SHA-256 of their encoding), and a placed copy of a repeated part (an instance fr a STEP assembly) records the part and its matrix, so it shows that part's display again instead of being meshed on its own. -`cache/model.json` records `solidcraft-model-cache/1`, the producer revision +`cache/model.json` records `solidcraft-model-cache/2`, the producer revision `solidcraft-truck-adapter/3`, the application version, the build (source commit, CPU architecture and OS), the SHA-256 of the exact `document.json` (whose blob references pin every STEP, mesh and image payload) and of `cache/bodies.bin`, the -slices, and the bodies' records: name, feature, component, placement source, -imported look and display share. A cache is read back only when every one of these -matches: the same source compiled for the same platform computes the same numbers, -so another build's cache is a miss. A build of unknown source (a tarball without -git) never reads a cache. +slices, each kernel body's slice and display share, and the model's records. A +cache is read back only when every one of these matches: the same source compiled +for the same platform computes the same numbers, so another build's cache is a +miss. A build of unknown source (a tarball without git) never reads a cache. The fixed budgets of earlier caches (4,096 bodies, 100,000 faces, 64 MiB) scale with the design now: up to 200,000 body records, 100,000 distinct bodies, a 32 MiB @@ -152,9 +163,34 @@ budgets (256 MiB per part, 512 MiB expanded, 10,000 entries) are unchanged, and cache is left out when it would push the container near them. Decoding runs under `kernel::guard` and is linear in the payload's bytes. -Opening still rebuilds the design from its timeline; the cache supplies the -provisional picture (a bounded mesh of the placed bodies) before that finishes. -Any failure in it is a miss, never a failed open. Earlier `cache/key.json` and +### Opening from the model + +Open takes the model as the design's evaluation (`Model::adopt`) when the key +matches and every feature's fingerprint (its definition, the parameters and +imported files it reads, the features before it, the timeline marker) is the one +the opened document gives it now. Nothing is evaluated: the imported STEP text is +resolved and hashed, never parsed. Every feature is up to date, so an edit +evaluates from the first feature it changes, as after any evaluation: a feature +appended or edited at the end evaluates from the saved final state, an edit to +feature k from the saved state before k. Moving the timeline marker, undo and redo +reuse the saved results whose fingerprints come back. `SOLIDCRAFT_NO_MODEL_CACHE` +set evaluates anyway. Any failure (a key or fingerprint mismatch, a malformed +record, a body that does not decode) is a miss: the design is evaluated from its +timeline as before, and only that. + +This replaces the earlier rule that a cache never supplies evaluated session +state. It is safe because the cache is the result of evaluating exactly this +document with exactly this build: the hashes tie it to the document (and through +it to every source blob) and to its own payload, the build key to the code that +computed it, the fingerprints to every feature's inputs, and the exact encoding +gives back the bodies number for number. Hashes are not trust: a crafted file can +carry a cache whose geometry disagrees with its timeline, as a crafted STEP file +can carry any geometry. Every decoded body passes the same structural and resource +checks, under `kernel::guard`, and Compute All (`timeline.compute_all`) evaluates +the whole timeline again. + +Before the session is ready the cache still supplies the picture (a bounded mesh +of the placed bodies) shown while opening. Earlier `cache/key.json` and `cache/brep.bin` entries are ignored. ## Review increments and kernel independence From 4dcca282daf0cf214784b04d85b9dce97e2adcbc Mon Sep 17 00:00:00 2001 From: amolinari-autotex Date: Tue, 20 Oct 2026 14:36:04 +0000 Subject: [PATCH 222/225] claim: #3245 (#3246) --- crates/engine/src/cmd/delete.rs | 101 ++++++++++- crates/engine/src/cmd/joints.rs | 7 +- crates/ui-egui/src/context_menu.rs | 2 +- crates/ui-egui/src/delete.rs | 10 +- crates/ui-egui/src/dialogs_assembly.rs | 42 ++++- crates/ui-egui/src/joint_browser_tests.rs | 202 ++++++++++++++++++++++ crates/ui-egui/src/timeline.rs | 2 + crates/ui-egui/src/timeline_left.rs | 4 + 8 files changed, 357 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/delete.rs b/crates/engine/src/cmd/delete.rs index 9a3bc89b7..2367dd845 100644 --- a/crates/engine/src/cmd/delete.rs +++ b/crates/engine/src/cmd/delete.rs @@ -1,7 +1,7 @@ //! Delete for everything that can be selected, in one undo step: sketch entities (while //! sketching), timeline features and sketches (with the features that depend on them), //! construction planes, bodies (a Remove feature from here on in the timeline), occurrences and -//! components, and canvases. `dry_run` reports what would go and what would fail without +//! components, canvases and joints. `dry_run` reports what would go and what would fail without //! changing anything, so the UI can ask first. use serde_json::{Value, json}; @@ -13,7 +13,7 @@ use crate::params::{bad, bool_}; use crate::{EngineError, Result, Sel, Session}; pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("selection.delete", "Delete", delete).icon("delete").params( - "items?: [selection items]; components?, occurrences?, canvases?: [ids or names]; dry_run?: bool → deleted, would_fail, skipped (one undo step)", + "items?: [selection items]; components?, occurrences?, canvases?, joints?: [ids or names]; dry_run?: bool → deleted, deleted_joints, would_fail, skipped (one undo step)", )]; /// Run another command's body inside this one (so the whole delete is one undo step). @@ -52,7 +52,24 @@ fn apply(s: &mut Session, p: &Value) -> Result { } Some(_) => return Err(bad(cmd, "`items` must be a list of selection items")), }; + if let Some(value) = p.get("joints").filter(|v| !v.is_null()) { + let Some(joints) = value.as_array() else { + return Err(bad(cmd, "`joints` must be a list of ids or names")); + }; + if joints.len() > 10_000 || joints.iter().any(|j| !j.is_string() && j.as_u64().is_none()) { + return Err(bad(cmd, "`joints` must contain at most 10000 ids or names")); + } + } let before = s.model.clone(); + let mut joints = p + .get("joints") + .and_then(Value::as_array) + .into_iter() + .flatten() + .map(|value| super::joints::joint_id(s, Some(value), cmd)) + .collect::>>()?; + joints.sort_unstable(); + joints.dedup(); let features_before: Vec<(u64, String)> = s.doc.features.iter().map(|f| (f.id, f.name.clone())).collect(); let mut skipped: Vec = Vec::new(); let mut skip = |why: String| { @@ -94,6 +111,10 @@ fn apply(s: &mut Session, p: &Value) -> Result { } features.dedup(); let mut done = false; + for id in &joints { + sub(s, "joint.delete", json!({"joint": id}))?; + done = true; + } if !entities.is_empty() { if s.active_sketch.is_none() { skip("sketch entities are deleted while editing their sketch".into()); @@ -168,7 +189,7 @@ fn apply(s: &mut Session, p: &Value) -> Result { .filter(|r| r.error.is_some() && before.result(r.id).is_some_and(|b| b.error.is_none() && !b.skipped)) .map(|r| r.name.clone()) .collect(); - Ok(json!({ "deleted": deleted, "bodies": bodies, "would_fail": would_fail, "skipped": skipped })) + Ok(json!({ "deleted": deleted, "deleted_joints": joints, "bodies": bodies, "would_fail": would_fail, "skipped": skipped })) } #[cfg(test)] @@ -251,6 +272,80 @@ mod tests { } } + fn joint_assembly() -> Session { + let mut s = Session::default(); + for (name, x) in [("A", 0), ("B", 30), ("C", 60)] { + run(&mut s, "component.activate", json!({"component": "root"})); + run(&mut s, "component.create", json!({"name": name})); + run(&mut s, "solid.box", json!({"length": 20, "width": 20, "height": 10, "corner": [x, 0, 0]})); + } + run(&mut s, "component.activate", json!({"component": "root"})); + run(&mut s, "occurrence.ground", json!({"occurrence": "A:1", "grounded": true})); + for (name, other, face) in [("Hinge", "B:1", [40, 10, 0]), ("Glue", "C:1", [70, 10, 0])] { + run( + &mut s, + "joint.create", + json!({"type": "revolute", "name": name, + "a": {"occurrence": "A:1", "face": [10, 10, 10]}, "b": {"occurrence": other, "face": face}}), + ); + } + run(&mut s, "joint.motion_link", json!({"a": "Hinge", "b": "Glue", "ratio": 1})); + s + } + + #[test] + fn selected_joints_and_their_link_are_deleted_in_one_undo_step_with_a_read_only_dry_run() { + let mut s = joint_assembly(); + let features = serde_json::to_value(&s.doc.features).unwrap(); + let hinge = s.doc.assembly.joints[0].id; + let dry = run(&mut s, "selection.delete", json!({"joints": [hinge, "Hinge", "Glue"], "dry_run": true})); + assert_eq!(dry["deleted_joints"].as_array().unwrap().len(), 2); + assert_eq!(s.doc.assembly.joints.len(), 2); + assert_eq!(s.doc.assembly.links.len(), 1); + assert_eq!(serde_json::to_value(&s.doc.features).unwrap(), features); + run(&mut s, "selection.delete", json!({"joints": [hinge, "Hinge", "Glue"]})); + assert!(s.doc.assembly.joints.is_empty() && s.doc.assembly.links.is_empty()); + assert_eq!(serde_json::to_value(&s.doc.features).unwrap(), features); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.assembly.joints.len(), 2); + assert_eq!(s.doc.assembly.links.len(), 1); + assert_eq!(serde_json::to_value(&s.doc.features).unwrap(), features); + run(&mut s, "edit.redo", json!({})); + assert!(s.doc.assembly.joints.is_empty() && s.doc.assembly.links.is_empty()); + } + + #[test] + fn an_unknown_joint_refuses_the_whole_delete_without_losing_features_or_other_joints() { + let mut s = joint_assembly(); + let before = serde_json::to_value(&s.doc.features).unwrap(); + let feature = s.doc.features[0].id; + assert!(s.execute("selection.delete", &json!({"items": [{"type": "feature", "id": feature}], "joints": ["Hinge", "missing"]})).is_err()); + for joints in [json!("Hinge"), json!([null]), json!([-1]), json!([1.5]), json!(vec!["Hinge"; 10_001])] { + assert!(s.execute("selection.delete", &json!({"joints": joints})).is_err()); + } + assert_eq!(serde_json::to_value(&s.doc.features).unwrap(), before); + assert_eq!(s.doc.assembly.joints.len(), 2); + assert_eq!(s.doc.assembly.links.len(), 1); + } + + #[test] + fn numeric_joint_ids_do_not_delete_a_different_joint_with_that_numeric_name() { + for batch in [false, true] { + let mut s = joint_assembly(); + let hinge = s.doc.assembly.joints[0].id; + let glue = s.doc.assembly.joints[1].id; + run(&mut s, "joint.edit", json!({"joint": hinge, "name": glue.to_string()})); + let features = serde_json::to_value(&s.doc.features).unwrap(); + let (command, params) = if batch { ("selection.delete", json!({"joints": [glue]})) } else { ("joint.delete", json!({"joint": glue})) }; + run(&mut s, command, params); + assert_eq!(s.doc.assembly.joints.len(), 1); + assert_eq!(s.doc.assembly.joints[0].id, hinge, "a numeric id must not match another joint's name"); + assert_eq!(serde_json::to_value(&s.doc.features).unwrap(), features); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.assembly.joints.len(), 2); + } + } + #[test] fn occurrences_components_and_sketch_entities() { let (mut s, _) = part(); diff --git a/crates/engine/src/cmd/joints.rs b/crates/engine/src/cmd/joints.rs index e7c071c45..bac77a780 100644 --- a/crates/engine/src/cmd/joints.rs +++ b/crates/engine/src/cmd/joints.rs @@ -497,7 +497,12 @@ pub(crate) fn joint_id(s: &Session, v: Option<&Value>, cmd: &str) -> Result Some(Value::String(x)) => x.clone(), _ => return Err(bad(cmd, "`joint` must be an id or a name")), }; - s.doc.assembly.joints.iter().find(|j| j.id.to_string() == key || j.name == key).map(|j| j.id).ok_or_else(|| bad(cmd, format!("no joint `{key}`"))) + let joint = if let Some(Value::Number(number)) = v { + number.as_u64().and_then(|id| s.doc.assembly.joints.iter().find(|joint| joint.id == id)) + } else { + s.doc.assembly.joints.iter().find(|joint| joint.id.to_string() == key || joint.name == key) + }; + joint.map(|joint| joint.id).ok_or_else(|| bad(cmd, format!("no joint `{key}`"))) } /// A joint value: numbers are degrees for angles and mm for distances; text is an expression. diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index 46429a9c5..9f0a6315e 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -643,7 +643,7 @@ fn joint_items(app: &SolveApp, id: u64) -> Vec { act("ui.findJoint", "Find in Window", "").with(json!({ "joint": id })), cmd(app, "joint.edit", if j.suppressed { "Unsuppress" } else { "Suppress" }).with(json!({ "joint": id, "suppressed": !j.suppressed })), Item::sep(), - cmd(app, "joint.delete", "Delete").key("Del").with(json!({ "joint": id })), + act("ui.delete", "Delete", "delete").key("Del").with(json!({ "joints": [id] })), act("ui.rename", "Rename", "").with(json!({ "joint": id })), Item::sep(), // Hiding a joint hides only its glyph: it still constrains and moves the parts. diff --git a/crates/ui-egui/src/delete.rs b/crates/ui-egui/src/delete.rs index 1f1260152..571e75cea 100644 --- a/crates/ui-egui/src/delete.rs +++ b/crates/ui-egui/src/delete.rs @@ -21,11 +21,11 @@ pub fn selection_params(app: &SolveApp) -> Value { let items: Vec<&solidcraft_engine::Sel> = app.session.selection.iter().filter(|s| !matches!(s, solidcraft_engine::Sel::Body { name } if app.ui.locked_bodies.contains(name))).collect(); let occurrences: Vec = app.tree.picked_components.iter().filter_map(|c| app.session.doc.occurrence_of(*c).map(|o| o.id)).collect(); - json!({ "items": items, "occurrences": occurrences, "canvases": app.tree.picked_canvases }) + json!({ "items": items, "occurrences": occurrences, "canvases": app.tree.picked_canvases, "joints": app.tree.picked_joints }) } fn is_empty(p: &Value) -> bool { - ["items", "occurrences", "components", "canvases"].iter().all(|k| p.get(*k).and_then(Value::as_array).is_none_or(|a| a.is_empty())) + ["items", "occurrences", "components", "canvases", "joints"].iter().all(|k| p.get(*k).and_then(Value::as_array).is_none_or(|a| a.is_empty())) } fn shared_occurrences(app: &SolveApp, params: &Value) -> bool { @@ -53,6 +53,11 @@ pub fn delete_selection(app: &mut SolveApp) { /// other features go with it or would fail. The dry run that finds out evaluates the history /// after what is deleted, so it may compute off the window thread (#2678). pub fn request(app: &mut SolveApp, params: Value) { + if params.get("joints").and_then(Value::as_array).is_some_and(|a| !a.is_empty()) + && (app.dialog.is_some() || app.tool.is_some() || app.computing_since().is_some() || app.file_load.busy()) + { + return; + } if is_empty(¶ms) { return; } @@ -87,6 +92,7 @@ fn run(app: &mut SolveApp, params: &Value) { Ok(r) => { app.tree.picked_components.clear(); app.tree.picked_canvases.clear(); + app.tree.picked_joints.clear(); if let Some(s) = r["skipped"].as_array().and_then(|a| a.first()).and_then(Value::as_str) { app.set_status(format!("deleted; {s}"), false); } diff --git a/crates/ui-egui/src/dialogs_assembly.rs b/crates/ui-egui/src/dialogs_assembly.rs index 045894c35..16270ba85 100644 --- a/crates/ui-egui/src/dialogs_assembly.rs +++ b/crates/ui-egui/src/dialogs_assembly.rs @@ -1229,7 +1229,7 @@ fn joint_menu( } ui.separator(); if ui.button("Delete").clicked() { - *run = Some(("joint.delete", json!({ "joint": id }))); + *run = Some(("selection.delete", json!({ "joints": [id] }))); ui.close(); } } @@ -1248,8 +1248,15 @@ pub fn timeline_joints(app: &mut SolveApp, ui: &mut egui::Ui, p: &egui::Painter, let mut run: Option<(&'static str, Value)> = None; for (id, name, kind, suppressed) in joints { let br = egui::Rect::from_min_size(egui::pos2(x, r.top() + 6.0), vec2(28.0, 28.0)); + crate::scenario::publish_handle(&format!("timeline-joint:{name}"), br.center()); let resp = ui.interact(br, ui.id().with(("joint", id)), egui::Sense::click()); - let bg = if resp.hovered() { t.hover } else { t.timeline_item }; + let bg = if app.tree.picked_joints.contains(&id) { + t.accent_soft + } else if resp.hovered() { + t.hover + } else { + t.timeline_item + }; p.rect(br, 3.0, bg, Stroke::new(1.0, t.border), egui::StrokeKind::Inside); crate::icons::paint(p, br.shrink(4.0), "joint", if suppressed { t.border } else { t.icon }, t.icon_fill, t.accent); if suppressed { @@ -1258,12 +1265,21 @@ pub fn timeline_joints(app: &mut SolveApp, ui: &mut egui::Ui, p: &egui::Painter, let resp = resp.on_hover_text(format!("{name} ({kind:?} joint)\nDouble-click to edit · right-click for more")); if resp.double_clicked() { open = edit_joint(app, id); + } else if resp.clicked() { + pick_joint(app, id, ui.input(|i| i.modifiers.command || i.modifiers.ctrl)); + } + if resp.secondary_clicked() && !app.tree.picked_joints.contains(&id) { + pick_joint(app, id, false); } resp.context_menu(|ui| joint_menu(app, ui, (id, kind, suppressed), &mut open, &mut run)); x += 32.0; } if let Some((c, prm)) = run { - let _ = app.run(c, prm); + if c == "selection.delete" { + crate::delete::request(app, prm); + } else { + let _ = app.run(c, prm); + } } if let Some(d) = open { app.tool = None; @@ -1286,7 +1302,10 @@ pub fn timeline_joints_vertical(app: &mut SolveApp, ui: &mut egui::Ui) { let mut run = None; for (id, name, kind, suppressed) in joints { let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), 30.0), egui::Sense::click()); - if response.hovered() { + crate::scenario::publish_handle(&format!("timeline-joint:{name}"), rect.center()); + if app.tree.picked_joints.contains(&id) { + ui.painter().rect_filled(rect, 3.0, t.accent_soft); + } else if response.hovered() { ui.painter().rect_filled(rect, 3.0, t.hover); } let icon = egui::Rect::from_min_size(egui::pos2(rect.left() + 4.0, rect.top() + 4.0), vec2(22.0, 22.0)); @@ -1304,11 +1323,20 @@ pub fn timeline_joints_vertical(app: &mut SolveApp, ui: &mut egui::Ui) { let response = response.on_hover_text(format!("{name} ({kind:?} joint)\nDouble-click to edit · right-click for more")); if response.double_clicked() { open = edit_joint(app, id); + } else if response.clicked() { + pick_joint(app, id, ui.input(|i| i.modifiers.command || i.modifiers.ctrl)); + } + if response.secondary_clicked() && !app.tree.picked_joints.contains(&id) { + pick_joint(app, id, false); } response.context_menu(|ui| joint_menu(app, ui, (id, kind, suppressed), &mut open, &mut run)); } if let Some((command, params)) = run { - let _ = app.run(command, params); + if command == "selection.delete" { + crate::delete::request(app, params); + } else { + let _ = app.run(command, params); + } } if let Some(dialog) = open { app.tool = None; @@ -1377,7 +1405,7 @@ pub fn browser_joints(app: &mut SolveApp, ui: &mut egui::Ui, depth: usize) { // The same menus as the rest of the browser. if let Some(at) = r.secondary { if !app.tree.picked_joints.contains(&id) { - app.tree.picked_joints = vec![id]; + pick_joint(app, id, false); } crate::context_menu::open_for(app, at, crate::context_menu::Target::Joint { id }); } @@ -1391,6 +1419,8 @@ pub fn browser_joints(app: &mut SolveApp, ui: &mut egui::Ui, depth: usize) { /// A click on a joint's browser row: it becomes the pick (or, with Ctrl, toggles in or out of /// it). Picked joints draw highlighted in the viewport, even hidden ones. pub fn pick_joint(app: &mut SolveApp, id: u64, add: bool) { + app.tree.picked_timeline_groups.clear(); + app.tree.timeline_anchor = None; if !add { let was = app.tree.picked_joints == [id]; app.tree.picked_joints.clear(); diff --git a/crates/ui-egui/src/joint_browser_tests.rs b/crates/ui-egui/src/joint_browser_tests.rs index 9d055bec4..7709eb8f2 100644 --- a/crates/ui-egui/src/joint_browser_tests.rs +++ b/crates/ui-egui/src/joint_browser_tests.rs @@ -119,3 +119,205 @@ fn the_menu_and_the_v_key_hide_and_show_picked_joints() { context_menu::toggle_visibility(&mut h.app); assert!(h.app.session.joint_visible(hinge) && h.app.session.joint_visible(glue)); } + +mod delete { + //! Joint history and Browser selection must be the target of the Delete key. + use serde_json::{Value, json}; + + use crate::scenario::Harness; + + fn assembly() -> Harness { + let mut h = Harness::new(); + h.app.home.open = false; + for (name, x) in [("A", 0), ("B", 30), ("C", 60)] { + h.app.run("component.activate", json!({"component": "root"})).unwrap(); + h.app.run("component.create", json!({"name": name})).unwrap(); + h.app.run("solid.box", json!({"length": 20, "width": 20, "height": 10, "corner": [x, 0, 0]})).unwrap(); + } + h.app.run("component.activate", json!({"component": "root"})).unwrap(); + h.app.run("occurrence.ground", json!({"occurrence": "A:1", "grounded": true})).unwrap(); + for (name, kind, other, face) in [("Hinge", "revolute", "B:1", [40, 10, 0]), ("Glue", "rigid", "C:1", [70, 10, 0])] { + h.app + .run( + "joint.create", + json!({"type": kind, "name": name, + "a": {"occurrence": "A:1", "face": [10, 10, 10]}, "b": {"occurrence": other, "face": face}}), + ) + .unwrap(); + } + h.frames(3); + h + } + + fn joint(h: &Harness, name: &str) -> u64 { + h.app.session.doc.assembly.joints.iter().find(|j| j.name == name).unwrap().id + } + + fn click(h: &mut Harness, handle: &str) { + h.step(&json!({"click": {"handle": handle}})).unwrap(); + h.frames(3); + } + + fn features(h: &Harness) -> Value { + serde_json::to_value(&h.app.session.doc.features).unwrap() + } + + #[test] + fn a_joint_history_click_replaces_the_stale_feature_before_delete_in_both_layouts() { + for left in [false, true] { + let mut h = assembly(); + h.app.ui.show_browser = false; + h.app.preferences.timeline_left = left; + h.frames(3); + let hinge = joint(&h, "Hinge"); + let before = features(&h); + let feature = h.app.session.doc.features.last().unwrap(); + let (id, name) = (feature.id, feature.name.clone()); + click(&mut h, &format!("timeline:{name}")); + assert!(h.app.session.selection.iter().any(|s| matches!(s, solidcraft_engine::Sel::Feature { id: f } if *f == id))); + click(&mut h, "timeline-joint:Hinge"); + assert_eq!(h.app.tree.picked_joints, [hinge], "the clicked joint is the selection; left={left}"); + assert!(h.app.session.selection.is_empty(), "the old feature must not remain a Delete target"); + h.step(&json!({"key": "Delete"})).unwrap(); + assert_eq!(features(&h), before, "Delete must leave every feature intact"); + assert!(h.app.session.doc.assembly.joints.iter().all(|j| j.id != hinge)); + assert_eq!(h.app.session.doc.assembly.joints.len(), 1); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.assembly.joints.len(), 2); + assert_eq!(features(&h), before); + h.app.run("edit.redo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.assembly.joints.len(), 1); + assert_eq!(features(&h), before); + } + } + + #[test] + fn browser_joint_multiselection_deletes_in_one_undo_step() { + let mut h = assembly(); + let before = features(&h); + click(&mut h, "row:Hinge"); + h.step(&json!({"click": {"handle": "row:Glue"}, "ctrl": true})).unwrap(); + h.frames(3); + assert_eq!(h.app.tree.picked_joints.len(), 2); + h.step(&json!({"key": "Backspace"})).unwrap(); + assert!(h.app.session.doc.assembly.joints.is_empty()); + assert!(h.app.tree.picked_joints.is_empty()); + assert_eq!(features(&h), before); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.assembly.joints.len(), 2); + assert_eq!(features(&h), before); + } + + #[test] + fn picking_a_feature_after_a_joint_replaces_the_joint_selection() { + for left in [false, true] { + let mut h = assembly(); + h.app.ui.show_browser = false; + h.app.preferences.timeline_left = left; + h.frames(3); + click(&mut h, "timeline-joint:Hinge"); + let name = h.app.session.doc.features.last().unwrap().name.clone(); + click(&mut h, &format!("timeline:{name}")); + assert!(h.app.tree.picked_joints.is_empty(), "joint selection must follow the feature click; left={left}"); + assert!(!h.app.session.selection.is_empty()); + } + } + + #[test] + fn a_joint_menu_delete_uses_its_target_despite_a_stale_feature_selection() { + let mut h = assembly(); + let before = features(&h); + let feature = h.app.session.doc.features.last().unwrap().id; + h.app.run("select.set", json!({"items": [{"type": "feature", "id": feature}]})).unwrap(); + let hinge = joint(&h, "Hinge"); + let items = crate::context_menu::items(&h.app, &crate::context_menu::Target::Joint { id: hinge }); + let item = items.iter().find(|i| i.label == "Delete").unwrap().clone(); + crate::context_menu::run_item(&mut h.app, &item, egui::pos2(0., 0.)); + assert_eq!(h.app.session.doc.assembly.joints.len(), 1); + assert_eq!(features(&h), before); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.assembly.joints.len(), 2); + } + + #[test] + fn history_joint_ctrl_click_toggles_and_the_context_menu_selects_its_target() { + for left in [false, true] { + let mut h = assembly(); + h.app.ui.show_browser = false; + h.app.preferences.timeline_left = left; + h.frames(3); + let (hinge, glue) = (joint(&h, "Hinge"), joint(&h, "Glue")); + let before = features(&h); + click(&mut h, "timeline-joint:Hinge"); + h.step(&json!({"click": {"handle": "timeline-joint:Glue"}, "ctrl": true})).unwrap(); + h.frames(3); + assert_eq!(h.app.tree.picked_joints, [hinge, glue]); + h.step(&json!({"click": {"handle": "timeline-joint:Hinge"}, "ctrl": true})).unwrap(); + h.frames(3); + assert_eq!(h.app.tree.picked_joints, [glue]); + let name = h.app.session.doc.features.last().unwrap().name.clone(); + click(&mut h, &format!("timeline:{name}")); + h.step(&json!({"click": {"handle": "timeline-joint:Hinge"}, "button": "right"})).unwrap(); + h.frames(3); + assert_eq!(h.app.tree.picked_joints, [hinge]); + assert!(h.app.session.selection.is_empty()); + h.step(&json!({"widget": "Delete"})).unwrap(); + assert!(h.app.session.doc.assembly.joints.iter().all(|j| j.id != hinge)); + assert!(h.app.session.doc.assembly.joints.iter().any(|j| j.id == glue)); + assert_eq!(features(&h), before); + } + } + + #[test] + fn joint_delete_does_not_run_while_a_dialog_or_history_command_is_active() { + let mut h = assembly(); + click(&mut h, "row:Hinge"); + let before = features(&h); + h.step(&json!({"start": "solid.box"})).unwrap(); + let hinge = joint(&h, "Hinge"); + h.app.tree.picked_joints.clear(); + crate::dialogs_assembly::pick_joint(&mut h.app, hinge, false); + assert!(h.app.dialog.is_some()); + assert_eq!(h.app.tree.picked_joints, [hinge], "the dialog guard must protect an actual joint selection"); + click(&mut h, "dialog:length"); + h.step(&json!({"key": "Delete"})).unwrap(); + assert_eq!(h.app.session.doc.assembly.joints.len(), 2, "Delete belongs to the focused field"); + assert_eq!(h.app.tree.picked_joints, [hinge]); + crate::delete::delete_selection(&mut h.app); + assert_eq!(h.app.session.doc.assembly.joints.len(), 2, "a dialog must not delete a joint behind it"); + h.step(&json!({"key": "Escape"})).unwrap(); + let hinge = joint(&h, "Hinge"); + h.app.tree.picked_joints.clear(); + crate::dialogs_assembly::pick_joint(&mut h.app, hinge, false); + assert_eq!(h.app.tree.picked_joints, [hinge]); + h.app.apply_off_thread = Some(std::time::Duration::ZERO); + h.app.run_heavy("timeline.roll_to", json!({"position": 1})).unwrap(); + assert!(h.app.computing_since().is_some()); + crate::delete::delete_selection(&mut h.app); + assert_eq!(h.app.session.doc.assembly.joints.len(), 2, "Delete must not race the pending history command"); + assert_eq!(features(&h), before); + } + + #[test] + fn a_ctrl_joint_pick_does_not_leave_a_folder_as_the_delete_target() { + let mut h = assembly(); + h.app.ui.show_browser = false; + h.app.preferences.timeline_left = true; + let feature = h.app.session.doc.features[0].id; + let group = h.app.run("timeline.group", json!({"name": "History", "features": [feature]})).unwrap()["group"].as_u64().unwrap(); + h.app.tree.picked_timeline_groups.push(group); + h.frames(3); + let before = features(&h); + let hinge = joint(&h, "Hinge"); + h.step(&json!({"click": {"handle": "timeline-joint:Hinge"}, "ctrl": true})).unwrap(); + h.frames(3); + assert_eq!(h.app.tree.picked_joints, [hinge]); + assert!(h.app.tree.picked_timeline_groups.is_empty()); + h.step(&json!({"key": "Delete"})).unwrap(); + assert!(h.app.session.doc.assembly.joints.iter().all(|joint| joint.id != hinge)); + assert!(h.app.session.doc.timeline_groups.iter().any(|folder| folder.id == group), "Delete must preserve the old folder"); + assert_eq!(features(&h), before); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.assembly.joints.len(), 2); + } +} diff --git a/crates/ui-egui/src/timeline.rs b/crates/ui-egui/src/timeline.rs index e3b831980..de7539525 100644 --- a/crates/ui-egui/src/timeline.rs +++ b/crates/ui-egui/src/timeline.rs @@ -402,6 +402,8 @@ pub fn timeline(app: &mut SolveApp, ui: &mut egui::Ui) { } else if ui.input(|i| i.modifiers.command || i.modifiers.ctrl) { toggle_feature(app, *id); } else { + app.tree.picked_joints.clear(); + app.tree.picked_timeline_groups.clear(); let _ = app.run("select.set", json!({"items": [{"type": "feature", "id": id}]})); } } diff --git a/crates/ui-egui/src/timeline_left.rs b/crates/ui-egui/src/timeline_left.rs index 192cca55b..f7db54a45 100644 --- a/crates/ui-egui/src/timeline_left.rs +++ b/crates/ui-egui/src/timeline_left.rs @@ -223,6 +223,7 @@ fn drag_x(items: &DragItems, pointer_x: f32) -> f32 { } fn select_only(app: &mut SolveApp, item: TimelineItem) { + app.tree.picked_joints.clear(); match item { TimelineItem::Group(id) => { app.tree.picked_timeline_groups.clear(); @@ -239,6 +240,9 @@ fn select_only(app: &mut SolveApp, item: TimelineItem) { fn select_item(app: &mut SolveApp, ui: &egui::Ui, item: TimelineItem, order: &[TimelineItem]) { let modifiers = ui.input(|input| input.modifiers); + if !modifiers.command && !modifiers.ctrl { + app.tree.picked_joints.clear(); + } if modifiers.shift && let Some(anchor) = app.tree.timeline_anchor.as_deref() && let (Some(from), Some(to)) = (order.iter().position(|entry| entry.key() == anchor), order.iter().position(|entry| *entry == item)) From db75b7bface3aecbab76e805b56d35511286dedb Mon Sep 17 00:00:00 2001 From: bherbruck Date: Tue, 20 Oct 2026 11:18:32 -0400 Subject: [PATCH 223/225] Make the off-thread OK test deterministic (#3622) The test could lose a race: with a zero wait the evaluation sometimes finished and applied before the check that the dialog was still computing. The evaluation is now held at a test gate until the dialog has been seen saying so. Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/apply_off_thread_tests.rs | 11 ++++------- crates/ui-egui/src/dialogs.rs | 6 ++++++ crates/ui-egui/src/lib.rs | 5 +++++ 3 files changed, 15 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/apply_off_thread_tests.rs b/crates/ui-egui/src/apply_off_thread_tests.rs index 0cd4c134b..c261fe077 100644 --- a/crates/ui-egui/src/apply_off_thread_tests.rs +++ b/crates/ui-egui/src/apply_off_thread_tests.rs @@ -43,15 +43,12 @@ fn until_applied(h: &mut Harness) { fn ok_computes_off_the_window_thread_saying_so_then_applies() { let mut h = square_on_a_block(); h.app.apply_off_thread = Some(Duration::ZERO); + // The evaluation is held until the dialog has been seen saying so (it is in the cache all + // the same), so no frame can apply it before the checks below. + let (finish, gate) = std::sync::mpsc::channel(); + h.app.apply_gate = Some(std::sync::Arc::new(std::sync::Mutex::new(gate))); h.step(&json!({"key": "Enter"})).unwrap(); assert!(h.app.applying.is_some() && h.app.dialog.is_some(), "computing, the dialog open"); - // The evaluation may be in by the next frame: it is held until the dialog has been seen - // saying so (the evaluation itself is in the cache all the same). - let (finish, done) = std::sync::mpsc::channel(); - if let Some(job) = h.app.applying.as_mut() { - let _ = job.done.recv(); - job.done = done; - } h.frames(1); assert!(h.widget("Computing… 0 s").is_some(), "the dialog says it computes"); // Enter again does not start it twice. diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index aeaa2115d..5e874f3de 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -451,10 +451,16 @@ fn begin_applying(app: &SolveApp, d: &Dialog) -> Option { let scratch = app.session.scratch(); let (tx, rx) = std::sync::mpsc::channel(); let computed = cmds.clone(); + #[cfg(test)] + let gate = app.apply_gate.clone(); std::thread::Builder::new() .name("apply".into()) .spawn(move || { let _ = scratch.preview(&computed); + #[cfg(test)] + if let Some(gate) = gate { + let _ = gate.lock().unwrap().recv(); + } let _ = tx.send(()); }) .ok()?; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 1b3b9a446..8e68c929b 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -384,6 +384,9 @@ pub struct SolveApp { /// How long OK waits for a feature before computing it off the window thread, saying so; /// `None`: it waits as long as it takes (headless use, tests). The desktop app sets it. pub apply_off_thread: Option, + /// Tests: the off-thread evaluation waits for this before it reports done. + #[cfg(test)] + pub(crate) apply_gate: Option>>>, /// The last command started interactively (id, label), for Repeat. pub last_command: Option<(String, String)>, /// Esc was already acted on this frame (by the shortcuts), so later handlers skip it. @@ -512,6 +515,8 @@ impl SolveApp { deferred_queue: Vec::new(), delete_check: None, apply_off_thread: None, + #[cfg(test)] + apply_gate: None, last_command: None, esc_handled: false, status: None, From c5129a45d77dfc661497c6e6141fb1c84f3bb67a Mon Sep 17 00:00:00 2001 From: bherbruck Date: Tue, 20 Oct 2026 11:41:10 -0400 Subject: [PATCH 224/225] Release 0.17.0 (#3629) Version 0.17.0; design format 28 fixed (13 pending changes folded). Co-authored-by: Claude Opus 5.5 --- Cargo.lock | 34 +++++++++---------- Cargo.toml | 2 +- .../{pending => v28}/component-metadata.rs | 0 .../{pending => v28}/joint-expressions.rs | 0 .../{pending => v28}/joint-origin-edge.rs | 0 .../{pending => v28}/joint-origin-frame-x.rs | 0 .../{pending => v28}/joint-origin-point-x.rs | 0 .../{pending => v28}/joint-relations.rs | 0 .../{pending => v28}/line-circle-distance.rs | 0 .../{pending => v28}/loft-guide-rails.rs | 0 .../sketch-point-expressions.rs | 0 .../{pending => v28}/surface-blend-seam.rs | 0 .../surface-trim-regions-curves-mutual.rs | 0 .../two-sided-extrude-direction.rs | 0 .../{pending => v28}/vertex-edge-names.rs | 0 15 files changed, 18 insertions(+), 18 deletions(-) rename crates/doc/src/format/{pending => v28}/component-metadata.rs (100%) rename crates/doc/src/format/{pending => v28}/joint-expressions.rs (100%) rename crates/doc/src/format/{pending => v28}/joint-origin-edge.rs (100%) rename crates/doc/src/format/{pending => v28}/joint-origin-frame-x.rs (100%) rename crates/doc/src/format/{pending => v28}/joint-origin-point-x.rs (100%) rename crates/doc/src/format/{pending => v28}/joint-relations.rs (100%) rename crates/doc/src/format/{pending => v28}/line-circle-distance.rs (100%) rename crates/doc/src/format/{pending => v28}/loft-guide-rails.rs (100%) rename crates/doc/src/format/{pending => v28}/sketch-point-expressions.rs (100%) rename crates/doc/src/format/{pending => v28}/surface-blend-seam.rs (100%) rename crates/doc/src/format/{pending => v28}/surface-trim-regions-curves-mutual.rs (100%) rename crates/doc/src/format/{pending => v28}/two-sided-extrude-direction.rs (100%) rename crates/doc/src/format/{pending => v28}/vertex-edge-names.rs (100%) diff --git a/Cargo.lock b/Cargo.lock index 1df6cfe09..f3891452c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4162,7 +4162,7 @@ dependencies = [ [[package]] name = "solidcraft" -version = "0.16.2" +version = "0.17.0" dependencies = [ "block2 0.6.2", "eframe", @@ -4193,11 +4193,11 @@ dependencies = [ [[package]] name = "solidcraft-3dx-client" -version = "0.16.2" +version = "0.17.0" [[package]] name = "solidcraft-cli" -version = "0.16.2" +version = "0.17.0" dependencies = [ "image", "serde_json", @@ -4208,7 +4208,7 @@ dependencies = [ [[package]] name = "solidcraft-derive" -version = "0.16.2" +version = "0.17.0" dependencies = [ "proc-macro2", "quote", @@ -4217,7 +4217,7 @@ dependencies = [ [[package]] name = "solidcraft-doc" -version = "0.16.2" +version = "0.17.0" dependencies = [ "log", "serde", @@ -4234,7 +4234,7 @@ dependencies = [ [[package]] name = "solidcraft-engine" -version = "0.16.2" +version = "0.17.0" dependencies = [ "log", "schemars", @@ -4253,7 +4253,7 @@ dependencies = [ [[package]] name = "solidcraft-geom" -version = "0.16.2" +version = "0.17.0" dependencies = [ "serde", "serde_json", @@ -4262,7 +4262,7 @@ dependencies = [ [[package]] name = "solidcraft-gpu" -version = "0.16.2" +version = "0.17.0" dependencies = [ "log", "naga", @@ -4279,7 +4279,7 @@ dependencies = [ [[package]] name = "solidcraft-io" -version = "0.16.2" +version = "0.17.0" dependencies = [ "cadmpeg-core", "cadmpeg-ir", @@ -4302,7 +4302,7 @@ dependencies = [ [[package]] name = "solidcraft-kernel" -version = "0.16.2" +version = "0.17.0" dependencies = [ "log", "proptest", @@ -4322,7 +4322,7 @@ dependencies = [ [[package]] name = "solidcraft-mcp" -version = "0.16.2" +version = "0.17.0" dependencies = [ "serde_json", "solidcraft-engine", @@ -4331,7 +4331,7 @@ dependencies = [ [[package]] name = "solidcraft-render" -version = "0.16.2" +version = "0.17.0" dependencies = [ "image", "moxcms", @@ -4345,7 +4345,7 @@ dependencies = [ [[package]] name = "solidcraft-sketch" -version = "0.16.2" +version = "0.17.0" dependencies = [ "serde", "serde_json", @@ -4356,14 +4356,14 @@ dependencies = [ [[package]] name = "solidcraft-space-mouse" -version = "0.16.2" +version = "0.17.0" dependencies = [ "serde", ] [[package]] name = "solidcraft-ui-egui" -version = "0.16.2" +version = "0.17.0" dependencies = [ "arboard", "egui", @@ -4389,7 +4389,7 @@ dependencies = [ [[package]] name = "solidcraft-web" -version = "0.16.2" +version = "0.17.0" dependencies = [ "eframe", "egui", @@ -5919,7 +5919,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7" [[package]] name = "xtask" -version = "0.16.2" +version = "0.17.0" dependencies = [ "serde_json", "sha2 0.10.9", diff --git a/Cargo.toml b/Cargo.toml index a4cecf4f3..19c6fb4eb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,7 +5,7 @@ members = ["crates/*", "apps/*", "xtask"] exclude = ["vendor"] [workspace.package] -version = "0.16.2" +version = "0.17.0" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" diff --git a/crates/doc/src/format/pending/component-metadata.rs b/crates/doc/src/format/v28/component-metadata.rs similarity index 100% rename from crates/doc/src/format/pending/component-metadata.rs rename to crates/doc/src/format/v28/component-metadata.rs diff --git a/crates/doc/src/format/pending/joint-expressions.rs b/crates/doc/src/format/v28/joint-expressions.rs similarity index 100% rename from crates/doc/src/format/pending/joint-expressions.rs rename to crates/doc/src/format/v28/joint-expressions.rs diff --git a/crates/doc/src/format/pending/joint-origin-edge.rs b/crates/doc/src/format/v28/joint-origin-edge.rs similarity index 100% rename from crates/doc/src/format/pending/joint-origin-edge.rs rename to crates/doc/src/format/v28/joint-origin-edge.rs diff --git a/crates/doc/src/format/pending/joint-origin-frame-x.rs b/crates/doc/src/format/v28/joint-origin-frame-x.rs similarity index 100% rename from crates/doc/src/format/pending/joint-origin-frame-x.rs rename to crates/doc/src/format/v28/joint-origin-frame-x.rs diff --git a/crates/doc/src/format/pending/joint-origin-point-x.rs b/crates/doc/src/format/v28/joint-origin-point-x.rs similarity index 100% rename from crates/doc/src/format/pending/joint-origin-point-x.rs rename to crates/doc/src/format/v28/joint-origin-point-x.rs diff --git a/crates/doc/src/format/pending/joint-relations.rs b/crates/doc/src/format/v28/joint-relations.rs similarity index 100% rename from crates/doc/src/format/pending/joint-relations.rs rename to crates/doc/src/format/v28/joint-relations.rs diff --git a/crates/doc/src/format/pending/line-circle-distance.rs b/crates/doc/src/format/v28/line-circle-distance.rs similarity index 100% rename from crates/doc/src/format/pending/line-circle-distance.rs rename to crates/doc/src/format/v28/line-circle-distance.rs diff --git a/crates/doc/src/format/pending/loft-guide-rails.rs b/crates/doc/src/format/v28/loft-guide-rails.rs similarity index 100% rename from crates/doc/src/format/pending/loft-guide-rails.rs rename to crates/doc/src/format/v28/loft-guide-rails.rs diff --git a/crates/doc/src/format/pending/sketch-point-expressions.rs b/crates/doc/src/format/v28/sketch-point-expressions.rs similarity index 100% rename from crates/doc/src/format/pending/sketch-point-expressions.rs rename to crates/doc/src/format/v28/sketch-point-expressions.rs diff --git a/crates/doc/src/format/pending/surface-blend-seam.rs b/crates/doc/src/format/v28/surface-blend-seam.rs similarity index 100% rename from crates/doc/src/format/pending/surface-blend-seam.rs rename to crates/doc/src/format/v28/surface-blend-seam.rs diff --git a/crates/doc/src/format/pending/surface-trim-regions-curves-mutual.rs b/crates/doc/src/format/v28/surface-trim-regions-curves-mutual.rs similarity index 100% rename from crates/doc/src/format/pending/surface-trim-regions-curves-mutual.rs rename to crates/doc/src/format/v28/surface-trim-regions-curves-mutual.rs diff --git a/crates/doc/src/format/pending/two-sided-extrude-direction.rs b/crates/doc/src/format/v28/two-sided-extrude-direction.rs similarity index 100% rename from crates/doc/src/format/pending/two-sided-extrude-direction.rs rename to crates/doc/src/format/v28/two-sided-extrude-direction.rs diff --git a/crates/doc/src/format/pending/vertex-edge-names.rs b/crates/doc/src/format/v28/vertex-edge-names.rs similarity index 100% rename from crates/doc/src/format/pending/vertex-edge-names.rs rename to crates/doc/src/format/v28/vertex-edge-names.rs From 511faedcfa4b0868aa5df883dfbf5653e1ed9d25 Mon Sep 17 00:00:00 2001 From: Christian Svensson Date: Tue, 20 Oct 2026 17:41:40 +0200 Subject: [PATCH 225/225] Fix OpenGL startup with portable AO depth reads (#2888) (#2933) * claim: #2888 * fix: preserve AO depth in a portable integer texture (#2888) --- assets/shaders/viewport.wgsl | 18 ++++++++--- crates/gpu/src/view/ao.rs | 60 ++++++++++++++++++++++++------------ crates/gpu/tests/capture.rs | 33 ++++++++++++++++++++ 3 files changed, 86 insertions(+), 25 deletions(-) diff --git a/assets/shaders/viewport.wgsl b/assets/shaders/viewport.wgsl index 42ce753b7..7e8c27a58 100644 --- a/assets/shaders/viewport.wgsl +++ b/assets/shaders/viewport.wgsl @@ -29,7 +29,7 @@ fn near_z(c: vec4) -> f32 { } @group(1) @binding(2) var acc_t: texture_2d; -@group(2) @binding(0) var ao_depth: texture_depth_2d; +@group(2) @binding(0) var ao_depth: texture_2d; fn clipped(p: vec3) -> bool { return length(u.clip.xyz) > 0.5 && dot(u.clip.xyz, p) > u.clip.w; @@ -141,11 +141,19 @@ fn solid(i: TOut, front: bool) -> vec4 { } // A single-sample opaque depth map, independent of the window's MSAA and its UI offsets. +// Preserve the depth's bits in R32Uint: GLSL cannot textureLoad a depth texture, +// and float colour attachments are not available on every GL adapter. +struct AoDepth { + @builtin(frag_depth) depth: f32, + @location(0) value: u32, +}; + @fragment -fn fs_ao_depth(i: TOut, @builtin(front_facing) front: bool) -> @builtin(frag_depth) f32 { +fn fs_ao_depth(i: TOut, @builtin(front_facing) front: bool) -> AoDepth { if (clipped(i.wp) || length(i.n) < 0.5) { discard; } - if (!front && length(u.clip.xyz) > 0.5) { return cap_depth(i.wp, i.pos.z); } - return i.pos.z; + var depth = i.pos.z; + if (!front && length(u.clip.xyz) > 0.5) { depth = cap_depth(i.wp, i.pos.z); } + return AoDepth(depth, bitcast(depth)); } // Deterministic cosine-weighted hemisphere samples. Projecting the sample and a point one @@ -180,7 +188,7 @@ fn occlusion(i: TOut) -> f32 { let ndc = q.xyz / q.w; let uv = vec2(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5); if (any(uv < vec2(0.0)) || any(uv >= vec2(1.0)) || ndc.z < 0.0 || ndc.z > 1.0) { continue; } - let d0 = textureLoad(ao_depth, vec2(uv * vec2(size)), 0); + let d0 = bitcast(textureLoad(ao_depth, vec2(uv * vec2(size)), 0).x); let zs = select(ndc.z, 1.0 - ndc.z, flip); let zn = select(near.z / near.w, 1.0 - near.z / near.w, flip); let d = select(d0, 1.0 - d0, flip); diff --git a/crates/gpu/src/view/ao.rs b/crates/gpu/src/view/ao.rs index 3fce30cf3..9381a20a2 100644 --- a/crates/gpu/src/view/ao.rs +++ b/crates/gpu/src/view/ao.rs @@ -2,6 +2,9 @@ //! depth is drawn once into a single-sample depth map the lit fragment samples for occlusion. //! The map is independent of the window's MSAA, and the depth runs the same way as the //! viewport's own buffer (see [`super::depth_compare`] and [`super::far_depth`]). +//! Depth testing chooses the nearest surface; an R32Uint colour attachment stores that depth's +//! bits for portable integer texel reads. GLSL cannot load from a depth texture, and float +//! colour attachments are not available on every GL adapter. use super::{Batches, color_layout, depth_compare, far_depth, planned_layout, tri_layout}; @@ -9,29 +12,34 @@ pub(super) struct Resources { pub layout: wgpu::BindGroupLayout, pub bind: wgpu::BindGroup, depth: wgpu::TextureView, + values: wgpu::TextureView, size: [u32; 2], pipeline: wgpu::RenderPipeline, planned_pipeline: wgpu::RenderPipeline, } -fn texture(device: &wgpu::Device, layout: &wgpu::BindGroupLayout, size: [u32; 2]) -> (wgpu::TextureView, wgpu::BindGroup) { - let texture = device.create_texture(&wgpu::TextureDescriptor { - label: Some("sc_ao_depth"), - size: wgpu::Extent3d { width: size[0], height: size[1], depth_or_array_layers: 1 }, - mip_level_count: 1, - sample_count: 1, - dimension: wgpu::TextureDimension::D2, - format: wgpu::TextureFormat::Depth32Float, - usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING, - view_formats: &[], - }); - let depth = texture.create_view(&Default::default()); +fn texture(device: &wgpu::Device, layout: &wgpu::BindGroupLayout, size: [u32; 2]) -> (wgpu::TextureView, wgpu::TextureView, wgpu::BindGroup) { + let texture = |label, format, usage| { + device.create_texture(&wgpu::TextureDescriptor { + label: Some(label), + size: wgpu::Extent3d { width: size[0], height: size[1], depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage, + view_formats: &[], + }) + }; + let depth = texture("sc_ao_depth", wgpu::TextureFormat::Depth32Float, wgpu::TextureUsages::RENDER_ATTACHMENT).create_view(&Default::default()); + let values = texture("sc_ao_values", wgpu::TextureFormat::R32Uint, wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING) + .create_view(&Default::default()); let bind = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("sc_ao_depth"), layout, - entries: &[wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&depth) }], + entries: &[wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&values) }], }); - (depth, bind) + (depth, values, bind) } impl Resources { @@ -42,7 +50,7 @@ impl Resources { binding: 0, visibility: wgpu::ShaderStages::FRAGMENT, ty: wgpu::BindingType::Texture { - sample_type: wgpu::TextureSampleType::Depth, + sample_type: wgpu::TextureSampleType::Uint, view_dimension: wgpu::TextureViewDimension::D2, multisampled: false, }, @@ -78,7 +86,11 @@ impl Resources { fragment: Some(wgpu::FragmentState { module, entry_point: Some("fs_ao_depth"), - targets: &[], + targets: &[Some(wgpu::ColorTargetState { + format: wgpu::TextureFormat::R32Uint, + blend: None, + write_mask: wgpu::ColorWrites::RED, + })], compilation_options: Default::default(), }), multiview_mask: None, @@ -87,8 +99,8 @@ impl Resources { }; let planned_pipeline = pipeline(true); let pipeline = pipeline(false); - let (depth, bind) = texture(device, &layout, [1, 1]); - Self { layout, bind, depth, size: [1, 1], pipeline, planned_pipeline } + let (depth, values, bind) = texture(device, &layout, [1, 1]); + Self { layout, bind, depth, values, size: [1, 1], pipeline, planned_pipeline } } pub fn prepare( @@ -105,7 +117,7 @@ impl Resources { // Bound memory at large window sizes; normalized coordinates also handle downsampling. let size = target_size(enabled, size_px, device.limits().max_texture_dimension_2d); if size != self.size { - (self.depth, self.bind) = texture(device, &self.layout, size); + (self.depth, self.values, self.bind) = texture(device, &self.layout, size); self.size = size; } if !enabled { @@ -113,7 +125,15 @@ impl Resources { } let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("sc_ao_prepass"), - color_attachments: &[], + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &self.values, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color { r: f64::from(far_depth(reversed).to_bits()), g: 0.0, b: 0.0, a: 0.0 }), + store: wgpu::StoreOp::Store, + }, + })], depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { view: &self.depth, depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(far_depth(reversed)), store: wgpu::StoreOp::Store }), diff --git a/crates/gpu/tests/capture.rs b/crates/gpu/tests/capture.rs index e71d3a7ff..e368d1194 100644 --- a/crates/gpu/tests/capture.rs +++ b/crates/gpu/tests/capture.rs @@ -39,6 +39,39 @@ fn session(script: &[(&str, serde_json::Value)]) -> Session { s } +/// #2888: compiling the viewport on GL used to reject AO's depth textureLoad, even +/// with AO disabled. Select GL explicitly so a working Vulkan adapter cannot hide it. +#[test] +fn opengl_viewport_pipelines_render_a_model() { + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + desc.backends = wgpu::Backends::GL; + let instance = wgpu::Instance::new(desc); + let adapter = match pollster::block_on(instance.request_adapter(&Default::default())) { + Ok(adapter) => adapter, + Err(e) => { + let required = std::env::var_os("SOLIDCRAFT_REQUIRE_GPU").is_some() && wgpu::Backends::from_env() == Some(wgpu::Backends::GL); + assert!(!required, "OpenGL is required here: {e}"); + eprintln!("skipping the OpenGL regression: {e}"); + return; + } + }; + assert_eq!(adapter.get_info().backend, wgpu::Backend::Gl); + eprintln!("OpenGL regression: {:?}", adapter.get_info()); + let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { + required_features: solidcraft_gpu::depth_features(&adapter), + required_limits: wgpu::Limits::downlevel_defaults().using_resolution(adapter.limits()), + ..Default::default() + })) + .unwrap(); + let c = Capturer::new(&adapter, device, queue).unwrap(); + let s = session(&[("solid.box", json!({"length": 40, "width": 30, "height": 20}))]); + let cam = view::home_camera(&s); + let img = c.rgba(&view::scene_with_guides(&s, &cam, None, Guides { grid: false, axes: false }), &cam, 160, 100).unwrap(); + let empty = c.rgba(&Default::default(), &cam, 160, 100).unwrap(); + let changed = pixels(&img).zip(pixels(&empty)).filter(|(a, b)| a != b).count(); + assert!(changed > 500, "the model covers only {changed} pixels"); +} + /// Appearances show as the viewport shows them: a body's colour, a face's own look. #[test] fn pictures_show_appearances() {