From a13124acdd53876f3eca4098f71c02654418e46f Mon Sep 17 00:00:00 2001 From: bherbruck Date: Thu, 15 Oct 2026 17:27:29 -0400 Subject: [PATCH 01/92] Import glTF 2.0 files (.glb, .gltf) as mesh bodies (#1512) glTF files open, insert and drop like 3MF/STL/OBJ: a component named after the file, the node tree as nested rigid components, repeated meshes as occurrences, metres to mm, Y up turned to Z up by default (up: z keeps axes), materials as PBR appearances. Bounded, hostile-input tested reader; no new persisted data. Closes #1505. Co-Authored-By: Claude Opus 5.5 --- ATTRIBUTION.md | 11 + Cargo.lock | 49 ++ Cargo.toml | 3 + README.md | 5 +- THIRD-PARTY-LICENSES.txt | 146 ++++- apps/solidcraft-web/src/files.rs | 2 +- apps/solidcraft-web/src/main.rs | 11 +- apps/solidcraft/src/main.rs | 10 +- crates/engine/src/cmd/file.rs | 94 ++- crates/engine/src/cmd/file_import.rs | 50 +- crates/engine/src/tests.rs | 1 + crates/engine/src/tests/gltf_import.rs | 210 ++++++ crates/io/Cargo.toml | 3 +- crates/io/src/gltf_in.rs | 871 +++++++++++++++++++++++++ crates/io/src/gltf_in_tests.rs | 445 +++++++++++++ crates/io/src/lib.rs | 21 +- crates/mcp/src/tools.rs | 12 +- crates/ui-egui/src/lib.rs | 4 +- docs/book/src/guide/files.md | 12 +- 19 files changed, 1889 insertions(+), 71 deletions(-) create mode 100644 crates/engine/src/tests/gltf_import.rs create mode 100644 crates/io/src/gltf_in.rs create mode 100644 crates/io/src/gltf_in_tests.rs diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 047d10d0b..856817e36 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -139,6 +139,17 @@ work cooperative and adds checked run lengths, zero-run rejection, width validat header/input/radiance bounds and cancellation. Original licence texts are retained in THIRD-PARTY-LICENSES.txt; no images or artwork from that project are copied. +## File-format crates + +| Crate | Used for | Licence | +|---|---|---| +| gltf 1.4.1, gltf-json 1.4.1, gltf-derive 1.4.1 (https://github.com/gltf-rs/gltf) | glTF 2.0 import (crates/io/src/gltf_in.rs): the JSON document model and its reference checks; the GLB container, buffers and accessors are read by SolidCraft's own code | MIT OR Apache-2.0 | +| inflections 1.1.1 (build-time, through gltf-derive) | case conversion in gltf's derive macros | MIT | +| lazy_static 1.5.1 (through gltf-json) | | MIT OR Apache-2.0 | + +The glTF test files are built by the tests themselves (crates/io/src/gltf_in_tests.rs, +crates/engine/src/tests/gltf_import.rs); no third-party models are committed. + ## Recovered contributions | SolidCraft file | Original contribution | Licence | diff --git a/Cargo.lock b/Cargo.lock index 0e4b61c28..137e4c9ac 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1531,6 +1531,42 @@ dependencies = [ "web-sys", ] +[[package]] +name = "gltf" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3ce1918195723ce6ac74e80542c5a96a40c2b26162c1957a5cd70799b8cacf7" +dependencies = [ + "byteorder", + "gltf-json", + "lazy_static", + "serde_json", +] + +[[package]] +name = "gltf-derive" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14070e711538afba5d6c807edb74bcb84e5dbb9211a3bf5dea0dfab5b24f4c51" +dependencies = [ + "inflections", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "gltf-json" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6176f9d60a7eab0a877e8e96548605dedbde9190a7ae1e80bbcc1c9af03ab14" +dependencies = [ + "gltf-derive", + "serde", + "serde_derive", + "serde_json", +] + [[package]] name = "glutin" version = "0.32.3" @@ -1877,6 +1913,12 @@ dependencies = [ "hashbrown 0.17.1", ] +[[package]] +name = "inflections" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a257582fdcde896fd96463bf2d40eefea0580021c0712a0e2b028b60b47a837a" + [[package]] name = "inout" version = "0.1.4" @@ -2047,6 +2089,12 @@ dependencies = [ "smallvec", ] +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + [[package]] name = "libc" version = "0.2.190" @@ -3808,6 +3856,7 @@ dependencies = [ name = "solidcraft-io" version = "0.13.0" dependencies = [ + "gltf", "quick-xml", "serde", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index a35256e36..07107d92f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -53,6 +53,9 @@ rayon = "1.12" # packages (3MF) zip = { version = "3", default-features = false, features = ["deflate"] } quick-xml = "0.41" +# 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"] } # fonts (sketch text outlines; MIT OR Apache-2.0, pure Rust) ttf-parser = { version = "0.25", default-features = false, features = ["std"] } diff --git a/README.md b/README.md index 233e64064..e99eef6df 100644 --- a/README.md +++ b/README.md @@ -129,7 +129,8 @@ rebuild with no errors, replayed here at 2× speed. 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 and OBJ import as mesh bodies (they render, measure, move and export; solid features + 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 @@ -230,7 +231,7 @@ configuration and an example session: [docs/mcp.md](docs/mcp.md). | 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 CPU rasterizer | | L2 | `doc` | parameters, expressions, the feature timeline and its incremental evaluation | -| L3 | `io` | design files, STL/OBJ/STEP/3MF export, STEP and 3MF/STL import features | +| 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/THIRD-PARTY-LICENSES.txt b/THIRD-PARTY-LICENSES.txt index f9063778e..a1ae0e020 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 508 crates below. +SolidCraft (the desktop app, solidcraft-cli and the web app) is built from the 513 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. @@ -145,6 +145,9 @@ getrandom 0.3.4 (MIT OR Apache-2.0) getrandom 0.4.3 (MIT OR Apache-2.0) glifo 0.2.0 (Apache-2.0 OR MIT) glow 0.17.0 (MIT OR Apache-2.0 OR Zlib) +gltf 1.4.1 (MIT OR Apache-2.0) +gltf-derive 1.4.1 (MIT OR Apache-2.0) +gltf-json 1.4.1 (MIT OR Apache-2.0) glutin 0.32.3 (Apache-2.0) glutin-winit 0.5.0 (MIT) glutin_egl_sys 0.7.1 (Apache-2.0) @@ -176,6 +179,7 @@ idna 1.1.0 (MIT OR Apache-2.0) idna_adapter 1.2.2 (Apache-2.0 OR MIT) image 0.25.10 (MIT OR Apache-2.0) indexmap 2.14.2 (Apache-2.0 OR MIT) +inflections 1.1.1 (MIT) inout 0.1.4 (MIT OR Apache-2.0) itertools 0.13.0 (MIT OR Apache-2.0) itertools 0.15.0 (MIT OR Apache-2.0) @@ -190,6 +194,7 @@ katexit 0.1.5 (MIT OR Apache-2.0) keyring 3.6.3 (MIT OR Apache-2.0) khronos-egl 6.0.0 (MIT/Apache-2.0) kurbo 0.13.1 (Apache-2.0 OR MIT) +lazy_static 1.5.1 (MIT OR Apache-2.0) libc 0.2.190 (MIT OR Apache-2.0) libdbus-sys 0.2.7 (Apache-2.0/MIT) libloading 0.8.9 (ISC) @@ -536,17 +541,17 @@ async-io 2.6.0, async-lock 3.4.2, async-process 2.5.0, async-recursion 1.2.0, as 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, -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, 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 +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, 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 @@ -1055,22 +1060,23 @@ blocking 1.7.0, bumpalo 3.20.3, cfg-if 1.0.5, cgl 0.3.2, concurrent-queue 2.5.0, 0.1.3, crossbeam-deque 0.8.8, crossbeam-epoch 0.9.21, crossbeam-utils 0.8.23, dbus-secret-service 4.1.0, derive_arbitrary 1.5.0, displaydoc 0.2.7, either 1.19.0, equivalent 1.0.2, errno 0.3.14, euclid 0.22.14, event-listener 5.4.2, event-listener-strategy 0.5.4, fastrand 2.5.0, flate2 1.1.10, -form_urlencoded 1.2.2, futures-lite 2.6.1, gethostname 1.1.0, glow 0.17.0, hashbrown 0.16.1, -hashbrown 0.17.1, hermit-abi 0.5.3, httparse 1.10.1, idna 1.1.0, idna_adapter 1.2.2, indexmap -2.14.2, itertools 0.13.0, itertools 0.15.0, js-sys 0.3.106, khronos-egl 6.0.0, linux-raw-sys 0.12.1, -linux-raw-sys 0.4.15, lock_api 0.4.14, log 0.4.34, num 0.4.3, num-bigint 0.4.8, num-complex 0.4.6, -num-integer 0.1.47, num-iter 0.1.46, num-rational 0.4.2, num-traits 0.2.19, once_cell 1.21.4, -openssl-probe 0.2.1, ordered-stream 0.2.0, parking 2.2.1, parking_lot 0.12.5, parking_lot_core -0.9.12, percent-encoding 2.3.2, piper 0.2.5, plain 0.2.3, png 0.18.1, polling 3.11.0, pollster -0.4.0, pollster 1.0.1, rayon 1.12.0, rayon-core 1.13.0, renderdoc-sys 1.1.0, robust 1.2.0, ron -0.12.2, rustc-hash 1.1.0, rustix 0.38.44, rustix 1.1.5, rustls 0.23.46, rustls-native-certs 0.8.5, -scoped-tls 1.0.1, scopeguard 1.2.0, secret-service 4.0.0, security-framework 2.11.1, -security-framework 3.7.0, security-framework-sys 2.17.0, signal-hook-registry 1.4.8, simd_cesu8 -1.2.0, smallvec 1.16.2, smol_str 0.2.2, stable_deref_trait 1.2.1, syn 1.0.109, tempfile 3.27.0, -ttf-parser 0.25.1, unicode-segmentation 1.13.3, unicode-width 0.2.2, url 2.5.8, uuid 1.27.0, wasi -0.11.1+wasi-snapshot-preview1, wasip2 1.0.4+wasi-0.2.12, wasm-bindgen 0.2.129, wasm-bindgen-futures -0.4.79, wasm-bindgen-macro 0.2.129, wasm-bindgen-macro-support 0.2.129, wasm-bindgen-shared 0.2.129, -web-sys 0.3.106, weezl 0.1.12, wit-bindgen 0.57.1 +form_urlencoded 1.2.2, futures-lite 2.6.1, gethostname 1.1.0, glow 0.17.0, gltf 1.4.1, gltf-derive +1.4.1, gltf-json 1.4.1, hashbrown 0.16.1, hashbrown 0.17.1, hermit-abi 0.5.3, httparse 1.10.1, idna +1.1.0, idna_adapter 1.2.2, indexmap 2.14.2, itertools 0.13.0, itertools 0.15.0, js-sys 0.3.106, +khronos-egl 6.0.0, lazy_static 1.5.1, linux-raw-sys 0.12.1, linux-raw-sys 0.4.15, lock_api 0.4.14, +log 0.4.34, num 0.4.3, num-bigint 0.4.8, num-complex 0.4.6, num-integer 0.1.47, num-iter 0.1.46, +num-rational 0.4.2, num-traits 0.2.19, once_cell 1.21.4, openssl-probe 0.2.1, ordered-stream 0.2.0, +parking 2.2.1, parking_lot 0.12.5, parking_lot_core 0.9.12, percent-encoding 2.3.2, piper 0.2.5, +plain 0.2.3, png 0.18.1, polling 3.11.0, pollster 0.4.0, pollster 1.0.1, rayon 1.12.0, rayon-core +1.13.0, renderdoc-sys 1.1.0, robust 1.2.0, ron 0.12.2, rustc-hash 1.1.0, rustix 0.38.44, rustix +1.1.5, rustls 0.23.46, rustls-native-certs 0.8.5, scoped-tls 1.0.1, scopeguard 1.2.0, secret-service +4.0.0, security-framework 2.11.1, security-framework 3.7.0, security-framework-sys 2.17.0, +signal-hook-registry 1.4.8, simd_cesu8 1.2.0, smallvec 1.16.2, smol_str 0.2.2, stable_deref_trait +1.2.1, syn 1.0.109, tempfile 3.27.0, ttf-parser 0.25.1, unicode-segmentation 1.13.3, unicode-width +0.2.2, url 2.5.8, uuid 1.27.0, wasi 0.11.1+wasi-snapshot-preview1, wasip2 1.0.4+wasi-0.2.12, +wasm-bindgen 0.2.129, wasm-bindgen-futures 0.4.79, wasm-bindgen-macro 0.2.129, +wasm-bindgen-macro-support 0.2.129, wasm-bindgen-shared 0.2.129, web-sys 0.3.106, weezl 0.1.12, +wit-bindgen 0.57.1 ================================================================================ Apache License @@ -5922,6 +5928,65 @@ freely, subject to the following restrictions: misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. +================================================================================ +gltf 1.4.1, gltf-json 1.4.1 +================================================================================ + +Copyright (c) 2017 The gltf Library Developers + +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. + +================================================================================ +gltf-derive 1.4.1 +================================================================================ + +`gltf_derive` was adapted from `validator_derive` (https://github.com/Keats/validator) +which has the following license: + +The MIT License (MIT) + +Copyright (c) 2016 Vincent Prouillet + +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. + ================================================================================ glutin 0.32.3, glutin_egl_sys 0.7.1, glutin_glx_sys 0.6.1, glutin_wgl_sys 0.6.1 ================================================================================ @@ -7187,6 +7252,31 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +================================================================================ +inflections 1.1.1 +================================================================================ + +Copyright (c) 2016 Caleb Meredith + +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. + ================================================================================ inout 0.1.4 ================================================================================ diff --git a/apps/solidcraft-web/src/files.rs b/apps/solidcraft-web/src/files.rs index 5eab04544..126bede0c 100644 --- a/apps/solidcraft-web/src/files.rs +++ b/apps/solidcraft-web/src/files.rs @@ -458,7 +458,7 @@ fn input_picker(files: &Rc, intent: Intent) { let Some(doc) = web_sys::window().and_then(|w| w.document()) else { return }; let Ok(input) = doc.create_element("input").map(|e| e.unchecked_into::()) else { return }; input.set_type("file"); - input.set_accept(".solidcraft,.solvecraft,.json,.step,.stp,.3mf,.stl"); + input.set_accept(".solidcraft,.solvecraft,.json,.step,.stp,.3mf,.stl,.obj,.glb,.gltf"); // Attached (hidden) while it is open: some browsers ignore a click on a detached input. let _ = input.set_attribute("style", "display:none"); if let Some(body) = doc.body() { diff --git a/apps/solidcraft-web/src/main.rs b/apps/solidcraft-web/src/main.rs index f3a788de5..b9ff0d74f 100644 --- a/apps/solidcraft-web/src/main.rs +++ b/apps/solidcraft-web/src/main.rs @@ -85,7 +85,16 @@ mod web { for (text, error) in self.files.messages.borrow_mut().drain(..) { self.app.set_status(text, error); } - let incoming: Vec<_> = self.files.incoming.borrow_mut().drain(..).collect(); + let mut incoming: Vec<_> = self.files.incoming.borrow_mut().drain(..).collect(); + // A glTF file's buffers picked with it are kept next to it, not opened. + incoming.retain_mut(|(name, bytes, _)| { + let companion = + std::path::Path::new(name.as_str()).extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("bin")); + if companion { + vfs::insert(&format!("{}{name}", files::UPLOAD), std::mem::take(bytes)); + } + !companion + }); for (name, bytes, intent) in incoming { let design = solidcraft_engine::io::is_design_path(&name); let path = if design && intent == Intent::Open { diff --git a/apps/solidcraft/src/main.rs b/apps/solidcraft/src/main.rs index 75f05b7f1..c2c8cfee1 100644 --- a/apps/solidcraft/src/main.rs +++ b/apps/solidcraft/src/main.rs @@ -6,7 +6,7 @@ //! the software renderer; see `startup` and docs/book/src/guide/troubleshooting.md. //! //! A `.step`/`.stp` file opens as a new design holding the file's bodies (an Import feature); a -//! `.3mf`/`.stl` file as a new design holding mesh bodies. +//! `.3mf`/`.stl`/`.obj`/`.glb`/`.gltf` file as a new design holding mesh bodies. //! //! `--control ` (or `SOLIDCRAFT_CONTROL_PORT`) starts a localhost JSON-lines control //! server: `{"id":1,"method":"engine.execute","params":{"command":"solid.box","params":{…}}}`. @@ -125,12 +125,18 @@ fn services(cc: &eframe::CreationContext<'_>) -> Services { "3MF", "stl", "STL", + "obj", + "OBJ", + "glb", + "GLB", + "gltf", + "GLTF", ], ) .add_filter("SolidCraft design (container or JSON)", &[io::DESIGN_EXT, io::LEGACY_DESIGN_EXT, "json"]) .add_filter("STEP", &["step", "stp", "STEP", "STP"]) .add_filter("IGES", &["igs", "iges", "IGS", "IGES"]) - .add_filter("Mesh (3MF, STL)", &["3mf", "3MF", "stl", "STL"]) + .add_filter("Mesh (3MF, STL, OBJ, glTF)", &["3mf", "3MF", "stl", "STL", "obj", "OBJ", "glb", "GLB", "gltf", "GLTF"]) .add_filter("Sketch drawings (DXF, SVG)", &["dxf", "DXF", "svg", "SVG"]) .add_filter("All files", &["*"]) .pick_file(); diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 1fdf684a0..4424794d7 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -20,7 +20,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .icon("open") .key("Ctrl+O") .noundo() - .params("path: .solidcraft design, or a .step/.stp/.igs/.3mf/.stl/.obj file (opens as a new design holding the file as a component named after it, as file.insert_step makes); up?: z|y and names?: solid|product|instance for a STEP or IGES file (see file.insert_step)"), + .params("path: .solidcraft design, or a .step/.stp/.igs/.3mf/.stl/.obj/.glb/.gltf file (opens as a new design holding the file as a component named after it, as file.insert_step and file.insert_mesh make); up?: z|y for a STEP, IGES or glTF file (see file.insert_step and file.insert_mesh); names?: solid|product|instance for a STEP or IGES file (see file.insert_step)"), CommandSpec::new("file.insert_step", "Insert STEP", insert_step) .at("SOLID", "INSERT") .icon("import") @@ -28,7 +28,7 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("file.insert_mesh", "Insert Mesh", insert_mesh) .at("SOLID", "INSERT") .icon("import") - .params("path: .3mf, .stl or .obj file (its meshes join the design as mesh bodies in a new component named after the file → component, component_name, occurrence); name?"), + .params("path: .3mf, .stl, .obj, .glb or .gltf file (its meshes join the design as mesh bodies in a new component named after the file → component, component_name, occurrence; a glTF file's node tree becomes nested components held as one rigid group until component.unlock, a mesh placed again another occurrence, its materials the bodies' appearances, and its metres millimetres); name?; up?: z|y for a glTF file (default y: glTF has Y up, so the import's component is turned a quarter turn about X, Y becoming Z → stand_up: its occurrence; z: the file's axes are kept)"), CommandSpec::new("file.save", "Save", save) .icon("save") .key("Ctrl+S") @@ -113,19 +113,10 @@ fn add_step(s: &mut Session, path: &str, name: Option<&str>, options: &StepOptio let sf = read_step(path, options.names)?; let fname = name.filter(|n| !n.trim().is_empty()).unwrap_or(&sf.name).to_string(); let cname = import::component_name(path, name); - let (id, placed) = import::add_in_component(s, sf.kind, &fname, sf.body_names, &cname, Some(&sf.import))?; + let (id, placed) = import::add_in_component(s, sf.kind, &fname, sf.body_names, &cname, import::Tree::Step(&sf.import))?; // Y up: the import's component is turned a quarter turn about X (Y becomes Z), so an // assembly's parts and instances turn together. - let turned = if options.y_up { - let occ = placed.occurrence.ok_or_else(|| EngineError::Other("the import has no placement to turn".into()))?; - if let Some(o) = s.doc_mut().occurrences.iter_mut().find(|o| o.id == occ) { - o.transform = solidcraft_doc::mat_mul(&quarter_turn_x(), &o.transform); - } - s.refresh(); - Some(occ) - } else { - None - }; + let turned = if options.y_up { turn_up(s, &placed)? } else { None }; let created = created_bodies(s, id); let fname = s.doc.feature(id).map(|f| f.name.clone()).unwrap_or_default(); let mut out = json!({"path": path, "feature": id, "name": fname, "bodies": created, "created_bodies": created, "warnings": sf.warnings}); @@ -141,27 +132,83 @@ fn created_bodies(s: &Session, feature: u64) -> Vec { s.model.state().bodies.iter().filter(|b| b.feature == feature).map(|b| b.name.clone()).collect() } -/// Add a MeshImport feature for a 3MF, STL or OBJ file, in a new component named after the file. -fn add_mesh(s: &mut Session, path: &str, name: Option<&str>) -> Result { +/// Add a MeshImport feature for a 3MF, STL, OBJ or glTF file, in a new component named after the +/// file. A glTF file's nodes become components in it, and its materials the bodies' looks; it is +/// in metres with Y up, so unless `y_up` is false its component is turned to Z up (#1505). +fn add_mesh(s: &mut Session, path: &str, name: Option<&str>, y_up: Option) -> Result { + let err = |e: solidcraft_io::IoError| EngineError::Other(format!("{path}: {e}")); let bytes = solidcraft_io::vfs::read(path, solidcraft_io::MAX_3MF_BYTES).map_err(|e| EngineError::Other(format!("{path}: {e}")))?; - let mf = solidcraft_io::mesh_import_feature(&bytes, path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?; + let gltf = solidcraft_io::is_gltf_path(path); + let (mf, plan, looks) = if gltf { + let dir = std::path::Path::new(path).parent().map(std::path::Path::to_path_buf).unwrap_or_default(); + let mut load = + |name: &str| solidcraft_io::vfs::read(&dir.join(name).to_string_lossy(), solidcraft_io::MAX_GLTF_BYTES).map_err(|e| e.to_string()); + let mut g = solidcraft_io::read_gltf(&bytes, path, &mut load).map_err(err)?; + if !import::mesh_plan_fits(&g.plan) { + g.flatten(); + } + (g.feature, Some(g.plan), g.looks) + } else { + (solidcraft_io::mesh_import_feature(&bytes, path).map_err(err)?, None, Vec::new()) + }; let fname = name.filter(|n| !n.trim().is_empty()).unwrap_or(&mf.name).to_string(); let cname = import::component_name(path, name); - let (id, placed) = import::add_in_component(s, mf.kind, &fname, mf.body_names, &cname, None)?; + let tree = match &plan { + Some(p) if !p.places.is_empty() => import::Tree::Mesh(p), + _ => import::Tree::Flat, + }; + let (id, placed) = import::add_in_component(s, mf.kind, &fname, mf.body_names, &cname, tree)?; let bodies = created_bodies(s, id); + // The materials' looks, body by body (the bodies are built in the file's order). + if looks.iter().any(Option::is_some) && bodies.len() == looks.len() { + for (body, look) in bodies.iter().zip(looks) { + if let Some(look) = look { + s.doc_mut().appearances.bodies.insert(body.clone(), look); + } + } + s.refresh(); + } + let turned = if gltf && y_up.unwrap_or(true) { turn_up(s, &placed)? } else { None }; let fname = s.doc.feature(id).map(|f| f.name.clone()).unwrap_or_default(); let mut out = json!({"path": path, "feature": id, "name": fname, "bodies": bodies, "created_bodies": bodies, "warnings": mf.warnings}); placed.report(&mut out); + if let Some(turned) = turned { + out["stand_up"] = json!(turned); + } Ok(out) } +/// Turn an import's component a quarter turn about X (the file's Y up becomes Z up), contents +/// and all. Returns its occurrence. +fn turn_up(s: &mut Session, placed: &import::Placed) -> Result> { + let occ = placed.occurrence.ok_or_else(|| EngineError::Other("the import has no placement to turn".into()))?; + if let Some(o) = s.doc_mut().occurrences.iter_mut().find(|o| o.id == occ) { + o.transform = solidcraft_doc::mat_mul(&quarter_turn_x(), &o.transform); + } + s.refresh(); + Ok(Some(occ)) +} + +/// `up` for a glTF file: `y` (the default: glTF is Y up) turns it to Z up, `z` keeps its axes. +/// Other mesh files take no `up`. +fn mesh_up(p: &Value, path: &str, cmd: &str) -> Result> { + if p.get("up").is_none_or(Value::is_null) { + return Ok(None); + } + if !solidcraft_io::is_gltf_path(path) { + return Err(bad(cmd, "`up` applies to STEP, IGES and glTF files only")); + } + Ok(Some(step_options(p, cmd)?.y_up)) +} + fn insert_mesh(s: &mut Session, p: &Value) -> Result { let cmd = "file.insert_mesh"; let path = path_arg(p, cmd)?; if !solidcraft_io::is_mesh_path(path) { - return Err(bad(cmd, "only 3MF and STL files (.3mf, .stl) can be inserted as meshes")); + return Err(bad(cmd, "only 3MF, STL, OBJ and glTF files (.3mf, .stl, .obj, .glb, .gltf) can be inserted as meshes")); } - add_mesh(s, path, str_(p, "name")) + let up = mesh_up(p, path, cmd)?; + add_mesh(s, path, str_(p, "name"), up) } fn insert_step(s: &mut Session, p: &Value) -> Result { @@ -176,8 +223,11 @@ fn insert_step(s: &mut Session, p: &Value) -> Result { fn open(s: &mut Session, p: &Value) -> Result { let path = path_arg(p, "doc.open")?; - if !solidcraft_io::is_step_path(path) && ["up", "names"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) { - return Err(bad("doc.open", "`up` and `names` apply to STEP and IGES files only")); + if !solidcraft_io::is_step_path(path) && p.get("names").is_some_and(|v| !v.is_null()) { + return Err(bad("doc.open", "`names` applies to STEP and IGES files only")); + } + if !solidcraft_io::is_step_path(path) && !solidcraft_io::is_gltf_path(path) && p.get("up").is_some_and(|v| !v.is_null()) { + return Err(bad("doc.open", "`up` applies to STEP, IGES and glTF files only")); } if solidcraft_io::is_step_path(path) || solidcraft_io::is_mesh_path(path) { // A new, unsaved design holding the file's bodies. @@ -186,7 +236,7 @@ fn open(s: &mut Session, p: &Value) -> Result { let r = if solidcraft_io::is_step_path(path) { add_step(&mut fresh, path, None, &step_options(p, "doc.open")?)? } else { - add_mesh(&mut fresh, path, None)? + add_mesh(&mut fresh, path, None, mesh_up(p, path, "doc.open")?)? }; // The design is the file: its component is the one being worked in. if let Some(c) = r["component"].as_u64() { diff --git a/crates/engine/src/cmd/file_import.rs b/crates/engine/src/cmd/file_import.rs index ee016fa98..399b4f5df 100644 --- a/crates/engine/src/cmd/file_import.rs +++ b/crates/engine/src/cmd/file_import.rs @@ -51,7 +51,47 @@ fn rigid(m: &Mat) -> bool { crate::cmd::component::valid_position(m) } +/// What an import's file says about its structure. +#[derive(Clone, Copy)] +pub(crate) enum Tree<'a> { + /// Nothing: every body in the import's component. + Flat, + /// A STEP file's products and placements. + Step(&'a StepImport), + /// A mesh file's components (glTF nodes), bodies already in their component's frame + /// (checked with [`mesh_plan_fits`] first). + Mesh(&'a solidcraft_io::MeshPlan), +} + +/// Can the components of `plan` be made as it says? (Otherwise its bodies are built in place.) +pub(crate) fn mesh_plan_fits(plan: &solidcraft_io::MeshPlan) -> bool { + Plan::of_mesh(plan).is_some() +} + impl Plan { + /// A glTF file's node plan, as it is; `None` when an occurrence can't hold it (a placement + /// that isn't rigid, or components out of order), so the caller builds the bodies in place. + fn of_mesh(plan: &solidcraft_io::MeshPlan) -> Option { + let mut made = 0usize; + let mut places = Vec::with_capacity(plan.places.len()); + for p in &plan.places { + // Components are made in the order of their first placement, inside one made before. + if p.slot > made || p.slot >= plan.slots.len() || p.parent.is_some_and(|q| q >= made || q == p.slot) || !rigid(&p.transform) { + return None; + } + if p.slot == made { + made += 1; + } + places.push(Place { slot: p.slot, parent: p.parent, transform: p.transform }); + } + if plan.bodies.iter().flatten().any(|s| *s >= made) { + return None; + } + let slots = plan.slots.iter().take(made).map(|n| Slot { name: n.clone() }).collect(); + let bodies = plan.bodies.iter().enumerate().filter_map(|(b, slot)| slot.map(|s| (b, s, IDENTITY))).collect(); + Some(Plan { slots, places, bodies, skip: Vec::new() }) + } + fn of(imp: &StepImport) -> Plan { let mut plan = Plan::default(); // One root product is the import's own component; several are components under it. @@ -200,10 +240,14 @@ pub(crate) fn add_in_component( feature_name: &str, body_names: Vec, name: &str, - imp: Option<&StepImport>, + tree: Tree<'_>, ) -> Result<(u64, Placed)> { let (top, top_occ) = new_component(s, name)?; - let plan = imp.map(Plan::of).unwrap_or_default(); + let (plan, imp) = match tree { + Tree::Flat => (Plan::default(), None), + Tree::Step(imp) => (Plan::of(imp), Some(imp)), + Tree::Mesh(m) => (Plan::of_mesh(m).ok_or_else(|| EngineError::Other("import: the file's node tree can't be placed".into()))?, None), + }; // The components, each made at its first placement; the others are further occurrences. let mut comps: Vec = Vec::with_capacity(plan.slots.len()); let mut first_occ: Vec> = Vec::with_capacity(plan.slots.len()); @@ -238,6 +282,8 @@ pub(crate) fn add_in_component( // The bodies' names, as the feature will give them (checked once it is built). let names = match (&kind, imp) { (FeatureKind::Import { skip, .. }, Some(imp)) => solidcraft_doc::import_body_names(&s.model.state(), &body_names, imp, skip), + // Mesh bodies keep their names unless taken (then they are put right once built). + (FeatureKind::MeshImport { .. }, _) => body_names.iter().cloned().map(Some).collect(), _ => Vec::new(), }; let id = s.doc_mut().add_feature(kind, Some(feature_name))?; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index b990ace92..8e1883281 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -307,6 +307,7 @@ mod blend_fit; mod boolean_diagnostics; mod component_frames; mod curved_seam_round; +mod gltf_import; mod import_component; mod large_step_import; mod loft_cut; diff --git a/crates/engine/src/tests/gltf_import.rs b/crates/engine/src/tests/gltf_import.rs new file mode 100644 index 000000000..16c3ecc41 --- /dev/null +++ b/crates/engine/src/tests/gltf_import.rs @@ -0,0 +1,210 @@ +//! glTF files import as mesh bodies (#1505): in a component named after the file, the node tree +//! as nested components held as one rigid group, a mesh placed again another occurrence of one +//! component, metres as millimetres, Y up turned to Z up (unless `up: z`), and the materials as +//! the bodies' appearances. Every file here is built by the test. + +use serde_json::{Value, json}; + +use super::run; +use crate::*; + +fn temp_dir(tag: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("solidcraft-gltf-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// A glTF document with one buffer holding a cube of side 0.01 m (10 mm) at the origin. +struct Cube { + bin: Vec, + json: Value, +} + +fn cube_file() -> Cube { + let s = 0.01f32; + let p: Vec<[f32; 3]> = (0..8).map(|i| [(i & 1) as f32 * s, ((i >> 1) & 1) as f32 * s, ((i >> 2) & 1) as f32 * s]).collect(); + let t: [u16; 36] = [0, 2, 1, 1, 2, 3, 4, 5, 6, 5, 7, 6, 0, 1, 4, 1, 5, 4, 2, 6, 3, 3, 6, 7, 0, 4, 2, 2, 4, 6, 1, 3, 5, 3, 7, 5]; + let mut bin: Vec = p.iter().flatten().flat_map(|v| v.to_le_bytes()).collect(); + bin.extend(t.iter().flat_map(|v| v.to_le_bytes())); + let json = json!({ + "asset": {"version": "2.0"}, + "scene": 0, + "scenes": [{"nodes": []}], + "nodes": [], + "meshes": [ + {"name": "Block", "primitives": [{"attributes": {"POSITION": 0}, "indices": 1, "material": 0}]}, + {"name": "Peg", "primitives": [{"attributes": {"POSITION": 0}, "indices": 1, "material": 1}]}, + ], + "materials": [ + {"name": "Brass", "pbrMetallicRoughness": {"baseColorFactor": [0.8, 0.5, 0.1, 1.0], "metallicFactor": 1.0, "roughnessFactor": 0.3}}, + {"name": "Blue", "pbrMetallicRoughness": {"baseColorFactor": [0.0, 0.0, 1.0, 1.0], "metallicFactor": 0.0, "roughnessFactor": 0.8}}, + ], + "accessors": [ + {"bufferView": 0, "componentType": 5126, "count": 8, "type": "VEC3", "min": [0.0, 0.0, 0.0], "max": [s, s, s]}, + {"bufferView": 1, "componentType": 5123, "count": 36, "type": "SCALAR"}, + ], + "bufferViews": [{"buffer": 0, "byteOffset": 0, "byteLength": 96}, {"buffer": 0, "byteOffset": 96, "byteLength": 72}], + "buffers": [{"byteLength": bin.len()}], + }); + Cube { bin, json } +} + +impl Cube { + fn glb(&self, dir: &std::path::Path, name: &str) -> String { + let path = dir.join(name); + std::fs::write(&path, solidcraft_io::glb_container(self.json.to_string().as_bytes(), &self.bin)).unwrap(); + path.to_string_lossy().to_string() + } +} + +/// World bounding boxes of every shown body, rounded to 0.001 mm, sorted. +fn shown_boxes(s: &Session) -> Vec<[i64; 6]> { + let mut out: Vec<[i64; 6]> = s + .world_state() + .bodies + .iter() + .map(|b| { + let bb = solidcraft_kernel::measure(&b.body).unwrap().bbox; + [bb.min.x, bb.min.y, bb.min.z, bb.max.x, bb.max.y, bb.max.z].map(|v| (v * 1000.0).round() as i64) + }) + .collect(); + out.sort(); + out +} + +fn mm(b: [f64; 6]) -> [i64; 6] { + b.map(|v| (v * 1000.0).round() as i64) +} + +fn components(s: &mut Session) -> Vec { + run(s, "component.list", json!({}))["components"].as_array().unwrap().clone() +} + +/// `robot.glb`: a `Base` (Block, at x = 0.1 m) with an `Arm` (Peg, 0.05 m up Y, a quarter turn +/// about Y), and three `Bolt` nodes all placing the Peg mesh (0.03 m apart along X). +fn robot(dir: &std::path::Path, up: Option<&str>) -> (Session, Value, String) { + let mut c = cube_file(); + c.json["nodes"] = json!([ + {"name": "Base", "mesh": 0, "translation": [0.1, 0.0, 0.0], "children": [1]}, + {"name": "Arm", "mesh": 1, "translation": [0.0, 0.05, 0.0], "rotation": [0.0, 0.70710677, 0.0, 0.70710677]}, + {"name": "Bolt", "mesh": 1, "translation": [0.0, 0.0, 0.0]}, + {"name": "Bolt", "mesh": 1, "translation": [0.03, 0.0, 0.0]}, + {"name": "Bolt", "mesh": 1, "translation": [0.06, 0.0, 0.0]}, + ]); + c.json["scenes"][0]["nodes"] = json!([0, 2, 3, 4]); + let path = c.glb(dir, "robot.glb"); + let mut s = Session::default(); + let mut p = json!({"path": path}); + if let Some(up) = up { + p["up"] = json!(up); + } + let r = run(&mut s, "file.insert_mesh", p); + (s, r, path) +} + +#[test] +fn a_gltf_node_tree_comes_in_as_components_with_instances() { + let dir = temp_dir("tree"); + let (mut s, r, path) = robot(&dir, Some("z")); + assert!(r.get("stand_up").is_none(), "{r}"); + let list = components(&mut s); + let names: Vec<&str> = list.iter().filter_map(|c| c["name"].as_str()).collect(); + // The arm and the bolts place the same mesh the same way inside: one component, named + // after the mesh. + for n in ["robot", "Base", "Peg"] { + assert!(names.contains(&n), "{n} in {names:?}"); + } + assert_eq!(r["component_name"], "robot"); + assert_eq!(r["subcomponents"], 2, "{r}"); + let id = |n: &str| list.iter().find(|c| c["name"] == n).unwrap()["id"].as_u64().unwrap(); + // Placed four times; its mesh is built once. + assert_eq!(s.doc.occurrences.iter().filter(|o| o.component == id("Peg")).count(), 4); + assert_eq!(s.model.state().bodies.len(), 2, "Block and Peg, once each"); + let peg_parent = list.iter().find(|c| c["name"] == "Peg").unwrap()["parent"].as_u64().unwrap(); + assert_eq!(peg_parent, id("Base"), "made where it is first placed"); + // Metres are millimetres, and each body is where the file puts it. The arm is turned a + // quarter about Y: its X becomes -Z. + let want = vec![ + mm([0.0, 0.0, 0.0, 10.0, 10.0, 10.0]), + mm([30.0, 0.0, 0.0, 40.0, 10.0, 10.0]), + mm([60.0, 0.0, 0.0, 70.0, 10.0, 10.0]), + mm([100.0, 0.0, 0.0, 110.0, 10.0, 10.0]), + mm([100.0, 50.0, -10.0, 110.0, 60.0, 0.0]), + ]; + assert_eq!(shown_boxes(&s), want); + // Materials are the bodies' looks, with their metal and roughness. + let brass = s.doc.appearances.bodies.get("Block").expect("the block's look"); + assert_eq!(brass.name, "Brass"); + assert_eq!(brass.color, [231, 188, 89]); + let pbr = brass.pbr.expect("PBR"); + assert!((pbr.metallic() - 1.0).abs() < 1e-9 && (pbr.roughness() - 0.3).abs() < 1e-6); + assert_eq!(s.doc.appearances.bodies.values().filter(|l| l.name == "Blue").count(), 1); + + // Rigid until unlocked. + let robot = id("robot"); + assert_eq!(s.contents_joints(robot).len(), 5, "one for each placement"); + let r = run(&mut s, "component.unlock", json!({"component": "robot"})); + assert_eq!(r["joints"].as_array().unwrap().len(), 5, "{r}"); + assert!(s.contents_joints(robot).is_empty()); + run(&mut s, "edit.undo", json!({})); + + // Saved and opened again, it is the same (nothing new is saved for glTF). + let design = dir.join("robot.solidcraft").to_string_lossy().to_string(); + run(&mut s, "file.save_as", json!({"path": design})); + let mut again = Session::default(); + run(&mut again, "doc.open", json!({"path": design})); + assert_eq!(shown_boxes(&again), want); + assert_eq!(again.doc.appearances.bodies.get("Block").map(|l| l.name.as_str()), Some("Brass")); + + // Opened by itself, the file is a new design of that component. + let mut opened = Session::default(); + let r = run(&mut opened, "doc.open", json!({"path": path, "up": "z"})); + assert_eq!(r["component_name"], "robot", "{r}"); + assert_eq!(shown_boxes(&opened), want); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn gltf_y_up_stands_up_by_default() { + let dir = temp_dir("up"); + let (s, r, _) = robot(&dir, None); + assert!(r["stand_up"].as_u64().is_some(), "{r}"); + // Y up becomes Z up: a body at file y in 50..60 mm is at z 50..60. + let boxes = shown_boxes(&s); + assert!(boxes.contains(&mm([100.0, 0.0, 50.0, 110.0, 10.0, 60.0])), "{boxes:?}"); + assert!(boxes.iter().all(|b| b[2] >= -1), "nothing below the ground: {boxes:?}"); + let e = Session::default().execute("file.insert_mesh", &json!({"path": "x.stl", "up": "y"})).unwrap_err().to_string(); + assert!(e.contains("glTF"), "{e}"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_gltf_with_its_bin_next_to_it_opens_and_broken_files_say_why() { + let dir = temp_dir("bin"); + let mut c = cube_file(); + c.json["nodes"] = json!([{"name": "Only", "mesh": 0}]); + c.json["scenes"][0]["nodes"] = json!([0]); + c.json["buffers"][0]["uri"] = json!("cube.bin"); + std::fs::write(dir.join("cube.bin"), &c.bin).unwrap(); + let path = dir.join("part.gltf").to_string_lossy().to_string(); + std::fs::write(&path, c.json.to_string()).unwrap(); + let mut s = Session::default(); + let r = run(&mut s, "doc.open", json!({"path": path})); + assert_eq!(r["bodies"], json!(["Block"]), "{r}"); + assert_eq!(s.doc.name, "part"); + assert_eq!(shown_boxes(&s), vec![mm([0.0, -10.0, 0.0, 10.0, 0.0, 10.0])], "turned Z up about X"); + + // The .bin missing, the file truncated: errors that say so, and the design is untouched. + std::fs::remove_file(dir.join("cube.bin")).unwrap(); + let before = s.doc.to_json(); + let e = s.execute("file.insert_mesh", &json!({"path": path})).unwrap_err().to_string(); + assert!(e.contains("cube.bin"), "{e}"); + let glb = dir.join("cut.glb"); + let whole = solidcraft_io::glb_container(c.json.to_string().as_bytes(), &c.bin); + std::fs::write(&glb, &whole[..whole.len() / 2]).unwrap(); + let e = s.execute("file.insert_mesh", &json!({"path": glb.to_string_lossy()})).unwrap_err().to_string(); + assert!(e.contains("truncated") || e.contains("GLB"), "{e}"); + assert_eq!(s.doc.to_json(), before); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index 3fbcadc36..fc9a7030d 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "solidcraft-io" -description = "SolidCraft file formats: designs (JSON), STL, OBJ, STEP and 3MF" +description = "SolidCraft file formats: designs (JSON), STL, OBJ, STEP, 3MF and glTF" version.workspace = true edition.workspace = true license.workspace = true @@ -15,6 +15,7 @@ solidcraft-doc = { workspace = true } thiserror = { workspace = true } zip = { workspace = true } quick-xml = { workspace = true } +gltf = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } sha2 = { workspace = true } diff --git a/crates/io/src/gltf_in.rs b/crates/io/src/gltf_in.rs new file mode 100644 index 000000000..bc0af454b --- /dev/null +++ b/crates/io/src/gltf_in.rs @@ -0,0 +1,871 @@ +//! glTF 2.0 import (`.glb`, `.gltf` with its `.bin` files next to it or embedded as `data:` +//! URIs): triangle meshes become mesh bodies, the node tree a component plan (#1505). +//! +//! The `gltf` crate reads the JSON document and checks its references; the GLB container and +//! every buffer, view and accessor are read here, with each length checked against the bytes +//! that are really there. The file is untrusted: sizes, counts, nesting and the nodes visited +//! are capped, and anything wrong is an error or a warning, never a panic. +//! +//! Geometry: glTF is in metres with Y up. Coordinates are scaled to millimetres here; turning +//! Y up into Z up is the caller's (the import component's placement, as for STEP). A node's +//! placement becomes an occurrence when it can be one (the rigid part of its transform); what +//! is left (scale, shear, a mirror) is baked into the node's meshes, so the hierarchy is kept +//! even under a scaled parent. A node that places the same mesh (and the same subtree) the +//! same way as an earlier one is another occurrence of that node's component. +//! +//! Materials: one body per mesh and material; the material's base colour (linear in glTF, +//! sRGB here), alpha (blended materials only) and metallic/roughness factors give the body's +//! look. Textures are not read. + +use std::collections::HashMap; +use std::hash::{Hash, Hasher}; + +use gltf::accessor::{DataType, Dimensions}; +use gltf::mesh::Mode; +use solidcraft_doc::appearance::Look; +use solidcraft_doc::{Mat, MeshData, mat_mul}; +use solidcraft_geom::Vec3; + +use crate::{IoError, MAX_3MF_BYTES, MeshFeature, Result}; + +/// Largest `.glb` / `.gltf` file read. +pub const MAX_GLTF_BYTES: usize = MAX_3MF_BYTES; +/// Most bytes of external and embedded buffers read for one file. +const MAX_BUFFER_BYTES: usize = 1 << 30; +/// Most vertices and triangles, over all bodies. +const MAX_VERTICES: usize = 20_000_000; +const MAX_TRIANGLES: usize = 20_000_000; +/// Most node placements followed (a node tree that shares or loops is cut off here). +const MAX_PLACEMENTS: usize = 100_000; +/// Deepest nesting kept as components; deeper nodes are baked into their parent's. +const MAX_COMPONENT_DEPTH: usize = 32; +/// Deepest nesting followed at all. +const MAX_DEPTH: usize = 64; +/// Most components one file makes. +const MAX_COMPONENTS: usize = 5_000; +/// Millimetres in a metre. +const MM: f64 = 1000.0; + +/// Is this a glTF file (`.glb`, `.gltf`, any case)? +pub fn is_gltf_path(path: &str) -> bool { + std::path::Path::new(path).extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("glb") || e.eq_ignore_ascii_case("gltf")) +} + +/// A placement of a component of the plan in another (`parent`, or the import's own component +/// when `None`), by a rigid transform in millimetres. +#[derive(Clone, Debug, PartialEq)] +pub struct PlanPlace { + pub slot: usize, + pub parent: Option, + pub transform: Mat, +} + +/// How a glTF file's nodes become components below the import's own: `slots` are the +/// components (by name), `places` their placements (the first one makes the component, later +/// ones are more occurrences of it), and `bodies` the component each mesh body goes into +/// (`None`: the import's own). Each body's coordinates are already in its component's frame. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct MeshPlan { + pub slots: Vec, + pub places: Vec, + pub bodies: Vec>, +} + +/// A glTF file read for import. +pub struct GltfImport { + /// The MeshImport feature: one mesh body per glTF mesh and material. + pub feature: MeshFeature, + /// Where the bodies go. + pub plan: MeshPlan, + /// Each body's look from its material (`None`: no material). + pub looks: Vec>, +} + +impl GltfImport { + /// Build every body where its component's first placement puts it, in the import's own + /// frame, and drop the components. + pub fn flatten(&mut self) { + if self.plan.places.is_empty() { + return; + } + let mut world: Vec> = vec![None; self.plan.slots.len()]; + for p in &self.plan.places { + let parent = match p.parent { + None => Some(solidcraft_doc::IDENTITY), + Some(q) => world.get(q).copied().flatten(), + }; + if let (Some(parent), Some(slot @ None)) = (parent, world.get_mut(p.slot)) { + *slot = Some(mat_mul(&parent, &p.transform)); + } + } + if let solidcraft_doc::FeatureKind::MeshImport { meshes, .. } = &mut self.feature.kind { + for (m, slot) in meshes.iter_mut().zip(&self.plan.bodies) { + let Some(frame) = slot.and_then(|s| world.get(s).copied().flatten()) else { continue }; + for p in m.positions.as_chunks_mut::<3>().0 { + let q = solidcraft_doc::apply_point(&frame, Vec3::new(p[0], p[1], p[2])); + *p = [q.x, q.y, q.z]; + } + } + } + self.plan = MeshPlan::default(); + } +} + +/// Reads an external file the glTF names (`uri`, relative to the glTF file's folder, already +/// percent-decoded and checked to stay in that folder). +pub type Loader<'a> = &'a mut dyn FnMut(&str) -> std::result::Result, String>; + +/// Read a `.glb` or `.gltf` file (`file` names it; its stem names the meshes when nothing in the +/// file does). External buffers are read through `load`. +pub fn read_gltf(bytes: &[u8], file: &str, load: Loader<'_>) -> Result { + if bytes.len() > MAX_GLTF_BYTES { + return Err(IoError::Invalid(format!("glTF file too large ({} MB)", bytes.len() >> 20))); + } + let (json, blob) = if bytes.starts_with(b"glTF") { split_glb(bytes)? } else { (bytes, None) }; + let doc = parse_document(json)?; + let stem = std::path::Path::new(file) + .file_stem() + .map(|s| s.to_string_lossy().trim().to_string()) + .filter(|s| !s.is_empty()) + .unwrap_or_else(|| "Mesh".into()); + let mut reader = Reader { + doc: &doc, + buffers: Buffers { blob, data: HashMap::new(), total: 0, load }, + meshes: Vec::new(), + looks: Vec::new(), + plan: MeshPlan::default(), + keys: HashMap::new(), + has_mesh: HashMap::new(), + open: Vec::new(), + slot_meshes: Vec::new(), + placements: 0, + vertices: 0, + triangles: 0, + skipped: Vec::new(), + cut_off: false, + stem: stem.clone(), + }; + let roots = scene_roots(&doc); + if roots.is_empty() { + return Err(IoError::Invalid("glTF has no nodes to import".into())); + } + // One root node is the import's own component (its placement baked in); several are + // components in it. + let units = scale(MM); + if let [root] = roots.as_slice() { + let m = reader.node(*root).map(|n| mat_mul(&units, &node_matrix(&n))).unwrap_or(units); + reader.walk_flat(*root, None, &m, 0)?; + } else { + for r in &roots { + reader.walk(*r, None, &units, 0)?; + } + } + if reader.meshes.is_empty() { + let why = reader.skipped.first().map(|s| format!(": {s}")).unwrap_or_default(); + return Err(IoError::Invalid(format!("glTF has no triangle meshes{why}"))); + } + let mut warnings = Vec::new(); + if !reader.skipped.is_empty() { + let n = reader.skipped.len(); + let first = reader.skipped.first().cloned().unwrap_or_default(); + warnings.push(if n == 1 { format!("left out: {first}") } else { format!("{n} parts left out (first: {first})") }); + } + if reader.cut_off { + warnings.push(format!("the node tree is too large or too deep: only the first {MAX_PLACEMENTS} placements were read")); + } + if doc.textures().len() > 0 { + warnings.push("textures are not imported: bodies take their materials' base colours".into()); + } + if doc.skins().len() > 0 || doc.animations().len() > 0 { + warnings.push("skins and animations are not imported: meshes are placed in their rest pose".into()); + } + let name = match reader.meshes.as_slice() { + [only] if !only.name.trim().is_empty() => only.name.clone(), + _ => stem, + }; + let file_name = std::path::Path::new(file).file_name().map(|s| s.to_string_lossy().to_string()).unwrap_or_else(|| file.to_string()); + let body_names = reader.meshes.iter().map(|m| m.name.clone()).collect(); + Ok(GltfImport { + feature: MeshFeature { name, body_names, kind: solidcraft_doc::FeatureKind::MeshImport { file: file_name, meshes: reader.meshes }, warnings }, + plan: reader.plan, + looks: reader.looks, + }) +} + +/// The JSON and binary chunks of a GLB container. +fn split_glb(bytes: &[u8]) -> Result<(&[u8], Option<&[u8]>)> { + let bad = |m: &str| IoError::Invalid(format!("GLB: {m}")); + let u32_at = |at: usize| bytes.get(at..at + 4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes); + let version = u32_at(4).ok_or_else(|| bad("truncated header"))?; + if version != 2 { + return Err(bad(&format!("version {version} is not glTF 2.0"))); + } + let length = u32_at(8).ok_or_else(|| bad("truncated header"))? as usize; + if length > bytes.len() { + return Err(bad(&format!("truncated: the header says {length} bytes, the file has {}", bytes.len()))); + } + let mut at = 12usize; + let (mut json, mut bin) = (None, None); + while at + 8 <= length { + let (Some(len), Some(kind)) = (u32_at(at), u32_at(at + 4)) else { break }; + let start = at + 8; + let end = start.checked_add(len as usize).filter(|e| *e <= length).ok_or_else(|| bad("a chunk runs past the end of the file"))?; + let data = bytes.get(start..end).ok_or_else(|| bad("a chunk runs past the end of the file"))?; + match kind { + 0x4E4F_534A if json.is_none() => json = Some(data), + 0x004E_4942 if json.is_some() && bin.is_none() => bin = Some(data), + 0x4E4F_534A | 0x004E_4942 => return Err(bad("chunks out of order")), + // Chunks of unknown types are skipped, as the specification asks. + _ => {} + } + at = end; + } + Ok((json.ok_or_else(|| bad("no JSON chunk"))?, bin)) +} + +/// Required extensions that only change how a file looks (textures, material models): the +/// geometry reads without them. +const LOOK_EXTENSIONS: [&str; 5] = ["KHR_texture_transform", "KHR_texture_basisu", "EXT_texture_webp", "MSFT_texture_dds", "KHR_materials_unlit"]; + +/// The checked glTF document. +fn parse_document(json: &[u8]) -> Result { + let parsed = solidcraft_kernel::guard("glTF", || { + let mut root: gltf::json::Root = match gltf::json::deserialize::from_slice(json) { + Ok(r) => r, + Err(e) => return Ok(Err(format!("not a glTF file: {e}"))), + }; + if let Some(asset) = root.asset.version.split('.').next().filter(|major| *major != "2") { + return Ok(Err(format!("glTF version {asset} (only 2.x is read)"))); + } + let geometry: Vec = root + .extensions_required + .iter() + .filter(|e| !LOOK_EXTENSIONS.contains(&e.as_str()) && !e.starts_with("KHR_materials_") && e.as_str() != "KHR_mesh_quantization") + .cloned() + .collect(); + if !geometry.is_empty() { + let hint = if geometry.iter().any(|e| e.contains("draco") || e.contains("meshopt")) { + " (compressed meshes: save the file uncompressed)" + } else { + "" + }; + return Ok(Err(format!("the file needs glTF extensions that aren't supported: {}{hint}", geometry.join(", ")))); + } + // The ones left only change looks (or are the quantized attributes read below). + root.extensions_required.clear(); + Ok(gltf::Document::from_json(root).map_err(|e| format!("invalid glTF: {e}"))) + }); + match parsed { + Ok(Ok(doc)) => Ok(doc), + Ok(Err(e)) => Err(IoError::Invalid(e)), + Err(e) => Err(IoError::Invalid(format!("glTF could not be read: {e}"))), + } +} + +/// The nodes to import: the default scene's (else the first scene's), else every node that is +/// no other's child. +fn scene_roots(doc: &gltf::Document) -> Vec { + if let Some(scene) = doc.default_scene().or_else(|| doc.scenes().next()) { + return scene.nodes().map(|n| n.index()).collect(); + } + let mut child = vec![false; doc.nodes().len()]; + for n in doc.nodes() { + for c in n.children() { + if let Some(x) = child.get_mut(c.index()) { + *x = true; + } + } + } + child.iter().enumerate().filter(|(_, c)| !**c).map(|(i, _)| i).collect() +} + +/// The file's buffers, read when first needed. +struct Buffers<'a, 'l> { + blob: Option<&'a [u8]>, + data: HashMap, String>>, + total: usize, + load: Loader<'l>, +} + +impl Buffers<'_, '_> { + fn get(&mut self, buffer: &gltf::Buffer<'_>) -> std::result::Result<&[u8], String> { + let index = buffer.index(); + if let gltf::buffer::Source::Bin = buffer.source() { + let blob = self.blob.ok_or("the file has no binary chunk for its buffer")?; + if blob.len() < buffer.length() { + return Err(format!("the binary chunk is shorter ({} bytes) than its buffer says ({})", blob.len(), buffer.length())); + } + return Ok(blob); + } + if !self.data.contains_key(&index) { + let r = self.read(buffer); + if let Ok(d) = &r { + self.total = self.total.saturating_add(d.len()); + } + self.data.insert(index, r); + } + match self.data.get(&index) { + Some(Ok(d)) => Ok(d.as_slice()), + Some(Err(e)) => Err(e.clone()), + None => Err("buffer".into()), + } + } + + fn read(&mut self, buffer: &gltf::Buffer<'_>) -> std::result::Result, String> { + let gltf::buffer::Source::Uri(uri) = buffer.source() else { return Err("buffer".into()) }; + if buffer.length() > MAX_BUFFER_BYTES.saturating_sub(self.total) { + return Err(format!("buffers larger than {} MB in all", MAX_BUFFER_BYTES >> 20)); + } + let data = if let Some(rest) = uri.strip_prefix("data:") { + let (_, payload) = rest.split_once(";base64,").ok_or("an embedded buffer that isn't base64")?; + base64(payload).ok_or("an embedded buffer with bad base64")? + } else { + let path = relative_path(uri)?; + let data = (self.load)(&path).map_err(|e| format!("buffer file `{path}`: {e}"))?; + if data.len() > MAX_BUFFER_BYTES.saturating_sub(self.total) { + return Err(format!("buffers larger than {} MB in all", MAX_BUFFER_BYTES >> 20)); + } + data + }; + if data.len() < buffer.length() { + return Err(format!("buffer `{}` is shorter ({} bytes) than the file says ({})", short(uri), data.len(), buffer.length())); + } + Ok(data) + } +} + +/// A URI for messages: an embedded buffer by its kind only. +fn short(uri: &str) -> String { + if uri.starts_with("data:") { "(embedded)".into() } else { uri.chars().take(80).collect() } +} + +/// A buffer's URI as a path relative to the glTF file, percent-decoded. Absolute paths, other +/// schemes and paths leaving the file's folder are refused. +fn relative_path(uri: &str) -> std::result::Result { + let mut bytes = Vec::with_capacity(uri.len()); + let raw = uri.as_bytes(); + let mut i = 0; + while let Some(&b) = raw.get(i) { + let hex = |k: usize| raw.get(k).and_then(|c| (*c as char).to_digit(16)); + match (b, hex(i + 1), hex(i + 2)) { + (b'%', Some(h), Some(l)) => { + bytes.push((h * 16 + l) as u8); + i += 3; + } + _ => { + bytes.push(b); + i += 1; + } + } + } + let path = String::from_utf8_lossy(&bytes).replace('\\', "/"); + let outside = path.starts_with('/') || path.contains(':') || path.split('/').any(|p| p == ".."); + if path.trim().is_empty() || outside { + return Err(format!("buffer `{}` is not a file next to the glTF file", short(uri))); + } + Ok(path) +} + +/// Standard base64 (padding optional). +fn base64(s: &str) -> Option> { + let value = |c: u8| match c { + b'A'..=b'Z' => Some(c - b'A'), + b'a'..=b'z' => Some(c - b'a' + 26), + b'0'..=b'9' => Some(c - b'0' + 52), + b'+' | b'-' => Some(62), + b'/' | b'_' => Some(63), + _ => None, + }; + let s = s.trim_end_matches('=').as_bytes(); + let mut out = Vec::with_capacity(s.len() / 4 * 3 + 3); + for chunk in s.chunks(4) { + let mut n = 0u32; + for (k, c) in chunk.iter().enumerate() { + n |= u32::from(value(*c)?) << (18 - 6 * k); + } + let bytes = [(n >> 16) as u8, (n >> 8) as u8, n as u8]; + match chunk.len() { + 4 => out.extend_from_slice(&bytes), + 3 => out.extend_from_slice(&bytes[..2]), + 2 => out.push(bytes[0]), + _ => return None, + } + } + Some(out) +} + +/// Uniform scale. +fn scale(s: f64) -> Mat { + [[s, 0.0, 0.0, 0.0], [0.0, s, 0.0, 0.0], [0.0, 0.0, s, 0.0], [0.0, 0.0, 0.0, 1.0]] +} + +/// A node's transform (in the file's units). +fn node_matrix(node: &gltf::Node<'_>) -> Mat { + match node.transform() { + gltf::scene::Transform::Matrix { matrix } => matrix.map(|c| c.map(f64::from)), + gltf::scene::Transform::Decomposed { translation: t, rotation: r, scale: s } => { + let [mut x, mut y, mut z, mut w] = r.map(f64::from); + let n = (x * x + y * y + z * z + w * w).sqrt(); + if n.is_finite() && n > 1e-12 { + (x, y, z, w) = (x / n, y / n, z / n, w / n); + } else { + (x, y, z, w) = (0.0, 0.0, 0.0, 1.0); + } + let [sx, sy, sz] = s.map(f64::from); + let rot = [ + [1.0 - 2.0 * (y * y + z * z), 2.0 * (x * y + z * w), 2.0 * (x * z - y * w)], + [2.0 * (x * y - z * w), 1.0 - 2.0 * (x * x + z * z), 2.0 * (y * z + x * w)], + [2.0 * (x * z + y * w), 2.0 * (y * z - x * w), 1.0 - 2.0 * (x * x + y * y)], + ]; + let col = |c: usize, k: f64| { + let r = rot.get(c).copied().unwrap_or([0.0; 3]); + [r[0] * k, r[1] * k, r[2] * k, 0.0] + }; + [col(0, sx), col(1, sy), col(2, sz), [f64::from(t[0]), f64::from(t[1]), f64::from(t[2]), 1.0]] + } + } +} + +/// `m` as a rigid placement and what is left: `m = place · rest`, `rest` without translation. +/// `None` when `m` is not finite or its translation is out of range. +fn split_rigid(m: &Mat) -> Option<(Mat, Mat)> { + if !m.iter().flatten().all(|v| v.is_finite()) || m[3][..3].iter().any(|v| v.abs() > 1e9) { + return None; + } + let col = |i: usize| Vec3::new(m[i][0], m[i][1], m[i][2]); + let frame = (|| { + let x = col(0).normalized()?; + let y = (col(1) - x * col(1).dot(x)).normalized()?; + Some((x, y, x.cross(y))) + })(); + let (x, y, z) = frame.unwrap_or((Vec3::X, Vec3::Y, Vec3::Z)); + let place = [[x.x, x.y, x.z, 0.0], [y.x, y.y, y.z, 0.0], [z.x, z.y, z.z, 0.0], [m[3][0], m[3][1], m[3][2], 1.0]]; + // The inverse of a rotation is its transpose; the translation goes with the placement. + let inverse_rotation = [[x.x, y.x, z.x, 0.0], [x.y, y.y, z.y, 0.0], [x.z, y.z, z.z, 0.0], [0.0, 0.0, 0.0, 1.0]]; + let mut linear = *m; + linear[3] = [0.0, 0.0, 0.0, 1.0]; + Some((place, mat_mul(&inverse_rotation, &linear))) +} + +fn hash_mat(m: &Mat, h: &mut impl Hasher) { + for v in m.iter().flatten() { + // Equal to within rounding is equal. + ((v * 1e6).round() as i64).hash(h); + } +} + +fn det3(m: &Mat) -> f64 { + let a = |r: usize, c: usize| m[c][r]; + a(0, 0) * (a(1, 1) * a(2, 2) - a(1, 2) * a(2, 1)) - a(0, 1) * (a(1, 0) * a(2, 2) - a(1, 2) * a(2, 0)) + + a(0, 2) * (a(1, 0) * a(2, 1) - a(1, 1) * a(2, 0)) +} + +fn clean_name(s: &str) -> String { + s.trim().chars().filter(|c| !c.is_control()).take(128).collect() +} + +struct Reader<'d, 'a, 'l> { + doc: &'d gltf::Document, + buffers: Buffers<'a, 'l>, + meshes: Vec, + looks: Vec>, + plan: MeshPlan, + /// Instance keys of the components made, to their slots. + keys: HashMap, + has_mesh: HashMap, + /// Each component's mesh's name. + slot_meshes: Vec>, + /// The components being filled (the current node's ancestors). + open: Vec, + placements: usize, + vertices: usize, + triangles: usize, + /// What was left out, and why. + skipped: Vec, + cut_off: bool, + stem: String, +} + +impl<'d> Reader<'d, '_, '_> { + fn node(&self, index: usize) -> Option> { + self.doc.nodes().nth(index) + } + + /// Does the subtree of node `index` hold a mesh? (Loops count as no.) + fn subtree_has_mesh(&mut self, index: usize, depth: usize) -> bool { + if let Some(&known) = self.has_mesh.get(&index) { + return known; + } + if depth > MAX_DEPTH { + return false; + } + // In progress: a loop back here adds nothing. + self.has_mesh.insert(index, false); + let Some(node) = self.node(index) else { return false }; + let children: Vec = node.children().map(|c| c.index()).collect(); + let mut any = node.mesh().is_some(); + for c in children { + any |= self.subtree_has_mesh(c, depth + 1); + } + self.has_mesh.insert(index, any); + any + } + + fn budget(&mut self, depth: usize) -> bool { + self.placements += 1; + if self.placements > MAX_PLACEMENTS || depth > MAX_DEPTH { + self.cut_off = true; + return false; + } + true + } + + /// Node `index` under component `parent` (`None`: the import's own), whose frame sees the + /// node's parent through `outer` (the parent's leftover scale, with the units). + fn walk(&mut self, index: usize, parent: Option, outer: &Mat, depth: usize) -> Result<()> { + if !self.subtree_has_mesh(index, 0) || !self.budget(depth) { + return Ok(()); + } + let Some(node) = self.node(index) else { return Ok(()) }; + let local = mat_mul(outer, &node_matrix(&node)); + let split = split_rigid(&local); + let Some((place, rest)) = split.filter(|_| depth < MAX_COMPONENT_DEPTH && self.plan.slots.len() < MAX_COMPONENTS) else { + // No component of its own: built where its parent is. + return self.walk_flat(index, parent, &local, depth); + }; + let key = self.key(index, &rest, 0); + if let Some(&slot) = self.keys.get(&key) { + if self.open.contains(&slot) { + // A node inside itself (the file's tree loops): not followed. + self.cut_off = true; + return Ok(()); + } + // The same mesh and subtree placed again: another occurrence. Placed by nodes of + // other names, it goes by its mesh's. + let name = node.name().map(clean_name).unwrap_or_default(); + if let (Some(own), Some(Some(mesh))) = (self.plan.slots.get_mut(slot), self.slot_meshes.get(slot)) + && *own != name + { + own.clone_from(mesh); + } + self.plan.places.push(PlanPlace { slot, parent, transform: place }); + return Ok(()); + } + let slot = self.plan.slots.len(); + let name = node.name().map(clean_name).filter(|n| !n.is_empty()); + let name = name.or_else(|| node.mesh().and_then(|m| m.name().map(clean_name)).filter(|n| !n.is_empty())); + self.plan.slots.push(name.unwrap_or_else(|| format!("Node {index}"))); + self.slot_meshes.push(node.mesh().and_then(|m| m.name().map(clean_name)).filter(|n| !n.is_empty())); + self.plan.places.push(PlanPlace { slot, parent, transform: place }); + self.keys.insert(key, slot); + self.node_meshes(index, Some(slot), &rest)?; + let children: Vec = node.children().map(|c| c.index()).collect(); + self.open.push(slot); + for c in children { + self.walk(c, Some(slot), &rest, depth + 1)?; + } + self.open.pop(); + Ok(()) + } + + /// Node `index` built in component `parent`, `local` being its whole placement there (scale + /// and all): its meshes are baked with it. + fn walk_flat(&mut self, index: usize, parent: Option, local: &Mat, depth: usize) -> Result<()> { + if !self.subtree_has_mesh(index, 0) || !self.budget(depth) { + return Ok(()); + } + let Some(node) = self.node(index) else { return Ok(()) }; + self.node_meshes(index, parent, local)?; + let children: Vec = node.children().map(|c| c.index()).collect(); + for c in children { + if depth + 1 < MAX_COMPONENT_DEPTH && self.plan.slots.len() < MAX_COMPONENTS { + self.walk(c, parent, local, depth + 1)?; + } else { + let Some(child) = self.node(c) else { continue }; + let m = mat_mul(local, &node_matrix(&child)); + self.walk_flat(c, parent, &m, depth + 1)?; + } + } + Ok(()) + } + + /// What makes two placements the same component: the node's mesh, how it is baked, and the + /// same children placed the same way below it. + fn key(&mut self, index: usize, rest: &Mat, depth: usize) -> u64 { + let mut h = std::collections::hash_map::DefaultHasher::new(); + let Some(node) = self.node(index) else { return 0 }; + node.mesh().map(|m| m.index()).hash(&mut h); + hash_mat(rest, &mut h); + if depth < 8 { + let children: Vec = node.children().map(|c| c.index()).collect(); + for c in children { + if !self.subtree_has_mesh(c, 0) { + continue; + } + let Some(child) = self.node(c) else { continue }; + let local = mat_mul(rest, &node_matrix(&child)); + match split_rigid(&local) { + Some((place, child_rest)) => { + hash_mat(&place, &mut h); + self.key(c, &child_rest, depth + 1).hash(&mut h); + } + None => c.hash(&mut h), + } + } + } else { + // Too deep to compare: only the very same node is the same. + index.hash(&mut h); + } + h.finish() + } + + /// Bodies of node `index`'s mesh, baked with `bake` (its frame in component `slot`). + fn node_meshes(&mut self, index: usize, slot: Option, bake: &Mat) -> Result<()> { + let Some(node) = self.node(index) else { return Ok(()) }; + let Some(mesh) = node.mesh() else { return Ok(()) }; + let base = mesh + .name() + .map(clean_name) + .filter(|n| !n.is_empty()) + .or_else(|| node.name().map(clean_name).filter(|n| !n.is_empty())) + .unwrap_or_else(|| self.stem.clone()); + if !bake.iter().flatten().all(|v| v.is_finite()) || det3(bake).abs() < 1e-18 { + self.skipped.push(format!("mesh `{base}` (its node scales it to nothing)")); + return Ok(()); + } + let flip = det3(bake) < 0.0; + // Primitives by material, in the order they first appear. + let mut groups: Vec<(Option, Vec, Vec<[u32; 3]>)> = Vec::new(); + for (k, prim) in mesh.primitives().enumerate() { + let tris = match self.primitive(&prim) { + Ok(Some(t)) => t, + Ok(None) => continue, + Err(e) => { + self.skipped.push(format!("mesh `{base}` part {k}: {e}")); + continue; + } + }; + let material = prim.material().index(); + let at = match groups.iter().position(|g| g.0 == material) { + Some(at) => at, + None => { + groups.push((material, Vec::new(), Vec::new())); + groups.len() - 1 + } + }; + let Some(group) = groups.get_mut(at) else { continue }; + let offset = u32::try_from(group.1.len()).map_err(|_| IoError::Invalid("glTF mesh too large".into()))?; + group.1.extend(tris.0.iter().map(|p| solidcraft_doc::apply_point(bake, *p))); + group.2.extend(tris.1.iter().map(|t| { + let t = t.map(|i| i + offset); + if flip { [t[0], t[2], t[1]] } else { t } + })); + } + let several = groups.len() > 1; + for (k, (material, positions, triangles)) in groups.into_iter().enumerate() { + if triangles.is_empty() { + continue; + } + let look = material.and_then(|m| self.doc.materials().nth(m)).map(|m| look_of(&m)); + let name = if several { + let suffix = look.as_ref().map(|l| l.name.clone()).filter(|n| !n.is_empty()).unwrap_or_else(|| format!("{}", k + 1)); + format!("{base} ({suffix})") + } else { + base.clone() + }; + if let Err(e) = solidcraft_kernel::mesh_body(&positions, &triangles) { + self.skipped.push(format!("mesh `{name}`: {e}")); + continue; + } + self.meshes.push(MeshData { + name, + positions: positions.iter().flat_map(|p| [p.x, p.y, p.z]).collect(), + triangles: triangles.iter().flatten().copied().collect(), + color: look.as_ref().map(Look::rgb), + }); + self.looks.push(look); + self.plan.bodies.push(slot); + } + Ok(()) + } + + /// A primitive's vertices (file units) and triangles; `None` for points and lines. + #[allow(clippy::type_complexity)] + fn primitive(&mut self, prim: &gltf::Primitive<'_>) -> std::result::Result, Vec<[u32; 3]>)>, String> { + let mode = prim.mode(); + if !matches!(mode, Mode::Triangles | Mode::TriangleStrip | Mode::TriangleFan) { + return Ok(None); + } + let acc = prim.get(&gltf::Semantic::Positions).ok_or("no positions")?; + let raw = self.accessor(&acc, Dimensions::Vec3)?; + let positions: Vec = raw.as_chunks::<3>().0.iter().map(|c| Vec3::new(c[0], c[1], c[2])).collect(); + let n = positions.len(); + let indices: Vec = match prim.indices() { + Some(a) => { + if !matches!(a.data_type(), DataType::U8 | DataType::U16 | DataType::U32) { + return Err("indices that aren't unsigned integers".into()); + } + self.accessor(&a, Dimensions::Scalar)?.into_iter().map(|v| v as u32).collect() + } + None => (0..u32::try_from(n).map_err(|_| "too many vertices")?).collect(), + }; + if let Some(bad) = indices.iter().find(|i| **i as usize >= n) { + return Err(format!("index {bad} past its {n} vertices")); + } + let at = |k: usize| indices.get(k).copied().unwrap_or(0); + let mut tris = Vec::new(); + match mode { + Mode::TriangleStrip => { + for k in 0..indices.len().saturating_sub(2) { + tris.push(if k % 2 == 0 { [at(k), at(k + 1), at(k + 2)] } else { [at(k + 1), at(k), at(k + 2)] }); + } + } + Mode::TriangleFan => { + for k in 1..indices.len().saturating_sub(1) { + tris.push([at(0), at(k), at(k + 1)]); + } + } + _ => tris.extend(indices.as_chunks::<3>().0.iter().copied()), + } + // Degenerate triangles (a repeated corner) close nothing. + tris.retain(|t| t[0] != t[1] && t[1] != t[2] && t[0] != t[2]); + if tris.is_empty() { + return Ok(None); + } + // Only the vertices used. + let mut map: HashMap = HashMap::new(); + let mut used = Vec::new(); + for t in &mut tris { + for i in t.iter_mut() { + let next = used.len() as u32; + *i = *map.entry(*i).or_insert_with(|| { + used.push(positions.get(*i as usize).copied().unwrap_or(Vec3::ZERO)); + next + }); + } + } + self.vertices = self.vertices.saturating_add(used.len()); + self.triangles = self.triangles.saturating_add(tris.len()); + if self.vertices > MAX_VERTICES || self.triangles > MAX_TRIANGLES { + return Err(format!("more than {MAX_TRIANGLES} triangles or {MAX_VERTICES} vertices in all")); + } + Ok(Some((used, tris))) + } + + /// An accessor's values (`dims` per element) as numbers; normalized integers as fractions. + fn accessor(&mut self, acc: &gltf::Accessor<'_>, dims: Dimensions) -> std::result::Result, String> { + if acc.sparse().is_some() { + return Err("sparse accessors aren't supported".into()); + } + if acc.dimensions() != dims { + return Err(format!("accessor {} has {:?} values, not {dims:?}", acc.index(), acc.dimensions())); + } + let view = acc.view().ok_or("an accessor without data")?; + let width = dims.multiplicity(); + let size = acc.data_type().size(); + let elem = width * size; + let stride = view.stride().unwrap_or(elem); + let count = acc.count(); + if stride < elem || count > MAX_VERTICES.max(3 * MAX_TRIANGLES) { + return Err(format!("accessor {} is malformed", acc.index())); + } + // Every element must lie in the view, and the view in its buffer. + let span = if count == 0 { 0 } else { (count - 1).checked_mul(stride).and_then(|s| s.checked_add(elem)).ok_or("accessor too large")? }; + let end = acc.offset().checked_add(span).ok_or("accessor too large")?; + if end > view.length() { + return Err(format!("accessor {} runs past its buffer view", acc.index())); + } + let view_end = view.offset().checked_add(view.length()).ok_or("buffer view too large")?; + let data = self.buffers.get(&view.buffer())?; + if view_end > data.len() || view_end > view.buffer().length() { + return Err(format!("buffer view {} runs past its buffer (the file may be truncated)", view.index())); + } + let base = view.offset() + acc.offset(); + let normalized = acc.normalized(); + let ty = acc.data_type(); + let mut out = Vec::with_capacity(count * width); + for e in 0..count { + for c in 0..width { + let at = base + e * stride + c * size; + let b = data.get(at..at + size).ok_or("accessor out of range")?; + let v = match ty { + DataType::F32 => f64::from(f32::from_le_bytes([b[0], b[1], b[2], b[3]])), + DataType::U32 => f64::from(u32::from_le_bytes([b[0], b[1], b[2], b[3]])), + DataType::U16 => { + let v = f64::from(u16::from_le_bytes([b[0], b[1]])); + if normalized { v / 65535.0 } else { v } + } + DataType::I16 => { + let v = f64::from(i16::from_le_bytes([b[0], b[1]])); + if normalized { (v / 32767.0).max(-1.0) } else { v } + } + DataType::U8 => { + let v = f64::from(b[0]); + if normalized { v / 255.0 } else { v } + } + DataType::I8 => { + let v = f64::from(b[0] as i8); + if normalized { (v / 127.0).max(-1.0) } else { v } + } + }; + if !v.is_finite() { + return Err(format!("accessor {} holds a number that isn't finite", acc.index())); + } + out.push(v); + } + } + Ok(out) + } +} + +/// Linear to sRGB (0–1). +fn srgb(c: f32) -> f32 { + let c = if c.is_finite() { c.clamp(0.0, 1.0) } else { 0.8 }; + if c <= 0.003_130_8 { 12.92 * c } else { 1.055 * c.powf(1.0 / 2.4) - 0.055 } +} + +/// A material's look: base colour, alpha when blended, metallic/roughness when opaque. +fn look_of(m: &gltf::Material<'_>) -> Look { + let pbr = m.pbr_metallic_roughness(); + let [r, g, b, a] = pbr.base_color_factor(); + let color = [r, g, b].map(|c| (srgb(c) * 255.0).round() as u8); + let opacity = match m.alpha_mode() { + gltf::material::AlphaMode::Blend if a.is_finite() => f64::from(a).clamp(0.0, 1.0), + _ => 1.0, + }; + let name = m.name().map(clean_name).filter(|n| !n.is_empty()).unwrap_or_else(|| "glTF material".into()); + let finite = |v: f32, d: f64| if v.is_finite() { f64::from(v).clamp(0.0, 1.0) } else { d }; + let pbr = (opacity >= 1.0) + .then(|| { + solidcraft_doc::pbr_appearance::PbrParameters::new(finite(pbr.metallic_factor(), 1.0), finite(pbr.roughness_factor(), 1.0), 1.5).ok() + }) + .flatten(); + Look { name, color, opacity, pbr } +} + +/// A GLB container of `json` and an optional binary chunk (each padded to four bytes). +pub fn glb_container(json: &[u8], bin: &[u8]) -> Vec { + let pad = |n: usize| (4 - n % 4) % 4; + let json_len = json.len() + pad(json.len()); + let bin_len = bin.len() + pad(bin.len()); + let total = 12 + 8 + json_len + if bin.is_empty() { 0 } else { 8 + bin_len }; + let mut out = Vec::with_capacity(total); + out.extend_from_slice(b"glTF"); + out.extend_from_slice(&2u32.to_le_bytes()); + out.extend_from_slice(&(total as u32).to_le_bytes()); + out.extend_from_slice(&(json_len as u32).to_le_bytes()); + out.extend_from_slice(b"JSON"); + out.extend_from_slice(json); + out.extend(std::iter::repeat_n(b' ', pad(json.len()))); + if !bin.is_empty() { + out.extend_from_slice(&(bin_len as u32).to_le_bytes()); + out.extend_from_slice(b"BIN\0"); + out.extend_from_slice(bin); + out.extend(std::iter::repeat_n(0u8, pad(bin.len()))); + } + out +} + +#[cfg(test)] +#[path = "gltf_in_tests.rs"] +mod tests; diff --git a/crates/io/src/gltf_in_tests.rs b/crates/io/src/gltf_in_tests.rs new file mode 100644 index 000000000..2d6f58523 --- /dev/null +++ b/crates/io/src/gltf_in_tests.rs @@ -0,0 +1,445 @@ +//! glTF import tests. Every file here is built by the tests themselves. + +use serde_json::{Value, json}; + +use super::*; + +/// A glTF file under construction: one binary buffer, meshes, nodes and materials. +#[derive(Default)] +pub(crate) struct Fixture { + pub bin: Vec, + pub views: Vec, + pub accessors: Vec, + pub meshes: Vec, + pub nodes: Vec, + pub materials: Vec, + pub roots: Vec, +} + +/// A cube of side `s` (metres) with its corner at the origin, outward facing. +pub(crate) fn cube(s: f32) -> (Vec<[f32; 3]>, Vec) { + let p = (0..8).map(|i| [(i & 1) as f32 * s, ((i >> 1) & 1) as f32 * s, ((i >> 2) & 1) as f32 * s]).collect(); + let t = vec![0, 2, 1, 1, 2, 3, 4, 5, 6, 5, 7, 6, 0, 1, 4, 1, 5, 4, 2, 6, 3, 3, 6, 7, 0, 4, 2, 2, 4, 6, 1, 3, 5, 3, 7, 5]; + (p, t) +} + +impl Fixture { + fn view(&mut self, bytes: &[u8]) -> usize { + while !self.bin.len().is_multiple_of(4) { + self.bin.push(0); + } + self.views.push(json!({"buffer": 0, "byteOffset": self.bin.len(), "byteLength": bytes.len()})); + self.bin.extend_from_slice(bytes); + self.views.len() - 1 + } + + /// A mesh of one primitive per (positions, indices, material). + pub fn mesh(&mut self, name: &str, prims: &[(&[[f32; 3]], &[u16], Option)]) -> usize { + let mut out = Vec::new(); + for (positions, indices, material) in prims { + let bytes: Vec = positions.iter().flatten().flat_map(|v| v.to_le_bytes()).collect(); + let v = self.view(&bytes); + let lo = (0..3).map(|k| positions.iter().map(|p| p[k]).fold(f32::INFINITY, f32::min)).collect::>(); + let hi = (0..3).map(|k| positions.iter().map(|p| p[k]).fold(f32::NEG_INFINITY, f32::max)).collect::>(); + self.accessors.push(json!({"bufferView": v, "componentType": 5126, "count": positions.len(), "type": "VEC3", "min": lo, "max": hi})); + let pa = self.accessors.len() - 1; + let bytes: Vec = indices.iter().flat_map(|v| v.to_le_bytes()).collect(); + let v = self.view(&bytes); + self.accessors.push(json!({"bufferView": v, "componentType": 5123, "count": indices.len(), "type": "SCALAR"})); + let mut p = json!({"attributes": {"POSITION": pa}, "indices": self.accessors.len() - 1}); + if let Some(m) = material { + p["material"] = json!(m); + } + out.push(p); + } + self.meshes.push(json!({"name": name, "primitives": out})); + self.meshes.len() - 1 + } + + pub fn cube_mesh(&mut self, name: &str, s: f32) -> usize { + let (p, t) = cube(s); + self.mesh(name, &[(&p, &t, None)]) + } + + pub fn node(&mut self, node: Value) -> usize { + self.nodes.push(node); + self.nodes.len() - 1 + } + + pub fn json(&self, uri: Option<&str>) -> Value { + let mut buffer = json!({"byteLength": self.bin.len()}); + if let Some(u) = uri { + buffer["uri"] = json!(u); + } + let mut j = json!({ + "asset": {"version": "2.0", "generator": "solidcraft tests"}, + "scene": 0, + "scenes": [{"nodes": self.roots}], + "nodes": self.nodes, + "meshes": self.meshes, + "accessors": self.accessors, + "bufferViews": self.views, + "buffers": [buffer], + }); + if !self.materials.is_empty() { + j["materials"] = json!(self.materials); + } + j + } + + pub fn glb(&self) -> Vec { + glb_container(self.json(None).to_string().as_bytes(), &self.bin) + } +} + +fn no_files(name: &str) -> std::result::Result, String> { + Err(format!("no file `{name}`")) +} + +fn read(bytes: &[u8]) -> Result { + read_gltf(bytes, "model.glb", &mut no_files) +} + +fn meshes(g: &GltfImport) -> &[MeshData] { + match &g.feature.kind { + solidcraft_doc::FeatureKind::MeshImport { meshes, .. } => meshes, + _ => &[], + } +} + +fn bounds(m: &MeshData) -> ([f64; 3], [f64; 3]) { + let mut lo = [f64::INFINITY; 3]; + let mut hi = [f64::NEG_INFINITY; 3]; + for p in m.positions.as_chunks::<3>().0 { + for k in 0..3 { + lo[k] = lo[k].min(p[k]); + hi[k] = hi[k].max(p[k]); + } + } + (lo, hi) +} + +/// Signed volume (positive for outward-facing triangles). +fn volume(m: &MeshData) -> f64 { + let p = |i: u32| { + let i = i as usize * 3; + Vec3::new(m.positions[i], m.positions[i + 1], m.positions[i + 2]) + }; + m.triangles.as_chunks::<3>().0.iter().map(|t| p(t[0]).dot(p(t[1]).cross(p(t[2]))) / 6.0).sum() +} + +fn close(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-6 * (1.0 + b.abs()) +} + +#[test] +fn single_mesh_in_millimetres() { + let mut f = Fixture::default(); + let m = f.cube_mesh("Cube", 0.01); + let n = f.node(json!({"name": "Cube node", "mesh": m})); + f.roots = vec![n]; + let g = read(&f.glb()).unwrap(); + assert!(g.feature.warnings.is_empty(), "{:?}", g.feature.warnings); + assert_eq!(g.feature.name, "Cube"); + let ms = meshes(&g); + assert_eq!(ms.len(), 1); + assert_eq!(ms[0].triangles.len(), 36); + let (lo, hi) = bounds(&ms[0]); + assert!(lo.iter().all(|v| close(*v, 0.0)) && hi.iter().all(|v| close(*v, 10.0)), "{lo:?} {hi:?}"); + assert!(close(volume(&ms[0]), 1000.0), "{}", volume(&ms[0])); + // One root node is the import's own component. + assert!(g.plan.slots.is_empty() && g.plan.places.is_empty()); + assert_eq!(g.plan.bodies, vec![None]); + assert_eq!(g.looks, vec![None]); + // The axes are the file's: Y up stays Y here (the caller turns the component). + let mut f = Fixture::default(); + let (p, t) = cube(0.01); + let tall: Vec<[f32; 3]> = p.iter().map(|q| [q[0], q[1] * 3.0, q[2]]).collect(); + let m = f.mesh("Tall", &[(&tall, &t, None)]); + let n = f.node(json!({"mesh": m})); + f.roots = vec![n]; + let g = read(&f.glb()).unwrap(); + let (_, hi) = bounds(&meshes(&g)[0]); + assert!(close(hi[1], 30.0) && close(hi[2], 10.0), "{hi:?}"); +} + +#[test] +fn node_hierarchy_becomes_components() { + let mut f = Fixture::default(); + let m = f.cube_mesh("Block", 0.01); + let arm = f.node(json!({"name": "Arm", "mesh": m, "translation": [0.0, 0.05, 0.0], "rotation": [0.0, 0.0, 0.70710677, 0.70710677]})); + let base = f.node(json!({"name": "Base", "mesh": m, "translation": [0.1, 0.0, 0.0], "children": [arm]})); + let block = f.cube_mesh("Other block", 0.01); + let other = f.node(json!({"name": "Other", "mesh": block, "translation": [0.0, 0.0, 0.2]})); + f.roots = vec![base, other]; + let g = read(&f.glb()).unwrap(); + assert_eq!(g.plan.slots, vec!["Base", "Arm", "Other"]); + assert_eq!(g.plan.places.len(), 3); + let base_place = &g.plan.places[0]; + assert_eq!((base_place.slot, base_place.parent), (0, None)); + assert!(close(base_place.transform[3][0], 100.0)); + let arm_place = &g.plan.places[1]; + assert_eq!((arm_place.slot, arm_place.parent), (1, Some(0))); + assert!(close(arm_place.transform[3][1], 50.0)); + // A quarter turn about Z: X goes to Y. + assert!(close(arm_place.transform[0][1], 1.0) && arm_place.transform[0][0].abs() < 1e-6, "{:?}", arm_place.transform); + assert_eq!(g.plan.bodies, vec![Some(0), Some(1), Some(2)]); + // Bodies are in their component's frame. + for m in meshes(&g) { + let (lo, hi) = bounds(m); + assert!(lo.iter().all(|v| close(*v, 0.0)) && hi.iter().all(|v| close(*v, 10.0)), "{} {lo:?} {hi:?}", m.name); + } +} + +#[test] +fn repeated_meshes_are_instances() { + let mut f = Fixture::default(); + let m = f.cube_mesh("Bolt", 0.005); + f.roots = (0..4).map(|k| f.node(json!({"name": format!("Bolt.{k}"), "mesh": m, "translation": [k as f32 * 0.02, 0.0, 0.0]}))).collect(); + let g = read(&f.glb()).unwrap(); + assert_eq!(g.plan.slots, vec!["Bolt"], "named after the mesh: the nodes' names differ"); + assert_eq!(g.plan.places.len(), 4); + assert!(g.plan.places.iter().all(|p| p.slot == 0 && p.parent.is_none())); + assert!(close(g.plan.places[3].transform[3][0], 60.0)); + assert_eq!(meshes(&g).len(), 1, "the mesh is built once"); + // The same mesh scaled differently is not the same part. + f.nodes[3]["scale"] = json!([2.0, 2.0, 2.0]); + let g = read(&f.glb()).unwrap(); + assert_eq!(g.plan.slots.len(), 2); + assert_eq!(meshes(&g).len(), 2); +} + +#[test] +fn scale_and_mirror_are_baked_and_the_tree_kept() { + let mut f = Fixture::default(); + let m = f.cube_mesh("Cube", 0.01); + let child = f.node(json!({"name": "Child", "mesh": m, "translation": [0.1, 0.0, 0.0]})); + let mirrored = f.node(json!({"name": "Mirror", "mesh": m, "scale": [-1.0, 1.0, 1.0]})); + let scaled = f.node(json!({"name": "Half", "scale": [0.5, 0.5, 0.5], "children": [child]})); + f.roots = vec![scaled, mirrored]; + let g = read(&f.glb()).unwrap(); + assert_eq!(g.plan.slots, vec!["Half", "Child", "Mirror"]); + // The child sits half as far out, and is half the size. + assert!(close(g.plan.places[1].transform[3][0], 50.0), "{:?}", g.plan.places[1].transform); + let ms = meshes(&g); + assert!(close(volume(&ms[0]), 125.0), "{}", volume(&ms[0])); + // A mirrored mesh still faces out. + assert!(close(volume(&ms[1]), 1000.0), "{}", volume(&ms[1])); + // Placed, it lies on the other side of the origin. + let place = &g.plan.places[2].transform; + let xs: Vec = ms[1].positions.as_chunks::<3>().0.iter().map(|p| solidcraft_doc::apply_point(place, Vec3::new(p[0], p[1], p[2])).x).collect(); + assert!( + close(xs.iter().copied().fold(f64::INFINITY, f64::min), -10.0) && close(xs.iter().copied().fold(f64::NEG_INFINITY, f64::max), 0.0), + "{xs:?}" + ); +} + +#[test] +fn materials_give_looks() { + let mut f = Fixture { + materials: vec![ + json!({"name": "Red metal", "pbrMetallicRoughness": {"baseColorFactor": [1.0, 0.0, 0.0, 1.0], "metallicFactor": 1.0, "roughnessFactor": 0.25}}), + json!({"name": "Glass", "alphaMode": "BLEND", "pbrMetallicRoughness": {"baseColorFactor": [0.214, 0.214, 0.214, 0.5]}}), + ], + ..Default::default() + }; + let (p, t) = cube(0.01); + let q: Vec<[f32; 3]> = p.iter().map(|v| [v[0] + 0.02, v[1], v[2]]).collect(); + let m = f.mesh("Two", &[(&p, &t, Some(0)), (&q, &t, Some(1))]); + let n = f.node(json!({"mesh": m})); + f.roots = vec![n]; + let g = read(&f.glb()).unwrap(); + let ms = meshes(&g); + assert_eq!(ms.iter().map(|m| m.name.as_str()).collect::>(), ["Two (Red metal)", "Two (Glass)"]); + let red = g.looks[0].as_ref().unwrap(); + assert_eq!((red.name.as_str(), red.color, red.opacity), ("Red metal", [255, 0, 0], 1.0)); + let pbr = red.pbr.unwrap(); + assert!(close(pbr.metallic(), 1.0) && close(pbr.roughness(), 0.25)); + assert_eq!(ms[0].color, Some([1.0, 0.0, 0.0])); + // Linear 0.214 is sRGB 128; a blended material is see-through and not PBR. + let glass = g.looks[1].as_ref().unwrap(); + assert!((i32::from(glass.color[0]) - 128).abs() <= 1, "{:?}", glass.color); + assert!(close(glass.opacity, 0.5) && glass.pbr.is_none()); +} + +#[test] +fn gltf_with_external_and_embedded_buffers() { + let mut f = Fixture::default(); + let m = f.cube_mesh("Cube", 0.01); + let n = f.node(json!({"mesh": m})); + f.roots = vec![n]; + let text = f.json(Some("cube%20data.bin")).to_string(); + let bin = f.bin.clone(); + let mut asked = Vec::new(); + let mut load = |name: &str| { + asked.push(name.to_string()); + Ok(bin.clone()) + }; + let g = read_gltf(text.as_bytes(), "dir/model.gltf", &mut load).unwrap(); + assert_eq!(meshes(&g).len(), 1); + assert_eq!(asked, ["cube data.bin"]); + // Missing: a clear error naming the file. + let e = read_gltf(text.as_bytes(), "model.gltf", &mut no_files).err().unwrap().to_string(); + assert!(e.contains("cube data.bin"), "{e}"); + // Outside the file's folder: refused before anything is read. + for uri in ["../secret.bin", "/etc/passwd", "C:/x.bin", "file:///x.bin", "a/%2e%2e/../b.bin"] { + let text = f.json(Some(uri)).to_string(); + let mut called = false; + let mut load = |_: &str| { + called = true; + Ok(Vec::new()) + }; + let r = read_gltf(text.as_bytes(), "model.gltf", &mut load); + assert!(r.is_err() && !called, "{uri}"); + } + // Embedded as a data URI. + let b64 = { + const A: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut s = String::new(); + for c in f.bin.chunks(3) { + let n = (u32::from(c[0]) << 16) | (u32::from(*c.get(1).unwrap_or(&0)) << 8) | u32::from(*c.get(2).unwrap_or(&0)); + for k in 0..4 { + s.push(if k <= c.len() { A[((n >> (18 - 6 * k)) & 63) as usize] as char } else { '=' }); + } + } + s + }; + let text = f.json(Some(&format!("data:application/octet-stream;base64,{b64}"))).to_string(); + let g = read_gltf(text.as_bytes(), "model.gltf", &mut no_files).unwrap(); + assert!(close(volume(&meshes(&g)[0]), 1000.0)); + // The GLB route through mesh_import_feature builds every body where it is. + let mut f2 = Fixture::default(); + let m = f2.cube_mesh("Cube", 0.01); + f2.roots = vec![f2.node(json!({"mesh": m, "translation": [1.0, 0.0, 0.0]})), f2.node(json!({"mesh": m, "translation": [2.0, 0.0, 0.0]}))]; + let mf = crate::mesh_import_feature(&f2.glb(), "two.glb").unwrap(); + let solidcraft_doc::FeatureKind::MeshImport { meshes, .. } = &mf.kind else { panic!() }; + assert_eq!(meshes.len(), 1); + assert!(close(bounds(&meshes[0]).0[0], 1000.0)); + assert!(crate::is_mesh_path("a.GLB") && crate::is_mesh_path("b.gltf") && is_gltf_path("c.Gltf") && !is_gltf_path("d.obj")); +} + +#[test] +fn strips_fans_and_unsupported_parts() { + let mut f = Fixture::default(); + // A square as a strip and as a fan, and a line primitive that is skipped. + let sq: Vec<[f32; 3]> = vec![[0.0, 0.0, 0.0], [0.01, 0.0, 0.0], [0.0, 0.01, 0.0], [0.01, 0.01, 0.0]]; + let m = f.mesh("Sheet", &[(&sq, &[0, 1, 2, 3], None)]); + f.meshes[m]["primitives"][0]["mode"] = json!(5); + let n = f.node(json!({"mesh": m})); + f.roots = vec![n]; + let g = read(&f.glb()).unwrap(); + assert_eq!(meshes(&g)[0].triangles.len(), 6); + f.meshes[m]["primitives"][0]["mode"] = json!(1); + let e = read(&f.glb()).err().unwrap().to_string(); + assert!(e.contains("no triangle meshes"), "{e}"); +} + +/// The plan makes each component at its first placement, inside one made before (never inside +/// itself), and puts bodies only in components it makes. +fn plan_ok(p: &MeshPlan) -> bool { + let mut made = 0; + for place in &p.places { + if place.slot > made || place.parent.is_some_and(|q| q >= made || q == place.slot) { + return false; + } + made += usize::from(place.slot == made); + } + made == p.slots.len() && p.bodies.iter().flatten().all(|b| *b < made) +} + +fn assert_no_panic(bytes: &[u8], what: &str) { + let r = std::panic::catch_unwind(|| read(bytes).map(|g| (meshes(&g).len(), plan_ok(&g.plan), g.looks.len() == meshes(&g).len()))); + assert!(r.is_ok(), "panicked on {what}"); + if let Ok(Ok((_, plan, looks))) = r { + assert!(plan && looks, "inconsistent plan on {what}"); + } +} + +#[test] +fn hostile_gltf_never_panics() { + let mut f = Fixture::default(); + let m = f.cube_mesh("Cube", 0.01); + let child = f.node(json!({"name": "C", "mesh": m, "translation": [0.0, 0.1, 0.0]})); + let n = f.node(json!({"mesh": m, "children": [child], "scale": [2.0, 1.0, 1.0]})); + f.roots = vec![n, child]; + let glb = f.glb(); + assert!(read(&glb).is_ok()); + // Every truncation is an error, never a panic. + for k in 0..glb.len() { + assert_no_panic(&glb[..k], &format!("truncated to {k}")); + assert!(read(&glb[..k]).is_err(), "truncated to {k}"); + } + // Flipped bytes anywhere. + for k in 0..glb.len() { + let mut bad = glb.clone(); + bad[k] ^= 0xA5; + assert_no_panic(&bad, &format!("byte {k} flipped")); + } + // Lengths in the container that lie. + for (at, v) in [(8, 0u32), (8, 5), (8, u32::MAX), (12, 0), (12, u32::MAX), (4, 1)] { + let mut bad = glb.clone(); + bad[at..at + 4].copy_from_slice(&v.to_le_bytes()); + assert_no_panic(&bad, &format!("{v} at {at}")); + assert!(read(&bad).is_err(), "{v} at {at}"); + } + // Documents that lie. + let base = f.json(None); + let cases: Vec<(&str, Box)> = vec![ + ("huge count", Box::new(|j| j["accessors"][0]["count"] = json!(u32::MAX))), + ("past the view", Box::new(|j| j["accessors"][0]["byteOffset"] = json!(1000))), + ("view past buffer", Box::new(|j| j["bufferViews"][0]["byteLength"] = json!(1 << 20))), + ("buffer longer than chunk", Box::new(|j| j["buffers"][0]["byteLength"] = json!(1 << 20))), + ("bad accessor index", Box::new(|j| j["meshes"][0]["primitives"][0]["attributes"]["POSITION"] = json!(99))), + ("bad mesh index", Box::new(|j| j["nodes"][0]["mesh"] = json!(99))), + ("bad child", Box::new(|j| j["nodes"][1]["children"] = json!([99]))), + ("loop", Box::new(|j| j["nodes"][0]["children"] = json!([1, 0]))), + ("two-node loop", Box::new(|j| j["nodes"][0]["children"] = json!([1]))), + ("index past vertices", Box::new(|j| j["accessors"][1]["componentType"] = json!(5125))), + ("float indices", Box::new(|j| j["accessors"][1]["componentType"] = json!(5126))), + ("stride too small", Box::new(|j| j["bufferViews"][0]["byteStride"] = json!(4))), + ("nan transform", Box::new(|j| j["nodes"][1]["matrix"] = json!([f32::MAX, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1e30, 0, 0, 1]))), + ("zero scale", Box::new(|j| j["nodes"][1]["scale"] = json!([0.0, 0.0, 0.0]))), + ("draco", Box::new(|j| j["extensionsRequired"] = json!(["KHR_draco_mesh_compression"]))), + ("version 1", Box::new(|j| j["asset"]["version"] = json!("1.0"))), + ("no scenes", Box::new(|j| j.as_object_mut().unwrap().retain(|k, _| k != "scenes" && k != "scene"))), + ( + "sparse", + Box::new(|j| { + j["accessors"][0]["sparse"] = json!({"count": 1, "indices": {"bufferView": 1, "componentType": 5123}, "values": {"bufferView": 0}}) + }), + ), + ("no buffer", Box::new(|j| j["buffers"] = json!([]))), + ("not json", Box::new(|j| *j = json!("nope"))), + ]; + for (what, edit) in &cases { + let mut j = base.clone(); + edit(&mut j); + let bytes = glb_container(j.to_string().as_bytes(), &f.bin); + assert_no_panic(&bytes, what); + let text = j.to_string(); + let r = std::panic::catch_unwind(|| read_gltf(text.as_bytes(), "x.gltf", &mut no_files).map(|g| meshes(&g).len())); + assert!(r.is_ok(), "panicked on {what} (gltf)"); + } + let mut j = base.clone(); + j["extensionsRequired"] = json!(["KHR_draco_mesh_compression"]); + let e = read(&glb_container(j.to_string().as_bytes(), &f.bin)).err().unwrap().to_string(); + assert!(e.contains("KHR_draco_mesh_compression") && e.contains("uncompressed"), "{e}"); + // Looks-only extensions don't stop a file. + j["extensionsRequired"] = json!(["KHR_texture_transform", "KHR_materials_emissive_strength"]); + assert!(read(&glb_container(j.to_string().as_bytes(), &f.bin)).is_ok()); + // A deep chain is cut off or flattened, not followed forever. + let mut f = Fixture::default(); + let m = f.cube_mesh("Cube", 0.01); + let mut last = f.node(json!({"mesh": m})); + for _ in 0..200 { + last = f.node(json!({"mesh": m, "translation": [0.0, 0.0, 0.01], "children": [last]})); + } + f.roots = vec![last, 0]; + let g = read(&f.glb()).unwrap(); + assert!(g.plan.slots.len() <= MAX_COMPONENTS); + assert!(g.feature.warnings.iter().any(|w| w.contains("too large or too deep")), "{:?}", g.feature.warnings); + for junk in [&b""[..], b"glTF", b"glTF\x02\0\0\0", b"{", b"\xff\xfe", b"[]", b"{\"asset\":{\"version\":\"2.0\"}}"] { + assert_no_panic(junk, &format!("{junk:?}")); + assert!(read(junk).is_err()); + } +} diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 5b28962e0..8d1db8e96 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -31,6 +31,8 @@ pub use legacy_dir::{APP_ID, LEGACY_APP_ID, adopt_legacy_dir, legacy_flatpak_pat pub use safe_write::{backup_path, write_atomic}; pub use sketch2d::{Geom2, MAX_DRAWING_BYTES}; pub use svg::read_svg; +mod gltf_in; +pub use gltf_in::{GltfImport, Loader, MAX_GLTF_BYTES, MeshPlan, PlanPlace, glb_container, is_gltf_path, read_gltf}; mod obj; pub use obj::read_obj; pub use threemf::{MAX_3MF_BYTES, MeshObject, model_xml, model_xml_with, read_3mf, weld, write_3mf, write_3mf_with}; @@ -188,12 +190,15 @@ pub fn step_import_feature_named(bytes: &[u8], file: &str, names: StepNames) -> }) } -/// Is this a mesh file we import (`.3mf`, `.stl`, `.obj`, any case)? +/// Is this a mesh file we import (`.3mf`, `.stl`, `.obj`, `.glb`, `.gltf`, any case)? pub fn is_mesh_path(path: &str) -> bool { - std::path::Path::new(path).extension().and_then(|e| e.to_str()).is_some_and(|e| ["3mf", "stl", "obj"].iter().any(|x| e.eq_ignore_ascii_case(x))) + std::path::Path::new(path) + .extension() + .and_then(|e| e.to_str()) + .is_some_and(|e| ["3mf", "stl", "obj", "glb", "gltf"].iter().any(|x| e.eq_ignore_ascii_case(x))) } -/// A 3MF, STL or OBJ file read as a mesh import feature. +/// A 3MF, STL, OBJ or glTF file read as a mesh import feature. pub struct MeshFeature { /// Timeline name: the only mesh's name, else the file name. pub name: String, @@ -202,8 +207,16 @@ pub struct MeshFeature { pub warnings: Vec, } -/// Read 3MF, STL or OBJ bytes (the format from `file`'s extension) into a MeshImport feature. +/// Read 3MF, STL, OBJ or glTF bytes (the format from `file`'s extension) into a MeshImport +/// feature. A glTF file's bodies are all built where they are (see [`read_gltf`] for its node +/// tree), and it can't read buffers in other files. pub fn mesh_import_feature(bytes: &[u8], file: &str) -> Result { + if is_gltf_path(file) { + let mut no_files = |name: &str| Err(format!("`{name}` can't be read here")); + let mut g = read_gltf(bytes, file, &mut no_files)?; + g.flatten(); + return Ok(g.feature); + } if bytes.len() > MAX_3MF_BYTES { return Err(IoError::Invalid(format!("mesh file too large ({} MB)", bytes.len() >> 20))); } diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index fafbb136f..6330899dd 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -250,13 +250,15 @@ pub fn tool_definitions() -> Vec { "Open a design", "Open a .solidcraft design file, a STEP file (.step/.stp: a new design whose bodies come from the file, as an \ Import base feature in a component named after the file; an assembly's parts become nested components) or a \ - 3MF/STL mesh (.3mf/.stl: mesh bodies in such a component); the result reports the component (id, component_name). Replaces the current design; insert into it \ - instead with the file.insert_step (STEP) or file.insert_mesh (3MF/STL) commands. A STEP file from a system \ - that has Y up opens lying on its back: `up: \"y\"` turns its component a quarter turn about X (Y becomes Z). `names` picks what the bodies are named after when the solids' own names say nothing useful.", + mesh (.3mf/.stl/.obj/.glb/.gltf: mesh bodies in such a component; a glTF file's nodes become nested components and its \ + materials appearances); the result reports the component (id, component_name). Replaces the current design; insert into it \ + instead with the file.insert_step (STEP) or file.insert_mesh (mesh) commands. A STEP file from a system \ + that has Y up opens lying on its back: `up: \"y\"` turns its component a quarter turn about X (Y becomes Z). glTF is Y up, \ + so it is turned by default (`up: \"z\"` keeps its axes). `names` picks what the bodies are named after when the solids' own names say nothing useful.", obj( json!({ - "path": string("Path to a .solidcraft, .step/.stp, .3mf or .stl file"), - "up": {"type": "string", "enum": ["z", "y"], "description": "STEP only. z (default) keeps the file's axes; y: the file has Y up, so its bodies are turned to stand Z up"}, + "path": string("Path to a .solidcraft, .step/.stp, .3mf, .stl, .obj, .glb or .gltf file"), + "up": {"type": "string", "enum": ["z", "y"], "description": "STEP and glTF only. z keeps the file's axes; y: the file has Y up, so its bodies are turned to stand Z up. Default: z for STEP, y for glTF"}, "names": {"type": "string", "enum": ["solid", "product", "instance"], "description": "STEP only. What the bodies are named after: solid (default: the solid's own name, else the product's), product (the part's name) or instance (the assembly occurrence's name, else the product's)"}, }), &["path"], diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index b9eb20f97..46106d4d7 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -953,7 +953,7 @@ impl SolveApp { file_load::begin(self, path, true); } - /// Insert a STEP file's bodies (an Import base feature) or a 3MF/STL file's meshes into the + /// Insert a STEP file's bodies (an Import base feature) or a mesh file's meshes into the /// current design. pub fn insert_path(&mut self, path: &str) { let cmd = if solidcraft_engine::io::is_mesh_path(path) { "file.insert_mesh" } else { "file.insert_step" }; @@ -967,7 +967,7 @@ impl SolveApp { } } - /// A dropped file: a STEP, 3MF or STL file joins a design that has features, anything else + /// A dropped file: a STEP or mesh file (3MF, STL, OBJ, glTF) joins a design that has features, anything else /// opens. pub fn drop_path(&mut self, path: &str) { let import = solidcraft_engine::io::is_step_path(path) || solidcraft_engine::io::is_mesh_path(path); diff --git a/docs/book/src/guide/files.md b/docs/book/src/guide/files.md index 2338ad0c2..990719fef 100644 --- a/docs/book/src/guide/files.md +++ b/docs/book/src/guide/files.md @@ -7,6 +7,7 @@ | STEP (AP203, AP214, AP242) | solids, assemblies, units, names, colours | AP242 with names, colours and the component tree | | IGES 5.3 | manifold solids, or trimmed surfaces sewn into solids | manifold solids with names and colours | | 3MF, STL, OBJ | mesh bodies | yes | +| glTF 2.0 (`.glb`, `.gltf` with its `.bin` files) | mesh bodies in the node tree's components, materials as appearances | | | 3MF with face tags | as 3MF | each triangle tagged with its B-rep face, exact coordinates | | URDF | | the assembly as a robot: links with meshes, mass and inertia, joints from the assembly's joints | | DXF, SVG | into a sketch | sketches and flat patterns as DXF | @@ -16,13 +17,22 @@ Opening a STEP or IGES file creates a design with the file's bodies as a base fe inserting one adds them to the current design. Later features build on them. Mesh bodies render, measure, move and export, but solid features need B-rep bodies. -Every imported file (STEP, IGES, 3MF, STL or OBJ) comes in as a new component named after the +Every imported file (STEP, IGES, 3MF, STL, OBJ or glTF) comes in as a new component named after the file, so its bodies never mix with yours. A STEP assembly keeps its structure: its parts and sub-assemblies become nested components, and a part used several times is one component with an occurrence for each place. The imported assembly is rigid: moving its component moves everything, and its parts don't move on their own. Right-click the component and choose **Unlock Contents** to joint the parts one by one. Undo removes a whole import in one step. +A glTF file (`.glb`, or `.gltf` with the `.bin` files it names in the same folder) comes in the +same way: its nodes become nested components, a mesh placed several times is one component with +an occurrence for each place, and the whole import is rigid until you unlock it. glTF is in metres +with Y up, so the import is scaled to millimetres and turned to stand Z up (`up: "z"` keeps the +file's axes). Each material's base colour, metal and roughness become the body's appearance, so +the model looks right in Render; textures, skins and animations are not imported. Scaled or +mirrored nodes are baked into their meshes. Compressed meshes (Draco, meshopt) are refused with a +message: save the file uncompressed first. + **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 3dd8e2d17630cd54f84194d1ef7a2651c35cb5a9 Mon Sep 17 00:00:00 2001 From: Erikas <5955795+erkexzcx@users.noreply.github.com> Date: Fri, 16 Oct 2026 01:03:32 +0300 Subject: [PATCH 02/92] timeline.edit: refuse fields the feature's definition doesn't have (#1507) A field the definition doesn't have is refused with the fields it does have, instead of reporting success and changing nothing (#1491). Co-Authored-By: Erikas Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/cmd/edit.rs | 132 +++++++++++++++++++++++++++- crates/engine/src/cmd/edit_tests.rs | 30 +++++++ 2 files changed, 161 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 339b6af0e..2c90bf777 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -546,6 +546,129 @@ fn merge(dst: &mut Value, src: &Value, depth: usize) { } } +/// One step of a path into a feature's JSON definition. +#[derive(Clone)] +enum Step { + Key(String), + Index(usize), +} + +fn path_text(path: &[Step]) -> String { + let mut t = String::new(); + for s in path { + match s { + Step::Key(k) if t.is_empty() => t.push_str(k), + Step::Key(k) => t.push_str(&format!(".{k}")), + Step::Index(i) => t.push_str(&format!("[{i}]")), + } + } + t +} + +fn at_path<'a>(v: &'a Value, path: &[Step]) -> Option<&'a Value> { + path.iter().try_fold(v, |v, s| match s { + Step::Key(k) => v.get(k), + Step::Index(i) => v.get(i), + }) +} + +/// Does the stored feature read the field at `path` of `merged` (a feature's JSON with the edit +/// merged in)? serde skips a field it doesn't know whatever its value, but no field type takes a +/// flag, a text and nested lists alike. +fn reads_field(merged: &Value, path: &[Step]) -> bool { + let Some((last, parent)) = path.split_last() else { return true }; + [json!(true), json!("\u{1}"), json!([[[]]])].into_iter().any(|probe| { + let mut v = merged.clone(); + let slot = parent.iter().try_fold(&mut v, |v, s| match s { + Step::Key(k) => v.get_mut(k), + Step::Index(i) => v.get_mut(*i), + }); + match (slot, last) { + (Some(Value::Object(o)), Step::Key(k)) => { + o.insert(k.clone(), probe); + } + (Some(Value::Array(a)), Step::Index(i)) => match a.get_mut(*i) { + Some(x) => *x = probe, + None => return false, + }, + _ => return false, + } + serde_json::from_value::(v).is_err() + }) +} + +/// The first field of `set` that the feature's definition doesn't have. A field the definition +/// shows before or after the edit is known; one it leaves out (an unset option, a value at its +/// default) is known when the stored feature reads it. Setting an absent field to `null` +/// changes nothing either way and passes. +fn unknown_field( + set: &Value, + before: Option<&Value>, + after: Option<&Value>, + merged: &Value, + path: &mut Vec, + depth: usize, +) -> Option> { + if depth > 16 { + return None; + } + let check = |step: Step, v: &Value, path: &mut Vec| { + let one = [step]; + let (b, a) = (before.and_then(|x| at_path(x, &one)), after.and_then(|x| at_path(x, &one))); + let [step] = one; + path.push(step); + let found = if b.is_none() && a.is_none() && !v.is_null() && !reads_field(merged, path) { + Some(path.clone()) + } else { + unknown_field(v, b, a, merged, path, depth + 1) + }; + path.pop(); + found + }; + match set { + Value::Object(o) => o.iter().find_map(|(k, v)| check(Step::Key(k.clone()), v, path)), + Value::Array(items) => items.iter().enumerate().take(10_000).find_map(|(i, v)| check(Step::Index(i), v, path)), + _ => None, + } +} + +/// "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) { + match v { + Value::Object(o) if depth < 4 && !o.is_empty() => { + for (k, x) in o { + if top && NOT_EDITABLE.contains(&k.as_str()) { + continue; + } + let at = if prefix.is_empty() { k.clone() } else { format!("{prefix}.{k}") }; + leaves(x, &at, false, depth + 1, out); + } + } + _ if !prefix.is_empty() => out.push(format!("`{prefix}`")), + _ => {} + } + } + 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); + } + const SHOWN: usize = 40; + let more = known.len().saturating_sub(SHOWN); + known.truncate(SHOWN); + let mut list = known.join(", "); + if more > 0 { + list.push_str(&format!(" and {more} more")); + } + let field = path_text(field); + if list.is_empty() { + return format!("unknown field `{field}`; timeline.inspect lists {type_name}'s fields"); + } + format!("unknown field `{field}`; {type_name} has {list} (timeline.inspect shows them with their values)") +} + /// `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 { @@ -624,7 +747,7 @@ fn edit_feature(s: &mut Session, p: &Value) -> Result { let mut v = serde_json::to_value(&f).map_err(|e| EngineError::Other(e.to_string()))?; let set = &command_profiles(set, cmd)?; merge(&mut v, set, 0); - let mut nf: Feature = serde_json::from_value(v).map_err(|e| bad(cmd, format!("invalid feature: {e}")))?; + let mut nf: Feature = serde_json::from_value(v.clone()).map_err(|e| bad(cmd, format!("invalid feature: {e}")))?; nf.id = f.id; if let (FeatureKind::Extrude { extent: old, .. }, FeatureKind::Extrude { extent: new, .. }) = (&f.kind, &mut nf.kind) && old.direction != solidcraft_doc::Direction::Symmetric @@ -636,6 +759,13 @@ fn edit_feature(s: &mut Session, p: &Value) -> Result { if std::mem::discriminant(&nf.kind) != std::mem::discriminant(&f.kind) { return Err(bad(cmd, "the feature type cannot change")); } + // 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()))); + } if let FeatureKind::BodyTransfer { bodies, from, to, transform } = &nf.kind { solidcraft_doc::validate_body_transfer(&s.doc, bodies, *from, *to, transform)?; nf.component = *to; diff --git a/crates/engine/src/cmd/edit_tests.rs b/crates/engine/src/cmd/edit_tests.rs index 1b5e9ee3a..22ebcf033 100644 --- a/crates/engine/src/cmd/edit_tests.rs +++ b/crates/engine/src/cmd/edit_tests.rs @@ -492,3 +492,33 @@ fn timeline_folders_can_nest_and_reject_cycles() { run(&mut s, "timeline.ungroup", json!({"group": root})); assert_eq!(s.doc.timeline_groups.iter().find(|group| group.id == child).unwrap().parent, None, "deleting a folder promotes its children"); } + +/// A field the feature's definition doesn't have is refused with the fields it does have, +/// instead of reporting success and changing nothing (#1491). +#[test] +fn edit_refuses_unknown_fields() { + let mut s = Session::default(); + run(&mut s, "construct.plane.offset", json!({"base": "XZ", "offset": 50, "name": "P"})); + let e = s.execute("timeline.edit", &json!({"feature": "P", "set": {"offset": "-50"}})).unwrap_err().to_string(); + assert!(e.contains("unknown field `offset`") && e.contains("`plane.distance`"), "{e}"); + let e = s.execute("timeline.edit", &json!({"feature": "P", "set": {"plane": {"dist": "-50"}}})).unwrap_err().to_string(); + assert!(e.contains("unknown field `plane.dist`") && e.contains("`plane.distance`"), "{e}"); + let def = run(&mut s, "timeline.inspect", json!({"feature": "P"}))["definition"].clone(); + assert_eq!(def["plane"]["distance"], json!("50"), "nothing changed: {def}"); + // The field it does have edits as before. + run(&mut s, "timeline.edit", json!({"feature": "P", "set": {"plane": {"distance": "-50"}}})); + let def = run(&mut s, "timeline.inspect", json!({"feature": "P"}))["definition"].clone(); + assert_eq!(def["plane"]["distance"], json!("-50"), "{def}"); + + // Fields the definition leaves out at their default are still fields: `combine: false` + // and `bodies: []` aren't shown on a feature mirror, and set them as they are. + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "name": "Base"})); + run(&mut s, "solid.mirror", json!({"features": ["Base"], "plane": "YZ", "name": "Twin"})); + run(&mut s, "timeline.edit", json!({"feature": "Twin", "set": {"combine": false, "bodies": []}})); + run(&mut s, "timeline.edit", json!({"feature": "Twin", "set": {"combine": true}})); + // An unknown field next to known ones refuses the whole edit. + let e = s.execute("timeline.edit", &json!({"feature": "Twin", "set": {"combine": false, "flip": true}})).unwrap_err().to_string(); + assert!(e.contains("unknown field `flip`") && e.contains("`combine`") && e.contains("`plane.name`"), "{e}"); + let def = run(&mut s, "timeline.inspect", json!({"feature": "Twin"}))["definition"].clone(); + assert_eq!(def["combine"], json!(true), "{def}"); +} From 061c0f3333e99eb12c7166574797b742b0bd5263 Mon Sep 17 00:00:00 2001 From: selune <35337584+0xlillith@users.noreply.github.com> Date: Fri, 16 Oct 2026 00:04:09 +0200 Subject: [PATCH 03/92] render: add perspective UV interpolation and derivatives (#1461) Co-Authored-By: selune <0xlillith@users.noreply.github.com> Co-Authored-By: Claude Sonnet 5.5 --- crates/render/src/lib.rs | 1 + crates/render/src/texture_interpolation.rs | 114 ++++++++++++++++++ .../render/src/texture_interpolation_tests.rs | 104 ++++++++++++++++ docs/render-texture-interpolation.md | 54 +++++++++ 4 files changed, 273 insertions(+) create mode 100644 crates/render/src/texture_interpolation.rs create mode 100644 crates/render/src/texture_interpolation_tests.rs create mode 100644 docs/render-texture-interpolation.md diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 46b4af0db..3de0e090c 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -14,6 +14,7 @@ mod raster; pub mod studio; pub mod surface; pub mod texture_input; +pub mod texture_interpolation; pub use backend::{ Availability, BackendDescriptor, BackendId, ExecutorDescriptor, ExecutorId, MAX_RENDER_ID_BYTES, RenderFeature, RenderFormat, RenderLimits, diff --git a/crates/render/src/texture_interpolation.rs b/crates/render/src/texture_interpolation.rs new file mode 100644 index 000000000..fea10bb3a --- /dev/null +++ b/crates/render/src/texture_interpolation.rs @@ -0,0 +1,114 @@ +//! Perspective-correct unwrapped UV and analytic gradients from caller-owned barycentrics. +//! No projection, clipping, raster coverage, instance transform or texture sampling. + +pub const UV_INTERPOLATION_POLICY: &str = "solidcraft.perspective-uv-differential/1"; +/// Matches the existing raster's near-edge admission; does not replace its top-left rule. +pub const BARYCENTRIC_EDGE_TOLERANCE: f64 = 1e-9; +const MAX_UV: f64 = 1_000_000.0; +const MAX_DERIVATIVE: f64 = 1_000_000.0; +const SUM_TOLERANCE: f64 = 1e-12; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum InterpolationError { + VertexUv, + ReciprocalW, + Barycentrics, + Derivatives, + Output, +} +impl std::fmt::Display for InterpolationError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::VertexUv => "vertex UV must be finite and within one million repeats", + Self::ReciprocalW => "reciprocal clip-w must be finite and in [1e-12, 1e12]", + Self::Barycentrics => "barycentric weights exceed near-edge bounds or do not sum to one", + Self::Derivatives => "barycentric derivatives must be bounded, finite and sum to zero", + Self::Output => "interpolated UV or gradients exceed the numerical reference bounds", + }) + } +} +impl std::error::Error for InterpolationError {} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct UvDifferential { + pub uv: [f64; 2], + /// Unwrapped UV per actual shading-grid pixel step, not necessarily final-image pixels. + pub duv_dx: [f64; 2], + pub duv_dy: [f64; 2], +} + +#[derive(Clone, Copy, Debug)] +pub struct PerspectiveUv { + anchor: [f64; 2], + deltas: [[f64; 2]; 3], + reciprocal_w: [f64; 3], +} +impl PerspectiveUv { + /// Vertices must already have valid positive clip-w after caller-owned clipping. + /// Only a common reciprocal-w scale is removed; UVs are never wrapped or flipped. + pub fn new(uv: [[f64; 2]; 3], reciprocal_w: [f64; 3]) -> Result { + if uv.iter().flatten().any(|v| !v.is_finite() || v.abs() > MAX_UV) { + return Err(InterpolationError::VertexUv); + } + if reciprocal_w.iter().any(|v| !v.is_finite() || !(1e-12..=1e12).contains(v)) { + return Err(InterpolationError::ReciprocalW); + } + let [anchor, _, _] = uv; + let [anchor_u, anchor_v] = anchor; + let scale = reciprocal_w.into_iter().fold(0.0, f64::max); + let deltas = uv.map(|[u, v]| [u - anchor_u, v - anchor_v]); + Ok(Self { anchor, deltas, reciprocal_w: reciprocal_w.map(|v| v / scale) }) + } + + /// Barycentrics and derivatives come from the same projected triangle/shading grid. + /// No coverage rule is applied here: weights beyond the explicit near-edge bound, malformed partitions and + /// unsupported gradients refuse instead of falling back to affine interpolation. + pub fn evaluate(&self, weights: [f64; 3], dweights_dx: [f64; 3], dweights_dy: [f64; 3]) -> Result { + let admitted_weights = -BARYCENTRIC_EDGE_TOLERANCE..=1.0 + 2.0 * BARYCENTRIC_EDGE_TOLERANCE; + if weights.iter().any(|v| !v.is_finite() || !admitted_weights.contains(v)) || (weights.into_iter().sum::() - 1.0).abs() > SUM_TOLERANCE { + return Err(InterpolationError::Barycentrics); + } + for derivatives in [dweights_dx, dweights_dy] { + let scale = derivatives.into_iter().map(f64::abs).fold(1.0, f64::max); + if derivatives.iter().any(|v| !v.is_finite() || v.abs() > MAX_DERIVATIVE) + || derivatives.into_iter().sum::().abs() > SUM_TOLERANCE * scale + { + return Err(InterpolationError::Derivatives); + } + } + let denominator = weighted_sum(weights, self.reciprocal_w); + if !(denominator > 0.0) || !denominator.is_finite() { + return Err(InterpolationError::Output); + } + let dx_denominator = weighted_sum(dweights_dx, self.reciprocal_w); + let dy_denominator = weighted_sum(dweights_dy, self.reciprocal_w); + let evaluate_channel = |anchor, [a, b, c]: [f64; 3]| { + let [qa, qb, qc] = self.reciprocal_w; + let corrected = [a * qa, b * qb, c * qc]; + let delta = weighted_sum(weights, corrected) / denominator; + // Avoid denominator squared and subtract the anchor before differentiating. + [ + anchor + delta, + (weighted_sum(dweights_dx, corrected) - delta * dx_denominator) / denominator, + (weighted_sum(dweights_dy, corrected) - delta * dy_denominator) / denominator, + ] + }; + let [[u0, v0], [u1, v1], [u2, v2]] = self.deltas; + let [anchor_u, anchor_v] = self.anchor; + let [u, du_dx, du_dy] = evaluate_channel(anchor_u, [u0, u1, u2]); + let [v, dv_dx, dv_dy] = evaluate_channel(anchor_v, [v0, v1, v2]); + let result = UvDifferential { uv: [u, v], duv_dx: [du_dx, dv_dx], duv_dy: [du_dy, dv_dy] }; + if result.uv.iter().chain(&result.duv_dx).chain(&result.duv_dy).any(|v| !v.is_finite() || v.abs() > MAX_UV) { + return Err(InterpolationError::Output); + } + Ok(result) + } +} + +fn weighted_sum(a: [f64; 3], b: [f64; 3]) -> f64 { + a.into_iter().zip(b).map(|(a, b)| a * b).sum() +} + +#[cfg(test)] +#[path = "texture_interpolation_tests.rs"] +mod tests; diff --git a/crates/render/src/texture_interpolation_tests.rs b/crates/render/src/texture_interpolation_tests.rs new file mode 100644 index 000000000..7677fb608 --- /dev/null +++ b/crates/render/src/texture_interpolation_tests.rs @@ -0,0 +1,104 @@ +use super::*; +const UV: [[f64; 2]; 3] = [[0., 0.], [1., 0.], [0., 1.]]; +const WEIGHTS: [f64; 3] = [0.5, 0.25, 0.25]; +const DX: [f64; 3] = [-1., 1., 0.]; +const DY: [f64; 3] = [-1., 0., 1.]; + +fn close(actual: [f64; 2], expected: [f64; 2]) { + for (a, b) in actual.into_iter().zip(expected) { + assert!((a - b).abs() < 1e-10, "{actual:?} != {expected:?}"); + } +} + +#[test] +fn orthographic_uv_and_derivatives_match_the_affine_plane() { + let result = PerspectiveUv::new(UV, [1.; 3]).unwrap().evaluate(WEIGHTS, DX, DY).unwrap(); + close(result.uv, [0.25, 0.25]); + close(result.duv_dx, [1., 0.]); + close(result.duv_dy, [0., 1.]); +} + +#[test] +fn perspective_quotient_and_derivatives_match_closed_form() { + let result = PerspectiveUv::new(UV, [1., 2., 1.]).unwrap().evaluate(WEIGHTS, DX, DY).unwrap(); + close(result.uv, [0.4, 0.2]); + close(result.duv_dx, [1.28, -0.16]); + close(result.duv_dy, [0., 0.8]); +} + +#[test] +fn common_clip_scale_and_vertex_order_preserve_the_result() { + for scale in [1e-6, 1., 1e6] { + for order in [[0, 1, 2], [2, 1, 0], [1, 2, 0]] { + let q = [scale, 2. * scale, scale]; + let interpolation = PerspectiveUv::new(order.map(|i| UV[i]), order.map(|i| q[i])).unwrap(); + let result = interpolation.evaluate(order.map(|i| WEIGHTS[i]), order.map(|i| DX[i]), order.map(|i| DY[i])).unwrap(); + close(result.uv, [0.4, 0.2]); + close(result.duv_dx, [1.28, -0.16]); + close(result.duv_dy, [0., 0.8]); + } + } +} + +#[test] +fn constant_large_offset_has_exactly_zero_gradients() { + let interpolation = PerspectiveUv::new([[999_999., -999_999.]; 3], [1e-12, 1., 1e12]).unwrap(); + let result = interpolation.evaluate(WEIGHTS, DX, DY).unwrap(); + assert_eq!(result.uv, [999_999., -999_999.]); + assert_eq!(result.duv_dx, [0.; 2]); + assert_eq!(result.duv_dy, [0.; 2]); +} + +#[test] +fn vertices_edges_and_shading_grid_units_remain_explicit() { + let interpolation = PerspectiveUv::new(UV, [1., 2., 1.]).unwrap(); + close(interpolation.evaluate([0., 1., 0.], DX, DY).unwrap().uv, [1., 0.]); + close(interpolation.evaluate([0.5, 0.5, 0.], DX, DY).unwrap().uv, [2. / 3., 0.]); + let fine = interpolation.evaluate(WEIGHTS, DX.map(|v| v / 2.), DY.map(|v| v / 4.)).unwrap(); + close(fine.uv, [0.4, 0.2]); + close(fine.duv_dx, [0.64, -0.08]); + close(fine.duv_dy, [0., 0.2]); +} + +#[test] +fn invalid_vertices_and_reciprocal_w_are_refused() { + for value in [f64::NAN, f64::INFINITY, MAX_UV + 1., -MAX_UV - 1.] { + assert!(matches!(PerspectiveUv::new([[value, 0.]; 3], [1.; 3]), Err(InterpolationError::VertexUv))); + } + for value in [f64::NAN, f64::INFINITY, 0., -1., 1e-13, 1e13] { + assert!(matches!(PerspectiveUv::new(UV, [1., value, 1.]), Err(InterpolationError::ReciprocalW))); + } +} + +#[test] +fn malformed_partitions_and_gradients_are_refused() { + let interpolation = PerspectiveUv::new(UV, [1.; 3]).unwrap(); + for weights in [[0.; 3], [1.; 3], [-0.1, 0.6, 0.5], [f64::NAN, 0., 1.], [f64::INFINITY, 0., 0.]] { + assert_eq!(interpolation.evaluate(weights, DX, DY), Err(InterpolationError::Barycentrics)); + } + for derivatives in [[1.; 3], [f64::NAN, 0., 0.], [f64::INFINITY, 0., 0.], [-MAX_DERIVATIVE - 1., MAX_DERIVATIVE + 1., 0.]] { + assert_eq!(interpolation.evaluate(WEIGHTS, derivatives, DY), Err(InterpolationError::Derivatives)); + assert_eq!(interpolation.evaluate(WEIGHTS, DX, derivatives), Err(InterpolationError::Derivatives)); + } +} + +#[test] +fn unsupported_output_gradient_refuses_without_affine_fallback() { + let interpolation = PerspectiveUv::new(UV, [1e-12, 1e12, 1.]).unwrap(); + assert_eq!(interpolation.evaluate([1., 0., 0.], DX, DY), Err(InterpolationError::Output)); + assert!(PerspectiveUv::new(UV, [1.; 3]).unwrap().evaluate(WEIGHTS, DX, DY).is_ok()); +} + +#[test] +fn near_edge_admission_keeps_exact_weights_and_refuses_beyond_bound_or_nonpositive_denominator() { + let e = BARYCENTRIC_EDGE_TOLERANCE; + let interpolation = PerspectiveUv::new(UV, [1.; 3]).unwrap(); + let result = interpolation.evaluate([-e, 1. + 2. * e, -e], DX, DY).unwrap(); + close(result.uv, [1. + 2. * e, -e]); + close(result.duv_dx, [1., 0.]); + close(result.duv_dy, [0., 1.]); + let outside = -e * 1.00001; + assert_eq!(interpolation.evaluate([outside, 0.5, 0.5 - outside], DX, DY), Err(InterpolationError::Barycentrics)); + let perspective = PerspectiveUv::new(UV, [1e12, 1e-12, 1.]).unwrap(); + assert_eq!(perspective.evaluate([-e, 1. + e, 0.], DX, DY), Err(InterpolationError::Output)); +} diff --git a/docs/render-texture-interpolation.md b/docs/render-texture-interpolation.md new file mode 100644 index 000000000..a2ede31b8 --- /dev/null +++ b/docs/render-texture-interpolation.md @@ -0,0 +1,54 @@ +# Perspective UV differential reference + +The independent L1 helper in #1346 supports the first wood consumer #1345. +`solidcraft_render::texture_interpolation::PerspectiveUv` accepts three unwrapped +vertex UVs and positive reciprocal clip-w values. `evaluate` takes the existing +rasterizer's screen barycentric weights and their x/y derivatives. It returns UV +and analytic perspective-correct derivatives without changing raster coverage, +projection, clipping, local mm mapping, instance transforms or resource ownership. +No pending helper branch, new dependency, file asset or GPU code is required. + +Vertex UV magnitudes are at most one million repeats. Reciprocal-w is finite in +[1e-12, 1e12]; only a common scale is removed, preserving relative perspective. +Weights must be finite in [-1e-9, 1+2e-9] and sum to one within 1e-12. The lower +bound matches the existing raster's near-edge tolerance; the upper bound follows +from two weights at that lower bound and partition of unity. This admits bounded +near-edge extrapolation and preserves the exact supplied weights, including small +negative UV results. It neither clamps weights nor replaces the caller's shared-edge +top-left decision. Negative near-edge weights can make a perspective denominator +nonpositive at extreme clip-w ratios; that explicitly refuses. The caller retains +its existing raw reciprocal-w sum/depth/coverage guards before invoking the helper. +Each derivative must +be finite with magnitude at most one million and sum to zero within +`1e-12 * max(1, largest_component_magnitude)`. No weights or derivatives are +silently repaired, normalized or clamped. The caller must supply derivatives +consistent with its projected triangle; admission alone cannot prove that. + +For q=1/w, the interpolation is `UV = sum(b*q*UV_vertex) / sum(b*q)`. +The helper subtracts the first vertex's UV before forming the numerator, then +adds it back to the result. This makes a constant large UV offset have exactly +zero derivatives instead of cancellation artifacts. Derivatives use the quotient +rule as `(dN - (N/D)*dD)/D`, avoiding a squared tiny denominator. Intermediates +are f64. Returned UV and derivative magnitudes must remain at most one million, +finite, or the evaluation refuses. No affine fallback hides unsupported results. + +UVs remain unwrapped: do not repeat-wrap vertices before interpolation. No Y flip +or normal/tangent interpretation is added. The barycentric derivatives are per +pixel of the actual shading grid. When starting from final-image-pixel derivatives +and supersampling Sx by Sy, the caller divides x/y derivatives by Sx/Sy exactly +once. Already shading-grid derivatives must not be rescaled. This matches #1339's +LOD boundary without introducing a dependency on that unpublished implementation. + +Caller responsibilities include positive clip-w after near-plane clipping, +triangle degeneracy/coverage/top-left rules, sample placement and valid derivatives. +This is a numerical reference, not a new rasterizer, clipping algorithm or proof +of that caller policy. GPU interpolation/gradient precision requires separate parity +evidence. Anisotropy, normal filtering, grain-frame inference and a visible texture +consumer remain separate work. No HDRI or final renderer capability is advertised. + +Version identifier `solidcraft.perspective-uv-differential/1` documents the input, +partition, precision and refusal policy. Original analytic tests cover affine and +perspective values/derivatives, reciprocal-w scaling, vertex order, large constant +offsets, edges, supersampling units and hostile/refused outputs. This invisible +helper has no useful app screenshot; actual wood still requires PNG, CPU/GPU and +offline-reopen evidence from the installed consumer. From 73493b94c3af065f820363b4b0db7b67085808ca Mon Sep 17 00:00:00 2001 From: cronos Date: Fri, 16 Oct 2026 07:04:17 +0900 Subject: [PATCH 04/92] Measure circle and arc centres as fixed 3D points (#1514) Picked circles and arcs keep their own centres when measured; only a cylindrical face uses its axis. Co-authored-by: cronos Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/cmd/measure_shape.rs | 63 ++++++++++++++++++++--- crates/engine/src/measure_centre_tests.rs | 33 ++++++++++++ 2 files changed, 88 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/measure_shape.rs b/crates/engine/src/cmd/measure_shape.rs index 507d57a3a..5c7f4ad9c 100644 --- a/crates/engine/src/cmd/measure_shape.rs +++ b/crates/engine/src/cmd/measure_shape.rs @@ -170,14 +170,20 @@ fn from_round(a: &Shape, b: &Shape) -> Option { let Shape::Round { center: ca, axis: na, radius: ra, planar: pa, lo: loa, hi: hia, .. } = *a else { return None }; let full_a = a.full(); let c = match *b { - Shape::Round { center: cb, axis: nb, radius: rb, lo: lob, hi: hib, .. } => { + Shape::Round { center: cb, axis: nb, radius: rb, planar: pb, lo: lob, hi: hib, .. } => { + // A picked circle/arc has a fixed centre; only a cylindrical face has an + // infinite axis. Do not project a rim's centre onto an imaginary extension. + let (from, to) = match (pa, pb) { + (true, true) => (ca, cb), + (true, false) => (ca, cb + nb * (ca - cb).dot(nb)), + (false, true) => (ca + na * (cb - ca).dot(na), cb), + (false, false) => line_line(ca, na, cb, nb), + }; + let (mut min, mut max) = (None, None); if parallel(na, nb) { let w = cb - ca; let along = w.dot(na); - // Drawn level with A's centre: on B's axis, the foot of A's centre. - let foot = cb - na * along; let d = (w - na * along).len(); - let (mut min, mut max) = (None, None); if full_a && b.full() { // B's extent along A's axis. let s = if na.dot(nb) >= 0.0 { 1.0 } else { -1.0 }; @@ -189,11 +195,8 @@ fn from_round(a: &Shape, b: &Shape) -> Option { min = Some(near.hypot(gap)); max = Some(far.hypot(reach)); } - Centre { distance: d, from: ca, to: foot, min, max } - } else { - let (p, q) = line_line(ca, na, cb, nb); - Centre { distance: p.dist(q), from: p, to: q, min: None, max: None } } + Centre { distance: from.dist(to), from, to, min, max } } Shape::Plane { point, normal } => { let n = normal.normalized()?; @@ -339,6 +342,50 @@ mod tests { assert!((c.max.unwrap() - 55.0).abs() < 1e-12); } + #[test] + fn circles_at_different_heights_keep_both_actual_centres() { + let (a, b) = (Vec3::new(0.0, 0.0, 10.0), Vec3::new(34.0, 19.0, 32.0)); + let c = centre(&circle(a, 4.0), &circle(b, 4.0)).unwrap(); + assert_eq!((c.from, c.to), (a, b)); + assert!((c.distance - 2001_f64.sqrt()).abs() < 1e-12); + assert!((c.min.unwrap() - (1517_f64.sqrt() - 8.0).hypot(22.0)).abs() < 1e-12); + assert!((c.max.unwrap() - (1517_f64.sqrt() + 8.0).hypot(22.0)).abs() < 1e-12); + let swapped = centre(&circle(b, 4.0), &circle(a, 4.0)).unwrap(); + assert_eq!((swapped.from, swapped.to, swapped.distance), (b, a, c.distance)); + } + + #[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 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()); + } + + #[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] { + 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) }; + 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(); + assert_eq!((swapped.from, swapped.to, swapped.distance), (c.to, c.from, c.distance)); + } + } + + #[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 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); + } + #[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 }; diff --git a/crates/engine/src/measure_centre_tests.rs b/crates/engine/src/measure_centre_tests.rs index 747918891..3526597cd 100644 --- a/crates/engine/src/measure_centre_tests.rs +++ b/crates/engine/src/measure_centre_tests.rs @@ -104,6 +104,39 @@ fn two_holes_measure_centre_to_centre_with_min_and_max() { assert_eq!(r["items"][0]["round"], "circle", "{r}"); } +#[test] +fn elevated_cylinder_rims_measure_between_the_picked_circles_centres() { + let mut s = Session::default(); + run(&mut s, "solid.cylinder", json!({"radius":4,"height":10,"body_name":"A"})); + run(&mut s, "solid.cylinder", json!({"base":[34,19,22],"radius":4,"height":10,"body_name":"B","operation":"new_body"})); + let items: Vec<_> = s + .model + .state() + .bodies + .iter() + .map(|b| { + let z = if b.name == "A" { 10.0 } else { 32.0 }; + let m = b.mesh(); + let index = m.edges.iter().position(|e| e.len() > 2 && e.iter().all(|p| (p.z - z).abs() < 1e-9)).unwrap(); + let e = &m.edges[index]; + json!({"type":"edge","body":b.name,"index":index,"point":e[e.len()/2]}) + }) + .collect(); + assert_eq!(items.len(), 2); + for picks in [items.clone(), items.into_iter().rev().collect()] { + let r = measure(&mut s, picks); + assert!(close(&r["center_distance"], 2001_f64.sqrt(), 1e-9), "{r}"); + for (endpoint, item) in [("center_from", 0), ("center_to", 1)] { + for axis in 0..3 { + assert!(close(&r[endpoint][axis], r["items"][item]["center"][axis].as_f64().unwrap(), 1e-9), "{r}"); + } + } + assert!((r["center_delta"][2].as_f64().unwrap().abs() - 22.0).abs() < 1e-9, "{r}"); + assert!(close(&r["min"], (1517_f64.sqrt() - 8.0).hypot(22.0), 1e-9), "{r}"); + assert!(close(&r["max"], (1517_f64.sqrt() + 8.0).hypot(22.0), 1e-9), "{r}"); + } +} + #[test] fn a_hole_to_the_plate_edge_and_side_measures_from_its_axis() { let mut s = Session::default(); From 6128a20c5fac5d513faea19c432bf59ed6332079 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Thu, 15 Oct 2026 18:36:41 -0400 Subject: [PATCH 05/92] Agent chat on Windows: start npm agents through their .cmd shim (#1530) --- crates/ui-egui/src/agent_chat/discover.rs | 42 +++++++++++++++++++++-- crates/ui-egui/src/agent_chat/process.rs | 5 ++- 2 files changed, 43 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/agent_chat/discover.rs b/crates/ui-egui/src/agent_chat/discover.rs index fcd09660c..24fffffaf 100644 --- a/crates/ui-egui/src/agent_chat/discover.rs +++ b/crates/ui-egui/src/agent_chat/discover.rs @@ -184,13 +184,30 @@ pub fn search_dirs() -> Vec { dirs } -/// The first `program` in `dirs` (on Windows also with `.exe`/`.cmd`). +/// The first `program` in `dirs` (on Windows with `.exe`/`.cmd`/`.bat`). pub fn find_in(program: &str, dirs: &[PathBuf]) -> Option { - let names: Vec = - if cfg!(windows) { ["", ".exe", ".cmd", ".bat"].iter().map(|e| format!("{program}{e}")).collect() } else { vec![program.to_string()] }; + let names = names_for(program, cfg!(windows)); dirs.iter().flat_map(|d| names.iter().map(move |n| d.join(n))).find(|p| p.is_file()) } +/// The file names `program` can have. On Windows only ones it can run: npm puts a Unix shell +/// script with the bare name next to the `.cmd` shim, and starting that fails with "not a valid +/// Win32 application". +fn names_for(program: &str, windows: bool) -> Vec { + if windows { [".exe", ".cmd", ".bat"].iter().map(|e| format!("{program}{e}")).collect() } else { vec![program.to_string()] } +} + +/// A Windows command saved without an extension (`…\npm\codex-acp`, from an older version's +/// lookup): the `.exe`/`.cmd`/`.bat` beside it, if there is one. +pub fn runnable_sibling(program: &Path) -> Option { + if program.extension().is_some() { + return None; + } + let dir = program.parent()?; + let name = program.file_name()?.to_str()?; + names_for(name, true).into_iter().map(|n| dir.join(n)).find(|p| p.is_file()) +} + /// `program --version`'s first line, or `None` after `limit` (the probe is then stopped). fn version(program: &Path, limit: Duration) -> Option { let mut cmd = if cfg!(windows) && program.extension().is_some_and(|e| e.eq_ignore_ascii_case("cmd") || e.eq_ignore_ascii_case("bat")) { @@ -279,6 +296,25 @@ mod tests { let _ = std::fs::remove_dir_all(root); } + #[test] + fn on_windows_only_runnable_shims_are_candidates() { + // npm's bare `codex-acp` is a shell script; Windows can't start it (os error 193). + assert_eq!(names_for("codex-acp", true), ["codex-acp.exe", "codex-acp.cmd", "codex-acp.bat"]); + assert_eq!(names_for("codex-acp", false), ["codex-acp"]); + } + + #[test] + fn a_saved_bare_npm_path_runs_its_cmd_shim() { + let root = std::env::temp_dir().join(format!("sc-agent-shim-{}", std::process::id())); + std::fs::create_dir_all(&root).unwrap(); + std::fs::write(root.join("codex-acp"), "#!/bin/sh").unwrap(); + std::fs::write(root.join("codex-acp.cmd"), "@echo off").unwrap(); + assert_eq!(runnable_sibling(&root.join("codex-acp")), Some(root.join("codex-acp.cmd"))); + assert_eq!(runnable_sibling(&root.join("codex-acp.cmd")), None); + assert_eq!(runnable_sibling(&root.join("gemini")), None); + let _ = std::fs::remove_dir_all(root); + } + #[test] fn the_version_number_is_picked_out_of_the_line() { assert_eq!(version_of("@agentclientprotocol/codex-acp 2.2.2"), "2.2.2"); diff --git a/crates/ui-egui/src/agent_chat/process.rs b/crates/ui-egui/src/agent_chat/process.rs index 4fc644842..e7049972d 100644 --- a/crates/ui-egui/src/agent_chat/process.rs +++ b/crates/ui-egui/src/agent_chat/process.rs @@ -51,8 +51,11 @@ impl ProcessHandle { } } -/// On Windows, npm installs `.cmd` shims, which only `cmd.exe` runs. +/// On Windows, npm installs `.cmd` shims, which only `cmd.exe` runs. A command saved as the bare +/// npm path (a shell script there) runs the shim beside it. fn command_for(program: &str) -> Command { + let shim = if cfg!(windows) { super::discover::runnable_sibling(std::path::Path::new(program)) } else { None }; + let program = shim.as_deref().and_then(|p| p.to_str()).unwrap_or(program); let lower = program.to_ascii_lowercase(); if cfg!(windows) && (lower.ends_with(".cmd") || lower.ends_with(".bat")) { let mut c = Command::new("cmd"); From b44ada89e58cc253dd9722122de10c00170de101 Mon Sep 17 00:00:00 2001 From: DuBearte <130190089+DuBearte@users.noreply.github.com> Date: Thu, 15 Oct 2026 18:40:07 -0400 Subject: [PATCH 06/92] Preferences: choose the interface font (#1408) Adds an Interface font setting that leads the proportional family, with the default face and CJK/Hangul fallbacks kept behind it (#1290). Co-authored-by: DuBearte Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/fonts.rs | 62 +++++++++++++++++++++-- crates/ui-egui/src/lib.rs | 8 ++- crates/ui-egui/src/prefs.rs | 83 +++++++++++++++++++++++++++++++ crates/ui-egui/src/sketch_text.rs | 2 +- docs/control-protocol.md | 2 +- 5 files changed, 148 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/fonts.rs b/crates/ui-egui/src/fonts.rs index 00c9c8688..b02fb892f 100644 --- a/crates/ui-egui/src/fonts.rs +++ b/crates/ui-egui/src/fonts.rs @@ -16,6 +16,34 @@ pub const CJK_FALLBACK: &str = "cjk_fallback"; /// Chinese falls through to this one per glyph. pub const CHINESE_FALLBACK: &str = "chinese_fallback"; +/// Name of the chosen interface font in [`egui::FontDefinitions`], first in the Proportional +/// family when one is set (#1290). +pub const UI_FONT: &str = "ui_font"; + +/// The interface font a preference names (#1290): an installed family, a font file, or the +/// sketch text's built-in family. `None` for the default (empty) or a font that can't be read. +pub fn ui_font(name: &str) -> Option { + let name = name.trim(); + if name.is_empty() { + return None; + } + let data = solidcraft_engine::sketch::font_data(Some(name)).ok()?; + ttf_parser::Face::parse(data.bytes(), data.index).ok()?; + let mut font = egui::FontData::from_owned(data.bytes().to_vec()); + font.index = data.index; + Some(font) +} + +/// `fonts` with `font` first in the Proportional family (menus, dialogs, labels); the default +/// face and the fallbacks stay after it for the glyphs it lacks. +pub fn with_ui_font(mut fonts: egui::FontDefinitions, font: egui::FontData) -> egui::FontDefinitions { + fonts.font_data.insert(UI_FONT.to_owned(), Arc::new(font)); + let list = fonts.families.entry(egui::FontFamily::Proportional).or_default(); + list.retain(|entry| entry != UI_FONT); + list.insert(0, UI_FONT.to_owned()); + fonts +} + /// Name of the Hangul fallback entry in [`egui::FontDefinitions`], last. pub const HANGUL_FALLBACK: &str = "hangul_fallback"; @@ -441,14 +469,20 @@ pub fn fallback_order(language: &str) -> [&'static str; 3] { } /// Configure font definitions with system CJK, Chinese and Hangul fallbacks where available, -/// ordered for the UI language (see [`fallback_order`]). +/// ordered for the UI language (see [`fallback_order`]), after the interface font `ui_font` +/// when one is chosen (see [`ui_font`]). #[cfg(not(target_arch = "wasm32"))] -pub fn setup_fonts_for(ctx: &egui::Context, language: &str) { +pub fn setup_fonts_for(ctx: &egui::Context, language: &str, ui_font: &str) { let cjk = find_system_cjk_font(); let chinese = find_system_chinese_font().filter(|bytes| cjk.as_ref() != Some(bytes)); let hangul = HANGUL_FONT_CANDIDATES.iter().find_map(|path| try_read_font(std::path::Path::new(path))); let mut fonts = egui::FontDefinitions::default(); - let mut found = false; + // 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); + } for name in fallback_order(language) { let bytes = match name { CJK_FALLBACK => cjk.clone(), @@ -472,7 +506,7 @@ pub fn setup_fonts_for(ctx: &egui::Context, language: &str) { /// follows the language, see [`setup_fonts_for`]). #[cfg(not(target_arch = "wasm32"))] pub fn setup_fonts(ctx: &egui::Context) { - setup_fonts_for(ctx, "en"); + setup_fonts_for(ctx, "en", ""); } /// Find a font covering simplified Chinese in the known candidate paths or by scanning the @@ -499,7 +533,7 @@ fn find_system_chinese_font() -> Option> { /// On web, setup_fonts does not perform synchronous disk reads. /// Use asynchronous loading through [`solidcraft_web`] or host scripts. #[cfg(target_arch = "wasm32")] -pub fn setup_fonts_for(_ctx: &egui::Context, _language: &str) {} +pub fn setup_fonts_for(_ctx: &egui::Context, _language: &str, _ui_font: &str) {} #[cfg(target_arch = "wasm32")] pub fn setup_fonts(_ctx: &egui::Context) {} @@ -508,6 +542,24 @@ pub fn setup_fonts(_ctx: &egui::Context) {} mod tests { use super::*; + #[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. + assert!(ui_font("").is_none()); + assert!(ui_font("No Such Font 1290").is_none()); + let font = ui_font(solidcraft_engine::sketch::DEFAULT_FONT_FAMILY).expect("the built-in sketch font reads"); + let defaults = egui::FontDefinitions::default(); + let first_default = defaults.families[&egui::FontFamily::Proportional][0].clone(); + let fonts = with_ui_font(defaults, font.clone()); + let list = &fonts.families[&egui::FontFamily::Proportional]; + assert_eq!(list[0], UI_FONT); + assert!(list.contains(&first_default), "{list:?}"); + assert!(!fonts.families[&egui::FontFamily::Monospace].contains(&UI_FONT.to_string())); + // Choosing again replaces it rather than adding a second entry. + let again = with_ui_font(fonts, font); + assert_eq!(again.families[&egui::FontFamily::Proportional].iter().filter(|n| *n == UI_FONT).count(), 1); + } + fn latin_font_bytes() -> Vec { let defaults = egui::FontDefinitions::default(); let name = &defaults.families[&egui::FontFamily::Proportional][0]; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 46106d4d7..3e58cd154 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -374,6 +374,8 @@ pub struct SolveApp { /// The language the installed font fallback chain is ordered for (`fonts::fallback_order`); /// changing `preferences.language` re-installs the fonts on the next frame. applied_fonts_language: String, + /// The interface font the fonts were last set up with (`Prefs::ui_font`). + applied_ui_font: String, } impl SolveApp { @@ -456,6 +458,7 @@ impl SolveApp { file_load: file_load::FileLoad::default(), docs: documents::Documents::default(), applied_fonts_language: "en".into(), + applied_ui_font: String::new(), } } @@ -1273,9 +1276,10 @@ impl SolveApp { pub fn ui(&mut self, ui: &mut egui::Ui) { expression_complete::begin_frame(ui.ctx()); let t0 = now_ms(); - if self.preferences.language != self.applied_fonts_language { + if self.preferences.language != self.applied_fonts_language || self.preferences.ui_font != self.applied_ui_font { self.applied_fonts_language.clone_from(&self.preferences.language); - crate::fonts::setup_fonts_for(ui.ctx(), &self.preferences.language); + self.applied_ui_font.clone_from(&self.preferences.ui_font); + crate::fonts::setup_fonts_for(ui.ctx(), &self.preferences.language, &self.preferences.ui_font); } let _language = crate::i18n::scope(&self.preferences.language); let mut report_input = None; diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index 9722bc369..b519acadd 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -292,6 +292,9 @@ pub struct Prefs { pub language: String, /// Interface scale (1 = 100 %). pub ui_scale: f32, + /// Interface font: an installed font family (or a font file), or empty for the built-in one + /// (#1290). Menus, dialogs and labels use it; glyphs it lacks fall back as before. + pub ui_font: String, /// Put the feature history above the parts browser in the left sidebar instead of along the /// bottom of the viewport. pub timeline_left: bool, @@ -398,6 +401,7 @@ impl Default for Prefs { theme: "dark".into(), language: "en".into(), ui_scale: 1.0, + ui_font: String::new(), timeline_left: false, timeline_left_height: 360.0, timeline_left_browser_collapsed: false, @@ -441,6 +445,8 @@ pub struct PrefsWindow { snapshot: Option, /// The up axis preference the view follows now (applied when it changes, and at startup). applied_up: Option, + /// The search text of the interface font list. + font_filter: String, } /// Open the dialog at a page. @@ -504,6 +510,54 @@ impl Snapshot { } } +/// The interface font (#1290): the built-in font first, then the installed families, with a +/// search box. The choice applies at once, like the other preferences. +fn ui_font_row(app: &mut SolveApp, ui: &mut egui::Ui) { + let builtin = app.tr_label("Built-in").to_string(); + let current = if app.preferences.ui_font.trim().is_empty() { builtin.clone() } else { app.preferences.ui_font.clone() }; + let families = crate::sketch_text::families(ui.ctx()); + let mut chosen: Option = None; + let combo = egui::ComboBox::from_id_salt("pref_ui_font") + .width(220.0) + .height(340.0) + .selected_text(current) + .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) + .show_ui(ui, |ui| { + let search = egui::TextEdit::singleline(&mut app.prefs_window.font_filter).hint_text(crate::i18n::tr("sketch_text.font_search")); + ui.add(search.desired_width(f32::INFINITY)); + let filter = app.prefs_window.font_filter.trim().to_lowercase(); + egui::ScrollArea::vertical().max_height(280.0).min_scrolled_height(280.0).auto_shrink([false, false]).show(ui, |ui| { + if builtin.to_lowercase().contains(&filter) && ui.selectable_label(app.preferences.ui_font.trim().is_empty(), &builtin).clicked() { + chosen = Some(String::new()); + } + match &families { + Some(list) => { + for family in list.iter().filter(|f| f.to_lowercase().contains(&filter)) { + let item = ui.selectable_label(app.preferences.ui_font == *family, family); + crate::scenario::publish_handle(&format!("prefs:font:{family}"), item.rect.center()); + if item.clicked() { + chosen = Some(family.clone()); + } + } + } + None => { + ui.label(crate::i18n::tr_label("Listing the installed fonts…")); + } + } + }); + }); + crate::scenario::publish_handle("prefs:ui_font", combo.response.rect.center()); + if let Some(name) = chosen { + if name.is_empty() || crate::fonts::ui_font(&name).is_some() { + app.preferences.ui_font = name; + } else { + app.set_status(format!("The font `{name}` could not be read"), true); + } + app.prefs_window.font_filter.clear(); + ui.close(); + } +} + /// Restore Defaults for one page. fn defaults(app: &mut SolveApp, page: usize) { let d = Prefs::default(); @@ -513,6 +567,7 @@ fn defaults(app: &mut SolveApp, page: usize) { p.theme = d.theme; p.language = d.language; p.ui_scale = d.ui_scale; + p.ui_font = d.ui_font; p.timeline_left = d.timeline_left; p.timeline_left_height = d.timeline_left_height; p.timeline_left_browser_collapsed = d.timeline_left_browser_collapsed; @@ -1004,6 +1059,11 @@ fn page(app: &mut SolveApp, ui: &mut egui::Ui, t: &Tokens) { ); crate::scenario::publish_rect("prefs:scale", scale.rect); ui.end_row(); + if !cfg!(target_arch = "wasm32") { + ui.label(app.tr_label("Interface font")); + ui_font_row(app, ui); + ui.end_row(); + } ui.label(app.tr("ui.feature_history")); let timeline_bottom = app.tr("ui.timeline_bottom").to_string(); let timeline_left = app.tr("ui.timeline_left_sidebar").to_string(); @@ -1429,6 +1489,9 @@ pub fn set(app: &mut SolveApp, p: &serde_json::Value) -> Result>().join(", "))); } + if new.ui_font != app.preferences.ui_font && !new.ui_font.trim().is_empty() && crate::fonts::ui_font(&new.ui_font).is_none() { + return Err(format!("`ui_font`: `{}` is not an installed font family or a readable font file", new.ui_font.trim())); + } 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()); } @@ -1458,6 +1521,26 @@ pub fn set(app: &mut SolveApp, p: &serde_json::Value) -> Result Option>> { +pub(crate) fn families(ctx: &egui::Context) -> Option>> { static FAMILIES: OnceLock>> = OnceLock::new(); static STARTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); if let Some(list) = FAMILIES.get() { diff --git a/docs/control-protocol.md b/docs/control-protocol.md index be49d189f..5c5a6e92b 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -132,7 +132,7 @@ unit regardless of the design, pass an expression with one: `"value": "50 mm"` o | `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`, `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`, `length_decimals`, `angle_decimals`, `theme` (`dark`, `light`, `system`), `language` (`en`, `ja`, `de`, `fr`, `ko`, `ru`, `uk`, `zh`; see [localization](localization.md)), `ui_scale`, `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 | 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`, `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`, `length_decimals`, `angle_decimals`, `theme` (`dark`, `light`, `system`), `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 | 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 | From a519f3cf748d3a0b409ee4e78cd42c7bf0d30006 Mon Sep 17 00:00:00 2001 From: CamWight <91156642+CamWight@users.noreply.github.com> Date: Thu, 15 Oct 2026 23:42:44 +0100 Subject: [PATCH 07/92] Web app: 3D mouse navigation through the Gamepad API (#1473) The web app reads a 3D mouse through the Gamepad API and drives the camera through navigation::device, so it follows each page's navigation capabilities (#1336). Co-authored-by: CamWight Co-Authored-By: Claude Sonnet 5.5 --- README.md | 4 +- apps/solidcraft-web/Cargo.toml | 2 +- apps/solidcraft-web/src/main.rs | 10 +- apps/solidcraft-web/src/space_mouse.rs | 351 +++++++++++++++++++++++++ apps/solidcraft/src/space_mouse.rs | 266 +++---------------- assets/locales/en.json | 2 +- assets/locales/fr.json | 2 +- assets/locales/ja.json | 2 +- assets/locales/ru.json | 2 +- assets/locales/uk.json | 2 +- assets/locales/zh.json | 2 +- crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/navigation.rs | 111 +++++++- crates/ui-egui/src/prefs.rs | 2 +- crates/ui-egui/src/space_mouse.rs | 351 +++++++++++++++++++++++++ crates/ui-egui/src/viewport.rs | 3 + docs/book/src/guide/getting-started.md | 50 ++++ docs/i18n_catalog_ja.md | 2 +- 18 files changed, 922 insertions(+), 243 deletions(-) create mode 100644 apps/solidcraft-web/src/space_mouse.rs create mode 100644 crates/ui-egui/src/space_mouse.rs diff --git a/README.md b/README.md index e99eef6df..54759d7a9 100644 --- a/README.md +++ b/README.md @@ -179,7 +179,9 @@ Windows builds: `cargo xwin build --release --target x86_64-pc-windows-msvc -p s On Windows and Linux, SolidCraft detects a connected 3Dconnexion SpaceNavigator or SpaceMouse through its multi-axis HID interface. 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 and a speed control for the 3D mouse. +page in Preferences has an on/off switch and a speed control 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)). On Linux 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 diff --git a/apps/solidcraft-web/Cargo.toml b/apps/solidcraft-web/Cargo.toml index db27ddafa..4c615fb40 100644 --- a/apps/solidcraft-web/Cargo.toml +++ b/apps/solidcraft-web/Cargo.toml @@ -29,5 +29,5 @@ web-sys = { version = "0.3", features = [ "Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "Location", "Navigator", "StorageManager", "FileSystemHandle", "FileSystemDirectoryHandle", "FileSystemFileHandle", "FileSystemGetFileOptions", "FileSystemWritableFileStream", "WritableStream", "File", "FileList", "Blob", "BlobPropertyBag", "Url", "HtmlAnchorElement", "HtmlInputElement", "Storage", - "BeforeUnloadEvent", "Event", "EventTarget", "Response", "MediaQueryList", + "BeforeUnloadEvent", "Event", "EventTarget", "Response", "MediaQueryList", "Gamepad", ] } diff --git a/apps/solidcraft-web/src/main.rs b/apps/solidcraft-web/src/main.rs index b9ff0d74f..555fe38c2 100644 --- a/apps/solidcraft-web/src/main.rs +++ b/apps/solidcraft-web/src/main.rs @@ -10,6 +10,8 @@ mod files; #[cfg(target_arch = "wasm32")] mod install; +#[cfg(any(target_arch = "wasm32", test))] +mod space_mouse; #[cfg(target_arch = "wasm32")] mod web { @@ -21,6 +23,7 @@ mod web { use wasm_bindgen::JsCast as _; use crate::files::{self, Files, Intent}; + use crate::space_mouse::SpaceMouse; const CANVAS_ID: &str = "solidcraft_canvas"; const LOADING_ID: &str = "solidcraft_loading"; @@ -67,6 +70,7 @@ mod web { /// On-demand CJK font: fetched only when a CJK language is selected. font: solidcraft_ui_egui::fonts::CjkFontLoader, font_result: FontLoadResult, + space_mouse: SpaceMouse, } impl Shell { @@ -382,11 +386,14 @@ mod web { fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { self.tick_font(ctx); self.app.logic(ctx); + self.space_mouse.logic(&mut self.app, ctx); self.files_tick(ctx); UNSAVED.with(|u| u.set(solidcraft_ui_egui::documents::any_dirty(&self.app))); } - fn raw_input_hook(&mut self, _ctx: &egui::Context, raw: &mut egui::RawInput) { + fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) { files::take_drops(&self.files, raw); + // Before the app's own hook, which adds the control channel's events. + self.space_mouse.raw_input_hook(ctx, self.app.preferences.space_mouse_enabled, raw); self.app.raw_input_hook(raw); } fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { @@ -516,6 +523,7 @@ mod web { recents_synced: false, font: Default::default(), font_result: Rc::new(std::cell::RefCell::new(None)), + space_mouse: SpaceMouse::default(), })) }), ) diff --git a/apps/solidcraft-web/src/space_mouse.rs b/apps/solidcraft-web/src/space_mouse.rs new file mode 100644 index 000000000..9707b89de --- /dev/null +++ b/apps/solidcraft-web/src/space_mouse.rs @@ -0,0 +1,351 @@ +//! The 3D mouse in the browser (#1336), through the Gamepad API. +//! +//! Chromium browsers list a 3Dconnexion device itself, with its six axes scaled to -1..1 from the +//! device's ±350. Firefox lists only joysticks and gamepads (a 3D mouse is a HID multi-axis +//! controller), but 3DxWare's virtual joystick carries the same six axes once 3DxWare's profile +//! for Firefox sends them there. Both come in the device's own order and signs, so the shared +//! 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}; + +/// 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. +const WHEEL_QUIET_S: f64 = 0.15; + +/// 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. +const LOGITECH: u16 = 0x046d; +const LOGITECH_3D_MICE: [u16; 11] = [0xc603, 0xc605, 0xc606, 0xc621, 0xc623, 0xc625, 0xc626, 0xc627, 0xc628, 0xc629, 0xc62b]; +/// 3Dconnexion's own vendor id. The browser lists only its 3D mice as gamepads: its mice, and the +/// mouse side of its receivers, are not gamepads. +const THREEDCONNEXION: u16 = 0x256f; +/// 3DxWare's virtual joystick. +const VIRTUAL_JOYSTICK: (u16, u16) = (0xbeef, 0x046d); + +/// What a gamepad the browser lists is, when it is a 3D mouse. A device is read before the +/// joystick: in a Chromium browser both are listed, and the joystick stays at rest. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum Source { + Device, + VirtualJoystick, +} + +/// The vendor and product ids in a gamepad's id: `Name (Vendor: 046d Product: c62b)` in Chromium +/// browsers, `046d-c62b-Name` in Firefox. +fn vendor_product(id: &str) -> Option<(u16, u16)> { + fn hex(digits: &str) -> Option { + if (1..=4).contains(&digits.len()) && digits.bytes().all(|b| b.is_ascii_hexdigit()) { u16::from_str_radix(digits, 16).ok() } else { None } + } + if let Some((_, ids)) = id.rsplit_once("Vendor: ") { + let (vendor, rest) = ids.split_once(" Product: ")?; + let product = rest.split(|c: char| !c.is_ascii_hexdigit()).next()?; + return Some((hex(vendor)?, hex(product)?)); + } + let mut parts = id.splitn(3, '-'); + let (vendor, product, _name) = (parts.next()?, parts.next()?, parts.next()?); + Some((hex(vendor)?, hex(product)?)) +} + +/// Whether a gamepad is a 3D mouse, from the id the browser gives it. +pub fn source(id: &str) -> Option { + match vendor_product(id)? { + VIRTUAL_JOYSTICK => Some(Source::VirtualJoystick), + (THREEDCONNEXION, _) => Some(Source::Device), + (LOGITECH, product) if LOGITECH_3D_MICE.contains(&product) => Some(Source::Device), + _ => None, + } +} + +/// The six axes in the device's raw units, from a gamepad's axes (-1..1). Fewer than six: not a +/// 3D mouse. A value that isn't a number reads as rest. +pub fn axes(values: &[f64]) -> Option { + let raw = |i: usize| values.get(i).map(|&v| if v.is_finite() { (v.clamp(-1.0, 1.0) * f64::from(FULL_SCALE)).round() as i16 } else { 0 }); + Some(Axes { translation: [raw(0)?, raw(1)?, raw(2)?], rotation: [raw(3)?, raw(4)?, raw(5)?] }) +} + +/// 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) +} + +/// 3DxWare turns the cap's motion into mouse-wheel turns in a browser (its zoom emulation). The +/// app reads the cap itself, so those are dropped: wheel events while the cap is moving and for +/// [`WHEEL_QUIET_S`] after. 3DxWare sends them only well past the dead zone (from about a third +/// of full deflection), never at rest, so a wheel turn with the cap at rest is the user's. +#[derive(Debug, Default)] +pub struct WheelGuard { + moved_at: Option, +} + +impl WheelGuard { + /// Takes this frame's reading (`now` in seconds) and drops the frame's wheel events if they + /// are 3DxWare's. + pub fn filter(&mut self, moving: bool, now: f64, events: &mut Vec) { + if moving { + self.moved_at = Some(now); + } + let recent = self.moved_at.is_some_and(|at| (0.0..=WHEEL_QUIET_S).contains(&(now - at))); + if recent { + events.retain(|e| !matches!(e, egui::Event::MouseWheel { .. } | egui::Event::Zoom(_))); + } + } +} + +#[cfg(target_arch = "wasm32")] +pub use browser::SpaceMouse; + +#[cfg(target_arch = "wasm32")] +mod browser { + use std::cell::Cell; + use std::rc::Rc; + + use solidcraft_ui_egui::SolveApp; + use solidcraft_ui_egui::space_mouse::{Axes, DriverMapping, navigate_frame}; + use wasm_bindgen::JsCast as _; + use wasm_bindgen::closure::Closure; + + use super::{WheelGuard, axes, choose, source}; + + /// 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 { + 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)?)) + })) + } + + /// Reads the 3D mouse once per frame and moves the view with it. + #[derive(Default)] + pub struct SpaceMouse { + axes: Axes, + /// The previous frame's time and the step since it (seconds). + last: Option, + seconds: f64, + wheel: WheelGuard, + /// Listening for gamepads (from the first frame with navigation on). + listening: bool, + /// The timer that wakes the app when the cap starts moving runs (from when a 3D mouse + /// is first listed). + waking: bool, + /// Navigation is on (the waker reads it). + enabled: Rc>, + } + + impl SpaceMouse { + /// At the start of a frame: reads the cap and drops 3DxWare's emulated wheel from the + /// frame's input, before the app sees it. + pub fn raw_input_hook(&mut self, ctx: &egui::Context, enabled: bool, raw: &mut egui::RawInput) { + let now = raw.time.unwrap_or_else(|| js_sys::Date::now() / 1000.0); + self.seconds = self.last.map_or(0.0, |last| now - last); + self.last = Some(now); + self.enabled.set(enabled); + self.axes = Axes::default(); + if !enabled { + return; + } + if !self.listening { + self.listening = true; + listen(ctx); + } + let reading = read(); + if reading.is_some() && !self.waking { + self.waking = wake(ctx, &self.enabled); + } + // 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); + } + + pub fn logic(&self, app: &mut SolveApp, ctx: &egui::Context) { + navigate_frame(app, ctx, DriverMapping::object_mode(), self.axes, self.seconds); + } + } + + /// A 3D mouse is listed only once it has been moved on the page: redraw then, so the frame + /// finds it without waiting for the pointer. + fn listen(ctx: &egui::Context) { + let Some(window) = web_sys::window() else { return }; + let ctx = ctx.clone(); + let on_connect = Closure::::new(move || ctx.request_repaint()); + let _ = window.add_event_listener_with_callback("gamepadconnected", on_connect.as_ref().unchecked_ref()); + // The listener lives as long as the page. + on_connect.forget(); + } + + /// 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 { + let Some(window) = web_sys::window() else { return false }; + let (ctx, enabled) = (ctx.clone(), Rc::clone(enabled)); + let tick = Closure::::new(move || { + if enabled.get() && read().is_some_and(Axes::moving) { + ctx.request_repaint(); + } + }); + let started = window.set_interval_with_callback_and_timeout_and_arguments_0(tick.as_ref().unchecked_ref(), WAKE_MS).is_ok(); + // The timer lives as long as the page. + tick.forget(); + started + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn wheel(dy: f32) -> egui::Event { + egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, dy), + modifiers: egui::Modifiers::NONE, + phase: egui::TouchPhase::Move, + } + } + + fn other() -> egui::Event { + egui::Event::PointerMoved(egui::pos2(1.0, 2.0)) + } + + #[test] + fn recognises_3d_mice_in_each_browsers_ids() { + // As Edge and Firefox list them (Windows 11, SpaceMouse Pro, 3DxWare 10). + assert_eq!(source("SpaceMouse Pro (Vendor: 046d Product: c62b)"), Some(Source::Device)); + assert_eq!(source("Unknown Gamepad (Vendor: beef Product: 046d)"), Some(Source::VirtualJoystick)); + assert_eq!(source("beef-046d-Unknown Gamepad"), Some(Source::VirtualJoystick)); + // 3Dconnexion's own vendor id, any product; the older devices under Logitech's. + assert_eq!(source("SpaceMouse Compact (Vendor: 256f Product: c635)"), Some(Source::Device)); + assert_eq!(source("256f-c652-3Dconnexion Universal Receiver"), Some(Source::Device)); + assert_eq!(source("46d-c626-SpaceNavigator"), Some(Source::Device)); + assert_eq!(source("SpaceNavigator (STANDARD GAMEPAD Vendor: 046d Product: c626)"), Some(Source::Device)); + for product in LOGITECH_3D_MICE { + assert_eq!(source(&format!("x (Vendor: 046d Product: {product:04x})")), Some(Source::Device)); + assert_eq!(source(&format!("046d-{product:04X}-x")), Some(Source::Device)); + } + } + + #[test] + fn gamepads_and_other_logitech_devices_are_not_3d_mice() { + for id in [ + "Logitech Dual Action (STANDARD GAMEPAD Vendor: 046d Product: c216)", + "046d-c21d-Logitech Gamepad F310", + "G29 Driving Force Racing Wheel (Vendor: 046d Product: c24f)", + "046d-c215-Logitech Extreme 3D", + "NuLOOQ navigator (Vendor: 046d Product: c640)", + "Xbox 360 Controller (XInput STANDARD GAMEPAD)", + "45e-28e-Xbox 360 Wired Controller", + "beef-046e-Unknown Gamepad", + "beee-046d-Unknown Gamepad", + "", + "-", + "--", + "256f-", + "256f-c635", + "Vendor: 256f", + "Vendor: 256f Product: ", + "x (Vendor: 256fff Product: c635)", + "x (Vendor: zz6f Product: c635)", + "12345-c635-x", + "256f--x", + "SpaceMouse Pro", + ] { + assert_eq!(source(id), None, "{id:?}"); + } + } + + #[test] + fn ids_never_panic() { + // Hostile and odd ids: multi-byte text around the markers, markers repeated or cut short. + for id in [ + "Vendor: é Product: ü", + "Vendor: Vendor: 256f Product: c635)", + "é-ü-ö", + "Ⅰ (Vendor: 256f Product: c6Ⅰ)", + "\u{0}-\u{0}-\u{0}", + "Vendor: 256f Product: c635 Vendor: ", + ] { + let _ = source(id); + } + let mut seed = 0x2545_f491_4f6c_dd1d_u64; + let alphabet: Vec = "0123456789abcdefABCDEF- ():VendorProductéⅠ\u{0}".chars().collect(); + for _ in 0..20_000 { + let len = (seed % 40) as usize; + let id: String = (0..len) + .map(|_| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + alphabet[(seed % alphabet.len() as u64) as usize] + }) + .collect(); + if let Some(Source::Device) = source(&id) { + let (vendor, product) = vendor_product(&id).expect("recognised ids have both"); + assert!(vendor == THREEDCONNEXION || (vendor == LOGITECH && LOGITECH_3D_MICE.contains(&product)), "{id:?}"); + } + } + } + + #[test] + fn gamepad_axes_are_the_devices_raw_units() { + // Full deflection is the desktop's 350, and the browser's scale keeps the device's steps. + let axes = axes(&[1.0, -1.0, 0.5, -0.5, 2.0 / 700.0, 0.0]).expect("six axes"); + assert_eq!(axes, Axes { translation: [350, -350, 175], rotation: [-175, 1, 0] }); + for raw in -350_i16..=350 { + let value = f64::from(raw) / 350.0; + assert_eq!(super::axes(&[value; 6]).map(|a| a.translation[0]), Some(raw)); + } + // Past full deflection is full deflection; anything that isn't a number is rest. + let hostile = super::axes(&[f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 1e300, -1e300, f64::MIN_POSITIVE]).expect("six axes"); + assert_eq!(hostile, Axes { translation: [0, 0, 0], rotation: [350, -350, 0] }); + // A gamepad with fewer than six axes is not a 3D mouse; extra axes are ignored. + assert_eq!(super::axes(&[1.0; 5]), None); + assert_eq!(super::axes(&[]), None); + assert_eq!(super::axes(&[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]), Some(Axes::default())); + } + + #[test] + fn a_device_is_read_before_the_virtual_joystick() { + let moving = Axes { translation: [100, 0, 0], rotation: [0; 3] }; + let other = Axes { translation: [0, 200, 0], rotation: [0; 3] }; + assert_eq!(choose([(Source::VirtualJoystick, other), (Source::Device, moving)]), Some(moving)); + assert_eq!(choose([(Source::Device, moving), (Source::VirtualJoystick, other)]), Some(moving)); + 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); + } + + #[test] + fn wheel_turns_are_dropped_while_the_cap_moves_and_kept_at_rest() { + let mut guard = WheelGuard::default(); + // At rest, the wheel is the user's. + let mut events = vec![wheel(100.0), other()]; + guard.filter(false, 10.0, &mut events); + assert_eq!(events.len(), 2); + // Moving: 3DxWare's wheel (and a pinch zoom) goes; everything else stays. + let mut events = vec![wheel(-100.0), other(), egui::Event::Zoom(1.1), wheel(100.0)]; + guard.filter(true, 11.0, &mut events); + assert_eq!(events, vec![other()]); + // Just after the cap stops, a queued one still goes. + let mut events = vec![wheel(100.0)]; + guard.filter(false, 11.0 + WHEEL_QUIET_S - 0.01, &mut events); + assert!(events.is_empty()); + // Later, the wheel is the user's again. + let mut events = vec![wheel(100.0)]; + guard.filter(false, 11.0 + WHEEL_QUIET_S + 0.01, &mut events); + assert_eq!(events.len(), 1); + // A clock that goes back never swallows the user's wheel. + let mut events = vec![wheel(100.0)]; + guard.filter(false, 5.0, &mut events); + assert_eq!(events.len(), 1); + let mut events = vec![wheel(100.0)]; + guard.filter(false, f64::NAN, &mut events); + assert_eq!(events.len(), 1); + } +} diff --git a/apps/solidcraft/src/space_mouse.rs b/apps/solidcraft/src/space_mouse.rs index 62734b6ec..d78734766 100644 --- a/apps/solidcraft/src/space_mouse.rs +++ b/apps/solidcraft/src/space_mouse.rs @@ -15,79 +15,18 @@ use hid_descriptor::Layout; use hidapi::{DeviceInfo, HidApi}; use quick_xml::Reader; use quick_xml::events::Event; -use solidcraft_engine::render::Camera; use solidcraft_ui_egui::SolveApp; +use solidcraft_ui_egui::space_mouse::{Axes, AxisRule, DriverMapping, navigate_frame}; const STALE_AFTER: Duration = Duration::from_millis(150); const RETRY_AFTER: Duration = Duration::from_secs(2); const MAX_PROFILE_BYTES: u64 = 1024 * 1024; -#[derive(Clone, Copy, Debug, Default, PartialEq)] -struct Axes { - translation: [i16; 3], - rotation: [i16; 3], -} - -#[derive(Clone, Copy, Debug, PartialEq)] -struct AxisRule { - output: usize, - enabled: bool, - reversed: bool, - scale: f64, -} - -#[derive(Clone, Copy, Debug, PartialEq)] -struct DriverMapping { - axes: [AxisRule; 6], - overall_scale: f64, -} - -impl Default for DriverMapping { - fn default() -> Self { - Self { axes: std::array::from_fn(|output| AxisRule { output, enabled: true, reversed: false, scale: 1.0 }), overall_scale: 1.0 } - } -} - -impl DriverMapping { - /// The mapping used when no 3DxWare profile is found. On Linux there is no 3DxWare, so it is - /// what the driver applies by default in object mode (#1172): the physical Ry and Rz swapped - /// and reversed, so a tilt left/right rolls and a twist spins. Elsewhere the driver writes a - /// profile, and the raw axes are used until it does. - fn without_profile() -> Self { - let mut mapping = Self::default(); - if cfg!(target_os = "linux") { - mapping.axes[4] = AxisRule { output: 5, enabled: true, reversed: true, scale: 1.0 }; - mapping.axes[5] = AxisRule { output: 4, enabled: true, reversed: true, scale: 1.0 }; - } - mapping - } -} - -#[derive(Clone, Copy, Debug, Default, PartialEq)] -struct Motion { - translation: [f64; 3], - rotation: [f64; 3], -} - -impl DriverMapping { - fn apply(self, axes: Axes) -> Motion { - let raw = [ - normalized(axes.translation[0]), - normalized(axes.translation[1]), - normalized(axes.translation[2]), - normalized(axes.rotation[0]), - normalized(axes.rotation[1]), - normalized(axes.rotation[2]), - ]; - let mut logical = [0.0; 6]; - for (input, rule) in self.axes.iter().enumerate() { - if rule.enabled { - let sign = if rule.reversed { -1.0 } else { 1.0 }; - logical[rule.output] = raw[input] * sign * rule.scale * self.overall_scale; - } - } - Motion { translation: [logical[0], logical[1], logical[2]], rotation: [logical[3], logical[4], logical[5]] } - } +/// The mapping used when no 3DxWare profile is found. On Linux there is no 3DxWare, so it is what +/// the driver applies by default in object mode (#1172). Elsewhere the driver writes a profile, +/// and the raw axes are used until it does. +fn without_profile() -> DriverMapping { + if cfg!(target_os = "linux") { DriverMapping::object_mode() } else { DriverMapping::default() } } #[derive(Clone, Copy, Debug, Default)] @@ -392,87 +331,38 @@ impl SpaceMouse { if let Err(error) = std::thread::Builder::new().name("solidcraft-3d-mouse".into()).spawn(move || reader(worker_ctx, worker_state)) { log::warn!("3D mouse: reader could not start: {error}"); } - Self { - shared, - last_frame: now, - driver_mapping: load_driver_mapping().unwrap_or_else(DriverMapping::without_profile), - mapping_checked_at: now, - } + Self { shared, last_frame: now, driver_mapping: load_driver_mapping().unwrap_or_else(without_profile), mapping_checked_at: now } } pub fn tick(&mut self, app: &mut SolveApp, ctx: &Context) { let now = Instant::now(); - let seconds = now.duration_since(self.last_frame).as_secs_f64().min(0.05); + let seconds = now.duration_since(self.last_frame).as_secs_f64(); self.last_frame = now; if now.duration_since(self.mapping_checked_at) >= RETRY_AFTER { - let updated = load_driver_mapping().unwrap_or_else(DriverMapping::without_profile); + let updated = load_driver_mapping().unwrap_or_else(without_profile); if updated != self.driver_mapping { log::info!("3D mouse: applying updated 3DxWare axis profile"); self.driver_mapping = updated; } self.mapping_checked_at = now; } - if !app.preferences.space_mouse_enabled || app.home.open { - return; - } let axes = match self.shared.lock() { Ok(reading) => reading.current(now), Err(_) => return, }; - if axes == Axes::default() { - return; - } - let speed = f64::from(app.preferences.space_mouse_speed); - if !speed.is_finite() { - return; - } - app.begin_external_navigation(); - let height = app.viewport.rect.map_or(600.0, |rect| f64::from(rect.height().max(1.0))); - navigate( - &mut app.cam, - self.driver_mapping.apply(axes), - seconds * speed.clamp(0.1, 5.0), - height, - app.session.active_sketch.is_some(), - app.preferences.zoom_reverse, - ); - ctx.request_repaint_after(Duration::from_millis(16)); - } -} - -/// A small dead zone avoids drift at rest. A full cap deflection takes roughly one viewport -/// per second to pan and about two radians per second to turn, independent of frame rate. -fn normalized(value: i16) -> f64 { - let v = f64::from(value); - if v.abs() <= 20.0 { 0.0 } else { v.signum() * ((v.abs() - 20.0) / 330.0).min(1.0) } -} - -fn navigate(cam: &mut Camera, motion: Motion, seconds: f64, height: f64, sketch: bool, reverse_zoom: bool) { - if !(seconds > 0.0) || !seconds.is_finite() { - return; - } - let [x, y, z] = motion.translation; - let [rx, ry, rz] = motion.rotation; - // Logical 3DxWare coordinates are X = left/right, Y = zoom and Z = up/down. The user's - // profile above can swap the physical forward/back and up/down axes before they reach here. - cam.pan(x * height * 0.6 * seconds, z * height * 0.6 * seconds, height); - let zoom_sign = if reverse_zoom { -1.0 } else { 1.0 }; - cam.zoom_at((-y * zoom_sign * 1.5 * seconds).exp(), None); - if !sketch { - // These are logical 3DxWare coordinates after the profile mapping above: Rx is Tilt, - // Ry is Roll and Rz is Spin. The KMJ profile swaps physical Ry/Rz for the selected - // navigation mode, so swapping them again here would make Roll behave like Spin. - cam.orbit(ry * 250.0 * seconds, rx * 250.0 * seconds); - cam.roll_by(rz * 2.0 * seconds); + navigate_frame(app, ctx, self.driver_mapping, axes, seconds); } } #[cfg(test)] mod tests { use super::*; + use solidcraft_ui_egui::space_mouse::{DeviceMotion, Motion}; - fn raw(axes: Axes) -> Motion { - DriverMapping::default().apply(axes) + /// The logical axes a reading reaches. Logical Rz rolls the view and logical Ry turns it about + /// its vertical (`navigation::device_camera` in solidcraft-ui-egui, tested there). + fn rotation(mapping: DriverMapping, rotation: [i16; 3]) -> [f64; 3] { + mapping.apply(Axes { translation: [0; 3], rotation }).rotation } #[test] @@ -519,69 +409,6 @@ mod tests { assert_eq!(reading.current(now), Axes { translation: [1, 2, 3], rotation: [4, 5, 6] }); } - #[test] - fn six_axes_move_the_camera_and_sketches_keep_their_orientation() { - let mut cam = Camera::default(); - let before = cam; - navigate(&mut cam, raw(Axes { translation: [350, 350, 350], rotation: [350, 350, 350] }), 0.02, 600.0, false, false); - assert_ne!(cam.target, before.target); - assert!(cam.distance < before.distance); - assert_ne!(cam.yaw, before.yaw); - assert_ne!(cam.pitch, before.pitch); - assert_ne!(cam.roll, before.roll); - let orientation = (cam.yaw, cam.pitch, cam.roll); - navigate(&mut cam, raw(Axes { translation: [350, 0, 0], rotation: [350, 350, 350] }), 0.02, 600.0, true, false); - assert_eq!((cam.yaw, cam.pitch, cam.roll), orientation); - assert!(cam.is_valid()); - } - - #[test] - fn individual_axes_have_physical_spacemouse_meaning() { - let before = Camera::default(); - - let mut slide = before; - navigate(&mut slide, raw(Axes { translation: [350, 0, 0], rotation: [0; 3] }), 0.02, 600.0, false, false); - assert_ne!(slide.target, before.target); - assert_eq!(slide.distance, before.distance); - - let mut push = before; - navigate(&mut push, raw(Axes { translation: [0, 350, 0], rotation: [0; 3] }), 0.02, 600.0, false, false); - assert_eq!(push.target, before.target); - assert!(push.distance < before.distance); - - let mut lift = before; - navigate(&mut lift, raw(Axes { translation: [0, 0, 350], rotation: [0; 3] }), 0.02, 600.0, false, false); - assert_ne!(lift.target, before.target); - assert_eq!(lift.distance, before.distance); - - let mut tilt = before; - navigate(&mut tilt, raw(Axes { translation: [0; 3], rotation: [350, 0, 0] }), 0.02, 600.0, false, false); - assert_eq!((tilt.yaw, tilt.roll), (before.yaw, before.roll)); - assert_ne!(tilt.pitch, before.pitch); - - let mut roll = before; - navigate(&mut roll, raw(Axes { translation: [0; 3], rotation: [0, 350, 0] }), 0.02, 600.0, false, false); - assert_eq!((roll.pitch, roll.roll), (before.pitch, before.roll)); - assert_ne!(roll.yaw, before.yaw); - - let mut twist = before; - navigate(&mut twist, raw(Axes { translation: [0; 3], rotation: [0, 0, 350] }), 0.02, 600.0, false, false); - assert_eq!((twist.yaw, twist.pitch), (before.yaw, before.pitch)); - assert_ne!(twist.roll, before.roll); - } - - #[test] - fn reverse_zoom_setting_applies_to_spacemouse() { - let before = Camera::default(); - let motion = raw(Axes { translation: [0, 350, 0], rotation: [0; 3] }); - let mut normal = before; - navigate(&mut normal, motion, 0.02, 600.0, false, false); - let mut reversed = before; - navigate(&mut reversed, motion, 0.02, 600.0, false, true); - assert!(normal.distance < before.distance); - assert!(reversed.distance > before.distance); - } - #[test] fn applies_3dxware_axis_swaps_and_reversals() { let profile = br#" @@ -615,38 +442,17 @@ mod tests { "#; let profile = parse_driver_mapping(object_mode).expect("valid 3DxWare profile"); if cfg!(target_os = "linux") { - assert_eq!(DriverMapping::without_profile(), profile); + assert_eq!(without_profile(), profile); // Tilting the cap rolls the view and twisting it spins it, as with the driver. - let before = Camera::default(); - let mut tilt = before; - navigate( - &mut tilt, - DriverMapping::without_profile().apply(Axes { translation: [0; 3], rotation: [0, 350, 0] }), - 0.02, - 600.0, - false, - false, - ); - assert_eq!((tilt.yaw, tilt.pitch), (before.yaw, before.pitch)); - assert_ne!(tilt.roll, before.roll); - let mut twist = before; - navigate( - &mut twist, - DriverMapping::without_profile().apply(Axes { translation: [0; 3], rotation: [0, 0, 350] }), - 0.02, - 600.0, - false, - false, - ); - assert_ne!(twist.yaw, before.yaw); - assert_eq!(twist.roll, before.roll); + assert_eq!(rotation(without_profile(), [0, 350, 0]), [0.0, 0.0, -1.0]); + assert_eq!(rotation(without_profile(), [0, 0, 350]), [0.0, -1.0, 0.0]); } else { - assert_eq!(DriverMapping::without_profile(), DriverMapping::default()); + assert_eq!(without_profile(), DriverMapping::default()); } } #[test] - fn mapped_roll_and_spin_reach_distinct_camera_rotations() { + fn mapped_roll_and_spin_reach_the_roll_and_turn_axes() { let profile = br#" trueHIDMultiAxis_RyHIDMultiAxis_Rzfalse @@ -654,16 +460,28 @@ mod tests { "#; let mapping = parse_driver_mapping(profile).expect("valid 3DxWare profile"); - let before = Camera::default(); + // The physical roll reaches the roll axis only, and the physical spin the turn only. + assert_eq!(rotation(mapping, [0, 350, 0]), [0.0, 0.0, 1.0]); + assert_eq!(rotation(mapping, [0, 0, 350]), [0.0, -1.0, 0.0]); + } - let mut physical_roll = before; - navigate(&mut physical_roll, mapping.apply(Axes { translation: [0; 3], rotation: [0, 350, 0] }), 0.02, 600.0, false, false); - assert_eq!((physical_roll.yaw, physical_roll.pitch), (before.yaw, before.pitch)); - assert_ne!(physical_roll.roll, before.roll); - - let mut physical_spin = before; - navigate(&mut physical_spin, mapping.apply(Axes { translation: [0; 3], rotation: [0, 0, 350] }), 0.02, 600.0, false, false); - assert_ne!(physical_spin.yaw, before.yaw); - assert_eq!((physical_spin.pitch, physical_spin.roll), (before.pitch, before.roll)); + #[test] + fn each_frame_hands_the_view_its_motion_through_the_drivers_mapping() { + // The reader's latest tilt, and a profile that makes tilt roll: the frame's motion rolls. + let now = Instant::now(); + let mut reading = Reading::new(now); + reading.axes.rotation = [0, 350, 0]; + let mut mouse = SpaceMouse { + shared: Arc::new(Mutex::new(reading)), + last_frame: now - Duration::from_millis(20), + driver_mapping: DriverMapping::object_mode(), + mapping_checked_at: now, + }; + let mut app = SolveApp::new(solidcraft_engine::Session::default(), solidcraft_ui_egui::Services::default()); + app.home.open = false; + mouse.tick(&mut app, &Context::default()); + 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/assets/locales/en.json b/assets/locales/en.json index 2b8345bc1..12317a2cc 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -344,7 +344,7 @@ "sketch.make_selection": "Convert the selection to {linetype}", "ui.1_degree_of_freedom": "1 degree of freedom", "ui.3d_mouse_speed": "3D mouse speed", - "ui.3d_mouse_windows": "3D mouse (Windows)", + "ui.3d_mouse_windows": "3D mouse", "ui.3d_sketch": "3D Sketch", "ui.about": "About", "ui.activate": "Activate", diff --git a/assets/locales/fr.json b/assets/locales/fr.json index 0b185008c..6aabcff45 100644 --- a/assets/locales/fr.json +++ b/assets/locales/fr.json @@ -344,7 +344,7 @@ "sketch.make_selection": "Convertir la sélection en {linetype}", "ui.1_degree_of_freedom": "1 degré de liberté", "ui.3d_mouse_speed": "Vitesse de la souris 3D", - "ui.3d_mouse_windows": "Souris 3D (Windows)", + "ui.3d_mouse_windows": "Souris 3D", "ui.3d_sketch": "Esquisse 3D", "ui.about": "À propos", "ui.activate": "Activer", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 5f718d417..b88765b29 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -344,7 +344,7 @@ "sketch.make_selection": "選択を{linetype}にする", "ui.1_degree_of_freedom": "自由度 1", "ui.3d_mouse_speed": "3D マウス速度", - "ui.3d_mouse_windows": "3D マウス (Windows)", + "ui.3d_mouse_windows": "3D マウス", "ui.3d_sketch": "3D スケッチ", "ui.about": "SolidCraft について", "ui.activate": "アクティブ化", diff --git a/assets/locales/ru.json b/assets/locales/ru.json index 15477724e..1aa220814 100644 --- a/assets/locales/ru.json +++ b/assets/locales/ru.json @@ -329,7 +329,7 @@ "sketch.make_selection": "Преобразовать выделение в {linetype}", "ui.1_degree_of_freedom": "1 степень свободы", "ui.3d_mouse_speed": "Скорость 3D-мыши", - "ui.3d_mouse_windows": "3D-мышь (Windows)", + "ui.3d_mouse_windows": "3D-мышь", "ui.3d_sketch": "3D-эскиз", "ui.about": "О программе", "ui.activate": "Активировать", diff --git a/assets/locales/uk.json b/assets/locales/uk.json index a5ea36744..2ffc11cdf 100644 --- a/assets/locales/uk.json +++ b/assets/locales/uk.json @@ -308,7 +308,7 @@ "sketch.make_selection": "Перетворити виділене на {linetype}", "ui.1_degree_of_freedom": "1 ступінь вільності", "ui.3d_mouse_speed": "Швидкість 3D-миші", - "ui.3d_mouse_windows": "3D-миша (Windows)", + "ui.3d_mouse_windows": "3D-миша", "ui.3d_sketch": "3D-ескіз", "ui.about": "Про програму", "ui.activate": "Активувати", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index 2168aa339..8a8432d56 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -344,7 +344,7 @@ "sketch.make_selection": "将选择转换为 {linetype}", "ui.1_degree_of_freedom": "1 个自由度", "ui.3d_mouse_speed": "3D 鼠标速度", - "ui.3d_mouse_windows": "3D 鼠标(Windows)", + "ui.3d_mouse_windows": "3D 鼠标", "ui.3d_sketch": "3D 草图", "ui.about": "关于", "ui.activate": "激活", diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 3e58cd154..05366d1c1 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -149,6 +149,7 @@ pub mod sketch_tools; pub mod smart_extrude; #[cfg(test)] mod smart_extrude_ui_tests; +pub mod space_mouse; pub mod stand_up; #[cfg(test)] mod sweep_dialog_tests; diff --git a/crates/ui-egui/src/navigation.rs b/crates/ui-egui/src/navigation.rs index 654ed752c..866a89c40 100644 --- a/crates/ui-egui/src/navigation.rs +++ b/crates/ui-egui/src/navigation.rs @@ -5,9 +5,10 @@ //! One entry point, [`handle`], reads a frame's pointer, wheel, trackpad and modifier input over a //! view and moves `app.cam` the way Preferences › Navigation says: the navigation preset (Fusion, //! SolidWorks, Blender, Touchpad…), Orbit around, zoom to the cursor, the middle double-click and -//! orbit snapping. The SpaceMouse, view keys and the navigators act on `app.cam` independently of -//! the page. New canvases must call `navigation::handle` rather than reading drags or the wheel -//! themselves; `hand_rolled_camera_input_is_rejected` fails when they do. +//! orbit snapping. The 3D mouse's motion goes through [`device`] too, with the page's +//! [`NavCaps`]. The view keys and the navigators act on `app.cam` independently of the page. New +//! canvases must call `navigation::handle` rather than reading drags or the wheel themselves; +//! `hand_rolled_camera_input_is_rejected` fails when they do. use egui::{Pos2, Rect, pos2, vec2}; use serde_json::json; @@ -16,6 +17,7 @@ use solidcraft_engine::render::Camera; use crate::SolveApp; use crate::prefs::{OrbitAround, pivot_under}; +use crate::space_mouse::Motion; use crate::viewport::{Hit, NavMode, axis_rect, nearest_quarter_turn, pick, pick_cached, projection}; /// What a page's camera may do. @@ -244,6 +246,8 @@ pub(crate) fn handle(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect, resp: &e // Ctrl or Alt held: drawing and dragging don't snap. crate::drag_snap::set_suppressed(mods.ctrl || mods.alt || mods.command); 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); // ---- navigation ---- let trackpad_pan = app.preferences.trackpad_pans(); @@ -464,6 +468,40 @@ pub(crate) fn handle(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect, resp: &e CameraInput { hover, scroll, mods, middle, secondary_down, primary_down, primary_pressed, delta, inside, axes, pinch, pan, primary_nav, mode } } +/// The 3D mouse's motion this frame (#1336), on a page `rect` whose camera may do `caps`: the cap +/// pans and zooms every page, and turns the view only where the page may orbit and no sketch is +/// being edited (a sketch keeps its view square to it). [`handle`] calls it for its page; the 3D +/// mouse only reads the device and queues the motion ([`crate::space_mouse::navigate_frame`]). +pub(crate) fn device(app: &mut SolveApp, rect: Rect, caps: NavCaps) { + let Some(queued) = app.viewport.device_motion.take() else { return }; + let turn = caps.orbit && app.session.active_sketch.is_none(); + let height = f64::from(rect.height().max(1.0)); + device_camera(&mut app.cam, queued.motion, queued.seconds, height, turn, app.preferences.zoom_reverse); +} + +/// `seconds` of 3D mouse `motion` on `cam`, in a view `height` points tall. A full deflection +/// pans about 0.6 of the view's height a second and turns about two radians a second, whatever +/// the frame rate. With `turn` off the view keeps its orientation. +pub(crate) fn device_camera(cam: &mut Camera, motion: Motion, seconds: f64, height: f64, turn: bool, reverse_zoom: bool) { + if !(seconds > 0.0) || !seconds.is_finite() { + return; + } + let [x, y, z] = motion.translation; + let [rx, ry, rz] = motion.rotation; + // Logical 3DxWare coordinates are X = left/right, Y = zoom and Z = up/down. The user's + // profile can swap the physical forward/back and up/down axes before they reach here. + cam.pan(x * height * 0.6 * seconds, z * height * 0.6 * seconds, height); + let zoom_sign = if reverse_zoom { -1.0 } else { 1.0 }; + cam.zoom_at((-y * zoom_sign * 1.5 * seconds).exp(), None); + if turn { + // These are logical 3DxWare coordinates after the profile mapping: Rx is Tilt, Ry is + // Roll and Rz is Spin. The KMJ profile swaps physical Ry/Rz for the selected navigation + // mode, so swapping them again here would make Roll behave like Spin. + cam.orbit(ry * 250.0 * seconds, rx * 250.0 * seconds); + cam.roll_by(rz * 2.0 * seconds); + } +} + /// Six principal views, twelve edge diagonals and eight isometric corner directions. pub(crate) fn snap_directions() -> impl Iterator { [-1.0, 0.0, 1.0].into_iter().flat_map(|x| { @@ -637,15 +675,15 @@ pub(crate) fn orbit_about(app: &mut SolveApp, rect: egui::Rect, dx: f64, dy: f64 mod tests { /// Every page with a camera navigates through [`super::handle`] (#1454). A page that reads /// the wheel or moves the view camera itself would drift from the user's navigation settings, - /// so outside this module (and the SpaceMouse driver, a device rather than a page) the camera - /// may only be moved through it, the view commands or the navigators. + /// so outside this module the camera may only be moved through it, the view commands or the + /// navigators. The 3D mouse in both apps hands its motion to [`super::device`]. #[test] fn hand_rolled_camera_input_is_rejected() { const PATTERNS: [&str; 7] = ["smooth_scroll_delta", "raw_scroll_delta", "zoom_delta()", "cam.orbit(", "cam.pan(", "cam.zoom_at(", "cam.roll_by("]; let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")); - let dirs = [root.join("src"), root.join("../../apps/solidcraft/src")]; - let allowed = ["navigation.rs", "space_mouse.rs"]; + let dirs = [root.join("src"), root.join("../../apps/solidcraft/src"), root.join("../../apps/solidcraft-web/src")]; + let allowed = ["navigation.rs"]; let mut offenders = Vec::new(); let mut scanned = 0; let mut stack: Vec = dirs.iter().filter(|d| d.is_dir()).cloned().collect(); @@ -661,7 +699,8 @@ mod tests { continue; } scanned += 1; - let text = std::fs::read_to_string(&path).unwrap(); + // A Windows checkout's CRLF lines, read as written, so the split below finds the tests. + let text = std::fs::read_to_string(&path).unwrap().replace("\r\n", "\n"); // In-file unit tests set cameras up directly; only the code above them counts. let code = text.split("\n#[cfg(test)]\nmod ").next().unwrap_or_default(); for (n, line) in code.lines().enumerate() { @@ -739,4 +778,60 @@ mod tests { assert_ne!(app.cam.distance, before.distance, "{preset}: the wheel zooms"); } } + + /// The 3D mouse pans and zooms a flat page with the cap and never turns it, as the mouse + /// does there; pages that orbit turn with it (#1336). + #[test] + fn the_3d_mouse_pans_and_zooms_a_flat_page_but_never_turns_it() { + use crate::space_mouse::{DeviceMotion, Motion}; + let every_axis = DeviceMotion { motion: Motion { translation: [1.0, 1.0, 1.0], rotation: [1.0, 1.0, 1.0] }, seconds: 0.05 }; + let flat = super::NavCaps { orbit: false, pick: false }; + for (caps, turns) in [(flat, false), (super::NavCaps::MODEL, true), (super::NavCaps::RENDER, true)] { + let mut s = solidcraft_engine::Session::default(); + s.execute("solid.box", &serde_json::json!({"length":40,"width":30,"height":20})).unwrap(); + let mut app = crate::SolveApp::new(s, crate::Services::default()); + let ctx = egui::Context::default(); + let before = app.cam; + app.viewport.device_motion = Some(every_axis); + let raw = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))), + time: Some(0.0), + focused: true, + ..Default::default() + }; + let mut out = ctx.run_ui(raw, |ui| { + let rect = ui.max_rect(); + app.viewport.rect = Some(rect); + let resp = ui.interact(rect, ui.id().with("page"), egui::Sense::click_and_drag()); + super::handle(&mut app, ui, rect, &resp, caps); + }); + out.textures_delta.clear(); + assert!(app.viewport.device_motion.is_none(), "{caps:?}: the page takes the motion"); + assert_ne!(app.cam.target, before.target, "{caps:?}: the cap pans"); + assert!(app.cam.distance < before.distance, "{caps:?}: the cap zooms"); + let turned = (app.cam.yaw, app.cam.pitch, app.cam.roll) != (before.yaw, before.pitch, before.roll); + assert_eq!(turned, turns, "{caps:?}: the cap turns the view only where the page orbits"); + } + } + + /// While a sketch is edited the cap pans and zooms, and the view stays square to the sketch. + #[test] + fn the_3d_mouse_never_turns_a_sketch_being_edited() { + use crate::space_mouse::{DeviceMotion, Motion}; + let mut s = solidcraft_engine::Session::default(); + s.execute("sketch.create", &serde_json::json!({"plane": "XY"})).unwrap(); + let mut app = crate::SolveApp::new(s, crate::Services::default()); + assert!(app.session.active_sketch.is_some()); + let before = app.cam; + app.viewport.device_motion = Some(DeviceMotion { motion: Motion { translation: [1.0; 3], rotation: [1.0; 3] }, seconds: 0.05 }); + let page = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0)); + super::device(&mut app, page, super::NavCaps::MODEL); + assert_eq!((app.cam.yaw, app.cam.pitch, app.cam.roll), (before.yaw, before.pitch, before.roll)); + assert_ne!(app.cam.target, before.target); + assert!(app.cam.distance < before.distance); + // Nothing queued, nothing moves. + let still = app.cam; + super::device(&mut app, page, super::NavCaps::MODEL); + assert_eq!(app.cam, still); + } } diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index b519acadd..6498e5491 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -1188,7 +1188,7 @@ fn page(app: &mut SolveApp, ui: &mut egui::Ui, t: &Tokens) { egui::Slider::new(&mut app.preferences.look_at_speed, 0.5..=3.0).step_by(0.25).custom_formatter(|v, _| format!("{v:.2}×")), ); ui.end_row(); - ui.label(crate::i18n::tr_label("3D mouse (Windows)")); + ui.label(crate::i18n::tr_label("3D mouse")); ui.checkbox(&mut app.preferences.space_mouse_enabled, crate::i18n::tr_label("Navigate with SpaceNavigator / SpaceMouse")); ui.end_row(); ui.label(crate::i18n::tr_label("3D mouse speed")); diff --git a/crates/ui-egui/src/space_mouse.rs b/crates/ui-egui/src/space_mouse.rs new file mode 100644 index 000000000..ff373fa38 --- /dev/null +++ b/crates/ui-egui/src/space_mouse.rs @@ -0,0 +1,351 @@ +//! 3D mouse input, shared by the desktop and web apps. Each app reads the device its own way (the +//! desktop through HID, the web app through the browser's Gamepad API) and hands its six raw axes +//! to [`navigate_frame`] once per frame. This module maps them, applies the dead zone and drops +//! 3DxWare's emulated wheel; the page showing the camera moves it (`navigation::device`), so the +//! cap does what that page's camera may do. + +use std::time::Duration; + +use crate::SolveApp; + +/// What a 3Dconnexion device reports at full deflection, in raw units, on every axis. +pub const FULL_SCALE: i16 = 350; + +/// One reading of the six axes in the device's raw units: X right, Y towards the user, Z down, +/// and the rotations about those axes (right-handed). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Axes { + pub translation: [i16; 3], + pub rotation: [i16; 3], +} + +impl Axes { + /// Some axis is past the dead zone: the cap is being moved. + pub fn moving(self) -> bool { + self.translation.iter().chain(&self.rotation).any(|&v| normalized(v) != 0.0) + } +} + +/// Where one physical axis goes: its logical axis, and how. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct AxisRule { + pub output: usize, + pub enabled: bool, + pub reversed: bool, + pub scale: f64, +} + +/// The physical-to-logical axis mapping 3DxWare applies (the desktop reads it from the driver's +/// profile; direct reads bypass the driver). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct DriverMapping { + pub axes: [AxisRule; 6], + pub overall_scale: f64, +} + +impl Default for DriverMapping { + fn default() -> Self { + Self { axes: std::array::from_fn(|output| AxisRule { output, enabled: true, reversed: false, scale: 1.0 }), overall_scale: 1.0 } + } +} + +impl DriverMapping { + /// What 3DxWare applies by default in object mode (#1172): the physical Ry and Rz swapped and + /// reversed, so a tilt left/right rolls and a twist spins. + pub fn object_mode() -> Self { + let mut mapping = Self::default(); + mapping.axes[4] = AxisRule { output: 5, enabled: true, reversed: true, scale: 1.0 }; + mapping.axes[5] = AxisRule { output: 4, enabled: true, reversed: true, scale: 1.0 }; + mapping + } + + pub fn apply(self, axes: Axes) -> Motion { + let raw = [ + normalized(axes.translation[0]), + normalized(axes.translation[1]), + normalized(axes.translation[2]), + normalized(axes.rotation[0]), + normalized(axes.rotation[1]), + normalized(axes.rotation[2]), + ]; + let mut logical = [0.0; 6]; + for (input, rule) in self.axes.iter().enumerate() { + if rule.enabled { + let sign = if rule.reversed { -1.0 } else { 1.0 }; + if let Some(slot) = logical.get_mut(rule.output) { + *slot = raw[input] * sign * rule.scale * self.overall_scale; + } + } + } + Motion { translation: [logical[0], logical[1], logical[2]], rotation: [logical[3], logical[4], logical[5]] } + } +} + +/// The logical axes after the mapping, each in -1..1. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Motion { + pub translation: [f64; 3], + pub rotation: [f64; 3], +} + +/// One frame of 3D mouse motion, waiting for the page that shows the camera: the logical axes, +/// and how many seconds of motion they stand for (the frame's time, scaled by the speed). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct DeviceMotion { + pub motion: Motion, + pub seconds: f64, +} + +/// 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. +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() { + return false; + } + let speed = f64::from(app.preferences.space_mouse_speed); + if !speed.is_finite() { + return false; + } + app.begin_external_navigation(); + // A long gap (the first frame after a pause) moves as far as a 50 ms one. + let step = if seconds.is_finite() { seconds.min(0.05) } else { 0.0 }; + app.viewport.device_motion = Some(DeviceMotion { motion: mapping.apply(axes), seconds: step * speed.clamp(0.1, 5.0) }); + ctx.request_repaint_after(Duration::from_millis(16)); + true +} + +/// A small dead zone avoids drift at rest. A full cap deflection takes roughly one viewport +/// per second to pan and about two radians per second to turn, independent of frame rate. +fn normalized(value: i16) -> f64 { + let v = f64::from(value); + if v.abs() <= 20.0 { 0.0 } else { v.signum() * ((v.abs() - 20.0) / 330.0).min(1.0) } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Services; + use solidcraft_engine::Session; + use solidcraft_engine::render::Camera; + + /// The camera math the page applies the motion with (`navigation::device`): `sketch` keeps + /// the orientation, as editing a sketch does. + fn navigate(cam: &mut Camera, motion: Motion, seconds: f64, height: f64, sketch: bool, reverse_zoom: bool) { + crate::navigation::device_camera(cam, motion, seconds, height, !sketch, reverse_zoom); + } + + /// 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); + let page = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0)); + crate::navigation::device(app, page, crate::navigation::NavCaps::MODEL); + handed + } + + fn raw(axes: Axes) -> Motion { + DriverMapping::default().apply(axes) + } + + fn app() -> SolveApp { + let mut app = SolveApp::new(Session::default(), Services::default()); + app.home.open = false; + app + } + + const PUSH: Axes = Axes { translation: [0, 350, 0], rotation: [0; 3] }; + + #[test] + fn six_axes_move_the_camera_and_sketches_keep_their_orientation() { + let mut cam = Camera::default(); + let before = cam; + navigate(&mut cam, raw(Axes { translation: [350, 350, 350], rotation: [350, 350, 350] }), 0.02, 600.0, false, false); + assert_ne!(cam.target, before.target); + assert!(cam.distance < before.distance); + assert_ne!(cam.yaw, before.yaw); + assert_ne!(cam.pitch, before.pitch); + assert_ne!(cam.roll, before.roll); + let orientation = (cam.yaw, cam.pitch, cam.roll); + navigate(&mut cam, raw(Axes { translation: [350, 0, 0], rotation: [350, 350, 350] }), 0.02, 600.0, true, false); + assert_eq!((cam.yaw, cam.pitch, cam.roll), orientation); + assert!(cam.is_valid()); + } + + #[test] + fn individual_axes_have_physical_spacemouse_meaning() { + let before = Camera::default(); + + let mut slide = before; + navigate(&mut slide, raw(Axes { translation: [350, 0, 0], rotation: [0; 3] }), 0.02, 600.0, false, false); + assert_ne!(slide.target, before.target); + assert_eq!(slide.distance, before.distance); + + let mut push = before; + navigate(&mut push, raw(Axes { translation: [0, 350, 0], rotation: [0; 3] }), 0.02, 600.0, false, false); + assert_eq!(push.target, before.target); + assert!(push.distance < before.distance); + + let mut lift = before; + navigate(&mut lift, raw(Axes { translation: [0, 0, 350], rotation: [0; 3] }), 0.02, 600.0, false, false); + assert_ne!(lift.target, before.target); + assert_eq!(lift.distance, before.distance); + + let mut tilt = before; + navigate(&mut tilt, raw(Axes { translation: [0; 3], rotation: [350, 0, 0] }), 0.02, 600.0, false, false); + assert_eq!((tilt.yaw, tilt.roll), (before.yaw, before.roll)); + assert_ne!(tilt.pitch, before.pitch); + + let mut roll = before; + navigate(&mut roll, raw(Axes { translation: [0; 3], rotation: [0, 350, 0] }), 0.02, 600.0, false, false); + assert_eq!((roll.pitch, roll.roll), (before.pitch, before.roll)); + assert_ne!(roll.yaw, before.yaw); + + let mut twist = before; + navigate(&mut twist, raw(Axes { translation: [0; 3], rotation: [0, 0, 350] }), 0.02, 600.0, false, false); + assert_eq!((twist.yaw, twist.pitch), (before.yaw, before.pitch)); + assert_ne!(twist.roll, before.roll); + } + + #[test] + fn reverse_zoom_setting_applies_to_spacemouse() { + let before = Camera::default(); + let motion = raw(Axes { translation: [0, 350, 0], rotation: [0; 3] }); + let mut normal = before; + navigate(&mut normal, motion, 0.02, 600.0, false, false); + let mut reversed = before; + navigate(&mut reversed, motion, 0.02, 600.0, false, true); + assert!(normal.distance < before.distance); + assert!(reversed.distance > before.distance); + } + + #[test] + fn object_mode_tilts_roll_and_twists_spin() { + let before = Camera::default(); + let mut tilt = before; + navigate(&mut tilt, DriverMapping::object_mode().apply(Axes { translation: [0; 3], rotation: [0, 350, 0] }), 0.02, 600.0, false, false); + assert_eq!((tilt.yaw, tilt.pitch), (before.yaw, before.pitch)); + assert_ne!(tilt.roll, before.roll); + let mut twist = before; + navigate(&mut twist, DriverMapping::object_mode().apply(Axes { translation: [0; 3], rotation: [0, 0, 350] }), 0.02, 600.0, false, false); + assert_ne!(twist.yaw, before.yaw); + assert_eq!((twist.pitch, twist.roll), (before.pitch, before.roll)); + // The physical tilt right (Ry−) rolls one way and the clockwise twist (Rz+) spins the + // other, as 3DxWare's profile has them (#1172). + let tilt_right = DriverMapping::object_mode().apply(Axes { translation: [0; 3], rotation: [0, -350, 0] }); + assert_eq!(tilt_right, Motion { translation: [0.0; 3], rotation: [0.0, 0.0, 1.0] }); + let twist_clockwise = DriverMapping::object_mode().apply(Axes { translation: [0; 3], rotation: [0, 0, 350] }); + assert_eq!(twist_clockwise, Motion { translation: [0.0; 3], rotation: [0.0, -1.0, 0.0] }); + // Translations and the forward tilt are the raw axes. + let all = Axes { translation: [100, -200, 300], rotation: [-150, 0, 0] }; + assert_eq!(DriverMapping::object_mode().apply(all), DriverMapping::default().apply(all)); + } + + #[test] + fn the_dead_zone_is_rest() { + assert!(!Axes::default().moving()); + assert!(!Axes { translation: [20, -20, 0], rotation: [0, 20, -20] }.moving()); + for i in 0..6 { + let mut values = [0_i16; 6]; + values[i] = 21; + let axes = Axes { translation: [values[0], values[1], values[2]], rotation: [values[3], values[4], values[5]] }; + assert!(axes.moving(), "axis {i}"); + values[i] = -21; + let axes = Axes { translation: [values[0], values[1], values[2]], rotation: [values[3], values[4], values[5]] }; + assert!(axes.moving(), "axis {i} reversed"); + } + assert!(Axes { translation: [i16::MIN, 0, 0], rotation: [0, 0, i16::MAX] }.moving()); + } + + #[test] + fn a_mapping_never_reaches_past_the_six_axes() { + let mut mapping = DriverMapping::default(); + mapping.axes[0].output = 6; + mapping.axes[1].output = usize::MAX; + let motion = mapping.apply(Axes { translation: [350, 350, 350], rotation: [350; 3] }); + assert_eq!(motion.translation, [0.0, 0.0, 1.0]); + assert_eq!(motion.rotation, [1.0; 3]); + } + + #[test] + fn a_frame_moves_the_view_and_keeps_the_next_frame_coming() { + let ctx = egui::Context::default(); + let mut app = app(); + let before = app.cam; + assert!(frame(&mut app, &ctx, DriverMapping::default(), PUSH, 0.02)); + assert!(app.cam.distance < before.distance); + // At rest, or with no time passed, nothing moves. + let still = app.cam; + assert!(!frame(&mut app, &ctx, DriverMapping::default(), Axes::default(), 0.02)); + assert!(frame(&mut app, &ctx, DriverMapping::default(), PUSH, 0.0)); + assert_eq!(app.cam.distance, still.distance); + } + + #[test] + fn an_open_file_picker_holds_the_view_until_it_closes() { + let ctx = egui::Context::default(); + let mut app = app(); + let slot: crate::picker_test_support::Slot = Default::default(); + crate::picker_test_support::open(&mut app, &slot); + app.pick_open(|_, _| {}); + assert!(app.file_picker_busy()); + let before = app.cam; + assert!(!frame(&mut app, &ctx, DriverMapping::default(), PUSH, 0.02)); + assert_eq!(app.cam.distance, before.distance); + // Cancelled: the 3D mouse moves the view again. + *slot.borrow_mut() = Some(None); + crate::file_picker::tick(&mut app, &ctx); + assert!(!app.file_picker_busy()); + assert!(frame(&mut app, &ctx, DriverMapping::default(), PUSH, 0.02)); + assert!(app.cam.distance < before.distance); + } + + #[test] + fn a_long_gap_between_frames_moves_as_far_as_a_short_one() { + let ctx = egui::Context::default(); + 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); + assert_eq!(short.cam.distance, long.cam.distance); + for seconds in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -1.0] { + let mut app = app(); + let before = app.cam; + frame(&mut app, &ctx, DriverMapping::default(), PUSH, seconds); + assert_eq!(app.cam.distance, before.distance, "{seconds}"); + } + } + + #[test] + fn navigation_off_the_start_page_and_a_hostile_speed_leave_the_view_alone() { + let ctx = egui::Context::default(); + let mut off = app(); + off.preferences.space_mouse_enabled = false; + let mut home = app(); + home.home.open = true; + let mut nan = app(); + nan.preferences.space_mouse_speed = f32::NAN; + for mut app in [off, home, nan] { + let before = app.cam; + assert!(!frame(&mut app, &ctx, DriverMapping::default(), PUSH, 0.02)); + assert_eq!(app.cam.distance, before.distance); + } + // Speed follows the preference, within 0.1 to 5 times. + let speeds = [0.5, 2.0, 5.0, f32::MAX, 0.25, 0.0, -3.0]; + let distances: Vec = speeds + .iter() + .map(|&speed| { + let mut app = app(); + app.preferences.space_mouse_speed = speed; + frame(&mut app, &ctx, DriverMapping::default(), PUSH, 0.02); + assert!(app.cam.is_valid(), "{speed}"); + app.cam.distance + }) + .collect(); + assert!(distances[1] < distances[0]); + assert_eq!(distances[3], distances[2], "past 5 times is 5 times"); + // Under 0.1 times is 0.1 times (the f32 preference can't hold 0.1 exactly): still a + // motion, less than at 0.25. + assert_eq!(distances[6], distances[5], "under 0.1 times is 0.1 times"); + assert!(distances[4] < distances[5] && distances[5] < app().cam.distance); + } +} diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 12313a5a2..71af58ad5 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -91,6 +91,9 @@ pub struct ViewportState { pub orbit_pivot: 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 + /// camera may do (`navigation::device`). + pub device_motion: Option, /// After immediate zoom, ignore egui's outstanding smoothing until the gesture ends. pub(crate) wheel_zoom_raw_until_idle: bool, /// While trackpad scrolling runs, ignore egui's smoothing tail for zoom so diff --git a/docs/book/src/guide/getting-started.md b/docs/book/src/guide/getting-started.md index badd89ec6..7aff90d52 100644 --- a/docs/book/src/guide/getting-started.md +++ b/docs/book/src/guide/getting-started.md @@ -110,6 +110,56 @@ cd apps/solidcraft-web && trunk serve --release --no-autoreload Offline use needs `--no-autoreload`: Trunk's live reload changes the page as it serves it, so it no longer matches the build the browser would keep. Debug builds (`trunk serve`) never keep a copy. +### 3D mouse in the browser + +The web app reads a 3Dconnexion SpaceMouse or SpaceNavigator through the browser's Gamepad API, +with the same switch and speed in Preferences › Navigation as the desktop app. Edge and Chrome +read the device as it is. A browser shows a gamepad to a page only once it has been moved there, +so if nothing happens at first, push the cap firmly once. 3DxWare also turns the cap into +mouse-wheel zoom in browsers; while the cap moves, the web app ignores the wheel and reads the +cap itself. Before the browser shows the cap to the page, that zoom still gets through, so the +first push after opening the page may zoom a little. + +Firefox doesn't list 3D mice ([Mozilla bug 1226575](https://bugzilla.mozilla.org/show_bug.cgi?id=1226575)). +On Windows it does list 3DxWare's virtual joystick, which can carry the cap instead. Save this +as `%APPDATA%\3Dconnexion\3DxWare\Cfg\Firefox.xml`, then restart Firefox (and 3DxWare, if the cap +still only zooms). It changes Firefox only: there 3DxWare sends the cap's six axes to the +joystick instead of the mouse wheel. Delete the file to undo it. + +```xml + + + + + STR_FIREFOX + FIREFOX.EXE + KMJ + + + + + ID_STR_FIREFOX + STR_FIREFOX + ID_STR_FIREFOX + + + + ID_Standard_3D_Mouse + + STR_DEFAULT_BANK + Default + trueHIDMultiAxis_X-5125110HIDJoystick_X + trueHIDMultiAxis_Y-5125110HIDJoystick_Y + trueHIDMultiAxis_Z-5125110HIDJoystick_Z + trueHIDMultiAxis_Rx-5125110HIDJoystick_Rx + trueHIDMultiAxis_Ry-5125110HIDJoystick_Ry + trueHIDMultiAxis_Rz-5125110HIDJoystick_Rz + + + + +``` + ## CLI `solidcraft-cli` runs the same commands without a window: diff --git a/docs/i18n_catalog_ja.md b/docs/i18n_catalog_ja.md index c2b5d192f..002d3286f 100644 --- a/docs/i18n_catalog_ja.md +++ b/docs/i18n_catalog_ja.md @@ -19,7 +19,7 @@ | 3-Point Rectangle | 3点指定長方形 | `cmd.sketch_rectangle_three_point` | | 3-Tangent Circle | 3接線指定の円 | `cmd.sketch_circle_three_tangent` | | 3D Line | 3D 線分 | `cmd.sketch_line3d` | -| 3D mouse (Windows) | 3D マウス (Windows) | `ui.3d_mouse_windows` | +| 3D mouse | 3D マウス | `ui.3d_mouse_windows` | | 3D mouse speed | 3D マウス速度 | `ui.3d_mouse_speed` | | 3D Point | 3D 点 | `cmd.sketch_point3d` | | 3D Sketch | 3D スケッチ | `ui.3d_sketch` | From f7967b1ff64d72c1161979623db365074be397ca Mon Sep 17 00:00:00 2001 From: Mateusz Sych <151755914+SychPL@users.noreply.github.com> Date: Fri, 16 Oct 2026 00:47:38 +0200 Subject: [PATCH 08/92] Joints: gears, rack and pinion, and screws (#1524) Motion links can carry a coupling (gear pair, rack and pinion, screw) whose ratio follows radii, picked round faces or pitch. Design format 23. Co-authored-by: SychPL Co-Authored-By: Claude Sonnet 5.5 --- ROADMAP.md | 2 +- assets/icons/ui/source/icons.rs | 43 +++ assets/locales/de.json | 21 +- assets/locales/en.json | 21 +- assets/locales/fr.json | 21 +- assets/locales/ja.json | 21 +- assets/locales/ko.json | 21 +- assets/locales/ru.json | 21 +- assets/locales/uk.json | 21 +- assets/locales/zh.json | 21 +- crates/doc/src/format.rs | 12 +- crates/doc/src/joints.rs | 201 +++++++++++-- .../src/cmd/component_clone_assembly.rs | 21 +- .../src/cmd/component_clone_assembly_tests.rs | 31 +- crates/engine/src/cmd/joints.rs | 210 ++++++++++++- .../engine/src/cmd/joints_coupling_tests.rs | 255 ++++++++++++++++ crates/engine/src/cmd/joints_tests.rs | 3 + crates/engine/src/cmd/motion.rs | 7 +- crates/ui-egui/src/dialogs_assembly.rs | 31 +- crates/ui-egui/src/dialogs_coupling.rs | 279 ++++++++++++++++++ crates/ui-egui/src/dialogs_coupling_tests.rs | 198 +++++++++++++ crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/preview.rs | 23 +- crates/ui-egui/src/workspace.rs | 3 + docs/book/src/guide/assemblies.md | 27 ++ docs/design-container.md | 2 +- docs/features.md | 7 +- skills/solidcraft-mechanisms/SKILL.md | 1 + skills/solidcraft-mechanisms/reference.md | 5 +- 29 files changed, 1476 insertions(+), 54 deletions(-) create mode 100644 crates/engine/src/cmd/joints_coupling_tests.rs create mode 100644 crates/ui-egui/src/dialogs_coupling.rs create mode 100644 crates/ui-egui/src/dialogs_coupling_tests.rs diff --git a/ROADMAP.md b/ROADMAP.md index 1cc2dc129..2cae5667b 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -54,7 +54,7 @@ PCB / Package, Render, Animation, Simulation, Manufacture/CAM, Drawings. | 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; taper handle open), 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), 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. Proposed, in order: surface Extrude/Revolve/Sweep/Loft from open and closed curves (#757), Offset surface (#758), Unstitch and Reverse Normal (#766), Delete Face without healing (#768); Extend curved faces and edges (#760), mutual trim and trim by projected curves (#767), Untrim (#761), Thicken every surface kind (#765); Ruled (#762), Boundary surface and curve networks with G0/G1/G2 (#763), Patch with G1/G2 and general loops (#759), Blend surface (#764), sweep guide rails and two-rail sweeps (#771; orientation, twist and end scale done; loft rails #201), fillet between surface bodies (#769); continuity analysis, surface curvature combs and isocurves (#770) | 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), 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), 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 and Interference (overlaps shown red); joints in the timeline and the Browser | in progress | 32 | +| 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), gears, rack and pinion and screws (motion links whose ratio follows picked radii, parameters or a pitch, also inside closed loops), 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), 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, Gear, Rack and Pinion, Screw 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 | | 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 | diff --git a/assets/icons/ui/source/icons.rs b/assets/icons/ui/source/icons.rs index 4f8879055..3a354f682 100644 --- a/assets/icons/ui/source/icons.rs +++ b/assets/icons/ui/source/icons.rs @@ -21,6 +21,19 @@ fn ellipse(x: f32, y: f32, rx: f32, ry: f32, a0: f32, a1: f32, n: usize) -> Vec< (0..=n).map(|i| a0 + (a1 - a0) * i as f32 / n as f32).map(|a| (x + rx * a.cos(), y + ry * a.sin())).collect() } +/// A gear's toothed outline about (x, y): `n` teeth from the root radius `root` out to `tip`, +/// turned by `phase` radians. +fn teeth(x: f32, y: f32, root: f32, tip: f32, n: usize, phase: f32) -> Vec<(f32, f32)> { + let step = std::f32::consts::TAU / n as f32; + let at = |a: f32, r: f32| (x + r * a.cos(), y - r * a.sin()); + (0..n) + .flat_map(|k| { + let a = phase + step * k as f32; + [at(a - 0.3 * step, root), at(a - 0.15 * step, tip), at(a + 0.15 * step, tip), at(a + 0.3 * step, root)] + }) + .collect() +} + struct Pen<'a> { p: &'a Painter, r: Rect, @@ -1256,6 +1269,36 @@ pub(crate) fn paint_with(p: &Painter, r: Rect, name: &str, ink: Color32, fill: C pen.dot(7.0, 14.0, a); pen.dot(17.5, 9.0, a); } + // Couplings: the driven part in the accent. + "gear" => { + pen.circle(9.0, 14.0, 5.2, pen.fill, Color32::TRANSPARENT); + pen.closed(&teeth(9.0, 14.0, 5.2, 6.8, 9, 0.0), ink); + pen.dot(9.0, 14.0, ink); + pen.circle(17.6, 7.4, 3.2, pen.fill, Color32::TRANSPARENT); + pen.closed(&teeth(17.6, 7.4, 3.2, 4.6, 6, 0.3), a); + pen.dot(17.6, 7.4, a); + } + "rack_pinion" => { + pen.circle(12.0, 7.4, 4.2, pen.fill, Color32::TRANSPARENT); + pen.closed(&teeth(12.0, 7.4, 4.2, 5.8, 8, 0.2), ink); + pen.dot(12.0, 7.4, ink); + let mut rack = vec![(2.0, 18.0)]; + for k in 0..5 { + let x = 2.5 + 4.0 * k as f32; + rack.extend([(x, 14.3), (x + 1.0, 12.8), (x + 2.2, 12.8), (x + 3.2, 14.3)]); + } + rack.extend([(22.0, 14.3), (22.0, 18.0)]); + pen.closed(&rack, a); + pen.arrow((7.0, 21.5), (17.5, 21.5), a); + } + "screw" => { + pen.poly(&[(9.5, 2.0), (14.5, 2.0), (14.5, 22.0), (9.5, 22.0)], pen.fill, ink); + for y in [5.0, 8.0, 17.0, 20.0] { + pen.line(&[(9.5, y), (14.5, y - 2.0)], ink); + } + pen.poly(&[(6.0, 10.0), (18.0, 10.0), (18.0, 15.0), (6.0, 15.0)], pen.fill, a); + pen.arrow((21.0, 17.0), (21.0, 6.0), a); + } "interference" => { pen.closed(&[(3.0, 5.0), (14.0, 5.0), (14.0, 16.0), (3.0, 16.0)], ink); pen.poly(&[(9.0, 10.0), (14.0, 10.0), (14.0, 16.0), (9.0, 16.0)], ic.interference, ic.interference); diff --git a/assets/locales/de.json b/assets/locales/de.json index 35e5f8af6..0d0c6524d 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -760,6 +760,9 @@ "cmd.joint_limits": "Gelenkgrenzen", "cmd.joint_list": "Gelenke auflisten", "cmd.joint_motion_link": "Bewegungsverknüpfung", + "cmd.joint_gear": "Zahnrad", + "cmd.joint_rack_pinion": "Zahnstange und Ritzel", + "cmd.joint_screw": "Schraube", "cmd.joint_origin": "Gelenkursprung", "cmd.joint_rigid_group": "Starrgruppe", "cmd.joint_solve": "Gelenke lösen", @@ -1122,5 +1125,21 @@ "Min": "Min", "Max": "Max", "Length": "Länge", - "Area": "Fläche" + "Area": "Fläche", + "coupling.gear_1": "Zahnrad 1", + "coupling.gear_2": "Zahnrad 2", + "coupling.pinion": "Ritzel", + "coupling.rack": "Zahnstange", + "coupling.nut": "Mutter", + "coupling.radius_1": "Radius 1", + "coupling.radius_2": "Radius 2", + "coupling.internal": "Innenzahnrad", + "coupling.pitch": "Steigung", + "coupling.picked": "gewählt", + "coupling.not_round": "keine runde Fläche", + "coupling.gear_1_pick": "Zahnrad 1 (optional)", + "coupling.gear_2_pick": "Zahnrad 2 (optional)", + "coupling.pinion_pick": "Ritzel (optional)", + "coupling.needs_turns": "braucht zwei Gelenke, die sich drehen", + "coupling.needs_turn_and_slide": "braucht ein Gelenk, das sich dreht, und eines, das gleitet" } diff --git a/assets/locales/en.json b/assets/locales/en.json index 12317a2cc..18d234ca1 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -125,6 +125,9 @@ "cmd.joint_limits": "Joint Limits", "cmd.joint_list": "List Joints", "cmd.joint_motion_link": "Motion Link", + "cmd.joint_gear": "Gear", + "cmd.joint_rack_pinion": "Rack and Pinion", + "cmd.joint_screw": "Screw", "cmd.joint_origin": "Joint Origin", "cmd.joint_rigid_group": "Rigid Group", "cmd.joint_solve": "Solve Joints", @@ -1377,5 +1380,21 @@ "Centre to centre": "Centre to centre", "Overall length": "Overall length", "Min": "Min", - "Max": "Max" + "Max": "Max", + "coupling.gear_1": "Gear 1", + "coupling.gear_2": "Gear 2", + "coupling.pinion": "Pinion", + "coupling.rack": "Rack", + "coupling.nut": "Nut", + "coupling.radius_1": "Radius 1", + "coupling.radius_2": "Radius 2", + "coupling.internal": "Internal gear", + "coupling.pitch": "Pitch", + "coupling.picked": "picked", + "coupling.not_round": "not a round face", + "coupling.gear_1_pick": "Gear 1 (optional)", + "coupling.gear_2_pick": "Gear 2 (optional)", + "coupling.pinion_pick": "Pinion (optional)", + "coupling.needs_turns": "needs two joints that turn", + "coupling.needs_turn_and_slide": "needs a joint that turns and one that slides" } diff --git a/assets/locales/fr.json b/assets/locales/fr.json index 6aabcff45..182b8a9c2 100644 --- a/assets/locales/fr.json +++ b/assets/locales/fr.json @@ -125,6 +125,9 @@ "cmd.joint_limits": "Limites de liaison", "cmd.joint_list": "Lister les liaisons", "cmd.joint_motion_link": "Lien de mouvement", + "cmd.joint_gear": "Engrenage", + "cmd.joint_rack_pinion": "Pignon et crémaillère", + "cmd.joint_screw": "Vis", "cmd.joint_origin": "Origine de liaison", "cmd.joint_rigid_group": "Groupe rigide", "cmd.joint_solve": "Résoudre les liaisons", @@ -1230,5 +1233,21 @@ "RULED SURFACE": "SURFACE RÉGLÉE", "Mitre": "Onglet", "Reference face": "Face de référence", - "Round": "Arrondi" + "Round": "Arrondi", + "coupling.gear_1": "Engrenage 1", + "coupling.gear_2": "Engrenage 2", + "coupling.pinion": "Pignon", + "coupling.rack": "Crémaillère", + "coupling.nut": "Écrou", + "coupling.radius_1": "Rayon 1", + "coupling.radius_2": "Rayon 2", + "coupling.internal": "Engrenage intérieur", + "coupling.pitch": "Pas", + "coupling.picked": "sélectionné", + "coupling.not_round": "pas une face ronde", + "coupling.gear_1_pick": "Engrenage 1 (facultatif)", + "coupling.gear_2_pick": "Engrenage 2 (facultatif)", + "coupling.pinion_pick": "Pignon (facultatif)", + "coupling.needs_turns": "nécessite deux liaisons qui tournent", + "coupling.needs_turn_and_slide": "nécessite une liaison qui tourne et une qui glisse" } diff --git a/assets/locales/ja.json b/assets/locales/ja.json index b88765b29..29bb48eda 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -125,6 +125,9 @@ "cmd.joint_limits": "ジョイントの制限", "cmd.joint_list": "ジョイントを一覧表示", "cmd.joint_motion_link": "モーション リンク", + "cmd.joint_gear": "ギア", + "cmd.joint_rack_pinion": "ラック アンド ピニオン", + "cmd.joint_screw": "ねじ", "cmd.joint_origin": "ジョイント原点", "cmd.joint_rigid_group": "リジッド グループ", "cmd.joint_solve": "ジョイントを解決", @@ -1377,5 +1380,21 @@ "Centre to centre": "中心間", "Overall length": "全長", "Min": "最小", - "Max": "最大" + "Max": "最大", + "coupling.gear_1": "ギア 1", + "coupling.gear_2": "ギア 2", + "coupling.pinion": "ピニオン", + "coupling.rack": "ラック", + "coupling.nut": "ナット", + "coupling.radius_1": "半径 1", + "coupling.radius_2": "半径 2", + "coupling.internal": "内歯車", + "coupling.pitch": "ピッチ", + "coupling.picked": "選択済み", + "coupling.not_round": "円筒面ではありません", + "coupling.gear_1_pick": "ギア 1 (オプション)", + "coupling.gear_2_pick": "ギア 2 (オプション)", + "coupling.pinion_pick": "ピニオン (オプション)", + "coupling.needs_turns": "回転するジョイントが 2 つ必要", + "coupling.needs_turn_and_slide": "回転するジョイントとスライドするジョイントが必要" } diff --git a/assets/locales/ko.json b/assets/locales/ko.json index a2b1c8122..ea74c84bd 100644 --- a/assets/locales/ko.json +++ b/assets/locales/ko.json @@ -760,6 +760,9 @@ "cmd.joint_limits": "관절 제한", "cmd.joint_list": "관절 목록", "cmd.joint_motion_link": "모션 링크", + "cmd.joint_gear": "기어", + "cmd.joint_rack_pinion": "랙 앤 피니언", + "cmd.joint_screw": "나사", "cmd.joint_origin": "관절 원점", "cmd.joint_rigid_group": "강체 그룹", "cmd.joint_solve": "관절 해석", @@ -1122,5 +1125,21 @@ "Min": "최소", "Max": "최대", "Length": "길이", - "Area": "면적" + "Area": "면적", + "coupling.gear_1": "기어 1", + "coupling.gear_2": "기어 2", + "coupling.pinion": "피니언", + "coupling.rack": "랙", + "coupling.nut": "너트", + "coupling.radius_1": "반지름 1", + "coupling.radius_2": "반지름 2", + "coupling.internal": "내접 기어", + "coupling.pitch": "피치", + "coupling.picked": "선택됨", + "coupling.not_round": "원통 면이 아님", + "coupling.gear_1_pick": "기어 1 (선택 사항)", + "coupling.gear_2_pick": "기어 2 (선택 사항)", + "coupling.pinion_pick": "피니언 (선택 사항)", + "coupling.needs_turns": "회전하는 관절 두 개가 필요함", + "coupling.needs_turn_and_slide": "회전하는 관절과 미끄러지는 관절이 필요함" } diff --git a/assets/locales/ru.json b/assets/locales/ru.json index 1aa220814..964efd542 100644 --- a/assets/locales/ru.json +++ b/assets/locales/ru.json @@ -114,6 +114,9 @@ "cmd.joint_limits": "Ограничения сопряжения", "cmd.joint_list": "Список сопряжений", "cmd.joint_motion_link": "Связь движений", + "cmd.joint_gear": "Зубчатая передача", + "cmd.joint_rack_pinion": "Реечная передача", + "cmd.joint_screw": "Винт", "cmd.joint_origin": "Точка сопряжения", "cmd.joint_rigid_group": "Жёсткая группа", "cmd.joint_solve": "Решить сопряжения", @@ -1142,5 +1145,21 @@ "render.opaque_image_summary": "Предпросмотр PNG · непрозрачный PBR · прозрачность через смешивание", "joint.one_component": "Эти детали - тела одного компонента: {bodies}. Сопряжение двигает один компонент относительно другого, поэтому каждой детали нужен свой компонент.", "joint.one_body": "Оба выбора на {body}. Выберите второй на другой детали.", - "joint.from_bodies_hint": "Каждое выбранное тело переходит в свой новый компонент и остаётся на месте." + "joint.from_bodies_hint": "Каждое выбранное тело переходит в свой новый компонент и остаётся на месте.", + "coupling.gear_1": "Шестерня 1", + "coupling.gear_2": "Шестерня 2", + "coupling.pinion": "Шестерня", + "coupling.rack": "Рейка", + "coupling.nut": "Гайка", + "coupling.radius_1": "Радиус 1", + "coupling.radius_2": "Радиус 2", + "coupling.internal": "Внутреннее зацепление", + "coupling.pitch": "Шаг", + "coupling.picked": "выбрано", + "coupling.not_round": "не круглая грань", + "coupling.gear_1_pick": "Шестерня 1 (необязательно)", + "coupling.gear_2_pick": "Шестерня 2 (необязательно)", + "coupling.pinion_pick": "Шестерня (необязательно)", + "coupling.needs_turns": "нужны два вращающихся сопряжения", + "coupling.needs_turn_and_slide": "нужны вращающееся и скользящее сопряжения" } diff --git a/assets/locales/uk.json b/assets/locales/uk.json index 2ffc11cdf..449050bb8 100644 --- a/assets/locales/uk.json +++ b/assets/locales/uk.json @@ -115,6 +115,9 @@ "cmd.joint_limits": "Обмеження з'єднання", "cmd.joint_list": "Список з'єднань", "cmd.joint_motion_link": "Зв'язок руху", + "cmd.joint_gear": "Зубчаста передача", + "cmd.joint_rack_pinion": "Рейкова передача", + "cmd.joint_screw": "Гвинт", "cmd.joint_origin": "Початок з'єднання", "cmd.joint_rigid_group": "Жорстка група", "cmd.joint_solve": "Розв'язати з'єднання", @@ -1061,5 +1064,21 @@ "drive.unconnected": "Нічого не рухається: {part} не з'єднано ні з чим закріпленим", "joint.one_component": "Ці деталі - тіла одного компонента: {bodies}. З'єднання рухає один компонент відносно іншого, тому кожній деталі потрібен власний компонент.", "joint.one_body": "Обидва вибори на {body}. Виберіть другий на іншій деталі.", - "joint.from_bodies_hint": "Кожне вибране тіло переходить у власний новий компонент і лишається на місці." + "joint.from_bodies_hint": "Кожне вибране тіло переходить у власний новий компонент і лишається на місці.", + "coupling.gear_1": "Шестерня 1", + "coupling.gear_2": "Шестерня 2", + "coupling.pinion": "Шестерня", + "coupling.rack": "Рейка", + "coupling.nut": "Гайка", + "coupling.radius_1": "Радіус 1", + "coupling.radius_2": "Радіус 2", + "coupling.internal": "Внутрішнє зачеплення", + "coupling.pitch": "Крок", + "coupling.picked": "вибрано", + "coupling.not_round": "не кругла грань", + "coupling.gear_1_pick": "Шестерня 1 (необов'язково)", + "coupling.gear_2_pick": "Шестерня 2 (необов'язково)", + "coupling.pinion_pick": "Шестерня (необов'язково)", + "coupling.needs_turns": "потрібні два обертові з'єднання", + "coupling.needs_turn_and_slide": "потрібні обертове й ковзне з'єднання" } diff --git a/assets/locales/zh.json b/assets/locales/zh.json index 8a8432d56..bea389b1c 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -125,6 +125,9 @@ "cmd.joint_limits": "接头限制", "cmd.joint_list": "列出接头", "cmd.joint_motion_link": "运动关联", + "cmd.joint_gear": "齿轮", + "cmd.joint_rack_pinion": "齿轮齿条", + "cmd.joint_screw": "螺旋", "cmd.joint_origin": "接头原点", "cmd.joint_rigid_group": "刚性组", "cmd.joint_solve": "解算接头", @@ -1377,5 +1380,21 @@ "Centre to centre": "中心距", "Overall length": "总长", "Min": "最小", - "Max": "最大" + "Max": "最大", + "coupling.gear_1": "齿轮 1", + "coupling.gear_2": "齿轮 2", + "coupling.pinion": "小齿轮", + "coupling.rack": "齿条", + "coupling.nut": "螺母", + "coupling.radius_1": "半径 1", + "coupling.radius_2": "半径 2", + "coupling.internal": "内齿轮", + "coupling.pitch": "螺距", + "coupling.picked": "已拾取", + "coupling.not_round": "不是圆柱面", + "coupling.gear_1_pick": "齿轮 1(可选)", + "coupling.gear_2_pick": "齿轮 2(可选)", + "coupling.pinion_pick": "小齿轮(可选)", + "coupling.needs_turns": "需要两个旋转接头", + "coupling.needs_turn_and_slide": "需要一个旋转接头和一个滑动接头" } diff --git a/crates/doc/src/format.rs b/crates/doc/src/format.rs index 091bb4e32..16a4500ad 100644 --- a/crates/doc/src/format.rs +++ b/crates/doc/src/format.rs @@ -222,13 +222,20 @@ //! parameters); the source's `at`, `height` and `angle` then hold the numbers they last came //! to. A text without `exprs` is set as it always was; 0.12.0 asks for an update instead of //! dropping the expressions and keeping the text at its last numbers. +//! - 23: a motion link can carry a `coupling`: a gear pair (`ra`, `rb`, `internal`), a rack and +//! pinion (`radius`) or a screw (`pitch`), each size a number in mm, an expression or a picked +//! round face, and `reverse`. The link's `ratio` is worked out from it whenever the design +//! changes and saved as well, so a link reads the same without it. Version 22 designs need no +//! transformation: a link without `coupling` is a plain motion link, as it always was; 0.13.0 +//! (which reads up to 22) asks for an update instead of keeping a gear's ratio when its radius +//! changes. use serde_json::Value; use crate::{DocError, Document, Result}; /// The format this build writes. -pub const FORMAT: u32 = 22; +pub const FORMAT: u32 = 23; pub fn format_string(n: u32) -> String { format!("solidcraft/{n}") @@ -245,7 +252,7 @@ pub fn version_of(s: &str) -> Option { /// JSON-level upgrades: entry `i` turns format `i + 1` into `i + 2`. type JsonStep = fn(&mut Value) -> Result<()>; -const JSON_STEPS: [JsonStep; 21] = [ +const JSON_STEPS: [JsonStep; 22] = [ |_| Ok(()), v2_to_v3, v3_to_v4, @@ -267,6 +274,7 @@ const JSON_STEPS: [JsonStep; 21] = [ |_| Ok(()), |_| Ok(()), |_| Ok(()), + |_| Ok(()), ]; /// Stored face and edge names were worked out from geometry before format 14; they get the diff --git a/crates/doc/src/joints.rs b/crates/doc/src/joints.rs index 5cf20897d..afeb93a27 100644 --- a/crates/doc/src/joints.rs +++ b/crates/doc/src/joints.rs @@ -1,7 +1,8 @@ //! 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, and the solver that places -//! occurrences from the joint graph. +//! planar, ball) with their motion values and limits, motion links (gears, racks and screws are +//! links whose ratio comes from radii or a pitch), 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` @@ -151,6 +152,115 @@ pub struct MotionLink { pub ratio: f64, #[serde(default)] pub offset: f64, + /// Gears, a rack and pinion or a screw: what the ratio comes from. The ratio is worked out + /// from it again whenever the design changes (`coupling_ratio`), so it follows the radii and + /// the pitch; the last one worked out is kept in `ratio`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub coupling: Option, +} + +/// A length a coupling's ratio comes from: millimetres, an expression over the design's +/// parameters, or the radius of the round face picked on an occurrence (a circle-centre snap, +/// found again on every solve like a joint origin). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum Size { + Length(f64), + Expr(String), + Circle(JointOrigin), +} + +/// The geometry a motion link's ratio comes from. `reverse` turns the follower the other way. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum Coupling { + /// Two gears on revolute joints, `ra` on a's and `rb` on b's (pitch radii, or any two lengths + /// in their proportion such as tooth counts): b turns ra/rb as far as a, the other way round, + /// or the same way when one is an internal (ring) gear. + Gear { + ra: Size, + rb: Size, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + internal: bool, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + reverse: bool, + }, + /// A pinion of pitch radius `radius` on a revolute joint and a rack on a slider: the rack + /// travels the radius times the pinion's turn in radians (either joint may drive). + RackPinion { + radius: Size, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + reverse: bool, + }, + /// A screw: the travel advances `pitch` per turn (a cylindrical joint's angle and distance, + /// or a revolute joint and a slider). Right-handed unless reversed. + Screw { + pitch: Size, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + reverse: bool, + }, +} + +impl Coupling { + /// The lengths the ratio comes from: a's gear and b's, or the pinion's radius or the pitch. + pub fn sizes(&self) -> Vec<&Size> { + match self { + Coupling::Gear { ra, rb, .. } => vec![ra, rb], + Coupling::RackPinion { radius: s, .. } | Coupling::Screw { pitch: s, .. } => vec![s], + } + } + + pub fn sizes_mut(&mut self) -> Vec<&mut Size> { + match self { + Coupling::Gear { ra, rb, .. } => vec![ra, rb], + Coupling::RackPinion { radius: s, .. } | Coupling::Screw { pitch: s, .. } => vec![s], + } + } +} + +/// Largest length a coupling takes (mm). +const MAX_SIZE: f64 = 1e7; + +/// A coupling length in millimetres: positive and finite. +fn size_of(doc: &Document, st: &ModelState, s: &Size) -> Result { + let v = match s { + Size::Length(v) => *v, + Size::Expr(e) => doc.eval(e, crate::expr::Kind::Length)?, + Size::Circle(o) => circle_at(doc, st, o)?.1.radius, + }; + if v.is_finite() && v > 1e-9 && v <= MAX_SIZE { + Ok(v) + } else { + Err(DocError::Invalid(format!("a gear, rack or screw needs a positive length, not {v}"))) + } +} + +/// The ratio a link's coupling gives it (b's value per a's, in radians and mm), worked out from +/// the geometry and parameters it is defined by; `None` for a plain link. +pub fn coupling_ratio(doc: &Document, st: &ModelState, l: &MotionLink) -> Option> { + l.coupling.as_ref().map(|c| coupled(doc, st, l, c)) +} + +fn coupled(doc: &Document, st: &ModelState, l: &MotionLink, c: &Coupling) -> Result { + let angle = |id: u64, i: usize| doc.assembly.joints.iter().find(|j| j.id == id).is_some_and(|j| j.kind.is_angle(i)); + let (turn_a, turn_b) = (angle(l.a, l.ia), angle(l.b, l.ib)); + // Travel per radian, for a turn coupled to a travel either way round. + let travel = |k: f64| match (turn_a, turn_b) { + (true, false) => Ok(k), + (false, true) => Ok(1.0 / k), + _ => Err(DocError::Invalid("a rack or a screw couples a turn and a travel".into())), + }; + let sign = |reverse: bool| if reverse { -1.0 } else { 1.0 }; + match c { + Coupling::Gear { ra, rb, internal, reverse } => { + if !(turn_a && turn_b) { + return Err(DocError::Invalid("gears couple two turns".into())); + } + Ok(size_of(doc, st, ra)? / size_of(doc, st, rb)? * sign(!internal) * sign(*reverse)) + } + Coupling::RackPinion { radius, reverse } => Ok(travel(size_of(doc, st, radius)?)? * sign(*reverse)), + Coupling::Screw { pitch, reverse } => Ok(travel(size_of(doc, st, pitch)? / std::f64::consts::TAU)? * sign(*reverse)), + } } /// Joints, joint origins and motion links of a design. @@ -272,27 +382,35 @@ pub fn resolve_origin(doc: &Document, st: &ModelState, o: &JointOrigin) -> Resul let (_, c, n) = best.ok_or_else(|| DocError::Invalid("joint origin: no planar face there".into()))?; frame(c, n, None).ok_or_else(bad) } - Snap::CircleCenter { pick, face } => { - let pick = &named_pick(st, *pick, face.as_deref())?; - let comp = component_of(doc, o.occurrence)?; - let cyl = component_bodies(doc, st, comp) - .into_iter() - .filter_map(|b| solidcraft_kernel::cylinder_face_at(&b.body, *pick)) - .min_by(|a, b| { - let off = |c: &solidcraft_kernel::CylinderFace| { - let v = *pick - c.axis_point; - ((v - c.axis * v.dot(c.axis)).len() - c.radius).abs() - }; - off(a).total_cmp(&off(b)) - }) - .ok_or_else(|| DocError::Invalid("joint origin: no cylindrical face there".into()))?; - let s = (*pick - cyl.axis_point).dot(cyl.axis); + Snap::CircleCenter { .. } => { + let (pick, cyl) = circle_at(doc, st, o)?; + let s = (pick - cyl.axis_point).dot(cyl.axis); let (at, dir) = if (s - cyl.start).abs() <= (cyl.end - s).abs() { (cyl.start, -1.0) } else { (cyl.end, 1.0) }; frame(cyl.axis_point + cyl.axis * at, cyl.axis * dir, None).ok_or_else(bad) } } } +/// The pick of a circle-centre snap (on its named face) and the cylindrical face there +/// (component coordinates). Any other snap is refused. +fn circle_at(doc: &Document, st: &ModelState, o: &JointOrigin) -> Result<(Vec3, solidcraft_kernel::CylinderFace)> { + let Snap::CircleCenter { pick, face } = &o.snap else { return Err(DocError::Invalid("pick a round face".into())) }; + let pick = named_pick(st, *pick, face.as_deref())?; + let comp = component_of(doc, o.occurrence)?; + let cyl = component_bodies(doc, st, comp) + .into_iter() + .filter_map(|b| solidcraft_kernel::cylinder_face_at(&b.body, pick)) + .min_by(|a, b| { + let off = |c: &solidcraft_kernel::CylinderFace| { + let v = pick - c.axis_point; + ((v - c.axis * v.dot(c.axis)).len() - c.radius).abs() + }; + off(a).total_cmp(&off(b)) + }) + .ok_or_else(|| DocError::Invalid("joint origin: no cylindrical face there".into()))?; + Ok((pick, cyl)) +} + /// World transform of an occurrence (through its parents). pub fn occurrence_world(doc: &Document, occ: u64) -> Mat { let mut m = IDENTITY; @@ -1283,7 +1401,7 @@ mod tests { suppressed: false, }) .collect(); - let links = (1..n).rev().map(|a| MotionLink { a, ia: 0, b: a + 1, ib: 0, ratio: 2.0, offset: 0.0 }).collect(); + let links = (1..n).rev().map(|a| MotionLink { a, ia: 0, b: a + 1, ib: 0, ratio: 2.0, offset: 0.0, coupling: None }).collect(); Assembly { joints, links, ..Assembly::default() } } @@ -1306,6 +1424,53 @@ mod tests { assert_eq!(again, vals); } + /// A coupling saves as its definition: sizes as numbers, expressions or picked faces, flags + /// only when set; a link without one (as every design before couplings has) reads as before. + #[test] + fn couplings_read_and_write_their_definition() { + let old: MotionLink = serde_json::from_str(r#"{"a": 1, "b": 2, "ratio": 2}"#).unwrap(); + assert_eq!((old.coupling, old.offset, old.ia), (None, 0.0, 0)); + let text = r#"{"a": 1, "b": 2, "ratio": -0.5, "coupling": {"type": "gear", "ra": 10, "rb": "r2 * 2", + "internal": true}}"#; + let l: MotionLink = serde_json::from_str(text).unwrap(); + let Some(Coupling::Gear { ra, rb, internal, reverse }) = &l.coupling else { panic!("{l:?}") }; + assert_eq!((ra, rb, *internal, *reverse), (&Size::Length(10.0), &Size::Expr("r2 * 2".into()), true, false)); + let back = serde_json::to_value(&l).unwrap(); + assert_eq!(back["coupling"], serde_json::json!({"type": "gear", "ra": 10.0, "rb": "r2 * 2", "internal": true})); + let picked: Size = serde_json::from_str(r#"{"occurrence": 3, "snap": {"type": "circle_center", "pick": [1, 0, 0]}}"#).unwrap(); + assert!(matches!(picked, Size::Circle(JointOrigin { occurrence: 3, snap: Snap::CircleCenter { .. } }))); + let screw: Coupling = serde_json::from_str(r#"{"type": "screw", "pitch": 1.5, "reverse": true}"#).unwrap(); + assert_eq!(screw, Coupling::Screw { pitch: Size::Length(1.5), reverse: true }); + } + + /// Ratios from the sizes: gears turn by their radii (the other way unless internal), a rack + /// and a screw travel per radian whichever of the two joints drives. + #[test] + fn coupling_ratios_follow_their_sizes() { + let mut doc = Document { assembly: chain(3, 0.0), ..Document::default() }; + if let Some(j) = doc.assembly.joints.get_mut(2) { + j.kind = JointKind::Slider; + } + let st = ModelState::default(); + let ratio = |a: u64, b: u64, c: Coupling| { + let l = MotionLink { a, ia: 0, b, ib: 0, ratio: 0.0, offset: 0.0, coupling: Some(c) }; + coupling_ratio(&doc, &st, &l).map(|r| r.map_err(|e| e.to_string())) + }; + let len = Size::Length; + assert_eq!(ratio(1, 2, Coupling::Gear { ra: len(10.0), rb: len(40.0), internal: false, reverse: false }), Some(Ok(-0.25))); + assert_eq!(ratio(1, 2, Coupling::Gear { ra: len(10.0), rb: len(40.0), internal: true, reverse: false }), Some(Ok(0.25))); + assert_eq!(ratio(1, 3, Coupling::RackPinion { radius: len(8.0), reverse: false }), Some(Ok(8.0))); + assert_eq!(ratio(3, 1, Coupling::RackPinion { radius: len(8.0), reverse: true }), Some(Ok(-0.125))); + let screw = ratio(1, 3, Coupling::Screw { pitch: len(std::f64::consts::TAU), reverse: false }); + assert_eq!(screw, Some(Ok(1.0))); + assert!(matches!(ratio(1, 2, Coupling::RackPinion { radius: len(8.0), reverse: false }), Some(Err(_)))); + assert!(matches!(ratio(1, 3, Coupling::Gear { ra: len(1.0), rb: len(1.0), internal: false, reverse: false }), Some(Err(_)))); + for bad in [0.0, -2.0, f64::NAN, f64::INFINITY, 1e300] { + assert!(matches!(ratio(1, 2, Coupling::Gear { ra: len(bad), rb: len(1.0), internal: false, reverse: false }), Some(Err(_))), "{bad}"); + } + assert!(matches!(ratio(1, 2, Coupling::Gear { ra: Size::Expr("nope".into()), rb: len(1.0), internal: false, reverse: false }), Some(Err(_)))); + } + #[test] fn motions_compose() { assert!(close(&motion(JointKind::Revolute, &[std::f64::consts::FRAC_PI_2]), &rot_z(std::f64::consts::FRAC_PI_2))); diff --git a/crates/engine/src/cmd/component_clone_assembly.rs b/crates/engine/src/cmd/component_clone_assembly.rs index a07845abe..88a2f2c97 100644 --- a/crates/engine/src/cmd/component_clone_assembly.rs +++ b/crates/engine/src/cmd/component_clone_assembly.rs @@ -3,7 +3,7 @@ use std::collections::{BTreeMap, BTreeSet}; use solidcraft_doc::Document; -use solidcraft_doc::joints::{Assembly, JointOrigin, Snap}; +use solidcraft_doc::joints::{Assembly, Coupling, JointOrigin, Size, Snap}; use crate::{EngineError, Result}; @@ -105,6 +105,14 @@ fn budget(assembly: &Assembly) -> Result<()> { if !assembly.links.iter().all(|l| l.ratio.is_finite() && l.offset.is_finite()) { return Err(invalid("motion link contains non-finite values")); } + for size in assembly.links.iter().filter_map(|l| l.coupling.as_ref()).flat_map(Coupling::sizes) { + match size { + Size::Length(v) if !v.is_finite() => return Err(invalid("motion link contains non-finite values")), + Size::Expr(e) => text(e)?, + Size::Circle(o) => finite_origin(o)?, + Size::Length(_) => {} + } + } if references > MAX_REFERENCES { return Err(invalid("assembly references exceed the processing budget")); } @@ -291,9 +299,16 @@ pub(super) fn clone_assembly( if !touched_joints.contains(&old.a) && !touched_joints.contains(&old.b) { continue; } + let mut item = old.clone(); + // A gear's picked round faces are on occurrences of the copy too. + let faces = item.coupling.as_mut().is_none_or(|c| { + c.sizes_mut().into_iter().all(|size| match size { + Size::Circle(o) => origin(o, occurrences, features, bodies).map(|new| *o = new).is_some(), + _ => true, + }) + }); match (joints.get(&old.a), joints.get(&old.b)) { - (Some(aa), Some(bb)) => { - let mut item = old.clone(); + (Some(aa), Some(bb)) if faces => { item.a = *aa; item.b = *bb; a.links.push(item); diff --git a/crates/engine/src/cmd/component_clone_assembly_tests.rs b/crates/engine/src/cmd/component_clone_assembly_tests.rs index 6930db751..f9157eabe 100644 --- a/crates/engine/src/cmd/component_clone_assembly_tests.rs +++ b/crates/engine/src/cmd/component_clone_assembly_tests.rs @@ -1,6 +1,6 @@ #![allow(clippy::unwrap_used, clippy::panic)] use super::*; -use solidcraft_doc::joints::{Joint, JointKind, MotionLink, NamedOrigin}; +use solidcraft_doc::joints::{Coupling, Joint, JointKind, MotionLink, NamedOrigin, Size}; use solidcraft_doc::motion::{ContactSet, ExplodedView, MotionStudy, StudyKey}; use solidcraft_doc::{IDENTITY, Occurrence}; use solidcraft_geom::Vec3; @@ -43,8 +43,10 @@ fn documents() -> (Document, Document) { }, NamedOrigin { name: "Outside".into(), origin: at(9) }, ]; - source.assembly.links = - vec![MotionLink { a: 1, ia: 0, b: 2, ib: 0, ratio: -2.0, offset: 0.3 }, MotionLink { a: 1, ia: 0, b: 3, ib: 0, ratio: 1.0, offset: 0.0 }]; + source.assembly.links = vec![ + MotionLink { a: 1, ia: 0, b: 2, ib: 0, ratio: -2.0, offset: 0.3, coupling: None }, + MotionLink { a: 1, ia: 0, b: 3, ib: 0, ratio: 1.0, offset: 0.0, coupling: None }, + ]; source.assembly.contact_sets = vec![ ContactSet { id: 1, name: "Internal contact".into(), occurrences: vec![1, 2], suppressed: true }, ContactSet { id: 2, name: "Cross contact".into(), occurrences: vec![1, 9], suppressed: false }, @@ -96,6 +98,29 @@ fn internal_relationships_receive_independent_ids_and_remapped_typed_references( assert_eq!(source.assembly.joints[0].values[0], 0.25); } +/// A gear's picked round face is on the copy's occurrence and face; one picked on geometry the +/// copy doesn't have is reported, not pointed back at the original. +#[test] +fn copied_gears_take_their_picked_faces_along() { + let (mut source, _) = documents(); + let circle = |face: &str| Size::Circle(JointOrigin { occurrence: 1, snap: Snap::CircleCenter { pick: Vec3::X, face: Some(face.into()) } }); + let gear = |ra| Coupling::Gear { ra, rb: Size::Length(5.0), internal: false, reverse: false }; + source.assembly.links = vec![ + MotionLink { a: 1, ia: 0, b: 2, ib: 0, ratio: -2.0, offset: 0.0, coupling: Some(gear(circle("F1:side"))) }, + MotionLink { a: 2, ia: 0, b: 1, ib: 0, ratio: -0.5, offset: 0.0, coupling: Some(gear(circle("F99:side"))) }, + ]; + let mut destination = source.clone(); + destination.occurrences.extend([101, 102].map(occurrence)); + let report = + clone_assembly(&mut destination, &source, &BTreeMap::from([(1, 101), (2, 102)]), &BTreeMap::from([(1, 11), (10, 110)]), &BTreeMap::new()) + .unwrap(); + let copied = destination.assembly.links.get(2).and_then(|l| l.coupling.clone()); + let Some(Coupling::Gear { ra: Size::Circle(o), .. }) = copied else { panic!("{:?}", destination.assembly.links) }; + assert!(o.occurrence == 101 && matches!(&o.snap, Snap::CircleCenter { face: Some(f), .. } if f == "F11:side"), "{o:?}"); + assert_eq!(destination.assembly.links.len(), 3, "the gear on foreign geometry stays behind"); + assert!(report.iter().any(|m| m.contains("motion link")), "{report:?}"); +} + #[test] fn naming_remaps_exact_tokens_unicode_and_legacy_body_identity() { let features = BTreeMap::from([(1, 21), (10, 30)]); diff --git a/crates/engine/src/cmd/joints.rs b/crates/engine/src/cmd/joints.rs index a6c8e8908..92b42b684 100644 --- a/crates/engine/src/cmd/joints.rs +++ b/crates/engine/src/cmd/joints.rs @@ -7,7 +7,7 @@ use std::collections::{BTreeMap, BTreeSet}; use serde_json::{Value, json}; use solidcraft_doc::expr::Kind; -use solidcraft_doc::joints::{self, Joint, JointKind, JointOrigin, MotionLink, NamedOrigin, Snap}; +use solidcraft_doc::joints::{self, Coupling, Joint, JointKind, JointOrigin, MotionLink, NamedOrigin, Size, Snap}; use solidcraft_geom::{Aabb3, Vec3}; use super::CommandSpec; @@ -40,6 +40,23 @@ pub static COMMANDS: &[CommandSpec] = &[ .at("SOLID", "ASSEMBLE") .icon("motion_link") .params("a, b: joints; ratio (b = ratio · a + offset): b's units per a's (mm per deg for an angle driving a distance); offset?: in b's units (deg for an angle, mm for a distance, or an expression); ia?, ib?: value indices (default 0)"), + CommandSpec::new("joint.gear", "Gear", gear).at("SOLID", "ASSEMBLE").icon("gear").params( + "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", + ), + 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", + ), + 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", + ), CommandSpec::new("joint.limits", "Joint Limits", limits).params("joint; index?: value index (default 0); min?, max? (omit both to clear)"), CommandSpec::new("joint.edit", "Edit Joint", edit).params("joint; type?, flip?, offset?, angle?, suppressed?, name?"), CommandSpec::new("joint.delete", "Delete Joint", delete).params("joint: id|name (or origin: name, link: index)"), @@ -53,11 +70,40 @@ pub static COMMANDS: &[CommandSpec] = &[ ), ]; -/// Re-solve the joints and move the occurrences they place (after any edit). +/// 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 { + recouple(s); resolve_holding(s, &BTreeMap::new()) } +/// Work out the ratios of the coupled motion links again (a radius or a parameter may have +/// changed). A coupling that can't be worked out (its face gone) keeps its last ratio; +/// `joint.list` says why. +fn recouple(s: &mut Session) { + if s.doc.assembly.links.iter().all(|l| l.coupling.is_none()) { + return; + } + let st = s.model.state(); + let changed: Vec<(usize, f64)> = s + .doc + .assembly + .links + .iter() + .enumerate() + .filter_map(|(i, l)| joints::coupling_ratio(&s.doc, &st, l)?.ok().filter(|r| *r != l.ratio).map(|r| (i, r))) + .collect(); + if changed.is_empty() { + return; + } + let doc = s.doc_mut(); + for (i, r) in changed { + if let Some(l) = doc.assembly.links.get_mut(i) { + l.ratio = r; + } + } +} + /// Re-solve the joints, keeping the `held` values (the ones being driven, mapped to the values /// they move from) where loops are closed. pub fn resolve_holding(s: &mut Session, held: &joints::Held) -> joints::Solution { @@ -101,6 +147,14 @@ pub(crate) fn named_values(j: &Joint, q: &[f64]) -> Vec { .collect() } +/// A joint's values as the solver places it (after motion links, so a screw's travel follows its +/// turn), named as `joint.list` gives them. +pub(crate) fn effective_values(s: &Session, id: u64) -> Option> { + let j = s.doc.assembly.joints.iter().find(|j| j.id == id)?; + let vals = joints::joint_values(&s.doc.assembly); + Some(named_values(j, vals.get(&id).map(Vec::as_slice).unwrap_or(&j.values))) +} + fn occurrence_name(s: &Session, id: u64) -> String { s.doc.occurrences.iter().find(|o| o.id == id).map(|o| o.name.clone()).unwrap_or_else(|| id.to_string()) } @@ -495,7 +549,7 @@ fn drive(s: &mut Session, p: &Value) -> Result { let sol = joints::solve(&s.doc, &s.model.state()); let mut out = sol_json(&sol, p); out["joint"] = json!(id); - out["values"] = json!(s.doc.assembly.joints.iter().find(|j| j.id == id).map(|j| named_values(j, &j.values))); + out["values"] = json!(effective_values(s, id)); out["stopped_by_contact"] = r["stopped_by_contact"].clone(); out["stopped_by_loop"] = r["stopped_by_loop"].clone(); out["moved"] = json!(super::motion::moved(&before, &super::motion::positions(s)).next().is_some()); @@ -526,11 +580,149 @@ fn motion_link(s: &mut Session, p: &Value) -> Result { None => 0.0, }; let ratio = ratio * ratio_scale(s, a, ia, b, ib); - s.doc_mut().assembly.links.push(MotionLink { a, ia, b, ib, ratio, offset }); + s.doc_mut().assembly.links.push(MotionLink { a, ia, b, ib, ratio, offset, coupling: None }); let sol = resolve(s); Ok(sol_json(&sol, p)) } +/// A coupling length: a number (mm), an expression (kept as typed, so it follows the +/// parameters), or `{circle: [x, y, z], occurrence?}`: the round face there, by its radius. +fn size_param(s: &Session, p: &Value, key: &str, cmd: &str) -> Result { + match p.get(key) { + Some(Value::Number(n)) => n.as_f64().map(Size::Length).ok_or_else(|| bad(cmd, format!("`{key}` must be a finite length"))), + Some(Value::String(t)) if t.len() <= 1000 => Ok(Size::Expr(t.trim().to_string())), + Some(o @ Value::Object(m)) if m.contains_key("circle") => Ok(Size::Circle(origin_param(s, Some(o), cmd)?)), + _ => Err(bad(cmd, format!("`{key}` must be a length (mm or an expression) or a round face ({{circle: [x, y, z]}})"))), + } +} + +/// A joint's first value that turns (an angle), or that travels (a distance). +fn value_index(s: &Session, id: u64, turn: bool) -> Option { + let j = s.doc.assembly.joints.iter().find(|j| j.id == id)?; + (0..j.kind.dofs().len()).find(|i| j.kind.is_angle(*i) == turn) +} + +/// The values a rack or a screw couples: a's turn and b's travel, or a's travel and b's turn. +fn turn_and_travel(s: &Session, a: u64, b: u64, cmd: &str) -> Result<(usize, usize)> { + match (value_index(s, a, true), value_index(s, b, false), value_index(s, a, false), value_index(s, b, true)) { + (Some(ia), Some(ib), ..) | (_, _, Some(ia), Some(ib)) => Ok((ia, ib)), + _ => Err(bad(cmd, "couple a joint that turns (revolute) with one that slides (slider)")), + } +} + +/// Two different joints `a` and `b`. +fn joint_pair(s: &Session, p: &Value, cmd: &str) -> Result<(u64, u64)> { + let (a, b) = (joint_id(s, p.get("a"), cmd)?, joint_id(s, p.get("b"), cmd)?); + if a == b { + return Err(bad(cmd, "couple two different joints")); + } + Ok((a, b)) +} + +fn reverse(p: &Value) -> bool { + bool_(p, "reverse").unwrap_or(false) +} + +fn gear(s: &mut Session, p: &Value) -> Result { + let cmd = "joint.gear"; + let (a, b) = joint_pair(s, p, cmd)?; + let turn = |id: u64| value_index(s, id, true).ok_or_else(|| bad(cmd, "gears need two joints that turn (revolute)")); + let (ia, ib) = (turn(a)?, turn(b)?); + let c = Coupling::Gear { + ra: size_param(s, p, "ra", cmd)?, + rb: size_param(s, p, "rb", cmd)?, + internal: bool_(p, "internal").unwrap_or(false), + reverse: reverse(p), + }; + couple(s, p, cmd, MotionLink { a, ia, b, ib, ratio: 1.0, offset: 0.0, coupling: Some(c) }) +} + +fn rack_pinion(s: &mut Session, p: &Value) -> Result { + let cmd = "joint.rack_pinion"; + let (a, b) = joint_pair(s, p, cmd)?; + let (ia, ib) = turn_and_travel(s, a, b, cmd)?; + let c = Coupling::RackPinion { radius: size_param(s, p, "radius", cmd)?, reverse: reverse(p) }; + couple(s, p, cmd, MotionLink { a, ia, b, ib, ratio: 1.0, offset: 0.0, coupling: Some(c) }) +} + +fn screw(s: &mut Session, p: &Value) -> Result { + let cmd = "joint.screw"; + let (a, ia, b, ib) = match p.get("joint") { + Some(v) => { + let id = joint_id(s, Some(v), cmd)?; + match (value_index(s, id, true), value_index(s, id, false)) { + (Some(ia), Some(ib)) => (id, ia, id, ib), + _ => return Err(bad(cmd, "a screw on one joint needs a joint that turns and slides (cylindrical); or give a and b")), + } + } + None => { + let (a, b) = joint_pair(s, p, cmd)?; + let (ia, ib) = turn_and_travel(s, a, b, cmd)?; + (a, ia, b, ib) + } + }; + let c = Coupling::Screw { pitch: size_param(s, p, "pitch", cmd)?, reverse: reverse(p) }; + couple(s, p, cmd, MotionLink { a, ia, b, ib, ratio: 1.0, offset: 0.0, coupling: Some(c) }) +} + +/// 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). +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") { + None => None, + Some(v) => { + Some(v.as_u64().and_then(|i| usize::try_from(i).ok()).filter(|i| *i < links.len()).ok_or_else(|| bad(cmd, "no such motion link"))?) + } + }; + if replace.is_none() && links.len() >= joints::MAX_JOINTS { + return Err(bad(cmd, "too many motion links")); + } + let others: Vec<&MotionLink> = links.iter().enumerate().filter(|(i, _)| Some(*i) != replace).map(|(_, k)| k).collect(); + let name = |id: u64| s.doc.assembly.joints.iter().find(|j| j.id == id).map(|j| j.name.clone()).unwrap_or_default(); + if others.iter().any(|k| (k.b, k.ib) == (l.b, l.ib)) { + return Err(bad(cmd, format!("{} already follows a motion link: couple it the other way round (as a)", name(l.b)))); + } + // The values that set a's, back through the links: b among them would make a cycle. + let mut at = (l.a, l.ia); + for _ in 0..=others.len() { + if at == (l.b, l.ib) { + return Err(bad(cmd, format!("{} already drives {} through motion links", name(l.b), name(l.a)))); + } + match others.iter().find(|k| (k.b, k.ib) == at) { + Some(k) => at = (k.a, k.ia), + None => break, + } + } + l.ratio = joints::coupling_ratio(&s.doc, &s.model.state(), &l).unwrap_or(Ok(l.ratio)).map_err(|e| bad(cmd, e.to_string()))?; + let vals = joints::joint_values(&s.doc.assembly); + let value = |id: u64, i: usize| vals.get(&id).and_then(|q| q.get(i)).copied().unwrap_or(0.0); + // A link put in place of another keeps its offset, as a radius edited in the design does. + l.offset = match replace.and_then(|i| links.get(i)) { + Some(old) => old.offset, + None => value(l.b, l.ib) - l.ratio * value(l.a, l.ia), + }; + let shown = l.ratio / ratio_scale(s, l.a, l.ia, l.b, l.ib); + let doc = s.doc_mut(); + let index = match replace { + Some(i) => { + if let Some(slot) = doc.assembly.links.get_mut(i) { + *slot = l; + } + i + } + None => { + doc.assembly.links.push(l); + doc.assembly.links.len() - 1 + } + }; + let sol = resolve(s); + let mut out = sol_json(&sol, p); + out["link"] = json!(index); + out["ratio"] = json!(shown); + Ok(out) +} + fn is_angle(s: &Session, joint: u64, i: usize) -> bool { s.doc.assembly.joints.iter().find(|j| j.id == joint).is_some_and(|j| j.kind.is_angle(i)) } @@ -666,7 +858,15 @@ fn list(s: &mut Session, p: &Value) -> Result { 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); - json!({"a": l.a, "ia": l.ia, "b": l.b, "ib": l.ib, "ratio": ratio, "offset": offset, "unit": if angle { "deg" } else { "mm" }}) + 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_ratio(&s.doc, &st, l) { + v["error"] = json!(e.to_string()); + } + } + v }) .collect(); let origins: Vec = s.doc.assembly.origins.iter().map(|o| json!({"name": o.name, "occurrence": o.origin.occurrence})).collect(); diff --git a/crates/engine/src/cmd/joints_coupling_tests.rs b/crates/engine/src/cmd/joints_coupling_tests.rs new file mode 100644 index 000000000..afdbb67e6 --- /dev/null +++ b/crates/engine/src/cmd/joints_coupling_tests.rs @@ -0,0 +1,255 @@ +//! Gears, racks and screws: motion links whose ratio comes from radii or a pitch. Expected values +//! are analytic: a gear train turns by the ratio of its radii, a rack travels r·θ, a screw +//! advances its pitch per turn. + +use super::*; +use solidcraft_doc::joints::{Coupling, Size}; + +/// A joint's value as `joint.list` gives it (degrees or mm). +fn shown(s: &mut Session, joint: &str) -> f64 { + let l = run(s, "joint.list", json!({"quiet": true})); + let j = l["joints"].as_array().into_iter().flatten().find(|j| j["name"] == joint).cloned().unwrap_or_default(); + j["values"][0]["value"].as_f64().unwrap_or(f64::NAN) +} + +fn close_to(got: f64, want: f64) -> bool { + (got - want).abs() < 1e-6 +} + +/// 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) { + 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) { + part(s, "Base", [-60.0, -60.0, -20.0]); + let g = occ(s, "Base"); + run(s, "occurrence.ground", json!({"occurrence": g, "grounded": true})); +} + +/// Gears of pitch radii r1 (a parameter), 20 and 15 in a row: G1 meshes G2 (radii picked on their +/// discs), G2 meshes G3 (radii typed). +fn gear_train() -> Session { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "r1", "expression": "10 mm"})); + base(&mut s); + disc(&mut s, "G1", 0.0, "r1"); + disc(&mut s, "G2", 30.0, "20 mm"); + disc(&mut s, "G3", 65.0, "15 mm"); + let r = run( + &mut s, + "joint.gear", + json!({"a": "G1", "b": "G2", "ra": {"occurrence": "G1", "circle": [10, 0, 2.5]}, "rb": {"occurrence": "G2", "circle": [50, 0, 2.5]}}), + ); + assert_eq!((r["link"].clone(), r["ratio"].as_f64().map(|x| close_to(x, -0.5))), (json!(0), Some(true)), "{r}"); + run(&mut s, "joint.gear", json!({"a": "G2", "b": "G3", "ra": 20, "rb": "15 mm"})); + s +} + +/// A point on a disc's rim, where the disc is placed. +fn rim(s: &Session, name: &str, x: f64, r: f64) -> Vec3 { + place(s, name, Vec3::new(x + r, 0.0, 2.5)) +} + +fn turned(x: f64, r: f64, deg: f64) -> Vec3 { + let a = deg.to_radians(); + Vec3::new(x + r * a.cos(), r * a.sin(), 2.5) +} + +#[test] +fn a_gear_train_of_three_turns_by_its_radii() { + let mut s = gear_train(); + let r = run(&mut s, "joint.drive", json!({"joint": "G1", "value": 90})); + assert_eq!(r["conflicts"].as_array().map(Vec::len), Some(0), "{r}"); + // ω2 = −ω1·r1/r2, ω3 = −ω2·r2/r3 = ω1·r1/r3: external gears turn the other way. + assert!(close_to(shown(&mut s, "G2"), -45.0) && close_to(shown(&mut s, "G3"), 60.0), "{}", run(&mut s, "joint.list", json!({}))); + for (name, x, r, deg) in [("G1", 0.0, 10.0, 90.0), ("G2", 30.0, 20.0, -45.0), ("G3", 65.0, 15.0, 60.0)] { + assert!(near(rim(&s, name, x, r), turned(x, r, deg)), "{name}: {:?}", rim(&s, name, x, r)); + } + // The picked radius follows the design: G1 grows to 12, so G2 turns 90·12/20. + run(&mut s, "parameters.change", json!({"name": "r1", "expression": "12 mm"})); + assert!(close_to(shown(&mut s, "G2"), -54.0) && close_to(shown(&mut s, "G3"), 72.0), "{}", run(&mut s, "joint.list", json!({}))); + let l = run(&mut s, "joint.list", json!({})); + assert!(close_to(l["links"][0]["ratio"].as_f64().unwrap_or(f64::NAN), -0.6), "{l}"); + assert_eq!(l["links"][0]["coupling"]["type"], "gear", "{l}"); + // A motion study playing G1 turns the train the same way. + 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. + 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}"); + 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!({}))); + // Undo takes the redefinition back. + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.assembly.links.get(1).and_then(|l| l.coupling.clone()).map(|c| matches!(c, Coupling::Gear { internal: false, .. })), Some(true)); +} + +#[test] +fn gears_save_and_open_with_their_definition() { + let mut s = gear_train(); + run(&mut s, "joint.drive", json!({"joint": "G1", "value": 30})); + let text = s.doc.to_json(); + let back = solidcraft_doc::format::read(&text).unwrap_or_else(|e| panic!("{e}")); + assert_eq!(back.assembly.links, s.doc.assembly.links); + assert!(matches!(back.assembly.links.first().and_then(|l| l.coupling.as_ref()), Some(Coupling::Gear { ra: Size::Circle(_), .. }))); + // A link saved before couplings (no `coupling`) opens as a plain link. + let mut v: Value = serde_json::from_str(&text).unwrap_or_default(); + for l in v["assembly"]["links"].as_array_mut().into_iter().flatten() { + l.as_object_mut().map(|o| o.remove("coupling")); + } + let old = solidcraft_doc::format::read(&v.to_string()).unwrap_or_else(|e| panic!("{e}")); + assert!(old.assembly.links.iter().all(|l| l.coupling.is_none()) && old.assembly.links.len() == 2); +} + +/// A pinion of radius 8 about +Z at the origin, a rack under it sliding along +X, and a stop the +/// rack runs into after 10 mm. +fn rack() -> Session { + let mut s = Session::default(); + base(&mut s); + disc(&mut s, "Pinion", 0.0, "8 mm"); + for (name, corner, length) in [("Rack", [-20.0, -14.0, 0.0], 40.0), ("Stop", [30.0, -14.0, 0.0], 4.0)] { + run(&mut s, "component.activate", json!({"component": "root"})); + run(&mut s, "component.create", json!({"name": name})); + run(&mut s, "solid.box", json!({"length": length, "width": 4, "height": 4, "corner": corner})); + } + pin(&mut s, "slider", "Rail", "Base", "Rack", Vec3::new(0.0, -10.0, 0.0), Vec3::X); + pin(&mut s, "rigid", "Stop", "Base", "Stop", Vec3::new(30.0, -10.0, 0.0), Vec3::Z); + s +} + +#[test] +fn a_rack_travels_r_times_theta() { + let mut s = rack(); + let r = run(&mut s, "joint.rack_pinion", json!({"a": "Pinion", "b": "Rail", "radius": {"occurrence": "Pinion", "circle": [8, 0, 2]}})); + // Per degree in the answer, as joint.list gives a link between an angle and a distance. + assert!(close_to(r["ratio"].as_f64().unwrap_or(f64::NAN), 8f64.to_radians()), "{r}"); + run(&mut s, "joint.drive", json!({"joint": "Pinion", "value": 45})); + let travel = 8.0 * std::f64::consts::FRAC_PI_4; + assert!(close_to(shown(&mut s, "Rail"), travel), "{}", shown(&mut s, "Rail")); + // The pinion turns counter-clockwise about +Z; its bottom, where the rack is, moves along +X. + assert!(near(place(&s, "Rack", Vec3::new(-20.0, -14.0, 0.0)), Vec3::new(-20.0 + travel, -14.0, 0.0))); + // Contact sets hold the rack at the stop, and the pinion with it: 10 mm is 10/8 rad. + run(&mut s, "contact.create", json!({"occurrences": ["Rack", "Stop"]})); + let r = run(&mut s, "joint.drive", json!({"joint": "Pinion", "value": 180})); + assert!(r["stopped_by_contact"].is_object(), "{r}"); + let (angle, travel) = (shown(&mut s, "Pinion"), shown(&mut s, "Rail")); + assert!((angle.to_radians() - 1.25).abs() < 0.01, "{angle}"); + assert!(close_to(travel, 8.0 * angle.to_radians()), "{travel} at {angle}°"); + // Either may drive: the rack turning the pinion, reversed. + let mut s = rack(); + let r = run(&mut s, "joint.rack_pinion", json!({"a": "Rail", "b": "Pinion", "radius": "8 mm", "reverse": true})); + assert!(close_to(r["ratio"].as_f64().unwrap_or(f64::NAN), -1.0 / 8f64.to_radians()), "{r}"); + run(&mut s, "joint.drive", json!({"joint": "Rail", "value": 5})); + assert!(close_to(shown(&mut s, "Pinion"), -(5.0f64 / 8.0).to_degrees()), "{}", shown(&mut s, "Pinion")); +} + +#[test] +fn a_screw_advances_its_pitch_per_turn() { + 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); + run(&mut s, "joint.screw", json!({"joint": "Thread", "pitch": 1.5})); + let r = run(&mut s, "joint.drive", json!({"joint": "Thread", "values": [720]})); + assert_eq!(r["conflicts"].as_array().map(Vec::len), Some(0), "{r}"); + 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. + 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}"); + // 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"})); + base(&mut s); + part(&mut s, "Shaft", [-1.0, -1.0, 0.0]); + part(&mut s, "Carriage", [10.0, -1.0, 0.0]); + pin(&mut s, "revolute", "Spin", "Base", "Shaft", Vec3::ZERO, Vec3::Z); + pin(&mut s, "slider", "Lift", "Base", "Carriage", Vec3::new(11.0, 0.0, 0.0), Vec3::Z); + run(&mut s, "joint.screw", json!({"a": "Spin", "b": "Lift", "pitch": "lead"})); + run(&mut s, "joint.drive", json!({"joint": "Spin", "value": 900})); + assert!(close_to(shown(&mut s, "Lift"), 5.0), "{}", shown(&mut s, "Lift")); + run(&mut s, "parameters.change", json!({"name": "lead", "expression": "4 mm"})); + assert!(close_to(shown(&mut s, "Lift"), 10.0), "{}", shown(&mut s, "Lift")); +} + +/// A motor gear turns the four-bar's crank: half as fast, the other way round, and the loop +/// follows. +#[test] +fn a_gear_drives_a_closed_loop() { + let (mut s, _, q0) = four_bar(); + part(&mut s, "Motor", [80.0, -1.0, -5.0]); + pin(&mut s, "revolute", "Motor", "Ground", "Motor", Vec3::new(80.0, 0.0, 0.0), Vec3::Z); + run(&mut s, "joint.gear", json!({"a": "Motor", "b": "Crank", "ra": 10, "rb": 20})); + let r = run(&mut s, "joint.drive", json!({"joint": "Motor", "value": -120})); + assert_eq!(r["conflicts"].as_array().map(Vec::len), Some(0), "{r}"); + assert!(r["stopped_by_loop"].is_null(), "{r}"); + assert!(close_to(shown(&mut s, "Crank"), 60.0), "{}", shown(&mut s, "Crank")); + assert!(near(place(&s, "Rocker", q0), rocker_pin(0.0, 60.0, q0)), "{:?}", place(&s, "Rocker", q0)); +} + +/// A pinion moves the piston of a slider-crank: the piston travels r·θ along its bore and the +/// crank follows, the rod keeping its length. +#[test] +fn a_rack_drives_a_slider_crank_from_its_piston() { + let (mut s, p0, s0) = slider_crank(); + part(&mut s, "Pinion", [0.0, -30.0, -5.0]); + pin(&mut s, "revolute", "Pinion", "Ground", "Pinion", Vec3::new(0.0, -30.0, 0.0), Vec3::Z); + run(&mut s, "joint.rack_pinion", json!({"a": "Pinion", "b": "Bore", "radius": 5})); + let r = run(&mut s, "joint.drive", json!({"joint": "Pinion", "value": 60})); + assert_eq!(r["conflicts"].as_array().map(Vec::len), Some(0), "{r}"); + assert!(r["stopped_by_loop"].is_null(), "{r}"); + let travel = 5.0 * 60f64.to_radians(); + assert!(close_to(shown(&mut s, "Bore"), travel), "{}", shown(&mut s, "Bore")); + let wrist = place(&s, "Piston", s0); + assert!(near(wrist, s0 + Vec3::X * travel), "{wrist:?}"); + let pin_at = place(&s, "Rod", p0); + assert!((pin_at.dist(wrist) - 40.0).abs() < 1e-6 && (pin_at.len() - 15.0).abs() < 1e-6, "{pin_at:?}"); +} + +#[test] +fn couplings_refuse_what_they_cannot_couple() { + let mut s = gear_train(); + let refused = |s: &mut Session, id: &str, p: Value| s.execute(id, &p).err().map(|e| e.to_string()).unwrap_or_default(); + // G3 already follows G2; a second writer, or a cycle back to G1, is refused. + assert!(refused(&mut s, "joint.gear", json!({"a": "G1", "b": "G3", "ra": 1, "rb": 1})).contains("already follows")); + assert!(refused(&mut s, "joint.gear", json!({"a": "G3", "b": "G1", "ra": 1, "rb": 1})).contains("already drives")); + assert!(refused(&mut s, "joint.gear", json!({"a": "G1", "b": "G1", "ra": 1, "rb": 1})).contains("two different")); + // A gear needs turns, a rack a turn and a travel. + assert!(refused(&mut s, "joint.rack_pinion", json!({"a": "G1", "b": "G3", "radius": 5})).contains("slides")); + // Hostile sizes and indices never panic and change nothing. + let before = s.doc.assembly.clone(); + for bad in [ + json!(-3), + json!(0), + json!(1e300), + json!("nope"), + json!("1/0"), + json!({"circle": [1e308, 0, 0]}), + json!({"circle": "x"}), + json!([1]), + Value::Null, + ] { + for (id, p) in [ + ("joint.gear", json!({"a": "G3", "b": "G1", "ra": bad, "rb": 1})), + ("joint.gear", json!({"a": "G1", "b": "G2", "ra": 1, "rb": bad, "link": 0})), + ("joint.rack_pinion", json!({"a": "G1", "b": "G2", "radius": bad})), + ("joint.screw", json!({"joint": "G1", "pitch": bad})), + ] { + assert!(s.execute(id, &p).is_err(), "{id} {p}"); + } + } + for bad in [json!(-1), json!(2), json!(1.5), json!(1e300), json!("0"), json!([0]), Value::Null] { + let p = json!({"a": "G1", "b": "G2", "ra": 1, "rb": 1, "link": bad}); + assert!(s.execute("joint.gear", &p).is_err(), "{p}"); + } + assert_eq!(s.doc.assembly, before); +} diff --git a/crates/engine/src/cmd/joints_tests.rs b/crates/engine/src/cmd/joints_tests.rs index 7d7a32902..1c86e632c 100644 --- a/crates/engine/src/cmd/joints_tests.rs +++ b/crates/engine/src/cmd/joints_tests.rs @@ -1178,3 +1178,6 @@ fn a_new_joint_starts_inside_its_limits_and_says_so() { let r = run(&mut s, "joint.as_built", json!({"type": "cylindrical", "a": "A", "b": "B", "name": "Spindle", "limits": [[-30, 30], [0, 5]]})); assert!(r.get("warnings").is_none(), "{r}"); } + +#[path = "joints_coupling_tests.rs"] +mod coupling; diff --git a/crates/engine/src/cmd/motion.rs b/crates/engine/src/cmd/motion.rs index de82075ee..33332ca01 100644 --- a/crates/engine/src/cmd/motion.rs +++ b/crates/engine/src/cmd/motion.rs @@ -10,7 +10,7 @@ use solidcraft_geom::Vec3; use solidcraft_kernel::Body; use super::CommandSpec; -use super::joints::{cannot_move, joint_id, named_values, occurrence_id, resolve_holding, value}; +use super::joints::{cannot_move, effective_values, joint_id, occurrence_id, resolve_holding, value}; use crate::params::{bad, bool_, str_, vec3}; use crate::{EngineError, Result, Session}; @@ -350,10 +350,7 @@ fn drive_with_contact(s: &mut Session, want: &[(u64, Vec)], given: &BTreeSe stopped = None; stopped_by_loop = Some(json!({"joint": name, "fraction": lo})); } - let values: Vec = want - .iter() - .map(|(id, _)| json!({"joint": id, "values": s.doc.assembly.joints.iter().find(|j| j.id == *id).map(|j| named_values(j, &j.values))})) - .collect(); + let values: Vec = want.iter().map(|(id, _)| json!({"joint": id, "values": effective_values(s, *id)})).collect(); let out = json!({"values": values, "stopped_by_contact": stopped, "stopped_by_loop": stopped_by_loop, "conflicts": sol.conflicts.len()}); Ok((out, sol)) } diff --git a/crates/ui-egui/src/dialogs_assembly.rs b/crates/ui-egui/src/dialogs_assembly.rs index 5c6a7e155..3010838ef 100644 --- a/crates/ui-egui/src/dialogs_assembly.rs +++ b/crates/ui-egui/src/dialogs_assembly.rs @@ -1,5 +1,5 @@ //! Assembly dialogs: New Component, Joint, As-built Joint, Joint Origin, Rigid Group, Drive -//! Joints, Motion Link and Interference. Joint origins are picked by hovering geometry: a face +//! Joints, Motion Link, Gear, Rack and Pinion, Screw (`dialogs_coupling`) and Interference. Joint origins are picked by hovering geometry: a face //! snaps to its centre (or a round face to the centre of its nearer end), an edge to its middle //! (a round edge to its centre), a vertex to itself; the snap shows as a glyph with its z axis //! before the click. Joints and drives preview on the placed (world) model: the moving @@ -27,8 +27,19 @@ const TYPE_LABELS: [&str; 7] = ["Rigid", "Revolute", "Slider", "Cylindrical", "P /// What a joint origin input accepts (snaps on faces, edges and vertices). const SNAPS: u16 = FACES | EDGES | VERTICES; /// Commands whose effect is where occurrences sit (previewed on the placed model). -const MOVES: [&str; 8] = - ["joint.create", "joint.as_built", "joint.drive", "joint.edit", "joint.limits", "joint.rigid_group", "parts.insert", "parts.fastener"]; +const MOVES: [&str; 11] = [ + "joint.create", + "joint.as_built", + "joint.drive", + "joint.edit", + "joint.limits", + "joint.rigid_group", + "joint.gear", + "joint.rack_pinion", + "joint.screw", + "parts.insert", + "parts.fastener", +]; #[derive(Clone, Debug)] pub enum Asm { @@ -56,6 +67,7 @@ pub enum Asm { ratio: String, offset: String, }, + Coupling(Box), Interference { result: Option, overlaps: Vec, @@ -128,12 +140,17 @@ impl Asm { Asm::RigidGroup => "RIGID GROUP", Asm::Drive { .. } => "DRIVE JOINTS", Asm::MotionLink { .. } => "MOTION LINK", + Asm::Coupling(f) => match f.command { + "joint.gear" => "GEAR", + "joint.rack_pinion" => "RACK AND PINION", + _ => "SCREW", + }, Asm::Interference { .. } => "INTERFERENCE", } } pub fn previews(&self) -> bool { - matches!(self, Asm::Joint(_) | Asm::Drive { .. } | Asm::RigidGroup) + matches!(self, Asm::Joint(_) | Asm::Drive { .. } | Asm::RigidGroup | Asm::Coupling(_)) } } @@ -166,6 +183,7 @@ pub fn start(app: &SolveApp, id: &str) -> Option<(Kind, Vec)> { let b = usize::from(movable(s).len() > 1); (Asm::MotionLink { a: 0, b, ia: 0, ib: 0, ratio: "1".into(), offset: "0".into() }, vec![]) } + "joint.gear" | "joint.rack_pinion" | "joint.screw" => crate::dialogs_coupling::start(app, id)?, "inspect.interference" => { (Asm::Interference { result: None, overlaps: Vec::new(), of: Vec::new() }, vec![SelInput::new("Bodies (all if none)", BODIES, true)]) } @@ -657,6 +675,7 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Asm, inputs: &mut [Se enter |= field(ui, offset); ui.end_row(); } + Asm::Coupling(f) => enter |= crate::dialogs_coupling::rows(app, ui, f, inputs), Asm::Interference { result, overlaps, of } => { let picked: Vec = inputs.first().map(|i| i.items.clone()).unwrap_or_default(); row_label(ui, ""); @@ -883,6 +902,7 @@ pub fn commands(app: &SolveApp, k: &Asm, inputs: &[SelInput]) -> Result return crate::dialogs_coupling::commands(app, f, inputs), // The check runs from its Compute button; OK only closes. Asm::Interference { .. } => Vec::new(), }) @@ -890,6 +910,9 @@ pub fn commands(app: &SolveApp, k: &Asm, inputs: &[SelInput]) -> Result) { + if let Asm::Coupling(f) = k { + crate::dialogs_coupling::animate(&app.session, f, cmds); + } let Asm::Joint(f) = k else { return }; if !f.animate { return; diff --git a/crates/ui-egui/src/dialogs_coupling.rs b/crates/ui-egui/src/dialogs_coupling.rs new file mode 100644 index 000000000..2cda97f64 --- /dev/null +++ b/crates/ui-egui/src/dialogs_coupling.rs @@ -0,0 +1,279 @@ +//! The Gear, Rack and Pinion and Screw dialogs: two joints coupled by radii or a pitch +//! (`joint.gear`, `joint.rack_pinion`, `joint.screw`). A radius is typed, or comes from the round +//! face picked on the part, and then follows that face when the design changes. Picking a gear's +//! face also picks the joint it turns on. Play turns the driving joint so the coupling shows its +//! motion before OK. + +use egui::RichText; +use serde_json::{Value, json}; +use solidcraft_engine::Sel; +use solidcraft_engine::Session; +use solidcraft_engine::doc::expr::Kind as ValueKind; + +use crate::SolveApp; +use crate::dialogs::{check, combo, field, row_label}; +use crate::dialogs_assembly::Asm; +use crate::selection::{EDGES, FACES, SelInput}; +use crate::theme::Tokens; + +/// What a round-face input takes: a face, or an edge of one. +const ROUND: u16 = FACES | EDGES; + +#[derive(Clone, Debug)] +pub struct CouplingForm { + /// `joint.gear`, `joint.rack_pinion` or `joint.screw`. + pub command: &'static str, + /// The driving joint and the driven one (ids; the same cylindrical joint for a screw on one). + pub a: u64, + pub b: u64, + /// Typed sizes, used where no round face is picked: gear 1's and gear 2's radii, the pinion's + /// radius, or the screw's pitch. + pub sizes: [String; 2], + pub internal: bool, + pub reverse: bool, + /// The bodies of the picks the joints were last chosen from, so a pick chooses once. + pub picked: [Option; 2], + pub animate: bool, + /// Animation phase, 0…1. + pub phase: f64, +} + +/// Joints with a value that turns (`turn`) or slides: (id, label). +fn joints_that(s: &Session, turn: bool) -> Vec<(u64, String)> { + s.doc + .assembly + .joints + .iter() + .filter(|j| (0..j.kind.dofs().len()).any(|i| j.kind.is_angle(i) == turn)) + .map(|j| (j.id, format!("{} ({:?})", j.name, j.kind))) + .collect() +} + +/// The joint roles and whether the driven one turns (a gear) or slides. +fn roles(command: &str) -> ([&'static str; 2], bool) { + match command { + "joint.gear" => (["Gear 1", "Gear 2"], true), + "joint.rack_pinion" => (["Pinion", "Rack"], false), + _ => (["Screw", "Nut"], false), + } +} + +pub fn start(app: &SolveApp, id: &str) -> Option<(Asm, Vec)> { + let s = &app.session; + let (_, turn_b) = roles(id); + let (turns, b_list) = (joints_that(s, true), joints_that(s, turn_b)); + let first = |l: &[(u64, String)]| l.first().map(|j| j.0).unwrap_or(0); + let (command, a, b, sizes, inputs) = match id { + "joint.gear" => ( + "joint.gear", + first(&turns), + turns.get(1).map(|j| j.0).unwrap_or(0), + ["10 mm".to_string(), "20 mm".to_string()], + vec![SelInput::new("Gear 1 (optional)", ROUND, false), SelInput::new("Gear 2 (optional)", ROUND, false)], + ), + "joint.rack_pinion" => ( + "joint.rack_pinion", + first(&turns), + first(&b_list), + ["10 mm".to_string(), String::new()], + vec![SelInput::new("Pinion (optional)", ROUND, false)], + ), + "joint.screw" => { + // A joint that turns and slides is a screw on its own. + let both = turns.iter().find(|t| b_list.iter().any(|l| l.0 == t.0)).map(|t| t.0); + let a = both.unwrap_or(first(&turns)); + ("joint.screw", a, both.unwrap_or(first(&b_list)), ["1.5 mm".to_string(), String::new()], vec![]) + } + _ => return None, + }; + let f = CouplingForm { command, a, b, sizes, internal: false, reverse: false, picked: [None, None], animate: false, phase: 0.0 }; + Some((Asm::Coupling(Box::new(f)), inputs)) +} + +/// The occurrence placing a picked body (0: the root), by the body's placement: each instance of +/// a copied gear is an occurrence of its own. +fn occurrence(s: &Session, body: &str) -> Option { + s.doc.body_frames(&s.model.state()).into_iter().find(|f| f.0 == body).map(|(_, _, path, _)| path.last().copied().unwrap_or(0)) +} + +fn pick(inputs: &[SelInput], i: usize) -> Option<(&str, solidcraft_engine::geom::Vec3)> { + match inputs.get(i)?.items.first()? { + Sel::Face { body, point, .. } | Sel::Edge { body, point, .. } => Some((body.as_str(), *point)), + _ => None, + } +} + +/// The radius of the round face picked in input `i`. +fn picked_radius(s: &Session, inputs: &[SelInput], i: usize) -> Option { + let (body, point) = pick(inputs, i)?; + let st = s.world_state(); + solidcraft_engine::kernel::cylinder_face_at(&st.body(body)?.body, point).map(|c| c.radius) +} + +/// Size `i` in mm: the picked face's radius, or the typed one. +fn size(s: &Session, f: &CouplingForm, inputs: &[SelInput], i: usize) -> Option { + picked_radius(s, inputs, i).or_else(|| s.doc.eval(f.sizes.get(i)?, ValueKind::Length).ok()).filter(|v| v.is_finite() && *v > 0.0) +} + +/// A joint row: the joints `list` offers, `sel` the chosen id. +fn joint_row(ui: &mut egui::Ui, label: &str, salt: &str, list: &[(u64, String)], sel: &mut u64) { + let labels: Vec<&str> = list.iter().map(|j| j.1.as_str()).collect(); + let mut pos = list.iter().position(|j| j.0 == *sel).unwrap_or(0); + row_label(ui, label); + combo(ui, salt, &labels, &mut pos); + ui.end_row(); + *sel = list.get(pos).map(|j| j.0).unwrap_or(0); +} + +/// The dialog's rows; true when Enter was pressed in a value. +pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, f: &mut CouplingForm, inputs: &[SelInput]) -> bool { + let t = Tokens::get(); + let s = &app.session; + let ([role_a, role_b], turn_b) = roles(f.command); + let (la, lb) = (joints_that(s, true), joints_that(s, turn_b)); + if la.is_empty() || lb.is_empty() { + row_label(ui, ""); + let need = if turn_b { "needs two joints that turn" } else { "needs a joint that turns and one that slides" }; + ui.label(RichText::new(crate::i18n::tr_label(need)).color(t.text_dim)); + ui.end_row(); + return false; + } + // A face picked on a part chooses the joint that part turns on, once. + for (i, slot) in [&mut f.a, &mut f.b].into_iter().enumerate() { + let body = pick(inputs, i).map(|(b, _)| b.to_string()); + if body.is_some() && body != f.picked.get(i).cloned().flatten() { + let turning = s.doc.assembly.joints.iter().filter(|j| la.iter().any(|l| l.0 == j.id)); + if let Some(j) = body + .as_deref() + .and_then(|b| occurrence(s, b)) + .and_then(|o| turning.clone().find(|j| j.b.occurrence == o).or(turning.clone().find(|j| j.a.occurrence == o))) + { + *slot = j.id; + } + } + if let Some(p) = f.picked.get_mut(i) { + *p = body; + } + } + let mut enter = false; + let size_row = |ui: &mut egui::Ui, label: &str, i: usize, text: &mut String, enter: &mut bool| { + row_label(ui, label); + match (pick(inputs, i), picked_radius(s, inputs, i)) { + (_, Some(r)) => { + ui.label(format!("{} mm ({})", trim(r), crate::i18n::tr_label("picked"))); + } + // A pick on a flat face or a straight edge has no radius: say so rather than fail on OK. + (Some(_), None) => { + ui.label(RichText::new(crate::i18n::tr_label("not a round face")).color(t.warning)); + } + (None, None) => *enter |= field(ui, text), + } + ui.end_row(); + }; + joint_row(ui, role_a, "cp_a", &la, &mut f.a); + let [s0, s1] = &mut f.sizes; + match f.command { + "joint.gear" => { + size_row(ui, "Radius 1", 0, s0, &mut enter); + joint_row(ui, role_b, "cp_b", &lb, &mut f.b); + size_row(ui, "Radius 2", 1, s1, &mut enter); + row_label(ui, "Internal gear"); + check(ui, &mut f.internal); + ui.end_row(); + } + "joint.rack_pinion" => { + size_row(ui, "Radius", 0, s0, &mut enter); + joint_row(ui, role_b, "cp_b", &lb, &mut f.b); + } + _ => { + joint_row(ui, role_b, "cp_b", &lb, &mut f.b); + row_label(ui, "Pitch"); + enter |= field(ui, s0); + ui.end_row(); + } + } + row_label(ui, "Reverse"); + check(ui, &mut f.reverse); + ui.end_row(); + // What the coupling does, as joint.list gives a link's ratio. + let sign = |neg: bool| if neg { -1.0 } else { 1.0 }; + let shown = match f.command { + "joint.gear" => size(s, f, inputs, 0) + .zip(size(s, f, inputs, 1)) + .map(|(ra, rb)| format!("{} deg / deg", trim(ra / rb * sign(!f.internal) * sign(f.reverse)))), + "joint.rack_pinion" => size(s, f, inputs, 0).map(|r| format!("{} mm / deg", trim(r.to_radians() * sign(f.reverse)))), + _ => size(s, f, inputs, 0).map(|p| format!("{} mm / deg", trim(p / 360.0 * sign(f.reverse)))), + }; + row_label(ui, "Ratio"); + ui.label(RichText::new(shown.unwrap_or_else(|| "-".into())).color(t.text_dim)); + ui.end_row(); + row_label(ui, "Animate"); + let label = if f.animate { "■ Stop" } else { "▶ Play" }; + let r = ui.button(label).on_hover_text(crate::i18n::tr_label("Play the joint's motion in the view")); + crate::scenario::publish_handle("dialog:Animate", r.rect.center()); + if r.clicked() { + f.animate = !f.animate; + } + ui.end_row(); + if f.animate { + let now = ui.input(|i| i.time); + // 48 steps over 4 s: each one a preview. + f.phase = ((now / 4.0).fract() * 48.0).floor() / 48.0; + ui.ctx().request_repaint_after(std::time::Duration::from_millis(30)); + } + enter +} + +/// A number without trailing zeros. +fn trim(v: f64) -> String { + let s = format!("{v:.4}"); + let s = s.trim_end_matches('0').trim_end_matches('.'); + if s == "-0" { "0".into() } else { s.into() } +} + +/// The command OK runs. +pub fn commands(app: &SolveApp, f: &CouplingForm, inputs: &[SelInput]) -> Result, String> { + let s = &app.session; + let joint = |id: u64| s.doc.assembly.joints.iter().find(|j| j.id == id).map(|j| j.id).ok_or_else(|| "choose the joints to couple".to_string()); + let (a, b) = (joint(f.a)?, joint(f.b)?); + // A picked face, or the typed size. + let size = |i: usize| -> Value { + match pick(inputs, i) { + Some((body, p)) => { + let mut v = json!({"circle": [p.x, p.y, p.z]}); + if let Some(o) = occurrence(s, body) { + v["occurrence"] = json!(o); + } + v + } + None => json!(f.sizes.get(i).map(|t| t.trim()).unwrap_or("")), + } + }; + let mut p = match f.command { + "joint.gear" => json!({"a": a, "b": b, "ra": size(0), "rb": size(1), "internal": f.internal}), + "joint.rack_pinion" => json!({"a": a, "b": b, "radius": size(0)}), + _ if a == b => json!({"joint": a, "pitch": f.sizes[0].trim()}), + _ => json!({"a": a, "b": b, "pitch": f.sizes[0].trim()}), + }; + p["reverse"] = json!(f.reverse); + Ok(vec![(f.command.to_string(), p)]) +} + +/// While animating, the preview turns the driving joint a full turn: its first value that turns +/// (a planar joint's is its third), the values before it as they are. +pub fn animate(s: &Session, f: &CouplingForm, cmds: &mut Vec<(String, Value)>) { + let Some(j) = s.doc.assembly.joints.iter().find(|j| j.id == f.a).filter(|_| f.animate) else { return }; + let Some(turn) = (0..j.kind.dofs().len()).find(|i| j.kind.is_angle(*i)) else { return }; + let values: Vec = (0..=turn) + .map(|i| match j.values.get(i).copied().unwrap_or(0.0) { + _ if i == turn => format!("{} deg", f.phase * 360.0), + v if j.kind.is_angle(i) => format!("{} deg", v.to_degrees()), + v => format!("{v} mm"), + }) + .collect(); + cmds.push(("joint.drive".into(), json!({"joint": f.a, "values": values}))); +} + +#[cfg(test)] +#[path = "dialogs_coupling_tests.rs"] +mod tests; diff --git a/crates/ui-egui/src/dialogs_coupling_tests.rs b/crates/ui-egui/src/dialogs_coupling_tests.rs new file mode 100644 index 000000000..206d3467a --- /dev/null +++ b/crates/ui-egui/src/dialogs_coupling_tests.rs @@ -0,0 +1,198 @@ +use serde_json::json; +use solidcraft_engine::Session; +use solidcraft_engine::geom::Vec3; + +use super::*; +use crate::Services; +use crate::dialogs::{Kind, apply_commands, preview_commands}; + +/// A grounded base with discs G1 (radius 10 at x = 0) and G2 (radius 20 at x = 30) turning on +/// revolute joints about +Z, and a nut on a cylindrical joint. +fn discs() -> SolveApp { + let mut s = Session::default(); + let mut run = |id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}")); + for (name, base, r) in [("Base", [0, -60, -20], 2), ("G1", [0, 0, 0], 10), ("G2", [30, 0, 0], 20), ("Nut", [0, 60, 0], 3)] { + run("component.activate", json!({"component": "root"})); + run("component.create", json!({ "name": name })); + run("solid.cylinder", json!({"base": base, "axis": [0, 0, 1], "radius": r, "height": 5})); + } + run("component.activate", json!({"component": "root"})); + run("occurrence.ground", json!({"occurrence": "Base:1", "grounded": true})); + for (kind, name, x, y) in [("revolute", "G1", 0, 0), ("revolute", "G2", 30, 0), ("cylindrical", "Nut", 0, 60)] { + let at = |o: &str| json!({"occurrence": o, "point": [x, y, 0], "z": [0, 0, 1]}); + run("joint.create", json!({"type": kind, "a": at("Base"), "b": at(name), "flip": true, "name": name})); + } + SolveApp::new(s, Services::default()) +} + +/// A pick of the round wall a point of the exact geometry lies on (the facets of the wall's mesh +/// cut inside it, so the nearest face of any body). +fn wall(app: &SolveApp, p: Vec3) -> Sel { + let st = app.session.world_state(); + let mut best: Option<(f64, Sel)> = None; + for b in &st.bodies { + 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 })); + } + } + } + best.map(|x| x.1).unwrap() +} + +fn joint(app: &SolveApp, name: &str) -> u64 { + app.session.doc.assembly.joints.iter().find(|j| j.name == name).map(|j| j.id).unwrap_or(0) +} + +/// The text of every text shape in a frame's output. +fn texts(out: &egui::FullOutput) -> Vec { + out.shapes + .iter() + .filter_map(|c| match &c.shape { + egui::Shape::Text(t) => Some(t.galley.text().to_string()), + _ => None, + }) + .collect() +} + +/// Picking a gear's round face chooses the joint it turns on and takes its radius; the ratio +/// row says what the pair does, and OK makes the coupling. +#[test] +fn picked_gear_faces_choose_their_joints_and_radii() { + let mut app = discs(); + app.start("joint.gear"); + let mut d = app.dialog.take().unwrap(); + // G2 first, G1 second: the joints follow the picks, whatever the dialog started on. + for (i, p) in [Vec3::new(50.0, 0.0, 2.5), Vec3::new(10.0, 0.0, 2.5)].into_iter().enumerate() { + d.active = i; + let pick = wall(&app, p); + d.pick(&app.session, pick); + } + app.dialog = Some(d); + let ctx = egui::Context::default(); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 1000.0)); + let frame = |app: &mut SolveApp| { + let input = egui::RawInput { screen_rect: Some(screen), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| crate::dialogs::show(app, ui.ctx())); + // Nothing is painted: drop the texture changes (an unapplied delta panics on drop). + out.textures_delta.clear(); + out + }; + frame(&mut app); + let out = frame(&mut app); + let shown = texts(&out); + assert!(shown.iter().any(|t| t == "-2 deg / deg"), "{shown:?}"); + assert!(shown.iter().any(|t| t.starts_with("20 mm")), "{shown:?}"); + let d = app.dialog.as_ref().expect("the dialog stays open"); + let c = apply_commands(&app, d).unwrap(); + let (id, p) = &c[0]; + assert_eq!((id.as_str(), p["a"].clone(), p["b"].clone()), ("joint.gear", json!(joint(&app, "G2")), json!(joint(&app, "G1"))), "{p}"); + assert!(p["ra"]["circle"].is_array() && p["rb"]["occurrence"].is_u64(), "{p}"); + // Play turns the driving gear in the preview. + let mut d = d.clone(); + if let Kind::Assembly(Asm::Coupling(f)) = &mut d.kind { + f.animate = true; + f.phase = 0.25; + } + let cmds = preview_commands(&app, &d).unwrap(); + assert_eq!(cmds.get(1).map(|c| c.1["values"].clone()), Some(json!(["90 deg"])), "{cmds:?}"); + for (id, p) in c { + app.run(&id, p).unwrap(); + } + let l = app.session.doc.assembly.links.first().cloned().unwrap(); + assert!((l.ratio + 2.0).abs() < 1e-9, "{l:?}"); +} + +/// Two instances of one gear (a copied component) are two occurrences, each on its own joint: +/// picks on each choose each one's joint, and the engine finds each pick on its own instance. +#[test] +fn instances_of_one_gear_are_coupled_as_two() { + let mut s = Session::default(); + let mut run = |id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}")); + for (name, r) in [("Base", 2), ("Twin", 15)] { + run("component.activate", json!({"component": "root"})); + run("component.create", json!({ "name": name })); + run("solid.cylinder", json!({"base": [0, 0, if name == "Base" { -20 } else { 0 }], "axis": [0, 0, 1], "radius": r, "height": 5})); + } + run("component.activate", json!({"component": "root"})); + run("occurrence.copy", json!({"component": "Twin", "translate": [30, 0, 0]})); + run("occurrence.ground", json!({"occurrence": "Base:1", "grounded": true})); + for (name, x) in [("Twin:1", 0), ("Twin:2", 30)] { + let at = |o: &str| json!({"occurrence": o, "point": [x, 0, 0], "z": [0, 0, 1]}); + run("joint.create", json!({"type": "revolute", "a": at("Base:1"), "b": at(name), "flip": true, "name": name})); + } + let mut app = SolveApp::new(s, Services::default()); + let occ = |app: &SolveApp, name: &str| app.session.doc.occurrences.iter().find(|o| o.name == name).map(|o| o.id).unwrap_or(0); + app.start("joint.gear"); + let mut d = app.dialog.take().unwrap(); + for (i, p) in [Vec3::new(-15.0, 0.0, 2.5), Vec3::new(45.0, 0.0, 2.5)].into_iter().enumerate() { + d.active = i; + let pick = wall(&app, p); + d.pick(&app.session, pick); + } + app.dialog = Some(d); + let ctx = egui::Context::default(); + for _ in 0..2 { + let input = + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 1000.0))), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| crate::dialogs::show(&mut app, ui.ctx())); + out.textures_delta.clear(); + } + let c = apply_commands(&app, app.dialog.as_ref().unwrap()).unwrap(); + let p = &c[0].1; + assert_eq!((p["a"].clone(), p["b"].clone()), (json!(joint(&app, "Twin:1")), json!(joint(&app, "Twin:2"))), "{p}"); + assert_eq!((p["ra"]["occurrence"].clone(), p["rb"]["occurrence"].clone()), (json!(occ(&app, "Twin:1")), json!(occ(&app, "Twin:2"))), "{p}"); + app.run(&c[0].0, p.clone()).unwrap(); + assert!((app.session.doc.assembly.links[0].ratio + 1.0).abs() < 1e-9); +} + +/// A cylindrical joint is a screw on its own: the dialog sends it as `joint` with the pitch. +#[test] +fn a_cylindrical_joint_is_a_screw_on_its_own() { + let mut app = discs(); + app.start("joint.screw"); + let d = app.dialog.take().unwrap(); + let c = apply_commands(&app, &d).unwrap(); + assert_eq!(c[0], ("joint.screw".to_string(), json!({"joint": joint(&app, "Nut"), "pitch": "1.5 mm", "reverse": false}))); + app.run(&c[0].0, c[0].1.clone()).unwrap(); + app.run("joint.drive", json!({"joint": "Nut", "values": [360]})).unwrap(); + let nut = solidcraft_engine::doc::joints::joint_values(&app.session.doc.assembly).get(&joint(&app, "Nut")).cloned().unwrap_or_default(); + assert!((nut.get(1).copied().unwrap_or(f64::NAN) - 1.5).abs() < 1e-9, "{nut:?}"); +} + +/// Play turns the pinion's angle, wherever it is among its joint's values: a planar joint's is +/// the third, after its x and y, which keep theirs. +#[test] +fn play_turns_the_angle_of_a_planar_pinion() { + let mut app = discs(); + let at = |o: &str| json!({"occurrence": o, "point": [0, 0, 0], "z": [0, 0, 1]}); + app.run("joint.edit", json!({"joint": "G1", "type": "planar"})).unwrap(); + app.run("joint.drive", json!({"joint": "G1", "values": [2, 0, 0]})).unwrap(); + app.run("joint.create", json!({"type": "slider", "a": at("Base"), "b": at("G2"), "flip": true, "name": "Rail"})).unwrap(); + app.start("joint.rack_pinion"); + let mut d = app.dialog.take().unwrap(); + if let Kind::Assembly(Asm::Coupling(f)) = &mut d.kind { + (f.a, f.animate, f.phase) = (joint(&app, "G1"), true, 0.5); + } + let cmds = preview_commands(&app, &d).unwrap(); + assert_eq!(cmds.last().map(|c| c.1["values"].clone()), Some(json!(["2 mm", "0 mm", "180 deg"])), "{cmds:?}"); +} + +/// The dialog's rows pass their English text, which the catalogs translate by its key. +#[test] +fn the_dialog_labels_translate() { + let de = crate::i18n::Locale::for_language("de"); + for (english, german) in [ + ("Gear 1", "Zahnrad 1"), + ("Radius 2", "Radius 2"), + ("Internal gear", "Innenzahnrad"), + ("Pitch", "Steigung"), + ("Rack and Pinion", "Zahnstange und Ritzel"), + ] { + assert_eq!(de.label(english), german); + } + assert_eq!(crate::i18n::Locale::for_language("ja").label("not a round face"), "円筒面ではありません"); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 05366d1c1..ede551ac4 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -25,6 +25,7 @@ pub mod design_properties; pub mod dialogs; pub mod dialogs_appearance; pub mod dialogs_assembly; +pub mod dialogs_coupling; pub mod dialogs_library; pub mod dialogs_motion; pub mod dialogs_move; diff --git a/crates/ui-egui/src/preview.rs b/crates/ui-egui/src/preview.rs index 2d6d28d37..25af7b69e 100644 --- a/crates/ui-egui/src/preview.rs +++ b/crates/ui-egui/src/preview.rs @@ -187,7 +187,19 @@ impl PreviewState { /// limits, feature dialog or document cannot reuse an obsolete pose. fn motion_key(cmds: &[(String, Value)], revision: u64, colors: Colors) -> Option { if !cmds.iter().any(|(c, p)| c == "joint.drive" || c == "joint.create" && p.get("values").is_some()) - || !cmds.iter().all(|(c, _)| matches!(c.as_str(), "joint.drive" | "joint.create" | "joint.as_built" | "joint.edit" | "joint.limits")) + || !cmds.iter().all(|(c, _)| { + matches!( + c.as_str(), + "joint.drive" + | "joint.create" + | "joint.as_built" + | "joint.edit" + | "joint.limits" + | "joint.gear" + | "joint.rack_pinion" + | "joint.screw" + ) + }) { return None; } @@ -826,6 +838,15 @@ mod tests { motion_key(&[(command.into(), json!({"joint": 1, "values": [90]}))], 7, colors()), ); } + // A gear dialog playing its driving joint streams its poses too. + let gear = |angle: &str| { + vec![ + ("joint.gear".to_string(), json!({"a": 1, "b": 2, "ra": 10, "rb": 20})), + ("joint.drive".to_string(), json!({"joint": 1, "values": [angle]})), + ] + }; + assert!(motion_key(&gear("0 deg"), 7, colors()).is_some()); + assert_eq!(motion_key(&gear("0 deg"), 7, colors()), motion_key(&gear("90 deg"), 7, colors())); } /// Combine previews its result (cut, join or intersect between existing bodies) without an diff --git a/crates/ui-egui/src/workspace.rs b/crates/ui-egui/src/workspace.rs index 953fc3dca..a3b04c2b0 100644 --- a/crates/ui-egui/src/workspace.rs +++ b/crates/ui-egui/src/workspace.rs @@ -16,6 +16,9 @@ const ASSEMBLE: &[&str] = &[ "joint.rigid_group", "joint.drive", "joint.motion_link", + "joint.gear", + "joint.rack_pinion", + "joint.screw", "motion.study", "explode.create", "contact.enable_sets", diff --git a/docs/book/src/guide/assemblies.md b/docs/book/src/guide/assemblies.md index e33e79b07..9b2ff8938 100644 --- a/docs/book/src/guide/assemblies.md +++ b/docs/book/src/guide/assemblies.md @@ -28,6 +28,33 @@ 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. +**Gear**, **Rack and Pinion** and **Screw** (on the **ASSEMBLE** panel) are motion links whose +ratio comes from the parts rather than a typed number: + +- **Gear** (`joint.gear {a, b, ra, rb}`) couples two joints that turn. Joint 2 turns ra/rb as far + as joint 1, the other way round; **Internal gear** (one of them is a ring gear) turns both the + same way. Pick the round face of each gear, such as its pitch cylinder, or type the radii. Tooth + counts work as well as radii, since only their proportion counts. Picking a gear's face also + chooses the joint that gear turns on. +- **Rack and Pinion** (`joint.rack_pinion {a, b, radius}`) couples a joint that turns with one + that slides: the rack travels the pinion's pitch radius times its turn in radians (r·θ). Either + joint may drive the other. In `joint.list` the ratio is given per degree, as for any link between + an angle and a distance. +- **Screw** (`joint.screw {joint, pitch}`, or `{a, b, pitch}` for a revolute joint and a slider) + advances `pitch` per turn. A cylindrical joint is a screw on its own: its turn drives its travel. + The thread is right-handed; **Reverse** makes it left-handed. + +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 +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 +driven one. A joint follows one link at most, and a coupling that would drive its own driver is +refused. `joint.list` lists each coupling's definition under `links` with an `error` when it can't +be worked out (the picked face is gone); the link then keeps its last ratio. + A joint moves one component against another, so its two picks must be on different components. A STEP file with several parts often comes in as bodies of one component, and picks on two of those bodies make no joint. The Joint and As-built Joint dialogs say so under the picks and offer diff --git a/docs/design-container.md b/docs/design-container.md index b4f275882..9bde0bfe2 100644 --- a/docs/design-container.md +++ b/docs/design-container.md @@ -7,7 +7,7 @@ self-contained input/output format. `io::write_design` keeps its JSON contract; `io::write_design_container` is the fallible container writer. Packages have `container.json` with `{"format":"solidcraft-container/1"}` and -`document.json` with the versioned parametric document (currently `solidcraft/22`). +`document.json` with the versioned parametric document (currently `solidcraft/23`). The independent versions let document migrations evolve without changing blob encodings. Existing serialized document fields are retained automatically, without a second copy of the document schema or a deep clone of embedded payloads. diff --git a/docs/features.md b/docs/features.md index e07ed6b8d..304b2008b 100644 --- a/docs/features.md +++ b/docs/features.md @@ -1,6 +1,6 @@ # Features -SolidCraft's commands by area, generated by `cargo xtask features` from the command registry (`solidcraft-cli commands`). **373 commands.** Planned (registered, not built yet): 3. 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`). **376 commands.** Planned (registered, not built yet): 3. 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 (102) @@ -246,7 +246,7 @@ SolidCraft's commands by area, generated by `cargo xtask features` from the comm | Break Link | `component.break_link` | – | | List Links | `component.links` | – | -## Assembly joints (11) +## Assembly joints (14) | Command | Id | Toolbar | |---|---|---| @@ -256,6 +256,9 @@ SolidCraft's commands by area, generated by `cargo xtask features` from the comm | Rigid Group | `joint.rigid_group` | SOLID › ASSEMBLE | | Drive Joints | `joint.drive` | SOLID › ASSEMBLE | | 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 | | Joint Limits | `joint.limits` | – | | Edit Joint | `joint.edit` | – | | Delete Joint | `joint.delete` | – | diff --git a/skills/solidcraft-mechanisms/SKILL.md b/skills/solidcraft-mechanisms/SKILL.md index 60485bf5f..56b29217e 100644 --- a/skills/solidcraft-mechanisms/SKILL.md +++ b/skills/solidcraft-mechanisms/SKILL.md @@ -41,6 +41,7 @@ Written against SolidCraft `main` after 0.11.1, which counts the degrees of free ## Linked and closed motion - **Motion links:** `joint.motion_link {"a":..., "b":..., "ratio":r, "offset":o}` sets b = r·a + o, clamped to b's own limits. `ratio` is b's units per a's: a pinion that moves its rack 0.5 mm per degree takes `ratio: 0.5`. `offset` is in b's units: degrees for an angle, mm for a distance, or an expression. A mirrored part takes `ratio: -1`, and limits mirrored too. Chains (a drives b, b drives c) work in any order of creation. Drive only the head of a chain. +- **Gears, racks and screws:** links whose ratio comes from radii or a pitch, kept up to date when they change. `joint.gear {"a":..., "b":..., "ra":r1, "rb":r2}` turns b r1/r2 as far as a, the other way (`internal: true`: the same way). `joint.rack_pinion {"a":pinion, "b":rack, "radius":r}` moves the rack r·θ. `joint.screw {"joint":cylindrical, "pitch":p}` (or `a`, `b` for a revolute and a slider) advances p per turn. A size is mm, an expression (`"m*z1/2"`), or a round face `{"occurrence":..., "circle":[x,y,z]}` whose radius is read again after every edit. `reverse: true` turns b the other way (a left-hand thread). The driven joint keeps where it is. Drive a, never b. - **Closed loops:** an actuator between a frame and a hinged panel takes three joints besides the hinge: - a revolute root pin (frame and barrel) - a slider (barrel and rod), with z along the actuator from root to tip on both origins, both at the root pin, and the stroke as its limits diff --git a/skills/solidcraft-mechanisms/reference.md b/skills/solidcraft-mechanisms/reference.md index cbc8ee61c..99adc3874 100644 --- a/skills/solidcraft-mechanisms/reference.md +++ b/skills/solidcraft-mechanisms/reference.md @@ -62,6 +62,7 @@ A slider's value grows as b moves along +z of its origin. Give its two origins t - `joint.as_built` takes occurrences, not origins. `at` is the joint's frame (default: b's component origin). - `joint.rigid_group` joins every occurrence to the first one with a rigid as-built joint. - `joint.motion_link`: b = ratio·a + offset, clamped to b's limits. `ratio` is in b's units per a's: mm per degree when an angle drives a distance (a pinion of pitch radius r moves its rack r·π/180 mm per degree), degrees per mm the other way, and a plain factor between two angles or two distances. `offset` is in b's units: degrees for an angle, mm for a distance, or an expression such as `"10 deg"`. `joint.list` gives each link's `ratio` the same way and its `offset` with its `unit`. `ia`/`ib` pick a value of a multi-value joint (default 0). `joint.delete {"link": n}` removes link n (its index in `joint.list` `links`). +- `joint.gear {a, b, ra, rb, internal?, reverse?}`, `joint.rack_pinion {a, b, radius, reverse?}` and `joint.screw {joint | a, b; pitch, reverse?}` make a motion link whose ratio comes from its sizes: gears -ra/rb (+ra/rb internal), a rack r mm per radian of its pinion (either joint may be `a`), a screw pitch per turn. Each size is mm, an expression, or `{occurrence, circle: [x,y,z]}`: the radius of the round face there, read again whenever the design changes. The reply gives `link` (its index) and `ratio` as `joint.list` does; `link: n` in the params replaces link n and keeps its offset. A new coupling's offset keeps b where it is. `joint.list` `links` carry the `coupling` and an `error` when it can't be worked out (a picked face gone: the last ratio stays). A value two links would set, or a coupling that would drive its own driver, is refused. - `joint.drive`: `values` drives the values it lists, in order (`Spindle` above is cylindrical: 30 degrees, then 5 mm), and `value` the first; values left out keep theirs, or follow in a closed loop. Values are clamped to the limits. The reply gives `values` as `joint.list` does (`{name, value, unit, limits}`), and `moved`; when the joint can move nothing, a `reason`. - `motion.study {"study":..., ...}` edits a study; `keys` given replace all keys. - `motion.play` sets the joints to the study's values at a step (fractions work) and changes the design. `motion.export` does not change it. @@ -123,6 +124,8 @@ The same pattern moved the solar wings of the SELENE rover (`Rover-v7.solidcraft | A part turns by some other angle when joined | The two origins have different forms or x axes. Use `point` + `z` on both sides, or `joint.as_built`. | | `joint.drive` answers `moved: false`, or `motion.play` lists the joint under `unmoved` | Read `reason`. Most often the chain is joined to nothing grounded: `unconnected` names the part, and `joint.list` lists the chain under `floating`, its occurrences with `dof: 6`. Ground it, join it, or `joint.rigid_group` it with the structure. | | A drive stops short, `stopped_by_loop` | A loop reached a limit or can't close further; `joint` names the joint that stopped it. Check the limits against your stroke numbers. | +| A gear, rack or screw turns its partner the wrong way | The joints' axes point opposite ways (or the rack lies on the other side of the pinion). Run the command again with `reverse: true` and `link: n`. | +| `already follows a motion link` from `joint.gear` | A joint follows one link at most. Make the joint that already follows the driving one (`a`), as in a gear train G1 → G2 → G3. | | A linked joint stops following | Its value is clamped to its own limits. Hinge 2 in the example has `[[-60, 0]]`, so a drive of Hinge below 0 leaves it at 0. Give a mirrored joint the mirrored limits. | | A drive stops short, `stopped_by_contact` | Two bodies of a contact set touch. `fraction` is how far the move got. | | `occurrence.ground` says there is no occurrence `Frame` | It takes occurrence names only: `Frame:1`. | @@ -140,7 +143,7 @@ The same pattern moved the solar wings of the SELENE rover (`Rover-v7.solidcraft | `joint.list` | about 0.5 KB per joint: 16 KB for 29 joints | | `motion.play` | about 0.2 KB per occurrence, per step: 9 KB on SELENE | | `motion.export` | the same per sample; pass `samples`, or `path` to write it to a file | -| `joint.create`, `joint.drive`, `joint.motion_link` | the `dof` list of every occurrence again, 40 B each; `quiet: true` leaves it out | +| `joint.create`, `joint.drive`, `joint.motion_link`, `joint.gear`, `joint.rack_pinion`, `joint.screw` | the `dof` list of every occurrence again, 40 B each; `quiet: true` leaves it out | | `occurrence.properties` | under 1 KB per occurrence | ## Showing it moving From 1c9d6617ade67589f41fd2bbe8a787eee17a843d Mon Sep 17 00:00:00 2001 From: macrulz54 Date: Fri, 16 Oct 2026 00:47:46 +0200 Subject: [PATCH 09/92] Add Turkish translation (#1520) Registers a Turkish (tr) catalog with its attribution, docs and a test. Co-authored-by: macrulz54 Co-Authored-By: Claude Sonnet 5.5 --- ATTRIBUTION.md | 1 + assets/locales/tr.json | 1381 ++++++++++++++++++++++++++++++++++++ crates/ui-egui/src/i18n.rs | 14 +- docs/localization.md | 4 +- 4 files changed, 1397 insertions(+), 3 deletions(-) create mode 100644 assets/locales/tr.json diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 856817e36..d3419e479 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -96,6 +96,7 @@ Editable drawing code, native projects and shipped exports are collected under ` | 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/ru.json | Alex Pro (del000) | Russian 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/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 | diff --git a/assets/locales/tr.json b/assets/locales/tr.json new file mode 100644 index 000000000..463a44ee6 --- /dev/null +++ b/assets/locales/tr.json @@ -0,0 +1,1381 @@ +{ + "Send your report on GitHub": "Raporunuzu GitHub üzerinden gönderin", + "1. Open GitHub draft below, then paste the report copied to your clipboard.": "1. Aşağıdaki GitHub taslağını açın, ardından panoya kopyalanan raporu yapıştırın.", + "1. Open GitHub draft below. Your title and report will be filled in.": "1. Aşağıdaki GitHub taslağını açın. Başlığınız ve raporunuz otomatik olarak doldurulur.", + "2. Attach your screenshot: copy and paste it, or save and upload the PNG.": "2. Ekran görüntüsünü ekleyin: kopyalayıp yapıştırın veya PNG olarak kaydedip yükleyin.", + "3. Click Submit new issue on GitHub to send your report.": "3. Raporu göndermek için GitHub'da Submit new issue düğmesine tıklayın.", + "nav.touchpad.label": "Dokunmatik yüzey", + "nav.touchpad.help": "Kaydırmak için Shift tuşunu basılı tutun ve imleci hareket ettirin; Alt/Option ile döndürün. Fare tuşu gerekmez. Dikey kaydırma yakınlaştırır.", + "nav.touchpad.orbit": "Döndür (Alt/Option tuşunu basılı tutup hareket ettirin; fare tuşu olmadan)", + "nav.touchpad.pan": "Kaydır (Shift tuşunu basılı tutup hareket ettirin; fare tuşu olmadan)", + "nav.touchpad.zoom": "Yakınlaştır (dikey kaydırın veya parmaklarınızı açıp kapatın)", + "nav.touchpad.scroll": "Dokunmatik yüzey yakınlaştırmak için dikey kaydırmayı kullanır. İki parmakla kaydırma diğer ön ayarlar için kayıtlı kalır.", + "browser.body_name": "Gövde {number}", + "browser.component_name": "Bileşen {number}", + "browser.parameters": "Parametreler ({count})", + "browser.precision": "Hassasiyet: {precision}", + "browser.sketch_name": "Eskiz {number}", + "browser.units": "Birimler: {units}", + "cmd.appearance_assign": "Görünüm", + "cmd.appearance_library": "Görünüm kitaplığı", + "cmd.appearance_list": "Görünümleri listele", + "cmd.body_rename": "Gövdeyi yeniden adlandır", + "cmd.browser_group": "Yeni grup", + "cmd.browser_move": "Tarayıcı öğelerini taşı", + "cmd.browser_order": "Tarayıcı öğelerini sırala", + "cmd.browser_rename_group": "Grubu yeniden adlandır", + "cmd.browser_ungroup": "Grubu çöz", + "cmd.browser_visibility": "Göster/Gizle", + "cmd.canvas_calibrate": "Tuvali kalibre et", + "cmd.canvas_decal": "Çıkartma", + "cmd.canvas_delete": "Tuvali sil", + "cmd.canvas_edit": "Tuvali düzenle", + "cmd.canvas_insert": "Tuval", + "cmd.component_activate": "Bileşeni etkinleştir", + "cmd.component_break_link": "Bağı kopar", + "cmd.component_capture_position": "Konumu yakala", + "cmd.component_create": "Yeni bileşen", + "cmd.component_delete": "Bileşeni sil", + "cmd.component_unlock": "İçeriğin kilidini aç", + "cmd.component_from_bodies": "Gövdelerden bileşen oluştur", + "cmd.component_insert_design": "Tasarım ekle", + "cmd.component_links": "Bağları listele", + "cmd.component_list": "Bileşenleri listele", + "cmd.component_move_bodies": "Gövdeleri bileşene taşı", + "cmd.component_move_sketches": "Eskizleri bileşene taşı", + "cmd.component_paste_new": "Yeni olarak yapıştır", + "cmd.component_properties": "Bileşenin fiziksel özellikleri", + "cmd.component_rename": "Bileşeni yeniden adlandır", + "cmd.component_revert_position": "Konumu geri al", + "cmd.component_update_links": "Bağları güncelle", + "cmd.config_activate": "Konfigürasyonu etkinleştir", + "cmd.config_column": "Konfigürasyon sütunu", + "cmd.config_configure": "Yapılandır", + "cmd.config_preview": "Konfigürasyonu önizle", + "cmd.config_row": "Konfigürasyon satırı", + "cmd.config_rule": "Konfigürasyon kuralı", + "cmd.config_rules": "Konfigürasyon kuralları", + "cmd.config_table": "Konfigürasyon tablosunu göster", + "cmd.construct_axis_edge": "Kenardan geçen eksen", + "cmd.construct_axis_normal_to_face": "Yüze dik eksen", + "cmd.construct_axis_through_cylinder": "Silindir/koni/torus içinden geçen eksen", + "cmd.construct_axis_two_planes": "İki düzlemden geçen eksen", + "cmd.construct_axis_two_points": "İki noktadan geçen eksen", + "cmd.construct_plane_along_path": "Yol boyunca düzlem", + "cmd.construct_plane_midplane": "Orta düzlem", + "cmd.construct_plane_perpendicular": "Dik düzlem", + "cmd.construct_plane_tangent": "Teğet düzlem", + "cmd.construct_plane_three_points": "Üç noktadan geçen düzlem", + "cmd.construct_plane_two_edges": "İki kenardan geçen düzlem", + "cmd.construct_point_along_path": "Yol boyunca nokta", + "cmd.construct_point_center": "Daire/küre/torus merkezinde nokta", + "cmd.construct_point_edge_plane": "Kenar ve düzlem kesişiminde nokta", + "cmd.construct_point_three_planes": "Üç düzlemin kesişiminde nokta", + "cmd.construct_point_two_edges": "İki kenarın kesişiminde nokta", + "cmd.construct_point_vertex": "Köşe noktasında nokta", + "cmd.contact_check": "Teması kontrol et", + "cmd.contact_create": "Yeni temas kümesi", + "cmd.contact_disable_all": "Teması devre dışı bırak", + "cmd.contact_edit": "Temas kümesini düzenle", + "cmd.contact_enable_all": "Tüm temasları etkinleştir", + "cmd.contact_enable_sets": "Temas kümelerini etkinleştir", + "cmd.contact_list": "Temas kümelerini listele", + "cmd.diagnostics_crash_report": "Çökme raporu", + "cmd.diagnostics_crash_reports": "Çökme raporları", + "cmd.diagnostics_crash_reports_clear": "Çökme raporlarını sil", + "cmd.diagnostics_crash_test": "Çökme testi", + "cmd.doc_recover": "Tasarımı kurtar", + "cmd.doc_recovery_discard": "Kurtarılan tasarımı at", + "cmd.doc_recovery_list": "Kurtarılabilir tasarımlar", + "cmd.document_inspect": "Tasarımı incele", + "cmd.document_units": "Tasarımın birimlerini değiştir", + "cmd.document_metadata": "Tasarım özellikleri", + "cmd.document_metadata_set": "Tasarım özelliklerini değiştir", + "cmd.document_metadata_remove": "Tasarım özelliğini kaldır", + "cmd.edit_checkpoint": "Kontrol noktası", + "cmd.edit_restore_checkpoint": "Kontrol noktasını geri yükle", + "cmd.engine_commands": "Komutları listele", + "cmd.explode_create": "Patlatılmış görünüm", + "cmd.explode_delete": "Patlatılmış görünümü sil", + "cmd.explode_list": "Patlatılmış görünümleri listele", + "cmd.explode_show": "Patlatılmış görünümü göster", + "cmd.expr_evaluate": "İfadeyi değerlendir", + "cmd.face_delete": "Yüzü sil", + "cmd.file_export": "Dışa aktar", + "cmd.file_insert_mesh": "Ağ ekle", + "cmd.file_insert_step": "STEP ekle", + "cmd.file_save_mesh": "Ağ olarak kaydet", + "cmd.file_slicers": "Yüklü dilimleyiciler", + "cmd.inspect_accessibility": "Erişilebilirlik analizi", + "cmd.inspect_center_of_mass": "Kütle merkezi", + "cmd.inspect_compare": "Gövdeleri karşılaştır", + "cmd.inspect_curvature_comb": "Eğrilik tarağı analizi", + "cmd.inspect_curvature_map": "Eğrilik haritası analizi", + "cmd.inspect_draft": "Koniklik analizi", + "cmd.inspect_environment_map": "Ortam haritası analizi", + "cmd.inspect_interference": "Girişim", + "cmd.inspect_isocurve": "İzoeğri analizi", + "cmd.inspect_minimum_radius": "Minimum yarıçap analizi", + "cmd.inspect_zebra": "Zebra analizi", + "cmd.joint_as_built": "Yerinde bağlantı", + "cmd.joint_create": "Bağlantı", + "cmd.joint_delete": "Bağlantıyı sil", + "cmd.joint_drive": "Bağlantıları tahrik et", + "cmd.joint_edit": "Bağlantıyı düzenle", + "cmd.joint_limits": "Bağlantı sınırları", + "cmd.joint_list": "Bağlantıları listele", + "cmd.joint_motion_link": "Hareket bağı", + "cmd.joint_origin": "Bağlantı orijini", + "cmd.joint_rigid_group": "Rijit grup", + "cmd.joint_solve": "Bağlantıları çöz", + "cmd.material_assign": "Fiziksel malzeme", + "cmd.material_create": "Yeni fiziksel malzeme", + "cmd.material_delete": "Fiziksel malzemeyi sil", + "cmd.material_edit": "Fiziksel malzemeyi düzenle", + "cmd.material_list": "Malzemeleri listele", + "cmd.mesh_convert": "Ağı dönüştür", + "cmd.model_edges": "Kenarları listele", + "cmd.model_faces": "Yüzleri listele", + "cmd.model_threads": "Dişleri listele", + "cmd.motion_delete": "Hareket etüdünü sil", + "cmd.motion_export": "Hareket etüdünü dışa aktar", + "cmd.motion_list": "Hareket etütlerini listele", + "cmd.motion_play": "Hareket etüdünü oynat", + "cmd.motion_study": "Hareket etüdü", + "cmd.occurrence_copy": "Yapıştır (örnek)", + "cmd.occurrence_ground": "Sabitle", + "cmd.occurrence_move": "Örneği taşı", + "cmd.occurrence_properties": "Örneğin fiziksel özellikleri", + "cmd.parameters_add": "Kullanıcı parametresi ekle", + "cmd.parameters_change": "Parametreleri değiştir", + "cmd.parameters_comment": "Parametreye yorum ekle", + "cmd.parameters_complete": "İfadeyi tamamla", + "cmd.parameters_delete": "Parametreyi sil", + "cmd.parameters_export": "Parametreleri dışa aktar", + "cmd.parameters_favorite": "Favori parametre", + "cmd.parameters_move": "Parametreyi taşı", + "cmd.parameters_graph": "Parametre grafiği", + "cmd.parameters_import": "Parametreleri içe aktar", + "cmd.parameters_list": "Parametreleri listele", + "cmd.parameters_rename": "Parametreyi yeniden adlandır", + "cmd.parameters_users": "Parametre kullanımları", + "cmd.parts_fastener": "Bağlantı elemanı ekle", + "cmd.parts_insert": "Parça ekle", + "cmd.parts_library": "Standart parçalar", + "cmd.parts_resize": "Parça boyutunu değiştir", + "cmd.plastic_assign_rule": "Plastik kuralı ata", + "cmd.plastic_boss": "Göbek", + "cmd.plastic_lip": "Dudak", + "cmd.plastic_manage_rules": "Plastik kurallarını yönet", + "cmd.plastic_rest": "Dayanak", + "cmd.plastic_rules": "Plastik kurallarını listele", + "cmd.plastic_snap_fit": "Geçmeli bağlantı", + "cmd.select_clear": "Seçimi temizle", + "cmd.sheet_convert": "Sac metale dönüştür", + "cmd.sheet_export_bend_table": "Büküm tablosunu dışa aktar", + "cmd.sheet_export_dxf": "Açınımı DXF olarak dışa aktar", + "cmd.sheet_flange": "Flanş", + "cmd.sheet_flat_pattern": "Açınım oluştur", + "cmd.sheet_fold": "Katla", + "cmd.sheet_hem": "Kenet", + "cmd.sheet_manage_rules": "Sac metal kuralları", + "cmd.sheet_perforate": "Perfore et", + "cmd.sheet_refold": "Yeniden katla", + "cmd.sheet_rules": "Sac metal kurallarını listele", + "cmd.sheet_unfold": "Katlamayı aç", + "cmd.sketch_arc_center_point": "Merkez noktalı yay", + "cmd.sketch_arc_tangent": "Teğet yay", + "cmd.sketch_arc_three_point": "3 noktalı yay", + "cmd.sketch_auto_constrain": "Otomatik kısıtlama", + "cmd.sketch_auto_constrain_from_datum": "Referanstan otomatik kısıtlama", + "cmd.sketch_auto_project": "Kenarları referansa otomatik yansıt", + "cmd.sketch_blend_curve": "Geçiş eğrisi", + "cmd.sketch_chain": "Zincir", + "cmd.sketch_chamfer_distance_angle": "Mesafe ve açıyla pah", + "cmd.sketch_chamfer_equal_distance": "Eşit mesafeli pah", + "cmd.sketch_chamfer_two_distance": "İki mesafeli pah", + "cmd.sketch_circle_center": "Merkez ve çap ile daire", + "cmd.sketch_circle_three_point": "3 noktalı daire", + "cmd.sketch_circle_three_tangent": "3 teğetli daire", + "cmd.sketch_circle_two_point": "2 noktalı daire", + "cmd.sketch_circle_two_tangent": "2 teğetli daire", + "cmd.sketch_constrainer": "Eskiz kısıtlaması", + "cmd.sketch_constraint_fix": "Sabitle/Çöz", + "cmd.sketch_constraint_midpoint": "Orta nokta", + "cmd.sketch_construction": "Normal/Yapı", + "cmd.sketch_copy": "Eskiz öğelerini kopyala", + "cmd.sketch_cut": "Eskiz öğelerini kes", + "cmd.sketch_delete": "Eskiz öğelerini sil", + "cmd.sketch_dimension_text": "Ölçü metnini taşı", + "cmd.sketch_drag": "Eskiz geometrisini sürükle", + "cmd.sketch_drag_end": "Eskiz sürüklemeyi bitir", + "cmd.sketch_draw_dimensioned": "Eskiz geometrisini ölçülerle çiz", + "cmd.sketch_edit": "Eskizi düzenle", + "cmd.sketch_edit_text": "Metni düzenle", + "cmd.sketch_export_dxf": "DXF olarak kaydet", + "cmd.sketch_finish_auto_constrain": "Otomatik kısıtlamayla bitir", + "cmd.sketch_fit_curves_to_section": "Eğrileri ağ kesitine uydur", + "cmd.sketch_glyphs": "Kısıtlama simgeleri", + "cmd.sketch_include_3d": "3D geometriyi dahil et", + "cmd.sketch_insert_dxf": "DXF ekle", + "cmd.sketch_insert_svg": "SVG ekle", + "cmd.sketch_inspect": "Eskizi incele", + "cmd.sketch_intersection_curve": "Kesişim eğrisi", + "cmd.sketch_isoparametric_curve": "İzoparametrik eğri", + "cmd.sketch_line3d": "3D çizgi", + "cmd.sketch_line_midpoint": "Orta noktadan geçen çizgi", + "cmd.sketch_move": "Eskiz öğelerini taşı/kopyala", + "cmd.sketch_move3d": "3D noktayı taşı", + "cmd.sketch_move_point": "Eskiz noktasını sürükle", + "cmd.sketch_offset_break": "Ofset bağını kopar", + "cmd.sketch_options": "Eskiz paleti seçenekleri", + "cmd.sketch_paste": "Eskiz öğelerini yapıştır", + "cmd.sketch_point3d": "3D nokta", + "cmd.sketch_polygon_circumscribed": "Dışa çizilmiş çokgen", + "cmd.sketch_polygon_edge": "Bir kenar üzerinden çokgen", + "cmd.sketch_polygon_inscribed": "İçe çizilmiş çokgen", + "cmd.sketch_project_to_surface": "Yüzeye yansıt", + "cmd.sketch_rectangle_center": "Merkezden dikdörtgen", + "cmd.sketch_rectangle_rounded": "Yuvarlatılmış dikdörtgen", + "cmd.sketch_rectangle_three_point": "3 noktalı dikdörtgen", + "cmd.sketch_rectangle_two_point": "2 noktalı dikdörtgen", + "cmd.sketch_redefine": "Eskiz düzlemini yeniden tanımla", + "cmd.sketch_slot_arc_center": "Merkez noktalı yay yuva", + "cmd.sketch_slot_arc_three_point": "3 noktalı yay yuva", + "cmd.sketch_slot_center_point": "Merkez noktalı yuva", + "cmd.sketch_slot_center_to_center": "Merkezden merkeze yuva", + "cmd.sketch_slot_overall": "Toplam uzunluklu yuva", + "cmd.sketch_snap": "Yakalama çıkarımı", + "cmd.sketch_solve": "Eskizi çöz", + "cmd.sketch_spline3d": "3D spline", + "cmd.sketch_spline_control_point": "Kontrol noktalı spline", + "cmd.sketch_spline_control_point_5": "Kontrol noktalı spline (derece 5)", + "cmd.sketch_spline_fit_point": "Uydurma noktalı spline", + "cmd.sketch_spun_profile": "Döndürülmüş profil", + "cmd.sketch_toggle_driven": "Türetilmiş ölçüyü aç/kapat", + "cmd.solid_align": "Hizala", + "cmd.solid_boundary_fill": "Sınır dolgusu", + "cmd.solid_bounding_solid": "Sınırlayıcı gövde", + "cmd.solid_emboss": "Kabartma", + "cmd.solid_move": "Taşı/Kopyala", + "cmd.solid_offset_face": "Yüzü ötele", + "cmd.solid_press_pull": "Bas/Çek", + "cmd.solid_remove": "Kaldır", + "cmd.solid_replace_face": "Yüzü değiştir", + "cmd.solid_rib": "Nervür", + "cmd.solid_split_face": "Yüzü böl", + "cmd.solid_web": "Ağ nervürü", + "cmd.surface_patch": "Yama", + "cmd.surface_stitch": "Dikiş", + "cmd.surface_thicken": "Kalınlaştır", + "cmd.surface_extrude": "Yüzey ekstrüzyonu", + "cmd.surface_revolve": "Yüzey döndürme", + "cmd.surface_sweep": "Yüzey süpürme", + "cmd.surface_loft": "Yüzey loftu", + "cmd.surface_ruled": "Regle yüzey", + "cmd.surface_boundary": "Sınır yüzeyi", + "cmd.surface_offset": "Ofset yüzey", + "cmd.surface_blend": "Geçiş yüzeyi", + "cmd.surface_fillet": "Yüzey yuvarlatma", + "cmd.surface_untrim": "Kırpmayı kaldır", + "cmd.surface_unstitch": "Dikişi aç", + "cmd.surface_reverse_normal": "Normali ters çevir", + "cmd.inspect_continuity": "Süreklilik kontrolü", + "cmd.timeline_add": "Kaydedilmiş özellik ekle", + "cmd.timeline_compute_all": "Tümünü hesapla", + "cmd.timeline_copy": "Özellikleri kopyala", + "cmd.timeline_dependents": "Özellik bağımlılıkları", + "cmd.timeline_export_script": "Komut betiğini dışa aktar", + "cmd.timeline_inspect": "Özelliği incele", + "cmd.timeline_paste": "Özellikleri yapıştır", + "cmd.timeline_redefine": "Özelliği düzenle", + "cmd.timeline_rename": "Yeniden adlandır", + "cmd.timeline_reorder": "Özelliği yeniden sırala", + "cmd.timeline_roll_to": "Geçmiş işaretçisini taşı", + "cmd.timeline_rollback": "Zaman çizelgesi işaretçisini taşı", + "cmd.timeline_suppress": "Özelliği bastır", + "cmd.view_apply": "Adlandırılmış görünümü geri yükle", + "cmd.view_delete": "Adlandırılmış görünümü sil", + "cmd.view_list": "Adlandırılmış görünümleri listele", + "cmd.view_rename": "Adlandırılmış görünümü yeniden adlandır", + "cmd.view_save": "Yeni adlandırılmış görünüm", + "dialog.computing": "Hesaplanıyor… {seconds} sn", + "dialog.custom_axis": "↖ Özel eksen", + "dialog.edit_title": "{title} düzenleniyor", + "dialog.select": "↖ Seç", + "dialog.selected_count": "↖ {count} seçildi", + "dialog.step": "Adım", + "dialog.selection_step": "{step}/{total}: {input} seçin", + "dialog.selection_guidance": "Değiştirmek için bir girdi seçin. Kaldırmak için seçili nesnelere tıklayın; Ctrl/Cmd+tıklama ile de seçime ekleyip çıkarabilirsiniz. Önizlemeyi kontrol edin ve ardından OK'e basın.", + "document.save_changes": "{name} içindeki değişiklikler kaydedilsin mi?", + "document.unsaved_changes": "{name} kaydedilmemiş değişiklikler içeriyor. Kaydetmezseniz bunlar kaybolur.", + "home.documentation": "Belgeler", + "home.in_this_browser": "bu tarayıcıda", + "home.missing": "eksik", + "home.open": "Aç…", + "home.opened_days_ago": "{count} gün önce açıldı", + "home.opened_hours_ago": "{count} sa. önce açıldı", + "home.opened_just_now": "Az önce açıldı", + "home.opened_minutes_ago": "{count} dk. önce açıldı", + "home.opening": "açılıyor…", + "home.recent": "Son kullanılanlar", + "home.report_issue": "Sorun bildir", + "home.samples": "Örnekler", + "home.whats_new": "Yenilikler", + "sample.bracket.about": "2 mm sac metal kuralına göre kenar flanşları ve bir kenet içeren taban flanşı", + "sample.bracket.name": "Sac metal köşebent", + "sample.enclosure.about": "Dudak, vida göbekleri, dayanak ve geçmeli bağlantı içeren, içi boşaltılmış blok", + "sample.enclosure.name": "Plastik muhafaza", + "sample.flange.about": "Parametre kontrollü dairesel desene sahip göbek ve flanş", + "sample.flange.name": "Cıvatalı flanş", + "sample.hinge.about": "İki bileşen ve 60°'ye tahrik edilen bir döner bağlantı", + "sample.hinge.name": "Menteşe montajı", + "sample.plate.about": "Yuvarlatmalar, delikler ve düz havşalı bir göbek içeren parametrik plaka", + "sample.plate.name": "Örnek plaka", + "sample.vents.about": "Dikdörtgen desende yuvalar: satırlar, sütunlar ve aralık parametredir", + "sample.vents.name": "Havalandırma plakası", + "settings.msaa_applies_on_restart": "Kenar yumuşatma, SolidCraft bir sonraki başlatıldığında uygulanır", + "settings.msaa_reset": "{setting}: {requested}× bu grafik aygıtı tarafından desteklenmiyor; {reset}× olarak ayarlandı (desteklenen: {supported}).", + "settings.msaa_unsupported": "Bu grafik aygıtı tarafından desteklenmiyor", + "settings.reset_intro": "Bu ayarlar bu bilgisayarda çalışmadığı ve SolidCraft'ın başlamasını engelleyeceği için değiştirildi:", + "settings.reset_title": "Ayarlar değiştirildi", + "sketch.degrees_of_freedom": "{count} serbestlik derecesi", + "sketch.draw_curves": "{linetype} olarak çiz", + "sketch.make_selection": "Seçimi {linetype} olarak işaretle", + "ui.1_degree_of_freedom": "1 serbestlik derecesi", + "ui.3d_mouse_speed": "3D fare hızı", + "ui.3d_mouse_windows": "3D fare (Windows)", + "ui.3d_sketch": "3D eskiz", + "ui.about": "Hakkında", + "ui.activate": "Etkinleştir", + "ui.active_component": "Etkin bileşen", + "ui.agent_cursor": "Ajan imleci", + "ui.agent_cursor_speed": "Ajan imleci hızı", + "ui.agent_chat": "Ajan sohbeti", + "ui.agent_chat_command": "Ajan komutu", + "ui.agent_chat_desktop_only": "Ajan sohbeti masaüstü uygulamasını gerektirir.", + "ui.agent_chat_side": "Ajan sohbeti konumu", + "ui.agent_chat_left": "Sol", + "ui.agent_chat_right": "Sağ", + "ui.agent_chat_turn_limit": "Mesaj başına değişiklik", + "ui.agent_chat_privacy_note": "SolidCraft hiçbir yere bir şey göndermez: Başlattığınız ajan, sizin hesabınızla kendi hizmetine bağlanır. SolidCraft hiçbir anahtarı veya parolayı görmez ve kaydetmez.", + "ui.agent_chat_connect": "Bağlan", + "ui.agent_chat_stop": "Durdur", + "ui.agent_chat_stop_tip": "Ajanı ve başlattığı her şeyi durdur", + "ui.agent_chat_close": "Kapat", + "ui.agent_chat_minimize": "Bir çubuğa küçült", + "ui.agent_chat_dock_left": "Sola yerleştir", + "ui.agent_chat_dock_right": "Sağa yerleştir", + "ui.agent_chat_send": "Gönder", + "ui.agent_chat_cancel": "İptal", + "ui.agent_chat_refresh": "Yenile", + "ui.agent_chat_pick": "Ajan", + "ui.agent_chat_custom_hint": "stdin ve stdout üzerinden Agent Client Protocol'ü kullanan herhangi bir program. Kabuk (shell) olmadan çalıştırılır.", + "ui.agent_chat_not_installed": "Yüklü değil", + "ui.agent_chat_none_found": "Kodlama ajanı bulunamadı. Bunlardan birini yükleyin ve ardından Yenile'ye tıklayın:", + "ui.agent_chat_detecting": "Ajanlar aranıyor…", + "ui.agent_chat_signed_in": "oturum açık", + "ui.agent_chat_key_in_env": "anahtar ayarlı", + "ui.agent_chat_not_signed_in": "oturum açık değil", + "ui.agent_chat_state_off": "Bağlı değil", + "ui.agent_chat_state_starting": "Başlatılıyor…", + "ui.agent_chat_state_ready": "Hazır", + "ui.agent_chat_state_busy": "Çalışıyor…", + "ui.agent_chat_state_auth": "Oturum açılması gerekiyor", + "ui.agent_chat_state_exited": "Ajan sonlandı", + "ui.agent_chat_changes_of": "{n}/{limit} değişiklik", + "ui.agent_chat_auth_title": "Ajan için oturum aç", + "ui.agent_chat_auth_needed": "Ajan oturum açmanızı istiyor. Oturumu ajanın kendisinde açarsınız; SolidCraft parolanızı veya anahtarlarınızı asla görmez.", + "ui.agent_chat_auth_none": "Ajan burada oturum açma imkânı sunmuyor: Belgelerinde açıklandığı şekilde oturum açın.", + "ui.agent_chat_auth_terminal": "Bunu bir terminalde çalıştırın ve ardından tekrar Bağlan'a tıklayın:", + "ui.agent_chat_auth_agent": "{name} ile oturum aç", + "ui.agent_chat_auth_env": "{vars} ortam değişkenlerini ayarlayın ve SolidCraft'ı yeniden başlatın.", + "ui.agent_chat_auth_retry": "Oturum açtım: yeniden bağlan", + "ui.agent_chat_copy": "Kopyala", + "ui.agent_chat_permission": "Ajan şunu çalıştırmak istiyor: {title}", + "ui.agent_chat_answered": "Yanıt: {option}", + "ui.agent_chat_approval": "Ajanın bunu yapmasına izin verilsin mi?", + "ui.agent_chat_allow": "İzin ver", + "ui.agent_chat_deny": "Reddet", + "ui.agent_chat_allowed": "İzin verildi", + "ui.agent_chat_denied": "Reddedildi", + "ui.agent_chat_changes": "{n} değişiklik, tek geri alma adımı", + "ui.agent_chat_undo_changes": "Bu değişiklikleri geri al", + "ui.agent_chat_undone": "(geri alındı)", + "ui.agent_chat_undo_label": "Ajan sohbeti: {message}", + "ui.agent_chat_limit": "Ajan, bir mesaj için {limit} değişiklik sınırına ulaştı. Devam etmesi için başka bir mesaj gönderin.", + "ui.agent_chat_refused": "Ajan için izin verilmiyor: {reason}", + "ui.agent_chat_wait_turn": "Ajan hâlâ son mesaj üzerinde çalışıyor: Bekleyin veya İptal'e tıklayın.", + "ui.agent_chat_placeholder": "Ajandan tasarımı değiştirmesini isteyin…", + "ui.agent_chat_attach_view": "Görünümü ekle", + "ui.agent_chat_attach_view_tip": "Geçerli görünümün bir resmini mesajla birlikte gönder", + "ui.agent_chat_no_images": "Bu ajan resim kabul etmiyor", + "ui.agent_chat_view_attached": "Görünüm eklendi", + "ui.agent_chat_no_cli": "solidcraft-cli uygulamanın yanında bulunamadı, bu yüzden ajan tasarıma erişemiyor.", + "ui.agent_chat_no_control": "Ajan sohbetinin uç noktası başlatılmadı, bu yüzden ajan tasarıma erişemiyor.", + "ui.agent_chat_exited": "Ajan sonlandırıldı.", + "ui.agent_chat_failed_start": "Ajan başlatılamadı: {error}", + "ui.agent_chat_intro": "Zaten kullandığınız bir kodlama ajanıyla veya seçtiğiniz bir model uç noktasıyla sohbet edin. Ajan, SolidCraft'ın araçlarıyla açık tasarım üzerinde çalışır: Değişiklikleri hemen görünür ve mesaj başına tek adımda geri alınabilir. Sormadan neleri yapabileceğini Ayarlar > AI altında belirlersiniz.", + "ui.agent_chat_privacy": "Kendi hesabınızla çalıştırdığınız ajan dışında hiçbir yere bir şey gitmez.", + "ui.agent_chat_none_found_short": "Ajan bulunamadı", + "ui.ai_add": "Ekle", + "ui.ai_add_agent": "Ajan ekle…", + "ui.ai_add_agent_title": "Ajan ekle", + "ui.ai_add_api": "OpenAI uyumlu API", + "ui.ai_add_custom": "Özel komut", + "ui.ai_added": "eklendi", + "ui.ai_add_installed": "Yüklü ajan", + "ui.ai_add_installed_note": "Yüklü bir ajan için ayrı bir giriş (örneğin farklı argümanlarla). Yüklü ajanlar kendiliğinden görünür.", + "ui.ai_agent_mode_tip": "Ajanın kendi modu: Kendi araçları (kabuk, dosya değişiklikleri) bu modu izler. SolidCraft'ın araçları Ayarlar > AI altındaki izinleri izler.", + "ui.ai_agents": "Ajanlar", + "ui.ai_always_allow": "Her zaman izin ver", + "ui.ai_always_allowed": "Her zaman izin verilenler", + "ui.ai_always_allowed_none": "Henüz her zaman izin verilen bir şey yok. Sohbette verdiğiniz “Her zaman izin ver” yanıtları burada görünür.", + "ui.ai_always_allow_tip": "{tool} için bu ajana bundan sonra sormadan izin ver", + "ui.ai_auto_allowed": "{title} için otomatik olarak izin verildi ({why})", + "ui.ai_auto_mode": "İzin ayarınız", + "ui.ai_auto_ours": "SolidCraft kendi araçlarını kendisi denetler", + "ui.ai_auto_remembered": "“Her zaman izin ver” seçeneğini seçtiniz", + "ui.ai_bad_url": "http:// veya https:// ile başlayan bir URL girin", + "ui.ai_base_url": "Temel URL", + "ui.ai_button": "AI", + "ui.ai_copy_suffix": "Kopya", + "ui.ai_custom_url": "Özel URL", + "ui.ai_default": "Varsayılan", + "ui.ai_http_busy": "uç nokta meşgul veya sınırda; daha sonra tekrar deneyin", + "ui.ai_http_key": "uç nokta anahtarı reddetti: Ayarlar > AI altında kontrol edin", + "ui.ai_http_not_found": "Uç nokta veya model bulunamadı: temel URL'yi ve model adını kontrol edin", + "ui.ai_key": "API anahtarı", + "ui.ai_keychain_error": "Sistem anahtar zinciri reddetti: {error}", + "ui.ai_key_hint": "isteğe bağlı; sistem anahtar zincirinde saklanır", + "ui.ai_key_needs_https": "Anahtar yalnızca HTTPS üzerinden veya bu bilgisayara gönderilir.", + "ui.ai_key_note": "SolidCraft ayarlarında değil, sistem anahtar zincirinde saklanır. Yerel bir sunucu için boş bırakın.", + "ui.ai_mode_all": "Her şeye izin ver", + "ui.ai_mode_all_note": "Hiçbir işlem için önceden onay istenmez. Çökme raporlarına yine erişilemez ve klasör sınırları geçerliliğini korur.", + "ui.ai_mode_all_warning": "Ajan tasarımınızı sormadan kaydedebilir, üzerine yazabilir, dışa aktarabilir ve değiştirebilir. Bunu yalnızca güvendiğiniz bir ajanla ve kaydedilmiş tasarımlarla kullanın.", + "ui.ai_mode_ask": "Her seferinde sor", + "ui.ai_mode_ask_note": "Tasarımdaki her değişiklik ve her dosya işlemi izninizi bekler.", + "ui.ai_mode_edits": "Model değişikliklerine otomatik izin ver", + "ui.ai_mode_edits_note": "Modelleme komutları onay istemeden çalışır; kaydetme, açma, dışa aktarma ve diğer dosya ya da yıkıcı işlemler için yine onay istenir.", + "ui.ai_mode_global": "Yukarıda ayarlandığı gibi", + "ui.ai_model": "Model", + "ui.ai_modes_scope": "Bu ayarlar SolidCraft araçları için geçerlidir. Bir ajanın kendi araçları (kabuğu, dosya değişiklikleri), ajanın modları varsa sohbet panelinin başlığında seçtiğiniz kendi modunu izler.", + "ui.ai_name": "Ad", + "ui.ai_need_command": "Ajanı başlatan komutu girin", + "ui.ai_need_model": "Model adını girin", + "ui.ai_no_answer": "Ajan zamanında yanıt vermedi", + "ui.ai_no_http": "Bu derleme API uç noktalarına erişemez", + "ui.ai_no_keychain": "Sistem anahtar zinciri kullanılamıyor, bu yüzden anahtar kaydedilemez. Anahtarsız yerel bir sunucu yine de çalışır.", + "ui.ai_panel": "Panel", + "ui.ai_permissions": "İzinler", + "ui.ai_preset": "Şablon", + "ui.ai_remove": "Kaldır", + "ui.ai_request_limit": "bir mesaj için 24 istekten sonra durduruldu; devam etmek için başka bir mesaj gönderin", + "ui.ai_reset": "Sıfırla", + "ui.ai_settings": "AI ayarları…", + "ui.ai_show_features": "AI özelliklerini göster", + "ui.ai_show_features_note": "Ajan sohbeti: zaten kullandığınız bir kodlama ajanının veya seçtiğiniz bir model uç noktasının açık tasarım üzerinde çalıştığı bir panel. Kapalı: AI düğmesi yok, kısayol yok, menü girişi yok, panel yok ve hiçbir şey aranmaz veya başlatılmaz.", + "ui.ai_switch_tip": "Bu sohbet için ajanı değiştir", + "ui.ai_test": "Test et", + "ui.ai_test_acp_ok": "{agent} yanıt veriyor", + "ui.ai_test_acp_tip": "Ajanı kısa süreliğine başlatır ve bir oturum ister; ardından tekrar kapatır", + "ui.ai_test_api_tip": "Uç noktadan model listesini ister", + "ui.ai_testing": "Test ediliyor…", + "ui.ai_test_no_model": "Uç noktaya ulaşıldı, {count} model bulundu ancak {model} aralarında yok", + "ui.ai_test_ok": "Uç noktaya ulaşıldı, {count} model bulundu", + "ui.ai_toolbar_button": "Araç çubuğunda düğmeyi göster", + "ui.ai_toolbar_button_note": "Araç çubuğunun sağ ucundaki AI düğmesi. Ctrl+Shift+A ve Görünüm menüsü paneli açmaya devam eder.", + "ui.ai_tool_done": "tamamlandı", + "ui.ai_tool_failed": "başarısız", + "ui.ai_tool_running": "çalışıyor", + "ui.ai_tool_unfold": "Sonucu göstermek için tıklayın", + "ui.ai_tool_waiting": "bekliyor", + "ui.ai_undo_tip": "Ajanın bu mesaj için değiştirdiği her şeyi tek adımda geri al", + "AI": "AI", + "ui.all": "Tümü", + "ui.analysis": "Analiz", + "ui.angle": "Açı", + "ui.angle_decimals": "Açı ondalık basamakları", + "ui.animate_view_changes": "Görünüm değişikliklerini animasyonla göster", + "ui.animation": "Animasyon", + "ui.animation_speed": "Animasyon hızı", + "ui.anti_aliasing": "Kenar yumuşatma", + "ui.supersampling": "Süper örnekleme (SSAA)", + "ui.supersampling_off": "Kapalı (1×)", + "ui.supersampling_adaptive": "Yalnızca görünüm hareketsizken", + "settings.supersampling_note": "Görünümü daha yüksek çözünürlükte çizer ve küçültür: 4K altındaki ekranlarda kenarlar, çizgiler ve ızgaralar daha pürüzsüz görünür. GPU süresi gerektirir: 1,5× ayarında yaklaşık 2,25 kat, 2× ayarında 4 kat daha fazla piksel işlenir.", + "ui.display_quality": "Görüntü kalitesi", + "ui.display_quality_coarse": "Kaba", + "ui.display_quality_normal": "Normal", + "ui.display_quality_fine": "İnce", + "ui.display_quality_ultra": "Ultra", + "settings.display_quality_note": "Daha ince seviyeler eğri yüzeyleri ve kenarları daha pürüzsüz gösterir, ancak ağ oluşturma daha uzun sürer. Yalnızca görünüm değişir; tasarım ve dışa aktarımlar asla değişmez.", + "ui.apply": "Uygula", + "ui.arc": "Yay", + "ui.assemble": "Montaj", + "ui.autosave_every": "Otomatik kaydetme aralığı", + "ui.axes": "Eksenler", + "ui.axis": "Eksen", + "ui.base_point": "Temel nokta", + "ui.bodies": "Gövdeler", + "ui.box": "Kutu", + "ui.break": "Kır", + "ui.cancel": "İptal", + "ui.canvases": "Tuvaller", + "ui.center": "Merkez", + "ui.centerline": "Merkez çizgisi", + "ui.chain": "Zincir", + "ui.chamfer": "Pah", + "ui.chamfer_type": "Pah türü", + "ui.change_workspace": "Çalışma alanını değiştir", + "ui.chord_length": "Kiriş uzunluğu", + "ui.curvature_g2": "Eğrilik sürekliliği (G2)", + "ui.equivalent_radius": "Eşdeğer yarıçap", + "ui.circle": "Daire", + "ui.circular_pattern": "Dairesel desen", + "ui.clear": "Temizle", + "ui.clear_recent": "Son kullanılanları temizle", + "ui.clear_the_selection": "Seçimi temizle", + "ui.click_selects_whole_bodies": "Tıklama tüm gövdeyi seçer", + "ui.click_then_press_key": "Tıklayın, ardından yeni tuşa basın", + "ui.close": "Kapat", + "ui.material_review.title": "Fiziksel malzeme verilerini kontrol et", + "ui.material_review.scope": "Yalnızca aday: atanmaz veya kaydedilmez. Sayısal kontrol teknik bir sertifika değildir.", + "ui.material_review.input": "Şema 1 malzeme kartını yapıştırın (JSON)", + "ui.material_review.review": "Kartı kontrol et", + "ui.material_review.limit": "Kart 256 KiB giriş sınırını aşıyor.", + "ui.material_review.unknown": "Bilinmiyor", + "ui.material_review.properties": "Özellikler", + "ui.material_review.conditions": "Belirtilen koşullar", + "ui.material_review.source": "Kaynak", + "ui.material_review.axes": "Malzemenin yerel eksenleri; gövde yönlendirmesi atanmadı.", + "ui.material_review.derived": "Türetilmiş izotropik modüller", + "ui.material_review.claims": "Kaynaklar ve lisanslar doğrulanmamış beyanlardır. Eksik değerler bilinmiyor olarak kalır.", + "ui.material_review.density": "Yoğunluk", + "ui.material_review.elasticity": "Elastikiyet", + "ui.material_review.tensile_strength": "Çekme dayanımı", + "ui.material_review.compressive_strength": "Basma dayanımı", + "ui.material_review.yield_strength": "Akma dayanımı", + "ui.material_review.shear_strength": "Kesme dayanımı", + "ui.material_review.thermal_conductivity": "Isıl iletkenlik", + "ui.material_review.thermal_expansion": "Isıl genleşme", + "ui.material_review.specific_heat": "Özgül ısı kapasitesi", + "ui.material_review.moisture_unit": "kg su / kg kuru malzeme", + "ui.coil": "Helezon", + "ui.coincident": "Çakışık", + "ui.collapse": "Daralt", + "ui.collinear": "Eşdoğrusal", + "ui.colour_vision": "Renk görme", + "ui.colour_vision_deutan": "Deutan", + "ui.colour_vision_deutan_tip": "Zayıf veya eksik yeşil algısı için", + "ui.colour_vision_failed": "Hata", + "ui.colour_vision_fixed": "Sabitlenmiş", + "ui.colour_vision_mode": "Mod", + "ui.colour_vision_note": "Anlam taşıyan renkleri değiştirir: eskiz durumu, eksenler, bükümler, analizler ve simgeler. Windows renk filtrelerini kullanıyorsanız bunu “Kapalı” bırakın.", + "ui.colour_vision_off": "Kapalı", + "ui.colour_vision_off_tip": "Tasarımın kendi renkleri", + "ui.colour_vision_projected": "Yansıtılmış", + "ui.colour_vision_protan": "Protan", + "ui.colour_vision_protan_tip": "Zayıf veya eksik kırmızı algısı için", + "ui.colour_vision_sample": "Örnek", + "ui.colour_vision_tritan": "Tritan", + "ui.colour_vision_tritan_tip": "Zayıf veya eksik mavi algısı için", + "ui.combine": "Birleştir", + "ui.coming_later": "yakında", + "ui.concentric": "Eş merkezli", + "ui.configurations": "Konfigürasyonlar", + "ui.conic_curve": "Konik eğri", + "ui.constant": "Sabit", + "ui.constraints_conflict": "Kısıtlamalar çakışıyor", + "ui.construct": "Yapı", + "ui.construction": "Yapı çizgisi", + "ui.context_menu": "Bağlam menüsü", + "ui.copy": "Kopyala", + "ui.corner": "Köşe", + "ui.corners": "Köşeler", + "ui.counterbore": "Düz havşa", + "ui.countersink": "Konik havşa", + "ui.create": "Oluştur", + "ui.create_copy": "Kopya oluştur", + "ui.create_sketch": "Eskiz oluştur", + "ui.current": "geçerli", + "ui.curvature": "Eğrilik", + "ui.curves": "Eğriler", + "ui.cut": "Kes", + "ui.cylinder": "Silindir", + "ui.dark": "Koyu", + "ui.default_modelling_orientation": "Varsayılan modelleme yönü", + "ui.degrees_of_freedom": "Serbestlik dereceleri", + "ui.delete": "Sil", + "ui.depth": "Derinlik", + "ui.design": "Tasarım", + "ui.diameter": "Çap", + "ui.dimension": "Ölçü", + "ui.direction": "Yön", + "ui.distance": "Mesafe", + "ui.distance_1": "Mesafe 1", + "ui.distance_2": "Mesafe 2", + "ui.document_settings": "Belge ayarları", + "ui.don_t_save": "Kaydetme", + "ui.draft": "Koniklik", + "ui.drawing": "Teknik resim", + "ui.drill_point": "Matkap ucu", + "ui.edit": "Düzenle", + "ui.edit_section_analysis": "Kesit analizini düzenle", + "ui.ellipse": "Elips", + "ui.end_radius": "Bitiş yarıçapı", + "ui.entities": "Öğeler", + "ui.equal": "Eşit", + "ui.expand": "Genişlet", + "ui.export_ellipsis": "Dışa aktar...", + "ui.export_ellipsis_keymap": "Dışa aktar…", + "ui.export_keymap_tip": "Tuşları, S kutusu favorilerini ve araç çubuğunu dosya olarak dışa aktarır", + "ui.extend": "Uzat", + "ui.extent_type": "Kapsam türü", + "ui.extrude": "Ekstrüzyon", + "ui.factor": "Faktör", + "ui.feature_history": "Özellik geçmişi", + "ui.feature_options": "Özellik seçenekleri", + "ui.features": "Özellikler", + "ui.file": "Dosya", + "ui.fillet": "Yuvarlatma", + "ui.filter_commands_or_keys": "Komutları veya tuşları filtrele", + "ui.finish_sketch": "Eskizi bitir", + "ui.fix_unfix": "Sabitle/Çöz", + "ui.flat": "Düz", + "ui.flip": "Ters çevir", + "ui.front": "Ön", + "ui.fully_constrained": "Tam kısıtlı", + "ui.general": "Genel", + "ui.graphics": "Grafik", + "ui.ground_shadow": "Zemin gölgesi", + "ui.heading_add_ins": "EKLENTİLER", + "ui.heading_assemble": "MONTAJ", + "ui.heading_box": "KUTU", + "ui.heading_chamfer": "PAH", + "ui.heading_circular_pattern": "DAİRESEL DESEN", + "ui.heading_coil": "HELEZON", + "ui.heading_combine": "BİRLEŞTİR", + "ui.heading_configure": "YAPILANDIR", + "ui.heading_constraints": "KISITLAMALAR", + "ui.heading_construct": "YAPI", + "ui.heading_create": "OLUŞTUR", + "ui.heading_create_sketch": "ESKİZ OLUŞTUR", + "ui.heading_cylinder": "SİLİNDİR", + "ui.heading_design": "TASARIM", + "ui.heading_draft": "KONİKLİK", + "ui.heading_edit": "DÜZENLE", + "ui.heading_extrude": "EKSTRÜZYON", + "ui.heading_fillet": "YUVARLATMA", + "ui.heading_finish_sketch": "ESKİZİ BİTİR", + "ui.heading_front": "ÖN", + "ui.heading_hole": "DELİK", + "ui.heading_home": "BAŞLANGIÇ", + "ui.heading_insert": "EKLE", + "ui.heading_inspect": "İNCELE", + "ui.heading_loft": "LOFT", + "ui.heading_make": "ÜRET", + "ui.heading_measure": "Ölç", + "ui.heading_mesh": "AĞ", + "ui.heading_mirror": "AYNALA", + "ui.heading_modify": "DEĞİŞTİR", + "ui.heading_move": "TAŞI", + "ui.heading_offset": "OFSET", + "ui.heading_move_copy": "TAŞI/KOPYALA", + "ui.heading_offset_plane": "OFSET DÜZLEM", + "ui.heading_ok": "OK", + "ui.heading_parameters": "PARAMETRELER", + "ui.heading_pattern_on_path": "YOL ÜZERİNDE DESEN", + "ui.heading_pipe": "BORU", + "ui.heading_plane_at_angle": "AÇILI DÜZLEM", + "ui.heading_plastic": "PLASTİK", + "ui.heading_prepare": "HAZIRLA", + "ui.heading_rectangular_pattern": "DİKDÖRTGEN DESEN", + "ui.heading_revolve": "DÖNDÜR", + "ui.heading_right": "SAĞ", + "ui.heading_scale": "ÖLÇEKLENDİR", + "ui.heading_section_analysis": "KESİT ANALİZİ", + "ui.heading_select": "SEÇ", + "ui.heading_sheet_metal": "SAC METAL", + "ui.heading_shell": "KABUK", + "ui.heading_sketch": "ESKİZ", + "ui.heading_sketch_palette": "ESKİZ PALETİ", + "ui.heading_sketch_scale": "ESKİZİ ÖLÇEKLENDİR", + "ui.heading_solid": "KATI", + "ui.heading_sphere": "KÜRE", + "ui.heading_split_body": "GÖVDEYİ BÖL", + "ui.heading_surface": "YÜZEY", + "ui.heading_sweep": "SÜPÜR", + "ui.heading_thread": "DİŞ", + "ui.heading_top": "ÜST", + "ui.heading_torus": "TORUS", + "ui.heading_utilities": "ARAÇLAR", + "ui.heading_utility": "YARDIMCI ARAÇLAR", + "ui.help": "Yardım", + "ui.hide": "Gizle", + "ui.hole": "Delik", + "ui.hole_tap_type": "Diş türü", + "ui.hole_type": "Delik türü", + "ui.home": "Başlangıç", + "ui.horizontal_vertical": "Yatay/Dikey", + "ui.import_ellipsis": "İçe aktar…", + "ui.insert": "Ekle", + "ui.inspect": "İncele", + "ui.intersect": "Kesişim", + "ui.join": "Birleştir", + "ui.joints": "Bağlantılar", + "ui.keyboard_shortcuts": "Klavye kısayolları", + "ui.language": "Dil", + "ui.length_decimals": "Uzunluk ondalık basamakları", + "ui.light": "Açık", + "ui.line": "Çizgi", + "ui.linetype": "Çizgi türü", + "ui.loft": "Loft", + "ui.look_at": "Bak", + "ui.look_at_anim_desc": "Eksen görünümü, Bak, Başlangıç ve Sığdır", + "ui.manufacture": "Üretim", + "ui.measure": "Ölç", + "ui.midpoint": "Orta nokta", + "ui.mirror": "Aynala", + "ui.mirror_line": "Ayna çizgisi", + "ui.modify": "Değiştir", + "ui.move": "Taşı", + "ui.multiple": "Çoklu", + "ui.named_views": "Adlandırılmış görünümler", + "ui.navigation": "Gezinme", + "ui.needs_design": "{command}: Önce bir tasarım açın", + "ui.new_body": "Yeni gövde", + "ui.new_design": "Yeni tasarım", + "ui.normal": "Normal", + "ui.object_type": "Nesne türü", + "ui.objects": "Nesneler", + "ui.offer_to_stand_up_y_up_files": "Y ekseni yukarı olan dosyaları dikleştirmeyi öner", + "ui.offset": "Ofset", + "ui.offset_plane": "Ofset düzlem", + "ui.one_side": "Tek taraflı", + "ui.open": "Aç", + "ui.open_ellipsis": "Aç...", + "ui.open_preferences": "Ayarları aç", + "ui.open_recent": "Son kullanılanlar", + "ui.operation": "İşlem", + "ui.options": "Seçenekler", + "ui.orbit_around": "Etrafında döndür", + "ui.origin": "Orijin", + "ui.palette_points": "Noktalar", + "ui.palette_profile": "Profil", + "ui.pan_zoom_orbit": "Kaydır, yakınlaştır, döndür", + "ui.parallel": "Paralel", + "ui.parameters": "Parametreler", + "ui.paste": "Yapıştır", + "ui.path": "Yol", + "ui.pattern_on_path": "Yol üzerinde desen", + "ui.perpendicular": "Dik", + "ui.perspective_view": "Perspektif görünüm", + "ui.pipe": "Boru", + "ui.placement": "Yerleşim", + "ui.plane": "Düzlem", + "ui.plane_at_angle": "Açılı düzlem", + "ui.point": "Nokta", + "ui.point_under_the_cursor": "İmlecin altındaki nokta", + "ui.points": "Noktalar", + "ui.polygon": "Çokgen", + "ui.preferences": "Ayarlar", + "ui.press_a_key": "bir tuşa basın…", + "ui.profile": "Profil", + "ui.profile_plane": "Profil düzlemi", + "ui.profiles": "Profiller", + "ui.project": "Yansıt", + "ui.project_face_edges_sketch": "Yüz kenarlarını yeni eskizlere yansıt", + "ui.quantity": "Adet", + "ui.quantity_2": "Adet 2", + "ui.quit": "Çıkış", + "ui.radial_context_menu": "Dairesel bağlam menüsü", + "ui.radius": "Yarıçap", + "ui.pull_direction": "Kalıptan çıkarma yönü", + "ui.tool_direction": "Takım yönü", + "ui.reachable": "Erişilebilir", + "ui.blocked": "Engellenmiş", + "ui.radius_type": "Yarıçap türü", + "ui.rectangle": "Dikdörtgen", + "ui.rectangular_pattern": "Dikdörtgen desen", + "ui.redo": "Yinele", + "ui.render": "Render", + "ui.renderer": "Çizim motoru", + "ui.reset": "Sıfırla", + "ui.reset_all": "Tümünü sıfırla", + "ui.reset_the_settings_on_this_page": "Bu sayfadaki ayarları sıfırla", + "ui.restore_defaults": "Varsayılanları geri yükle", + "ui.reverse_zoom_direction": "Yakınlaştırma yönünü tersine çevir", + "ui.revolve": "Döndür", + "ui.right": "Sağ", + "ui.save": "Kaydet", + "ui.heading_save_mesh": "AĞ OLARAK KAYDET", + "ui.format": "Biçim", + "ui.mesh_format_stl": "STL", + "ui.mesh_format_3mf": "3MF", + "ui.mesh_format_3mf_tagged": "Yüz etiketli 3MF", + "ui.send_to_slicer": "Dilimleyiciye gönder", + "ui.slicer": "Dilimleyici", + "ui.custom_program": "Özel…", + "ui.no_slicer_found": "Dilimleyici bulunamadı", + "ui.send": "Gönder", + "ui.custom_program_tip": "Listeye bir dilimleyici programı ekle", + "ui.slicer_delete_tip": "{program}\nDelete tuşuyla listeden kaldır", + "ui.save_mesh_pick_bodies": "Kaydedilecek gövdeleri seçin", + "ui.save_mesh_no_slicer": "Dilimleyici bulunamadı: “Özel…” seçeneğini seçip dilimleyici programını belirtin veya “Dilimleyiciye gönder” seçeneğini kapatın", + "ui.not_a_program": "{path} başlatılabilir bir program değil", + "ui.sent_to_slicer": "{slicer} uygulamasına gönderildi", + "ui.saved_to": "{path} konumuna kaydedildi", + "ui.save_mesh_temp_failed": "{folder} oluşturulamadı: {error}", + "ui.save_as": "Farklı kaydet", + "ui.save_as_ellipsis": "Farklı kaydet...", + "ui.scale": "Ölçekle", + "ui.orientation": "Yönlendirme", + "ui.twist": "Burulma", + "ui.end_scale": "Bitiş ölçeği", + "ui.sweep_turn_with_path": "Yolla birlikte dön", + "ui.sweep_keep_as_drawn": "Çizildiği gibi", + "ui.sweep_follow_direction": "Yönü izle", + "ui.section_analysis": "Kesit analizi", + "ui.select": "Seç", + "ui.select_other_hint": "Diğerini seç: İmlecin altındaki her şeyi listelemek için sol tuşu model üzerinde hareket ettirmeden basılı tutun (veya sağ tık › Diğerini seç…); oradaki bir sonraki öğeyi seçmek için aynı noktaya tekrar tıklayın.", + "ui.selection": "Seçim", + "ui.shell": "Kabuk", + "ui.show": "Göster", + "ui.show_constraints": "Kısıtlamalar", + "ui.show_dimensions": "Ölçüler", + "ui.show_points": "Noktaları göster", + "ui.show_profile": "Profili göster", + "ui.show_projected_geometries": "Yansıtılmış geometriler", + "ui.simple": "Basit", + "ui.simulation": "Simülasyon", + "ui.single": "Tekli", + "ui.sketch": "Eskiz", + "ui.sketch_dimension": "Eskiz ölçüsü", + "ui.sketch_grid": "Eskiz ızgarası", + "ui.sketch_scale": "Eskiz ölçeği", + "ui.sketch_status": "Eskiz durumu", + "ui.sketches": "Eskizler", + "ui.slice": "Dilim", + "ui.slot": "Yuva", + "ui.smooth": "Pürüzsüz", + "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_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.spacing": "Aralık", + "ui.spacing_2": "Aralık 2", + "ui.sphere": "Küre", + "ui.spline": "Spline", + "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_radius": "Başlangıç yarıçapı", + "ui.sweep": "Süpür", + "ui.symmetric": "Simetrik", + "ui.symmetry": "Simetri", + "ui.system": "Sistem", + "ui.tangent": "Teğet", + "ui.taper_angle": "Konik açı", + "ui.tapped": "Kılavuzlu", + "ui.text": "Metin", + "ui.theme": "Tema", + "ui.thickness": "Kalınlık", + "ui.thread": "Diş", + "ui.timeline_bottom": "Zaman çizelgesi altta", + "ui.timeline_left_note": "Sol düzende geri sarma işaretçisi, parça ve sahne tarayıcısının üzerinde gösterilir.", + "ui.timeline_left_sidebar": "Sol kenar çubuğu", + "ui.tip_angle": "Uç açısı", + "ui.to_object": "Nesneye kadar", + "ui.top": "Üst", + "ui.torus": "Torus", + "ui.trackpad_pan_tip": "Dokunmatik yüzey hareketleri görünümü kaydırır (kapalı: tekerlek gibi yakınlaştırır); fare tekerleği yakınlaştırır, başparmak tekerleği yana kaydırır, iki parmakla sıkıştırma her zaman yakınlaştırır", + "ui.trim": "Kırp", + "ui.two_finger_scroll_pans": "İki parmakla kaydırma görünümü kaydırır", + "ui.two_sides": "İki taraflı", + "ui.ui_scale": "Arayüz ölçeği", + "ui.undo": "Geri al", + "ui.units": "Birimler", + "ui.units_of_new_designs": "Yeni tasarımların birimleri", + "ui.untitled": "Adsız", + "ui.up_axis_note": "Görünümlerde (eksen görünümü, Başlangıç, Bak) hangi eksenin yukarıyı gösterdiğini belirler. Tasarımlar değişmez.", + "ui.variable": "Değişken", + "ui.view_centre": "Görünüm merkezi", + "ui.visual_shaded_hidden_edges": "Gizli kenarlarla gölgeli", + "ui.visual_shaded_with_edges": "Kenarlarla gölgeli", + "ui.visual_style": "Görsel stil", + "ui.visual_wireframe": "Tel kafes", + "ui.workspace": "Çalışma alanı", + "ui.x_distance": "X mesafesi", + "ui.y_distance": "Y mesafesi", + "ui.y_up": "Y yukarı", + "ui.z_up": "Z yukarı", + "ui.zoom_to_cursor_tip": "Tekerlek, imlecin altındaki noktaya doğru yakınlaştırır (kapalı: görünümün merkezine doğru)", + "ui.zoom_to_the_cursor": "İmlece doğru yakınlaştır", + "A new configuration, a copy of the active one": "Etkin konfigürasyonun kopyası olan yeni bir konfigürasyon", + "About SolidCraft": "SolidCraft hakkında", + "Active": "Etkin", + "Active rule": "Etkin kural", + "Add": "Ekle", + "Add Key": "Tuş ekle", + "Add Mid Radius": "Ara yarıçap ekle", + "Add Row": "Satır ekle", + "All Sketch Points": "Tüm eskiz noktaları", + "All open designs": "Tüm açık tasarımlar", + "Allowed expressions, separated by semicolons": "Noktalı virgülle ayrılmış izin verilen ifadeler", + "Also deletes": "Bunları da siler", + "Angle 2": "Açı 2", + "Animate": "Canlandır", + "Appearance name": "Görünüm adı", + "Applied Radius": "Uygulanan yarıçap", + "Apply To": "Uygulama hedefi", + "Area": "Alan", + "Attachment": "Bağlama", + "BROWSER": "TARAYICI", + "Bend Line Position": "Büküm çizgisi konumu", + "Bend Position": "Büküm konumu", + "Bend Radius": "Büküm yarıçapı", + "Bends": "Bükümler", + "Body": "Gövde", + "Bounding box": "Sınırlayıcı kutu", + "CSV or JSON: updates existing parameters, adds new ones": "CSV veya JSON: mevcut parametreleri günceller, yenilerini ekler", + "Capture All Positions": "Tüm konumları yakala", + "Catch Direction": "Yakalama yönü", + "Cells": "Hücreler", + "Center X": "Merkez X", + "Center Y": "Merkez Y", + "Center of mass": "Kütle merkezi", + "Chamfer Type": "Pah türü", + "Check collisions": "Çarpışmaları kontrol et", + "Checked": "Kontrol edildi", + "Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.": "Yeni bir düzlem seçin. Eskiz geometrisi ve ölçüler, iki boyutlu koordinatlarında değişmeden kalır.", + "Close draft": "Taslağı kapat", + "Collisions": "Çarpışmalar", + "Colour": "Renk", + "Component1": "Bileşen1", + "Configuration": "Konfigürasyon", + "Configuration rules": "Konfigürasyon kuralları", + "Contact": "Temas", + "Copy all licences": "Tüm lisansları kopyala", + "Copy diagnostic information": "Tanılama bilgilerini kopyala", + "Copy report": "Raporu kopyala", + "Corner Relief Shape": "Köşe boşaltma şekli", + "Counterbore depth": "Düz havşa derinliği", + "Countersink angle": "Konik havşa açısı", + "Create Issue — review draft": "Sorun oluştur — taslağı gözden geçirin", + "Customize Toolbar": "Araç çubuğunu özelleştir", + "Delete all": "Tümünü sil", + "Delete rule": "Kuralı sil", + "Delete the row": "Satırı sil", + "Delete the set": "Kümeyi sil", + "Delete this parameter": "Bu parametreyi sil", + "Density": "Yoğunluk", + "Designs you open or save appear here.": "Açtığınız veya kaydettiğiniz tasarımlar burada görünür.", + "Determined by To Object. Choose Angle to edit the angular extent.": "Nesneye kadar seçeneğiyle belirlenir. Açısal kapsamı düzenlemek için Açı seçeneğini seçin.", + "Discard": "At", + "Double-click to rename": "Yeniden adlandırmak için çift tıklayın", + "Drive Joint": "Bağlantıyı tahrik et", + "Edit Profile Sketch": "Profil eskizini düzenle", + "Enable rule": "Kuralı etkinleştir", + "Enabled": "Etkin", + "Explode": "Patlat", + "Extents": "Kapsamlar", + "Face attachment lost": "Yüze bağlama kayboldu", + "Faces / edges / vertices": "Yüzler / kenarlar / köşe noktaları", + "Favourite": "Favori", + "Files from many CAD programs have Y up, so they open lying on their back here (Z up).": "Birçok CAD programının dosyalarında Y yukarıyı gösterir; bu yüzden burada (Z yukarı) sırtüstü yatar hâlde açılırlar.", + "Filter": "Filtre", + "Find in Browser": "Tarayıcıda bul", + "Copy Error Message": "Hata mesajını kopyala", + "Copy Warning Message": "Uyarı mesajını kopyala", + "Flat size": "Açınım boyutu", + "Follow camera (Look At sketches)": "Kamera takibi (eskizlerde Bak)", + "Font": "Yazı tipi", + "Full Length": "Tam uzunluk", + "Gap": "Boşluk", + "Grid": "Izgara", + "Height": "Yükseklik", + "Home view": "Başlangıç görünümü", + "In This Design": "Bu tasarımda", + "Interferes": "Girişim var", + "Issue title": "Sorun başlığı", + "Joint Origin1": "Bağlantı orijini1", + "Keep Tools": "Araçları koru", + "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.", + "Length": "Uzunluk", + "Length units": "Uzunluk birimleri", + "Library": "Kitaplık", + "Loop": "Döngü", + "Margin": "Kenar boşluğu", + "Mass": "Kütle", + "Material": "Malzeme", + "Mid Radius": "Ara yarıçap", + "Modeled": "Modellenmiş", + "More toolbar panels": "Diğer araç çubuğu panelleri", + "Motion": "Hareket", + "Move Type": "Taşıma türü", + "Move earlier": "Öne al", + "Move later": "Sonraya al", + "Name": "Ad", + "No crash reports.": "Çökme raporu yok.", + "No matching appearances": "Eşleşen görünüm yok", + "Not available yet": "Henüz kullanılamıyor", + "Opacity": "Opaklık", + "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", + "Parameter values": "Parametre değerleri", + "Per Edge": "Kenar başına", + "Pick the tool bodies": "Araç gövdelerini seçin", + "Place at the origin instead": "Bunun yerine orijine yerleştir", + "Playback": "Oynatma", + "Position": "Konum", + "Position (0 to 1)": "Konum (0 ile 1 arası)", + "Position along the edge, 0 at the start end, 1 at the other": "Kenar boyunca konum: başlangıç ucunda 0, diğer uçta 1", + "Preview leaves the current design unchanged.": "Önizleme geçerli tasarımı değiştirmez.", + "RECENT": "SON KULLANILANLAR", + "Radius Fit": "Yarıçap uydurma", + "Ratio": "Oran", + "Recover": "Kurtar", + "Recover unsaved design?": "Kaydedilmemiş tasarım kurtarılsın mı?", + "Remove Tools": "Araçları kaldır", + "Remove from list": "Listeden kaldır", + "Remove private design details or paths before sharing.": "Paylaşmadan önce özel tasarım ayrıntılarını veya dosya yollarını kaldırın.", + "Remove the column": "Sütunu kaldır", + "Remove the track": "İzi kaldır", + "Remove this point": "Bu noktayı kaldır", + "Report a bug — review a screenshot and open a GitHub draft": "Hata bildir — ekran görüntüsünü kontrol edin ve bir GitHub taslağı açın", + "Reset Toolbar": "Araç çubuğunu sıfırla", + "Restore the inherited component or physical material appearance": "Bileşenden veya fiziksel malzemeden devralınan görünümü geri yükle", + "Result": "Sonuç", + "Retake screenshot": "Ekran görüntüsünü yeniden al", + "Reverse": "Ters çevir", + "Reverse Direction": "Yönü ters çevir", + "Revert": "Geri al", + "Revert All Positions": "Tüm konumları geri al", + "Review the report and screenshot before opening GitHub.": "GitHub'ı açmadan önce raporu ve ekran görüntüsünü gözden geçirin.", + "Rim Edge": "Ağız kenarı", + "Roll History Marker Here": "Geçmiş işaretçisini buraya taşı", + "Rule": "Kural", + "Saved preview. Geometry is being checked before editing.": "Kaydedilmiş önizleme. Düzenlemeden önce geometri kontrol ediliyor.", + "Scale factor": "Ölçek faktörü", + "Search": "Ara", + "Search commands": "Komutlarda ara", + "Select bodies (a face picks its body)": "Gövdeleri seçin (bir yüz kendi gövdesini seçer)", + "Select bodies or faces instead": "Bunun yerine gövde veya yüz seçin", + "Selection filter": "Seçim filtresi", + "Semantic faces share their appearance across instances.": "Anlamsal yüzler görünümlerini örnekler arasında paylaşır.", + "Shape": "Şekil", + "Show Agent Cursor": "Ajan imlecini göster", + "Show in folder": "Klasörde göster", + "Size": "Boyut", + "Sketch plane has no body-face attachment.": "Eskiz düzleminin bir gövde yüzüne bağlaması yok.", + "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft bu tasarımlar kaydedilmeden önce kapandı. Son otomatik kayıtları açılabilir.", + "Speed": "Hız", + "Stand it up": "Dik çevir", + "Stand it up: a quarter turn about X, as one Move feature you can undo.": "Dik çevir: X etrafında çeyrek tur; geri alınabilen tek bir Taşı özelliği olarak eklenir.", + "Stand this part up?": "Bu parça dik çevrilsin mi?", + "Step": "Adım", + "Steps": "Adımlar", + "Suppressed": "Bastırılmış", + "Swap Ends": "Uçları değiştir", + "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.", + "Then": "Sonra", + "These features will be deleted:": "Şu özellikler silinecek:", + "These features will fail:": "Şu özellikler başarısız olacak:", + "This child is shared. Deleting it removes it from every copy of its parent.": "Bu alt öğe paylaşılıyor. Silindiğinde üst öğesinin tüm kopyalarından kaldırılır.", + "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", + "Tolerance": "Tolerans", + "Type": "Tür", + "Updating the preview": "Önizleme güncelleniyor", + "Use fixed plane": "Sabit düzlem kullan", + "VIEW": "GÖRÜNÜM", + "Value": "Değer", + "Volume": "Hacim", + "Wall": "Cidar", + "When": "Eğer", + "Width": "Genişlik", + "Will fail": "Başarısız olacak", + "angle, height": "açı, yükseklik", + "command name": "komut adı", + "expression, e.g. 25 mm": "ifade, ör. 25 mm", + "fits the face, e.g. M8": "yüze uyar, ör. M8", + "from the rule": "kuraldan", + "needs two joints": "iki bağlantı gerektirir", + "new configuration": "yeni konfigürasyon", + "new name": "yeni ad", + "new parameter": "yeni parametre", + "no interference": "girişim yok", + "no joint that moves yet": "henüz hareket eden bir bağlantı yok", + "no picture": "resim yok", + "pick a hole to seat it, or OK places it at the origin": "yerleştirmek için bir delik seçin veya OK ile orijine yerleştirin", + "pick one or two vertices, edges or faces": "bir veya iki köşe noktası, kenar ya da yüz seçin", + "the parts library is not available": "parça kitaplığı kullanılamıyor", + "to the next face": "sonraki yüze kadar", + "Revert Position": "Konumu geri al", + "Construction": "Yapı çizgisi", + "Faces": "Yüzler", + "Edges": "Kenarlar", + "Vertices": "Köşe noktaları", + "Sketch geometry and profiles": "Eskiz geometrisi ve profiller", + "Sketch curves": "Eskiz eğrileri", + "Sketch points": "Eskiz noktaları", + "Sketch dimensions": "Eskiz ölçüleri", + "Sketch constraints": "Eskiz kısıtlamaları", + "0 turns it off": "0 değeri kapatır", + "Show the pointer an AI agent moves (#35)": "Bir AI ajanının hareket ettirdiği imleci göster (#35)", + "Follow the camera (Look At sketches)": "Kamera takibi (eskizlerde Bak)", + "Flat": "Düz", + "Save Rule": "Kuralı kaydet", + "Preview Row": "Satırı önizle", + "Add condition": "Koşul ekle", + "Apply to selection": "Seçime uygula", + "Remove override": "Geçersiz kılmayı kaldır", + "Copy screenshot": "Ekran görüntüsünü kopyala", + "Remove screenshot": "Ekran görüntüsünü kaldır", + "Use active author placement": "Etkin kaynak yerleşimini kullan", + "Reattach selected face": "Seçili yüze yeniden bağla", + "Use saved fixed plane": "Kaydedilmiş sabit düzlemi kullan", + "Use selected face as fixed plane": "Seçili yüzü sabit düzlem olarak kullan", + "View navigator": "Görünüm gezgini", + "Signed axes": "İşaretli eksenler", + "Cube": "Küp", + "Middle double-click": "Orta tuşla çift tıklama", + "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": "Görünümde orta tuşla çift tıklama: Başlangıç (gösterileni çerçeveleyen başlangıç görünümü), Sığdır (yönü koruyarak gösterileni çerçeveler) veya hiçbir şey", + "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).": "Diğerini seç: İmlecin altındaki her şeyi listelemek için sol tuşu model üzerinde hareket ettirmeden basılı tutun (veya sağ tık › Diğerini seç…); oradaki bir sonraki öğeyi seçmek için aynı noktaya tekrar tıklayın. Başlangıç görünümüne dönmek için orta tuşla çift tıklayın (Ayarlar › Gezinme).", + "cmd.render_backends": "Render arka uçları", + "cmd.view_navigate": "Görünümde gezin", + "ui.animateJoint": "Bağlantıyı canlandır", + "ui.calibrate": "Kalibre et", + "ui.customizeToolbar": "Araç çubuğunu özelleştir…", + "ui.editJointLimits": "Bağlantı sınırlarını düzenle", + "ui.exportDxf": "DXF olarak dışa aktar…", + "ui.findInTimeline": "Zaman çizelgesinde bul", + "ui.findInWindow": "Pencerede bul", + "ui.fit": "Sığdır", + "ui.groupSelected": "Seçimi grupla", + "ui.hideAxes": "Eksenleri gizle", + "ui.hideDimension": "Ölçüyü gizle", + "ui.hideOrigin": "Orijini gizle", + "ui.hidePlanes": "Düzlemleri gizle", + "ui.hideProfile": "Profili gizle", + "ui.homeView": "Başlangıç görünümü", + "ui.isolate": "Yalıt", + "ui.lock": "Kilitle", + "ui.newSketchGroup": "Yeni eskiz grubu", + "ui.normalConstruction": "Normal / Yapı", + "ui.orbit": "Döndür", + "ui.heading_position": "KONUM", + "ui.pan": "Kaydır", + "ui.pinToShortcuts": "Kısayollara sabitle", + "ui.pinToToolbar": "Araç çubuğuna sabitle", + "ui.properties": "Özellikler", + "ui.design_properties.project": "Proje", + "ui.design_properties.part_number": "Parça numarası", + "ui.design_properties.revision": "Revizyon", + "ui.design_properties.author": "Yazar", + "ui.design_properties.organization": "Kuruluş", + "ui.design_properties.description": "Açıklama", + "ui.design_properties.license": "Lisans", + "ui.design_properties.not_text": "Metin olarak kaydedilmedi; buraya yapılan bir giriş değerin yerini alır.", + "ui.design_properties.exports": "STEP, IGES ve 3MF dışa aktarımları, biçim bunun için bir alan sunuyorsa bu bilgileri de aktarır.", + "ui.design_properties.others": "Diğer araçların verileri", + "ui.design_properties.others_note": "Tasarımda değişmeden kalır ve asla dışa aktarılmaz.", + "ui.removeSection": "Kesiti kaldır", + "ui.removeFromToolbar": "Araç çubuğundan kaldır", + "ui.repeat": "Tekrarla", + "ui.report_a_bug": "Hata bildir", + "ui.restore": "Geri yükle", + "ui.heading_setup": "KURULUM", + "ui.selectOther": "Diğerini seç…", + "ui.selectTangentChain": "Teğet zinciri seç", + "ui.showAll": "Tümünü göster", + "ui.showAllBodies": "Tüm gövdeleri göster", + "ui.showAxes": "Eksenleri göster", + "ui.showDimension": "Ölçüyü göster", + "ui.showOrigin": "Orijini göster", + "ui.showPlanes": "Düzlemleri göster", + "ui.suppress": "Bastır", + "ui.command_palette_hint": "Bir komut yazın (ör. {example}) — veya aramak için S tuşuna basın", + "ui.unground": "Sabitlemeyi kaldır", + "ui.unisolate": "Yalıtımı kaldır", + "ui.unlock": "Kilidi aç", + "ui.unsuppress": "Bastırmayı kaldır", + "ui.updateToCurrentView": "Geçerli görünüme güncelle", + "ui.zoom": "Yakınlaştır", + "ui.command_done": "{command} tamamlandı", + "drive.stopped_by_loop": "{value} değerinde durdu: {joint} üzerinden geçen döngü daha fazla kapatılamıyor", + "drive.stopped_by_contact": "{value} değerinde durdu: {a} ile {b} iç içe geçerdi", + "drive.unconnected": "Hiçbir şey hareket etmiyor: {part} sabitlenmiş hiçbir parçaya bağlı değil", + "timeline.group": "Yeni özellik klasörü oluştur", + "timeline.ungroup": "Özellik klasörünü kaldır", + "timeline.rename_group": "Özellik klasörünü yeniden adlandır", + "timeline.move_to_group": "Özellikleri klasöre taşı", + "timeline.move_many": "Zaman çizelgesi öğelerini taşı", + "timeline.reorder_many": "Özellikleri yeniden sırala", + "ui.show_construction_geometries": "Yapı geometrileri", + "ui.total_angle": "Toplam açı", + "sketch_text.builtin_font": "{family} (yerleşik)", + "sketch_text.font_search": "Yazı tiplerini ara", + "sketch_text.loading_fonts": "Yüklü yazı tipleri aranıyor…", + "sketch_text.use_font_file": "{path} yazı tipi dosyasını kullan", + "sketch_text.bold": "Kalın", + "sketch_text.italic": "İtalik", + "sketch_text.align_left": "Sol", + "sketch_text.align_center": "Orta", + "sketch_text.align_right": "Sağ", + "sketch_text.path_hint": "Metnin izleyeceği eskiz eğrisi: önce buraya, ardından eğriye tıklayın", + "sketch_text.path_clear": "Metni eğriden ayır", + "Style": "Stil", + "Alignment": "Hizalama", + "Letter Spacing": "Harf aralığı", + "Line Spacing": "Satır aralığı", + "Path": "Yol", + "sketch_text.on_path": "Metin eğrisini izler: konumunu eğri belirler", + "cmd.library_inspect": "Yerel kitaplığı incele", + "cmd.library_export": "Tasarım kitaplığını dışa aktar", + "cmd.library_apply": "Yerel kitaplık girişini uygula", + "Thin": "İnce cidarlı", + "Thin Extrude": "İnce cidarlı ekstrüzyon", + "Wall Location": "Cidar konumu", + "Wall Thickness": "Et kalınlığı", + "Thickness Outside": "Dış kalınlık", + "Inside": "İç", + "Outside": "Dış", + "Profiles/Curves": "Profiller/Eğriler", + "cmd.material_properties_validate": "Fiziksel malzeme verilerini kontrol et", + "cmd.material_properties_directional": "Yöne bağlı elastisite modülü", + "update.button": "Güncelle", + "update.button_tip": "SolidCraft {version} kullanılabilir", + "install.menu": "Uygulamayı yükle…", + "install.button_tip": "SolidCraft'ı uygulama olarak yükleyin: kendi penceresinde açılır ve çevrimdışı da çalışır", + "install.title": "SolidCraft'ı yükle", + "install.steps_intro": "Safari web uygulamalarını kendi menüleri üzerinden yükler:", + "install.home_screen_1": "“Paylaş” düğmesine dokunun (araç çubuğunda değilse … menüsünde).", + "install.home_screen_2": "“Ana Ekrana Ekle” seçeneğini seçin.", + "install.home_screen_3": "“Ekle” düğmesine dokunun.", + "install.home_screen_after": "SolidCraft daha sonra ana ekrandaki simgesinden, Safari çubukları olmadan açılır ve çevrimdışı da çalışır.", + "install.dock_1": "Dosya › Dock'a Ekle'yi seçin.", + "install.dock_2": "“Ekle” düğmesine tıklayın.", + "install.dock_after": "SolidCraft daha sonra Dock'tan kendi penceresinde açılır ve çevrimdışı da çalışır.", + "install.done": "Bitti", + "update.title": "Güncelleme mevcut", + "update.available": "SolidCraft {version} kullanılabilir", + "update.you_have": "Yüklü sürüm: {version}.", + "update.no_notes": "Bu sürüm için not bulunmuyor.", + "update.system_hint": "Bu kurulum bir {kind}. Şu komutla güncelleyin:", + "update.package_hint": "Bu kurulum bir {kind} kaynağından geliyor. Yeni paketi indirip şu komutla yükleyin:", + "update.copy": "Kopyala", + "update.file": "“İndir” düğmesi {file} dosyasını indirir.", + "update.download": "İndir", + "update.release_page": "Sürüm sayfasını aç", + "update.skip": "Bu sürümü atla", + "update.later": "Daha sonra hatırlat", + "update.prefs_label": "Güncellemeler", + "update.check_automatically": "Güncellemeleri otomatik denetle", + "update.check_now": "Şimdi denetle", + "update.checking": "Denetleniyor…", + "update.failed": "Denetim başarısız: {error}", + "update.up_to_date": "SolidCraft güncel.", + "update.prefs_note": "Bu, SolidCraft {version} ({kind}). Denetim, GitHub'a en yeni sürümü sorar ve başka hiçbir şey göndermez.", + "update.prefs_dev": "Bu bir geliştirme derlemesi ({version}): güncelleme aramaz.", + "update.show": "{version} güncellemesini göster", + "update.prefs_flatpak": "Bu kurulum ({version}) Flatpak tarafından güncellenir: {command} komutunu çalıştırın veya yazılım yöneticisini kullanın. SolidCraft kendisi denetlemez.", + "update.update_now": "Şimdi güncelle", + "update.install_msi": "Yükle (SolidCraft'ı kapatır)", + "update.download_open": "İndir ve aç", + "update.downloading": "İndiriliyor ve doğrulanıyor… {done} / {total} MB", + "update.installed": "SolidCraft {version} yüklendi. Kullanmak için yeniden başlatın.", + "update.restart": "Şimdi yeniden başlat", + "update.restart_later": "Daha sonra", + "update.installer_started": "Yükleme programı, SolidCraft kapatıldığında başlar.", + "update.dmg_opened": "Disk görüntüsü açıldı ve doğrulandı: SolidCraft'ı “Uygulamalar” klasörüne sürükleyin, eski sürümü değiştirin ve SolidCraft'ı yeniden başlatın.", + "update.install_failed": "Güncelleme yüklenmedi: {error}. Hiçbir şey değiştirilmedi; paketi “İndir” ile indirebilirsiniz.", + "cmd.render_settings_get": "Render ayarları", + "cmd.render_settings_set": "Render ayarlarını kaydet", + "cmd.render_scene": "Render sahnesini incele", + "cmd.render_settings_apply": "Render kamerasını uygula", + "toolbar.render": "RENDER", + "toolbar.render_scene": "SAHNE", + "render.preview": "Yerleşik önizleme", + "render.preview_help": "Harmanlanmış saydamlıkla raster görüntü. Kırılma, HDRI ve son render henüz kullanılamıyor.", + "render.setup_name": "Kurulumun adı", + "render.background": "Sahne arka planı", + "render.perspective": "Perspektif kamera", + "render.fit": "Ürünü sığdır", + "render.restore_camera": "Kaydedilmiş kamerayı yükle", + "render.save_setup": "Kurulumu kaydet", + "render.unsaved": "Kaydedilmemiş önizleme değişiklikleri", + "render.reload_settings": "Kaydedilmiş ayarları yükle", + "render.unavailable_preview": "Bu kurulum, kullanılamayan bir önizleme profili gerektiriyor.", + "render.use_preview": "Yerleşik önizlemeyi kullan", + "render.navigation_help": "Kamera, tasarım modundaki gibi hareket eder (Ayarlar › Gezinme). Kurulumu kaydettiğinizde geçerli kamera kaydedilir.", + "render.return_design": "Tasarıma dön", + "render.image_title": "Resmi render et", + "render.image_help": "CPU önizleme resmi · PNG · yaklaşık saydamlık", + "render.image_width": "Genişlik", + "render.image_height": "Yükseklik", + "render.image_transparent": "Saydam arka plan", + "render.image_check": "Render isteğini kontrol et", + "render.image_supported": "Render isteği destekleniyor; kuyruk ve bellek, başlatılırken yeniden kontrol edilir.", + "render.image_queued": "Render için sırada bekliyor", + "render.image_preparing": "Resim hazırlanıyor", + "render.image_running": "Resim render ediliyor", + "render.image_encoding": "PNG kodlanıyor", + "render.image_cancelling": "İptal ediliyor", + "render.image_cancelled": "Render iptal edildi", + "render.image_completed": "Resim dışa aktarmaya hazır", + "render.image_failed": "Render başarısız", + "render.image_unknown": "Render durumu kullanılamıyor", + "render.image_reduce": "Daha küçük bir resim veya daha basit bir sahne deneyin.", + "render.image_too_large": "Resim sınırının üzerinde: kenar başına 4096 piksel ve toplam 4.194.304 piksel.", + "render.image_use_largest": "Bu en-boy oranıyla en büyük boyutu kullan:", + "render.image_cancel": "Render'ı iptal et", + "render.image_stale": "Bu resim, sonraki değişikliklerden önceki sahneyi kullanıyor.", + "render.image_start": "Render'ı başlat", + "render.image_overwrite": "Mevcut dosyanın üzerine yaz", + "render.image_export": "PNG dışa aktar", + "cmd.render_preflight": "Render isteğini kontrol et", + "cmd.render_start": "Resmi render et", + "cmd.render_status": "Render ilerlemesi", + "cmd.render_cancel": "Render'ı iptal et", + "cmd.render_export": "PNG dışa aktar", + "toolbar.image": "RESİM", + "appearance.surface_response": "Yüzey davranışı", + "appearance.pbr_opaque": "Opak PBR", + "appearance.metallic": "Metaliklik", + "appearance.roughness": "Pürüzlülük", + "appearance.dielectric_ior": "Dielektrik kırılma indisi", + "appearance.pbr_help": "Bu yüzeyi Render'da veya bir ürün PNG'sinde görüntüleyin. Kırılma veya geçirgenlik yok.", + "render.opaque_preview_help": "Opak PBR ve düz renkler; saydamlık harmanlanarak gösterilir. Kırılma, HDRI ve son render henüz kullanılamıyor.", + "render.opaque_image_summary": "Önizleme PNG · opak PBR · harmanlanmış saydamlık", + "UNTRIM": "KIRPMAYI KALDIR", + "Face": "Yüz", + "Holes": "Delikler", + "Holes (edges on them)": "Delikler (kenarları)", + "In place (surfaces)": "Yerinde (yüzeyler)", + "None": "Hiçbiri", + "Picked": "Seçilenler", + "Restore outer boundary": "Dış sınırı geri yükle", + "RULED SURFACE": "REGLE YÜZEY", + "Mitre": "Gönye", + "Reference face": "Referans yüzü", + "Round": "Yuvarlak", + "joint.one_component": "Bu parçalar tek bir bileşenin gövdeleridir: {bodies}. Bir bağlantı bir bileşeni diğerine göre hareket ettirir, bu nedenle her parçanın kendi bileşeni olması gerekir.", + "joint.one_body": "Her iki seçim de {body} üzerinde. İkincisini başka bir parçada seçin.", + "joint.from_bodies_hint": "Seçilen her gövde kendi yeni bileşenine konur ve bulunduğu yerde kalır.", + "Circumference": "Çevre", + "Arc length": "Yay uzunluğu", + "Slot width": "Yuva genişliği", + "Centre to centre": "Merkezden merkeze", + "Overall length": "Toplam uzunluk", + "Min": "Min", + "Max": "Maks" +} diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 8d8027451..a6589a809 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -38,8 +38,9 @@ static FRENCH: Catalog = Catalog::new("fr", "Français", include_str!(concat!(en static KOREAN: Catalog = Catalog::new("ko", "한국어", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/ko.json"))); static RUSSIAN: Catalog = Catalog::new("ru", "Русский", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/ru.json"))); static UKRAINIAN: Catalog = Catalog::new("uk", "Українська", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/uk.json"))); +static TURKISH: Catalog = Catalog::new("tr", "Türkçe", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/tr.json"))); static CHINESE: Catalog = Catalog::new("zh", "中文", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/zh.json"))); -pub const LOCALES: &[&Catalog] = &[&ENGLISH, &JAPANESE, &GERMAN, &FRENCH, &KOREAN, &RUSSIAN, &UKRAINIAN, &CHINESE]; +pub const LOCALES: &[&Catalog] = &[&ENGLISH, &JAPANESE, &GERMAN, &FRENCH, &KOREAN, &RUSSIAN, &UKRAINIAN, &TURKISH, &CHINESE]; pub fn is_supported(id: &str) -> bool { LOCALES.iter().any(|catalog| catalog.id == id) @@ -508,6 +509,17 @@ mod tests { assert_eq!(fr.dynamic("Sketch of bracket"), "Sketch of bracket"); } + #[test] + fn turkish_catalog_is_registered_and_translates_keys() { + let tr = Locale::for_language("tr"); + assert_eq!(tr.name(), "Türkçe"); + assert!(is_supported("tr")); + assert_eq!(tr.text("ui.preferences"), "Ayarlar"); + assert_eq!(tr.format("document.save_changes", &[("name", "My {design}")]), "My {design} içindeki değişiklikler kaydedilsin mi?"); + assert_eq!(tr.format("dialog.selected_count", &[("count", "2")]), "↖ 2 seçildi"); + assert_eq!(tr.label("NonExistentKey"), "NonExistentKey"); + } + #[test] fn ukrainian_catalog_translates_keys_labels_and_browser_patterns() { let uk = Locale::for_language("uk"); diff --git a/docs/localization.md b/docs/localization.md index 35a512b45..16c0f14ba 100644 --- a/docs/localization.md +++ b/docs/localization.md @@ -1,7 +1,7 @@ # UI localization SolidCraft embeds its translations and works offline. English, Japanese, German, French, Korean, -Russian, Ukrainian and Chinese are currently registered in `crates/ui-egui/src/i18n.rs`. Adding a language requires an +Russian, Ukrainian, Turkish 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. @@ -31,7 +31,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, Korean, Russian, French and Ukrainian are + Japanese and Chinese are delivered complete; German, Korean, 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 follow later. From b400958c3e87ab263e9778cd4aac22b2cfdd7a9c Mon Sep 17 00:00:00 2001 From: selune <35337584+0xlillith@users.noreply.github.com> Date: Fri, 16 Oct 2026 00:55:14 +0200 Subject: [PATCH 10/92] render: add isotropic texture footprint LOD reference (#1460) Co-Authored-By: selune <0xlillith@users.noreply.github.com> Co-Authored-By: Claude Sonnet 5.5 --- crates/render/src/lib.rs | 1 + crates/render/src/texture_lod.rs | 78 ++++++++++++++++++++++ crates/render/src/texture_lod_tests.rs | 91 ++++++++++++++++++++++++++ docs/render-texture-lod.md | 51 +++++++++++++++ 4 files changed, 221 insertions(+) create mode 100644 crates/render/src/texture_lod.rs create mode 100644 crates/render/src/texture_lod_tests.rs create mode 100644 docs/render-texture-lod.md diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 3de0e090c..9a1af147d 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -15,6 +15,7 @@ pub mod studio; pub mod surface; pub mod texture_input; pub mod texture_interpolation; +pub mod texture_lod; pub use backend::{ Availability, BackendDescriptor, BackendId, ExecutorDescriptor, ExecutorId, MAX_RENDER_ID_BYTES, RenderFeature, RenderFormat, RenderLimits, diff --git a/crates/render/src/texture_lod.rs b/crates/render/src/texture_lod.rs new file mode 100644 index 000000000..bf1ebed19 --- /dev/null +++ b/crates/render/src/texture_lod.rs @@ -0,0 +1,78 @@ +//! Independent isotropic CPU LOD reference from unwrapped UV gradients per shading-grid pixel. +//! No sampling, derivative inference, normal filtering or GPU capability is implied. +use crate::texture_input::MAX_TEXTURE_EDGE; + +/// Versioned convention: largest singular value, log2, magnification at zero, +/// saturated at the last floor-halved level. Not a GPU parity guarantee. +pub const LOD_POLICY_ID: &str = "solidcraft.isotropic-singular-value-lod/1"; +pub const MAX_UV_GRADIENT: f64 = 1_048_576.0; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LodError { + Dimensions, + Gradients, +} +impl std::fmt::Display for LodError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::Dimensions => "texture dimensions must be positive and within admission limits", + Self::Gradients => "UV gradients must be finite and within the CPU reference bound", + }) + } +} +impl std::error::Error for LodError {} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct LodSelection { + /// Continuous LOD, explicitly saturated to [0, max_level]. + pub lod: f64, + /// Largest singular value of the UV-to-texel differential, before saturation. + pub footprint_texels: f64, + pub max_level: u32, +} + +/// Select LOD using caller-supplied derivatives of UNWRAPPED UV per shading-grid pixel. +/// `duv_dx` and `duv_dy` must already account for perspective/placement/mapping. +/// For Sx by Sy supersampling, divide final-image-pixel derivatives by Sx and Sy, +/// respectively. Derivatives already measured on the shading grid need no division. +/// The policy uses a circular differential footprint, not exact pixel-square coverage. +/// It can blur the shorter axis of an elongated footprint; it is not anisotropic. +/// Dimensions describe the base image; its available chain must end at 1x1 through +/// floor-halving. Odd-size levels use the documented log2 approximation. +pub fn select_isotropic_lod(dimensions: [u32; 2], duv_dx: [f64; 2], duv_dy: [f64; 2]) -> Result { + let [width, height] = dimensions; + if width == 0 || height == 0 || width > MAX_TEXTURE_EDGE || height > MAX_TEXTURE_EDGE { + return Err(LodError::Dimensions); + } + if duv_dx.iter().chain(&duv_dy).any(|v| !v.is_finite() || v.abs() > MAX_UV_GRADIENT) { + return Err(LodError::Gradients); + } + let [dudx, dvdx] = duv_dx; + let [dudy, dvdy] = duv_dy; + let columns = [dudx * f64::from(width), dvdx * f64::from(height), dudy * f64::from(width), dvdy * f64::from(height)]; + let scale = columns.into_iter().map(f64::abs).fold(0.0, f64::max); + let footprint_texels = if scale == 0.0 { + 0.0 + } else { + let [a, b, c, d] = columns.map(|v| v / scale); + // Largest eigenvalue of J^T J; scaling keeps the quadratic bounded. + let first = a * a + b * b; + let second = c * c + d * d; + let cross = a * c + b * d; + scale * (0.5 * (first + second + (first - second).hypot(2.0 * cross))).sqrt() + }; + let mut w = width; + let mut h = height; + let mut max_level = 0; + while w > 1 || h > 1 { + w = (w / 2).max(1); + h = (h / 2).max(1); + max_level += 1; + } + let lod = if footprint_texels <= 1.0 { 0.0 } else { footprint_texels.log2().min(f64::from(max_level)) }; + Ok(LodSelection { lod, footprint_texels, max_level }) +} + +#[cfg(test)] +#[path = "texture_lod_tests.rs"] +mod tests; diff --git a/crates/render/src/texture_lod_tests.rs b/crates/render/src/texture_lod_tests.rs new file mode 100644 index 000000000..847f1292c --- /dev/null +++ b/crates/render/src/texture_lod_tests.rs @@ -0,0 +1,91 @@ +use super::*; + +fn close(a: f64, b: f64) { + assert!((a - b).abs() <= 1e-12 * b.abs().max(1.0), "{a} != {b}"); +} + +#[test] +fn magnification_zero_integer_and_fractional_minification() { + for (footprint, expected) in [(0., 0.), (0.25, 0.), (1., 0.), (2., 1.), (2_f64.sqrt(), 0.5), (8., 3.)] { + let result = select_isotropic_lod([256, 256], [footprint / 256., 0.], [0., footprint / 256.]).unwrap(); + close(result.footprint_texels, footprint); + close(result.lod, expected); + assert_eq!(result.max_level, 8); + } +} + +#[test] +fn rectangular_textures_scale_each_uv_axis_separately() { + let result = select_isotropic_lod([512, 128], [1. / 512., 0.], [0., 1. / 128.]).unwrap(); + close(result.footprint_texels, 1.); + close(result.lod, 0.); + let result = select_isotropic_lod([512, 128], [0., 4. / 128.], [2. / 512., 0.]).unwrap(); + close(result.footprint_texels, 4.); + close(result.lod, 2.); +} + +#[test] +fn supplied_derivatives_follow_the_actual_supersampling_grid() { + // A final-image pixel covers4 texels. On a2x4 shading grid its per-step + // footprints are2 and1; final downsampling remains a separate operation. + let dx = [4. / 256., 0.]; + let dy = [0., 4. / 256.]; + let coarse = select_isotropic_lod([256, 256], dx, dy).unwrap(); + let fine = select_isotropic_lod([256, 256], dx.map(|v| v / 2.), dy.map(|v| v / 4.)).unwrap(); + close(coarse.lod, 2.); + close(fine.footprint_texels, 2.); + close(fine.lod, 1.); +} + +#[test] +fn shear_uses_singular_value_rather_than_smaller_max_column_norm() { + // J columns both [2,0]: max column length2, true largest singular value sqrt8. + let result = select_isotropic_lod([256, 256], [2. / 256., 0.], [2. / 256., 0.]).unwrap(); + close(result.footprint_texels, 8_f64.sqrt()); + close(result.lod, 1.5); +} + +#[test] +fn rotation_sign_and_screen_axis_swap_preserve_the_footprint() { + let angle = 0.37_f64; + let (s, c) = angle.sin_cos(); + // Rotated texel-space axes with singular values4 and2, rectangular base. + let x = [4. * c / 512., 4. * s / 128.]; + let y = [-2. * s / 512., 2. * c / 128.]; + for (dx, dy) in [(x, y), (y, x), (x.map(|v| -v), y), (x, y.map(|v| -v))] { + let result = select_isotropic_lod([512, 128], dx, dy).unwrap(); + close(result.footprint_texels, 4.); + close(result.lod, 2.); + } +} + +#[test] +fn full_chain_saturation_is_explicit_for_odd_single_axis_and_single_texel_images() { + for (dimensions, last) in [([5, 3], 2), ([7, 1], 2), ([1, 7], 2), ([1, 1], 0), ([2048, 2048], 11)] { + let result = select_isotropic_lod(dimensions, [MAX_UV_GRADIENT; 2], [MAX_UV_GRADIENT; 2]).unwrap(); + assert_eq!(result.max_level, last); + close(result.lod, f64::from(last)); + assert!(result.footprint_texels.is_finite()); + } +} + +#[test] +fn zero_and_tiny_gradients_are_finite() { + for value in [0., -0., f64::MIN_POSITIVE, f64::from_bits(1)] { + let result = select_isotropic_lod([2048, 2048], [value; 2], [value; 2]).unwrap(); + assert!(result.footprint_texels.is_finite()); + close(result.lod, 0.); + } +} + +#[test] +fn hostile_dimensions_and_each_gradient_component_refuse() { + for dimensions in [[0, 1], [1, 0], [MAX_TEXTURE_EDGE + 1, 1], [u32::MAX; 2]] { + assert_eq!(select_isotropic_lod(dimensions, [0.; 2], [0.; 2]), Err(LodError::Dimensions)); + } + for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, f64::MAX, MAX_UV_GRADIENT + 1., -MAX_UV_GRADIENT - 1.] { + for (x, y) in [([value, 0.], [0., 0.]), ([0., value], [0., 0.]), ([0., 0.], [value, 0.]), ([0., 0.], [0., value])] { + assert_eq!(select_isotropic_lod([2, 2], x, y), Err(LodError::Gradients)); + } + } +} diff --git a/docs/render-texture-lod.md b/docs/render-texture-lod.md new file mode 100644 index 000000000..8b9762a34 --- /dev/null +++ b/docs/render-texture-lod.md @@ -0,0 +1,51 @@ +# Independent CPU LOD reference + +`solidcraft_render::texture_lod::select_isotropic_lod` is the small numerical +unit in #1339, supporting the eventual wood consumer under #786. It depends only +on existing texture admission limits and the standard library; #1327/#1332 do +not need to merge first. It installs no texture consumer or renderer capability. + +Supply positive base dimensions (each at most 2048) and two derivatives of +unwrapped UV per pixel of the actual shading grid: `duv_dx`, `duv_dy`. Every component must be finite +and have magnitude at most 2^20. Invalid inputs refuse before calculation. The +caller supplies perspective-correct mapping derivatives; the helper does not +infer them from mesh/world bounds, sampled UVs or neighbouring wrapped coordinates. +Differencing after repeat wrapping would turn a seam into a false large footprint. + +The shading grid is where samples are evaluated, which may differ from the final +PNG or logical viewport grid. For Sx by Sy supersampling, derivatives measured +per final-image pixel must be divided by Sx for `duv_dx` and Sy for `duv_dy` before +this call. Derivatives already computed on the shading grid must not be divided +again. Choosing a final-pixel footprint for every subsample would over-filter the +image. Downsampling to the final image remains the consumer's separate filter. +The helper infers no SSAA setting, device-pixel ratio or logical display scale. + +The texel-space Jacobian is +`[[width*du/dx, width*du/dy], [height*dv/dx, height*dv/dy]]`. +Its largest singular value is the footprint scale. This uses a circular screen +differential convention, not an exact integration over the square pixel area. +It is at least each individual column norm, accounting for shear that a maximum +column estimate misses. An elongated footprint can over-blur its shorter axis: +anisotropic filtering remains separate work. + +The implementation scales the Jacobian before forming its quadratic and uses +f64 arithmetic. Admitted gradient/dimension bounds keep all intermediate values +finite. Zero and subpixel footprints select LOD0. Otherwise LOD is log2(scale), +explicitly saturated to the final level of a complete floor-halved chain ending +at 1x1. The result includes the unsaturated scale and maximum level. For odd +dimensions log2 remains a convention approximating non-power-of-two level ratios; +it is not a claim of exact area integration or alias-free minification. + +Policy identifier `solidcraft.isotropic-singular-value-lod/1` fixes that +convention. A consumer must explicitly reconcile it with its prepared chain; +incomplete chains and different halving/filter policies cannot silently substitute. +No sampling, alpha/normal interpretation, derivative persistence, allocation, +resource cache, UI, engine command, GPU code or dependency is added. f64 reference +results alone do not certify GPU/f32 precision or visual parity. + +Original analytic tests cover zero/magnification, integer and fractional LOD, +rectangular texture scaling, rotated/signed/swapped axes, a sheared Jacobian, +odd/single-axis chains and hostile/extreme inputs. This invisible numerical +helper has no useful app screenshot. The visible consumer still requires typed +bindings, local millimetre mapping, preparation ownership, CPU/GPU integration, +PNG and offline reopen evidence. HDRI and final rendering remain separate work. From 7160ff7beb84a02c38969051714c4e985e48aeba Mon Sep 17 00:00:00 2001 From: Philipp Bischoff <86558944+PhilippBischoff0@users.noreply.github.com> Date: Fri, 16 Oct 2026 00:55:17 +0200 Subject: [PATCH 11/92] A sketch on an extrude's cap keeps its face when the extrude is made thin (#1532) Thin extrude caps are certified by the curves the wall follows, so a sketch attached to a cap survives switching between solid and thin (#1519). Co-Authored-By: Philipp Bischoff Co-Authored-By: Claude Sonnet 5.5 --- crates/doc/src/config_certificates.rs | 29 ++++++ crates/doc/src/eval.rs | 5 +- crates/engine/src/cmd/thin_extrude_tests.rs | 110 ++++++++++++++++++++ docs/face-attachments.md | 7 +- 4 files changed, 149 insertions(+), 2 deletions(-) diff --git a/crates/doc/src/config_certificates.rs b/crates/doc/src/config_certificates.rs index 25e9b94d3..a5902e13c 100644 --- a/crates/doc/src/config_certificates.rs +++ b/crates/doc/src/config_certificates.rs @@ -148,6 +148,35 @@ pub(crate) fn extrude_cap_bindings(sketch: &SolvedSketch, bodies: &[solidcraft_k Some(bindings) } +/// Cap signatures for a thin extrude (#1519). A thin wall's caps are bounded by offset curves +/// the sketch doesn't have, so [`extrude_cap_bindings`] can never certify them. A wall built +/// from one region is signed by the curves it follows instead: the cap of this extrude whose +/// wall runs along them. That is the signature its solid caps had when the wall follows the +/// whole profile (a rectangle's four lines), so a sketch attached to a solid cap keeps its face +/// when the extrude is made thin, and the other way round. Several regions (walls apart, or one +/// meeting itself) are left uncertified: they keep their history names. +pub(crate) fn thin_extrude_cap_bindings(curves: &[String], regions: usize, bodies: &[solidcraft_kernel::Body]) -> CapBindings { + use solidcraft_kernel::FaceSource; + let mut outer = curves.to_vec(); + outer.sort(); + outer.dedup(); + let signed = regions == 1 && bodies.len() == 1 && valid_signature(&outer, &[]); + bodies + .iter() + .map(|body| { + let sources: Vec<_> = body.face_sources().into_iter().flatten().collect(); + let ends = + |high: bool| sources.iter().filter(|source| matches!(source, Some(FaceSource::ExtrudeCap { high: h, .. }) if *h == high)).count(); + // One cap at each end, or none of them is certified. + let unique = ends(true) <= 1 && ends(false) <= 1; + sources + .iter() + .map(|source| (signed && unique && matches!(source, Some(FaceSource::ExtrudeCap { .. }))).then(|| (outer.clone(), Vec::new()))) + .collect() + }) + .collect() +} + #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] pub enum FaceCertificate { diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 263c82331..e468e913f 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -2938,7 +2938,10 @@ fn feature_tools_with_constructor( // certified as a new body's are (see `Body::with_preserved_union_planar_sources`). if matches!(operation, Operation::NewBody | Operation::Join) && extent.taper.is_none() { let bodies: Vec = tools.iter().map(|t| t.body.clone()).collect(); - let cap_bindings = crate::config::extrude_cap_bindings(&ss, &bodies, 10_000_000); + let cap_bindings = match thin { + Some(thin) => Some(crate::config::thin_extrude_cap_bindings(&thin.curves, regions.len(), &bodies)), + None => crate::config::extrude_cap_bindings(&ss, &bodies, 10_000_000), + }; let source_curves = cap_bindings.as_ref().map(|_| crate::config::ExactSketchCurves::new(&ss)); tools = tools .into_iter() diff --git a/crates/engine/src/cmd/thin_extrude_tests.rs b/crates/engine/src/cmd/thin_extrude_tests.rs index f2086497c..94f27e982 100644 --- a/crates/engine/src/cmd/thin_extrude_tests.rs +++ b/crates/engine/src/cmd/thin_extrude_tests.rs @@ -172,3 +172,113 @@ fn hostile_thin_params_never_panic() { } } } + +// #1519: sketches on a thin extrude's caps. A thin wall's caps are bounded by offset curves the +// sketch doesn't have, so they are certified by the curves the wall follows: the signature the +// solid caps had when the wall follows the whole profile. + +fn attachment(s: &Session, sketch: &str) -> solidcraft_doc::FaceAttachmentStatus { + let id = s.doc.find_feature(sketch).map(|f| f.id).unwrap_or_default(); + s.placed_document().sketch_face_attachment(id, &s.model) +} + +fn attached(s: &Session, sketch: &str) -> (solidcraft_geom::Plane, Option) { + match attachment(s, sketch) { + solidcraft_doc::FaceAttachmentStatus::Healthy { plane, target, .. } => (plane, target.certificate), + other => panic!("{sketch}: {other:?}"), + } +} + +fn same_plane(a: &solidcraft_geom::Plane, b: &solidcraft_geom::Plane) { + let near = |p: solidcraft_geom::Vec3, q: solidcraft_geom::Vec3| (p - q).len() < 1e-9; + assert!(near(a.origin, b.origin) && near(a.x, b.x) && near(a.y, b.y), "{a:?} != {b:?}"); +} + +fn sketch_on(s: &mut Session, at: [f64; 3], name: &str) { + run(s, "sketch.create", json!({"plane": {"face": at}, "name": name})); + run(s, "sketch.finish", json!({})); +} + +fn is_extrude_cap(certificate: &Option) -> bool { + matches!(certificate, Some(solidcraft_doc::config::FaceCertificate::ExtrudeCap { .. })) +} + +#[test] +fn sketches_on_a_solid_extrudes_caps_keep_their_faces_when_it_is_made_thin_and_solid_again() { + for side in ["center", "inside", "outside"] { + let mut s = Session::default(); + let sides = rectangle(&mut s); + run(&mut s, "solid.extrude", json!({"sketch": "Outline", "distance": 10, "name": "Wall"})); + // On the rim of the wall whichever side it lies on (the rectangle starts at (5, 5)). + sketch_on(&mut s, [5.5, 5.5, 10.0], "Top"); + sketch_on(&mut s, [5.5, 5.5, 0.0], "Bottom"); + let (top, _) = attached(&s, "Top"); + let (bottom, _) = attached(&s, "Bottom"); + run(&mut s, "timeline.edit", json!({"feature": "Wall", "set": {"thin": {"curves": sides, "thickness": "1", "side": side}}})); + no_errors(&s, side); + let (thin_top, certificate) = attached(&s, "Top"); + assert!(is_extrude_cap(&certificate), "{side}: {certificate:?}"); + same_plane(&thin_top, &top); + same_plane(&attached(&s, "Bottom").0, &bottom); + // The sketch follows the thin wall's height, and keeps its face through a save. + run(&mut s, "timeline.edit", json!({"feature": "Wall", "set": {"extent": {"distance": "25"}}})); + assert!((attached(&s, "Top").0.origin.z - 25.0).abs() < 1e-9, "{side}"); + let mut reopened = Session { doc: solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap().into(), ..Session::default() }; + reopened.refresh(); + no_errors(&reopened, side); + assert!((attached(&reopened, "Top").0.origin.z - 25.0).abs() < 1e-9, "{side}"); + // And solid again. + run(&mut s, "timeline.edit", json!({"feature": "Wall", "set": {"thin": null, "extent": {"distance": "10"}}})); + no_errors(&s, side); + same_plane(&attached(&s, "Top").0, &top); + same_plane(&attached(&s, "Bottom").0, &bottom); + } +} + +#[test] +fn a_sketch_on_a_thin_cap_is_certified_and_keeps_its_face_when_the_extrude_is_made_solid() { + let mut s = Session::default(); + rectangle(&mut s); + run(&mut s, "solid.extrude", json!({"sketch": "Outline", "thin": true, "thickness": 2, "side": "inside", "distance": 10, "name": "Wall"})); + sketch_on(&mut s, [6.0, 6.0, 10.0], "Top"); + let (top, certificate) = attached(&s, "Top"); + assert!(is_extrude_cap(&certificate), "{certificate:?}"); + run(&mut s, "timeline.edit", json!({"feature": "Wall", "set": {"thin": null}})); + no_errors(&s, "solid"); + same_plane(&attached(&s, "Top").0, &top); +} + +#[test] +fn a_thin_wall_along_part_of_the_profile_does_not_take_over_its_cap() { + // A wall along two sides is another wall than the rectangle's: the sketch reports its lost + // face instead of moving onto the new one. + let mut s = Session::default(); + let sides = rectangle(&mut s); + run(&mut s, "solid.extrude", json!({"sketch": "Outline", "distance": 10, "name": "Wall"})); + sketch_on(&mut s, [6.0, 6.0, 10.0], "Top"); + let _ = s.execute("timeline.edit", &json!({"feature": "Wall", "set": {"thin": {"curves": [&sides[0], &sides[1]], "thickness": "2"}}})); + assert!(matches!(attachment(&s, "Top"), solidcraft_doc::FaceAttachmentStatus::Lost { .. }), "{:?}", attachment(&s, "Top")); +} + +#[test] +fn the_caps_of_walls_apart_attach_by_their_history_names() { + // Two rectangles make two walls: their caps aren't certified (one signature would name + // both), so a sketch on one attaches by its exact history name, as before. + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Outline"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [10, 10]})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [20, 0], "p1": [30, 10]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"sketch": "Outline", "thin": true, "thickness": 1, "side": "inside", "distance": 5})); + sketch_on(&mut s, [0.5, 0.5, 5.0], "Top"); + let (_, certificate) = attached(&s, "Top"); + assert!(matches!(certificate, Some(solidcraft_doc::config::FaceCertificate::Lineage)), "{certificate:?}"); +} + +fn no_errors(s: &Session, context: &str) { + assert!( + s.model.results.iter().all(|r| r.error.is_none()), + "{context}: {:?}", + s.model.results.iter().filter_map(|r| r.error.as_ref()).collect::>() + ); +} diff --git a/docs/face-attachments.md b/docs/face-attachments.md index 1a6a7d8ad..50f39112e 100644 --- a/docs/face-attachments.md +++ b/docs/face-attachments.md @@ -9,7 +9,12 @@ geometry and dimensions. Supported planar sources are exact Box faces, untapered New Body and Join Extrude caps and straight sketch sides, and planar faces of immutable STEP imports. Extrude caps also identify their outer boundary and holes by source curve IDs. Reordering profiles cannot substitute another -profile's cap. A profile drawn over a face sketch's projected boundary (a rectangle +profile's cap. A thin extrude's caps are bounded by offset curves the sketch doesn't have, so a +wall built as one region is identified by the curves it follows instead (as its outer boundary, +with no holes). That is the identity the solid caps had when the wall follows the whole profile, +so a sketch on a cap keeps its face when the extrude is made thin, or solid again. A wall along +other curves, or one of several walls apart, is another face: it is attached by its history +name below, and a sketch made on the solid cap reports a lost attachment. A profile drawn over a face sketch's projected boundary (a rectangle traced over the whole face, or a strip whose sides lie on the face's edges) is identified by the drawn curves: where a drawn curve and a projected one cover the same edge, the drawn curve is the source. Two drawn curves, or two projections, over one edge remain ambiguous. Curved surfaces cannot host a planar sketch through this workflow. From 1b5c2b58471de16f193d48cc071a71292055fbd1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pablo=20L=C3=B3pez?= Date: Fri, 16 Oct 2026 01:01:04 +0200 Subject: [PATCH 12/92] New tab: no stale fillet preview, and + always opens a tab (#1533) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Pablo López Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/documents.rs | 37 +++++++++++++++++++++++++++++++-- crates/ui-egui/src/lib.rs | 2 +- crates/ui-egui/src/preview.rs | 31 +++++++++++++++++++++++++++ 3 files changed, 67 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/documents.rs b/crates/ui-egui/src/documents.rs index 7ab22a725..be579a94f 100644 --- a/crates/ui-egui/src/documents.rs +++ b/crates/ui-egui/src/documents.rs @@ -99,7 +99,7 @@ fn swap_in(app: &mut SolveApp, slot: DocSlot) -> DocSlot { app.cancel_view_animation(); app.viewport.orbit_snap = None; app.viewport.orbit_free = None; - app.preview = crate::preview::PreviewState::default(); + app.preview.reset(); app.viewport.hover = None; app.menu.props = None; crate::sketch_attachment_ui::clear(app); @@ -199,6 +199,24 @@ pub fn new_design(app: &mut SolveApp) { } } +/// The tab strip's +: always a new tab, except over the blank design the start page covers +/// (a launch), which New takes as [`new_design`] does. +pub fn new_tab(app: &mut SolveApp) { + if app.file_picker_busy() { + return; + } + if app.home.open && active_is_blank(app) { + new_design(app); + return; + } + app.home.open = false; + if let Err(e) = open_tab(app, Session::default()) { + app.set_status(e, true); + } else { + crate::prefs::apply_new_design(app); + } +} + /// Before opening a file: a fresh tab unless the active design is blank. The empty design, /// new or already showing, takes Units of new designs so a cancelled open is not millimetres /// when the preference says otherwise. @@ -455,7 +473,7 @@ pub fn tabs(app: &mut SolveApp, ui: &mut egui::Ui, r: Rect, x0: f32, x1: f32) { // A file loading into the window keeps the tabs as they are (dragging still moves it). let idle = !app.file_load.busy(); if presp.on_hover_text("New Design (Ctrl+N)").clicked() && idle { - new_design(app); + new_tab(app); } match (shut, pick) { _ if !idle => {} @@ -703,6 +721,21 @@ mod tests { assert!(active_is_blank(&a) && a.home.open); } + /// The tab strip's + opens a tab every time, an empty design's included; over the start + /// page's blank design (a launch) it uses that design. + #[test] + fn plus_opens_a_tab_every_time() { + let mut a = app(); + a.home.open = true; + new_tab(&mut a); + assert_eq!(a.docs.count(), 1, "the launch's blank design is used"); + assert!(!a.home.open); + new_tab(&mut a); + new_tab(&mut a); + assert_eq!(a.docs.count(), 3); + assert_eq!(a.docs.active, 2); + } + /// Quitting asks once per design with unsaved changes: Don't Save moves on (and keeps no /// recovery copy), Save saves and moves on, and the app quits after the last answer. #[test] diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index ede551ac4..8311be002 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -642,7 +642,7 @@ impl SolveApp { // applying cancellation hooks (such as restoring its timeline marker). self.dialog = None; self.tool = None; - self.preview = preview::PreviewState::default(); + self.preview.reset(); self.cam = Camera::default(); self.fit_view(); } diff --git a/crates/ui-egui/src/preview.rs b/crates/ui-egui/src/preview.rs index 25af7b69e..f234ab8af 100644 --- a/crates/ui-egui/src/preview.rs +++ b/crates/ui-egui/src/preview.rs @@ -118,6 +118,15 @@ impl PreviewState { } } + /// Drop the preview of a design that leaves the window. Its scene goes too: the viewport + /// keeps drawing the last scene it took until the slot it reads hands it another, so a fresh + /// state (another slot, empty) would leave the old preview drawn over the next design. + pub fn reset(&mut self) { + let (slot, key) = (std::mem::take(&mut self.slot), self.key); + *self = PreviewState { slot, key, ..PreviewState::default() }; + self.set_scene(GpuScene::default()); + } + fn set_scene(&mut self, sc: GpuScene) { if let Ok(mut slot) = self.slot.lock() { *slot = Some(sc); @@ -1052,6 +1061,28 @@ mod tests { pv.poll(4, None); assert!(pv.error.is_none() && pv.shown_key == Some(1), "an old error is dropped"); } + + /// A design leaving the window (another tab) takes its preview off the viewport: an empty + /// scene in the slot the viewport reads, under a new key. A fresh slot left the fillet + /// preview of the old design drawn over the new tab's empty design. + #[test] + fn reset_hands_the_viewport_an_empty_scene() { + let mut pv = PreviewState::default(); + let mut sc = GpuScene::default(); + sc.xray_tri([0.0; 3], [0.0, 0.0, 1.0], [255; 4]); + pv.set_scene(sc); + pv.active = true; + pv.replaced = vec!["Body1".into()]; + let slot = pv.slot.clone(); + let key = pv.key; + // The viewport took the scene. + assert!(slot.lock().unwrap().take().is_some_and(|s| !s.xray.is_empty())); + pv.reset(); + assert!(std::sync::Arc::ptr_eq(&slot, &pv.slot), "the slot the viewport reads"); + assert_ne!(pv.key, key, "a new key: the viewport takes the slot again"); + assert!(slot.lock().unwrap().as_ref().is_some_and(|s| s.xray.is_empty() && s.blocks.is_empty())); + assert!(!pv.active && pv.replaced.is_empty()); + } } #[cfg(test)] From 3d914c9f158828487a52d68111f8a9e3d3905732 Mon Sep 17 00:00:00 2001 From: Rec0iL Date: Fri, 16 Oct 2026 01:01:09 +0200 Subject: [PATCH 13/92] Agent chat gate: curve and occurrence ids named path are not files; broken tool arguments are not run (#1499) Co-Authored-By: Rec0iL Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/agent_chat/api_client.rs | 74 ++++++++++- crates/ui-egui/src/agent_chat/gate.rs | 134 ++++++++++++++++++-- docs/agent-chat.md | 6 + 3 files changed, 200 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/agent_chat/api_client.rs b/crates/ui-egui/src/agent_chat/api_client.rs index 49a89974a..878270f12 100644 --- a/crates/ui-egui/src/agent_chat/api_client.rs +++ b/crates/ui-egui/src/agent_chat/api_client.rs @@ -225,10 +225,8 @@ impl Worker { for (i, c) in calls.iter().enumerate().take(32) { let id = c.get("id").and_then(Value::as_str).map_or_else(|| format!("call-{i}"), str::to_string); let name = c.pointer("/function/name").and_then(Value::as_str).unwrap_or("").to_string(); - let args: Value = c - .pointer("/function/arguments") - .and_then(|a| if let Some(s) = a.as_str() { serde_json::from_str(s).ok() } else { Some(a.clone()) }) - .unwrap_or(json!({})); + let parsed = tool_arguments(c.pointer("/function/arguments")); + let args = parsed.clone().unwrap_or_else(|_| json!({})); let title = tool_title(&name, &args); let tool_id = format!("{id}-{}", self.next); self.emit(Event::Tool { @@ -240,6 +238,9 @@ impl Worker { }); let (text, failed) = if self.cancel.load(Ordering::Relaxed) { ("cancelled by the user".to_string(), true) + } else if let Err(e) = &parsed { + // A call whose arguments do not parse is answered, never run with `{}`. + (format!("Not run: {e}"), true) } else if HIDDEN_TOOLS.contains(&name.as_str()) || !self.tools.iter().any(|t| t.pointer("/function/name").and_then(Value::as_str) == Some(name.as_str())) { @@ -307,6 +308,25 @@ pub fn http_error(status: u16, body: &Value) -> String { ) } +/// A tool call's arguments as an object: the JSON text a model sends (or an object, for servers +/// that send one), or why they cannot be used. Missing or empty arguments are an empty object. +fn tool_arguments(raw: Option<&Value>) -> Result { + let text = match raw { + None | Some(Value::Null) => return Ok(json!({})), + Some(v @ Value::Object(_)) => return Ok(v.clone()), + Some(Value::String(s)) => s.trim(), + Some(_) => return Err("the tool arguments must be a JSON object".into()), + }; + if text.is_empty() { + return Ok(json!({})); + } + match serde_json::from_str::(text) { + Ok(v @ Value::Object(_)) => Ok(v), + Ok(_) => Err("the tool arguments must be a JSON object".into()), + Err(e) => Err(format!("the tool arguments were not valid JSON ({e}); send the call again with a JSON object")), + } +} + /// The message for what the user typed (and the view, as a data URL). fn user_message(parts: &[PromptPart]) -> Value { let images = parts.iter().any(|p| matches!(p, PromptPart::Image { .. })); @@ -474,6 +494,52 @@ mod tests { b.shutdown(true); } + #[test] + fn tool_arguments_are_an_object_or_an_error() { + assert_eq!(tool_arguments(None), Ok(json!({}))); + assert_eq!(tool_arguments(Some(&json!(""))), Ok(json!({}))); + assert_eq!(tool_arguments(Some(&json!("{\"a\": 1}"))), Ok(json!({"a": 1}))); + assert_eq!(tool_arguments(Some(&json!({"a": 1}))), Ok(json!({"a": 1}))); + for bad in [json!("{command: solid.box"), json!("[1]"), json!("7"), json!(7), json!([1])] { + assert!(tool_arguments(Some(&bad)).is_err(), "{bad}"); + } + } + + /// A call with arguments that are not JSON is answered with the reason, not run with `{}`. + #[test] + fn a_call_with_broken_arguments_is_not_run() { + let answers = std::sync::Mutex::new(vec![ + json!({"choices": [{"message": {"role": "assistant", "content": "Sorry."}}]}), + json!({"choices": [{"message": {"role": "assistant", "content": "", "tool_calls": [{"id": "c1", "type": "function", "function": {"name": "batch", "arguments": "{commands: [oops"}}]}}]}), + ]); + let seen = Arc::new(std::sync::Mutex::new(Vec::::new())); + let log = seen.clone(); + let http: HttpFn = Arc::new(move |r: &HttpRequest| { + log.lock().unwrap().push(serde_json::from_slice(r.body.as_deref().unwrap_or(b"null")).unwrap()); + Ok((200, answers.lock().unwrap().pop().unwrap_or(json!({})).to_string().into_bytes())) + }); + let cfg = ApiConfig { name: "Test".into(), base_url: "http://localhost:1/v1".into(), model: "m".into(), key: None, http }; + let ctx = StartContext { cwd: std::env::temp_dir(), bridge: None, tools: None, wake: Box::new(|| {}) }; + let mut b = ApiBackend::start(cfg, ctx).unwrap(); + b.prompt(&[PromptPart::Text("go".into())]); + let mut events = Vec::new(); + let start = std::time::Instant::now(); + while !events.iter().any(|e| matches!(e, Event::TurnEnded { .. })) && start.elapsed() < Duration::from_secs(10) { + events.extend(b.poll()); + std::thread::sleep(Duration::from_millis(10)); + } + let failed = events.iter().find_map(|e| match e { + Event::Tool { status: Some(ToolStatus::Failed), output: Some(o), .. } => Some(o.clone()), + _ => None, + }); + assert!(failed.is_some_and(|o| o.contains("Not run") && o.contains("not valid JSON")), "{events:?}"); + // The model was told, in the next request. + let sent = seen.lock().unwrap(); + let last = sent[1]["messages"].as_array().unwrap().last().unwrap().clone(); + assert!(last["content"].as_str().unwrap_or("").contains("not valid JSON"), "{last}"); + b.shutdown(true); + } + #[test] fn keys_never_go_over_plain_http_to_another_computer() { let http: HttpFn = Arc::new(|_: &HttpRequest| Ok((200, b"{}".to_vec()))); diff --git a/crates/ui-egui/src/agent_chat/gate.rs b/crates/ui-egui/src/agent_chat/gate.rs index 6317808ea..2eb4141c5 100644 --- a/crates/ui-egui/src/agent_chat/gate.rs +++ b/crates/ui-egui/src/agent_chat/gate.rs @@ -27,8 +27,36 @@ pub enum Verdict { /// itself) is the agent's. const METHODS: &[&str] = &["engine.commands", "document.inspect", "engine.execute", "engine.batch", "ui.view", "ui.render", "ui.screenshot"]; -/// Parameter names that hold a file or folder. -const PATH_KEYS: &[&str] = &["path", "paths", "file", "files", "dir", "folder", "out", "output", "filename", "source", "target_path"]; +/// Parameter names that hold a file or folder and nothing else. +const FILE_KEYS: &[&str] = &["file", "files", "dir", "folder", "out", "output", "filename", "target_path"]; + +/// Parameter names that are a file in some commands and geometry in others (`path`: a sweep's or +/// pattern's curve ids, an occurrence's ids; `source`: a feature or body). They name a file only +/// when the value reads like one, or the command is by its nature about files. +const AMBIGUOUS_KEYS: &[&str] = &["path", "paths", "source"]; + +/// File extensions that make a bare word a file name. +const FILE_EXTENSIONS: &[&str] = &[ + "solidcraft", + "json", + "csv", + "step", + "stp", + "iges", + "igs", + "stl", + "3mf", + "obj", + "dxf", + "svg", + "png", + "jpg", + "jpeg", + "urdf", + "txt", + "py", + "toml", +]; /// Commands that only read (not counted as changes). fn reads_only(id: &str) -> bool { @@ -39,13 +67,45 @@ fn reads_only(id: &str) -> bool { || matches!(id, "edit.checkpoint" | "render.status" | "render.backends" | "render.settings.get" | "file.slicers") } -fn names_a_file(params: &Value) -> Option { +/// Commands that read or write a file by their nature: any string they are given in a path +/// parameter is a file, whatever it looks like. +fn is_file_verb(id: &str) -> bool { + id.starts_with("library.") || ["export", "import", "save", "open", "insert", "load", "write", "recover"].iter().any(|v| id.contains(v)) +} + +/// Whether `s` reads like a file or folder name: a path separator, `~`, a leading dot, or a known +/// extension. Curve ids (`c1`), edge names (`edge-3`) and the like do not. +fn looks_like_file(s: &str) -> bool { + if s.is_empty() || s.len() > 4096 { + return false; + } + if s.contains('/') || s.contains('\\') || s.starts_with('~') || s.starts_with('.') { + return true; + } + s.rsplit_once('.').is_some_and(|(stem, ext)| !stem.is_empty() && FILE_EXTENSIONS.contains(&ext.to_ascii_lowercase().as_str())) +} + +/// The first file or folder a request's parameters name, for the question and the decision. +/// `id`: the command (empty for methods that are not commands). +fn names_a_file(id: &str, params: &Value) -> Option { let o = params.as_object()?; - PATH_KEYS.iter().find_map(|k| match o.get(*k) { - Some(Value::String(s)) if !s.is_empty() => Some(s.chars().take(200).collect()), - Some(Value::Array(a)) if !a.is_empty() => Some(a.iter().filter_map(Value::as_str).take(3).collect::>().join(", ")), - _ => None, - }) + let shown = |s: &str| s.chars().take(200).collect::(); + let by_nature = is_file_verb(id); + let first = |v: &Value, any: bool| -> Option { + match v { + Value::String(s) if any && !s.is_empty() => Some(shown(s)), + Value::String(s) if looks_like_file(s) => Some(shown(s)), + Value::Array(a) => { + let names: Vec<&str> = a.iter().filter_map(Value::as_str).filter(|s| (any && !s.is_empty()) || looks_like_file(s)).take(3).collect(); + (!names.is_empty()).then(|| names.join(", ")) + } + _ => None, + } + }; + FILE_KEYS + .iter() + .find_map(|k| o.get(*k).and_then(|v| first(v, true))) + .or_else(|| AMBIGUOUS_KEYS.iter().find_map(|k| o.get(*k).and_then(|v| first(v, by_nature)))) } /// One command as the agent would run it. `undo_left`: steps this turn may still undo without @@ -60,7 +120,7 @@ pub fn command(id: &str, params: &Value, undo_left: usize) -> Verdict { } // Files, and commands that replace or reload the whole design. let file_command = id.starts_with("file.") || id.starts_with("doc.") || matches!(id, "render.export" | "render.start"); - if let Some(p) = names_a_file(params) { + if let Some(p) = names_a_file(id, params) { return Verdict::Ask(format!("{id}: {p}")); } if file_command && !reads_only(id) { @@ -111,7 +171,7 @@ pub fn request(method: &str, params: &Value, undo_left: usize) -> Verdict { } } // A picture saved to a file names it. - "ui.screenshot" | "ui.render" => match names_a_file(params) { + "ui.screenshot" | "ui.render" => match names_a_file("ui.render.export", params) { Some(_) if is_scratch(params) => Verdict::Run { change: false }, Some(p) => Verdict::Ask(format!("{method}: {p}")), None => Verdict::Run { change: false }, @@ -189,6 +249,60 @@ mod tests { assert!(matches!(request("engine.batch", &batch, 0), Verdict::Ask(a) if a.contains("/etc/x"))); } + /// `path`, `source` and friends are also geometry (curve ids, edges, occurrence ids): those + /// are not files and must not stop a sweep or a pattern with a question. + #[test] + fn geometry_named_path_is_not_a_file() { + assert_eq!(exec("solid.sweep", json!({"profile": "S1", "path_sketch": "S2", "path": ["c1", "c2"]})), Verdict::Run { change: true }); + assert_eq!( + exec("solid.pattern.path", json!({"features": ["F1"], "path_sketch": "S2", "path": ["c1"], "count": 4})), + Verdict::Run { change: true } + ); + assert_eq!(exec("construct.plane.along_path", json!({"path": "edge-3", "t": 0.5})), Verdict::Run { change: true }); + assert_eq!(exec("component.move", json!({"component": 2, "path": [4, 7], "translate": [1, 0, 0]})), Verdict::Run { change: true }); + assert_eq!(exec("occurrence.move", json!({"occurrence": 3, "path": [1, 2]})), Verdict::Run { change: true }); + let batch = json!({"commands": [ + {"command": "solid.box", "params": {}}, + {"command": "solid.sweep", "params": {"path": ["c1", "c2"], "path_sketch": "S"}}, + ]}); + assert_eq!(request("engine.batch", &batch, 0), Verdict::Run { change: true }); + } + + /// What does name a file still asks, with or without a separator or an extension, and in + /// the commands that export, import or save by their nature. + #[test] + fn real_file_names_still_ask() { + for (id, p) in [ + ("sketch.export_dxf", json!({"path": "/tmp/s.dxf"})), + ("sketch.export_dxf", json!({"path": "s"})), + ("parameters.export", json!({"path": "params"})), + ("parameters.import", json!({"path": "p.csv"})), + ("motion.export", json!({"study": "a", "path": "out.csv"})), + ("canvas.insert", json!({"file": "pic"})), + ("library.apply", json!({"path": "lib"})), + ("solid.box", json!({"filename": "x"})), + ("solid.box", json!({"path": "../x.step"})), + ("solid.box", json!({"paths": ["a/b.step"]})), + ("solid.box", json!({"dir": "out"})), + ] { + assert!(matches!(exec(id, p.clone()), Verdict::Ask(_)), "{id} {p}"); + } + } + + /// Every registered `file.*` and `doc.*` command asks, so a new one cannot slip through by + /// name (the read-only ones, `reads_only`, are the listed exceptions). + #[test] + fn every_registered_file_and_doc_command_asks() { + let mut n = 0; + for spec in solidcraft_engine::command_specs() { + if (spec.id.starts_with("file.") || spec.id.starts_with("doc.")) && !reads_only(spec.id) { + n += 1; + assert!(matches!(exec(spec.id, json!({})), Verdict::Ask(_)), "{}", spec.id); + } + } + assert!(n >= 8, "found {n}"); + } + #[test] fn crash_reports_and_app_methods_are_never_the_agents() { assert!(matches!(exec("diagnostics.crash_reports", json!({})), Verdict::Refuse(_))); diff --git a/docs/agent-chat.md b/docs/agent-chat.md index 185ba1a03..756060c18 100644 --- a/docs/agent-chat.md +++ b/docs/agent-chat.md @@ -136,6 +136,12 @@ using one of SolidCraft's tools, SolidCraft answers for you, since its own gate and notes it in the chat as *Auto-allowed*. With **Allow everything**, or after **Always allow**, the agent's other questions are answered the same way and noted too. +What counts as "a command given a file name": a parameter that holds a file or folder (`file`, +`dir`, `output`, …), or `path` and `source` when the value reads like a file name (a separator, `~`, +a leading dot or a known extension), or any value of those in a command that exports, imports, +saves, opens or inserts. A sweep's or pattern's `path` (curve ids) and an occurrence's `path` +(ids) are geometry and run without a question. + ## What it can't do - **Files wait for you** unless you chose **Allow everything**. **Cancel** or **Stop** declines From 96d1ad0ab20a32da70e1fb8a422dd4c712a18382 Mon Sep 17 00:00:00 2001 From: cronos Date: Fri, 16 Oct 2026 08:09:26 +0900 Subject: [PATCH 14/92] Show optional X/Y/Z distances in measurement overlays (#1422) Measure can show the world-axis components alongside the total distance, with a Graphics preference to turn them off. Co-authored-by: cronos <19868002+crono2250@users.noreply.github.com> Co-Authored-By: Claude Sonnet 5.5 --- assets/locales/de.json | 2 + assets/locales/en.json | 2 + assets/locales/fr.json | 2 + assets/locales/ja.json | 2 + assets/locales/ko.json | 2 + assets/locales/ru.json | 2 + assets/locales/uk.json | 2 + assets/locales/zh.json | 2 + crates/ui-egui/src/canvas.rs | 76 ++++++++++ crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/measurement_ui_tests.rs | 153 +++++++++++++++++++++ crates/ui-egui/src/prefs.rs | 11 +- docs/book/src/guide/sketching.md | 5 + docs/control-protocol.md | 11 ++ 14 files changed, 272 insertions(+), 2 deletions(-) create mode 100644 crates/ui-egui/src/measurement_ui_tests.rs diff --git a/assets/locales/de.json b/assets/locales/de.json index 0d0c6524d..42755ebd8 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -1,4 +1,6 @@ { + "settings.measure_axis_distances": "X/Y/Z-Maße anzeigen", + "settings.measure_axis_distances_help": "Bei geöffneter Messung die Abstände entlang der Weltachsen zusätzlich zum Gesamtabstand anzeigen.", "Send your report on GitHub": "Bericht auf GitHub senden", "1. Open GitHub draft below, then paste the report copied to your clipboard.": "1. Unten den GitHub-Entwurf öffnen und den kopierten Bericht aus der Zwischenablage einfügen.", "1. Open GitHub draft below. Your title and report will be filled in.": "1. Unten den GitHub-Entwurf öffnen. Titel und Bericht werden vorausgefüllt.", diff --git a/assets/locales/en.json b/assets/locales/en.json index 18d234ca1..ac454dc78 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -1,4 +1,6 @@ { + "settings.measure_axis_distances": "Show X/Y/Z distances", + "settings.measure_axis_distances_help": "Show world-axis component dimensions alongside the total distance while Measure is open.", "Send your report on GitHub": "Send your report on GitHub", "1. Open GitHub draft below, then paste the report copied to your clipboard.": "1. Open GitHub draft below, then paste the report copied to your clipboard.", "1. Open GitHub draft below. Your title and report will be filled in.": "1. Open GitHub draft below. Your title and report will be filled in.", diff --git a/assets/locales/fr.json b/assets/locales/fr.json index 182b8a9c2..2cfea4c4e 100644 --- a/assets/locales/fr.json +++ b/assets/locales/fr.json @@ -1,4 +1,6 @@ { + "settings.measure_axis_distances": "Afficher les cotes X/Y/Z", + "settings.measure_axis_distances_help": "Afficher les cotes suivant les axes du repère global en plus de la distance totale pendant la mesure.", "Send your report on GitHub": "Envoyer votre rapport sur GitHub", "1. Open GitHub draft below, then paste the report copied to your clipboard.": "1. Ouvrir le brouillon GitHub ci-dessous, puis coller le rapport copié dans le presse-papiers.", "1. Open GitHub draft below. Your title and report will be filled in.": "1. Ouvrir le brouillon GitHub ci-dessous. Votre titre et votre rapport y seront déjà remplis.", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 29bb48eda..f71689d72 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -1,4 +1,6 @@ { + "settings.measure_axis_distances": "計測のX・Y・Z距離を表示", + "settings.measure_axis_distances_help": "計測ダイアログを開いている間、2点間距離に加えてワールドX・Y・Z軸方向の寸法線と距離を表示します。", "Send your report on GitHub": "GitHubでレポートを送信", "1. Open GitHub draft below, then paste the report copied to your clipboard.": "1. 下のボタンでGitHubの下書きを開き、クリップボードにコピーされたレポートを貼り付けます。", "1. Open GitHub draft below. Your title and report will be filled in.": "1. 下のボタンでGitHubの下書きを開きます。タイトルとレポートは入力済みです。", diff --git a/assets/locales/ko.json b/assets/locales/ko.json index ea74c84bd..758975dd0 100644 --- a/assets/locales/ko.json +++ b/assets/locales/ko.json @@ -1,4 +1,6 @@ { + "settings.measure_axis_distances": "X/Y/Z 거리 표시", + "settings.measure_axis_distances_help": "측정 대화상자가 열려 있는 동안 전체 거리와 함께 월드 축 방향 치수와 거리를 표시합니다.", "Send your report on GitHub": "GitHub에서 보고서 보내기", "1. Open GitHub draft below, then paste the report copied to your clipboard.": "1. 아래에서 GitHub 초안을 열고 클립보드에 복사된 보고서를 붙여넣으세요.", "1. Open GitHub draft below. Your title and report will be filled in.": "1. 아래에서 GitHub 초안을 여세요. 제목과 보고서가 자동으로 입력됩니다.", diff --git a/assets/locales/ru.json b/assets/locales/ru.json index 964efd542..70822a6ad 100644 --- a/assets/locales/ru.json +++ b/assets/locales/ru.json @@ -1,4 +1,6 @@ { + "settings.measure_axis_distances": "Расстояния X/Y/Z", + "settings.measure_axis_distances_help": "Показывать размеры вдоль мировых осей вместе с общим расстоянием, пока открыто окно измерения.", "browser.body_name": "Тело{number}", "browser.component_name": "Компонент{number}", "browser.parameters": "Параметры ({count})", diff --git a/assets/locales/uk.json b/assets/locales/uk.json index 449050bb8..fd32c912e 100644 --- a/assets/locales/uk.json +++ b/assets/locales/uk.json @@ -1,4 +1,6 @@ { + "settings.measure_axis_distances": "Відстані X/Y/Z", + "settings.measure_axis_distances_help": "Показувати розміри вздовж світових осей разом із загальною відстанню, поки відкрите вікно вимірювання.", "Send your report on GitHub": "Надіслати звіт на GitHub", "1. Open GitHub draft below, then paste the report copied to your clipboard.": "1. Відкрийте чернетку GitHub нижче, а потім вставте звіт, скопійований у буфер обміну.", "1. Open GitHub draft below. Your title and report will be filled in.": "1. Відкрийте чернетку GitHub нижче. Заголовок і звіт буде заповнено.", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index bea389b1c..4d3a0aa77 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -1,4 +1,6 @@ { + "settings.measure_axis_distances": "显示 X/Y/Z 距离", + "settings.measure_axis_distances_help": "测量对话框打开时,在总距离之外显示沿世界坐标轴方向的尺寸线和距离。", "Send your report on GitHub": "在 GitHub 上发送报告", "1. Open GitHub draft below, then paste the report copied to your clipboard.": "1. 点击下方按钮打开 GitHub 草稿,然后粘贴已复制到剪贴板的报告。", "1. Open GitHub draft below. Your title and report will be filled in.": "1. 点击下方按钮打开 GitHub 草稿。标题和报告将自动填入。", diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 22641c893..95929af31 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -769,7 +769,13 @@ fn radius_spline_handles(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Pain fn measure_line(app: &SolveApp, painter: &egui::Painter, proj: &Proj, r: &serde_json::Value, show: Option) { let t = Tokens::get(); let Some((_, d, a, b)) = crate::dialogs::shown_distance(r, show) else { return }; + if !a.is_finite() || !b.is_finite() || !d.is_finite() { + return; + } let (Some(sa), Some(sb)) = (proj.to_screen(a), proj.to_screen(b)) else { return }; + if !sa.is_finite() || !sb.is_finite() { + return; + } painter.line_segment([sa, sb], Stroke::new(2.0, t.manipulator)); for s in [sa, sb] { painter.circle(s, 3.5, t.manipulator, Stroke::new(1.0, Color32::WHITE)); @@ -777,10 +783,80 @@ fn measure_line(app: &SolveApp, painter: &egui::Painter, proj: &Proj, r: &serde_ let mid = sa + (sb - sa) * 0.5 + vec2(10.0, -14.0); let galley = painter.layout_no_wrap(crate::prefs::show_mm(app, d, 1), egui::FontId::proportional(12.5), t.text); let rect = egui::Rect::from_min_size(mid, galley.size() + vec2(10.0, 6.0)); + crate::scenario::publish_handle("measure:label", rect.center()); + crate::scenario::publish_rect("measure:label", rect); + if app.preferences.measure_axis_distances { + measure_components(app, painter, proj, a, b, rect); + } painter.rect(rect, 3.0, t.overlay, Stroke::new(1.0, t.border), egui::StrokeKind::Inside); painter.galley(rect.min + vec2(5.0, 3.0), galley, t.text); } +/// A world-axis-aligned chain between the same two measured points. Zero-length and +/// view-aligned legs still get a label; labels move apart when their projections coincide. +fn measure_components(app: &SolveApp, painter: &egui::Painter, proj: &Proj, a: Vec3, b: Vec3, total: egui::Rect) { + let t = Tokens::get(); + let x = Vec3::new(b.x, a.y, a.z); + let y = Vec3::new(b.x, b.y, a.z); + let mut occupied = vec![total]; + for (axis, start, end, color) in [("x", a, x, t.axis_x), ("y", x, y, t.axis_y), ("z", y, b, t.axis_z)] { + let color = color.lerp_to_gamma(t.text, 0.25); + let distance = start.dist(end); + if !distance.is_finite() { + continue; + } + let screen = + proj.to_screen(start).zip(proj.to_screen(end)).filter(|(sa, sb)| sa.is_finite() && sb.is_finite() && (*sb - *sa).length_sq().is_finite()); + let (at, offset) = if let Some((sa, sb)) = screen { + let leg = sb - sa; + if leg.length_sq() > 1.0 { + painter.add(egui::Shape::dashed_line(&[sa, sb], Stroke::new(1.5, color), 5.0, 3.0)); + let normal = vec2(-leg.y, leg.x).normalized(); + for p in [sa, sb] { + painter.line_segment([p - normal * 3.0, p + normal * 3.0], Stroke::new(1.0, color)); + } + (sa + leg * 0.5, normal * 20.0) + } else { + (sa, vec2(20.0, 20.0)) + } + } else { + (total.center(), vec2(20.0, 20.0)) + }; + let text = format!("{}: {}", axis.to_uppercase(), crate::prefs::show_mm(app, distance, 1)); + let galley = painter.layout_no_wrap(text, egui::FontId::proportional(12.5), t.text); + let size = galley.size() + vec2(10.0, 6.0); + let bounds = proj.rect.shrink(4.0); + let clamp = |rect: egui::Rect| { + egui::Rect::from_min_size( + egui::pos2( + rect.left().clamp(bounds.left(), (bounds.right() - size.x).max(bounds.left())), + rect.top().clamp(bounds.top(), (bounds.bottom() - size.y).max(bounds.top())), + ), + size, + ) + }; + let preferred = clamp(egui::Rect::from_center_size(at + offset, size)); + let mut rect = preferred; + // Four labels at most. Search both sides of the anchor, including at viewport edges. + 'place: for row in 0..12 { + for side in [1.0, -1.0] { + let candidate = clamp(preferred.translate(vec2(0.0, side * row as f32 * (size.y + 4.0)))); + if occupied.iter().all(|other| !other.expand(3.0).intersects(candidate)) { + rect = candidate; + break 'place; + } + } + } + painter.line_segment([at, rect.center()], Stroke::new(0.8, color)); + painter.rect(rect, 3.0, t.overlay, Stroke::new(1.0, color), egui::StrokeKind::Inside); + painter.galley(rect.min + vec2(5.0, 3.0), galley, t.text); + let handle = format!("measure:label:{axis}"); + crate::scenario::publish_handle(&handle, rect.center()); + crate::scenario::publish_rect(&handle, rect); + occupied.push(rect); + } +} + /// The taper handle: a line from `foot` along the extrude (`span`) leaning by `angle` towards /// `e`, with a ring at its end; dragging the ring sideways sets the angle (1° steps, Alt/Ctrl: /// free). diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 8311be002..b0026ec6e 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -63,6 +63,8 @@ pub mod issue_report; pub mod keymap; mod material_card_review; #[cfg(test)] +mod measurement_ui_tests; +#[cfg(test)] mod menu_tests; #[cfg(test)] mod surface_clamp_tests; diff --git a/crates/ui-egui/src/measurement_ui_tests.rs b/crates/ui-egui/src/measurement_ui_tests.rs new file mode 100644 index 000000000..12ca2ce86 --- /dev/null +++ b/crates/ui-egui/src/measurement_ui_tests.rs @@ -0,0 +1,153 @@ +//! World-axis component dimensions use the same endpoints as the displayed measurement. +use crate::dialogs::Kind; +use crate::scenario::Harness; +use serde_json::{Value, json}; +use solidcraft_engine::Sel; + +fn result(h: &Harness) -> &Value { + match &h.app.dialog.as_ref().unwrap().kind { + Kind::Measure { result: Some(r), .. } => r, + _ => panic!("expected a measurement result"), + } +} + +fn vertex_measurement(a: [f64; 3], b: [f64; 3]) -> Harness { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.ui.show_origin = false; + h.app.ui.show_browser = false; + h.app.run("solid.box", json!({"length":3,"width":4,"height":12,"corner":[-3,0,-12],"body_name":"Box"})).unwrap(); + h.app.session.selection = [a, b].into_iter().map(|p| Sel::Vertex { body: "Box".into(), point: p.into() }).collect(); + h.app.start("inspect.measure"); + h.call("ui.view", json!({"view":"fit"})); + h +} + +/// Inspect the actual painted text, including the viewport labels (which are not widgets). +fn painted_text(h: &mut Harness) -> Vec { + // Continue the harness clock (a hair on) so egui's input history never sees time go backwards. + let time = h.ctx.input(|i| i.time) + 1e-4; + let raw = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 1000.0))), + time: Some(time), + ..Default::default() + }; + let mut output = h.ctx.run_ui(raw, |ui| h.app.ui(ui)); + output.textures_delta.clear(); + output.shapes.iter().filter_map(|s| if let egui::Shape::Text(t) = &s.shape { Some(t.galley.text().to_string()) } else { None }).collect() +} + +fn component_rects() -> Vec { + ["measure:label", "measure:label:x", "measure:label:y", "measure:label:z"].into_iter().map(|key| crate::scenario::rect_of(key).unwrap()).collect() +} + +#[test] +fn measurement_axis_distances_follow_the_upstream_centre_min_and_max_choices() { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.ui.show_origin = false; + h.app.ui.show_browser = false; + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + let mut items = Vec::new(); + for (center, radius) in [([0, 0], 3), ([30, 40], 5)] { + let made = h.app.run("sketch.circle.center", json!({"center":center,"radius":radius})).unwrap(); + items.push(Sel::SketchCurve { id: made["curves"][0].as_str().unwrap().into() }); + } + h.app.session.selection = items; + h.app.start("inspect.measure"); + h.call("ui.view", json!({"view":"fit"})); + let measured = result(&h).clone(); + assert!((measured["center_distance"].as_f64().unwrap() - 50.).abs() < 1e-8); + assert!(measured["distance_mm"].as_f64().unwrap() < 50. && measured["max"].as_f64().unwrap() > 50.); + + for (label, distance, from, to) in [ + ("Centre to centre", "center_distance", "center_from", "center_to"), + ("Min", "distance_mm", "from", "to"), + ("Max", "max", "max_from", "max_to"), + ] { + let [x, y] = h.widget(label).unwrap_or_else(|| panic!("missing upstream distance choice: {label}")); + h.call("ui.click", json!({"x":x,"y":y})); + let texts = painted_text(&mut h); + for (axis, index) in [("X", 0), ("Y", 1), ("Z", 2)] { + let delta = measured[to][index].as_f64().unwrap() - measured[from][index].as_f64().unwrap(); + let expected = format!("{axis}: {}", crate::prefs::show_mm(&h.app, delta.abs(), 1)); + assert!(texts.contains(&expected), "{label} must use its own endpoints: {texts:?}"); + } + assert!(texts.contains(&crate::prefs::show_mm(&h.app, measured[distance].as_f64().unwrap(), 1))); + assert_eq!(*result(&h), measured, "changing the displayed distance must retain upstream measurement results"); + } +} + +#[test] +fn measurement_axis_distances_show_absolute_world_components_in_every_view() { + for reverse in [false, true] { + let (a, b) = ([0., 0., 0.], [-3., 4., -12.]); + let mut h = if reverse { vertex_measurement(b, a) } else { vertex_measurement(a, b) }; + assert!((result(&h)["distance_mm"].as_f64().unwrap() - 13.).abs() < 1e-8); + for view in ["iso", "top", "front", "right"] { + h.call("ui.view", json!({"view":view})); + let texts = painted_text(&mut h); + for text in ["13.00 mm", "X: 3.00 mm", "Y: 4.00 mm", "Z: 12.00 mm"] { + assert!(texts.iter().any(|t| t == text), "{view}, reverse={reverse}: {texts:?}"); + } + let rects = component_rects(); + for (i, a) in rects.iter().enumerate() { + assert!(rects.iter().skip(i + 1).all(|b| !a.intersects(*b)), "labels overlap in {view}: {rects:?}"); + } + } + h.call("ui.set", json!({"perspective":true})); + h.call("ui.prefs", json!({"up_axis":"y"})); + let texts = painted_text(&mut h); + assert!(texts.contains(&"Z: 12.00 mm".to_string()), "view orientation does not change world-axis distances"); + h.call("ui.key", json!({"key":"Escape"})); + assert!(crate::scenario::handles("measure:label").is_empty(), "all temporary dimensions disappear on close"); + } +} + +#[test] +fn measurement_axis_distances_keep_zero_components_readable_and_follow_units() { + let mut h = vertex_measurement([0., 0., 0.], [-3., 0., 0.]); + h.call("ui.view", json!({"view":"top"})); + let texts = painted_text(&mut h); + assert!(texts.contains(&"Y: 0.00 mm".into()) && texts.contains(&"Z: 0.00 mm".into())); + let rects = component_rects(); + for (i, a) in rects.iter().enumerate() { + assert!(rects.iter().skip(i + 1).all(|b| !a.intersects(*b)), "zero-component labels must remain readable: {rects:?}"); + } + h.app.run("document.units", json!({"units":"in"})).unwrap(); + h.call("ui.prefs", json!({"length_decimals":3})); + let texts = painted_text(&mut h); + assert!(texts.contains(&"X: 0.1181 in".into()), "inch dimensions retain a meaningful fourth digit: {texts:?}"); + assert!(texts.contains(&"Y: 0.000 in".into()) && texts.contains(&"Z: 0.000 in".into())); +} + +#[test] +fn measurement_axis_distances_can_be_disabled_saved_and_restored_in_preferences() { + assert!(serde_json::from_value::(json!({})).unwrap().measure_axis_distances, "existing settings get the default-on option"); + let mut h = vertex_measurement([0., 0., 0.], [-3., 4., -12.]); + let measurement = result(&h).clone(); + h.call("ui.prefs", json!({"open":"Graphics"})); + 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); + assert!(crate::scenario::handle_at("measure:label").is_some(), "total stays visible"); + assert!(crate::scenario::handle_at("measure:label:x").is_none()); + assert_eq!(*result(&h), measurement, "hiding the extra overlay does not change the measurement"); + h.call("ui.prefs", json!({"button":"ok"})); + let texts = painted_text(&mut h); + assert!(!texts.iter().any(|text| text.starts_with("X: ") || text.starts_with("Y: ") || text.starts_with("Z: "))); + let mut restored = crate::SolveApp::new(Default::default(), Default::default()); + restored.load_prefs(&h.app.prefs()); + assert!(!restored.preferences.measure_axis_distances, "disabled preference survives restart"); + h.call("ui.prefs", json!({"open":"Graphics","measure_axis_distances":true})); + assert!(crate::scenario::handle_at("measure:label:x").is_some()); + h.call("ui.prefs", json!({"button":"cancel"})); + assert!(!h.app.preferences.measure_axis_distances, "Cancel restores the saved choice"); + h.call("ui.prefs", json!({"open":"Graphics"})); + h.call("ui.prefs", json!({"button":"defaults"})); + assert!(h.app.preferences.measure_axis_distances); + h.call("ui.prefs", json!({"button":"apply"})); + h.call("ui.prefs", json!({"measure_axis_distances":false})); + h.call("ui.prefs", json!({"button":"cancel"})); + assert!(h.app.preferences.measure_axis_distances, "Cancel restores the last Apply"); +} diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index 6498e5491..6a81f8998 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -283,6 +283,8 @@ pub struct Prefs { pub supersampling: f32, /// Supersample only while the view holds still (full speed while orbiting). pub supersampling_adaptive: bool, + /// Show world X/Y/Z component dimensions beside the total distance in Measure. + pub measure_axis_distances: bool, /// Decimals shown for lengths and angles. pub length_decimals: u8, pub angle_decimals: u8, @@ -396,6 +398,7 @@ impl Default for Prefs { display_quality: "normal".into(), supersampling: 1.0, supersampling_adaptive: true, + measure_axis_distances: true, length_decimals: 2, angle_decimals: 1, theme: "dark".into(), @@ -618,6 +621,7 @@ fn defaults(app: &mut SolveApp, page: usize) { p.display_quality = d.display_quality; p.supersampling = d.supersampling; p.supersampling_adaptive = d.supersampling_adaptive; + p.measure_axis_distances = d.measure_axis_distances; p.color_vision = d.color_vision; app.ui.visual_style = 0; app.ui.show_grid = true; @@ -1278,9 +1282,12 @@ fn page(app: &mut SolveApp, ui: &mut egui::Ui, t: &Tokens) { _ => "CPU (software)".to_string(), }); ui.end_row(); - // Colour vision (#778): its own section at the end of the page. - ui.label(""); + ui.label(app.tr("settings.measure_axis_distances")); + let response = ui.checkbox(&mut app.preferences.measure_axis_distances, ""); + 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(); diff --git a/docs/book/src/guide/sketching.md b/docs/book/src/guide/sketching.md index 3affeb018..3ca3c4efd 100644 --- a/docs/book/src/guide/sketching.md +++ b/docs/book/src/guide/sketching.md @@ -243,6 +243,11 @@ retain trailing zeros. Component/canvas distance controls and inspection, parts- and flat-pattern measurements follow design units too; parameter expressions and metric standard names retain their explicit authored units. +Measure shows the currently selected distance (centre, minimum or maximum) and separate X, Y and Z +distances on the canvas. The component dimensions follow the world axes and remain visible +until the Measure dialog closes. To hide these extra lines and labels, turn off +**Preferences > Graphics > Show X/Y/Z distances**. The choice is saved between runs. + ### Reviewing mirror, pattern, and offset results Mirror, rectangular/circular Pattern, and Offset show the active selection step in their diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 5c5a6e92b..eb2360fd4 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -97,6 +97,17 @@ read in the design's units, exactly as if it were typed into the dimension box: unit regardless of the design, pass an expression with one: `"value": "50 mm"` or `"value": "0.5 in"`. Angles are degrees unless the expression says otherwise. +The viewport also shows an X/Y/Z-aligned dimension chain between the endpoints of the +currently shown distance (centre, minimum or maximum), with each world-axis distance +labelled separately as an absolute value (including zero). +It uses the design's units and length precision, independently of the view or sketch plane. +Preferences → Graphics → **Show X/Y/Z distances** controls these extra lines and +labels (default on, saved between runs). Set `ui.prefs {"measure_axis_distances": false}` +to hide them while keeping the total distance and the dialog's ΔX/ΔY/ΔZ values. These +overlays remain visible until Measure closes. +Overlay handles `measure:label:x`, `measure:label:y` and `measure:label:z` identify the extra +labels; `prefs:measure_axis_distances` identifies the checkbox. + ## UI | Method | Params | Notes | From 4097ac0131a5cf4f6ce9db675aa2e8c54482d93e Mon Sep 17 00:00:00 2001 From: bherbruck Date: Thu, 15 Oct 2026 19:12:55 -0400 Subject: [PATCH 15/92] sketch.cut: refuse non-object params instead of panicking --- crates/engine/src/cmd/sketch_clipboard.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/sketch_clipboard.rs b/crates/engine/src/cmd/sketch_clipboard.rs index 5818063cb..b8036f933 100644 --- a/crates/engine/src/cmd/sketch_clipboard.rs +++ b/crates/engine/src/cmd/sketch_clipboard.rs @@ -209,8 +209,12 @@ fn copy(s: &mut Session, p: &Value) -> Result { } fn cut(s: &mut Session, p: &Value) -> Result { + // `q["entities"] = …` below panics on anything but an object. + if !(p.is_object() || p.is_null()) { + return Err(bad("sketch.cut", "params must be an object")); + } let entities = chosen(s, p); - let mut q = p.clone(); + let mut q = if p.is_null() { json!({}) } else { p.clone() }; q["entities"] = json!(entities); let out = copy(s, &q)?; let delete = super::find_command("sketch.delete").ok_or_else(|| bad("sketch.cut", "sketch.delete is missing"))?; From 2b45635d73138ed2610832b478e8ced900960670 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Thu, 15 Oct 2026 19:18:52 -0400 Subject: [PATCH 16/92] Version 0.13.1 --- Cargo.lock | 30 +++++++++++++++--------------- Cargo.toml | 2 +- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 137e4c9ac..e8312e2d7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3752,7 +3752,7 @@ dependencies = [ [[package]] name = "solidcraft" -version = "0.13.0" +version = "0.13.1" dependencies = [ "block2 0.6.2", "eframe", @@ -3781,7 +3781,7 @@ dependencies = [ [[package]] name = "solidcraft-cli" -version = "0.13.0" +version = "0.13.1" dependencies = [ "serde_json", "solidcraft-engine", @@ -3790,7 +3790,7 @@ dependencies = [ [[package]] name = "solidcraft-derive" -version = "0.13.0" +version = "0.13.1" dependencies = [ "proc-macro2", "quote", @@ -3799,7 +3799,7 @@ dependencies = [ [[package]] name = "solidcraft-doc" -version = "0.13.0" +version = "0.13.1" dependencies = [ "log", "serde", @@ -3816,7 +3816,7 @@ dependencies = [ [[package]] name = "solidcraft-engine" -version = "0.13.0" +version = "0.13.1" dependencies = [ "log", "serde", @@ -3832,7 +3832,7 @@ dependencies = [ [[package]] name = "solidcraft-geom" -version = "0.13.0" +version = "0.13.1" dependencies = [ "serde", "serde_json", @@ -3841,7 +3841,7 @@ dependencies = [ [[package]] name = "solidcraft-gpu" -version = "0.13.0" +version = "0.13.1" dependencies = [ "log", "naga", @@ -3854,7 +3854,7 @@ dependencies = [ [[package]] name = "solidcraft-io" -version = "0.13.0" +version = "0.13.1" dependencies = [ "gltf", "quick-xml", @@ -3870,7 +3870,7 @@ dependencies = [ [[package]] name = "solidcraft-kernel" -version = "0.13.0" +version = "0.13.1" dependencies = [ "log", "rayon", @@ -3888,7 +3888,7 @@ dependencies = [ [[package]] name = "solidcraft-mcp" -version = "0.13.0" +version = "0.13.1" dependencies = [ "serde_json", "solidcraft-engine", @@ -3896,7 +3896,7 @@ dependencies = [ [[package]] name = "solidcraft-render" -version = "0.13.0" +version = "0.13.1" dependencies = [ "image", "moxcms", @@ -3909,7 +3909,7 @@ dependencies = [ [[package]] name = "solidcraft-sketch" -version = "0.13.0" +version = "0.13.1" dependencies = [ "serde", "serde_json", @@ -3920,7 +3920,7 @@ dependencies = [ [[package]] name = "solidcraft-ui-egui" -version = "0.13.0" +version = "0.13.1" dependencies = [ "egui", "egui-wgpu", @@ -3941,7 +3941,7 @@ dependencies = [ [[package]] name = "solidcraft-web" -version = "0.13.0" +version = "0.13.1" dependencies = [ "eframe", "egui", @@ -5430,7 +5430,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7" [[package]] name = "xtask" -version = "0.13.0" +version = "0.13.1" dependencies = [ "serde_json", "sha2", diff --git a/Cargo.toml b/Cargo.toml index 07107d92f..b669ad901 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,7 +5,7 @@ members = ["crates/*", "apps/*", "xtask"] exclude = ["vendor"] [workspace.package] -version = "0.13.0" +version = "0.13.1" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" From 78242d67d1d35924ccba36142e2baf5625cafb80 Mon Sep 17 00:00:00 2001 From: Jackson Oursland Date: Thu, 15 Oct 2026 16:30:03 -0700 Subject: [PATCH 17/92] Import FreeCAD and Rhino files through cadmpeg (#1435) FreeCAD .FCStd and Rhino .3dm files open, insert and drop like STEP and IGES: cadmpeg (Apache-2.0, pinned =0.6.1, native builds only) detects the format, decodes it under its service resource caps, validates the model and writes it as STEP AP214, which becomes an Import feature in a new component named after the file, with the up and names options. Only the fcstd, rhino and step codecs are compiled in (no default features). ACIS is left out: cadmpeg's sat codec is a ShapeManager stream decoder. native_cad.rs is the single importer seam. Self-made FreeCAD and Rhino box fixtures, hostile-input, ZIP-bomb and cap tests, engine tests for the component path; the browser build reports these formats as not supported. A note under design format 23 says an Import's file can name these formats. Co-authored-by: Jacob Oursland Co-Authored-By: Claude Opus 5.5 --- ATTRIBUTION.md | 12 + Cargo.lock | 349 +++++- Cargo.toml | 8 + README.md | 4 +- ROADMAP.md | 4 +- THIRD-PARTY-LICENSES.txt | 1065 ++++++++++++----- apps/solidcraft/src/main.rs | 7 +- crates/doc/src/format.rs | 4 + crates/engine/src/cmd/file.rs | 6 +- crates/engine/src/tests.rs | 2 + crates/engine/src/tests/native_cad_import.rs | 94 ++ crates/io/Cargo.toml | 8 +- crates/io/src/lib.rs | 26 +- crates/io/src/native_cad.rs | 156 +++ crates/io/src/native_cad/fixtures/block.3dm | Bin 0 -> 19497 bytes crates/io/src/native_cad/fixtures/block.FCStd | Bin 0 -> 2485 bytes .../src/native_cad/fixtures/make_block_3dm.py | 11 + .../native_cad/fixtures/make_block_fcstd.py | 12 + crates/io/src/native_cad/tests.rs | 126 ++ crates/ui-egui/src/file_load.rs | 8 +- docs/book/src/guide/files.md | 3 +- docs/step-import.md | 6 + xtask/src/assets.rs | 2 + 23 files changed, 1585 insertions(+), 328 deletions(-) create mode 100644 crates/engine/src/tests/native_cad_import.rs create mode 100644 crates/io/src/native_cad.rs create mode 100644 crates/io/src/native_cad/fixtures/block.3dm create mode 100644 crates/io/src/native_cad/fixtures/block.FCStd create mode 100644 crates/io/src/native_cad/fixtures/make_block_3dm.py create mode 100644 crates/io/src/native_cad/fixtures/make_block_fcstd.py create mode 100644 crates/io/src/native_cad/tests.rs diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index d3419e479..9c7c0876a 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -110,6 +110,8 @@ Editable drawing code, native projects and shipped exports are collected under ` | assets/shaders/viewport.wgsl | SolidCraft contributors | Original SolidCraft resource data or drawing code, collected without redesign | MIT OR Apache-2.0 | | assets/styles/ui/palettes.rs | SolidCraft contributors | Original SolidCraft resource data or drawing code, collected without redesign | MIT OR Apache-2.0 | | assets/styles/web/loading.css | SolidCraft contributors | Original SolidCraft resource data or drawing code, collected without redesign | MIT OR Apache-2.0 | +| crates/io/src/native_cad/fixtures/block.FCStd | SolidCraft contributors | original 10 × 20 × 30 mm test box saved by FreeCAD 1.1.4 run as an external program (`make_block_fcstd.py` beside it); no third-party geometry | MIT OR Apache-2.0 | +| crates/io/src/native_cad/fixtures/block.3dm | SolidCraft contributors | original 10 × 20 × 30 mm test box written with McNeel's MIT-licensed rhino3dm Python package (`make_block_3dm.py` beside it); no third-party geometry | 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 | @@ -151,6 +153,16 @@ in THIRD-PARTY-LICENSES.txt; no images or artwork from that project are copied. The glTF test files are built by the tests themselves (crates/io/src/gltf_in_tests.rs, crates/engine/src/tests/gltf_import.rs); no third-party models are committed. +## FreeCAD and Rhino import library + +FreeCAD `.FCStd` and Rhino `.3dm` files are read with [cadmpeg](https://github.com/cadmpeg/cadmpeg) +0.6.1 (Apache-2.0), linked as the crates `cadmpeg-core`, `cadmpeg-ir`, `cadmpeg-registry`, +`cadmpeg-container`, `cadmpeg-codec-freecad`, `cadmpeg-codec-rhino` and `cadmpeg-codec-step` +in native builds (`crates/io/src/native_cad.rs`). Only those open-format codecs are built: no +default features, so cadmpeg's codecs for commercial CAD formats and its ShapeManager/ACIS +codec are not compiled in. Its licence text is in THIRD-PARTY-LICENSES.txt; no code from it is +copied into SolidCraft. + ## Recovered contributions | SolidCraft file | Original contribution | Licence | diff --git a/Cargo.lock b/Cargo.lock index e8312e2d7..6862c0be5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -131,7 +131,7 @@ checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" dependencies = [ "cfg-if", "cipher", - "cpufeatures", + "cpufeatures 0.2.17", ] [[package]] @@ -489,6 +489,15 @@ dependencies = [ "generic-array", ] +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + [[package]] name = "block-padding" version = "0.3.3" @@ -582,6 +591,117 @@ version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +[[package]] +name = "cadmpeg-codec-freecad" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a5257265c2549cf59a8457b3c7aadcc96c95abe20205232553766993a808812" +dependencies = [ + "cadmpeg-container", + "cadmpeg-core", + "cadmpeg-ir", + "roxmltree", + "serde", + "serde_json", + "tempfile", + "zip 8.6.0", +] + +[[package]] +name = "cadmpeg-codec-rhino" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d88b42fb91c7e5af4c75c0433029771f7e3233a0b72ec3d0b2e5ff2c72bed07" +dependencies = [ + "cadmpeg-container", + "cadmpeg-core", + "cadmpeg-ir", + "crc32fast", + "flate2", + "roxmltree", + "serde", + "serde_json", + "sha1 0.11.0", + "sha2 0.11.1", + "tempfile", +] + +[[package]] +name = "cadmpeg-codec-step" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e83a52258c129a683f77fb360ca30af54ae34339625ad890be12621128a5811c" +dependencies = [ + "base64", + "cadmpeg-container", + "cadmpeg-core", + "cadmpeg-ir", + "encoding_rs", + "serde_json", + "thiserror 2.0.21", + "zip 8.6.0", +] + +[[package]] +name = "cadmpeg-container" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c110508cd9155e905f52906de505dfd42dc70a0321f5e90b5f68c28ba207686e" +dependencies = [ + "cadmpeg-core", + "crc32fast", + "flate2", + "zip 8.6.0", + "zstd 0.14.2", +] + +[[package]] +name = "cadmpeg-core" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21b1147e51a74e7c52da5b393a0344597238cdc622fac6443eb2fd526759f6fa" +dependencies = [ + "flate2", + "memchr", + "roxmltree", + "serde", + "serde_json", + "thiserror 2.0.21", + "zstd 0.14.2", +] + +[[package]] +name = "cadmpeg-ir" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71ff19f019f013d97e353bb802c5d2e253c2859aaa5422009aa933dc2f2e7dbc" +dependencies = [ + "base64", + "cadmpeg-core", + "serde", + "serde-value", + "serde_json", + "sha2 0.11.1", + "thiserror 2.0.21", +] + +[[package]] +name = "cadmpeg-registry" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66046f1a694926707bea8944f861e699964b04c68972708588f97e14ccee3c5d" +dependencies = [ + "cadmpeg-codec-freecad", + "cadmpeg-codec-rhino", + "cadmpeg-codec-step", + "cadmpeg-container", + "cadmpeg-core", + "cadmpeg-ir", + "serde", + "thiserror 2.0.21", + "toml", +] + [[package]] name = "calloop" version = "0.13.0" @@ -704,7 +824,7 @@ version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" dependencies = [ - "crypto-common", + "crypto-common 0.1.7", "inout", ] @@ -756,6 +876,12 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + [[package]] name = "convert_case" version = "0.4.0" @@ -812,6 +938,12 @@ dependencies = [ "libc", ] +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -821,6 +953,15 @@ dependencies = [ "libc", ] +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + [[package]] name = "crc32fast" version = "1.5.2" @@ -871,6 +1012,15 @@ dependencies = [ "typenum", ] +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + [[package]] name = "cursor-icon" version = "1.2.0" @@ -902,7 +1052,7 @@ dependencies = [ "hkdf", "num", "once_cell", - "sha2", + "sha2 0.10.9", "zeroize", ] @@ -936,11 +1086,22 @@ version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ - "block-buffer", - "crypto-common", + "block-buffer 0.10.4", + "crypto-common 0.1.7", "subtle", ] +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid", + "crypto-common 0.2.2", +] + [[package]] name = "dispatch" version = "0.2.0" @@ -1155,6 +1316,20 @@ dependencies = [ "winreg", ] +[[package]] +name = "encoding_rs" +version = "0.8.42" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e985e0451871ad22fb8d2b6b076e2028a502a0d3950998c2c5c0a4f9b5d9679" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + [[package]] name = "endi" version = "1.1.1" @@ -1740,7 +1915,7 @@ version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" dependencies = [ - "digest", + "digest 0.10.7", ] [[package]] @@ -1759,6 +1934,15 @@ version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + [[package]] name = "iana-time-zone" version = "0.1.65" @@ -2252,6 +2436,12 @@ dependencies = [ "pxfm", ] +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + [[package]] name = "naga" version = "30.0.1" @@ -2767,6 +2957,15 @@ dependencies = [ "libredox", ] +[[package]] +name = "ordered-float" +version = "2.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68f19d67e5a2795c94e73e0bb1cc1a7edeb2e28efd39e2e1c9b7a40c1108b11c" +dependencies = [ + "num-traits", +] + [[package]] name = "ordered-float" version = "5.5.0" @@ -3291,6 +3490,15 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "roxmltree" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1964b10c76125c36f8afe190065a4bf9a87bf324842c05701330bba9f1cacbb" +dependencies = [ + "memchr", +] + [[package]] name = "rustc-hash" version = "1.1.0" @@ -3463,7 +3671,7 @@ dependencies = [ "once_cell", "rand", "serde", - "sha2", + "sha2 0.10.9", "zbus 4.4.0", ] @@ -3525,6 +3733,16 @@ dependencies = [ "serde_derive", ] +[[package]] +name = "serde-value" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3a1a3341211875ef120e117ea7fd5228530ae7e7036a779fdc9117be6b3282c" +dependencies = [ + "ordered-float 2.10.1", + "serde", +] + [[package]] name = "serde_core" version = "1.0.229" @@ -3585,8 +3803,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" dependencies = [ "cfg-if", - "cpufeatures", - "digest", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + +[[package]] +name = "sha1" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", ] [[package]] @@ -3596,8 +3825,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" dependencies = [ "cfg-if", - "cpufeatures", - "digest", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", ] [[package]] @@ -3804,7 +4044,7 @@ dependencies = [ "log", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "solidcraft-derive", "solidcraft-geom", "solidcraft-kernel", @@ -3856,16 +4096,19 @@ dependencies = [ name = "solidcraft-io" version = "0.13.1" dependencies = [ + "cadmpeg-core", + "cadmpeg-ir", + "cadmpeg-registry", "gltf", "quick-xml", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "solidcraft-doc", "solidcraft-geom", "solidcraft-kernel", "thiserror 2.0.21", - "zip", + "zip 3.0.0", ] [[package]] @@ -3903,7 +4146,7 @@ dependencies = [ "png", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "solidcraft-geom", ] @@ -3931,12 +4174,12 @@ dependencies = [ "semver", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "solidcraft-engine", "solidcraft-gpu", "ttf-parser", "web-time", - "zip", + "zip 3.0.0", ] [[package]] @@ -4370,6 +4613,12 @@ dependencies = [ "rustc-hash 2.1.3", ] +[[package]] +name = "typed-path" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e" + [[package]] name = "typeid" version = "1.0.3" @@ -4941,7 +5190,7 @@ dependencies = [ "objc2-metal 0.3.2", "objc2-quartz-core 0.3.2", "once_cell", - "ordered-float", + "ordered-float 5.5.0", "parking_lot", "portable-atomic", "portable-atomic-util", @@ -5433,7 +5682,7 @@ name = "xtask" version = "0.13.1" dependencies = [ "serde_json", - "sha2", + "sha2 0.10.9", ] [[package]] @@ -5486,7 +5735,7 @@ dependencies = [ "rand", "serde", "serde_repr", - "sha1", + "sha1 0.10.7", "static_assertions", "tracing", "uds_windows", @@ -5735,6 +5984,20 @@ dependencies = [ "zopfli", ] +[[package]] +name = "zip" +version = "8.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d04a6b5381502aa6087c94c669499eb1602eb9c5e8198e534de571f7154809b" +dependencies = [ + "crc32fast", + "flate2", + "indexmap", + "memchr", + "typed-path", + "zstd 0.13.3", +] + [[package]] name = "zlib-rs" version = "0.6.8" @@ -5759,6 +6022,52 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "zstd" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a" +dependencies = [ + "zstd-safe 7.3.0", +] + +[[package]] +name = "zstd" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "057cfd910cfac363a0ada849592624b4c9ff2e10bef504c3433810d78ed96f93" +dependencies = [ + "zstd-safe 8.1.0", +] + +[[package]] +name = "zstd-safe" +version = "7.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64d80649ab6db9d9f6f9c80a40becd948eda4714a0a5ac8c4d157a32231c7882" +dependencies = [ + "zstd-sys", +] + +[[package]] +name = "zstd-safe" +version = "8.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdd44c6a7284e91f3717755b24315a302edd9153a01f753c3cba3d765e8eafac" +dependencies = [ + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.1.1+zstd.1.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aeec9eaf2dffbbd09201e23bd0ffcbaa33bb8e9266a10734fd7ed90a85eca078" +dependencies = [ + "cc", + "pkg-config", +] + [[package]] name = "zune-core" version = "0.5.3" diff --git a/Cargo.toml b/Cargo.toml index b669ad901..1066b71b7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -57,6 +57,14 @@ quick-xml = "0.41" # read by crates/io itself, so no image decoding or file access comes with it. gltf = { version = "1.4", default-features = false, features = ["names"] } +# FreeCAD and Rhino import (Apache-2.0, pure Rust apart from zstd; native builds only). +# Pinned: its IR and codec APIs change between minor versions. Open formats only: no default +# features, so cadmpeg's codecs for commercial formats (f3d, sldprt, inventor, catia, creo, nx) +# and its ShapeManager/ACIS `sat` codec are not compiled in. `step` is the writer we restate through. +cadmpeg-core = "=0.6.1" +cadmpeg-ir = "=0.6.1" +cadmpeg-registry = { version = "=0.6.1", default-features = false, features = ["fcstd", "rhino", "step"] } + # fonts (sketch text outlines; MIT OR Apache-2.0, pure Rust) ttf-parser = { version = "0.25", default-features = false, features = ["std"] } diff --git a/README.md b/README.md index 54759d7a9..daaf675a2 100644 --- a/README.md +++ b/README.md @@ -136,7 +136,9 @@ rebuild with no errors, replayed here at 2× speed. 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)). + 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. diff --git a/ROADMAP.md b/ROADMAP.md index 2cae5667b..c9a64dbb7 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -7,7 +7,7 @@ features → parametric timeline) as an open, pure-Rust, agent-drivable applicat | Question | Answer | |---|---| -| Where are we? | **M0 and M13 done; M1, M2, M5–M7, M9, M10, M14 in progress.** Sketch with solver and the full SKETCH create/modify set; extrude, revolve (two sides, symmetric, to object), fillet/chamfer (variable radius, chord length, a radius per edge, corner patches), holes, threads (cosmetic and modelled), patterns, mirror, shell (inside/outside/both), draft, loft, sweep, coil, split body and split face, delete face, construction planes, axes and points; persistent naming of faces and edges; parameters and configurations; components, joints, motion studies, exploded views; sheet metal and a plastic enclosure subset; STEP/IGES/3MF/STL/OBJ/DXF; autosave and crash recovery; desktop and browser (wasm) app, CLI, MCP server. | +| Where are we? | **M0 and M13 done; M1, M2, M5–M7, M9, M10, M14 in progress.** Sketch with solver and the full SKETCH create/modify set; extrude, revolve (two sides, symmetric, to object), fillet/chamfer (variable radius, chord length, a radius per edge, corner patches), holes, threads (cosmetic and modelled), patterns, mirror, shell (inside/outside/both), draft, loft, sweep, coil, split body and split face, delete face, construction planes, axes and points; persistent naming of faces and edges; parameters and configurations; components, joints, motion studies, exploded views; sheet metal and a plastic enclosure subset; STEP/IGES/3MF/STL/OBJ/DXF; FreeCAD/Rhino import; autosave and crash recovery; desktop and browser (wasm) app, CLI, MCP server. | | Features | Every registered command by area — [docs/features.md](docs/features.md) (`cargo xtask features`); registry breadth does not establish workflow or geometric depth | | Reference tests | **82 / 82 parts match** — [docs/oracle.md](docs/oracle.md): public cases in `tests/oracle/` with analytic (61) or FreeCAD-computed (21) expected values, run by CI on every PR. | | Tests | Solver, profiles, kernel booleans/blends/measures, expressions, timeline, persistent naming, file formats and migrations, assemblies, sheet metal, engine end-to-end, hostile-input fuzz over every command and headless UI scenarios. `cargo xtask ci` reports the current passing counts. | @@ -49,7 +49,7 @@ PCB / Package, Render, Animation, Simulation, Manufacture/CAM, Drawings. | 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 | -| M4 | Files: STEP import (done — [docs/step-import.md](docs/step-import.md)), 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 | +| 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; taper handle open), 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 | diff --git a/THIRD-PARTY-LICENSES.txt b/THIRD-PARTY-LICENSES.txt index a1ae0e020..86cbc1afb 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 513 crates below. +SolidCraft (the desktop app, solidcraft-cli and the web app) is built from the 544 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. @@ -48,6 +48,7 @@ bit-vec 0.9.1 (Apache-2.0 OR MIT) bitflags 1.3.2 (MIT/Apache-2.0) bitflags 2.13.2 (MIT OR Apache-2.0) block-buffer 0.10.4 (MIT OR Apache-2.0) +block-buffer 0.12.1 (MIT OR Apache-2.0) block-padding 0.3.3 (MIT OR Apache-2.0) block2 0.5.1 (MIT) block2 0.6.2 (MIT) @@ -59,6 +60,13 @@ bytemuck_derive 1.12.1 (Zlib OR Apache-2.0 OR MIT) byteorder 1.5.0 (Unlicense OR MIT) byteorder-lite 0.1.0 (Unlicense OR MIT) bytes 1.12.1 (MIT) +cadmpeg-codec-freecad 0.6.1 (Apache-2.0) +cadmpeg-codec-rhino 0.6.1 (Apache-2.0) +cadmpeg-codec-step 0.6.1 (Apache-2.0) +cadmpeg-container 0.6.1 (Apache-2.0) +cadmpeg-core 0.6.1 (Apache-2.0) +cadmpeg-ir 0.6.1 (Apache-2.0) +cadmpeg-registry 0.6.1 (Apache-2.0) calloop 0.13.0 (MIT) calloop 0.14.5 (MIT) calloop-wayland-source 0.3.0 (MIT) @@ -74,25 +82,30 @@ codespan-reporting 0.13.1 (Apache-2.0) color 0.3.3 (Apache-2.0 OR MIT) combine 4.6.8 (MIT) concurrent-queue 2.5.0 (Apache-2.0 OR MIT) +const-oid 0.10.2 (Apache-2.0 OR MIT) convert_case 0.4.0 (MIT) core-foundation 0.10.1 (MIT OR Apache-2.0) core-foundation 0.9.4 (MIT OR Apache-2.0) core-foundation-sys 0.8.7 (MIT OR Apache-2.0) core-graphics 0.23.2 (MIT OR Apache-2.0) core-graphics-types 0.1.3 (MIT OR Apache-2.0) +core_detect 1.0.0 (MIT/Apache-2.0) cpufeatures 0.2.17 (MIT OR Apache-2.0) +cpufeatures 0.3.1 (MIT OR Apache-2.0) crc32fast 1.5.2 (MIT OR Apache-2.0) crossbeam-deque 0.8.8 (MIT OR Apache-2.0) crossbeam-epoch 0.9.21 (MIT OR Apache-2.0) crossbeam-utils 0.8.23 (MIT OR Apache-2.0) crunchy 0.2.4 (MIT) crypto-common 0.1.7 (MIT OR Apache-2.0) +crypto-common 0.2.2 (MIT OR Apache-2.0) cursor-icon 1.2.0 (MIT OR Apache-2.0 OR Zlib) dbus 0.9.12 (Apache-2.0/MIT) dbus-secret-service 4.1.0 (MIT OR Apache-2.0) derive_arbitrary 1.5.0 (MIT OR Apache-2.0) derive_more 0.99.20 (MIT) digest 0.10.7 (MIT OR Apache-2.0) +digest 0.11.3 (MIT OR Apache-2.0) dispatch 0.2.0 (MIT) dispatch2 0.3.1 (Zlib OR Apache-2.0 OR MIT) displaydoc 0.2.7 (MIT OR Apache-2.0) @@ -108,6 +121,7 @@ egui-winit 0.36.2 (MIT OR Apache-2.0) egui_glow 0.36.2 (MIT OR Apache-2.0) either 1.19.0 (MIT OR Apache-2.0) emath 0.36.2 (MIT OR Apache-2.0) +encoding_rs 0.8.42 ((Apache-2.0 OR MIT) AND BSD-3-Clause) endi 1.1.1 (MIT) enumflags2 0.7.12 (MIT OR Apache-2.0) enumflags2_derive 0.7.12 (MIT OR Apache-2.0) @@ -166,6 +180,7 @@ hkdf 0.12.4 (MIT OR Apache-2.0) hmac 0.12.1 (MIT OR Apache-2.0) http 1.5.0 (MIT OR Apache-2.0) httparse 1.10.1 (MIT OR Apache-2.0) +hybrid-array 0.4.15 (MIT OR Apache-2.0) iana-time-zone 0.1.65 (MIT OR Apache-2.0) iana-time-zone-haiku 0.1.2 (MIT OR Apache-2.0) icu_collections 2.3.0 (Unicode-3.0) @@ -215,6 +230,7 @@ minisign-verify 0.3.0 (MIT) miniz_oxide 0.8.9 (MIT OR Zlib OR Apache-2.0) miniz_oxide 0.9.1 (MIT OR Zlib OR Apache-2.0) moxcms 0.8.1 (BSD-3-Clause OR Apache-2.0) +multiversion_no_op 1.0.0 (Apache-2.0 OR MIT) naga 30.0.1 (MIT OR Apache-2.0) naga-types 30.0.1 (MIT OR Apache-2.0) ndk 0.9.0 (MIT OR Apache-2.0) @@ -260,6 +276,7 @@ objc2-user-notifications 0.2.2 (MIT) once_cell 1.21.4 (MIT OR Apache-2.0) openssl-probe 0.2.1 (MIT OR Apache-2.0) orbclient 0.3.55 (MIT) +ordered-float 2.10.1 (MIT) ordered-float 5.5.0 (MIT) ordered-stream 0.2.0 (MIT OR Apache-2.0) parking 2.2.1 (Apache-2.0 OR MIT) @@ -315,6 +332,7 @@ rfd 0.17.2 (MIT) ring 0.17.14 (Apache-2.0 AND ISC) robust 1.2.0 (MIT OR Apache-2.0) ron 0.12.2 (MIT OR Apache-2.0) +roxmltree 0.21.1 (MIT OR Apache-2.0) rustc-hash 1.1.0 (Apache-2.0/MIT) rustc-hash 2.1.3 (Apache-2.0 OR MIT) rustix 0.38.44 (Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT) @@ -336,12 +354,16 @@ security-framework-sys 2.17.0 (MIT OR Apache-2.0) self_cell 1.3.0 (Apache-2.0 OR GPL-2.0-only) semver 1.0.28 (MIT OR Apache-2.0) 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_json 1.0.151 (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) +sha1 0.11.0 (MIT OR Apache-2.0) sha2 0.10.9 (MIT OR Apache-2.0) +sha2 0.11.1 (MIT OR Apache-2.0) signal-hook-registry 1.4.8 (MIT OR Apache-2.0) simd-adler32 0.3.10 (MIT) simd_cesu8 1.2.0 (Apache-2.0 OR MIT) @@ -373,9 +395,11 @@ thiserror-impl 2.0.21 (MIT OR Apache-2.0) tiff 0.11.3 (MIT) tinystr 0.8.4 (Unicode-3.0) tokio 1.53.2 (MIT) +toml 1.1.8+spec-1.1.0 (MIT OR Apache-2.0) toml_datetime 1.1.2+spec-1.1.0 (MIT OR Apache-2.0) toml_edit 0.25.15+spec-1.1.0 (MIT OR Apache-2.0) toml_parser 1.1.5+spec-1.1.0 (MIT OR Apache-2.0) +toml_writer 1.1.3+spec-1.1.0 (MIT OR Apache-2.0) tracing 0.1.44 (MIT) tracing-attributes 0.1.31 (MIT) tracing-core 0.1.36 (MIT) @@ -391,6 +415,7 @@ truck-stepio 0.3.0 (Apache-2.0) truck-topology 0.6.0 (Apache-2.0) ttf-parser 0.25.1 (MIT OR Apache-2.0) type-map 0.5.1 (MIT/Apache-2.0) +typed-path 0.12.3 (MIT OR Apache-2.0) typeid 1.0.3 (MIT OR Apache-2.0) typenum 1.20.1 (MIT OR Apache-2.0) uds_windows 1.2.1 (MIT) @@ -506,9 +531,15 @@ zerotrie 0.2.5 (Unicode-3.0) zerovec 0.11.8 (Unicode-3.0) zerovec-derive 0.11.6 (Unicode-3.0) zip 3.0.0 (MIT) +zip 8.6.0 (MIT) zlib-rs 0.6.8 (Zlib) zmij 1.0.23 (MIT) zopfli 0.8.3 (Apache-2.0) +zstd 0.13.3 (MIT) +zstd 0.14.2 (BSD-3-Clause) +zstd-safe 7.3.0 (BSD-3-Clause) +zstd-safe 8.1.0 (BSD-3-Clause) +zstd-sys 2.1.1+zstd.1.5.7 (BSD-3-Clause) zune-core 0.5.3 (MIT OR Apache-2.0 OR Zlib) zune-jpeg 0.5.15 (MIT OR Apache-2.0 OR Zlib) zvariant 4.2.0 (MIT) @@ -548,10 +579,10 @@ pin-project-internal 1.1.13, pin-project-lite 0.2.17, piper 0.2.5, polling 3.11. 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, 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 +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 @@ -815,8 +846,10 @@ IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================================================ -aes 0.8.4, block-buffer 0.10.4, block-padding 0.3.3, cbc 0.1.2, cipher 0.4.4, cpufeatures 0.2.17, -crypto-common 0.1.7, digest 0.10.7, hkdf 0.12.4, hmac 0.12.1, inout 0.1.4, sha1 0.10.7, sha2 0.10.9 +aes 0.8.4, block-buffer 0.10.4, block-buffer 0.12.1, block-padding 0.3.3, cbc 0.1.2, cipher 0.4.4, +const-oid 0.10.2, cpufeatures 0.2.17, cpufeatures 0.3.1, crypto-common 0.1.7, crypto-common 0.2.2, +digest 0.10.7, digest 0.11.3, hkdf 0.12.4, hmac 0.12.1, hybrid-array 0.4.15, inout 0.1.4, sha1 +0.10.7, sha1 0.11.0, sha2 0.10.9, sha2 0.11.1 ================================================================================ Apache License @@ -1057,20 +1090,21 @@ ahash 0.8.12, arbitrary 1.5.0, arrayvec 0.7.8, async-channel 2.5.0, async-execut 0.2.14, async-task 4.7.1, atomic-waker 1.1.2, base64 0.23.1, bitflags 1.3.2, bitflags 2.13.2, blocking 1.7.0, bumpalo 3.20.3, cfg-if 1.0.5, cgl 0.3.2, concurrent-queue 2.5.0, core-foundation 0.10.1, core-foundation 0.9.4, core-foundation-sys 0.8.7, core-graphics 0.23.2, core-graphics-types -0.1.3, crossbeam-deque 0.8.8, crossbeam-epoch 0.9.21, crossbeam-utils 0.8.23, dbus-secret-service -4.1.0, derive_arbitrary 1.5.0, displaydoc 0.2.7, either 1.19.0, equivalent 1.0.2, errno 0.3.14, -euclid 0.22.14, event-listener 5.4.2, event-listener-strategy 0.5.4, fastrand 2.5.0, flate2 1.1.10, -form_urlencoded 1.2.2, futures-lite 2.6.1, gethostname 1.1.0, glow 0.17.0, gltf 1.4.1, gltf-derive -1.4.1, gltf-json 1.4.1, hashbrown 0.16.1, hashbrown 0.17.1, hermit-abi 0.5.3, httparse 1.10.1, idna -1.1.0, idna_adapter 1.2.2, indexmap 2.14.2, itertools 0.13.0, itertools 0.15.0, js-sys 0.3.106, -khronos-egl 6.0.0, lazy_static 1.5.1, linux-raw-sys 0.12.1, linux-raw-sys 0.4.15, lock_api 0.4.14, -log 0.4.34, num 0.4.3, num-bigint 0.4.8, num-complex 0.4.6, num-integer 0.1.47, num-iter 0.1.46, -num-rational 0.4.2, num-traits 0.2.19, once_cell 1.21.4, openssl-probe 0.2.1, ordered-stream 0.2.0, -parking 2.2.1, parking_lot 0.12.5, parking_lot_core 0.9.12, percent-encoding 2.3.2, piper 0.2.5, -plain 0.2.3, png 0.18.1, polling 3.11.0, pollster 0.4.0, pollster 1.0.1, rayon 1.12.0, rayon-core -1.13.0, renderdoc-sys 1.1.0, robust 1.2.0, ron 0.12.2, rustc-hash 1.1.0, rustix 0.38.44, rustix -1.1.5, rustls 0.23.46, rustls-native-certs 0.8.5, scoped-tls 1.0.1, scopeguard 1.2.0, secret-service -4.0.0, security-framework 2.11.1, security-framework 3.7.0, security-framework-sys 2.17.0, +0.1.3, core_detect 1.0.0, crossbeam-deque 0.8.8, crossbeam-epoch 0.9.21, crossbeam-utils 0.8.23, +dbus-secret-service 4.1.0, derive_arbitrary 1.5.0, displaydoc 0.2.7, either 1.19.0, equivalent +1.0.2, errno 0.3.14, euclid 0.22.14, event-listener 5.4.2, event-listener-strategy 0.5.4, fastrand +2.5.0, flate2 1.1.10, form_urlencoded 1.2.2, futures-lite 2.6.1, gethostname 1.1.0, glow 0.17.0, +gltf 1.4.1, gltf-derive 1.4.1, gltf-json 1.4.1, hashbrown 0.16.1, hashbrown 0.17.1, hermit-abi +0.5.3, httparse 1.10.1, idna 1.1.0, idna_adapter 1.2.2, indexmap 2.14.2, itertools 0.13.0, itertools +0.15.0, js-sys 0.3.106, khronos-egl 6.0.0, lazy_static 1.5.1, linux-raw-sys 0.12.1, linux-raw-sys +0.4.15, lock_api 0.4.14, log 0.4.34, num 0.4.3, num-bigint 0.4.8, num-complex 0.4.6, num-integer +0.1.47, num-iter 0.1.46, num-rational 0.4.2, num-traits 0.2.19, once_cell 1.21.4, openssl-probe +0.2.1, ordered-stream 0.2.0, parking 2.2.1, parking_lot 0.12.5, parking_lot_core 0.9.12, +percent-encoding 2.3.2, piper 0.2.5, plain 0.2.3, png 0.18.1, polling 3.11.0, pollster 0.4.0, +pollster 1.0.1, rayon 1.12.0, rayon-core 1.13.0, renderdoc-sys 1.1.0, robust 1.2.0, ron 0.12.2, +roxmltree 0.21.1, rustc-hash 1.1.0, rustix 0.38.44, rustix 1.1.5, rustls 0.23.46, +rustls-native-certs 0.8.5, scoped-tls 1.0.1, scopeguard 1.2.0, secret-service 4.0.0, +security-framework 2.11.1, security-framework 3.7.0, security-framework-sys 2.17.0, signal-hook-registry 1.4.8, simd_cesu8 1.2.0, smallvec 1.16.2, smol_str 0.2.2, stable_deref_trait 1.2.1, syn 1.0.109, tempfile 3.27.0, ttf-parser 0.25.1, unicode-segmentation 1.13.3, unicode-width 0.2.2, url 2.5.8, uuid 1.27.0, wasi 0.11.1+wasi-snapshot-preview1, wasip2 1.0.4+wasi-0.2.12, @@ -1286,7 +1320,8 @@ allocator-api2 0.2.21, async-trait 0.1.92, enumn 0.1.14, glifo 0.2.0, itoa 1.0.1 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, typeid 1.0.3, unicode-ident 1.0.26, utf8-zero 0.8.1 +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 @@ -1778,10 +1813,11 @@ 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, kurbo 0.13.1, 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 +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, +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 ================================================================================ Apache License @@ -2854,6 +2890,36 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +================================================================================ +block-buffer 0.12.1 +================================================================================ + +Copyright (c) 2018-2025 The RustCrypto Project Developers + +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. + ================================================================================ branches 0.3.0, rclite 0.2.8 ================================================================================ @@ -3551,6 +3617,66 @@ 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. +================================================================================ +const-oid 0.10.2, cpufeatures 0.3.1 +================================================================================ + +Copyright (c) 2020-2026 The RustCrypto Project Developers + +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. + +================================================================================ +core_detect 1.0.0 +================================================================================ + +Copyright (c) 2017-2020 The Rust Project Developers + +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. + ================================================================================ cpufeatures 0.2.17 ================================================================================ @@ -3903,6 +4029,36 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +================================================================================ +crypto-common 0.2.2 +================================================================================ + +Copyright (c) 2021-2026 RustCrypto Developers + +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. + ================================================================================ cursor-icon 1.2.0 ================================================================================ @@ -4465,6 +4621,37 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +================================================================================ +digest 0.11.3 +================================================================================ + +Copyright (c) 2017-2025 RustCrypto Developers +Copyright (c) 2017 Artyom Pavlov + +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. + ================================================================================ dlib 0.5.3 ================================================================================ @@ -4737,6 +4924,89 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +================================================================================ +encoding_rs 0.8.42 +================================================================================ + +Copyright © WHATWG (Apple, Google, Mozilla, Microsoft). + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +================================================================================ +encoding_rs 0.8.42 +================================================================================ + +encoding_rs 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. + +This crate includes data derived from the data files supplied +with the WHATWG Encoding Standard, which, when incorporated into +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 ================================================================================ @@ -6872,6 +7142,36 @@ 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. +================================================================================ +hybrid-array 0.4.15 +================================================================================ + +Copyright (c) 2022-2026 The RustCrypto Project Developers + +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. + ================================================================================ iana-time-zone 0.1.65, iana-time-zone-haiku 0.1.2 ================================================================================ @@ -9068,6 +9368,26 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +================================================================================ +multiversion_no_op 1.0.0 +================================================================================ + +Copyright Mozilla Foundation + +Licensed under the Apache License (Version 2.0), or the MIT license, +(the "Licenses") at your option. You may not use this file except in +compliance with one of the Licenses. You may obtain copies of the +Licenses at: + + https://www.apache.org/licenses/LICENSE-2.0 + https://opensource.org/licenses/MIT + +Unless required by applicable law or agreed to in writing, software +distributed under the Licenses is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the Licenses for the specific language governing permissions and +limitations under the Licenses. + ================================================================================ naga 30.0.1, naga-types 30.0.1, wgpu 30.0.1, wgpu-core 30.0.1, wgpu-core-deps-apple 30.0.1, wgpu-core-deps-emscripten 30.0.1, wgpu-core-deps-wasm 30.0.1, wgpu-core-deps-windows-linux-android @@ -9204,7 +9524,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================================================ -ordered-float 5.5.0 +ordered-float 2.10.1, ordered-float 5.5.0 ================================================================================ Copyright (c) 2015 Jonathan Reem @@ -10923,6 +11243,32 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +================================================================================ +roxmltree 0.21.1 +================================================================================ + +The MIT License (MIT) + +Copyright (c) 2018 Yevhenii Reizner + +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. + ================================================================================ rustix 0.38.44, rustix 1.1.5 ================================================================================ @@ -11718,6 +12064,262 @@ consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. +================================================================================ +serde-value 0.7.0 +================================================================================ + +Copyright (c) 2016 arcnmx + +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. + +================================================================================ +serde_spanned 1.1.2, toml 1.1.8+spec-1.1.0, toml_datetime 1.1.2+spec-1.1.0, toml_edit +0.25.15+spec-1.1.0, toml_parser 1.1.5+spec-1.1.0, toml_writer 1.1.3+spec-1.1.0 +================================================================================ + +Copyright (c) Individual contributors + +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. + +================================================================================ +serde_spanned 1.1.2, toml 1.1.8+spec-1.1.0, toml_datetime 1.1.2+spec-1.1.0, toml_parser +1.1.5+spec-1.1.0, toml_writer 1.1.3+spec-1.1.0 +================================================================================ + +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright Individual contributors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + ================================================================================ sha1 0.10.7, sha2 0.10.9 ================================================================================ @@ -11750,6 +12352,39 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +================================================================================ +sha1 0.11.0, sha2 0.11.1 +================================================================================ + +Copyright (c) 2016-2026 The RustCrypto Project Developers +Copyright (c) 2016 Artyom Pavlov +Copyright (c) 2009-2013 Mozilla Foundation +Copyright (c) 2006-2009 Graydon Hoare + +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. + ================================================================================ signal-hook-registry 1.4.8 ================================================================================ @@ -12140,236 +12775,6 @@ 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. -================================================================================ -toml_datetime 1.1.2+spec-1.1.0, toml_edit 0.25.15+spec-1.1.0, toml_parser 1.1.5+spec-1.1.0 -================================================================================ - -Copyright (c) Individual contributors - -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. - -================================================================================ -toml_datetime 1.1.2+spec-1.1.0, toml_parser 1.1.5+spec-1.1.0 -================================================================================ - -Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright Individual contributors - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - ================================================================================ tracing 0.1.44, tracing-attributes 0.1.31, tracing-core 0.1.36 ================================================================================ @@ -13371,36 +13776,6 @@ licensed under the Apache License, Version 2.0 or or the MIT license or , at your option. -================================================================================ -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. - ================================================================================ uuid 1.27.0 ================================================================================ @@ -15079,6 +15454,32 @@ SOFTWARE. Some files in the "tests/data" subdirectory of this repository are under other licences; see files named LICENSE.*.txt for details. +================================================================================ +zip 8.6.0 +================================================================================ + +The MIT License (MIT) + +Copyright (c) 2014 Mathijs van de Nes + +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. + ================================================================================ zlib-rs 0.6.8 ================================================================================ @@ -15309,6 +15710,89 @@ Apache License See the License for the specific language governing permissions and limitations under the License. +================================================================================ +zstd 0.13.3 +================================================================================ + +The MIT License (MIT) +Copyright (c) 2016 Alexandre Bury + +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. + +================================================================================ +zstd 0.14.2, zstd-safe 7.3.0, zstd-safe 8.1.0, zstd-sys 2.1.1+zstd.1.5.7 +================================================================================ + +BSD 3-Clause License + +Copyright (c) 2026, Alexandre Bury + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +================================================================================ +zstd-sys 2.1.1+zstd.1.5.7 +================================================================================ + +The auto-generated bindings are under the 3-clause BSD license: + +BSD License + +For Zstandard software + +Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + * Neither the name Facebook, nor Meta, nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ================================================================================ zune-core 0.5.3, zune-jpeg 0.5.15 ================================================================================ @@ -15376,6 +15860,13 @@ accesskit_winit 0.32.2: Apache-2.0 (https://github.com/AccessKit/accesskit) array-macro 2.1.8: MIT OR Apache-2.0 (https://codeberg.org/xfix/array-macro) block2 0.5.1: MIT (https://github.com/madsmtm/objc2) block2 0.6.2: MIT (https://github.com/madsmtm/objc2) +cadmpeg-codec-freecad 0.6.1: Apache-2.0 (https://github.com/cadmpeg/cadmpeg) +cadmpeg-codec-rhino 0.6.1: Apache-2.0 (https://github.com/cadmpeg/cadmpeg) +cadmpeg-codec-step 0.6.1: Apache-2.0 (https://github.com/cadmpeg/cadmpeg) +cadmpeg-container 0.6.1: Apache-2.0 (https://github.com/cadmpeg/cadmpeg) +cadmpeg-core 0.6.1: Apache-2.0 (https://github.com/cadmpeg/cadmpeg) +cadmpeg-ir 0.6.1: Apache-2.0 (https://github.com/cadmpeg/cadmpeg) +cadmpeg-registry 0.6.1: Apache-2.0 (https://github.com/cadmpeg/cadmpeg) clipboard-win 5.4.1: BSL-1.0 (https://github.com/DoumanAsh/clipboard-win) convert_case 0.4.0: MIT (https://github.com/rutrum/convert-case) dispatch 0.2.0: MIT (http://github.com/SSheldon/rust-dispatch) diff --git a/apps/solidcraft/src/main.rs b/apps/solidcraft/src/main.rs index c2c8cfee1..0a43b95b5 100644 --- a/apps/solidcraft/src/main.rs +++ b/apps/solidcraft/src/main.rs @@ -108,7 +108,7 @@ fn services(cc: &eframe::CreationContext<'_>) -> Services { let future = open_parent .clone() .add_filter( - "Designs, STEP, IGES and meshes", + "Designs, CAD files and meshes", &[ io::DESIGN_EXT, io::LEGACY_DESIGN_EXT, @@ -121,6 +121,10 @@ fn services(cc: &eframe::CreationContext<'_>) -> Services { "iges", "IGS", "IGES", + "FCStd", + "fcstd", + "3dm", + "3DM", "3mf", "3MF", "stl", @@ -136,6 +140,7 @@ fn services(cc: &eframe::CreationContext<'_>) -> Services { .add_filter("SolidCraft design (container or JSON)", &[io::DESIGN_EXT, io::LEGACY_DESIGN_EXT, "json"]) .add_filter("STEP", &["step", "stp", "STEP", "STP"]) .add_filter("IGES", &["igs", "iges", "IGS", "IGES"]) + .add_filter("FreeCAD and Rhino", &["FCStd", "fcstd", "3dm", "3DM"]) .add_filter("Mesh (3MF, STL, OBJ, glTF)", &["3mf", "3MF", "stl", "STL", "obj", "OBJ", "glb", "GLB", "gltf", "GLTF"]) .add_filter("Sketch drawings (DXF, SVG)", &["dxf", "DXF", "svg", "SVG"]) .add_filter("All files", &["*"]) diff --git a/crates/doc/src/format.rs b/crates/doc/src/format.rs index 16a4500ad..284d9bf54 100644 --- a/crates/doc/src/format.rs +++ b/crates/doc/src/format.rs @@ -229,6 +229,10 @@ //! transformation: a link without `coupling` is a plain motion link, as it always was; 0.13.0 //! (which reads up to 22) asks for an update instead of keeping a gear's ratio when its radius //! changes. +//! Also under 23, an Import's `file` can name a FreeCAD `.FCStd` or Rhino `.3dm` file (#1435, +//! read through cadmpeg); its `step` is still the STEP text the file was restated as, so the +//! feature's fields are unchanged and version 22 designs need no transformation; 0.13.x asks +//! for an update before it meets these imports. use serde_json::Value; diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 4424794d7..6a05824d2 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -20,11 +20,11 @@ pub static COMMANDS: &[CommandSpec] = &[ .icon("open") .key("Ctrl+O") .noundo() - .params("path: .solidcraft design, or a .step/.stp/.igs/.3mf/.stl/.obj/.glb/.gltf file (opens as a new design holding the file as a component named after it, as file.insert_step and file.insert_mesh make); up?: z|y for a STEP, IGES or glTF file (see file.insert_step and file.insert_mesh); names?: solid|product|instance for a STEP or IGES file (see file.insert_step)"), + .params("path: .solidcraft design, or a .step/.stp/.igs/.fcstd/.3dm/.3mf/.stl/.obj/.glb/.gltf file (STEP, IGES, FreeCAD, Rhino, 3MF, STL, OBJ or glTF; opens as a new design holding the file as a component named after it, as file.insert_step and file.insert_mesh make); up?: z|y for a STEP, IGES, FreeCAD, Rhino or glTF file (see file.insert_step and file.insert_mesh); names?: solid|product|instance for a STEP, IGES, FreeCAD or Rhino file (see file.insert_step)"), CommandSpec::new("file.insert_step", "Insert STEP", insert_step) .at("SOLID", "INSERT") .icon("import") - .params("path: .step/.stp 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)"), CommandSpec::new("file.insert_mesh", "Insert Mesh", insert_mesh) .at("SOLID", "INSERT") .icon("import") @@ -215,7 +215,7 @@ fn insert_step(s: &mut Session, p: &Value) -> Result { let cmd = "file.insert_step"; let path = path_arg(p, cmd)?; if !solidcraft_io::is_step_path(path) { - return Err(bad(cmd, "only STEP files (.step, .stp) can be inserted")); + 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) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 8e1883281..c39a51488 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -314,6 +314,8 @@ mod loft_cut; mod loft_ring; mod loft_spacing; mod mirror_planes; +#[cfg(not(target_arch = "wasm32"))] +mod native_cad_import; mod path_scope; mod primitive_points; mod rim_cut; diff --git a/crates/engine/src/tests/native_cad_import.rs b/crates/engine/src/tests/native_cad_import.rs new file mode 100644 index 000000000..0e0b2ce41 --- /dev/null +++ b/crates/engine/src/tests/native_cad_import.rs @@ -0,0 +1,94 @@ +//! FreeCAD and Rhino files (read through cadmpeg) go the same way as STEP files: a new rigid +//! component named after the file (#1426), with the `up` and `names` options (#1312). + +use serde_json::{Value, json}; + +use super::run; +use crate::*; + +const BLOCK_FCSTD: &[u8] = include_bytes!("../../../io/src/native_cad/fixtures/block.FCStd"); +const BLOCK_3DM: &[u8] = include_bytes!("../../../io/src/native_cad/fixtures/block.3dm"); + +/// `bytes` saved as `name` in a fresh temp directory. +fn file(tag: &str, name: &str, bytes: &[u8]) -> (std::path::PathBuf, String) { + let dir = std::env::temp_dir().join(format!("solidcraft-native-cad-{tag}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join(name); + std::fs::write(&path, bytes).unwrap(); + (dir, path.to_string_lossy().to_string()) +} + +fn extent(s: &Session) -> ([f64; 3], [f64; 3]) { + let b = crate::view::bounds(s); + ([b.min.x, b.min.y, b.min.z], [b.max.x, b.max.y, b.max.z]) +} + +fn near(a: [f64; 3], b: [f64; 3]) -> bool { + a.iter().zip(&b).all(|(x, y)| (x - y).abs() < 1e-6) +} + +fn volume(s: &mut Session) -> f64 { + run(s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64().unwrap() +} + +fn body_names(s: &Session) -> Vec { + s.model.state().bodies.iter().map(|b| b.name.clone()).collect() +} + +#[test] +fn freecad_and_rhino_files_come_in_as_a_component_named_after_the_file() { + for (tag, name, bytes) in [("fc", "block.FCStd", BLOCK_FCSTD), ("rh", "block.3dm", BLOCK_3DM)] { + let (dir, path) = file(tag, name, bytes); + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 5, "corner": [100, 0, 0]})); + let r = run(&mut s, "file.insert_step", json!({"path": path})); + assert_eq!(r["component_name"], "block", "{name}: {r}"); + let feature = r["feature"].as_u64().unwrap(); + assert_eq!(s.doc.feature(feature).unwrap().kind.type_name(), "BaseFeature", "{name}"); + assert_eq!(s.doc.feature(feature).unwrap().component, r["component"].as_u64().unwrap(), "{name}"); + assert!((volume(&mut s) - (6000.0 + 125.0)).abs() < 1e-6, "{name}"); + // Rhino keeps the object's name; cadmpeg leaves FreeCAD's label out, so it is the file's. + assert!(body_names(&s).iter().any(|n| n == "Block" || n == "block"), "{name}: {:?}", body_names(&s)); + assert_eq!(s.active_component, 0, "{name}: the active component is unchanged"); + + // As written the block spans 10 × 20 × 30; up: y stands it up, (x, y, z) → (x, -z, y). + let mut d = Session::default(); + let r = run(&mut d, "doc.open", json!({"path": path})); + assert_eq!((r["features"].clone(), r["component_name"].clone()), (json!(1), json!("block")), "{name}: {r}"); + assert!(near(extent(&d).1, [10.0, 20.0, 30.0]), "{name}: {:?}", extent(&d)); + let mut d = Session::default(); + let r = run(&mut d, "file.insert_step", json!({"path": path, "up": "y"})); + assert_eq!(r["stand_up"], r["occurrence"], "{name}: {r}"); + let (lo, hi) = extent(&d); + assert!(near(lo, [0.0, -30.0, 0.0]) && near(hi, [10.0, 0.0, 20.0]), "{name}: stood up: {lo:?} {hi:?}"); + + // Every names choice is taken, and the body is named something. + for names in ["solid", "product", "instance"] { + let mut d = Session::default(); + run(&mut d, "file.insert_step", json!({"path": path, "names": names})); + let got = body_names(&d); + assert!(got.len() == 1 && !got[0].is_empty(), "{name} names={names}: {got:?}"); + } + let _ = std::fs::remove_dir_all(&dir); + } +} + +/// A broken file is refused with a message naming it, and the design is left as it was. +#[test] +fn a_broken_freecad_or_rhino_file_is_refused_cleanly() { + let mut cut = BLOCK_FCSTD[..BLOCK_FCSTD.len() / 2].to_vec(); + cut.extend_from_slice(b"garbage"); + for (tag, name, bytes) in + [("bad-fc", "broken.FCStd", cut.as_slice()), ("bad-rh", "broken.3dm", &BLOCK_3DM[..200]), ("acis", "cube.sat", b"700 0 1 0\n")] + { + let (dir, path) = file(tag, name, bytes); + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 5})); + let before = s.doc.clone(); + let e: Result = s.execute("file.insert_step", &json!({"path": path})); + let e = e.expect_err(name).to_string(); + assert!(!e.contains("internal"), "{name}: a clean error, not a caught panic: {e}"); + assert_eq!(s.doc, before, "{name}: the design is unchanged"); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index fc9a7030d..7afd3eebc 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "solidcraft-io" -description = "SolidCraft file formats: designs (JSON), STL, OBJ, STEP, 3MF and glTF" +description = "SolidCraft file formats: designs (JSON), STL, OBJ, STEP, IGES, 3MF and glTF, and FreeCAD/Rhino import" version.workspace = true edition.workspace = true license.workspace = true @@ -19,3 +19,9 @@ gltf = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } sha2 = { workspace = true } + +# FreeCAD and Rhino import. Not in the browser build: it compiles the zstd C library. +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +cadmpeg-core = { workspace = true } +cadmpeg-ir = { workspace = true } +cadmpeg-registry = { workspace = true } diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 8d1db8e96..be8ae3be7 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -1,8 +1,8 @@ //! File formats. Designs use JSON or versioned containers (`.solidcraft`); the authoritative //! document rebuilds on load and optional display caches remain provisional. Bodies export -//! as STL (binary or ASCII), OBJ, STEP and 3MF, and assemblies as URDF ([`urdf()`]); STEP -//! files import as a base feature (see [`step_import_feature`]), 3MF and STL files as mesh bodies -//! (see [`mesh_import_feature`]). +//! as STL (binary or ASCII), OBJ, STEP and 3MF, and assemblies as URDF ([`urdf()`]); STEP, IGES, +//! FreeCAD and Rhino files import as a base feature (see [`step_import_feature`]), 3MF and +//! STL files as mesh bodies (see [`mesh_import_feature`]). #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] @@ -18,6 +18,8 @@ pub use design::{ write_design_container_with_thumbnail, }; mod legacy_dir; +mod native_cad; +pub use native_cad::{NATIVE_CAD_EXTS, is_native_cad_path, native_cad_to_step}; pub mod safe_write; mod sketch2d; mod svg; @@ -78,13 +80,14 @@ pub type Result = std::result::Result; /// Largest STEP file we read. pub const MAX_STEP_BYTES: usize = 512 << 20; -/// Is this a CAD exchange file read as an Import base feature: STEP (`.step` / `.stp`) or IGES -/// (`.igs` / `.iges`), any case? +/// Is this a CAD file read as an Import base feature: STEP (`.step` / `.stp`), IGES +/// (`.igs` / `.iges`) or a format read through cadmpeg ([`is_native_cad_path`]), any case? pub fn is_step_path(path: &str) -> bool { std::path::Path::new(path) .extension() .and_then(|e| e.to_str()) .is_some_and(|e| ["step", "stp", "igs", "iges"].iter().any(|x| e.eq_ignore_ascii_case(x))) + || is_native_cad_path(path) } /// Is this an IGES file name (`.igs` / `.iges`, any case)? @@ -162,11 +165,14 @@ pub fn step_import_feature_named(bytes: &[u8], file: &str, names: StepNames) -> if bytes.len() > MAX_STEP_BYTES { return Err(IoError::Invalid(format!("STEP file too large ({} MB, limit {} MB)", bytes.len() >> 20, MAX_STEP_BYTES >> 20))); } - // STEP is 7-bit text with escapes; tolerate stray 8-bit bytes. IGES is restated as STEP - // (the feature keeps that STEP text). - let text = String::from_utf8_lossy(bytes).into_owned(); - let (text, iges_warnings) = - if is_iges_path(file) { solidcraft_kernel::iges_to_step(&text).map_err(IoError::Invalid)? } else { (text, Vec::new()) }; + // STEP is 7-bit text with escapes; tolerate stray 8-bit bytes. IGES and the cadmpeg formats + // are restated as STEP (the feature keeps that STEP text). + 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(); + 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)?; let stem = std::path::Path::new(file) .file_stem() diff --git a/crates/io/src/native_cad.rs b/crates/io/src/native_cad.rs new file mode 100644 index 000000000..97aa26d50 --- /dev/null +++ b/crates/io/src/native_cad.rs @@ -0,0 +1,156 @@ +//! Other CAD formats read through [cadmpeg](https://github.com/cadmpeg/cadmpeg): FreeCAD +//! `.FCStd` and Rhino `.3dm`. cadmpeg decodes the file into its neutral model and writes that as +//! STEP, which the Import feature then reads and keeps like any STEP file. +//! +//! Only codecs for open formats are compiled in (the workspace enables cadmpeg-registry's +//! `fcstd`, `rhino` and `step` features alone). cadmpeg's codecs for commercial formats, and its +//! `sat` codec (a ShapeManager stream decoder that reads ACIS as one dialect), are not built. +//! +//! This module is the importer seam: the one place cadmpeg is called, returning STEP text plus +//! warnings. A cadmpeg-based STEP reader could be added here later and chosen by a setting, to +//! compare with our own STEP reader, without changing that reader. +//! +//! cadmpeg is not built for the browser (it compiles the zstd C library); there these formats +//! return "not supported in the browser yet". + +/// File extensions read through cadmpeg (lower case). +pub const NATIVE_CAD_EXTS: [&str; 2] = ["fcstd", "3dm"]; + +/// Is this a FreeCAD or Rhino file name (any case)? +pub fn is_native_cad_path(path: &str) -> bool { + std::path::Path::new(path).extension().and_then(|e| e.to_str()).is_some_and(|e| NATIVE_CAD_EXTS.iter().any(|x| e.eq_ignore_ascii_case(x))) +} + +/// Restate a FreeCAD or Rhino file (`file` is its name) as STEP text, with the losses +/// and warnings cadmpeg reported. Panics inside cadmpeg become errors. +#[cfg(not(target_arch = "wasm32"))] +pub fn native_cad_to_step(bytes: &[u8], file: &str) -> Result<(String, Vec), String> { + let name = std::path::Path::new(file).file_name().map(|s| s.to_string_lossy().to_string()).unwrap_or_else(|| file.to_string()); + solidcraft_kernel::guard("cadmpeg import", || convert::to_step(&name, bytes).map_err(solidcraft_kernel::KernelError::Invalid)).map_err( + |e| match e { + solidcraft_kernel::KernelError::Invalid(m) => m, + e => e.to_string(), + }, + ) +} + +/// Restate a FreeCAD or Rhino file as STEP: not available in the browser yet. +#[cfg(target_arch = "wasm32")] +pub fn native_cad_to_step(_bytes: &[u8], file: &str) -> Result<(String, Vec), String> { + Err(format!("{file}: not supported in the browser yet (FreeCAD and Rhino files open in the desktop app)")) +} + +#[cfg(not(target_arch = "wasm32"))] +mod convert { + use std::io::Cursor; + + use cadmpeg_core::decode::{DecodeArena, DecodeContext, DecodeMode, DecodePolicy, ResourceLimits, View}; + use cadmpeg_ir::codec::write::{EncodeInput, target::TargetRequest}; + use cadmpeg_ir::codec::{DecodeFailure, DecodeOptions, DecodeResult}; + use cadmpeg_ir::validate::validate_neutral_for_decode; + use cadmpeg_registry::{DETECTION_PREFIX_LEN, Format, InputCatalog, ResolveSourceError, ResolvedSource, build_encoder, forced_input}; + + /// The codecs we accept (cadmpeg codec ids), whatever else the registry recognises. + const ACCEPTED: [&str; 2] = ["fcstd", "rhino"]; + + /// Caps for hostile input: cadmpeg's tight `service` profile, with our STEP size limit. + pub(super) fn policy() -> DecodePolicy { + DecodePolicy { + mode: DecodeMode::Salvage, + limits: ResourceLimits { max_input_bytes: crate::MAX_STEP_BYTES as u64, ..ResourceLimits::service() }, + } + } + + /// Decode `bytes` (a file called `name`, extension `ext`) with the codec cadmpeg detects from + /// the bytes, else the one the extension names, if it is one of `accepted`. Returns the codec id + /// and the decoded model. + pub(super) fn decode(name: &str, ext: &str, bytes: &[u8], accepted: &[&str]) -> Result<(String, DecodeResult), String> { + let policy = policy(); + let catalog = InputCatalog::with_builtins(); + let codec = { + let arena = DecodeArena::new(); + let (ctx, _) = DecodeContext::from_root_bytes(&[], &arena, &policy).map_err(|e| e.to_string())?; + let prefix = bytes.get(..DETECTION_PREFIX_LEN).unwrap_or(bytes); + let resolved = catalog.resolve_seekable_source(&ctx, View::over_retained(prefix), &mut Cursor::new(bytes), None); + let resolved = match resolved { + Ok(ResolvedSource::Unrecognized | ResolvedSource::Cadir) | Err(ResolveSourceError::Ambiguous(_)) => { + match forced_input(ext).map_err(|e| e.to_string())? { + Some(forced) => catalog.resolve_source(&ctx, View::over_retained(prefix), Some(forced)), + None => Ok(ResolvedSource::Unrecognized), + } + } + other => other, + }; + ctx.finish_session().map_err(|e| e.to_string())?; + match resolved.map_err(|e| format!("{name}: {e}"))? { + ResolvedSource::Native { codec, .. } => codec, + _ => return Err(format!("{name}: unrecognised file contents")), + } + }; + let format = codec.id().as_str().to_string(); + if !accepted.contains(&format.as_str()) { + return Err(format!("{name}: {format} files are not supported (FreeCAD .FCStd and Rhino .3dm only)")); + } + + // Decode in memory under the caps. + let options = DecodeOptions { container_only: false, policy }; + let decoded = codec.decode(&mut Cursor::new(bytes), &options).map_err(|e| match e { + DecodeFailure::Codec(e) => format!("{name}: could not read this {format} file: {e}"), + other => format!("{name}: {other}"), + })?; + Ok((format, decoded)) + } + + pub(super) fn to_step(name: &str, bytes: &[u8]) -> Result<(String, Vec), String> { + let ext = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).unwrap_or_default(); + if !super::NATIVE_CAD_EXTS.contains(&ext.as_str()) { + return Err(format!("{name}: not supported (FreeCAD .FCStd and Rhino .3dm only)")); + } + let (format, decoded) = decode(name, &ext, bytes, &ACCEPTED)?; + let policy = policy(); + let (ir, report, fidelity) = decoded.into_parts(); + if !report.geometry_transferred() { + return Err(format!("{name}: no geometry could be read from this {format} file")); + } + let mut warnings: Vec = report.losses.iter().map(|l| format!("{}: {}", l.code, l.message)).collect(); + + // Validate the neutral model, as cadmpeg's own conversion does. + let arena = DecodeArena::new(); + let ctx = DecodeContext::for_loaded_input(&arena, &policy, bytes.len() as u64).map_err(|e| e.to_string())?; + let validation = validate_neutral_for_decode(&ctx, &ir, Vec::new()).map_err(|e| e.to_string())?; + ctx.finish_session().map_err(|e| e.to_string())?; + warnings.extend(validation.findings.iter().map(|f| format!("{}: {}", f.severity, f.message))); + if !validation.is_ok() { + return Err(format!("{name}: the {format} model is invalid ({} errors)", validation.error_count())); + } + + // Write it as STEP AP214. + let plan = build_encoder(Format::Step) + .plan(EncodeInput::new(&ir, Some(&fidelity)), TargetRequest::Explicit("ap214")) + .map_err(|e| format!("{name}: could not restate as STEP: {e}"))?; + let losses = &plan.report().losses; + if losses.iter().any(|l| l.code.to_string() == "step/export.no-exportable-solids") { + return Err(format!("{name}: this {format} file has no solids that can be imported")); + } + warnings.extend(losses.iter().map(|l| format!("{}: {}", l.code, l.message))); + let mut out = Vec::new(); + plan.write_to(&mut out).map_err(|e| e.to_string())?; + let step = String::from_utf8(out).map_err(|e| e.to_string())?; + Ok((super::name_unnamed_products(step, name), warnings)) + } +} + +/// cadmpeg's STEP writer calls a product it has no name for `cadmpeg_model`; name it after the +/// file instead (as plain STEP text: letters, digits, spaces, `-`, `_` and `.` only). +#[cfg(not(target_arch = "wasm32"))] +fn name_unnamed_products(step: String, file: &str) -> String { + const PLACEHOLDER: &str = "'cadmpeg_model'"; + let stem: String = std::path::Path::new(file) + .file_stem() + .map(|s| s.to_string_lossy().chars().filter(|c| c.is_ascii_alphanumeric() || matches!(c, ' ' | '-' | '_' | '.')).collect()) + .unwrap_or_default(); + if stem.trim().is_empty() || !step.contains(PLACEHOLDER) { step } else { step.replace(PLACEHOLDER, &format!("'{stem}'")) } +} + +#[cfg(test)] +mod tests; diff --git a/crates/io/src/native_cad/fixtures/block.3dm b/crates/io/src/native_cad/fixtures/block.3dm new file mode 100644 index 0000000000000000000000000000000000000000..715f1f05a5d1f9651870f2db62392521eba4800d GIT binary patch literal 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pz9vy>&7z8OF@-YQ-3SDNsH5*N8t{%QAKAJf?PTR4)IESdY3RW=C`Abg| zN+tCjh{et{qc2L7*DM-_ouJb5$t-y5LWdXqO%AOZ|E&*RCaG_mPSGnW{s4B(b-)_N F{{rbkf#?7L literal 0 HcmV?d00001 diff --git a/crates/io/src/native_cad/fixtures/block.FCStd b/crates/io/src/native_cad/fixtures/block.FCStd new file mode 100644 index 0000000000000000000000000000000000000000..9b06266a016f01e67d050acc15008c088acbd716 GIT binary patch literal 2485 zcmZ`*c{J3E9{<@ULb6=4+-${AgR$@XJ|<(&GO{-qGYnZr3&u{021PCs;Wm;mvJ;Vv zG}b6$EJK+n)5UFW@4fTRdGEgSzMnrn=X}ojobO+s^Z6iP9GoHm0B{59g^ozIdfzk} z7XXZ&1^~XFswFn?N<=UwMkPK1{mIkYgKjNymFeNIhcIdY;n;-0i9~jHk1oWUw>C2c z4t`-6xPtP!$CYQSrK9H03+-u~LY1uoG_#SQOWkuxly1I73YM7Vo4M{XY^)~|-Y+ZH zy0$^RUnT__Tbdf6)E-;hiT?p0K2Ja(&7MXHqJ<4 zQ}~80h%17Y5#Pi7K@wrl=GiEzovxe`p)LW-syx8szRJpV2SfDh;=#M|syxmx6iiwF zAWMDK@kyvYsX{l#4BjlWI+2+G90?t|d?fJJ9^*D%qy?|8h_N3jmi5YNf6Fwv;$W0G zS=Jk}-1ZieTzd8vd#}$&s6C#Vqhv*}5IEhMeB9e^det&?aJPstR*(n5^%LT;%aW-3 zWCnh%qx^!saKmZ=MUD4J__5N<=Gm|o@&PDIfcpBESoo)P0@xFyEy?fs{=D*{T}9%~ zu@b@g=*9`ky;Vp_aT&q4NgNo+-cB4PJ5}U-nj7BS;|{SjVfp2qWF${`kHQ0BP9i)3 zSLAaUnO~}Ub6y{F`ege$zwt>YcSnv2g06v{-UKG{T3rp&%?gM=QMnP~D6 zr+#=?EZ+?q+=rRJ%iSE)yk(>4vLk%8ny)dk7OdYh=L_z!+MyaGg`@+|$ierID{x!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&HA2c5{tm$)?rRTPk;p>z5Ah(4UJ5gtqauU%eto8WIB< z;*Kpx^lh58-T#q~Ph{vI{;LiqW8c*;umb>H4gdsx)`2-18yK$Qg7S|HRtdmGE?z`p z=hZ}#nIy)FHc^Q=&%?NA#%u{KG+m6gG{{b~ePL7c<4|vgOVD5VnkJ{aa(30dt!Rp# zag=}c^N|eEJLkG`8<)PHO|%xNS<)$>aO`F zeIJDMuPyHP(kPZIo<_HL_ZTm)q*n(;diiyXQ0JXzF2I)O-^M_0=$1X6g+PQmjg7G- z*~`x#Q_>86pd(8o*?h@Nm=@c0Z^uW6BEOFI=h9)a}!q+RN~k9jcM$btXdQ>B>M=8 zSUJ5GTVa}0N~0P~rl*CCuR4E|yG zSU*Ku{rq!Ht)(I)hx8+Llij7ioRcw}sSob333nM~WJISUojhG){ARx;hn1Y(PZC(2%lG^} z5TnZ_Xvwc)bdmBNL6xAtP^1i>)S%xML(kmbXEs-RO?&6IU9VbhGBw$v9XJA z{QqV2GY$W|mK*<||J+G`cm6#@|MCGq%MAh0|3nG_> = (0..good.len()).step_by((good.len() / 60).max(1)).map(|n| good[..n].to_vec()).collect(); + for i in (0..good.len()).step_by((good.len() / 80).max(1)) { + let mut b = good.to_vec(); + b[i] ^= 0x5a; + cases.push(b); + let mut b = good.to_vec(); + b[i] = 0xff; + cases.push(b); + } + let mut tail = good.to_vec(); + tail.extend((0..4096u32).map(|i| (i.wrapping_mul(2_654_435_761) >> 24) as u8)); + cases.push(tail); + cases.push(good.iter().rev().copied().collect()); + for (i, bytes) in cases.iter().enumerate() { + let r = std::panic::catch_unwind(|| crate::step_import_feature(bytes, name)); + assert!(r.is_ok(), "{name}: case {i} panicked"); + } + } +} + +/// cadmpeg decodes under its tight `service` caps, with our STEP size limit on the input. +#[test] +fn decoding_is_capped() { + let limits = convert::policy().limits; + let service = cadmpeg_core::decode::ResourceLimits::service(); + assert_eq!(limits.max_input_bytes, crate::MAX_STEP_BYTES as u64); + assert_eq!(cadmpeg_core::decode::ResourceLimits { max_input_bytes: service.max_input_bytes, ..limits }, service); +} + +/// A FreeCAD archive whose Document.xml inflates past the per-entry cap (a ZIP bomb, 300 MB of +/// zeros in a few hundred KB) is refused. +#[test] +fn a_zip_bomb_is_refused() { + use std::io::Write; + let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + zip.start_file("Document.xml", zip::write::SimpleFileOptions::default().large_file(true)).unwrap(); + let zeros = vec![0u8; 1 << 20]; + for _ in 0..300 { + zip.write_all(&zeros).unwrap(); + } + let bytes = zip.finish().unwrap().into_inner(); + assert!(bytes.len() < 2 << 20, "{} bytes", bytes.len()); + assert!(native_cad_to_step(&bytes, "bomb.FCStd").is_err()); +} diff --git a/crates/ui-egui/src/file_load.rs b/crates/ui-egui/src/file_load.rs index 6c37a4725..49462e5e2 100644 --- a/crates/ui-egui/src/file_load.rs +++ b/crates/ui-egui/src/file_load.rs @@ -125,11 +125,15 @@ const STAGED_THUMBNAIL_TRIANGLES: usize = 1_000_000; /// How long a frame spends on a staged STEP import. const STAGED_FRAME_MS: f64 = 30.0; -/// Files read in stages: STEP (not IGES, which is first restated as STEP) to insert or open. +/// Files read in stages: STEP (not IGES, FreeCAD or Rhino, which are first restated as STEP) to +/// insert or open. #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] fn staged_kind(request: &Request) -> bool { let p = &request.path; - matches!(request.kind, Kind::Insert | Kind::Open) && solidcraft_engine::io::is_step_path(p) && !solidcraft_engine::io::is_iges_path(p) + matches!(request.kind, Kind::Insert | Kind::Open) + && solidcraft_engine::io::is_step_path(p) + && !solidcraft_engine::io::is_iges_path(p) + && !solidcraft_engine::io::is_native_cad_path(p) } impl Running { diff --git a/docs/book/src/guide/files.md b/docs/book/src/guide/files.md index 990719fef..d2c2900dc 100644 --- a/docs/book/src/guide/files.md +++ b/docs/book/src/guide/files.md @@ -6,6 +6,7 @@ | `.json` (self-contained plain JSON design) | yes | yes | | STEP (AP203, AP214, AP242) | solids, assemblies, units, names, colours | AP242 with names, colours and the component tree | | IGES 5.3 | manifold solids, or trimmed surfaces sewn into solids | manifold solids with names and colours | +| FreeCAD `.FCStd`, Rhino `.3dm` | solids, through cadmpeg (desktop app only) | | | 3MF, STL, OBJ | mesh bodies | yes | | glTF 2.0 (`.glb`, `.gltf` with its `.bin` files) | mesh bodies in the node tree's components, materials as appearances | | | 3MF with face tags | as 3MF | each triangle tagged with its B-rep face, exact coordinates | @@ -13,7 +14,7 @@ | DXF, SVG | into a sketch | sketches and flat patterns as DXF | | PNG, JPEG | canvases and decals | | -Opening a STEP or IGES file creates a design with the file's bodies as a base feature, and +Opening a STEP, IGES, FreeCAD or Rhino file creates a design with the file's bodies as a base feature, and inserting one adds them to the current design. Later features build on them. Mesh bodies render, measure, move and export, but solid features need B-rep bodies. diff --git a/docs/step-import.md b/docs/step-import.md index 019722f25..3dcca34d1 100644 --- a/docs/step-import.md +++ b/docs/step-import.md @@ -39,3 +39,9 @@ display on the resulting body. ## IGES IGES 5.3 files (`.igs`/`.iges`) open, insert and drop the same way: `crates/kernel/src/iges_in.rs` (written from the published specification) restates the file as STEP and the STEP reader reads it, so the feature holds STEP text. Read: manifold solid B-reps (186) with their shells, faces, loops, edge and vertex lists; trimmed (144) and bounded (143) surfaces, and bare B-spline patches, sewn into a solid by their shared edges (an open body when they do not close); lines, circular arcs, ellipses, composite curves, rational B-spline curves; planes (108, 190), cylinders, cones, spheres, tori, rational B-spline surfaces, surfaces of revolution and tabulated cylinders; transformation matrices; units; colours (314 and the predefined numbers); body names (name properties, else labels). Not read yet: ruled and offset surfaces, curves on surfaces given only in parameter space. Export (`file.export` to `.igs`) writes each body as a manifold solid B-rep on the same surfaces a STEP export uses, with its name and colour. + +## FreeCAD and Rhino + +FreeCAD `.FCStd` and Rhino `.3dm` files open, insert and drop the same way, in the desktop app and the CLI. They are read with [cadmpeg](https://github.com/cadmpeg/cadmpeg) (Apache-2.0, `crates/io/src/native_cad.rs`): cadmpeg detects the format from the bytes, decodes it into its neutral model under resource caps, checks that model and writes it as STEP AP214, which the STEP reader then reads. The feature holds that STEP text, so the design reopens without the original file. The file's solids come in; its feature history, sketches and parameters do not. Losses cadmpeg reports become warnings on the feature, and a file without an importable solid is refused with a message. cadmpeg runs inside the panic guard. How much of a file is read follows cadmpeg's support for that format ([format support](https://github.com/cadmpeg/cadmpeg/blob/main/docs/format-support.md)). + +Only codecs for open formats are compiled in: the workspace turns off cadmpeg's default features and enables `fcstd`, `rhino` and `step` (the writer). cadmpeg's codecs for commercial CAD formats are not built, and neither is its `sat` codec, which decodes ShapeManager streams with ACIS as one dialect, so ACIS `.sat`/`.sab` files are not read yet. `crates/io/src/native_cad.rs` is the one place cadmpeg is called; a cadmpeg-based STEP reader could be added there later behind a setting, to compare with the STEP reader above without changing it. The browser app does not read these formats yet: cadmpeg compiles the zstd C library, which the wasm build leaves out. diff --git a/xtask/src/assets.rs b/xtask/src/assets.rs index e2467f9da..9d03f9ef8 100644 --- a/xtask/src/assets.rs +++ b/xtask/src/assets.rs @@ -30,6 +30,8 @@ const ASSET_EXT: &[&str] = &[ "step", "stp", "obj", + "fcstd", + "3dm", ]; fn walk(dir: &Path, root: &Path, out: &mut Vec) -> Result<(), String> { From 845f4913cf1ee24bf2a7081432d9c9b8bc5e1611 Mon Sep 17 00:00:00 2001 From: selune <35337584+0xlillith@users.noreply.github.com> Date: Fri, 16 Oct 2026 01:39:30 +0200 Subject: [PATCH 18/92] render: add opaque CPU sampling and bounded mip chains (#1459) Co-Authored-By: selune <0xlillith@users.noreply.github.com> Co-Authored-By: Claude Sonnet 5.5 --- crates/render/src/lib.rs | 1 + crates/render/src/texture_sampling.rs | 95 +++++++++ crates/render/src/texture_sampling/mips.rs | 191 ++++++++++++++++++ .../render/src/texture_sampling/mips/tests.rs | 115 +++++++++++ crates/render/src/texture_sampling/tests.rs | 94 +++++++++ docs/render-texture-mips.md | 69 +++++++ docs/render-texture-sampling.md | 47 +++++ 7 files changed, 612 insertions(+) create mode 100644 crates/render/src/texture_sampling.rs create mode 100644 crates/render/src/texture_sampling/mips.rs create mode 100644 crates/render/src/texture_sampling/mips/tests.rs create mode 100644 crates/render/src/texture_sampling/tests.rs create mode 100644 docs/render-texture-mips.md create mode 100644 docs/render-texture-sampling.md diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 9a1af147d..126ecf9c5 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -16,6 +16,7 @@ pub mod surface; pub mod texture_input; pub mod texture_interpolation; pub mod texture_lod; +pub mod texture_sampling; pub use backend::{ Availability, BackendDescriptor, BackendId, ExecutorDescriptor, ExecutorId, MAX_RENDER_ID_BYTES, RenderFeature, RenderFormat, RenderLimits, diff --git a/crates/render/src/texture_sampling.rs b/crates/render/src/texture_sampling.rs new file mode 100644 index 000000000..72efd4616 --- /dev/null +++ b/crates/render/src/texture_sampling.rs @@ -0,0 +1,95 @@ +//! Allocation-free periodic reference sampling of already normalized, linear RGBA. +//! No decoding, transfer function, normal interpretation or renderer capability is implied. + +use crate::texture_input::MAX_TEXTURE_EDGE; + +pub mod mips; + +/// CPU reference bound: beyond this, fractional repeat precision is deliberately refused. +/// This is not a GPU/f32 coordinate precision guarantee. +pub const MAX_REPEAT_COORDINATE: f64 = 1_048_576.0; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SamplingError { + Dimensions, + Length, + Values, + Coordinates, +} +impl std::fmt::Display for SamplingError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::Dimensions => "texture dimensions must be positive and at most 2048", + Self::Length => "texture storage must be exactly width * height * 4 floats", + Self::Values => "normalized texture channels must be finite and in [0, 1]", + Self::Coordinates => "repeat coordinates must be finite and within the CPU reference bound", + }) + } +} +impl std::error::Error for SamplingError {} + +/// Validated borrowed normalized RGBA. Construction scans the bounded input once; +/// sampling does constant work, without allocations. The caller retains ownership. +#[derive(Clone, Copy, Debug)] +pub struct TextureView<'a> { + rgba: &'a [f32], + width: usize, + height: usize, +} +impl<'a> TextureView<'a> { + pub fn new(rgba: &'a [f32], dimensions: [u32; 2]) -> Result { + let [width, height] = dimensions; + if width == 0 || height == 0 || width > MAX_TEXTURE_EDGE || height > MAX_TEXTURE_EDGE { + return Err(SamplingError::Dimensions); + } + let width = usize::try_from(width).map_err(|_| SamplingError::Dimensions)?; + let height = usize::try_from(height).map_err(|_| SamplingError::Dimensions)?; + let length = width.checked_mul(height).and_then(|n| n.checked_mul(4)).ok_or(SamplingError::Length)?; + if rgba.len() != length { + return Err(SamplingError::Length); + } + if rgba.iter().any(|v| !v.is_finite() || !(0.0..=1.0).contains(v)) { + return Err(SamplingError::Values); + } + Ok(Self { rgba, width, height }) + } + + /// Bilinear level-zero RGB for an explicitly opaque consumer. Alpha is validated + /// but deliberately ignored (even zero-alpha RGB participates). This is NOT + /// transparent compositing or premultiplied-alpha filtering. + /// UV (0,0) is the top-left image boundary, and v increases downwards. Texel + /// centers are ((x+.5)/width, (y+.5)/height). Both axes repeat, without a Y flip. + /// Inputs must already be linear color or linear data; no transfer is applied. + pub fn sample_repeat_opaque(&self, uv: [f64; 2]) -> Result<[f64; 3], SamplingError> { + if uv.iter().any(|v| !v.is_finite() || v.abs() > MAX_REPEAT_COORDINATE) { + return Err(SamplingError::Coordinates); + } + let [u, v] = uv; + let (x0, x1, tx) = axis(u, self.width); + let (y0, y1, ty) = axis(v, self.height); + let mut rgb = [0.0; 3]; + for (channel, output) in rgb.iter_mut().enumerate() { + let a = self.channel(x0, y0, channel)?; + let b = self.channel(x1, y0, channel)?; + let c = self.channel(x0, y1, channel)?; + let d = self.channel(x1, y1, channel)?; + *output = (a * (1.0 - tx) + b * tx) * (1.0 - ty) + (c * (1.0 - tx) + d * tx) * ty; + } + Ok(rgb) + } + + fn channel(&self, x: usize, y: usize, channel: usize) -> Result { + self.rgba.get((y * self.width + x) * 4 + channel).copied().map(f64::from).ok_or(SamplingError::Length) + } +} + +fn axis(coordinate: f64, size: usize) -> (usize, usize, f64) { + // Reduce before scaling: no huge-coordinate multiplication or unbounded index. + let position = coordinate.rem_euclid(1.0) * size as f64 - 0.5; + let lower = position.floor(); + let first = (lower as i64).rem_euclid(size as i64) as usize; + (first, (first + 1) % size, position - lower) +} + +#[cfg(test)] +mod tests; diff --git a/crates/render/src/texture_sampling/mips.rs b/crates/render/src/texture_sampling/mips.rs new file mode 100644 index 000000000..c0bffec10 --- /dev/null +++ b/crates/render/src/texture_sampling/mips.rs @@ -0,0 +1,191 @@ +//! Bounded linear area-filtered mip preparation for opaque CPU reference sampling. +//! Call from the existing preparation host; row cancellation does not yield a browser event loop. +use super::{SamplingError, TextureView}; + +/// Derived pixel storage only, excluding the borrowed base and small level metadata. +pub const MAX_MIP_TAIL_BYTES: usize = 32 * 1024 * 1024; +/// Include this recipe in preparation/cache identity, alongside source/role/policies. +/// V1 means floor-halved linear area filtering, opaque RGB and generated alpha=1. +pub const MIP_RECIPE_ID: &str = "solidcraft.opaque-linear-area-mips/1"; +const MAX_LEVELS: usize = 12; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum MipError { + Budget, + Allocation, + Cancelled, + Lod, + Sampling(SamplingError), +} +impl std::fmt::Display for MipError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Budget => f.write_str("mip tail storage exceeds the admitted budget"), + Self::Allocation => f.write_str("cannot allocate mip tail storage"), + Self::Cancelled => f.write_str("mip preparation cancelled"), + Self::Lod => f.write_str("LOD must be finite and within the prepared level range"), + Self::Sampling(e) => e.fmt(f), + } + } +} +impl std::error::Error for MipError {} +impl From for MipError { + fn from(value: SamplingError) -> Self { + Self::Sampling(value) + } +} + +struct Level { + rgba: Vec, + width: usize, + height: usize, +} +impl Level { + fn view(&self) -> TextureView<'_> { + // Private levels are created only from admitted pixels and convex averages. + // Reuse validation rather than rescan every stored pixel on each sample. + TextureView { rgba: &self.rgba, width: self.width, height: self.height } + } +} + +/// Immutable derived levels; level zero borrows the admitted base without copying it. +/// Generated levels have alpha=1, matching the explicitly opaque RGB sampler. +pub struct MipChain<'a> { + base: TextureView<'a>, + tail: Vec, + tail_bytes: usize, + retained_bytes: usize, +} +impl<'a> MipChain<'a> { + /// Generate all floor-halved levels through 1x1, or return no chain on failure. + /// `max_tail_bytes` bounds derived pixel capacity, not total process memory. + /// Preparation is synchronous and must run in the caller-owned preparation host. + pub fn prepare(base: TextureView<'a>, max_tail_bytes: usize, cancelled: impl Fn() -> bool) -> Result { + if max_tail_bytes > MAX_MIP_TAIL_BYTES { + return Err(MipError::Budget); + } + check_cancel(&cancelled)?; + let required = required_bytes(base.width, base.height)?; + if required > max_tail_bytes { + return Err(MipError::Budget); + } + let mut chain = Self { base, tail: Vec::new(), tail_bytes: 0, retained_bytes: size_of::() }; + chain.tail.try_reserve_exact(MAX_LEVELS - 1).map_err(|_| MipError::Allocation)?; + let metadata_bytes = + chain.tail.capacity().checked_mul(size_of::()).and_then(|n| n.checked_add(size_of::())).ok_or(MipError::Budget)?; + chain.retained_bytes = metadata_bytes; + while chain.level_count() < MAX_LEVELS { + check_cancel(&cancelled)?; + let source = chain.level(chain.level_count() - 1).ok_or(MipError::Budget)?; + if source.width == 1 && source.height == 1 { + break; + } + let width = (source.width / 2).max(1); + let height = (source.height / 2).max(1); + let length = width.checked_mul(height).and_then(|n| n.checked_mul(4)).ok_or(MipError::Budget)?; + let mut rgba = Vec::new(); + rgba.try_reserve_exact(length).map_err(|_| MipError::Allocation)?; + let bytes = rgba.capacity().checked_mul(size_of::()).ok_or(MipError::Budget)?; + let next_bytes = chain.tail_bytes.checked_add(bytes).ok_or(MipError::Budget)?; + if next_bytes > max_tail_bytes { + return Err(MipError::Budget); + } + let retained_bytes = metadata_bytes.checked_add(next_bytes).ok_or(MipError::Budget)?; + for y in 0..height { + check_cancel(&cancelled)?; + for x in 0..width { + let rgb = area_average(source, x, y, width, height)?; + rgba.extend(rgb.map(|v| v as f32)); + rgba.push(1.0); + } + } + check_cancel(&cancelled)?; + chain.tail.push(Level { rgba, width, height }); + chain.tail_bytes = next_bytes; + chain.retained_bytes = retained_bytes; + } + check_cancel(&cancelled)?; + Ok(chain) + } + + pub fn level_count(&self) -> usize { + self.tail.len() + 1 + } + pub fn tail_bytes(&self) -> usize { + self.tail_bytes + } + /// Retained pixel/level Vec capacities plus the chain value. Charge to the + /// existing host pool; borrowed base ownership and allocator overhead are separate. + pub fn retained_bytes(&self) -> usize { + self.retained_bytes + } + /// Borrow a prepared level without allocation or another full-image admission scan. + pub fn level(&self, index: usize) -> Option> { + if index == 0 { Some(self.base) } else { self.tail.get(index - 1).map(Level::view) } + } + pub fn dimensions(&self, index: usize) -> Option<[u32; 2]> { + self.level(index).map(|v| [v.width as u32, v.height as u32]) + } + + /// Explicit LOD only: bilinear within each level, linear between adjacent levels. + /// This does not choose a footprint, provide anisotropy or certify GPU parity. + /// Out-of-range LOD refuses rather than silently clamping to a different policy. + pub fn sample_repeat_lod_opaque(&self, uv: [f64; 2], lod: f64) -> Result<[f64; 3], MipError> { + let last = self.level_count() - 1; + if !lod.is_finite() || lod < 0.0 || lod > last as f64 { + return Err(MipError::Lod); + } + let low = lod.floor() as usize; + let high = (low + 1).min(last); + let t = lod - low as f64; + let a = self.level(low).ok_or(MipError::Lod)?.sample_repeat_opaque(uv)?; + let b = self.level(high).ok_or(MipError::Lod)?.sample_repeat_opaque(uv)?; + let mut rgb = [0.0; 3]; + for ((output, a), b) in rgb.iter_mut().zip(a).zip(b) { + *output = a * (1.0 - t) + b * t; + } + Ok(rgb) + } +} + +fn check_cancel(cancelled: &impl Fn() -> bool) -> Result<(), MipError> { + if cancelled() { Err(MipError::Cancelled) } else { Ok(()) } +} + +fn required_bytes(mut width: usize, mut height: usize) -> Result { + let mut bytes = 0usize; + for _ in 1..MAX_LEVELS { + if width == 1 && height == 1 { + return Ok(bytes); + } + width = (width / 2).max(1); + height = (height / 2).max(1); + let level_bytes = width.checked_mul(height).and_then(|n| n.checked_mul(4 * size_of::())).ok_or(MipError::Budget)?; + bytes = bytes.checked_add(level_bytes).ok_or(MipError::Budget)?; + } + if width == 1 && height == 1 { Ok(bytes) } else { Err(MipError::Budget) } +} + +fn area_average(source: TextureView<'_>, x: usize, y: usize, width: usize, height: usize) -> Result<[f64; 3], MipError> { + // Integer overlap numerators avoid dropping the final row/column at odd sizes. + // All factors are bounded by the validated 2048 edge; at most 3x3 source cells. + let x_start = x * source.width; + let x_end = (x + 1) * source.width; + let y_start = y * source.height; + let y_end = (y + 1) * source.height; + let mut rgb = [0.0; 3]; + for sy in y_start / height..y_end.div_ceil(height) { + let wy = ((sy + 1) * height).min(y_end) - (sy * height).max(y_start); + for sx in x_start / width..x_end.div_ceil(width) { + let wx = ((sx + 1) * width).min(x_end) - (sx * width).max(x_start); + let weight = wx as f64 * wy as f64 / (source.width as f64 * source.height as f64); + for (channel, output) in rgb.iter_mut().enumerate() { + *output += source.channel(sx, sy, channel)? * weight; + } + } + } + Ok(rgb) +} + +#[cfg(test)] +mod tests; diff --git a/crates/render/src/texture_sampling/mips/tests.rs b/crates/render/src/texture_sampling/mips/tests.rs new file mode 100644 index 000000000..417f228a3 --- /dev/null +++ b/crates/render/src/texture_sampling/mips/tests.rs @@ -0,0 +1,115 @@ +use super::*; +use std::cell::Cell; + +fn close(actual: [f64; 3], expected: [f64; 3]) { + for (a, b) in actual.into_iter().zip(expected) { + assert!((a - b).abs() < 1e-7, "{actual:?} != {expected:?}"); + } +} + +#[test] +fn linear_checkerboard_mean_and_fractional_lod() { + let pixels = [0., 0., 0., 0., 1., 1., 1., 1., 1., 1., 1., 1., 0., 0., 0., 0.]; + let base = TextureView::new(&pixels, [2, 2]).unwrap(); + let chain = MipChain::prepare(base, 16, || false).unwrap(); + assert_eq!(chain.level_count(), 2); + assert_eq!(chain.tail_bytes(), 16); + assert_eq!(chain.retained_bytes(), chain.tail_bytes() + chain.tail.capacity() * size_of::() + size_of::>()); + assert_eq!(MIP_RECIPE_ID, "solidcraft.opaque-linear-area-mips/1"); + close(chain.sample_repeat_lod_opaque([0.25, 0.25], 0.).unwrap(), [0.; 3]); + close(chain.sample_repeat_lod_opaque([0.25, 0.25], 1.).unwrap(), [0.5; 3]); + close(chain.sample_repeat_lod_opaque([0.25, 0.25], 0.25).unwrap(), [0.125; 3]); + close(chain.sample_repeat_lod_opaque([0.25, 0.25], 0.5).unwrap(), [0.25; 3]); +} + +#[test] +fn odd_edges_contribute_by_area_instead_of_being_dropped_or_overweighted() { + // Five pixels reduce to two equal-width cells: [0,0,0] and [0,0,1]. + // The middle pixel straddles the boundary, the last pixel weighs 1/2.5. + let mut pixels = [0., 0., 0., 1.].repeat(5); + pixels[16] = 1.; + let chain = MipChain::prepare(TextureView::new(&pixels, [5, 1]).unwrap(), 48, || false).unwrap(); + assert_eq!(chain.dimensions(1), Some([2, 1])); + close(chain.level(1).unwrap().sample_repeat_opaque([0.75, 0.5]).unwrap(), [0.4, 0., 0.]); + close(chain.sample_repeat_lod_opaque([0., 0.], 2.).unwrap(), [0.2, 0., 0.]); +} + +#[test] +fn rectangular_odd_pyramid_preserves_independent_mean() { + let mut pixels = Vec::new(); + for i in 0..15 { + pixels.extend([i as f32 / 16., 0.25, (14 - i) as f32 / 16., (i % 2) as f32]); + } + let chain = MipChain::prepare(TextureView::new(&pixels, [5, 3]).unwrap(), 48, || false).unwrap(); + assert_eq!(chain.level_count(), 3); + assert_eq!(chain.dimensions(0), Some([5, 3])); + assert_eq!(chain.dimensions(1), Some([2, 1])); + assert_eq!(chain.dimensions(2), Some([1, 1])); + assert_eq!(chain.dimensions(usize::MAX), None); + close(chain.sample_repeat_lod_opaque([-9.5, 12.], 2.).unwrap(), [7. / 16., 0.25, 7. / 16.]); +} + +#[test] +fn single_texel_borrows_base_and_needs_no_pixel_budget() { + let pixels = [0.25, 0.5, 0.75, 0.]; + let chain = MipChain::prepare(TextureView::new(&pixels, [1, 1]).unwrap(), 0, || false).unwrap(); + assert_eq!(chain.level_count(), 1); + assert_eq!(chain.tail_bytes(), 0); + assert!(std::ptr::eq(chain.level(0).unwrap().rgba.as_ptr(), pixels.as_ptr())); + close(chain.sample_repeat_lod_opaque([-0.1, 0.7], 0.).unwrap(), [0.25, 0.5, 0.75]); +} + +#[test] +fn constant_images_and_single_axes_are_invariant_at_all_lods() { + for dimensions in [[1, 7], [7, 1], [7, 5]] { + let pixels = [0.25, 0.5, 0.75, 0.].repeat((dimensions[0] * dimensions[1]) as usize); + let chain = MipChain::prepare(TextureView::new(&pixels, dimensions).unwrap(), MAX_MIP_TAIL_BYTES, || false).unwrap(); + for quarter in 0..=(chain.level_count() - 1) * 4 { + close(chain.sample_repeat_lod_opaque([-2.34, 1.92], quarter as f64 / 4.).unwrap(), [0.25, 0.5, 0.75]); + } + } +} + +#[test] +fn hostile_lod_and_uv_refuse_without_changing_the_chain() { + let pixels = [0., 0., 0., 1.].repeat(4); + let chain = MipChain::prepare(TextureView::new(&pixels, [2, 2]).unwrap(), 16, || false).unwrap(); + for lod in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -0.001, 1.001, f64::MAX] { + assert_eq!(chain.sample_repeat_lod_opaque([0., 0.], lod), Err(MipError::Lod)); + } + assert_eq!(chain.sample_repeat_lod_opaque([f64::NAN, 0.], 0.5), Err(MipError::Sampling(SamplingError::Coordinates))); + close(chain.sample_repeat_lod_opaque([0.25, 0.25], 0.).unwrap(), [0.; 3]); +} + +#[test] +fn exact_budget_and_global_cap_are_admitted_before_work() { + let pixels = [0., 0., 0., 1.].repeat(4); + let base = TextureView::new(&pixels, [2, 2]).unwrap(); + assert!(matches!(MipChain::prepare(base, 15, || false), Err(MipError::Budget))); + assert!(MipChain::prepare(base, 16, || false).is_ok()); + assert!(matches!(MipChain::prepare(base, MAX_MIP_TAIL_BYTES + 1, || false), Err(MipError::Budget))); + assert!(matches!(MipChain::prepare(base, usize::MAX, || false), Err(MipError::Budget))); + assert_eq!(required_bytes(2048, 2048).unwrap(), 22_369_616); + assert!(required_bytes(2048, 2048).unwrap() < MAX_MIP_TAIL_BYTES); +} + +#[test] +fn cancellation_before_during_and_after_preparation_never_returns_a_partial_chain() { + let pixels = [0.25, 0.5, 0.75, 0.].repeat(64); + let base = TextureView::new(&pixels, [8, 8]).unwrap(); + let successful_calls = Cell::new(0); + MipChain::prepare(base, MAX_MIP_TAIL_BYTES, || { + successful_calls.set(successful_calls.get() + 1); + false + }) + .unwrap(); + for stop in 1..=successful_calls.get() { + let calls = Cell::new(0); + let result = MipChain::prepare(base, MAX_MIP_TAIL_BYTES, || { + calls.set(calls.get() + 1); + calls.get() == stop + }); + assert!(matches!(result, Err(MipError::Cancelled))); + } + assert!(MipChain::prepare(base, MAX_MIP_TAIL_BYTES, || false).is_ok()); +} diff --git a/crates/render/src/texture_sampling/tests.rs b/crates/render/src/texture_sampling/tests.rs new file mode 100644 index 000000000..93040acf2 --- /dev/null +++ b/crates/render/src/texture_sampling/tests.rs @@ -0,0 +1,94 @@ +use super::*; + +const PIXELS: [f32; 16] = [1., 0., 0., 0., 0., 1., 0., 1., 0., 0., 1., 1., 1., 1., 1., 1.]; + +fn close(actual: [f64; 3], expected: [f64; 3]) { + for (a, b) in actual.into_iter().zip(expected) { + assert!((a - b).abs() < 1e-9, "{actual:?} != {expected:?}"); + } +} + +#[test] +fn centers_orientation_and_explicit_opaque_alpha() { + let view = TextureView::new(&PIXELS, [2, 2]).unwrap(); + for (uv, rgb) in [([0.25, 0.25], [1., 0., 0.]), ([0.75, 0.25], [0., 1., 0.]), ([0.25, 0.75], [0., 0., 1.]), ([0.75, 0.75], [1., 1., 1.])] { + close(view.sample_repeat_opaque(uv).unwrap(), rgb); + } + close(view.sample_repeat_opaque([0.5, 0.5]).unwrap(), [0.5; 3]); + close(view.sample_repeat_opaque([0.5, 0.25]).unwrap(), [0.5, 0.5, 0.]); + close(view.sample_repeat_opaque([0.375, 0.625]).unwrap(), [0.375, 0.25, 0.75]); +} + +#[test] +fn linear_black_white_mixing_is_not_encoded_srgb_averaging() { + let pixels = [0., 0., 0., 1., 1., 1., 1., 1.]; + let view = TextureView::new(&pixels, [2, 1]).unwrap(); + // Linear 0.5, which would encode to about sRGB 0.735, not encoded 0.5. + close(view.sample_repeat_opaque([0.5, 0.5]).unwrap(), [0.5; 3]); +} + +#[test] +fn signed_repeats_and_both_periodic_seams() { + let view = TextureView::new(&PIXELS, [2, 2]).unwrap(); + for uv in [[0., 0.], [1., 1.], [-1., -1.], [MAX_REPEAT_COORDINATE, -MAX_REPEAT_COORDINATE]] { + close(view.sample_repeat_opaque(uv).unwrap(), [0.5; 3]); + } + close(view.sample_repeat_opaque([-0.75, -0.25]).unwrap(), [0., 0., 1.]); + for uv in [[0.13, 0.92], [0., 0.25], [0.75, 0.]] { + close(view.sample_repeat_opaque(uv).unwrap(), view.sample_repeat_opaque([uv[0] - 7., uv[1] + 9.]).unwrap()); + } + for epsilon in [-1e-12, 0., 1e-12] { + close(view.sample_repeat_opaque([epsilon, 0.25]).unwrap(), [0.5, 0.5, 0.]); + close(view.sample_repeat_opaque([0.25, epsilon]).unwrap(), [0.5, 0., 0.5]); + } +} + +#[test] +fn constant_and_single_texel_invariance() { + for dimensions in [[1, 1], [1, 3], [3, 1], [3, 5]] { + let pixels = [0.25, 0.5, 0.75, 0.].repeat((dimensions[0] * dimensions[1]) as usize); + let view = TextureView::new(&pixels, dimensions).unwrap(); + for uv in [[0., 0.], [-12.125, 3.25], [1., 1.], [MAX_REPEAT_COORDINATE - 0.125, 0.5]] { + close(view.sample_repeat_opaque(uv).unwrap(), [0.25, 0.5, 0.75]); + } + } +} + +#[test] +fn rejects_hostile_storage_and_channels() { + for dimensions in [[0, 1], [1, 0], [MAX_TEXTURE_EDGE + 1, 1], [u32::MAX, u32::MAX]] { + assert_eq!(TextureView::new(&[], dimensions).unwrap_err(), SamplingError::Dimensions); + } + for pixels in [&[][..], &[0.; 3][..], &[0.; 5][..]] { + assert_eq!(TextureView::new(pixels, [1, 1]).unwrap_err(), SamplingError::Length); + } + for invalid in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -0.01, 1.01] { + for channel in 0..4 { + let mut pixels = [0.; 4]; + pixels[channel] = invalid; + assert_eq!(TextureView::new(&pixels, [1, 1]).unwrap_err(), SamplingError::Values); + } + } +} + +#[test] +fn rejects_nonfinite_and_extreme_coordinates() { + let view = TextureView::new(&PIXELS, [2, 2]).unwrap(); + for invalid in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, f64::MAX, MAX_REPEAT_COORDINATE + 0.001, -MAX_REPEAT_COORDINATE - 0.001] { + for uv in [[invalid, 0.], [0., invalid]] { + assert_eq!(view.sample_repeat_opaque(uv), Err(SamplingError::Coordinates)); + } + } +} + +#[test] +fn reference_bound_retains_fractional_centers_and_maximum_edge() { + let view = TextureView::new(&PIXELS, [2, 2]).unwrap(); + close(view.sample_repeat_opaque([MAX_REPEAT_COORDINATE - 0.75, -MAX_REPEAT_COORDINATE + 0.25]).unwrap(), [1., 0., 0.]); + let mut pixels = [0., 0., 0., 1.].repeat(MAX_TEXTURE_EDGE as usize); + pixels[0] = 1.; + let view = TextureView::new(&pixels, [MAX_TEXTURE_EDGE, 1]).unwrap(); + let half_texel = 0.5 / f64::from(MAX_TEXTURE_EDGE); + close(view.sample_repeat_opaque([half_texel, 0.]).unwrap(), [1., 0., 0.]); + close(view.sample_repeat_opaque([half_texel - MAX_REPEAT_COORDINATE, 0.]).unwrap(), [1., 0., 0.]); +} diff --git a/docs/render-texture-mips.md b/docs/render-texture-mips.md new file mode 100644 index 000000000..33dc6378b --- /dev/null +++ b/docs/render-texture-mips.md @@ -0,0 +1,69 @@ +# Opaque CPU mip reference + +The numerical follow-up #1332 reuses the reference sampler in #1327 through +`solidcraft_render::texture_sampling::mips`. It adds no installed renderer, +resource storage, normalization, file decoder, worker, cache or GPU capability. +The visible wood consumer remains separate work. + +`MipChain::prepare(base, max_tail_bytes, cancelled)` borrows a validated +`TextureView` as level zero. Each following level has dimensions +`[max(1, width / 2), max(1, height / 2)]` until 1x1, at most 12 levels including +the base. All derived levels are immutable and allocated through fallible reserve. +The base is not copied. `level` borrows a prepared view without another whole-image +admission scan; `dimensions`, `level_count` and `tail_bytes` expose its accounting. + +The caller chooses a derived pixel capacity budget no larger than 32 MiB. +The complete required pixel size is checked before work, and retained Vec capacity +is checked before filling each level. A maximum admitted 2048x2048 base requires +22,369,616 derived pixel bytes. The borrowed base (up to 64 MiB), small bounded +level metadata, allocator overhead and other normalization/preparation allocations +are separate. This is not a total process-memory bound. The existing resource host +must count both the retained base lease and derived levels against its cache budget. +`retained_bytes()` includes the actual pixel and level-vector capacities and the +chain value. The host must also budget allocator overhead conservatively; this +helper's cap is not an additional allowance outside #1237's shared preparation pool. +Keep the borrowed base alive through its existing prepared-result/lease. + +`MIP_RECIPE_ID` is `solidcraft.opaque-linear-area-mips/1`: include it in preparation +and cache identity alongside source digest, role, normalization policies and host +generation. This recipe fixes floor-halving, linear area filtering and opaque alpha. +It must not alias level-zero-only output, a normal filter or another alpha policy. +Future changes to those semantics need a new recipe identity. + +Every destination texel is an area average over its equal-sized cell in the source +image, treating source texels as piecewise constant. Integer overlap numerators +include partial source cells. Thus odd edges are neither discarded nor given the +weight of a complete destination cell. For example, [0,0,0,0,1] reduces to [0,0.4] +then [0.2], preserving its original mean. Intermediates use f64 and each generated +level is stored in f32, so successive levels include f32 rounding. No transfer +function is applied; the input must already be linear normalized color/data. + +The API is deliberately opaque: alpha is ignored in RGB filtering and generated +levels have alpha=1. This is not premultiplied filtering or transparent compositing. +Normal maps need a separate role-aware vector filtering policy and must not use +this helper as though scalar averaging produced valid unit normals. There is no +hidden Y flip, tangent basis, grain-axis inference or source orientation transform. + +Cancellation is checked before work, at each level, before every destination row, +after a level and before returning the complete chain. Failure/cancellation drops +local partial results; callers receive no partial chain. Preparation is synchronous +and belongs to the existing caller-owned host. Cancellation polls do not yield the +browser event loop, schedule a worker or establish browser responsiveness. + +`sample_repeat_lod_opaque(uv, lod)` applies the #1327 periodic bilinear convention +within each level and interpolates adjacent levels in linear space. LOD must be +finite in [0, level_count - 1]; out-of-range values refuse. Signed/unwrapped UVs +keep the sampler's existing finite 2^20 repeat bound. Sampling performs no +allocation or full-image validation scan. GPU/f32 parity is not inferred from +the CPU arithmetic. + +LOD is supplied explicitly. Screen-space derivatives, footprint selection, +anisotropic filtering and grazing-angle grain remain consumer work; a mip chain +alone is not a proof of alias-free wood. Typed bindings, local mm mapping and +inverse-instance placement, CPU/GPU consumers, PNG/offline reopen and real native +visual evidence are still required. HDRI and final rendering are not enabled. + +Original generated tests cover linear checkerboard and fractional LOD values, +area-weighted odd/rectangular means, 1x1 and single-axis images, budget boundaries, +hostile LOD/UVs and cancellation at every publication checkpoint. No third-party +assets, code or dependencies are added. This numerical helper has no app screenshot. diff --git a/docs/render-texture-sampling.md b/docs/render-texture-sampling.md new file mode 100644 index 000000000..ee1be1f47 --- /dev/null +++ b/docs/render-texture-sampling.md @@ -0,0 +1,47 @@ +# CPU texture reference sampler + +`solidcraft_render::texture_sampling` supplies the independent numerical unit in +#1327. It does not install a texture consumer or close the wood rendering work. + +Construct `TextureView::new(rgba, [width, height])` from immutable normalized float +RGBA. Dimensions must be positive and no larger than the existing admission edge +limit (2048); storage is exactly `width * height * 4` floats, at most 64 MiB. +Every channel, including alpha, must be finite and within [0, 1]. Construction +scans once and borrows the caller's storage. Sampling does constant work without +allocating. The sampler neither decodes nor converts color, and owns no cache. + +The normalization contribution #1267 can provide the inputs directly through +`NormalizedTexture::rgba()` and `receipt().output_dimensions`; no normalization +implementation or dependency is copied into this module. Raw encoded RGBA8 from +the older admission utility is not interchangeable with normalized linear color. + +`sample_repeat_opaque([u, v])` returns three f64 channels. Both axes use periodic +bilinear level-zero addressing. UV (0, 0) is the top-left image boundary; v grows +downwards. Texel (x, y) is centered at ((x + 0.5) / width, (y + 0.5) / height). +An integer coordinate lies halfway between the last and first texels. Negative +and unwrapped coordinates repeat; nothing clamps UVs or flips rows a second time. + +Interpolation is in the supplied linear color or data space, with f64 arithmetic +on f32 input samples. The helper applies no sRGB transfer, normal-vector decoding, +tangent basis or engineering grain-axis interpretation. Alpha is deliberately +ignored for this opaque API: even zero-alpha RGB participates. It must not be used +as a transparent compositor; there is no claim of premultiplied-alpha filtering. + +Coordinates must be finite and have magnitude at most 2^20 repeats. Reduction +precedes multiplication by dimensions. Around this bound, f64 input spacing is +at most 2^-32 repeats, or 2^-21 texels at maximum width. Smaller sub-ULP offsets +cannot be recovered. Tests use a 1e-9 absolute channel tolerance for analytic +fixtures; this is not a universal error bound or f32 GPU parity certification. +Consumers must reject or explicitly reconcile larger mapping ranges rather than +silently clamp them. GPU upload/filtering precision requires separate evidence. + +Original generated 1x1/2x2 and rectangular constant fixtures check centers, row +orientation, linear black/white mixing, interpolation, both seams, signed/integer +repeats, alpha policy and hostile storage/coordinate refusal. No third-party +assets or code are added. This invisible helper has no useful app screenshot. + +Still required for visible wood: typed bindings and persistence, local millimetre +mapping with one inverse-instance transform, resource lifetime/budgets, product +CPU/GPU integration, minification/mips, PNG and offline reopen evidence. Bilinear +level-zero filtering alone does not prevent aliasing of oblique/minified grain. +HDRI, glass, final integration and mechanical wood properties are separate work. From c36163095490cb8683275f23ce03fa6cdc603897 Mon Sep 17 00:00:00 2001 From: cronos Date: Fri, 16 Oct 2026 09:04:25 +0900 Subject: [PATCH 19/92] Export the current 3D view as 2D DXF with optional hidden lines (#1449) Adds File > Export > Current View as DXF: the visible bodies projected from the current camera onto 2D LINE/LWPOLYLINE entities, with hidden edges omitted or dashed. Co-authored-by: cronos <19868002+crono2250@users.noreply.github.com> Co-Authored-By: Claude Sonnet 5.5 --- README.md | 3 + ROADMAP.md | 5 + assets/locales/de.json | 12 + assets/locales/en.json | 12 + assets/locales/ja.json | 12 + assets/locales/ko.json | 12 + assets/locales/zh.json | 12 + crates/engine/src/cmd/mod.rs | 2 + crates/engine/src/cmd/view_dxf.rs | 101 ++++++ crates/engine/src/cmd/view_dxf_projection.rs | 342 +++++++++++++++++++ crates/engine/src/cmd/view_dxf_tests.rs | 102 ++++++ crates/engine/src/tests/path_scope.rs | 1 + crates/io/src/dxf_out.rs | 39 ++- crates/ui-egui/src/dialogs.rs | 11 + crates/ui-egui/src/dialogs_view_dxf.rs | 88 +++++ crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/prefs.rs | 3 + crates/ui-egui/src/toolbar.rs | 4 + docs/features.md | 5 +- docs/view-dxf.md | 34 ++ 20 files changed, 798 insertions(+), 3 deletions(-) create mode 100644 crates/engine/src/cmd/view_dxf.rs create mode 100644 crates/engine/src/cmd/view_dxf_projection.rs create mode 100644 crates/engine/src/cmd/view_dxf_tests.rs create mode 100644 crates/ui-egui/src/dialogs_view_dxf.rs create mode 100644 docs/view-dxf.md diff --git a/README.md b/README.md index daaf675a2..3b11f3dd1 100644 --- a/README.md +++ b/README.md @@ -82,6 +82,9 @@ rebuild with no errors, replayed here at 2× speed. ## 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). + - **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. diff --git a/ROADMAP.md b/ROADMAP.md index c9a64dbb7..68b101950 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -66,6 +66,11 @@ pointer movement orbits without a mouse button, and vertical scrolling zooms. Ot retain their saved two-finger scroll preference; camera motion is available through `view.navigate` and modifier-aware `ui.move` automation. +M11 precursor: File → Export Current View as DXF exports shown placed bodies from the current +camera as a 2D millimetre drawing, with hidden edges omitted or dashed. Vector occlusion splits +partly hidden edges and includes curved silhouettes. Curves are approximated; drawing sheets, +annotations and exact projected curves remain deferred. See [view DXF](docs/view-dxf.md). + ## Interactive modelling - New Body extrusion and face-offset previews show completed intermediate geometry while a diff --git a/assets/locales/de.json b/assets/locales/de.json index 42755ebd8..a3e96c2bc 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -1,6 +1,18 @@ { "settings.measure_axis_distances": "X/Y/Z-Maße anzeigen", "settings.measure_axis_distances_help": "Bei geöffneter Messung die Abstände entlang der Weltachsen zusätzlich zum Gesamtabstand anzeigen.", + "Export Current View as DXF": "Aktuelle Ansicht als DXF exportieren", + "Export Current View as DXF…": "Aktuelle Ansicht als DXF exportieren…", + "Hidden edges": "Verdeckte Kanten", + "Do not export hidden edges": "Verdeckte Kanten nicht exportieren", + "Export hidden edges as dashed lines": "Verdeckte Kanten gestrichelt exportieren", + "Projection": "Projektion", + "Current perspective view": "Aktuelle perspektivische Ansicht", + "Current orthographic view (1:1 mm)": "Aktuelle orthogonale Ansicht (1:1 mm)", + "Visible bodies only. Curves use line segments (0.01 mm tolerance).": "Nur sichtbare Körper. Kurven werden durch Liniensegmente angenähert (Toleranz: 0,01 mm).", + "Turn off section analysis before exporting the view.": "Deaktivieren Sie die Schnittanalyse, bevor Sie die Ansicht exportieren.", + "No visible bodies to export.": "Keine sichtbaren Körper zum Exportieren.", + "Export DXF…": "DXF exportieren…", "Send your report on GitHub": "Bericht auf GitHub senden", "1. Open GitHub draft below, then paste the report copied to your clipboard.": "1. Unten den GitHub-Entwurf öffnen und den kopierten Bericht aus der Zwischenablage einfügen.", "1. Open GitHub draft below. Your title and report will be filled in.": "1. Unten den GitHub-Entwurf öffnen. Titel und Bericht werden vorausgefüllt.", diff --git a/assets/locales/en.json b/assets/locales/en.json index ac454dc78..6c392dd49 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -1,6 +1,18 @@ { "settings.measure_axis_distances": "Show X/Y/Z distances", "settings.measure_axis_distances_help": "Show world-axis component dimensions alongside the total distance while Measure is open.", + "Export Current View as DXF": "Export Current View as DXF", + "Export Current View as DXF…": "Export Current View as DXF…", + "Hidden edges": "Hidden edges", + "Do not export hidden edges": "Do not export hidden edges", + "Export hidden edges as dashed lines": "Export hidden edges as dashed lines", + "Projection": "Projection", + "Current perspective view": "Current perspective view", + "Current orthographic view (1:1 mm)": "Current orthographic view (1:1 mm)", + "Visible bodies only. Curves use line segments (0.01 mm tolerance).": "Visible bodies only. Curves use line segments (0.01 mm tolerance).", + "Turn off section analysis before exporting the view.": "Turn off section analysis before exporting the view.", + "No visible bodies to export.": "No visible bodies to export.", + "Export DXF…": "Export DXF…", "Send your report on GitHub": "Send your report on GitHub", "1. Open GitHub draft below, then paste the report copied to your clipboard.": "1. Open GitHub draft below, then paste the report copied to your clipboard.", "1. Open GitHub draft below. Your title and report will be filled in.": "1. Open GitHub draft below. Your title and report will be filled in.", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index f71689d72..d338ae8e8 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -1,6 +1,18 @@ { "settings.measure_axis_distances": "計測のX・Y・Z距離を表示", "settings.measure_axis_distances_help": "計測ダイアログを開いている間、2点間距離に加えてワールドX・Y・Z軸方向の寸法線と距離を表示します。", + "Export Current View as DXF": "現在の表示をDXFでエクスポート", + "Export Current View as DXF…": "現在の表示をDXFでエクスポート…", + "Hidden edges": "隠線", + "Do not export hidden edges": "出力しない", + "Export hidden edges as dashed lines": "点線で出力", + "Projection": "投影", + "Current perspective view": "現在の透視投影", + "Current orthographic view (1:1 mm)": "現在の平行投影(実寸・mm)", + "Visible bodies only. Curves use line segments (0.01 mm tolerance).": "表示中のボディを出力します。曲線は線分で近似します(許容誤差0.01 mm)。", + "Turn off section analysis before exporting the view.": "断面解析をオフにしてからエクスポートしてください。", + "No visible bodies to export.": "出力する表示中のボディがありません。", + "Export DXF…": "DXFをエクスポート…", "Send your report on GitHub": "GitHubでレポートを送信", "1. Open GitHub draft below, then paste the report copied to your clipboard.": "1. 下のボタンでGitHubの下書きを開き、クリップボードにコピーされたレポートを貼り付けます。", "1. Open GitHub draft below. Your title and report will be filled in.": "1. 下のボタンでGitHubの下書きを開きます。タイトルとレポートは入力済みです。", diff --git a/assets/locales/ko.json b/assets/locales/ko.json index 758975dd0..4d5596fb8 100644 --- a/assets/locales/ko.json +++ b/assets/locales/ko.json @@ -1,6 +1,18 @@ { "settings.measure_axis_distances": "X/Y/Z 거리 표시", "settings.measure_axis_distances_help": "측정 대화상자가 열려 있는 동안 전체 거리와 함께 월드 축 방향 치수와 거리를 표시합니다.", + "Export Current View as DXF": "현재 뷰를 DXF로 내보내기", + "Export Current View as DXF…": "현재 뷰를 DXF로 내보내기…", + "Hidden edges": "숨겨진 모서리", + "Do not export hidden edges": "숨겨진 모서리 내보내지 않기", + "Export hidden edges as dashed lines": "숨겨진 모서리를 파선으로 내보내기", + "Projection": "투영", + "Current perspective view": "현재 원근 투영 뷰", + "Current orthographic view (1:1 mm)": "현재 직교 투영 뷰 (1:1 mm)", + "Visible bodies only. Curves use line segments (0.01 mm tolerance).": "표시된 바디만 내보냅니다. 곡선은 선분으로 근사합니다 (허용오차 0.01 mm).", + "Turn off section analysis before exporting the view.": "뷰를 내보내기 전에 단면 분석을 끄세요.", + "No visible bodies to export.": "표시된 바디가 없어 내보낼 수 없습니다.", + "Export DXF…": "DXF 내보내기…", "Send your report on GitHub": "GitHub에서 보고서 보내기", "1. Open GitHub draft below, then paste the report copied to your clipboard.": "1. 아래에서 GitHub 초안을 열고 클립보드에 복사된 보고서를 붙여넣으세요.", "1. Open GitHub draft below. Your title and report will be filled in.": "1. 아래에서 GitHub 초안을 여세요. 제목과 보고서가 자동으로 입력됩니다.", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index 4d3a0aa77..bc14ab2b6 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -1,6 +1,18 @@ { "settings.measure_axis_distances": "显示 X/Y/Z 距离", "settings.measure_axis_distances_help": "测量对话框打开时,在总距离之外显示沿世界坐标轴方向的尺寸线和距离。", + "Export Current View as DXF": "将当前视图导出为DXF", + "Export Current View as DXF…": "将当前视图导出为DXF…", + "Hidden edges": "隐藏线", + "Do not export hidden edges": "不导出隐藏线", + "Export hidden edges as dashed lines": "以虚线导出隐藏线", + "Projection": "投影", + "Current perspective view": "当前透视视图", + "Current orthographic view (1:1 mm)": "当前正交视图(1:1毫米)", + "Visible bodies only. Curves use line segments (0.01 mm tolerance).": "仅导出可见实体。曲线以线段近似(公差0.01毫米)。", + "Turn off section analysis before exporting the view.": "请关闭截面分析后再导出视图。", + "No visible bodies to export.": "没有可导出的可见实体。", + "Export DXF…": "导出DXF…", "Send your report on GitHub": "在 GitHub 上发送报告", "1. Open GitHub draft below, then paste the report copied to your clipboard.": "1. 点击下方按钮打开 GitHub 草稿,然后粘贴已复制到剪贴板的报告。", "1. Open GitHub draft below. Your title and report will be filled in.": "1. 点击下方按钮打开 GitHub 草稿。标题和报告将自动填入。", diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index bb6ed59d1..7c1353ca8 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -74,6 +74,7 @@ mod sketch_modify; mod sketch_project; mod surface; mod surface_analysis; +mod view_dxf; mod view_navigation; use serde::Serialize; @@ -265,6 +266,7 @@ pub fn command_specs() -> Vec<&'static CommandSpec> { v.extend(libraries::COMMANDS.iter()); v.extend(section::COMMANDS.iter()); v.extend(view_navigation::COMMANDS.iter()); + v.extend(view_dxf::COMMANDS.iter()); v.extend(diagnostics::COMMANDS.iter()); v.extend(render::COMMANDS.iter()); v diff --git a/crates/engine/src/cmd/view_dxf.rs b/crates/engine/src/cmd/view_dxf.rs new file mode 100644 index 000000000..3a18f0db6 --- /dev/null +++ b/crates/engine/src/cmd/view_dxf.rs @@ -0,0 +1,101 @@ +//! A drawing of the visible bodies from a supplied viewport camera. No screen pixels, grid, +//! selection highlights or tessellation diagonals are exported. + +#[path = "view_dxf_projection.rs"] +mod projection; + +use serde_json::{Value, json}; +use solidcraft_io::{DxfEntity, DxfLayer, DxfLinetype, DxfShape}; +use solidcraft_render::Camera; + +use super::CommandSpec; +use crate::params::{bad, str_}; +use crate::{Result, Session}; + +const CMD: &str = "file.export_view_dxf"; +pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new(CMD, "Export Current View as DXF", export) + .icon("export") + .noundo() + .params("camera: Camera (current view); hidden?: omit|dashed (default omit); tolerance?: 0.0001..1 mm (curve chord tolerance, default 0.01); path?: .dxf file (else returns dxf text). Visible placed bodies only; 2D LINE/LWPOLYLINE entities on VISIBLE/HIDDEN layers, mm; perspective projected onto the camera target plane; no viewport crop or overlays.")]; + +fn export(s: &mut Session, p: &Value) -> Result { + let cam: Camera = + serde_json::from_value(p.get("camera").cloned().ok_or_else(|| bad(CMD, "camera is required"))?).map_err(|_| bad(CMD, "invalid camera"))?; + if !cam.is_valid() + || !(0.0..std::f64::consts::PI).contains(&cam.fov) + || cam.pitch.abs() > std::f64::consts::FRAC_PI_2 + || cam.yaw.abs() > 1e6 + || cam.roll.abs() > 1e6 + { + return Err(bad(CMD, "invalid camera")); + } + let dashed = match p.get("hidden") { + None => false, + Some(Value::String(v)) if v == "omit" => false, + Some(Value::String(v)) if v == "dashed" => true, + _ => return Err(bad(CMD, "hidden must be omit or dashed")), + }; + let tolerance = match p.get("tolerance") { + None => 0.01, + Some(v) => v.as_f64().filter(|t| (0.0001..=1.0).contains(t)).ok_or_else(|| bad(CMD, "tolerance must be 0.0001..1 mm"))?, + }; + let path = match p.get("path") { + None => None, + Some(_) => Some(str_(p, "path").filter(|v| !v.trim().is_empty() && v.len() < 4096).ok_or_else(|| bad(CMD, "invalid path"))?), + }; + if let Some(path) = path { + solidcraft_io::vfs::check(path).map_err(|e| crate::EngineError::Other(e.to_string()))?; + } + let world = s.world_state(); + let mut meshes = Vec::new(); + let mut count = 0usize; + for body in world.bodies.iter().filter(|b| s.body_visible(&b.name)) { + let mesh = body.body.reference_display_mesh_angular(tolerance, solidcraft_kernel::DISPLAY_ANGLE)?; + count = count.saturating_add(mesh.triangles.len()).saturating_add(mesh.edges.iter().map(Vec::len).sum::()); + if count > 1_000_000 { + return Err(bad(CMD, "view too complex to export; hide bodies or increase tolerance")); + } + if mesh.triangles.is_empty() { + return Err(bad(CMD, format!("{} has no exportable surface", body.name))); + } + meshes.push(mesh); + } + if meshes.is_empty() { + return Err(bad(CMD, "no visible bodies to export")); + } + let lines = projection::drawing(&meshes, &cam).map_err(|e| bad(CMD, e))?; + let mut visible = 0; + let mut hidden = 0; + let mut entities = Vec::new(); + for line in lines { + if line.hidden && !dashed { + continue; + } + let layer = if line.hidden { + hidden += 1; + "HIDDEN" + } else { + visible += 1; + "VISIBLE" + }; + entities.push(DxfEntity { layer: layer.into(), shape: DxfShape::Line(line.a, line.b) }); + } + let entities = projection::connect(entities); + let mut layers = vec![DxfLayer::new("VISIBLE", 7)]; + if dashed { + layers.push(DxfLayer { linetype: DxfLinetype::Hidden, ..DxfLayer::new("HIDDEN", 8) }); + } + let text = solidcraft_io::write_dxf_drawing(&layers, &entities); + let mut result = json!({"visible":visible,"hidden":hidden,"units":"mm","tolerance":tolerance,"projection":if cam.fov > 0.0 {"perspective"} else {"orthographic"}}); + if let Some(path) = path { + solidcraft_io::vfs::write(path, text.as_bytes()).map_err(|e| crate::EngineError::Other(e.to_string()))?; + result["path"] = json!(path); + } else { + result["dxf"] = json!(text); + } + Ok(result) +} + +#[cfg(test)] +#[path = "view_dxf_tests.rs"] +mod tests; diff --git a/crates/engine/src/cmd/view_dxf_projection.rs b/crates/engine/src/cmd/view_dxf_projection.rs new file mode 100644 index 000000000..c496b2ac9 --- /dev/null +++ b/crates/engine/src/cmd/view_dxf_projection.rs @@ -0,0 +1,342 @@ +//! Vector hidden-line removal: intersect each projected edge with triangle half planes and +//! its depth plane, then union occluded parameter intervals. A BVH bounds the candidate work. +use solidcraft_geom::{Aabb3, Mesh, Vec2, Vec3}; +use solidcraft_io::{DxfEntity, DxfShape}; +use solidcraft_render::Camera; +use std::collections::BTreeMap; + +/// Keep the hidden curves connected: restarting a dash on every short chord would make a +/// small circular hole look solid. Degree-two joins continue; junctions end the polyline. +pub(super) fn connect(entities: Vec) -> Vec { + let mut result = Vec::new(); + let mut lines = Vec::new(); + for entity in entities { + match entity { + DxfEntity { layer, shape: DxfShape::Line(a, b) } if layer == "HIDDEN" => lines.push((a, b)), + e => result.push(e), + } + } + let extent = lines.iter().flat_map(|(a, b)| [a, b]).fold(1.0_f64, |s, p| s.max(p.x.abs()).max(p.y.abs())); + let eps = extent * 1e-8; + let key = |p: Vec2| [(p.x / eps).round() as i64, (p.y / eps).round() as i64]; + let mut nodes: BTreeMap<[i64; 2], Vec> = BTreeMap::new(); + for (i, (a, b)) in lines.iter().enumerate() { + nodes.entry(key(*a)).or_default().push(i); + nodes.entry(key(*b)).or_default().push(i); + } + let mut used = vec![false; lines.len()]; + for (i, (a, b)) in lines.iter().enumerate() { + if used.get(i).copied().unwrap_or(true) { + continue; + } + if let Some(v) = used.get_mut(i) { + *v = true; + } + let mut points = vec![*a, *b]; + for _ in 0..2 { + while let Some(end) = points.last().copied() { + let Some(neighbours) = nodes.get(&key(end)).filter(|n| n.len() == 2) else { break }; + let Some(next) = neighbours.iter().copied().find(|i| used.get(*i) == Some(&false)) else { break }; + let Some((a, b)) = lines.get(next) else { break }; + if let Some(v) = used.get_mut(next) { + *v = true; + } + points.push(if key(*a) == key(end) { *b } else { *a }); + } + points.reverse(); + } + result.push(DxfEntity { layer: "HIDDEN".into(), shape: DxfShape::Polyline { points } }); + } + result +} + +pub(super) struct Line { + pub a: Vec2, + pub b: Vec2, + pub hidden: bool, +} + +fn xy(p: Vec3) -> Vec2 { + Vec2::new(p.x, p.y) +} +fn cross(a: Vec2, b: Vec2) -> f64 { + a.x * b.y - a.y * b.x +} +fn bounds(points: impl IntoIterator) -> Aabb3 { + let mut b = Aabb3::EMPTY; + for p in points { + b.add(p); + } + b +} +fn overlap(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 +} + +struct Triangle { + p: [Vec3; 3], + bounds: Aabb3, +} +struct Tree { + bounds: Aabb3, + children: Option<(Box, Box)>, + triangles: Vec, +} +impl Tree { + fn new(mut triangles: Vec) -> Self { + let b = triangles.iter().fold(Aabb3::EMPTY, |b, t| b.union(&t.bounds)); + if triangles.len() <= 12 { + return Self { bounds: b, children: None, triangles }; + } + let x = b.size().x > b.size().y; + let middle = triangles.len() / 2; + triangles.select_nth_unstable_by(middle, |a, b| { + let c = |t: &Triangle| if x { t.bounds.center().x } else { t.bounds.center().y }; + c(a).total_cmp(&c(b)) + }); + let right = triangles.split_off(middle); + Self { bounds: b, children: Some((Box::new(Self::new(triangles)), Box::new(Self::new(right)))), triangles: Vec::new() } + } + fn intervals(&self, a: Vec3, b: Vec3, bx: &Aabb3, eps: f64, out: &mut Vec<(f64, f64)>, budget: &mut usize) -> Result<(), &'static str> { + *budget = budget.checked_sub(1).ok_or("view too complex to export; hide some bodies")?; + if !overlap(&self.bounds, bx) || self.bounds.max.z <= a.z.min(b.z) + eps { + return Ok(()); + } + if let Some((left, right)) = &self.children { + left.intervals(a, b, bx, eps, out, budget)?; + right.intervals(a, b, bx, eps, out, budget)?; + } else { + for t in &self.triangles { + if overlap(&t.bounds, bx) + && let Some(span) = occluded(a, b, t.p, eps) + { + out.push(span); + } + } + } + Ok(()) + } +} + +/// Clip [lo,hi] by the linear inequality f(t) >= 0. +fn clip(lo: &mut f64, hi: &mut f64, f0: f64, f1: f64) -> bool { + if f0 < 0.0 && f1 < 0.0 { + return false; + } + if (f0 < 0.0) != (f1 < 0.0) { + let at = f0 / (f0 - f1); + if f0 < 0.0 { + *lo = lo.max(at); + } else { + *hi = hi.min(at); + } + } + *hi > *lo +} +fn occluded(a: Vec3, b: Vec3, t: [Vec3; 3], eps: f64) -> Option<(f64, f64)> { + let [p, q, r] = t; + let area = cross(xy(q - p), xy(r - p)); + if area.abs() < 1e-20 { + return None; + } + let (mut lo, mut hi) = (0.0, 1.0); + for (u, v) in [(p, q), (q, r), (r, p)] { + let side = |w: Vec3| cross(xy(v - u), xy(w - u)) * area.signum(); + if !clip(&mut lo, &mut hi, side(a), side(b)) { + return None; + } + } + let depth = |w: Vec3| { + let s = cross(xy(w - p), xy(r - p)) / area; + let u = cross(xy(q - p), xy(w - p)) / area; + p.z + s * (q.z - p.z) + u * (r.z - p.z) - w.z - eps + }; + clip(&mut lo, &mut hi, depth(a), depth(b)).then_some((lo, hi)) +} + +fn key(p: Vec3, eps: f64) -> [i64; 3] { + [(p.x / eps).round() as i64, (p.y / eps).round() as i64, (p.z / eps).round() as i64] +} + +/// Merge collinear projected intervals, giving visible strokes precedence. This also removes +/// a rear edge underneath only part of a visible edge, and rejoins subdivided silhouettes. +fn merge_lines(lines: Vec, eps: f64) -> Vec { + type Events = (Vec2, Vec2, Vec<(f64, i32, i32)>); + let mut groups: BTreeMap<[i64; 3], Events> = BTreeMap::new(); + for line in lines { + let delta = line.b - line.a; + let mut dir = delta / delta.len(); + if (dir.x.abs() > 1e-8 && dir.x < 0.0) || (dir.x.abs() <= 1e-8 && dir.y < 0.0) { + dir = -dir; + } + let offset = cross(dir, line.a); + let k = [(dir.x / 1e-8).round() as i64, (dir.y / 1e-8).round() as i64, (offset / eps).round() as i64]; + let (origin, dir, events) = groups.entry(k).or_insert((line.a, dir, Vec::new())); + let (a, b) = ((line.a - *origin).dot(*dir), (line.b - *origin).dot(*dir)); + let (v, h) = if line.hidden { (0, 1) } else { (1, 0) }; + events.push((a.min(b), v, h)); + events.push((a.max(b), -v, -h)); + } + let mut result = Vec::new(); + for (_, (origin, dir, mut events)) in groups { + events.sort_unstable_by(|a, b| a.0.total_cmp(&b.0)); + let (mut visible, mut hidden, mut last) = (0, 0, 0.0); + let mut path: Option = None; + for (at, v, h) in events { + if at - last > eps { + if visible > 0 || hidden > 0 { + let is_hidden = visible == 0; + let a = origin + dir * last; + let b = origin + dir * at; + if let Some(p) = path.as_mut().filter(|p| p.hidden == is_hidden && p.b.dist(a) <= eps) { + p.b = b; + } else { + if let Some(p) = path.take() { + result.push(p); + } + path = Some(Line { a, b, hidden: is_hidden }); + } + } else if let Some(p) = path.take() { + result.push(p); + } + } + visible += v; + hidden += h; + last = at; + } + if let Some(p) = path { + result.push(p); + } + } + result +} + +/// B-rep edges plus curved silhouettes. Triangle adjacency is welded by position because +/// different faces can have different vertex indices along their shared boundary. +fn edges(mesh: &Mesh, cam: &Camera, eps: f64) -> Vec<(Vec3, Vec3)> { + let mut result = Vec::new(); + for (_, e) in mesh.edges.iter().enumerate().filter(|(i, _)| mesh.shaded_edge_visible(*i)) { + result.extend(e.windows(2).filter_map(|w| Some((*w.first()?, *w.get(1)?)))); + } + let mut adjacent: BTreeMap<_, (Vec3, Vec3, bool, bool, usize)> = BTreeMap::new(); + for indices in &mesh.triangles { + let Some([a, b, c]) = mesh.tri(indices) else { continue }; + let n = (b - a).cross(c - a); + let toward = if cam.fov > 0.0 { cam.eye() - (a + b + c) / 3.0 } else { cam.basis().2 }; + let front = n.dot(toward) > 0.0; + for (a, b) in [(a, b), (b, c), (c, a)] { + let (ka, kb) = (key(a, eps), key(b, eps)); + let k = if ka < kb { (ka, kb) } else { (kb, ka) }; + let e = adjacent.entry(k).or_insert((a, b, false, false, 0)); + e.2 |= front; + e.3 |= !front; + e.4 += 1; + } + } + for (_, (a, b, front, back, n)) in adjacent { + if (front && back) || n == 1 { + result.push((a, b)); + } + } + result +} + +pub(super) fn drawing(meshes: &[Mesh], cam: &Camera) -> Result, &'static str> { + let (right, up, back) = cam.basis(); + let scale = meshes.iter().fold(Aabb3::EMPTY, |b, m| b.union(&m.bounds())).diagonal().max(1.0); + let eps = scale * 1e-8; + let project = |p: Vec3| -> Result { + if !p.is_finite() { + return Err("model contains invalid coordinates"); + } + let d = p - cam.target; + let z = d.dot(back); + let projected = if cam.fov > 0.0 { + let w = cam.distance - z; + if w <= cam.distance * 1e-6 { + return Err("model crosses the camera eye plane; zoom out before exporting"); + } + Vec3::new(d.dot(right) * cam.distance / w, d.dot(up) * cam.distance / w, 1.0 / w) + } else { + Vec3::new(d.dot(right), d.dot(up), z) + }; + if !projected.is_finite() || projected.len() > 1e12 { + return Err("projected coordinates exceed the export range"); + } + Ok(projected) + }; + let mut triangles = Vec::new(); + let mut segments = Vec::new(); + for m in meshes { + for t in &m.triangles { + if let Some([a, b, c]) = m.tri(t) { + let p = [project(a)?, project(b)?, project(c)?]; + triangles.push(Triangle { p, bounds: bounds(p) }); + } + } + for (a, b) in edges(m, cam, eps) { + let (a, b) = (project(a)?, project(b)?); + if xy(a).dist(xy(b)) > eps { + segments.push((a, b)); + } + } + } + let tree = Tree::new(triangles); + let depth_eps = if cam.fov > 0.0 { 1e-8 / cam.distance } else { eps }; + let mut result = Vec::new(); + let mut budget = 20_000_000usize; + for (a, b) in segments { + let mut spans = Vec::new(); + tree.intervals(a, b, &bounds([a, b]), depth_eps, &mut spans, &mut budget)?; + spans.sort_unstable_by(|a, b| a.0.total_cmp(&b.0)); + let mut merged: Vec<(f64, f64)> = Vec::new(); + for (lo, hi) in spans { + if let Some(last) = merged.last_mut().filter(|last| lo <= last.1 + 1e-9) { + last.1 = last.1.max(hi); + } else { + merged.push((lo, hi)); + } + } + let mut emit = |lo: f64, hi: f64, hidden: bool| { + let (a, b) = (xy(a + (b - a) * lo), xy(a + (b - a) * hi)); + if a.dist(b) <= eps { + return; + } + result.push(Line { a, b, hidden }); + }; + let mut cursor = 0.0; + for (lo, hi) in merged { + emit(cursor, lo, false); + emit(lo, hi, true); + cursor = hi; + } + emit(cursor, 1.0, false); + if result.len() > 1_000_000 { + return Err("view too complex to export; hide some bodies"); + } + } + Ok(merge_lines(result, eps)) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn a_visible_edge_overrides_only_the_overlapping_part_of_a_hidden_edge() { + let lines = + vec![Line { a: Vec2::ZERO, b: Vec2::new(10., 0.), hidden: true }, Line { a: Vec2::new(3., 0.), b: Vec2::new(7., 0.), hidden: false }]; + let merged = merge_lines(lines, 1e-8); + assert_eq!(merged.len(), 3); + let length = |hidden| merged.iter().filter(|l| l.hidden == hidden).map(|l| l.a.dist(l.b)).sum::(); + assert!((length(false) - 4.).abs() < 1e-8 && (length(true) - 6.).abs() < 1e-8); + } + #[test] + fn a_line_is_split_at_triangle_boundaries_and_depth_crossings() { + let t = [Vec3::new(0., 0., 1.), Vec3::new(2., 0., 1.), Vec3::new(0., 2., 1.)]; + let (lo, hi) = occluded(Vec3::new(-1., 0.5, 0.), Vec3::new(3., 0.5, 0.), t, 0.).unwrap(); + assert!((lo - 0.25).abs() < 1e-9 && (hi - 0.625).abs() < 1e-9); + assert!(occluded(Vec3::new(0., 0.5, 2.), Vec3::new(1., 0.5, 2.), t, 0.).is_none()); + let (lo, hi) = occluded(Vec3::new(0., 0.5, 0.), Vec3::new(1., 0.5, 2.), t, 0.).unwrap(); + assert!(lo.abs() < 1e-9 && (hi - 0.5).abs() < 1e-9); + } +} diff --git a/crates/engine/src/cmd/view_dxf_tests.rs b/crates/engine/src/cmd/view_dxf_tests.rs new file mode 100644 index 000000000..3b6242a63 --- /dev/null +++ b/crates/engine/src/cmd/view_dxf_tests.rs @@ -0,0 +1,102 @@ +use super::*; +use solidcraft_geom::{Vec2, Vec3}; +use solidcraft_render::StandardView; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap() +} +fn sample() -> Session { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length":40,"width":30,"height":10,"body_name":"Plate"})); + // A blind hole on the bottom, completely hidden from above. + run(&mut s, "solid.cylinder", json!({"radius":3,"height":4,"base":[10,10,0],"operation":"cut","targets":["Plate"]})); + s +} +fn camera(view: StandardView) -> Camera { + let mut c = Camera { target: Vec3::new(20., 15., 5.), fov: 0., distance: 150., ..Default::default() }; + c.set_view(view); + c +} +fn export(s: &mut Session, c: Camera, hidden: &str) -> Value { + run(s, CMD, json!({"camera":c,"hidden":hidden})) +} + +#[test] +fn view_dxf_blind_back_hole_is_omitted_or_dashed_and_front_hole_is_visible() { + let mut s = sample(); + let undo = s.undo.len(); + let doc = s.doc.clone(); + let top = export(&mut s, camera(StandardView::Top), "omit"); + let dashed = export(&mut s, camera(StandardView::Top), "dashed"); + assert!(top["visible"].as_u64().unwrap() > 0); + assert_eq!(top["hidden"], 0); + assert!(dashed["hidden"].as_u64().unwrap() > 12, "{dashed}"); + assert_eq!(top["visible"], dashed["visible"]); + assert!(!top["dxf"].as_str().unwrap().contains("HIDDEN")); + assert!(dashed["dxf"].as_str().unwrap().contains("LWPOLYLINE")); + assert!(dashed["dxf"].as_str().unwrap().contains("128\n")); + let bottom = export(&mut s, camera(StandardView::Bottom), "omit"); + assert!(bottom["visible"].as_u64().unwrap() > top["visible"].as_u64().unwrap()); + assert_eq!(s.undo.len(), undo); + assert!(std::sync::Arc::ptr_eq(&doc, &s.doc)); +} + +#[test] +fn view_dxf_respects_hidden_bodies_mm_and_camera_roll() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length":40,"width":30,"height":10,"body_name":"Plate"})); + run(&mut s, "solid.box", json!({"length":5,"width":5,"height":5,"corner":[100,0,0],"body_name":"Other"})); + run(&mut s, "browser.visibility", json!({"items":["Other"],"visible":false})); + let mut c = camera(StandardView::Top); + let drawing = export(&mut s, c, "omit"); + let size = |v: &Value| { + let mut points = Vec::new(); + for g in solidcraft_io::read_dxf(v["dxf"].as_str().unwrap()).unwrap() { + if let solidcraft_io::Geom2::Line(a, b) = g { + points.extend([a, b]); + } + } + let min = points.iter().fold(Vec2::new(f64::INFINITY, f64::INFINITY), |a, p| Vec2::new(a.x.min(p.x), a.y.min(p.y))); + let max = points.iter().fold(Vec2::new(f64::NEG_INFINITY, f64::NEG_INFINITY), |a, p| Vec2::new(a.x.max(p.x), a.y.max(p.y))); + max - min + }; + let d = size(&drawing); + assert!((d.x - 40.).abs() < 0.001 && (d.y - 30.).abs() < 0.001, "{d:?}"); + c.roll = std::f64::consts::FRAC_PI_2; + let d = size(&export(&mut s, c, "omit")); + assert!((d.x - 30.).abs() < 0.001 && (d.y - 40.).abs() < 0.001, "{d:?}"); + run(&mut s, "browser.visibility", json!({"items":["Plate"],"visible":false})); + assert!(s.execute(CMD, &json!({"camera":c})).is_err()); +} + +#[test] +fn view_dxf_cylinders_have_side_silhouettes_and_perspective_is_supported() { + let mut s = Session::default(); + run(&mut s, "solid.cylinder", json!({"radius":10,"height":20})); + let mut c = camera(StandardView::Front); + c.target = Vec3::new(0., 0., 10.); + let v = export(&mut s, c, "omit"); + let lines = solidcraft_io::read_dxf(v["dxf"].as_str().unwrap()).unwrap(); + assert!(lines.iter().filter(|g| matches!(g,solidcraft_io::Geom2::Line(a,b) if (a.y-b.y).abs()>19.9)).count() >= 2); + c.fov = 0.6; + let v = export(&mut s, c, "dashed"); + assert_eq!(v["projection"], "perspective"); + assert!(v["visible"].as_u64().unwrap() > 0); +} + +#[test] +fn view_dxf_rejects_invalid_options_and_near_eye_geometry_without_panicking() { + let mut s = sample(); + for extra in [json!({"hidden":"all"}), json!({"hidden":true}), json!({"tolerance":0}), json!({"tolerance":"x"}), json!({"path":false})] { + let mut p = extra; + p["camera"] = json!(camera(StandardView::Top)); + assert!(s.execute(CMD, &p).is_err(), "{p}"); + } + assert!(s.execute(CMD, &json!({})).is_err()); + let mut c = camera(StandardView::Top); + c.fov = 0.5; + c.distance = 1.; + assert!(s.execute(CMD, &json!({"camera":c})).is_err()); + c.fov = 4.; + assert!(s.execute(CMD, &json!({"camera":c})).is_err()); +} diff --git a/crates/engine/src/tests/path_scope.rs b/crates/engine/src/tests/path_scope.rs index 3f2961a10..ebab2546a 100644 --- a/crates/engine/src/tests/path_scope.rs +++ b/crates/engine/src/tests/path_scope.rs @@ -29,6 +29,7 @@ fn file_commands_stay_inside_the_agents_folders() { ("file.save_as", json!({"path": at(&out, "x.solidcraft")})), ("file.save", json!({"path": at(&root, "../out/x.solidcraft")})), ("file.export", json!({"path": at(&out, "x.stl")})), + ("file.export_view_dxf", json!({"path": at(&out, "x.dxf"),"camera":render::Camera::default()})), ("file.export", json!({"path": at(&out, "x.json"), "format": "json"})), ("file.save_as", json!({"path": at(&out, "x.json"), "format": "json", "preview": true})), ("parameters.export", json!({"path": at(&out, "x.csv")})), diff --git a/crates/io/src/dxf_out.rs b/crates/io/src/dxf_out.rs index 465698959..bba7f8476 100644 --- a/crates/io/src/dxf_out.rs +++ b/crates/io/src/dxf_out.rs @@ -22,6 +22,8 @@ pub enum DxfLinetype { Continuous, /// AutoCAD's DASHED: a dash of 12.7 mm and a gap of 6.35 mm. Dashed, + /// Short 2 mm dashes and 1 mm gaps for hidden edges in millimetre drawings. + Hidden, } impl DxfLinetype { @@ -29,6 +31,7 @@ impl DxfLinetype { match self { DxfLinetype::Continuous => "Continuous", DxfLinetype::Dashed => "DASHED", + DxfLinetype::Hidden => "HIDDEN", } } } @@ -57,6 +60,10 @@ impl DxfLayer { #[derive(Clone, Debug, PartialEq)] pub enum DxfShape { Line(Vec2, Vec2), + /// Connected straight segments, with continuous linetype generation through the vertices. + Polyline { + points: Vec, + }, Circle { c: Vec2, r: f64, @@ -207,6 +214,7 @@ impl DxfShape { fn sample(&self, out: &mut Vec) { match self { DxfShape::Line(a, b) => out.extend([*a, *b]), + DxfShape::Polyline { points } => out.extend(points.iter().copied()), DxfShape::Circle { c, r } => out.extend([*c - Vec2::new(*r, *r), *c + Vec2::new(*r, *r)]), DxfShape::Arc { c, r, a0, a1 } => { let sweep = (a1 - a0).rem_euclid(360.0); @@ -348,12 +356,15 @@ pub fn write_dxf_drawing(layers: &[DxfLayer], entities: &[DxfEntity]) -> String o.code(2, "TABLES"); // The three every drawing has, and DASHED, which the dashed layers name: dash and gap lengths // (a gap is negative) after the pattern's total. - let linetypes: [(&str, &str, &[f64]); 4] = [ + let mut linetypes: Vec<(&str, &str, &[f64])> = vec![ ("ByBlock", "", &[]), ("ByLayer", "", &[]), ("Continuous", "Solid line", &[]), ("DASHED", "Dashed __ __ __ __ __ __ __ __ __ __", &[12.7, -6.35]), ]; + if layer_list.iter().any(|l| l.linetype == DxfLinetype::Hidden) { + linetypes.push(("HIDDEN", "Hidden edges", &[2.0, -1.0])); + } let t = o.table("LTYPE", linetypes.len()); for (name, description, pattern) in linetypes { o.record("LTYPE", "AcDbLinetypeTableRecord", &t); @@ -414,6 +425,7 @@ pub fn write_dxf_drawing(layers: &[DxfLayer], entities: &[DxfEntity]) -> String for e in entities { let kind = match &e.shape { DxfShape::Line(..) => "LINE", + DxfShape::Polyline { .. } => "LWPOLYLINE", DxfShape::Circle { .. } => "CIRCLE", DxfShape::Arc { .. } => "ARC", DxfShape::Ellipse { .. } => "ELLIPSE", @@ -427,6 +439,16 @@ pub fn write_dxf_drawing(layers: &[DxfLayer], entities: &[DxfEntity]) -> String o.code(100, "AcDbEntity"); o.code(8, if e.layer.trim().is_empty() { "0" } else { e.layer.as_str() }); match &e.shape { + DxfShape::Polyline { points } => { + o.code(100, "AcDbPolyline"); + o.code(90, points.len()); + // Autodesk DXF reference: bit 128 (PLINEGEN) continues the dash pattern. + o.code(70, 128); + for p in points { + o.num(10, p.x); + o.num(20, p.y); + } + } DxfShape::Line(a, b) => { o.code(100, "AcDbLine"); o.point(10, *a); @@ -811,6 +833,21 @@ mod tests { ); } + #[test] + fn hidden_polylines_continue_short_dashes_across_chords_and_round_trip() { + let points = vec![Vec2::ZERO, Vec2::new(1., 0.), Vec2::new(2., 1.), Vec2::new(3., 1.)]; + let layer = DxfLayer { linetype: DxfLinetype::Hidden, ..DxfLayer::new("HIDDEN", 8) }; + let text = write_dxf_drawing(&[layer], &[DxfEntity { layer: "HIDDEN".into(), shape: DxfShape::Polyline { points } }]); + let records = entities(&text); + assert_eq!(records[0].0, "LWPOLYLINE"); + assert_eq!(field(&records[0].1, 70), "128"); + assert_eq!(field(&records[0].1, 90), "4"); + let types = table_records(&pairs(&text), "LTYPE"); + let hidden = types.iter().find(|r| field(r, 2) == "HIDDEN").unwrap(); + assert_eq!(hidden.iter().filter(|(c, _)| *c == 49).map(|(_, v)| v.parse::().unwrap()).collect::>(), [2., -1.]); + assert_eq!(read_dxf(&text).unwrap().len(), 3); + } + #[test] fn text_is_centred_on_its_point_and_the_reader_gets_it_back() { let at = Vec2::new(30.0, 12.0); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 473050327..280c19731 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -258,6 +258,9 @@ pub enum Kind { /// Surface tools and Split Face (`dialogs_surface`). Surface(crate::dialogs_surface::Surf), SaveMesh(crate::dialogs_save_mesh::SaveMesh), + ViewDxf { + dashed: bool, + }, /// Plastic features (`dialogs_plastic`). Plastic(crate::dialogs_plastic::Pl), /// Appearance (`dialogs_appearance`). @@ -609,6 +612,7 @@ impl Dialog { .or_else(|| crate::dialogs_sheet::start(app, id)) .or_else(|| crate::dialogs_surface::start(app, id)) .or_else(|| crate::dialogs_save_mesh::start(app, id)) + .or_else(|| crate::dialogs_view_dxf::start(app, id)) .or_else(|| crate::dialogs_plastic::start(app, id)) .or_else(|| crate::dialogs_appearance::start(app, id)) .or_else(|| crate::dialogs_motion::start(app, id)) @@ -1379,6 +1383,7 @@ fn title(k: &Kind) -> &'static str { Kind::Sheet(k) => k.title(), Kind::Surface(k) => k.title(), Kind::SaveMesh(_) => "SAVE AS MESH", + Kind::ViewDxf { .. } => "Export Current View as DXF", Kind::Plastic(k) => k.title(), Kind::Appearance(_) => "APPEARANCE", Kind::Motion(k) => k.title(), @@ -2773,6 +2778,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { Kind::Surface(k) => enter |= crate::dialogs_surface::rows(ui, k), Kind::SketchModify(k) => enter |= crate::sketch_modify_ui::rows(ui, k), Kind::SaveMesh(k) => enter |= crate::dialogs_save_mesh::rows(app, ui, k), + Kind::ViewDxf { dashed } => crate::dialogs_view_dxf::rows(app, ui, dashed), Kind::Plastic(k) => enter |= crate::dialogs_plastic::rows(app, ui, k, &d.inputs), 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), @@ -2835,6 +2841,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { let raw_label = match &d.kind { Kind::ConfirmDelete { .. } => "Delete", Kind::SaveMesh(k) => crate::dialogs_save_mesh::button(k), + Kind::ViewDxf { .. } => "Export DXF…", _ => "OK", }; let label = tr(raw_label); @@ -3278,6 +3285,9 @@ fn sels(d: &Dialog, i: usize) -> &[Sel] { } pub(crate) fn run_dialog(app: &mut SolveApp, d: &Dialog) -> Result<(), String> { + if let Kind::ViewDxf { dashed } = &d.kind { + return crate::dialogs_view_dxf::run(app, *dashed); + } // Saving asks for a file name first; `Err("")` is the user backing out of that. if let Kind::SaveMesh(k) = &d.kind { return crate::dialogs_save_mesh::run(app, k, &d.inputs); @@ -3975,6 +3985,7 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result, S Kind::Surface(k) => return crate::dialogs_surface::commands(app, k, &d.inputs, &d.extra), Kind::SketchModify(k) => return crate::sketch_modify_ui::commands(app, k, &d.inputs, &d.extra), Kind::SaveMesh(k) => return crate::dialogs_save_mesh::commands(k, &d.inputs), + Kind::ViewDxf { .. } => return Ok(Vec::new()), Kind::Plastic(k) => return crate::dialogs_plastic::commands(app, k, &d.inputs, &d.extra), Kind::Appearance(k) => return Ok(crate::dialogs_appearance::commands(k, &d.inputs)), Kind::Motion(k) => return crate::dialogs_motion::commands(app, k, &d.inputs), diff --git a/crates/ui-egui/src/dialogs_view_dxf.rs b/crates/ui-egui/src/dialogs_view_dxf.rs new file mode 100644 index 000000000..cbf0222b1 --- /dev/null +++ b/crates/ui-egui/src/dialogs_view_dxf.rs @@ -0,0 +1,88 @@ +//! Export the camera at the instant Export is pressed, with a remembered hidden-edge choice. +use crate::{SolveApp, dialogs::Kind, selection::SelInput}; +use serde_json::json; + +pub fn start(app: &SolveApp, id: &str) -> Option<(Kind, Vec)> { + (id == "file.export_view_dxf").then(|| (Kind::ViewDxf { dashed: app.preferences.view_dxf_dashed }, Vec::new())) +} + +pub fn rows(app: &SolveApp, ui: &mut egui::Ui, dashed: &mut bool) { + crate::dialogs::row_label(ui, "Hidden edges"); + ui.vertical(|ui| { + let r = ui.radio_value(dashed, false, app.tr_label("Do not export hidden edges")); + crate::scenario::publish_handle("dialog:dxf:omit", r.rect.center()); + let r = ui.radio_value(dashed, true, app.tr_label("Export hidden edges as dashed lines")); + crate::scenario::publish_handle("dialog:dxf:dashed", r.rect.center()); + }); + ui.end_row(); + crate::dialogs::row_label(ui, "Projection"); + ui.label(app.tr_label(if app.cam.fov > 0.0 { "Current perspective view" } else { "Current orthographic view (1:1 mm)" })); + ui.end_row(); + crate::dialogs::row_label(ui, ""); + ui.label(app.tr_label("Visible bodies only. Curves use line segments (0.01 mm tolerance).")); + ui.end_row(); +} + +pub fn run(app: &mut SolveApp, dashed: bool) -> Result<(), String> { + if crate::viewport::section_plane(app).is_some() { + return Err(app.tr_label("Turn off section analysis before exporting the view.").into()); + } + if !app.session.world_state().bodies.iter().any(|b| app.session.body_visible(&b.name)) { + return Err(app.tr_label("No visible bodies to export.").into()); + } + app.preferences.view_dxf_dashed = dashed; + let camera = app.cam; + app.pick_save(&format!("{}-view.dxf", app.session.doc.name), &["dxf"], move |app, path| { + if let Some(path) = path { + let params = json!({"camera":camera,"hidden":if dashed {"dashed"} else {"omit"},"path":path}); + if app.run("file.export_view_dxf", params).is_ok() { + app.set_status(crate::i18n::format("ui.saved_to", &[("path", &path)]), false); + } + } + }); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use solidcraft_engine::render::StandardView; + + #[test] + fn view_dxf_file_menu_exports_with_the_current_camera_and_remembers_hidden_choice() { + let mut h = crate::scenario::Harness::new(); + h.app.run("solid.box", json!({"length":40,"width":30,"height":10})).unwrap(); + h.app.run("solid.cylinder", json!({"radius":3,"height":4,"base":[10,10,0],"operation":"cut"})).unwrap(); + h.app.cam.fov = 0.0; + h.app.cam.set_view(StandardView::Top); + h.frames(3); + h.step(&json!({"click":{"handle":"appbar:folder"}})).unwrap(); + h.step(&json!({"widget":"Export Current View as DXF…"})).unwrap(); + assert!(matches!(h.app.dialog.as_ref().map(|d| &d.kind), Some(Kind::ViewDxf { dashed: false }))); + h.step(&json!({"click":{"handle":"dialog:dxf:dashed"}})).unwrap(); + let dir = h.dir.clone(); + h.app.services.pick_save = Some(Box::new(move |name, extensions| { + assert!(name.ends_with("-view.dxf")); + assert_eq!(extensions, &["dxf"]); + Box::pin(std::future::ready(Some(dir.join("view.dxf").to_string_lossy().into_owned()))) + })); + h.step(&json!({"click":{"handle":"dialog:Export DXF…"}})).unwrap(); + h.frames(3); + let text = std::fs::read_to_string(h.dir.join("view.dxf")).unwrap(); + assert!(text.contains("LWPOLYLINE") && text.contains("HIDDEN")); + assert!(h.app.dialog.is_none() && h.app.preferences.view_dxf_dashed); + let saved = h.app.prefs(); + let mut restored = SolveApp::new(Default::default(), Default::default()); + restored.load_prefs(&saved); + assert!(restored.preferences.view_dxf_dashed); + h.app.start("file.export_view_dxf"); + h.frames(3); + assert!(matches!(h.app.dialog.as_ref().map(|d| &d.kind), Some(Kind::ViewDxf { dashed: true }))); + h.step(&json!({"click":{"handle":"dialog:dxf:omit"}})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:Export DXF…"}})).unwrap(); + h.frames(3); + let text = std::fs::read_to_string(h.dir.join("view.dxf")).unwrap(); + assert!(!text.contains("LWPOLYLINE") && !text.contains("HIDDEN")); + assert!(!h.app.preferences.view_dxf_dashed); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index b0026ec6e..e90c6e18c 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -35,6 +35,7 @@ pub mod dialogs_save_mesh; pub mod dialogs_sheet; pub mod dialogs_surface; pub mod dialogs_sweep; +pub mod dialogs_view_dxf; pub mod dim_view; #[cfg(test)] mod dimension_create_ui_tests; diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index 6a81f8998..a7c28b5f0 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -328,6 +328,8 @@ pub struct Prefs { /// Save as mesh: the last format (`stl` or `3mf`), whether it was sent to a slicer, which one /// (an installed slicer's id or a program path), and the programs the user added (newest first). pub save_mesh_format: String, + /// Hidden edges in the current-view DXF export (false: omit, true: dashed). + pub view_dxf_dashed: bool, pub save_mesh_send: bool, pub save_mesh_slicer: String, pub custom_slicers: Vec, @@ -420,6 +422,7 @@ impl Default for Prefs { check_updates: true, update: crate::update::Memo::default(), save_mesh_format: "stl".into(), + view_dxf_dashed: false, save_mesh_send: false, save_mesh_slicer: String::new(), custom_slicers: Vec::new(), diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 9ae138f49..c414ceece 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -448,6 +448,10 @@ fn file_menu(app: &mut SolveApp, ctx: &egui::Context) { export(app, "step"); close = true; } + if item_if(ui, app.tr_label("Export Current View as DXF…"), "", shown) { + app.start("file.export_view_dxf"); + close = true; + } if item_if(ui, "Export OBJ…", "", shown) { export(app, "obj"); close = true; diff --git a/docs/features.md b/docs/features.md index 304b2008b..29ae43bca 100644 --- a/docs/features.md +++ b/docs/features.md @@ -1,6 +1,6 @@ # Features -SolidCraft's commands by area, generated by `cargo xtask features` from the command registry (`solidcraft-cli commands`). **376 commands.** Planned (registered, not built yet): 3. 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`). **377 commands.** Planned (registered, not built yet): 3. 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 (102) @@ -323,7 +323,7 @@ SolidCraft's commands by area, generated by `cargo xtask features` from the comm | Compare Bodies | `inspect.compare` | – | | Section Analysis | `inspect.section` | SOLID › INSPECT | -## Files (8) +## Files (9) | Command | Id | Toolbar | |---|---|---| @@ -335,6 +335,7 @@ SolidCraft's commands by area, generated by `cargo xtask features` from the comm | 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) diff --git a/docs/view-dxf.md b/docs/view-dxf.md new file mode 100644 index 000000000..9fa3e3fd5 --- /dev/null +++ b/docs/view-dxf.md @@ -0,0 +1,34 @@ +# Export the current view as DXF + +Choose **File → Export Current View as DXF…**, choose whether to omit hidden edges or +export them as dashed lines, then choose **Export DXF…** and a destination. The hidden-edge +choice is remembered between runs. The Japanese menu is **ファイル → 現在の表示をDXFでエクスポート…**. + +The drawing uses the camera when Export is pressed, including roll, the world's up axis +and perspective. Only shown bodies are exported, at their current component/occurrence +placements. Hidden bodies neither draw nor hide other bodies. The complete projected +geometry is exported, including geometry beyond the viewport's edges. Grid, sketches, +dimensions, selection highlights and other overlays are excluded. Turn off section analysis +before exporting. + +Coordinates are 2D, Z=0, in millimetres. Orthographic views retain 1:1 dimensions in the +view plane. Perspective views retain foreshortening, projected onto the plane through the +camera target; they are intended for illustrations rather than dimensioned fabrication. +Curves and curved silhouettes are approximated with straight segments at a default +model-space chord tolerance of 0.01 mm. This is not an exact analytic curve export. + +The AutoCAD 2000 ASCII DXF contains `VISIBLE` (continuous) and, when requested, `HIDDEN` +(2 mm dashes / 1 mm gaps) layers. Hidden curves use connected `LWPOLYLINE` entities with +continuous linetype generation so the pattern does not restart on each chord. The pattern +is embedded in the file. The polyline flags follow the +[Autodesk DXF reference](https://help.autodesk.com/cloudhelp/2017/ENU/AutoCAD-DXF/files/GUID-748FC305-F3F2-4F74-825A-61F04D757A50.htm). + +Edges are split where another surface occludes them, including partial occlusion by another +body. Hidden edges are never included in omit mode. Triangle diagonals and smooth seams +are excluded; curved-body silhouettes are included. Very complex drawings fail with an +error rather than returning an incomplete export. If geometry crosses the perspective +camera's eye plane, zoom out before exporting. + +Programmatic callers use `file.export_view_dxf` with `camera: Camera`, `hidden: "omit"` or +`"dashed"`, optional `tolerance` (0.0001–1 mm) and optional `path`. Without `path`, the +command returns the DXF text. The command does not modify the design or its undo history. From 4cbf9cf6074c663e28ad6840ad38a2906a4a71c7 Mon Sep 17 00:00:00 2001 From: NOWN-DEV <257771410+NOWN-DEV@users.noreply.github.com> Date: Fri, 16 Oct 2026 02:22:31 +0200 Subject: [PATCH 20/92] Sheet metal: an Edge Flange can choose its own corner relief (#1481) An Edge Flange feature can set the shape and size of the relief at the corners its flanges make, in place of the sheet metal rule's. Design format 24. Co-authored-by: NOWN-DEV Co-Authored-By: Claude Sonnet 5.5 --- assets/locales/de.json | 5 + assets/locales/en.json | 5 + assets/locales/fr.json | 5 + assets/locales/ja.json | 5 + assets/locales/ko.json | 5 + assets/locales/ru.json | 5 + assets/locales/uk.json | 5 + assets/locales/zh.json | 5 + crates/doc/src/document.rs | 9 + crates/doc/src/eval_more.rs | 18 +- crates/doc/src/feature_walk_tests/fixtures.rs | 2 +- .../src/feature_walk_tests/golden_exprs.txt | 3 +- crates/doc/src/format.rs | 49 +++- crates/doc/src/sheet.rs | 59 +++-- crates/doc/src/sheet_convert.rs | 4 +- crates/engine/src/cmd/sheet.rs | 55 ++++- crates/engine/src/cmd/sheet_tests.rs | 220 ++++++++++++++++++ crates/ui-egui/src/dialogs_sheet.rs | 35 ++- crates/ui-egui/src/dialogs_sheet_tests.rs | 72 ++++++ docs/book/src/guide/files.md | 2 +- docs/book/src/guide/sheet-metal.md | 16 ++ docs/design-container.md | 2 +- 22 files changed, 543 insertions(+), 43 deletions(-) diff --git a/assets/locales/de.json b/assets/locales/de.json index a3e96c2bc..5e9164560 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -1011,6 +1011,11 @@ "Inside": "Innen", "Outside": "Außen", "Profiles/Curves": "Profile/Kurven", + "Corner Relief": "Eckenentlastung", + "Notch": "Ausklinkung", + "Round": "Rund", + "Rectangular": "Rechteckig", + "Tear": "Reißen", "update.button": "Update", "update.button_tip": "SolidCraft {version} ist verfügbar", "install.menu": "App installieren…", diff --git a/assets/locales/en.json b/assets/locales/en.json index 6c392dd49..8971a167f 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -977,7 +977,12 @@ "Copy all licences": "Copy all licences", "Copy diagnostic information": "Copy diagnostic information", "Copy report": "Copy report", + "Corner Relief": "Corner Relief", "Corner Relief Shape": "Corner Relief Shape", + "Notch": "Notch", + "Round": "Round", + "Rectangular": "Rectangular", + "Tear": "Tear", "Counterbore depth": "Counterbore depth", "Countersink angle": "Countersink angle", "Create Issue — review draft": "Create Issue — review draft", diff --git a/assets/locales/fr.json b/assets/locales/fr.json index 2cfea4c4e..4ea271819 100644 --- a/assets/locales/fr.json +++ b/assets/locales/fr.json @@ -824,7 +824,12 @@ "Copy all licences": "Copier toutes les licences", "Copy diagnostic information": "Copier les informations de diagnostic", "Copy report": "Copier le rapport", + "Corner Relief": "Dégagement d'angle", "Corner Relief Shape": "Forme du dégagement d'angle", + "Notch": "Encoche", + "Round": "Rond", + "Rectangular": "Rectangulaire", + "Tear": "Déchirure", "Counterbore depth": "Profondeur du lamage", "Countersink angle": "Angle de la fraisure", "Create Issue — review draft": "Créer un ticket — relire le brouillon", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index d338ae8e8..abc53ec22 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -977,7 +977,12 @@ "Copy all licences": "すべてのライセンスをコピー", "Copy diagnostic information": "診断情報をコピー", "Copy report": "レポートをコピー", + "Corner Relief": "コーナーリリーフ", "Corner Relief Shape": "コーナーリリーフ形状", + "Notch": "ノッチ", + "Round": "円形", + "Rectangular": "長方形", + "Tear": "引き裂き", "Counterbore depth": "座ぐり深さ", "Countersink angle": "皿穴角度", "Create Issue — review draft": "Issueを作成 — 下書きの確認", diff --git a/assets/locales/ko.json b/assets/locales/ko.json index 4d5596fb8..ccde07225 100644 --- a/assets/locales/ko.json +++ b/assets/locales/ko.json @@ -1011,6 +1011,11 @@ "Inside": "안쪽", "Outside": "바깥쪽", "Profiles/Curves": "프로파일/곡선", + "Corner Relief": "모서리 릴리프", + "Notch": "노치", + "Round": "원형", + "Rectangular": "직사각형", + "Tear": "찢김", "update.button": "업데이트", "update.button_tip": "SolidCraft {version} 사용 가능", "install.menu": "앱 설치…", diff --git a/assets/locales/ru.json b/assets/locales/ru.json index 70822a6ad..b91b2e89d 100644 --- a/assets/locales/ru.json +++ b/assets/locales/ru.json @@ -795,7 +795,12 @@ "Copy all licences": "Копировать все лицензии", "Copy diagnostic information": "Копировать диагностическую информацию", "Copy report": "Копировать отчёт", + "Corner Relief": "Разгрузка угла", "Corner Relief Shape": "Форма разгрузки угла", + "Notch": "Вырез", + "Round": "Круглая", + "Rectangular": "Прямоугольная", + "Tear": "Разрыв", "Counterbore depth": "Глубина цековки", "Countersink angle": "Угол зенковки", "Create Issue — review draft": "Создать Issue — проверить черновик", diff --git a/assets/locales/uk.json b/assets/locales/uk.json index fd32c912e..2e8234ef8 100644 --- a/assets/locales/uk.json +++ b/assets/locales/uk.json @@ -741,7 +741,12 @@ "Copy all licences": "Копіювати всі ліцензії", "Copy diagnostic information": "Копіювати діагностичну інформацію", "Copy report": "Копіювати звіт", + "Corner Relief": "Полегшення кута", "Corner Relief Shape": "Форма полегшення кута", + "Notch": "Виріз", + "Round": "Круглий", + "Rectangular": "Прямокутний", + "Tear": "Розрив", "Counterbore depth": "Глибина циліндричного розширення", "Countersink angle": "Кут зенкування", "Create Issue — review draft": "Створити повідомлення про проблему — перегляд чернетки", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index bc14ab2b6..6c79eb623 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -975,7 +975,12 @@ "Copy all licences": "复制所有许可证", "Copy diagnostic information": "复制诊断信息", "Copy report": "复制报告", + "Corner Relief": "拐角释放", "Corner Relief Shape": "拐角释放形状", + "Notch": "缺口", + "Round": "圆形", + "Rectangular": "矩形", + "Tear": "撕裂", "Counterbore depth": "沉孔深度", "Countersink angle": "沉头角度", "Create Issue — review draft": "创建 Issue——审阅草稿", diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 89394a899..0463746a2 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -1013,6 +1013,15 @@ pub enum FeatureKind { #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(body)] body: Option, + /// The relief cut where two of this feature's bends meet at a corner of the base, in place + /// of the rule's: `corner_relief_shape` (notch | round | rectangular | tear) and + /// `corner_relief`, the size across. Either one left out follows the rule. + #[serde(default, skip_serializing_if = "Option::is_none")] + corner_relief_shape: Option, + /// Walked last, after the edges' values, so the inputs before it keep their names. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[walk(length = "Corner relief")] + corner_relief: Option, }, /// Flat hems on sheet edges. SheetHem { diff --git a/crates/doc/src/eval_more.rs b/crates/doc/src/eval_more.rs index 6cebb3eeb..e2407d87c 100644 --- a/crates/doc/src/eval_more.rs +++ b/crates/doc/src/eval_more.rs @@ -449,7 +449,7 @@ pub(super) fn sheet_eval( st.sheets.push(sh); Ok(()) } - FeatureKind::SheetFlange { edges, height, angle, radius, position, flip, body } => { + FeatureKind::SheetFlange { edges, height, angle, radius, position, flip, body, corner_relief_shape, corner_relief } => { let i = sheet_for(st, body, edges.first().map(|e| e.point))?; let (h, a) = (val(vals, height, Kind::Length)?, val(vals, angle, Kind::Angle)?); // Each edge's own height and angle, else the feature's. @@ -472,6 +472,20 @@ pub(super) fn sheet_eval( doc.rule_values(vals, &doc.sheet_rule(Some(&rule)))?.bend_radius } }; + // The corner relief these flanges ask for in place of the rule's. + let relief = sheet::ReliefOverride { + shape: match corner_relief_shape { + Some(name) => Some( + sheet::ReliefShape::parse(name) + .ok_or_else(|| DocError::Invalid(format!("unknown corner relief shape `{name}` (notch, round, rectangular or tear)")))?, + ), + None => None, + }, + size: match corner_relief { + Some(e) => Some(val(vals, e, Kind::Length)?), + None => None, + }, + }; let sh = st.sheets.get_mut(i).ok_or_else(|| DocError::Invalid("sheet".into()))?; if sh.flat { return Err(DocError::Invalid("refold the sheet before adding flanges".into())); @@ -483,7 +497,7 @@ pub(super) fn sheet_eval( .map(|(pick, (height, angle))| sheet::EdgeFlange { pick, height, angle }) .collect(); let n0 = sh.flanges.len(); - let (_, notes) = sh.add_flanges_each(&each, rr, position, *flip)?; + let (_, notes) = sh.add_flanges_each(&each, rr, position, *flip, relief)?; if !notes.is_empty() { let notes = notes.join("; "); *warning = Some(match warning.take() { diff --git a/crates/doc/src/feature_walk_tests/fixtures.rs b/crates/doc/src/feature_walk_tests/fixtures.rs index 1b388a61b..eaf315dca 100644 --- a/crates/doc/src/feature_walk_tests/fixtures.rs +++ b/crates/doc/src/feature_walk_tests/fixtures.rs @@ -114,7 +114,7 @@ pub(super) fn fixtures() -> Vec<(&'static str, Value)> { ("sheet_contour", json!({"type": "sheet_contour", "sketch": 1, "curves": ["l1"], "distance": "contour.distance"})), ( "sheet_flange", - json!({"type": "sheet_flange", "edges": [{"point": o, "angle": "flange.e1_angle", "height": "flange.e1_height"}, {"point": o, "angle": null, "height": "flange.e2_height"}], "height": "flange.height", "angle": "flange.angle", "radius": "flange.radius"}), + json!({"type": "sheet_flange", "edges": [{"point": o, "angle": "flange.e1_angle", "height": "flange.e1_height"}, {"point": o, "angle": null, "height": "flange.e2_height"}], "height": "flange.height", "angle": "flange.angle", "radius": "flange.radius", "corner_relief_shape": "round", "corner_relief": "flange.relief"}), ), ("sheet_hem", json!({"type": "sheet_hem", "edges": [o], "length": "hem.length", "gap": "hem.gap"})), ( diff --git a/crates/doc/src/feature_walk_tests/golden_exprs.txt b/crates/doc/src/feature_walk_tests/golden_exprs.txt index ace4b70d2..c21df3236 100644 --- a/crates/doc/src/feature_walk_tests/golden_exprs.txt +++ b/crates/doc/src/feature_walk_tests/golden_exprs.txt @@ -243,7 +243,8 @@ sheet_flange Edge angle = flange.e1_angle (Angle) Edge height = flange.e1_height (Length) Edge height = flange.e2_height (Length) - expressions: flange.height, flange.angle, flange.radius, flange.e1_angle, flange.e1_height, flange.e2_height + Corner relief = flange.relief (Length) + expressions: flange.height, flange.angle, flange.radius, flange.e1_angle, flange.e1_height, flange.e2_height, flange.relief sheet_hem inputs: Length = hem.length (Length) diff --git a/crates/doc/src/format.rs b/crates/doc/src/format.rs index 284d9bf54..1286678bb 100644 --- a/crates/doc/src/format.rs +++ b/crates/doc/src/format.rs @@ -233,13 +233,18 @@ //! read through cadmpeg); its `step` is still the STEP text the file was restated as, so the //! feature's fields are unchanged and version 22 designs need no transformation; 0.13.x asks //! for an update before it meets these imports. +//! - 24: an Edge Flange feature can choose its own corner relief (`corner_relief_shape`: notch, +//! round, rectangular or tear, and `corner_relief`, the size across), for the corners its +//! flanges make. Version 23 designs need no transformation: a feature without them follows the +//! sheet metal rule, as it always did, and saves as before; 0.13.0 (which reads up to 22) asks +//! for an update instead of silently building the rule's relief where a design asks for another. use serde_json::Value; use crate::{DocError, Document, Result}; /// The format this build writes. -pub const FORMAT: u32 = 23; +pub const FORMAT: u32 = 24; pub fn format_string(n: u32) -> String { format!("solidcraft/{n}") @@ -256,7 +261,7 @@ pub fn version_of(s: &str) -> Option { /// JSON-level upgrades: entry `i` turns format `i + 1` into `i + 2`. type JsonStep = fn(&mut Value) -> Result<()>; -const JSON_STEPS: [JsonStep; 22] = [ +const JSON_STEPS: [JsonStep; 23] = [ |_| Ok(()), v2_to_v3, v3_to_v4, @@ -279,6 +284,7 @@ const JSON_STEPS: [JsonStep; 22] = [ |_| Ok(()), |_| Ok(()), |_| Ok(()), + |_| Ok(()), ]; /// Stored face and edge names were worked out from geometry before format 14; they get the @@ -1011,6 +1017,45 @@ fn normalise(d: &mut Document) -> Result<()> { mod tests { use super::*; + /// 24 added the corner relief of an edge flange: a no-op step carries a 23 design up, a flange + /// without a relief of its own saves as before, and one with it is saved under 24 and kept. + #[test] + fn version_twenty_three_designs_open_and_an_edge_flange_relief_is_saved_in_twenty_four() { + assert_eq!(JSON_STEPS.len(), FORMAT as usize - 1, "one upgrade step for each format"); + let flange = |shape: Option<&str>, size: Option<&str>| crate::FeatureKind::SheetFlange { + edges: vec![crate::FlangeEdge::at(solidcraft_geom::Vec3::ZERO)], + height: "10 mm".into(), + angle: "90 deg".into(), + radius: None, + position: "inside".into(), + flip: false, + body: None, + corner_relief_shape: shape.map(Into::into), + corner_relief: size.map(Into::into), + }; + let saved = |document: &Document| -> Value { serde_json::from_str(&document.to_json()).unwrap() }; + // A flange that follows the rule saves neither key, and a design of format 23 opens as it was. + let mut plain = Document::new("A"); + plain.add_feature(flange(None, None), None).unwrap(); + let mut file = saved(&plain); + let feature = file["features"].as_array().and_then(|f| f.last()).cloned().unwrap(); + assert_eq!(feature["type"], "sheet_flange"); + assert!(feature.get("corner_relief_shape").is_none() && feature.get("corner_relief").is_none(), "{feature}"); + file["format"] = Value::from("solidcraft/23"); + let opened = read(&file.to_string()).unwrap(); + assert_eq!(opened.format, format_string(FORMAT)); + assert_eq!(opened.features, plain.features); + // One that chooses its relief says so in the file, which is stamped 24 and keeps it. + let mut own = Document::new("A"); + own.add_feature(flange(Some("round"), Some("6 mm")), None).unwrap(); + let file = saved(&own); + let feature = file["features"].as_array().and_then(|f| f.last()).cloned().unwrap(); + assert_eq!((&feature["corner_relief_shape"], &feature["corner_relief"]), (&Value::from("round"), &Value::from("6 mm"))); + // A build that reads up to 23 asks for an update on that stamp instead of dropping the relief. + assert_eq!(version_of(file["format"].as_str().unwrap_or_default()), Some(FORMAT)); + assert_eq!(read(&file.to_string()).unwrap(), own); + } + #[test] fn version_thirteen_names_keep_their_meaning_under_the_legacy_mark() { let file = serde_json::json!({ diff --git a/crates/doc/src/sheet.rs b/crates/doc/src/sheet.rs index 18d647f71..6538b3bbb 100644 --- a/crates/doc/src/sheet.rs +++ b/crates/doc/src/sheet.rs @@ -361,6 +361,15 @@ impl ReliefShape { } } +/// The corner relief an edge flange feature asks for in place of the rule's. A value left out +/// follows the rule. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct ReliefOverride { + pub shape: Option, + /// How far across the relief is (mm). + pub size: Option, +} + /// A rule's values (mm, unit-less K). #[derive(Clone, Copy, Debug, PartialEq, Serialize)] pub struct RuleValues { @@ -2151,7 +2160,7 @@ impl SheetBody { flip: bool, ) -> Result<(Vec, Vec)> { let each: Vec = picks.iter().map(|&pick| EdgeFlange { pick, height, angle }).collect(); - self.add_flanges_each(&each, radius, position, flip) + self.add_flanges_each(&each, radius, position, flip, ReliefOverride::default()) } /// Edge flanges that each have their own height and angle, in one go: every edge is trimmed @@ -2164,8 +2173,16 @@ impl SheetBody { /// the base that ends beside more of the base gets the rule's bend relief there /// (`relieve_bend_ends`). Where cut-outs have taken part of a picked edge away, the flange /// runs along the stretch they leave nearest the pick and takes its setback off that stretch - /// only; an edge they took whole is refused. - pub fn add_flanges_each(&mut self, edges: &[EdgeFlange], radius: f64, position: &str, flip: bool) -> Result<(Vec, Vec)> { + /// only; an edge they took whole is refused. The corners between these flanges are relieved + /// as the rule says, except where `relief` names another shape or size. + pub fn add_flanges_each( + &mut self, + edges: &[EdgeFlange], + radius: f64, + position: &str, + flip: bool, + relief: ReliefOverride, + ) -> Result<(Vec, Vec)> { if edges.is_empty() || edges.len() > 1000 { return Err(DocError::Invalid("pick 1…1000 edges".into())); } @@ -2293,7 +2310,7 @@ impl SheetBody { for (&i, &free) in made.iter().zip(&freed) { notes.extend(self.relieve_bend_ends(i, free)); } - notes.extend(self.close_corners(&made)); + notes.extend(self.close_corners(&made, relief)); notes.extend(self.close_return_corners(&made)); Ok((made, notes)) } @@ -2711,9 +2728,10 @@ impl SheetBody { out } - /// Close the corners the new flanges make, then cut the rule's relief at each (or tear it). - /// Returns a note for every corner left open, without its relief or not torn. - fn close_corners(&mut self, made: &[usize]) -> Vec { + /// Close the corners the new flanges make, then cut the relief at each (or tear it): the + /// rule's, but for the shape or size `relief` names. Returns a note for every corner left + /// open, without its relief or not torn. + fn close_corners(&mut self, made: &[usize], relief: ReliefOverride) -> Vec { let corners = self.corners(made); let mut notes = Vec::new(); let mut closed = Vec::with_capacity(corners.len()); @@ -2723,7 +2741,7 @@ impl SheetBody { Err(why) => notes.push(format!("the flanges at {} are left open: {why}", self.shown(k.c))), } } - notes.extend(self.relieve_corners(&corners, &closed)); + notes.extend(self.relieve_corners(&corners, &closed, relief)); notes } @@ -2733,16 +2751,18 @@ impl SheetBody { format!("({:.3}, {:.3}, {:.3})", w.x, w.y, w.z) } - /// Cut the rule's relief at each of `corners`, or tear those of them that are `closed`. - /// Returns a note for every corner without its relief or not torn. - fn relieve_corners(&mut self, corners: &[Corner], closed: &[Corner]) -> Vec { + /// Cut the relief at each of `corners`, or tear those of them that are `closed`: the rule's, + /// but for the shape or size `relief` names. Returns a note for every corner without its + /// relief or not torn. + fn relieve_corners(&mut self, corners: &[Corner], closed: &[Corner], relief: ReliefOverride) -> Vec { let mut notes = Vec::new(); - match self.relief { + let (shape, size) = (relief.shape.unwrap_or(self.relief), relief.size.unwrap_or(self.relief_size)); + match shape { ReliefShape::Notch => {} // The reliefs come last: they move the bends' ends, which is how the corners were found. ReliefShape::Round | ReliefShape::Rectangular => { for k in corners { - if let Err(why) = self.relieve_corner(k, corners) { + if let Err(why) = self.relieve_corner(k, corners, shape, size) { notes.push(format!("no corner relief at {}: {why}", self.shown(k.c))); } } @@ -2918,7 +2938,7 @@ impl SheetBody { Ok(()) } - /// Cut the rule's relief where two bends meet at a corner of the base, `relief_size / 2` + /// 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 @@ -2928,8 +2948,7 @@ impl SheetBody { /// 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]) -> std::result::Result<(), String> { - let size = self.relief_size; + fn relieve_corner(&mut 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")); } @@ -2961,7 +2980,7 @@ 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 self.relief { + let (relief, reach) = match shape { ReliefShape::Notch | ReliefShape::Tear => return Ok(()), ReliefShape::Round => (vec![Seg2::Arc { center: c, radius: r, start: da.angle(), sweep: -alpha }], r), ReliefShape::Rectangular => { @@ -6075,7 +6094,7 @@ mod tests { /// sheet and the notes on corners left open. fn flanges_each(base: Region2, rv: &RuleValues, each: &[EdgeFlange]) -> (SheetBody, Vec) { let mut s = base_flange("Body1", "AL2", rv, Plane::XY, base); - let notes = s.add_flanges_each(each, rv.bend_radius, "inside", false).unwrap().1; + let notes = s.add_flanges_each(each, rv.bend_radius, "inside", false, ReliefOverride::default()).unwrap().1; (s, notes) } @@ -6630,7 +6649,7 @@ mod tests { let (mut s, _) = tray(&rv, 90.0, 20.0); let each: Vec = (0..4).map(|i| EdgeFlange { pick: far_edge_pick(&s, i, true), height: 12.0, angle: [90f64, 70.0][i % 2].to_radians() }).collect(); - let (made, notes) = s.add_flanges_each(&each, 1.0, "inside", false).unwrap(); + let (made, notes) = s.add_flanges_each(&each, 1.0, "inside", false, ReliefOverride::default()).unwrap(); assert!(notes.is_empty() && made == [4, 5, 6, 7], "{made:?} {notes:?}"); for (a, a_end, b, b_end) in TRAY_RETURNS { let (fa, fb) = (&s.flanges[a], &s.flanges[b]); @@ -6803,7 +6822,7 @@ mod tests { EdgeFlange { pick: far_edge_pick(&s, i, true), height: 12.0, angle: deg.to_radians() } }) .collect(); - let (_, notes) = s.add_flanges_each(&each, 1.0, "inside", false).unwrap(); + let (_, notes) = s.add_flanges_each(&each, 1.0, "inside", false, ReliefOverride::default()).unwrap(); assert!(notes.is_empty(), "{what}: {notes:?}"); returns_keep_out_of_the_walls(&s, &what); holds_the_flat_material(&s, &what); diff --git a/crates/doc/src/sheet_convert.rs b/crates/doc/src/sheet_convert.rs index 82add169f..660dae183 100644 --- a/crates/doc/src/sheet_convert.rs +++ b/crates/doc/src/sheet_convert.rs @@ -53,7 +53,7 @@ use std::f64::consts::{FRAC_PI_2, PI, TAU}; use solidcraft_geom::{Loop2, Mesh, Plane, Region2, Seg2, Vec2, Vec3}; use solidcraft_kernel::{Body, FaceSurface, face_surface}; -use super::{FlatWork, RuleValues, SheetBody, SheetFlange, base_flange, point_in, polys_cross, signed_area, snap}; +use super::{FlatWork, ReliefOverride, RuleValues, SheetBody, SheetFlange, base_flange, point_in, polys_cross, signed_area, snap}; use crate::{DocError, ModelBody, Result, apply_point, mat_inverse}; const MAX_BENDS: usize = 1000; @@ -1002,7 +1002,7 @@ pub fn convert_body(mb: &ModelBody, rule: &str, rv: &RuleValues, face: Vec3, ben Err(why) => notes.push(format!("the corner at {} stays cut open: {why}", sh.shown(k.c))), } } - notes.extend(sh.relieve_corners(&corners, &closed)); + notes.extend(sh.relieve_corners(&corners, &closed, ReliefOverride::default())); Ok((sh, notes)) } diff --git a/crates/engine/src/cmd/sheet.rs b/crates/engine/src/cmd/sheet.rs index 396e2f9f2..0d0d55a16 100644 --- a/crates/engine/src/cmd/sheet.rs +++ b/crates/engine/src/cmd/sheet.rs @@ -17,8 +17,11 @@ pub static COMMANDS: &[CommandSpec] = &[ "base: sketch + profiles? (rule?, flip?) | contour: sketch + curves (open chain of lines) + distance (rule?, flip?, reverse?) | \ edge: edges: [[x,y,z] on top/bottom edges, or {point: [x,y,z], angle?, height?} for an edge with its own angle and height] + \ height (to the outer face), angle? (default 90 deg), radius? (default: rule), \ - position?: inside|outside|middle, flip?, body?; type?: base|edge|contour (default from the inputs); name?, body_name? (the new body). \ - Thickness, K-factor and bend radius come from the rule (sheet.manage_rules); passing them here is refused", + position?: inside|outside|middle, flip?, body?, corner_relief_shape?: notch|round|rectangular|tear and corner_relief? (size across): \ + the relief at the corners these flanges make (default: the rule's); \ + type?: base|edge|contour (default from the inputs); name?, body_name? (the new body). \ + Thickness, K-factor and bend radius come from the rule (sheet.manage_rules); passing them here is refused, \ + and so is the corner relief on a base or contour flange", ), CommandSpec::new("sheet.perforate", "Perforate", perforate).at("SHEET METAL", "CREATE").icon("hem").params( "diameter, pitch: expr; margin?: expr (clear of edges, cut-outs and bends; default: the diameter); pattern?: staggered (60°, default) | square; body? - a perforation field over the whole flat sheet: holes in the flat pattern (perforations), the DXF (layer PERFORATION) and the measured volume, not cut into the B-rep (#732)", @@ -133,10 +136,20 @@ fn rule_param(s: &Session, p: &Value, cmd: &str) -> Result> { const RULE_ONLY: [&str; 8] = ["thickness", "k_factor", "bend_radius", "relief_width", "relief_depth", "corner_relief", "corner_relief_shape", "hem_gap"]; +/// The two rule values an edge flange may set for itself: the corner relief. +const EDGE_RELIEF: [&str; 2] = ["corner_relief", "corner_relief_shape"]; + fn flange(s: &mut Session, p: &Value) -> Result { let cmd = "sheet.flange"; let nested = p.get("base").filter(|b| b.is_object()); - if let Some(key) = RULE_ONLY.iter().find(|k| p.get(**k).is_some() || nested.is_some_and(|b| b.get(**k).is_some())) { + let ty = match str_(p, "type") { + Some(t) => t.to_ascii_lowercase(), + None if p.get("edges").is_some() => "edge".into(), + None if p.get("curves").is_some() => "contour".into(), + None => "base".into(), + }; + let refused = |k: &&&str| !(ty == "edge" && EDGE_RELIEF.contains(*k)); + if let Some(key) = RULE_ONLY.iter().filter(refused).find(|k| p.get(**k).is_some() || nested.is_some_and(|b| b.get(**k).is_some())) { return Err(bad( cmd, format!( @@ -145,12 +158,6 @@ fn flange(s: &mut Session, p: &Value) -> Result { ), )); } - let ty = match str_(p, "type") { - Some(t) => t.to_ascii_lowercase(), - None if p.get("edges").is_some() => "edge".into(), - None if p.get("curves").is_some() => "contour".into(), - None => "base".into(), - }; match ty.as_str() { "base" => { let sketch = feature_sketch(s, p, cmd)?; @@ -194,7 +201,35 @@ fn flange(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, "`position` must be inside, outside or middle")); } let body = str_(p, "body").map(str::to_string); - add_feature(s, p, FeatureKind::SheetFlange { edges, height, angle, radius, position, flip: bool_(p, "flip").unwrap_or(false), body }) + // The corner relief these flanges make, in place of the rule's; null is not given. + let corner_relief_shape = match p.get("corner_relief_shape").filter(|v| !v.is_null()) { + Some(v) => Some( + v.as_str() + .and_then(solidcraft_doc::sheet::ReliefShape::parse) + .map(|shape| shape.name().to_string()) + .ok_or_else(|| bad(cmd, "`corner_relief_shape` must be notch, round, rectangular or tear"))?, + ), + None => None, + }; + let corner_relief = expr(p, "corner_relief"); + if let Some(c) = &corner_relief { + check_expr(s, c, Kind::Length, cmd, "corner_relief")?; + } + add_feature( + s, + p, + FeatureKind::SheetFlange { + edges, + height, + angle, + radius, + position, + flip: bool_(p, "flip").unwrap_or(false), + body, + corner_relief_shape, + corner_relief, + }, + ) } other => Err(bad(cmd, format!("unknown flange type `{other}` (base, edge or contour)"))), } diff --git a/crates/engine/src/cmd/sheet_tests.rs b/crates/engine/src/cmd/sheet_tests.rs index a48f42545..96f53ba00 100644 --- a/crates/engine/src/cmd/sheet_tests.rs +++ b/crates/engine/src/cmd/sheet_tests.rs @@ -3082,6 +3082,226 @@ fn the_corner_relief_shape_is_a_rule_setting_checked_and_undone() { assert!(w.contains("would take a whole bend away") && volume(&mut s) == v0, "{w}"); } +/// A 120 x 90 base in 2 mm aluminium (R 1, K 0.5, gap 0.5; `rule` adds to its settings) with two edge +/// flange features, 20 high at 90°: `near` on the bottom and left edges, which meet at the corner at +/// the origin, and `far` on the top and right edges, which meet at the corner at (120, 90). The two +/// objects hold what each feature is given besides its edges. +fn two_flange_groups(rule: Value, near: Value, far: Value) -> Session { + let mut s = Session::default(); + 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(&mut s, "sheet.manage_rules", r); + base(&mut s, 120.0, 90.0); + for (edges, own) in [(json!([[60, 0, 2], [0, 45, 2]]), near), (json!([[60, 90, 2], [120, 45, 2]]), far)] { + let mut p = json!({"edges": edges, "height": 20, "angle": "90 deg"}); + if let (Some(p), Some(own)) = (p.as_object_mut(), own.as_object()) { + p.extend(own.clone()); + } + run(&mut s, "sheet.flange", p); + } + s +} + +/// What the DXF of the flat pattern draws of the corner reliefs: the arcs (centre, radius) and the +/// lines' end points. +fn relief_drawing(s: &mut Session) -> (Vec<(solidcraft_geom::Vec2, f64)>, Vec) { + let dxf = run(s, "sheet.export_dxf", json!({}))["dxf"].as_str().unwrap_or_default().to_string(); + let read = solidcraft_io::read_dxf(&dxf).unwrap_or_default(); + let arcs = read.iter().filter_map(|g| if let solidcraft_io::Geom2::Arc { c, a, .. } = g { Some((*c, a.dist(*c))) } else { None }).collect(); + let ends = read.iter().flat_map(|g| if let solidcraft_io::Geom2::Line(a, b) = g { vec![*a, *b] } else { Vec::new() }).collect(); + (arcs, ends) +} + +#[test] +fn each_edge_flange_feature_chooses_the_corner_relief_of_its_own_corners() { + use solidcraft_geom::Vec2; + // At 90° the bends of a corner meet at (s0, s0) in from the sheet's edges, s0 = (R + T)·tan 45° = 3, + // and are BA = π/2·(R + K·T) = π wide. A relief d across reaches r = d/2 along both bends and takes, + // at its corner, r²·π/4 (round) or r² (rectangular) of the base and r of each bend, 2 mm thick. + let (s0, ba) = (3.0, PI); + let at = |ends: &[Vec2], x: f64, y: f64| ends.iter().any(|p| p.dist(Vec2::new(x, y)) < 1e-6); + // The rule says notch, as it does by default: the corners are not relieved. + let mut plain = two_flange_groups(json!({}), json!({}), json!({})); + assert!(no_errors_or_warnings(&plain), "{:?}", plain.model.results); + let v0 = volume(&mut plain); + assert!(relief_drawing(&mut plain).0.is_empty()); + // The flanges at the origin ask for a round 6 mm across, those at (120, 90) for a rectangular 3 mm. + let near = json!({"corner_relief_shape": "round", "corner_relief": "6 mm"}); + let far = json!({"corner_relief_shape": "Rectangular", "corner_relief": "3 mm"}); + let mut s = two_flange_groups(json!({}), near, far); + assert!(no_errors_or_warnings(&s), "{:?}", s.model.results); + let listed = run(&mut s, "sheet.rules", json!({})); + let rule = &listed["rules"][0]; + assert_eq!((&rule["rule"]["corner_relief_shape"], &rule["values"]["corner_relief_shape"]), (&json!("notch"), &json!("notch"))); + // The folded part loses what the two reliefs take. + let (v, want) = (volume(&mut s), ((PI * 9.0 / 4.0 + 6.0 * ba) + (1.5 * 1.5 + 3.0 * ba)) * 2.0); + assert!((v0 - v - want).abs() < 0.1, "{v0} - {v} vs {want}"); + // The DXF: one arc of radius 3 about the corner at the origin and nothing round at the other corner; + // there the relief is a kite ending 1.5 mm in from the corner of the bends, and none at the origin. + let (arcs, ends) = relief_drawing(&mut s); + assert!(arcs.len() == 1 && arcs[0].0.dist(Vec2::new(s0, s0)) < 1e-6 && (arcs[0].1 - 3.0).abs() < 1e-6, "{arcs:?}"); + assert!(at(&ends, 120.0 - s0 - 1.5, 90.0 - s0 - 1.5), "the corner at (120, 90) is relieved with a rectangular relief"); + assert!(!at(&ends, s0 + 1.5, s0 + 1.5), "the corner at the origin is not"); + // Unfolding, refolding and reopening the design keep both. + run(&mut s, "sheet.unfold", json!({})); + run(&mut s, "sheet.refold", json!({})); + assert!((volume(&mut s) - v).abs() < 1e-6 * v); + let mut reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); + assert!((volume(&mut reopened) - v).abs() < 1e-6 * v); + assert_eq!(relief_drawing(&mut reopened).0.len(), 1); + // The size is an input of the feature like its height: another size moves the relief. + let near_feature = s.doc.features.iter().find(|f| matches!(f.kind, solidcraft_doc::FeatureKind::SheetFlange { .. })); + let names = near_feature.map(|f| f.param_names.clone()).unwrap_or_default(); + assert_eq!(names.len(), 3, "height, angle and the relief: {names:?}"); + run(&mut s, "parameters.change", json!({"name": names[2], "expression": "4 mm"})); + let arcs = relief_drawing(&mut s).0; + assert!(arcs.len() == 1 && (arcs[0].1 - 2.0).abs() < 1e-6, "{arcs:?}"); +} + +#[test] +fn an_edge_flange_feature_follows_the_rule_for_the_relief_it_leaves_out() { + use solidcraft_geom::Vec2; + let s0 = 3.0; + let at = |ends: &[Vec2], x: f64, y: f64| ends.iter().any(|p| p.dist(Vec2::new(x, y)) < 1e-6); + let round8 = json!({"corner_relief_shape": "round", "corner_relief": "8 mm"}); + // The rule says a round 8 mm across. A feature that asks for nothing gets it, one that asks for a + // size alone keeps the rule's shape. + let mut s = two_flange_groups(round8.clone(), json!({"corner_relief": "6 mm"}), json!({})); + assert!(no_errors_or_warnings(&s), "{:?}", s.model.results); + let mut arcs = relief_drawing(&mut s).0; + arcs.sort_by(|a, b| a.1.total_cmp(&b.1)); + assert_eq!(arcs.len(), 2, "{arcs:?}"); + assert!(arcs[0].0.dist(Vec2::new(s0, s0)) < 1e-6 && (arcs[0].1 - 3.0).abs() < 1e-6, "{arcs:?}"); + assert!(arcs[1].0.dist(Vec2::new(120.0 - s0, 90.0 - s0)) < 1e-6 && (arcs[1].1 - 4.0).abs() < 1e-6, "{arcs:?}"); + // A shape alone keeps the rule's size. + let mut s = two_flange_groups(round8, json!({"corner_relief_shape": "rectangular"}), json!({})); + assert!(no_errors_or_warnings(&s), "{:?}", s.model.results); + let (arcs, ends) = relief_drawing(&mut s); + assert!(arcs.len() == 1 && arcs[0].0.dist(Vec2::new(120.0 - s0, 90.0 - s0)) < 1e-6 && (arcs[0].1 - 4.0).abs() < 1e-6, "{arcs:?}"); + assert!(at(&ends, s0 + 4.0, s0 + 4.0), "a kite 8 mm across at the origin"); + // A change of the rule still reaches the feature that asks for nothing. + run(&mut s, "sheet.manage_rules", json!({"name": "AL2", "corner_relief": "6 mm"})); + let arcs = relief_drawing(&mut s).0; + assert!(arcs.len() == 1 && (arcs[0].1 - 3.0).abs() < 1e-6, "{arcs:?}"); +} + +#[test] +fn an_edge_flange_feature_can_tear_its_corners_under_a_notch_rule() { + use std::f64::consts::SQRT_2; + // Torn, the two bends of a corner run to the corner of the bends and each is cut straight to its + // flange's end: at 90° it is grow = sin 90° − gap/√2 past the corner, a triangle BA·grow/2 at each of + // the two bend ends, and a corner less at each (see a_tear_of_the_rule_reaches_the_part_the_flat_pattern_and_the_dxf). + let (ba, grow) = (PI, 1.0 - 0.5 / SQRT_2); + let mut notch = two_flange_groups(json!({}), json!({}), json!({})); + let (v0, stepped) = (volume(&mut notch), outline_points(&flat(&mut notch))); + let mut s = two_flange_groups(json!({}), json!({"corner_relief_shape": "tear"}), json!({})); + assert!(no_errors_or_warnings(&s), "{:?}", s.model.results); + let torn = s.model.state().sheets.last().map(|b| b.flanges.iter().map(|f| f.tear).collect::>()).unwrap_or_default(); + assert_eq!(torn.iter().filter(|t| **t != (false, false)).count(), 2, "{torn:?}"); + let want = 2.0 * ba * grow / 2.0 * 2.0; + assert!((volume(&mut s) - v0 - want).abs() < 0.05, "{} - {v0} vs {want}", volume(&mut s)); + assert_eq!(outline_points(&flat(&mut s)).len() + 2, stepped.len()); +} + +#[test] +fn only_an_edge_flange_takes_a_corner_relief_of_its_own() { + 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", "active": true})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Base"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [120, 90]})); + run(&mut s, "sketch.finish", json!({})); + let features = s.doc.features.len(); + // A base flange and a contour flange take their relief from the rule, as before: refused, and + // the message names the key. + for (params, key) in [ + (json!({"sketch": "Base", "corner_relief_shape": "round"}), "corner_relief_shape"), + (json!({"sketch": "Base", "corner_relief": "6 mm"}), "corner_relief"), + (json!({"type": "base", "sketch": "Base", "corner_relief_shape": null}), "corner_relief_shape"), + (json!({"sketch": "Base", "curves": ["l1"], "distance": 10, "corner_relief": "6 mm"}), "corner_relief"), + (json!({"type": "contour", "sketch": "Base", "curves": ["l1"], "distance": 10, "corner_relief_shape": "tear"}), "corner_relief_shape"), + (json!({"base": {"sketch": "Base", "corner_relief": "6 mm"}}), "corner_relief"), + ] { + let e = s.execute("sheet.flange", ¶ms).map(|_| ()).unwrap_err().to_string(); + let today = format!( + "`{key}` is not a sheet.flange parameter: the sheet metal rule sets it. Make a rule with sheet.manage_rules {{name, {key}, …}} and pass its name as `rule`" + ); + assert!(e.contains(&today), "{params}: {e}"); + } + assert_eq!(s.doc.features.len(), features, "a refused flange changes nothing"); + run(&mut s, "sheet.flange", json!({"sketch": "Base"})); + // The rest of the rule stays with the rule for an edge flange as well, and a relief that is no shape + // or no length is refused before anything changes. + let features = s.doc.features.len(); + let edge = |extra: Value| { + let mut p = json!({"edges": [[60, 0, 2], [0, 45, 2]], "height": 20}); + if let (Some(p), Some(extra)) = (p.as_object_mut(), extra.as_object()) { + p.extend(extra.clone()); + } + p + }; + for (extra, want) in [ + (json!({"thickness": "3 mm"}), "`thickness` is not a sheet.flange parameter"), + (json!({"relief_width": "1 mm"}), "`relief_width` is not a sheet.flange parameter"), + (json!({"corner_relief_shape": "star"}), "`corner_relief_shape` must be notch, round, rectangular or tear"), + (json!({"corner_relief_shape": 2}), "`corner_relief_shape` must be notch, round, rectangular or tear"), + (json!({"corner_relief": "wide"}), "corner_relief"), + (json!({"corner_relief": "30 deg"}), "corner_relief"), + ] { + let e = s.execute("sheet.flange", &edge(extra.clone())).map(|_| ()).unwrap_err().to_string(); + assert!(e.contains(want), "{extra}: {e}"); + } + assert_eq!(s.doc.features.len(), features); + // Null is not given: the corners follow the rule. A shape is stored by its name. + run(&mut s, "sheet.flange", edge(json!({"corner_relief_shape": null}))); + let mut torn = edge(json!({"corner_relief_shape": " Tear ", "corner_relief": 5})); + torn["edges"] = json!([[60, 90, 2], [120, 45, 2]]); + run(&mut s, "sheet.flange", torn); + let saved: Value = serde_json::from_str(&s.doc.to_json()).unwrap_or_default(); + let own: Vec<(Value, Value)> = saved["features"] + .as_array() + .cloned() + .unwrap_or_default() + .iter() + .filter(|f| f["type"] == "sheet_flange") + .map(|f| (f["corner_relief_shape"].clone(), f["corner_relief"].clone())) + .collect(); + assert_eq!(own, [(Value::Null, Value::Null), (json!("tear"), json!("5"))]); +} + +#[test] +fn a_corner_relief_of_an_edge_flange_is_saved_with_it_and_designs_without_one_save_as_before() { + let flange_features = |s: &Session| -> Vec { + let saved: Value = serde_json::from_str(&s.doc.to_json()).unwrap_or_default(); + saved["features"].as_array().cloned().unwrap_or_default().into_iter().filter(|f| f["type"] == "sheet_flange").collect() + }; + // Without a relief of its own the feature saves what it always did: neither key. + let plain = two_flange_groups(json!({}), json!({}), json!({})); + let features = flange_features(&plain); + assert_eq!(features.len(), 2); + assert!(features.iter().all(|f| f.get("corner_relief_shape").is_none() && f.get("corner_relief").is_none()), "{features:?}"); + // With one, the file has it and a design read from it builds the same part. + let near = json!({"corner_relief_shape": "round", "corner_relief": "6 mm"}); + let mut s = two_flange_groups(json!({}), near, json!({"corner_relief_shape": "tear"})); + let features = flange_features(&s); + assert_eq!((&features[0]["corner_relief_shape"], &features[0]["corner_relief"]), (&json!("round"), &json!("6 mm"))); + assert_eq!(features[1]["corner_relief_shape"], "tear"); + assert!(features[1].get("corner_relief").is_none(), "{}", features[1]); + let saved = s.doc.to_json(); + let mut reopened = Session::new(solidcraft_doc::Document::from_json(&saved).unwrap()); + assert_eq!(reopened.doc.features, s.doc.features); + assert!((volume(&mut reopened) - volume(&mut s)).abs() < 1e-6); + assert_eq!(relief_drawing(&mut reopened), relief_drawing(&mut s)); + // timeline.edit changes the relief of a saved feature, and null takes it back to the rule's. + let id = s.doc.features.iter().rev().nth(1).map_or(0, |f| f.id); + run(&mut s, "timeline.edit", json!({"feature": id, "set": {"corner_relief_shape": "rectangular"}})); + assert!(relief_drawing(&mut s).0.is_empty()); + run(&mut s, "timeline.edit", json!({"feature": id, "set": {"corner_relief_shape": null, "corner_relief": null}})); + assert!(flange_features(&s)[0].get("corner_relief_shape").is_none()); + assert!(flange_features(&s)[0].get("corner_relief").is_none()); +} + #[test] fn corners_left_open_are_reported_on_the_flange() { let mut s = Session::default(); diff --git a/crates/ui-egui/src/dialogs_sheet.rs b/crates/ui-egui/src/dialogs_sheet.rs index 07c1f0aac..1b52d08d2 100644 --- a/crates/ui-egui/src/dialogs_sheet.rs +++ b/crates/ui-egui/src/dialogs_sheet.rs @@ -35,6 +35,9 @@ const RULE_FIELDS: [(&str, &str); 8] = [ /// The corner relief shapes the manager offers (the rule's `corner_relief_shape`) and their labels. const RELIEF_SHAPES: [&str; 4] = ["notch", "round", "rectangular", "tear"]; const RELIEF_SHAPE_LABELS: [&str; 4] = ["Notch", "Round", "Rectangular", "Tear"]; +/// The corner relief shapes an edge flange offers: the rule's (index 0, nothing of its own), then +/// the shapes of `RELIEF_SHAPES` in order. +const FLANGE_RELIEF_LABELS: [&str; 5] = ["Rule", "Notch", "Round", "Rectangular", "Tear"]; #[derive(Clone, Debug)] pub enum Sm { @@ -52,6 +55,10 @@ pub enum Sm { /// Edge flanges: the edges with an angle and/or a height of their own (the picked point, /// angle, height; an empty text means the dialog's), from the rows per edge. own: Vec<(Vec3, String, String)>, + /// Edge flanges: the corner relief shape of their own (index into `FLANGE_RELIEF_LABELS`; + /// 0 is the rule's) and its size (empty: the rule's). + relief: usize, + relief_size: String, }, Hem { length: String, @@ -134,6 +141,8 @@ fn new_flange(ty: usize) -> Sm { reverse: false, rule: 0, own: Vec::new(), + relief: 0, + relief_size: String::new(), } } @@ -199,7 +208,7 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Sm, inputs: &mut [Sel let t = Tokens::get(); let mut enter = false; match k { - Sm::Flange { ty, height, angle, radius, position, flip, distance, reverse, rule, own } => { + Sm::Flange { ty, height, angle, radius, position, flip, distance, reverse, rule, own, relief, relief_size } => { *ty = flange_type(inputs); row_label(ui, "Type"); ui.label(FLANGE_TYPES.get(*ty).copied().unwrap_or("")); @@ -220,6 +229,15 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Sm, inputs: &mut [Sel crate::params_dialog::complete(ui, &r, radius); enter |= r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)); ui.end_row(); + // The relief at the corners these flanges make: the rule's unless set here. + row_label(ui, "Corner Relief Shape"); + combo(ui, "sm_flange_relief", &FLANGE_RELIEF_LABELS, relief); + ui.end_row(); + row_label(ui, "Corner Relief"); + let r = ui.add(egui::TextEdit::singleline(relief_size).hint_text(crate::i18n::tr_label("from the rule"))); + crate::params_dialog::complete(ui, &r, relief_size); + enter |= r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)); + ui.end_row(); // With several edges, a row for each: an angle and a height of its own, left // empty for the values above (shown as the hints). let points = edge_point_list(inputs); @@ -514,7 +532,7 @@ fn flange_edges(inputs: &[SelInput], own: &[(Vec3, String, String)]) -> Vec) -> Result, String> { let s = &app.session; let (cmd, mut p): (&str, Value) = match k { - Sm::Flange { height, angle, radius, position, flip, distance, reverse, rule, own, .. } => { + Sm::Flange { height, angle, radius, position, flip, distance, reverse, rule, own, relief, relief_size, .. } => { let mut p = match flange_type(inputs) { 1 => { let mut p = json!({"type": "edge", "edges": flange_edges(inputs, own), "height": height, "angle": angle, @@ -522,6 +540,12 @@ pub fn commands(app: &SolveApp, k: &Sm, inputs: &[SelInput], extra: &Map { @@ -667,7 +691,7 @@ pub fn for_feature(app: &SolveApp, kind: &FeatureKind) -> Option<(Kind, Vec { + FeatureKind::SheetFlange { edges, height, angle, radius, position, flip, body, corner_relief_shape, corner_relief } => { if let Some(b) = body { extra.insert("body".into(), json!(b)); } @@ -692,6 +716,11 @@ pub fn for_feature(app: &SolveApp, kind: &FeatureKind) -> Option<(Kind, Vec = [[60.0, 0.0, 2.0], [0.0, 45.0, 2.0]].iter().filter_map(|p| edge_sel(&h.app.session, Vec3::new(p[0], p[1], p[2]))).collect(); + assert_eq!(edges.len(), 2); + h.app.session.selection = edges; + h.app.start("sheet.flange"); + h.frames(3); + let shown = |app: &SolveApp| match app.dialog.as_ref().map(|d| &d.kind) { + Some(Kind::Sheet(Sm::Flange { relief, relief_size, .. })) => Some((*relief, relief_size.clone())), + _ => None, + }; + let relief = |app: &SolveApp| match &app.session.doc.features.last().map(|f| &f.kind) { + Some(FeatureKind::SheetFlange { corner_relief_shape, corner_relief, .. }) => Some((corner_relief_shape.clone(), corner_relief.clone())), + _ => None, + }; + // Untouched, the dialog asks for nothing: the rule's relief. + assert_eq!(shown(&h.app), Some((0, String::new()))); + let d = h.app.dialog.clone().unwrap(); + let c = apply_commands(&h.app, &d).unwrap(); + assert!(c[0].1.get("corner_relief_shape").is_none() && c[0].1.get("corner_relief").is_none(), "{}", c[0].1); + // Round from the selector, 6 mm in the size row. + h.step(&json!({"click": {"handle": "dialog:Corner Relief Shape"}})).unwrap(); + h.step(&json!({"click": {"handle": "dialog:Corner Relief Shape:Round"}})).unwrap(); + assert_eq!(shown(&h.app), Some((2, String::new()))); + if let Some(Kind::Sheet(Sm::Flange { relief_size, .. })) = h.app.dialog.as_mut().map(|d| &mut d.kind) { + *relief_size = "6 mm".into(); + } + let d = h.app.dialog.clone().unwrap(); + let c = apply_commands(&h.app, &d).unwrap(); + assert_eq!((&c[0].1["corner_relief_shape"], &c[0].1["corner_relief"]), (&json!("round"), &json!("6 mm"))); + h.step(&json!({"widget": "OK"})).unwrap(); + assert!(h.app.dialog.is_none(), "{:?}", h.app.dialog); + assert_eq!(relief(&h.app), Some((Some("round".into()), Some("6 mm".into())))); + assert!(h.app.session.model.results.iter().all(|r| r.error.is_none() && r.warning.is_none()), "{:?}", h.app.session.model.results); + let arcs = |app: &SolveApp| { + app.session + .model + .state() + .sheets + .last() + .map(|s| s.base.outer.segs.iter().filter(|g| matches!(g, solidcraft_engine::geom::Seg2::Arc { .. })).count()) + }; + assert_eq!(arcs(&h.app), Some(1), "the round is cut at the one corner the two flanges make"); + // Edit Feature shows both again; Rule and an empty size take the feature back to the rule's relief. + let id = h.app.session.doc.features.last().map(|f| f.id).unwrap(); + let mut e = edit_dialog(&h.app, id, None).unwrap(); + assert!(matches!(&e.kind, Kind::Sheet(Sm::Flange { relief: 2, relief_size, .. }) if relief_size == "6 mm")); + let c = apply_commands(&h.app, &e).unwrap(); + assert_eq!((&c[0].1["params"]["corner_relief_shape"], &c[0].1["params"]["corner_relief"]), (&json!("round"), &json!("6 mm"))); + if let Kind::Sheet(Sm::Flange { relief, relief_size, .. }) = &mut e.kind { + *relief = 0; + relief_size.clear(); + } + let commands = apply_commands(&h.app, &e).unwrap(); + run_all(&mut h.app, commands); + assert_eq!(relief(&h.app), Some((None, None))); + assert_eq!(arcs(&h.app), Some(0)); +} + #[test] fn pocket_depth_labels_follow_inches_without_changing_flat_data() { let mut app = plate(); diff --git a/docs/book/src/guide/files.md b/docs/book/src/guide/files.md index d2c2900dc..32ca2581c 100644 --- a/docs/book/src/guide/files.md +++ b/docs/book/src/guide/files.md @@ -86,7 +86,7 @@ is available. Missing or incompatible pictures use the usual thumbnail generatio The default `cache: false` omits the portable thumbnail too. The repository's `docs/design-container.md` describes limits and encoding details. -Current designs use format 21, including design properties, named render setups, opaque PBR looks, thin extrudes, sheet metal perforation fields, associative editable sketch patterns, editable associative offset-distance dimensions, the style of sketch text (bold, italic, alignment, spacing and the curve it follows), face anchors on a piece of a face by its own name, sheet metal rims and bend ends, bend edges for Convert to Sheet Metal, the tear corner relief of sheet metal rules, the names of projected edges, physical materials defined in the design, the font of sketch text, the expressions behind a sketch text's height, place and angle, sheet metal corner relief shapes, sketch face anchors on cylinder caps, sketch axis +Current designs use format 24, including the corner relief of an edge flange, the gear, rack and pinion and screw couplings of motion links, design properties, named render setups, opaque PBR looks, thin extrudes, sheet metal perforation fields, associative editable sketch patterns, editable associative offset-distance dimensions, the style of sketch text (bold, italic, alignment, spacing and the curve it follows), face anchors on a piece of a face by its own name, sheet metal rims and bend ends, bend edges for Convert to Sheet Metal, the tear corner relief of sheet metal rules, the names of projected edges, physical materials defined in the design, the font of sketch text, the expressions behind a sketch text's height, place and angle, sheet metal corner relief shapes, sketch face anchors on cylinder caps, sketch axis links, persistent names from exact face history, exact planar shell-face anchors, persistent analytic offset boundary roles and association profile references, durable sketch face anchors, periodic fit splines and versioned diff --git a/docs/book/src/guide/sheet-metal.md b/docs/book/src/guide/sheet-metal.md index 098a37849..b3ad5f805 100644 --- a/docs/book/src/guide/sheet-metal.md +++ b/docs/book/src/guide/sheet-metal.md @@ -64,6 +64,22 @@ warning saying where. "bend_radius":"1 mm","corner_relief_shape":"round","corner_relief":"8 mm","active":true}} ``` +The rule's shape and size are the default. An edge flange feature can choose its own for the +corners its flanges make: `corner_relief_shape` (`notch`, `round`, `rectangular` or `tear`) and +`corner_relief` (the size across, a length or an expression) in `sheet.flange`, or Corner Relief +Shape and Corner Relief in the Flange dialog. In the dialog, Rule as the shape and an empty size +take the rule's; either one left out follows the rule while the other is the feature's. Corners are +relieved only between the flanges of one feature, so a feature's choice never meets another's at a +corner, and two edge flange features of one part can have different reliefs under one rule. A +base or contour flange takes its corners from the rule only and refuses both parameters. The +flange gap and the rule's other values stay with the rule for every flange. The feature's choice is +saved with the design (file format 23). + +```json +{"command":"sheet.flange","params":{"edges":[[60,0,2],[120,45,2],[60,90,2],[0,45,2]], + "height":20,"corner_relief_shape":"round","corner_relief":"6 mm"}} +``` + Where the edge flanges of one feature meet at a corner of the base, their panels are closed toward each other at any bend angle: each end is cut square to the sheet, on a line in the flat chosen so that the edges nearest each other (on the inner faces) run parallel, the rule's diff --git a/docs/design-container.md b/docs/design-container.md index 9bde0bfe2..c391879f0 100644 --- a/docs/design-container.md +++ b/docs/design-container.md @@ -7,7 +7,7 @@ self-contained input/output format. `io::write_design` keeps its JSON contract; `io::write_design_container` is the fallible container writer. Packages have `container.json` with `{"format":"solidcraft-container/1"}` and -`document.json` with the versioned parametric document (currently `solidcraft/23`). +`document.json` with the versioned parametric document (currently `solidcraft/24`). The independent versions let document migrations evolve without changing blob encodings. Existing serialized document fields are retained automatically, without a second copy of the document schema or a deep clone of embedded payloads. From af771b9ceb4583be368962642de648b999ddc030 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Thu, 15 Oct 2026 20:58:26 -0400 Subject: [PATCH 21/92] CI: PRs build and test only the packages they touch (#1561) Clippy, the test archive and the test shards cover the packages a PR changes plus their dependents. Main, nightly and manual runs stay full. Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/ci.yml | 48 ++++++++++++++-- CONTRIBUTING.md | 7 +++ scripts/ci/affected.py | 108 ++++++++++++++++++++++++++++++++++++ scripts/ci/test_affected.py | 76 +++++++++++++++++++++++++ 4 files changed, 234 insertions(+), 5 deletions(-) create mode 100644 scripts/ci/affected.py create mode 100644 scripts/ci/test_affected.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3c2b16075..a245aab59 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,4 +1,10 @@ # Fast checks always run; native builds run for code/CI changes. +# 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. # Tests are built once and run in 4 shards. A few heavy tests (see .config/nextest.toml) are # skipped on pull requests and run on pushes to main and nightly. # Cross-compilation is opt-in through Run workflow; release builds remain in release.yml. @@ -49,6 +55,8 @@ jobs: outputs: native: ${{ steps.paths.outputs.native }} kernel: ${{ steps.paths.outputs.kernel }} + full: ${{ steps.paths.outputs.full }} + packages: ${{ steps.paths.outputs.packages }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -62,6 +70,8 @@ jobs: run: | native=false kernel=false + full=true + packages= if [ "$EVENT_NAME" != pull_request ]; then native=true else @@ -76,9 +86,20 @@ jobs: *) native=true ;; esac done < "$RUNNER_TEMP/ci-paths" + # 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 fi - echo "native=$native" >> "$GITHUB_OUTPUT" - echo "kernel=$kernel" >> "$GITHUB_OUTPUT" + { + echo "native=$native" + echo "kernel=$kernel" + echo "full=$full" + echo "packages=$packages" + } >> "$GITHUB_OUTPUT" checks: name: Format and repository checks @@ -102,6 +123,8 @@ jobs: run: cargo xtask layers - name: Web app offline use and updates (headless Chrome) run: cargo xtask web-offline-test + - name: Affected-package selection self-test + run: python3 -I scripts/ci/test_affected.py clippy: name: Native Linux Clippy @@ -117,7 +140,15 @@ jobs: - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 with: key: native-clippy - - run: cargo clippy --workspace --all-targets --profile ci --locked -- -D warnings + - name: Clippy + env: + FULL: ${{ needs.changes.outputs.full }} + PACKAGES: ${{ needs.changes.outputs.packages }} + run: | + # Pull requests lint the affected packages (scripts/ci/affected.py); everything else, all. + scope=(--workspace) + if [ "$FULL" != true ]; then scope=(); for p in $PACKAGES; do scope+=(-p "$p"); done; fi + cargo clippy "${scope[@]}" --all-targets --profile ci --locked -- -D warnings build-tests: name: Build tests @@ -144,7 +175,14 @@ jobs: with: tool: cargo-nextest - name: Compile tests into a nextest archive - run: cargo nextest archive --workspace --cargo-profile ci --locked --archive-file tests.tar.zst + env: + FULL: ${{ needs.changes.outputs.full }} + PACKAGES: ${{ needs.changes.outputs.packages }} + run: | + # Pull requests archive only the affected packages (scripts/ci/affected.py). + scope=(--workspace) + if [ "$FULL" != true ]; then scope=(); for p in $PACKAGES; do scope+=(-p "$p"); done; fi + cargo nextest archive "${scope[@]}" --cargo-profile ci --locked --archive-file tests.tar.zst - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: nextest-archive @@ -183,7 +221,7 @@ jobs: # 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/4" "${all[@]}" + --profile ci --partition "slice:$SHARD/4" --no-tests=pass "${all[@]}" - name: Robustness goldens sample (pull requests that touch the kernel) # Every 8th seed of tests/robustness/goldens.json, a quarter per shard; pushes to main and # the nightly run every seed in the step above. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8f15211f0..edde06489 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -163,6 +163,13 @@ in the PR. `cargo xtask test` builds the tests with it and then runs every test `cargo xtask test -- shell`. Tests run beside each other on a busy machine, so a test must not depend on wall-clock timing. +**PRs test what they touch; main and nightly test everything.** On a pull request, CI maps the +changed files to workspace packages and runs Clippy, the test build and the tests for those and +the packages that depend on them (`scripts/ci/affected.py`, self-tested in the `checks` job). A +change to `Cargo.lock`, the root `Cargo.toml`, `.cargo/`, `.config/`, `.github/`, `vendor/`, +`tests/`, `scripts/` or any file outside a package runs the whole workspace, as does every push +to `main`, the nightly run and Run workflow. + **CI shards the tests.** One job builds them into a cargo-nextest archive and four jobs run a quarter each, so every test runs in its own process: don't rely on state left by another test. Pull requests skip a few heavy tests (one to four minutes each), which run on every push to diff --git a/scripts/ci/affected.py b/scripts/ci/affected.py new file mode 100644 index 000000000..b6d0a082a --- /dev/null +++ b/scripts/ci/affected.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python3 +"""Select the workspace packages a pull request affects. + +Usage: affected.py --paths FILE [--metadata FILE] [--github-output FILE] + +FILE holds the changed paths relative to the repository root, separated by NUL (git diff -z); +"-" reads standard input. --metadata is the output of `cargo metadata --no-deps +--format-version 1` (run on demand when omitted). + +Prints and optionally appends to $GITHUB_OUTPUT: + full=true|false test the whole workspace + 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. +""" +import argparse +import json +import subprocess +import sys + +# Changes here can affect every package. +FULL_PREFIXES = (".cargo/", ".config/", ".github/", "vendor/", "tests/", "scripts/") +FULL_FILES = ("Cargo.toml", "Cargo.lock") +# Changes here affect no code: documentation and packaging. +IGNORED_PREFIXES = ("docs/", "packaging/") +# Root files that a crate embeds (include_str!), so they are not ignorable documentation. +EMBEDDED = {"ATTRIBUTION.md": "solidcraft-ui-egui"} + + +def load_metadata(path): + if path: + with open(path, encoding="utf-8") as f: + return json.load(f) + out = subprocess.run( + ["cargo", "metadata", "--no-deps", "--format-version", "1", "--locked"], + check=True, capture_output=True, text=True, + ).stdout + return json.loads(out) + + +def read_paths(src): + data = sys.stdin.buffer.read() if src == "-" else open(src, "rb").read() + return [p.decode() for p in data.split(b"\0") if p] + + +def select(meta, paths): + """Return (full, sorted package names).""" + root = meta["workspace_root"].rstrip("/") + "/" + pkgs = {} + for p in meta["packages"]: + manifest = p["manifest_path"] + assert manifest.startswith(root), manifest + pkgs[p["name"]] = manifest[len(root):].rsplit("/", 1)[0] + "/" + by_dir = {d: n for n, d in pkgs.items()} + # Reverse dependencies inside the workspace, matched by the dependency's path. + dependents = {n: set() for n in pkgs} + for p in meta["packages"]: + for d in p["dependencies"]: + path = d.get("path") + if not path: + continue + rel = path.rstrip("/") + "/" + target = by_dir.get(rel[len(root):]) if rel.startswith(root) else None + if target: + dependents[target].add(p["name"]) + + 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: + hit.add(by_dir[max(owners, key=len)]) + elif path in EMBEDDED: + hit.add(EMBEDDED[path]) + elif path.startswith(IGNORED_PREFIXES) or ("/" not in path and path.endswith(".md")): + continue + else: + return True, [] # not owned by any package + + todo, seen = list(hit), set(hit) + while todo: + for dep in dependents[todo.pop()]: + if dep not in seen: + seen.add(dep) + todo.append(dep) + return False, sorted(seen) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--paths", required=True) + ap.add_argument("--metadata") + ap.add_argument("--github-output") + a = ap.parse_args() + full, packages = select(load_metadata(a.metadata), read_paths(a.paths)) + lines = [f"full={'true' if full else 'false'}", f"packages={' '.join(packages)}"] + print("\n".join(lines)) + if a.github_output: + with open(a.github_output, "a", encoding="utf-8") as f: + f.write("\n".join(lines) + "\n") + + +if __name__ == "__main__": + main() diff --git a/scripts/ci/test_affected.py b/scripts/ci/test_affected.py new file mode 100644 index 000000000..5fae56cd9 --- /dev/null +++ b/scripts/ci/test_affected.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 +"""Self-test for affected.py. Run: python3 -I scripts/ci/test_affected.py (from the repo root). + +Uses a small synthetic workspace, then the real one (`cargo metadata --no-deps`). +""" +import os +import sys +import unittest + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import affected # noqa: E402 + +R = "/ws" + + +def pkg(name, dir_, deps=()): + return { + "name": name, + "manifest_path": f"{R}/{dir_}/Cargo.toml", + "dependencies": [{"name": d, "path": f"{R}/{p}"} for d, p in deps] + [{"name": "serde"}], + } + + +SYNTH = { + "workspace_root": R, + "packages": [ + pkg("base", "crates/base"), + pkg("mid", "crates/mid", [("base", "crates/base")]), + pkg("top", "apps/top", [("mid", "crates/mid")]), + pkg("alone", "crates/alone"), + ], +} + + +class Synthetic(unittest.TestCase): + def test_leaf_selects_only_itself(self): + self.assertEqual(affected.select(SYNTH, ["apps/top/src/main.rs"]), (False, ["top"])) + + def test_reverse_dependencies_are_added(self): + self.assertEqual(affected.select(SYNTH, ["crates/base/src/lib.rs"]), (False, ["base", "mid", "top"])) + + def test_unrelated_package_is_not_selected(self): + full, pk = affected.select(SYNTH, ["crates/mid/Cargo.toml"]) + self.assertEqual((full, pk), (False, ["mid", "top"])) + + def test_full_triggers(self): + for p in ["Cargo.lock", "Cargo.toml", ".cargo/config.toml", ".config/nextest.toml", "rust-toolchain.toml", + ".github/workflows/ci.yml", "vendor/x/lib.rs", "tests/oracle/a.json", "assets/a.png", + "scripts/ci/affected.py", "unknown.txt"]: + self.assertEqual(affected.select(SYNTH, ["crates/alone/a.rs", p]), (True, []), p) + + def test_docs_only_selects_nothing(self): + self.assertEqual(affected.select(SYNTH, ["docs/book/a.md", "README.md", "packaging/x.yml"]), (False, [])) + + +class RealWorkspace(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.meta = affected.load_metadata(None) + + def test_render_change_selects_render_and_dependents_not_kernel(self): + full, pk = affected.select(self.meta, ["crates/render/src/lib.rs"]) + self.assertFalse(full) + self.assertIn("solidcraft-render", pk) + self.assertGreater(len(pk), 1) + self.assertNotIn("solidcraft-kernel", pk) + + def test_cargo_lock_selects_full(self): + self.assertEqual(affected.select(self.meta, ["Cargo.lock"]), (True, [])) + + def test_docs_only_selects_nothing(self): + self.assertEqual(affected.select(self.meta, ["docs/book/src/dev/testing.md", "CONTRIBUTING.md"]), (False, [])) + + +if __name__ == "__main__": + unittest.main() From 067f2642c27fc3f46d5cb1fe2205b305681949d5 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Thu, 15 Oct 2026 21:11:49 -0400 Subject: [PATCH 22/92] Agent chat on Windows: no terminal window flashes when agents are detected --- crates/ui-egui/src/agent_chat/discover.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/ui-egui/src/agent_chat/discover.rs b/crates/ui-egui/src/agent_chat/discover.rs index 24fffffaf..bdbf28099 100644 --- a/crates/ui-egui/src/agent_chat/discover.rs +++ b/crates/ui-egui/src/agent_chat/discover.rs @@ -217,6 +217,12 @@ fn version(program: &Path, limit: Duration) -> Option { } else { Command::new(program) }; + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + // CREATE_NO_WINDOW: probing a console agent doesn't flash a terminal window. + cmd.creation_flags(0x0800_0000); + } let mut child = cmd.arg("--version").stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn().ok()?; let start = Instant::now(); loop { From 9a07932f20258953c3f68724bc57d37ad58cf724 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Thu, 15 Oct 2026 21:13:38 -0400 Subject: [PATCH 23/92] Design format: a change is one new file, never an edit to FORMAT (#1563) A PR that saves something new adds crates/doc/src/format/pending/.rs (a note, and an upgrade step if older designs must be rewritten). The build writes the next format number while changes are pending and lists them in format_pending; scripts/fold-format-pending.sh fixes them as v/ at release time. Formats 23 and 24 move into v23/ and v24/. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/lists.yml | 20 ++ AGENTS.md | 7 + CLAUDE.md | 7 + CONTRIBUTING.md | 25 ++ crates/doc/build.rs | 62 +++++ crates/doc/src/document.rs | 5 + crates/doc/src/format.rs | 258 ++++++++++++++++-- crates/doc/src/format/pending/README.md | 27 ++ crates/doc/src/format/v23/import-fcstd-3dm.rs | 4 + .../src/format/v23/motion-link-coupling.rs | 7 + .../format/v24/edge-flange-corner-relief.rs | 5 + docs/book/src/guide/files.md | 11 +- docs/design-container.md | 2 +- docs/releasing.md | 7 +- scripts/fold-format-pending.sh | 33 +++ scripts/test-format-pending.sh | 47 ++++ 16 files changed, 494 insertions(+), 33 deletions(-) create mode 100644 .github/workflows/lists.yml create mode 100644 crates/doc/build.rs create mode 100644 crates/doc/src/format/pending/README.md create mode 100644 crates/doc/src/format/v23/import-fcstd-3dm.rs create mode 100644 crates/doc/src/format/v23/motion-link-coupling.rs create mode 100644 crates/doc/src/format/v24/edge-flange-corner-relief.rs create mode 100755 scripts/fold-format-pending.sh create mode 100755 scripts/test-format-pending.sh diff --git a/.github/workflows/lists.yml b/.github/workflows/lists.yml new file mode 100644 index 000000000..0e4da028c --- /dev/null +++ b/.github/workflows/lists.yml @@ -0,0 +1,20 @@ +# Files many pull requests add to are kept so that additions don't conflict: one file per change +# or one sorted line per item (CONTRIBUTING.md, "Lists many changes add to"). Fast, no build. +name: Lists + +on: + pull_request: + push: + branches: [main] + +permissions: + contents: read + +jobs: + format-changes: + name: Design format changes merge cleanly + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - run: bash scripts/test-format-pending.sh diff --git a/AGENTS.md b/AGENTS.md index aaeb9c242..9c669979f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -123,6 +123,13 @@ People trust SolidCraft with their designs; a crash loses their work. **This out keep monitoring it while the task is active and make its pending status clear at handoff; do not claim it merged without checking. +## 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 diff --git a/CLAUDE.md b/CLAUDE.md index 60b87023b..b3a508e4f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -96,6 +96,13 @@ People trust SolidCraft with their designs; a crash loses their work. **This out - **Never break wasm**: everything below the apps must build for `wasm32-unknown-unknown` (`cargo xtask wasm`, part of `cargo xtask ci`). +## 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 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index edde06489..5fc5f89a8 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -199,6 +199,31 @@ the current results, and CI runs `cargo xtask oracle` on every pull request. A c because of a known bug names its issue in `expected.json` (`"known_failure": "#123"`); never change an expected value to match SolidCraft's output. +## Changing the design file format + +A design file says which format it is in (`"format": "solidcraft/N"`). If your change saves +something new in a design (a field, a feature type, a new kind of name), or makes older designs +mean something else, it needs a format change. **Add one file, and edit nothing shared:** + +1. Create `crates/doc/src/format/pending/.rs` (lowercase, dashes). Start it with a + `//!` note: what is saved, what older designs get without it, and that the last release asks + for an update instead of meeting it. +2. If older designs must be rewritten as they open, put `pub fn step(v: &mut Value) -> + crate::Result<()>` in the same file. Pending steps run in file-name order, after the older + formats' steps. +3. Don't touch `FORMAT`, `JSON_STEPS`, the history in `crates/doc/src/format.rs`, another + change's file, or any `v/` folder: those are fixed once released. + +That's all. The build counts the files: while any are pending it writes the next format number, +which no release reads, so a release refuses a design that has your change instead of losing it. +A file also lists the pending changes it has (`format_pending`), so a later development build +runs only the steps that file is missing. Two pull requests that each add a change merge without +a conflict. `crates/doc/src/format/pending/README.md` has an example. + +**At release time** the maintainer runs `scripts/fold-format-pending.sh`, which moves the pending +files into `crates/doc/src/format/v/` and fixes that number for good (see +[docs/releasing.md](docs/releasing.md)). Never add a file to a `v/` folder afterwards. + ## Sending a change 1. Work is tracked in [GitHub issues](https://github.com/bherbruck/solidcraft/issues), labelled diff --git a/crates/doc/build.rs b/crates/doc/build.rs new file mode 100644 index 000000000..18bea3206 --- /dev/null +++ b/crates/doc/build.rs @@ -0,0 +1,62 @@ +//! Lists the design-format changes in `src/format/`: one file per change, in `v/` once a +//! release fixed its number, else in `pending/` (see `src/format/pending/README.md`). The list is +//! generated so that a change adds a file and never edits a line another change also edits. + +use std::fmt::Write as _; +use std::path::{Path, PathBuf}; + +/// The last format whose upgrade steps are written out in `format.rs` (`JSON_STEPS`). +const HAND_WRITTEN: u32 = 22; + +fn main() { + let root = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap()).join("src/format"); + println!("cargo:rerun-if-changed={}", root.display()); + let mut folded: Vec<(u32, PathBuf)> = std::fs::read_dir(&root) + .unwrap_or_else(|e| panic!("{}: {e}", root.display())) + .filter_map(|entry| { + let path = entry.ok()?.path(); + let version = path.file_name()?.to_str()?.strip_prefix('v')?.parse().ok()?; + path.is_dir().then_some((version, path)) + }) + .collect(); + folded.sort(); + for (i, (version, _)) in folded.iter().enumerate() { + let expected = HAND_WRITTEN + 1 + i as u32; + assert_eq!(*version, expected, "src/format/: expected v{expected}/ next, found v{version}/ (versions are contiguous)"); + } + let mut out = String::new(); + let mut mods = String::new(); + out.push_str("/// The changes of each format after the hand-written ones, oldest first.\nconst FOLDED: &[(u32, &[Part])] = &[\n"); + for (version, dir) in &folded { + let _ = writeln!(out, " ({version}, &["); + parts(dir, &format!("v{version}"), &mut out, &mut mods); + out.push_str(" ]),\n"); + } + out.push_str("];\n\n/// The changes no release has a number for yet (`src/format/pending/`).\nconst PENDING: &[Part] = &[\n"); + parts(&root.join("pending"), "pending", &mut out, &mut mods); + out.push_str("];\n"); + out.push_str(&mods); + let dest = PathBuf::from(std::env::var("OUT_DIR").unwrap()).join("format_parts.rs"); + std::fs::write(dest, out).unwrap(); +} + +/// The `Part`s of the change files in `dir`, in file-name order, and a module for each. +fn parts(dir: &Path, prefix: &str, out: &mut String, mods: &mut String) { + let Ok(entries) = std::fs::read_dir(dir) else { return }; + let mut files: Vec = entries.filter_map(|e| e.ok().map(|e| e.path())).filter(|p| p.extension().is_some_and(|x| x == "rs")).collect(); + files.sort(); + for path in files { + let name = path.file_stem().and_then(|s| s.to_str()).unwrap_or_default().to_string(); + assert!( + !name.is_empty() && name.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-'), + "{}: name a format change file with lowercase letters, digits and dashes", + path.display() + ); + let text = std::fs::read_to_string(&path).unwrap(); + assert!(text.trim_start().starts_with("//!"), "{}: start a format change with a `//!` note", path.display()); + let module = format!("{prefix}_{}", name.replace('-', "_")); + let step = if text.contains("fn step(") { format!("Some({module}::step)") } else { "None".into() }; + let _ = writeln!(out, " Part {{ name: {name:?}, step: {step} }},"); + let _ = writeln!(mods, "#[path = {:?}]\nmod {module};", path.display().to_string()); + } +} diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 0463746a2..2f13f4e3a 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -2133,6 +2133,10 @@ pub struct Document { pub render: std::sync::Arc, #[serde(default = "default_format")] pub format: String, + /// The changes of `format` this design has while they are pending (no release has fixed + /// that number yet; `crate::format::pending_names`). Empty, and not saved, otherwise. + #[serde(default = "crate::format::pending_names", skip_serializing_if = "Vec::is_empty")] + pub format_pending: Vec, pub name: String, #[serde(default = "default_units")] pub units: String, @@ -2350,6 +2354,7 @@ impl Document { Document { render: Default::default(), format: default_format(), + format_pending: crate::format::pending_names(), name: name.into(), units: default_units(), metadata: Default::default(), diff --git a/crates/doc/src/format.rs b/crates/doc/src/format.rs index 1286678bb..7f667d6ef 100644 --- a/crates/doc/src/format.rs +++ b/crates/doc/src/format.rs @@ -222,29 +222,111 @@ //! parameters); the source's `at`, `height` and `angle` then hold the numbers they last came //! to. A text without `exprs` is set as it always was; 0.12.0 asks for an update instead of //! dropping the expressions and keeping the text at its last numbers. -//! - 23: a motion link can carry a `coupling`: a gear pair (`ra`, `rb`, `internal`), a rack and -//! pinion (`radius`) or a screw (`pitch`), each size a number in mm, an expression or a picked -//! round face, and `reverse`. The link's `ratio` is worked out from it whenever the design -//! changes and saved as well, so a link reads the same without it. Version 22 designs need no -//! transformation: a link without `coupling` is a plain motion link, as it always was; 0.13.0 -//! (which reads up to 22) asks for an update instead of keeping a gear's ratio when its radius -//! changes. -//! Also under 23, an Import's `file` can name a FreeCAD `.FCStd` or Rhino `.3dm` file (#1435, -//! read through cadmpeg); its `step` is still the STEP text the file was restated as, so the -//! feature's fields are unchanged and version 22 designs need no transformation; 0.13.x asks -//! for an update before it meets these imports. -//! - 24: an Edge Flange feature can choose its own corner relief (`corner_relief_shape`: notch, -//! round, rectangular or tear, and `corner_relief`, the size across), for the corners its -//! flanges make. Version 23 designs need no transformation: a feature without them follows the -//! sheet metal rule, as it always did, and saves as before; 0.13.0 (which reads up to 22) asks -//! for an update instead of silently building the rule's relief where a design asks for another. +//! +//! Later formats are one file per change, so changes made side by side never edit the same line +//! (`src/format/pending/README.md`): +//! - `src/format/v/`: the changes format N added, one file each, its `//!` note saying what is +//! saved and what older designs get, and a `step` when older designs are rewritten as they open +//! (23: motion link couplings, FreeCAD and Rhino imports; 24: an Edge Flange's own corner relief). +//! - `src/format/pending/`: changes no release has fixed a number for yet. While there are any, +//! this build writes the next number (which no release reads), with the names of these changes +//! in `format_pending`, so a later build applies just the steps a file is missing. At release +//! time `scripts/fold-format-pending.sh` moves them into the next `v/`. use serde_json::Value; use crate::{DocError, Document, Result}; -/// The format this build writes. -pub const FORMAT: u32 = 24; +/// The format this build writes: the last folded one, or the next while changes are pending. +pub const FORMAT: u32 = FORMATS.current(); + +/// The last format whose upgrade step is written out in [`JSON_STEPS`]; later formats are made +/// of [`Part`]s (`src/format/`, listed by `build.rs`). +const HAND_WRITTEN: u32 = 22; + +/// One change to the file format: a file in `src/format/v/` or `src/format/pending/`. +pub(crate) struct Part { + /// The file's name, which a file written while the change was pending lists. + pub name: &'static str, + /// How a design from before the change is rewritten as it opens, if it is. + pub step: Option, +} + +include!(concat!(env!("OUT_DIR"), "/format_parts.rs")); + +/// Every format this build knows and how to upgrade a design through them. +const FORMATS: Formats<'static> = Formats { hand: &JSON_STEPS, folded: FOLDED, pending: PENDING }; + +/// The names of the pending changes this build writes into a design (`format_pending`). +pub fn pending_names() -> Vec { + FORMATS.pending.iter().map(|p| p.name.to_string()).collect() +} + +/// The upgrade path: the hand-written steps up to [`HAND_WRITTEN`], the folded formats after it +/// (each a list of changes) and the pending changes, which make the next format. +struct Formats<'a> { + hand: &'a [JsonStep], + folded: &'a [(u32, &'a [Part])], + pending: &'a [Part], +} + +impl Formats<'_> { + const fn current(&self) -> u32 { + self.hand.len() as u32 + 1 + self.folded.len() as u32 + if self.pending.is_empty() { 0 } else { 1 } + } + + /// The changes format `version` is made of, if it is made of changes. + fn parts(&self, version: u32) -> Option<&[Part]> { + let after = version.checked_sub(self.hand.len() as u32 + 2)? as usize; + match self.folded.get(after) { + Some((_, parts)) => Some(parts), + None if after == self.folded.len() && !self.pending.is_empty() => Some(self.pending), + None => None, + } + } + + /// Bring a design of format `version` up to [`Formats::current`]. `applied` is the file's + /// `format_pending`: the changes of its format it already has, when it was written while they + /// were pending; the others' steps run first. A pending change this build doesn't have is a + /// newer build's, and the design is refused. + fn upgrade(&self, v: &mut Value, version: u32, applied: Option<&[String]>) -> Result<()> { + if version == 0 || version > self.current() { + return Err(DocError::Invalid(format!("not a SolidCraft design (format {version})"))); + } + // A list beside a format that isn't made of changes means nothing (a tool or a test set + // an older number on a newer file): it is ignored, like any field an upgrade drops. + if let (Some(applied), Some(parts)) = (applied, self.parts(version)) { + let pending = version == self.current() && !self.pending.is_empty(); + if let Some(unknown) = applied.iter().find(|name| pending && !parts.iter().any(|p| p.name == name.as_str())) { + return Err(DocError::Invalid(format!( + "this design was saved by a newer SolidCraft (file format {version} with `{unknown}`, which this version doesn't know): update SolidCraft to open it" + ))); + } + for part in parts.iter().filter(|p| !applied.iter().any(|name| name == p.name)) { + part.step.map_or(Ok(()), |step| step(v))?; + } + } + for from in version..self.current() { + match self.hand.get(from as usize - 1) { + Some(step) => step(v)?, + None => { + for part in self.parts(from + 1).unwrap_or_default() { + part.step.map_or(Ok(()), |step| step(v))?; + } + } + } + } + Ok(()) + } +} + +/// Take a file's `format_pending` (the pending changes it has) out of its JSON. +fn take_pending(v: &mut Value) -> Result>> { + let Some(list) = v.as_object_mut().and_then(|o| o.remove("format_pending")) else { return Ok(None) }; + let invalid = || DocError::Invalid("damaged design: `format_pending` is not a short list of names".into()); + let list = list.as_array().filter(|l| l.len() <= 1000).ok_or_else(invalid)?; + list.iter().map(|n| n.as_str().filter(|n| n.len() <= 128).map(str::to_string).ok_or_else(invalid)).collect::>().map(Some) +} pub fn format_string(n: u32) -> String { format!("solidcraft/{n}") @@ -259,9 +341,10 @@ pub fn version_of(s: &str) -> Option { s.strip_prefix("solidcraft/").or_else(|| s.strip_prefix(LEGACY_FORMAT_PREFIX))?.parse().ok() } -/// JSON-level upgrades: entry `i` turns format `i + 1` into `i + 2`. +/// JSON-level upgrades up to [`HAND_WRITTEN`]: entry `i` turns format `i + 1` into `i + 2`. +/// Never add to it: a new format is a file in `src/format/pending/`. type JsonStep = fn(&mut Value) -> Result<()>; -const JSON_STEPS: [JsonStep; 23] = [ +const JSON_STEPS: [JsonStep; HAND_WRITTEN as usize - 1] = [ |_| Ok(()), v2_to_v3, v3_to_v4, @@ -283,8 +366,6 @@ const JSON_STEPS: [JsonStep; 23] = [ |_| Ok(()), |_| Ok(()), |_| Ok(()), - |_| Ok(()), - |_| Ok(()), ]; /// Stored face and edge names were worked out from geometry before format 14; they get the @@ -475,6 +556,7 @@ pub fn read(s: &str) -> Result { Some(Value::String(f)) => version_of(f).ok_or_else(|| DocError::Invalid(format!("not a SolidCraft design (format `{f}`)")))?, Some(_) => return Err(DocError::Invalid("not a SolidCraft design (format is not a string)".into())), }; + let applied = take_pending(&mut v)?; if version == 0 { return Err(DocError::Invalid("not a SolidCraft design (format 0)".into())); } @@ -494,9 +576,7 @@ pub fn read(s: &str) -> Result { crate::format_offsets::validate_raw(&v)?; let legacy_wires = validate_wires(&v, version)?; validate_body_transfers(&v)?; - for step in JSON_STEPS.iter().skip(version as usize - 1).take((FORMAT - version) as usize) { - step(&mut v)?; - } + FORMATS.upgrade(&mut v, version, applied.as_deref())?; let mut d: Document = serde_json::from_value(v).map_err(|e| DocError::Invalid(format!("design file: {e}")))?; let mut legacy_by_feature = std::collections::BTreeMap::>::new(); for (feature, wire) in legacy_wires { @@ -595,6 +675,7 @@ pub fn read(s: &str) -> Result { let floor = largest.checked_add(1).ok_or_else(|| DocError::Invalid("damaged design: the id space is exhausted".into()))?; d.next_id = d.next_id.max(floor).max(1); d.format = format_string(FORMAT); + d.format_pending = pending_names(); Ok(d) } @@ -1017,11 +1098,136 @@ fn normalise(d: &mut Document) -> Result<()> { mod tests { use super::*; + /// A pending change that records that its step ran, in `trace`. + fn traced(name: &'static str) -> Part { + fn step_a(v: &mut Value) -> Result<()> { + trace(v, "a") + } + fn step_b(v: &mut Value) -> Result<()> { + trace(v, "b") + } + fn trace(v: &mut Value, s: &str) -> Result<()> { + let o = v.as_object_mut().ok_or_else(|| DocError::Invalid("no object".into()))?; + o.entry("trace").or_insert_with(|| Value::Array(Vec::new())).as_array_mut().into_iter().for_each(|t| t.push(Value::from(s))); + Ok(()) + } + Part { name, step: Some(if name.starts_with('a') { step_a } else { step_b }) } + } + + fn trace_of(v: &Value) -> Vec<&str> { + v["trace"].as_array().into_iter().flatten().filter_map(Value::as_str).collect() + } + + /// Formats after the hand-written ones follow on from them, one folder each, and the build + /// writes the next number exactly while changes are pending, so the last release (which + /// reads up to 22) refuses what a development build saves. + #[test] + fn formats_follow_on_and_pending_changes_take_the_next_number() { + assert_eq!(JSON_STEPS.len() as u32, HAND_WRITTEN - 1); + for (i, (version, parts)) in FOLDED.iter().enumerate() { + assert_eq!(*version, HAND_WRITTEN + 1 + i as u32); + assert!(!parts.is_empty(), "format {version} has no changes"); + } + let last_folded = HAND_WRITTEN + FOLDED.len() as u32; + assert_eq!(FORMAT, last_folded + u32::from(!PENDING.is_empty())); + const { assert!(FORMAT >= 24, "designs saved as 23 and 24 by nightlies still open") }; + assert_eq!(pending_names(), PENDING.iter().map(|p| p.name).collect::>()); + assert_eq!(Document::new("A").format_pending, pending_names()); + } + + /// The build lists every change file there is, in file-name order: a change is a file, so + /// two branches that each add one merge cleanly and the merged build has both. + #[test] + fn every_change_file_is_listed_in_name_order() { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/format"); + let names = |dir: &str| -> Vec { + let mut names: Vec = std::fs::read_dir(root.join(dir)) + .map(|d| d.filter_map(|e| e.ok()?.file_name().to_str()?.strip_suffix(".rs").map(str::to_string)).collect()) + .unwrap_or_default(); + names.sort(); + names + }; + assert_eq!(names("pending"), pending_names()); + for (version, parts) in FOLDED { + assert_eq!(names(&format!("v{version}")), parts.iter().map(|p| p.name).collect::>()); + } + } + + /// Two changes pending side by side both run, in name order, after every older format's + /// steps: an old design upgrades through all of them, and one from the last folded format + /// gets just the pending ones. + #[test] + fn pending_changes_apply_in_order_after_older_formats() { + let pending = [traced("a-first"), traced("b-second")]; + let formats = Formats { hand: &JSON_STEPS, folded: FOLDED, pending: &pending }; + let next = HAND_WRITTEN + FOLDED.len() as u32 + 1; + assert_eq!(formats.current(), next); + for version in [1, HAND_WRITTEN, next - 1] { + let mut v = serde_json::json!({"features": [], "assembly": {"joints": [{"flip": false}]}}); + formats.upgrade(&mut v, version, None).unwrap(); + assert_eq!(trace_of(&v), ["a", "b"], "from format {version}"); + // The hand-written steps ran too: format 3's joints were flipped on the way up. + assert_eq!(v["assembly"]["joints"][0]["flip"], Value::Bool(version < 4), "from format {version}"); + } + // A design of the pending number written before `b-second` existed gets just that step. + let mut v = serde_json::json!({}); + formats.upgrade(&mut v, next, Some(&["a-first".to_string()])).unwrap(); + assert_eq!(trace_of(&v), ["b"]); + // One that has both, or that this build wrote, needs nothing. + let mut v = serde_json::json!({}); + formats.upgrade(&mut v, next, Some(&["a-first".into(), "b-second".into()])).unwrap(); + assert_eq!(trace_of(&v), Vec::<&str>::new()); + // A change this build doesn't know is a newer build's: refused, not guessed at. + let err = formats.upgrade(&mut serde_json::json!({}), next, Some(&["c-later".into()])).unwrap_err(); + assert!(err.to_string().contains("newer SolidCraft"), "{err}"); + // A list on a format that isn't made of changes means nothing. + let mut v = serde_json::json!({}); + formats.upgrade(&mut v, HAND_WRITTEN, Some(&["a-first".into()])).unwrap(); + assert_eq!(trace_of(&v), ["a", "b"]); + } + + /// Folding the pending changes into a number (the release script) keeps every design + /// opening the same: a file saved while they were pending gets the steps it missed. + #[test] + fn folded_changes_upgrade_like_pending_ones() { + let parts = [traced("a-first"), traced("b-second")]; + let mut folded: Vec<(u32, &[Part])> = FOLDED.to_vec(); + let next = HAND_WRITTEN + folded.len() as u32 + 1; + folded.push((next, &parts)); + let formats = Formats { hand: &JSON_STEPS, folded: &folded, pending: &[] }; + assert_eq!(formats.current(), next); + let mut old = serde_json::json!({}); + formats.upgrade(&mut old, HAND_WRITTEN, None).unwrap(); + assert_eq!(trace_of(&old), ["a", "b"]); + let mut nightly = serde_json::json!({}); + formats.upgrade(&mut nightly, next, Some(&["a-first".into()])).unwrap(); + assert_eq!(trace_of(&nightly), ["b"]); + let mut released = serde_json::json!({}); + formats.upgrade(&mut released, next, None).unwrap(); + assert_eq!(trace_of(&released), Vec::<&str>::new()); + } + + /// `format_pending` is read and checked: a damaged list is refused, a list of changes this + /// build doesn't have is a newer build's, and saving writes this build's own list. + #[test] + fn format_pending_in_a_file_is_checked() { + let mut file: Value = serde_json::from_str(&Document::new("A").to_json()).unwrap(); + assert_eq!(file.get("format_pending").is_some(), !PENDING.is_empty()); + for damaged in [serde_json::json!("x"), serde_json::json!([1]), serde_json::json!(["x".repeat(200)])] { + file["format_pending"] = damaged; + assert!(read(&file.to_string()).is_err()); + } + file["format_pending"] = serde_json::json!(["not-a-change-anyone-made"]); + assert_eq!(read(&file.to_string()).is_err(), !PENDING.is_empty(), "only a pending format's list names changes"); + file["format_pending"] = Value::from(pending_names()); + let opened = read(&file.to_string()).unwrap(); + assert_eq!(opened.format_pending, pending_names()); + } + /// 24 added the corner relief of an edge flange: a no-op step carries a 23 design up, a flange /// without a relief of its own saves as before, and one with it is saved under 24 and kept. #[test] fn version_twenty_three_designs_open_and_an_edge_flange_relief_is_saved_in_twenty_four() { - assert_eq!(JSON_STEPS.len(), FORMAT as usize - 1, "one upgrade step for each format"); let flange = |shape: Option<&str>, size: Option<&str>| crate::FeatureKind::SheetFlange { edges: vec![crate::FlangeEdge::at(solidcraft_geom::Vec3::ZERO)], height: "10 mm".into(), diff --git a/crates/doc/src/format/pending/README.md b/crates/doc/src/format/pending/README.md new file mode 100644 index 000000000..824a6e2c4 --- /dev/null +++ b/crates/doc/src/format/pending/README.md @@ -0,0 +1,27 @@ +# Pending design-format changes + +One file per change to what a design file saves that no release has shipped yet. Adding a file +here is the whole format bump: never edit `FORMAT`, `JSON_STEPS` or another change's file. + +- Name it after the change, lowercase with dashes: `placed-plane-origins.rs`. +- Start it with a `//!` note: what is saved, what an older design gets without it, and what + the last release does with a design that has it (it refuses the newer format number). +- If older designs must be rewritten as they open, add the step to the same file: + + ```rust + //! …the note… + use serde_json::Value; + + pub fn step(v: &mut Value) -> crate::Result<()> { + // rewrite the design's JSON here + Ok(()) + } + ``` + + Steps run in file-name order, after the steps of every older format. + +While this folder has a change in it, the build writes the next format number (the last +folded one + 1, which no release reads), and lists the changes a file has in its +`format_pending` field, so a later build applies only the steps that file is missing. At release +time `scripts/fold-format-pending.sh` moves these files into `../v/`, which fixes that number +for good. See `crates/doc/src/format.rs` and CONTRIBUTING.md. diff --git a/crates/doc/src/format/v23/import-fcstd-3dm.rs b/crates/doc/src/format/v23/import-fcstd-3dm.rs new file mode 100644 index 000000000..3a6b04764 --- /dev/null +++ b/crates/doc/src/format/v23/import-fcstd-3dm.rs @@ -0,0 +1,4 @@ +//! An Import's `file` can name a FreeCAD `.FCStd` or Rhino `.3dm` file (#1435, read through +//! cadmpeg); its `step` is still the STEP text the file was restated as, so the feature's fields +//! are unchanged and version 22 designs need no transformation; 0.13.x asks for an update before +//! it meets these imports. diff --git a/crates/doc/src/format/v23/motion-link-coupling.rs b/crates/doc/src/format/v23/motion-link-coupling.rs new file mode 100644 index 000000000..60071a137 --- /dev/null +++ b/crates/doc/src/format/v23/motion-link-coupling.rs @@ -0,0 +1,7 @@ +//! A motion link can carry a `coupling`: a gear pair (`ra`, `rb`, `internal`), a rack and pinion +//! (`radius`) or a screw (`pitch`), each size a number in mm, an expression or a picked round +//! face, and `reverse`. The link's `ratio` is worked out from it whenever the design changes and +//! saved as well, so a link reads the same without it. Version 22 designs need no +//! transformation: a link without `coupling` is a plain motion link, as it always was; 0.13.0 +//! (which reads up to 22) asks for an update instead of keeping a gear's ratio when its radius +//! changes. diff --git a/crates/doc/src/format/v24/edge-flange-corner-relief.rs b/crates/doc/src/format/v24/edge-flange-corner-relief.rs new file mode 100644 index 000000000..bd21e9725 --- /dev/null +++ b/crates/doc/src/format/v24/edge-flange-corner-relief.rs @@ -0,0 +1,5 @@ +//! An Edge Flange feature can choose its own corner relief (`corner_relief_shape`: notch, round, +//! rectangular or tear, and `corner_relief`, the size across), for the corners its flanges make. +//! Version 23 designs need no transformation: a feature without them follows the sheet metal +//! rule, as it always did, and saves as before; 0.13.0 (which reads up to 22) asks for an update +//! instead of silently building the rule's relief where a design asks for another. diff --git a/docs/book/src/guide/files.md b/docs/book/src/guide/files.md index 32ca2581c..888e04dfd 100644 --- a/docs/book/src/guide/files.md +++ b/docs/book/src/guide/files.md @@ -86,11 +86,12 @@ is available. Missing or incompatible pictures use the usual thumbnail generatio The default `cache: false` omits the portable thumbnail too. The repository's `docs/design-container.md` describes limits and encoding details. -Current designs use format 24, including the corner relief of an edge flange, the gear, rack and pinion and screw couplings of motion links, design properties, named render setups, opaque PBR looks, thin extrudes, sheet metal perforation fields, associative editable sketch patterns, editable associative offset-distance dimensions, the style of sketch text (bold, italic, alignment, spacing and the curve it follows), face anchors on a piece of a face by its own name, sheet metal rims and bend ends, bend edges for Convert to Sheet Metal, the tear corner relief of sheet metal rules, the names of projected edges, physical materials defined in the design, the font of sketch text, the expressions behind a sketch text's height, place and angle, sheet metal corner relief shapes, sketch face anchors on cylinder caps, sketch axis -links, persistent -names from exact face history, exact planar shell-face anchors, persistent analytic offset boundary roles and -association profile references, durable sketch face anchors, periodic fit splines and versioned -revolve conventions. It also retains recorded body transfers, explicit 3D curve coordinate +Designs are saved in the newest format this version of SolidCraft knows (`"format": "solidcraft/N"` +in the file). It opens designs of every older format and upgrades them as they open; a design +from a newer version asks you to update instead of being guessed at. Development (nightly) builds +save a format number no release reads yet. + +Upgrading keeps what a design meant. Designs keep recorded body transfers, explicit 3D curve coordinate spaces and certified face bindings, alongside semantic configuration styles, associative free-form offsets and cylindrical emboss selections. Older ownership maps, geometry and expressions retain their saved meaning. Legacy 3D curves with retained associations receive diff --git a/docs/design-container.md b/docs/design-container.md index c391879f0..d84f43db6 100644 --- a/docs/design-container.md +++ b/docs/design-container.md @@ -7,7 +7,7 @@ self-contained input/output format. `io::write_design` keeps its JSON contract; `io::write_design_container` is the fallible container writer. Packages have `container.json` with `{"format":"solidcraft-container/1"}` and -`document.json` with the versioned parametric document (currently `solidcraft/24`). +`document.json` with the versioned parametric document (`solidcraft/N`, the format in `crates/doc/src/format.rs`). The independent versions let document migrations evolve without changing blob encodings. Existing serialized document fields are retained automatically, without a second copy of the document schema or a deep clone of embedded payloads. diff --git a/docs/releasing.md b/docs/releasing.md index 8c9754c80..0263dcd14 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -71,7 +71,12 @@ deployment. The stable Flatpak repository is not automatically updated with nigh `Cargo.lock` (it changes only our own crates, never dependency versions, and needs no network). Inspect the diff: only `version = ` lines of workspace crates should change. SolidCraft does not currently implement `cargo xtask version set`. -3. Run `cargo xtask ci` and the packaging checks in `.github/workflows/packaging-lint.yml`. +3. Fix the design format number: run `scripts/fold-format-pending.sh`. It moves the pending + format changes (`crates/doc/src/format/pending/*.rs`) into the next `crates/doc/src/format/v/` + folder, so the release writes and reads that number for good, and does nothing when nothing + is pending. Commit the move with the version files. (CONTRIBUTING.md, "Changing the design + file format".) +4. Run `cargo xtask ci` and the packaging checks in `.github/workflows/packaging-lint.yml`. Commit the version files through the normal review flow and land them on `main`. Do not use `[skip ci]`. Record the exact commit SHA to release. If it changes, revalidate it. diff --git a/scripts/fold-format-pending.sh b/scripts/fold-format-pending.sh new file mode 100755 index 000000000..ea7cfd8cb --- /dev/null +++ b/scripts/fold-format-pending.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +# Release step: give the pending design-format changes their number for good. +# +# Moves every change in crates/doc/src/format/pending/ into crates/doc/src/format/v/, where N +# is the number development builds have been writing for them (the last folded format + 1). +# Commit the result with the release's version bump. Nothing to do when nothing is pending. +# See crates/doc/src/format/pending/README.md. +set -euo pipefail + +root=$(git rev-parse --show-toplevel) +dir="$root/crates/doc/src/format" +last=$(sed -n 's/^const HAND_WRITTEN: u32 = \([0-9]*\);/\1/p' "$root/crates/doc/build.rs") +[ -n "$last" ] || { echo "HAND_WRITTEN not found in crates/doc/build.rs" >&2; exit 1; } +for d in "$dir"/v*/; do + [ -d "$d" ] || continue + n=${d%/} + n=${n##*/v} + if [ "$n" -gt "$last" ]; then last=$n; fi +done + +shopt -s nullglob +pending=("$dir"/pending/*.rs) +if [ ${#pending[@]} -eq 0 ]; then + echo "No pending format changes: this release writes format $last." + exit 0 +fi + +next=$((last + 1)) +mkdir -p "$dir/v$next" +git -C "$root" mv "${pending[@]}" "$dir/v$next/" +echo "Format $next is now fixed, with ${#pending[@]} change(s):" +for f in "${pending[@]}"; do echo " ${f##*/}"; done +echo "Commit crates/doc/src/format/ with the version bump." diff --git a/scripts/test-format-pending.sh b/scripts/test-format-pending.sh new file mode 100755 index 000000000..634835867 --- /dev/null +++ b/scripts/test-format-pending.sh @@ -0,0 +1,47 @@ +#!/usr/bin/env bash +# Checks the design-format change files (crates/doc/src/format/): two branches that each add a +# pending change merge without a conflict, and the release fold moves both into the next number. +# The order they apply in and the upgrades themselves are tested in crates/doc/src/format.rs. +set -euo pipefail + +root=$(git rev-parse --show-toplevel) +tmp=$(mktemp -d) +trap 'rm -rf "$tmp"' EXIT +repo="$tmp/repo" +mkdir -p "$repo/crates/doc/src" "$repo/scripts" +cp -r "$root/crates/doc/src/format" "$repo/crates/doc/src/" +cp "$root/crates/doc/build.rs" "$repo/crates/doc/" +cp "$root/scripts/fold-format-pending.sh" "$repo/scripts/" +rm -f "$repo"/crates/doc/src/format/pending/*.rs # start from a release: nothing pending +git() { command git -C "$repo" -c user.name=test -c user.email=test@example.com "$@"; } +git init -q -b main +git add -A +git commit -qm base + +change() { + git switch -q -c "$1" main + printf '//! %s\n' "$1" > "$repo/crates/doc/src/format/pending/$1.rs" + git add -A + git commit -qm "$1" +} +change b-second +change a-first + +git switch -q main +if ! tree=$(git merge-tree --write-tree a-first b-second); then + echo "FAIL: two pending format changes conflict" >&2 + exit 1 +fi +git merge -q --no-edit a-first b-second >/dev/null +listed=$(git ls-tree --name-only HEAD crates/doc/src/format/pending/ | grep '\.rs$' | sed 's#.*/##' | tr '\n' ' ') +[ "$listed" = "a-first.rs b-second.rs " ] || { echo "FAIL: merged pending changes are: $listed" >&2; exit 1; } +[ "$tree" = "$(git rev-parse HEAD^{tree})" ] || { echo "FAIL: merge-tree and merge disagree" >&2; exit 1; } + +before=$(ls -d "$repo"/crates/doc/src/format/v*/ 2>/dev/null | wc -l) +(cd "$repo" && bash scripts/fold-format-pending.sh) > "$tmp/fold.log" +after=$(ls -d "$repo"/crates/doc/src/format/v*/ | sort -V | tail -1) +[ "$(ls -d "$repo"/crates/doc/src/format/v*/ | wc -l)" -eq $((before + 1)) ] || { echo "FAIL: the fold made no new version" >&2; exit 1; } +[ "$(ls "$after")" = "$(printf 'a-first.rs\nb-second.rs')" ] || { echo "FAIL: the fold moved $(ls "$after")" >&2; exit 1; } +[ -z "$(ls "$repo/crates/doc/src/format/pending/" | grep '\.rs$' || true)" ] || { echo "FAIL: pending changes left after the fold" >&2; exit 1; } +(cd "$repo" && bash scripts/fold-format-pending.sh) | grep -q "No pending format changes" || { echo "FAIL: a second fold did something" >&2; exit 1; } +echo "ok: pending format changes merge cleanly and fold into $(basename "$after")" From 584bbe923ddb86128bb5baf71af2d5da88a14e14 Mon Sep 17 00:00:00 2001 From: Karl Von Richter Date: Fri, 16 Oct 2026 11:27:24 +1000 Subject: [PATCH 24/92] sketch(fix): preserve rectangle constraints through fillets (#1543) Thanks @Karl-VonRichter for the fix. Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/cmd/sketch_corner_tests.rs | 61 ++++++++++++++++++++ crates/engine/src/cmd/sketch_modify.rs | 45 ++++++++++++++- crates/ui-egui/src/sketch_corner_ui_tests.rs | 28 +++++++++ crates/ui-egui/src/sketch_tools.rs | 19 +++--- 4 files changed, 143 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/sketch_corner_tests.rs b/crates/engine/src/cmd/sketch_corner_tests.rs index aca737840..a6e6214e4 100644 --- a/crates/engine/src/cmd/sketch_corner_tests.rs +++ b/crates/engine/src/cmd/sketch_corner_tests.rs @@ -102,6 +102,67 @@ fn driven_by(s: &Session, name: &str) -> Vec { sk(s).constraints.iter().filter(|c| c.param.as_deref() == Some(name)).map(|c| c.id.clone()).collect() } +#[test] +fn fully_defined_rectangles_keep_their_size_when_all_corners_are_filleted() { + for center in [false, true] { + for square in [false, true] { + let mut s = new_sketch(); + let height = if square { 40.0 } else { 20.0 }; + let r = if center { + run(&mut s, "sketch.rectangle.center", json!({"center": [0, 0], "corner": [20, height / 2.0]})) + } else { + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, height]})) + }; + let anchor = if center { "p5" } else { "p1" }; + run(&mut s, "sketch.constraint.coincident", json!({"a": anchor, "b": "origin"})); + let width = run(&mut s, "sketch.dimension", json!({"entities": ["l1"], "value": 40})); + if square { + run(&mut s, "sketch.constraint.equal", json!({"a": "l1", "b": "l2"})); + } else { + run(&mut s, "sketch.dimension", json!({"entities": ["l2"], "value": height})); + } + let info = run(&mut s, "sketch.inspect", json!({})); + assert_eq!(info["dof"], 0, "{info}"); + let points: Vec = ["bottom_left", "bottom_right", "top_right", "top_left"].iter().map(|name| r["corners"][name].clone()).collect(); + for (i, point) in points.iter().enumerate() { + let f = run(&mut s, "sketch.fillet", json!({"point": point, "radius": 3})); + assert_eq!(f["sketch"]["solved"], true, "center={center}, square={square}: {f}"); + assert_eq!(f["sketch"]["dof"], 0, "center={center}, square={square}: {f}"); + let expected = 40.0 * height - (i + 1) as f64 * (9.0 - std::f64::consts::PI * 9.0 / 4.0); + assert!((area(&s) - expected).abs() < 1e-5, "corner={i}, center={center}, square={square}: {} != {expected}", area(&s)); + } + let expected = 40.0 * height - 4.0 * (9.0 - std::f64::consts::PI * 9.0 / 4.0); + assert!((area(&s) - expected).abs() < 1e-5, "center={center}, square={square}: {} != {expected}", area(&s)); + run(&mut s, "parameters.change", json!({"name": width["param"], "expression": "50 mm"})); + assert!(solved(&s)); + let expected = 50.0 * if square { 50.0 } else { height } - 4.0 * (9.0 - std::f64::consts::PI * 9.0 / 4.0); + assert!((area(&s) - expected).abs() < 1e-5, "center={center}, square={square}: {} != {expected}", area(&s)); + let id = s.active_sketch.unwrap(); + let saved = solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap(); + assert_eq!(saved.sketch(id).unwrap(), s.doc.sketch(id).unwrap()); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.redo", json!({})); + assert!((area(&s) - expected).abs() < 1e-5); + } + } +} + +#[test] +fn filleting_a_side_keeps_its_original_midpoint() { + let mut s = new_sketch(); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [-20, 0], "p1": [20, 30]})); + run(&mut s, "sketch.constraint.midpoint", json!({"point": "origin", "line": "l1"})); + run(&mut s, "sketch.dimension", json!({"entities": ["l1"], "value": 40})); + run(&mut s, "sketch.dimension", json!({"entities": ["l2"], "value": 30})); + for point in ["p1", "p2"] { + let f = run(&mut s, "sketch.fillet", json!({"point": point, "radius": 3})); + assert_eq!(f["sketch"]["solved"], true, "{f}"); + assert_eq!(f["sketch"]["dof"], 0, "{f}"); + let (lo, hi) = sk(&s).bounds().unwrap(); + assert!((lo.x + 20.0).abs() < 1e-6 && (hi.x - 20.0).abs() < 1e-6, "{lo:?} {hi:?}"); + } +} + /// 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 diff --git a/crates/engine/src/cmd/sketch_modify.rs b/crates/engine/src/cmd/sketch_modify.rs index 0f321bbf2..65e6325d3 100644 --- a/crates/engine/src/cmd/sketch_modify.rs +++ b/crates/engine/src/cmd/sketch_modify.rs @@ -569,6 +569,44 @@ fn reattach(sk: &mut Sketch, l: usize, corner: usize, np: usize) { } } +/// Equal lengths and midpoints describe the original side, not its shortened tangent +/// segment. Keep that side as construction geometry sharing the original corner points. +/// Later corner cuts retain those points through `keep_corner`, so this also works when +/// the other end is rounded in a separate command. +fn keep_side_relations(sk: &mut Sketch, line: usize) -> Result> { + let affected = |k: &ConstraintKind| { + matches!(*k, ConstraintKind::Equal { a, b } if a == line || b == line) || matches!(*k, ConstraintKind::Midpoint { l, .. } if l == line) + }; + if !sk.constraints.iter().any(|k| affected(&k.kind)) { + return Ok(Vec::new()); + } + let Some(CurveKind::Line { a, b }) = sk.curves.get(line).map(|c| c.kind.clone()) else { return Ok(Vec::new()) }; + let support = sk.add_line_pts(a, b, None)?; + if let Some(c) = sk.curves.get_mut(support) { + c.construction = true; + } + let mut moved = Vec::new(); + for k in &mut sk.constraints { + if !affected(&k.kind) { + continue; + } + match &mut k.kind { + ConstraintKind::Equal { a, b } => { + if *a == line { + *a = support; + } + if *b == line { + *b = support; + } + } + ConstraintKind::Midpoint { l, .. } => *l = support, + _ => {} + } + moved.push(k.id.clone()); + } + Ok(moved) +} + /// What became of a rounded or cut corner's point: kept as a virtual sharp corner (its id), /// and the constraints and dimensions that now measure to it. #[derive(Default)] @@ -642,9 +680,14 @@ fn cut_corner( let v = (pb - pc).normalized().ok_or_else(|| bad(cmd, "degenerate line"))?; let ta = sk.add_point(pc + u * da, None)?; let tb = sk.add_point(pc + v * db, None)?; + let mut moved = keep_side_relations(sk, la)?; + moved.extend(keep_side_relations(sk, lb)?); reattach(sk, la, c, ta); reattach(sk, lb, c, tb); - let kept = keep_corner(sk, c, [(la, ta), (lb, tb)])?; + let mut kept = keep_corner(sk, c, [(la, ta), (lb, tb)])?; + if let Some(k) = &mut kept { + k.moved.extend(moved); + } let removed = kept.is_none(); if removed { sk.remove_points(&[c]); diff --git a/crates/ui-egui/src/sketch_corner_ui_tests.rs b/crates/ui-egui/src/sketch_corner_ui_tests.rs index 73107da72..c07e49d2b 100644 --- a/crates/ui-egui/src/sketch_corner_ui_tests.rs +++ b/crates/ui-egui/src/sketch_corner_ui_tests.rs @@ -378,6 +378,34 @@ fn a_fillet_rounds_every_picked_corner_to_one_radius() { assert!((ss.profiles[0].area - (1200.0 - 3.0 * 25.0 * (1.0 - std::f64::consts::PI / 4.0))).abs() < 1e-6, "{}", ss.profiles[0].area); } +#[test] +fn fully_constrained_center_rectangle_corners_can_be_picked_and_filleted() { + let mut h = crate::scenario::Harness::new(); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + h.app.run("sketch.rectangle.center", json!({"center":[0,0],"corner":[20,15]})).unwrap(); + h.app.run("sketch.constraint.coincident", json!({"a":"p5","b":"origin"})).unwrap(); + h.app.run("sketch.dimension", json!({"entities":["l1"],"value":40})).unwrap(); + h.app.run("sketch.dimension", json!({"entities":["l2"],"value":30})).unwrap(); + h.frames(2); + h.step(&json!({"start":"sketch.fillet"})).unwrap(); + h.frames(2); + for corner in [[-20, -15, 0], [20, -15, 0], [20, 15, 0], [-20, 15, 0]] { + h.step(&json!({"click":{"world":corner}})).unwrap(); + h.frames(2); + } + assert_eq!(h.app.dialog.as_ref().map(|d| d.inputs[0].items.len()), Some(4)); + set_size(&mut h.app, "3"); + apply(&mut h); + assert!(h.app.dialog.is_none(), "{:?}", h.app.status); + let info = h.app.run("sketch.inspect", json!({})).unwrap(); + assert_eq!(info["dof"], 0, "{info}"); + assert_eq!(info["status"], "solved", "{info}"); + let st = h.app.session.world_state(); + let ss = st.sketch(h.app.session.active_sketch.unwrap()).unwrap(); + assert_eq!(ss.sketch.curves.iter().filter(|c| matches!(c.kind, CurveKind::Arc { .. })).count(), 4); + assert!((ss.profiles[0].area - (1200.0 - 36.0 * (1.0 - std::f64::consts::PI / 4.0))).abs() < 1e-6); +} + #[test] fn ordinary_drawing_keeps_origin_snap_and_real_origin_corners_work() { let mut h = crate::scenario::Harness::new(); diff --git a/crates/ui-egui/src/sketch_tools.rs b/crates/ui-egui/src/sketch_tools.rs index 4ee4ea9b3..cc93ae56a 100644 --- a/crates/ui-egui/src/sketch_tools.rs +++ b/crates/ui-egui/src/sketch_tools.rs @@ -460,17 +460,18 @@ fn sketch_entity(app: &SolveApp, hits: &[Hit]) -> Option<(String, bool)> { } /// The two editable curves that meet at sketch point `pi`, in curve order, which is the order -/// the corner commands resolve them in from a `point` parameter. None unless exactly two meet -/// there and each is one the command can work on: a line always, an arc only for a fillet. +/// the corner commands resolve them in from a `point` parameter. Construction curves are +/// ignored when more than two meet. Each side must be a line, or an arc for a fillet. pub(crate) fn corner_curves(sk: &solidcraft_engine::sketch::Sketch, pi: usize, arcs_ok: bool) -> Option<(usize, usize)> { use solidcraft_engine::sketch::CurveKind; - let curves: Vec<_> = sk - .curves - .iter() - .enumerate() - .filter(|(ci, c)| !sk.is_linked_curve(*ci) && c.kind.ends().is_some_and(|(a, b)| a == pi || b == pi)) - .take(3) - .collect(); + let candidates = + sk.curves.iter().enumerate().filter(|(ci, c)| !sk.is_linked_curve(*ci) && c.kind.ends().is_some_and(|(a, b)| a == pi || b == pi)); + let mut curves: Vec<_> = candidates.clone().take(3).collect(); + // Center rectangles have construction diagonals at their corners. Match the engine's + // corner selection: when more than two curves meet, use the profile sides. + if curves.len() > 2 { + curves = candidates.filter(|(_, c)| !c.construction).take(3).collect(); + } if curves.iter().any(|(_, c)| !matches!(c.kind, CurveKind::Line { .. }) && !(arcs_ok && matches!(c.kind, CurveKind::Arc { .. }))) { return None; } From abb15e4b0e89da7f769d15e889278e12d1bc7548 Mon Sep 17 00:00:00 2001 From: cronos Date: Fri, 16 Oct 2026 10:27:29 +0900 Subject: [PATCH 25/92] Preserve circle and arc centre heights when measuring straight edges (#1546) Thanks @crono2250 for the fix. Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/cmd/measure_shape.rs | 61 +++++++++++++++++++++-- crates/engine/src/measure_centre_tests.rs | 29 +++++++++++ 2 files changed, 86 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/measure_shape.rs b/crates/engine/src/cmd/measure_shape.rs index 5c7f4ad9c..00f958c86 100644 --- a/crates/engine/src/cmd/measure_shape.rs +++ b/crates/engine/src/cmd/measure_shape.rs @@ -215,11 +215,22 @@ fn from_round(a: &Shape, b: &Shape) -> Option { } Shape::Line { a: la, b: lb } => { let dir = (lb - la).normalized()?; - let (p, q) = line_line(ca, na, la, dir); - let d = p.dist(q); let across = dir.dot(na).abs() < 1e-6; - let min = (full_a && across && d >= ra).then_some(d - ra); - Centre { distance: d, from: p, to: q, min, max: None } + if pa { + // A circle/arc has a fixed centre. Project that point onto the picked + // finite edge, retaining the height difference and clamping to its ends. + let to = la + dir * (ca - la).dot(dir).clamp(0.0, (lb - la).len()); + let offset = to - ca; + let height = offset.dot(na); + let radial = (offset - na * height).len(); + let min = (full_a && across && radial >= ra).then(|| (radial - ra).hypot(height)); + Centre { distance: ca.dist(to), from: ca, to, min, max: None } + } else { + let (p, q) = line_line(ca, na, la, dir); + let d = p.dist(q); + let min = (full_a && across && d >= ra).then_some(d - ra); + Centre { distance: d, from: p, to: q, min, max: None } + } } Shape::Point(p) => { if pa { @@ -410,6 +421,48 @@ mod tests { assert!(c.from.dist(Vec3::new(10.0, 15.0, 10.0)) < 1e-12 && c.to.dist(Vec3::new(10.0, 0.0, 10.0)) < 1e-12); } + #[test] + 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 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); + if angle == TAU { + assert!((c.min.unwrap() - 13_f64.hypot(14.0)).abs() < 1e-12); + } else { + assert!(c.min.is_none()); + } + let swapped = centre(&edge, &round).unwrap(); + assert_eq!((swapped.from, swapped.to, swapped.distance), (c.to, c.from, c.distance)); + } + } + + #[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] { + 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); + assert!(c.to.dist(Vec3::new(4.5, 0.0, 4.5)) < 1e-12); + assert!((c.distance - 20.5_f64.sqrt()).abs() < 1e-12); + } + } + + #[test] + fn a_circle_center_to_a_finite_edge_does_not_use_its_extension() { + for (center, expected) in [(Vec3::new(20.0, 3.0, 4.0), Vec3::new(10.0, 0.0, 0.0)), (Vec3::new(-10.0, 3.0, 4.0), Vec3::ZERO)] { + for (a, b) in [(Vec3::ZERO, Vec3::new(10.0, 0.0, 0.0)), (Vec3::new(10.0, 0.0, 0.0), Vec3::ZERO)] { + let c = centre(&circle(center, 2.0), &Shape::Line { a, b }).unwrap(); + assert_eq!((c.from, c.to), (center, expected)); + assert!((c.distance - 125_f64.sqrt()).abs() < 1e-12); + } + } + assert!(centre(&circle(Vec3::ZERO, 2.0), &Shape::Line { a: Vec3::ZERO, b: Vec3::ZERO }).is_none()); + } + #[test] fn coverage_of_a_half_and_a_whole_ring() { let ring = |n: usize, span: f64| -> Vec { diff --git a/crates/engine/src/measure_centre_tests.rs b/crates/engine/src/measure_centre_tests.rs index 3526597cd..1fbae18d7 100644 --- a/crates/engine/src/measure_centre_tests.rs +++ b/crates/engine/src/measure_centre_tests.rs @@ -137,6 +137,35 @@ fn elevated_cylinder_rims_measure_between_the_picked_circles_centres() { } } +#[test] +fn an_elevated_circle_to_a_straight_edge_keeps_its_height_difference() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length":68,"width":50,"height":6,"body_name":"Plate"})); + run(&mut s, "solid.cylinder", json!({"base":[34,25,6],"radius":12,"height":14,"body_name":"Boss","operation":"new_body"})); + let straight = edge(&s, |p| p.y.abs() < 1e-9 && (p.z - 6.0).abs() < 1e-9); + let round = { + let st = s.model.state(); + let b = st.bodies.iter().find(|b| b.name == "Boss").unwrap(); + let m = b.mesh(); + let index = m.edges.iter().position(|e| e.len() > 2 && e.iter().all(|p| (p.z - 20.0).abs() < 1e-9)).unwrap(); + let e = &m.edges[index]; + json!({"type":"edge","body":b.name,"index":index,"point":e[e.len()/2]}) + }; + for items in [vec![straight.clone(), round.clone()], vec![round, straight]] { + let r = measure(&mut s, items); + assert!(close(&r["center_distance"], 25_f64.hypot(14.0), 1e-9), "{r}"); + let (line, circle) = if r["items"][0]["round"] == "circle" { ("center_to", "center_from") } else { ("center_from", "center_to") }; + for (key, expected) in [(line, [34.0, 0.0, 6.0]), (circle, [34.0, 25.0, 20.0])] { + for (axis, value) in expected.into_iter().enumerate() { + assert!(close(&r[key][axis], value, 1e-9), "{r}"); + } + } + assert!((r["center_delta"][2].as_f64().unwrap().abs() - 14.0).abs() < 1e-9, "{r}"); + assert!(close(&r["min"], 13_f64.hypot(14.0), 1e-9), "{r}"); + assert!(close(&r["max"], (34_f64.hypot(25.0) + 12.0).hypot(14.0), 0.05), "{r}"); + } +} + #[test] fn a_hole_to_the_plate_edge_and_side_measures_from_its_axis() { let mut s = Session::default(); From a6742180a90b48bfdc84901de7a0eeaab197d666 Mon Sep 17 00:00:00 2001 From: Mateusz Sych <151755914+SychPL@users.noreply.github.com> Date: Fri, 16 Oct 2026 03:27:35 +0200 Subject: [PATCH 26/92] Join from a sketch on a body's face joins that body (#1349) (#1526) Thanks @SychPL for the fix. Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/cmd/face_join_tests.rs | 41 ++++++++++++++++++++++++ crates/engine/src/cmd/features.rs | 22 ++++++++++--- 2 files changed, 59 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/face_join_tests.rs b/crates/engine/src/cmd/face_join_tests.rs index 20dce23b6..12d1f95cc 100644 --- a/crates/engine/src/cmd/face_join_tests.rs +++ b/crates/engine/src/cmd/face_join_tests.rs @@ -125,3 +125,44 @@ fn face_join_of_a_step_import_keeps_all_32_neighbours_unchanged() { let FeatureKind::Extrude { targets, .. } = &s.doc.feature(result["feature"].as_u64().unwrap()).unwrap().kind else { panic!("extrude") }; assert_eq!(targets, &["Wall"]); } + +/// #1349: a profile sketched on a body's face joins that body, and leaves alone a neighbour +/// whose face it lies on too: a rib on the side of a bracket, drawn down over the motor the +/// bracket sits on, welded the motor in (a join that ran for minutes on the imported motor and +/// failed). Explicit targets still join both. +#[test] +fn join_of_a_profile_sketched_on_a_face_leaves_a_neighbour_it_lies_on() { + for targets in [None, Some(json!(["Bracket", "Motor"]))] { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length":40,"width":30,"height":20,"body_name":"Motor"})); + run(&mut s, "solid.box", json!({"corner":[0,0,20],"length":40,"width":30,"height":5,"body_name":"Bracket"})); + let sketch = run(&mut s, "sketch.create", json!({"plane": {"face": [40, 15, 22.5]}}))["sketch"].as_u64().unwrap(); + let plane = s.model.state().sketch(sketch).unwrap().plane; + let at = |y: f64, z: f64| { + let p = plane.to_local(Vec3::new(40.0, y, z)); + json!([p.x, p.y]) + }; + // On the bracket's side and down over the motor's. + run(&mut s, "sketch.rectangle.two_point", json!({"p0": at(5.0, 10.0), "p1": at(25.0, 25.0)})); + run(&mut s, "sketch.finish", json!({})); + let mut params = + json!({"sketch": sketch, "profiles": [{"point": at(15.0, 22.5)}, {"point": at(15.0, 15.0)}], "distance": 1, "operation": "join"}); + if let Some(t) = &targets { + params["targets"] = t.clone(); + } + let result = run(&mut s, "solid.extrude", params); + assert!(s.model.results.iter().all(|r| r.error.is_none()), "{:?}", s.model.results); + let state = s.model.state(); + let volume = |name: &str| solidcraft_kernel::measure(&state.body(name).unwrap().body).unwrap().volume; + if targets.is_some() { + assert_eq!(state.bodies.len(), 1); + assert!((volume("Bracket") - (24_000.0 + 6000.0 + 300.0)).abs() < 1e-6, "{}", volume("Bracket")); + continue; + } + assert_eq!(state.bodies.len(), 2); + assert!((volume("Motor") - 24_000.0).abs() < 1e-6, "the motor is untouched"); + assert!((volume("Bracket") - (6000.0 + 300.0)).abs() < 1e-6, "{}", volume("Bracket")); + let FeatureKind::Extrude { targets, .. } = &s.doc.feature(result["feature"].as_u64().unwrap()).unwrap().kind else { panic!("extrude") }; + assert_eq!(targets, &["Bracket"]); + } +} diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs index facd8beed..ce17bea52 100644 --- a/crates/engine/src/cmd/features.rs +++ b/crates/engine/src/cmd/features.rs @@ -15,7 +15,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); 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 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); 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"), CommandSpec::new("solid.revolve", "Revolve", revolve) .at("SOLID", "CREATE") .icon("revolve") @@ -552,10 +552,13 @@ fn extrude(s: &mut Session, p: &Value) -> Result { }; let mut targets = string_list(p, "targets"); if operation == Operation::Join && targets.is_empty() && string_list(p, "participants").is_empty() { - // A face's outward extension joins that body. Assembly neighbours can touch only an - // edge of the tool: trying to join them first fails, or absorbs unrelated parts (#226). + // A face's outward extension joins that body, and so does a profile sketched on a body's + // face. Assembly neighbours can touch only an edge of the tool: trying to join them + // first fails, or absorbs unrelated parts (#226). A profile drawn past the face can lie + // on a neighbour's face too: a rib on a bracket's side welded in the motor the bracket + // holds, a join that ran for minutes and failed (#1349). // Store the resolved target so recomputes and reopening keep the same scope. - targets.extend(face_body); + targets.extend(face_body.or_else(|| sketch_face_body(s, sketch))); } let kind = FeatureKind::Extrude { sketch, @@ -572,6 +575,17 @@ fn extrude(s: &mut Session, p: &Value) -> Result { add_feature(s, p, kind) } +/// The body whose face `sketch` is attached to (on the face itself, not offset from it), when +/// it is a body of the active component. +fn sketch_face_body(s: &Session, sketch: u64) -> Option { + let FeatureKind::Sketch { plane: solidcraft_doc::PlaneRef::Face { anchor: Some(anchor), .. }, .. } = &s.doc.feature(sketch)?.kind else { + return None; + }; + let st = s.model.state(); + let body = st.body(&anchor.target.body)?; + (s.doc.model_body_component(body) == s.active_component).then(|| body.name.clone()) +} + /// A thin extrude's wall from its parameters: the sketch's curves it follows (every drawn /// curve when none are given), its thickness and which side of them it lies on. fn thin_param(s: &Session, p: &Value, sketch: u64, cmd: &str) -> Result { From 342305705d2e01b367b1fdd0642f5fbc52dd381c Mon Sep 17 00:00:00 2001 From: Colin Faulkingham Date: Thu, 15 Oct 2026 20:27:50 -0500 Subject: [PATCH 27/92] Add XAI Grok to the AI panel (#1558) Grok Build is added as one more entry in the agent discovery list, over ACP, like the others. Thanks @cfaulkingham. Co-Authored-By: Claude Sonnet 5.5 --- ROADMAP.md | 5 +++-- crates/ui-egui/src/agent_chat/discover.rs | 23 +++++++++++++++++++++-- docs/agent-chat.md | 18 ++++++++++++++++-- docs/design/in-app-agent-chat.md | 1 + 4 files changed, 41 insertions(+), 6 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 68b101950..90a2c2618 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -228,12 +228,13 @@ annotations and exact projected curves remain deferred. See [view DXF](docs/view `diagnostics.crash_reports`, the MCP `crash_reports` tool or the CLI. Nothing is sent anywhere. See [crash reports](docs/crash-reports.md). - Agent chat (off by default, desktop): a side panel that drives a coding agent the user - already has (Claude Code through its ACP adapter, Codex, Gemini CLI, OpenCode, …) over the + already has (Claude Code through its ACP adapter, Codex, Gemini CLI, OpenCode, Grok Build, …) over the Agent Client Protocol, under the user's own login; SolidCraft stores no keys. The agent works through SolidCraft's MCP tools on a gated endpoint of its own: file actions wait for Allow or Deny, crash reports are off limits, 24 changes per message, one undo step per message, and the agent's whole process group ends with the panel or the app. Docks left or right, - minimises to a strip. See [agent chat](docs/agent-chat.md). + minimises to a strip. Grok Build discovery includes `~/.grok/bin` and reuses the user's + Grok login. See [agent chat](docs/agent-chat.md). - Command scripts from designs (#886): `timeline.export_script` (CLI `solidcraft-cli script`) writes a design's history as a script that `eval` and `run` replay into the same design — user parameters, units, sheet metal and plastic rules and materials as their own commands, diff --git a/crates/ui-egui/src/agent_chat/discover.rs b/crates/ui-egui/src/agent_chat/discover.rs index bdbf28099..c7f24c690 100644 --- a/crates/ui-egui/src/agent_chat/discover.rs +++ b/crates/ui-egui/src/agent_chat/discover.rs @@ -68,6 +68,16 @@ pub const KNOWN: &[Known] = &[ config_dir_var: None, key_vars: &[], }, + Known { + id: "grok", + name: "XAI Grok", + programs: &["grok"], + args: &["agent", "stdio"], + install: "see https://docs.x.ai/build/overview (Grok Build installer); then run grok login", + credentials: Some(".grok/auth.json"), + config_dir_var: None, + key_vars: &["XAI_API_KEY"], + }, Known { id: "copilot", name: "GitHub Copilot CLI", @@ -153,14 +163,14 @@ fn home() -> Option { std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" }).map(PathBuf::from).filter(|p| p.is_absolute()) } -/// PATH, then the usual places npm, Homebrew, nvm, Volta, bun and pipx put commands. +/// PATH, then the usual places npm, Homebrew, nvm, Volta, bun, pipx and Grok put commands. pub fn search_dirs() -> Vec { let mut dirs: Vec = std::env::var_os("PATH").map(|p| std::env::split_paths(&p).collect()).unwrap_or_default(); if let Some(prefix) = std::env::var_os("NPM_CONFIG_PREFIX").map(PathBuf::from) { dirs.push(if cfg!(windows) { prefix.clone() } else { prefix.join("bin") }); } if let Some(h) = home() { - for d in [".local/bin", ".npm-global/bin", ".npm-packages/bin", ".volta/bin", ".bun/bin", ".cargo/bin", "bin"] { + for d in [".local/bin", ".npm-global/bin", ".npm-packages/bin", ".volta/bin", ".bun/bin", ".cargo/bin", ".grok/bin", "bin"] { dirs.push(h.join(d)); } // nvm: every installed Node version's bin. @@ -326,6 +336,7 @@ mod tests { assert_eq!(version_of("@agentclientprotocol/codex-acp 2.2.2"), "2.2.2"); assert_eq!(version_of("2.1.295 (Claude Code)"), "2.1.295"); assert_eq!(version_of("goose v1.9.0"), "v1.9.0"); + assert_eq!(version_of("grok 1.0.58 (26283d10dd58) [alpha]"), "1.0.58"); assert_eq!(version_of("dev build"), "dev build"); } @@ -336,6 +347,7 @@ mod tests { let gemini = KNOWN.iter().find(|k| k.id == "gemini").unwrap(); let qwen = KNOWN.iter().find(|k| k.id == "qwen").unwrap(); let goose = KNOWN.iter().find(|k| k.id == "goose").unwrap(); + let grok = KNOWN.iter().find(|k| k.id == "grok").unwrap(); if std::env::var_os("GEMINI_API_KEY").is_none() && std::env::var_os("GOOGLE_API_KEY").is_none() { assert_eq!(login_of(gemini, Some(&home)), Login::NotLoggedIn); } @@ -345,6 +357,13 @@ mod tests { assert_eq!(login_of(qwen, Some(&home)), Login::NotLoggedIn); } assert_eq!(login_of(goose, Some(&home)), Login::Unknown, "keeps no file we know"); + if std::env::var_os("XAI_API_KEY").is_none() { + assert_eq!(login_of(grok, Some(&home)), Login::NotLoggedIn); + } + std::fs::create_dir_all(home.join(".grok")).unwrap(); + // Discovery checks only for the file; it never needs to parse the user's tokens. + std::fs::write(home.join(".grok/auth.json"), "not credential data").unwrap(); + assert_eq!(login_of(grok, Some(&home)), Login::LooksLoggedIn); let _ = std::fs::remove_dir_all(home); } diff --git a/docs/agent-chat.md b/docs/agent-chat.md index 756060c18..f3981244d 100644 --- a/docs/agent-chat.md +++ b/docs/agent-chat.md @@ -1,7 +1,7 @@ # Agent chat Agent chat is a side panel where you talk to a coding agent you already use (Claude Code, -Codex, Gemini CLI, OpenCode and others), or to a model behind an OpenAI-compatible endpoint you +Codex, Gemini CLI, OpenCode, Grok Build and others), or to a model behind an OpenAI-compatible endpoint you choose (Ollama or LM Studio on your computer, OpenAI, any other URL), and have it work on the design that's open. A coding agent runs on your computer under **your own account** with that agent: SolidCraft doesn't sell or proxy a model and needs no key for it. An endpoint's key, if @@ -53,7 +53,7 @@ conversation starts with), its own permission setting, and **Remove** for the on SolidCraft looks for agents that speak the [Agent Client Protocol](https://agentclientprotocol.com) on your `PATH` and in the usual install folders a desktop app's `PATH` often misses (npm's -global folder, nvm, Volta, bun, `~/.local/bin`, Homebrew, `%APPDATA%\npm`). For each one it +global folder, nvm, Volta, bun, `~/.local/bin`, `~/.grok/bin`, Homebrew, `%APPDATA%\npm`). For each one it shows its **version** (from `--version`, given three seconds) and whether it looks **signed in**. SolidCraft only checks whether the agent's own login file (`~/.claude/.credentials.json`, `~/.codex/auth.json`, `~/.gemini/oauth_creds.json`, …) or one of its key variables exists. It never @@ -66,12 +66,26 @@ the keychain, so SolidCraft doesn't guess there. | Codex | `npm install -g @agentclientprotocol/codex-acp` | | Gemini CLI | `npm install -g @google/gemini-cli` (it speaks ACP itself: `gemini --acp`) | | OpenCode | `npm install -g opencode-ai` (`opencode acp`) | +| XAI Grok | [Grok Build installer](https://docs.x.ai/build/overview), then `grok login` (`grok agent stdio` speaks ACP) | | GitHub Copilot CLI, Qwen Code, goose | listed with their install command when missing | The panel lists agents that aren't installed with their install command and a **Copy** button. **Refresh** looks again after you install one. **Test** starts an agent briefly, asks it for a session and ends it again. +### XAI Grok + +Install **Grok Build** and run `grok login` in a terminal to sign in with your Grok account. +In SolidCraft, open **AI → Refresh**, select +**XAI Grok**, then **Connect**. You can make it the default under +**Preferences → AI → Agents**. + +SolidCraft reuses Grok Build's sign-in in `~/.grok/auth.json`; it checks only whether that file +exists and does not read or copy its tokens. If sign-in is needed, the panel offers Grok's own +sign-in methods. You can also run `grok login` again and reconnect. Grok controls model access +and usage limits for your account. This connection does not require an API key in SolidCraft. +Grok Build also supports `XAI_API_KEY` for users who choose API authentication. + ### Add agent… - **Installed agent:** your own entry for an installed agent, for example with other arguments. diff --git a/docs/design/in-app-agent-chat.md b/docs/design/in-app-agent-chat.md index 56f65a273..8db181ba5 100644 --- a/docs/design/in-app-agent-chat.md +++ b/docs/design/in-app-agent-chat.md @@ -50,6 +50,7 @@ with SolidCraft, the user installs the agent. | Codex | `codex-acp` adapter (`@zed-industries/codex-acp` 0.16 moved to `@agentclientprotocol/codex-acp`) | `@agentclientprotocol/codex-acp` 2.2.2, Apache-2.0 | `--version` (0.16 rejected the flag; 2.x prints it) | Agent method `chat-gpt` (the adapter opens the browser for the ChatGPT login when the client calls `authenticate`), and `api-key` for a key the user configures in Codex. 0.16 also listed `env_var` methods for `CODEX_API_KEY` / `OPENAI_API_KEY`. The login is Codex's own: `~/.codex/auth.json`. | | Gemini CLI | built in: `gemini --acp` (the ACP registry's current flag; older releases used `--experimental-acp`) | `@google/gemini-cli` 0.64, Apache-2.0 | `--version` | Its own Google login (`~/.gemini/oauth_creds.json`) or a key in the environment. | | OpenCode | built in: `opencode acp` | `opencode-ai` 1.19, MIT | `--version` | Its own providers' logins (`~/.local/share/opencode/auth.json`) or keys in the environment. | +| XAI Grok | built in: `grok agent stdio` | [Grok Build](https://github.com/xai-org/grok-build), Apache-2.0; installed separately | `grok --version` prints `grok 1.0.58 (…) [alpha]` (checked 2026-10-15; in-app connection also checked with 1.0.60) | Its own `~/.grok/auth.json` or `XAI_API_KEY`. `grok login` signs in in the browser; ACP advertises `cached_token` and `grok.com` authentication methods. | | Others in the ACP registry | `copilot --acp`, `qwen --acp`, `opencode acp`, `goose acp`, `cline --acp`, `kimi acp`, … | mixed; several are proprietary, one is GPL and one AGPL (we only start them as programs, never link them) | `--version` | each its own | The registry (`https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json`) lists From f08ed74617364ba11ea6fe47ea8d63d62c89afc2 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Thu, 15 Oct 2026 21:59:52 -0400 Subject: [PATCH 28/92] Keep the files many PRs add to conflict-free (#1564) Message catalogs sorted one message per line (cargo xtask lists [--fix], checked in cargo xtask ci and the Lists workflow); the language list one per line, English first then by id; THIRD-PARTY-LICENSES.txt and docs/features.md rewritten on main by the Generated files workflow instead of in PRs. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/generated.yml | 48 + .github/workflows/lists.yml | 12 + AGENTS.md | 10 +- CLAUDE.md | 10 +- CONTRIBUTING.md | 22 +- assets/locales/de.json | 1741 +++++++++++++++---------------- assets/locales/en.json | 1297 ++++++++++++----------- assets/locales/fr.json | 1126 ++++++++++---------- assets/locales/ja.json | 1297 ++++++++++++----------- assets/locales/ko.json | 1741 +++++++++++++++---------------- assets/locales/ru.json | 990 +++++++++--------- assets/locales/tr.json | 1222 +++++++++++----------- assets/locales/uk.json | 876 ++++++++-------- assets/locales/zh.json | 1309 ++++++++++++----------- crates/ui-egui/src/i18n.rs | 28 +- xtask/src/licences.rs | 11 +- xtask/src/lists.rs | 68 ++ xtask/src/main.rs | 10 +- 18 files changed, 6001 insertions(+), 5817 deletions(-) create mode 100644 .github/workflows/generated.yml create mode 100644 xtask/src/lists.rs diff --git a/.github/workflows/generated.yml b/.github/workflows/generated.yml new file mode 100644 index 000000000..20951305c --- /dev/null +++ b/.github/workflows/generated.yml @@ -0,0 +1,48 @@ +# Files generated from the code are rewritten here, on main, after each merge, so pull requests +# never edit them (two pull requests that each regenerated one would always conflict): +# THIRD-PARTY-LICENSES.txt (`cargo xtask licences`) and docs/features.md (`cargo xtask features`). +name: Generated files + +on: + push: + branches: [main] + workflow_dispatch: + +permissions: + contents: write + +# One run at a time; a burst of merges leaves one run waiting, which sees all of them. +concurrency: + group: generated-files + cancel-in-progress: false + +jobs: + regenerate: + name: Regenerate and commit + runs-on: ubuntu-24.04 + timeout-minutes: 60 + steps: + # Always main itself, never pull request code, since this job can push. + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: main + - uses: dtolnay/rust-toolchain@stable + - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 + with: + key: generated-files + - name: THIRD-PARTY-LICENSES.txt + run: cargo xtask licences + - name: docs/features.md + run: cargo xtask features + - name: Commit if changed + run: | + if git diff --quiet -- THIRD-PARTY-LICENSES.txt docs/features.md; then echo "unchanged"; exit 0; fi + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + git add THIRD-PARTY-LICENSES.txt docs/features.md + git commit -m "Regenerate THIRD-PARTY-LICENSES.txt and docs/features.md [skip ci]" + for _ in 1 2 3; do + git pull --rebase origin main && git push origin HEAD:main && exit 0 + sleep 10 + done + exit 1 diff --git a/.github/workflows/lists.yml b/.github/workflows/lists.yml index 0e4da028c..54c4daf37 100644 --- a/.github/workflows/lists.yml +++ b/.github/workflows/lists.yml @@ -18,3 +18,15 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - run: bash scripts/test-format-pending.sh + + sorted: + name: Lists are sorted one item per line + runs-on: ubuntu-24.04 + timeout-minutes: 15 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: dtolnay/rust-toolchain@stable + - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 + with: + key: lists + - run: cargo xtask lists diff --git a/AGENTS.md b/AGENTS.md index 9c669979f..f61b51e37 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -160,5 +160,11 @@ before the draft is verified. ## Roadmap `ROADMAP.md` (committed) tracks status, milestones and estimates. Update it whenever a -milestone task lands. `cargo xtask features` regenerates `docs/features.md` (SolidCraft's -commands by area, from the registry) when commands are added or renamed. +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. diff --git a/CLAUDE.md b/CLAUDE.md index b3a508e4f..3becde411 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -133,5 +133,11 @@ before the draft is verified. ## Roadmap `ROADMAP.md` (committed) tracks status, milestones and estimates. Update it whenever a -milestone task lands. `cargo xtask features` regenerates `docs/features.md` (SolidCraft's -commands by area, from the registry) when commands are added or renamed. +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. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 5fc5f89a8..c835471a0 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -98,8 +98,8 @@ The [README](README.md#architecture) has the layer table. The short version: MIT OR Apache-2.0, and its solver and blends are written from the maths. (Running an open-source application to get reference values for a test is fine; reading its source is not.) Permissive - dependencies are fine. Note which one you're adding and why in the PR, and run - `cargo xtask licences` so THIRD-PARTY-LICENSES.txt lists it (CI checks that it is current). + dependencies are fine. Note which one you're adding and why in the PR. THIRD-PARTY-LICENSES.txt + lists it once the change lands: the Generated files workflow rewrites it on `main`. Nightly/manual CI also scans advisories, bans and sources with cargo-deny; see [the local command and coverage limits](docs/book/src/dev/testing.md#dependency-advisories). 3. **Every asset is original or openly licensed and has a row in @@ -224,6 +224,24 @@ a conflict. `crates/doc/src/format/pending/README.md` has an example. files into `crates/doc/src/format/v/` and fixes that number for good (see [docs/releasing.md](docs/releasing.md)). Never add a file to a `v/` folder afterwards. +## Lists many changes add to + +Some files gain an item in many pull requests at once. They are kept so that two changes that +each add an item only meet when their items are neighbours, which spares everyone a conflict +and a fresh CI run: + +- **Message catalogs** (`assets/locales/*.json`): one message per line, sorted by id. Add your + message anywhere and run `cargo xtask lists --fix`; `cargo xtask lists` (in `cargo xtask ci` + and the Lists workflow) fails on an unsorted catalog or an id that appears twice. +- **`mod` lines**: one per line, in the sorted group they belong to (`cargo fmt` keeps each group + sorted). Add a new module into the existing group, not as a new group at the end. +- **Languages** (`crates/ui-egui/src/i18n.rs`): one per line, English first, then by id (a test + checks it). +- **Generated files**: `THIRD-PARTY-LICENSES.txt` and `docs/features.md` are rewritten on `main` + after each merge by the Generated files workflow (`cargo xtask licences`, `cargo xtask + features`). Don't regenerate or edit them in a pull request. +- **Design format**: one file per change, never an edit to a shared number (above). + ## Sending a change 1. Work is tracked in [GitHub issues](https://github.com/bherbruck/solidcraft/issues), labelled diff --git a/assets/locales/de.json b/assets/locales/de.json index 5e9164560..e55fd08f7 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -1,670 +1,90 @@ { - "settings.measure_axis_distances": "X/Y/Z-Maße anzeigen", - "settings.measure_axis_distances_help": "Bei geöffneter Messung die Abstände entlang der Weltachsen zusätzlich zum Gesamtabstand anzeigen.", - "Export Current View as DXF": "Aktuelle Ansicht als DXF exportieren", - "Export Current View as DXF…": "Aktuelle Ansicht als DXF exportieren…", - "Hidden edges": "Verdeckte Kanten", - "Do not export hidden edges": "Verdeckte Kanten nicht exportieren", - "Export hidden edges as dashed lines": "Verdeckte Kanten gestrichelt exportieren", - "Projection": "Projektion", - "Current perspective view": "Aktuelle perspektivische Ansicht", - "Current orthographic view (1:1 mm)": "Aktuelle orthogonale Ansicht (1:1 mm)", - "Visible bodies only. Curves use line segments (0.01 mm tolerance).": "Nur sichtbare Körper. Kurven werden durch Liniensegmente angenähert (Toleranz: 0,01 mm).", - "Turn off section analysis before exporting the view.": "Deaktivieren Sie die Schnittanalyse, bevor Sie die Ansicht exportieren.", - "No visible bodies to export.": "Keine sichtbaren Körper zum Exportieren.", - "Export DXF…": "DXF exportieren…", - "Send your report on GitHub": "Bericht auf GitHub senden", "1. Open GitHub draft below, then paste the report copied to your clipboard.": "1. Unten den GitHub-Entwurf öffnen und den kopierten Bericht aus der Zwischenablage einfügen.", "1. Open GitHub draft below. Your title and report will be filled in.": "1. Unten den GitHub-Entwurf öffnen. Titel und Bericht werden vorausgefüllt.", "2. Attach your screenshot: copy and paste it, or save and upload the PNG.": "2. Screenshot anhängen: kopieren und einfügen oder als PNG speichern und hochladen.", "3. Click Submit new issue on GitHub to send your report.": "3. Auf GitHub auf Submit new issue klicken, um den Bericht zu senden.", - "nav.touchpad.label": "Touchpad", - "nav.touchpad.help": "Umschalt gedrückt halten und den Zeiger zum Verschieben bewegen; mit Alt/Option drehen. Keine Maustaste nötig. Vertikales Scrollen zoomt.", - "nav.touchpad.orbit": "Drehen (Alt/Option halten und bewegen; ohne Maustaste)", - "nav.touchpad.pan": "Verschieben (Umschalt halten und bewegen; ohne Maustaste)", - "nav.touchpad.zoom": "Zoom (vertikal scrollen oder Finger spreizen/zusammenziehen)", - "nav.touchpad.scroll": "Touchpad verwendet vertikales Scrollen zum Zoomen. Die Zwei-Finger-Verschiebung bleibt für andere Vorgaben gespeichert.", + "AI": "KI", + "Arc length": "Bogenlänge", + "Area": "Fläche", + "BROWSER": "BROWSER", + "Bends": "Biegungen", + "Centre to centre": "Mitte zu Mitte", + "Circumference": "Umfang", + "Construction": "Konstruktionslinie", + "Copy Error Message": "Fehlermeldung kopieren", + "Copy Warning Message": "Warnmeldung kopieren", + "Corner Relief": "Eckenentlastung", + "Current orthographic view (1:1 mm)": "Aktuelle orthogonale Ansicht (1:1 mm)", + "Current perspective view": "Aktuelle perspektivische Ansicht", + "Do not export hidden edges": "Verdeckte Kanten nicht exportieren", + "Drive Joint": "Gelenk antreiben", + "Edges": "Kanten", + "Edit Profile Sketch": "Profile-Skizze bearbeiten", + "Export Current View as DXF": "Aktuelle Ansicht als DXF exportieren", + "Export Current View as DXF…": "Aktuelle Ansicht als DXF exportieren…", + "Export DXF…": "DXF exportieren…", + "Export hidden edges as dashed lines": "Verdeckte Kanten gestrichelt exportieren", + "Face": "Fläche", + "Faces": "Flächen", + "Find in Browser": "Im Browser suchen", + "Flat": "Flach", + "Hidden edges": "Verdeckte Kanten", + "Holes": "Löcher", + "Holes (edges on them)": "Löcher (ihre Kanten)", + "In place (surfaces)": "An Ort und Stelle (Flächen)", + "Inside": "Innen", + "Length": "Länge", + "Max": "Max", + "Min": "Min", + "Mitre": "Gehrung", + "No visible bodies to export.": "Keine sichtbaren Körper zum Exportieren.", + "None": "Keine", + "Notch": "Ausklinkung", + "Outside": "Außen", + "Overall length": "Gesamtlänge", + "Picked": "Ausgewählte", + "Profiles/Curves": "Profile/Kurven", + "Projection": "Projektion", + "RULED SURFACE": "REGELFLÄCHE", + "Rectangular": "Rechteckig", + "Reference face": "Referenzfläche", + "Report a bug — review a screenshot and open a GitHub draft": "Fehler melden — Screenshot prüfen und einen GitHub-Entwurf öffnen", + "Reset Toolbar": "Symbolleiste zurücksetzen", + "Restore outer boundary": "Äußere Begrenzung wiederherstellen", + "Revert Position": "Position zurücksetzen", + "Round": "Rund", + "Select bodies (a face picks its body)": "Körper auswählen (eine Fläche wählt ihren Körper)", + "Selection filter": "Auswahlfilter", + "Send your report on GitHub": "Bericht auf GitHub senden", + "Sketch constraints": "Skizzenbedingungen", + "Sketch curves": "Skizzenkurven", + "Sketch dimensions": "Skizzenmaße", + "Sketch geometry and profiles": "Skizzengeometrie und Profile", + "Sketch points": "Skizzenpunkte", + "Slot width": "Langlochbreite", + "Tear": "Reißen", + "Thickness Outside": "Dicke außen", + "Thin": "Dünnwandig", + "Thin Extrude": "Dünnwandig extrudieren", + "Turn off section analysis before exporting the view.": "Deaktivieren Sie die Schnittanalyse, bevor Sie die Ansicht exportieren.", + "Type": "Typ", + "UNTRIM": "TRIMMEN AUFHEBEN", + "Vertices": "Scheitelpunkte", + "Visible bodies only. Curves use line segments (0.01 mm tolerance).": "Nur sichtbare Körper. Kurven werden durch Liniensegmente angenähert (Toleranz: 0,01 mm).", + "Wall Location": "Wandlage", + "Wall Thickness": "Wandstärke", + "appearance.dielectric_ior": "Brechungsindex des Dielektrikums", + "appearance.metallic": "Metallanteil", + "appearance.pbr_help": "Diese Oberfläche in Render oder einem Produkt-PNG ansehen. Keine Brechung oder Transmission.", + "appearance.pbr_opaque": "Opakes PBR", + "appearance.roughness": "Rauheit", + "appearance.surface_response": "Oberflächenverhalten", "browser.body_name": "Körper {number}", "browser.component_name": "Komponente {number}", "browser.parameters": "Parameter ({count})", "browser.precision": "Genauigkeit: {precision}", "browser.sketch_name": "Skizze {number}", "browser.units": "Einheiten: {units}", - "dialog.computing": "Wird berechnet… {seconds} s", - "dialog.custom_axis": "↖ Eigene Achse", - "dialog.edit_title": "{title} bearbeiten", - "dialog.select": "↖ Auswählen", - "dialog.selected_count": "↖ {count} ausgewählt", - "dialog.step": "Schritt", - "dialog.selection_step": "{step} von {total}: {input} auswählen", - "dialog.selection_guidance": "Wählen Sie eine Eingabe aus, um sie zu ändern. Klicken Sie auf ausgewählte Objekte, um sie zu entfernen; Strg/Cmd-Klick schaltet sie ebenfalls um. Prüfen Sie die Vorschau und drücken Sie dann OK.", - "document.save_changes": "Änderungen in {name} speichern?", - "document.unsaved_changes": "{name} enthält ungespeicherte Änderungen. Wenn Sie nicht speichern, gehen sie verloren.", - "home.documentation": "Dokumentation", - "home.in_this_browser": "in diesem Browser", - "home.missing": "fehlt", - "home.open": "Öffnen…", - "home.opened_days_ago": "Vor {count} Tag(en) geöffnet", - "home.opened_hours_ago": "Vor {count} Std. geöffnet", - "home.opened_just_now": "Gerade eben geöffnet", - "home.opened_minutes_ago": "Vor {count} Min. geöffnet", - "home.opening": "wird geöffnet…", - "home.recent": "Zuletzt verwendet", - "home.report_issue": "Problem melden", - "home.samples": "Beispiele", - "home.whats_new": "Neuigkeiten", - "sample.bracket.about": "Grundflansch mit Kantenflanschen und einer Umkantung nach einer 2-mm-Blechregel", - "sample.bracket.name": "Blechwinkel", - "sample.enclosure.about": "Ausgehöhlter Block mit Lippe, Schraubenerhöhungen, Auflage und Rastverbindung", - "sample.enclosure.name": "Kunststoffgehäuse", - "sample.flange.about": "Nabe und Flansch mit einem parametergesteuerten radialen Muster", - "sample.flange.name": "Schraubflansch", - "sample.hinge.about": "Zwei Komponenten und ein Drehgelenk, auf 60° angetrieben", - "sample.hinge.name": "Scharnierbaugruppe", - "sample.plate.about": "Parametrische Platte mit Vollrundungen, Bohrungen und einer aufgebohrten Erhöhung", - "sample.plate.name": "Beispielplatte", - "sample.vents.about": "Langlöcher in einem Rechteckmuster: Zeilen, Spalten und Abstand sind Parameter", - "sample.vents.name": "Lüftungsplatte", - "settings.msaa_applies_on_restart": "Die Kantenglättung wird beim nächsten Start von SolidCraft übernommen", - "settings.msaa_reset": "{setting}: {requested}× wird von diesem Grafikgerät nicht unterstützt; jetzt {reset}× (unterstützt: {supported}).", - "settings.msaa_unsupported": "Von diesem Grafikgerät nicht unterstützt", - "settings.reset_intro": "Diese Einstellungen funktionieren auf diesem Computer nicht und würden den Start von SolidCraft verhindern. Sie wurden daher geändert:", - "settings.reset_title": "Einstellungen wurden geändert", - "sketch.degrees_of_freedom": "{count} Freiheitsgrade", - "sketch.draw_curves": "Als {linetype} zeichnen", - "sketch.make_selection": "Auswahl als {linetype} markieren", - "ui.1_degree_of_freedom": "1 Freiheitsgrad", - "ui.3d_sketch": "3D-Skizze", - "ui.about": "Über", - "ui.activate": "Aktivieren", - "ui.active_component": "Aktive Komponente", - "ui.agent_cursor": "Agent-Cursor", - "ui.agent_cursor_speed": "Agent-Cursor-Geschwindigkeit", - "ui.agent_chat": "Agenten-Chat", - "ui.agent_chat_command": "Agentenbefehl", - "ui.agent_chat_desktop_only": "Der Agenten-Chat braucht die Desktop-App.", - "ui.agent_chat_side": "Seite des Agenten-Chats", - "ui.agent_chat_left": "Links", - "ui.agent_chat_right": "Rechts", - "ui.agent_chat_turn_limit": "Änderungen pro Nachricht", - "ui.agent_chat_privacy_note": "SolidCraft sendet nichts irgendwohin: Der Agent, den Sie starten, spricht unter Ihrem eigenen Konto mit seinem eigenen Dienst. SolidCraft sieht und speichert nie einen Schlüssel oder ein Passwort.", - "ui.agent_chat_connect": "Verbinden", - "ui.agent_chat_stop": "Beenden", - "ui.agent_chat_stop_tip": "Den Agenten und alles, was er gestartet hat, beenden", - "ui.agent_chat_close": "Schließen", - "ui.agent_chat_minimize": "Zu einer Leiste minimieren", - "ui.agent_chat_dock_left": "Links andocken", - "ui.agent_chat_dock_right": "Rechts andocken", - "ui.agent_chat_send": "Senden", - "ui.agent_chat_cancel": "Abbrechen", - "ui.agent_chat_refresh": "Aktualisieren", - "ui.agent_chat_pick": "Agent", - "ui.agent_chat_custom_hint": "Jedes Programm, das das Agent Client Protocol über stdin und stdout spricht. Es läuft ohne Shell.", - "ui.agent_chat_not_installed": "Nicht installiert", - "ui.agent_chat_none_found": "Kein Coding-Agent gefunden. Installieren Sie einen davon und klicken Sie dann auf Aktualisieren:", - "ui.agent_chat_detecting": "Suche nach Agenten…", - "ui.agent_chat_signed_in": "angemeldet", - "ui.agent_chat_key_in_env": "Schlüssel gesetzt", - "ui.agent_chat_not_signed_in": "nicht angemeldet", - "ui.agent_chat_state_off": "Nicht verbunden", - "ui.agent_chat_state_starting": "Startet…", - "ui.agent_chat_state_ready": "Bereit", - "ui.agent_chat_state_busy": "Arbeitet…", - "ui.agent_chat_state_auth": "Anmeldung nötig", - "ui.agent_chat_state_exited": "Agent beendet", - "ui.agent_chat_changes_of": "{n}/{limit} Änderungen", - "ui.agent_chat_auth_title": "Beim Agenten anmelden", - "ui.agent_chat_auth_needed": "Der Agent bittet Sie, sich anzumelden. Sie melden sich beim Agenten selbst an; SolidCraft sieht Ihr Passwort oder Ihre Schlüssel nie.", - "ui.agent_chat_auth_none": "Der Agent bietet hier keine Anmeldung an: Melden Sie sich so an, wie es seine Dokumentation beschreibt.", - "ui.agent_chat_auth_terminal": "Führen Sie dies in einem Terminal aus und klicken Sie dann erneut auf Verbinden:", - "ui.agent_chat_auth_agent": "Mit {name} anmelden", - "ui.agent_chat_auth_env": "Setzen Sie {vars} in Ihrer Umgebung und starten Sie SolidCraft neu.", - "ui.agent_chat_auth_retry": "Ich bin angemeldet: erneut verbinden", - "ui.agent_chat_copy": "Kopieren", - "ui.agent_chat_permission": "Der Agent möchte ausführen: {title}", - "ui.agent_chat_answered": "Antwort: {option}", - "ui.agent_chat_approval": "Darf der Agent das tun?", - "ui.agent_chat_allow": "Erlauben", - "ui.agent_chat_deny": "Ablehnen", - "ui.agent_chat_allowed": "Erlaubt", - "ui.agent_chat_denied": "Abgelehnt", - "ui.agent_chat_changes": "Änderungen: {n}, ein Rückgängig-Schritt", - "ui.agent_chat_undo_changes": "Diese Änderungen rückgängig machen", - "ui.agent_chat_undone": "(rückgängig gemacht)", - "ui.agent_chat_undo_label": "Agenten-Chat: {message}", - "ui.agent_chat_limit": "Der Agent hat die Grenze von {limit} Änderungen für eine Nachricht erreicht. Senden Sie eine weitere Nachricht, damit er weitermacht.", - "ui.agent_chat_refused": "Für den Agenten nicht erlaubt: {reason}", - "ui.agent_chat_wait_turn": "Der Agent arbeitet noch an der letzten Nachricht: Warten Sie oder klicken Sie auf Abbrechen.", - "ui.agent_chat_placeholder": "Bitten Sie den Agenten, das Design zu ändern…", - "ui.agent_chat_attach_view": "Ansicht anhängen", - "ui.agent_chat_attach_view_tip": "Ein Bild der aktuellen Ansicht mit der Nachricht senden", - "ui.agent_chat_no_images": "Dieser Agent nimmt keine Bilder an", - "ui.agent_chat_view_attached": "Ansicht angehängt", - "ui.agent_chat_no_cli": "solidcraft-cli wurde neben der App nicht gefunden, daher kann der Agent das Design nicht erreichen.", - "ui.agent_chat_no_control": "Der Endpunkt des Agenten-Chats ist nicht gestartet, daher kann der Agent das Design nicht erreichen.", - "ui.agent_chat_exited": "Der Agent wurde beendet.", - "ui.agent_chat_failed_start": "Der Agent konnte nicht starten: {error}", - "ui.agent_chat_intro": "Chatten Sie mit einem Coding-Agenten, den Sie schon nutzen, oder einem Modell-Endpunkt Ihrer Wahl. Er arbeitet über die Werkzeuge von SolidCraft am geöffneten Design: Seine Änderungen erscheinen sofort und lassen sich pro Nachricht in einem Schritt rückgängig machen. Was er ohne Nachfrage darf, legen Sie unter Einstellungen > KI fest.", - "ui.agent_chat_privacy": "Nichts geht irgendwohin außer an den Agenten, den Sie unter Ihrem eigenen Konto ausführen.", - "ui.agent_chat_none_found_short": "Kein Agent gefunden", - "ui.ai_add": "Hinzufügen", - "ui.ai_add_agent": "Agent hinzufügen…", - "ui.ai_add_agent_title": "Agent hinzufügen", - "ui.ai_add_api": "OpenAI-kompatible API", - "ui.ai_add_custom": "Eigener Befehl", - "ui.ai_added": "hinzugefügt", - "ui.ai_add_installed": "Installierter Agent", - "ui.ai_add_installed_note": "Ein eigener Eintrag für einen installierten Agenten, zum Beispiel mit anderen Argumenten. Installierte Agenten erscheinen von selbst.", - "ui.ai_agent_mode_tip": "Der eigene Modus des Agenten: Seine eigenen Werkzeuge (Shell, Dateiänderungen) folgen ihm. Die Werkzeuge von SolidCraft folgen den Berechtigungen unter Einstellungen > KI.", - "ui.ai_agents": "Agenten", - "ui.ai_always_allow": "Immer erlauben", - "ui.ai_always_allowed": "Immer erlaubt", - "ui.ai_always_allowed_none": "Noch nichts ist immer erlaubt. Antworten „Immer erlauben“ im Chat erscheinen hier.", - "ui.ai_always_allow_tip": "{tool} für diesen Agenten ab jetzt ohne Nachfrage erlauben", - "ui.ai_auto_allowed": "Automatisch erlaubt: {title} ({why})", - "ui.ai_auto_mode": "Ihre Berechtigungseinstellung", - "ui.ai_auto_ours": "SolidCraft prüft seine eigenen Werkzeuge selbst", - "ui.ai_auto_remembered": "Sie haben „Immer erlauben“ gewählt", - "ui.ai_bad_url": "Geben Sie eine URL ein, die mit http:// oder https:// beginnt", - "ui.ai_base_url": "Basis-URL", - "ui.ai_button": "KI", - "ui.ai_copy_suffix": "Kopie", - "ui.ai_custom_url": "Eigene URL", - "ui.ai_default": "Standard", - "ui.ai_http_busy": "der Endpunkt ist ausgelastet oder am Limit; versuchen Sie es später", - "ui.ai_http_key": "der Endpunkt hat den Schlüssel abgelehnt: prüfen Sie ihn unter Einstellungen > KI", - "ui.ai_http_not_found": "Endpunkt oder Modell nicht gefunden: prüfen Sie Basis-URL und Modellnamen", - "ui.ai_key": "API-Schlüssel", - "ui.ai_keychain_error": "Der Schlüsselbund des Systems hat abgelehnt: {error}", - "ui.ai_key_hint": "optional; im Schlüsselbund des Systems gespeichert", - "ui.ai_key_needs_https": "Ein Schlüssel wird nur über HTTPS oder an diesen Computer gesendet.", - "ui.ai_key_note": "Im Schlüsselbund des Systems gespeichert, nie in den Einstellungen von SolidCraft. Für einen lokalen Server leer lassen.", - "ui.ai_mode_all": "Alles erlauben", - "ui.ai_mode_all_note": "Nichts fragt vorher. Absturzberichte bleiben tabu, und die Ordnergrenzen gelten weiter.", - "ui.ai_mode_all_warning": "Der Agent kann Ihr Design ohne Nachfrage speichern, überschreiben, exportieren und ersetzen. Nutzen Sie das nur mit einem Agenten, dem Sie vertrauen, und mit gespeicherten Designs.", - "ui.ai_mode_ask": "Jedes Mal fragen", - "ui.ai_mode_ask_note": "Jede Änderung am Design und jede Dateiaktion wartet auf Ihr Erlauben.", - "ui.ai_mode_edits": "Modelländerungen automatisch erlauben", - "ui.ai_mode_edits_note": "Modellierbefehle laufen ohne Nachfrage; Speichern, Öffnen, Exportieren und andere Datei- oder destruktive Aktionen fragen weiterhin.", - "ui.ai_mode_global": "Wie oben eingestellt", - "ui.ai_model": "Modell", - "ui.ai_modes_scope": "Diese Einstellungen gelten für die Werkzeuge von SolidCraft. Die eigenen Werkzeuge eines Agenten (seine Shell, seine Dateiänderungen) folgen seinem eigenen Modus, den Sie im Kopf des Chat-Panels wählen, wenn der Agent Modi hat.", - "ui.ai_name": "Name", - "ui.ai_need_command": "Geben Sie den Befehl ein, der den Agenten startet", - "ui.ai_need_model": "Geben Sie den Modellnamen ein", - "ui.ai_no_answer": "Der Agent hat nicht rechtzeitig geantwortet", - "ui.ai_no_http": "Dieser Build kann keine API-Endpunkte erreichen", - "ui.ai_no_keychain": "Der Schlüsselbund des Systems ist nicht verfügbar, daher kann kein Schlüssel gespeichert werden. Ein lokaler Server ohne Schlüssel funktioniert trotzdem.", - "ui.ai_panel": "Panel", - "ui.ai_permissions": "Berechtigungen", - "ui.ai_preset": "Vorlage", - "ui.ai_remove": "Entfernen", - "ui.ai_request_limit": "nach 24 Anfragen für eine Nachricht angehalten; senden Sie eine weitere Nachricht, um fortzufahren", - "ui.ai_reset": "Zurücksetzen", - "ui.ai_settings": "KI-Einstellungen…", - "ui.ai_show_features": "KI-Funktionen anzeigen", - "ui.ai_show_features_note": "Der Agenten-Chat: ein Panel, in dem ein Coding-Agent, den Sie schon nutzen, oder ein Modell-Endpunkt Ihrer Wahl am geöffneten Design arbeitet. Aus: keine KI-Schaltfläche, kein Kürzel, kein Menüeintrag, kein Panel, und nichts wird gesucht oder gestartet.", - "ui.ai_switch_tip": "Den Agenten für dieses Gespräch wechseln", - "ui.ai_test": "Testen", - "ui.ai_test_acp_ok": "Antwortet: {agent}", - "ui.ai_test_acp_tip": "Startet den Agenten kurz und bittet um eine Sitzung; beendet ihn wieder", - "ui.ai_test_api_tip": "Fragt den Endpunkt nach seinen Modellen", - "ui.ai_testing": "Teste…", - "ui.ai_test_no_model": "Erreicht: {count} Modelle, aber nicht {model}", - "ui.ai_test_ok": "Erreicht: {count} Modelle", - "ui.ai_toolbar_button": "Schaltfläche in der Werkzeugleiste anzeigen", - "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_tool_done": "fertig", - "ui.ai_tool_failed": "fehlgeschlagen", - "ui.ai_tool_running": "läuft", - "ui.ai_tool_unfold": "Klicken, um das Ergebnis zu zeigen", - "ui.ai_tool_waiting": "wartet", - "ui.ai_undo_tip": "Alles, was der Agent für diese Nachricht geändert hat, in einem Schritt rückgängig machen", - "AI": "KI", - "ui.all": "Alle", - "ui.analysis": "Analyse", - "ui.angle": "Winkel", - "ui.angle_decimals": "Winkel-Dezimalstellen", - "ui.animate_view_changes": "Ansichtsänderungen animieren", - "ui.animation": "Animation", - "ui.animation_speed": "Animationsgeschwindigkeit", - "ui.anti_aliasing": "Kantenglättung", - "ui.supersampling": "Supersampling (SSAA)", - "ui.supersampling_off": "Aus (1×)", - "ui.supersampling_adaptive": "Nur bei ruhender Ansicht", - "settings.supersampling_note": "Zeichnet die Ansicht in höherer Auflösung und rechnet sie herunter: glattere Kanten, Linien und Raster auf Bildschirmen unter 4K. Kostet GPU-Zeit: etwa 2,25-mal so viele Pixel bei 1,5× und 4-mal bei 2×.", - "ui.display_quality": "Darstellungsqualität", - "ui.display_quality_coarse": "Grob", - "ui.display_quality_normal": "Normal", - "ui.display_quality_fine": "Fein", - "ui.display_quality_ultra": "Ultra", - "settings.display_quality_note": "Feinere Stufen zeigen gekrümmte Flächen und Kanten glatter und brauchen länger zum Vernetzen. Nur die Ansicht ändert sich, nie das Design oder Exporte.", - "ui.apply": "Anwenden", - "ui.arc": "Kreisbogen", - "ui.assemble": "Zusammenbau", - "ui.autosave_every": "Autospeichern alle", - "ui.axes": "Achsen", - "ui.axis": "Achse", - "ui.base_point": "Basispunkt", - "ui.bodies": "Körper", - "ui.box": "Block", - "ui.break": "Unterbrechen", - "ui.cancel": "Abbrechen", - "ui.canvases": "Kanvas", - "ui.center": "Mittelpunkt", - "ui.centerline": "Mittellinie", - "ui.chain": "Kette", - "ui.chamfer": "Abschrägung", - "ui.chamfer_type": "Fasentyp", - "ui.change_workspace": "Arbeitsbereich wechseln", - "ui.chord_length": "Sehnenlänge", - "ui.curvature_g2": "Krümmungsstetig (G2)", - "ui.equivalent_radius": "Äquivalenter Radius", - "ui.circle": "Kreis", - "ui.circular_pattern": "Radiales Muster", - "ui.clear_recent": "Zuletzt verwendet leeren", - "ui.clear_the_selection": "Auswahl aufheben", - "ui.close": "Schließen", - "ui.material_review.title": "Physikalische Materialdaten prüfen", - "ui.material_review.scope": "Nur Kandidat: nicht zugewiesen oder gespeichert. Numerische Prüfung ist keine technische Zertifizierung.", - "ui.material_review.input": "Materialkarte mit Schema 1 einfügen (JSON)", - "ui.material_review.review": "Karte prüfen", - "ui.material_review.limit": "Die Karte überschreitet die Eingabegrenze von 256 KiB.", - "ui.material_review.unknown": "Unbekannt", - "ui.material_review.properties": "Eigenschaften", - "ui.material_review.conditions": "Angegebene Bedingungen", - "ui.material_review.source": "Quelle", - "ui.material_review.axes": "Materiallokale Achsen; keine Körperausrichtung zugewiesen.", - "ui.material_review.derived": "Abgeleitete isotrope Moduln", - "ui.material_review.claims": "Quellen und Lizenzen sind ungeprüfte Angaben. Fehlende Werte bleiben unbekannt.", - "ui.material_review.density": "Dichte", - "ui.material_review.elasticity": "Elastizität", - "ui.material_review.tensile_strength": "Zugfestigkeit", - "ui.material_review.compressive_strength": "Druckfestigkeit", - "ui.material_review.yield_strength": "Streckgrenze", - "ui.material_review.shear_strength": "Scherfestigkeit", - "ui.material_review.thermal_conductivity": "Wärmeleitfähigkeit", - "ui.material_review.thermal_expansion": "Wärmeausdehnung", - "ui.material_review.specific_heat": "Spezifische Wärmekapazität", - "ui.material_review.moisture_unit": "kg Wasser / kg Trockenmaterial", - "ui.coil": "Schraube", - "ui.coincident": "Koinzident", - "ui.collapse": "Einklappen", - "ui.collinear": "Kollinear", - "ui.colour_vision": "Farbsehen", - "ui.colour_vision_deutan": "Deutan", - "ui.colour_vision_deutan_tip": "Bei schwachem oder fehlendem Grünsinn", - "ui.colour_vision_failed": "Fehler", - "ui.colour_vision_fixed": "Fixiert", - "ui.colour_vision_mode": "Modus", - "ui.colour_vision_note": "Ändert die Farben, die eine Bedeutung tragen: Skizzenstatus, Achsen, Biegungen, Analysen und Symbole. Wenn Sie die Farbfilter von Windows verwenden, lassen Sie dies auf „Aus“.", - "ui.colour_vision_off": "Aus", - "ui.colour_vision_off_tip": "Die eigenen Farben des Designs", - "ui.colour_vision_projected": "Projiziert", - "ui.colour_vision_protan": "Protan", - "ui.colour_vision_protan_tip": "Bei schwachem oder fehlendem Rotsinn", - "ui.colour_vision_sample": "Beispiel", - "ui.colour_vision_tritan": "Tritan", - "ui.colour_vision_tritan_tip": "Bei schwachem oder fehlendem Blausinn", - "ui.combine": "Kombinieren", - "ui.coming_later": "bald verfügbar", - "ui.concentric": "Konzentrisch", - "ui.configurations": "Konfigurationen", - "ui.conic_curve": "Kegelschnitt", - "ui.constant": "Konstant", - "ui.constraints_conflict": "Bedingungen konfliktreich", - "ui.construct": "Konstruktion", - "ui.construction": "Konstruktionslinie", - "ui.copy": "Kopieren", - "ui.corners": "Ecken", - "ui.corner": "Ecke", - "ui.counterbore": "Tiefenbohrung", - "ui.countersink": "Senkung", - "ui.create": "Erstellen", - "ui.create_copy": "Kopie erstellen", - "ui.create_sketch": "Skizze erstellen", - "ui.current": "aktuell", - "ui.curvature": "Krümmung", - "ui.curves": "Kurven", - "ui.cut": "Ausschneiden", - "ui.cylinder": "Zylinder", - "ui.dark": "Dunkel", - "ui.default_modelling_orientation": "Standard-Modellierungsorientierung", - "ui.degrees_of_freedom": "Freiheitsgrade", - "ui.delete": "Löschen", - "ui.depth": "Tiefe", - "ui.design": "Design", - "ui.diameter": "Durchmesser", - "ui.dimension": "Maß", - "ui.direction": "Richtung", - "ui.distance": "Abstand", - "ui.distance_1": "Abstand 1", - "ui.distance_2": "Abstand 2", - "ui.document_settings": "Dokumenteneinstellungen", - "ui.don_t_save": "Nicht speichern", - "ui.draft": "Abziehen", - "ui.drawing": "Zeichnung", - "ui.drill_point": "Bohrpunkt", - "ui.edit": "Bearbeiten", - "ui.edit_section_analysis": "Querschnittsanalyse bearbeiten", - "ui.ellipse": "Ellipse", - "ui.end_radius": "Endradius", - "ui.entities": "Elemente", - "ui.equal": "Gleich", - "ui.expand": "Aufklappen", - "ui.export_ellipsis": "Exportieren...", - "ui.extend": "Verlängern", - "ui.extent_type": "Ausdehnungstyp", - "ui.extrude": "Extrudieren", - "ui.factor": "Faktor", - "ui.feature_history": "Feature-Verlauf", - "ui.feature_options": "Funktionsoptionen", - "ui.features": "Funktionen", - "ui.file": "Datei", - "ui.fillet": "Vollrundung", - "ui.finish_sketch": "Skizze beenden", - "ui.fix_unfix": "Fixieren/Lösen", - "ui.flat": "Flach", - "ui.flip": "Umkehren", - "ui.front": "Vorne", - "ui.fully_constrained": "Vollständig bestimmt", - "ui.general": "Allgemein", - "ui.graphics": "Grafik", - "ui.heading_assemble": "ZUSAMMENBAU", - "ui.heading_box": "BLOCK", - "ui.heading_chamfer": "ABSCHRÄGUNG", - "ui.heading_circular_pattern": "RADIALES MUSTER", - "ui.heading_coil": "SCHRAUBE", - "ui.heading_combine": "KOMBINIEREN", - "ui.heading_construct": "KONSTRUKTION", - "ui.heading_create": "ERSTELLEN", - "ui.heading_create_sketch": "SKIZZE ERSTELLEN", - "ui.heading_cylinder": "ZYLINDER", - "ui.heading_design": "DESIGN", - "ui.heading_draft": "ABZIEHEN", - "ui.heading_edit": "BEARBEITEN", - "ui.heading_extrude": "EXTRUDIEREN", - "ui.heading_fillet": "VOLLRUNDUNG", - "ui.heading_finish_sketch": "SKIZZE BEENDEN", - "ui.heading_front": "VORNE", - "ui.heading_hole": "BOHRUNG", - "ui.heading_home": "START", - "ui.heading_insert": "EINFÜGEN", - "ui.heading_inspect": "PRÜFEN", - "ui.heading_loft": "LOFT", - "ui.heading_measure": "Messen", - "ui.heading_mesh": "MESH", - "ui.heading_mirror": "SPIEGELN", - "ui.heading_modify": "ÄNDERN", - "ui.heading_move": "VERSCHIEBEN", - "ui.heading_offset": "ABSTAND", - "ui.heading_move_copy": "VERSCHIEBEN/KOPIEREN", - "ui.heading_offset_plane": "ABSTANDSEBENE", - "ui.heading_ok": "OK", - "ui.heading_parameters": "PARAMETER", - "ui.heading_pattern_on_path": "PFADMUSTER", - "ui.heading_pipe": "ROHR", - "ui.heading_plane_at_angle": "EBENE IM WINKEL", - "ui.heading_plastic": "PLASTIK", - "ui.heading_rectangular_pattern": "RECHTECKMUSTER", - "ui.heading_revolve": "DREHEN", - "ui.heading_right": "RECHTS", - "ui.heading_scale": "SKALIEREN", - "ui.heading_section_analysis": "QUERSCHNITTSANALYSE", - "ui.heading_select": "AUSWÄHLEN", - "ui.heading_sheet_metal": "BLECH", - "ui.heading_shell": "HÜLLE", - "ui.heading_sketch": "SKIZZE", - "ui.heading_sketch_palette": "SKIZZENPALETTE", - "ui.heading_sketch_scale": "SKIZZE SKALIEREN", - "ui.heading_solid": "KÖRPER", - "ui.heading_sphere": "SPHÄRE", - "ui.heading_split_body": "KÖRPER TRENNEN", - "ui.heading_surface": "FLÄCHE", - "ui.heading_sweep": "FÜHREN", - "ui.heading_thread": "GEWINDE", - "ui.heading_top": "OBEN", - "ui.heading_torus": "TORUS", - "ui.help": "Hilfe", - "ui.hide": "Ausblenden", - "ui.hole": "Bohrung", - "ui.hole_tap_type": "Gewindetyp", - "ui.hole_type": "Bohrungstyp", - "ui.home": "Start", - "ui.horizontal_vertical": "Horizontal/Vertikal", - "ui.insert": "Einfügen", - "ui.inspect": "Prüfen", - "ui.intersect": "Schnitt", - "ui.join": "Verbinden", - "ui.joints": "Gelenke", - "ui.keyboard_shortcuts": "Tastenkürzel", - "ui.language": "Sprache", - "ui.length_decimals": "Längen-Dezimalstellen", - "ui.light": "Hell", - "ui.line": "Linie", - "ui.linetype": "Linientyp", - "ui.loft": "Loft", - "ui.look_at": "Ansehen", - "ui.manufacture": "Fertigung", - "ui.measure": "Messen", - "ui.midpoint": "Mittelpunkt", - "ui.mirror": "Spiegeln", - "ui.mirror_line": "Spiegelachse", - "ui.modify": "Ändern", - "ui.move": "Verschieben", - "ui.multiple": "Mehrfach", - "ui.named_views": "Benannte Ansichten", - "ui.navigation": "Navigation", - "ui.needs_design": "{command}: Öffnen Sie zuerst ein Design", - "ui.new_body": "Neuer Körper", - "ui.new_design": "Neues Design", - "ui.normal": "Normal", - "ui.object_type": "Objekttyp", - "ui.objects": "Objekte", - "ui.offer_to_stand_up_y_up_files": "Y-hoch-Dateien aufrecht anbieten", - "ui.offset": "Abstand", - "ui.offset_plane": "Abstandsebene", - "ui.one_side": "Einseitig", - "ui.open": "Öffnen", - "ui.open_ellipsis": "Öffnen...", - "ui.open_preferences": "Einstellungen öffnen", - "ui.open_recent": "Zuletzt verwendet", - "ui.operation": "Operation", - "ui.options": "Optionen", - "ui.orbit_around": "Umkreisen um", - "ui.origin": "Ursprung", - "ui.palette_points": "Punkte", - "ui.palette_profile": "Profil", - "ui.pan_zoom_orbit": "Verschieben, zoomen, umkreisen", - "ui.parallel": "Parallel", - "ui.parameters": "Parameter", - "ui.paste": "Einfügen", - "ui.path": "Pfad", - "ui.pattern_on_path": "Pfadmuster", - "ui.perpendicular": "Senkrecht", - "ui.pipe": "Rohr", - "ui.placement": "Platzierung", - "ui.plane": "Ebene", - "ui.plane_at_angle": "Ebene im Winkel", - "ui.point": "Punkt", - "ui.point_under_the_cursor": "Punkt unter dem Cursor", - "ui.points": "Punkte", - "ui.polygon": "Polygon", - "ui.preferences": "Einstellungen", - "ui.profile": "Profil", - "ui.profile_plane": "Profilebene", - "ui.profiles": "Profile", - "ui.project": "Projizieren", - "ui.quantity_2": "Anzahl 2", - "ui.quantity": "Anzahl", - "ui.quit": "Beenden", - "ui.radius": "Radius", - "ui.pull_direction": "Entformungsrichtung", - "ui.tool_direction": "Werkzeugrichtung", - "ui.reachable": "Erreichbar", - "ui.blocked": "Verdeckt", - "ui.radius_type": "Radius-Typ", - "ui.rectangle": "Rechteck", - "ui.rectangular_pattern": "Rechteckmuster", - "ui.redo": "Wiederholen", - "ui.render": "Rendern", - "ui.reset_the_settings_on_this_page": "Einstellungen auf dieser Seite zurücksetzen", - "ui.restore_defaults": "Standardeinstellungen wiederherstellen", - "ui.reverse_zoom_direction": "Zoomrichtung umkehren", - "ui.revolve": "Drehen", - "ui.right": "Rechts", - "ui.save": "Speichern", - "ui.heading_save_mesh": "ALS NETZ SPEICHERN", - "ui.format": "Format", - "ui.mesh_format_stl": "STL", - "ui.mesh_format_3mf": "3MF", - "ui.mesh_format_3mf_tagged": "3MF mit Flächenmarken", - "ui.send_to_slicer": "An Slicer senden", - "ui.slicer": "Slicer", - "ui.custom_program": "Benutzerdefiniert…", - "ui.no_slicer_found": "Kein Slicer gefunden", - "ui.send": "Senden", - "ui.custom_program_tip": "Ein Slicer-Programm zur Liste hinzufügen", - "ui.slicer_delete_tip": "{program}\nMit Entf aus der Liste entfernen", - "ui.save_mesh_pick_bodies": "Wähle die Körper zum Speichern aus", - "ui.save_mesh_no_slicer": "Kein Slicer gefunden: „Benutzerdefiniert…“ wählen und das Slicer-Programm angeben, oder „An Slicer senden“ ausschalten", - "ui.not_a_program": "{path} ist kein startbares Programm", - "ui.sent_to_slicer": "An {slicer} gesendet", - "ui.saved_to": "Gespeichert: {path}", - "ui.save_mesh_temp_failed": "{folder} konnte nicht angelegt werden: {error}", - "ui.save_as": "Speichern unter", - "ui.save_as_ellipsis": "Speichern unter...", - "ui.scale": "Skalieren", - "ui.orientation": "Ausrichtung", - "ui.twist": "Verdrehung", - "ui.end_scale": "Endskalierung", - "ui.sweep_turn_with_path": "Mit Pfad drehen", - "ui.sweep_keep_as_drawn": "Wie gezeichnet", - "ui.sweep_follow_direction": "Richtung folgen", - "ui.section_analysis": "Querschnittsanalyse", - "ui.select": "Auswählen", - "ui.selection": "Auswahl", - "ui.shell": "Hülle", - "ui.show": "Einblenden", - "ui.show_constraints": "Bedingungen", - "ui.show_dimensions": "Maße", - "ui.show_points": "Punkte anzeigen", - "ui.show_profile": "Profil anzeigen", - "ui.show_projected_geometries": "Projizierte Geometrien", - "ui.simple": "Einfach", - "ui.simulation": "Simulation", - "ui.single": "Einzel", - "ui.sketch": "Skizze", - "ui.sketch_dimension": "Skizzenmaß", - "ui.sketch_grid": "Skizzenraster", - "ui.sketch_scale": "Skizzenskalierung", - "ui.sketch_status": "Skizzenstatus", - "ui.sketches": "Skizzen", - "ui.slice": "Scheibe", - "ui.slot": "Langloch", - "ui.smooth": "Glatt", - "ui.snap": "Einrasten", - "ui.spacing_2": "Abstand 2", - "ui.spacing": "Abstand", - "ui.sphere": "Sphäre", - "ui.spline": "Spline", - "ui.split_body": "Körper trennen", - "ui.start": "Start", - "ui.start_radius": "Startradius", - "ui.sweep": "Führen", - "ui.symmetric": "Symmetrisch", - "ui.symmetry": "Symmetrie", - "ui.system": "System", - "ui.tangent": "Tangential", - "ui.taper_angle": "Kegelwinkel", - "ui.tapped": "Gewindebohrung", - "ui.text": "Text", - "ui.theme": "Design", - "ui.thickness": "Dicke", - "ui.thread": "Gewinde", - "ui.timeline_bottom": "Timeline unten", - "ui.timeline_left_note": "Im linken Layout wird die Rücksetzmarke über dem Teile- und Szenenbrowser eingeblendet.", - "ui.timeline_left_sidebar": "Linke Seitenleiste", - "ui.tip_angle": "Spitzenwinkel", - "ui.to_object": "Bis Objekt", - "ui.top": "Oben", - "ui.torus": "Torus", - "ui.trim": "Kürzen", - "ui.two_sides": "Beidseitig", - "ui.ui_scale": "UI-Skalierung", - "ui.undo": "Rückgängig", - "ui.units": "Einheiten", - "ui.units_of_new_designs": "Einheiten für neue Designs", - "ui.untitled": "Ohne Titel", - "ui.variable": "Variabel", - "ui.view_centre": "Ansichtszentrum", - "ui.visual_style": "Ansichtsstil", - "ui.workspace": "Arbeitsbereich", - "ui.y_distance": "Y-Abstand", - "ui.x_distance": "X-Abstand", - "ui.zoom_to_the_cursor": "Zum Cursor zoomen", - "ui.animateJoint": "Gelenk animieren", - "ui.calibrate": "Kalibrieren", - "ui.customizeToolbar": "Symbolleiste anpassen…", - "ui.editJointLimits": "Gelenkgrenzen bearbeiten", - "ui.exportDxf": "Als DXF exportieren…", - "ui.findInTimeline": "In der Zeitleiste suchen", - "ui.findInWindow": "Im Fenster suchen", - "ui.fit": "Einpassen", - "ui.groupSelected": "Auswahl gruppieren", - "ui.hideAxes": "Achsen ausblenden", - "ui.hideDimension": "Bemaßung ausblenden", - "ui.hideOrigin": "Ursprung ausblenden", - "ui.hidePlanes": "Ebenen ausblenden", - "ui.hideProfile": "Profil ausblenden", - "ui.homeView": "Startansicht", - "ui.isolate": "Isolieren", - "ui.lock": "Sperren", - "ui.newSketchGroup": "Neue Skizzengruppe", - "ui.normalConstruction": "Normal / Konstruktion", - "ui.orbit": "Drehen", - "ui.heading_position": "POSITION", - "ui.pan": "Verschieben", - "ui.pinToShortcuts": "An Verknüpfungen anheften", - "ui.pinToToolbar": "An Symbolleiste anheften", - "ui.properties": "Eigenschaften", - "ui.design_properties.project": "Projekt", - "ui.design_properties.part_number": "Teilenummer", - "ui.design_properties.revision": "Revision", - "ui.design_properties.author": "Autor", - "ui.design_properties.organization": "Organisation", - "ui.design_properties.description": "Beschreibung", - "ui.design_properties.license": "Lizenz", - "ui.design_properties.not_text": "Nicht als Text gespeichert; eine Eingabe hier ersetzt den Wert.", - "ui.design_properties.exports": "STEP-, IGES- und 3MF-Exporte übernehmen diese Angaben, wo das Format ein Feld dafür hat.", - "ui.design_properties.others": "Daten anderer Werkzeuge", - "ui.design_properties.others_note": "Bleiben unverändert in der Konstruktion und werden nie exportiert.", - "ui.removeSection": "Schnitt entfernen", - "ui.removeFromToolbar": "Aus der Symbolleiste entfernen", - "ui.repeat": "Wiederholen", - "ui.report_a_bug": "Fehler melden", - "ui.restore": "Wiederherstellen", - "ui.heading_setup": "EINRICHTEN", - "ui.selectOther": "Andere auswählen…", - "ui.selectTangentChain": "Tangentialkette auswählen", - "ui.showAll": "Alle einblenden", - "ui.showAllBodies": "Alle Volumenkörper einblenden", - "ui.showAxes": "Achsen einblenden", - "ui.showDimension": "Bemaßung einblenden", - "ui.showOrigin": "Ursprung einblenden", - "ui.showPlanes": "Ebenen einblenden", - "ui.suppress": "Unterdrücken", - "ui.command_palette_hint": "Befehl eingeben, z. B. {example} — oder S drücken, um zu suchen", - "ui.unground": "Fixierung lösen", - "ui.unisolate": "Isolierung aufheben", - "ui.unlock": "Entsperren", - "ui.unsuppress": "Unterdrückung aufheben", - "ui.updateToCurrentView": "Auf aktuelle Ansicht aktualisieren", - "ui.zoom": "Zoomen", - "ui.command_done": "{command} fertig", - "drive.stopped_by_loop": "Angehalten bei {value}: die Schleife über {joint} lässt sich nicht weiter schließen", - "drive.stopped_by_contact": "Angehalten bei {value}: {a} würde {b} durchdringen", - "drive.unconnected": "Bewegt nichts: {part} ist mit nichts Festgesetztem verbunden", "cmd.appearance_assign": "Erscheinungsbild", "cmd.appearance_library": "Erscheinungsbild-Bibliothek", "cmd.appearance_list": "Erscheinungsbilder auflisten", @@ -685,7 +105,6 @@ "cmd.component_capture_position": "Position erfassen", "cmd.component_create": "Neue Komponente", "cmd.component_delete": "Komponente löschen", - "cmd.component_unlock": "Inhalt entsperren", "cmd.component_from_bodies": "Komponenten aus Körpern erstellen", "cmd.component_insert_design": "Konstruktion einfügen", "cmd.component_links": "Verknüpfungen auflisten", @@ -696,6 +115,7 @@ "cmd.component_properties": "Physikalische Eigenschaften der Komponente", "cmd.component_rename": "Komponente umbenennen", "cmd.component_revert_position": "Position zurücksetzen", + "cmd.component_unlock": "Inhalt entsperren", "cmd.component_update_links": "Verknüpfungen aktualisieren", "cmd.config_activate": "Konfiguration aktivieren", "cmd.config_column": "Konfigurationsspalte", @@ -737,10 +157,10 @@ "cmd.doc_recovery_discard": "Wiederhergestellte Konstruktion verwerfen", "cmd.doc_recovery_list": "Wiederherstellbare Konstruktionen", "cmd.document_inspect": "Konstruktion prüfen", - "cmd.document_units": "Einheiten der Konstruktion ändern", "cmd.document_metadata": "Konstruktionseigenschaften", - "cmd.document_metadata_set": "Konstruktionseigenschaften ändern", "cmd.document_metadata_remove": "Konstruktionseigenschaft entfernen", + "cmd.document_metadata_set": "Konstruktionseigenschaften ändern", + "cmd.document_units": "Einheiten der Konstruktion ändern", "cmd.edit_checkpoint": "Prüfpunkt", "cmd.edit_restore_checkpoint": "Prüfpunkt wiederherstellen", "cmd.engine_commands": "Befehle auflisten", @@ -758,6 +178,7 @@ "cmd.inspect_accessibility": "Zugänglichkeitsanalyse", "cmd.inspect_center_of_mass": "Massenschwerpunkt", "cmd.inspect_compare": "Körper vergleichen", + "cmd.inspect_continuity": "Kontinuitätsprüfung", "cmd.inspect_curvature_comb": "Krümmungskamm-Analyse", "cmd.inspect_curvature_map": "Krümmungskartenanalyse", "cmd.inspect_draft": "Auswinkelanalyse", @@ -771,15 +192,18 @@ "cmd.joint_delete": "Gelenk löschen", "cmd.joint_drive": "Gelenke antreiben", "cmd.joint_edit": "Gelenk bearbeiten", + "cmd.joint_gear": "Zahnrad", "cmd.joint_limits": "Gelenkgrenzen", "cmd.joint_list": "Gelenke auflisten", "cmd.joint_motion_link": "Bewegungsverknüpfung", - "cmd.joint_gear": "Zahnrad", - "cmd.joint_rack_pinion": "Zahnstange und Ritzel", - "cmd.joint_screw": "Schraube", "cmd.joint_origin": "Gelenkursprung", + "cmd.joint_rack_pinion": "Zahnstange und Ritzel", "cmd.joint_rigid_group": "Starrgruppe", + "cmd.joint_screw": "Schraube", "cmd.joint_solve": "Gelenke lösen", + "cmd.library_apply": "Lokalen Bibliothekseintrag anwenden", + "cmd.library_export": "Designbibliothek exportieren", + "cmd.library_inspect": "Lokale Bibliothek prüfen", "cmd.material_assign": "Physikalisches Material", "cmd.material_create": "Neues physikalisches Material", "cmd.material_delete": "Physisches Material löschen", @@ -807,10 +231,10 @@ "cmd.parameters_delete": "Parameter löschen", "cmd.parameters_export": "Parameter exportieren", "cmd.parameters_favorite": "Favorisierter Parameter", - "cmd.parameters_move": "Parameter verschieben", "cmd.parameters_graph": "Parametergraph", "cmd.parameters_import": "Parameter importieren", "cmd.parameters_list": "Parameter auflisten", + "cmd.parameters_move": "Parameter verschieben", "cmd.parameters_rename": "Parameter umbenennen", "cmd.parameters_users": "Parameterverwendungen", "cmd.parts_fastener": "Verbindungselement einfügen", @@ -824,6 +248,16 @@ "cmd.plastic_rest": "Auflage", "cmd.plastic_rules": "Kunststoffregeln auflisten", "cmd.plastic_snap_fit": "Rastverbindung", + "cmd.render_backends": "Render-Backends", + "cmd.render_cancel": "Rendering abbrechen", + "cmd.render_export": "PNG exportieren", + "cmd.render_preflight": "Renderanfrage prüfen", + "cmd.render_scene": "Renderszene prüfen", + "cmd.render_settings_apply": "Renderkamera anwenden", + "cmd.render_settings_get": "Rendereinstellungen", + "cmd.render_settings_set": "Rendereinstellungen speichern", + "cmd.render_start": "Bild rendern", + "cmd.render_status": "Renderfortschritt", "cmd.select_clear": "Auswahl aufheben", "cmd.sheet_convert": "In Blech umwandeln", "cmd.sheet_export_bend_table": "Biegungstabelle exportieren", @@ -918,22 +352,21 @@ "cmd.solid_rib": "Rippe", "cmd.solid_split_face": "Fläche teilen", "cmd.solid_web": "Gewebe", - "cmd.surface_patch": "Patch", - "cmd.surface_stitch": "Nähen", - "cmd.surface_thicken": "Dicke vergeben", - "cmd.surface_extrude": "Flächen-Extrusion", - "cmd.surface_revolve": "Flächen-Rotation", - "cmd.surface_sweep": "Flächen-Sweep", - "cmd.surface_loft": "Flächen-Loft", - "cmd.surface_ruled": "Regelfläche", - "cmd.surface_boundary": "Begrenzungsfläche", - "cmd.surface_offset": "Offsetfläche", "cmd.surface_blend": "Verbindungsfläche", + "cmd.surface_boundary": "Begrenzungsfläche", + "cmd.surface_extrude": "Flächen-Extrusion", "cmd.surface_fillet": "Flächenverrundung", - "cmd.surface_untrim": "Trimmen aufheben", - "cmd.surface_unstitch": "Verbund aufheben", + "cmd.surface_loft": "Flächen-Loft", + "cmd.surface_offset": "Offsetfläche", + "cmd.surface_patch": "Patch", "cmd.surface_reverse_normal": "Normale umkehren", - "cmd.inspect_continuity": "Kontinuitätsprüfung", + "cmd.surface_revolve": "Flächen-Rotation", + "cmd.surface_ruled": "Regelfläche", + "cmd.surface_stitch": "Nähen", + "cmd.surface_sweep": "Flächen-Sweep", + "cmd.surface_thicken": "Dicke vergeben", + "cmd.surface_unstitch": "Verbund aufheben", + "cmd.surface_untrim": "Trimmen aufheben", "cmd.timeline_add": "Aufgezeichnetes Merkmal hinzufügen", "cmd.timeline_compute_all": "Alles berechnen", "cmd.timeline_copy": "Merkmale kopieren", @@ -950,215 +383,781 @@ "cmd.view_apply": "Benannte Ansicht wiederherstellen", "cmd.view_delete": "Benannte Ansicht löschen", "cmd.view_list": "Benannte Ansichten auflisten", + "cmd.view_navigate": "Ansicht navigieren", "cmd.view_rename": "Benannte Ansicht umbenennen", "cmd.view_save": "Neue benannte Ansicht", - "ui.export_ellipsis_keymap": "Exportieren…", - "ui.heading_configure": "KONFIGURIEREN", - "ui.heading_constraints": "RANDBEDINGUNGEN", - "ui.heading_utilities": "WERKZEUGE", - "BROWSER": "BROWSER", - "Bends": "Biegungen", - "Drive Joint": "Gelenk antreiben", - "Edit Profile Sketch": "Profile-Skizze bearbeiten", - "Find in Browser": "Im Browser suchen", - "Copy Error Message": "Fehlermeldung kopieren", - "Copy Warning Message": "Warnmeldung kopieren", - "Report a bug — review a screenshot and open a GitHub draft": "Fehler melden — Screenshot prüfen und einen GitHub-Entwurf öffnen", - "Reset Toolbar": "Symbolleiste zurücksetzen", - "Select bodies (a face picks its body)": "Körper auswählen (eine Fläche wählt ihren Körper)", - "Selection filter": "Auswahlfilter", - "Revert Position": "Position zurücksetzen", - "Construction": "Konstruktionslinie", - "Faces": "Flächen", - "Edges": "Kanten", - "Vertices": "Scheitelpunkte", - "Sketch geometry and profiles": "Skizzengeometrie und Profile", - "Sketch curves": "Skizzenkurven", - "Sketch points": "Skizzenpunkte", - "Sketch dimensions": "Skizzenmaße", - "Sketch constraints": "Skizzenbedingungen", - "Flat": "Flach", - "cmd.render_backends": "Render-Backends", - "cmd.view_navigate": "Ansicht navigieren", - "timeline.group": "Neuen Merkmalsordner anlegen", - "timeline.ungroup": "Merkmalsordner entfernen", - "timeline.rename_group": "Merkmalsordner umbenennen", - "timeline.move_to_group": "Merkmale in Ordner verschieben", - "timeline.move_many": "Zeitleistenelemente verschieben", - "timeline.reorder_many": "Merkmale neu ordnen", - "ui.show_construction_geometries": "Konstruktionsgeometrien", - "ui.total_angle": "Gesamtwinkel", - "sketch_text.builtin_font": "{family} (integriert)", - "sketch_text.font_search": "Schriftarten suchen", - "sketch_text.loading_fonts": "Installierte Schriftarten werden gesucht…", - "sketch_text.use_font_file": "Schriftdatei {path} verwenden", - "sketch_text.bold": "Fett", - "sketch_text.italic": "Kursiv", - "sketch_text.align_left": "Links", - "sketch_text.align_center": "Mitte", - "sketch_text.align_right": "Rechts", - "sketch_text.path_hint": "Eine Skizzenkurve, der der Text folgt: hier klicken, dann die Kurve", - "sketch_text.path_clear": "Text von der Kurve lösen", - "sketch_text.on_path": "Der Text folgt seiner Kurve: sie bestimmt seine Lage", - "cmd.library_inspect": "Lokale Bibliothek prüfen", - "cmd.library_export": "Designbibliothek exportieren", - "cmd.library_apply": "Lokalen Bibliothekseintrag anwenden", - "Thin": "Dünnwandig", - "Thin Extrude": "Dünnwandig extrudieren", - "Wall Location": "Wandlage", - "Wall Thickness": "Wandstärke", - "Thickness Outside": "Dicke außen", - "Inside": "Innen", - "Outside": "Außen", - "Profiles/Curves": "Profile/Kurven", - "Corner Relief": "Eckenentlastung", - "Notch": "Ausklinkung", - "Round": "Rund", - "Rectangular": "Rechteckig", - "Tear": "Reißen", - "update.button": "Update", - "update.button_tip": "SolidCraft {version} ist verfügbar", - "install.menu": "App installieren…", + "coupling.gear_1": "Zahnrad 1", + "coupling.gear_1_pick": "Zahnrad 1 (optional)", + "coupling.gear_2": "Zahnrad 2", + "coupling.gear_2_pick": "Zahnrad 2 (optional)", + "coupling.internal": "Innenzahnrad", + "coupling.needs_turn_and_slide": "braucht ein Gelenk, das sich dreht, und eines, das gleitet", + "coupling.needs_turns": "braucht zwei Gelenke, die sich drehen", + "coupling.not_round": "keine runde Fläche", + "coupling.nut": "Mutter", + "coupling.picked": "gewählt", + "coupling.pinion": "Ritzel", + "coupling.pinion_pick": "Ritzel (optional)", + "coupling.pitch": "Steigung", + "coupling.rack": "Zahnstange", + "coupling.radius_1": "Radius 1", + "coupling.radius_2": "Radius 2", + "dialog.computing": "Wird berechnet… {seconds} s", + "dialog.custom_axis": "↖ Eigene Achse", + "dialog.edit_title": "{title} bearbeiten", + "dialog.select": "↖ Auswählen", + "dialog.selected_count": "↖ {count} ausgewählt", + "dialog.selection_guidance": "Wählen Sie eine Eingabe aus, um sie zu ändern. Klicken Sie auf ausgewählte Objekte, um sie zu entfernen; Strg/Cmd-Klick schaltet sie ebenfalls um. Prüfen Sie die Vorschau und drücken Sie dann OK.", + "dialog.selection_step": "{step} von {total}: {input} auswählen", + "dialog.step": "Schritt", + "document.save_changes": "Änderungen in {name} speichern?", + "document.unsaved_changes": "{name} enthält ungespeicherte Änderungen. Wenn Sie nicht speichern, gehen sie verloren.", + "drive.stopped_by_contact": "Angehalten bei {value}: {a} würde {b} durchdringen", + "drive.stopped_by_loop": "Angehalten bei {value}: die Schleife über {joint} lässt sich nicht weiter schließen", + "drive.unconnected": "Bewegt nichts: {part} ist mit nichts Festgesetztem verbunden", + "home.documentation": "Dokumentation", + "home.in_this_browser": "in diesem Browser", + "home.missing": "fehlt", + "home.open": "Öffnen…", + "home.opened_days_ago": "Vor {count} Tag(en) geöffnet", + "home.opened_hours_ago": "Vor {count} Std. geöffnet", + "home.opened_just_now": "Gerade eben geöffnet", + "home.opened_minutes_ago": "Vor {count} Min. geöffnet", + "home.opening": "wird geöffnet…", + "home.recent": "Zuletzt verwendet", + "home.report_issue": "Problem melden", + "home.samples": "Beispiele", + "home.whats_new": "Neuigkeiten", "install.button_tip": "SolidCraft als App installieren: eigenes Fenster, funktioniert auch offline", - "install.title": "SolidCraft installieren", - "install.steps_intro": "Safari installiert Web-Apps über seine eigenen Menüs:", - "install.home_screen_1": "Tippen Sie auf „Teilen“ (im Menü …, falls es nicht in der Symbolleiste ist).", - "install.home_screen_2": "Wählen Sie „Zum Home-Bildschirm“.", - "install.home_screen_3": "Tippen Sie auf „Hinzufügen“.", - "install.home_screen_after": "SolidCraft öffnet sich dann über sein Symbol auf dem Home-Bildschirm, ohne die Leisten von Safari, und funktioniert auch offline.", "install.dock_1": "Wählen Sie Ablage › Zum Dock hinzufügen.", "install.dock_2": "Klicken Sie auf „Hinzufügen“.", "install.dock_after": "SolidCraft öffnet sich dann aus dem Dock in einem eigenen Fenster und funktioniert auch offline.", "install.done": "Fertig", - "update.title": "Update verfügbar", + "install.home_screen_1": "Tippen Sie auf „Teilen“ (im Menü …, falls es nicht in der Symbolleiste ist).", + "install.home_screen_2": "Wählen Sie „Zum Home-Bildschirm“.", + "install.home_screen_3": "Tippen Sie auf „Hinzufügen“.", + "install.home_screen_after": "SolidCraft öffnet sich dann über sein Symbol auf dem Home-Bildschirm, ohne die Leisten von Safari, und funktioniert auch offline.", + "install.menu": "App installieren…", + "install.steps_intro": "Safari installiert Web-Apps über seine eigenen Menüs:", + "install.title": "SolidCraft installieren", + "joint.from_bodies_hint": "Jeder ausgewählte Körper kommt in eine eigene neue Komponente und bleibt, wo er ist.", + "joint.one_body": "Beide Auswahlen liegen auf {body}. Wählen Sie die zweite auf einem anderen Teil.", + "joint.one_component": "Diese Teile sind Körper einer Komponente: {bodies}. Ein Gelenk bewegt eine Komponente gegenüber einer anderen, daher braucht jedes Teil eine eigene Komponente.", + "nav.touchpad.help": "Umschalt gedrückt halten und den Zeiger zum Verschieben bewegen; mit Alt/Option drehen. Keine Maustaste nötig. Vertikales Scrollen zoomt.", + "nav.touchpad.label": "Touchpad", + "nav.touchpad.orbit": "Drehen (Alt/Option halten und bewegen; ohne Maustaste)", + "nav.touchpad.pan": "Verschieben (Umschalt halten und bewegen; ohne Maustaste)", + "nav.touchpad.scroll": "Touchpad verwendet vertikales Scrollen zum Zoomen. Die Zwei-Finger-Verschiebung bleibt für andere Vorgaben gespeichert.", + "nav.touchpad.zoom": "Zoom (vertikal scrollen oder Finger spreizen/zusammenziehen)", + "render.background": "Szenenhintergrund", + "render.fit": "Produkt einpassen", + "render.image_cancel": "Rendering abbrechen", + "render.image_cancelled": "Rendering abgebrochen", + "render.image_cancelling": "Wird abgebrochen", + "render.image_check": "Renderanfrage prüfen", + "render.image_completed": "Bild bereit zum Export", + "render.image_encoding": "PNG wird kodiert", + "render.image_export": "PNG exportieren", + "render.image_failed": "Rendering fehlgeschlagen", + "render.image_height": "Höhe", + "render.image_help": "CPU-Vorschaubild · PNG · angenäherte Transparenz", + "render.image_overwrite": "Vorhandene Datei ersetzen", + "render.image_preparing": "Bild wird vorbereitet", + "render.image_queued": "Warten auf Rendering", + "render.image_reduce": "Kleineres Bild oder einfachere Szene versuchen.", + "render.image_running": "Bild wird gerendert", + "render.image_stale": "Dieses Bild verwendet die Szene vor den nachfolgenden Änderungen.", + "render.image_start": "Rendering starten", + "render.image_supported": "Renderanfrage unterstützt; Warteschlange und Speicher werden beim Start erneut geprüft.", + "render.image_title": "Bild rendern", + "render.image_too_large": "Über dem Bildlimit: 4096 Pixel pro Seite und 4.194.304 Pixel insgesamt.", + "render.image_transparent": "Transparenter Hintergrund", + "render.image_unknown": "Renderstatus nicht verfügbar", + "render.image_use_largest": "Größte Größe mit diesem Seitenverhältnis verwenden:", + "render.image_width": "Breite", + "render.navigation_help": "Die Kamera bewegt sich wie im Konstruieren (Einstellungen › Navigation). Setup speichern übernimmt die aktuelle Kamera.", + "render.opaque_image_summary": "Vorschau-PNG · opakes PBR · Transparenz durch Blending", + "render.opaque_preview_help": "Opakes PBR und einfache Farben; Transparenz durch Blending. Brechung, HDRI und finales Rendering sind noch nicht verfügbar.", + "render.perspective": "Perspektivische Kamera", + "render.preview": "Integrierte Vorschau", + "render.preview_help": "Rasterdarstellung mit gemischter Transparenz. Brechung, HDRI und finales Rendering sind noch nicht verfügbar.", + "render.reload_settings": "Gespeicherte Einstellungen laden", + "render.restore_camera": "Gespeicherte Kamera laden", + "render.return_design": "Zurück zu Design", + "render.save_setup": "Setup speichern", + "render.setup_name": "Name des Setups", + "render.unavailable_preview": "Dieses Setup verlangt ein nicht verfügbares Vorschauprofil.", + "render.unsaved": "Ungespeicherte Vorschauänderungen", + "render.use_preview": "Integrierte Vorschau verwenden", + "sample.bracket.about": "Grundflansch mit Kantenflanschen und einer Umkantung nach einer 2-mm-Blechregel", + "sample.bracket.name": "Blechwinkel", + "sample.enclosure.about": "Ausgehöhlter Block mit Lippe, Schraubenerhöhungen, Auflage und Rastverbindung", + "sample.enclosure.name": "Kunststoffgehäuse", + "sample.flange.about": "Nabe und Flansch mit einem parametergesteuerten radialen Muster", + "sample.flange.name": "Schraubflansch", + "sample.hinge.about": "Zwei Komponenten und ein Drehgelenk, auf 60° angetrieben", + "sample.hinge.name": "Scharnierbaugruppe", + "sample.plate.about": "Parametrische Platte mit Vollrundungen, Bohrungen und einer aufgebohrten Erhöhung", + "sample.plate.name": "Beispielplatte", + "sample.vents.about": "Langlöcher in einem Rechteckmuster: Zeilen, Spalten und Abstand sind Parameter", + "sample.vents.name": "Lüftungsplatte", + "settings.display_quality_note": "Feinere Stufen zeigen gekrümmte Flächen und Kanten glatter und brauchen länger zum Vernetzen. Nur die Ansicht ändert sich, nie das Design oder Exporte.", + "settings.measure_axis_distances": "X/Y/Z-Maße anzeigen", + "settings.measure_axis_distances_help": "Bei geöffneter Messung die Abstände entlang der Weltachsen zusätzlich zum Gesamtabstand anzeigen.", + "settings.msaa_applies_on_restart": "Die Kantenglättung wird beim nächsten Start von SolidCraft übernommen", + "settings.msaa_reset": "{setting}: {requested}× wird von diesem Grafikgerät nicht unterstützt; jetzt {reset}× (unterstützt: {supported}).", + "settings.msaa_unsupported": "Von diesem Grafikgerät nicht unterstützt", + "settings.reset_intro": "Diese Einstellungen funktionieren auf diesem Computer nicht und würden den Start von SolidCraft verhindern. Sie wurden daher geändert:", + "settings.reset_title": "Einstellungen wurden geändert", + "settings.supersampling_note": "Zeichnet die Ansicht in höherer Auflösung und rechnet sie herunter: glattere Kanten, Linien und Raster auf Bildschirmen unter 4K. Kostet GPU-Zeit: etwa 2,25-mal so viele Pixel bei 1,5× und 4-mal bei 2×.", + "sketch.degrees_of_freedom": "{count} Freiheitsgrade", + "sketch.draw_curves": "Als {linetype} zeichnen", + "sketch.make_selection": "Auswahl als {linetype} markieren", + "sketch_text.align_center": "Mitte", + "sketch_text.align_left": "Links", + "sketch_text.align_right": "Rechts", + "sketch_text.bold": "Fett", + "sketch_text.builtin_font": "{family} (integriert)", + "sketch_text.font_search": "Schriftarten suchen", + "sketch_text.italic": "Kursiv", + "sketch_text.loading_fonts": "Installierte Schriftarten werden gesucht…", + "sketch_text.on_path": "Der Text folgt seiner Kurve: sie bestimmt seine Lage", + "sketch_text.path_clear": "Text von der Kurve lösen", + "sketch_text.path_hint": "Eine Skizzenkurve, der der Text folgt: hier klicken, dann die Kurve", + "sketch_text.use_font_file": "Schriftdatei {path} verwenden", + "timeline.group": "Neuen Merkmalsordner anlegen", + "timeline.move_many": "Zeitleistenelemente verschieben", + "timeline.move_to_group": "Merkmale in Ordner verschieben", + "timeline.rename_group": "Merkmalsordner umbenennen", + "timeline.reorder_many": "Merkmale neu ordnen", + "timeline.ungroup": "Merkmalsordner entfernen", + "toolbar.image": "BILD", + "toolbar.render": "RENDERN", + "toolbar.render_scene": "SZENE", + "ui.1_degree_of_freedom": "1 Freiheitsgrad", + "ui.3d_sketch": "3D-Skizze", + "ui.about": "Über", + "ui.activate": "Aktivieren", + "ui.active_component": "Aktive Komponente", + "ui.agent_chat": "Agenten-Chat", + "ui.agent_chat_allow": "Erlauben", + "ui.agent_chat_allowed": "Erlaubt", + "ui.agent_chat_answered": "Antwort: {option}", + "ui.agent_chat_approval": "Darf der Agent das tun?", + "ui.agent_chat_attach_view": "Ansicht anhängen", + "ui.agent_chat_attach_view_tip": "Ein Bild der aktuellen Ansicht mit der Nachricht senden", + "ui.agent_chat_auth_agent": "Mit {name} anmelden", + "ui.agent_chat_auth_env": "Setzen Sie {vars} in Ihrer Umgebung und starten Sie SolidCraft neu.", + "ui.agent_chat_auth_needed": "Der Agent bittet Sie, sich anzumelden. Sie melden sich beim Agenten selbst an; SolidCraft sieht Ihr Passwort oder Ihre Schlüssel nie.", + "ui.agent_chat_auth_none": "Der Agent bietet hier keine Anmeldung an: Melden Sie sich so an, wie es seine Dokumentation beschreibt.", + "ui.agent_chat_auth_retry": "Ich bin angemeldet: erneut verbinden", + "ui.agent_chat_auth_terminal": "Führen Sie dies in einem Terminal aus und klicken Sie dann erneut auf Verbinden:", + "ui.agent_chat_auth_title": "Beim Agenten anmelden", + "ui.agent_chat_cancel": "Abbrechen", + "ui.agent_chat_changes": "Änderungen: {n}, ein Rückgängig-Schritt", + "ui.agent_chat_changes_of": "{n}/{limit} Änderungen", + "ui.agent_chat_close": "Schließen", + "ui.agent_chat_command": "Agentenbefehl", + "ui.agent_chat_connect": "Verbinden", + "ui.agent_chat_copy": "Kopieren", + "ui.agent_chat_custom_hint": "Jedes Programm, das das Agent Client Protocol über stdin und stdout spricht. Es läuft ohne Shell.", + "ui.agent_chat_denied": "Abgelehnt", + "ui.agent_chat_deny": "Ablehnen", + "ui.agent_chat_desktop_only": "Der Agenten-Chat braucht die Desktop-App.", + "ui.agent_chat_detecting": "Suche nach Agenten…", + "ui.agent_chat_dock_left": "Links andocken", + "ui.agent_chat_dock_right": "Rechts andocken", + "ui.agent_chat_exited": "Der Agent wurde beendet.", + "ui.agent_chat_failed_start": "Der Agent konnte nicht starten: {error}", + "ui.agent_chat_intro": "Chatten Sie mit einem Coding-Agenten, den Sie schon nutzen, oder einem Modell-Endpunkt Ihrer Wahl. Er arbeitet über die Werkzeuge von SolidCraft am geöffneten Design: Seine Änderungen erscheinen sofort und lassen sich pro Nachricht in einem Schritt rückgängig machen. Was er ohne Nachfrage darf, legen Sie unter Einstellungen > KI fest.", + "ui.agent_chat_key_in_env": "Schlüssel gesetzt", + "ui.agent_chat_left": "Links", + "ui.agent_chat_limit": "Der Agent hat die Grenze von {limit} Änderungen für eine Nachricht erreicht. Senden Sie eine weitere Nachricht, damit er weitermacht.", + "ui.agent_chat_minimize": "Zu einer Leiste minimieren", + "ui.agent_chat_no_cli": "solidcraft-cli wurde neben der App nicht gefunden, daher kann der Agent das Design nicht erreichen.", + "ui.agent_chat_no_control": "Der Endpunkt des Agenten-Chats ist nicht gestartet, daher kann der Agent das Design nicht erreichen.", + "ui.agent_chat_no_images": "Dieser Agent nimmt keine Bilder an", + "ui.agent_chat_none_found": "Kein Coding-Agent gefunden. Installieren Sie einen davon und klicken Sie dann auf Aktualisieren:", + "ui.agent_chat_none_found_short": "Kein Agent gefunden", + "ui.agent_chat_not_installed": "Nicht installiert", + "ui.agent_chat_not_signed_in": "nicht angemeldet", + "ui.agent_chat_permission": "Der Agent möchte ausführen: {title}", + "ui.agent_chat_pick": "Agent", + "ui.agent_chat_placeholder": "Bitten Sie den Agenten, das Design zu ändern…", + "ui.agent_chat_privacy": "Nichts geht irgendwohin außer an den Agenten, den Sie unter Ihrem eigenen Konto ausführen.", + "ui.agent_chat_privacy_note": "SolidCraft sendet nichts irgendwohin: Der Agent, den Sie starten, spricht unter Ihrem eigenen Konto mit seinem eigenen Dienst. SolidCraft sieht und speichert nie einen Schlüssel oder ein Passwort.", + "ui.agent_chat_refresh": "Aktualisieren", + "ui.agent_chat_refused": "Für den Agenten nicht erlaubt: {reason}", + "ui.agent_chat_right": "Rechts", + "ui.agent_chat_send": "Senden", + "ui.agent_chat_side": "Seite des Agenten-Chats", + "ui.agent_chat_signed_in": "angemeldet", + "ui.agent_chat_state_auth": "Anmeldung nötig", + "ui.agent_chat_state_busy": "Arbeitet…", + "ui.agent_chat_state_exited": "Agent beendet", + "ui.agent_chat_state_off": "Nicht verbunden", + "ui.agent_chat_state_ready": "Bereit", + "ui.agent_chat_state_starting": "Startet…", + "ui.agent_chat_stop": "Beenden", + "ui.agent_chat_stop_tip": "Den Agenten und alles, was er gestartet hat, beenden", + "ui.agent_chat_turn_limit": "Änderungen pro Nachricht", + "ui.agent_chat_undo_changes": "Diese Änderungen rückgängig machen", + "ui.agent_chat_undo_label": "Agenten-Chat: {message}", + "ui.agent_chat_undone": "(rückgängig gemacht)", + "ui.agent_chat_view_attached": "Ansicht angehängt", + "ui.agent_chat_wait_turn": "Der Agent arbeitet noch an der letzten Nachricht: Warten Sie oder klicken Sie auf Abbrechen.", + "ui.agent_cursor": "Agent-Cursor", + "ui.agent_cursor_speed": "Agent-Cursor-Geschwindigkeit", + "ui.ai_add": "Hinzufügen", + "ui.ai_add_agent": "Agent hinzufügen…", + "ui.ai_add_agent_title": "Agent hinzufügen", + "ui.ai_add_api": "OpenAI-kompatible API", + "ui.ai_add_custom": "Eigener Befehl", + "ui.ai_add_installed": "Installierter Agent", + "ui.ai_add_installed_note": "Ein eigener Eintrag für einen installierten Agenten, zum Beispiel mit anderen Argumenten. Installierte Agenten erscheinen von selbst.", + "ui.ai_added": "hinzugefügt", + "ui.ai_agent_mode_tip": "Der eigene Modus des Agenten: Seine eigenen Werkzeuge (Shell, Dateiänderungen) folgen ihm. Die Werkzeuge von SolidCraft folgen den Berechtigungen unter Einstellungen > KI.", + "ui.ai_agents": "Agenten", + "ui.ai_always_allow": "Immer erlauben", + "ui.ai_always_allow_tip": "{tool} für diesen Agenten ab jetzt ohne Nachfrage erlauben", + "ui.ai_always_allowed": "Immer erlaubt", + "ui.ai_always_allowed_none": "Noch nichts ist immer erlaubt. Antworten „Immer erlauben“ im Chat erscheinen hier.", + "ui.ai_auto_allowed": "Automatisch erlaubt: {title} ({why})", + "ui.ai_auto_mode": "Ihre Berechtigungseinstellung", + "ui.ai_auto_ours": "SolidCraft prüft seine eigenen Werkzeuge selbst", + "ui.ai_auto_remembered": "Sie haben „Immer erlauben“ gewählt", + "ui.ai_bad_url": "Geben Sie eine URL ein, die mit http:// oder https:// beginnt", + "ui.ai_base_url": "Basis-URL", + "ui.ai_button": "KI", + "ui.ai_copy_suffix": "Kopie", + "ui.ai_custom_url": "Eigene URL", + "ui.ai_default": "Standard", + "ui.ai_http_busy": "der Endpunkt ist ausgelastet oder am Limit; versuchen Sie es später", + "ui.ai_http_key": "der Endpunkt hat den Schlüssel abgelehnt: prüfen Sie ihn unter Einstellungen > KI", + "ui.ai_http_not_found": "Endpunkt oder Modell nicht gefunden: prüfen Sie Basis-URL und Modellnamen", + "ui.ai_key": "API-Schlüssel", + "ui.ai_key_hint": "optional; im Schlüsselbund des Systems gespeichert", + "ui.ai_key_needs_https": "Ein Schlüssel wird nur über HTTPS oder an diesen Computer gesendet.", + "ui.ai_key_note": "Im Schlüsselbund des Systems gespeichert, nie in den Einstellungen von SolidCraft. Für einen lokalen Server leer lassen.", + "ui.ai_keychain_error": "Der Schlüsselbund des Systems hat abgelehnt: {error}", + "ui.ai_mode_all": "Alles erlauben", + "ui.ai_mode_all_note": "Nichts fragt vorher. Absturzberichte bleiben tabu, und die Ordnergrenzen gelten weiter.", + "ui.ai_mode_all_warning": "Der Agent kann Ihr Design ohne Nachfrage speichern, überschreiben, exportieren und ersetzen. Nutzen Sie das nur mit einem Agenten, dem Sie vertrauen, und mit gespeicherten Designs.", + "ui.ai_mode_ask": "Jedes Mal fragen", + "ui.ai_mode_ask_note": "Jede Änderung am Design und jede Dateiaktion wartet auf Ihr Erlauben.", + "ui.ai_mode_edits": "Modelländerungen automatisch erlauben", + "ui.ai_mode_edits_note": "Modellierbefehle laufen ohne Nachfrage; Speichern, Öffnen, Exportieren und andere Datei- oder destruktive Aktionen fragen weiterhin.", + "ui.ai_mode_global": "Wie oben eingestellt", + "ui.ai_model": "Modell", + "ui.ai_modes_scope": "Diese Einstellungen gelten für die Werkzeuge von SolidCraft. Die eigenen Werkzeuge eines Agenten (seine Shell, seine Dateiänderungen) folgen seinem eigenen Modus, den Sie im Kopf des Chat-Panels wählen, wenn der Agent Modi hat.", + "ui.ai_name": "Name", + "ui.ai_need_command": "Geben Sie den Befehl ein, der den Agenten startet", + "ui.ai_need_model": "Geben Sie den Modellnamen ein", + "ui.ai_no_answer": "Der Agent hat nicht rechtzeitig geantwortet", + "ui.ai_no_http": "Dieser Build kann keine API-Endpunkte erreichen", + "ui.ai_no_keychain": "Der Schlüsselbund des Systems ist nicht verfügbar, daher kann kein Schlüssel gespeichert werden. Ein lokaler Server ohne Schlüssel funktioniert trotzdem.", + "ui.ai_panel": "Panel", + "ui.ai_permissions": "Berechtigungen", + "ui.ai_preset": "Vorlage", + "ui.ai_remove": "Entfernen", + "ui.ai_request_limit": "nach 24 Anfragen für eine Nachricht angehalten; senden Sie eine weitere Nachricht, um fortzufahren", + "ui.ai_reset": "Zurücksetzen", + "ui.ai_settings": "KI-Einstellungen…", + "ui.ai_show_features": "KI-Funktionen anzeigen", + "ui.ai_show_features_note": "Der Agenten-Chat: ein Panel, in dem ein Coding-Agent, den Sie schon nutzen, oder ein Modell-Endpunkt Ihrer Wahl am geöffneten Design arbeitet. Aus: keine KI-Schaltfläche, kein Kürzel, kein Menüeintrag, kein Panel, und nichts wird gesucht oder gestartet.", + "ui.ai_switch_tip": "Den Agenten für dieses Gespräch wechseln", + "ui.ai_test": "Testen", + "ui.ai_test_acp_ok": "Antwortet: {agent}", + "ui.ai_test_acp_tip": "Startet den Agenten kurz und bittet um eine Sitzung; beendet ihn wieder", + "ui.ai_test_api_tip": "Fragt den Endpunkt nach seinen Modellen", + "ui.ai_test_no_model": "Erreicht: {count} Modelle, aber nicht {model}", + "ui.ai_test_ok": "Erreicht: {count} Modelle", + "ui.ai_testing": "Teste…", + "ui.ai_tool_done": "fertig", + "ui.ai_tool_failed": "fehlgeschlagen", + "ui.ai_tool_running": "läuft", + "ui.ai_tool_unfold": "Klicken, um das Ergebnis zu zeigen", + "ui.ai_tool_waiting": "wartet", + "ui.ai_toolbar_button": "Schaltfläche in der Werkzeugleiste anzeigen", + "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.analysis": "Analyse", + "ui.angle": "Winkel", + "ui.angle_decimals": "Winkel-Dezimalstellen", + "ui.animateJoint": "Gelenk animieren", + "ui.animate_view_changes": "Ansichtsänderungen animieren", + "ui.animation": "Animation", + "ui.animation_speed": "Animationsgeschwindigkeit", + "ui.anti_aliasing": "Kantenglättung", + "ui.apply": "Anwenden", + "ui.arc": "Kreisbogen", + "ui.assemble": "Zusammenbau", + "ui.autosave_every": "Autospeichern alle", + "ui.axes": "Achsen", + "ui.axis": "Achse", + "ui.base_point": "Basispunkt", + "ui.blocked": "Verdeckt", + "ui.bodies": "Körper", + "ui.box": "Block", + "ui.break": "Unterbrechen", + "ui.calibrate": "Kalibrieren", + "ui.cancel": "Abbrechen", + "ui.canvases": "Kanvas", + "ui.center": "Mittelpunkt", + "ui.centerline": "Mittellinie", + "ui.chain": "Kette", + "ui.chamfer": "Abschrägung", + "ui.chamfer_type": "Fasentyp", + "ui.change_workspace": "Arbeitsbereich wechseln", + "ui.chord_length": "Sehnenlänge", + "ui.circle": "Kreis", + "ui.circular_pattern": "Radiales Muster", + "ui.clear_recent": "Zuletzt verwendet leeren", + "ui.clear_the_selection": "Auswahl aufheben", + "ui.close": "Schließen", + "ui.coil": "Schraube", + "ui.coincident": "Koinzident", + "ui.collapse": "Einklappen", + "ui.collinear": "Kollinear", + "ui.colour_vision": "Farbsehen", + "ui.colour_vision_deutan": "Deutan", + "ui.colour_vision_deutan_tip": "Bei schwachem oder fehlendem Grünsinn", + "ui.colour_vision_failed": "Fehler", + "ui.colour_vision_fixed": "Fixiert", + "ui.colour_vision_mode": "Modus", + "ui.colour_vision_note": "Ändert die Farben, die eine Bedeutung tragen: Skizzenstatus, Achsen, Biegungen, Analysen und Symbole. Wenn Sie die Farbfilter von Windows verwenden, lassen Sie dies auf „Aus“.", + "ui.colour_vision_off": "Aus", + "ui.colour_vision_off_tip": "Die eigenen Farben des Designs", + "ui.colour_vision_projected": "Projiziert", + "ui.colour_vision_protan": "Protan", + "ui.colour_vision_protan_tip": "Bei schwachem oder fehlendem Rotsinn", + "ui.colour_vision_sample": "Beispiel", + "ui.colour_vision_tritan": "Tritan", + "ui.colour_vision_tritan_tip": "Bei schwachem oder fehlendem Blausinn", + "ui.combine": "Kombinieren", + "ui.coming_later": "bald verfügbar", + "ui.command_done": "{command} fertig", + "ui.command_palette_hint": "Befehl eingeben, z. B. {example} — oder S drücken, um zu suchen", + "ui.concentric": "Konzentrisch", + "ui.configurations": "Konfigurationen", + "ui.conic_curve": "Kegelschnitt", + "ui.constant": "Konstant", + "ui.constraints_conflict": "Bedingungen konfliktreich", + "ui.construct": "Konstruktion", + "ui.construction": "Konstruktionslinie", + "ui.copy": "Kopieren", + "ui.corner": "Ecke", + "ui.corners": "Ecken", + "ui.counterbore": "Tiefenbohrung", + "ui.countersink": "Senkung", + "ui.create": "Erstellen", + "ui.create_copy": "Kopie erstellen", + "ui.create_sketch": "Skizze erstellen", + "ui.current": "aktuell", + "ui.curvature": "Krümmung", + "ui.curvature_g2": "Krümmungsstetig (G2)", + "ui.curves": "Kurven", + "ui.custom_program": "Benutzerdefiniert…", + "ui.custom_program_tip": "Ein Slicer-Programm zur Liste hinzufügen", + "ui.customizeToolbar": "Symbolleiste anpassen…", + "ui.cut": "Ausschneiden", + "ui.cylinder": "Zylinder", + "ui.dark": "Dunkel", + "ui.default_modelling_orientation": "Standard-Modellierungsorientierung", + "ui.degrees_of_freedom": "Freiheitsgrade", + "ui.delete": "Löschen", + "ui.depth": "Tiefe", + "ui.design": "Design", + "ui.design_properties.author": "Autor", + "ui.design_properties.description": "Beschreibung", + "ui.design_properties.exports": "STEP-, IGES- und 3MF-Exporte übernehmen diese Angaben, wo das Format ein Feld dafür hat.", + "ui.design_properties.license": "Lizenz", + "ui.design_properties.not_text": "Nicht als Text gespeichert; eine Eingabe hier ersetzt den Wert.", + "ui.design_properties.organization": "Organisation", + "ui.design_properties.others": "Daten anderer Werkzeuge", + "ui.design_properties.others_note": "Bleiben unverändert in der Konstruktion und werden nie exportiert.", + "ui.design_properties.part_number": "Teilenummer", + "ui.design_properties.project": "Projekt", + "ui.design_properties.revision": "Revision", + "ui.diameter": "Durchmesser", + "ui.dimension": "Maß", + "ui.direction": "Richtung", + "ui.display_quality": "Darstellungsqualität", + "ui.display_quality_coarse": "Grob", + "ui.display_quality_fine": "Fein", + "ui.display_quality_normal": "Normal", + "ui.display_quality_ultra": "Ultra", + "ui.distance": "Abstand", + "ui.distance_1": "Abstand 1", + "ui.distance_2": "Abstand 2", + "ui.document_settings": "Dokumenteneinstellungen", + "ui.don_t_save": "Nicht speichern", + "ui.draft": "Abziehen", + "ui.drawing": "Zeichnung", + "ui.drill_point": "Bohrpunkt", + "ui.edit": "Bearbeiten", + "ui.editJointLimits": "Gelenkgrenzen bearbeiten", + "ui.edit_section_analysis": "Querschnittsanalyse bearbeiten", + "ui.ellipse": "Ellipse", + "ui.end_radius": "Endradius", + "ui.end_scale": "Endskalierung", + "ui.entities": "Elemente", + "ui.equal": "Gleich", + "ui.equivalent_radius": "Äquivalenter Radius", + "ui.expand": "Aufklappen", + "ui.exportDxf": "Als DXF exportieren…", + "ui.export_ellipsis": "Exportieren...", + "ui.export_ellipsis_keymap": "Exportieren…", + "ui.extend": "Verlängern", + "ui.extent_type": "Ausdehnungstyp", + "ui.extrude": "Extrudieren", + "ui.factor": "Faktor", + "ui.feature_history": "Feature-Verlauf", + "ui.feature_options": "Funktionsoptionen", + "ui.features": "Funktionen", + "ui.file": "Datei", + "ui.fillet": "Vollrundung", + "ui.findInTimeline": "In der Zeitleiste suchen", + "ui.findInWindow": "Im Fenster suchen", + "ui.finish_sketch": "Skizze beenden", + "ui.fit": "Einpassen", + "ui.fix_unfix": "Fixieren/Lösen", + "ui.flat": "Flach", + "ui.flip": "Umkehren", + "ui.format": "Format", + "ui.front": "Vorne", + "ui.fully_constrained": "Vollständig bestimmt", + "ui.general": "Allgemein", + "ui.graphics": "Grafik", + "ui.groupSelected": "Auswahl gruppieren", + "ui.heading_assemble": "ZUSAMMENBAU", + "ui.heading_box": "BLOCK", + "ui.heading_chamfer": "ABSCHRÄGUNG", + "ui.heading_circular_pattern": "RADIALES MUSTER", + "ui.heading_coil": "SCHRAUBE", + "ui.heading_combine": "KOMBINIEREN", + "ui.heading_configure": "KONFIGURIEREN", + "ui.heading_constraints": "RANDBEDINGUNGEN", + "ui.heading_construct": "KONSTRUKTION", + "ui.heading_create": "ERSTELLEN", + "ui.heading_create_sketch": "SKIZZE ERSTELLEN", + "ui.heading_cylinder": "ZYLINDER", + "ui.heading_design": "DESIGN", + "ui.heading_draft": "ABZIEHEN", + "ui.heading_edit": "BEARBEITEN", + "ui.heading_extrude": "EXTRUDIEREN", + "ui.heading_fillet": "VOLLRUNDUNG", + "ui.heading_finish_sketch": "SKIZZE BEENDEN", + "ui.heading_front": "VORNE", + "ui.heading_hole": "BOHRUNG", + "ui.heading_home": "START", + "ui.heading_insert": "EINFÜGEN", + "ui.heading_inspect": "PRÜFEN", + "ui.heading_loft": "LOFT", + "ui.heading_measure": "Messen", + "ui.heading_mesh": "MESH", + "ui.heading_mirror": "SPIEGELN", + "ui.heading_modify": "ÄNDERN", + "ui.heading_move": "VERSCHIEBEN", + "ui.heading_move_copy": "VERSCHIEBEN/KOPIEREN", + "ui.heading_offset": "ABSTAND", + "ui.heading_offset_plane": "ABSTANDSEBENE", + "ui.heading_ok": "OK", + "ui.heading_parameters": "PARAMETER", + "ui.heading_pattern_on_path": "PFADMUSTER", + "ui.heading_pipe": "ROHR", + "ui.heading_plane_at_angle": "EBENE IM WINKEL", + "ui.heading_plastic": "PLASTIK", + "ui.heading_position": "POSITION", + "ui.heading_rectangular_pattern": "RECHTECKMUSTER", + "ui.heading_revolve": "DREHEN", + "ui.heading_right": "RECHTS", + "ui.heading_save_mesh": "ALS NETZ SPEICHERN", + "ui.heading_scale": "SKALIEREN", + "ui.heading_section_analysis": "QUERSCHNITTSANALYSE", + "ui.heading_select": "AUSWÄHLEN", + "ui.heading_setup": "EINRICHTEN", + "ui.heading_sheet_metal": "BLECH", + "ui.heading_shell": "HÜLLE", + "ui.heading_sketch": "SKIZZE", + "ui.heading_sketch_palette": "SKIZZENPALETTE", + "ui.heading_sketch_scale": "SKIZZE SKALIEREN", + "ui.heading_solid": "KÖRPER", + "ui.heading_sphere": "SPHÄRE", + "ui.heading_split_body": "KÖRPER TRENNEN", + "ui.heading_surface": "FLÄCHE", + "ui.heading_sweep": "FÜHREN", + "ui.heading_thread": "GEWINDE", + "ui.heading_top": "OBEN", + "ui.heading_torus": "TORUS", + "ui.heading_utilities": "WERKZEUGE", + "ui.help": "Hilfe", + "ui.hide": "Ausblenden", + "ui.hideAxes": "Achsen ausblenden", + "ui.hideDimension": "Bemaßung ausblenden", + "ui.hideOrigin": "Ursprung ausblenden", + "ui.hidePlanes": "Ebenen ausblenden", + "ui.hideProfile": "Profil ausblenden", + "ui.hole": "Bohrung", + "ui.hole_tap_type": "Gewindetyp", + "ui.hole_type": "Bohrungstyp", + "ui.home": "Start", + "ui.homeView": "Startansicht", + "ui.horizontal_vertical": "Horizontal/Vertikal", + "ui.insert": "Einfügen", + "ui.inspect": "Prüfen", + "ui.intersect": "Schnitt", + "ui.isolate": "Isolieren", + "ui.join": "Verbinden", + "ui.joints": "Gelenke", + "ui.keyboard_shortcuts": "Tastenkürzel", + "ui.language": "Sprache", + "ui.length_decimals": "Längen-Dezimalstellen", + "ui.light": "Hell", + "ui.line": "Linie", + "ui.linetype": "Linientyp", + "ui.lock": "Sperren", + "ui.loft": "Loft", + "ui.look_at": "Ansehen", + "ui.manufacture": "Fertigung", + "ui.material_review.axes": "Materiallokale Achsen; keine Körperausrichtung zugewiesen.", + "ui.material_review.claims": "Quellen und Lizenzen sind ungeprüfte Angaben. Fehlende Werte bleiben unbekannt.", + "ui.material_review.compressive_strength": "Druckfestigkeit", + "ui.material_review.conditions": "Angegebene Bedingungen", + "ui.material_review.density": "Dichte", + "ui.material_review.derived": "Abgeleitete isotrope Moduln", + "ui.material_review.elasticity": "Elastizität", + "ui.material_review.input": "Materialkarte mit Schema 1 einfügen (JSON)", + "ui.material_review.limit": "Die Karte überschreitet die Eingabegrenze von 256 KiB.", + "ui.material_review.moisture_unit": "kg Wasser / kg Trockenmaterial", + "ui.material_review.properties": "Eigenschaften", + "ui.material_review.review": "Karte prüfen", + "ui.material_review.scope": "Nur Kandidat: nicht zugewiesen oder gespeichert. Numerische Prüfung ist keine technische Zertifizierung.", + "ui.material_review.shear_strength": "Scherfestigkeit", + "ui.material_review.source": "Quelle", + "ui.material_review.specific_heat": "Spezifische Wärmekapazität", + "ui.material_review.tensile_strength": "Zugfestigkeit", + "ui.material_review.thermal_conductivity": "Wärmeleitfähigkeit", + "ui.material_review.thermal_expansion": "Wärmeausdehnung", + "ui.material_review.title": "Physikalische Materialdaten prüfen", + "ui.material_review.unknown": "Unbekannt", + "ui.material_review.yield_strength": "Streckgrenze", + "ui.measure": "Messen", + "ui.mesh_format_3mf": "3MF", + "ui.mesh_format_3mf_tagged": "3MF mit Flächenmarken", + "ui.mesh_format_stl": "STL", + "ui.midpoint": "Mittelpunkt", + "ui.mirror": "Spiegeln", + "ui.mirror_line": "Spiegelachse", + "ui.modify": "Ändern", + "ui.move": "Verschieben", + "ui.multiple": "Mehrfach", + "ui.named_views": "Benannte Ansichten", + "ui.navigation": "Navigation", + "ui.needs_design": "{command}: Öffnen Sie zuerst ein Design", + "ui.newSketchGroup": "Neue Skizzengruppe", + "ui.new_body": "Neuer Körper", + "ui.new_design": "Neues Design", + "ui.no_slicer_found": "Kein Slicer gefunden", + "ui.normal": "Normal", + "ui.normalConstruction": "Normal / Konstruktion", + "ui.not_a_program": "{path} ist kein startbares Programm", + "ui.object_type": "Objekttyp", + "ui.objects": "Objekte", + "ui.offer_to_stand_up_y_up_files": "Y-hoch-Dateien aufrecht anbieten", + "ui.offset": "Abstand", + "ui.offset_plane": "Abstandsebene", + "ui.one_side": "Einseitig", + "ui.open": "Öffnen", + "ui.open_ellipsis": "Öffnen...", + "ui.open_preferences": "Einstellungen öffnen", + "ui.open_recent": "Zuletzt verwendet", + "ui.operation": "Operation", + "ui.options": "Optionen", + "ui.orbit": "Drehen", + "ui.orbit_around": "Umkreisen um", + "ui.orientation": "Ausrichtung", + "ui.origin": "Ursprung", + "ui.palette_points": "Punkte", + "ui.palette_profile": "Profil", + "ui.pan": "Verschieben", + "ui.pan_zoom_orbit": "Verschieben, zoomen, umkreisen", + "ui.parallel": "Parallel", + "ui.parameters": "Parameter", + "ui.paste": "Einfügen", + "ui.path": "Pfad", + "ui.pattern_on_path": "Pfadmuster", + "ui.perpendicular": "Senkrecht", + "ui.pinToShortcuts": "An Verknüpfungen anheften", + "ui.pinToToolbar": "An Symbolleiste anheften", + "ui.pipe": "Rohr", + "ui.placement": "Platzierung", + "ui.plane": "Ebene", + "ui.plane_at_angle": "Ebene im Winkel", + "ui.point": "Punkt", + "ui.point_under_the_cursor": "Punkt unter dem Cursor", + "ui.points": "Punkte", + "ui.polygon": "Polygon", + "ui.preferences": "Einstellungen", + "ui.profile": "Profil", + "ui.profile_plane": "Profilebene", + "ui.profiles": "Profile", + "ui.project": "Projizieren", + "ui.properties": "Eigenschaften", + "ui.pull_direction": "Entformungsrichtung", + "ui.quantity": "Anzahl", + "ui.quantity_2": "Anzahl 2", + "ui.quit": "Beenden", + "ui.radius": "Radius", + "ui.radius_type": "Radius-Typ", + "ui.reachable": "Erreichbar", + "ui.rectangle": "Rechteck", + "ui.rectangular_pattern": "Rechteckmuster", + "ui.redo": "Wiederholen", + "ui.removeFromToolbar": "Aus der Symbolleiste entfernen", + "ui.removeSection": "Schnitt entfernen", + "ui.render": "Rendern", + "ui.repeat": "Wiederholen", + "ui.report_a_bug": "Fehler melden", + "ui.reset_the_settings_on_this_page": "Einstellungen auf dieser Seite zurücksetzen", + "ui.restore": "Wiederherstellen", + "ui.restore_defaults": "Standardeinstellungen wiederherstellen", + "ui.reverse_zoom_direction": "Zoomrichtung umkehren", + "ui.revolve": "Drehen", + "ui.right": "Rechts", + "ui.save": "Speichern", + "ui.save_as": "Speichern unter", + "ui.save_as_ellipsis": "Speichern unter...", + "ui.save_mesh_no_slicer": "Kein Slicer gefunden: „Benutzerdefiniert…“ wählen und das Slicer-Programm angeben, oder „An Slicer senden“ ausschalten", + "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.scale": "Skalieren", + "ui.section_analysis": "Querschnittsanalyse", + "ui.select": "Auswählen", + "ui.selectOther": "Andere auswählen…", + "ui.selectTangentChain": "Tangentialkette auswählen", + "ui.selection": "Auswahl", + "ui.send": "Senden", + "ui.send_to_slicer": "An Slicer senden", + "ui.sent_to_slicer": "An {slicer} gesendet", + "ui.shell": "Hülle", + "ui.show": "Einblenden", + "ui.showAll": "Alle einblenden", + "ui.showAllBodies": "Alle Volumenkörper einblenden", + "ui.showAxes": "Achsen einblenden", + "ui.showDimension": "Bemaßung einblenden", + "ui.showOrigin": "Ursprung einblenden", + "ui.showPlanes": "Ebenen einblenden", + "ui.show_constraints": "Bedingungen", + "ui.show_construction_geometries": "Konstruktionsgeometrien", + "ui.show_dimensions": "Maße", + "ui.show_points": "Punkte anzeigen", + "ui.show_profile": "Profil anzeigen", + "ui.show_projected_geometries": "Projizierte Geometrien", + "ui.simple": "Einfach", + "ui.simulation": "Simulation", + "ui.single": "Einzel", + "ui.sketch": "Skizze", + "ui.sketch_dimension": "Skizzenmaß", + "ui.sketch_grid": "Skizzenraster", + "ui.sketch_scale": "Skizzenskalierung", + "ui.sketch_status": "Skizzenstatus", + "ui.sketches": "Skizzen", + "ui.slice": "Scheibe", + "ui.slicer": "Slicer", + "ui.slicer_delete_tip": "{program}\nMit Entf aus der Liste entfernen", + "ui.slot": "Langloch", + "ui.smooth": "Glatt", + "ui.snap": "Einrasten", + "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_radius": "Startradius", + "ui.supersampling": "Supersampling (SSAA)", + "ui.supersampling_adaptive": "Nur bei ruhender Ansicht", + "ui.supersampling_off": "Aus (1×)", + "ui.suppress": "Unterdrücken", + "ui.sweep": "Führen", + "ui.sweep_follow_direction": "Richtung folgen", + "ui.sweep_keep_as_drawn": "Wie gezeichnet", + "ui.sweep_turn_with_path": "Mit Pfad drehen", + "ui.symmetric": "Symmetrisch", + "ui.symmetry": "Symmetrie", + "ui.system": "System", + "ui.tangent": "Tangential", + "ui.taper_angle": "Kegelwinkel", + "ui.tapped": "Gewindebohrung", + "ui.text": "Text", + "ui.theme": "Design", + "ui.thickness": "Dicke", + "ui.thread": "Gewinde", + "ui.timeline_bottom": "Timeline unten", + "ui.timeline_left_note": "Im linken Layout wird die Rücksetzmarke über dem Teile- und Szenenbrowser eingeblendet.", + "ui.timeline_left_sidebar": "Linke Seitenleiste", + "ui.tip_angle": "Spitzenwinkel", + "ui.to_object": "Bis Objekt", + "ui.tool_direction": "Werkzeugrichtung", + "ui.top": "Oben", + "ui.torus": "Torus", + "ui.total_angle": "Gesamtwinkel", + "ui.trim": "Kürzen", + "ui.twist": "Verdrehung", + "ui.two_sides": "Beidseitig", + "ui.ui_scale": "UI-Skalierung", + "ui.undo": "Rückgängig", + "ui.unground": "Fixierung lösen", + "ui.unisolate": "Isolierung aufheben", + "ui.units": "Einheiten", + "ui.units_of_new_designs": "Einheiten für neue Designs", + "ui.unlock": "Entsperren", + "ui.unsuppress": "Unterdrückung aufheben", + "ui.untitled": "Ohne Titel", + "ui.updateToCurrentView": "Auf aktuelle Ansicht aktualisieren", + "ui.variable": "Variabel", + "ui.view_centre": "Ansichtszentrum", + "ui.visual_style": "Ansichtsstil", + "ui.workspace": "Arbeitsbereich", + "ui.x_distance": "X-Abstand", + "ui.y_distance": "Y-Abstand", + "ui.zoom": "Zoomen", + "ui.zoom_to_the_cursor": "Zum Cursor zoomen", "update.available": "SolidCraft {version} ist verfügbar", - "update.you_have": "Installiert ist {version}.", - "update.no_notes": "Zu diesem Release gibt es keine Hinweise.", - "update.system_hint": "Diese Installation ist ein {kind}. Aktualisieren mit:", - "update.package_hint": "Diese Installation stammt aus einem {kind}. Neues Paket herunterladen und installieren mit:", - "update.copy": "Kopieren", - "update.file": "Herunterladen holt {file}.", - "update.download": "Herunterladen", - "update.release_page": "Release-Seite öffnen", - "update.skip": "Diese Version überspringen", - "update.later": "Später erinnern", - "update.prefs_label": "Updates", + "update.button": "Update", + "update.button_tip": "SolidCraft {version} ist verfügbar", "update.check_automatically": "Automatisch nach Updates suchen", "update.check_now": "Jetzt suchen", "update.checking": "Suche läuft…", - "update.failed": "Suche fehlgeschlagen: {error}", - "update.up_to_date": "SolidCraft ist aktuell.", - "update.prefs_note": "Dies ist SolidCraft {version} ({kind}). Die Suche fragt GitHub nach dem neuesten Release und sendet sonst nichts.", - "update.prefs_dev": "Dies ist ein Entwicklungs-Build ({version}): er sucht nicht nach Updates.", - "update.show": "Update auf {version} anzeigen", - "update.prefs_flatpak": "Flatpak aktualisiert diese Installation ({version}): {command} ausführen oder die Softwareverwaltung nutzen. SolidCraft sucht nicht selbst.", - "update.update_now": "Jetzt aktualisieren", - "update.install_msi": "Installieren (schließt SolidCraft)", + "update.copy": "Kopieren", + "update.dmg_opened": "Das Disk-Image ist geöffnet und geprüft: SolidCraft in „Programme“ ziehen, die alte Version ersetzen und SolidCraft neu starten.", + "update.download": "Herunterladen", "update.download_open": "Herunterladen und öffnen", "update.downloading": "Herunterladen und prüfen… {done} von {total} MB", + "update.failed": "Suche fehlgeschlagen: {error}", + "update.file": "Herunterladen holt {file}.", + "update.install_failed": "Das Update wurde nicht installiert: {error}. Es wurde nichts verändert; „Herunterladen“ holt das Paket.", + "update.install_msi": "Installieren (schließt SolidCraft)", "update.installed": "SolidCraft {version} ist installiert. Zum Verwenden neu starten.", + "update.installer_started": "Das Installationsprogramm startet, wenn SolidCraft geschlossen wird.", + "update.later": "Später erinnern", + "update.no_notes": "Zu diesem Release gibt es keine Hinweise.", + "update.package_hint": "Diese Installation stammt aus einem {kind}. Neues Paket herunterladen und installieren mit:", + "update.prefs_dev": "Dies ist ein Entwicklungs-Build ({version}): er sucht nicht nach Updates.", + "update.prefs_flatpak": "Flatpak aktualisiert diese Installation ({version}): {command} ausführen oder die Softwareverwaltung nutzen. SolidCraft sucht nicht selbst.", + "update.prefs_label": "Updates", + "update.prefs_note": "Dies ist SolidCraft {version} ({kind}). Die Suche fragt GitHub nach dem neuesten Release und sendet sonst nichts.", + "update.release_page": "Release-Seite öffnen", "update.restart": "Jetzt neu starten", "update.restart_later": "Später", - "update.installer_started": "Das Installationsprogramm startet, wenn SolidCraft geschlossen wird.", - "update.dmg_opened": "Das Disk-Image ist geöffnet und geprüft: SolidCraft in „Programme“ ziehen, die alte Version ersetzen und SolidCraft neu starten.", - "update.install_failed": "Das Update wurde nicht installiert: {error}. Es wurde nichts verändert; „Herunterladen“ holt das Paket.", - "cmd.render_settings_get": "Rendereinstellungen", - "cmd.render_settings_set": "Rendereinstellungen speichern", - "cmd.render_scene": "Renderszene prüfen", - "cmd.render_settings_apply": "Renderkamera anwenden", - "toolbar.render": "RENDERN", - "toolbar.render_scene": "SZENE", - "render.preview": "Integrierte Vorschau", - "render.preview_help": "Rasterdarstellung mit gemischter Transparenz. Brechung, HDRI und finales Rendering sind noch nicht verfügbar.", - "render.setup_name": "Name des Setups", - "render.background": "Szenenhintergrund", - "render.perspective": "Perspektivische Kamera", - "render.fit": "Produkt einpassen", - "render.restore_camera": "Gespeicherte Kamera laden", - "render.save_setup": "Setup speichern", - "render.unsaved": "Ungespeicherte Vorschauänderungen", - "render.reload_settings": "Gespeicherte Einstellungen laden", - "render.unavailable_preview": "Dieses Setup verlangt ein nicht verfügbares Vorschauprofil.", - "render.use_preview": "Integrierte Vorschau verwenden", - "render.navigation_help": "Die Kamera bewegt sich wie im Konstruieren (Einstellungen › Navigation). Setup speichern übernimmt die aktuelle Kamera.", - "render.return_design": "Zurück zu Design", - "render.image_title": "Bild rendern", - "render.image_help": "CPU-Vorschaubild · PNG · angenäherte Transparenz", - "render.image_width": "Breite", - "render.image_height": "Höhe", - "render.image_transparent": "Transparenter Hintergrund", - "render.image_check": "Renderanfrage prüfen", - "render.image_supported": "Renderanfrage unterstützt; Warteschlange und Speicher werden beim Start erneut geprüft.", - "render.image_queued": "Warten auf Rendering", - "render.image_preparing": "Bild wird vorbereitet", - "render.image_running": "Bild wird gerendert", - "render.image_encoding": "PNG wird kodiert", - "render.image_cancelling": "Wird abgebrochen", - "render.image_cancelled": "Rendering abgebrochen", - "render.image_completed": "Bild bereit zum Export", - "render.image_failed": "Rendering fehlgeschlagen", - "render.image_unknown": "Renderstatus nicht verfügbar", - "render.image_reduce": "Kleineres Bild oder einfachere Szene versuchen.", - "render.image_too_large": "Über dem Bildlimit: 4096 Pixel pro Seite und 4.194.304 Pixel insgesamt.", - "render.image_use_largest": "Größte Größe mit diesem Seitenverhältnis verwenden:", - "render.image_cancel": "Rendering abbrechen", - "render.image_stale": "Dieses Bild verwendet die Szene vor den nachfolgenden Änderungen.", - "render.image_start": "Rendering starten", - "render.image_overwrite": "Vorhandene Datei ersetzen", - "render.image_export": "PNG exportieren", - "cmd.render_preflight": "Renderanfrage prüfen", - "cmd.render_start": "Bild rendern", - "cmd.render_status": "Renderfortschritt", - "cmd.render_cancel": "Rendering abbrechen", - "cmd.render_export": "PNG exportieren", - "toolbar.image": "BILD", - "appearance.surface_response": "Oberflächenverhalten", - "appearance.pbr_opaque": "Opakes PBR", - "appearance.metallic": "Metallanteil", - "appearance.roughness": "Rauheit", - "appearance.dielectric_ior": "Brechungsindex des Dielektrikums", - "appearance.pbr_help": "Diese Oberfläche in Render oder einem Produkt-PNG ansehen. Keine Brechung oder Transmission.", - "render.opaque_preview_help": "Opakes PBR und einfache Farben; Transparenz durch Blending. Brechung, HDRI und finales Rendering sind noch nicht verfügbar.", - "render.opaque_image_summary": "Vorschau-PNG · opakes PBR · Transparenz durch Blending", - "UNTRIM": "TRIMMEN AUFHEBEN", - "Face": "Fläche", - "Holes": "Löcher", - "Holes (edges on them)": "Löcher (ihre Kanten)", - "In place (surfaces)": "An Ort und Stelle (Flächen)", - "None": "Keine", - "Picked": "Ausgewählte", - "Restore outer boundary": "Äußere Begrenzung wiederherstellen", - "RULED SURFACE": "REGELFLÄCHE", - "Mitre": "Gehrung", - "Reference face": "Referenzfläche", - "Round": "Rund", - "Type": "Typ", - "joint.one_component": "Diese Teile sind Körper einer Komponente: {bodies}. Ein Gelenk bewegt eine Komponente gegenüber einer anderen, daher braucht jedes Teil eine eigene Komponente.", - "joint.one_body": "Beide Auswahlen liegen auf {body}. Wählen Sie die zweite auf einem anderen Teil.", - "joint.from_bodies_hint": "Jeder ausgewählte Körper kommt in eine eigene neue Komponente und bleibt, wo er ist.", - "Circumference": "Umfang", - "Arc length": "Bogenlänge", - "Slot width": "Langlochbreite", - "Centre to centre": "Mitte zu Mitte", - "Overall length": "Gesamtlänge", - "Min": "Min", - "Max": "Max", - "Length": "Länge", - "Area": "Fläche", - "coupling.gear_1": "Zahnrad 1", - "coupling.gear_2": "Zahnrad 2", - "coupling.pinion": "Ritzel", - "coupling.rack": "Zahnstange", - "coupling.nut": "Mutter", - "coupling.radius_1": "Radius 1", - "coupling.radius_2": "Radius 2", - "coupling.internal": "Innenzahnrad", - "coupling.pitch": "Steigung", - "coupling.picked": "gewählt", - "coupling.not_round": "keine runde Fläche", - "coupling.gear_1_pick": "Zahnrad 1 (optional)", - "coupling.gear_2_pick": "Zahnrad 2 (optional)", - "coupling.pinion_pick": "Ritzel (optional)", - "coupling.needs_turns": "braucht zwei Gelenke, die sich drehen", - "coupling.needs_turn_and_slide": "braucht ein Gelenk, das sich dreht, und eines, das gleitet" + "update.show": "Update auf {version} anzeigen", + "update.skip": "Diese Version überspringen", + "update.system_hint": "Diese Installation ist ein {kind}. Aktualisieren mit:", + "update.title": "Update verfügbar", + "update.up_to_date": "SolidCraft ist aktuell.", + "update.update_now": "Jetzt aktualisieren", + "update.you_have": "Installiert ist {version}." } diff --git a/assets/locales/en.json b/assets/locales/en.json index 8971a167f..2230785bf 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -1,29 +1,286 @@ { - "settings.measure_axis_distances": "Show X/Y/Z distances", - "settings.measure_axis_distances_help": "Show world-axis component dimensions alongside the total distance while Measure is open.", - "Export Current View as DXF": "Export Current View as DXF", - "Export Current View as DXF…": "Export Current View as DXF…", - "Hidden edges": "Hidden edges", - "Do not export hidden edges": "Do not export hidden edges", - "Export hidden edges as dashed lines": "Export hidden edges as dashed lines", - "Projection": "Projection", - "Current perspective view": "Current perspective view", - "Current orthographic view (1:1 mm)": "Current orthographic view (1:1 mm)", - "Visible bodies only. Curves use line segments (0.01 mm tolerance).": "Visible bodies only. Curves use line segments (0.01 mm tolerance).", - "Turn off section analysis before exporting the view.": "Turn off section analysis before exporting the view.", - "No visible bodies to export.": "No visible bodies to export.", - "Export DXF…": "Export DXF…", - "Send your report on GitHub": "Send your report on GitHub", + "0 turns it off": "0 turns it off", "1. Open GitHub draft below, then paste the report copied to your clipboard.": "1. Open GitHub draft below, then paste the report copied to your clipboard.", "1. Open GitHub draft below. Your title and report will be filled in.": "1. Open GitHub draft below. Your title and report will be filled in.", "2. Attach your screenshot: copy and paste it, or save and upload the PNG.": "2. Attach your screenshot: copy and paste it, or save and upload the PNG.", "3. Click Submit new issue on GitHub to send your report.": "3. Click Submit new issue on GitHub to send your report.", - "nav.touchpad.label": "Touchpad", - "nav.touchpad.help": "Hold Shift and move the pointer to pan; hold Alt/Option and move it to orbit. No mouse button is needed. Vertical scroll zooms.", - "nav.touchpad.orbit": "Orbit (hold Alt/Option and move; no mouse button)", - "nav.touchpad.pan": "Pan (hold Shift and move; no mouse button)", - "nav.touchpad.zoom": "Zoom (vertical scroll or pinch)", - "nav.touchpad.scroll": "Touchpad uses vertical scroll to zoom. Your two-finger pan setting is kept for other presets.", + "A new configuration, a copy of the active one": "A new configuration, a copy of the active one", + "AI": "AI", + "About SolidCraft": "About SolidCraft", + "Active": "Active", + "Active rule": "Active rule", + "Add": "Add", + "Add Key": "Add Key", + "Add Mid Radius": "Add Mid Radius", + "Add Row": "Add Row", + "Add condition": "Add condition", + "Alignment": "Alignment", + "All Sketch Points": "All Sketch Points", + "All open designs": "All open designs", + "Allowed expressions, separated by semicolons": "Allowed expressions, separated by semicolons", + "Also deletes": "Also deletes", + "Angle 2": "Angle 2", + "Animate": "Animate", + "Appearance name": "Appearance name", + "Applied Radius": "Applied Radius", + "Apply To": "Apply To", + "Apply to selection": "Apply to selection", + "Arc length": "Arc length", + "Area": "Area", + "Attachment": "Attachment", + "BROWSER": "BROWSER", + "Bend Line Position": "Bend Line Position", + "Bend Position": "Bend Position", + "Bend Radius": "Bend Radius", + "Bends": "Bends", + "Body": "Body", + "Bounding box": "Bounding box", + "CSV or JSON: updates existing parameters, adds new ones": "CSV or JSON: updates existing parameters, adds new ones", + "Capture All Positions": "Capture All Positions", + "Catch Direction": "Catch Direction", + "Cells": "Cells", + "Center X": "Center X", + "Center Y": "Center Y", + "Center of mass": "Center of mass", + "Centre to centre": "Centre to centre", + "Chamfer Type": "Chamfer Type", + "Check collisions": "Check collisions", + "Checked": "Checked", + "Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.": "Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.", + "Circumference": "Circumference", + "Close draft": "Close draft", + "Collisions": "Collisions", + "Colour": "Colour", + "Component1": "Component1", + "Configuration": "Configuration", + "Configuration rules": "Configuration rules", + "Construction": "Construction", + "Contact": "Contact", + "Copy Error Message": "Copy Error Message", + "Copy Warning Message": "Copy Warning Message", + "Copy all licences": "Copy all licences", + "Copy diagnostic information": "Copy diagnostic information", + "Copy report": "Copy report", + "Copy screenshot": "Copy screenshot", + "Corner Relief": "Corner Relief", + "Corner Relief Shape": "Corner Relief Shape", + "Counterbore depth": "Counterbore depth", + "Countersink angle": "Countersink angle", + "Create Issue — review draft": "Create Issue — review draft", + "Cube": "Cube", + "Current orthographic view (1:1 mm)": "Current orthographic view (1:1 mm)", + "Current perspective view": "Current perspective view", + "Customize Toolbar": "Customize Toolbar", + "Delete all": "Delete all", + "Delete rule": "Delete rule", + "Delete the row": "Delete the row", + "Delete the set": "Delete the set", + "Delete this parameter": "Delete this parameter", + "Density": "Density", + "Designs you open or save appear here.": "Designs you open or save appear here.", + "Determined by To Object. Choose Angle to edit the angular extent.": "Determined by To Object. Choose Angle to edit the angular extent.", + "Discard": "Discard", + "Do not export hidden edges": "Do not export hidden edges", + "Double-click to rename": "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": "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": "Drive Joint", + "Edges": "Edges", + "Edit Profile Sketch": "Edit Profile Sketch", + "Enable rule": "Enable rule", + "Enabled": "Enabled", + "Explode": "Explode", + "Export Current View as DXF": "Export Current View as DXF", + "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", + "Extents": "Extents", + "Face": "Face", + "Face attachment lost": "Face attachment lost", + "Faces": "Faces", + "Faces / edges / vertices": "Faces / edges / vertices", + "Favourite": "Favourite", + "Files from many CAD programs have Y up, so they open lying on their back here (Z up).": "Files from many CAD programs have Y up, so they open lying on their back here (Z up).", + "Filter": "Filter", + "Find in Browser": "Find in Browser", + "Flat": "Flat", + "Flat size": "Flat size", + "Follow camera (Look At sketches)": "Follow camera (Look At sketches)", + "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", + "Holes": "Holes", + "Holes (edges on them)": "Holes (edges on them)", + "Home view": "Home view", + "In This Design": "In This Design", + "In place (surfaces)": "In place (surfaces)", + "Inside": "Inside", + "Interferes": "Interferes", + "Issue title": "Issue title", + "Joint Origin1": "Joint Origin1", + "Keep Tools": "Keep Tools", + "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.", + "Length": "Length", + "Length units": "Length units", + "Letter Spacing": "Letter Spacing", + "Library": "Library", + "Line Spacing": "Line Spacing", + "Loop": "Loop", + "Margin": "Margin", + "Mass": "Mass", + "Material": "Material", + "Max": "Max", + "Mid Radius": "Mid Radius", + "Middle double-click": "Middle double-click", + "Min": "Min", + "Mitre": "Mitre", + "Modeled": "Modeled", + "More toolbar panels": "More toolbar panels", + "Motion": "Motion", + "Move Type": "Move Type", + "Move earlier": "Move earlier", + "Move later": "Move later", + "Name": "Name", + "No crash reports.": "No crash reports.", + "No matching appearances": "No matching appearances", + "No visible bodies to export.": "No visible bodies to export.", + "None": "None", + "Not available yet": "Not available yet", + "Notch": "Notch", + "Opacity": "Opacity", + "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", + "Outside": "Outside", + "Overall length": "Overall length", + "Parameter values": "Parameter values", + "Path": "Path", + "Per Edge": "Per Edge", + "Pick the tool bodies": "Pick the tool bodies", + "Picked": "Picked", + "Place at the origin instead": "Place at the origin instead", + "Playback": "Playback", + "Position": "Position", + "Position (0 to 1)": "Position (0 to 1)", + "Position along the edge, 0 at the start end, 1 at the other": "Position along the edge, 0 at the start end, 1 at the other", + "Preview Row": "Preview Row", + "Preview leaves the current design unchanged.": "Preview leaves the current design unchanged.", + "Profiles/Curves": "Profiles/Curves", + "Projection": "Projection", + "RECENT": "RECENT", + "RULED SURFACE": "RULED SURFACE", + "Radius Fit": "Radius Fit", + "Ratio": "Ratio", + "Reattach selected face": "Reattach selected face", + "Recover": "Recover", + "Recover unsaved design?": "Recover unsaved design?", + "Rectangular": "Rectangular", + "Reference face": "Reference face", + "Remove Tools": "Remove Tools", + "Remove from list": "Remove from list", + "Remove override": "Remove override", + "Remove private design details or paths before sharing.": "Remove private design details or paths before sharing.", + "Remove screenshot": "Remove screenshot", + "Remove the column": "Remove the column", + "Remove the track": "Remove the track", + "Remove this point": "Remove this point", + "Report a bug — review a screenshot and open a GitHub draft": "Report a bug — review a screenshot and open a GitHub draft", + "Reset Toolbar": "Reset Toolbar", + "Restore outer boundary": "Restore outer boundary", + "Restore the inherited component or physical material appearance": "Restore the inherited component or physical material appearance", + "Result": "Result", + "Retake screenshot": "Retake screenshot", + "Reverse": "Reverse", + "Reverse Direction": "Reverse Direction", + "Revert": "Revert", + "Revert All Positions": "Revert All Positions", + "Revert Position": "Revert Position", + "Review the report and screenshot before opening GitHub.": "Review the report and screenshot before opening GitHub.", + "Rim Edge": "Rim Edge", + "Roll History Marker Here": "Roll History Marker Here", + "Round": "Round", + "Rule": "Rule", + "Save Rule": "Save Rule", + "Saved preview. Geometry is being checked before editing.": "Saved preview. Geometry is being checked before editing.", + "Scale factor": "Scale factor", + "Search": "Search", + "Search commands": "Search commands", + "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).": "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).", + "Select bodies (a face picks its body)": "Select bodies (a face picks its body)", + "Select bodies or faces instead": "Select bodies or faces instead", + "Selection filter": "Selection filter", + "Semantic faces share their appearance across instances.": "Semantic faces share their appearance across instances.", + "Send your report on GitHub": "Send your report on GitHub", + "Shape": "Shape", + "Show Agent Cursor": "Show Agent Cursor", + "Show in folder": "Show in folder", + "Show the pointer an AI agent moves (#35)": "Show the pointer an AI agent moves (#35)", + "Signed axes": "Signed axes", + "Size": "Size", + "Sketch constraints": "Sketch constraints", + "Sketch curves": "Sketch curves", + "Sketch dimensions": "Sketch dimensions", + "Sketch geometry and profiles": "Sketch geometry and profiles", + "Sketch plane has no body-face attachment.": "Sketch plane has no body-face attachment.", + "Sketch points": "Sketch points", + "Slot width": "Slot width", + "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft closed before these designs were saved. Their last autosave can be opened.", + "Speed": "Speed", + "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?", + "Step": "Step", + "Steps": "Steps", + "Style": "Style", + "Suppressed": "Suppressed", + "Swap Ends": "Swap Ends", + "Tangent Chain": "Tangent Chain", + "Tear": "Tear", + "The dashed sketch is a saved plane guide. Select a new face to repair the attachment.": "The dashed sketch is a saved plane guide. Select a new face to repair the attachment.", + "The saved author occurrence is missing. Select a valid author placement before rebinding.": "The saved author occurrence is missing. Select a valid author placement before rebinding.", + "Then": "Then", + "These features will be deleted:": "These features will be deleted:", + "These features will fail:": "These features will fail:", + "Thickness Outside": "Thickness Outside", + "Thin": "Thin", + "Thin Extrude": "Thin Extrude", + "This child is shared. Deleting it removes it from every copy of its parent.": "This child is shared. Deleting it removes it from every copy of its parent.", + "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", + "Tolerance": "Tolerance", + "Turn off section analysis before exporting the view.": "Turn off section analysis before exporting the view.", + "Type": "Type", + "UNTRIM": "UNTRIM", + "Updating the preview": "Updating the preview", + "Use active author placement": "Use active author placement", + "Use fixed plane": "Use fixed plane", + "Use saved fixed plane": "Use saved fixed plane", + "Use selected face as fixed plane": "Use selected face as fixed plane", + "VIEW": "VIEW", + "Value": "Value", + "Vertices": "Vertices", + "View navigator": "View navigator", + "Visible bodies only. Curves use line segments (0.01 mm tolerance).": "Visible bodies only. Curves use line segments (0.01 mm tolerance).", + "Volume": "Volume", + "Wall": "Wall", + "Wall Location": "Wall Location", + "Wall Thickness": "Wall Thickness", + "When": "When", + "Width": "Width", + "Will fail": "Will fail", + "angle, height": "angle, height", + "appearance.dielectric_ior": "Dielectric IOR", + "appearance.metallic": "Metallic", + "appearance.pbr_help": "View this surface in Render or a product PNG. No refraction or transmission.", + "appearance.pbr_opaque": "Opaque PBR", + "appearance.roughness": "Roughness", + "appearance.surface_response": "Surface response", "browser.body_name": "Body{number}", "browser.component_name": "Component{number}", "browser.parameters": "Parameters ({count})", @@ -50,7 +307,6 @@ "cmd.component_capture_position": "Capture Position", "cmd.component_create": "New Component", "cmd.component_delete": "Delete Component", - "cmd.component_unlock": "Unlock Contents", "cmd.component_from_bodies": "Create Components from Bodies", "cmd.component_insert_design": "Insert Design", "cmd.component_links": "List Links", @@ -61,6 +317,7 @@ "cmd.component_properties": "Component Physical Properties", "cmd.component_rename": "Rename Component", "cmd.component_revert_position": "Revert Position", + "cmd.component_unlock": "Unlock Contents", "cmd.component_update_links": "Update Links", "cmd.config_activate": "Activate Configuration", "cmd.config_column": "Configuration Column", @@ -102,10 +359,10 @@ "cmd.doc_recovery_discard": "Discard Recovered Design", "cmd.doc_recovery_list": "Recoverable Designs", "cmd.document_inspect": "Inspect Design", - "cmd.document_units": "Change Design Units", "cmd.document_metadata": "Design Properties", - "cmd.document_metadata_set": "Change Design Properties", "cmd.document_metadata_remove": "Remove Design Property", + "cmd.document_metadata_set": "Change Design Properties", + "cmd.document_units": "Change Design Units", "cmd.edit_checkpoint": "Checkpoint", "cmd.edit_restore_checkpoint": "Restore Checkpoint", "cmd.engine_commands": "List Commands", @@ -123,6 +380,7 @@ "cmd.inspect_accessibility": "Accessibility Analysis", "cmd.inspect_center_of_mass": "Center of Mass", "cmd.inspect_compare": "Compare Bodies", + "cmd.inspect_continuity": "Continuity Analysis", "cmd.inspect_curvature_comb": "Curvature Comb Analysis", "cmd.inspect_curvature_map": "Curvature Map Analysis", "cmd.inspect_draft": "Draft Analysis", @@ -136,20 +394,25 @@ "cmd.joint_delete": "Delete Joint", "cmd.joint_drive": "Drive Joints", "cmd.joint_edit": "Edit Joint", + "cmd.joint_gear": "Gear", "cmd.joint_limits": "Joint Limits", "cmd.joint_list": "List Joints", "cmd.joint_motion_link": "Motion Link", - "cmd.joint_gear": "Gear", - "cmd.joint_rack_pinion": "Rack and Pinion", - "cmd.joint_screw": "Screw", "cmd.joint_origin": "Joint Origin", + "cmd.joint_rack_pinion": "Rack and Pinion", "cmd.joint_rigid_group": "Rigid Group", + "cmd.joint_screw": "Screw", "cmd.joint_solve": "Solve Joints", + "cmd.library_apply": "Apply Local Library Entry", + "cmd.library_export": "Export Design Library", + "cmd.library_inspect": "Inspect Local Library", "cmd.material_assign": "Physical Material", "cmd.material_create": "New Physical Material", "cmd.material_delete": "Delete Physical Material", "cmd.material_edit": "Edit Physical Material", "cmd.material_list": "List Materials", + "cmd.material_properties_directional": "Directional Elastic Modulus", + "cmd.material_properties_validate": "Validate Physical Material Data", "cmd.mesh_convert": "Convert Mesh", "cmd.model_edges": "List Edges", "cmd.model_faces": "List Faces", @@ -170,10 +433,10 @@ "cmd.parameters_delete": "Delete Parameter", "cmd.parameters_export": "Export Parameters", "cmd.parameters_favorite": "Favourite Parameter", - "cmd.parameters_move": "Move Parameter", "cmd.parameters_graph": "Parameter Graph", "cmd.parameters_import": "Import Parameters", "cmd.parameters_list": "List Parameters", + "cmd.parameters_move": "Move Parameter", "cmd.parameters_rename": "Rename Parameter", "cmd.parameters_users": "Parameter Users", "cmd.parts_fastener": "Insert Fastener", @@ -187,6 +450,16 @@ "cmd.plastic_rest": "Rest", "cmd.plastic_rules": "List Plastic Rules", "cmd.plastic_snap_fit": "Snap Fit", + "cmd.render_backends": "Render Backends", + "cmd.render_cancel": "Cancel Render", + "cmd.render_export": "Export Render Image", + "cmd.render_preflight": "Check Render Request", + "cmd.render_scene": "Inspect Render Scene", + "cmd.render_settings_apply": "Apply Render Camera", + "cmd.render_settings_get": "Render Settings", + "cmd.render_settings_set": "Save Render Settings", + "cmd.render_start": "Render Image", + "cmd.render_status": "Render Progress", "cmd.select_clear": "Clear Selection", "cmd.sheet_convert": "Convert to Sheet Metal", "cmd.sheet_export_bend_table": "Export Bend Table", @@ -282,22 +555,21 @@ "cmd.solid_rib": "Rib", "cmd.solid_split_face": "Split Face", "cmd.solid_web": "Web", - "cmd.surface_patch": "Patch", - "cmd.surface_stitch": "Stitch", - "cmd.surface_thicken": "Thicken", - "cmd.surface_extrude": "Surface Extrude", - "cmd.surface_revolve": "Surface Revolve", - "cmd.surface_sweep": "Surface Sweep", - "cmd.surface_loft": "Surface Loft", - "cmd.surface_ruled": "Ruled Surface", - "cmd.surface_boundary": "Boundary Surface", - "cmd.surface_offset": "Offset Surface", "cmd.surface_blend": "Blend Surface", + "cmd.surface_boundary": "Boundary Surface", + "cmd.surface_extrude": "Surface Extrude", "cmd.surface_fillet": "Surface Fillet", - "cmd.surface_untrim": "Untrim", - "cmd.surface_unstitch": "Unstitch", + "cmd.surface_loft": "Surface Loft", + "cmd.surface_offset": "Offset Surface", + "cmd.surface_patch": "Patch", "cmd.surface_reverse_normal": "Reverse Normal", - "cmd.inspect_continuity": "Continuity Analysis", + "cmd.surface_revolve": "Surface Revolve", + "cmd.surface_ruled": "Ruled Surface", + "cmd.surface_stitch": "Stitch", + "cmd.surface_sweep": "Surface Sweep", + "cmd.surface_thicken": "Thicken", + "cmd.surface_unstitch": "Unstitch", + "cmd.surface_untrim": "Untrim", "cmd.timeline_add": "Add Recorded Feature", "cmd.timeline_compute_all": "Compute All", "cmd.timeline_copy": "Copy Features", @@ -314,18 +586,42 @@ "cmd.view_apply": "Restore Named View", "cmd.view_delete": "Delete Named View", "cmd.view_list": "List Named Views", + "cmd.view_navigate": "Navigate View", "cmd.view_rename": "Rename Named View", "cmd.view_save": "New Named View", + "command name": "command name", + "coupling.gear_1": "Gear 1", + "coupling.gear_1_pick": "Gear 1 (optional)", + "coupling.gear_2": "Gear 2", + "coupling.gear_2_pick": "Gear 2 (optional)", + "coupling.internal": "Internal gear", + "coupling.needs_turn_and_slide": "needs a joint that turns and one that slides", + "coupling.needs_turns": "needs two joints that turn", + "coupling.not_round": "not a round face", + "coupling.nut": "Nut", + "coupling.picked": "picked", + "coupling.pinion": "Pinion", + "coupling.pinion_pick": "Pinion (optional)", + "coupling.pitch": "Pitch", + "coupling.rack": "Rack", + "coupling.radius_1": "Radius 1", + "coupling.radius_2": "Radius 2", "dialog.computing": "Computing… {seconds} s", "dialog.custom_axis": "↖ Custom Axis", "dialog.edit_title": "EDIT {title}", "dialog.select": "↖ Select", "dialog.selected_count": "↖ {count} selected", - "dialog.step": "Step", - "dialog.selection_step": "{step} of {total}: Select {input}", "dialog.selection_guidance": "Select an input to change it. Click selected objects to remove them; Ctrl/Cmd-click also toggles them. Review the preview, then press OK.", + "dialog.selection_step": "{step} of {total}: Select {input}", + "dialog.step": "Step", "document.save_changes": "Save changes to {name}?", "document.unsaved_changes": "{name} has unsaved changes. If you don't save, they are lost.", + "drive.stopped_by_contact": "Stopped at {value}: {a} would pass through {b}", + "drive.stopped_by_loop": "Stopped at {value}: the loop through {joint} can't close any further", + "drive.unconnected": "Moves nothing: {part} is not connected to anything grounded", + "expression, e.g. 25 mm": "expression, e.g. 25 mm", + "fits the face, e.g. M8": "fits the face, e.g. M8", + "from the rule": "from the rule", "home.documentation": "Documentation", "home.in_this_browser": "in this browser", "home.missing": "missing", @@ -339,6 +635,76 @@ "home.report_issue": "Report an Issue", "home.samples": "Samples", "home.whats_new": "What's new", + "install.button_tip": "Install SolidCraft as an app: it opens in its own window and works offline", + "install.dock_1": "Choose File › Add to Dock.", + "install.dock_2": "Click Add.", + "install.dock_after": "SolidCraft then opens in its own window from the Dock, and works offline.", + "install.done": "Done", + "install.home_screen_1": "Tap Share (in the … menu if it isn't on the toolbar).", + "install.home_screen_2": "Choose Add to Home Screen.", + "install.home_screen_3": "Tap Add.", + "install.home_screen_after": "SolidCraft then opens from its icon on the Home Screen, without Safari's toolbars, and works offline.", + "install.menu": "Install app…", + "install.steps_intro": "Safari installs web apps from its own menus:", + "install.title": "Install SolidCraft", + "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.", + "nav.touchpad.help": "Hold Shift and move the pointer to pan; hold Alt/Option and move it to orbit. No mouse button is needed. Vertical scroll zooms.", + "nav.touchpad.label": "Touchpad", + "nav.touchpad.orbit": "Orbit (hold Alt/Option and move; no mouse button)", + "nav.touchpad.pan": "Pan (hold Shift and move; no mouse button)", + "nav.touchpad.scroll": "Touchpad uses vertical scroll to zoom. Your two-finger pan setting is kept for other presets.", + "nav.touchpad.zoom": "Zoom (vertical scroll or pinch)", + "needs two joints": "needs two joints", + "new configuration": "new configuration", + "new name": "new name", + "new parameter": "new parameter", + "no interference": "no interference", + "no joint that moves yet": "no joint that moves yet", + "no picture": "no picture", + "pick a hole to seat it, or OK places it at the origin": "pick a hole to seat it, or OK places it at the origin", + "pick one or two vertices, edges or faces": "pick one or two vertices, edges or faces", + "render.background": "Scene background", + "render.fit": "Fit Product", + "render.image_cancel": "Cancel Render", + "render.image_cancelled": "Render cancelled", + "render.image_cancelling": "Cancelling", + "render.image_check": "Check Render Request", + "render.image_completed": "Image ready to export", + "render.image_encoding": "Encoding PNG", + "render.image_export": "Export PNG", + "render.image_failed": "Render failed", + "render.image_height": "Height", + "render.image_help": "CPU preview image · PNG · approximate transparency", + "render.image_overwrite": "Replace existing file", + "render.image_preparing": "Preparing image", + "render.image_queued": "Waiting to render", + "render.image_reduce": "Try a smaller image or simpler scene.", + "render.image_running": "Rendering image", + "render.image_stale": "This image uses the scene captured before subsequent changes.", + "render.image_start": "Start Render", + "render.image_supported": "Render request is supported; the queue and memory pool are checked again at start.", + "render.image_title": "Render Image", + "render.image_too_large": "Over the image limit: 4096 pixels per side and 4,194,304 pixels in all.", + "render.image_transparent": "Transparent background", + "render.image_unknown": "Render status unavailable", + "render.image_use_largest": "Use the largest size at this aspect:", + "render.image_width": "Width", + "render.navigation_help": "The camera moves as in Design (Preferences › Navigation). Save Setup records the current camera.", + "render.opaque_image_summary": "Preview PNG · opaque PBR · blended transparency", + "render.opaque_preview_help": "Opaque PBR and simple colors; blended transparency. Refraction, HDRI and final rendering are not available yet.", + "render.perspective": "Perspective camera", + "render.preview": "Integrated preview", + "render.preview_help": "Raster shading and blended transparency. Refraction, HDRI and final rendering are not available yet.", + "render.reload_settings": "Reload Saved Settings", + "render.restore_camera": "Restore Saved Camera", + "render.return_design": "Return to Design", + "render.save_setup": "Save Setup", + "render.setup_name": "Setup name", + "render.unavailable_preview": "This setup requests an unavailable preview profile.", + "render.unsaved": "Unsaved preview changes", + "render.use_preview": "Use Integrated Preview", "sample.bracket.about": "Base flange with edge flanges and a hem on a 2 mm rule", "sample.bracket.name": "Sheet Metal Bracket", "sample.enclosure.about": "Shelled box with a lip, screw bosses, a rest and a snap fit", @@ -351,14 +717,41 @@ "sample.plate.name": "Sample Plate", "sample.vents.about": "Slots in a rectangular pattern: rows, columns and pitch are parameters", "sample.vents.name": "Vent Plate", + "settings.display_quality_note": "Finer levels draw curved faces and edges smoother and take longer to mesh. Only the viewport changes, never the design or exports.", + "settings.measure_axis_distances": "Show X/Y/Z distances", + "settings.measure_axis_distances_help": "Show world-axis component dimensions alongside the total distance while Measure is open.", "settings.msaa_applies_on_restart": "Anti-aliasing applies the next time SolidCraft starts", "settings.msaa_reset": "{setting}: {requested}× isn't supported by this graphics device; it is now {reset}× (supported: {supported}).", "settings.msaa_unsupported": "Not supported by this graphics device", "settings.reset_intro": "These settings don't work on this computer and would keep SolidCraft from starting, so they were changed:", "settings.reset_title": "Settings were changed", + "settings.supersampling_note": "Draws the view at a higher resolution and filters it down: smoother edges, lines and grid on screens below 4K. It costs GPU time: about 2.25× the pixels at 1.5× and 4× at 2×.", "sketch.degrees_of_freedom": "{count} degrees of freedom", "sketch.draw_curves": "Draw as {linetype}", "sketch.make_selection": "Convert the selection to {linetype}", + "sketch_text.align_center": "Center", + "sketch_text.align_left": "Left", + "sketch_text.align_right": "Right", + "sketch_text.bold": "Bold", + "sketch_text.builtin_font": "{family} (built-in)", + "sketch_text.font_search": "Search fonts", + "sketch_text.italic": "Italic", + "sketch_text.loading_fonts": "Looking for installed fonts…", + "sketch_text.on_path": "The text follows its path: the curve places it", + "sketch_text.path_clear": "Take the text off its curve", + "sketch_text.path_hint": "A curve of the sketch the text follows: click here, then the curve", + "sketch_text.use_font_file": "Use the font file {path}", + "the parts library is not available": "the parts library is not available", + "timeline.group": "New Feature Folder", + "timeline.move_many": "Move Timeline Items", + "timeline.move_to_group": "Move Features to Folder", + "timeline.rename_group": "Rename Feature Folder", + "timeline.reorder_many": "Reorder Features", + "timeline.ungroup": "Remove Feature Folders", + "to the next face": "to the next face", + "toolbar.image": "IMAGE", + "toolbar.render": "RENDER", + "toolbar.render_scene": "SCENE", "ui.1_degree_of_freedom": "1 degree of freedom", "ui.3d_mouse_speed": "3D mouse speed", "ui.3d_mouse_windows": "3D mouse", @@ -366,89 +759,89 @@ "ui.about": "About", "ui.activate": "Activate", "ui.active_component": "Active component", - "ui.agent_cursor": "Agent cursor", - "ui.agent_cursor_speed": "Agent cursor speed", "ui.agent_chat": "Agent chat", - "ui.agent_chat_command": "Agent command", - "ui.agent_chat_desktop_only": "The agent chat needs the desktop app.", - "ui.agent_chat_side": "Agent chat side", - "ui.agent_chat_left": "Left", - "ui.agent_chat_right": "Right", - "ui.agent_chat_turn_limit": "Changes per message", - "ui.agent_chat_privacy_note": "SolidCraft sends nothing anywhere: the agent you run talks to its own service under your own account. SolidCraft never sees or stores a key or password.", - "ui.agent_chat_connect": "Connect", - "ui.agent_chat_stop": "Stop", - "ui.agent_chat_stop_tip": "Stop the agent and everything it started", - "ui.agent_chat_close": "Close", - "ui.agent_chat_minimize": "Minimise to a strip", - "ui.agent_chat_dock_left": "Dock on the left", - "ui.agent_chat_dock_right": "Dock on the right", - "ui.agent_chat_send": "Send", - "ui.agent_chat_cancel": "Cancel", - "ui.agent_chat_refresh": "Refresh", - "ui.agent_chat_pick": "Agent", - "ui.agent_chat_custom_hint": "Any program that speaks the Agent Client Protocol on stdin and stdout. No shell runs it.", - "ui.agent_chat_not_installed": "Not installed", - "ui.agent_chat_none_found": "No coding agent found. Install one of these, then press Refresh:", - "ui.agent_chat_detecting": "Looking for agents…", - "ui.agent_chat_signed_in": "signed in", - "ui.agent_chat_key_in_env": "key set", - "ui.agent_chat_not_signed_in": "not signed in", - "ui.agent_chat_state_off": "Not connected", - "ui.agent_chat_state_starting": "Starting…", - "ui.agent_chat_state_ready": "Ready", - "ui.agent_chat_state_busy": "Working…", - "ui.agent_chat_state_auth": "Sign-in needed", - "ui.agent_chat_state_exited": "Agent stopped", - "ui.agent_chat_changes_of": "{n}/{limit} changes", - "ui.agent_chat_auth_title": "Sign in to the agent", - "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.", - "ui.agent_chat_auth_none": "The agent offers no sign-in method here: sign in the way its own documentation describes.", - "ui.agent_chat_auth_terminal": "Run this in a terminal, then press Connect again:", - "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_retry": "I've signed in: connect again", - "ui.agent_chat_copy": "Copy", - "ui.agent_chat_permission": "The agent asks to run: {title}", + "ui.agent_chat_allow": "Allow", + "ui.agent_chat_allowed": "Allowed", "ui.agent_chat_answered": "Answer: {option}", "ui.agent_chat_approval": "Allow the agent to do this?", - "ui.agent_chat_allow": "Allow", - "ui.agent_chat_deny": "Deny", - "ui.agent_chat_allowed": "Allowed", - "ui.agent_chat_denied": "Denied", - "ui.agent_chat_changes": "Changes: {n}, one undo step", - "ui.agent_chat_undo_changes": "Undo these changes", - "ui.agent_chat_undone": "(undone)", - "ui.agent_chat_undo_label": "Agent chat: {message}", - "ui.agent_chat_limit": "The agent reached the limit of {limit} changes for one message. Send another message to let it go on.", - "ui.agent_chat_refused": "Not allowed for the agent: {reason}", - "ui.agent_chat_wait_turn": "The agent is still working on the last message: wait for it or press Cancel.", - "ui.agent_chat_placeholder": "Ask the agent to change the design…", "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_no_images": "This agent doesn't take pictures", - "ui.agent_chat_view_attached": "View attached", - "ui.agent_chat_no_cli": "solidcraft-cli was not found next to the app, so the agent can't reach the design.", - "ui.agent_chat_no_control": "The agent chat's endpoint did not start, so the agent can't reach the design.", + "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.", + "ui.agent_chat_auth_none": "The agent offers no sign-in method here: sign in the way its own documentation describes.", + "ui.agent_chat_auth_retry": "I've signed in: connect again", + "ui.agent_chat_auth_terminal": "Run this in a terminal, then press Connect again:", + "ui.agent_chat_auth_title": "Sign in to the agent", + "ui.agent_chat_cancel": "Cancel", + "ui.agent_chat_changes": "Changes: {n}, one undo step", + "ui.agent_chat_changes_of": "{n}/{limit} changes", + "ui.agent_chat_close": "Close", + "ui.agent_chat_command": "Agent command", + "ui.agent_chat_connect": "Connect", + "ui.agent_chat_copy": "Copy", + "ui.agent_chat_custom_hint": "Any program that speaks the Agent Client Protocol on stdin and stdout. No shell runs it.", + "ui.agent_chat_denied": "Denied", + "ui.agent_chat_deny": "Deny", + "ui.agent_chat_desktop_only": "The agent chat needs the desktop app.", + "ui.agent_chat_detecting": "Looking for agents…", + "ui.agent_chat_dock_left": "Dock on the left", + "ui.agent_chat_dock_right": "Dock on the right", "ui.agent_chat_exited": "The agent stopped.", "ui.agent_chat_failed_start": "The agent could not start: {error}", "ui.agent_chat_intro": "Chat with a coding agent you already use, or a model endpoint you choose. It works on the open design through SolidCraft's tools: its changes show as it makes them and undo as one step per message. What it may do without asking is set in Preferences > AI.", - "ui.agent_chat_privacy": "Nothing goes anywhere except to the agent you run, under your own account.", + "ui.agent_chat_key_in_env": "key set", + "ui.agent_chat_left": "Left", + "ui.agent_chat_limit": "The agent reached the limit of {limit} changes for one message. Send another message to let it go on.", + "ui.agent_chat_minimize": "Minimise to a strip", + "ui.agent_chat_no_cli": "solidcraft-cli was not found next to the app, so the agent can't reach the design.", + "ui.agent_chat_no_control": "The agent chat's endpoint did not start, so the agent can't reach the design.", + "ui.agent_chat_no_images": "This agent doesn't take pictures", + "ui.agent_chat_none_found": "No coding agent found. Install one of these, then press Refresh:", "ui.agent_chat_none_found_short": "No agent found", + "ui.agent_chat_not_installed": "Not installed", + "ui.agent_chat_not_signed_in": "not signed in", + "ui.agent_chat_permission": "The agent asks to run: {title}", + "ui.agent_chat_pick": "Agent", + "ui.agent_chat_placeholder": "Ask the agent to change the design…", + "ui.agent_chat_privacy": "Nothing goes anywhere except to the agent you run, under your own account.", + "ui.agent_chat_privacy_note": "SolidCraft sends nothing anywhere: the agent you run talks to its own service under your own account. SolidCraft never sees or stores a key or password.", + "ui.agent_chat_refresh": "Refresh", + "ui.agent_chat_refused": "Not allowed for the agent: {reason}", + "ui.agent_chat_right": "Right", + "ui.agent_chat_send": "Send", + "ui.agent_chat_side": "Agent chat side", + "ui.agent_chat_signed_in": "signed in", + "ui.agent_chat_state_auth": "Sign-in needed", + "ui.agent_chat_state_busy": "Working…", + "ui.agent_chat_state_exited": "Agent stopped", + "ui.agent_chat_state_off": "Not connected", + "ui.agent_chat_state_ready": "Ready", + "ui.agent_chat_state_starting": "Starting…", + "ui.agent_chat_stop": "Stop", + "ui.agent_chat_stop_tip": "Stop the agent and everything it started", + "ui.agent_chat_turn_limit": "Changes per message", + "ui.agent_chat_undo_changes": "Undo these changes", + "ui.agent_chat_undo_label": "Agent chat: {message}", + "ui.agent_chat_undone": "(undone)", + "ui.agent_chat_view_attached": "View attached", + "ui.agent_chat_wait_turn": "The agent is still working on the last message: wait for it or press Cancel.", + "ui.agent_cursor": "Agent cursor", + "ui.agent_cursor_speed": "Agent cursor speed", "ui.ai_add": "Add", "ui.ai_add_agent": "Add agent…", "ui.ai_add_agent_title": "Add agent", "ui.ai_add_api": "OpenAI-compatible API", "ui.ai_add_custom": "Custom command", - "ui.ai_added": "added", "ui.ai_add_installed": "Installed agent", "ui.ai_add_installed_note": "An entry of your own for an installed agent, for example with other arguments. Installed agents are listed by themselves.", + "ui.ai_added": "added", "ui.ai_agent_mode_tip": "The agent's own mode: its own tools (shell, file edits) follow it. SolidCraft's tools follow the permissions in Preferences > AI.", "ui.ai_agents": "Agents", "ui.ai_always_allow": "Always allow", + "ui.ai_always_allow_tip": "Allow {tool} for this agent from now on, without asking", "ui.ai_always_allowed": "Always allowed", "ui.ai_always_allowed_none": "Nothing is always allowed yet. \"Always allow\" answers you give in the chat are listed here.", - "ui.ai_always_allow_tip": "Allow {tool} for this agent from now on, without asking", "ui.ai_auto_allowed": "Auto-allowed: {title} ({why})", "ui.ai_auto_mode": "your permission setting", "ui.ai_auto_ours": "SolidCraft checks its own tools itself", @@ -463,10 +856,10 @@ "ui.ai_http_key": "the endpoint refused the key: check it in Preferences > AI", "ui.ai_http_not_found": "no such endpoint or model: check the base URL and the model name", "ui.ai_key": "API key", - "ui.ai_keychain_error": "The system keychain refused: {error}", "ui.ai_key_hint": "optional; kept in the system keychain", "ui.ai_key_needs_https": "A key is only sent over HTTPS, or to this computer.", "ui.ai_key_note": "Stored in the system keychain, never in SolidCraft's settings. Leave it empty for a local server.", + "ui.ai_keychain_error": "The system keychain refused: {error}", "ui.ai_mode_all": "Allow everything", "ui.ai_mode_all_note": "Nothing asks first. Crash reports stay off limits and the folder limits still apply.", "ui.ai_mode_all_warning": "The agent can save, overwrite, export and replace your design without asking. Use this only with an agent you trust, on designs you have saved.", @@ -497,36 +890,26 @@ "ui.ai_test_acp_ok": "Answers: {agent}", "ui.ai_test_acp_tip": "Starts the agent briefly and asks it for a session; ends it again", "ui.ai_test_api_tip": "Asks the endpoint for its models", - "ui.ai_testing": "Testing…", "ui.ai_test_no_model": "Reached: {count} models, but not {model}", "ui.ai_test_ok": "Reached: {count} models", - "ui.ai_toolbar_button": "Show button in toolbar", - "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_testing": "Testing…", "ui.ai_tool_done": "done", "ui.ai_tool_failed": "failed", "ui.ai_tool_running": "running", "ui.ai_tool_unfold": "Click to show what it returned", "ui.ai_tool_waiting": "waiting", + "ui.ai_toolbar_button": "Show button in toolbar", + "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", - "AI": "AI", "ui.all": "All", "ui.analysis": "Analysis", "ui.angle": "Angle", "ui.angle_decimals": "Angle decimals", + "ui.animateJoint": "Animate Joint", "ui.animate_view_changes": "Animate view changes", "ui.animation": "Animation", "ui.animation_speed": "Animation speed", "ui.anti_aliasing": "Anti-aliasing", - "ui.supersampling": "Supersampling (SSAA)", - "ui.supersampling_off": "Off (1×)", - "ui.supersampling_adaptive": "Only when the view is still", - "settings.supersampling_note": "Draws the view at a higher resolution and filters it down: smoother edges, lines and grid on screens below 4K. It costs GPU time: about 2.25× the pixels at 1.5× and 4× at 2×.", - "ui.display_quality": "Display quality", - "ui.display_quality_coarse": "Coarse", - "ui.display_quality_normal": "Normal", - "ui.display_quality_fine": "Fine", - "ui.display_quality_ultra": "Ultra", - "settings.display_quality_note": "Finer levels draw curved faces and edges smoother and take longer to mesh. Only the viewport changes, never the design or exports.", "ui.apply": "Apply", "ui.arc": "Arc", "ui.assemble": "Assemble", @@ -534,9 +917,11 @@ "ui.axes": "Axes", "ui.axis": "Axis", "ui.base_point": "Base point", + "ui.blocked": "Blocked", "ui.bodies": "Bodies", "ui.box": "Box", "ui.break": "Break", + "ui.calibrate": "Calibrate", "ui.cancel": "Cancel", "ui.canvases": "Canvases", "ui.center": "Center", @@ -546,8 +931,6 @@ "ui.chamfer_type": "Chamfer Type", "ui.change_workspace": "Change workspace", "ui.chord_length": "Chord Length", - "ui.curvature_g2": "Curvature (G2)", - "ui.equivalent_radius": "Equivalent Radius", "ui.circle": "Circle", "ui.circular_pattern": "Circular Pattern", "ui.clear": "Clear", @@ -556,28 +939,6 @@ "ui.click_selects_whole_bodies": "Click selects whole bodies", "ui.click_then_press_key": "Click, then press the new key", "ui.close": "Close", - "ui.material_review.title": "Review Physical Material Data", - "ui.material_review.scope": "Candidate only: not assigned or saved. Numerical validation is not engineering certification.", - "ui.material_review.input": "Paste a schema-1 material card (JSON)", - "ui.material_review.review": "Review card", - "ui.material_review.limit": "The card exceeds the 256 KiB input limit.", - "ui.material_review.unknown": "Unknown", - "ui.material_review.properties": "Properties", - "ui.material_review.conditions": "Stated conditions", - "ui.material_review.source": "Source", - "ui.material_review.axes": "Material-local axes; no body orientation is assigned.", - "ui.material_review.derived": "Derived isotropic moduli", - "ui.material_review.claims": "Sources and licences are unverified claims. Missing values remain unknown.", - "ui.material_review.density": "Density", - "ui.material_review.elasticity": "Elasticity", - "ui.material_review.tensile_strength": "Tensile strength", - "ui.material_review.compressive_strength": "Compressive strength", - "ui.material_review.yield_strength": "Yield strength", - "ui.material_review.shear_strength": "Shear strength", - "ui.material_review.thermal_conductivity": "Thermal conductivity", - "ui.material_review.thermal_expansion": "Thermal expansion", - "ui.material_review.specific_heat": "Specific heat", - "ui.material_review.moisture_unit": "kg water / kg dry material", "ui.coil": "Coil", "ui.coincident": "Coincident", "ui.collapse": "Collapse", @@ -599,6 +960,8 @@ "ui.colour_vision_tritan_tip": "For a weak or missing blue sense", "ui.combine": "Combine", "ui.coming_later": "coming later", + "ui.command_done": "{command} done", + "ui.command_palette_hint": "Type a command, e.g. {example} — or press S to search", "ui.concentric": "Concentric", "ui.configurations": "Configurations", "ui.conic_curve": "Conic Curve", @@ -617,7 +980,11 @@ "ui.create_sketch": "Create Sketch", "ui.current": "current", "ui.curvature": "Curvature", + "ui.curvature_g2": "Curvature (G2)", "ui.curves": "Curves", + "ui.custom_program": "Custom…", + "ui.custom_program_tip": "Choose a slicer program to add to the list", + "ui.customizeToolbar": "Customize Toolbar…", "ui.cut": "Cut", "ui.cylinder": "Cylinder", "ui.dark": "Dark", @@ -626,9 +993,25 @@ "ui.delete": "Delete", "ui.depth": "Depth", "ui.design": "Design", + "ui.design_properties.author": "Author", + "ui.design_properties.description": "Description", + "ui.design_properties.exports": "STEP, IGES and 3MF exports carry these where the format has a place for them.", + "ui.design_properties.license": "License", + "ui.design_properties.not_text": "Saved as something other than text; typing here replaces it.", + "ui.design_properties.organization": "Organization", + "ui.design_properties.others": "Other tools' data", + "ui.design_properties.others_note": "Kept in the design as it is and never exported.", + "ui.design_properties.part_number": "Part number", + "ui.design_properties.project": "Project", + "ui.design_properties.revision": "Revision", "ui.diameter": "Diameter", "ui.dimension": "Dimension", "ui.direction": "Direction", + "ui.display_quality": "Display quality", + "ui.display_quality_coarse": "Coarse", + "ui.display_quality_fine": "Fine", + "ui.display_quality_normal": "Normal", + "ui.display_quality_ultra": "Ultra", "ui.distance": "Distance", "ui.distance_1": "Distance 1", "ui.distance_2": "Distance 2", @@ -638,12 +1021,16 @@ "ui.drawing": "Drawing", "ui.drill_point": "Drill Point", "ui.edit": "Edit", + "ui.editJointLimits": "Edit Joint Limits", "ui.edit_section_analysis": "Edit Section Analysis", "ui.ellipse": "Ellipse", "ui.end_radius": "End Radius", + "ui.end_scale": "End Scale", "ui.entities": "Entities", "ui.equal": "Equal", + "ui.equivalent_radius": "Equivalent Radius", "ui.expand": "Expand", + "ui.exportDxf": "Export DXF…", "ui.export_ellipsis": "Export...", "ui.export_ellipsis_keymap": "Export…", "ui.export_keymap_tip": "Keys, S box favourites and the toolbar, as a file", @@ -657,15 +1044,20 @@ "ui.file": "File", "ui.fillet": "Fillet", "ui.filter_commands_or_keys": "Filter commands or keys", + "ui.findInTimeline": "Find in Timeline", + "ui.findInWindow": "Find in Window", "ui.finish_sketch": "Finish Sketch", + "ui.fit": "Fit", "ui.fix_unfix": "Fix/Unfix", "ui.flat": "Flat", "ui.flip": "Flip", + "ui.format": "Format", "ui.front": "Front", "ui.fully_constrained": "Fully constrained", "ui.general": "General", "ui.graphics": "Graphics", "ui.ground_shadow": "Ground shadow", + "ui.groupSelected": "Group Selected", "ui.heading_add_ins": "ADD-INS", "ui.heading_assemble": "ASSEMBLE", "ui.heading_box": "BOX", @@ -697,8 +1089,8 @@ "ui.heading_mirror": "MIRROR", "ui.heading_modify": "MODIFY", "ui.heading_move": "MOVE", - "ui.heading_offset": "OFFSET", "ui.heading_move_copy": "MOVE/COPY", + "ui.heading_offset": "OFFSET", "ui.heading_offset_plane": "OFFSET PLANE", "ui.heading_ok": "OK", "ui.heading_parameters": "PARAMETERS", @@ -706,13 +1098,16 @@ "ui.heading_pipe": "PIPE", "ui.heading_plane_at_angle": "PLANE AT ANGLE", "ui.heading_plastic": "PLASTIC", + "ui.heading_position": "POSITION", "ui.heading_prepare": "PREPARE", "ui.heading_rectangular_pattern": "RECTANGULAR PATTERN", "ui.heading_revolve": "REVOLVE", "ui.heading_right": "RIGHT", + "ui.heading_save_mesh": "SAVE AS MESH", "ui.heading_scale": "SCALE", "ui.heading_section_analysis": "SECTION ANALYSIS", "ui.heading_select": "SELECT", + "ui.heading_setup": "SETUP", "ui.heading_sheet_metal": "SHEET METAL", "ui.heading_shell": "SHELL", "ui.heading_sketch": "SKETCH", @@ -730,15 +1125,22 @@ "ui.heading_utility": "UTILITY", "ui.help": "Help", "ui.hide": "Hide", + "ui.hideAxes": "Hide Axes", + "ui.hideDimension": "Hide Dimension", + "ui.hideOrigin": "Hide Origin", + "ui.hidePlanes": "Hide Planes", + "ui.hideProfile": "Hide Profile", "ui.hole": "Hole", "ui.hole_tap_type": "Hole Tap Type", "ui.hole_type": "Hole Type", "ui.home": "Home", + "ui.homeView": "Home View", "ui.horizontal_vertical": "Horizontal/Vertical", "ui.import_ellipsis": "Import…", "ui.insert": "Insert", "ui.inspect": "Inspect", "ui.intersect": "Intersect", + "ui.isolate": "Isolate", "ui.join": "Join", "ui.joints": "Joints", "ui.keyboard_shortcuts": "Keyboard Shortcuts", @@ -747,11 +1149,37 @@ "ui.light": "Light", "ui.line": "Line", "ui.linetype": "Linetype", + "ui.lock": "Lock", "ui.loft": "Loft", "ui.look_at": "Look At", "ui.look_at_anim_desc": "Axis view, Look At, Home and Fit", "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.", + "ui.material_review.compressive_strength": "Compressive strength", + "ui.material_review.conditions": "Stated conditions", + "ui.material_review.density": "Density", + "ui.material_review.derived": "Derived isotropic moduli", + "ui.material_review.elasticity": "Elasticity", + "ui.material_review.input": "Paste a schema-1 material card (JSON)", + "ui.material_review.limit": "The card exceeds the 256 KiB input limit.", + "ui.material_review.moisture_unit": "kg water / kg dry material", + "ui.material_review.properties": "Properties", + "ui.material_review.review": "Review card", + "ui.material_review.scope": "Candidate only: not assigned or saved. Numerical validation is not engineering certification.", + "ui.material_review.shear_strength": "Shear strength", + "ui.material_review.source": "Source", + "ui.material_review.specific_heat": "Specific heat", + "ui.material_review.tensile_strength": "Tensile strength", + "ui.material_review.thermal_conductivity": "Thermal conductivity", + "ui.material_review.thermal_expansion": "Thermal expansion", + "ui.material_review.title": "Review Physical Material Data", + "ui.material_review.unknown": "Unknown", + "ui.material_review.yield_strength": "Yield strength", "ui.measure": "Measure", + "ui.mesh_format_3mf": "3MF", + "ui.mesh_format_3mf_tagged": "3MF with face tags", + "ui.mesh_format_stl": "STL", "ui.midpoint": "Midpoint", "ui.mirror": "Mirror", "ui.mirror_line": "Mirror line", @@ -761,9 +1189,13 @@ "ui.named_views": "Named Views", "ui.navigation": "Navigation", "ui.needs_design": "{command}: open a design first", + "ui.newSketchGroup": "New Sketch Group", "ui.new_body": "New Body", "ui.new_design": "New Design", + "ui.no_slicer_found": "No slicer found", "ui.normal": "Normal", + "ui.normalConstruction": "Normal / Construction", + "ui.not_a_program": "{path} is not a program that can be started", "ui.object_type": "Object Type", "ui.objects": "Objects", "ui.offer_to_stand_up_y_up_files": "Offer to stand up Y-up files", @@ -776,10 +1208,13 @@ "ui.open_recent": "Open Recent", "ui.operation": "Operation", "ui.options": "Options", + "ui.orbit": "Orbit", "ui.orbit_around": "Orbit around", + "ui.orientation": "Orientation", "ui.origin": "Origin", "ui.palette_points": "Points", "ui.palette_profile": "Profile", + "ui.pan": "Pan", "ui.pan_zoom_orbit": "Pan, zoom, orbit", "ui.parallel": "Parallel", "ui.parameters": "Parameters", @@ -788,6 +1223,8 @@ "ui.pattern_on_path": "Pattern on Path", "ui.perpendicular": "Perpendicular", "ui.perspective_view": "Perspective view", + "ui.pinToShortcuts": "Pin to Shortcuts", + "ui.pinToToolbar": "Pin to Toolbar", "ui.pipe": "Pipe", "ui.placement": "Placement", "ui.plane": "Plane", @@ -803,63 +1240,59 @@ "ui.profiles": "Profiles", "ui.project": "Project", "ui.project_face_edges_sketch": "Project face edges into new sketches", + "ui.properties": "Properties", + "ui.pull_direction": "Pull direction", "ui.quantity": "Quantity", "ui.quantity_2": "Quantity 2", "ui.quit": "Quit", "ui.radial_context_menu": "Radial context menu", "ui.radius": "Radius", - "ui.pull_direction": "Pull direction", - "ui.tool_direction": "Tool direction", - "ui.reachable": "Reachable", - "ui.blocked": "Blocked", "ui.radius_type": "Radius Type", + "ui.reachable": "Reachable", "ui.rectangle": "Rectangle", "ui.rectangular_pattern": "Rectangular Pattern", "ui.redo": "Redo", + "ui.removeFromToolbar": "Remove from Toolbar", + "ui.removeSection": "Remove Section", "ui.render": "Render", "ui.renderer": "Renderer", + "ui.repeat": "Repeat", + "ui.report_a_bug": "Report a bug", "ui.reset": "Reset", "ui.reset_all": "Reset All", "ui.reset_the_settings_on_this_page": "Reset the settings on this page", + "ui.restore": "Restore", "ui.restore_defaults": "Restore Defaults", "ui.reverse_zoom_direction": "Reverse zoom direction", "ui.revolve": "Revolve", "ui.right": "Right", "ui.save": "Save", - "ui.heading_save_mesh": "SAVE AS MESH", - "ui.format": "Format", - "ui.mesh_format_stl": "STL", - "ui.mesh_format_3mf": "3MF", - "ui.mesh_format_3mf_tagged": "3MF with face tags", - "ui.send_to_slicer": "Send to slicer", - "ui.slicer": "Slicer", - "ui.custom_program": "Custom…", - "ui.no_slicer_found": "No slicer found", - "ui.send": "Send", - "ui.custom_program_tip": "Choose a slicer program to add to the list", - "ui.slicer_delete_tip": "{program}\nPress Delete to remove it from the list", - "ui.save_mesh_pick_bodies": "Select the bodies to save", - "ui.save_mesh_no_slicer": "No slicer found: choose Custom… and pick your slicer program, or turn off Send to slicer", - "ui.not_a_program": "{path} is not a program that can be started", - "ui.sent_to_slicer": "Sent to {slicer}", - "ui.saved_to": "Saved {path}", - "ui.save_mesh_temp_failed": "Couldn't make {folder}: {error}", "ui.save_as": "Save As", "ui.save_as_ellipsis": "Save As...", + "ui.save_mesh_no_slicer": "No slicer found: choose Custom… and pick your slicer program, or turn off Send to slicer", + "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.scale": "Scale", - "ui.orientation": "Orientation", - "ui.twist": "Twist", - "ui.end_scale": "End Scale", - "ui.sweep_turn_with_path": "Turn with Path", - "ui.sweep_keep_as_drawn": "Keep as Drawn", - "ui.sweep_follow_direction": "Follow Direction", "ui.section_analysis": "Section Analysis", "ui.select": "Select", + "ui.selectOther": "Select Other…", + "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.send": "Send", + "ui.send_to_slicer": "Send to slicer", + "ui.sent_to_slicer": "Sent to {slicer}", "ui.shell": "Shell", "ui.show": "Show", + "ui.showAll": "Show All", + "ui.showAllBodies": "Show All Bodies", + "ui.showAxes": "Show Axes", + "ui.showDimension": "Show Dimension", + "ui.showOrigin": "Show Origin", + "ui.showPlanes": "Show Planes", "ui.show_constraints": "Constraints", + "ui.show_construction_geometries": "Construction Geometries", "ui.show_dimensions": "Dimensions", "ui.show_points": "Show Points", "ui.show_profile": "Show Profile", @@ -874,6 +1307,8 @@ "ui.sketch_status": "Sketch Status", "ui.sketches": "Sketches", "ui.slice": "Slice", + "ui.slicer": "Slicer", + "ui.slicer_delete_tip": "{program}\nPress Delete to remove it from the list", "ui.slot": "Slot", "ui.smooth": "Smooth", "ui.smooth_wheel_zoom": "Smooth wheel zoom", @@ -889,7 +1324,14 @@ "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_radius": "Start Radius", + "ui.supersampling": "Supersampling (SSAA)", + "ui.supersampling_adaptive": "Only when the view is still", + "ui.supersampling_off": "Off (1×)", + "ui.suppress": "Suppress", "ui.sweep": "Sweep", + "ui.sweep_follow_direction": "Follow Direction", + "ui.sweep_keep_as_drawn": "Keep as Drawn", + "ui.sweep_turn_with_path": "Turn with Path", "ui.symmetric": "Symmetric", "ui.symmetry": "Symmetry", "ui.system": "System", @@ -905,18 +1347,26 @@ "ui.timeline_left_sidebar": "Left sidebar", "ui.tip_angle": "Tip Angle", "ui.to_object": "To Object", + "ui.tool_direction": "Tool direction", "ui.top": "Top", "ui.torus": "Torus", + "ui.total_angle": "Total angle", "ui.trackpad_pan_tip": "Trackpad gestures pan (off: they zoom like the wheel); mouse wheel zooms, thumb wheel pans sideways, pinch always zooms", "ui.trim": "Trim", + "ui.twist": "Twist", "ui.two_finger_scroll_pans": "Two-finger scroll pans", "ui.two_sides": "Two Sides", "ui.ui_scale": "UI scale", "ui.undo": "Undo", + "ui.unground": "Unground", + "ui.unisolate": "Unisolate", "ui.units": "Units", "ui.units_of_new_designs": "Units of new designs", + "ui.unlock": "Unlock", + "ui.unsuppress": "Unsuppress", "ui.untitled": "Untitled", "ui.up_axis_note": "Which axis points up in the views (axis view, Home, Look At). Designs are unchanged.", + "ui.updateToCurrentView": "Update to Current View", "ui.variable": "Variable", "ui.view_centre": "View centre", "ui.visual_shaded_hidden_edges": "Shaded with hidden edges", @@ -928,492 +1378,41 @@ "ui.y_distance": "Y Distance", "ui.y_up": "Y up", "ui.z_up": "Z up", + "ui.zoom": "Zoom", "ui.zoom_to_cursor_tip": "The wheel zooms toward the point under the cursor (off: toward the view's centre)", "ui.zoom_to_the_cursor": "Zoom to the cursor", - "A new configuration, a copy of the active one": "A new configuration, a copy of the active one", - "About SolidCraft": "About SolidCraft", - "Active": "Active", - "Active rule": "Active rule", - "Add": "Add", - "Add Key": "Add Key", - "Add Mid Radius": "Add Mid Radius", - "Add Row": "Add Row", - "All Sketch Points": "All Sketch Points", - "All open designs": "All open designs", - "Allowed expressions, separated by semicolons": "Allowed expressions, separated by semicolons", - "Also deletes": "Also deletes", - "Angle 2": "Angle 2", - "Animate": "Animate", - "Appearance name": "Appearance name", - "Applied Radius": "Applied Radius", - "Apply To": "Apply To", - "Area": "Area", - "Attachment": "Attachment", - "BROWSER": "BROWSER", - "Bend Line Position": "Bend Line Position", - "Bend Position": "Bend Position", - "Bend Radius": "Bend Radius", - "Bends": "Bends", - "Body": "Body", - "Bounding box": "Bounding box", - "CSV or JSON: updates existing parameters, adds new ones": "CSV or JSON: updates existing parameters, adds new ones", - "Capture All Positions": "Capture All Positions", - "Catch Direction": "Catch Direction", - "Cells": "Cells", - "Center X": "Center X", - "Center Y": "Center Y", - "Center of mass": "Center of mass", - "Chamfer Type": "Chamfer Type", - "Check collisions": "Check collisions", - "Checked": "Checked", - "Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.": "Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.", - "Close draft": "Close draft", - "Collisions": "Collisions", - "Colour": "Colour", - "Component1": "Component1", - "Configuration": "Configuration", - "Configuration rules": "Configuration rules", - "Contact": "Contact", - "Copy all licences": "Copy all licences", - "Copy diagnostic information": "Copy diagnostic information", - "Copy report": "Copy report", - "Corner Relief": "Corner Relief", - "Corner Relief Shape": "Corner Relief Shape", - "Notch": "Notch", - "Round": "Round", - "Rectangular": "Rectangular", - "Tear": "Tear", - "Counterbore depth": "Counterbore depth", - "Countersink angle": "Countersink angle", - "Create Issue — review draft": "Create Issue — review draft", - "Customize Toolbar": "Customize Toolbar", - "Delete all": "Delete all", - "Delete rule": "Delete rule", - "Delete the row": "Delete the row", - "Delete the set": "Delete the set", - "Delete this parameter": "Delete this parameter", - "Density": "Density", - "Designs you open or save appear here.": "Designs you open or save appear here.", - "Determined by To Object. Choose Angle to edit the angular extent.": "Determined by To Object. Choose Angle to edit the angular extent.", - "Discard": "Discard", - "Double-click to rename": "Double-click to rename", - "Drive Joint": "Drive Joint", - "Edit Profile Sketch": "Edit Profile Sketch", - "Enable rule": "Enable rule", - "Enabled": "Enabled", - "Explode": "Explode", - "Extents": "Extents", - "Face attachment lost": "Face attachment lost", - "Faces / edges / vertices": "Faces / edges / vertices", - "Favourite": "Favourite", - "Files from many CAD programs have Y up, so they open lying on their back here (Z up).": "Files from many CAD programs have Y up, so they open lying on their back here (Z up).", - "Filter": "Filter", - "Find in Browser": "Find in Browser", - "Copy Error Message": "Copy Error Message", - "Copy Warning Message": "Copy Warning Message", - "Flat size": "Flat size", - "Follow camera (Look At sketches)": "Follow camera (Look At sketches)", - "Font": "Font", - "Full Length": "Full Length", - "Gap": "Gap", - "Grid": "Grid", - "Height": "Height", - "Home view": "Home view", - "In This Design": "In This Design", - "Interferes": "Interferes", - "Issue title": "Issue title", - "Joint Origin1": "Joint Origin1", - "Keep Tools": "Keep Tools", - "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.", - "Length": "Length", - "Length units": "Length units", - "Library": "Library", - "Loop": "Loop", - "Margin": "Margin", - "Mass": "Mass", - "Material": "Material", - "Mid Radius": "Mid Radius", - "Modeled": "Modeled", - "More toolbar panels": "More toolbar panels", - "Motion": "Motion", - "Move Type": "Move Type", - "Move earlier": "Move earlier", - "Move later": "Move later", - "Name": "Name", - "No crash reports.": "No crash reports.", - "No matching appearances": "No matching appearances", - "Not available yet": "Not available yet", - "Opacity": "Opacity", - "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", - "Parameter values": "Parameter values", - "Per Edge": "Per Edge", - "Pick the tool bodies": "Pick the tool bodies", - "Place at the origin instead": "Place at the origin instead", - "Playback": "Playback", - "Position": "Position", - "Position (0 to 1)": "Position (0 to 1)", - "Position along the edge, 0 at the start end, 1 at the other": "Position along the edge, 0 at the start end, 1 at the other", - "Preview leaves the current design unchanged.": "Preview leaves the current design unchanged.", - "RECENT": "RECENT", - "Radius Fit": "Radius Fit", - "Ratio": "Ratio", - "Recover": "Recover", - "Recover unsaved design?": "Recover unsaved design?", - "Remove Tools": "Remove Tools", - "Remove from list": "Remove from list", - "Remove private design details or paths before sharing.": "Remove private design details or paths before sharing.", - "Remove the column": "Remove the column", - "Remove the track": "Remove the track", - "Remove this point": "Remove this point", - "Report a bug — review a screenshot and open a GitHub draft": "Report a bug — review a screenshot and open a GitHub draft", - "Reset Toolbar": "Reset Toolbar", - "Restore the inherited component or physical material appearance": "Restore the inherited component or physical material appearance", - "Result": "Result", - "Retake screenshot": "Retake screenshot", - "Reverse": "Reverse", - "Reverse Direction": "Reverse Direction", - "Revert": "Revert", - "Revert All Positions": "Revert All Positions", - "Review the report and screenshot before opening GitHub.": "Review the report and screenshot before opening GitHub.", - "Rim Edge": "Rim Edge", - "Roll History Marker Here": "Roll History Marker Here", - "Rule": "Rule", - "Saved preview. Geometry is being checked before editing.": "Saved preview. Geometry is being checked before editing.", - "Scale factor": "Scale factor", - "Search": "Search", - "Search commands": "Search commands", - "Select bodies (a face picks its body)": "Select bodies (a face picks its body)", - "Select bodies or faces instead": "Select bodies or faces instead", - "Selection filter": "Selection filter", - "Semantic faces share their appearance across instances.": "Semantic faces share their appearance across instances.", - "Shape": "Shape", - "Show Agent Cursor": "Show Agent Cursor", - "Show in folder": "Show in folder", - "Size": "Size", - "Sketch plane has no body-face attachment.": "Sketch plane has no body-face attachment.", - "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft closed before these designs were saved. Their last autosave can be opened.", - "Speed": "Speed", - "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?", - "Step": "Step", - "Steps": "Steps", - "Suppressed": "Suppressed", - "Swap Ends": "Swap Ends", - "Tangent Chain": "Tangent Chain", - "The dashed sketch is a saved plane guide. Select a new face to repair the attachment.": "The dashed sketch is a saved plane guide. Select a new face to repair the attachment.", - "The saved author occurrence is missing. Select a valid author placement before rebinding.": "The saved author occurrence is missing. Select a valid author placement before rebinding.", - "Then": "Then", - "These features will be deleted:": "These features will be deleted:", - "These features will fail:": "These features will fail:", - "This child is shared. Deleting it removes it from every copy of its parent.": "This child is shared. Deleting it removes it from every copy of its parent.", - "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", - "Tolerance": "Tolerance", - "Type": "Type", - "Updating the preview": "Updating the preview", - "Use fixed plane": "Use fixed plane", - "VIEW": "VIEW", - "Value": "Value", - "Volume": "Volume", - "Wall": "Wall", - "When": "When", - "Width": "Width", - "Will fail": "Will fail", - "angle, height": "angle, height", - "command name": "command name", - "expression, e.g. 25 mm": "expression, e.g. 25 mm", - "fits the face, e.g. M8": "fits the face, e.g. M8", - "from the rule": "from the rule", - "needs two joints": "needs two joints", - "new configuration": "new configuration", - "new name": "new name", - "new parameter": "new parameter", - "no interference": "no interference", - "no joint that moves yet": "no joint that moves yet", - "no picture": "no picture", - "pick a hole to seat it, or OK places it at the origin": "pick a hole to seat it, or OK places it at the origin", - "pick one or two vertices, edges or faces": "pick one or two vertices, edges or faces", - "the parts library is not available": "the parts library is not available", - "to the next face": "to the next face", - "Revert Position": "Revert Position", - "Construction": "Construction", - "Faces": "Faces", - "Edges": "Edges", - "Vertices": "Vertices", - "Sketch geometry and profiles": "Sketch geometry and profiles", - "Sketch curves": "Sketch curves", - "Sketch points": "Sketch points", - "Sketch dimensions": "Sketch dimensions", - "Sketch constraints": "Sketch constraints", - "0 turns it off": "0 turns it off", - "Show the pointer an AI agent moves (#35)": "Show the pointer an AI agent moves (#35)", - "Follow the camera (Look At sketches)": "Follow the camera (Look At sketches)", - "Flat": "Flat", - "Save Rule": "Save Rule", - "Preview Row": "Preview Row", - "Add condition": "Add condition", - "Apply to selection": "Apply to selection", - "Remove override": "Remove override", - "Copy screenshot": "Copy screenshot", - "Remove screenshot": "Remove screenshot", - "Use active author placement": "Use active author placement", - "Reattach selected face": "Reattach selected face", - "Use saved fixed plane": "Use saved fixed plane", - "Use selected face as fixed plane": "Use selected face as fixed plane", - "View navigator": "View navigator", - "Signed axes": "Signed axes", - "Cube": "Cube", - "Middle double-click": "Middle double-click", - "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": "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", - "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).": "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).", - "cmd.render_backends": "Render Backends", - "cmd.view_navigate": "Navigate View", - "ui.animateJoint": "Animate Joint", - "ui.calibrate": "Calibrate", - "ui.customizeToolbar": "Customize Toolbar…", - "ui.editJointLimits": "Edit Joint Limits", - "ui.exportDxf": "Export DXF…", - "ui.findInTimeline": "Find in Timeline", - "ui.findInWindow": "Find in Window", - "ui.fit": "Fit", - "ui.groupSelected": "Group Selected", - "ui.hideAxes": "Hide Axes", - "ui.hideDimension": "Hide Dimension", - "ui.hideOrigin": "Hide Origin", - "ui.hidePlanes": "Hide Planes", - "ui.hideProfile": "Hide Profile", - "ui.homeView": "Home View", - "ui.isolate": "Isolate", - "ui.lock": "Lock", - "ui.newSketchGroup": "New Sketch Group", - "ui.normalConstruction": "Normal / Construction", - "ui.orbit": "Orbit", - "ui.heading_position": "POSITION", - "ui.pan": "Pan", - "ui.pinToShortcuts": "Pin to Shortcuts", - "ui.pinToToolbar": "Pin to Toolbar", - "ui.properties": "Properties", - "ui.design_properties.project": "Project", - "ui.design_properties.part_number": "Part number", - "ui.design_properties.revision": "Revision", - "ui.design_properties.author": "Author", - "ui.design_properties.organization": "Organization", - "ui.design_properties.description": "Description", - "ui.design_properties.license": "License", - "ui.design_properties.not_text": "Saved as something other than text; typing here replaces it.", - "ui.design_properties.exports": "STEP, IGES and 3MF exports carry these where the format has a place for them.", - "ui.design_properties.others": "Other tools' data", - "ui.design_properties.others_note": "Kept in the design as it is and never exported.", - "ui.removeSection": "Remove Section", - "ui.removeFromToolbar": "Remove from Toolbar", - "ui.repeat": "Repeat", - "ui.report_a_bug": "Report a bug", - "ui.restore": "Restore", - "ui.heading_setup": "SETUP", - "ui.selectOther": "Select Other…", - "ui.selectTangentChain": "Select Tangent Chain", - "ui.showAll": "Show All", - "ui.showAllBodies": "Show All Bodies", - "ui.showAxes": "Show Axes", - "ui.showDimension": "Show Dimension", - "ui.showOrigin": "Show Origin", - "ui.showPlanes": "Show Planes", - "ui.suppress": "Suppress", - "ui.command_palette_hint": "Type a command, e.g. {example} — or press S to search", - "ui.unground": "Unground", - "ui.unisolate": "Unisolate", - "ui.unlock": "Unlock", - "ui.unsuppress": "Unsuppress", - "ui.updateToCurrentView": "Update to Current View", - "ui.zoom": "Zoom", - "ui.command_done": "{command} done", - "drive.stopped_by_loop": "Stopped at {value}: the loop through {joint} can't close any further", - "drive.stopped_by_contact": "Stopped at {value}: {a} would pass through {b}", - "drive.unconnected": "Moves nothing: {part} is not connected to anything grounded", - "timeline.group": "New Feature Folder", - "timeline.ungroup": "Remove Feature Folders", - "timeline.rename_group": "Rename Feature Folder", - "timeline.move_to_group": "Move Features to Folder", - "timeline.move_many": "Move Timeline Items", - "timeline.reorder_many": "Reorder Features", - "ui.show_construction_geometries": "Construction Geometries", - "ui.total_angle": "Total angle", - "sketch_text.builtin_font": "{family} (built-in)", - "sketch_text.font_search": "Search fonts", - "sketch_text.loading_fonts": "Looking for installed fonts…", - "sketch_text.use_font_file": "Use the font file {path}", - "sketch_text.bold": "Bold", - "sketch_text.italic": "Italic", - "sketch_text.align_left": "Left", - "sketch_text.align_center": "Center", - "sketch_text.align_right": "Right", - "sketch_text.path_hint": "A curve of the sketch the text follows: click here, then the curve", - "sketch_text.path_clear": "Take the text off its curve", - "Style": "Style", - "Alignment": "Alignment", - "Letter Spacing": "Letter Spacing", - "Line Spacing": "Line Spacing", - "Path": "Path", - "sketch_text.on_path": "The text follows its path: the curve places it", - "cmd.library_inspect": "Inspect Local Library", - "cmd.library_export": "Export Design Library", - "cmd.library_apply": "Apply Local Library Entry", - "Thin": "Thin", - "Thin Extrude": "Thin Extrude", - "Wall Location": "Wall Location", - "Wall Thickness": "Wall Thickness", - "Thickness Outside": "Thickness Outside", - "Inside": "Inside", - "Outside": "Outside", - "Profiles/Curves": "Profiles/Curves", - "cmd.material_properties_validate": "Validate Physical Material Data", - "cmd.material_properties_directional": "Directional Elastic Modulus", + "update.available": "SolidCraft {version} is available", "update.button": "Update", "update.button_tip": "SolidCraft {version} is available", - "install.menu": "Install app…", - "install.button_tip": "Install SolidCraft as an app: it opens in its own window and works offline", - "install.title": "Install SolidCraft", - "install.steps_intro": "Safari installs web apps from its own menus:", - "install.home_screen_1": "Tap Share (in the … menu if it isn't on the toolbar).", - "install.home_screen_2": "Choose Add to Home Screen.", - "install.home_screen_3": "Tap Add.", - "install.home_screen_after": "SolidCraft then opens from its icon on the Home Screen, without Safari's toolbars, and works offline.", - "install.dock_1": "Choose File › Add to Dock.", - "install.dock_2": "Click Add.", - "install.dock_after": "SolidCraft then opens in its own window from the Dock, and works offline.", - "install.done": "Done", - "update.title": "Update available", - "update.available": "SolidCraft {version} is available", - "update.you_have": "You have {version}.", - "update.no_notes": "This release has no notes.", - "update.system_hint": "This copy is a {kind}. Update it with:", - "update.package_hint": "This copy came from a {kind}. Download the new package, then install it with:", - "update.copy": "Copy", - "update.file": "Download gets {file}.", - "update.download": "Download", - "update.release_page": "Open release page", - "update.skip": "Skip this version", - "update.later": "Remind me later", - "update.prefs_label": "Updates", "update.check_automatically": "Check for updates automatically", "update.check_now": "Check now", "update.checking": "Checking…", - "update.failed": "Couldn't check: {error}", - "update.up_to_date": "SolidCraft is up to date.", - "update.prefs_note": "This is SolidCraft {version} ({kind}). A check asks GitHub for the latest release and sends nothing else.", - "update.prefs_dev": "This is a development build ({version}): it doesn't check for updates.", - "update.show": "Show the update to {version}", - "update.prefs_flatpak": "Flatpak updates this copy ({version}): run {command} or use your software center. SolidCraft doesn't check.", - "update.update_now": "Update now", - "update.install_msi": "Install (closes SolidCraft)", + "update.copy": "Copy", + "update.dmg_opened": "The disk image is open and verified: drag SolidCraft to Applications, replacing the old copy, then restart SolidCraft.", + "update.download": "Download", "update.download_open": "Download and open", "update.downloading": "Downloading and verifying… {done} of {total} MB", + "update.failed": "Couldn't check: {error}", + "update.file": "Download gets {file}.", + "update.install_failed": "The update didn't install: {error}. Nothing was changed; Download gets the package instead.", + "update.install_msi": "Install (closes SolidCraft)", "update.installed": "SolidCraft {version} is installed. Restart to use it.", + "update.installer_started": "The installer starts when SolidCraft closes.", + "update.later": "Remind me later", + "update.no_notes": "This release has no notes.", + "update.package_hint": "This copy came from a {kind}. Download the new package, then install it with:", + "update.prefs_dev": "This is a development build ({version}): it doesn't check for updates.", + "update.prefs_flatpak": "Flatpak updates this copy ({version}): run {command} or use your software center. SolidCraft doesn't check.", + "update.prefs_label": "Updates", + "update.prefs_note": "This is SolidCraft {version} ({kind}). A check asks GitHub for the latest release and sends nothing else.", + "update.release_page": "Open release page", "update.restart": "Restart now", "update.restart_later": "Later", - "update.installer_started": "The installer starts when SolidCraft closes.", - "update.dmg_opened": "The disk image is open and verified: drag SolidCraft to Applications, replacing the old copy, then restart SolidCraft.", - "update.install_failed": "The update didn't install: {error}. Nothing was changed; Download gets the package instead.", - "cmd.render_settings_get": "Render Settings", - "cmd.render_settings_set": "Save Render Settings", - "cmd.render_scene": "Inspect Render Scene", - "cmd.render_settings_apply": "Apply Render Camera", - "toolbar.render": "RENDER", - "toolbar.render_scene": "SCENE", - "render.preview": "Integrated preview", - "render.preview_help": "Raster shading and blended transparency. Refraction, HDRI and final rendering are not available yet.", - "render.setup_name": "Setup name", - "render.background": "Scene background", - "render.perspective": "Perspective camera", - "render.fit": "Fit Product", - "render.restore_camera": "Restore Saved Camera", - "render.save_setup": "Save Setup", - "render.unsaved": "Unsaved preview changes", - "render.reload_settings": "Reload Saved Settings", - "render.unavailable_preview": "This setup requests an unavailable preview profile.", - "render.use_preview": "Use Integrated Preview", - "render.navigation_help": "The camera moves as in Design (Preferences › Navigation). Save Setup records the current camera.", - "render.return_design": "Return to Design", - "render.image_title": "Render Image", - "render.image_help": "CPU preview image · PNG · approximate transparency", - "render.image_width": "Width", - "render.image_height": "Height", - "render.image_transparent": "Transparent background", - "render.image_check": "Check Render Request", - "render.image_supported": "Render request is supported; the queue and memory pool are checked again at start.", - "render.image_queued": "Waiting to render", - "render.image_preparing": "Preparing image", - "render.image_running": "Rendering image", - "render.image_encoding": "Encoding PNG", - "render.image_cancelling": "Cancelling", - "render.image_cancelled": "Render cancelled", - "render.image_completed": "Image ready to export", - "render.image_failed": "Render failed", - "render.image_unknown": "Render status unavailable", - "render.image_reduce": "Try a smaller image or simpler scene.", - "render.image_too_large": "Over the image limit: 4096 pixels per side and 4,194,304 pixels in all.", - "render.image_use_largest": "Use the largest size at this aspect:", - "render.image_cancel": "Cancel Render", - "render.image_stale": "This image uses the scene captured before subsequent changes.", - "render.image_start": "Start Render", - "render.image_overwrite": "Replace existing file", - "render.image_export": "Export PNG", - "cmd.render_preflight": "Check Render Request", - "cmd.render_start": "Render Image", - "cmd.render_status": "Render Progress", - "cmd.render_cancel": "Cancel Render", - "cmd.render_export": "Export Render Image", - "toolbar.image": "IMAGE", - "appearance.surface_response": "Surface response", - "appearance.pbr_opaque": "Opaque PBR", - "appearance.metallic": "Metallic", - "appearance.roughness": "Roughness", - "appearance.dielectric_ior": "Dielectric IOR", - "appearance.pbr_help": "View this surface in Render or a product PNG. No refraction or transmission.", - "render.opaque_preview_help": "Opaque PBR and simple colors; blended transparency. Refraction, HDRI and final rendering are not available yet.", - "render.opaque_image_summary": "Preview PNG · opaque PBR · blended transparency", - "UNTRIM": "UNTRIM", - "Face": "Face", - "Holes": "Holes", - "Holes (edges on them)": "Holes (edges on them)", - "In place (surfaces)": "In place (surfaces)", - "None": "None", - "Picked": "Picked", - "Restore outer boundary": "Restore outer boundary", - "RULED SURFACE": "RULED SURFACE", - "Mitre": "Mitre", - "Reference face": "Reference face", - "Round": "Round", - "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.", - "joint.one_body": "Both picks are on {body}. Pick the second one on another part.", - "joint.from_bodies_hint": "Each picked body moves into a new component of its own and stays where it is.", - "Circumference": "Circumference", - "Arc length": "Arc length", - "Slot width": "Slot width", - "Centre to centre": "Centre to centre", - "Overall length": "Overall length", - "Min": "Min", - "Max": "Max", - "coupling.gear_1": "Gear 1", - "coupling.gear_2": "Gear 2", - "coupling.pinion": "Pinion", - "coupling.rack": "Rack", - "coupling.nut": "Nut", - "coupling.radius_1": "Radius 1", - "coupling.radius_2": "Radius 2", - "coupling.internal": "Internal gear", - "coupling.pitch": "Pitch", - "coupling.picked": "picked", - "coupling.not_round": "not a round face", - "coupling.gear_1_pick": "Gear 1 (optional)", - "coupling.gear_2_pick": "Gear 2 (optional)", - "coupling.pinion_pick": "Pinion (optional)", - "coupling.needs_turns": "needs two joints that turn", - "coupling.needs_turn_and_slide": "needs a joint that turns and one that slides" + "update.show": "Show the update to {version}", + "update.skip": "Skip this version", + "update.system_hint": "This copy is a {kind}. Update it with:", + "update.title": "Update available", + "update.up_to_date": "SolidCraft is up to date.", + "update.update_now": "Update now", + "update.you_have": "You have {version}." } diff --git a/assets/locales/fr.json b/assets/locales/fr.json index 4ea271819..88763bf38 100644 --- a/assets/locales/fr.json +++ b/assets/locales/fr.json @@ -1,17 +1,266 @@ { - "settings.measure_axis_distances": "Afficher les cotes X/Y/Z", - "settings.measure_axis_distances_help": "Afficher les cotes suivant les axes du repère global en plus de la distance totale pendant la mesure.", - "Send your report on GitHub": "Envoyer votre rapport sur GitHub", + "0 turns it off": "0 le désactive", "1. Open GitHub draft below, then paste the report copied to your clipboard.": "1. Ouvrir le brouillon GitHub ci-dessous, puis coller le rapport copié dans le presse-papiers.", "1. Open GitHub draft below. Your title and report will be filled in.": "1. Ouvrir le brouillon GitHub ci-dessous. Votre titre et votre rapport y seront déjà remplis.", "2. Attach your screenshot: copy and paste it, or save and upload the PNG.": "2. Joindre votre capture d'écran : la copier-coller, ou enregistrer le PNG puis le téléverser.", "3. Click Submit new issue on GitHub to send your report.": "3. Cliquer sur Submit new issue sur GitHub pour envoyer votre rapport.", - "nav.touchpad.label": "Pavé tactile", - "nav.touchpad.help": "Maintenir Maj et déplacer le pointeur pour faire un panoramique ; maintenir Alt/Option et le déplacer pour orbiter. Aucun bouton de souris n'est nécessaire. Le défilement vertical zoome.", - "nav.touchpad.orbit": "Orbite (maintenir Alt/Option et déplacer ; sans bouton de souris)", - "nav.touchpad.pan": "Panoramique (maintenir Maj et déplacer ; sans bouton de souris)", - "nav.touchpad.zoom": "Zoom (défilement vertical ou pincement)", - "nav.touchpad.scroll": "Le pavé tactile zoome avec le défilement vertical. Votre réglage de panoramique à deux doigts est conservé pour les autres préréglages.", + "A new configuration, a copy of the active one": "Nouvelle configuration, copie de la configuration active", + "About SolidCraft": "À propos de SolidCraft", + "Active": "Actif", + "Active rule": "Règle active", + "Add": "Ajouter", + "Add Key": "Ajouter une image clé", + "Add Mid Radius": "Ajouter un rayon intermédiaire", + "Add Row": "Ajouter une ligne", + "Add condition": "Ajouter une condition", + "Alignment": "Alignement", + "All Sketch Points": "Tous les points d'esquisse", + "All open designs": "Toutes les conceptions ouvertes", + "Allowed expressions, separated by semicolons": "Expressions autorisées, séparées par des points-virgules", + "Also deletes": "Supprime aussi", + "Angle 2": "Angle 2", + "Animate": "Animer", + "Appearance name": "Nom de l'apparence", + "Applied Radius": "Rayon appliqué", + "Apply To": "Appliquer à", + "Apply to selection": "Appliquer à la sélection", + "Area": "Aire", + "Attachment": "Rattachement", + "BROWSER": "NAVIGATEUR", + "Bend Line Position": "Position de la ligne de pli", + "Bend Position": "Position du pli", + "Bend Radius": "Rayon de pliage", + "Bends": "Plis", + "Body": "Corps", + "Bounding box": "Boîte englobante", + "CSV or JSON: updates existing parameters, adds new ones": "CSV ou JSON : met à jour les paramètres existants, ajoute les nouveaux", + "Capture All Positions": "Capturer toutes les positions", + "Catch Direction": "Direction de l'ergot", + "Cells": "Cellules", + "Center X": "Centre X", + "Center Y": "Centre Y", + "Center of mass": "Centre de gravité", + "Chamfer Type": "Type de chanfrein", + "Check collisions": "Vérifier les collisions", + "Checked": "Vérifié", + "Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.": "Choisir un nouveau plan. La géométrie et les cotes de l'esquisse restent inchangées dans ses coordonnées bidimensionnelles.", + "Close draft": "Fermer le brouillon", + "Collisions": "Collisions", + "Colour": "Couleur", + "Component1": "Composant1", + "Configuration": "Configuration", + "Configuration rules": "Règles de configuration", + "Construction": "Construction", + "Contact": "Contact", + "Copy Error Message": "Copier le message d'erreur", + "Copy Warning Message": "Copier le message d'avertissement", + "Copy all licences": "Copier toutes les licences", + "Copy diagnostic information": "Copier les informations de diagnostic", + "Copy report": "Copier le rapport", + "Copy screenshot": "Copier la capture d'écran", + "Corner Relief": "Dégagement d'angle", + "Corner Relief Shape": "Forme du dégagement d'angle", + "Counterbore depth": "Profondeur du lamage", + "Countersink angle": "Angle de la fraisure", + "Create Issue — review draft": "Créer un ticket — relire le brouillon", + "Cube": "Cube", + "Customize Toolbar": "Personnaliser la barre d'outils", + "Delete all": "Tout supprimer", + "Delete rule": "Supprimer la règle", + "Delete the row": "Supprimer la ligne", + "Delete the set": "Supprimer le jeu", + "Delete this parameter": "Supprimer ce paramètre", + "Density": "Masse volumique", + "Designs you open or save appear here.": "Les conceptions que vous ouvrez ou enregistrez apparaissent ici.", + "Determined by To Object. Choose Angle to edit the angular extent.": "Déterminé par Jusqu'à l'objet. Choisir Angle pour modifier l'étendue angulaire.", + "Discard": "Abandonner", + "Double-click to rename": "Double-cliquer pour renommer", + "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": "Double-clic sur le bouton du milieu dans la vue : Accueil (vue d'accueil, cadrant ce qui est affiché), Cadrer (cadrer ce qui est affiché en gardant l'orientation) ou rien", + "Drive Joint": "Piloter la liaison", + "Edges": "Arêtes", + "Edit Profile Sketch": "Modifier l'esquisse du profil", + "Enable rule": "Activer la règle", + "Enabled": "Activé", + "Explode": "Éclater", + "Extents": "Étendues", + "Face": "Face", + "Face attachment lost": "Rattachement à la face perdu", + "Faces": "Faces", + "Faces / edges / vertices": "Faces / arêtes / sommets", + "Favourite": "Favori", + "Files from many CAD programs have Y up, so they open lying on their back here (Z up).": "Les fichiers de nombreux logiciels de CAO ont Y vers le haut : ils s'ouvrent donc couchés ici (Z vers le haut).", + "Filter": "Filtrer", + "Find in Browser": "Trouver dans le navigateur", + "Flat": "Plat", + "Flat size": "Dimensions à plat", + "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", + "Full Length": "Longueur totale", + "Gap": "Jeu", + "Grid": "Grille", + "Height": "Hauteur", + "Holes": "Trous", + "Holes (edges on them)": "Trous (par leurs arêtes)", + "Home view": "Vue d'accueil", + "In This Design": "Dans cette conception", + "In place (surfaces)": "En place (surfaces)", + "Inside": "Intérieur", + "Interferes": "Interfère", + "Issue title": "Titre du ticket", + "Joint Origin1": "Origine de liaison1", + "Keep Tools": "Conserver les outils", + "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.", + "Length": "Longueur", + "Length units": "Unités de longueur", + "Letter Spacing": "Espacement des lettres", + "Library": "Bibliothèque", + "Line Spacing": "Interligne", + "Loop": "Boucle", + "Margin": "Marge", + "Mass": "Masse", + "Material": "Matériau", + "Mid Radius": "Rayon intermédiaire", + "Middle double-click": "Double-clic milieu", + "Mitre": "Onglet", + "Modeled": "Modélisé", + "More toolbar panels": "Autres groupes de la barre d'outils", + "Motion": "Mouvement", + "Move Type": "Type de déplacement", + "Move earlier": "Déplacer plus tôt", + "Move later": "Déplacer plus tard", + "Name": "Nom", + "No crash reports.": "Aucun rapport de plantage.", + "No matching appearances": "Aucune apparence correspondante", + "None": "Aucun", + "Not available yet": "Pas encore disponible", + "Notch": "Encoche", + "Opacity": "Opacité", + "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é", + "Outside": "Extérieur", + "Parameter values": "Valeurs des paramètres", + "Path": "Trajectoire", + "Per Edge": "Par arête", + "Pick the tool bodies": "Choisir les corps outils", + "Picked": "Sélectionnés", + "Place at the origin instead": "Placer plutôt à l'origine", + "Playback": "Lecture", + "Position": "Position", + "Position (0 to 1)": "Position (0 à 1)", + "Position along the edge, 0 at the start end, 1 at the other": "Position le long de l'arête : 0 à l'extrémité de départ, 1 à l'autre", + "Preview Row": "Aperçu de la ligne", + "Preview leaves the current design unchanged.": "L'aperçu ne modifie pas la conception actuelle.", + "Profiles/Curves": "Profils/Courbes", + "RECENT": "RÉCENTS", + "RULED SURFACE": "SURFACE RÉGLÉE", + "Radius Fit": "Ajustement du rayon", + "Ratio": "Rapport", + "Reattach selected face": "Rattacher la face sélectionnée", + "Recover": "Récupérer", + "Recover unsaved design?": "Récupérer la conception non enregistrée ?", + "Rectangular": "Rectangulaire", + "Reference face": "Face de référence", + "Remove Tools": "Retirer les outils", + "Remove from list": "Retirer de la liste", + "Remove override": "Retirer le remplacement", + "Remove private design details or paths before sharing.": "Retirez les détails privés de la conception et les chemins avant de partager.", + "Remove screenshot": "Retirer la capture d'écran", + "Remove the column": "Retirer la colonne", + "Remove the track": "Retirer la piste", + "Remove this point": "Retirer ce point", + "Report a bug — review a screenshot and open a GitHub draft": "Signaler un bug — relire une capture d'écran et ouvrir un brouillon GitHub", + "Reset Toolbar": "Réinitialiser la barre d'outils", + "Restore outer boundary": "Restaurer le contour extérieur", + "Restore the inherited component or physical material appearance": "Rétablir l'apparence héritée du composant ou du matériau physique", + "Result": "Résultat", + "Retake screenshot": "Reprendre la capture d'écran", + "Reverse": "Inverser", + "Reverse Direction": "Inverser la direction", + "Revert": "Rétablir", + "Revert All Positions": "Rétablir toutes les positions", + "Revert Position": "Rétablir la position", + "Review the report and screenshot before opening GitHub.": "Relisez le rapport et la capture d'écran avant d'ouvrir GitHub.", + "Rim Edge": "Arête du bord", + "Roll History Marker Here": "Placer le marqueur d'historique ici", + "Round": "Arrondi", + "Rule": "Règle", + "Save Rule": "Enregistrer la règle", + "Saved preview. Geometry is being checked before editing.": "Aperçu enregistré. La géométrie est en cours de vérification avant modification.", + "Scale factor": "Facteur d'échelle", + "Search": "Rechercher", + "Search commands": "Rechercher des commandes", + "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).": "Sélectionner un autre élément : maintenir le bouton gauche immobile sur le modèle (ou clic droit › Sélectionner un autre…) pour lister tout ce qui se trouve sous le curseur ; cliquer de nouveau au même endroit pour sélectionner l'élément suivant. Double-cliquer avec le bouton du milieu pour revenir à l'accueil (Préférences › Navigation).", + "Select bodies (a face picks its body)": "Sélectionner des corps (une face sélectionne son corps)", + "Select bodies or faces instead": "Sélectionner plutôt des corps ou des faces", + "Selection filter": "Filtre de sélection", + "Semantic faces share their appearance across instances.": "Les faces sémantiques partagent leur apparence entre les instances.", + "Send your report on GitHub": "Envoyer votre rapport sur GitHub", + "Shape": "Forme", + "Show Agent Cursor": "Afficher le curseur de l'agent", + "Show in folder": "Afficher dans le dossier", + "Show the pointer an AI agent moves (#35)": "Afficher le pointeur déplacé par un agent IA (#35)", + "Signed axes": "Axes signés", + "Size": "Taille", + "Sketch constraints": "Contraintes d'esquisse", + "Sketch curves": "Courbes d'esquisse", + "Sketch dimensions": "Cotes d'esquisse", + "Sketch geometry and profiles": "Géométrie et profils d'esquisse", + "Sketch plane has no body-face attachment.": "Le plan d'esquisse n'est rattaché à aucune face de corps.", + "Sketch points": "Points d'esquisse", + "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft s'est fermé avant l'enregistrement de ces conceptions. Leur dernier enregistrement automatique peut être ouvert.", + "Speed": "Vitesse", + "Stand it up": "Redresser", + "Stand it up: a quarter turn about X, as one Move feature you can undo.": "Redresser : un quart de tour autour de X, sous forme d'une fonction Déplacer que vous pouvez annuler.", + "Stand this part up?": "Redresser cette pièce ?", + "Step": "Étape", + "Steps": "Étapes", + "Style": "Style", + "Suppressed": "Désactivé", + "Swap Ends": "Permuter les extrémités", + "Tangent Chain": "Chaîne tangente", + "Tear": "Déchirure", + "The dashed sketch is a saved plane guide. Select a new face to repair the attachment.": "L'esquisse en pointillés est un guide de plan enregistré. Sélectionnez une nouvelle face pour réparer le rattachement.", + "The saved author occurrence is missing. Select a valid author placement before rebinding.": "L'occurrence d'auteur enregistrée est introuvable. Sélectionnez un placement d'auteur valide avant de relier.", + "Then": "Alors", + "These features will be deleted:": "Ces fonctions seront supprimées :", + "These features will fail:": "Ces fonctions échoueront :", + "Thickness Outside": "Épaisseur extérieure", + "Thin": "Mince", + "Thin Extrude": "Extrusion mince", + "This child is shared. Deleting it removes it from every copy of its parent.": "Cet enfant est partagé. Le supprimer le retire de toutes les copies de son parent.", + "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", + "Tolerance": "Tolérance", + "Type": "Type", + "UNTRIM": "ANNULER L'AJUSTEMENT", + "Updating the preview": "Mise à jour de l'aperçu", + "Use active author placement": "Utiliser le placement d'auteur actif", + "Use fixed plane": "Utiliser un plan fixe", + "Use saved fixed plane": "Utiliser le plan fixe enregistré", + "Use selected face as fixed plane": "Utiliser la face sélectionnée comme plan fixe", + "VIEW": "VUE", + "Value": "Valeur", + "Vertices": "Sommets", + "View navigator": "Repère de navigation", + "Volume": "Volume", + "Wall": "Paroi", + "Wall Location": "Position de la paroi", + "Wall Thickness": "Épaisseur de paroi", + "When": "Quand", + "Width": "Largeur", + "Will fail": "Échouera", + "angle, height": "angle, hauteur", + "appearance.dielectric_ior": "Indice de réfraction (diélectrique)", + "appearance.metallic": "Métallique", + "appearance.pbr_help": "Voir cette surface dans l'espace Rendu ou dans un PNG du produit. Sans réfraction ni transmission.", + "appearance.pbr_opaque": "PBR opaque", + "appearance.roughness": "Rugosité", + "appearance.surface_response": "Réponse de la surface", "browser.body_name": "Corps{number}", "browser.component_name": "Composant{number}", "browser.parameters": "Paramètres ({count})", @@ -38,7 +287,6 @@ "cmd.component_capture_position": "Capturer la position", "cmd.component_create": "Nouveau composant", "cmd.component_delete": "Supprimer le composant", - "cmd.component_unlock": "Déverrouiller le contenu", "cmd.component_from_bodies": "Créer des composants à partir des corps", "cmd.component_insert_design": "Insérer une conception", "cmd.component_links": "Lister les liens", @@ -49,6 +297,7 @@ "cmd.component_properties": "Propriétés physiques du composant", "cmd.component_rename": "Renommer le composant", "cmd.component_revert_position": "Rétablir la position", + "cmd.component_unlock": "Déverrouiller le contenu", "cmd.component_update_links": "Mettre à jour les liens", "cmd.config_activate": "Activer la configuration", "cmd.config_column": "Colonne de configuration", @@ -90,10 +339,10 @@ "cmd.doc_recovery_discard": "Abandonner la conception récupérée", "cmd.doc_recovery_list": "Conceptions récupérables", "cmd.document_inspect": "Inspecter la conception", - "cmd.document_units": "Changer les unités de la conception", "cmd.document_metadata": "Propriétés de la conception", - "cmd.document_metadata_set": "Modifier les propriétés de la conception", "cmd.document_metadata_remove": "Supprimer une propriété de la conception", + "cmd.document_metadata_set": "Modifier les propriétés de la conception", + "cmd.document_units": "Changer les unités de la conception", "cmd.edit_checkpoint": "Point de restauration", "cmd.edit_restore_checkpoint": "Revenir au point de restauration", "cmd.engine_commands": "Lister les commandes", @@ -111,6 +360,7 @@ "cmd.inspect_accessibility": "Analyse d'accessibilité", "cmd.inspect_center_of_mass": "Centre de gravité", "cmd.inspect_compare": "Comparer les corps", + "cmd.inspect_continuity": "Analyse de continuité", "cmd.inspect_curvature_comb": "Analyse par peigne de courbure", "cmd.inspect_curvature_map": "Analyse par carte de courbure", "cmd.inspect_draft": "Analyse de dépouille", @@ -124,20 +374,25 @@ "cmd.joint_delete": "Supprimer la liaison", "cmd.joint_drive": "Piloter les liaisons", "cmd.joint_edit": "Modifier la liaison", + "cmd.joint_gear": "Engrenage", "cmd.joint_limits": "Limites de liaison", "cmd.joint_list": "Lister les liaisons", "cmd.joint_motion_link": "Lien de mouvement", - "cmd.joint_gear": "Engrenage", - "cmd.joint_rack_pinion": "Pignon et crémaillère", - "cmd.joint_screw": "Vis", "cmd.joint_origin": "Origine de liaison", + "cmd.joint_rack_pinion": "Pignon et crémaillère", "cmd.joint_rigid_group": "Groupe rigide", + "cmd.joint_screw": "Vis", "cmd.joint_solve": "Résoudre les liaisons", + "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", "cmd.material_assign": "Matériau physique", "cmd.material_create": "Nouveau matériau physique", "cmd.material_delete": "Supprimer le matériau physique", "cmd.material_edit": "Modifier le matériau physique", "cmd.material_list": "Lister les matériaux", + "cmd.material_properties_directional": "Module d'élasticité directionnel", + "cmd.material_properties_validate": "Valider les données du matériau physique", "cmd.mesh_convert": "Convertir le maillage", "cmd.model_edges": "Lister les arêtes", "cmd.model_faces": "Lister les faces", @@ -158,10 +413,10 @@ "cmd.parameters_delete": "Supprimer le paramètre", "cmd.parameters_export": "Exporter les paramètres", "cmd.parameters_favorite": "Paramètre favori", - "cmd.parameters_move": "Déplacer le paramètre", "cmd.parameters_graph": "Graphe des paramètres", "cmd.parameters_import": "Importer des paramètres", "cmd.parameters_list": "Lister les paramètres", + "cmd.parameters_move": "Déplacer le paramètre", "cmd.parameters_rename": "Renommer le paramètre", "cmd.parameters_users": "Utilisations du paramètre", "cmd.parts_fastener": "Insérer une fixation", @@ -175,6 +430,16 @@ "cmd.plastic_rest": "Appui", "cmd.plastic_rules": "Lister les règles plastique", "cmd.plastic_snap_fit": "Clip", + "cmd.render_backends": "Moteurs de rendu", + "cmd.render_cancel": "Annuler le rendu", + "cmd.render_export": "Exporter l'image de rendu", + "cmd.render_preflight": "Vérifier la demande de rendu", + "cmd.render_scene": "Inspecter la scène de rendu", + "cmd.render_settings_apply": "Appliquer la caméra de rendu", + "cmd.render_settings_get": "Réglages de rendu", + "cmd.render_settings_set": "Enregistrer les réglages de rendu", + "cmd.render_start": "Rendu d'image", + "cmd.render_status": "Progression du rendu", "cmd.select_clear": "Effacer la sélection", "cmd.sheet_convert": "Convertir en tôlerie", "cmd.sheet_export_bend_table": "Exporter la table des plis", @@ -270,22 +535,21 @@ "cmd.solid_rib": "Nervure", "cmd.solid_split_face": "Scinder la face", "cmd.solid_web": "Voile", - "cmd.surface_patch": "Surface de remplissage", - "cmd.surface_stitch": "Coudre", - "cmd.surface_thicken": "Épaissir", - "cmd.surface_extrude": "Extrusion de surface", - "cmd.surface_revolve": "Révolution de surface", - "cmd.surface_sweep": "Balayage de surface", - "cmd.surface_loft": "Lissage de surface", - "cmd.surface_ruled": "Surface réglée", - "cmd.surface_boundary": "Surface frontière", - "cmd.surface_offset": "Surface décalée", "cmd.surface_blend": "Surface de raccordement", + "cmd.surface_boundary": "Surface frontière", + "cmd.surface_extrude": "Extrusion de surface", "cmd.surface_fillet": "Congé de surface", - "cmd.surface_untrim": "Annuler l'ajustement", - "cmd.surface_unstitch": "Découdre", + "cmd.surface_loft": "Lissage de surface", + "cmd.surface_offset": "Surface décalée", + "cmd.surface_patch": "Surface de remplissage", "cmd.surface_reverse_normal": "Inverser la normale", - "cmd.inspect_continuity": "Analyse de continuité", + "cmd.surface_revolve": "Révolution de surface", + "cmd.surface_ruled": "Surface réglée", + "cmd.surface_stitch": "Coudre", + "cmd.surface_sweep": "Balayage de surface", + "cmd.surface_thicken": "Épaissir", + "cmd.surface_unstitch": "Découdre", + "cmd.surface_untrim": "Annuler l'ajustement", "cmd.timeline_add": "Ajouter une fonction enregistrée", "cmd.timeline_compute_all": "Tout recalculer", "cmd.timeline_copy": "Copier les fonctions", @@ -302,18 +566,42 @@ "cmd.view_apply": "Restaurer la vue nommée", "cmd.view_delete": "Supprimer la vue nommée", "cmd.view_list": "Lister les vues nommées", + "cmd.view_navigate": "Naviguer dans la vue", "cmd.view_rename": "Renommer la vue nommée", "cmd.view_save": "Nouvelle vue nommée", + "command name": "nom de la commande", + "coupling.gear_1": "Engrenage 1", + "coupling.gear_1_pick": "Engrenage 1 (facultatif)", + "coupling.gear_2": "Engrenage 2", + "coupling.gear_2_pick": "Engrenage 2 (facultatif)", + "coupling.internal": "Engrenage intérieur", + "coupling.needs_turn_and_slide": "nécessite une liaison qui tourne et une qui glisse", + "coupling.needs_turns": "nécessite deux liaisons qui tournent", + "coupling.not_round": "pas une face ronde", + "coupling.nut": "Écrou", + "coupling.picked": "sélectionné", + "coupling.pinion": "Pignon", + "coupling.pinion_pick": "Pignon (facultatif)", + "coupling.pitch": "Pas", + "coupling.rack": "Crémaillère", + "coupling.radius_1": "Rayon 1", + "coupling.radius_2": "Rayon 2", "dialog.computing": "Calcul… {seconds} s", "dialog.custom_axis": "↖ Axe personnalisé", "dialog.edit_title": "MODIFIER {title}", "dialog.select": "↖ Sélectionner", "dialog.selected_count": "↖ {count} sélectionné(s)", - "dialog.step": "Étape", - "dialog.selection_step": "{step} sur {total} : sélectionner {input}", "dialog.selection_guidance": "Sélectionner une entrée pour la modifier. Cliquer sur un objet sélectionné pour le retirer ; Ctrl/Cmd-clic le bascule aussi. Vérifier l'aperçu, puis appuyer sur OK.", + "dialog.selection_step": "{step} sur {total} : sélectionner {input}", + "dialog.step": "Étape", "document.save_changes": "Enregistrer les modifications de {name} ?", "document.unsaved_changes": "{name} contient des modifications non enregistrées. Si vous n'enregistrez pas, elles seront perdues.", + "drive.stopped_by_contact": "Arrêté à {value} : {a} traverserait {b}", + "drive.stopped_by_loop": "Arrêté à {value} : la boucle passant par {joint} ne peut plus se fermer", + "drive.unconnected": "Rien ne bouge : {part} n'est relié à rien de fixé", + "expression, e.g. 25 mm": "expression, par ex. 25 mm", + "fits the face, e.g. M8": "adapté à la face, par ex. M8", + "from the rule": "selon la règle", "home.documentation": "Documentation", "home.in_this_browser": "dans ce navigateur", "home.missing": "introuvable", @@ -327,6 +615,76 @@ "home.report_issue": "Signaler un problème", "home.samples": "Exemples", "home.whats_new": "Nouveautés", + "install.button_tip": "Installer SolidCraft comme une app : il s'ouvre dans sa propre fenêtre et fonctionne hors ligne", + "install.dock_1": "Choisissez Fichier › Ajouter au Dock.", + "install.dock_2": "Cliquez sur Ajouter.", + "install.dock_after": "SolidCraft s'ouvre ensuite dans sa propre fenêtre depuis le Dock, et fonctionne hors ligne.", + "install.done": "Terminé", + "install.home_screen_1": "Touchez Partager (dans le menu … s'il n'est pas dans la barre d'outils).", + "install.home_screen_2": "Choisissez Sur l'écran d'accueil.", + "install.home_screen_3": "Touchez Ajouter.", + "install.home_screen_after": "SolidCraft s'ouvre ensuite depuis son icône sur l'écran d'accueil, sans les barres de Safari, et fonctionne hors ligne.", + "install.menu": "Installer l'app…", + "install.steps_intro": "Safari installe les apps web depuis ses propres menus :", + "install.title": "Installer SolidCraft", + "joint.from_bodies_hint": "Chaque corps sélectionné passe dans un nouveau composant à lui et reste où il est.", + "joint.one_body": "Les deux sélections sont sur {body}. Choisissez la seconde sur une autre pièce.", + "joint.one_component": "Ces pièces sont des corps d'un même composant : {bodies}. Une liaison déplace un composant par rapport à un autre, chaque pièce a donc besoin de son propre composant.", + "nav.touchpad.help": "Maintenir Maj et déplacer le pointeur pour faire un panoramique ; maintenir Alt/Option et le déplacer pour orbiter. Aucun bouton de souris n'est nécessaire. Le défilement vertical zoome.", + "nav.touchpad.label": "Pavé tactile", + "nav.touchpad.orbit": "Orbite (maintenir Alt/Option et déplacer ; sans bouton de souris)", + "nav.touchpad.pan": "Panoramique (maintenir Maj et déplacer ; sans bouton de souris)", + "nav.touchpad.scroll": "Le pavé tactile zoome avec le défilement vertical. Votre réglage de panoramique à deux doigts est conservé pour les autres préréglages.", + "nav.touchpad.zoom": "Zoom (défilement vertical ou pincement)", + "needs two joints": "nécessite deux liaisons", + "new configuration": "nouvelle configuration", + "new name": "nouveau nom", + "new parameter": "nouveau paramètre", + "no interference": "aucune interférence", + "no joint that moves yet": "aucune liaison mobile pour l'instant", + "no picture": "aucune image", + "pick a hole to seat it, or OK places it at the origin": "choisir un trou pour la loger, ou OK la place à l'origine", + "pick one or two vertices, edges or faces": "choisir un ou deux sommets, arêtes ou faces", + "render.background": "Arrière-plan de la scène", + "render.fit": "Cadrer le produit", + "render.image_cancel": "Annuler le rendu", + "render.image_cancelled": "Rendu annulé", + "render.image_cancelling": "Annulation", + "render.image_check": "Vérifier la demande de rendu", + "render.image_completed": "Image prête à exporter", + "render.image_encoding": "Encodage du PNG", + "render.image_export": "Exporter en PNG", + "render.image_failed": "Échec du rendu", + "render.image_height": "Hauteur", + "render.image_help": "Image d'aperçu CPU · PNG · transparence approximative", + "render.image_overwrite": "Remplacer le fichier existant", + "render.image_preparing": "Préparation de l'image", + "render.image_queued": "En attente de rendu", + "render.image_reduce": "Essayez une image plus petite ou une scène plus simple.", + "render.image_running": "Rendu de l'image", + "render.image_stale": "Cette image utilise la scène capturée avant les dernières modifications.", + "render.image_start": "Lancer le rendu", + "render.image_supported": "La demande de rendu est prise en charge ; la file d'attente et la réserve de mémoire seront revérifiées au lancement.", + "render.image_title": "Image de rendu", + "render.image_too_large": "Au-delà de la limite d'image : 4096 pixels par côté et 4 194 304 pixels au total.", + "render.image_transparent": "Arrière-plan transparent", + "render.image_unknown": "État du rendu indisponible", + "render.image_use_largest": "Utiliser la plus grande taille à ce format :", + "render.image_width": "Largeur", + "render.navigation_help": "La caméra se déplace comme dans Conception (Préférences › Navigation). Enregistrer le préréglage mémorise la caméra actuelle.", + "render.opaque_image_summary": "PNG d'aperçu · PBR opaque · transparence mélangée", + "render.opaque_preview_help": "PBR opaque et couleurs simples ; transparence mélangée. La réfraction, l'HDRI et le rendu final ne sont pas encore disponibles.", + "render.perspective": "Caméra en perspective", + "render.preview": "Aperçu intégré", + "render.preview_help": "Ombrage par rastérisation et transparence mélangée. La réfraction, l'HDRI et le rendu final ne sont pas encore disponibles.", + "render.reload_settings": "Recharger les réglages enregistrés", + "render.restore_camera": "Restaurer la caméra enregistrée", + "render.return_design": "Revenir à la conception", + "render.save_setup": "Enregistrer le préréglage", + "render.setup_name": "Nom du préréglage", + "render.unavailable_preview": "Ce préréglage demande un profil d'aperçu indisponible.", + "render.unsaved": "Modifications de l'aperçu non enregistrées", + "render.use_preview": "Utiliser l'aperçu intégré", "sample.bracket.about": "Tôle de base avec bords tombés et un ourlet, selon une règle de 2 mm", "sample.bracket.name": "Équerre en tôle", "sample.enclosure.about": "Boîte en coque avec lèvre, bossages de vis, appui et clip", @@ -339,14 +697,41 @@ "sample.plate.name": "Plaque d'exemple", "sample.vents.about": "Rainures en réseau rectangulaire : lignes, colonnes et pas sont des paramètres", "sample.vents.name": "Plaque d'aération", + "settings.display_quality_note": "Les niveaux plus fins affichent plus lisses les faces et arêtes courbes, mais leur maillage prend plus de temps. Seule la vue change, jamais la conception ni les exports.", + "settings.measure_axis_distances": "Afficher les cotes X/Y/Z", + "settings.measure_axis_distances_help": "Afficher les cotes suivant les axes du repère global en plus de la distance totale pendant la mesure.", "settings.msaa_applies_on_restart": "L'anticrénelage s'appliquera au prochain démarrage de SolidCraft", "settings.msaa_reset": "{setting} : {requested}× n'est pas pris en charge par ce périphérique graphique ; la valeur est désormais {reset}× (pris en charge : {supported}).", "settings.msaa_unsupported": "Non pris en charge par ce périphérique graphique", "settings.reset_intro": "Ces réglages ne fonctionnent pas sur cet ordinateur et empêcheraient SolidCraft de démarrer ; ils ont donc été modifiés :", "settings.reset_title": "Des réglages ont été modifiés", + "settings.supersampling_note": "Dessine la vue à une résolution plus élevée puis la réduit : arêtes, lignes et grille plus lisses sur les écrans de définition inférieure à la 4K. Cela coûte du temps GPU : environ 2,25× plus de pixels à 1,5× et 4× plus à 2×.", "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_text.align_center": "Centre", + "sketch_text.align_left": "Gauche", + "sketch_text.align_right": "Droite", + "sketch_text.bold": "Gras", + "sketch_text.builtin_font": "{family} (intégrée)", + "sketch_text.font_search": "Rechercher des polices", + "sketch_text.italic": "Italique", + "sketch_text.loading_fonts": "Recherche des polices installées…", + "sketch_text.on_path": "Le texte suit sa trajectoire : la courbe le positionne", + "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}", + "the parts library is not available": "la bibliothèque de pièces n'est pas disponible", + "timeline.group": "Nouveau dossier de fonctions", + "timeline.move_many": "Déplacer des éléments de la chronologie", + "timeline.move_to_group": "Déplacer les fonctions vers le dossier", + "timeline.rename_group": "Renommer le dossier de fonctions", + "timeline.reorder_many": "Réordonner les fonctions", + "timeline.ungroup": "Supprimer les dossiers de fonctions", + "to the next face": "jusqu'à la face suivante", + "toolbar.image": "IMAGE", + "toolbar.render": "RENDU", + "toolbar.render_scene": "SCÈNE", "ui.1_degree_of_freedom": "1 degré de liberté", "ui.3d_mouse_speed": "Vitesse de la souris 3D", "ui.3d_mouse_windows": "Souris 3D", @@ -360,20 +745,11 @@ "ui.analysis": "Analyse", "ui.angle": "Angle", "ui.angle_decimals": "Décimales des angles", + "ui.animateJoint": "Animer la liaison", "ui.animate_view_changes": "Animer les changements de vue", "ui.animation": "Animation", "ui.animation_speed": "Vitesse d'animation", "ui.anti_aliasing": "Anticrénelage", - "ui.supersampling": "Suréchantillonnage (SSAA)", - "ui.supersampling_off": "Désactivé (1×)", - "ui.supersampling_adaptive": "Seulement quand la vue est immobile", - "settings.supersampling_note": "Dessine la vue à une résolution plus élevée puis la réduit : arêtes, lignes et grille plus lisses sur les écrans de définition inférieure à la 4K. Cela coûte du temps GPU : environ 2,25× plus de pixels à 1,5× et 4× plus à 2×.", - "ui.display_quality": "Qualité d'affichage", - "ui.display_quality_coarse": "Grossière", - "ui.display_quality_normal": "Normale", - "ui.display_quality_fine": "Fine", - "ui.display_quality_ultra": "Ultra", - "settings.display_quality_note": "Les niveaux plus fins affichent plus lisses les faces et arêtes courbes, mais leur maillage prend plus de temps. Seule la vue change, jamais la conception ni les exports.", "ui.apply": "Appliquer", "ui.arc": "Arc", "ui.assemble": "Assembler", @@ -381,9 +757,11 @@ "ui.axes": "Axes", "ui.axis": "Axe", "ui.base_point": "Point de base", + "ui.blocked": "Inaccessible", "ui.bodies": "Corps", "ui.box": "Boîte", "ui.break": "Fractionner", + "ui.calibrate": "Étalonner", "ui.cancel": "Annuler", "ui.canvases": "Canevas", "ui.center": "Centre", @@ -393,8 +771,6 @@ "ui.chamfer_type": "Type de chanfrein", "ui.change_workspace": "Changer d'espace de travail", "ui.chord_length": "Longueur de corde", - "ui.curvature_g2": "Courbure (G2)", - "ui.equivalent_radius": "Rayon équivalent", "ui.circle": "Cercle", "ui.circular_pattern": "Réseau circulaire", "ui.clear": "Effacer", @@ -403,28 +779,6 @@ "ui.click_selects_whole_bodies": "Un clic sélectionne des corps entiers", "ui.click_then_press_key": "Cliquer, puis appuyer sur la nouvelle touche", "ui.close": "Fermer", - "ui.material_review.title": "Examiner les données physiques du matériau", - "ui.material_review.scope": "Candidat uniquement : ni attribué ni enregistré. La validation numérique ne constitue pas une certification technique.", - "ui.material_review.input": "Coller une fiche matériau de schéma 1 (JSON)", - "ui.material_review.review": "Examiner la fiche", - "ui.material_review.limit": "La fiche dépasse la limite de saisie de 256 Kio.", - "ui.material_review.unknown": "Inconnu", - "ui.material_review.properties": "Propriétés", - "ui.material_review.conditions": "Conditions déclarées", - "ui.material_review.source": "Source", - "ui.material_review.axes": "Axes locaux au matériau ; aucune orientation du corps attribuée.", - "ui.material_review.derived": "Modules isotropes dérivés", - "ui.material_review.claims": "Les sources et licences sont des déclarations non vérifiées. Les valeurs absentes restent inconnues.", - "ui.material_review.density": "Masse volumique", - "ui.material_review.elasticity": "Élasticité", - "ui.material_review.tensile_strength": "Résistance à la traction", - "ui.material_review.compressive_strength": "Résistance à la compression", - "ui.material_review.yield_strength": "Limite élastique", - "ui.material_review.shear_strength": "Résistance au cisaillement", - "ui.material_review.thermal_conductivity": "Conductivité thermique", - "ui.material_review.thermal_expansion": "Dilatation thermique", - "ui.material_review.specific_heat": "Capacité thermique massique", - "ui.material_review.moisture_unit": "kg eau / kg matériau sec", "ui.coil": "Hélice", "ui.coincident": "Coïncidence", "ui.collapse": "Réduire", @@ -446,6 +800,8 @@ "ui.colour_vision_tritan_tip": "Pour une perception du bleu faible ou absente", "ui.combine": "Combiner", "ui.coming_later": "bientôt disponible", + "ui.command_done": "{command} terminé", + "ui.command_palette_hint": "Tapez une commande, ex. {example} — ou S pour chercher", "ui.concentric": "Concentricité", "ui.configurations": "Configurations", "ui.conic_curve": "Courbe conique", @@ -464,7 +820,11 @@ "ui.create_sketch": "Créer une esquisse", "ui.current": "actuel", "ui.curvature": "Courbure", + "ui.curvature_g2": "Courbure (G2)", "ui.curves": "Courbes", + "ui.custom_program": "Personnalisé…", + "ui.custom_program_tip": "Choisir un slicer à ajouter à la liste", + "ui.customizeToolbar": "Personnaliser la barre d'outils…", "ui.cut": "Couper", "ui.cylinder": "Cylindre", "ui.dark": "Sombre", @@ -473,9 +833,25 @@ "ui.delete": "Supprimer", "ui.depth": "Profondeur", "ui.design": "Conception", + "ui.design_properties.author": "Auteur", + "ui.design_properties.description": "Description", + "ui.design_properties.exports": "Les exports STEP, IGES et 3MF les incluent quand le format le permet.", + "ui.design_properties.license": "Licence", + "ui.design_properties.not_text": "Enregistré sous une autre forme que du texte ; une saisie ici le remplace.", + "ui.design_properties.organization": "Organisation", + "ui.design_properties.others": "Données d'autres logiciels", + "ui.design_properties.others_note": "Conservées telles quelles dans la conception et jamais exportées.", + "ui.design_properties.part_number": "Référence", + "ui.design_properties.project": "Projet", + "ui.design_properties.revision": "Indice", "ui.diameter": "Diamètre", "ui.dimension": "Cote", "ui.direction": "Direction", + "ui.display_quality": "Qualité d'affichage", + "ui.display_quality_coarse": "Grossière", + "ui.display_quality_fine": "Fine", + "ui.display_quality_normal": "Normale", + "ui.display_quality_ultra": "Ultra", "ui.distance": "Distance", "ui.distance_1": "Distance 1", "ui.distance_2": "Distance 2", @@ -485,12 +861,16 @@ "ui.drawing": "Mise en plan", "ui.drill_point": "Pointe de foret", "ui.edit": "Modifier", + "ui.editJointLimits": "Modifier les limites de liaison", "ui.edit_section_analysis": "Modifier l'analyse de coupe", "ui.ellipse": "Ellipse", "ui.end_radius": "Rayon final", + "ui.end_scale": "Échelle finale", "ui.entities": "Entités", "ui.equal": "Égalité", + "ui.equivalent_radius": "Rayon équivalent", "ui.expand": "Développer", + "ui.exportDxf": "Exporter en DXF…", "ui.export_ellipsis": "Exporter...", "ui.export_ellipsis_keymap": "Exporter…", "ui.export_keymap_tip": "Raccourcis, favoris de la boîte S et barre d'outils, dans un fichier", @@ -504,15 +884,20 @@ "ui.file": "Fichier", "ui.fillet": "Congé", "ui.filter_commands_or_keys": "Filtrer les commandes ou les touches", + "ui.findInTimeline": "Trouver dans la chronologie", + "ui.findInWindow": "Trouver dans la fenêtre", "ui.finish_sketch": "Terminer l'esquisse", + "ui.fit": "Cadrer", "ui.fix_unfix": "Fixer/Libérer", "ui.flat": "Plat", "ui.flip": "Inverser", + "ui.format": "Format", "ui.front": "Avant", "ui.fully_constrained": "Entièrement contrainte", "ui.general": "Général", "ui.graphics": "Graphisme", "ui.ground_shadow": "Ombre au sol", + "ui.groupSelected": "Grouper la sélection", "ui.heading_add_ins": "COMPLÉMENTS", "ui.heading_assemble": "ASSEMBLER", "ui.heading_box": "BOÎTE", @@ -544,8 +929,8 @@ "ui.heading_mirror": "SYMÉTRIE", "ui.heading_modify": "MODIFIER", "ui.heading_move": "DÉPLACER", - "ui.heading_offset": "DÉCALAGE", "ui.heading_move_copy": "DÉPLACER/COPIER", + "ui.heading_offset": "DÉCALAGE", "ui.heading_offset_plane": "PLAN DÉCALÉ", "ui.heading_ok": "OK", "ui.heading_parameters": "PARAMÈTRES", @@ -553,13 +938,16 @@ "ui.heading_pipe": "TUYAU", "ui.heading_plane_at_angle": "PLAN INCLINÉ", "ui.heading_plastic": "PLASTIQUE", + "ui.heading_position": "POSITION", "ui.heading_prepare": "PRÉPARER", "ui.heading_rectangular_pattern": "RÉSEAU RECTANGULAIRE", "ui.heading_revolve": "RÉVOLUTION", "ui.heading_right": "DROITE", + "ui.heading_save_mesh": "ENREGISTRER COMME MAILLAGE", "ui.heading_scale": "ÉCHELLE", "ui.heading_section_analysis": "ANALYSE DE COUPE", "ui.heading_select": "SÉLECTIONNER", + "ui.heading_setup": "RÉGLAGES", "ui.heading_sheet_metal": "TÔLERIE", "ui.heading_shell": "COQUE", "ui.heading_sketch": "ESQUISSE", @@ -577,15 +965,22 @@ "ui.heading_utility": "UTILITAIRE", "ui.help": "Aide", "ui.hide": "Masquer", + "ui.hideAxes": "Masquer les axes", + "ui.hideDimension": "Masquer la cote", + "ui.hideOrigin": "Masquer l'origine", + "ui.hidePlanes": "Masquer les plans", + "ui.hideProfile": "Masquer le profil", "ui.hole": "Perçage", "ui.hole_tap_type": "Type de taraudage", "ui.hole_type": "Type de perçage", "ui.home": "Accueil", + "ui.homeView": "Vue d'accueil", "ui.horizontal_vertical": "Horizontale/Verticale", "ui.import_ellipsis": "Importer…", "ui.insert": "Insérer", "ui.inspect": "Inspecter", "ui.intersect": "Intersection", + "ui.isolate": "Isoler", "ui.join": "Joindre", "ui.joints": "Liaisons", "ui.keyboard_shortcuts": "Raccourcis clavier", @@ -594,11 +989,37 @@ "ui.light": "Clair", "ui.line": "Ligne", "ui.linetype": "Type de ligne", + "ui.lock": "Verrouiller", "ui.loft": "Lissage", "ui.look_at": "Vue normale", "ui.look_at_anim_desc": "Vue d'axe, Vue normale, Accueil et Cadrer", "ui.manufacture": "Fabrication", + "ui.material_review.axes": "Axes locaux au matériau ; aucune orientation du corps attribuée.", + "ui.material_review.claims": "Les sources et licences sont des déclarations non vérifiées. Les valeurs absentes restent inconnues.", + "ui.material_review.compressive_strength": "Résistance à la compression", + "ui.material_review.conditions": "Conditions déclarées", + "ui.material_review.density": "Masse volumique", + "ui.material_review.derived": "Modules isotropes dérivés", + "ui.material_review.elasticity": "Élasticité", + "ui.material_review.input": "Coller une fiche matériau de schéma 1 (JSON)", + "ui.material_review.limit": "La fiche dépasse la limite de saisie de 256 Kio.", + "ui.material_review.moisture_unit": "kg eau / kg matériau sec", + "ui.material_review.properties": "Propriétés", + "ui.material_review.review": "Examiner la fiche", + "ui.material_review.scope": "Candidat uniquement : ni attribué ni enregistré. La validation numérique ne constitue pas une certification technique.", + "ui.material_review.shear_strength": "Résistance au cisaillement", + "ui.material_review.source": "Source", + "ui.material_review.specific_heat": "Capacité thermique massique", + "ui.material_review.tensile_strength": "Résistance à la traction", + "ui.material_review.thermal_conductivity": "Conductivité thermique", + "ui.material_review.thermal_expansion": "Dilatation thermique", + "ui.material_review.title": "Examiner les données physiques du matériau", + "ui.material_review.unknown": "Inconnu", + "ui.material_review.yield_strength": "Limite élastique", "ui.measure": "Mesurer", + "ui.mesh_format_3mf": "3MF", + "ui.mesh_format_3mf_tagged": "3MF avec étiquettes de faces", + "ui.mesh_format_stl": "STL", "ui.midpoint": "Point milieu", "ui.mirror": "Symétrie", "ui.mirror_line": "Ligne de symétrie", @@ -608,9 +1029,13 @@ "ui.named_views": "Vues nommées", "ui.navigation": "Navigation", "ui.needs_design": "{command} : ouvrez d'abord une conception", + "ui.newSketchGroup": "Nouveau groupe d'esquisses", "ui.new_body": "Nouveau corps", "ui.new_design": "Nouvelle conception", + "ui.no_slicer_found": "Aucun slicer trouvé", "ui.normal": "Normal", + "ui.normalConstruction": "Normal / Construction", + "ui.not_a_program": "{path} n'est pas un programme exécutable", "ui.object_type": "Type d'objet", "ui.objects": "Objets", "ui.offer_to_stand_up_y_up_files": "Proposer de redresser les fichiers Y vers le haut", @@ -623,10 +1048,13 @@ "ui.open_recent": "Ouvrir un fichier récent", "ui.operation": "Opération", "ui.options": "Options", + "ui.orbit": "Orbite", "ui.orbit_around": "Orbite autour de", + "ui.orientation": "Orientation", "ui.origin": "Origine", "ui.palette_points": "Points", "ui.palette_profile": "Profil", + "ui.pan": "Panoramique", "ui.pan_zoom_orbit": "Panoramique, zoom, orbite", "ui.parallel": "Parallélisme", "ui.parameters": "Paramètres", @@ -635,6 +1063,8 @@ "ui.pattern_on_path": "Réseau sur trajectoire", "ui.perpendicular": "Perpendicularité", "ui.perspective_view": "Vue en perspective", + "ui.pinToShortcuts": "Épingler aux raccourcis", + "ui.pinToToolbar": "Épingler à la barre d'outils", "ui.pipe": "Tuyau", "ui.placement": "Placement", "ui.plane": "Plan", @@ -650,63 +1080,59 @@ "ui.profiles": "Profils", "ui.project": "Projeter", "ui.project_face_edges_sketch": "Projeter les arêtes de la face dans les nouvelles esquisses", + "ui.properties": "Propriétés", + "ui.pull_direction": "Direction de démoulage", "ui.quantity": "Quantité", "ui.quantity_2": "Quantité 2", "ui.quit": "Quitter", "ui.radial_context_menu": "Menu contextuel radial", "ui.radius": "Rayon", - "ui.pull_direction": "Direction de démoulage", - "ui.tool_direction": "Direction de l'outil", - "ui.reachable": "Accessible", - "ui.blocked": "Inaccessible", "ui.radius_type": "Type de rayon", + "ui.reachable": "Accessible", "ui.rectangle": "Rectangle", "ui.rectangular_pattern": "Réseau rectangulaire", "ui.redo": "Rétablir", + "ui.removeFromToolbar": "Retirer de la barre d'outils", + "ui.removeSection": "Retirer la coupe", "ui.render": "Rendu", "ui.renderer": "Moteur de rendu", + "ui.repeat": "Répéter", + "ui.report_a_bug": "Signaler un bug", "ui.reset": "Réinitialiser", "ui.reset_all": "Tout réinitialiser", "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_zoom_direction": "Inverser le sens du zoom", "ui.revolve": "Révolution", "ui.right": "Droite", "ui.save": "Enregistrer", - "ui.heading_save_mesh": "ENREGISTRER COMME MAILLAGE", - "ui.format": "Format", - "ui.mesh_format_stl": "STL", - "ui.mesh_format_3mf": "3MF", - "ui.mesh_format_3mf_tagged": "3MF avec étiquettes de faces", - "ui.send_to_slicer": "Envoyer au slicer", - "ui.slicer": "Slicer", - "ui.custom_program": "Personnalisé…", - "ui.no_slicer_found": "Aucun slicer trouvé", - "ui.send": "Envoyer", - "ui.custom_program_tip": "Choisir un slicer à ajouter à la liste", - "ui.slicer_delete_tip": "{program}\nAppuyer sur Suppr pour le retirer de la liste", - "ui.save_mesh_pick_bodies": "Sélectionner les corps à enregistrer", - "ui.save_mesh_no_slicer": "Aucun slicer trouvé : choisissez Personnalisé… et sélectionnez votre slicer, ou désactivez Envoyer au slicer", - "ui.not_a_program": "{path} n'est pas un programme exécutable", - "ui.sent_to_slicer": "Envoyé à {slicer}", - "ui.saved_to": "Enregistré : {path}", - "ui.save_mesh_temp_failed": "Impossible de créer {folder} : {error}", "ui.save_as": "Enregistrer sous", "ui.save_as_ellipsis": "Enregistrer sous...", + "ui.save_mesh_no_slicer": "Aucun slicer trouvé : choisissez Personnalisé… et sélectionnez votre slicer, ou désactivez Envoyer au slicer", + "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.scale": "Échelle", - "ui.orientation": "Orientation", - "ui.twist": "Torsion", - "ui.end_scale": "Échelle finale", - "ui.sweep_turn_with_path": "Tourner avec la trajectoire", - "ui.sweep_keep_as_drawn": "Garder tel que dessiné", - "ui.sweep_follow_direction": "Suivre une direction", "ui.section_analysis": "Analyse de coupe", "ui.select": "Sélectionner", + "ui.selectOther": "Sélectionner un autre…", + "ui.selectTangentChain": "Sélectionner la chaîne tangente", "ui.select_other_hint": "Sélectionner un autre élément : maintenir le bouton gauche immobile sur le modèle (ou clic droit › Sélectionner un autre…) pour lister tout ce qui se trouve sous le curseur ; cliquer de nouveau au même endroit pour sélectionner l'élément suivant.", "ui.selection": "Sélection", + "ui.send": "Envoyer", + "ui.send_to_slicer": "Envoyer au slicer", + "ui.sent_to_slicer": "Envoyé à {slicer}", "ui.shell": "Coque", "ui.show": "Afficher", + "ui.showAll": "Tout afficher", + "ui.showAllBodies": "Afficher tous les corps", + "ui.showAxes": "Afficher les axes", + "ui.showDimension": "Afficher la cote", + "ui.showOrigin": "Afficher l'origine", + "ui.showPlanes": "Afficher les plans", "ui.show_constraints": "Contraintes", + "ui.show_construction_geometries": "Géométries de construction", "ui.show_dimensions": "Cotes", "ui.show_points": "Afficher les points", "ui.show_profile": "Afficher le profil", @@ -721,6 +1147,8 @@ "ui.sketch_status": "État de l'esquisse", "ui.sketches": "Esquisses", "ui.slice": "Trancher", + "ui.slicer": "Slicer", + "ui.slicer_delete_tip": "{program}\nAppuyer sur Suppr pour le retirer de la liste", "ui.slot": "Rainure", "ui.smooth": "Lisse", "ui.smooth_wheel_zoom": "Zoom fluide à la molette", @@ -736,7 +1164,14 @@ "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_radius": "Rayon initial", + "ui.supersampling": "Suréchantillonnage (SSAA)", + "ui.supersampling_adaptive": "Seulement quand la vue est immobile", + "ui.supersampling_off": "Désactivé (1×)", + "ui.suppress": "Désactiver", "ui.sweep": "Balayage", + "ui.sweep_follow_direction": "Suivre une direction", + "ui.sweep_keep_as_drawn": "Garder tel que dessiné", + "ui.sweep_turn_with_path": "Tourner avec la trajectoire", "ui.symmetric": "Symétrique", "ui.symmetry": "Symétrie", "ui.system": "Système", @@ -752,18 +1187,26 @@ "ui.timeline_left_sidebar": "Barre latérale gauche", "ui.tip_angle": "Angle de pointe", "ui.to_object": "Jusqu'à l'objet", + "ui.tool_direction": "Direction de l'outil", "ui.top": "Dessus", "ui.torus": "Tore", + "ui.total_angle": "Angle total", "ui.trackpad_pan_tip": "Les gestes du pavé tactile font un panoramique (désactivé : ils zooment comme la molette) ; la molette zoome, la molette latérale fait un panoramique horizontal, le pincement zoome toujours", "ui.trim": "Ajuster", + "ui.twist": "Torsion", "ui.two_finger_scroll_pans": "Défilement à deux doigts pour le panoramique", "ui.two_sides": "Deux côtés", "ui.ui_scale": "Échelle de l'interface", "ui.undo": "Annuler", + "ui.unground": "Libérer", + "ui.unisolate": "Annuler l'isolement", "ui.units": "Unités", "ui.units_of_new_designs": "Unités des nouvelles conceptions", + "ui.unlock": "Déverrouiller", + "ui.unsuppress": "Réactiver", "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", "ui.variable": "Variable", "ui.view_centre": "Centre de la vue", "ui.visual_shaded_hidden_edges": "Ombré avec arêtes cachées", @@ -775,486 +1218,41 @@ "ui.y_distance": "Distance Y", "ui.y_up": "Y vers le haut", "ui.z_up": "Z vers le haut", + "ui.zoom": "Zoom", "ui.zoom_to_cursor_tip": "La molette zoome vers le point sous le curseur (désactivé : vers le centre de la vue)", "ui.zoom_to_the_cursor": "Zoom vers le curseur", - "A new configuration, a copy of the active one": "Nouvelle configuration, copie de la configuration active", - "About SolidCraft": "À propos de SolidCraft", - "Active": "Actif", - "Active rule": "Règle active", - "Add": "Ajouter", - "Add Key": "Ajouter une image clé", - "Add Mid Radius": "Ajouter un rayon intermédiaire", - "Add Row": "Ajouter une ligne", - "All Sketch Points": "Tous les points d'esquisse", - "All open designs": "Toutes les conceptions ouvertes", - "Allowed expressions, separated by semicolons": "Expressions autorisées, séparées par des points-virgules", - "Also deletes": "Supprime aussi", - "Angle 2": "Angle 2", - "Animate": "Animer", - "Appearance name": "Nom de l'apparence", - "Applied Radius": "Rayon appliqué", - "Apply To": "Appliquer à", - "Area": "Aire", - "Attachment": "Rattachement", - "BROWSER": "NAVIGATEUR", - "Bend Line Position": "Position de la ligne de pli", - "Bend Position": "Position du pli", - "Bend Radius": "Rayon de pliage", - "Bends": "Plis", - "Body": "Corps", - "Bounding box": "Boîte englobante", - "CSV or JSON: updates existing parameters, adds new ones": "CSV ou JSON : met à jour les paramètres existants, ajoute les nouveaux", - "Capture All Positions": "Capturer toutes les positions", - "Catch Direction": "Direction de l'ergot", - "Cells": "Cellules", - "Center X": "Centre X", - "Center Y": "Centre Y", - "Center of mass": "Centre de gravité", - "Chamfer Type": "Type de chanfrein", - "Check collisions": "Vérifier les collisions", - "Checked": "Vérifié", - "Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.": "Choisir un nouveau plan. La géométrie et les cotes de l'esquisse restent inchangées dans ses coordonnées bidimensionnelles.", - "Close draft": "Fermer le brouillon", - "Collisions": "Collisions", - "Colour": "Couleur", - "Component1": "Composant1", - "Configuration": "Configuration", - "Configuration rules": "Règles de configuration", - "Contact": "Contact", - "Copy all licences": "Copier toutes les licences", - "Copy diagnostic information": "Copier les informations de diagnostic", - "Copy report": "Copier le rapport", - "Corner Relief": "Dégagement d'angle", - "Corner Relief Shape": "Forme du dégagement d'angle", - "Notch": "Encoche", - "Round": "Rond", - "Rectangular": "Rectangulaire", - "Tear": "Déchirure", - "Counterbore depth": "Profondeur du lamage", - "Countersink angle": "Angle de la fraisure", - "Create Issue — review draft": "Créer un ticket — relire le brouillon", - "Customize Toolbar": "Personnaliser la barre d'outils", - "Delete all": "Tout supprimer", - "Delete rule": "Supprimer la règle", - "Delete the row": "Supprimer la ligne", - "Delete the set": "Supprimer le jeu", - "Delete this parameter": "Supprimer ce paramètre", - "Density": "Masse volumique", - "Designs you open or save appear here.": "Les conceptions que vous ouvrez ou enregistrez apparaissent ici.", - "Determined by To Object. Choose Angle to edit the angular extent.": "Déterminé par Jusqu'à l'objet. Choisir Angle pour modifier l'étendue angulaire.", - "Discard": "Abandonner", - "Double-click to rename": "Double-cliquer pour renommer", - "Drive Joint": "Piloter la liaison", - "Edit Profile Sketch": "Modifier l'esquisse du profil", - "Enable rule": "Activer la règle", - "Enabled": "Activé", - "Explode": "Éclater", - "Extents": "Étendues", - "Face attachment lost": "Rattachement à la face perdu", - "Faces / edges / vertices": "Faces / arêtes / sommets", - "Favourite": "Favori", - "Files from many CAD programs have Y up, so they open lying on their back here (Z up).": "Les fichiers de nombreux logiciels de CAO ont Y vers le haut : ils s'ouvrent donc couchés ici (Z vers le haut).", - "Filter": "Filtrer", - "Find in Browser": "Trouver dans le navigateur", - "Copy Error Message": "Copier le message d'erreur", - "Copy Warning Message": "Copier le message d'avertissement", - "Flat size": "Dimensions à plat", - "Follow camera (Look At sketches)": "Suivre la caméra (vue normale aux esquisses)", - "Font": "Police", - "Full Length": "Longueur totale", - "Gap": "Jeu", - "Grid": "Grille", - "Height": "Hauteur", - "Home view": "Vue d'accueil", - "In This Design": "Dans cette conception", - "Interferes": "Interfère", - "Issue title": "Titre du ticket", - "Joint Origin1": "Origine de liaison1", - "Keep Tools": "Conserver les outils", - "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.", - "Length": "Longueur", - "Length units": "Unités de longueur", - "Library": "Bibliothèque", - "Loop": "Boucle", - "Margin": "Marge", - "Mass": "Masse", - "Material": "Matériau", - "Mid Radius": "Rayon intermédiaire", - "Modeled": "Modélisé", - "More toolbar panels": "Autres groupes de la barre d'outils", - "Motion": "Mouvement", - "Move Type": "Type de déplacement", - "Move earlier": "Déplacer plus tôt", - "Move later": "Déplacer plus tard", - "Name": "Nom", - "No crash reports.": "Aucun rapport de plantage.", - "No matching appearances": "Aucune apparence correspondante", - "Not available yet": "Pas encore disponible", - "Opacity": "Opacité", - "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é", - "Parameter values": "Valeurs des paramètres", - "Per Edge": "Par arête", - "Pick the tool bodies": "Choisir les corps outils", - "Place at the origin instead": "Placer plutôt à l'origine", - "Playback": "Lecture", - "Position": "Position", - "Position (0 to 1)": "Position (0 à 1)", - "Position along the edge, 0 at the start end, 1 at the other": "Position le long de l'arête : 0 à l'extrémité de départ, 1 à l'autre", - "Preview leaves the current design unchanged.": "L'aperçu ne modifie pas la conception actuelle.", - "RECENT": "RÉCENTS", - "Radius Fit": "Ajustement du rayon", - "Ratio": "Rapport", - "Recover": "Récupérer", - "Recover unsaved design?": "Récupérer la conception non enregistrée ?", - "Remove Tools": "Retirer les outils", - "Remove from list": "Retirer de la liste", - "Remove private design details or paths before sharing.": "Retirez les détails privés de la conception et les chemins avant de partager.", - "Remove the column": "Retirer la colonne", - "Remove the track": "Retirer la piste", - "Remove this point": "Retirer ce point", - "Report a bug — review a screenshot and open a GitHub draft": "Signaler un bug — relire une capture d'écran et ouvrir un brouillon GitHub", - "Reset Toolbar": "Réinitialiser la barre d'outils", - "Restore the inherited component or physical material appearance": "Rétablir l'apparence héritée du composant ou du matériau physique", - "Result": "Résultat", - "Retake screenshot": "Reprendre la capture d'écran", - "Reverse": "Inverser", - "Reverse Direction": "Inverser la direction", - "Revert": "Rétablir", - "Revert All Positions": "Rétablir toutes les positions", - "Review the report and screenshot before opening GitHub.": "Relisez le rapport et la capture d'écran avant d'ouvrir GitHub.", - "Rim Edge": "Arête du bord", - "Roll History Marker Here": "Placer le marqueur d'historique ici", - "Rule": "Règle", - "Saved preview. Geometry is being checked before editing.": "Aperçu enregistré. La géométrie est en cours de vérification avant modification.", - "Scale factor": "Facteur d'échelle", - "Search": "Rechercher", - "Search commands": "Rechercher des commandes", - "Select bodies (a face picks its body)": "Sélectionner des corps (une face sélectionne son corps)", - "Select bodies or faces instead": "Sélectionner plutôt des corps ou des faces", - "Selection filter": "Filtre de sélection", - "Semantic faces share their appearance across instances.": "Les faces sémantiques partagent leur apparence entre les instances.", - "Shape": "Forme", - "Show Agent Cursor": "Afficher le curseur de l'agent", - "Show in folder": "Afficher dans le dossier", - "Size": "Taille", - "Sketch plane has no body-face attachment.": "Le plan d'esquisse n'est rattaché à aucune face de corps.", - "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft s'est fermé avant l'enregistrement de ces conceptions. Leur dernier enregistrement automatique peut être ouvert.", - "Speed": "Vitesse", - "Stand it up": "Redresser", - "Stand it up: a quarter turn about X, as one Move feature you can undo.": "Redresser : un quart de tour autour de X, sous forme d'une fonction Déplacer que vous pouvez annuler.", - "Stand this part up?": "Redresser cette pièce ?", - "Step": "Étape", - "Steps": "Étapes", - "Suppressed": "Désactivé", - "Swap Ends": "Permuter les extrémités", - "Tangent Chain": "Chaîne tangente", - "The dashed sketch is a saved plane guide. Select a new face to repair the attachment.": "L'esquisse en pointillés est un guide de plan enregistré. Sélectionnez une nouvelle face pour réparer le rattachement.", - "The saved author occurrence is missing. Select a valid author placement before rebinding.": "L'occurrence d'auteur enregistrée est introuvable. Sélectionnez un placement d'auteur valide avant de relier.", - "Then": "Alors", - "These features will be deleted:": "Ces fonctions seront supprimées :", - "These features will fail:": "Ces fonctions échoueront :", - "This child is shared. Deleting it removes it from every copy of its parent.": "Cet enfant est partagé. Le supprimer le retire de toutes les copies de son parent.", - "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", - "Tolerance": "Tolérance", - "Type": "Type", - "Updating the preview": "Mise à jour de l'aperçu", - "Use fixed plane": "Utiliser un plan fixe", - "VIEW": "VUE", - "Value": "Valeur", - "Volume": "Volume", - "Wall": "Paroi", - "When": "Quand", - "Width": "Largeur", - "Will fail": "Échouera", - "angle, height": "angle, hauteur", - "command name": "nom de la commande", - "expression, e.g. 25 mm": "expression, par ex. 25 mm", - "fits the face, e.g. M8": "adapté à la face, par ex. M8", - "from the rule": "selon la règle", - "needs two joints": "nécessite deux liaisons", - "new configuration": "nouvelle configuration", - "new name": "nouveau nom", - "new parameter": "nouveau paramètre", - "no interference": "aucune interférence", - "no joint that moves yet": "aucune liaison mobile pour l'instant", - "no picture": "aucune image", - "pick a hole to seat it, or OK places it at the origin": "choisir un trou pour la loger, ou OK la place à l'origine", - "pick one or two vertices, edges or faces": "choisir un ou deux sommets, arêtes ou faces", - "the parts library is not available": "la bibliothèque de pièces n'est pas disponible", - "to the next face": "jusqu'à la face suivante", - "Revert Position": "Rétablir la position", - "Construction": "Construction", - "Faces": "Faces", - "Edges": "Arêtes", - "Vertices": "Sommets", - "Sketch geometry and profiles": "Géométrie et profils d'esquisse", - "Sketch curves": "Courbes d'esquisse", - "Sketch points": "Points d'esquisse", - "Sketch dimensions": "Cotes d'esquisse", - "Sketch constraints": "Contraintes d'esquisse", - "0 turns it off": "0 le désactive", - "Show the pointer an AI agent moves (#35)": "Afficher le pointeur déplacé par un agent IA (#35)", - "Follow the camera (Look At sketches)": "Suivre la caméra (vue normale aux esquisses)", - "Flat": "Plat", - "Save Rule": "Enregistrer la règle", - "Preview Row": "Aperçu de la ligne", - "Add condition": "Ajouter une condition", - "Apply to selection": "Appliquer à la sélection", - "Remove override": "Retirer le remplacement", - "Copy screenshot": "Copier la capture d'écran", - "Remove screenshot": "Retirer la capture d'écran", - "Use active author placement": "Utiliser le placement d'auteur actif", - "Reattach selected face": "Rattacher la face sélectionnée", - "Use saved fixed plane": "Utiliser le plan fixe enregistré", - "Use selected face as fixed plane": "Utiliser la face sélectionnée comme plan fixe", - "View navigator": "Repère de navigation", - "Signed axes": "Axes signés", - "Cube": "Cube", - "Middle double-click": "Double-clic milieu", - "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": "Double-clic sur le bouton du milieu dans la vue : Accueil (vue d'accueil, cadrant ce qui est affiché), Cadrer (cadrer ce qui est affiché en gardant l'orientation) ou rien", - "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).": "Sélectionner un autre élément : maintenir le bouton gauche immobile sur le modèle (ou clic droit › Sélectionner un autre…) pour lister tout ce qui se trouve sous le curseur ; cliquer de nouveau au même endroit pour sélectionner l'élément suivant. Double-cliquer avec le bouton du milieu pour revenir à l'accueil (Préférences › Navigation).", - "cmd.render_backends": "Moteurs de rendu", - "cmd.view_navigate": "Naviguer dans la vue", - "ui.animateJoint": "Animer la liaison", - "ui.calibrate": "Étalonner", - "ui.customizeToolbar": "Personnaliser la barre d'outils…", - "ui.editJointLimits": "Modifier les limites de liaison", - "ui.exportDxf": "Exporter en DXF…", - "ui.findInTimeline": "Trouver dans la chronologie", - "ui.findInWindow": "Trouver dans la fenêtre", - "ui.fit": "Cadrer", - "ui.groupSelected": "Grouper la sélection", - "ui.hideAxes": "Masquer les axes", - "ui.hideDimension": "Masquer la cote", - "ui.hideOrigin": "Masquer l'origine", - "ui.hidePlanes": "Masquer les plans", - "ui.hideProfile": "Masquer le profil", - "ui.homeView": "Vue d'accueil", - "ui.isolate": "Isoler", - "ui.lock": "Verrouiller", - "ui.newSketchGroup": "Nouveau groupe d'esquisses", - "ui.normalConstruction": "Normal / Construction", - "ui.orbit": "Orbite", - "ui.heading_position": "POSITION", - "ui.pan": "Panoramique", - "ui.pinToShortcuts": "Épingler aux raccourcis", - "ui.pinToToolbar": "Épingler à la barre d'outils", - "ui.properties": "Propriétés", - "ui.design_properties.project": "Projet", - "ui.design_properties.part_number": "Référence", - "ui.design_properties.revision": "Indice", - "ui.design_properties.author": "Auteur", - "ui.design_properties.organization": "Organisation", - "ui.design_properties.description": "Description", - "ui.design_properties.license": "Licence", - "ui.design_properties.not_text": "Enregistré sous une autre forme que du texte ; une saisie ici le remplace.", - "ui.design_properties.exports": "Les exports STEP, IGES et 3MF les incluent quand le format le permet.", - "ui.design_properties.others": "Données d'autres logiciels", - "ui.design_properties.others_note": "Conservées telles quelles dans la conception et jamais exportées.", - "ui.removeSection": "Retirer la coupe", - "ui.removeFromToolbar": "Retirer de la barre d'outils", - "ui.repeat": "Répéter", - "ui.report_a_bug": "Signaler un bug", - "ui.restore": "Restaurer", - "ui.heading_setup": "RÉGLAGES", - "ui.selectOther": "Sélectionner un autre…", - "ui.selectTangentChain": "Sélectionner la chaîne tangente", - "ui.showAll": "Tout afficher", - "ui.showAllBodies": "Afficher tous les corps", - "ui.showAxes": "Afficher les axes", - "ui.showDimension": "Afficher la cote", - "ui.showOrigin": "Afficher l'origine", - "ui.showPlanes": "Afficher les plans", - "ui.suppress": "Désactiver", - "ui.command_palette_hint": "Tapez une commande, ex. {example} — ou S pour chercher", - "ui.unground": "Libérer", - "ui.unisolate": "Annuler l'isolement", - "ui.unlock": "Déverrouiller", - "ui.unsuppress": "Réactiver", - "ui.updateToCurrentView": "Mettre à jour avec la vue actuelle", - "ui.zoom": "Zoom", - "ui.command_done": "{command} terminé", - "drive.stopped_by_loop": "Arrêté à {value} : la boucle passant par {joint} ne peut plus se fermer", - "drive.stopped_by_contact": "Arrêté à {value} : {a} traverserait {b}", - "drive.unconnected": "Rien ne bouge : {part} n'est relié à rien de fixé", - "timeline.group": "Nouveau dossier de fonctions", - "timeline.ungroup": "Supprimer les dossiers de fonctions", - "timeline.rename_group": "Renommer le dossier de fonctions", - "timeline.move_to_group": "Déplacer les fonctions vers le dossier", - "timeline.move_many": "Déplacer des éléments de la chronologie", - "timeline.reorder_many": "Réordonner les fonctions", - "ui.show_construction_geometries": "Géométries de construction", - "ui.total_angle": "Angle total", - "sketch_text.builtin_font": "{family} (intégrée)", - "sketch_text.font_search": "Rechercher des polices", - "sketch_text.loading_fonts": "Recherche des polices installées…", - "sketch_text.use_font_file": "Utiliser le fichier de police {path}", - "sketch_text.bold": "Gras", - "sketch_text.italic": "Italique", - "sketch_text.align_left": "Gauche", - "sketch_text.align_center": "Centre", - "sketch_text.align_right": "Droite", - "sketch_text.path_hint": "Une courbe de l'esquisse que le texte suit : cliquer ici, puis sur la courbe", - "sketch_text.path_clear": "Détacher le texte de sa courbe", - "Style": "Style", - "Alignment": "Alignement", - "Letter Spacing": "Espacement des lettres", - "Line Spacing": "Interligne", - "Path": "Trajectoire", - "sketch_text.on_path": "Le texte suit sa trajectoire : la courbe le positionne", - "cmd.library_inspect": "Inspecter la bibliothèque locale", - "cmd.library_export": "Exporter la bibliothèque de la conception", - "cmd.library_apply": "Appliquer une entrée de la bibliothèque locale", - "Thin": "Mince", - "Thin Extrude": "Extrusion mince", - "Wall Location": "Position de la paroi", - "Wall Thickness": "Épaisseur de paroi", - "Thickness Outside": "Épaisseur extérieure", - "Inside": "Intérieur", - "Outside": "Extérieur", - "Profiles/Curves": "Profils/Courbes", - "cmd.material_properties_validate": "Valider les données du matériau physique", - "cmd.material_properties_directional": "Module d'élasticité directionnel", + "update.available": "SolidCraft {version} est disponible", "update.button": "Mettre à jour", "update.button_tip": "SolidCraft {version} est disponible", - "install.menu": "Installer l'app…", - "install.button_tip": "Installer SolidCraft comme une app : il s'ouvre dans sa propre fenêtre et fonctionne hors ligne", - "install.title": "Installer SolidCraft", - "install.steps_intro": "Safari installe les apps web depuis ses propres menus :", - "install.home_screen_1": "Touchez Partager (dans le menu … s'il n'est pas dans la barre d'outils).", - "install.home_screen_2": "Choisissez Sur l'écran d'accueil.", - "install.home_screen_3": "Touchez Ajouter.", - "install.home_screen_after": "SolidCraft s'ouvre ensuite depuis son icône sur l'écran d'accueil, sans les barres de Safari, et fonctionne hors ligne.", - "install.dock_1": "Choisissez Fichier › Ajouter au Dock.", - "install.dock_2": "Cliquez sur Ajouter.", - "install.dock_after": "SolidCraft s'ouvre ensuite dans sa propre fenêtre depuis le Dock, et fonctionne hors ligne.", - "install.done": "Terminé", - "update.title": "Mise à jour disponible", - "update.available": "SolidCraft {version} est disponible", - "update.you_have": "Vous avez la version {version}.", - "update.no_notes": "Cette version n'a pas de notes.", - "update.system_hint": "Cette copie est un {kind}. Mettez-la à jour avec :", - "update.package_hint": "Cette copie provient d'un {kind}. Téléchargez le nouveau paquet, puis installez-le avec :", - "update.copy": "Copier", - "update.file": "Le téléchargement récupère {file}.", - "update.download": "Télécharger", - "update.release_page": "Ouvrir la page de la version", - "update.skip": "Ignorer cette version", - "update.later": "Me le rappeler plus tard", - "update.prefs_label": "Mises à jour", "update.check_automatically": "Rechercher automatiquement les mises à jour", "update.check_now": "Vérifier maintenant", "update.checking": "Vérification…", - "update.failed": "Vérification impossible : {error}", - "update.up_to_date": "SolidCraft est à jour.", - "update.prefs_note": "Ceci est SolidCraft {version} ({kind}). Une vérification interroge GitHub sur la dernière version et n'envoie rien d'autre.", - "update.prefs_dev": "Ceci est une version de développement ({version}) : elle ne vérifie pas les mises à jour.", - "update.show": "Afficher la mise à jour vers {version}", - "update.prefs_flatpak": "Flatpak met à jour cette copie ({version}) : exécutez {command} ou utilisez votre logithèque. SolidCraft ne vérifie pas.", - "update.update_now": "Mettre à jour maintenant", - "update.install_msi": "Installer (ferme SolidCraft)", + "update.copy": "Copier", + "update.dmg_opened": "L'image disque est ouverte et vérifiée : faites glisser SolidCraft dans Applications en remplaçant l'ancienne copie, puis redémarrez SolidCraft.", + "update.download": "Télécharger", "update.download_open": "Télécharger et ouvrir", "update.downloading": "Téléchargement et vérification… {done} sur {total} Mo", + "update.failed": "Vérification impossible : {error}", + "update.file": "Le téléchargement récupère {file}.", + "update.install_failed": "La mise à jour ne s'est pas installée : {error}. Rien n'a été modifié ; Télécharger récupère plutôt le paquet.", + "update.install_msi": "Installer (ferme SolidCraft)", "update.installed": "SolidCraft {version} est installé. Redémarrez pour l'utiliser.", + "update.installer_started": "L'installateur démarre à la fermeture de SolidCraft.", + "update.later": "Me le rappeler plus tard", + "update.no_notes": "Cette version n'a pas de notes.", + "update.package_hint": "Cette copie provient d'un {kind}. Téléchargez le nouveau paquet, puis installez-le avec :", + "update.prefs_dev": "Ceci est une version de développement ({version}) : elle ne vérifie pas les mises à jour.", + "update.prefs_flatpak": "Flatpak met à jour cette copie ({version}) : exécutez {command} ou utilisez votre logithèque. SolidCraft ne vérifie pas.", + "update.prefs_label": "Mises à jour", + "update.prefs_note": "Ceci est SolidCraft {version} ({kind}). Une vérification interroge GitHub sur la dernière version et n'envoie rien d'autre.", + "update.release_page": "Ouvrir la page de la version", "update.restart": "Redémarrer maintenant", "update.restart_later": "Plus tard", - "update.installer_started": "L'installateur démarre à la fermeture de SolidCraft.", - "update.dmg_opened": "L'image disque est ouverte et vérifiée : faites glisser SolidCraft dans Applications en remplaçant l'ancienne copie, puis redémarrez SolidCraft.", - "update.install_failed": "La mise à jour ne s'est pas installée : {error}. Rien n'a été modifié ; Télécharger récupère plutôt le paquet.", - "cmd.render_settings_get": "Réglages de rendu", - "cmd.render_settings_set": "Enregistrer les réglages de rendu", - "drive.unconnected": "Rien ne bouge : {part} n'est relié à rien de fixé", - "joint.one_component": "Ces pièces sont des corps d'un même composant : {bodies}. Une liaison déplace un composant par rapport à un autre, chaque pièce a donc besoin de son propre composant.", - "joint.one_body": "Les deux sélections sont sur {body}. Choisissez la seconde sur une autre pièce.", - "joint.from_bodies_hint": "Chaque corps sélectionné passe dans un nouveau composant à lui et reste où il est.", - "cmd.render_scene": "Inspecter la scène de rendu", - "cmd.render_settings_apply": "Appliquer la caméra de rendu", - "toolbar.render": "RENDU", - "toolbar.render_scene": "SCÈNE", - "render.preview": "Aperçu intégré", - "render.preview_help": "Ombrage par rastérisation et transparence mélangée. La réfraction, l'HDRI et le rendu final ne sont pas encore disponibles.", - "render.setup_name": "Nom du préréglage", - "render.background": "Arrière-plan de la scène", - "render.perspective": "Caméra en perspective", - "render.fit": "Cadrer le produit", - "render.restore_camera": "Restaurer la caméra enregistrée", - "render.save_setup": "Enregistrer le préréglage", - "render.unsaved": "Modifications de l'aperçu non enregistrées", - "render.reload_settings": "Recharger les réglages enregistrés", - "render.unavailable_preview": "Ce préréglage demande un profil d'aperçu indisponible.", - "render.use_preview": "Utiliser l'aperçu intégré", - "render.navigation_help": "La caméra se déplace comme dans Conception (Préférences › Navigation). Enregistrer le préréglage mémorise la caméra actuelle.", - "render.return_design": "Revenir à la conception", - "render.image_title": "Image de rendu", - "render.image_help": "Image d'aperçu CPU · PNG · transparence approximative", - "render.image_width": "Largeur", - "render.image_height": "Hauteur", - "render.image_transparent": "Arrière-plan transparent", - "render.image_check": "Vérifier la demande de rendu", - "render.image_supported": "La demande de rendu est prise en charge ; la file d'attente et la réserve de mémoire seront revérifiées au lancement.", - "render.image_queued": "En attente de rendu", - "render.image_preparing": "Préparation de l'image", - "render.image_running": "Rendu de l'image", - "render.image_encoding": "Encodage du PNG", - "render.image_cancelling": "Annulation", - "render.image_cancelled": "Rendu annulé", - "render.image_completed": "Image prête à exporter", - "render.image_failed": "Échec du rendu", - "render.image_unknown": "État du rendu indisponible", - "render.image_reduce": "Essayez une image plus petite ou une scène plus simple.", - "render.image_too_large": "Au-delà de la limite d'image : 4096 pixels par côté et 4 194 304 pixels au total.", - "render.image_use_largest": "Utiliser la plus grande taille à ce format :", - "render.image_cancel": "Annuler le rendu", - "render.image_stale": "Cette image utilise la scène capturée avant les dernières modifications.", - "render.image_start": "Lancer le rendu", - "render.image_overwrite": "Remplacer le fichier existant", - "render.image_export": "Exporter en PNG", - "cmd.render_preflight": "Vérifier la demande de rendu", - "cmd.render_start": "Rendu d'image", - "cmd.render_status": "Progression du rendu", - "cmd.render_cancel": "Annuler le rendu", - "cmd.render_export": "Exporter l'image de rendu", - "toolbar.image": "IMAGE", - "appearance.surface_response": "Réponse de la surface", - "appearance.pbr_opaque": "PBR opaque", - "appearance.metallic": "Métallique", - "appearance.roughness": "Rugosité", - "appearance.dielectric_ior": "Indice de réfraction (diélectrique)", - "appearance.pbr_help": "Voir cette surface dans l'espace Rendu ou dans un PNG du produit. Sans réfraction ni transmission.", - "render.opaque_preview_help": "PBR opaque et couleurs simples ; transparence mélangée. La réfraction, l'HDRI et le rendu final ne sont pas encore disponibles.", - "render.opaque_image_summary": "PNG d'aperçu · PBR opaque · transparence mélangée", - "UNTRIM": "ANNULER L'AJUSTEMENT", - "Face": "Face", - "Holes": "Trous", - "Holes (edges on them)": "Trous (par leurs arêtes)", - "In place (surfaces)": "En place (surfaces)", - "None": "Aucun", - "Picked": "Sélectionnés", - "Restore outer boundary": "Restaurer le contour extérieur", - "RULED SURFACE": "SURFACE RÉGLÉE", - "Mitre": "Onglet", - "Reference face": "Face de référence", - "Round": "Arrondi", - "coupling.gear_1": "Engrenage 1", - "coupling.gear_2": "Engrenage 2", - "coupling.pinion": "Pignon", - "coupling.rack": "Crémaillère", - "coupling.nut": "Écrou", - "coupling.radius_1": "Rayon 1", - "coupling.radius_2": "Rayon 2", - "coupling.internal": "Engrenage intérieur", - "coupling.pitch": "Pas", - "coupling.picked": "sélectionné", - "coupling.not_round": "pas une face ronde", - "coupling.gear_1_pick": "Engrenage 1 (facultatif)", - "coupling.gear_2_pick": "Engrenage 2 (facultatif)", - "coupling.pinion_pick": "Pignon (facultatif)", - "coupling.needs_turns": "nécessite deux liaisons qui tournent", - "coupling.needs_turn_and_slide": "nécessite une liaison qui tourne et une qui glisse" + "update.show": "Afficher la mise à jour vers {version}", + "update.skip": "Ignorer cette version", + "update.system_hint": "Cette copie est un {kind}. Mettez-la à jour avec :", + "update.title": "Mise à jour disponible", + "update.up_to_date": "SolidCraft est à jour.", + "update.update_now": "Mettre à jour maintenant", + "update.you_have": "Vous avez la version {version}." } diff --git a/assets/locales/ja.json b/assets/locales/ja.json index abc53ec22..8f51b893c 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -1,29 +1,286 @@ { - "settings.measure_axis_distances": "計測のX・Y・Z距離を表示", - "settings.measure_axis_distances_help": "計測ダイアログを開いている間、2点間距離に加えてワールドX・Y・Z軸方向の寸法線と距離を表示します。", - "Export Current View as DXF": "現在の表示をDXFでエクスポート", - "Export Current View as DXF…": "現在の表示をDXFでエクスポート…", - "Hidden edges": "隠線", - "Do not export hidden edges": "出力しない", - "Export hidden edges as dashed lines": "点線で出力", - "Projection": "投影", - "Current perspective view": "現在の透視投影", - "Current orthographic view (1:1 mm)": "現在の平行投影(実寸・mm)", - "Visible bodies only. Curves use line segments (0.01 mm tolerance).": "表示中のボディを出力します。曲線は線分で近似します(許容誤差0.01 mm)。", - "Turn off section analysis before exporting the view.": "断面解析をオフにしてからエクスポートしてください。", - "No visible bodies to export.": "出力する表示中のボディがありません。", - "Export DXF…": "DXFをエクスポート…", - "Send your report on GitHub": "GitHubでレポートを送信", + "0 turns it off": "0で無効化", "1. Open GitHub draft below, then paste the report copied to your clipboard.": "1. 下のボタンでGitHubの下書きを開き、クリップボードにコピーされたレポートを貼り付けます。", "1. Open GitHub draft below. Your title and report will be filled in.": "1. 下のボタンでGitHubの下書きを開きます。タイトルとレポートは入力済みです。", "2. Attach your screenshot: copy and paste it, or save and upload the PNG.": "2. スクリーンショットを添付します。コピーして貼り付けるか、PNGを保存してアップロードします。", "3. Click Submit new issue on GitHub to send your report.": "3. GitHubでSubmit new issueをクリックしてレポートを送信します。", - "nav.touchpad.label": "タッチパッド", - "nav.touchpad.help": "Shift を押しながらポインターを動かすとパン、Alt/Option を押しながら動かすと回転します。マウスボタンは不要です。縦スクロールでズームします。", - "nav.touchpad.orbit": "回転(Alt/Option を押しながら移動、マウスボタン不要)", - "nav.touchpad.pan": "パン(Shift を押しながら移動、マウスボタン不要)", - "nav.touchpad.zoom": "ズーム(縦スクロールまたはピンチ)", - "nav.touchpad.scroll": "タッチパッドでは縦スクロールでズームします。2 本指パンの設定は他のプリセット用に保持されます。", + "A new configuration, a copy of the active one": "アクティブな構成をコピーして新しい構成を作成", + "AI": "AI", + "About SolidCraft": "SolidCraft について", + "Active": "アクティブ", + "Active rule": "有効なルール", + "Add": "追加", + "Add Key": "キーを追加", + "Add Mid Radius": "中間半径を追加", + "Add Row": "行を追加", + "Add condition": "条件を追加", + "Alignment": "配置", + "All Sketch Points": "すべてのスケッチ点", + "All open designs": "すべての開いているデザイン", + "Allowed expressions, separated by semicolons": "使用可能な式(セミコロンで区切る)", + "Also deletes": "同時に削除される要素:", + "Angle 2": "角度 2", + "Animate": "アニメーション", + "Appearance name": "外観名", + "Applied Radius": "適用半径", + "Apply To": "適用先", + "Apply to selection": "選択項目に適用", + "Arc length": "円弧の長さ", + "Area": "表面積", + "Attachment": "アタッチメント", + "BROWSER": "ブラウザ", + "Bend Line Position": "曲げ線位置", + "Bend Position": "曲げ位置", + "Bend Radius": "曲げ半径", + "Bends": "曲げ", + "Body": "ボディ", + "Bounding box": "境界ボックス", + "CSV or JSON: updates existing parameters, adds new ones": "CSVまたはJSON:既存のパラメータを更新し、新しいパラメータを追加します", + "Capture All Positions": "すべての位置をキャプチャ", + "Catch Direction": "キャッチ方向", + "Cells": "セル", + "Center X": "中心 X", + "Center Y": "中心 Y", + "Center of mass": "重心", + "Centre to centre": "中心間", + "Chamfer Type": "面取りタイプ", + "Check collisions": "衝突チェック", + "Checked": "チェック済み", + "Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.": "新しい平面を選択してください。スケッチジオメトリと寸法は2次元座標系のまま維持されます。", + "Circumference": "円周", + "Close draft": "下書きを閉じる", + "Collisions": "衝突", + "Colour": "色", + "Component1": "コンポーネント1", + "Configuration": "構成", + "Configuration rules": "構成ルール", + "Construction": "コンストラクション", + "Contact": "接触", + "Copy Error Message": "エラーメッセージをコピー", + "Copy Warning Message": "警告メッセージをコピー", + "Copy all licences": "すべてのライセンスをコピー", + "Copy diagnostic information": "診断情報をコピー", + "Copy report": "レポートをコピー", + "Copy screenshot": "スクリーンショットをコピー", + "Corner Relief": "コーナーリリーフ", + "Corner Relief Shape": "コーナーリリーフ形状", + "Counterbore depth": "座ぐり深さ", + "Countersink angle": "皿穴角度", + "Create Issue — review draft": "Issueを作成 — 下書きの確認", + "Cube": "キューブ", + "Current orthographic view (1:1 mm)": "現在の平行投影(実寸・mm)", + "Current perspective view": "現在の透視投影", + "Customize Toolbar": "ツールバーのカスタマイズ", + "Delete all": "すべて削除", + "Delete rule": "ルールを削除", + "Delete the row": "行を削除", + "Delete the set": "セットを削除", + "Delete this parameter": "このパラメータを削除", + "Density": "密度", + "Designs you open or save appear here.": "開いたデザインや保存したデザインがここに表示されます。", + "Determined by To Object. Choose Angle to edit the angular extent.": "「対象オブジェクトまで」により決定されます。角度範囲を編集するには「角度」を選択してください。", + "Discard": "破棄", + "Do not export hidden edges": "出力しない", + "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": "ジョイントを駆動", + "Edges": "エッジ", + "Edit Profile Sketch": "プロファイルスケッチを編集", + "Enable rule": "ルールを有効化", + "Enabled": "有効", + "Explode": "分解", + "Export Current View as DXF": "現在の表示をDXFでエクスポート", + "Export Current View as DXF…": "現在の表示をDXFでエクスポート…", + "Export DXF…": "DXFをエクスポート…", + "Export hidden edges as dashed lines": "点線で出力", + "Extents": "範囲", + "Face": "面", + "Face attachment lost": "面アタッチメントが失われました", + "Faces": "面", + "Faces / edges / vertices": "面 / エッジ / 頂点", + "Favourite": "お気に入り", + "Files from many CAD programs have Y up, so they open lying on their back here (Z up).": "多くのCADではY軸を上向きとしているため、Z軸を上向きとするSolidCraftでは、読み込んだモデルが横倒しの向きで表示されることがあります。", + "Filter": "フィルター", + "Find in Browser": "ブラウザで検索", + "Flat": "展開", + "Flat size": "展開サイズ", + "Follow camera (Look At sketches)": "カメラ追従(スケッチを正面視)", + "Follow the camera (Look At sketches)": "カメラ追従(スケッチを正面視)", + "Font": "フォント", + "Full Length": "全長", + "Gap": "ギャップ", + "Grid": "グリッド", + "Height": "高さ", + "Hidden edges": "隠線", + "Holes": "穴", + "Holes (edges on them)": "穴(そのエッジ)", + "Home view": "ホームビュー", + "In This Design": "このデザイン内", + "In place (surfaces)": "その場で(サーフェス)", + "Inside": "内側", + "Interferes": "干渉あり", + "Issue title": "Issueタイトル", + "Joint Origin1": "ジョイント原点1", + "Keep Tools": "ツールボディを保持", + "Later": "後で", + "Leave it": "そのままにする", + "Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "従来の面アタッチメントです。確定された面に再バインドすると正確なアタッチメントが作成されます。", + "Length": "長さ", + "Length units": "長さの単位", + "Letter Spacing": "文字間隔", + "Library": "ライブラリ", + "Line Spacing": "行間", + "Loop": "ループ", + "Margin": "マージン", + "Mass": "質量", + "Material": "材料", + "Max": "最大", + "Mid Radius": "中間半径", + "Middle double-click": "中ボタンのダブルクリック", + "Min": "最小", + "Mitre": "留め継ぎ", + "Modeled": "モデル化済み", + "More toolbar panels": "その他のツールバーパネル", + "Motion": "モーション", + "Move Type": "移動タイプ", + "Move earlier": "前へ移動", + "Move later": "後へ移動", + "Name": "名前", + "No crash reports.": "クラッシュレポートはありません。", + "No matching appearances": "一致する外観がありません", + "No visible bodies to export.": "出力する表示中のボディがありません。", + "None": "なし", + "Not available yet": "まだ利用できません", + "Notch": "ノッチ", + "Opacity": "不透明度", + "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": "反対側", + "Outside": "外側", + "Overall length": "全長", + "Parameter values": "パラメータ値", + "Path": "パス", + "Per Edge": "エッジごと", + "Pick the tool bodies": "ツールボディを選択", + "Picked": "選択したもの", + "Place at the origin instead": "代わりに原点に配置", + "Playback": "再生", + "Position": "位置", + "Position (0 to 1)": "位置 (0〜1)", + "Position along the edge, 0 at the start end, 1 at the other": "エッジ上の位置(始点が0、終点が1)", + "Preview Row": "行をプレビュー", + "Preview leaves the current design unchanged.": "プレビューは現在のデザインを変更しません。", + "Profiles/Curves": "プロファイル/曲線", + "Projection": "投影", + "RECENT": "最近使用した項目", + "RULED SURFACE": "ルールドサーフェス", + "Radius Fit": "半径フィット", + "Ratio": "比率", + "Reattach selected face": "選択した面を再アタッチ", + "Recover": "復元", + "Recover unsaved design?": "未保存のデザインを復元しますか?", + "Rectangular": "長方形", + "Reference face": "参照面", + "Remove Tools": "ツールボディを削除", + "Remove from list": "リストから削除", + "Remove override": "オーバーライドを削除", + "Remove private design details or paths before sharing.": "共有前に、非公開の設計情報やファイルパスを削除してください。", + "Remove screenshot": "スクリーンショットを削除", + "Remove the column": "列を削除", + "Remove the track": "トラックを削除", + "Remove this point": "この点を削除", + "Report a bug — review a screenshot and open a GitHub draft": "バグを報告 — スクリーンショットを確認してGitHub下書きを作成", + "Reset Toolbar": "ツールバーをリセット", + "Restore outer boundary": "外側の境界を復元", + "Restore the inherited component or physical material appearance": "コンポーネントまたは物理マテリアルから継承した外観に戻す", + "Result": "結果", + "Retake screenshot": "スクリーンショットを再取得", + "Reverse": "反転", + "Reverse Direction": "方向を反転", + "Revert": "元に戻す", + "Revert All Positions": "すべての位置を元に戻す", + "Revert Position": "位置を元に戻す", + "Review the report and screenshot before opening GitHub.": "GitHubを開く前にレポートとスクリーンショットを確認してください。", + "Rim Edge": "リムエッジ", + "Roll History Marker Here": "履歴マーカーをここに移動", + "Round": "丸め", + "Rule": "ルール", + "Save Rule": "ルールを保存", + "Saved preview. Geometry is being checked before editing.": "保存済みのプレビューです。編集前にジオメトリを検証しています。", + "Scale factor": "尺度係数", + "Search": "検索", + "Search commands": "コマンドを検索", + "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).": "その他を選択: モデル上で左ボタンを長押し(または右クリック › その他を選択…)するとカーソル下の要素が一覧表示されます。同じ場所を再度クリックすると次の要素が選択されます。中ボタンをダブルクリックするとホームビューに戻ります(環境設定 › ナビゲーション)。", + "Select bodies (a face picks its body)": "ボディを選択(面をクリックするとそのボディが選択されます)", + "Select bodies or faces instead": "代わりにボディまたは面を選択", + "Selection filter": "選択フィルター", + "Semantic faces share their appearance across instances.": "セマンティック面はインスタンス間で外観を共有します。", + "Send your report on GitHub": "GitHubでレポートを送信", + "Shape": "形状", + "Show Agent Cursor": "エージェントカーソルを表示", + "Show in folder": "フォルダに表示", + "Show the pointer an AI agent moves (#35)": "エージェントが操作するポインターを表示 (#35)", + "Signed axes": "符号付き座標軸", + "Size": "サイズ", + "Sketch constraints": "スケッチ拘束", + "Sketch curves": "スケッチ曲線", + "Sketch dimensions": "スケッチ寸法", + "Sketch geometry and profiles": "スケッチジオメトリとプロファイル", + "Sketch plane has no body-face attachment.": "スケッチ平面にボディ面のアタッチメントがありません。", + "Sketch points": "スケッチ点", + "Slot width": "長穴の幅", + "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "これらのデザインが保存される前にSolidCraftが終了しました。最後の自動保存ファイルを開くことができます。", + "Speed": "速度", + "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?": "このパーツを正立させますか?", + "Step": "ステップ", + "Steps": "ステップ数", + "Style": "スタイル", + "Suppressed": "抑制", + "Swap Ends": "端点を入れ替え", + "Tangent Chain": "正接チェーン", + "Tear": "引き裂き", + "The dashed sketch is a saved plane guide. Select a new face to repair the attachment.": "破線のスケッチは保存された平面ガイドです。新しい面を選択してアタッチメントを修復してください。", + "The saved author occurrence is missing. Select a valid author placement before rebinding.": "保存された作成元のオカレンスが見つかりません。再バインドする前に有効な作成元配置を選択してください。", + "Then": "次を実行 (Then)", + "These features will be deleted:": "以下のフィーチャーが削除されます:", + "These features will fail:": "以下のフィーチャーでエラーが発生します:", + "Thickness Outside": "外側の厚さ", + "Thin": "薄肉", + "Thin Extrude": "薄肉押し出し", + "This child is shared. Deleting it removes it from 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.": "この面は安定したアタッチメントを提供できません。別の面を選択するか、固定平面を明示的に使用してください。", + "To Offset": "オフセットまで", + "Tolerance": "公差", + "Turn off section analysis before exporting the view.": "断面解析をオフにしてからエクスポートしてください。", + "Type": "タイプ", + "UNTRIM": "トリム解除", + "Updating the preview": "プレビューを更新中", + "Use active author placement": "アクティブな作成元配置を使用", + "Use fixed plane": "固定平面を使用", + "Use saved fixed plane": "保存された固定平面を使用", + "Use selected face as fixed plane": "選択した面を固定平面として使用", + "VIEW": "表示", + "Value": "値", + "Vertices": "頂点", + "View navigator": "ビューナビゲーター", + "Visible bodies only. Curves use line segments (0.01 mm tolerance).": "表示中のボディを出力します。曲線は線分で近似します(許容誤差0.01 mm)。", + "Volume": "体積", + "Wall": "肉厚", + "Wall Location": "壁の位置", + "Wall Thickness": "壁の厚さ", + "When": "条件 (When)", + "Width": "幅", + "Will fail": "失敗します", + "angle, height": "角度, 高さ", + "appearance.dielectric_ior": "誘電体の屈折率", + "appearance.metallic": "金属度", + "appearance.pbr_help": "この表面はレンダリング作業空間または製品PNGで確認できます。屈折や透過には対応していません。", + "appearance.pbr_opaque": "不透明PBR", + "appearance.roughness": "粗さ", + "appearance.surface_response": "表面の応答", "browser.body_name": "ボディ{number}", "browser.component_name": "コンポーネント{number}", "browser.parameters": "パラメータ ({count})", @@ -50,7 +307,6 @@ "cmd.component_capture_position": "位置をキャプチャ", "cmd.component_create": "新規コンポーネント", "cmd.component_delete": "コンポーネントを削除", - "cmd.component_unlock": "内容のロックを解除", "cmd.component_from_bodies": "ボディからコンポーネントを作成", "cmd.component_insert_design": "デザインを挿入", "cmd.component_links": "リンクを一覧表示", @@ -61,6 +317,7 @@ "cmd.component_properties": "コンポーネントの物理的プロパティ", "cmd.component_rename": "コンポーネントの名前を変更", "cmd.component_revert_position": "位置を元に戻す", + "cmd.component_unlock": "内容のロックを解除", "cmd.component_update_links": "リンクを更新", "cmd.config_activate": "構成をアクティブ化", "cmd.config_column": "構成列", @@ -102,10 +359,10 @@ "cmd.doc_recovery_discard": "復元デザインを破棄", "cmd.doc_recovery_list": "復元可能なデザイン", "cmd.document_inspect": "デザインを検査", - "cmd.document_units": "デザインの単位を変更", "cmd.document_metadata": "デザインのプロパティ", - "cmd.document_metadata_set": "デザインのプロパティを変更", "cmd.document_metadata_remove": "デザインのプロパティを削除", + "cmd.document_metadata_set": "デザインのプロパティを変更", + "cmd.document_units": "デザインの単位を変更", "cmd.edit_checkpoint": "チェックポイント", "cmd.edit_restore_checkpoint": "チェックポイントを復元", "cmd.engine_commands": "コマンドを一覧表示", @@ -123,6 +380,7 @@ "cmd.inspect_accessibility": "アクセシビリティ解析", "cmd.inspect_center_of_mass": "重心", "cmd.inspect_compare": "ボディを比較", + "cmd.inspect_continuity": "連続性解析", "cmd.inspect_curvature_comb": "曲率コーム解析", "cmd.inspect_curvature_map": "曲率マップ解析", "cmd.inspect_draft": "勾配解析", @@ -136,20 +394,25 @@ "cmd.joint_delete": "ジョイントを削除", "cmd.joint_drive": "ジョイントを駆動", "cmd.joint_edit": "ジョイントを編集", + "cmd.joint_gear": "ギア", "cmd.joint_limits": "ジョイントの制限", "cmd.joint_list": "ジョイントを一覧表示", "cmd.joint_motion_link": "モーション リンク", - "cmd.joint_gear": "ギア", - "cmd.joint_rack_pinion": "ラック アンド ピニオン", - "cmd.joint_screw": "ねじ", "cmd.joint_origin": "ジョイント原点", + "cmd.joint_rack_pinion": "ラック アンド ピニオン", "cmd.joint_rigid_group": "リジッド グループ", + "cmd.joint_screw": "ねじ", "cmd.joint_solve": "ジョイントを解決", + "cmd.library_apply": "ローカルライブラリ項目を適用", + "cmd.library_export": "デザインライブラリを書き出す", + "cmd.library_inspect": "ローカルライブラリを確認", "cmd.material_assign": "物理マテリアル", "cmd.material_create": "新規物理マテリアル", "cmd.material_delete": "物理マテリアルを削除", "cmd.material_edit": "物理マテリアルを編集", "cmd.material_list": "マテリアルを一覧表示", + "cmd.material_properties_directional": "方向別弾性率", + "cmd.material_properties_validate": "物理材料データを検証", "cmd.mesh_convert": "メッシュを変換", "cmd.model_edges": "エッジを一覧表示", "cmd.model_faces": "面を一覧表示", @@ -170,10 +433,10 @@ "cmd.parameters_delete": "パラメータを削除", "cmd.parameters_export": "パラメータをエクスポート", "cmd.parameters_favorite": "お気に入りパラメータ", - "cmd.parameters_move": "パラメータを移動", "cmd.parameters_graph": "パラメータ グラフ", "cmd.parameters_import": "パラメータをインポート", "cmd.parameters_list": "パラメータを一覧表示", + "cmd.parameters_move": "パラメータを移動", "cmd.parameters_rename": "パラメータの名前を変更", "cmd.parameters_users": "パラメータの参照先", "cmd.parts_fastener": "ファスナーを挿入", @@ -187,6 +450,16 @@ "cmd.plastic_rest": "レスト", "cmd.plastic_rules": "プラスチック ルールを一覧表示", "cmd.plastic_snap_fit": "スナップ フィット", + "cmd.render_backends": "レンダリング バックエンド", + "cmd.render_cancel": "レンダリングをキャンセル", + "cmd.render_export": "PNGをエクスポート", + "cmd.render_preflight": "レンダリング要求を確認", + "cmd.render_scene": "レンダリングシーンを確認", + "cmd.render_settings_apply": "レンダリングカメラを適用", + "cmd.render_settings_get": "レンダリング設定", + "cmd.render_settings_set": "レンダリング設定を保存", + "cmd.render_start": "画像をレンダリング", + "cmd.render_status": "レンダリングの進行状況", "cmd.select_clear": "選択をクリア", "cmd.sheet_convert": "板金に変換", "cmd.sheet_export_bend_table": "曲げテーブルをエクスポート", @@ -282,22 +555,21 @@ "cmd.solid_rib": "リブ", "cmd.solid_split_face": "面を分割", "cmd.solid_web": "ウェブ", - "cmd.surface_patch": "パッチ", - "cmd.surface_stitch": "ステッチ", - "cmd.surface_thicken": "厚み付け", - "cmd.surface_extrude": "サーフェス押し出し", - "cmd.surface_revolve": "サーフェス回転", - "cmd.surface_sweep": "サーフェススイープ", - "cmd.surface_loft": "サーフェスロフト", - "cmd.surface_ruled": "ルールドサーフェス", - "cmd.surface_boundary": "境界サーフェス", - "cmd.surface_offset": "オフセットサーフェス", "cmd.surface_blend": "ブレンドサーフェス", + "cmd.surface_boundary": "境界サーフェス", + "cmd.surface_extrude": "サーフェス押し出し", "cmd.surface_fillet": "サーフェスフィレット", - "cmd.surface_untrim": "トリム解除", - "cmd.surface_unstitch": "縫い合わせ解除", + "cmd.surface_loft": "サーフェスロフト", + "cmd.surface_offset": "オフセットサーフェス", + "cmd.surface_patch": "パッチ", "cmd.surface_reverse_normal": "法線を反転", - "cmd.inspect_continuity": "連続性解析", + "cmd.surface_revolve": "サーフェス回転", + "cmd.surface_ruled": "ルールドサーフェス", + "cmd.surface_stitch": "ステッチ", + "cmd.surface_sweep": "サーフェススイープ", + "cmd.surface_thicken": "厚み付け", + "cmd.surface_unstitch": "縫い合わせ解除", + "cmd.surface_untrim": "トリム解除", "cmd.timeline_add": "記録したフィーチャーを追加", "cmd.timeline_compute_all": "すべて再計算", "cmd.timeline_copy": "フィーチャーをコピー", @@ -314,18 +586,42 @@ "cmd.view_apply": "名前付きビューを復元", "cmd.view_delete": "名前付きビューを削除", "cmd.view_list": "名前付きビューを一覧表示", + "cmd.view_navigate": "ビューナビゲーション", "cmd.view_rename": "名前付きビューの名前を変更", "cmd.view_save": "新規名前付きビュー", + "command name": "コマンド名", + "coupling.gear_1": "ギア 1", + "coupling.gear_1_pick": "ギア 1 (オプション)", + "coupling.gear_2": "ギア 2", + "coupling.gear_2_pick": "ギア 2 (オプション)", + "coupling.internal": "内歯車", + "coupling.needs_turn_and_slide": "回転するジョイントとスライドするジョイントが必要", + "coupling.needs_turns": "回転するジョイントが 2 つ必要", + "coupling.not_round": "円筒面ではありません", + "coupling.nut": "ナット", + "coupling.picked": "選択済み", + "coupling.pinion": "ピニオン", + "coupling.pinion_pick": "ピニオン (オプション)", + "coupling.pitch": "ピッチ", + "coupling.rack": "ラック", + "coupling.radius_1": "半径 1", + "coupling.radius_2": "半径 2", "dialog.computing": "計算中… {seconds} 秒", "dialog.custom_axis": "↖ カスタム軸", "dialog.edit_title": "{title}を編集", "dialog.select": "↖ 選択", "dialog.selected_count": "↖ {count} 個選択中", - "dialog.step": "ステップ", - "dialog.selection_step": "{total} ステップ中 {step}: {input} を選択", "dialog.selection_guidance": "入力欄を選んで変更します。選択済みのオブジェクトをクリックすると解除できます。Ctrl/Cmd を押しながらクリックしても切り替えられます。プレビューを確認してから OK を押してください。", + "dialog.selection_step": "{total} ステップ中 {step}: {input} を選択", + "dialog.step": "ステップ", "document.save_changes": "{name} への変更を保存しますか?", "document.unsaved_changes": "{name} には保存されていない変更があります。保存しない場合、変更内容は失われます。", + "drive.stopped_by_contact": "{value} で停止: {a} が {b} を通り抜けてしまいます", + "drive.stopped_by_loop": "{value} で停止: {joint} を通るループはこれ以上閉じられません", + "drive.unconnected": "何も動きません: {part} は空間固定されたものに接続されていません", + "expression, e.g. 25 mm": "計算式 (例: 25 mm)", + "fits the face, e.g. M8": "面に適合するサイズ (例: M8)", + "from the rule": "ルールから", "home.documentation": "ドキュメント", "home.in_this_browser": "このブラウザ内", "home.missing": "見つかりません", @@ -339,6 +635,76 @@ "home.report_issue": "問題を報告", "home.samples": "サンプル", "home.whats_new": "新機能", + "install.button_tip": "SolidCraft をアプリとしてインストールします。専用のウィンドウで開き、オフラインでも使えます", + "install.dock_1": "「ファイル」›「Dockに追加」を選びます。", + "install.dock_2": "「追加」をクリックします。", + "install.dock_after": "SolidCraft は Dock から専用のウィンドウで開き、オフラインでも使えます。", + "install.done": "完了", + "install.home_screen_1": "「共有」をタップします(ツールバーにない場合は … メニューの中にあります)。", + "install.home_screen_2": "「ホーム画面に追加」を選びます。", + "install.home_screen_3": "「追加」をタップします。", + "install.home_screen_after": "SolidCraft はホーム画面のアイコンから Safari のツールバーなしで開き、オフラインでも使えます。", + "install.menu": "アプリをインストール…", + "install.steps_intro": "Safari では、Web アプリを Safari 自身のメニューからインストールします:", + "install.title": "SolidCraft をインストール", + "joint.from_bodies_hint": "選択した各ボディを、位置はそのままで専用の新しいコンポーネントに移動します。", + "joint.one_body": "両方の選択が {body} 上にあります。2 つ目は別の部品で選択してください。", + "joint.one_component": "これらの部品は 1 つのコンポーネントのボディです: {bodies}。ジョイントはコンポーネント同士を動かすため、部品ごとに専用のコンポーネントが必要です。", + "nav.touchpad.help": "Shift を押しながらポインターを動かすとパン、Alt/Option を押しながら動かすと回転します。マウスボタンは不要です。縦スクロールでズームします。", + "nav.touchpad.label": "タッチパッド", + "nav.touchpad.orbit": "回転(Alt/Option を押しながら移動、マウスボタン不要)", + "nav.touchpad.pan": "パン(Shift を押しながら移動、マウスボタン不要)", + "nav.touchpad.scroll": "タッチパッドでは縦スクロールでズームします。2 本指パンの設定は他のプリセット用に保持されます。", + "nav.touchpad.zoom": "ズーム(縦スクロールまたはピンチ)", + "needs two joints": "2つのジョイントが必要", + "new configuration": "新規構成", + "new name": "新しい名前", + "new parameter": "新規パラメータ", + "no interference": "干渉なし", + "no joint that moves yet": "可動ジョイントがまだありません", + "no picture": "画像なし", + "pick a hole to seat it, or OK places it at the origin": "配置先の穴を選択するか、[OK]を押すと原点に配置します。", + "pick one or two vertices, edges or faces": "1つまたは2つの頂点、エッジ、面を選択", + "render.background": "シーンの背景", + "render.fit": "製品を画面に合わせる", + "render.image_cancel": "レンダリングをキャンセル", + "render.image_cancelled": "レンダリングをキャンセルしました", + "render.image_cancelling": "キャンセル中", + "render.image_check": "レンダリング要求を確認", + "render.image_completed": "画像をエクスポートできます", + "render.image_encoding": "PNGをエンコード中", + "render.image_export": "PNGをエクスポート", + "render.image_failed": "レンダリングに失敗しました", + "render.image_height": "高さ", + "render.image_help": "CPUプレビュー画像 · PNG · 近似透過", + "render.image_overwrite": "既存のファイルを置換", + "render.image_preparing": "画像を準備中", + "render.image_queued": "レンダリング待機中", + "render.image_reduce": "画像を小さくするかシーンを簡略化してください。", + "render.image_running": "画像をレンダリング中", + "render.image_stale": "この画像は後続の変更前に取得したシーンを使用しています。", + "render.image_start": "レンダリングを開始", + "render.image_supported": "レンダリング要求に対応しています。開始時にキューとメモリを再確認します。", + "render.image_title": "画像をレンダリング", + "render.image_too_large": "画像の上限を超えています:一辺 4096 ピクセル、合計 4,194,304 ピクセル。", + "render.image_transparent": "透明な背景", + "render.image_unknown": "レンダリング状態を取得できません", + "render.image_use_largest": "この縦横比での最大サイズを使用:", + "render.image_width": "幅", + "render.navigation_help": "カメラはデザインと同じように動きます(環境設定 › ナビゲーション)。「セットアップを保存」で現在のカメラを記録します。", + "render.opaque_image_summary": "プレビューPNG · 不透明PBR · アルファ合成の透明表示", + "render.opaque_preview_help": "不透明PBRと単色表示、アルファ合成による透明表示に対応します。屈折、HDRI、最終レンダリングにはまだ対応していません。", + "render.perspective": "透視投影カメラ", + "render.preview": "統合プレビュー", + "render.preview_help": "ラスタシェーディングとブレンド透明度を使用します。屈折、HDRI、最終レンダリングはまだ利用できません。", + "render.reload_settings": "保存した設定を再読み込み", + "render.restore_camera": "保存したカメラを復元", + "render.return_design": "設計に戻る", + "render.save_setup": "セットアップを保存", + "render.setup_name": "セットアップ名", + "render.unavailable_preview": "このセットアップは利用できないプレビュープロファイルを要求しています。", + "render.unsaved": "未保存のプレビュー変更", + "render.use_preview": "統合プレビューを使用", "sample.bracket.about": "2 mm の板金ルールによるベース フランジ、エッジ フランジ、ヘミング", "sample.bracket.name": "板金ブラケット", "sample.enclosure.about": "リップ、ねじボス、レスト、スナップ フィットを備えたシェル化した直方体", @@ -351,14 +717,41 @@ "sample.plate.name": "サンプル プレート", "sample.vents.about": "矩形パターンに並んだスロット: 行数、列数、ピッチはパラメータ", "sample.vents.name": "通気プレート", + "settings.display_quality_note": "細かいほど曲面とエッジが滑らかに表示されますが、メッシュの生成に時間がかかります。変わるのはビューポートだけで、設計やエクスポートは変わりません。", + "settings.measure_axis_distances": "計測のX・Y・Z距離を表示", + "settings.measure_axis_distances_help": "計測ダイアログを開いている間、2点間距離に加えてワールドX・Y・Z軸方向の寸法線と距離を表示します。", "settings.msaa_applies_on_restart": "アンチエイリアスは次回 SolidCraft を起動したときに適用されます", "settings.msaa_reset": "{setting}: {requested}× はこのグラフィックスデバイスではサポートされていないため、{reset}× に変更しました(サポート: {supported})。", "settings.msaa_unsupported": "このグラフィックスデバイスではサポートされていません", "settings.reset_intro": "次の設定はこのコンピューターでは使用できず、SolidCraft が起動できなくなるため変更されました:", "settings.reset_title": "設定が変更されました", + "settings.supersampling_note": "ビューを高い解像度で描画してから縮小します。4K 未満の画面でエッジ、線、グリッドが滑らかになります。GPU の負荷が増えます(1.5× で約 2.25 倍、2× で 4 倍のピクセル)。", "sketch.degrees_of_freedom": "自由度 {count}", "sketch.draw_curves": "{linetype}として描く", "sketch.make_selection": "選択を{linetype}にする", + "sketch_text.align_center": "中央", + "sketch_text.align_left": "左", + "sketch_text.align_right": "右", + "sketch_text.bold": "太字", + "sketch_text.builtin_font": "{family}(内蔵)", + "sketch_text.font_search": "フォントを検索", + "sketch_text.italic": "斜体", + "sketch_text.loading_fonts": "インストール済みフォントを検索中…", + "sketch_text.on_path": "文字はパスに沿います: 位置は曲線で決まります", + "sketch_text.path_clear": "文字を曲線から外す", + "sketch_text.path_hint": "文字が沿うスケッチの曲線: ここをクリックしてから曲線をクリック", + "sketch_text.use_font_file": "フォント ファイル {path} を使用", + "the parts library is not available": "パーツライブラリは利用できません", + "timeline.group": "フィーチャーフォルダを新規作成", + "timeline.move_many": "タイムライン項目を移動", + "timeline.move_to_group": "フィーチャーをフォルダへ移動", + "timeline.rename_group": "フィーチャーフォルダの名前を変更", + "timeline.reorder_many": "フィーチャーの順序を変更", + "timeline.ungroup": "フィーチャーフォルダを削除", + "to the next face": "次の面まで", + "toolbar.image": "画像", + "toolbar.render": "レンダリング", + "toolbar.render_scene": "シーン", "ui.1_degree_of_freedom": "自由度 1", "ui.3d_mouse_speed": "3D マウス速度", "ui.3d_mouse_windows": "3D マウス", @@ -366,89 +759,89 @@ "ui.about": "SolidCraft について", "ui.activate": "アクティブ化", "ui.active_component": "アクティブなコンポーネント", - "ui.agent_cursor": "エージェントカーソル", - "ui.agent_cursor_speed": "エージェントカーソル速度", "ui.agent_chat": "エージェントチャット", - "ui.agent_chat_command": "エージェントのコマンド", - "ui.agent_chat_desktop_only": "エージェントチャットにはデスクトップアプリが必要です。", - "ui.agent_chat_side": "エージェントチャットの位置", - "ui.agent_chat_left": "左", - "ui.agent_chat_right": "右", - "ui.agent_chat_turn_limit": "1メッセージあたりの変更数", - "ui.agent_chat_privacy_note": "SolidCraft はどこにも何も送信しません。あなたが実行するエージェントが、あなた自身のアカウントでそのサービスと通信します。SolidCraft がキーやパスワードを見たり保存したりすることはありません。", - "ui.agent_chat_connect": "接続", - "ui.agent_chat_stop": "停止", - "ui.agent_chat_stop_tip": "エージェントと、それが起動したものをすべて停止します", - "ui.agent_chat_close": "閉じる", - "ui.agent_chat_minimize": "細いバーに最小化", - "ui.agent_chat_dock_left": "左にドッキング", - "ui.agent_chat_dock_right": "右にドッキング", - "ui.agent_chat_send": "送信", - "ui.agent_chat_cancel": "キャンセル", - "ui.agent_chat_refresh": "再検索", - "ui.agent_chat_pick": "エージェント", - "ui.agent_chat_custom_hint": "標準入出力で Agent Client Protocol を話す任意のプログラム。シェルは使いません。", - "ui.agent_chat_not_installed": "未インストール", - "ui.agent_chat_none_found": "コーディングエージェントが見つかりません。次のいずれかをインストールしてから「再検索」を押してください:", - "ui.agent_chat_detecting": "エージェントを検索中…", - "ui.agent_chat_signed_in": "サインイン済み", - "ui.agent_chat_key_in_env": "キー設定済み", - "ui.agent_chat_not_signed_in": "未サインイン", - "ui.agent_chat_state_off": "未接続", - "ui.agent_chat_state_starting": "起動中…", - "ui.agent_chat_state_ready": "準備完了", - "ui.agent_chat_state_busy": "作業中…", - "ui.agent_chat_state_auth": "サインインが必要", - "ui.agent_chat_state_exited": "エージェント停止", - "ui.agent_chat_changes_of": "変更 {n}/{limit}", - "ui.agent_chat_auth_title": "エージェントにサインイン", - "ui.agent_chat_auth_needed": "エージェントがサインインを求めています。サインインはエージェント自身で行います。SolidCraft がパスワードやキーを見ることはありません。", - "ui.agent_chat_auth_none": "このエージェントはここでのサインイン方法を提示していません。エージェントのドキュメントに従ってサインインしてください。", - "ui.agent_chat_auth_terminal": "ターミナルでこれを実行してから、もう一度「接続」を押してください:", - "ui.agent_chat_auth_agent": "{name} でサインイン", - "ui.agent_chat_auth_env": "環境変数 {vars} を設定して SolidCraft を再起動してください。", - "ui.agent_chat_auth_retry": "サインインしました: 再接続", - "ui.agent_chat_copy": "コピー", - "ui.agent_chat_permission": "エージェントが実行の許可を求めています: {title}", + "ui.agent_chat_allow": "許可", + "ui.agent_chat_allowed": "許可しました", "ui.agent_chat_answered": "回答: {option}", "ui.agent_chat_approval": "エージェントにこの操作を許可しますか?", - "ui.agent_chat_allow": "許可", - "ui.agent_chat_deny": "拒否", - "ui.agent_chat_allowed": "許可しました", - "ui.agent_chat_denied": "拒否しました", - "ui.agent_chat_changes": "{n} 件の変更(元に戻すは1回)", - "ui.agent_chat_undo_changes": "これらの変更を元に戻す", - "ui.agent_chat_undone": "(元に戻しました)", - "ui.agent_chat_undo_label": "エージェントチャット: {message}", - "ui.agent_chat_limit": "エージェントが1メッセージあたりの変更上限 {limit} に達しました。続けさせるには、もう一度メッセージを送ってください。", - "ui.agent_chat_refused": "エージェントには許可されていません: {reason}", - "ui.agent_chat_wait_turn": "エージェントはまだ前のメッセージを処理中です。待つか「キャンセル」を押してください。", - "ui.agent_chat_placeholder": "デザインの変更をエージェントに依頼…", "ui.agent_chat_attach_view": "ビューを添付", "ui.agent_chat_attach_view_tip": "現在のビューの画像をメッセージと一緒に送ります", - "ui.agent_chat_no_images": "このエージェントは画像を受け付けません", - "ui.agent_chat_view_attached": "ビューを添付済み", - "ui.agent_chat_no_cli": "アプリの隣に solidcraft-cli が見つからないため、エージェントはデザインにアクセスできません。", - "ui.agent_chat_no_control": "エージェントチャットのエンドポイントが起動しなかったため、エージェントはデザインにアクセスできません。", + "ui.agent_chat_auth_agent": "{name} でサインイン", + "ui.agent_chat_auth_env": "環境変数 {vars} を設定して SolidCraft を再起動してください。", + "ui.agent_chat_auth_needed": "エージェントがサインインを求めています。サインインはエージェント自身で行います。SolidCraft がパスワードやキーを見ることはありません。", + "ui.agent_chat_auth_none": "このエージェントはここでのサインイン方法を提示していません。エージェントのドキュメントに従ってサインインしてください。", + "ui.agent_chat_auth_retry": "サインインしました: 再接続", + "ui.agent_chat_auth_terminal": "ターミナルでこれを実行してから、もう一度「接続」を押してください:", + "ui.agent_chat_auth_title": "エージェントにサインイン", + "ui.agent_chat_cancel": "キャンセル", + "ui.agent_chat_changes": "{n} 件の変更(元に戻すは1回)", + "ui.agent_chat_changes_of": "変更 {n}/{limit}", + "ui.agent_chat_close": "閉じる", + "ui.agent_chat_command": "エージェントのコマンド", + "ui.agent_chat_connect": "接続", + "ui.agent_chat_copy": "コピー", + "ui.agent_chat_custom_hint": "標準入出力で Agent Client Protocol を話す任意のプログラム。シェルは使いません。", + "ui.agent_chat_denied": "拒否しました", + "ui.agent_chat_deny": "拒否", + "ui.agent_chat_desktop_only": "エージェントチャットにはデスクトップアプリが必要です。", + "ui.agent_chat_detecting": "エージェントを検索中…", + "ui.agent_chat_dock_left": "左にドッキング", + "ui.agent_chat_dock_right": "右にドッキング", "ui.agent_chat_exited": "エージェントが停止しました。", "ui.agent_chat_failed_start": "エージェントを起動できませんでした: {error}", "ui.agent_chat_intro": "普段使っているコーディングエージェント、または選んだモデルのエンドポイントとチャットできます。SolidCraft のツールで開いているデザインを操作し、変更はその場で表示され、メッセージごとに1回で元に戻せます。確認なしで許可する範囲は「環境設定 > AI」で設定します。", - "ui.agent_chat_privacy": "あなたのアカウントで実行するエージェント以外には、何も送信されません。", + "ui.agent_chat_key_in_env": "キー設定済み", + "ui.agent_chat_left": "左", + "ui.agent_chat_limit": "エージェントが1メッセージあたりの変更上限 {limit} に達しました。続けさせるには、もう一度メッセージを送ってください。", + "ui.agent_chat_minimize": "細いバーに最小化", + "ui.agent_chat_no_cli": "アプリの隣に solidcraft-cli が見つからないため、エージェントはデザインにアクセスできません。", + "ui.agent_chat_no_control": "エージェントチャットのエンドポイントが起動しなかったため、エージェントはデザインにアクセスできません。", + "ui.agent_chat_no_images": "このエージェントは画像を受け付けません", + "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_permission": "エージェントが実行の許可を求めています: {title}", + "ui.agent_chat_pick": "エージェント", + "ui.agent_chat_placeholder": "デザインの変更をエージェントに依頼…", + "ui.agent_chat_privacy": "あなたのアカウントで実行するエージェント以外には、何も送信されません。", + "ui.agent_chat_privacy_note": "SolidCraft はどこにも何も送信しません。あなたが実行するエージェントが、あなた自身のアカウントでそのサービスと通信します。SolidCraft がキーやパスワードを見たり保存したりすることはありません。", + "ui.agent_chat_refresh": "再検索", + "ui.agent_chat_refused": "エージェントには許可されていません: {reason}", + "ui.agent_chat_right": "右", + "ui.agent_chat_send": "送信", + "ui.agent_chat_side": "エージェントチャットの位置", + "ui.agent_chat_signed_in": "サインイン済み", + "ui.agent_chat_state_auth": "サインインが必要", + "ui.agent_chat_state_busy": "作業中…", + "ui.agent_chat_state_exited": "エージェント停止", + "ui.agent_chat_state_off": "未接続", + "ui.agent_chat_state_ready": "準備完了", + "ui.agent_chat_state_starting": "起動中…", + "ui.agent_chat_stop": "停止", + "ui.agent_chat_stop_tip": "エージェントと、それが起動したものをすべて停止します", + "ui.agent_chat_turn_limit": "1メッセージあたりの変更数", + "ui.agent_chat_undo_changes": "これらの変更を元に戻す", + "ui.agent_chat_undo_label": "エージェントチャット: {message}", + "ui.agent_chat_undone": "(元に戻しました)", + "ui.agent_chat_view_attached": "ビューを添付済み", + "ui.agent_chat_wait_turn": "エージェントはまだ前のメッセージを処理中です。待つか「キャンセル」を押してください。", + "ui.agent_cursor": "エージェントカーソル", + "ui.agent_cursor_speed": "エージェントカーソル速度", "ui.ai_add": "追加", "ui.ai_add_agent": "エージェントを追加…", "ui.ai_add_agent_title": "エージェントを追加", "ui.ai_add_api": "OpenAI 互換 API", "ui.ai_add_custom": "カスタムコマンド", - "ui.ai_added": "追加済み", "ui.ai_add_installed": "インストール済みエージェント", "ui.ai_add_installed_note": "インストール済みエージェントの独自エントリ(例: 別の引数で起動)。インストール済みのエージェントは自動で一覧に表示されます。", + "ui.ai_added": "追加済み", "ui.ai_agent_mode_tip": "エージェント自身のモード: エージェント自身のツール(シェル、ファイル編集)はこれに従います。SolidCraft のツールは「環境設定 > AI」の権限に従います。", "ui.ai_agents": "エージェント", "ui.ai_always_allow": "常に許可", + "ui.ai_always_allow_tip": "今後このエージェントに {tool} を確認なしで許可します", "ui.ai_always_allowed": "常に許可されたもの", "ui.ai_always_allowed_none": "まだ常に許可されたものはありません。チャットで「常に許可」と答えたものがここに表示されます。", - "ui.ai_always_allow_tip": "今後このエージェントに {tool} を確認なしで許可します", "ui.ai_auto_allowed": "自動許可: {title}({why})", "ui.ai_auto_mode": "権限の設定", "ui.ai_auto_ours": "SolidCraft のツールは SolidCraft 自身が確認します", @@ -463,10 +856,10 @@ "ui.ai_http_key": "エンドポイントがキーを拒否しました。「環境設定 > AI」で確認してください", "ui.ai_http_not_found": "エンドポイントまたはモデルが見つかりません。ベース URL とモデル名を確認してください", "ui.ai_key": "API キー", - "ui.ai_keychain_error": "システムのキーチェーンが拒否しました: {error}", "ui.ai_key_hint": "任意。システムのキーチェーンに保存", "ui.ai_key_needs_https": "キーは HTTPS 経由、またはこのコンピューター宛てにのみ送信されます。", "ui.ai_key_note": "システムのキーチェーンに保存され、SolidCraft の設定には保存されません。ローカルサーバーの場合は空欄のままにします。", + "ui.ai_keychain_error": "システムのキーチェーンが拒否しました: {error}", "ui.ai_mode_all": "すべて許可", "ui.ai_mode_all_note": "確認なしで実行します。クラッシュレポートは引き続き対象外で、フォルダー制限も有効です。", "ui.ai_mode_all_warning": "エージェントは確認なしでデザインの保存・上書き・エクスポート・置き換えができます。信頼できるエージェントで、保存済みのデザインに対してのみ使ってください。", @@ -497,36 +890,26 @@ "ui.ai_test_acp_ok": "応答あり: {agent}", "ui.ai_test_acp_tip": "エージェントを短時間起動してセッションを要求し、終了します", "ui.ai_test_api_tip": "エンドポイントにモデル一覧を問い合わせます", - "ui.ai_testing": "テスト中…", "ui.ai_test_no_model": "接続成功: {count} 個のモデル({model} はありません)", "ui.ai_test_ok": "接続成功: {count} 個のモデル", - "ui.ai_toolbar_button": "ツールバーにボタンを表示", - "ui.ai_toolbar_button_note": "ツールバー右端の AI ボタン。Ctrl+Shift+A と表示メニューからも引き続きパネルを開けます。", + "ui.ai_testing": "テスト中…", "ui.ai_tool_done": "完了", "ui.ai_tool_failed": "失敗", "ui.ai_tool_running": "実行中", "ui.ai_tool_unfold": "クリックして結果を表示", "ui.ai_tool_waiting": "待機中", + "ui.ai_toolbar_button": "ツールバーにボタンを表示", + "ui.ai_toolbar_button_note": "ツールバー右端の AI ボタン。Ctrl+Shift+A と表示メニューからも引き続きパネルを開けます。", "ui.ai_undo_tip": "このメッセージでエージェントが行った変更を、1回でまとめて元に戻します", - "AI": "AI", "ui.all": "すべて", "ui.analysis": "解析", "ui.angle": "角度", "ui.angle_decimals": "角度の小数点以下の桁数", + "ui.animateJoint": "ジョイントをアニメート", "ui.animate_view_changes": "視点変更をアニメーション表示", "ui.animation": "アニメーション", "ui.animation_speed": "アニメーション速度", "ui.anti_aliasing": "アンチエイリアス", - "ui.supersampling": "スーパーサンプリング (SSAA)", - "ui.supersampling_off": "オフ (1×)", - "ui.supersampling_adaptive": "ビューが静止しているときのみ", - "settings.supersampling_note": "ビューを高い解像度で描画してから縮小します。4K 未満の画面でエッジ、線、グリッドが滑らかになります。GPU の負荷が増えます(1.5× で約 2.25 倍、2× で 4 倍のピクセル)。", - "ui.display_quality": "表示品質", - "ui.display_quality_coarse": "粗い", - "ui.display_quality_normal": "標準", - "ui.display_quality_fine": "細かい", - "ui.display_quality_ultra": "最高", - "settings.display_quality_note": "細かいほど曲面とエッジが滑らかに表示されますが、メッシュの生成に時間がかかります。変わるのはビューポートだけで、設計やエクスポートは変わりません。", "ui.apply": "適用", "ui.arc": "円弧", "ui.assemble": "アセンブリ", @@ -534,9 +917,11 @@ "ui.axes": "軸", "ui.axis": "軸", "ui.base_point": "基点", + "ui.blocked": "到達不可", "ui.bodies": "ボディ", "ui.box": "直方体", "ui.break": "分割", + "ui.calibrate": "校正", "ui.cancel": "キャンセル", "ui.canvases": "キャンバス", "ui.center": "中心", @@ -546,8 +931,6 @@ "ui.chamfer_type": "面取りタイプ", "ui.change_workspace": "ワークスペースの変更", "ui.chord_length": "弦長", - "ui.curvature_g2": "曲率連続 (G2)", - "ui.equivalent_radius": "等価半径", "ui.circle": "円", "ui.circular_pattern": "円形パターン", "ui.clear": "クリア", @@ -556,28 +939,6 @@ "ui.click_selects_whole_bodies": "クリックでボディ全体を選択", "ui.click_then_press_key": "クリックした後、割り当てるキーを押してください", "ui.close": "閉じる", - "ui.material_review.title": "物理材料データを確認", - "ui.material_review.scope": "候補のみ:割り当てや保存は行いません。数値検証は工学的認証ではありません。", - "ui.material_review.input": "スキーマ1の材料カードを貼り付け(JSON)", - "ui.material_review.review": "カードを確認", - "ui.material_review.limit": "カードが256 KiBの入力上限を超えています。", - "ui.material_review.unknown": "不明", - "ui.material_review.properties": "特性", - "ui.material_review.conditions": "記載された条件", - "ui.material_review.source": "出典", - "ui.material_review.axes": "材料ローカル軸。ボディの方向は割り当てません。", - "ui.material_review.derived": "導出された等方性弾性率", - "ui.material_review.claims": "出典とライセンスの申告は未確認です。欠落値は不明のままです。", - "ui.material_review.density": "密度", - "ui.material_review.elasticity": "弾性", - "ui.material_review.tensile_strength": "引張強度", - "ui.material_review.compressive_strength": "圧縮強度", - "ui.material_review.yield_strength": "降伏強度", - "ui.material_review.shear_strength": "せん断強度", - "ui.material_review.thermal_conductivity": "熱伝導率", - "ui.material_review.thermal_expansion": "熱膨張", - "ui.material_review.specific_heat": "比熱", - "ui.material_review.moisture_unit": "kg 水 / kg 乾燥材料", "ui.coil": "コイル", "ui.coincident": "一致", "ui.collapse": "折りたたむ", @@ -599,6 +960,8 @@ "ui.colour_vision_tritan_tip": "青を感じにくい、または感じない場合に", "ui.combine": "結合", "ui.coming_later": "準備中", + "ui.command_done": "{command} 完了", + "ui.command_palette_hint": "コマンドを入力(例: {example})— または S キーで検索", "ui.concentric": "同心", "ui.configurations": "構成", "ui.conic_curve": "円錐曲線", @@ -617,7 +980,11 @@ "ui.create_sketch": "スケッチを作成", "ui.current": "現在", "ui.curvature": "曲率", + "ui.curvature_g2": "曲率連続 (G2)", "ui.curves": "曲線", + "ui.custom_program": "カスタム…", + "ui.custom_program_tip": "リストに追加するスライサーのプログラムを選択", + "ui.customizeToolbar": "ツールバーをカスタマイズ…", "ui.cut": "切り取り", "ui.cylinder": "円柱", "ui.dark": "ダーク", @@ -626,9 +993,25 @@ "ui.delete": "削除", "ui.depth": "深さ", "ui.design": "デザイン", + "ui.design_properties.author": "作成者", + "ui.design_properties.description": "説明", + "ui.design_properties.exports": "STEP、IGES、3MF のエクスポートでは、形式に対応する項目があればこれらが書き込まれます。", + "ui.design_properties.license": "ライセンス", + "ui.design_properties.not_text": "テキスト以外の値で保存されています。ここに入力すると置き換わります。", + "ui.design_properties.organization": "組織", + "ui.design_properties.others": "他のツールのデータ", + "ui.design_properties.others_note": "デザイン内にそのまま保持され、エクスポートされることはありません。", + "ui.design_properties.part_number": "部品番号", + "ui.design_properties.project": "プロジェクト", + "ui.design_properties.revision": "リビジョン", "ui.diameter": "直径", "ui.dimension": "寸法", "ui.direction": "方向", + "ui.display_quality": "表示品質", + "ui.display_quality_coarse": "粗い", + "ui.display_quality_fine": "細かい", + "ui.display_quality_normal": "標準", + "ui.display_quality_ultra": "最高", "ui.distance": "距離", "ui.distance_1": "距離 1", "ui.distance_2": "距離 2", @@ -638,12 +1021,16 @@ "ui.drawing": "図面", "ui.drill_point": "ドリル先端", "ui.edit": "編集", + "ui.editJointLimits": "ジョイント制限を編集", "ui.edit_section_analysis": "断面解析を編集", "ui.ellipse": "楕円", "ui.end_radius": "終了半径", + "ui.end_scale": "終端スケール", "ui.entities": "エンティティ", "ui.equal": "等しい", + "ui.equivalent_radius": "等価半径", "ui.expand": "展開", + "ui.exportDxf": "DXF をエクスポート…", "ui.export_ellipsis": "エクスポート…", "ui.export_ellipsis_keymap": "エクスポート…", "ui.export_keymap_tip": "ショートカット、Sボックスのお気に入り、ツールバー設定をファイルに保存", @@ -657,15 +1044,20 @@ "ui.file": "ファイル", "ui.fillet": "フィレット", "ui.filter_commands_or_keys": "コマンドまたはキーを検索", + "ui.findInTimeline": "タイムラインで検索", + "ui.findInWindow": "ウィンドウで検索", "ui.finish_sketch": "スケッチを終了", + "ui.fit": "フィット", "ui.fix_unfix": "固定/固定解除", "ui.flat": "展開", "ui.flip": "反転", + "ui.format": "形式", "ui.front": "正面", "ui.fully_constrained": "完全拘束", "ui.general": "一般", "ui.graphics": "グラフィックス", "ui.ground_shadow": "地面の影", + "ui.groupSelected": "選択をグループ化", "ui.heading_add_ins": "アドイン", "ui.heading_assemble": "アセンブリ", "ui.heading_box": "直方体", @@ -697,8 +1089,8 @@ "ui.heading_mirror": "ミラー", "ui.heading_modify": "修正", "ui.heading_move": "移動", - "ui.heading_offset": "オフセット", "ui.heading_move_copy": "移動/コピー", + "ui.heading_offset": "オフセット", "ui.heading_offset_plane": "オフセット平面", "ui.heading_ok": "OK", "ui.heading_parameters": "パラメータ", @@ -706,13 +1098,16 @@ "ui.heading_pipe": "パイプ", "ui.heading_plane_at_angle": "傾斜平面", "ui.heading_plastic": "プラスチック", + "ui.heading_position": "配置", "ui.heading_prepare": "準備", "ui.heading_rectangular_pattern": "矩形パターン", "ui.heading_revolve": "回転", "ui.heading_right": "右側面", + "ui.heading_save_mesh": "メッシュとして保存", "ui.heading_scale": "尺度", "ui.heading_section_analysis": "断面解析", "ui.heading_select": "選択", + "ui.heading_setup": "セットアップ", "ui.heading_sheet_metal": "板金", "ui.heading_shell": "シェル", "ui.heading_sketch": "スケッチ", @@ -730,15 +1125,22 @@ "ui.heading_utility": "ユーティリティ", "ui.help": "ヘルプ", "ui.hide": "非表示", + "ui.hideAxes": "軸を非表示", + "ui.hideDimension": "寸法を非表示", + "ui.hideOrigin": "原点を非表示", + "ui.hidePlanes": "平面を非表示", + "ui.hideProfile": "プロファイルを非表示", "ui.hole": "穴", "ui.hole_tap_type": "ねじ穴タイプ", "ui.hole_type": "穴タイプ", "ui.home": "ホーム", + "ui.homeView": "ホームビュー", "ui.horizontal_vertical": "水平/垂直", "ui.import_ellipsis": "インポート…", "ui.insert": "挿入", "ui.inspect": "検査", "ui.intersect": "交差", + "ui.isolate": "分離表示", "ui.join": "結合", "ui.joints": "ジョイント", "ui.keyboard_shortcuts": "キーボードショートカット", @@ -747,11 +1149,37 @@ "ui.light": "ライト", "ui.line": "線分", "ui.linetype": "線種", + "ui.lock": "ロック", "ui.loft": "ロフト", "ui.look_at": "正面視", "ui.look_at_anim_desc": "軸ビュー、正面視、ホーム、全体表示", "ui.manufacture": "製造", + "ui.material_review.axes": "材料ローカル軸。ボディの方向は割り当てません。", + "ui.material_review.claims": "出典とライセンスの申告は未確認です。欠落値は不明のままです。", + "ui.material_review.compressive_strength": "圧縮強度", + "ui.material_review.conditions": "記載された条件", + "ui.material_review.density": "密度", + "ui.material_review.derived": "導出された等方性弾性率", + "ui.material_review.elasticity": "弾性", + "ui.material_review.input": "スキーマ1の材料カードを貼り付け(JSON)", + "ui.material_review.limit": "カードが256 KiBの入力上限を超えています。", + "ui.material_review.moisture_unit": "kg 水 / kg 乾燥材料", + "ui.material_review.properties": "特性", + "ui.material_review.review": "カードを確認", + "ui.material_review.scope": "候補のみ:割り当てや保存は行いません。数値検証は工学的認証ではありません。", + "ui.material_review.shear_strength": "せん断強度", + "ui.material_review.source": "出典", + "ui.material_review.specific_heat": "比熱", + "ui.material_review.tensile_strength": "引張強度", + "ui.material_review.thermal_conductivity": "熱伝導率", + "ui.material_review.thermal_expansion": "熱膨張", + "ui.material_review.title": "物理材料データを確認", + "ui.material_review.unknown": "不明", + "ui.material_review.yield_strength": "降伏強度", "ui.measure": "計測", + "ui.mesh_format_3mf": "3MF", + "ui.mesh_format_3mf_tagged": "面タグ付き 3MF", + "ui.mesh_format_stl": "STL", "ui.midpoint": "中点", "ui.mirror": "ミラー", "ui.mirror_line": "ミラー線", @@ -761,9 +1189,13 @@ "ui.named_views": "名前付きビュー", "ui.navigation": "ナビゲーション", "ui.needs_design": "{command}: 先にデザインを開いてください", + "ui.newSketchGroup": "新しいスケッチグループ", "ui.new_body": "新規ボディ", "ui.new_design": "新規デザイン", + "ui.no_slicer_found": "スライサーが見つかりません", "ui.normal": "標準", + "ui.normalConstruction": "通常 / コンストラクション", + "ui.not_a_program": "{path} は起動できるプログラムではありません", "ui.object_type": "オブジェクトタイプ", "ui.objects": "オブジェクト", "ui.offer_to_stand_up_y_up_files": "Y-upファイルを正立させるか確認", @@ -776,10 +1208,13 @@ "ui.open_recent": "最近使った項目を開く", "ui.operation": "操作", "ui.options": "オプション", + "ui.orbit": "回転", "ui.orbit_around": "回転中心", + "ui.orientation": "向き", "ui.origin": "原点", "ui.palette_points": "点", "ui.palette_profile": "プロファイル", + "ui.pan": "パン", "ui.pan_zoom_orbit": "パン、ズーム、オービット", "ui.parallel": "平行", "ui.parameters": "パラメータ", @@ -788,6 +1223,8 @@ "ui.pattern_on_path": "パス上のパターン", "ui.perpendicular": "直交", "ui.perspective_view": "パースペクティブ表示", + "ui.pinToShortcuts": "ショートカットに固定", + "ui.pinToToolbar": "ツールバーに固定", "ui.pipe": "パイプ", "ui.placement": "配置", "ui.plane": "平面", @@ -803,63 +1240,59 @@ "ui.profiles": "プロファイル", "ui.project": "投影", "ui.project_face_edges_sketch": "新規スケッチに面のエッジを自動投影", + "ui.properties": "プロパティ", + "ui.pull_direction": "抜き方向", "ui.quantity": "数量", "ui.quantity_2": "数量 2", "ui.quit": "終了", "ui.radial_context_menu": "パイ メニュー", "ui.radius": "半径", - "ui.pull_direction": "抜き方向", - "ui.tool_direction": "工具方向", - "ui.reachable": "到達可能", - "ui.blocked": "到達不可", "ui.radius_type": "半径タイプ", + "ui.reachable": "到達可能", "ui.rectangle": "長方形", "ui.rectangular_pattern": "矩形パターン", "ui.redo": "やり直す", + "ui.removeFromToolbar": "ツールバーから削除", + "ui.removeSection": "セクションを解除", "ui.render": "レンダリング", "ui.renderer": "レンダラー", + "ui.repeat": "繰り返し", + "ui.report_a_bug": "不具合を報告", "ui.reset": "リセット", "ui.reset_all": "すべてリセット", "ui.reset_the_settings_on_this_page": "このページの設定をリセット", + "ui.restore": "復元", "ui.restore_defaults": "初期値に戻す", "ui.reverse_zoom_direction": "ズーム方向を反転", "ui.revolve": "回転", "ui.right": "右側面", "ui.save": "保存", - "ui.heading_save_mesh": "メッシュとして保存", - "ui.format": "形式", - "ui.mesh_format_stl": "STL", - "ui.mesh_format_3mf": "3MF", - "ui.mesh_format_3mf_tagged": "面タグ付き 3MF", - "ui.send_to_slicer": "スライサーに送る", - "ui.slicer": "スライサー", - "ui.custom_program": "カスタム…", - "ui.no_slicer_found": "スライサーが見つかりません", - "ui.send": "送信", - "ui.custom_program_tip": "リストに追加するスライサーのプログラムを選択", - "ui.slicer_delete_tip": "{program}\nDelete キーでリストから削除", - "ui.save_mesh_pick_bodies": "保存するボディを選択してください", - "ui.save_mesh_no_slicer": "スライサーが見つかりません。「カスタム…」でスライサーのプログラムを選ぶか、「スライサーに送る」をオフにしてください", - "ui.not_a_program": "{path} は起動できるプログラムではありません", - "ui.sent_to_slicer": "{slicer} に送信しました", - "ui.saved_to": "保存しました: {path}", - "ui.save_mesh_temp_failed": "{folder} を作成できません: {error}", "ui.save_as": "名前を付けて保存", "ui.save_as_ellipsis": "名前を付けて保存…", + "ui.save_mesh_no_slicer": "スライサーが見つかりません。「カスタム…」でスライサーのプログラムを選ぶか、「スライサーに送る」をオフにしてください", + "ui.save_mesh_pick_bodies": "保存するボディを選択してください", + "ui.save_mesh_temp_failed": "{folder} を作成できません: {error}", + "ui.saved_to": "保存しました: {path}", "ui.scale": "尺度", - "ui.orientation": "向き", - "ui.twist": "ねじれ", - "ui.end_scale": "終端スケール", - "ui.sweep_turn_with_path": "パスに沿って回転", - "ui.sweep_keep_as_drawn": "描いた向きを保持", - "ui.sweep_follow_direction": "方向に従う", "ui.section_analysis": "断面解析", "ui.select": "選択", + "ui.selectOther": "その他を選択…", + "ui.selectTangentChain": "接線チェーンを選択", "ui.select_other_hint": "その他を選択: モデル上で左ボタンを長押し(または右クリック › その他を選択…)するとカーソル下の要素が一覧表示されます。同じ場所を再度クリックすると次の要素が選択されます。", "ui.selection": "選択", + "ui.send": "送信", + "ui.send_to_slicer": "スライサーに送る", + "ui.sent_to_slicer": "{slicer} に送信しました", "ui.shell": "シェル", "ui.show": "表示", + "ui.showAll": "すべて表示", + "ui.showAllBodies": "すべてのボディを表示", + "ui.showAxes": "軸を表示", + "ui.showDimension": "寸法を表示", + "ui.showOrigin": "原点を表示", + "ui.showPlanes": "平面を表示", "ui.show_constraints": "拘束", + "ui.show_construction_geometries": "構築ジオメトリ", "ui.show_dimensions": "寸法", "ui.show_points": "点を表示", "ui.show_profile": "プロファイルを表示", @@ -874,6 +1307,8 @@ "ui.sketch_status": "スケッチの状態", "ui.sketches": "スケッチ", "ui.slice": "スライス", + "ui.slicer": "スライサー", + "ui.slicer_delete_tip": "{program}\nDelete キーでリストから削除", "ui.slot": "スロット", "ui.smooth": "スムーズ", "ui.smooth_wheel_zoom": "滑らかなホイールズーム", @@ -889,7 +1324,14 @@ "ui.stand_up_tip": "Z軸上向きで開いたSTEPまたはIGESファイルに対し、X軸周りに90度回転させるか確認します", "ui.start": "開始", "ui.start_radius": "開始半径", + "ui.supersampling": "スーパーサンプリング (SSAA)", + "ui.supersampling_adaptive": "ビューが静止しているときのみ", + "ui.supersampling_off": "オフ (1×)", + "ui.suppress": "抑制", "ui.sweep": "スイープ", + "ui.sweep_follow_direction": "方向に従う", + "ui.sweep_keep_as_drawn": "描いた向きを保持", + "ui.sweep_turn_with_path": "パスに沿って回転", "ui.symmetric": "対称", "ui.symmetry": "対称", "ui.system": "システム", @@ -905,18 +1347,26 @@ "ui.timeline_left_sidebar": "左サイドバー", "ui.tip_angle": "先端角度", "ui.to_object": "オブジェクトまで", + "ui.tool_direction": "工具方向", "ui.top": "上面", "ui.torus": "トーラス", + "ui.total_angle": "合計角度", "ui.trackpad_pan_tip": "トラックパッドのジェスチャーでパンします(オフの場合はマウスホイールと同様にズームします)。マウスホイールはズーム、サイドホイールは横方向のパン、ピンチ操作は常にズームになります。", "ui.trim": "トリム", + "ui.twist": "ねじれ", "ui.two_finger_scroll_pans": "2本指スクロールでパン", "ui.two_sides": "両側", "ui.ui_scale": "UIスケール", "ui.undo": "元に戻す", + "ui.unground": "固定を解除", + "ui.unisolate": "分離表示を解除", "ui.units": "単位", "ui.units_of_new_designs": "新規デザインの単位", + "ui.unlock": "ロック解除", + "ui.unsuppress": "抑制を解除", "ui.untitled": "無題", "ui.up_axis_note": "ビュー(軸ビュー、ホーム、正面視)で上向きにする軸を指定します。デザインデータ自体は変更されません。", + "ui.updateToCurrentView": "現在のビューに更新", "ui.variable": "可変", "ui.view_centre": "ビュー中心", "ui.visual_shaded_hidden_edges": "隠線付きシェーディング", @@ -928,492 +1378,41 @@ "ui.y_distance": "Y 距離", "ui.y_up": "Y軸上向き", "ui.z_up": "Z軸上向き", + "ui.zoom": "ズーム", "ui.zoom_to_cursor_tip": "マウスホイールでカーソル位置を基準にズームします(オフの場合はビューの中心を基準にズームします)。", "ui.zoom_to_the_cursor": "カーソル位置へズーム", - "A new configuration, a copy of the active one": "アクティブな構成をコピーして新しい構成を作成", - "About SolidCraft": "SolidCraft について", - "Active": "アクティブ", - "Active rule": "有効なルール", - "Add": "追加", - "Add Key": "キーを追加", - "Add Mid Radius": "中間半径を追加", - "Add Row": "行を追加", - "All Sketch Points": "すべてのスケッチ点", - "All open designs": "すべての開いているデザイン", - "Allowed expressions, separated by semicolons": "使用可能な式(セミコロンで区切る)", - "Also deletes": "同時に削除される要素:", - "Angle 2": "角度 2", - "Animate": "アニメーション", - "Appearance name": "外観名", - "Applied Radius": "適用半径", - "Apply To": "適用先", - "Area": "表面積", - "Attachment": "アタッチメント", - "BROWSER": "ブラウザ", - "Bend Line Position": "曲げ線位置", - "Bend Position": "曲げ位置", - "Bend Radius": "曲げ半径", - "Bends": "曲げ", - "Body": "ボディ", - "Bounding box": "境界ボックス", - "CSV or JSON: updates existing parameters, adds new ones": "CSVまたはJSON:既存のパラメータを更新し、新しいパラメータを追加します", - "Capture All Positions": "すべての位置をキャプチャ", - "Catch Direction": "キャッチ方向", - "Cells": "セル", - "Center X": "中心 X", - "Center Y": "中心 Y", - "Center of mass": "重心", - "Chamfer Type": "面取りタイプ", - "Check collisions": "衝突チェック", - "Checked": "チェック済み", - "Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.": "新しい平面を選択してください。スケッチジオメトリと寸法は2次元座標系のまま維持されます。", - "Close draft": "下書きを閉じる", - "Collisions": "衝突", - "Colour": "色", - "Component1": "コンポーネント1", - "Configuration": "構成", - "Configuration rules": "構成ルール", - "Contact": "接触", - "Copy all licences": "すべてのライセンスをコピー", - "Copy diagnostic information": "診断情報をコピー", - "Copy report": "レポートをコピー", - "Corner Relief": "コーナーリリーフ", - "Corner Relief Shape": "コーナーリリーフ形状", - "Notch": "ノッチ", - "Round": "円形", - "Rectangular": "長方形", - "Tear": "引き裂き", - "Counterbore depth": "座ぐり深さ", - "Countersink angle": "皿穴角度", - "Create Issue — review draft": "Issueを作成 — 下書きの確認", - "Customize Toolbar": "ツールバーのカスタマイズ", - "Delete all": "すべて削除", - "Delete rule": "ルールを削除", - "Delete the row": "行を削除", - "Delete the set": "セットを削除", - "Delete this parameter": "このパラメータを削除", - "Density": "密度", - "Designs you open or save appear here.": "開いたデザインや保存したデザインがここに表示されます。", - "Determined by To Object. Choose Angle to edit the angular extent.": "「対象オブジェクトまで」により決定されます。角度範囲を編集するには「角度」を選択してください。", - "Discard": "破棄", - "Double-click to rename": "ダブルクリックで名前変更", - "Drive Joint": "ジョイントを駆動", - "Edit Profile Sketch": "プロファイルスケッチを編集", - "Enable rule": "ルールを有効化", - "Enabled": "有効", - "Explode": "分解", - "Extents": "範囲", - "Face attachment lost": "面アタッチメントが失われました", - "Faces / edges / vertices": "面 / エッジ / 頂点", - "Favourite": "お気に入り", - "Files from many CAD programs have Y up, so they open lying on their back here (Z up).": "多くのCADではY軸を上向きとしているため、Z軸を上向きとするSolidCraftでは、読み込んだモデルが横倒しの向きで表示されることがあります。", - "Filter": "フィルター", - "Find in Browser": "ブラウザで検索", - "Copy Error Message": "エラーメッセージをコピー", - "Copy Warning Message": "警告メッセージをコピー", - "Flat size": "展開サイズ", - "Follow camera (Look At sketches)": "カメラ追従(スケッチを正面視)", - "Font": "フォント", - "Full Length": "全長", - "Gap": "ギャップ", - "Grid": "グリッド", - "Height": "高さ", - "Home view": "ホームビュー", - "In This Design": "このデザイン内", - "Interferes": "干渉あり", - "Issue title": "Issueタイトル", - "Joint Origin1": "ジョイント原点1", - "Keep Tools": "ツールボディを保持", - "Later": "後で", - "Leave it": "そのままにする", - "Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "従来の面アタッチメントです。確定された面に再バインドすると正確なアタッチメントが作成されます。", - "Length": "長さ", - "Length units": "長さの単位", - "Library": "ライブラリ", - "Loop": "ループ", - "Margin": "マージン", - "Mass": "質量", - "Material": "材料", - "Mid Radius": "中間半径", - "Modeled": "モデル化済み", - "More toolbar panels": "その他のツールバーパネル", - "Motion": "モーション", - "Move Type": "移動タイプ", - "Move earlier": "前へ移動", - "Move later": "後へ移動", - "Name": "名前", - "No crash reports.": "クラッシュレポートはありません。", - "No matching appearances": "一致する外観がありません", - "Not available yet": "まだ利用できません", - "Opacity": "不透明度", - "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": "反対側", - "Parameter values": "パラメータ値", - "Per Edge": "エッジごと", - "Pick the tool bodies": "ツールボディを選択", - "Place at the origin instead": "代わりに原点に配置", - "Playback": "再生", - "Position": "位置", - "Position (0 to 1)": "位置 (0〜1)", - "Position along the edge, 0 at the start end, 1 at the other": "エッジ上の位置(始点が0、終点が1)", - "Preview leaves the current design unchanged.": "プレビューは現在のデザインを変更しません。", - "RECENT": "最近使用した項目", - "Radius Fit": "半径フィット", - "Ratio": "比率", - "Recover": "復元", - "Recover unsaved design?": "未保存のデザインを復元しますか?", - "Remove Tools": "ツールボディを削除", - "Remove from list": "リストから削除", - "Remove private design details or paths before sharing.": "共有前に、非公開の設計情報やファイルパスを削除してください。", - "Remove the column": "列を削除", - "Remove the track": "トラックを削除", - "Remove this point": "この点を削除", - "Report a bug — review a screenshot and open a GitHub draft": "バグを報告 — スクリーンショットを確認してGitHub下書きを作成", - "Reset Toolbar": "ツールバーをリセット", - "Restore the inherited component or physical material appearance": "コンポーネントまたは物理マテリアルから継承した外観に戻す", - "Result": "結果", - "Retake screenshot": "スクリーンショットを再取得", - "Reverse": "反転", - "Reverse Direction": "方向を反転", - "Revert": "元に戻す", - "Revert All Positions": "すべての位置を元に戻す", - "Review the report and screenshot before opening GitHub.": "GitHubを開く前にレポートとスクリーンショットを確認してください。", - "Rim Edge": "リムエッジ", - "Roll History Marker Here": "履歴マーカーをここに移動", - "Rule": "ルール", - "Saved preview. Geometry is being checked before editing.": "保存済みのプレビューです。編集前にジオメトリを検証しています。", - "Scale factor": "尺度係数", - "Search": "検索", - "Search commands": "コマンドを検索", - "Select bodies (a face picks its body)": "ボディを選択(面をクリックするとそのボディが選択されます)", - "Select bodies or faces instead": "代わりにボディまたは面を選択", - "Selection filter": "選択フィルター", - "Semantic faces share their appearance across instances.": "セマンティック面はインスタンス間で外観を共有します。", - "Shape": "形状", - "Show Agent Cursor": "エージェントカーソルを表示", - "Show in folder": "フォルダに表示", - "Size": "サイズ", - "Sketch plane has no body-face attachment.": "スケッチ平面にボディ面のアタッチメントがありません。", - "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "これらのデザインが保存される前にSolidCraftが終了しました。最後の自動保存ファイルを開くことができます。", - "Speed": "速度", - "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?": "このパーツを正立させますか?", - "Step": "ステップ", - "Steps": "ステップ数", - "Suppressed": "抑制", - "Swap Ends": "端点を入れ替え", - "Tangent Chain": "正接チェーン", - "The dashed sketch is a saved plane guide. Select a new face to repair the attachment.": "破線のスケッチは保存された平面ガイドです。新しい面を選択してアタッチメントを修復してください。", - "The saved author occurrence is missing. Select a valid author placement before rebinding.": "保存された作成元のオカレンスが見つかりません。再バインドする前に有効な作成元配置を選択してください。", - "Then": "次を実行 (Then)", - "These features will be deleted:": "以下のフィーチャーが削除されます:", - "These features will fail:": "以下のフィーチャーでエラーが発生します:", - "This child is shared. Deleting it removes it from 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.": "この面は安定したアタッチメントを提供できません。別の面を選択するか、固定平面を明示的に使用してください。", - "To Offset": "オフセットまで", - "Tolerance": "公差", - "Type": "タイプ", - "Updating the preview": "プレビューを更新中", - "Use fixed plane": "固定平面を使用", - "VIEW": "表示", - "Value": "値", - "Volume": "体積", - "Wall": "肉厚", - "When": "条件 (When)", - "Width": "幅", - "Will fail": "失敗します", - "angle, height": "角度, 高さ", - "command name": "コマンド名", - "expression, e.g. 25 mm": "計算式 (例: 25 mm)", - "fits the face, e.g. M8": "面に適合するサイズ (例: M8)", - "from the rule": "ルールから", - "needs two joints": "2つのジョイントが必要", - "new configuration": "新規構成", - "new name": "新しい名前", - "new parameter": "新規パラメータ", - "no interference": "干渉なし", - "no joint that moves yet": "可動ジョイントがまだありません", - "no picture": "画像なし", - "pick a hole to seat it, or OK places it at the origin": "配置先の穴を選択するか、[OK]を押すと原点に配置します。", - "pick one or two vertices, edges or faces": "1つまたは2つの頂点、エッジ、面を選択", - "the parts library is not available": "パーツライブラリは利用できません", - "to the next face": "次の面まで", - "Revert Position": "位置を元に戻す", - "Construction": "コンストラクション", - "Flat": "展開", - "Faces": "面", - "Edges": "エッジ", - "Vertices": "頂点", - "Sketch geometry and profiles": "スケッチジオメトリとプロファイル", - "Sketch curves": "スケッチ曲線", - "Sketch points": "スケッチ点", - "Sketch dimensions": "スケッチ寸法", - "Sketch constraints": "スケッチ拘束", - "0 turns it off": "0で無効化", - "Show the pointer an AI agent moves (#35)": "エージェントが操作するポインターを表示 (#35)", - "Follow the camera (Look At sketches)": "カメラ追従(スケッチを正面視)", - "Save Rule": "ルールを保存", - "Preview Row": "行をプレビュー", - "Add condition": "条件を追加", - "Apply to selection": "選択項目に適用", - "Remove override": "オーバーライドを削除", - "Copy screenshot": "スクリーンショットをコピー", - "Remove screenshot": "スクリーンショットを削除", - "Use active author placement": "アクティブな作成元配置を使用", - "Reattach selected face": "選択した面を再アタッチ", - "Use saved fixed plane": "保存された固定平面を使用", - "Use selected face as fixed plane": "選択した面を固定平面として使用", - "View navigator": "ビューナビゲーター", - "Signed axes": "符号付き座標軸", - "Cube": "キューブ", - "Middle double-click": "中ボタンのダブルクリック", - "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": "ビュー上で中ボタンをダブルクリックした時の動作: ホーム(全体を収めたホームビュー)、全体表示(向きを維持して全体を収める)、または無効", - "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).": "その他を選択: モデル上で左ボタンを長押し(または右クリック › その他を選択…)するとカーソル下の要素が一覧表示されます。同じ場所を再度クリックすると次の要素が選択されます。中ボタンをダブルクリックするとホームビューに戻ります(環境設定 › ナビゲーション)。", - "cmd.render_backends": "レンダリング バックエンド", - "cmd.view_navigate": "ビューナビゲーション", - "ui.animateJoint": "ジョイントをアニメート", - "ui.calibrate": "校正", - "ui.customizeToolbar": "ツールバーをカスタマイズ…", - "ui.editJointLimits": "ジョイント制限を編集", - "ui.exportDxf": "DXF をエクスポート…", - "ui.findInTimeline": "タイムラインで検索", - "ui.findInWindow": "ウィンドウで検索", - "ui.fit": "フィット", - "ui.groupSelected": "選択をグループ化", - "ui.hideAxes": "軸を非表示", - "ui.hideDimension": "寸法を非表示", - "ui.hideOrigin": "原点を非表示", - "ui.hidePlanes": "平面を非表示", - "ui.hideProfile": "プロファイルを非表示", - "ui.homeView": "ホームビュー", - "ui.isolate": "分離表示", - "ui.lock": "ロック", - "ui.newSketchGroup": "新しいスケッチグループ", - "ui.normalConstruction": "通常 / コンストラクション", - "ui.orbit": "回転", - "ui.heading_position": "配置", - "ui.pan": "パン", - "ui.pinToShortcuts": "ショートカットに固定", - "ui.pinToToolbar": "ツールバーに固定", - "ui.properties": "プロパティ", - "ui.design_properties.project": "プロジェクト", - "ui.design_properties.part_number": "部品番号", - "ui.design_properties.revision": "リビジョン", - "ui.design_properties.author": "作成者", - "ui.design_properties.organization": "組織", - "ui.design_properties.description": "説明", - "ui.design_properties.license": "ライセンス", - "ui.design_properties.not_text": "テキスト以外の値で保存されています。ここに入力すると置き換わります。", - "ui.design_properties.exports": "STEP、IGES、3MF のエクスポートでは、形式に対応する項目があればこれらが書き込まれます。", - "ui.design_properties.others": "他のツールのデータ", - "ui.design_properties.others_note": "デザイン内にそのまま保持され、エクスポートされることはありません。", - "ui.removeSection": "セクションを解除", - "ui.removeFromToolbar": "ツールバーから削除", - "ui.repeat": "繰り返し", - "ui.report_a_bug": "不具合を報告", - "ui.restore": "復元", - "ui.heading_setup": "セットアップ", - "ui.selectOther": "その他を選択…", - "ui.selectTangentChain": "接線チェーンを選択", - "ui.showAll": "すべて表示", - "ui.showAllBodies": "すべてのボディを表示", - "ui.showAxes": "軸を表示", - "ui.showDimension": "寸法を表示", - "ui.showOrigin": "原点を表示", - "ui.showPlanes": "平面を表示", - "ui.suppress": "抑制", - "ui.command_palette_hint": "コマンドを入力(例: {example})— または S キーで検索", - "ui.unground": "固定を解除", - "ui.unisolate": "分離表示を解除", - "ui.unlock": "ロック解除", - "ui.unsuppress": "抑制を解除", - "ui.updateToCurrentView": "現在のビューに更新", - "ui.zoom": "ズーム", - "ui.command_done": "{command} 完了", - "drive.stopped_by_loop": "{value} で停止: {joint} を通るループはこれ以上閉じられません", - "drive.stopped_by_contact": "{value} で停止: {a} が {b} を通り抜けてしまいます", - "drive.unconnected": "何も動きません: {part} は空間固定されたものに接続されていません", - "timeline.group": "フィーチャーフォルダを新規作成", - "timeline.ungroup": "フィーチャーフォルダを削除", - "timeline.rename_group": "フィーチャーフォルダの名前を変更", - "timeline.move_to_group": "フィーチャーをフォルダへ移動", - "timeline.move_many": "タイムライン項目を移動", - "timeline.reorder_many": "フィーチャーの順序を変更", - "ui.show_construction_geometries": "構築ジオメトリ", - "ui.total_angle": "合計角度", - "sketch_text.builtin_font": "{family}(内蔵)", - "sketch_text.font_search": "フォントを検索", - "sketch_text.loading_fonts": "インストール済みフォントを検索中…", - "sketch_text.use_font_file": "フォント ファイル {path} を使用", - "sketch_text.bold": "太字", - "sketch_text.italic": "斜体", - "sketch_text.align_left": "左", - "sketch_text.align_center": "中央", - "sketch_text.align_right": "右", - "sketch_text.path_hint": "文字が沿うスケッチの曲線: ここをクリックしてから曲線をクリック", - "sketch_text.path_clear": "文字を曲線から外す", - "Style": "スタイル", - "Alignment": "配置", - "Letter Spacing": "文字間隔", - "Line Spacing": "行間", - "Path": "パス", - "sketch_text.on_path": "文字はパスに沿います: 位置は曲線で決まります", - "cmd.library_inspect": "ローカルライブラリを確認", - "cmd.library_export": "デザインライブラリを書き出す", - "cmd.library_apply": "ローカルライブラリ項目を適用", - "Thin": "薄肉", - "Thin Extrude": "薄肉押し出し", - "Wall Location": "壁の位置", - "Wall Thickness": "壁の厚さ", - "Thickness Outside": "外側の厚さ", - "Inside": "内側", - "Outside": "外側", - "Profiles/Curves": "プロファイル/曲線", - "cmd.material_properties_validate": "物理材料データを検証", - "cmd.material_properties_directional": "方向別弾性率", + "update.available": "SolidCraft {version} が利用できます", "update.button": "アップデート", "update.button_tip": "SolidCraft {version} が利用できます", - "install.menu": "アプリをインストール…", - "install.button_tip": "SolidCraft をアプリとしてインストールします。専用のウィンドウで開き、オフラインでも使えます", - "install.title": "SolidCraft をインストール", - "install.steps_intro": "Safari では、Web アプリを Safari 自身のメニューからインストールします:", - "install.home_screen_1": "「共有」をタップします(ツールバーにない場合は … メニューの中にあります)。", - "install.home_screen_2": "「ホーム画面に追加」を選びます。", - "install.home_screen_3": "「追加」をタップします。", - "install.home_screen_after": "SolidCraft はホーム画面のアイコンから Safari のツールバーなしで開き、オフラインでも使えます。", - "install.dock_1": "「ファイル」›「Dockに追加」を選びます。", - "install.dock_2": "「追加」をクリックします。", - "install.dock_after": "SolidCraft は Dock から専用のウィンドウで開き、オフラインでも使えます。", - "install.done": "完了", - "update.title": "アップデートがあります", - "update.available": "SolidCraft {version} が利用できます", - "update.you_have": "現在のバージョンは {version} です。", - "update.no_notes": "このリリースにはリリースノートがありません。", - "update.system_hint": "このコピーは {kind} です。次のコマンドで更新します:", - "update.package_hint": "このコピーは {kind} からインストールされました。新しいパッケージをダウンロードし、次のコマンドでインストールします:", - "update.copy": "コピー", - "update.file": "ダウンロードするファイル: {file}", - "update.download": "ダウンロード", - "update.release_page": "リリースページを開く", - "update.skip": "このバージョンをスキップ", - "update.later": "後で通知", - "update.prefs_label": "アップデート", "update.check_automatically": "アップデートを自動的に確認", "update.check_now": "今すぐ確認", "update.checking": "確認中…", - "update.failed": "確認できませんでした: {error}", - "update.up_to_date": "SolidCraft は最新です。", - "update.prefs_note": "これは SolidCraft {version} ({kind}) です。確認では GitHub に最新リリースを問い合わせるだけで、ほかには何も送信しません。", - "update.prefs_dev": "これは開発ビルド ({version}) のため、アップデートを確認しません。", - "update.show": "{version} へのアップデートを表示", - "update.prefs_flatpak": "このコピー ({version}) は Flatpak が更新します: {command} を実行するか、ソフトウェアセンターを使ってください。SolidCraft 自身は確認しません。", - "update.update_now": "今すぐ更新", - "update.install_msi": "インストール (SolidCraft を終了)", + "update.copy": "コピー", + "update.dmg_opened": "ディスクイメージを検証して開きました: SolidCraft をアプリケーションフォルダにドラッグして古いものを置き換え、SolidCraft を再起動してください。", + "update.download": "ダウンロード", "update.download_open": "ダウンロードして開く", "update.downloading": "ダウンロードと検証中… {done} / {total} MB", + "update.failed": "確認できませんでした: {error}", + "update.file": "ダウンロードするファイル: {file}", + "update.install_failed": "アップデートをインストールできませんでした: {error}。何も変更されていません。「ダウンロード」でパッケージを入手できます。", + "update.install_msi": "インストール (SolidCraft を終了)", "update.installed": "SolidCraft {version} をインストールしました。再起動すると使えます。", + "update.installer_started": "SolidCraft の終了後にインストーラーが起動します。", + "update.later": "後で通知", + "update.no_notes": "このリリースにはリリースノートがありません。", + "update.package_hint": "このコピーは {kind} からインストールされました。新しいパッケージをダウンロードし、次のコマンドでインストールします:", + "update.prefs_dev": "これは開発ビルド ({version}) のため、アップデートを確認しません。", + "update.prefs_flatpak": "このコピー ({version}) は Flatpak が更新します: {command} を実行するか、ソフトウェアセンターを使ってください。SolidCraft 自身は確認しません。", + "update.prefs_label": "アップデート", + "update.prefs_note": "これは SolidCraft {version} ({kind}) です。確認では GitHub に最新リリースを問い合わせるだけで、ほかには何も送信しません。", + "update.release_page": "リリースページを開く", "update.restart": "今すぐ再起動", "update.restart_later": "後で", - "update.installer_started": "SolidCraft の終了後にインストーラーが起動します。", - "update.dmg_opened": "ディスクイメージを検証して開きました: SolidCraft をアプリケーションフォルダにドラッグして古いものを置き換え、SolidCraft を再起動してください。", - "update.install_failed": "アップデートをインストールできませんでした: {error}。何も変更されていません。「ダウンロード」でパッケージを入手できます。", - "cmd.render_settings_get": "レンダリング設定", - "cmd.render_settings_set": "レンダリング設定を保存", - "cmd.render_scene": "レンダリングシーンを確認", - "cmd.render_settings_apply": "レンダリングカメラを適用", - "toolbar.render": "レンダリング", - "toolbar.render_scene": "シーン", - "render.preview": "統合プレビュー", - "render.preview_help": "ラスタシェーディングとブレンド透明度を使用します。屈折、HDRI、最終レンダリングはまだ利用できません。", - "render.setup_name": "セットアップ名", - "render.background": "シーンの背景", - "render.perspective": "透視投影カメラ", - "render.fit": "製品を画面に合わせる", - "render.restore_camera": "保存したカメラを復元", - "render.save_setup": "セットアップを保存", - "render.unsaved": "未保存のプレビュー変更", - "render.reload_settings": "保存した設定を再読み込み", - "render.unavailable_preview": "このセットアップは利用できないプレビュープロファイルを要求しています。", - "render.use_preview": "統合プレビューを使用", - "render.navigation_help": "カメラはデザインと同じように動きます(環境設定 › ナビゲーション)。「セットアップを保存」で現在のカメラを記録します。", - "render.return_design": "設計に戻る", - "render.image_title": "画像をレンダリング", - "render.image_help": "CPUプレビュー画像 · PNG · 近似透過", - "render.image_width": "幅", - "render.image_height": "高さ", - "render.image_transparent": "透明な背景", - "render.image_check": "レンダリング要求を確認", - "render.image_supported": "レンダリング要求に対応しています。開始時にキューとメモリを再確認します。", - "render.image_queued": "レンダリング待機中", - "render.image_preparing": "画像を準備中", - "render.image_running": "画像をレンダリング中", - "render.image_encoding": "PNGをエンコード中", - "render.image_cancelling": "キャンセル中", - "render.image_cancelled": "レンダリングをキャンセルしました", - "render.image_completed": "画像をエクスポートできます", - "render.image_failed": "レンダリングに失敗しました", - "render.image_unknown": "レンダリング状態を取得できません", - "render.image_reduce": "画像を小さくするかシーンを簡略化してください。", - "render.image_too_large": "画像の上限を超えています:一辺 4096 ピクセル、合計 4,194,304 ピクセル。", - "render.image_use_largest": "この縦横比での最大サイズを使用:", - "render.image_cancel": "レンダリングをキャンセル", - "render.image_stale": "この画像は後続の変更前に取得したシーンを使用しています。", - "render.image_start": "レンダリングを開始", - "render.image_overwrite": "既存のファイルを置換", - "render.image_export": "PNGをエクスポート", - "cmd.render_preflight": "レンダリング要求を確認", - "cmd.render_start": "画像をレンダリング", - "cmd.render_status": "レンダリングの進行状況", - "cmd.render_cancel": "レンダリングをキャンセル", - "cmd.render_export": "PNGをエクスポート", - "toolbar.image": "画像", - "appearance.surface_response": "表面の応答", - "appearance.pbr_opaque": "不透明PBR", - "appearance.metallic": "金属度", - "appearance.roughness": "粗さ", - "appearance.dielectric_ior": "誘電体の屈折率", - "appearance.pbr_help": "この表面はレンダリング作業空間または製品PNGで確認できます。屈折や透過には対応していません。", - "render.opaque_preview_help": "不透明PBRと単色表示、アルファ合成による透明表示に対応します。屈折、HDRI、最終レンダリングにはまだ対応していません。", - "render.opaque_image_summary": "プレビューPNG · 不透明PBR · アルファ合成の透明表示", - "UNTRIM": "トリム解除", - "Face": "面", - "Holes": "穴", - "Holes (edges on them)": "穴(そのエッジ)", - "In place (surfaces)": "その場で(サーフェス)", - "None": "なし", - "Picked": "選択したもの", - "Restore outer boundary": "外側の境界を復元", - "RULED SURFACE": "ルールドサーフェス", - "Mitre": "留め継ぎ", - "Reference face": "参照面", - "Round": "丸め", - "joint.one_component": "これらの部品は 1 つのコンポーネントのボディです: {bodies}。ジョイントはコンポーネント同士を動かすため、部品ごとに専用のコンポーネントが必要です。", - "joint.one_body": "両方の選択が {body} 上にあります。2 つ目は別の部品で選択してください。", - "joint.from_bodies_hint": "選択した各ボディを、位置はそのままで専用の新しいコンポーネントに移動します。", - "Circumference": "円周", - "Arc length": "円弧の長さ", - "Slot width": "長穴の幅", - "Centre to centre": "中心間", - "Overall length": "全長", - "Min": "最小", - "Max": "最大", - "coupling.gear_1": "ギア 1", - "coupling.gear_2": "ギア 2", - "coupling.pinion": "ピニオン", - "coupling.rack": "ラック", - "coupling.nut": "ナット", - "coupling.radius_1": "半径 1", - "coupling.radius_2": "半径 2", - "coupling.internal": "内歯車", - "coupling.pitch": "ピッチ", - "coupling.picked": "選択済み", - "coupling.not_round": "円筒面ではありません", - "coupling.gear_1_pick": "ギア 1 (オプション)", - "coupling.gear_2_pick": "ギア 2 (オプション)", - "coupling.pinion_pick": "ピニオン (オプション)", - "coupling.needs_turns": "回転するジョイントが 2 つ必要", - "coupling.needs_turn_and_slide": "回転するジョイントとスライドするジョイントが必要" + "update.show": "{version} へのアップデートを表示", + "update.skip": "このバージョンをスキップ", + "update.system_hint": "このコピーは {kind} です。次のコマンドで更新します:", + "update.title": "アップデートがあります", + "update.up_to_date": "SolidCraft は最新です。", + "update.update_now": "今すぐ更新", + "update.you_have": "現在のバージョンは {version} です。" } diff --git a/assets/locales/ko.json b/assets/locales/ko.json index ccde07225..c532303d1 100644 --- a/assets/locales/ko.json +++ b/assets/locales/ko.json @@ -1,670 +1,90 @@ { - "settings.measure_axis_distances": "X/Y/Z 거리 표시", - "settings.measure_axis_distances_help": "측정 대화상자가 열려 있는 동안 전체 거리와 함께 월드 축 방향 치수와 거리를 표시합니다.", - "Export Current View as DXF": "현재 뷰를 DXF로 내보내기", - "Export Current View as DXF…": "현재 뷰를 DXF로 내보내기…", - "Hidden edges": "숨겨진 모서리", - "Do not export hidden edges": "숨겨진 모서리 내보내지 않기", - "Export hidden edges as dashed lines": "숨겨진 모서리를 파선으로 내보내기", - "Projection": "투영", - "Current perspective view": "현재 원근 투영 뷰", - "Current orthographic view (1:1 mm)": "현재 직교 투영 뷰 (1:1 mm)", - "Visible bodies only. Curves use line segments (0.01 mm tolerance).": "표시된 바디만 내보냅니다. 곡선은 선분으로 근사합니다 (허용오차 0.01 mm).", - "Turn off section analysis before exporting the view.": "뷰를 내보내기 전에 단면 분석을 끄세요.", - "No visible bodies to export.": "표시된 바디가 없어 내보낼 수 없습니다.", - "Export DXF…": "DXF 내보내기…", - "Send your report on GitHub": "GitHub에서 보고서 보내기", "1. Open GitHub draft below, then paste the report copied to your clipboard.": "1. 아래에서 GitHub 초안을 열고 클립보드에 복사된 보고서를 붙여넣으세요.", "1. Open GitHub draft below. Your title and report will be filled in.": "1. 아래에서 GitHub 초안을 여세요. 제목과 보고서가 자동으로 입력됩니다.", "2. Attach your screenshot: copy and paste it, or save and upload the PNG.": "2. 스크린샷을 첨부하세요. 복사하여 붙여넣거나 PNG로 저장한 뒤 업로드하세요.", "3. Click Submit new issue on GitHub to send your report.": "3. GitHub에서 Submit new issue를 클릭하여 보고서를 보내세요.", - "nav.touchpad.label": "터치패드", - "nav.touchpad.help": "Shift를 누른 채 포인터를 움직이면 화면이 이동하고, Alt/Option을 누른 채 움직이면 회전합니다. 마우스 버튼은 필요 없습니다. 세로 스크롤로 확대/축소합니다.", - "nav.touchpad.orbit": "회전 (Alt/Option을 누르고 이동, 마우스 버튼 불필요)", - "nav.touchpad.pan": "화면 이동 (Shift를 누르고 이동, 마우스 버튼 불필요)", - "nav.touchpad.zoom": "확대/축소 (세로 스크롤 또는 핀치)", - "nav.touchpad.scroll": "터치패드는 세로 스크롤로 확대/축소합니다. 두 손가락 이동 설정은 다른 프리셋을 위해 유지됩니다.", + "AI": "AI", + "Arc length": "호 길이", + "Area": "면적", + "BROWSER": "브라우저", + "Bends": "벤딩", + "Centre to centre": "중심 간", + "Circumference": "원주", + "Construction": "구성선", + "Copy Error Message": "오류 메시지 복사", + "Copy Warning Message": "경고 메시지 복사", + "Corner Relief": "모서리 릴리프", + "Current orthographic view (1:1 mm)": "현재 직교 투영 뷰 (1:1 mm)", + "Current perspective view": "현재 원근 투영 뷰", + "Do not export hidden edges": "숨겨진 모서리 내보내지 않기", + "Drive Joint": "조인트 구동", + "Edges": "모서리", + "Edit Profile Sketch": "윤곽 스케치 편집", + "Export Current View as DXF": "현재 뷰를 DXF로 내보내기", + "Export Current View as DXF…": "현재 뷰를 DXF로 내보내기…", + "Export DXF…": "DXF 내보내기…", + "Export hidden edges as dashed lines": "숨겨진 모서리를 파선으로 내보내기", + "Face": "면", + "Faces": "면", + "Find in Browser": "브라우저에서 찾기", + "Flat": "플랫", + "Hidden edges": "숨겨진 모서리", + "Holes": "구멍", + "Holes (edges on them)": "구멍 (구멍의 모서리)", + "In place (surfaces)": "제자리에서 (서피스)", + "Inside": "안쪽", + "Length": "길이", + "Max": "최대", + "Min": "최소", + "Mitre": "연귀", + "No visible bodies to export.": "표시된 바디가 없어 내보낼 수 없습니다.", + "None": "없음", + "Notch": "노치", + "Outside": "바깥쪽", + "Overall length": "전체 길이", + "Picked": "선택한 항목", + "Profiles/Curves": "프로파일/곡선", + "Projection": "투영", + "RULED SURFACE": "룰드 서피스", + "Rectangular": "직사각형", + "Reference face": "참조 면", + "Report a bug — review a screenshot and open a GitHub draft": "버그 신고 — 스크린샷을 검토하고 GitHub 초안 열기", + "Reset Toolbar": "도구 모음 재설정", + "Restore outer boundary": "외부 경계 복원", + "Revert Position": "위치 복원", + "Round": "둥글게", + "Select bodies (a face picks its body)": "바디 선택(면을 클릭하면 해당 바디 선택)", + "Selection filter": "선택 필터", + "Send your report on GitHub": "GitHub에서 보고서 보내기", + "Sketch constraints": "스케치 구속 조건", + "Sketch curves": "스케치 곡선", + "Sketch dimensions": "스케치 치수", + "Sketch geometry and profiles": "스케치 기하 및 프로파일", + "Sketch points": "스케치 점", + "Slot width": "슬롯 폭", + "Tear": "찢김", + "Thickness Outside": "바깥쪽 두께", + "Thin": "얇은 벽", + "Thin Extrude": "얇은 벽 돌출", + "Turn off section analysis before exporting the view.": "뷰를 내보내기 전에 단면 분석을 끄세요.", + "Type": "유형", + "UNTRIM": "트림 해제", + "Vertices": "꼭짓점", + "Visible bodies only. Curves use line segments (0.01 mm tolerance).": "표시된 바디만 내보냅니다. 곡선은 선분으로 근사합니다 (허용오차 0.01 mm).", + "Wall Location": "벽 위치", + "Wall Thickness": "벽 두께", + "appearance.dielectric_ior": "유전체 굴절률", + "appearance.metallic": "금속성", + "appearance.pbr_help": "이 표면은 렌더링 작업 공간이나 제품 PNG에서 확인하세요. 굴절과 투과는 지원하지 않습니다.", + "appearance.pbr_opaque": "불투명 PBR", + "appearance.roughness": "거칠기", + "appearance.surface_response": "표면 반응", "browser.body_name": "바디{number}", "browser.component_name": "컴포넌트{number}", "browser.parameters": "매개변수 ({count})", "browser.precision": "정밀도: {precision}", "browser.sketch_name": "스케치{number}", "browser.units": "단위: {units}", - "dialog.computing": "계산 중… {seconds}초", - "dialog.custom_axis": "↖ 사용자 정의 축", - "dialog.edit_title": "{title} 편집", - "dialog.select": "↖ 선택", - "dialog.selected_count": "↖ {count}개 선택됨", - "dialog.step": "단계", - "dialog.selection_step": "{step}/{total} 단계: {input} 선택", - "dialog.selection_guidance": "변경할 입력을 선택하세요. 선택한 객체를 클릭하면 선택이 해제되며, Ctrl/Cmd를 누른 채 클릭해도 전환됩니다. 미리 보기를 확인한 다음 확인을 누르세요.", - "document.save_changes": "{name}의 변경 사항을 저장하시겠습니까?", - "document.unsaved_changes": "{name}에 저장되지 않은 변경 사항이 있습니다. 저장하지 않으면 변경 사항이 사라집니다.", - "home.documentation": "문서", - "home.in_this_browser": "이 브라우저에 저장됨", - "home.missing": "찾을 수 없음", - "home.open": "열기…", - "home.opened_days_ago": "{count}일 전에 열림", - "home.opened_hours_ago": "{count}시간 전에 열림", - "home.opened_just_now": "방금 열림", - "home.opened_minutes_ago": "{count}분 전에 열림", - "home.opening": "여는 중…", - "home.recent": "최근 항목", - "home.report_issue": "문제 신고", - "home.samples": "샘플", - "home.whats_new": "새로운 기능", - "sample.bracket.about": "2 mm 판금 규칙을 적용한 베이스 플랜지, 에지 플랜지, 헴", - "sample.bracket.name": "판금 브래킷", - "sample.enclosure.about": "리프, 나사 보스, 레스트, 스냅핏이 있는 쉘 처리된 박스", - "sample.enclosure.name": "플라스틱 인클로저", - "sample.flange.about": "매개변수로 제어되는 원형 패턴이 있는 허브와 플랜지", - "sample.flange.name": "볼트 플랜지", - "sample.hinge.about": "두 구성 요소와 회전 관절, 60°까지 구동", - "sample.hinge.name": "힌지 어셈블리", - "sample.plate.about": "필렛, 구멍, 보어 가공된 보스가 있는 매개변수 기반 플레이트", - "sample.plate.name": "샘플 플레이트", - "sample.vents.about": "직사각형 패턴의 슬롯: 행, 열, 피치가 매개변수", - "sample.vents.name": "통풍 플레이트", - "settings.msaa_applies_on_restart": "안티앨리어싱은 다음에 SolidCraft를 시작할 때 적용됩니다", - "settings.msaa_reset": "{setting}: {requested}×는 이 그래픽 장치에서 지원되지 않아 {reset}×로 변경했습니다(지원: {supported}).", - "settings.msaa_unsupported": "이 그래픽 장치에서 지원되지 않음", - "settings.reset_intro": "다음 설정은 이 컴퓨터에서 작동하지 않아 SolidCraft를 시작할 수 없게 하므로 변경되었습니다:", - "settings.reset_title": "설정이 변경되었습니다", - "sketch.degrees_of_freedom": "자유도 {count}개", - "sketch.draw_curves": "{linetype}(으)로 그리기", - "sketch.make_selection": "선택 항목을 {linetype}(으)로 변경", - "ui.1_degree_of_freedom": "자유도 1개", - "ui.3d_sketch": "3D 스케치", - "ui.about": "정보", - "ui.activate": "활성화", - "ui.active_component": "활성 컴포넌트", - "ui.agent_cursor": "에이전트 커서", - "ui.agent_cursor_speed": "에이전트 커서 속도", - "ui.agent_chat": "에이전트 채팅", - "ui.agent_chat_command": "에이전트 명령", - "ui.agent_chat_desktop_only": "에이전트 채팅은 데스크톱 앱이 필요합니다.", - "ui.agent_chat_side": "에이전트 채팅 위치", - "ui.agent_chat_left": "왼쪽", - "ui.agent_chat_right": "오른쪽", - "ui.agent_chat_turn_limit": "메시지당 변경 수", - "ui.agent_chat_privacy_note": "SolidCraft는 아무것도 어디로도 보내지 않습니다. 실행한 에이전트가 사용자의 계정으로 자신의 서비스와 통신합니다. SolidCraft는 키나 비밀번호를 보거나 저장하지 않습니다.", - "ui.agent_chat_connect": "연결", - "ui.agent_chat_stop": "중지", - "ui.agent_chat_stop_tip": "에이전트와 에이전트가 시작한 모든 것을 중지", - "ui.agent_chat_close": "닫기", - "ui.agent_chat_minimize": "얇은 막대로 최소화", - "ui.agent_chat_dock_left": "왼쪽에 고정", - "ui.agent_chat_dock_right": "오른쪽에 고정", - "ui.agent_chat_send": "보내기", - "ui.agent_chat_cancel": "취소", - "ui.agent_chat_refresh": "새로 고침", - "ui.agent_chat_pick": "에이전트", - "ui.agent_chat_custom_hint": "표준 입출력으로 Agent Client Protocol을 사용하는 모든 프로그램. 셸 없이 실행됩니다.", - "ui.agent_chat_not_installed": "설치되지 않음", - "ui.agent_chat_none_found": "코딩 에이전트를 찾지 못했습니다. 다음 중 하나를 설치한 뒤 새로 고침을 누르세요:", - "ui.agent_chat_detecting": "에이전트 찾는 중…", - "ui.agent_chat_signed_in": "로그인됨", - "ui.agent_chat_key_in_env": "키 설정됨", - "ui.agent_chat_not_signed_in": "로그인 안 됨", - "ui.agent_chat_state_off": "연결 안 됨", - "ui.agent_chat_state_starting": "시작하는 중…", - "ui.agent_chat_state_ready": "준비됨", - "ui.agent_chat_state_busy": "작업 중…", - "ui.agent_chat_state_auth": "로그인 필요", - "ui.agent_chat_state_exited": "에이전트 중지됨", - "ui.agent_chat_changes_of": "변경 {n}/{limit}", - "ui.agent_chat_auth_title": "에이전트에 로그인", - "ui.agent_chat_auth_needed": "에이전트가 로그인을 요청합니다. 로그인은 에이전트에서 직접 하며, SolidCraft는 비밀번호나 키를 보지 않습니다.", - "ui.agent_chat_auth_none": "이 에이전트는 여기서 로그인 방법을 제공하지 않습니다. 에이전트 문서에 안내된 방법으로 로그인하세요.", - "ui.agent_chat_auth_terminal": "터미널에서 이것을 실행한 뒤 다시 연결을 누르세요:", - "ui.agent_chat_auth_agent": "{name}(으)로 로그인", - "ui.agent_chat_auth_env": "환경 변수 {vars}을(를) 설정하고 SolidCraft를 다시 시작하세요.", - "ui.agent_chat_auth_retry": "로그인했습니다: 다시 연결", - "ui.agent_chat_copy": "복사", - "ui.agent_chat_permission": "에이전트가 실행 허락을 요청합니다: {title}", - "ui.agent_chat_answered": "응답: {option}", - "ui.agent_chat_approval": "에이전트가 이 작업을 하도록 허용할까요?", - "ui.agent_chat_allow": "허용", - "ui.agent_chat_deny": "거부", - "ui.agent_chat_allowed": "허용함", - "ui.agent_chat_denied": "거부함", - "ui.agent_chat_changes": "변경 {n}개, 실행 취소 한 번", - "ui.agent_chat_undo_changes": "이 변경 사항 실행 취소", - "ui.agent_chat_undone": "(취소됨)", - "ui.agent_chat_undo_label": "에이전트 채팅: {message}", - "ui.agent_chat_limit": "에이전트가 메시지당 변경 한도 {limit}에 도달했습니다. 계속하게 하려면 메시지를 하나 더 보내세요.", - "ui.agent_chat_refused": "에이전트에게 허용되지 않음: {reason}", - "ui.agent_chat_wait_turn": "에이전트가 아직 이전 메시지를 처리 중입니다. 기다리거나 취소를 누르세요.", - "ui.agent_chat_placeholder": "에이전트에게 디자인 변경을 요청하세요…", - "ui.agent_chat_attach_view": "뷰 첨부", - "ui.agent_chat_attach_view_tip": "현재 뷰의 이미지를 메시지와 함께 보냅니다", - "ui.agent_chat_no_images": "이 에이전트는 이미지를 받지 않습니다", - "ui.agent_chat_view_attached": "뷰 첨부됨", - "ui.agent_chat_no_cli": "앱 옆에서 solidcraft-cli를 찾지 못해 에이전트가 디자인에 접근할 수 없습니다.", - "ui.agent_chat_no_control": "에이전트 채팅 엔드포인트가 시작되지 않아 에이전트가 디자인에 접근할 수 없습니다.", - "ui.agent_chat_exited": "에이전트가 중지되었습니다.", - "ui.agent_chat_failed_start": "에이전트를 시작할 수 없습니다: {error}", - "ui.agent_chat_intro": "이미 사용 중인 코딩 에이전트나 선택한 모델 엔드포인트와 채팅하세요. SolidCraft 도구로 열린 디자인을 다루며, 변경 사항은 바로 보이고 메시지마다 한 번에 실행 취소할 수 있습니다. 묻지 않고 할 수 있는 일은 환경 설정 > AI에서 정합니다.", - "ui.agent_chat_privacy": "사용자의 계정으로 실행하는 에이전트 외에는 아무 데도 전송되지 않습니다.", - "ui.agent_chat_none_found_short": "에이전트를 찾지 못함", - "ui.ai_add": "추가", - "ui.ai_add_agent": "에이전트 추가…", - "ui.ai_add_agent_title": "에이전트 추가", - "ui.ai_add_api": "OpenAI 호환 API", - "ui.ai_add_custom": "사용자 지정 명령", - "ui.ai_added": "추가됨", - "ui.ai_add_installed": "설치된 에이전트", - "ui.ai_add_installed_note": "설치된 에이전트에 대한 별도 항목(예: 다른 인수로 실행). 설치된 에이전트는 자동으로 표시됩니다.", - "ui.ai_agent_mode_tip": "에이전트 자체 모드: 에이전트 자체 도구(셸, 파일 편집)는 이 모드를 따릅니다. SolidCraft 도구는 환경 설정 > AI의 권한을 따릅니다.", - "ui.ai_agents": "에이전트", - "ui.ai_always_allow": "항상 허용", - "ui.ai_always_allowed": "항상 허용됨", - "ui.ai_always_allowed_none": "아직 항상 허용된 것이 없습니다. 채팅에서 \"항상 허용\"으로 답한 항목이 여기에 표시됩니다.", - "ui.ai_always_allow_tip": "이 에이전트에게 앞으로 {tool}을(를) 묻지 않고 허용", - "ui.ai_auto_allowed": "자동 허용: {title} ({why})", - "ui.ai_auto_mode": "권한 설정", - "ui.ai_auto_ours": "SolidCraft가 자체 도구를 직접 확인합니다", - "ui.ai_auto_remembered": "\"항상 허용\"을 선택함", - "ui.ai_bad_url": "http:// 또는 https://로 시작하는 URL을 입력하세요", - "ui.ai_base_url": "기본 URL", - "ui.ai_button": "AI", - "ui.ai_copy_suffix": "복사본", - "ui.ai_custom_url": "사용자 지정 URL", - "ui.ai_default": "기본값", - "ui.ai_http_busy": "엔드포인트가 바쁘거나 한도에 도달했습니다. 나중에 다시 시도하세요", - "ui.ai_http_key": "엔드포인트가 키를 거부했습니다. 환경 설정 > AI에서 확인하세요", - "ui.ai_http_not_found": "엔드포인트나 모델을 찾을 수 없습니다. 기본 URL과 모델 이름을 확인하세요", - "ui.ai_key": "API 키", - "ui.ai_keychain_error": "시스템 키체인이 거부했습니다: {error}", - "ui.ai_key_hint": "선택 사항, 시스템 키체인에 저장", - "ui.ai_key_needs_https": "키는 HTTPS를 통해서만, 또는 이 컴퓨터로만 전송됩니다.", - "ui.ai_key_note": "SolidCraft 설정이 아닌 시스템 키체인에 저장됩니다. 로컬 서버라면 비워 두세요.", - "ui.ai_mode_all": "모두 허용", - "ui.ai_mode_all_note": "묻지 않고 실행합니다. 충돌 보고서는 계속 제외되고 폴더 제한도 그대로 적용됩니다.", - "ui.ai_mode_all_warning": "에이전트가 묻지 않고 디자인을 저장, 덮어쓰기, 내보내기, 교체할 수 있습니다. 신뢰하는 에이전트와 저장된 디자인에서만 사용하세요.", - "ui.ai_mode_ask": "매번 묻기", - "ui.ai_mode_ask_note": "디자인의 모든 변경과 파일 작업이 사용자의 허용을 기다립니다.", - "ui.ai_mode_edits": "모델 편집 자동 허용", - "ui.ai_mode_edits_note": "모델링 명령은 묻지 않고 실행되며, 저장·열기·내보내기 등 파일 작업이나 파괴적인 작업은 계속 묻습니다.", - "ui.ai_mode_global": "위 설정 따름", - "ui.ai_model": "모델", - "ui.ai_modes_scope": "이 설정은 SolidCraft 도구에 적용됩니다. 에이전트 자체 도구(셸, 파일 편집)는 에이전트에 모드가 있을 때 채팅 패널 머리글에서 고르는 에이전트 자체 모드를 따릅니다.", - "ui.ai_name": "이름", - "ui.ai_need_command": "에이전트를 시작하는 명령을 입력하세요", - "ui.ai_need_model": "모델 이름을 입력하세요", - "ui.ai_no_answer": "에이전트가 제시간에 응답하지 않았습니다", - "ui.ai_no_http": "이 빌드는 API 엔드포인트에 연결할 수 없습니다", - "ui.ai_no_keychain": "시스템 키체인을 사용할 수 없어 키를 저장할 수 없습니다. 키가 필요 없는 로컬 서버는 사용할 수 있습니다.", - "ui.ai_panel": "패널", - "ui.ai_permissions": "권한", - "ui.ai_preset": "프리셋", - "ui.ai_remove": "제거", - "ui.ai_request_limit": "메시지 하나에 24번 요청 후 멈췄습니다. 계속하려면 메시지를 하나 더 보내세요", - "ui.ai_reset": "재설정", - "ui.ai_settings": "AI 설정…", - "ui.ai_show_features": "AI 기능 표시", - "ui.ai_show_features_note": "에이전트 채팅: 이미 사용 중인 코딩 에이전트나 선택한 모델 엔드포인트가 열린 디자인을 다루는 패널입니다. 끄면 AI 버튼, 단축키, 메뉴 항목, 패널이 없고 아무것도 찾거나 시작하지 않습니다.", - "ui.ai_switch_tip": "이 대화의 에이전트 변경", - "ui.ai_test": "테스트", - "ui.ai_test_acp_ok": "응답: {agent}", - "ui.ai_test_acp_tip": "에이전트를 잠시 시작해 세션을 요청한 뒤 종료합니다", - "ui.ai_test_api_tip": "엔드포인트에 모델 목록을 요청합니다", - "ui.ai_testing": "테스트 중…", - "ui.ai_test_no_model": "연결됨: 모델 {count}개, {model} 없음", - "ui.ai_test_ok": "연결됨: 모델 {count}개", - "ui.ai_toolbar_button": "도구 모음에 버튼 표시", - "ui.ai_toolbar_button_note": "도구 모음 오른쪽 끝의 AI 버튼. Ctrl+Shift+A와 보기 메뉴로도 패널을 열 수 있습니다.", - "ui.ai_tool_done": "완료", - "ui.ai_tool_failed": "실패", - "ui.ai_tool_running": "실행 중", - "ui.ai_tool_unfold": "클릭하면 결과를 표시", - "ui.ai_tool_waiting": "대기 중", - "ui.ai_undo_tip": "이 메시지에서 에이전트가 바꾼 모든 것을 한 번에 실행 취소", - "AI": "AI", - "ui.all": "모두", - "ui.analysis": "분석", - "ui.angle": "각도", - "ui.angle_decimals": "각도 소수점 자릿수", - "ui.animate_view_changes": "뷰 변경 애니메이션", - "ui.animation": "애니메이션", - "ui.animation_speed": "애니메이션 속도", - "ui.anti_aliasing": "안티앨리어싱", - "ui.supersampling": "슈퍼샘플링 (SSAA)", - "ui.supersampling_off": "끔 (1×)", - "ui.supersampling_adaptive": "뷰가 멈춰 있을 때만", - "settings.supersampling_note": "뷰를 더 높은 해상도로 그린 뒤 축소합니다. 4K 미만 화면에서 모서리, 선, 그리드가 더 매끄러워집니다. GPU 시간이 듭니다: 1.5×에서 약 2.25배, 2×에서 4배의 픽셀.", - "ui.display_quality": "표시 품질", - "ui.display_quality_coarse": "거침", - "ui.display_quality_normal": "보통", - "ui.display_quality_fine": "세밀", - "ui.display_quality_ultra": "최고", - "settings.display_quality_note": "세밀할수록 곡면과 모서리가 더 매끄럽게 표시되지만 메시 생성 시간이 늘어납니다. 뷰포트만 바뀌며 설계나 내보내기는 바뀌지 않습니다.", - "ui.apply": "적용", - "ui.arc": "호", - "ui.assemble": "조립", - "ui.autosave_every": "자동 저장 간격", - "ui.axes": "축", - "ui.axis": "축", - "ui.base_point": "기준점", - "ui.bodies": "바디", - "ui.box": "박스", - "ui.break": "끊기", - "ui.cancel": "취소", - "ui.canvases": "캔버스", - "ui.center": "중심", - "ui.centerline": "중심선", - "ui.chain": "체인", - "ui.chamfer": "모따기", - "ui.chamfer_type": "모따기 유형", - "ui.change_workspace": "작업 공간 변경", - "ui.chord_length": "현 길이", - "ui.curvature_g2": "곡률 연속 (G2)", - "ui.equivalent_radius": "등가 반지름", - "ui.circle": "원", - "ui.circular_pattern": "원형 패턴", - "ui.clear_recent": "최근 항목 지우기", - "ui.clear_the_selection": "선택 해제", - "ui.close": "닫기", - "ui.material_review.title": "물리적 재료 데이터 검토", - "ui.material_review.scope": "후보만 검토합니다. 지정하거나 저장하지 않습니다. 수치 검증은 공학적 인증이 아닙니다.", - "ui.material_review.input": "스키마 1 재료 카드 붙여넣기 (JSON)", - "ui.material_review.review": "카드 검토", - "ui.material_review.limit": "카드가 256 KiB 입력 한도를 초과합니다.", - "ui.material_review.unknown": "알 수 없음", - "ui.material_review.properties": "물성", - "ui.material_review.conditions": "명시된 조건", - "ui.material_review.source": "출처", - "ui.material_review.axes": "재료 로컬 축입니다. 바디 방향을 지정하지 않습니다.", - "ui.material_review.derived": "유도된 등방성 탄성 계수", - "ui.material_review.claims": "출처와 라이선스는 검증되지 않은 주장입니다. 누락된 값은 알 수 없는 상태로 유지됩니다.", - "ui.material_review.density": "밀도", - "ui.material_review.elasticity": "탄성", - "ui.material_review.tensile_strength": "인장 강도", - "ui.material_review.compressive_strength": "압축 강도", - "ui.material_review.yield_strength": "항복 강도", - "ui.material_review.shear_strength": "전단 강도", - "ui.material_review.thermal_conductivity": "열전도율", - "ui.material_review.thermal_expansion": "열팽창", - "ui.material_review.specific_heat": "비열", - "ui.material_review.moisture_unit": "kg 물 / kg 건조 재료", - "ui.coil": "코일", - "ui.coincident": "일치", - "ui.collapse": "접기", - "ui.collinear": "동일 선상", - "ui.colour_vision": "색각", - "ui.colour_vision_deutan": "녹색각이상 (Deutan)", - "ui.colour_vision_deutan_tip": "녹색 감각이 약하거나 없는 경우", - "ui.colour_vision_failed": "실패", - "ui.colour_vision_fixed": "고정", - "ui.colour_vision_mode": "모드", - "ui.colour_vision_note": "의미를 나타내는 색을 바꿉니다: 스케치 상태, 축, 벤딩, 분석, 아이콘. Windows 색 필터를 사용한다면 '끄기'로 두세요.", - "ui.colour_vision_off": "끄기", - "ui.colour_vision_off_tip": "테마 고유의 색상", - "ui.colour_vision_projected": "투영", - "ui.colour_vision_protan": "적색각이상 (Protan)", - "ui.colour_vision_protan_tip": "빨간색 감각이 약하거나 없는 경우", - "ui.colour_vision_sample": "예시", - "ui.colour_vision_tritan": "청색각이상 (Tritan)", - "ui.colour_vision_tritan_tip": "파란색 감각이 약하거나 없는 경우", - "ui.combine": "결합", - "ui.coming_later": "추후 지원 예정", - "ui.concentric": "동심", - "ui.configurations": "구성", - "ui.conic_curve": "원뿔 곡선", - "ui.constant": "상수", - "ui.constraints_conflict": "구속 조건 충돌", - "ui.construct": "구성", - "ui.construction": "구성선", - "ui.copy": "복사", - "ui.corners": "코너", - "ui.corner": "코너", - "ui.counterbore": "카운터보어", - "ui.countersink": "카운터싱크", - "ui.create": "만들기", - "ui.create_copy": "복사본 만들기", - "ui.create_sketch": "스케치 만들기", - "ui.current": "현재", - "ui.curvature": "곡률", - "ui.curves": "곡선", - "ui.cut": "잘라내기", - "ui.cylinder": "원통", - "ui.dark": "어둡게", - "ui.default_modelling_orientation": "기본 모델링 방향", - "ui.degrees_of_freedom": "자유도", - "ui.delete": "삭제", - "ui.depth": "깊이", - "ui.design": "디자인", - "ui.diameter": "지름", - "ui.dimension": "치수", - "ui.direction": "방향", - "ui.distance": "거리", - "ui.distance_1": "거리 1", - "ui.distance_2": "거리 2", - "ui.document_settings": "문서 설정", - "ui.don_t_save": "저장 안 함", - "ui.draft": "구배", - "ui.drawing": "도면", - "ui.drill_point": "드릴 선단", - "ui.edit": "편집", - "ui.edit_section_analysis": "단면 분석 편집", - "ui.ellipse": "타원", - "ui.end_radius": "끝 반지름", - "ui.entities": "요소", - "ui.equal": "동일", - "ui.expand": "펼치기", - "ui.export_ellipsis": "내보내기...", - "ui.extend": "연장", - "ui.extent_type": "범위 유형", - "ui.extrude": "돌출", - "ui.factor": "배율", - "ui.feature_history": "피처 기록", - "ui.feature_options": "피처 옵션", - "ui.features": "피처", - "ui.file": "파일", - "ui.fillet": "필렛", - "ui.finish_sketch": "스케치 종료", - "ui.fix_unfix": "고정/고정 해제", - "ui.flat": "플랫", - "ui.flip": "뒤집기", - "ui.front": "정면", - "ui.fully_constrained": "완전 구속", - "ui.general": "일반", - "ui.graphics": "그래픽", - "ui.heading_assemble": "조립", - "ui.heading_box": "박스", - "ui.heading_chamfer": "모따기", - "ui.heading_circular_pattern": "원형 패턴", - "ui.heading_coil": "코일", - "ui.heading_combine": "결합", - "ui.heading_construct": "구성", - "ui.heading_create": "만들기", - "ui.heading_create_sketch": "스케치 만들기", - "ui.heading_cylinder": "원통", - "ui.heading_design": "디자인", - "ui.heading_draft": "구배", - "ui.heading_edit": "편집", - "ui.heading_extrude": "돌출", - "ui.heading_fillet": "필렛", - "ui.heading_finish_sketch": "스케치 종료", - "ui.heading_front": "정면", - "ui.heading_hole": "구멍", - "ui.heading_home": "홈", - "ui.heading_insert": "삽입", - "ui.heading_inspect": "검사", - "ui.heading_loft": "로프트", - "ui.heading_measure": "측정", - "ui.heading_mesh": "메시", - "ui.heading_mirror": "대칭 복사", - "ui.heading_modify": "수정", - "ui.heading_move": "이동", - "ui.heading_offset": "오프셋", - "ui.heading_move_copy": "이동/복사", - "ui.heading_offset_plane": "오프셋 평면", - "ui.heading_ok": "확인", - "ui.heading_parameters": "매개변수", - "ui.heading_pattern_on_path": "경로 패턴", - "ui.heading_pipe": "파이프", - "ui.heading_plane_at_angle": "각도 평면", - "ui.heading_plastic": "플라스틱", - "ui.heading_rectangular_pattern": "직사각형 패턴", - "ui.heading_revolve": "회전", - "ui.heading_right": "우측면", - "ui.heading_scale": "축척", - "ui.heading_section_analysis": "단면 분석", - "ui.heading_select": "선택", - "ui.heading_sheet_metal": "판금", - "ui.heading_shell": "쉘", - "ui.heading_sketch": "스케치", - "ui.heading_sketch_palette": "스케치 팔레트", - "ui.heading_sketch_scale": "스케치 배율", - "ui.heading_solid": "솔리드", - "ui.heading_sphere": "구", - "ui.heading_split_body": "바디 분할", - "ui.heading_surface": "서피스", - "ui.heading_sweep": "스윕", - "ui.heading_thread": "나사산", - "ui.heading_top": "상면", - "ui.heading_torus": "토러스", - "ui.help": "도움말", - "ui.hide": "숨기기", - "ui.hole": "구멍", - "ui.hole_tap_type": "탭 유형", - "ui.hole_type": "구멍 유형", - "ui.home": "홈", - "ui.horizontal_vertical": "수평/수직", - "ui.insert": "삽입", - "ui.inspect": "검사", - "ui.intersect": "교차", - "ui.join": "접합", - "ui.joints": "조인트", - "ui.keyboard_shortcuts": "키보드 단축키", - "ui.language": "언어", - "ui.length_decimals": "길이 소수점 자릿수", - "ui.light": "밝게", - "ui.line": "선", - "ui.linetype": "선 종류", - "ui.loft": "로프트", - "ui.look_at": "바라보기", - "ui.manufacture": "제조", - "ui.measure": "측정", - "ui.midpoint": "중간점", - "ui.mirror": "대칭 복사", - "ui.mirror_line": "대칭선", - "ui.modify": "수정", - "ui.move": "이동", - "ui.multiple": "다중", - "ui.named_views": "명명된 뷰", - "ui.navigation": "탐색", - "ui.needs_design": "{command}: 먼저 디자인을 열어 주세요", - "ui.new_body": "새 바디", - "ui.new_design": "새 디자인", - "ui.normal": "일반", - "ui.object_type": "객체 유형", - "ui.objects": "객체", - "ui.offer_to_stand_up_y_up_files": "Y-up 파일을 Z-up으로 세우도록 제안", - "ui.offset": "오프셋", - "ui.offset_plane": "오프셋 평면", - "ui.one_side": "한 방향", - "ui.open": "열기", - "ui.open_ellipsis": "열기...", - "ui.open_preferences": "환경 설정 열기", - "ui.open_recent": "최근 항목 열기", - "ui.operation": "작업", - "ui.options": "옵션", - "ui.orbit_around": "궤도 회전 기준", - "ui.origin": "원점", - "ui.palette_points": "점", - "ui.palette_profile": "프로파일", - "ui.pan_zoom_orbit": "이동, 확대/축소, 궤도 회전", - "ui.parallel": "평행", - "ui.parameters": "매개변수", - "ui.paste": "붙여넣기", - "ui.path": "경로", - "ui.pattern_on_path": "경로 패턴", - "ui.perpendicular": "수직", - "ui.pipe": "파이프", - "ui.placement": "배치", - "ui.plane": "평면", - "ui.plane_at_angle": "각도 평면", - "ui.point": "점", - "ui.point_under_the_cursor": "커서 아래의 점", - "ui.points": "점", - "ui.polygon": "다각형", - "ui.preferences": "환경 설정", - "ui.profile": "프로파일", - "ui.profile_plane": "프로파일 평면", - "ui.profiles": "프로파일", - "ui.project": "투영", - "ui.quantity_2": "수량 2", - "ui.quantity": "수량", - "ui.quit": "종료", - "ui.radius": "반지름", - "ui.pull_direction": "빼기 방향", - "ui.tool_direction": "공구 방향", - "ui.reachable": "도달 가능", - "ui.blocked": "막힘", - "ui.radius_type": "반지름 유형", - "ui.rectangle": "직사각형", - "ui.rectangular_pattern": "직사각형 패턴", - "ui.redo": "다시 실행", - "ui.render": "렌더", - "ui.reset_the_settings_on_this_page": "이 페이지의 설정 초기화", - "ui.restore_defaults": "기본값 복원", - "ui.reverse_zoom_direction": "확대/축소 방향 반전", - "ui.revolve": "회전", - "ui.right": "우측면", - "ui.save": "저장", - "ui.heading_save_mesh": "메쉬로 저장", - "ui.format": "형식", - "ui.mesh_format_stl": "STL", - "ui.mesh_format_3mf": "3MF", - "ui.mesh_format_3mf_tagged": "면 태그가 있는 3MF", - "ui.send_to_slicer": "슬라이서로 보내기", - "ui.slicer": "슬라이서", - "ui.custom_program": "사용자 지정…", - "ui.no_slicer_found": "슬라이서를 찾을 수 없음", - "ui.send": "보내기", - "ui.custom_program_tip": "목록에 추가할 슬라이서 프로그램 선택", - "ui.slicer_delete_tip": "{program}\nDelete 키로 목록에서 제거", - "ui.save_mesh_pick_bodies": "저장할 바디를 선택하세요", - "ui.save_mesh_no_slicer": "슬라이서를 찾을 수 없습니다. '사용자 지정…'에서 슬라이서 프로그램을 선택하거나 '슬라이서로 보내기'를 끄세요", - "ui.not_a_program": "{path}은(는) 실행할 수 있는 프로그램이 아닙니다", - "ui.sent_to_slicer": "{slicer}(으)로 보냈습니다", - "ui.saved_to": "저장됨: {path}", - "ui.save_mesh_temp_failed": "{folder}을(를) 만들 수 없습니다: {error}", - "ui.save_as": "다른 이름으로 저장", - "ui.save_as_ellipsis": "다른 이름으로 저장...", - "ui.scale": "축척", - "ui.orientation": "배향", - "ui.twist": "비틀림", - "ui.end_scale": "끝 배율", - "ui.sweep_turn_with_path": "경로를 따라 회전", - "ui.sweep_keep_as_drawn": "그린 대로 유지", - "ui.sweep_follow_direction": "방향 따르기", - "ui.section_analysis": "단면 분석", - "ui.select": "선택", - "ui.selection": "선택", - "ui.shell": "쉘", - "ui.show": "표시", - "ui.show_constraints": "구속 조건", - "ui.show_dimensions": "치수", - "ui.show_points": "점 표시", - "ui.show_profile": "프로파일 표시", - "ui.show_projected_geometries": "투영된 형상", - "ui.simple": "단순", - "ui.simulation": "시뮬레이션", - "ui.single": "단일", - "ui.sketch": "스케치", - "ui.sketch_dimension": "스케치 치수", - "ui.sketch_grid": "스케치 격자", - "ui.sketch_scale": "스케치 축척", - "ui.sketch_status": "스케치 상태", - "ui.sketches": "스케치", - "ui.slice": "슬라이스", - "ui.slot": "슬롯", - "ui.smooth": "부드럽게", - "ui.snap": "스냅", - "ui.spacing_2": "간격 2", - "ui.spacing": "간격", - "ui.sphere": "구", - "ui.spline": "스플라인", - "ui.split_body": "바디 분할", - "ui.start": "시작", - "ui.start_radius": "시작 반지름", - "ui.sweep": "스윕", - "ui.symmetric": "대칭", - "ui.symmetry": "대칭", - "ui.system": "시스템", - "ui.tangent": "접선", - "ui.taper_angle": "테이퍼 각도", - "ui.tapped": "탭", - "ui.text": "텍스트", - "ui.theme": "테마", - "ui.thickness": "두께", - "ui.thread": "나사산", - "ui.timeline_bottom": "하단 타임라인", - "ui.timeline_left_note": "왼쪽 레이아웃에서는 롤백 바가 부품 및 장면 브라우저 위에 표시됩니다.", - "ui.timeline_left_sidebar": "왼쪽 사이드바", - "ui.tip_angle": "선단 각도", - "ui.to_object": "객체까지", - "ui.top": "상면", - "ui.torus": "토러스", - "ui.trim": "트림", - "ui.two_sides": "양방향", - "ui.ui_scale": "UI 배율", - "ui.undo": "실행 취소", - "ui.units": "단위", - "ui.units_of_new_designs": "새 디자인의 단위", - "ui.untitled": "제목 없음", - "ui.variable": "가변", - "ui.view_centre": "뷰 중심", - "ui.visual_style": "시각 스타일", - "ui.workspace": "작업 공간", - "ui.y_distance": "Y 거리", - "ui.x_distance": "X 거리", - "ui.zoom_to_the_cursor": "커서 위치로 확대/축소", - "ui.animateJoint": "조인트 애니메이션", - "ui.calibrate": "캘리브레이션", - "ui.customizeToolbar": "도구 모음 사용자 지정…", - "ui.editJointLimits": "조인트 제한 편집", - "ui.exportDxf": "DXF 내보내기…", - "ui.findInTimeline": "타임라인에서 찾기", - "ui.findInWindow": "창에서 찾기", - "ui.fit": "맞춤", - "ui.groupSelected": "선택 항목 그룹화", - "ui.hideAxes": "축 숨기기", - "ui.hideDimension": "치수 숨기기", - "ui.hideOrigin": "원점 숨기기", - "ui.hidePlanes": "평면 숨기기", - "ui.hideProfile": "윤곽 숨기기", - "ui.homeView": "홈 보기", - "ui.isolate": "분리 표시", - "ui.lock": "잠금", - "ui.newSketchGroup": "새 스케치 그룹", - "ui.normalConstruction": "일반 / 생성", - "ui.orbit": "회전", - "ui.heading_position": "배치", - "ui.pan": "이동", - "ui.pinToShortcuts": "바로 가기에 고정", - "ui.pinToToolbar": "도구 모음에 고정", - "ui.properties": "속성", - "ui.design_properties.project": "프로젝트", - "ui.design_properties.part_number": "부품 번호", - "ui.design_properties.revision": "리비전", - "ui.design_properties.author": "작성자", - "ui.design_properties.organization": "조직", - "ui.design_properties.description": "설명", - "ui.design_properties.license": "라이선스", - "ui.design_properties.not_text": "텍스트가 아닌 값으로 저장되어 있습니다. 여기에 입력하면 대체됩니다.", - "ui.design_properties.exports": "STEP, IGES, 3MF 내보내기는 형식에 해당 항목이 있으면 이 속성을 기록합니다.", - "ui.design_properties.others": "다른 도구의 데이터", - "ui.design_properties.others_note": "설계에 그대로 유지되며 내보내지지 않습니다.", - "ui.removeSection": "단면 제거", - "ui.removeFromToolbar": "도구 모음에서 제거", - "ui.repeat": "반복", - "ui.report_a_bug": "버그 신고", - "ui.restore": "복원", - "ui.heading_setup": "설정", - "ui.selectOther": "기타 선택…", - "ui.selectTangentChain": "접선 체인 선택", - "ui.showAll": "모두 표시", - "ui.showAllBodies": "모두 표시", - "ui.showAxes": "축 표시", - "ui.showDimension": "치수 표시", - "ui.showOrigin": "원점 표시", - "ui.showPlanes": "평면 표시", - "ui.suppress": "비활성화", - "ui.command_palette_hint": "명령 입력(예: {example}) — 또는 S 키를 눌러 검색", - "ui.unground": "고정 해제", - "ui.unisolate": "분리 표시 해제", - "ui.unlock": "잠금 해제", - "ui.unsuppress": "비활성화 해제", - "ui.updateToCurrentView": "현재 보기로 업데이트", - "ui.zoom": "확대/축소", - "ui.command_done": "{command} 완료", - "drive.stopped_by_loop": "{value}에서 멈춤: {joint}을(를) 지나는 루프를 더 이상 닫을 수 없습니다", - "drive.stopped_by_contact": "{value}에서 멈춤: {a}이(가) {b}을(를) 통과하게 됩니다", - "drive.unconnected": "아무것도 움직이지 않습니다: {part}이(가) 고정된 것에 연결되어 있지 않습니다", "cmd.appearance_assign": "외관", "cmd.appearance_library": "외관 라이브러리", "cmd.appearance_list": "외관 목록", @@ -685,7 +105,6 @@ "cmd.component_capture_position": "위치 캡처", "cmd.component_create": "새 구성 요소", "cmd.component_delete": "구성 요소 삭제", - "cmd.component_unlock": "내용 잠금 해제", "cmd.component_from_bodies": "바디로 구성 요소 만들기", "cmd.component_insert_design": "설계 삽입", "cmd.component_links": "링크 목록", @@ -696,6 +115,7 @@ "cmd.component_properties": "구성 요소 물리 속성", "cmd.component_rename": "구성 요소 이름 변경", "cmd.component_revert_position": "위치 복원", + "cmd.component_unlock": "내용 잠금 해제", "cmd.component_update_links": "링크 업데이트", "cmd.config_activate": "구성 활성화", "cmd.config_column": "구성 열", @@ -737,10 +157,10 @@ "cmd.doc_recovery_discard": "복구된 설계 폐기", "cmd.doc_recovery_list": "복구 가능한 설계", "cmd.document_inspect": "설계 검사", - "cmd.document_units": "설계 단위 변경", "cmd.document_metadata": "설계 속성", - "cmd.document_metadata_set": "설계 속성 변경", "cmd.document_metadata_remove": "설계 속성 제거", + "cmd.document_metadata_set": "설계 속성 변경", + "cmd.document_units": "설계 단위 변경", "cmd.edit_checkpoint": "체크포인트", "cmd.edit_restore_checkpoint": "체크포인트 복원", "cmd.engine_commands": "명령 목록", @@ -758,6 +178,7 @@ "cmd.inspect_accessibility": "접근성 분석", "cmd.inspect_center_of_mass": "무게중심", "cmd.inspect_compare": "바디 비교", + "cmd.inspect_continuity": "연속성 분석", "cmd.inspect_curvature_comb": "곡률빗 분석", "cmd.inspect_curvature_map": "곡률맵 분석", "cmd.inspect_draft": "블록각 분석", @@ -771,15 +192,18 @@ "cmd.joint_delete": "관절 삭제", "cmd.joint_drive": "관절 구동", "cmd.joint_edit": "관절 편집", + "cmd.joint_gear": "기어", "cmd.joint_limits": "관절 제한", "cmd.joint_list": "관절 목록", "cmd.joint_motion_link": "모션 링크", - "cmd.joint_gear": "기어", - "cmd.joint_rack_pinion": "랙 앤 피니언", - "cmd.joint_screw": "나사", "cmd.joint_origin": "관절 원점", + "cmd.joint_rack_pinion": "랙 앤 피니언", "cmd.joint_rigid_group": "강체 그룹", + "cmd.joint_screw": "나사", "cmd.joint_solve": "관절 해석", + "cmd.library_apply": "로컬 라이브러리 항목 적용", + "cmd.library_export": "설계 라이브러리 내보내기", + "cmd.library_inspect": "로컬 라이브러리 확인", "cmd.material_assign": "물리 재질", "cmd.material_create": "새 물리 재질", "cmd.material_delete": "물리 재질 삭제", @@ -807,10 +231,10 @@ "cmd.parameters_delete": "매개 변수 삭제", "cmd.parameters_export": "매개 변수 내보내기", "cmd.parameters_favorite": "즐겨찾는 매개 변수", - "cmd.parameters_move": "매개 변수 이동", "cmd.parameters_graph": "매개 변수 그래프", "cmd.parameters_import": "매개 변수 가져오기", "cmd.parameters_list": "매개 변수 목록", + "cmd.parameters_move": "매개 변수 이동", "cmd.parameters_rename": "매개 변수 이름 변경", "cmd.parameters_users": "매개 변수 사용처", "cmd.parts_fastener": "체결 부품 삽입", @@ -824,6 +248,16 @@ "cmd.plastic_rest": "레스트", "cmd.plastic_rules": "플라스틱 규칙 목록", "cmd.plastic_snap_fit": "스냅핏", + "cmd.render_backends": "렌더링 백엔드", + "cmd.render_cancel": "렌더링 취소", + "cmd.render_export": "PNG 내보내기", + "cmd.render_preflight": "렌더 요청 확인", + "cmd.render_scene": "렌더링 장면 검사", + "cmd.render_settings_apply": "렌더링 카메라 적용", + "cmd.render_settings_get": "렌더링 설정", + "cmd.render_settings_set": "렌더링 설정 저장", + "cmd.render_start": "이미지 렌더링", + "cmd.render_status": "렌더링 진행 상황", "cmd.select_clear": "선택 지우기", "cmd.sheet_convert": "판금으로 변환", "cmd.sheet_export_bend_table": "벤딩 표 내보내기", @@ -918,22 +352,21 @@ "cmd.solid_rib": "리브", "cmd.solid_split_face": "면 분할", "cmd.solid_web": "웹", - "cmd.surface_patch": "패치", - "cmd.surface_stitch": "재봉", - "cmd.surface_thicken": "두께 주기", - "cmd.surface_extrude": "서피스 돌출", - "cmd.surface_revolve": "서피스 회전", - "cmd.surface_sweep": "서피스 스윕", - "cmd.surface_loft": "서피스 로프트", - "cmd.surface_ruled": "룰드 서피스", - "cmd.surface_boundary": "바운더리 서피스", - "cmd.surface_offset": "오프셋 서피스", "cmd.surface_blend": "블렌드 서피스", + "cmd.surface_boundary": "바운더리 서피스", + "cmd.surface_extrude": "서피스 돌출", "cmd.surface_fillet": "서피스 필렛", - "cmd.surface_untrim": "트림 해제", - "cmd.surface_unstitch": "스티치 해제", + "cmd.surface_loft": "서피스 로프트", + "cmd.surface_offset": "오프셋 서피스", + "cmd.surface_patch": "패치", "cmd.surface_reverse_normal": "법선 반전", - "cmd.inspect_continuity": "연속성 분석", + "cmd.surface_revolve": "서피스 회전", + "cmd.surface_ruled": "룰드 서피스", + "cmd.surface_stitch": "재봉", + "cmd.surface_sweep": "서피스 스윕", + "cmd.surface_thicken": "두께 주기", + "cmd.surface_unstitch": "스티치 해제", + "cmd.surface_untrim": "트림 해제", "cmd.timeline_add": "기록된 특성 추가", "cmd.timeline_compute_all": "모두 다시 계산", "cmd.timeline_copy": "특성 복사", @@ -950,215 +383,781 @@ "cmd.view_apply": "이름 있는 보기 복원", "cmd.view_delete": "이름 있는 보기 삭제", "cmd.view_list": "이름 있는 보기 목록", + "cmd.view_navigate": "보기 탐색", "cmd.view_rename": "이름 있는 보기 이름 변경", "cmd.view_save": "새 이름 있는 보기", - "ui.export_ellipsis_keymap": "내보내기…", - "ui.heading_configure": "구성", - "ui.heading_constraints": "구속 조건", - "ui.heading_utilities": "유틸리티", - "BROWSER": "브라우저", - "Bends": "벤딩", - "Drive Joint": "조인트 구동", - "Edit Profile Sketch": "윤곽 스케치 편집", - "Find in Browser": "브라우저에서 찾기", - "Copy Error Message": "오류 메시지 복사", - "Copy Warning Message": "경고 메시지 복사", - "Report a bug — review a screenshot and open a GitHub draft": "버그 신고 — 스크린샷을 검토하고 GitHub 초안 열기", - "Reset Toolbar": "도구 모음 재설정", - "Select bodies (a face picks its body)": "바디 선택(면을 클릭하면 해당 바디 선택)", - "Selection filter": "선택 필터", - "Revert Position": "위치 복원", - "Construction": "구성선", - "Faces": "면", - "Edges": "모서리", - "Vertices": "꼭짓점", - "Sketch geometry and profiles": "스케치 기하 및 프로파일", - "Sketch curves": "스케치 곡선", - "Sketch points": "스케치 점", - "Sketch dimensions": "스케치 치수", - "Sketch constraints": "스케치 구속 조건", - "Flat": "플랫", - "cmd.render_backends": "렌더링 백엔드", - "cmd.view_navigate": "보기 탐색", - "timeline.group": "새 특성 폴더", - "timeline.ungroup": "특성 폴더 제거", - "timeline.rename_group": "특성 폴더 이름 변경", - "timeline.move_to_group": "특성을 폴더로 이동", - "timeline.move_many": "타임라인 항목 이동", - "timeline.reorder_many": "특성 순서 변경", - "ui.show_construction_geometries": "구성 형상", - "ui.total_angle": "전진 각도", - "sketch_text.builtin_font": "{family}(내장)", - "sketch_text.font_search": "글꼴 검색", - "sketch_text.loading_fonts": "설치된 글꼴을 찾는 중…", - "sketch_text.use_font_file": "글꼴 파일 {path} 사용", - "sketch_text.bold": "굵게", - "sketch_text.italic": "기울임꼴", - "sketch_text.align_left": "왼쪽", - "sketch_text.align_center": "가운데", - "sketch_text.align_right": "오른쪽", - "sketch_text.path_hint": "텍스트가 따라갈 스케치 곡선: 여기를 클릭한 다음 곡선을 클릭", - "sketch_text.path_clear": "곡선에서 텍스트 떼기", - "sketch_text.on_path": "텍스트가 경로를 따릅니다: 위치는 곡선이 정합니다", - "cmd.library_inspect": "로컬 라이브러리 확인", - "cmd.library_export": "설계 라이브러리 내보내기", - "cmd.library_apply": "로컬 라이브러리 항목 적용", - "Thin": "얇은 벽", - "Thin Extrude": "얇은 벽 돌출", - "Wall Location": "벽 위치", - "Wall Thickness": "벽 두께", - "Thickness Outside": "바깥쪽 두께", - "Inside": "안쪽", - "Outside": "바깥쪽", - "Profiles/Curves": "프로파일/곡선", - "Corner Relief": "모서리 릴리프", - "Notch": "노치", - "Round": "원형", - "Rectangular": "직사각형", - "Tear": "찢김", - "update.button": "업데이트", - "update.button_tip": "SolidCraft {version} 사용 가능", - "install.menu": "앱 설치…", + "coupling.gear_1": "기어 1", + "coupling.gear_1_pick": "기어 1 (선택 사항)", + "coupling.gear_2": "기어 2", + "coupling.gear_2_pick": "기어 2 (선택 사항)", + "coupling.internal": "내접 기어", + "coupling.needs_turn_and_slide": "회전하는 관절과 미끄러지는 관절이 필요함", + "coupling.needs_turns": "회전하는 관절 두 개가 필요함", + "coupling.not_round": "원통 면이 아님", + "coupling.nut": "너트", + "coupling.picked": "선택됨", + "coupling.pinion": "피니언", + "coupling.pinion_pick": "피니언 (선택 사항)", + "coupling.pitch": "피치", + "coupling.rack": "랙", + "coupling.radius_1": "반지름 1", + "coupling.radius_2": "반지름 2", + "dialog.computing": "계산 중… {seconds}초", + "dialog.custom_axis": "↖ 사용자 정의 축", + "dialog.edit_title": "{title} 편집", + "dialog.select": "↖ 선택", + "dialog.selected_count": "↖ {count}개 선택됨", + "dialog.selection_guidance": "변경할 입력을 선택하세요. 선택한 객체를 클릭하면 선택이 해제되며, Ctrl/Cmd를 누른 채 클릭해도 전환됩니다. 미리 보기를 확인한 다음 확인을 누르세요.", + "dialog.selection_step": "{step}/{total} 단계: {input} 선택", + "dialog.step": "단계", + "document.save_changes": "{name}의 변경 사항을 저장하시겠습니까?", + "document.unsaved_changes": "{name}에 저장되지 않은 변경 사항이 있습니다. 저장하지 않으면 변경 사항이 사라집니다.", + "drive.stopped_by_contact": "{value}에서 멈춤: {a}이(가) {b}을(를) 통과하게 됩니다", + "drive.stopped_by_loop": "{value}에서 멈춤: {joint}을(를) 지나는 루프를 더 이상 닫을 수 없습니다", + "drive.unconnected": "아무것도 움직이지 않습니다: {part}이(가) 고정된 것에 연결되어 있지 않습니다", + "home.documentation": "문서", + "home.in_this_browser": "이 브라우저에 저장됨", + "home.missing": "찾을 수 없음", + "home.open": "열기…", + "home.opened_days_ago": "{count}일 전에 열림", + "home.opened_hours_ago": "{count}시간 전에 열림", + "home.opened_just_now": "방금 열림", + "home.opened_minutes_ago": "{count}분 전에 열림", + "home.opening": "여는 중…", + "home.recent": "최근 항목", + "home.report_issue": "문제 신고", + "home.samples": "샘플", + "home.whats_new": "새로운 기능", "install.button_tip": "SolidCraft를 앱으로 설치합니다. 별도 창에서 열리며 오프라인에서도 작동합니다", - "install.title": "SolidCraft 설치", - "install.steps_intro": "Safari는 자체 메뉴에서 웹 앱을 설치합니다:", - "install.home_screen_1": "공유를 탭합니다(도구 막대에 없으면 … 메뉴 안에 있습니다).", - "install.home_screen_2": "홈 화면에 추가를 선택합니다.", - "install.home_screen_3": "추가를 탭합니다.", - "install.home_screen_after": "이후 SolidCraft는 홈 화면의 아이콘에서 Safari 도구 막대 없이 열리며 오프라인에서도 작동합니다.", "install.dock_1": "파일 › Dock에 추가를 선택합니다.", "install.dock_2": "추가를 클릭합니다.", "install.dock_after": "이후 SolidCraft는 Dock에서 별도 창으로 열리며 오프라인에서도 작동합니다.", "install.done": "완료", - "update.title": "업데이트 사용 가능", + "install.home_screen_1": "공유를 탭합니다(도구 막대에 없으면 … 메뉴 안에 있습니다).", + "install.home_screen_2": "홈 화면에 추가를 선택합니다.", + "install.home_screen_3": "추가를 탭합니다.", + "install.home_screen_after": "이후 SolidCraft는 홈 화면의 아이콘에서 Safari 도구 막대 없이 열리며 오프라인에서도 작동합니다.", + "install.menu": "앱 설치…", + "install.steps_intro": "Safari는 자체 메뉴에서 웹 앱을 설치합니다:", + "install.title": "SolidCraft 설치", + "joint.from_bodies_hint": "선택한 각 바디가 제자리에 그대로 있으면서 자체의 새 구성 요소로 옮겨집니다.", + "joint.one_body": "두 선택이 모두 {body}에 있습니다. 두 번째는 다른 부품에서 선택하세요.", + "joint.one_component": "이 부품들은 한 구성 요소의 바디입니다: {bodies}. 관절은 한 구성 요소를 다른 구성 요소에 대해 움직이므로 부품마다 자체 구성 요소가 필요합니다.", + "nav.touchpad.help": "Shift를 누른 채 포인터를 움직이면 화면이 이동하고, Alt/Option을 누른 채 움직이면 회전합니다. 마우스 버튼은 필요 없습니다. 세로 스크롤로 확대/축소합니다.", + "nav.touchpad.label": "터치패드", + "nav.touchpad.orbit": "회전 (Alt/Option을 누르고 이동, 마우스 버튼 불필요)", + "nav.touchpad.pan": "화면 이동 (Shift를 누르고 이동, 마우스 버튼 불필요)", + "nav.touchpad.scroll": "터치패드는 세로 스크롤로 확대/축소합니다. 두 손가락 이동 설정은 다른 프리셋을 위해 유지됩니다.", + "nav.touchpad.zoom": "확대/축소 (세로 스크롤 또는 핀치)", + "render.background": "장면 배경", + "render.fit": "제품에 맞추기", + "render.image_cancel": "렌더링 취소", + "render.image_cancelled": "렌더링 취소됨", + "render.image_cancelling": "취소 중", + "render.image_check": "렌더 요청 확인", + "render.image_completed": "이미지 내보내기 준비됨", + "render.image_encoding": "PNG 인코딩 중", + "render.image_export": "PNG 내보내기", + "render.image_failed": "렌더링 실패", + "render.image_height": "높이", + "render.image_help": "CPU 미리 보기 이미지 · PNG · 근사 투명도", + "render.image_overwrite": "기존 파일 바꾸기", + "render.image_preparing": "이미지 준비 중", + "render.image_queued": "렌더링 대기 중", + "render.image_reduce": "더 작은 이미지나 더 단순한 장면을 사용해 보세요.", + "render.image_running": "이미지 렌더링 중", + "render.image_stale": "이 이미지는 후속 변경 전에 캡처한 장면을 사용합니다.", + "render.image_start": "렌더링 시작", + "render.image_supported": "지원되는 렌더 요청입니다. 시작 시 대기열과 메모리 풀을 다시 확인합니다.", + "render.image_title": "이미지 렌더링", + "render.image_too_large": "이미지 한도를 초과했습니다: 한 변 4096픽셀, 전체 4,194,304픽셀.", + "render.image_transparent": "투명 배경", + "render.image_unknown": "렌더 상태를 확인할 수 없습니다", + "render.image_use_largest": "이 비율에서 가장 큰 크기 사용:", + "render.image_width": "너비", + "render.navigation_help": "카메라는 디자인에서와 같이 움직입니다(환경설정 › 탐색). 설정 저장은 현재 카메라를 기록합니다.", + "render.opaque_image_summary": "미리보기 PNG · 불투명 PBR · 블렌딩 투명도", + "render.opaque_preview_help": "불투명 PBR 및 단색 표시, 블렌딩 투명도를 지원합니다. 굴절, HDRI 및 최종 렌더링은 아직 지원하지 않습니다.", + "render.perspective": "원근 카메라", + "render.preview": "통합 미리보기", + "render.preview_help": "래스터 셰이딩과 블렌딩 투명도를 사용합니다. 굴절, HDRI 및 최종 렌더링은 아직 지원하지 않습니다.", + "render.reload_settings": "저장된 설정 다시 불러오기", + "render.restore_camera": "저장된 카메라 복원", + "render.return_design": "설계로 돌아가기", + "render.save_setup": "설정 저장", + "render.setup_name": "설정 이름", + "render.unavailable_preview": "이 설정은 사용할 수 없는 미리보기 프로필을 요청합니다.", + "render.unsaved": "저장하지 않은 미리보기 변경 사항", + "render.use_preview": "통합 미리보기 사용", + "sample.bracket.about": "2 mm 판금 규칙을 적용한 베이스 플랜지, 에지 플랜지, 헴", + "sample.bracket.name": "판금 브래킷", + "sample.enclosure.about": "리프, 나사 보스, 레스트, 스냅핏이 있는 쉘 처리된 박스", + "sample.enclosure.name": "플라스틱 인클로저", + "sample.flange.about": "매개변수로 제어되는 원형 패턴이 있는 허브와 플랜지", + "sample.flange.name": "볼트 플랜지", + "sample.hinge.about": "두 구성 요소와 회전 관절, 60°까지 구동", + "sample.hinge.name": "힌지 어셈블리", + "sample.plate.about": "필렛, 구멍, 보어 가공된 보스가 있는 매개변수 기반 플레이트", + "sample.plate.name": "샘플 플레이트", + "sample.vents.about": "직사각형 패턴의 슬롯: 행, 열, 피치가 매개변수", + "sample.vents.name": "통풍 플레이트", + "settings.display_quality_note": "세밀할수록 곡면과 모서리가 더 매끄럽게 표시되지만 메시 생성 시간이 늘어납니다. 뷰포트만 바뀌며 설계나 내보내기는 바뀌지 않습니다.", + "settings.measure_axis_distances": "X/Y/Z 거리 표시", + "settings.measure_axis_distances_help": "측정 대화상자가 열려 있는 동안 전체 거리와 함께 월드 축 방향 치수와 거리를 표시합니다.", + "settings.msaa_applies_on_restart": "안티앨리어싱은 다음에 SolidCraft를 시작할 때 적용됩니다", + "settings.msaa_reset": "{setting}: {requested}×는 이 그래픽 장치에서 지원되지 않아 {reset}×로 변경했습니다(지원: {supported}).", + "settings.msaa_unsupported": "이 그래픽 장치에서 지원되지 않음", + "settings.reset_intro": "다음 설정은 이 컴퓨터에서 작동하지 않아 SolidCraft를 시작할 수 없게 하므로 변경되었습니다:", + "settings.reset_title": "설정이 변경되었습니다", + "settings.supersampling_note": "뷰를 더 높은 해상도로 그린 뒤 축소합니다. 4K 미만 화면에서 모서리, 선, 그리드가 더 매끄러워집니다. GPU 시간이 듭니다: 1.5×에서 약 2.25배, 2×에서 4배의 픽셀.", + "sketch.degrees_of_freedom": "자유도 {count}개", + "sketch.draw_curves": "{linetype}(으)로 그리기", + "sketch.make_selection": "선택 항목을 {linetype}(으)로 변경", + "sketch_text.align_center": "가운데", + "sketch_text.align_left": "왼쪽", + "sketch_text.align_right": "오른쪽", + "sketch_text.bold": "굵게", + "sketch_text.builtin_font": "{family}(내장)", + "sketch_text.font_search": "글꼴 검색", + "sketch_text.italic": "기울임꼴", + "sketch_text.loading_fonts": "설치된 글꼴을 찾는 중…", + "sketch_text.on_path": "텍스트가 경로를 따릅니다: 위치는 곡선이 정합니다", + "sketch_text.path_clear": "곡선에서 텍스트 떼기", + "sketch_text.path_hint": "텍스트가 따라갈 스케치 곡선: 여기를 클릭한 다음 곡선을 클릭", + "sketch_text.use_font_file": "글꼴 파일 {path} 사용", + "timeline.group": "새 특성 폴더", + "timeline.move_many": "타임라인 항목 이동", + "timeline.move_to_group": "특성을 폴더로 이동", + "timeline.rename_group": "특성 폴더 이름 변경", + "timeline.reorder_many": "특성 순서 변경", + "timeline.ungroup": "특성 폴더 제거", + "toolbar.image": "이미지", + "toolbar.render": "렌더링", + "toolbar.render_scene": "장면", + "ui.1_degree_of_freedom": "자유도 1개", + "ui.3d_sketch": "3D 스케치", + "ui.about": "정보", + "ui.activate": "활성화", + "ui.active_component": "활성 컴포넌트", + "ui.agent_chat": "에이전트 채팅", + "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_auth_agent": "{name}(으)로 로그인", + "ui.agent_chat_auth_env": "환경 변수 {vars}을(를) 설정하고 SolidCraft를 다시 시작하세요.", + "ui.agent_chat_auth_needed": "에이전트가 로그인을 요청합니다. 로그인은 에이전트에서 직접 하며, SolidCraft는 비밀번호나 키를 보지 않습니다.", + "ui.agent_chat_auth_none": "이 에이전트는 여기서 로그인 방법을 제공하지 않습니다. 에이전트 문서에 안내된 방법으로 로그인하세요.", + "ui.agent_chat_auth_retry": "로그인했습니다: 다시 연결", + "ui.agent_chat_auth_terminal": "터미널에서 이것을 실행한 뒤 다시 연결을 누르세요:", + "ui.agent_chat_auth_title": "에이전트에 로그인", + "ui.agent_chat_cancel": "취소", + "ui.agent_chat_changes": "변경 {n}개, 실행 취소 한 번", + "ui.agent_chat_changes_of": "변경 {n}/{limit}", + "ui.agent_chat_close": "닫기", + "ui.agent_chat_command": "에이전트 명령", + "ui.agent_chat_connect": "연결", + "ui.agent_chat_copy": "복사", + "ui.agent_chat_custom_hint": "표준 입출력으로 Agent Client Protocol을 사용하는 모든 프로그램. 셸 없이 실행됩니다.", + "ui.agent_chat_denied": "거부함", + "ui.agent_chat_deny": "거부", + "ui.agent_chat_desktop_only": "에이전트 채팅은 데스크톱 앱이 필요합니다.", + "ui.agent_chat_detecting": "에이전트 찾는 중…", + "ui.agent_chat_dock_left": "왼쪽에 고정", + "ui.agent_chat_dock_right": "오른쪽에 고정", + "ui.agent_chat_exited": "에이전트가 중지되었습니다.", + "ui.agent_chat_failed_start": "에이전트를 시작할 수 없습니다: {error}", + "ui.agent_chat_intro": "이미 사용 중인 코딩 에이전트나 선택한 모델 엔드포인트와 채팅하세요. SolidCraft 도구로 열린 디자인을 다루며, 변경 사항은 바로 보이고 메시지마다 한 번에 실행 취소할 수 있습니다. 묻지 않고 할 수 있는 일은 환경 설정 > AI에서 정합니다.", + "ui.agent_chat_key_in_env": "키 설정됨", + "ui.agent_chat_left": "왼쪽", + "ui.agent_chat_limit": "에이전트가 메시지당 변경 한도 {limit}에 도달했습니다. 계속하게 하려면 메시지를 하나 더 보내세요.", + "ui.agent_chat_minimize": "얇은 막대로 최소화", + "ui.agent_chat_no_cli": "앱 옆에서 solidcraft-cli를 찾지 못해 에이전트가 디자인에 접근할 수 없습니다.", + "ui.agent_chat_no_control": "에이전트 채팅 엔드포인트가 시작되지 않아 에이전트가 디자인에 접근할 수 없습니다.", + "ui.agent_chat_no_images": "이 에이전트는 이미지를 받지 않습니다", + "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_permission": "에이전트가 실행 허락을 요청합니다: {title}", + "ui.agent_chat_pick": "에이전트", + "ui.agent_chat_placeholder": "에이전트에게 디자인 변경을 요청하세요…", + "ui.agent_chat_privacy": "사용자의 계정으로 실행하는 에이전트 외에는 아무 데도 전송되지 않습니다.", + "ui.agent_chat_privacy_note": "SolidCraft는 아무것도 어디로도 보내지 않습니다. 실행한 에이전트가 사용자의 계정으로 자신의 서비스와 통신합니다. SolidCraft는 키나 비밀번호를 보거나 저장하지 않습니다.", + "ui.agent_chat_refresh": "새로 고침", + "ui.agent_chat_refused": "에이전트에게 허용되지 않음: {reason}", + "ui.agent_chat_right": "오른쪽", + "ui.agent_chat_send": "보내기", + "ui.agent_chat_side": "에이전트 채팅 위치", + "ui.agent_chat_signed_in": "로그인됨", + "ui.agent_chat_state_auth": "로그인 필요", + "ui.agent_chat_state_busy": "작업 중…", + "ui.agent_chat_state_exited": "에이전트 중지됨", + "ui.agent_chat_state_off": "연결 안 됨", + "ui.agent_chat_state_ready": "준비됨", + "ui.agent_chat_state_starting": "시작하는 중…", + "ui.agent_chat_stop": "중지", + "ui.agent_chat_stop_tip": "에이전트와 에이전트가 시작한 모든 것을 중지", + "ui.agent_chat_turn_limit": "메시지당 변경 수", + "ui.agent_chat_undo_changes": "이 변경 사항 실행 취소", + "ui.agent_chat_undo_label": "에이전트 채팅: {message}", + "ui.agent_chat_undone": "(취소됨)", + "ui.agent_chat_view_attached": "뷰 첨부됨", + "ui.agent_chat_wait_turn": "에이전트가 아직 이전 메시지를 처리 중입니다. 기다리거나 취소를 누르세요.", + "ui.agent_cursor": "에이전트 커서", + "ui.agent_cursor_speed": "에이전트 커서 속도", + "ui.ai_add": "추가", + "ui.ai_add_agent": "에이전트 추가…", + "ui.ai_add_agent_title": "에이전트 추가", + "ui.ai_add_api": "OpenAI 호환 API", + "ui.ai_add_custom": "사용자 지정 명령", + "ui.ai_add_installed": "설치된 에이전트", + "ui.ai_add_installed_note": "설치된 에이전트에 대한 별도 항목(예: 다른 인수로 실행). 설치된 에이전트는 자동으로 표시됩니다.", + "ui.ai_added": "추가됨", + "ui.ai_agent_mode_tip": "에이전트 자체 모드: 에이전트 자체 도구(셸, 파일 편집)는 이 모드를 따릅니다. SolidCraft 도구는 환경 설정 > AI의 권한을 따릅니다.", + "ui.ai_agents": "에이전트", + "ui.ai_always_allow": "항상 허용", + "ui.ai_always_allow_tip": "이 에이전트에게 앞으로 {tool}을(를) 묻지 않고 허용", + "ui.ai_always_allowed": "항상 허용됨", + "ui.ai_always_allowed_none": "아직 항상 허용된 것이 없습니다. 채팅에서 \"항상 허용\"으로 답한 항목이 여기에 표시됩니다.", + "ui.ai_auto_allowed": "자동 허용: {title} ({why})", + "ui.ai_auto_mode": "권한 설정", + "ui.ai_auto_ours": "SolidCraft가 자체 도구를 직접 확인합니다", + "ui.ai_auto_remembered": "\"항상 허용\"을 선택함", + "ui.ai_bad_url": "http:// 또는 https://로 시작하는 URL을 입력하세요", + "ui.ai_base_url": "기본 URL", + "ui.ai_button": "AI", + "ui.ai_copy_suffix": "복사본", + "ui.ai_custom_url": "사용자 지정 URL", + "ui.ai_default": "기본값", + "ui.ai_http_busy": "엔드포인트가 바쁘거나 한도에 도달했습니다. 나중에 다시 시도하세요", + "ui.ai_http_key": "엔드포인트가 키를 거부했습니다. 환경 설정 > AI에서 확인하세요", + "ui.ai_http_not_found": "엔드포인트나 모델을 찾을 수 없습니다. 기본 URL과 모델 이름을 확인하세요", + "ui.ai_key": "API 키", + "ui.ai_key_hint": "선택 사항, 시스템 키체인에 저장", + "ui.ai_key_needs_https": "키는 HTTPS를 통해서만, 또는 이 컴퓨터로만 전송됩니다.", + "ui.ai_key_note": "SolidCraft 설정이 아닌 시스템 키체인에 저장됩니다. 로컬 서버라면 비워 두세요.", + "ui.ai_keychain_error": "시스템 키체인이 거부했습니다: {error}", + "ui.ai_mode_all": "모두 허용", + "ui.ai_mode_all_note": "묻지 않고 실행합니다. 충돌 보고서는 계속 제외되고 폴더 제한도 그대로 적용됩니다.", + "ui.ai_mode_all_warning": "에이전트가 묻지 않고 디자인을 저장, 덮어쓰기, 내보내기, 교체할 수 있습니다. 신뢰하는 에이전트와 저장된 디자인에서만 사용하세요.", + "ui.ai_mode_ask": "매번 묻기", + "ui.ai_mode_ask_note": "디자인의 모든 변경과 파일 작업이 사용자의 허용을 기다립니다.", + "ui.ai_mode_edits": "모델 편집 자동 허용", + "ui.ai_mode_edits_note": "모델링 명령은 묻지 않고 실행되며, 저장·열기·내보내기 등 파일 작업이나 파괴적인 작업은 계속 묻습니다.", + "ui.ai_mode_global": "위 설정 따름", + "ui.ai_model": "모델", + "ui.ai_modes_scope": "이 설정은 SolidCraft 도구에 적용됩니다. 에이전트 자체 도구(셸, 파일 편집)는 에이전트에 모드가 있을 때 채팅 패널 머리글에서 고르는 에이전트 자체 모드를 따릅니다.", + "ui.ai_name": "이름", + "ui.ai_need_command": "에이전트를 시작하는 명령을 입력하세요", + "ui.ai_need_model": "모델 이름을 입력하세요", + "ui.ai_no_answer": "에이전트가 제시간에 응답하지 않았습니다", + "ui.ai_no_http": "이 빌드는 API 엔드포인트에 연결할 수 없습니다", + "ui.ai_no_keychain": "시스템 키체인을 사용할 수 없어 키를 저장할 수 없습니다. 키가 필요 없는 로컬 서버는 사용할 수 있습니다.", + "ui.ai_panel": "패널", + "ui.ai_permissions": "권한", + "ui.ai_preset": "프리셋", + "ui.ai_remove": "제거", + "ui.ai_request_limit": "메시지 하나에 24번 요청 후 멈췄습니다. 계속하려면 메시지를 하나 더 보내세요", + "ui.ai_reset": "재설정", + "ui.ai_settings": "AI 설정…", + "ui.ai_show_features": "AI 기능 표시", + "ui.ai_show_features_note": "에이전트 채팅: 이미 사용 중인 코딩 에이전트나 선택한 모델 엔드포인트가 열린 디자인을 다루는 패널입니다. 끄면 AI 버튼, 단축키, 메뉴 항목, 패널이 없고 아무것도 찾거나 시작하지 않습니다.", + "ui.ai_switch_tip": "이 대화의 에이전트 변경", + "ui.ai_test": "테스트", + "ui.ai_test_acp_ok": "응답: {agent}", + "ui.ai_test_acp_tip": "에이전트를 잠시 시작해 세션을 요청한 뒤 종료합니다", + "ui.ai_test_api_tip": "엔드포인트에 모델 목록을 요청합니다", + "ui.ai_test_no_model": "연결됨: 모델 {count}개, {model} 없음", + "ui.ai_test_ok": "연결됨: 모델 {count}개", + "ui.ai_testing": "테스트 중…", + "ui.ai_tool_done": "완료", + "ui.ai_tool_failed": "실패", + "ui.ai_tool_running": "실행 중", + "ui.ai_tool_unfold": "클릭하면 결과를 표시", + "ui.ai_tool_waiting": "대기 중", + "ui.ai_toolbar_button": "도구 모음에 버튼 표시", + "ui.ai_toolbar_button_note": "도구 모음 오른쪽 끝의 AI 버튼. Ctrl+Shift+A와 보기 메뉴로도 패널을 열 수 있습니다.", + "ui.ai_undo_tip": "이 메시지에서 에이전트가 바꾼 모든 것을 한 번에 실행 취소", + "ui.all": "모두", + "ui.analysis": "분석", + "ui.angle": "각도", + "ui.angle_decimals": "각도 소수점 자릿수", + "ui.animateJoint": "조인트 애니메이션", + "ui.animate_view_changes": "뷰 변경 애니메이션", + "ui.animation": "애니메이션", + "ui.animation_speed": "애니메이션 속도", + "ui.anti_aliasing": "안티앨리어싱", + "ui.apply": "적용", + "ui.arc": "호", + "ui.assemble": "조립", + "ui.autosave_every": "자동 저장 간격", + "ui.axes": "축", + "ui.axis": "축", + "ui.base_point": "기준점", + "ui.blocked": "막힘", + "ui.bodies": "바디", + "ui.box": "박스", + "ui.break": "끊기", + "ui.calibrate": "캘리브레이션", + "ui.cancel": "취소", + "ui.canvases": "캔버스", + "ui.center": "중심", + "ui.centerline": "중심선", + "ui.chain": "체인", + "ui.chamfer": "모따기", + "ui.chamfer_type": "모따기 유형", + "ui.change_workspace": "작업 공간 변경", + "ui.chord_length": "현 길이", + "ui.circle": "원", + "ui.circular_pattern": "원형 패턴", + "ui.clear_recent": "최근 항목 지우기", + "ui.clear_the_selection": "선택 해제", + "ui.close": "닫기", + "ui.coil": "코일", + "ui.coincident": "일치", + "ui.collapse": "접기", + "ui.collinear": "동일 선상", + "ui.colour_vision": "색각", + "ui.colour_vision_deutan": "녹색각이상 (Deutan)", + "ui.colour_vision_deutan_tip": "녹색 감각이 약하거나 없는 경우", + "ui.colour_vision_failed": "실패", + "ui.colour_vision_fixed": "고정", + "ui.colour_vision_mode": "모드", + "ui.colour_vision_note": "의미를 나타내는 색을 바꿉니다: 스케치 상태, 축, 벤딩, 분석, 아이콘. Windows 색 필터를 사용한다면 '끄기'로 두세요.", + "ui.colour_vision_off": "끄기", + "ui.colour_vision_off_tip": "테마 고유의 색상", + "ui.colour_vision_projected": "투영", + "ui.colour_vision_protan": "적색각이상 (Protan)", + "ui.colour_vision_protan_tip": "빨간색 감각이 약하거나 없는 경우", + "ui.colour_vision_sample": "예시", + "ui.colour_vision_tritan": "청색각이상 (Tritan)", + "ui.colour_vision_tritan_tip": "파란색 감각이 약하거나 없는 경우", + "ui.combine": "결합", + "ui.coming_later": "추후 지원 예정", + "ui.command_done": "{command} 완료", + "ui.command_palette_hint": "명령 입력(예: {example}) — 또는 S 키를 눌러 검색", + "ui.concentric": "동심", + "ui.configurations": "구성", + "ui.conic_curve": "원뿔 곡선", + "ui.constant": "상수", + "ui.constraints_conflict": "구속 조건 충돌", + "ui.construct": "구성", + "ui.construction": "구성선", + "ui.copy": "복사", + "ui.corner": "코너", + "ui.corners": "코너", + "ui.counterbore": "카운터보어", + "ui.countersink": "카운터싱크", + "ui.create": "만들기", + "ui.create_copy": "복사본 만들기", + "ui.create_sketch": "스케치 만들기", + "ui.current": "현재", + "ui.curvature": "곡률", + "ui.curvature_g2": "곡률 연속 (G2)", + "ui.curves": "곡선", + "ui.custom_program": "사용자 지정…", + "ui.custom_program_tip": "목록에 추가할 슬라이서 프로그램 선택", + "ui.customizeToolbar": "도구 모음 사용자 지정…", + "ui.cut": "잘라내기", + "ui.cylinder": "원통", + "ui.dark": "어둡게", + "ui.default_modelling_orientation": "기본 모델링 방향", + "ui.degrees_of_freedom": "자유도", + "ui.delete": "삭제", + "ui.depth": "깊이", + "ui.design": "디자인", + "ui.design_properties.author": "작성자", + "ui.design_properties.description": "설명", + "ui.design_properties.exports": "STEP, IGES, 3MF 내보내기는 형식에 해당 항목이 있으면 이 속성을 기록합니다.", + "ui.design_properties.license": "라이선스", + "ui.design_properties.not_text": "텍스트가 아닌 값으로 저장되어 있습니다. 여기에 입력하면 대체됩니다.", + "ui.design_properties.organization": "조직", + "ui.design_properties.others": "다른 도구의 데이터", + "ui.design_properties.others_note": "설계에 그대로 유지되며 내보내지지 않습니다.", + "ui.design_properties.part_number": "부품 번호", + "ui.design_properties.project": "프로젝트", + "ui.design_properties.revision": "리비전", + "ui.diameter": "지름", + "ui.dimension": "치수", + "ui.direction": "방향", + "ui.display_quality": "표시 품질", + "ui.display_quality_coarse": "거침", + "ui.display_quality_fine": "세밀", + "ui.display_quality_normal": "보통", + "ui.display_quality_ultra": "최고", + "ui.distance": "거리", + "ui.distance_1": "거리 1", + "ui.distance_2": "거리 2", + "ui.document_settings": "문서 설정", + "ui.don_t_save": "저장 안 함", + "ui.draft": "구배", + "ui.drawing": "도면", + "ui.drill_point": "드릴 선단", + "ui.edit": "편집", + "ui.editJointLimits": "조인트 제한 편집", + "ui.edit_section_analysis": "단면 분석 편집", + "ui.ellipse": "타원", + "ui.end_radius": "끝 반지름", + "ui.end_scale": "끝 배율", + "ui.entities": "요소", + "ui.equal": "동일", + "ui.equivalent_radius": "등가 반지름", + "ui.expand": "펼치기", + "ui.exportDxf": "DXF 내보내기…", + "ui.export_ellipsis": "내보내기...", + "ui.export_ellipsis_keymap": "내보내기…", + "ui.extend": "연장", + "ui.extent_type": "범위 유형", + "ui.extrude": "돌출", + "ui.factor": "배율", + "ui.feature_history": "피처 기록", + "ui.feature_options": "피처 옵션", + "ui.features": "피처", + "ui.file": "파일", + "ui.fillet": "필렛", + "ui.findInTimeline": "타임라인에서 찾기", + "ui.findInWindow": "창에서 찾기", + "ui.finish_sketch": "스케치 종료", + "ui.fit": "맞춤", + "ui.fix_unfix": "고정/고정 해제", + "ui.flat": "플랫", + "ui.flip": "뒤집기", + "ui.format": "형식", + "ui.front": "정면", + "ui.fully_constrained": "완전 구속", + "ui.general": "일반", + "ui.graphics": "그래픽", + "ui.groupSelected": "선택 항목 그룹화", + "ui.heading_assemble": "조립", + "ui.heading_box": "박스", + "ui.heading_chamfer": "모따기", + "ui.heading_circular_pattern": "원형 패턴", + "ui.heading_coil": "코일", + "ui.heading_combine": "결합", + "ui.heading_configure": "구성", + "ui.heading_constraints": "구속 조건", + "ui.heading_construct": "구성", + "ui.heading_create": "만들기", + "ui.heading_create_sketch": "스케치 만들기", + "ui.heading_cylinder": "원통", + "ui.heading_design": "디자인", + "ui.heading_draft": "구배", + "ui.heading_edit": "편집", + "ui.heading_extrude": "돌출", + "ui.heading_fillet": "필렛", + "ui.heading_finish_sketch": "스케치 종료", + "ui.heading_front": "정면", + "ui.heading_hole": "구멍", + "ui.heading_home": "홈", + "ui.heading_insert": "삽입", + "ui.heading_inspect": "검사", + "ui.heading_loft": "로프트", + "ui.heading_measure": "측정", + "ui.heading_mesh": "메시", + "ui.heading_mirror": "대칭 복사", + "ui.heading_modify": "수정", + "ui.heading_move": "이동", + "ui.heading_move_copy": "이동/복사", + "ui.heading_offset": "오프셋", + "ui.heading_offset_plane": "오프셋 평면", + "ui.heading_ok": "확인", + "ui.heading_parameters": "매개변수", + "ui.heading_pattern_on_path": "경로 패턴", + "ui.heading_pipe": "파이프", + "ui.heading_plane_at_angle": "각도 평면", + "ui.heading_plastic": "플라스틱", + "ui.heading_position": "배치", + "ui.heading_rectangular_pattern": "직사각형 패턴", + "ui.heading_revolve": "회전", + "ui.heading_right": "우측면", + "ui.heading_save_mesh": "메쉬로 저장", + "ui.heading_scale": "축척", + "ui.heading_section_analysis": "단면 분석", + "ui.heading_select": "선택", + "ui.heading_setup": "설정", + "ui.heading_sheet_metal": "판금", + "ui.heading_shell": "쉘", + "ui.heading_sketch": "스케치", + "ui.heading_sketch_palette": "스케치 팔레트", + "ui.heading_sketch_scale": "스케치 배율", + "ui.heading_solid": "솔리드", + "ui.heading_sphere": "구", + "ui.heading_split_body": "바디 분할", + "ui.heading_surface": "서피스", + "ui.heading_sweep": "스윕", + "ui.heading_thread": "나사산", + "ui.heading_top": "상면", + "ui.heading_torus": "토러스", + "ui.heading_utilities": "유틸리티", + "ui.help": "도움말", + "ui.hide": "숨기기", + "ui.hideAxes": "축 숨기기", + "ui.hideDimension": "치수 숨기기", + "ui.hideOrigin": "원점 숨기기", + "ui.hidePlanes": "평면 숨기기", + "ui.hideProfile": "윤곽 숨기기", + "ui.hole": "구멍", + "ui.hole_tap_type": "탭 유형", + "ui.hole_type": "구멍 유형", + "ui.home": "홈", + "ui.homeView": "홈 보기", + "ui.horizontal_vertical": "수평/수직", + "ui.insert": "삽입", + "ui.inspect": "검사", + "ui.intersect": "교차", + "ui.isolate": "분리 표시", + "ui.join": "접합", + "ui.joints": "조인트", + "ui.keyboard_shortcuts": "키보드 단축키", + "ui.language": "언어", + "ui.length_decimals": "길이 소수점 자릿수", + "ui.light": "밝게", + "ui.line": "선", + "ui.linetype": "선 종류", + "ui.lock": "잠금", + "ui.loft": "로프트", + "ui.look_at": "바라보기", + "ui.manufacture": "제조", + "ui.material_review.axes": "재료 로컬 축입니다. 바디 방향을 지정하지 않습니다.", + "ui.material_review.claims": "출처와 라이선스는 검증되지 않은 주장입니다. 누락된 값은 알 수 없는 상태로 유지됩니다.", + "ui.material_review.compressive_strength": "압축 강도", + "ui.material_review.conditions": "명시된 조건", + "ui.material_review.density": "밀도", + "ui.material_review.derived": "유도된 등방성 탄성 계수", + "ui.material_review.elasticity": "탄성", + "ui.material_review.input": "스키마 1 재료 카드 붙여넣기 (JSON)", + "ui.material_review.limit": "카드가 256 KiB 입력 한도를 초과합니다.", + "ui.material_review.moisture_unit": "kg 물 / kg 건조 재료", + "ui.material_review.properties": "물성", + "ui.material_review.review": "카드 검토", + "ui.material_review.scope": "후보만 검토합니다. 지정하거나 저장하지 않습니다. 수치 검증은 공학적 인증이 아닙니다.", + "ui.material_review.shear_strength": "전단 강도", + "ui.material_review.source": "출처", + "ui.material_review.specific_heat": "비열", + "ui.material_review.tensile_strength": "인장 강도", + "ui.material_review.thermal_conductivity": "열전도율", + "ui.material_review.thermal_expansion": "열팽창", + "ui.material_review.title": "물리적 재료 데이터 검토", + "ui.material_review.unknown": "알 수 없음", + "ui.material_review.yield_strength": "항복 강도", + "ui.measure": "측정", + "ui.mesh_format_3mf": "3MF", + "ui.mesh_format_3mf_tagged": "면 태그가 있는 3MF", + "ui.mesh_format_stl": "STL", + "ui.midpoint": "중간점", + "ui.mirror": "대칭 복사", + "ui.mirror_line": "대칭선", + "ui.modify": "수정", + "ui.move": "이동", + "ui.multiple": "다중", + "ui.named_views": "명명된 뷰", + "ui.navigation": "탐색", + "ui.needs_design": "{command}: 먼저 디자인을 열어 주세요", + "ui.newSketchGroup": "새 스케치 그룹", + "ui.new_body": "새 바디", + "ui.new_design": "새 디자인", + "ui.no_slicer_found": "슬라이서를 찾을 수 없음", + "ui.normal": "일반", + "ui.normalConstruction": "일반 / 생성", + "ui.not_a_program": "{path}은(는) 실행할 수 있는 프로그램이 아닙니다", + "ui.object_type": "객체 유형", + "ui.objects": "객체", + "ui.offer_to_stand_up_y_up_files": "Y-up 파일을 Z-up으로 세우도록 제안", + "ui.offset": "오프셋", + "ui.offset_plane": "오프셋 평면", + "ui.one_side": "한 방향", + "ui.open": "열기", + "ui.open_ellipsis": "열기...", + "ui.open_preferences": "환경 설정 열기", + "ui.open_recent": "최근 항목 열기", + "ui.operation": "작업", + "ui.options": "옵션", + "ui.orbit": "회전", + "ui.orbit_around": "궤도 회전 기준", + "ui.orientation": "배향", + "ui.origin": "원점", + "ui.palette_points": "점", + "ui.palette_profile": "프로파일", + "ui.pan": "이동", + "ui.pan_zoom_orbit": "이동, 확대/축소, 궤도 회전", + "ui.parallel": "평행", + "ui.parameters": "매개변수", + "ui.paste": "붙여넣기", + "ui.path": "경로", + "ui.pattern_on_path": "경로 패턴", + "ui.perpendicular": "수직", + "ui.pinToShortcuts": "바로 가기에 고정", + "ui.pinToToolbar": "도구 모음에 고정", + "ui.pipe": "파이프", + "ui.placement": "배치", + "ui.plane": "평면", + "ui.plane_at_angle": "각도 평면", + "ui.point": "점", + "ui.point_under_the_cursor": "커서 아래의 점", + "ui.points": "점", + "ui.polygon": "다각형", + "ui.preferences": "환경 설정", + "ui.profile": "프로파일", + "ui.profile_plane": "프로파일 평면", + "ui.profiles": "프로파일", + "ui.project": "투영", + "ui.properties": "속성", + "ui.pull_direction": "빼기 방향", + "ui.quantity": "수량", + "ui.quantity_2": "수량 2", + "ui.quit": "종료", + "ui.radius": "반지름", + "ui.radius_type": "반지름 유형", + "ui.reachable": "도달 가능", + "ui.rectangle": "직사각형", + "ui.rectangular_pattern": "직사각형 패턴", + "ui.redo": "다시 실행", + "ui.removeFromToolbar": "도구 모음에서 제거", + "ui.removeSection": "단면 제거", + "ui.render": "렌더", + "ui.repeat": "반복", + "ui.report_a_bug": "버그 신고", + "ui.reset_the_settings_on_this_page": "이 페이지의 설정 초기화", + "ui.restore": "복원", + "ui.restore_defaults": "기본값 복원", + "ui.reverse_zoom_direction": "확대/축소 방향 반전", + "ui.revolve": "회전", + "ui.right": "우측면", + "ui.save": "저장", + "ui.save_as": "다른 이름으로 저장", + "ui.save_as_ellipsis": "다른 이름으로 저장...", + "ui.save_mesh_no_slicer": "슬라이서를 찾을 수 없습니다. '사용자 지정…'에서 슬라이서 프로그램을 선택하거나 '슬라이서로 보내기'를 끄세요", + "ui.save_mesh_pick_bodies": "저장할 바디를 선택하세요", + "ui.save_mesh_temp_failed": "{folder}을(를) 만들 수 없습니다: {error}", + "ui.saved_to": "저장됨: {path}", + "ui.scale": "축척", + "ui.section_analysis": "단면 분석", + "ui.select": "선택", + "ui.selectOther": "기타 선택…", + "ui.selectTangentChain": "접선 체인 선택", + "ui.selection": "선택", + "ui.send": "보내기", + "ui.send_to_slicer": "슬라이서로 보내기", + "ui.sent_to_slicer": "{slicer}(으)로 보냈습니다", + "ui.shell": "쉘", + "ui.show": "표시", + "ui.showAll": "모두 표시", + "ui.showAllBodies": "모두 표시", + "ui.showAxes": "축 표시", + "ui.showDimension": "치수 표시", + "ui.showOrigin": "원점 표시", + "ui.showPlanes": "평면 표시", + "ui.show_constraints": "구속 조건", + "ui.show_construction_geometries": "구성 형상", + "ui.show_dimensions": "치수", + "ui.show_points": "점 표시", + "ui.show_profile": "프로파일 표시", + "ui.show_projected_geometries": "투영된 형상", + "ui.simple": "단순", + "ui.simulation": "시뮬레이션", + "ui.single": "단일", + "ui.sketch": "스케치", + "ui.sketch_dimension": "스케치 치수", + "ui.sketch_grid": "스케치 격자", + "ui.sketch_scale": "스케치 축척", + "ui.sketch_status": "스케치 상태", + "ui.sketches": "스케치", + "ui.slice": "슬라이스", + "ui.slicer": "슬라이서", + "ui.slicer_delete_tip": "{program}\nDelete 키로 목록에서 제거", + "ui.slot": "슬롯", + "ui.smooth": "부드럽게", + "ui.snap": "스냅", + "ui.spacing": "간격", + "ui.spacing_2": "간격 2", + "ui.sphere": "구", + "ui.spline": "스플라인", + "ui.split_body": "바디 분할", + "ui.start": "시작", + "ui.start_radius": "시작 반지름", + "ui.supersampling": "슈퍼샘플링 (SSAA)", + "ui.supersampling_adaptive": "뷰가 멈춰 있을 때만", + "ui.supersampling_off": "끔 (1×)", + "ui.suppress": "비활성화", + "ui.sweep": "스윕", + "ui.sweep_follow_direction": "방향 따르기", + "ui.sweep_keep_as_drawn": "그린 대로 유지", + "ui.sweep_turn_with_path": "경로를 따라 회전", + "ui.symmetric": "대칭", + "ui.symmetry": "대칭", + "ui.system": "시스템", + "ui.tangent": "접선", + "ui.taper_angle": "테이퍼 각도", + "ui.tapped": "탭", + "ui.text": "텍스트", + "ui.theme": "테마", + "ui.thickness": "두께", + "ui.thread": "나사산", + "ui.timeline_bottom": "하단 타임라인", + "ui.timeline_left_note": "왼쪽 레이아웃에서는 롤백 바가 부품 및 장면 브라우저 위에 표시됩니다.", + "ui.timeline_left_sidebar": "왼쪽 사이드바", + "ui.tip_angle": "선단 각도", + "ui.to_object": "객체까지", + "ui.tool_direction": "공구 방향", + "ui.top": "상면", + "ui.torus": "토러스", + "ui.total_angle": "전진 각도", + "ui.trim": "트림", + "ui.twist": "비틀림", + "ui.two_sides": "양방향", + "ui.ui_scale": "UI 배율", + "ui.undo": "실행 취소", + "ui.unground": "고정 해제", + "ui.unisolate": "분리 표시 해제", + "ui.units": "단위", + "ui.units_of_new_designs": "새 디자인의 단위", + "ui.unlock": "잠금 해제", + "ui.unsuppress": "비활성화 해제", + "ui.untitled": "제목 없음", + "ui.updateToCurrentView": "현재 보기로 업데이트", + "ui.variable": "가변", + "ui.view_centre": "뷰 중심", + "ui.visual_style": "시각 스타일", + "ui.workspace": "작업 공간", + "ui.x_distance": "X 거리", + "ui.y_distance": "Y 거리", + "ui.zoom": "확대/축소", + "ui.zoom_to_the_cursor": "커서 위치로 확대/축소", "update.available": "SolidCraft {version} 사용 가능", - "update.you_have": "현재 버전은 {version}입니다.", - "update.no_notes": "이 릴리스에는 릴리스 노트가 없습니다.", - "update.system_hint": "이 사본은 {kind}입니다. 다음 명령으로 업데이트하세요:", - "update.package_hint": "이 사본은 {kind}(으)로 설치되었습니다. 새 패키지를 내려받은 뒤 다음 명령으로 설치하세요:", - "update.copy": "복사", - "update.file": "내려받을 파일: {file}", - "update.download": "다운로드", - "update.release_page": "릴리스 페이지 열기", - "update.skip": "이 버전 건너뛰기", - "update.later": "나중에 알림", - "update.prefs_label": "업데이트", + "update.button": "업데이트", + "update.button_tip": "SolidCraft {version} 사용 가능", "update.check_automatically": "업데이트 자동 확인", "update.check_now": "지금 확인", "update.checking": "확인 중…", - "update.failed": "확인할 수 없습니다: {error}", - "update.up_to_date": "SolidCraft가 최신 버전입니다.", - "update.prefs_note": "SolidCraft {version} ({kind})입니다. 확인 시 GitHub에 최신 릴리스만 요청하며 다른 정보는 보내지 않습니다.", - "update.prefs_dev": "개발 빌드({version})이므로 업데이트를 확인하지 않습니다.", - "update.show": "{version} 업데이트 보기", - "update.prefs_flatpak": "이 사본({version})은 Flatpak이 업데이트합니다: {command}를 실행하거나 소프트웨어 센터를 사용하세요. SolidCraft는 직접 확인하지 않습니다.", - "update.update_now": "지금 업데이트", - "update.install_msi": "설치 (SolidCraft 종료)", + "update.copy": "복사", + "update.dmg_opened": "디스크 이미지를 확인하고 열었습니다: SolidCraft를 응용 프로그램 폴더로 끌어 기존 버전을 바꾼 뒤 SolidCraft를 다시 시작하세요.", + "update.download": "다운로드", "update.download_open": "다운로드 후 열기", "update.downloading": "다운로드 및 확인 중… {done} / {total} MB", + "update.failed": "확인할 수 없습니다: {error}", + "update.file": "내려받을 파일: {file}", + "update.install_failed": "업데이트를 설치하지 못했습니다: {error}. 아무것도 변경되지 않았습니다. 다운로드로 패키지를 받을 수 있습니다.", + "update.install_msi": "설치 (SolidCraft 종료)", "update.installed": "SolidCraft {version}이(가) 설치되었습니다. 다시 시작하면 사용할 수 있습니다.", + "update.installer_started": "SolidCraft가 종료되면 설치 프로그램이 시작됩니다.", + "update.later": "나중에 알림", + "update.no_notes": "이 릴리스에는 릴리스 노트가 없습니다.", + "update.package_hint": "이 사본은 {kind}(으)로 설치되었습니다. 새 패키지를 내려받은 뒤 다음 명령으로 설치하세요:", + "update.prefs_dev": "개발 빌드({version})이므로 업데이트를 확인하지 않습니다.", + "update.prefs_flatpak": "이 사본({version})은 Flatpak이 업데이트합니다: {command}를 실행하거나 소프트웨어 센터를 사용하세요. SolidCraft는 직접 확인하지 않습니다.", + "update.prefs_label": "업데이트", + "update.prefs_note": "SolidCraft {version} ({kind})입니다. 확인 시 GitHub에 최신 릴리스만 요청하며 다른 정보는 보내지 않습니다.", + "update.release_page": "릴리스 페이지 열기", "update.restart": "지금 다시 시작", "update.restart_later": "나중에", - "update.installer_started": "SolidCraft가 종료되면 설치 프로그램이 시작됩니다.", - "update.dmg_opened": "디스크 이미지를 확인하고 열었습니다: SolidCraft를 응용 프로그램 폴더로 끌어 기존 버전을 바꾼 뒤 SolidCraft를 다시 시작하세요.", - "update.install_failed": "업데이트를 설치하지 못했습니다: {error}. 아무것도 변경되지 않았습니다. 다운로드로 패키지를 받을 수 있습니다.", - "cmd.render_settings_get": "렌더링 설정", - "cmd.render_settings_set": "렌더링 설정 저장", - "cmd.render_scene": "렌더링 장면 검사", - "cmd.render_settings_apply": "렌더링 카메라 적용", - "toolbar.render": "렌더링", - "toolbar.render_scene": "장면", - "render.preview": "통합 미리보기", - "render.preview_help": "래스터 셰이딩과 블렌딩 투명도를 사용합니다. 굴절, HDRI 및 최종 렌더링은 아직 지원하지 않습니다.", - "render.setup_name": "설정 이름", - "render.background": "장면 배경", - "render.perspective": "원근 카메라", - "render.fit": "제품에 맞추기", - "render.restore_camera": "저장된 카메라 복원", - "render.save_setup": "설정 저장", - "render.unsaved": "저장하지 않은 미리보기 변경 사항", - "render.reload_settings": "저장된 설정 다시 불러오기", - "render.unavailable_preview": "이 설정은 사용할 수 없는 미리보기 프로필을 요청합니다.", - "render.use_preview": "통합 미리보기 사용", - "render.navigation_help": "카메라는 디자인에서와 같이 움직입니다(환경설정 › 탐색). 설정 저장은 현재 카메라를 기록합니다.", - "render.return_design": "설계로 돌아가기", - "render.image_title": "이미지 렌더링", - "render.image_help": "CPU 미리 보기 이미지 · PNG · 근사 투명도", - "render.image_width": "너비", - "render.image_height": "높이", - "render.image_transparent": "투명 배경", - "render.image_check": "렌더 요청 확인", - "render.image_supported": "지원되는 렌더 요청입니다. 시작 시 대기열과 메모리 풀을 다시 확인합니다.", - "render.image_queued": "렌더링 대기 중", - "render.image_preparing": "이미지 준비 중", - "render.image_running": "이미지 렌더링 중", - "render.image_encoding": "PNG 인코딩 중", - "render.image_cancelling": "취소 중", - "render.image_cancelled": "렌더링 취소됨", - "render.image_completed": "이미지 내보내기 준비됨", - "render.image_failed": "렌더링 실패", - "render.image_unknown": "렌더 상태를 확인할 수 없습니다", - "render.image_reduce": "더 작은 이미지나 더 단순한 장면을 사용해 보세요.", - "render.image_too_large": "이미지 한도를 초과했습니다: 한 변 4096픽셀, 전체 4,194,304픽셀.", - "render.image_use_largest": "이 비율에서 가장 큰 크기 사용:", - "render.image_cancel": "렌더링 취소", - "render.image_stale": "이 이미지는 후속 변경 전에 캡처한 장면을 사용합니다.", - "render.image_start": "렌더링 시작", - "render.image_overwrite": "기존 파일 바꾸기", - "render.image_export": "PNG 내보내기", - "cmd.render_preflight": "렌더 요청 확인", - "cmd.render_start": "이미지 렌더링", - "cmd.render_status": "렌더링 진행 상황", - "cmd.render_cancel": "렌더링 취소", - "cmd.render_export": "PNG 내보내기", - "toolbar.image": "이미지", - "appearance.surface_response": "표면 반응", - "appearance.pbr_opaque": "불투명 PBR", - "appearance.metallic": "금속성", - "appearance.roughness": "거칠기", - "appearance.dielectric_ior": "유전체 굴절률", - "appearance.pbr_help": "이 표면은 렌더링 작업 공간이나 제품 PNG에서 확인하세요. 굴절과 투과는 지원하지 않습니다.", - "render.opaque_preview_help": "불투명 PBR 및 단색 표시, 블렌딩 투명도를 지원합니다. 굴절, HDRI 및 최종 렌더링은 아직 지원하지 않습니다.", - "render.opaque_image_summary": "미리보기 PNG · 불투명 PBR · 블렌딩 투명도", - "UNTRIM": "트림 해제", - "Face": "면", - "Holes": "구멍", - "Holes (edges on them)": "구멍 (구멍의 모서리)", - "In place (surfaces)": "제자리에서 (서피스)", - "None": "없음", - "Picked": "선택한 항목", - "Restore outer boundary": "외부 경계 복원", - "RULED SURFACE": "룰드 서피스", - "Mitre": "연귀", - "Reference face": "참조 면", - "Round": "둥글게", - "Type": "유형", - "joint.one_component": "이 부품들은 한 구성 요소의 바디입니다: {bodies}. 관절은 한 구성 요소를 다른 구성 요소에 대해 움직이므로 부품마다 자체 구성 요소가 필요합니다.", - "joint.one_body": "두 선택이 모두 {body}에 있습니다. 두 번째는 다른 부품에서 선택하세요.", - "joint.from_bodies_hint": "선택한 각 바디가 제자리에 그대로 있으면서 자체의 새 구성 요소로 옮겨집니다.", - "Circumference": "원주", - "Arc length": "호 길이", - "Slot width": "슬롯 폭", - "Centre to centre": "중심 간", - "Overall length": "전체 길이", - "Min": "최소", - "Max": "최대", - "Length": "길이", - "Area": "면적", - "coupling.gear_1": "기어 1", - "coupling.gear_2": "기어 2", - "coupling.pinion": "피니언", - "coupling.rack": "랙", - "coupling.nut": "너트", - "coupling.radius_1": "반지름 1", - "coupling.radius_2": "반지름 2", - "coupling.internal": "내접 기어", - "coupling.pitch": "피치", - "coupling.picked": "선택됨", - "coupling.not_round": "원통 면이 아님", - "coupling.gear_1_pick": "기어 1 (선택 사항)", - "coupling.gear_2_pick": "기어 2 (선택 사항)", - "coupling.pinion_pick": "피니언 (선택 사항)", - "coupling.needs_turns": "회전하는 관절 두 개가 필요함", - "coupling.needs_turn_and_slide": "회전하는 관절과 미끄러지는 관절이 필요함" + "update.show": "{version} 업데이트 보기", + "update.skip": "이 버전 건너뛰기", + "update.system_hint": "이 사본은 {kind}입니다. 다음 명령으로 업데이트하세요:", + "update.title": "업데이트 사용 가능", + "update.up_to_date": "SolidCraft가 최신 버전입니다.", + "update.update_now": "지금 업데이트", + "update.you_have": "현재 버전은 {version}입니다." } diff --git a/assets/locales/ru.json b/assets/locales/ru.json index b91b2e89d..0022d10ad 100644 --- a/assets/locales/ru.json +++ b/assets/locales/ru.json @@ -1,6 +1,242 @@ { - "settings.measure_axis_distances": "Расстояния X/Y/Z", - "settings.measure_axis_distances_help": "Показывать размеры вдоль мировых осей вместе с общим расстоянием, пока открыто окно измерения.", + "0 turns it off": "0 отключает", + "A new configuration, a copy of the active one": "Новая конфигурация — копия активной", + "About SolidCraft": "О SolidCraft", + "Active": "Активный", + "Active rule": "Активное правило", + "Add": "Добавить", + "Add Key": "Добавить клавишу", + "Add Mid Radius": "Добавить средний радиус", + "Add Row": "Добавить строку", + "Add condition": "Добавить условие", + "Alignment": "Выравнивание", + "All Sketch Points": "Все точки эскиза", + "All open designs": "Все открытые дизайны", + "Allowed expressions, separated by semicolons": "Разрешённые выражения через точку с запятой", + "Also deletes": "Также удаляет", + "Angle 2": "Угол 2", + "Animate": "Анимировать", + "Appearance name": "Имя внешнего вида", + "Applied Radius": "Применённый радиус", + "Apply To": "Применить к", + "Apply to selection": "Применить к выделению", + "Area": "Площадь", + "Attachment": "Привязка", + "BROWSER": "БРАУЗЕР", + "Bend Line Position": "Положение линии гиба", + "Bend Position": "Положение гиба", + "Bend Radius": "Радиус гиба", + "Bends": "Гибы", + "Body": "Тело", + "Bounding box": "Габаритная рамка", + "CSV or JSON: updates existing parameters, adds new ones": "CSV или JSON: обновляет существующие параметры, добавляет новые", + "Capture All Positions": "Зафиксировать все положения", + "Catch Direction": "Направление защёлкивания", + "Cells": "Ячейки", + "Center X": "Центр X", + "Center Y": "Центр Y", + "Center of mass": "Центр масс", + "Chamfer Type": "Тип фаски", + "Check collisions": "Проверить столкновения", + "Checked": "Включено", + "Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.": "Выберите новую плоскость. Геометрия и размеры эскиза останутся неизменными в её двумерных координатах.", + "Close draft": "Закрыть анализ уклонов", + "Collisions": "Столкновения", + "Colour": "Цвет", + "Component1": "Компонент1", + "Configuration": "Конфигурация", + "Configuration rules": "Правила конфигурации", + "Construction": "Вспомогательная", + "Contact": "Контакт", + "Copy Error Message": "Скопировать сообщение об ошибке", + "Copy Warning Message": "Скопировать предупреждение", + "Copy all licences": "Копировать все лицензии", + "Copy diagnostic information": "Копировать диагностическую информацию", + "Copy report": "Копировать отчёт", + "Copy screenshot": "Копировать скриншот", + "Corner Relief": "Разгрузка угла", + "Corner Relief Shape": "Форма разгрузки угла", + "Counterbore depth": "Глубина цековки", + "Countersink angle": "Угол зенковки", + "Create Issue — review draft": "Создать Issue — проверить черновик", + "Cube": "Куб", + "Customize Toolbar": "Настроить панель инструментов", + "Delete all": "Удалить все", + "Delete rule": "Удалить правило", + "Delete the row": "Удалить строку", + "Delete the set": "Удалить набор", + "Delete this parameter": "Удалить этот параметр", + "Density": "Плотность", + "Designs you open or save appear here.": "Здесь появляются открытые и сохранённые дизайны.", + "Determined by To Object. Choose Angle to edit the angular extent.": "Определяется параметром «До объекта». Выберите «Угол», чтобы задать угловой предел.", + "Discard": "Отменить", + "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": "Привод сопряжения", + "Edges": "Рёбра", + "Edit Profile Sketch": "Редактировать эскиз профиля", + "Enable rule": "Включить правило", + "Enabled": "Включено", + "Explode": "Разобрать", + "Extents": "Пределы", + "Face attachment lost": "Привязка к грани потеряна", + "Faces": "Грани", + "Faces / edges / vertices": "Грани / рёбра / вершины", + "Favourite": "Избранное", + "Files from many CAD programs have Y up, so they open lying on their back here (Z up).": "Файлы многих CAD-программ ориентированы Y вверх, поэтому здесь они открываются лёжа на спине (Z вверх).", + "Filter": "Фильтр", + "Find in Browser": "Найти в браузере", + "Flat": "Плоский", + "Flat size": "Размер развёртки", + "Follow camera (Look At sketches)": "Следовать за камерой (эскизы «Взгляд на»)", + "Follow the camera (Look At sketches)": "Следовать за камерой (эскизы «Взгляд на»)", + "Font": "Шрифт", + "Full Length": "Полная длина", + "Gap": "Зазор", + "Grid": "Сетка", + "Height": "Высота", + "Home view": "Главный вид", + "In This Design": "В этом дизайне", + "Interferes": "Пересекается", + "Issue title": "Заголовок Issue", + "Joint Origin1": "Точка сопряжения1", + "Keep Tools": "Оставить инструменты", + "Later": "Позже", + "Leave it": "Оставить как есть", + "Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "Устаревшая привязка к грани. Перепривязка к сертифицированной грани создаёт точную привязку.", + "Length": "Длина", + "Length units": "Единицы длины", + "Letter Spacing": "Межбуквенный интервал", + "Library": "Библиотека", + "Line Spacing": "Межстрочный интервал", + "Loop": "Контур", + "Margin": "Отступ", + "Mass": "Масса", + "Material": "Материал", + "Mid Radius": "Средний радиус", + "Middle double-click": "Двойной щелчок средней кнопкой", + "Modeled": "Смоделировано", + "More toolbar panels": "Другие панели инструментов", + "Motion": "Движение", + "Move Type": "Тип перемещения", + "Move earlier": "Сдвинуть раньше", + "Move later": "Сдвинуть позже", + "Name": "Имя", + "No crash reports.": "Нет отчётов о сбоях.", + "No matching appearances": "Нет подходящих внешних видов", + "Not available yet": "Пока недоступно", + "Notch": "Вырез", + "Opacity": "Непрозрачность", + "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": "Другая сторона", + "Parameter values": "Значения параметров", + "Path": "Траектория", + "Per Edge": "По каждому ребру", + "Pick the tool bodies": "Выберите тела-инструменты", + "Place at the origin instead": "Разместить в начале координат", + "Playback": "Воспроизведение", + "Position": "Положение", + "Position (0 to 1)": "Положение (от 0 до 1)", + "Position along the edge, 0 at the start end, 1 at the other": "Положение вдоль ребра: 0 — начало, 1 — конец", + "Preview Row": "Строка предпросмотра", + "Preview leaves the current design unchanged.": "Предпросмотр не меняет текущий дизайн.", + "RECENT": "НЕДАВНИЕ", + "Radius Fit": "Подобрать радиус", + "Ratio": "Отношение", + "Reattach selected face": "Перепривязать выбранную грань", + "Recover": "Восстановить", + "Recover unsaved design?": "Восстановить несохранённый дизайн?", + "Rectangular": "Прямоугольная", + "Remove Tools": "Убрать инструменты", + "Remove from list": "Убрать из списка", + "Remove override": "Убрать переопределение", + "Remove private design details or paths before sharing.": "Перед публикацией удалите личные данные и пути из дизайна.", + "Remove screenshot": "Убрать скриншот", + "Remove the column": "Удалить столбец", + "Remove the track": "Удалить дорожку", + "Remove this point": "Удалить эту точку", + "Report a bug — review a screenshot and open a GitHub draft": "Сообщить об ошибке — проверьте скриншот и откройте черновик на GitHub", + "Reset Toolbar": "Сбросить панель инструментов", + "Restore the inherited component or physical material appearance": "Вернуть унаследованный внешний вид компонента или физического материала", + "Result": "Результат", + "Retake screenshot": "Сделать скриншот заново", + "Reverse": "Обратить", + "Reverse Direction": "Обратить направление", + "Revert": "Вернуть", + "Revert All Positions": "Вернуть все положения", + "Revert Position": "Вернуть положение", + "Review the report and screenshot before opening GitHub.": "Проверьте отчёт и скриншот перед открытием GitHub.", + "Rim Edge": "Кромка обода", + "Roll History Marker Here": "Переместить маркер истории сюда", + "Round": "Круглая", + "Rule": "Правило", + "Save Rule": "Сохранить правило", + "Saved preview. Geometry is being checked before editing.": "Сохранённый предпросмотр. Геометрия проверяется перед редактированием.", + "Scale factor": "Коэффициент масштаба", + "Search": "Поиск", + "Search commands": "Поиск команд", + "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).": "Выбрать другое: удерживайте левую кнопку на модели (или правый щелчок › Выбрать другое…), чтобы увидеть всё под курсором; повторный щелчок в том же месте выбирает следующий объект. Двойной щелчок средней кнопкой — «Главная» (Настройки › Навигация).", + "Select bodies (a face picks its body)": "Выберите тела (выбор грани выбирает её тело)", + "Select bodies or faces instead": "Вместо этого выберите тела или грани", + "Selection filter": "Фильтр выделения", + "Semantic faces share their appearance across instances.": "Семантические грани разделяют внешний вид между вхождениями.", + "Shape": "Форма", + "Show Agent Cursor": "Показывать курсор агента", + "Show in folder": "Показать в папке", + "Show the pointer an AI agent moves (#35)": "Показывать указатель, которым двигается ИИ-агент (#35)", + "Signed axes": "Знаковые оси", + "Size": "Размер", + "Sketch constraints": "Ограничения эскиза", + "Sketch curves": "Кривые эскиза", + "Sketch dimensions": "Размеры эскиза", + "Sketch geometry and profiles": "Геометрия и профили эскиза", + "Sketch plane has no body-face attachment.": "Плоскость эскиза не привязана к грани тела.", + "Sketch points": "Точки эскиза", + "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft закрылся до сохранения этих дизайнов. Можно открыть последнюю автосохранённую версию.", + "Speed": "Скорость", + "Stand it up": "Поставить вертикально", + "Stand it up: a quarter turn about X, as one Move feature you can undo.": "Поставить вертикально: четверть оборота вокруг X одной операцией «Переместить», которую можно отменить.", + "Stand this part up?": "Поставить эту деталь вертикально?", + "Step": "Шаг", + "Steps": "Шаги", + "Style": "Стиль", + "Suppressed": "Подавлено", + "Swap Ends": "Поменять концы", + "Tangent Chain": "Касательная цепочка", + "Tear": "Разрыв", + "The dashed sketch is a saved plane guide. Select a new face to repair the attachment.": "Пунктирный эскиз — сохранённая подсказка плоскости. Выберите новую грань, чтобы восстановить привязку.", + "The saved author occurrence is missing. Select a valid author placement before rebinding.": "Сохранённое исходное вхождение отсутствует. Выберите корректное исходное положение перед перепривязкой.", + "Then": "Затем", + "These features will be deleted:": "Эти операции будут удалены:", + "These features will fail:": "Эти операции завершатся с ошибкой:", + "This child is shared. Deleting it removes it from 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.": "Эта грань не может обеспечить надёжную привязку. Выберите другую грань или явно используйте фиксированную плоскость.", + "To Offset": "До смещения", + "Tolerance": "Допуск", + "Type": "Тип", + "Updating the preview": "Обновление предпросмотра", + "Use active author placement": "Использовать активное исходное положение", + "Use fixed plane": "Использовать фиксированную плоскость", + "Use saved fixed plane": "Использовать сохранённую фиксированную плоскость", + "Use selected face as fixed plane": "Использовать выбранную грань как фиксированную плоскость", + "VIEW": "ВИД", + "Value": "Значение", + "Vertices": "Вершины", + "View navigator": "Навигатор видов", + "Volume": "Объём", + "Wall": "Стенка", + "When": "Когда", + "Width": "Ширина", + "Will fail": "Завершится с ошибкой", + "angle, height": "угол, высота", + "appearance.dielectric_ior": "Показатель преломления диэлектрика", + "appearance.metallic": "Металличность", + "appearance.pbr_help": "Просмотр поверхности во вкладке Рендер или на PNG изделия. Без преломления и пропускания света.", + "appearance.pbr_opaque": "Непрозрачный PBR", + "appearance.roughness": "Шероховатость", + "appearance.surface_response": "Поведение поверхности", "browser.body_name": "Тело{number}", "browser.component_name": "Компонент{number}", "browser.parameters": "Параметры ({count})", @@ -27,7 +263,6 @@ "cmd.component_capture_position": "Зафиксировать положение", "cmd.component_create": "Новый компонент", "cmd.component_delete": "Удалить компонент", - "cmd.component_unlock": "Разблокировать содержимое", "cmd.component_from_bodies": "Создать компоненты из тел", "cmd.component_insert_design": "Вставить дизайн", "cmd.component_links": "Список связей", @@ -38,6 +273,7 @@ "cmd.component_properties": "Физические свойства компонента", "cmd.component_rename": "Переименовать компонент", "cmd.component_revert_position": "Вернуть положение", + "cmd.component_unlock": "Разблокировать содержимое", "cmd.component_update_links": "Обновить связи", "cmd.config_activate": "Активировать конфигурацию", "cmd.config_column": "Столбец конфигурации", @@ -79,10 +315,10 @@ "cmd.doc_recovery_discard": "Отказаться от восстановленного дизайна", "cmd.doc_recovery_list": "Восстановимые дизайны", "cmd.document_inspect": "Инспекция дизайна", - "cmd.document_units": "Изменить единицы дизайна", "cmd.document_metadata": "Свойства дизайна", - "cmd.document_metadata_set": "Изменить свойства дизайна", "cmd.document_metadata_remove": "Удалить свойство дизайна", + "cmd.document_metadata_set": "Изменить свойства дизайна", + "cmd.document_units": "Изменить единицы дизайна", "cmd.edit_checkpoint": "Контрольная точка", "cmd.edit_restore_checkpoint": "Вернуть контрольную точку", "cmd.engine_commands": "Список команд", @@ -100,6 +336,7 @@ "cmd.inspect_accessibility": "Анализ доступности", "cmd.inspect_center_of_mass": "Центр масс", "cmd.inspect_compare": "Сравнить тела", + "cmd.inspect_continuity": "Анализ непрерывности", "cmd.inspect_curvature_comb": "Анализ кривизны (гребёнка)", "cmd.inspect_curvature_map": "Карта кривизны", "cmd.inspect_draft": "Анализ уклонов", @@ -113,20 +350,21 @@ "cmd.joint_delete": "Удалить сопряжение", "cmd.joint_drive": "Привод сопряжений", "cmd.joint_edit": "Изменить сопряжение", + "cmd.joint_gear": "Зубчатая передача", "cmd.joint_limits": "Ограничения сопряжения", "cmd.joint_list": "Список сопряжений", "cmd.joint_motion_link": "Связь движений", - "cmd.joint_gear": "Зубчатая передача", - "cmd.joint_rack_pinion": "Реечная передача", - "cmd.joint_screw": "Винт", "cmd.joint_origin": "Точка сопряжения", + "cmd.joint_rack_pinion": "Реечная передача", "cmd.joint_rigid_group": "Жёсткая группа", + "cmd.joint_screw": "Винт", "cmd.joint_solve": "Решить сопряжения", "cmd.material_assign": "Физический материал", "cmd.material_create": "Новый физический материал", "cmd.material_delete": "Удалить физический материал", "cmd.material_edit": "Изменить физический материал", "cmd.material_list": "Список материалов", + "cmd.material_properties_validate": "Проверить данные физического материала", "cmd.mesh_convert": "Преобразовать меш", "cmd.model_edges": "Список рёбер", "cmd.model_faces": "Список граней", @@ -147,10 +385,10 @@ "cmd.parameters_delete": "Удалить параметр", "cmd.parameters_export": "Экспортировать параметры", "cmd.parameters_favorite": "Избранный параметр", - "cmd.parameters_move": "Переместить параметр", "cmd.parameters_graph": "График параметра", "cmd.parameters_import": "Импортировать параметры", "cmd.parameters_list": "Список параметров", + "cmd.parameters_move": "Переместить параметр", "cmd.parameters_rename": "Переименовать параметр", "cmd.parameters_users": "Где используется параметр", "cmd.parts_fastener": "Вставить крепёж", @@ -164,6 +402,16 @@ "cmd.plastic_rest": "Опора", "cmd.plastic_rules": "Список правил пластика", "cmd.plastic_snap_fit": "Защёлка", + "cmd.render_backends": "Рендер-бэкенды", + "cmd.render_cancel": "Отменить рендеринг", + "cmd.render_export": "Экспортировать изображение рендеринга", + "cmd.render_preflight": "Проверить запрос рендеринга", + "cmd.render_scene": "Просмотреть сцену рендеринга", + "cmd.render_settings_apply": "Применить камеру рендеринга", + "cmd.render_settings_get": "Настройки рендеринга", + "cmd.render_settings_set": "Сохранить настройки рендеринга", + "cmd.render_start": "Рендеринг изображения", + "cmd.render_status": "Ход рендеринга", "cmd.select_clear": "Снять выделение", "cmd.sheet_convert": "Преобразовать в листовой металл", "cmd.sheet_export_bend_table": "Экспортировать таблицу гибов", @@ -258,22 +506,21 @@ "cmd.solid_rib": "Ребро жёсткости", "cmd.solid_split_face": "Разделить грань", "cmd.solid_web": "Перегородка", - "cmd.surface_patch": "Заплатка", - "cmd.surface_stitch": "Сшить", - "cmd.surface_thicken": "Утолщить", - "cmd.surface_extrude": "Выдавливание поверхности", - "cmd.surface_revolve": "Вращение поверхности", - "cmd.surface_sweep": "Сдвиг поверхности", - "cmd.surface_loft": "Лофт поверхности", - "cmd.surface_ruled": "Линейчатая поверхность", - "cmd.surface_boundary": "Поверхность по границе", - "cmd.surface_offset": "Смещённая поверхность", "cmd.surface_blend": "Сопряжённая поверхность", + "cmd.surface_boundary": "Поверхность по границе", + "cmd.surface_extrude": "Выдавливание поверхности", "cmd.surface_fillet": "Скругление поверхности", - "cmd.surface_untrim": "Отменить обрезку", - "cmd.surface_unstitch": "Расшить", + "cmd.surface_loft": "Лофт поверхности", + "cmd.surface_offset": "Смещённая поверхность", + "cmd.surface_patch": "Заплатка", "cmd.surface_reverse_normal": "Обратить нормаль", - "cmd.inspect_continuity": "Анализ непрерывности", + "cmd.surface_revolve": "Вращение поверхности", + "cmd.surface_ruled": "Линейчатая поверхность", + "cmd.surface_stitch": "Сшить", + "cmd.surface_sweep": "Сдвиг поверхности", + "cmd.surface_thicken": "Утолщить", + "cmd.surface_unstitch": "Расшить", + "cmd.surface_untrim": "Отменить обрезку", "cmd.timeline_compute_all": "Пересчитать всё", "cmd.timeline_copy": "Копировать операции", "cmd.timeline_dependents": "Зависимые операции", @@ -288,17 +535,41 @@ "cmd.view_apply": "Вернуть именованный вид", "cmd.view_delete": "Удалить именованный вид", "cmd.view_list": "Список именованных видов", + "cmd.view_navigate": "Навигация вида", "cmd.view_rename": "Переименовать именованный вид", "cmd.view_save": "Новый именованный вид", + "command name": "имя команды", + "coupling.gear_1": "Шестерня 1", + "coupling.gear_1_pick": "Шестерня 1 (необязательно)", + "coupling.gear_2": "Шестерня 2", + "coupling.gear_2_pick": "Шестерня 2 (необязательно)", + "coupling.internal": "Внутреннее зацепление", + "coupling.needs_turn_and_slide": "нужны вращающееся и скользящее сопряжения", + "coupling.needs_turns": "нужны два вращающихся сопряжения", + "coupling.not_round": "не круглая грань", + "coupling.nut": "Гайка", + "coupling.picked": "выбрано", + "coupling.pinion": "Шестерня", + "coupling.pinion_pick": "Шестерня (необязательно)", + "coupling.pitch": "Шаг", + "coupling.rack": "Рейка", + "coupling.radius_1": "Радиус 1", + "coupling.radius_2": "Радиус 2", "dialog.custom_axis": "↖ Своя ось", "dialog.edit_title": "ИЗМЕНИТЬ: {title}", "dialog.select": "↖ Выбрать", "dialog.selected_count": "↖ Выбрано: {count}", - "dialog.step": "Шаг", - "dialog.selection_step": "{step} из {total}: Выберите {input}", "dialog.selection_guidance": "Щёлкните поле ввода, чтобы изменить его. Щелчок по выделенному объекту убирает его; Ctrl/Cmd+щелчок тоже переключает. Проверьте предпросмотр и нажмите OK.", + "dialog.selection_step": "{step} из {total}: Выберите {input}", + "dialog.step": "Шаг", "document.save_changes": "Сохранить изменения в {name}?", "document.unsaved_changes": "В {name} есть несохранённые изменения. Если их не сохранить, они будут потеряны.", + "drive.stopped_by_contact": "Остановлено на {value}: {a} прошёл бы сквозь {b}", + "drive.stopped_by_loop": "Остановлено на {value}: контур через {joint} дальше не замыкается", + "drive.unconnected": "Ничего не движется: {part} не соединён ни с чем закреплённым", + "expression, e.g. 25 mm": "выражение, напр. 25 мм", + "fits the face, e.g. M8": "подходит грани, напр. M8", + "from the rule": "из правила", "home.documentation": "Документация", "home.in_this_browser": "в этом браузере", "home.missing": "отсутствует", @@ -312,6 +583,70 @@ "home.report_issue": "Сообщить о проблеме", "home.samples": "Примеры", "home.whats_new": "Что нового", + "install.button_tip": "Установить SolidCraft как приложение: отдельное окно и работа без сети", + "install.dock_1": "Выберите «Файл» › «Добавить в Dock».", + "install.dock_2": "Нажмите «Добавить».", + "install.dock_after": "После этого SolidCraft открывается из Dock в отдельном окне и работает без сети.", + "install.done": "Готово", + "install.home_screen_1": "Нажмите «Поделиться» (в меню …, если кнопки нет на панели).", + "install.home_screen_2": "Выберите «На экран „Домой“».", + "install.home_screen_3": "Нажмите «Добавить».", + "install.home_screen_after": "После этого SolidCraft открывается значком на экране «Домой», без панелей Safari, и работает без сети.", + "install.menu": "Установить приложение…", + "install.steps_intro": "Safari устанавливает веб-приложения через собственные меню:", + "install.title": "Установка SolidCraft", + "joint.from_bodies_hint": "Каждое выбранное тело переходит в свой новый компонент и остаётся на месте.", + "joint.one_body": "Оба выбора на {body}. Выберите второй на другой детали.", + "joint.one_component": "Эти детали - тела одного компонента: {bodies}. Сопряжение двигает один компонент относительно другого, поэтому каждой детали нужен свой компонент.", + "needs two joints": "нужны два сопряжения", + "new configuration": "новая конфигурация", + "new name": "новое имя", + "new parameter": "новый параметр", + "no interference": "нет интерференции", + "no joint that moves yet": "пока нет подвижных сопряжений", + "no picture": "нет картинки", + "pick a hole to seat it, or OK places it at the origin": "выберите отверстие для установки, или OK разместит в начале координат", + "pick one or two vertices, edges or faces": "выберите одну-две вершины, ребра или грани", + "render.background": "Фон сцены", + "render.fit": "Вписать модель", + "render.image_cancel": "Отменить рендеринг", + "render.image_cancelled": "Рендеринг отменён", + "render.image_cancelling": "Отмена", + "render.image_check": "Проверить запрос рендеринга", + "render.image_completed": "Изображение готово к экспорту", + "render.image_encoding": "Кодирование PNG", + "render.image_export": "Экспорт PNG", + "render.image_failed": "Ошибка рендеринга", + "render.image_height": "Высота", + "render.image_help": "Предпросмотр на CPU · PNG · приближённая прозрачность", + "render.image_overwrite": "Заменить существующий файл", + "render.image_preparing": "Подготовка изображения", + "render.image_queued": "Ожидание рендеринга", + "render.image_reduce": "Попробуйте уменьшить изображение или упростить сцену.", + "render.image_running": "Рендеринг изображения", + "render.image_stale": "Используется сцена, сохранённая до последующих изменений.", + "render.image_start": "Начать рендеринг", + "render.image_supported": "Запрос поддерживается; при запуске очередь и пул памяти будут проверены снова.", + "render.image_title": "Рендеринг изображения", + "render.image_too_large": "Превышен предел изображения: 4096 пикселей по стороне и 4 194 304 пикселя всего.", + "render.image_transparent": "Прозрачный фон", + "render.image_unknown": "Состояние рендеринга недоступно", + "render.image_use_largest": "Использовать наибольший размер с этим соотношением сторон:", + "render.image_width": "Ширина", + "render.navigation_help": "Камера управляется так же, как в проектировании (Настройки › Навигация). Сохранение набора записывает текущую камеру.", + "render.opaque_image_summary": "Предпросмотр PNG · непрозрачный PBR · прозрачность через смешивание", + "render.opaque_preview_help": "Непрозрачный PBR и простые цвета; прозрачность через смешивание. Преломление, HDRI и финальный рендер пока недоступны.", + "render.perspective": "Перспективная камера", + "render.preview": "Встроенный предпросмотр", + "render.preview_help": "Растровое затенение и смешанная прозрачность. Преломление, HDRI и финальный рендеринг пока недоступны.", + "render.reload_settings": "Загрузить сохранённые настройки", + "render.restore_camera": "Восстановить сохранённую камеру", + "render.return_design": "Вернуться к проектированию", + "render.save_setup": "Сохранить набор", + "render.setup_name": "Имя набора настроек", + "render.unavailable_preview": "Этот набор запрашивает недоступный профиль предпросмотра.", + "render.unsaved": "Несохранённые изменения предпросмотра", + "render.use_preview": "Использовать встроенный предпросмотр", "sample.bracket.about": "Базовый фланец с краевыми фланцами и кромкой по правилу листового металла 2 мм", "sample.bracket.name": "Кронштейн из листового металла", "sample.enclosure.about": "Тонкостенный бокс с выступом, бобышками под винты, опорой и защёлкой", @@ -324,6 +659,8 @@ "sample.plate.name": "Образец пластины", "sample.vents.about": "Пазы в прямоугольном массиве: число рядов, столбцов и шаг заданы параметрами", "sample.vents.name": "Вентиляционная пластина", + "settings.measure_axis_distances": "Расстояния X/Y/Z", + "settings.measure_axis_distances_help": "Показывать размеры вдоль мировых осей вместе с общим расстоянием, пока открыто окно измерения.", "settings.msaa_applies_on_restart": "Сглаживание вступит в силу при следующем запуске SolidCraft", "settings.msaa_reset": "{setting}: {requested}× не поддерживается этим графическим устройством; теперь {reset}× (поддерживается: {supported}).", "settings.msaa_unsupported": "Не поддерживается этим графическим устройством", @@ -332,6 +669,29 @@ "sketch.degrees_of_freedom": "Степеней свободы: {count}", "sketch.draw_curves": "Рисовать как {linetype}", "sketch.make_selection": "Преобразовать выделение в {linetype}", + "sketch_text.align_center": "По центру", + "sketch_text.align_left": "По левому краю", + "sketch_text.align_right": "По правому краю", + "sketch_text.bold": "Полужирный", + "sketch_text.builtin_font": "{family} (встроенный)", + "sketch_text.font_search": "Поиск шрифтов", + "sketch_text.italic": "Курсив", + "sketch_text.loading_fonts": "Поиск установленных шрифтов…", + "sketch_text.on_path": "Текст следует по траектории: кривая задаёт его положение", + "sketch_text.path_clear": "Снять текст с кривой", + "sketch_text.path_hint": "Кривая эскиза, вдоль которой идёт текст: щёлкните здесь, затем по кривой", + "sketch_text.use_font_file": "Использовать файл шрифта {path}", + "the parts library is not available": "библиотека деталей недоступна", + "timeline.group": "Новая папка операций", + "timeline.move_many": "Переместить объекты шкалы", + "timeline.move_to_group": "Переместить операции в папку", + "timeline.rename_group": "Переименовать папку операций", + "timeline.reorder_many": "Изменить порядок операций", + "timeline.ungroup": "Убрать папки операций", + "to the next face": "до следующей грани", + "toolbar.image": "ИЗОБРАЖЕНИЕ", + "toolbar.render": "РЕНДЕРИНГ", + "toolbar.render_scene": "СЦЕНА", "ui.1_degree_of_freedom": "1 степень свободы", "ui.3d_mouse_speed": "Скорость 3D-мыши", "ui.3d_mouse_windows": "3D-мышь", @@ -345,6 +705,7 @@ "ui.analysis": "Анализ", "ui.angle": "Угол", "ui.angle_decimals": "Знаков после запятой (углы)", + "ui.animateJoint": "Анимировать сопряжение", "ui.animate_view_changes": "Анимировать смену вида", "ui.animation": "Анимация", "ui.animation_speed": "Скорость анимации", @@ -359,6 +720,7 @@ "ui.bodies": "Тела", "ui.box": "Бокс", "ui.break": "Разорвать", + "ui.calibrate": "Калибровать", "ui.cancel": "Отмена", "ui.canvases": "Подложки", "ui.center": "Центр", @@ -368,8 +730,6 @@ "ui.chamfer_type": "Тип фаски", "ui.change_workspace": "Сменить рабочую область", "ui.chord_length": "Длина хорды", - "ui.curvature_g2": "Кривизна (G2)", - "ui.equivalent_radius": "Эквивалентный радиус", "ui.circle": "Окружность", "ui.circular_pattern": "Круговой массив", "ui.clear": "Очистить", @@ -378,28 +738,6 @@ "ui.click_selects_whole_bodies": "Щелчок выделяет тела целиком", "ui.click_then_press_key": "Щёлкните, затем нажмите новую клавишу", "ui.close": "Закрыть", - "ui.material_review.title": "Проверка физических данных материала", - "ui.material_review.scope": "Только кандидат: без назначения и сохранения. Численная проверка не является инженерной сертификацией.", - "ui.material_review.input": "Вставьте карточку материала по схеме 1 (JSON)", - "ui.material_review.review": "Проверить карточку", - "ui.material_review.limit": "Карточка превышает предел ввода 256 КиБ.", - "ui.material_review.unknown": "Неизвестно", - "ui.material_review.properties": "Свойства", - "ui.material_review.conditions": "Указанные условия", - "ui.material_review.source": "Источник", - "ui.material_review.axes": "Локальные оси материала; ориентация тела не назначается.", - "ui.material_review.derived": "Вычисленные изотропные модули", - "ui.material_review.claims": "Источники и лицензии указаны без проверки. Отсутствующие значения остаются неизвестными.", - "ui.material_review.density": "Плотность", - "ui.material_review.elasticity": "Упругость", - "ui.material_review.tensile_strength": "Прочность при растяжении", - "ui.material_review.compressive_strength": "Прочность при сжатии", - "ui.material_review.yield_strength": "Предел текучести", - "ui.material_review.shear_strength": "Прочность при сдвиге", - "ui.material_review.thermal_conductivity": "Теплопроводность", - "ui.material_review.thermal_expansion": "Тепловое расширение", - "ui.material_review.specific_heat": "Удельная теплоёмкость", - "ui.material_review.moisture_unit": "кг воды / кг сухого материала", "ui.coil": "Спираль", "ui.coincident": "Совпадение", "ui.collapse": "Свернуть", @@ -421,6 +759,8 @@ "ui.colour_vision_tritan_tip": "При слабом или отсутствующем восприятии синего", "ui.combine": "Объединение", "ui.coming_later": "появится позже", + "ui.command_done": "{command} — готово", + "ui.command_palette_hint": "Введите команду, напр. {example} — или нажмите S для поиска", "ui.concentric": "Концентричность", "ui.configurations": "Конфигурации", "ui.conic_curve": "Коническая кривая", @@ -439,7 +779,11 @@ "ui.create_sketch": "Создать эскиз", "ui.current": "текущий", "ui.curvature": "Кривизна", + "ui.curvature_g2": "Кривизна (G2)", "ui.curves": "Кривые", + "ui.custom_program": "Другая…", + "ui.custom_program_tip": "Выберите программу-слайсер для добавления в список", + "ui.customizeToolbar": "Настроить панель инструментов…", "ui.cut": "Вырезать", "ui.cylinder": "Цилиндр", "ui.dark": "Тёмная", @@ -448,6 +792,17 @@ "ui.delete": "Удалить", "ui.depth": "Глубина", "ui.design": "Дизайн", + "ui.design_properties.author": "Автор", + "ui.design_properties.description": "Описание", + "ui.design_properties.exports": "Экспорт в STEP, IGES и 3MF записывает эти свойства, если в формате для них есть поле.", + "ui.design_properties.license": "Лицензия", + "ui.design_properties.not_text": "Сохранено не как текст; ввод здесь заменит значение.", + "ui.design_properties.organization": "Организация", + "ui.design_properties.others": "Данные других программ", + "ui.design_properties.others_note": "Хранятся в дизайне без изменений и никогда не экспортируются.", + "ui.design_properties.part_number": "Номер детали", + "ui.design_properties.project": "Проект", + "ui.design_properties.revision": "Редакция", "ui.diameter": "Диаметр", "ui.dimension": "Размер", "ui.direction": "Направление", @@ -460,12 +815,16 @@ "ui.drawing": "Чертёж", "ui.drill_point": "Конус сверла", "ui.edit": "Изменить", + "ui.editJointLimits": "Изменить ограничения сопряжения", "ui.edit_section_analysis": "Изменить анализ сечения", "ui.ellipse": "Эллипс", "ui.end_radius": "Конечный радиус", + "ui.end_scale": "Масштаб в конце", "ui.entities": "Объекты", "ui.equal": "Равенство", + "ui.equivalent_radius": "Эквивалентный радиус", "ui.expand": "Развернуть", + "ui.exportDxf": "Экспорт DXF…", "ui.export_ellipsis": "Экспорт...", "ui.export_ellipsis_keymap": "Экспорт…", "ui.export_keymap_tip": "Сочетания клавиш, избранное панели S и панель инструментов — в файл", @@ -479,15 +838,20 @@ "ui.file": "Файл", "ui.fillet": "Скругление", "ui.filter_commands_or_keys": "Фильтр команд или клавиш", + "ui.findInTimeline": "Найти на шкале", + "ui.findInWindow": "Найти в окне", "ui.finish_sketch": "Завершить эскиз", + "ui.fit": "Вписать", "ui.fix_unfix": "Зафиксировать/Освободить", "ui.flat": "Плоский", "ui.flip": "Перевернуть", + "ui.format": "Формат", "ui.front": "Спереди", "ui.fully_constrained": "Полностью определён", "ui.general": "Общие", "ui.graphics": "Графика", "ui.ground_shadow": "Тень на земле", + "ui.groupSelected": "Группировать выбранное", "ui.heading_add_ins": "НАДСТРОЙКИ", "ui.heading_assemble": "СБОРКА", "ui.heading_box": "БОКС", @@ -519,8 +883,8 @@ "ui.heading_mirror": "ЗЕРКАЛО", "ui.heading_modify": "ИЗМЕНЕНИЕ", "ui.heading_move": "ПЕРЕМЕСТИТЬ", - "ui.heading_offset": "СМЕЩЕНИЕ", "ui.heading_move_copy": "ПЕРЕМЕСТИТЬ/СКОПИРОВАТЬ", + "ui.heading_offset": "СМЕЩЕНИЕ", "ui.heading_offset_plane": "СМЕЩЁННАЯ ПЛОСКОСТЬ", "ui.heading_ok": "OK", "ui.heading_parameters": "ПАРАМЕТРЫ", @@ -528,13 +892,16 @@ "ui.heading_pipe": "ТРУБА", "ui.heading_plane_at_angle": "ПЛОСКОСТЬ ПОД УГЛОМ", "ui.heading_plastic": "ПЛАСТИК", + "ui.heading_position": "ПОЛОЖЕНИЕ", "ui.heading_prepare": "ПОДГОТОВКА", "ui.heading_rectangular_pattern": "ПРЯМОУГОЛЬНЫЙ МАССИВ", "ui.heading_revolve": "ВРАЩЕНИЕ", "ui.heading_right": "СПРАВА", + "ui.heading_save_mesh": "СОХРАНИТЬ КАК МЕШ", "ui.heading_scale": "МАСШТАБ", "ui.heading_section_analysis": "АНАЛИЗ СЕЧЕНИЯ", "ui.heading_select": "ВЫБРАТЬ", + "ui.heading_setup": "НАСТРОЙКА", "ui.heading_sheet_metal": "ЛИСТОВОЙ МЕТАЛЛ", "ui.heading_shell": "ОБОЛОЧКА", "ui.heading_sketch": "ЭСКИЗ", @@ -552,15 +919,22 @@ "ui.heading_utility": "УТИЛИТА", "ui.help": "Справка", "ui.hide": "Скрыть", + "ui.hideAxes": "Скрыть оси", + "ui.hideDimension": "Скрыть размер", + "ui.hideOrigin": "Скрыть начало координат", + "ui.hidePlanes": "Скрыть плоскости", + "ui.hideProfile": "Скрыть профиль", "ui.hole": "Отверстие", "ui.hole_tap_type": "Тип резьбы отверстия", "ui.hole_type": "Тип отверстия", "ui.home": "Главная", + "ui.homeView": "Главный вид", "ui.horizontal_vertical": "Горизонталь/Вертикаль", "ui.import_ellipsis": "Импорт…", "ui.insert": "Вставить", "ui.inspect": "Инспекция", "ui.intersect": "Пересечение", + "ui.isolate": "Изолировать", "ui.join": "Объединить", "ui.joints": "Сопряжения", "ui.keyboard_shortcuts": "Сочетания клавиш", @@ -569,11 +943,37 @@ "ui.light": "Светлая", "ui.line": "Линия", "ui.linetype": "Тип линии", + "ui.lock": "Заблокировать", "ui.loft": "Лофт", "ui.look_at": "Взгляд на", "ui.look_at_anim_desc": "Осевые виды, «Взгляд на», «Главная» и «Вписать»", "ui.manufacture": "Производство", + "ui.material_review.axes": "Локальные оси материала; ориентация тела не назначается.", + "ui.material_review.claims": "Источники и лицензии указаны без проверки. Отсутствующие значения остаются неизвестными.", + "ui.material_review.compressive_strength": "Прочность при сжатии", + "ui.material_review.conditions": "Указанные условия", + "ui.material_review.density": "Плотность", + "ui.material_review.derived": "Вычисленные изотропные модули", + "ui.material_review.elasticity": "Упругость", + "ui.material_review.input": "Вставьте карточку материала по схеме 1 (JSON)", + "ui.material_review.limit": "Карточка превышает предел ввода 256 КиБ.", + "ui.material_review.moisture_unit": "кг воды / кг сухого материала", + "ui.material_review.properties": "Свойства", + "ui.material_review.review": "Проверить карточку", + "ui.material_review.scope": "Только кандидат: без назначения и сохранения. Численная проверка не является инженерной сертификацией.", + "ui.material_review.shear_strength": "Прочность при сдвиге", + "ui.material_review.source": "Источник", + "ui.material_review.specific_heat": "Удельная теплоёмкость", + "ui.material_review.tensile_strength": "Прочность при растяжении", + "ui.material_review.thermal_conductivity": "Теплопроводность", + "ui.material_review.thermal_expansion": "Тепловое расширение", + "ui.material_review.title": "Проверка физических данных материала", + "ui.material_review.unknown": "Неизвестно", + "ui.material_review.yield_strength": "Предел текучести", "ui.measure": "Измерить", + "ui.mesh_format_3mf": "3MF", + "ui.mesh_format_3mf_tagged": "3MF с метками граней", + "ui.mesh_format_stl": "STL", "ui.midpoint": "Середина", "ui.mirror": "Зеркало", "ui.mirror_line": "Линия зеркала", @@ -583,9 +983,13 @@ "ui.named_views": "Именованные виды", "ui.navigation": "Навигация", "ui.needs_design": "{command}: сначала откройте дизайн", + "ui.newSketchGroup": "Новая группа эскизов", "ui.new_body": "Новое тело", "ui.new_design": "Новый дизайн", + "ui.no_slicer_found": "Слайсер не найден", "ui.normal": "Нормаль", + "ui.normalConstruction": "Обычная / Вспомогательная", + "ui.not_a_program": "{path} — не программа, которую можно запустить", "ui.object_type": "Тип объекта", "ui.objects": "Объекты", "ui.offer_to_stand_up_y_up_files": "Предлагать ставить Y-up файлы вертикально", @@ -598,10 +1002,13 @@ "ui.open_recent": "Открыть недавние", "ui.operation": "Операция", "ui.options": "Параметры", + "ui.orbit": "Орбита", "ui.orbit_around": "Вращать вокруг", + "ui.orientation": "Ориентация", "ui.origin": "Начало координат", "ui.palette_points": "Точки", "ui.palette_profile": "Профиль", + "ui.pan": "Панорамирование", "ui.pan_zoom_orbit": "Панорама, масштаб, орбита", "ui.parallel": "Параллельность", "ui.parameters": "Параметры", @@ -610,6 +1017,8 @@ "ui.pattern_on_path": "Массив по траектории", "ui.perpendicular": "Перпендикулярность", "ui.perspective_view": "Перспективный вид", + "ui.pinToShortcuts": "Закрепить в сочетаниях клавиш", + "ui.pinToToolbar": "Закрепить на панели", "ui.pipe": "Труба", "ui.placement": "Размещение", "ui.plane": "Плоскость", @@ -625,6 +1034,7 @@ "ui.profiles": "Профили", "ui.project": "Проецировать", "ui.project_face_edges_sketch": "Проецировать рёбра граней в новые эскизы", + "ui.properties": "Свойства", "ui.quantity": "Количество", "ui.quantity_2": "Количество 2", "ui.quit": "Выход", @@ -634,50 +1044,47 @@ "ui.rectangle": "Прямоугольник", "ui.rectangular_pattern": "Прямоугольный массив", "ui.redo": "Повторить", + "ui.removeFromToolbar": "Убрать с панели", + "ui.removeSection": "Убрать сечение", "ui.render": "Рендер", "ui.renderer": "Рендерер", + "ui.repeat": "Повторить", + "ui.report_a_bug": "Сообщить об ошибке", "ui.reset": "Сбросить", "ui.reset_all": "Сбросить всё", "ui.reset_the_settings_on_this_page": "Сбросить настройки этой страницы", + "ui.restore": "Восстановить", "ui.restore_defaults": "Восстановить по умолчанию", "ui.reverse_zoom_direction": "Обратить направление масштабирования", "ui.revolve": "Вращение", "ui.right": "Справа", "ui.save": "Сохранить", - "ui.heading_save_mesh": "СОХРАНИТЬ КАК МЕШ", - "ui.format": "Формат", - "ui.mesh_format_stl": "STL", - "ui.mesh_format_3mf": "3MF", - "ui.mesh_format_3mf_tagged": "3MF с метками граней", - "ui.send_to_slicer": "Отправить в слайсер", - "ui.slicer": "Слайсер", - "ui.custom_program": "Другая…", - "ui.no_slicer_found": "Слайсер не найден", - "ui.send": "Отправить", - "ui.custom_program_tip": "Выберите программу-слайсер для добавления в список", - "ui.slicer_delete_tip": "{program}\nНажмите Delete, чтобы убрать из списка", - "ui.save_mesh_pick_bodies": "Выберите тела для сохранения", - "ui.save_mesh_no_slicer": "Слайсер не найден: выберите «Другая…» и укажите программу или отключите «Отправить в слайсер»", - "ui.not_a_program": "{path} — не программа, которую можно запустить", - "ui.sent_to_slicer": "Отправлено в {slicer}", - "ui.saved_to": "Сохранено: {path}", - "ui.save_mesh_temp_failed": "Не удалось создать {folder}: {error}", "ui.save_as": "Сохранить как", "ui.save_as_ellipsis": "Сохранить как...", + "ui.save_mesh_no_slicer": "Слайсер не найден: выберите «Другая…» и укажите программу или отключите «Отправить в слайсер»", + "ui.save_mesh_pick_bodies": "Выберите тела для сохранения", + "ui.save_mesh_temp_failed": "Не удалось создать {folder}: {error}", + "ui.saved_to": "Сохранено: {path}", "ui.scale": "Масштаб", - "ui.orientation": "Ориентация", - "ui.twist": "Закрутка", - "ui.end_scale": "Масштаб в конце", - "ui.sweep_turn_with_path": "Поворачивать по траектории", - "ui.sweep_keep_as_drawn": "Как нарисовано", - "ui.sweep_follow_direction": "Следовать направлению", "ui.section_analysis": "Анализ сечения", "ui.select": "Выбрать", + "ui.selectOther": "Выбрать другое…", + "ui.selectTangentChain": "Выбрать касательную цепочку", "ui.select_other_hint": "Выбрать другое: удерживайте левую кнопку на модели (или правый щелчок › Выбрать другое…), чтобы увидеть всё под курсором; повторный щелчок в том же месте выбирает следующий объект.", "ui.selection": "Выделение", + "ui.send": "Отправить", + "ui.send_to_slicer": "Отправить в слайсер", + "ui.sent_to_slicer": "Отправлено в {slicer}", "ui.shell": "Оболочка", "ui.show": "Показать", + "ui.showAll": "Показать всё", + "ui.showAllBodies": "Показать все тела", + "ui.showAxes": "Показать оси", + "ui.showDimension": "Показать размер", + "ui.showOrigin": "Показать начало координат", + "ui.showPlanes": "Показать плоскости", "ui.show_constraints": "Ограничения", + "ui.show_construction_geometries": "Вспомогательная геометрия", "ui.show_dimensions": "Размеры", "ui.show_points": "Показать точки", "ui.show_profile": "Показать профиль", @@ -692,6 +1099,8 @@ "ui.sketch_status": "Статус эскиза", "ui.sketches": "Эскизы", "ui.slice": "Срез", + "ui.slicer": "Слайсер", + "ui.slicer_delete_tip": "{program}\nНажмите Delete, чтобы убрать из списка", "ui.slot": "Паз", "ui.smooth": "Сглаживание", "ui.smooth_wheel_zoom": "Плавное масштабирование колесом", @@ -707,7 +1116,11 @@ "ui.stand_up_tip": "Если файл STEP или IGES открывается с Z вверх, предложить поворот на четверть оборота вокруг X", "ui.start": "Старт", "ui.start_radius": "Начальный радиус", + "ui.suppress": "Подавить", "ui.sweep": "Сдвиг", + "ui.sweep_follow_direction": "Следовать направлению", + "ui.sweep_keep_as_drawn": "Как нарисовано", + "ui.sweep_turn_with_path": "Поворачивать по траектории", "ui.symmetric": "Симметрично", "ui.symmetry": "Симметрия", "ui.system": "Системная", @@ -725,16 +1138,23 @@ "ui.to_object": "До объекта", "ui.top": "Сверху", "ui.torus": "Тор", + "ui.total_angle": "Полный угол", "ui.trackpad_pan_tip": "Жесты тачпада панорамируют (выкл.: масштабируют как колесо); колесо мыши масштабирует, боковое колесо панорамирует вбок, щипок всегда масштабирует", "ui.trim": "Обрезать", + "ui.twist": "Закрутка", "ui.two_finger_scroll_pans": "Прокрутка двумя пальцами панорамирует", "ui.two_sides": "Две стороны", "ui.ui_scale": "Масштаб интерфейса", "ui.undo": "Отменить", + "ui.unground": "Открепить", + "ui.unisolate": "Снять изоляцию", "ui.units": "Единицы", "ui.units_of_new_designs": "Единицы новых дизайнов", + "ui.unlock": "Разблокировать", + "ui.unsuppress": "Восстановить операцию", "ui.untitled": "Без имени", "ui.up_axis_note": "Какая ось направлена вверх в видах (осевые виды, «Главная», «Взгляд на»). Дизайны не меняются.", + "ui.updateToCurrentView": "Обновить до текущего вида", "ui.variable": "Переменный", "ui.view_centre": "Центр вида", "ui.visual_shaded_hidden_edges": "Заполненный с невидимыми рёбрами", @@ -746,427 +1166,7 @@ "ui.y_distance": "Расстояние Y", "ui.y_up": "Y вверх", "ui.z_up": "Z вверх", - "ui.zoom_to_cursor_tip": "Колесо масштабирует к точке под курсором (выкл.: к центру вида)", - "ui.zoom_to_the_cursor": "Масштаб к курсору", - "A new configuration, a copy of the active one": "Новая конфигурация — копия активной", - "About SolidCraft": "О SolidCraft", - "Active": "Активный", - "Active rule": "Активное правило", - "Add": "Добавить", - "Add Key": "Добавить клавишу", - "Add Mid Radius": "Добавить средний радиус", - "Add Row": "Добавить строку", - "All Sketch Points": "Все точки эскиза", - "All open designs": "Все открытые дизайны", - "Allowed expressions, separated by semicolons": "Разрешённые выражения через точку с запятой", - "Also deletes": "Также удаляет", - "Angle 2": "Угол 2", - "Animate": "Анимировать", - "Appearance name": "Имя внешнего вида", - "Applied Radius": "Применённый радиус", - "Apply To": "Применить к", - "Area": "Площадь", - "Attachment": "Привязка", - "BROWSER": "БРАУЗЕР", - "Bend Line Position": "Положение линии гиба", - "Bend Position": "Положение гиба", - "Bend Radius": "Радиус гиба", - "Bends": "Гибы", - "Body": "Тело", - "Bounding box": "Габаритная рамка", - "CSV or JSON: updates existing parameters, adds new ones": "CSV или JSON: обновляет существующие параметры, добавляет новые", - "Capture All Positions": "Зафиксировать все положения", - "Catch Direction": "Направление защёлкивания", - "Cells": "Ячейки", - "Center X": "Центр X", - "Center Y": "Центр Y", - "Center of mass": "Центр масс", - "Chamfer Type": "Тип фаски", - "Check collisions": "Проверить столкновения", - "Checked": "Включено", - "Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.": "Выберите новую плоскость. Геометрия и размеры эскиза останутся неизменными в её двумерных координатах.", - "Close draft": "Закрыть анализ уклонов", - "Collisions": "Столкновения", - "Colour": "Цвет", - "Component1": "Компонент1", - "Configuration": "Конфигурация", - "Configuration rules": "Правила конфигурации", - "Contact": "Контакт", - "Copy all licences": "Копировать все лицензии", - "Copy diagnostic information": "Копировать диагностическую информацию", - "Copy report": "Копировать отчёт", - "Corner Relief": "Разгрузка угла", - "Corner Relief Shape": "Форма разгрузки угла", - "Notch": "Вырез", - "Round": "Круглая", - "Rectangular": "Прямоугольная", - "Tear": "Разрыв", - "Counterbore depth": "Глубина цековки", - "Countersink angle": "Угол зенковки", - "Create Issue — review draft": "Создать Issue — проверить черновик", - "Customize Toolbar": "Настроить панель инструментов", - "Delete all": "Удалить все", - "Delete rule": "Удалить правило", - "Delete the row": "Удалить строку", - "Delete the set": "Удалить набор", - "Delete this parameter": "Удалить этот параметр", - "Density": "Плотность", - "Designs you open or save appear here.": "Здесь появляются открытые и сохранённые дизайны.", - "Determined by To Object. Choose Angle to edit the angular extent.": "Определяется параметром «До объекта». Выберите «Угол», чтобы задать угловой предел.", - "Discard": "Отменить", - "Double-click to rename": "Двойной щелчок — переименовать", - "Drive Joint": "Привод сопряжения", - "Edit Profile Sketch": "Редактировать эскиз профиля", - "Enable rule": "Включить правило", - "Enabled": "Включено", - "Explode": "Разобрать", - "Extents": "Пределы", - "Face attachment lost": "Привязка к грани потеряна", - "Faces / edges / vertices": "Грани / рёбра / вершины", - "Favourite": "Избранное", - "Files from many CAD programs have Y up, so they open lying on their back here (Z up).": "Файлы многих CAD-программ ориентированы Y вверх, поэтому здесь они открываются лёжа на спине (Z вверх).", - "Filter": "Фильтр", - "Find in Browser": "Найти в браузере", - "Copy Error Message": "Скопировать сообщение об ошибке", - "Copy Warning Message": "Скопировать предупреждение", - "Flat size": "Размер развёртки", - "Follow camera (Look At sketches)": "Следовать за камерой (эскизы «Взгляд на»)", - "Font": "Шрифт", - "Full Length": "Полная длина", - "Gap": "Зазор", - "Grid": "Сетка", - "Height": "Высота", - "Home view": "Главный вид", - "In This Design": "В этом дизайне", - "Interferes": "Пересекается", - "Issue title": "Заголовок Issue", - "Joint Origin1": "Точка сопряжения1", - "Keep Tools": "Оставить инструменты", - "Later": "Позже", - "Leave it": "Оставить как есть", - "Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "Устаревшая привязка к грани. Перепривязка к сертифицированной грани создаёт точную привязку.", - "Length": "Длина", - "Length units": "Единицы длины", - "Library": "Библиотека", - "Loop": "Контур", - "Margin": "Отступ", - "Mass": "Масса", - "Material": "Материал", - "Mid Radius": "Средний радиус", - "Modeled": "Смоделировано", - "More toolbar panels": "Другие панели инструментов", - "Motion": "Движение", - "Move Type": "Тип перемещения", - "Move earlier": "Сдвинуть раньше", - "Move later": "Сдвинуть позже", - "Name": "Имя", - "No crash reports.": "Нет отчётов о сбоях.", - "No matching appearances": "Нет подходящих внешних видов", - "Not available yet": "Пока недоступно", - "Opacity": "Непрозрачность", - "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": "Другая сторона", - "Parameter values": "Значения параметров", - "Per Edge": "По каждому ребру", - "Pick the tool bodies": "Выберите тела-инструменты", - "Place at the origin instead": "Разместить в начале координат", - "Playback": "Воспроизведение", - "Position": "Положение", - "Position (0 to 1)": "Положение (от 0 до 1)", - "Position along the edge, 0 at the start end, 1 at the other": "Положение вдоль ребра: 0 — начало, 1 — конец", - "Preview leaves the current design unchanged.": "Предпросмотр не меняет текущий дизайн.", - "RECENT": "НЕДАВНИЕ", - "Radius Fit": "Подобрать радиус", - "Ratio": "Отношение", - "Recover": "Восстановить", - "Recover unsaved design?": "Восстановить несохранённый дизайн?", - "Remove Tools": "Убрать инструменты", - "Remove from list": "Убрать из списка", - "Remove private design details or paths before sharing.": "Перед публикацией удалите личные данные и пути из дизайна.", - "Remove the column": "Удалить столбец", - "Remove the track": "Удалить дорожку", - "Remove this point": "Удалить эту точку", - "Report a bug — review a screenshot and open a GitHub draft": "Сообщить об ошибке — проверьте скриншот и откройте черновик на GitHub", - "Reset Toolbar": "Сбросить панель инструментов", - "Restore the inherited component or physical material appearance": "Вернуть унаследованный внешний вид компонента или физического материала", - "Result": "Результат", - "Retake screenshot": "Сделать скриншот заново", - "Reverse": "Обратить", - "Reverse Direction": "Обратить направление", - "Revert": "Вернуть", - "Revert All Positions": "Вернуть все положения", - "Review the report and screenshot before opening GitHub.": "Проверьте отчёт и скриншот перед открытием GitHub.", - "Rim Edge": "Кромка обода", - "Roll History Marker Here": "Переместить маркер истории сюда", - "Rule": "Правило", - "Saved preview. Geometry is being checked before editing.": "Сохранённый предпросмотр. Геометрия проверяется перед редактированием.", - "Scale factor": "Коэффициент масштаба", - "Search": "Поиск", - "Search commands": "Поиск команд", - "Select bodies (a face picks its body)": "Выберите тела (выбор грани выбирает её тело)", - "Select bodies or faces instead": "Вместо этого выберите тела или грани", - "Selection filter": "Фильтр выделения", - "Semantic faces share their appearance across instances.": "Семантические грани разделяют внешний вид между вхождениями.", - "Shape": "Форма", - "Show Agent Cursor": "Показывать курсор агента", - "Show in folder": "Показать в папке", - "Size": "Размер", - "Sketch plane has no body-face attachment.": "Плоскость эскиза не привязана к грани тела.", - "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft закрылся до сохранения этих дизайнов. Можно открыть последнюю автосохранённую версию.", - "Speed": "Скорость", - "Stand it up": "Поставить вертикально", - "Stand it up: a quarter turn about X, as one Move feature you can undo.": "Поставить вертикально: четверть оборота вокруг X одной операцией «Переместить», которую можно отменить.", - "Stand this part up?": "Поставить эту деталь вертикально?", - "Step": "Шаг", - "Steps": "Шаги", - "Suppressed": "Подавлено", - "Swap Ends": "Поменять концы", - "Tangent Chain": "Касательная цепочка", - "The dashed sketch is a saved plane guide. Select a new face to repair the attachment.": "Пунктирный эскиз — сохранённая подсказка плоскости. Выберите новую грань, чтобы восстановить привязку.", - "The saved author occurrence is missing. Select a valid author placement before rebinding.": "Сохранённое исходное вхождение отсутствует. Выберите корректное исходное положение перед перепривязкой.", - "Then": "Затем", - "These features will be deleted:": "Эти операции будут удалены:", - "These features will fail:": "Эти операции завершатся с ошибкой:", - "This child is shared. Deleting it removes it from 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.": "Эта грань не может обеспечить надёжную привязку. Выберите другую грань или явно используйте фиксированную плоскость.", - "To Offset": "До смещения", - "Tolerance": "Допуск", - "Type": "Тип", - "Updating the preview": "Обновление предпросмотра", - "Use fixed plane": "Использовать фиксированную плоскость", - "VIEW": "ВИД", - "Value": "Значение", - "Volume": "Объём", - "Wall": "Стенка", - "When": "Когда", - "Width": "Ширина", - "Will fail": "Завершится с ошибкой", - "angle, height": "угол, высота", - "command name": "имя команды", - "expression, e.g. 25 mm": "выражение, напр. 25 мм", - "fits the face, e.g. M8": "подходит грани, напр. M8", - "from the rule": "из правила", - "needs two joints": "нужны два сопряжения", - "new configuration": "новая конфигурация", - "new name": "новое имя", - "new parameter": "новый параметр", - "no interference": "нет интерференции", - "no joint that moves yet": "пока нет подвижных сопряжений", - "no picture": "нет картинки", - "pick a hole to seat it, or OK places it at the origin": "выберите отверстие для установки, или OK разместит в начале координат", - "pick one or two vertices, edges or faces": "выберите одну-две вершины, ребра или грани", - "the parts library is not available": "библиотека деталей недоступна", - "to the next face": "до следующей грани", - "Revert Position": "Вернуть положение", - "Construction": "Вспомогательная", - "Faces": "Грани", - "Edges": "Рёбра", - "Vertices": "Вершины", - "Sketch geometry and profiles": "Геометрия и профили эскиза", - "Sketch curves": "Кривые эскиза", - "Sketch points": "Точки эскиза", - "Sketch dimensions": "Размеры эскиза", - "Sketch constraints": "Ограничения эскиза", - "0 turns it off": "0 отключает", - "Show the pointer an AI agent moves (#35)": "Показывать указатель, которым двигается ИИ-агент (#35)", - "Follow the camera (Look At sketches)": "Следовать за камерой (эскизы «Взгляд на»)", - "Flat": "Плоский", - "Save Rule": "Сохранить правило", - "Preview Row": "Строка предпросмотра", - "Add condition": "Добавить условие", - "Apply to selection": "Применить к выделению", - "Remove override": "Убрать переопределение", - "Copy screenshot": "Копировать скриншот", - "Remove screenshot": "Убрать скриншот", - "Use active author placement": "Использовать активное исходное положение", - "Reattach selected face": "Перепривязать выбранную грань", - "Use saved fixed plane": "Использовать сохранённую фиксированную плоскость", - "Use selected face as fixed plane": "Использовать выбранную грань как фиксированную плоскость", - "View navigator": "Навигатор видов", - "Signed axes": "Знаковые оси", - "Cube": "Куб", - "Middle double-click": "Двойной щелчок средней кнопкой", - "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": "Двойной щелчок средней кнопкой в виде: «Главная» (главный вид, кадрирует показанное), «Вписать» (кадрирует, сохраняя ориентацию) или ничего", - "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).": "Выбрать другое: удерживайте левую кнопку на модели (или правый щелчок › Выбрать другое…), чтобы увидеть всё под курсором; повторный щелчок в том же месте выбирает следующий объект. Двойной щелчок средней кнопкой — «Главная» (Настройки › Навигация).", - "cmd.render_backends": "Рендер-бэкенды", - "cmd.view_navigate": "Навигация вида", - "ui.animateJoint": "Анимировать сопряжение", - "ui.calibrate": "Калибровать", - "ui.customizeToolbar": "Настроить панель инструментов…", - "ui.editJointLimits": "Изменить ограничения сопряжения", - "ui.exportDxf": "Экспорт DXF…", - "ui.findInTimeline": "Найти на шкале", - "ui.findInWindow": "Найти в окне", - "ui.fit": "Вписать", - "ui.groupSelected": "Группировать выбранное", - "ui.hideAxes": "Скрыть оси", - "ui.hideDimension": "Скрыть размер", - "ui.hideOrigin": "Скрыть начало координат", - "ui.hidePlanes": "Скрыть плоскости", - "ui.hideProfile": "Скрыть профиль", - "ui.homeView": "Главный вид", - "ui.isolate": "Изолировать", - "ui.lock": "Заблокировать", - "ui.newSketchGroup": "Новая группа эскизов", - "ui.normalConstruction": "Обычная / Вспомогательная", - "ui.orbit": "Орбита", - "ui.heading_position": "ПОЛОЖЕНИЕ", - "ui.pan": "Панорамирование", - "ui.pinToShortcuts": "Закрепить в сочетаниях клавиш", - "ui.pinToToolbar": "Закрепить на панели", - "ui.properties": "Свойства", - "ui.design_properties.project": "Проект", - "ui.design_properties.part_number": "Номер детали", - "ui.design_properties.revision": "Редакция", - "ui.design_properties.author": "Автор", - "ui.design_properties.organization": "Организация", - "ui.design_properties.description": "Описание", - "ui.design_properties.license": "Лицензия", - "ui.design_properties.not_text": "Сохранено не как текст; ввод здесь заменит значение.", - "ui.design_properties.exports": "Экспорт в STEP, IGES и 3MF записывает эти свойства, если в формате для них есть поле.", - "ui.design_properties.others": "Данные других программ", - "ui.design_properties.others_note": "Хранятся в дизайне без изменений и никогда не экспортируются.", - "ui.removeSection": "Убрать сечение", - "ui.removeFromToolbar": "Убрать с панели", - "ui.repeat": "Повторить", - "ui.report_a_bug": "Сообщить об ошибке", - "install.menu": "Установить приложение…", - "install.button_tip": "Установить SolidCraft как приложение: отдельное окно и работа без сети", - "install.title": "Установка SolidCraft", - "install.steps_intro": "Safari устанавливает веб-приложения через собственные меню:", - "install.home_screen_1": "Нажмите «Поделиться» (в меню …, если кнопки нет на панели).", - "install.home_screen_2": "Выберите «На экран „Домой“».", - "install.home_screen_3": "Нажмите «Добавить».", - "install.home_screen_after": "После этого SolidCraft открывается значком на экране «Домой», без панелей Safari, и работает без сети.", - "install.dock_1": "Выберите «Файл» › «Добавить в Dock».", - "install.dock_2": "Нажмите «Добавить».", - "install.dock_after": "После этого SolidCraft открывается из Dock в отдельном окне и работает без сети.", - "install.done": "Готово", - "ui.restore": "Восстановить", - "ui.heading_setup": "НАСТРОЙКА", - "ui.selectOther": "Выбрать другое…", - "ui.selectTangentChain": "Выбрать касательную цепочку", - "ui.showAll": "Показать всё", - "ui.showAllBodies": "Показать все тела", - "ui.showAxes": "Показать оси", - "ui.showDimension": "Показать размер", - "ui.showOrigin": "Показать начало координат", - "ui.showPlanes": "Показать плоскости", - "ui.suppress": "Подавить", - "ui.command_palette_hint": "Введите команду, напр. {example} — или нажмите S для поиска", - "ui.unground": "Открепить", - "ui.unisolate": "Снять изоляцию", - "ui.unlock": "Разблокировать", - "ui.unsuppress": "Восстановить операцию", - "ui.updateToCurrentView": "Обновить до текущего вида", "ui.zoom": "Масштаб", - "ui.command_done": "{command} — готово", - "drive.stopped_by_loop": "Остановлено на {value}: контур через {joint} дальше не замыкается", - "drive.stopped_by_contact": "Остановлено на {value}: {a} прошёл бы сквозь {b}", - "drive.unconnected": "Ничего не движется: {part} не соединён ни с чем закреплённым", - "timeline.group": "Новая папка операций", - "timeline.ungroup": "Убрать папки операций", - "timeline.rename_group": "Переименовать папку операций", - "timeline.move_to_group": "Переместить операции в папку", - "timeline.move_many": "Переместить объекты шкалы", - "timeline.reorder_many": "Изменить порядок операций", - "ui.show_construction_geometries": "Вспомогательная геометрия", - "ui.total_angle": "Полный угол", - "sketch_text.builtin_font": "{family} (встроенный)", - "sketch_text.font_search": "Поиск шрифтов", - "sketch_text.loading_fonts": "Поиск установленных шрифтов…", - "sketch_text.use_font_file": "Использовать файл шрифта {path}", - "sketch_text.bold": "Полужирный", - "sketch_text.italic": "Курсив", - "sketch_text.align_left": "По левому краю", - "sketch_text.align_center": "По центру", - "sketch_text.align_right": "По правому краю", - "sketch_text.path_hint": "Кривая эскиза, вдоль которой идёт текст: щёлкните здесь, затем по кривой", - "sketch_text.path_clear": "Снять текст с кривой", - "Style": "Стиль", - "Alignment": "Выравнивание", - "Letter Spacing": "Межбуквенный интервал", - "Line Spacing": "Межстрочный интервал", - "Path": "Траектория", - "sketch_text.on_path": "Текст следует по траектории: кривая задаёт его положение", - "cmd.material_properties_validate": "Проверить данные физического материала", - "cmd.render_settings_get": "Настройки рендеринга", - "cmd.render_settings_set": "Сохранить настройки рендеринга", - "cmd.render_scene": "Просмотреть сцену рендеринга", - "cmd.render_settings_apply": "Применить камеру рендеринга", - "toolbar.render": "РЕНДЕРИНГ", - "toolbar.render_scene": "СЦЕНА", - "render.preview": "Встроенный предпросмотр", - "render.preview_help": "Растровое затенение и смешанная прозрачность. Преломление, HDRI и финальный рендеринг пока недоступны.", - "render.setup_name": "Имя набора настроек", - "render.background": "Фон сцены", - "render.perspective": "Перспективная камера", - "render.fit": "Вписать модель", - "render.restore_camera": "Восстановить сохранённую камеру", - "render.save_setup": "Сохранить набор", - "render.unsaved": "Несохранённые изменения предпросмотра", - "render.reload_settings": "Загрузить сохранённые настройки", - "render.unavailable_preview": "Этот набор запрашивает недоступный профиль предпросмотра.", - "render.use_preview": "Использовать встроенный предпросмотр", - "render.navigation_help": "Камера управляется так же, как в проектировании (Настройки › Навигация). Сохранение набора записывает текущую камеру.", - "render.return_design": "Вернуться к проектированию", - "render.image_title": "Рендеринг изображения", - "render.image_help": "Предпросмотр на CPU · PNG · приближённая прозрачность", - "render.image_width": "Ширина", - "render.image_height": "Высота", - "render.image_transparent": "Прозрачный фон", - "render.image_check": "Проверить запрос рендеринга", - "render.image_supported": "Запрос поддерживается; при запуске очередь и пул памяти будут проверены снова.", - "render.image_queued": "Ожидание рендеринга", - "render.image_preparing": "Подготовка изображения", - "render.image_running": "Рендеринг изображения", - "render.image_encoding": "Кодирование PNG", - "render.image_cancelling": "Отмена", - "render.image_cancelled": "Рендеринг отменён", - "render.image_completed": "Изображение готово к экспорту", - "render.image_failed": "Ошибка рендеринга", - "render.image_unknown": "Состояние рендеринга недоступно", - "render.image_reduce": "Попробуйте уменьшить изображение или упростить сцену.", - "render.image_too_large": "Превышен предел изображения: 4096 пикселей по стороне и 4 194 304 пикселя всего.", - "render.image_use_largest": "Использовать наибольший размер с этим соотношением сторон:", - "render.image_cancel": "Отменить рендеринг", - "render.image_stale": "Используется сцена, сохранённая до последующих изменений.", - "render.image_start": "Начать рендеринг", - "render.image_overwrite": "Заменить существующий файл", - "render.image_export": "Экспорт PNG", - "cmd.render_preflight": "Проверить запрос рендеринга", - "cmd.render_start": "Рендеринг изображения", - "cmd.render_status": "Ход рендеринга", - "cmd.render_cancel": "Отменить рендеринг", - "cmd.render_export": "Экспортировать изображение рендеринга", - "toolbar.image": "ИЗОБРАЖЕНИЕ", - "appearance.surface_response": "Поведение поверхности", - "appearance.pbr_opaque": "Непрозрачный PBR", - "appearance.metallic": "Металличность", - "appearance.roughness": "Шероховатость", - "appearance.dielectric_ior": "Показатель преломления диэлектрика", - "appearance.pbr_help": "Просмотр поверхности во вкладке Рендер или на PNG изделия. Без преломления и пропускания света.", - "render.opaque_preview_help": "Непрозрачный PBR и простые цвета; прозрачность через смешивание. Преломление, HDRI и финальный рендер пока недоступны.", - "render.opaque_image_summary": "Предпросмотр PNG · непрозрачный PBR · прозрачность через смешивание", - "joint.one_component": "Эти детали - тела одного компонента: {bodies}. Сопряжение двигает один компонент относительно другого, поэтому каждой детали нужен свой компонент.", - "joint.one_body": "Оба выбора на {body}. Выберите второй на другой детали.", - "joint.from_bodies_hint": "Каждое выбранное тело переходит в свой новый компонент и остаётся на месте.", - "coupling.gear_1": "Шестерня 1", - "coupling.gear_2": "Шестерня 2", - "coupling.pinion": "Шестерня", - "coupling.rack": "Рейка", - "coupling.nut": "Гайка", - "coupling.radius_1": "Радиус 1", - "coupling.radius_2": "Радиус 2", - "coupling.internal": "Внутреннее зацепление", - "coupling.pitch": "Шаг", - "coupling.picked": "выбрано", - "coupling.not_round": "не круглая грань", - "coupling.gear_1_pick": "Шестерня 1 (необязательно)", - "coupling.gear_2_pick": "Шестерня 2 (необязательно)", - "coupling.pinion_pick": "Шестерня (необязательно)", - "coupling.needs_turns": "нужны два вращающихся сопряжения", - "coupling.needs_turn_and_slide": "нужны вращающееся и скользящее сопряжения" + "ui.zoom_to_cursor_tip": "Колесо масштабирует к точке под курсором (выкл.: к центру вида)", + "ui.zoom_to_the_cursor": "Масштаб к курсору" } diff --git a/assets/locales/tr.json b/assets/locales/tr.json index 463a44ee6..36798f876 100644 --- a/assets/locales/tr.json +++ b/assets/locales/tr.json @@ -1,15 +1,270 @@ { - "Send your report on GitHub": "Raporunuzu GitHub üzerinden gönderin", + "0 turns it off": "0 değeri kapatır", "1. Open GitHub draft below, then paste the report copied to your clipboard.": "1. Aşağıdaki GitHub taslağını açın, ardından panoya kopyalanan raporu yapıştırın.", "1. Open GitHub draft below. Your title and report will be filled in.": "1. Aşağıdaki GitHub taslağını açın. Başlığınız ve raporunuz otomatik olarak doldurulur.", "2. Attach your screenshot: copy and paste it, or save and upload the PNG.": "2. Ekran görüntüsünü ekleyin: kopyalayıp yapıştırın veya PNG olarak kaydedip yükleyin.", "3. Click Submit new issue on GitHub to send your report.": "3. Raporu göndermek için GitHub'da Submit new issue düğmesine tıklayın.", - "nav.touchpad.label": "Dokunmatik yüzey", - "nav.touchpad.help": "Kaydırmak için Shift tuşunu basılı tutun ve imleci hareket ettirin; Alt/Option ile döndürün. Fare tuşu gerekmez. Dikey kaydırma yakınlaştırır.", - "nav.touchpad.orbit": "Döndür (Alt/Option tuşunu basılı tutup hareket ettirin; fare tuşu olmadan)", - "nav.touchpad.pan": "Kaydır (Shift tuşunu basılı tutup hareket ettirin; fare tuşu olmadan)", - "nav.touchpad.zoom": "Yakınlaştır (dikey kaydırın veya parmaklarınızı açıp kapatın)", - "nav.touchpad.scroll": "Dokunmatik yüzey yakınlaştırmak için dikey kaydırmayı kullanır. İki parmakla kaydırma diğer ön ayarlar için kayıtlı kalır.", + "A new configuration, a copy of the active one": "Etkin konfigürasyonun kopyası olan yeni bir konfigürasyon", + "AI": "AI", + "About SolidCraft": "SolidCraft hakkında", + "Active": "Etkin", + "Active rule": "Etkin kural", + "Add": "Ekle", + "Add Key": "Tuş ekle", + "Add Mid Radius": "Ara yarıçap ekle", + "Add Row": "Satır ekle", + "Add condition": "Koşul ekle", + "Alignment": "Hizalama", + "All Sketch Points": "Tüm eskiz noktaları", + "All open designs": "Tüm açık tasarımlar", + "Allowed expressions, separated by semicolons": "Noktalı virgülle ayrılmış izin verilen ifadeler", + "Also deletes": "Bunları da siler", + "Angle 2": "Açı 2", + "Animate": "Canlandır", + "Appearance name": "Görünüm adı", + "Applied Radius": "Uygulanan yarıçap", + "Apply To": "Uygulama hedefi", + "Apply to selection": "Seçime uygula", + "Arc length": "Yay uzunluğu", + "Area": "Alan", + "Attachment": "Bağlama", + "BROWSER": "TARAYICI", + "Bend Line Position": "Büküm çizgisi konumu", + "Bend Position": "Büküm konumu", + "Bend Radius": "Büküm yarıçapı", + "Bends": "Bükümler", + "Body": "Gövde", + "Bounding box": "Sınırlayıcı kutu", + "CSV or JSON: updates existing parameters, adds new ones": "CSV veya JSON: mevcut parametreleri günceller, yenilerini ekler", + "Capture All Positions": "Tüm konumları yakala", + "Catch Direction": "Yakalama yönü", + "Cells": "Hücreler", + "Center X": "Merkez X", + "Center Y": "Merkez Y", + "Center of mass": "Kütle merkezi", + "Centre to centre": "Merkezden merkeze", + "Chamfer Type": "Pah türü", + "Check collisions": "Çarpışmaları kontrol et", + "Checked": "Kontrol edildi", + "Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.": "Yeni bir düzlem seçin. Eskiz geometrisi ve ölçüler, iki boyutlu koordinatlarında değişmeden kalır.", + "Circumference": "Çevre", + "Close draft": "Taslağı kapat", + "Collisions": "Çarpışmalar", + "Colour": "Renk", + "Component1": "Bileşen1", + "Configuration": "Konfigürasyon", + "Configuration rules": "Konfigürasyon kuralları", + "Construction": "Yapı çizgisi", + "Contact": "Temas", + "Copy Error Message": "Hata mesajını kopyala", + "Copy Warning Message": "Uyarı mesajını kopyala", + "Copy all licences": "Tüm lisansları kopyala", + "Copy diagnostic information": "Tanılama bilgilerini kopyala", + "Copy report": "Raporu kopyala", + "Copy screenshot": "Ekran görüntüsünü kopyala", + "Corner Relief Shape": "Köşe boşaltma şekli", + "Counterbore depth": "Düz havşa derinliği", + "Countersink angle": "Konik havşa açısı", + "Create Issue — review draft": "Sorun oluştur — taslağı gözden geçirin", + "Cube": "Küp", + "Customize Toolbar": "Araç çubuğunu özelleştir", + "Delete all": "Tümünü sil", + "Delete rule": "Kuralı sil", + "Delete the row": "Satırı sil", + "Delete the set": "Kümeyi sil", + "Delete this parameter": "Bu parametreyi sil", + "Density": "Yoğunluk", + "Designs you open or save appear here.": "Açtığınız veya kaydettiğiniz tasarımlar burada görünür.", + "Determined by To Object. Choose Angle to edit the angular extent.": "Nesneye kadar seçeneğiyle belirlenir. Açısal kapsamı düzenlemek için Açı seçeneğini seçin.", + "Discard": "At", + "Double-click to rename": "Yeniden adlandırmak için çift tıklayı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": "Görünümde orta tuşla çift tıklama: Başlangıç (gösterileni çerçeveleyen başlangıç görünümü), Sığdır (yönü koruyarak gösterileni çerçeveler) veya hiçbir şey", + "Drive Joint": "Bağlantıyı tahrik et", + "Edges": "Kenarlar", + "Edit Profile Sketch": "Profil eskizini düzenle", + "Enable rule": "Kuralı etkinleştir", + "Enabled": "Etkin", + "Explode": "Patlat", + "Extents": "Kapsamlar", + "Face": "Yüz", + "Face attachment lost": "Yüze bağlama kayboldu", + "Faces": "Yüzler", + "Faces / edges / vertices": "Yüzler / kenarlar / köşe noktaları", + "Favourite": "Favori", + "Files from many CAD programs have Y up, so they open lying on their back here (Z up).": "Birçok CAD programının dosyalarında Y yukarıyı gösterir; bu yüzden burada (Z yukarı) sırtüstü yatar hâlde açılırlar.", + "Filter": "Filtre", + "Find in Browser": "Tarayıcıda bul", + "Flat": "Düz", + "Flat size": "Açınım boyutu", + "Follow camera (Look At sketches)": "Kamera takibi (eskizlerde Bak)", + "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", + "Holes (edges on them)": "Delikler (kenarları)", + "Home view": "Başlangıç görünümü", + "In This Design": "Bu tasarımda", + "In place (surfaces)": "Yerinde (yüzeyler)", + "Inside": "İç", + "Interferes": "Girişim var", + "Issue title": "Sorun başlığı", + "Joint Origin1": "Bağlantı orijini1", + "Keep Tools": "Araçları koru", + "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.", + "Length": "Uzunluk", + "Length units": "Uzunluk birimleri", + "Letter Spacing": "Harf aralığı", + "Library": "Kitaplık", + "Line Spacing": "Satır aralığı", + "Loop": "Döngü", + "Margin": "Kenar boşluğu", + "Mass": "Kütle", + "Material": "Malzeme", + "Max": "Maks", + "Mid Radius": "Ara yarıçap", + "Middle double-click": "Orta tuşla çift tıklama", + "Min": "Min", + "Mitre": "Gönye", + "Modeled": "Modellenmiş", + "More toolbar panels": "Diğer araç çubuğu panelleri", + "Motion": "Hareket", + "Move Type": "Taşıma türü", + "Move earlier": "Öne al", + "Move later": "Sonraya al", + "Name": "Ad", + "No crash reports.": "Çökme raporu yok.", + "No matching appearances": "Eşleşen görünüm yok", + "None": "Hiçbiri", + "Not available yet": "Henüz kullanılamıyor", + "Opacity": "Opaklık", + "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", + "Outside": "Dış", + "Overall length": "Toplam uzunluk", + "Parameter values": "Parametre değerleri", + "Path": "Yol", + "Per Edge": "Kenar başına", + "Pick the tool bodies": "Araç gövdelerini seçin", + "Picked": "Seçilenler", + "Place at the origin instead": "Bunun yerine orijine yerleştir", + "Playback": "Oynatma", + "Position": "Konum", + "Position (0 to 1)": "Konum (0 ile 1 arası)", + "Position along the edge, 0 at the start end, 1 at the other": "Kenar boyunca konum: başlangıç ucunda 0, diğer uçta 1", + "Preview Row": "Satırı önizle", + "Preview leaves the current design unchanged.": "Önizleme geçerli tasarımı değiştirmez.", + "Profiles/Curves": "Profiller/Eğriler", + "RECENT": "SON KULLANILANLAR", + "RULED SURFACE": "REGLE YÜZEY", + "Radius Fit": "Yarıçap uydurma", + "Ratio": "Oran", + "Reattach selected face": "Seçili yüze yeniden bağla", + "Recover": "Kurtar", + "Recover unsaved design?": "Kaydedilmemiş tasarım kurtarılsın mı?", + "Reference face": "Referans yüzü", + "Remove Tools": "Araçları kaldır", + "Remove from list": "Listeden kaldır", + "Remove override": "Geçersiz kılmayı kaldır", + "Remove private design details or paths before sharing.": "Paylaşmadan önce özel tasarım ayrıntılarını veya dosya yollarını kaldırın.", + "Remove screenshot": "Ekran görüntüsünü kaldır", + "Remove the column": "Sütunu kaldır", + "Remove the track": "İzi kaldır", + "Remove this point": "Bu noktayı kaldır", + "Report a bug — review a screenshot and open a GitHub draft": "Hata bildir — ekran görüntüsünü kontrol edin ve bir GitHub taslağı açın", + "Reset Toolbar": "Araç çubuğunu sıfırla", + "Restore outer boundary": "Dış sınırı geri yükle", + "Restore the inherited component or physical material appearance": "Bileşenden veya fiziksel malzemeden devralınan görünümü geri yükle", + "Result": "Sonuç", + "Retake screenshot": "Ekran görüntüsünü yeniden al", + "Reverse": "Ters çevir", + "Reverse Direction": "Yönü ters çevir", + "Revert": "Geri al", + "Revert All Positions": "Tüm konumları geri al", + "Revert Position": "Konumu geri al", + "Review the report and screenshot before opening GitHub.": "GitHub'ı açmadan önce raporu ve ekran görüntüsünü gözden geçirin.", + "Rim Edge": "Ağız kenarı", + "Roll History Marker Here": "Geçmiş işaretçisini buraya taşı", + "Round": "Yuvarlak", + "Rule": "Kural", + "Save Rule": "Kuralı kaydet", + "Saved preview. Geometry is being checked before editing.": "Kaydedilmiş önizleme. Düzenlemeden önce geometri kontrol ediliyor.", + "Scale factor": "Ölçek faktörü", + "Search": "Ara", + "Search commands": "Komutlarda ara", + "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).": "Diğerini seç: İmlecin altındaki her şeyi listelemek için sol tuşu model üzerinde hareket ettirmeden basılı tutun (veya sağ tık › Diğerini seç…); oradaki bir sonraki öğeyi seçmek için aynı noktaya tekrar tıklayın. Başlangıç görünümüne dönmek için orta tuşla çift tıklayın (Ayarlar › Gezinme).", + "Select bodies (a face picks its body)": "Gövdeleri seçin (bir yüz kendi gövdesini seçer)", + "Select bodies or faces instead": "Bunun yerine gövde veya yüz seçin", + "Selection filter": "Seçim filtresi", + "Semantic faces share their appearance across instances.": "Anlamsal yüzler görünümlerini örnekler arasında paylaşır.", + "Send your report on GitHub": "Raporunuzu GitHub üzerinden gönderin", + "Shape": "Şekil", + "Show Agent Cursor": "Ajan imlecini göster", + "Show in folder": "Klasörde göster", + "Show the pointer an AI agent moves (#35)": "Bir AI ajanının hareket ettirdiği imleci göster (#35)", + "Signed axes": "İşaretli eksenler", + "Size": "Boyut", + "Sketch constraints": "Eskiz kısıtlamaları", + "Sketch curves": "Eskiz eğrileri", + "Sketch dimensions": "Eskiz ölçüleri", + "Sketch geometry and profiles": "Eskiz geometrisi ve profiller", + "Sketch plane has no body-face attachment.": "Eskiz düzleminin bir gövde yüzüne bağlaması yok.", + "Sketch points": "Eskiz noktaları", + "Slot width": "Yuva genişliği", + "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft bu tasarımlar kaydedilmeden önce kapandı. Son otomatik kayıtları açılabilir.", + "Speed": "Hız", + "Stand it up": "Dik çevir", + "Stand it up: a quarter turn about X, as one Move feature you can undo.": "Dik çevir: X etrafında çeyrek tur; geri alınabilen tek bir Taşı özelliği olarak eklenir.", + "Stand this part up?": "Bu parça dik çevrilsin mi?", + "Step": "Adım", + "Steps": "Adımlar", + "Style": "Stil", + "Suppressed": "Bastırılmış", + "Swap Ends": "Uçları değiştir", + "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.", + "Then": "Sonra", + "These features will be deleted:": "Şu özellikler silinecek:", + "These features will fail:": "Şu özellikler başarısız olacak:", + "Thickness Outside": "Dış kalınlık", + "Thin": "İnce cidarlı", + "Thin Extrude": "İnce cidarlı ekstrüzyon", + "This child is shared. Deleting it removes it from every copy of its parent.": "Bu alt öğe paylaşılıyor. Silindiğinde üst öğesinin tüm kopyalarından kaldırılır.", + "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", + "Tolerance": "Tolerans", + "Type": "Tür", + "UNTRIM": "KIRPMAYI KALDIR", + "Updating the preview": "Önizleme güncelleniyor", + "Use active author placement": "Etkin kaynak yerleşimini kullan", + "Use fixed plane": "Sabit düzlem kullan", + "Use saved fixed plane": "Kaydedilmiş sabit düzlemi kullan", + "Use selected face as fixed plane": "Seçili yüzü sabit düzlem olarak kullan", + "VIEW": "GÖRÜNÜM", + "Value": "Değer", + "Vertices": "Köşe noktaları", + "View navigator": "Görünüm gezgini", + "Volume": "Hacim", + "Wall": "Cidar", + "Wall Location": "Cidar konumu", + "Wall Thickness": "Et kalınlığı", + "When": "Eğer", + "Width": "Genişlik", + "Will fail": "Başarısız olacak", + "angle, height": "açı, yükseklik", + "appearance.dielectric_ior": "Dielektrik kırılma indisi", + "appearance.metallic": "Metaliklik", + "appearance.pbr_help": "Bu yüzeyi Render'da veya bir ürün PNG'sinde görüntüleyin. Kırılma veya geçirgenlik yok.", + "appearance.pbr_opaque": "Opak PBR", + "appearance.roughness": "Pürüzlülük", + "appearance.surface_response": "Yüzey davranışı", "browser.body_name": "Gövde {number}", "browser.component_name": "Bileşen {number}", "browser.parameters": "Parametreler ({count})", @@ -36,7 +291,6 @@ "cmd.component_capture_position": "Konumu yakala", "cmd.component_create": "Yeni bileşen", "cmd.component_delete": "Bileşeni sil", - "cmd.component_unlock": "İçeriğin kilidini aç", "cmd.component_from_bodies": "Gövdelerden bileşen oluştur", "cmd.component_insert_design": "Tasarım ekle", "cmd.component_links": "Bağları listele", @@ -47,6 +301,7 @@ "cmd.component_properties": "Bileşenin fiziksel özellikleri", "cmd.component_rename": "Bileşeni yeniden adlandır", "cmd.component_revert_position": "Konumu geri al", + "cmd.component_unlock": "İçeriğin kilidini aç", "cmd.component_update_links": "Bağları güncelle", "cmd.config_activate": "Konfigürasyonu etkinleştir", "cmd.config_column": "Konfigürasyon sütunu", @@ -88,10 +343,10 @@ "cmd.doc_recovery_discard": "Kurtarılan tasarımı at", "cmd.doc_recovery_list": "Kurtarılabilir tasarımlar", "cmd.document_inspect": "Tasarımı incele", - "cmd.document_units": "Tasarımın birimlerini değiştir", "cmd.document_metadata": "Tasarım özellikleri", - "cmd.document_metadata_set": "Tasarım özelliklerini değiştir", "cmd.document_metadata_remove": "Tasarım özelliğini kaldır", + "cmd.document_metadata_set": "Tasarım özelliklerini değiştir", + "cmd.document_units": "Tasarımın birimlerini değiştir", "cmd.edit_checkpoint": "Kontrol noktası", "cmd.edit_restore_checkpoint": "Kontrol noktasını geri yükle", "cmd.engine_commands": "Komutları listele", @@ -109,6 +364,7 @@ "cmd.inspect_accessibility": "Erişilebilirlik analizi", "cmd.inspect_center_of_mass": "Kütle merkezi", "cmd.inspect_compare": "Gövdeleri karşılaştır", + "cmd.inspect_continuity": "Süreklilik kontrolü", "cmd.inspect_curvature_comb": "Eğrilik tarağı analizi", "cmd.inspect_curvature_map": "Eğrilik haritası analizi", "cmd.inspect_draft": "Koniklik analizi", @@ -128,11 +384,16 @@ "cmd.joint_origin": "Bağlantı orijini", "cmd.joint_rigid_group": "Rijit grup", "cmd.joint_solve": "Bağlantıları çöz", + "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", "cmd.material_assign": "Fiziksel malzeme", "cmd.material_create": "Yeni fiziksel malzeme", "cmd.material_delete": "Fiziksel malzemeyi sil", "cmd.material_edit": "Fiziksel malzemeyi düzenle", "cmd.material_list": "Malzemeleri listele", + "cmd.material_properties_directional": "Yöne bağlı elastisite modülü", + "cmd.material_properties_validate": "Fiziksel malzeme verilerini kontrol et", "cmd.mesh_convert": "Ağı dönüştür", "cmd.model_edges": "Kenarları listele", "cmd.model_faces": "Yüzleri listele", @@ -153,10 +414,10 @@ "cmd.parameters_delete": "Parametreyi sil", "cmd.parameters_export": "Parametreleri dışa aktar", "cmd.parameters_favorite": "Favori parametre", - "cmd.parameters_move": "Parametreyi taşı", "cmd.parameters_graph": "Parametre grafiği", "cmd.parameters_import": "Parametreleri içe aktar", "cmd.parameters_list": "Parametreleri listele", + "cmd.parameters_move": "Parametreyi taşı", "cmd.parameters_rename": "Parametreyi yeniden adlandır", "cmd.parameters_users": "Parametre kullanımları", "cmd.parts_fastener": "Bağlantı elemanı ekle", @@ -170,6 +431,16 @@ "cmd.plastic_rest": "Dayanak", "cmd.plastic_rules": "Plastik kurallarını listele", "cmd.plastic_snap_fit": "Geçmeli bağlantı", + "cmd.render_backends": "Render arka uçları", + "cmd.render_cancel": "Render'ı iptal et", + "cmd.render_export": "PNG dışa aktar", + "cmd.render_preflight": "Render isteğini kontrol et", + "cmd.render_scene": "Render sahnesini incele", + "cmd.render_settings_apply": "Render kamerasını uygula", + "cmd.render_settings_get": "Render ayarları", + "cmd.render_settings_set": "Render ayarlarını kaydet", + "cmd.render_start": "Resmi render et", + "cmd.render_status": "Render ilerlemesi", "cmd.select_clear": "Seçimi temizle", "cmd.sheet_convert": "Sac metale dönüştür", "cmd.sheet_export_bend_table": "Büküm tablosunu dışa aktar", @@ -265,22 +536,21 @@ "cmd.solid_rib": "Nervür", "cmd.solid_split_face": "Yüzü böl", "cmd.solid_web": "Ağ nervürü", - "cmd.surface_patch": "Yama", - "cmd.surface_stitch": "Dikiş", - "cmd.surface_thicken": "Kalınlaştır", - "cmd.surface_extrude": "Yüzey ekstrüzyonu", - "cmd.surface_revolve": "Yüzey döndürme", - "cmd.surface_sweep": "Yüzey süpürme", - "cmd.surface_loft": "Yüzey loftu", - "cmd.surface_ruled": "Regle yüzey", - "cmd.surface_boundary": "Sınır yüzeyi", - "cmd.surface_offset": "Ofset yüzey", "cmd.surface_blend": "Geçiş yüzeyi", + "cmd.surface_boundary": "Sınır yüzeyi", + "cmd.surface_extrude": "Yüzey ekstrüzyonu", "cmd.surface_fillet": "Yüzey yuvarlatma", - "cmd.surface_untrim": "Kırpmayı kaldır", - "cmd.surface_unstitch": "Dikişi aç", + "cmd.surface_loft": "Yüzey loftu", + "cmd.surface_offset": "Ofset yüzey", + "cmd.surface_patch": "Yama", "cmd.surface_reverse_normal": "Normali ters çevir", - "cmd.inspect_continuity": "Süreklilik kontrolü", + "cmd.surface_revolve": "Yüzey döndürme", + "cmd.surface_ruled": "Regle yüzey", + "cmd.surface_stitch": "Dikiş", + "cmd.surface_sweep": "Yüzey süpürme", + "cmd.surface_thicken": "Kalınlaştır", + "cmd.surface_unstitch": "Dikişi aç", + "cmd.surface_untrim": "Kırpmayı kaldır", "cmd.timeline_add": "Kaydedilmiş özellik ekle", "cmd.timeline_compute_all": "Tümünü hesapla", "cmd.timeline_copy": "Özellikleri kopyala", @@ -297,18 +567,26 @@ "cmd.view_apply": "Adlandırılmış görünümü geri yükle", "cmd.view_delete": "Adlandırılmış görünümü sil", "cmd.view_list": "Adlandırılmış görünümleri listele", + "cmd.view_navigate": "Görünümde gezin", "cmd.view_rename": "Adlandırılmış görünümü yeniden adlandır", "cmd.view_save": "Yeni adlandırılmış görünüm", + "command name": "komut adı", "dialog.computing": "Hesaplanıyor… {seconds} sn", "dialog.custom_axis": "↖ Özel eksen", "dialog.edit_title": "{title} düzenleniyor", "dialog.select": "↖ Seç", "dialog.selected_count": "↖ {count} seçildi", - "dialog.step": "Adım", - "dialog.selection_step": "{step}/{total}: {input} seçin", "dialog.selection_guidance": "Değiştirmek için bir girdi seçin. Kaldırmak için seçili nesnelere tıklayın; Ctrl/Cmd+tıklama ile de seçime ekleyip çıkarabilirsiniz. Önizlemeyi kontrol edin ve ardından OK'e basın.", + "dialog.selection_step": "{step}/{total}: {input} seçin", + "dialog.step": "Adım", "document.save_changes": "{name} içindeki değişiklikler kaydedilsin mi?", "document.unsaved_changes": "{name} kaydedilmemiş değişiklikler içeriyor. Kaydetmezseniz bunlar kaybolur.", + "drive.stopped_by_contact": "{value} değerinde durdu: {a} ile {b} iç içe geçerdi", + "drive.stopped_by_loop": "{value} değerinde durdu: {joint} üzerinden geçen döngü daha fazla kapatılamıyor", + "drive.unconnected": "Hiçbir şey hareket etmiyor: {part} sabitlenmiş hiçbir parçaya bağlı değil", + "expression, e.g. 25 mm": "ifade, ör. 25 mm", + "fits the face, e.g. M8": "yüze uyar, ör. M8", + "from the rule": "kuraldan", "home.documentation": "Belgeler", "home.in_this_browser": "bu tarayıcıda", "home.missing": "eksik", @@ -322,6 +600,76 @@ "home.report_issue": "Sorun bildir", "home.samples": "Örnekler", "home.whats_new": "Yenilikler", + "install.button_tip": "SolidCraft'ı uygulama olarak yükleyin: kendi penceresinde açılır ve çevrimdışı da çalışır", + "install.dock_1": "Dosya › Dock'a Ekle'yi seçin.", + "install.dock_2": "“Ekle” düğmesine tıklayın.", + "install.dock_after": "SolidCraft daha sonra Dock'tan kendi penceresinde açılır ve çevrimdışı da çalışır.", + "install.done": "Bitti", + "install.home_screen_1": "“Paylaş” düğmesine dokunun (araç çubuğunda değilse … menüsünde).", + "install.home_screen_2": "“Ana Ekrana Ekle” seçeneğini seçin.", + "install.home_screen_3": "“Ekle” düğmesine dokunun.", + "install.home_screen_after": "SolidCraft daha sonra ana ekrandaki simgesinden, Safari çubukları olmadan açılır ve çevrimdışı da çalışır.", + "install.menu": "Uygulamayı yükle…", + "install.steps_intro": "Safari web uygulamalarını kendi menüleri üzerinden yükler:", + "install.title": "SolidCraft'ı yükle", + "joint.from_bodies_hint": "Seçilen her gövde kendi yeni bileşenine konur ve bulunduğu yerde kalır.", + "joint.one_body": "Her iki seçim de {body} üzerinde. İkincisini başka bir parçada seçin.", + "joint.one_component": "Bu parçalar tek bir bileşenin gövdeleridir: {bodies}. Bir bağlantı bir bileşeni diğerine göre hareket ettirir, bu nedenle her parçanın kendi bileşeni olması gerekir.", + "nav.touchpad.help": "Kaydırmak için Shift tuşunu basılı tutun ve imleci hareket ettirin; Alt/Option ile döndürün. Fare tuşu gerekmez. Dikey kaydırma yakınlaştırır.", + "nav.touchpad.label": "Dokunmatik yüzey", + "nav.touchpad.orbit": "Döndür (Alt/Option tuşunu basılı tutup hareket ettirin; fare tuşu olmadan)", + "nav.touchpad.pan": "Kaydır (Shift tuşunu basılı tutup hareket ettirin; fare tuşu olmadan)", + "nav.touchpad.scroll": "Dokunmatik yüzey yakınlaştırmak için dikey kaydırmayı kullanır. İki parmakla kaydırma diğer ön ayarlar için kayıtlı kalır.", + "nav.touchpad.zoom": "Yakınlaştır (dikey kaydırın veya parmaklarınızı açıp kapatın)", + "needs two joints": "iki bağlantı gerektirir", + "new configuration": "yeni konfigürasyon", + "new name": "yeni ad", + "new parameter": "yeni parametre", + "no interference": "girişim yok", + "no joint that moves yet": "henüz hareket eden bir bağlantı yok", + "no picture": "resim yok", + "pick a hole to seat it, or OK places it at the origin": "yerleştirmek için bir delik seçin veya OK ile orijine yerleştirin", + "pick one or two vertices, edges or faces": "bir veya iki köşe noktası, kenar ya da yüz seçin", + "render.background": "Sahne arka planı", + "render.fit": "Ürünü sığdır", + "render.image_cancel": "Render'ı iptal et", + "render.image_cancelled": "Render iptal edildi", + "render.image_cancelling": "İptal ediliyor", + "render.image_check": "Render isteğini kontrol et", + "render.image_completed": "Resim dışa aktarmaya hazır", + "render.image_encoding": "PNG kodlanıyor", + "render.image_export": "PNG dışa aktar", + "render.image_failed": "Render başarısız", + "render.image_height": "Yükseklik", + "render.image_help": "CPU önizleme resmi · PNG · yaklaşık saydamlık", + "render.image_overwrite": "Mevcut dosyanın üzerine yaz", + "render.image_preparing": "Resim hazırlanıyor", + "render.image_queued": "Render için sırada bekliyor", + "render.image_reduce": "Daha küçük bir resim veya daha basit bir sahne deneyin.", + "render.image_running": "Resim render ediliyor", + "render.image_stale": "Bu resim, sonraki değişikliklerden önceki sahneyi kullanıyor.", + "render.image_start": "Render'ı başlat", + "render.image_supported": "Render isteği destekleniyor; kuyruk ve bellek, başlatılırken yeniden kontrol edilir.", + "render.image_title": "Resmi render et", + "render.image_too_large": "Resim sınırının üzerinde: kenar başına 4096 piksel ve toplam 4.194.304 piksel.", + "render.image_transparent": "Saydam arka plan", + "render.image_unknown": "Render durumu kullanılamıyor", + "render.image_use_largest": "Bu en-boy oranıyla en büyük boyutu kullan:", + "render.image_width": "Genişlik", + "render.navigation_help": "Kamera, tasarım modundaki gibi hareket eder (Ayarlar › Gezinme). Kurulumu kaydettiğinizde geçerli kamera kaydedilir.", + "render.opaque_image_summary": "Önizleme PNG · opak PBR · harmanlanmış saydamlık", + "render.opaque_preview_help": "Opak PBR ve düz renkler; saydamlık harmanlanarak gösterilir. Kırılma, HDRI ve son render henüz kullanılamıyor.", + "render.perspective": "Perspektif kamera", + "render.preview": "Yerleşik önizleme", + "render.preview_help": "Harmanlanmış saydamlıkla raster görüntü. Kırılma, HDRI ve son render henüz kullanılamıyor.", + "render.reload_settings": "Kaydedilmiş ayarları yükle", + "render.restore_camera": "Kaydedilmiş kamerayı yükle", + "render.return_design": "Tasarıma dön", + "render.save_setup": "Kurulumu kaydet", + "render.setup_name": "Kurulumun adı", + "render.unavailable_preview": "Bu kurulum, kullanılamayan bir önizleme profili gerektiriyor.", + "render.unsaved": "Kaydedilmemiş önizleme değişiklikleri", + "render.use_preview": "Yerleşik önizlemeyi kullan", "sample.bracket.about": "2 mm sac metal kuralına göre kenar flanşları ve bir kenet içeren taban flanşı", "sample.bracket.name": "Sac metal köşebent", "sample.enclosure.about": "Dudak, vida göbekleri, dayanak ve geçmeli bağlantı içeren, içi boşaltılmış blok", @@ -334,14 +682,39 @@ "sample.plate.name": "Örnek plaka", "sample.vents.about": "Dikdörtgen desende yuvalar: satırlar, sütunlar ve aralık parametredir", "sample.vents.name": "Havalandırma plakası", + "settings.display_quality_note": "Daha ince seviyeler eğri yüzeyleri ve kenarları daha pürüzsüz gösterir, ancak ağ oluşturma daha uzun sürer. Yalnızca görünüm değişir; tasarım ve dışa aktarımlar asla değişmez.", "settings.msaa_applies_on_restart": "Kenar yumuşatma, SolidCraft bir sonraki başlatıldığında uygulanır", "settings.msaa_reset": "{setting}: {requested}× bu grafik aygıtı tarafından desteklenmiyor; {reset}× olarak ayarlandı (desteklenen: {supported}).", "settings.msaa_unsupported": "Bu grafik aygıtı tarafından desteklenmiyor", "settings.reset_intro": "Bu ayarlar bu bilgisayarda çalışmadığı ve SolidCraft'ın başlamasını engelleyeceği için değiştirildi:", "settings.reset_title": "Ayarlar değiştirildi", + "settings.supersampling_note": "Görünümü daha yüksek çözünürlükte çizer ve küçültür: 4K altındaki ekranlarda kenarlar, çizgiler ve ızgaralar daha pürüzsüz görünür. GPU süresi gerektirir: 1,5× ayarında yaklaşık 2,25 kat, 2× ayarında 4 kat daha fazla piksel işlenir.", "sketch.degrees_of_freedom": "{count} serbestlik derecesi", "sketch.draw_curves": "{linetype} olarak çiz", "sketch.make_selection": "Seçimi {linetype} olarak işaretle", + "sketch_text.align_center": "Orta", + "sketch_text.align_left": "Sol", + "sketch_text.align_right": "Sağ", + "sketch_text.bold": "Kalın", + "sketch_text.builtin_font": "{family} (yerleşik)", + "sketch_text.font_search": "Yazı tiplerini ara", + "sketch_text.italic": "İtalik", + "sketch_text.loading_fonts": "Yüklü yazı tipleri aranıyor…", + "sketch_text.on_path": "Metin eğrisini izler: konumunu eğri belirler", + "sketch_text.path_clear": "Metni eğriden ayır", + "sketch_text.path_hint": "Metnin izleyeceği eskiz eğrisi: önce buraya, ardından eğriye tıklayın", + "sketch_text.use_font_file": "{path} yazı tipi dosyasını kullan", + "the parts library is not available": "parça kitaplığı kullanılamıyor", + "timeline.group": "Yeni özellik klasörü oluştur", + "timeline.move_many": "Zaman çizelgesi öğelerini taşı", + "timeline.move_to_group": "Özellikleri klasöre taşı", + "timeline.rename_group": "Özellik klasörünü yeniden adlandır", + "timeline.reorder_many": "Özellikleri yeniden sırala", + "timeline.ungroup": "Özellik klasörünü kaldır", + "to the next face": "sonraki yüze kadar", + "toolbar.image": "RESİM", + "toolbar.render": "RENDER", + "toolbar.render_scene": "SAHNE", "ui.1_degree_of_freedom": "1 serbestlik derecesi", "ui.3d_mouse_speed": "3D fare hızı", "ui.3d_mouse_windows": "3D fare (Windows)", @@ -349,89 +722,89 @@ "ui.about": "Hakkında", "ui.activate": "Etkinleştir", "ui.active_component": "Etkin bileşen", - "ui.agent_cursor": "Ajan imleci", - "ui.agent_cursor_speed": "Ajan imleci hızı", "ui.agent_chat": "Ajan sohbeti", - "ui.agent_chat_command": "Ajan komutu", - "ui.agent_chat_desktop_only": "Ajan sohbeti masaüstü uygulamasını gerektirir.", - "ui.agent_chat_side": "Ajan sohbeti konumu", - "ui.agent_chat_left": "Sol", - "ui.agent_chat_right": "Sağ", - "ui.agent_chat_turn_limit": "Mesaj başına değişiklik", - "ui.agent_chat_privacy_note": "SolidCraft hiçbir yere bir şey göndermez: Başlattığınız ajan, sizin hesabınızla kendi hizmetine bağlanır. SolidCraft hiçbir anahtarı veya parolayı görmez ve kaydetmez.", - "ui.agent_chat_connect": "Bağlan", - "ui.agent_chat_stop": "Durdur", - "ui.agent_chat_stop_tip": "Ajanı ve başlattığı her şeyi durdur", - "ui.agent_chat_close": "Kapat", - "ui.agent_chat_minimize": "Bir çubuğa küçült", - "ui.agent_chat_dock_left": "Sola yerleştir", - "ui.agent_chat_dock_right": "Sağa yerleştir", - "ui.agent_chat_send": "Gönder", - "ui.agent_chat_cancel": "İptal", - "ui.agent_chat_refresh": "Yenile", - "ui.agent_chat_pick": "Ajan", - "ui.agent_chat_custom_hint": "stdin ve stdout üzerinden Agent Client Protocol'ü kullanan herhangi bir program. Kabuk (shell) olmadan çalıştırılır.", - "ui.agent_chat_not_installed": "Yüklü değil", - "ui.agent_chat_none_found": "Kodlama ajanı bulunamadı. Bunlardan birini yükleyin ve ardından Yenile'ye tıklayın:", - "ui.agent_chat_detecting": "Ajanlar aranıyor…", - "ui.agent_chat_signed_in": "oturum açık", - "ui.agent_chat_key_in_env": "anahtar ayarlı", - "ui.agent_chat_not_signed_in": "oturum açık değil", - "ui.agent_chat_state_off": "Bağlı değil", - "ui.agent_chat_state_starting": "Başlatılıyor…", - "ui.agent_chat_state_ready": "Hazır", - "ui.agent_chat_state_busy": "Çalışıyor…", - "ui.agent_chat_state_auth": "Oturum açılması gerekiyor", - "ui.agent_chat_state_exited": "Ajan sonlandı", - "ui.agent_chat_changes_of": "{n}/{limit} değişiklik", - "ui.agent_chat_auth_title": "Ajan için oturum aç", - "ui.agent_chat_auth_needed": "Ajan oturum açmanızı istiyor. Oturumu ajanın kendisinde açarsınız; SolidCraft parolanızı veya anahtarlarınızı asla görmez.", - "ui.agent_chat_auth_none": "Ajan burada oturum açma imkânı sunmuyor: Belgelerinde açıklandığı şekilde oturum açın.", - "ui.agent_chat_auth_terminal": "Bunu bir terminalde çalıştırın ve ardından tekrar Bağlan'a tıklayın:", - "ui.agent_chat_auth_agent": "{name} ile oturum aç", - "ui.agent_chat_auth_env": "{vars} ortam değişkenlerini ayarlayın ve SolidCraft'ı yeniden başlatın.", - "ui.agent_chat_auth_retry": "Oturum açtım: yeniden bağlan", - "ui.agent_chat_copy": "Kopyala", - "ui.agent_chat_permission": "Ajan şunu çalıştırmak istiyor: {title}", + "ui.agent_chat_allow": "İzin ver", + "ui.agent_chat_allowed": "İzin verildi", "ui.agent_chat_answered": "Yanıt: {option}", "ui.agent_chat_approval": "Ajanın bunu yapmasına izin verilsin mi?", - "ui.agent_chat_allow": "İzin ver", - "ui.agent_chat_deny": "Reddet", - "ui.agent_chat_allowed": "İzin verildi", - "ui.agent_chat_denied": "Reddedildi", - "ui.agent_chat_changes": "{n} değişiklik, tek geri alma adımı", - "ui.agent_chat_undo_changes": "Bu değişiklikleri geri al", - "ui.agent_chat_undone": "(geri alındı)", - "ui.agent_chat_undo_label": "Ajan sohbeti: {message}", - "ui.agent_chat_limit": "Ajan, bir mesaj için {limit} değişiklik sınırına ulaştı. Devam etmesi için başka bir mesaj gönderin.", - "ui.agent_chat_refused": "Ajan için izin verilmiyor: {reason}", - "ui.agent_chat_wait_turn": "Ajan hâlâ son mesaj üzerinde çalışıyor: Bekleyin veya İptal'e tıklayın.", - "ui.agent_chat_placeholder": "Ajandan tasarımı değiştirmesini isteyin…", "ui.agent_chat_attach_view": "Görünümü ekle", "ui.agent_chat_attach_view_tip": "Geçerli görünümün bir resmini mesajla birlikte gönder", - "ui.agent_chat_no_images": "Bu ajan resim kabul etmiyor", - "ui.agent_chat_view_attached": "Görünüm eklendi", - "ui.agent_chat_no_cli": "solidcraft-cli uygulamanın yanında bulunamadı, bu yüzden ajan tasarıma erişemiyor.", - "ui.agent_chat_no_control": "Ajan sohbetinin uç noktası başlatılmadı, bu yüzden ajan tasarıma erişemiyor.", + "ui.agent_chat_auth_agent": "{name} ile oturum aç", + "ui.agent_chat_auth_env": "{vars} ortam değişkenlerini ayarlayın ve SolidCraft'ı yeniden başlatın.", + "ui.agent_chat_auth_needed": "Ajan oturum açmanızı istiyor. Oturumu ajanın kendisinde açarsınız; SolidCraft parolanızı veya anahtarlarınızı asla görmez.", + "ui.agent_chat_auth_none": "Ajan burada oturum açma imkânı sunmuyor: Belgelerinde açıklandığı şekilde oturum açın.", + "ui.agent_chat_auth_retry": "Oturum açtım: yeniden bağlan", + "ui.agent_chat_auth_terminal": "Bunu bir terminalde çalıştırın ve ardından tekrar Bağlan'a tıklayın:", + "ui.agent_chat_auth_title": "Ajan için oturum aç", + "ui.agent_chat_cancel": "İptal", + "ui.agent_chat_changes": "{n} değişiklik, tek geri alma adımı", + "ui.agent_chat_changes_of": "{n}/{limit} değişiklik", + "ui.agent_chat_close": "Kapat", + "ui.agent_chat_command": "Ajan komutu", + "ui.agent_chat_connect": "Bağlan", + "ui.agent_chat_copy": "Kopyala", + "ui.agent_chat_custom_hint": "stdin ve stdout üzerinden Agent Client Protocol'ü kullanan herhangi bir program. Kabuk (shell) olmadan çalıştırılır.", + "ui.agent_chat_denied": "Reddedildi", + "ui.agent_chat_deny": "Reddet", + "ui.agent_chat_desktop_only": "Ajan sohbeti masaüstü uygulamasını gerektirir.", + "ui.agent_chat_detecting": "Ajanlar aranıyor…", + "ui.agent_chat_dock_left": "Sola yerleştir", + "ui.agent_chat_dock_right": "Sağa yerleştir", "ui.agent_chat_exited": "Ajan sonlandırıldı.", "ui.agent_chat_failed_start": "Ajan başlatılamadı: {error}", "ui.agent_chat_intro": "Zaten kullandığınız bir kodlama ajanıyla veya seçtiğiniz bir model uç noktasıyla sohbet edin. Ajan, SolidCraft'ın araçlarıyla açık tasarım üzerinde çalışır: Değişiklikleri hemen görünür ve mesaj başına tek adımda geri alınabilir. Sormadan neleri yapabileceğini Ayarlar > AI altında belirlersiniz.", - "ui.agent_chat_privacy": "Kendi hesabınızla çalıştırdığınız ajan dışında hiçbir yere bir şey gitmez.", + "ui.agent_chat_key_in_env": "anahtar ayarlı", + "ui.agent_chat_left": "Sol", + "ui.agent_chat_limit": "Ajan, bir mesaj için {limit} değişiklik sınırına ulaştı. Devam etmesi için başka bir mesaj gönderin.", + "ui.agent_chat_minimize": "Bir çubuğa küçült", + "ui.agent_chat_no_cli": "solidcraft-cli uygulamanın yanında bulunamadı, bu yüzden ajan tasarıma erişemiyor.", + "ui.agent_chat_no_control": "Ajan sohbetinin uç noktası başlatılmadı, bu yüzden ajan tasarıma erişemiyor.", + "ui.agent_chat_no_images": "Bu ajan resim kabul etmiyor", + "ui.agent_chat_none_found": "Kodlama ajanı bulunamadı. Bunlardan birini yükleyin ve ardından Yenile'ye tıklayın:", "ui.agent_chat_none_found_short": "Ajan bulunamadı", + "ui.agent_chat_not_installed": "Yüklü değil", + "ui.agent_chat_not_signed_in": "oturum açık değil", + "ui.agent_chat_permission": "Ajan şunu çalıştırmak istiyor: {title}", + "ui.agent_chat_pick": "Ajan", + "ui.agent_chat_placeholder": "Ajandan tasarımı değiştirmesini isteyin…", + "ui.agent_chat_privacy": "Kendi hesabınızla çalıştırdığınız ajan dışında hiçbir yere bir şey gitmez.", + "ui.agent_chat_privacy_note": "SolidCraft hiçbir yere bir şey göndermez: Başlattığınız ajan, sizin hesabınızla kendi hizmetine bağlanır. SolidCraft hiçbir anahtarı veya parolayı görmez ve kaydetmez.", + "ui.agent_chat_refresh": "Yenile", + "ui.agent_chat_refused": "Ajan için izin verilmiyor: {reason}", + "ui.agent_chat_right": "Sağ", + "ui.agent_chat_send": "Gönder", + "ui.agent_chat_side": "Ajan sohbeti konumu", + "ui.agent_chat_signed_in": "oturum açık", + "ui.agent_chat_state_auth": "Oturum açılması gerekiyor", + "ui.agent_chat_state_busy": "Çalışıyor…", + "ui.agent_chat_state_exited": "Ajan sonlandı", + "ui.agent_chat_state_off": "Bağlı değil", + "ui.agent_chat_state_ready": "Hazır", + "ui.agent_chat_state_starting": "Başlatılıyor…", + "ui.agent_chat_stop": "Durdur", + "ui.agent_chat_stop_tip": "Ajanı ve başlattığı her şeyi durdur", + "ui.agent_chat_turn_limit": "Mesaj başına değişiklik", + "ui.agent_chat_undo_changes": "Bu değişiklikleri geri al", + "ui.agent_chat_undo_label": "Ajan sohbeti: {message}", + "ui.agent_chat_undone": "(geri alındı)", + "ui.agent_chat_view_attached": "Görünüm eklendi", + "ui.agent_chat_wait_turn": "Ajan hâlâ son mesaj üzerinde çalışıyor: Bekleyin veya İptal'e tıklayın.", + "ui.agent_cursor": "Ajan imleci", + "ui.agent_cursor_speed": "Ajan imleci hızı", "ui.ai_add": "Ekle", "ui.ai_add_agent": "Ajan ekle…", "ui.ai_add_agent_title": "Ajan ekle", "ui.ai_add_api": "OpenAI uyumlu API", "ui.ai_add_custom": "Özel komut", - "ui.ai_added": "eklendi", "ui.ai_add_installed": "Yüklü ajan", "ui.ai_add_installed_note": "Yüklü bir ajan için ayrı bir giriş (örneğin farklı argümanlarla). Yüklü ajanlar kendiliğinden görünür.", + "ui.ai_added": "eklendi", "ui.ai_agent_mode_tip": "Ajanın kendi modu: Kendi araçları (kabuk, dosya değişiklikleri) bu modu izler. SolidCraft'ın araçları Ayarlar > AI altındaki izinleri izler.", "ui.ai_agents": "Ajanlar", "ui.ai_always_allow": "Her zaman izin ver", + "ui.ai_always_allow_tip": "{tool} için bu ajana bundan sonra sormadan izin ver", "ui.ai_always_allowed": "Her zaman izin verilenler", "ui.ai_always_allowed_none": "Henüz her zaman izin verilen bir şey yok. Sohbette verdiğiniz “Her zaman izin ver” yanıtları burada görünür.", - "ui.ai_always_allow_tip": "{tool} için bu ajana bundan sonra sormadan izin ver", "ui.ai_auto_allowed": "{title} için otomatik olarak izin verildi ({why})", "ui.ai_auto_mode": "İzin ayarınız", "ui.ai_auto_ours": "SolidCraft kendi araçlarını kendisi denetler", @@ -446,10 +819,10 @@ "ui.ai_http_key": "uç nokta anahtarı reddetti: Ayarlar > AI altında kontrol edin", "ui.ai_http_not_found": "Uç nokta veya model bulunamadı: temel URL'yi ve model adını kontrol edin", "ui.ai_key": "API anahtarı", - "ui.ai_keychain_error": "Sistem anahtar zinciri reddetti: {error}", "ui.ai_key_hint": "isteğe bağlı; sistem anahtar zincirinde saklanır", "ui.ai_key_needs_https": "Anahtar yalnızca HTTPS üzerinden veya bu bilgisayara gönderilir.", "ui.ai_key_note": "SolidCraft ayarlarında değil, sistem anahtar zincirinde saklanır. Yerel bir sunucu için boş bırakın.", + "ui.ai_keychain_error": "Sistem anahtar zinciri reddetti: {error}", "ui.ai_mode_all": "Her şeye izin ver", "ui.ai_mode_all_note": "Hiçbir işlem için önceden onay istenmez. Çökme raporlarına yine erişilemez ve klasör sınırları geçerliliğini korur.", "ui.ai_mode_all_warning": "Ajan tasarımınızı sormadan kaydedebilir, üzerine yazabilir, dışa aktarabilir ve değiştirebilir. Bunu yalnızca güvendiğiniz bir ajanla ve kaydedilmiş tasarımlarla kullanın.", @@ -480,36 +853,26 @@ "ui.ai_test_acp_ok": "{agent} yanıt veriyor", "ui.ai_test_acp_tip": "Ajanı kısa süreliğine başlatır ve bir oturum ister; ardından tekrar kapatır", "ui.ai_test_api_tip": "Uç noktadan model listesini ister", - "ui.ai_testing": "Test ediliyor…", "ui.ai_test_no_model": "Uç noktaya ulaşıldı, {count} model bulundu ancak {model} aralarında yok", "ui.ai_test_ok": "Uç noktaya ulaşıldı, {count} model bulundu", - "ui.ai_toolbar_button": "Araç çubuğunda düğmeyi göster", - "ui.ai_toolbar_button_note": "Araç çubuğunun sağ ucundaki AI düğmesi. Ctrl+Shift+A ve Görünüm menüsü paneli açmaya devam eder.", + "ui.ai_testing": "Test ediliyor…", "ui.ai_tool_done": "tamamlandı", "ui.ai_tool_failed": "başarısız", "ui.ai_tool_running": "çalışıyor", "ui.ai_tool_unfold": "Sonucu göstermek için tıklayın", "ui.ai_tool_waiting": "bekliyor", + "ui.ai_toolbar_button": "Araç çubuğunda düğmeyi göster", + "ui.ai_toolbar_button_note": "Araç çubuğunun sağ ucundaki AI düğmesi. Ctrl+Shift+A ve Görünüm menüsü paneli açmaya devam eder.", "ui.ai_undo_tip": "Ajanın bu mesaj için değiştirdiği her şeyi tek adımda geri al", - "AI": "AI", "ui.all": "Tümü", "ui.analysis": "Analiz", "ui.angle": "Açı", "ui.angle_decimals": "Açı ondalık basamakları", + "ui.animateJoint": "Bağlantıyı canlandır", "ui.animate_view_changes": "Görünüm değişikliklerini animasyonla göster", "ui.animation": "Animasyon", "ui.animation_speed": "Animasyon hızı", "ui.anti_aliasing": "Kenar yumuşatma", - "ui.supersampling": "Süper örnekleme (SSAA)", - "ui.supersampling_off": "Kapalı (1×)", - "ui.supersampling_adaptive": "Yalnızca görünüm hareketsizken", - "settings.supersampling_note": "Görünümü daha yüksek çözünürlükte çizer ve küçültür: 4K altındaki ekranlarda kenarlar, çizgiler ve ızgaralar daha pürüzsüz görünür. GPU süresi gerektirir: 1,5× ayarında yaklaşık 2,25 kat, 2× ayarında 4 kat daha fazla piksel işlenir.", - "ui.display_quality": "Görüntü kalitesi", - "ui.display_quality_coarse": "Kaba", - "ui.display_quality_normal": "Normal", - "ui.display_quality_fine": "İnce", - "ui.display_quality_ultra": "Ultra", - "settings.display_quality_note": "Daha ince seviyeler eğri yüzeyleri ve kenarları daha pürüzsüz gösterir, ancak ağ oluşturma daha uzun sürer. Yalnızca görünüm değişir; tasarım ve dışa aktarımlar asla değişmez.", "ui.apply": "Uygula", "ui.arc": "Yay", "ui.assemble": "Montaj", @@ -517,9 +880,11 @@ "ui.axes": "Eksenler", "ui.axis": "Eksen", "ui.base_point": "Temel nokta", + "ui.blocked": "Engellenmiş", "ui.bodies": "Gövdeler", "ui.box": "Kutu", "ui.break": "Kır", + "ui.calibrate": "Kalibre et", "ui.cancel": "İptal", "ui.canvases": "Tuvaller", "ui.center": "Merkez", @@ -529,8 +894,6 @@ "ui.chamfer_type": "Pah türü", "ui.change_workspace": "Çalışma alanını değiştir", "ui.chord_length": "Kiriş uzunluğu", - "ui.curvature_g2": "Eğrilik sürekliliği (G2)", - "ui.equivalent_radius": "Eşdeğer yarıçap", "ui.circle": "Daire", "ui.circular_pattern": "Dairesel desen", "ui.clear": "Temizle", @@ -539,28 +902,6 @@ "ui.click_selects_whole_bodies": "Tıklama tüm gövdeyi seçer", "ui.click_then_press_key": "Tıklayın, ardından yeni tuşa basın", "ui.close": "Kapat", - "ui.material_review.title": "Fiziksel malzeme verilerini kontrol et", - "ui.material_review.scope": "Yalnızca aday: atanmaz veya kaydedilmez. Sayısal kontrol teknik bir sertifika değildir.", - "ui.material_review.input": "Şema 1 malzeme kartını yapıştırın (JSON)", - "ui.material_review.review": "Kartı kontrol et", - "ui.material_review.limit": "Kart 256 KiB giriş sınırını aşıyor.", - "ui.material_review.unknown": "Bilinmiyor", - "ui.material_review.properties": "Özellikler", - "ui.material_review.conditions": "Belirtilen koşullar", - "ui.material_review.source": "Kaynak", - "ui.material_review.axes": "Malzemenin yerel eksenleri; gövde yönlendirmesi atanmadı.", - "ui.material_review.derived": "Türetilmiş izotropik modüller", - "ui.material_review.claims": "Kaynaklar ve lisanslar doğrulanmamış beyanlardır. Eksik değerler bilinmiyor olarak kalır.", - "ui.material_review.density": "Yoğunluk", - "ui.material_review.elasticity": "Elastikiyet", - "ui.material_review.tensile_strength": "Çekme dayanımı", - "ui.material_review.compressive_strength": "Basma dayanımı", - "ui.material_review.yield_strength": "Akma dayanımı", - "ui.material_review.shear_strength": "Kesme dayanımı", - "ui.material_review.thermal_conductivity": "Isıl iletkenlik", - "ui.material_review.thermal_expansion": "Isıl genleşme", - "ui.material_review.specific_heat": "Özgül ısı kapasitesi", - "ui.material_review.moisture_unit": "kg su / kg kuru malzeme", "ui.coil": "Helezon", "ui.coincident": "Çakışık", "ui.collapse": "Daralt", @@ -582,6 +923,8 @@ "ui.colour_vision_tritan_tip": "Zayıf veya eksik mavi algısı için", "ui.combine": "Birleştir", "ui.coming_later": "yakında", + "ui.command_done": "{command} tamamlandı", + "ui.command_palette_hint": "Bir komut yazın (ör. {example}) — veya aramak için S tuşuna basın", "ui.concentric": "Eş merkezli", "ui.configurations": "Konfigürasyonlar", "ui.conic_curve": "Konik eğri", @@ -600,7 +943,11 @@ "ui.create_sketch": "Eskiz oluştur", "ui.current": "geçerli", "ui.curvature": "Eğrilik", + "ui.curvature_g2": "Eğrilik sürekliliği (G2)", "ui.curves": "Eğriler", + "ui.custom_program": "Özel…", + "ui.custom_program_tip": "Listeye bir dilimleyici programı ekle", + "ui.customizeToolbar": "Araç çubuğunu özelleştir…", "ui.cut": "Kes", "ui.cylinder": "Silindir", "ui.dark": "Koyu", @@ -609,9 +956,25 @@ "ui.delete": "Sil", "ui.depth": "Derinlik", "ui.design": "Tasarım", + "ui.design_properties.author": "Yazar", + "ui.design_properties.description": "Açıklama", + "ui.design_properties.exports": "STEP, IGES ve 3MF dışa aktarımları, biçim bunun için bir alan sunuyorsa bu bilgileri de aktarır.", + "ui.design_properties.license": "Lisans", + "ui.design_properties.not_text": "Metin olarak kaydedilmedi; buraya yapılan bir giriş değerin yerini alır.", + "ui.design_properties.organization": "Kuruluş", + "ui.design_properties.others": "Diğer araçların verileri", + "ui.design_properties.others_note": "Tasarımda değişmeden kalır ve asla dışa aktarılmaz.", + "ui.design_properties.part_number": "Parça numarası", + "ui.design_properties.project": "Proje", + "ui.design_properties.revision": "Revizyon", "ui.diameter": "Çap", "ui.dimension": "Ölçü", "ui.direction": "Yön", + "ui.display_quality": "Görüntü kalitesi", + "ui.display_quality_coarse": "Kaba", + "ui.display_quality_fine": "İnce", + "ui.display_quality_normal": "Normal", + "ui.display_quality_ultra": "Ultra", "ui.distance": "Mesafe", "ui.distance_1": "Mesafe 1", "ui.distance_2": "Mesafe 2", @@ -621,12 +984,16 @@ "ui.drawing": "Teknik resim", "ui.drill_point": "Matkap ucu", "ui.edit": "Düzenle", + "ui.editJointLimits": "Bağlantı sınırlarını düzenle", "ui.edit_section_analysis": "Kesit analizini düzenle", "ui.ellipse": "Elips", "ui.end_radius": "Bitiş yarıçapı", + "ui.end_scale": "Bitiş ölçeği", "ui.entities": "Öğeler", "ui.equal": "Eşit", + "ui.equivalent_radius": "Eşdeğer yarıçap", "ui.expand": "Genişlet", + "ui.exportDxf": "DXF olarak dışa aktar…", "ui.export_ellipsis": "Dışa aktar...", "ui.export_ellipsis_keymap": "Dışa aktar…", "ui.export_keymap_tip": "Tuşları, S kutusu favorilerini ve araç çubuğunu dosya olarak dışa aktarır", @@ -640,15 +1007,20 @@ "ui.file": "Dosya", "ui.fillet": "Yuvarlatma", "ui.filter_commands_or_keys": "Komutları veya tuşları filtrele", + "ui.findInTimeline": "Zaman çizelgesinde bul", + "ui.findInWindow": "Pencerede bul", "ui.finish_sketch": "Eskizi bitir", + "ui.fit": "Sığdır", "ui.fix_unfix": "Sabitle/Çöz", "ui.flat": "Düz", "ui.flip": "Ters çevir", + "ui.format": "Biçim", "ui.front": "Ön", "ui.fully_constrained": "Tam kısıtlı", "ui.general": "Genel", "ui.graphics": "Grafik", "ui.ground_shadow": "Zemin gölgesi", + "ui.groupSelected": "Seçimi grupla", "ui.heading_add_ins": "EKLENTİLER", "ui.heading_assemble": "MONTAJ", "ui.heading_box": "KUTU", @@ -680,8 +1052,8 @@ "ui.heading_mirror": "AYNALA", "ui.heading_modify": "DEĞİŞTİR", "ui.heading_move": "TAŞI", - "ui.heading_offset": "OFSET", "ui.heading_move_copy": "TAŞI/KOPYALA", + "ui.heading_offset": "OFSET", "ui.heading_offset_plane": "OFSET DÜZLEM", "ui.heading_ok": "OK", "ui.heading_parameters": "PARAMETRELER", @@ -689,13 +1061,16 @@ "ui.heading_pipe": "BORU", "ui.heading_plane_at_angle": "AÇILI DÜZLEM", "ui.heading_plastic": "PLASTİK", + "ui.heading_position": "KONUM", "ui.heading_prepare": "HAZIRLA", "ui.heading_rectangular_pattern": "DİKDÖRTGEN DESEN", "ui.heading_revolve": "DÖNDÜR", "ui.heading_right": "SAĞ", + "ui.heading_save_mesh": "AĞ OLARAK KAYDET", "ui.heading_scale": "ÖLÇEKLENDİR", "ui.heading_section_analysis": "KESİT ANALİZİ", "ui.heading_select": "SEÇ", + "ui.heading_setup": "KURULUM", "ui.heading_sheet_metal": "SAC METAL", "ui.heading_shell": "KABUK", "ui.heading_sketch": "ESKİZ", @@ -713,15 +1088,22 @@ "ui.heading_utility": "YARDIMCI ARAÇLAR", "ui.help": "Yardım", "ui.hide": "Gizle", + "ui.hideAxes": "Eksenleri gizle", + "ui.hideDimension": "Ölçüyü gizle", + "ui.hideOrigin": "Orijini gizle", + "ui.hidePlanes": "Düzlemleri gizle", + "ui.hideProfile": "Profili gizle", "ui.hole": "Delik", "ui.hole_tap_type": "Diş türü", "ui.hole_type": "Delik türü", "ui.home": "Başlangıç", + "ui.homeView": "Başlangıç görünümü", "ui.horizontal_vertical": "Yatay/Dikey", "ui.import_ellipsis": "İçe aktar…", "ui.insert": "Ekle", "ui.inspect": "İncele", "ui.intersect": "Kesişim", + "ui.isolate": "Yalıt", "ui.join": "Birleştir", "ui.joints": "Bağlantılar", "ui.keyboard_shortcuts": "Klavye kısayolları", @@ -730,11 +1112,37 @@ "ui.light": "Açık", "ui.line": "Çizgi", "ui.linetype": "Çizgi türü", + "ui.lock": "Kilitle", "ui.loft": "Loft", "ui.look_at": "Bak", "ui.look_at_anim_desc": "Eksen görünümü, Bak, Başlangıç ve Sığdır", "ui.manufacture": "Üretim", + "ui.material_review.axes": "Malzemenin yerel eksenleri; gövde yönlendirmesi atanmadı.", + "ui.material_review.claims": "Kaynaklar ve lisanslar doğrulanmamış beyanlardır. Eksik değerler bilinmiyor olarak kalır.", + "ui.material_review.compressive_strength": "Basma dayanımı", + "ui.material_review.conditions": "Belirtilen koşullar", + "ui.material_review.density": "Yoğunluk", + "ui.material_review.derived": "Türetilmiş izotropik modüller", + "ui.material_review.elasticity": "Elastikiyet", + "ui.material_review.input": "Şema 1 malzeme kartını yapıştırın (JSON)", + "ui.material_review.limit": "Kart 256 KiB giriş sınırını aşıyor.", + "ui.material_review.moisture_unit": "kg su / kg kuru malzeme", + "ui.material_review.properties": "Özellikler", + "ui.material_review.review": "Kartı kontrol et", + "ui.material_review.scope": "Yalnızca aday: atanmaz veya kaydedilmez. Sayısal kontrol teknik bir sertifika değildir.", + "ui.material_review.shear_strength": "Kesme dayanımı", + "ui.material_review.source": "Kaynak", + "ui.material_review.specific_heat": "Özgül ısı kapasitesi", + "ui.material_review.tensile_strength": "Çekme dayanımı", + "ui.material_review.thermal_conductivity": "Isıl iletkenlik", + "ui.material_review.thermal_expansion": "Isıl genleşme", + "ui.material_review.title": "Fiziksel malzeme verilerini kontrol et", + "ui.material_review.unknown": "Bilinmiyor", + "ui.material_review.yield_strength": "Akma dayanımı", "ui.measure": "Ölç", + "ui.mesh_format_3mf": "3MF", + "ui.mesh_format_3mf_tagged": "Yüz etiketli 3MF", + "ui.mesh_format_stl": "STL", "ui.midpoint": "Orta nokta", "ui.mirror": "Aynala", "ui.mirror_line": "Ayna çizgisi", @@ -744,9 +1152,13 @@ "ui.named_views": "Adlandırılmış görünümler", "ui.navigation": "Gezinme", "ui.needs_design": "{command}: Önce bir tasarım açın", + "ui.newSketchGroup": "Yeni eskiz grubu", "ui.new_body": "Yeni gövde", "ui.new_design": "Yeni tasarım", + "ui.no_slicer_found": "Dilimleyici bulunamadı", "ui.normal": "Normal", + "ui.normalConstruction": "Normal / Yapı", + "ui.not_a_program": "{path} başlatılabilir bir program değil", "ui.object_type": "Nesne türü", "ui.objects": "Nesneler", "ui.offer_to_stand_up_y_up_files": "Y ekseni yukarı olan dosyaları dikleştirmeyi öner", @@ -759,10 +1171,13 @@ "ui.open_recent": "Son kullanılanlar", "ui.operation": "İşlem", "ui.options": "Seçenekler", + "ui.orbit": "Döndür", "ui.orbit_around": "Etrafında döndür", + "ui.orientation": "Yönlendirme", "ui.origin": "Orijin", "ui.palette_points": "Noktalar", "ui.palette_profile": "Profil", + "ui.pan": "Kaydır", "ui.pan_zoom_orbit": "Kaydır, yakınlaştır, döndür", "ui.parallel": "Paralel", "ui.parameters": "Parametreler", @@ -771,6 +1186,8 @@ "ui.pattern_on_path": "Yol üzerinde desen", "ui.perpendicular": "Dik", "ui.perspective_view": "Perspektif görünüm", + "ui.pinToShortcuts": "Kısayollara sabitle", + "ui.pinToToolbar": "Araç çubuğuna sabitle", "ui.pipe": "Boru", "ui.placement": "Yerleşim", "ui.plane": "Düzlem", @@ -786,63 +1203,59 @@ "ui.profiles": "Profiller", "ui.project": "Yansıt", "ui.project_face_edges_sketch": "Yüz kenarlarını yeni eskizlere yansıt", + "ui.properties": "Özellikler", + "ui.pull_direction": "Kalıptan çıkarma yönü", "ui.quantity": "Adet", "ui.quantity_2": "Adet 2", "ui.quit": "Çıkış", "ui.radial_context_menu": "Dairesel bağlam menüsü", "ui.radius": "Yarıçap", - "ui.pull_direction": "Kalıptan çıkarma yönü", - "ui.tool_direction": "Takım yönü", - "ui.reachable": "Erişilebilir", - "ui.blocked": "Engellenmiş", "ui.radius_type": "Yarıçap türü", + "ui.reachable": "Erişilebilir", "ui.rectangle": "Dikdörtgen", "ui.rectangular_pattern": "Dikdörtgen desen", "ui.redo": "Yinele", + "ui.removeFromToolbar": "Araç çubuğundan kaldır", + "ui.removeSection": "Kesiti kaldır", "ui.render": "Render", "ui.renderer": "Çizim motoru", + "ui.repeat": "Tekrarla", + "ui.report_a_bug": "Hata bildir", "ui.reset": "Sıfırla", "ui.reset_all": "Tümünü sıfırla", "ui.reset_the_settings_on_this_page": "Bu sayfadaki ayarları sıfırla", + "ui.restore": "Geri yükle", "ui.restore_defaults": "Varsayılanları geri yükle", "ui.reverse_zoom_direction": "Yakınlaştırma yönünü tersine çevir", "ui.revolve": "Döndür", "ui.right": "Sağ", "ui.save": "Kaydet", - "ui.heading_save_mesh": "AĞ OLARAK KAYDET", - "ui.format": "Biçim", - "ui.mesh_format_stl": "STL", - "ui.mesh_format_3mf": "3MF", - "ui.mesh_format_3mf_tagged": "Yüz etiketli 3MF", - "ui.send_to_slicer": "Dilimleyiciye gönder", - "ui.slicer": "Dilimleyici", - "ui.custom_program": "Özel…", - "ui.no_slicer_found": "Dilimleyici bulunamadı", - "ui.send": "Gönder", - "ui.custom_program_tip": "Listeye bir dilimleyici programı ekle", - "ui.slicer_delete_tip": "{program}\nDelete tuşuyla listeden kaldır", - "ui.save_mesh_pick_bodies": "Kaydedilecek gövdeleri seçin", - "ui.save_mesh_no_slicer": "Dilimleyici bulunamadı: “Özel…” seçeneğini seçip dilimleyici programını belirtin veya “Dilimleyiciye gönder” seçeneğini kapatın", - "ui.not_a_program": "{path} başlatılabilir bir program değil", - "ui.sent_to_slicer": "{slicer} uygulamasına gönderildi", - "ui.saved_to": "{path} konumuna kaydedildi", - "ui.save_mesh_temp_failed": "{folder} oluşturulamadı: {error}", "ui.save_as": "Farklı kaydet", "ui.save_as_ellipsis": "Farklı kaydet...", + "ui.save_mesh_no_slicer": "Dilimleyici bulunamadı: “Özel…” seçeneğini seçip dilimleyici programını belirtin veya “Dilimleyiciye gönder” seçeneğini kapatın", + "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.scale": "Ölçekle", - "ui.orientation": "Yönlendirme", - "ui.twist": "Burulma", - "ui.end_scale": "Bitiş ölçeği", - "ui.sweep_turn_with_path": "Yolla birlikte dön", - "ui.sweep_keep_as_drawn": "Çizildiği gibi", - "ui.sweep_follow_direction": "Yönü izle", "ui.section_analysis": "Kesit analizi", "ui.select": "Seç", + "ui.selectOther": "Diğerini seç…", + "ui.selectTangentChain": "Teğet zinciri seç", "ui.select_other_hint": "Diğerini seç: İmlecin altındaki her şeyi listelemek için sol tuşu model üzerinde hareket ettirmeden basılı tutun (veya sağ tık › Diğerini seç…); oradaki bir sonraki öğeyi seçmek için aynı noktaya tekrar tıklayın.", "ui.selection": "Seçim", + "ui.send": "Gönder", + "ui.send_to_slicer": "Dilimleyiciye gönder", + "ui.sent_to_slicer": "{slicer} uygulamasına gönderildi", "ui.shell": "Kabuk", "ui.show": "Göster", + "ui.showAll": "Tümünü göster", + "ui.showAllBodies": "Tüm gövdeleri göster", + "ui.showAxes": "Eksenleri göster", + "ui.showDimension": "Ölçüyü göster", + "ui.showOrigin": "Orijini göster", + "ui.showPlanes": "Düzlemleri göster", "ui.show_constraints": "Kısıtlamalar", + "ui.show_construction_geometries": "Yapı geometrileri", "ui.show_dimensions": "Ölçüler", "ui.show_points": "Noktaları göster", "ui.show_profile": "Profili göster", @@ -857,6 +1270,8 @@ "ui.sketch_status": "Eskiz durumu", "ui.sketches": "Eskizler", "ui.slice": "Dilim", + "ui.slicer": "Dilimleyici", + "ui.slicer_delete_tip": "{program}\nDelete tuşuyla listeden kaldır", "ui.slot": "Yuva", "ui.smooth": "Pürüzsüz", "ui.smooth_wheel_zoom": "Yumuşak tekerlek yakınlaştırması", @@ -872,7 +1287,14 @@ "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_radius": "Başlangıç yarıçapı", + "ui.supersampling": "Süper örnekleme (SSAA)", + "ui.supersampling_adaptive": "Yalnızca görünüm hareketsizken", + "ui.supersampling_off": "Kapalı (1×)", + "ui.suppress": "Bastır", "ui.sweep": "Süpür", + "ui.sweep_follow_direction": "Yönü izle", + "ui.sweep_keep_as_drawn": "Çizildiği gibi", + "ui.sweep_turn_with_path": "Yolla birlikte dön", "ui.symmetric": "Simetrik", "ui.symmetry": "Simetri", "ui.system": "Sistem", @@ -888,18 +1310,26 @@ "ui.timeline_left_sidebar": "Sol kenar çubuğu", "ui.tip_angle": "Uç açısı", "ui.to_object": "Nesneye kadar", + "ui.tool_direction": "Takım yönü", "ui.top": "Üst", "ui.torus": "Torus", + "ui.total_angle": "Toplam açı", "ui.trackpad_pan_tip": "Dokunmatik yüzey hareketleri görünümü kaydırır (kapalı: tekerlek gibi yakınlaştırır); fare tekerleği yakınlaştırır, başparmak tekerleği yana kaydırır, iki parmakla sıkıştırma her zaman yakınlaştırır", "ui.trim": "Kırp", + "ui.twist": "Burulma", "ui.two_finger_scroll_pans": "İki parmakla kaydırma görünümü kaydırır", "ui.two_sides": "İki taraflı", "ui.ui_scale": "Arayüz ölçeği", "ui.undo": "Geri al", + "ui.unground": "Sabitlemeyi kaldır", + "ui.unisolate": "Yalıtımı kaldır", "ui.units": "Birimler", "ui.units_of_new_designs": "Yeni tasarımların birimleri", + "ui.unlock": "Kilidi aç", + "ui.unsuppress": "Bastırmayı kaldır", "ui.untitled": "Adsız", "ui.up_axis_note": "Görünümlerde (eksen görünümü, Başlangıç, Bak) hangi eksenin yukarıyı gösterdiğini belirler. Tasarımlar değişmez.", + "ui.updateToCurrentView": "Geçerli görünüme güncelle", "ui.variable": "Değişken", "ui.view_centre": "Görünüm merkezi", "ui.visual_shaded_hidden_edges": "Gizli kenarlarla gölgeli", @@ -911,471 +1341,41 @@ "ui.y_distance": "Y mesafesi", "ui.y_up": "Y yukarı", "ui.z_up": "Z yukarı", + "ui.zoom": "Yakınlaştır", "ui.zoom_to_cursor_tip": "Tekerlek, imlecin altındaki noktaya doğru yakınlaştırır (kapalı: görünümün merkezine doğru)", "ui.zoom_to_the_cursor": "İmlece doğru yakınlaştır", - "A new configuration, a copy of the active one": "Etkin konfigürasyonun kopyası olan yeni bir konfigürasyon", - "About SolidCraft": "SolidCraft hakkında", - "Active": "Etkin", - "Active rule": "Etkin kural", - "Add": "Ekle", - "Add Key": "Tuş ekle", - "Add Mid Radius": "Ara yarıçap ekle", - "Add Row": "Satır ekle", - "All Sketch Points": "Tüm eskiz noktaları", - "All open designs": "Tüm açık tasarımlar", - "Allowed expressions, separated by semicolons": "Noktalı virgülle ayrılmış izin verilen ifadeler", - "Also deletes": "Bunları da siler", - "Angle 2": "Açı 2", - "Animate": "Canlandır", - "Appearance name": "Görünüm adı", - "Applied Radius": "Uygulanan yarıçap", - "Apply To": "Uygulama hedefi", - "Area": "Alan", - "Attachment": "Bağlama", - "BROWSER": "TARAYICI", - "Bend Line Position": "Büküm çizgisi konumu", - "Bend Position": "Büküm konumu", - "Bend Radius": "Büküm yarıçapı", - "Bends": "Bükümler", - "Body": "Gövde", - "Bounding box": "Sınırlayıcı kutu", - "CSV or JSON: updates existing parameters, adds new ones": "CSV veya JSON: mevcut parametreleri günceller, yenilerini ekler", - "Capture All Positions": "Tüm konumları yakala", - "Catch Direction": "Yakalama yönü", - "Cells": "Hücreler", - "Center X": "Merkez X", - "Center Y": "Merkez Y", - "Center of mass": "Kütle merkezi", - "Chamfer Type": "Pah türü", - "Check collisions": "Çarpışmaları kontrol et", - "Checked": "Kontrol edildi", - "Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.": "Yeni bir düzlem seçin. Eskiz geometrisi ve ölçüler, iki boyutlu koordinatlarında değişmeden kalır.", - "Close draft": "Taslağı kapat", - "Collisions": "Çarpışmalar", - "Colour": "Renk", - "Component1": "Bileşen1", - "Configuration": "Konfigürasyon", - "Configuration rules": "Konfigürasyon kuralları", - "Contact": "Temas", - "Copy all licences": "Tüm lisansları kopyala", - "Copy diagnostic information": "Tanılama bilgilerini kopyala", - "Copy report": "Raporu kopyala", - "Corner Relief Shape": "Köşe boşaltma şekli", - "Counterbore depth": "Düz havşa derinliği", - "Countersink angle": "Konik havşa açısı", - "Create Issue — review draft": "Sorun oluştur — taslağı gözden geçirin", - "Customize Toolbar": "Araç çubuğunu özelleştir", - "Delete all": "Tümünü sil", - "Delete rule": "Kuralı sil", - "Delete the row": "Satırı sil", - "Delete the set": "Kümeyi sil", - "Delete this parameter": "Bu parametreyi sil", - "Density": "Yoğunluk", - "Designs you open or save appear here.": "Açtığınız veya kaydettiğiniz tasarımlar burada görünür.", - "Determined by To Object. Choose Angle to edit the angular extent.": "Nesneye kadar seçeneğiyle belirlenir. Açısal kapsamı düzenlemek için Açı seçeneğini seçin.", - "Discard": "At", - "Double-click to rename": "Yeniden adlandırmak için çift tıklayın", - "Drive Joint": "Bağlantıyı tahrik et", - "Edit Profile Sketch": "Profil eskizini düzenle", - "Enable rule": "Kuralı etkinleştir", - "Enabled": "Etkin", - "Explode": "Patlat", - "Extents": "Kapsamlar", - "Face attachment lost": "Yüze bağlama kayboldu", - "Faces / edges / vertices": "Yüzler / kenarlar / köşe noktaları", - "Favourite": "Favori", - "Files from many CAD programs have Y up, so they open lying on their back here (Z up).": "Birçok CAD programının dosyalarında Y yukarıyı gösterir; bu yüzden burada (Z yukarı) sırtüstü yatar hâlde açılırlar.", - "Filter": "Filtre", - "Find in Browser": "Tarayıcıda bul", - "Copy Error Message": "Hata mesajını kopyala", - "Copy Warning Message": "Uyarı mesajını kopyala", - "Flat size": "Açınım boyutu", - "Follow camera (Look At sketches)": "Kamera takibi (eskizlerde Bak)", - "Font": "Yazı tipi", - "Full Length": "Tam uzunluk", - "Gap": "Boşluk", - "Grid": "Izgara", - "Height": "Yükseklik", - "Home view": "Başlangıç görünümü", - "In This Design": "Bu tasarımda", - "Interferes": "Girişim var", - "Issue title": "Sorun başlığı", - "Joint Origin1": "Bağlantı orijini1", - "Keep Tools": "Araçları koru", - "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.", - "Length": "Uzunluk", - "Length units": "Uzunluk birimleri", - "Library": "Kitaplık", - "Loop": "Döngü", - "Margin": "Kenar boşluğu", - "Mass": "Kütle", - "Material": "Malzeme", - "Mid Radius": "Ara yarıçap", - "Modeled": "Modellenmiş", - "More toolbar panels": "Diğer araç çubuğu panelleri", - "Motion": "Hareket", - "Move Type": "Taşıma türü", - "Move earlier": "Öne al", - "Move later": "Sonraya al", - "Name": "Ad", - "No crash reports.": "Çökme raporu yok.", - "No matching appearances": "Eşleşen görünüm yok", - "Not available yet": "Henüz kullanılamıyor", - "Opacity": "Opaklık", - "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", - "Parameter values": "Parametre değerleri", - "Per Edge": "Kenar başına", - "Pick the tool bodies": "Araç gövdelerini seçin", - "Place at the origin instead": "Bunun yerine orijine yerleştir", - "Playback": "Oynatma", - "Position": "Konum", - "Position (0 to 1)": "Konum (0 ile 1 arası)", - "Position along the edge, 0 at the start end, 1 at the other": "Kenar boyunca konum: başlangıç ucunda 0, diğer uçta 1", - "Preview leaves the current design unchanged.": "Önizleme geçerli tasarımı değiştirmez.", - "RECENT": "SON KULLANILANLAR", - "Radius Fit": "Yarıçap uydurma", - "Ratio": "Oran", - "Recover": "Kurtar", - "Recover unsaved design?": "Kaydedilmemiş tasarım kurtarılsın mı?", - "Remove Tools": "Araçları kaldır", - "Remove from list": "Listeden kaldır", - "Remove private design details or paths before sharing.": "Paylaşmadan önce özel tasarım ayrıntılarını veya dosya yollarını kaldırın.", - "Remove the column": "Sütunu kaldır", - "Remove the track": "İzi kaldır", - "Remove this point": "Bu noktayı kaldır", - "Report a bug — review a screenshot and open a GitHub draft": "Hata bildir — ekran görüntüsünü kontrol edin ve bir GitHub taslağı açın", - "Reset Toolbar": "Araç çubuğunu sıfırla", - "Restore the inherited component or physical material appearance": "Bileşenden veya fiziksel malzemeden devralınan görünümü geri yükle", - "Result": "Sonuç", - "Retake screenshot": "Ekran görüntüsünü yeniden al", - "Reverse": "Ters çevir", - "Reverse Direction": "Yönü ters çevir", - "Revert": "Geri al", - "Revert All Positions": "Tüm konumları geri al", - "Review the report and screenshot before opening GitHub.": "GitHub'ı açmadan önce raporu ve ekran görüntüsünü gözden geçirin.", - "Rim Edge": "Ağız kenarı", - "Roll History Marker Here": "Geçmiş işaretçisini buraya taşı", - "Rule": "Kural", - "Saved preview. Geometry is being checked before editing.": "Kaydedilmiş önizleme. Düzenlemeden önce geometri kontrol ediliyor.", - "Scale factor": "Ölçek faktörü", - "Search": "Ara", - "Search commands": "Komutlarda ara", - "Select bodies (a face picks its body)": "Gövdeleri seçin (bir yüz kendi gövdesini seçer)", - "Select bodies or faces instead": "Bunun yerine gövde veya yüz seçin", - "Selection filter": "Seçim filtresi", - "Semantic faces share their appearance across instances.": "Anlamsal yüzler görünümlerini örnekler arasında paylaşır.", - "Shape": "Şekil", - "Show Agent Cursor": "Ajan imlecini göster", - "Show in folder": "Klasörde göster", - "Size": "Boyut", - "Sketch plane has no body-face attachment.": "Eskiz düzleminin bir gövde yüzüne bağlaması yok.", - "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft bu tasarımlar kaydedilmeden önce kapandı. Son otomatik kayıtları açılabilir.", - "Speed": "Hız", - "Stand it up": "Dik çevir", - "Stand it up: a quarter turn about X, as one Move feature you can undo.": "Dik çevir: X etrafında çeyrek tur; geri alınabilen tek bir Taşı özelliği olarak eklenir.", - "Stand this part up?": "Bu parça dik çevrilsin mi?", - "Step": "Adım", - "Steps": "Adımlar", - "Suppressed": "Bastırılmış", - "Swap Ends": "Uçları değiştir", - "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.", - "Then": "Sonra", - "These features will be deleted:": "Şu özellikler silinecek:", - "These features will fail:": "Şu özellikler başarısız olacak:", - "This child is shared. Deleting it removes it from every copy of its parent.": "Bu alt öğe paylaşılıyor. Silindiğinde üst öğesinin tüm kopyalarından kaldırılır.", - "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", - "Tolerance": "Tolerans", - "Type": "Tür", - "Updating the preview": "Önizleme güncelleniyor", - "Use fixed plane": "Sabit düzlem kullan", - "VIEW": "GÖRÜNÜM", - "Value": "Değer", - "Volume": "Hacim", - "Wall": "Cidar", - "When": "Eğer", - "Width": "Genişlik", - "Will fail": "Başarısız olacak", - "angle, height": "açı, yükseklik", - "command name": "komut adı", - "expression, e.g. 25 mm": "ifade, ör. 25 mm", - "fits the face, e.g. M8": "yüze uyar, ör. M8", - "from the rule": "kuraldan", - "needs two joints": "iki bağlantı gerektirir", - "new configuration": "yeni konfigürasyon", - "new name": "yeni ad", - "new parameter": "yeni parametre", - "no interference": "girişim yok", - "no joint that moves yet": "henüz hareket eden bir bağlantı yok", - "no picture": "resim yok", - "pick a hole to seat it, or OK places it at the origin": "yerleştirmek için bir delik seçin veya OK ile orijine yerleştirin", - "pick one or two vertices, edges or faces": "bir veya iki köşe noktası, kenar ya da yüz seçin", - "the parts library is not available": "parça kitaplığı kullanılamıyor", - "to the next face": "sonraki yüze kadar", - "Revert Position": "Konumu geri al", - "Construction": "Yapı çizgisi", - "Faces": "Yüzler", - "Edges": "Kenarlar", - "Vertices": "Köşe noktaları", - "Sketch geometry and profiles": "Eskiz geometrisi ve profiller", - "Sketch curves": "Eskiz eğrileri", - "Sketch points": "Eskiz noktaları", - "Sketch dimensions": "Eskiz ölçüleri", - "Sketch constraints": "Eskiz kısıtlamaları", - "0 turns it off": "0 değeri kapatır", - "Show the pointer an AI agent moves (#35)": "Bir AI ajanının hareket ettirdiği imleci göster (#35)", - "Follow the camera (Look At sketches)": "Kamera takibi (eskizlerde Bak)", - "Flat": "Düz", - "Save Rule": "Kuralı kaydet", - "Preview Row": "Satırı önizle", - "Add condition": "Koşul ekle", - "Apply to selection": "Seçime uygula", - "Remove override": "Geçersiz kılmayı kaldır", - "Copy screenshot": "Ekran görüntüsünü kopyala", - "Remove screenshot": "Ekran görüntüsünü kaldır", - "Use active author placement": "Etkin kaynak yerleşimini kullan", - "Reattach selected face": "Seçili yüze yeniden bağla", - "Use saved fixed plane": "Kaydedilmiş sabit düzlemi kullan", - "Use selected face as fixed plane": "Seçili yüzü sabit düzlem olarak kullan", - "View navigator": "Görünüm gezgini", - "Signed axes": "İşaretli eksenler", - "Cube": "Küp", - "Middle double-click": "Orta tuşla çift tıklama", - "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": "Görünümde orta tuşla çift tıklama: Başlangıç (gösterileni çerçeveleyen başlangıç görünümü), Sığdır (yönü koruyarak gösterileni çerçeveler) veya hiçbir şey", - "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).": "Diğerini seç: İmlecin altındaki her şeyi listelemek için sol tuşu model üzerinde hareket ettirmeden basılı tutun (veya sağ tık › Diğerini seç…); oradaki bir sonraki öğeyi seçmek için aynı noktaya tekrar tıklayın. Başlangıç görünümüne dönmek için orta tuşla çift tıklayın (Ayarlar › Gezinme).", - "cmd.render_backends": "Render arka uçları", - "cmd.view_navigate": "Görünümde gezin", - "ui.animateJoint": "Bağlantıyı canlandır", - "ui.calibrate": "Kalibre et", - "ui.customizeToolbar": "Araç çubuğunu özelleştir…", - "ui.editJointLimits": "Bağlantı sınırlarını düzenle", - "ui.exportDxf": "DXF olarak dışa aktar…", - "ui.findInTimeline": "Zaman çizelgesinde bul", - "ui.findInWindow": "Pencerede bul", - "ui.fit": "Sığdır", - "ui.groupSelected": "Seçimi grupla", - "ui.hideAxes": "Eksenleri gizle", - "ui.hideDimension": "Ölçüyü gizle", - "ui.hideOrigin": "Orijini gizle", - "ui.hidePlanes": "Düzlemleri gizle", - "ui.hideProfile": "Profili gizle", - "ui.homeView": "Başlangıç görünümü", - "ui.isolate": "Yalıt", - "ui.lock": "Kilitle", - "ui.newSketchGroup": "Yeni eskiz grubu", - "ui.normalConstruction": "Normal / Yapı", - "ui.orbit": "Döndür", - "ui.heading_position": "KONUM", - "ui.pan": "Kaydır", - "ui.pinToShortcuts": "Kısayollara sabitle", - "ui.pinToToolbar": "Araç çubuğuna sabitle", - "ui.properties": "Özellikler", - "ui.design_properties.project": "Proje", - "ui.design_properties.part_number": "Parça numarası", - "ui.design_properties.revision": "Revizyon", - "ui.design_properties.author": "Yazar", - "ui.design_properties.organization": "Kuruluş", - "ui.design_properties.description": "Açıklama", - "ui.design_properties.license": "Lisans", - "ui.design_properties.not_text": "Metin olarak kaydedilmedi; buraya yapılan bir giriş değerin yerini alır.", - "ui.design_properties.exports": "STEP, IGES ve 3MF dışa aktarımları, biçim bunun için bir alan sunuyorsa bu bilgileri de aktarır.", - "ui.design_properties.others": "Diğer araçların verileri", - "ui.design_properties.others_note": "Tasarımda değişmeden kalır ve asla dışa aktarılmaz.", - "ui.removeSection": "Kesiti kaldır", - "ui.removeFromToolbar": "Araç çubuğundan kaldır", - "ui.repeat": "Tekrarla", - "ui.report_a_bug": "Hata bildir", - "ui.restore": "Geri yükle", - "ui.heading_setup": "KURULUM", - "ui.selectOther": "Diğerini seç…", - "ui.selectTangentChain": "Teğet zinciri seç", - "ui.showAll": "Tümünü göster", - "ui.showAllBodies": "Tüm gövdeleri göster", - "ui.showAxes": "Eksenleri göster", - "ui.showDimension": "Ölçüyü göster", - "ui.showOrigin": "Orijini göster", - "ui.showPlanes": "Düzlemleri göster", - "ui.suppress": "Bastır", - "ui.command_palette_hint": "Bir komut yazın (ör. {example}) — veya aramak için S tuşuna basın", - "ui.unground": "Sabitlemeyi kaldır", - "ui.unisolate": "Yalıtımı kaldır", - "ui.unlock": "Kilidi aç", - "ui.unsuppress": "Bastırmayı kaldır", - "ui.updateToCurrentView": "Geçerli görünüme güncelle", - "ui.zoom": "Yakınlaştır", - "ui.command_done": "{command} tamamlandı", - "drive.stopped_by_loop": "{value} değerinde durdu: {joint} üzerinden geçen döngü daha fazla kapatılamıyor", - "drive.stopped_by_contact": "{value} değerinde durdu: {a} ile {b} iç içe geçerdi", - "drive.unconnected": "Hiçbir şey hareket etmiyor: {part} sabitlenmiş hiçbir parçaya bağlı değil", - "timeline.group": "Yeni özellik klasörü oluştur", - "timeline.ungroup": "Özellik klasörünü kaldır", - "timeline.rename_group": "Özellik klasörünü yeniden adlandır", - "timeline.move_to_group": "Özellikleri klasöre taşı", - "timeline.move_many": "Zaman çizelgesi öğelerini taşı", - "timeline.reorder_many": "Özellikleri yeniden sırala", - "ui.show_construction_geometries": "Yapı geometrileri", - "ui.total_angle": "Toplam açı", - "sketch_text.builtin_font": "{family} (yerleşik)", - "sketch_text.font_search": "Yazı tiplerini ara", - "sketch_text.loading_fonts": "Yüklü yazı tipleri aranıyor…", - "sketch_text.use_font_file": "{path} yazı tipi dosyasını kullan", - "sketch_text.bold": "Kalın", - "sketch_text.italic": "İtalik", - "sketch_text.align_left": "Sol", - "sketch_text.align_center": "Orta", - "sketch_text.align_right": "Sağ", - "sketch_text.path_hint": "Metnin izleyeceği eskiz eğrisi: önce buraya, ardından eğriye tıklayın", - "sketch_text.path_clear": "Metni eğriden ayır", - "Style": "Stil", - "Alignment": "Hizalama", - "Letter Spacing": "Harf aralığı", - "Line Spacing": "Satır aralığı", - "Path": "Yol", - "sketch_text.on_path": "Metin eğrisini izler: konumunu eğri belirler", - "cmd.library_inspect": "Yerel kitaplığı incele", - "cmd.library_export": "Tasarım kitaplığını dışa aktar", - "cmd.library_apply": "Yerel kitaplık girişini uygula", - "Thin": "İnce cidarlı", - "Thin Extrude": "İnce cidarlı ekstrüzyon", - "Wall Location": "Cidar konumu", - "Wall Thickness": "Et kalınlığı", - "Thickness Outside": "Dış kalınlık", - "Inside": "İç", - "Outside": "Dış", - "Profiles/Curves": "Profiller/Eğriler", - "cmd.material_properties_validate": "Fiziksel malzeme verilerini kontrol et", - "cmd.material_properties_directional": "Yöne bağlı elastisite modülü", + "update.available": "SolidCraft {version} kullanılabilir", "update.button": "Güncelle", "update.button_tip": "SolidCraft {version} kullanılabilir", - "install.menu": "Uygulamayı yükle…", - "install.button_tip": "SolidCraft'ı uygulama olarak yükleyin: kendi penceresinde açılır ve çevrimdışı da çalışır", - "install.title": "SolidCraft'ı yükle", - "install.steps_intro": "Safari web uygulamalarını kendi menüleri üzerinden yükler:", - "install.home_screen_1": "“Paylaş” düğmesine dokunun (araç çubuğunda değilse … menüsünde).", - "install.home_screen_2": "“Ana Ekrana Ekle” seçeneğini seçin.", - "install.home_screen_3": "“Ekle” düğmesine dokunun.", - "install.home_screen_after": "SolidCraft daha sonra ana ekrandaki simgesinden, Safari çubukları olmadan açılır ve çevrimdışı da çalışır.", - "install.dock_1": "Dosya › Dock'a Ekle'yi seçin.", - "install.dock_2": "“Ekle” düğmesine tıklayın.", - "install.dock_after": "SolidCraft daha sonra Dock'tan kendi penceresinde açılır ve çevrimdışı da çalışır.", - "install.done": "Bitti", - "update.title": "Güncelleme mevcut", - "update.available": "SolidCraft {version} kullanılabilir", - "update.you_have": "Yüklü sürüm: {version}.", - "update.no_notes": "Bu sürüm için not bulunmuyor.", - "update.system_hint": "Bu kurulum bir {kind}. Şu komutla güncelleyin:", - "update.package_hint": "Bu kurulum bir {kind} kaynağından geliyor. Yeni paketi indirip şu komutla yükleyin:", - "update.copy": "Kopyala", - "update.file": "“İndir” düğmesi {file} dosyasını indirir.", - "update.download": "İndir", - "update.release_page": "Sürüm sayfasını aç", - "update.skip": "Bu sürümü atla", - "update.later": "Daha sonra hatırlat", - "update.prefs_label": "Güncellemeler", "update.check_automatically": "Güncellemeleri otomatik denetle", "update.check_now": "Şimdi denetle", "update.checking": "Denetleniyor…", - "update.failed": "Denetim başarısız: {error}", - "update.up_to_date": "SolidCraft güncel.", - "update.prefs_note": "Bu, SolidCraft {version} ({kind}). Denetim, GitHub'a en yeni sürümü sorar ve başka hiçbir şey göndermez.", - "update.prefs_dev": "Bu bir geliştirme derlemesi ({version}): güncelleme aramaz.", - "update.show": "{version} güncellemesini göster", - "update.prefs_flatpak": "Bu kurulum ({version}) Flatpak tarafından güncellenir: {command} komutunu çalıştırın veya yazılım yöneticisini kullanın. SolidCraft kendisi denetlemez.", - "update.update_now": "Şimdi güncelle", - "update.install_msi": "Yükle (SolidCraft'ı kapatır)", + "update.copy": "Kopyala", + "update.dmg_opened": "Disk görüntüsü açıldı ve doğrulandı: SolidCraft'ı “Uygulamalar” klasörüne sürükleyin, eski sürümü değiştirin ve SolidCraft'ı yeniden başlatın.", + "update.download": "İndir", "update.download_open": "İndir ve aç", "update.downloading": "İndiriliyor ve doğrulanıyor… {done} / {total} MB", + "update.failed": "Denetim başarısız: {error}", + "update.file": "“İndir” düğmesi {file} dosyasını indirir.", + "update.install_failed": "Güncelleme yüklenmedi: {error}. Hiçbir şey değiştirilmedi; paketi “İndir” ile indirebilirsiniz.", + "update.install_msi": "Yükle (SolidCraft'ı kapatır)", "update.installed": "SolidCraft {version} yüklendi. Kullanmak için yeniden başlatın.", + "update.installer_started": "Yükleme programı, SolidCraft kapatıldığında başlar.", + "update.later": "Daha sonra hatırlat", + "update.no_notes": "Bu sürüm için not bulunmuyor.", + "update.package_hint": "Bu kurulum bir {kind} kaynağından geliyor. Yeni paketi indirip şu komutla yükleyin:", + "update.prefs_dev": "Bu bir geliştirme derlemesi ({version}): güncelleme aramaz.", + "update.prefs_flatpak": "Bu kurulum ({version}) Flatpak tarafından güncellenir: {command} komutunu çalıştırın veya yazılım yöneticisini kullanın. SolidCraft kendisi denetlemez.", + "update.prefs_label": "Güncellemeler", + "update.prefs_note": "Bu, SolidCraft {version} ({kind}). Denetim, GitHub'a en yeni sürümü sorar ve başka hiçbir şey göndermez.", + "update.release_page": "Sürüm sayfasını aç", "update.restart": "Şimdi yeniden başlat", "update.restart_later": "Daha sonra", - "update.installer_started": "Yükleme programı, SolidCraft kapatıldığında başlar.", - "update.dmg_opened": "Disk görüntüsü açıldı ve doğrulandı: SolidCraft'ı “Uygulamalar” klasörüne sürükleyin, eski sürümü değiştirin ve SolidCraft'ı yeniden başlatın.", - "update.install_failed": "Güncelleme yüklenmedi: {error}. Hiçbir şey değiştirilmedi; paketi “İndir” ile indirebilirsiniz.", - "cmd.render_settings_get": "Render ayarları", - "cmd.render_settings_set": "Render ayarlarını kaydet", - "cmd.render_scene": "Render sahnesini incele", - "cmd.render_settings_apply": "Render kamerasını uygula", - "toolbar.render": "RENDER", - "toolbar.render_scene": "SAHNE", - "render.preview": "Yerleşik önizleme", - "render.preview_help": "Harmanlanmış saydamlıkla raster görüntü. Kırılma, HDRI ve son render henüz kullanılamıyor.", - "render.setup_name": "Kurulumun adı", - "render.background": "Sahne arka planı", - "render.perspective": "Perspektif kamera", - "render.fit": "Ürünü sığdır", - "render.restore_camera": "Kaydedilmiş kamerayı yükle", - "render.save_setup": "Kurulumu kaydet", - "render.unsaved": "Kaydedilmemiş önizleme değişiklikleri", - "render.reload_settings": "Kaydedilmiş ayarları yükle", - "render.unavailable_preview": "Bu kurulum, kullanılamayan bir önizleme profili gerektiriyor.", - "render.use_preview": "Yerleşik önizlemeyi kullan", - "render.navigation_help": "Kamera, tasarım modundaki gibi hareket eder (Ayarlar › Gezinme). Kurulumu kaydettiğinizde geçerli kamera kaydedilir.", - "render.return_design": "Tasarıma dön", - "render.image_title": "Resmi render et", - "render.image_help": "CPU önizleme resmi · PNG · yaklaşık saydamlık", - "render.image_width": "Genişlik", - "render.image_height": "Yükseklik", - "render.image_transparent": "Saydam arka plan", - "render.image_check": "Render isteğini kontrol et", - "render.image_supported": "Render isteği destekleniyor; kuyruk ve bellek, başlatılırken yeniden kontrol edilir.", - "render.image_queued": "Render için sırada bekliyor", - "render.image_preparing": "Resim hazırlanıyor", - "render.image_running": "Resim render ediliyor", - "render.image_encoding": "PNG kodlanıyor", - "render.image_cancelling": "İptal ediliyor", - "render.image_cancelled": "Render iptal edildi", - "render.image_completed": "Resim dışa aktarmaya hazır", - "render.image_failed": "Render başarısız", - "render.image_unknown": "Render durumu kullanılamıyor", - "render.image_reduce": "Daha küçük bir resim veya daha basit bir sahne deneyin.", - "render.image_too_large": "Resim sınırının üzerinde: kenar başına 4096 piksel ve toplam 4.194.304 piksel.", - "render.image_use_largest": "Bu en-boy oranıyla en büyük boyutu kullan:", - "render.image_cancel": "Render'ı iptal et", - "render.image_stale": "Bu resim, sonraki değişikliklerden önceki sahneyi kullanıyor.", - "render.image_start": "Render'ı başlat", - "render.image_overwrite": "Mevcut dosyanın üzerine yaz", - "render.image_export": "PNG dışa aktar", - "cmd.render_preflight": "Render isteğini kontrol et", - "cmd.render_start": "Resmi render et", - "cmd.render_status": "Render ilerlemesi", - "cmd.render_cancel": "Render'ı iptal et", - "cmd.render_export": "PNG dışa aktar", - "toolbar.image": "RESİM", - "appearance.surface_response": "Yüzey davranışı", - "appearance.pbr_opaque": "Opak PBR", - "appearance.metallic": "Metaliklik", - "appearance.roughness": "Pürüzlülük", - "appearance.dielectric_ior": "Dielektrik kırılma indisi", - "appearance.pbr_help": "Bu yüzeyi Render'da veya bir ürün PNG'sinde görüntüleyin. Kırılma veya geçirgenlik yok.", - "render.opaque_preview_help": "Opak PBR ve düz renkler; saydamlık harmanlanarak gösterilir. Kırılma, HDRI ve son render henüz kullanılamıyor.", - "render.opaque_image_summary": "Önizleme PNG · opak PBR · harmanlanmış saydamlık", - "UNTRIM": "KIRPMAYI KALDIR", - "Face": "Yüz", - "Holes": "Delikler", - "Holes (edges on them)": "Delikler (kenarları)", - "In place (surfaces)": "Yerinde (yüzeyler)", - "None": "Hiçbiri", - "Picked": "Seçilenler", - "Restore outer boundary": "Dış sınırı geri yükle", - "RULED SURFACE": "REGLE YÜZEY", - "Mitre": "Gönye", - "Reference face": "Referans yüzü", - "Round": "Yuvarlak", - "joint.one_component": "Bu parçalar tek bir bileşenin gövdeleridir: {bodies}. Bir bağlantı bir bileşeni diğerine göre hareket ettirir, bu nedenle her parçanın kendi bileşeni olması gerekir.", - "joint.one_body": "Her iki seçim de {body} üzerinde. İkincisini başka bir parçada seçin.", - "joint.from_bodies_hint": "Seçilen her gövde kendi yeni bileşenine konur ve bulunduğu yerde kalır.", - "Circumference": "Çevre", - "Arc length": "Yay uzunluğu", - "Slot width": "Yuva genişliği", - "Centre to centre": "Merkezden merkeze", - "Overall length": "Toplam uzunluk", - "Min": "Min", - "Max": "Maks" + "update.show": "{version} güncellemesini göster", + "update.skip": "Bu sürümü atla", + "update.system_hint": "Bu kurulum bir {kind}. Şu komutla güncelleyin:", + "update.title": "Güncelleme mevcut", + "update.up_to_date": "SolidCraft güncel.", + "update.update_now": "Şimdi güncelle", + "update.you_have": "Yüklü sürüm: {version}." } diff --git a/assets/locales/uk.json b/assets/locales/uk.json index 2e8234ef8..cde0098b9 100644 --- a/assets/locales/uk.json +++ b/assets/locales/uk.json @@ -1,11 +1,247 @@ { - "settings.measure_axis_distances": "Відстані X/Y/Z", - "settings.measure_axis_distances_help": "Показувати розміри вздовж світових осей разом із загальною відстанню, поки відкрите вікно вимірювання.", - "Send your report on GitHub": "Надіслати звіт на GitHub", + "0 turns it off": "0 вимикає це", "1. Open GitHub draft below, then paste the report copied to your clipboard.": "1. Відкрийте чернетку GitHub нижче, а потім вставте звіт, скопійований у буфер обміну.", "1. Open GitHub draft below. Your title and report will be filled in.": "1. Відкрийте чернетку GitHub нижче. Заголовок і звіт буде заповнено.", "2. Attach your screenshot: copy and paste it, or save and upload the PNG.": "2. Додайте знімок екрана: скопіюйте й вставте його або збережіть і завантажте PNG.", "3. Click Submit new issue on GitHub to send your report.": "3. Натисніть Submit new issue на GitHub, щоб надіслати звіт.", + "A new configuration, a copy of the active one": "Нова конфігурація, копія активної", + "About SolidCraft": "Про SolidCraft", + "Active": "Активна", + "Active rule": "Активне правило", + "Add": "Додати", + "Add Key": "Додати клавішу", + "Add Mid Radius": "Додати середній радіус", + "Add Row": "Додати рядок", + "Add condition": "Додати умову", + "Alignment": "Вирівнювання", + "All Sketch Points": "Усі точки ескізу", + "All open designs": "Усі відкриті проєкти", + "Allowed expressions, separated by semicolons": "Дозволені вирази, розділені крапками з комою", + "Also deletes": "Також видаляє", + "Angle 2": "Кут 2", + "Animate": "Анімувати", + "Appearance name": "Назва вигляду", + "Applied Radius": "Застосований радіус", + "Apply To": "Застосувати до", + "Apply to selection": "Застосувати до виділення", + "Area": "Площа", + "Attachment": "Прив'язка", + "BROWSER": "БРАУЗЕР", + "Bend Line Position": "Положення лінії згину", + "Bend Position": "Положення згину", + "Bend Radius": "Радіус згину", + "Bends": "Згини", + "Body": "Тіло", + "Bounding box": "Обмежувальна рамка", + "CSV or JSON: updates existing parameters, adds new ones": "CSV або JSON: оновлює наявні параметри, додає нові", + "Capture All Positions": "Зафіксувати всі положення", + "Catch Direction": "Напрямок зачеплення", + "Cells": "Комірки", + "Center X": "Центр X", + "Center Y": "Центр Y", + "Center of mass": "Центр мас", + "Chamfer Type": "Тип фаски", + "Check collisions": "Перевіряти зіткнення", + "Checked": "Перевірено", + "Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.": "Виберіть нову площину. Геометрія та розміри ескізу залишаються незмінними у своїх двовимірних координатах.", + "Close draft": "Закрити чернетку", + "Collisions": "Зіткнення", + "Colour": "Колір", + "Component1": "Компонент1", + "Configuration": "Конфігурація", + "Configuration rules": "Правила конфігурації", + "Construction": "Конструкційна", + "Contact": "Контакт", + "Copy all licences": "Копіювати всі ліцензії", + "Copy diagnostic information": "Копіювати діагностичну інформацію", + "Copy report": "Копіювати звіт", + "Copy screenshot": "Копіювати знімок екрана", + "Corner Relief": "Полегшення кута", + "Corner Relief Shape": "Форма полегшення кута", + "Counterbore depth": "Глибина циліндричного розширення", + "Countersink angle": "Кут зенкування", + "Create Issue — review draft": "Створити повідомлення про проблему — перегляд чернетки", + "Cube": "Куб", + "Customize Toolbar": "Налаштувати панель інструментів", + "Delete all": "Видалити все", + "Delete rule": "Видалити правило", + "Delete the row": "Видалити рядок", + "Delete the set": "Видалити набір", + "Delete this parameter": "Видалити цей параметр", + "Density": "Густина", + "Designs you open or save appear here.": "Проєкти, які ви відкриваєте чи зберігаєте, з'являються тут.", + "Determined by To Object. Choose Angle to edit the angular extent.": "Визначається об'єктом призначення. Виберіть «Кут», щоб редагувати кутову протяжність.", + "Discard": "Відхилити", + "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": "Керувати з'єднанням", + "Edges": "Ребра", + "Edit Profile Sketch": "Редагувати ескіз профілю", + "Enable rule": "Увімкнути правило", + "Enabled": "Увімкнено", + "Explode": "Рознести", + "Extents": "Межі", + "Face attachment lost": "Втрачено прив'язку до грані", + "Faces": "Грані", + "Faces / edges / vertices": "Грані / ребра / вершини", + "Favourite": "Обране", + "Files from many CAD programs have Y up, so they open lying on their back here (Z up).": "Файли з багатьох CAD-програм мають напрямок Y вгору, тому тут вони відкриваються лежачи на спині (Z вгору).", + "Filter": "Фільтр", + "Find in Browser": "Знайти в браузері", + "Flat": "Плоска", + "Flat size": "Розмір розгортки", + "Follow camera (Look At sketches)": "Стежити за камерою (ескізи наведення)", + "Follow the camera (Look At sketches)": "Стежити за камерою (ескізи наведення)", + "Font": "Шрифт", + "Full Length": "Повна довжина", + "Gap": "Проміжок", + "Grid": "Сітка", + "Height": "Висота", + "Home view": "Головний вид", + "In This Design": "У цьому проєкті", + "Inside": "Усередину", + "Interferes": "Перетинається", + "Issue title": "Заголовок повідомлення", + "Joint Origin1": "Початок з'єднання1", + "Keep Tools": "Зберегти інструменти", + "Later": "Пізніше", + "Leave it": "Залишити як є", + "Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "Застаріла прив'язка до грані. Повторна прив'язка до перевіреної грані створює точну прив'язку.", + "Length": "Довжина", + "Length units": "Одиниці довжини", + "Letter Spacing": "Міжлітерний інтервал", + "Library": "Бібліотека", + "Line Spacing": "Міжрядковий інтервал", + "Loop": "Контур", + "Margin": "Відступ", + "Mass": "Маса", + "Material": "Матеріал", + "Mid Radius": "Середній радіус", + "Middle double-click": "Подвійне клацання середньою кнопкою", + "Modeled": "Змодельовано", + "More toolbar panels": "Більше панелей інструментів", + "Motion": "Рух", + "Move Type": "Тип переміщення", + "Move earlier": "Перемістити раніше", + "Move later": "Перемістити пізніше", + "Name": "Назва", + "No crash reports.": "Немає звітів про збої.", + "No matching appearances": "Немає відповідних виглядів", + "Not available yet": "Ще недоступно", + "Notch": "Виріз", + "Opacity": "Непрозорість", + "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": "Інший бік", + "Outside": "Назовні", + "Parameter values": "Значення параметрів", + "Path": "Траєкторія", + "Per Edge": "На кожне ребро", + "Pick the tool bodies": "Виберіть тіла інструмента", + "Place at the origin instead": "Натомість розмістити в початку координат", + "Playback": "Відтворення", + "Position": "Положення", + "Position (0 to 1)": "Положення (від 0 до 1)", + "Position along the edge, 0 at the start end, 1 at the other": "Положення вздовж ребра: 0 на початку, 1 на іншому кінці", + "Preview Row": "Рядок перегляду", + "Preview leaves the current design unchanged.": "Попередній перегляд не змінює поточний проєкт.", + "Profiles/Curves": "Профілі/криві", + "RECENT": "НЕДАВНІ", + "Radius Fit": "Підгонка за радіусом", + "Ratio": "Співвідношення", + "Reattach selected face": "Повторно приєднати вибрану грань", + "Recover": "Відновити", + "Recover unsaved design?": "Відновити незбережений проєкт?", + "Rectangular": "Прямокутний", + "Remove Tools": "Прибрати інструменти", + "Remove from list": "Прибрати зі списку", + "Remove override": "Прибрати перевизначення", + "Remove private design details or paths before sharing.": "Перед публікацією приберіть приватні дані проєкту або шляхи.", + "Remove screenshot": "Прибрати знімок екрана", + "Remove the column": "Прибрати стовпець", + "Remove the track": "Прибрати доріжку", + "Remove this point": "Прибрати цю точку", + "Report a bug — review a screenshot and open a GitHub draft": "Повідомити про помилку — переглянути знімок екрана й відкрити чернетку GitHub", + "Reset Toolbar": "Скинути панель інструментів", + "Restore the inherited component or physical material appearance": "Відновити успадкований вигляд компонента або фізичного матеріалу", + "Result": "Результат", + "Retake screenshot": "Повторити знімок екрана", + "Reverse": "Обернути", + "Reverse Direction": "Обернути напрямок", + "Revert": "Повернути", + "Revert All Positions": "Повернути всі положення", + "Revert Position": "Повернути положення", + "Review the report and screenshot before opening GitHub.": "Перегляньте звіт і знімок екрана перед відкриттям GitHub.", + "Rim Edge": "Крайове ребро", + "Roll History Marker Here": "Перемістити маркер історії сюди", + "Round": "Круглий", + "Rule": "Правило", + "Save Rule": "Зберегти правило", + "Saved preview. Geometry is being checked before editing.": "Збережений перегляд. Геометрію перевіряють перед редагуванням.", + "Scale factor": "Коефіцієнт масштабу", + "Search": "Пошук", + "Search commands": "Пошук команд", + "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).": "Вибір іншого: утримуйте ліву кнопку нерухомо на моделі (або клацніть правою › Вибрати інше…), щоб побачити список усього під курсором; клацніть ще раз у тому ж місці, щоб вибрати наступний об'єкт там. Двічі клацніть середньою кнопкою, щоб перейти до головного виду (Налаштування › Навігація).", + "Select bodies (a face picks its body)": "Виділяти тіла (грань виділяє своє тіло)", + "Select bodies or faces instead": "Натомість виділіть тіла або грані", + "Selection filter": "Фільтр виділення", + "Semantic faces share their appearance across instances.": "Семантичні грані спільно використовують свій вигляд між екземплярами.", + "Send your report on GitHub": "Надіслати звіт на GitHub", + "Shape": "Форма", + "Show Agent Cursor": "Показати курсор агента", + "Show in folder": "Показати в теці", + "Show the pointer an AI agent moves (#35)": "Показувати вказівник, яким рухає ШІ-агент (#35)", + "Signed axes": "Підписані осі", + "Size": "Розмір", + "Sketch constraints": "Обмеження ескізу", + "Sketch curves": "Криві ескізу", + "Sketch dimensions": "Розміри ескізу", + "Sketch geometry and profiles": "Геометрія та профілі ескізу", + "Sketch plane has no body-face attachment.": "Площина ескізу не має прив'язки до грані тіла.", + "Sketch points": "Точки ескізу", + "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft закрився до того, як ці проєкти було збережено. Можна відкрити їхнє останнє автозбереження.", + "Speed": "Швидкість", + "Stand it up": "Вирівняти", + "Stand it up: a quarter turn about X, as one Move feature you can undo.": "Вирівняти: поворот на чверть оберту навколо X як одна операція переміщення, яку можна скасувати.", + "Stand this part up?": "Вирівняти цю деталь?", + "Step": "Крок", + "Steps": "Кроки", + "Style": "Стиль", + "Suppressed": "Придушено", + "Swap Ends": "Поміняти кінці місцями", + "Tangent Chain": "Дотичний ланцюг", + "Tear": "Розрив", + "The dashed sketch is a saved plane guide. Select a new face to repair the attachment.": "Штриховий ескіз — це збережений орієнтир площини. Виберіть нову грань, щоб відновити прив'язку.", + "The saved author occurrence is missing. Select a valid author placement before rebinding.": "Збережений вихідний екземпляр відсутній. Перед повторною прив'язкою виберіть дійсне вихідне розміщення.", + "Then": "Потім", + "These features will be deleted:": "Ці операції буде видалено:", + "These features will fail:": "Ці операції зазнають невдачі:", + "Thickness Outside": "Товщина назовні", + "Thin": "Тонкий", + "Thin Extrude": "Тонке видавлювання", + "This child is shared. Deleting it removes it from 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.": "Ця грань не може забезпечити надійну прив'язку. Виберіть іншу грань або явно використайте фіксовану площину.", + "To Offset": "До зсуву", + "Tolerance": "Допуск", + "Type": "Тип", + "Updating the preview": "Оновлення попереднього перегляду", + "Use active author placement": "Використати активне вихідне розміщення", + "Use fixed plane": "Використати фіксовану площину", + "Use saved fixed plane": "Використати збережену фіксовану площину", + "Use selected face as fixed plane": "Використати вибрану грань як фіксовану площину", + "VIEW": "ВИД", + "Value": "Значення", + "Vertices": "Вершини", + "View navigator": "Навігатор виду", + "Volume": "Об'єм", + "Wall": "Стінка", + "Wall Location": "Розташування стінки", + "Wall Thickness": "Товщина стінки", + "When": "Коли", + "Width": "Ширина", + "Will fail": "Зазнає невдачі", + "angle, height": "кут, висота", "browser.body_name": "Тіло{number}", "browser.component_name": "Компонент{number}", "browser.parameters": "Параметри ({count})", @@ -32,7 +268,6 @@ "cmd.component_capture_position": "Зафіксувати положення", "cmd.component_create": "Новий компонент", "cmd.component_delete": "Видалити компонент", - "cmd.component_unlock": "Розблокувати вміст", "cmd.component_from_bodies": "Створити компоненти з тіл", "cmd.component_insert_design": "Вставити проєкт", "cmd.component_links": "Список зв'язків", @@ -43,6 +278,7 @@ "cmd.component_properties": "Фізичні властивості компонента", "cmd.component_rename": "Перейменувати компонент", "cmd.component_revert_position": "Відновити положення", + "cmd.component_unlock": "Розблокувати вміст", "cmd.component_update_links": "Оновити зв'язки", "cmd.config_activate": "Активувати конфігурацію", "cmd.config_column": "Стовпець конфігурації", @@ -101,6 +337,7 @@ "cmd.inspect_accessibility": "Аналіз доступності", "cmd.inspect_center_of_mass": "Центр мас", "cmd.inspect_compare": "Порівняти тіла", + "cmd.inspect_continuity": "Аналіз неперервності", "cmd.inspect_curvature_comb": "Аналіз гребеня кривизни", "cmd.inspect_curvature_map": "Аналіз карти кривизни", "cmd.inspect_draft": "Аналіз ухилу", @@ -114,20 +351,25 @@ "cmd.joint_delete": "Видалити з'єднання", "cmd.joint_drive": "Керувати з'єднаннями", "cmd.joint_edit": "Редагувати з'єднання", + "cmd.joint_gear": "Зубчаста передача", "cmd.joint_limits": "Обмеження з'єднання", "cmd.joint_list": "Список з'єднань", "cmd.joint_motion_link": "Зв'язок руху", - "cmd.joint_gear": "Зубчаста передача", - "cmd.joint_rack_pinion": "Рейкова передача", - "cmd.joint_screw": "Гвинт", "cmd.joint_origin": "Початок з'єднання", + "cmd.joint_rack_pinion": "Рейкова передача", "cmd.joint_rigid_group": "Жорстка група", + "cmd.joint_screw": "Гвинт", "cmd.joint_solve": "Розв'язати з'єднання", + "cmd.library_apply": "Застосувати елемент локальної бібліотеки", + "cmd.library_export": "Експортувати бібліотеку проєкту", + "cmd.library_inspect": "Перевірити локальну бібліотеку", "cmd.material_assign": "Фізичний матеріал", "cmd.material_create": "Новий фізичний матеріал", "cmd.material_delete": "Видалити фізичний матеріал", "cmd.material_edit": "Редагувати фізичний матеріал", "cmd.material_list": "Список матеріалів", + "cmd.material_properties_directional": "Спрямований модуль пружності", + "cmd.material_properties_validate": "Перевірити дані фізичного матеріалу", "cmd.mesh_convert": "Перетворити сітку", "cmd.model_edges": "Список ребер", "cmd.model_faces": "Список граней", @@ -148,10 +390,10 @@ "cmd.parameters_delete": "Видалити параметр", "cmd.parameters_export": "Експортувати параметри", "cmd.parameters_favorite": "Обраний параметр", - "cmd.parameters_move": "Перемістити параметр", "cmd.parameters_graph": "Граф параметрів", "cmd.parameters_import": "Імпортувати параметри", "cmd.parameters_list": "Список параметрів", + "cmd.parameters_move": "Перемістити параметр", "cmd.parameters_rename": "Перейменувати параметр", "cmd.parameters_users": "Користувачі параметра", "cmd.parts_fastener": "Вставити кріплення", @@ -165,6 +407,7 @@ "cmd.plastic_rest": "Упор", "cmd.plastic_rules": "Список правил пластику", "cmd.plastic_snap_fit": "Клацкове з'єднання", + "cmd.render_backends": "Рендер-бекенди", "cmd.select_clear": "Зняти виділення", "cmd.sheet_convert": "Перетворити на листовий метал", "cmd.sheet_export_bend_table": "Експортувати таблицю згинів", @@ -260,22 +503,21 @@ "cmd.solid_rib": "Ребро", "cmd.solid_split_face": "Розділити грань", "cmd.solid_web": "Перемичка", - "cmd.surface_patch": "Латка", - "cmd.surface_stitch": "Зшити", - "cmd.surface_thicken": "Потовщити", - "cmd.surface_extrude": "Видавлювання поверхні", - "cmd.surface_revolve": "Обертання поверхні", - "cmd.surface_sweep": "Протягування поверхні", - "cmd.surface_loft": "Лофт поверхні", - "cmd.surface_ruled": "Лінійчаста поверхня", - "cmd.surface_boundary": "Поверхня за межами", - "cmd.surface_offset": "Зсунута поверхня", "cmd.surface_blend": "Сполучна поверхня", + "cmd.surface_boundary": "Поверхня за межами", + "cmd.surface_extrude": "Видавлювання поверхні", "cmd.surface_fillet": "Заокруглення поверхні", - "cmd.surface_untrim": "Зняти обрізання", - "cmd.surface_unstitch": "Розшити", + "cmd.surface_loft": "Лофт поверхні", + "cmd.surface_offset": "Зсунута поверхня", + "cmd.surface_patch": "Латка", "cmd.surface_reverse_normal": "Обернути нормаль", - "cmd.inspect_continuity": "Аналіз неперервності", + "cmd.surface_revolve": "Обертання поверхні", + "cmd.surface_ruled": "Лінійчаста поверхня", + "cmd.surface_stitch": "Зшити", + "cmd.surface_sweep": "Протягування поверхні", + "cmd.surface_thicken": "Потовщити", + "cmd.surface_unstitch": "Розшити", + "cmd.surface_untrim": "Зняти обрізання", "cmd.timeline_add": "Додати записану операцію", "cmd.timeline_compute_all": "Обчислити все", "cmd.timeline_copy": "Копіювати операції", @@ -292,17 +534,65 @@ "cmd.view_apply": "Відновити іменований вид", "cmd.view_delete": "Видалити іменований вид", "cmd.view_list": "Список іменованих видів", + "cmd.view_navigate": "Навігація видом", "cmd.view_rename": "Перейменувати іменований вид", "cmd.view_save": "Новий іменований вид", + "command name": "назва команди", + "coupling.gear_1": "Шестерня 1", + "coupling.gear_1_pick": "Шестерня 1 (необов'язково)", + "coupling.gear_2": "Шестерня 2", + "coupling.gear_2_pick": "Шестерня 2 (необов'язково)", + "coupling.internal": "Внутрішнє зачеплення", + "coupling.needs_turn_and_slide": "потрібні обертове й ковзне з'єднання", + "coupling.needs_turns": "потрібні два обертові з'єднання", + "coupling.not_round": "не кругла грань", + "coupling.nut": "Гайка", + "coupling.picked": "вибрано", + "coupling.pinion": "Шестерня", + "coupling.pinion_pick": "Шестерня (необов'язково)", + "coupling.pitch": "Крок", + "coupling.rack": "Рейка", + "coupling.radius_1": "Радіус 1", + "coupling.radius_2": "Радіус 2", "dialog.custom_axis": "↖ Власна вісь", "dialog.edit_title": "РЕДАГУВАННЯ {title}", "dialog.select": "↖ Вибрати", "dialog.selected_count": "↖ Вибрано: {count}", - "dialog.step": "Крок", - "dialog.selection_step": "Крок {step} з {total}: виберіть {input}", "dialog.selection_guidance": "Виберіть вхідні дані, щоб змінити їх. Клацніть вибрані об'єкти, щоб прибрати їх; натискання з Ctrl/Cmd також перемикає їх. Перегляньте попередній перегляд, а потім натисніть OK.", + "dialog.selection_step": "Крок {step} з {total}: виберіть {input}", + "dialog.step": "Крок", "document.save_changes": "Зберегти зміни в {name}?", "document.unsaved_changes": "У {name} є незбережені зміни. Якщо не зберегти, вони будуть втрачені.", + "drive.unconnected": "Нічого не рухається: {part} не з'єднано ні з чим закріпленим", + "expression, e.g. 25 mm": "вираз, напр. 25 mm", + "fits the face, e.g. M8": "відповідає грані, напр. M8", + "from the rule": "з правила", + "install.button_tip": "Встановити SolidCraft як застосунок: він відкривається в окремому вікні й працює без мережі", + "install.dock_1": "Виберіть «Файл» › «Додати в Dock».", + "install.dock_2": "Натисніть «Додати».", + "install.dock_after": "Після цього SolidCraft відкривається з Dock в окремому вікні й працює без мережі.", + "install.done": "Готово", + "install.home_screen_1": "Торкніться «Поширити» (у меню …, якщо цієї кнопки немає на панелі).", + "install.home_screen_2": "Виберіть «На початковий екран».", + "install.home_screen_3": "Торкніться «Додати».", + "install.home_screen_after": "Після цього SolidCraft відкривається значком на початковому екрані, без панелей Safari, і працює без мережі.", + "install.menu": "Встановити застосунок…", + "install.steps_intro": "Safari встановлює вебзастосунки через власні меню:", + "install.title": "Встановлення SolidCraft", + "joint.from_bodies_hint": "Кожне вибране тіло переходить у власний новий компонент і лишається на місці.", + "joint.one_body": "Обидва вибори на {body}. Виберіть другий на іншій деталі.", + "joint.one_component": "Ці деталі - тіла одного компонента: {bodies}. З'єднання рухає один компонент відносно іншого, тому кожній деталі потрібен власний компонент.", + "needs two joints": "потрібні два з'єднання", + "new configuration": "нова конфігурація", + "new name": "нова назва", + "new parameter": "новий параметр", + "no interference": "немає перетинів", + "no joint that moves yet": "ще немає рухомого з'єднання", + "no picture": "немає зображення", + "pick a hole to seat it, or OK places it at the origin": "виберіть отвір для посадки, або OK розмістить його в початку координат", + "pick one or two vertices, edges or faces": "виберіть одну-дві вершини, ребра або грані", + "settings.measure_axis_distances": "Відстані X/Y/Z", + "settings.measure_axis_distances_help": "Показувати розміри вздовж світових осей разом із загальною відстанню, поки відкрите вікно вимірювання.", "settings.msaa_applies_on_restart": "Згладжування застосується під час наступного запуску SolidCraft", "settings.msaa_reset": "{setting}: {requested}× не підтримується цим графічним пристроєм; тепер це {reset}× (підтримується: {supported}).", "settings.msaa_unsupported": "Не підтримується цим графічним пристроєм", @@ -311,6 +601,26 @@ "sketch.degrees_of_freedom": "{count} ступенів вільності", "sketch.draw_curves": "Малювати як {linetype}", "sketch.make_selection": "Перетворити виділене на {linetype}", + "sketch_text.align_center": "По центру", + "sketch_text.align_left": "Ліворуч", + "sketch_text.align_right": "Праворуч", + "sketch_text.bold": "Жирний", + "sketch_text.builtin_font": "{family} (вбудований)", + "sketch_text.font_search": "Пошук шрифтів", + "sketch_text.italic": "Курсив", + "sketch_text.loading_fonts": "Пошук встановлених шрифтів…", + "sketch_text.on_path": "Текст дотримується своєї траєкторії: крива його розміщує", + "sketch_text.path_clear": "Зняти текст з його кривої", + "sketch_text.path_hint": "Крива ескізу, якої дотримується текст: клацніть тут, а потім на кривій", + "sketch_text.use_font_file": "Використати файл шрифту {path}", + "the parts library is not available": "бібліотека деталей недоступна", + "timeline.group": "Нова тека операцій", + "timeline.move_many": "Перемістити елементи часового ланцюжка", + "timeline.move_to_group": "Перемістити операції до теки", + "timeline.rename_group": "Перейменувати теку операцій", + "timeline.reorder_many": "Перевпорядкувати операції", + "timeline.ungroup": "Прибрати теки операцій", + "to the next face": "до наступної грані", "ui.1_degree_of_freedom": "1 ступінь вільності", "ui.3d_mouse_speed": "Швидкість 3D-миші", "ui.3d_mouse_windows": "3D-миша", @@ -324,6 +634,7 @@ "ui.analysis": "Аналіз", "ui.angle": "Кут", "ui.angle_decimals": "Знаки після коми для кутів", + "ui.animateJoint": "Анімувати з'єднання", "ui.animate_view_changes": "Анімувати зміни виду", "ui.animation": "Анімація", "ui.animation_speed": "Швидкість анімації", @@ -338,6 +649,7 @@ "ui.bodies": "Тіла", "ui.box": "Куб", "ui.break": "Розірвати", + "ui.calibrate": "Калібрувати", "ui.cancel": "Скасувати", "ui.canvases": "Полотна", "ui.center": "Центр", @@ -347,8 +659,6 @@ "ui.chamfer_type": "Тип фаски", "ui.change_workspace": "Змінити робочу область", "ui.chord_length": "Довжина хорди", - "ui.curvature_g2": "Кривизна (G2)", - "ui.equivalent_radius": "Еквівалентний радіус", "ui.circle": "Коло", "ui.circular_pattern": "Круговий масив", "ui.clear": "Очистити", @@ -357,34 +667,14 @@ "ui.click_selects_whole_bodies": "Клацання виділяє тіла цілком", "ui.click_then_press_key": "Клацніть, а потім натисніть нову клавішу", "ui.close": "Закрити", - "ui.material_review.title": "Перевірка фізичних даних матеріалу", - "ui.material_review.scope": "Лише кандидат: без призначення та збереження. Числова перевірка не є інженерною сертифікацією.", - "ui.material_review.input": "Вставте картку матеріалу за схемою 1 (JSON)", - "ui.material_review.review": "Перевірити картку", - "ui.material_review.limit": "Картка перевищує межу введення 256 КіБ.", - "ui.material_review.unknown": "Невідомо", - "ui.material_review.properties": "Властивості", - "ui.material_review.conditions": "Зазначені умови", - "ui.material_review.source": "Джерело", - "ui.material_review.axes": "Локальні осі матеріалу; орієнтація тіла не призначається.", - "ui.material_review.derived": "Обчислені ізотропні модулі", - "ui.material_review.claims": "Джерела та ліцензії зазначені без перевірки. Відсутні значення залишаються невідомими.", - "ui.material_review.density": "Густина", - "ui.material_review.elasticity": "Пружність", - "ui.material_review.tensile_strength": "Міцність на розтяг", - "ui.material_review.compressive_strength": "Міцність на стиск", - "ui.material_review.yield_strength": "Межа плинності", - "ui.material_review.shear_strength": "Міцність на зсув", - "ui.material_review.thermal_conductivity": "Теплопровідність", - "ui.material_review.thermal_expansion": "Теплове розширення", - "ui.material_review.specific_heat": "Питома теплоємність", - "ui.material_review.moisture_unit": "кг води / кг сухого матеріалу", "ui.coil": "Спіраль", "ui.coincident": "Співпадання", "ui.collapse": "Згорнути", "ui.collinear": "Колінеарність", "ui.combine": "Об'єднати", "ui.coming_later": "з'явиться пізніше", + "ui.command_done": "{command} виконано", + "ui.command_palette_hint": "Введіть команду, напр. {example} — або натисніть S для пошуку", "ui.concentric": "Концентричність", "ui.configurations": "Конфігурації", "ui.conic_curve": "Конічна крива", @@ -403,7 +693,9 @@ "ui.create_sketch": "Створити ескіз", "ui.current": "поточний", "ui.curvature": "Кривизна", + "ui.curvature_g2": "Кривизна (G2)", "ui.curves": "Криві", + "ui.customizeToolbar": "Налаштувати панель інструментів…", "ui.cut": "Вирізати", "ui.cylinder": "Циліндр", "ui.dark": "Темна", @@ -424,12 +716,16 @@ "ui.drawing": "Креслення", "ui.drill_point": "Вістря свердла", "ui.edit": "Редагувати", + "ui.editJointLimits": "Редагувати обмеження з'єднання", "ui.edit_section_analysis": "Редагувати аналіз перерізу", "ui.ellipse": "Еліпс", "ui.end_radius": "Кінцевий радіус", + "ui.end_scale": "Масштаб у кінці", "ui.entities": "Елементи", "ui.equal": "Рівність", + "ui.equivalent_radius": "Еквівалентний радіус", "ui.expand": "Розгорнути", + "ui.exportDxf": "Експорт DXF…", "ui.export_ellipsis": "Експорт...", "ui.export_ellipsis_keymap": "Експорт…", "ui.export_keymap_tip": "Клавіші, обрані в полі S і панель інструментів як файл", @@ -443,7 +739,10 @@ "ui.file": "Файл", "ui.fillet": "Заокруглення", "ui.filter_commands_or_keys": "Фільтрувати команди або клавіші", + "ui.findInTimeline": "Знайти в часовому ланцюжку", + "ui.findInWindow": "Знайти у вікні", "ui.finish_sketch": "Завершити ескіз", + "ui.fit": "Вписати", "ui.fix_unfix": "Закріпити/розкріпити", "ui.flat": "Плоска", "ui.flip": "Перевернути", @@ -452,6 +751,7 @@ "ui.general": "Загальні", "ui.graphics": "Графіка", "ui.ground_shadow": "Тінь на землі", + "ui.groupSelected": "Згрупувати виділене", "ui.heading_add_ins": "НАДБУДОВИ", "ui.heading_assemble": "СКЛАДАННЯ", "ui.heading_box": "КУБ", @@ -483,8 +783,8 @@ "ui.heading_mirror": "ДЗЕРКАЛО", "ui.heading_modify": "ЗМІНИТИ", "ui.heading_move": "ПЕРЕМІСТИТИ", - "ui.heading_offset": "ЗСУВ", "ui.heading_move_copy": "ПЕРЕМІСТИТИ/КОПІЮВАТИ", + "ui.heading_offset": "ЗСУВ", "ui.heading_offset_plane": "ЗСУНУТА ПЛОЩИНА", "ui.heading_ok": "OK", "ui.heading_parameters": "ПАРАМЕТРИ", @@ -492,6 +792,7 @@ "ui.heading_pipe": "ТРУБА", "ui.heading_plane_at_angle": "ПЛОЩИНА ПІД КУТОМ", "ui.heading_plastic": "ПЛАСТИК", + "ui.heading_position": "ПОЛОЖЕННЯ", "ui.heading_prepare": "ПІДГОТУВАТИ", "ui.heading_rectangular_pattern": "ПРЯМОКУТНИЙ МАСИВ", "ui.heading_revolve": "ОБЕРТАННЯ", @@ -499,6 +800,7 @@ "ui.heading_scale": "МАСШТАБ", "ui.heading_section_analysis": "АНАЛІЗ ПЕРЕРІЗУ", "ui.heading_select": "ВИБІР", + "ui.heading_setup": "НАЛАШТУВАННЯ", "ui.heading_sheet_metal": "ЛИСТОВИЙ МЕТАЛ", "ui.heading_shell": "ОБОЛОНКА", "ui.heading_sketch": "ЕСКІЗ", @@ -516,15 +818,22 @@ "ui.heading_utility": "УТИЛІТА", "ui.help": "Довідка", "ui.hide": "Приховати", + "ui.hideAxes": "Приховати осі", + "ui.hideDimension": "Приховати розмір", + "ui.hideOrigin": "Приховати початок координат", + "ui.hidePlanes": "Приховати площини", + "ui.hideProfile": "Приховати профіль", "ui.hole": "Отвір", "ui.hole_tap_type": "Тип різьби отвору", "ui.hole_type": "Тип отвору", "ui.home": "Головна", + "ui.homeView": "Головний вид", "ui.horizontal_vertical": "Горизонталь/вертикаль", "ui.import_ellipsis": "Імпорт…", "ui.insert": "Вставити", "ui.inspect": "Перевірити", "ui.intersect": "Перетин", + "ui.isolate": "Ізолювати", "ui.join": "З'єднати", "ui.joints": "З'єднання", "ui.keyboard_shortcuts": "Комбінації клавіш", @@ -533,10 +842,33 @@ "ui.light": "Світла", "ui.line": "Пряма", "ui.linetype": "Тип лінії", + "ui.lock": "Заблокувати", "ui.loft": "Лофт", "ui.look_at": "Наведення", "ui.look_at_anim_desc": "Вид осі, наведення, головний і вписування", "ui.manufacture": "Виготовлення", + "ui.material_review.axes": "Локальні осі матеріалу; орієнтація тіла не призначається.", + "ui.material_review.claims": "Джерела та ліцензії зазначені без перевірки. Відсутні значення залишаються невідомими.", + "ui.material_review.compressive_strength": "Міцність на стиск", + "ui.material_review.conditions": "Зазначені умови", + "ui.material_review.density": "Густина", + "ui.material_review.derived": "Обчислені ізотропні модулі", + "ui.material_review.elasticity": "Пружність", + "ui.material_review.input": "Вставте картку матеріалу за схемою 1 (JSON)", + "ui.material_review.limit": "Картка перевищує межу введення 256 КіБ.", + "ui.material_review.moisture_unit": "кг води / кг сухого матеріалу", + "ui.material_review.properties": "Властивості", + "ui.material_review.review": "Перевірити картку", + "ui.material_review.scope": "Лише кандидат: без призначення та збереження. Числова перевірка не є інженерною сертифікацією.", + "ui.material_review.shear_strength": "Міцність на зсув", + "ui.material_review.source": "Джерело", + "ui.material_review.specific_heat": "Питома теплоємність", + "ui.material_review.tensile_strength": "Міцність на розтяг", + "ui.material_review.thermal_conductivity": "Теплопровідність", + "ui.material_review.thermal_expansion": "Теплове розширення", + "ui.material_review.title": "Перевірка фізичних даних матеріалу", + "ui.material_review.unknown": "Невідомо", + "ui.material_review.yield_strength": "Межа плинності", "ui.measure": "Вимірювання", "ui.midpoint": "Середня точка", "ui.mirror": "Дзеркало", @@ -547,9 +879,11 @@ "ui.named_views": "Іменовані види", "ui.navigation": "Навігація", "ui.needs_design": "{command}: спершу відкрийте проєкт", + "ui.newSketchGroup": "Нова група ескізів", "ui.new_body": "Нове тіло", "ui.new_design": "Новий проєкт", "ui.normal": "Звичайна", + "ui.normalConstruction": "Звичайна / конструкційна", "ui.object_type": "Тип об'єкта", "ui.objects": "Об'єкти", "ui.offer_to_stand_up_y_up_files": "Пропонувати вирівнювати файли з напрямком Y вгору", @@ -562,10 +896,13 @@ "ui.open_recent": "Відкрити недавні", "ui.operation": "Операція", "ui.options": "Параметри", + "ui.orbit": "Обертати", "ui.orbit_around": "Обертати навколо", + "ui.orientation": "Орієнтація", "ui.origin": "Початок координат", "ui.palette_points": "Точки", "ui.palette_profile": "Профіль", + "ui.pan": "Панорамувати", "ui.pan_zoom_orbit": "Панорамування, масштаб, обертання", "ui.parallel": "Паралельність", "ui.parameters": "Параметри", @@ -574,6 +911,8 @@ "ui.pattern_on_path": "Масив на траєкторії", "ui.perpendicular": "Перпендикулярність", "ui.perspective_view": "Перспективний вид", + "ui.pinToShortcuts": "Закріпити в комбінаціях клавіш", + "ui.pinToToolbar": "Закріпити на панелі інструментів", "ui.pipe": "Труба", "ui.placement": "Розміщення", "ui.plane": "Площина", @@ -589,6 +928,7 @@ "ui.profiles": "Профілі", "ui.project": "Проєктувати", "ui.project_face_edges_sketch": "Проєктувати ребра граней у нові ескізи", + "ui.properties": "Властивості", "ui.quantity": "Кількість", "ui.quantity_2": "Кількість 2", "ui.quit": "Вихід", @@ -598,11 +938,16 @@ "ui.rectangle": "Прямокутник", "ui.rectangular_pattern": "Прямокутний масив", "ui.redo": "Повторити", + "ui.removeFromToolbar": "Прибрати з панелі інструментів", + "ui.removeSection": "Прибрати розріз", "ui.render": "Візуалізувати", "ui.renderer": "Рендерер", + "ui.repeat": "Повторити", + "ui.report_a_bug": "Повідомити про помилку", "ui.reset": "Скинути", "ui.reset_all": "Скинути все", "ui.reset_the_settings_on_this_page": "Скинути налаштування на цій сторінці", + "ui.restore": "Відновити", "ui.restore_defaults": "Відновити типові", "ui.reverse_zoom_direction": "Змінити напрямок масштабування", "ui.revolve": "Обертання", @@ -611,19 +956,22 @@ "ui.save_as": "Зберегти як", "ui.save_as_ellipsis": "Зберегти як...", "ui.scale": "Масштаб", - "ui.orientation": "Орієнтація", - "ui.twist": "Закручування", - "ui.end_scale": "Масштаб у кінці", - "ui.sweep_turn_with_path": "Повертати за траєкторією", - "ui.sweep_keep_as_drawn": "Як намальовано", - "ui.sweep_follow_direction": "Слідувати напрямку", "ui.section_analysis": "Аналіз перерізу", "ui.select": "Вибрати", + "ui.selectOther": "Вибрати інше…", + "ui.selectTangentChain": "Вибрати дотичний ланцюг", "ui.select_other_hint": "Вибір іншого: утримуйте ліву кнопку нерухомо на моделі (або клацніть правою › Вибрати інше…), щоб побачити список усього під курсором; клацніть ще раз у тому ж місці, щоб вибрати наступний об'єкт там.", "ui.selection": "Виділення", "ui.shell": "Оболонка", "ui.show": "Показати", + "ui.showAll": "Показати все", + "ui.showAllBodies": "Показати всі тіла", + "ui.showAxes": "Показати осі", + "ui.showDimension": "Показати розмір", + "ui.showOrigin": "Показати початок координат", + "ui.showPlanes": "Показати площини", "ui.show_constraints": "Обмеження", + "ui.show_construction_geometries": "Конструкційна геометрія", "ui.show_dimensions": "Розміри", "ui.show_points": "Показати точки", "ui.show_profile": "Показати профіль", @@ -653,7 +1001,11 @@ "ui.stand_up_tip": "Після відкриття файлу STEP або IGES з напрямком Z вгору пропонувати поворот на чверть оберту навколо X", "ui.start": "Початок", "ui.start_radius": "Початковий радіус", + "ui.suppress": "Придушити", "ui.sweep": "Протягування", + "ui.sweep_follow_direction": "Слідувати напрямку", + "ui.sweep_keep_as_drawn": "Як намальовано", + "ui.sweep_turn_with_path": "Повертати за траєкторією", "ui.symmetric": "Симетричний", "ui.symmetry": "Симетрія", "ui.system": "Системна", @@ -671,16 +1023,23 @@ "ui.to_object": "До об'єкта", "ui.top": "Зверху", "ui.torus": "Тор", + "ui.total_angle": "Загальний кут", "ui.trackpad_pan_tip": "Жести трекпада виконують панорамування (вимкнено: масштабують, як колесо); колесо миші масштабує, бічне колесо панорамує вбік, стискання завжди масштабує", "ui.trim": "Обрізати", + "ui.twist": "Закручування", "ui.two_finger_scroll_pans": "Прокрутка двома пальцями виконує панорамування", "ui.two_sides": "Два боки", "ui.ui_scale": "Масштаб інтерфейсу", "ui.undo": "Скасувати", + "ui.unground": "Розкріпити", + "ui.unisolate": "Зняти ізоляцію", "ui.units": "Одиниці", "ui.units_of_new_designs": "Одиниці нових проєктів", + "ui.unlock": "Розблокувати", + "ui.unsuppress": "Скасувати придушення", "ui.untitled": "Без назви", "ui.up_axis_note": "Яка вісь спрямована вгору у видах (вид осі, головний, наведення). Проєкти не змінюються.", + "ui.updateToCurrentView": "Оновити до поточного виду", "ui.variable": "Змінна", "ui.view_centre": "Центр виду", "ui.visual_shaded_hidden_edges": "Затінений із прихованими ребрами", @@ -692,400 +1051,41 @@ "ui.y_distance": "Відстань Y", "ui.y_up": "Y вгору", "ui.z_up": "Z вгору", + "ui.zoom": "Масштабувати", "ui.zoom_to_cursor_tip": "Колесо масштабує до точки під курсором (вимкнено: до центру виду)", "ui.zoom_to_the_cursor": "Масштабувати до курсора", - "A new configuration, a copy of the active one": "Нова конфігурація, копія активної", - "About SolidCraft": "Про SolidCraft", - "Active": "Активна", - "Active rule": "Активне правило", - "Add": "Додати", - "Add Key": "Додати клавішу", - "Add Mid Radius": "Додати середній радіус", - "Add Row": "Додати рядок", - "All Sketch Points": "Усі точки ескізу", - "All open designs": "Усі відкриті проєкти", - "Allowed expressions, separated by semicolons": "Дозволені вирази, розділені крапками з комою", - "Also deletes": "Також видаляє", - "Angle 2": "Кут 2", - "Animate": "Анімувати", - "Appearance name": "Назва вигляду", - "Applied Radius": "Застосований радіус", - "Apply To": "Застосувати до", - "Area": "Площа", - "Attachment": "Прив'язка", - "BROWSER": "БРАУЗЕР", - "Bend Line Position": "Положення лінії згину", - "Bend Position": "Положення згину", - "Bend Radius": "Радіус згину", - "Bends": "Згини", - "Body": "Тіло", - "Bounding box": "Обмежувальна рамка", - "CSV or JSON: updates existing parameters, adds new ones": "CSV або JSON: оновлює наявні параметри, додає нові", - "Capture All Positions": "Зафіксувати всі положення", - "Catch Direction": "Напрямок зачеплення", - "Cells": "Комірки", - "Center X": "Центр X", - "Center Y": "Центр Y", - "Center of mass": "Центр мас", - "Chamfer Type": "Тип фаски", - "Check collisions": "Перевіряти зіткнення", - "Checked": "Перевірено", - "Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.": "Виберіть нову площину. Геометрія та розміри ескізу залишаються незмінними у своїх двовимірних координатах.", - "Close draft": "Закрити чернетку", - "Collisions": "Зіткнення", - "Colour": "Колір", - "Component1": "Компонент1", - "Configuration": "Конфігурація", - "Configuration rules": "Правила конфігурації", - "Contact": "Контакт", - "Copy all licences": "Копіювати всі ліцензії", - "Copy diagnostic information": "Копіювати діагностичну інформацію", - "Copy report": "Копіювати звіт", - "Corner Relief": "Полегшення кута", - "Corner Relief Shape": "Форма полегшення кута", - "Notch": "Виріз", - "Round": "Круглий", - "Rectangular": "Прямокутний", - "Tear": "Розрив", - "Counterbore depth": "Глибина циліндричного розширення", - "Countersink angle": "Кут зенкування", - "Create Issue — review draft": "Створити повідомлення про проблему — перегляд чернетки", - "Customize Toolbar": "Налаштувати панель інструментів", - "Delete all": "Видалити все", - "Delete rule": "Видалити правило", - "Delete the row": "Видалити рядок", - "Delete the set": "Видалити набір", - "Delete this parameter": "Видалити цей параметр", - "Density": "Густина", - "Designs you open or save appear here.": "Проєкти, які ви відкриваєте чи зберігаєте, з'являються тут.", - "Determined by To Object. Choose Angle to edit the angular extent.": "Визначається об'єктом призначення. Виберіть «Кут», щоб редагувати кутову протяжність.", - "Discard": "Відхилити", - "Double-click to rename": "Двічі клацніть, щоб перейменувати", - "Drive Joint": "Керувати з'єднанням", - "Edit Profile Sketch": "Редагувати ескіз профілю", - "Enable rule": "Увімкнути правило", - "Enabled": "Увімкнено", - "Explode": "Рознести", - "Extents": "Межі", - "Face attachment lost": "Втрачено прив'язку до грані", - "Faces / edges / vertices": "Грані / ребра / вершини", - "Favourite": "Обране", - "Files from many CAD programs have Y up, so they open lying on their back here (Z up).": "Файли з багатьох CAD-програм мають напрямок Y вгору, тому тут вони відкриваються лежачи на спині (Z вгору).", - "Filter": "Фільтр", - "Find in Browser": "Знайти в браузері", - "Flat size": "Розмір розгортки", - "Follow camera (Look At sketches)": "Стежити за камерою (ескізи наведення)", - "Font": "Шрифт", - "Full Length": "Повна довжина", - "Gap": "Проміжок", - "Grid": "Сітка", - "Height": "Висота", - "Home view": "Головний вид", - "In This Design": "У цьому проєкті", - "Interferes": "Перетинається", - "Issue title": "Заголовок повідомлення", - "Joint Origin1": "Початок з'єднання1", - "Keep Tools": "Зберегти інструменти", - "Later": "Пізніше", - "Leave it": "Залишити як є", - "Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "Застаріла прив'язка до грані. Повторна прив'язка до перевіреної грані створює точну прив'язку.", - "Length": "Довжина", - "Length units": "Одиниці довжини", - "Library": "Бібліотека", - "Loop": "Контур", - "Margin": "Відступ", - "Mass": "Маса", - "Material": "Матеріал", - "Mid Radius": "Середній радіус", - "Modeled": "Змодельовано", - "More toolbar panels": "Більше панелей інструментів", - "Motion": "Рух", - "Move Type": "Тип переміщення", - "Move earlier": "Перемістити раніше", - "Move later": "Перемістити пізніше", - "Name": "Назва", - "No crash reports.": "Немає звітів про збої.", - "No matching appearances": "Немає відповідних виглядів", - "Not available yet": "Ще недоступно", - "Opacity": "Непрозорість", - "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": "Інший бік", - "Parameter values": "Значення параметрів", - "Per Edge": "На кожне ребро", - "Pick the tool bodies": "Виберіть тіла інструмента", - "Place at the origin instead": "Натомість розмістити в початку координат", - "Playback": "Відтворення", - "Position": "Положення", - "Position (0 to 1)": "Положення (від 0 до 1)", - "Position along the edge, 0 at the start end, 1 at the other": "Положення вздовж ребра: 0 на початку, 1 на іншому кінці", - "Preview leaves the current design unchanged.": "Попередній перегляд не змінює поточний проєкт.", - "RECENT": "НЕДАВНІ", - "Radius Fit": "Підгонка за радіусом", - "Ratio": "Співвідношення", - "Recover": "Відновити", - "Recover unsaved design?": "Відновити незбережений проєкт?", - "Remove Tools": "Прибрати інструменти", - "Remove from list": "Прибрати зі списку", - "Remove private design details or paths before sharing.": "Перед публікацією приберіть приватні дані проєкту або шляхи.", - "Remove the column": "Прибрати стовпець", - "Remove the track": "Прибрати доріжку", - "Remove this point": "Прибрати цю точку", - "Report a bug — review a screenshot and open a GitHub draft": "Повідомити про помилку — переглянути знімок екрана й відкрити чернетку GitHub", - "Reset Toolbar": "Скинути панель інструментів", - "Restore the inherited component or physical material appearance": "Відновити успадкований вигляд компонента або фізичного матеріалу", - "Result": "Результат", - "Retake screenshot": "Повторити знімок екрана", - "Reverse": "Обернути", - "Reverse Direction": "Обернути напрямок", - "Revert": "Повернути", - "Revert All Positions": "Повернути всі положення", - "Review the report and screenshot before opening GitHub.": "Перегляньте звіт і знімок екрана перед відкриттям GitHub.", - "Rim Edge": "Крайове ребро", - "Roll History Marker Here": "Перемістити маркер історії сюди", - "Rule": "Правило", - "Saved preview. Geometry is being checked before editing.": "Збережений перегляд. Геометрію перевіряють перед редагуванням.", - "Scale factor": "Коефіцієнт масштабу", - "Search": "Пошук", - "Search commands": "Пошук команд", - "Select bodies (a face picks its body)": "Виділяти тіла (грань виділяє своє тіло)", - "Select bodies or faces instead": "Натомість виділіть тіла або грані", - "Selection filter": "Фільтр виділення", - "Semantic faces share their appearance across instances.": "Семантичні грані спільно використовують свій вигляд між екземплярами.", - "Shape": "Форма", - "Show Agent Cursor": "Показати курсор агента", - "Show in folder": "Показати в теці", - "Size": "Розмір", - "Sketch plane has no body-face attachment.": "Площина ескізу не має прив'язки до грані тіла.", - "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft закрився до того, як ці проєкти було збережено. Можна відкрити їхнє останнє автозбереження.", - "Speed": "Швидкість", - "Stand it up": "Вирівняти", - "Stand it up: a quarter turn about X, as one Move feature you can undo.": "Вирівняти: поворот на чверть оберту навколо X як одна операція переміщення, яку можна скасувати.", - "Stand this part up?": "Вирівняти цю деталь?", - "Step": "Крок", - "Steps": "Кроки", - "Suppressed": "Придушено", - "Swap Ends": "Поміняти кінці місцями", - "Tangent Chain": "Дотичний ланцюг", - "The dashed sketch is a saved plane guide. Select a new face to repair the attachment.": "Штриховий ескіз — це збережений орієнтир площини. Виберіть нову грань, щоб відновити прив'язку.", - "The saved author occurrence is missing. Select a valid author placement before rebinding.": "Збережений вихідний екземпляр відсутній. Перед повторною прив'язкою виберіть дійсне вихідне розміщення.", - "Then": "Потім", - "These features will be deleted:": "Ці операції буде видалено:", - "These features will fail:": "Ці операції зазнають невдачі:", - "This child is shared. Deleting it removes it from 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.": "Ця грань не може забезпечити надійну прив'язку. Виберіть іншу грань або явно використайте фіксовану площину.", - "To Offset": "До зсуву", - "Tolerance": "Допуск", - "Type": "Тип", - "Updating the preview": "Оновлення попереднього перегляду", - "Use fixed plane": "Використати фіксовану площину", - "VIEW": "ВИД", - "Value": "Значення", - "Volume": "Об'єм", - "Wall": "Стінка", - "When": "Коли", - "Width": "Ширина", - "Will fail": "Зазнає невдачі", - "angle, height": "кут, висота", - "command name": "назва команди", - "expression, e.g. 25 mm": "вираз, напр. 25 mm", - "fits the face, e.g. M8": "відповідає грані, напр. M8", - "from the rule": "з правила", - "needs two joints": "потрібні два з'єднання", - "new configuration": "нова конфігурація", - "new name": "нова назва", - "new parameter": "новий параметр", - "no interference": "немає перетинів", - "no joint that moves yet": "ще немає рухомого з'єднання", - "no picture": "немає зображення", - "pick a hole to seat it, or OK places it at the origin": "виберіть отвір для посадки, або OK розмістить його в початку координат", - "pick one or two vertices, edges or faces": "виберіть одну-дві вершини, ребра або грані", - "the parts library is not available": "бібліотека деталей недоступна", - "to the next face": "до наступної грані", - "Revert Position": "Повернути положення", - "Construction": "Конструкційна", - "Faces": "Грані", - "Edges": "Ребра", - "Vertices": "Вершини", - "Sketch geometry and profiles": "Геометрія та профілі ескізу", - "Sketch curves": "Криві ескізу", - "Sketch points": "Точки ескізу", - "Sketch dimensions": "Розміри ескізу", - "Sketch constraints": "Обмеження ескізу", - "0 turns it off": "0 вимикає це", - "Show the pointer an AI agent moves (#35)": "Показувати вказівник, яким рухає ШІ-агент (#35)", - "Follow the camera (Look At sketches)": "Стежити за камерою (ескізи наведення)", - "Flat": "Плоска", - "Save Rule": "Зберегти правило", - "Preview Row": "Рядок перегляду", - "Add condition": "Додати умову", - "Apply to selection": "Застосувати до виділення", - "Remove override": "Прибрати перевизначення", - "Copy screenshot": "Копіювати знімок екрана", - "Remove screenshot": "Прибрати знімок екрана", - "Use active author placement": "Використати активне вихідне розміщення", - "Reattach selected face": "Повторно приєднати вибрану грань", - "Use saved fixed plane": "Використати збережену фіксовану площину", - "Use selected face as fixed plane": "Використати вибрану грань як фіксовану площину", - "View navigator": "Навігатор виду", - "Signed axes": "Підписані осі", - "Cube": "Куб", - "Middle double-click": "Подвійне клацання середньою кнопкою", - "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": "Подвійне клацання середньою кнопкою у виді: головний (головний вид, що охоплює показане), вписування (охопити показане, зберігаючи орієнтацію) або нічого", - "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).": "Вибір іншого: утримуйте ліву кнопку нерухомо на моделі (або клацніть правою › Вибрати інше…), щоб побачити список усього під курсором; клацніть ще раз у тому ж місці, щоб вибрати наступний об'єкт там. Двічі клацніть середньою кнопкою, щоб перейти до головного виду (Налаштування › Навігація).", - "cmd.render_backends": "Рендер-бекенди", - "cmd.view_navigate": "Навігація видом", - "ui.animateJoint": "Анімувати з'єднання", - "ui.calibrate": "Калібрувати", - "ui.customizeToolbar": "Налаштувати панель інструментів…", - "ui.editJointLimits": "Редагувати обмеження з'єднання", - "ui.exportDxf": "Експорт DXF…", - "ui.findInTimeline": "Знайти в часовому ланцюжку", - "ui.findInWindow": "Знайти у вікні", - "ui.fit": "Вписати", - "ui.groupSelected": "Згрупувати виділене", - "ui.hideAxes": "Приховати осі", - "ui.hideDimension": "Приховати розмір", - "ui.hideOrigin": "Приховати початок координат", - "ui.hidePlanes": "Приховати площини", - "ui.hideProfile": "Приховати профіль", - "ui.homeView": "Головний вид", - "ui.isolate": "Ізолювати", - "ui.lock": "Заблокувати", - "ui.newSketchGroup": "Нова група ескізів", - "ui.normalConstruction": "Звичайна / конструкційна", - "ui.orbit": "Обертати", - "ui.heading_position": "ПОЛОЖЕННЯ", - "ui.pan": "Панорамувати", - "ui.pinToShortcuts": "Закріпити в комбінаціях клавіш", - "ui.pinToToolbar": "Закріпити на панелі інструментів", - "ui.properties": "Властивості", - "ui.removeSection": "Прибрати розріз", - "ui.removeFromToolbar": "Прибрати з панелі інструментів", - "ui.repeat": "Повторити", - "ui.report_a_bug": "Повідомити про помилку", - "ui.restore": "Відновити", - "ui.heading_setup": "НАЛАШТУВАННЯ", - "ui.selectOther": "Вибрати інше…", - "ui.selectTangentChain": "Вибрати дотичний ланцюг", - "ui.showAll": "Показати все", - "ui.showAllBodies": "Показати всі тіла", - "ui.showAxes": "Показати осі", - "ui.showDimension": "Показати розмір", - "ui.showOrigin": "Показати початок координат", - "ui.showPlanes": "Показати площини", - "ui.suppress": "Придушити", - "ui.command_palette_hint": "Введіть команду, напр. {example} — або натисніть S для пошуку", - "ui.unground": "Розкріпити", - "ui.unisolate": "Зняти ізоляцію", - "ui.unlock": "Розблокувати", - "ui.unsuppress": "Скасувати придушення", - "ui.updateToCurrentView": "Оновити до поточного виду", - "ui.zoom": "Масштабувати", - "ui.command_done": "{command} виконано", - "timeline.group": "Нова тека операцій", - "timeline.ungroup": "Прибрати теки операцій", - "timeline.rename_group": "Перейменувати теку операцій", - "timeline.move_to_group": "Перемістити операції до теки", - "timeline.move_many": "Перемістити елементи часового ланцюжка", - "timeline.reorder_many": "Перевпорядкувати операції", - "ui.show_construction_geometries": "Конструкційна геометрія", - "ui.total_angle": "Загальний кут", - "sketch_text.builtin_font": "{family} (вбудований)", - "sketch_text.font_search": "Пошук шрифтів", - "sketch_text.loading_fonts": "Пошук встановлених шрифтів…", - "sketch_text.use_font_file": "Використати файл шрифту {path}", - "sketch_text.bold": "Жирний", - "sketch_text.italic": "Курсив", - "sketch_text.align_left": "Ліворуч", - "sketch_text.align_center": "По центру", - "sketch_text.align_right": "Праворуч", - "sketch_text.path_hint": "Крива ескізу, якої дотримується текст: клацніть тут, а потім на кривій", - "sketch_text.path_clear": "Зняти текст з його кривої", - "Style": "Стиль", - "Alignment": "Вирівнювання", - "Letter Spacing": "Міжлітерний інтервал", - "Line Spacing": "Міжрядковий інтервал", - "Path": "Траєкторія", - "sketch_text.on_path": "Текст дотримується своєї траєкторії: крива його розміщує", - "cmd.library_inspect": "Перевірити локальну бібліотеку", - "cmd.library_export": "Експортувати бібліотеку проєкту", - "cmd.library_apply": "Застосувати елемент локальної бібліотеки", - "Thin": "Тонкий", - "Thin Extrude": "Тонке видавлювання", - "Wall Location": "Розташування стінки", - "Wall Thickness": "Товщина стінки", - "Thickness Outside": "Товщина назовні", - "Inside": "Усередину", - "Outside": "Назовні", - "Profiles/Curves": "Профілі/криві", - "cmd.material_properties_validate": "Перевірити дані фізичного матеріалу", - "cmd.material_properties_directional": "Спрямований модуль пружності", + "update.available": "Доступна версія SolidCraft {version}", "update.button": "Оновити", "update.button_tip": "Доступна версія SolidCraft {version}", - "install.menu": "Встановити застосунок…", - "install.button_tip": "Встановити SolidCraft як застосунок: він відкривається в окремому вікні й працює без мережі", - "install.title": "Встановлення SolidCraft", - "install.steps_intro": "Safari встановлює вебзастосунки через власні меню:", - "install.home_screen_1": "Торкніться «Поширити» (у меню …, якщо цієї кнопки немає на панелі).", - "install.home_screen_2": "Виберіть «На початковий екран».", - "install.home_screen_3": "Торкніться «Додати».", - "install.home_screen_after": "Після цього SolidCraft відкривається значком на початковому екрані, без панелей Safari, і працює без мережі.", - "install.dock_1": "Виберіть «Файл» › «Додати в Dock».", - "install.dock_2": "Натисніть «Додати».", - "install.dock_after": "Після цього SolidCraft відкривається з Dock в окремому вікні й працює без мережі.", - "install.done": "Готово", - "update.title": "Доступне оновлення", - "update.available": "Доступна версія SolidCraft {version}", - "update.you_have": "У вас версія {version}.", - "update.no_notes": "Цей випуск не має приміток.", - "update.system_hint": "Ця копія — {kind}. Оновіть її за допомогою:", - "update.package_hint": "Ця копія походить з {kind}. Завантажте новий пакет, а потім установіть його за допомогою:", - "update.copy": "Копіювати", - "update.file": "Завантаження отримає {file}.", - "update.download": "Завантажити", - "update.release_page": "Відкрити сторінку випуску", - "update.skip": "Пропустити цю версію", - "update.later": "Нагадати пізніше", - "update.prefs_label": "Оновлення", "update.check_automatically": "Автоматично перевіряти оновлення", "update.check_now": "Перевірити зараз", "update.checking": "Перевірка…", - "update.failed": "Не вдалося перевірити: {error}", - "update.up_to_date": "SolidCraft оновлено.", - "update.prefs_note": "Це SolidCraft {version} ({kind}). Перевірка запитує в GitHub останній випуск і більше нічого не надсилає.", - "update.prefs_dev": "Це збірка для розробки ({version}): вона не перевіряє оновлення.", - "update.show": "Показати оновлення до {version}", - "update.prefs_flatpak": "Flatpak оновлює цю копію ({version}): виконайте {command} або скористайтеся центром програм. SolidCraft не перевіряє.", - "update.update_now": "Оновити зараз", - "update.install_msi": "Установити (закриє SolidCraft)", + "update.copy": "Копіювати", + "update.dmg_opened": "Образ диска відкрито й перевірено: перетягніть SolidCraft до Applications, замінивши стару копію, а потім перезапустіть SolidCraft.", + "update.download": "Завантажити", "update.download_open": "Завантажити й відкрити", "update.downloading": "Завантаження та перевірка… {done} з {total} МБ", + "update.failed": "Не вдалося перевірити: {error}", + "update.file": "Завантаження отримає {file}.", + "update.install_failed": "Оновлення не встановлено: {error}. Нічого не змінено; натомість «Завантажити» отримає пакет.", + "update.install_msi": "Установити (закриє SolidCraft)", "update.installed": "SolidCraft {version} установлено. Перезапустіть, щоб скористатися.", + "update.installer_started": "Інсталятор запуститься, коли SolidCraft закриється.", + "update.later": "Нагадати пізніше", + "update.no_notes": "Цей випуск не має приміток.", + "update.package_hint": "Ця копія походить з {kind}. Завантажте новий пакет, а потім установіть його за допомогою:", + "update.prefs_dev": "Це збірка для розробки ({version}): вона не перевіряє оновлення.", + "update.prefs_flatpak": "Flatpak оновлює цю копію ({version}): виконайте {command} або скористайтеся центром програм. SolidCraft не перевіряє.", + "update.prefs_label": "Оновлення", + "update.prefs_note": "Це SolidCraft {version} ({kind}). Перевірка запитує в GitHub останній випуск і більше нічого не надсилає.", + "update.release_page": "Відкрити сторінку випуску", "update.restart": "Перезапустити зараз", "update.restart_later": "Пізніше", - "update.installer_started": "Інсталятор запуститься, коли SolidCraft закриється.", - "update.dmg_opened": "Образ диска відкрито й перевірено: перетягніть SolidCraft до Applications, замінивши стару копію, а потім перезапустіть SolidCraft.", - "update.install_failed": "Оновлення не встановлено: {error}. Нічого не змінено; натомість «Завантажити» отримає пакет.", - "drive.unconnected": "Нічого не рухається: {part} не з'єднано ні з чим закріпленим", - "joint.one_component": "Ці деталі - тіла одного компонента: {bodies}. З'єднання рухає один компонент відносно іншого, тому кожній деталі потрібен власний компонент.", - "joint.one_body": "Обидва вибори на {body}. Виберіть другий на іншій деталі.", - "joint.from_bodies_hint": "Кожне вибране тіло переходить у власний новий компонент і лишається на місці.", - "coupling.gear_1": "Шестерня 1", - "coupling.gear_2": "Шестерня 2", - "coupling.pinion": "Шестерня", - "coupling.rack": "Рейка", - "coupling.nut": "Гайка", - "coupling.radius_1": "Радіус 1", - "coupling.radius_2": "Радіус 2", - "coupling.internal": "Внутрішнє зачеплення", - "coupling.pitch": "Крок", - "coupling.picked": "вибрано", - "coupling.not_round": "не кругла грань", - "coupling.gear_1_pick": "Шестерня 1 (необов'язково)", - "coupling.gear_2_pick": "Шестерня 2 (необов'язково)", - "coupling.pinion_pick": "Шестерня (необов'язково)", - "coupling.needs_turns": "потрібні два обертові з'єднання", - "coupling.needs_turn_and_slide": "потрібні обертове й ковзне з'єднання" + "update.show": "Показати оновлення до {version}", + "update.skip": "Пропустити цю версію", + "update.system_hint": "Ця копія — {kind}. Оновіть її за допомогою:", + "update.title": "Доступне оновлення", + "update.up_to_date": "SolidCraft оновлено.", + "update.update_now": "Оновити зараз", + "update.you_have": "У вас версія {version}." } diff --git a/assets/locales/zh.json b/assets/locales/zh.json index 6c79eb623..7b7565333 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -1,29 +1,286 @@ { - "settings.measure_axis_distances": "显示 X/Y/Z 距离", - "settings.measure_axis_distances_help": "测量对话框打开时,在总距离之外显示沿世界坐标轴方向的尺寸线和距离。", - "Export Current View as DXF": "将当前视图导出为DXF", - "Export Current View as DXF…": "将当前视图导出为DXF…", - "Hidden edges": "隐藏线", - "Do not export hidden edges": "不导出隐藏线", - "Export hidden edges as dashed lines": "以虚线导出隐藏线", - "Projection": "投影", - "Current perspective view": "当前透视视图", - "Current orthographic view (1:1 mm)": "当前正交视图(1:1毫米)", - "Visible bodies only. Curves use line segments (0.01 mm tolerance).": "仅导出可见实体。曲线以线段近似(公差0.01毫米)。", - "Turn off section analysis before exporting the view.": "请关闭截面分析后再导出视图。", - "No visible bodies to export.": "没有可导出的可见实体。", - "Export DXF…": "导出DXF…", - "Send your report on GitHub": "在 GitHub 上发送报告", + "0 turns it off": "0 表示关闭", "1. Open GitHub draft below, then paste the report copied to your clipboard.": "1. 点击下方按钮打开 GitHub 草稿,然后粘贴已复制到剪贴板的报告。", "1. Open GitHub draft below. Your title and report will be filled in.": "1. 点击下方按钮打开 GitHub 草稿。标题和报告将自动填入。", "2. Attach your screenshot: copy and paste it, or save and upload the PNG.": "2. 附上截图:复制并粘贴,或保存为 PNG 后上传。", "3. Click Submit new issue on GitHub to send your report.": "3. 在 GitHub 上点击 Submit new issue 发送报告。", - "nav.touchpad.label": "触控板", - "nav.touchpad.help": "按住 Shift 并移动指针可平移;按住 Alt/Option 并移动可旋转。无需按鼠标按钮。垂直滚动可缩放。", - "nav.touchpad.orbit": "旋转(按住 Alt/Option 并移动,无需鼠标按钮)", - "nav.touchpad.pan": "平移(按住 Shift 并移动,无需鼠标按钮)", - "nav.touchpad.zoom": "缩放(垂直滚动或双指捏合)", - "nav.touchpad.scroll": "触控板使用垂直滚动进行缩放。双指平移设置将保留供其他预设使用。", + "A new configuration, a copy of the active one": "新建配置,为当前配置的副本", + "AI": "AI", + "About SolidCraft": "关于 SolidCraft", + "Active": "活动", + "Active rule": "活动规则", + "Add": "添加", + "Add Key": "添加按键", + "Add Mid Radius": "添加中间半径", + "Add Row": "添加行", + "Add condition": "添加条件", + "Alignment": "对齐", + "All Sketch Points": "所有草图点", + "All open designs": "所有打开的设计", + "Allowed expressions, separated by semicolons": "允许的表达式,以分号分隔", + "Also deletes": "同时删除", + "Angle 2": "角度 2", + "Animate": "动画", + "Appearance name": "外观名称", + "Applied Radius": "应用半径", + "Apply To": "应用于", + "Apply to selection": "应用到选择", + "Arc length": "弧长", + "Area": "面积", + "Attachment": "附着", + "BROWSER": "浏览器", + "Bend Line Position": "弯折线位置", + "Bend Position": "折弯位置", + "Bend Radius": "折弯半径", + "Bends": "折弯", + "Body": "实体", + "Bounding box": "边界框", + "CSV or JSON: updates existing parameters, adds new ones": "CSV 或 JSON:更新现有参数、添加新参数", + "Capture All Positions": "捕获所有位置", + "Catch Direction": "卡扣方向", + "Cells": "区域", + "Center X": "中心 X", + "Center Y": "中心 Y", + "Center of mass": "质心", + "Centre to centre": "中心距", + "Chamfer Type": "倒角类型", + "Check collisions": "检查碰撞", + "Checked": "已检查", + "Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.": "选择一个新平面。草图几何和尺寸在其二维坐标中保持不变。", + "Circumference": "周长", + "Close draft": "关闭草稿", + "Collisions": "碰撞", + "Colour": "颜色", + "Component1": "组件1", + "Configuration": "配置", + "Configuration rules": "配置规则", + "Construction": "构造", + "Contact": "接触", + "Copy Error Message": "复制错误消息", + "Copy Warning Message": "复制警告消息", + "Copy all licences": "复制所有许可证", + "Copy diagnostic information": "复制诊断信息", + "Copy report": "复制报告", + "Copy screenshot": "复制截图", + "Corner Relief": "拐角释放", + "Corner Relief Shape": "拐角释放形状", + "Counterbore depth": "沉孔深度", + "Countersink angle": "沉头角度", + "Create Issue — review draft": "创建 Issue——审阅草稿", + "Cube": "立方体", + "Current orthographic view (1:1 mm)": "当前正交视图(1:1毫米)", + "Current perspective view": "当前透视视图", + "Customize Toolbar": "自定义工具栏", + "Delete all": "全部删除", + "Delete rule": "删除规则", + "Delete the row": "删除此行", + "Delete the set": "删除此集合", + "Delete this parameter": "删除此参数", + "Density": "密度", + "Designs you open or save appear here.": "你打开或保存的设计会显示在此处。", + "Determined by To Object. Choose Angle to edit the angular extent.": "由“到对象”确定。选择“角度”可编辑角度范围。", + "Discard": "放弃", + "Do not export hidden edges": "不导出隐藏线", + "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": "驱动接头", + "Edges": "边", + "Edit Profile Sketch": "编辑轮廓草图", + "Enable rule": "启用规则", + "Enabled": "已启用", + "Explode": "爆炸", + "Export Current View as DXF": "将当前视图导出为DXF", + "Export Current View as DXF…": "将当前视图导出为DXF…", + "Export DXF…": "导出DXF…", + "Export hidden edges as dashed lines": "以虚线导出隐藏线", + "Extents": "范围", + "Face": "面", + "Face attachment lost": "面附着丢失", + "Faces": "面", + "Faces / edges / vertices": "面 / 边 / 顶点", + "Favourite": "收藏", + "Files from many CAD programs have Y up, so they open lying on their back here (Z up).": "许多 CAD 程序的文件以 Y 为上轴,因此在此处打开时会平躺(Z 朝上)。", + "Filter": "筛选", + "Find in Browser": "在浏览器中查找", + "Flat": "平面", + "Flat size": "平板尺寸", + "Follow camera (Look At sketches)": "跟随相机(注视草图)", + "Follow the camera (Look At sketches)": "跟随相机(注视草图)", + "Font": "字体", + "Full Length": "全长", + "Gap": "间隙", + "Grid": "网格", + "Height": "高度", + "Hidden edges": "隐藏线", + "Holes": "孔", + "Holes (edges on them)": "孔(孔上的边)", + "Home view": "主视图", + "In This Design": "在此设计中", + "In place (surfaces)": "原位(曲面)", + "Inside": "内侧", + "Interferes": "发生干涉", + "Issue title": "Issue 标题", + "Joint Origin1": "接头原点1", + "Keep Tools": "保留工具", + "Later": "稍后", + "Leave it": "保持原样", + "Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "旧版面附着。重新绑定到经验证的面可创建精确附着。", + "Length": "长度", + "Length units": "长度单位", + "Letter Spacing": "字间距", + "Library": "零件库", + "Line Spacing": "行间距", + "Loop": "循环", + "Margin": "余量", + "Mass": "质量", + "Material": "材质", + "Max": "最大", + "Mid Radius": "中间半径", + "Middle double-click": "中键双击", + "Min": "最小", + "Mitre": "斜接", + "Modeled": "已建模", + "More toolbar panels": "更多工具栏面板", + "Motion": "运动", + "Move Type": "移动类型", + "Move earlier": "向前移动", + "Move later": "向后移动", + "Name": "名称", + "No crash reports.": "没有崩溃报告。", + "No matching appearances": "没有匹配的外观", + "No visible bodies to export.": "没有可导出的可见实体。", + "None": "无", + "Not available yet": "暂不可用", + "Notch": "缺口", + "Opacity": "不透明度", + "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": "另一侧", + "Outside": "外侧", + "Overall length": "总长", + "Parameter values": "参数值", + "Path": "路径", + "Per Edge": "每条边", + "Pick the tool bodies": "选择工具实体", + "Picked": "所选", + "Place at the origin instead": "改为放置在原点", + "Playback": "播放", + "Position": "位置", + "Position (0 to 1)": "位置(0 到 1)", + "Position along the edge, 0 at the start end, 1 at the other": "沿边的位置,起点端为 0,另一端为 1", + "Preview Row": "预览行", + "Preview leaves the current design unchanged.": "预览不会更改当前设计。", + "Profiles/Curves": "轮廓/曲线", + "Projection": "投影", + "RECENT": "最近使用", + "RULED SURFACE": "直纹曲面", + "Radius Fit": "半径拟合", + "Ratio": "比率", + "Reattach selected face": "重新附着所选面", + "Recover": "恢复", + "Recover unsaved design?": "恢复未保存的设计?", + "Rectangular": "矩形", + "Reference face": "参考面", + "Remove Tools": "移除工具", + "Remove from list": "从列表移除", + "Remove override": "移除覆盖", + "Remove private design details or paths before sharing.": "共享前请移除私密设计细节或路径。", + "Remove screenshot": "移除截图", + "Remove the column": "移除此列", + "Remove the track": "移除轨迹", + "Remove this point": "移除此点", + "Report a bug — review a screenshot and open a GitHub draft": "报告缺陷 — 复核截图并开启 GitHub 草稿", + "Reset Toolbar": "重置工具栏", + "Restore outer boundary": "恢复外边界", + "Restore the inherited component or physical material appearance": "还原继承的组件或物理材质外观", + "Result": "结果", + "Retake screenshot": "重新截图", + "Reverse": "反向", + "Reverse Direction": "反向", + "Revert": "还原", + "Revert All Positions": "还原所有位置", + "Revert Position": "恢复位置", + "Review the report and screenshot before opening GitHub.": "打开 GitHub 前请审阅报告和截图。", + "Rim Edge": "轮缘边", + "Roll History Marker Here": "将历史标记滚动到此处", + "Round": "圆角", + "Rule": "规则", + "Save Rule": "保存规则", + "Saved preview. Geometry is being checked before editing.": "已保存预览。编辑前正在检查几何。", + "Scale factor": "比例因子", + "Search": "搜索", + "Search commands": "搜索命令", + "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).": "“选择其他”:在模型上按住左键(或右键单击 › 选择其他…)列出光标下的所有对象;在同一位置再次单击可选择该处的下一个对象。双击中键转到主视图(首选项 › 导航)。", + "Select bodies (a face picks its body)": "选择实体(单击面即选择其所属实体)", + "Select bodies or faces instead": "改为选择实体或面", + "Selection filter": "选择筛选", + "Semantic faces share their appearance across instances.": "语义面在各实例间共享外观。", + "Send your report on GitHub": "在 GitHub 上发送报告", + "Shape": "形状", + "Show Agent Cursor": "显示代理光标", + "Show in folder": "在文件夹中显示", + "Show the pointer an AI agent moves (#35)": "显示 AI 代理移动的指针(#35)", + "Signed axes": "带符号轴", + "Size": "大小", + "Sketch constraints": "草图约束", + "Sketch curves": "草图曲线", + "Sketch dimensions": "草图尺寸", + "Sketch geometry and profiles": "草图几何和轮廓", + "Sketch plane has no body-face attachment.": "草图平面没有实体面附着。", + "Sketch points": "草图点", + "Slot width": "槽宽", + "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft 在这些设计保存前已关闭。可以打开它们的上次自动保存。", + "Speed": "速度", + "Stand it up": "将其立起", + "Stand it up: a quarter turn about X, as one Move feature you can undo.": "将其立起:绕 X 轴旋转四分之一周,作为一个可撤销的移动特征。", + "Stand this part up?": "立起此零件?", + "Step": "步骤", + "Steps": "步数", + "Style": "样式", + "Suppressed": "已抑制", + "Swap Ends": "交换端点", + "Tangent Chain": "相切链", + "Tear": "撕裂", + "The dashed sketch is a saved plane guide. Select a new face to repair the attachment.": "虚线草图是已保存的平面引导。选择一个新面以修复附着。", + "The saved author occurrence is missing. Select a valid author placement before rebinding.": "保存的作者实例缺失。重新绑定前请选择有效的作者放置。", + "Then": "操作", + "These features will be deleted:": "以下特征将被删除:", + "These features will fail:": "以下特征将失败:", + "Thickness Outside": "外侧厚度", + "Thin": "薄壁", + "Thin Extrude": "薄壁拉伸", + "This child is shared. Deleting it removes it from 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.": "此面无法提供持久附着。请选择其他面或显式使用固定平面。", + "To Offset": "偏移", + "Tolerance": "公差", + "Turn off section analysis before exporting the view.": "请关闭截面分析后再导出视图。", + "Type": "类型", + "UNTRIM": "取消修剪", + "Updating the preview": "正在更新预览", + "Use active author placement": "使用活动作者放置", + "Use fixed plane": "使用固定平面", + "Use saved fixed plane": "使用已保存的固定平面", + "Use selected face as fixed plane": "使用所选面作为固定平面", + "VIEW": "视图", + "Value": "值", + "Vertices": "顶点", + "View navigator": "视图导航器", + "Visible bodies only. Curves use line segments (0.01 mm tolerance).": "仅导出可见实体。曲线以线段近似(公差0.01毫米)。", + "Volume": "体积", + "Wall": "壁厚", + "Wall Location": "壁位置", + "Wall Thickness": "壁厚度", + "When": "条件", + "Width": "宽度", + "Will fail": "将失败", + "angle, height": "角度、高度", + "appearance.dielectric_ior": "电介质折射率", + "appearance.metallic": "金属度", + "appearance.pbr_help": "在渲染工作区或产品 PNG 中查看此表面。不支持折射或透射。", + "appearance.pbr_opaque": "不透明 PBR", + "appearance.roughness": "粗糙度", + "appearance.surface_response": "表面响应", "browser.body_name": "实体{number}", "browser.component_name": "组件{number}", "browser.parameters": "参数 ({count})", @@ -50,7 +307,6 @@ "cmd.component_capture_position": "捕获位置", "cmd.component_create": "新建组件", "cmd.component_delete": "删除组件", - "cmd.component_unlock": "解锁内容", "cmd.component_from_bodies": "由实体创建组件", "cmd.component_insert_design": "插入设计", "cmd.component_links": "列出链接", @@ -61,6 +317,7 @@ "cmd.component_properties": "组件物理属性", "cmd.component_rename": "重命名组件", "cmd.component_revert_position": "恢复位置", + "cmd.component_unlock": "解锁内容", "cmd.component_update_links": "更新链接", "cmd.config_activate": "激活配置", "cmd.config_column": "配置列", @@ -102,10 +359,10 @@ "cmd.doc_recovery_discard": "丢弃已恢复的设计", "cmd.doc_recovery_list": "可恢复的设计", "cmd.document_inspect": "检查设计", - "cmd.document_units": "更改设计单位", "cmd.document_metadata": "设计属性", - "cmd.document_metadata_set": "更改设计属性", "cmd.document_metadata_remove": "删除设计属性", + "cmd.document_metadata_set": "更改设计属性", + "cmd.document_units": "更改设计单位", "cmd.edit_checkpoint": "检查点", "cmd.edit_restore_checkpoint": "恢复检查点", "cmd.engine_commands": "列出命令", @@ -123,6 +380,7 @@ "cmd.inspect_accessibility": "可达性分析", "cmd.inspect_center_of_mass": "质心", "cmd.inspect_compare": "比较实体", + "cmd.inspect_continuity": "连续性分析", "cmd.inspect_curvature_comb": "曲率梳分析", "cmd.inspect_curvature_map": "曲率图分析", "cmd.inspect_draft": "拔模分析", @@ -136,20 +394,25 @@ "cmd.joint_delete": "删除接头", "cmd.joint_drive": "驱动接头", "cmd.joint_edit": "编辑接头", + "cmd.joint_gear": "齿轮", "cmd.joint_limits": "接头限制", "cmd.joint_list": "列出接头", "cmd.joint_motion_link": "运动关联", - "cmd.joint_gear": "齿轮", - "cmd.joint_rack_pinion": "齿轮齿条", - "cmd.joint_screw": "螺旋", "cmd.joint_origin": "接头原点", + "cmd.joint_rack_pinion": "齿轮齿条", "cmd.joint_rigid_group": "刚性组", + "cmd.joint_screw": "螺旋", "cmd.joint_solve": "解算接头", + "cmd.library_apply": "应用本地库条目", + "cmd.library_export": "导出设计库", + "cmd.library_inspect": "检查本地库", "cmd.material_assign": "物理材质", "cmd.material_create": "新建物理材质", "cmd.material_delete": "删除物理材质", "cmd.material_edit": "编辑物理材质", "cmd.material_list": "列出材质", + "cmd.material_properties_directional": "方向弹性模量", + "cmd.material_properties_validate": "验证物理材料数据", "cmd.mesh_convert": "转换网格", "cmd.model_edges": "列出边", "cmd.model_faces": "列出面", @@ -170,10 +433,10 @@ "cmd.parameters_delete": "删除参数", "cmd.parameters_export": "导出参数", "cmd.parameters_favorite": "收藏参数", - "cmd.parameters_move": "移动参数", "cmd.parameters_graph": "参数关系图", "cmd.parameters_import": "导入参数", "cmd.parameters_list": "列出参数", + "cmd.parameters_move": "移动参数", "cmd.parameters_rename": "重命名参数", "cmd.parameters_users": "参数使用者", "cmd.parts_fastener": "插入紧固件", @@ -187,6 +450,16 @@ "cmd.plastic_rest": "垫块", "cmd.plastic_rules": "列出塑料规则", "cmd.plastic_snap_fit": "卡扣", + "cmd.render_backends": "渲染后端", + "cmd.render_cancel": "取消渲染", + "cmd.render_export": "导出 PNG", + "cmd.render_preflight": "检查渲染请求", + "cmd.render_scene": "检查渲染场景", + "cmd.render_settings_apply": "应用渲染相机", + "cmd.render_settings_get": "渲染设置", + "cmd.render_settings_set": "保存渲染设置", + "cmd.render_start": "渲染图像", + "cmd.render_status": "渲染进度", "cmd.select_clear": "清除选择", "cmd.sheet_convert": "转换为钣金", "cmd.sheet_export_bend_table": "导出折弯表", @@ -282,22 +555,21 @@ "cmd.solid_rib": "筋板", "cmd.solid_split_face": "拆分面", "cmd.solid_web": "网格筋", - "cmd.surface_patch": "补面", - "cmd.surface_stitch": "缝合", - "cmd.surface_thicken": "加厚", - "cmd.surface_extrude": "曲面拉伸", - "cmd.surface_revolve": "曲面旋转", - "cmd.surface_sweep": "曲面扫掠", - "cmd.surface_loft": "曲面放样", - "cmd.surface_ruled": "直纹曲面", - "cmd.surface_boundary": "边界曲面", - "cmd.surface_offset": "偏移曲面", "cmd.surface_blend": "混合曲面", + "cmd.surface_boundary": "边界曲面", + "cmd.surface_extrude": "曲面拉伸", "cmd.surface_fillet": "曲面圆角", - "cmd.surface_untrim": "取消修剪", - "cmd.surface_unstitch": "取消缝合", + "cmd.surface_loft": "曲面放样", + "cmd.surface_offset": "偏移曲面", + "cmd.surface_patch": "补面", "cmd.surface_reverse_normal": "反转法向", - "cmd.inspect_continuity": "连续性分析", + "cmd.surface_revolve": "曲面旋转", + "cmd.surface_ruled": "直纹曲面", + "cmd.surface_stitch": "缝合", + "cmd.surface_sweep": "曲面扫掠", + "cmd.surface_thicken": "加厚", + "cmd.surface_unstitch": "取消缝合", + "cmd.surface_untrim": "取消修剪", "cmd.timeline_add": "添加记录的特征", "cmd.timeline_compute_all": "全部重新計算", "cmd.timeline_copy": "复制特征", @@ -314,18 +586,42 @@ "cmd.view_apply": "还原命名视图", "cmd.view_delete": "删除命名视图", "cmd.view_list": "列出命名视图", + "cmd.view_navigate": "导航视图", "cmd.view_rename": "重命名命名视图", "cmd.view_save": "新建命名视图", + "command name": "命令名称", + "coupling.gear_1": "齿轮 1", + "coupling.gear_1_pick": "齿轮 1(可选)", + "coupling.gear_2": "齿轮 2", + "coupling.gear_2_pick": "齿轮 2(可选)", + "coupling.internal": "内齿轮", + "coupling.needs_turn_and_slide": "需要一个旋转接头和一个滑动接头", + "coupling.needs_turns": "需要两个旋转接头", + "coupling.not_round": "不是圆柱面", + "coupling.nut": "螺母", + "coupling.picked": "已拾取", + "coupling.pinion": "小齿轮", + "coupling.pinion_pick": "小齿轮(可选)", + "coupling.pitch": "螺距", + "coupling.rack": "齿条", + "coupling.radius_1": "半径 1", + "coupling.radius_2": "半径 2", "dialog.computing": "正在计算… {seconds} 秒", "dialog.custom_axis": "↖ 自定义轴", "dialog.edit_title": "编辑 {title}", "dialog.select": "↖ 选择", "dialog.selected_count": "↖ 已选择 {count} 个", - "dialog.step": "步骤", - "dialog.selection_step": "第 {step} 步,共 {total} 步:选择{input}", "dialog.selection_guidance": "选择输入项进行修改。点击已选对象可取消选择;按住 Ctrl/Cmd 点击也可切换选择。检查预览后,再按“确定”。", + "dialog.selection_step": "第 {step} 步,共 {total} 步:选择{input}", + "dialog.step": "步骤", "document.save_changes": "保存对 {name} 的更改?", "document.unsaved_changes": "{name} 有未保存的更改。如果不保存,将丢失这些更改。", + "drive.stopped_by_contact": "停在 {value}:{a} 会穿过 {b}", + "drive.stopped_by_loop": "停在 {value}:经过 {joint} 的环路无法再闭合", + "drive.unconnected": "没有任何移动:{part} 未连接到任何固定的零部件", + "expression, e.g. 25 mm": "表达式,例如 25 mm", + "fits the face, e.g. M8": "适配该面,例如 M8", + "from the rule": "来自规则", "home.documentation": "文档", "home.in_this_browser": "在此浏览器中", "home.missing": "文件不存在", @@ -339,6 +635,76 @@ "home.report_issue": "报告问题", "home.samples": "示例", "home.whats_new": "新功能", + "install.button_tip": "将 SolidCraft 安装为应用:在独立窗口中打开,离线也能使用", + "install.dock_1": "选择“文件”›“添加到程序坞”。", + "install.dock_2": "点按“添加”。", + "install.dock_after": "之后 SolidCraft 从程序坞在独立窗口中打开,离线也能使用。", + "install.done": "完成", + "install.home_screen_1": "轻点“共享”(若不在工具栏上,则在 … 菜单中)。", + "install.home_screen_2": "选择“添加到主屏幕”。", + "install.home_screen_3": "轻点“添加”。", + "install.home_screen_after": "之后 SolidCraft 从主屏幕上的图标打开,不显示 Safari 的工具栏,离线也能使用。", + "install.menu": "安装应用…", + "install.steps_intro": "Safari 通过自身的菜单安装网页应用:", + "install.title": "安装 SolidCraft", + "joint.from_bodies_hint": "每个所选实体移入各自的新组件,位置保持不变。", + "joint.one_body": "两次选择都在 {body} 上。请在另一个零件上选择第二个。", + "joint.one_component": "这些零件是同一组件的实体:{bodies}。接头使一个组件相对另一个组件运动,因此每个零件都需要自己的组件。", + "nav.touchpad.help": "按住 Shift 并移动指针可平移;按住 Alt/Option 并移动可旋转。无需按鼠标按钮。垂直滚动可缩放。", + "nav.touchpad.label": "触控板", + "nav.touchpad.orbit": "旋转(按住 Alt/Option 并移动,无需鼠标按钮)", + "nav.touchpad.pan": "平移(按住 Shift 并移动,无需鼠标按钮)", + "nav.touchpad.scroll": "触控板使用垂直滚动进行缩放。双指平移设置将保留供其他预设使用。", + "nav.touchpad.zoom": "缩放(垂直滚动或双指捏合)", + "needs two joints": "需要两个接头", + "new configuration": "新配置", + "new name": "新名称", + "new parameter": "新参数", + "no interference": "无干涉", + "no joint that moves yet": "尚无运动接头", + "no picture": "无图片", + "pick a hole to seat it, or OK places it at the origin": "选择一个孔放置,或单击确定放置在原点", + "pick one or two vertices, edges or faces": "选择一个或两个顶点、边或面", + "render.background": "场景背景", + "render.fit": "适配产品视图", + "render.image_cancel": "取消渲染", + "render.image_cancelled": "渲染已取消", + "render.image_cancelling": "正在取消", + "render.image_check": "检查渲染请求", + "render.image_completed": "图像可导出", + "render.image_encoding": "正在编码 PNG", + "render.image_export": "导出 PNG", + "render.image_failed": "渲染失败", + "render.image_height": "高度", + "render.image_help": "CPU 预览图像 · PNG · 近似透明度", + "render.image_overwrite": "替换现有文件", + "render.image_preparing": "正在准备图像", + "render.image_queued": "等待渲染", + "render.image_reduce": "请尝试更小的图像或更简单的场景。", + "render.image_running": "正在渲染图像", + "render.image_stale": "此图像使用后续更改之前捕获的场景。", + "render.image_start": "开始渲染", + "render.image_supported": "支持此渲染请求;开始时将再次检查队列和内存池。", + "render.image_title": "渲染图像", + "render.image_too_large": "超出图像限制:每边 4096 像素,总计 4,194,304 像素。", + "render.image_transparent": "透明背景", + "render.image_unknown": "渲染状态不可用", + "render.image_use_largest": "使用此宽高比下的最大尺寸:", + "render.image_width": "宽度", + "render.navigation_help": "相机的操作与设计中相同(首选项 › 导航)。保存设置会记录当前相机。", + "render.opaque_image_summary": "预览 PNG · 不透明 PBR · 混合透明", + "render.opaque_preview_help": "不透明 PBR 和纯色;透明效果使用混合。不支持折射、HDRI 和最终渲染。", + "render.perspective": "透视相机", + "render.preview": "集成预览", + "render.preview_help": "光栅着色和混合透明度。暂不支持折射、HDRI 和最终渲染。", + "render.reload_settings": "重新加载已保存设置", + "render.restore_camera": "恢复已保存相机", + "render.return_design": "返回设计", + "render.save_setup": "保存设置", + "render.setup_name": "设置名称", + "render.unavailable_preview": "此设置请求了不可用的预览配置。", + "render.unsaved": "未保存的预览更改", + "render.use_preview": "使用集成预览", "sample.bracket.about": "基于 2 mm 钣金规则的基础法兰、边线法兰和卷边", "sample.bracket.name": "钣金支架", "sample.enclosure.about": "带凸缘、螺钉凸台、垫块和卡扣的抽壳长方体", @@ -351,14 +717,41 @@ "sample.plate.name": "示例板", "sample.vents.about": "按矩形阵列排列的槽:行数、列数和间距均为参数", "sample.vents.name": "通风板", + "settings.display_quality_note": "级别越精细,曲面和边显示越平滑,但网格生成耗时更长。只影响视口,不影响设计或导出。", + "settings.measure_axis_distances": "显示 X/Y/Z 距离", + "settings.measure_axis_distances_help": "测量对话框打开时,在总距离之外显示沿世界坐标轴方向的尺寸线和距离。", "settings.msaa_applies_on_restart": "抗锯齿将在下次启动 SolidCraft 时生效", "settings.msaa_reset": "{setting}: {requested}× 不受此图形设备支持;已重置为 {reset}× (支持: {supported})。", "settings.msaa_unsupported": "此图形设备不支持", "settings.reset_intro": "这些设置在此计算机上无法正常工作,会导致 SolidCraft 无法启动,因此已更改:", "settings.reset_title": "设置已更改", + "settings.supersampling_note": "以更高分辨率绘制视图再缩小:在低于 4K 的屏幕上边、线和网格更平滑。会消耗 GPU 时间:1.5× 时约 2.25 倍像素,2× 时 4 倍。", "sketch.degrees_of_freedom": "{count} 个自由度", "sketch.draw_curves": "绘制为 {linetype}", "sketch.make_selection": "将选择转换为 {linetype}", + "sketch_text.align_center": "居中", + "sketch_text.align_left": "左对齐", + "sketch_text.align_right": "右对齐", + "sketch_text.bold": "粗体", + "sketch_text.builtin_font": "{family}(内置)", + "sketch_text.font_search": "搜索字体", + "sketch_text.italic": "斜体", + "sketch_text.loading_fonts": "正在查找已安装字体…", + "sketch_text.on_path": "文字沿路径排列:由曲线放置", + "sketch_text.path_clear": "将文字移离其曲线", + "sketch_text.path_hint": "文字所跟随的草图曲线:先单击此处,再选择曲线", + "sketch_text.use_font_file": "使用字体文件 {path}", + "the parts library is not available": "零件库不可用", + "timeline.group": "新建特征文件夹", + "timeline.move_many": "移动时间线项目", + "timeline.move_to_group": "将特征移至文件夹", + "timeline.rename_group": "重命名特征文件夹", + "timeline.reorder_many": "特征重新排序", + "timeline.ungroup": "移除特征文件夹", + "to the next face": "到下一个面", + "toolbar.image": "图像", + "toolbar.render": "渲染", + "toolbar.render_scene": "场景", "ui.1_degree_of_freedom": "1 个自由度", "ui.3d_mouse_speed": "3D 鼠标速度", "ui.3d_mouse_windows": "3D 鼠标", @@ -366,89 +759,89 @@ "ui.about": "关于", "ui.activate": "激活", "ui.active_component": "活动组件", - "ui.agent_cursor": "代理光标", - "ui.agent_cursor_speed": "代理光标速度", "ui.agent_chat": "智能体聊天", - "ui.agent_chat_command": "智能体命令", - "ui.agent_chat_desktop_only": "智能体聊天需要桌面应用。", - "ui.agent_chat_side": "智能体聊天位置", - "ui.agent_chat_left": "左侧", - "ui.agent_chat_right": "右侧", - "ui.agent_chat_turn_limit": "每条消息的更改数", - "ui.agent_chat_privacy_note": "SolidCraft 不向任何地方发送任何内容:你运行的智能体以你自己的账户与它自己的服务通信。SolidCraft 从不查看或保存任何密钥或密码。", - "ui.agent_chat_connect": "连接", - "ui.agent_chat_stop": "停止", - "ui.agent_chat_stop_tip": "停止智能体及其启动的所有进程", - "ui.agent_chat_close": "关闭", - "ui.agent_chat_minimize": "最小化为细条", - "ui.agent_chat_dock_left": "停靠在左侧", - "ui.agent_chat_dock_right": "停靠在右侧", - "ui.agent_chat_send": "发送", - "ui.agent_chat_cancel": "取消", - "ui.agent_chat_refresh": "刷新", - "ui.agent_chat_pick": "智能体", - "ui.agent_chat_custom_hint": "任何通过标准输入输出使用 Agent Client Protocol 的程序。不经过 shell 运行。", - "ui.agent_chat_not_installed": "未安装", - "ui.agent_chat_none_found": "未找到编程智能体。请安装以下之一,然后点击刷新:", - "ui.agent_chat_detecting": "正在查找智能体…", - "ui.agent_chat_signed_in": "已登录", - "ui.agent_chat_key_in_env": "已设置密钥", - "ui.agent_chat_not_signed_in": "未登录", - "ui.agent_chat_state_off": "未连接", - "ui.agent_chat_state_starting": "正在启动…", - "ui.agent_chat_state_ready": "就绪", - "ui.agent_chat_state_busy": "工作中…", - "ui.agent_chat_state_auth": "需要登录", - "ui.agent_chat_state_exited": "智能体已停止", - "ui.agent_chat_changes_of": "更改 {n}/{limit}", - "ui.agent_chat_auth_title": "登录智能体", - "ui.agent_chat_auth_needed": "智能体要求你登录。登录在智能体本身完成;SolidCraft 从不接触你的密码或密钥。", - "ui.agent_chat_auth_none": "该智能体未在此提供登录方式:请按照它自己的文档登录。", - "ui.agent_chat_auth_terminal": "在终端中运行以下命令,然后再次点击连接:", - "ui.agent_chat_auth_agent": "使用 {name} 登录", - "ui.agent_chat_auth_env": "请在环境中设置 {vars},然后重启 SolidCraft。", - "ui.agent_chat_auth_retry": "我已登录:重新连接", - "ui.agent_chat_copy": "复制", - "ui.agent_chat_permission": "智能体请求运行:{title}", + "ui.agent_chat_allow": "允许", + "ui.agent_chat_allowed": "已允许", "ui.agent_chat_answered": "回答:{option}", "ui.agent_chat_approval": "允许智能体执行此操作吗?", - "ui.agent_chat_allow": "允许", - "ui.agent_chat_deny": "拒绝", - "ui.agent_chat_allowed": "已允许", - "ui.agent_chat_denied": "已拒绝", - "ui.agent_chat_changes": "{n} 项更改,一步撤销", - "ui.agent_chat_undo_changes": "撤销这些更改", - "ui.agent_chat_undone": "(已撤销)", - "ui.agent_chat_undo_label": "智能体聊天:{message}", - "ui.agent_chat_limit": "智能体已达到每条消息 {limit} 项更改的上限。再发送一条消息可让它继续。", - "ui.agent_chat_refused": "不允许智能体执行:{reason}", - "ui.agent_chat_wait_turn": "智能体仍在处理上一条消息:请等待或点击取消。", - "ui.agent_chat_placeholder": "让智能体修改设计…", "ui.agent_chat_attach_view": "附加视图", "ui.agent_chat_attach_view_tip": "随消息发送当前视图的图片", - "ui.agent_chat_no_images": "该智能体不接收图片", - "ui.agent_chat_view_attached": "已附加视图", - "ui.agent_chat_no_cli": "在应用旁边未找到 solidcraft-cli,因此智能体无法访问设计。", - "ui.agent_chat_no_control": "智能体聊天的端点未能启动,因此智能体无法访问设计。", + "ui.agent_chat_auth_agent": "使用 {name} 登录", + "ui.agent_chat_auth_env": "请在环境中设置 {vars},然后重启 SolidCraft。", + "ui.agent_chat_auth_needed": "智能体要求你登录。登录在智能体本身完成;SolidCraft 从不接触你的密码或密钥。", + "ui.agent_chat_auth_none": "该智能体未在此提供登录方式:请按照它自己的文档登录。", + "ui.agent_chat_auth_retry": "我已登录:重新连接", + "ui.agent_chat_auth_terminal": "在终端中运行以下命令,然后再次点击连接:", + "ui.agent_chat_auth_title": "登录智能体", + "ui.agent_chat_cancel": "取消", + "ui.agent_chat_changes": "{n} 项更改,一步撤销", + "ui.agent_chat_changes_of": "更改 {n}/{limit}", + "ui.agent_chat_close": "关闭", + "ui.agent_chat_command": "智能体命令", + "ui.agent_chat_connect": "连接", + "ui.agent_chat_copy": "复制", + "ui.agent_chat_custom_hint": "任何通过标准输入输出使用 Agent Client Protocol 的程序。不经过 shell 运行。", + "ui.agent_chat_denied": "已拒绝", + "ui.agent_chat_deny": "拒绝", + "ui.agent_chat_desktop_only": "智能体聊天需要桌面应用。", + "ui.agent_chat_detecting": "正在查找智能体…", + "ui.agent_chat_dock_left": "停靠在左侧", + "ui.agent_chat_dock_right": "停靠在右侧", "ui.agent_chat_exited": "智能体已停止。", "ui.agent_chat_failed_start": "智能体无法启动:{error}", "ui.agent_chat_intro": "与你已在使用的编程智能体或你选择的模型端点聊天。它通过 SolidCraft 的工具处理打开的设计:更改即时显示,每条消息的更改可一步撤销。无需询问即可执行的范围在“首选项 > AI”中设置。", - "ui.agent_chat_privacy": "除了你以自己的账户运行的智能体之外,不会向任何地方发送任何内容。", + "ui.agent_chat_key_in_env": "已设置密钥", + "ui.agent_chat_left": "左侧", + "ui.agent_chat_limit": "智能体已达到每条消息 {limit} 项更改的上限。再发送一条消息可让它继续。", + "ui.agent_chat_minimize": "最小化为细条", + "ui.agent_chat_no_cli": "在应用旁边未找到 solidcraft-cli,因此智能体无法访问设计。", + "ui.agent_chat_no_control": "智能体聊天的端点未能启动,因此智能体无法访问设计。", + "ui.agent_chat_no_images": "该智能体不接收图片", + "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_permission": "智能体请求运行:{title}", + "ui.agent_chat_pick": "智能体", + "ui.agent_chat_placeholder": "让智能体修改设计…", + "ui.agent_chat_privacy": "除了你以自己的账户运行的智能体之外,不会向任何地方发送任何内容。", + "ui.agent_chat_privacy_note": "SolidCraft 不向任何地方发送任何内容:你运行的智能体以你自己的账户与它自己的服务通信。SolidCraft 从不查看或保存任何密钥或密码。", + "ui.agent_chat_refresh": "刷新", + "ui.agent_chat_refused": "不允许智能体执行:{reason}", + "ui.agent_chat_right": "右侧", + "ui.agent_chat_send": "发送", + "ui.agent_chat_side": "智能体聊天位置", + "ui.agent_chat_signed_in": "已登录", + "ui.agent_chat_state_auth": "需要登录", + "ui.agent_chat_state_busy": "工作中…", + "ui.agent_chat_state_exited": "智能体已停止", + "ui.agent_chat_state_off": "未连接", + "ui.agent_chat_state_ready": "就绪", + "ui.agent_chat_state_starting": "正在启动…", + "ui.agent_chat_stop": "停止", + "ui.agent_chat_stop_tip": "停止智能体及其启动的所有进程", + "ui.agent_chat_turn_limit": "每条消息的更改数", + "ui.agent_chat_undo_changes": "撤销这些更改", + "ui.agent_chat_undo_label": "智能体聊天:{message}", + "ui.agent_chat_undone": "(已撤销)", + "ui.agent_chat_view_attached": "已附加视图", + "ui.agent_chat_wait_turn": "智能体仍在处理上一条消息:请等待或点击取消。", + "ui.agent_cursor": "代理光标", + "ui.agent_cursor_speed": "代理光标速度", "ui.ai_add": "添加", "ui.ai_add_agent": "添加智能体…", "ui.ai_add_agent_title": "添加智能体", "ui.ai_add_api": "OpenAI 兼容 API", "ui.ai_add_custom": "自定义命令", - "ui.ai_added": "已添加", "ui.ai_add_installed": "已安装的智能体", "ui.ai_add_installed_note": "为已安装的智能体添加一个自己的条目,例如使用其他参数。已安装的智能体会自动列出。", + "ui.ai_added": "已添加", "ui.ai_agent_mode_tip": "智能体自己的模式:它自己的工具(shell、文件编辑)遵循此模式。SolidCraft 的工具遵循“首选项 > AI”中的权限。", "ui.ai_agents": "智能体", "ui.ai_always_allow": "始终允许", + "ui.ai_always_allow_tip": "从现在起允许该智能体使用 {tool},不再询问", "ui.ai_always_allowed": "始终允许的项目", "ui.ai_always_allowed_none": "尚无始终允许的项目。你在聊天中选择“始终允许”的回答会列在这里。", - "ui.ai_always_allow_tip": "从现在起允许该智能体使用 {tool},不再询问", "ui.ai_auto_allowed": "已自动允许:{title}({why})", "ui.ai_auto_mode": "你的权限设置", "ui.ai_auto_ours": "SolidCraft 会自行检查它自己的工具", @@ -463,10 +856,10 @@ "ui.ai_http_key": "端点拒绝了密钥:请在“首选项 > AI”中检查", "ui.ai_http_not_found": "找不到该端点或模型:请检查基础 URL 和模型名称", "ui.ai_key": "API 密钥", - "ui.ai_keychain_error": "系统钥匙串拒绝:{error}", "ui.ai_key_hint": "可选;保存在系统钥匙串中", "ui.ai_key_needs_https": "密钥只会通过 HTTPS 发送,或发送到本机。", "ui.ai_key_note": "保存在系统钥匙串中,绝不保存在 SolidCraft 的设置里。本地服务器可留空。", + "ui.ai_keychain_error": "系统钥匙串拒绝:{error}", "ui.ai_mode_all": "全部允许", "ui.ai_mode_all_note": "不再询问。崩溃报告仍不可访问,文件夹限制仍然有效。", "ui.ai_mode_all_warning": "智能体可以不经询问保存、覆盖、导出和替换你的设计。只在你信任的智能体和已保存的设计上使用。", @@ -497,35 +890,26 @@ "ui.ai_test_acp_ok": "已响应:{agent}", "ui.ai_test_acp_tip": "短暂启动智能体并请求一个会话,然后结束它", "ui.ai_test_api_tip": "向端点查询其模型列表", - "ui.ai_testing": "正在测试…", "ui.ai_test_no_model": "已连接:{count} 个模型,但没有 {model}", "ui.ai_test_ok": "已连接:{count} 个模型", - "ui.ai_toolbar_button": "在工具栏显示按钮", - "ui.ai_toolbar_button_note": "工具栏右端的 AI 按钮。Ctrl+Shift+A 和视图菜单仍可打开面板。", + "ui.ai_testing": "正在测试…", "ui.ai_tool_done": "完成", "ui.ai_tool_failed": "失败", "ui.ai_tool_running": "运行中", "ui.ai_tool_unfold": "点击显示返回内容", "ui.ai_tool_waiting": "等待中", + "ui.ai_toolbar_button": "在工具栏显示按钮", + "ui.ai_toolbar_button_note": "工具栏右端的 AI 按钮。Ctrl+Shift+A 和视图菜单仍可打开面板。", "ui.ai_undo_tip": "将智能体为此消息所做的全部更改一步撤销", - "AI": "AI", "ui.all": "全部", + "ui.analysis": "分析", "ui.angle": "角度", "ui.angle_decimals": "角度小数位", + "ui.animateJoint": "动画接头", "ui.animate_view_changes": "视图变化动画", "ui.animation": "动画", "ui.animation_speed": "动画速度", "ui.anti_aliasing": "抗锯齿", - "ui.supersampling": "超级采样 (SSAA)", - "ui.supersampling_off": "关 (1×)", - "ui.supersampling_adaptive": "仅在视图静止时", - "settings.supersampling_note": "以更高分辨率绘制视图再缩小:在低于 4K 的屏幕上边、线和网格更平滑。会消耗 GPU 时间:1.5× 时约 2.25 倍像素,2× 时 4 倍。", - "ui.display_quality": "显示质量", - "ui.display_quality_coarse": "粗糙", - "ui.display_quality_normal": "标准", - "ui.display_quality_fine": "精细", - "ui.display_quality_ultra": "极高", - "settings.display_quality_note": "级别越精细,曲面和边显示越平滑,但网格生成耗时更长。只影响视口,不影响设计或导出。", "ui.apply": "应用", "ui.arc": "圆弧", "ui.assemble": "装配", @@ -533,9 +917,11 @@ "ui.axes": "轴", "ui.axis": "轴", "ui.base_point": "基点", + "ui.blocked": "被遮挡", "ui.bodies": "实体", "ui.box": "长方体", "ui.break": "打断", + "ui.calibrate": "校准", "ui.cancel": "取消", "ui.canvases": "画布", "ui.center": "中心", @@ -545,8 +931,6 @@ "ui.chamfer_type": "倒角类型", "ui.change_workspace": "更改工作区", "ui.chord_length": "弦长", - "ui.curvature_g2": "曲率连续 (G2)", - "ui.equivalent_radius": "等效半径", "ui.circle": "圆", "ui.circular_pattern": "圆形阵列", "ui.clear": "清除", @@ -555,28 +939,6 @@ "ui.click_selects_whole_bodies": "单击选择整个实体", "ui.click_then_press_key": "单击,然后按新按键", "ui.close": "关闭", - "ui.material_review.title": "检查物理材料数据", - "ui.material_review.scope": "仅检查候选数据:不指定或保存。数值验证不等于工程认证。", - "ui.material_review.input": "粘贴架构版本1的材料卡(JSON)", - "ui.material_review.review": "检查材料卡", - "ui.material_review.limit": "材料卡超过256 KiB输入限制。", - "ui.material_review.unknown": "未知", - "ui.material_review.properties": "属性", - "ui.material_review.conditions": "声明的条件", - "ui.material_review.source": "来源", - "ui.material_review.axes": "材料局部坐标轴;不指定实体方向。", - "ui.material_review.derived": "推导的各向同性模量", - "ui.material_review.claims": "来源和许可证声明未经核实。缺失值保持未知。", - "ui.material_review.density": "密度", - "ui.material_review.elasticity": "弹性", - "ui.material_review.tensile_strength": "抗拉强度", - "ui.material_review.compressive_strength": "抗压强度", - "ui.material_review.yield_strength": "屈服强度", - "ui.material_review.shear_strength": "抗剪强度", - "ui.material_review.thermal_conductivity": "导热系数", - "ui.material_review.thermal_expansion": "热膨胀", - "ui.material_review.specific_heat": "比热容", - "ui.material_review.moisture_unit": "kg 水 / kg 干燥材料", "ui.coil": "螺旋", "ui.coincident": "重合", "ui.collapse": "折叠", @@ -598,6 +960,8 @@ "ui.colour_vision_tritan_tip": "蓝色感知较弱或缺失时使用", "ui.combine": "组合", "ui.coming_later": "即将推出", + "ui.command_done": "{command} 完成", + "ui.command_palette_hint": "输入命令,例如 {example} — 或按 S 搜索", "ui.concentric": "同心", "ui.configurations": "配置", "ui.conic_curve": "圆锥曲线", @@ -607,8 +971,8 @@ "ui.construction": "构造", "ui.context_menu": "上下文菜单", "ui.copy": "复制", - "ui.corners": "角点", "ui.corner": "角", + "ui.corners": "角点", "ui.counterbore": "沉头孔", "ui.countersink": "锥形沉孔", "ui.create": "创建", @@ -616,7 +980,11 @@ "ui.create_sketch": "创建草图", "ui.current": "当前", "ui.curvature": "曲率", + "ui.curvature_g2": "曲率连续 (G2)", "ui.curves": "曲线", + "ui.custom_program": "自定义…", + "ui.custom_program_tip": "选择要添加到列表的切片软件程序", + "ui.customizeToolbar": "自定义工具栏…", "ui.cut": "剪切", "ui.cylinder": "圆柱体", "ui.dark": "深色", @@ -625,9 +993,25 @@ "ui.delete": "删除", "ui.depth": "深度", "ui.design": "设计", + "ui.design_properties.author": "作者", + "ui.design_properties.description": "描述", + "ui.design_properties.exports": "导出 STEP、IGES 和 3MF 时,若格式有对应字段,会写入这些属性。", + "ui.design_properties.license": "许可证", + "ui.design_properties.not_text": "已保存为非文本值;在此输入将替换它。", + "ui.design_properties.organization": "组织", + "ui.design_properties.others": "其他工具的数据", + "ui.design_properties.others_note": "按原样保存在设计中,从不导出。", + "ui.design_properties.part_number": "零件号", + "ui.design_properties.project": "项目", + "ui.design_properties.revision": "版本", "ui.diameter": "直径", "ui.dimension": "尺寸", "ui.direction": "方向", + "ui.display_quality": "显示质量", + "ui.display_quality_coarse": "粗糙", + "ui.display_quality_fine": "精细", + "ui.display_quality_normal": "标准", + "ui.display_quality_ultra": "极高", "ui.distance": "距离", "ui.distance_1": "距离 1", "ui.distance_2": "距离 2", @@ -637,11 +1021,16 @@ "ui.drawing": "绘图", "ui.drill_point": "钻尖", "ui.edit": "编辑", + "ui.editJointLimits": "编辑接头限制", + "ui.edit_section_analysis": "编辑截面分析", "ui.ellipse": "椭圆", "ui.end_radius": "结束半径", + "ui.end_scale": "末端缩放", "ui.entities": "实体", "ui.equal": "相等", + "ui.equivalent_radius": "等效半径", "ui.expand": "展开", + "ui.exportDxf": "导出 DXF…", "ui.export_ellipsis": "导出...", "ui.export_ellipsis_keymap": "导出…", "ui.export_keymap_tip": "将按键、S 框收藏和工具栏导出为文件", @@ -655,15 +1044,20 @@ "ui.file": "文件", "ui.fillet": "圆角", "ui.filter_commands_or_keys": "筛选命令或按键", + "ui.findInTimeline": "在时间线中查找", + "ui.findInWindow": "在窗口中查找", "ui.finish_sketch": "完成草图", + "ui.fit": "适合", "ui.fix_unfix": "固定/取消固定", "ui.flat": "平面", "ui.flip": "翻转", + "ui.format": "格式", "ui.front": "前视", "ui.fully_constrained": "完全约束", "ui.general": "常规", "ui.graphics": "图形", "ui.ground_shadow": "地面阴影", + "ui.groupSelected": "将所选编组", "ui.heading_add_ins": "加载项", "ui.heading_assemble": "装配", "ui.heading_box": "长方体", @@ -695,8 +1089,8 @@ "ui.heading_mirror": "镜像", "ui.heading_modify": "修改", "ui.heading_move": "移动", - "ui.heading_offset": "偏移", "ui.heading_move_copy": "移动/复制", + "ui.heading_offset": "偏移", "ui.heading_offset_plane": "偏移平面", "ui.heading_ok": "确定", "ui.heading_parameters": "参数", @@ -704,13 +1098,16 @@ "ui.heading_pipe": "管道", "ui.heading_plane_at_angle": "角度平面", "ui.heading_plastic": "塑料", + "ui.heading_position": "位置", "ui.heading_prepare": "准备", "ui.heading_rectangular_pattern": "矩形阵列", "ui.heading_revolve": "旋转", "ui.heading_right": "右视", + "ui.heading_save_mesh": "另存为网格", "ui.heading_scale": "缩放", "ui.heading_section_analysis": "截面分析", "ui.heading_select": "选择", + "ui.heading_setup": "设置", "ui.heading_sheet_metal": "钣金", "ui.heading_shell": "抽壳", "ui.heading_sketch": "草图", @@ -728,15 +1125,22 @@ "ui.heading_utility": "实用工具", "ui.help": "帮助", "ui.hide": "隐藏", + "ui.hideAxes": "隐藏轴", + "ui.hideDimension": "隐藏尺寸", + "ui.hideOrigin": "隐藏原点", + "ui.hidePlanes": "隐藏平面", + "ui.hideProfile": "隐藏轮廓", "ui.hole": "孔", "ui.hole_tap_type": "孔攻丝类型", "ui.hole_type": "孔类型", "ui.home": "主页", + "ui.homeView": "主视图", "ui.horizontal_vertical": "水平/垂直", "ui.import_ellipsis": "导入…", "ui.insert": "插入", "ui.inspect": "检查", "ui.intersect": "相交", + "ui.isolate": "隔离", "ui.join": "连接", "ui.joints": "关节", "ui.keyboard_shortcuts": "键盘快捷键", @@ -745,11 +1149,37 @@ "ui.light": "浅色", "ui.line": "直线", "ui.linetype": "线型", + "ui.lock": "锁定", "ui.loft": "放样", "ui.look_at": "朝向", "ui.look_at_anim_desc": "轴视图、注视、主视图与适合窗口", "ui.manufacture": "制造", + "ui.material_review.axes": "材料局部坐标轴;不指定实体方向。", + "ui.material_review.claims": "来源和许可证声明未经核实。缺失值保持未知。", + "ui.material_review.compressive_strength": "抗压强度", + "ui.material_review.conditions": "声明的条件", + "ui.material_review.density": "密度", + "ui.material_review.derived": "推导的各向同性模量", + "ui.material_review.elasticity": "弹性", + "ui.material_review.input": "粘贴架构版本1的材料卡(JSON)", + "ui.material_review.limit": "材料卡超过256 KiB输入限制。", + "ui.material_review.moisture_unit": "kg 水 / kg 干燥材料", + "ui.material_review.properties": "属性", + "ui.material_review.review": "检查材料卡", + "ui.material_review.scope": "仅检查候选数据:不指定或保存。数值验证不等于工程认证。", + "ui.material_review.shear_strength": "抗剪强度", + "ui.material_review.source": "来源", + "ui.material_review.specific_heat": "比热容", + "ui.material_review.tensile_strength": "抗拉强度", + "ui.material_review.thermal_conductivity": "导热系数", + "ui.material_review.thermal_expansion": "热膨胀", + "ui.material_review.title": "检查物理材料数据", + "ui.material_review.unknown": "未知", + "ui.material_review.yield_strength": "屈服强度", "ui.measure": "测量", + "ui.mesh_format_3mf": "3MF", + "ui.mesh_format_3mf_tagged": "带面标签的 3MF", + "ui.mesh_format_stl": "STL", "ui.midpoint": "中点", "ui.mirror": "镜像", "ui.mirror_line": "镜像线", @@ -759,9 +1189,13 @@ "ui.named_views": "命名视图", "ui.navigation": "导航", "ui.needs_design": "{command}: 请先打开一个设计", + "ui.newSketchGroup": "新建草图组", "ui.new_body": "新建实体", "ui.new_design": "新建设计", + "ui.no_slicer_found": "未找到切片软件", "ui.normal": "法向", + "ui.normalConstruction": "普通 / 构造", + "ui.not_a_program": "{path} 不是可以启动的程序", "ui.object_type": "对象类型", "ui.objects": "对象", "ui.offer_to_stand_up_y_up_files": "提供站立 Y-up 文件", @@ -774,10 +1208,13 @@ "ui.open_recent": "打开最近", "ui.operation": "操作", "ui.options": "选项", + "ui.orbit": "环绕", "ui.orbit_around": "环绕", + "ui.orientation": "定向", "ui.origin": "原点", "ui.palette_points": "点", "ui.palette_profile": "轮廓", + "ui.pan": "平移", "ui.pan_zoom_orbit": "平移、缩放、环绕", "ui.parallel": "平行", "ui.parameters": "参数", @@ -786,6 +1223,8 @@ "ui.pattern_on_path": "路径阵列", "ui.perpendicular": "垂直", "ui.perspective_view": "透视图", + "ui.pinToShortcuts": "固定到快捷方式", + "ui.pinToToolbar": "固定到工具栏", "ui.pipe": "管道", "ui.placement": "放置", "ui.plane": "平面", @@ -801,63 +1240,59 @@ "ui.profiles": "轮廓", "ui.project": "投影", "ui.project_face_edges_sketch": "将面的边投影到新草图", - "ui.quantity_2": "数量 2", + "ui.properties": "属性", + "ui.pull_direction": "拔模方向", "ui.quantity": "数量", + "ui.quantity_2": "数量 2", "ui.quit": "退出", "ui.radial_context_menu": "环形上下文菜单", "ui.radius": "半径", - "ui.pull_direction": "拔模方向", - "ui.tool_direction": "刀具方向", - "ui.reachable": "可到达", - "ui.blocked": "被遮挡", "ui.radius_type": "半径类型", + "ui.reachable": "可到达", "ui.rectangle": "矩形", "ui.rectangular_pattern": "矩形阵列", "ui.redo": "重做", + "ui.removeFromToolbar": "从工具栏移除", + "ui.removeSection": "移除剖面", "ui.render": "渲染", "ui.renderer": "渲染器", + "ui.repeat": "重复", + "ui.report_a_bug": "报告缺陷", "ui.reset": "重置", "ui.reset_all": "全部重置", "ui.reset_the_settings_on_this_page": "重置此页面上的设置", + "ui.restore": "还原", "ui.restore_defaults": "恢复默认值", "ui.reverse_zoom_direction": "反转缩放方向", "ui.revolve": "旋转", "ui.right": "右视", "ui.save": "保存", - "ui.heading_save_mesh": "另存为网格", - "ui.format": "格式", - "ui.mesh_format_stl": "STL", - "ui.mesh_format_3mf": "3MF", - "ui.mesh_format_3mf_tagged": "带面标签的 3MF", - "ui.send_to_slicer": "发送到切片软件", - "ui.slicer": "切片软件", - "ui.custom_program": "自定义…", - "ui.no_slicer_found": "未找到切片软件", - "ui.send": "发送", - "ui.custom_program_tip": "选择要添加到列表的切片软件程序", - "ui.slicer_delete_tip": "{program}\n按 Delete 键从列表中移除", - "ui.save_mesh_pick_bodies": "请选择要保存的实体", - "ui.save_mesh_no_slicer": "未找到切片软件:请选择“自定义…”并指定切片软件程序,或关闭“发送到切片软件”", - "ui.not_a_program": "{path} 不是可以启动的程序", - "ui.sent_to_slicer": "已发送到 {slicer}", - "ui.saved_to": "已保存:{path}", - "ui.save_mesh_temp_failed": "无法创建 {folder}:{error}", "ui.save_as": "另存为", "ui.save_as_ellipsis": "另存为...", + "ui.save_mesh_no_slicer": "未找到切片软件:请选择“自定义…”并指定切片软件程序,或关闭“发送到切片软件”", + "ui.save_mesh_pick_bodies": "请选择要保存的实体", + "ui.save_mesh_temp_failed": "无法创建 {folder}:{error}", + "ui.saved_to": "已保存:{path}", "ui.scale": "缩放", - "ui.orientation": "定向", - "ui.twist": "扭转", - "ui.end_scale": "末端缩放", - "ui.sweep_turn_with_path": "随路径转动", - "ui.sweep_keep_as_drawn": "保持绘制方向", - "ui.sweep_follow_direction": "跟随方向", "ui.section_analysis": "截面分析", "ui.select": "选择", + "ui.selectOther": "选择其他…", + "ui.selectTangentChain": "选择相切链", "ui.select_other_hint": "“选择其他”:在模型上按住左键(或右键单击 › 选择其他…)列出光标下的所有对象;在同一位置再次单击可选择该处的下一个对象。", "ui.selection": "选择", + "ui.send": "发送", + "ui.send_to_slicer": "发送到切片软件", + "ui.sent_to_slicer": "已发送到 {slicer}", "ui.shell": "抽壳", "ui.show": "显示", + "ui.showAll": "显示全部", + "ui.showAllBodies": "显示所有实体", + "ui.showAxes": "显示轴", + "ui.showDimension": "显示尺寸", + "ui.showOrigin": "显示原点", + "ui.showPlanes": "显示平面", "ui.show_constraints": "约束", + "ui.show_construction_geometries": "构造几何图元", "ui.show_dimensions": "尺寸", "ui.show_points": "显示点", "ui.show_profile": "显示轮廓", @@ -872,6 +1307,8 @@ "ui.sketch_status": "草图状态", "ui.sketches": "草图", "ui.slice": "切片", + "ui.slicer": "切片软件", + "ui.slicer_delete_tip": "{program}\n按 Delete 键从列表中移除", "ui.slot": "槽", "ui.smooth": "平滑", "ui.smooth_wheel_zoom": "平滑滚轮缩放", @@ -879,15 +1316,22 @@ "ui.snap": "捕捉", "ui.space_mouse_hint": "同时移动和旋转视图;草图中仅支持平移和缩放。", "ui.space_mouse_navigate": "使用 SpaceNavigator / SpaceMouse 导航", - "ui.spacing_2": "间距 2", "ui.spacing": "间距", + "ui.spacing_2": "间距 2", "ui.sphere": "球体", "ui.spline": "样条曲线", "ui.split_body": "分割实体", "ui.stand_up_tip": "当 Z 朝上的 STEP 或 IGES 文件打开后,提示绕 X 轴旋转四分之一周", "ui.start": "开始", "ui.start_radius": "起始半径", + "ui.supersampling": "超级采样 (SSAA)", + "ui.supersampling_adaptive": "仅在视图静止时", + "ui.supersampling_off": "关 (1×)", + "ui.suppress": "抑制", "ui.sweep": "扫掠", + "ui.sweep_follow_direction": "跟随方向", + "ui.sweep_keep_as_drawn": "保持绘制方向", + "ui.sweep_turn_with_path": "随路径转动", "ui.symmetric": "对称", "ui.symmetry": "对称", "ui.system": "系统", @@ -903,18 +1347,26 @@ "ui.timeline_left_sidebar": "左侧边栏", "ui.tip_angle": "尖端角度", "ui.to_object": "到对象", + "ui.tool_direction": "刀具方向", "ui.top": "上视", "ui.torus": "圆环体", + "ui.total_angle": "总角度", "ui.trackpad_pan_tip": "触控板手势用于平移(关闭:像滚轮一样缩放);鼠标滚轮缩放、拇指滚轮横向平移、双指捏合始终缩放", "ui.trim": "修剪", + "ui.twist": "扭转", "ui.two_finger_scroll_pans": "双指滚动平移", "ui.two_sides": "双侧", "ui.ui_scale": "界面缩放", "ui.undo": "撤销", + "ui.unground": "取消固定", + "ui.unisolate": "取消隔离", "ui.units": "单位", "ui.units_of_new_designs": "新设计的单位", + "ui.unlock": "解锁", + "ui.unsuppress": "取消抑制", "ui.untitled": "无标题", "ui.up_axis_note": "视图中朝上的轴(轴视图、主视图、注视)。设计本身不变。", + "ui.updateToCurrentView": "更新为当前视图", "ui.variable": "变量", "ui.view_centre": "视图中心", "ui.visual_shaded_hidden_edges": "带隐藏边的着色", @@ -922,498 +1374,45 @@ "ui.visual_style": "视觉样式", "ui.visual_wireframe": "线框", "ui.workspace": "工作区", - "ui.y_distance": "Y 距离", "ui.x_distance": "X 距离", + "ui.y_distance": "Y 距离", "ui.y_up": "Y 朝上", "ui.z_up": "Z 朝上", + "ui.zoom": "缩放", "ui.zoom_to_cursor_tip": "滚轮向光标所在点缩放(关闭:向视图中心缩放)", "ui.zoom_to_the_cursor": "缩放到光标", - "A new configuration, a copy of the active one": "新建配置,为当前配置的副本", - "About SolidCraft": "关于 SolidCraft", - "Active": "活动", - "Active rule": "活动规则", - "Add": "添加", - "Add Key": "添加按键", - "Add Mid Radius": "添加中间半径", - "Add Row": "添加行", - "All Sketch Points": "所有草图点", - "All open designs": "所有打开的设计", - "Allowed expressions, separated by semicolons": "允许的表达式,以分号分隔", - "Also deletes": "同时删除", - "Angle 2": "角度 2", - "Animate": "动画", - "Appearance name": "外观名称", - "Applied Radius": "应用半径", - "Apply To": "应用于", - "Area": "面积", - "Attachment": "附着", - "BROWSER": "浏览器", - "Bend Line Position": "弯折线位置", - "Bend Position": "折弯位置", - "Bend Radius": "折弯半径", - "Bends": "折弯", - "Body": "实体", - "Bounding box": "边界框", - "CSV or JSON: updates existing parameters, adds new ones": "CSV 或 JSON:更新现有参数、添加新参数", - "Capture All Positions": "捕获所有位置", - "Catch Direction": "卡扣方向", - "Cells": "区域", - "Center X": "中心 X", - "Center Y": "中心 Y", - "Center of mass": "质心", - "Chamfer Type": "倒角类型", - "Check collisions": "检查碰撞", - "Checked": "已检查", - "Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.": "选择一个新平面。草图几何和尺寸在其二维坐标中保持不变。", - "Close draft": "关闭草稿", - "Collisions": "碰撞", - "Colour": "颜色", - "Component1": "组件1", - "Configuration": "配置", - "Configuration rules": "配置规则", - "Contact": "接触", - "Copy all licences": "复制所有许可证", - "Copy diagnostic information": "复制诊断信息", - "Copy report": "复制报告", - "Corner Relief": "拐角释放", - "Corner Relief Shape": "拐角释放形状", - "Notch": "缺口", - "Round": "圆形", - "Rectangular": "矩形", - "Tear": "撕裂", - "Counterbore depth": "沉孔深度", - "Countersink angle": "沉头角度", - "Create Issue — review draft": "创建 Issue——审阅草稿", - "Customize Toolbar": "自定义工具栏", - "Delete all": "全部删除", - "Delete rule": "删除规则", - "Delete the row": "删除此行", - "Delete the set": "删除此集合", - "Delete this parameter": "删除此参数", - "Density": "密度", - "Designs you open or save appear here.": "你打开或保存的设计会显示在此处。", - "Determined by To Object. Choose Angle to edit the angular extent.": "由“到对象”确定。选择“角度”可编辑角度范围。", - "Discard": "放弃", - "Double-click to rename": "双击重命名", - "Drive Joint": "驱动接头", - "Edit Profile Sketch": "编辑轮廓草图", - "Enable rule": "启用规则", - "Enabled": "已启用", - "Explode": "爆炸", - "Extents": "范围", - "Face attachment lost": "面附着丢失", - "Faces / edges / vertices": "面 / 边 / 顶点", - "Favourite": "收藏", - "Files from many CAD programs have Y up, so they open lying on their back here (Z up).": "许多 CAD 程序的文件以 Y 为上轴,因此在此处打开时会平躺(Z 朝上)。", - "Filter": "筛选", - "Find in Browser": "在浏览器中查找", - "Copy Error Message": "复制错误消息", - "Copy Warning Message": "复制警告消息", - "Flat size": "平板尺寸", - "Follow camera (Look At sketches)": "跟随相机(注视草图)", - "Font": "字体", - "Full Length": "全长", - "Gap": "间隙", - "Grid": "网格", - "Height": "高度", - "Home view": "主视图", - "In This Design": "在此设计中", - "Interferes": "发生干涉", - "Issue title": "Issue 标题", - "Joint Origin1": "接头原点1", - "Keep Tools": "保留工具", - "Later": "稍后", - "Leave it": "保持原样", - "Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "旧版面附着。重新绑定到经验证的面可创建精确附着。", - "Length": "长度", - "Length units": "长度单位", - "Library": "零件库", - "Loop": "循环", - "Margin": "余量", - "Mass": "质量", - "Material": "材质", - "Mid Radius": "中间半径", - "Modeled": "已建模", - "More toolbar panels": "更多工具栏面板", - "Motion": "运动", - "Move Type": "移动类型", - "Move earlier": "向前移动", - "Move later": "向后移动", - "Name": "名称", - "No crash reports.": "没有崩溃报告。", - "No matching appearances": "没有匹配的外观", - "Not available yet": "暂不可用", - "Opacity": "不透明度", - "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": "另一侧", - "Parameter values": "参数值", - "Per Edge": "每条边", - "Pick the tool bodies": "选择工具实体", - "Place at the origin instead": "改为放置在原点", - "Playback": "播放", - "Position": "位置", - "Position (0 to 1)": "位置(0 到 1)", - "Position along the edge, 0 at the start end, 1 at the other": "沿边的位置,起点端为 0,另一端为 1", - "Preview leaves the current design unchanged.": "预览不会更改当前设计。", - "RECENT": "最近使用", - "Radius Fit": "半径拟合", - "Ratio": "比率", - "Recover": "恢复", - "Recover unsaved design?": "恢复未保存的设计?", - "Remove Tools": "移除工具", - "Remove from list": "从列表移除", - "Remove private design details or paths before sharing.": "共享前请移除私密设计细节或路径。", - "Remove the column": "移除此列", - "Remove the track": "移除轨迹", - "Remove this point": "移除此点", - "Report a bug — review a screenshot and open a GitHub draft": "报告缺陷 — 复核截图并开启 GitHub 草稿", - "Reset Toolbar": "重置工具栏", - "Restore the inherited component or physical material appearance": "还原继承的组件或物理材质外观", - "Result": "结果", - "Retake screenshot": "重新截图", - "Reverse": "反向", - "Reverse Direction": "反向", - "Revert": "还原", - "Revert All Positions": "还原所有位置", - "Review the report and screenshot before opening GitHub.": "打开 GitHub 前请审阅报告和截图。", - "Rim Edge": "轮缘边", - "Roll History Marker Here": "将历史标记滚动到此处", - "Rule": "规则", - "Saved preview. Geometry is being checked before editing.": "已保存预览。编辑前正在检查几何。", - "Scale factor": "比例因子", - "Search": "搜索", - "Search commands": "搜索命令", - "Select bodies (a face picks its body)": "选择实体(单击面即选择其所属实体)", - "Select bodies or faces instead": "改为选择实体或面", - "Selection filter": "选择筛选", - "Semantic faces share their appearance across instances.": "语义面在各实例间共享外观。", - "Shape": "形状", - "Show Agent Cursor": "显示代理光标", - "Show in folder": "在文件夹中显示", - "Size": "大小", - "Sketch plane has no body-face attachment.": "草图平面没有实体面附着。", - "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft 在这些设计保存前已关闭。可以打开它们的上次自动保存。", - "Speed": "速度", - "Stand it up": "将其立起", - "Stand it up: a quarter turn about X, as one Move feature you can undo.": "将其立起:绕 X 轴旋转四分之一周,作为一个可撤销的移动特征。", - "Stand this part up?": "立起此零件?", - "Step": "步骤", - "Steps": "步数", - "Suppressed": "已抑制", - "Swap Ends": "交换端点", - "Tangent Chain": "相切链", - "The dashed sketch is a saved plane guide. Select a new face to repair the attachment.": "虚线草图是已保存的平面引导。选择一个新面以修复附着。", - "The saved author occurrence is missing. Select a valid author placement before rebinding.": "保存的作者实例缺失。重新绑定前请选择有效的作者放置。", - "Then": "操作", - "These features will be deleted:": "以下特征将被删除:", - "These features will fail:": "以下特征将失败:", - "This child is shared. Deleting it removes it from 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.": "此面无法提供持久附着。请选择其他面或显式使用固定平面。", - "To Offset": "偏移", - "Tolerance": "公差", - "Type": "类型", - "Updating the preview": "正在更新预览", - "Use fixed plane": "使用固定平面", - "VIEW": "视图", - "Value": "值", - "Volume": "体积", - "Wall": "壁厚", - "When": "条件", - "Width": "宽度", - "Will fail": "将失败", - "angle, height": "角度、高度", - "command name": "命令名称", - "expression, e.g. 25 mm": "表达式,例如 25 mm", - "fits the face, e.g. M8": "适配该面,例如 M8", - "from the rule": "来自规则", - "needs two joints": "需要两个接头", - "new configuration": "新配置", - "new name": "新名称", - "new parameter": "新参数", - "no interference": "无干涉", - "no joint that moves yet": "尚无运动接头", - "no picture": "无图片", - "pick a hole to seat it, or OK places it at the origin": "选择一个孔放置,或单击确定放置在原点", - "pick one or two vertices, edges or faces": "选择一个或两个顶点、边或面", - "the parts library is not available": "零件库不可用", - "to the next face": "到下一个面", - "Revert Position": "恢复位置", - "Construction": "构造", - "Faces": "面", - "Edges": "边", - "Vertices": "顶点", - "Sketch geometry and profiles": "草图几何和轮廓", - "Sketch curves": "草图曲线", - "Sketch points": "草图点", - "Sketch dimensions": "草图尺寸", - "Sketch constraints": "草图约束", - "0 turns it off": "0 表示关闭", - "Show the pointer an AI agent moves (#35)": "显示 AI 代理移动的指针(#35)", - "Follow the camera (Look At sketches)": "跟随相机(注视草图)", - "Flat": "平面", - "Save Rule": "保存规则", - "Preview Row": "预览行", - "Add condition": "添加条件", - "Apply to selection": "应用到选择", - "Remove override": "移除覆盖", - "Copy screenshot": "复制截图", - "Remove screenshot": "移除截图", - "Use active author placement": "使用活动作者放置", - "Reattach selected face": "重新附着所选面", - "Use saved fixed plane": "使用已保存的固定平面", - "Use selected face as fixed plane": "使用所选面作为固定平面", - "View navigator": "视图导航器", - "Signed axes": "带符号轴", - "Cube": "立方体", - "Middle double-click": "中键双击", - "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": "在视图中双击中键:主视图(主视图,框住所显示的内容)、适合窗口(框住所显示的内容,保持方向)或无动作", - "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).": "“选择其他”:在模型上按住左键(或右键单击 › 选择其他…)列出光标下的所有对象;在同一位置再次单击可选择该处的下一个对象。双击中键转到主视图(首选项 › 导航)。", - "cmd.render_backends": "渲染后端", - "cmd.view_navigate": "导航视图", - "ui.animateJoint": "动画接头", - "ui.calibrate": "校准", - "ui.customizeToolbar": "自定义工具栏…", - "ui.editJointLimits": "编辑接头限制", - "ui.exportDxf": "导出 DXF…", - "ui.findInTimeline": "在时间线中查找", - "ui.findInWindow": "在窗口中查找", - "ui.fit": "适合", - "ui.groupSelected": "将所选编组", - "ui.hideAxes": "隐藏轴", - "ui.hideDimension": "隐藏尺寸", - "ui.hideOrigin": "隐藏原点", - "ui.hidePlanes": "隐藏平面", - "ui.hideProfile": "隐藏轮廓", - "ui.homeView": "主视图", - "ui.isolate": "隔离", - "ui.lock": "锁定", - "ui.newSketchGroup": "新建草图组", - "ui.normalConstruction": "普通 / 构造", - "ui.orbit": "环绕", - "ui.heading_position": "位置", - "ui.pan": "平移", - "ui.pinToShortcuts": "固定到快捷方式", - "ui.pinToToolbar": "固定到工具栏", - "ui.properties": "属性", - "ui.design_properties.project": "项目", - "ui.design_properties.part_number": "零件号", - "ui.design_properties.revision": "版本", - "ui.design_properties.author": "作者", - "ui.design_properties.organization": "组织", - "ui.design_properties.description": "描述", - "ui.design_properties.license": "许可证", - "ui.design_properties.not_text": "已保存为非文本值;在此输入将替换它。", - "ui.design_properties.exports": "导出 STEP、IGES 和 3MF 时,若格式有对应字段,会写入这些属性。", - "ui.design_properties.others": "其他工具的数据", - "ui.design_properties.others_note": "按原样保存在设计中,从不导出。", - "ui.removeSection": "移除剖面", - "ui.removeFromToolbar": "从工具栏移除", - "ui.repeat": "重复", - "ui.report_a_bug": "报告缺陷", - "ui.restore": "还原", - "ui.heading_setup": "设置", - "ui.selectOther": "选择其他…", - "ui.selectTangentChain": "选择相切链", - "ui.showAll": "显示全部", - "ui.showAllBodies": "显示所有实体", - "ui.showAxes": "显示轴", - "ui.showDimension": "显示尺寸", - "ui.showOrigin": "显示原点", - "ui.showPlanes": "显示平面", - "ui.suppress": "抑制", - "ui.command_palette_hint": "输入命令,例如 {example} — 或按 S 搜索", - "ui.unground": "取消固定", - "ui.unisolate": "取消隔离", - "ui.unlock": "解锁", - "ui.unsuppress": "取消抑制", - "ui.updateToCurrentView": "更新为当前视图", - "ui.zoom": "缩放", - "ui.command_done": "{command} 完成", - "drive.stopped_by_loop": "停在 {value}:经过 {joint} 的环路无法再闭合", - "drive.stopped_by_contact": "停在 {value}:{a} 会穿过 {b}", - "drive.unconnected": "没有任何移动:{part} 未连接到任何固定的零部件", - "timeline.group": "新建特征文件夹", - "timeline.ungroup": "移除特征文件夹", - "timeline.rename_group": "重命名特征文件夹", - "timeline.move_to_group": "将特征移至文件夹", - "timeline.move_many": "移动时间线项目", - "timeline.reorder_many": "特征重新排序", - "ui.show_construction_geometries": "构造几何图元", - "ui.total_angle": "总角度", - "sketch_text.builtin_font": "{family}(内置)", - "sketch_text.font_search": "搜索字体", - "sketch_text.loading_fonts": "正在查找已安装字体…", - "sketch_text.use_font_file": "使用字体文件 {path}", - "sketch_text.bold": "粗体", - "sketch_text.italic": "斜体", - "sketch_text.align_left": "左对齐", - "sketch_text.align_center": "居中", - "sketch_text.align_right": "右对齐", - "sketch_text.path_hint": "文字所跟随的草图曲线:先单击此处,再选择曲线", - "sketch_text.path_clear": "将文字移离其曲线", - "Style": "样式", - "Alignment": "对齐", - "Letter Spacing": "字间距", - "Line Spacing": "行间距", - "Path": "路径", - "sketch_text.on_path": "文字沿路径排列:由曲线放置", - "ui.analysis": "分析", - "ui.edit_section_analysis": "编辑截面分析", - "cmd.library_inspect": "检查本地库", - "cmd.library_export": "导出设计库", - "cmd.library_apply": "应用本地库条目", - "Thin": "薄壁", - "Thin Extrude": "薄壁拉伸", - "Wall Location": "壁位置", - "Wall Thickness": "壁厚度", - "Thickness Outside": "外侧厚度", - "Inside": "内侧", - "Outside": "外侧", - "Profiles/Curves": "轮廓/曲线", - "cmd.material_properties_validate": "验证物理材料数据", - "cmd.material_properties_directional": "方向弹性模量", + "update.available": "SolidCraft {version} 已发布", "update.button": "更新", "update.button_tip": "SolidCraft {version} 已发布", - "install.menu": "安装应用…", - "install.button_tip": "将 SolidCraft 安装为应用:在独立窗口中打开,离线也能使用", - "install.title": "安装 SolidCraft", - "install.steps_intro": "Safari 通过自身的菜单安装网页应用:", - "install.home_screen_1": "轻点“共享”(若不在工具栏上,则在 … 菜单中)。", - "install.home_screen_2": "选择“添加到主屏幕”。", - "install.home_screen_3": "轻点“添加”。", - "install.home_screen_after": "之后 SolidCraft 从主屏幕上的图标打开,不显示 Safari 的工具栏,离线也能使用。", - "install.dock_1": "选择“文件”›“添加到程序坞”。", - "install.dock_2": "点按“添加”。", - "install.dock_after": "之后 SolidCraft 从程序坞在独立窗口中打开,离线也能使用。", - "install.done": "完成", - "update.title": "有可用更新", - "update.available": "SolidCraft {version} 已发布", - "update.you_have": "当前版本为 {version}。", - "update.no_notes": "此版本没有发布说明。", - "update.system_hint": "此副本为 {kind}。用以下命令更新:", - "update.package_hint": "此副本来自 {kind}。下载新软件包后用以下命令安装:", - "update.copy": "复制", - "update.file": "将下载 {file}。", - "update.download": "下载", - "update.release_page": "打开发布页面", - "update.skip": "跳过此版本", - "update.later": "稍后提醒", - "update.prefs_label": "更新", "update.check_automatically": "自动检查更新", "update.check_now": "立即检查", "update.checking": "正在检查…", - "update.failed": "无法检查: {error}", - "update.up_to_date": "SolidCraft 已是最新版本。", - "update.prefs_note": "当前为 SolidCraft {version}({kind})。检查时只向 GitHub 查询最新版本,不发送其他任何数据。", - "update.prefs_dev": "这是开发版本({version}),不检查更新。", - "update.show": "显示 {version} 更新", - "update.prefs_flatpak": "此副本({version})由 Flatpak 更新:运行 {command} 或使用软件中心。SolidCraft 不会自行检查。", - "update.update_now": "立即更新", - "update.install_msi": "安装(将关闭 SolidCraft)", + "update.copy": "复制", + "update.dmg_opened": "磁盘映像已校验并打开:将 SolidCraft 拖到“应用程序”替换旧版本,然后重启 SolidCraft。", + "update.download": "下载", "update.download_open": "下载并打开", "update.downloading": "正在下载并校验… {done} / {total} MB", + "update.failed": "无法检查: {error}", + "update.file": "将下载 {file}。", + "update.install_failed": "更新未安装:{error}。未做任何更改;可用“下载”获取安装包。", + "update.install_msi": "安装(将关闭 SolidCraft)", "update.installed": "SolidCraft {version} 已安装。重新启动后生效。", + "update.installer_started": "SolidCraft 关闭后将启动安装程序。", + "update.later": "稍后提醒", + "update.no_notes": "此版本没有发布说明。", + "update.package_hint": "此副本来自 {kind}。下载新软件包后用以下命令安装:", + "update.prefs_dev": "这是开发版本({version}),不检查更新。", + "update.prefs_flatpak": "此副本({version})由 Flatpak 更新:运行 {command} 或使用软件中心。SolidCraft 不会自行检查。", + "update.prefs_label": "更新", + "update.prefs_note": "当前为 SolidCraft {version}({kind})。检查时只向 GitHub 查询最新版本,不发送其他任何数据。", + "update.release_page": "打开发布页面", "update.restart": "立即重启", "update.restart_later": "稍后", - "update.installer_started": "SolidCraft 关闭后将启动安装程序。", - "update.dmg_opened": "磁盘映像已校验并打开:将 SolidCraft 拖到“应用程序”替换旧版本,然后重启 SolidCraft。", - "update.install_failed": "更新未安装:{error}。未做任何更改;可用“下载”获取安装包。", - "cmd.render_settings_get": "渲染设置", - "cmd.render_settings_set": "保存渲染设置", - "cmd.render_scene": "检查渲染场景", - "cmd.render_settings_apply": "应用渲染相机", - "toolbar.render": "渲染", - "toolbar.render_scene": "场景", - "render.preview": "集成预览", - "render.preview_help": "光栅着色和混合透明度。暂不支持折射、HDRI 和最终渲染。", - "render.setup_name": "设置名称", - "render.background": "场景背景", - "render.perspective": "透视相机", - "render.fit": "适配产品视图", - "render.restore_camera": "恢复已保存相机", - "render.save_setup": "保存设置", - "render.unsaved": "未保存的预览更改", - "render.reload_settings": "重新加载已保存设置", - "render.unavailable_preview": "此设置请求了不可用的预览配置。", - "render.use_preview": "使用集成预览", - "render.navigation_help": "相机的操作与设计中相同(首选项 › 导航)。保存设置会记录当前相机。", - "render.return_design": "返回设计", - "render.image_title": "渲染图像", - "render.image_help": "CPU 预览图像 · PNG · 近似透明度", - "render.image_width": "宽度", - "render.image_height": "高度", - "render.image_transparent": "透明背景", - "render.image_check": "检查渲染请求", - "render.image_supported": "支持此渲染请求;开始时将再次检查队列和内存池。", - "render.image_queued": "等待渲染", - "render.image_preparing": "正在准备图像", - "render.image_running": "正在渲染图像", - "render.image_encoding": "正在编码 PNG", - "render.image_cancelling": "正在取消", - "render.image_cancelled": "渲染已取消", - "render.image_completed": "图像可导出", - "render.image_failed": "渲染失败", - "render.image_unknown": "渲染状态不可用", - "render.image_reduce": "请尝试更小的图像或更简单的场景。", - "render.image_too_large": "超出图像限制:每边 4096 像素,总计 4,194,304 像素。", - "render.image_use_largest": "使用此宽高比下的最大尺寸:", - "render.image_cancel": "取消渲染", - "render.image_stale": "此图像使用后续更改之前捕获的场景。", - "render.image_start": "开始渲染", - "render.image_overwrite": "替换现有文件", - "render.image_export": "导出 PNG", - "cmd.render_preflight": "检查渲染请求", - "cmd.render_start": "渲染图像", - "cmd.render_status": "渲染进度", - "cmd.render_cancel": "取消渲染", - "cmd.render_export": "导出 PNG", - "toolbar.image": "图像", - "appearance.surface_response": "表面响应", - "appearance.pbr_opaque": "不透明 PBR", - "appearance.metallic": "金属度", - "appearance.roughness": "粗糙度", - "appearance.dielectric_ior": "电介质折射率", - "appearance.pbr_help": "在渲染工作区或产品 PNG 中查看此表面。不支持折射或透射。", - "render.opaque_preview_help": "不透明 PBR 和纯色;透明效果使用混合。不支持折射、HDRI 和最终渲染。", - "render.opaque_image_summary": "预览 PNG · 不透明 PBR · 混合透明", - "UNTRIM": "取消修剪", - "Face": "面", - "Holes": "孔", - "Holes (edges on them)": "孔(孔上的边)", - "In place (surfaces)": "原位(曲面)", - "None": "无", - "Picked": "所选", - "Restore outer boundary": "恢复外边界", - "RULED SURFACE": "直纹曲面", - "Mitre": "斜接", - "Reference face": "参考面", - "Round": "圆角", - "joint.one_component": "这些零件是同一组件的实体:{bodies}。接头使一个组件相对另一个组件运动,因此每个零件都需要自己的组件。", - "joint.one_body": "两次选择都在 {body} 上。请在另一个零件上选择第二个。", - "joint.from_bodies_hint": "每个所选实体移入各自的新组件,位置保持不变。", - "Circumference": "周长", - "Arc length": "弧长", - "Slot width": "槽宽", - "Centre to centre": "中心距", - "Overall length": "总长", - "Min": "最小", - "Max": "最大", - "coupling.gear_1": "齿轮 1", - "coupling.gear_2": "齿轮 2", - "coupling.pinion": "小齿轮", - "coupling.rack": "齿条", - "coupling.nut": "螺母", - "coupling.radius_1": "半径 1", - "coupling.radius_2": "半径 2", - "coupling.internal": "内齿轮", - "coupling.pitch": "螺距", - "coupling.picked": "已拾取", - "coupling.not_round": "不是圆柱面", - "coupling.gear_1_pick": "齿轮 1(可选)", - "coupling.gear_2_pick": "齿轮 2(可选)", - "coupling.pinion_pick": "小齿轮(可选)", - "coupling.needs_turns": "需要两个旋转接头", - "coupling.needs_turn_and_slide": "需要一个旋转接头和一个滑动接头" + "update.show": "显示 {version} 更新", + "update.skip": "跳过此版本", + "update.system_hint": "此副本为 {kind}。用以下命令更新:", + "update.title": "有可用更新", + "update.up_to_date": "SolidCraft 已是最新版本。", + "update.update_now": "立即更新", + "update.you_have": "当前版本为 {version}。" } diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index a6589a809..ff8ac778f 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -32,15 +32,28 @@ impl Catalog { } static ENGLISH: Catalog = Catalog::new("en", "English", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/en.json"))); -static JAPANESE: Catalog = Catalog::new("ja", "日本語", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/ja.json"))); static GERMAN: Catalog = Catalog::new("de", "Deutsch", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/de.json"))); static FRENCH: Catalog = Catalog::new("fr", "Français", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/fr.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 RUSSIAN: Catalog = Catalog::new("ru", "Русский", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/ru.json"))); -static UKRAINIAN: Catalog = Catalog::new("uk", "Українська", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/uk.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 CHINESE: Catalog = Catalog::new("zh", "中文", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/zh.json"))); -pub const LOCALES: &[&Catalog] = &[&ENGLISH, &JAPANESE, &GERMAN, &FRENCH, &KOREAN, &RUSSIAN, &UKRAINIAN, &TURKISH, &CHINESE]; +/// English first (the fallback), then by language id, one per line so that adding a language +/// doesn't edit a line another addition edits. +#[rustfmt::skip] +pub const LOCALES: &[&Catalog] = &[ + &ENGLISH, + &GERMAN, + &FRENCH, + &JAPANESE, + &KOREAN, + &RUSSIAN, + &TURKISH, + &UKRAINIAN, + &CHINESE, +]; pub fn is_supported(id: &str) -> bool { LOCALES.iter().any(|catalog| catalog.id == id) @@ -188,6 +201,15 @@ pub fn tr_name(text: &str) -> String { #[cfg(test)] mod tests { use super::*; + + /// The languages are listed English first, then by id, so adding one doesn't edit the + /// line another addition edits. + #[test] + fn locales_are_listed_english_first_then_by_id() { + let ids: Vec<&str> = LOCALES.iter().map(|c| c.id).collect(); + assert_eq!(ids.first(), Some(&"en")); + assert!(ids[1..].is_sorted(), "{ids:?}"); + } use std::collections::BTreeSet; fn placeholders(text: &str) -> BTreeSet<&str> { diff --git a/xtask/src/licences.rs b/xtask/src/licences.rs index 16ba4a9b7..d69123893 100644 --- a/xtask/src/licences.rs +++ b/xtask/src/licences.rs @@ -2,8 +2,10 @@ //! into the shipped programs (solidcraft, solidcraft-cli, solidcraft-web), read from //! `cargo metadata` and the crates' own licence files. The programs embed it (Help ▸ About ▸ //! Licences, `solidcraft-cli licences`), so a release download needs no licence files beside it. -//! `--check` (part of `cargo xtask ci`) fails when the committed file is out of date, e.g. after a -//! dependency changed. +//! `--check` (part of `cargo xtask ci`) generates it without writing it: it fails when the +//! dependency graph can't be read, and only reports a file that is out of date, since pull +//! requests leave it to the Generated files workflow (`.github/workflows/generated.yml`), which +//! rewrites it on main after each merge. use std::collections::{BTreeMap, BTreeSet, VecDeque}; use std::path::Path; @@ -21,7 +23,10 @@ pub fn run(root: &Path, check: bool) -> Result<(), String> { if check { let old = std::fs::read_to_string(&path).unwrap_or_default(); if old.replace("\r\n", "\n") != text { - return Err(format!("{FILE} is out of date (dependencies changed): run `cargo xtask licences` and commit it")); + // Not an error: pull requests don't edit the file (two that did would always conflict); + // the Generated files workflow rewrites it on main after the merge. + println!("licences: {FILE} will change when this lands (the Generated files workflow rewrites it on main)"); + return Ok(()); } println!("licences: {FILE} is up to date"); return Ok(()); diff --git a/xtask/src/lists.rs b/xtask/src/lists.rs new file mode 100644 index 000000000..ce3abf360 --- /dev/null +++ b/xtask/src/lists.rs @@ -0,0 +1,68 @@ +//! `cargo xtask lists [--fix]`: files that many pull requests add to are kept in a canonical, +//! sorted form, so two changes that each add an item meet only when their items are neighbours +//! (CONTRIBUTING.md, "Lists many changes add to"). Checked by `cargo xtask ci` and the Lists +//! workflow; `--fix` rewrites them. +//! +//! - The message catalogs (`assets/locales/*.json`): one message per line, sorted by id, no +//! duplicate ids, as `serde_json` pretty-prints them. + +use std::path::Path; + +use serde_json::{Map, Value}; + +const LOCALES: &str = "assets/locales"; + +pub fn run(root: &Path, fix: bool) -> Result<(), String> { + let dir = root.join(LOCALES); + let entries = std::fs::read_dir(&dir).map_err(|e| format!("{}: {e}", dir.display()))?; + let mut files: Vec<_> = entries.filter_map(Result::ok).map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "json")).collect(); + files.sort(); + let mut stale = Vec::new(); + for path in files { + let text = std::fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?; + let canonical = canonical(&text).map_err(|e| format!("{}: {e}", path.display()))?; + if canonical == text.replace("\r\n", "\n") { + continue; + } + if fix { + std::fs::write(&path, &canonical).map_err(|e| format!("{}: {e}", path.display()))?; + println!("lists: sorted {}", path.display()); + } else { + stale.push(path.strip_prefix(root).unwrap_or(&path).display().to_string()); + } + } + if !stale.is_empty() { + return Err(format!( + "not sorted one message per line (or an id appears twice): {}\nrun `cargo xtask lists --fix` and commit the result", + stale.join(", ") + )); + } + println!("lists: message catalogs are sorted"); + Ok(()) +} + +/// A catalog as it should be written: its messages sorted by id, one per line. A repeated id +/// keeps its last message, the one the app reads. +pub fn canonical(text: &str) -> Result { + let map: Map = match serde_json::from_str(text).map_err(|e| e.to_string())? { + Value::Object(map) => map, + _ => return Err("a catalog must be a JSON object".into()), + }; + if let Some((id, _)) = map.iter().find(|(_, v)| !v.is_string()) { + return Err(format!("message `{id}` is not a string")); + } + Ok(serde_json::to_string_pretty(&Value::Object(map)).map_err(|e| e.to_string())? + "\n") +} + +#[cfg(test)] +mod tests { + use super::canonical; + + #[test] + fn catalogs_are_sorted_one_per_line_and_a_repeated_id_keeps_its_last_message() { + let text = "{\n \"b\": \"B\",\n \"a\": \"A\",\n \"b\": \"B2\"\n}"; + assert_eq!(canonical(text).unwrap(), "{\n \"a\": \"A\",\n \"b\": \"B2\"\n}\n"); + assert!(canonical("[]").is_err()); + assert!(canonical("{\"a\": 1}").is_err()); + } +} diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 390e1751c..8d009c638 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -10,6 +10,7 @@ mod features; mod i18n; mod layers; mod licences; +mod lists; mod test; mod web_offline; mod web_offline_test; @@ -46,7 +47,10 @@ commands: into target/book licences [--check] write THIRD-PARTY-LICENSES.txt (the licences of every shipped crate, embedded - in the programs); --check fails when it is out of date + in the programs); --check only reports when it is out of date: pull requests + leave it to the Generated files workflow on main + lists [--fix] check that files many changes add to are sorted one item per line (the + message catalogs in assets/locales); --fix sorts them test [CARGO ARGS] [-- TEST ARGS] build the tests with the ci profile, then run every test binary at once (and the doc tests alongside) @@ -57,7 +61,7 @@ commands: web-offline-test [--site DIR] check in headless Chrome that the web app works offline and updates to a new build (a stand-in app, or the web build in DIR such as dist/web) - ci fmt --check, assets, licences --check, layers, clippy -D warnings, then the tests + ci fmt --check, assets, licences --check, lists, layers, clippy -D warnings, then the tests with the wasm check alongside, then web-offline-test when Chrome is installed (stops at the first failing step) "; @@ -78,6 +82,7 @@ fn main() -> ExitCode { } Some("book") => book::run(&root(), !rest.contains(&"--no-build")), Some("licences") => licences::run(&root(), rest.contains(&"--check")), + Some("lists") => lists::run(&root(), rest.contains(&"--fix")), Some("test") => { let (cargo_args, test_args) = rest.iter().position(|a| *a == "--").map_or((&rest[..], &[][..]), |i| (&rest[..i], &rest[i + 1..])); test::run(cargo_args, test_args, vec![test::doc_tests(cargo_args, test_args)]) @@ -358,6 +363,7 @@ fn cmd_ci() -> Result<(), String> { run(c, "cargo fmt --check")?; assets::run(&root())?; licences::run(&root(), true)?; + lists::run(&root(), false)?; cmd_layers()?; let mut c = cargo(); c.args(["clippy", "--workspace", "--all-targets", "--profile", "ci", "--", "-D", "warnings"]); From 105a3146c08aa699d30b13dd5f0b6e83750e5fd6 Mon Sep 17 00:00:00 2001 From: DuBearte <130190089+DuBearte@users.noreply.github.com> Date: Thu, 15 Oct 2026 22:04:42 -0400 Subject: [PATCH 29/92] Toolbar: a second click on a drop-down's button closes it (#1522) (#1576) The workspace switcher's menu closed on the press (a press outside the menu) and the click reopened it; the menu now keeps the button that opened it, a press there is not outside, and its click toggles. A panel's label toggles its command list instead of always opening it. Fixes #1522 Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/context_menu.rs | 17 +++++++++++- crates/ui-egui/src/toolbar.rs | 42 ++++++++++++++++++++++++++++-- 2 files changed, 56 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index fa5f5c544..cad1081ea 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -179,6 +179,9 @@ pub struct MenuState { pub over_geometry: bool, /// The plane under the cursor when the viewport menu opened: it offers a sketch on it. pub plane: Option, + /// The button that opened the menu, when it toggles it: a press there is not a press outside, + /// so its click closes the menu instead of closing and reopening it (#1522). + opener: Option, } #[derive(Clone, Debug, PartialEq)] @@ -1349,12 +1352,24 @@ pub fn open_for(app: &mut SolveApp, at: Pos2, target: Target) { app.menu.radial = target == Target::Viewport && app.preferences.radial_context_menu; app.menu.target = target; app.menu.flick = false; + app.menu.opener = None; app.viewport.context_menu = Some(at); } +/// A button's menu: a click opens it, and a click on the same button while it is open closes it. +pub fn toggle_for(app: &mut SolveApp, opener: Rect, at: Pos2, target: Target) { + if app.viewport.context_menu.is_some() && app.menu.target == target && app.menu.opener == Some(opener) { + close(app); + } else { + open_for(app, at, target); + app.menu.opener = Some(opener); + } +} + pub fn close(app: &mut SolveApp) { app.viewport.context_menu = None; app.menu.flick = false; + app.menu.opener = None; } /// Open the menu at a point for automation: the pointer moves there first so what is under it @@ -1557,8 +1572,8 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { let target = app.menu.target.clone(); let list = items(app, &target); let mut picked: Option = None; - let mut inside = false; let pointer = ctx.input(|i| i.pointer.latest_pos()); + let mut inside = app.menu.opener.is_some_and(|r| pointer.is_some_and(|p| r.contains(p))); let list_at = if app.menu.radial { let c = radial_center(at, screen); diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index c414ceece..effc2bfef 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -582,7 +582,7 @@ pub fn toolbar(app: &mut SolveApp, ui: &mut egui::Ui) { caret(&painter, pos2(ws.center().x + 27.0, ws.top() + 52.0), t.text); painter.text(pos2(ws.center().x, ws.top() + 69.0), Align2::CENTER_CENTER, app.tr("ui.workspace"), FontId::proportional(10.0), t.text_dim); if wresp.on_hover_text(app.tr("ui.change_workspace")).clicked() { - crate::context_menu::open_for(app, ws.left_bottom(), crate::context_menu::Target::Workspace); + crate::context_menu::toggle_for(app, ws, ws.left_bottom(), crate::context_menu::Target::Workspace); } crate::scenario::publish_rect("toolbar", r); crate::scenario::publish_rect("workspace_switcher", ws); @@ -830,8 +830,16 @@ pub fn toolbar(app: &mut SolveApp, ui: &mut egui::Ui) { let gy = lr.center().y - g.size().y / 2.0; painter.galley(pos2(gx, gy), g, lc); caret(&painter, pos2(gx + gw / 2.0 + 6.0, lr.center().y), lc); + // The label toggles its drop-down (#1522). if lresp.clicked() { - ui.ctx().data_mut(|d| d.insert_temp(egui::Id::new("sc_panel_open"), popup_id)); + ui.ctx().data_mut(|d| { + let key = egui::Id::new("sc_panel_open"); + if d.get_temp::(key) == Some(popup_id) { + d.remove::(key); + } else { + d.insert_temp(key, popup_id); + } + }); } // Labels, gaps and margins append; actual buttons keep their insert-before target. // Respect the current layer so a dropdown covering the panel is not a drop target. @@ -1813,3 +1821,33 @@ mod icon_accent_tests { } } } + +#[cfg(test)] +mod dropdown_toggle_tests { + use crate::scenario::{Harness, rect_of}; + use serde_json::json; + + /// A second click on the button that opened a drop-down closes it (#1522): the workspace + /// switcher's menu, and a panel's command list. + #[test] + fn a_second_click_on_its_button_closes_a_drop_down() { + let mut h = Harness::new(); + h.frames(3); + let ws = rect_of("workspace_switcher").unwrap().center(); + h.step(&json!({"click": [ws.x, ws.y]})).unwrap(); + assert!(h.app.viewport.context_menu.is_some(), "the first click opens the workspace menu"); + h.step(&json!({"click": [ws.x, ws.y]})).unwrap(); + h.frames(2); + assert!(h.app.viewport.context_menu.is_none(), "the second click closes it instead of reopening it"); + h.step(&json!({"click": [ws.x, ws.y]})).unwrap(); + assert!(h.app.viewport.context_menu.is_some(), "and a third opens it again"); + h.step(&json!({"key": "Escape"})).unwrap(); + + h.step(&json!({"click": {"handle": "panel:SOLID:CREATE"}})).unwrap(); + h.frames(2); + assert!(rect_of("toolbar_dropdown").is_some(), "the first click opens the panel's list"); + h.step(&json!({"click": {"handle": "panel:SOLID:CREATE"}})).unwrap(); + h.frames(2); + assert!(rect_of("toolbar_dropdown").is_none(), "the second click closes it"); + } +} From b562ab51e114ccca32487664eb5e73751bc218b0 Mon Sep 17 00:00:00 2001 From: DuBearte <130190089+DuBearte@users.noreply.github.com> Date: Thu, 15 Oct 2026 22:05:55 -0400 Subject: [PATCH 30/92] Agent discovery test: the fixture uses a name Windows runs (#1554) (#1575) The search-order test wrote an extensionless codex-acp, which Windows discovery rightly skips; it now writes the first name this platform looks for (codex-acp.exe on Windows, codex-acp elsewhere). Fixes #1554 Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/agent_chat/discover.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/agent_chat/discover.rs b/crates/ui-egui/src/agent_chat/discover.rs index c7f24c690..1bf100fc1 100644 --- a/crates/ui-egui/src/agent_chat/discover.rs +++ b/crates/ui-egui/src/agent_chat/discover.rs @@ -306,8 +306,10 @@ mod tests { let (a, b) = (root.join("a"), root.join("b")); std::fs::create_dir_all(&a).unwrap(); std::fs::create_dir_all(&b).unwrap(); - std::fs::write(b.join("codex-acp"), "").unwrap(); - assert_eq!(find_in("codex-acp", &[a.clone(), b.clone()]), Some(b.join("codex-acp"))); + // A name this platform runs: Windows looks only for `.exe`/`.cmd`/`.bat` (#1554). + let name = names_for("codex-acp", cfg!(windows)).remove(0); + std::fs::write(b.join(&name), "").unwrap(); + assert_eq!(find_in("codex-acp", &[a.clone(), b.clone()]), Some(b.join(name))); assert_eq!(find_in("gemini", &[a, b]), None); let _ = std::fs::remove_dir_all(root); } From 1a552418820876a49c25a3924fb8f7be23a22f59 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Thu, 15 Oct 2026 22:17:39 -0400 Subject: [PATCH 31/92] Contributing: claim an issue with a draft PR (#1565) Check gh pr list --search "#N", then open a draft titled " (#N)" with an empty claim commit; the lowest-numbered open PR for an issue wins, and a draft with no pushes for 72 hours may be taken over after a comment. Agents on a shared machine check the load before a big build. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 10 ++++++++++ CLAUDE.md | 10 ++++++++++ CONTRIBUTING.md | 14 +++++++++++--- 3 files changed, 31 insertions(+), 3 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index f61b51e37..82492953b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -123,6 +123,16 @@ People trust SolidCraft with their designs; a crash loses their work. **This out 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. Don't claim by commenting or 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`, diff --git a/CLAUDE.md b/CLAUDE.md index 3becde411..5ed78acd5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -96,6 +96,16 @@ People trust SolidCraft with their designs; a crash loses their work. **This out - **Never break wasm**: everything below the apps must build for `wasm32-unknown-unknown` (`cargo xtask wasm`, part of `cargo xtask ci`). +## 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. Don't claim by commenting or 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`, diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c835471a0..ee6bf7496 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -245,9 +245,17 @@ and a fresh CI run: ## Sending a change 1. Work is tracked in [GitHub issues](https://github.com/bherbruck/solidcraft/issues), labelled - by area (`area:kernel`, `area:sketch`, `area:doc`, `area:ui`, `area:infra`). Before starting, - comment on the issue so it gets the `in progress` label and two people don't build the same - thing. For anything bigger than a bug fix that has no issue yet, open one first. + by area (`area:kernel`, `area:sketch`, `area:doc`, `area:ui`, `area:infra`). For anything + bigger than a bug fix that has no issue yet, open one first. **Claim the issue with a draft + PR** before you start, so two people don't build the same thing: + - Check nobody has it: `gh pr list -R bherbruck/solidcraft --state open --search "#N"`. + - Branch from the latest `main`, commit `git commit --allow-empty -m "claim: #N"`, push, and + open a **draft** PR titled ` (#N)`, e.g. `Fillet: variable radius along a chain (#123)`. + - **The lowest-numbered open PR for an issue wins.** If yours lost, close it (or offer to help + on the other one). + - 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. + - Mark the PR ready for review when it is done. 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. From 723c7b61c4b90fb1eff49fdfeb6c3f74505fc45c Mon Sep 17 00:00:00 2001 From: "H. Conrad" <78785932+Ian-cmd-ops@users.noreply.github.com> Date: Thu, 15 Oct 2026 19:18:31 -0700 Subject: [PATCH 32/92] Boolean: cut around a part's sealed voids when the whole cut fails (#1570) A cut clear of every void cuts the outer shell alone and puts the voids back (robustness seed 15 now builds). --- crates/kernel/src/body_lump_tests.rs | 23 +++++++++ crates/kernel/src/ops.rs | 75 ++++++++++++++++++++++++++++ tests/robustness/goldens.json | 5 +- 3 files changed, 101 insertions(+), 2 deletions(-) diff --git a/crates/kernel/src/body_lump_tests.rs b/crates/kernel/src/body_lump_tests.rs index 19457af34..89aa73ada 100644 --- a/crates/kernel/src/body_lump_tests.rs +++ b/crates/kernel/src/body_lump_tests.rs @@ -37,6 +37,29 @@ fn check_nested(body: &Body) { } } +/// Robustness seed 15, shrunk: a sphere cut at a corner of a part with a sealed internal void far +/// from the sphere. The same cut on the part without the void works; with it, the boolean failed +/// ("no result", then "the exact fallback … takes planar faces only"). A cut from a box or a +/// cylinder on the voided part worked. +#[test] +fn sphere_cut_far_from_a_void_keeps_the_void() { + let block = box_solid(Vec3::ZERO, Vec3::new(40.0, 40.0, 40.0)).unwrap(); + let cavity = box_solid(Vec3::new(25.0, 25.0, 25.0), Vec3::new(30.0, 30.0, 30.0)).unwrap(); + let hollow = boolean(&block, &cavity, BoolOp::Cut).unwrap().unwrap(); + assert_eq!(hollow.solid.boundaries().len(), 2, "the cavity is a second shell"); + let ball = sphere(Vec3::new(0.0, 0.0, 40.0), 8.0).unwrap(); + let cut = boolean(&hollow, &ball, BoolOp::Cut).unwrap().unwrap(); + // The block, less the cavity, less the eighth of the ball inside the corner. + let want = 64_000.0 - 125.0 - std::f64::consts::PI * 512.0 / 6.0; + let got = measure(&cut).unwrap().volume; + assert!((got - want).abs() < want * 1e-3, "volume {got}, want {want}"); + assert_eq!(cut.solid.boundaries().len(), 2, "the cavity stays a sealed second shell"); + let mesh = cut.tessellate_with(0.01, true).unwrap(); + for (p, material) in [(Vec3::new(27.5, 27.5, 27.5), false), (Vec3::new(1.0, 1.0, 39.0), false), (Vec3::new(20.0, 20.0, 20.0), true)] { + assert_eq!(mesh.contains(p), material, "material at {p:?}"); + } +} + #[test] fn nested_cavities_stay_with_their_material_islands_for_every_shell_order() { let body = nested_island(); diff --git a/crates/kernel/src/ops.rs b/crates/kernel/src/ops.rs index a78e73e9d..102b6e985 100644 --- a/crates/kernel/src/ops.rs +++ b/crates/kernel/src/ops.rs @@ -332,6 +332,15 @@ fn boolean_via(a: &Body, b: &Body, op: BoolOp, whole: &dyn Fn(&Body, &Body, Bool } } } + // A piece with sealed voids, cut clear of them: the outer shell alone, the voids put back. + if op == BoolOp::Cut && r.is_err() { + let (cut, report) = capture_boolean_diagnostics(|| cut_around_voids(a, b, whole)); + if let Ok(Some(x)) = cut { + r = Ok(Some(x)); + diagnostics = report; + diagnostics.push(BooleanFallback::new(BooleanStrategy::Piecewise)); + } + } if op == BoolOp::Union && let Ok(Some(body)) = &r && !preserves_planar_surfaces(a, b, body) @@ -374,6 +383,72 @@ fn boolean_via(a: &Body, b: &Body, op: BoolOp, whole: &dyn Fn(&Body, &Body, Bool r } +/// The most shells [`cut_around_voids`] takes apart. +const MAX_VOID_SHELLS: usize = 64; + +/// `a` cut by `b` around `a`'s voids: when `a` is one piece with sealed voids (inner shells) and +/// `b` stays clear of every void, the outer shell alone is cut and the voids are put back. The cut +/// of the whole failed on such bodies where the same cut of the outer shell works: a sphere cut +/// far from a void (robustness seed 15). `None` when `a` has no voids, `b` comes near one, or +/// the cut of the outer shell fails too. The result carries no history. +fn cut_around_voids(a: &Body, b: &Body, whole: &dyn Fn(&Body, &Body, BoolOp) -> Result>) -> Result> { + let shells = a.solid.boundaries().clone(); + if shells.len() < 2 || shells.len() > MAX_VOID_SHELLS || b.solid.boundaries().len() != 1 || a.lumps()?.len() != 1 { + return Ok(None); + } + let tol = (a.size() * 1e-3).max(1e-3); + let mut boxes = Vec::with_capacity(shells.len()); + for sh in &shells { + let piece = + guard("void shell", || Body::new(Solid::try_new(vec![sh.clone()]).map_err(|e| KernelError::Failed(format!("void shell: {e}")))?))?; + let m = piece.tessellate(tol)?; + if m.positions.is_empty() { + return Ok(None); + } + boxes.push(m.bounds()); + } + let extent = |i: usize| { + boxes.get(i).map_or(0.0, |x| { + let d = x.max - x.min; + d.x * d.y * d.z + }) + }; + let Some(outer) = (0..shells.len()).max_by(|i, j| extent(*i).total_cmp(&extent(*j))) else { return Ok(None) }; + let Some(ob) = boxes.get(outer) else { return Ok(None) }; + let tm = b.tessellate((b.size() * 1e-3).max(1e-3))?; + let tb = tm.bounds(); + // Clear of the tool by more than both meshes' deflection. + let gap = 4.0 * tol + (b.size() * 1e-3).max(1e-3); + let inside = |x: &solidcraft_geom::Aabb3| { + x.min.x >= ob.min.x && x.min.y >= ob.min.y && x.min.z >= ob.min.z && x.max.x <= ob.max.x && x.max.y <= ob.max.y && x.max.z <= ob.max.z + }; + let clear = |x: &solidcraft_geom::Aabb3| { + x.max.x + gap < tb.min.x + || tb.max.x + gap < x.min.x + || x.max.y + gap < tb.min.y + || tb.max.y + gap < x.min.y + || x.max.z + gap < tb.min.z + || tb.max.z + gap < x.min.z + }; + let mut voids = Vec::new(); + for (i, (sh, x)) in shells.iter().zip(&boxes).enumerate() { + if i == outer { + continue; + } + if !inside(x) || !clear(x) { + return Ok(None); + } + voids.push(sh.clone()); + } + let Some(outer_shell) = shells.get(outer) else { return Ok(None) }; + let alone = + guard("outer shell", || Body::new(Solid::try_new(vec![outer_shell.clone()]).map_err(|e| KernelError::Failed(format!("outer shell: {e}")))?))?; + let Some(cut) = boolean_via(&alone, b, BoolOp::Cut, whole)? else { return Ok(None) }; + let mut all = cut.solid.boundaries().clone(); + all.extend(voids); + Ok(Some(guard("voids back", || Body::new(Solid::try_new(all).map_err(|e| KernelError::Failed(format!("voids back: {e}")))?))?)) +} + /// Every face of an all-planar union must remain on an operand's original plane. /// Curved operands keep their existing surface-specific boolean handling. fn preserves_planar_surfaces(a: &Body, b: &Body, result: &Body) -> bool { diff --git a/tests/robustness/goldens.json b/tests/robustness/goldens.json index eae512b69..0728e06e2 100644 --- a/tests/robustness/goldens.json +++ b/tests/robustness/goldens.json @@ -16,7 +16,7 @@ "12": {"area":4668.664174,"bodies":2,"edges":59,"error":null,"faces":25,"outcome":"ok","rejected":0,"shells":2,"steps":["extruded profile","chamfer","join cylinder","join box","cut cylinder","circular pattern"],"unsupported":3,"volume":11874.471611}, "13": {"area":1967.991667,"bodies":3,"edges":85,"error":null,"faces":37,"outcome":"ok","rejected":1,"shells":3,"steps":["revolved section","cut cylinder","join box","rectangular pattern","cut cylinder","cut box","fillet","hole"],"unsupported":0,"volume":2647.948638}, "14": {"area":10553.267409,"bodies":1,"edges":43,"error":null,"faces":20,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","cut cylinder","shell","fillet"],"unsupported":0,"volume":10369.008764}, - "15": {"area":1974.784048,"bodies":1,"edges":40,"error":"boolean Cut: the operation failed: no result; the operation ","faces":18,"outcome":"failed","rejected":1,"shells":2,"steps":["revolved section","fillet","cut box","rectangular pattern","cut sphere","cut cylinder","cut sphere"],"unsupported":0,"volume":4781.224576}, + "15": {"area":1957.859861,"bodies":1,"edges":49,"error":null,"faces":21,"outcome":"ok","rejected":1,"shells":2,"steps":["revolved section","fillet","cut box","rectangular pattern","cut sphere","cut cylinder","cut sphere"],"unsupported":0,"volume":4723.415743}, "16": {"area":8872.873884,"bodies":3,"edges":49,"error":null,"faces":23,"outcome":"ok","rejected":0,"shells":3,"steps":["box","join cylinder","circular pattern","hole"],"unsupported":0,"volume":44953.403148}, "17": {"area":6048.425782,"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":2968.53154}, "18": {"area":5524.583817,"bodies":4,"edges":98,"error":"boolean Cut: the operation failed: no result","faces":44,"outcome":"failed","rejected":0,"shells":4,"steps":["extruded profile","join cylinder","circular pattern","cut cylinder","hole","cut cylinder","hole","circular pattern"],"unsupported":0,"volume":21568.016672}, @@ -121,6 +121,7 @@ {"reason":"#1213: a round or chamfer on an edge chain that runs on across a curved seam now builds (it was refused with 'a curved seam where the edge chain turns'). Seed 41's second fillet (three edges, radius 1) was one of those refusals and is now built. Replaying the seed's commands on the build before and after gives the same volume, area, faces and edges after each of steps 1 to 6; step 7, the fillet, is refused before and builds after (5292.19 to 5289.17 mm³, area 7395.26 to 7381.22 mm²); the run then reaches its eight steps one step sooner, so its last step is a cut sphere (5185.22 mm³) where it was a join cylinder (the generator draws its later steps from the new state).","seeds":[41]}, {"reason":"#391 after merging main with #1213: seed 41 now reaches its second fillet (built since #1213), and the end-snap fix again drops a sliver edge the cuts left (94 to 93 edges); its steps, outcome, faces and shells are unchanged, volume moves by 0.005 mm³ (5185.215737 to 5185.221068) and area by 0.0014 mm²","seeds":[41]}, {"reason":"the chamfer bug is on main too, see #1390","seeds":[57]}, - {"reason":"#1390: a chamfer of a convex edge that would grow the part is refused (TooLarge). Seed 57's 0.5 mm chamfer on the sphere cut's rim, which grew the part since #391 reordered its steps, is now refused, so the run goes on to its later steps and ends ok (16017.21 mm³, 24 faces)","seeds":[57]} + {"reason":"#1390: a chamfer of a convex edge that would grow the part is refused (TooLarge). Seed 57's 0.5 mm chamfer on the sphere cut's rim, which grew the part since #391 reordered its steps, is now refused, so the run goes on to its later steps and ends ok (16017.21 mm³, 24 faces)","seeds":[57]}, + {"reason":"seed 15 now cuts around a sealed void","seeds":[15]} ] } From 2141a3802a8aec4225ca877ded9eac7a4b7fe2b3 Mon Sep 17 00:00:00 2001 From: "H. Conrad" <78785932+Ian-cmd-ops@users.noreply.github.com> Date: Thu, 15 Oct 2026 19:19:04 -0700 Subject: [PATCH 33/92] Shell: an open face next to a concave edge no longer cuts the wall past it (#1495) The pushed-out cavity is trimmed so that past an open face's plane it only reaches through the open face itself. --- .../engine/tests/shell_opening_regressions.rs | 58 +++++++++++++ crates/kernel/src/polyhedron.rs | 85 +++++++++++++++++++ 2 files changed, 143 insertions(+) create mode 100644 crates/engine/tests/shell_opening_regressions.rs diff --git a/crates/engine/tests/shell_opening_regressions.rs b/crates/engine/tests/shell_opening_regressions.rs new file mode 100644 index 000000000..b3c7db28d --- /dev/null +++ b/crates/engine/tests/shell_opening_regressions.rs @@ -0,0 +1,58 @@ +//! A shell whose open face meets a concave edge must not cut into the wall past that edge. +//! +//! Lower box `[0, 25] × [0, 17.5] × [0, 35]`, top box `[7.5, 22.5] × [0, w] × [35, 42.5]` with +//! `w ≤ 17.5`, and the shell opens the top box's left face (x = 7.5). That face's bottom edge is +//! concave: the lower box's top runs on from it. With walls `t` thick, the cavity is +//! +//! - in the lower box: `[t, 25 − t] × [t, 17.5 − t] × [t, 35 − t]` +//! - in the top box, out to the open face: `[7.5, 22.5 − t] × [t, w − t] × [35 − t, 42.5 − t]` +//! +//! The shell's volume is the solid's volume less those two boxes. The open face used to be +//! pushed out past the lower box's top, cutting a strip through that wall. +use serde_json::json; +use solidcraft_engine::Session; + +fn run(s: &mut Session, id: &str, p: serde_json::Value) { + if let Err(e) = s.execute(id, &p) { + panic!("{id} {p}: {e}"); + } +} + +fn shell_volume(w: f64, t: f64) -> f64 { + let solid = 25.0 * 17.5 * 35.0 + 15.0 * w * 7.5; + let lower = (25.0 - 2.0 * t) * (17.5 - 2.0 * t) * (35.0 - 2.0 * t); + let upper = (15.0 - t) * (w - 2.0 * t) * 7.5; + solid - lower - upper +} + +fn shelled(w: f64, t: f64) -> Session { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"height": 35.0, "length": 25.0, "width": 17.5})); + run(&mut s, "solid.box", json!({"corner": [7.5, 0.0, 35.0], "height": 7.5, "length": 15.0, "operation": "join", "width": w})); + run(&mut s, "solid.shell", json!({"faces": [[7.5, w / 2.0, 38.75]], "thickness": t})); + s +} + +fn check(s: &Session, want: f64) { + let errors: Vec<_> = s.model.results.iter().filter_map(|r| r.error.clone()).collect(); + assert!(errors.is_empty(), "{errors:?}"); + let st = s.model.state(); + assert_eq!(st.bodies.len(), 1, "one body"); + let b = &st.bodies[0].body; + assert!(b.validity().is_empty(), "{:?}", b.validity()); + assert_eq!(b.shell_count(), 1, "one shell"); + let got = solidcraft_kernel::measure(b).map(|m| m.volume).unwrap_or(f64::NAN); + assert!((got - want).abs() < 1e-6 * want, "shell volume {got}, want {want}"); +} + +#[test] +fn open_face_flush_with_the_back_keeps_the_wall_past_its_concave_edge() { + for t in [1.0, 1.5] { + check(&shelled(17.5, t), shell_volume(17.5, t)); + } +} + +#[test] +fn open_face_inside_the_footprint_keeps_the_wall_past_its_concave_edge() { + check(&shelled(15.0, 1.5), shell_volume(15.0, 1.5)); +} diff --git a/crates/kernel/src/polyhedron.rs b/crates/kernel/src/polyhedron.rs index 6b7675eff..461da12ef 100644 --- a/crates/kernel/src/polyhedron.rs +++ b/crates/kernel/src/polyhedron.rs @@ -561,6 +561,14 @@ fn shell_opened(b: &Body, healed: &Body, open: &[Vec3], opened: &[usize], thickn Ok(c) => c, Err(e) => return shell_by_opening(healed, opened, thickness, margin).map_err(|_| e), }; + let cavity = match opening_overreach(healed, &cavity, opened, thickness, margin) { + Ok(Some(trimmed)) => trimmed, + Ok(None) => cavity, + Err(e) => { + log::warn!("shell: could not trim the opening to the open faces ({e}); the wall next to it may be cut"); + cavity + } + }; let r = crate::ops::boolean(healed, &cavity, crate::BoolOp::Cut); if r.is_err() && let Ok(x) = shell_by_opening(healed, opened, thickness, margin) @@ -605,6 +613,83 @@ fn shell_opened(b: &Body, healed: &Body, open: &[Vec3], opened: &[usize], thickn /// A shell made from the cavity with every face moved in by the thickness (open faces too), /// joined with each open face's moved copy swept out through the body. No history: the /// opening's walls, swept from the cavity's edges, come from nothing of `b`. +/// The cavity with each open face pushed out (`cavity`), trimmed so that beyond an open face's +/// plane it only reaches through the open face itself; `None` when it already does. +/// +/// The pushed-out face carries the cavity past every edge of the open face. Past a convex edge +/// that is outside the body, but past a concave one (a box on a box, its side face open where it +/// meets the lower box's top) it runs on into the neighbouring wall and cuts a strip through it, +/// as wide as the push. The trimmed cavity is the shell's cavity with every face moved in, +/// together with the pushed-out cavity's parts that are on the body's side of every open face's +/// plane or in front of that open face. +fn opening_overreach(healed: &Body, cavity: &Body, opened: &[usize], thickness: f64, margin: f64) -> Result> { + let size = healed.size(); + let tol = size * 1e-6 + 1e-9; + let faces: Vec = healed.solid.face_iter().cloned().collect(); + // Each open face's plane (outward normal, offset) and its triangles. + let mesh = healed.tessellate((size * 1e-3).max(1e-3))?; + let mut open: Vec<(&mt::Face, Vec3, f64, Vec<[Vec3; 3]>)> = Vec::new(); + for fi in opened { + let Some(f) = faces.get(*fi) else { return Ok(None) }; + let mt::Surface::Plane(pl) = f.oriented_surface() else { return Ok(None) }; + let n = pl.normal(); + let Some(n) = Vec3::new(n.x, n.y, n.z).normalized() else { return Ok(None) }; + let d = n.dot(from_p3(pl.origin())); + let tris: Vec<[Vec3; 3]> = + mesh.triangles.iter().zip(&mesh.tri_face).filter(|(_, f)| **f as usize == *fi).filter_map(|(t, _)| mesh.tri(t)).collect(); + if tris.is_empty() { + return Ok(None); + } + open.push((f, n, d, tris)); + } + // Only a corner of the cavity past an open face's plane and not in front of that face can be + // in a wall; with none, the cavity is right as it is. + let overreach = cavity.solid.vertex_iter().any(|v| { + let q = from_p3(v.point()); + open.iter().any(|(_, n, d, tris)| { + let h = n.dot(q) - d; + h > tol && { + let on = q - *n * h; + !tris.iter().any(|[a, b, c]| point_tri(on, *a, *b, *c) < size * 1e-4 + 1e-6) + } + }) + }); + if !overreach { + return Ok(None); + } + let closed = offset_planar(healed, |_, _| -thickness)?; + // Keep: on the body's side of each open plane, or in front of the open face. + let reach = size * 4.0; + let mut keep: Option = None; + for (f, n, d, _) in &open { + let c = *n * *d; + let mut hs = vec![HalfSpace { n: *n, d: *d }]; + for axis in [Vec3::X, Vec3::Y, Vec3::Z] { + hs.push(HalfSpace { n: axis, d: axis.dot(c) + reach }); + hs.push(HalfSpace { n: axis * -1.0, d: -axis.dot(c) + reach }); + } + let (side, _) = polyhedron(&hs)?; + // In front of the face: its prism, from half a wall inside the body (overlapping `side` + // rather than touching it) to past the pushed-out face. + let inset = thickness * 0.5; + let prism = guard("shell opening prism", || { + let start = builder::translated(*f, v3(*n * -inset)); + let solid: Solid = builder::tsweep(&start, v3(*n * (inset + margin * 2.0))); + Ok(solid) + })?; + let prism = Body::new(prism)?; + let k = crate::ops::boolean(&side, &prism, crate::BoolOp::Union)?.ok_or_else(|| KernelError::Failed("shell: opening".into()))?; + keep = Some(match keep { + None => k, + Some(acc) => crate::ops::boolean(&acc, &k, crate::BoolOp::Intersect)?.ok_or_else(|| KernelError::Failed("shell: opening".into()))?, + }); + } + let Some(keep) = keep else { return Ok(None) }; + let kept = crate::ops::boolean(cavity, &keep, crate::BoolOp::Intersect)?.ok_or_else(|| KernelError::Failed("shell: opening".into()))?; + let trimmed = crate::ops::boolean(&closed, &kept, crate::BoolOp::Union)?.ok_or_else(|| KernelError::Failed("shell: opening".into()))?; + Ok(Some(trimmed)) +} + fn shell_by_opening(b: &Body, opened: &[usize], thickness: f64, reach: f64) -> Result { let closed = offset_planar(b, |_, _| -thickness)?; let faces: Vec = closed.solid.face_iter().cloned().collect(); From d188eea1f4212d8f0b1a04e5a737189957414364 Mon Sep 17 00:00:00 2001 From: Mythic Keeper <125914417+MythicForge@users.noreply.github.com> Date: Thu, 15 Oct 2026 21:19:08 -0500 Subject: [PATCH 34/92] Fix: edges between two faces hard to pick (#1568) Thanks @MythicForge. --- crates/ui-egui/src/viewport.rs | 93 ++++++++++++++++++++++++++++++---- 1 file changed, 82 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 71af58ad5..a033c4564 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -1013,6 +1013,23 @@ fn ray_box(o: Vec3, d: Vec3, b: &solidcraft_engine::geom::Aabb3, pad: f64) -> Op (t0 <= t1).then_some(t0) } +/// The point of segment `a`–`b` nearest the ray from `o` along `d`. +fn ray_segment_closest(o: Vec3, d: Vec3, a: Vec3, b: Vec3) -> Vec3 { + let u = b - a; + let w = a - o; + let (dd, du, uu) = (d.dot(d), d.dot(u), u.dot(u)); + let den = dd * uu - du * du; + // Parallel or degenerate: every point is as near, so the start stands for the segment. + if !(den.is_finite() && den > 1e-12 * dd * uu) { + return a; + } + let s = (du * d.dot(w) - dd * u.dot(w)) / den; + if !s.is_finite() { + return a; + } + a + u * s.clamp(0.0, 1.0) +} + /// A box's outline on screen, grown by `px` (None: behind the eye). fn screen_box(proj: &Proj, b: &solidcraft_engine::geom::Aabb3, px: f32) -> Option { let mut r = Rect::NOTHING; @@ -1227,7 +1244,9 @@ fn pick_hits(app: &SolveApp, proj: &Proj, pos: Pos2, other_sketch_points: bool, } } let slack = scene_radius(app) * 0.02; - let visible = |p: Vec3| bestf.as_ref().is_none_or(|(t, _)| (p - o).dot(d) <= *t + slack); + // Wireframe draws no faces, so nothing hides an edge or a vertex. + let wireframe = app.ui.visual_style == 2; + let visible = |p: Vec3| wireframe || bestf.as_ref().is_none_or(|(t, _)| (p - o).dot(d) <= *t + slack); // Vertices (edge end points) and edges. let mut bestv = Near::new(all); let mut beste = Near::new(all); @@ -1254,16 +1273,13 @@ fn pick_hits(app: &SolveApp, proj: &Proj, pos: Pos2, other_sketch_points: bool, } } } - let pts: Vec = e.iter().filter_map(|q| proj.to_screen(*q)).collect(); - for (k, w) in pts.windows(2).enumerate() { - let dd = seg_dist(pos, w[0], w[1]); - if dd < 6.0 && beste.wants(dd) { - let mid = polyline_mid(e); - // Visible where the cursor is (not just at the middle). - let at = e.get(k).copied().unwrap_or(mid); - if visible(at) || visible(mid) { - beste.offer(dd, Hit::Edge { body: b.name.clone(), index: ei, mid }); - } + for w in e.windows(2) { + let (Some(a), Some(c)) = (proj.to_screen(w[0]), proj.to_screen(w[1])) else { continue }; + let dd = seg_dist(pos, a, c); + // Visible where the cursor is: the edge's point under the cursor, not an end or + // the middle, which can lie deeper than the face the cursor is on. + if dd < 6.0 && beste.wants(dd) && visible(ray_segment_closest(o, d, w[0], w[1])) { + beste.offer(dd, Hit::Edge { body: b.name.clone(), index: ei, mid: polyline_mid(e) }); } } } @@ -3784,6 +3800,61 @@ mod tests { assert!(bounds.min.x >= 29.99 && bounds.max.x <= 32.01 && bounds.max.y >= 41.99, "{bounds:?}"); } + #[test] + fn ray_segment_closest_takes_the_point_under_the_ray() { + let (o, d) = (Vec3::new(0.0, 0.0, 10.0), Vec3::new(0.0, 0.0, -1.0)); + let x = |a: Vec3, b: Vec3| ray_segment_closest(o, d, a, b); + assert!(x(Vec3::new(-5.0, 0.0, 0.0), Vec3::new(5.0, 0.0, -4.0)).dist(Vec3::new(0.0, 0.0, -2.0)) < 1e-9); + // Beyond an end: the end. + assert!(x(Vec3::new(1.0, 0.0, 0.0), Vec3::new(3.0, 0.0, 0.0)).dist(Vec3::new(1.0, 0.0, 0.0)) < 1e-9); + // Parallel, degenerate and non-finite input: the start, no panic. + assert_eq!(x(Vec3::new(1.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 5.0)), Vec3::new(1.0, 0.0, 0.0)); + assert_eq!(x(Vec3::new(2.0, 0.0, 0.0), Vec3::new(2.0, 0.0, 0.0)), Vec3::new(2.0, 0.0, 0.0)); + let nan = Vec3::new(f64::NAN, 0.0, 0.0); + let _ = x(nan, Vec3::ZERO); + } + + /// Hovering anywhere along a visible edge between two faces picks that edge, not a face + /// (the edge used to pick only where its start or middle was as near as the face). + #[test] + fn edge_between_two_faces_picks_along_its_whole_length() { + for style in [0u8, 2] { + let ctx = egui::Context::default(); + let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + app.viewport.no_pixels = true; + app.run("solid.box", json!({"length":200,"width":120,"height":160})).unwrap(); + app.ui.show_origin = false; + app.ui.visual_style = style; + app.cam.yaw = 0.7; + app.cam.pitch = 0.5; + app.cam.target = Vec3::new(100.0, 60.0, 80.0); + app.cam.distance = 500.0; + hover_frame(&mut app, &ctx, vec![]); + let proj = projection(&app, app.viewport.rect.unwrap()); + let st = app.session.world_state(); + let m = st.body("Body1").unwrap().mesh(); + let mut checked = 0; + for (ei, e) in m.edges.iter().enumerate() { + let (Some(a), Some(b)) = (e.first().copied(), e.last().copied()) else { continue }; + for k in 1..10 { + let p = a.lerp(b, k as f64 / 10.0); + let Some(sp) = proj.to_screen(p) else { continue }; + let (o, d) = proj.ray(sp); + // Only edges in front at that point (shaded); every edge in wireframe. + let depth = (p - o).dot(d); + if style != 2 && m.raycast(o, d).is_some_and(|(t, _)| t < depth - 1e-3) { + continue; + } + let hits = pick(&app, &proj, sp); + let first = candidate(&app, &hits).map(|x| x.1); + assert!(matches!(first, Some(Sel::Edge { index, .. }) if index == ei), "style {style}: edge {ei} at {k}/10 picked {first:?}"); + checked += 1; + } + } + assert!(checked > 50, "style {style}: only {checked} samples"); + } + } + fn hover_frame(app: &mut SolveApp, ctx: &egui::Context, events: Vec) { let selected = app.highlighted(); let mut output = ctx.run_ui( From 63accec16e287c6b20fe06716ad3835d49752b5d Mon Sep 17 00:00:00 2001 From: "H. Conrad" <78785932+Ian-cmd-ops@users.noreply.github.com> Date: Thu, 15 Oct 2026 19:19:10 -0700 Subject: [PATCH 35/92] STEP export: shelled revolved bodies export instead of panicking (#1496) A scale across a revolution's axis keeps the face a surface of revolution and is written as one; any other refusal from the writer is an export error, not a panic. --- .../engine/tests/step_export_regressions.rs | 68 +++++++++++++++++++ crates/kernel/src/step.rs | 17 ++++- crates/kernel/src/step_in/tests.rs | 39 +++++++++++ vendor/README.md | 6 ++ vendor/truck-stepio/src/out/geometry.rs | 44 ++++++++---- 5 files changed, 161 insertions(+), 13 deletions(-) create mode 100644 crates/engine/tests/step_export_regressions.rs diff --git a/crates/engine/tests/step_export_regressions.rs b/crates/engine/tests/step_export_regressions.rs new file mode 100644 index 000000000..45c92c500 --- /dev/null +++ b/crates/engine/tests/step_export_regressions.rs @@ -0,0 +1,68 @@ +//! STEP export regressions found by round-tripping the robustness designs: a body the app built +//! must export, and read back as the same solid. + +use serde_json::{Value, json}; +use solidcraft_engine::Session; +use solidcraft_kernel::{measure, step_export, step_import}; + +fn run(s: &mut Session, script: Value) { + for c in script.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} {p}: {e}"); + } + } +} + +/// The design's one body exports, and reads back closed with the same volume and area. +fn round_trips(s: &Session) { + let st = s.model.state(); + assert_eq!(st.bodies.len(), 1); + let body = &st.bodies[0].body; + let text = step_export(&[body], "test").unwrap_or_else(|e| panic!("export: {e}")); + let imp = step_import(&text).unwrap_or_else(|e| panic!("import: {e}")); + assert_eq!(imp.bodies.len(), 1, "{:?}", imp.warnings); + assert!(imp.bodies[0].closed && imp.warnings.is_empty(), "{:?}", imp.warnings); + let (a, b) = (measure(body).unwrap(), measure(&imp.bodies[0].body).unwrap()); + assert!((a.volume - b.volume).abs() < 1e-3 * a.volume, "volume {} -> {}", a.volume, b.volume); + assert!((a.area - b.area).abs() < 1e-3 * a.area, "area {} -> {}", a.area, b.area); +} + +/// Robustness seed 19, shrunk: a three-quarter turn of a rectangle, a sphere cut, a 1 mm shell. +/// The shell moves revolved faces by a scale across their axis; export refused them and the +/// refusal surfaced as a panic ("a Display implementation returned an error"). +#[test] +fn shelled_revolve_with_a_sphere_cut_exports() { + let mut s = Session::default(); + run( + &mut s, + json!([ + {"command":"sketch.create","params":{"plane":"XZ"}}, + {"command":"sketch.rectangle.two_point","params":{"p0":[5.0,0],"p1":[25.0,5.0]}}, + {"command":"sketch.finish","params":{}}, + {"command":"solid.revolve","params":{"angle":"270 deg","axis":"Z"}}, + {"command":"solid.sphere","params":{"center":[-2.5,5.0,-2.5],"operation":"cut","radius":10.0}}, + {"command":"solid.shell","params":{"faces":[[-2.7554552980815448e-15,-15.0,-2.5000000000000004]],"thickness":1.0}} + ]), + ); + round_trips(&s); +} + +/// Robustness seed 24, shrunk: a three-quarter turn of a rectangle, a chamfer of two edges, a +/// 1.5 mm shell. The same refusal as seed 19's, reached through a chamfer. +#[test] +fn shelled_chamfered_revolve_exports() { + let mut s = Session::default(); + run( + &mut s, + json!([ + {"command":"sketch.create","params":{"plane":"XZ"}}, + {"command":"sketch.rectangle.two_point","params":{"p0":[10.0,0],"p1":[27.5,22.5]}}, + {"command":"sketch.finish","params":{}}, + {"command":"solid.revolve","params":{"angle":"270 deg","axis":"Z"}}, + {"command":"solid.chamfer","params":{"distance":2.0,"edges":[[7.0710678118654755,7.0710678118654755,0.0],[-19.445436482630054,19.44543648263006,0.0]]}}, + {"command":"solid.shell","params":{"faces":[[18.75,0.0,-11.358616634594824]],"thickness":1.5}} + ]), + ); + round_trips(&s); +} diff --git a/crates/kernel/src/step.rs b/crates/kernel/src/step.rs index b6656ec79..1f6d343e6 100644 --- a/crates/kernel/src/step.rs +++ b/crates/kernel/src/step.rs @@ -74,10 +74,25 @@ pub(crate) fn truck_step(bodies: &[&Body], system: &str) -> Result { let cs: Vec<_> = bodies.iter().map(|b| plain_curves(b).map(|solid| solid.compress())).collect::>()?; let models: out::StepModels<_, _, _> = cs.iter().collect(); let header = out::StepHeaderDescriptor { organization_system: system.to_owned(), ..Default::default() }; - Ok(out::CompleteStepDisplay::new(models, header).to_string()) + written(&out::CompleteStepDisplay::new(models, header)) }) } +/// The text of truck's STEP writer, or an error. The writer refuses some geometry by returning +/// `fmt::Error` after a line saying why; `to_string` would turn that into a panic (caught by +/// `guard` on the desktop, but the browser build aborts on any panic). +fn written(display: &impl std::fmt::Display) -> Result { + use std::fmt::Write; + let mut text = String::new(); + match write!(text, "{display}") { + Ok(()) => Ok(text), + Err(_) => { + let why = text.lines().last().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#')).unwrap_or("unsupported geometry"); + Err(KernelError::Failed(format!("not supported yet: STEP export of this body ({why})"))) + } + } +} + /// STEP (ISO 10303-21, AP242) text for the given bodies as one part (`Body1`…, with the /// bodies' colours). pub fn step_export(bodies: &[&Body], system: &str) -> Result { diff --git a/crates/kernel/src/step_in/tests.rs b/crates/kernel/src/step_in/tests.rs index 6012461ca..5b7d7680f 100644 --- a/crates/kernel/src/step_in/tests.rs +++ b/crates/kernel/src/step_in/tests.rs @@ -1202,3 +1202,42 @@ fn large_imports_are_freed_with_their_last_user() { drop((first, again)); assert!(weak.upgrade().is_none(), "the cache must not keep a large import alive after its design is gone"); } + +/// A three-quarter turn of a rectangle about Z: planar end caps, revolved cylinders and annuli. +fn three_quarter_ring() -> Body { + let rect = + Region2 { outer: Loop2::polygon(&[Vec2::new(5.0, 0.0), Vec2::new(25.0, 0.0), Vec2::new(25.0, 5.0), Vec2::new(5.0, 5.0)]), holes: vec![] }; + revolve(&Plane::XZ, &[rect], Vec2::ZERO, Vec2::Y, 1.5 * std::f64::consts::PI).unwrap().pop().unwrap() +} + +fn scaled(b: &Body, x: f64, y: f64, z: f64) -> Body { + crate::transform_matrix(b, [[x, 0.0, 0.0, 0.0], [0.0, y, 0.0, 0.0], [0.0, 0.0, z, 0.0], [0.0, 0.0, 0.0, 1.0]]).unwrap() +} + +/// A scale across the revolution axis that differs from the scale along it (how a shell or an +/// offset moves a revolved face) keeps the faces surfaces of revolution. The writer refused it +/// ("non-uniform scale"), and the refusal surfaced as a panic in export (robustness seeds 19, 24). +#[test] +fn revolved_faces_scaled_across_the_axis_round_trip() { + let ring = three_quarter_ring(); + let v0 = measure(&ring).unwrap().volume; + let b = scaled(&ring, 1.5, 1.5, 0.5); + assert!(rel(measure(&b).unwrap().volume, v0 * 1.5 * 1.5 * 0.5) < 1e-3); + round_trip(&b); +} + +/// A transform that does not keep the faces surfaces of revolution: export may refuse the body, +/// but with an error, never a panic (the browser build aborts on any panic), and anything it does +/// write must read back as the same solid. +#[test] +fn revolved_faces_skewed_never_panic_on_export() { + let b = scaled(&three_quarter_ring(), 1.5, 1.0, 1.0); + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| step_export(&[&b], "t"))); + let Ok(r) = r else { panic!("STEP export panicked") }; + match r { + Err(e) => assert!(e.to_string().contains("not supported yet"), "{e}"), + Ok(_) => { + round_trip(&b); + } + } +} diff --git a/vendor/README.md b/vendor/README.md index 1f38c8835..eff274ac7 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -53,6 +53,12 @@ Changes: mirrored revolutions (ISO 10303-42 parameterises them by angle then profile, so their normal is the opposite of truck's; a mirroring transform reverses it again), and the modeling-surface wrapper passes the revolution's sense through instead of always `true`. +- `out/geometry.rs`: a surface of revolution under a transform that commutes with turning about + its axis (a scale across the axis that differs from the scale along it, as a shell or offset + makes of a revolved face) is written as the transformed profile revolved about the + transformed axis. Only uniform scales were taken. Other transforms are still refused: the + writer stops with a formatting error, which SolidCraft's `step.rs` now reports as an export + error (`to_string` panicked on it). - `lib.rs`: compiler warnings no longer fail the build. Example and test targets are dropped (their sources are not vendored). diff --git a/vendor/truck-stepio/src/out/geometry.rs b/vendor/truck-stepio/src/out/geometry.rs index 293cdfa5e..91abc3eee 100644 --- a/vendor/truck-stepio/src/out/geometry.rs +++ b/vendor/truck-stepio/src/out/geometry.rs @@ -748,22 +748,42 @@ impl StepSurface for RevolutedCurve { impl DisplayByStep for Processor, Matrix4> where C: StepLength + Transformed + DisplayByStep { + // SolidCraft: a transform that commutes with turning about the axis keeps the surface one of + // revolution: the transformed profile revolved about the transformed axis. That holds for + // uniform scales (the only case taken before) and also for a scale across the axis that + // differs from the scale along it, which is how a shell or an offset moves a revolved + // cylinder or cone face. Any other transform is still refused. fn fmt(&self, idx: usize, f: &mut Formatter<'_>) -> Result { let surface = self.entity(); - let transform = self.transform(); - let (k, a, _) = match transform.iwasawa_decomposition() { - Some(x) => x, - None => { - f.write_str("Transform is not regular")?; - return ERR; - } - }; - if !a[0][0].near(&a[1][1]) || !a[1][1].near(&a[2][2]) { - f.write_str("Transform contains non-uniform scale.")?; + let transform = *self.transform(); + if transform.determinant().so_small() { + f.write_str("Transform is not regular")?; return ERR; } - let curve = surface.entity_curve().transformed(*transform); - let axis = k.transform_vector(surface.axis()); + let a = surface.axis().normalize(); + let la = transform.transform_vector(a); + if la.so_small() { + f.write_str("Transform is not regular")?; + return ERR; + } + let axis = la.normalize(); + // Two directions across the axis, and their images. + let seed = if a.x.abs() < 0.9 { Vector3::unit_x() } else { Vector3::unit_y() }; + let u = (seed - a * a.dot(seed)).normalize(); + let v = a.cross(u); + let (lu, lv) = (transform.transform_vector(u), transform.transform_vector(v)); + let s = lu.magnitude(); + // Across the axis: a similarity onto the plane across the image axis. + let commutes = !s.so_small() + && (lu.dot(axis) / s).so_small() + && (lv.dot(axis) / s).so_small() + && (lu.dot(lv) / (s * s)).so_small() + && (lv.magnitude() / s).near(&1.0); + if !commutes { + f.write_str("Transform does not keep the surface one of revolution.")?; + return ERR; + } + let curve = surface.entity_curve().transformed(transform); let origin = transform.transform_point(surface.origin()); let surface = RevolutedCurve::by_revolution(curve, origin, axis); DisplayByStep::fmt(&surface, idx, f) From b20fd3d9d69c26fbe55418d559d53e9f0bc4aac2 Mon Sep 17 00:00:00 2001 From: Erikas <5955795+erkexzcx@users.noreply.github.com> Date: Fri, 16 Oct 2026 05:19:15 +0300 Subject: [PATCH 36/92] Booleans: when the last-resort nudge fails both ways, try two more screw axes (#1490) (#1527) Thanks @erkexzcx. --- crates/engine/src/tests.rs | 1 + .../fixtures/battery-tpu-case-v2.solidcraft | 2501 +++++++++++++++++ crates/engine/src/tests/pleat_join.rs | 47 + crates/kernel/src/ops.rs | 39 +- tests/robustness/goldens.json | 5 +- 5 files changed, 2585 insertions(+), 8 deletions(-) create mode 100644 crates/engine/src/tests/fixtures/battery-tpu-case-v2.solidcraft create mode 100644 crates/engine/src/tests/pleat_join.rs diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index c39a51488..a1b92233f 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -317,6 +317,7 @@ mod mirror_planes; #[cfg(not(target_arch = "wasm32"))] mod native_cad_import; mod path_scope; +mod pleat_join; mod primitive_points; mod rim_cut; mod robustness; diff --git a/crates/engine/src/tests/fixtures/battery-tpu-case-v2.solidcraft b/crates/engine/src/tests/fixtures/battery-tpu-case-v2.solidcraft new file mode 100644 index 000000000..198e620dc --- /dev/null +++ b/crates/engine/src/tests/fixtures/battery-tpu-case-v2.solidcraft @@ -0,0 +1,2501 @@ +{ + "format": "solidcraft/21", + "name": "Battery TPU Case v2", + "units": "mm", + "params": [ + { + "name": "batt_w", + "expr": "290 mm", + "unit": "mm", + "comment": "Battery flat top/bottom width", + "model": false + }, + { + "name": "batt_bulge", + "expr": "10 mm", + "unit": "mm", + "comment": "Side bulge past the top/bottom corners", + "model": false + }, + { + "name": "batt_h", + "expr": "92 mm", + "unit": "mm", + "comment": "Battery height", + "model": false + }, + { + "name": "peak_left", + "expr": "27 mm", + "unit": "mm", + "comment": "Height of the left side's widest point", + "model": false + }, + { + "name": "peak_right", + "expr": "batt_h - peak_left", + "unit": "mm", + "comment": "Height of the right side's widest point", + "model": false + }, + { + "name": "batt_len", + "expr": "198 mm", + "unit": "mm", + "comment": "Battery length", + "model": false + }, + { + "name": "tab_w", + "expr": "15 mm", + "unit": "mm", + "comment": "Connector tab width", + "model": false + }, + { + "name": "tab_depth", + "expr": "5.5 mm", + "unit": "mm", + "comment": "Connector tab protrusion", + "model": false + }, + { + "name": "ramp_len", + "expr": "35 mm", + "unit": "mm", + "comment": "Ramp from tab back to the wall", + "model": false + }, + { + "name": "ramp_blend_wall", + "expr": "80 mm", + "unit": "mm", + "comment": "Blend radius ramp to wall", + "model": false + }, + { + "name": "ramp_blend_tab", + "expr": "40 mm", + "unit": "mm", + "comment": "Blend radius tab to ramp", + "model": false + }, + { + "name": "wall", + "expr": "2.5 mm", + "unit": "mm", + "comment": "TPU wall thickness", + "model": false + }, + { + "name": "r_big", + "expr": "5 mm", + "unit": "mm", + "comment": "Fillet on the 4 long edges", + "model": false + }, + { + "name": "r_small", + "expr": "1 mm", + "unit": "mm", + "comment": "Fillet on all other edges", + "model": false + }, + { + "name": "clear", + "expr": "1 mm", + "unit": "mm", + "comment": "Tool overshoot", + "model": false + }, + { + "name": "pleat_top", + "expr": "batt_h - 2 * r_small", + "unit": "mm", + "comment": "Height where the pleat fades out", + "model": false + }, + { + "name": "d1", + "expr": "batt_w", + "unit": "mm", + "model": true + }, + { + "name": "d2", + "expr": "batt_w", + "unit": "mm", + "model": true + }, + { + "name": "d3", + "expr": "batt_h", + "unit": "mm", + "model": true + }, + { + "name": "d4", + "expr": "batt_bulge", + "unit": "mm", + "model": true + }, + { + "name": "d5", + "expr": "peak_right", + "unit": "mm", + "model": true + }, + { + "name": "d6", + "expr": "batt_bulge", + "unit": "mm", + "model": true + }, + { + "name": "d7", + "expr": "peak_left", + "unit": "mm", + "model": true + }, + { + "name": "d10", + "expr": "batt_w + 2 * batt_bulge + 10 * clear", + "unit": "mm", + "model": true + }, + { + "name": "d11", + "expr": "clear", + "unit": "mm", + "model": true + }, + { + "name": "d12", + "expr": "batt_len", + "unit": "mm", + "model": true + }, + { + "name": "d13", + "expr": "batt_len + tab_depth", + "unit": "mm", + "model": true + }, + { + "name": "d14", + "expr": "batt_w / 2 - tab_w", + "unit": "mm", + "model": true + }, + { + "name": "d15", + "expr": "ramp_len", + "unit": "mm", + "model": true + }, + { + "name": "d16", + "expr": "ramp_blend_wall", + "unit": "mm", + "model": true + }, + { + "name": "d17", + "expr": "ramp_blend_tab", + "unit": "mm", + "model": true + } + ], + "features": [ + { + "id": 1, + "name": "BatteryProfile", + "suppressed": false, + "type": "sketch", + "plane": { + "type": "custom", + "plane": { + "origin": [ + 0.0, + 0.0, + 0.0 + ], + "x_dir": [ + 1.0, + 0.0, + 0.0 + ], + "y_dir": [ + -0.0, + 0.0, + 1.0 + ] + } + }, + "sketch": { + "points": [ + { + "id": "origin", + "pos": [ + 0.0, + 0.0 + ], + "fixed": true + }, + { + "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": false + }, + { + "id": "p1", + "pos": [ + -100.0, + 0.0 + ], + "fixed": true, + "link": "j1" + }, + { + "id": "p2", + "pos": [ + 100.0, + 0.0 + ], + "fixed": true, + "link": "j1" + }, + { + "id": "p3", + "pos": [ + 0.0, + -100.0 + ], + "fixed": true, + "link": "j2" + }, + { + "id": "p4", + "pos": [ + 0.0, + 100.0 + ], + "fixed": true, + "link": "j2" + } + ], + "curves": [ + { + "id": "l1", + "type": "line", + "a": 1, + "b": 2, + "construction": false + }, + { + "id": "l2", + "type": "line", + "a": 2, + "b": 3, + "construction": false + }, + { + "id": "l3", + "type": "line", + "a": 3, + "b": 4, + "construction": false + }, + { + "id": "l4", + "type": "line", + "a": 4, + "b": 5, + "construction": false + }, + { + "id": "l5", + "type": "line", + "a": 5, + "b": 6, + "construction": false + }, + { + "id": "l6", + "type": "line", + "a": 6, + "b": 1, + "construction": false + }, + { + "id": "l7", + "type": "line", + "a": 7, + "b": 8, + "construction": true, + "link": "j1" + }, + { + "id": "l8", + "type": "line", + "a": 9, + "b": 10, + "construction": true, + "link": "j2" + } + ], + "constraints": [ + { + "id": "k1", + "type": "horizontal", + "l": 0 + }, + { + "id": "k2", + "type": "horizontal", + "l": 3 + }, + { + "id": "k3", + "type": "collinear", + "a": 3, + "b": 6 + }, + { + "id": "k4", + "type": "symmetric", + "p": 1, + "q": 2, + "l": 7 + }, + { + "id": "k5", + "type": "symmetric", + "p": 4, + "q": 5, + "l": 7 + }, + { + "id": "k6", + "type": "length", + "l": 0, + "value": 290.0, + "param": "d1" + }, + { + "id": "k7", + "type": "length", + "l": 3, + "value": 290.0, + "param": "d2" + }, + { + "id": "k8", + "type": "distance_y", + "p": 1, + "q": 5, + "value": 92.0, + "param": "d3" + }, + { + "id": "k9", + "type": "distance_x", + "p": 2, + "q": 3, + "value": 10.0, + "param": "d4" + }, + { + "id": "k10", + "type": "distance_y", + "p": 4, + "q": 3, + "value": 65.0, + "param": "d5" + }, + { + "id": "k11", + "type": "distance_x", + "p": 5, + "q": 6, + "value": 10.0, + "param": "d6" + }, + { + "id": "k12", + "type": "distance_y", + "p": 5, + "q": 6, + "value": 27.0, + "param": "d7" + } + ], + "links": [ + { + "id": "j1", + "kind": "project", + "source": { + "type": "sketch_axis", + "name": "x" + } + }, + { + "id": "j2", + "kind": "project", + "source": { + "type": "sketch_axis", + "name": "y" + } + } + ], + "counters": { + "j": 2, + "k": 12, + "l": 8, + "p": 4 + } + } + }, + { + "id": 2, + "name": "BatteryStock", + "suppressed": false, + "body_names": [ + "Battery" + ], + "param_names": [ + "d8" + ], + "type": "extrude", + "sketch": 1, + "profiles": { + "type": "all" + }, + "extent": { + "distance": "batt_len + tab_depth + clear", + "convention": "total_distance", + "direction": "positive" + }, + "operation": "new_body" + }, + { + "id": 3, + "name": "PlanOutline", + "suppressed": false, + "param_names": [ + "d9" + ], + "type": "sketch", + "plane": { + "type": "offset", + "base": { + "type": "origin", + "name": "XY" + }, + "distance": "-clear" + }, + "sketch": { + "points": [ + { + "id": "origin", + "pos": [ + 0.0, + 0.0 + ], + "fixed": true + }, + { + "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": false + }, + { + "id": "p1", + "pos": [ + 0.0, + -100.0 + ], + "fixed": true, + "link": "j1" + }, + { + "id": "p2", + "pos": [ + 0.0, + 100.0 + ], + "fixed": true, + "link": "j1" + }, + { + "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 + ], + "fixed": false + } + ], + "curves": [ + { + "id": "l1", + "type": "line", + "a": 1, + "b": 2, + "construction": false + }, + { + "id": "l2", + "type": "line", + "a": 2, + "b": 3, + "construction": false + }, + { + "id": "l3", + "type": "line", + "a": 3, + "b": 9, + "construction": false + }, + { + "id": "l4", + "type": "line", + "a": 10, + "b": 12, + "construction": false + }, + { + "id": "l5", + "type": "line", + "a": 13, + "b": 6, + "construction": false + }, + { + "id": "l6", + "type": "line", + "a": 6, + "b": 1, + "construction": false + }, + { + "id": "l7", + "type": "line", + "a": 7, + "b": 8, + "construction": true, + "link": "j1" + }, + { + "id": "a1", + "type": "arc", + "c": 11, + "a": 9, + "b": 10, + "construction": false + }, + { + "id": "a2", + "type": "arc", + "c": 14, + "a": 13, + "b": 12, + "construction": false + } + ], + "constraints": [ + { + "id": "k1", + "type": "horizontal", + "l": 0 + }, + { + "id": "k2", + "type": "vertical", + "l": 1 + }, + { + "id": "k3", + "type": "horizontal", + "l": 2 + }, + { + "id": "k4", + "type": "horizontal", + "l": 4 + }, + { + "id": "k5", + "type": "vertical", + "l": 5 + }, + { + "id": "k6", + "type": "symmetric", + "p": 1, + "q": 2, + "l": 6 + }, + { + "id": "k7", + "type": "length", + "l": 0, + "value": 320.0, + "param": "d10" + }, + { + "id": "k8", + "type": "distance_y", + "p": 0, + "q": 1, + "value": 1.0, + "param": "d11" + }, + { + "id": "k9", + "type": "distance_y", + "p": 0, + "q": 3, + "value": 198.0, + "param": "d12" + }, + { + "id": "k10", + "type": "distance_y", + "p": 0, + "q": 5, + "value": 203.5, + "param": "d13" + }, + { + "id": "k11", + "type": "distance_x", + "p": 0, + "q": 5, + "value": 130.0, + "param": "d14" + }, + { + "id": "k12", + "type": "distance_x", + "p": 5, + "q": 4, + "value": 35.0, + "param": "d15" + }, + { + "id": "k13", + "type": "point_on_curve", + "p": 4, + "c": 2 + }, + { + "id": "k14", + "type": "point_on_curve", + "p": 4, + "c": 3 + }, + { + "id": "k15", + "type": "tangent", + "a": 2, + "b": 7 + }, + { + "id": "k16", + "type": "tangent", + "a": 3, + "b": 7 + }, + { + "id": "k17", + "type": "radius", + "c": 7, + "value": 80.0, + "param": "d16" + }, + { + "id": "k18", + "type": "point_on_curve", + "p": 5, + "c": 3 + }, + { + "id": "k19", + "type": "point_on_curve", + "p": 5, + "c": 4 + }, + { + "id": "k20", + "type": "tangent", + "a": 3, + "b": 8 + }, + { + "id": "k21", + "type": "tangent", + "a": 4, + "b": 8 + }, + { + "id": "k22", + "type": "radius", + "c": 8, + "value": 40.0, + "param": "d17" + } + ], + "links": [ + { + "id": "j1", + "kind": "project", + "source": { + "type": "sketch_axis", + "name": "y" + } + } + ], + "counters": { + "a": 2, + "corner": 2, + "j": 1, + "k": 22, + "l": 7, + "p": 6 + } + } + }, + { + "id": 4, + "name": "TabAndRamp", + "suppressed": false, + "param_names": [ + "d18" + ], + "type": "extrude", + "sketch": 3, + "profiles": { + "type": "all" + }, + "extent": { + "distance": "batt_h + 2 * clear", + "convention": "total_distance", + "direction": "positive" + }, + "operation": "intersect", + "targets": [ + "Battery" + ] + }, + { + "id": 5, + "name": "CopyForCase", + "suppressed": false, + "body_names": [ + "Case" + ], + "param_names": [ + "d19", + "d20", + "d21" + ], + "type": "move", + "bodies": [ + "Battery" + ], + "translate": [ + "0", + "0", + "0" + ], + "copy": true + }, + { + "id": 6, + "name": "CaseShell", + "suppressed": false, + "param_names": [ + "d22" + ], + "face_names": [ + "F2:side:l4" + ], + "type": "shell", + "faces": [ + [ + 0.0, + -100.0, + 0.0 + ] + ], + "thickness": "wall", + "body": "Case", + "direction": "outside" + }, + { + "id": 7, + "name": "PleatCutSketch", + "suppressed": false, + "param_names": [ + "d23" + ], + "type": "sketch", + "plane": { + "type": "offset", + "base": { + "type": "origin", + "name": "XY" + }, + "distance": "-clear" + }, + "sketch": { + "points": [ + { + "id": "origin", + "pos": [ + 0.0, + 0.0 + ], + "fixed": true + }, + { + "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 + ], + "fixed": false + } + ], + "curves": [ + { + "id": "l1", + "type": "line", + "a": 1, + "b": 2, + "construction": false + }, + { + "id": "l2", + "type": "line", + "a": 2, + "b": 3, + "construction": false + }, + { + "id": "l3", + "type": "line", + "a": 3, + "b": 4, + "construction": false + }, + { + "id": "l4", + "type": "line", + "a": 4, + "b": 1, + "construction": false + } + ], + "constraints": [ + { + "id": "k1", + "type": "horizontal", + "l": 0 + }, + { + "id": "k2", + "type": "horizontal", + "l": 2 + }, + { + "id": "k3", + "type": "vertical", + "l": 1 + }, + { + "id": "k4", + "type": "vertical", + "l": 3 + } + ], + "counters": { + "k": 4, + "l": 4, + "p": 4 + } + } + }, + { + "id": 8, + "name": "PleatCut", + "suppressed": false, + "param_names": [ + "d24" + ], + "type": "extrude", + "sketch": 7, + "profiles": { + "type": "all" + }, + "extent": { + "distance": "pleat_top + clear", + "convention": "total_distance", + "direction": "positive" + }, + "operation": "cut", + "targets": [ + "Case" + ] + }, + { + "id": 9, + "name": "PleatBottom", + "suppressed": false, + "type": "sketch", + "plane": { + "type": "origin", + "name": "XY" + }, + "sketch": { + "points": [ + { + "id": "origin", + "pos": [ + 0.0, + 0.0 + ], + "fixed": true + }, + { + "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 + ], + "fixed": false + } + ], + "curves": [ + { + "id": "l1", + "type": "line", + "a": 1, + "b": 2, + "construction": false + }, + { + "id": "l2", + "type": "line", + "a": 2, + "b": 3, + "construction": false + }, + { + "id": "l3", + "type": "line", + "a": 3, + "b": 4, + "construction": false + }, + { + "id": "l4", + "type": "line", + "a": 4, + "b": 5, + "construction": false + }, + { + "id": "l5", + "type": "line", + "a": 5, + "b": 6, + "construction": false + }, + { + "id": "l6", + "type": "line", + "a": 6, + "b": 7, + "construction": false + }, + { + "id": "l7", + "type": "line", + "a": 7, + "b": 8, + "construction": false + }, + { + "id": "l8", + "type": "line", + "a": 8, + "b": 9, + "construction": false + }, + { + "id": "l9", + "type": "line", + "a": 9, + "b": 10, + "construction": false + }, + { + "id": "l10", + "type": "line", + "a": 10, + "b": 11, + "construction": false + }, + { + "id": "l11", + "type": "line", + "a": 11, + "b": 12, + "construction": false + }, + { + "id": "l12", + "type": "line", + "a": 12, + "b": 13, + "construction": false + }, + { + "id": "l13", + "type": "line", + "a": 13, + "b": 14, + "construction": false + }, + { + "id": "l14", + "type": "line", + "a": 14, + "b": 15, + "construction": false + }, + { + "id": "l15", + "type": "line", + "a": 15, + "b": 16, + "construction": false + }, + { + "id": "l16", + "type": "line", + "a": 16, + "b": 17, + "construction": false + }, + { + "id": "l17", + "type": "line", + "a": 17, + "b": 18, + "construction": false + }, + { + "id": "l18", + "type": "line", + "a": 18, + "b": 1, + "construction": false + } + ], + "constraints": [], + "counters": { + "l": 18 + } + } + }, + { + "id": 10, + "name": "PleatTop", + "suppressed": false, + "param_names": [ + "d25" + ], + "type": "sketch", + "plane": { + "type": "offset", + "base": { + "type": "origin", + "name": "XY" + }, + "distance": "pleat_top + 0.5 mm" + }, + "sketch": { + "points": [ + { + "id": "origin", + "pos": [ + 0.0, + 0.0 + ], + "fixed": true + }, + { + "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 + ], + "fixed": false + } + ], + "curves": [ + { + "id": "l1", + "type": "line", + "a": 1, + "b": 2, + "construction": false + }, + { + "id": "l2", + "type": "line", + "a": 2, + "b": 3, + "construction": false + }, + { + "id": "l3", + "type": "line", + "a": 3, + "b": 4, + "construction": false + }, + { + "id": "l4", + "type": "line", + "a": 4, + "b": 5, + "construction": false + }, + { + "id": "l5", + "type": "line", + "a": 5, + "b": 6, + "construction": false + }, + { + "id": "l6", + "type": "line", + "a": 6, + "b": 7, + "construction": false + }, + { + "id": "l7", + "type": "line", + "a": 7, + "b": 8, + "construction": false + }, + { + "id": "l8", + "type": "line", + "a": 8, + "b": 9, + "construction": false + }, + { + "id": "l9", + "type": "line", + "a": 9, + "b": 10, + "construction": false + }, + { + "id": "l10", + "type": "line", + "a": 10, + "b": 11, + "construction": false + }, + { + "id": "l11", + "type": "line", + "a": 11, + "b": 12, + "construction": false + }, + { + "id": "l12", + "type": "line", + "a": 12, + "b": 13, + "construction": false + }, + { + "id": "l13", + "type": "line", + "a": 13, + "b": 14, + "construction": false + }, + { + "id": "l14", + "type": "line", + "a": 14, + "b": 15, + "construction": false + }, + { + "id": "l15", + "type": "line", + "a": 15, + "b": 16, + "construction": false + }, + { + "id": "l16", + "type": "line", + "a": 16, + "b": 17, + "construction": false + }, + { + "id": "l17", + "type": "line", + "a": 17, + "b": 18, + "construction": false + }, + { + "id": "l18", + "type": "line", + "a": 18, + "b": 1, + "construction": false + } + ], + "constraints": [], + "counters": { + "l": 18 + } + } + }, + { + "id": 11, + "name": "PleatNear", + "suppressed": false, + "type": "loft", + "sections": [ + { + "sketch": 9, + "profiles": { + "type": "all" + } + }, + { + "sketch": 10, + "profiles": { + "type": "all" + } + } + ], + "operation": "join", + "targets": [ + "Case" + ] + }, + { + "id": 12, + "name": "MidLength", + "suppressed": false, + "param_names": [ + "d26" + ], + "type": "construction_plane", + "plane": { + "type": "offset", + "base": { + "type": "origin", + "name": "XZ" + }, + "distance": "-batt_len / 2" + } + }, + { + "id": 13, + "name": "PleatFar", + "suppressed": false, + "type": "mirror", + "features": [ + "PleatCut", + "PleatNear" + ], + "plane": { + "type": "construction", + "name": "MidLength" + } + }, + { + "id": 14, + "name": "FilletBig", + "suppressed": false, + "param_names": [ + "d27" + ], + "edge_refs": [ + { + "dir": [ + 0.0, + -1.0, + 0.0 + ], + "min": [ + -158.0833834441611, + -212.97245548710006, + -0.0005980913533997968 + ], + "max": [ + 158.08338344416106, + 14.97245064486031, + 95.00000000000003 + ] + }, + { + "dir": [ + 0.0, + -1.0, + 0.0 + ], + "min": [ + -158.0833834441611, + -212.97245548710006, + -0.0005980913533997968 + ], + "max": [ + 158.08338344416106, + 14.97245064486031, + 95.00000000000003 + ] + }, + { + "dir": [ + 0.0, + 1.0, + 0.0 + ], + "min": [ + -158.0833834441611, + -212.97245548710006, + -0.0005980913533997968 + ], + "max": [ + 158.08338344416106, + 14.97245064486031, + 95.00000000000003 + ] + }, + { + "dir": [ + 0.0, + -1.0, + 0.0 + ], + "min": [ + -158.0833834441611, + -212.97245548710006, + -0.0005980913533997968 + ], + "max": [ + 158.08338344416106, + 14.97245064486031, + 95.00000000000003 + ] + }, + { + "dir": [ + 0.0, + 1.0, + 0.0 + ], + "min": [ + -158.0833834441611, + -212.97245548710006, + -0.0005980913533997968 + ], + "max": [ + 158.08338344416106, + 14.97245064486031, + 95.00000000000003 + ] + }, + { + "dir": [ + 0.0, + 1.0, + 0.0 + ], + "min": [ + -158.0833834441611, + -212.97245548710006, + -0.0005980913533997968 + ], + "max": [ + 158.08338344416106, + 14.97245064486031, + 95.00000000000003 + ] + }, + { + "dir": [ + 0.0, + -1.0, + 0.0 + ], + "min": [ + -158.0833834441611, + -212.97245548710006, + -0.0005980913533997968 + ], + "max": [ + 158.08338344416106, + 14.97245064486031, + 95.00000000000003 + ] + }, + { + "dir": [ + 0.0, + 1.0, + 0.0 + ], + "min": [ + -158.0833834441611, + -212.97245548710006, + -0.0005980913533997968 + ], + "max": [ + 158.08338344416106, + 14.97245064486031, + 95.00000000000003 + ] + } + ], + "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" + ], + "type": "fillet", + "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 + ] + ], + "radius": "r_big", + "body": "Case" + }, + { + "id": 15, + "name": "FilletFrontOuter", + "suppressed": false, + "param_names": [ + "d28" + ], + "edge_refs": [ + { + "dir": [ + 0.34731435582359377, + 0.0, + -0.9377487607237037 + ], + "min": [ + -157.9189160095873, + -212.97245548710006, + -0.0005980913533997968 + ], + "max": [ + 157.9189160095873, + 14.97245064486031, + 95.00000000000003 + ] + }, + { + "dir": [ + -0.1520571842539413, + 6.854850442197856e-18, + -0.9883716976506173 + ], + "min": [ + -157.9189160095873, + -212.97245548710006, + -0.0005980913533997968 + ], + "max": [ + 157.9189160095873, + 14.97245064486031, + 95.00000000000003 + ] + }, + { + "dir": [ + -0.3473143558235947, + 0.0, + 0.9377487607237034 + ], + "min": [ + -157.9189160095873, + -212.97245548710006, + -0.0005980913533997968 + ], + "max": [ + 157.9189160095873, + 14.97245064486031, + 95.00000000000003 + ] + }, + { + "dir": [ + 0.15205718425394107, + 6.990187846251234e-18, + 0.9883716976506172 + ], + "min": [ + -157.9189160095873, + -212.97245548710006, + -0.0005980913533997968 + ], + "max": [ + 157.9189160095873, + 14.97245064486031, + 95.00000000000003 + ] + }, + { + "dir": [ + 1.0, + -1.5479309295511088e-18, + 0.0 + ], + "min": [ + -157.9189160095873, + -212.97245548710006, + -0.0005980913533997968 + ], + "max": [ + 157.9189160095873, + 14.97245064486031, + 95.00000000000003 + ] + } + ], + "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" + ], + "type": "fillet", + "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 + ] + ], + "radius": "r_small", + "body": "Case" + }, + { + "id": 16, + "name": "FilletRearOuter", + "suppressed": false, + "param_names": [ + "d29" + ], + "edge_refs": [ + { + "dir": [ + -0.1520571842539413, + 0.0, + -0.9883716976506173 + ], + "min": [ + -157.92605659069406, + -212.97245548710006, + -0.0005980913533997968 + ], + "max": [ + 157.92605659069403, + 14.97245064486031, + 95.00000000000003 + ] + }, + { + "dir": [ + 0.34731435582359377, + 0.0, + -0.9377487607237037 + ], + "min": [ + -157.92605659069406, + -212.97245548710006, + -0.0005980913533997968 + ], + "max": [ + 157.92605659069403, + 14.97245064486031, + 95.00000000000003 + ] + }, + { + "dir": [ + -0.3473143558235947, + 0.0, + 0.9377487607237034 + ], + "min": [ + -157.92605659069406, + -212.97245548710006, + -0.0005980913533997968 + ], + "max": [ + 157.92605659069403, + 14.97245064486031, + 95.00000000000003 + ] + }, + { + "dir": [ + 0.15205718425394107, + 0.0, + 0.9883716976506172 + ], + "min": [ + -157.92605659069406, + -212.97245548710006, + -0.0005980913533997968 + ], + "max": [ + 157.92605659069403, + 14.97245064486031, + 95.00000000000003 + ] + }, + { + "dir": [ + 1.0, + 2.4463450711209976e-16, + 0.0 + ], + "min": [ + -157.92605659069406, + -212.97245548710006, + -0.0005980913533997968 + ], + "max": [ + 157.92605659069403, + 14.97245064486031, + 95.00000000000003 + ] + } + ], + "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" + ], + "type": "fillet", + "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 + ] + ], + "radius": "r_small", + "body": "Case" + }, + { + "id": 17, + "name": "FilletFrontInner", + "suppressed": false, + "param_names": [ + "d30" + ], + "edge_refs": [ + { + "dir": [ + 0.1520571842539411, + 0.0, + 0.988371697650617 + ], + "min": [ + -157.9260565909712, + -212.97245548710006, + -0.0005980913533997968 + ], + "max": [ + 157.92605659097126, + 14.97245064486031, + 95.00000000000001 + ] + }, + { + "dir": [ + -0.34731435582359377, + 0.0, + 0.9377487607237037 + ], + "min": [ + -157.9260565909712, + -212.97245548710006, + -0.0005980913533997968 + ], + "max": [ + 157.92605659097126, + 14.97245064486031, + 95.00000000000001 + ] + }, + { + "dir": [ + -1.0, + 0.0, + 0.0 + ], + "min": [ + -157.9260565909712, + -212.97245548710006, + -0.0005980913533997968 + ], + "max": [ + 157.92605659097126, + 14.97245064486031, + 95.00000000000001 + ] + }, + { + "dir": [ + -0.15205718425394102, + 0.0, + -0.9883716976506172 + ], + "min": [ + -157.9260565909712, + -212.97245548710006, + -0.0005980913533997968 + ], + "max": [ + 157.92605659097126, + 14.97245064486031, + 95.00000000000001 + ] + }, + { + "dir": [ + 0.3473143558235949, + 0.0, + -0.9377487607237033 + ], + "min": [ + -157.9260565909712, + -212.97245548710006, + -0.0005980913533997968 + ], + "max": [ + 157.92605659097126, + 14.97245064486031, + 95.00000000000001 + ] + } + ], + "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" + ], + "type": "fillet", + "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 + ] + ], + "radius": "r_small", + "body": "Case" + }, + { + "id": 18, + "name": "FilletRearInner", + "suppressed": false, + "param_names": [ + "d31" + ], + "edge_refs": [ + { + "dir": [ + 0.1520571842539411, + 0.0, + 0.988371697650617 + ], + "min": [ + -157.9260565909712, + -212.97245548710006, + -0.0005980913533997968 + ], + "max": [ + 157.92605659097126, + 14.97245064486031, + 95.00000000000001 + ] + }, + { + "dir": [ + -0.34731435582359377, + 0.0, + 0.9377487607237037 + ], + "min": [ + -157.9260565909712, + -212.97245548710006, + -0.0005980913533997968 + ], + "max": [ + 157.92605659097126, + 14.97245064486031, + 95.00000000000001 + ] + }, + { + "dir": [ + -1.0, + -2.4685277687458984e-16, + 0.0 + ], + "min": [ + -157.9260565909712, + -212.97245548710006, + -0.0005980913533997968 + ], + "max": [ + 157.92605659097126, + 14.97245064486031, + 95.00000000000001 + ] + }, + { + "dir": [ + -0.15205718425394102, + 0.0, + -0.9883716976506172 + ], + "min": [ + -157.9260565909712, + -212.97245548710006, + -0.0005980913533997968 + ], + "max": [ + 157.92605659097126, + 14.97245064486031, + 95.00000000000001 + ] + }, + { + "dir": [ + 0.347314355823594, + 0.0, + -0.9377487607237036 + ], + "min": [ + -157.9260565909712, + -212.97245548710006, + -0.0005980913533997968 + ], + "max": [ + 157.92605659097126, + 14.97245064486031, + 95.00000000000001 + ] + } + ], + "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" + ], + "type": "fillet", + "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 + ] + ], + "radius": "r_small", + "body": "Case" + } + ], + "next_id": 19, + "visibility": { + "hidden_bodies": [ + "Battery" + ], + "hidden_occurrences": [], + "hidden_origin": [], + "hidden_sketches": [], + "shown_sketches": [] + } +} \ No newline at end of file diff --git a/crates/engine/src/tests/pleat_join.rs b/crates/engine/src/tests/pleat_join.rs new file mode 100644 index 000000000..9ddaeaa57 --- /dev/null +++ b/crates/engine/src/tests/pleat_join.rs @@ -0,0 +1,47 @@ +//! #1490: the owner's shelled battery case (`battery-tpu-case-v2.solidcraft`, format 21, saved +//! at `wall = 2.5 mm`) with a pleat loft joined into a window in one end wall. The loft stands on +//! the case's open rim and its end strips lie in the wall's inner face. At walls of 2.4–2.6 mm +//! the join failed with "no result": every exact route was refused, and the last resort's +//! nudge failed both ways about its one screw axis. The other screws are now tried too. + +use std::path::Path; + +use serde_json::json; + +use super::run; +use crate::Session; + +fn open() -> Session { + let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("src/tests/fixtures/battery-tpu-case-v2.solidcraft"); + let mut s = Session::default(); + run(&mut s, "doc.open", json!({"path": path.to_string_lossy()})); + s +} + +fn errors(s: &Session) -> Vec<(String, String)> { + s.model.results.iter().filter_map(|r| Some((r.name.clone(), r.error.clone()?))).collect() +} + +fn case_volume(s: &mut Session) -> f64 { + let m = run(s, "inspect.measure", json!({"bodies": ["Case"]})); + m["total"]["volume_mm3"].as_f64().unwrap() +} + +/// The design rebuilds as saved, and at 2.4 and 2.6 mm, with both pleats and every round; the +/// case grows with the wall between them. +#[test] +fn the_pleats_join_at_every_wall_from_2_4_to_2_6_mm() { + let mut s = open(); + assert_eq!(errors(&s), Vec::new(), "as saved, at 2.5 mm"); + let at = case_volume(&mut s); + let mut volumes = Vec::new(); + for wall in ["2.4 mm", "2.6 mm"] { + run(&mut s, "parameters.change", json!({"name": "wall", "expression": wall})); + assert_eq!(errors(&s), Vec::new(), "at {wall}"); + volumes.push(case_volume(&mut s)); + } + // About 14.8 cm³ of wall per tenth of a millimetre here. + let (thin, thick) = (volumes[0], volumes[1]); + assert!(thin < at && at < thick, "{thin} < {at} < {thick}"); + assert!(((at - thin) - (thick - at)).abs() < 0.01 * (thick - thin), "{thin} {at} {thick}"); +} diff --git a/crates/kernel/src/ops.rs b/crates/kernel/src/ops.rs index 102b6e985..0afa9ee23 100644 --- a/crates/kernel/src/ops.rs +++ b/crates/kernel/src/ops.rs @@ -903,14 +903,15 @@ fn boolean_whole(a: &Body, b: &Body, op: BoolOp) -> Result> { if !APART.with(|c| c.get()) { APART.with(|c| c.set(true)); let c = b.solid.vertex_iter().fold(Vec3::ZERO, |acc, v| acc + from_p3(v.point())) * (1.0 / b.solid.vertex_iter().count().max(1) as f64); - let translation = Vec3::new(0.61, -0.37, 0.71) * (size * 2e-6); - let nudge = |sign: f64| { + let translation = |screw: usize| SCREWS.get(screw).map_or(Vec3::ZERO, |s| Vec3::new(s.0[0], s.0[1], s.0[2]) * (size * 2e-6)); + let nudge = |screw: usize, sign: f64| { + let axis = SCREWS.get(screw).map_or(Vec3::Z, |s| Vec3::new(s.1[0], s.1[1], s.1[2])); capture_boolean_diagnostics(|| { - transform(b, translation * sign, c, Vec3::new(0.27, 0.83, -0.49), 2e-6 * sign) - .and_then(|nb| Ok(boolean(a, &nb, op)?.map(|r| nudged(r, &nb, &counts)))) + transform(b, translation(screw) * sign, c, axis, 2e-6 * sign).and_then(|nb| Ok(boolean(a, &nb, op)?.map(|r| nudged(r, &nb, &counts)))) }) }; - let (mut r, mut diagnostics) = nudge(1.0); + let mut used = 0; + let (mut r, mut diagnostics) = nudge(used, 1.0); // A nudge that pushes a face into a curved face it only touched (a cut whose end lies // tangent to a round side) leaves a sliver of that face behind, a fraction of a // millimetre wide, which later features (a shell, a fillet) can't work with. The @@ -923,7 +924,7 @@ fn boolean_whole(a: &Body, b: &Body, op: BoolOp) -> Result> { }; let made = slivers.is_none_or(|n| n > 0 && n > sliver_faces(a, size).saturating_add(sliver_faces(b, size))); if !matches!(r, Ok(None)) && made { - let (r2, diagnostics2) = nudge(-1.0); + let (r2, diagnostics2) = nudge(used, -1.0); if let Ok(Some(body)) = &r2 && slivers.is_none_or(|n| sliver_faces(body, size) < n) && check(body).0 @@ -931,6 +932,26 @@ fn boolean_whole(a: &Body, b: &Body, op: BoolOp) -> Result> { (r, diagnostics) = (r2, diagnostics2); } } + // Neither way worked: the screw can turn the tool along a seam it lies in (a loft + // standing in the rim of a shelled case with its ends in the wall's inner face, #1490). + // The other screws are tried in turn, and the first result that checks is taken. + let works = |r: &Result>| match r { + Ok(None) => true, + Ok(Some(body)) => check(body).0, + Err(_) => false, + }; + if !works(&r) { + 'screws: for screw in 1..SCREWS.len() { + for sign in [1.0, -1.0] { + let (r2, diagnostics2) = nudge(screw, sign); + if matches!(&r2, Ok(Some(body)) if check(body).0) { + (r, diagnostics, used) = (r2, diagnostics2, screw); + break 'screws; + } + } + } + } + let translation = translation(used); APART.with(|c| c.set(false)); match r { Ok(Some(body)) => { @@ -972,6 +993,12 @@ fn boolean_whole(a: &Body, b: &Body, op: BoolOp) -> Result> { } } +/// The screw motions a tool is nudged by as a last resort: (direction of the move, axis of the +/// turn), each tried both ways. The first is the one every nudge used before #1490; the others +/// are asked only when it fails both ways. +const SCREWS: [([f64; 3], [f64; 3]); 3] = + [([0.61, -0.37, 0.71], [0.27, 0.83, -0.49]), ([-0.42, 0.68, 0.6], [0.77, -0.18, 0.61]), ([0.31, 0.52, -0.79], [-0.58, 0.41, 0.70])]; + /// Faces of `b` narrower than 1/200 of `size` (twice their area over their boundary's /// length): the slivers a nudged tool leaves where it was pushed into a face it touched. fn sliver_faces(b: &Body, size: f64) -> usize { diff --git a/tests/robustness/goldens.json b/tests/robustness/goldens.json index 0728e06e2..cc943915d 100644 --- a/tests/robustness/goldens.json +++ b/tests/robustness/goldens.json @@ -64,7 +64,7 @@ "60": {"area":3443.328607,"bodies":1,"edges":39,"error":null,"faces":15,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","cut sphere"],"unsupported":0,"volume":11779.204543}, "61": {"area":5020.413153,"bodies":1,"edges":36,"error":"boolean Cut: the operation failed: no result","faces":15,"outcome":"failed","rejected":0,"shells":1,"steps":["extruded profile","cut cylinder","shell","rectangular pattern"],"unsupported":0,"volume":4906.628538}, "62": {"area":8771.003732,"bodies":1,"edges":60,"error":null,"faces":23,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","cut cylinder","circular pattern","cut box","cut box","join cylinder"],"unsupported":2,"volume":40107.001728}, - "63": {"area":3060.37707,"bodies":1,"edges":57,"error":"boolean Union: implausible result volume ","faces":21,"outcome":"failed","rejected":1,"shells":1,"steps":["revolved section","join box","cut cylinder","hole","cut cylinder","join box"],"unsupported":0,"volume":6534.395036}, + "63": {"area":3198.797259,"bodies":1,"edges":84,"error":null,"faces":30,"outcome":"ok","rejected":1,"shells":1,"steps":["revolved section","join box","cut cylinder","hole","cut cylinder","join box","fillet"],"unsupported":0,"volume":7075.892751}, "64": {"area":4088.335645,"bodies":1,"edges":36,"error":null,"faces":14,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","fillet","join cylinder"],"unsupported":0,"volume":8495.220295}, "65": {"area":8442.175249,"bodies":1,"edges":33,"error":null,"faces":13,"outcome":"ok","rejected":0,"shells":1,"steps":["box","cut cylinder","fillet","rectangular pattern","circular pattern","circular pattern","fillet","cut box"],"unsupported":0,"volume":45117.305023}, "66": {"area":9222.76638,"bodies":1,"edges":99,"error":null,"faces":37,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","join box","join box","join box","cut sphere","cut box"],"unsupported":1,"volume":35217.203139}, @@ -122,6 +122,7 @@ {"reason":"#391 after merging main with #1213: seed 41 now reaches its second fillet (built since #1213), and the end-snap fix again drops a sliver edge the cuts left (94 to 93 edges); its steps, outcome, faces and shells are unchanged, volume moves by 0.005 mm³ (5185.215737 to 5185.221068) and area by 0.0014 mm²","seeds":[41]}, {"reason":"the chamfer bug is on main too, see #1390","seeds":[57]}, {"reason":"#1390: a chamfer of a convex edge that would grow the part is refused (TooLarge). Seed 57's 0.5 mm chamfer on the sphere cut's rim, which grew the part since #391 reordered its steps, is now refused, so the run goes on to its later steps and ends ok (16017.21 mm³, 24 faces)","seeds":[57]}, - {"reason":"seed 15 now cuts around a sealed void","seeds":[15]} + {"reason":"seed 15 now cuts around a sealed void","seeds":[15]}, + {"reason":"#1490: when the last-resort nudge fails both ways, two more screw axes are tried; seed 63's final box join (its face 0.00005 mm off the half-ring's cut face) now builds instead of being refused with an implausible volume, and the design goes on to its fillet","seeds":[63]} ] } From 5c0351b1f42f295e2a79f13acc0c7fbc79029d7b Mon Sep 17 00:00:00 2001 From: Erikas <5955795+erkexzcx@users.noreply.github.com> Date: Fri, 16 Oct 2026 05:19:19 +0300 Subject: [PATCH 37/92] Fillet: refuse only crossed faces the round makes, not ones the body had (#1488) (#1517) Thanks @erkexzcx. --- crates/engine/src/tests.rs | 1 + crates/engine/src/tests/nudge_slivers.rs | 76 ++++++++++++++++++++++++ crates/kernel/src/blend.rs | 27 +++++---- crates/kernel/src/body.rs | 15 ++++- 4 files changed, 106 insertions(+), 13 deletions(-) create mode 100644 crates/engine/src/tests/nudge_slivers.rs diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a1b92233f..e9bef2570 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -316,6 +316,7 @@ mod loft_spacing; mod mirror_planes; #[cfg(not(target_arch = "wasm32"))] mod native_cad_import; +mod nudge_slivers; mod path_scope; mod pleat_join; mod primitive_points; diff --git a/crates/engine/src/tests/nudge_slivers.rs b/crates/engine/src/tests/nudge_slivers.rs new file mode 100644 index 000000000..090bc78d3 --- /dev/null +++ b/crates/engine/src/tests/nudge_slivers.rs @@ -0,0 +1,76 @@ +//! #1488: a loft joined into a slab, flush with the slab's outer face and its bottom, takes the +//! boolean's last retry (the tool nudged a fraction of a micron). That leaves sliver faces +//! along the flush faces, one of which reads as a face whose boundary crosses itself; every +//! later round on the body was then refused for it ("the rounds would leave openings"), even +//! one 36 mm away. A round is now refused only for crossed faces it makes. + +use serde_json::json; + +use super::run; +use crate::Session; + +/// The issue's slab `width` thick with a window through it and the pleat loft joined into it. +fn slab_with_pleat(width: f64) -> Session { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"corner": [-60, 0, 0], "length": 120, "width": width, "height": 95, "body_name": "Wall"})); + run( + &mut s, + "solid.box", + json!({"corner": [-24, -0.5, -1], "length": 48, "width": width + 1.0, "height": 91, "operation": "cut", "targets": ["Wall"]}), + ); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Bottom"})); + run( + &mut s, + "sketch.line", + json!({"closed": true, "infer": false, "connect": false, "points": [ + [-26, 3], [-24.76384, 3], [-16.0568, 14.97217], [-8, 4.90117], [0, 14.90117], [8, 4.90117], [16.0568, 14.97217], [24.76384, 3], [26, 3], + [26, 0], [23.23616, 0], [15.9432, 10.02783], [8, 0.09883], [0, 10.09883], [-8, 0.09883], [-15.9432, 10.02783], [-23.23616, 0], [-26, 0]]}), + ); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "sketch.create", json!({"plane": "XY", "offset": 90.5, "name": "Top"})); + run( + &mut s, + "sketch.line", + json!({"closed": true, "infer": false, "connect": false, "points": [ + [-26, 3], [-24, 3], [-16, 3], [-8, 3], [0, 3], [8, 3], [16, 3], [24, 3], [26, 3], + [26, 0], [24, 0], [16, 0], [8, 0], [0, 0], [-8, 0], [-16, 0], [-24, 0], [-26, 0]]}), + ); + run(&mut s, "sketch.finish", json!({})); + run( + &mut s, + "solid.loft", + json!({"sections": [{"sketch": "Bottom"}, {"sketch": "Top"}], "operation": "join", "targets": ["Wall"], "name": "Pleat"}), + ); + s +} + +fn wall(s: &Session) -> solidcraft_kernel::Body { + s.model.state().body("Wall").map(|b| b.body.clone()).unwrap() +} + +/// The R1 round on the slab's end edge at x = −60 works after the join, as it does on the 3 mm +/// slab (and on the 3.5 mm one before the loft), and adds no crossed face of its own. +#[test] +fn a_round_far_from_the_joined_loft_works() { + for (width, pick) in [(3.5, [-60.0, 1.75, 95.0]), (3.0, [-60.0, 1.5, 95.0])] { + let mut s = slab_with_pleat(width); + let before = wall(&s); + let r = s.execute("solid.fillet", &json!({"body": "Wall", "edges": [pick], "radius": 1})); + assert!(r.is_ok(), "{width} mm: {r:?}"); + let after = wall(&s); + assert_eq!(after.face_count(), before.face_count() + 1, "{width} mm: one round face"); + assert_eq!(after.crossed_faces().unwrap(), before.crossed_faces().unwrap(), "{width} mm"); + // The round lies along the picked edge: the end face's top corner is gone. + let m = solidcraft_kernel::measure(&after).unwrap(); + assert!((m.bbox.min.x + 60.0).abs() < 1e-6 && (m.bbox.max.z - 95.0).abs() < 1e-6, "{width} mm: {:?}", m.bbox); + } +} + +/// A round that does cross faces is still refused, joined loft or not (#871's check stands). +#[test] +fn rounds_that_overlap_are_still_refused() { + let mut s = slab_with_pleat(3.5); + // Both long top edges of the 3.5 mm slab with a radius over half its thickness. + let r = s.execute("solid.fillet", &json!({"body": "Wall", "edges": [[-40, 0, 95], [-40, 3.5, 95]], "radius": 2})); + assert!(r.is_err(), "{r:?}"); +} diff --git a/crates/kernel/src/blend.rs b/crates/kernel/src/blend.rs index f0f003a89..08c3bd625 100644 --- a/crates/kernel/src/blend.rs +++ b/crates/kernel/src/blend.rs @@ -1121,7 +1121,7 @@ pub fn fillet_g2(body: &Body, edges: &[Vec3], radius: f64) -> Result { let (made, rec) = guard("G2 fillet", || blend_one(&solid, &edge, size, radius, Shape::Curvature))?; cur = record::after(record::rebuilt(made, &[&solid], &rec)?, &cur, &counts); } - closed(cur) + closed(body, cur) } /// Most edges whose other orders are tried when the order given is refused. @@ -1804,9 +1804,16 @@ fn loop_split(cur: &Body, pts: &[Vec3]) -> Result>, Vec Result { - match b.crossed_face_loops()? { +/// refused. Faces of `input` that crossed already and that the fillet carried over unchanged +/// (a sliver an earlier boolean left far from the rounds, #1488) are not the fillet's doing. +fn closed(input: &Body, b: Body) -> Result { + let after = b.crossed_faces()?; + if after.is_empty() { + return Ok(b); + } + let before = input.crossed_faces()?; + let tol = (input.size().max(b.size()) * 1e-6).max(1e-9); + match after.iter().filter(|p| !before.iter().any(|q| q.dist(**p) <= tol)).count() { 0 => Ok(b), _ => Err(KernelError::Failed( "fillet: the rounds would leave openings in the surface (they overlap where a wall or a face is narrower than both)".into(), @@ -1832,17 +1839,17 @@ pub fn fillet(body: &Body, edges: &[Vec3], radius: f64) -> Result { fn fillet_built(body: &Body, edges: &[Vec3], radius: f64) -> Result { // Corners the local blends refuse (an earlier round at an edge's end): radius per edge. blend(body, edges, radius, Shape::Round, "fillet") - .and_then(closed) + .and_then(|b| closed(body, b)) .or_else(|e| { let sel: Vec<(Vec3, f64)> = edges.iter().map(|p| (*p, radius)).collect(); // The local blend's refusal, unless only the corner build found the radius too large. crate::blend_corner::fillet_radii(body, &sel) - .and_then(closed) + .and_then(|b| closed(body, b)) .map_err(|e2| keep_size(e, e2)) // Three edges at a vertex of any faces end in a sphere. .or_else(|e| { if edges.len() >= 3 { - crate::blend_vertex::fillet_ball_vertices(body, edges, radius).and_then(closed).map_err(|_| e) + crate::blend_vertex::fillet_ball_vertices(body, edges, radius).and_then(|b| closed(body, b)).map_err(|_| e) } else { Err(e) } @@ -1850,9 +1857,9 @@ fn fillet_built(body: &Body, edges: &[Vec3], radius: f64) -> Result { }) // Straight edges ending at a curved face that isn't an earlier round's: a rolling ball // trimmed by the face. Refused, the refusal above stands. - .or_else(|e| blend_with(body, edges, radius, Shape::Round, "fillet", true).and_then(closed).map_err(|_| e)) + .or_else(|e| blend_with(body, edges, radius, Shape::Round, "fillet", true).and_then(|b| closed(body, b)).map_err(|_| e)) // Blends meeting at corners on curved faces: all at once. - .or_else(|e| corners(body, edges, radius, Shape::Round, "fillet").and_then(closed).map_err(|e2| keep_size(e, e2))) + .or_else(|e| corners(body, edges, radius, Shape::Round, "fillet").and_then(|b| closed(body, b)).map_err(|e2| keep_size(e, e2))) } /// The first refusal, unless only the second found the blend too large (a smaller one may fit). @@ -1970,7 +1977,7 @@ pub fn fillet_each(body: &Body, edges: &[Vec3], radii: &[f64]) -> Result { } Ok(b) }; - if let Ok(b) = crate::blend_corner::fillet_radii(body, &sel).and_then(closed).and_then(fit) { + if let Ok(b) = crate::blend_corner::fillet_radii(body, &sel).and_then(|b| closed(body, b)).and_then(fit) { return Ok(b); } let mut by_radius: Vec<(f64, Vec)> = Vec::new(); diff --git a/crates/kernel/src/body.rs b/crates/kernel/src/body.rs index d38f03a9f..5f77d5d7e 100644 --- a/crates/kernel/src/body.rs +++ b/crates/kernel/src/body.rs @@ -1165,15 +1165,21 @@ impl Body { /// (rounds that overlap where a wall is thinner than both, #871). Boundaries that only /// touch (at a vertex they share, or within the size's millionth) don't count. pub fn crossed_face_loops(&self) -> Result { + Ok(self.crossed_faces()?.len()) + } + + /// The faces [`Body::crossed_face_loops`] counts, each as the mean of its boundary's + /// points: the same for a face an operation carried over unchanged. + pub fn crossed_faces(&self) -> Result> { use mt::{BoundedCurve, ParameterDivision1D}; if self.is_mesh() { - return Ok(0); + return Ok(Vec::new()); } const MAX_SEGMENTS: usize = 20_000; let size = self.size(); let tol = (size * 1e-6).max(1e-9); let chord = (size * 1e-3).max(1e-4); - let mut crossed = 0; + let mut crossed = Vec::new(); for f in self.solid.face_iter() { let mt::Surface::Plane(pl) = f.oriented_surface() else { continue }; let o = from_p3(pl.origin()); @@ -1226,7 +1232,10 @@ impl Body { loops.iter().enumerate().flat_map(|(l, segs)| segs.iter().map(move |s| (l, s))).collect(); let bad = all.iter().enumerate().any(|(i, (_, s))| all.iter().skip(i + 1).any(|(_, t)| cross(s, t))); if bad { - crossed += 1; + let ends: Vec<(f64, f64)> = all.iter().map(|(_, s)| s.0).collect(); + let k = ends.len().max(1) as f64; + let (su, sv) = ends.iter().fold((0.0, 0.0), |acc, p| (acc.0 + p.0, acc.1 + p.1)); + crossed.push(o + u * (su / k) + v * (sv / k)); } } Ok(crossed) From 48322f64645dc2ad97c60cd858368acf136a98a0 Mon Sep 17 00:00:00 2001 From: Giovanni <1319291+gvocale@users.noreply.github.com> Date: Thu, 15 Oct 2026 22:19:22 -0400 Subject: [PATCH 38/92] Join a flange flush with a bent, tapered loft's end where the retry fails (#1391) (#1556) Thanks @gvocale. --- crates/engine/src/tests.rs | 1 + crates/engine/src/tests/flush_join_loft.rs | 99 ++++ crates/kernel/src/clearance.rs | 55 ++- crates/kernel/src/coplanar.rs | 521 ++++++++++++++++++++- crates/kernel/src/coplanar_tests.rs | 58 +++ crates/kernel/src/ops.rs | 24 + crates/kernel/src/planar_faces.rs | 7 + 7 files changed, 753 insertions(+), 12 deletions(-) create mode 100644 crates/engine/src/tests/flush_join_loft.rs diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e9bef2570..000b8b583 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -307,6 +307,7 @@ mod blend_fit; mod boolean_diagnostics; mod component_frames; mod curved_seam_round; +mod flush_join_loft; mod gltf_import; mod import_component; mod large_step_import; diff --git a/crates/engine/src/tests/flush_join_loft.rs b/crates/engine/src/tests/flush_join_loft.rs new file mode 100644 index 000000000..18598e5da --- /dev/null +++ b/crates/engine/src/tests/flush_join_loft.rs @@ -0,0 +1,99 @@ +//! A flange joined flush with the end of a bent, tapered lofted half tube (#1391). +//! +//! The tube is a half annulus with a 6 mm wall, lofted through three sections along a bend of radius 300 mm and 20 degrees, its radius +//! growing from 60 to 75 mm. The flange is a thicker half annulus (3 mm into the wall, 25 mm beyond it), 8 mm thick, extruded back from +//! the tube's end plane and joined. Its front face lies in that plane, coplanar with the tube's end face, and the neighbours of that +//! face are faces of the loft, which curve and lean: the faces cannot be pushed apart, and the join failed with "Union: no result". +//! (With a 40 degree bend the retry with the tool displaced joins it; with this bend that retry fails too.) + +use std::f64::consts::PI; + +use super::*; + +/// Radius of the bend of the tube's axis, and the turn of it (radians). +const BEND: f64 = 300.0; +const TURN: f64 = 20.0 * PI / 180.0; +/// Inner radius of the tube at its start and at its end, and the wall. +const R0: f64 = 60.0; +const R1: f64 = 75.0; +const WALL: f64 = 6.0; +/// How far the flange reaches into the tube's wall, how far beyond its outer face, and how thick it is. +const LAND_IN: f64 = 3.0; +const LAND_OUT: f64 = 25.0; +const THICK: f64 = 8.0; + +/// Sketch coordinates are given to nine decimals, as a design's own would be. +fn r9(x: f64) -> f64 { + (x * 1e9).round() / 1e9 +} + +/// The plane of the section at the bend angle `a`, moved `over` along the axis (the sketch's x is up, its y across the tube). +fn plane(a: f64, over: f64) -> Value { + let (tx, ty) = (a.cos(), a.sin()); + json!({ + "origin": [r9(BEND * a.sin() + over * tx), r9(BEND * (1.0 - a.cos()) + over * ty), 0], + "x_dir": [0, 0, 1], + "y_dir": [r9(ty), r9(-tx), 0], + }) +} + +/// A half annulus (the half above z = 0) on `plane`, between the radii `r_in` and `r_out`. +fn half_annulus(s: &mut Session, name: &str, plane: Value, r_in: f64, r_out: f64) { + let (r_in, r_out) = (r9(r_in), r9(r_out)); + run(s, "sketch.create", json!({"plane": plane, "name": name})); + run(s, "sketch.arc.three_point", json!({"start": [0, -r_out], "end": [0, r_out], "through": [r_out, 0]})); + run(s, "sketch.line", json!({"points": [[0, r_out], [0, r_in]]})); + run(s, "sketch.arc.three_point", json!({"start": [0, r_in], "end": [0, -r_in], "through": [r_in, 0]})); + run(s, "sketch.line", json!({"points": [[0, -r_in], [0, -r_out]]})); + run(s, "sketch.finish", json!({})); +} + +/// The tube: a loft through three sections. +fn tube(s: &mut Session) { + for i in 0..3 { + let t = i as f64 / 2.0; + let r_in = R0 + (R1 - R0) * t; + half_annulus(s, &format!("S{i}"), plane(TURN * t, 0.0), r_in, r_in + WALL); + } + let sections: Vec = (0..3).map(|i| json!({"sketch": format!("S{i}")})).collect(); + run(s, "solid.loft", json!({"sections": sections, "operation": "new", "name": "TubeLoft", "body_name": "Tube"})); +} + +/// The flange, joined to the tube. Its front face is `over` mm past the tube's end plane (0: in it). +fn flange(s: &mut Session, over: f64) { + half_annulus(s, "Flange", plane(TURN, over), R1 + LAND_IN, R1 + WALL + LAND_OUT); + let join = json!({"sketch": "Flange", "distance": THICK + over, "direction": "negative", "operation": "join", "targets": ["Tube"], "name": "JoinFlange"}); + run(s, "solid.extrude", join); +} + +#[test] +fn a_flange_flush_with_the_end_of_a_bent_tapered_tube_joins() { + // The flange's face, the half annulus, has this area. + let (r_in, r_out) = (R1 + LAND_IN, R1 + WALL + LAND_OUT); + let footprint = PI / 2.0 * (r_out * r_out - r_in * r_in); + + // The reference: with the flange 2 mm past the end plane nothing is coplanar with the tube's end face (that join is made by another + // route), and what it adds beyond that plane is the footprint, 2 mm deep. + let mut s = Session::default(); + tube(&mut s); + flange(&mut s, 2.0); + let reference = volume(&mut s) - 2.0 * footprint; + + let mut s = Session::default(); + tube(&mut s); + flange(&mut s, 0.0); + let v = volume(&mut s); + assert!(rel(v, reference) < 3e-4, "{v} against {reference}"); + + // One valid body in one piece, and nothing of it beyond the end plane (to a micrometre: the curved faces end on it within the + // tolerance of their edges): the face the flange and the tube share is one flat face. + 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_eq!(body.lumps().unwrap().len(), 1); + let (origin, normal) = (Vec3::new(BEND * TURN.sin(), BEND * (1.0 - TURN.cos()), 0.0), Vec3::new(TURN.cos(), TURN.sin(), 0.0)); + let mesh = body.tessellate(0.05).unwrap(); + let beyond = mesh.positions.iter().map(|p| (*p - origin).dot(normal)).fold(f64::MIN, f64::max); + assert!(beyond < 1e-3, "the join reaches {beyond} mm past the end plane"); +} diff --git a/crates/kernel/src/clearance.rs b/crates/kernel/src/clearance.rs index a2843ff23..c33c9c963 100644 --- a/crates/kernel/src/clearance.rs +++ b/crates/kernel/src/clearance.rs @@ -110,6 +110,8 @@ pub(crate) struct Clearance<'a> { /// How far a curved face may stand off its triangles. sag: f64, tol: f64, + /// Whether curved faces are judged by their exact bounds (see [`Clearance::with_exact_bounds`]). + exact: bool, } /// Pairs of triangles one question may compare; beyond it there is no answer. @@ -119,7 +121,18 @@ impl<'a> Clearance<'a> { /// `chord`: the chord error of the mesh the body is asked on. pub(crate) fn new(body: &'a Body, chord: f64) -> Option> { let mesh = body.tessellate_with(chord, true).ok()?; - (!mesh.triangles.is_empty()).then(|| Clearance { body, mesh, sag: 2.0 * chord, tol: (body.size() * 1e-7).max(1e-9) }) + (!mesh.triangles.is_empty()).then(|| Clearance { body, mesh, sag: 2.0 * chord, tol: (body.size() * 1e-7).max(1e-9), exact: false }) + } + + /// Judge curved faces by their exact bounds where `clear_of_slab` is asked, not by the chord error each way. A B-spline or NURBS + /// face lies in the hull of its control net, so a face whose net ends before a region begins (a loft's side running out in the + /// plane the region starts from) can't reach into it, however its triangles stand off it. A face of a sphere or a cylinder + /// stands off its triangles away from the centre or the axis only, so a triangle that lies clear of the region and leans away + /// from it is clear (a dome standing on the plane the region starts from). Without this such a face counts as reaching in by + /// the chord error. + pub(crate) fn with_exact_bounds(mut self, on: bool) -> Self { + self.exact = on; + self } /// How the body's material sits in the space that `faces` move through when they go along @@ -194,18 +207,44 @@ impl<'a> Clearance<'a> { /// a unit vector), anywhere? pub(crate) fn clear_of_slab(&self, n: Vec3, d: f64, lo: f64, hi: f64) -> bool { let mut reach: HashMap = HashMap::new(); + let mut round: HashMap> = HashMap::new(); self.mesh.triangles.iter().zip(&self.mesh.tri_face).all(|(t, face)| { let Some(tri) = self.mesh.tri(t) else { return false }; - let pad = match *reach.entry(*face).or_insert_with(|| self.reach(*face, n, d + lo, d + hi)) { + // How far the face may stand off its triangle towards larger and towards smaller heights. + let (up, down) = match *reach.entry(*face).or_insert_with(|| self.reach(*face, n, d + lo, d + hi)) { Reach::Never => return true, - Reach::Around | Reach::Beyond { .. } => self.sag, - Reach::Exact | Reach::Sideways => 0.0, + Reach::Around => (self.sag, self.sag), + Reach::Beyond { .. } => match self.exact.then(|| round.entry(*face).or_insert_with(|| self.round_of(*face))).and_then(|s| s.as_ref()) + { + Some(s) => self.bulge(s, (tri[0] + tri[1] + tri[2]) / 3.0, n), + None => (self.sag, self.sag), + }, + Reach::Exact | Reach::Sideways => (0.0, 0.0), }; let heights = tri.map(|p| n.dot(p) - d); - heights.iter().all(|s| s + pad < lo) || heights.iter().all(|s| s - pad > hi) + heights.iter().all(|s| s + up < lo) || heights.iter().all(|s| s - down > hi) }) } + /// The round surface (sphere, cylinder, cone, torus) a face lies on, if it is one. + fn round_of(&self, face: u32) -> Option { + let f = self.body.solid.face_iter().nth(face as usize)?; + surf_of(f, self.tol * 100.0) + } + + /// How far the surface may stand off a triangle with its centroid at `p`, towards larger and towards smaller heights along `n`: a + /// sphere or a cylinder lies radially outward from its triangles, within the chord error. + fn bulge(&self, s: &Surf, p: Vec3, n: Vec3) -> (f64, f64) { + let radial = match *s { + Surf::Sphere { c, .. } => p - c, + Surf::Cylinder { o, a, .. } => (p - o) - a * (p - o).dot(a), + _ => return (self.sag, self.sag), + }; + let Some(out) = radial.normalized() else { return (self.sag, self.sag) }; + let lean = out.dot(n); + (self.sag * lean.max(0.0), self.sag * (-lean).max(0.0)) + } + /// How the face's triangles stand for it in a region between the heights `lo` and `hi` /// along `along` (measured as `along · p`). fn reach(&self, face: u32, along: Vec3, lo: f64, hi: f64) -> Reach { @@ -218,6 +257,12 @@ impl<'a> Clearance<'a> { if matches!(surface, mt::Surface::Plane(_)) { return Ok(Reach::Exact); } + if self.exact + && let Some((least, greatest)) = crate::planar_faces::control_net_span(&surface, along) + && (greatest <= lo || least >= hi) + { + return Ok(Reach::Never); + } let round = surf_of(f, self.tol * 100.0); let straight = matches!(round, Some(Surf::Cylinder { a, .. }) if a.dot(along).abs() > 1.0 - 1e-12) || crate::prism::wall_along(&surface, along, self.tol * 10.0, &mut 262_144); diff --git a/crates/kernel/src/coplanar.rs b/crates/kernel/src/coplanar.rs index b834963dd..530cc4a4c 100644 --- a/crates/kernel/src/coplanar.rs +++ b/crates/kernel/src/coplanar.rs @@ -240,6 +240,483 @@ pub(crate) fn push_faces_exact(b: &Body, n: Vec3, d: f64, delta: f64) -> Result< }) } +/// Move the planar faces of `b` that lie in the plane (n, d), n their outward normal, out by `delta`, whatever their +/// neighbours are. [`push_faces`] stretches the neighbours, which must stand square to the face along straight edges (a +/// box, an extruded outline); the neighbours of a lofted tube's end cap curve and lean. Here nothing is stretched: the +/// faces move, and each edge one shares with a face that stays gets a new face between them, the edge swept along `n` +/// (a strip). The neighbours keep their surfaces and meet the strips at a crease along the old edge, so the body is +/// the old one with a short prism of the faces' outline on each of them. Exact, with no boolean. The result has no +/// history. +pub(crate) fn grow_faces_exact(b: &Body, n: Vec3, d: f64, delta: f64) -> Result { + use mt::{BoundedCurve, ParametricCurve, ParametricSurface3D, SearchNearestParameter}; + let size = b.size(); + let tol = (size * 1e-7).max(1e-9); + let fail = |m: &str| KernelError::Failed(format!("growing a face: {m}")); + guard("grow face", || { + let solid = b.deep_copy(); + let shift = n * delta; + let mat = mt::Matrix4::from_translation(v3(shift)); + let mut shells = Vec::new(); + for sh in solid.boundaries() { + let faces: Vec = sh.face_iter().cloned().collect(); + let on_plane = |f: &mt::Face| match f.oriented_surface() { + mt::Surface::Plane(p) => { + let m = p.normal(); + let m = Vec3::new(m.x, m.y, m.z); + m.dot(n) > 1.0 - 1e-9 && (n.dot(from_p3(p.origin())) - d).abs() < tol * 10.0 + } + _ => false, + }; + let moving: Vec = (0..faces.len()).filter(|i| faces.get(*i).is_some_and(on_plane)).collect(); + if moving.is_empty() { + shells.push(sh.clone()); + continue; + } + let stays = |i: &usize| !moving.contains(i); + // The faces each edge bounds. + let mut bounds: HashMap> = HashMap::new(); + for (i, f) in faces.iter().enumerate() { + for e in f.edge_iter() { + bounds.entry(e.id()).or_default().push(i); + } + } + // The moved copies of the moving faces' vertices and edges. + let mut vmap: HashMap = HashMap::new(); + let mut emap: HashMap = HashMap::new(); + for i in &moving { + let f = faces.get(*i).ok_or_else(|| fail("face"))?; + for v in f.vertex_iter() { + vmap.entry(v.id()).or_insert_with(|| builder::vertex(p3(from_p3(v.point()) + shift))); + } + } + for i in &moving { + let f = faces.get(*i).ok_or_else(|| fail("face"))?; + for e in f.edge_iter() { + if emap.contains_key(&e.id()) { + continue; + } + let (a, bb) = ( + vmap.get(&e.absolute_front().id()).ok_or_else(|| fail("vertex"))?, + vmap.get(&e.absolute_back().id()).ok_or_else(|| fail("vertex"))?, + ); + emap.insert(e.id(), mt::Edge::new(a, bb, mt::Transformed::transformed(&e.curve(), mat))); + } + } + // The moved copy of an edge, running the way the edge does. + let moved = |e: &mt::Edge| -> Result { + let ne = emap.get(&e.id()).ok_or_else(|| fail("edge"))?; + Ok(if e.front() == e.absolute_front() { ne.clone() } else { ne.inverse() }) + }; + // A strip on every edge between a moving face and one that stays; the edges from a vertex to its moved copy are + // shared by the two strips that meet there. + let mut lateral: HashMap = HashMap::new(); + let mut strips: Vec = Vec::new(); + for i in &moving { + let f = faces.get(*i).ok_or_else(|| fail("face"))?; + for w in f.boundaries() { + for e in w.edge_iter() { + let Some(&beside) = bounds.get(&e.id()).and_then(|fs| fs.iter().find(|j| stays(j))) else { continue }; + // The moving face runs along the edge from p to q; the strip runs along it the same way. + let (p, q) = (e.front().clone(), e.back().clone()); + let mut lat = |v: &mt::Vertex| -> Result { + let to = vmap.get(&v.id()).ok_or_else(|| fail("vertex"))?; + Ok(lateral.entry(v.id()).or_insert_with(|| builder::line(v, to)).clone()) + }; + let (lp, lq) = (lat(&p)?, lat(&q)?); + let wire: mt::Wire = vec![e.clone(), lq, moved(e)?.inverse(), lp.inverse()].into(); + // Its surface is the edge's curve swept along `n`, facing the way the face beside it does; a straight edge + // sweeps to a plane (truck makes that a B-spline patch, which does not mesh). + let curve = e.curve(); + let (t0, t1) = curve.range_tuple(); + let mid = from_p3(curve.subs(0.5 * (t0 + t1))); + let old = faces.get(beside).ok_or_else(|| fail("face"))?.oriented_surface(); + let Some((u0, v0)) = old.search_nearest_parameter(p3(mid), None, 100) else { + return Err(fail("which way a strip faces")); + }; + let outward = old.normal(u0, v0); + let outward = Vec3::new(outward.x, outward.y, outward.z); + // (a loft's straight section edge is a B-spline of degree one, so ask the points, not the type) + let straight = [0.2, 0.4, 0.6, 0.8].iter().all(|t| { + let x = from_p3(curve.subs(t0 + t * (t1 - t0))); + let chord = from_p3(q.point()) - from_p3(p.point()); + let off = (x - from_p3(p.point())).cross(chord).len(); + off <= tol * 10.0 * chord.len() + }); + let s = if straight { + let dir = (from_p3(q.point()) - from_p3(p.point())).normalized().ok_or_else(|| fail("a zero edge"))?; + let mut m = dir.cross(n).normalized().ok_or_else(|| fail("an edge along the normal"))?; + if m.dot(outward) < 0.0 { + m = -m; + } + let o = from_p3(p.point()); + mt::Surface::Plane(mt::Plane::new(p3(o), p3(o + dir), p3(o + m.cross(dir)))) + } else { + let swept: mt::Face = builder::tsweep(e, v3(shift)); + let mut s = swept.surface(); + let Some((u1, v1)) = s.search_nearest_parameter(p3(mid + shift * 0.5), None, 100) else { + return Err(fail("which way a strip faces")); + }; + let now = s.normal(u1, v1); + if outward.dot(Vec3::new(now.x, now.y, now.z)) < 0.0 { + s = mt::Invertible::inverse(&s); + } + s + }; + strips.push(mt::Face::try_new(vec![wire], s).map_err(|e| fail(&e.to_string()))?); + } + } + } + let mut out: Vec = Vec::new(); + for (i, f) in faces.iter().enumerate() { + if !moving.contains(&i) { + out.push(f.clone()); + continue; + } + let wires = f + .absolute_boundaries() + .iter() + .map(|w| w.edge_iter().map(&moved).collect::>>().map(mt::Wire::from)) + .collect::>>()?; + let mut nf = mt::Face::try_new(wires, mt::Transformed::transformed(&f.surface(), mat)).map_err(|e| fail(&e.to_string()))?; + if !f.orientation() { + nf.invert(); + } + out.push(nf); + } + out.extend(strips); + shells.push(out.into()); + } + let s = Solid::try_new(shells).map_err(|e| fail(&e.to_string()))?; + let r = Body::new(s)?; + let problems = r.validity(); + if !problems.is_empty() { + return Err(fail(&format!("an unsound result ({})", problems.iter().take(2).cloned().collect::>().join("; ")))); + } + Ok(r) + }) +} + +/// An edge's points from its start to its end along its curve, `k + 1` of them. +fn edge_samples(e: &mt::Edge, k: u32) -> Vec { + use mt::{BoundedCurve, ParametricCurve}; + let c = e.curve(); + let (t0, t1) = c.range_tuple(); + (0..=k).map(|i| from_p3(c.subs(t0 + (t1 - t0) * f64::from(i) / f64::from(k)))).collect() +} + +/// Where the edges of `b` cross the plane (n, d), one point for every time (edges are cut there before a body is trimmed). +fn plane_crossings(b: &Body, n: Vec3, d: f64, tol: f64) -> Vec { + use mt::{BoundedCurve, ParametricCurve}; + const STEPS: u32 = 64; + let mut out = Vec::new(); + for e in b.solid.edge_iter() { + let c = e.curve(); + let (t0, t1) = c.range_tuple(); + let at = |t: f64| from_p3(c.subs(t)); + let h = |t: f64| n.dot(at(t)) - d; + let ts: Vec = (0..=STEPS).map(|i| t0 + (t1 - t0) * f64::from(i) / f64::from(STEPS)).collect(); + // The samples clear of the plane, and between each two that lie on different sides the crossing. + let clear: Vec<(f64, f64)> = ts.iter().map(|t| (*t, h(*t))).filter(|(_, x)| x.abs() > tol).collect(); + for pair in clear.windows(2) { + let [(ta, ha), (tb, hb)] = pair else { continue }; + if (*ha < 0.0) == (*hb < 0.0) { + continue; + } + let (mut lo, mut hi, mut hlo) = (*ta, *tb, *ha); + for _ in 0..80 { + let mid = 0.5 * (lo + hi); + let hm = h(mid); + if (hm < 0.0) == (hlo < 0.0) { + lo = mid; + hlo = hm; + } else { + hi = mid; + } + } + out.push(at(0.5 * (lo + hi))); + } + } + out +} + +/// Which side of the plane (n, d) an edge lies on, once edges that cross it are cut: -1 near, +1 far, 0 in it. +fn edge_side(e: &mt::Edge, n: Vec3, d: f64, tol: f64) -> Result { + let hs: Vec = edge_samples(e, 8).iter().map(|p| n.dot(*p) - d).collect(); + let (lo, hi) = hs.iter().fold((f64::MAX, f64::MIN), |(l, h), x| (l.min(*x), h.max(*x))); + if hi <= tol && lo >= -tol { + Ok(0) + } else if hi <= tol { + Ok(-1) + } else if lo >= -tol { + Ok(1) + } else { + Err(KernelError::Failed("trimming at a plane: an edge still crosses it".into())) + } +} + +/// Whether the point lies on the surface, to within `tol`. +fn on_surface(s: &mt::Surface, p: Vec3, tol: f64) -> bool { + use mt::{ParametricSurface, SearchNearestParameter}; + if let mt::Surface::Plane(pl) = s { + let m = pl.normal(); + return (Vec3::new(m.x, m.y, m.z).dot(p - from_p3(pl.origin()))).abs() <= tol; + } + s.search_nearest_parameter(p3(p), None, 100).is_some_and(|(u, v)| from_p3(s.subs(u, v)).dist(p) <= tol) +} + +/// The edge that closes the boundary of the flat face `face` from the vertex `from` to the vertex `to` (both in the plane) where a run of +/// its edges beyond the plane went: the segment between them, which lies in the face. (A curved face that crosses the plane has been +/// divided along it already.) Nothing when they are the same vertex. +fn bridge(face: &mt::Face, from: &mt::Vertex, to: &mt::Vertex, tol: f64) -> Result> { + if from.id() == to.id() { + return Ok(Vec::new()); + } + let (p, q) = (from_p3(from.point()), from_p3(to.point())); + let surface = face.oriented_surface(); + if [0.25, 0.5, 0.75].iter().all(|t| on_surface(&surface, p + (q - p) * *t, tol * 10.0)) { + Ok(vec![builder::line(from, to)]) + } else { + Err(KernelError::Failed("trimming at a plane: a curved face crosses the plane where it could not be divided".into())) + } +} + +/// One boundary of the flat face `face`, which crosses the plane (n, d), clipped to the near side: the edges beyond the plane go and the +/// segment in the plane from where the boundary leaves it to where it comes back takes their place. `None` when nothing of the boundary +/// is on the near side. +fn clip_wire(face: &mt::Face, w: &mt::Wire, n: Vec3, d: f64, tol: f64) -> Result>> { + let fail = |m: &str| KernelError::Failed(format!("trimming at a plane: {m}")); + let mut edges: Vec<(mt::Edge, i8)> = Vec::new(); + for e in w.edge_iter() { + let side = edge_side(e, n, d, tol)?; + edges.push((e.clone(), side)); + } + if !edges.iter().any(|(_, side)| *side < 0) { + return Ok(None); + } + let m = edges.len(); + let gone = |i: usize| edges.get(i % m).is_some_and(|(_, side)| *side > 0); + // Begin where a run of edges beyond the plane ends, so that no run is split between the end and the start. + let Some(start) = (0..m).find(|i| !gone(*i) && gone(*i + m - 1)) else { + return Ok(Some(edges.into_iter().map(|(e, _)| e).collect())); + }; + let mut out: Vec = Vec::new(); + let mut skipping = false; + for k in 0..m { + let Some((e, side)) = edges.get((start + k) % m) else { continue }; + if *side > 0 { + skipping = true; + continue; + } + if skipping { + let from = out.last().ok_or_else(|| fail("a run beyond the plane first"))?.back().clone(); + out.extend(bridge(face, &from, e.front(), tol)?); + skipping = false; + } + out.push(e.clone()); + } + if skipping { + let from = out.last().ok_or_else(|| fail("nothing kept"))?.back().clone(); + let to = out.first().ok_or_else(|| fail("nothing kept"))?.front().clone(); + out.extend(bridge(face, &from, &to, tol)?); + } + Ok(Some(out)) +} + +/// `b` with everything beyond the plane (n, d) cut off, for a body that was grown or pushed past the plane (the faces that +/// [`grow_faces_exact`] and [`push_faces`] moved) and joined there. A cut with a boolean would run along the edges where the grown +/// faces meet their neighbours, which the mesh intersection cannot take. Here the edges that cross the plane are cut at it, the +/// faces beyond it go, each face that crosses it gets one edge in the plane where its far part was, and the rim they leave (edges +/// lying in the plane) is closed with flat faces. The result has no history. +pub(crate) fn trim_exact(b: &Body, n: Vec3, d: f64) -> Result { + let fail = |m: &str| KernelError::Failed(format!("trimming at a plane: {m}")); + let tol = (b.size() * 1e-6).max(1e-9); + // A curved face that crosses the plane (a sphere or a cylinder stretched past it) is divided along the plane where they meet, exactly + // ([`crate::splitface::split_faces`]); the flat ones are clipped below. + let curved: Vec = b + .solid + .face_iter() + .enumerate() + .filter(|(_, f)| !matches!(f.oriented_surface(), mt::Surface::Plane(_))) + .filter(|(_, f)| { + let (mut near, mut far) = (false, false); + for e in f.edge_iter() { + for p in edge_samples(&e, 8) { + near |= n.dot(p) - d < -tol; + far |= n.dot(p) - d > tol; + } + } + near && far + }) + .map(|(i, _)| i) + .collect(); + let divided = if curved.is_empty() { + b.clone() + } else { + let u = n.any_perp(); + let plane = solidcraft_geom::Plane::new(n * d, u, n.cross(u)).ok_or_else(|| fail("the plane"))?; + crate::splitface::split_faces(b, &curved, &crate::SplitTool::Plane(plane))? + }; + let cut = crate::splitface::split_edges_at(÷d, &plane_crossings(÷d, n, d, tol))?; + guard("trim at a plane", || { + let mut kept: Vec = Vec::new(); + for f in cut.solid.face_iter() { + let mut sides: Vec = Vec::new(); + for e in f.edge_iter() { + sides.push(edge_side(&e, n, d, tol)?); + } + match (sides.contains(&-1), sides.contains(&1)) { + (true, false) => kept.push(f.clone()), + (false, true) => {} + // A face lying in the plane (a sliver the join left there) goes with the others: the rim it leaves is closed below. + (false, false) => {} + (true, true) => { + let mut wires: Vec = Vec::new(); + for (i, w) in f.absolute_boundaries().iter().enumerate() { + match clip_wire(f, w, n, d, tol)? { + Some(edges) => wires.push(edges.into()), + None if i == 0 => return Err(fail("a face with no edge left on the near side")), + None => {} + } + } + let mut nf = mt::Face::try_new(wires, f.surface()).map_err(|x| fail(&x.to_string()))?; + if !f.orientation() { + nf.invert(); + } + kept.push(nf); + } + } + } + close_rim(kept, n, d, tol) + }) +} + +/// The body whose faces are `faces`, which leave an opening in the plane (n, d): the edges only one face is on (all lying in the plane) +/// are closed with flat faces. Counterclockwise loops about the normal are outlines, the others holes in the outline around them. +fn close_rim(mut faces: Vec, n: Vec3, d: f64, tol: f64) -> Result { + let fail = |m: &str| KernelError::Failed(format!("closing the cut: {m}")); + let mut uses: HashMap = HashMap::new(); + for f in &faces { + for e in f.edge_iter() { + *uses.entry(e.id()).or_default() += 1; + } + } + if uses.values().any(|c| *c > 2) { + return Err(fail("an edge on more than two faces")); + } + let mut open: Vec = Vec::new(); + for f in &faces { + for w in f.boundaries() { + for e in w.edge_iter() { + if uses.get(&e.id()) == Some(&1) { + if edge_samples(e, 8).iter().any(|p| (n.dot(*p) - d).abs() > tol) { + return Err(fail("an edge left open off the plane")); + } + // The cap runs along it the other way. + open.push(e.inverse()); + } + } + } + } + if open.is_empty() { + return Err(fail("nothing was cut off")); + } + let mut loops: Vec> = Vec::new(); + while let Some(first) = open.pop() { + let start = first.front().id(); + let mut at = first.back().id(); + let mut chain = vec![first]; + while at != start { + let next: Vec = (0..open.len()).filter(|i| open.get(*i).is_some_and(|e| e.front().id() == at)).collect(); + let [i] = next[..] else { return Err(fail("the rim does not close up, or pinches")) }; + let e = open.remove(i); + at = e.back().id(); + chain.push(e); + } + loops.push(chain); + } + let u = n.any_perp(); + let v = n.cross(u); + let origin = n * d; + let polys: Vec> = loops + .iter() + .map(|chain| { + chain + .iter() + .flat_map(|e| { + let mut pts = edge_samples(e, 8); + if !e.orientation() { + pts.reverse(); + } + pts.pop(); + pts + }) + .map(|p| ((p - origin).dot(u), (p - origin).dot(v))) + .collect() + }) + .collect(); + let areas: Vec = polys + .iter() + .map(|poly| { + let m = poly.len(); + (0..m) + .map(|i| match (poly.get(i), poly.get((i + 1) % m)) { + (Some(a), Some(b)) => a.0 * b.1 - b.0 * a.1, + _ => 0.0, + }) + .sum::() + * 0.5 + }) + .collect(); + let inside = |poly: &[(f64, f64)], q: (f64, f64)| -> bool { + let m = poly.len(); + (0..m) + .filter(|i| match (poly.get(*i), poly.get((*i + 1) % m)) { + (Some(a), Some(b)) => (a.1 > q.1) != (b.1 > q.1) && q.0 < (b.0 - a.0) * (q.1 - a.1) / (b.1 - a.1) + a.0, + _ => false, + }) + .count() + % 2 + == 1 + }; + let outers: Vec = (0..loops.len()).filter(|i| areas.get(*i).is_some_and(|a| *a > 0.0)).collect(); + let mut holes_of: HashMap> = HashMap::new(); + for i in (0..loops.len()).filter(|i| !outers.contains(i)) { + let q = polys.get(i).and_then(|p| p.first()).copied().ok_or_else(|| fail("an empty loop"))?; + let around = outers + .iter() + .filter(|o| polys.get(**o).is_some_and(|p| inside(p, q))) + .min_by(|x, y| areas.get(**x).partial_cmp(&areas.get(**y)).unwrap_or(std::cmp::Ordering::Equal)) + .ok_or_else(|| fail("a hole outside every outline"))?; + holes_of.entry(*around).or_default().push(i); + } + let surface = mt::Surface::Plane(mt::Plane::new(p3(origin), p3(origin + u), p3(origin + v))); + for o in &outers { + let mut wires: Vec = vec![loops.get(*o).cloned().ok_or_else(|| fail("a loop"))?.into()]; + for h in holes_of.get(o).into_iter().flatten() { + wires.push(loops.get(*h).cloned().ok_or_else(|| fail("a loop"))?.into()); + } + faces.push(mt::Face::try_new(wires, surface.clone()).map_err(|x| fail(&x.to_string()))?); + } + let shell: mt::Shell = faces.into(); + let solid = Solid::try_new(crate::polybool::components_in_order(&shell)).map_err(|x| fail(&x.to_string()))?; + let r = Body::new(solid)?; + let problems = r.validity(); + if !problems.is_empty() { + return Err(fail(&format!("an unsound result ({})", problems.iter().take(2).cloned().collect::>().join("; ")))); + } + Ok(r) +} + +/// Move the planar faces of `x` in the plane (n, d) out by `delta`: stretched ([`push_faces`]) where their neighbours +/// allow it, else, when `grow`, grown ([`grow_faces_exact`]). Whether it grew them (the body then has no history). +fn move_out(x: &Body, n: Vec3, d: f64, delta: f64, grow: bool) -> Result<(Body, bool)> { + match push_faces(x, n, d, delta) { + Ok(r) => Ok((r, false)), + Err(e) if grow => grow_faces_exact(x, n, d, delta).map(|r| (r, true)).map_err(|_| e), + Err(e) => Err(e), + } +} + /// A box covering everything beyond the plane (n, d) by up to `depth`. fn slab_beyond(n: Vec3, d: f64, depth: f64, extent: f64) -> Result { let u = n.any_perp(); @@ -326,6 +803,23 @@ pub(crate) const NO_ROOM: &str = "coincident faces were left in place: pushing t /// coincident faces or the faces can't be pushed; the error [`NO_ROOM`] when a face would /// move through something that changes the result. pub(crate) fn boolean_apart(a: &Body, b: &Body, op: BoolOp) -> Option>> { + apart_with(a, b, op, false) +} + +/// [`boolean_apart`] for a join whose coincident faces cannot be pushed, because the neighbours of one of them curve +/// (a flange flush with the end of a lofted tube): such a face is grown instead ([`grow_faces_exact`]) and the join's excess beyond +/// the plane is cut off again by editing faces ([`trim_exact`]), where a boolean would fail on the edges the grown faces meet their +/// neighbours along. The planar faces that sit on B-spline surfaces (a loft's flat sides) are put on planes first so that they +/// are seen. Asked after the other routes have failed, so that what they take stays as it was. `None` when it does not apply. +pub(crate) fn boolean_grown(a: &Body, b: &Body, op: BoolOp) -> Option>> { + if op != BoolOp::Union { + return None; + } + let (pa, pb) = (crate::planar_faces::planarized(a), crate::planar_faces::planarized(b)); + apart_with(pa.as_ref().unwrap_or(a), pb.as_ref().unwrap_or(b), op, true) +} + +fn apart_with(a: &Body, b: &Body, op: BoolOp, grow: bool) -> Option>> { let size = a.size().max(b.size()); let tol = (size * 1e-7).max(1e-9); let coincident = coincident_planes(a, b); @@ -341,7 +835,7 @@ pub(crate) fn boolean_apart(a: &Body, b: &Body, op: BoolOp) -> Option Result> { // The target's faces, meshed when the first face asks what it would move through. let faces_of_a = std::cell::OnceCell::new(); - let target = || faces_of_a.get_or_init(|| Clearance::new(a, chord)).as_ref().ok_or_else(no_room); + let target = || faces_of_a.get_or_init(|| Clearance::new(a, chord).map(|c| c.with_exact_bounds(grow))).as_ref().ok_or_else(no_room); let (mut a2, mut b2) = (a.clone(), b.clone()); // What the pushed bodies are made of: their histories over [a] and [b]. let (mut ha, mut hb) = (crate::boolean_record::kept(a, 0, 1), crate::boolean_record::kept(b, 0, 1)); @@ -351,7 +845,7 @@ pub(crate) fn boolean_apart(a: &Body, b: &Body, op: BoolOp) -> Option Option Option Body { + let ball = sphere(Vec3::ZERO, r).unwrap(); + let below = box_solid(Vec3::new(-2.0 * r, -2.0 * r, -2.0 * r), Vec3::new(2.0 * r, 2.0 * r, 0.0)).unwrap(); + boolean(&ball, &below, BoolOp::Cut).unwrap().unwrap() +} + +/// A hemisphere (r 20) and a block (x 5 to 35, y -30 to 30, z 0 to 25) that both stand on z = 0, the block's foot over most of the +/// hemisphere's flat face. The neighbour of that face is the sphere, which cannot be stretched, so its face is grown instead (a +/// strip along its rim) and what the join leaves below the plane is cut off by editing faces. The block takes the part of the dome +/// beyond x = 5, half of a cap 15 high: the union is the dome and the block less that part. +#[test] +fn a_block_flush_with_the_flat_face_of_a_hemisphere_joins_exactly() { + let (r, x0) = (20.0, 5.0); + let block = box_solid(Vec3::new(x0, -30.0, 0.0), Vec3::new(35.0, 30.0, 25.0)).unwrap(); + let dome = hemisphere(r); + let h = r - x0; + let expected = 2.0 / 3.0 * std::f64::consts::PI * r.powi(3) - std::f64::consts::PI * h * h * (3.0 * r - h) / 6.0 + 30.0 * 60.0 * 25.0; + for (a, b) in [(&dome, &block), (&block, &dome)] { + let joined = crate::coplanar::boolean_grown(a, b, BoolOp::Union).expect("the route applies").unwrap().unwrap(); + let v = measure(&joined).unwrap().volume; + assert!((v - expected).abs() < expected * 1e-4, "{v} against {expected}"); + assert_eq!(joined.lumps().unwrap().len(), 1); + assert!(joined.validity().is_empty(), "{:?}", joined.validity()); + // The flat faces are one plane again: nothing of the join stays below z = 0. + let mesh = joined.tessellate(0.05).unwrap(); + let lowest = mesh.positions.iter().map(|p| p.z).fold(f64::MAX, f64::min); + assert!(lowest > -1e-6, "the join reaches down to z = {lowest}"); + } +} + +/// Growing the flat face of a dome past its plane and cutting what that adds off again gives the dome back: the same volume, the same +/// faces, nothing below the plane. +#[test] +fn what_growing_a_face_adds_is_cut_off_again_exactly() { + let dome = hemisphere(20.0); + let measured = measure(&dome).unwrap().volume; + let grown = crate::coplanar::grow_faces_exact(&dome, -Vec3::Z, 0.0, 3.0).unwrap(); + assert!(measure(&grown).unwrap().volume > measured + 3.0 * 300.0, "the stub adds volume"); + let back = crate::coplanar::trim_exact(&grown, -Vec3::Z, 0.0).unwrap(); + let v = measure(&back).unwrap().volume; + assert!((v - measured).abs() < measured * 1e-6, "{v} against {measured}"); + assert_eq!(back.face_count(), dome.face_count()); + assert!(back.validity().is_empty(), "{:?}", back.validity()); + let lowest = back.tessellate(0.05).unwrap().positions.iter().map(|p| p.z).fold(f64::MAX, f64::min); + assert!(lowest > -1e-6, "the body reaches down to z = {lowest}"); +} + +/// A plane the body stands on has nothing beyond it, and one clear of the body is refused (nothing is cut off). +#[test] +fn trimming_at_a_plane_with_nothing_beyond_it() { + let dome = hemisphere(20.0); + let measured = measure(&dome).unwrap().volume; + let same = crate::coplanar::trim_exact(&dome, -Vec3::Z, 0.0).unwrap(); + assert!((measure(&same).unwrap().volume - measured).abs() < measured * 1e-9); + assert!(crate::coplanar::trim_exact(&dome, -Vec3::Z, 5.0).is_err()); +} diff --git a/crates/kernel/src/ops.rs b/crates/kernel/src/ops.rs index 0afa9ee23..491890e5b 100644 --- a/crates/kernel/src/ops.rs +++ b/crates/kernel/src/ops.rs @@ -977,6 +977,30 @@ fn boolean_whole(a: &Body, b: &Body, op: BoolOp) -> Result> { Err(e) => last = format!("{last}; nudged: {e}"), } } + // A join whose coincident planar faces cannot be pushed apart because the neighbours of one of them curve (a flange + // flush with the end of a lofted tube): the faces are grown instead, and what the growth leaves beyond the plane is cut + // off by editing the faces. After every route above, the nudge included, has failed, so that a join any of them takes + // stays as it was. + if op == BoolOp::Union && !APART.with(|c| c.get()) { + APART.with(|c| c.set(true)); + let (r, diagnostics) = capture_boolean_diagnostics(|| crate::coplanar::boolean_grown(a, b, op)); + APART.with(|c| c.set(false)); + match r { + Some(Ok(Some(body))) => { + let (ok, v) = check(&body); + if ok { + merge(diagnostics); + let mut event = BooleanFallback::new(BooleanStrategy::CoplanarSeparation); + event.face_shift_mm = size * 0.0137; + record(event); + return Ok(Some(body)); + } + last = format!("{last}; faces grown apart gave an implausible volume {v:.4}"); + } + Some(Err(e)) => last = format!("{last}; {e}"), + Some(Ok(None)) | None => {} + } + } // The tries at the meeting region's scale come last, after every strategy that answered // before them, so a result any of those gave is kept as it was. if let Some(body) = fine(&mut last) { diff --git a/crates/kernel/src/planar_faces.rs b/crates/kernel/src/planar_faces.rs index d4df8fa65..17e1b3130 100644 --- a/crates/kernel/src/planar_faces.rs +++ b/crates/kernel/src/planar_faces.rs @@ -36,6 +36,13 @@ fn control_points(s: &mt::Surface) -> Option> { } } +/// The least and the greatest `along · p` over the control points of a B-spline or NURBS surface; the surface lies +/// between them (it is in the convex hull of its control net). `None` for any other surface. +pub(crate) fn control_net_span(s: &mt::Surface, along: Vec3) -> Option<(f64, f64)> { + let pts = control_points(s)?; + pts.iter().map(|p| along.dot(*p)).fold(None, |acc, h| Some(acc.map_or((h, h), |(lo, hi): (f64, f64)| (lo.min(h), hi.max(h))))) +} + /// A point and the unit normal of the plane every point lies within `tol` of, if there is one. fn common_plane(pts: &[Vec3], tol: f64) -> Option<(Vec3, Vec3)> { let p0 = *pts.first()?; From 1a0b33fcf32d579536bf8b90b851bdaec8a9209a Mon Sep 17 00:00:00 2001 From: Irakli Kourtis Date: Thu, 15 Oct 2026 22:19:26 -0400 Subject: [PATCH 39/92] Headless pictures draw on the GPU, with the viewport's pipelines (CPU rasterizer as last tier) (#1555) Thanks @jyviko. --- .github/workflows/ci.yml | 15 +- .github/workflows/pages.yml | 7 + ATTRIBUTION.md | 2 +- Cargo.lock | 7 + README.md | 2 +- apps/solidcraft-cli/Cargo.toml | 5 + apps/solidcraft-cli/src/main.rs | 68 +- apps/solidcraft-cli/tests/run_results.rs | 19 +- apps/solidcraft-cli/tests/snapshot_camera.rs | 239 ++- apps/solidcraft-web/src/main.rs | 2 + apps/solidcraft/src/main.rs | 1 + assets/styles/ui/palettes.rs | 7 +- crates/engine/src/capture.rs | 114 ++ crates/engine/src/cmd/file.rs | 2 + crates/engine/src/cmd/file_thumbnail.rs | 88 +- crates/engine/src/lib.rs | 15 + crates/engine/src/view.rs | 90 +- crates/engine/src/view_palette_tests.rs | 17 +- crates/gpu/Cargo.toml | 7 +- crates/gpu/src/capture.rs | 428 +++++ crates/gpu/src/lib.rs | 38 +- .../src/pbr_gpu.rs => gpu/src/pbr.rs} | 0 crates/gpu/src/select.rs | 261 +++ crates/gpu/src/view.rs | 1590 +++++++++++++++++ crates/gpu/tests/capture.rs | 168 ++ crates/mcp/Cargo.toml | 4 + crates/mcp/src/backend.rs | 24 +- crates/mcp/src/tests.rs | 53 +- crates/mcp/src/tools.rs | 9 +- crates/render/Cargo.toml | 2 +- crates/render/src/analysis.rs | 54 + crates/render/src/lib.rs | 6 +- crates/render/src/raster.rs | 62 +- crates/render/src/scene.rs | 65 + crates/ui-egui/src/access.rs | 74 +- crates/ui-egui/src/agent_chat/mod.rs | 9 +- crates/ui-egui/src/control.rs | 89 +- crates/ui-egui/src/dialogs_assembly_tests.rs | 1 - crates/ui-egui/src/dialogs_sheet_tests.rs | 1 - crates/ui-egui/src/file_load.rs | 28 +- crates/ui-egui/src/file_load_ui_tests.rs | 1 - crates/ui-egui/src/gpu.rs | 1554 +--------------- crates/ui-egui/src/home.rs | 15 +- crates/ui-egui/src/render_workspace.rs | 6 +- crates/ui-egui/src/render_workspace_tests.rs | 1 - crates/ui-egui/src/scenario.rs | 15 +- crates/ui-egui/src/theme.rs | 14 +- crates/ui-egui/src/viewport.rs | 218 +-- docs/book/src/dev/architecture.md | 11 +- docs/book/src/guide/getting-started.md | 2 +- docs/control-protocol.md | 2 +- docs/mcp.md | 4 +- xtask/src/book.rs | 2 +- xtask/src/layers.rs | 5 +- 54 files changed, 3525 insertions(+), 1998 deletions(-) create mode 100644 crates/engine/src/capture.rs create mode 100644 crates/gpu/src/capture.rs rename crates/{ui-egui/src/pbr_gpu.rs => gpu/src/pbr.rs} (100%) create mode 100644 crates/gpu/src/select.rs create mode 100644 crates/gpu/src/view.rs create mode 100644 crates/gpu/tests/capture.rs create mode 100644 crates/render/src/analysis.rs create mode 100644 crates/render/src/scene.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a245aab59..6046eed95 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -202,8 +202,18 @@ jobs: fail-fast: false matrix: shard: [1, 2, 3, 4] + env: + # Pictures (snapshots, screenshots, ui.render, the viewport's offscreen tests) are drawn on + # the GPU. The runner has none: Mesa's lavapipe (software Vulkan) draws them, and a test that + # would skip for want of an adapter fails instead. + SOLIDCRAFT_GPU: software + SOLIDCRAFT_REQUIRE_GPU: "1" steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Install a software Vulkan driver (lavapipe) + 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 @@ -364,7 +374,8 @@ jobs: # D3D12's older shader compiler (FXC, used where dxcompiler.dll is absent) is stricter than # DXC, Vulkan and Metal: a shader it cannot compile once crashed the app at startup. Build the # GPU tessellation pipeline with FXC on the runner's WARP software adapter and compare its - # results with the CPU. + # results with the CPU, and draw headless pictures with the viewport's pipelines there + # (crates/gpu/tests/capture.rs). windows-fxc: name: Windows D3D12 FXC shaders needs: changes @@ -374,6 +385,8 @@ jobs: env: WGPU_BACKEND: dx12 WGPU_DX12_COMPILER: fxc + # WARP is a software (Cpu) adapter. + SOLIDCRAFT_GPU: software SOLIDCRAFT_REQUIRE_GPU: "1" steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml index 401b39473..604c3fef1 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -45,7 +45,14 @@ jobs: curl -sSL "https://github.com/rust-lang/mdBook/releases/download/${MDBOOK_VERSION}/mdbook-${MDBOOK_VERSION}-x86_64-unknown-linux-gnu.tar.gz" | tar -xz -C "$HOME/.local/bin" curl -sSL "https://github.com/trunk-rs/trunk/releases/download/${TRUNK_VERSION}/trunk-x86_64-unknown-linux-gnu.tar.gz" | tar -xz -C "$HOME/.local/bin" echo "$HOME/.local/bin" >> "$GITHUB_PATH" + - name: Install a software Vulkan driver (lavapipe) + # The book's pictures are `solidcraft-cli snapshot`s, drawn on the GPU; the runner has none. + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends mesa-vulkan-drivers libvulkan1 - name: Build the book + env: + SOLIDCRAFT_GPU: software run: cargo xtask book - name: Build the web app working-directory: apps/solidcraft-web diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 9c7c0876a..d20962567 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -16,7 +16,7 @@ Editable drawing code, native projects and shipped exports are collected under ` |---|---|---|---| | examples/render-studio.json | SolidCraft contributors | original procedural box/cylinder enclosure script for the integrated Render workspace | MIT OR Apache-2.0 | | examples/render-opaque-studio.json | SolidCraft contributors | original procedural sphere study varying opaque metal fraction and roughness independently; no external assets or engineering data | MIT OR Apache-2.0 | -| crates/ui-egui/src/pbr_gpu.rs | SolidCraft contributors | original WGSL translation of SolidCraft's opaque surface and fixed studio reference, embedded as Rust source; no external shader code | MIT OR Apache-2.0 | +| crates/gpu/src/pbr.rs | SolidCraft contributors | original WGSL translation of SolidCraft's opaque surface and fixed studio reference, embedded as Rust source; no external shader code | MIT OR Apache-2.0 | | assets/archive/icons/macos-v1/exports/icon.svg | SolidCraft contributors | original macOS adaptation of the code-drawn SolidCraft mark, edited and exported with VectorCraft; Apple HIG and production templates consulted as layout references only | MIT OR Apache-2.0 | | assets/icons/app/macos/source/SolidCraft.icon/icon.json | SolidCraft contributors | approved Icon Composer composition and appearance settings for the original SolidCraft artwork | MIT OR Apache-2.0 | | assets/icons/app/macos/source/SolidCraft.icon/Assets/02-grid.svg | SolidCraft contributors | original perspective grid with elliptical radial alpha, exported from VectorCraft | MIT OR Apache-2.0 | diff --git a/Cargo.lock b/Cargo.lock index 6862c0be5..d8602e2f4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4023,8 +4023,10 @@ dependencies = [ name = "solidcraft-cli" version = "0.13.1" dependencies = [ + "image", "serde_json", "solidcraft-engine", + "solidcraft-gpu", "solidcraft-mcp", ] @@ -4086,8 +4088,12 @@ dependencies = [ "log", "naga", "pollster 0.4.0", + "serde", + "serde_json", + "solidcraft-engine", "solidcraft-geom", "solidcraft-kernel", + "solidcraft-render", "thiserror 2.0.21", "wgpu", ] @@ -4135,6 +4141,7 @@ version = "0.13.1" dependencies = [ "serde_json", "solidcraft-engine", + "solidcraft-gpu", ] [[package]] diff --git a/README.md b/README.md index 3b11f3dd1..b5c0c8fca 100644 --- a/README.md +++ b/README.md @@ -236,7 +236,7 @@ configuration and an example session: [docs/mcp.md](docs/mcp.md). | 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 CPU rasterizer | +| 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) | diff --git a/apps/solidcraft-cli/Cargo.toml b/apps/solidcraft-cli/Cargo.toml index 3e4f01e11..85401bae6 100644 --- a/apps/solidcraft-cli/Cargo.toml +++ b/apps/solidcraft-cli/Cargo.toml @@ -21,5 +21,10 @@ path = "src/alias.rs" [dependencies] solidcraft-engine = { workspace = true } +solidcraft-gpu = { workspace = true } solidcraft-mcp = { workspace = true } serde_json = { workspace = true } + +[dev-dependencies] +# Snapshot tests decode the pictures to compare them with a tolerance. +image = { workspace = true } diff --git a/apps/solidcraft-cli/src/main.rs b/apps/solidcraft-cli/src/main.rs index 9d3200690..b078297ab 100644 --- a/apps/solidcraft-cli/src/main.rs +++ b/apps/solidcraft-cli/src/main.rs @@ -34,7 +34,6 @@ use serde_json::{Value, json}; mod app_icon; use solidcraft_engine::Session; -use solidcraft_engine::render::render_png; use solidcraft_engine::view::Guides; const USAGE: &str = "usage: @@ -63,6 +62,10 @@ const USAGE: &str = "usage: solidcraft-cli mcp [--in design.solidcraft|script.json] [--connect 127.0.0.1:PORT [--token T]] [--allow-path DIR]... [--allow-any-path] solidcraft-cli crashes [list [--json] | show | replay | dir | clear []] solidcraft-cli licences + solidcraft-cli gpu [--policy auto|hardware|software|cpu] + (the GPU adapters a headless render can open, best first, the one the policy picks and the tier it + lands on: gpu, gpu-software, or the CPU rasterizer (auto with no adapter, or cpu); the policy defaults + to SOLIDCRAFT_GPU, else auto; exits with an error when hardware or software finds no such adapter) solidcraft-cli icon --out icon.png [--size 256] | --out icon.ico "; @@ -75,6 +78,7 @@ fn main() -> ExitCode { Some("snapshot") => cmd_snapshot(&args[1..]), Some("render") => render::run(&args[1..]), Some("exec") => cmd_exec(&args[1..]), + Some("gpu") => cmd_gpu(&args[1..]), Some("commands") => { use std::io::Write as _; let mut s = Session::default(); @@ -213,6 +217,7 @@ fn print_json(v: &Value, file: Option<&str>) -> Result<(), String> { } fn cmd_run(args: &[String]) -> Result<(), String> { + install_renderer(); let json_out = json_out(args)?; let base = flag(args, "--in"); let path = positional(args); @@ -334,13 +339,59 @@ fn cmd_script(args: &[String]) -> Result<(), String> { Ok(()) } +/// `gpu`: the headless adapter survey and the policy's pick. +fn cmd_gpu(args: &[String]) -> Result<(), String> { + use solidcraft_gpu::select::{Policy, survey}; + let policy = match args { + [] => Policy::from_env()?, + [flag, v] if flag == "--policy" => Policy::parse(v).ok_or_else(|| format!("--policy must be auto, hardware, software or cpu, not `{v}`"))?, + _ => return Err("usage: solidcraft-cli gpu [--policy auto|hardware|software|cpu]".into()), + }; + let s = survey(policy); + let chosen = s.chosen.and_then(|i| s.adapters.get(i)).cloned(); + // The tier pictures land on: a hardware GPU, a software adapter, or the CPU rasterizer. + let renderer = s.lands_on.map(|l| l.renderer()); + println!( + "{}", + pretty(&json!({ + "policy": policy.name(), + "backends": s.backends, + "adapters": s.adapters, + "chosen": chosen, + "lands_on": s.lands_on, + "renderer": renderer, + })) + ); + match s.lands_on { + Some(solidcraft_gpu::select::Landing::Cpu) => { + eprintln!("warning: {}", solidcraft_engine::capture::CPU_WARNING); + Ok(()) + } + Some(_) => Ok(()), + None => Err(format!("no adapter qualifies under the {} policy", policy.name())), + } +} + +/// Draw this process's pictures (snapshots, MCP screenshots, saved thumbnails) on the GPU with the +/// viewport's pipelines: the headless device the `SOLIDCRAFT_GPU` policy picks, opened on the first +/// picture; under `auto` with no qualifying adapter (or `cpu`), the CPU rasterizer, and the +/// picture says so. Under `hardware` or `software` with no such adapter a picture fails with an +/// error that names the policy. +fn install_renderer() { + solidcraft_engine::capture::install(std::sync::Arc::new(|scene, cam, w, h| { + let (rgba, renderer) = solidcraft_gpu::capture::headless_rgba(scene, cam, w, h)?; + Ok(solidcraft_engine::capture::Picture { rgba, renderer }) + })); +} + fn cmd_snapshot(args: &[String]) -> Result<(), String> { + install_renderer(); known_flags("snapshot", args, &["--in", "--out", "--width", "--height", "--view", "--camera"], &["--no-grid", "--no-axes"])?; if positional(args).is_none() && flag(args, "--in").is_none() { return Err(USAGE.to_string()); } let out = flag(args, "--out").ok_or("snapshot needs --out FILE.png")?; - let size = |name: &str, default: usize| match flag(args, name) { + let size = |name: &str, default: u32| match flag(args, name) { None => Ok(default), Some(x) => x.parse().ok().filter(|n| (16..=8192).contains(n)).ok_or_else(|| format!("{name} must be 16 to 8192 pixels, not `{x}`")), }; @@ -364,9 +415,14 @@ fn cmd_snapshot(args: &[String]) -> Result<(), String> { let cam = s.camera.unwrap_or_else(|| solidcraft_engine::view::home_camera(&s)); let guides = Guides { grid: !args.iter().any(|a| a == "--no-grid"), axes: !args.iter().any(|a| a == "--no-axes") }; let scene = solidcraft_engine::view::scene_with_guides(&s, &cam, s.section, guides); - let png = render_png(&scene, &cam, w, h).ok_or("render failed")?; - std::fs::write(out, &png).map_err(|e| format!("{out}: {e}"))?; - println!("{}", pretty(&json!({"path": out, "width": w, "height": h, "bytes": png.len()}))); + let png = solidcraft_engine::capture::png(&scene, &cam, w, h)?; + std::fs::write(out, &png.bytes).map_err(|e| format!("{out}: {e}"))?; + let mut reply = json!({"path": out, "width": w, "height": h, "bytes": png.bytes.len(), "renderer": png.renderer}); + if let Some(w) = solidcraft_engine::capture::warning(png.renderer) { + eprintln!("warning: {w}"); + reply["warning"] = json!(w); + } + println!("{}", pretty(&reply)); Ok(()) } @@ -412,6 +468,7 @@ fn ico(images: &[(usize, Vec)]) -> Result, String> { } fn cmd_exec(args: &[String]) -> Result<(), String> { + install_renderer(); let id = args.first().ok_or_else(|| USAGE.to_string())?; let p: Value = match args.get(1) { Some(t) => serde_json::from_str(t).map_err(|e| format!("params: {e}"))?, @@ -427,6 +484,7 @@ fn cmd_exec(args: &[String]) -> Result<(), String> { /// a running app's control port. stdout carries only protocol messages. Files the agent's tool /// calls reach are confined to `solidcraft_mcp::agent_scope` unless `--allow-any-path` is given. fn cmd_mcp(args: &[String]) -> Result<(), String> { + install_renderer(); let scope = (!args.iter().any(|a| a == "--allow-any-path")) .then(|| solidcraft_mcp::agent_scope(flags(args, "--allow-path").into_iter().map(std::path::PathBuf::from))); if let Some(s) = &scope { diff --git a/apps/solidcraft-cli/tests/run_results.rs b/apps/solidcraft-cli/tests/run_results.rs index 5b805ad26..1da815e92 100644 --- a/apps/solidcraft-cli/tests/run_results.rs +++ b/apps/solidcraft-cli/tests/run_results.rs @@ -151,11 +151,20 @@ fn snapshot_runs_its_script_on_the_in_design() { json_output(cli().arg("snapshot").args(args).arg("--out").arg(&png).args(["--width", "64", "--height", "48"]).output().unwrap()); std::fs::read(&png).unwrap() }; - let alone = shot("alone.png", &[shifted.as_os_str()]); - let on_base = shot("on_base.png", &[shifted.as_os_str(), "--in".as_ref(), base.as_os_str()]); - let base_only = shot("base.png", &["--in".as_ref(), base.as_os_str()]); - assert_ne!(alone, on_base, "the script ran on the --in design"); - assert_ne!(base_only, on_base); + // Pictures are drawn on the GPU: without an adapter only the option checks below run. + match solidcraft_gpu::capture::shared() { + Ok(_) => { + let alone = shot("alone.png", &[shifted.as_os_str()]); + let on_base = shot("on_base.png", &[shifted.as_os_str(), "--in".as_ref(), base.as_os_str()]); + let base_only = shot("base.png", &["--in".as_ref(), base.as_os_str()]); + assert_ne!(alone, on_base, "the script ran on the --in design"); + assert_ne!(base_only, on_base); + } + Err(e @ solidcraft_gpu::GpuError::NoAdapter(_)) if std::env::var_os("SOLIDCRAFT_REQUIRE_GPU").is_none() => { + eprintln!("pictures left out: {e}") + } + Err(e) => panic!("{e}"), + } for (bad, says) in [(["--frobnicate", "1"], "doesn't take --frobnicate"), (["--width", "wide"], "--width must be 16 to 8192")] { let output = cli().arg("snapshot").arg(&base).arg("--out").arg(dir.0.join("x.png")).args(bad).output().unwrap(); assert_eq!(output.status.code(), Some(1)); diff --git a/apps/solidcraft-cli/tests/snapshot_camera.rs b/apps/solidcraft-cli/tests/snapshot_camera.rs index 8f70b1b53..69e4f89b7 100644 --- a/apps/solidcraft-cli/tests/snapshot_camera.rs +++ b/apps/solidcraft-cli/tests/snapshot_camera.rs @@ -1,6 +1,8 @@ //! `snapshot` frames its picture like the MCP `screenshot`: from a camera, a view saved in the //! design or one the script applies itself, and without the ground grid and the origin's axes -//! when asked (the grid lies on Z 0 and cuts through a part that straddles it). +//! when asked (the grid lies on Z 0 and cuts through a part that straddles it). Pictures are drawn +//! on the GPU and compared with a tolerance; without a GPU adapter the tests that draw are skipped +//! with the reason printed (`SOLIDCRAFT_REQUIRE_GPU=1` makes that a failure). use std::path::{Path, PathBuf}; use std::process::{Command, Output}; @@ -12,7 +14,52 @@ use solidcraft_mcp::{Headless, Server}; static NEXT: AtomicUsize = AtomicUsize::new(0); -const SIZE: (usize, usize) = (160, 100); +/// Whether pictures can be drawn here; installs the renderer the CLI installs, so the MCP +/// `screenshot` in this process draws as `solidcraft-cli mcp` does. +fn gpu() -> bool { + match solidcraft_gpu::capture::shared() { + Ok(c) => { + solidcraft_engine::capture::install(std::sync::Arc::new(move |scene, cam, w, h| { + c.rgba(scene, cam, w, h).map(|rgba| solidcraft_engine::capture::Picture { rgba, renderer: c.renderer() }).map_err(|e| e.to_string()) + })); + true + } + Err(e @ solidcraft_gpu::GpuError::NoAdapter(_)) if std::env::var_os("SOLIDCRAFT_REQUIRE_GPU").is_none() => { + eprintln!("skipping: {e}"); + false + } + Err(e) => panic!("{e}"), + } +} + +/// 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: GPU output may differ by a few levels or a stray edge pixel between drivers. +#[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 >= 20, "{what}: only {n} pixels differ"); +} + +const SIZE: (u32, u32) = (160, 100); fn camera() -> Value { json!({"target": [20, 0, 0], "yaw": 0.6, "pitch": 0.25, "distance": 100}) @@ -88,32 +135,38 @@ impl Drop for Scratch { /// not the home view the option used to be ignored for. #[test] fn a_camera_frames_the_picture_as_the_mcp_screenshot_does() { + if !gpu() { + return; + } let dir = Scratch::new(); let script = dir.script("part.json", &[]); let home = dir.snapshot(&script, "home.png", &[]); let json = camera().to_string(); let shot = dir.snapshot(&script, "camera.png", &["--camera", &json]); - assert_ne!(shot, home, "--camera was ignored"); - assert_eq!(shot, dir.mcp(&script, "mcp-camera.png", json!({"camera": camera()}))); + assert_differs(&shot, &home, "--camera was ignored"); + assert_same(&shot, &dir.mcp(&script, "mcp-camera.png", json!({"camera": camera()})), "the MCP screenshot"); // A perspective camera too, and a different eye gives a different picture. let mut near = camera(); near["fov"] = json!(0.6); let perspective = dir.snapshot(&script, "perspective.png", &["--camera", &near.to_string()]); - assert_ne!(perspective, shot); - assert_eq!(perspective, dir.mcp(&script, "mcp-perspective.png", json!({"camera": near}))); + assert_differs(&perspective, &shot, "perspective"); + assert_same(&perspective, &dir.mcp(&script, "mcp-perspective.png", json!({"camera": near})), "the MCP perspective screenshot"); } /// `--view` also takes a view saved in the design, which is the camera it was saved with; a /// standard view still looks as it did. #[test] fn a_saved_view_is_its_camera_and_a_standard_view_is_unchanged() { + if !gpu() { + return; + } let dir = Scratch::new(); let script = dir.script("part.json", &[]); let json = camera().to_string(); let by_camera = dir.snapshot(&script, "camera.png", &["--camera", &json]); let saved = dir.snapshot(&script, "saved.png", &["--view", "Detail"]); - assert_eq!(saved, by_camera); - assert_eq!(saved, dir.mcp(&script, "mcp-saved.png", json!({"view": "Detail"}))); + assert_same(&saved, &by_camera, "the saved view"); + assert_same(&saved, &dir.mcp(&script, "mcp-saved.png", json!({"view": "Detail"})), "the MCP saved view"); // A standard view frames the model from its direction, as before: the home camera turned. let top = dir.snapshot(&script, "top.png", &["--view", "top"]); let mut s = Session::default(); @@ -121,32 +174,38 @@ fn a_saved_view_is_its_camera_and_a_standard_view_is_unchanged() { let mut cam = solidcraft_engine::view::home_camera(&s); cam.set_view(solidcraft_engine::render::StandardView::Top); let scene = solidcraft_engine::view::scene(&s, &cam); - assert_eq!(top, solidcraft_engine::render::render_png(&scene, &cam, SIZE.0, SIZE.1).unwrap()); - assert_eq!(top, dir.mcp(&script, "mcp-top.png", json!({"view": "top"}))); - assert_ne!(top, saved); + assert_same(&top, &solidcraft_engine::capture::png(&scene, &cam, SIZE.0, SIZE.1).unwrap().bytes, "the home camera turned to the top"); + assert_same(&top, &dir.mcp(&script, "mcp-top.png", json!({"view": "top"})), "the MCP top view"); + assert_differs(&top, &saved, "top and the saved view"); let iso = dir.snapshot(&script, "iso.png", &["--view", "iso"]); - assert_eq!(iso, dir.snapshot(&script, "home.png", &[])); - assert_ne!(iso, top); + assert_same(&iso, &dir.snapshot(&script, "home.png", &[]), "iso is home"); + assert_differs(&iso, &top, "iso and top"); } /// A script that applies a view itself (as an MCP `execute` of `view.apply` does) sets the camera /// of its snapshot; `--view` and `--camera` still decide when given. #[test] fn a_script_can_carry_its_camera() { + if !gpu() { + return; + } let dir = Scratch::new(); let script = dir.script("carried.json", &[json!({"command": "view.apply", "params": {"camera": camera()}})]); let plain = dir.script("plain.json", &[]); let carried = dir.snapshot(&script, "carried.png", &[]); - assert_eq!(carried, dir.snapshot(&plain, "by-camera.png", &["--camera", &camera().to_string()])); - assert_ne!(carried, dir.snapshot(&plain, "home.png", &[])); + assert_same(&carried, &dir.snapshot(&plain, "by-camera.png", &["--camera", &camera().to_string()]), "the carried camera"); + assert_differs(&carried, &dir.snapshot(&plain, "home.png", &[]), "the carried camera and home"); let top = dir.snapshot(&script, "top.png", &["--view", "top"]); - assert_eq!(top, dir.snapshot(&plain, "plain-top.png", &["--view", "top"])); + assert_same(&top, &dir.snapshot(&plain, "plain-top.png", &["--view", "top"]), "--view decides"); } /// The grid and the axes each go when asked, and a render without both from any side shows the /// model alone: an empty design is then the same blank picture from every camera. #[test] fn the_grid_and_the_axes_can_be_left_out() { + if !gpu() { + return; + } let dir = Scratch::new(); let script = dir.script("part.json", &[]); let json = camera().to_string(); @@ -161,7 +220,7 @@ fn the_grid_and_the_axes_can_be_left_out() { let different = [&all, &no_grid, &no_axes, &bare]; for (i, a) in different.iter().enumerate() { for b in &different[i + 1..] { - assert_ne!(a, b, "{view:?}: two pictures are the same"); + assert_differs(a, b, &format!("{view:?}: two of the pictures")); } } // The same as the MCP's `grid` and `axes`. @@ -173,15 +232,151 @@ fn the_grid_and_the_axes_can_be_left_out() { a.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); dir.mcp(&script, out, a) }; - assert_eq!(no_grid, mcp(json!({"grid": false}), "mcp-no-grid.png")); - assert_eq!(no_axes, mcp(json!({"axes": false}), "mcp-no-axes.png")); - assert_eq!(bare, mcp(json!({"grid": false, "axes": false}), "mcp-bare.png")); + assert_same(&no_grid, &mcp(json!({"grid": false}), "mcp-no-grid.png"), "the MCP's grid: false"); + assert_same(&no_axes, &mcp(json!({"axes": false}), "mcp-no-axes.png"), "the MCP's axes: false"); + assert_same(&bare, &mcp(json!({"grid": false, "axes": false}), "mcp-bare.png"), "the MCP's bare picture"); } let empty = dir.0.join("empty.json"); std::fs::write(&empty, json!({"commands": []}).to_string()).unwrap(); let blank = |view: &str, out: &str| dir.snapshot(&empty, out, &["--view", view, "--no-grid", "--no-axes"]); - assert_eq!(blank("top", "blank-top.png"), blank("front", "blank-front.png")); - assert_ne!(blank("top", "blank-top.png"), dir.snapshot(&empty, "top.png", &["--view", "top"])); + assert_same(&blank("top", "blank-top.png"), &blank("front", "blank-front.png"), "blank from every side"); + assert_differs(&blank("top", "blank-top.png"), &dir.snapshot(&empty, "top.png", &["--view", "top"]), "blank and the grid"); +} + +/// A snapshot of a box shows its silhouette where the camera puts it: the pixels that differ +/// from an empty design's picture (same camera, no grid or axes) span the box's corners projected +/// to pixels, within the edge and silhouette lines' width. +#[test] +fn a_snapshot_shows_the_part_where_the_camera_puts_it() { + if !gpu() { + return; + } + let dir = Scratch::new(); + let part = dir.0.join("box.json"); + let empty = dir.0.join("empty.json"); + let corner = [10.0, -20.0, -15.0]; + let size = [60.0, 40.0, 30.0]; + std::fs::write( + &part, + json!({"commands": [{"command": "solid.box", "params": {"length": size[0], "width": size[1], "height": size[2], "corner": corner}}]}) + .to_string(), + ) + .unwrap(); + std::fs::write(&empty, json!({"commands": []}).to_string()).unwrap(); + for cam in [ + camera(), + json!({"target": [40, 0, 0], "yaw": 0.0, "pitch": 0.0, "distance": 160}), + json!({"target": [40, 0, 0], "yaw": -0.4, "pitch": 0.5, "distance": 150, "fov": 0.6}), + ] { + let args = ["--camera", &cam.to_string(), "--no-grid", "--no-axes"]; + let (_, _, with) = decode(&dir.snapshot(&part, "part.png", &args)); + let (_, _, without) = decode(&dir.snapshot(&empty, "empty.png", &args)); + // The part's pixels: where the picture differs from the empty one. + let (mut lo, mut hi) = ([u32::MAX; 2], [0u32; 2]); + for (i, (p, q)) in with.as_chunks::<4>().0.iter().zip(without.as_chunks::<4>().0).enumerate() { + if p.iter().zip(q.iter()).any(|(x, y)| x.abs_diff(*y) > 24) { + let (x, y) = (i as u32 % SIZE.0, i as u32 / SIZE.0); + lo = [lo[0].min(x), lo[1].min(y)]; + hi = [hi[0].max(x), hi[1].max(y)]; + } + } + assert!(lo[0] <= hi[0], "{cam}: the part is not in the picture"); + // Where the camera puts the corners. + let mut s = solidcraft_engine::Session::default(); + s.execute("view.apply", &json!({"camera": cam})).unwrap(); + let c = s.camera.unwrap(); + let vp = c.view_proj(f64::from(SIZE.0) / f64::from(SIZE.1), 1000.0); + let (mut elo, mut ehi) = ([f64::MAX; 2], [f64::MIN; 2]); + for k in 0..8 { + let p = solidcraft_engine::geom::Vec3::new( + corner[0] + size[0] * f64::from(k & 1), + corner[1] + size[1] * f64::from((k >> 1) & 1), + corner[2] + size[2] * f64::from((k >> 2) & 1), + ); + let q = vp.apply(p); + let (x, y) = ((q[0] / q[3] + 1.0) * 0.5 * f64::from(SIZE.0), (1.0 - q[1] / q[3]) * 0.5 * f64::from(SIZE.1)); + elo = [elo[0].min(x), elo[1].min(y)]; + ehi = [ehi[0].max(x), ehi[1].max(y)]; + } + let near = |got: u32, want: f64| (f64::from(got) - want).abs() <= 2.5; + assert!( + near(lo[0], elo[0]) && near(lo[1], elo[1]) && near(hi[0] + 1, ehi[0]) && near(hi[1] + 1, ehi[1]), + "{cam}: the part spans pixels {lo:?}..={hi:?}, its corners project to {elo:?}..{ehi:?}" + ); + } +} + +/// `snapshot` under a `SOLIDCRAFT_GPU` policy: its reply and stderr. +fn snapshot_under(dir: &Scratch, script: &Path, out: &str, policy: &str) -> Output { + Command::new(env!("CARGO_BIN_EXE_solidcraft-cli")) + .env("SOLIDCRAFT_GPU", policy) + .arg("snapshot") + .arg(script) + .arg("--out") + .arg(dir.0.join(out)) + .args(["--width", &SIZE.0.to_string(), "--height", &SIZE.1.to_string(), "--view", "top"]) + .output() + .unwrap() +} + +/// The last tier: `SOLIDCRAFT_GPU=cpu` draws with the CPU rasterizer whatever adapters there are, +/// says so (`renderer: cpu` and a warning that overlays are not drawn), and the picture is the +/// rasterizer's own. +#[test] +fn a_forced_cpu_snapshot_is_the_cpu_rasterizers_and_says_so() { + let dir = Scratch::new(); + let script = dir.script("part.json", &[]); + let output = snapshot_under(&dir, &script, "cpu.png", "cpu"); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(output.status.success(), "{stderr}"); + let reply: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(reply["renderer"], "cpu", "{reply}"); + assert!(reply["warning"].as_str().is_some_and(|w| w.contains("not drawn")), "{reply}"); + assert!(stderr.contains("CPU rasterizer"), "{stderr}"); + let mut s = Session::default(); + s.run_script(&serde_json::from_slice(&std::fs::read(&script).unwrap()).unwrap()).unwrap(); + let mut cam = solidcraft_engine::view::home_camera(&s); + cam.set_view(solidcraft_engine::render::StandardView::Top); + let scene = solidcraft_engine::view::scene(&s, &cam); + let cpu = solidcraft_engine::render::render_png(&scene, &cam, SIZE.0 as usize, SIZE.1 as usize).unwrap(); + assert_eq!(std::fs::read(dir.0.join("cpu.png")).unwrap(), cpu); +} + +/// `hardware` (and `software`) never fall to the CPU rasterizer: without such an adapter the +/// snapshot fails, naming the policy, and writes nothing; with one it says it was drawn on the GPU. +/// `auto` lands where `solidcraft-cli gpu` says it does. +#[test] +fn a_strict_policy_never_falls_to_the_cpu() { + let dir = Scratch::new(); + let script = dir.script("part.json", &[]); + let survey = |policy: &str| { + let o = Command::new(env!("CARGO_BIN_EXE_solidcraft-cli")).args(["gpu", "--policy", policy]).output().unwrap(); + (o.status.success(), serde_json::from_slice::(&o.stdout).unwrap_or(Value::Null)) + }; + for policy in ["hardware", "software"] { + let (found, report) = survey(policy); + let output = snapshot_under(&dir, &script, &format!("{policy}.png"), policy); + let stderr = String::from_utf8_lossy(&output.stderr); + if found { + assert!(output.status.success(), "{policy}: {stderr}"); + let reply: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(reply["renderer"], report["renderer"], "{policy}: {reply}"); + assert_ne!(reply["renderer"], "cpu"); + } else { + assert_eq!(report["lands_on"], Value::Null, "{policy}: {report}"); + assert_eq!(output.status.code(), Some(1), "{policy}: {stderr}"); + assert!(stderr.contains(&format!("`{policy}` policy")) && stderr.contains("solidcraft-cli gpu"), "{policy}: {stderr}"); + assert!(!dir.0.join(format!("{policy}.png")).exists()); + } + } + let (found, report) = survey("auto"); + assert!(found, "auto always lands somewhere: {report}"); + let output = snapshot_under(&dir, &script, "auto.png", "auto"); + assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr)); + let reply: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(reply["renderer"], report["renderer"], "{reply} vs {report}"); + let (_, cpu) = survey("cpu"); + assert_eq!((cpu["lands_on"].clone(), cpu["renderer"].clone()), (json!("cpu"), json!("cpu")), "{cpu}"); } #[test] diff --git a/apps/solidcraft-web/src/main.rs b/apps/solidcraft-web/src/main.rs index 555fe38c2..ad0cd8754 100644 --- a/apps/solidcraft-web/src/main.rs +++ b/apps/solidcraft-web/src/main.rs @@ -491,6 +491,8 @@ mod web { install_app: Some(crate::install::service(&cc.egui_ctx)), ..Default::default() }; + // Thumbnails of saves and start-page cards. + solidcraft_ui_egui::gpu::install_cpu_picture_renderer(); let mut app = SolveApp::new(Session::default(), services); if let Some(p) = cc.storage.and_then(|s| solidcraft_ui_egui::prefs::stored(|k| s.get_string(k))) { app.load_prefs(&p); diff --git a/apps/solidcraft/src/main.rs b/apps/solidcraft/src/main.rs index 0a43b95b5..bc55e8668 100644 --- a/apps/solidcraft/src/main.rs +++ b/apps/solidcraft/src/main.rs @@ -567,6 +567,7 @@ fn main() -> eframe::Result { eprintln!("SolidCraft graphics: {:?}, MSAA {}x (requested {}x)", rs.adapter.get_info().backend, rs.msaa_samples, samples); solidcraft_engine::crash::phase("viewport pipelines (shader compile)"); app.set_wgpu(rs, DEPTH_BITS, STENCIL_BITS, rs.msaa_samples); + solidcraft_ui_egui::gpu::install_picture_renderer(rs); // The graphics driver is loaded now; it may have put its own exception filter // in front of ours. #[cfg(target_os = "windows")] diff --git a/assets/styles/ui/palettes.rs b/assets/styles/ui/palettes.rs index d28cfd69c..2236e5ff6 100644 --- a/assets/styles/ui/palettes.rs +++ b/assets/styles/ui/palettes.rs @@ -93,12 +93,7 @@ impl Tokens { bend_up: Color32::from_rgb(30, 140, 50), bend_down: Color32::from_rgb(200, 90, 20), interference: Color32::from_rgb(235, 45, 40), - analysis: AnalysisColors { - draft: [[0.20, 0.75, 0.30], [0.95, 0.80, 0.15], [0.85, 0.22, 0.20]], - access: [[0.20, 0.75, 0.30], [0.85, 0.22, 0.20]], - curvature: [[0.15, 0.35, 0.95], [0.10, 0.80, 0.25], [0.90, 0.15, 0.10]], - hatch: false, - }, + analysis: AnalysisColors::DEFAULT, icons: IconColors { sheet: Color32::from_rgb(170, 200, 240), sheet_2: Color32::from_rgb(150, 185, 235), diff --git a/crates/engine/src/capture.rs b/crates/engine/src/capture.rs new file mode 100644 index 000000000..22d7b29da --- /dev/null +++ b/crates/engine/src/capture.rs @@ -0,0 +1,114 @@ +//! How headless pictures of the model are drawn: a renderer the host installs. The engine +//! describes what a picture shows ([`crate::view::scene`]); drawing it is a GPU job the engine +//! cannot do itself (the GPU crate sits above it), so the application, the CLI and the MCP +//! server install one ([`install`]) that draws with the viewport's own pipelines (or, as a last +//! resort the host chooses, the CPU rasterizer). Every picture names the renderer that drew it. +//! Without a renderer, a picture is an error and a save simply has no thumbnail. + +use std::sync::{Arc, RwLock}; + +use solidcraft_render::{Camera, Scene}; + +/// A picture: straight RGBA, rows top to bottom, and the renderer that drew it (`gpu`, +/// `gpu-software` or `cpu`). +pub struct Picture { + pub rgba: Vec, + pub renderer: &'static str, +} + +/// A picture as PNG bytes, and the renderer that drew it. +pub struct Png { + pub bytes: Vec, + pub renderer: &'static str, +} + +/// What a reply says when the CPU rasterizer drew the picture. +pub const CPU_WARNING: &str = "drawn by the CPU rasterizer (no GPU adapter qualified, or SOLIDCRAFT_GPU=cpu): surface analysis colours, highlights and legends are not drawn; `solidcraft-cli gpu` lists the adapters"; + +/// The warning that goes with a picture drawn by `renderer`, if any. +pub fn warning(renderer: &str) -> Option<&'static str> { + (renderer == "cpu").then_some(CPU_WARNING) +} + +/// Draws `scene` seen by `cam` at `width` × `height` pixels (`width * height * 4` bytes of RGBA), +/// or says why it could not. +pub type Renderer = dyn Fn(&Scene, &Camera, u32, u32) -> Result + Send + Sync; + +static RENDERER: RwLock>> = RwLock::new(None); + +/// Make `renderer` draw this process's headless pictures (replacing any installed before). +pub fn install(renderer: Arc) { + if let Ok(mut r) = RENDERER.write() { + *r = Some(renderer); + } +} + +/// The installed renderer, if any. +pub fn installed() -> Option> { + RENDERER.read().ok().and_then(|r| r.clone()) +} + +/// `scene` drawn by the installed renderer. +pub fn rgba(scene: &Scene, cam: &Camera, width: u32, height: u32) -> Result { + rgba_with(installed().as_deref(), scene, cam, width, height) +} + +/// `scene` drawn by the installed renderer, as PNG. +pub fn png(scene: &Scene, cam: &Camera, width: u32, height: u32) -> Result { + png_with(installed().as_deref(), scene, cam, width, height) +} + +/// [`rgba`] with `renderer` instead of the installed one. +pub fn rgba_with(renderer: Option<&Renderer>, scene: &Scene, cam: &Camera, width: u32, height: u32) -> Result { + let renderer = renderer.ok_or("no renderer is installed to draw pictures in this process")?; + let picture = renderer(scene, cam, width, height)?; + if picture.rgba.len() as u64 != u64::from(width) * u64::from(height) * 4 { + return Err(format!("the renderer returned {} bytes for {width} × {height} pixels", picture.rgba.len())); + } + if let Some(w) = warning(picture.renderer) { + log::warn!("{w}"); + } + Ok(picture) +} + +/// [`png`] with `renderer` instead of the installed one. +pub fn png_with(renderer: Option<&Renderer>, scene: &Scene, cam: &Camera, width: u32, height: u32) -> Result { + let Picture { rgba, renderer } = rgba_with(renderer, scene, cam, width, height)?; + let bytes = solidcraft_render::png(width as usize, height as usize, rgba).ok_or_else(|| "PNG encoding failed".to_string())?; + Ok(Png { bytes, renderer }) +} + +/// For tests: a stand-in for the renderer the hosts install, a flat picture whose first byte +/// counts the scene's meshes. +#[cfg(test)] +pub(crate) fn install_test_renderer() { + install(Arc::new(|scene: &Scene, _: &Camera, w: u32, h: u32| { + let mut rgba = vec![200; (w * h * 4) as usize]; + if let Some(first) = rgba.first_mut() { + *first = scene.meshes.len() as u8; + } + Ok(Picture { rgba, renderer: "gpu" }) + })); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn without_a_renderer_a_picture_is_an_error_not_a_crash() { + let e = png_with(None, &Scene::default(), &Camera::default(), 16, 16).err().unwrap(); + assert!(e.contains("no renderer"), "{e}"); + } + + #[test] + fn a_renderer_that_returns_the_wrong_size_is_an_error() { + let short: &Renderer = &|_, _, _, _| Ok(Picture { rgba: vec![0; 3], renderer: "gpu" }); + assert!(rgba_with(Some(short), &Scene::default(), &Camera::default(), 2, 2).is_err()); + let plain: &Renderer = &|_, _, w, h| Ok(Picture { rgba: vec![255; (w * h * 4) as usize], renderer: "cpu" }); + let png = png_with(Some(plain), &Scene::default(), &Camera::default(), 2, 2).unwrap(); + assert!(png.bytes.starts_with(b"\x89PNG")); + assert_eq!(png.renderer, "cpu"); + assert_eq!((warning("cpu"), warning("gpu"), warning("gpu-software")), (Some(CPU_WARNING), None, None)); + } +} diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 6a05824d2..78147187f 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -738,6 +738,8 @@ mod tests { #[test] fn save_and_save_as_require_explicit_native_cache_opt_in() { + // Thumbnails are drawn by the renderer the host installs. + crate::capture::install_test_renderer(); let mut session = Session::new(Document::new("Cache opt-in")); session.execute("solid.box", &json!({"length":10,"width":20,"height":30})).unwrap(); let world = session.world_state(); diff --git a/crates/engine/src/cmd/file_thumbnail.rs b/crates/engine/src/cmd/file_thumbnail.rs index b3c6aea5f..30c7f09ca 100644 --- a/crates/engine/src/cmd/file_thumbnail.rs +++ b/crates/engine/src/cmd/file_thumbnail.rs @@ -4,6 +4,15 @@ use solidcraft_geom::Aabb3; use solidcraft_render::{Camera, Rgb, Scene, SceneMesh, StandardView}; pub(super) fn saved(s: &Session) -> Option> { + let (scene, camera) = scene(s)?; + let [width, height] = solidcraft_io::THUMBNAIL_SIZE; + // Drawn by the renderer the host installed (the GPU); none installed, no thumbnail. + let renderer = crate::capture::installed()?; + crate::capture::png_with(Some(&*renderer), &scene, &camera, u32::try_from(width).ok()?, u32::try_from(height).ok()?).ok().map(|p| p.bytes) +} + +/// What the thumbnail shows: the shown bodies' warm display meshes in their colours, iso, fitted. +fn scene(s: &Session) -> Option<(Scene, Camera)> { if s.active_sketch.is_some() || !s.pending_moves.is_empty() || s.model.results.iter().any(|r| r.error.is_some()) { return None; } @@ -38,76 +47,16 @@ pub(super) fn saved(s: &Session) -> Option> { camera.distance *= 0.7; scene.radius = (bounds.diagonal() * 0.5).max(camera.half_height()).max(10.); scene.background = Some((crate::view::colors::BG_TOP, crate::view::colors::BG_BOTTOM)); - let [width, height] = solidcraft_io::THUMBNAIL_SIZE; - if !within_raster_budget(&scene, &camera, width, height) { - return None; - } - let image = solidcraft_render::render(&scene, &camera, width, height); - solidcraft_render::png(width, height, image.rgba) -} - -// Bound overlapping-triangle work too, not only mesh size. The renderer uses -// 2x supersampling; conservatively count each projected triangle's pixel box. -fn within_raster_budget(scene: &Scene, camera: &Camera, width: usize, height: usize) -> bool { - let (w, h) = ((width * 2) as f64, (height * 2) as f64); - let matrix = camera.view_proj(w / h, scene.radius.max(1.)); - let mut pixels = 0usize; - let mut colors = 0usize; - for entry in &scene.meshes { - colors = colors.saturating_add(entry.mesh.triangles.len().saturating_mul(entry.face_colors.len())); - if colors > 1_000_000 { - return false; - } - let mut projected = Vec::with_capacity(entry.mesh.positions.len()); - for point in &entry.mesh.positions { - let q = matrix.apply(*point); - if q.iter().any(|x| !x.is_finite()) || q[3] <= 1e-9 { - return false; - } - let pixel = [(q[0] / q[3] + 1.) * 0.5 * w, (1. - q[1] / q[3]) * 0.5 * h]; - if pixel.iter().any(|x| !x.is_finite()) { - return false; - } - projected.push(pixel); - } - for triangle in &entry.mesh.triangles { - let [Some(a), Some(b), Some(c)] = triangle.map(|i| projected.get(i as usize).copied()) else { - return false; - }; - let dx = (a[0].max(b[0]).max(c[0]).ceil().clamp(0., w) - a[0].min(b[0]).min(c[0]).floor().clamp(0., w) + 2.) as usize; - let dy = (a[1].max(b[1]).max(c[1]).ceil().clamp(0., h) - a[1].min(b[1]).min(c[1]).floor().clamp(0., h) + 2.) as usize; - pixels = pixels.saturating_add(dx.saturating_mul(dy)); - if pixels > 4_000_000 { - return false; - } - } - } - true + Some((scene, camera)) } #[cfg(test)] mod tests { use super::*; - #[test] - fn portable_thumbnail_refuses_excessive_overdraw() { - let mut session = Session::default(); - session.execute("solid.box", &serde_json::json!({"length":10,"width":20,"height":30})).unwrap(); - let mesh = session.world_state().bodies[0].mesh(); - let bounds = mesh.bounds(); - let mut camera = Camera::default(); - camera.set_view(StandardView::Iso); - camera.fit(&bounds); - let mut scene = Scene { radius: bounds.diagonal(), ..Scene::default() }; - scene.meshes.push(SceneMesh { mesh: mesh.clone(), color: Rgb(100, 100, 100), face_colors: vec![] }); - assert!(within_raster_budget(&scene, &camera, 240, 150)); - let mut repeated = (*mesh).clone(); - repeated.triangles = vec![repeated.triangles[0]; 100_000]; - scene.meshes[0].mesh = std::sync::Arc::new(repeated); - assert!(!within_raster_budget(&scene, &camera, 240, 150)); - } #[test] fn portable_thumbnail_preserves_saved_visibility() { + crate::capture::install_test_renderer(); let mut session = Session::default(); session.execute("solid.box", &serde_json::json!({"length":10,"width":20,"height":30,"body_name":"Visible"})).unwrap(); session.execute("solid.box", &serde_json::json!({"length":100,"width":100,"height":100,"body_name":"Hidden"})).unwrap(); @@ -116,6 +65,7 @@ mod tests { for body in &world.bodies { body.mesh(); } + assert_eq!(scene(&session).unwrap().0.meshes.len(), 1, "the hidden body is not in the picture"); let expected = saved(&session).unwrap(); let bytes = session.design_container(solidcraft_io::DesignCompression::Fast, false, true).unwrap(); let doc = solidcraft_io::read_design(&bytes).unwrap(); @@ -131,6 +81,7 @@ mod tests { #[test] fn portable_thumbnail_never_forces_cold_evaluation_or_meshing() { + crate::capture::install_test_renderer(); let mut session = Session::default(); session.execute("solid.box", &serde_json::json!({"length":10,"width":20,"height":30})).unwrap(); let world = session.world_state(); @@ -147,4 +98,17 @@ mod tests { let disabled = session.design_container(solidcraft_io::DesignCompression::Fast, false, false).unwrap(); assert!(solidcraft_io::read_design_thumbnail(&disabled).is_none()); } + + /// Without a renderer installed (a browser, a tool that draws nothing) a save has no + /// thumbnail and does not fail. + #[test] + fn without_a_renderer_a_save_has_no_thumbnail() { + let mut session = Session::default(); + session.execute("solid.box", &serde_json::json!({"length":10,"width":20,"height":30})).unwrap(); + for body in &session.world_state().bodies { + body.mesh(); + } + let (scene, camera) = scene(&session).unwrap(); + assert!(crate::capture::png_with(None, &scene, &camera, 240, 150).is_err()); + } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 8fc7f217d..c75ba9991 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -7,6 +7,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] +pub mod capture; pub mod cmd; pub mod control_auth; pub mod crash; @@ -290,6 +291,20 @@ pub enum SurfaceAnalysis { Access { dir: Vec3 }, } +impl SurfaceAnalysis { + /// How a picture shades the faces for this analysis. + pub fn mode(self) -> render::AnalysisMode { + use render::AnalysisMode as M; + match self { + SurfaceAnalysis::Zebra { stripes } => M::Zebra { stripes }, + SurfaceAnalysis::Draft { pull, angle } => M::Draft { pull, angle }, + SurfaceAnalysis::Curvature { radius } => M::Curvature { radius }, + SurfaceAnalysis::Environment => M::Environment, + SurfaceAnalysis::Access { dir } => M::Access { dir }, + } + } +} + const MAX_UNDO: usize = 200; /// Checkpoints kept (the oldest go first). const MAX_CHECKPOINTS: usize = 16; diff --git a/crates/engine/src/view.rs b/crates/engine/src/view.rs index 026ae0844..8a889ea1b 100644 --- a/crates/engine/src/view.rs +++ b/crates/engine/src/view.rs @@ -5,7 +5,7 @@ use std::sync::Arc; use solidcraft_geom::{Aabb3, Plane, Vec3}; -use solidcraft_render::{Camera, Rgb, Scene, SceneLine, SceneMesh}; +use solidcraft_render::{AnalysisColors, Camera, Rgb, Scene, SceneAnalysis, SceneLine, SceneMesh}; use solidcraft_sketch::Sketch; use crate::{Sel, Session}; @@ -68,6 +68,8 @@ pub struct Palette { pub axes: [Rgb; 3], /// What the section cap is tinted toward. pub cap: Rgb, + /// The surface analysis colours. + pub analysis: AnalysisColors, } impl Palette { @@ -89,6 +91,7 @@ impl Palette { sketch_centerline: colors::SKETCH_CENTERLINE, axes: [colors::AXIS_X, colors::AXIS_Y, colors::AXIS_Z], cap: colors::SECTION_CAP, + analysis: AnalysisColors::DEFAULT, }; } @@ -362,10 +365,17 @@ fn build_scene( ) -> Scene { let st = s.world_state(); let section = section.filter(|(o, n)| o.is_finite() && n.is_finite() && n.len() > 1e-9); - let mut sc = Scene { background: Some(p.background), clip: section.map(|(o, n)| (n, n.dot(o))), cap: Some(p.cap), ..Default::default() }; + let mut sc = Scene { + background: Some(p.background), + clip: section.map(|(o, n)| (n, n.dot(o))), + cap: Some(p.cap), + analysis: s.analysis.map(|a| SceneAnalysis { mode: a.mode(), colors: p.analysis }), + ..Default::default() + }; let b = bounds(s); sc.radius = (b.diagonal() * 0.5).max(cam.half_height()).max(10.0) + b.center().dist(cam.target); - // Grid on the ground plane (XY with Z up, XZ with Y up). + // Grid on the ground plane (XY with Z up, XZ with Y up), drawn under the model as in the + // viewport. if guides.grid { let (minor, major) = grid_step(cam.half_height()); let ext = (cam.half_height() * 3.0 / major).ceil() * major; @@ -375,19 +385,12 @@ fn build_scene( let n = ((ext / minor) as i64).clamp(1, 400); for i in -n..=n { let t = i as f64 * minor; - let col = if (t / major).fract().abs() < 1e-9 { p.grid_major } else { p.grid }; - sc.lines.push(SceneLine { - points: vec![w(c + Vec3::new(t, -ext, 0.0)), w(c + Vec3::new(t, ext, 0.0))], - color: col, - width: 0.6, - on_top: false, - }); - sc.lines.push(SceneLine { - points: vec![w(c + Vec3::new(-ext, t, 0.0)), w(c + Vec3::new(ext, t, 0.0))], - color: col, - width: 0.6, - on_top: false, - }); + let major_line = (t / major).fract().abs() < 1e-9; + let col = if major_line { p.grid_major } else { p.grid }; + // The viewport's widths (pixels). + let width = if major_line { 1.0 } else { 0.7 }; + sc.grid.push(SceneLine { points: vec![w(c + Vec3::new(t, -ext, 0.0)), w(c + Vec3::new(t, ext, 0.0))], color: col, width, on_top: false }); + sc.grid.push(SceneLine { points: vec![w(c + Vec3::new(-ext, t, 0.0)), w(c + Vec3::new(ext, t, 0.0))], color: col, width, on_top: false }); } } // The origin's axes, each unless hidden one by one (`browser.visibility`), as in the viewport. @@ -583,8 +586,8 @@ mod tests { use super::*; - /// The CPU renderer (snapshots) shows appearances as the viewport does: a body's colour and - /// faces with looks of their own. + /// Headless pictures show appearances as the viewport does: a body's colour and faces with + /// looks of their own (the picture itself: `solidcraft-gpu`'s capture tests). #[test] fn snapshot_scene_carries_appearances() { let mut s = Session::default(); @@ -596,9 +599,6 @@ mod tests { let sc = scene(&s, &cam); assert!(sc.meshes.iter().any(|m| m.color == Rgb(220, 60, 40))); assert!(sc.meshes.iter().any(|m| m.face_colors.iter().any(|(_, c)| *c == Rgb(40, 170, 80)))); - // And the rendered picture has the green top. - let img = solidcraft_render::render(&sc, &cam, 200, 140); - assert!(img.rgba.chunks(4).any(|p| p[1] > 120 && p[0] < 90 && p[2] < 110), "no green pixels"); } /// A render can leave out the ground grid and the origin's axes (a box straddling Z 0 is cut @@ -610,7 +610,7 @@ mod tests { let cam = home_camera(&s); let grid = [colors::GRID, colors::GRID_MAJOR]; let axes = [colors::AXIS_X, colors::AXIS_Y, colors::AXIS_Z]; - let count = |sc: &Scene, colours: &[Rgb]| sc.lines.iter().filter(|l| colours.contains(&l.color)).count(); + let count = |sc: &Scene, colours: &[Rgb]| sc.grid.iter().chain(&sc.lines).filter(|l| colours.contains(&l.color)).count(); let all = scene(&s, &cam); let (grid_lines, edges) = (count(&all, &grid), count(&all, &[colors::EDGE])); assert!(grid_lines > 20 && edges >= 12, "{grid_lines} grid lines, {edges} edges"); @@ -622,10 +622,7 @@ mod tests { let no_axes = render(Guides { grid: true, axes: false }); assert_eq!((count(&no_axes, &grid), count(&no_axes, &axes), count(&no_axes, &[colors::EDGE])), (grid_lines, 0, edges)); let bare = render(Guides { grid: false, axes: false }); - assert_eq!(bare.lines.len(), edges); - // The picture changes with each. - let png = |sc: &Scene| solidcraft_render::render_png(sc, &cam, 160, 100); - assert!(png(&all) != png(&no_grid) && png(&all) != png(&no_axes) && png(&no_grid) != png(&bare)); + assert_eq!((bare.lines.len(), bare.grid.len()), (edges, 0)); } /// An origin axis hidden with `browser.visibility` stays out of headless renders, as it does @@ -646,14 +643,43 @@ mod tests { s.execute("browser.visibility", &json!({"folder": "origin", "visible": false})).unwrap(); assert!(shown(&s).is_empty()); let sc = scene_with_guides(&s, &cam, None, Guides { grid: true, axes: true }); - assert!(sc.lines.iter().any(|l| l.color == colors::GRID), "the grid is not part of the origin"); + assert!(sc.grid.iter().any(|l| l.color == colors::GRID), "the grid is not part of the origin"); s.execute("browser.visibility", &json!({"folder": "origin", "visible": true})).unwrap(); assert_eq!(shown(&s), axes); } - /// Curved surfaces get a dark silhouette line in snapshots where they turn away. + /// A section cuts the headless scene: the clip plane and the cap colour, and the outline + /// where the plane cuts each body (the picture: `solidcraft-gpu`'s capture tests). #[test] - fn snapshots_draw_silhouettes_on_curved_surfaces() { + fn the_section_cuts_the_scene() { + let mut s = Session::default(); + s.execute("solid.box", &json!({"length": 40, "width": 30, "height": 20})).unwrap(); + let cam = home_camera(&s); + assert!(scene(&s, &cam).clip.is_none()); + s.execute("inspect.section", &json!({"plane": {"origin": [0, 15, 0], "normal": [0, -1, 0]}})).unwrap(); + let sc = scene(&s, &cam); + let (n, d) = sc.clip.unwrap(); + assert!((n - Vec3::new(0.0, -1.0, 0.0)).len() < 1e-12 && (d + 15.0).abs() < 1e-12, "{n:?} {d}"); + assert_eq!(sc.cap, Some(colors::SECTION_CAP)); + assert!(!section_segments(&s.world_state().bodies[0].mesh(), Vec3::new(0.0, 15.0, 0.0), -Vec3::Y).is_empty()); + } + + /// The surface analysis shades the headless scene too, in the palette's colours. + #[test] + fn the_surface_analysis_shades_the_scene() { + let mut s = Session::default(); + s.execute("solid.box", &json!({"length": 40, "width": 30, "height": 20})).unwrap(); + let cam = home_camera(&s); + assert!(scene(&s, &cam).analysis.is_none()); + s.analysis = Some(crate::SurfaceAnalysis::Curvature { radius: 5.0 }); + let a = scene(&s, &cam).analysis.unwrap(); + assert_eq!((a.mode, a.colors), (solidcraft_render::AnalysisMode::Curvature { radius: 5.0 }, Palette::DEFAULT.analysis)); + } + + /// The CPU rasterizer (the last tier of headless pictures, `SOLIDCRAFT_GPU=cpu` or no adapter + /// under `auto`): curved surfaces get a dark silhouette line where they turn away. + #[test] + fn cpu_pictures_draw_silhouettes_on_curved_surfaces() { let mut s = Session::default(); s.execute("solid.sphere", &json!({"diameter": 20})).unwrap(); let cam = home_camera(&s); @@ -662,9 +688,9 @@ mod tests { assert!(dark > 40, "silhouette pixels: {dark}"); } - /// A section shows in snapshots: the cut part is gone and the cut face is drawn. + /// The CPU rasterizer: a section shows; the cut part is gone and the cut face is drawn. #[test] - fn snapshots_show_the_section() { + fn cpu_pictures_show_the_section() { let mut s = Session::default(); s.execute("solid.box", &json!({"length": 40, "width": 30, "height": 20})).unwrap(); let cam = home_camera(&s); @@ -681,7 +707,7 @@ mod tests { /// plane's depth, not on the far wall like a pane of glass), shows in the cap colour, and /// the cut's outline is drawn. #[test] - fn snapshot_section_caps_hide_the_inside() { + fn cpu_picture_section_caps_hide_the_inside() { let mut s = Session::default(); s.execute("solid.box", &json!({"length": 40, "width": 30, "height": 20})).unwrap(); // Cut away the front half (y < 15), so the iso camera looks into the cut. diff --git a/crates/engine/src/view_palette_tests.rs b/crates/engine/src/view_palette_tests.rs index 0d65b9b08..31d7fdfed 100644 --- a/crates/engine/src/view_palette_tests.rs +++ b/crates/engine/src/view_palette_tests.rs @@ -24,6 +24,12 @@ const MARK: Palette = Palette { sketch_centerline: Rgb(43, 44, 45), axes: [Rgb(46, 47, 48), Rgb(49, 50, 51), Rgb(52, 53, 54)], cap: Rgb(55, 56, 57), + analysis: solidcraft_render::AnalysisColors { + draft: [[0.1, 0.2, 0.3], [0.4, 0.5, 0.6], [0.7, 0.8, 0.9]], + access: [[0.11, 0.12, 0.13], [0.14, 0.15, 0.16]], + curvature: [[0.17, 0.18, 0.19], [0.21, 0.22, 0.23], [0.24, 0.25, 0.26]], + hatch: true, + }, }; /// Each curve's lines at x = its index, so a line tells which curve it draws. @@ -49,6 +55,7 @@ fn the_default_palette_is_the_colour_table() { (colors::SKETCH_PROJECTED, colors::SKETCH_LOST, colors::SKETCH_CONSTRUCTION, colors::SKETCH_CENTERLINE) ); assert_eq!((p.axes, p.cap), ([colors::AXIS_X, colors::AXIS_Y, colors::AXIS_Z], colors::SECTION_CAP)); + assert_eq!(p.analysis, solidcraft_render::AnalysisColors::DEFAULT); } #[test] @@ -154,11 +161,13 @@ fn every_scene_colour_comes_from_its_palette_and_appearances_stay() { MARK.sketch_construction, MARK.sketch_centerline, ]; - let stray: Vec = marked.lines.iter().map(|l| l.color).filter(|c| !allowed.contains(c)).collect(); + let all_lines = || marked.grid.iter().chain(&marked.lines); + let stray: Vec = all_lines().map(|l| l.color).filter(|c| !allowed.contains(c)).collect(); assert!(stray.is_empty(), "line colours not from the palette: {stray:?}"); for want in [MARK.grid, MARK.grid_major, MARK.edge, MARK.axes[0], MARK.axes[1], MARK.axes[2], MARK.sketch_done] { - assert!(marked.lines.iter().any(|l| l.color == want), "no line in {want:?}"); + assert!(all_lines().any(|l| l.color == want), "no line in {want:?}"); } + assert!(marked.grid.iter().all(|l| [MARK.grid, MARK.grid_major].contains(&l.color)), "only the grid is drawn under the model"); assert_eq!(mesh(&marked, "Grey").0, colors::BODY, "an appearance equal to the default grey is the design's"); assert_eq!(mesh(&marked, "Picked").0, MARK.body_selected); let (plain, faces) = mesh(&marked, "Plain"); @@ -172,8 +181,8 @@ fn every_scene_colour_comes_from_its_palette_and_appearances_stay() { (default.background, default.cap, default.clip, default.radius), (plain_scene.background, plain_scene.cap, plain_scene.clip, plain_scene.radius) ); - assert_eq!(default.lines.len(), plain_scene.lines.len()); - for (a, b) in default.lines.iter().zip(&plain_scene.lines) { + assert_eq!((default.lines.len(), default.grid.len()), (plain_scene.lines.len(), plain_scene.grid.len())); + for (a, b) in default.lines.iter().zip(&plain_scene.lines).chain(default.grid.iter().zip(&plain_scene.grid)) { assert_eq!((&a.points, a.color, a.width, a.on_top), (&b.points, b.color, b.width, b.on_top)); } for name in &names { diff --git a/crates/gpu/Cargo.toml b/crates/gpu/Cargo.toml index 077909c4c..b8bc671f4 100644 --- a/crates/gpu/Cargo.toml +++ b/crates/gpu/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "solidcraft-gpu" -description = "SolidCraft GPU compute: evaluates display tessellation plans (surface points and normals) in a compute shader" +description = "SolidCraft GPU rendering: the viewport's render pipelines, offscreen captures, and display tessellation plans evaluated in a compute shader" version.workspace = true edition.workspace = true license.workspace = true @@ -10,9 +10,11 @@ workspace = true [dependencies] solidcraft-geom = { workspace = true } +solidcraft-render = { workspace = true } wgpu = { workspace = true } log = { workspace = true } thiserror = { workspace = true } +serde = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] pollster = { workspace = true } @@ -21,5 +23,8 @@ wgpu = { workspace = true, features = ["metal", "vulkan", "dx12", "gles"] } [dev-dependencies] solidcraft-kernel = { workspace = true } +# Headless pictures of real designs (capture tests). +solidcraft-engine = { workspace = true } +serde_json = { workspace = true } # The HLSL the D3D12 backend compiles (tests check it suits FXC). naga = { workspace = true, features = ["wgsl-in", "hlsl-out"] } diff --git a/crates/gpu/src/capture.rs b/crates/gpu/src/capture.rs new file mode 100644 index 000000000..07d4e1b97 --- /dev/null +++ b/crates/gpu/src/capture.rs @@ -0,0 +1,428 @@ +//! Pictures of a [`Scene`] drawn offscreen with the viewport's pipelines ([`crate::view`]): the +//! same shading, edges, silhouettes, section cap and surface analysis the viewport shows, read +//! back as RGBA. `solidcraft-cli snapshot`, MCP screenshots, `ui.render` and thumbnails draw +//! through it, on the application's device ([`Capturer::new`]) or on a headless one +//! ([`Capturer::headless`], [`shared`]). Without a qualifying adapter, the `auto` policy falls +//! to the last tier, the CPU rasterizer ([`headless_rgba`]), and says so: every picture names the +//! renderer that drew it (`gpu`, `gpu-software` or `cpu`); `hardware` and `software` fail with an +//! error that names the policy. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +use solidcraft_geom::Vec3; +use solidcraft_render::{AnalysisMode, Camera, Rgb, SECTION_CAP, Scene}; +use wgpu::util::DeviceExt; + +use crate::view::{AccessMap, Frame, GpuScene, GpuTarget, Renderer, analysis_colors, analysis_uniform}; +use crate::{GpuError, Result, popped}; + +/// The colour format pictures are drawn in: sRGB bytes as they are, like the viewport's usual +/// (non-sRGB) target. +pub const FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm; +const DEPTH: wgpu::TextureFormat = wgpu::TextureFormat::Depth24PlusStencil8; +/// Samples per pixel (MSAA), as the desktop viewport's default; 1 where the device has no 4×. +pub const SAMPLES: u32 = 4; +/// The largest picture side (pixels); the device's texture limit may lower it. +pub const MAX_SIDE: u32 = 8192; +/// The background of a scene without one of its own: the light theme's viewport gradient. +const BACKGROUND: (Rgb, Rgb) = (Rgb(236, 240, 245), Rgb(205, 212, 222)); +/// How long a picture may take on the GPU before it is given up. +const TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60); + +/// The viewport's pipelines on one device, drawing pictures offscreen. Pictures are drawn one at +/// a time (callers on several threads take turns). +pub struct Capturer { + device: wgpu::Device, + queue: wgpu::Queue, + adapter: String, + /// The adapter is a GPU driver running on the CPU (llvmpipe, lavapipe, WARP). + software: bool, + samples: u32, + max_side: u32, + state: Mutex, +} + +struct State { + renderer: Renderer, + background: wgpu::RenderPipeline, + /// The last picture's scene key and accessibility map version (each picture uploads anew). + key: u64, + access_version: u64, +} + +impl Capturer { + /// The pipelines on an existing device (the application's). + pub fn new(adapter: &wgpu::Adapter, device: wgpu::Device, queue: wgpu::Queue) -> 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 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); + caught(scopes).map_or(Ok(()), |e| Err(GpuError::Pipeline(e)))?; + let max_side = device.limits().max_texture_dimension_2d.min(MAX_SIDE); + Ok(Capturer { + adapter: adapter.get_info().name, + software: adapter.get_info().device_type == wgpu::DeviceType::Cpu, + samples, + max_side, + state: Mutex::new(State { renderer, background, key: 0, access_version: 0 }), + device, + queue, + }) + } + + /// A device of its own, without a window (native only): the adapter the `SOLIDCRAFT_GPU` + /// policy picks ([`crate::select`]). + #[cfg(not(target_arch = "wasm32"))] + pub fn headless() -> Result { + let (adapter, device, queue) = crate::open_headless()?; + // Errors are caught per picture (error scopes); anything else is logged, never a panic. + device.on_uncaptured_error(Arc::new(|e: wgpu::Error| log::error!("GPU: {e}"))); + Self::new(&adapter, device, queue) + } + + /// The adapter's name. + pub fn adapter_name(&self) -> &str { + &self.adapter + } + + /// What a picture's reply names as its renderer: `gpu`, or `gpu-software` on a software + /// adapter. + pub fn renderer(&self) -> &'static str { + if self.software { "gpu-software" } else { "gpu" } + } + + /// Samples per pixel the pictures are drawn with. + pub fn samples(&self) -> u32 { + self.samples + } + + /// `scene` seen by `cam`, `width` × `height` pixels: straight RGBA, rows top to bottom. + pub fn rgba(&self, scene: &Scene, cam: &Camera, width: u32, height: u32) -> Result> { + if !(1..=self.max_side).contains(&width) || !(1..=self.max_side).contains(&height) { + return Err(GpuError::Render(format!("a picture is 1 to {} pixels a side, not {width} × {height}", self.max_side))); + } + let mut state = self.state.lock().map_err(|_| GpuError::Render("an earlier picture failed on this device".into()))?; + let state = &mut *state; + state.key = state.key.wrapping_add(1); + let mode = scene.analysis.map(|a| a.mode); + let access = match mode { + Some(AnalysisMode::Access { dir }) => { + state.access_version = state.access_version.wrapping_add(1); + AccessMap::build(&scene.meshes.iter().map(|m| m.mesh.as_ref()).collect::>(), dir, state.access_version) + } + _ => None, + }; + let frame = frame(scene, cam, [width, height], state.key, access); + let (device, queue) = (&self.device, &self.queue); + let scopes = error_scopes(device); + let size = wgpu::Extent3d { width, height, depth_or_array_layers: 1 }; + let texture = |label: &str, format: wgpu::TextureFormat, samples: u32, usage: wgpu::TextureUsages| { + device.create_texture(&wgpu::TextureDescriptor { + label: Some(label), + size, + mip_level_count: 1, + sample_count: samples, + dimension: wgpu::TextureDimension::D2, + format, + usage, + view_formats: &[], + }) + }; + let resolved = texture("sc_capture", FORMAT, 1, wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC); + let multisampled = (self.samples > 1).then(|| texture("sc_capture_ms", FORMAT, self.samples, wgpu::TextureUsages::RENDER_ATTACHMENT)); + let depth = texture("sc_capture_depth", DEPTH, self.samples, wgpu::TextureUsages::RENDER_ATTACHMENT); + let (resolved_view, depth_view) = (resolved.create_view(&Default::default()), depth.create_view(&Default::default())); + let multisampled_view = multisampled.as_ref().map(|t| t.create_view(&Default::default())); + let (top, bottom) = scene.background.unwrap_or(BACKGROUND); + let background = background_vertices(device, top, bottom); + let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("sc_capture") }); + state.renderer.prepare(device, queue, &mut encoder, &frame); + { + let (view, resolve_target, store) = match &multisampled_view { + Some(ms) => (ms, Some(&resolved_view), wgpu::StoreOp::Discard), + None => (&resolved_view, None, wgpu::StoreOp::Store), + }; + let mut pass = encoder + .begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("sc_capture"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view, + depth_slice: None, + resolve_target, + ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), store }, + })], + depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { + view: &depth_view, + depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(1.0), store: wgpu::StoreOp::Discard }), + stencil_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(0), store: wgpu::StoreOp::Discard }), + }), + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }) + .forget_lifetime(); + // The background first, as the viewport paints it before the model. + pass.set_pipeline(&state.background); + pass.set_vertex_buffer(0, background.slice(..)); + pass.draw(0..6, 0..1); + state.renderer.paint(&frame, &mut pass, [0.0, 0.0, width as f32, height as f32]); + } + let row = width * 4; + let padded = row.div_ceil(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT) * wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; + let read = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("sc_capture_read"), + size: u64::from(padded) * u64::from(height), + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + encoder.copy_texture_to_buffer( + resolved.as_image_copy(), + wgpu::TexelCopyBufferInfo { + buffer: &read, + layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(padded), rows_per_image: Some(height) }, + }, + size, + ); + let submission = queue.submit([encoder.finish()]); + if let Some(e) = caught(scopes) { + return Err(GpuError::Render(e)); + } + let slice = read.slice(..); + let (tx, rx) = std::sync::mpsc::channel(); + slice.map_async(wgpu::MapMode::Read, move |r| { + let _ = tx.send(r); + }); + device + .poll(wgpu::PollType::Wait { submission_index: Some(submission), timeout: Some(TIMEOUT) }) + .map_err(|e| GpuError::Render(format!("waiting for the picture: {e}")))?; + match rx.try_recv() { + Ok(Ok(())) => {} + Ok(Err(e)) => return Err(GpuError::Render(format!("reading the picture back: {e}"))), + Err(_) => return Err(GpuError::Unsupported("reading a picture back without waiting for the browser".into())), + } + let data = slice.get_mapped_range().map_err(|e| GpuError::Render(format!("reading the picture back: {e}")))?; + let mut rgba = Vec::with_capacity((row as usize) * (height as usize)); + for r in data.chunks(padded as usize).take(height as usize) { + rgba.extend_from_slice(r.get(..row as usize).unwrap_or_default()); + } + if rgba.len() != (row as usize) * (height as usize) { + return Err(GpuError::Render("the picture read back short".into())); + } + Ok(rgba) + } + + /// [`Capturer::rgba`] as PNG bytes. + pub fn png(&self, scene: &Scene, cam: &Camera, width: u32, height: u32) -> Result> { + let rgba = self.rgba(scene, cam, width, height)?; + solidcraft_render::png(width as usize, height as usize, rgba).ok_or_else(|| GpuError::Render("PNG encoding failed".into())) + } +} + +/// The process's headless capturer (native only), opened on first use under the `SOLIDCRAFT_GPU` +/// policy and kept; the error when no adapter qualifies or the device fails (not retried). +#[cfg(not(target_arch = "wasm32"))] +pub fn shared() -> std::result::Result<&'static Capturer, &'static GpuError> { + static SHARED: std::sync::OnceLock> = std::sync::OnceLock::new(); + SHARED.get_or_init(Capturer::headless).as_ref() +} + +/// What draws this process's headless pictures (native only): the shared headless device, or the +/// CPU rasterizer where the `SOLIDCRAFT_GPU` policy lands there (`cpu`, or `auto` with no +/// qualifying adapter). +#[cfg(not(target_arch = "wasm32"))] +pub enum Headless { + Gpu(&'static Capturer), + Cpu, +} + +/// [`Headless`] under the `SOLIDCRAFT_GPU` policy; an error when the policy is `hardware` or +/// `software` and no adapter of that tier opens (or the variable names no policy). +#[cfg(not(target_arch = "wasm32"))] +pub fn headless() -> std::result::Result { + use crate::select::Policy; + let policy = Policy::from_env()?; + if policy == Policy::Cpu { + return Ok(Headless::Cpu); + } + match shared() { + Ok(c) => Ok(Headless::Gpu(c)), + Err(e) if policy == Policy::Auto => { + log::warn!("pictures are drawn by the CPU rasterizer: {e}"); + Ok(Headless::Cpu) + } + Err(e) => Err(e.to_string()), + } +} + +/// `scene` drawn by [`headless`]: straight RGBA and the renderer that drew it (`gpu`, +/// `gpu-software` or `cpu`). The CPU rasterizer draws no surface analysis, highlights or legends. +#[cfg(not(target_arch = "wasm32"))] +pub fn headless_rgba(scene: &Scene, cam: &Camera, width: u32, height: u32) -> std::result::Result<(Vec, &'static str), String> { + match headless()? { + Headless::Gpu(c) => c.rgba(scene, cam, width, height).map(|rgba| (rgba, c.renderer())).map_err(|e| e.to_string()), + Headless::Cpu => { + if !(1..=MAX_SIDE).contains(&width) || !(1..=MAX_SIDE).contains(&height) { + return Err(format!("a picture is 1 to {MAX_SIDE} pixels a side, not {width} × {height}")); + } + let canvas = solidcraft_render::render(scene, cam, width as usize, height as usize); + Ok((canvas.rgba, "cpu")) + } + } +} + +/// The frame parameters of a picture: the scene's own geometry as the model scene (key `key`), +/// the camera, the section, the analysis, and the silhouette outlines of the default visual style. +fn frame(scene: &Scene, cam: &Camera, [width, height]: [u32; 2], key: u64, access: Option) -> Frame { + let empty = || Arc::new(Mutex::new(None)); + let eye = cam.eye().to_f32(); + let cap = scene.cap.unwrap_or(SECTION_CAP); + let mode = scene.analysis.map(|a| a.mode); + Frame { + product: false, + key, + slot: Arc::new(Mutex::new(Some(scene_geometry(scene)))), + sketch_key: 0, + sketch_slot: empty(), + hl_key: 0, + hl_slot: empty(), + pv_key: 0, + pv_slot: empty(), + 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], + clip: scene.clip.map_or([0.0; 4], |(n, d)| [n.x as f32, n.y as f32, n.z as f32, d as f32]), + cap: [f32::from(cap.0) / 255.0, f32::from(cap.1) / 255.0, f32::from(cap.2) / 255.0, 1.0], + images: Vec::new(), + analysis: analysis_uniform(mode, access.as_ref()), + analysis_colors: scene.analysis.map_or([0.0; 36], |a| analysis_colors(&a.colors)), + access, + outline: true, + eye: [eye[0], eye[1], eye[2], if cam.fov > 0.0 { 1.0 } else { 0.0 }], + ssaa: 1.0, + } +} + +/// 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. +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 faces: HashMap = m.face_colors.iter().copied().collect(); + let mesh = &m.mesh; + for (ti, t) in mesh.triangles.iter().enumerate() { + let col = c4(mesh.tri_face.get(ti).and_then(|f| faces.get(f)).copied().unwrap_or(m.color)); + let [Some(a), Some(b), Some(c)] = t.map(|k| mesh.positions.get(k as usize).copied()) else { continue }; + 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); + } + } + } + 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); + } + } + for l in &scene.lines { + for w in l.points.windows(2) { + sc.line(w[0].to_f32(), w[1].to_f32(), c4(l.color), l.width as f32, l.on_top); + } + } + sc +} + +/// Error scopes catching what a picture's GPU work may raise (popped by [`caught`]). +fn error_scopes(device: &wgpu::Device) -> [wgpu::ErrorScopeGuard; 3] { + [wgpu::ErrorFilter::OutOfMemory, wgpu::ErrorFilter::Internal, wgpu::ErrorFilter::Validation].map(|f| device.push_error_scope(f)) +} + +/// The first error the scopes caught. +fn caught(scopes: [wgpu::ErrorScopeGuard; 3]) -> Option { + let mut failed = None; + for scope in scopes.into_iter().rev() { + if let Some(e) = popped(scope.pop()) { + failed.get_or_insert(e.to_string()); + } + } + failed +} + +/// The background gradient: the viewport's top colour at the top, its bottom one at the bottom, +/// mixed in sRGB as the window paints it. +const BACKGROUND_SHADER: &str = r#" +struct O { @builtin(position) pos: vec4, @location(0) color: vec4 }; +@vertex +fn vs(@location(0) p: vec2, @location(1) c: vec4) -> O { + var o: O; + o.pos = vec4(p, 0.0, 1.0); + o.color = c; + return o; +} +@fragment +fn fs(i: O) -> @location(0) vec4 { + return i.color; +} +"#; + +/// Background vertex: NDC position (2 × f32) and sRGB colour (4 × u8). +const BACKGROUND_VERTEX: u64 = 12; + +fn background_vertices(device: &wgpu::Device, top: Rgb, bottom: Rgb) -> wgpu::Buffer { + let mut bytes = Vec::with_capacity(6 * BACKGROUND_VERTEX as usize); + let corner = |x: f32, y: f32| (x, y, if y > 0.0 { top } else { bottom }); + for (x, y, c) in [corner(-1.0, 1.0), corner(1.0, 1.0), corner(1.0, -1.0), corner(-1.0, 1.0), corner(1.0, -1.0), corner(-1.0, -1.0)] { + bytes.extend_from_slice(&x.to_le_bytes()); + bytes.extend_from_slice(&y.to_le_bytes()); + bytes.extend_from_slice(&[c.0, c.1, c.2, 255]); + } + device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("sc_capture_background"), + contents: &bytes, + usage: wgpu::BufferUsages::VERTEX, + }) +} + +fn background_pipeline(device: &wgpu::Device, samples: u32) -> wgpu::RenderPipeline { + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("sc_capture_background"), + source: wgpu::ShaderSource::Wgsl(BACKGROUND_SHADER.into()), + }); + let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("sc_capture_background"), + bind_group_layouts: &[], + immediate_size: 0, + }); + const A: [wgpu::VertexAttribute; 2] = wgpu::vertex_attr_array![0 => Float32x2, 1 => Unorm8x4]; + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("sc_capture_background"), + layout: Some(&layout), + vertex: wgpu::VertexState { + module: &module, + entry_point: Some("vs"), + buffers: &[Some(wgpu::VertexBufferLayout { array_stride: BACKGROUND_VERTEX, step_mode: wgpu::VertexStepMode::Vertex, attributes: &A })], + compilation_options: Default::default(), + }, + primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() }, + depth_stencil: Some(wgpu::DepthStencilState { + format: DEPTH, + depth_write_enabled: Some(false), + depth_compare: Some(wgpu::CompareFunction::Always), + stencil: Default::default(), + bias: Default::default(), + }), + multisample: wgpu::MultisampleState { count: samples, mask: !0, alpha_to_coverage_enabled: false }, + fragment: Some(wgpu::FragmentState { + module: &module, + entry_point: Some("fs"), + targets: &[Some(wgpu::ColorTargetState { format: FORMAT, blend: None, write_mask: wgpu::ColorWrites::ALL })], + compilation_options: Default::default(), + }), + multiview_mask: None, + cache: None, + }) +} diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index e069db061..98f4515a8 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -1,7 +1,9 @@ -//! GPU evaluation of display tessellation plans: the surface point and normal at every -//! vertex's parameters, in a compute shader (`tess.wgsl`), the GPU twin of -//! [`TessPlan::evaluate`]. Shared edge nodes keep their exact positions, so faces still meet -//! exactly; evaluation runs in f32. +//! SolidCraft's GPU work: the viewport's render pipelines ([`view`]), pictures drawn with them +//! offscreen ([`capture`]), and display tessellation plans evaluated in a compute shader. +//! +//! Plan evaluation: the surface point and normal at every vertex's parameters, in a compute +//! shader (`tess.wgsl`), the GPU twin of [`TessPlan::evaluate`]. Shared edge nodes keep their +//! exact positions, so faces still meet exactly; evaluation runs in f32. //! //! Use [`TessGpu::new`] with the application's device, or [`TessGpu::headless`] (native only) //! to open one without a window, as the CLI and tests do. A viewport draws a plan straight from @@ -17,6 +19,12 @@ use solidcraft_geom::Vec3; use solidcraft_geom::tess::{EvalCurve, EvalSurface, TessPlan}; use wgpu::util::DeviceExt; +pub mod capture; +mod pbr; +#[cfg(not(target_arch = "wasm32"))] +pub mod select; +pub mod view; + /// The tessellation compute shader (WGSL). pub const SHADER: &str = include_str!("tess.wgsl"); @@ -30,17 +38,15 @@ fn popped(f: impl std::future::Future>) -> Option Result<(wgpu::Adapter, wgpu::Device, wgpu::Queue)> { - let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env()); - let adapter = pollster::block_on( - instance.request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() }), - ) - .map_err(|_| GpuError::NoAdapter)?; + let policy = select::Policy::from_env().map_err(GpuError::Policy)?; + let (adapter, _) = select::pick(policy).ok_or(GpuError::NoAdapter(policy.name()))?; let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { - label: Some("solidcraft compute"), + label: Some("solidcraft headless"), required_limits: wgpu::Limits::downlevel_defaults().using_resolution(adapter.limits()), ..Default::default() })) @@ -54,12 +60,16 @@ const WORKGROUP: u32 = 64; #[derive(Debug, thiserror::Error)] pub enum GpuError { - #[error("no GPU adapter is available")] - NoAdapter, + #[error("no GPU adapter qualifies under the `{0}` policy (SOLIDCRAFT_GPU); `solidcraft-cli gpu` lists the adapters this machine offers")] + NoAdapter(&'static str), + #[error("{0}")] + Policy(String), #[error("the GPU device could not be opened: {0}")] Device(String), #[error("the GPU evaluation failed: {0}")] Failed(String), + #[error("the GPU render failed: {0}")] + Render(String), #[error("the GPU tessellation pipeline could not be created: {0}")] Pipeline(String), #[error("not supported yet: {0}")] diff --git a/crates/ui-egui/src/pbr_gpu.rs b/crates/gpu/src/pbr.rs similarity index 100% rename from crates/ui-egui/src/pbr_gpu.rs rename to crates/gpu/src/pbr.rs diff --git a/crates/gpu/src/select.rs b/crates/gpu/src/select.rs new file mode 100644 index 000000000..c7a1559fc --- /dev/null +++ b/crates/gpu/src/select.rs @@ -0,0 +1,261 @@ +//! What draws a headless picture: every adapter the platform's native backends offer is +//! classified as hardware (a discrete, integrated or virtual GPU) or software (a GPU driver that +//! runs on the CPU, such as llvmpipe, lavapipe or WARP), and a [`Policy`] picks one. The last +//! tier, below any adapter, is SolidCraft's own CPU rasterizer (no surface analysis, highlights +//! or legends): `auto` lands there only when no adapter qualifies, `cpu` forces it, `hardware` +//! and `software` never use it. macOS uses Metal only, and has no software adapter. `SOLIDCRAFT_GPU` +//! (`auto`, `hardware`, `software`, `cpu`) sets the policy from the environment; `WGPU_BACKEND` +//! still narrows the backends. + +use serde::Serialize; + +/// Whether an adapter is a GPU or a software rasterizer. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum Tier { + Hardware, + Software, +} + +/// Which adapters a headless device may open. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub enum Policy { + /// The best hardware adapter, else a software one. + #[default] + Auto, + /// A hardware adapter or nothing. + Hardware, + /// A software adapter or nothing. + Software, + /// The CPU rasterizer, whatever adapters there are. + Cpu, +} + +/// Where a policy lands: an adapter of a tier, or the CPU rasterizer. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum Landing { + Hardware, + Software, + Cpu, +} + +impl Landing { + /// What a picture's reply names as its renderer: `gpu`, `gpu-software` or `cpu`. + pub fn renderer(self) -> &'static str { + match self { + Landing::Hardware => "gpu", + Landing::Software => "gpu-software", + Landing::Cpu => "cpu", + } + } +} + +impl From for Landing { + fn from(t: Tier) -> Self { + match t { + Tier::Hardware => Landing::Hardware, + Tier::Software => Landing::Software, + } + } +} + +impl Policy { + /// `auto`, `hardware`, `software` or `cpu` (case-insensitive). + pub fn parse(s: &str) -> Option { + match s.trim().to_ascii_lowercase().as_str() { + "auto" => Some(Policy::Auto), + "hardware" | "hw" | "gpu" => Some(Policy::Hardware), + "software" | "sw" => Some(Policy::Software), + "cpu" => Some(Policy::Cpu), + _ => None, + } + } + + /// The policy `SOLIDCRAFT_GPU` names; [`Policy::Auto`] when it is unset, and an error when + /// it names none. + pub fn from_env() -> Result { + match std::env::var("SOLIDCRAFT_GPU") { + Ok(v) => Policy::parse(&v).ok_or_else(|| format!("SOLIDCRAFT_GPU must be auto, hardware, software or cpu, not `{v}`")), + Err(_) => Ok(Policy::Auto), + } + } + + /// `auto`, `hardware`, `software` or `cpu`. + pub fn name(self) -> &'static str { + match self { + Policy::Auto => "auto", + Policy::Hardware => "hardware", + Policy::Software => "software", + Policy::Cpu => "cpu", + } + } + + fn admits(self, tier: Tier) -> bool { + match self { + Policy::Auto => true, + Policy::Hardware => tier == Tier::Hardware, + Policy::Software => tier == Tier::Software, + Policy::Cpu => false, + } + } + + /// Where the policy lands when the best qualifying adapter is of tier `adapter` (`None`: no + /// adapter qualifies): that adapter; else the CPU rasterizer under `auto` (and always under + /// `cpu`); else nowhere, and a picture is an error. + pub fn lands_on(self, adapter: Option) -> Option { + match (self, adapter) { + (Policy::Cpu, _) => Some(Landing::Cpu), + (_, Some(t)) => Some(t.into()), + (Policy::Auto, None) => Some(Landing::Cpu), + (Policy::Hardware | Policy::Software, None) => None, + } + } +} + +/// One adapter as the survey saw it. +#[derive(Clone, Debug, Serialize)] +pub struct AdapterReport { + pub name: String, + pub backend: String, + pub device_type: String, + pub driver: String, + pub tier: Tier, +} + +/// The backends a headless device looks at on this platform: Metal on macOS, Vulkan and D3D12 +/// on Windows, Vulkan and GL elsewhere; `WGPU_BACKEND` narrows them further. +pub fn native_backends() -> wgpu::Backends { + let native = if cfg!(target_os = "macos") { + wgpu::Backends::METAL + } else if cfg!(target_os = "windows") { + wgpu::Backends::DX12 | wgpu::Backends::VULKAN + } else { + wgpu::Backends::VULKAN | wgpu::Backends::GL + }; + match wgpu::Backends::from_env() { + Some(env) if !(env & native).is_empty() => env & native, + _ => native, + } +} + +fn tier_of(t: wgpu::DeviceType) -> Tier { + match t { + wgpu::DeviceType::Cpu => Tier::Software, + wgpu::DeviceType::DiscreteGpu | wgpu::DeviceType::IntegratedGpu | wgpu::DeviceType::VirtualGpu | wgpu::DeviceType::Other => Tier::Hardware, + } +} + +/// Preference among adapters (higher first): a discrete GPU, an integrated one, a virtual one, +/// an unknown kind, a software rasterizer. +fn rank(t: wgpu::DeviceType) -> u8 { + match t { + wgpu::DeviceType::DiscreteGpu => 4, + wgpu::DeviceType::IntegratedGpu => 3, + wgpu::DeviceType::VirtualGpu => 2, + wgpu::DeviceType::Other => 1, + wgpu::DeviceType::Cpu => 0, + } +} + +fn report(info: &wgpu::AdapterInfo) -> AdapterReport { + AdapterReport { + name: info.name.clone(), + backend: format!("{:?}", info.backend), + device_type: format!("{:?}", info.device_type), + driver: [info.driver.as_str(), info.driver_info.as_str()].iter().filter(|s| !s.is_empty()).copied().collect::>().join(" "), + tier: tier_of(info.device_type), + } +} + +fn instance() -> wgpu::Instance { + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle_from_env(); + desc.backends = native_backends(); + wgpu::Instance::new(desc) +} + +/// Every adapter the native backends offer, best first. +#[cfg(not(target_arch = "wasm32"))] +fn adapters(instance: &wgpu::Instance) -> Vec { + let mut all = pollster::block_on(instance.enumerate_adapters(native_backends())); + all.sort_by_key(|a| std::cmp::Reverse(rank(a.get_info().device_type))); + all +} + +/// What a survey found, which adapter the policy picks (`chosen` indexes `adapters`) and where +/// it lands (`None`: nowhere, a picture is an error). +#[derive(Clone, Debug, Serialize)] +pub struct Survey { + pub backends: String, + pub adapters: Vec, + pub chosen: Option, + pub lands_on: Option, +} + +/// Every adapter the native backends offer, best first, and which one `policy` picks. +#[cfg(not(target_arch = "wasm32"))] +pub fn survey(policy: Policy) -> Survey { + let found: Vec = adapters(&instance()).iter().map(|a| report(&a.get_info())).collect(); + let chosen = found.iter().position(|r| policy.admits(r.tier)); + let lands_on = policy.lands_on(chosen.and_then(|i| found.get(i)).map(|r| r.tier)); + Survey { backends: format!("{:?}", native_backends()), adapters: found, chosen, lands_on } +} + +/// The adapter `policy` picks, with its report; `None` when no adapter qualifies. +#[cfg(not(target_arch = "wasm32"))] +pub fn pick(policy: Policy) -> Option<(wgpu::Adapter, AdapterReport)> { + adapters(&instance()) + .into_iter() + .map(|a| { + let r = report(&a.get_info()); + (a, r) + }) + .find(|(_, r)| policy.admits(r.tier)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn policies_parse_and_admit_their_tiers() { + assert_eq!(Policy::parse(" Hardware "), Some(Policy::Hardware)); + assert_eq!(Policy::parse("sw"), Some(Policy::Software)); + assert_eq!(Policy::parse("metal"), None); + assert_eq!(Policy::parse("CPU"), Some(Policy::Cpu)); + assert!(!Policy::Cpu.admits(Tier::Software) && !Policy::Cpu.admits(Tier::Hardware)); + assert!(Policy::Auto.admits(Tier::Software) && Policy::Auto.admits(Tier::Hardware)); + assert!(!Policy::Hardware.admits(Tier::Software)); + assert!(!Policy::Software.admits(Tier::Hardware)); + } + + /// Hardware GPU, then a software adapter, then the CPU rasterizer: `auto` walks all three, + /// `hardware` and `software` never fall to the CPU, and `cpu` always lands there. + #[test] + fn policies_land_on_their_tiers() { + use Landing as L; + let (hw, sw) = (Some(Tier::Hardware), Some(Tier::Software)); + assert_eq!([hw, sw, None].map(|t| Policy::Auto.lands_on(t)), [Some(L::Hardware), Some(L::Software), Some(L::Cpu)]); + assert_eq!(Policy::Hardware.lands_on(hw), Some(L::Hardware)); + assert_eq!(Policy::Hardware.lands_on(None), None); + assert_eq!(Policy::Software.lands_on(sw), Some(L::Software)); + assert_eq!(Policy::Software.lands_on(None), None); + assert_eq!([hw, sw, None].map(|t| Policy::Cpu.lands_on(t)), [Some(L::Cpu); 3]); + assert_eq!([L::Hardware, L::Software, L::Cpu].map(L::renderer), ["gpu", "gpu-software", "cpu"]); + } + + #[test] + fn software_rasterizers_rank_last() { + assert_eq!(tier_of(wgpu::DeviceType::Cpu), Tier::Software); + assert!(rank(wgpu::DeviceType::IntegratedGpu) > rank(wgpu::DeviceType::Cpu)); + assert!(rank(wgpu::DeviceType::DiscreteGpu) > rank(wgpu::DeviceType::IntegratedGpu)); + } + + #[cfg(target_os = "macos")] + #[test] + fn macos_surveys_metal_only() { + assert_eq!(native_backends() & !wgpu::Backends::METAL, wgpu::Backends::empty()); + let s = survey(Policy::Auto); + assert!(s.adapters.iter().all(|a| a.backend == "Metal"), "{s:?}"); + } +} diff --git a/crates/gpu/src/view.rs b/crates/gpu/src/view.rs new file mode 100644 index 000000000..c29542af3 --- /dev/null +++ b/crates/gpu/src/view.rs @@ -0,0 +1,1590 @@ +//! The viewport's drawing: shaded triangles and screen-space wide lines with a depth buffer, +//! the section cap, surface analysis, reference images and supersampling, as render pipelines on +//! any wgpu device. The desktop and web viewport draws through it (an `egui_wgpu` paint callback +//! hands it the device and the pass); headless pictures draw through it offscreen +//! ([`crate::capture`]). Geometry is uploaded when a scene changes; each frame only the camera +//! uniform changes. Where the device runs compute shaders, opaque bodies are drawn straight from +//! their display plans: the plan is evaluated on the GPU into the vertex buffer the pass draws +//! (see [`PlannedBody`]), with nothing built or read back on the CPU. + +use std::sync::{Arc, Mutex}; + +use solidcraft_geom::Vec3; +use wgpu::util::DeviceExt; + +use crate::pbr; + +/// 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 and their +/// flags (`uniform_bytes`). +const UNIFORM_SIZE: u64 = 352; + +/// 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). +#[derive(Clone)] +pub struct PlannedBody { + pub plan: Arc, + pub face_colors: Vec<[u8; 4]>, +} + +/// CPU-side geometry waiting to be uploaded. The model scene changes with the design; the +/// highlight scene (hover, selection, the origin widget) changes often and is small. +#[derive(Default, Clone)] +pub struct GpuScene { + /// Opaque triangles. A zero normal draws the colour flat (unlit). + pub tris: Vec, + /// Opaque product PBR vertices; linear base color and explicit optical parameters. + pub pbr: Vec, + /// Translucent triangles (alpha from the colour), drawn after the opaque ones without + /// writing depth. + pub trans: Vec, + /// See-through bodies and faces (appearance opacity below 1), closed and outward-wound: + /// their far sides are drawn first, then their near sides, so they read like glass. + pub glass: Vec, + /// Depth-tested lines. + pub lines: Vec, + /// Lines drawn only where the model hides them (hidden edges). + pub hidden: Vec, + /// Lines drawn over everything (active sketch, highlights). + pub overlay: Vec, + /// Translucent triangles pushed slightly back in depth, so they only show where nothing + /// coincides with them (removed material in a preview). + pub ghost: Vec, + /// Translucent triangles drawn through everything (a cut's tool body). + pub xray: Vec, + /// Lines drawn first, under everything (the ground grid: the model hides it, it never + /// hides the model). + pub under: Vec, + /// Origin and construction planes (translucent, like `trans`) and their axes (lines, like + /// `lines`): reference geometry, never cut away by a section (#1229). + pub guide_trans: Vec, + pub guide_lines: Vec, + /// Opaque bodies drawn from their plans on the GPU, like `tris`. + pub planned: Vec, + /// The model's bodies, a few at a time, drawn before the loose geometry above (`tris`, + /// `trans`, `lines` and `hidden` of each block, in order, then the scene's own). A block + /// that comes back unchanged keeps its buffers: a design changing one body at a time (an + /// agent adding bodies over MCP) uploads only the blocks that changed, not the whole model. + pub blocks: Vec, +} + +impl GpuScene { + /// The blocks' geometry moved into the scene's own lists, in drawing order (for tests that + /// count what the scene holds). + pub fn merged(mut self) -> GpuScene { + let mut out = GpuScene { glass: std::mem::take(&mut self.glass), ..Default::default() }; + for block in std::mem::take(&mut self.blocks) { + out.tris.extend_from_slice(&block.bytes.tris); + out.trans.extend_from_slice(&block.bytes.trans); + out.lines.extend_from_slice(&block.bytes.lines); + out.hidden.extend_from_slice(&block.bytes.hidden); + } + out.tris.append(&mut self.tris); + out.trans.append(&mut self.trans); + out.lines.append(&mut self.lines); + out.hidden.append(&mut self.hidden); + GpuScene { tris: out.tris, trans: out.trans, glass: out.glass, lines: out.lines, hidden: out.hidden, ..self } + } +} + +/// A run of the model's bodies in the scene: their triangles and edges, and a key that names +/// exactly this content (the viewport keeps the bytes while the key comes back). +#[derive(Clone)] +pub struct SceneBlock { + pub key: u64, + pub bytes: Arc, +} + +/// A block's geometry, laid out as in [`GpuScene`]. +#[derive(Default)] +pub struct BlockBytes { + pub tris: Vec, + pub trans: Vec, + pub glass: Vec, + pub lines: Vec, + pub hidden: Vec, +} + +impl GpuScene { + pub fn pbr_tri(&mut self, p: [f32; 3], n: [f32; 3], surface: solidcraft_render::surface::OpaqueSurface) { + let base = surface.base_color().to_f32(); + let parameters = [surface.metallic() as f32, surface.roughness() as f32, surface.dielectric_ior() as f32]; + for value in p.into_iter().chain(n).chain(base).chain(parameters) { + self.pbr.extend_from_slice(&value.to_le_bytes()); + } + } + pub fn tri(&mut self, p: [f32; 3], n: [f32; 3], c: [u8; 4]) { + for v in p.iter().chain(&n) { + self.tris.extend_from_slice(&v.to_le_bytes()); + } + self.tris.extend_from_slice(&c); + } + pub fn trans_tri(&mut self, p: [f32; 3], n: [f32; 3], c: [u8; 4]) { + for v in p.iter().chain(&n) { + self.trans.extend_from_slice(&v.to_le_bytes()); + } + self.trans.extend_from_slice(&c); + } + /// A line shown only where the model hides it. + pub fn hidden_line(&mut self, a: [f32; 3], b: [f32; 3], c: [u8; 4], width: f32) { + for v in a.iter().chain(&b) { + self.hidden.extend_from_slice(&v.to_le_bytes()); + } + self.hidden.extend_from_slice(&c); + self.hidden.extend_from_slice(&width.to_le_bytes()); + } + pub fn glass_tri(&mut self, p: [f32; 3], n: [f32; 3], c: [u8; 4]) { + for v in p.iter().chain(&n) { + self.glass.extend_from_slice(&v.to_le_bytes()); + } + self.glass.extend_from_slice(&c); + } + pub fn ghost_tri(&mut self, p: [f32; 3], n: [f32; 3], c: [u8; 4]) { + for v in p.iter().chain(&n) { + self.ghost.extend_from_slice(&v.to_le_bytes()); + } + self.ghost.extend_from_slice(&c); + } + pub fn xray_tri(&mut self, p: [f32; 3], n: [f32; 3], c: [u8; 4]) { + for v in p.iter().chain(&n) { + self.xray.extend_from_slice(&v.to_le_bytes()); + } + self.xray.extend_from_slice(&c); + } + /// A line under everything (see [`GpuScene::under`]). + pub fn under_line(&mut self, a: [f32; 3], b: [f32; 3], c: [u8; 4], width: f32) { + for v in a.iter().chain(&b) { + self.under.extend_from_slice(&v.to_le_bytes()); + } + self.under.extend_from_slice(&c); + self.under.extend_from_slice(&width.to_le_bytes()); + } + /// A translucent triangle of a plane a section does not cut (see [`GpuScene::guide_trans`]). + pub fn guide_tri(&mut self, p: [f32; 3], c: [u8; 4]) { + for v in p.iter().chain(&[0.0; 3]) { + self.guide_trans.extend_from_slice(&v.to_le_bytes()); + } + self.guide_trans.extend_from_slice(&c); + } + /// A depth-tested line a section does not cut (see [`GpuScene::guide_lines`]). + pub fn guide_line(&mut self, a: [f32; 3], b: [f32; 3], c: [u8; 4], width: f32) { + for v in a.iter().chain(&b) { + self.guide_lines.extend_from_slice(&v.to_le_bytes()); + } + self.guide_lines.extend_from_slice(&c); + self.guide_lines.extend_from_slice(&width.to_le_bytes()); + } + pub fn line(&mut self, a: [f32; 3], b: [f32; 3], c: [u8; 4], width: f32, on_top: bool) { + let out = if on_top { &mut self.overlay } else { &mut self.lines }; + for v in a.iter().chain(&b) { + out.extend_from_slice(&v.to_le_bytes()); + } + out.extend_from_slice(&c); + out.extend_from_slice(&width.to_le_bytes()); + } +} + +pub type SceneSlot = Arc>>; + +/// A reference image (canvas or decal): a textured quad, depth-tested against the model. +#[derive(Clone)] +pub struct GpuImage { + pub id: u64, + /// Changes when the pixels change (the texture is re-uploaded). + pub version: u64, + pub size: [u32; 2], + /// Straight RGBA8, `size[0] * size[1] * 4` bytes. + pub rgba: Arc>, + /// Bottom-left, bottom-right, top-right, top-left of the image. + pub corners: [[f32; 3]; 4], + pub opacity: f32, +} + +/// Image vertex: position (3 × f32), uv (2 × f32), opacity (f32). +const IMG_SIZE: usize = 24; + +/// Per-frame parameters. +pub struct Frame { + /// Product preview uses its own batches, retaining the Design viewport's uploads. + pub product: bool, + pub key: u64, + pub slot: SceneSlot, + pub sketch_key: u64, + pub sketch_slot: SceneSlot, + /// The highlight scene and its key. + pub hl_key: u64, + pub hl_slot: SceneSlot, + /// The live preview scene and its key. + pub pv_key: u64, + pub pv_slot: SceneSlot, + /// Column-major view-projection. + pub view_proj: [[f32; 4]; 4], + /// Direction toward the eye (for lighting). + pub back: [f32; 3], + /// Viewport size in physical pixels. + pub size_px: [f32; 2], + /// Section cut: (normal, d); fragments with normal·p > d are hidden. A zero normal: none. + pub clip: [f32; 4], + /// Colour of the inside of cut bodies (straight sRGBA, 0..1). + pub cap: [f32; 4], + /// Canvases and decals. + pub images: Vec, + /// Surface analysis: (mode: 0 none, 1 zebra, 2 draft, 3 curvature, 4 environment, + /// 5 accessibility; parameter; scale; size) and the pull / access direction. + pub analysis: [f32; 8], + /// The analysis colours and the stripe flag ([`analysis_colors`]). + pub analysis_colors: [f32; 36], + /// Accessibility: the depth map seen from the access direction. + pub access: Option, + /// Draw silhouette outlines around the model (visual styles with edges). + pub outline: bool, + /// Eye position and 1 for a perspective camera (0: orthographic), for the section cap's depth + /// and the depth bias. + pub eye: [f32; 4], + /// 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). + pub ssaa: f32, +} + +/// Heights of the model seen from a direction (an orthographic depth map): a point is reachable +/// from that direction when nothing lies above it. +#[derive(Clone)] +pub struct AccessMap { + pub version: u64, + pub size: u32, + /// Row-major heights along the direction (−∞ where nothing is). + pub depth: Arc>, + /// Map axes: pixel = (p·u + u.w, p·v + v.w) × scale. + pub u: [f32; 4], + pub v: [f32; 4], + pub scale: f32, +} + +/// The accessibility depth map's resolution (pixels per side). +pub const ACCESS_SIZE: u32 = 1024; + +impl AccessMap { + /// The depth map of `meshes` seen along `dir` (`version`: what the GPU uploads it by): + /// rasterise the triangles seen along `dir` (orthographic), keeping the highest point per pixel. + pub fn build(meshes: &[&solidcraft_geom::Mesh], dir: Vec3, version: u64) -> Option { + let d = dir.normalized()?; + let u = d.cross(if d.x.abs() < 0.9 { Vec3::X } else { Vec3::Y }).normalized()?; + let v = d.cross(u); + let (mut lo, mut hi) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]); + for m in meshes { + for p in &m.positions { + let (a, b) = (p.dot(u), p.dot(v)); + lo = [lo[0].min(a), lo[1].min(b)]; + hi = [hi[0].max(a), hi[1].max(b)]; + } + } + let ext = (hi[0] - lo[0]).max(hi[1] - lo[1]); + if !(ext.is_finite() && ext > 1e-9) { + return None; + } + let n = ACCESS_SIZE as usize; + let scale = (ACCESS_SIZE - 2) as f64 / ext; + // One pixel of margin on each side. + let (ou, ov) = (-lo[0] + 1.0 / scale, -lo[1] + 1.0 / scale); + let mut depth = vec![f32::NEG_INFINITY; n * n]; + for m in meshes { + for t in &m.triangles { + let q: Vec<(f64, f64, f64)> = t + .iter() + .filter_map(|i| m.positions.get(*i as usize)) + .map(|p| ((p.dot(u) + ou) * scale, (p.dot(v) + ov) * scale, p.dot(d))) + .collect(); + let [a, b, c] = q[..] else { continue }; + let area = (b.0 - a.0) * (c.1 - a.1) - (b.1 - a.1) * (c.0 - a.0); + let (x0, x1) = (a.0.min(b.0).min(c.0).floor().max(0.0) as usize, (a.0.max(b.0).max(c.0).ceil() as usize).min(n - 1)); + let (y0, y1) = (a.1.min(b.1).min(c.1).floor().max(0.0) as usize, (a.1.max(b.1).max(c.1).ceil() as usize).min(n - 1)); + // Edge-on triangles: their vertices still count. + if area.abs() < 1e-12 { + for p in [a, b, c] { + let (x, y) = (p.0 as usize, p.1 as usize); + if let Some(z) = depth.get_mut(y * n + x) { + *z = z.max(p.2 as f32); + } + } + continue; + } + for y in y0..=y1 { + for x in x0..=x1 { + let (px, py) = (x as f64 + 0.5, y as f64 + 0.5); + let w0 = ((b.0 - px) * (c.1 - py) - (b.1 - py) * (c.0 - px)) / area; + let w1 = ((c.0 - px) * (a.1 - py) - (c.1 - py) * (a.0 - px)) / area; + let w2 = 1.0 - w0 - w1; + if w0 < -1e-9 || w1 < -1e-9 || w2 < -1e-9 { + continue; + } + let z = (w0 * a.2 + w1 * b.2 + w2 * c.2) as f32; + if let Some(cell) = depth.get_mut(y * n + x) { + *cell = cell.max(z); + } + } + } + } + } + Some(AccessMap { + version, + size: ACCESS_SIZE, + depth: Arc::new(depth), + u: [u.x as f32, u.y as f32, u.z as f32, ou as f32], + v: [v.x as f32, v.y as f32, v.z as f32, ov as f32], + scale: scale as f32, + }) + } +} + +/// The shader's surface analysis uniform (see [`Frame::analysis`]) for `mode`; Accessibility +/// reads its depth map's scale and size from `access`. +pub fn analysis_uniform(mode: Option, access: Option<&AccessMap>) -> [f32; 8] { + use solidcraft_render::AnalysisMode as A; + match mode { + Some(A::Zebra { stripes }) => [1.0, stripes as f32, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0], + Some(A::Draft { pull, angle }) => [2.0, angle as f32, 0.0, 0.0, pull.x as f32, pull.y as f32, pull.z as f32, 0.0], + Some(A::Curvature { radius }) => [3.0, radius as f32, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0], + Some(A::Environment) => [4.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0], + Some(A::Access { dir }) => { + let (scale, size, eps) = access.map(|m| (m.scale, m.size as f32, 1.5 / m.scale.max(1e-9))).unwrap_or((0.0, 0.0, 0.0)); + [5.0, eps, scale, size, dir.x as f32, dir.y as f32, dir.z as f32, 0.0] + } + None => [0.0; 8], + } +} + +/// Vertices (or line instances) on the GPU, in as many buffers as the device's buffer size +/// limit needs: a large import's triangles can exceed one buffer (#883). +struct Batch { + /// Each buffer and its vertex (instance) count. + parts: Vec<(wgpu::Buffer, u32)>, + /// Bytes per buffer (all but the last are full). + chunk: usize, +} + +/// A chunk of planned bodies on the GPU: their evaluated mesh and a colour per vertex. +struct PlannedDraw { + mesh: Arc, + colors: wgpu::Buffer, +} + +/// A scene block on the GPU, with the bytes it was uploaded from. +struct BlockGpu { + bytes: Arc, + tris: Option, + trans: Option, + lines: Option, + hidden: Option, +} + +/// The blocks' buffers, then the scene's own, as one batch (the blocks' buffers are shared, +/// not copied). +fn joined<'a>(blocks: impl Iterator>, own: Option) -> Option { + let mut parts: Vec<(wgpu::Buffer, u32)> = blocks.flatten().flat_map(|b| b.parts.iter().cloned()).collect(); + let chunk = own.as_ref().map(|b| b.chunk).unwrap_or(0); + parts.extend(own.into_iter().flat_map(|b| b.parts)); + (!parts.is_empty()).then_some(Batch { parts, chunk }) +} + +/// Planned bodies end a GPU chunk one time in this many (by their plan's address), and a chunk +/// holds at most [`MAX_CHUNK_BODIES`]: a scene of a thousand bodies takes a few dozen dispatches +/// once, and a changed body re-evaluates a few dozen bodies, not all of them. +const CHUNK_SPLIT: u64 = 32; +const MAX_CHUNK_BODIES: usize = 128; + +#[derive(Default)] +struct Batches { + /// The scene blocks on the GPU, by key. + blocks: std::collections::HashMap, + key: Option, + tris: Option, + pbr: Option, + trans: Option, + glass: Option, + /// The glass triangles as built, and the view direction they were last sorted for. + glass_cpu: Vec, + glass_sorted_for: Option<[f32; 3]>, + lines: Option, + hidden: Option, + overlays: Option, + ghost: Option, + xray: Option, + under: Option, + guide_trans: Option, + guide_lines: Option, + planned: Vec, + /// Evaluated chunks by their plans' addresses, holding the plans so the addresses stay + /// theirs: a chunk whose plans are unchanged is not evaluated again when the scene is rebuilt. + resident: std::collections::HashMap, (Vec>, Arc)>, +} + +impl Batches { + /// Upload a new scene. Planned bodies not yet on the GPU are evaluated there: their + /// dispatches go into `encoder`, ahead of this frame's render pass. + fn take(&mut self, device: &wgpu::Device, key: u64, slot: &SceneSlot, tess: Option<(&crate::TessGpu, &mut wgpu::CommandEncoder)>) { + if self.key == Some(key) { + return; + } + if let Some(sc) = slot.lock().ok().and_then(|mut s| s.take()) { + self.planned = match tess { + Some((tess, encoder)) => self.planned(device, tess, encoder, &sc.planned), + None => Vec::new(), + }; + let mut kept = std::mem::take(&mut self.blocks); + let mut blocks: Vec<&BlockGpu> = Vec::with_capacity(sc.blocks.len()); + for block in &sc.blocks { + let gpu = match kept.remove(&block.key).filter(|g| Arc::ptr_eq(&g.bytes, &block.bytes)) { + Some(g) => g, + None => BlockGpu { + bytes: block.bytes.clone(), + tris: upload(device, "sc_tris", &block.bytes.tris, TRI_SIZE), + trans: upload(device, "sc_trans", &block.bytes.trans, TRI_SIZE), + lines: upload(device, "sc_lines", &block.bytes.lines, LINE_SIZE), + hidden: upload(device, "sc_hidden", &block.bytes.hidden, LINE_SIZE), + }, + }; + self.blocks.insert(block.key, gpu); + } + for block in &sc.blocks { + if let Some(g) = self.blocks.get(&block.key) { + blocks.push(g); + } + } + self.tris = joined(blocks.iter().map(|b| &b.tris), upload(device, "sc_tris", &sc.tris, TRI_SIZE)); + self.pbr = upload(device, "sc_pbr", &sc.pbr, PBR_SIZE); + self.trans = joined(blocks.iter().map(|b| &b.trans), upload(device, "sc_trans", &sc.trans, TRI_SIZE)); + self.glass = upload_with(device, "sc_glass", &sc.glass, TRI_SIZE, wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST); + self.glass_cpu = sc.glass; + self.glass_sorted_for = None; + self.lines = joined(blocks.iter().map(|b| &b.lines), upload(device, "sc_lines", &sc.lines, LINE_SIZE)); + self.hidden = joined(blocks.iter().map(|b| &b.hidden), upload(device, "sc_hidden", &sc.hidden, LINE_SIZE)); + self.overlays = upload(device, "sc_overlay", &sc.overlay, LINE_SIZE); + self.ghost = upload(device, "sc_ghost", &sc.ghost, TRI_SIZE); + self.xray = upload(device, "sc_xray", &sc.xray, TRI_SIZE); + self.under = upload(device, "sc_under", &sc.under, LINE_SIZE); + self.guide_trans = upload(device, "sc_guide_trans", &sc.guide_trans, TRI_SIZE); + self.guide_lines = upload(device, "sc_guide_lines", &sc.guide_lines, LINE_SIZE); + self.key = Some(key); + } + } + + /// The planned bodies on the GPU: in chunks of at most `MAX_BATCH` vertices (one for any + /// ordinary scene), each uploaded and evaluated in one dispatch and drawn in one call. A + /// chunk whose plans are unchanged is not evaluated again; colours are rebuilt each time. + fn planned( + &mut self, + device: &wgpu::Device, + tess: &crate::TessGpu, + encoder: &mut wgpu::CommandEncoder, + bodies: &[PlannedBody], + ) -> Vec { + // Chunks end where a body's own plan says (or when full), so a body whose plan changes + // (an edit, or a refinement as the view zooms in, #1320) re-evaluates only its own + // chunk, not the whole scene. + let mut chunks: Vec> = Vec::new(); + let mut filled = 0usize; + let mut open = false; + for b in bodies { + let n = b.plan.vertex_count(); + match chunks.last_mut() { + Some(c) if open && filled + n <= crate::MAX_BATCH => c.push(b), + _ => { + chunks.push(vec![b]); + filled = 0; + } + } + filled += n; + let mut h = std::collections::hash_map::DefaultHasher::new(); + std::hash::Hash::hash(&(Arc::as_ptr(&b.plan) as usize), &mut h); + open = !std::hash::Hasher::finish(&h).is_multiple_of(CHUNK_SPLIT) && chunks.last().is_some_and(|c| c.len() < MAX_CHUNK_BODIES); + } + let key = |c: &[&PlannedBody]| c.iter().map(|b| Arc::as_ptr(&b.plan) as usize).collect::>(); + self.resident.retain(|k, _| chunks.iter().any(|c| key(c) == *k)); + let mut out = Vec::with_capacity(chunks.len()); + for chunk in &chunks { + let mesh = match self.resident.get(&key(chunk)) { + Some((_, m)) => m.clone(), + None => { + let plans: Vec<&solidcraft_geom::tess::TessPlan> = chunk.iter().map(|b| &*b.plan).collect(); + match tess.prepare_many(&plans) { + Ok(m) => { + tess.record(encoder, &m); + let m = Arc::new(m); + self.resident.insert(key(chunk), (chunk.iter().map(|b| b.plan.clone()).collect(), m.clone())); + m + } + Err(e) => { + log::warn!("bodies are not drawn on the GPU: {e}"); + continue; + } + } + } + }; + let mut bytes = Vec::with_capacity(mesh.vertex_face.len() * 4); + for (part, b) in mesh.parts.iter().zip(chunk) { + let last = b.face_colors.last().copied().unwrap_or([200, 200, 200, 255]); + let faces = mesh.vertex_face.get(part.vertices.start as usize..part.vertices.end as usize).unwrap_or_default(); + bytes.extend(faces.iter().flat_map(|f| b.face_colors.get(*f as usize).copied().unwrap_or(last))); + } + if let Some((colors, _)) = upload(device, "sc_planned_colors", &bytes, 4).and_then(|c| c.parts.into_iter().next()) { + out.push(PlannedDraw { mesh, colors }); + } + } + out + } +} + +/// The viewport's pipelines and the scenes uploaded to one device, for one kind of target. +pub struct Renderer { + tri: wgpu::RenderPipeline, + /// `tri` and `tri_cut` for planned bodies (positions and normals from the GPU evaluation, + /// colours per vertex, indexed). + tri_planned: wgpu::RenderPipeline, + tri_cut_planned: Option<(wgpu::RenderPipeline, wgpu::RenderPipeline)>, + /// The tessellation compute pipeline, where the device runs compute shaders. + tess: Option, + /// While a section is shown (when the depth buffer has a stencil): `tri` marking where the + /// cap shows, then the cap again at the section plane's depth, so it hides the inside. + tri_cut: Option<(wgpu::RenderPipeline, wgpu::RenderPipeline)>, + /// Highlight triangles over the model (depth test ≤, no depth write). + tri_hl: wgpu::RenderPipeline, + pbr: wgpu::RenderPipeline, + trans: wgpu::RenderPipeline, + /// Glass: far sides (front faces culled), then near sides (back faces culled). + glass_far: wgpu::RenderPipeline, + glass_near: wgpu::RenderPipeline, + ghost: wgpu::RenderPipeline, + xray: wgpu::RenderPipeline, + line: wgpu::RenderPipeline, + /// Lines behind the model (depth test >). + line_hidden: wgpu::RenderPipeline, + overlay: wgpu::RenderPipeline, + /// Reference planes and axes: as `trans` and `line`, but not cut by a section. + guide_trans: wgpu::RenderPipeline, + guide_line: wgpu::RenderPipeline, + uniform: wgpu::Buffer, + bind: wgpu::BindGroup, + linear_out: bool, + model: Batches, + product: Batches, + empty: Batches, + sketch: Batches, + highlight: Batches, + preview: Batches, + image: wgpu::RenderPipeline, + image_bgl: wgpu::BindGroupLayout, + sampler: wgpu::Sampler, + /// Textures by image id: (version, bind group). + textures: std::collections::HashMap, + /// This frame's quads: (image id, vertices). + quads: Vec<(u64, Batch)>, + access_bgl: wgpu::BindGroupLayout, + /// The accessibility depth map (a 1 × 1 stand-in when there is none) and its version. + access_bind: wgpu::BindGroup, + access_version: u64, + /// The target the pipelines draw into (format, depth, samples): a supersampled frame is + /// drawn into textures of the same kind. + target: GpuTarget, + /// The device's largest 2D texture side (#869). + max_texture: u32, + /// Supersampling (#1288): the filter that draws the supersampled frame into the viewport. + ss_blit: wgpu::RenderPipeline, + ss_bgl: wgpu::BindGroupLayout, + /// The supersampled frame's textures, kept while its size stays. + ss: Option, + /// This frame was drawn supersampled (in `prepare`): `paint` only filters it down. + ss_ready: bool, +} + +/// A supersampled frame: the scene drawn at a multiple of the viewport's pixels. +struct Supersampled { + size: [u32; 2], + /// Drawn into (multisampled with the viewport's MSAA). + color: wgpu::TextureView, + /// The resolved colour (when `color` is multisampled). + resolve: Option, + depth: Option, + /// The single-sampled colour, for the filter. + bind: wgpu::BindGroup, +} + +/// Most memory (bytes) a supersampled frame's colour and depth may take. +const SS_BUDGET: u64 = 384 << 20; + +/// The size (px) to draw a `size` viewport supersampled `factor` times in each direction: +/// within the device's largest texture side (#869) and the memory budget (at `samples` per pixel, +/// four bytes of colour and four of depth each). `None` when that leaves under 1.25×: the frame +/// is drawn as usual. A `factor` under 1 draws it that much smaller, to be filtered up. +pub fn supersampled_size(size: [f32; 2], factor: f32, max_side: u32, samples: u32) -> Option<[u32; 2]> { + let [w, h] = size; + if w >= 1.0 && h >= 1.0 && factor > 0.0 && factor < 1.0 { + return Some([((w * factor).floor() as u32).clamp(1, max_side.max(1)), ((h * factor).floor() as u32).clamp(1, max_side.max(1))]); + } + if !(w >= 1.0 && h >= 1.0 && factor.is_finite() && factor > 1.0) { + return None; + } + let side = max_side as f32; + let bytes_per_px = 8.0 * samples.max(1) as f32; + let by_memory = (SS_BUDGET as f32 / (w * h * bytes_per_px)).sqrt(); + let f = factor.min(side / w).min(side / h).min(by_memory); + (f >= 1.25).then(|| [((w * f).floor() as u32).clamp(1, max_side), ((h * f).floor() as u32).clamp(1, max_side)]) +} + +/// The filter: each viewport pixel the mean of the supersampled pixels under it (four bilinear +/// taps a quarter of its footprint from its centre: exactly the 2 × 2 box at 2×). +const SS_SHADER: &str = r#" +@group(0) @binding(0) var src: texture_2d; +@group(0) @binding(1) var smp: sampler; +struct O { @builtin(position) pos: vec4, @location(0) uv: vec2 }; +@vertex +fn vs(@builtin(vertex_index) i: u32) -> O { + let x = f32((i << 1u) & 2u); + let y = f32(i & 2u); + var o: O; + o.pos = vec4(x * 2.0 - 1.0, 1.0 - y * 2.0, 0.0, 1.0); + o.uv = vec2(x, y); + return o; +} +@fragment +fn fs(i: O) -> @location(0) vec4 { + let d = vec2(dpdx(i.uv.x), dpdy(i.uv.y)) * 0.25; + let a = textureSampleLevel(src, smp, i.uv + vec2(-d.x, -d.y), 0.0); + let b = textureSampleLevel(src, smp, i.uv + vec2(d.x, -d.y), 0.0); + let c = textureSampleLevel(src, smp, i.uv + vec2(-d.x, d.y), 0.0); + let e = textureSampleLevel(src, smp, i.uv + vec2(d.x, d.y), 0.0); + return (a + b + c + e) * 0.25; +} +"#; + +fn access_texture(device: &wgpu::Device, queue: Option<&wgpu::Queue>, bgl: &wgpu::BindGroupLayout, size: u32, depth: &[f32]) -> wgpu::BindGroup { + let extent = wgpu::Extent3d { width: size.max(1), height: size.max(1), depth_or_array_layers: 1 }; + let tex = device.create_texture(&wgpu::TextureDescriptor { + label: Some("sc_access"), + size: extent, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::R32Float, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + if let Some(q) = queue + && depth.len() == (size as usize) * (size as usize) + { + let bytes: Vec = depth.iter().flat_map(|x| x.to_le_bytes()).collect(); + q.write_texture( + wgpu::TexelCopyTextureInfo { texture: &tex, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, + &bytes, + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(4 * size), rows_per_image: Some(size) }, + extent, + ); + } + let view = tex.create_view(&Default::default()); + device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("sc_access"), + layout: bgl, + entries: &[wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(&view) }], + }) +} + +pub const SHADER: &str = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/shaders/viewport.wgsl")); + +fn tri_layout() -> wgpu::VertexBufferLayout<'static> { + const A: [wgpu::VertexAttribute; 3] = wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x3, 2 => Unorm8x4]; + wgpu::VertexBufferLayout { array_stride: TRI_SIZE as u64, step_mode: wgpu::VertexStepMode::Vertex, attributes: &A } +} + +/// A planned body's vertices as the GPU evaluation writes them: the position, then the normal +/// at [`crate::NORMAL_OFFSET`] (each padded to four floats). +fn pbr_layout() -> wgpu::VertexBufferLayout<'static> { + const A: [wgpu::VertexAttribute; 4] = wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x3, 2 => Float32x3, 3 => Float32x3]; + wgpu::VertexBufferLayout { array_stride: PBR_SIZE as u64, step_mode: wgpu::VertexStepMode::Vertex, attributes: &A } +} + +fn planned_layout() -> wgpu::VertexBufferLayout<'static> { + const A: [wgpu::VertexAttribute; 2] = [ + wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x3, offset: 0, shader_location: 0 }, + wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x3, offset: crate::NORMAL_OFFSET, shader_location: 1 }, + ]; + wgpu::VertexBufferLayout { array_stride: crate::VERTEX_STRIDE, step_mode: wgpu::VertexStepMode::Vertex, attributes: &A } +} + +/// A planned body's colours, one per vertex. +fn color_layout() -> wgpu::VertexBufferLayout<'static> { + const A: [wgpu::VertexAttribute; 1] = wgpu::vertex_attr_array![2 => Unorm8x4]; + wgpu::VertexBufferLayout { array_stride: 4, step_mode: wgpu::VertexStepMode::Vertex, attributes: &A } +} + +fn line_layout() -> wgpu::VertexBufferLayout<'static> { + const A: [wgpu::VertexAttribute; 4] = wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x3, 2 => Unorm8x4, 3 => Float32]; + wgpu::VertexBufferLayout { array_stride: LINE_SIZE as u64, step_mode: wgpu::VertexStepMode::Instance, attributes: &A } +} + +/// The target configuration: colour format, depth format and MSAA sample count of the app. +#[derive(Clone, Copy, Debug)] +pub struct GpuTarget { + pub format: wgpu::TextureFormat, + pub depth: Option, + pub samples: u32, + /// The device evaluates display plans (compute shaders): bodies may be drawn from them. + pub tess: bool, +} + +impl Renderer { + /// The pipelines for target `t` on `device`; `tess` evaluates planned bodies on the GPU. + pub fn new(device: &wgpu::Device, t: GpuTarget, tess: Option) -> Self { + let source = format!("{SHADER}\n{}", pbr::SOURCE); + let module = + device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("sc_viewport"), source: wgpu::ShaderSource::Wgsl(source.into()) }); + let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("sc_viewport"), + entries: &[wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::VERTEX_FRAGMENT, + ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None }, + count: None, + }], + }); + let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("sc_viewport"), + bind_group_layouts: &[Some(&bgl)], + immediate_size: 0, + }); + let uniform = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("sc_viewport_u"), + size: UNIFORM_SIZE, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let bind = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("sc_viewport"), + layout: &bgl, + entries: &[wgpu::BindGroupEntry { binding: 0, resource: uniform.as_entire_binding() }], + }); + let depth = |compare: wgpu::CompareFunction, write: bool| -> Option { + t.depth.map(|format| wgpu::DepthStencilState { + format, + depth_write_enabled: Some(write), + depth_compare: Some(compare), + stencil: Default::default(), + bias: Default::default(), + }) + }; + let pipeline = |label: &str, + vs: &str, + fs: &str, + buf: wgpu::VertexBufferLayout<'static>, + ds: Option, + blend: Option| { + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(label), + layout: Some(&layout), + vertex: wgpu::VertexState { module: &module, entry_point: Some(vs), buffers: &[Some(buf)], compilation_options: Default::default() }, + primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() }, + depth_stencil: ds, + multisample: wgpu::MultisampleState { count: t.samples.max(1), mask: !0, alpha_to_coverage_enabled: false }, + fragment: Some(wgpu::FragmentState { + module: &module, + entry_point: Some(fs), + targets: &[Some(wgpu::ColorTargetState { format: t.format, blend, write_mask: wgpu::ColorWrites::ALL })], + compilation_options: Default::default(), + }), + multiview_mask: None, + cache: None, + }) + }; + let alpha = Some(wgpu::BlendState::ALPHA_BLENDING); + let glass = |label: &str, cull: wgpu::Face| { + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(label), + layout: Some(&layout), + vertex: wgpu::VertexState { + module: &module, + entry_point: Some("vs_tri"), + buffers: &[Some(tri_layout())], + compilation_options: Default::default(), + }, + primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, cull_mode: Some(cull), ..Default::default() }, + depth_stencil: depth(wgpu::CompareFunction::LessEqual, false), + multisample: wgpu::MultisampleState { count: t.samples.max(1), mask: !0, alpha_to_coverage_enabled: false }, + fragment: Some(wgpu::FragmentState { + module: &module, + entry_point: Some("fs_tri"), + targets: &[Some(wgpu::ColorTargetState { format: t.format, blend: alpha, write_mask: wgpu::ColorWrites::ALL })], + compilation_options: Default::default(), + }), + multiview_mask: None, + cache: None, + }) + }; + let image_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("sc_image"), + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + count: None, + }, + ], + }); + let image_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("sc_image"), + bind_group_layouts: &[Some(&bgl), Some(&image_bgl)], + immediate_size: 0, + }); + const IA: [wgpu::VertexAttribute; 3] = wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x2, 2 => Float32]; + let image = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("sc_image"), + layout: Some(&image_layout), + vertex: wgpu::VertexState { + module: &module, + entry_point: Some("vs_img"), + buffers: &[Some(wgpu::VertexBufferLayout { + array_stride: IMG_SIZE as u64, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &IA, + })], + compilation_options: Default::default(), + }, + primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() }, + depth_stencil: depth(wgpu::CompareFunction::LessEqual, false), + multisample: wgpu::MultisampleState { count: t.samples.max(1), mask: !0, alpha_to_coverage_enabled: false }, + fragment: Some(wgpu::FragmentState { + module: &module, + entry_point: Some("fs_img"), + targets: &[Some(wgpu::ColorTargetState { format: t.format, blend: alpha, write_mask: wgpu::ColorWrites::ALL })], + compilation_options: Default::default(), + }), + multiview_mask: None, + cache: None, + }); + let access_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("sc_access"), + entries: &[wgpu::BindGroupLayoutEntry { + binding: 2, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: false }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }], + }); + let solid_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("sc_solid"), + bind_group_layouts: &[Some(&bgl), Some(&access_bgl)], + immediate_size: 0, + }); + let built = [Some(tri_layout())]; + let evaluated = [Some(planned_layout()), Some(color_layout())]; + let solid = |label: &str, fs: &str, cull: Option, ds: Option, planned: bool| { + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(label), + layout: Some(&solid_layout), + vertex: wgpu::VertexState { + module: &module, + entry_point: Some("vs_tri"), + buffers: if planned { &evaluated[..] } else { &built[..] }, + compilation_options: Default::default(), + }, + primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, cull_mode: cull, ..Default::default() }, + depth_stencil: ds, + multisample: wgpu::MultisampleState { count: t.samples.max(1), mask: !0, alpha_to_coverage_enabled: false }, + fragment: Some(wgpu::FragmentState { + module: &module, + entry_point: Some(fs), + targets: &[Some(wgpu::ColorTargetState { format: t.format, blend: None, write_mask: wgpu::ColorWrites::ALL })], + compilation_options: Default::default(), + }), + multiview_mask: None, + cache: None, + }) + }; + // While a section is shown: the stencil marking and the cap (see `Renderer::tri_cut`). + let cut = |planned: bool| { + t.depth.filter(|f| f.has_stencil_aspect()).map(|format| { + // The visible surface marks the stencil: 1 where it is a back face (the cap). + use wgpu::StencilOperation::{Keep, Replace, Zero}; + let face = |pass_op| wgpu::StencilFaceState { compare: wgpu::CompareFunction::Always, fail_op: Keep, depth_fail_op: Keep, pass_op }; + let mark = wgpu::DepthStencilState { + format, + depth_write_enabled: Some(true), + depth_compare: Some(wgpu::CompareFunction::Less), + stencil: wgpu::StencilState { front: face(Zero), back: face(Replace), read_mask: 0xff, write_mask: 0xff }, + bias: Default::default(), + }; + // Then the cap's back faces again, only there, at the section plane's depth. + let only = wgpu::StencilFaceState { compare: wgpu::CompareFunction::Equal, ..face(Keep) }; + let cap = wgpu::DepthStencilState { + format, + depth_write_enabled: Some(true), + depth_compare: Some(wgpu::CompareFunction::Always), + stencil: wgpu::StencilState { front: only, back: only, read_mask: 0xff, write_mask: 0 }, + bias: Default::default(), + }; + ( + solid("sc_tris_mark", "fs_solid", None, Some(mark), planned), + solid("sc_tris_cap", "fs_solid_cut", Some(wgpu::Face::Front), Some(cap), planned), + ) + }) + }; + let access_bind = access_texture(device, None, &access_bgl, 1, &[]); + let sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("sc_image"), + mag_filter: wgpu::FilterMode::Linear, + min_filter: wgpu::FilterMode::Linear, + ..Default::default() + }); + let ss_module = + device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("sc_ssaa"), source: wgpu::ShaderSource::Wgsl(SS_SHADER.into()) }); + let ss_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("sc_ssaa"), + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + count: None, + }, + ], + }); + let ss_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("sc_ssaa"), + bind_group_layouts: &[Some(&ss_bgl)], + immediate_size: 0, + }); + // The frame is premultiplied (drawn over transparent black), so it goes over the + // viewport's background premultiplied; the viewport's depth is left as it is. + let ss_blit = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("sc_ssaa"), + layout: Some(&ss_layout), + vertex: wgpu::VertexState { module: &ss_module, entry_point: Some("vs"), buffers: &[], compilation_options: Default::default() }, + primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() }, + depth_stencil: depth(wgpu::CompareFunction::Always, false), + multisample: wgpu::MultisampleState { count: t.samples.max(1), mask: !0, alpha_to_coverage_enabled: false }, + fragment: Some(wgpu::FragmentState { + module: &ss_module, + entry_point: Some("fs"), + targets: &[Some(wgpu::ColorTargetState { + format: t.format, + blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING), + write_mask: wgpu::ColorWrites::ALL, + })], + compilation_options: Default::default(), + }), + multiview_mask: None, + cache: None, + }); + Renderer { + target: t, + max_texture: device.limits().max_texture_dimension_2d, + ss_blit, + ss_bgl, + ss: None, + ss_ready: false, + image, + image_bgl, + sampler, + textures: Default::default(), + quads: Vec::new(), + tri: solid("sc_tris", "fs_solid", None, depth(wgpu::CompareFunction::Less, true), false), + tri_cut: cut(false), + tri_planned: solid("sc_tris_planned", "fs_solid", None, depth(wgpu::CompareFunction::Less, true), true), + tri_cut_planned: cut(true), + tess, + access_bgl, + access_bind, + access_version: 0, + tri_hl: pipeline("sc_tris_hl", "vs_tri", "fs_tri", tri_layout(), highlight_depth(t.depth), alpha), + pbr: pipeline("sc_pbr", "vs_pbr", "fs_pbr", pbr_layout(), depth(wgpu::CompareFunction::Less, true), None), + trans: pipeline("sc_trans", "vs_tri", "fs_tri", tri_layout(), depth(wgpu::CompareFunction::LessEqual, false), alpha), + glass_far: glass("sc_glass_far", wgpu::Face::Front), + glass_near: glass("sc_glass_near", wgpu::Face::Back), + ghost: pipeline("sc_ghost", "vs_ghost", "fs_tri", tri_layout(), depth(wgpu::CompareFunction::LessEqual, false), alpha), + xray: pipeline("sc_xray", "vs_tri", "fs_tri", tri_layout(), depth(wgpu::CompareFunction::Always, false), alpha), + line: pipeline("sc_lines", "vs_line", "fs_line", line_layout(), depth(wgpu::CompareFunction::LessEqual, false), alpha), + line_hidden: pipeline("sc_lines_hidden", "vs_line", "fs_line", line_layout(), depth(wgpu::CompareFunction::Greater, false), alpha), + overlay: pipeline("sc_overlay", "vs_line", "fs_line_all", line_layout(), depth(wgpu::CompareFunction::Always, false), alpha), + guide_trans: pipeline("sc_guide_trans", "vs_tri", "fs_tri_all", tri_layout(), depth(wgpu::CompareFunction::LessEqual, false), alpha), + guide_line: pipeline("sc_guide_lines", "vs_line", "fs_line_all", line_layout(), depth(wgpu::CompareFunction::LessEqual, false), alpha), + uniform, + bind, + linear_out: t.format.is_srgb(), + model: Batches::default(), + product: Batches::default(), + empty: Batches::default(), + sketch: Batches::default(), + highlight: Batches::default(), + preview: Batches::default(), + } + } +} + +/// Depth state of faces lit over the model (hover, selection): tested, not written, and pulled a +/// little toward the eye. They lie on the model's own faces, but the GPU evaluates a body's plan +/// in f32 while the highlight's copy of the same triangles is evaluated on the CPU, so the two +/// depths differ by rounding and an unbiased equal test lights the face in speckles and wedges. +/// The bias is a few depth steps plus the face's own slope: far less than any real gap. +fn highlight_depth(format: Option) -> Option { + format.map(|format| wgpu::DepthStencilState { + format, + depth_write_enabled: Some(false), + depth_compare: Some(wgpu::CompareFunction::LessEqual), + stencil: Default::default(), + bias: HIGHLIGHT_BIAS, + }) +} + +/// See [`highlight_depth`]. Negative: toward the eye (depth grows away from it). +const HIGHLIGHT_BIAS: wgpu::DepthBiasState = wgpu::DepthBiasState { constant: -8, slope_scale: -1.0, clamp: 0.0 }; + +fn upload(device: &wgpu::Device, label: &str, bytes: &[u8], stride: usize) -> Option { + upload_with(device, label, bytes, stride, wgpu::BufferUsages::VERTEX) +} + +fn upload_with(device: &wgpu::Device, label: &str, bytes: &[u8], stride: usize, usage: wgpu::BufferUsages) -> Option { + if bytes.len() < stride || stride == 0 { + return None; + } + let chunk = buffer_chunk(stride, device.limits().max_buffer_size); + let parts = bytes + .chunks(chunk) + .filter(|part| part.len() >= stride) + .map(|part| { + let buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some(label), contents: part, usage }); + (buffer, u32::try_from(part.len() / stride).unwrap_or(0)) + }) + .collect(); + Some(Batch { parts, chunk }) +} + +/// Bytes per GPU buffer for vertices of `stride` bytes: within the device's limit and a +/// whole number of triangles and line pairs, so no primitive straddles two buffers. +fn buffer_chunk(stride: usize, max_buffer_size: u64) -> usize { + let unit = stride.max(1) * 6; + let max = usize::try_from(max_buffer_size).unwrap_or(usize::MAX).min(1 << 30); + (max / unit).max(1) * unit +} + +/// Triangles (3 vertices of `TRI_SIZE` bytes each, position first) ordered far to near along +/// the view direction `back` (toward the eye), so blended glass draws back to front. +pub fn sort_back_to_front(bytes: &[u8], back: [f32; 3]) -> Vec { + let tri = TRI_SIZE * 3; + let depth = |t: &[u8]| -> f32 { + let f = |o: usize| t.get(o..o + 4).and_then(|b| b.try_into().ok()).map_or(0.0, f32::from_le_bytes); + (0..3).map(|v| (0..3).map(|k| f(v * TRI_SIZE + k * 4) * back[k]).sum::()).sum::() + }; + let mut tris: Vec<(f32, &[u8])> = bytes.chunks_exact(tri).map(|t| (depth(t), t)).collect(); + tris.sort_by(|a, b| a.0.total_cmp(&b.0)); + tris.into_iter().flat_map(|(_, t)| t.iter().copied()).collect() +} + +impl Batches { + /// Re-sort the glass for a new view direction (when it turned more than about 2 degrees). + fn sort_glass(&mut self, queue: &wgpu::Queue, back: [f32; 3]) { + let (Some(g), false) = (&self.glass, self.glass_cpu.is_empty()) else { return }; + let turned = self.glass_sorted_for.is_none_or(|s| s[0] * back[0] + s[1] * back[1] + s[2] * back[2] < 0.9994); + if turned { + let sorted = sort_back_to_front(&self.glass_cpu, back); + for ((buffer, _), bytes) in g.parts.iter().zip(sorted.chunks(g.chunk.max(1))) { + queue.write_buffer(buffer, 0, bytes); + } + self.glass_sorted_for = Some(back); + } + } +} + +/// The tessellation pipeline (`shader`: its source), where display plans are evaluated: on a +/// device that runs compute shaders with the storage buffers the evaluation binds (not WebGL2) +/// and builds the pipeline. Elsewhere `None`, and bodies are built on the CPU: a device whose +/// shader compiler rejects the shader (D3D12's FXC once did) only loses GPU evaluation. +pub fn tessellation(adapter: &wgpu::Adapter, device: &wgpu::Device, queue: &wgpu::Queue, shader: &str) -> Option { + let compute = adapter.get_downlevel_capabilities().flags.contains(wgpu::DownlevelFlags::COMPUTE_SHADERS) + && device.limits().max_storage_buffers_per_shader_stage >= 4; + if !compute { + return None; + } + let info = adapter.get_info(); + if hangs_on_gpu_tessellation(info.backend, &info.name) || std::env::var_os("SOLIDCRAFT_CPU_TESS").is_some() { + log::warn!("bodies are built on the CPU on {} ({:?})", info.name, info.backend); + return None; + } + match crate::TessGpu::with_shader(info.name.clone(), device.clone(), queue.clone(), shader) { + Ok(t) => Some(t), + Err(e) => { + log::warn!("bodies are built on the CPU on {} ({:?}): {e}", info.name, info.backend); + None + } + } +} + +/// A device whose driver hangs on the evaluation shader, so bodies are built on the CPU there: +/// the AMD FirePro D300/D500/D700 (Mac Pro 2013, Tahiti) under Metal, where macOS resets the GPU +/// and the whole desktop freezes. `SOLIDCRAFT_CPU_TESS=1` forces CPU evaluation on any device. +pub fn hangs_on_gpu_tessellation(backend: wgpu::Backend, name: &str) -> bool { + backend == wgpu::Backend::Metal && name.contains("FirePro") +} + +impl Renderer { + /// Before the frame's render pass: upload the scenes that changed (planned bodies not yet on + /// the GPU are evaluated by dispatches recorded into `encoder`), the uniform, the images and + /// the accessibility map, and draw the frame supersampled when it asks for that. + pub fn prepare(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, frame: &Frame) { + let res = self; + let cb = frame; + if cb.product { + res.product.take(device, cb.key, &cb.slot, None); + res.product.sort_glass(queue, cb.back); + queue.write_buffer(&res.uniform, 0, &uniform_bytes(cb, cb.size_px[0], cb.size_px[1], res.linear_out)); + return; + } + res.model.take(device, cb.key, &cb.slot, res.tess.as_ref().map(|t| (t, &mut *encoder))); + res.sketch.take(device, cb.sketch_key, &cb.sketch_slot, None); + res.highlight.take(device, cb.hl_key, &cb.hl_slot, None); + res.preview.take(device, cb.pv_key, &cb.pv_slot, None); + res.model.sort_glass(queue, cb.back); + queue.write_buffer(&res.uniform, 0, &uniform_bytes(cb, cb.size_px[0], cb.size_px[1], res.linear_out)); + if let Some(a) = &cb.access + && a.version != res.access_version + { + res.access_bind = access_texture(device, Some(queue), &res.access_bgl, a.size, &a.depth); + res.access_version = a.version; + } + // 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(); + for img in &cb.images { + let [w, h] = img.size; + if w == 0 || h == 0 || img.rgba.len() != (w as usize) * (h as usize) * 4 { + continue; + } + if res.textures.get(&img.id).is_none_or(|t| t.0 != img.version) { + let size = wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }; + let tex = device.create_texture(&wgpu::TextureDescriptor { + label: Some("sc_image"), + size, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + queue.write_texture( + wgpu::TexelCopyTextureInfo { texture: &tex, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, + &img.rgba, + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(4 * w), rows_per_image: Some(h) }, + size, + ); + let view = tex.create_view(&Default::default()); + let bind = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("sc_image"), + layout: &res.image_bgl, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&view) }, + wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(&res.sampler) }, + ], + }); + res.textures.insert(img.id, (img.version, bind)); + } + let c = img.corners; + let uv = [[0.0_f32, 1.0], [1.0, 1.0], [1.0, 0.0], [0.0, 0.0]]; + let mut bytes = Vec::with_capacity(6 * IMG_SIZE); + for k in [0, 1, 2, 0, 2, 3] { + for v in c[k].iter().chain(&uv[k]).chain(std::iter::once(&img.opacity)) { + bytes.extend_from_slice(&v.to_le_bytes()); + } + } + if let Some(b) = upload(device, "sc_image_quad", &bytes, IMG_SIZE) { + res.quads.push((img.id, b)); + } + } + res.ss_ready = cb.ssaa != 1.0 && res.supersample(device, encoder, cb); + } + + /// Draw the frame into `pass` within `viewport` (x, y, width, height in physical pixels): + /// filtered down from the supersampled frame [`Renderer::prepare`] drew, or drawn directly. + pub fn paint(&self, frame: &Frame, pass: &mut wgpu::RenderPass<'static>, viewport: [f32; 4]) { + let [x, y, w, h] = viewport; + if !(w > 0.0 && h > 0.0) { + return; + } + pass.set_viewport(x, y, w, h, 0.0, 1.0); + if self.ss_ready + && let Some(ss) = &self.ss + { + pass.set_pipeline(&self.ss_blit); + pass.set_bind_group(0, &ss.bind, &[]); + pass.draw(0..3, 0..1); + return; + } + self.draw(frame, pass); + } + + /// The target the pipelines draw into. + pub fn target(&self) -> GpuTarget { + self.target + } +} + +impl Renderer { + /// Draw the frame's scenes into `pass` (its viewport already set). + fn draw(&self, cb: &Frame, pass: &mut wgpu::RenderPass<'static>) { + let res = self; + pass.set_bind_group(0, &res.bind, &[]); + let tris = |pass: &mut wgpu::RenderPass<'static>, p: &wgpu::RenderPipeline, b: &Option| { + if let Some(b) = b { + pass.set_pipeline(p); + for (buffer, count) in &b.parts { + pass.set_vertex_buffer(0, buffer.slice(..)); + pass.draw(0..*count, 0..1); + } + } + }; + let lines = |pass: &mut wgpu::RenderPass<'static>, p: &wgpu::RenderPipeline, b: &Option| { + if let Some(b) = b { + pass.set_pipeline(p); + for (buffer, count) in &b.parts { + pass.set_vertex_buffer(0, buffer.slice(..)); + pass.draw(0..6, 0..*count); + } + } + }; + 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) }; + lines(pass, &res.overlay, &m.under); + lines(pass, &res.overlay, &sk.under); + pass.set_bind_group(1, &res.access_bind, &[]); + let planned = |pass: &mut wgpu::RenderPass<'static>, p: &wgpu::RenderPipeline| { + for d in &m.planned { + pass.set_pipeline(p); + pass.set_vertex_buffer(0, d.mesh.vertices.slice(..)); + pass.set_vertex_buffer(1, d.colors.slice(..)); + pass.set_index_buffer(d.mesh.indices.slice(..), wgpu::IndexFormat::Uint32); + pass.draw_indexed(0..d.mesh.index_count, 0, 0..1); + } + }; + let sectioned = cb.clip[..3].iter().map(|c| c * c).sum::() > 0.25; + match (res.tri_cut.as_ref().filter(|_| sectioned), res.tri_cut_planned.as_ref()) { + (Some((mark, cap)), Some((mark_planned, cap_planned))) => { + pass.set_stencil_reference(1); + tris(pass, mark, &m.tris); + tris(pass, mark, &pv.tris); + planned(pass, mark_planned); + tris(pass, cap, &m.tris); + tris(pass, cap, &pv.tris); + planned(pass, cap_planned); + } + _ => { + tris(pass, &res.tri, &m.tris); + tris(pass, &res.tri, &pv.tris); + planned(pass, &res.tri_planned); + } + } + tris(pass, &res.pbr, &m.pbr); + tris(pass, &res.tri_hl, &h.tris); + lines(pass, &res.line, &m.lines); + lines(pass, &res.line, &sk.lines); + lines(pass, &res.line_hidden, &m.hidden); + lines(pass, &res.line_hidden, &h.hidden); + lines(pass, &res.line, &pv.lines); + lines(pass, &res.line, &h.lines); + lines(pass, &res.guide_line, &h.guide_lines); + for (id, q) in res.quads.iter().filter(|_| !cb.product) { + if let Some((_, bind)) = res.textures.get(id) { + pass.set_pipeline(&res.image); + pass.set_bind_group(1, bind, &[]); + for (buffer, count) in &q.parts { + pass.set_vertex_buffer(0, buffer.slice(..)); + pass.draw(0..*count, 0..1); + } + } + } + tris(pass, &res.ghost, &pv.ghost); + tris(pass, &res.glass_far, &m.glass); + tris(pass, &res.glass_near, &m.glass); + tris(pass, &res.trans, &m.trans); + tris(pass, &res.trans, &sk.trans); + tris(pass, &res.trans, &h.trans); + tris(pass, &res.guide_trans, &h.guide_trans); + tris(pass, &res.xray, &pv.xray); + lines(pass, &res.overlay, &m.overlays); + lines(pass, &res.overlay, &sk.overlays); + lines(pass, &res.overlay, &h.overlays); + } +} + +impl Renderer { + /// Draw the frame supersampled (`cb.ssaa` times the viewport's pixels each way, within the + /// device's texture limit and the memory budget) into textures of the viewport's kind. + /// `false` when it cannot be (too small a gain, a zero-sized viewport): drawn as usual. + fn supersample(&mut self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, cb: &Frame) -> bool { + let Some(size) = supersampled_size(cb.size_px, cb.ssaa, self.max_texture, self.target.samples) else { + self.ss = None; + return false; + }; + if self.ss.as_ref().is_none_or(|ss| ss.size != size) { + self.ss = Some(self.supersampled(device, size)); + } + let Some(ss) = &self.ss else { return false }; + let depth_format = self.target.depth; + let mut pass = encoder + .begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("sc_ssaa"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &ss.color, + depth_slice: None, + resolve_target: ss.resolve.as_ref(), + ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), store: wgpu::StoreOp::Store }, + })], + depth_stencil_attachment: ss.depth.as_ref().map(|view| wgpu::RenderPassDepthStencilAttachment { + view, + depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(1.0), store: wgpu::StoreOp::Discard }), + stencil_ops: depth_format + .filter(|f| f.has_stencil_aspect()) + .map(|_| wgpu::Operations { load: wgpu::LoadOp::Clear(0), store: wgpu::StoreOp::Discard }), + }), + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }) + .forget_lifetime(); + pass.set_viewport(0.0, 0.0, size[0] as f32, size[1] as f32, 0.0, 1.0); + self.draw(cb, &mut pass); + true + } + + /// Textures for a supersampled frame of `size` pixels. + fn supersampled(&self, device: &wgpu::Device, size: [u32; 2]) -> Supersampled { + let t = self.target; + let texture = |label: &str, format: wgpu::TextureFormat, samples: u32, usage: wgpu::TextureUsages| { + 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: samples, + dimension: wgpu::TextureDimension::D2, + format, + usage, + view_formats: &[], + }) + .create_view(&Default::default()) + }; + let samples = t.samples.max(1); + let sampled = wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING; + let (color, resolve) = if samples > 1 { + (texture("sc_ssaa_ms", t.format, samples, wgpu::TextureUsages::RENDER_ATTACHMENT), Some(texture("sc_ssaa", t.format, 1, sampled))) + } else { + (texture("sc_ssaa", t.format, 1, sampled), None) + }; + let depth = t.depth.map(|f| texture("sc_ssaa_depth", f, samples, wgpu::TextureUsages::RENDER_ATTACHMENT)); + let bind = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("sc_ssaa"), + layout: &self.ss_bgl, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(resolve.as_ref().unwrap_or(&color)) }, + wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(&self.sampler) }, + ], + }); + Supersampled { size, color, resolve, depth, bind } + } +} + +/// Uniform bytes for a frame. +pub fn uniform_bytes(cb: &Frame, w: f32, h: f32, linear: bool) -> Vec { + let mut v: Vec = cb.view_proj.iter().flatten().copied().collect(); + v.extend([cb.back[0], cb.back[1], cb.back[2], if linear { 1.0 } else { 0.0 }]); + v.extend([w.max(1.0), h.max(1.0), 2e-4, if cb.outline { 1.0 } else { 0.0 }]); + v.extend(cb.clip); + v.extend(cb.cap); + v.extend(cb.analysis); + match &cb.access { + Some(a) => { + v.extend(a.u); + v.extend(a.v); + } + None => v.extend([0.0; 8]), + } + v.extend(cb.eye); + v.extend(cb.analysis_colors); + v.iter().flat_map(|x| x.to_le_bytes()).collect() +} + +/// The shader's analysis colours (`ana_c`: draft positive, between, negative; reachable, +/// blocked; curvature flat, middle, tight; alpha 1) and flags (`ana_f.x`: 1 to stripe the bad +/// faces). +pub fn analysis_colors(c: &solidcraft_render::AnalysisColors) -> [f32; 36] { + let mut v = [0.0; 36]; + let colors = c.draft.iter().chain(&c.access).chain(&c.curvature).flat_map(|rgb| [rgb[0], rgb[1], rgb[2], 1.0]); + for (slot, x) in v.iter_mut().zip(colors) { + *slot = x; + } + v[32] = if c.hatch { 1.0 } else { 0.0 }; + v +} + +#[cfg(test)] +mod tests { + + /// Only the FirePro under Metal skips GPU evaluation; the same card under another backend + /// and other Metal GPUs keep it. + #[test] + fn firepro_under_metal_builds_bodies_on_the_cpu() { + assert!(super::hangs_on_gpu_tessellation(wgpu::Backend::Metal, "AMD FirePro D500")); + assert!(super::hangs_on_gpu_tessellation(wgpu::Backend::Metal, "AMD FirePro D700")); + assert!(!super::hangs_on_gpu_tessellation(wgpu::Backend::Metal, "Apple M2")); + assert!(!super::hangs_on_gpu_tessellation(wgpu::Backend::Metal, "AMD Radeon Pro 560X")); + assert!(!super::hangs_on_gpu_tessellation(wgpu::Backend::Vulkan, "AMD FirePro W5100")); + } + + /// The viewport shader parses and validates (a bad shader would only fail at run time). + #[test] + fn shader_is_valid() { + let module = naga::front::wgsl::parse_str(super::SHADER).unwrap_or_else(|e| panic!("{}", e.emit_to_string(super::SHADER))); + naga::valid::Validator::new(naga::valid::ValidationFlags::all(), naga::valid::Capabilities::empty()).validate(&module).unwrap(); + } + + /// Derivatives and implicit-lod sampling run only in uniform control flow: browsers' WGSL + /// compilers (Tint) reject them after a branch, and the whole viewport shader then fails, + /// a black screen on the web (naga accepts it). Every fragment entry point makes such calls + /// (directly or through a helper) before its first branch or return. + #[test] + fn derivatives_only_in_uniform_control_flow() { + // Without comments (their words are not code). + let src: String = super::SHADER.lines().map(|l| l.split("//").next().unwrap_or("")).collect::>().join("\n"); + let src = src.as_str(); + let derivs = ["dpdx(", "dpdy(", "fwidth(", "textureSample("]; + // Functions: name -> body. + let mut fns: Vec<(String, String, bool)> = Vec::new(); + let mut rest = src; + let mut fragment = false; + while let Some(at) = rest.find("fn ") { + let before = &rest[..at]; + if before.contains("@fragment") { + fragment = true; + } + let Some(open) = rest[at..].find('{') else { break }; + let name = rest[at + 3..].split('(').next().unwrap_or("").trim().to_string(); + let start = at + open; + let mut depth = 0; + let mut end = start; + for (k, ch) in rest[start..].char_indices() { + match ch { + '{' => depth += 1, + '}' => { + depth -= 1; + if depth == 0 { + end = start + k; + break; + } + } + _ => {} + } + } + fns.push((name, rest[start..=end].to_string(), fragment)); + fragment = false; + rest = &rest[end + 1..]; + } + // Helpers that take derivatives (directly or through another helper). + let mut uses: Vec = Vec::new(); + for _ in 0..8 { + for (n, body, _) in &fns { + if !uses.contains(n) && (derivs.iter().any(|d| body.contains(d)) || uses.iter().any(|u| body.contains(&format!("{u}(")))) { + uses.push(n.clone()); + } + } + } + for (n, body, frag) in &fns { + let calls: Vec = derivs + .iter() + .map(|d| d.to_string()) + .chain(uses.iter().map(|u| format!("{u}("))) + .flat_map(|c| body.match_indices(&c).map(|(i, _)| i).collect::>()) + .collect(); + if calls.is_empty() { + continue; + } + if !*frag { + // A helper: its own derivatives must come before any branch or return in it. + let first = ["if (", "return", "discard"].iter().filter_map(|k| body.find(k)).min().unwrap_or(usize::MAX); + for d in derivs { + if let Some(i) = body.find(d) { + assert!(i < first, "{n}: {d} after a branch"); + } + } + continue; + } + let first = ["if (", "return", "discard"].iter().filter_map(|k| body.find(k)).min().unwrap_or(usize::MAX); + for c in calls { + assert!(c < first, "fragment {n}: a derivative after a branch or return: {}", &body[c..(c + 40).min(body.len())]); + } + } + } +} + +#[cfg(test)] +mod glass_tests { + use super::*; + + /// A large import's triangles once went into one buffer past the device's limit (524 MB + /// against 256 MB) and the app crashed (#883): they are split into whole triangles. + #[test] + fn large_scenes_are_split_into_buffers_within_the_device_limit() { + let limit = 256u64 << 20; + for stride in [TRI_SIZE, LINE_SIZE, 4] { + let chunk = buffer_chunk(stride, limit); + assert!(chunk as u64 <= limit && chunk > limit as usize / 2); + assert_eq!(chunk % (stride * 3), 0, "whole triangles"); + assert_eq!(chunk % (stride * 2), 0, "whole line pairs"); + } + let scene = 524_434_680usize; + assert_eq!(scene.div_ceil(buffer_chunk(TRI_SIZE, limit)), 2); + assert!(buffer_chunk(TRI_SIZE, 1) >= TRI_SIZE * 6, "a tiny limit still holds one unit"); + } + + #[test] + fn glass_is_drawn_far_to_near() { + // Two triangles at z = 5 and z = -5, given near first; looking down from +Z. + let mut sc = GpuScene::default(); + for z in [5.0f32, -5.0] { + for p in [[0.0, 0.0, z], [1.0, 0.0, z], [0.0, 1.0, z]] { + sc.glass_tri(p, [0.0, 0.0, 1.0], [255, 0, 0, 100]); + } + } + let sorted = sort_back_to_front(&sc.glass, [0.0, 0.0, 1.0]); + let z0 = f32::from_le_bytes(sorted[8..12].try_into().unwrap()); + assert_eq!(z0, -5.0, "the far triangle first"); + assert_eq!(sorted.len(), sc.glass.len()); + // Seen from below, the order flips. + let sorted = sort_back_to_front(&sc.glass, [0.0, 0.0, -1.0]); + assert_eq!(f32::from_le_bytes(sorted[8..12].try_into().unwrap()), 5.0); + } +} diff --git a/crates/gpu/tests/capture.rs b/crates/gpu/tests/capture.rs new file mode 100644 index 000000000..e71d3a7ff --- /dev/null +++ b/crates/gpu/tests/capture.rs @@ -0,0 +1,168 @@ +//! Headless pictures drawn with the viewport's pipelines: what they show (appearances, guides, +//! silhouettes, the section and its cap, surface analysis) and that bad requests are errors. +//! GPU output differs a little between drivers, so the checks count pixels of a kind rather than +//! compare bytes. Skipped, with the reason printed, on a machine without a GPU adapter +//! (`SOLIDCRAFT_REQUIRE_GPU=1` makes that a failure). + +use serde_json::json; +use solidcraft_engine::Session; +use solidcraft_engine::geom::Vec3; +use solidcraft_engine::render::{Camera, Rgb, SceneLine}; +use solidcraft_engine::view::{self, Guides, colors}; +use solidcraft_gpu::GpuError; +use solidcraft_gpu::capture::{self, Capturer}; + +fn capturer() -> Option<&'static Capturer> { + match capture::shared() { + Ok(c) => { + eprintln!("GPU: {} ({}x MSAA)", c.adapter_name(), c.samples()); + Some(c) + } + Err(e @ GpuError::NoAdapter(_)) if std::env::var_os("SOLIDCRAFT_REQUIRE_GPU").is_none() => { + eprintln!("skipping: {e}"); + None + } + Err(e) => panic!("{e}"), + } +} + +/// RGBA pixels as `[r, g, b, a]`. +fn pixels(img: &[u8]) -> impl Iterator + '_ { + img.as_chunks::<4>().0.iter().copied() +} + +fn session(script: &[(&str, serde_json::Value)]) -> Session { + let mut s = Session::default(); + for (c, p) in script { + s.execute(c, p).unwrap(); + } + s +} + +/// Appearances show as the viewport shows them: a body's colour, a face's own look. +#[test] +fn pictures_show_appearances() { + let Some(c) = capturer() else { return }; + let s = session(&[ + ("solid.box", json!({"length": 40, "width": 30, "height": 20})), + ("solid.cylinder", json!({"diameter": 14, "height": 30, "base": [50, 15, 0], "operation": "new"})), + ("appearance.assign", json!({"bodies": ["Body2"], "color": [220, 60, 40]})), + ("appearance.assign", json!({"faces": [[20, 15, 20]], "body": "Body1", "color": [40, 170, 80]})), + ]); + let cam = view::home_camera(&s); + let img = c.rgba(&view::scene(&s, &cam), &cam, 200, 140).unwrap(); + assert_eq!(img.len(), 200 * 140 * 4); + let green = pixels(&img).filter(|p| p[1] > 120 && p[0] < 90 && p[2] < 110).count(); + let red = pixels(&img).filter(|p| p[0] > 150 && p[1] < 90 && p[2] < 80).count(); + assert!(green > 100 && red > 100, "green top {green}, red cylinder {red} pixels"); + assert!(pixels(&img).all(|p| p[3] == 255), "the picture is opaque"); +} + +/// The ground grid and the origin's axes each change the picture. +#[test] +fn guides_change_the_picture() { + let Some(c) = capturer() else { return }; + let s = session(&[("solid.box", json!({"length": 40, "width": 30, "height": 20, "corner": [10, -15, -10]}))]); + let cam = view::home_camera(&s); + let picture = |grid, axes| c.rgba(&view::scene_with_guides(&s, &cam, None, Guides { grid, axes }), &cam, 160, 100).unwrap(); + let (all, no_grid, no_axes, bare) = (picture(true, true), picture(false, true), picture(true, false), picture(false, false)); + assert!(all != no_grid && all != no_axes && no_grid != bare && no_axes != bare); +} + +/// Curved surfaces get a dark silhouette where they turn away (the viewport's outline). +#[test] +fn pictures_draw_silhouettes_on_curved_surfaces() { + let Some(c) = capturer() else { return }; + let s = session(&[("solid.sphere", json!({"diameter": 20}))]); + let cam = view::home_camera(&s); + let img = c.rgba(&view::scene_with_guides(&s, &cam, None, Guides { grid: false, axes: false }), &cam, 400, 400).unwrap(); + let dark = pixels(&img).filter(|p| p[0] < 90 && p[1] < 90 && p[2] < 95).count(); + assert!(dark > 40, "silhouette pixels: {dark}"); +} + +/// A section shows: the cut part is gone, the cut face hides what lies inside the body behind +/// it and shows in the cap colour. +#[test] +fn pictures_show_the_section_and_its_cap() { + let Some(c) = capturer() else { return }; + let mut s = session(&[("solid.box", json!({"length": 40, "width": 30, "height": 20}))]); + let cam = view::home_camera(&s); + let whole = c.rgba(&view::scene(&s, &cam), &cam, 200, 140).unwrap(); + // Cut away the front half (y < 15), so the iso camera looks into the cut. + s.execute("inspect.section", &json!({"plane": {"origin": [0, 15, 0], "normal": [0, -1, 0]}})).unwrap(); + let cut = c.rgba(&view::scene(&s, &cam), &cam, 200, 140).unwrap(); + let changed = pixels(&whole).zip(pixels(&cut)).filter(|(a, b)| a != b).count(); + assert!(changed > 500, "{changed} pixels changed"); + for fov in [0.0, 0.6] { + let mut cam = view::home_camera(&s); + cam.fov = fov; + let mut sc = view::scene(&s, &cam); + // A marker inside the body, behind the cut face. + let red = Rgb(255, 0, 0); + sc.lines.push(SceneLine { points: vec![Vec3::new(5.0, 25.0, 10.0), Vec3::new(35.0, 25.0, 10.0)], color: red, width: 3.0, on_top: false }); + let img = c.rgba(&sc, &cam, 300, 220).unwrap(); + let marker = pixels(&img).filter(|p| p[0] > 200 && p[1] < 60 && p[2] < 60).count(); + assert_eq!(marker, 0, "fov {fov}: the inside shows through the cut face"); + // The cap: warm (red over blue), unlike the grey-blue body and background. + let cap = pixels(&img).filter(|p| i32::from(p[0]) - i32::from(p[2]) > 20).count(); + assert!(cap > 500, "fov {fov}: cap pixels {cap}"); + } +} + +/// Surface analysis shades headless pictures as it shades the viewport: a box's flat faces in +/// the curvature map's flat colour, zebra stripes in black and white, the accessibility analysis +/// in reachable and blocked colours. +#[test] +fn pictures_show_the_surface_analysis() { + let Some(c) = capturer() else { return }; + let mut s = session(&[ + ("solid.box", json!({"length": 60, "width": 40, "height": 20})), + ("solid.hole", json!({"position": [30, 20, 20], "diameter": 10, "depth": 20})), + ]); + let cam = view::home_camera(&s); + let picture = |s: &Session| c.rgba(&view::scene_with_guides(s, &cam, None, Guides { grid: false, axes: false }), &cam, 320, 200).unwrap(); + let plain = picture(&s); + s.execute("inspect.curvature_map", &json!({})).unwrap(); + let curvature = picture(&s); + let blue = |img: &[u8]| pixels(img).filter(|p| i32::from(p[2]) - i32::from(p[0]) > 120 && p[1] < 140).count(); + assert!(blue(&curvature) > 3000 && blue(&plain) == 0, "flat faces in the flat colour: {} (plain {})", blue(&curvature), blue(&plain)); + s.execute("inspect.zebra", &json!({})).unwrap(); + let zebra = picture(&s); + let black = pixels(&zebra).filter(|p| p[0] < 40 && p[1] < 40 && p[2] < 40).count(); + let white = pixels(&zebra).filter(|p| p[0] > 225 && p[1] > 225 && p[2] > 225).count(); + assert!(black > 500 && white > 500, "zebra: {black} black, {white} white pixels"); + s.execute("inspect.accessibility", &json!({})).unwrap(); + let access = picture(&s); + let [ok, blocked] = colors_of(solidcraft_engine::render::AnalysisColors::DEFAULT.access); + let near = |p: [u8; 4], c: [u8; 3]| (0..3).all(|k| (i32::from(p[k]) - i32::from(c[k])).abs() < 60); + let (reachable, under) = (pixels(&access).filter(|p| near(*p, ok)).count(), pixels(&access).filter(|p| near(*p, blocked)).count()); + assert!(reachable > 1000 && under > 1000, "accessibility: {reachable} reachable, {under} blocked pixels"); +} + +fn colors_of(c: [[f32; 3]; 2]) -> [[u8; 3]; 2] { + c.map(|rgb| rgb.map(|x| (x * 255.0).round() as u8)) +} + +/// An empty scene is the background gradient: the top colour at the top, the bottom one at the +/// bottom. +#[test] +fn an_empty_picture_is_the_background() { + let Some(c) = capturer() else { return }; + let sc = solidcraft_engine::render::Scene { background: Some((colors::BG_TOP, colors::BG_BOTTOM)), ..Default::default() }; + let img = c.rgba(&sc, &Camera::default(), 64, 64).unwrap(); + let at = |row: usize| pixels(&img).nth(row * 64 + 32).unwrap_or_default(); + let near = |p: [u8; 4], c: Rgb| [p[0], p[1], p[2]].iter().zip([c.0, c.1, c.2]).all(|(a, b)| a.abs_diff(b) <= 3); + assert!(near(at(0), colors::BG_TOP) && near(at(63), colors::BG_BOTTOM), "{:?} {:?}", at(0), at(63)); +} + +/// Sizes outside 1 to the device's limit are errors, not crashes. +#[test] +fn bad_picture_sizes_are_errors() { + let Some(c) = capturer() else { return }; + let sc = solidcraft_engine::render::Scene::default(); + for (w, h) in [(0, 10), (10, 0), (capture::MAX_SIDE + 1, 10), (u32::MAX, u32::MAX)] { + assert!(c.rgba(&sc, &Camera::default(), w, h).is_err(), "{w} x {h}"); + } + // And the device still draws. + assert!(c.rgba(&sc, &Camera::default(), 8, 8).is_ok()); +} diff --git a/crates/mcp/Cargo.toml b/crates/mcp/Cargo.toml index b71ede268..057cca258 100644 --- a/crates/mcp/Cargo.toml +++ b/crates/mcp/Cargo.toml @@ -11,3 +11,7 @@ workspace = true [dependencies] solidcraft-engine = { workspace = true } serde_json = { workspace = true } + +[dev-dependencies] +# The renderer `solidcraft-cli mcp` installs, so the tests' screenshots are drawn as the server's. +solidcraft-gpu = { workspace = true } diff --git a/crates/mcp/src/backend.rs b/crates/mcp/src/backend.rs index b71a67ef0..7d107c165 100644 --- a/crates/mcp/src/backend.rs +++ b/crates/mcp/src/backend.rs @@ -6,7 +6,7 @@ use std::time::Duration; use serde_json::{Value, json}; use solidcraft_engine::Session; -use solidcraft_engine::render::{StandardView, render_png}; +use solidcraft_engine::render::StandardView; use solidcraft_engine::view::Guides; /// Something that answers control-channel methods: `engine.execute`, `engine.commands`, @@ -234,8 +234,8 @@ impl Headless { } } -fn dim(p: &Value, k: &str, default: f64) -> usize { - p.get(k).and_then(Value::as_f64).filter(|x| x.is_finite()).unwrap_or(default).clamp(16.0, 4096.0) as usize +fn dim(p: &Value, k: &str, default: f64) -> u32 { + p.get(k).and_then(Value::as_f64).filter(|x| x.is_finite()).unwrap_or(default).clamp(16.0, 4096.0) as u32 } impl Backend for Headless { @@ -279,11 +279,21 @@ impl Backend for Headless { // The grid and the axes are drawn unless the request leaves them out. let shown = |k: &str| p.get(k).and_then(Value::as_bool).unwrap_or(true); let guides = Guides { grid: shown("grid"), axes: shown("axes") }; - let scene = solidcraft_engine::view::scene_with_guides(s, &cam, s.section, guides); - let png = render_png(&scene, &cam, w, h).ok_or("render failed")?; let path = str_p("path").ok_or("missing `path`")?; - solidcraft_engine::io::vfs::write(path, &png).map_err(|e| format!("{path}: {e}"))?; - Ok(json!({"path": path, "bytes": png.len(), "width": w, "height": h})) + // A path outside the agent's folders is refused before anything is drawn. + solidcraft_engine::io::vfs::check(path).map_err(|e| format!("{path}: {e}"))?; + let scene = solidcraft_engine::view::scene_with_guides(s, &cam, s.section, guides); + // Drawn on the GPU by the renderer the host installed (`solidcraft-cli mcp`). + let png = solidcraft_engine::capture::png(&scene, &cam, w, h)?; + solidcraft_engine::io::vfs::write(path, &png.bytes).map_err(|e| format!("{path}: {e}"))?; + Ok(json!({ + "path": path, + "bytes": png.bytes.len(), + "width": w, + "height": h, + "renderer": png.renderer, + "warning": solidcraft_engine::capture::warning(png.renderer), + })) } "ui.screenshot" => Err("no window in headless mode; use ui.render".into()), other => Err(format!("unknown method `{other}`")), diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 6f8957548..bdb3c11b1 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -10,6 +10,25 @@ fn server() -> Server { Server::new(Box::new(Headless::default())) } +/// Screenshots are drawn on the GPU by the renderer the host installs (`solidcraft-cli mcp`); the +/// tests install the same one. `false`, with the reason printed, on a machine without a GPU +/// adapter: the screenshots are then left out of the test. +fn renders() -> bool { + match solidcraft_gpu::capture::shared() { + Ok(c) => { + solidcraft_engine::capture::install(std::sync::Arc::new(move |scene, cam, w, h| { + c.rgba(scene, cam, w, h).map(|rgba| solidcraft_engine::capture::Picture { rgba, renderer: c.renderer() }).map_err(|e| e.to_string()) + })); + true + } + Err(e @ solidcraft_gpu::GpuError::NoAdapter(_)) if std::env::var_os("SOLIDCRAFT_REQUIRE_GPU").is_none() => { + eprintln!("screenshots left out: {e}"); + false + } + Err(e) => panic!("{e}"), + } +} + fn call(s: &mut Server, id: u64, method: &str, params: Value) -> Value { let line = json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}).to_string(); let r = s.handle_line(&line).expect("reply"); @@ -166,10 +185,12 @@ fn agent_builds_box_fillet_hole() { assert!(rel(volume(&mut s), expect) < 5e-4); // Look at it from the top: a real PNG comes back as an image block. - let img = tool(&mut s, "screenshot", json!({"view": "top", "width": 320, "height": 200})); - assert_eq!(img["type"], "image"); - assert_eq!(img["mimeType"], "image/png"); - assert!(img["data"].as_str().unwrap().starts_with("iVBORw0KGgo"), "not a PNG"); + if renders() { + let img = tool(&mut s, "screenshot", json!({"view": "top", "width": 320, "height": 200})); + assert_eq!(img["type"], "image"); + assert_eq!(img["mimeType"], "image/png"); + assert!(img["data"].as_str().unwrap().starts_with("iVBORw0KGgo"), "not a PNG"); + } // Export, save, start over, open. let dir = std::env::temp_dir().join(format!("solidcraft-mcp-test-{}", std::process::id())); @@ -181,8 +202,10 @@ fn agent_builds_box_fillet_hole() { tool(&mut s, "export", json!({"path": stl.to_string_lossy(), "format": "stl"})); assert!(std::fs::metadata(&stl).unwrap().len() > 1000); let shot = dir.join("shot.png"); - tool(&mut s, "screenshot", json!({"path": shot.to_string_lossy(), "width": 64, "height": 64})); - assert!(std::fs::metadata(&shot).unwrap().len() > 100); + if renders() { + tool(&mut s, "screenshot", json!({"path": shot.to_string_lossy(), "width": 64, "height": 64})); + assert!(std::fs::metadata(&shot).unwrap().len() > 100); + } let design = dir.join("part.solidcraft"); tool(&mut s, "save", json!({"path": design.to_string_lossy()})); tool(&mut s, "new_design", json!({"name": "Empty"})); @@ -524,7 +547,9 @@ fn the_default_folders_are_the_designs_the_recovery_folder_and_the_scratch_folde tool(&mut s, "execute", json!({"command": "parameters.export", "params": {"path": at(&proj, "params.csv")}})); tool(&mut s, "save", json!({"path": at(&proj, "copy.solidcraft")})); tool(&mut s, "open", json!({"path": at(&proj, "part.solidcraft")})); - tool(&mut s, "screenshot", json!({"width": 32, "height": 32})); + if renders() { + tool(&mut s, "screenshot", json!({"width": 32, "height": 32})); + } tool(&mut s, "execute", json!({"command": "doc.recovery_list", "params": {"dir": recovery.to_string_lossy()}})); assert!(proj.join("part.step").exists() && proj.join("copy.solidcraft").exists()); // Hidden files in it, and folders beside it, stay out of reach. @@ -563,7 +588,9 @@ fn tool_calls_stay_inside_the_agents_folders() { tool(&mut s, "save", json!({"path": at(&root, "part.solidcraft")})); tool(&mut s, "export", json!({"path": at(&root, "part.step")})); tool(&mut s, "open", json!({"path": at(&root, "part.solidcraft")})); - tool(&mut s, "screenshot", json!({"path": at(&root, "shot.png"), "width": 64, "height": 64})); + if renders() { + tool(&mut s, "screenshot", json!({"path": at(&root, "shot.png"), "width": 64, "height": 64})); + } let escapes = vec![at(&out, "x.step"), at(&root, "../out/x.step")]; #[cfg(unix)] let mut escapes = escapes; @@ -644,7 +671,9 @@ fn short_names_child() { assert!(windows_refusal(&temp.to_string_lossy()).is_some_and(|why| why.contains("8.3")), "{}", temp.display()); let mut s = Server::new(Box::new(Headless::default())).with_path_scope(Some(crate::agent_scope([]))); tool(&mut s, "execute", json!({"command": "solid.box", "params": {"length": 10, "width": 10, "height": 10}})); - tool(&mut s, "screenshot", json!({"width": 32, "height": 32})); + if renders() { + tool(&mut s, "screenshot", json!({"width": 32, "height": 32})); + } tool(&mut s, "execute", json!({"command": "doc.recovery_list", "params": {}})); // An agent's own short spelling of the scratch folder stays refused. let scratch = crate::scratch_dir().unwrap(); @@ -687,6 +716,9 @@ fn a_bridged_request_carries_the_agents_folders() { /// standard view. #[test] fn screenshot_renders_a_saved_named_view() { + if !renders() { + return; + } let mut s = server(); tool(&mut s, "execute", json!({"command": "solid.box", "params": {"length": 40, "width": 20, "height": 10}})); let camera = json!({"target": [20, 10, 5], "yaw": 0.5, "pitch": -0.6, "distance": 150}); @@ -710,6 +742,9 @@ fn screenshot_renders_a_saved_named_view() { /// `browser.visibility` stays out whatever `axes` says. #[test] fn screenshot_can_leave_the_grid_and_the_axes_out() { + if !renders() { + return; + } let mut s = server(); tool(&mut s, "execute", json!({"command": "solid.box", "params": {"length": 40, "width": 30, "height": 20, "corner": [10, -15, -10]}})); let shot = |s: &mut Server, extra: Value| { diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index 6330899dd..561ecc995 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -658,7 +658,14 @@ fn capture(b: &mut dyn Backend, a: &Map) -> Result<(Vec, Valu _ => (info.get("width").cloned().unwrap_or(Value::Null), info.get("height").cloned().unwrap_or(Value::Null)), }; let bytes = png.len(); - Ok((png, json!({"source": source, "path": keep, "width": w, "height": h, "bytes": bytes}))) + let mut reply = json!({"source": source, "path": keep, "width": w, "height": h, "bytes": bytes}); + // What drew a model render (gpu, gpu-software or cpu), and the warning a CPU render carries. + for k in ["renderer", "warning"] { + if let Some(v) = info.get(k).filter(|v| !v.is_null()) { + reply[k] = v.clone(); + } + } + Ok((png, reply)) } /// Standard base64 with padding (RFC 4648). diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index 8e02c73f8..b988a4ad2 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "solidcraft-render" -description = "SolidCraft view math (orbit camera, projection, picking rays) and a CPU rasterizer for headless snapshots" +description = "SolidCraft view math (orbit camera, projection, picking rays), the description of headless pictures, and product render jobs" version.workspace = true edition.workspace = true license.workspace = true diff --git a/crates/render/src/analysis.rs b/crates/render/src/analysis.rs new file mode 100644 index 000000000..942a16f19 --- /dev/null +++ b/crates/render/src/analysis.rs @@ -0,0 +1,54 @@ +//! Surface analysis as a view draws it: the shading mode and the colours it uses. + +use solidcraft_geom::Vec3; + +/// Surface analysis colours, straight sRGB 0..1 as the shader takes them. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct AnalysisColors { + /// Draft Analysis: at least the draft angle, between, at most minus the angle. + pub draft: [[f32; 3]; 3], + /// Accessibility Analysis: reachable, blocked. + pub access: [[f32; 3]; 2], + /// Curvature Map: flat, the middle of the scale, at or below the analysis radius. + pub curvature: [[f32; 3]; 3], + /// Stripe the negative draft and blocked faces too, so colour is not the only cue. + pub hatch: bool, +} + +impl AnalysisColors { + /// The light theme's colours (no colour vision mode): what headless pictures use. + pub const DEFAULT: AnalysisColors = AnalysisColors { + draft: [[0.20, 0.75, 0.30], [0.95, 0.80, 0.15], [0.85, 0.22, 0.20]], + access: [[0.20, 0.75, 0.30], [0.85, 0.22, 0.20]], + curvature: [[0.15, 0.35, 0.95], [0.10, 0.80, 0.25], [0.90, 0.15, 0.10]], + hatch: false, + }; +} + +impl Default for AnalysisColors { + fn default() -> Self { + AnalysisColors::DEFAULT + } +} + +/// A way of shading the model's faces to judge their shape. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum AnalysisMode { + /// Reflected stripes: `stripes` across the view. + Zebra { stripes: f64 }, + /// Faces by draft angle (degrees) to `pull`. + Draft { pull: Vec3, angle: f64 }, + /// Colour by curvature, reaching the tight end at 1 / `radius`. + Curvature { radius: f64 }, + /// Mirror finish reflecting a studio. + Environment, + /// Reachable along `dir` (facing it, nothing above) or blocked. + Access { dir: Vec3 }, +} + +/// A surface analysis shading a picture: the mode and its colours. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct SceneAnalysis { + pub mode: AnalysisMode, + pub colors: AnalysisColors, +} diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 126ecf9c5..0e12a95a0 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -4,6 +4,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] +mod analysis; mod backend; mod camera; mod curve_display; @@ -11,6 +12,7 @@ pub mod job; pub mod lighting; mod product; mod raster; +mod scene; pub mod studio; pub mod surface; pub mod texture_input; @@ -18,6 +20,7 @@ pub mod texture_interpolation; pub mod texture_lod; pub mod texture_sampling; +pub use analysis::{AnalysisColors, AnalysisMode, SceneAnalysis}; pub use backend::{ Availability, BackendDescriptor, BackendId, ExecutorDescriptor, ExecutorId, MAX_RENDER_ID_BYTES, RenderFeature, RenderFormat, RenderLimits, RenderMode, RenderOperation, RenderPolicy, RenderProfile, RenderRequest, ResolveError, ResolvedRequest, ScratchLayout, builtin_backend, @@ -26,4 +29,5 @@ pub use backend::{ pub use camera::{Camera, CameraAnim, Mat4, Quat, StandardView, UpAxis, ease_in_out}; pub use curve_display::{PixelCurveView, SampledPath, SamplingBudget, SamplingQuality, sample_segment, sample_segment_unclipped}; pub use product::{FaceAppearance, ProductMesh, ProductScene}; -pub use raster::{Canvas, Rgb, SECTION_CAP, Scene, SceneLine, SceneMesh, png, render, render_png, render_transparent}; +pub use raster::{Canvas, render, render_png, render_transparent}; +pub use scene::{Rgb, SECTION_CAP, Scene, SceneLine, SceneMesh, png}; diff --git a/crates/render/src/raster.rs b/crates/render/src/raster.rs index 9946ff72f..a9393ae0f 100644 --- a/crates/render/src/raster.rs +++ b/crates/render/src/raster.rs @@ -1,54 +1,10 @@ //! CPU rasterizer for headless snapshots: z-buffered, smooth-shaded triangles and depth-tested //! lines, rendered at 2× and downsampled for anti-aliasing. -use std::sync::Arc; - -use solidcraft_geom::{Mesh, Vec3}; +use solidcraft_geom::Vec3; use crate::Camera; - -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct Rgb(pub u8, pub u8, pub u8); - -impl Rgb { - fn f(self) -> [f64; 3] { - [self.0 as f64 / 255.0, self.1 as f64 / 255.0, self.2 as f64 / 255.0] - } -} - -pub struct SceneMesh { - pub mesh: Arc, - pub color: Rgb, - /// Faces in colours of their own: (B-rep face index, colour). - pub face_colors: Vec<(u32, Rgb)>, -} - -pub struct SceneLine { - pub points: Vec, - pub color: Rgb, - /// Width in output pixels. - pub width: f64, - /// Draw over everything (sketch geometry being edited). - pub on_top: bool, -} - -#[derive(Default)] -pub struct Scene { - pub meshes: Vec, - pub lines: Vec, - /// Background gradient top → bottom. - pub background: Option<(Rgb, Rgb)>, - /// Scene radius for clipping planes. - pub radius: f64, - /// A section cut: (normal, d); what lies where normal·p > d is cut away, and the inside - /// shows as a hatched cap. - pub clip: Option<(Vec3, f64)>, - /// The colour the section cap is tinted toward (default: [`SECTION_CAP`]). - pub cap: Option, -} - -/// The section cap's default tint, as in the viewport. -pub const SECTION_CAP: Rgb = Rgb(214, 128, 72); +use crate::scene::{Rgb, SECTION_CAP, Scene, png}; /// RGBA pixels plus depth. pub struct Canvas { @@ -220,7 +176,7 @@ pub fn render(scene: &Scene, cam: &Camera, w: usize, h: usize) -> Canvas { *s = s.max(cap_slope); } } - for l in &scene.lines { + for l in scene.grid.iter().chain(&scene.lines) { let col = l.color.f(); let half = (l.width * SS as f64 * 0.5).max(0.5); for seg in l.points.windows(2) { @@ -326,14 +282,6 @@ pub fn render_png(scene: &Scene, cam: &Camera, w: usize, h: usize) -> Option) -> Option> { - let img = image::RgbaImage::from_raw(u32::try_from(w).ok()?, u32::try_from(h).ok()?, rgba)?; - let mut buf = std::io::Cursor::new(Vec::new()); - img.write_to(&mut buf, image::ImageFormat::Png).ok()?; - Some(buf.into_inner()) -} - /// Render on a transparent background: the scene drawn over black and over white, and the /// alpha recovered from the difference (exact for the anti-aliased edges). pub fn render_transparent(scene: &mut Scene, cam: &Camera, w: usize, h: usize) -> Canvas { @@ -359,6 +307,9 @@ pub fn render_transparent(scene: &mut Scene, cam: &Camera, w: usize, h: usize) - mod tests { use super::*; use crate::StandardView; + use crate::scene::{SceneLine, SceneMesh}; + use solidcraft_geom::Mesh; + use std::sync::Arc; /// Lines are cut by the section in 3D: the kept piece ends on the plane. #[test] @@ -391,6 +342,7 @@ mod tests { radius: 20.0, clip: None, cap: None, + ..Default::default() }; let mut cam = Camera { distance: 50.0, ..Default::default() }; cam.set_view(StandardView::Front); diff --git a/crates/render/src/scene.rs b/crates/render/src/scene.rs new file mode 100644 index 000000000..a8700ad31 --- /dev/null +++ b/crates/render/src/scene.rs @@ -0,0 +1,65 @@ +//! What a picture of the model shows, independent of how it is drawn: meshes in colours, lines, +//! the background, a section cut and a surface analysis. The GPU draws it with the viewport's +//! pipelines (`solidcraft_gpu::capture`). + +use std::sync::Arc; + +use solidcraft_geom::{Mesh, Vec3}; + +use crate::SceneAnalysis; + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Rgb(pub u8, pub u8, pub u8); + +impl Rgb { + /// The colour as 0..1 per channel. + pub fn f(self) -> [f64; 3] { + [self.0 as f64 / 255.0, self.1 as f64 / 255.0, self.2 as f64 / 255.0] + } +} + +pub struct SceneMesh { + pub mesh: Arc, + pub color: Rgb, + /// Faces in colours of their own: (B-rep face index, colour). + pub face_colors: Vec<(u32, Rgb)>, +} + +pub struct SceneLine { + pub points: Vec, + pub color: Rgb, + /// Width in output pixels. + pub width: f64, + /// Draw over everything (sketch geometry being edited). + pub on_top: bool, +} + +#[derive(Default)] +pub struct Scene { + pub meshes: Vec, + pub lines: Vec, + /// The ground grid: drawn under everything (the model hides it; it never hides the model). + pub grid: Vec, + /// Background gradient top → bottom. + pub background: Option<(Rgb, Rgb)>, + /// Scene radius for clipping planes. + pub radius: f64, + /// A section cut: (normal, d); what lies where normal·p > d is cut away, and the inside + /// shows as a hatched cap. + pub clip: Option<(Vec3, f64)>, + /// The colour the section cap is tinted toward (default: [`SECTION_CAP`]). + pub cap: Option, + /// A surface analysis shading the meshes (zebra, draft, curvature map, ...). + pub analysis: Option, +} + +/// The section cap's default tint, as in the viewport. +pub const SECTION_CAP: Rgb = Rgb(214, 128, 72); + +/// RGBA pixels (`w × h`) to PNG bytes. +pub fn png(w: usize, h: usize, rgba: Vec) -> Option> { + let img = image::RgbaImage::from_raw(u32::try_from(w).ok()?, u32::try_from(h).ok()?, rgba)?; + let mut buf = std::io::Cursor::new(Vec::new()); + img.write_to(&mut buf, image::ImageFormat::Png).ok()?; + Some(buf.into_inner()) +} diff --git a/crates/ui-egui/src/access.rs b/crates/ui-egui/src/access.rs index 0274704d2..19bdc8ea8 100644 --- a/crates/ui-egui/src/access.rs +++ b/crates/ui-egui/src/access.rs @@ -2,17 +2,12 @@ //! to tell reachable surface from surface under something else. use std::cell::RefCell; -use std::sync::Arc; use solidcraft_engine::SurfaceAnalysis; -use solidcraft_engine::geom::Vec3; use crate::SolveApp; use crate::gpu::AccessMap; -/// Map resolution (pixels per side). -const SIZE: u32 = 1024; - thread_local! { /// The last map, by (model revision, direction). static CACHE: RefCell> = const { RefCell::new(None) }; @@ -33,74 +28,7 @@ pub fn map(app: &SolveApp) -> Option { v.set(v.get() + 1); v.get() }); - let m = build(&meshes.iter().map(|m| m.as_ref()).collect::>(), dir, version)?; + let m = AccessMap::build(&meshes.iter().map(|m| m.as_ref()).collect::>(), dir, version)?; CACHE.with(|c| *c.borrow_mut() = Some((key, m.clone()))); Some(m) } - -/// Rasterise the triangles seen along `dir` (orthographic), keeping the highest point per pixel. -fn build(meshes: &[&solidcraft_engine::geom::Mesh], dir: Vec3, version: u64) -> Option { - let d = dir.normalized()?; - let u = d.cross(if d.x.abs() < 0.9 { Vec3::X } else { Vec3::Y }).normalized()?; - let v = d.cross(u); - let (mut lo, mut hi) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]); - for m in meshes { - for p in &m.positions { - let (a, b) = (p.dot(u), p.dot(v)); - lo = [lo[0].min(a), lo[1].min(b)]; - hi = [hi[0].max(a), hi[1].max(b)]; - } - } - let ext = (hi[0] - lo[0]).max(hi[1] - lo[1]); - if !(ext.is_finite() && ext > 1e-9) { - return None; - } - let n = SIZE as usize; - let scale = (SIZE - 2) as f64 / ext; - // One pixel of margin on each side. - let (ou, ov) = (-lo[0] + 1.0 / scale, -lo[1] + 1.0 / scale); - let mut depth = vec![f32::NEG_INFINITY; n * n]; - for m in meshes { - for t in &m.triangles { - let q: Vec<(f64, f64, f64)> = - t.iter().filter_map(|i| m.positions.get(*i as usize)).map(|p| ((p.dot(u) + ou) * scale, (p.dot(v) + ov) * scale, p.dot(d))).collect(); - let [a, b, c] = q[..] else { continue }; - let area = (b.0 - a.0) * (c.1 - a.1) - (b.1 - a.1) * (c.0 - a.0); - let (x0, x1) = (a.0.min(b.0).min(c.0).floor().max(0.0) as usize, (a.0.max(b.0).max(c.0).ceil() as usize).min(n - 1)); - let (y0, y1) = (a.1.min(b.1).min(c.1).floor().max(0.0) as usize, (a.1.max(b.1).max(c.1).ceil() as usize).min(n - 1)); - // Edge-on triangles: their vertices still count. - if area.abs() < 1e-12 { - for p in [a, b, c] { - let (x, y) = (p.0 as usize, p.1 as usize); - if let Some(z) = depth.get_mut(y * n + x) { - *z = z.max(p.2 as f32); - } - } - continue; - } - for y in y0..=y1 { - for x in x0..=x1 { - let (px, py) = (x as f64 + 0.5, y as f64 + 0.5); - let w0 = ((b.0 - px) * (c.1 - py) - (b.1 - py) * (c.0 - px)) / area; - let w1 = ((c.0 - px) * (a.1 - py) - (c.1 - py) * (a.0 - px)) / area; - let w2 = 1.0 - w0 - w1; - if w0 < -1e-9 || w1 < -1e-9 || w2 < -1e-9 { - continue; - } - let z = (w0 * a.2 + w1 * b.2 + w2 * c.2) as f32; - if let Some(cell) = depth.get_mut(y * n + x) { - *cell = cell.max(z); - } - } - } - } - } - Some(AccessMap { - version, - size: SIZE, - depth: Arc::new(depth), - u: [u.x as f32, u.y as f32, u.z as f32, ou as f32], - v: [v.x as f32, v.y as f32, v.z as f32, ov as f32], - scale: scale as f32, - }) -} diff --git a/crates/ui-egui/src/agent_chat/mod.rs b/crates/ui-egui/src/agent_chat/mod.rs index af90cfbb7..d7a1cefc0 100644 --- a/crates/ui-egui/src/agent_chat/mod.rs +++ b/crates/ui-egui/src/agent_chat/mod.rs @@ -50,7 +50,7 @@ const MAX_PROMPT: usize = 100_000; /// up on a request after five minutes). const APPROVAL_TIMEOUT_MS: f64 = 240_000.0; /// Size of the picture of the view sent with a message. -const VIEW_IMAGE: (usize, usize) = (960, 600); +const VIEW_IMAGE: (u32, u32) = (960, 600); #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum State { @@ -521,8 +521,11 @@ pub fn send(app: &mut SolveApp, ctx: &egui::Context, text: String) { fn start_turn(app: &mut SolveApp, text: String, image: bool) { let mut parts = vec![PromptPart::Text(text.clone())]; - if image && let Some(png) = crate::control::view_png(app, VIEW_IMAGE.0, VIEW_IMAGE.1) { - parts.push(PromptPart::Image { mime: "image/png".into(), base64: backend::base64(&png) }); + if image { + match crate::control::view_png(app, VIEW_IMAGE.0, VIEW_IMAGE.1) { + Ok(png) => parts.push(PromptPart::Image { mime: "image/png".into(), base64: backend::base64(&png) }), + Err(e) => log::warn!("the view's picture is left out of the prompt: {e}"), + } } let label: String = text.lines().next().unwrap_or("").chars().take(48).collect(); app.agent_chat.turn = diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index bf3ced9a5..f7cb7ebe9 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -43,7 +43,7 @@ use std::sync::mpsc::Sender; use serde_json::{Value, json}; use solidcraft_engine::io::vfs; -use solidcraft_engine::render::{StandardView, render_png}; +use solidcraft_engine::render::StandardView; use crate::SolveApp; @@ -172,19 +172,35 @@ pub fn request_scope(app: &SolveApp, params: &Value) -> Result Option> { - let guides = - solidcraft_engine::view::Guides { grid: app.ui.show_grid && !crate::viewport::active_view(app).hide_grid, axes: app.origin_visible() }; - let scene = solidcraft_engine::view::scene_with_palette_and_guides( +/// What a picture of the view shows: the model as the window shows it (theme and colour vision +/// mode, the section the viewport shows: an open Section Analysis dialog's preview, a sketch's +/// Slice), with the grid and the origin's axes as `guides` says. +pub(crate) fn view_scene(app: &SolveApp, guides: solidcraft_engine::view::Guides) -> solidcraft_engine::render::Scene { + solidcraft_engine::view::scene_with_palette_and_guides( &app.session, &app.cam, crate::viewport::section_plane(app), solidcraft_engine::view::world_curve_parts, &crate::viewport::scene_palette(app.ui.dark, app.preferences.color_vision), guides, - ); - render_png(&scene, &app.cam, w, h) + ) +} + +/// The grid and the origin's axes as the window shows them (the Grid and Origin switches). +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() } +} + +/// A picture of the view as the window shows it, RGBA, drawn on the GPU with the viewport's +/// pipelines (the renderer the app installs). +pub(crate) fn view_rgba(app: &SolveApp, w: u32, h: u32) -> Result, String> { + solidcraft_engine::capture::rgba(&view_scene(app, window_guides(app)), &app.cam, w, h).map(|p| p.rgba) +} + +/// [`view_rgba`] as PNG. +pub fn view_png(app: &SolveApp, w: u32, h: u32) -> Result, String> { + let rgba = view_rgba(app, w, h)?; + solidcraft_engine::render::png(w as usize, h as usize, rgba).ok_or_else(|| "PNG encoding failed".to_string()) } pub fn handle(app: &mut SolveApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome { @@ -694,31 +710,32 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) -> _ => Outcome::Screenshot { path: s("path").map(str::to_string) }, }, "ui.render" => { - let w = f("width").unwrap_or(1280.0).clamp(16.0, 8192.0) as usize; - let h = f("height").unwrap_or(800.0).clamp(16.0, 8192.0) as usize; - // In the window's theme and colour vision mode, and cut by the section the viewport shows (an open Section - // Analysis dialog's preview, a sketch's Slice), not only the committed one. - // The grid and the axes as the window shows them (the Grid and Origin switches), unless - // the request says: `grid` and `axes` leave them out of the picture or put them in. + let w = f("width").unwrap_or(1280.0).clamp(16.0, 8192.0) as u32; + let h = f("height").unwrap_or(800.0).clamp(16.0, 8192.0) as u32; + // As the window shows it (`view_scene`). The grid and the axes as the window shows + // them, unless the request says: `grid` and `axes` leave them out or put them in. + let shown = window_guides(app); let guides = solidcraft_engine::view::Guides { - grid: p.get("grid").and_then(Value::as_bool).unwrap_or(app.ui.show_grid && !crate::viewport::active_view(app).hide_grid), - axes: p.get("axes").and_then(Value::as_bool).unwrap_or_else(|| app.origin_visible()), + grid: p.get("grid").and_then(Value::as_bool).unwrap_or(shown.grid), + axes: p.get("axes").and_then(Value::as_bool).unwrap_or(shown.axes), }; - let scene = solidcraft_engine::view::scene_with_palette_and_guides( - &app.session, - &app.cam, - crate::viewport::section_plane(app), - solidcraft_engine::view::world_curve_parts, - &crate::viewport::scene_palette(app.ui.dark, app.preferences.color_vision), - guides, - ); - let Some(png) = render_png(&scene, &app.cam, w, h) else { return err("render failed") }; + // A path outside the request's folders is refused before anything is drawn. + if let Some(Err(e)) = s("path").map(vfs::check) { + return err(e); + } + let scene = view_scene(app, guides); + let png = match solidcraft_engine::capture::png(&scene, &app.cam, w, h) { + Ok(png) => png, + Err(e) => return err(format!("render failed: {e}")), + }; + // What drew it (gpu, gpu-software or cpu), and the warning a CPU render carries. + let (renderer, warning) = (png.renderer, solidcraft_engine::capture::warning(png.renderer)); match s("path") { - Some(path) => match vfs::check(path).and_then(|()| std::fs::write(path, &png)) { - Ok(()) => ok(json!({"path": path, "bytes": png.len()})), + Some(path) => match vfs::check(path).and_then(|()| std::fs::write(path, &png.bytes)) { + Ok(()) => ok(json!({"path": path, "bytes": png.bytes.len(), "renderer": renderer, "warning": warning})), Err(e) => err(e), }, - None => ok(json!({"bytes": png.len()})), + None => ok(json!({"bytes": png.bytes.len(), "renderer": renderer, "warning": warning})), } } "app.quit" => { @@ -949,6 +966,9 @@ mod tests { /// or dark. #[test] fn model_render_is_in_the_windows_theme() { + if !crate::gpu::test_picture_renderer() { + return; + } let mut s = Session::default(); s.execute("solid.box", &json!({"length": 40, "width": 30, "height": 20})).unwrap(); let mut app = SolveApp::new(s, Services::default()); @@ -975,6 +995,9 @@ mod tests { /// preview too, not only a committed `inspect.section`. #[test] fn model_render_shows_the_section_dialog_preview() { + if !crate::gpu::test_picture_renderer() { + return; + } let mut s = Session::default(); s.execute("solid.box", &json!({"length": 40, "width": 30, "height": 20})).unwrap(); let mut app = SolveApp::new(s, Services::default()); @@ -1014,6 +1037,9 @@ mod tests { /// in the request say otherwise for that render. #[test] fn model_render_follows_the_grid_and_origin_switches_unless_asked() { + if !crate::gpu::test_picture_renderer() { + return; + } let mut s = Session::default(); s.execute("solid.box", &json!({"length": 40, "width": 30, "height": 20, "corner": [10, -15, -10]})).unwrap(); let mut app = SolveApp::new(s, Services::default()); @@ -1246,7 +1272,9 @@ mod tests { }; let export = |p: String| json!({"command": "file.export", "params": {"path": p}}); assert_eq!(call("engine.execute", export(at(&root, "a.step")), true)["ok"], true); - assert_eq!(call("ui.render", json!({"path": at(&root, "a.png"), "width": 32, "height": 32}), true)["ok"], true); + if crate::gpu::test_picture_renderer() { + assert_eq!(call("ui.render", json!({"path": at(&root, "a.png"), "width": 32, "height": 32}), true)["ok"], true); + } assert_eq!(call("ui.screenshot", json!({"path": at(&root, "b.png")}), true)["ok"], true); for (method, params) in [ ("engine.execute", export(at(&out, "a.step"))), @@ -1279,7 +1307,6 @@ mod tests { s.execute("component.activate", &json!({"component": "root"})).unwrap(); let mut h = crate::scenario::Harness::new(); h.app = SolveApp::new(s, Services::default()); - h.app.viewport.no_pixels = true; h.frames(2); let before = h.app.cam; // Reading during an animated view change leaves it running (no frames run between). @@ -1341,7 +1368,6 @@ mod tests { } // Nothing shown: nothing to fit. let mut empty = crate::scenario::Harness::new(); - empty.app.viewport.no_pixels = true; let before = empty.app.cam; let r = empty.call("ui.camera", json!({"yaw": 1, "fit": true})); assert!(r["ok"] == false && empty.app.cam == before, "{r}"); @@ -1364,7 +1390,6 @@ mod tests { s.execute("joint.create", &json!({"type": "slider", "a": at("B", 55), "b": at("C", 55), "flip": true, "name": "Rail"})).unwrap(); let mut h = crate::scenario::Harness::new(); h.app = SolveApp::new(s, Services::default()); - h.app.viewport.no_pixels = true; let before = h.app.session.doc.clone(); let drive = |h: &crate::scenario::Harness| match h.app.dialog.as_ref().map(|d| &d.kind) { Some(crate::dialogs::Kind::Assembly(crate::dialogs_assembly::Asm::Drive { joint, values, .. })) => { diff --git a/crates/ui-egui/src/dialogs_assembly_tests.rs b/crates/ui-egui/src/dialogs_assembly_tests.rs index 7ee32d2f7..c306440aa 100644 --- a/crates/ui-egui/src/dialogs_assembly_tests.rs +++ b/crates/ui-egui/src/dialogs_assembly_tests.rs @@ -330,7 +330,6 @@ fn drive_value_takes_the_keyboard() { fn drive_slider_previews_intermediate_positions_before_release() { let mut h = crate::scenario::Harness::new(); h.app = two_boxes(); - h.app.viewport.no_pixels = true; let (a, b) = (occ(&h.app, "A"), occ(&h.app, "B")); h.app .run( diff --git a/crates/ui-egui/src/dialogs_sheet_tests.rs b/crates/ui-egui/src/dialogs_sheet_tests.rs index 8a9f303a1..1265e4ab1 100644 --- a/crates/ui-egui/src/dialogs_sheet_tests.rs +++ b/crates/ui-egui/src/dialogs_sheet_tests.rs @@ -554,7 +554,6 @@ fn flat_app(preset: &str) -> SolveApp { app.start("sheet.flat_pattern"); let Some(Kind::Sheet(Sm::FlatPattern { data, .. })) = app.dialog.as_mut().map(|d| &mut d.kind) else { panic!("flat dialog") }; *data = Some(Ok(flat)); - app.viewport.no_pixels = true; app.preferences.nav = preset.into(); app.preferences.zoom_to_cursor = true; app diff --git a/crates/ui-egui/src/file_load.rs b/crates/ui-egui/src/file_load.rs index 49462e5e2..bfe3b711e 100644 --- a/crates/ui-egui/src/file_load.rs +++ b/crates/ui-egui/src/file_load.rs @@ -554,8 +554,7 @@ fn partial_picture(world: &solidcraft_engine::doc::ModelState, stop: &dyn Fn() - if stop() || !preview_work_fits(&scene, &camera) { return None; } - let canvas = solidcraft_engine::render::render(&scene, &camera, 320, 200); - Some(egui::ColorImage::from_rgba_unmultiplied([320, 200], &canvas.rgba)) + preview_image(&scene, &camera) } #[cfg(not(target_arch = "wasm32"))] @@ -601,12 +600,24 @@ fn saved_picture(preview: solidcraft_engine::io::DesignPreview) -> Option Option { + match solidcraft_engine::capture::rgba(scene, camera, 320, 200) { + Ok(picture) => Some(egui::ColorImage::from_rgba_unmultiplied([320, 200], &picture.rgba)), + Err(e) => { + log::warn!("no preview picture: {e}"); + None + } + } +} + +/// Bound drawing work as well as file size: repeated full-screen triangles (a hostile file) must +/// not monopolize the file worker or a software GPU. Counts each triangle's pixel box at twice the +/// picture's size. #[cfg(not(target_arch = "wasm32"))] fn preview_work_fits(scene: &solidcraft_engine::render::Scene, camera: &solidcraft_engine::render::Camera) -> bool { let mut pixels = 0.0; @@ -950,6 +961,9 @@ mod tests { #[cfg(not(target_arch = "wasm32"))] #[test] fn provisional_picture_renders_without_adopting_cached_meshes() { + if !crate::gpu::test_picture_renderer() { + return; + } let preview = solidcraft_engine::io::DesignPreview { meshes: vec![solidcraft_engine::doc::MeshData { name: "Saved triangle".into(), @@ -965,7 +979,7 @@ mod tests { #[cfg(not(target_arch = "wasm32"))] #[test] - fn repeated_large_preview_triangles_are_a_cache_miss_before_rasterization() { + fn repeated_large_preview_triangles_are_a_cache_miss_before_drawing() { let preview = solidcraft_engine::io::DesignPreview { meshes: vec![solidcraft_engine::doc::MeshData { name: "Hostile overdraw".into(), diff --git a/crates/ui-egui/src/file_load_ui_tests.rs b/crates/ui-egui/src/file_load_ui_tests.rs index a899f0a45..1b791dd4f 100644 --- a/crates/ui-egui/src/file_load_ui_tests.rs +++ b/crates/ui-egui/src/file_load_ui_tests.rs @@ -18,7 +18,6 @@ impl Win { fn new() -> Self { let mut app = SolveApp::new(Session::default(), Default::default()); app.custom_titlebar = true; - app.viewport.no_pixels = true; let mut w = Win { ctx: egui::Context::default(), app, time: 0.0 }; for _ in 0..3 { w.frame(vec![]); diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs index 12ec2b88e..83e2e3f85 100644 --- a/crates/ui-egui/src/gpu.rs +++ b/crates/ui-egui/src/gpu.rs @@ -1,1071 +1,88 @@ -//! GPU viewport: shaded triangles and screen-space wide lines with a depth buffer, drawn in an -//! `egui_wgpu` paint callback. Geometry is uploaded when the scene changes; each frame only the -//! camera uniform changes. Where the device runs compute shaders, opaque bodies are drawn -//! straight from their display plans: the plan is evaluated on the GPU into the vertex buffer -//! the pass draws (see [`PlannedBody`]), with nothing built or read back on the CPU. +//! The GPU viewport in egui: the viewport's pipelines ([`solidcraft_gpu::view`]) drawn in an +//! `egui_wgpu` paint callback. Everything that draws lives in the GPU crate, so headless pictures +//! (`solidcraft-cli snapshot`, MCP screenshots, `ui.render`) use the same pipelines; this is the +//! glue that hands them egui's device and render pass. +#[cfg(all(test, not(target_arch = "wasm32")))] use std::sync::{Arc, Mutex}; use egui_wgpu::wgpu; -use egui_wgpu::wgpu::util::DeviceExt; +pub use solidcraft_gpu::view::{ + AccessMap, BlockBytes, Frame, GpuImage, GpuScene, GpuTarget, LINE_SIZE, PBR_SIZE, PlannedBody, Renderer, SceneBlock, SceneSlot, TRI_SIZE, + supersampled_size, +}; -/// Triangle vertex: position (3 × f32), normal (3 × f32), sRGB colour (4 × u8). -pub const TRI_SIZE: usize = 28; -#[path = "pbr_gpu.rs"] -mod pbr; -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 and their -/// flags (`uniform_bytes`). -const UNIFORM_SIZE: u64 = 352; - -/// 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). -#[derive(Clone)] -pub struct PlannedBody { - pub plan: Arc, - pub face_colors: Vec<[u8; 4]>, -} - -/// CPU-side geometry waiting to be uploaded. The model scene changes with the design; the -/// highlight scene (hover, selection, the origin widget) changes often and is small. -#[derive(Default, Clone)] -pub struct GpuScene { - /// Opaque triangles. A zero normal draws the colour flat (unlit). - pub tris: Vec, - /// Opaque product PBR vertices; linear base color and explicit optical parameters. - pub pbr: Vec, - /// Translucent triangles (alpha from the colour), drawn after the opaque ones without - /// writing depth. - pub trans: Vec, - /// See-through bodies and faces (appearance opacity below 1), closed and outward-wound: - /// their far sides are drawn first, then their near sides, so they read like glass. - pub glass: Vec, - /// Depth-tested lines. - pub lines: Vec, - /// Lines drawn only where the model hides them (hidden edges). - pub hidden: Vec, - /// Lines drawn over everything (active sketch, highlights). - pub overlay: Vec, - /// Translucent triangles pushed slightly back in depth, so they only show where nothing - /// coincides with them (removed material in a preview). - pub ghost: Vec, - /// Translucent triangles drawn through everything (a cut's tool body). - pub xray: Vec, - /// Lines drawn first, under everything (the ground grid: the model hides it, it never - /// hides the model). - pub under: Vec, - /// Origin and construction planes (translucent, like `trans`) and their axes (lines, like - /// `lines`): reference geometry, never cut away by a section (#1229). - pub guide_trans: Vec, - pub guide_lines: Vec, - /// Opaque bodies drawn from their plans on the GPU, like `tris`. - pub planned: Vec, - /// The model's bodies, a few at a time, drawn before the loose geometry above (`tris`, - /// `trans`, `lines` and `hidden` of each block, in order, then the scene's own). A block - /// that comes back unchanged keeps its buffers: a design changing one body at a time (an - /// agent adding bodies over MCP) uploads only the blocks that changed, not the whole model. - pub blocks: Vec, -} - -#[cfg(test)] -impl GpuScene { - /// The blocks' geometry moved into the scene's own lists, in drawing order (for tests that - /// count what the scene holds). - pub fn merged(mut self) -> GpuScene { - let mut out = GpuScene { glass: std::mem::take(&mut self.glass), ..Default::default() }; - for block in std::mem::take(&mut self.blocks) { - out.tris.extend_from_slice(&block.bytes.tris); - out.trans.extend_from_slice(&block.bytes.trans); - out.lines.extend_from_slice(&block.bytes.lines); - out.hidden.extend_from_slice(&block.bytes.hidden); - } - out.tris.append(&mut self.tris); - out.trans.append(&mut self.trans); - out.lines.append(&mut self.lines); - out.hidden.append(&mut self.hidden); - GpuScene { tris: out.tris, trans: out.trans, glass: out.glass, lines: out.lines, hidden: out.hidden, ..self } - } -} - -/// A run of the model's bodies in the scene: their triangles and edges, and a key that names -/// exactly this content (the viewport keeps the bytes while the key comes back). -#[derive(Clone)] -pub struct SceneBlock { - pub key: u64, - pub bytes: Arc, -} - -/// A block's geometry, laid out as in [`GpuScene`]. -#[derive(Default)] -pub struct BlockBytes { - pub tris: Vec, - pub trans: Vec, - pub glass: Vec, - pub lines: Vec, - pub hidden: Vec, -} - -impl GpuScene { - pub fn pbr_tri(&mut self, p: [f32; 3], n: [f32; 3], surface: solidcraft_engine::render::surface::OpaqueSurface) { - let base = surface.base_color().to_f32(); - let parameters = [surface.metallic() as f32, surface.roughness() as f32, surface.dielectric_ior() as f32]; - for value in p.into_iter().chain(n).chain(base).chain(parameters) { - self.pbr.extend_from_slice(&value.to_le_bytes()); - } - } - pub fn tri(&mut self, p: [f32; 3], n: [f32; 3], c: [u8; 4]) { - for v in p.iter().chain(&n) { - self.tris.extend_from_slice(&v.to_le_bytes()); - } - self.tris.extend_from_slice(&c); - } - pub fn trans_tri(&mut self, p: [f32; 3], n: [f32; 3], c: [u8; 4]) { - for v in p.iter().chain(&n) { - self.trans.extend_from_slice(&v.to_le_bytes()); - } - self.trans.extend_from_slice(&c); - } - /// A line shown only where the model hides it. - pub fn hidden_line(&mut self, a: [f32; 3], b: [f32; 3], c: [u8; 4], width: f32) { - for v in a.iter().chain(&b) { - self.hidden.extend_from_slice(&v.to_le_bytes()); - } - self.hidden.extend_from_slice(&c); - self.hidden.extend_from_slice(&width.to_le_bytes()); - } - pub fn glass_tri(&mut self, p: [f32; 3], n: [f32; 3], c: [u8; 4]) { - for v in p.iter().chain(&n) { - self.glass.extend_from_slice(&v.to_le_bytes()); - } - self.glass.extend_from_slice(&c); - } - pub fn ghost_tri(&mut self, p: [f32; 3], n: [f32; 3], c: [u8; 4]) { - for v in p.iter().chain(&n) { - self.ghost.extend_from_slice(&v.to_le_bytes()); - } - self.ghost.extend_from_slice(&c); - } - pub fn xray_tri(&mut self, p: [f32; 3], n: [f32; 3], c: [u8; 4]) { - for v in p.iter().chain(&n) { - self.xray.extend_from_slice(&v.to_le_bytes()); - } - self.xray.extend_from_slice(&c); - } - /// A line under everything (see [`GpuScene::under`]). - pub fn under_line(&mut self, a: [f32; 3], b: [f32; 3], c: [u8; 4], width: f32) { - for v in a.iter().chain(&b) { - self.under.extend_from_slice(&v.to_le_bytes()); - } - self.under.extend_from_slice(&c); - self.under.extend_from_slice(&width.to_le_bytes()); - } - /// A translucent triangle of a plane a section does not cut (see [`GpuScene::guide_trans`]). - pub fn guide_tri(&mut self, p: [f32; 3], c: [u8; 4]) { - for v in p.iter().chain(&[0.0; 3]) { - self.guide_trans.extend_from_slice(&v.to_le_bytes()); - } - self.guide_trans.extend_from_slice(&c); - } - /// A depth-tested line a section does not cut (see [`GpuScene::guide_lines`]). - pub fn guide_line(&mut self, a: [f32; 3], b: [f32; 3], c: [u8; 4], width: f32) { - for v in a.iter().chain(&b) { - self.guide_lines.extend_from_slice(&v.to_le_bytes()); - } - self.guide_lines.extend_from_slice(&c); - self.guide_lines.extend_from_slice(&width.to_le_bytes()); - } - pub fn line(&mut self, a: [f32; 3], b: [f32; 3], c: [u8; 4], width: f32, on_top: bool) { - let out = if on_top { &mut self.overlay } else { &mut self.lines }; - for v in a.iter().chain(&b) { - out.extend_from_slice(&v.to_le_bytes()); - } - out.extend_from_slice(&c); - out.extend_from_slice(&width.to_le_bytes()); - } -} - -pub type SceneSlot = Arc>>; - -/// A reference image (canvas or decal): a textured quad, depth-tested against the model. -#[derive(Clone)] -pub struct GpuImage { - pub id: u64, - /// Changes when the pixels change (the texture is re-uploaded). - pub version: u64, - pub size: [u32; 2], - /// Straight RGBA8, `size[0] * size[1] * 4` bytes. - pub rgba: Arc>, - /// Bottom-left, bottom-right, top-right, top-left of the image. - pub corners: [[f32; 3]; 4], - pub opacity: f32, -} - -/// Image vertex: position (3 × f32), uv (2 × f32), opacity (f32). -const IMG_SIZE: usize = 24; - -/// Per-frame parameters. -pub struct ViewportCallback { - /// Product preview uses its own batches, retaining the Design viewport's uploads. - pub product: bool, - pub key: u64, - pub slot: SceneSlot, - pub sketch_key: u64, - pub sketch_slot: SceneSlot, - /// The highlight scene and its key. - pub hl_key: u64, - pub hl_slot: SceneSlot, - /// The live preview scene and its key. - pub pv_key: u64, - pub pv_slot: SceneSlot, - /// Column-major view-projection. - pub view_proj: [[f32; 4]; 4], - /// Direction toward the eye (for lighting). - pub back: [f32; 3], - /// Viewport size in physical pixels. - pub size_px: [f32; 2], - /// Section cut: (normal, d); fragments with normal·p > d are hidden. A zero normal: none. - pub clip: [f32; 4], - /// Colour of the inside of cut bodies (straight sRGBA, 0..1). - pub cap: [f32; 4], - /// Canvases and decals. - pub images: Vec, - /// Surface analysis: (mode: 0 none, 1 zebra, 2 draft, 3 curvature, 4 environment, - /// 5 accessibility; parameter; scale; size) and the pull / access direction. - pub analysis: [f32; 8], - /// The analysis colours and the stripe flag ([`analysis_colors`]). - pub analysis_colors: [f32; 36], - /// Accessibility: the depth map seen from the access direction. - pub access: Option, - /// Draw silhouette outlines around the model (visual styles with edges). - pub outline: bool, - /// Eye position and 1 for a perspective camera (0: orthographic), for the section cap's depth - /// and the depth bias. - pub eye: [f32; 4], - /// 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). - pub ssaa: f32, -} - -/// Heights of the model seen from a direction (an orthographic depth map): a point is reachable -/// from that direction when nothing lies above it. -#[derive(Clone)] -pub struct AccessMap { - pub version: u64, - pub size: u32, - /// Row-major heights along the direction (−∞ where nothing is). - pub depth: Arc>, - /// Map axes: pixel = (p·u + u.w, p·v + v.w) × scale. - pub u: [f32; 4], - pub v: [f32; 4], - pub scale: f32, -} - -/// Vertices (or line instances) on the GPU, in as many buffers as the device's buffer size -/// limit needs: a large import's triangles can exceed one buffer (#883). -struct Batch { - /// Each buffer and its vertex (instance) count. - parts: Vec<(wgpu::Buffer, u32)>, - /// Bytes per buffer (all but the last are full). - chunk: usize, -} - -/// A chunk of planned bodies on the GPU: their evaluated mesh and a colour per vertex. -struct PlannedDraw { - mesh: Arc, - colors: wgpu::Buffer, -} - -/// A scene block on the GPU, with the bytes it was uploaded from. -struct BlockGpu { - bytes: Arc, - tris: Option, - trans: Option, - lines: Option, - hidden: Option, -} - -/// The blocks' buffers, then the scene's own, as one batch (the blocks' buffers are shared, -/// not copied). -fn joined<'a>(blocks: impl Iterator>, own: Option) -> Option { - let mut parts: Vec<(wgpu::Buffer, u32)> = blocks.flatten().flat_map(|b| b.parts.iter().cloned()).collect(); - let chunk = own.as_ref().map(|b| b.chunk).unwrap_or(0); - parts.extend(own.into_iter().flat_map(|b| b.parts)); - (!parts.is_empty()).then_some(Batch { parts, chunk }) -} - -/// Planned bodies end a GPU chunk one time in this many (by their plan's address), and a chunk -/// holds at most [`MAX_CHUNK_BODIES`]: a scene of a thousand bodies takes a few dozen dispatches -/// once, and a changed body re-evaluates a few dozen bodies, not all of them. -const CHUNK_SPLIT: u64 = 32; -const MAX_CHUNK_BODIES: usize = 128; - -#[derive(Default)] -struct Batches { - /// The scene blocks on the GPU, by key. - blocks: std::collections::HashMap, - key: Option, - tris: Option, - pbr: Option, - trans: Option, - glass: Option, - /// The glass triangles as built, and the view direction they were last sorted for. - glass_cpu: Vec, - glass_sorted_for: Option<[f32; 3]>, - lines: Option, - hidden: Option, - overlays: Option, - ghost: Option, - xray: Option, - under: Option, - guide_trans: Option, - guide_lines: Option, - planned: Vec, - /// Evaluated chunks by their plans' addresses, holding the plans so the addresses stay - /// theirs: a chunk whose plans are unchanged is not evaluated again when the scene is rebuilt. - resident: std::collections::HashMap, (Vec>, Arc)>, -} - -impl Batches { - /// Upload a new scene. Planned bodies not yet on the GPU are evaluated there: their - /// dispatches go into `encoder`, ahead of this frame's render pass. - fn take(&mut self, device: &wgpu::Device, key: u64, slot: &SceneSlot, tess: Option<(&solidcraft_gpu::TessGpu, &mut wgpu::CommandEncoder)>) { - if self.key == Some(key) { - return; - } - if let Some(sc) = slot.lock().ok().and_then(|mut s| s.take()) { - self.planned = match tess { - Some((tess, encoder)) => self.planned(device, tess, encoder, &sc.planned), - None => Vec::new(), - }; - let mut kept = std::mem::take(&mut self.blocks); - let mut blocks: Vec<&BlockGpu> = Vec::with_capacity(sc.blocks.len()); - for block in &sc.blocks { - let gpu = match kept.remove(&block.key).filter(|g| Arc::ptr_eq(&g.bytes, &block.bytes)) { - Some(g) => g, - None => BlockGpu { - bytes: block.bytes.clone(), - tris: upload(device, "sc_tris", &block.bytes.tris, TRI_SIZE), - trans: upload(device, "sc_trans", &block.bytes.trans, TRI_SIZE), - lines: upload(device, "sc_lines", &block.bytes.lines, LINE_SIZE), - hidden: upload(device, "sc_hidden", &block.bytes.hidden, LINE_SIZE), - }, - }; - self.blocks.insert(block.key, gpu); - } - for block in &sc.blocks { - if let Some(g) = self.blocks.get(&block.key) { - blocks.push(g); - } - } - self.tris = joined(blocks.iter().map(|b| &b.tris), upload(device, "sc_tris", &sc.tris, TRI_SIZE)); - self.pbr = upload(device, "sc_pbr", &sc.pbr, PBR_SIZE); - self.trans = joined(blocks.iter().map(|b| &b.trans), upload(device, "sc_trans", &sc.trans, TRI_SIZE)); - self.glass = upload_with(device, "sc_glass", &sc.glass, TRI_SIZE, wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST); - self.glass_cpu = sc.glass; - self.glass_sorted_for = None; - self.lines = joined(blocks.iter().map(|b| &b.lines), upload(device, "sc_lines", &sc.lines, LINE_SIZE)); - self.hidden = joined(blocks.iter().map(|b| &b.hidden), upload(device, "sc_hidden", &sc.hidden, LINE_SIZE)); - self.overlays = upload(device, "sc_overlay", &sc.overlay, LINE_SIZE); - self.ghost = upload(device, "sc_ghost", &sc.ghost, TRI_SIZE); - self.xray = upload(device, "sc_xray", &sc.xray, TRI_SIZE); - self.under = upload(device, "sc_under", &sc.under, LINE_SIZE); - self.guide_trans = upload(device, "sc_guide_trans", &sc.guide_trans, TRI_SIZE); - self.guide_lines = upload(device, "sc_guide_lines", &sc.guide_lines, LINE_SIZE); - self.key = Some(key); - } - } - - /// The planned bodies on the GPU: in chunks of at most `MAX_BATCH` vertices (one for any - /// ordinary scene), each uploaded and evaluated in one dispatch and drawn in one call. A - /// chunk whose plans are unchanged is not evaluated again; colours are rebuilt each time. - fn planned( - &mut self, - device: &wgpu::Device, - tess: &solidcraft_gpu::TessGpu, - encoder: &mut wgpu::CommandEncoder, - bodies: &[PlannedBody], - ) -> Vec { - // Chunks end where a body's own plan says (or when full), so a body whose plan changes - // (an edit, or a refinement as the view zooms in, #1320) re-evaluates only its own - // chunk, not the whole scene. - let mut chunks: Vec> = Vec::new(); - let mut filled = 0usize; - let mut open = false; - for b in bodies { - let n = b.plan.vertex_count(); - match chunks.last_mut() { - Some(c) if open && filled + n <= solidcraft_gpu::MAX_BATCH => c.push(b), - _ => { - chunks.push(vec![b]); - filled = 0; - } - } - filled += n; - let mut h = std::collections::hash_map::DefaultHasher::new(); - std::hash::Hash::hash(&(Arc::as_ptr(&b.plan) as usize), &mut h); - open = !std::hash::Hasher::finish(&h).is_multiple_of(CHUNK_SPLIT) && chunks.last().is_some_and(|c| c.len() < MAX_CHUNK_BODIES); - } - let key = |c: &[&PlannedBody]| c.iter().map(|b| Arc::as_ptr(&b.plan) as usize).collect::>(); - self.resident.retain(|k, _| chunks.iter().any(|c| key(c) == *k)); - let mut out = Vec::with_capacity(chunks.len()); - for chunk in &chunks { - let mesh = match self.resident.get(&key(chunk)) { - Some((_, m)) => m.clone(), - None => { - let plans: Vec<&solidcraft_engine::geom::tess::TessPlan> = chunk.iter().map(|b| &*b.plan).collect(); - match tess.prepare_many(&plans) { - Ok(m) => { - tess.record(encoder, &m); - let m = Arc::new(m); - self.resident.insert(key(chunk), (chunk.iter().map(|b| b.plan.clone()).collect(), m.clone())); - m - } - Err(e) => { - log::warn!("bodies are not drawn on the GPU: {e}"); - continue; - } - } - } - }; - let mut bytes = Vec::with_capacity(mesh.vertex_face.len() * 4); - for (part, b) in mesh.parts.iter().zip(chunk) { - let last = b.face_colors.last().copied().unwrap_or([200, 200, 200, 255]); - let faces = mesh.vertex_face.get(part.vertices.start as usize..part.vertices.end as usize).unwrap_or_default(); - bytes.extend(faces.iter().flat_map(|f| b.face_colors.get(*f as usize).copied().unwrap_or(last))); - } - if let Some((colors, _)) = upload(device, "sc_planned_colors", &bytes, 4).and_then(|c| c.parts.into_iter().next()) { - out.push(PlannedDraw { mesh, colors }); - } - } - out - } -} - -struct Resources { - tri: wgpu::RenderPipeline, - /// `tri` and `tri_cut` for planned bodies (positions and normals from the GPU evaluation, - /// colours per vertex, indexed). - tri_planned: wgpu::RenderPipeline, - tri_cut_planned: Option<(wgpu::RenderPipeline, wgpu::RenderPipeline)>, - /// The tessellation compute pipeline, where the device runs compute shaders. - tess: Option, - /// While a section is shown (when the depth buffer has a stencil): `tri` marking where the - /// cap shows, then the cap again at the section plane's depth, so it hides the inside. - tri_cut: Option<(wgpu::RenderPipeline, wgpu::RenderPipeline)>, - /// Highlight triangles over the model (depth test ≤, no depth write). - tri_hl: wgpu::RenderPipeline, - pbr: wgpu::RenderPipeline, - trans: wgpu::RenderPipeline, - /// Glass: far sides (front faces culled), then near sides (back faces culled). - glass_far: wgpu::RenderPipeline, - glass_near: wgpu::RenderPipeline, - ghost: wgpu::RenderPipeline, - xray: wgpu::RenderPipeline, - line: wgpu::RenderPipeline, - /// Lines behind the model (depth test >). - line_hidden: wgpu::RenderPipeline, - overlay: wgpu::RenderPipeline, - /// Reference planes and axes: as `trans` and `line`, but not cut by a section. - guide_trans: wgpu::RenderPipeline, - guide_line: wgpu::RenderPipeline, - uniform: wgpu::Buffer, - bind: wgpu::BindGroup, - linear_out: bool, - model: Batches, - product: Batches, - empty: Batches, - sketch: Batches, - highlight: Batches, - preview: Batches, - image: wgpu::RenderPipeline, - image_bgl: wgpu::BindGroupLayout, - sampler: wgpu::Sampler, - /// Textures by image id: (version, bind group). - textures: std::collections::HashMap, - /// This frame's quads: (image id, vertices). - quads: Vec<(u64, Batch)>, - access_bgl: wgpu::BindGroupLayout, - /// The accessibility depth map (a 1 × 1 stand-in when there is none) and its version. - access_bind: wgpu::BindGroup, - access_version: u64, - /// The target the pipelines draw into (format, depth, samples): a supersampled frame is - /// drawn into textures of the same kind. - target: GpuTarget, - /// The device's largest 2D texture side (#869). - max_texture: u32, - /// Supersampling (#1288): the filter that draws the supersampled frame into the viewport. - ss_blit: wgpu::RenderPipeline, - ss_bgl: wgpu::BindGroupLayout, - /// The supersampled frame's textures, kept while its size stays. - ss: Option, - /// This frame was drawn supersampled (in `prepare`): `paint` only filters it down. - ss_ready: bool, -} - -/// A supersampled frame: the scene drawn at a multiple of the viewport's pixels. -struct Supersampled { - size: [u32; 2], - /// Drawn into (multisampled with the viewport's MSAA). - color: wgpu::TextureView, - /// The resolved colour (when `color` is multisampled). - resolve: Option, - depth: Option, - /// The single-sampled colour, for the filter. - bind: wgpu::BindGroup, -} - -/// Most memory (bytes) a supersampled frame's colour and depth may take. -const SS_BUDGET: u64 = 384 << 20; - -/// The size (px) to draw a `size` viewport supersampled `factor` times in each direction: -/// within the device's largest texture side (#869) and the memory budget (at `samples` per pixel, -/// four bytes of colour and four of depth each). `None` when that leaves under 1.25×: the frame -/// is drawn as usual. A `factor` under 1 draws it that much smaller, to be filtered up. -pub(crate) fn supersampled_size(size: [f32; 2], factor: f32, max_side: u32, samples: u32) -> Option<[u32; 2]> { - let [w, h] = size; - if w >= 1.0 && h >= 1.0 && factor > 0.0 && factor < 1.0 { - return Some([((w * factor).floor() as u32).clamp(1, max_side.max(1)), ((h * factor).floor() as u32).clamp(1, max_side.max(1))]); - } - if !(w >= 1.0 && h >= 1.0 && factor.is_finite() && factor > 1.0) { - return None; - } - let side = max_side as f32; - let bytes_per_px = 8.0 * samples.max(1) as f32; - let by_memory = (SS_BUDGET as f32 / (w * h * bytes_per_px)).sqrt(); - let f = factor.min(side / w).min(side / h).min(by_memory); - (f >= 1.25).then(|| [((w * f).floor() as u32).clamp(1, max_side), ((h * f).floor() as u32).clamp(1, max_side)]) -} - -/// The filter: each viewport pixel the mean of the supersampled pixels under it (four bilinear -/// taps a quarter of its footprint from its centre: exactly the 2 × 2 box at 2×). -const SS_SHADER: &str = r#" -@group(0) @binding(0) var src: texture_2d; -@group(0) @binding(1) var smp: sampler; -struct O { @builtin(position) pos: vec4, @location(0) uv: vec2 }; -@vertex -fn vs(@builtin(vertex_index) i: u32) -> O { - let x = f32((i << 1u) & 2u); - let y = f32(i & 2u); - var o: O; - o.pos = vec4(x * 2.0 - 1.0, 1.0 - y * 2.0, 0.0, 1.0); - o.uv = vec2(x, y); - return o; -} -@fragment -fn fs(i: O) -> @location(0) vec4 { - let d = vec2(dpdx(i.uv.x), dpdy(i.uv.y)) * 0.25; - let a = textureSampleLevel(src, smp, i.uv + vec2(-d.x, -d.y), 0.0); - let b = textureSampleLevel(src, smp, i.uv + vec2(d.x, -d.y), 0.0); - let c = textureSampleLevel(src, smp, i.uv + vec2(-d.x, d.y), 0.0); - let e = textureSampleLevel(src, smp, i.uv + vec2(d.x, d.y), 0.0); - return (a + b + c + e) * 0.25; -} -"#; - -fn access_texture(device: &wgpu::Device, queue: Option<&wgpu::Queue>, bgl: &wgpu::BindGroupLayout, size: u32, depth: &[f32]) -> wgpu::BindGroup { - let extent = wgpu::Extent3d { width: size.max(1), height: size.max(1), depth_or_array_layers: 1 }; - let tex = device.create_texture(&wgpu::TextureDescriptor { - label: Some("sc_access"), - size: extent, - mip_level_count: 1, - sample_count: 1, - dimension: wgpu::TextureDimension::D2, - format: wgpu::TextureFormat::R32Float, - usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, - view_formats: &[], - }); - if let Some(q) = queue - && depth.len() == (size as usize) * (size as usize) - { - let bytes: Vec = depth.iter().flat_map(|x| x.to_le_bytes()).collect(); - q.write_texture( - wgpu::TexelCopyTextureInfo { texture: &tex, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, - &bytes, - wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(4 * size), rows_per_image: Some(size) }, - extent, - ); - } - let view = tex.create_view(&Default::default()); - device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("sc_access"), - layout: bgl, - entries: &[wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(&view) }], - }) -} - -const SHADER: &str = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/shaders/viewport.wgsl")); - -fn tri_layout() -> wgpu::VertexBufferLayout<'static> { - const A: [wgpu::VertexAttribute; 3] = wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x3, 2 => Unorm8x4]; - wgpu::VertexBufferLayout { array_stride: TRI_SIZE as u64, step_mode: wgpu::VertexStepMode::Vertex, attributes: &A } -} - -/// A planned body's vertices as the GPU evaluation writes them: the position, then the normal -/// at [`solidcraft_gpu::NORMAL_OFFSET`] (each padded to four floats). -fn pbr_layout() -> wgpu::VertexBufferLayout<'static> { - const A: [wgpu::VertexAttribute; 4] = wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x3, 2 => Float32x3, 3 => Float32x3]; - wgpu::VertexBufferLayout { array_stride: PBR_SIZE as u64, step_mode: wgpu::VertexStepMode::Vertex, attributes: &A } -} - -fn planned_layout() -> wgpu::VertexBufferLayout<'static> { - const A: [wgpu::VertexAttribute; 2] = [ - wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x3, offset: 0, shader_location: 0 }, - wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x3, offset: solidcraft_gpu::NORMAL_OFFSET, shader_location: 1 }, - ]; - wgpu::VertexBufferLayout { array_stride: solidcraft_gpu::VERTEX_STRIDE, step_mode: wgpu::VertexStepMode::Vertex, attributes: &A } -} - -/// A planned body's colours, one per vertex. -fn color_layout() -> wgpu::VertexBufferLayout<'static> { - const A: [wgpu::VertexAttribute; 1] = wgpu::vertex_attr_array![2 => Unorm8x4]; - wgpu::VertexBufferLayout { array_stride: 4, step_mode: wgpu::VertexStepMode::Vertex, attributes: &A } -} - -fn line_layout() -> wgpu::VertexBufferLayout<'static> { - const A: [wgpu::VertexAttribute; 4] = wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x3, 2 => Unorm8x4, 3 => Float32]; - wgpu::VertexBufferLayout { array_stride: LINE_SIZE as u64, step_mode: wgpu::VertexStepMode::Instance, attributes: &A } -} - -/// The target configuration: colour format, depth format and MSAA sample count of the app. -#[derive(Clone, Copy, Debug)] -pub struct GpuTarget { - pub format: wgpu::TextureFormat, - pub depth: Option, - pub samples: u32, - /// The device evaluates display plans (compute shaders): bodies may be drawn from them. - pub tess: bool, -} - -impl Resources { - fn new(device: &wgpu::Device, t: GpuTarget, tess: Option) -> Self { - let source = format!("{SHADER}\n{}", pbr::SOURCE); - let module = - device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("sc_viewport"), source: wgpu::ShaderSource::Wgsl(source.into()) }); - let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: Some("sc_viewport"), - entries: &[wgpu::BindGroupLayoutEntry { - binding: 0, - visibility: wgpu::ShaderStages::VERTEX_FRAGMENT, - ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None }, - count: None, - }], - }); - let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { - label: Some("sc_viewport"), - bind_group_layouts: &[Some(&bgl)], - immediate_size: 0, - }); - let uniform = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("sc_viewport_u"), - size: UNIFORM_SIZE, - usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, - mapped_at_creation: false, - }); - let bind = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("sc_viewport"), - layout: &bgl, - entries: &[wgpu::BindGroupEntry { binding: 0, resource: uniform.as_entire_binding() }], - }); - let depth = |compare: wgpu::CompareFunction, write: bool| -> Option { - t.depth.map(|format| wgpu::DepthStencilState { - format, - depth_write_enabled: Some(write), - depth_compare: Some(compare), - stencil: Default::default(), - bias: Default::default(), - }) - }; - let pipeline = |label: &str, - vs: &str, - fs: &str, - buf: wgpu::VertexBufferLayout<'static>, - ds: Option, - blend: Option| { - device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: Some(label), - layout: Some(&layout), - vertex: wgpu::VertexState { module: &module, entry_point: Some(vs), buffers: &[Some(buf)], compilation_options: Default::default() }, - primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() }, - depth_stencil: ds, - multisample: wgpu::MultisampleState { count: t.samples.max(1), mask: !0, alpha_to_coverage_enabled: false }, - fragment: Some(wgpu::FragmentState { - module: &module, - entry_point: Some(fs), - targets: &[Some(wgpu::ColorTargetState { format: t.format, blend, write_mask: wgpu::ColorWrites::ALL })], - compilation_options: Default::default(), - }), - multiview_mask: None, - cache: None, - }) - }; - let alpha = Some(wgpu::BlendState::ALPHA_BLENDING); - let glass = |label: &str, cull: wgpu::Face| { - device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: Some(label), - layout: Some(&layout), - vertex: wgpu::VertexState { - module: &module, - entry_point: Some("vs_tri"), - buffers: &[Some(tri_layout())], - compilation_options: Default::default(), - }, - primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, cull_mode: Some(cull), ..Default::default() }, - depth_stencil: depth(wgpu::CompareFunction::LessEqual, false), - multisample: wgpu::MultisampleState { count: t.samples.max(1), mask: !0, alpha_to_coverage_enabled: false }, - fragment: Some(wgpu::FragmentState { - module: &module, - entry_point: Some("fs_tri"), - targets: &[Some(wgpu::ColorTargetState { format: t.format, blend: alpha, write_mask: wgpu::ColorWrites::ALL })], - compilation_options: Default::default(), - }), - multiview_mask: None, - cache: None, - }) - }; - let image_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: Some("sc_image"), - entries: &[ - wgpu::BindGroupLayoutEntry { - binding: 0, - visibility: wgpu::ShaderStages::FRAGMENT, - ty: wgpu::BindingType::Texture { - sample_type: wgpu::TextureSampleType::Float { filterable: true }, - view_dimension: wgpu::TextureViewDimension::D2, - multisampled: false, - }, - count: None, - }, - wgpu::BindGroupLayoutEntry { - binding: 1, - visibility: wgpu::ShaderStages::FRAGMENT, - ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), - count: None, - }, - ], - }); - let image_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { - label: Some("sc_image"), - bind_group_layouts: &[Some(&bgl), Some(&image_bgl)], - immediate_size: 0, - }); - const IA: [wgpu::VertexAttribute; 3] = wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x2, 2 => Float32]; - let image = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: Some("sc_image"), - layout: Some(&image_layout), - vertex: wgpu::VertexState { - module: &module, - entry_point: Some("vs_img"), - buffers: &[Some(wgpu::VertexBufferLayout { - array_stride: IMG_SIZE as u64, - step_mode: wgpu::VertexStepMode::Vertex, - attributes: &IA, - })], - compilation_options: Default::default(), - }, - primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() }, - depth_stencil: depth(wgpu::CompareFunction::LessEqual, false), - multisample: wgpu::MultisampleState { count: t.samples.max(1), mask: !0, alpha_to_coverage_enabled: false }, - fragment: Some(wgpu::FragmentState { - module: &module, - entry_point: Some("fs_img"), - targets: &[Some(wgpu::ColorTargetState { format: t.format, blend: alpha, write_mask: wgpu::ColorWrites::ALL })], - compilation_options: Default::default(), - }), - multiview_mask: None, - cache: None, - }); - let access_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: Some("sc_access"), - entries: &[wgpu::BindGroupLayoutEntry { - binding: 2, - visibility: wgpu::ShaderStages::FRAGMENT, - ty: wgpu::BindingType::Texture { - sample_type: wgpu::TextureSampleType::Float { filterable: false }, - view_dimension: wgpu::TextureViewDimension::D2, - multisampled: false, - }, - count: None, - }], - }); - let solid_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { - label: Some("sc_solid"), - bind_group_layouts: &[Some(&bgl), Some(&access_bgl)], - immediate_size: 0, - }); - let built = [Some(tri_layout())]; - let evaluated = [Some(planned_layout()), Some(color_layout())]; - let solid = |label: &str, fs: &str, cull: Option, ds: Option, planned: bool| { - device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: Some(label), - layout: Some(&solid_layout), - vertex: wgpu::VertexState { - module: &module, - entry_point: Some("vs_tri"), - buffers: if planned { &evaluated[..] } else { &built[..] }, - compilation_options: Default::default(), - }, - primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, cull_mode: cull, ..Default::default() }, - depth_stencil: ds, - multisample: wgpu::MultisampleState { count: t.samples.max(1), mask: !0, alpha_to_coverage_enabled: false }, - fragment: Some(wgpu::FragmentState { - module: &module, - entry_point: Some(fs), - targets: &[Some(wgpu::ColorTargetState { format: t.format, blend: None, write_mask: wgpu::ColorWrites::ALL })], - compilation_options: Default::default(), - }), - multiview_mask: None, - cache: None, - }) - }; - // While a section is shown: the stencil marking and the cap (see `Resources::tri_cut`). - let cut = |planned: bool| { - t.depth.filter(|f| f.has_stencil_aspect()).map(|format| { - // The visible surface marks the stencil: 1 where it is a back face (the cap). - use wgpu::StencilOperation::{Keep, Replace, Zero}; - let face = |pass_op| wgpu::StencilFaceState { compare: wgpu::CompareFunction::Always, fail_op: Keep, depth_fail_op: Keep, pass_op }; - let mark = wgpu::DepthStencilState { - format, - depth_write_enabled: Some(true), - depth_compare: Some(wgpu::CompareFunction::Less), - stencil: wgpu::StencilState { front: face(Zero), back: face(Replace), read_mask: 0xff, write_mask: 0xff }, - bias: Default::default(), - }; - // Then the cap's back faces again, only there, at the section plane's depth. - let only = wgpu::StencilFaceState { compare: wgpu::CompareFunction::Equal, ..face(Keep) }; - let cap = wgpu::DepthStencilState { - format, - depth_write_enabled: Some(true), - depth_compare: Some(wgpu::CompareFunction::Always), - stencil: wgpu::StencilState { front: only, back: only, read_mask: 0xff, write_mask: 0 }, - bias: Default::default(), - }; - ( - solid("sc_tris_mark", "fs_solid", None, Some(mark), planned), - solid("sc_tris_cap", "fs_solid_cut", Some(wgpu::Face::Front), Some(cap), planned), - ) - }) - }; - let access_bind = access_texture(device, None, &access_bgl, 1, &[]); - let sampler = device.create_sampler(&wgpu::SamplerDescriptor { - label: Some("sc_image"), - mag_filter: wgpu::FilterMode::Linear, - min_filter: wgpu::FilterMode::Linear, - ..Default::default() - }); - let ss_module = - device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("sc_ssaa"), source: wgpu::ShaderSource::Wgsl(SS_SHADER.into()) }); - let ss_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: Some("sc_ssaa"), - entries: &[ - wgpu::BindGroupLayoutEntry { - binding: 0, - visibility: wgpu::ShaderStages::FRAGMENT, - ty: wgpu::BindingType::Texture { - sample_type: wgpu::TextureSampleType::Float { filterable: true }, - view_dimension: wgpu::TextureViewDimension::D2, - multisampled: false, - }, - count: None, - }, - wgpu::BindGroupLayoutEntry { - binding: 1, - visibility: wgpu::ShaderStages::FRAGMENT, - ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), - count: None, - }, - ], - }); - let ss_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { - label: Some("sc_ssaa"), - bind_group_layouts: &[Some(&ss_bgl)], - immediate_size: 0, - }); - // The frame is premultiplied (drawn over transparent black), so it goes over the - // viewport's background premultiplied; the viewport's depth is left as it is. - let ss_blit = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: Some("sc_ssaa"), - layout: Some(&ss_layout), - vertex: wgpu::VertexState { module: &ss_module, entry_point: Some("vs"), buffers: &[], compilation_options: Default::default() }, - primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() }, - depth_stencil: depth(wgpu::CompareFunction::Always, false), - multisample: wgpu::MultisampleState { count: t.samples.max(1), mask: !0, alpha_to_coverage_enabled: false }, - fragment: Some(wgpu::FragmentState { - module: &ss_module, - entry_point: Some("fs"), - targets: &[Some(wgpu::ColorTargetState { - format: t.format, - blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING), - write_mask: wgpu::ColorWrites::ALL, - })], - compilation_options: Default::default(), - }), - multiview_mask: None, - cache: None, - }); - Resources { - target: t, - max_texture: device.limits().max_texture_dimension_2d, - ss_blit, - ss_bgl, - ss: None, - ss_ready: false, - image, - image_bgl, - sampler, - textures: Default::default(), - quads: Vec::new(), - tri: solid("sc_tris", "fs_solid", None, depth(wgpu::CompareFunction::Less, true), false), - tri_cut: cut(false), - tri_planned: solid("sc_tris_planned", "fs_solid", None, depth(wgpu::CompareFunction::Less, true), true), - tri_cut_planned: cut(true), - tess, - access_bgl, - access_bind, - access_version: 0, - tri_hl: pipeline("sc_tris_hl", "vs_tri", "fs_tri", tri_layout(), highlight_depth(t.depth), alpha), - pbr: pipeline("sc_pbr", "vs_pbr", "fs_pbr", pbr_layout(), depth(wgpu::CompareFunction::Less, true), None), - trans: pipeline("sc_trans", "vs_tri", "fs_tri", tri_layout(), depth(wgpu::CompareFunction::LessEqual, false), alpha), - glass_far: glass("sc_glass_far", wgpu::Face::Front), - glass_near: glass("sc_glass_near", wgpu::Face::Back), - ghost: pipeline("sc_ghost", "vs_ghost", "fs_tri", tri_layout(), depth(wgpu::CompareFunction::LessEqual, false), alpha), - xray: pipeline("sc_xray", "vs_tri", "fs_tri", tri_layout(), depth(wgpu::CompareFunction::Always, false), alpha), - line: pipeline("sc_lines", "vs_line", "fs_line", line_layout(), depth(wgpu::CompareFunction::LessEqual, false), alpha), - line_hidden: pipeline("sc_lines_hidden", "vs_line", "fs_line", line_layout(), depth(wgpu::CompareFunction::Greater, false), alpha), - overlay: pipeline("sc_overlay", "vs_line", "fs_line_all", line_layout(), depth(wgpu::CompareFunction::Always, false), alpha), - guide_trans: pipeline("sc_guide_trans", "vs_tri", "fs_tri_all", tri_layout(), depth(wgpu::CompareFunction::LessEqual, false), alpha), - guide_line: pipeline("sc_guide_lines", "vs_line", "fs_line_all", line_layout(), depth(wgpu::CompareFunction::LessEqual, false), alpha), - uniform, - bind, - linear_out: t.format.is_srgb(), - model: Batches::default(), - product: Batches::default(), - empty: Batches::default(), - sketch: Batches::default(), - highlight: Batches::default(), - preview: Batches::default(), - } - } -} - -/// Depth state of faces lit over the model (hover, selection): tested, not written, and pulled a -/// little toward the eye. They lie on the model's own faces, but the GPU evaluates a body's plan -/// in f32 while the highlight's copy of the same triangles is evaluated on the CPU, so the two -/// depths differ by rounding and an unbiased equal test lights the face in speckles and wedges. -/// The bias is a few depth steps plus the face's own slope: far less than any real gap. -fn highlight_depth(format: Option) -> Option { - format.map(|format| wgpu::DepthStencilState { - format, - depth_write_enabled: Some(false), - depth_compare: Some(wgpu::CompareFunction::LessEqual), - stencil: Default::default(), - bias: HIGHLIGHT_BIAS, - }) -} - -/// See [`highlight_depth`]. Negative: toward the eye (depth grows away from it). -const HIGHLIGHT_BIAS: wgpu::DepthBiasState = wgpu::DepthBiasState { constant: -8, slope_scale: -1.0, clamp: 0.0 }; - -fn upload(device: &wgpu::Device, label: &str, bytes: &[u8], stride: usize) -> Option { - upload_with(device, label, bytes, stride, wgpu::BufferUsages::VERTEX) -} - -fn upload_with(device: &wgpu::Device, label: &str, bytes: &[u8], stride: usize, usage: wgpu::BufferUsages) -> Option { - if bytes.len() < stride || stride == 0 { - return None; - } - let chunk = buffer_chunk(stride, device.limits().max_buffer_size); - let parts = bytes - .chunks(chunk) - .filter(|part| part.len() >= stride) - .map(|part| { - let buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some(label), contents: part, usage }); - (buffer, u32::try_from(part.len() / stride).unwrap_or(0)) - }) - .collect(); - Some(Batch { parts, chunk }) -} - -/// Bytes per GPU buffer for vertices of `stride` bytes: within the device's limit and a -/// whole number of triangles and line pairs, so no primitive straddles two buffers. -fn buffer_chunk(stride: usize, max_buffer_size: u64) -> usize { - let unit = stride.max(1) * 6; - let max = usize::try_from(max_buffer_size).unwrap_or(usize::MAX).min(1 << 30); - (max / unit).max(1) * unit -} - -/// Triangles (3 vertices of `TRI_SIZE` bytes each, position first) ordered far to near along -/// the view direction `back` (toward the eye), so blended glass draws back to front. -pub fn sort_back_to_front(bytes: &[u8], back: [f32; 3]) -> Vec { - let tri = TRI_SIZE * 3; - let depth = |t: &[u8]| -> f32 { - let f = |o: usize| t.get(o..o + 4).and_then(|b| b.try_into().ok()).map_or(0.0, f32::from_le_bytes); - (0..3).map(|v| (0..3).map(|k| f(v * TRI_SIZE + k * 4) * back[k]).sum::()).sum::() - }; - let mut tris: Vec<(f32, &[u8])> = bytes.chunks_exact(tri).map(|t| (depth(t), t)).collect(); - tris.sort_by(|a, b| a.0.total_cmp(&b.0)); - tris.into_iter().flat_map(|(_, t)| t.iter().copied()).collect() -} - -impl Batches { - /// Re-sort the glass for a new view direction (when it turned more than about 2 degrees). - fn sort_glass(&mut self, queue: &wgpu::Queue, back: [f32; 3]) { - let (Some(g), false) = (&self.glass, self.glass_cpu.is_empty()) else { return }; - let turned = self.glass_sorted_for.is_none_or(|s| s[0] * back[0] + s[1] * back[1] + s[2] * back[2] < 0.9994); - if turned { - let sorted = sort_back_to_front(&self.glass_cpu, back); - for ((buffer, _), bytes) in g.parts.iter().zip(sorted.chunks(g.chunk.max(1))) { - queue.write_buffer(buffer, 0, bytes); - } - self.glass_sorted_for = Some(back); - } - } -} - -/// The tessellation pipeline (`shader`: its source), where display plans are evaluated: on a -/// device that runs compute shaders with the storage buffers the evaluation binds (not WebGL2) -/// and builds the pipeline. Elsewhere `None`, and bodies are built on the CPU: a device whose -/// shader compiler rejects the shader (D3D12's FXC once did) only loses GPU evaluation. -fn tessellation(adapter: &wgpu::Adapter, device: &wgpu::Device, queue: &wgpu::Queue, shader: &str) -> Option { - let compute = adapter.get_downlevel_capabilities().flags.contains(wgpu::DownlevelFlags::COMPUTE_SHADERS) - && device.limits().max_storage_buffers_per_shader_stage >= 4; - if !compute { - return None; - } - let info = adapter.get_info(); - if hangs_on_gpu_tessellation(info.backend, &info.name) || std::env::var_os("SOLIDCRAFT_CPU_TESS").is_some() { - log::warn!("bodies are built on the CPU on {} ({:?})", info.name, info.backend); - return None; - } - match solidcraft_gpu::TessGpu::with_shader(info.name.clone(), device.clone(), queue.clone(), shader) { - Ok(t) => Some(t), - Err(e) => { - log::warn!("bodies are built on the CPU on {} ({:?}): {e}", info.name, info.backend); - None - } - } -} - -/// A device whose driver hangs on the evaluation shader, so bodies are built on the CPU there: -/// the AMD FirePro D300/D500/D700 (Mac Pro 2013, Tahiti) under Metal, where macOS resets the GPU -/// and the whole desktop freezes. `SOLIDCRAFT_CPU_TESS=1` forces CPU evaluation on any device. -fn hangs_on_gpu_tessellation(backend: wgpu::Backend, name: &str) -> bool { - backend == wgpu::Backend::Metal && name.contains("FirePro") -} +/// A frame of the viewport as an egui paint callback. +pub struct ViewportCallback(pub Frame); /// Create the pipelines. Call once with the app's render state and its depth/stencil/MSAA /// settings. Without a stencil the section cap does not hide the inside of cut bodies. Without /// `gpu_meshing` (safe mode) bodies are meshed on the CPU. pub fn install(rs: &egui_wgpu::RenderState, depth_bits: u8, stencil_bits: u8, samples: u32, gpu_meshing: bool) -> GpuTarget { - let tess = if gpu_meshing { tessellation(&rs.adapter, &rs.device, &rs.queue, solidcraft_gpu::SHADER) } else { None }; + let tess = if gpu_meshing { solidcraft_gpu::view::tessellation(&rs.adapter, &rs.device, &rs.queue, solidcraft_gpu::SHADER) } else { None }; let t = GpuTarget { format: rs.target_format, depth: egui_wgpu::depth_format_from_bits(depth_bits, stencil_bits), samples, tess: tess.is_some() }; - let res = Resources::new(&rs.device, t, tess); + let res = Renderer::new(&rs.device, t, tess); rs.renderer.write().callback_resources.insert(res); t } +/// Draw this process's headless pictures (`ui.render`, the agent's view image, thumbnails of +/// designs and saves) on the app's own device, with the viewport's pipelines (native only: a +/// browser cannot wait for the GPU to hand a picture back); where the device cannot, the CPU +/// rasterizer draws them. +#[cfg(not(target_arch = "wasm32"))] +pub fn install_picture_renderer(rs: &egui_wgpu::RenderState) { + match solidcraft_gpu::capture::Capturer::new(&rs.adapter, rs.device.clone(), rs.queue.clone()) { + Ok(capturer) => { + let capturer = std::sync::Arc::new(capturer); + solidcraft_engine::capture::install(std::sync::Arc::new(move |scene, cam, w, h| { + let rgba = capturer.rgba(scene, cam, w, h).map_err(|e| e.to_string())?; + Ok(solidcraft_engine::capture::Picture { rgba, renderer: capturer.renderer() }) + })); + } + Err(e) => { + log::warn!("pictures of the model are drawn by the CPU rasterizer: the GPU cannot draw them: {e}"); + install_cpu_picture_renderer(); + } + } +} + +/// The last tier: draw this process's headless pictures with the CPU rasterizer, and every +/// picture says so. The app uses it when its device cannot draw pictures; the web app always +/// does, since a browser cannot wait for the GPU to hand a picture back. +pub fn install_cpu_picture_renderer() { + solidcraft_engine::capture::install(std::sync::Arc::new(|scene, cam, w, h| { + let canvas = solidcraft_engine::render::render(scene, cam, w as usize, h as usize); + Ok(solidcraft_engine::capture::Picture { rgba: canvas.rgba, renderer: "cpu" }) + })); +} + +#[cfg(test)] +mod test_support { + /// For tests that look at pictures: install the headless GPU renderer (the CLI's). `false`, with + /// the reason printed, on a machine without a GPU adapter, and the test skips. + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn test_picture_renderer() -> bool { + match solidcraft_gpu::capture::shared() { + Ok(c) => { + solidcraft_engine::capture::install(std::sync::Arc::new(move |scene, cam, w, h| { + c.rgba(scene, cam, w, h) + .map(|rgba| solidcraft_engine::capture::Picture { rgba, renderer: c.renderer() }) + .map_err(|e| e.to_string()) + })); + true + } + Err(e @ solidcraft_gpu::GpuError::NoAdapter(_)) if std::env::var_os("SOLIDCRAFT_REQUIRE_GPU").is_none() => { + eprintln!("skipping: {e}"); + false + } + Err(e) => panic!("{e}"), + } + } +} +#[cfg(all(test, not(target_arch = "wasm32")))] +pub(crate) use test_support::test_picture_renderer; + impl egui_wgpu::CallbackTrait for ViewportCallback { fn prepare( &self, @@ -1075,260 +92,22 @@ impl egui_wgpu::CallbackTrait for ViewportCallback { encoder: &mut wgpu::CommandEncoder, resources: &mut egui_wgpu::CallbackResources, ) -> Vec { - let Some(res) = resources.get_mut::() else { return Vec::new() }; - if self.product { - res.product.take(device, self.key, &self.slot, None); - res.product.sort_glass(queue, self.back); - queue.write_buffer(&res.uniform, 0, &uniform_bytes(self, self.size_px[0], self.size_px[1], res.linear_out)); - return Vec::new(); + if let Some(res) = resources.get_mut::() { + res.prepare(device, queue, encoder, &self.0); } - res.model.take(device, self.key, &self.slot, res.tess.as_ref().map(|t| (t, &mut *encoder))); - res.sketch.take(device, self.sketch_key, &self.sketch_slot, None); - res.highlight.take(device, self.hl_key, &self.hl_slot, None); - res.preview.take(device, self.pv_key, &self.pv_slot, None); - res.model.sort_glass(queue, self.back); - queue.write_buffer(&res.uniform, 0, &uniform_bytes(self, self.size_px[0], self.size_px[1], res.linear_out)); - if let Some(a) = &self.access - && a.version != res.access_version - { - res.access_bind = access_texture(device, Some(queue), &res.access_bgl, a.size, &a.depth); - res.access_version = a.version; - } - // Images: upload new or changed textures, drop removed ones, rebuild the quads. - res.textures.retain(|id, _| self.images.iter().any(|i| i.id == *id)); - res.quads.clear(); - for img in &self.images { - let [w, h] = img.size; - if w == 0 || h == 0 || img.rgba.len() != (w as usize) * (h as usize) * 4 { - continue; - } - if res.textures.get(&img.id).is_none_or(|t| t.0 != img.version) { - let size = wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }; - let tex = device.create_texture(&wgpu::TextureDescriptor { - label: Some("sc_image"), - size, - mip_level_count: 1, - sample_count: 1, - dimension: wgpu::TextureDimension::D2, - format: wgpu::TextureFormat::Rgba8Unorm, - usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, - view_formats: &[], - }); - queue.write_texture( - wgpu::TexelCopyTextureInfo { texture: &tex, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, - &img.rgba, - wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(4 * w), rows_per_image: Some(h) }, - size, - ); - let view = tex.create_view(&Default::default()); - let bind = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("sc_image"), - layout: &res.image_bgl, - entries: &[ - wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&view) }, - wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(&res.sampler) }, - ], - }); - res.textures.insert(img.id, (img.version, bind)); - } - let c = img.corners; - let uv = [[0.0_f32, 1.0], [1.0, 1.0], [1.0, 0.0], [0.0, 0.0]]; - let mut bytes = Vec::with_capacity(6 * IMG_SIZE); - for k in [0, 1, 2, 0, 2, 3] { - for v in c[k].iter().chain(&uv[k]).chain(std::iter::once(&img.opacity)) { - bytes.extend_from_slice(&v.to_le_bytes()); - } - } - if let Some(b) = upload(device, "sc_image_quad", &bytes, IMG_SIZE) { - res.quads.push((img.id, b)); - } - } - res.ss_ready = self.ssaa != 1.0 && res.supersample(device, encoder, self); Vec::new() } fn paint(&self, info: egui::PaintCallbackInfo, pass: &mut wgpu::RenderPass<'static>, resources: &egui_wgpu::CallbackResources) { - let Some(res) = resources.get::() else { return }; + let Some(res) = resources.get::() else { return }; let vp = info.viewport_in_pixels(); - if vp.width_px <= 0 || vp.height_px <= 0 { - return; - } - pass.set_viewport(vp.left_px as f32, vp.top_px as f32, vp.width_px as f32, vp.height_px as f32, 0.0, 1.0); - // Drawn supersampled in `prepare`: filter it down into the viewport. - if res.ss_ready - && let Some(ss) = &res.ss - { - pass.set_pipeline(&res.ss_blit); - pass.set_bind_group(0, &ss.bind, &[]); - pass.draw(0..3, 0..1); - return; - } - res.draw(self, pass); + res.paint(&self.0, pass, [vp.left_px as f32, vp.top_px as f32, vp.width_px as f32, vp.height_px as f32]); } } -impl Resources { - /// Draw the frame's scenes into `pass` (its viewport already set). - fn draw(&self, cb: &ViewportCallback, pass: &mut wgpu::RenderPass<'static>) { - let res = self; - pass.set_bind_group(0, &res.bind, &[]); - let tris = |pass: &mut wgpu::RenderPass<'static>, p: &wgpu::RenderPipeline, b: &Option| { - if let Some(b) = b { - pass.set_pipeline(p); - for (buffer, count) in &b.parts { - pass.set_vertex_buffer(0, buffer.slice(..)); - pass.draw(0..*count, 0..1); - } - } - }; - let lines = |pass: &mut wgpu::RenderPass<'static>, p: &wgpu::RenderPipeline, b: &Option| { - if let Some(b) = b { - pass.set_pipeline(p); - for (buffer, count) in &b.parts { - pass.set_vertex_buffer(0, buffer.slice(..)); - pass.draw(0..6, 0..*count); - } - } - }; - 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) }; - lines(pass, &res.overlay, &m.under); - lines(pass, &res.overlay, &sk.under); - pass.set_bind_group(1, &res.access_bind, &[]); - let planned = |pass: &mut wgpu::RenderPass<'static>, p: &wgpu::RenderPipeline| { - for d in &m.planned { - pass.set_pipeline(p); - pass.set_vertex_buffer(0, d.mesh.vertices.slice(..)); - pass.set_vertex_buffer(1, d.colors.slice(..)); - pass.set_index_buffer(d.mesh.indices.slice(..), wgpu::IndexFormat::Uint32); - pass.draw_indexed(0..d.mesh.index_count, 0, 0..1); - } - }; - let sectioned = cb.clip[..3].iter().map(|c| c * c).sum::() > 0.25; - match (res.tri_cut.as_ref().filter(|_| sectioned), res.tri_cut_planned.as_ref()) { - (Some((mark, cap)), Some((mark_planned, cap_planned))) => { - pass.set_stencil_reference(1); - tris(pass, mark, &m.tris); - tris(pass, mark, &pv.tris); - planned(pass, mark_planned); - tris(pass, cap, &m.tris); - tris(pass, cap, &pv.tris); - planned(pass, cap_planned); - } - _ => { - tris(pass, &res.tri, &m.tris); - tris(pass, &res.tri, &pv.tris); - planned(pass, &res.tri_planned); - } - } - tris(pass, &res.pbr, &m.pbr); - tris(pass, &res.tri_hl, &h.tris); - lines(pass, &res.line, &m.lines); - lines(pass, &res.line, &sk.lines); - lines(pass, &res.line_hidden, &m.hidden); - lines(pass, &res.line_hidden, &h.hidden); - lines(pass, &res.line, &pv.lines); - lines(pass, &res.line, &h.lines); - lines(pass, &res.guide_line, &h.guide_lines); - for (id, q) in res.quads.iter().filter(|_| !cb.product) { - if let Some((_, bind)) = res.textures.get(id) { - pass.set_pipeline(&res.image); - pass.set_bind_group(1, bind, &[]); - for (buffer, count) in &q.parts { - pass.set_vertex_buffer(0, buffer.slice(..)); - pass.draw(0..*count, 0..1); - } - } - } - tris(pass, &res.ghost, &pv.ghost); - tris(pass, &res.glass_far, &m.glass); - tris(pass, &res.glass_near, &m.glass); - tris(pass, &res.trans, &m.trans); - tris(pass, &res.trans, &sk.trans); - tris(pass, &res.trans, &h.trans); - tris(pass, &res.guide_trans, &h.guide_trans); - tris(pass, &res.xray, &pv.xray); - lines(pass, &res.overlay, &m.overlays); - lines(pass, &res.overlay, &sk.overlays); - lines(pass, &res.overlay, &h.overlays); - } -} - -impl Resources { - /// Draw the frame supersampled (`cb.ssaa` times the viewport's pixels each way, within the - /// device's texture limit and the memory budget) into textures of the viewport's kind. - /// `false` when it cannot be (too small a gain, a zero-sized viewport): drawn as usual. - fn supersample(&mut self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, cb: &ViewportCallback) -> bool { - let Some(size) = supersampled_size(cb.size_px, cb.ssaa, self.max_texture, self.target.samples) else { - self.ss = None; - return false; - }; - if self.ss.as_ref().is_none_or(|ss| ss.size != size) { - self.ss = Some(self.supersampled(device, size)); - } - let Some(ss) = &self.ss else { return false }; - let depth_format = self.target.depth; - let mut pass = encoder - .begin_render_pass(&wgpu::RenderPassDescriptor { - label: Some("sc_ssaa"), - color_attachments: &[Some(wgpu::RenderPassColorAttachment { - view: &ss.color, - depth_slice: None, - resolve_target: ss.resolve.as_ref(), - ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), store: wgpu::StoreOp::Store }, - })], - depth_stencil_attachment: ss.depth.as_ref().map(|view| wgpu::RenderPassDepthStencilAttachment { - view, - depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(1.0), store: wgpu::StoreOp::Discard }), - stencil_ops: depth_format - .filter(|f| f.has_stencil_aspect()) - .map(|_| wgpu::Operations { load: wgpu::LoadOp::Clear(0), store: wgpu::StoreOp::Discard }), - }), - timestamp_writes: None, - occlusion_query_set: None, - multiview_mask: None, - }) - .forget_lifetime(); - pass.set_viewport(0.0, 0.0, size[0] as f32, size[1] as f32, 0.0, 1.0); - self.draw(cb, &mut pass); - true - } - - /// Textures for a supersampled frame of `size` pixels. - fn supersampled(&self, device: &wgpu::Device, size: [u32; 2]) -> Supersampled { - let t = self.target; - let texture = |label: &str, format: wgpu::TextureFormat, samples: u32, usage: wgpu::TextureUsages| { - 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: samples, - dimension: wgpu::TextureDimension::D2, - format, - usage, - view_formats: &[], - }) - .create_view(&Default::default()) - }; - let samples = t.samples.max(1); - let sampled = wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING; - let (color, resolve) = if samples > 1 { - (texture("sc_ssaa_ms", t.format, samples, wgpu::TextureUsages::RENDER_ATTACHMENT), Some(texture("sc_ssaa", t.format, 1, sampled))) - } else { - (texture("sc_ssaa", t.format, 1, sampled), None) - }; - let depth = t.depth.map(|f| texture("sc_ssaa_depth", f, samples, wgpu::TextureUsages::RENDER_ATTACHMENT)); - let bind = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("sc_ssaa"), - layout: &self.ss_bgl, - entries: &[ - wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(resolve.as_ref().unwrap_or(&color)) }, - wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(&self.sampler) }, - ], - }); - Supersampled { size, color, resolve, depth, bind } - } +/// The shader's analysis colours and flags for the theme's colours. +pub fn analysis_colors(c: &crate::theme::AnalysisColors) -> [f32; 36] { + solidcraft_gpu::view::analysis_colors(c) } /// The backends the offscreen tests start, chosen once per test process as the app chooses them @@ -1375,7 +154,7 @@ fn offscreen_device() -> Option<(wgpu::Adapter, wgpu::Device, wgpu::Queue)> { #[cfg(all(test, not(target_arch = "wasm32")))] pub(crate) fn offscreen_tessellates(shader: &str) -> Option { let (adapter, device, queue) = offscreen_device()?; - Some(tessellation(&adapter, &device, &queue, shader).is_some()) + Some(solidcraft_gpu::view::tessellation(&adapter, &device, &queue, shader).is_some()) } /// Render `scene` offscreen on a device of its own, through the viewport's real resources and @@ -1475,12 +254,12 @@ fn offscreen( eprintln!("offscreen adapter: {:?}", adapter.get_info().backend); let format = if srgb { wgpu::TextureFormat::Rgba8UnormSrgb } else { wgpu::TextureFormat::Rgba8Unorm }; let depth = wgpu::TextureFormat::Depth24PlusStencil8; - let compute = tess.and_then(|shader| tessellation(&adapter, &device, &queue, shader)); + let compute = tess.and_then(|shader| solidcraft_gpu::view::tessellation(&adapter, &device, &queue, shader)); let target = GpuTarget { format, depth: Some(depth), samples: 1, tess: compute.is_some() }; let mut resources = egui_wgpu::CallbackResources::default(); - resources.insert(Resources::new(&device, target, compute)); + resources.insert(Renderer::new(&device, target, compute)); let none = || Arc::new(Mutex::new(None)); - let cb = ViewportCallback { + let cb = ViewportCallback(Frame { product, key: 1, slot: Arc::new(Mutex::new(Some(scene))), @@ -1502,7 +281,7 @@ fn offscreen( outline: false, eye, ssaa, - }; + }); let texture = |format, usage| { device.create_texture(&wgpu::TextureDescriptor { label: Some("offscreen"), @@ -1567,54 +346,8 @@ fn offscreen( Some(bytes) } -/// Uniform bytes for a frame. -pub fn uniform_bytes(cb: &ViewportCallback, w: f32, h: f32, linear: bool) -> Vec { - let mut v: Vec = cb.view_proj.iter().flatten().copied().collect(); - v.extend([cb.back[0], cb.back[1], cb.back[2], if linear { 1.0 } else { 0.0 }]); - v.extend([w.max(1.0), h.max(1.0), 2e-4, if cb.outline { 1.0 } else { 0.0 }]); - v.extend(cb.clip); - v.extend(cb.cap); - v.extend(cb.analysis); - match &cb.access { - Some(a) => { - v.extend(a.u); - v.extend(a.v); - } - None => v.extend([0.0; 8]), - } - v.extend(cb.eye); - v.extend(cb.analysis_colors); - v.iter().flat_map(|x| x.to_le_bytes()).collect() -} - -/// The shader's analysis colours (`ana_c`: draft positive, between, negative; reachable, -/// blocked; curvature flat, middle, tight; alpha 1) and flags (`ana_f.x`: 1 to stripe the bad -/// faces). -pub fn analysis_colors(c: &crate::theme::AnalysisColors) -> [f32; 36] { - let mut v = [0.0; 36]; - let colors = c.draft.iter().chain(&c.access).chain(&c.curvature).flat_map(|rgb| [rgb[0], rgb[1], rgb[2], 1.0]); - for (slot, x) in v.iter_mut().zip(colors) { - *slot = x; - } - v[32] = if c.hatch { 1.0 } else { 0.0 }; - v -} - #[cfg(test)] mod tests { - use egui_wgpu::wgpu::{self, naga}; - - /// Only the FirePro under Metal skips GPU evaluation; the same card under another backend - /// and other Metal GPUs keep it. - #[test] - fn firepro_under_metal_builds_bodies_on_the_cpu() { - assert!(super::hangs_on_gpu_tessellation(wgpu::Backend::Metal, "AMD FirePro D500")); - assert!(super::hangs_on_gpu_tessellation(wgpu::Backend::Metal, "AMD FirePro D700")); - assert!(!super::hangs_on_gpu_tessellation(wgpu::Backend::Metal, "Apple M2")); - assert!(!super::hangs_on_gpu_tessellation(wgpu::Backend::Metal, "AMD Radeon Pro 560X")); - assert!(!super::hangs_on_gpu_tessellation(wgpu::Backend::Vulkan, "AMD FirePro W5100")); - } - /// The offscreen tests start the backends the app would: on Windows without `WGPU_BACKEND` /// exactly one, from the app's order (D3D12, Vulkan, OpenGL); otherwise wgpu's default. #[cfg(not(target_arch = "wasm32"))] @@ -1635,127 +368,4 @@ mod tests { assert!(chosen.contains(used), "the offscreen device runs on {used:?}, not on {chosen:?}"); } } - - /// The viewport shader parses and validates (a bad shader would only fail at run time). - #[test] - fn shader_is_valid() { - let module = naga::front::wgsl::parse_str(super::SHADER).unwrap_or_else(|e| panic!("{}", e.emit_to_string(super::SHADER))); - naga::valid::Validator::new(naga::valid::ValidationFlags::all(), naga::valid::Capabilities::empty()).validate(&module).unwrap(); - } - - /// Derivatives and implicit-lod sampling run only in uniform control flow: browsers' WGSL - /// compilers (Tint) reject them after a branch, and the whole viewport shader then fails, - /// a black screen on the web (naga accepts it). Every fragment entry point makes such calls - /// (directly or through a helper) before its first branch or return. - #[test] - fn derivatives_only_in_uniform_control_flow() { - // Without comments (their words are not code). - let src: String = super::SHADER.lines().map(|l| l.split("//").next().unwrap_or("")).collect::>().join("\n"); - let src = src.as_str(); - let derivs = ["dpdx(", "dpdy(", "fwidth(", "textureSample("]; - // Functions: name -> body. - let mut fns: Vec<(String, String, bool)> = Vec::new(); - let mut rest = src; - let mut fragment = false; - while let Some(at) = rest.find("fn ") { - let before = &rest[..at]; - if before.contains("@fragment") { - fragment = true; - } - let Some(open) = rest[at..].find('{') else { break }; - let name = rest[at + 3..].split('(').next().unwrap_or("").trim().to_string(); - let start = at + open; - let mut depth = 0; - let mut end = start; - for (k, ch) in rest[start..].char_indices() { - match ch { - '{' => depth += 1, - '}' => { - depth -= 1; - if depth == 0 { - end = start + k; - break; - } - } - _ => {} - } - } - fns.push((name, rest[start..=end].to_string(), fragment)); - fragment = false; - rest = &rest[end + 1..]; - } - // Helpers that take derivatives (directly or through another helper). - let mut uses: Vec = Vec::new(); - for _ in 0..8 { - for (n, body, _) in &fns { - if !uses.contains(n) && (derivs.iter().any(|d| body.contains(d)) || uses.iter().any(|u| body.contains(&format!("{u}(")))) { - uses.push(n.clone()); - } - } - } - for (n, body, frag) in &fns { - let calls: Vec = derivs - .iter() - .map(|d| d.to_string()) - .chain(uses.iter().map(|u| format!("{u}("))) - .flat_map(|c| body.match_indices(&c).map(|(i, _)| i).collect::>()) - .collect(); - if calls.is_empty() { - continue; - } - if !*frag { - // A helper: its own derivatives must come before any branch or return in it. - let first = ["if (", "return", "discard"].iter().filter_map(|k| body.find(k)).min().unwrap_or(usize::MAX); - for d in derivs { - if let Some(i) = body.find(d) { - assert!(i < first, "{n}: {d} after a branch"); - } - } - continue; - } - let first = ["if (", "return", "discard"].iter().filter_map(|k| body.find(k)).min().unwrap_or(usize::MAX); - for c in calls { - assert!(c < first, "fragment {n}: a derivative after a branch or return: {}", &body[c..(c + 40).min(body.len())]); - } - } - } -} - -#[cfg(test)] -mod glass_tests { - use super::*; - - /// A large import's triangles once went into one buffer past the device's limit (524 MB - /// against 256 MB) and the app crashed (#883): they are split into whole triangles. - #[test] - fn large_scenes_are_split_into_buffers_within_the_device_limit() { - let limit = 256u64 << 20; - for stride in [TRI_SIZE, LINE_SIZE, 4] { - let chunk = buffer_chunk(stride, limit); - assert!(chunk as u64 <= limit && chunk > limit as usize / 2); - assert_eq!(chunk % (stride * 3), 0, "whole triangles"); - assert_eq!(chunk % (stride * 2), 0, "whole line pairs"); - } - let scene = 524_434_680usize; - assert_eq!(scene.div_ceil(buffer_chunk(TRI_SIZE, limit)), 2); - assert!(buffer_chunk(TRI_SIZE, 1) >= TRI_SIZE * 6, "a tiny limit still holds one unit"); - } - - #[test] - fn glass_is_drawn_far_to_near() { - // Two triangles at z = 5 and z = -5, given near first; looking down from +Z. - let mut sc = GpuScene::default(); - for z in [5.0f32, -5.0] { - for p in [[0.0, 0.0, z], [1.0, 0.0, z], [0.0, 1.0, z]] { - sc.glass_tri(p, [0.0, 0.0, 1.0], [255, 0, 0, 100]); - } - } - let sorted = sort_back_to_front(&sc.glass, [0.0, 0.0, 1.0]); - let z0 = f32::from_le_bytes(sorted[8..12].try_into().unwrap()); - assert_eq!(z0, -5.0, "the far triangle first"); - assert_eq!(sorted.len(), sc.glass.len()); - // Seen from below, the order flips. - let sorted = sort_back_to_front(&sc.glass, [0.0, 0.0, -1.0]); - assert_eq!(f32::from_le_bytes(sorted[8..12].try_into().unwrap()), 5.0); - } } diff --git a/crates/ui-egui/src/home.rs b/crates/ui-egui/src/home.rs index b2b1d2377..6a9c72c61 100644 --- a/crates/ui-egui/src/home.rs +++ b/crates/ui-egui/src/home.rs @@ -69,8 +69,9 @@ pub fn thumbnail(s: &Session) -> Option { // Fill the card: the fit leaves room for a whole window's margins. cam.distance *= 0.7; let scene = solidcraft_engine::view::scene(s, &cam); - let c = solidcraft_engine::render::render(&scene, &cam, THUMB[0], THUMB[1]); - (c.rgba.len() == c.w * c.h * 4).then(|| egui::ColorImage::from_rgba_unmultiplied([c.w, c.h], &c.rgba)) + // Drawn on the GPU by the renderer the app installs; none (a browser): no picture. + let picture = solidcraft_engine::capture::rgba(&scene, &cam, THUMB[0] as u32, THUMB[1] as u32).ok()?; + Some(egui::ColorImage::from_rgba_unmultiplied(THUMB, &picture.rgba)) } /// File identity, not just its path: saving or replacing a design invalidates its picture. @@ -570,6 +571,9 @@ mod tests { #[cfg(not(target_arch = "wasm32"))] #[test] fn cached_recent_uses_a_separate_png_without_reading_or_changing_design_json() { + 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-thumb-{}-{nonce}.solidcraft", std::process::id())); // Deliberately invalid design: a cached recent must not parse/evaluate it. @@ -594,6 +598,9 @@ mod tests { #[cfg(not(target_arch = "wasm32"))] #[test] fn portable_thumbnail_loads_without_a_local_picture_or_model_rebuild() { + if !crate::gpu::test_picture_renderer() { + return; + } let mut session = Session::default(); session.execute("solid.box", &serde_json::json!({"length":10,"width":20,"height":30})).unwrap(); for body in &session.world_state().bodies { @@ -630,8 +637,12 @@ mod tests { } /// Samples build in the background and make a picture; picking one opens its design. + #[cfg(not(target_arch = "wasm32"))] #[test] fn sample_card_makes_a_picture_and_opens() { + if !crate::gpu::test_picture_renderer() { + return; + } let (key, img, session) = make("sample:0"); assert_eq!(key, "sample:0"); let img = img.unwrap(); diff --git a/crates/ui-egui/src/render_workspace.rs b/crates/ui-egui/src/render_workspace.rs index 68c9e8e95..332ba2ca8 100644 --- a/crates/ui-egui/src/render_workspace.rs +++ b/crates/ui-egui/src/render_workspace.rs @@ -11,7 +11,7 @@ use solidcraft_engine::render::{ ScratchLayout, }; -use crate::gpu::{GpuScene, SceneSlot, ViewportCallback}; +use crate::gpu::{Frame, GpuScene, SceneSlot, ViewportCallback}; use crate::{SolveApp, theme::Tokens}; const MAX_GEOMETRY_BYTES: usize = 128 * 1024 * 1024; @@ -518,7 +518,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { let radius = scene.bounds.diagonal().max(10.0) + scene.bounds.center().dist(camera.target); let eye = camera.eye(); let slot = app.render_workspace.slot.clone(); - let callback = ViewportCallback { + let callback = ViewportCallback(Frame { product: true, key, slot: slot.clone(), @@ -540,7 +540,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { outline: false, 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 }, - }; + }); ui.painter().add(egui_wgpu::Callback::new_paint_callback(rect, callback)); Ok(()) })(); diff --git a/crates/ui-egui/src/render_workspace_tests.rs b/crates/ui-egui/src/render_workspace_tests.rs index 027dc4c85..4c53f2160 100644 --- a/crates/ui-egui/src/render_workspace_tests.rs +++ b/crates/ui-egui/src/render_workspace_tests.rs @@ -496,7 +496,6 @@ fn nav_app(render: bool, preset: &str, around: crate::prefs::OrbitAround) -> cra let mut s = Session::default(); s.execute("solid.box", &json!({"length":40,"width":30,"height":20,"body_name":"Product"})).unwrap(); let mut app = crate::SolveApp::new(s, crate::Services::default()); - app.viewport.no_pixels = true; if render { enter(&mut app, true).unwrap(); assert!(active(&app)); diff --git a/crates/ui-egui/src/scenario.rs b/crates/ui-egui/src/scenario.rs index 798b4029d..a2fea596e 100644 --- a/crates/ui-egui/src/scenario.rs +++ b/crates/ui-egui/src/scenario.rs @@ -179,8 +179,6 @@ impl Harness { /// File pickers answer like a person would: save into the scenario's folder, open the file /// the scenario chose. fn install(&mut self) { - // Frames are laid out, never painted. - self.app.viewport.no_pixels = true; let dir = self.dir.clone(); self.app.services.pick_save = Some(Box::new(move |name, _| Box::pin(std::future::ready(Some(dir.join(name).to_string_lossy().into_owned()))))); @@ -444,8 +442,19 @@ impl Harness { } else if let Some(name) = s.get("shot").and_then(Value::as_str) { // With SOLIDCRAFT_SCENARIO_SHOTS set: a render of the model as the camera sees it. if let Ok(dir) = solidcraft_engine::geom::env::var("SCENARIO_SHOTS").ok_or(()) { + // Drawn on the GPU: the headless device, as the CLI draws. + #[cfg(not(target_arch = "wasm32"))] + if solidcraft_engine::capture::installed().is_none() { + solidcraft_engine::capture::install(std::sync::Arc::new(|scene, cam, w, h| { + let (rgba, renderer) = solidcraft_gpu::capture::headless_rgba(scene, cam, w, h)?; + Ok(solidcraft_engine::capture::Picture { rgba, renderer }) + })); + } let path = std::path::Path::new(&dir).join(format!("{name}.png")); - self.call("ui.render", json!({"path": path.to_string_lossy(), "width": 1000, "height": 700})); + let r = self.call("ui.render", json!({"path": path.to_string_lossy(), "width": 1000, "height": 700})); + if r["ok"] != true { + return Err(format!("shot {name}: {}", r["error"])); + } } return Ok(()); } else if let Some(c) = s.get("camera") { diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index beb974b79..ef64fc239 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -108,18 +108,8 @@ pub fn srgb(c: [f32; 3]) -> Color32 { } /// Surface analysis colours, straight sRGB 0..1 as the shader takes them (exact, so they read -/// the same as when they were literals in the WGSL). -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct AnalysisColors { - /// Draft Analysis: at least the draft angle, between, at most minus the angle. - pub draft: [[f32; 3]; 3], - /// Accessibility Analysis: reachable, blocked. - pub access: [[f32; 3]; 2], - /// Curvature Map: flat, the middle of the scale, at or below the analysis radius. - pub curvature: [[f32; 3]; 3], - /// Stripe the negative draft and blocked faces too, so colour is not the only cue. - pub hatch: bool, -} +/// the same as when they were literals in the WGSL). The light theme's are the headless default. +pub use solidcraft_engine::render::AnalysisColors; /// The colours icons draw of their own (`icons::paint` takes ink, fill and accent from its /// caller). Every icon colour is a token so a colour vision mode can reach it. diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index a033c4564..72928841d 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -10,7 +10,7 @@ use solidcraft_engine::sketch::CurveKind; use solidcraft_engine::view::{colors, grid_step, sketch_lines_with_sampler}; use std::hash::{Hash, Hasher}; -use crate::gpu::{GpuScene, GpuTarget, SceneSlot, ViewportCallback}; +use crate::gpu::{Frame, GpuScene, GpuTarget, SceneSlot, ViewportCallback}; use crate::navigation::{CameraInput, NavCaps, OrbitSnap, orbit_drag}; use crate::selection::{BoxSel, origin_quads, origin_size, ray_quad}; use crate::theme::Tokens; @@ -69,9 +69,6 @@ pub struct ViewportState { pub(crate) display: std::sync::Mutex, hl_slot: SceneSlot, hl_key: u64, - cpu: Option<(u64, egui::TextureHandle)>, - /// Nothing will look at the frame (the headless scenario harness): skip the software render. - pub no_pixels: bool, pub nav: Option, /// The preset's navigation for the left-button drag under way (Alias: Shift+Alt), taken /// when the button went down, so the drag neither selects nor moves sketch geometry. @@ -1501,20 +1498,9 @@ pub fn selection_bounds(app: &SolveApp) -> Option [f32; 8] { - use solidcraft_engine::SurfaceAnalysis as A; - match app.session.analysis { - Some(A::Zebra { stripes }) => [1.0, stripes as f32, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0], - Some(A::Draft { pull, angle }) => [2.0, angle as f32, 0.0, 0.0, pull.x as f32, pull.y as f32, pull.z as f32, 0.0], - Some(A::Curvature { radius }) => [3.0, radius as f32, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0], - Some(A::Environment) => [4.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0], - Some(A::Access { dir }) => { - let (scale, size, eps) = crate::access::map(app).map(|m| (m.scale, m.size as f32, 1.5 / m.scale.max(1e-9))).unwrap_or((0.0, 0.0, 0.0)); - [5.0, eps, scale, size, dir.x as f32, dir.y as f32, dir.z as f32, 0.0] - } - None => [0.0; 8], - } + solidcraft_gpu::view::analysis_uniform(app.session.analysis.map(|a| a.mode()), crate::access::map(app).as_ref()) } /// While Draft, Accessibility or Curvature Map analysis is on, what each of its colours means and @@ -2193,7 +2179,8 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { update_refinement(app, ui.ctx(), &proj); let key = scene_key(app); let t0 = crate::now_ms(); - if let Some(_g) = app.viewport.gpu { + // Drawn on the GPU; without one (the headless harness, tests) the model is not drawn. + if app.viewport.gpu.is_some() { if key != app.viewport.key { let sc = build_scene(app); if let Ok(mut slot) = app.viewport.slot.lock() { @@ -2221,7 +2208,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { let ppp = ui.ctx().pixels_per_point(); let size_px = [rect.width() * ppp, rect.height() * ppp]; let ssaa = supersampling(app, ui.ctx(), proj.vp.to_f32(), size_px); - let cb = ViewportCallback { + let cb = ViewportCallback(Frame { ssaa, product: false, key: app.viewport.key, @@ -2246,10 +2233,8 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { let e = proj.cam.eye().to_f32(); [e[0], e[1], e[2], if proj.cam.fov > 0.0 { 1.0 } else { 0.0 }] }, - }; + }); painter.add(egui_wgpu::Callback::new_paint_callback(rect, cb)); - } else { - cpu_render(app, ui.ctx(), &painter, rect, &proj); } analysis_legend(app, &painter, rect); @@ -2952,44 +2937,9 @@ fn overlays(app: &SolveApp, painter: &egui::Painter, proj: &Proj) { } } -fn cpu_render(app: &mut SolveApp, ctx: &egui::Context, painter: &egui::Painter, rect: Rect, proj: &Proj) { - if app.viewport.no_pixels { - return; - } - let mut h = std::collections::hash_map::DefaultHasher::new(); - sketch_scene_key(app, proj).hash(&mut h); - for v in [proj.cam.yaw, proj.cam.pitch, proj.cam.roll, proj.cam.distance, proj.cam.target.x, proj.cam.target.y, proj.cam.target.z] { - v.to_bits().hash(&mut h); - } - (rect.width() as u32, rect.height() as u32).hash(&mut h); - app.ui.dark.hash(&mut h); - app.preferences.color_vision.hash(&mut h); - let key = h.finish(); - if app.viewport.cpu.as_ref().is_none_or(|(k, _)| *k != key) { - let mut budget = solidcraft_engine::render::SamplingBudget::new(131_072, 1_048_576); - let palette = scene_palette(app.ui.dark, app.preferences.color_vision); - let scene = solidcraft_engine::view::scene_with_palette( - &app.session, - &proj.cam, - section_plane(app), - |sk, index, plane| crate::sketch_display::curve_with_budget(sk, index, plane, proj, app.viewport.pixels_per_point(), &mut budget).parts, - &palette, - ); - let w = (rect.width() as usize).clamp(16, 4096); - let hh = (rect.height() as usize).clamp(16, 4096); - let c = solidcraft_engine::render::render(&scene, &proj.cam, w, hh); - let img = egui::ColorImage::from_rgba_unmultiplied([c.w, c.h], &c.rgba); - let tex = ctx.load_texture("sc_cpu_viewport", img, egui::TextureOptions::LINEAR); - app.viewport.cpu = Some((key, tex)); - } - if let Some((_, tex)) = &app.viewport.cpu { - painter.image(tex.id(), rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); - } -} - -/// The colours of a CPU picture of the model (`ui.render` and the CPU viewport) in the dark or -/// the light theme and a colour vision mode, from the tokens the window draws with, so the picture -/// matches the window. The light theme's tokens (Off) are the engine's own colours, so a light +/// The colours of a headless picture of the model (`ui.render`, the agent's view image) in the +/// dark or the light theme and a colour vision mode, from the tokens the window draws with, so the +/// picture matches the window. The light theme's tokens (Off) are the engine's own colours, so a light /// render is unchanged. pub(crate) fn scene_palette(dark: bool, mode: crate::theme::ColorVision) -> solidcraft_engine::view::Palette { let t = Tokens::themed(dark, mode); @@ -3011,6 +2961,7 @@ pub(crate) fn scene_palette(dark: bool, mode: crate::theme::ColorVision) -> soli sketch_centerline: rgb(t.sketch_centerline), axes: t.triad.map(rgb), cap: rgb(t.section_cap), + analysis: t.analysis, } } @@ -3337,7 +3288,6 @@ mod tests { let mut s = solidcraft_engine::Session::default(); s.run_script(&solidcraft_engine::sample::script()).unwrap(); let mut app = SolveApp::new(s, crate::Services::default()); - app.viewport.no_pixels = true; app.fit_view(); const SIZE: u32 = 256; let rect = Rect::from_min_size(Pos2::ZERO, vec2(SIZE as f32, SIZE as f32)); @@ -3400,7 +3350,6 @@ mod tests { let mut s = solidcraft_engine::Session::default(); s.run_script(&solidcraft_engine::sample::script()).unwrap(); let mut app = SolveApp::new(s, crate::Services::default()); - app.viewport.no_pixels = true; app.fit_view(); app.viewport.gpu = Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess }); const SIZE: u32 = 256; @@ -3439,7 +3388,6 @@ mod tests { let mut s = solidcraft_engine::Session::default(); s.run_script(&solidcraft_engine::sample::script()).unwrap(); let mut app = SolveApp::new(s, crate::Services::default()); - app.viewport.no_pixels = true; app.fit_view(); app.viewport.gpu = Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: false }); const SIZE: u32 = 256; @@ -3498,7 +3446,6 @@ mod tests { s.execute("solid.box", &json!({"length": 16, "width": 16, "height": 20, "corner": [12, 12, 20], "operation": "cut"})).unwrap(); s.execute("solid.cylinder", &json!({"base": [33, 33, 40], "diameter": 10, "height": 10, "operation": "join"})).unwrap(); let mut app = SolveApp::new(s, crate::Services::default()); - app.viewport.no_pixels = true; app.fit_view(); const SIZE: u32 = 256; let rect = Rect::from_min_size(Pos2::ZERO, vec2(SIZE as f32, SIZE as f32)); @@ -3599,13 +3546,13 @@ mod tests { crate::sketch_palette::set_mode(&mut h.app, 0); } - /// The CPU pictures (`ui.render`, the CPU viewport) are drawn in the window's theme (#974) - /// and colour vision mode (#778). The light theme's tokens are the engine's own colours, so a + /// Headless pictures of the view (`ui.render`, the agent's view image) are drawn in the + /// window's theme (#974) and colour vision mode (#778). The light theme's tokens are the engine's own colours, so a /// light picture in Off is unchanged; otherwise each part takes the token the window draws it /// with. Sketch states follow what the window does with them (`sketch_color`) and the axes the /// mode's triad, so the two can't drift apart. #[test] - fn cpu_pictures_are_drawn_in_the_windows_theme() { + fn pictures_are_drawn_in_the_windows_theme() { use crate::theme::ColorVision; use solidcraft_engine::view::Palette; assert_eq!(scene_palette(false, ColorVision::Off), Palette::DEFAULT, "the light theme is the engine's colours"); @@ -3620,6 +3567,7 @@ mod tests { for (dark, mode) in [false, true].into_iter().flat_map(|d| ColorVision::ALL.map(|m| (d, m))) { let (p, t) = (scene_palette(dark, mode), Tokens::themed(dark, mode)); assert_eq!(p.axes, t.triad.map(rgb), "dark {dark}, {mode:?}: the axes"); + assert_eq!(p.analysis, t.analysis, "dark {dark}, {mode:?}: the surface analysis"); for (tag, cpu) in [ (colors::SKETCH, p.sketch), (colors::SKETCH_FIXED, p.sketch_fixed), @@ -3636,65 +3584,43 @@ mod tests { } } - /// The CPU viewport follows a theme or colour vision mode change at once: both are part of its - /// picture's key. + /// The view's picture follows a theme change: its background is the window's. + #[cfg(not(target_arch = "wasm32"))] #[test] - fn cpu_viewport_redraws_in_the_new_theme() { + fn the_view_picture_follows_the_theme() { + if !crate::gpu::test_picture_renderer() { + return; + } let mut h = crate::scenario::Harness::new(); h.app.run("solid.box", json!({"length": 40, "width": 30, "height": 20})).unwrap(); - let rect = Rect::from_min_size(Pos2::ZERO, vec2(160.0, 120.0)); - let cam = solidcraft_engine::view::home_camera(&h.app.session); - let proj = Proj { cam, vp: cam.view_proj(4.0 / 3.0, 100.0), rect }; - h.app.viewport.no_pixels = false; - // The new picture's top row, most common colour first (the background's top); None when - // nothing new was drawn. - let top_row = |h: &mut crate::scenario::Harness| { - let mut out = h.ctx.run_ui(egui::RawInput { screen_rect: Some(rect), ..Default::default() }, |ui| { - cpu_render(&mut h.app, ui.ctx(), ui.painter(), rect, &proj); - }); - let id = h.app.viewport.cpu.as_ref().map(|(_, tex)| tex.id()); - let top = id.and_then(|id| out.textures_delta.set.get(&id)).and_then(|d| d.iter().find(|delta| delta.pos.is_none())).map(|upload| { - let egui::ImageData::Color(image) = &upload.image; - let mut counts = std::collections::HashMap::new(); - for px in image.pixels.iter().take(image.size[0]) { - *counts.entry(*px).or_insert(0) += 1; - } - counts.into_iter().max_by_key(|(_, n)| *n).map(|(c, _)| c).unwrap_or_default() - }); - out.textures_delta.clear(); - top - }; + h.app.cam = solidcraft_engine::view::home_camera(&h.app.session); for dark in [false, true, false] { h.app.ui.dark = dark; - let Some(px) = top_row(&mut h) else { panic!("dark {dark}: the CPU viewport kept the old picture") }; + let img = crate::control::view_rgba(&h.app, 160, 120).unwrap(); + // The top row's most common colour: the background's top. + let mut counts = std::collections::HashMap::new(); + for px in img.as_chunks::<4>().0.iter().take(160) { + *counts.entry([px[0], px[1], px[2]]).or_insert(0) += 1; + } + let px = counts.into_iter().max_by_key(|(_, n)| *n).map(|(c, _)| c).unwrap_or_default(); let want = if dark { Tokens::dark() } else { Tokens::light() }.viewport_top; - let near = [px.r(), px.g(), px.b()].iter().zip([want.r(), want.g(), want.b()]).all(|(a, b)| a.abs_diff(b) <= 2); + let near = px.iter().zip([want.r(), want.g(), want.b()]).all(|(a, b)| a.abs_diff(b) <= 2); assert!(near, "dark {dark}: top row {px:?}, the window's background {want:?}"); } - // And a colour vision mode change, on its own. - h.app.preferences.color_vision = crate::theme::ColorVision::Deutan; - assert!(top_row(&mut h).is_some(), "a new mode kept the old picture"); - assert!(top_row(&mut h).is_none(), "no change, no new picture"); } + /// The view's picture is cut by the section the viewport shows: an open Section Analysis + /// dialog's preview, a sketch's Slice. + #[cfg(not(target_arch = "wasm32"))] #[test] - fn cpu_viewport_uses_section_preview_and_sketch_slice() { - fn pixels(h: &mut crate::scenario::Harness, cam: Camera) -> Vec { - let rect = Rect::from_min_size(Pos2::ZERO, vec2(320.0, 240.0)); - let proj = Proj { cam, vp: cam.view_proj(4.0 / 3.0, 100.0), rect }; - h.app.viewport.no_pixels = false; - // Force a texture upload so this test reads the actual CPU rasterizer result. - h.app.viewport.cpu = None; - let mut out = h.ctx.run_ui(egui::RawInput { screen_rect: Some(rect), ..Default::default() }, |ui| { - cpu_render(&mut h.app, ui.ctx(), ui.painter(), rect, &proj); - }); - let id = h.app.viewport.cpu.as_ref().unwrap().1.id(); - let upload = out.textures_delta.set.get(&id).unwrap().iter().find(|delta| delta.pos.is_none()).unwrap(); - let egui::ImageData::Color(image) = &upload.image; - assert_eq!(image.size, [320, 240]); - let pixels = image.pixels.clone(); - out.textures_delta.clear(); - pixels + fn the_view_picture_uses_section_preview_and_sketch_slice() { + fn pixels(h: &mut crate::scenario::Harness, cam: Camera) -> Vec<[u8; 4]> { + h.app.cam = cam; + let img = crate::control::view_rgba(&h.app, 320, 240).unwrap(); + img.as_chunks::<4>().0.to_vec() + } + if !crate::gpu::test_picture_renderer() { + return; } let mut h = crate::scenario::Harness::new(); h.app.run("solid.box", json!({"length":40,"width":30,"height":20})).unwrap(); @@ -3708,12 +3634,12 @@ mod tests { *offset = "15 mm".into(); assert!(h.app.session.section.is_none()); let preview = pixels(&mut h, cam); - assert!(whole.iter().zip(&preview).filter(|(a, b)| a != b).count() > 100, "CPU viewport ignored uncommitted section preview"); + assert!(whole.iter().zip(&preview).filter(|(a, b)| a != b).count() > 100, "the picture ignored the uncommitted section preview"); assert!(std::sync::Arc::ptr_eq(&before, &h.app.session.doc)); assert_eq!(h.app.session.undo.len(), undo); h.app.run("inspect.section", json!({"plane":"XZ","offset":15})).unwrap(); h.app.dialog = None; - assert_eq!(preview, pixels(&mut h, cam), "preview and committed section must rasterize identically"); + assert_eq!(preview, pixels(&mut h, cam), "preview and committed section must draw identically"); h.app.session.section = None; h.app.run("sketch.create", json!({"plane":{"origin":[0,0,10],"x_dir":[1,0,0],"y_dir":[0,1,0]}})).unwrap(); @@ -3721,7 +3647,7 @@ mod tests { h.app.run("sketch.options", json!({"slice":true})).unwrap(); assert!(h.app.session.section.is_none()); let sliced = pixels(&mut h, cam); - assert!(whole.iter().zip(&sliced).filter(|(a, b)| a != b).count() > 100, "CPU viewport ignored active Sketch Slice"); + assert!(whole.iter().zip(&sliced).filter(|(a, b)| a != b).count() > 100, "the picture ignored the active Sketch Slice"); h.app.run("sketch.options", json!({"slice":false})).unwrap(); assert_eq!(whole, pixels(&mut h, cam), "disabling Slice restores the whole-body pixels"); } @@ -3876,7 +3802,6 @@ mod tests { s.execute("sketch.create", &json!({"plane": "XY"})).unwrap(); s.execute("sketch.point", &json!({"point": [0, 0]})).unwrap(); let mut app = SolveApp::new(s, crate::Services::default()); - app.viewport.no_pixels = true; if gpu { // The callback is queued by egui; no device is needed to inspect scene updates. app.viewport.gpu = Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: false }); @@ -4106,7 +4031,6 @@ mod tests { s.selection = vec![Sel::Body { name: "Body1".into() }]; let mut app = SolveApp::new(s, crate::Services::default()); app.preferences.nav = "touchpad".into(); - app.viewport.no_pixels = true; app.start("solid.move"); app.dialog.as_mut().unwrap().focus = false; let p = pos2(100.0, 100.0); @@ -4341,7 +4265,6 @@ mod tests { }; for tess in [true, false] { let mut app = cylinder_app(); - app.viewport.no_pixels = true; app.viewport.gpu = Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess }); let body = app.session.world_state().bodies[0].clone(); let before = build_scene(&app).merged(); @@ -4444,8 +4367,9 @@ mod tests { if wireframe { scene.meshes.clear(); } - let png = solidcraft_engine::render::render_png(&scene, &cam, 1200, 800).unwrap(); - std::fs::write(std::path::Path::new(&directory).join(format!("smooth-ring-{name}.png")), png).unwrap(); + assert!(crate::gpu::test_picture_renderer(), "SMOOTH_SCREENSHOTS needs a GPU"); + let png = solidcraft_engine::capture::png(&scene, &cam, 1200, 800).unwrap(); + std::fs::write(std::path::Path::new(&directory).join(format!("smooth-ring-{name}.png")), png.bytes).unwrap(); } } } @@ -4846,7 +4770,6 @@ mod tests { let ctx = egui::Context::default(); let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); assert!(app.preferences.trackpad_pan); - app.viewport.no_pixels = true; crate::help::run(&mut app, &ctx, "shortcuts"); let mut time = 0.0; let pan = @@ -4905,7 +4828,6 @@ mod tests { let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); app.preferences.smooth_wheel_zoom = smooth; app.preferences.trackpad_pan = false; - app.viewport.no_pixels = true; crate::help::run(&mut app, &ctx, "shortcuts"); let mut time = 0.0; let mut frame = |app: &mut SolveApp, pointer: Option, wheel: f32| { @@ -5396,7 +5318,6 @@ mod tests { let mut s = solidcraft_engine::Session::default(); s.run_script(&solidcraft_engine::sample::script()).unwrap(); let mut app = SolveApp::new(s, crate::Services::default()); - app.viewport.no_pixels = true; app.fit_view(); app.run("inspect.draft", json!({"pull": [-1, -1, 0]})).unwrap(); app.viewport.gpu = Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: false }); @@ -5448,46 +5369,39 @@ mod tests { assert!(changed.iter().all(|&i| b[4 * i..4 * i + 3].iter().zip(&c[4 * i..4 * i + 3]).all(|(x, y)| x <= y)), "stripes are darker"); } - /// The CPU viewport draws in the colour vision mode: a fixed sketch line in the light theme + /// The view's picture draws in the colour vision mode: a fixed sketch line in the light theme /// takes Deutan's value, and Off's is gone. + #[cfg(not(target_arch = "wasm32"))] #[test] - fn cpu_viewport_draws_in_the_colour_vision_mode() { + fn the_view_picture_draws_in_the_colour_vision_mode() { use crate::theme::ColorVision; + if !crate::gpu::test_picture_renderer() { + return; + } let mut h = crate::scenario::Harness::new(); h.app.ui.dark = false; h.app.run("sketch.create", json!({"plane": "XY"})).unwrap(); let made = h.app.run("sketch.line", json!({"points": [[-30, -20], [30, 20]]})).unwrap(); h.app.run("sketch.constraint.fix", json!({"entity": made["created"]["curves"][0]})).unwrap(); - let rect = Rect::from_min_size(Pos2::ZERO, vec2(320.0, 240.0)); let mut cam = solidcraft_engine::view::home_camera(&h.app.session); cam.set_view(solidcraft_engine::render::StandardView::Top); - let proj = Proj { cam, vp: cam.view_proj(4.0 / 3.0, 100.0), rect }; - h.app.viewport.no_pixels = false; - let count = |h: &mut crate::scenario::Harness, c: Color32| { - h.app.viewport.cpu = None; - let mut out = h.ctx.run_ui(egui::RawInput { screen_rect: Some(rect), ..Default::default() }, |ui| { - cpu_render(&mut h.app, ui.ctx(), ui.painter(), rect, &proj); - }); - let id = h.app.viewport.cpu.as_ref().map(|(_, tex)| tex.id()); - let n = id.and_then(|id| out.textures_delta.set.get(&id)).and_then(|d| d.iter().find(|delta| delta.pos.is_none())).map_or(0, |upload| { - let egui::ImageData::Color(image) = &upload.image; - image.pixels.iter().filter(|p| [p.r(), p.g(), p.b()].iter().zip([c.r(), c.g(), c.b()]).all(|(a, b)| a.abs_diff(b) <= 8)).count() - }); - out.textures_delta.clear(); - n + h.app.cam = cam; + let count = |h: &crate::scenario::Harness, c: Color32| { + let img = crate::control::view_rgba(&h.app, 320, 240).unwrap(); + img.as_chunks::<4>().0.iter().filter(|p| p[..3].iter().zip([c.r(), c.g(), c.b()]).all(|(a, b)| a.abs_diff(b) <= 8)).count() }; let (off, deutan) = (Tokens::light().sketch_locked, Tokens::themed(false, ColorVision::Deutan).sketch_locked); - let (a, b) = (count(&mut h, off), count(&mut h, deutan)); + let (a, b) = (count(&h, off), count(&h, deutan)); assert!(a > 20 && b == 0, "Off: {a} fixed-line pixels, {b} in Deutan's colour"); h.app.preferences.color_vision = ColorVision::Deutan; - let (a, b) = (count(&mut h, off), count(&mut h, deutan)); + let (a, b) = (count(&h, off), count(&h, deutan)); assert!(a == 0 && b > 20, "Deutan: {a} fixed-line pixels in Off's colour, {b} in Deutan's"); } - /// A mode's table reaches the CPU picture: the sketch states and axes it changes, and nothing - /// else (the light theme in Off is the engine's own colours). + /// A mode's table reaches the headless picture's palette: the sketch states and axes it + /// changes, and nothing else (the light theme in Off is the engine's own colours). #[test] - fn cpu_picture_follows_the_colour_vision_mode() { + fn picture_palette_follows_the_colour_vision_mode() { use crate::theme::ColorVision; let rgb = |c: Color32| Rgb(c.r(), c.g(), c.b()); let off = scene_palette(false, ColorVision::Off); @@ -5505,6 +5419,7 @@ mod tests { /// The mode is on from the next frame (theme, widgets, caches, `ui.render`), and Cancel puts /// it back. + #[cfg(not(target_arch = "wasm32"))] #[test] fn colour_vision_mode_reaches_the_frame_and_the_view_caches() { use crate::theme::ColorVision; @@ -5524,8 +5439,11 @@ mod tests { h.frame(); assert_eq!((h.app.preferences.color_vision, crate::theme::vision()), (ColorVision::Off, ColorVision::Off)); assert_eq!(keys(&h.app), before); - // `ui.render` (the CPU picture) shows the mode too: a fixed sketch line in Deutan's value - // (in the light theme, where the red-green table changes it; the render follows the theme). + // `ui.render` shows the mode too: a fixed sketch line in Deutan's value (in the light + // theme, where the red-green table changes it; the render follows the theme). + if !crate::gpu::test_picture_renderer() { + return; + } h.call("ui.prefs", json!({"theme": "light"})); h.frame(); h.app.run("sketch.create", json!({"plane": "XY"})).unwrap(); diff --git a/docs/book/src/dev/architecture.md b/docs/book/src/dev/architecture.md index 026a01cf4..61912142a 100644 --- a/docs/book/src/dev/architecture.md +++ b/docs/book/src/dev/architecture.md @@ -18,5 +18,12 @@ A few rules follow from the layering: - **Everything the user can do is a command** in `crates/engine`. See [The command engine](commands.md). - **The front end is swappable.** Nothing below `ui-egui` depends on egui. The CLI and the MCP - server run the same engine without a window, and `crates/render` has a CPU rasterizer so - headless screenshots work anywhere. + server run the same engine without a window. Headless pictures (`solidcraft-cli snapshot`, MCP + screenshots, `ui.render`, thumbnails) are drawn on the GPU with the viewport's own pipelines + (`crates/gpu`, `capture`): the engine describes the scene (`view::scene`) and the host installs + the renderer (`engine::capture`). The tiers, in order: a hardware GPU, a software adapter (Mesa + lavapipe or llvmpipe, WARP), and last `crates/render`'s CPU rasterizer, which draws no surface + analysis, highlights or legends. `SOLIDCRAFT_GPU=auto` walks all three, `hardware` and `software` + stay on their tier (an error without one), `cpu` forces the rasterizer; every picture's reply + names its `renderer` (`gpu`, `gpu-software`, `cpu`) and a CPU picture carries a warning. + `solidcraft-cli gpu` lists the adapters and the tier the policy lands on. diff --git a/docs/book/src/guide/getting-started.md b/docs/book/src/guide/getting-started.md index 7aff90d52..30940c6ee 100644 --- a/docs/book/src/guide/getting-started.md +++ b/docs/book/src/guide/getting-started.md @@ -186,7 +186,7 @@ A script is a list of commands: ![The bracket example, rendered by solidcraft-cli snapshot](../generated/bracket.png) -`snapshot` looks at the model from the iso view. `--view NAME` takes another standard view (`front`, `back`, `top`, `bottom`, `left`, `right`) or the name of a view saved in the design with `view.save`. `--camera JSON` takes any camera, as the MCP `screenshot` tool does (its conventions are in [the MCP page](mcp.md#camera-and-close-up-recipe)). A script that applies a view itself with `view.apply` sets the camera too. The ground grid lies on Z 0, so it cuts through a part that straddles it: `--no-grid` leaves it out of the picture, and `--no-axes` the origin's axes. +`snapshot` looks at the model from the iso view. `--view NAME` takes another standard view (`front`, `back`, `top`, `bottom`, `left`, `right`) or the name of a view saved in the design with `view.save`. `--camera JSON` takes any camera, as the MCP `screenshot` tool does (its conventions are in [the MCP page](mcp.md#camera-and-close-up-recipe)). A script that applies a view itself with `view.apply` sets the camera too. The ground grid lies on Z 0, so it cuts through a part that straddles it: `--no-grid` leaves it out of the picture, and `--no-axes` the origin's axes. The picture is drawn on the GPU with the viewport's own pipelines, so it shows what the window would (a surface analysis such as `inspect.zebra` included); a machine without a GPU uses a software one (Mesa's lavapipe on Linux, WARP on Windows), and with neither (a Mac without usable Metal, a Linux box without Mesa's Vulkan) the CPU rasterizer draws it, without surface analysis colours, and the reply's `renderer` says `cpu` with a warning. `SOLIDCRAFT_GPU=auto|hardware|software|cpu` chooses (`hardware` and `software` fail rather than fall to the CPU), and `solidcraft-cli gpu` lists the adapters and the tier a snapshot would use. ```sh solidcraft-cli snapshot part.solidcraft --out photo.png --view Photo diff --git a/docs/control-protocol.md b/docs/control-protocol.md index eb2360fd4..3de543ff8 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -136,7 +136,7 @@ labels; `prefs:measure_axis_distances` identifies the checkbox. | `ui.key` | `key` (egui key name, `Enter`, `Escape`…), `cmd?`, `shift?` | | | `ui.text` | `text` | typed text | | `ui.screenshot` | `path?` | PNG of the window (needs a presented frame) | -| `ui.render` | `path`, `width?`, `height?`, `grid?`, `axes?` | CPU render of the model with the current camera (no window needed), 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.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.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 | diff --git a/docs/mcp.md b/docs/mcp.md index 4a2ba2524..4085cd84a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -18,7 +18,7 @@ document remains the reference implementation today. ## Start it ```sh -# Headless: an in-process design session, no window (CPU renders for screenshots). +# Headless: an in-process design session, no window (screenshots are drawn on the GPU). solidcraft-cli mcp # Headless, starting from a design file or a command script. @@ -149,7 +149,7 @@ They cover the workflow, the command shapes, how to verify with `measure`, and t | `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. | -| `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: CPU render fitted to the model, or from the named view or camera. 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. | +| `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. | | `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. | | `crash_reports` | `id?`, `limit?` | The crash reports on this computer, newest first; with `id`, the whole report (backtrace, command, recent commands, `design_path`/`replay_path`). See [crash-reports.md](crash-reports.md). | diff --git a/xtask/src/book.rs b/xtask/src/book.rs index b20f0115f..03311f7bc 100644 --- a/xtask/src/book.rs +++ b/xtask/src/book.rs @@ -2,7 +2,7 @@ //! //! The command reference (`docs/book/src/reference/commands.md`) comes from //! `solidcraft-cli commands`, so it can't drift from the registry. The screenshots in -//! `docs/book/src/generated/` are CPU renders by `solidcraft-cli snapshot` of `examples/*.json` +//! `docs/book/src/generated/` are GPU renders by `solidcraft-cli snapshot` of `examples/*.json` //! and `docs/book/scripts/*.json`, plus the app screenshot from `docs/screenshots/`. Both are //! gitignored and attributed in ATTRIBUTION.md. The book itself is built by `mdbook` (a separate //! tool, not a dependency) into `target/book`. diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs index b2a5413f9..2118c8e0d 100644 --- a/xtask/src/layers.rs +++ b/xtask/src/layers.rs @@ -56,8 +56,9 @@ pub const TABLE: &[(&str, Class)] = &[ ]; /// Explicit orderings *within* a layer (earlier may be used by later). -/// The viewport draws display plans the GPU crate evaluates. -pub const INTRA_LAYER_ORDER: &[&[&str]] = &[&["gpu", "ui-egui"]]; +/// The viewport draws display plans the GPU crate evaluates and draws with its pipelines; the MCP +/// server's tests draw screenshots with them. +pub const INTRA_LAYER_ORDER: &[&[&str]] = &[&["gpu", "ui-egui"], &["gpu", "mcp"]]; fn intra_layer_allowed(from: &str, to: &str) -> bool { let (from, to) = (short_name(from), short_name(to)); From 5165e428cd1908461a259a0dbb9a3d472a003a25 Mon Sep 17 00:00:00 2001 From: phanoob Date: Fri, 16 Oct 2026 04:19:28 +0200 Subject: [PATCH 40/92] Boolean: refuse a nudged result that meshes inconsistently (#1360) (#1455) The last-resort nudge's result is also measured finely; a face left a hair wide that meshes as its whole plane no longer passes as a plausible cut. --- crates/engine/src/cmd/features_more_tests.rs | 33 ++++++++++++++++++++ crates/kernel/src/ops.rs | 12 +++++-- 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/features_more_tests.rs b/crates/engine/src/cmd/features_more_tests.rs index 413c04785..582ae1fa5 100644 --- a/crates/engine/src/cmd/features_more_tests.rs +++ b/crates/engine/src/cmd/features_more_tests.rs @@ -1058,6 +1058,39 @@ fn a_ring_cut_round_a_hole_takes_in_the_hole_it_is_drawn_round() { assert!(if ok { rel(blind, taken) < 1e-3 } else { blind.abs() < 1e-6 }, "{ok} {blind} vs {taken}"); } +/// #1360: an annulus cut 3 mm into a chamfered disc, its inner circle on a hole's wall. The +/// boolean can't intersect the two walls lying on each other; its last resort (the tool moved by +/// a micron) left a face a hair wide that meshes as its whole plane at a fine step, and the part +/// came back 21000 mm³ larger than before, a square plane across it. A cut may fail there, but it +/// never gives back more than it was given. +#[test] +fn a_cut_flush_with_a_hole_never_grows_the_part() { + let mut s = Session::default(); + for (c, p) in [ + ("sketch.create", json!({"plane":"XY"})), + ("sketch.circle.center", json!({"center":[0,0],"radius":40})), + ("sketch.finish", json!({})), + ("solid.extrude", json!({"distance":10})), + ("solid.hole", json!({"position":[20,0,10],"diameter":6})), + ("solid.chamfer", json!({"edges":[[40,0,10]],"distance":1})), + ("sketch.create", json!({"plane":{"face":[0,0,10]}})), + ("sketch.circle.center", json!({"center":[20,0],"radius":3})), + ("sketch.circle.center", json!({"center":[20,0],"radius":6})), + ("sketch.finish", json!({})), + ] { + run(&mut s, c, p); + } + let before = volume(&mut s); + // Profile 2: the annulus between the hole's wall and the larger circle. + let r = s.execute("solid.extrude", &json!({"direction":"negative","distance":"3","operation":"cut","profiles":[2]})); + let after = volume(&mut s); + let ring = std::f64::consts::PI * (36.0 - 9.0) * 3.0; + match r { + Ok(_) => assert!(rel(before - after, ring) < 1e-2, "{before} -> {after}, want {ring} taken"), + Err(_) => assert!(rel(after, before) < 1e-9, "{before} -> {after} after a failed cut"), + } +} + /// A line of text cut into a face: the letters' curves (the font's quadratics) are read /// exactly, and the cut is decided in 2D in one boolean, at any depth and where the text runs /// off the face. The B-rep boolean failed on many letters at once ("no result" at 3.5 mm, and diff --git a/crates/kernel/src/ops.rs b/crates/kernel/src/ops.rs index 491890e5b..6bb9a9835 100644 --- a/crates/kernel/src/ops.rs +++ b/crates/kernel/src/ops.rs @@ -956,15 +956,23 @@ fn boolean_whole(a: &Body, b: &Body, op: BoolOp) -> Result> { match r { Ok(Some(body)) => { let (ok, v) = check(&body); - if ok { + // Measured finely too: a face the boolean left a hair wide, its loops a hair + // apart, can mesh as its whole plane at a fine step though it meshed as a sliver + // at the check's (#1360: an annulus cut flush with a hole's wall came out 21000 + // mm³ larger than the part it was cut from, a square plane across it). + let fine_ok = ok && crate::measure(&body).is_ok_and(|m| plausible(m.volume, op, va, vb, slack)); + if ok && !fine_ok { + last = format!("{last}; the nudged tool gave a solid whose faces mesh inconsistently"); + } else if ok { merge(diagnostics); let mut event = BooleanFallback::new(BooleanStrategy::ToolNudge); event.translation_mm = translation.len(); event.rotation_rad = 2e-6; record(event); return Ok(Some(body)); + } else { + last = format!("{last}; the nudged tool gave an implausible volume {v:.4}"); } - last = format!("{last}; the nudged tool gave an implausible volume {v:.4}"); } Ok(None) => { merge(diagnostics); From daf618c344402f40502634d99f389d536576d674 Mon Sep 17 00:00:00 2001 From: rlartot <94693724+rlartot@users.noreply.github.com> Date: Fri, 16 Oct 2026 04:19:51 +0200 Subject: [PATCH 41/92] Edge division: evaluate each point once (#1560) Thanks @rlartot. --- crates/kernel/src/edge_polyline_tests.rs | 159 ++++++++++++++++++ crates/kernel/src/lib.rs | 2 + docs/perf.md | 49 ++++++ vendor/README.md | 5 + vendor/truck-meshalgo/src/tessellation/mod.rs | 17 +- .../src/tessellation/triangulation.rs | 26 +-- 6 files changed, 243 insertions(+), 15 deletions(-) create mode 100644 crates/kernel/src/edge_polyline_tests.rs diff --git a/crates/kernel/src/edge_polyline_tests.rs b/crates/kernel/src/edge_polyline_tests.rs new file mode 100644 index 000000000..88d068e9d --- /dev/null +++ b/crates/kernel/src/edge_polyline_tests.rs @@ -0,0 +1,159 @@ +//! The vendored edge division evaluates each parameter once (the ends of a piece are carried +//! along, its midpoint is the probe and an end of both halves). Regressions against the division +//! as it was, which evaluated both ends of every piece again: the polylines must be the same, bit +//! for bit, including the fallbacks for samples that do not evaluate. +#![allow(clippy::unwrap_used, clippy::panic)] +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use solidcraft_geom::Vec3; +use truck_meshalgo::prelude::PolylineCurve; +use truck_meshalgo::tessellation::{Deflection, TrySubs, bounded_polyline}; +use truck_modeling::{BoundedCurve, Curve, EuclideanSpace, MetricSpace, ParameterDivision1D, ParameterRange, ParametricCurve, Point3, Vector3}; + +use crate::*; + +/// A curve that counts its evaluations. +#[derive(Clone)] +struct Counted { + curve: Curve, + calls: Arc, +} + +impl Counted { + fn new(curve: &Curve) -> Self { + Counted { curve: curve.clone(), calls: Arc::default() } + } + + fn calls(&self) -> usize { + self.calls.load(Ordering::Relaxed) + } +} + +impl ParametricCurve for Counted { + type Point = Point3; + type Vector = Vector3; + fn subs(&self, t: f64) -> Point3 { + self.calls.fetch_add(1, Ordering::Relaxed); + self.curve.subs(t) + } + fn der(&self, t: f64) -> Vector3 { + self.curve.der(t) + } + fn der2(&self, t: f64) -> Vector3 { + self.curve.der2(t) + } + fn parameter_range(&self) -> ParameterRange { + self.curve.parameter_range() + } + fn period(&self) -> Option { + self.curve.period() + } +} + +impl BoundedCurve for Counted {} + +/// The division samples through `TrySubs`: count those evaluations. +impl TrySubs for Counted { + fn try_subs(&self, t: f64) -> Option { + self.calls.fetch_add(1, Ordering::Relaxed); + TrySubs::try_subs(&self.curve, t) + } + fn approx_subs(&self, t: f64) -> Point3 { + self.calls.fetch_add(1, Ordering::Relaxed); + TrySubs::approx_subs(&self.curve, t) + } +} + +impl ParameterDivision1D for Counted { + type Point = Point3; + fn parameter_division(&self, range: (f64, f64), tol: f64) -> (Vec, Vec) { + self.curve.parameter_division(range, tol) + } +} + +/// `bounded_polyline` before it carried the end points: 4 evaluations per piece (both ends, the +/// probe and the midpoint), with the same fallbacks for samples that do not evaluate. +fn reference(curve: &Counted, range: (f64, f64), d: Deflection) -> PolylineCurve { + const MAX_EDGE_POINTS: usize = 20_000; + let (tol, turn2) = (d.chord, d.turn2()); + let end = |t: f64| curve.try_subs(t).unwrap_or_else(|| curve.approx_subs(t)); + let probe = |t: f64| curve.try_subs(t).unwrap_or(Point3::new(f64::NAN, f64::NAN, f64::NAN)); + let mut out = vec![end(range.0)]; + let mut stack: Vec<(f64, f64, usize)> = vec![(range.0, range.1, 0)]; + while let Some((a, b, depth)) = stack.pop() { + let (pa, pb) = (end(a), end(b)); + let t = a + (b - a) * 0.4729; + let chord = pa + (pb - pa) * 0.4729; + let d2 = probe(t).distance2(chord); + let tm = 0.5 * (a + b); + let dm = probe(tm).distance2(pa.midpoint(pb)); + let flat = !(d2 >= tol * tol || dm >= tol * tol); + let flat = flat && !d.turns(turn2, d2.max(dm), pa.distance2(pb)); + if flat || depth >= 24 || out.len() + stack.len() >= MAX_EDGE_POINTS { + out.push(pb); + } else { + stack.push((tm, b, depth + 1)); + stack.push((a, tm, depth + 1)); + } + } + PolylineCurve(out) +} + +/// Divides `curve` both ways and checks the points, their order and the evaluations; returns +/// the polyline. +fn same_division(curve: &Curve, d: Deflection) -> Vec { + let range = curve.range_tuple(); + let (before, after) = (Counted::new(curve), Counted::new(curve)); + let old = reference(&before, range, d).0; + let new = bounded_polyline(&after, range, d).0; + let bits = |p: &Point3| [p.x.to_bits(), p.y.to_bits(), p.z.to_bits()]; + assert_eq!(old.len(), new.len(), "{d:?}"); + for (i, (p, q)) in old.iter().zip(&new).enumerate() { + assert_eq!(bits(p), bits(q), "point {i} of {}: {p:?} before, {q:?} now ({d:?})", new.len()); + } + // Every piece is kept (one point) or halved: n points come from 2n - 3 pieces. + let pieces = 2 * new.len() - 3; + assert_eq!(before.calls(), 1 + 4 * pieces); + assert_eq!(after.calls(), 2 + 2 * pieces); + new +} + +/// The chord tolerance alone (booleans), then with the display's facet angle. +fn deflections(tol: f64) -> [Deflection; 2] { + [Deflection::chord(tol), Deflection { chord: tol, angle: DISPLAY_ANGLE, floor: tol * 0.05, rulings: true }] +} + +#[test] +fn intersection_curves_of_a_drilled_cylinder_divide_as_before() { + // The radial hole of a clamping hub: both cylinders are NURBS, so each point of the edges + // is two grid searches. + let hub = cylinder(Vec3::new(0.0, 0.0, -10.0), Vec3::Z, 8.0, 20.0).unwrap(); + let drill = cylinder(Vec3::new(-12.0, 0.0, 1.5), Vec3::X, 1.25, 24.0).unwrap(); + let drilled = boolean(&hub, &drill, BoolOp::Cut).unwrap().unwrap(); + let curves: Vec = drilled.solid.edge_iter().map(|e| e.curve()).filter(|c| matches!(c, Curve::IntersectionCurve(_))).collect(); + assert!(curves.len() >= 2, "{} intersection curves", curves.len()); + // One curve with each deflection (each division takes about half a second here). + for (curve, d) in curves.iter().zip(deflections(0.01)) { + let points = same_division(curve, d); + assert!(points.len() > 8, "{} points ({d:?})", points.len()); + // On the drill's wall. + for p in &points { + let r = (p.y * p.y + (p.z - 1.5) * (p.z - 1.5)).sqrt(); + assert!((r - 1.25).abs() < 1e-3, "{p:?} at {r} from the drill's axis"); + } + } +} + +#[test] +fn circle_divides_as_before() { + let body = cylinder(Vec3::ZERO, Vec3::Z, 5.0, 10.0).unwrap(); + let circle = body.solid.edge_iter().map(|e| e.curve()).find(|c| !matches!(c, Curve::Line(_))).unwrap(); + for d in deflections(0.001) { + let points = same_division(&circle, d); + assert!(points.len() > 18, "{} points ({d:?})", points.len()); + for p in &points { + assert!(((p.x * p.x + p.y * p.y).sqrt() - 5.0).abs() < 1e-9, "{p:?}"); + } + } +} diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rs index 46c4a087f..77ae5f6e7 100644 --- a/crates/kernel/src/lib.rs +++ b/crates/kernel/src/lib.rs @@ -30,6 +30,8 @@ mod clearance; mod coplanar; mod curveblend; mod delete_face; +#[cfg(test)] +mod edge_polyline_tests; mod emboss; mod face_params; #[cfg(test)] diff --git a/docs/perf.md b/docs/perf.md index ad0cd7274..cd6f35c9a 100644 --- a/docs/perf.md +++ b/docs/perf.md @@ -1,5 +1,54 @@ # Design loading +## Edges made by booleans: each point evaluated once (2026-10-16) + +A boolean meshes both operands with truck-meshalgo, which first divides every edge into a +polyline (`bounded_polyline`, vendored). An edge that an earlier boolean made is an +intersection curve. Each of its points is found by a grid search on each of the two surfaces, +51 × 51 evaluations of a NURBS surface each, before Newton. The division evaluated both ends of +every piece again, so 2 of its 4 evaluations per piece repeated a point it already had. +Profiles of `main` (01b1b705) on the machine below put the division at 42 % of the CPU time +of opening the rover, 58 % of `bench-agent` and 82-85 % of a drilled hub or a union of tubes. + +Each piece now carries the points of its ends, and its midpoint is both the probe and an end of +both halves: 2 evaluations per piece. The fallbacks for samples that do not evaluate (#1364) are +kept: a midpoint that fails is NaN as a probe and the curve's approximation as an end, exactly as +before. The polyline is the same, bit for bit: `edge_polyline_tests` compares it with the +previous division (points, order and number of evaluations) on the intersection curves of a +drilled cylinder and on a circle. + +Release `solidcraft-cli` from `main` (73493b94) and the same with the change, 3 alternating +pairs (before/after, after/before, before/after), each run a new process timed with +`/usr/bin/time -v`, started once the 1-minute load average was below 2.5. Medians, with the +range of the 3 runs. 2018 laptop: Intel Core i7-8565U (4 cores / 8 threads, 15 W), 7.4 GB, +Ubuntu (Linux 7.0), on mains power: + +| Run | Evaluation | Meshes | Wall time | CPU time | Peak RSS | +|---|---:|---:|---:|---:|---:| +| `bench-open`, `examples/acceptance/sensor_enclosure.json` | 3,203 → 3,089 ms | 6 → 6 ms | 3.2 → 3.1 s | 8.7 → 8.5 s | 91 → 91 MB | +| `bench-open`, a hub barrel with one radial hole cut through it | 966 → 817 ms | 878 → 481 ms | 1.9 → 1.4 s (-24 %) | 4.4 → 2.8 s (-37 %) | 27 → 30 MB | +| `bench-open`, the frame of the `bench-agent` bicycle (one union of tilted tubes) | 8,204 → 6,277 ms | 1,711 → 893 ms | 9.9 → 7.2 s (-28 %) | 33.3 → 20.6 s (-38 %) | 44 → 46 MB | +| `bench-open`, a rover (3,324 features, 1,395 bodies) | 26,783 → 22,792 ms | 7,960 → 6,046 ms | 35.7 → 29.8 s (-17 %) | 129.0 → 101.9 s (-21 %) | 2,076 → 2,079 MB | +| `bench-agent` (build 33.5 → 30.2 s, -10 %) | 10,553 → 8,565 ms | 2,778 → 2,081 ms | 47.6 → 41.1 s (-14 %) | 124.0 → 91.0 s (-27 %) | 1,428 → 1,432 MB | + +`bench-agent`'s evaluation and meshes are those of reopening the saved design. CPU time is the +steadier measure on this 15 W processor: its before and after ranges are apart for the four +cases with boolean edges (the hub 3.0-4.4 s before, 2.5-2.9 s after; the rover 113.6-133.5 s, +101.0-102.5 s), while the first pair's "before" run, which started on a cool processor, overlaps +the "after" wall times of the two short cases. The sensor enclosure does not change: its time goes +to grid searches in face meshing, which this does not touch. An earlier series on `main` +(8535d229), on a quieter machine, gave -38 %, -35 %, -18 % and -16 % of wall time for the same +four cases. The CPU time saved is close to half the division's share in the profile. The mesh +phase gains as well, so these display meshes also call the reference mesher somewhere (where is +not traced here; `tess::edges`, the display plans' own edge division, already evaluated each +point once). In the rover, the second shell (which names every body's faces, so meshes them all) +goes from 7.8 s to 5.7 s. + +No model changed. `solidcraft-cli eval` of the five designs (the bicycle as `bench-agent` saved +it) is the same with both binaries apart from the per-feature milliseconds: bodies, volumes, +areas, centres, bounding boxes, topology counts and warnings. `bench-open` meshes the same +triangle counts, and the bicycles both binaries save differ only in the document's name. + ## STEP assemblies: a repeated part is meshed once (2026-10-14) The reader already converts each B-rep item once and keeps it for the instances that list it diff --git a/vendor/README.md b/vendor/README.md index eff274ac7..62cd65e60 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -108,6 +108,11 @@ Changes: point that does not evaluate counts as flat instead of recursing). Surface grids refine only the direction that bends, and a ruling left undivided gets cells comparable to the other direction (long triangles from a trim loop to the grid's far ends cut through cylinders). +- `tessellation/triangulation.rs`: an edge's division evaluates each parameter once. A piece + carries the points of its ends and its midpoint is an end of both halves: 2 evaluations per + piece instead of 4, and the same polyline (a point of an intersection curve costs two grid + searches of its surfaces). `bounded_polyline` and `Deflection::turn2`/`turns` are public but + hidden, for the kernel's regression against the old division. - `tessellation/mod.rs`, `tessellation/triangulation.rs`, for display: a `Deflection` is the chord tolerance plus an optional bound on the angle one facet spans, and `RoundMeshableShape::robust_triangulation_within` divides by it: an edge or a grid direction diff --git a/vendor/truck-meshalgo/src/tessellation/mod.rs b/vendor/truck-meshalgo/src/tessellation/mod.rs index f9d64f02a..1bcfd8a71 100644 --- a/vendor/truck-meshalgo/src/tessellation/mod.rs +++ b/vendor/truck-meshalgo/src/tessellation/mod.rs @@ -25,6 +25,13 @@ pub fn preview_face(surface: &S, loops: &[Vec] triangulation::preview_face(surface, loops, steps) } +/// SolidCraft: an edge's polyline as the meshers divide it (at most 20 000 points). Exposed for +/// the kernel's regressions in the workspace CI. +#[doc(hidden)] +pub fn bounded_polyline(curve: &C, range: (f64, f64), d: Deflection) -> PolylineCurve { + triangulation::bounded_polyline(curve, range, d) +} + /// SolidCraft: sampling a curve that may fail to evaluate. truck's `IntersectionCurve::subs` /// unwraps the projection of its leader's point onto both surfaces, which does not converge /// everywhere; the mesher samples through this trait so that a failed sample is data, not a panic. @@ -145,8 +152,9 @@ impl Deflection { /// The squared sag over squared length above which a facet turns more than `angle`: a /// chord spanning `a` of a circle sags `tan(a / 4) / 2` of its length. Infinite without - /// an angle bound. - pub(super) fn turn2(&self) -> f64 { + /// an angle bound. SolidCraft: public for the kernel's regressions. + #[doc(hidden)] + pub fn turn2(&self) -> f64 { match self.angular() && self.angle < std::f64::consts::PI { true => (f64::tan(self.angle / 4.0) / 2.0).powi(2), false => f64::INFINITY, @@ -154,8 +162,9 @@ impl Deflection { } /// Whether the angle bound splits a facet of squared sag `sag2` and squared length `len2` - /// (`turn2` from [`Deflection::turn2`]). - pub(super) fn turns(&self, turn2: f64, sag2: f64, len2: f64) -> bool { + /// (`turn2` from [`Deflection::turn2`]). SolidCraft: public for the kernel's regressions. + #[doc(hidden)] + pub fn turns(&self, turn2: f64, sag2: f64, len2: f64) -> bool { turn2.is_finite() && sag2 > self.floor * self.floor && sag2 > turn2 * len2 } } diff --git a/vendor/truck-meshalgo/src/tessellation/triangulation.rs b/vendor/truck-meshalgo/src/tessellation/triangulation.rs index 773f8f41b..3049e3893 100644 --- a/vendor/truck-meshalgo/src/tessellation/triangulation.rs +++ b/vendor/truck-meshalgo/src/tessellation/triangulation.rs @@ -861,30 +861,34 @@ pub(super) fn face_cap(faces: usize) -> usize { /// bisection depth of 24; a midpoint that does not evaluate (NaN) counts as flat (truck's /// version recursed on it 100 levels deep, which never finishes). A piece within the chord /// tolerance is still halved while it turns more than the deflection's angle. -fn bounded_polyline(curve: &C, range: (f64, f64), d: Deflection) -> PolylineCurve { +pub(super) fn bounded_polyline(curve: &C, range: (f64, f64), d: Deflection) -> PolylineCurve { let (tol, turn2) = (d.chord, d.turn2()); // A sample that does not evaluate (an intersection curve whose projection fails): an interval // end falls back to the curve's approximation so the polyline stays finite; an interior probe - // is NaN, which counts as flat. + // is NaN, which counts as flat. Each parameter is evaluated once: a piece carries the points + // of its ends, and its midpoint, an end of both halves, serves as probe and as end (a point of + // an intersection curve costs two grid searches). let end = |t: f64| curve.try_subs(t).unwrap_or_else(|| curve.approx_subs(t)); - let probe = |t: f64| curve.try_subs(t).unwrap_or(Point3::new(f64::NAN, f64::NAN, f64::NAN)); - let mut out = vec![end(range.0)]; - let mut stack: Vec<(f64, f64, usize)> = vec![(range.0, range.1, 0)]; - while let Some((a, b, depth)) = stack.pop() { - let (pa, pb) = (end(a), end(b)); + let nan = Point3::new(f64::NAN, f64::NAN, f64::NAN); + let (p0, p1) = (end(range.0), end(range.1)); + let mut out = vec![p0]; + let mut stack: Vec<(f64, f64, Point3, Point3, usize)> = vec![(range.0, range.1, p0, p1, 0)]; + while let Some((a, b, pa, pb, depth)) = stack.pop() { let t = a + (b - a) * 0.4729; let chord = pa + (pb - pa) * 0.4729; - let d2 = probe(t).distance2(chord); + let d2 = curve.try_subs(t).unwrap_or(nan).distance2(chord); let tm = 0.5 * (a + b); - let dm = probe(tm).distance2(pa.midpoint(pb)); + let sm = curve.try_subs(tm); + let dm = sm.unwrap_or(nan).distance2(pa.midpoint(pb)); let flat = !(d2 >= tol * tol || dm >= tol * tol); let flat = flat && !d.turns(turn2, d2.max(dm), pa.distance2(pb)); if flat || depth >= 24 || out.len() + stack.len() >= MAX_EDGE_POINTS { out.push(pb); } else { + let pm = sm.unwrap_or_else(|| curve.approx_subs(tm)); // Right half after the left one (stack order). - stack.push((tm, b, depth + 1)); - stack.push((a, tm, depth + 1)); + stack.push((tm, b, pm, pb, depth + 1)); + stack.push((a, tm, pa, pm, depth + 1)); } } PolylineCurve(out) From a422fb1a4bfb7a04e8ac5a4a7c07e0c3f1f1dbfe Mon Sep 17 00:00:00 2001 From: Erikas <5955795+erkexzcx@users.noreply.github.com> Date: Fri, 16 Oct 2026 05:37:08 +0300 Subject: [PATCH 42/92] solid.mirror: a plane's {origin} takes length expressions and follows them (#1492) (#1501) Thanks @erkexzcx. --- crates/doc/src/assembly.rs | 5 +++ crates/doc/src/clipboard.rs | 2 +- crates/doc/src/document.rs | 17 +++++++++ .../format/pending/placed-plane-origins.rs | 4 +++ crates/doc/src/params.rs | 28 +++++++++++++-- crates/doc/src/walk.rs | 17 +++++++-- crates/engine/src/cmd/features.rs | 22 ++++++++---- crates/engine/src/tests/mirror_planes.rs | 35 +++++++++++++++++++ skills/solidcraft-modeling/SKILL.md | 2 +- skills/solidcraft-modeling/reference.md | 2 +- 10 files changed, 120 insertions(+), 14 deletions(-) create mode 100644 crates/doc/src/format/pending/placed-plane-origins.rs diff --git a/crates/doc/src/assembly.rs b/crates/doc/src/assembly.rs index aeda6e265..20172b342 100644 --- a/crates/doc/src/assembly.rs +++ b/crates/doc/src/assembly.rs @@ -136,6 +136,11 @@ fn map_plane(m: &Mat, p: &Plane) -> Plane { fn map_plane_ref(m: &Mat, p: &mut PlaneRef) { match p { PlaneRef::Custom { plane } => *plane = map_plane(m, plane), + PlaneRef::Placed { origin, x_dir, y_dir } => { + map_point_expr(m, origin); + *x_dir = apply_vector(m, *x_dir); + *y_dir = apply_vector(m, *y_dir); + } PlaneRef::Face { plane, at, .. } => { *plane = map_plane(m, plane); *at = apply_point(m, *at); diff --git a/crates/doc/src/clipboard.rs b/crates/doc/src/clipboard.rs index cc449d701..13fa98298 100644 --- a/crates/doc/src/clipboard.rs +++ b/crates/doc/src/clipboard.rs @@ -223,7 +223,7 @@ impl crate::Feature { for (_, e, _) in self.kind.inputs_mut() { *e = clone_expression(e, parameters); } - for e in self.kind.point_expr_mut().into_iter().flatten() { + for e in self.kind.placement_exprs_mut() { *e = clone_expression(e, parameters); } self.kind.remap_bodies(bodies); diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 2f13f4e3a..233c0a2e8 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -42,6 +42,14 @@ pub enum PlaneRef { Origin { name: String }, /// An explicit plane (e.g. picked from a planar face). Custom { plane: Plane }, + /// An explicit plane whose origin is given as length expressions + /// (`{origin: ["half", 0, 0], normal: [1, 0, 0]}`), so it follows parameter changes. + Placed { + #[serde(with = "point_expr")] + origin: PointExpr, + x_dir: Vec3, + y_dir: Vec3, + }, /// Another plane offset along its normal by an expression. Offset { base: Box, distance: String }, /// Another plane rotated about a line (in world coordinates) by an angle expression. @@ -2938,6 +2946,15 @@ impl Document { PlaneRef::Custom { plane } | PlaneRef::Face { plane, .. } => { Plane::new(plane.origin, plane.x, plane.y).ok_or_else(|| DocError::Invalid("degenerate plane".into())) } + PlaneRef::Placed { origin, x_dir, y_dir } => { + let [x, y, z] = origin; + let o = + Vec3::new(Self::eval_in(vals, x, Kind::Length)?, Self::eval_in(vals, y, Kind::Length)?, Self::eval_in(vals, z, Kind::Length)?); + if ![o.x, o.y, o.z].iter().all(|c| c.is_finite() && c.abs() < 1e9) { + return Err(DocError::Invalid("the plane's origin is out of range".into())); + } + Plane::new(o, *x_dir, *y_dir).ok_or_else(|| DocError::Invalid("degenerate plane".into())) + } PlaneRef::Offset { base, distance } => { let b = self.resolve_plane_in(vals, base, depth + 1, st)?; Ok(b.offset(Self::eval_in(vals, distance, Kind::Length)?)) diff --git a/crates/doc/src/format/pending/placed-plane-origins.rs b/crates/doc/src/format/pending/placed-plane-origins.rs new file mode 100644 index 000000000..91a18d622 --- /dev/null +++ b/crates/doc/src/format/pending/placed-plane-origins.rs @@ -0,0 +1,4 @@ +//! An explicit plane (a mirror's, or any plane reference) can be `placed`: an `origin` of three +//! length expressions with `x_dir` and `y_dir`, so it follows the design's parameters (#1492). A +//! plane whose origin is plain numbers is still saved as `custom`. Older designs need no +//! transformation; 0.13.x asks for an update instead of failing to read the plane. diff --git a/crates/doc/src/params.rs b/crates/doc/src/params.rs index c9753be45..f956bcf12 100644 --- a/crates/doc/src/params.rs +++ b/crates/doc/src/params.rs @@ -44,6 +44,30 @@ impl FeatureKind { v } + /// The coordinates of the points that place the feature: a primitive's position, an + /// explicit plane's origin. They are not inputs (no parameter names), but follow + /// parameters as inputs do. + pub fn placement_exprs_mut(&mut self) -> Vec<&mut String> { + let mut v = Vec::new(); + self.walk_exprs_mut(&mut |(_, e, _, role)| { + if role == ExprRole::Placement { + v.push(e); + } + }); + v + } + + /// Read-only view of [`FeatureKind::placement_exprs_mut`]. + pub fn placement_exprs(&self) -> Vec<&str> { + let mut v = Vec::new(); + self.walk_exprs(&mut |(_, e, _, role)| { + if role == ExprRole::Placement { + v.push(e.as_str()); + } + }); + v + } + /// Every expression the feature uses: its inputs, then a primitive's placement coordinates. pub fn expressions(&self) -> Vec<&str> { let (mut inputs, mut placement) = (Vec::new(), Vec::new()); @@ -575,7 +599,7 @@ impl Document { } } } - if f.kind.point_expr().is_some_and(|p| p.iter().any(|e| expr::references(e).iter().any(|r| r == name))) { + if f.kind.placement_exprs().iter().any(|e| expr::references(e).iter().any(|r| r == name)) { out.push(ParamUser::Feature { feature: f.id, name: f.name.clone(), input: "Position".into() }); } if let FeatureKind::Sketch { sketch, .. } = &f.kind { @@ -646,7 +670,7 @@ impl Document { *x = new.to_string(); } } - for e in f.kind.point_expr_mut().into_iter().flatten() { + for e in f.kind.placement_exprs_mut() { let r = expr::rename_reference(e, old, new); if r != *e { *e = r; diff --git a/crates/doc/src/walk.rs b/crates/doc/src/walk.rs index dc32c1771..534af73c8 100644 --- a/crates/doc/src/walk.rs +++ b/crates/doc/src/walk.rs @@ -264,8 +264,9 @@ impl &'static str> Label for F { } } -/// The offsets and angles of a plane, outermost first (nesting is capped like every walk over a -/// plane), the construction plane it is built on, and the plane itself. +/// The offsets and angles of a plane, outermost first, and an explicit origin's coordinates +/// (nesting is capped like every walk over a plane), the construction plane it is built on, and +/// the plane itself. impl Walk for PlaneRef { fn walk_exprs<'a>(&'a self, f: &mut dyn FnMut(ExprItem<'a>)) { let mut p = self; @@ -280,6 +281,12 @@ impl Walk for PlaneRef { p = base; } PlaneRef::AlongPath { t, .. } => return f(("Distance (0 to 1)", t, Kind::Unitless, ExprRole::Input)), + PlaneRef::Placed { origin, .. } => { + for (label, e) in ["X", "Y", "Z"].into_iter().zip(origin) { + f((label, e, Kind::Length, ExprRole::Placement)); + } + return; + } _ => return, } } @@ -297,6 +304,12 @@ impl Walk for PlaneRef { p = base; } PlaneRef::AlongPath { t, .. } => return f(("Distance (0 to 1)", t, Kind::Unitless, ExprRole::Input)), + PlaneRef::Placed { origin, .. } => { + for (label, e) in ["X", "Y", "Z"].into_iter().zip(origin) { + f((label, e, Kind::Length, ExprRole::Placement)); + } + return; + } _ => return, } } diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs index ce17bea52..6adb6aeb1 100644 --- a/crates/engine/src/cmd/features.rs +++ b/crates/engine/src/cmd/features.rs @@ -48,7 +48,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .at("SOLID", "CREATE") .icon("pattern_rect") .params("features: [names] | bodies: [names]; path_sketch: sketch; path: [curve ids in order]; count; spacing (between instances) | distance (first to last); orientation?: identical|path; flip?: bool"), - CommandSpec::new("solid.mirror", "Mirror", mirror).at("SOLID", "CREATE").icon("mirror").params("features: [names] | bodies: [names] (combine?: join with the original); plane: XY|XZ|YZ|construction plane name or id|{origin, normal}|{origin, x_dir, y_dir} (a construction plane keeps the mirror following it)"), + CommandSpec::new("solid.mirror", "Mirror", mirror).at("SOLID", "CREATE").icon("mirror").params("features: [names] | bodies: [names] (combine?: join with the original); plane: XY|XZ|YZ|construction plane name or id|{origin, normal}|{origin, x_dir, y_dir} (origin coordinates may be length expressions; the mirror follows them, or a construction plane)"), CommandSpec::new("solid.hole", "Hole", hole) .at("SOLID", "CREATE") .icon("hole") @@ -1303,7 +1303,7 @@ pub(super) fn check_plane_name(name: &str, cmd: &str) -> Result<()> { /// plane reads it here. pub(super) fn plane_param(s: &Session, v: Option<&Value>, cmd: &str) -> Result { use solidcraft_doc::PlaneRef; - const WANT: &str = "XY, XZ, YZ, a construction plane name or id, or {origin, normal}"; + const WANT: &str = "XY, XZ, YZ, a construction plane name or id, or {origin, normal} (origin coordinates may be length expressions)"; let construction = |r: &str| match s.doc.find_feature(r) { Some(f) if matches!(f.kind, FeatureKind::ConstructionPlane { .. }) => Ok(PlaneRef::Construction { name: f.name.clone() }), Some(f) => Err(bad(cmd, format!("`{}` is not a construction plane (a plane is {WANT})", f.name))), @@ -1332,16 +1332,24 @@ pub(super) fn plane_param(s: &Session, v: Option<&Value>, cmd: &str) -> Result Err(bad(cmd, format!("`plane` must be {WANT}"))), }, Some(o @ Value::Object(_)) => { + // The origin's coordinates are numbers or length expressions; expressions are kept, + // so the plane follows its parameters. let origin = match o.get("origin") { - None => Vec3::ZERO, - Some(x) => vec3(x).ok_or_else(|| bad(cmd, "the plane's `origin` must be a point [x, y, z]"))?, + None => point_expr(Vec3::ZERO), + Some(_) => point_param(s, o, "origin", cmd)?.unwrap_or_else(|| point_expr(Vec3::ZERO)), }; + let at = |e: &String| s.doc.eval(e, Kind::Length).unwrap_or(0.0); + let here = Vec3::new(at(&origin[0]), at(&origin[1]), at(&origin[2])); let pl = match (o.get("x_dir").and_then(vec3), o.get("y_dir").and_then(vec3), o.get("normal").and_then(vec3)) { - (Some(x), Some(y), _) => solidcraft_geom::Plane::new(origin, x, y), - (_, _, Some(n)) => solidcraft_geom::Plane::from_normal(origin, n), + (Some(x), Some(y), _) => solidcraft_geom::Plane::new(here, x, y), + (_, _, Some(n)) => solidcraft_geom::Plane::from_normal(here, n), _ => None, }; - Ok(PlaneRef::Custom { plane: pl.ok_or_else(|| bad(cmd, "plane needs x_dir and y_dir, or normal"))? }) + let plane = pl.ok_or_else(|| bad(cmd, "plane needs x_dir and y_dir, or normal"))?; + if origin.iter().all(|e| solidcraft_doc::expr::is_literal(e)) { + return Ok(PlaneRef::Custom { plane }); + } + Ok(PlaneRef::Placed { origin, x_dir: plane.x, y_dir: plane.y }) } _ => Err(bad(cmd, format!("`plane` must be {WANT}"))), } diff --git a/crates/engine/src/tests/mirror_planes.rs b/crates/engine/src/tests/mirror_planes.rs index af766e59c..03e6dc9c9 100644 --- a/crates/engine/src/tests/mirror_planes.rs +++ b/crates/engine/src/tests/mirror_planes.rs @@ -39,6 +39,41 @@ fn mirror_across_a_construction_plane_follows_it() { } } +/// A plane `{origin, normal}` takes length expressions in its origin, as a primitive's corner +/// does, and the mirror follows them through parameter changes, renames and a save (#1492). +#[test] +fn mirror_plane_origin_follows_its_parameters() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "half", "expression": "50 mm"})); + run(&mut s, "solid.box", json!({"length": 20, "width": 20, "height": 20})); + run(&mut s, "solid.mirror", json!({"features": ["Box1"], "plane": {"origin": ["half", 0, 0], "normal": [1, 0, 0]}, "name": "Twin"})); + let at = |s: &Session| min_x(s, &last_body(s)); + // The box spans x = 0…20; mirrored about x = 50 it spans 80…100. + assert!((at(&s) - 80.0).abs() < 1e-6, "{}", at(&s)); + run(&mut s, "parameters.change", json!({"name": "half", "expression": "30 mm"})); + assert!((at(&s) - 40.0).abs() < 1e-6, "{}", at(&s)); + run(&mut s, "parameters.rename", json!({"name": "half", "new_name": "mid"})); + run(&mut s, "parameters.change", json!({"name": "mid", "expression": "25 mm"})); + assert!((at(&s) - 30.0).abs() < 1e-6, "{}", at(&s)); + // Saved and opened again, the plane still names the parameter. + let mut s2 = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); + assert!(s2.doc.to_json().contains("\"mid\"")); + run(&mut s2, "parameters.change", json!({"name": "mid", "expression": "60 mm"})); + assert!((at(&s2) - 100.0).abs() < 1e-6, "{}", at(&s2)); + // A parameter the plane uses can't be deleted from under it. + assert!(s2.execute("parameters.delete", &json!({"name": "mid"})).is_err()); + // Plain numbers still make a fixed plane. + let r = run(&mut s2, "solid.mirror", json!({"features": ["Box1"], "plane": {"origin": [-10, 0, 0], "normal": [1, 0, 0]}})); + let id = r["feature"].as_u64().unwrap(); + let f = s2.doc.feature(id).unwrap(); + assert!(matches!(f.kind, solidcraft_doc::FeatureKind::Mirror { plane: solidcraft_doc::PlaneRef::Custom { .. }, .. }), "{:?}", f.kind); + assert!((at(&s2) + 40.0).abs() < 1e-6, "{}", at(&s2)); +} + +fn last_body(s: &Session) -> String { + s.model.state().bodies.last().map(|b| b.name.clone()).unwrap() +} + #[test] fn unknown_mirror_planes_are_refused_with_the_choices() { let mut s = Session::default(); diff --git a/skills/solidcraft-modeling/SKILL.md b/skills/solidcraft-modeling/SKILL.md index 6e2ca4cef..be74e91be 100644 --- a/skills/solidcraft-modeling/SKILL.md +++ b/skills/solidcraft-modeling/SKILL.md @@ -36,7 +36,7 @@ Work the part out as numbers first. Then build it in a few large `batch` calls, - expression fields such as `solid.cylinder base:["w/2-6","d/2-6","wall"]` A plain number never follows a parameter. -- **Repeats:** `solid.pattern.rectangular` takes expression spacing; `solid.mirror` takes `XY`/`XZ`/`YZ`, a construction plane or `{origin, normal}`. A mirror or pattern feature cannot be mirrored or patterned again. +- **Repeats:** `solid.pattern.rectangular` takes expression spacing; `solid.mirror` takes `XY`/`XZ`/`YZ`, a construction plane or `{origin, normal}` (origin coordinates may be length expressions such as `["half", 0, 0]`). A mirror or pattern feature cannot be mirrored or patterned again. - **Edge and face picks** snap to the nearest edge or face. There is no distance limit and no error, so compute the exact midpoint from your geometry (the vertical corner edge of a centred box is `[w/2, d/2, h/2]`). - Picks must be plain numbers. - A pick is resolved once and then follows its edge when parameters change. diff --git a/skills/solidcraft-modeling/reference.md b/skills/solidcraft-modeling/reference.md index 4216d56c9..7cab578e0 100644 --- a/skills/solidcraft-modeling/reference.md +++ b/skills/solidcraft-modeling/reference.md @@ -78,7 +78,7 @@ Distances are unsigned. Draw the geometry on the correct side first, and the dim | `solid.hole` | `position:[x,y,z]` on a face + `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}`) | Follows parameters. Mirror and pattern features cannot be mirrored or patterned again. | +| `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. | - **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. From 7ef78f960a33ee160c12912108c904f149e903ca Mon Sep 17 00:00:00 2001 From: Colin Faulkingham Date: Thu, 15 Oct 2026 21:40:09 -0500 Subject: [PATCH 43/92] Fix perpendicular fillets after connected rounds (#1581) Thanks @cfaulkingham. --- ROADMAP.md | 4 +- crates/engine/src/cmd/features.rs | 3 + .../src/cmd/fillet_connected_rounds_tests.rs | 64 +++++++++ crates/kernel/src/blend.rs | 2 +- crates/kernel/src/blend_corner.rs | 136 +++++++++++++++++- crates/kernel/src/delete_face.rs | 40 +++++- 6 files changed, 240 insertions(+), 9 deletions(-) create mode 100644 crates/engine/src/cmd/fillet_connected_rounds_tests.rs diff --git a/ROADMAP.md b/ROADMAP.md index 90a2c2618..824591151 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -307,7 +307,9 @@ annotations and exact projected curves remain deferred. See [view DXF](docs/view is an equivalent circular setback. Curved faces/edges, sloped 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); straight edges (convex or concave) between planar faces with perpendicular + 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); + 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 corners around pocket rims, with unequal wall slopes and extensions confined to the face; diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs index 6adb6aeb1..8c6944c10 100644 --- a/crates/engine/src/cmd/features.rs +++ b/crates/engine/src/cmd/features.rs @@ -1888,3 +1888,6 @@ mod thin_extrude_tests; #[cfg(test)] #[path = "extrude_convention_tests.rs"] mod extrude_convention_tests; +#[cfg(test)] +#[path = "fillet_connected_rounds_tests.rs"] +mod fillet_connected_rounds_tests; diff --git a/crates/engine/src/cmd/fillet_connected_rounds_tests.rs b/crates/engine/src/cmd/fillet_connected_rounds_tests.rs new file mode 100644 index 000000000..5e0602981 --- /dev/null +++ b/crates/engine/src/cmd/fillet_connected_rounds_tests.rs @@ -0,0 +1,64 @@ +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 bottom_rounds() -> Session { + let mut s = Session::default(); + run(&mut s, "parameters.change", json!({"name":"corner_radius", "expression":"2 mm"})); + run(&mut s, "sketch.create", json!({"plane":"XY", "name":"Rectangle"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0":[0,0], "p1":[25,25]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"distance":"10 mm", "body_name":"Block"})); + run(&mut s, "solid.fillet", json!({"edges":[[12.5,0,0],[25,12.5,0],[12.5,25,0],[0,12.5,0]], "radius":"2 mm"})); + s +} + +fn volume(s: &mut Session) -> f64 { + let value = run(s, "inspect.measure", json!({})); + assert_eq!(value["body_count"], 1); + let state = s.model.state(); + let body = &state.body("Block").unwrap().body; + assert!(body.validity().is_empty(), "{:?}", body.validity()); + value["total"]["volume_mm3"].as_f64().unwrap() +} + +#[test] +fn issue1557_fillet_recomputes_and_survives_undo_and_reload() { + for edges in [json!([[25, 0, 6]]), json!([[25, 0, 6], [24.287266336668306, 0.7127336633316916, 0.48266373325510686]])] { + let mut s = bottom_rounds(); + let before = volume(&mut s); + let out = run(&mut s, "solid.fillet", json!({"edges":edges, "radius":"corner_radius"})); + let id = out["feature"].as_u64().unwrap(); + let after = volume(&mut s); + assert!(after < before - 1.0); + assert_eq!(s.doc.features.len(), 4); + run(&mut s, "edit.undo", json!({})); + assert!((volume(&mut s) - before).abs() < 1e-6); + run(&mut s, "edit.redo", json!({})); + assert!((volume(&mut s) - after).abs() < 1e-6); + run(&mut s, "parameters.change", json!({"name":"corner_radius", "expression":"1 mm"})); + let smaller = volume(&mut s); + assert!(smaller > after && smaller < before); + assert!(run(&mut s, "timeline.inspect", json!({"feature":id}))["error"].is_null()); + let bytes = crate::io::write_design_container(&s.doc).unwrap(); + let mut reopened = Session::new(crate::io::read_design(&bytes).unwrap()); + assert!((volume(&mut reopened) - smaller).abs() < 1e-6); + assert_eq!(reopened.doc.features.len(), 4); + } +} + +#[test] +fn issue1557_failed_radius_keeps_the_existing_rounds() { + let mut s = bottom_rounds(); + let before = s.doc.to_json(); + let v = volume(&mut s); + let undo = s.undo.len(); + assert!(s.execute("solid.fillet", &json!({"edges":[[25,0,6]], "radius":"1000 mm"})).is_err()); + assert_eq!(s.doc.to_json(), before); + assert_eq!(s.undo.len(), undo); + assert!((volume(&mut s) - v).abs() < 1e-6); +} diff --git a/crates/kernel/src/blend.rs b/crates/kernel/src/blend.rs index 08c3bd625..324250bab 100644 --- a/crates/kernel/src/blend.rs +++ b/crates/kernel/src/blend.rs @@ -1611,7 +1611,7 @@ fn tangent_faces(solid: &Solid, edge: &mt::Edge) -> bool { /// The chain of edges continuing `edge` smoothly at its ends (its ids): closed, or open where /// the next edge turns sharply. -fn smooth_chain(solid: &Solid, edge: &mt::Edge) -> Option> { +pub(crate) fn smooth_chain(solid: &Solid, edge: &mt::Edge) -> Option> { smooth_chain_within(solid, edge, &|_| true) } diff --git a/crates/kernel/src/blend_corner.rs b/crates/kernel/src/blend_corner.rs index ea3cd7de3..a41528665 100644 --- a/crates/kernel/src/blend_corner.rs +++ b/crates/kernel/src/blend_corner.rs @@ -44,12 +44,13 @@ pub fn fillet_radii(body: &Body, edges: &[(Vec3, f64)]) -> Result { Ok(b) => return Ok(crate::record::after(b, &cur, &counts)), Err(e) => e, }; - let rounds = rounds_at(&cur, &sel); + let rounds = guard("recognise earlier rounds", || rounds_at(&cur, &sel))?; if rounds.is_empty() { return Err(first.unwrap_or(err)); } first.get_or_insert(err); let idx: Vec = rounds.iter().map(|r| r.0).collect(); + sel = guard("map picks across earlier rounds", || surviving_picks(&cur, &sel, &idx))?; cur = crate::record::after(crate::delete_faces(&cur, &idx)?, &cur, &counts); sel.extend(rounds.iter().map(|r| (r.1, r.2))); } @@ -793,9 +794,35 @@ fn crease(a: &Sel, b: &Sel, q: Vec3, end: Vec3, size: f64) -> Result crate::splitface::fit(&pts, size) } -/// Faces at the filleted edges' ends that are rounds of a straight edge between planar faces: +/// Keep selected sharp edges while consuming a selected mitre that is on the same smooth +/// chain as one of them. After removing the rounds, that mitre no longer exists; using its +/// old point would silently choose a different nearby edge, possibly with a different radius. +fn surviving_picks(cur: &Body, sel: &[(Vec3, f64)], removed: &[usize]) -> Result> { + let solid = &*cur.solid; + let edges = Body::unique_edges(solid); + let faces: Vec<_> = solid.face_iter().collect(); + let mut selected = Vec::new(); + for (p, r) in sel { + let (idx, _) = cur.nearest_edge(*p, (cur.size() * 2e-3).max(1e-3))?.ok_or_else(|| unsupported("no edge at a fillet pick"))?; + let e = edges.get(idx).ok_or_else(|| unsupported("no edge at a fillet pick"))?; + let count = removed.iter().filter_map(|i| faces.get(*i)).filter(|f| f.edge_iter().any(|x| x.id() == e.id())).count(); + selected.push((e, *p, *r, count)); + } + for (e, _, r, count) in &selected { + if *count == 0 { + continue; + } + let chain = crate::blend::smooth_chain(solid, e).unwrap_or_default(); + if *count != 2 || !selected.iter().any(|(other, _, rr, n)| *n == 0 && (r - rr).abs() <= r * 1e-9 && chain.contains(&other.id())) { + return Err(unsupported("a selected earlier-round boundary cannot be mapped to a sharp edge")); + } + } + Ok(selected.into_iter().filter(|(_, _, _, n)| *n == 0).map(|(_, p, r, _)| (p, r)).collect()) +} + +/// Connected faces at the filleted edges' ends that are rounds of straight edges between planar faces: /// (face index, a point on the sharp edge it replaced, its radius). -fn rounds_at(cur: &Body, sel: &[(Vec3, f64)]) -> Vec<(usize, Vec3, f64)> { +fn rounds_at(cur: &Body, sel: &[(Vec3, f64)]) -> Result> { let size = cur.size(); let tol = (size * 2e-3).max(1e-3); let solid = &*cur.solid; @@ -810,16 +837,43 @@ fn rounds_at(cur: &Body, sel: &[(Vec3, f64)]) -> Vec<(usize, Vec3, f64)> { } } let faces: Vec<&mt::Face> = solid.face_iter().collect(); - let mut out = Vec::new(); + let mut neighbours: HashMap> = HashMap::new(); for (fi, f) in faces.iter().enumerate() { - if plane_normal(f).is_some() || !f.vertex_iter().any(|v| ends.iter().any(|p| p.dist(vtx(&v)) <= size * 1e-9)) { + for e in f.edge_iter() { + neighbours.entry(e.id()).or_default().push(fi); + } + } + let mut pending: Vec = faces + .iter() + .enumerate() + .filter(|(_, f)| f.vertex_iter().any(|v| ends.iter().any(|p| p.dist(vtx(&v)) <= size * 1e-9))) + .map(|(fi, _)| fi) + .collect(); + let mut visited = HashSet::new(); + let mut out = Vec::new(); + while let Some(fi) = pending.pop() { + if !visited.insert(fi) { + continue; + } + let Some(f) = faces.get(fi) else { continue }; + if plane_normal(f).is_some() { continue; } if let Some((p, r)) = round_of(&faces, f, size) { + if out.len() + sel.len() >= 1000 { + return Err(unsupported("too many connected earlier rounds to rebuild")); + } out.push((fi, p, r)); + // Healing requires planar neighbours. Include the other recognised rounds + // sharing this one's mitres, rather than leaving a curved neighbour across + // the gap. A closed ring must be restored and reblended as a whole (#1557). + for e in f.edge_iter() { + pending.extend(neighbours.get(&e.id()).into_iter().flatten().copied().filter(|i| !visited.contains(i))); + } } } - out + out.sort_by_key(|r| r.0); + Ok(out) } /// A round between two planes: two parallel straight boundary edges on planar faces, the @@ -1274,6 +1328,76 @@ mod tests { assert!((vol(&e) - strips(2.0, 2.0, 0.0)).abs() < 0.05); } + #[test] + fn issue1557_vertical_after_bottom_rounds() { + let b = box_solid(Vec3::ZERO, Vec3::new(25.0, 25.0, 10.0)).unwrap(); + let bottom = [Vec3::new(12.5, 0.0, 0.0), Vec3::new(25.0, 12.5, 0.0), Vec3::new(12.5, 25.0, 0.0), Vec3::new(0.0, 12.5, 0.0)]; + let rounded = fillet(&b, &bottom, 2.0).unwrap(); + let vertical = Vec3::new(25.0, 0.0, 6.0); + let seam = Vec3::new(24.287266336668306, 0.7127336633316916, 0.48266373325510686); + let mut together = bottom.to_vec(); + together.push(vertical); + let reference = fillet(&b, &together, 2.0).unwrap(); + for picks in [vec![vertical], vec![vertical, seam], vec![seam, vertical]] { + let result = fillet(&rounded, &picks, 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(24.9, 0.1, 5.0))); + assert!(result.contains(Vec3::new(24.0, 1.0, 5.0))); + } + } + + #[test] + fn issue1557_connected_rounds_keep_their_radii() { + let b = box_solid(Vec3::ZERO, Vec3::new(25.0, 25.0, 10.0)).unwrap(); + let bottom = [Vec3::new(12.5, 0.0, 0.0), Vec3::new(25.0, 12.5, 0.0), Vec3::new(12.5, 25.0, 0.0), Vec3::new(0.0, 12.5, 0.0)]; + let rounded = fillet(&b, &bottom, 2.0).unwrap(); + let vertical = Vec3::new(25.0, 0.0, 6.0); + let seam = Vec3::new(24.287266336668306, 0.7127336633316916, 0.48266373325510686); + for radius in [0.5, 1.0, 3.0] { + let mut together: Vec<_> = bottom.iter().map(|p| (*p, 2.0)).collect(); + together.push((vertical, radius)); + let reference = fillet_radii(&b, &together).unwrap(); + let result = fillet(&rounded, &[seam, vertical], radius).unwrap(); + assert!(result.validity().is_empty(), "{:?}", result.validity()); + assert!((vol(&result) - vol(&reference)).abs() < 0.05, "radius {radius}"); + // The old bottom radius is still 2, away from the newly rounded corner. + assert!(!result.contains(Vec3::new(12.5, 0.5, 0.5))); + assert!(result.contains(Vec3::new(12.5, 1.0, 1.0))); + } + // A tangent boundary of an earlier round is not a sharp edge, and cannot be + // reinterpreted as the sharp edge exposed when that round is taken off. + assert!(fillet(&rounded, &[Vec3::new(12.5, 0.0, 2.0)], 1.0).is_err()); + // Consuming a mitre must not silently discard its independently requested radius, + // or turn a mitre-only selection into a different sharp edge. + assert!(fillet_radii(&rounded, &[(vertical, 1.0), (seam, 2.0)]).is_err()); + assert!(fillet_radii(&rounded, &[(seam, 2.0)]).is_err()); + } + + #[test] + fn issue1557_all_vertical_corners_match_analytic_volume() { + let origin = Vec3::new(10.0, -5.0, 7.0); + let b = box_solid(origin, origin + Vec3::new(25.0, 25.0, 10.0)).unwrap(); + let bottom = + [Vec3::new(12.5, 0.0, 0.0), Vec3::new(25.0, 12.5, 0.0), Vec3::new(12.5, 25.0, 0.0), Vec3::new(0.0, 12.5, 0.0)].map(|p| p + origin); + let vertical = + [Vec3::new(0.0, 0.0, 6.0), Vec3::new(25.0, 0.0, 6.0), Vec3::new(25.0, 25.0, 6.0), Vec3::new(0.0, 25.0, 6.0)].map(|p| p + origin); + let rounded = fillet(&b, &bottom, 2.0).unwrap(); + let result = fillet(&rounded, &vertical, 2.0).unwrap(); + assert!(result.validity().is_empty(), "{:?}", result.validity()); + assert!(kink(&result) < 0.05); + // Integrate rounded-square horizontal sections. Above z=r the area is + // L²-(4-π)r²; below, a square of side L-2r plus a disk offset of radius + // sqrt(r²-(z-r)²). This includes the four spherical bottom corners. + let (l, h, r) = (25.0, 10.0, 2.0); + let pi = std::f64::consts::PI; + let a = l - 2.0 * r; + let expected = (h - r) * (l * l - (4.0 - pi) * r * r) + a * a * r + pi * a * r * r + 2.0 * pi * r * r * r / 3.0; + assert!((vol(&result) - expected).abs() < 0.1, "{} vs {expected}", vol(&result)); + } + #[test] fn three_rounds_at_a_corner() { let (bx, a, b, c) = setup(); diff --git a/crates/kernel/src/delete_face.rs b/crates/kernel/src/delete_face.rs index 3da5f1131..3817463df 100644 --- a/crates/kernel/src/delete_face.rs +++ b/crates/kernel/src/delete_face.rs @@ -3,7 +3,8 @@ //! //! The body is rebuilt from its own topology. Faces away from the gap are kept as they are. //! Each neighbouring face (planar) keeps its edges that don't touch the gap; a loop that ran -//! entirely along deleted faces (a hole's rim, a boss's footprint) is dropped; a corner on the +//! entirely along deleted faces is dropped for a hole's rim or a boss's footprint, or restored +//! at the moved corners for a face enclosed by rounds. A corner on the //! gap moves to where its planes meet the neighbours across the gap (a fillet's tangent points //! go to the sharp corner), and the stretch of loop that bordered deleted faces closes with a //! straight edge between the moved corners. Anything else (curved neighbours, a gap the @@ -216,6 +217,28 @@ pub fn delete_faces(body: &Body, faces: &[usize]) -> Result { for w in f.boundaries() { let edges: Vec = w.edge_iter().cloned().collect(); if edges.iter().all(gap) { + // A hole or boss footprint disappears when its walls are removed. A + // face surrounded by rounds does not: its whole boundary moves back to + // the intersections of the remaining planes (#1557). Keep that loop, + // sharing its restored edges with the adjacent rebuilt faces. + let moving = edges.iter().any(|e| moved.contains_key(&e.front().id()) || moved.contains_key(&e.back().id())); + if moving { + if !edges.iter().all(|e| moved.contains_key(&e.front().id()) && moved.contains_key(&e.back().id())) { + return Err(fail(format!("face {fi} has a closed gap boundary that cannot be restored completely"))); + } + let mut boundary = Vec::new(); + for e in &edges { + let (a, b) = (pos(e.front()), pos(e.back())); + if a.dist(b) > q * 10.0 { + let restored = line(a, b, &mut verts); + rec.piece(&restored, e); + boundary.push(restored); + } + } + if !boundary.is_empty() { + wires.push(boundary.into()); + } + } continue; } // Start after a gap stretch so stretches don't wrap around. @@ -321,6 +344,21 @@ mod tests { .collect() } + #[test] + fn issue1557_delete_closed_fillet_ring_keeps_the_floor() { + let b = box_solid(Vec3::ZERO, Vec3::new(25.0, 25.0, 10.0)).unwrap(); + let picks = [Vec3::new(12.5, 0.0, 0.0), Vec3::new(25.0, 12.5, 0.0), Vec3::new(12.5, 25.0, 0.0), Vec3::new(0.0, 12.5, 0.0)]; + let rounded = fillet(&b, &picks, 2.0).unwrap(); + let rounds: Vec = + rounded.solid.face_iter().enumerate().filter(|(_, f)| crate::blend::plane_normal(f).is_none()).map(|(i, _)| i).collect(); + assert_eq!(rounds.len(), 4); + let restored = delete_faces(&rounded, &rounds).unwrap(); + assert_eq!(restored.face_count(), 6); + assert_eq!(restored.unmeshed_faces(), 0); + assert!((volume(&restored) - 6250.0).abs() < 1e-6); + assert!(restored.contains(Vec3::new(0.1, 0.1, 0.1))); + } + #[test] fn delete_fillet_chamfer_hole_and_boss_faces() { let sharp = 24000.0; From 904bf19e8336f494718969f313b17ab18f1ac813 Mon Sep 17 00:00:00 2001 From: Colin Faulkingham Date: Thu, 15 Oct 2026 21:44:13 -0500 Subject: [PATCH 44/92] Fix agent runtime lookup when launched from the desktop (#1551) Thanks @cfaulkingham. --- crates/ui-egui/src/agent_chat/discover.rs | 67 ++++++++++++++++++++++- crates/ui-egui/src/agent_chat/process.rs | 17 +----- docs/agent-chat.md | 3 + 3 files changed, 69 insertions(+), 18 deletions(-) diff --git a/crates/ui-egui/src/agent_chat/discover.rs b/crates/ui-egui/src/agent_chat/discover.rs index 1bf100fc1..3b028ca24 100644 --- a/crates/ui-egui/src/agent_chat/discover.rs +++ b/crates/ui-egui/src/agent_chat/discover.rs @@ -218,8 +218,13 @@ pub fn runnable_sibling(program: &Path) -> Option { names_for(name, true).into_iter().map(|n| dir.join(n)).find(|p| p.is_file()) } -/// `program --version`'s first line, or `None` after `limit` (the probe is then stopped). -fn version(program: &Path, limit: Duration) -> Option { +/// Start probes and sessions with the same PATH used for discovery. Desktop launchers often +/// omit Node's install folder even when we found an adapter with a `#!/usr/bin/env node` shebang. +/// Only the child's environment changes; inherited absolute PATH entries keep precedence. +pub(super) fn command_for(program: &Path) -> Command { + // Older saved Windows commands may name npm's bare Unix script rather than its .cmd shim. + let shim = if cfg!(windows) { runnable_sibling(program) } else { None }; + let program = shim.as_deref().unwrap_or(program); let mut cmd = if cfg!(windows) && program.extension().is_some_and(|e| e.eq_ignore_ascii_case("cmd") || e.eq_ignore_ascii_case("bat")) { let mut c = Command::new("cmd"); c.arg("/C").arg(program); @@ -227,6 +232,15 @@ fn version(program: &Path, limit: Duration) -> Option { } else { Command::new(program) }; + if let Ok(path) = std::env::join_paths(search_dirs()) { + cmd.env("PATH", path); + } + cmd +} + +/// `program --version`'s first line, or `None` after `limit` (the probe is then stopped). +fn version(program: &Path, limit: Duration) -> Option { + let mut cmd = command_for(program); #[cfg(windows)] { use std::os::windows::process::CommandExt; @@ -376,4 +390,53 @@ mod tests { } assert_eq!(KNOWN.first().map(|k| k.id), Some("claude"), "the Claude Code adapter is the default"); } + + /// Finder's PATH lacks user-installed runtimes. Discovery, the version probe and a live + /// agent must all work with an env shebang whose interpreter is in ~/.local/bin. + #[test] + #[cfg(unix)] + fn desktop_path_can_start_an_agent_and_its_runtime() { + use super::super::process::{AgentProcess, FromAgent}; + use std::os::unix::fs::PermissionsExt; + + const CHILD: &str = "SOLIDCRAFT_AGENT_PATH_TEST"; + if let Some(root) = std::env::var_os(CHILD) { + let root = PathBuf::from(root); + let agent = find_in("solidcraft-test-agent", &search_dirs()).unwrap(); + assert_eq!(version(&agent, Duration::from_secs(3)).as_deref(), Some("1.2.3")); + let mut p = AgentProcess::spawn(&[agent.to_string_lossy().into_owned()], &root, &[], || {}).unwrap(); + let message = serde_json::json!({"id": 1, "method": "initialize"}); + p.send(&message); + let reply = p.from_agent.recv_timeout(Duration::from_secs(5)).unwrap(); + p.shutdown(true); + match reply { + FromAgent::Line(line) => assert_eq!(serde_json::from_str::(&line).unwrap(), message), + FromAgent::Exited(tail) => panic!("the agent could not start its runtime: {tail:?}"), + } + return; + } + + let root = std::env::temp_dir().join(format!("sc-agent-desktop-path-{}", std::process::id())); + let bin = root.join(".local/bin"); + std::fs::create_dir_all(&bin).unwrap(); + for (name, script) in [ + ("solidcraft-test-agent", "#!/usr/bin/env solidcraft-test-runtime\n"), + ("solidcraft-test-runtime", "#!/bin/sh\nif [ \"$2\" = \"--version\" ]; then printf 'test-agent 1.2.3\\n'; else cat; fi\n"), + ] { + let path = bin.join(name); + std::fs::write(&path, script).unwrap(); + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + // Change only a child process's environment: no global mutation or unsafe set_var. + let output = Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "agent_chat::discover::tests::desktop_path_can_start_an_agent_and_its_runtime", "--nocapture"]) + .env(CHILD, &root) + .env("HOME", &root) + .env("PATH", "/usr/bin:/bin") + .env_remove("NPM_CONFIG_PREFIX") + .output() + .unwrap(); + let _ = std::fs::remove_dir_all(root); + assert!(output.status.success(), "{}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); + } } diff --git a/crates/ui-egui/src/agent_chat/process.rs b/crates/ui-egui/src/agent_chat/process.rs index e7049972d..fb0e75432 100644 --- a/crates/ui-egui/src/agent_chat/process.rs +++ b/crates/ui-egui/src/agent_chat/process.rs @@ -51,21 +51,6 @@ impl ProcessHandle { } } -/// On Windows, npm installs `.cmd` shims, which only `cmd.exe` runs. A command saved as the bare -/// npm path (a shell script there) runs the shim beside it. -fn command_for(program: &str) -> Command { - let shim = if cfg!(windows) { super::discover::runnable_sibling(std::path::Path::new(program)) } else { None }; - let program = shim.as_deref().and_then(|p| p.to_str()).unwrap_or(program); - let lower = program.to_ascii_lowercase(); - if cfg!(windows) && (lower.ends_with(".cmd") || lower.ends_with(".bat")) { - let mut c = Command::new("cmd"); - c.arg("/C").arg(program); - c - } else { - Command::new(program) - } -} - /// Start the agent in a process group of its own (Unix) or without a console window (Windows). fn detach_group(cmd: &mut Command) { #[cfg(unix)] @@ -161,7 +146,7 @@ impl AgentProcess { wake: impl Fn() + Send + Sync + 'static, ) -> Result { let Some((program, args)) = argv.split_first() else { return Err("no agent command".into()) }; - let mut cmd = command_for(program); + let mut cmd = super::discover::command_for(std::path::Path::new(program)); cmd.args(args).current_dir(cwd).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()); for v in env_remove { cmd.env_remove(v); diff --git a/docs/agent-chat.md b/docs/agent-chat.md index f3981244d..005ff723a 100644 --- a/docs/agent-chat.md +++ b/docs/agent-chat.md @@ -55,6 +55,9 @@ SolidCraft looks for agents that speak the [Agent Client Protocol](https://agent on your `PATH` and in the usual install folders a desktop app's `PATH` often misses (npm's global folder, nvm, Volta, bun, `~/.local/bin`, `~/.grok/bin`, Homebrew, `%APPDATA%\npm`). For each one it shows its **version** (from `--version`, given three seconds) and whether it looks **signed in**. +Version checks and agent sessions also use those folders on their `PATH`, so adapters can find +runtimes such as Node when SolidCraft is opened from Finder or the Dock. Existing absolute +`PATH` entries keep their order; no shell startup files are run. SolidCraft only checks whether the agent's own login file (`~/.claude/.credentials.json`, `~/.codex/auth.json`, `~/.gemini/oauth_creds.json`, …) or one of its key variables exists. It never reads the file and never starts the agent to find out. On macOS Claude Code keeps its login in From e21c5f06ac87da091e8bd9fe3b8dee301dbb0c44 Mon Sep 17 00:00:00 2001 From: sthifen Date: Thu, 15 Oct 2026 20:50:41 -0600 Subject: [PATCH 45/92] =?UTF-8?q?Viewport=20frame-rate=20readout=20(Prefer?= =?UTF-8?q?ences=20=E2=96=B8=20Graphics)=20(#1580)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Thanks @sthifen. --- assets/locales/de.json | 2 + assets/locales/en.json | 2 + assets/locales/fr.json | 2 + assets/locales/ja.json | 2 + assets/locales/ko.json | 2 + assets/locales/zh.json | 2 + crates/ui-egui/src/frame_rate.rs | 96 ++++++++++++++++++++++++++++++++ crates/ui-egui/src/lib.rs | 4 ++ crates/ui-egui/src/prefs.rs | 11 ++++ crates/ui-egui/src/viewport.rs | 1 + docs/control-protocol.md | 2 +- 11 files changed, 125 insertions(+), 1 deletion(-) create mode 100644 crates/ui-egui/src/frame_rate.rs diff --git a/assets/locales/de.json b/assets/locales/de.json index e55fd08f7..5ee1040f6 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -502,6 +502,7 @@ "sample.vents.about": "Langlöcher in einem Rechteckmuster: Zeilen, Spalten und Abstand sind Parameter", "sample.vents.name": "Lüftungsplatte", "settings.display_quality_note": "Feinere Stufen zeigen gekrümmte Flächen und Kanten glatter und brauchen länger zum Vernetzen. Nur die Ansicht ändert sich, nie das Design oder Exporte.", + "settings.frame_rate_note": "Zeigt die Bilder pro Sekunde unten rechts in der Ansicht. Solange sie an ist, wird die Ansicht fortlaufend neu gezeichnet.", "settings.measure_axis_distances": "X/Y/Z-Maße anzeigen", "settings.measure_axis_distances_help": "Bei geöffneter Messung die Abstände entlang der Weltachsen zusätzlich zum Gesamtabstand anzeigen.", "settings.msaa_applies_on_restart": "Die Kantenglättung wird beim nächsten Start von SolidCraft übernommen", @@ -826,6 +827,7 @@ "ui.flat": "Flach", "ui.flip": "Umkehren", "ui.format": "Format", + "ui.frame_rate": "Bildrate", "ui.front": "Vorne", "ui.fully_constrained": "Vollständig bestimmt", "ui.general": "Allgemein", diff --git a/assets/locales/en.json b/assets/locales/en.json index 2230785bf..768d01a10 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -718,6 +718,7 @@ "sample.vents.about": "Slots in a rectangular pattern: rows, columns and pitch are parameters", "sample.vents.name": "Vent Plate", "settings.display_quality_note": "Finer levels draw curved faces and edges smoother and take longer to mesh. Only the viewport changes, never the design or exports.", + "settings.frame_rate_note": "Shows frames per second in the view's bottom-right corner. While it is on, the view redraws continuously.", "settings.measure_axis_distances": "Show X/Y/Z distances", "settings.measure_axis_distances_help": "Show world-axis component dimensions alongside the total distance while Measure is open.", "settings.msaa_applies_on_restart": "Anti-aliasing applies the next time SolidCraft starts", @@ -1052,6 +1053,7 @@ "ui.flat": "Flat", "ui.flip": "Flip", "ui.format": "Format", + "ui.frame_rate": "Frame rate", "ui.front": "Front", "ui.fully_constrained": "Fully constrained", "ui.general": "General", diff --git a/assets/locales/fr.json b/assets/locales/fr.json index 88763bf38..f48841047 100644 --- a/assets/locales/fr.json +++ b/assets/locales/fr.json @@ -698,6 +698,7 @@ "sample.vents.about": "Rainures en réseau rectangulaire : lignes, colonnes et pas sont des paramètres", "sample.vents.name": "Plaque d'aération", "settings.display_quality_note": "Les niveaux plus fins affichent plus lisses les faces et arêtes courbes, mais leur maillage prend plus de temps. Seule la vue change, jamais la conception ni les exports.", + "settings.frame_rate_note": "Affiche les images par seconde dans le coin inférieur droit de la vue. Tant qu'elle est activée, la vue est redessinée en continu.", "settings.measure_axis_distances": "Afficher les cotes X/Y/Z", "settings.measure_axis_distances_help": "Afficher les cotes suivant les axes du repère global en plus de la distance totale pendant la mesure.", "settings.msaa_applies_on_restart": "L'anticrénelage s'appliquera au prochain démarrage de SolidCraft", @@ -892,6 +893,7 @@ "ui.flat": "Plat", "ui.flip": "Inverser", "ui.format": "Format", + "ui.frame_rate": "Fréquence d'images", "ui.front": "Avant", "ui.fully_constrained": "Entièrement contrainte", "ui.general": "Général", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 8f51b893c..8afc38321 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -718,6 +718,7 @@ "sample.vents.about": "矩形パターンに並んだスロット: 行数、列数、ピッチはパラメータ", "sample.vents.name": "通気プレート", "settings.display_quality_note": "細かいほど曲面とエッジが滑らかに表示されますが、メッシュの生成に時間がかかります。変わるのはビューポートだけで、設計やエクスポートは変わりません。", + "settings.frame_rate_note": "ビューの右下に 1 秒あたりのフレーム数を表示します。オンの間、ビューは常に再描画されます。", "settings.measure_axis_distances": "計測のX・Y・Z距離を表示", "settings.measure_axis_distances_help": "計測ダイアログを開いている間、2点間距離に加えてワールドX・Y・Z軸方向の寸法線と距離を表示します。", "settings.msaa_applies_on_restart": "アンチエイリアスは次回 SolidCraft を起動したときに適用されます", @@ -1052,6 +1053,7 @@ "ui.flat": "展開", "ui.flip": "反転", "ui.format": "形式", + "ui.frame_rate": "フレームレート", "ui.front": "正面", "ui.fully_constrained": "完全拘束", "ui.general": "一般", diff --git a/assets/locales/ko.json b/assets/locales/ko.json index c532303d1..dc99a66ae 100644 --- a/assets/locales/ko.json +++ b/assets/locales/ko.json @@ -502,6 +502,7 @@ "sample.vents.about": "직사각형 패턴의 슬롯: 행, 열, 피치가 매개변수", "sample.vents.name": "통풍 플레이트", "settings.display_quality_note": "세밀할수록 곡면과 모서리가 더 매끄럽게 표시되지만 메시 생성 시간이 늘어납니다. 뷰포트만 바뀌며 설계나 내보내기는 바뀌지 않습니다.", + "settings.frame_rate_note": "뷰의 오른쪽 아래에 초당 프레임 수를 표시합니다. 켜져 있는 동안 뷰를 계속 다시 그립니다.", "settings.measure_axis_distances": "X/Y/Z 거리 표시", "settings.measure_axis_distances_help": "측정 대화상자가 열려 있는 동안 전체 거리와 함께 월드 축 방향 치수와 거리를 표시합니다.", "settings.msaa_applies_on_restart": "안티앨리어싱은 다음에 SolidCraft를 시작할 때 적용됩니다", @@ -826,6 +827,7 @@ "ui.flat": "플랫", "ui.flip": "뒤집기", "ui.format": "형식", + "ui.frame_rate": "프레임 속도", "ui.front": "정면", "ui.fully_constrained": "완전 구속", "ui.general": "일반", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index 7b7565333..e32c8632d 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -718,6 +718,7 @@ "sample.vents.about": "按矩形阵列排列的槽:行数、列数和间距均为参数", "sample.vents.name": "通风板", "settings.display_quality_note": "级别越精细,曲面和边显示越平滑,但网格生成耗时更长。只影响视口,不影响设计或导出。", + "settings.frame_rate_note": "在视图右下角显示每秒帧数。开启时视图会持续重绘。", "settings.measure_axis_distances": "显示 X/Y/Z 距离", "settings.measure_axis_distances_help": "测量对话框打开时,在总距离之外显示沿世界坐标轴方向的尺寸线和距离。", "settings.msaa_applies_on_restart": "抗锯齿将在下次启动 SolidCraft 时生效", @@ -1052,6 +1053,7 @@ "ui.flat": "平面", "ui.flip": "翻转", "ui.format": "格式", + "ui.frame_rate": "帧率", "ui.front": "前视", "ui.fully_constrained": "完全约束", "ui.general": "常规", diff --git a/crates/ui-egui/src/frame_rate.rs b/crates/ui-egui/src/frame_rate.rs new file mode 100644 index 000000000..523cdc08f --- /dev/null +++ b/crates/ui-egui/src/frame_rate.rs @@ -0,0 +1,96 @@ +//! The viewport's frame-rate readout (Preferences ▸ Graphics ▸ "Frame rate"). + +use egui::{FontId, Rect, Stroke, pos2, vec2}; + +use crate::SolveApp; +use crate::theme::Tokens; + +/// Weight of the newest frame in the running mean (roughly the last 20 frames count). +const NEWEST: f64 = 0.05; + +/// Frames per second, averaged over recent frames. +#[derive(Clone, Copy, Debug, Default)] +pub struct FrameRate { + mean_dt: f64, +} + +impl FrameRate { + /// Takes the time since the previous frame, in seconds. A gap over a second (the app idle + /// before the readout was turned on, a window being moved) is not a frame of a running view + /// and is left out, as is anything that isn't a positive finite time. + pub fn record(&mut self, dt: f64) { + if !dt.is_finite() || dt <= 0.0 || dt > 1.0 { + return; + } + self.mean_dt = if self.mean_dt > 0.0 { self.mean_dt + NEWEST * (dt - self.mean_dt) } else { dt }; + } + + /// The averaged rate; `None` before the first frame was recorded. + pub fn fps(&self) -> Option { + (self.mean_dt > 0.0).then(|| 1.0 / self.mean_dt) + } + + /// The readout's text: rate and the matching time per frame. + pub fn label(&self) -> Option { + self.fps().map(|fps| format!("{fps:.0} FPS · {:.1} ms", 1000.0 * self.mean_dt)) + } +} + +/// Records this frame and paints the readout in the view's bottom-right corner. While it is on +/// the view redraws every frame, so the rate is what the view can draw rather than how often +/// something happened to change. +pub(crate) fn paint(app: &mut SolveApp, ctx: &egui::Context, painter: &egui::Painter, rect: Rect) { + if !app.preferences.show_frame_rate { + app.frame_rate = FrameRate::default(); + return; + } + app.frame_rate.record(f64::from(ctx.input(|i| i.unstable_dt))); + ctx.request_repaint(); + let Some(text) = app.frame_rate.label() else { return }; + let t = Tokens::get(); + let font = FontId::monospace(12.0); + let galley = painter.layout_no_wrap(text, font, t.text); + let size = galley.size() + vec2(16.0, 8.0); + let r = Rect::from_min_size(pos2(rect.right() - 12.0 - size.x, rect.bottom() - 12.0 - size.y), size); + painter.rect(r, 4.0, t.overlay, Stroke::new(1.0, t.border), egui::StrokeKind::Inside); + crate::scenario::publish_handle("viewport:frame_rate", r.center()); + painter.galley(r.center() - galley.size() / 2.0, galley, t.text); +} + +#[cfg(test)] +mod tests { + use super::FrameRate; + + #[test] + fn steady_frames_read_their_rate() { + let mut f = FrameRate::default(); + assert_eq!(f.fps(), None); + for _ in 0..200 { + f.record(1.0 / 60.0); + } + assert!((f.fps().unwrap_or(0.0) - 60.0).abs() < 1e-6); + assert_eq!(f.label().as_deref(), Some("60 FPS · 16.7 ms")); + } + + #[test] + fn pauses_and_hostile_times_are_left_out() { + let mut f = FrameRate::default(); + for dt in [0.0, -1.0, f64::NAN, f64::INFINITY, 5.0] { + f.record(dt); + } + assert_eq!(f.fps(), None); + f.record(0.01); + f.record(3.0); + assert!((f.fps().unwrap_or(0.0) - 100.0).abs() < 1e-6); + } + + #[test] + fn the_mean_follows_a_slower_view() { + let mut f = FrameRate::default(); + f.record(1.0 / 120.0); + for _ in 0..300 { + f.record(1.0 / 30.0); + } + assert!((f.fps().unwrap_or(0.0) - 30.0).abs() < 0.1); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index e90c6e18c..a740dd3b9 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -44,6 +44,7 @@ pub mod drag_snap; pub mod edit_clipboard; pub mod fonts; pub mod frame; +pub mod frame_rate; pub mod gizmo; pub mod gpu; pub mod help; @@ -353,6 +354,8 @@ pub struct SolveApp { /// [`SolveApp::set_wgpu`]. pub cpu_meshing: bool, pub frame_ms: f64, + /// The viewport's frame-rate readout ([`frame_rate`]). + pub frame_rate: frame_rate::FrameRate, pub synthetic: Vec, /// The modifiers of the synthetic press in progress (a Ctrl-drag keeps Ctrl while it moves). pub synthetic_mods: egui::Modifiers, @@ -446,6 +449,7 @@ impl SolveApp { integrated_titlebar: false, cpu_meshing: false, frame_ms: 0.0, + frame_rate: frame_rate::FrameRate::default(), synthetic: Vec::new(), synthetic_mods: egui::Modifiers::default(), control_rx: None, diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index a7c28b5f0..9ed418365 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -283,6 +283,8 @@ pub struct Prefs { pub supersampling: f32, /// Supersample only while the view holds still (full speed while orbiting). pub supersampling_adaptive: bool, + /// Show the frame rate in the view's corner (the view then redraws every frame). + pub show_frame_rate: bool, /// Show world X/Y/Z component dimensions beside the total distance in Measure. pub measure_axis_distances: bool, /// Decimals shown for lengths and angles. @@ -400,6 +402,7 @@ impl Default for Prefs { display_quality: "normal".into(), supersampling: 1.0, supersampling_adaptive: true, + show_frame_rate: false, measure_axis_distances: true, length_decimals: 2, angle_decimals: 1, @@ -624,6 +627,7 @@ fn defaults(app: &mut SolveApp, page: usize) { p.display_quality = d.display_quality; p.supersampling = d.supersampling; p.supersampling_adaptive = d.supersampling_adaptive; + p.show_frame_rate = d.show_frame_rate; p.measure_axis_distances = d.measure_axis_distances; p.color_vision = d.color_vision; app.ui.visual_style = 0; @@ -1310,6 +1314,13 @@ fn page(app: &mut SolveApp, ui: &mut egui::Ui, t: &Tokens) { 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(); + ui.label(app.tr("ui.frame_rate")); + ui.checkbox(&mut app.preferences.show_frame_rate, ""); + ui.end_row(); + note(ui, app.tr("settings.frame_rate_note")); } 5 => { ui.label(crate::i18n::tr_label("Project face edges into new sketches")); diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 72928841d..f43441544 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -2237,6 +2237,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { painter.add(egui_wgpu::Callback::new_paint_callback(rect, cb)); } analysis_legend(app, &painter, rect); + crate::frame_rate::paint(app, ui.ctx(), &painter, rect); // ---- interaction ---- let add = mods.shift || mods.command || mods.ctrl; diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 3de543ff8..2857b9ac1 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -143,7 +143,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`, `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`, `length_decimals`, `angle_decimals`, `theme` (`dark`, `light`, `system`), `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 | 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`, `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`), `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 | 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 | From bd17eeef0c248a30d3ac4f81014b5b5e21973513 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Thu, 15 Oct 2026 22:54:06 -0400 Subject: [PATCH 46/92] Claim bot: /claim and /unclaim on issues (#1584) Comment /claim on an issue to be assigned and get the in progress label; /unclaim releases it. A daily sweep frees claims with no PR after 72 h or with a PR idle for 14 days. --- .github/workflows/ci.yml | 2 + .github/workflows/claim.yml | 44 ++++++ CONTRIBUTING.md | 6 + scripts/claim/claim.js | 294 ++++++++++++++++++++++++++++++++++++ scripts/claim/claim.test.js | 230 ++++++++++++++++++++++++++++ 5 files changed, 576 insertions(+) create mode 100644 .github/workflows/claim.yml create mode 100644 scripts/claim/claim.js create mode 100644 scripts/claim/claim.test.js diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6046eed95..06a6aa063 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -125,6 +125,8 @@ jobs: run: cargo xtask web-offline-test - name: Affected-package selection self-test run: python3 -I scripts/ci/test_affected.py + - name: Claim bot tests + run: node --test scripts/claim/*.test.js clippy: name: Native Linux Clippy diff --git a/.github/workflows/claim.yml b/.github/workflows/claim.yml new file mode 100644 index 000000000..637253e9d --- /dev/null +++ b/.github/workflows/claim.yml @@ -0,0 +1,44 @@ +# `/claim` and `/unclaim` on issues (CONTRIBUTING.md, "Sending a change"), and a daily sweep that +# frees claims nobody is working on. The logic is in scripts/claim/claim.js (tested in ci.yml). +name: Claim + +on: + issue_comment: + types: [created] + schedule: + - cron: '17 5 * * *' + workflow_dispatch: + +permissions: + contents: read # to check out scripts/claim + issues: write + pull-requests: read + +# One run at a time per issue, so two simultaneous /claim comments can't both win. +concurrency: + group: claim-${{ github.event.issue.number || 'sweep' }} + cancel-in-progress: false + +jobs: + claim: + name: Claim bot + runs-on: ubuntu-24.04 + timeout-minutes: 10 + if: >- + github.event_name != 'issue_comment' || + (!github.event.issue.pull_request && github.event.comment.user.type != 'Bot' && + (startsWith(github.event.comment.body, '/claim') || startsWith(github.event.comment.body, '/unclaim'))) + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + sparse-checkout: scripts/claim + - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + script: | + const claim = require('./scripts/claim/claim.js'); + if (context.eventName === 'issue_comment') { + await claim.handleComment({ github, context }); + } else { + const released = await claim.sweep({ github, context }); + core.info(`Released: ${released.join(', ') || 'none'}`); + } diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ee6bf7496..edc890bee 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -262,6 +262,12 @@ and a fresh CI run: 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). +Comment `/claim` on an issue to take it: you are assigned, it gets the `in progress` label, and +the bot replies with the deadline. Open a draft PR referencing the issue within 72 hours, or the +claim lapses and the issue is freed again; a claim with a PR is freed after 14 days without +pushes. `/unclaim` releases it early (only you or a maintainer can). Issues a maintainer has +taken are never freed automatically. + Help reviewers see what the words mean. For observable CAD, UI or model behavior, please include actual descriptive screenshots or a short recording in the issue or PR. This evidence is required for changes or bugs that can be demonstrated in the app, including kernel, diff --git a/scripts/claim/claim.js b/scripts/claim/claim.js new file mode 100644 index 000000000..f3cf632ad --- /dev/null +++ b/scripts/claim/claim.js @@ -0,0 +1,294 @@ +// The /claim bot's logic, used by .github/workflows/claim.yml through actions/github-script. +// Everything takes the github-script `github` client and `context`, so the tests can pass fakes. +'use strict'; + +const LABEL = 'in progress'; +const LABEL_COLOR = 'fbca04'; +const LABEL_DESCRIPTION = 'Someone is working on this'; +const CLAIM_HOURS = 72; +const PR_IDLE_DAYS = 14; +const HOUR = 3600 * 1000; + +function parseCommand(body) { + const text = String(body || '').trimStart(); + if (/^\/claim(\s|$)/.test(text)) return 'claim'; + if (/^\/unclaim(\s|$)/.test(text)) return 'unclaim'; + return null; +} + +function fmt(date) { + return new Date(date).toISOString().slice(0, 16).replace('T', ' ') + ' UTC'; +} + +function repoArgs(context) { + return { owner: context.repo.owner, repo: context.repo.repo }; +} + +async function isMaintainer(github, context, login, cache) { + if (login === context.repo.owner) return true; + if (cache && cache.has(login)) return cache.get(login); + let result = false; + try { + const { data } = await github.rest.repos.getCollaboratorPermissionLevel({ + ...repoArgs(context), + username: login, + }); + result = + ['admin', 'write', 'maintain'].includes(data.permission) || + ['admin', 'maintain', 'write'].includes(data.role_name); + } catch (e) { + result = false; + } + if (cache) cache.set(login, result); + return result; +} + +async function ensureLabel(github, context) { + try { + await github.rest.issues.getLabel({ ...repoArgs(context), name: LABEL }); + } catch (e) { + if (e.status !== 404) throw e; + try { + await github.rest.issues.createLabel({ + ...repoArgs(context), + name: LABEL, + color: LABEL_COLOR, + description: LABEL_DESCRIPTION, + }); + } catch (e2) { + if (e2.status !== 422) throw e2; // created meanwhile + } + } +} + +// When the label was last added, from the timeline; the issue's update time if it can't be found. +async function labeledAt(github, context, issue, timeline) { + const events = timeline || (await getTimeline(github, context, issue.number)); + let at = null; + for (const ev of events) { + if (ev.event === 'labeled' && ev.label && ev.label.name === LABEL) at = ev.created_at; + } + return new Date(at || issue.updated_at).getTime(); +} + +function getTimeline(github, context, number) { + return github.paginate(github.rest.issues.listEventsForTimeline, { + ...repoArgs(context), + issue_number: number, + per_page: 100, + }); +} + +// Open pull requests that mention the issue, from the timeline's cross-references. +function linkedPulls(timeline) { + const seen = new Map(); + for (const ev of timeline) { + const src = ev.event === 'cross-referenced' && ev.source && ev.source.issue; + if (src && src.pull_request && src.state === 'open') seen.set(src.number, src); + } + return [...seen.values()]; +} + +async function lastPush(github, context, pr) { + const { data } = await github.rest.pulls.get({ ...repoArgs(context), pull_number: pr.number }); + const { data: commit } = await github.rest.repos.getCommit({ + ...repoArgs(context), + ref: data.head.sha, + }); + return new Date(commit.commit.committer.date).getTime(); +} + +// Where a claimed issue stands: when it lapses, and whether it is free to release now. +async function claimStatus(github, context, issue, now) { + const timeline = await getTimeline(github, context, issue.number); + const since = await labeledAt(github, context, issue, timeline); + const pulls = linkedPulls(timeline); + if (pulls.length === 0) { + const expires = since + CLAIM_HOURS * HOUR; + return { pulls, since, expires, release: now >= expires, reason: 'no PR' }; + } + let newest = 0; + for (const pr of pulls) newest = Math.max(newest, await lastPush(github, context, pr)); + const expires = newest + PR_IDLE_DAYS * 24 * HOUR; + return { pulls, since, expires, release: now >= expires, reason: 'idle PR' }; +} + +async function react(github, context, content) { + await github.rest.reactions.createForIssueComment({ + ...repoArgs(context), + comment_id: context.payload.comment.id, + content, + }); +} + +async function reply(github, context, body) { + await github.rest.issues.createComment({ + ...repoArgs(context), + issue_number: context.payload.issue.number, + body, + }); +} + +function hasLabel(issue) { + return (issue.labels || []).some((l) => (typeof l === 'string' ? l : l.name) === LABEL); +} + +async function release(github, context, issue, assignees) { + if (assignees.length) { + await github.rest.issues.removeAssignees({ + ...repoArgs(context), + issue_number: issue.number, + assignees, + }); + } + try { + await github.rest.issues.removeLabel({ + ...repoArgs(context), + issue_number: issue.number, + name: LABEL, + }); + } catch (e) { + if (e.status !== 404) throw e; + } +} + +async function claim(github, context, now) { + const issue = context.payload.issue; + const user = context.payload.comment.user.login; + const n = issue.number; + const cache = new Map(); + const assignees = (issue.assignees || []).map((a) => a.login); + + if (assignees.includes(user)) { + await react(github, context, '+1'); // already theirs + return; + } + + // Someone else is assigned: theirs unless the claim has lapsed (never for a maintainer). + let held = assignees.length > 0 || hasLabel(issue); + let status = null; + if (held) { + let maintained = false; + for (const a of assignees) maintained = maintained || (await isMaintainer(github, context, a, cache)); + if (!maintained) { + status = await claimStatus(github, context, issue, now); + if (status.release) held = false; + } + if (held) { + await react(github, context, 'eyes'); + const who = assignees.length ? assignees.map((a) => '@' + a).join(', ') + ' has' : 'Someone has'; + const when = maintained || !status ? '' : ` The claim lapses on ${fmt(status.expires)} unless there's progress.`; + await reply(github, context, `${who} claimed this already.${when}`); + return; + } + } else { + // Not claimed, but a draft PR may already be the claim (CONTRIBUTING.md, "Claim = a draft PR"). + const timeline = await getTimeline(github, context, n); + const other = linkedPulls(timeline).find((p) => p.user && p.user.login !== user); + if (other) { + await react(github, context, 'eyes'); + await reply(github, context, `#${other.number} already covers this one.`); + return; + } + } + + // Free (or lapsed): hand it to the commenter. Clear a lapsed claimant first. + if (assignees.length) { + await github.rest.issues.removeAssignees({ ...repoArgs(context), issue_number: n, assignees }); + } + await ensureLabel(github, context); + await github.rest.issues.addLabels({ ...repoArgs(context), issue_number: n, labels: [LABEL] }); + try { + await github.rest.issues.addAssignees({ + ...repoArgs(context), + issue_number: n, + assignees: [user], + }); + } catch (e) { + // Assignment can be refused; the label and the reply naming them still stand. + } + await react(github, context, '+1'); + await reply( + github, + context, + `Claimed by @${user}. Please open a draft PR referencing #${n} within ${CLAIM_HOURS} h; the claim lapses otherwise. \`/unclaim\` releases it.`, + ); +} + +async function unclaim(github, context) { + const issue = context.payload.issue; + const user = context.payload.comment.user.login; + const assignees = (issue.assignees || []).map((a) => a.login); + if (!hasLabel(issue) && assignees.length === 0) { + await react(github, context, '+1'); // nothing to release + return; + } + if (assignees.includes(context.repo.owner)) { + await react(github, context, 'eyes'); // never touched by the bot + return; + } + const allowed = assignees.includes(user) || (await isMaintainer(github, context, user)); + if (!allowed) { + await react(github, context, 'eyes'); + await reply(github, context, `Only the person who claimed this, or a maintainer, can release it, @${user}.`); + return; + } + await release(github, context, issue, assignees); + await react(github, context, '+1'); + await reply(github, context, `Released. This one is free again, so anyone can \`/claim\` it.`); +} + +// The comment event. +async function handleComment({ github, context, now = Date.now() }) { + const { issue, comment } = context.payload; + if (!issue || issue.pull_request || !comment) return 'skip'; + if (issue.state !== 'open' || issue.locked) return 'skip'; + if (comment.user.type === 'Bot' || comment.user.login.endsWith('[bot]')) return 'skip'; + const cmd = parseCommand(comment.body); + if (!cmd) return 'skip'; + if (cmd === 'claim') await claim(github, context, now); + else await unclaim(github, context); + return cmd; +} + +// The daily sweep over open issues labelled `in progress`. +async function sweep({ github, context, now = Date.now() }) { + const issues = await github.paginate(github.rest.issues.listForRepo, { + ...repoArgs(context), + state: 'open', + labels: LABEL, + per_page: 100, + }); + const cache = new Map(); + const released = []; + for (const issue of issues) { + if (issue.pull_request || issue.locked) continue; + const assignees = (issue.assignees || []).map((a) => a.login); + let skip = false; + for (const a of assignees) skip = skip || (await isMaintainer(github, context, a, cache)); + if (skip) continue; + const status = await claimStatus(github, context, issue, now); + if (!status.release) continue; + await release(github, context, issue, assignees); + await github.rest.issues.createComment({ + ...repoArgs(context), + issue_number: issue.number, + body: + status.reason === 'no PR' + ? `No draft PR showed up within ${CLAIM_HOURS} h, so this one is free again. Anyone can \`/claim\` it.` + : `Nothing has been pushed for ${PR_IDLE_DAYS} days, so this one is free again. Anyone can \`/claim\` it.`, + }); + released.push(issue.number); + } + return released; +} + +module.exports = { + LABEL, + parseCommand, + isMaintainer, + linkedPulls, + claimStatus, + handleComment, + sweep, +}; diff --git a/scripts/claim/claim.test.js b/scripts/claim/claim.test.js new file mode 100644 index 000000000..c61da8a1f --- /dev/null +++ b/scripts/claim/claim.test.js @@ -0,0 +1,230 @@ +'use strict'; +const test = require('node:test'); +const assert = require('node:assert/strict'); +const claim = require('./claim.js'); + +const NOW = Date.parse('2026-10-16T12:00:00Z'); +const H = 3600 * 1000; +const ago = (ms) => new Date(NOW - ms).toISOString(); + +// A fake github-script client that records writes. `world` describes the repo. +function fake(world = {}) { + const calls = []; + const rec = (name) => async (args) => { + calls.push([name, args]); + if (world.fail && world.fail[name]) throw Object.assign(new Error(name), { status: world.fail[name] }); + return { data: {} }; + }; + const github = { + paginate: async (fn, args) => (await fn(args)).data, + rest: { + repos: { + getCollaboratorPermissionLevel: async ({ username }) => { + const permission = (world.perms || {})[username] || 'none'; + return { data: { permission } }; + }, + getCommit: async () => ({ data: { commit: { committer: { date: world.pushed || ago(H) } } } }), + }, + pulls: { get: async () => ({ data: { head: { sha: 'abc' } } }) }, + reactions: { createForIssueComment: rec('react') }, + issues: { + getLabel: async () => { + if (world.labelMissing) throw Object.assign(new Error('nf'), { status: 404 }); + return { data: {} }; + }, + createLabel: rec('createLabel'), + addLabels: rec('addLabels'), + removeLabel: rec('removeLabel'), + addAssignees: rec('addAssignees'), + removeAssignees: rec('removeAssignees'), + createComment: rec('comment'), + listForRepo: async () => ({ data: world.issues || [] }), + listEventsForTimeline: async () => ({ data: world.timeline || [] }), + }, + }, + }; + return { github, calls }; +} + +const names = (calls) => calls.map((c) => c[0]); +const find = (calls, n) => calls.find((c) => c[0] === n); +const labeled = (at) => ({ event: 'labeled', label: { name: 'in progress' }, created_at: at }); +const pr = (number, login = 'other', state = 'open') => ({ + event: 'cross-referenced', + source: { issue: { number, state, pull_request: {}, user: { login } } }, +}); + +function ctx(body, { assignees = [], labels = [], user = 'alice', extra = {} } = {}) { + return { + repo: { owner: 'bherbruck', repo: 'solidcraft' }, + payload: { + issue: { + number: 7, + state: 'open', + locked: false, + updated_at: ago(1000 * H), + assignees: assignees.map((login) => ({ login })), + labels: labels.map((name) => ({ name })), + ...extra, + }, + comment: { id: 99, body, user: { login: user, type: 'User' } }, + }, + }; +} + +test('parseCommand', () => { + assert.equal(claim.parseCommand('/claim'), 'claim'); + assert.equal(claim.parseCommand(' /claim please'), 'claim'); + assert.equal(claim.parseCommand('/unclaim'), 'unclaim'); + assert.equal(claim.parseCommand('/claimed'), null); + assert.equal(claim.parseCommand('I would /claim this'), null); + assert.equal(claim.parseCommand(undefined), null); +}); + +test('claim on a free issue assigns, labels, reacts and replies', async () => { + const { github, calls } = fake({ labelMissing: true }); + assert.equal(await claim.handleComment({ github, context: ctx('/claim'), now: NOW }), 'claim'); + assert.deepEqual(find(calls, 'addAssignees')[1].assignees, ['alice']); + assert.deepEqual(find(calls, 'addLabels')[1].labels, ['in progress']); + assert.equal(find(calls, 'createLabel')[1].color, 'fbca04'); + assert.equal(find(calls, 'react')[1].content, '+1'); + assert.match(find(calls, 'comment')[1].body, /^Claimed by @alice\. .*draft PR referencing #7 within 72 h/); +}); + +test('claim still labels and replies when assignment is refused', async () => { + const { github, calls } = fake({ fail: { addAssignees: 422 } }); + await claim.handleComment({ github, context: ctx('/claim'), now: NOW }); + assert.ok(find(calls, 'addLabels')); + assert.match(find(calls, 'comment')[1].body, /@alice/); +}); + +test('claim by the current claimant is a quiet thumbs up', async () => { + const { github, calls } = fake(); + await claim.handleComment({ github, context: ctx('/claim', { assignees: ['alice'], labels: ['in progress'] }), now: NOW }); + assert.deepEqual(names(calls), ['react']); +}); + +test('claim on an issue claimed by someone else names them and when it lapses', async () => { + const { github, calls } = fake({ timeline: [labeled(ago(10 * H))] }); + await claim.handleComment({ github, context: ctx('/claim', { assignees: ['bob'], labels: ['in progress'] }), now: NOW }); + assert.equal(find(calls, 'react')[1].content, 'eyes'); + const body = find(calls, 'comment')[1].body; + assert.match(body, /@bob/); + assert.match(body, /2026-10-19 02:00 UTC/); // 10 h ago + 72 h + assert.equal(find(calls, 'addAssignees'), undefined); +}); + +test('a lapsed claim is taken over', async () => { + const { github, calls } = fake({ timeline: [labeled(ago(100 * H))] }); + await claim.handleComment({ github, context: ctx('/claim', { assignees: ['bob'], labels: ['in progress'] }), now: NOW }); + assert.deepEqual(find(calls, 'removeAssignees')[1].assignees, ['bob']); + assert.deepEqual(find(calls, 'addAssignees')[1].assignees, ['alice']); +}); + +test('a claim with a recent PR is not taken over', async () => { + const { github, calls } = fake({ timeline: [labeled(ago(100 * H)), pr(50, 'bob')], pushed: ago(2 * H) }); + await claim.handleComment({ github, context: ctx('/claim', { assignees: ['bob'], labels: ['in progress'] }), now: NOW }); + assert.equal(find(calls, 'addAssignees'), undefined); +}); + +test('a maintainer\'s claim is never taken over', async () => { + const { github, calls } = fake({ timeline: [labeled(ago(500 * H))], perms: { carol: 'write' } }); + await claim.handleComment({ github, context: ctx('/claim', { assignees: ['carol'], labels: ['in progress'] }), now: NOW }); + assert.equal(find(calls, 'addAssignees'), undefined); + assert.equal(find(calls, 'react')[1].content, 'eyes'); +}); + +test('an unclaimed issue with someone else\'s open PR points at the PR', async () => { + const { github, calls } = fake({ timeline: [pr(42, 'bob')] }); + await claim.handleComment({ github, context: ctx('/claim'), now: NOW }); + assert.equal(find(calls, 'addAssignees'), undefined); + assert.match(find(calls, 'comment')[1].body, /#42/); +}); + +test('bots, locked issues, closed issues, PRs and other comments are ignored', async () => { + const { github, calls } = fake(); + const bot = ctx('/claim'); + bot.payload.comment.user = { login: 'dependabot[bot]', type: 'Bot' }; + assert.equal(await claim.handleComment({ github, context: bot, now: NOW }), 'skip'); + assert.equal(await claim.handleComment({ github, context: ctx('/claim', { extra: { locked: true } }), now: NOW }), 'skip'); + assert.equal(await claim.handleComment({ github, context: ctx('/claim', { extra: { state: 'closed' } }), now: NOW }), 'skip'); + assert.equal(await claim.handleComment({ github, context: ctx('/claim', { extra: { pull_request: {} } }), now: NOW }), 'skip'); + assert.equal(await claim.handleComment({ github, context: ctx('hello'), now: NOW }), 'skip'); + assert.equal(calls.length, 0); +}); + +test('unclaim by the claimant releases', async () => { + const { github, calls } = fake(); + await claim.handleComment({ github, context: ctx('/unclaim', { assignees: ['alice'], labels: ['in progress'] }), now: NOW }); + assert.deepEqual(find(calls, 'removeAssignees')[1].assignees, ['alice']); + assert.equal(find(calls, 'removeLabel')[1].name, 'in progress'); +}); + +test('unclaim by a maintainer releases, by a stranger does not', async () => { + let w = fake({ perms: { carol: 'admin' } }); + await claim.handleComment({ github: w.github, context: ctx('/unclaim', { user: 'carol', assignees: ['bob'], labels: ['in progress'] }), now: NOW }); + assert.ok(find(w.calls, 'removeLabel')); + w = fake(); + await claim.handleComment({ github: w.github, context: ctx('/unclaim', { user: 'mallory', assignees: ['bob'], labels: ['in progress'] }), now: NOW }); + assert.equal(find(w.calls, 'removeLabel'), undefined); + assert.equal(find(w.calls, 'react')[1].content, 'eyes'); +}); + +test('unclaim never touches an issue assigned to the owner', async () => { + const { github, calls } = fake(); + await claim.handleComment({ github, context: ctx('/unclaim', { user: 'bherbruck', assignees: ['bherbruck'], labels: ['in progress'] }), now: NOW }); + assert.equal(find(calls, 'removeLabel'), undefined); +}); + +const issue = (number, assignees = ['bob']) => ({ + number, + locked: false, + updated_at: ago(1000 * H), + assignees: assignees.map((login) => ({ login })), + labels: [{ name: 'in progress' }], +}); +const repo = { owner: 'bherbruck', repo: 'solidcraft' }; + +test('sweep releases a claim older than 72 h with no PR', async () => { + const { github, calls } = fake({ issues: [issue(7)], timeline: [labeled(ago(80 * H))] }); + assert.deepEqual(await claim.sweep({ github, context: { repo }, now: NOW }), [7]); + assert.ok(find(calls, 'removeLabel')); + assert.deepEqual(find(calls, 'removeAssignees')[1].assignees, ['bob']); + assert.match(find(calls, 'comment')[1].body, /free again/); +}); + +test('sweep keeps a young claim and a claim with a fresh PR, using the latest label time', async () => { + let w = fake({ issues: [issue(7)], timeline: [labeled(ago(100 * H)), labeled(ago(5 * H))] }); + assert.deepEqual(await claim.sweep({ github: w.github, context: { repo }, now: NOW }), []); + w = fake({ issues: [issue(7)], timeline: [labeled(ago(500 * H)), pr(9)], pushed: ago(3 * 24 * H) }); + assert.deepEqual(await claim.sweep({ github: w.github, context: { repo }, now: NOW }), []); +}); + +test('sweep releases a claim whose PR has been idle for 14 days', async () => { + const w = fake({ issues: [issue(7)], timeline: [labeled(ago(500 * H)), pr(9)], pushed: ago(15 * 24 * H) }); + assert.deepEqual(await claim.sweep({ github: w.github, context: { repo }, now: NOW }), [7]); + assert.match(find(w.calls, 'comment')[1].body, /14 days/); +}); + +test('sweep ignores a closed PR', async () => { + const w = fake({ issues: [issue(7)], timeline: [labeled(ago(80 * H)), pr(9, 'other', 'closed')] }); + assert.deepEqual(await claim.sweep({ github: w.github, context: { repo }, now: NOW }), [7]); +}); + +test('sweep never touches owner- or maintainer-claimed issues', async () => { + const w = fake({ + issues: [issue(1, ['bherbruck']), issue(2, ['carol']), issue(3, ['bob', 'carol'])], + timeline: [labeled(ago(900 * H))], + perms: { carol: 'write' }, + }); + assert.deepEqual(await claim.sweep({ github: w.github, context: { repo }, now: NOW }), []); + assert.equal(w.calls.length, 0); +}); + +test('sweep is idempotent: a released issue is no longer listed', async () => { + const world = { issues: [issue(7)], timeline: [labeled(ago(80 * H))] }; + const w = fake(world); + assert.deepEqual(await claim.sweep({ github: w.github, context: { repo }, now: NOW }), [7]); + world.issues = []; + assert.deepEqual(await claim.sweep({ github: w.github, context: { repo }, now: NOW }), []); +}); From 987f0be21ebcf9fee070dd919a30d75c50fe3610 Mon Sep 17 00:00:00 2001 From: DuBearte <130190089+DuBearte@users.noreply.github.com> Date: Thu, 15 Oct 2026 22:54:16 -0400 Subject: [PATCH 47/92] Sketch: infinite construction lines (#1359) (#1547) Thanks @DuBearte. --- assets/icons/ui/source/icons.rs | 19 ++- assets/locales/de.json | 2 + assets/locales/en.json | 2 + assets/locales/fr.json | 2 + assets/locales/ja.json | 2 + assets/locales/ko.json | 2 + assets/locales/ru.json | 2 + assets/locales/uk.json | 2 + assets/locales/zh.json | 2 + .../format/pending/infinite-sketch-lines.rs | 5 + crates/engine/src/cmd/features.rs | 3 +- crates/engine/src/cmd/sketch.rs | 8 +- crates/engine/src/cmd/sketch_clipboard.rs | 4 +- crates/engine/src/cmd/sketch_create.rs | 28 ++++ .../engine/src/cmd/sketch_infinite_tests.rs | 137 ++++++++++++++++++ crates/engine/src/cmd/sketch_modify.rs | 42 +++++- crates/engine/src/cmd/sketch_support.rs | 14 ++ crates/sketch/src/link.rs | 1 + crates/sketch/src/model.rs | 10 +- crates/sketch/src/offset_topology.rs | 12 +- crates/sketch/src/profiles.rs | 2 +- crates/ui-egui/src/context_menu.rs | 14 ++ .../src/infinite_line_display_tests.rs | 61 ++++++++ crates/ui-egui/src/sketch_display.rs | 35 ++++- crates/ui-egui/src/sketch_palette.rs | 45 ++++-- crates/ui-egui/src/tools.rs | 4 +- crates/ui-egui/src/viewport.rs | 3 +- 27 files changed, 435 insertions(+), 28 deletions(-) create mode 100644 crates/doc/src/format/pending/infinite-sketch-lines.rs create mode 100644 crates/engine/src/cmd/sketch_infinite_tests.rs create mode 100644 crates/ui-egui/src/infinite_line_display_tests.rs diff --git a/assets/icons/ui/source/icons.rs b/assets/icons/ui/source/icons.rs index 3a354f682..8f4fb5ded 100644 --- a/assets/icons/ui/source/icons.rs +++ b/assets/icons/ui/source/icons.rs @@ -490,6 +490,23 @@ pub(crate) fn paint_with(p: &Painter, r: Rect, name: &str, ink: Color32, fill: C } p.circle_filled(at(0.5), dot_r, a); } + "infinite" => { + // An infinite line (#1359): Construction's broken line, with an open arrowhead at + // each end saying it runs on. Accent only, like Construction and Centerline. + let w = line_type_stroke(r); + let at = |t: f32| pen.at(3.0 + 16.0 * t, 19.0 - 16.0 * t); + for (t0, t1) in [(0.0, 0.38), (0.62, 1.0)] { + p.add(Shape::line(vec![at(t0), at(t1)], Stroke::new(w, a))); + } + // Each head: two short strokes back from the tip, either side of the line. + let tip_len = 0.3; + for (tip, back) in [(0.0f32, tip_len), (1.0, 1.0 - tip_len)] { + let (t, b) = (at(tip), at(back)); + let along = b - t; + let side = egui::vec2(-along.y, along.x) * 0.55; + p.add(Shape::line(vec![b + side, t, b - side], Stroke::new(w, a))); + } + } "c_hv" => { pen.line(&[(4.0, 18.0), (20.0, 18.0)], a); pen.line(&[(6.0, 4.0), (6.0, 14.0)], a); @@ -1482,7 +1499,7 @@ mod tests { /// theme's construction orange) and must not change with `ink`. #[test] fn construction_and_centerline_icons_follow_the_callers_accent_only() { - for name in ["construction", "centerline"] { + for name in ["construction", "centerline", "infinite"] { let base = drawn(name, Color32::BLACK, Color32::WHITE, Color32::from_rgb(1, 2, 3)); let other_accent = drawn(name, Color32::BLACK, Color32::WHITE, Color32::from_rgb(4, 5, 6)); assert_ne!(base, other_accent, "{name} icon must change with the caller's accent colour"); diff --git a/assets/locales/de.json b/assets/locales/de.json index 5ee1040f6..bf66c50dd 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -305,6 +305,7 @@ "cmd.sketch_fit_curves_to_section": "Kurven an Netzquerschnitt anpassen", "cmd.sketch_glyphs": "Bedingungssymbole", "cmd.sketch_include_3d": "3D-Geometrie einbeziehen", + "cmd.sketch_infinite": "Unendliche Linie", "cmd.sketch_insert_dxf": "DXF einfügen", "cmd.sketch_insert_svg": "SVG einfügen", "cmd.sketch_inspect": "Skizze prüfen", @@ -907,6 +908,7 @@ "ui.home": "Start", "ui.homeView": "Startansicht", "ui.horizontal_vertical": "Horizontal/Vertikal", + "ui.infinite": "Unendlich", "ui.insert": "Einfügen", "ui.inspect": "Prüfen", "ui.intersect": "Schnitt", diff --git a/assets/locales/en.json b/assets/locales/en.json index 768d01a10..c4f790a14 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -507,6 +507,7 @@ "cmd.sketch_fit_curves_to_section": "Fit Curves to Mesh Section", "cmd.sketch_glyphs": "Constraint Glyphs", "cmd.sketch_include_3d": "Include 3D Geometry", + "cmd.sketch_infinite": "Infinite Line", "cmd.sketch_insert_dxf": "Insert DXF", "cmd.sketch_insert_svg": "Insert SVG", "cmd.sketch_inspect": "Inspect Sketch", @@ -1139,6 +1140,7 @@ "ui.homeView": "Home View", "ui.horizontal_vertical": "Horizontal/Vertical", "ui.import_ellipsis": "Import…", + "ui.infinite": "Infinite", "ui.insert": "Insert", "ui.inspect": "Inspect", "ui.intersect": "Intersect", diff --git a/assets/locales/fr.json b/assets/locales/fr.json index f48841047..df64badb8 100644 --- a/assets/locales/fr.json +++ b/assets/locales/fr.json @@ -487,6 +487,7 @@ "cmd.sketch_fit_curves_to_section": "Ajuster des courbes à la section du maillage", "cmd.sketch_glyphs": "Symboles de contraintes", "cmd.sketch_include_3d": "Inclure une géométrie 3D", + "cmd.sketch_infinite": "Ligne infinie", "cmd.sketch_insert_dxf": "Insérer un DXF", "cmd.sketch_insert_svg": "Insérer un SVG", "cmd.sketch_inspect": "Inspecter l'esquisse", @@ -979,6 +980,7 @@ "ui.homeView": "Vue d'accueil", "ui.horizontal_vertical": "Horizontale/Verticale", "ui.import_ellipsis": "Importer…", + "ui.infinite": "Infinie", "ui.insert": "Insérer", "ui.inspect": "Inspecter", "ui.intersect": "Intersection", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 8afc38321..b1ef7be09 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -507,6 +507,7 @@ "cmd.sketch_fit_curves_to_section": "メッシュ断面に曲線をフィット", "cmd.sketch_glyphs": "拘束記号", "cmd.sketch_include_3d": "3D ジオメトリを含める", + "cmd.sketch_infinite": "無限線", "cmd.sketch_insert_dxf": "DXF を挿入", "cmd.sketch_insert_svg": "SVG を挿入", "cmd.sketch_inspect": "スケッチを検査", @@ -1139,6 +1140,7 @@ "ui.homeView": "ホームビュー", "ui.horizontal_vertical": "水平/垂直", "ui.import_ellipsis": "インポート…", + "ui.infinite": "無限", "ui.insert": "挿入", "ui.inspect": "検査", "ui.intersect": "交差", diff --git a/assets/locales/ko.json b/assets/locales/ko.json index dc99a66ae..611179b57 100644 --- a/assets/locales/ko.json +++ b/assets/locales/ko.json @@ -305,6 +305,7 @@ "cmd.sketch_fit_curves_to_section": "메시 단면에 곡선 맞추기", "cmd.sketch_glyphs": "구속 기호", "cmd.sketch_include_3d": "3D 기하 포함", + "cmd.sketch_infinite": "무한선", "cmd.sketch_insert_dxf": "DXF 삽입", "cmd.sketch_insert_svg": "SVG 삽입", "cmd.sketch_inspect": "스케치 검사", @@ -907,6 +908,7 @@ "ui.home": "홈", "ui.homeView": "홈 보기", "ui.horizontal_vertical": "수평/수직", + "ui.infinite": "무한", "ui.insert": "삽입", "ui.inspect": "검사", "ui.intersect": "교차", diff --git a/assets/locales/ru.json b/assets/locales/ru.json index 0022d10ad..e7d0e2b4a 100644 --- a/assets/locales/ru.json +++ b/assets/locales/ru.json @@ -458,6 +458,7 @@ "cmd.sketch_fit_curves_to_section": "Подобрать кривые по сечению меша", "cmd.sketch_glyphs": "Знаки ограничений", "cmd.sketch_include_3d": "Включить 3D-геометрию", + "cmd.sketch_infinite": "Бесконечная линия", "cmd.sketch_insert_dxf": "Вставить DXF", "cmd.sketch_insert_svg": "Вставить SVG", "cmd.sketch_inspect": "Инспекция эскиза", @@ -931,6 +932,7 @@ "ui.homeView": "Главный вид", "ui.horizontal_vertical": "Горизонталь/Вертикаль", "ui.import_ellipsis": "Импорт…", + "ui.infinite": "Бесконечная", "ui.insert": "Вставить", "ui.inspect": "Инспекция", "ui.intersect": "Пересечение", diff --git a/assets/locales/uk.json b/assets/locales/uk.json index cde0098b9..15b0e1b40 100644 --- a/assets/locales/uk.json +++ b/assets/locales/uk.json @@ -455,6 +455,7 @@ "cmd.sketch_fit_curves_to_section": "Підігнати криві до перерізу сітки", "cmd.sketch_glyphs": "Позначки обмежень", "cmd.sketch_include_3d": "Включити 3D-геометрію", + "cmd.sketch_infinite": "Нескінченна лінія", "cmd.sketch_insert_dxf": "Вставити DXF", "cmd.sketch_insert_svg": "Вставити SVG", "cmd.sketch_inspect": "Перевірити ескіз", @@ -830,6 +831,7 @@ "ui.homeView": "Головний вид", "ui.horizontal_vertical": "Горизонталь/вертикаль", "ui.import_ellipsis": "Імпорт…", + "ui.infinite": "Нескінченна", "ui.insert": "Вставити", "ui.inspect": "Перевірити", "ui.intersect": "Перетин", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index e32c8632d..ed6d0c8d5 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -507,6 +507,7 @@ "cmd.sketch_fit_curves_to_section": "将曲线拟合到网格截面", "cmd.sketch_glyphs": "约束符号", "cmd.sketch_include_3d": "包含三维几何", + "cmd.sketch_infinite": "无限长直线", "cmd.sketch_insert_dxf": "插入 DXF", "cmd.sketch_insert_svg": "插入 SVG", "cmd.sketch_inspect": "检查草图", @@ -1139,6 +1140,7 @@ "ui.homeView": "主视图", "ui.horizontal_vertical": "水平/垂直", "ui.import_ellipsis": "导入…", + "ui.infinite": "无限", "ui.insert": "插入", "ui.inspect": "检查", "ui.intersect": "相交", diff --git a/crates/doc/src/format/pending/infinite-sketch-lines.rs b/crates/doc/src/format/pending/infinite-sketch-lines.rs new file mode 100644 index 000000000..1893a5d3a --- /dev/null +++ b/crates/doc/src/format/pending/infinite-sketch-lines.rs @@ -0,0 +1,5 @@ +//! A sketch line can be `infinite` (#1359): construction geometry through its two points, drawn +//! across the whole view, a boundary for trim and extend along its whole line. Saved only when +//! set: older designs need no transformation, and a line without it is the line it always was; +//! 0.13.x (which reads up to 24) asks for an update instead of drawing such a line between its +//! two points. diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs index 8c6944c10..c9055cb40 100644 --- a/crates/engine/src/cmd/features.rs +++ b/crates/engine/src/cmd/features.rs @@ -593,7 +593,8 @@ fn thin_param(s: &Session, p: &Value, sketch: u64, cmd: &str) -> Result 1000 { return Err(bad(cmd, "a thin extrude needs 1…1000 sketch curves (`curves`)")); diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rs index f1e5d9b3b..6cc69a3d7 100644 --- a/crates/engine/src/cmd/sketch.rs +++ b/crates/engine/src/cmd/sketch.rs @@ -2244,11 +2244,14 @@ fn construction(s: &mut Session, p: &Value) -> Result { let mut n = 0; for c in cs { if let Some(cu) = sk.curves.get_mut(c) - && (cu.construction != to || to && cu.centerline) + && (cu.construction != to || to && cu.centerline || !to && cu.infinite) { cu.construction = to; if to { cu.centerline = false; + } else { + // A normal line is a finite one. + cu.infinite = false; } n += 1; } @@ -2512,6 +2515,9 @@ mod drag_live_tests; #[path = "sketch_ids_tests.rs"] mod ids_tests; #[cfg(test)] +#[path = "sketch_infinite_tests.rs"] +mod infinite_tests; +#[cfg(test)] #[path = "sketch_redundant_tests.rs"] mod redundant_tests; #[cfg(test)] diff --git a/crates/engine/src/cmd/sketch_clipboard.rs b/crates/engine/src/cmd/sketch_clipboard.rs index b8036f933..c97644558 100644 --- a/crates/engine/src/cmd/sketch_clipboard.rs +++ b/crates/engine/src/cmd/sketch_clipboard.rs @@ -36,6 +36,7 @@ pub struct ClipCurve { pub construction: bool, pub centerline: bool, pub reversed: bool, + pub infinite: bool, } /// A constraint or dimension of the clipboard, over clipboard points and curves. A dimension @@ -133,7 +134,7 @@ fn copy(s: &mut Session, p: &Value) -> Result { kind.map_points(&|q| used.iter().find(|(o, _)| *o == q).map_or(q, |(_, n)| *n)); cmap.insert(c, clip.curves.len()); // Projected geometry comes in as ordinary geometry. - clip.curves.push(ClipCurve { kind, construction: cu.construction, centerline: cu.centerline, reversed: cu.reversed }); + clip.curves.push(ClipCurve { kind, construction: cu.construction, centerline: cu.centerline, reversed: cu.reversed, infinite: cu.infinite }); } for &q in &ps { let known = pmap.contains_key(&q); @@ -276,6 +277,7 @@ fn paste(s: &mut Session, p: &Value) -> Result { cu.construction = c.construction; cu.centerline = c.centerline; cu.reversed = c.reversed; + cu.infinite = c.infinite; } made.push(i); } diff --git a/crates/engine/src/cmd/sketch_create.rs b/crates/engine/src/cmd/sketch_create.rs index e6d428d41..9cf50fbbf 100644 --- a/crates/engine/src/cmd/sketch_create.rs +++ b/crates/engine/src/cmd/sketch_create.rs @@ -94,6 +94,9 @@ pub static COMMANDS: &[CommandSpec] = &[ .icon("centerline") .enabled(in_sketch) .params("curves: [line ids], value?: bool (default toggles): centerline line type (not in profiles; an axis)"), + CommandSpec::new("sketch.infinite", "Infinite Line", infinite_line) + .enabled(in_sketch) + .params("curves: [line ids], value?: bool (default toggles): infinite line type (#1359): construction geometry drawn across the whole view through the line's two points; off, a normal line"), CommandSpec::new("sketch.text", "Text", text).at("SKETCH", "CREATE").icon("text").enabled(in_sketch).params(concat!( "text: string (\\n breaks lines), at: baseline start [x,y], height?: capital height mm (default 5), angle?: deg; at's x and y, height and angle each take a number or an expression over the design's parameters as a string (\"plate_width / 2\", \"label_size\"): the text keeps the expression, follows the parameters, and returns it in `exprs`; an expression naming no parameter is the number it comes to, a bare number in one is in the design's units, \ font?: an installed font's family or full name, or a .ttf/.otf file path (~ and %VAR% expand; default: the built-in Liberation Sans), ", @@ -436,6 +439,7 @@ fn centerline(s: &mut Session, p: &Value) -> Result { cu.centerline = want.unwrap_or(!cu.centerline); if cu.centerline { cu.construction = false; + cu.infinite = false; } } Ok(ids.len()) @@ -443,6 +447,30 @@ fn centerline(s: &mut Session, p: &Value) -> Result { Ok(json!({"changed": n, "sketch": info})) } +fn infinite_line(s: &mut Session, p: &Value) -> Result { + let cmd = "sketch.infinite"; + let ids = string_list(p, "curves"); + if ids.is_empty() { + return Err(bad(cmd, "`curves` must list lines")); + } + let want = crate::params::bool_(p, "value"); + let (n, info) = edit(s, p, cmd, false, |sk, _| { + for id in &ids { + let c = sk.curve_index(id).ok_or_else(|| bad(cmd, format!("unknown curve `{id}`")))?; + let cu = sk.curves.get_mut(c).ok_or_else(|| bad(cmd, "curve"))?; + if !matches!(cu.kind, CurveKind::Line { .. }) { + return Err(bad(cmd, format!("`{id}` is not a line"))); + } + // Infinite lines are construction geometry (never in a profile); off, a normal line. + cu.infinite = want.unwrap_or(!cu.infinite); + cu.construction = cu.infinite; + cu.centerline = false; + } + Ok(ids.len()) + })?; + Ok(json!({"changed": n, "sketch": info})) +} + fn ellipse(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.ellipse"; let (c, m) = (req_vec2(cmd, p, "center")?, req_vec2(cmd, p, "major")?); diff --git a/crates/engine/src/cmd/sketch_infinite_tests.rs b/crates/engine/src/cmd/sketch_infinite_tests.rs new file mode 100644 index 000000000..11fff7ad5 --- /dev/null +++ b/crates/engine/src/cmd/sketch_infinite_tests.rs @@ -0,0 +1,137 @@ +//! Infinite lines (#1359): a line type through two points, construction geometry that reaches +//! across the whole view, a boundary along its whole line, never trimmed, filleted or in a +//! profile. + +use serde_json::{Value, json}; +use solidcraft_geom::Vec2; +use solidcraft_sketch::{CurveKind, Sketch}; + +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) -> Sketch { + s.doc.sketch(s.active_sketch.unwrap()).unwrap().clone() +} + +fn curve<'a>(sk: &'a Sketch, id: &str) -> &'a solidcraft_sketch::Curve { + sk.curves.get(sk.curve_index(id).unwrap()).unwrap() +} + +fn new_sketch() -> Session { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY"})); + s +} + +fn profiles(s: &Session) -> usize { + s.model.state().sketch(s.active_sketch.unwrap()).unwrap().profiles.len() +} + +#[test] +fn the_line_type_switches_on_and_off_and_stays_out_of_profiles() { + let mut s = new_sketch(); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 20]})); + run(&mut s, "sketch.line", json!({"points": [[20, -10], [20, 30]], "ids": ["axis"]})); + assert_eq!(profiles(&s), 2, "a normal line cuts the rectangle in two"); + run(&mut s, "sketch.infinite", json!({"curves": ["axis"]})); + let sk = sketch(&s); + assert!(curve(&sk, "axis").infinite && curve(&sk, "axis").construction && !curve(&sk, "axis").centerline); + assert_eq!(profiles(&s), 1, "an infinite line is construction: no profile"); + // Back to a normal line, by toggling or by Normal/Construction. + run(&mut s, "sketch.infinite", json!({"curves": ["axis"]})); + let sk = sketch(&s); + assert!(!curve(&sk, "axis").infinite && !curve(&sk, "axis").construction); + run(&mut s, "sketch.infinite", json!({"curves": ["axis"], "value": true})); + run(&mut s, "sketch.construction", json!({"curves": ["axis"], "value": false})); + assert!(!curve(&sketch(&s), "axis").infinite, "a normal line is a finite one"); + // A centerline is not an infinite line. + run(&mut s, "sketch.infinite", json!({"curves": ["axis"], "value": true})); + run(&mut s, "sketch.centerline", json!({"curves": ["axis"], "value": true})); + let sk = sketch(&s); + assert!(curve(&sk, "axis").centerline && !curve(&sk, "axis").infinite); + // Only lines. + run(&mut s, "sketch.circle.center", json!({"center": [60, 0], "radius": 5, "id": "c"})); + assert!(s.execute("sketch.infinite", &json!({"curves": ["c"]})).is_err()); +} + +#[test] +fn it_is_saved_and_a_line_without_it_reads_finite() { + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points": [[0, 0], [10, 5]], "ids": ["a"]})); + run(&mut s, "sketch.line", json!({"points": [[0, 10], [10, 15]], "ids": ["b"]})); + run(&mut s, "sketch.infinite", json!({"curves": ["a"]})); + let text = s.doc.to_json(); + let back = solidcraft_doc::Document::from_json(&text).unwrap(); + let sk = back.sketch(s.active_sketch.unwrap()).unwrap(); + assert!(curve(sk, "a").infinite); + assert!(!curve(sk, "b").infinite); + assert_eq!(text.matches("\"infinite\"").count(), 1, "saved only where it is set"); +} + +#[test] +fn trim_and_extend_use_the_whole_line_but_never_trim_it() { + // An infinite vertical line at x = 25 whose two points lie far above the other line. + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points": [[25, 50], [25, 60]], "ids": ["inf"]})); + run(&mut s, "sketch.infinite", json!({"curves": ["inf"]})); + run(&mut s, "sketch.line", json!({"points": [[0, 0], [40, 0]], "ids": ["l"]})); + // Trimming the line's right part stops at the infinite line's crossing, x = 25. + run(&mut s, "sketch.trim", json!({"curve": "l", "at": [35, 0]})); + let sk = sketch(&s); + let CurveKind::Line { a, b } = curve(&sk, "l").kind else { panic!("a line") }; + let xs = [sk.point(a).unwrap().x, sk.point(b).unwrap().x]; + assert!(xs.iter().any(|x| (x - 25.0).abs() < 1e-6) && xs.iter().all(|x| *x <= 25.0 + 1e-6), "{xs:?}"); + // The infinite line itself is not trimmed. + let e = s.execute("sketch.trim", &json!({"curve": "inf", "at": [25, 55]})).unwrap_err().to_string(); + assert!(e.contains("infinite"), "{e}"); + // A short line extends to it, beyond its two points. + run(&mut s, "sketch.line", json!({"points": [[0, 10], [10, 10]], "ids": ["short"]})); + run(&mut s, "sketch.extend", json!({"curve": "short", "at": [10, 10]})); + let sk = sketch(&s); + let CurveKind::Line { b, .. } = curve(&sk, "short").kind else { panic!("a line") }; + assert!(sk.point(b).unwrap().dist(Vec2::new(25.0, 10.0)) < 1e-6, "{:?}", sk.point(b)); +} + +#[test] +fn fillets_and_chamfers_refuse_it_and_mirrors_copy_it() { + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points": [[0, 0], [20, 0], [20, 20]], "ids": ["a", "b"]})); + run(&mut s, "sketch.infinite", json!({"curves": ["a"]})); + let before = s.doc.to_json(); + for (cmd, p) in [ + ("sketch.fillet", json!({"point": "a.end", "radius": 2})), + ("sketch.fillet", json!({"a": "a", "b": "b", "radius": 2})), + ("sketch.chamfer.equal_distance", json!({"point": "a.end", "distance": 2})), + ] { + let e = s.execute(cmd, &p).unwrap_err().to_string(); + assert!(e.contains("infinite"), "{cmd}: {e}"); + } + assert_eq!(s.doc.to_json(), before); + run(&mut s, "sketch.line", json!({"points": [[-10, -5], [-10, 5]], "ids": ["m"]})); + let r = run(&mut s, "sketch.mirror", json!({"entities": ["a"], "line": "m"})); + let made = r["curves"].as_array().unwrap().iter().filter_map(Value::as_str).map(str::to_string).collect::>(); + let sk = sketch(&s); + assert!(made.iter().any(|id| curve(&sk, id).infinite), "{r}"); +} + +#[test] +fn an_offset_of_it_is_infinite_too() { + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points": [[0, 0], [10, 0]], "ids": ["inf"]})); + run(&mut s, "sketch.infinite", json!({"curves": ["inf"]})); + let r = run(&mut s, "sketch.offset", json!({"curves": ["inf"], "distance": 5, "side": [5, 5]})); + let made = r["curves"].as_array().unwrap().iter().filter_map(Value::as_str).map(str::to_string).collect::>(); + let sk = sketch(&s); + assert!(!made.is_empty() && made.iter().all(|id| curve(&sk, id).infinite), "{r}"); + // It stays infinite when the offset follows a new distance. + let param = r["param"].as_str().unwrap().to_string(); + run(&mut s, "parameters.change", json!({"name": param, "expression": "8 mm"})); + let sk = sketch(&s); + assert!(made.iter().all(|id| curve(&sk, id).infinite)); +} diff --git a/crates/engine/src/cmd/sketch_modify.rs b/crates/engine/src/cmd/sketch_modify.rs index 65e6325d3..6c6249ee2 100644 --- a/crates/engine/src/cmd/sketch_modify.rs +++ b/crates/engine/src/cmd/sketch_modify.rs @@ -147,8 +147,10 @@ fn cut_points(sk: &Sketch, ci: usize) -> Vec<(f64, Vec2, usize)> { { pts.extend([other.point(0.0), other.point(sweep)]); } + // An infinite line (#1359) cuts wherever its line crosses, beyond its two points too. + let other_infinite = sk.curves.get(oi).is_some_and(|c| c.infinite); for q in pts { - if on_bounded(&other, q).is_some() + if (other_infinite || on_bounded(&other, q).is_some()) && let Some(t) = on_bounded(&sh, q) && !out.iter().any(|(_, x, _)| x.dist(q) < TOL * 10.0) { @@ -197,7 +199,7 @@ fn split_at(sk: &mut Sketch, ci: usize, ts: &[f64]) -> Result<(Vec, Vec Result<()> { let id = sk.fresh(prefix)?; - sk.curves.push(Curve { id, kind, construction, reversed: false, link: None, centerline: false, fixed: false }); + sk.curves.push(Curve { id, kind, construction, reversed: false, link: None, centerline: false, fixed: false, infinite: false }); pieces.push(sk.curves.len() - 1); Ok(()) }; @@ -286,6 +288,9 @@ fn trim(s: &mut Session, p: &Value) -> Result { 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(); @@ -418,7 +423,11 @@ fn extend(s: &mut Session, p: &Value) -> Result { if oi == ci { continue; } - let pieces = sk.exact_segs(oi).unwrap_or_else(|| sk.segs(oi)); + let mut pieces = sk.exact_segs(oi).unwrap_or_else(|| sk.segs(oi)); + // An infinite line (#1359) is a boundary along its whole line. + if sk.curves.get(oi).is_some_and(|c| c.infinite) { + pieces = pieces.iter().map(|s| support::endless(s, sh.point(sh.param(at)))).collect(); + } segment_count += pieces.len(); if segment_count > 16_384 { return Err(bad(cmd, "too many exact curve pieces to extend safely")); @@ -528,6 +537,16 @@ fn weld_corner(sk: &mut Sketch, p: &Value) { } } +/// Fillets and chamfers refuse a corner on an infinite line (#1359): it has no end there. +fn refuse_infinite_corner(sk: &Sketch, p: &Value, cmd: &str) -> Result<()> { + let infinite = |c: Option| c.and_then(|c| sk.curves.get(c)).is_some_and(|c| c.infinite); + let at_corner = match str_(p, "point").and_then(|r| sk.resolve_point(r)) { + Some(q) => sk.curves.iter().any(|c| c.infinite && c.kind.uses(q)), + None => ["a", "b"].iter().any(|k| infinite(str_(p, k).and_then(|i| sk.curve_index(i)))), + }; + if at_corner { Err(bad(cmd, "an infinite line has no corner to round or cut: make it a normal line first")) } else { Ok(()) } +} + /// A corner of two lines: (line a, line b, corner point, far end of a, far end of b). fn corner(sk: &Sketch, p: &Value, cmd: &str) -> Result<(usize, usize, usize, usize, usize)> { let ends = |l: usize| match sk.curves.get(l).map(|c| &c.kind) { @@ -745,6 +764,7 @@ fn kept_json(kept: Vec) -> (Vec, Vec) { /// Round one corner (`point` or `a`, `b`) with an arc of radius `r` tangent to both curves: /// the arc, the tangent constraints and what became of the corner point. fn fillet_corner(sk: &mut Sketch, p: &Value, r: f64, cmd: &str) -> Result<(usize, Vec, CornerKept)> { + refuse_infinite_corner(sk, p, cmd)?; weld_corner(sk, p); let (la, lb, c, fa, fb) = match corner(sk, p, cmd) { Ok(x) => x, @@ -854,6 +874,7 @@ fn round_corner(sk: &mut Sketch, p: &Value, r: f64, cmd: &str) -> Result Result<(f64, f64)>) -> Result { let (out, info) = edit(s, p, cmd, false, |sk, _| { + refuse_infinite_corner(sk, p, cmd)?; weld_corner(sk, p); let (la, lb, c, fa, fb) = corner(sk, p, cmd)?; let (pc, pa, pb) = (sk.point(c).unwrap_or_default(), sk.point(fa).unwrap_or_default(), sk.point(fb).unwrap_or_default()); @@ -1343,6 +1364,18 @@ fn offset(s: &mut Session, p: &Value) -> Result { .map(|o| o.sources.iter().map(|(id, _)| id.clone()).collect::>()) .or_else(|| sk.freeform_offsets.iter().find(|o| o.output == *output).map(|o| vec![o.source.clone()])) .ok_or_else(|| bad(cmd, "offset association is missing"))?; + // An offset of infinite lines is infinite lines too (#1359). + let infinite = sources.iter().all(|id| sk.curve_index(id).and_then(|c| sk.curves.get(c)).is_some_and(|c| c.infinite)); + if infinite { + for id in group.iter().flat_map(|side| side.curves.iter()) { + if let Some(cu) = sk.curve_index(id).and_then(|c| sk.curves.get_mut(c)) + && matches!(cu.kind, CurveKind::Line { .. }) + { + cu.infinite = true; + cu.construction = true; + } + } + } for (index, side) in group.iter_mut().enumerate() { let name = if index == 1 { param2.as_ref().unwrap_or(¶m) } else { ¶m }; let output = side.curves.first().ok_or_else(|| bad(cmd, "offset produced no curves"))?; @@ -1631,6 +1664,8 @@ fn copy_through( } }; let id = sk.fresh(prefix)?; + // A mirrored or patterned infinite line is an infinite line too (#1359). + let infinite = cu.infinite && matches!(kind, CurveKind::Line { .. }); sk.curves.push(Curve { id, kind, @@ -1639,6 +1674,7 @@ fn copy_through( link: None, centerline: false, fixed: false, + infinite, }); made.push(sk.curves.len() - 1); } diff --git a/crates/engine/src/cmd/sketch_support.rs b/crates/engine/src/cmd/sketch_support.rs index 1a3208ef2..1f3b1543e 100644 --- a/crates/engine/src/cmd/sketch_support.rs +++ b/crates/engine/src/cmd/sketch_support.rs @@ -154,6 +154,20 @@ pub(super) fn hits(support: &Shape, seg: &Seg2, budget: &mut usize) -> Result Seg2 { + let Seg2::Line { a, b } = *seg else { return *seg }; + let Some(dir) = (b - a).normalized() else { return *seg }; + let mid = a + dir * (near - a).dot(dir); + Seg2::Line { a: mid - dir * ENDLESS, b: mid + dir * ENDLESS } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/sketch/src/link.rs b/crates/sketch/src/link.rs index 4f57b9ba2..8a8c274ab 100644 --- a/crates/sketch/src/link.rs +++ b/crates/sketch/src/link.rs @@ -655,6 +655,7 @@ impl Sketch { link: Some(id.to_string()), centerline: false, fixed: false, + infinite: false, }); } for li in &lay.lone { diff --git a/crates/sketch/src/model.rs b/crates/sketch/src/model.rs index 2a483cc24..042d968b8 100644 --- a/crates/sketch/src/model.rs +++ b/crates/sketch/src/model.rs @@ -169,6 +169,11 @@ pub struct Curve { /// Fixed (locked): its points and radius are constants for the solver. #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub fixed: bool, + /// Infinite line type (#1359), for lines only: construction geometry drawn across the whole + /// view, through its two points, which fix where it lies and which way it runs. Never part of + /// a profile (it is construction too). + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub infinite: bool, } /// Geometric constraints and dimensions. Indices refer to `Sketch::points` (`p`, `q`) or @@ -735,6 +740,7 @@ impl Sketch { link: None, centerline: false, fixed: false, + infinite: false, }); Ok(self.curves.len() - 1) } @@ -772,6 +778,7 @@ impl Sketch { link: None, centerline: false, fixed: false, + infinite: false, }); Ok(self.curves.len() - 1) } @@ -806,6 +813,7 @@ impl Sketch { link: None, centerline: false, fixed: false, + infinite: false, }); Ok(self.curves.len() - 1) } @@ -1376,7 +1384,7 @@ impl Sketch { } }; let id = self.curve_id(id, prefix)?; - self.curves.push(Curve { id, kind, construction: false, reversed: false, link: None, centerline: false, fixed: false }); + self.curves.push(Curve { id, kind, construction: false, reversed: false, link: None, centerline: false, fixed: false, infinite: false }); Ok(self.curves.len() - 1) } diff --git a/crates/sketch/src/offset_topology.rs b/crates/sketch/src/offset_topology.rs index 0427d1215..2d04e071c 100644 --- a/crates/sketch/src/offset_topology.rs +++ b/crates/sketch/src/offset_topology.rs @@ -27,13 +27,21 @@ pub struct OffsetRoleFlags { pub centerline: bool, pub reversed: bool, pub fixed: bool, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub infinite: bool, } impl OffsetRoleFlags { fn is_default(&self) -> bool { *self == Self::default() } fn of(curve: &Curve) -> Self { - Self { construction: curve.construction, centerline: curve.centerline, reversed: curve.reversed, fixed: curve.fixed } + Self { + construction: curve.construction, + centerline: curve.centerline, + reversed: curve.reversed, + fixed: curve.fixed, + infinite: curve.infinite, + } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -614,6 +622,7 @@ impl Sketch { link: None, centerline: false, fixed: false, + infinite: false, }); outputs.push(output); } @@ -767,6 +776,7 @@ impl Sketch { link: None, centerline: role.flags.centerline, fixed: role.flags.fixed, + infinite: role.flags.infinite, }); } outputs.push(role.output.clone()); diff --git a/crates/sketch/src/profiles.rs b/crates/sketch/src/profiles.rs index 1a0be1fbb..2b6d4a96e 100644 --- a/crates/sketch/src/profiles.rs +++ b/crates/sketch/src/profiles.rs @@ -558,7 +558,7 @@ fn find_profiles_bounded(sk: &Sketch, max_edges: usize) -> Vec { let mut whole_graph_complete = true; let mut expected = std::collections::HashMap::>::new(); for (ci, c) in sk.curves.iter().enumerate() { - if c.construction || c.centerline { + if c.construction || c.centerline || c.infinite { continue; } if matches!(c.kind, CurveKind::Line { .. } | CurveKind::Arc { .. } | CurveKind::Circle { .. }) { diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index cad1081ea..cc1d18e47 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -781,6 +781,20 @@ fn sketch_entity_items(app: &SolveApp) -> Vec { if !curves.is_empty() { v.push(cmd(app, "sketch.construction", "Normal / Construction").with(json!({ "curves": curves }))); } + // Infinite lines (#1359): the selected lines switch together. + let lines: Vec = curves + .iter() + .filter(|id| { + ss.sketch + .curve_index(id) + .and_then(|i| ss.sketch.curves.get(i)) + .is_some_and(|c| matches!(c.kind, solidcraft_engine::sketch::CurveKind::Line { .. })) + }) + .cloned() + .collect(); + if !lines.is_empty() { + v.push(cmd(app, "sketch.infinite", "Infinite Line").with(json!({ "curves": lines }))); + } if curves.len() == 1 && ss.sketch.freeform_offsets.iter().any(|offset| offset.output == curves[0]) { v.push(cmd(app, "sketch.offset.break", "Break Offset Association").with(json!({"curve":curves[0]}))); } diff --git a/crates/ui-egui/src/infinite_line_display_tests.rs b/crates/ui-egui/src/infinite_line_display_tests.rs new file mode 100644 index 000000000..bbb3bcc54 --- /dev/null +++ b/crates/ui-egui/src/infinite_line_display_tests.rs @@ -0,0 +1,61 @@ +//! An infinite line (#1359) is drawn across the whole view and picked along its whole line, +//! and the Sketch Palette's Infinite mode draws one. + +use serde_json::json; + +use crate::scenario::Harness; +use crate::viewport::{Hit, pick, projection}; + +/// An XY sketch with a short line from (0, 0) to (2, 0) made infinite, the view zoomed out. +fn short_infinite_line() -> Harness { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.run("sketch.create", json!({"plane": "XY"})).unwrap(); + h.app.run("sketch.line", json!({"points": [[0, 0], [2, 0]], "ids": ["inf"]})).unwrap(); + h.app.run("sketch.infinite", json!({"curves": ["inf"]})).unwrap(); + h.app.cam.distance = 400.0; + h.settle(); + h +} + +#[test] +fn it_is_drawn_from_edge_to_edge_of_the_view() { + let h = short_infinite_line(); + let rect = h.app.viewport.rect.unwrap(); + let proj = projection(&h.app, rect); + let st = h.app.session.world_state(); + let ss = st.sketch(h.app.session.active_sketch.unwrap()).unwrap(); + let i = ss.sketch.curve_index("inf").unwrap(); + let parts = super::curve_parts(&ss.sketch, i, &ss.plane, &proj, 1.0); + let xs: Vec = parts.iter().flatten().filter_map(|p| proj.to_screen(*p)).map(|p| p.x).collect(); + let (lo, hi) = xs.iter().fold((f32::MAX, f32::MIN), |(lo, hi), x| (lo.min(*x), hi.max(*x))); + // Its two points are a few pixels apart; drawn, it spans the view. + assert!(lo <= rect.left() + 2.0 && hi >= rect.right() - 2.0, "drawn from {lo} to {hi} in {rect:?}"); +} + +#[test] +fn it_is_picked_far_beyond_its_two_points() { + let h = short_infinite_line(); + let rect = h.app.viewport.rect.unwrap(); + let proj = projection(&h.app, rect); + let ss_plane = h.app.session.world_state().sketch(h.app.session.active_sketch.unwrap()).unwrap().plane; + let far = proj.to_screen(ss_plane.to_world(solidcraft_engine::geom::Vec2::new(150.0, 0.0))).unwrap(); + assert!(rect.contains(far)); + let hits = pick(&h.app, &proj, far); + assert!(hits.iter().any(|h| matches!(h, Hit::SketchCurve { id, .. } if id == "inf")), "{hits:?}"); +} + +#[test] +fn infinite_mode_draws_infinite_lines() { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.run("sketch.create", json!({"plane": "XY"})).unwrap(); + h.settle(); + crate::sketch_palette::set_mode(&mut h.app, 3); + let r = h.app.run("sketch.line", json!({"points": [[0, 0], [10, 5]]})).unwrap(); + crate::sketch_palette::apply_mode(&mut h.app, "sketch.line", &r); + let id = r["curves"][0].as_str().unwrap().to_string(); + let sk = h.app.session.doc.sketch(h.app.session.active_sketch.unwrap()).unwrap(); + let c = sk.curves.get(sk.curve_index(&id).unwrap()).unwrap(); + assert!(c.infinite && c.construction, "{c:?}"); +} diff --git a/crates/ui-egui/src/sketch_display.rs b/crates/ui-egui/src/sketch_display.rs index fbb20c190..a1178b609 100644 --- a/crates/ui-egui/src/sketch_display.rs +++ b/crates/ui-egui/src/sketch_display.rs @@ -26,8 +26,35 @@ pub fn pixel_view(proj: &Proj, ppp: f32) -> PixelCurveView { PixelCurveView { vp: proj.vp, width_px: f64::from(proj.rect.width() * ppp), height_px: f64::from(proj.rect.height() * ppp) } } +/// The pieces a curve is drawn and picked from. An infinite line (#1359) reaches across the whole +/// view: through the point of its line nearest the view's centre, far past the view each way +/// (the sampler clips it to the view). Only the display changes: the line keeps its two points. +fn display_segs(sketch: &Sketch, index: usize, plane: &Plane, proj: &Proj) -> Vec { + use solidcraft_engine::geom::Seg2; + let segs = sketch.exact_segs(index).unwrap_or_else(|| sketch.segs(index)); + if !sketch.curves.get(index).is_some_and(|c| c.infinite) { + return segs; + } + let target = proj.cam.target - plane.origin; + let centre = Vec2::new(target.dot(plane.x), target.dot(plane.y)); + let reach = 4.0 * (proj.cam.distance.abs() + proj.cam.half_height().abs()) + 1.0; + segs.into_iter() + .map(|s| match s { + Seg2::Line { a, b } => match (b - a).normalized() { + Some(dir) => { + let mid = a + dir * (centre - a).dot(dir); + let reach = reach + mid.dist(centre); + Seg2::Line { a: mid - dir * reach, b: mid + dir * reach } + } + None => s, + }, + other => other, + }) + .collect() +} + pub fn curve_with_budget(sketch: &Sketch, index: usize, plane: &Plane, proj: &Proj, ppp: f32, budget: &mut SamplingBudget) -> SampledPath { - let segments = sketch.exact_segs(index).unwrap_or_else(|| sketch.segs(index)); + let segments = display_segs(sketch, index, plane, proj); let mut local = SamplingBudget::new(budget.remaining_vertices.min(4096), budget.remaining_nodes.min(65_536)); let initial = local.clone(); let mut out = SampledPath { parts: Vec::new(), quality: SamplingQuality::Complete, vertex_count: 0 }; @@ -47,7 +74,7 @@ pub fn curve_with_budget(sketch: &Sketch, index: usize, plane: &Plane, proj: &Pr pub fn curve_unclipped(sketch: &Sketch, index: usize, plane: &Plane, proj: &Proj, ppp: f32) -> SampledPath { let mut budget = SamplingBudget::new(4096, 65_536); let mut out = SampledPath { parts: Vec::new(), quality: SamplingQuality::Complete, vertex_count: 0 }; - for segment in sketch.exact_segs(index).unwrap_or_else(|| sketch.segs(index)) { + for segment in display_segs(sketch, index, plane, proj) { let sampled = sample_segment_unclipped(&segment, plane, &pixel_view(proj, ppp), &mut budget); if sampled.quality != SamplingQuality::Complete { out.quality = sampled.quality; @@ -244,3 +271,7 @@ pub fn curve_sample(app: &SolveApp, sketch: u64, index: usize, plane: &Plane, pr )), } } + +#[cfg(test)] +#[path = "infinite_line_display_tests.rs"] +mod infinite_line_display_tests; diff --git a/crates/ui-egui/src/sketch_palette.rs b/crates/ui-egui/src/sketch_palette.rs index ac376ec09..aa81e55a8 100644 --- a/crates/ui-egui/src/sketch_palette.rs +++ b/crates/ui-egui/src/sketch_palette.rs @@ -83,7 +83,7 @@ pub fn dof_text(dof: usize, ok: bool) -> String { } /// The line type new curves get in the sketch being edited (0 normal, 1 construction, -/// 2 centerline); a new sketch starts normal. +/// 2 centerline, 3 infinite); a new sketch starts normal. pub fn mode(app: &SolveApp) -> u8 { let (m, sk) = MODE.with(Cell::get); if sk.is_some() && sk == app.session.active_sketch { m } else { 0 } @@ -95,6 +95,7 @@ pub fn set_mode(app: &mut SolveApp, m: u8) { let hint = match m { 1 => "Construction mode: new curves are construction geometry (X or the palette's Normal to leave)", 2 => "Centerline mode: new lines are centerlines", + 3 => "Infinite mode: new lines are infinite construction lines", _ => "Normal mode", }; app.set_status(hint, false); @@ -124,7 +125,7 @@ pub fn apply_mode(app: &mut SolveApp, id: &str, result: &Value) { if curves.is_empty() { return; } - let lines: Vec = if m == 2 { + let lines: Vec = if m == 2 || m == 3 { let st = app.session.model.state(); let Some(ss) = app.session.active_sketch.and_then(|s| st.sketch(s)) else { return }; curves @@ -144,7 +145,8 @@ pub fn apply_mode(app: &mut SolveApp, id: &str, result: &Value) { // Part of the drawing's own undo step. let depth = app.session.undo.len(); if !lines.is_empty() { - let _ = app.session.execute("sketch.centerline", &json!({ "curves": lines, "value": true })); + let line_type = if m == 3 { "sketch.infinite" } else { "sketch.centerline" }; + let _ = app.session.execute(line_type, &json!({ "curves": lines, "value": true })); } if !rest.is_empty() { let _ = app.session.execute("sketch.construction", &json!({ "curves": rest, "value": true })); @@ -158,9 +160,10 @@ fn selected_curves(app: &SolveApp) -> Vec { } /// The line types among the selected curves of the active sketch, indexed like the palette's -/// buttons (0 normal, 1 construction, 2 centerline); a mixed selection marks each of its types. -fn selected_linetypes(app: &SolveApp) -> [bool; 3] { - let mut types = [false; 3]; +/// buttons (0 normal, 1 construction, 2 centerline, 3 infinite); a mixed selection marks each of +/// its types. +fn selected_linetypes(app: &SolveApp) -> [bool; 4] { + let mut types = [false; 4]; let curves = selected_curves(app); if curves.is_empty() { return types; @@ -168,7 +171,9 @@ fn selected_linetypes(app: &SolveApp) -> [bool; 3] { let st = app.session.world_state(); let Some(ss) = app.session.active_sketch.and_then(|s| st.sketch(s)) else { return types }; for c in curves.iter().filter_map(|id| ss.sketch.curve_index(id).and_then(|i| ss.sketch.curves.get(i))) { - let k = if c.centerline { + let k = if c.infinite { + 3 + } else if c.centerline { 2 } else if c.construction { 1 @@ -182,7 +187,8 @@ fn selected_linetypes(app: &SolveApp) -> [bool; 3] { types } -/// Set the line type of the selected curves: 0 normal, 1 construction, 2 centerline (lines). +/// Set the line type of the selected curves: 0 normal, 1 construction, 2 centerline, 3 infinite +/// (the last two for lines). pub fn set_linetype(app: &mut SolveApp, kind: u8) { let curves = selected_curves(app); if curves.is_empty() { @@ -210,7 +216,14 @@ pub fn set_linetype(app: &mut SolveApp, kind: u8) { } app.run("sketch.construction", json!({ "curves": curves, "value": false })) } - 1 => app.run("sketch.construction", json!({ "curves": curves, "value": true })), + 1 => { + if !lines.is_empty() { + let _ = app.run("sketch.infinite", json!({ "curves": lines, "value": false })); + } + app.run("sketch.construction", json!({ "curves": curves, "value": true })) + } + 3 if lines.is_empty() => Err("an infinite line must be a line".to_string()), + 3 => app.run("sketch.infinite", json!({ "curves": lines, "value": true })), _ if lines.is_empty() => Err("a centerline must be a line".to_string()), _ => app.run("sketch.centerline", json!({ "curves": lines, "value": true })), }; @@ -430,7 +443,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { // Centerline need a round dot and a clear gap to read apart. 30 by // 20 px left too little square room for either. let btn_w = 36.0; - let group_w = 3.0 * btn_w + 2.0 * ui.spacing().item_spacing.x; + let group_w = 4.0 * btn_w + 3.0 * ui.spacing().item_spacing.x; crate::frame::right_aligned(ui, width, group_w, |ui| { ui.horizontal(|ui| { // With a selection: its line type, and a click converts it; @@ -442,10 +455,14 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { // construction orange. Normal's icon never changes with the // accent colour. It stays neutral in every case. let current = mode(app); - for (i, (label, icon, tip)) in - [("—", "normal", "Normal"), ("- -", "construction", "Construction"), ("-·-", "centerline", "Centerline")] - .iter() - .enumerate() + for (i, (label, icon, tip)) in [ + ("—", "normal", "Normal"), + ("- -", "construction", "Construction"), + ("-·-", "centerline", "Centerline"), + ("↔", "infinite", "Infinite"), + ] + .iter() + .enumerate() { let on = if has_curves { selected_types.get(i).copied().unwrap_or(false) } else { current == i as u8 }; let tr_tip = app.tr_label(tip); diff --git a/crates/ui-egui/src/tools.rs b/crates/ui-egui/src/tools.rs index 8a8e22ae5..cd23fc7b6 100644 --- a/crates/ui-egui/src/tools.rs +++ b/crates/ui-egui/src/tools.rs @@ -533,7 +533,9 @@ pub(crate) fn paint_preview_curve( mode: u8, ) { for curve in &mut sketch.curves { - curve.centerline = mode == 2 && matches!(curve.kind, solidcraft_engine::sketch::CurveKind::Line { .. }); + 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; } paint_curve(&sketch, 0, plane, painter, proj, stroke, &mut solidcraft_engine::render::SamplingBudget::new(4096, 65_536)); diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index f43441544..583915d3e 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -807,7 +807,8 @@ fn ground_shadow(sc: &mut GpuScene, app: &SolveApp, st: &std::sync::Arc Vec<(Vec3, Vec3)> { match mode { - 1 => dashes(pts, &[0.3 * unit, 0.2 * unit]), + // Construction, and infinite lines (#1359), which are construction too. + 1 | 3 => dashes(pts, &[0.3 * unit, 0.2 * unit]), 2 => dashes(pts, &[0.6 * unit, 0.15 * unit, 0.05 * unit, 0.15 * unit]), _ => pts.windows(2).map(|w| (w[0], w[1])).collect(), } From 77bdcc47e9e6ad7d2bdf12ed508ba8e89035c6cb Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 16 Oct 2026 03:01:46 +0000 Subject: [PATCH 48/92] Regenerate THIRD-PARTY-LICENSES.txt and docs/features.md [skip ci] --- docs/features.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/features.md b/docs/features.md index 29ae43bca..11693a1e9 100644 --- a/docs/features.md +++ b/docs/features.md @@ -1,8 +1,8 @@ # Features -SolidCraft's commands by area, generated by `cargo xtask features` from the command registry (`solidcraft-cli commands`). **377 commands.** Planned (registered, not built yet): 3. 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`). **378 commands.** Planned (registered, not built yet): 3. 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 (102) +## Sketch (103) | Command | Id | Toolbar | |---|---|---| @@ -61,6 +61,7 @@ SolidCraft's commands by area, generated by `cargo xtask features` from the comm | 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 | From fac3f96bdd82a146c952d8a35d7e50bb85aa995c Mon Sep 17 00:00:00 2001 From: Irakli Kourtis Date: Thu, 15 Oct 2026 23:07:24 -0400 Subject: [PATCH 49/92] Patch: G1/G2 to the faces beside the loop, general and N-sided loops, points (#759) (#1521) Thanks @jyviko. --- ROADMAP.md | 2 + assets/locales/de.json | 6 + assets/locales/en.json | 6 + assets/locales/fr.json | 6 + assets/locales/ja.json | 6 + assets/locales/ko.json | 6 + assets/locales/ru.json | 6 + assets/locales/uk.json | 6 + assets/locales/zh.json | 6 + crates/doc/src/document.rs | 47 + crates/doc/src/eval_surface.rs | 10 +- .../pending/patch-continuity-and-points.rs | 6 + crates/engine/src/cmd/surface.rs | 142 +- crates/engine/src/tests.rs | 2 + crates/geom/src/fill.rs | 132 +- crates/geom/src/fill_general.rs | 1150 +++++++++++++++++ crates/geom/src/fill_general_tests.rs | 191 +++ crates/geom/src/lib.rs | 1 + crates/kernel/src/bridge.rs | 122 +- crates/kernel/src/fill.rs | 286 +++- crates/kernel/src/fill_general_tests.rs | 506 ++++++++ crates/kernel/src/lib.rs | 4 +- crates/ui-egui/src/dialogs_surface.rs | 65 +- crates/ui-egui/src/preselect_tests.rs | 51 + 24 files changed, 2688 insertions(+), 77 deletions(-) create mode 100644 crates/doc/src/format/pending/patch-continuity-and-points.rs create mode 100644 crates/geom/src/fill_general.rs create mode 100644 crates/geom/src/fill_general_tests.rs create mode 100644 crates/kernel/src/fill_general_tests.rs diff --git a/ROADMAP.md b/ROADMAP.md index 824591151..7cd14739d 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -53,6 +53,8 @@ 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; taper handle open), 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 of any shape and number of sides as one face, G0/G1/G2 to the faces beside each edge, through points, #759), 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. Proposed, in order: surface Extrude/Revolve/Sweep/Loft from open and closed curves (#757), Offset surface (#758), Unstitch and Reverse Normal (#766), Delete Face without healing (#768); Extend curved faces and edges (#760), mutual trim and trim by projected curves (#767), Untrim (#761), Thicken every surface kind (#765); Ruled (#762), Boundary surface and curve networks with G0/G1/G2 (#763), Blend surface (#764), sweep guide rails and two-rail sweeps (#771; orientation, twist and end scale done; loft rails #201), fillet between surface bodies (#769); continuity analysis, surface curvature combs and isocurves (#770) | 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), 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), 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 and Interference (overlaps shown red); joints in the timeline and the Browser | in progress | 32 | | M8 | Surface workspace (#772). Done: Patch (sketch regions; edge loops filled G0), 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. Proposed, in order: surface Extrude/Revolve/Sweep/Loft from open and closed curves (#757), Offset surface (#758), Unstitch and Reverse Normal (#766), Delete Face without healing (#768); Extend curved faces and edges (#760), mutual trim and trim by projected curves (#767), Untrim (#761), Thicken every surface kind (#765); Ruled (#762), Boundary surface and curve networks with G0/G1/G2 (#763), Patch with G1/G2 and general loops (#759), Blend surface (#764), sweep guide rails and two-rail sweeps (#771; orientation, twist and end scale done; loft rails #201), fillet between surface bodies (#769); continuity analysis, surface curvature combs and isocurves (#770) | 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), gears, rack and pinion and screws (motion links whose ratio follows picked radii, parameters or a pitch, also inside closed loops), 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), 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, Gear, Rack and Pinion, Screw 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 | diff --git a/assets/locales/de.json b/assets/locales/de.json index bf66c50dd..e87a5cd35 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -8,14 +8,17 @@ "Area": "Fläche", "BROWSER": "BROWSER", "Bends": "Biegungen", + "Boundary": "Begrenzung", "Centre to centre": "Mitte zu Mitte", "Circumference": "Umfang", "Construction": "Konstruktionslinie", + "Continuity": "Stetigkeit", "Copy Error Message": "Fehlermeldung kopieren", "Copy Warning Message": "Warnmeldung kopieren", "Corner Relief": "Eckenentlastung", "Current orthographic view (1:1 mm)": "Aktuelle orthogonale Ansicht (1:1 mm)", "Current perspective view": "Aktuelle perspektivische Ansicht", + "Curvature (G2)": "Krümmung (G2)", "Do not export hidden edges": "Verdeckte Kanten nicht exportieren", "Drive Joint": "Gelenk antreiben", "Edges": "Kanten", @@ -42,7 +45,9 @@ "Notch": "Ausklinkung", "Outside": "Außen", "Overall length": "Gesamtlänge", + "Pass through": "Durch Punkte", "Picked": "Ausgewählte", + "Position (G0)": "Position (G0)", "Profiles/Curves": "Profile/Kurven", "Projection": "Projektion", "RULED SURFACE": "REGELFLÄCHE", @@ -62,6 +67,7 @@ "Sketch geometry and profiles": "Skizzengeometrie und Profile", "Sketch points": "Skizzenpunkte", "Slot width": "Langlochbreite", + "Tangent (G1)": "Tangente (G1)", "Tear": "Reißen", "Thickness Outside": "Dicke außen", "Thin": "Dünnwandig", diff --git a/assets/locales/en.json b/assets/locales/en.json index c4f790a14..1e00199b8 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -34,6 +34,7 @@ "Bend Radius": "Bend Radius", "Bends": "Bends", "Body": "Body", + "Boundary": "Boundary", "Bounding box": "Bounding box", "CSV or JSON: updates existing parameters, adds new ones": "CSV or JSON: updates existing parameters, adds new ones", "Capture All Positions": "Capture All Positions", @@ -56,6 +57,7 @@ "Configuration rules": "Configuration rules", "Construction": "Construction", "Contact": "Contact", + "Continuity": "Continuity", "Copy Error Message": "Copy Error Message", "Copy Warning Message": "Copy Warning Message", "Copy all licences": "Copy all licences", @@ -70,6 +72,7 @@ "Cube": "Cube", "Current orthographic view (1:1 mm)": "Current orthographic view (1:1 mm)", "Current perspective view": "Current perspective view", + "Curvature (G2)": "Curvature (G2)", "Customize Toolbar": "Customize Toolbar", "Delete all": "Delete all", "Delete rule": "Delete rule", @@ -159,6 +162,7 @@ "Outside": "Outside", "Overall length": "Overall length", "Parameter values": "Parameter values", + "Pass through": "Pass through", "Path": "Path", "Per Edge": "Per Edge", "Pick the tool bodies": "Pick the tool bodies", @@ -167,6 +171,7 @@ "Playback": "Playback", "Position": "Position", "Position (0 to 1)": "Position (0 to 1)", + "Position (G0)": "Position (G0)", "Position along the edge, 0 at the start end, 1 at the other": "Position along the edge, 0 at the start end, 1 at the other", "Preview Row": "Preview Row", "Preview leaves the current design unchanged.": "Preview leaves the current design unchanged.", @@ -239,6 +244,7 @@ "Style": "Style", "Suppressed": "Suppressed", "Swap Ends": "Swap Ends", + "Tangent (G1)": "Tangent (G1)", "Tangent Chain": "Tangent Chain", "Tear": "Tear", "The dashed sketch is a saved plane guide. Select a new face to repair the attachment.": "The dashed sketch is a saved plane guide. Select a new face to repair the attachment.", diff --git a/assets/locales/fr.json b/assets/locales/fr.json index df64badb8..bff40076b 100644 --- a/assets/locales/fr.json +++ b/assets/locales/fr.json @@ -32,6 +32,7 @@ "Bend Radius": "Rayon de pliage", "Bends": "Plis", "Body": "Corps", + "Boundary": "Contour", "Bounding box": "Boîte englobante", "CSV or JSON: updates existing parameters, adds new ones": "CSV ou JSON : met à jour les paramètres existants, ajoute les nouveaux", "Capture All Positions": "Capturer toutes les positions", @@ -52,6 +53,7 @@ "Configuration rules": "Règles de configuration", "Construction": "Construction", "Contact": "Contact", + "Continuity": "Continuité", "Copy Error Message": "Copier le message d'erreur", "Copy Warning Message": "Copier le message d'avertissement", "Copy all licences": "Copier toutes les licences", @@ -64,6 +66,7 @@ "Countersink angle": "Angle de la fraisure", "Create Issue — review draft": "Créer un ticket — relire le brouillon", "Cube": "Cube", + "Curvature (G2)": "Courbure (G2)", "Customize Toolbar": "Personnaliser la barre d'outils", "Delete all": "Tout supprimer", "Delete rule": "Supprimer la règle", @@ -143,6 +146,7 @@ "Other side": "Autre côté", "Outside": "Extérieur", "Parameter values": "Valeurs des paramètres", + "Pass through": "Passer par", "Path": "Trajectoire", "Per Edge": "Par arête", "Pick the tool bodies": "Choisir les corps outils", @@ -151,6 +155,7 @@ "Playback": "Lecture", "Position": "Position", "Position (0 to 1)": "Position (0 à 1)", + "Position (G0)": "Position (G0)", "Position along the edge, 0 at the start end, 1 at the other": "Position le long de l'arête : 0 à l'extrémité de départ, 1 à l'autre", "Preview Row": "Aperçu de la ligne", "Preview leaves the current design unchanged.": "L'aperçu ne modifie pas la conception actuelle.", @@ -221,6 +226,7 @@ "Style": "Style", "Suppressed": "Désactivé", "Swap Ends": "Permuter les extrémités", + "Tangent (G1)": "Tangence (G1)", "Tangent Chain": "Chaîne tangente", "Tear": "Déchirure", "The dashed sketch is a saved plane guide. Select a new face to repair the attachment.": "L'esquisse en pointillés est un guide de plan enregistré. Sélectionnez une nouvelle face pour réparer le rattachement.", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index b1ef7be09..df92e4352 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -34,6 +34,7 @@ "Bend Radius": "曲げ半径", "Bends": "曲げ", "Body": "ボディ", + "Boundary": "境界", "Bounding box": "境界ボックス", "CSV or JSON: updates existing parameters, adds new ones": "CSVまたはJSON:既存のパラメータを更新し、新しいパラメータを追加します", "Capture All Positions": "すべての位置をキャプチャ", @@ -56,6 +57,7 @@ "Configuration rules": "構成ルール", "Construction": "コンストラクション", "Contact": "接触", + "Continuity": "連続性", "Copy Error Message": "エラーメッセージをコピー", "Copy Warning Message": "警告メッセージをコピー", "Copy all licences": "すべてのライセンスをコピー", @@ -70,6 +72,7 @@ "Cube": "キューブ", "Current orthographic view (1:1 mm)": "現在の平行投影(実寸・mm)", "Current perspective view": "現在の透視投影", + "Curvature (G2)": "曲率 (G2)", "Customize Toolbar": "ツールバーのカスタマイズ", "Delete all": "すべて削除", "Delete rule": "ルールを削除", @@ -159,6 +162,7 @@ "Outside": "外側", "Overall length": "全長", "Parameter values": "パラメータ値", + "Pass through": "通過点", "Path": "パス", "Per Edge": "エッジごと", "Pick the tool bodies": "ツールボディを選択", @@ -167,6 +171,7 @@ "Playback": "再生", "Position": "位置", "Position (0 to 1)": "位置 (0〜1)", + "Position (G0)": "位置 (G0)", "Position along the edge, 0 at the start end, 1 at the other": "エッジ上の位置(始点が0、終点が1)", "Preview Row": "行をプレビュー", "Preview leaves the current design unchanged.": "プレビューは現在のデザインを変更しません。", @@ -239,6 +244,7 @@ "Style": "スタイル", "Suppressed": "抑制", "Swap Ends": "端点を入れ替え", + "Tangent (G1)": "接線 (G1)", "Tangent Chain": "正接チェーン", "Tear": "引き裂き", "The dashed sketch is a saved plane guide. Select a new face to repair the attachment.": "破線のスケッチは保存された平面ガイドです。新しい面を選択してアタッチメントを修復してください。", diff --git a/assets/locales/ko.json b/assets/locales/ko.json index 611179b57..1ac034ef9 100644 --- a/assets/locales/ko.json +++ b/assets/locales/ko.json @@ -8,14 +8,17 @@ "Area": "면적", "BROWSER": "브라우저", "Bends": "벤딩", + "Boundary": "경계", "Centre to centre": "중심 간", "Circumference": "원주", "Construction": "구성선", + "Continuity": "연속성", "Copy Error Message": "오류 메시지 복사", "Copy Warning Message": "경고 메시지 복사", "Corner Relief": "모서리 릴리프", "Current orthographic view (1:1 mm)": "현재 직교 투영 뷰 (1:1 mm)", "Current perspective view": "현재 원근 투영 뷰", + "Curvature (G2)": "곡률 (G2)", "Do not export hidden edges": "숨겨진 모서리 내보내지 않기", "Drive Joint": "조인트 구동", "Edges": "모서리", @@ -42,7 +45,9 @@ "Notch": "노치", "Outside": "바깥쪽", "Overall length": "전체 길이", + "Pass through": "통과점", "Picked": "선택한 항목", + "Position (G0)": "위치 (G0)", "Profiles/Curves": "프로파일/곡선", "Projection": "투영", "RULED SURFACE": "룰드 서피스", @@ -62,6 +67,7 @@ "Sketch geometry and profiles": "스케치 기하 및 프로파일", "Sketch points": "스케치 점", "Slot width": "슬롯 폭", + "Tangent (G1)": "접선 (G1)", "Tear": "찢김", "Thickness Outside": "바깥쪽 두께", "Thin": "얇은 벽", diff --git a/assets/locales/ru.json b/assets/locales/ru.json index e7d0e2b4a..52fcd9772 100644 --- a/assets/locales/ru.json +++ b/assets/locales/ru.json @@ -28,6 +28,7 @@ "Bend Radius": "Радиус гиба", "Bends": "Гибы", "Body": "Тело", + "Boundary": "Граница", "Bounding box": "Габаритная рамка", "CSV or JSON: updates existing parameters, adds new ones": "CSV или JSON: обновляет существующие параметры, добавляет новые", "Capture All Positions": "Зафиксировать все положения", @@ -48,6 +49,7 @@ "Configuration rules": "Правила конфигурации", "Construction": "Вспомогательная", "Contact": "Контакт", + "Continuity": "Непрерывность", "Copy Error Message": "Скопировать сообщение об ошибке", "Copy Warning Message": "Скопировать предупреждение", "Copy all licences": "Копировать все лицензии", @@ -60,6 +62,7 @@ "Countersink angle": "Угол зенковки", "Create Issue — review draft": "Создать Issue — проверить черновик", "Cube": "Куб", + "Curvature (G2)": "Кривизна (G2)", "Customize Toolbar": "Настроить панель инструментов", "Delete all": "Удалить все", "Delete rule": "Удалить правило", @@ -131,6 +134,7 @@ "Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "Открытая параметрическая 3D CAD на Rust. Лицензия MIT OR Apache-2.0.", "Other side": "Другая сторона", "Parameter values": "Значения параметров", + "Pass through": "Через точки", "Path": "Траектория", "Per Edge": "По каждому ребру", "Pick the tool bodies": "Выберите тела-инструменты", @@ -138,6 +142,7 @@ "Playback": "Воспроизведение", "Position": "Положение", "Position (0 to 1)": "Положение (от 0 до 1)", + "Position (G0)": "Положение (G0)", "Position along the edge, 0 at the start end, 1 at the other": "Положение вдоль ребра: 0 — начало, 1 — конец", "Preview Row": "Строка предпросмотра", "Preview leaves the current design unchanged.": "Предпросмотр не меняет текущий дизайн.", @@ -203,6 +208,7 @@ "Style": "Стиль", "Suppressed": "Подавлено", "Swap Ends": "Поменять концы", + "Tangent (G1)": "Касание (G1)", "Tangent Chain": "Касательная цепочка", "Tear": "Разрыв", "The dashed sketch is a saved plane guide. Select a new face to repair the attachment.": "Пунктирный эскиз — сохранённая подсказка плоскости. Выберите новую грань, чтобы восстановить привязку.", diff --git a/assets/locales/uk.json b/assets/locales/uk.json index 15b0e1b40..f5c5d0155 100644 --- a/assets/locales/uk.json +++ b/assets/locales/uk.json @@ -32,6 +32,7 @@ "Bend Radius": "Радіус згину", "Bends": "Згини", "Body": "Тіло", + "Boundary": "Межа", "Bounding box": "Обмежувальна рамка", "CSV or JSON: updates existing parameters, adds new ones": "CSV або JSON: оновлює наявні параметри, додає нові", "Capture All Positions": "Зафіксувати всі положення", @@ -52,6 +53,7 @@ "Configuration rules": "Правила конфігурації", "Construction": "Конструкційна", "Contact": "Контакт", + "Continuity": "Неперервність", "Copy all licences": "Копіювати всі ліцензії", "Copy diagnostic information": "Копіювати діагностичну інформацію", "Copy report": "Копіювати звіт", @@ -62,6 +64,7 @@ "Countersink angle": "Кут зенкування", "Create Issue — review draft": "Створити повідомлення про проблему — перегляд чернетки", "Cube": "Куб", + "Curvature (G2)": "Кривина (G2)", "Customize Toolbar": "Налаштувати панель інструментів", "Delete all": "Видалити все", "Delete rule": "Видалити правило", @@ -135,6 +138,7 @@ "Other side": "Інший бік", "Outside": "Назовні", "Parameter values": "Значення параметрів", + "Pass through": "Через точки", "Path": "Траєкторія", "Per Edge": "На кожне ребро", "Pick the tool bodies": "Виберіть тіла інструмента", @@ -142,6 +146,7 @@ "Playback": "Відтворення", "Position": "Положення", "Position (0 to 1)": "Положення (від 0 до 1)", + "Position (G0)": "Положення (G0)", "Position along the edge, 0 at the start end, 1 at the other": "Положення вздовж ребра: 0 на початку, 1 на іншому кінці", "Preview Row": "Рядок перегляду", "Preview leaves the current design unchanged.": "Попередній перегляд не змінює поточний проєкт.", @@ -209,6 +214,7 @@ "Style": "Стиль", "Suppressed": "Придушено", "Swap Ends": "Поміняти кінці місцями", + "Tangent (G1)": "Дотик (G1)", "Tangent Chain": "Дотичний ланцюг", "Tear": "Розрив", "The dashed sketch is a saved plane guide. Select a new face to repair the attachment.": "Штриховий ескіз — це збережений орієнтир площини. Виберіть нову грань, щоб відновити прив'язку.", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index ed6d0c8d5..1481b9701 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -34,6 +34,7 @@ "Bend Radius": "折弯半径", "Bends": "折弯", "Body": "实体", + "Boundary": "边界", "Bounding box": "边界框", "CSV or JSON: updates existing parameters, adds new ones": "CSV 或 JSON:更新现有参数、添加新参数", "Capture All Positions": "捕获所有位置", @@ -56,6 +57,7 @@ "Configuration rules": "配置规则", "Construction": "构造", "Contact": "接触", + "Continuity": "连续性", "Copy Error Message": "复制错误消息", "Copy Warning Message": "复制警告消息", "Copy all licences": "复制所有许可证", @@ -70,6 +72,7 @@ "Cube": "立方体", "Current orthographic view (1:1 mm)": "当前正交视图(1:1毫米)", "Current perspective view": "当前透视视图", + "Curvature (G2)": "曲率 (G2)", "Customize Toolbar": "自定义工具栏", "Delete all": "全部删除", "Delete rule": "删除规则", @@ -159,6 +162,7 @@ "Outside": "外侧", "Overall length": "总长", "Parameter values": "参数值", + "Pass through": "通过点", "Path": "路径", "Per Edge": "每条边", "Pick the tool bodies": "选择工具实体", @@ -167,6 +171,7 @@ "Playback": "播放", "Position": "位置", "Position (0 to 1)": "位置(0 到 1)", + "Position (G0)": "位置 (G0)", "Position along the edge, 0 at the start end, 1 at the other": "沿边的位置,起点端为 0,另一端为 1", "Preview Row": "预览行", "Preview leaves the current design unchanged.": "预览不会更改当前设计。", @@ -239,6 +244,7 @@ "Style": "样式", "Suppressed": "已抑制", "Swap Ends": "交换端点", + "Tangent (G1)": "相切 (G1)", "Tangent Chain": "相切链", "Tear": "撕裂", "The dashed sketch is a saved plane guide. Select a new face to repair the attachment.": "虚线草图是已保存的平面引导。选择一个新面以修复附着。", diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 233c0a2e8..3aeb554c2 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -1276,6 +1276,14 @@ pub enum FeatureKind { /// exact plane whatever this says). #[serde(default, skip_serializing_if = "is_zero")] crown: f64, + /// How a patch on edges meets the faces beside its loop (G0 everywhere by default, and + /// then not saved). + #[serde(default, skip_serializing_if = "PatchContinuity::is_g0")] + continuity: PatchContinuity, + /// Points a patch on edges passes through. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + #[walk(pos)] + points: Vec, }, /// Surface bodies sewn along shared edges into the first one (a solid when they close). Stitch { @@ -1666,6 +1674,45 @@ pub struct BlendSide { pub edges: Vec, } +/// How a patch on a loop of edges meets the faces beside the loop: every edge with `all`, but the +/// edges picked in `edges` with their own. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, solidcraft_derive::Walk)] +pub struct PatchContinuity { + #[serde(default = "patch_g0", skip_serializing_if = "is_g0")] + pub all: Continuity, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub edges: Vec, +} + +/// One edge of a patch's loop (a point on it) and how the patch meets the face beside it. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, solidcraft_derive::Walk)] +pub struct EdgeContinuity { + #[walk(pos)] + pub edge: Vec3, + pub g: Continuity, +} + +impl Default for PatchContinuity { + fn default() -> PatchContinuity { + PatchContinuity { all: Continuity::G0, edges: Vec::new() } + } +} + +impl PatchContinuity { + /// G0 everywhere: the patch only meets its edges. + pub fn is_g0(&self) -> bool { + self.all == Continuity::G0 && self.edges.iter().all(|e| e.g == Continuity::G0) + } +} + +fn patch_g0() -> Continuity { + Continuity::G0 +} + +fn is_g0(g: &Continuity) -> bool { + *g == Continuity::G0 +} + /// The continuity a blend repeats by default: the tangent plane on both sides. fn blend_orders() -> [Continuity; 2] { [Continuity::G1, Continuity::G1] diff --git a/crates/doc/src/eval_surface.rs b/crates/doc/src/eval_surface.rs index 41d0aa7b2..09969eef8 100644 --- a/crates/doc/src/eval_surface.rs +++ b/crates/doc/src/eval_surface.rs @@ -8,7 +8,7 @@ use solidcraft_geom::Seg2; pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, st: &mut ModelState, warning: &mut Option) -> Result<()> { match &f.kind { - FeatureKind::Patch { sketch, profiles, body, edges, crown } => { + FeatureKind::Patch { sketch, profiles, body, edges, crown, continuity, points } => { let mut made = Vec::new(); if let Some(sk) = sketch { let ss = st.sketch(*sk).ok_or_else(|| DocError::Unknown(format!("sketch {sk} (it must come earlier in the timeline)")))?; @@ -20,7 +20,13 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, if !edges.is_empty() { let i = body_at(st, body, edges)?; let b = st.bodies.get(i).ok_or_else(|| DocError::Invalid("body".into()))?; - made.push(kernel::patch_edges_crowned(&b.body, edges, *crown)?); + let spec = kernel::PatchSpec { + continuity: continuity.all, + edges: continuity.edges.iter().map(|e| (e.edge, e.g)).collect(), + points: points.clone(), + crown: *crown, + }; + made.push(kernel::patch_edges_with(&b.body, edges, &spec)?); } if made.is_empty() { return Err(DocError::Invalid("a patch needs a sketch region or a loop of edges".into())); diff --git a/crates/doc/src/format/pending/patch-continuity-and-points.rs b/crates/doc/src/format/pending/patch-continuity-and-points.rs new file mode 100644 index 000000000..c93846460 --- /dev/null +++ b/crates/doc/src/format/pending/patch-continuity-and-points.rs @@ -0,0 +1,6 @@ +//! A `Patch` on edges can carry `continuity` (`all`: `g0`, `g1` or `g2`, and `edges`: +//! `[{edge: [x, y, z], g}]` for edges met otherwise; G0 everywhere when absent, and then not +//! saved) and `points` it passes through (none when absent). Older designs need no +//! transformation: a patch without them fills as it always did; a loop that is not a height field +//! over its plane, which 0.13.0 refused, now fills with one face. 0.13.x asks for an update +//! instead of dropping them. diff --git a/crates/engine/src/cmd/surface.rs b/crates/engine/src/cmd/surface.rs index 33c5aa2de..a2e9deac0 100644 --- a/crates/engine/src/cmd/surface.rs +++ b/crates/engine/src/cmd/surface.rs @@ -2,7 +2,9 @@ //! solids), and the planned surface toolset (`planned!`: registered, not built yet). use serde_json::Value; -use solidcraft_doc::{BlendSide, ExtendMode, ExtendTo, FaceAt, FeatureKind, PlaneRef, ProfileSel, RuledCorners, RuledMode, expr::Kind}; +use solidcraft_doc::{ + BlendSide, EdgeContinuity, ExtendMode, ExtendTo, FaceAt, FeatureKind, PatchContinuity, PlaneRef, ProfileSel, RuledCorners, RuledMode, expr::Kind, +}; use solidcraft_kernel::Continuity; use super::CommandSpec; @@ -14,7 +16,7 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("surface.patch", "Patch", patch) .at("SURFACE", "CREATE") .icon("patch") - .params("sketch?: id|name and profiles? (planar patches of sketch regions) | edges: [[x,y,z]] (points on a closed loop of a body's edges: one face on them, planar when the loop is, else a smooth B-spline surface) and body?; crown?: number −0.9…3 (default 0: only a fitted patch, whose middle becomes fuller by this many times the loop's size — the bump vanishes on the loop, so the face still meets the picked edges; a loop that is planar is the exact plane whatever the crown); name?, body_name?"), + .params("sketch?: id|name and profiles? (planar patches of sketch regions) | edges: [[x,y,z]] (points on a closed loop of a body's edges: one face on them, planar when the loop is, else a smooth B-spline surface) and body?; continuity?: g0|g1|g2 (edges only, default g0: how the patch meets the faces beside the loop — g1 their tangent planes, g2 also their curvature across the edges) or [{edge: [x,y,z], g: g0|g1|g2}] (those edges so, the rest g0) or {all, edges}; points?: [[x,y,z]] (edges only, up to 64: points the patch passes through); crown?: number −0.9…3 (default 0: only a fitted patch, whose middle becomes fuller by this many times the loop's size — the bump vanishes on the loop, so the face still meets the picked edges and the continuity across them; a loop that is planar and g0 is the exact plane whatever the crown; with points, crown needs a g1 or g2 edge); name?, body_name?"), CommandSpec::new("surface.stitch", "Stitch", stitch) .at("SURFACE", "MODIFY") .icon("stitch") @@ -84,24 +86,91 @@ pub static COMMANDS: &[CommandSpec] = &[ fn patch(s: &mut Session, p: &Value) -> Result { let cmd = "surface.patch"; let crown = crown_param(p, cmd)?; + let continuity = patch_continuity(p, cmd)?; + let points = patch_points(p, cmd)?; let edges: Vec = p.get("edges").and_then(Value::as_array).map(|a| a.iter().filter_map(vec3).collect()).unwrap_or_default(); let mut v = if !edges.is_empty() { if edges.len() > 10_000 { return Err(bad(cmd, "too many edges")); } let body = str_(p, "body").map(str::to_string); - add_feature(s, p, FeatureKind::Patch { sketch: None, profiles: ProfileSel::All, body, edges, crown })? + add_feature(s, p, FeatureKind::Patch { sketch: None, profiles: ProfileSel::All, body, edges, crown, continuity: continuity.clone(), points })? } else { + if !continuity.is_g0() || !points.is_empty() { + return Err(bad(cmd, "`continuity` and `points` are for a patch on a loop of edges")); + } let sketch = feature_sketch(s, p, cmd)?; let profiles = profiles(p, cmd)?; - add_feature(s, p, FeatureKind::Patch { sketch: Some(sketch), profiles, body: None, edges: Vec::new(), crown })? + let kind = FeatureKind::Patch { + sketch: Some(sketch), + profiles, + body: None, + edges: Vec::new(), + crown, + continuity: PatchContinuity::default(), + points, + }; + add_feature(s, p, kind)? }; if let Some(o) = v.as_object_mut() { o.insert("crown".into(), serde_json::json!(crown)); + o.insert("continuity".into(), serde_json::to_value(&continuity).unwrap_or(Value::Null)); } Ok(v) } +/// A continuity word for a patch: g0, g1 or g2 (a patch does not hold g3). +fn patch_order(v: Option<&Value>, cmd: &str) -> Result { + match v.and_then(Value::as_str).and_then(Continuity::parse) { + Some(g) if g != Continuity::G3 => Ok(g), + _ => Err(bad(cmd, "a patch's continuity is g0, g1 or g2")), + } +} + +/// The patch's `continuity`: one word for every edge, a list of `{edge, g}` for some edges (the +/// rest g0), or `{all, edges}`. +fn patch_continuity(p: &Value, cmd: &str) -> Result { + let edges = |list: &Value| -> Result> { + let list = list.as_array().ok_or_else(|| bad(cmd, "`continuity` edges must be a list of {edge: [x,y,z], g}"))?; + if list.len() > 10_000 { + return Err(bad(cmd, "`continuity` lists at most 10000 edges")); + } + list.iter() + .map(|e| { + let edge = e.get("edge").and_then(vec3).ok_or_else(|| bad(cmd, "a `continuity` entry's `edge` must be a point [x,y,z]"))?; + Ok(EdgeContinuity { edge, g: patch_order(e.get("g"), cmd)? }) + }) + .collect() + }; + match p.get("continuity") { + None => Ok(PatchContinuity::default()), + Some(v) if v.is_string() => Ok(PatchContinuity { all: patch_order(Some(v), cmd)?, edges: Vec::new() }), + Some(v) if v.is_array() => Ok(PatchContinuity { all: Continuity::G0, edges: edges(v)? }), + Some(v) if v.is_object() => { + let all = match v.get("all") { + None => Continuity::G0, + some => patch_order(some, cmd)?, + }; + let edges = match v.get("edges") { + None => Vec::new(), + Some(list) => edges(list)?, + }; + Ok(PatchContinuity { all, edges }) + } + Some(_) => Err(bad(cmd, "`continuity` must be g0, g1 or g2, or a list of {edge, g}")), + } +} + +/// The points a patch passes through (at most 64, each a finite point). +fn patch_points(p: &Value, cmd: &str) -> Result> { + let Some(v) = p.get("points") else { return Ok(Vec::new()) }; + let list = v + .as_array() + .filter(|a| a.len() <= solidcraft_geom::fill_general::MAX_FILL_POINTS) + .ok_or_else(|| bad(cmd, "`points` must list at most 64 points [x,y,z]"))?; + list.iter().map(|q| vec3(q).filter(|q| q.is_finite()).ok_or_else(|| bad(cmd, "a patch point must be a finite [x,y,z]"))).collect() +} + /// The patch's `crown`: how full a fitted patch's middle is made, -0.9…3 (default 0). A hostile /// value (NaN, infinity, out of range, a string) is refused. fn crown_param(p: &Value, cmd: &str) -> Result { @@ -1329,4 +1398,69 @@ mod tests { .is_err() ); } + + /// 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(); + run(&mut s, "solid.cylinder", json!({"radius": 10, "height": 30, "body_name": "Tube"})); + run(&mut s, "surface.unstitch", json!({"body": "Tube", "faces": [[0, 0, 30]]})); + let rim: Vec = (0..8).map(|k| f64::from(k) * 0.785).map(|a| json!([10.0 * a.cos(), 10.0 * a.sin(), 30.0])).collect(); + (s, json!(rim)) + } + + /// `surface.patch continuity` and `points`: the tube's open end capped G1, per-edge + /// continuity, a point the cap passes through, all saved with the design and read back; + /// hostile values refused. + #[test] + fn patch_continuity_and_points_cap_a_tube() { + // A coarse mesh is enough to tell the patches apart (measuring a fitted face's area + // exactly tessellates it finely). + let mesh = |s: &Session, name: &str| s.world_state().body(name).unwrap().body.tessellate(0.05).unwrap(); + let (mut s, rim) = open_tube(); + let reply = run(&mut s, "surface.patch", json!({"edges": rim, "body": "Tube", "continuity": "g1", "body_name": "Cap"})); + assert_eq!(reply["continuity"], json!({"all": "g1"}), "{reply}"); + // A dome over the rim, not the flat disc a G0 patch of a planar rim is. + let disc = std::f64::consts::PI * 100.0; + let dome = mesh(&s, "Cap").measure().area; + assert!(dome > disc * 1.2, "a dome, not the disc: {dome}"); + // Through a point 8 above the rim, G1 to the wall: the cap reaches it. + run(&mut s, "surface.patch", json!({"edges": rim, "body": "Tube", "continuity": {"all": "g1"}, "points": [[0, 0, 38]], "body_name": "Tall"})); + let top = mesh(&s, "Tall").bounds().max.z; + assert!(top >= 38.0 - 1e-2, "the cap passes through the point: top {top}"); + // One edge G2, the rest G0 (the list form). + let first = rim[0].clone(); + let reply = + run(&mut s, "surface.patch", json!({"edges": rim, "body": "Tube", "continuity": [{"edge": first, "g": "g2"}], "body_name": "Mixed"})); + assert_eq!(reply["continuity"]["edges"][0]["g"], json!("g2"), "{reply}"); + // Saved and read back: the same patches. + let back = solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap(); + let reopened = Session::new(back); + for name in ["Cap", "Tall", "Mixed"] { + let (a, b) = (mesh(&s, name).positions, mesh(&reopened, name).positions); + assert_eq!(a, b, "{name}: the same surface read back"); + } + assert!(s.doc.to_json().contains("\"continuity\""), "the continuity is saved"); + // Hostile and misplaced values. + for (key, v) in [ + ("continuity", json!("g3")), + ("continuity", json!("smooth")), + ("continuity", json!(5)), + ("continuity", json!([{"edge": "here", "g": "g1"}])), + ("continuity", json!([{"edge": [f64::INFINITY, 0, 0], "g": "g1"}])), + ("continuity", json!({"all": "g9"})), + ("continuity", json!([{"edge": [0, 0, 0], "g": "g1"}])), + ("points", json!([[0, 0, f64::NAN]])), + ("points", json!("up")), + ("points", json!(vec![[0, 0, 35]; 65])), + ("points", json!([[100, 0, 30]])), + ] { + let mut p = json!({"edges": rim, "body": "Tube"}); + p[key] = v.clone(); + assert!(s.execute("surface.patch", &p).is_err(), "accepted {key}: {v}"); + } + run(&mut s, "sketch.create", json!({"plane": "XY"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [30, 0], "p1": [40, 10]})); + let sketch_patch = json!({"sketch": 1, "continuity": "g1"}); + assert!(s.execute("surface.patch", &sketch_patch).is_err(), "continuity on a sketch patch"); + } } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 000b8b583..02ff35551 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -779,6 +779,8 @@ fn hostile_params_never_panic() { "orientation", "twist", "scale", + "continuity", + "crown", ]; // 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/geom/src/fill.rs b/crates/geom/src/fill.rs index 3122982bc..7169a1856 100644 --- a/crates/geom/src/fill.rs +++ b/crates/geom/src/fill.rs @@ -33,7 +33,7 @@ const GAUSS4: [(f64, f64); 4] = [ (0.861_136_311_594_052_6, 0.347_854_845_137_453_8), ]; /// The smoothness term's weight per fitted point (see [`fill_loop`]). -const SMOOTHNESS: f64 = 1e-7; +pub(crate) const SMOOTHNESS: f64 = 1e-7; /// A loop step shorter than this fraction of its length in space, seen along the normal, runs /// along the normal (steeper than about 87° from the plane). const MIN_STEP_SLOPE: f64 = 0.05; @@ -289,13 +289,32 @@ fn fit_once(fit: &[Vec3], all: &[Vec3], tol: f64, crown: f64) -> SplineResult SplineResult<(NurbsSurface, usize, f64)> { + if crown == 0.0 { + return Ok((surface, 0, 0.0)); + } + if !normal.is_finite() { + return invalid("the loop's extent is not finite"); + } + crown_fill_along(surface, uv, crown, &|_| Some(normal), MAX_FILL_SPANS) +} + +/// [`crown_fill`] moving each control point along `along(ξ, η)` (at its Greville point, the mean +/// of its knots each way) rather than one normal: what a fill that is not a height field takes, +/// with its own normal there. Its net may be refined up to `max_spans` each way. +pub(crate) fn crown_fill_along( + surface: NurbsSurface, + uv: &[[f64; 2]], + crown: f64, + along: &dyn Fn([f64; 2]) -> Option, + max_spans: usize, +) -> SplineResult<(NurbsSurface, usize, f64)> { if crown == 0.0 { return Ok((surface, 0, 0.0)); } let gap = loop_gap(uv); let mut base = surface; loop { - if let Some((crowned, points)) = crown_net(&base, uv, gap, crown, normal)? { + if let Some((crowned, points)) = crown_net(&base, uv, gap, crown, along)? { let mut drift = 0.0f64; for q in uv { if let (Ok(a), Ok(b)) = (base.eval(q[0], q[1]), crowned.eval(q[0], q[1])) { @@ -309,11 +328,11 @@ fn crown_fill(surface: NurbsSurface, uv: &[[f64; 2]], crown: f64, normal: Vec3) } // No room inside the loop yet: halve the cells (the surface itself does not change). let spans = [0, 1].map(|d| base.count()[d].saturating_sub(3)); - if spans[0] >= MAX_FILL_SPANS && spans[1] >= MAX_FILL_SPANS { + if spans[0] >= max_spans && spans[1] >= max_spans { return Err(SplineError::Unsupported("crowning a patch whose loop leaves no room inside it".into())); } for (d, &s) in spans.iter().enumerate() { - if s < MAX_FILL_SPANS { + if s < max_spans { base = subdivide(&base, d)?; } } @@ -324,13 +343,19 @@ fn crown_fill(surface: NurbsSurface, uv: &[[f64; 2]], crown: f64, normal: Vec3) /// loop takes `crown · size · B(ξ, η)`, `B` the bubble's blossom at the point's knots (so the /// surface between the perturbed points is exactly the bubble, not a fit of it) and `size` the /// box's diagonal. `None` when the net has no such point. -fn crown_net(base: &NurbsSurface, uv: &[[f64; 2]], gap: [f64; 2], crown: f64, normal: Vec3) -> SplineResult> { +fn crown_net( + base: &NurbsSurface, + uv: &[[f64; 2]], + gap: [f64; 2], + crown: f64, + along: &dyn Fn([f64; 2]) -> Option, +) -> SplineResult> { let [cu, cv] = base.count(); let degree = base.degree(); let knots = base.knots(); let domain = base.domain(); let size = (domain[0][1] - domain[0][0]).hypot(domain[1][1] - domain[1][0]); - if !(size > 0.0 && size.is_finite() && normal.is_finite()) { + if !(size > 0.0 && size.is_finite()) { return invalid("the loop's extent is not finite"); } // The bubble `4·s·(1−s)` per direction, as a quadratic in the plane coordinate. @@ -351,6 +376,8 @@ fn crown_net(base: &NurbsSurface, uv: &[[f64; 2]], gap: [f64; 2], crown: f64, no continue; } let bump = crown * size * blossom(qu, u_knots) * blossom(qv, v_knots); + let mean = |t: [f64; 3]| (t[0] + t[1] + t[2]) / 3.0; + let Some(normal) = along([mean(u_knots), mean(v_knots)]).filter(|n| n.is_finite()) else { continue }; let Some(slot) = ctrl.get_mut(j * cu + i) else { continue }; let h = *slot; let Some(p) = h.project() else { continue }; @@ -431,7 +458,7 @@ fn loop_gap(uv: &[[f64; 2]]) -> [f64; 2] { } /// Whether `p` is inside the closed loop `uv` (ray casting). -fn inside_loop(p: [f64; 2], uv: &[[f64; 2]]) -> bool { +pub(crate) fn inside_loop(p: [f64; 2], uv: &[[f64; 2]]) -> bool { let m = uv.len(); let mut inside = false; for k in 0..m { @@ -512,7 +539,7 @@ fn check_projectable(points: &[Vec3], uv: &[[f64; 2]]) -> SplineResult<()> { } /// Whether the closed segments `ab` and `cd` share a point. -fn segments_meet(a: [f64; 2], b: [f64; 2], c: [f64; 2], d: [f64; 2]) -> bool { +pub(crate) fn segments_meet(a: [f64; 2], b: [f64; 2], c: [f64; 2], d: [f64; 2]) -> bool { let orient = |p: [f64; 2], q: [f64; 2], r: [f64; 2]| (q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0]); let within = |p: [f64; 2], q: [f64; 2], r: [f64; 2]| r[0] >= p[0].min(q[0]) && r[0] <= p[0].max(q[0]) && r[1] >= p[1].min(q[1]) && r[1] <= p[1].max(q[1]); @@ -525,9 +552,9 @@ fn segments_meet(a: [f64; 2], b: [f64; 2], c: [f64; 2], d: [f64; 2]) -> bool { /// A bicubic height field's grid: uniform clamped knots over `[lo, hi]` in each direction, /// `count` control points along each. -struct Grid { - knots: [Vec; 2], - count: [usize; 2], +pub(crate) struct Grid { + pub(crate) knots: [Vec; 2], + pub(crate) count: [usize; 2], } impl LoopFill { @@ -540,7 +567,7 @@ impl LoopFill { } impl Grid { - fn new(spans: [usize; 2], lo: [f64; 2], hi: [f64; 2]) -> Grid { + pub(crate) fn new(spans: [usize; 2], lo: [f64; 2], hi: [f64; 2]) -> Grid { let knots = [0, 1].map(|d| { let (a, b, s) = (lo[d], hi[d], spans[d]); let mut k = vec![a; 4]; @@ -552,7 +579,7 @@ impl Grid { } /// The length of one span in direction `d`. - fn cell(&self, d: usize) -> f64 { + pub(crate) fn cell(&self, d: usize) -> f64 { let (Some(k), Some(&c)) = (self.knots.get(d), self.count.get(d)) else { return 0.0 }; (k.last().copied().unwrap_or(0.0) - k.first().copied().unwrap_or(0.0)) / (c - 3) as f64 } @@ -564,7 +591,7 @@ impl Grid { /// The four non-zero basis functions' `r`-th derivatives and the first index, at `x` in /// direction `d`. - fn basis_derivative(&self, d: usize, x: f64, r: usize) -> Option<(usize, [f64; 4])> { + pub(crate) fn basis_derivative(&self, d: usize, x: f64, r: usize) -> Option<(usize, [f64; 4])> { let kn = self.knots.get(d)?; let x = x.clamp(*kn.first()?, *kn.last()?); let span = find_span(kn, 3, *self.count.get(d)?, x)?; @@ -622,6 +649,22 @@ impl Grid { // against the data term (squared heights) alike at any size. Each term is a product of // one-direction Gram matrices of the basis functions' derivatives. let lambda = SMOOTHNESS * fitted as f64 / n as f64 * self.cell(0) * self.cell(1); + self.add_energy(&mut band, lambda); + band.solve(rhs) + } + + /// Add `lambda` times the thin-plate energy `∫∫ h_uu² + 2·h_uv² + h_vv²` over the grid's box + /// to the normal equations `band` (unknowns i fastest): each term is a product of + /// one-direction Gram matrices of the basis functions' derivatives. + pub(crate) fn add_energy(&self, band: &mut Band, lambda: f64) { + let cu = self.count[0]; + self.energy(lambda, &mut |(i, j), (k, l), e| band.add(j * cu + i, l * cu + k, e)); + } + + /// The entries of `lambda` times the thin-plate energy's matrix (see [`Grid::add_energy`]), + /// control point `(i, j)` against `(k, l)`, for every pair whose supports overlap. + pub(crate) fn energy(&self, lambda: f64, add: &mut dyn FnMut((usize, usize), (usize, usize), f64)) { + let [cu, cv] = self.count; let gram = |d: usize, r: usize| -> Vec { let c = self.count.get(d).copied().unwrap_or(0); let mut g = vec![0.0; c * c]; @@ -652,16 +695,14 @@ impl Grid { }; for j in 0..cv { for i in 0..cu { - let r = j * cu + i; for l in j.saturating_sub(3)..(j + 4).min(cv) { for k in i.saturating_sub(3)..(i + 4).min(cu) { let e: f64 = ENERGY.iter().map(|&(ru, rv, w)| w * g(0, ru, i, k) * g(1, rv, j, l)).sum(); - band.add(r, l * cu + k, lambda * e); + add((i, j), (k, l), lambda * e); } } } } - band.solve(rhs) } /// The surface of the net `heights` over the plane `o`, `x`, `y`, `n`: control point `(i, j)` @@ -680,14 +721,15 @@ impl Grid { } /// A symmetric banded matrix: the upper band, row `r` holding columns `r ..= r + bw`. -struct Band { +#[derive(Clone)] +pub(crate) struct Band { n: usize, bw: usize, a: Vec, } impl Band { - fn new(n: usize, bw: usize) -> Band { + pub(crate) fn new(n: usize, bw: usize) -> Band { Band { n, bw, a: vec![0.0; n * (bw + 1)] } } fn index(&self, r: usize, s: usize) -> Option { @@ -704,7 +746,7 @@ impl Band { } /// Add `v` at `(r, s)` with `r ≤ s` (the lower half is the same by symmetry: callers adding /// a full outer product reach each stored entry once through `r ≤ s`). - fn add(&mut self, r: usize, s: usize, v: f64) { + pub(crate) fn add(&mut self, r: usize, s: usize, v: f64) { if r <= s && let Some(x) = self.index(r, s).and_then(|i| self.a.get_mut(i)) { @@ -713,7 +755,13 @@ impl Band { } /// Solve `A·x = b` by banded Cholesky factorisation `A = Uᵀ·U`; an error when `A` is not /// positive definite. - fn solve(mut self, mut b: Vec) -> SplineResult> { + fn solve(self, b: Vec) -> SplineResult> { + self.factor()?.substitute(b) + } + + /// The Cholesky factor `U` of `A = Uᵀ·U`, in place; an error when `A` is not positive + /// definite. + pub(crate) fn factor(mut self) -> SplineResult { let (n, bw) = (self.n, self.bw); for r in 0..n { let mut d = self.get(r, r); @@ -734,6 +782,48 @@ impl Band { self.set(r, s, v / d); } } + Ok(self) + } + + /// [`Band::factor`] by rows: once row `r` of `U` is known, the rows below it within the band + /// are updated from it at once (right-looking), which walks memory row by row instead of down + /// columns. The same factor, to rounding; what the general fill, whose bands are wide, uses. + pub(crate) fn factor_rows(mut self) -> SplineResult { + let (n, bw) = (self.n, self.bw); + let w = bw + 1; + let mut row = vec![0.0; w]; + for r in 0..n { + let Some(here) = self.a.get_mut(r * w..r * w + w) else { return invalid("the fit's equations are out of shape") }; + let d = here.first().copied().unwrap_or(0.0); + if !(d > 0.0) { + return invalid("the fit's equations are singular"); + } + let d = d.sqrt(); + for (k, x) in here.iter_mut().enumerate() { + *x = if k == 0 { d } else { *x / d }; + } + row.copy_from_slice(here); + let end = (r + bw + 1).min(n); + for s in r + 1..end { + let us = row.get(s - r).copied().unwrap_or(0.0); + if us == 0.0 { + continue; + } + let len = end - s; + let (Some(dst), Some(src)) = (self.a.get_mut(s * w..s * w + len), row.get(s - r..s - r + len)) else { + return invalid("the fit's equations are out of shape"); + }; + for (x, y) in dst.iter_mut().zip(src) { + *x -= us * y; + } + } + } + Ok(self) + } + + /// Solve `Uᵀ·U·x = b` with a factor from [`Band::factor`]. + pub(crate) fn substitute(&self, mut b: Vec) -> SplineResult> { + let (n, bw) = (self.n, self.bw); // Uᵀ·y = b, then U·x = y. for r in 0..n { let mut v = b.get(r).copied().unwrap_or(0.0); diff --git a/crates/geom/src/fill_general.rs b/crates/geom/src/fill_general.rs new file mode 100644 index 000000000..e6f5da582 --- /dev/null +++ b/crates/geom/src/fill_general.rs @@ -0,0 +1,1150 @@ +//! Filling a closed loop with one surface that meets the faces beside the loop with a chosen +//! continuity (G0, G1 or G2 per station) and passes through given points, for any loop that +//! turns round once: loops that are not a height field over any plane, and loops of any number of +//! sides, are filled whole. +//! +//! The formulation: +//! +//! - **The parameter domain is developed from the loop itself**, not projected. The loop is +//! walked as a polygon of its samples; each step keeps its length, and each turn between steps +//! is split, against the patch's expected normal there (`up`), into its part about that normal +//! (the turn *in* the patch: the boundary's geodesic turn, signed, so a reflex corner stays +//! reflex) and the rest (the turn the boundary makes *with* the patch bending under it, which a +//! plane cannot show). By Gauss–Bonnet the in-patch turns of a developable patch add up to a +//! full turn; a curved patch makes up the difference with its curvature, so a shortfall is given +//! back in proportion to the bending turns (a cap over a round rim, whose rim does not turn in +//! its neighbours' tangent planes at all, develops to the circle), and a saddle's excess comes +//! off the smooth stretches, so corners keep their angles. The headings then close exactly, and +//! the small gap left in position is spread along the steps by length. A domain that crosses +//! itself is refused. The domain's steps are as long as the loop's, so the parameters are +//! millimetres along the boundary. (`up` is the neighbour's normal at a G1/G2 station; at a G0 +//! station, the loop's tangent × the neighbour's leave direction tilted towards the loop's mean +//! plane.) +//! - **The surface is a bicubic B-spline over the domain's box** whose control points minimise, +//! by least squares, the misfit to the boundary conditions plus a vanishing multiple of the +//! thin-plate energy `∫∫ |S_uu|² + 2|S_uv|² + |S_vv|²` (which only decides what the conditions +//! leave free): +//! - G0, every station: the position. +//! - G1: `n·∂S/∂ν = 0` (`ν` the domain's inward normal, `n` the neighbour's normal): the +//! cross-boundary derivative lies in the neighbour's tangent plane, which with the boundary +//! tangent makes the normals agree; plus weak Hermite rows `∂S/∂ν = s·w` (`w` the direction +//! the neighbour leaves in across the edge, `s` the boundary's own speed), which say that the +//! patch leaves into itself rather than folding back over the neighbour, and about how fast, +//! but give way where full Hermite data cannot all hold (it is consistent only with a map +//! exactly conformal at the boundary, which a curved patch's is not). +//! - G2: `n·∂²S/∂ν² = (∂S/∂ν·w)²·κ` (`κ` the neighbour's normal curvature along `w`, read off +//! the bridge's frames): the patch's normal curvature across the edge is the neighbour's. The +//! speed is the fit's own, so the row is solved again with the last solution's speed. +//! +//! Without G1/G2 the three coordinates are fitted apart on one shared matrix; with them, together +//! (the geometric rows couple them), numbered so the band stays narrow. At corners the two +//! sides' conditions overdetermine the surface: see [`Near`] and [`fades`]. The face is bounded +//! by the body's own edges, so the surface only has to pass within the tolerance of them. +//! - **Points the patch must pass through** are located on the fitted surface (nearest point, +//! inside the domain), added as position data there, and the fit and the location are repeated +//! — Hoschek's parameter correction — so each point ends on the surface. +//! - **Grids** of 4 to [`MAX_GENERAL_SPANS`] spans across the domain's longer side are tried in +//! turn; the first whose surface is within the tolerance of every station, whose normals are +//! within the angle tolerance of the neighbours' at every G1 or G2 station (away from corners +//! where the neighbours' tangent planes disagree: no surface can meet both there), that passes +//! through the points, and that neither folds nor pinches inside the loop, is the fill. When a +//! grid needs more stations than it has, the sampling doubles. +//! - **A crown** fills the middle out along the surface's own normals, on control points clear of +//! the loop, so it moves neither the loop nor the conditions across it. + +use crate::Vec3; +use crate::bspline::{HPoint, NurbsSurface, SplineError, SplineResult, invalid}; +use crate::fill::{Band, Grid, MAX_LOOP_POINTS, SMOOTHNESS, inside_loop, segments_meet}; + +/// Most spans of the surface along the domain's longer side. +pub const MAX_GENERAL_SPANS: usize = 64; +/// Most points a patch can be asked to pass through. +pub const MAX_FILL_POINTS: usize = 64; +/// Fewest spans along the domain's longer side (the first grid tried). +const MIN_SPANS: usize = 4; +/// A turn between two loop steps sharper than this (radians) folds the loop back on itself. +const FOLD_TURN: f64 = 3.05; +/// How many points of the domain's box each way the fold check samples. +const FOLD_SAMPLES: usize = 32; +/// Rounds of locating the points on the surface and fitting again. +const POINT_ROUNDS: usize = 3; +/// A domain is rectilinear when this fraction of its length (weighted by how squarely it runs) +/// lies along two directions at right angles. +const RECTILINEAR: f64 = 0.5; +/// How far (radians) the domain's angle at a corner may be from the loop's for the corner to be +/// met conformally (see [`Near`]). +const CORNER_ANGLE_TOL: f64 = 0.5 * std::f64::consts::PI / 180.0; +/// Near a corner whose neighbours disagree, the G1 rows are left out over this share of the run to +/// the next corner (see [`fades`]). +const BLEND_SHARE: f64 = 0.4; +/// How close, in grid cells, a station is to a corner when it is near it (see [`Near`]): G1 and +/// G2 stations that near a corner whose neighbours disagree are not held to the angle tolerance. +const CLASH_CELLS: f64 = 2.0; + +/// What the face beside a station asks the patch to repeat across it. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Across { + /// The unit direction the neighbour leaves in across the edge (its tangent plane, at right + /// angles to the edge, away from the neighbour): where the patch goes. + pub leave: Vec3, + /// The neighbour's unit normal (either sign). + pub normal: Vec3, + /// G2: the neighbour's curvature vector along `leave` (unit speed). + pub bend: Option, +} + +/// One sample of the loop. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Station { + pub p: Vec3, + /// The patch's expected unit normal here, so that the loop runs counter-clockwise about it + /// with the patch on its left: the loop's tangent × the direction into the patch. It need not + /// be exact; it decides which way the loop turns in the patch. + pub up: Vec3, + /// G1 or G2 conditions (`None`: position only, G0). + pub across: Option, + /// The loop has a corner here: position only (two neighbours' conditions meet). + pub corner: bool, + /// A corner where the neighbours' tangent planes disagree: no surface is G1 to both, so the + /// angle tolerance is not asked of the stations close to it. + pub clash: bool, +} + +/// What [`fill_general`] is asked for. +#[derive(Clone, Copy, Debug)] +pub struct FillSpec<'a> { + /// How far the surface may be from the loop (and from the points). + pub tol: f64, + /// How far (radians) the surface's normal may turn from a G1/G2 neighbour's. + pub angle_tol: f64, + /// How full the middle is made (see [`crate::fill::fill_loop`]'s crown, between + /// [`crate::fill::MIN_CROWN`] and [`crate::fill::MAX_CROWN`]): the bump, `crown` times the + /// domain's diagonal at its middle, is laid along the surface's own normal, turned to the side + /// the G1/G2 neighbours' normals face, on control points clear of the loop, so neither the + /// loop nor the conditions across it move. A loop with no G1/G2 station has no side to crown + /// to and is refused one. + pub crown: f64, + /// Points the surface passes through. + pub points: &'a [Vec3], +} + +/// The fill and what it achieved. +#[derive(Clone, Debug, PartialEq)] +pub struct GeneralFill { + pub surface: NurbsSurface, + /// Whether the loop, in the order given, runs counter-clockwise about the surface's normal + /// `∂S/∂u × ∂S/∂v`. + pub counter_clockwise: bool, + /// The farthest station from the surface. + pub deviation: f64, + /// The largest angle (radians) between the surface's normal and a neighbour's at a G1/G2 + /// station held to the angle tolerance, and at any G1/G2 station. + pub normal_deviation: f64, + pub normal_deviation_all: f64, + /// The largest difference (1/length) between the surface's normal curvature across the + /// boundary and the neighbour's, at the G2 stations held to the angle tolerance. + pub curvature_mismatch: f64, + /// The farthest point from the surface. + pub point_deviation: f64, + /// Spans of the grid each way, and stations sampled. + pub spans: [usize; 2], + pub stations: usize, +} + +/// Fill the closed loop of `sides` sides with one surface (see the module documentation). +/// `stations(k, ts)` samples side `k` at the parameters `ts` (0 at its start, which is where side +/// `k−1` ends, towards 1 at its end); it is asked for the same parameters again only when the +/// sampling grows. +pub fn fill_general( + sides: usize, + stations: &mut dyn FnMut(usize, &[f64]) -> Result, String>, + spec: &FillSpec, +) -> SplineResult { + if sides == 0 || sides.saturating_mul(16) > MAX_LOOP_POINTS / 2 { + return Err(SplineError::TooLarge(format!("a loop of {sides} sides (at most {})", MAX_LOOP_POINTS / 32))); + } + if !(spec.tol.is_finite() && spec.tol > 0.0) || !(spec.angle_tol.is_finite() && spec.angle_tol > 0.0) { + return invalid("the fill tolerances must be positive"); + } + // A range test also throws out NaN. + if !(crate::fill::MIN_CROWN..=crate::fill::MAX_CROWN).contains(&spec.crown) { + return invalid("the crown must be between -0.9 and 3"); + } + if spec.points.len() > MAX_FILL_POINTS || spec.points.iter().any(|p| !p.is_finite()) { + return invalid(format!("a patch passes through at most {MAX_FILL_POINTS} finite points")); + } + let mut sample = |ts: &[f64]| -> SplineResult>> { + (0..sides) + .map(|k| { + let got = stations(k, ts).map_err(SplineError::Invalid)?; + if got.len() == ts.len() && got.iter().all(finite_station) { + Ok(got) + } else { + Err(SplineError::Invalid(format!("side {k} has no finite stations"))) + } + }) + .collect() + }; + let mut per = 16usize; + let mut fit = sample(&(0..per).map(|i| i as f64 / per as f64).collect::>())?; + let mut best = Shortfall::default(); + // Each round starts at the grid the last one stopped at: the coarser grids fell short with + // fewer stations, and more stations do not make a coarse grid hold the loop closer. + let mut level = MIN_SPANS; + loop { + let check = sample(&(0..per).map(|i| (i as f64 + 0.5) / per as f64).collect::>())?; + // Each side in order: fitted and checked stations alternating. + let all: Vec> = fit.iter().zip(&check).map(|(f, c)| f.iter().zip(c).flat_map(|(a, b)| [*a, *b]).collect()).collect(); + let flat: Vec = all.iter().flatten().copied().collect(); + match fit_round(&flat, spec, level)? { + Round::Done(fill) => return Ok(*fill), + Round::Denser(s, at) => { + best = best.min(s); + level = at; + } + Round::Exhausted(s) => { + best = best.min(s); + break; + } + } + if flat.len() * 2 > MAX_LOOP_POINTS { + break; + } + fit = all; + per *= 2; + } + let mut why = format!("filling this loop with one surface: the closest fit stays {:e} off the loop (tolerance {:e})", best.deviation, spec.tol); + if fit.iter().flatten().any(|s| s.across.is_some()) { + why += &format!(", turns {:.3}° from its neighbours (tolerance {:.3}°)", best.angle.to_degrees(), spec.angle_tol.to_degrees()); + } + if !spec.points.is_empty() { + why += &format!(", {:e} off its points", best.points); + } + Err(SplineError::Unsupported(why)) +} + +fn finite_station(s: &Station) -> bool { + s.p.is_finite() + && s.up.is_finite() + && s.across.is_none_or(|a| a.leave.is_finite() && a.normal.is_finite() && a.bend.is_none_or(|b| b.is_finite())) +} + +/// How close a grid came: what [`fill_general`] reports when none is close enough. +#[derive(Clone, Copy, Debug)] +struct Shortfall { + deviation: f64, + angle: f64, + points: f64, +} + +impl Default for Shortfall { + fn default() -> Shortfall { + Shortfall { deviation: f64::INFINITY, angle: f64::INFINITY, points: f64::INFINITY } + } +} + +impl Shortfall { + /// The closer of two, by how many times its tolerance each misses. + fn min(self, other: Shortfall) -> Shortfall { + let worst = |s: &Shortfall| s.deviation.max(s.points) + s.angle; + if worst(&other) < worst(&self) { other } else { self } + } +} + +enum Round { + Done(Box), + /// Denser sampling is needed for the grid of this level (the coarser ones fell short). + Denser(Shortfall, usize), + Exhausted(Shortfall), +} + +/// The loop developed into the plane (see the module documentation). +struct Developed { + /// The stations' places in the domain. + d: Vec<[f64; 2]>, + /// The domain's inward unit normal at each station. + nu: Vec<[f64; 2]>, + /// The boundary's speed at each station: loop length per domain length. + speed: Vec, + /// Whether the domain turns at each station by the loop's own angle there (to + /// [`CORNER_ANGLE_TOL`]): a corner where it does not cannot be met conformally. + true_angle: Vec, + counter_clockwise: bool, +} + +/// Develop the loop `st` into the plane. +fn develop(st: &[Station]) -> SplineResult { + let m = st.len(); + if m < 3 { + return invalid("a loop needs three stations"); + } + let at = |k: usize| st.get(k % m).map_or(Vec3::ZERO, |s| s.p); + let chord: Vec = (0..m).map(|k| at(k + 1) - at(k)).collect(); + let len: Vec = chord.iter().map(|c| c.len()).collect(); + let total: f64 = len.iter().sum(); + if !(total > 0.0 && total.is_finite()) { + return invalid("the loop has no length"); + } + if len.iter().any(|l| !(*l > 1e-12 * total)) { + return Err(SplineError::Unsupported("filling a loop with two stations in one place".into())); + } + // The turn at each station, split into its part in the patch (signed about `up`) and the rest. + // A G0 station's `up` is the loop's tangent × its neighbour's leave direction: the patch's + // normal if it carried on from the neighbour, which says nothing about the turns of a loop + // whose neighbours stand square to the patch (a lid on walls). It is tilted towards the + // loop's own mean plane (Newell's area vector, its part square to the tangent, at half + // weight): that decides those turns, and where a loop wraps round so far that the mean plane + // faces the other way, the neighbour's direction still wins. + let area = (0..m).fold(Vec3::ZERO, |a, k| a + at(k).cross(at(k + 1))); + let loop_normal = area.normalized().unwrap_or(Vec3::ZERO); + let up: Vec = (0..m) + .map(|k| { + let Some(s) = st.get(k) else { return Vec3::ZERO }; + if s.across.is_some() { + return s.up; + } + let (Some(a), Some(b)) = (chord.get((k + m - 1) % m), chord.get(k)) else { return s.up }; + let Some(t) = (*a + *b).normalized() else { return s.up }; + let square = loop_normal - t * loop_normal.dot(t); + (s.up + square * 0.5).normalized().unwrap_or(s.up) + }) + .collect(); + let mut full_turn = vec![0.0; m]; + let mut in_patch = vec![0.0; m]; + let mut bending = vec![0.0; m]; + for k in 0..m { + let (Some(a), Some(b), Some(&up)) = (chord.get((k + m - 1) % m), chord.get(k), up.get(k)) else { continue }; + let (la, lb) = (a.len(), b.len()); + let cos = (a.dot(*b) / (la * lb)).clamp(-1.0, 1.0); + let turn = cos.acos(); + if turn > FOLD_TURN { + return Err(SplineError::Unsupported("filling a loop that folds back on itself".into())); + } + if let Some(f) = full_turn.get_mut(k) { + *f = turn; + } + let axis = a.cross(*b); + let Some(axis) = axis.normalized().filter(|_| axis.len() > 1e-15 * la * lb) else { continue }; + let along = axis.dot(up).clamp(-1.0, 1.0); + if let (Some(g), Some(r)) = (in_patch.get_mut(k), bending.get_mut(k)) { + *g = turn * along; + *r = turn * (1.0 - along * along).max(0.0).sqrt(); + } + } + let geodesic: f64 = in_patch.iter().sum(); + let bend_total: f64 = bending.iter().sum(); + let sense = if geodesic >= 0.0 { 1.0 } else { -1.0 }; + let full = std::f64::consts::TAU; + // A saddle's boundary turns more than once round in the patch: the excess comes off the + // smooth stretches, so the corners keep their angles (a G1 patch is conformal at its + // boundary, and a map conformal at a corner keeps its angle); only when the corners alone + // turn too far are they scaled too. + let is_corner = |k: usize| st.get(k).is_some_and(|s| s.corner || s.clash); + let at_corners: f64 = (0..m).filter(|k| is_corner(*k)).filter_map(|k| in_patch.get(k)).sum::() * sense; + let smooth = geodesic * sense - at_corners; + let turns: Vec = if geodesic.abs() >= full && at_corners <= full && smooth > 0.0 { + let f = (full - at_corners) / smooth; + in_patch.iter().enumerate().map(|(k, g)| if is_corner(k) { *g } else { g * f }).collect() + } else if geodesic.abs() >= full { + in_patch.iter().map(|g| g * full / geodesic.abs()).collect() + } else if bend_total > 1e-9 { + let mu = (full - geodesic.abs()) / bend_total; + in_patch.iter().zip(&bending).map(|(g, r)| g + sense * mu * r).collect() + } else { + return Err(SplineError::Unsupported("filling a loop that does not turn round".into())); + }; + // Steps at their lengths along the headings, the gap spread by length. + let mut heading = 0.0; + let mut steps: Vec<[f64; 2]> = Vec::with_capacity(m); + for k in 0..m { + heading += turns.get(k).copied().unwrap_or(0.0); + let l = len.get(k).copied().unwrap_or(0.0); + steps.push([l * heading.cos(), l * heading.sin()]); + } + let gap = steps.iter().fold([0.0, 0.0], |g, s| [g[0] + s[0], g[1] + s[1]]); + for (s, l) in steps.iter_mut().zip(&len) { + s[0] -= gap[0] * l / total; + s[1] -= gap[1] * l / total; + } + let mut d = Vec::with_capacity(m); + let mut q = [0.0, 0.0]; + for s in &steps { + d.push(q); + q = [q[0] + s[0], q[1] + s[1]]; + } + // Centred and turned so the domain, and with it the grid and the fill, does not depend on + // where the loop starts: a mostly rectilinear domain (most of its length runs along two + // directions at right angles, as a polygon of straight sides often does) with those + // directions along the grid's lines, which hold data along them exactly; any other onto its + // principal axes. The larger extent is along u. + let centre = d.iter().fold([0.0, 0.0], |c, p| [c[0] + p[0] / m as f64, c[1] + p[1] / m as f64]); + let (mut sxx, mut sxy, mut syy) = (0.0, 0.0, 0.0); + for p in &d { + let (x, y) = (p[0] - centre[0], p[1] - centre[1]); + sxx += x * x; + sxy += x * y; + syy += y * y; + } + let (mut c4, mut s4) = (0.0, 0.0); + for st in &steps { + let (l, a) = (st[0].hypot(st[1]), st[1].atan2(st[0])); + c4 += l * (4.0 * a).cos(); + s4 += l * (4.0 * a).sin(); + } + let angle = if c4.hypot(s4) > RECTILINEAR * total { 0.25 * s4.atan2(c4) } else { 0.5 * (2.0 * sxy).atan2(sxx - syy) }; + let turned = |angle: f64| -> Vec<[f64; 2]> { + let (c, s) = (angle.cos(), angle.sin()); + d.iter() + .map(|p| { + let (x, y) = (p[0] - centre[0], p[1] - centre[1]); + [c * x + s * y, -s * x + c * y] + }) + .collect() + }; + let mut d = turned(angle); + let spread = + |d: &[[f64; 2]], k: usize| d.iter().map(|p| p[k]).fold(f64::NEG_INFINITY, f64::max) - d.iter().map(|p| p[k]).fold(f64::INFINITY, f64::min); + if spread(&d, 1) > spread(&d, 0) * (1.0 + 1e-9) { + d = turned(angle + std::f64::consts::FRAC_PI_2); + } + let skew: f64 = d.iter().map(|p| p[0] * p[0] * p[0] + p[1] * p[1] * p[1]).sum(); + if skew < 0.0 { + for p in &mut d { + *p = [-p[0], -p[1]]; + } + } + check_simple(&d)?; + // The domain runs the way the loop turned in the patch. + let area: f64 = (0..m).map(|k| cross2(get2(&d, k), get2(&d, k + 1))).sum::() * 0.5; + if !(area * sense > 0.0) { + return Err(SplineError::Unsupported("filling a loop that develops inside out".into())); + } + let mut nu = Vec::with_capacity(m); + let mut speed = Vec::with_capacity(m); + for k in 0..m { + let (prev, next) = (get2(&d, k + m - 1), get2(&d, k + 1)); + let here = get2(&d, k); + let (a, b) = ([here[0] - prev[0], here[1] - prev[1]], [next[0] - here[0], next[1] - here[1]]); + let (la, lb) = (a[0].hypot(a[1]), b[0].hypot(b[1])); + if !(la > 0.0 && lb > 0.0) { + return Err(SplineError::Unsupported("filling a loop with two stations in one place".into())); + } + let t = [a[0] / la + b[0] / lb, a[1] / la + b[1] / lb]; + let lt = t[0].hypot(t[1]); + let t = if lt > 1e-9 { [t[0] / lt, t[1] / lt] } else { [b[0] / lb, b[1] / lb] }; + // The left normal is inward on a counter-clockwise domain. + nu.push([-t[1] * sense, t[0] * sense]); + let space = len.get((k + m - 1) % m).copied().unwrap_or(0.0) + len.get(k).copied().unwrap_or(0.0); + speed.push(space / (la + lb)); + } + let true_angle = turns.iter().zip(&full_turn).map(|(t, f)| (t.abs() - f).abs() <= CORNER_ANGLE_TOL).collect(); + Ok(Developed { d, nu, speed, true_angle, counter_clockwise: sense > 0.0 }) +} + +fn get2(d: &[[f64; 2]], k: usize) -> [f64; 2] { + d.get(k % d.len().max(1)).copied().unwrap_or([0.0; 2]) +} + +fn cross2(a: [f64; 2], b: [f64; 2]) -> f64 { + a[0] * b[1] - a[1] * b[0] +} + +/// Refuse a domain polygon whose non-adjacent sides meet. +fn check_simple(d: &[[f64; 2]]) -> SplineResult<()> { + let m = d.len(); + let q = |k: usize| get2(d, k); + let mut segs: Vec<(f64, f64, usize)> = (0..m) + .map(|k| { + let (a, b) = (q(k), q(k + 1)); + (a[0].min(b[0]), a[0].max(b[0]), k) + }) + .collect(); + segs.sort_by(|a, b| a.0.total_cmp(&b.0)); + for (i, &(_, hi, k)) in segs.iter().enumerate() { + for &(lo2, _, l) in segs.get(i + 1..).into_iter().flatten() { + if lo2 > hi { + break; + } + let adjacent = (k + 1) % m == l || (l + 1) % m == k; + if !adjacent && segments_meet(q(k), q(k + 1), q(l), q(l + 1)) { + return Err(SplineError::Unsupported("filling a loop whose development crosses itself".into())); + } + } + } + Ok(()) +} + +/// The basis of a grid at `q`: the first indices and the values of the four non-zero functions +/// and their first two derivatives, each way. +struct Basis { + first: [usize; 2], + /// `[direction][derivative][function]`. + b: [[[f64; 4]; 3]; 2], +} + +impl Basis { + fn at(grid: &Grid, q: [f64; 2]) -> Option { + let mut first = [0usize; 2]; + let mut b = [[[0.0; 4]; 3]; 2]; + for d in 0..2 { + for r in 0..3 { + let (f, vals) = grid.basis_derivative(d, *q.get(d)?, r)?; + *first.get_mut(d)? = f; + *b.get_mut(d)?.get_mut(r)? = vals; + } + } + Some(Basis { first, b }) + } + + /// The 16 (i, j, coefficient) terms of the derivative `Σ w[ru][rv] ∂^ru_u ∂^rv_v` at the point. + fn cells(&self, w: &[(usize, usize, f64)]) -> [(usize, usize, f64); 16] { + let mut out = [(0usize, 0usize, 0.0f64); 16]; + for (t, slot) in out.iter_mut().enumerate() { + let (a, b) = (t % 4, t / 4); + let c: f64 = w.iter().map(|&(ru, rv, k)| k * self.b[0][ru.min(2)][a] * self.b[1][rv.min(2)][b]).sum(); + *slot = (self.first[0] + a, self.first[1] + b, c); + } + out + } + + /// The 16 (index, coefficient) terms of the derivative `Σ w[ru][rv] ∂^ru_u ∂^rv_v` at the + /// point, over control points numbered i fastest in a grid `cu` wide. + fn terms(&self, cu: usize, w: &[(usize, usize, f64)]) -> [(usize, f64); 16] { + let mut out = [(0usize, 0.0f64); 16]; + for (t, slot) in out.iter_mut().enumerate() { + let (a, b) = (t % 4, t / 4); + let c: f64 = w.iter().map(|&(ru, rv, k)| k * self.b[0][ru.min(2)][a] * self.b[1][rv.min(2)][b]).sum(); + *slot = ((self.first[1] + b) * cu + self.first[0] + a, c); + } + out + } +} + +/// The normal equations of the fit, shared by the three coordinates. +struct System { + band: Band, + rhs: [Vec; 3], + rows: usize, +} + +impl System { + fn new(n: usize, bw: usize) -> System { + System { band: Band::new(n, bw), rhs: [vec![0.0; n], vec![0.0; n], vec![0.0; n]], rows: 0 } + } + + /// One least-squares row: `Σ coefficient · control = target`. + fn row(&mut self, terms: &[(usize, f64); 16], target: Vec3) { + for &(r, wr) in terms { + for (rhs, t) in self.rhs.iter_mut().zip([target.x, target.y, target.z]) { + if let Some(slot) = rhs.get_mut(r) { + *slot += wr * t; + } + } + for &(s, ws) in terms { + self.band.add(r, s, wr * ws); + } + } + self.rows += 1; + } +} + +/// A fitted surface's net on its grid. +struct Net<'a> { + grid: &'a Grid, + ctrl: Vec, +} + +impl Net<'_> { + /// `∂^ru_u ∂^rv_v S` at `q`. + fn der(&self, q: [f64; 2], ru: usize, rv: usize) -> Option { + let b = Basis::at(self.grid, q)?; + let cu = *self.grid.count.first()?; + let mut s = Vec3::ZERO; + for (i, c) in b.terms(cu, &[(ru, rv, 1.0)]) { + s += *self.ctrl.get(i)? * c; + } + Some(s) + } + + fn point(&self, q: [f64; 2]) -> Option { + self.der(q, 0, 0) + } + + /// The unit normal `S_u × S_v` and the first derivatives. + fn frame(&self, q: [f64; 2]) -> Option<(Vec3, Vec3, Vec3)> { + let (su, sv) = (self.der(q, 1, 0)?, self.der(q, 0, 1)?); + Some((su.cross(sv).normalized()?, su, sv)) + } +} + +/// The weights `(ru, rv, w)` of the first and second derivatives along the domain direction `nu`. +fn along(nu: [f64; 2], order: usize) -> Vec<(usize, usize, f64)> { + let [a, b] = nu; + match order { + 1 => vec![(1, 0, a), (0, 1, b)], + _ => vec![(2, 0, a * a), (1, 1, 2.0 * a * b), (0, 2, b * b)], + } +} + +/// One round: develop the loop `st` (the fitted stations at even places), then try the grids. +fn fit_round(st: &[Station], spec: &FillSpec, start: usize) -> SplineResult { + let dev = develop(st)?; + let m = st.len(); + let (mut lo, mut hi) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]); + for q in &dev.d { + for k in 0..2 { + lo[k] = lo[k].min(q[k]); + hi[k] = hi[k].max(q[k]); + } + } + let pad = 0.05 * (hi[0] - lo[0]).max(hi[1] - lo[1]); + for k in 0..2 { + lo[k] -= pad; + hi[k] += pad; + } + let extent = [hi[0] - lo[0], hi[1] - lo[1]]; + if !(extent[0] > 0.0 && extent[1] > 0.0 && extent[0].is_finite() && extent[1].is_finite()) { + return invalid("the loop's development has no extent"); + } + // The largest step between fitted stations, per direction. + let mut step = [0.0f64; 2]; + for k in (0..m).step_by(2) { + let (p, q) = (get2(&dev.d, k), get2(&dev.d, k + 2)); + for i in 0..2 { + step[i] = step[i].max((q[i] - p[i]).abs()); + } + } + // Where the corners are in the domain, and those whose neighbours disagree. + let corners: Vec<[f64; 2]> = st.iter().zip(&dev.d).filter(|(s, _)| s.corner || s.clash).map(|(_, d)| *d).collect(); + let rough: Vec<[f64; 2]> = st + .iter() + .zip(&dev.d) + .zip(&dev.true_angle) + .filter(|((s, _), true_angle)| s.clash || (s.corner && !**true_angle)) + .map(|((_, d), _)| *d) + .collect(); + let clashes: Vec<[f64; 2]> = st.iter().zip(&dev.d).filter(|(s, _)| s.clash).map(|(_, d)| *d).collect(); + let fade = fades(st); + let longer = extent[0].max(extent[1]); + let mut best = Shortfall::default(); + let mut level = start.max(MIN_SPANS); + while level <= MAX_GENERAL_SPANS { + let spans = [0, 1].map(|d| ((extent[d] / longer * level as f64).ceil() as usize).clamp(1, level)); + let holds = (0..2).all(|d| extent[d] / spans[d] as f64 >= 2.0 * step[d]); + if !holds && level > start { + return Ok(Round::Denser(best, level)); + } + let grid = Grid::new(spans, lo, hi); + let cell = (grid.cell(0) * grid.cell(1)).sqrt(); + let near = Near::of(&dev.d, &corners, &rough, &clashes, CLASH_CELLS * cell); + let (net, located) = fit_grid(&grid, st, &dev, spec, &near, &fade)?; + let got = measure(&net, st, &dev, spec, &located, &near, &fade)?; + best = best.min(got.shortfall); + let within = got.shortfall.deviation <= spec.tol && got.shortfall.angle <= spec.angle_tol && got.shortfall.points <= spec.tol; + if within && holds { + check_folds(&net, &dev.d, lo, hi)?; + let ctrl: Vec = net.ctrl.iter().map(|p| HPoint::weighted(*p, 1.0)).collect(); + let surface = NurbsSurface::from_homogeneous([3, 3], grid.knots.clone(), ctrl)?; + let surface = crown(surface, &net, st, &dev, spec.crown)?; + return Ok(Round::Done(Box::new(GeneralFill { + surface, + counter_clockwise: dev.counter_clockwise, + deviation: got.shortfall.deviation, + normal_deviation: got.shortfall.angle, + normal_deviation_all: got.angle_all, + curvature_mismatch: got.curvature, + point_deviation: got.shortfall.points, + spans, + stations: m, + }))); + } + if !holds { + return Ok(Round::Denser(best, level)); + } + level *= 2; + } + Ok(Round::Exhausted(best)) +} + +/// Which stations are close to a corner, and to a corner whose neighbours disagree, on one grid. +/// +/// At a corner the two sides' conditions meet and overdetermine the surface (the compatibility +/// of Hermite boundary data at a vertex): there one side's cross-boundary derivatives are the +/// other side's boundary curve, and the development's corner angle only approximates the loop's. +/// Close to any corner the second-derivative rows are left out, and close to a corner the domain +/// does not turn by the loop's own angle (a conformal map keeps angles), or where the neighbours' +/// tangent planes disagree, the first-derivative rows too: the positions decide there. The +/// neighbourhood is a few grid cells, so it shrinks as the grid refines. (Where the neighbours' +/// tangent planes disagree no surface is tangent to both; see [`fades`].) +struct Near { + corner: Vec, + rough: Vec, + clash: Vec, +} + +impl Near { + fn of(d: &[[f64; 2]], corners: &[[f64; 2]], rough: &[[f64; 2]], clashes: &[[f64; 2]], reach: f64) -> Near { + let close = |set: &[[f64; 2]]| -> Vec { d.iter().map(|q| set.iter().any(|c| (c[0] - q[0]).hypot(c[1] - q[1]) <= reach)).collect() }; + Near { corner: close(corners), rough: close(rough), clash: close(clashes) } + } + + fn rough(&self, k: usize) -> bool { + self.rough.get(k).copied().unwrap_or(true) + } + + fn corner(&self, k: usize) -> bool { + self.corner.get(k).copied().unwrap_or(true) + } + + fn clash(&self, k: usize) -> bool { + self.clash.get(k).copied().unwrap_or(true) + } +} + +/// Whether each station's G1 rows are asked (1) or not (0): not near a corner whose neighbours' +/// tangent planes disagree. +struct Fade { + weight: Vec, +} + +impl Fade { + fn at(&self, k: usize) -> f64 { + self.weight.get(k).copied().unwrap_or(0.0) + } +} + +/// The G1 rows' weights. At a corner whose neighbours' tangent planes disagree no surface is +/// tangent to both: its tangent plane there must hold both boundary tangents, so it is singular +/// at the corner however it is shaped. Within [`BLEND_SHARE`] of the run to the next corner of +/// such a corner the G1 rows are left out and the positions and the smoothness decide the +/// surface; those stations are not held to the angle tolerance. (Rows fading out towards the +/// corner instead keep asking for a tangent plane the corner cannot have, and the fit folds +/// there.) +fn fades(st: &[Station]) -> Fade { + let m = st.len(); + let mut weight = vec![1.0f64; m]; + let clashes: Vec = (0..m).filter(|k| st.get(*k).is_some_and(|s| s.clash)).collect(); + if clashes.is_empty() || m < 3 { + return Fade { weight }; + } + let p = |k: usize| st.get(k % m).map_or(Vec3::ZERO, |s| s.p); + let step = |k: usize| p(k + 1).dist(p(k)); + let is_corner = |k: usize| st.get(k % m).is_some_and(|s| s.corner || s.clash); + for &c in &clashes { + if let Some(w) = weight.get_mut(c) { + *w = 0.0; + } + // Back along the incoming side, then on along the outgoing one. + for back in [true, false] { + let next = |k: usize| if back { (k + m - 1) % m } else { (k + 1) % m }; + // The run to the next corner. + let (mut run, mut k) = (0.0, c); + for _ in 0..m { + let n = next(k); + run += if back { step(n) } else { step(k) }; + k = n; + if is_corner(k) { + break; + } + } + let reach = BLEND_SHARE * run; + let (mut dist, mut k) = (0.0, c); + for _ in 0..m { + let n = next(k); + dist += if back { step(n) } else { step(k) }; + k = n; + if dist >= reach || is_corner(k) { + break; + } + if let Some(w) = weight.get_mut(k) { + *w = 0.0; + } + } + } + } + Fade { weight } +} + +/// Fit the grid to the even stations' conditions and the points: the net, and where the points +/// ended up in the domain. +fn fit_grid<'a>( + grid: &'a Grid, + st: &[Station], + dev: &Developed, + spec: &FillSpec, + near: &Near, + fade: &Fade, +) -> SplineResult<(Net<'a>, Vec<[f64; 2]>)> { + let cell = (grid.cell(0) * grid.cell(1)).sqrt(); + let mut rows: Vec = Vec::new(); + for (k, s) in st.iter().enumerate().step_by(2) { + let Some(across) = s.across.filter(|_| !s.corner) else { continue }; + let (Some(&q), Some(&nu), Some(&speed)) = (dev.d.get(k), dev.nu.get(k), dev.speed.get(k)) else { continue }; + let weight = fade.at(k); + if !(weight > 1e-3) { + continue; + } + let full = weight >= 1.0; + let bend = across.bend.filter(|_| full && !near.corner(k)); + rows.push(Hermite { + q, + nu, + normal: across.normal, + leave: across.leave, + hermite: full && !near.rough(k), + weight, + curvature: bend.map(|b| across.normal.dot(b)), + speed, + }); + } + // The fitted stations (every other one), then the points where they were last found. + let fitted: Vec<([f64; 2], Vec3)> = st.iter().zip(&dev.d).step_by(2).map(|(s, q)| (*q, s.p)).collect(); + let mut extra: Vec<([f64; 2], Vec3)> = Vec::new(); + let rounds = if spec.points.is_empty() { 0 } else { POINT_ROUNDS }; + let mut round = 0; + loop { + let data: Vec<([f64; 2], Vec3)> = fitted.iter().chain(&extra).copied().collect(); + let net = if rows.is_empty() { fit_positions(grid, &data)? } else { fit_coupled(grid, &data, &mut rows, cell)? }; + let located = spec.points.iter().map(|p| locate(&net, &dev.d, *p)).collect::>>()?; + if round >= rounds { + return Ok((net, located)); + } + extra = located.iter().copied().zip(spec.points.iter().copied()).collect(); + round += 1; + } +} + +/// The fit to positions alone (G0 everywhere): the three coordinates apart, sharing one matrix. +fn fit_positions<'a>(grid: &'a Grid, data: &[([f64; 2], Vec3)]) -> SplineResult> { + let [cu, cv] = grid.count; + let n = cu * cv; + let mut sys = System::new(n, 3 * cu + 3); + for (q, p) in data { + let b = Basis::at(grid, *q).ok_or_else(|| SplineError::Invalid("a station is off the grid".into()))?; + sys.row(&b.terms(cu, &[(0, 0, 1.0)]), *p); + } + let lambda = SMOOTHNESS * sys.rows as f64 / n as f64 * grid.cell(0) * grid.cell(1); + grid.add_energy(&mut sys.band, lambda); + let factor = sys.band.factor_rows()?; + let [x, y, z] = sys.rhs; + let (x, y, z) = (factor.substitute(x)?, factor.substitute(y)?, factor.substitute(z)?); + net_of(grid, x.iter().zip(&y).zip(&z).map(|((x, y), z)| Vec3::new(*x, *y, *z)).collect()) +} + +fn net_of(grid: &Grid, ctrl: Vec) -> SplineResult> { + if ctrl.iter().any(|p| !p.is_finite()) { + return invalid("the fit is not finite"); + } + Ok(Net { grid, ctrl }) +} + +/// One G1/G2 station's rows (see [`fit_coupled`]). +struct Hermite { + q: [f64; 2], + nu: [f64; 2], + /// The normal of the tangent plane asked for, and the direction the patch should leave in. + normal: Vec3, + leave: Vec3, + /// Whether the weak Hermite rows are asked (not close to a corner the development does not + /// keep the angle of, unless in a blend). + hermite: bool, + /// How much the G1 row weighs (see [`fades`]). + weight: f64, + /// G2: the neighbour's normal curvature along `leave`. + curvature: Option, + /// How fast the patch leaves: first the boundary's own speed, then what the fit gives. + speed: f64, +} + +/// How much the Hermite rows (the full first derivative `s·w`) weigh against the G1 rows: enough +/// to say which way and about how fast the patch leaves, little enough to give way where the +/// full data cannot all hold. +const HERMITE_WEIGHT: f64 = 0.05; +/// Rounds of updating the speed a G2 row's curvature is asked at. +const G2_ROUNDS: usize = 4; + +/// The fit with G1 and G2 rows: the three coordinates together, since the rows that hold the +/// continuity are geometric and couple them. +/// +/// - Positions, as for [`fit_positions`]. +/// - G1: `n·∂S/∂ν = 0` — the patch's cross-boundary derivative lies in the tangent plane asked +/// for, which with the boundary tangent in it makes the normals agree. That is all G1 asks. +/// - Weak Hermite rows `∂S/∂ν = s·w` (weight [`HERMITE_WEIGHT`]): which way the patch leaves +/// (into the patch, not folding back over the neighbour) and about how fast. A whole set of +/// full Hermite data is consistent only with a boundary map that is exactly conformal at the +/// boundary's own speed, which a curved patch's is not, so these give way. +/// - G2: `n·∂²S/∂ν² = (∂S/∂ν·w)²·κ` — the patch's normal curvature across the edge is the +/// neighbour's. The speed is the fit's own, so the row is solved again with the speed from the +/// last solution (the matrix stays, so each round is a back substitution). +/// +/// The unknowns are numbered with the grid's shorter direction fastest and the coordinates +/// innermost, which keeps the band narrow. +fn fit_coupled<'a>(grid: &'a Grid, data: &[([f64; 2], Vec3)], rows: &mut [Hermite], cell: f64) -> SplineResult> { + let [cu, cv] = grid.count; + let n = cu * cv; + let u_fast = cu <= cv; + let fast = if u_fast { cu } else { cv }; + let index = |i: usize, j: usize, c: usize| if u_fast { (j * cu + i) * 3 + c } else { (i * cv + j) * 3 + c }; + let mut band = Band::new(3 * n, 3 * (3 * fast + 3) + 2); + let mut rhs = vec![0.0; 3 * n]; + let mut count = 0usize; + // A row on the three coordinates: `Σ_c Σ_t coefficient_t · weight_c · control_{t,c} = target`. + let mut row = |band: &mut Band, rhs: &mut [f64], cells: &[(usize, usize, f64); 16], weights: [f64; 3], target: f64| { + let mut terms = [(0usize, 0.0f64); 48]; + for (c, w) in weights.iter().enumerate() { + for (t, &(i, j, k)) in cells.iter().enumerate() { + if let Some(slot) = terms.get_mut(c * 16 + t) { + *slot = (index(i, j, c), k * w); + } + } + } + for &(r, wr) in &terms { + if wr == 0.0 { + continue; + } + if let Some(slot) = rhs.get_mut(r) { + *slot += wr * target; + } + for &(s, ws) in &terms { + band.add(r, s, wr * ws); + } + } + count += 1; + }; + let axes = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]; + let coords = |p: Vec3| [p.x, p.y, p.z]; + for &(q, p) in data { + let b = Basis::at(grid, q).ok_or_else(|| SplineError::Invalid("a station is off the grid".into()))?; + let cells = b.cells(&[(0, 0, 1.0)]); + for (axis, t) in axes.iter().zip(coords(p)) { + row(&mut band, &mut rhs, &cells, *axis, t); + } + } + // The right-hand side so far; the G2 rows' targets are added per round. + let mut second: Vec<([(usize, usize, f64); 16], usize)> = Vec::new(); + for (h, r) in rows.iter().enumerate() { + let b = Basis::at(grid, r.q).ok_or_else(|| SplineError::Invalid("a station is off the grid".into()))?; + let first = b.cells(&along(r.nu, 1)).map(|(i, j, k)| (i, j, k * cell)); + let held = first.map(|(i, j, k)| (i, j, k * r.weight)); + row(&mut band, &mut rhs, &held, coords(r.normal), 0.0); + if r.hermite { + let w = HERMITE_WEIGHT * r.weight; + let weak = first.map(|(i, j, k)| (i, j, k * w)); + for (axis, t) in axes.iter().zip(coords(r.leave * (r.speed * cell * w))) { + row(&mut band, &mut rhs, &weak, *axis, t); + } + } + if r.curvature.is_some() { + let cells = b.cells(&along(r.nu, 2)).map(|(i, j, k)| (i, j, k * cell * cell)); + row(&mut band, &mut rhs, &cells, coords(r.normal), 0.0); + second.push((cells, h)); + } + } + let lambda = SMOOTHNESS * count as f64 / (3 * n) as f64 * grid.cell(0) * grid.cell(1); + grid.energy(lambda, &mut |(i, j), (k, l), e| { + for c in 0..3 { + band.add(index(i, j, c), index(k, l, c), e); + } + }); + let factor = band.factor_rows()?; + let rounds = if second.is_empty() { 1 } else { G2_ROUNDS }; + let mut net = None; + for _ in 0..rounds { + let mut b = rhs.clone(); + for (cells, h) in &second { + let Some(r) = rows.get(*h) else { continue }; + let target = r.curvature.unwrap_or(0.0) * r.speed * r.speed * cell * cell; + for (c, w) in coords(r.normal).iter().enumerate() { + for &(i, j, k) in cells { + if let Some(slot) = b.get_mut(index(i, j, c)) { + *slot += k * w * target; + } + } + } + } + let x = factor.substitute(b)?; + let ctrl: Vec = (0..cv) + .flat_map(|j| (0..cu).map(move |i| (i, j))) + .map(|(i, j)| { + Vec3::new( + x.get(index(i, j, 0)).copied().unwrap_or(f64::NAN), + x.get(index(i, j, 1)).copied().unwrap_or(f64::NAN), + x.get(index(i, j, 2)).copied().unwrap_or(f64::NAN), + ) + }) + .collect(); + let current = net_of(grid, ctrl)?; + for r in rows.iter_mut().filter(|r| r.curvature.is_some()) { + let (Some(su), Some(sv)) = (current.der(r.q, 1, 0), current.der(r.q, 0, 1)) else { + return invalid("the fit cannot be evaluated on the loop"); + }; + let ahead = (su * r.nu[0] + sv * r.nu[1]).dot(r.leave); + if ahead > 0.0 { + r.speed = ahead; + } + } + net = Some(current); + } + net.ok_or_else(|| SplineError::Invalid("the fit made no rounds".into())) +} + +/// Where in the domain the surface comes nearest `p`: the nearest of a grid of samples inside +/// the domain, then Gauss–Newton. A point nearest the surface outside the loop is refused. +fn locate(net: &Net, d: &[[f64; 2]], p: Vec3) -> SplineResult<[f64; 2]> { + let kn = &net.grid.knots; + let (Some(u0), Some(u1), Some(v0), Some(v1)) = (kn[0].first(), kn[0].last(), kn[1].first(), kn[1].last()) else { + return invalid("the grid has no knots"); + }; + let (lo, hi) = ([*u0, *v0], [*u1, *v1]); + let samples = 48; + let mut best: Option<(f64, [f64; 2])> = None; + for i in 0..=samples { + for j in 0..=samples { + let q = [lo[0] + (hi[0] - lo[0]) * i as f64 / samples as f64, lo[1] + (hi[1] - lo[1]) * j as f64 / samples as f64]; + if !inside_loop(q, d) { + continue; + } + let Some(s) = net.point(q) else { continue }; + let dist = s.dist(p); + if best.is_none_or(|(b, _)| dist < b) { + best = Some((dist, q)); + } + } + } + let Some((_, mut q)) = best else { return Err(SplineError::Unsupported("passing through points: the loop's development is too thin".into())) }; + for _ in 0..40 { + let (Some(s), Some(su), Some(sv)) = (net.point(q), net.der(q, 1, 0), net.der(q, 0, 1)) else { break }; + let r = s - p; + let (a, b, c) = (su.dot(su), su.dot(sv), sv.dot(sv)); + let det = a * c - b * b; + if !(det.abs() > 1e-300) { + break; + } + let (ga, gb) = (su.dot(r), sv.dot(r)); + let next = [(q[0] - (c * ga - b * gb) / det).clamp(lo[0], hi[0]), (q[1] - (a * gb - b * ga) / det).clamp(lo[1], hi[1])]; + let moved = (next[0] - q[0]).hypot(next[1] - q[1]); + q = next; + if moved < 1e-13 * (hi[0] - lo[0]) { + break; + } + } + if !inside_loop(q, d) { + return Err(SplineError::Unsupported("passing through a point that is not over the inside of the loop".into())); + } + Ok(q) +} + +/// What a fit achieved. +struct Measured { + shortfall: Shortfall, + angle_all: f64, + curvature: f64, +} + +/// Measure a fit against every station and the points. +fn measure(net: &Net, st: &[Station], dev: &Developed, spec: &FillSpec, located: &[[f64; 2]], near: &Near, fade: &Fade) -> SplineResult { + let off = |what: &str| SplineError::Invalid(format!("the fit cannot be evaluated {what}")); + let sense = if dev.counter_clockwise { 1.0 } else { -1.0 }; + let (mut deviation, mut angle, mut angle_all, mut curvature) = (0.0f64, 0.0f64, 0.0f64, 0.0f64); + for (k, s) in st.iter().enumerate() { + let (Some(&q), Some(&nu)) = (dev.d.get(k), dev.nu.get(k)) else { continue }; + deviation = deviation.max(net.point(q).ok_or_else(|| off("on the loop"))?.dist(s.p)); + let Some(across) = s.across.filter(|_| !s.corner) else { continue }; + let (normal, su, sv) = net.frame(q).ok_or_else(|| off("on the loop"))?; + // The neighbour's normal turned to the side the patch's normal should be on. + let want = if across.normal.dot(s.up) * sense >= 0.0 { across.normal } else { across.normal * -1.0 }; + let a = normal.dot(want).clamp(-1.0, 1.0).acos(); + angle_all = angle_all.max(a); + if near.clash(k) || fade.at(k) < 1.0 { + continue; + } + angle = angle.max(a); + if let Some(bend) = across.bend.filter(|_| !near.corner(k)) { + let first = su * nu[0] + sv * nu[1]; + let second = net.der(q, 2, 0).zip(net.der(q, 1, 1)).zip(net.der(q, 0, 2)).ok_or_else(|| off("on the loop"))?; + let ((uu, uv), vv) = second; + let second = uu * (nu[0] * nu[0]) + uv * (2.0 * nu[0] * nu[1]) + vv * (nu[1] * nu[1]); + let speed2 = first.dot(first); + if speed2 > 0.0 { + curvature = curvature.max((normal.dot(second) / speed2 - want.dot(bend)).abs()); + } + } + } + let mut points = 0.0f64; + for (q, p) in located.iter().zip(spec.points) { + points = points.max(net.point(*q).ok_or_else(|| off("at a point"))?.dist(*p)); + } + if ![deviation, angle, angle_all, curvature, points].iter().all(|x| x.is_finite()) { + return invalid("the fit is not finite"); + } + Ok(Measured { shortfall: Shortfall { deviation, angle, points }, angle_all, curvature }) +} + +/// The fill with its crown (see [`FillSpec::crown`]). +fn crown(surface: NurbsSurface, net: &Net, st: &[Station], dev: &Developed, crown: f64) -> SplineResult { + if crown == 0.0 { + return Ok(surface); + } + // The side the neighbours' normals face, by the patch's normals at the G1/G2 stations. + let mut side = 0.0; + for (s, q) in st.iter().zip(&dev.d) { + if let (Some(a), Some((n, _, _))) = (s.across, net.frame(*q)) { + side += n.dot(a.normal).signum(); + } + } + if side == 0.0 { + return Err(SplineError::Unsupported("crowning a patch with no g1 or g2 edge to say which side is out".into())); + } + let sign = side.signum(); + let along = |g: [f64; 2]| net.frame(g).map(|(n, _, _)| n * sign); + let (surface, _, _) = crate::fill::crown_fill_along(surface, &dev.d, crown, &along, MAX_GENERAL_SPANS)?; + Ok(surface) +} + +/// Refuse a fit that folds over or pinches inside the loop: on a grid of samples inside the +/// domain, the normal must be defined everywhere (the surface's parameter speed nowhere collapses +/// against the rest) and must not turn over between neighbouring samples. +fn check_folds(net: &Net, d: &[[f64; 2]], lo: [f64; 2], hi: [f64; 2]) -> SplineResult<()> { + let n = FOLD_SAMPLES; + let mut cells: Vec> = Vec::with_capacity((n + 1) * (n + 1)); + for j in 0..=n { + for i in 0..=n { + let q = [lo[0] + (hi[0] - lo[0]) * i as f64 / n as f64, lo[1] + (hi[1] - lo[1]) * j as f64 / n as f64]; + if !inside_loop(q, d) { + cells.push(None); + continue; + } + let (Some(su), Some(sv)) = (net.der(q, 1, 0), net.der(q, 0, 1)) else { return invalid("the fit cannot be evaluated inside") }; + let c = su.cross(sv); + cells.push(Some((c, c.len()))); + } + } + let mut sizes: Vec = cells.iter().flatten().map(|(_, l)| *l).collect(); + if sizes.is_empty() { + return Ok(()); + } + sizes.sort_by(f64::total_cmp); + let median = sizes.get(sizes.len() / 2).copied().unwrap_or(0.0); + let smallest = sizes.first().copied().unwrap_or(0.0); + if !(smallest > 1e-3 * median) { + return Err(SplineError::Unsupported("filling this loop: the surface pinches inside it".into())); + } + let at = |i: usize, j: usize| cells.get(j * (n + 1) + i).copied().flatten(); + for j in 0..=n { + for i in 0..=n { + let Some((a, _)) = at(i, j) else { continue }; + for (x, y) in [(i + 1, j), (i, j + 1)] { + if let Some((b, _)) = at(x, y) + && a.dot(b) <= 0.0 + { + return Err(SplineError::Unsupported("filling this loop: the surface folds over inside it".into())); + } + } + } + } + Ok(()) +} + +#[cfg(test)] +#[path = "fill_general_tests.rs"] +mod tests; diff --git a/crates/geom/src/fill_general_tests.rs b/crates/geom/src/fill_general_tests.rs new file mode 100644 index 000000000..35ff6b6cd --- /dev/null +++ b/crates/geom/src/fill_general_tests.rs @@ -0,0 +1,191 @@ +use super::*; +use std::f64::consts::{PI, TAU}; + +const TOL: f64 = 1e-5; +const ANGLE: f64 = 0.05 * PI / 180.0; + +/// The surface at fractions `(x, y)` of its domain. +fn at(s: &NurbsSurface, x: f64, y: f64) -> Vec3 { + let [du, dv] = s.domain(); + s.eval((du[0] + (du[1] - du[0]) * x).min(du[1]), (dv[0] + (dv[1] - dv[0]) * y).min(dv[1])).unwrap() +} + +fn spec(points: &[Vec3]) -> FillSpec<'_> { + FillSpec { tol: TOL, angle_tol: ANGLE, crown: 0.0, points } +} + +/// The radial and tangential unit vectors of a cylinder about z at angle `a`. +fn radial(a: f64) -> Vec3 { + Vec3::new(a.cos(), a.sin(), 0.0) +} +fn around(a: f64) -> Vec3 { + Vec3::new(-a.sin(), a.cos(), 0.0) +} + +/// The open end of a tube about z (radius `r`, its wall below z = 0), one side: G1 (or G2) to +/// the wall, which leaves straight up. +fn tube_end(r: f64, g2: bool) -> impl FnMut(usize, &[f64]) -> Result, String> { + move |_, ts| { + Ok(ts + .iter() + .map(|t| { + let a = t * TAU; + let across = Across { leave: Vec3::Z, normal: radial(a), bend: g2.then_some(Vec3::ZERO) }; + Station { p: radial(a) * r, up: around(a).cross(Vec3::Z), across: Some(across), corner: false, clash: false } + }) + .collect()) + } +} + +/// A window in the wall of a cylinder about z (radius `r`): `a` either side of the x axis, `h` +/// high, its four sides G1 to the wall around it (the same cylinder). +fn window(r: f64, a: f64, h: f64) -> impl FnMut(usize, &[f64]) -> Result, String> { + move |k, ts| { + Ok(ts + .iter() + .map(|&t| { + let (angle, z, tangent, leave) = match k { + 0 => (-a + 2.0 * a * t, 0.0, around(-a + 2.0 * a * t), Vec3::Z), + 1 => (a, h * t, Vec3::Z, around(a) * -1.0), + 2 => (a - 2.0 * a * t, h, around(a - 2.0 * a * t) * -1.0, Vec3::Z * -1.0), + _ => (-a, h - h * t, Vec3::Z * -1.0, around(-a)), + }; + let p = radial(angle) * r + Vec3::Z * z; + let up = tangent.cross(leave); + Station { p, up, across: Some(Across { leave, normal: radial(angle), bend: None }), corner: t == 0.0, clash: false } + }) + .collect()) + } +} + +#[test] +fn a_tube_end_capped_g1_meets_the_wall_and_rises_over_it() { + for g2 in [false, true] { + let f = fill_general(1, &mut tube_end(10.0, g2), &spec(&[])).unwrap(); + eprintln!( + "tube end (g2 {g2}): {:?} spans, {} stations, off the rim {:e}, normals within {:.4}°, curvature mismatch {:e}", + f.spans, + f.stations, + f.deviation, + f.normal_deviation.to_degrees(), + f.curvature_mismatch + ); + assert!(f.deviation <= TOL && f.normal_deviation <= ANGLE); + // The middle rises over the rim (the cap leaves the wall upwards). + let mid = at(&f.surface, 0.5, 0.5); + eprintln!("the cap's middle: {mid:?}"); + assert!(mid.z > 2.0 && mid.x.hypot(mid.y) < 1.0, "{mid:?}"); + } +} + +#[test] +fn a_window_in_a_cylinder_wrapping_past_half_way_fills_close_to_the_cylinder() { + // 240° around: no plane sees it as a height field. + let (r, a, h) = (10.0, 2.0 * PI / 3.0, 10.0); + let f = fill_general(4, &mut window(r, a, h), &spec(&[])).unwrap(); + eprintln!("window: {:?} spans, off {:e}, normals within {:.4}°", f.spans, f.deviation, f.normal_deviation.to_degrees()); + assert!(f.deviation <= TOL && f.normal_deviation <= ANGLE); + // Inside, the fill stays near the cylinder it was cut from (it is the least-bending surface + // with the cylinder's boundary data, not the cylinder itself). + let mut worst = 0.0f64; + for k in 1..20 { + for j in 1..20 { + let (ang, z) = (-a + 2.0 * a * k as f64 / 20.0, h * j as f64 / 20.0); + // The fill's point nearest this cylinder point, by a coarse search. + let target = radial(ang) * r + Vec3::Z * z; + let mut best = f64::INFINITY; + for u in 0..=120 { + for v in 0..=120 { + best = best.min(at(&f.surface, u as f64 / 120.0, v as f64 / 120.0).dist(target)); + } + } + worst = worst.max(best); + } + } + eprintln!("window: the cylinder is within {worst} of the fill"); + assert!(worst < 0.25, "{worst}"); +} + +#[test] +fn a_planar_polygon_is_its_plane_and_a_point_lifts_it() { + // An L-shaped hexagon (one reflex corner) in z = 0, its neighbours standing up around it. + let c = [[0.0, 0.0], [20.0, 0.0], [20.0, 10.0], [10.0, 10.0], [10.0, 20.0], [0.0, 20.0]]; + let mut stations = |k: usize, ts: &[f64]| -> Result, String> { + let (Some(a), Some(b)) = (c.get(k), c.get((k + 1) % 6)) else { return Err("no side".into()) }; + let tangent = Vec3::new(b[0] - a[0], b[1] - a[1], 0.0).normalized().ok_or("no tangent")?; + let inward = Vec3::Z.cross(tangent); + Ok(ts + .iter() + .map(|t| { + let p = Vec3::new(a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, 0.0); + Station { p, up: Vec3::Z, across: Some(Across { leave: inward, normal: Vec3::Z, bend: None }), corner: *t == 0.0, clash: false } + }) + .collect()) + }; + let f = fill_general(6, &mut stations, &spec(&[])).unwrap(); + let mut off = 0.0f64; + for i in 0..=20 { + for j in 0..=20 { + off = off.max(at(&f.surface, i as f64 / 20.0, j as f64 / 20.0).z.abs()); + } + } + eprintln!("L: {:?} spans, the plane within {off:e}", f.spans); + assert!(off < 1e-8, "{off}"); + // G0 with a point 3 above the inside of the L: the surface passes through it. + let mut g0 = |k: usize, ts: &[f64]| stations(k, ts).map(|v| v.into_iter().map(|s| Station { across: None, ..s }).collect()); + let point = [Vec3::new(5.0, 5.0, 3.0)]; + let f = fill_general(6, &mut g0, &spec(&point)).unwrap(); + eprintln!("L through a point: {:?} spans, off the loop {:e}, off the point {:e}", f.spans, f.deviation, f.point_deviation); + assert!(f.deviation <= TOL && f.point_deviation <= TOL); +} + +#[test] +fn hostile_loops_and_specs_are_refused() { + let ok = |s: &FillSpec| fill_general(1, &mut tube_end(10.0, false), s); + for (tol, angle, crown) in + [(0.0, ANGLE, 0.0), (f64::NAN, ANGLE, 0.0), (TOL, -1.0, 0.0), (TOL, ANGLE, f64::NAN), (TOL, ANGLE, -0.95), (TOL, ANGLE, 1e300)] + { + assert!(ok(&FillSpec { tol, angle_tol: angle, crown, points: &[] }).is_err(), "{tol} {angle} {crown}"); + } + assert!(ok(&spec(&[Vec3::new(f64::NAN, 0.0, 0.0)])).is_err()); + assert!(ok(&spec(&vec![Vec3::ZERO; MAX_FILL_POINTS + 1])).is_err()); + // A point not over the inside of the loop. + assert!(ok(&spec(&[Vec3::new(30.0, 0.0, 0.0)])).is_err()); + assert!(fill_general(0, &mut tube_end(10.0, false), &spec(&[])).is_err()); + assert!(fill_general(10_000, &mut tube_end(10.0, false), &spec(&[])).is_err()); + assert!(fill_general(1, &mut |_, _| Err("no".into()), &spec(&[])).is_err()); + assert!( + fill_general( + 1, + &mut |_, ts| Ok(vec![Station { p: Vec3::ZERO, up: Vec3::Z, across: None, corner: false, clash: false }; ts.len()]), + &spec(&[]) + ) + .is_err() + ); + // A loop that runs out and straight back. + let mut spike = |_: usize, ts: &[f64]| -> Result, String> { + Ok(ts + .iter() + .map(|t| Station { p: Vec3::X * (1.0 - (2.0 * t - 1.0f64).abs()) * 10.0, up: Vec3::Z, across: None, corner: false, clash: false }) + .collect()) + }; + assert!(fill_general(1, &mut spike, &spec(&[])).is_err()); + // A figure eight: its development crosses itself. + let mut eight = |_: usize, ts: &[f64]| -> Result, String> { + Ok(ts + .iter() + .map(|t| { + let a = t * TAU; + Station { p: Vec3::new(10.0 * a.sin(), 5.0 * (2.0 * a).sin(), 0.0), up: Vec3::Z, across: None, corner: false, clash: false } + }) + .collect()) + }; + assert!(fill_general(1, &mut eight, &spec(&[])).is_err()); + // Huge and tiny loops do not panic. + for scale in [1e300, 1e-300] { + let mut s = |_: usize, ts: &[f64]| -> Result, String> { + Ok(ts.iter().map(|t| Station { p: radial(t * TAU) * scale, up: Vec3::Z, across: None, corner: false, clash: false }).collect()) + }; + let _ = fill_general(1, &mut s, &spec(&[])); + } +} diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index 21e44948e..850f471f1 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -14,6 +14,7 @@ pub mod bspline; pub mod compare; pub mod env; pub mod fill; +pub mod fill_general; mod mesh; mod plane; mod profile; diff --git a/crates/kernel/src/bridge.rs b/crates/kernel/src/bridge.rs index 1b55c40a5..23db38744 100644 --- a/crates/kernel/src/bridge.rs +++ b/crates/kernel/src/bridge.rs @@ -191,44 +191,115 @@ pub fn frames(face: &mt::Face, edges: &[mt::Edge], leave: Vec3, count: usize) -> 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 surf = face.surface(); - let (Some(range_u), Some(range_v)) = surf.try_range_tuple() else { - return Err(KernelError::Failed("bridge: the support surface is unbounded".into())); + 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())) }; - // A face's own edges may sit a fit tolerance off its surface (a cylinder's wall as a NURBS - // next to its exact ring), so the projection is only asked to be close, not exact. - let tol = (length * 1e-4).max(1e-6); - // Finite-difference step: a thousandth of the chain, so curvature over the chain is read - // locally but round-off stays far below the geometry. - let mut step = (length * 1e-3).clamp(1e-6, 0.5); let mut out = Vec::with_capacity(pts.len()); - // The station before this one, as the hint for the projection: it keeps the search on the - // same side of a periodic or split surface. - let mut hint: Option<(f64, f64)> = None; for p in &pts { - let project = |hint: Option<(f64, f64)>| surf.search_nearest_parameter(p3(*p), hint, 100); - let close = |uv: (f64, f64)| from_p3(surf.subs(uv.0, uv.1)).dist(*p) <= tol; + out.push(support.station(*p, &along, &mut walk, true)?.0); + } + Ok(out) +} + +/// The frames of `face` at stations on its own boundary, each leaving the face straight across +/// that boundary: `stations` are points on the boundary with the boundary's direction there *as +/// the face's own boundary runs* (its wires as [`mt::Face::boundaries`] gives them), and the leave +/// direction is that direction × the face's outward normal — in the face's tangent plane, at +/// right angles to the boundary, away from the face. `length` is the size of the boundary the +/// stations are on (it sets how closely a station must lie on the surface and the step the shape +/// is read with). Each frame comes with the face's unit normal there (as the face is oriented). +/// With `shape` false only the leave direction and the normal are read (`bend` and +/// `bend_change` are zero), which needs no room on the surface beside the station. +pub fn frames_across(face: &mt::Face, stations: &[(Vec3, Vec3)], length: f64, shape: bool) -> Result> { + if stations.len() > 1 << 16 || !(length.is_finite() && length > 0.0) { + return Err(KernelError::Invalid("frames across a boundary need at most 65536 stations on a boundary of finite size".into())); + } + let support = Support::of(face, length)?; + let outward = if face.orientation() { 1.0 } else { -1.0 }; + let mut walk = Walk::new(length); + let mut out = Vec::with_capacity(stations.len()); + for (p, tangent) in stations { + if !p.is_finite() || !tangent.is_finite() { + return Err(KernelError::Invalid("a boundary station must be finite".into())); + } + let away = |n: Vec3| -> Result { + tangent.cross(n * outward).normalized().ok_or_else(|| KernelError::Invalid("the boundary runs along the face's normal".to_string())) + }; + let (frame, normal) = support.station(*p, &away, &mut walk, shape)?; + out.push((frame, normal * outward)); + } + Ok(out) +} + +/// A support surface read at stations: the surface, its parameter box, and how close a station +/// must lie to it. +struct Support { + surf: mt::Surface, + range_u: (f64, f64), + range_v: (f64, f64), + tol: f64, +} + +/// What reading one station hands on to the next: the station's parameters (the hint for the +/// next projection, which keeps the search on the same side of a periodic or split surface) and +/// the finite-difference step that worked. +struct Walk { + hint: Option<(f64, f64)>, + step: f64, +} + +impl Walk { + fn new(length: f64) -> Walk { + // Finite-difference step: a thousandth of the chain, so curvature over the chain is read + // locally but round-off stays far below the geometry. + Walk { hint: None, step: (length * 1e-3).clamp(1e-6, 0.5) } + } +} + +impl Support { + fn of(face: &mt::Face, length: f64) -> Result { + let surf = face.surface(); + let (Some(range_u), Some(range_v)) = surf.try_range_tuple() else { + return Err(KernelError::Failed("bridge: the support surface is unbounded".into())); + }; + // A face's own edges may sit a fit tolerance off its surface (a cylinder's wall as a NURBS + // next to its exact ring), so the projection is only asked to be close, not exact. + let tol = (length * 1e-4).max(1e-6); + Ok(Support { surf, range_u, range_v, tol }) + } + + /// The frame at `p`, leaving in `leave(n)` (`n` the surface's unit normal there), and that + /// normal. Without `read_shape`, the frame's shape is left at zero. + fn station(&self, p: Vec3, leave: &dyn Fn(Vec3) -> Result, walk: &mut Walk, read_shape: bool) -> Result<(Frame, Vec3)> { + let (surf, range_u, range_v, tol) = (&self.surf, self.range_u, self.range_v, self.tol); + let project = |hint: Option<(f64, f64)>| surf.search_nearest_parameter(p3(p), hint, 100); + let close = |uv: (f64, f64)| from_p3(surf.subs(uv.0, uv.1)).dist(p) <= tol; // The station before this one is the hint where it lands close; a chain that wraps the // surface (or a periodic one) falls back to a free search. - let (u, v) = match project(hint).filter(|uv| close(*uv)).or_else(|| project(None).filter(|uv| close(*uv))) { + let (u, v) = match project(walk.hint).filter(|uv| close(*uv)).or_else(|| project(None).filter(|uv| close(*uv))) { Some(uv) => uv, None => return Err(KernelError::Invalid("a picked edge is not on the support surface".into())), }; - hint = Some((u, v)); + walk.hint = Some((u, v)); let at = from_p3(surf.subs(u, v)); - if at.dist(*p) > tol { + if at.dist(p) > tol { return Err(KernelError::Invalid("a picked edge is not on the support surface".into())); } let normal = surf.normal(u, v); let n = Vec3::new(normal.x, normal.y, normal.z) .normalized() .ok_or_else(|| KernelError::Failed("bridge: the support surface has no normal".into()))?; - let w = (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 w = leave(n)?; + if !read_shape { + return Ok((Frame { p, leave: w, bend: Vec3::ZERO, bend_change: Vec3::ZERO }, n)); + } // Parameter-space direction that leaves in `w` at unit 3D speed: S_u·du + S_v·dv = w. - let su = tangent(&surf, u, v, range_u, true); - let sv = tangent(&surf, u, v, range_v, false); + let su = tangent(surf, u, v, range_u, true); + let sv = tangent(surf, u, v, range_v, false); let (a, b, c) = (su.dot(su), su.dot(sv), sv.dot(sv)); let det = a * c - b * b; let scale = a.max(c).max(1e-30); @@ -260,7 +331,7 @@ pub fn frames(face: &mt::Face, edges: &[mt::Edge], leave: Vec3, count: usize) -> None } }; - let mut h = step; + let mut h = walk.step; let mut chosen = pick(h); for _ in 0..8 { if chosen.is_some() { @@ -299,10 +370,9 @@ pub fn frames(face: &mt::Face, edges: &[mt::Edge], leave: Vec3, count: usize) -> // against the leave direction: the curvature vector is the same either way, the change of // curvature turns round with the direction of travel. let bend_change = if t.dot(w) < 0.0 { -bend_change } else { bend_change }; - out.push(Frame { p: *p, leave: w, bend, bend_change }); - step = h; + walk.step = h; + Ok((Frame { p, leave: w, bend, bend_change }, n)) } - Ok(out) } /// A first derivative of the surface in one parameter, by central differences (one-sided where diff --git a/crates/kernel/src/fill.rs b/crates/kernel/src/fill.rs index 90e80d965..29ea2b2fa 100644 --- a/crates/kernel/src/fill.rs +++ b/crates/kernel/src/fill.rs @@ -1,16 +1,259 @@ -//! Filling a closed loop of a body's edges that is not planar with one face: a B-spline height -//! field over the loop's best-fit plane (`solidcraft_geom::fill::fill_loop`), bounded by the -//! body's own edges, whole. Loops that do not bound a height field over a plane are refused. +//! Filling a closed loop of a body's edges that is not planar with one face, bounded by the +//! body's own edges, whole: a B-spline height field over the loop's best-fit plane +//! (`solidcraft_geom::fill::fill_loop`) when the patch only has to meet the edges (G0) and the +//! loop bounds one; otherwise the general fill (`solidcraft_geom::fill_general`), developed from +//! the loop itself, which also meets the faces beside the loop with G1 or G2 and passes through +//! given points. use solidcraft_geom::Vec3; use solidcraft_geom::bspline::SplineError; +use solidcraft_geom::fill_general::{Across, FillSpec, MAX_FILL_POINTS, Station}; use truck_modeling as mt; use crate::body::{Body, from_p3}; +use crate::bridge::{Continuity, frames_across}; use crate::plane_fit::EdgeSampler; use crate::record::{Rebuild, rebuilt_body}; use crate::{KernelError, Result}; +/// How far (degrees) a G1 or G2 patch's normal may turn from its neighbour's along the loop. +pub const PATCH_ANGLE_TOL_DEG: f64 = 0.05; + +/// A spline error as the patch reports it. +fn spline_error(e: SplineError) -> KernelError { + match e { + SplineError::Unsupported(m) => KernelError::Invalid(format!("not supported yet: {m}")), + other => KernelError::Invalid(format!("cannot fill the loop: {other}")), + } +} + +/// What a patch on a loop of edges must do besides filling it. +#[derive(Clone, Debug, PartialEq)] +pub struct PatchSpec { + /// How every edge's neighbour is met (G0, G1 or G2). + pub continuity: Continuity, + /// Edges met otherwise: a point on the edge and its continuity. + pub edges: Vec<(Vec3, Continuity)>, + /// Points the patch passes through. + pub points: Vec, + /// How full the patch's middle is, `crown` times the loop's size (−0.9…3): the bump of + /// [`patch_edges_crowned`], laid along the general fill's own normal there (to the side its + /// G1/G2 neighbours' normals face) on control points clear of the loop, so the loop and the + /// conditions across it do not move. A general fill needs a G1 or G2 edge to crown. + pub crown: f64, +} + +impl Default for PatchSpec { + fn default() -> PatchSpec { + PatchSpec { continuity: Continuity::G0, edges: Vec::new(), points: Vec::new(), crown: 0.0 } + } +} + +impl PatchSpec { + /// Whether this is the plain patch of [`patch_edges_crowned`]: G0 everywhere, no points. + pub fn is_plain(&self) -> bool { + self.continuity == Continuity::G0 && self.edges.iter().all(|(_, g)| *g == Continuity::G0) && self.points.is_empty() + } +} + +/// What a general fill achieved (all zero for a planar or height-field patch, which meet their +/// edges within [`face_tolerance`] and ask nothing else). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct PatchReport { + /// Whether the general fill made the face. + pub general: bool, + /// The farthest loop station from the surface. + pub gap: f64, + /// The largest angle (degrees) between the patch's normal and a G1/G2 neighbour's, away from + /// corners where the neighbours themselves disagree, and anywhere. + pub normal_deviation_deg: f64, + pub normal_deviation_all_deg: f64, + /// The largest difference (1/mm) between the patch's normal curvature across a G2 edge and + /// the neighbour's. + pub curvature_mismatch: f64, + /// The farthest point from the surface. + pub point_gap: f64, +} + +/// [`crate::patch_edges`] meeting the faces beside the loop with the continuity `spec` asks for +/// and passing through its points; a plain spec is exactly [`patch_edges_crowned`]. Its history +/// is over `[body]`: the face is new, its edges the body's own. +pub fn patch_edges_with(body: &Body, at: &[Vec3], spec: &PatchSpec) -> Result { + patch_edges_report(body, at, spec).map(|(b, _)| b) +} + +/// [`patch_edges_with`] and what the fill achieved. +pub fn patch_edges_report(body: &Body, at: &[Vec3], spec: &PatchSpec) -> Result<(Body, PatchReport)> { + if at.is_empty() || at.len() > 10_000 { + return Err(KernelError::Invalid("pick the edges of a closed loop".into())); + } + // A range test also throws out NaN. + if !(solidcraft_geom::fill::MIN_CROWN..=solidcraft_geom::fill::MAX_CROWN).contains(&spec.crown) { + return Err(KernelError::Invalid("a patch's crown must be between -0.9 and 3".into())); + } + let g3 = |g: Continuity| g == Continuity::G3; + if g3(spec.continuity) || spec.edges.iter().any(|(_, g)| g3(*g)) { + return Err(KernelError::Invalid("not supported yet: a patch meets its neighbours with g0, g1 or g2".into())); + } + if spec.edges.len() > 10_000 || spec.edges.iter().any(|(p, _)| !p.is_finite()) { + return Err(KernelError::Invalid("pick at most 10000 edges, each by a finite point, for their continuity".into())); + } + if spec.points.len() > MAX_FILL_POINTS || spec.points.iter().any(|p| !p.is_finite()) { + return Err(KernelError::Invalid(format!("a patch passes through at most {MAX_FILL_POINTS} finite points"))); + } + if spec.is_plain() { + return patch_edges_crowned(body, at, spec.crown).map(|b| (b, PatchReport::default())); + } + body.require_brep("patch")?; + crate::guard("patch", || { + let chain = crate::surfaces::picked_loop(body, at)?; + let mut orders = vec![spec.continuity; chain.len()]; + for (p, g) in &spec.edges { + let e = crate::surfaces::edge_near(body, *p).ok_or_else(|| KernelError::Invalid(format!("no edge at {p:?}")))?; + let k = chain + .iter() + .position(|c| c.id() == e.id()) + .ok_or_else(|| KernelError::Invalid("a continuity pick is not on an edge of the loop".into()))?; + if let Some(slot) = orders.get_mut(k) { + *slot = *g; + } + } + if spec.crown != 0.0 && orders.iter().all(|g| *g == Continuity::G0) { + return Err(KernelError::Invalid("not supported yet: a crown on a patch through points with no g1 or g2 edge".into())); + } + general_fill(body, &chain, &orders, &spec.points, spec.crown) + }) +} + +/// One edge of the loop as the general fill samples it. +struct Side { + sampler: EdgeSampler, + start: Vec3, + /// The face beside the edge, and whether its boundary runs the edge the way the loop does. + face: mt::Face, + along: bool, + order: Continuity, + /// The loop has a corner at the edge's start, and the neighbours' tangent planes disagree + /// there. + corner: bool, + clash: bool, +} + +impl Side { + fn point(&mut self, t: f64) -> Option { + // The loop's corners are its vertices (an imported edge's curve may end a little off). + if t <= 0.0 { Some(self.start) } else { self.sampler.at(t) } + } + + /// The loop's unit tangent at `t`, by a central difference (one-sided at the ends). + fn tangent(&mut self, t: f64) -> Option { + const STEP: f64 = 1e-4; + let (a, b) = ((t - STEP).max(0.0), (t + STEP).min(1.0)); + let (p, q) = (self.sampler.at(a)?, self.sampler.at(b)?); + (q - p).normalized() + } + + /// The face's frames at points of this edge with the loop's tangents there. + fn frames(&self, stations: &[(Vec3, Vec3)], size: f64, shape: bool) -> Result> { + let along: Vec<(Vec3, Vec3)> = stations.iter().map(|(p, t)| (*p, if self.along { *t } else { *t * -1.0 })).collect(); + frames_across(&self.face, &along, size, shape) + } +} + +/// The general fill of the closed loop `chain` of `body`'s edges, edge `k` meeting the face beside +/// it with `orders[k]`, passing through `points`, its middle made fuller by `crown` (see +/// [`PatchSpec::crown`]). Call it under [`crate::guard`]. +pub(crate) fn general_fill(body: &Body, chain: &[mt::Edge], orders: &[Continuity], points: &[Vec3], crown: f64) -> Result<(Body, PatchReport)> { + let tol = face_tolerance(body); + let size = body.size().max(solidcraft_geom::LINEAR_TOL); + let mut sides: Vec = Vec::with_capacity(chain.len()); + for (e, order) in chain.iter().zip(orders) { + let faces: Vec<&mt::Face> = body.solid.face_iter().filter(|f| f.edge_iter().any(|x| x.id() == e.id())).collect(); + let face = match faces.as_slice() { + [f] => (*f).clone(), + [f, ..] if *order == Continuity::G0 => (*f).clone(), + [] => return Err(KernelError::Failed("patch: an edge of the loop bounds no face".into())), + _ => return Err(KernelError::Invalid("an edge of the loop lies between two faces: g1 and g2 need the one face beside it".into())), + }; + let along = face + .boundaries() + .iter() + .flat_map(|w| w.edge_iter()) + .find(|x| x.id() == e.id()) + .map(|x| x.orientation() == e.orientation()) + .ok_or_else(|| KernelError::Failed("patch: the face beside an edge does not hold it".into()))?; + let sampler = EdgeSampler::new(e).ok_or_else(|| KernelError::Invalid("an edge has no parameter range".into()))?; + sides.push(Side { sampler, start: from_p3(e.front().point()), face, along, order: *order, corner: false, clash: false }); + } + // The corners: where the loop's tangent turns, and where the faces beside it disagree. + let n = sides.len(); + for k in 0..n { + let prev = (k + n - 1) % n; + let (Some(t_in), Some(t_out)) = (sides.get_mut(prev).and_then(|s| s.tangent(1.0)), sides.get_mut(k).and_then(|s| s.tangent(0.0))) else { + return Err(KernelError::Invalid("an edge of the loop has no tangent".into())); + }; + let Some(vertex) = sides.get(k).map(|s| s.start) else { continue }; + let corner = t_in.dot(t_out) < CORNER_DEG.to_radians().cos(); + let normal = |s: Option<&Side>, t: Vec3| -> Result { + let s = s.ok_or_else(|| KernelError::Failed("patch: side".into()))?; + let f = s.frames(&[(vertex, t)], size, false)?; + f.first().map(|f| f.1).ok_or_else(|| KernelError::Failed("patch: frame".into())) + }; + let g1 = |s: Option<&Side>| s.is_some_and(|s| s.order != Continuity::G0); + let clash = if g1(sides.get(prev)) || g1(sides.get(k)) { + let (a, b) = (normal(sides.get(prev), t_in)?, normal(sides.get(k), t_out)?); + a.dot(b).abs() < (2.0 * PATCH_ANGLE_TOL_DEG).to_radians().cos() + } else { + false + }; + if let Some(s) = sides.get_mut(k) { + s.corner = corner; + s.clash = clash; + } + } + let mut stations = |k: usize, ts: &[f64]| -> std::result::Result, String> { + let side = sides.get_mut(k).ok_or("no such side")?; + let mut at = Vec::with_capacity(ts.len()); + for &t in ts { + let (Some(p), Some(tangent)) = (side.point(t), side.tangent(t)) else { return Err("an edge cannot be sampled".into()) }; + at.push((p, tangent)); + } + let frames = side.frames(&at, size, side.order == Continuity::G2).map_err(|e| e.to_string())?; + let mut out = Vec::with_capacity(ts.len()); + for ((&t, (p, tangent)), (frame, normal)) in ts.iter().zip(&at).zip(&frames) { + let up = tangent.cross(frame.leave).normalized().ok_or("the loop runs across its neighbour")?; + let across = (side.order != Continuity::G0).then(|| Across { + leave: frame.leave, + normal: *normal, + bend: (side.order == Continuity::G2).then_some(frame.bend), + }); + let first = t <= 0.0; + out.push(Station { p: *p, up, across, corner: first && side.corner, clash: first && side.clash }); + } + Ok(out) + }; + let spec = FillSpec { tol, angle_tol: PATCH_ANGLE_TOL_DEG.to_radians(), crown, points }; + let fill = solidcraft_geom::fill_general::fill_general(chain.len(), &mut stations, &spec).map_err(spline_error)?; + // The wire runs counter-clockwise about the surface's normal. + let wire: mt::Wire = + if fill.counter_clockwise { chain.to_vec().into() } else { chain.iter().rev().map(mt::Edge::inverse).collect::>().into() }; + let face = mt::Face::try_new(vec![wire], crate::spline_conv::surface(&fill.surface)?).map_err(|e| KernelError::Failed(format!("fill: {e}")))?; + let mut rec = Rebuild::default(); + rec.made(&face, Vec::new()); + let report = PatchReport { + general: true, + gap: fill.deviation, + normal_deviation_deg: fill.normal_deviation.to_degrees(), + normal_deviation_all_deg: fill.normal_deviation_all.to_degrees(), + curvature_mismatch: fill.curvature_mismatch, + point_gap: fill.point_deviation, + }; + Ok((rebuilt_body(crate::surfaces::surface_body(vec![face]), &[&body.solid], &rec), report)) +} + +/// The loop turns by more than this (degrees) at a corner: its stations hold position only. +const CORNER_DEG: f64 = 1.0; + /// A surface body of one face filling the closed loop `chain` of `body`'s edges (each edge /// oriented along the loop, each ending where the next starts), within [`face_tolerance`] of /// every edge. Its history is over `[body]`: the face is new, its edges the body's own. Call it @@ -34,10 +277,16 @@ pub(crate) fn fill_loop_crowned(body: &Body, chain: &[mt::Edge], crown: f64) -> // The loop's corners are its vertices (an imported edge's curve may end a little off). if t <= 0.0 { Some(*start) } else { sampler.at(t) } }; - let fill = solidcraft_geom::fill::fill_loop(chain.len(), &mut point, tol, crown).map_err(|e| match e { - SplineError::Unsupported(m) => KernelError::Invalid(format!("not supported yet: {m}")), - other => KernelError::Invalid(format!("cannot fill the loop: {other}")), - })?; + let fill = match solidcraft_geom::fill::fill_loop(chain.len(), &mut point, tol, crown) { + Ok(fill) => fill, + // Not a height field over its plane (or too wavy for one): the general fill, developed + // from the loop itself, when no crown asks for the height field's bump. + Err(SplineError::Unsupported(_)) if crown == 0.0 => { + let orders = vec![Continuity::G0; chain.len()]; + return general_fill(body, chain, &orders, &[], 0.0).map(|(b, _)| b); + } + Err(e) => return Err(spline_error(e)), + }; // The wire runs counter-clockwise about the surface's normal. let wire: mt::Wire = if fill.counter_clockwise { chain.to_vec().into() } else { chain.iter().rev().map(mt::Edge::inverse).collect::>().into() }; @@ -489,9 +738,11 @@ mod tests { } #[test] - fn a_loop_that_does_not_bound_a_height_field_is_refused() { + fn a_loop_that_does_not_bound_a_height_field_fills_with_one_face() { // Half a round post's side: two straight edges up and two half circles, whose plane - // stands on the post's axis; the half circles run along its normal at their ends. + // stands on the post's axis; the half circles run along its normal at their ends, so no + // height field over it bounds them (the height-field fill refuses it). The general fill + // (#759) fills it with one face on its four edges. let post = cylinder(Vec3::ZERO, Vec3::Z, 10.0, 20.0).unwrap(); let halves = crate::split_by_plane(&post, &Plane::from_normal(Vec3::ZERO, Vec3::X).unwrap()).unwrap(); let half = halves.into_iter().find(|b| measure(b).unwrap().bbox.min.x > -1e-6).unwrap(); @@ -499,9 +750,16 @@ mod tests { (-4..=4).map(|k| Vec2::from_angle(k as f64 * 0.35).extend(10.0) * 1.0).map(|p| Vec3::new(p.x * 10.0, p.y * 10.0, 10.0)).collect(); let side = copy_faces(&half, &at).unwrap(); let rim = free_edge_points(&side); - let err = patch_edges(&side, &rim).unwrap_err().to_string(); - eprintln!("half a post's side: {err}"); - assert!(err.contains("not supported yet"), "{err}"); + let fill = patch_edges(&side, &rim).unwrap(); + assert_eq!(fill.face_count(), 1, "one face"); + let face = fill.solid.face_iter().next().unwrap().clone(); + let (off, tol) = (edges_off_surface(&face), super::face_tolerance(&side)); + assert!(off <= tol, "an edge is {off} off the face (tolerance {tol})"); + // Its area is at least its shadow on the plane x = 0 (the 20 × 20 square the loop bounds + // there) and, a least-bending fill, no more than the half side it spans. + let area = measure(&fill).unwrap().area; + eprintln!("half a post's side: one face of area {area}, its edges within {off:e}"); + assert!(area > 400.0 && area < std::f64::consts::PI * 10.0 * 20.0, "{area}"); } #[test] @@ -611,3 +869,7 @@ mod tests { } } } + +#[cfg(test)] +#[path = "fill_general_tests.rs"] +mod general_tests; diff --git a/crates/kernel/src/fill_general_tests.rs b/crates/kernel/src/fill_general_tests.rs new file mode 100644 index 000000000..3ac620ca3 --- /dev/null +++ b/crates/kernel/src/fill_general_tests.rs @@ -0,0 +1,506 @@ +//! The general fill on bodies (#759): G1 and G2 to the faces beside the loop, loops that are not +//! height fields, N-sided loops and points the patch passes through. Every number is checked +//! against the analytic surface the loop was cut from, or against a quadrature of the fitted +//! surface itself, never against the mesher alone. + +use mt::{BoundedCurve, InnerSpace, ParametricCurve, ParametricSurface, ParametricSurface3D}; +use solidcraft_geom::{Loop2, Plane, Region2, Vec2, Vec3}; +use truck_modeling as mt; + +use super::{PATCH_ANGLE_TOL_DEG, PatchReport, PatchSpec, face_tolerance, patch_edges_report}; +use crate::body::{Body, from_p3, p3}; +use crate::bridge::Continuity; +use crate::{BoolOp, boolean, box_solid, copy_faces, cylinder, extrude, measure, patch_edges, stitch, torus}; + +/// The surface's parameters nearest `p`: the nearest of a grid of samples (or `hint`), then +/// Gauss–Newton within the domain. +fn nearest(s: &mt::Surface, p: Vec3, hint: Option<(f64, f64)>) -> (f64, f64) { + let (Some((u0, u1)), Some((v0, v1))) = s.try_range_tuple() else { panic!("a bounded surface") }; + let p = p3(p); + let (mut u, mut v) = match hint { + Some(h) => h, + None => { + let n = 100; + let mut best = (f64::MAX, u0, v0); + for i in 0..=n { + for j in 0..=n { + let (u, v) = (u0 + (u1 - u0) * i as f64 / n as f64, v0 + (v1 - v0) * j as f64 / n as f64); + let d = (s.subs(u, v) - p).magnitude(); + if d < best.0 { + best = (d, u, v); + } + } + } + (best.1, best.2) + } + }; + for _ in 0..60 { + let (q, a, b) = (s.subs(u, v), s.uder(u, v), s.vder(u, v)); + let r = q - p; + let (aa, ab, bb) = (a.dot(a), a.dot(b), b.dot(b)); + let det = aa * bb - ab * ab; + if det.abs() < 1e-300 { + break; + } + let (ga, gb) = (a.dot(r), b.dot(r)); + u = (u - (bb * ga - ab * gb) / det).clamp(u0, u1); + v = (v - (aa * gb - ab * ga) / det).clamp(v0, v1); + } + (u, v) +} + +fn v3(v: mt::Vector3) -> Vec3 { + Vec3::new(v.x, v.y, v.z) +} + +/// Points along every edge of the loop: `per` on each. +fn rim_points(face: &mt::Face, per: usize) -> Vec { + let mut out = Vec::new(); + for e in face.boundaries().iter().flat_map(|w| w.edge_iter()) { + let c = e.oriented_curve(); + let (t0, t1) = c.range_tuple(); + for k in 0..per { + out.push(from_p3(c.subs(t0 + (t1 - t0) * (k as f64 + 0.5) / per as f64))); + } + } + out +} + +/// Along the loop, densely: the farthest a rim point is from the patch, the largest angle +/// (degrees) between the patch's normal and the neighbour's exact one (`normal(p)`, one sign for +/// the whole loop: a fold would show as 180°), and the largest difference between the patch's +/// normal curvature across the loop and `curvature(p)`, the neighbour's. +fn along_the_loop(fill: &Body, normal: &dyn Fn(Vec3) -> Vec3, curvature: &dyn Fn(Vec3) -> f64) -> (f64, f64, f64) { + let face = fill.solid.face_iter().next().unwrap().clone(); + let s = face.surface(); + let pts = rim_points(&face, 200); + let mut found = Vec::with_capacity(pts.len()); + let mut hint = None; + for p in &pts { + let uv = nearest(&s, *p, hint); + hint = Some(uv); + found.push(uv); + } + // One sign for the whole loop: the one most rim points agree with. + let patch_normal = |(u, v): (f64, f64)| v3(s.normal(u, v)); + let agree: f64 = pts.iter().zip(&found).map(|(p, uv)| patch_normal(*uv).dot(normal(*p)).signum()).sum(); + let sign = agree.signum(); + let (mut gap, mut angle, mut kappa) = (0.0f64, 0.0f64, 0.0f64); + for (k, (p, &(u, v))) in pts.iter().zip(&found).enumerate() { + gap = gap.max(from_p3(s.subs(u, v)).dist(*p)); + let n = patch_normal((u, v)); + let want = normal(*p) * sign; + angle = angle.max(n.dot(want).clamp(-1.0, 1.0).acos().to_degrees()); + // Across the loop: the tangent-plane direction square to the rim. + let next = pts.get(k + 1).or(pts.get(k.wrapping_sub(1))).copied().unwrap(); + let t = (next - *p).normalized().unwrap(); + let Some(d) = n.cross(t).normalized() else { continue }; + let (su, sv) = (v3(s.uder(u, v)), v3(s.vder(u, v))); + // d = a·su + b·sv. + let (aa, ab, bb) = (su.dot(su), su.dot(sv), sv.dot(sv)); + let det = aa * bb - ab * ab; + let (a, b) = ((bb * d.dot(su) - ab * d.dot(sv)) / det, (aa * d.dot(sv) - ab * d.dot(su)) / det); + // The second derivatives by central differences of the surface's own points. + let h = 1e-3; + let e = |du: f64, dv: f64| from_p3(s.subs(u + du * h, v + dv * h)); + let suu = (e(1.0, 0.0) - e(0.0, 0.0) * 2.0 + e(-1.0, 0.0)) * (1.0 / (h * h)); + let svv = (e(0.0, 1.0) - e(0.0, 0.0) * 2.0 + e(0.0, -1.0)) * (1.0 / (h * h)); + let suv = (e(1.0, 1.0) - e(1.0, -1.0) - e(-1.0, 1.0) + e(-1.0, -1.0)) * (0.25 / (h * h)); + let second = suu * (a * a) + suv * (2.0 * a * b) + svv * (b * b); + kappa = kappa.max((second.dot(want) - curvature(*p)).abs()); + } + (gap, angle, kappa) +} + +/// `∫∫ f(S, S_u × S_v) du dv` over the face's own region of its surface (its loop taken into +/// parameter space by the nearest parameters of points along it), by the midpoint rule on a +/// `n × n` grid over the region's box: the quadrature the mesher's area is checked against. +fn quadrature(face: &mt::Face, n: usize, f: &dyn Fn(Vec3, Vec3) -> f64) -> f64 { + let s = face.surface(); + let mut poly: Vec<(f64, f64)> = Vec::new(); + let mut hint = None; + for p in rim_points(face, 400) { + let uv = nearest(&s, p, hint); + hint = Some(uv); + poly.push(uv); + } + let (mut lo, mut hi) = ((f64::MAX, f64::MAX), (f64::MIN, f64::MIN)); + for &(u, v) in &poly { + lo = (lo.0.min(u), lo.1.min(v)); + hi = (hi.0.max(u), hi.1.max(v)); + } + let inside = |u: f64, v: f64| { + let mut w = false; + for k in 0..poly.len() { + let (a, b) = (poly[k], poly[(k + 1) % poly.len()]); + if (a.1 > v) != (b.1 > v) && u < a.0 + (v - a.1) / (b.1 - a.1) * (b.0 - a.0) { + w = !w; + } + } + w + }; + let (du, dv) = ((hi.0 - lo.0) / n as f64, (hi.1 - lo.1) / n as f64); + let mut sum = 0.0; + for i in 0..n { + for j in 0..n { + let (u, v) = (lo.0 + (i as f64 + 0.5) * du, lo.1 + (j as f64 + 0.5) * dv); + if inside(u, v) { + sum += f(from_p3(s.subs(u, v)), v3(s.uder(u, v)).cross(v3(s.vder(u, v)))) * du * dv; + } + } + } + sum +} + +/// The fill is one face on the open body's own edges, within the fill's tolerance of them; its +/// mesh has no folded triangle (each faces the way its corners' normals do); and the mesher's +/// area agrees with a quadrature of the surface over its own region. Returns the area. +fn check_face(name: &str, open: &Body, fill: &Body) -> f64 { + assert!(fill.is_surface()); + assert_eq!(fill.face_count(), 1, "{name}: one face"); + let own: Vec = open.solid.edge_iter().map(|e| e.id()).collect(); + assert!(fill.solid.edge_iter().all(|e| own.contains(&e.id())), "{name}: an edge that is not the body's"); + let face = fill.solid.face_iter().next().unwrap().clone(); + let s = face.surface(); + let tol = face_tolerance(open); + let mut off = 0.0f64; + let mut hint = None; + for p in rim_points(&face, 64) { + let uv = nearest(&s, p, hint); + hint = Some(uv); + off = off.max(from_p3(s.subs(uv.0, uv.1)).dist(p)); + } + assert!(off <= tol * 1.01, "{name}: an edge is {off} off the face (tolerance {tol})"); + let m = fill.tessellate(0.01).unwrap(); + assert!(!m.triangles.is_empty(), "{name}: the face meshes"); + for t in &m.triangles { + let [a, b, c] = m.tri(t).unwrap(); + let v = (b - a).cross(c - a); + let n: Vec3 = t.iter().map(|&i| m.normals[i as usize]).fold(Vec3::ZERO, |s, x| s + x); + if v.len() > 1e-10 { + assert!(v.dot(n) > 0.0, "{name}: a folded triangle"); + } + } + let area = measure(fill).unwrap().area; + let quad = quadrature(&face, 500, &|_, n| n.len()); + eprintln!("{name}: one face, edges within {off:e} (tolerance {tol:e}), mesh area {area:.4}, quadrature {quad:.4}"); + assert!((area - quad).abs() < 3e-3 * quad, "{name}: mesh area {area} against the surface's {quad}"); + area +} + +fn spec(g: Continuity) -> PatchSpec { + PatchSpec { continuity: g, ..PatchSpec::default() } +} + +fn report(name: &str, r: &PatchReport) { + eprintln!( + "{name}: fill reports gap {:e}, normals within {:.4}° ({:.4}° near clashing corners), curvature mismatch {:e}, points within {:e}", + r.gap, r.normal_deviation_deg, r.normal_deviation_all_deg, r.curvature_mismatch, r.point_gap + ); +} + +/// A cylinder about z of radius 10 and 30 high with its top face taken off; points around the rim. +fn open_tube() -> (Body, Vec) { + let solid = cylinder(Vec3::ZERO, Vec3::Z, 10.0, 30.0).unwrap(); + let open = copy_faces(&solid, &[&around(10.0, 15.0)[..], &[Vec3::ZERO]].concat()).unwrap(); + assert!(open.is_surface()); + let rim = (0..8).map(|k| Vec2::from_angle(k as f64 * 0.785).extend(0.0) * 10.0 + Vec3::Z * 30.0).collect(); + (open, rim) +} + +/// `body` without its planar faces but those at height `z0` or `z1` (the ends of a cylinder): +/// a cut solid's walls (and ends) as a surface, the faces the cut made taken away. +fn curved_and_ends(body: &Body, ends: &[f64]) -> Body { + let drop: Vec = body + .solid + .face_iter() + .enumerate() + .filter(|(_, f)| match f.surface() { + mt::Surface::Plane(p) => !ends.iter().any(|z| (p.origin().z - z).abs() < 1e-9 && p.normal().z.abs() > 1.0 - 1e-12), + _ => false, + }) + .map(|(i, _)| i) + .collect(); + let open = crate::remove_faces(body, &drop).unwrap(); + assert!(open.is_surface()); + open +} + +/// A point on each edge that bounds only one face of `body` (its free edges): the middle of +/// each, where the edge picker samples it. +fn free_edge_points(body: &Body) -> Vec { + let mut uses: std::collections::HashMap = std::collections::HashMap::new(); + for f in body.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 points = uses + .values() + .filter(|(n, _)| *n == 1) + .map(|(_, e)| { + let c = e.curve(); + let (t0, t1) = c.range_tuple(); + from_p3(c.subs(0.5 * (t0 + t1))) + }) + .collect::>(); + // In a fixed order, whatever the map's. + points.sort_by(|a, b| (a.z, a.y, a.x).partial_cmp(&(b.z, b.y, b.x)).unwrap()); + points +} + +/// Points round the circle of radius `r` about z at height `z`, every 30°. +fn around(r: f64, z: f64) -> Vec { + (0..12).map(|k| Vec2::from_angle(0.1 + k as f64 * std::f64::consts::TAU / 12.0).extend(0.0) * r + Vec3::Z * z).collect() +} + +fn radial(p: Vec3) -> Vec3 { + Vec3::new(p.x, p.y, 0.0).normalized().unwrap() +} + +#[test] +fn an_opened_tube_end_capped_g1_and_g2_meets_the_wall() { + let (open, rim) = open_tube(); + let mut kappas = Vec::new(); + for g in [Continuity::G1, Continuity::G2] { + let name = format!("tube end {}", g.as_str()); + let started = std::time::Instant::now(); + let (fill, r) = patch_edges_report(&open, &rim, &spec(g)).unwrap(); + eprintln!("{name}: filled in {:?}", started.elapsed()); + report(&name, &r); + assert!(r.general); + let area = check_face(&name, &open, &fill); + // The wall's normal is radial and it does not bend along its axis. + let (gap, angle, kappa) = along_the_loop(&fill, &radial, &|_| 0.0); + eprintln!( + "{name}: along the rim (1600 points): within {gap:e} of it, normal within {angle:.5}° of the wall's, curvature across {kappa:e} /mm (the wall's 0)" + ); + assert!(angle < 0.1, "{name}: the normal turns {angle}° from the wall's"); + kappas.push(kappa); + // A dome over the rim, not a flat lid: more than the disc. + assert!(area > std::f64::consts::PI * 100.0 * 1.05, "{name}: {area}"); + // Sealed: the tube's volume plus the dome's, the dome's by the divergence theorem over the + // patch (∫∫ (z − 30)·n_z dA), independent of the mesher. + let closed = stitch(&[&open, &fill], 0.0).unwrap(); + assert!(!closed.is_surface(), "{name}: the cap closes the tube"); + let face = fill.solid.face_iter().next().unwrap().clone(); + let dome = quadrature(&face, 500, &|p, n| (p.z - 30.0) * n.z).abs(); + let (got, want) = (measure(&closed).unwrap().volume, std::f64::consts::PI * 100.0 * 30.0 + dome); + eprintln!("{name}: sealed volume {got:.3}, tube + dome {want:.3}"); + assert!((got - want).abs() < 2e-4 * want, "{name}: {got} vs {want}"); + } + eprintln!("tube end: curvature across the rim g1 {:e}, g2 {:e} /mm", kappas[0], kappas[1]); + assert!(kappas[1] < kappas[0], "g2 holds the wall's curvature closer than g1"); +} + +/// A cylinder about z (radius 10, 40 high) with a window `half` either side of the x axis +/// through its wall, from z = 15 to 25; the wall and both ends without the faces the cut made (the +/// window's edges bound only the wall), and a point on each of the window's edges. +fn windowed(half: f64) -> (Body, Body, Vec) { + let solid = cylinder(Vec3::ZERO, Vec3::Z, 10.0, 40.0).unwrap(); + let x = 10.0 * half.cos(); + let tool = box_solid(Vec3::new(x, -11.0, 15.0), Vec3::new(11.0, 11.0, 25.0)).unwrap(); + let cut = boolean(&solid, &tool, BoolOp::Cut).unwrap().unwrap(); + let open = curved_and_ends(&cut, &[0.0, 40.0]); + let rim = free_edge_points(&open); + (solid, open, rim) +} + +#[test] +fn a_window_cut_through_a_cylinder_wall_past_half_way_fills_g1_close_to_the_cylinder() { + // 240° round: seen along any direction the window folds over itself, so it bounds no height + // field; the old fill refused it. + let half = 2.0 * std::f64::consts::PI / 3.0; + let (solid, open, rim) = windowed(half); + for g in [Continuity::G0, Continuity::G1] { + let name = format!("window {}", g.as_str()); + let (fill, r) = patch_edges_report(&open, &rim, &spec(g)).unwrap(); + report(&name, &r); + let area = check_face(&name, &open, &fill); + let (gap, angle, _) = along_the_loop(&fill, &radial, &|_| 0.0); + eprintln!("{name}: along the window (1600 points): within {gap:e}, normal within {angle:.5}° of the wall's"); + // How far the fill strays from the cylinder it replaces, inside. + let face = fill.solid.face_iter().next().unwrap().clone(); + let s = face.surface(); + let (Some((u0, u1)), Some((v0, v1))) = s.try_range_tuple() else { panic!() }; + let mut stray = 0.0f64; + for i in 0..=40 { + for j in 0..=40 { + let p = from_p3(s.subs(u0 + (u1 - u0) * i as f64 / 40.0, v0 + (v1 - v0) * j as f64 / 40.0)); + let ang = p.y.atan2(p.x); + if ang.abs() < half - 0.05 && p.z > 15.5 && p.z < 24.5 { + stray = stray.max((Vec2::new(p.x, p.y).len() - 10.0).abs()); + } + } + } + let exact = 10.0 * 2.0 * half * 10.0; + let closed = stitch(&[&open, &fill], 0.0).unwrap(); + let (got, want) = (measure(&closed).unwrap().volume, measure(&solid).unwrap().volume); + eprintln!( + "{name}: area {area:.3} (the cylinder's window {exact:.3}), the fill within {stray:.4} of the cylinder inside, sealed volume {got:.2} against the whole cylinder's {want:.2}" + ); + assert!(!closed.is_surface()); + if g == Continuity::G1 { + assert!(angle < 0.1, "{name}: the normal turns {angle}° from the wall's"); + assert!((area - exact).abs() < 0.01 * exact && stray < 0.25, "{name}: {area} vs {exact}, stray {stray}"); + assert!((got - want).abs() < 0.005 * want, "{name}: {got} vs {want}"); + } + } +} + +#[test] +fn a_saddle_window_in_a_torus_fills_g0_and_g1() { + // The inner wall of a torus (major 20, minor 8) is saddle-shaped; a window 240° round it + // between z = ±3 bounds no height field. + let solid = torus(Vec3::ZERO, 20.0, 8.0).unwrap(); + let tool = box_solid(Vec3::new(-6.0, -13.0, -3.0), Vec3::new(13.0, 13.0, 3.0)).unwrap(); + let cut = boolean(&solid, &tool, BoolOp::Cut).unwrap().unwrap(); + let open = curved_and_ends(&cut, &[]); + let rim = free_edge_points(&open); + // The torus's normal: from the tube's centre circle. + let normal = |p: Vec3| { + let c = Vec3::new(p.x, p.y, 0.0).normalized().unwrap() * 20.0; + (p - c).normalized().unwrap() + }; + for g in [Continuity::G0, Continuity::G1] { + let name = format!("torus window {}", g.as_str()); + let (fill, r) = patch_edges_report(&open, &rim, &spec(g)).unwrap(); + report(&name, &r); + check_face(&name, &open, &fill); + let (gap, angle, _) = along_the_loop(&fill, &normal, &|_| 0.0); + eprintln!("{name}: along the window (1600 points): within {gap:e}, normal within {angle:.5}° of the torus's"); + if g == Continuity::G1 { + assert!(angle < 0.1, "{name}: {angle}°"); + } + } +} + +/// A cylinder about z (radius 10, 40 high) with a pentagonal pocket cut into its wall from the +/// +x side (the pentagon in the yz plane about z = 20, circumradius 6): the wall and both ends +/// copied out, and a point on each of the pocket rim's five edges. +fn pentagon_window() -> (Body, Vec) { + let solid = cylinder(Vec3::ZERO, Vec3::Z, 10.0, 40.0).unwrap(); + let corners: Vec = (0..5).map(|k| Vec2::from_angle(0.3 + k as f64 * std::f64::consts::TAU / 5.0) * 6.0 + Vec2::new(0.0, 20.0)).collect(); + let prism = extrude(&Plane::YZ, &[Region2 { outer: Loop2::polygon(&corners), holes: vec![] }], 0.0, 15.0).unwrap().pop().unwrap(); + let cut = boolean(&solid, &prism, BoolOp::Cut).unwrap().unwrap(); + let open = curved_and_ends(&cut, &[0.0, 40.0]); + let rim = free_edge_points(&open); + (open, rim) +} + +#[test] +fn a_five_sided_window_fills_as_one_face_g1_and_through_a_point() { + let (open, rim) = pentagon_window(); + let (fill, r) = patch_edges_report(&open, &rim, &spec(Continuity::G1)).unwrap(); + report("pentagon g1", &r); + assert!(fill.edge_count() >= 5, "the rim's own edges (five, or more where a seam splits one)"); + check_face("pentagon g1", &open, &fill); + let (gap, angle, _) = along_the_loop(&fill, &radial, &|_| 0.0); + eprintln!("pentagon g1: along the rim: within {gap:e}, normal within {angle:.5}° of the wall's"); + assert!(angle < 0.1, "{angle}°"); + // Through a point half a millimetre out from the wall in the middle (G0 and G1). + let point = Vec3::new(10.5, 0.0, 20.0); + for g in [Continuity::G0, Continuity::G1] { + let name = format!("pentagon {} through a point", g.as_str()); + let spec = PatchSpec { continuity: g, points: vec![point], ..PatchSpec::default() }; + let (fill, r) = patch_edges_report(&open, &rim, &spec).unwrap(); + report(&name, &r); + check_face(&name, &open, &fill); + let s = fill.solid.face_iter().next().unwrap().surface(); + let (u, v) = nearest(&s, point, None); + let off = from_p3(s.subs(u, v)).dist(point); + eprintln!("{name}: the point is {off:e} off the surface"); + assert!(off <= face_tolerance(&open), "{name}: {off}"); + } +} + +#[test] +fn a_hexagonal_rim_fills_through_a_point_and_g1_to_walls_meeting_at_angles_holds_away_from_the_corners() { + // A hexagonal prism's top cut by a sideways cylinder: six walls meeting at 120°. + let corners: Vec = (0..6).map(|k| Vec2::from_angle(0.3 + k as f64 * std::f64::consts::TAU / 6.0) * 20.0).collect(); + let prism = extrude(&Plane::XY, &[Region2 { outer: Loop2::polygon(&corners), holes: vec![] }], 0.0, 20.0).unwrap().pop().unwrap(); + let tool = cylinder(Vec3::new(0.0, -60.0, 50.0), Vec3::Y, 40.0, 120.0).unwrap(); + let solid = boolean(&prism, &tool, BoolOp::Cut).unwrap().unwrap(); + let mut keep = vec![Vec3::ZERO]; + let mut rim = Vec::new(); + for k in 0..6 { + let m = corners[k].lerp(corners[(k + 1) % 6], 0.5); + keep.push(m.extend(5.0)); + rim.push(m.extend(50.0 - (1600.0 - m.x * m.x).sqrt())); + } + let open = copy_faces(&solid, &keep).unwrap(); + let plain = patch_edges(&open, &rim).unwrap(); + let sealed = |f: &Body| measure(&stitch(&[&open, f], 0.0).unwrap()).unwrap().volume; + // Six sides, G0, through a point 3 mm above the middle of the plain fill: one face. + let s = plain.solid.face_iter().next().unwrap().surface(); + let (u, v) = nearest(&s, Vec3::new(0.0, 0.0, 12.0), None); + let point = from_p3(s.subs(u, v)) + Vec3::Z * 3.0; + let (lifted, r) = patch_edges_report(&open, &rim, &PatchSpec { points: vec![point], ..PatchSpec::default() }).unwrap(); + report("hexagon through a point", &r); + assert_eq!(lifted.edge_count(), 6, "the rim's own six edges"); + check_face("hexagon through a point", &open, &lifted); + let s = lifted.solid.face_iter().next().unwrap().surface(); + let (u, v) = nearest(&s, point, None); + let off = from_p3(s.subs(u, v)).dist(point); + eprintln!("hexagon through a point: the point is {off:e} off the surface; sealed {:.2} against {:.2} plain", sealed(&lifted), sealed(&plain)); + assert!(off <= face_tolerance(&open) && sealed(&lifted) > sealed(&plain)); + // G1 to the walls: at a corner no surface is tangent to both walls (its tangent plane there + // holds both rim edges), so G1 is asked only away from the corners. On walls standing square + // to the patch the corner is pinched too sharply for the finest grid to hold the rim within + // the fill's tolerance, and the fill says so. + match patch_edges_report(&open, &rim, &spec(Continuity::G1)) { + Ok((fill, r)) => { + report("hexagon g1", &r); + check_face("hexagon g1", &open, &fill); + assert!(r.normal_deviation_deg <= PATCH_ANGLE_TOL_DEG); + assert!(sealed(&fill) > sealed(&plain)); + } + Err(e) => { + eprintln!("hexagon g1: {e}"); + assert!(e.to_string().contains("not supported yet"), "{e}"); + } + } +} + +#[test] +fn per_edge_continuity_and_hostile_specs() { + let (open, rim) = pentagon_window(); + // G1 on two edges only. + let spec = PatchSpec { edges: vec![(rim[0], Continuity::G1), (rim[2], Continuity::G2)], ..PatchSpec::default() }; + let (fill, r) = patch_edges_report(&open, &rim, &spec).unwrap(); + report("pentagon, two edges g1/g2", &r); + check_face("pentagon, two edges g1/g2", &open, &fill); + let bad = |spec: PatchSpec| patch_edges_report(&open, &rim, &spec).is_err(); + let g1 = PatchSpec { continuity: Continuity::G1, ..PatchSpec::default() }; + assert!(bad(PatchSpec { continuity: Continuity::G3, ..g1.clone() })); + assert!(bad(PatchSpec { edges: vec![(rim[0], Continuity::G3)], ..g1.clone() })); + assert!(bad(PatchSpec { edges: vec![(Vec3::new(0.0, 0.0, 40.0), Continuity::G1)], ..g1.clone() }), "an edge off the loop"); + assert!(bad(PatchSpec { edges: vec![(Vec3::new(f64::NAN, 0.0, 0.0), Continuity::G1)], ..g1.clone() })); + assert!(bad(PatchSpec { points: vec![Vec3::new(f64::INFINITY, 0.0, 0.0)], ..g1.clone() })); + assert!(bad(PatchSpec { points: vec![Vec3::new(10.0, 0.0, 20.0); 65], ..g1.clone() })); + assert!(bad(PatchSpec { points: vec![Vec3::new(-10.0, 0.0, 20.0)], ..g1.clone() }), "a point off the far side"); + for crown in [f64::NAN, 3.5, -1.0] { + assert!(bad(PatchSpec { crown, ..g1.clone() }), "crown {crown}"); + } + assert!(bad(PatchSpec { crown: 0.1, points: vec![Vec3::new(10.2, 0.0, 20.0)], ..PatchSpec::default() }), "a crown with no g1 edge"); + // A crown fills the middle out from the wall (the side the wall's normals face) and leaves + // the loop, and G1 across it, as they were. + let (plain, _) = patch_edges_report(&open, &rim, &g1).unwrap(); + let (full, r) = patch_edges_report(&open, &rim, &PatchSpec { crown: 0.1, ..g1.clone() }).unwrap(); + report("pentagon g1 crown 0.1", &r); + check_face("pentagon g1 crown 0.1", &open, &full); + let (_, angle, _) = along_the_loop(&full, &radial, &|_| 0.0); + let middle = |b: &Body| { + let s = b.solid.face_iter().next().unwrap().surface(); + let (u, v) = nearest(&s, Vec3::new(10.0, 0.0, 20.0), None); + let p = from_p3(s.subs(u, v)); + Vec2::new(p.x, p.y).len() + }; + let (a, b) = (middle(&plain), middle(&full)); + eprintln!("pentagon g1: the middle {a:.4} from the axis plain, {b:.4} with crown 0.1; normal within {angle:.5}° of the wall's"); + assert!(b > a + 0.5 && angle < 0.1, "{a} {b} {angle}"); + // The edges of a closed solid lie between two faces: g1 has no one face to meet. + let b = box_solid(Vec3::ZERO, Vec3::new(10.0, 10.0, 10.0)).unwrap(); + let top = [Vec3::new(5.0, 0.0, 10.0), Vec3::new(10.0, 5.0, 10.0), Vec3::new(5.0, 10.0, 10.0), Vec3::new(0.0, 5.0, 10.0)]; + assert!(patch_edges_report(&b, &top, &PatchSpec { continuity: Continuity::G1, ..PatchSpec::default() }).is_err()); +} diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rs index 77ae5f6e7..212483729 100644 --- a/crates/kernel/src/lib.rs +++ b/crates/kernel/src/lib.rs @@ -122,14 +122,14 @@ 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 boolean_diagnostics::{BooleanDiagnostics, BooleanFallback, BooleanStrategy, capture_boolean_diagnostics}; -pub use bridge::{Continuity, Frame, blend_between, bridge, chain, chain_closes, frames, sample_grid}; +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, loft, revolve, sphere, sweep, sweep_with, torus, }; pub use delete_face::delete_faces; pub use emboss::{cylinder_emboss_anchor, emboss_cylinder, emboss_cylinder_at, has_cylinder_emboss_wall, infer_cylinder_emboss}; -pub use fill::patch_edges_crowned; +pub use fill::{PATCH_ANGLE_TOL_DEG, PatchReport, PatchSpec, patch_edges_crowned, patch_edges_report, patch_edges_with}; 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; diff --git a/crates/ui-egui/src/dialogs_surface.rs b/crates/ui-egui/src/dialogs_surface.rs index d235be7d9..7621066b2 100644 --- a/crates/ui-egui/src/dialogs_surface.rs +++ b/crates/ui-egui/src/dialogs_surface.rs @@ -9,7 +9,7 @@ use solidcraft_engine::geom::Vec3; use crate::SolveApp; use crate::dialogs::{Kind, OP_LABELS, OPS, combo, field, op_index, row_label}; -use crate::selection::{AXES, BODIES, CURVES, EDGES, FACES, PLANES, PROFILES, SelInput}; +use crate::selection::{AXES, BODIES, CURVES, EDGES, FACES, PLANES, PROFILES, SelInput, VERTICES}; /// A surface tool dialog's values. #[derive(Clone, Debug, PartialEq)] @@ -27,7 +27,11 @@ pub enum Surf { }, Sweep(crate::dialogs_sweep::SweepOpts), Loft, - Patch, + /// `continuity`: an index into [`PATCH_CONTINUITY`] (how a patch on edges meets the faces + /// beside its loop). + Patch { + continuity: usize, + }, Unstitch, ReverseNormal, Offset { @@ -70,7 +74,7 @@ impl Surf { Surf::Revolve { .. } => "SURFACE REVOLVE", Surf::Sweep(_) => "SURFACE SWEEP", Surf::Loft => "SURFACE LOFT", - Surf::Patch => "PATCH", + Surf::Patch { .. } => "PATCH", Surf::Unstitch => "UNSTITCH", Surf::ReverseNormal => "REVERSE NORMAL", Surf::Offset { .. } => "OFFSET SURFACE", @@ -97,6 +101,9 @@ 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")]; + /// Which holes Untrim takes away: every one, the picked ones, or none (the outer boundary only). const UNTRIM_HOLES: [&str; 3] = ["All", "Picked", "None"]; @@ -116,7 +123,7 @@ fn inputs(k: &Surf) -> Vec { crate::dialogs_sweep::direction_input(), ], Surf::Loft => vec![SelInput::new("Sections (one sketch each)", PROFILES | CURVES, true)], - Surf::Patch => vec![SelInput::new("Boundary", PROFILES | 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)], Surf::ReverseNormal => vec![SelInput::new("Surface, or faces to turn over", BODIES | FACES, true)], Surf::Offset { .. } => vec![SelInput::new("Faces", FACES, true)], @@ -143,7 +150,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, - "surface.patch" => Surf::Patch, + "surface.patch" => Surf::Patch { continuity: 0 }, "surface.unstitch" => Surf::Unstitch, "surface.reverse_normal" => Surf::ReverseNormal, "surface.offset" => Surf::Offset { distance: "2 mm".into(), chain: false }, @@ -247,8 +254,13 @@ pub fn rows(ui: &mut egui::Ui, k: &mut Surf) -> bool { ui.checkbox(in_place, ""); ui.end_row(); } + Surf::Patch { continuity } => { + row_label(ui, "Continuity"); + combo(ui, "pa_cont", &PATCH_CONTINUITY.map(|(label, _)| label), continuity); + ui.end_row(); + } Surf::Sweep(opts) => enter |= crate::dialogs_sweep::rows(ui, opts, "ss"), - Surf::Patch | Surf::Trim | Surf::SplitFace | Surf::Unstitch | Surf::ReverseNormal | Surf::Loft => {} + Surf::Trim | Surf::SplitFace | Surf::Unstitch | Surf::ReverseNormal | Surf::Loft => {} } enter } @@ -390,7 +402,7 @@ pub fn commands(app: &SolveApp, k: &Surf, inputs: &[SelInput], extra: &Map>()?; ("surface.loft", json!({ "sections": sections })) } - Surf::Patch => { + Surf::Patch { continuity } => { need(0, "a boundary (sketch profiles or a loop of edges)")?; let profiles: Vec<(u64, usize)> = items(inputs, 0).iter().filter_map(|x| if let Sel::Profile { sketch, index } = x { Some((*sketch, *index)) } else { None }).collect(); @@ -401,7 +413,21 @@ pub fn commands(app: &SolveApp, k: &Surf, inputs: &[SelInput], extra: &Map = items(inputs, 0).iter().filter_map(|x| if let Sel::Edge { point, .. } = x { Some(pt(*point)) } else { None }).collect(); let body = items(inputs, 0).iter().find_map(|x| if let Sel::Edge { body, .. } = x { Some(body.clone()) } else { None }); - ("surface.patch", json!({"edges": edges, "body": body})) + let mut p = json!({"edges": edges, "body": body}); + if let Some((_, word)) = PATCH_CONTINUITY.get(*continuity).filter(|_| *continuity > 0) { + p["continuity"] = json!(word); + } + let points: Vec = items(inputs, 1) + .iter() + .filter_map(|x| match x { + Sel::Vertex { point, .. } | Sel::Face { point, .. } => Some(pt(*point)), + _ => None, + }) + .collect(); + if !points.is_empty() { + p["points"] = json!(points); + } + ("surface.patch", p) } } Surf::Offset { distance, chain } => { @@ -614,7 +640,7 @@ pub fn for_feature(app: &SolveApp, kind: &FeatureKind, frame: &Mat) -> Option<(K extra.insert("convention".into(), json!(extent.convention)); return Some((Kind::Surface(k), ins, extra)); } - FeatureKind::Patch { sketch, edges, .. } => { + FeatureKind::Patch { sketch, edges, crown, continuity, points, .. } => { let mut sels: Vec = edges.iter().filter_map(edge).collect(); if let Some(sk) = sketch { let st = s.world_state(); @@ -622,7 +648,26 @@ pub fn for_feature(app: &SolveApp, kind: &FeatureKind, frame: &Mat) -> Option<(K sels.extend((0..ss.profiles.len()).map(|index| Sel::Profile { sketch: *sk, index })); } } - (Surf::Patch, vec![sels]) + let index = PATCH_CONTINUITY.iter().position(|(_, w)| *w == continuity.all.as_str()).unwrap_or(0); + // What the dialog does not show is kept as it was: the crown, edges with a + // continuity of their own, and points that are not on a face any more. + let through: Vec = points.iter().filter_map(|p| crate::dialogs::face_sel(s, *p)).collect(); + let mut extra = Map::new(); + if *crown != 0.0 { + extra.insert("crown".into(), json!(crown)); + } + if !continuity.edges.is_empty() { + extra.insert("continuity".into(), serde_json::to_value(continuity).unwrap_or(Value::Null)); + } + if through.len() != points.len() { + extra.insert("points".into(), json!(points.iter().map(|p| pt(*p)).collect::>())); + } + let k = Surf::Patch { continuity: index }; + let mut ins = inputs(&k); + for (input, picks) in ins.iter_mut().zip([sels, through]) { + input.items = picks; + } + return Some((Kind::Surface(k), ins, extra)); } FeatureKind::SurfaceOffset { faces, distance, chain, .. } => { (Surf::Offset { distance: distance.clone(), chain: *chain }, vec![faces.iter().filter_map(|p| crate::dialogs::face_sel(s, *p)).collect()]) diff --git a/crates/ui-egui/src/preselect_tests.rs b/crates/ui-egui/src/preselect_tests.rs index 63c1b00b3..adebe32ac 100644 --- a/crates/ui-egui/src/preselect_tests.rs +++ b/crates/ui-egui/src/preselect_tests.rs @@ -1216,3 +1216,54 @@ fn a_primitive_without_a_pick_or_with_its_position_cleared_stays_at_the_origin() let (p, _) = primitive_on(&mut app, vec![v], "solid.sphere", |_| {}); assert_eq!(p["center"], json!([40.0, 30.0, 20.0]), "{p}"); } + +#[test] +fn patch_dialog_takes_continuity_and_points_and_brings_them_back() { + // A tube with its top face taken off: the rim's edges, G1, through a point above it. + let mut app = app_with(json!([ + {"command": "solid.cylinder", "params": {"radius": 10, "height": 30, "body_name": "Tube"}}, + {"command": "surface.unstitch", "params": {"body": "Tube", "faces": [[0, 0, 30]]}} + ])); + let rim: Vec = { + let st = app.session.model.state(); + let m = st.body("Tube").unwrap().mesh(); + m.edges + .iter() + .enumerate() + .filter(|(_, e)| e.iter().all(|p| (p.z - 30.0).abs() < 1e-6)) + .map(|(i, e)| Sel::Edge { body: "Tube".into(), index: i, point: e[e.len() / 2] }) + .collect() + }; + assert!(!rim.is_empty()); + let mut d = start(&mut app, vec![], "surface.patch"); + d.inputs[0].items = rim; + d.inputs[1].items = vec![Sel::Vertex { body: "Tube".into(), point: Vec3::new(0.0, 0.0, 36.0) }]; + if let Kind::Surface(crate::dialogs_surface::Surf::Patch { continuity }) = &mut d.kind { + *continuity = 1; + } + let (id, p) = apply_commands(&app, &d).unwrap().remove(0); + assert_eq!((id.as_str(), &p["continuity"], &p["points"]), ("surface.patch", &json!("g1"), &json!([[0.0, 0.0, 36.0]])), "{p}"); + app.session.execute(&id, &p).unwrap(); + let top = app.session.model.state().bodies.last().unwrap().mesh().bounds().max.z; + assert!(top > 35.9, "the cap reaches the point: {top}"); + // Edit Feature: G1 again, and the point (on no face) kept as it was. + 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::Patch { continuity: 1 }))); + let (_, p) = apply_commands(&app, &back).unwrap().remove(0); + assert_eq!((&p["params"]["continuity"], &p["params"]["points"]), (&json!("g1"), &json!([[0.0, 0.0, 36.0]])), "{p}"); +} + +#[test] +fn patch_dialog_rows_are_translated() { + for (lang, continuity, through) in [("en", "Continuity", "Pass through"), ("de", "Stetigkeit", "Durch Punkte"), ("ja", "連続性", "通過点")] + { + let mut h = crate::scenario::Harness::new(); + h.app.preferences.language = lang.into(); + h.app.home.open = false; + h.call("ui.start", json!({"command": "surface.patch"})); + h.frames(3); + assert!(h.widget(continuity).is_some(), "{lang}: the Continuity row must show {continuity:?}"); + assert!(h.widget(through).is_some(), "{lang}: the points input must show {through:?}"); + } +} From 5cfcf7fd03a0b7ab5acce811806016b1be75f3c7 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Thu, 15 Oct 2026 23:09:41 -0400 Subject: [PATCH 50/92] Fix the main build: the edge-pick test used a removed field (#1590) --- crates/ui-egui/src/viewport.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 583915d3e..d02d06e18 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -3749,7 +3749,6 @@ mod tests { for style in [0u8, 2] { let ctx = egui::Context::default(); let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); - app.viewport.no_pixels = true; app.run("solid.box", json!({"length":200,"width":120,"height":160})).unwrap(); app.ui.show_origin = false; app.ui.visual_style = style; From ce96e625b4069b03cec88c891012001038f369bb Mon Sep 17 00:00:00 2001 From: bherbruck Date: Thu, 15 Oct 2026 23:12:50 -0400 Subject: [PATCH 51/92] Contributing: kernel speed work goes to solidcore (#1597) (#1598) Thanks @bherbruck. --- CONTRIBUTING.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index edc890bee..bd5be2309 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -296,6 +296,8 @@ long as the change meets the rules above. ## Where help is wanted most +**Kernel speed (slow fillets, booleans, STEP):** please don't rewrite the current kernel code for speed; it is being replaced by [solidcore](https://github.com/bherbruck/solidcore) ([progress](https://bherbruck.github.io/solidcore/)). Report slow cases with a file under the `kernel-perf` label, and put kernel effort into solidcore instead. See [#1597](https://github.com/bherbruck/solidcraft/issues/1597). + See the [`help wanted`](https://github.com/bherbruck/solidcraft/labels/help%20wanted) and [`good first issue`](https://github.com/bherbruck/solidcraft/labels/good%20first%20issue) labels. In order of how much they'd help users: From 556e424bb2589af18b9333c365e2e5c2db72aeba Mon Sep 17 00:00:00 2001 From: bherbruck Date: Thu, 15 Oct 2026 23:22:43 -0400 Subject: [PATCH 52/92] Fix main: drop the removed viewport.no_pixels from the edge-pick test (#1596) #1555 removed the field; #1568's new test still set it. From c01a7b9b37e64c3757101acc4409b4793bb6cc4c Mon Sep 17 00:00:00 2001 From: bherbruck Date: Thu, 15 Oct 2026 23:24:57 -0400 Subject: [PATCH 53/92] Fix main: drop a test's use of the removed viewport.no_pixels (#1594) Thanks @bherbruck. From 6220d8f8a6e91739d95085db366920957c974970 Mon Sep 17 00:00:00 2001 From: CamWight <91156642+CamWight@users.noreply.github.com> Date: Fri, 16 Oct 2026 04:28:02 +0100 Subject: [PATCH 54/92] Desktop 3D mouse on Windows without a 3DxWare profile: object-mode axes, no emulated wheel (#1380) (#1528) Thanks @CamWight. --- README.md | 4 + apps/solidcraft-web/src/space_mouse.rs | 72 +--------------- apps/solidcraft/src/main.rs | 3 + apps/solidcraft/src/space_mouse.rs | 110 +++++++++++++++++++++---- crates/ui-egui/src/space_mouse.rs | 69 ++++++++++++++++ 5 files changed, 174 insertions(+), 84 deletions(-) diff --git a/README.md b/README.md index b5c0c8fca..f24a498d4 100644 --- a/README.md +++ b/README.md @@ -188,6 +188,10 @@ page in Preferences has an on/off switch and a speed control for the 3D mouse. T 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 `/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 devices with 3Dconnexion's vendor id: diff --git a/apps/solidcraft-web/src/space_mouse.rs b/apps/solidcraft-web/src/space_mouse.rs index 9707b89de..07394de56 100644 --- a/apps/solidcraft-web/src/space_mouse.rs +++ b/apps/solidcraft-web/src/space_mouse.rs @@ -9,10 +9,6 @@ use solidcraft_ui_egui::space_mouse::{Axes, FULL_SCALE}; -/// 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. -const WHEEL_QUIET_S: f64 = 0.15; - /// 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. const LOGITECH: u16 = 0x046d; @@ -69,29 +65,6 @@ pub fn choose(found: impl IntoIterator) -> Option { found.into_iter().min_by_key(|(source, _)| *source).map(|(_, axes)| axes) } -/// 3DxWare turns the cap's motion into mouse-wheel turns in a browser (its zoom emulation). The -/// app reads the cap itself, so those are dropped: wheel events while the cap is moving and for -/// [`WHEEL_QUIET_S`] after. 3DxWare sends them only well past the dead zone (from about a third -/// of full deflection), never at rest, so a wheel turn with the cap at rest is the user's. -#[derive(Debug, Default)] -pub struct WheelGuard { - moved_at: Option, -} - -impl WheelGuard { - /// Takes this frame's reading (`now` in seconds) and drops the frame's wheel events if they - /// are 3DxWare's. - pub fn filter(&mut self, moving: bool, now: f64, events: &mut Vec) { - if moving { - self.moved_at = Some(now); - } - let recent = self.moved_at.is_some_and(|at| (0.0..=WHEEL_QUIET_S).contains(&(now - at))); - if recent { - events.retain(|e| !matches!(e, egui::Event::MouseWheel { .. } | egui::Event::Zoom(_))); - } - } -} - #[cfg(target_arch = "wasm32")] pub use browser::SpaceMouse; @@ -105,7 +78,9 @@ mod browser { use wasm_bindgen::JsCast as _; use wasm_bindgen::closure::Closure; - use super::{WheelGuard, axes, choose, source}; + use solidcraft_ui_egui::space_mouse::WheelGuard; + + use super::{axes, choose, source}; /// How often the page looks for the cap starting to move while nothing else redraws. const WAKE_MS: i32 = 50; @@ -200,19 +175,6 @@ mod browser { mod tests { use super::*; - fn wheel(dy: f32) -> egui::Event { - egui::Event::MouseWheel { - unit: egui::MouseWheelUnit::Point, - delta: egui::vec2(0.0, dy), - modifiers: egui::Modifiers::NONE, - phase: egui::TouchPhase::Move, - } - } - - fn other() -> egui::Event { - egui::Event::PointerMoved(egui::pos2(1.0, 2.0)) - } - #[test] fn recognises_3d_mice_in_each_browsers_ids() { // As Edge and Firefox list them (Windows 11, SpaceMouse Pro, 3DxWare 10). @@ -320,32 +282,4 @@ mod tests { assert_eq!(choose([(Source::Device, moving), (Source::Device, other)]), Some(moving)); assert_eq!(choose([]), None); } - - #[test] - fn wheel_turns_are_dropped_while_the_cap_moves_and_kept_at_rest() { - let mut guard = WheelGuard::default(); - // At rest, the wheel is the user's. - let mut events = vec![wheel(100.0), other()]; - guard.filter(false, 10.0, &mut events); - assert_eq!(events.len(), 2); - // Moving: 3DxWare's wheel (and a pinch zoom) goes; everything else stays. - let mut events = vec![wheel(-100.0), other(), egui::Event::Zoom(1.1), wheel(100.0)]; - guard.filter(true, 11.0, &mut events); - assert_eq!(events, vec![other()]); - // Just after the cap stops, a queued one still goes. - let mut events = vec![wheel(100.0)]; - guard.filter(false, 11.0 + WHEEL_QUIET_S - 0.01, &mut events); - assert!(events.is_empty()); - // Later, the wheel is the user's again. - let mut events = vec![wheel(100.0)]; - guard.filter(false, 11.0 + WHEEL_QUIET_S + 0.01, &mut events); - assert_eq!(events.len(), 1); - // A clock that goes back never swallows the user's wheel. - let mut events = vec![wheel(100.0)]; - guard.filter(false, 5.0, &mut events); - assert_eq!(events.len(), 1); - let mut events = vec![wheel(100.0)]; - guard.filter(false, f64::NAN, &mut events); - assert_eq!(events.len(), 1); - } } diff --git a/apps/solidcraft/src/main.rs b/apps/solidcraft/src/main.rs index bc55e8668..9d2b8c899 100644 --- a/apps/solidcraft/src/main.rs +++ b/apps/solidcraft/src/main.rs @@ -77,6 +77,9 @@ impl eframe::App for App { } } fn raw_input_hook(&mut self, _ctx: &egui::Context, raw: &mut egui::RawInput) { + // Before the app's own hook, which adds the control channel's events. + #[cfg(any(target_os = "windows", target_os = "linux"))] + self.space_mouse.raw_input_hook(self.solve.preferences.space_mouse_enabled, raw); self.solve.raw_input_hook(raw); } fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { diff --git a/apps/solidcraft/src/space_mouse.rs b/apps/solidcraft/src/space_mouse.rs index d78734766..da872320f 100644 --- a/apps/solidcraft/src/space_mouse.rs +++ b/apps/solidcraft/src/space_mouse.rs @@ -16,17 +16,17 @@ use hidapi::{DeviceInfo, HidApi}; use quick_xml::Reader; use quick_xml::events::Event; use solidcraft_ui_egui::SolveApp; -use solidcraft_ui_egui::space_mouse::{Axes, AxisRule, DriverMapping, navigate_frame}; +use solidcraft_ui_egui::space_mouse::{Axes, AxisRule, DriverMapping, WheelGuard, navigate_frame}; const STALE_AFTER: Duration = Duration::from_millis(150); const RETRY_AFTER: Duration = Duration::from_secs(2); const MAX_PROFILE_BYTES: u64 = 1024 * 1024; -/// The mapping used when no 3DxWare profile is found. On Linux there is no 3DxWare, so it is what -/// the driver applies by default in object mode (#1172). Elsewhere the driver writes a profile, -/// and the raw axes are used until it does. +/// The mapping used when no 3DxWare profile is found: what the driver applies by default in +/// object mode. On Linux there is no 3DxWare (#1172); on Windows 3DxWare has no profile for +/// SolidCraft until one is made, and the raw axes swap roll and spin (#1380). fn without_profile() -> DriverMapping { - if cfg!(target_os = "linux") { DriverMapping::object_mode() } else { DriverMapping::default() } + DriverMapping::object_mode() } #[derive(Clone, Copy, Debug, Default)] @@ -320,6 +320,9 @@ pub struct SpaceMouse { last_frame: Instant, driver_mapping: DriverMapping, mapping_checked_at: Instant, + /// Drops 3DxWare's emulated wheel while the cap moves (#1380). + wheel: WheelGuard, + started: Instant, } impl SpaceMouse { @@ -331,7 +334,25 @@ impl SpaceMouse { if let Err(error) = std::thread::Builder::new().name("solidcraft-3d-mouse".into()).spawn(move || reader(worker_ctx, worker_state)) { log::warn!("3D mouse: reader could not start: {error}"); } - Self { shared, last_frame: now, driver_mapping: load_driver_mapping().unwrap_or_else(without_profile), mapping_checked_at: now } + Self { + shared, + last_frame: now, + driver_mapping: load_driver_mapping().unwrap_or_else(without_profile), + mapping_checked_at: now, + wheel: WheelGuard::default(), + started: now, + } + } + + /// Before the app's own hook (which adds the control channel's events): with navigation on, + /// the wheel events 3DxWare makes from the cap's motion are dropped. + pub fn raw_input_hook(&mut self, enabled: bool, raw: &mut egui::RawInput) { + if !enabled { + return; + } + let now = Instant::now(); + let moving = self.shared.lock().map(|reading| reading.current(now).moving()).unwrap_or(false); + self.wheel.filter(moving, now.duration_since(self.started).as_secs_f64(), &mut raw.events); } pub fn tick(&mut self, app: &mut SolveApp, ctx: &Context) { @@ -428,7 +449,7 @@ mod tests { } #[test] - fn without_a_profile_linux_uses_the_drivers_object_mode_axes() { + fn without_a_profile_the_drivers_object_mode_axes_are_used() { // 3DxWare's object-mode mapping, as a profile (#1172: confirmed on a SpaceMouse Compact). let object_mode = br#" @@ -441,14 +462,11 @@ mod tests { "#; let profile = parse_driver_mapping(object_mode).expect("valid 3DxWare profile"); - if cfg!(target_os = "linux") { - assert_eq!(without_profile(), profile); - // Tilting the cap rolls the view and twisting it spins it, as with the driver. - assert_eq!(rotation(without_profile(), [0, 350, 0]), [0.0, 0.0, -1.0]); - assert_eq!(rotation(without_profile(), [0, 0, 350]), [0.0, -1.0, 0.0]); - } else { - assert_eq!(without_profile(), DriverMapping::default()); - } + // On every platform (#1172 on Linux, #1380 on Windows). + assert_eq!(without_profile(), profile); + // Tilting the cap rolls the view and twisting it spins it, as with the driver. + assert_eq!(rotation(without_profile(), [0, 350, 0]), [0.0, 0.0, -1.0]); + assert_eq!(rotation(without_profile(), [0, 0, 350]), [0.0, -1.0, 0.0]); } #[test] @@ -476,6 +494,8 @@ mod tests { last_frame: now - Duration::from_millis(20), driver_mapping: DriverMapping::object_mode(), mapping_checked_at: now, + wheel: WheelGuard::default(), + started: now, }; let mut app = SolveApp::new(solidcraft_engine::Session::default(), solidcraft_ui_egui::Services::default()); app.home.open = false; @@ -484,4 +504,64 @@ mod tests { assert_eq!(motion, Motion { translation: [0.0; 3], rotation: [0.0, 0.0, -1.0] }); assert!(seconds > 0.0); } + + fn wheel() -> egui::Event { + egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: egui::vec2(0.0, -1.0), + modifiers: Default::default(), + phase: egui::TouchPhase::Move, + } + } + + fn mouse(reading: Reading) -> SpaceMouse { + let now = Instant::now(); + SpaceMouse { + shared: Arc::new(Mutex::new(reading)), + last_frame: now, + driver_mapping: DriverMapping::object_mode(), + mapping_checked_at: now, + wheel: WheelGuard::default(), + started: now, + } + } + + #[test] + fn the_wheel_3dxware_makes_from_the_cap_is_dropped() { + // The cap tilted forward: 3DxWare also sends wheel turns (#1380). They are dropped. + let now = Instant::now(); + let mut tilted = Reading::new(now); + tilted.axes.rotation = [-200, 0, 0]; + let mut moving = mouse(tilted); + let mut raw = egui::RawInput { events: vec![wheel(), egui::Event::Zoom(1.1), egui::Event::Text("a".into())], ..Default::default() }; + moving.raw_input_hook(true, &mut raw); + assert_eq!(raw.events, [egui::Event::Text("a".into())]); + // With navigation off, the wheel is the cap's only way to move the view: kept. + let mut raw = egui::RawInput { events: vec![wheel()], ..Default::default() }; + moving.raw_input_hook(false, &mut raw); + assert_eq!(raw.events.len(), 1); + // The cap at rest: the wheel is the user's. + let mut resting = mouse(Reading::new(now)); + let mut raw = egui::RawInput { events: vec![wheel()], ..Default::default() }; + resting.raw_input_hook(true, &mut raw); + assert_eq!(raw.events.len(), 1); + } + + #[test] + fn the_wheel_is_the_users_again_once_the_cap_has_been_still_a_moment() { + let mut tilted = Reading::new(Instant::now()); + tilted.axes.rotation = [-200, 0, 0]; + let mut cap = mouse(tilted); + let mut raw = egui::RawInput { events: vec![wheel()], ..Default::default() }; + cap.raw_input_hook(true, &mut raw); + assert!(raw.events.is_empty(), "dropped while the cap moves"); + // Let go, then wait out the quiet time. + if let Ok(mut reading) = cap.shared.lock() { + *reading = Reading::new(Instant::now()); + } + std::thread::sleep(Duration::from_secs_f64(solidcraft_ui_egui::space_mouse::WHEEL_QUIET_S) + Duration::from_millis(60)); + let mut raw = egui::RawInput { events: vec![wheel()], ..Default::default() }; + cap.raw_input_hook(true, &mut raw); + assert_eq!(raw.events.len(), 1, "kept once the cap has been still"); + } } diff --git a/crates/ui-egui/src/space_mouse.rs b/crates/ui-egui/src/space_mouse.rs index ff373fa38..bb9d76e04 100644 --- a/crates/ui-egui/src/space_mouse.rs +++ b/crates/ui-egui/src/space_mouse.rs @@ -26,6 +26,34 @@ impl Axes { } } +/// 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; + +/// 3DxWare turns the cap's motion into mouse-wheel turns for programs it has no profile for (its +/// keyboard and mouse emulation), browsers included (#1336, #1380). Both apps read the cap +/// themselves, so those are dropped: wheel events while the cap is moving and for +/// [`WHEEL_QUIET_S`] after. 3DxWare sends them only well past the dead zone (from about a third +/// of full deflection), never at rest, so a wheel turn with the cap at rest is the user's. +#[derive(Debug, Default)] +pub struct WheelGuard { + moved_at: Option, +} + +impl WheelGuard { + /// Takes this frame's reading (`now` in seconds) and drops the frame's wheel events if they + /// are 3DxWare's. + pub fn filter(&mut self, moving: bool, now: f64, events: &mut Vec) { + if moving { + self.moved_at = Some(now); + } + let recent = self.moved_at.is_some_and(|at| (0.0..=WHEEL_QUIET_S).contains(&(now - at))); + if recent { + events.retain(|e| !matches!(e, egui::Event::MouseWheel { .. } | egui::Event::Zoom(_))); + } + } +} + /// Where one physical axis goes: its logical axis, and how. #[derive(Clone, Copy, Debug, PartialEq)] pub struct AxisRule { @@ -156,6 +184,19 @@ mod tests { const PUSH: Axes = Axes { translation: [0, 350, 0], rotation: [0; 3] }; + fn wheel(dy: f32) -> egui::Event { + egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, dy), + modifiers: egui::Modifiers::NONE, + phase: egui::TouchPhase::Move, + } + } + + fn other() -> egui::Event { + egui::Event::PointerMoved(egui::pos2(1.0, 2.0)) + } + #[test] fn six_axes_move_the_camera_and_sketches_keep_their_orientation() { let mut cam = Camera::default(); @@ -348,4 +389,32 @@ mod tests { assert_eq!(distances[6], distances[5], "under 0.1 times is 0.1 times"); assert!(distances[4] < distances[5] && distances[5] < app().cam.distance); } + + #[test] + fn wheel_turns_are_dropped_while_the_cap_moves_and_kept_at_rest() { + let mut guard = WheelGuard::default(); + // At rest, the wheel is the user's. + let mut events = vec![wheel(100.0), other()]; + guard.filter(false, 10.0, &mut events); + assert_eq!(events.len(), 2); + // Moving: 3DxWare's wheel (and a pinch zoom) goes; everything else stays. + let mut events = vec![wheel(-100.0), other(), egui::Event::Zoom(1.1), wheel(100.0)]; + guard.filter(true, 11.0, &mut events); + assert_eq!(events, vec![other()]); + // Just after the cap stops, a queued one still goes. + let mut events = vec![wheel(100.0)]; + guard.filter(false, 11.0 + WHEEL_QUIET_S - 0.01, &mut events); + assert!(events.is_empty()); + // Later, the wheel is the user's again. + let mut events = vec![wheel(100.0)]; + guard.filter(false, 11.0 + WHEEL_QUIET_S + 0.01, &mut events); + assert_eq!(events.len(), 1); + // A clock that goes back never swallows the user's wheel. + let mut events = vec![wheel(100.0)]; + guard.filter(false, 5.0, &mut events); + assert_eq!(events.len(), 1); + let mut events = vec![wheel(100.0)]; + guard.filter(false, f64::NAN, &mut events); + assert_eq!(events.len(), 1); + } } From 716107f0e492f96d3128f436aa71933dd814256d Mon Sep 17 00:00:00 2001 From: "H. Conrad" <78785932+Ian-cmd-ops@users.noreply.github.com> Date: Thu, 15 Oct 2026 20:34:18 -0700 Subject: [PATCH 55/92] Sketch cut and paste: refuse parameters that are not an object (no panic) (#1577) Thanks @Ian-cmd-ops. --- crates/engine/src/cmd/sketch_clipboard.rs | 4 ++++ .../engine/src/cmd/sketch_clipboard_tests.rs | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/crates/engine/src/cmd/sketch_clipboard.rs b/crates/engine/src/cmd/sketch_clipboard.rs index c97644558..364f18516 100644 --- a/crates/engine/src/cmd/sketch_clipboard.rs +++ b/crates/engine/src/cmd/sketch_clipboard.rs @@ -242,6 +242,10 @@ fn paste_step(extent: f64) -> f64 { fn paste(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.paste"; + // `p["sketch"] = …` below panics on anything but an object. + if !(p.is_object() || p.is_null()) { + return Err(bad(cmd, "params must be an object")); + } let Some(clip) = s.sketch_clipboard.clone() else { return Err(bad(cmd, "nothing copied (sketch.copy first)")) }; let target = target_sketch(s, p, cmd)?; let positioned = p.get("at").is_some() || p.get("translate").is_some(); diff --git a/crates/engine/src/cmd/sketch_clipboard_tests.rs b/crates/engine/src/cmd/sketch_clipboard_tests.rs index 86ec2e248..3399f442a 100644 --- a/crates/engine/src/cmd/sketch_clipboard_tests.rs +++ b/crates/engine/src/cmd/sketch_clipboard_tests.rs @@ -231,3 +231,21 @@ fn cut_copies_and_deletes_in_one_step_and_pastes_back_in_place() { run(&mut s, "edit.undo", json!({})); assert_eq!(sketch(&s, sid), &before); } + +/// Parameters that are not a JSON object (a number, text, a list) are an error, not a panic: +/// `sketch.cut` and `sketch.paste` add keys to a copy of the parameters, and serde_json panics +/// when a key is set on anything but an object (#1536, found by `hostile_params_never_panic`). +#[test] +fn clipboard_commands_refuse_parameters_that_are_not_an_object() { + let (mut s, rect, _) = drawing(); + run(&mut s, "sketch.copy", json!({"entities": [rect[0].clone()]})); + for id in ["sketch.cut", "sketch.copy", "sketch.paste"] { + for hostile in [json!(true), json!(-1), json!(1e308), json!("nope"), json!([]), json!([0, 0, 0]), json!([{"x": 1}])] { + let result = s.execute(id, &hostile); + assert!(!matches!(result, Err(crate::EngineError::Internal(..))), "{id} {hostile} panicked inside the command: {result:?}"); + assert!(result.is_err(), "{id} {hostile} should be refused"); + } + } + // Nothing was cut or pasted by the refused calls. + assert!(s.execute("sketch.paste", &json!({})).is_ok(), "the clipboard still holds the copy"); +} From fdb059cfed9424bc8acc0906b269152e6072eac8 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Thu, 15 Oct 2026 23:57:15 -0400 Subject: [PATCH 56/92] Claim bot: let me /unclaim my own issues (#1595) An explicit /unclaim from the owner releases an owner-assigned issue; the sweep still never touches them. --- scripts/claim/claim.js | 4 ++-- scripts/claim/claim.test.js | 11 +++++++---- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/scripts/claim/claim.js b/scripts/claim/claim.js index f3cf632ad..8cfd19555 100644 --- a/scripts/claim/claim.js +++ b/scripts/claim/claim.js @@ -223,8 +223,8 @@ async function unclaim(github, context) { await react(github, context, '+1'); // nothing to release return; } - if (assignees.includes(context.repo.owner)) { - await react(github, context, 'eyes'); // never touched by the bot + if (assignees.includes(context.repo.owner) && user !== context.repo.owner) { + await react(github, context, 'eyes'); // only the owner releases their own issues return; } const allowed = assignees.includes(user) || (await isMaintainer(github, context, user)); diff --git a/scripts/claim/claim.test.js b/scripts/claim/claim.test.js index c61da8a1f..f2fe47df7 100644 --- a/scripts/claim/claim.test.js +++ b/scripts/claim/claim.test.js @@ -170,10 +170,13 @@ test('unclaim by a maintainer releases, by a stranger does not', async () => { assert.equal(find(w.calls, 'react')[1].content, 'eyes'); }); -test('unclaim never touches an issue assigned to the owner', async () => { - const { github, calls } = fake(); - await claim.handleComment({ github, context: ctx('/unclaim', { user: 'bherbruck', assignees: ['bherbruck'], labels: ['in progress'] }), now: NOW }); - assert.equal(find(calls, 'removeLabel'), undefined); +test('unclaim on an owner-assigned issue works only for the owner', async () => { + let w = fake(); + await claim.handleComment({ github: w.github, context: ctx('/unclaim', { user: 'carol', assignees: ['bherbruck'], labels: ['in progress'] }), now: NOW }); + assert.equal(find(w.calls, 'removeLabel'), undefined); + w = fake(); + await claim.handleComment({ github: w.github, context: ctx('/unclaim', { user: 'bherbruck', assignees: ['bherbruck'], labels: ['in progress'] }), now: NOW }); + assert.ok(find(w.calls, 'removeLabel')); }); const issue = (number, assignees = ['bob']) => ({ From baf44657c176ecc87ca5214f4605d359d329362c Mon Sep 17 00:00:00 2001 From: bherbruck Date: Thu, 15 Oct 2026 23:58:28 -0400 Subject: [PATCH 57/92] Agent chat: queue messages while the agent works, Send now, Stop, New chat, and a model picker (#1566, #1571) (#1566) Thanks @bherbruck. --- assets/locales/de.json | 1 - assets/locales/en.json | 16 +- assets/locales/ja.json | 16 +- assets/locales/ko.json | 1 - assets/locales/tr.json | 1 - assets/locales/zh.json | 16 +- crates/ui-egui/src/agent_chat/acp.rs | 59 +++ crates/ui-egui/src/agent_chat/acp_client.rs | 21 +- crates/ui-egui/src/agent_chat/api_client.rs | 246 ++++++++++- crates/ui-egui/src/agent_chat/backend.rs | 7 + crates/ui-egui/src/agent_chat/mod.rs | 266 +++++++++++- crates/ui-egui/src/agent_chat/panel.rs | 195 ++++++++- crates/ui-egui/src/agent_chat/tests.rs | 453 ++++++++++++++++++++ crates/ui-egui/src/prefs.rs | 3 + docs/agent-chat.md | 23 +- docs/control-protocol.md | 2 +- 16 files changed, 1293 insertions(+), 33 deletions(-) diff --git a/assets/locales/de.json b/assets/locales/de.json index e87a5cd35..95fa40987 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -613,7 +613,6 @@ "ui.agent_chat_undo_label": "Agenten-Chat: {message}", "ui.agent_chat_undone": "(rückgängig gemacht)", "ui.agent_chat_view_attached": "Ansicht angehängt", - "ui.agent_chat_wait_turn": "Der Agent arbeitet noch an der letzten Nachricht: Warten Sie oder klicken Sie auf Abbrechen.", "ui.agent_cursor": "Agent-Cursor", "ui.agent_cursor_speed": "Agent-Cursor-Geschwindigkeit", "ui.ai_add": "Hinzufügen", diff --git a/assets/locales/en.json b/assets/locales/en.json index 1e00199b8..b9a583d1d 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -795,6 +795,7 @@ "ui.agent_chat_detecting": "Looking for agents…", "ui.agent_chat_dock_left": "Dock on the left", "ui.agent_chat_dock_right": "Dock on the right", + "ui.agent_chat_edit": "Edit", "ui.agent_chat_exited": "The agent stopped.", "ui.agent_chat_failed_start": "The agent could not start: {error}", "ui.agent_chat_intro": "Chat with a coding agent you already use, or a model endpoint you choose. It works on the open design through SolidCraft's tools: its changes show as it makes them and undo as one step per message. What it may do without asking is set in Preferences > AI.", @@ -802,6 +803,10 @@ "ui.agent_chat_left": "Left", "ui.agent_chat_limit": "The agent reached the limit of {limit} changes for one message. Send another message to let it go on.", "ui.agent_chat_minimize": "Minimise to a strip", + "ui.agent_chat_model_tip": "The model the agent uses. Your choice is remembered for this agent.", + "ui.agent_chat_new": "New chat", + "ui.agent_chat_new_confirm": "Start a new chat? The current one is cleared.", + "ui.agent_chat_new_yes": "New chat", "ui.agent_chat_no_cli": "solidcraft-cli was not found next to the app, so the agent can't reach the design.", "ui.agent_chat_no_control": "The agent chat's endpoint did not start, so the agent can't reach the design.", "ui.agent_chat_no_images": "This agent doesn't take pictures", @@ -812,12 +817,21 @@ "ui.agent_chat_permission": "The agent asks to run: {title}", "ui.agent_chat_pick": "Agent", "ui.agent_chat_placeholder": "Ask the agent to change the design…", + "ui.agent_chat_placeholder_busy": "Queue a message for when the agent is done (Ctrl+Enter: send now)", "ui.agent_chat_privacy": "Nothing goes anywhere except to the agent you run, under your own account.", "ui.agent_chat_privacy_note": "SolidCraft sends nothing anywhere: the agent you run talks to its own service under your own account. SolidCraft never sees or stores a key or password.", + "ui.agent_chat_queue": "Queue", + "ui.agent_chat_queue_full": "Too many messages are waiting: remove one or wait for the agent.", + "ui.agent_chat_queued": "Queued", + "ui.agent_chat_queued_stopped": "Queued (stopped, not sent)", "ui.agent_chat_refresh": "Refresh", "ui.agent_chat_refused": "Not allowed for the agent: {reason}", + "ui.agent_chat_remove": "Remove from the queue", "ui.agent_chat_right": "Right", + "ui.agent_chat_save": "Save", "ui.agent_chat_send": "Send", + "ui.agent_chat_send_now": "Send now", + "ui.agent_chat_send_now_tip": "Stop the agent's current step and send this next (Ctrl+Enter)", "ui.agent_chat_side": "Agent chat side", "ui.agent_chat_signed_in": "signed in", "ui.agent_chat_state_auth": "Sign-in needed", @@ -828,12 +842,12 @@ "ui.agent_chat_state_starting": "Starting…", "ui.agent_chat_stop": "Stop", "ui.agent_chat_stop_tip": "Stop the agent and everything it started", + "ui.agent_chat_stop_turn_tip": "Stop the agent (Esc). Queued messages stay queued.", "ui.agent_chat_turn_limit": "Changes per message", "ui.agent_chat_undo_changes": "Undo these changes", "ui.agent_chat_undo_label": "Agent chat: {message}", "ui.agent_chat_undone": "(undone)", "ui.agent_chat_view_attached": "View attached", - "ui.agent_chat_wait_turn": "The agent is still working on the last message: wait for it or press Cancel.", "ui.agent_cursor": "Agent cursor", "ui.agent_cursor_speed": "Agent cursor speed", "ui.ai_add": "Add", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index df92e4352..a50b3417f 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -795,6 +795,7 @@ "ui.agent_chat_detecting": "エージェントを検索中…", "ui.agent_chat_dock_left": "左にドッキング", "ui.agent_chat_dock_right": "右にドッキング", + "ui.agent_chat_edit": "編集", "ui.agent_chat_exited": "エージェントが停止しました。", "ui.agent_chat_failed_start": "エージェントを起動できませんでした: {error}", "ui.agent_chat_intro": "普段使っているコーディングエージェント、または選んだモデルのエンドポイントとチャットできます。SolidCraft のツールで開いているデザインを操作し、変更はその場で表示され、メッセージごとに1回で元に戻せます。確認なしで許可する範囲は「環境設定 > AI」で設定します。", @@ -802,6 +803,10 @@ "ui.agent_chat_left": "左", "ui.agent_chat_limit": "エージェントが1メッセージあたりの変更上限 {limit} に達しました。続けさせるには、もう一度メッセージを送ってください。", "ui.agent_chat_minimize": "細いバーに最小化", + "ui.agent_chat_model_tip": "エージェントが使うモデル。選択はこのエージェントに対して記憶されます。", + "ui.agent_chat_new": "新しいチャット", + "ui.agent_chat_new_confirm": "新しいチャットを始めますか? 現在のチャットは消去されます。", + "ui.agent_chat_new_yes": "新しいチャット", "ui.agent_chat_no_cli": "アプリの隣に solidcraft-cli が見つからないため、エージェントはデザインにアクセスできません。", "ui.agent_chat_no_control": "エージェントチャットのエンドポイントが起動しなかったため、エージェントはデザインにアクセスできません。", "ui.agent_chat_no_images": "このエージェントは画像を受け付けません", @@ -812,12 +817,21 @@ "ui.agent_chat_permission": "エージェントが実行の許可を求めています: {title}", "ui.agent_chat_pick": "エージェント", "ui.agent_chat_placeholder": "デザインの変更をエージェントに依頼…", + "ui.agent_chat_placeholder_busy": "エージェントの作業が終わったら送るメッセージを入力(Ctrl+Enter: 今すぐ送信)", "ui.agent_chat_privacy": "あなたのアカウントで実行するエージェント以外には、何も送信されません。", "ui.agent_chat_privacy_note": "SolidCraft はどこにも何も送信しません。あなたが実行するエージェントが、あなた自身のアカウントでそのサービスと通信します。SolidCraft がキーやパスワードを見たり保存したりすることはありません。", + "ui.agent_chat_queue": "待機に追加", + "ui.agent_chat_queue_full": "待機中のメッセージが多すぎます。削除するか、エージェントの完了をお待ちください。", + "ui.agent_chat_queued": "待機中", + "ui.agent_chat_queued_stopped": "待機中(停止済み・未送信)", "ui.agent_chat_refresh": "再検索", "ui.agent_chat_refused": "エージェントには許可されていません: {reason}", + "ui.agent_chat_remove": "待機から削除", "ui.agent_chat_right": "右", + "ui.agent_chat_save": "保存", "ui.agent_chat_send": "送信", + "ui.agent_chat_send_now": "今すぐ送信", + "ui.agent_chat_send_now_tip": "エージェントの現在のステップを止めて、これを次に送信します(Ctrl+Enter)", "ui.agent_chat_side": "エージェントチャットの位置", "ui.agent_chat_signed_in": "サインイン済み", "ui.agent_chat_state_auth": "サインインが必要", @@ -828,12 +842,12 @@ "ui.agent_chat_state_starting": "起動中…", "ui.agent_chat_stop": "停止", "ui.agent_chat_stop_tip": "エージェントと、それが起動したものをすべて停止します", + "ui.agent_chat_stop_turn_tip": "エージェントを停止します(Esc)。待機中のメッセージは待機のままです。", "ui.agent_chat_turn_limit": "1メッセージあたりの変更数", "ui.agent_chat_undo_changes": "これらの変更を元に戻す", "ui.agent_chat_undo_label": "エージェントチャット: {message}", "ui.agent_chat_undone": "(元に戻しました)", "ui.agent_chat_view_attached": "ビューを添付済み", - "ui.agent_chat_wait_turn": "エージェントはまだ前のメッセージを処理中です。待つか「キャンセル」を押してください。", "ui.agent_cursor": "エージェントカーソル", "ui.agent_cursor_speed": "エージェントカーソル速度", "ui.ai_add": "追加", diff --git a/assets/locales/ko.json b/assets/locales/ko.json index 1ac034ef9..b5cec8c18 100644 --- a/assets/locales/ko.json +++ b/assets/locales/ko.json @@ -613,7 +613,6 @@ "ui.agent_chat_undo_label": "에이전트 채팅: {message}", "ui.agent_chat_undone": "(취소됨)", "ui.agent_chat_view_attached": "뷰 첨부됨", - "ui.agent_chat_wait_turn": "에이전트가 아직 이전 메시지를 처리 중입니다. 기다리거나 취소를 누르세요.", "ui.agent_cursor": "에이전트 커서", "ui.agent_cursor_speed": "에이전트 커서 속도", "ui.ai_add": "추가", diff --git a/assets/locales/tr.json b/assets/locales/tr.json index 36798f876..8ccc757ad 100644 --- a/assets/locales/tr.json +++ b/assets/locales/tr.json @@ -788,7 +788,6 @@ "ui.agent_chat_undo_label": "Ajan sohbeti: {message}", "ui.agent_chat_undone": "(geri alındı)", "ui.agent_chat_view_attached": "Görünüm eklendi", - "ui.agent_chat_wait_turn": "Ajan hâlâ son mesaj üzerinde çalışıyor: Bekleyin veya İptal'e tıklayın.", "ui.agent_cursor": "Ajan imleci", "ui.agent_cursor_speed": "Ajan imleci hızı", "ui.ai_add": "Ekle", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index 1481b9701..2e6162e5b 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -795,6 +795,7 @@ "ui.agent_chat_detecting": "正在查找智能体…", "ui.agent_chat_dock_left": "停靠在左侧", "ui.agent_chat_dock_right": "停靠在右侧", + "ui.agent_chat_edit": "编辑", "ui.agent_chat_exited": "智能体已停止。", "ui.agent_chat_failed_start": "智能体无法启动:{error}", "ui.agent_chat_intro": "与你已在使用的编程智能体或你选择的模型端点聊天。它通过 SolidCraft 的工具处理打开的设计:更改即时显示,每条消息的更改可一步撤销。无需询问即可执行的范围在“首选项 > AI”中设置。", @@ -802,6 +803,10 @@ "ui.agent_chat_left": "左侧", "ui.agent_chat_limit": "智能体已达到每条消息 {limit} 项更改的上限。再发送一条消息可让它继续。", "ui.agent_chat_minimize": "最小化为细条", + "ui.agent_chat_model_tip": "智能体使用的模型。你的选择会为此智能体记住。", + "ui.agent_chat_new": "新对话", + "ui.agent_chat_new_confirm": "开始新对话?当前对话将被清除。", + "ui.agent_chat_new_yes": "新对话", "ui.agent_chat_no_cli": "在应用旁边未找到 solidcraft-cli,因此智能体无法访问设计。", "ui.agent_chat_no_control": "智能体聊天的端点未能启动,因此智能体无法访问设计。", "ui.agent_chat_no_images": "该智能体不接收图片", @@ -812,12 +817,21 @@ "ui.agent_chat_permission": "智能体请求运行:{title}", "ui.agent_chat_pick": "智能体", "ui.agent_chat_placeholder": "让智能体修改设计…", + "ui.agent_chat_placeholder_busy": "输入消息,待智能体完成后发送(Ctrl+Enter:立即发送)", "ui.agent_chat_privacy": "除了你以自己的账户运行的智能体之外,不会向任何地方发送任何内容。", "ui.agent_chat_privacy_note": "SolidCraft 不向任何地方发送任何内容:你运行的智能体以你自己的账户与它自己的服务通信。SolidCraft 从不查看或保存任何密钥或密码。", + "ui.agent_chat_queue": "加入队列", + "ui.agent_chat_queue_full": "等待中的消息太多:请删除一条,或等待智能体完成。", + "ui.agent_chat_queued": "已排队", + "ui.agent_chat_queued_stopped": "已排队(已停止,未发送)", "ui.agent_chat_refresh": "刷新", "ui.agent_chat_refused": "不允许智能体执行:{reason}", + "ui.agent_chat_remove": "从队列中移除", "ui.agent_chat_right": "右侧", + "ui.agent_chat_save": "保存", "ui.agent_chat_send": "发送", + "ui.agent_chat_send_now": "立即发送", + "ui.agent_chat_send_now_tip": "停止智能体当前的步骤,并接着发送这条消息(Ctrl+Enter)", "ui.agent_chat_side": "智能体聊天位置", "ui.agent_chat_signed_in": "已登录", "ui.agent_chat_state_auth": "需要登录", @@ -828,12 +842,12 @@ "ui.agent_chat_state_starting": "正在启动…", "ui.agent_chat_stop": "停止", "ui.agent_chat_stop_tip": "停止智能体及其启动的所有进程", + "ui.agent_chat_stop_turn_tip": "停止智能体(Esc)。排队的消息仍保持排队。", "ui.agent_chat_turn_limit": "每条消息的更改数", "ui.agent_chat_undo_changes": "撤销这些更改", "ui.agent_chat_undo_label": "智能体聊天:{message}", "ui.agent_chat_undone": "(已撤销)", "ui.agent_chat_view_attached": "已附加视图", - "ui.agent_chat_wait_turn": "智能体仍在处理上一条消息:请等待或点击取消。", "ui.agent_cursor": "代理光标", "ui.agent_cursor_speed": "代理光标速度", "ui.ai_add": "添加", diff --git a/crates/ui-egui/src/agent_chat/acp.rs b/crates/ui-egui/src/agent_chat/acp.rs index 20814ad5a..28315f8d6 100644 --- a/crates/ui-egui/src/agent_chat/acp.rs +++ b/crates/ui-egui/src/agent_chat/acp.rs @@ -115,6 +115,40 @@ pub fn modes(session: &Value) -> Option<(String, Vec<(String, String)>)> { (!available.is_empty()).then_some((current, available)) } +/// One model an agent offers. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ModelInfo { + pub id: String, + pub name: String, + pub description: String, +} + +/// The agent's models in a `session/new` or `session/load` reply (`models`: `currentModelId` and +/// `availableModels: [{modelId, name, description?}]`): the current one and each model. `None` +/// when the agent reports none. +pub fn models(session: &Value) -> Option<(String, Vec)> { + let m = session.get("models")?; + let current = m.get("currentModelId").and_then(Value::as_str).unwrap_or("").to_string(); + let available: Vec = m + .get("availableModels")? + .as_array()? + .iter() + .take(200) + .filter_map(|x| { + let id = x.get("modelId").or_else(|| x.get("id"))?.as_str()?.to_string(); + let name = x.get("name").and_then(Value::as_str).filter(|n| !n.is_empty()).unwrap_or(&id).to_string(); + let description = x.get("description").and_then(Value::as_str).unwrap_or("").to_string(); + Some(ModelInfo { id, name, description }) + }) + .collect(); + (!available.is_empty()).then_some((current, available)) +} + +/// `session/set_model` parameters. +pub fn set_model_params(session: &str, model: &str) -> Value { + json!({"sessionId": session, "modelId": model}) +} + /// 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) @@ -245,6 +279,8 @@ pub enum Incoming { AuthStatus(String), /// The agent switched to another of its modes. ModeChanged(String), + /// The agent switched to another model. + ModelChanged(String), /// A request we don't serve (file system, terminal, …): answer "method not found". Unsupported { rpc: Value, method: String }, /// Anything else (mode and command lists, usage): nothing to show. @@ -351,6 +387,10 @@ fn update(u: &Value) -> Incoming { Some(m) => Incoming::ModeChanged(m), None => Incoming::Ignored, }, + Some("current_model_update") => match s("currentModelId").or_else(|| s("modelId")) { + Some(m) => Incoming::ModelChanged(m), + None => Incoming::Ignored, + }, Some("plan") => Incoming::Plan( u.get("entries") .and_then(Value::as_array) @@ -496,4 +536,23 @@ mod tests { let Incoming::Tool { output: Some(o), .. } = update(&u) else { panic!() }; assert!(o.len() <= MAX_OUTPUT + 3 && o.ends_with('…')); } + + #[test] + fn the_models_of_a_session_reply_are_read_like_its_modes() { + let v = json!({"sessionId": "s", "models": {"currentModelId": "sonnet", "availableModels": [ + {"modelId": "opus", "name": "Opus", "description": "Most capable"}, + {"modelId": "sonnet", "name": "Sonnet"}, + {"modelId": "haiku"}, + {"name": "no id"}]}}); + let (current, list) = models(&v).unwrap(); + assert_eq!(current, "sonnet"); + let names: Vec<_> = list.iter().map(|m| (m.id.as_str(), m.name.as_str(), m.description.as_str())).collect(); + assert_eq!(names, [("opus", "Opus", "Most capable"), ("sonnet", "Sonnet", ""), ("haiku", "haiku", "")]); + // An agent without models, or with an empty list, reports none. + assert!(models(&json!({"sessionId": "s"})).is_none()); + assert!(models(&json!({"models": {"currentModelId": "x", "availableModels": []}})).is_none()); + let changed = r#"{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"current_model_update","currentModelId":"haiku"}}}"#; + assert_eq!(parse(changed), Some(Incoming::ModelChanged("haiku".into()))); + assert_eq!(set_model_params("s", "opus"), json!({"sessionId": "s", "modelId": "opus"})); + } } diff --git a/crates/ui-egui/src/agent_chat/acp_client.rs b/crates/ui-egui/src/agent_chat/acp_client.rs index 6e11bd497..ca9e16b76 100644 --- a/crates/ui-egui/src/agent_chat/acp_client.rs +++ b/crates/ui-egui/src/agent_chat/acp_client.rs @@ -17,6 +17,7 @@ enum Pending { Prompt, Authenticate, SetMode, + SetModel, } /// Variables the agent doesn't inherit: a control token set for the app's own `--control` port @@ -90,6 +91,9 @@ impl AcpBackend { if let Some((current, available)) = acp::modes(&v) { out.push(Event::Modes { current, available }); } + if let Some((current, available)) = acp::models(&v) { + out.push(Event::Models { current, available }); + } out.push(Event::Ready { agent: self.agent.clone(), images: self.images }); } None => out.push(Event::Error("session/new: no sessionId".into())), @@ -100,7 +104,7 @@ impl AcpBackend { } // Signed in: try the session again. (Pending::Authenticate, Ok(_)) => self.new_session(), - (Pending::SetMode, Ok(_)) => {} + (Pending::SetMode | Pending::SetModel, Ok(_)) => {} (what, Err((code, message))) => { let auth = code == acp::AUTH_REQUIRED || message.to_ascii_lowercase().contains("auth"); if auth { @@ -128,6 +132,7 @@ impl AcpBackend { } Incoming::AuthStatus(s) => out.push(Event::AuthStatus(s)), Incoming::ModeChanged(m) => out.push(Event::Modes { current: m, available: Vec::new() }), + Incoming::ModelChanged(m) => out.push(Event::Models { current: m, available: Vec::new() }), Incoming::Unsupported { rpc, method } => { self.proc.send(&acp::reply_error(rpc, acp::METHOD_NOT_FOUND, &format!("SolidCraft does not serve `{method}`"))); } @@ -178,6 +183,14 @@ impl ChatBackend for AcpBackend { } } + fn new_session(&mut self) { + if self.pending.values().any(|p| *p == Pending::Prompt) { + self.cancel(); + } + self.session = None; + self.new_session(); + } + fn answer_permission(&mut self, key: u64, option: Option<&str>) { if let Some(rpc) = self.permissions.remove(&key) { self.proc.send(&acp::permission_reply(rpc, option)); @@ -194,6 +207,12 @@ impl ChatBackend for AcpBackend { } } + fn set_model(&mut self, model: &str) { + if let Some(s) = self.session.clone() { + self.request(Pending::SetModel, "session/set_model", acp::set_model_params(&s, model)); + } + } + fn pid(&self) -> Option { self.proc.pid() } diff --git a/crates/ui-egui/src/agent_chat/api_client.rs b/crates/ui-egui/src/agent_chat/api_client.rs index 878270f12..8c50fd316 100644 --- a/crates/ui-egui/src/agent_chat/api_client.rs +++ b/crates/ui-egui/src/agent_chat/api_client.rs @@ -14,6 +14,7 @@ use std::time::Duration; use serde_json::{Value, json}; +use super::acp::ModelInfo; use super::backend::{ChatBackend, Event, HttpFn, HttpRequest, PromptPart, StartContext, ToolStatus}; use super::process::{AgentProcess, FromAgent, ProcessHandle}; @@ -27,6 +28,8 @@ const MAX_HISTORY: usize = 240; const REQUEST_TIMEOUT_S: u64 = 300; /// How long one tool call may take (it may wait for the user's Allow). const TOOL_TIMEOUT: Duration = Duration::from_secs(330); +/// How often a waiting request or tool call looks at the cancel flag. +const CANCEL_POLL: Duration = Duration::from_millis(40); /// Tools the model is not offered. const HIDDEN_TOOLS: &[&str] = &["crash_reports"]; @@ -41,6 +44,8 @@ pub struct ApiConfig { enum Cmd { Prompt(Vec), + NewChat, + SetModel(String), } pub struct ApiBackend { @@ -90,6 +95,18 @@ impl ChatBackend for ApiBackend { fn cancel(&mut self) { self.cancel.store(true, Ordering::Relaxed); } + fn set_model(&mut self, model: &str) { + if let Some(c) = &self.cmds { + let _ = c.send(Cmd::SetModel(model.to_string())); + } + } + fn new_session(&mut self) { + // A running turn is cancelled; the worker resets the history once it has ended. + self.cancel.store(true, Ordering::Relaxed); + if let Some(c) = &self.cmds { + let _ = c.send(Cmd::NewChat); + } + } fn answer_permission(&mut self, _key: u64, _option: Option<&str>) {} fn authenticate(&mut self, _method: &str) {} fn pid(&self) -> Option { @@ -134,9 +151,25 @@ impl Worker { } self.history.push(json!({"role": "system", "content": super::acp::SYSTEM_NOTE})); self.emit(Event::Ready { agent: format!("{} · {}", self.cfg.name, self.cfg.model), images: true }); + // The endpoint's models for the picker; an endpoint that does not list them shows none. + if let Ok(list) = model_list(&self.cfg.http, &self.cfg.base_url, self.cfg.key.as_deref()) { + let mut available = list; + if !self.cfg.model.is_empty() && !available.iter().any(|m| m.id == self.cfg.model) { + available.insert(0, ModelInfo { id: self.cfg.model.clone(), name: self.cfg.model.clone(), description: String::new() }); + } + if !available.is_empty() { + self.emit(Event::Models { current: self.cfg.model.clone(), available }); + } + } for cmd in cmds { match cmd { Cmd::Prompt(parts) => self.turn(parts), + Cmd::SetModel(m) => self.cfg.model = m, + Cmd::NewChat => { + self.history.truncate(1); + self.cancel.store(false, Ordering::Relaxed); + self.emit(Event::Ready { agent: format!("{} · {}", self.cfg.name, self.cfg.model), images: true }); + } } } if let Some(mut m) = self.mcp.take() { @@ -152,7 +185,12 @@ impl Worker { m.send(&json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params})); let deadline = std::time::Instant::now() + TOOL_TIMEOUT; loop { - let left = deadline.saturating_duration_since(std::time::Instant::now()); + // Wait in short slices so Stop and Send now do not wait for a slow tool: its late + // answer is skipped later (its id no longer matches). + if self.cancel.load(Ordering::Relaxed) { + return Err("cancelled by the user".into()); + } + let left = deadline.saturating_duration_since(std::time::Instant::now()).min(CANCEL_POLL); match m.from_agent.recv_timeout(left) { Ok(FromAgent::Line(l)) => { let Ok(v) = serde_json::from_str::(l.trim()) else { continue }; @@ -165,6 +203,7 @@ impl Worker { return Ok(v.get("result").cloned().unwrap_or(Value::Null)); } Ok(FromAgent::Exited(_)) => return Err("the SolidCraft tools stopped".into()), + Err(std::sync::mpsc::RecvTimeoutError::Timeout) if std::time::Instant::now() < deadline => {} Err(_) => return Err("the SolidCraft tools did not answer".into()), } } @@ -196,12 +235,25 @@ impl Worker { self.history.remove(1); } for _ in 0..MAX_REQUESTS_PER_TURN { + // The history as of here is complete (every tool call answered): a cancelled request + // goes back to it, so no half-finished round is left to confuse the next message. + let sound = self.history.len(); if self.cancel.load(Ordering::Relaxed) { self.emit(Event::TurnEnded { reason: "cancelled".into() }); return; } let reply = match self.request() { + Ok(_) if self.cancel.load(Ordering::Relaxed) => { + self.history.truncate(sound); + self.emit(Event::TurnEnded { reason: "cancelled".into() }); + return; + } Ok(r) => r, + Err(_) if self.cancel.load(Ordering::Relaxed) => { + self.history.truncate(sound); + self.emit(Event::TurnEnded { reason: "cancelled".into() }); + return; + } Err(e) => { self.emit(Event::Error(e)); self.emit(Event::TurnEnded { reason: "error".into() }); @@ -282,7 +334,23 @@ impl Worker { body: Some(body.to_string().into_bytes()), timeout_s: REQUEST_TIMEOUT_S, }; - let (status, bytes) = (self.cfg.http)(&req)?; + // The request runs on a thread of its own so that Stop does not wait for the model: a + // cancelled one is abandoned (the host's own timeout ends it) and its answer dropped. + let (tx, rx) = channel(); + let http = self.cfg.http.clone(); + std::thread::spawn(move || { + let _ = tx.send(http(&req)); + }); + let (status, bytes) = loop { + if self.cancel.load(Ordering::Relaxed) { + return Err("cancelled by the user".into()); + } + match rx.recv_timeout(CANCEL_POLL) { + Ok(r) => break r?, + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {} + Err(_) => return Err("the request ended without an answer".into()), + } + }; let v: Value = serde_json::from_slice(&bytes).unwrap_or(Value::Null); if status != 200 { return Err(http_error(status, &v)); @@ -413,6 +481,32 @@ fn tool_title(name: &str, args: &Value) -> String { } } +/// `GET {base_url}/models`: the model ids, in the order the endpoint lists them. +fn model_ids(http: &HttpFn, base_url: &str, headers: Vec<(String, String)>) -> Result, String> { + let req = HttpRequest { method: "GET", url: format!("{base_url}/models"), headers, body: None, timeout_s: 15 }; + let (status, bytes) = http(&req)?; + let v: Value = serde_json::from_slice(&bytes).unwrap_or(Value::Null); + if status != 200 { + return Err(http_error(status, &v)); + } + Ok(v.get("data") + .and_then(Value::as_array) + .map(|a| a.iter().take(500).filter_map(|m| m.get("id").and_then(Value::as_str).map(String::from)).collect()) + .unwrap_or_default()) +} + +/// The endpoint's models for the picker. +pub fn model_list(http: &HttpFn, base_url: &str, key: Option<&str>) -> Result, String> { + let mut headers = Vec::new(); + if let Some(k) = key { + if !super::agents::key_safe_for(base_url) { + return Err(crate::i18n::tr("ui.ai_key_needs_https").to_string()); + } + headers.push(("Authorization".to_string(), format!("Bearer {k}"))); + } + Ok(model_ids(http, base_url, headers)?.into_iter().map(|id| ModelInfo { name: id.clone(), id, description: String::new() }).collect()) +} + /// Ask an endpoint for its models (Test connection): how many, and whether `model` is one. pub fn test_endpoint(http: &HttpFn, base_url: &str, key: Option<&str>, model: &str) -> Result { let mut headers = Vec::new(); @@ -422,14 +516,8 @@ pub fn test_endpoint(http: &HttpFn, base_url: &str, key: Option<&str>, model: &s } headers.push(("Authorization".to_string(), format!("Bearer {k}"))); } - let req = HttpRequest { method: "GET", url: format!("{base_url}/models"), headers, body: None, timeout_s: 15 }; - let (status, bytes) = http(&req)?; - let v: Value = serde_json::from_slice(&bytes).unwrap_or(Value::Null); - if status != 200 { - return Err(http_error(status, &v)); - } - let ids: Vec<&str> = - v.get("data").and_then(Value::as_array).map(|a| a.iter().filter_map(|m| m.get("id").and_then(Value::as_str)).collect()).unwrap_or_default(); + let ids = model_ids(http, base_url, headers)?; + let ids: Vec<&str> = ids.iter().map(String::as_str).collect(); let found = model.is_empty() || ids.contains(&model); Ok(crate::i18n::format(if found { "ui.ai_test_ok" } else { "ui.ai_test_no_model" }, &[("count", &ids.len().to_string()), ("model", model)])) } @@ -469,6 +557,9 @@ mod tests { let seen = Arc::new(std::sync::Mutex::new(Vec::::new())); let log = seen.clone(); let http: HttpFn = Arc::new(move |r: &HttpRequest| { + if r.method == "GET" { + return Ok((200, b"{\"data\":[]}".to_vec())); + } log.lock().unwrap().push(serde_json::from_slice(r.body.as_deref().unwrap_or(b"null")).unwrap()); let a = answers.lock().unwrap().pop().unwrap_or(json!({})); Ok((200, a.to_string().into_bytes())) @@ -494,6 +585,138 @@ mod tests { b.shutdown(true); } + /// Cancel while a model request is in flight ends the turn at once (the request is + /// abandoned, its late answer dropped), leaves no half-finished round in the history and + /// the next message goes through. + #[test] + fn cancelling_a_request_ends_the_turn_and_the_next_message_still_works() { + let (release_tx, release_rx) = channel::<()>(); + let release_rx = std::sync::Mutex::new(release_rx); + let seen = Arc::new(std::sync::Mutex::new(Vec::::new())); + let log = seen.clone(); + let http: HttpFn = Arc::new(move |r: &HttpRequest| { + if r.method == "GET" { + return Ok((200, b"{\"data\":[]}".to_vec())); + } + let n = { + let mut l = log.lock().unwrap(); + l.push(serde_json::from_slice(r.body.as_deref().unwrap_or(b"null")).unwrap()); + l.len() + }; + if n == 1 { + // The first request hangs until the test lets it go, then answers late. + let _ = release_rx.lock().unwrap().recv_timeout(Duration::from_secs(20)); + return Ok((200, json!({"choices": [{"message": {"role": "assistant", "content": "Too late."}}]}).to_string().into_bytes())); + } + Ok((200, json!({"choices": [{"message": {"role": "assistant", "content": "Steered."}}]}).to_string().into_bytes())) + }); + let cfg = ApiConfig { name: "Test".into(), base_url: "http://localhost:1/v1".into(), model: "m".into(), key: None, http }; + let ctx = StartContext { cwd: std::env::temp_dir(), bridge: None, tools: None, wake: Box::new(|| {}) }; + let mut b = ApiBackend::start(cfg, ctx).unwrap(); + let wait = |b: &mut ApiBackend, events: &mut Vec| { + let start = std::time::Instant::now(); + while !events.iter().any(|e| matches!(e, Event::TurnEnded { .. })) && start.elapsed() < Duration::from_secs(10) { + events.extend(b.poll()); + std::thread::sleep(Duration::from_millis(10)); + } + }; + b.prompt(&[PromptPart::Text("long job".into())]); + let start = std::time::Instant::now(); + while seen.lock().unwrap().is_empty() && start.elapsed() < Duration::from_secs(10) { + std::thread::sleep(Duration::from_millis(10)); + } + b.cancel(); + let mut events = Vec::new(); + wait(&mut b, &mut events); + assert!(start.elapsed() < Duration::from_secs(8), "the turn ended while the request still hung"); + assert!(matches!(events.last(), Some(Event::TurnEnded { reason }) if reason == "cancelled"), "{events:?}"); + assert!(!events.iter().any(|e| matches!(e, Event::Text { .. } | Event::Error(_))), "{events:?}"); + // The next message is answered, and the late answer of the first never shows up. + b.prompt(&[PromptPart::Text("[interrupted] do this instead".into())]); + let mut events = Vec::new(); + wait(&mut b, &mut events); + let _ = release_tx.send(()); + assert!(events.iter().any(|e| matches!(e, Event::Text { text, .. } if text == "Steered.")), "{events:?}"); + assert!(matches!(events.last(), Some(Event::TurnEnded { reason }) if reason.is_empty()), "{events:?}"); + let sent = seen.lock().unwrap(); + let roles: Vec<&str> = sent[1]["messages"].as_array().unwrap().iter().map(|m| m["role"].as_str().unwrap_or("")).collect(); + assert_eq!(roles, ["system", "user", "user"], "no reply or tool call of the cancelled round is left"); + b.shutdown(true); + } + + /// New chat resets the model's history to the system note: the next request carries nothing + /// of the conversation before it. + #[test] + fn a_new_chat_resets_the_history_to_the_system_note() { + let seen = Arc::new(std::sync::Mutex::new(Vec::::new())); + let log = seen.clone(); + let http: HttpFn = Arc::new(move |r: &HttpRequest| { + if r.method == "GET" { + return Ok((200, b"{\"data\":[]}".to_vec())); + } + log.lock().unwrap().push(serde_json::from_slice(r.body.as_deref().unwrap_or(b"null")).unwrap()); + Ok((200, json!({"choices": [{"message": {"role": "assistant", "content": "ok"}}]}).to_string().into_bytes())) + }); + let cfg = ApiConfig { name: "Test".into(), base_url: "http://localhost:1/v1".into(), model: "m".into(), key: None, http }; + let ctx = StartContext { cwd: std::env::temp_dir(), bridge: None, tools: None, wake: Box::new(|| {}) }; + let mut b = ApiBackend::start(cfg, ctx).unwrap(); + let run = |b: &mut ApiBackend, f: &dyn Fn(&mut ApiBackend), want: usize| { + f(b); + let mut events = Vec::new(); + let start = std::time::Instant::now(); + while events.iter().filter(|e| matches!(e, Event::TurnEnded { .. } | Event::Ready { .. })).count() < want + && start.elapsed() < Duration::from_secs(10) + { + events.extend(b.poll()); + std::thread::sleep(Duration::from_millis(10)); + } + }; + run(&mut b, &|b| b.prompt(&[PromptPart::Text("one".into())]), 2); + run(&mut b, &|b| b.new_session(), 1); + run(&mut b, &|b| b.prompt(&[PromptPart::Text("two".into())]), 1); + let sent = seen.lock().unwrap(); + let roles: Vec<&str> = sent[1]["messages"].as_array().unwrap().iter().map(|m| m["role"].as_str().unwrap_or("")).collect(); + assert_eq!(roles, ["system", "user"]); + assert_eq!(sent[1]["messages"][1]["content"], "two"); + b.shutdown(true); + } + + /// The endpoint's `/models` fills the picker (with the current model first if it is not + /// listed), and choosing one changes the model of the next request. + #[test] + fn the_endpoint_lists_models_and_a_choice_changes_the_next_request() { + let seen = Arc::new(std::sync::Mutex::new(Vec::::new())); + let log = seen.clone(); + let http: HttpFn = Arc::new(move |r: &HttpRequest| { + if r.method == "GET" { + assert!(r.url.ends_with("/models")); + return Ok((200, json!({"data": [{"id": "big"}, {"id": "small"}]}).to_string().into_bytes())); + } + log.lock().unwrap().push(serde_json::from_slice(r.body.as_deref().unwrap_or(b"null")).unwrap()); + Ok((200, json!({"choices": [{"message": {"role": "assistant", "content": "ok"}}]}).to_string().into_bytes())) + }); + let cfg = ApiConfig { name: "Test".into(), base_url: "http://localhost:1/v1".into(), model: "local".into(), key: None, http }; + let ctx = StartContext { cwd: std::env::temp_dir(), bridge: None, tools: None, wake: Box::new(|| {}) }; + let mut b = ApiBackend::start(cfg, ctx).unwrap(); + let mut events = Vec::new(); + let start = std::time::Instant::now(); + while !events.iter().any(|e| matches!(e, Event::Models { .. })) && start.elapsed() < Duration::from_secs(10) { + events.extend(b.poll()); + std::thread::sleep(Duration::from_millis(10)); + } + let Some(Event::Models { current, available }) = events.iter().find(|e| matches!(e, Event::Models { .. })) else { panic!("{events:?}") }; + assert_eq!(current, "local"); + assert_eq!(available.iter().map(|m| m.id.as_str()).collect::>(), ["local", "big", "small"]); + b.set_model("big"); + b.prompt(&[PromptPart::Text("hi".into())]); + let start = std::time::Instant::now(); + while seen.lock().unwrap().is_empty() && start.elapsed() < Duration::from_secs(10) { + std::thread::sleep(Duration::from_millis(10)); + } + assert_eq!(seen.lock().unwrap()[0]["model"], "big"); + b.shutdown(true); + } + #[test] fn tool_arguments_are_an_object_or_an_error() { assert_eq!(tool_arguments(None), Ok(json!({}))); @@ -515,6 +738,9 @@ mod tests { let seen = Arc::new(std::sync::Mutex::new(Vec::::new())); let log = seen.clone(); let http: HttpFn = Arc::new(move |r: &HttpRequest| { + if r.method == "GET" { + return Ok((200, b"{\"data\":[]}".to_vec())); + } log.lock().unwrap().push(serde_json::from_slice(r.body.as_deref().unwrap_or(b"null")).unwrap()); Ok((200, answers.lock().unwrap().pop().unwrap_or(json!({})).to_string().into_bytes())) }); diff --git a/crates/ui-egui/src/agent_chat/backend.rs b/crates/ui-egui/src/agent_chat/backend.rs index 301b92768..a44a54826 100644 --- a/crates/ui-egui/src/agent_chat/backend.rs +++ b/crates/ui-egui/src/agent_chat/backend.rs @@ -40,6 +40,8 @@ pub enum Event { AuthStatus(String), /// Its own modes (an ACP agent's `modes`: ask, accept edits, plan, …) and the current one. Modes { current: String, available: Vec<(String, String)> }, + /// Its models (empty `available`: only the current one changed). + Models { current: String, available: Vec }, /// The message is answered (`reason`: why it stopped, empty for a normal end). TurnEnded { reason: String }, /// Something failed; the backend is still running unless [`Event::Exited`] follows. @@ -69,10 +71,15 @@ pub trait ChatBackend { fn prompt(&mut self, parts: &[PromptPart]); /// Stop the message being answered; open permission questions count as cancelled. fn cancel(&mut self); + /// Start a fresh conversation on the running backend (no restart); [`Event::Ready`] follows. + /// A message being answered is cancelled first. + fn new_session(&mut self); /// Answer an [`Event::Permission`] with one of its options (`None`: cancelled). fn answer_permission(&mut self, key: u64, option: Option<&str>); /// Ask the backend to sign in by itself with one of its methods (it opens the browser). fn authenticate(&mut self, method: &str); + /// Use one of the models it reported in [`Event::Models`]. + fn set_model(&mut self, _model: &str) {} /// Switch to one of the modes it reported in [`Event::Modes`]. fn set_mode(&mut self, _mode: &str) {} /// Its process, for status and tests. diff --git a/crates/ui-egui/src/agent_chat/mod.rs b/crates/ui-egui/src/agent_chat/mod.rs index d7a1cefc0..e4be8689c 100644 --- a/crates/ui-egui/src/agent_chat/mod.rs +++ b/crates/ui-egui/src/agent_chat/mod.rs @@ -145,6 +145,13 @@ struct Turn { label: String, } +/// A message typed while the agent works: shown in the transcript as "Queued" until it is sent. +#[derive(Clone, Debug, PartialEq)] +pub struct Pending { + pub text: String, + pub image: bool, +} + /// A request held for Allow or Deny. struct Held { id: u64, @@ -171,6 +178,25 @@ pub struct AgentChat { auth_status: Option, /// A message typed before the agent was ready. queued: Option<(String, bool)>, + /// Messages typed while the agent works, in order. They go as one prompt when the turn ends + /// (or at once with Send now); after Stop they wait for Send. + pub pending: Vec, + /// The queued message being edited, and its text so far. + pub pending_edit: Option<(usize, String)>, + /// Send now was pressed: the queue goes as soon as the cancelled turn has ended. + steering: bool, + /// The turn was stopped: its queue is not sent by itself. + stopped: bool, + /// Why the last turn ended. + ended: Option, + /// New chat while a message ran: its late end is not reported. + discard_end: bool, + /// The mode to put back when the fresh session is ready. + restore_mode: Option, + /// New chat is waiting for the user's yes (a message is running or queued). + pub confirm_new: bool, + /// Where the panel was drawn last (for its shortcuts). + pub panel_rect: Option, /// The last message sent, kept to send again after a sign-in. last: Option<(String, bool)>, /// The command the running agent was started with. @@ -182,6 +208,13 @@ pub struct AgentChat { /// The agent's own modes, and the current one. modes: Vec<(String, String)>, mode: String, + /// The models the agent offers (none: no picker), and the current one. + pub models: Vec, + pub model: String, + /// An API endpoint's models, kept per endpoint (its base URL) for the next connection. + models_cache: std::collections::HashMap>, + /// The running API agent's endpoint (empty for other agents). + running_endpoint: String, backend: Option>, turn: Option, held: Vec, @@ -227,6 +260,7 @@ impl AgentChat { } fn stop_backend(&mut self, wait: bool) { + self.steering = false; if let Some(mut b) = self.backend.take() { b.cancel(); b.shutdown(wait); @@ -275,6 +309,14 @@ impl AgentChat { self.images = images; self.state = Some(State::Ready); self.picking = Some(false); + // Keep the mode across a new chat. + if let Some(m) = self.restore_mode.take() + && self.modes.iter().any(|(id, _)| *id == m) + && let Some(b) = self.backend.as_mut() + { + b.set_mode(&m); + self.mode = m; + } } Event::Text { thought, text } => { if let Some(Item::Agent { thought: t, text: last }) = self.items.last_mut() @@ -320,6 +362,15 @@ impl AgentChat { } self.mode = current; } + Event::Models { current, available } => { + if !available.is_empty() { + if !self.running_endpoint.is_empty() { + self.models_cache.insert(self.running_endpoint.clone(), available.clone()); + } + self.models = available; + } + self.model = current; + } Event::AuthRequired { methods } => { self.auth = methods; self.state = Some(State::NeedsAuth); @@ -334,6 +385,10 @@ impl AgentChat { if self.state() == State::Busy { self.state = Some(State::Ready); } + self.ended = Some(reason.clone()); + if std::mem::take(&mut self.discard_end) { + return Some(Outcome::TurnEnd); + } if !matches!(reason.as_str(), "" | "auth" | "error") { self.notice(format!("({reason})"), false); } @@ -347,6 +402,7 @@ impl AgentChat { } Event::Exited { tail } => { self.state = Some(State::Exited); + self.steering = false; let last: Vec = tail.into_iter().rev().take(6).collect::>().into_iter().rev().collect(); let detail = if last.is_empty() { String::new() } else { format!("\n{}", last.join("\n")) }; self.notice(format!("{}{detail}", tr("ui.agent_chat_exited")), true); @@ -468,6 +524,14 @@ pub fn connect(app: &mut SolveApp, ctx: &egui::Context) { chat.running_id = entry.id.clone(); chat.modes.clear(); chat.mode.clear(); + chat.models.clear(); + chat.model.clear(); + chat.running_endpoint = if entry.kind == agents::Kind::Api { entry.base_url.clone() } else { String::new() }; + // An endpoint's models from the last time, until the new list arrives. + if let Some(list) = chat.models_cache.get(&chat.running_endpoint) { + chat.models = list.clone(); + chat.model = entry.model.clone(); + } chat.state = Some(State::Starting); chat.auth.clear(); chat.auth_status = None; @@ -496,17 +560,44 @@ pub fn shutdown(app: &mut SolveApp) { app.agent_chat.stop_backend(true); } -/// Send what the user typed: now if the agent is ready, else once it is (starting it if needed). +/// Most messages waiting in the queue. +const MAX_PENDING: usize = 20; +/// Said to the agent before a message that interrupted it, so it knows its last step may be +/// incomplete. +const INTERRUPT_NOTE: &str = "[The user interrupted your previous step.]"; + +/// Send what the user typed: now if the agent is ready, queued behind the running message if it +/// is working, else once it is ready (starting it if needed). pub fn send(app: &mut SolveApp, ctx: &egui::Context, text: String) { let text: String = text.chars().take(MAX_PROMPT).collect(); if text.trim().is_empty() { return; } let image = app.agent_chat.attach_view && app.agent_chat.images; + if app.agent_chat.state() == State::Busy { + let chat = &mut app.agent_chat; + if chat.pending.len() >= MAX_PENDING { + chat.notice(tr("ui.agent_chat_queue_full"), false); + } else { + chat.pending.push(Pending { text, image }); + } + return; + } + // Messages left waiting by Stop go first, in one prompt with this one. + if !app.agent_chat.pending.is_empty() { + app.agent_chat.pending.push(Pending { text, image }); + send_queue(app, ctx, false); + return; + } + submit(app, ctx, text, image, false); +} + +/// Put `text` in the conversation and send it (`interrupted`: the agent is told it cut in on its +/// previous step). +fn submit(app: &mut SolveApp, ctx: &egui::Context, text: String, image: bool, interrupted: bool) { app.agent_chat.push(Item::User { text: text.clone(), image }); match app.agent_chat.state() { - State::Ready => start_turn(app, text, image), - State::Busy => app.agent_chat.notice(tr("ui.agent_chat_wait_turn"), false), + State::Ready => start_turn_with(app, text, image, interrupted.then_some(INTERRUPT_NOTE)), s => { app.agent_chat.queued = Some((text, image)); #[cfg(not(target_arch = "wasm32"))] @@ -519,8 +610,105 @@ pub fn send(app: &mut SolveApp, ctx: &egui::Context, text: String) { } } +/// Send the queued messages as one prompt, in order. +fn send_queue(app: &mut SolveApp, ctx: &egui::Context, interrupted: bool) { + let chat = &mut app.agent_chat; + chat.pending_edit = None; + if chat.pending.is_empty() { + return; + } + let all = std::mem::take(&mut chat.pending); + let image = all.iter().any(|p| p.image); + let text = all.into_iter().map(|p| p.text).collect::>().join("\n\n"); + let text: String = text.chars().take(MAX_PROMPT).collect(); + submit(app, ctx, text, image, interrupted); +} + +/// Send now: stop the running step and send the queue as the next prompt once the agent has said +/// it stopped (its note tells the agent it was interrupted). With nothing running, sends the queue. +pub fn send_now(app: &mut SolveApp, ctx: &egui::Context) { + if app.agent_chat.pending.is_empty() { + return; + } + if app.agent_chat.state() == State::Busy { + app.agent_chat.steering = true; + app.agent_chat.stopped = false; + interrupt(app); + } else { + send_queue(app, ctx, false); + } +} + +/// New chat: stop what runs (as Stop does), clear the conversation and the queue, and start a +/// fresh session on the same agent (no restart); the agent and its mode stay, the design's undo +/// history is untouched. +pub fn new_chat(app: &mut SolveApp) { + let running = app.agent_chat.state() == State::Busy; + if running { + cancel(app); + } + decline_all(app, "the chat was cleared"); + end_turn(app); + let chat = &mut app.agent_chat; + chat.confirm_new = false; + chat.items.clear(); + chat.pending.clear(); + chat.pending_edit = None; + chat.queued = None; + chat.last = None; + chat.steering = false; + chat.stopped = false; + chat.ended = None; + chat.discard_end = running; + if matches!(chat.state(), State::Ready | State::Busy) { + chat.restore_mode = Some(chat.mode.clone()).filter(|m| !m.is_empty()); + chat.state = Some(State::Starting); + if let Some(b) = chat.backend.as_mut() { + b.new_session(); + } + } +} + +/// Whether New chat would throw something away that the user may want (so it asks first). +pub fn new_chat_needs_confirm(app: &SolveApp) -> bool { + app.agent_chat.state() == State::Busy || !app.agent_chat.pending.is_empty() +} + +/// Take a queued message out of the queue. +pub fn remove_pending(app: &mut SolveApp, index: usize) { + let chat = &mut app.agent_chat; + if index < chat.pending.len() { + chat.pending.remove(index); + } + chat.pending_edit = None; +} + +/// The turn ended: the queue goes on its own after a normal end, and after a Send now; not after +/// Stop, a sign-in request or an error. +fn after_turn(app: &mut SolveApp, ctx: &egui::Context) { + let reason = app.agent_chat.ended.take().unwrap_or_default(); + let steering = std::mem::take(&mut app.agent_chat.steering); + if app.agent_chat.state() != State::Ready || app.agent_chat.pending.is_empty() { + return; + } + if steering && !matches!(reason.as_str(), "auth" | "error") { + send_queue(app, ctx, reason == "cancelled"); + } else if !app.agent_chat.stopped && reason.is_empty() { + send_queue(app, ctx, false); + } +} + fn start_turn(app: &mut SolveApp, text: String, image: bool) { - let mut parts = vec![PromptPart::Text(text.clone())]; + start_turn_with(app, text, image, None); +} + +/// Start a message; `note` goes before the text for the agent, not into the conversation. +fn start_turn_with(app: &mut SolveApp, text: String, image: bool, note: Option<&str>) { + let sent = match note { + Some(n) => format!("{n}\n\n{text}"), + None => text.clone(), + }; + let mut parts = vec![PromptPart::Text(sent)]; if image { match crate::control::view_png(app, VIEW_IMAGE.0, VIEW_IMAGE.1) { Ok(png) => parts.push(PromptPart::Image { mime: "image/png".into(), base64: backend::base64(&png) }), @@ -532,13 +720,24 @@ fn start_turn(app: &mut SolveApp, text: String, image: bool) { Some(Turn { start_doc: app.session.doc.clone(), start_undo: app.session.undo.len(), changes: 0, requests: 0, limit_told: false, label }); app.agent_chat.last = Some((text, image)); app.agent_chat.state = Some(State::Busy); + app.agent_chat.stopped = false; + app.agent_chat.steering = false; + app.agent_chat.ended = None; if let Some(b) = app.agent_chat.backend.as_mut() { b.prompt(&parts); } } -/// Ask the agent to stop the message it is on; requests waiting for approval are declined. +/// Stop: ask the agent to stop the message it is on; requests waiting for approval are declined. +/// Messages queued meanwhile stay queued (they wait for Send). pub fn cancel(app: &mut SolveApp) { + app.agent_chat.steering = false; + app.agent_chat.stopped = true; + interrupt(app); +} + +/// Ask the agent to stop the message it is on and decline what waits for approval. +fn interrupt(app: &mut SolveApp) { decline_all(app, "the user stopped the message"); if let Some(b) = app.agent_chat.backend.as_mut() { b.cancel(); @@ -775,10 +974,16 @@ pub fn poll(app: &mut SolveApp, ctx: &egui::Context) { for e in events { let ready = matches!(e, Event::Ready { .. }); match app.agent_chat.on_event(e) { - Some(Outcome::TurnEnd) => end_turn(app), + Some(Outcome::TurnEnd) => { + end_turn(app); + after_turn(app, ctx); + } Some(Outcome::Permission { key, title, options }) => on_permission(app, key, title, options), None => {} } + if ready { + apply_saved_model(app); + } if ready && let Some((text, image)) = app.agent_chat.queued.take() { start_turn(app, text, image); } @@ -804,6 +1009,37 @@ pub fn refresh(app: &mut SolveApp, ctx: &egui::Context) { app.agent_chat.detecting = Some(rx); } +/// Choose the model for this chat (the header's model picker): the agent switches to it, and it is +/// remembered for this agent; an API endpoint's agent also keeps it as its default model. +pub fn set_model(app: &mut SolveApp, model: &str) { + if !app.agent_chat.models.iter().any(|m| m.id == model) { + return; + } + if let Some(b) = app.agent_chat.backend.as_mut() { + b.set_model(model); + } + app.agent_chat.model = model.to_string(); + let agent = app.agent_chat.running_id.clone(); + if let Some(a) = app.preferences.agents.iter_mut().find(|a| a.id == agent && a.kind == agents::Kind::Api) { + a.model = model.to_string(); + } + app.preferences.agent_models.insert(agent, model.to_string()); +} + +/// A new session is ready: put back the model last chosen for this agent, when it offers it. +fn apply_saved_model(app: &mut SolveApp) { + let chat = &app.agent_chat; + let Some(saved) = app.preferences.agent_models.get(&chat.running_id).cloned() else { return }; + if saved != chat.model && chat.models.iter().any(|m| m.id == saved) { + set_model(app, &saved); + } +} + +/// Whether the model picker shows: only for an agent that reports models. +pub fn models_shown(app: &SolveApp) -> bool { + !app.agent_chat.models.is_empty() && app.agent_chat.state().running() +} + /// Switch the agent to one of its own modes (the header's mode picker). pub fn set_mode(app: &mut SolveApp, mode: &str) { if app.agent_chat.modes.iter().any(|(id, _)| id == mode) @@ -817,7 +1053,7 @@ pub fn set_mode(app: &mut SolveApp, mode: &str) { /// `ui.agent_chat` on the control channel (tests and screenshots): `enabled`, `command`, `open`, /// `side`, `minimized`, `width`, `refresh`, `connect`, `stop`, `send`, `attach_view`, /// `permission` (an option id, or `"cancel"`), `approve` (`true`/`false`, the oldest held -/// request), `cancel`, `undo` (the newest message's changes); returns the panel's state. +/// request), `cancel` (Stop), `send_now` (steer: stop, then send the queue), `remove_pending` (index), `undo` (the newest message's changes); returns the panel's state. pub fn control(app: &mut SolveApp, ctx: &egui::Context, p: &Value) -> Result { if let Some(e) = p.get("features").and_then(Value::as_bool) { app.preferences.ai_features = e; @@ -875,6 +1111,9 @@ pub fn control(app: &mut SolveApp, ctx: &egui::Context, p: &Value) -> Result Result Value { "permissions": app.preferences.ai_permissions.id(), "agents": agents::entries(app).iter().map(|e| json!({"id": e.id, "name": e.name, "kind": if e.kind == agents::Kind::Api { "api" } else { "acp" }, "found": e.found, "version": e.version, "login": e.login})).collect::>(), "currentAgent": agents::current(app).map(|e| e.id), + "models": c.models.iter().map(|m| json!({"id": m.id, "name": m.name, "description": m.description})).collect::>(), + "model": c.model, "modes": c.modes.iter().map(|(id, name)| json!({"id": id, "name": name})).collect::>(), "mode": c.mode, "open": c.open, @@ -990,6 +1240,8 @@ pub fn status(app: &SolveApp) -> Value { "toolsPort": c.tools_port, "pid": pid, "waiting": c.waiting(), + "pending": c.pending.iter().map(|p| json!({"text": p.text, "image": p.image})).collect::>(), + "stopped": c.stopped, "turn": c.turn.as_ref().map(|t| json!({"changes": t.changes, "requests": t.requests})), "detection": detection, "items": items, diff --git a/crates/ui-egui/src/agent_chat/panel.rs b/crates/ui-egui/src/agent_chat/panel.rs index 44f0ecf26..087a26dc0 100644 --- a/crates/ui-egui/src/agent_chat/panel.rs +++ b/crates/ui-egui/src/agent_chat/panel.rs @@ -58,6 +58,12 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { if ctx.input_mut(|i| i.consume_shortcut(&SHORTCUT)) { toggle(app); } + // New chat, when the chat has focus (its input, or the pointer over the panel). + let in_chat = ctx.memory(|m| m.has_focus(Id::new("sc_agent_chat_input"))) + || ctx.pointer_hover_pos().is_some_and(|p| app.agent_chat.panel_rect.is_some_and(|r| r.contains(p))); + if app.agent_chat.open && in_chat && ctx.input_mut(|i| i.consume_shortcut(&NEW_CHAT_SHORTCUT)) { + request_new_chat(app); + } if !app.agent_chat.open { return; } @@ -81,13 +87,27 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { .frame(egui::Frame::NONE.fill(t.panel).inner_margin(egui::Margin::symmetric(8, 6))) .show(ui, |ui| body(app, ui, left)); crate::scenario::publish_rect("agent_chat:panel", r.response.rect); + app.agent_chat.panel_rect = Some(r.response.rect); let w = r.response.rect.width(); if w.is_finite() && (MIN_WIDTH..=MAX_WIDTH).contains(&w) { app.preferences.agent_chat_width = w; } } -/// A small drawn button: `kind` is `minimize`, `close` or `expand`. +/// New chat (when the chat has focus). +pub const NEW_CHAT_SHORTCUT: egui::KeyboardShortcut = + egui::KeyboardShortcut::new(egui::Modifiers::COMMAND.plus(egui::Modifiers::SHIFT), egui::Key::L); + +/// Clear the chat, asking first when something would be lost. +fn request_new_chat(app: &mut SolveApp) { + if new_chat_needs_confirm(app) { + app.agent_chat.confirm_new = true; + } else { + new_chat(app); + } +} + +/// A small drawn button: `kind` is `minimize`, `close`, `stopturn` or `expand`. fn glyph_button(ui: &mut egui::Ui, kind: &str, tip: &str) -> egui::Response { let t = Tokens::get(); let (r, resp) = ui.allocate_exact_size(vec2(22.0, 22.0), Sense::click()); @@ -104,6 +124,15 @@ fn glyph_button(ui: &mut egui::Ui, kind: &str, tip: &str) -> egui::Response { ui.painter().line_segment([c + vec2(-4.5, -4.5), c + vec2(4.5, 4.5)], s); ui.painter().line_segment([c + vec2(-4.5, 4.5), c + vec2(4.5, -4.5)], s); } + "newchat" => { + // A speech bubble with a plus. + ui.painter().rect_stroke(Rect::from_center_size(c, vec2(14.0, 11.0)), 2.5, s, egui::StrokeKind::Inside); + ui.painter().line_segment([c + vec2(-2.5, 0.0), c + vec2(2.5, 0.0)], Stroke::new(1.2, t.text)); + ui.painter().line_segment([c + vec2(0.0, -2.5), c + vec2(0.0, 2.5)], Stroke::new(1.2, t.text)); + } + "stopturn" => { + ui.painter().rect_filled(Rect::from_center_size(c, vec2(9.0, 9.0)), 1.5, t.error); + } _ => {} } crate::scenario::publish_handle(&format!("agent_chat:{kind}"), r.center()); @@ -185,6 +214,16 @@ fn header(app: &mut SolveApp, ui: &mut egui::Ui, left: bool) { app.preferences.agent_chat_minimized = true; } #[cfg(not(target_arch = "wasm32"))] + if glyph_button( + ui, + "newchat", + &format!("{} ({})", tr("ui.agent_chat_new"), if cfg!(target_os = "macos") { "Cmd+Shift+L" } else { "Ctrl+Shift+L" }), + ) + .clicked() + { + request_new_chat(app); + } + #[cfg(not(target_arch = "wasm32"))] { let b = if state.running() { ui.button(tr("ui.agent_chat_stop")).on_hover_text(tr("ui.agent_chat_stop_tip")) @@ -261,6 +300,23 @@ fn desktop_body(app: &mut SolveApp, ui: &mut egui::Ui) { refresh(app, ui.ctx()); } let state = app.agent_chat.state(); + if app.agent_chat.confirm_new { + let t = Tokens::get(); + egui::Frame::NONE.fill(t.accent_soft).corner_radius(6.0).inner_margin(egui::Margin::same(6)).show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.label(tr("ui.agent_chat_new_confirm")); + ui.horizontal(|ui| { + let yes = ui.button(tr("ui.agent_chat_new_yes")); + crate::scenario::publish_handle("agent_chat:new_confirm", yes.rect.center()); + if yes.clicked() { + new_chat(app); + } + if ui.button(tr("ui.agent_chat_cancel")).clicked() { + app.agent_chat.confirm_new = false; + } + }); + }); + } picker(app, ui); if state == State::NeedsAuth { auth_box(app, ui); @@ -275,21 +331,38 @@ fn desktop_body(app: &mut SolveApp, ui: &mut egui::Ui) { ui.separator(); let busy = state == State::Busy; let edit = egui::TextEdit::multiline(&mut app.agent_chat.input) - .hint_text(tr("ui.agent_chat_placeholder")) + .hint_text(tr(if busy { "ui.agent_chat_placeholder_busy" } else { "ui.agent_chat_placeholder" })) .desired_rows(2) .desired_width(f32::INFINITY) .id_salt("sc_agent_chat_input"); + // Enter sends (queues while the agent works); Ctrl/Cmd+Enter sends now; Esc stops. They are + // read before the field sees them so no newline is typed. + let focused = ui.memory(|m| m.has_focus(Id::new("sc_agent_chat_input"))); + let (steer, esc) = if focused { + ui.input_mut(|i| (i.consume_key(egui::Modifiers::COMMAND, egui::Key::Enter), busy && i.consume_key(egui::Modifiers::NONE, egui::Key::Escape))) + } else { + (false, false) + }; let r = ui.add(edit); crate::scenario::publish_rect("agent_chat:input", r.rect); let enter = r.has_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter) && !i.modifiers.shift); + if esc { + cancel(app); + } ui.horizontal(|ui| { - let send_b = ui.add_enabled(!busy, egui::Button::new(tr("ui.agent_chat_send"))); + let send_b = ui.button(tr(if busy { "ui.agent_chat_queue" } else { "ui.agent_chat_send" })); crate::scenario::publish_handle("agent_chat:send", send_b.rect.center()); - if (send_b.clicked() || (enter && !busy)) && !app.agent_chat.input.trim().is_empty() { + if (send_b.clicked() || enter || steer) && !app.agent_chat.input.trim().is_empty() { let text = std::mem::take(&mut app.agent_chat.input).trim_end_matches('\n').to_string(); send(app, ui.ctx(), text); + if steer { + send_now(app, ui.ctx()); + } + } else if steer { + // Nothing typed: Ctrl+Enter sends what is already queued. + send_now(app, ui.ctx()); } - if busy && ui.button(tr("ui.agent_chat_cancel")).clicked() { + if busy && glyph_button(ui, "stopturn", tr("ui.agent_chat_stop_turn_tip")).clicked() { cancel(app); } // A picture of the view goes with the message to agents that take pictures. @@ -350,7 +423,9 @@ fn switcher(app: &mut SolveApp, ui: &mut egui::Ui) { || tr(if app.agent_chat.detecting.is_some() { "ui.agent_chat_detecting" } else { "ui.agent_chat_none_found_short" }).to_string(), |e| e.name.clone(), ); - let w = (ui.available_width() - if app.agent_chat.modes.is_empty() { 4.0 } else { 120.0 }).clamp(120.0, 260.0); + let models = models_shown(app); + let w = + (ui.available_width() - if app.agent_chat.modes.is_empty() { 4.0 } else { 116.0 } - if models { 146.0 } else { 0.0 }).clamp(90.0, 260.0); let mut picked: Option = None; let mut add = false; let combo = egui::ComboBox::from_id_salt("sc_agent_switch").width(w).selected_text(RichText::new(label).strong()).show_ui(ui, |ui| { @@ -405,6 +480,27 @@ fn switcher(app: &mut SolveApp, ui: &mut egui::Ui) { set_mode(app, &m); } } + // The agent's models (ACP `models`, or an endpoint's list): shown only when it reports some. + if models { + let list = app.agent_chat.models.clone(); + let cur = list.iter().find(|m| m.id == app.agent_chat.model).map_or_else(|| app.agent_chat.model.clone(), |m| m.name.clone()); + let mut pick: Option = None; + let r = egui::ComboBox::from_id_salt("sc_agent_model").width(140.0).truncate().selected_text(cur).show_ui(ui, |ui| { + for m in &list { + let row = ui.selectable_label(m.id == app.agent_chat.model, &m.name); + let row = if m.description.is_empty() { row } else { row.on_hover_text(&m.description) }; + crate::scenario::publish_handle(&format!("agent_chat:model:{}", m.id), row.rect.center()); + if row.clicked() { + pick = Some(m.id.clone()); + } + } + }); + crate::scenario::publish_handle("agent_chat:model", r.response.rect.center()); + r.response.on_hover_text(tr("ui.agent_chat_model_tip")); + if let Some(m) = pick { + set_model(app, &m); + } + } }); if let Some(a) = &app.agent_chat.auth_status { ui.label(RichText::new(a).color(t.text_dim).size(11.0)); @@ -641,12 +737,97 @@ fn conversation(app: &mut SolveApp, ui: &mut egui::Ui) { } ui.add_space(2.0); } - if app.agent_chat.items.is_empty() { + let (mut send_now_clicked, mut send_queue_clicked) = (false, false); + let mut remove: Option = None; + let mut edit_done: Option<(usize, Option)> = None; + let busy = app.agent_chat.state() == State::Busy; + let stopped = app.agent_chat.stopped; + let editing = app.agent_chat.pending_edit.clone(); + let mut start_edit: Option<(usize, String)> = None; + let mut edit_buf = editing.as_ref().map(|(_, b)| b.clone()); + for (n, p) in app.agent_chat.pending.iter().enumerate() { + ui.add_space(6.0); + egui::Frame::NONE.fill(t.panel).stroke(Stroke::new(1.0, t.accent)).corner_radius(6.0).inner_margin(egui::Margin::same(6)).show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.horizontal(|ui| { + let tag = if stopped && !busy { "ui.agent_chat_queued_stopped" } else { "ui.agent_chat_queued" }; + ui.label(RichText::new(tr(tag)).color(t.accent).strong().size(11.0)); + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + let x = ui.add(egui::Button::new(RichText::new("×").size(14.0)).frame(false)).on_hover_text(tr("ui.agent_chat_remove")); + crate::scenario::publish_handle(&format!("agent_chat:pending_remove:{n}"), x.rect.center()); + if x.clicked() { + remove = Some(n); + } + if editing.as_ref().is_none_or(|(i, _)| *i != n) { + let e = ui.add(egui::Button::new(RichText::new(tr("ui.agent_chat_edit")).size(11.5)).frame(false)); + crate::scenario::publish_handle(&format!("agent_chat:pending_edit:{n}"), e.rect.center()); + if e.clicked() { + start_edit = Some((n, p.text.clone())); + } + } + }); + }); + match (&editing, edit_buf.as_mut()) { + (Some((i, _)), Some(buf)) if *i == n => { + let te = ui.add(egui::TextEdit::multiline(buf).desired_rows(2).desired_width(f32::INFINITY)); + crate::scenario::publish_rect("agent_chat:pending_input", te.rect); + ui.horizontal(|ui| { + if ui.button(tr("ui.agent_chat_save")).clicked() { + edit_done = Some((n, Some(buf.clone()))); + } + if ui.button(tr("ui.agent_chat_cancel")).clicked() { + edit_done = Some((n, None)); + } + }); + } + _ => { + ui.add(egui::Label::new(RichText::new(&p.text).color(t.text)).selectable(true).wrap()); + if p.image { + ui.label(RichText::new(tr("ui.agent_chat_view_attached")).color(t.text_dim).size(11.0)); + } + } + } + }); + } + if !app.agent_chat.pending.is_empty() && editing.is_none() { + ui.horizontal(|ui| { + if busy { + let b = ui.button(tr("ui.agent_chat_send_now")).on_hover_text(tr("ui.agent_chat_send_now_tip")); + crate::scenario::publish_handle("agent_chat:send_now", b.rect.center()); + send_now_clicked = b.clicked(); + } else { + let b = ui.add(egui::Button::new(tr("ui.agent_chat_send")).fill(t.accent_soft)); + crate::scenario::publish_handle("agent_chat:send_queue", b.rect.center()); + send_queue_clicked = b.clicked(); + } + }); + } + if let Some(start) = start_edit { + app.agent_chat.pending_edit = Some(start); + } else if let (Some(buf), Some(slot)) = (edit_buf, app.agent_chat.pending_edit.as_mut()) { + slot.1 = buf; + } + if app.agent_chat.items.is_empty() && app.agent_chat.pending.is_empty() { ui.add_space(12.0); ui.label(RichText::new(tr("ui.agent_chat_intro")).color(t.text_dim)); ui.add_space(6.0); ui.label(RichText::new(tr("ui.agent_chat_privacy")).color(t.text_dim).size(11.0)); } + if let Some((n, text)) = edit_done { + if let (Some(text), Some(p)) = (text.filter(|t| !t.trim().is_empty()), app.agent_chat.pending.get_mut(n)) { + p.text = text; + } + app.agent_chat.pending_edit = None; + } + if let Some(n) = remove { + remove_pending(app, n); + } + if send_now_clicked { + send_now(app, ui.ctx()); + } + if send_queue_clicked { + send_now(app, ui.ctx()); + } if let Some((n, o)) = answer { answer_permission(app, n, o.as_deref()); } diff --git a/crates/ui-egui/src/agent_chat/tests.rs b/crates/ui-egui/src/agent_chat/tests.rs index a2208cc18..52eb2a90f 100644 --- a/crates/ui-egui/src/agent_chat/tests.rs +++ b/crates/ui-egui/src/agent_chat/tests.rs @@ -303,3 +303,456 @@ fn the_agents_own_questions_are_answered_by_the_mode_or_asked() { on_permission(&mut app, 3, "Run ls".into(), opts()); assert!(matches!(app.agent_chat.items.last(), Some(Item::Notice { .. })), "remembered"); } + +// ---- Messages typed while the agent works ---- + +use std::sync::Mutex; + +/// A backend that records what the panel asks of it, and reports what the test pushes. +#[derive(Clone, Default)] +struct Script { + calls: Arc>>, + events: Arc>>, +} + +impl Script { + fn calls(&self) -> Vec { + self.calls.lock().unwrap().clone() + } + fn report(&self, e: Event) { + self.events.lock().unwrap().push(e); + } +} + +impl ChatBackend for Script { + fn poll(&mut self) -> Vec { + std::mem::take(&mut *self.events.lock().unwrap()) + } + fn prompt(&mut self, parts: &[PromptPart]) { + let text = parts.iter().find_map(|p| if let PromptPart::Text(t) = p { Some(t.clone()) } else { None }).unwrap_or_default(); + self.calls.lock().unwrap().push(format!("prompt: {text}")); + } + fn cancel(&mut self) { + self.calls.lock().unwrap().push("cancel".into()); + } + fn new_session(&mut self) { + self.calls.lock().unwrap().push("new_session".into()); + } + fn set_model(&mut self, model: &str) { + self.calls.lock().unwrap().push(format!("set_model: {model}")); + } + fn answer_permission(&mut self, _: u64, _: Option<&str>) {} + fn authenticate(&mut self, _: &str) {} + fn shutdown(&mut self, _: bool) {} +} + +/// An app whose agent is scripted and ready. +fn app_with_script() -> (SolveApp, Script, egui::Context) { + let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + let script = Script::default(); + app.agent_chat.backend = Some(Box::new(script.clone())); + app.agent_chat.state = Some(State::Ready); + (app, script, egui::Context::default()) +} + +fn ended(script: &Script, reason: &str) { + script.report(Event::TurnEnded { reason: reason.into() }); +} + +fn texts(app: &SolveApp) -> Vec { + app.agent_chat.pending.iter().map(|p| p.text.clone()).collect() +} + +/// While the agent works a message is queued, not dropped and not sent; it is not in the +/// transcript as a sent message, but waits as a pending one that can be edited and removed. +#[test] +fn a_message_typed_while_busy_is_queued() { + let (mut app, script, ctx) = app_with_script(); + send(&mut app, &ctx, "make a box".into()); + assert_eq!(app.agent_chat.state(), State::Busy); + send(&mut app, &ctx, "then a cylinder".into()); + send(&mut app, &ctx, " ".into()); + send(&mut app, &ctx, "and a sphere".into()); + assert_eq!(texts(&app), ["then a cylinder", "and a sphere"]); + assert_eq!(script.calls(), ["prompt: make a box"], "nothing else was sent"); + let users = app.agent_chat.items.iter().filter(|i| matches!(i, Item::User { .. })).count(); + assert_eq!(users, 1, "queued messages are not sent messages yet"); + // Remove one; edit the other. + remove_pending(&mut app, 0); + assert_eq!(texts(&app), ["and a sphere"]); + app.agent_chat.pending[0].text = "and a cone".into(); + assert_eq!(app.agent_chat.waiting(), 0); + assert!(status(&app)["pending"][0]["text"] == "and a cone"); +} + +/// When the turn ends normally the queue goes as the next prompt, all messages in order in one. +#[test] +fn the_queue_is_sent_when_the_turn_ends() { + let (mut app, script, ctx) = app_with_script(); + send(&mut app, &ctx, "first".into()); + send(&mut app, &ctx, "second".into()); + send(&mut app, &ctx, "third".into()); + ended(&script, ""); + poll(&mut app, &ctx); + assert_eq!(script.calls(), ["prompt: first", "prompt: second\n\nthird"]); + assert!(app.agent_chat.pending.is_empty()); + assert_eq!(app.agent_chat.state(), State::Busy, "the next turn is under way"); + assert!(matches!(app.agent_chat.items.last(), Some(Item::User { text, .. }) if text == "second\n\nthird")); + // Nothing queued: the end of the turn just ends it. + ended(&script, ""); + poll(&mut app, &ctx); + assert_eq!(app.agent_chat.state(), State::Ready); + assert_eq!(script.calls().len(), 2); +} + +/// Stop does not send the queue by itself; it stays, with a Send that sends it later. +#[test] +fn stop_keeps_the_queue() { + let (mut app, script, ctx) = app_with_script(); + send(&mut app, &ctx, "first".into()); + send(&mut app, &ctx, "later".into()); + cancel(&mut app); + assert_eq!(script.calls(), ["prompt: first", "cancel"]); + ended(&script, "cancelled"); + poll(&mut app, &ctx); + assert_eq!(app.agent_chat.state(), State::Ready); + assert_eq!(texts(&app), ["later"], "still queued"); + assert_eq!(script.calls().len(), 2, "not sent"); + // Send (the bubble's button) sends it, without the interruption note. + send_now(&mut app, &ctx); + assert_eq!(script.calls(), ["prompt: first", "cancel", "prompt: later"]); + assert!(app.agent_chat.pending.is_empty()); +} + +/// Send now: cancel first, the prompt only after the agent has ended the cancelled turn, with a +/// note that the previous step was interrupted (shown without it in the conversation). +#[test] +fn send_now_cancels_then_sends_with_a_note() { + let (mut app, script, ctx) = app_with_script(); + send(&mut app, &ctx, "build a gearbox".into()); + send(&mut app, &ctx, "use 12 teeth instead".into()); + send_now(&mut app, &ctx); + assert_eq!(script.calls(), ["prompt: build a gearbox", "cancel"], "cancel alone, the prompt waits for the end"); + poll(&mut app, &ctx); + assert_eq!(script.calls().len(), 2); + ended(&script, "cancelled"); + poll(&mut app, &ctx); + assert_eq!(script.calls(), ["prompt: build a gearbox".to_string(), "cancel".into(), format!("prompt: {INTERRUPT_NOTE}\n\nuse 12 teeth instead")]); + assert!(matches!(app.agent_chat.items.last(), Some(Item::User { text, .. }) if text == "use 12 teeth instead")); + // Stop after Send now wins: nothing more is sent by itself. + send(&mut app, &ctx, "one more".into()); + send_now(&mut app, &ctx); + cancel(&mut app); + ended(&script, "cancelled"); + poll(&mut app, &ctx); + assert_eq!(texts(&app), ["one more"]); +} + +/// The steered message also goes after a turn that ended by itself just before the cancel arrived. +#[test] +fn send_now_after_the_turn_already_ended_still_sends() { + let (mut app, script, ctx) = app_with_script(); + send(&mut app, &ctx, "a".into()); + send(&mut app, &ctx, "b".into()); + send_now(&mut app, &ctx); + ended(&script, ""); + poll(&mut app, &ctx); + assert_eq!(script.calls().last().map(String::as_str), Some("prompt: b"), "no note: nothing was interrupted"); +} + +/// What an interrupted turn changed undoes as one step, and the steered message starts its own. +#[test] +fn an_interrupted_turns_changes_undo_as_one_step() { + let (mut app, script, ctx) = app_with_script(); + let (tx, rx) = channel(); + app.agent_chat.tools_rx = Some(rx); + let before = app.session.doc.clone(); + let depth = app.session.undo.len(); + send(&mut app, &ctx, "two boxes".into()); + let replies: Vec<_> = [0.0, 20.0].into_iter().map(|x| ask(&tx, "engine.execute", boxed(x))).collect(); + frame(&mut app); + for r in replies { + assert_eq!(r.recv_timeout(std::time::Duration::from_secs(30)).unwrap()["ok"], true); + } + send(&mut app, &ctx, "stop, make it one".into()); + send_now(&mut app, &ctx); + ended(&script, "cancelled"); + poll(&mut app, &ctx); + assert_eq!(app.session.undo.len(), depth + 1, "the interrupted message is one step"); + let n = app.agent_chat.items.iter().rposition(|i| matches!(i, Item::Changes { steps: 2, .. })).expect("its changes are listed"); + // The steered message is on its own turn. + assert!(app.agent_chat.turn.as_ref().is_some_and(|t| t.label.contains("stop, make it one") && t.changes == 0)); + undo_changes(&mut app, n); + assert!(Arc::ptr_eq(&app.session.doc, &before)); +} + +/// The same with a real agent process speaking ACP: `session/cancel` goes out, the agent answers +/// the held prompt with the cancelled stop reason, and only then does the queued text go as a new +/// `session/prompt`. +#[cfg(unix)] +#[test] +fn send_now_with_an_acp_agent_sends_cancel_then_the_prompt() { + let dir = std::env::temp_dir().join(format!("sc-agent-chat-steer-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let log = dir.join("received.log"); + // A fake agent: answers initialize and session/new; holds a prompt whose text says "slow" + // until it gets session/cancel (then answers it "cancelled"); answers other prompts at once. + let script = r#" +log="$1"; held="" +while IFS= read -r line; do + printf '%s\n' "$line" >> "$log" + id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9][0-9]*\).*/\1/p') + case "$line" in + *'"method":"initialize"'*) printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentInfo":{"name":"fake","version":"1"}}}\n' "$id" ;; + *'"method":"session/new"'*) printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"s1"}}\n' "$id" ;; + *'"method":"session/prompt"'*) + case "$line" in + *slow*) held="$id" ;; + *) printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn"}}\n' "$id" ;; + esac ;; + *'"method":"session/cancel"'*) + if [ -n "$held" ]; then printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"cancelled"}}\n' "$held"; held=""; fi ;; + esac +done +"#; + let argv = vec!["sh".to_string(), "-c".to_string(), script.to_string(), "fake-agent".to_string(), log.to_string_lossy().into_owned()]; + let start = backend::StartContext { cwd: dir.clone(), bridge: None, tools: None, wake: Box::new(|| {}) }; + let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + app.agent_chat.backend = Some(Box::new(acp_client::AcpBackend::start(&argv, start).unwrap())); + app.agent_chat.state = Some(State::Starting); + let ctx = egui::Context::default(); + let until = |app: &mut SolveApp, what: &str, done: &dyn Fn(&SolveApp) -> bool| { + let t = std::time::Instant::now(); + while !done(app) { + assert!(t.elapsed() < std::time::Duration::from_secs(20), "timed out waiting for {what}"); + poll(app, &ctx); + std::thread::sleep(std::time::Duration::from_millis(10)); + } + }; + until(&mut app, "the agent to be ready", &|a| a.agent_chat.state() == State::Ready); + send(&mut app, &ctx, "slow job".into()); + send(&mut app, &ctx, "do this instead".into()); + assert_eq!(texts(&app), ["do this instead"]); + send_now(&mut app, &ctx); + until(&mut app, "the steered turn to finish", &|a| a.agent_chat.state() == State::Ready && a.agent_chat.pending.is_empty()); + let methods: Vec = std::fs::read_to_string(&log) + .unwrap() + .lines() + .filter_map(|l| serde_json::from_str::(l).ok()) + .filter_map(|v| { + let m = v["method"].as_str()?.to_string(); + let text = v.pointer("/params/prompt/0/text").and_then(Value::as_str).unwrap_or(""); + Some(if text.is_empty() { m } else { format!("{m}: {text}") }) + }) + .collect(); + assert_eq!( + methods, + [ + "initialize".to_string(), + "session/new".into(), + "session/prompt: slow job".into(), + "session/cancel".into(), + format!("session/prompt: {INTERRUPT_NOTE}\n\ndo this instead"), + ] + ); + disconnect(&mut app); + let _ = std::fs::remove_dir_all(&dir); +} + +/// New chat: the running message is stopped, the transcript and the queue are cleared, a fresh +/// session starts on the same agent, the mode stays, and the design's undo history is untouched. +#[test] +fn new_chat_clears_everything_and_keeps_the_agent_and_mode() { + let (mut app, script, ctx) = app_with_script(); + app.agent_chat.modes = vec![("plan".into(), "Plan".into()), ("code".into(), "Code".into())]; + app.agent_chat.mode = "plan".into(); + app.agent_chat.agent_id = Some("claude".into()); + let depth = app.session.undo.len(); + assert!(!new_chat_needs_confirm(&app)); + send(&mut app, &ctx, "first".into()); + send(&mut app, &ctx, "queued".into()); + assert!(new_chat_needs_confirm(&app), "a running message and a queue ask first"); + new_chat(&mut app); + assert_eq!(script.calls(), ["prompt: first", "cancel", "new_session"]); + assert!(app.agent_chat.items.is_empty() && app.agent_chat.pending.is_empty()); + assert_eq!(app.agent_chat.state(), State::Starting); + assert_eq!(app.agent_chat.agent_id.as_deref(), Some("claude")); + // The cancelled message's late end is not reported; the fresh session is ready again. + ended(&script, "cancelled"); + script.report(Event::Modes { current: "code".into(), available: vec![] }); + script.report(Event::Ready { agent: "fake".into(), images: false }); + poll(&mut app, &ctx); + assert_eq!(app.agent_chat.state(), State::Ready); + assert!(app.agent_chat.items.is_empty(), "no notice about the old message"); + assert_eq!(app.agent_chat.mode, "plan", "the mode is kept"); + assert_eq!(app.session.undo.len(), depth); + assert!(!new_chat_needs_confirm(&app)); +} + +/// With a real ACP agent, New chat sends `session/new` on the same process (no restart). +#[cfg(unix)] +#[test] +fn new_chat_with_an_acp_agent_opens_a_new_session_on_the_same_process() { + let dir = std::env::temp_dir().join(format!("sc-agent-chat-new-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let log = dir.join("received.log"); + let script = r#" +log="$1"; n=0 +while IFS= read -r line; do + printf '%s\n' "$line" >> "$log" + id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9][0-9]*\).*/\1/p') + case "$line" in + *'"method":"initialize"'*) printf '{"jsonrpc":"2.0","id":%s,"result":{"agentInfo":{"name":"fake","version":"1"}}}\n' "$id" ;; + *'"method":"session/new"'*) n=$((n+1)); printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"s%s"}}\n' "$id" "$n" ;; + *'"method":"session/prompt"'*) printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn"}}\n' "$id" ;; + esac +done +"#; + let argv = vec!["sh".to_string(), "-c".to_string(), script.to_string(), "fake-agent".to_string(), log.to_string_lossy().into_owned()]; + let start = backend::StartContext { cwd: dir.clone(), bridge: None, tools: None, wake: Box::new(|| {}) }; + let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + app.agent_chat.backend = Some(Box::new(acp_client::AcpBackend::start(&argv, start).unwrap())); + app.agent_chat.state = Some(State::Starting); + let ctx = egui::Context::default(); + let until = |app: &mut SolveApp, done: &dyn Fn(&SolveApp) -> bool| { + let t = std::time::Instant::now(); + while !done(app) { + assert!(t.elapsed() < std::time::Duration::from_secs(20), "timed out"); + poll(app, &ctx); + std::thread::sleep(std::time::Duration::from_millis(10)); + } + }; + until(&mut app, &|a| a.agent_chat.state() == State::Ready); + send(&mut app, &ctx, "hello".into()); + until(&mut app, &|a| a.agent_chat.state() == State::Ready); + assert!(!app.agent_chat.items.is_empty()); + let pid = app.agent_chat.backend.as_ref().and_then(|b| b.pid()); + new_chat(&mut app); + assert!(app.agent_chat.items.is_empty()); + until(&mut app, &|a| a.agent_chat.state() == State::Ready); + assert_eq!(app.agent_chat.backend.as_ref().and_then(|b| b.pid()), pid, "same process"); + send(&mut app, &ctx, "again".into()); + until(&mut app, &|a| a.agent_chat.state() == State::Ready); + let log_text = std::fs::read_to_string(&log).unwrap(); + let methods: Vec = + log_text.lines().filter_map(|l| serde_json::from_str::(l).ok()).filter_map(|v| v["method"].as_str().map(String::from)).collect(); + assert_eq!(methods, ["initialize", "session/new", "session/prompt", "session/new", "session/prompt"]); + assert!(log_text.lines().last().is_some_and(|l| l.contains("\"s2\"")), "the prompt goes to the new session: {log_text}"); + disconnect(&mut app); + let _ = std::fs::remove_dir_all(&dir); +} + +fn models_reply(current: &str) -> Event { + let m = |id: &str| acp::ModelInfo { id: id.into(), name: id.to_uppercase(), description: String::new() }; + Event::Models { current: current.into(), available: vec![m("fast"), m("smart")] } +} + +/// Choosing a model tells the agent, shows it as current and remembers it for this agent; a model +/// the agent did not offer is ignored. +#[test] +fn choosing_a_model_sets_it_and_remembers_it() { + let (mut app, script, ctx) = app_with_script(); + app.agent_chat.running_id = "claude".into(); + script.report(models_reply("fast")); + poll(&mut app, &ctx); + assert!(models_shown(&app)); + assert_eq!(app.agent_chat.model, "fast"); + set_model(&mut app, "smart"); + set_model(&mut app, "nonsense"); + assert_eq!(script.calls(), ["set_model: smart"]); + assert_eq!(app.agent_chat.model, "smart"); + assert_eq!(app.preferences.agent_models.get("claude").map(String::as_str), Some("smart")); + assert_eq!(status(&app)["model"], "smart"); + // The agent switching its own model is shown too. + script.report(Event::Models { current: "fast".into(), available: vec![] }); + poll(&mut app, &ctx); + assert_eq!(app.agent_chat.model, "fast"); + assert_eq!(app.agent_chat.models.len(), 2, "the list stays"); +} + +/// The next session puts back the model chosen last time, when the agent offers it. +#[test] +fn the_remembered_model_is_set_on_the_next_session() { + let (mut app, script, ctx) = app_with_script(); + app.agent_chat.running_id = "claude".into(); + app.preferences.agent_models.insert("claude".into(), "smart".into()); + script.report(models_reply("fast")); + script.report(Event::Ready { agent: "fake".into(), images: false }); + poll(&mut app, &ctx); + assert_eq!(script.calls(), ["set_model: smart"]); + assert_eq!(app.agent_chat.model, "smart"); + // Already on it, or no longer offered: nothing is sent. + script.report(models_reply("smart")); + script.report(Event::Ready { agent: "fake".into(), images: false }); + poll(&mut app, &ctx); + app.preferences.agent_models.insert("claude".into(), "gone".into()); + script.report(models_reply("fast")); + script.report(Event::Ready { agent: "fake".into(), images: false }); + poll(&mut app, &ctx); + assert_eq!(script.calls().len(), 1); +} + +/// An agent that reports no models gets no picker; another agent's choice is not applied to it. +#[test] +fn an_agent_without_models_shows_no_picker() { + let (mut app, script, ctx) = app_with_script(); + app.agent_chat.running_id = "other".into(); + app.preferences.agent_models.insert("claude".into(), "smart".into()); + script.report(Event::Ready { agent: "fake".into(), images: false }); + poll(&mut app, &ctx); + assert!(!models_shown(&app)); + assert!(script.calls().is_empty()); + assert_eq!(status(&app)["models"], json!([])); +} + +/// With a real ACP agent the choice goes out as `session/set_model` with the session and model. +#[cfg(unix)] +#[test] +fn set_model_goes_to_an_acp_agent() { + let dir = std::env::temp_dir().join(format!("sc-agent-chat-model-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let log = dir.join("received.log"); + let script = r#" +log="$1" +while IFS= read -r line; do + printf '%s\n' "$line" >> "$log" + id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9][0-9]*\).*/\1/p') + case "$line" in + *'"method":"initialize"'*) printf '{"jsonrpc":"2.0","id":%s,"result":{"agentInfo":{"name":"fake","version":"1"}}}\n' "$id" ;; + *'"method":"session/new"'*) printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"s1","models":{"currentModelId":"fast","availableModels":[{"modelId":"fast","name":"Fast"},{"modelId":"smart","name":"Smart"}]}}}\n' "$id" ;; + *'"method":"session/set_model"'*) printf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id" ;; + esac +done +"#; + let argv = vec!["sh".to_string(), "-c".to_string(), script.to_string(), "fake-agent".to_string(), log.to_string_lossy().into_owned()]; + let start = backend::StartContext { cwd: dir.clone(), bridge: None, tools: None, wake: Box::new(|| {}) }; + let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + app.agent_chat.backend = Some(Box::new(acp_client::AcpBackend::start(&argv, start).unwrap())); + app.agent_chat.state = Some(State::Starting); + app.agent_chat.running_id = "fake".into(); + app.preferences.agent_models.insert("fake".into(), "smart".into()); + let ctx = egui::Context::default(); + let t = std::time::Instant::now(); + loop { + poll(&mut app, &ctx); + let logged = std::fs::read_to_string(&log).unwrap_or_default(); + if logged.contains("session/set_model") { + break; + } + assert!(t.elapsed() < std::time::Duration::from_secs(20), "no set_model: {logged}"); + std::thread::sleep(std::time::Duration::from_millis(10)); + } + assert!(models_shown(&app) && app.agent_chat.model == "smart", "the remembered model was put back"); + let logged = std::fs::read_to_string(&log).unwrap(); + let set: Value = logged.lines().filter_map(|l| serde_json::from_str::(l).ok()).find(|v| v["method"] == "session/set_model").unwrap(); + assert_eq!(set["params"], json!({"sessionId": "s1", "modelId": "smart"})); + // A choice made in the picker goes out too. + set_model(&mut app, "fast"); + let t = std::time::Instant::now(); + while std::fs::read_to_string(&log).unwrap_or_default().matches("session/set_model").count() < 2 { + assert!(t.elapsed() < std::time::Duration::from_secs(20)); + std::thread::sleep(std::time::Duration::from_millis(10)); + } + disconnect(&mut app); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index 9ed418365..c52887920 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -348,6 +348,8 @@ pub struct Prefs { /// How much the agent may do without asking (`ask`, `edits`, `all`), and per agent. pub ai_permissions: crate::agent_chat::agents::Mode, pub agent_permissions: std::collections::BTreeMap, + /// The model last chosen in the chat, per agent: put back when the agent offers it again. + pub agent_models: std::collections::BTreeMap, /// "Always allow" answers: per agent, the tools it may use without asking. pub agent_always_allow: std::collections::BTreeMap>, /// The side the panel docks on (`left` or `right`), its width, and whether it is folded to a strip. @@ -435,6 +437,7 @@ impl Default for Prefs { agent_default: String::new(), ai_permissions: crate::agent_chat::agents::Mode::Edits, agent_permissions: Default::default(), + agent_models: Default::default(), agent_always_allow: Default::default(), agent_chat_side: "right".into(), agent_chat_width: 380.0, diff --git a/docs/agent-chat.md b/docs/agent-chat.md index 005ff723a..5529a94c8 100644 --- a/docs/agent-chat.md +++ b/docs/agent-chat.md @@ -41,7 +41,28 @@ when you send a message or press **Connect**. unfold it. **Close** (×) hides the panel. Neither stops the agent; **Stop** does. - **The agent switcher** under the title picks the agent for this conversation; switching stops the one running. Next to it, when the agent has modes of its own (Claude Code has *Default*, - *Accept Edits*, *Plan*…), a second drop-down sets the agent's mode. + *Accept Edits*, *Plan*…), a second drop-down sets the agent's mode. When the agent reports its models (an ACP agent's + model list, or an endpoint's `/models`), a model drop-down shows the one in use and changes it; + SolidCraft remembers the last choice for each agent and puts it back on the next session. An + endpoint's agent also keeps it as its default model. An agent that reports no models shows no + drop-down. + +## Typing while the agent works + +The input stays enabled during a turn. **Enter** queues the message: it shows in the conversation +as a **Queued** bubble that you can **Edit** or remove (×) until it is sent. Several queued +messages go as one prompt, in order, when the turn ends normally. + +- **Send now** (on the bubble, or **Ctrl+Enter** / **Cmd+Enter** in the input) stops the current + step, waits for the agent to say it stopped, then sends the queue as the next prompt, with a + short note that the agent's previous step was interrupted. What the interrupted message changed + undoes as one step, like any other message. +- **Stop** (the square next to the input, or **Esc** in the input) stops the agent and keeps + the queue: the bubbles wait for **Send**. +- **New chat** (the header button, **Ctrl+Shift+L** / **Cmd+Shift+L** with the chat focused) + stops what runs, clears the conversation and the queue and starts a fresh session on the same + agent, keeping the agent and its mode. It asks first when a message is running or queued. The + design's undo history is untouched. ## Agents diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 2857b9ac1..142ea2639 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -147,7 +147,7 @@ labels; `prefs:measure_axis_distances` identifies the checkbox. | `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 | -| `ui.agent_chat` | `features?`, `toolbar_button?`, `permissions?` (`ask`, `edits`, `all`), `add_agent?` ({`name`, `kind`: `acp` or `api`, `command` or `base_url` + `model`}; no keys), `default_agent?`, `agent?` (the conversation's agent, by id), `mode?` (the agent's own mode), `open?`, `side?` (`left`, `right`), `minimized?`, `width?`, `picker?`, `refresh?`, `connect?`, `stop?`, `send?`: text, `attach_view?`, `permission?`: an option id or `"cancel"` (the newest question of the agent's own), `approve?`: true, false or `"always"` (the oldest request held for Allow/Deny), `cancel?`, `undo?` (the last message's changes) | the chat's state: `features`, `agents` (found and added), `currentAgent`, `state` (off, starting, ready, busy, auth, exited), `agent`, `modes`, `mode`, `authMethods`, `toolsPort`, `pid`, `waiting`, `turn`, `detection` and the conversation (`items`). With `features` off only the settings apply. Desktop only; see [Agent chat](agent-chat.md) | +| `ui.agent_chat` | `features?`, `toolbar_button?`, `permissions?` (`ask`, `edits`, `all`), `add_agent?` ({`name`, `kind`: `acp` or `api`, `command` or `base_url` + `model`}; no keys), `default_agent?`, `agent?` (the conversation's agent, by id), `mode?` (the agent's own mode), `model?` (one of its models), `open?`, `side?` (`left`, `right`), `minimized?`, `width?`, `picker?`, `refresh?`, `connect?`, `stop?`, `send?`: text, `attach_view?`, `permission?`: an option id or `"cancel"` (the newest question of the agent's own), `approve?`: true, false or `"always"` (the oldest request held for Allow/Deny), `cancel?` (Stop: the queue stays), `send_now?` (stop the running step, then send the queued messages), `remove_pending?` (index), `new_chat?` (clear the chat, new session), `undo?` (the last message's changes) | the chat's state: `features`, `agents` (found and added), `currentAgent`, `state` (off, starting, ready, busy, auth, exited), `agent`, `modes`, `mode`, `models`, `model`, `authMethods`, `toolsPort`, `pid`, `waiting`, `turn`, `pending` (queued messages), `stopped`, `detection` and the conversation (`items`). With `features` off only the settings apply. Desktop only; see [Agent chat](agent-chat.md) | | `ui.resize` | `width`, `height` | | | `app.quit` | `force?` (quit without asking about unsaved designs) | `quitting` (the window closes), `asking` (a "save changes?" prompt is open) | From 4d862cd76ccfa3a171c66c48d9a184209a33a945 Mon Sep 17 00:00:00 2001 From: Mateusz Sych <151755914+SychPL@users.noreply.github.com> Date: Fri, 16 Oct 2026 05:58:34 +0200 Subject: [PATCH 58/92] Joints: joint.reach (inverse kinematics), and a jointed part follows a drag (#1540) Thanks @SychPL. --- ROADMAP.md | 2 +- 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/uk.json | 1 + assets/locales/zh.json | 1 + crates/doc/src/joints.rs | 100 +++-- crates/doc/src/joints_reach.rs | 445 ++++++++++++++++++++ crates/engine/src/cmd/joints.rs | 111 +++++ crates/engine/src/cmd/joints_reach_tests.rs | 315 ++++++++++++++ crates/engine/src/cmd/joints_tests.rs | 14 +- crates/ui-egui/src/dialogs_assembly.rs | 2 +- crates/ui-egui/src/joint_drag.rs | 214 ++++++++++ crates/ui-egui/src/lib.rs | 5 +- crates/ui-egui/src/viewport.rs | 22 + docs/book/src/guide/assemblies.md | 15 + skills/solidcraft-mechanisms/SKILL.md | 1 + skills/solidcraft-mechanisms/reference.md | 3 + 21 files changed, 1209 insertions(+), 48 deletions(-) create mode 100644 crates/doc/src/joints_reach.rs create mode 100644 crates/engine/src/cmd/joints_reach_tests.rs create mode 100644 crates/ui-egui/src/joint_drag.rs diff --git a/ROADMAP.md b/ROADMAP.md index 7cd14739d..681339c85 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -56,7 +56,7 @@ PCB / Package, Render, Animation, Simulation, Manufacture/CAM, Drawings. | M8 | Surface workspace (#772). Done: Patch (sketch regions; edge loops of any shape and number of sides as one face, G0/G1/G2 to the faces beside each edge, through points, #759), 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. Proposed, in order: surface Extrude/Revolve/Sweep/Loft from open and closed curves (#757), Offset surface (#758), Unstitch and Reverse Normal (#766), Delete Face without healing (#768); Extend curved faces and edges (#760), mutual trim and trim by projected curves (#767), Untrim (#761), Thicken every surface kind (#765); Ruled (#762), Boundary surface and curve networks with G0/G1/G2 (#763), Blend surface (#764), sweep guide rails and two-rail sweeps (#771; orientation, twist and end scale done; loft rails #201), fillet between surface bodies (#769); continuity analysis, surface curvature combs and isocurves (#770) | 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), 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), 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 and Interference (overlaps shown red); joints in the timeline and the Browser | in progress | 32 | | M8 | Surface workspace (#772). Done: Patch (sketch regions; edge loops filled G0), 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. Proposed, in order: surface Extrude/Revolve/Sweep/Loft from open and closed curves (#757), Offset surface (#758), Unstitch and Reverse Normal (#766), Delete Face without healing (#768); Extend curved faces and edges (#760), mutual trim and trim by projected curves (#767), Untrim (#761), Thicken every surface kind (#765); Ruled (#762), Boundary surface and curve networks with G0/G1/G2 (#763), Patch with G1/G2 and general loops (#759), Blend surface (#764), sweep guide rails and two-rail sweeps (#771; orientation, twist and end scale done; loft rails #201), fillet between surface bodies (#769); continuity analysis, surface curvature combs and isocurves (#770) | 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), gears, rack and pinion and screws (motion links whose ratio follows picked radii, parameters or a pitch, also inside closed loops), 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), 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, Gear, Rack and Pinion, Screw and Interference (overlaps shown red); joints in the timeline and the Browser | in progress | 32 | +| 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), gears, rack and pinion and screws (motion links whose ratio follows picked radii, parameters or a pitch, also inside closed loops), inverse kinematics (`joint.reach`: a part's point to a target through the joints on its chain, within limits and with loops closed, nearest pose and its stopper when out of reach; dragging a jointed part in the viewport moves it as far as its joints allow), 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), 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, Gear, Rack and Pinion, Screw 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 | | 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 | diff --git a/assets/locales/de.json b/assets/locales/de.json index 95fa40987..d291fa094 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -204,6 +204,7 @@ "cmd.joint_motion_link": "Bewegungsverknüpfung", "cmd.joint_origin": "Gelenkursprung", "cmd.joint_rack_pinion": "Zahnstange und Ritzel", + "cmd.joint_reach": "Punkt anfahren", "cmd.joint_rigid_group": "Starrgruppe", "cmd.joint_screw": "Schraube", "cmd.joint_solve": "Gelenke lösen", diff --git a/assets/locales/en.json b/assets/locales/en.json index b9a583d1d..fab0d438d 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -406,6 +406,7 @@ "cmd.joint_motion_link": "Motion Link", "cmd.joint_origin": "Joint Origin", "cmd.joint_rack_pinion": "Rack and Pinion", + "cmd.joint_reach": "Reach Point", "cmd.joint_rigid_group": "Rigid Group", "cmd.joint_screw": "Screw", "cmd.joint_solve": "Solve Joints", diff --git a/assets/locales/fr.json b/assets/locales/fr.json index bff40076b..acb46e487 100644 --- a/assets/locales/fr.json +++ b/assets/locales/fr.json @@ -386,6 +386,7 @@ "cmd.joint_motion_link": "Lien de mouvement", "cmd.joint_origin": "Origine de liaison", "cmd.joint_rack_pinion": "Pignon et crémaillère", + "cmd.joint_reach": "Atteindre un point", "cmd.joint_rigid_group": "Groupe rigide", "cmd.joint_screw": "Vis", "cmd.joint_solve": "Résoudre les liaisons", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index a50b3417f..676c707bb 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -406,6 +406,7 @@ "cmd.joint_motion_link": "モーション リンク", "cmd.joint_origin": "ジョイント原点", "cmd.joint_rack_pinion": "ラック アンド ピニオン", + "cmd.joint_reach": "点に到達", "cmd.joint_rigid_group": "リジッド グループ", "cmd.joint_screw": "ねじ", "cmd.joint_solve": "ジョイントを解決", diff --git a/assets/locales/ko.json b/assets/locales/ko.json index b5cec8c18..877fbe9c5 100644 --- a/assets/locales/ko.json +++ b/assets/locales/ko.json @@ -204,6 +204,7 @@ "cmd.joint_motion_link": "모션 링크", "cmd.joint_origin": "관절 원점", "cmd.joint_rack_pinion": "랙 앤 피니언", + "cmd.joint_reach": "점에 도달", "cmd.joint_rigid_group": "강체 그룹", "cmd.joint_screw": "나사", "cmd.joint_solve": "관절 해석", diff --git a/assets/locales/ru.json b/assets/locales/ru.json index 52fcd9772..630f085f8 100644 --- a/assets/locales/ru.json +++ b/assets/locales/ru.json @@ -362,6 +362,7 @@ "cmd.joint_motion_link": "Связь движений", "cmd.joint_origin": "Точка сопряжения", "cmd.joint_rack_pinion": "Реечная передача", + "cmd.joint_reach": "Достичь точки", "cmd.joint_rigid_group": "Жёсткая группа", "cmd.joint_screw": "Винт", "cmd.joint_solve": "Решить сопряжения", diff --git a/assets/locales/uk.json b/assets/locales/uk.json index f5c5d0155..b8c77211d 100644 --- a/assets/locales/uk.json +++ b/assets/locales/uk.json @@ -363,6 +363,7 @@ "cmd.joint_motion_link": "Зв'язок руху", "cmd.joint_origin": "Початок з'єднання", "cmd.joint_rack_pinion": "Рейкова передача", + "cmd.joint_reach": "Досягти точки", "cmd.joint_rigid_group": "Жорстка група", "cmd.joint_screw": "Гвинт", "cmd.joint_solve": "Розв'язати з'єднання", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index 2e6162e5b..8a4115b77 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -406,6 +406,7 @@ "cmd.joint_motion_link": "运动关联", "cmd.joint_origin": "接头原点", "cmd.joint_rack_pinion": "齿轮齿条", + "cmd.joint_reach": "到达点", "cmd.joint_rigid_group": "刚性组", "cmd.joint_screw": "螺旋", "cmd.joint_solve": "解算接头", diff --git a/crates/doc/src/joints.rs b/crates/doc/src/joints.rs index afeb93a27..f526d4c7c 100644 --- a/crates/doc/src/joints.rs +++ b/crates/doc/src/joints.rs @@ -1211,8 +1211,61 @@ pub fn solve(doc: &Document, st: &ModelState) -> Solution { pub fn solve_holding(doc: &Document, st: &ModelState, held: &Held) -> Solution { let asm = &doc.assembly; let mut sol = Solution::default(); - let joints: Vec<&Joint> = asm.joints.iter().filter(|j| !j.suppressed).take(MAX_JOINTS).collect(); let mut vals = joint_values(asm); + let Built { tree, mut placed, closing, mut dof } = build(doc, st, &vals, &mut sol); + let mut stuck = BTreeSet::new(); + if !closing.is_empty() { + (sol.values, stuck) = close_loops(&tree, &closing, asm, held, &mut vals); + if !sol.values.is_empty() { + placed = tree.place(&vals); + } + } + for id in &closing { + let Some(j) = tree.joints.get(id) else { continue }; + let (Some(ta), Some(tb)) = (placed.get(&j.a.occurrence), placed.get(&j.b.occurrence)) else { continue }; + let (Some(want), Some((_, fb))) = (tree.step(*id, true, ta, &vals), tree.frames.get(id)) else { continue }; + // Measured at the joint, where the loop solver closes it. + let (dt, da) = mismatch(&mat_mul(&want, fb), &mat_mul(tb, fb)); + if dt > 1e-6 || da > 1e-8 { + sol.conflicts.push(( + j.id, + j.name.clone(), + format!("off by {dt:.4} mm and {:.3}° from the placement the other joints give", da.to_degrees()), + )); + } else if stuck.contains(id) { + // It meets there, but the loop would have to come apart on the way (a rocker + // driven a full turn ends where it started). + sol.conflicts.push((j.id, j.name.clone(), "the loop can't stay closed on the way to these values".into())); + } + } + if !closing.is_empty() { + loop_dof(&tree, &closing, asm, &vals, &mut dof); + } + for o in &doc.occurrences { + dof.entry(o.id).or_insert(6); + } + placed.remove(&0); + sol.world = placed; + sol.dof = dof; + sol +} + +/// The joint graph laid out for a solve: the tree, where it places each occurrence for the +/// values it was built with, the joints that close loops, and each occurrence's degrees of +/// freedom along the tree. +struct Built<'a> { + tree: Tree<'a>, + placed: BTreeMap, + closing: Vec, + dof: BTreeMap, +} + +/// Lay out the joint graph: the spanning tree out from the fixed occurrences (the root, grounded +/// ones; with neither involved, the first joint's A side) and the joints left over, which close +/// loops. Joints whose origins can't be resolved go to `sol.errors`; `sol.fixed` is set. +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). let mut frames: BTreeMap = BTreeMap::new(); for j in &joints { @@ -1270,7 +1323,7 @@ pub fn solve_holding(doc: &Document, st: &ModelState, held: &Held) -> Solution { if placed.contains_key(&other) { continue; } - let Some(m) = tree.step(j.id, from_a, &t, &vals) else { continue }; + let Some(m) = tree.step(j.id, from_a, &t, vals) else { continue }; used.insert(j.id); placed.insert(other, m); tree.parent.insert(other, (occ, j.id, from_a)); @@ -1279,48 +1332,15 @@ pub fn solve_holding(doc: &Document, st: &ModelState, held: &Held) -> Solution { queue.push_back(other); } } - // Joints that close loops: move the loops' values to meet them, then check they agree. + // Joints that close loops: the solve moves the loops' values to meet them, then checks they + // agree. let closing: Vec = joints .iter() .filter(|j| !used.contains(&j.id) && tree.frames.contains_key(&j.id)) .filter(|j| placed.contains_key(&j.a.occurrence) && placed.contains_key(&j.b.occurrence)) .map(|j| j.id) .collect(); - let mut stuck = BTreeSet::new(); - if !closing.is_empty() { - (sol.values, stuck) = close_loops(&tree, &closing, asm, held, &mut vals); - if !sol.values.is_empty() { - placed = tree.place(&vals); - } - } - for id in &closing { - let Some(j) = tree.joints.get(id) else { continue }; - let (Some(ta), Some(tb)) = (placed.get(&j.a.occurrence), placed.get(&j.b.occurrence)) else { continue }; - let (Some(want), Some((_, fb))) = (tree.step(*id, true, ta, &vals), tree.frames.get(id)) else { continue }; - // Measured at the joint, where the loop solver closes it. - let (dt, da) = mismatch(&mat_mul(&want, fb), &mat_mul(tb, fb)); - if dt > 1e-6 || da > 1e-8 { - sol.conflicts.push(( - j.id, - j.name.clone(), - format!("off by {dt:.4} mm and {:.3}° from the placement the other joints give", da.to_degrees()), - )); - } else if stuck.contains(id) { - // It meets there, but the loop would have to come apart on the way (a rocker - // driven a full turn ends where it started). - sol.conflicts.push((j.id, j.name.clone(), "the loop can't stay closed on the way to these values".into())); - } - } - if !closing.is_empty() { - loop_dof(&tree, &closing, asm, &vals, &mut dof); - } - for o in &doc.occurrences { - dof.entry(o.id).or_insert(6); - } - placed.remove(&0); - sol.world = placed; - sol.dof = dof; - sol + Built { tree, placed, closing, dof } } impl Document { @@ -1368,6 +1388,10 @@ impl Document { } } +#[path = "joints_reach.rs"] +mod reach; +pub use reach::{REACH_TOL, Reach, Reached, reach}; + /// 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/doc/src/joints_reach.rs b/crates/doc/src/joints_reach.rs new file mode 100644 index 000000000..07bd137f4 --- /dev/null +++ b/crates/doc/src/joints_reach.rs @@ -0,0 +1,445 @@ +//! Inverse kinematics (`joint.reach`): move the values of the joints on an occurrence's chain so a +//! point of it reaches a target (and an axis of it points a given way), every value within its +//! limits, motion links followed, and the closed loops those values are in kept closed. + +use std::cell::Cell; +use std::collections::BTreeSet; + +use solidcraft_geom::Vec3; +use solidcraft_sketch::linalg; + +use super::{ + Assembly, Held, MAX_LOOP_VALUES, MAX_LOOP_WORK, MAX_LOOPS, Solution, Tree, Values, apply_links, build, closure_gaps, jacobian, joint_values, + largest, least_squares, limit_bounds, link_chains, loop_groups, loop_scale, unknowns, +}; +use crate::{Document, ModelState, apply_point, apply_vector, mat_mul}; + +/// How close counts as reached: mm for the point, degrees for the axis. +pub const REACH_TOL: f64 = 1e-4; + +/// What a reach asks. +#[derive(Clone, Debug)] +pub struct Reach { + /// The occurrence that reaches. + pub occurrence: u64, + /// Its point that goes to `to`, in its own (component) coordinates. + pub point: Vec3, + /// Where the point goes (world). + pub to: Vec3, + /// A unit axis of it (its own coordinates) and the unit world direction it turns to. + pub axis: Option<(Vec3, Vec3)>, + /// The joints whose values move toward the target (`None`: every joint on its chain). The + /// other joints of a closed loop they are in follow. + pub joints: Option>, +} + +/// How a reach ended. +#[derive(Clone, Debug, Default)] +pub struct Reached { + /// The new stored values of the joints that moved (joint id → values). + pub values: Values, + /// Short of the target: the values it ended on a limit of, with the target pulling past it + /// (joint, value index, the upper limit). + pub limits: Vec<(u64, usize, bool)>, + /// Short of the target: the closing joint of a loop that stopped it (the chain alone, the + /// loop left open, gets closer). + pub stopped_by_loop: Option, +} + +/// How much a loop's gap (mm) outweighs a miss of the target (mm) in a step: enough to keep the +/// step along the mechanism, so putting it back on the loops moves it little. +const LOOP_WEIGHT: f64 = 1e3; +/// Steps a reach takes at most, each moving no value more than 10° or a tenth of the chain's +/// size (so it follows the mechanism's branch). +const MAX_REACH_STEPS: usize = 200; +const STEP_ANGLE: f64 = 10.0; +const STEP_SHARE: f64 = 0.1; + +/// Move the values of the joints on `r.occurrence`'s chain (those in `r.joints`, when given) so +/// its point gets to `r.to`, or as close as the limits and closed loops let it: the nearest pose, +/// found from where it is (it stays on the mechanism's branch). Values a motion link sets move +/// through the start of their link chain; the other values of the loops they are in follow. An +/// error says why nothing can move. +pub fn reach(doc: &Document, st: &ModelState, r: &Reach) -> Result { + let asm = &doc.assembly; + let vals = joint_values(asm); + let built = build(doc, st, &vals, &mut Solution::default()); + let tree = &built.tree; + if tree.fixed.contains_key(&r.occurrence) { + return Err("it is fixed in place (grounded, or the part its joints are placed from)".into()); + } + if !tree.parent.contains_key(&r.occurrence) { + return Err("no joint places it: it is not connected to anything grounded (ground a part, or join it to a grounded part)".into()); + } + let linked: BTreeSet<(u64, usize)> = asm.links.iter().map(|l| (l.b, l.ib)).collect(); + let allowed = |id: &u64| r.joints.as_ref().is_none_or(|js| js.contains(id)); + let path: BTreeSet = tree.path(r.occurrence).1.iter().map(|(k, _)| *k).collect(); + // The values that move it: those of the joints on its chain (the ones given), a linked one + // through the start of its link chain (given or not), and the starts given of the chain's + // other linked values. + let chosen: BTreeSet = path.iter().copied().filter(allowed).collect(); + let mut drive: Vec<(u64, usize)> = Vec::new(); + for j in chosen.iter().filter_map(|id| tree.joints.get(id)) { + drive.extend((0..j.kind.dofs().len()).map(|i| (j.id, i)).filter(|v| !linked.contains(v))); + } + let starts = link_chains(asm, tree, &path, &linked).1.into_iter().filter(|v| allowed(&v.0)); + for v in link_chains(asm, tree, &chosen, &linked).1.into_iter().chain(starts) { + if !drive.contains(&v) { + drive.push(v); + } + } + if drive.is_empty() { + return Err(if r.joints.is_some() { + "none of the joints given moves it" + } else { + "no joint on its chain moves (rigid, or set by motion links)" + } + .into()); + } + // The loops those values are in, and the values of theirs that follow. + if built.closing.len() > MAX_LOOPS { + return Err(format!("the design has more than {MAX_LOOPS} closed loops")); + } + let groups = loop_groups(tree, &built.closing, asm, &linked); + let (mut vars, mut closers, mut around) = (drive.clone(), Vec::new(), path.clone()); + let mut taken = BTreeSet::new(); + while vars.len() <= MAX_LOOP_VALUES { + let more: Vec = + groups.iter().enumerate().filter(|(g, (_, _, t))| !taken.contains(g) && t.iter().any(|v| vars.contains(v))).map(|(g, _)| g).collect(); + if more.is_empty() { + break; + } + for (c, a, _) in more.iter().filter_map(|g| groups.get(*g)) { + closers.extend(c.iter().copied()); + around.extend(a.iter().copied()); + for v in unknowns(tree, a, asm, &linked, &Held::new()) { + if !vars.contains(&v) { + vars.push(v); + } + } + } + taken.extend(more); + } + if vars.len() > MAX_LOOP_VALUES { + return Err(format!("its chain and loops have more than {MAX_LOOP_VALUES} values")); + } + let scale = loop_scale(tree, &around, &vals); + let bounds = limit_bounds(tree, &vars); + let x0: Vec = vars.iter().map(|(id, i)| vals.get(id).and_then(|q| q.get(*i)).copied().unwrap_or(0.0)).collect(); + // A distance steps by a share of the chain's size, of the way to the target or of the point's + // reach from its joints, whichever is longest (one slider on its own has no size, and a part + // turning about a joint far from its point moves that far). + let point = tree.world(r.occurrence, &vals).map(|t| apply_point(&t, r.point)); + let lever = path + .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).dist(point?)) + }) + .fold(0.0, f64::max); + let span = point.map_or(scale, |p| scale.max(p.dist(r.to)).max(lever)); + let cap: Vec = vars + .iter() + .map(|(id, i)| if tree.joints.get(id).is_some_and(|j| j.kind.is_angle(*i)) { STEP_ANGLE.to_radians() } else { STEP_SHARE * span }) + .collect(); + // Every value around the chain and its loops, links included, moves at most a step at a time: + // a value a link sets can turn far more than the one that drives it, and a loop must stay + // closed on the way, as joint.drive steps its loops. + let mut paced: Vec<((u64, usize), f64)> = Vec::new(); + for j in around.iter().filter_map(|id| tree.joints.get(id)) { + for i in 0..j.kind.dofs().len() { + paced.push(((j.id, i), if j.kind.is_angle(i) { STEP_ANGLE.to_radians() } else { STEP_SHARE * span })); + } + } + let tol = (1e-10 * scale).min(1e-7); + let mt = if r.axis.is_some() { 6 } else { 3 }; + let spent = Cell::new(0usize); + let mut work = vals.clone(); + let mut f = |x: &[f64]| misses(tree, asm, r, scale, &vars, &closers, x, &mut work, &spent); + let mut x = x0.clone(); + let miss = |res: &[f64]| res.iter().take(mt).map(|v| v * v).sum::().sqrt(); + let before = f(&x0).map_or(f64::INFINITY, |r| miss(&r)); + let res = approach(&mut f, &|a, b| stride(asm, &vals, &vars, &paced, a, b), mt, &mut x, &bounds, &cap, tol) + .ok_or("a closed loop on its chain is open and can't close (joint.list shows its conflict)")?; + let mut out = Reached::default(); + let point_miss = res.iter().take(3).map(|v| v * v).sum::().sqrt(); + let turn_miss = (res.iter().skip(3).take(mt - 3).map(|v| v * v).sum::().sqrt() / scale).to_degrees(); + if point_miss > REACH_TOL || turn_miss > REACH_TOL { + // The limits it rests on: the target pulls the value past them (−Jᵀr over the target's + // rows, ignoring pulls at right angles to the miss: under a millionth of the value's own + // reach times the miss). + let n = x.len(); + if let Some(jac) = jacobian(&mut f, &x, res.len()) { + for (k, (((id, i), v), (lo, hi))) in vars.iter().zip(&x).zip(&bounds).enumerate() { + let column = |row: usize| jac.get(row * n + k).copied().unwrap_or(0.0); + let pull: f64 = -(0..mt).map(|row| column(row) * res.get(row).copied().unwrap_or(0.0)).sum::(); + let eps = 1e-6 * (0..mt).map(|row| column(row).powi(2)).sum::().sqrt() * miss(&res); + let at = |b: f64| b.is_finite() && (v - b).abs() <= 1e-9 * b.abs().max(1.0); + if at(*hi) && pull > eps { + out.limits.push((*id, *i, true)); + } else if at(*lo) && pull < -eps { + out.limits.push((*id, *i, false)); + } + } + } + // A value a motion link sets, held at its own limit (the link clamps it there): the + // target's pull on it as if it were free. + if f(&x).is_some() { + for (id, i) in linked.iter().filter(|(id, _)| around.contains(id)) { + let (Some(v), Some((lo, hi))) = (work.get(id).and_then(|q| q.get(*i)).copied(), limit_bounds(tree, &[(*id, *i)]).first().copied()) + else { + continue; + }; + let at = |b: f64| b.is_finite() && (v - b).abs() <= 1e-9 * b.abs().max(1.0); + if !at(lo) && !at(hi) { + continue; + } + let nudged = |dv: f64| { + let mut w = work.clone(); + if let Some(slot) = w.get_mut(id).and_then(|q| q.get_mut(*i)) { + *slot = v + dv; + } + target(tree, r, scale, &w) + }; + let (Some(up), Some(down)) = (nudged(1e-6), nudged(-1e-6)) else { continue }; + let pull: f64 = -up.iter().zip(&down).zip(&res).map(|((a, b), r)| (a - b) / 2e-6 * r).sum::(); + let eps = 1e-6 * up.iter().zip(&down).map(|(a, b)| ((a - b) / 2e-6).powi(2)).sum::().sqrt() * miss(&res); + if at(hi) && pull > eps { + out.limits.push((*id, *i, true)); + } else if at(lo) && pull < -eps { + out.limits.push((*id, *i, false)); + } + } + } + // A loop stopped it when the chain alone gets closer. + // ponytail: names the first loop of several; trying each one open would name the one that binds. + if let Some(first) = closers.first() { + let k = drive.len(); + let mut alone = vals.clone(); + let mut g = |x: &[f64]| misses(tree, asm, r, scale, &drive, &[], x, &mut alone, &spent); + let (mut xo, bo, co) = (x0.get(..k).unwrap_or_default().to_vec(), bounds.get(..k).unwrap_or_default(), cap.get(..k).unwrap_or_default()); + // The loops left open, nothing to pace. + if let Some(ro) = approach(&mut g, &|_, _| 0.0, mt, &mut xo, bo, co, tol) + && miss(&ro) < miss(&res) - REACH_TOL.max(1e-9 * miss(&res)) + { + out.stopped_by_loop = Some(*first); + } + } + } + // The stored values that changed, when that got it closer (by more than the solver's noise: + // a held part doesn't creep). + let gained = before - miss(&res) > 1e-7; + for ((id, i), v) in vars.iter().zip(&x).filter(|_| gained) { + let Some(j) = tree.joints.get(id) else { continue }; + if j.values.get(*i) == Some(v) { + continue; + } + let q = out.values.entry(*id).or_insert_with(|| { + let mut q = j.values.clone(); + q.resize(j.kind.dofs().len(), 0.0); + q + }); + if let Some(slot) = q.get_mut(*i) { + *slot = *v; + } + } + Ok(out) +} + +/// The target's misses with the values `vars` at `x`: the point's (mm), then the axis's (as mm +/// across the chain's `scale`), then the gaps of the loops `closers`, weighted. +fn misses( + tree: &Tree, + asm: &Assembly, + r: &Reach, + scale: f64, + vars: &[(u64, usize)], + closers: &[u64], + x: &[f64], + work: &mut Values, + spent: &Cell, +) -> Option> { + spent.set(spent.get() + 1); + if spent.get() > MAX_LOOP_WORK { + return None; + } + for ((id, i), v) in vars.iter().zip(x) { + if let Some(slot) = work.get_mut(id).and_then(|q| q.get_mut(*i)) { + *slot = *v; + } + } + apply_links(asm, work); + let mut out = target(tree, r, scale, work)?; + let n = out.len(); + closure_gaps(tree, closers, work, scale, &mut out)?; + for v in out.iter_mut().skip(n) { + *v *= LOOP_WEIGHT; + } + out.iter().all(|v| v.is_finite()).then_some(out) +} + +/// The target's misses for these values: the point's (mm), then the axis's (as mm across `scale`). +fn target(tree: &Tree, r: &Reach, scale: f64, vals: &Values) -> Option> { + let t = tree.world(r.occurrence, vals)?; + let d = apply_point(&t, r.point) - r.to; + let mut out = vec![d.x, d.y, d.z]; + if let Some((a, z)) = r.axis { + let w = (apply_vector(&t, a) - z) * scale; + out.extend([w.x, w.y, w.z]); + } + Some(out) +} + +/// How many steps apart the values `vars` at `a` and at `b` put the `paced` values (each with its +/// step), motion links followed. +fn stride(asm: &Assembly, vals: &Values, vars: &[(u64, usize)], paced: &[((u64, usize), f64)], a: &[f64], b: &[f64]) -> f64 { + let at = |x: &[f64]| { + let mut w = vals.clone(); + for ((id, i), v) in vars.iter().zip(x) { + if let Some(slot) = w.get_mut(id).and_then(|q| q.get_mut(*i)) { + *slot = *v; + } + } + apply_links(asm, &mut w); + w + }; + let (wa, wb) = (at(a), at(b)); + let get = |w: &Values, id: &u64, i: usize| w.get(id).and_then(|q| q.get(i)).copied().unwrap_or(0.0); + paced.iter().map(|((id, i), step)| (get(&wb, id, *i) - get(&wa, id, *i)).abs() / step).fold(0.0, f64::max) +} + +/// Levenberg-Marquardt that stays on the loops: move `x` (within `bounds`, at most `cap` per value +/// and a step of every value `stride` measures, links included, a step) to bring the first `mt` values of `f` (the target's misses) toward zero, the rest (the +/// loops' weighted gaps) at zero. Each step is solved over all the rows, values on a limit the +/// step pushes past held, then put back on the loops (`least_squares` on their gaps) and taken +/// when it gets closer. It ends at the target, or as close as the limits and loops let it get. +/// Returns `f` there, or `None` when the loops don't close at the start. +fn approach( + f: &mut dyn FnMut(&[f64]) -> Option>, + stride: &dyn Fn(&[f64], &[f64]) -> f64, + mt: usize, + x: &mut Vec, + bounds: &[(f64, f64)], + cap: &[f64], + tol: f64, +) -> Option> { + let n = x.len(); + let miss = |r: &[f64]| r.iter().take(mt).map(|v| v * v).sum::(); + let close = |f: &mut dyn FnMut(&[f64]) -> Option>, x: &mut Vec| { + least_squares(&mut |y| f(y).map(|r| r.get(mt..).unwrap_or_default().to_vec()), x, bounds, tol * LOOP_WEIGHT) + }; + let loops = f(x)?.len() > mt; + if loops && !close(f, x) { + return None; + } + let mut r = f(x)?; + let (mut lambda, mut kicked) = (1e-3, false); + for _ in 0..MAX_REACH_STEPS { + if largest(r.get(..mt).unwrap_or_default()) <= tol { + break; + } + let m = r.len(); + let Some(jac) = jacobian(f, x, m) else { break }; + // The normal equations JᵀJ δ = −Jᵀr, and the target rows' share of the diagonal (the + // damping scales with it, so the loops' weight doesn't slow the step along them). + let (mut jtj, mut g, mut diag) = (linalg::Mat::zeros(n, n), vec![0.0; n], vec![0.0; n]); + for (row, ri) in r.iter().enumerate() { + let a = jac.get(row * n..(row + 1) * n).unwrap_or_default(); + for (p, ap) in a.iter().enumerate().filter(|(_, v)| **v != 0.0) { + if let Some(gp) = g.get_mut(p) { + *gp -= ap * ri; + } + if row < mt + && let Some(dp) = diag.get_mut(p) + { + *dp += ap * ap; + } + for (q, aq) in a.iter().enumerate().skip(p) { + jtj.add(p, q, ap * aq); + } + } + } + for p in 0..n { + for q in 0..p { + jtj.set(p, q, jtj.get(q, p)); + } + } + let mut stepped = false; + while lambda < 1e12 && !stepped { + let mut held = vec![false; n]; + // Solved, then again with the values held that it pushes past their limits. + for _ in 0..=n { + let mut a = jtj.clone(); + let mut b = g.clone(); + for p in 0..n { + a.add(p, p, lambda * (1.0 + diag.get(p).copied().unwrap_or(0.0))); + if held.get(p).copied().unwrap_or(false) { + for q in 0..n { + a.set(p, q, if p == q { 1.0 } else { 0.0 }); + a.set(q, p, if p == q { 1.0 } else { 0.0 }); + } + if let Some(bp) = b.get_mut(p) { + *bp = 0.0; + } + } + } + let Some(d) = linalg::solve(a, b) else { break }; + let past: Vec = + x.iter().zip(&d).zip(bounds).map(|((v, dv), (lo, hi))| (*dv > 0.0 && *v >= *hi) || (*dv < 0.0 && *v <= *lo)).collect(); + if past.iter().zip(&held).any(|(p, h)| *p && !*h) { + held = held.iter().zip(&past).map(|(h, p)| *h || *p).collect(); + continue; + } + let full: Vec = x.iter().zip(&d).map(|(v, dv)| v + dv).collect(); + let over = d.iter().zip(cap).map(|(d, c)| d.abs() / c).fold(1.0f64, f64::max).max(stride(x, &full)); + let mut next: Vec = x.iter().zip(&d).zip(bounds).map(|((v, dv), (lo, hi))| (v + dv / over).max(*lo).min(*hi)).collect(); + // Checked again once taken: a link held at a limit or the loops closed again may + // move it further than foreseen (joint.drive halves such steps too). + if (!loops || close(f, &mut next)) + && stride(x, &next) <= 2.0 + && let Some(rn) = f(&next) + && miss(&rn) < miss(&r) + { + (*x, r) = (next, rn); + // A step cut down to the cap (as at a stretched, singular pose) damps the next one + // more instead of less, so it doesn't crawl along its longest value. + lambda = if over > 1.0 { (lambda * over).min(1e6) } else { (lambda / 3.0).max(1e-9) }; + stepped = true; + } + break; + } + if !stepped { + lambda *= 4.0; + } + } + if !stepped { + // Where nothing changes the misses to first order but they aren't least (the target + // straight across a pivot from the point), a small kick off it gets closer, once. + if kicked { + break; + } + kicked = true; + // Both ways: one may run into a limit. + for sign in [1.0, -1.0] { + let mut next: Vec = x + .iter() + .zip(cap.iter().zip(bounds)) + .enumerate() + .map(|(k, (v, (c, (lo, hi))))| (v + sign * 1e-3 * c * if k % 2 == 0 { 1.0 } else { -1.0 }).max(*lo).min(*hi)) + .collect(); + if (!loops || close(f, &mut next)) + && stride(x, &next) <= 2.0 + && let Some(rn) = f(&next) + && miss(&rn) < miss(&r) + { + (*x, r, lambda, stepped) = (next, rn, 1e-3, true); + break; + } + } + if !stepped { + break; + } + } + } + Some(r) +} diff --git a/crates/engine/src/cmd/joints.rs b/crates/engine/src/cmd/joints.rs index 92b42b684..4b8fdbfe3 100644 --- a/crates/engine/src/cmd/joints.rs +++ b/crates/engine/src/cmd/joints.rs @@ -36,6 +36,9 @@ pub static COMMANDS: &[CommandSpec] = &[ reason: why the joint can move nothing (suppressed, its origins lost, or its chain joined to nothing grounded → unconnected: \ the occurrence named)", ), + CommandSpec::new("joint.reach", "Reach Point", reach).params( + "occurrence: id|name; point: [x,y,z] (where its point goes, world); at?: [x,y,z] (its point, in the world where it is now; default: the centre of its bodies' box); z?: [x,y,z] (the way its axis then points); axis?: [x,y,z] (that axis, in the world now; default: its own z); joints?: [ids or names] (only these move toward the point; the other joints of a closed loop they are in follow); quiet?: bool; continuous?: bool (a frame of a drag: the answer says continuous, and the app's command line doesn't echo it). Moves the values of the joints on its chain from where they are to the nearest pose, within their limits, through motion links, keeping closed loops closed as joint.drive does (contact sets are not checked) → reached; error_mm (and error_deg with z): how close it got; point: where its point is; values: [{joint, name, values}] of the joints that moved, as joint.list gives them; moved; stopped_by_limit: [{joint, value, limit: min|max}]: the limits it rests on short of the point; stopped_by_loop: {joint}: the closed loop that stopped it (its chain alone gets closer); reason: why nothing can move", + ), CommandSpec::new("joint.motion_link", "Motion Link", motion_link) .at("SOLID", "ASSEMBLE") .icon("motion_link") @@ -562,6 +565,111 @@ fn drive(s: &mut Session, p: &Value) -> Result { Ok(out) } +/// Joints `joint.reach` takes at most in `joints`. +const MAX_REACH_JOINTS: usize = 1000; + +fn reach(s: &mut Session, p: &Value) -> Result { + let cmd = "joint.reach"; + let occ = occurrence_id(s, p.get("occurrence"), cmd)?; + let given = |k: &str| p.get(k).and_then(vec3).filter(|v| v.is_finite() && v.len() < 1e9); + let to = given("point").ok_or_else(|| bad(cmd, "`point` must be [x, y, z]"))?; + let world = if occ == 0 { solidcraft_doc::IDENTITY } else { joints::occurrence_world(&s.doc, occ) }; + let inv = solidcraft_doc::mat_inverse(&world).ok_or_else(|| bad(cmd, "occurrence transform"))?; + let at = match p.get("at") { + Some(_) => solidcraft_doc::apply_point(&inv, given("at").ok_or_else(|| bad(cmd, "`at` must be [x, y, z]"))?), + None => body_centre(s, occ), + }; + let unit = |k: &str| -> Result> { + match p.get(k) { + None => Ok(None), + Some(_) => given(k).and_then(Vec3::normalized).map(Some).ok_or_else(|| bad(cmd, format!("`{k}` must be a direction [x, y, z]"))), + } + }; + let (z, axis) = (unit("z")?, unit("axis")?); + if axis.is_some() && z.is_none() { + return Err(bad(cmd, "`axis` goes with `z`, the way it points")); + } + let axis = z.map(|z| (axis.map(|a| solidcraft_doc::apply_vector(&inv, a)).and_then(Vec3::normalized).unwrap_or(Vec3::Z), z)); + let only = match p.get("joints") { + None => None, + Some(Value::Array(a)) if a.len() <= MAX_REACH_JOINTS => Some(a.iter().map(|v| joint_id(s, Some(v), cmd)).collect::>>()?), + Some(_) => return Err(bad(cmd, format!("`joints` must be a list of joints (ids or names), at most {MAX_REACH_JOINTS}"))), + }; + let before = super::motion::positions(s); + let st = s.model.state(); + let r = joints::reach(&s.doc, &st, &joints::Reach { occurrence: occ, point: at, to, axis, joints: only }); + let reached = match &r { + Ok(x) => { + // Only a reach that moves something touches the design (and so adds an undo step). + if !x.values.is_empty() { + let doc = s.doc_mut(); + for (id, q) in &x.values { + if let Some(j) = doc.assembly.joints.iter_mut().find(|j| j.id == *id) { + j.values.clone_from(q); + } + } + } + x.clone() + } + Err(_) => joints::Reached::default(), + }; + // Loops closed again from there, and where it ended up. + let sol = resolve(s); + let t = joints::occurrence_world(&s.doc, occ); + let got = solidcraft_doc::apply_point(&t, at); + let mut out = sol_json(&sol, p); + out["occurrence"] = json!(occurrence_name(s, occ)); + out["point"] = json!([got.x, got.y, got.z]); + out["error_mm"] = json!(got.dist(to)); + let mut there = got.dist(to) <= joints::REACH_TOL; + if let Some((a, z)) = axis { + // From the sine too: the cosine alone loses small angles to rounding. + let v = solidcraft_doc::apply_vector(&t, a); + let deg = v.cross(z).len().atan2(v.dot(z)).to_degrees(); + out["error_deg"] = json!(deg); + there &= deg <= joints::REACH_TOL; + } + out["reached"] = json!(there); + let name = |id: u64| s.doc.assembly.joints.iter().find(|j| j.id == id); + // As joint.list gives them: with what motion links set. + let effective = joints::joint_values(&s.doc.assembly); + out["values"] = reached + .values + .keys() + .filter_map(|id| name(*id)) + .map(|j| json!({"joint": j.id, "name": j.name, "values": named_values(j, effective.get(&j.id).unwrap_or(&j.values))})) + .collect(); + out["moved"] = json!(super::motion::moved(&before, &super::motion::positions(s)).next().is_some()); + out["stopped_by_limit"] = if reached.limits.is_empty() { + Value::Null + } else { + reached + .limits + .iter() + .filter_map(|(id, i, upper)| { + let j = name(*id)?; + Some(json!({"joint": j.name, "value": j.kind.dofs().get(*i), "limit": if *upper { "max" } else { "min" }})) + }) + .collect() + }; + out["stopped_by_loop"] = json!(reached.stopped_by_loop.and_then(name).map(|j| json!({"joint": j.name}))); + if let Err(why) = r { + out["reason"] = json!(why); + } + if bool_(p, "continuous") == Some(true) { + out["continuous"] = json!(true); + } + Ok(out) +} + +/// The centre of the box around an occurrence's bodies, in its own coordinates (its origin when +/// it has none). +fn body_centre(s: &Session, occ: u64) -> Vec3 { + let comp = s.doc.occurrences.iter().find(|o| o.id == occ).map(|o| o.component).unwrap_or(0); + let st = s.model.state(); + st.bodies.iter().filter(|b| s.doc.model_body_component(b) == comp).fold(Aabb3::EMPTY, |bb, b| bb.union(&b.mesh().bounds())).center() +} + fn motion_link(s: &mut Session, p: &Value) -> Result { let cmd = "joint.motion_link"; let (a, b) = (joint_id(s, p.get("a"), cmd)?, joint_id(s, p.get("b"), cmd)?); @@ -959,6 +1067,9 @@ fn overlapping_pairs(boxes: &[Aabb3], limit: usize) -> (Vec<(usize, usize)>, usi (pairs, skipped) } +#[cfg(test)] +#[path = "joints_reach_tests.rs"] +mod reach_tests; #[cfg(test)] #[path = "joints_tests.rs"] mod tests; diff --git a/crates/engine/src/cmd/joints_reach_tests.rs b/crates/engine/src/cmd/joints_reach_tests.rs new file mode 100644 index 000000000..ee4918b1c --- /dev/null +++ b/crates/engine/src/cmd/joints_reach_tests.rs @@ -0,0 +1,315 @@ +//! `joint.reach`: inverse kinematics against closed-form answers (planar arms), the nearest pose +//! out of reach, limits, and a four-bar reached through its rocker. + +use serde_json::{Value, json}; +use solidcraft_geom::Vec3; + +use super::tests::{four_bar, meet, occ, part, pin, place, run}; +use crate::Session; + +/// A planar arm about +Z on a grounded base: Shoulder at the origin, Upper 60 long, Elbow, Fore +/// 40 long, and with `hand` a Wrist and Hand 20 long, all along +X at 0°. Elbow starts at `elbow`°. +fn arm(hand: bool, elbow: f64) -> Session { + let mut s = Session::default(); + part(&mut s, "Base", [-1.0, -1.0, -1.0]); + part(&mut s, "Upper", [30.0, -1.0, -1.0]); + part(&mut s, "Fore", [80.0, -1.0, -1.0]); + let base = occ(&s, "Base"); + run(&mut s, "occurrence.ground", json!({"occurrence": base, "grounded": true})); + pin(&mut s, "revolute", "Shoulder", "Base", "Upper", Vec3::ZERO, Vec3::Z); + pin(&mut s, "revolute", "Elbow", "Upper", "Fore", Vec3::new(60.0, 0.0, 0.0), Vec3::Z); + if hand { + part(&mut s, "Hand", [110.0, -1.0, -1.0]); + pin(&mut s, "revolute", "Wrist", "Fore", "Hand", Vec3::new(100.0, 0.0, 0.0), Vec3::Z); + } + run(&mut s, "joint.drive", json!({"joint": "Elbow", "value": elbow})); + s +} + +/// A joint's first value as `joint.list` gives it (degrees for an angle). +fn value(s: &mut Session, joint: &str) -> f64 { + let l = run(s, "joint.list", json!({"quiet": true})); + l["joints"] + .as_array() + .and_then(|js| js.iter().find(|j| j["name"] == joint)) + .map_or(f64::NAN, |j| j["values"][0]["value"].as_f64().unwrap_or(f64::NAN)) +} + +/// `joint.reach` of the occurrence's point `local` (its own coordinates). +fn reach(s: &mut Session, occurrence: &str, local: Vec3, mut p: Value) -> Value { + p["occurrence"] = json!(occurrence); + p["at"] = pt(place(s, occurrence, local)); + run(s, "joint.reach", p) +} + +fn pt(v: Vec3) -> Value { + json!([v.x, v.y, v.z]) +} + +fn got(r: &Value) -> Vec3 { + Vec3::new(r["point"][0].as_f64().unwrap_or(f64::NAN), r["point"][1].as_f64().unwrap_or(f64::NAN), r["point"][2].as_f64().unwrap_or(f64::NAN)) +} + +/// The two-link arm's closed-form answer for a tip at (x, y), elbow bent the positive way: the +/// shoulder and elbow angles in degrees. +fn two_link(x: f64, y: f64, l1: f64, l2: f64) -> (f64, f64) { + let c2 = (x * x + y * y - l1 * l1 - l2 * l2) / (2.0 * l1 * l2); + let t2 = c2.acos(); + let t1 = y.atan2(x) - (l2 * t2.sin()).atan2(l1 + l2 * t2.cos()); + (t1.to_degrees(), t2.to_degrees()) +} + +#[test] +fn a_two_link_arm_reaches_its_closed_form_pose() { + let mut s = arm(false, 30.0); + let tip = Vec3::new(100.0, 0.0, 0.0); + let to = Vec3::new(50.0, 50.0, 0.0); + let r = reach(&mut s, "Fore", tip, json!({"point": pt(to)})); + assert_eq!( + (&r["reached"], &r["moved"], &r["stopped_by_limit"], &r["stopped_by_loop"]), + (&json!(true), &json!(true), &Value::Null, &Value::Null), + "{r}" + ); + assert!(r["error_mm"].as_f64().is_some_and(|e| e < 1e-6), "{r}"); + assert!(place(&s, "Fore", tip).dist(to) < 1e-6, "{:?}", place(&s, "Fore", tip)); + let (t1, t2) = two_link(50.0, 50.0, 60.0, 40.0); + assert!((value(&mut s, "Shoulder") - t1).abs() < 1e-6 && (value(&mut s, "Elbow") - t2).abs() < 1e-6, "{r}"); + assert_eq!(r["values"].as_array().map(Vec::len), Some(2), "{r}"); + // Already there, a reach moves nothing and adds no undo step. + let steps = s.undo.len(); + let r = reach(&mut s, "Fore", tip, json!({"point": pt(to)})); + assert_eq!((&r["reached"], &r["moved"], s.undo.len()), (&json!(true), &json!(false), steps), "{r}"); + // One undo step puts it back. + run(&mut s, "edit.undo", json!({})); + assert!((value(&mut s, "Elbow") - 30.0).abs() < 1e-9 && value(&mut s, "Shoulder").abs() < 1e-9); +} + +/// A three-link arm puts its tip on the point and its hand along the axis given: the wrist is +/// then the two-link answer, and the hand's turn makes up the rest. +#[test] +fn a_three_link_arm_reaches_a_point_and_an_axis() { + let mut s = arm(true, 30.0); + let tip = Vec3::new(120.0, 0.0, 0.0); + // The hand's length, along its own X: at 30° in the world now (the elbow's turn). + let along = place(&s, "Hand", tip) - place(&s, "Hand", Vec3::new(100.0, 0.0, 0.0)); + let r = reach(&mut s, "Hand", tip, json!({"point": [50, 50, 0], "z": [0, 1, 0], "axis": pt(along)})); + assert_eq!(r["reached"], true, "{r}"); + assert!(r["error_deg"].as_f64().is_some_and(|e| e < 1e-6), "{r}"); + let (t1, t2) = two_link(50.0, 30.0, 60.0, 40.0); + let t3 = 90.0 - t1 - t2; + for (joint, want) in [("Shoulder", t1), ("Elbow", t2), ("Wrist", t3)] { + assert!((value(&mut s, joint) - want).abs() < 1e-6, "{joint}: {} wants {want}: {r}", value(&mut s, joint)); + } +} + +#[test] +fn out_of_reach_the_arm_points_at_the_target() { + let tip = Vec3::new(100.0, 0.0, 0.0); + // 150 mm away: the arm stretches toward it, 50 mm short. + let mut s = arm(false, 30.0); + let r = reach(&mut s, "Fore", tip, json!({"point": [-90, 120, 0]})); + assert_eq!( + (&r["reached"], &r["moved"], &r["stopped_by_limit"], &r["stopped_by_loop"]), + (&json!(false), &json!(true), &Value::Null, &Value::Null), + "{r}" + ); + assert!(r["error_mm"].as_f64().is_some_and(|e| (e - 50.0).abs() < 1e-3), "{r}"); + assert!(got(&r).dist(Vec3::new(-60.0, 80.0, 0.0)) < 1e-2, "{r}"); + assert!(place(&s, "Fore", tip).dist(got(&r)) < 1e-9, "{r}"); + // Out of its plane: the nearest is the point under the target. + let mut s = arm(false, 30.0); + let r = reach(&mut s, "Fore", tip, json!({"point": [50, 50, 30]})); + assert_eq!(r["reached"], false, "{r}"); + assert!(r["error_mm"].as_f64().is_some_and(|e| (e - 30.0).abs() < 1e-6), "{r}"); + assert!(got(&r).dist(Vec3::new(50.0, 50.0, 0.0)) < 1e-6, "{r}"); +} + +#[test] +fn a_limited_elbow_stops_the_reach_and_says_so() { + let tip = Vec3::new(100.0, 0.0, 0.0); + let mut s = arm(false, 10.0); + run(&mut s, "joint.limits", json!({"joint": "Elbow", "min": -30, "max": 30})); + let r = reach(&mut s, "Fore", tip, json!({"point": [50, 50, 0]})); + // The target needs the elbow at 92°: it bends to its limit, and the arm points at the target. + assert_eq!(r["reached"], false, "{r}"); + assert_eq!(r["stopped_by_limit"], json!([{"joint": "Elbow", "value": "angle", "limit": "max"}]), "{r}"); + assert!((value(&mut s, "Elbow") - 30.0).abs() < 1e-9, "{r}"); + let span = (60f64.powi(2) + 40f64.powi(2) + 2.0 * 60.0 * 40.0 * 30f64.to_radians().cos()).sqrt(); + let d = 50.0 * 2f64.sqrt(); + assert!(r["error_mm"].as_f64().is_some_and(|e| (e - (span - d)).abs() < 1e-4), "{r}"); + // Only the shoulder moves when only it is given: the tip swings on its circle. + let mut s = arm(false, 30.0); + let r = reach(&mut s, "Fore", tip, json!({"point": [0, 100, 0], "joints": ["Shoulder"]})); + let span = (60f64.powi(2) + 40f64.powi(2) + 2.0 * 60.0 * 40.0 * 30f64.to_radians().cos()).sqrt(); + assert!(r["error_mm"].as_f64().is_some_and(|e| (e - (100.0 - span)).abs() < 1e-4), "{r}"); + assert!((value(&mut s, "Elbow") - 30.0).abs() < 1e-12, "{r}"); +} + +/// A linked elbow (elbow = −shoulder, so the forearm keeps pointing along +X) follows the +/// shoulder: the tip moves on a circle about (40, 0), and the reach turns the shoulder only. +#[test] +fn a_linked_joint_follows_the_reach() { + let tip = Vec3::new(100.0, 0.0, 0.0); + let mut s = arm(false, 0.0); + run(&mut s, "joint.motion_link", json!({"a": "Shoulder", "b": "Elbow", "ratio": -1})); + let th = 40f64.to_radians(); + let to = json!([40.0 + 60.0 * th.cos(), 60.0 * th.sin(), 0.0]); + let r = reach(&mut s, "Fore", tip, json!({"point": to})); + assert_eq!(r["reached"], true, "{r}"); + assert!((value(&mut s, "Shoulder") - 40.0).abs() < 1e-6 && (value(&mut s, "Elbow") + 40.0).abs() < 1e-6, "{r}"); + // Given only the linked elbow, the reach turns it through its link's source. + run(&mut s, "edit.undo", json!({})); + let r = reach(&mut s, "Fore", tip, json!({"point": to, "joints": ["Elbow"]})); + assert_eq!(r["reached"], true, "{r}"); + assert!((value(&mut s, "Shoulder") - 40.0).abs() < 1e-6, "{r}"); + // The elbow held at its own limit by the link stops the reach, and is named. + run(&mut s, "edit.undo", json!({})); + run(&mut s, "joint.limits", json!({"joint": "Elbow", "min": -30, "max": 30})); + let r = reach(&mut s, "Fore", tip, json!({"point": to})); + assert_eq!(r["reached"], false, "{r}"); + assert!(r["stopped_by_limit"].as_array().is_some_and(|l| l.contains(&json!({"joint": "Elbow", "value": "angle", "limit": "min"}))), "{r}"); +} + +/// A target straight across the pivot from the point (where the misses don't change to first +/// order) is still reached: the arm turns half round, the way its limits leave open. +#[test] +fn a_target_across_the_pivot_is_reached() { + let tip = Vec3::new(100.0, 0.0, 0.0); + for (limits, want) in [(None, None), (Some([-180, 0]), Some(-180.0)), (Some([0, 180]), Some(180.0))] { + let mut s = arm(false, 0.0); + if let Some([min, max]) = limits { + run(&mut s, "joint.limits", json!({"joint": "Shoulder", "min": min, "max": max})); + } + let r = reach(&mut s, "Fore", tip, json!({"point": [-100, 0, 0], "joints": ["Shoulder"]})); + assert_eq!(r["reached"], true, "{limits:?}: {r}"); + let got = value(&mut s, "Shoulder"); + assert!((got.abs() - 180.0).abs() < 1e-6 && want.is_none_or(|w| (got - w).abs() < 1e-6), "{limits:?}: {got}"); + } +} + +/// A loop that only closes again after a full turn of a value geared up from the arm's (a joint +/// between two grounded parts, linked 36:1 to the shoulder) holds the arm: a step of a tenth of a +/// turn would close it at both ends, but not on the way. +#[test] +fn a_loop_geared_up_from_the_chain_holds_it() { + let tip = Vec3::new(100.0, 0.0, 0.0); + let mut s = arm(false, 0.0); + part(&mut s, "Lock", [-1.0, 5.0, -1.0]); + let lock = occ(&s, "Lock"); + run(&mut s, "occurrence.ground", json!({"occurrence": lock, "grounded": true})); + pin(&mut s, "revolute", "Lock", "Base", "Lock", Vec3::ZERO, Vec3::Z); + run(&mut s, "joint.motion_link", json!({"a": "Shoulder", "b": "Lock", "ratio": 36})); + let r = reach(&mut s, "Fore", tip, json!({"point": [0, 1e6, 0], "joints": ["Shoulder"]})); + assert_eq!((&r["reached"], &r["stopped_by_loop"]), (&json!(false), &json!({"joint": "Lock"})), "{r}"); + assert!(value(&mut s, "Shoulder").abs() < 1e-6, "{r}"); + // Geared up so far that even the small kick off a target straight across the pivot would turn + // the loop a whole turn: it holds too. + run(&mut s, "joint.delete", json!({"link": 0})); + run(&mut s, "joint.motion_link", json!({"a": "Shoulder", "b": "Lock", "ratio": 36000})); + let r = reach(&mut s, "Fore", tip, json!({"point": [-100, 0, 0], "joints": ["Shoulder"]})); + assert_eq!(r["reached"], false, "{r}"); + assert!(value(&mut s, "Shoulder").abs() < 1e-6, "{r}"); +} + +/// A planar joint far from the point turns it and slides the long way round, and the answer +/// gives the values as joint.list does. +#[test] +fn a_planar_joint_far_from_the_point_turns_and_slides() { + let mut s = Session::default(); + part(&mut s, "Base", [-1.0, -1.0, -1.0]); + part(&mut s, "Puck", [99.0, -1.0, 2.0]); + let base = occ(&s, "Base"); + run(&mut s, "occurrence.ground", json!({"occurrence": base, "grounded": true})); + pin(&mut s, "planar", "Table", "Base", "Puck", Vec3::ZERO, Vec3::Z); + let r = reach(&mut s, "Puck", Vec3::new(100.0, 0.0, 0.0), json!({"point": [100, 0, 0], "z": [0, 1, 0], "axis": [1, 0, 0]})); + assert_eq!(r["reached"], true, "{r}"); + let l = run(&mut s, "joint.list", json!({"quiet": true})); + let listed = l["joints"].as_array().and_then(|js| js.iter().find(|j| j["name"] == "Table")).map(|j| j["values"].clone()); + assert_eq!(Some(r["values"][0]["values"].clone()), listed, "{r}"); + assert!((r["values"][0]["values"][2]["value"].as_f64().unwrap_or(f64::NAN) - 90.0).abs() < 1e-6, "{r}"); +} + +/// A slider on its own (a chain with no size) still travels the whole way. +#[test] +fn a_lone_slider_travels_all_the_way() { + let mut s = Session::default(); + part(&mut s, "Base", [-1.0, -1.0, -1.0]); + part(&mut s, "Ram", [-1.0, -1.0, 2.0]); + let base = occ(&s, "Base"); + run(&mut s, "occurrence.ground", json!({"occurrence": base, "grounded": true})); + pin(&mut s, "slider", "Rail", "Base", "Ram", Vec3::ZERO, Vec3::Z); + let r = reach(&mut s, "Ram", Vec3::ZERO, json!({"point": [0, 0, 100]})); + assert_eq!(r["reached"], true, "{r}"); + assert!((value(&mut s, "Rail") - 100.0).abs() < 1e-6, "{r}"); + // However far. + let r = reach(&mut s, "Ram", Vec3::ZERO, json!({"point": [0, 0, 3e7]})); + assert_eq!(r["reached"], true, "{r}"); + // A limit on it is named whatever the chain's size. + run(&mut s, "edit.undo", json!({})); + run(&mut s, "joint.limits", json!({"joint": "Rail", "min": -50, "max": 100})); + let r = reach(&mut s, "Ram", Vec3::ZERO, json!({"point": [0, 0, 1e6]})); + assert_eq!(r["stopped_by_limit"], json!([{"joint": "Rail", "value": "distance", "limit": "max"}]), "{r}"); + // And a reach of a thousandth of a millimetre still moves it. + let r = reach(&mut s, "Ram", Vec3::ZERO, json!({"point": [0, 0, 99.999]})); + assert_eq!((&r["reached"], &r["moved"]), (&json!(true), &json!(true)), "{r}"); +} + +/// The four-bar's rocker reaches a point on its swing, the crank and coupler following with the +/// loop closed; past its toggle position it stops there, and the loop is named. +#[test] +fn a_four_bar_reaches_with_its_rocker() { + let (mut s, _, q0) = four_bar(); + let o4 = Vec3::new(45.0, 0.0, 0.0); + let start = q0.y.atan2(q0.x - 45.0); + let swing = |deg: f64| o4 + Vec3::new((start + deg.to_radians()).cos(), (start + deg.to_radians()).sin(), 0.0) * 40.0; + let r = run(&mut s, "joint.reach", json!({"occurrence": "Rocker", "at": pt(q0), "point": pt(swing(-10.0))})); + assert_eq!((&r["reached"], &r["stopped_by_loop"]), (&json!(true), &Value::Null), "{r}"); + assert_eq!(r["conflicts"].as_array().map(Vec::len), Some(0), "{r}"); + assert!(place(&s, "Rocker", q0).dist(swing(-10.0)) < 1e-6 && place(&s, "Coupler", q0).dist(swing(-10.0)) < 1e-6, "{r}"); + // The crank turned to where the loop closes with the rocker there (its pin on the coupler's circle). + let th = (90.0 + value(&mut s, "Crank")).to_radians(); + let crank_pin = Vec3::new(20.0 * th.cos(), 20.0 * th.sin(), 0.0); + assert!((crank_pin.dist(swing(-10.0)) - 50.0).abs() < 1e-6 && place(&s, "Coupler", Vec3::new(0.0, 20.0, 0.0)).dist(crank_pin) < 1e-6, "{r}"); + // Past its toggle position (|Q| = 30) the loop stops it there. + let (mut s, _, q0) = four_bar(); + let r = run(&mut s, "joint.reach", json!({"occurrence": "Rocker", "at": pt(q0), "point": pt(swing(100.0))})); + assert_eq!((&r["reached"], &r["stopped_by_loop"]), (&json!(false), &json!({"joint": "Rocker pin"})), "{r}"); + // Its joints have no limits, so none is named. + assert_eq!(r["stopped_by_limit"], Value::Null, "{r}"); + assert_eq!(r["conflicts"].as_array().map(Vec::len), Some(0), "{r}"); + let limit = ((900.0f64 - 3625.0) / 3600.0).acos().to_degrees() - start.to_degrees(); + let at = value(&mut s, "Rocker"); + assert!(at > limit - 0.5 && at <= limit + 1e-6, "stopped at {at}°, the toggle is at {limit}°: {r}"); + let [m1, m2] = meet(o4, 40.0, Vec3::ZERO, 30.0); + assert!(place(&s, "Rocker", q0).dist(m1).min(place(&s, "Rocker", q0).dist(m2)) < 0.5, "{r}"); +} + +#[test] +fn reach_refuses_bad_params_and_says_why_nothing_moves() { + let mut s = arm(false, 30.0); + for bad in [ + json!({"occurrence": "Fore"}), + json!({"occurrence": "Nope", "point": [0, 0, 0]}), + json!({"occurrence": "Fore", "point": [1e300, 0, 0]}), + json!({"occurrence": "Fore", "point": [0, 0, "x"]}), + json!({"occurrence": "Fore", "point": [0, 0, 0], "z": [0, 0, 0]}), + json!({"occurrence": "Fore", "point": [0, 0, 0], "axis": [1, 0, 0]}), + json!({"occurrence": "Fore", "point": [0, 0, 0], "joints": "Elbow"}), + json!({"occurrence": "Fore", "point": [0, 0, 0], "joints": ["Nope"]}), + json!({"occurrence": "Fore", "point": [0, 0, 0], "at": [f64::MAX, 0, 0]}), + ] { + assert!(s.execute("joint.reach", &bad).is_err(), "{bad}"); + } + // A grounded part, a part no joint places, and joints that don't move it: nothing moves, and + // the answer says why. + part(&mut s, "Loose", [200.0, 0.0, 0.0]); + for (p, why) in [ + (json!({"occurrence": "Base", "point": [5, 5, 5]}), "fixed in place"), + (json!({"occurrence": "Loose", "point": [5, 5, 5]}), "not connected"), + (json!({"occurrence": "Upper", "point": [5, 5, 5], "joints": ["Elbow"]}), "none of the joints given"), + ] { + let r = run(&mut s, "joint.reach", p.clone()); + assert_eq!((&r["reached"], &r["moved"]), (&json!(false), &json!(false)), "{p}: {r}"); + assert!(r["reason"].as_str().is_some_and(|w| w.contains(why)), "{p}: {r}"); + } +} diff --git a/crates/engine/src/cmd/joints_tests.rs b/crates/engine/src/cmd/joints_tests.rs index 1c86e632c..66da370ed 100644 --- a/crates/engine/src/cmd/joints_tests.rs +++ b/crates/engine/src/cmd/joints_tests.rs @@ -5,19 +5,19 @@ use solidcraft_geom::Vec3; use crate::Session; -fn run(s: &mut Session, id: &str, p: Value) -> Value { +pub(super) 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 occ(s: &Session, component: &str) -> u64 { +pub(super) fn occ(s: &Session, component: &str) -> u64 { let c = s.doc.find_component(component).unwrap_or(0); s.doc.occurrence_of(c).map(|o| o.id).unwrap_or(0) } -fn place(s: &Session, component: &str, p: Vec3) -> Vec3 { +pub(super) fn place(s: &Session, component: &str, p: Vec3) -> Vec3 { solidcraft_doc::apply_point(&solidcraft_doc::joints::occurrence_world(&s.doc, occ(s, component)), p) } @@ -313,21 +313,21 @@ fn interference_box_sweep_matches_every_pair_check() { } /// A small block in a new component: a part of a linkage, where only its joints matter. -fn part(s: &mut Session, name: &str, corner: [f64; 3]) { +pub(super) fn part(s: &mut Session, name: &str, corner: [f64; 3]) { run(s, "component.activate", json!({"component": "root"})); run(s, "component.create", json!({"name": name})); run(s, "solid.box", json!({"length": 2, "width": 2, "height": 2, "corner": corner})); } /// A joint between two parts as they are, at a world point with its z along `z`. -fn pin(s: &mut Session, kind: &str, name: &str, a: &str, b: &str, p: Vec3, z: Vec3) { +pub(super) fn pin(s: &mut Session, kind: &str, name: &str, a: &str, b: &str, p: Vec3, z: Vec3) { let at = |o: &str| json!({"occurrence": o, "point": [p.x, p.y, p.z], "z": [z.x, z.y, z.z]}); let r = run(s, "joint.create", json!({"type": kind, "a": at(a), "b": at(b), "flip": true, "name": name})); assert_eq!(r["conflicts"].as_array().map(Vec::len), Some(0), "{r}"); } /// Where circles about `p` (radius `r`) and `q` (radius `s`) in the XY plane meet. -fn meet(p: Vec3, r: f64, q: Vec3, s: f64) -> [Vec3; 2] { +pub(super) fn meet(p: Vec3, r: f64, q: Vec3, s: f64) -> [Vec3; 2] { let d = q - p; let l = d.len(); let a = (r * r - s * s + l * l) / (2.0 * l); @@ -339,7 +339,7 @@ fn meet(p: Vec3, r: f64, q: Vec3, s: f64) -> [Vec3; 2] { /// A crank-rocker four-bar about +Z: ground pivots O2 = (0, 0) and O4 = (45, 0), crank 20, /// coupler 50, rocker 40, assembled with the crank at 90°. Returns the crank pin P0 and the /// rocker pin Q0 (the upper, open assembly). -fn four_bar() -> (Session, Vec3, Vec3) { +pub(super) fn four_bar() -> (Session, Vec3, Vec3) { let mut s = Session::default(); let (o2, o4, p0) = (Vec3::ZERO, Vec3::new(45.0, 0.0, 0.0), Vec3::new(0.0, 20.0, 0.0)); let [q0, _] = meet(p0, 50.0, o4, 40.0); diff --git a/crates/ui-egui/src/dialogs_assembly.rs b/crates/ui-egui/src/dialogs_assembly.rs index 3010838ef..06fd681a1 100644 --- a/crates/ui-egui/src/dialogs_assembly.rs +++ b/crates/ui-egui/src/dialogs_assembly.rs @@ -343,7 +343,7 @@ fn pt(v: Vec3) -> Value { } /// The occurrence placing a body (0: the root design), when the body is its primary instance. -fn occurrence_of_body(s: &Session, body: &str) -> Option { +pub(crate) fn occurrence_of_body(s: &Session, body: &str) -> Option { let st = s.world_state(); let b = st.body(body)?; let comp = s.doc.model_body_component(b); diff --git a/crates/ui-egui/src/joint_drag.rs b/crates/ui-egui/src/joint_drag.rs new file mode 100644 index 000000000..2b2929b15 --- /dev/null +++ b/crates/ui-egui/src/joint_drag.rs @@ -0,0 +1,214 @@ +//! Dragging a part that joints place moves it as far as its joints allow: each frame runs +//! `joint.reach`, taking the point grabbed toward the pointer in the plane through it that faces +//! the view. The whole drag is one undo step. + +use egui::Pos2; +use serde_json::json; +use solidcraft_engine::doc::{apply_point, joints, mat_inverse}; +use solidcraft_engine::geom::Vec3; + +use crate::SolveApp; +use crate::viewport::{Hit, Proj}; + +/// A drag under way. +#[derive(Clone, Debug)] +pub struct Drag { + occurrence: u64, + /// The point grabbed, in the occurrence's own coordinates. + local: Vec3, + /// The plane the pointer moves the point in: through where it was grabbed, facing the view. + origin: Vec3, + normal: Vec3, + /// The drag's undo step is on top of the history (it went in with the first frame that moved). + pushed: bool, +} + +/// Begin a drag on the part under `p` when joints place it and leave it free to move (it is +/// neither grounded nor fixed to what is). True when one began. +pub fn start(app: &mut SolveApp, proj: &Proj, p: Pos2) -> bool { + // The face under the pointer, past the part's own edges and vertices (not past sketches or + // construction geometry in front of it). + let hits = crate::viewport::pick(app, proj, p); + let Some((body, at)) = + hits.into_iter().take_while(|h| matches!(h, Hit::Face { .. } | Hit::Edge { .. } | Hit::Vertex { .. })).find_map(|h| match h { + Hit::Face { body, point, .. } => Some((body, point)), + _ => None, + }) + else { + return false; + }; + let s = &app.session; + let Some(occurrence) = crate::dialogs_assembly::occurrence_of_body(s, &body).filter(|o| *o != 0) else { return false }; + if !s.doc.assembly.joints.iter().any(|j| !j.suppressed && (j.a.occurrence == occurrence || j.b.occurrence == occurrence)) { + return false; + } + let sol = joints::solve(&s.doc, &s.model.state()); + if !sol.world.contains_key(&occurrence) || sol.dof.get(&occurrence).is_none_or(|d| *d == 0) { + return false; + } + let Some(local) = mat_inverse(&joints::occurrence_world(&s.doc, occurrence)).map(|inv| apply_point(&inv, at)) else { return false }; + let normal = proj.ray(p).1; + app.viewport.joint_drag = Some(Drag { occurrence, local, origin: at, normal, pushed: false }); + true +} + +pub fn active(app: &SolveApp) -> bool { + app.viewport.joint_drag.is_some() +} + +/// Reach for the point under `p`. +pub fn to(app: &mut SolveApp, proj: &Proj, p: Pos2) { + let Some(d) = app.viewport.joint_drag.clone() else { return }; + let (o, dir) = proj.ray(p); + let facing = dir.dot(d.normal); + if facing.abs() < 1e-9 { + return; + } + let target = o + dir * ((d.origin - o).dot(d.normal) / facing); + if !target.is_finite() { + return; + } + let at = apply_point(&joints::occurrence_world(&app.session.doc, d.occurrence), d.local); + let params = + json!({"occurrence": d.occurrence, "at": [at.x, at.y, at.z], "point": [target.x, target.y, target.z], "quiet": true, "continuous": true}); + // One undo step for the whole drag: the first frame's, kept on top while the others run (not + // truncated by depth, which a full history would make lose its oldest steps frame by frame). + let own = if d.pushed { app.session.undo.pop() } else { None }; + // A frame that changes the design adds an undo step (a full history drops its oldest for it, + // so its length says nothing). + let before = app.session.doc.clone(); + let pushed = app.run("joint.reach", params).is_ok() && !std::sync::Arc::ptr_eq(&before, &app.session.doc); + match own { + Some(step) => { + if pushed { + app.session.undo.pop(); + } + app.session.undo.push(step); + } + None if pushed => { + if let Some(d) = app.viewport.joint_drag.as_mut() { + d.pushed = true; + } + } + None => {} + } +} + +pub fn end(app: &mut SolveApp) { + app.viewport.joint_drag = None; +} + +#[cfg(test)] +mod tests { + use serde_json::{Value, json}; + use solidcraft_engine::doc::{apply_point, joints}; + use solidcraft_engine::geom::Vec3; + + use crate::scenario::Harness; + + fn run(h: &mut Harness, id: &str, p: Value) -> Value { + h.app.run(id, p.clone()).unwrap_or_else(|e| panic!("{id} {p}: {e}")) + } + + fn screen(h: &mut Harness, p: Vec3) -> egui::Pos2 { + let [x, y] = h.at(&json!({"world": [p.x, p.y, p.z]})).expect("on screen"); + egui::pos2(x as f32, y as f32) + } + + /// Where the arm's point `local` (its own coordinates) is. + fn arm_at(h: &Harness, local: Vec3) -> Vec3 { + let s = &h.app.session; + let c = s.doc.find_component("Arm").unwrap_or(0); + let o = s.doc.occurrence_of(c).map(|o| o.id).unwrap_or(0); + apply_point(&joints::occurrence_world(&s.doc, o), local) + } + + /// An arm hinged about +Z on a grounded base (seen from the top): its far end, and the screen + /// points of that end and of the end turned a quarter round. + fn hinged_arm() -> (Harness, Vec3, egui::Pos2, egui::Pos2) { + let mut h = Harness::new(); + h.app.home.open = false; + for (name, corner, size) in [("Base", [-5, -5, 0], [10, 10, 5]), ("Arm", [-3, -3, 5], [63, 6, 5])] { + run(&mut h, "component.activate", json!({"component": "root"})); + run(&mut h, "component.create", json!({"name": name})); + run(&mut h, "solid.box", json!({"length": size[0], "width": size[1], "height": size[2], "corner": corner})); + } + run(&mut h, "component.activate", json!({"component": "root"})); + let base = h.app.session.doc.find_component("Base").and_then(|c| h.app.session.doc.occurrence_of(c)).map(|o| o.id).unwrap_or(0); + run(&mut h, "occurrence.ground", json!({"occurrence": base, "grounded": true})); + let at = |o: &str| json!({"occurrence": o, "point": [0, 0, 5], "z": [0, 0, 1]}); + run(&mut h, "joint.create", json!({"type": "revolute", "a": at("Base"), "b": at("Arm"), "flip": true, "name": "Hinge"})); + h.call("ui.view", json!({"view": "top"})); + h.app.cam.distance = 200.0; + h.frames(3); + let end = Vec3::new(55.0, 0.0, 10.0); + let (a, b) = (screen(&mut h, end), screen(&mut h, Vec3::new(0.0, 55.0, 10.0))); + (h, end, a, b) + } + + fn play(h: &mut Harness) { + while !h.app.synthetic.is_empty() { + h.frame(); + } + h.frames(2); + } + + /// Press at `a` and move to `b` in 12 frames, holding the button there. + fn press_and_move(h: &mut Harness, a: egui::Pos2, b: egui::Pos2) { + 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((1..=12).map(|k| egui::Event::PointerMoved(a + (b - a) * (k as f32 / 12.0)))); + play(h); + } + + fn release(h: &mut Harness, b: egui::Pos2) { + h.app.synthetic.push(egui::Event::PointerButton { + pos: b, + button: egui::PointerButton::Primary, + pressed: false, + modifiers: Default::default(), + }); + play(h); + } + + /// Dragged by its far end a quarter turn round, the arm turns there in one undo step, and undo + /// turns it back. + #[test] + fn dragging_a_jointed_part_turns_it_about_its_hinge() { + let (mut h, end, a, b) = hinged_arm(); + let undo = h.app.session.undo.len(); + press_and_move(&mut h, a, b); + assert!(h.app.viewport.joint_drag.is_some() && h.app.viewport.boxsel.is_none(), "the drag moves the arm, not a selection box"); + release(&mut h, b); + assert!(h.app.viewport.joint_drag.is_none()); + assert!(arm_at(&h, end).dist(Vec3::new(0.0, 55.0, 10.0)) < 0.5, "{:?}", arm_at(&h, end)); + assert_eq!(h.app.session.undo.len(), undo + 1, "one undo step for the drag"); + assert!(!h.app.session.log.iter().any(|l| l.contains("Reach")), "frames are not echoed: {:?}", h.app.session.log); + run(&mut h, "edit.undo", json!({})); + assert!(arm_at(&h, end).dist(end) < 1e-9, "{:?}", arm_at(&h, end)); + } + + /// With the undo history full, a drag still adds one step: it drops the oldest once, not one + /// per frame. + #[test] + fn a_drag_on_a_full_undo_history_drops_one_step() { + let (mut h, _, a, b) = hinged_arm(); + let step = h.app.session.undo.last().cloned().expect("an undo step"); + while h.app.session.undo.len() < 200 { + let mut older = step.clone(); + older.label = format!("step {}", h.app.session.undo.len()); + h.app.session.undo.insert(0, older); + } + let second = h.app.session.undo.get(1).map(|s| s.label.clone()); + press_and_move(&mut h, a, b); + release(&mut h, b); + assert_eq!(h.app.session.undo.len(), 200); + assert_eq!(h.app.session.undo.first().map(|s| s.label.clone()), second, "only the oldest step went"); + assert_eq!(h.app.session.undo.last().map(|s| s.label.as_str()), Some("Reach Point"), "the drag's step is on top"); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index a740dd3b9..6a5bf6b40 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -62,6 +62,7 @@ pub mod icons; pub mod inference; pub mod install; pub mod issue_report; +pub mod joint_drag; pub mod keymap; mod material_card_review; #[cfg(test)] @@ -632,7 +633,9 @@ impl SolveApp { // reads the same way the toolbar button it came from does. let language = i18n::Locale::for_language(&self.preferences.language); let label = language.label(command_label(id)); - if !(id == "view.navigate" && v.get("continuous").and_then(Value::as_bool) == Some(true)) { + // Frames of a gesture (a continuous view move, a part dragged by its joints) are + // not echoed one by one. + if v.get("continuous").and_then(Value::as_bool) != Some(true) { self.session.echo(language.format("ui.command_done", &[("command", label)])); } if id == "file.new" { diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index d02d06e18..2bcc6464a 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -118,6 +118,8 @@ pub struct ViewportState { pub point_drag: Option<(String, usize, Option)>, /// Checkpoint and source for a cancellable whole-text drag. pub(crate) text_drag: Option<(u64, String)>, + /// A part that joints place, being dragged. + pub(crate) joint_drag: Option, } /// Something under the cursor. @@ -2493,12 +2495,32 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { if crate::sketch_text_handles::dragging(app) && !crate::issue_report::cad_input_blocked() && !ui.input(|i| i.pointer.primary_down()) { crate::sketch_text_handles::drag_end(app); } + // Dragging a part that joints place moves it as far as they allow (outside sketches). + if app.tool.is_none() && app.dialog.is_none() && primary_nav.is_none() && mode.is_none() && app.session.active_sketch.is_none() && !held { + if resp.drag_started_by(egui::PointerButton::Primary) + && let Some(a) = ui.input(|i| i.pointer.press_origin()) + && rect.contains(a) + && !axes.contains(a) + { + crate::joint_drag::start(app, &proj, a); + } + if crate::joint_drag::active(app) + && resp.dragged_by(egui::PointerButton::Primary) + && let Some(p) = hover + { + crate::joint_drag::to(app, &proj, p); + } + } + if crate::joint_drag::active(app) && (resp.drag_stopped() || !ui.input(|i| i.pointer.primary_down())) { + crate::joint_drag::end(app); + } // Box selection: a primary drag on the model when no navigation mode is on. if app.tool.is_none() && !held && primary_nav.is_none() && mode.is_none() && app.viewport.point_drag.is_none() + && !crate::joint_drag::active(app) && !crate::dim_view::dragging() && !crate::sketch3d::dragging() && !crate::sketch_text_handles::dragging(app) diff --git a/docs/book/src/guide/assemblies.md b/docs/book/src/guide/assemblies.md index 9b2ff8938..ca29a5613 100644 --- a/docs/book/src/guide/assemblies.md +++ b/docs/book/src/guide/assemblies.md @@ -76,6 +76,21 @@ why. While it previews, a row under the values gives the value the joint reached status line repeats it. The value box keeps what you typed. The dialog opens on the joint picked in the browser, or on the first joint that moves when none is picked. +**Drag a part that joints place** and it moves as far as its joints allow: the point you +grabbed follows the pointer in the plane through it that faces the view, the joints on the +part's chain take the values that bring it nearest, within their limits, through motion links, +and with closed loops kept closed, and a four-bar's rocker stops at the end of its swing. The +whole drag is one undo step. A grounded part, or one no joint places, is not moved; a drag on +it draws a selection box as before. Each frame runs `joint.reach`, which scripts and agents use +directly to put a part's point somewhere: `joint.reach {occurrence, point}` moves the joints on +its chain from where they are to the nearest pose (the arm keeps its elbow up or down, and a +linkage stays on its branch). `at` picks the part's point (the centre of its bodies by +default), `z` with `axis` also turns one of its axes, and `joints` names the only joints to +move (the other joints of a closed loop they are in follow). The answer says whether it +`reached` the point and how close it got (`error_mm`, `error_deg`), and when it falls short, +the limits it rests on (`stopped_by_limit`) or the loop that stopped it (`stopped_by_loop`). +Contact sets are not checked by a reach; drive the joints for that. + The solver places what it reaches from the root and from grounded components. A chain of joints that is joined to nothing grounded is never placed, so driving one of its joints moves nothing. The drive says so: `joint.drive` answers `moved: false` with a `reason` and the `unconnected` diff --git a/skills/solidcraft-mechanisms/SKILL.md b/skills/solidcraft-mechanisms/SKILL.md index 56b29217e..535bcdc04 100644 --- a/skills/solidcraft-mechanisms/SKILL.md +++ b/skills/solidcraft-mechanisms/SKILL.md @@ -74,6 +74,7 @@ Written against SolidCraft `main` after 0.11.1, which counts the degrees of free |---|---| | "The origins are at the same point, so `flip` doesn't matter" | Pass `flip: true`, or the part turns 180 degrees. | | "The drive answered values, so it moved" | Read `moved`; a chain joined to nothing grounded answers `moved: false` and a `reason`. | +| "Drive the arm joint by joint until the gripper gets there" | `joint.reach {"occurrence":..., "at":..., "point":...}` solves every joint on its chain at once; read `reached` and `error_mm`. | | "Key every joint of the loop in the study" | Key the driving joint only; the loop follows. | | "Check the pose with `component.list`" | `occurrence.properties` on the one occurrence. `component.list` is 140 KB on a 36-part assembly. | | "Open the design with `file.open`" | The `open` tool, or `doc.open`; there is no `file.open`. | diff --git a/skills/solidcraft-mechanisms/reference.md b/skills/solidcraft-mechanisms/reference.md index 99adc3874..aee1fa9bf 100644 --- a/skills/solidcraft-mechanisms/reference.md +++ b/skills/solidcraft-mechanisms/reference.md @@ -47,6 +47,7 @@ A slider's value grows as b moves along +z of its origin. Give its two origins t {"command":"joint.motion_link","params":{"a":"Hinge","b":"Hinge 2","ratio":-1}} {"command":"joint.drive","params":{"joint":"Hinge","value":20}} {"command":"joint.drive","params":{"joint":"Spindle","values":[30,5]}} +{"command":"joint.reach","params":{"occurrence":"Gripper","at":[120,0,40],"point":[60,80,40],"z":[0,0,-1],"axis":[1,0,0],"quiet":true}} {"command":"joint.limits","params":{"joint":"Hinge","min":0,"max":60}} {"command":"joint.edit","params":{"joint":"Hinge","flip":true}} {"command":"joint.delete","params":{"link":0}} @@ -64,6 +65,7 @@ A slider's value grows as b moves along +z of its origin. Give its two origins t - `joint.motion_link`: b = ratio·a + offset, clamped to b's limits. `ratio` is in b's units per a's: mm per degree when an angle drives a distance (a pinion of pitch radius r moves its rack r·π/180 mm per degree), degrees per mm the other way, and a plain factor between two angles or two distances. `offset` is in b's units: degrees for an angle, mm for a distance, or an expression such as `"10 deg"`. `joint.list` gives each link's `ratio` the same way and its `offset` with its `unit`. `ia`/`ib` pick a value of a multi-value joint (default 0). `joint.delete {"link": n}` removes link n (its index in `joint.list` `links`). - `joint.gear {a, b, ra, rb, internal?, reverse?}`, `joint.rack_pinion {a, b, radius, reverse?}` and `joint.screw {joint | a, b; pitch, reverse?}` make a motion link whose ratio comes from its sizes: gears -ra/rb (+ra/rb internal), a rack r mm per radian of its pinion (either joint may be `a`), a screw pitch per turn. Each size is mm, an expression, or `{occurrence, circle: [x,y,z]}`: the radius of the round face there, read again whenever the design changes. The reply gives `link` (its index) and `ratio` as `joint.list` does; `link: n` in the params replaces link n and keeps its offset. A new coupling's offset keeps b where it is. `joint.list` `links` carry the `coupling` and an `error` when it can't be worked out (a picked face gone: the last ratio stays). A value two links would set, or a coupling that would drive its own driver, is refused. - `joint.drive`: `values` drives the values it lists, in order (`Spindle` above is cylindrical: 30 degrees, then 5 mm), and `value` the first; values left out keep theirs, or follow in a closed loop. Values are clamped to the limits. The reply gives `values` as `joint.list` does (`{name, value, unit, limits}`), and `moved`; when the joint can move nothing, a `reason`. +- `joint.reach` (inverse kinematics): moves the joints on the occurrence's chain so its point `at` (world, where it is now; default: the centre of its bodies) gets to `point`, from the pose it is in to the nearest one, within limits, through motion links, and with closed loops kept closed. `z` with `axis` (world, now; default its own z) also turns that axis. `joints: [...]` moves only those (loop followers still follow). The reply: `reached`, `error_mm` (and `error_deg`), `point` where it ended, `values` of the joints that moved, `moved`, and when short, `stopped_by_limit: [{joint, value, limit}]` or `stopped_by_loop: {joint}`. A part that nothing moves answers `moved: false` with a `reason`. Contact sets are not checked; check with `contact.check` afterwards. - `motion.study {"study":..., ...}` edits a study; `keys` given replace all keys. - `motion.play` sets the joints to the study's values at a step (fractions work) and changes the design. `motion.export` does not change it. @@ -127,6 +129,7 @@ The same pattern moved the solar wings of the SELENE rover (`Rover-v7.solidcraft | A gear, rack or screw turns its partner the wrong way | The joints' axes point opposite ways (or the rack lies on the other side of the pinion). Run the command again with `reverse: true` and `link: n`. | | `already follows a motion link` from `joint.gear` | A joint follows one link at most. Make the joint that already follows the driving one (`a`), as in a gear train G1 → G2 → G3. | | A linked joint stops following | Its value is clamped to its own limits. Hinge 2 in the example has `[[-60, 0]]`, so a drive of Hinge below 0 leaves it at 0. Give a mirrored joint the mirrored limits. | +| `joint.reach` answers `reached: false` | The point is out of reach: `point` and `error_mm` give the nearest pose. `stopped_by_limit` names the limits it rests on, `stopped_by_loop` the loop that can't follow further; with neither, the chain can't get there at all (too far, or out of its plane). | | A drive stops short, `stopped_by_contact` | Two bodies of a contact set touch. `fraction` is how far the move got. | | `occurrence.ground` says there is no occurrence `Frame` | It takes occurrence names only: `Frame:1`. | | `a joint needs two different occurrences` | Both origins found the same part. Give `occurrence` on both. If the parts are bodies of one component (an imported STEP file often brings them so), run `component.from_bodies {"bodies": [...]}` first. | From 6c1a898e3d48421027e02bf724b274ccc269ca02 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Fri, 16 Oct 2026 00:07:41 -0400 Subject: [PATCH 59/92] Check for updates at every start; show "Update to X" as a title-bar pill (#1538) Thanks @bherbruck. --- 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/uk.json | 1 + assets/locales/zh.json | 1 + crates/ui-egui/src/toolbar.rs | 61 +++++++--- crates/ui-egui/src/update.rs | 49 +++++--- crates/ui-egui/src/update/tests.rs | 182 +++++++++++++++++++++++++++-- docs/book/src/guide/updates.md | 19 +-- 11 files changed, 268 insertions(+), 50 deletions(-) diff --git a/assets/locales/de.json b/assets/locales/de.json index d291fa094..37247a446 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -1139,6 +1139,7 @@ "update.available": "SolidCraft {version} ist verfügbar", "update.button": "Update", "update.button_tip": "SolidCraft {version} ist verfügbar", + "update.button_version": "Auf {version} aktualisieren", "update.check_automatically": "Automatisch nach Updates suchen", "update.check_now": "Jetzt suchen", "update.checking": "Suche läuft…", diff --git a/assets/locales/en.json b/assets/locales/en.json index fab0d438d..97a63780d 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -1409,6 +1409,7 @@ "update.available": "SolidCraft {version} is available", "update.button": "Update", "update.button_tip": "SolidCraft {version} is available", + "update.button_version": "Update to {version}", "update.check_automatically": "Check for updates automatically", "update.check_now": "Check now", "update.checking": "Checking…", diff --git a/assets/locales/fr.json b/assets/locales/fr.json index acb46e487..be28647c0 100644 --- a/assets/locales/fr.json +++ b/assets/locales/fr.json @@ -1235,6 +1235,7 @@ "update.available": "SolidCraft {version} est disponible", "update.button": "Mettre à jour", "update.button_tip": "SolidCraft {version} est disponible", + "update.button_version": "Mettre à jour vers {version}", "update.check_automatically": "Rechercher automatiquement les mises à jour", "update.check_now": "Vérifier maintenant", "update.checking": "Vérification…", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 676c707bb..1a454e417 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -1409,6 +1409,7 @@ "update.available": "SolidCraft {version} が利用できます", "update.button": "アップデート", "update.button_tip": "SolidCraft {version} が利用できます", + "update.button_version": "{version} にアップデート", "update.check_automatically": "アップデートを自動的に確認", "update.check_now": "今すぐ確認", "update.checking": "確認中…", diff --git a/assets/locales/ko.json b/assets/locales/ko.json index 877fbe9c5..29fd3eb0a 100644 --- a/assets/locales/ko.json +++ b/assets/locales/ko.json @@ -1139,6 +1139,7 @@ "update.available": "SolidCraft {version} 사용 가능", "update.button": "업데이트", "update.button_tip": "SolidCraft {version} 사용 가능", + "update.button_version": "{version}(으)로 업데이트", "update.check_automatically": "업데이트 자동 확인", "update.check_now": "지금 확인", "update.checking": "확인 중…", diff --git a/assets/locales/uk.json b/assets/locales/uk.json index b8c77211d..ce842bcb7 100644 --- a/assets/locales/uk.json +++ b/assets/locales/uk.json @@ -1066,6 +1066,7 @@ "update.available": "Доступна версія SolidCraft {version}", "update.button": "Оновити", "update.button_tip": "Доступна версія SolidCraft {version}", + "update.button_version": "Оновити до {version}", "update.check_automatically": "Автоматично перевіряти оновлення", "update.check_now": "Перевірити зараз", "update.checking": "Перевірка…", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index 8a4115b77..b4082881d 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -1409,6 +1409,7 @@ "update.available": "SolidCraft {version} 已发布", "update.button": "更新", "update.button_tip": "SolidCraft {version} 已发布", + "update.button_version": "更新到 {version}", "update.check_automatically": "自动检查更新", "update.check_now": "立即检查", "update.checking": "正在检查…", diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index effc2bfef..8407fc223 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -166,30 +166,55 @@ fn report_rect(bar: Rect, captions: f32, tabs_start: f32, label_width: f32) -> ( (Rect::from_min_size(pos2(right - width, bar.top() + 4.0), vec2(width, 26.0)), labeled) } -/// An application-bar button for something on offer (Update, Install) at the right of `span` (the -/// bar's free space): an accent-framed `icon`, labeled with `text` when `labeled` and it fits. -/// None when even the icon alone doesn't fit: it never covers the bar's other buttons. `handle` -/// names it for scenarios. -pub(crate) fn offer_button(ui: &mut egui::Ui, span: Rect, labeled: bool, text: &str, icon: &str, handle: &str) -> Option<(Rect, egui::Response)> { +/// The height of an application-bar pill ([`offer_pill`]), a little under the bar's 26 px buttons. +pub(crate) const PILL_HEIGHT: f32 = 22.0; + +/// An application-bar pill for something on offer (Update) at the right of `span` (the bar's free +/// space): accent-filled, with `icon` and the first of `labels` that fits (the icon alone when +/// none does or `labeled` is false). Every label but the last also leaves `keep` points of the +/// span free (for the document tabs). None when even the icon doesn't fit: it never covers the +/// bar's other buttons. `handle` names it for scenarios. +pub(crate) fn offer_pill( + ui: &mut egui::Ui, + span: Rect, + labeled: bool, + labels: &[&str], + keep: f32, + icon: &str, + handle: &str, +) -> Option<(Rect, egui::Response)> { let t = Tokens::get(); - let full = 30.0 + ui.fonts_mut(|f| f.layout_no_wrap(text.to_string(), FontId::proportional(13.0), t.app_bar_text).size().x) + 10.0; - let labeled = labeled && full <= span.width(); - let width = if labeled { full } else { 28.0 }; + let font = FontId::proportional(12.5); + let (icon_x, text_x, right_pad) = (16.0, 29.0, 11.0); + let last = labels.len().saturating_sub(1); + let label = labels.iter().enumerate().filter(|_| labeled).find_map(|(i, text)| { + let galley = ui.fonts_mut(|f| f.layout_no_wrap(text.to_string(), font.clone(), t.app_bar_text)); + let width = text_x + galley.size().x + right_pad; + let room = if i < last { span.width() - keep } else { span.width() }; + (width <= room).then_some((*text, width)) + }); + let width = label.map_or(PILL_HEIGHT + 4.0, |(_, w)| w); if width > span.width() { return None; } - let rect = Rect::from_min_size(pos2(span.right() - width, span.top()), vec2(width, 26.0)); - let response = ui.interact(rect, ui.id().with(("sc_offer_button", handle)), Sense::click()); - response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), text)); + let rect = Rect::from_min_size(pos2(span.right() - width, span.center().y - PILL_HEIGHT / 2.0), vec2(width, PILL_HEIGHT)); + let response = ui.interact(rect, ui.id().with(("sc_offer_pill", handle)), Sense::click()); + let name = label.map(|(text, _)| text).or(labels.first().copied()).unwrap_or_default().to_string(); + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &name)); crate::scenario::publish_handle(handle, rect.center()); crate::scenario::publish_rect(handle, rect); - let fill = if response.hovered() || response.has_focus() { t.hover } else { t.app_bar }; - ui.painter().rect_filled(rect, 4.0, fill); - ui.painter().rect_stroke(rect, 4.0, Stroke::new(1.0, t.accent), egui::StrokeKind::Inside); - let glyph = Rect::from_center_size(pos2(rect.left() + 14.0, rect.center().y), vec2(18.0, 18.0)); - icons::paint(ui.painter(), glyph, icon, t.accent, t.accent, t.app_bar); - if labeled { - ui.painter().text(pos2(rect.left() + 29.0, rect.center().y), Align2::LEFT_CENTER, text, FontId::proportional(13.0), t.app_bar_text); + let hot = response.hovered() || response.has_focus(); + let fill = if hot { t.accent.lerp_to_gamma(t.app_bar_text, 0.18) } else { t.accent }; + let radius = PILL_HEIGHT / 2.0; + ui.painter().rect_filled(rect, radius, fill); + if response.has_focus() { + ui.painter().rect_stroke(rect.expand(2.0), radius + 2.0, Stroke::new(1.0, t.app_bar_text), egui::StrokeKind::Outside); + } + let glyph_x = if label.is_some() { rect.left() + icon_x } else { rect.center().x }; + let glyph = Rect::from_center_size(pos2(glyph_x, rect.center().y), vec2(16.0, 16.0)); + icons::paint(ui.painter(), glyph, icon, t.app_bar_text, fill, t.app_bar_text); + if let Some((text, _)) = label { + ui.painter().text(pos2(rect.left() + text_x, rect.center().y), Align2::LEFT_CENTER, text, font, t.app_bar_text); } Some((rect, response)) } diff --git a/crates/ui-egui/src/update.rs b/crates/ui-egui/src/update.rs index b49c6003f..508f72b46 100644 --- a/crates/ui-egui/src/update.rs +++ b/crates/ui-egui/src/update.rs @@ -1,5 +1,5 @@ -//! Update notifications (docs/updates.md). At start, and at most once a day after that, a -//! background thread asks GitHub for the latest stable release (`releases/latest`; nightlies and +//! Update notifications (docs/book/src/guide/updates.md). At every start, and once a day after +//! that while the app stays open, a background thread asks GitHub for the latest stable release (`releases/latest`; nightlies and //! release candidates are never "latest"). When it is newer than this build, an Update button //! appears in the application bar beside Report a bug; it opens a small window with the version, //! the release notes and Download, Skip this version and Remind me later. @@ -32,17 +32,19 @@ pub const RELEASES_PAGE: &str = "https://github.com/bherbruck/solidcraft/release /// Release pages and assets must be on GitHub, under this repository. const RELEASE_PREFIX: &str = "https://github.com/bherbruck/solidcraft/releases/"; -/// Automatic checks: at most one a day. +/// While the app stays open, automatic checks run once a day (every start checks too). pub const CHECK_INTERVAL_S: f64 = 24.0 * 3600.0; /// Remind me later hides the button for three days. pub const REMIND_DELAY_S: f64 = 3.0 * 24.0 * 3600.0; /// Check now can't be pressed more often than this (GitHub allows 60 anonymous requests an hour). pub const MANUAL_COOLDOWN_S: f64 = 30.0; -/// After a failed automatic check, try again after this long (an hour), not every start. +/// After a failed automatic check, the open app tries again after this long (an hour). pub const RETRY_AFTER_FAILURE_S: f64 = 3600.0; /// Caps on what a release response may hold (it comes from the network). const MAX_NOTES: usize = 64 * 1024; const MAX_ASSETS: usize = 400; +/// The room the Update pill's long label leaves for the document tabs. +const TAB_ROOM: f32 = 300.0; /// The Update window's width, and its release notes' wrap width. const WINDOW_W: f32 = 460.0; const NOTES_W: f32 = WINDOW_W - 30.0; @@ -407,7 +409,8 @@ impl Release { pub struct Memo { /// When the last check finished (successfully or not). pub last_check: f64, - /// The next automatic check: a day after a successful one, an hour after a failed one. + /// The next automatic check while the app stays open: a day after a successful one, an hour + /// after a failed one. A new start doesn't wait for it. pub next_check: f64, /// GitHub's rate limit was reached: no request at all before this, not even Check now. pub rate_limited_until: f64, @@ -418,9 +421,13 @@ pub struct Memo { } impl Memo { - /// An automatic check is due (a clock set back by more than a day counts as due). - pub fn due(&self, now: f64) -> bool { - now >= self.rate_limited_until && (now >= self.next_check || self.next_check - now > CHECK_INTERVAL_S) + /// An automatic check is due. `launch`: no automatic check has run since SolidCraft started, + /// so one is due whatever the daily schedule says (someone who started yesterday's version + /// this morning hears about today's release at the next start). GitHub's rate limit always + /// holds. A clock set back by more than a day counts as due. + pub fn due(&self, now: f64, launch: bool) -> bool { + let limited = now < self.rate_limited_until && self.rate_limited_until - now <= CHECK_INTERVAL_S; + !limited && (launch || now >= self.next_check || self.next_check - now > CHECK_INTERVAL_S) } /// The Update button shows for `release`. @@ -484,6 +491,10 @@ pub struct Updater { /// The check in flight, and whether Check now started it. rx: Option<(Receiver>, bool)>, started: bool, + /// An automatic check has started since launch (until then one is due at once). + launch_checked: bool, + /// `SOLIDCRAFT_UPDATE_CHECK=0`: no checks at all. + off: bool, /// When Check now was last pressed (Unix seconds). last_manual: f64, /// A release given by `SOLIDCRAFT_UPDATE_FEED` (a file), for tests and screenshots. @@ -511,10 +522,11 @@ pub fn offered(app: &SolveApp) -> Option<&Release> { /// Checks may run here: a release build with the host's HTTP client, or a test feed. pub fn available(app: &mut SolveApp) -> bool { - app.updater.feed.is_some() || (app.services.http_get.is_some() && app.updater.kind().checks()) + !app.updater.off && (app.updater.feed.is_some() || (app.services.http_get.is_some() && app.updater.kind().checks())) } -/// Per frame: the first frame starts a due automatic check; a finished check is collected. +/// Per frame: the first frame of each launch starts an automatic check, the open app checks +/// again once a day (an hour after a failure), and a finished check is collected. pub fn tick(app: &mut SolveApp, ctx: &egui::Context) { poll_install(app); // Quitting to restart or install was cancelled (a "save changes?" answered Cancel). @@ -527,6 +539,7 @@ pub fn tick(app: &mut SolveApp, ctx: &egui::Context) { { install::clean_up_after_update(std::env::current_exe().ok().as_deref()); if std::env::var("SOLIDCRAFT_UPDATE_CHECK").is_ok_and(|v| v == "0") { + app.updater.off = true; return; } app.updater.feed = std::env::var_os("SOLIDCRAFT_UPDATE_FEED").map(PathBuf::from); @@ -534,7 +547,9 @@ pub fn tick(app: &mut SolveApp, ctx: &egui::Context) { } poll(app); let now = unix_now(); - if app.updater.rx.is_none() && app.preferences.check_updates && app.preferences.update.due(now) && available(app) { + let launch = !app.updater.launch_checked; + if app.updater.rx.is_none() && app.preferences.check_updates && app.preferences.update.due(now, launch) && available(app) { + app.updater.launch_checked = true; start(app, ctx, false); } } @@ -714,11 +729,15 @@ pub fn take_launch(app: &mut SolveApp) -> Option<(PathBuf, Vec)> { // ---- user interface --------------------------------------------------------------------------- -/// The application bar's Update button, at the right of `span`; returns its rect (None: not shown). +/// The application bar's Update pill ("Update to 0.14.0"), at the right of `span`: it opens and +/// closes the Update window. Returns its rect (None: not shown). pub fn button(app: &mut SolveApp, ui: &mut egui::Ui, span: egui::Rect, labeled: bool) -> Option { - offered(app)?; - let (rect, response) = crate::toolbar::offer_button(ui, span, labeled, crate::i18n::tr("update.button"), "update", "titlebar:update")?; - let version = app.updater.release.as_ref().map(|r| r.version().to_string()).unwrap_or_default(); + let version = offered(app)?.version().to_string(); + // "Update to 0.14.0" while the document tabs keep room; a short "Update" when they would be + // squeezed; the icon alone in a narrow bar. + let full = crate::i18n::format("update.button_version", &[("version", &version)]); + let labels = [full.as_str(), crate::i18n::tr("update.button")]; + let (rect, response) = crate::toolbar::offer_pill(ui, span, labeled, &labels, TAB_ROOM, "update", "titlebar:update")?; if response.on_hover_text(crate::i18n::format("update.button_tip", &[("version", &version)])).clicked() { app.updater.open = !app.updater.open; } diff --git a/crates/ui-egui/src/update/tests.rs b/crates/ui-egui/src/update/tests.rs index 94eb05f31..9bcab45aa 100644 --- a/crates/ui-egui/src/update/tests.rs +++ b/crates/ui-egui/src/update/tests.rs @@ -217,24 +217,186 @@ fn skip_and_remind_later() { } #[test] -fn checks_run_daily_and_back_off() { +fn every_launch_checks_and_the_open_app_checks_daily() { let mut m = Memo::default(); let now = 1_800_000_000.0; - assert!(m.due(now), "the first start checks"); + assert!(m.due(now, true), "the first start checks"); m.checked(now, &Ok(release())); - assert!(!m.due(now + 3600.0)); - assert!(m.due(now + CHECK_INTERVAL_S)); - assert!(m.due(now - 2.0 * CHECK_INTERVAL_S), "a clock set back doesn't block checks for days"); + // Started this morning, checked then: the next start checks again at once. + assert!(m.due(now + 3600.0, true), "every start checks, whatever the daily schedule says"); + assert!(m.due(now + 5.0, true)); + // While it stays open: once a day. + assert!(!m.due(now + 3600.0, false)); + assert!(m.due(now + CHECK_INTERVAL_S, false)); + assert!(m.due(now - 2.0 * CHECK_INTERVAL_S, false), "a clock set back doesn't block checks for days"); + // A failed check: the open app tries again an hour later; a new start checks anyway. m.checked(now, &Err(FetchError::Failed("offline".into()))); - assert!(!m.due(now + 60.0)); - assert!(m.due(now + RETRY_AFTER_FAILURE_S)); + assert!(!m.due(now + 60.0, false)); + assert!(m.due(now + RETRY_AFTER_FAILURE_S, false)); + assert!(m.due(now + 60.0, true)); +} + +#[test] +fn the_rate_limit_holds_at_launch_too() { + let mut m = Memo::default(); + let now = 1_800_000_000.0; m.checked(now, &Err(FetchError::RateLimited { retry_after_s: 1800 })); - assert!(!m.due(now + 1700.0)); - assert!(m.due(now + 1800.0)); assert_eq!(m.rate_limited_until, now + 1800.0); + for launch in [false, true] { + assert!(!m.due(now + 1700.0, launch), "GitHub said to wait (launch: {launch})"); + assert!(m.due(now + 1800.0, launch)); + } // Absurd waits are capped at a day. m.checked(now, &Err(FetchError::RateLimited { retry_after_s: u64::MAX })); - assert!(m.due(now + CHECK_INTERVAL_S)); + assert!(!m.due(now + 3600.0, true)); + assert!(m.due(now + CHECK_INTERVAL_S, false)); + // A clock set back more than a day doesn't keep the limit for days. + assert!(m.due(now - 2.0 * CHECK_INTERVAL_S, true)); +} + +/// A fresh folder for a test's feed file, removed with it. +struct Scratch(PathBuf); + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn scratch() -> Scratch { + static N: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let dir = std::env::temp_dir().join(format!("solidcraft-update-test-{}-{n}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + Scratch(dir) +} + +/// A release one minor version past this build, as the `SOLIDCRAFT_UPDATE_FEED` file gives it. +fn next_release_feed(dir: &Path) -> (PathBuf, String) { + let mut v = parse_version(current_version()).unwrap(); + v = semver::Version::new(v.major, v.minor + 1, 0); + let path = dir.join("latest.json"); + let body = json!({ + "tag_name": format!("v{v}"), + "name": format!("SolidCraft {v}"), + "body": "## What's new\n\n- Faster rebuilds.", + "html_url": format!("https://github.com/bherbruck/solidcraft/releases/tag/v{v}"), + "assets": [] + }); + std::fs::write(&path, body.to_string()).unwrap(); + (path, v.to_string()) +} + +/// Frames until the check in flight has been collected. +fn wait_for_check(h: &mut crate::scenario::Harness) { + for _ in 0..500 { + h.frame(); + if h.app.updater.rx.is_none() && h.app.updater.status != Status::Checking { + return; + } + std::thread::sleep(std::time::Duration::from_millis(2)); + } + panic!("the update check didn't finish"); +} + +#[test] +fn a_new_launch_checks_even_when_the_last_check_was_today() { + let dir = scratch(); + let (feed, version) = next_release_feed(&dir.0); + let mut h = crate::scenario::Harness::new(); + // Yesterday's version was started and checked this morning: no check due until tomorrow. + let now = unix_now(); + h.app.preferences.update.last_check = now - 3600.0; + h.app.preferences.update.next_check = now + CHECK_INTERVAL_S - 3600.0; + h.app.updater.feed = Some(feed); + h.frame(); + assert_eq!(h.app.updater.status, Status::Checking, "the launch checks at once"); + wait_for_check(&mut h); + assert_eq!(h.app.updater.release.as_ref().map(|r| r.version().to_string()), Some(version.clone())); + assert!(h.app.preferences.update.next_check > now + CHECK_INTERVAL_S - 60.0, "the next check is a day later"); + // While the app stays open it doesn't ask again before then. + h.frames(5); + assert!(h.app.updater.rx.is_none() && h.app.updater.status == Status::Idle); +} + +#[test] +fn turning_off_automatic_checks_stops_the_launch_check() { + let dir = scratch(); + let (feed, _) = next_release_feed(&dir.0); + let mut h = crate::scenario::Harness::new(); + h.app.preferences.check_updates = false; + h.app.updater.feed = Some(feed); + h.frames(3); + assert_eq!(h.app.updater.status, Status::Idle); + assert!(h.app.updater.release.is_none()); +} + +#[test] +fn the_title_bar_offers_the_new_version_and_opens_the_update_window() { + let dir = scratch(); + let (feed, version) = next_release_feed(&dir.0); + let mut h = crate::scenario::Harness::new(); + let report = crate::scenario::rect_of("titlebar:report").unwrap(); + assert!(crate::scenario::rect_of("titlebar:update").is_none(), "nothing offered before a check"); + h.app.updater.feed = Some(feed); + h.frame(); + wait_for_check(&mut h); + h.frames(2); + // An accent pill reading "Update to ", just left of Report a bug, on the bar. + let label = format!("Update to {version}"); + let at = h.widget(&label).unwrap_or_else(|| panic!("no `{label}` in the title bar")); + let pill = crate::scenario::rect_of("titlebar:update").unwrap(); + assert!(pill.contains(egui::pos2(at[0] as f32, at[1] as f32))); + assert!(pill.right() <= report.left() && report.left() - pill.right() < 12.0, "beside Report a bug: {pill:?} {report:?}"); + assert!((pill.center().y - report.center().y).abs() < 1.0 && pill.height() <= report.height()); + assert_eq!(crate::scenario::rect_of("titlebar:report"), Some(report), "Report a bug stays where it was"); + assert!(!h.app.updater.open, "no window pops up by itself"); + assert!(crate::scenario::rect_of("update:window").is_none()); + // Clicking it opens the Update window (not a modal: the bar stays usable). + h.call("ui.click", json!({"x": pill.center().x, "y": pill.center().y})); + h.frames(2); + assert!(h.app.updater.open); + assert!(h.widget("Skip this version").is_some() && h.widget("Remind me later").is_some()); + // Remind me later hides the pill. + let later = h.widget("Remind me later").unwrap(); + h.call("ui.click", json!({"x": later[0], "y": later[1]})); + h.frames(2); + assert!(!h.app.updater.open); + assert!(h.widget(&label).is_none(), "Remind me later hides it"); +} + +#[test] +fn the_pill_shortens_in_a_narrow_title_bar() { + let dir = scratch(); + let (feed, version) = next_release_feed(&dir.0); + let mut h = crate::scenario::Harness::new(); + h.app.updater.feed = Some(feed); + h.frame(); + wait_for_check(&mut h); + let wide = crate::scenario::rect_of("titlebar:update").unwrap(); + let label = format!("Update to {version}"); + assert!(h.widget(&label).is_some()); + // Narrower and narrower: the pill never grows, never reaches Report a bug, and its label gives + // way (to "Update", then the icon alone) before the document tabs run out of room. + let mut last = wide.width(); + let mut shortened = false; + for width in [1000.0, 800.0, 700.0, 600.0, 520.0, 440.0] { + h.call("ui.resize", json!({"width": width, "height": 600})); + h.frames(3); + let report = crate::scenario::rect_of("titlebar:report").unwrap(); + // Icon alone, it keeps the full text for screen readers. + let pill = crate::scenario::rect_of("titlebar:update").filter(|_| h.widget(&label).is_some() || h.widget("Update").is_some()); + if let Some(p) = pill { + assert!(p.width() <= last + 0.5, "at {width}: {p:?} grew from {last}"); + assert!(p.right() <= report.left(), "at {width}: {p:?} overlaps Report a bug {report:?}"); + last = p.width(); + } + shortened |= pill.is_none_or(|p| p.width() < wide.width()); + if width == 800.0 { + assert!(h.widget("Update").is_some() && h.widget(&label).is_none(), "the short label keeps room for the tabs"); + } + } + assert!(shortened, "the long label gives way in a narrow bar"); } #[test] diff --git a/docs/book/src/guide/updates.md b/docs/book/src/guide/updates.md index 9dd8aec3d..453075902 100644 --- a/docs/book/src/guide/updates.md +++ b/docs/book/src/guide/updates.md @@ -5,15 +5,20 @@ the check sends nothing about you or your designs. ## What you see -When a newer stable release exists, an **Update** button appears in the title bar next to -**Report a bug**. It opens a small window with the new version, its release notes and three -choices: +When a newer stable release exists, a small accent-coloured pill reading **Update to 0.14.0** +(the new version) appears in the title bar next to **Report a bug**. Nothing pops up by itself: +clicking the pill opens a small window with the new version, its release notes and three +choices. In a narrower window the pill shortens to **Update** so the document tabs keep their +room, then to its icon alone. - **Download** opens the file that fits your installation (see the table below) in your browser, or the release page when there isn't one. -- **Skip this version** hides the button until an even newer release comes out. +- **Skip this version** hides the pill until an even newer release comes out. - **Remind me later** hides it for three days. +SolidCraft checks every time it starts, so a release that came out since you last opened it shows +up straight away, and again once a day while it stays open. + **Preferences ▸ General ▸ Updates** has **Check for updates automatically** (on by default) and **Check now**, which checks right away and shows the window even for a version you skipped. @@ -43,7 +48,7 @@ fails with a message, and **Download** is the way to update it. ## What is sent -One HTTPS request, at start and at most once a day while SolidCraft runs: +One HTTPS request each time SolidCraft starts, and once a day while it stays open: ```text GET https://api.github.com/repos/bherbruck/solidcraft/releases/latest @@ -60,9 +65,9 @@ sees the request like any other visit to the API (your IP address, the time); se SolidCraft compares the answer with its own version on your computer. - Offline, or GitHub doesn't answer within 15 seconds: nothing is shown, and the check is tried - again an hour later. + again an hour later (or at the next start, whichever comes first). - GitHub's rate limit for anonymous requests (60 an hour per address) is respected: when GitHub - says to wait, SolidCraft waits that long, Check now included. + says to wait, SolidCraft waits that long, Check now and the check at start included. - Turning off **Check for updates automatically** stops the checks; only **Check now** asks. - Setting the environment variable `SOLIDCRAFT_UPDATE_CHECK=0` turns all checks off, for example on managed machines. From 2e5b7b11e417b5a6ced4ee92403bcc985ba5c8d6 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 16 Oct 2026 04:08:04 +0000 Subject: [PATCH 60/92] Regenerate THIRD-PARTY-LICENSES.txt and docs/features.md [skip ci] --- docs/features.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/features.md b/docs/features.md index 11693a1e9..7b0495e3e 100644 --- a/docs/features.md +++ b/docs/features.md @@ -1,6 +1,6 @@ # Features -SolidCraft's commands by area, generated by `cargo xtask features` from the command registry (`solidcraft-cli commands`). **378 commands.** Planned (registered, not built yet): 3. 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`). **379 commands.** Planned (registered, not built yet): 3. 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 (103) @@ -247,7 +247,7 @@ SolidCraft's commands by area, generated by `cargo xtask features` from the comm | Break Link | `component.break_link` | – | | List Links | `component.links` | – | -## Assembly joints (14) +## Assembly joints (15) | Command | Id | Toolbar | |---|---|---| @@ -256,6 +256,7 @@ SolidCraft's commands by area, generated by `cargo xtask features` from the comm | 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 | From f98c5e350d0940c608342dc910a6d74ffe309e7c Mon Sep 17 00:00:00 2001 From: bherbruck Date: Fri, 16 Oct 2026 00:11:30 -0400 Subject: [PATCH 61/92] Shell: put shell_by_opening's doc comment back on it (#1588) Thanks @bherbruck. --- crates/kernel/src/polyhedron.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/kernel/src/polyhedron.rs b/crates/kernel/src/polyhedron.rs index 461da12ef..35e20477a 100644 --- a/crates/kernel/src/polyhedron.rs +++ b/crates/kernel/src/polyhedron.rs @@ -610,9 +610,6 @@ fn shell_opened(b: &Body, healed: &Body, open: &[Vec3], opened: &[usize], thickn } } -/// A shell made from the cavity with every face moved in by the thickness (open faces too), -/// joined with each open face's moved copy swept out through the body. No history: the -/// opening's walls, swept from the cavity's edges, come from nothing of `b`. /// The cavity with each open face pushed out (`cavity`), trimmed so that beyond an open face's /// plane it only reaches through the open face itself; `None` when it already does. /// @@ -690,6 +687,9 @@ fn opening_overreach(healed: &Body, cavity: &Body, opened: &[usize], thickness: Ok(Some(trimmed)) } +/// A shell made from the cavity with every face moved in by the thickness (open faces too), +/// joined with each open face's moved copy swept out through the body. No history: the +/// opening's walls, swept from the cavity's edges, come from nothing of `b`. fn shell_by_opening(b: &Body, opened: &[usize], thickness: f64, reach: f64) -> Result { let closed = offset_planar(b, |_, _| -thickness)?; let faces: Vec = closed.solid.face_iter().cloned().collect(); From c5b7009ce3075e74a25ad493ae73de8d0017f6fd Mon Sep 17 00:00:00 2001 From: "H. Conrad" <78785932+Ian-cmd-ops@users.noreply.github.com> Date: Thu, 15 Oct 2026 21:13:48 -0700 Subject: [PATCH 62/92] ci: nightly property tests with more cases (#1498) Thanks @Ian-cmd-ops. --- .config/nextest.toml | 2 + .github/workflows/ci.yml | 26 +++ CONTRIBUTING.md | 4 +- Cargo.lock | 76 +++++- crates/engine/tests/atomic_commands.rs | 102 ++++++++ crates/kernel/Cargo.toml | 3 + .../tests/boolean_props.proptest-regressions | 7 + crates/kernel/tests/boolean_props.rs | 220 ++++++++++++++++++ docs/book/src/dev/testing.md | 4 +- 9 files changed, 435 insertions(+), 9 deletions(-) create mode 100644 crates/engine/tests/atomic_commands.rs create mode 100644 crates/kernel/tests/boolean_props.proptest-regressions create mode 100644 crates/kernel/tests/boolean_props.rs diff --git a/.config/nextest.toml b/.config/nextest.toml index 341290690..d393c69be 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -16,6 +16,8 @@ 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) & binary(boolean_props)) + | (package(solidcraft-engine) & binary(atomic_commands)) | (package(solidcraft-ui-egui) & binary(scenarios) & test(=acceptance_sensor_enclosure)) ) """ diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 06a6aa063..5b6769121 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -317,6 +317,32 @@ jobs: cargo nextest run --archive-file tests.tar.zst --workspace-remap . --extract-to . --extract-overwrite \ --profile ci --success-output final --run-ignored only -E "binary(action_matrix) & test(=action_matrix_determinism)" + property-tests: + # The boolean property tests and the atomic command tests with many cases. Pull requests skip + # them (.config/nextest.toml); pushes to main run them with small defaults (8 cases, seeds 0..4). + name: Property tests (many cases) + needs: build-tests + if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' + runs-on: ubuntu-24.04 + timeout-minutes: 60 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: taiki-e/install-action@1168f6810a3cb30a3514bf5756a3b7f0422c6df8 # v2.87.28 + with: + tool: cargo-nextest + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: nextest-archive + - name: Boolean properties and atomic commands + # The defaults (8 cases, seeds 0..4) take 159 s and 802 s on a 2-core VM; four times the + # cases and twice the seeds are estimated at about 40 minutes there (not yet timed on CI). + env: + PROPTEST_CASES: "32" + ATOMIC_SEEDS: "0..8" + run: | + cargo nextest run --archive-file tests.tar.zst --workspace-remap . --extract-to . --extract-overwrite \ + --profile ci --ignore-default-filter --success-output final -E "binary(boolean_props) | binary(atomic_commands)" + doc-tests: name: Doc tests needs: changes diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index bd5be2309..095a61afa 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -180,8 +180,8 @@ Pull requests skip a few heavy tests (one to four minutes each), which run on ev `tests::robustness_goldens` (pull requests that touch `crates/kernel` run its `sample_*` part), `pattern_suppress_tests::enclosure_arc_extinction_keeps_a_real_sharp_inner_lip_after_resize_and_reopen`, `pattern_suppress_tests::enclosure_datums_follow_wall_height_and_board_depth_with_material_proofs`, - `cmd::plastic::tests::enclosure_snap_fit_follows_resized_front_wall` -- `solidcraft-kernel`: `tests::boolean_identity_on_tangent_primitives` + `cmd::plastic::tests::enclosure_snap_fit_follows_resized_front_wall`, the `atomic_commands` contract tests +- `solidcraft-kernel`: `tests::boolean_identity_on_tangent_primitives`, the `boolean_props` property tests - `solidcraft-ui-egui` scenarios: `acceptance_sensor_enclosure` **The action matrix** tries every ordinary action on every face, edge, vertex and body of a diff --git a/Cargo.lock b/Cargo.lock index d8602e2f4..4124950ca 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -805,6 +805,17 @@ dependencies = [ "serde", ] +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core 0.10.1", +] + [[package]] name = "chrono" version = "0.4.45" @@ -1665,6 +1676,7 @@ dependencies = [ "cfg-if", "libc", "r-efi 6.0.0", + "rand_core 0.10.1", ] [[package]] @@ -3260,6 +3272,22 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5" +[[package]] +name = "proptest" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0" +dependencies = [ + "bitflags 2.13.2", + "chacha20", + "core_detect", + "num-traits", + "rand 0.10.3", + "rand_xorshift", + "regex-syntax", + "unarray", +] + [[package]] name = "pxfm" version = "0.1.30" @@ -3310,7 +3338,17 @@ checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" dependencies = [ "libc", "rand_chacha", - "rand_core", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "getrandom 0.4.3", + "rand_core 0.10.1", ] [[package]] @@ -3320,7 +3358,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" dependencies = [ "ppv-lite86", - "rand_core", + "rand_core 0.6.4", ] [[package]] @@ -3332,6 +3370,21 @@ dependencies = [ "getrandom 0.2.17", ] +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_xorshift" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60aa6af80be32871323012e02e6e65f8a7cc7890931ae421d217ad8fe0df2ccf" +dependencies = [ + "rand_core 0.10.1", +] + [[package]] name = "range-alloc" version = "0.1.5" @@ -3423,6 +3476,12 @@ dependencies = [ "bitflags 2.13.2", ] +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + [[package]] name = "renderdoc-sys" version = "1.1.0" @@ -3669,7 +3728,7 @@ dependencies = [ "hkdf", "num", "once_cell", - "rand", + "rand 0.8.8", "serde", "sha2 0.10.9", "zbus 4.4.0", @@ -4122,6 +4181,7 @@ name = "solidcraft-kernel" version = "0.13.1" dependencies = [ "log", + "proptest", "rayon", "serde", "serde_json", @@ -4508,7 +4568,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "97a31fe98d5a0589ad20576260e214af23dea21a8d125da81ad3bbcb666f411f" dependencies = [ "getrandom 0.2.17", - "rand", + "rand 0.8.8", "thiserror 1.0.69", "truck-base", "truck-derivers", @@ -4649,6 +4709,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "unarray" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" + [[package]] name = "unicode-general-category" version = "1.1.0" @@ -5739,7 +5805,7 @@ dependencies = [ "hex", "nix", "ordered-stream", - "rand", + "rand 0.8.8", "serde", "serde_repr", "sha1 0.10.7", diff --git a/crates/engine/tests/atomic_commands.rs b/crates/engine/tests/atomic_commands.rs new file mode 100644 index 000000000..9912bb162 --- /dev/null +++ b/crates/engine/tests/atomic_commands.rs @@ -0,0 +1,102 @@ +//! Atomic command tests: the engine's transaction contract, checked on random designs. +//! +//! The contract (crates/engine/src/lib.rs, `Session::execute`): +//! 1. A command that returns an error leaves the design exactly as it was. +//! 2. Undo back to the start gives the empty design. Redo back to the end gives the final design. +//! 3. The same commands give the same design every time (no hidden state between runs). +//! +//! The designs come from the engine's own fuzzer (`fuzz::run`), so these tests cover every +//! command it can generate: sketches, extrudes, revolves, holes, patterns, fillets, shells. +//! +//! Seeds: `ATOMIC_SEEDS` (default 0..4). Pull requests skip this file (.config/nextest.toml); pushes +//! to main run it, and the nightly `property-tests` job uses more seeds. A long local run: +//! `ATOMIC_SEEDS=0..100`. + +use solidcraft_doc::Document; +use solidcraft_engine::{Session, fuzz}; + +fn seeds() -> std::ops::Range { + let s = std::env::var("ATOMIC_SEEDS").unwrap_or_else(|_| "0..4".into()); + let (a, b) = s.split_once("..").expect("ATOMIC_SEEDS looks like 0..4"); + a.parse().unwrap()..b.parse().unwrap() +} + +/// The commands a seed's design runs, flattened. +fn commands(seed: u64) -> Vec<(String, serde_json::Value)> { + fuzz::run(seed, 8).steps.into_iter().flat_map(|s| s.commands).collect() +} + +/// Run the commands. For each failed command, check the design did not change. +/// Returns the session and a list of contract breaks. +fn replay(seed: u64, cmds: &[(String, serde_json::Value)]) -> (Session, Vec) { + let mut s = Session::default(); + let mut broken = Vec::new(); + for (i, (id, p)) in cmds.iter().enumerate() { + let before: Document = (*s.doc).clone(); + if let Err(e) = s.execute(id, p) + && *s.doc != before + { + broken.push(format!("seed {seed} cmd {i} `{id}` failed ({e}) but changed the design")); + } + } + (s, broken) +} + +#[test] +fn failed_commands_leave_the_design_unchanged() { + let mut broken = Vec::new(); + for seed in seeds() { + broken.extend(replay(seed, &commands(seed)).1); + } + assert!(broken.is_empty(), "{} contract breaks:\n{}", broken.len(), broken.join("\n")); +} + +#[test] +fn undo_all_then_redo_all_round_trips() { + let empty = (*Session::default().doc).clone(); + let mut broken = Vec::new(); + for seed in seeds() { + let (mut s, _) = replay(seed, &commands(seed)); + let end: Document = (*s.doc).clone(); + let mut n = 0; + while s.execute("edit.undo", &serde_json::Value::Null).is_ok() { + n += 1; + assert!(n < 10_000, "seed {seed}: undo never runs out"); + } + if *s.doc != empty { + broken.push(format!("seed {seed}: after {n} undos the design is not the empty design")); + } + for _ in 0..n { + if let Err(e) = s.execute("edit.redo", &serde_json::Value::Null) { + broken.push(format!("seed {seed}: redo failed: {e}")); + break; + } + } + if *s.doc != end { + broken.push(format!("seed {seed}: after {n} redos the design is not the design before undo")); + } + } + assert!(broken.is_empty(), "{} contract breaks:\n{}", broken.len(), broken.join("\n")); +} + +#[test] +fn same_commands_same_design() { + let mut broken = Vec::new(); + for seed in seeds() { + let cmds = commands(seed); + let (a, _) = replay(seed, &cmds); + let (b, _) = replay(seed, &cmds); + if *a.doc != *b.doc { + broken.push(format!("seed {seed}: two runs of the same commands gave different designs")); + } + let (va, vb) = (volume(&a), volume(&b)); + if va.to_bits() != vb.to_bits() { + broken.push(format!("seed {seed}: two runs gave volumes {va} and {vb}")); + } + } + assert!(broken.is_empty(), "{} contract breaks:\n{}", broken.len(), broken.join("\n")); +} + +fn volume(s: &Session) -> f64 { + s.model.state().bodies.iter().filter_map(|b| solidcraft_kernel::measure(&b.body).ok()).map(|m| m.volume).sum() +} diff --git a/crates/kernel/Cargo.toml b/crates/kernel/Cargo.toml index a728a365c..1ab5837c3 100644 --- a/crates/kernel/Cargo.toml +++ b/crates/kernel/Cargo.toml @@ -23,3 +23,6 @@ spade = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] rayon = { workspace = true } + +[dev-dependencies] +proptest = { version = "1", default-features = false, features = ["std"] } diff --git a/crates/kernel/tests/boolean_props.proptest-regressions b/crates/kernel/tests/boolean_props.proptest-regressions new file mode 100644 index 000000000..83c0147e1 --- /dev/null +++ b/crates/kernel/tests/boolean_props.proptest-regressions @@ -0,0 +1,7 @@ +# Seeds for failure cases proptest has generated in the past. It is +# automatically read and these particular cases re-run before any +# novel cases are generated. +# +# It is recommended to check this file in to source control so that +# everyone who runs the test benefits from these saved cases. +cc 739d5cbd9e471e0ff65bc2b7c1b9a323c2e769939c73def2e74fb17b0536c1d0 # shrinks to a = [0.0, 2.5, 30.0], sa = [22.5, 5.0, 5.0], b = [22.5, 7.5, 15.0], sb = [5.0, 5.0, 17.5] diff --git a/crates/kernel/tests/boolean_props.rs b/crates/kernel/tests/boolean_props.rs new file mode 100644 index 000000000..fadecae79 --- /dev/null +++ b/crates/kernel/tests/boolean_props.rs @@ -0,0 +1,220 @@ +//! Property tests for the kernel boolean (`boolean`, `measure`, `transform`). +//! +//! Each test states one invariant that every correct B-rep boolean holds. proptest picks the +//! inputs, and when a case fails it shrinks the inputs to a small case that still fails. Paste +//! that case into a normal `#[test]` as a regression test. +//! +//! Case count: `PROPTEST_CASES` (default 8). Pull requests skip this file (.config/nextest.toml); +//! pushes to main run it, and the nightly `property-tests` job uses more cases. A long local run: +//! `PROPTEST_CASES=2000 cargo test -p solidcraft-kernel --test boolean_props`. +//! proptest saves every failing seed in `tests/boolean_props.proptest-regressions`. Commit it. + +use proptest::prelude::*; +use solidcraft_geom::Vec3; +use solidcraft_kernel::{Body, BoolOp, boolean, box_solid, cylinder, measure, sphere, transform}; + +/// Relative volume tolerance. The same 0.2 % that `fuzz::boolean_case` uses. +const REL: f64 = 2e-3; + +#[derive(Clone, Debug)] +enum Prim { + Box { at: [f64; 3], size: [f64; 3] }, + Cyl { at: [f64; 3], axis: usize, r: f64, h: f64 }, + Sph { at: [f64; 3], r: f64 }, +} + +impl Prim { + fn body(&self) -> Body { + let v = |p: [f64; 3]| Vec3::new(p[0], p[1], p[2]); + let axes = [Vec3::X, Vec3::Y, Vec3::Z]; + match *self { + Prim::Box { at, size } => box_solid(v(at), v([at[0] + size[0], at[1] + size[1], at[2] + size[2]])), + Prim::Cyl { at, axis, r, h } => cylinder(v(at), axes[axis], r, h), + Prim::Sph { at, r } => sphere(v(at), r), + } + .expect("a primitive with positive size must build") + } +} + +/// Coordinates on a 2.5 mm grid: coincident faces, shared edges and tangencies come up often. +/// These are the cases that break B-rep booleans. +fn grid() -> impl Strategy + Clone { + (0u32..=12).prop_map(|i| i as f64 * 2.5) +} +/// Size on the grid, never zero. +fn grid_size() -> impl Strategy + Clone { + (2u32..=12).prop_map(|i| i as f64 * 2.5) +} +/// Generic coordinates: almost never coincident. A failure here is a plain bug, not an edge case. +fn free() -> impl Strategy + Clone { + 0.0f64..30.0 +} +fn free_size() -> impl Strategy + Clone { + 3.0f64..30.0 +} + +fn prim(c: impl Strategy + Clone, s: impl Strategy + Clone) -> impl Strategy { + let p = [c.clone(), c.clone(), c]; + prop_oneof![ + 5 => (p.clone(), [s.clone(), s.clone(), s.clone()]).prop_map(|(at, size)| Prim::Box { at, size }), + 3 => (p.clone(), 0usize..3, s.clone(), s.clone()).prop_map(|(at, axis, r, h)| Prim::Cyl { at, axis, r: r / 2.0, h }), + 2 => (p, s).prop_map(|(at, r)| Prim::Sph { at, r: r / 2.0 }), + ] +} +fn grid_prim() -> impl Strategy { + prim(grid(), grid_size()) +} +fn free_prim() -> impl Strategy { + prim(free(), free_size()) +} + +/// Volume of a boolean result (an empty result has volume 0). Also fails the case when the +/// result is not a sound solid. +fn run(a: &Body, b: &Body, op: BoolOp) -> Result { + let r = boolean(a, b, op).map_err(|e| TestCaseError::fail(format!("{op:?} returned an error: {e}")))?; + match r { + None => Ok(0.0), + Some(body) => { + let bad = body.validity(); + prop_assert!(bad.is_empty(), "{op:?} result is not a sound solid: {}", bad.join("; ")); + Ok(measure(&body).map_err(|e| TestCaseError::fail(format!("measure: {e}")))?.volume) + } + } +} +fn vol(b: &Body) -> f64 { + measure(b).expect("measure a primitive").volume +} +fn close(x: f64, y: f64, scale: f64) -> bool { + (x - y).abs() <= REL * scale.max(1e-9) +} + +/// Inclusion-exclusion: V(A∪B) + V(A∩B) = V(A) + V(B), and V(A−B) = V(A) − V(A∩B). +fn identity(a: &Prim, b: &Prim) -> Result<(), TestCaseError> { + let (ba, bb) = (a.body(), b.body()); + let (va, vb) = (vol(&ba), vol(&bb)); + let (vu, vi, vc) = (run(&ba, &bb, BoolOp::Union)?, run(&ba, &bb, BoolOp::Intersect)?, run(&ba, &bb, BoolOp::Cut)?); + prop_assert!(close(vu + vi, va + vb, va + vb), "union+intersect {} != A+B {} (A {va:.3}, B {vb:.3}, U {vu:.3}, I {vi:.3})", vu + vi, va + vb); + prop_assert!(close(vc, va - vi, va + vb), "cut {vc:.3} != A-I {:.3}", va - vi); + 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. + let cases = std::env::var("PROPTEST_CASES").ok().and_then(|s| s.parse().ok()).unwrap_or(default); + ProptestConfig { cases, max_shrink_iters: 200, ..ProptestConfig::default() } +} + +proptest! { + #![proptest_config(cfg(8))] + + /// Generic placement: these must all pass. A failure is a real bug. + #[test] + fn identity_generic(a in free_prim(), b in free_prim()) { + identity(&a, &b)?; + } + + /// Grid placement: coincident and tangent faces. The hard cases. + #[test] + fn identity_on_grid(a in grid_prim(), b in grid_prim()) { + identity(&a, &b)?; + } + + /// Union and intersection do not depend on operand order. + #[test] + fn commutative(a in grid_prim(), b in grid_prim()) { + let (ba, bb) = (a.body(), b.body()); + let s = vol(&ba) + vol(&bb); + for op in [BoolOp::Union, BoolOp::Intersect] { + let (ab, ba_) = (run(&ba, &bb, op)?, run(&bb, &ba, op)?); + prop_assert!(close(ab, ba_, s), "{op:?}: A,B gives {ab:.4} but B,A gives {ba_:.4}"); + } + } + + /// Moving both operands together does not change the answer. A large offset exposes + /// absolute tolerances (1e-6, 1e-9 literals) that should scale with the model. + #[test] + fn translation_invariant(a in grid_prim(), b in grid_prim(), off in prop::sample::select(vec![0.0, 1.0e3, 1.0e5])) { + let (ba, bb) = (a.body(), b.body()); + let t = Vec3::new(off, -off * 0.7, off * 0.3); + let mv = |x: &Body| transform(x, t, Vec3::ZERO, Vec3::Z, 0.0).expect("translate"); + let (ta, tb) = (mv(&ba), mv(&bb)); + let s = vol(&ba) + vol(&bb); + for op in [BoolOp::Union, BoolOp::Intersect, BoolOp::Cut] { + let (here, there) = (run(&ba, &bb, op)?, run(&ta, &tb, op)?); + prop_assert!(close(here, there, s), "{op:?} at origin {here:.4}, moved by {off} gives {there:.4}"); + } + } + + /// Scaling the whole problem scales volume by k³. Small parts (0.05x) and large parts + /// (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)? / (k * k * k)); + prop_assert!(close(one, big, s), "{op:?} at scale 1 gives {one:.4}, at scale {k} gives {big:.4} (normalised)"); + } + } + + /// A∪A = A, A∩A = A, A−A = nothing. + #[test] + fn self_operations(a in grid_prim()) { + let ba = a.body(); + let va = vol(&ba); + prop_assert!(close(run(&ba, &ba, BoolOp::Union)?, va, va), "A∪A != A"); + prop_assert!(close(run(&ba, &ba, BoolOp::Intersect)?, va, va), "A∩A != A"); + prop_assert!(run(&ba, &ba, BoolOp::Cut)? <= REL * va, "A−A is not empty"); + } + + /// The same inputs give the same output, twice in a row. The boolean keeps thread-local + /// state (the nudge guard); this catches state that leaks from one call to the next. + #[test] + fn deterministic(a in grid_prim(), b in grid_prim()) { + let (ba, bb) = (a.body(), b.body()); + for op in [BoolOp::Union, BoolOp::Intersect, BoolOp::Cut] { + let m = |r: Option| r.map(|x| { let m = measure(&x).unwrap(); (m.volume.to_bits(), m.faces, m.edges) }); + let first = boolean(&ba, &bb, op).ok().map(m); + let second = boolean(&ba, &bb, op).ok().map(m); + prop_assert_eq!(first, second, "{:?} gave two different answers for the same input", op); + } + } + + /// Two boxes whose overlap is known exactly (closed form, no tessellation guesswork). + #[test] + fn box_box_exact(a in [grid(), grid(), grid()], sa in [grid_size(), grid_size(), grid_size()], + b in [grid(), grid(), grid()], sb in [grid_size(), grid_size(), grid_size()]) { + let overlap: f64 = (0..3).map(|i| ((a[i] + sa[i]).min(b[i] + sb[i]) - a[i].max(b[i])).max(0.0)).product(); + let (pa, pb) = (Prim::Box { at: a, size: sa }, Prim::Box { at: b, size: sb }); + let (ba, bb) = (pa.body(), pb.body()); + let (va, vb) = (sa.iter().product::(), sb.iter().product::()); + let s = va + vb; + // Per axis: the gap between the boxes (<0 overlap, 0 touch, >0 apart). + let gap: Vec = (0..3).map(|i| a[i].max(b[i]) - (a[i] + sa[i]).min(b[i] + sb[i])).collect(); + // Touching along an edge or at a corner only: a union there is not a manifold solid. + // The kernel refuses it on purpose ("zero-thickness edge contact"). Allowed, as an error. + let edge_only = gap.iter().all(|g| *g <= 0.0) && gap.iter().filter(|g| **g == 0.0).count() >= 2; + prop_assert!(close(run(&ba, &bb, BoolOp::Intersect)?, overlap, s), "intersect != closed-form overlap {overlap}"); + prop_assert!(close(run(&ba, &bb, BoolOp::Cut)?, va - overlap, s), "cut != closed form {}", va - overlap); + match run(&ba, &bb, BoolOp::Union) { + Err(_) if edge_only => {} + r => prop_assert!(close(r?, s - overlap, s), "union != closed form {}", s - overlap), + } + } + + /// Two boxes that share part of a face must fuse into one solid. This is the most common + /// join in real parts (a boss on a plate). + #[test] + fn face_touching_boxes_fuse(x in grid(), y in grid(), w in grid_size(), d in grid_size(), h in grid_size()) { + let plate = Prim::Box { at: [0.0, 0.0, 0.0], size: [30.0, 30.0, 5.0] }.body(); + let boss = Prim::Box { at: [x.min(27.5), y.min(27.5), 5.0], size: [w, d, h] }.body(); + let (vp, vb) = (vol(&plate), vol(&boss)); + prop_assert!(close(run(&plate, &boss, BoolOp::Union)?, vp + vb, vp + vb), "plate + boss lost or gained volume"); + } +} diff --git a/docs/book/src/dev/testing.md b/docs/book/src/dev/testing.md index aa458bea0..105160b5b 100644 --- a/docs/book/src/dev/testing.md +++ b/docs/book/src/dev/testing.md @@ -80,8 +80,8 @@ Pull requests skip a few heavy tests (each takes one to four minutes); they run `tests::robustness_goldens` (pull requests that touch `crates/kernel` run its `sample_*` part), `pattern_suppress_tests::enclosure_arc_extinction_keeps_a_real_sharp_inner_lip_after_resize_and_reopen`, `pattern_suppress_tests::enclosure_datums_follow_wall_height_and_board_depth_with_material_proofs`, - `cmd::plastic::tests::enclosure_snap_fit_follows_resized_front_wall` -- `solidcraft-kernel`: `tests::boolean_identity_on_tangent_primitives` + `cmd::plastic::tests::enclosure_snap_fit_follows_resized_front_wall`, the `atomic_commands` contract tests +- `solidcraft-kernel`: `tests::boolean_identity_on_tangent_primitives`, the `boolean_props` property tests - `solidcraft-ui-egui` scenarios: `acceptance_sensor_enclosure` The **action matrix** (`apps/solidcraft-cli/tests/action_matrix.rs`) tries every ordinary action From 8f5073ff14938a2a1cfdaff98bec33246b048aaf Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 16 Oct 2026 04:18:59 +0000 Subject: [PATCH 63/92] Regenerate THIRD-PARTY-LICENSES.txt and docs/features.md [skip ci] --- THIRD-PARTY-LICENSES.txt | 49 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 47 insertions(+), 2 deletions(-) diff --git a/THIRD-PARTY-LICENSES.txt b/THIRD-PARTY-LICENSES.txt index 86cbc1afb..6254c85ec 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 544 crates below. +SolidCraft (the desktop app, solidcraft-cli and the web app) is built from the 545 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. @@ -316,6 +316,7 @@ r-efi 5.3.0 (MIT OR Apache-2.0 OR LGPL-2.1-or-later) r-efi 6.0.0 (MIT OR Apache-2.0 OR LGPL-2.1-or-later) rand 0.8.8 (MIT OR Apache-2.0) rand_chacha 0.3.1 (MIT OR Apache-2.0) +rand_core 0.10.1 (MIT OR Apache-2.0) rand_core 0.6.4 (MIT OR Apache-2.0) range-alloc 0.1.5 (MIT OR Apache-2.0) raw-window-handle 0.6.2 (MIT OR Apache-2.0 OR Zlib) @@ -10462,7 +10463,51 @@ The Rand project includes code from the Rust project published under these same licenses. ================================================================================ -rand_core 0.6.4 +rand_core 0.10.1 +================================================================================ + +Copyright (c) 2018-2026 The Rand Project Developers + +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. + +================================================================================ +rand_core 0.10.1 +================================================================================ + +Copyrights in the Rand project are retained by their contributors. No +copyright assignment is required to contribute to the Rand project. + +For full authorship information, see the version control history. + +Except as otherwise noted (below and/or in individual files), Rand is +licensed under the Apache License, Version 2.0 or + or the MIT license + or , at your option. + +================================================================================ +rand_core 0.10.1, rand_core 0.6.4 ================================================================================ Apache License From ac3a25fb5be590a7251176bd1ec1a228917d6c68 Mon Sep 17 00:00:00 2001 From: DuBearte <130190089+DuBearte@users.noreply.github.com> Date: Fri, 16 Oct 2026 00:27:12 -0400 Subject: [PATCH 64/92] View keys: arrows turn the view, Ctrl+arrows pan, Ctrl+8 looks at the selection (#1541) (#1585) Thanks @DuBearte. --- crates/engine/src/cmd/view_navigation.rs | 55 ++++++++++++++-- crates/ui-egui/src/keymap.rs | 14 ++++ crates/ui-egui/src/navigation.rs | 82 ++++++++++++++++++++++++ crates/ui-egui/src/toolbar.rs | 3 + docs/book/src/guide/shortcuts.md | 3 + 5 files changed, 151 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/view_navigation.rs b/crates/engine/src/cmd/view_navigation.rs index ad5f3a4f7..258c0b143 100644 --- a/crates/engine/src/cmd/view_navigation.rs +++ b/crates/engine/src/cmd/view_navigation.rs @@ -10,7 +10,7 @@ pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("view.navigate", "Navig .icon("orbit") .noundo() .doc_only() - .params("camera: Camera; direction?: [x,y,z] in the camera's up-axis frame; or action: left|right|up|down|clockwise|counterclockwise|home|fit; or motion: pan|orbit|zoom, delta?: [dx,dy] (pixels, each ±10000), viewport?: [width,height] (1..1000000, required for pan or pivot), pivot?: [x,y,z], factor?: 0.05..20 (required for zoom), anchor?: [x,y,z] → camera, fit, continuous?")]; + .params("camera: Camera; direction?: [x,y,z] in the camera's up-axis frame; or action: left|right|up|down|clockwise|counterclockwise|home|fit, degrees?: 0..180 (how far left|right|up|down turn; default 90); or motion: pan|orbit|zoom, delta?: [dx,dy] (pixels, each ±10000), viewport?: [width,height] (1..1000000, required for pan or pivot), pivot?: [x,y,z], factor?: 0.05..20 (required for zoom), anchor?: [x,y,z] → camera, fit, continuous?")]; fn navigate(_s: &mut Session, p: &Value) -> Result { let cmd = "view.navigate"; @@ -41,12 +41,23 @@ fn navigate(_s: &mut Session, p: &Value) -> Result { } } else { use std::f64::consts::FRAC_PI_2; - let (r, u, _) = cam.basis(); + let (r, u, b) = cam.basis(); + // Left, right, up and down turn the view a quarter turn (the navigation cube's arrows), + // or `degrees` (the arrow keys' 15° steps, #1541). + let (sin, cos) = match p.get("degrees") { + None => (1.0, 0.0), + Some(d) => d + .as_f64() + .filter(|d| d.is_finite() && *d > 0.0 && *d <= 180.0) + .map(|d| if d == 90.0 { (1.0, 0.0) } else { d.to_radians().sin_cos() }) + .ok_or_else(|| bad(cmd, "degrees must be a number above 0 and at most 180"))?, + }; + let turn = |toward: solidcraft_geom::Vec3| cam.looking_from(b * cos + toward * sin); match p.get("action").and_then(Value::as_str) { - Some("left") => cam = cam.looking_from(-r), - Some("right") => cam = cam.looking_from(r), - Some("up") => cam = cam.looking_from(u), - Some("down") => cam = cam.looking_from(-u), + Some("left") => cam = turn(-r), + Some("right") => cam = turn(r), + Some("up") => cam = turn(u), + Some("down") => cam = turn(-u), Some("clockwise") => cam.roll = (cam.roll + FRAC_PI_2).rem_euclid(std::f64::consts::TAU), Some("counterclockwise") => cam.roll = (cam.roll - FRAC_PI_2).rem_euclid(std::f64::consts::TAU), Some("home") => { @@ -131,6 +142,38 @@ mod tests { use solidcraft_geom::Vec3; use solidcraft_render::UpAxis; + /// #1541: left, right, up and down turn a quarter turn, or `degrees` (the arrow keys' 15°). + #[test] + fn turns_take_degrees_and_default_to_a_quarter_turn() { + let mut s = Session::default(); + let cam = Camera { yaw: 0.0, pitch: 0.0, distance: 100.0, ..Default::default() }; + let mut turn = |action: &str, degrees: Option| -> Result { + let mut params = json!({"camera": cam, "action": action}); + if let Some(d) = degrees { + params["degrees"] = d; + } + let result = s.execute("view.navigate", ¶ms)?; + Ok(serde_json::from_value(result["camera"].clone()).unwrap()) + }; + let close = |a: f64, b: f64| (a - b).abs() < 1e-9; + // A quarter turn as before, given or not. + let quarter = turn("left", None).unwrap(); + assert_eq!(turn("left", Some(json!(90))).unwrap(), quarter); + assert!(close((quarter.yaw - cam.yaw).abs(), std::f64::consts::FRAC_PI_2)); + // 15° each way, about the up axis or over the top. + for (action, yaw, pitch) in [("left", -15.0, 0.0), ("right", 15.0, 0.0), ("up", 0.0, 15.0), ("down", 0.0, -15.0)] { + let to = turn(action, Some(json!(15))).unwrap(); + assert!(close(to.yaw.abs(), f64::to_radians(yaw).abs()), "{action}: yaw {}", to.yaw); + assert!(close(to.pitch, f64::to_radians(pitch)), "{action}: pitch {}", to.pitch); + assert_eq!((to.target, to.distance), (cam.target, cam.distance)); + } + // Left and right turn opposite ways. + assert!(close(turn("left", Some(json!(15))).unwrap().yaw, -turn("right", Some(json!(15))).unwrap().yaw)); + for bad in [json!(0), json!(-15), json!(181), json!(f64::NAN.to_string()), json!("15"), json!(null)] { + assert!(turn("left", Some(bad.clone())).is_err(), "{bad}"); + } + } + #[test] fn continuous_navigation_moves_the_camera_without_editing_the_design() { let mut s = Session::default(); diff --git a/crates/ui-egui/src/keymap.rs b/crates/ui-egui/src/keymap.rs index 11dc230e5..abb381034 100644 --- a/crates/ui-egui/src/keymap.rs +++ b/crates/ui-egui/src/keymap.rs @@ -31,6 +31,20 @@ pub const RESERVED: &[&str] = &[ "Ctrl+C", "Ctrl+X", "Ctrl+V", + // View keys (`navigation::view_key`). + "Left", + "Right", + "Up", + "Down", + "Shift+Left", + "Shift+Right", + "Shift+Up", + "Shift+Down", + "Ctrl+Left", + "Ctrl+Right", + "Ctrl+Up", + "Ctrl+Down", + "Ctrl+8", ]; #[derive(Default)] diff --git a/crates/ui-egui/src/navigation.rs b/crates/ui-egui/src/navigation.rs index 866a89c40..7f401cf9c 100644 --- a/crates/ui-egui/src/navigation.rs +++ b/crates/ui-egui/src/navigation.rs @@ -181,6 +181,45 @@ pub(crate) fn modifier_motion( }) } +/// View keys (#1541): the arrows turn the view 15° (with Shift a quarter turn, as the navigation +/// cube's arrows), Ctrl+arrows pan it a tenth of the view, and Ctrl+8 looks straight at the +/// selected face, plane or sketch. Not while a menu, the command box or a focused widget has the +/// arrows. Returns whether the key was used. +pub(crate) fn view_key(app: &mut SolveApp, ctx: &egui::Context, key: egui::Key, mods: egui::Modifiers) -> bool { + use egui::Key; + let menu_open = egui::Popup::is_any_open(ctx) + || app.viewport.context_menu.is_some() + || app.ui.palette_open + || ctx.memory(|m| m.focused().is_some()) + || ctx.data(|d| d.get_temp::(egui::Id::new("sc_panel_open")).is_some()); + let ctrl = mods.command || mods.ctrl; + if mods.alt || menu_open { + return false; + } + if key == Key::Num8 && ctrl && !mods.shift { + crate::viewport::look_at_selection(app); + return true; + } + let (action, dx, dy) = match key { + Key::ArrowLeft => ("left", -1.0, 0.0), + Key::ArrowRight => ("right", 1.0, 0.0), + Key::ArrowUp => ("up", 0.0, -1.0), + Key::ArrowDown => ("down", 0.0, 1.0), + _ => return false, + }; + if ctrl { + // The model moves with the arrow, as it does under a pan drag. + if let Some(rect) = app.viewport.rect { + let step = rect.height() * 0.1; + camera_motion(app, rect, json!({"motion": "pan", "delta": [dx * step, dy * step]})); + } + } else { + let degrees = if mods.shift { 90.0 } else { 15.0 }; + let _ = app.run("view.navigate", json!({"camera": app.cam, "action": action, "degrees": degrees})); + } + true +} + /// Continuous camera changes use the same JSON command as programmatic callers. pub(crate) fn camera_motion(app: &mut SolveApp, rect: Rect, mut params: serde_json::Value) { let stored_fov = app.cam.fov; @@ -835,3 +874,46 @@ mod tests { assert_eq!(app.cam, still); } } + +#[cfg(test)] +mod view_key_tests { + use crate::scenario::Harness; + use serde_json::json; + + fn turned(h: &mut Harness, key: serde_json::Value) -> (f64, f64) { + let before = h.app.cam; + h.step(&key).unwrap(); + h.frames(2); + (h.app.cam.yaw - before.yaw, h.app.cam.pitch - before.pitch) + } + + /// #1541: the arrows turn the view 15°, Shift+arrows a quarter turn, Ctrl+arrows pan, and none + /// of them is a shortcut a command can take. + #[test] + fn arrow_keys_turn_and_pan_the_view() { + let mut h = Harness::new(); + h.app.preferences.look_at_anim = false; + h.app.run("solid.box", json!({"length": 10, "width": 10, "height": 10})).unwrap(); + h.step(&json!({"call": "ui.view", "params": {"view": "front"}})).unwrap(); + h.frames(3); + let close = |a: f64, b: f64| (a.abs() - b.to_radians()).abs() < 1e-6; + let (yaw, pitch) = turned(&mut h, json!({"key": "ArrowLeft"})); + assert!(close(yaw, 15.0) && close(pitch, 0.0), "Left turns 15°: {yaw} {pitch}"); + let (yaw, pitch) = turned(&mut h, json!({"key": "ArrowUp"})); + assert!(close(yaw, 0.0) && close(pitch, 15.0), "Up turns 15° over: {yaw} {pitch}"); + let (yaw, _) = turned(&mut h, json!({"key": "ArrowRight", "shift": true})); + assert!(close(yaw, 90.0), "Shift+Right is a quarter turn: {yaw}"); + let (before, angles) = (h.app.cam.target, (h.app.cam.yaw, h.app.cam.pitch)); + h.step(&json!({"key": "ArrowRight", "cmd": true})).unwrap(); + h.frames(2); + assert_ne!(h.app.cam.target, before, "Ctrl+Right pans"); + assert_eq!((h.app.cam.yaw, h.app.cam.pitch), angles, "and does not turn"); + for k in [egui::Key::ArrowLeft, egui::Key::ArrowRight, egui::Key::ArrowUp, egui::Key::ArrowDown] { + for mods in [egui::Modifiers::NONE, egui::Modifiers::SHIFT, egui::Modifiers::COMMAND] { + let name = crate::keymap::key_name(k, mods); + assert!(crate::keymap::RESERVED.contains(&name.as_str()), "{name} must be reserved"); + } + } + assert!(crate::keymap::RESERVED.contains(&crate::keymap::key_name(egui::Key::Num8, egui::Modifiers::COMMAND).as_str())); + } +} diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 8407fc223..ffc53d8ca 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -1305,6 +1305,9 @@ pub fn shortcuts(app: &mut SolveApp, ctx: &egui::Context) { } for k in keys { use egui::Key; + if shown && crate::navigation::view_key(app, ctx, k, mods) { + continue; + } if mods.command { match k { Key::N => crate::documents::new_design(app), diff --git a/docs/book/src/guide/shortcuts.md b/docs/book/src/guide/shortcuts.md index babc08fdd..9b937313b 100644 --- a/docs/book/src/guide/shortcuts.md +++ b/docs/book/src/guide/shortcuts.md @@ -24,6 +24,9 @@ Keys handled by the window itself: | V | show or hide the selected bodies, sketches and planes | | F2 | rename the selected browser or timeline item | | F6 | fit the view to the model | +| ← → ↑ ↓ | turn the view 15° (with Shift, a quarter turn) | +| Ctrl+← → ↑ ↓ | pan the view | +| Ctrl+8 | look straight at the selected face, plane or sketch | | Esc | cancel the running command, or clear the selection | While a value box has the keyboard (a dimension being added, a dialog field), keys type into From f91103c51dae8d81ca3941938a1b27330f7859df Mon Sep 17 00:00:00 2001 From: DuBearte <130190089+DuBearte@users.noreply.github.com> Date: Fri, 16 Oct 2026 00:27:19 -0400 Subject: [PATCH 65/92] Viewport: the grid faces side views (#1470) (#1583) Thanks @DuBearte. --- crates/engine/src/view.rs | 28 +++++++++++++++++---- crates/ui-egui/src/viewport.rs | 45 ++++++++++++++++++++++++++++++---- 2 files changed, 63 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/view.rs b/crates/engine/src/view.rs index 8a889ea1b..e27e50272 100644 --- a/crates/engine/src/view.rs +++ b/crates/engine/src/view.rs @@ -131,6 +131,22 @@ pub fn visible_bounds(s: &Session, sketches: bool) -> Aabb3 { b } +/// The two axes (in the camera's Z-up frame) of the plane the grid lies in, for a view whose +/// direction toward the eye is `back` (in that frame). The ground (frame XY) unless it is seen +/// nearly edge-on, as in the Front or Right view; then the upright origin plane that faces the +/// view more, so the grid stays visible (#1470). +pub fn grid_plane(back: Vec3) -> (Vec3, Vec3) { + // About 11.5° above or below the ground. + const EDGE_ON: f64 = 0.2; + if back.z.abs() >= EDGE_ON || !back.z.is_finite() { + (Vec3::X, Vec3::Y) + } else if back.y.abs() >= back.x.abs() { + (Vec3::X, Vec3::Z) + } else { + (Vec3::Y, Vec3::Z) + } +} + /// Grid spacing (minor, major) for a view of the given half height. pub fn grid_step(half_height: f64) -> (f64, f64) { let raw = (half_height / 10.0).max(1e-3); @@ -374,13 +390,15 @@ fn build_scene( }; let b = bounds(s); sc.radius = (b.diagonal() * 0.5).max(cam.half_height()).max(10.0) + b.center().dist(cam.target); - // Grid on the ground plane (XY with Z up, XZ with Y up), drawn under the model as in the - // viewport. + // Grid on the ground plane (XY with Z up, XZ with Y up), or the upright origin plane facing + // a view that sees the ground edge-on ([`grid_plane`]), drawn under the model as in the viewport. 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); - let c = Vec3::new((tf.x / major).round() * major, (tf.y / major).round() * major, 0.0); + let (u, v) = grid_plane(cam.to_frame(cam.back())); + 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); let n = ((ext / minor) as i64).clamp(1, 400); for i in -n..=n { @@ -389,8 +407,8 @@ fn build_scene( let col = if major_line { p.grid_major } else { p.grid }; // The viewport's widths (pixels). let width = if major_line { 1.0 } else { 0.7 }; - sc.grid.push(SceneLine { points: vec![w(c + Vec3::new(t, -ext, 0.0)), w(c + Vec3::new(t, ext, 0.0))], color: col, width, on_top: false }); - sc.grid.push(SceneLine { points: vec![w(c + Vec3::new(-ext, t, 0.0)), w(c + Vec3::new(ext, t, 0.0))], color: col, width, on_top: false }); + sc.grid.push(SceneLine { points: vec![w(c + u * t - v * ext), w(c + u * t + v * ext)], color: col, width, on_top: false }); + sc.grid.push(SceneLine { points: vec![w(c - u * ext + v * t), w(c + u * ext + v * t)], color: col, width, on_top: false }); } } // The origin's axes, each unless hidden one by one (`browser.visibility`), as in the viewport. diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 2bcc6464a..267a3bc05 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -7,7 +7,7 @@ use solidcraft_engine::Sel; use solidcraft_engine::geom::{Vec2, Vec3}; use solidcraft_engine::render::{Camera, Mat4, Rgb}; use solidcraft_engine::sketch::CurveKind; -use solidcraft_engine::view::{colors, grid_step, sketch_lines_with_sampler}; +use solidcraft_engine::view::{colors, grid_plane, grid_step, sketch_lines_with_sampler}; use std::hash::{Hash, Hasher}; use crate::gpu::{Frame, GpuScene, GpuTarget, SceneSlot, ViewportCallback}; @@ -696,9 +696,12 @@ fn build_sketch_scene(app: &SolveApp, proj: &Proj) -> GpuScene { if 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). + // 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); - let c = Vec3::new((tf.x / major).round() * major, (tf.y / major).round() * major, 0.0); + let (u, v) = grid_plane(app.cam.to_frame(app.cam.back())); + 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 { @@ -706,8 +709,8 @@ fn build_sketch_scene(app: &SolveApp, proj: &Proj) -> GpuScene { 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 + Vec3::new(t, -ext, 0.0)), w3(c + Vec3::new(t, ext, 0.0)), col, w); - sc.under_line(w3(c + Vec3::new(-ext, t, 0.0)), w3(c + Vec3::new(ext, t, 0.0)), col, w); + 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); } } for sid in visible_sketches(app) { @@ -5496,3 +5499,35 @@ mod tests { #[cfg(test)] #[path = "view_home_tests.rs"] mod view_home_tests; + +#[cfg(test)] +mod grid_plane_tests { + use super::*; + use solidcraft_engine::render::{StandardView, UpAxis}; + + fn plane(view: StandardView, up: UpAxis) -> (Vec3, Vec3) { + let (yaw, pitch) = view.angles(); + let cam = Camera { yaw, pitch, up, ..Camera::default() }; + let (u, v) = grid_plane(cam.to_frame(cam.back())); + (cam.from_frame(u), cam.from_frame(v)) + } + + /// #1470: the grid lies on the ground unless the view sees the ground edge-on; then it lies on + /// the upright origin plane facing the view, Z up or Y up alike. + #[test] + fn the_grid_faces_side_views_and_stays_on_the_ground_otherwise() { + let normal = |(u, v): (Vec3, Vec3)| u.cross(v); + for up in [UpAxis::Z, UpAxis::Y] { + for view in [StandardView::Top, StandardView::Bottom, StandardView::Iso] { + assert_eq!(normal(plane(view, up)).dot(up.dir()).abs(), 1.0, "{view:?} {up:?}: the ground"); + } + for view in [StandardView::Front, StandardView::Back, StandardView::Right, StandardView::Left] { + let (yaw, pitch) = view.angles(); + let back = Camera { yaw, pitch, up, ..Camera::default() }.back(); + let n = normal(plane(view, up)); + assert!(n.dot(up.dir()).abs() < 1e-9, "{view:?} {up:?}: an upright plane"); + assert!((n.dot(back).abs() - 1.0).abs() < 1e-9, "{view:?} {up:?}: facing the view"); + } + } + } +} From c419dec76c1809bf56fa708ac2442e9d0e4edc23 Mon Sep 17 00:00:00 2001 From: DuBearte <130190089+DuBearte@users.noreply.github.com> Date: Fri, 16 Oct 2026 00:27:26 -0400 Subject: [PATCH 66/92] Joint drive test: wait as long as the other preview tests (#1549) (#1582) Thanks @DuBearte. --- crates/ui-egui/src/dialogs_assembly_tests.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs_assembly_tests.rs b/crates/ui-egui/src/dialogs_assembly_tests.rs index c306440aa..24c05c9bd 100644 --- a/crates/ui-egui/src/dialogs_assembly_tests.rs +++ b/crates/ui-egui/src/dialogs_assembly_tests.rs @@ -363,7 +363,9 @@ fn drive_slider_previews_intermediate_positions_before_release() { let second = preview_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap(); assert_ne!(first, second, "the held slider requests a new pose before release"); assert!(h.ctx.input(|i| i.pointer.primary_down())); - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + // The preview runs on a worker thread; on a machine busy with other test binaries it can + // take several seconds, so wait as long as the other preview tests do (#1549). + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60); while h.app.preview.busy { assert!(std::time::Instant::now() < deadline, "held-slider preview did not finish"); std::thread::sleep(std::time::Duration::from_millis(1)); From 3fe929e91c3fffa33d3759657e2e95225ae2fee3 Mon Sep 17 00:00:00 2001 From: DuBearte <130190089+DuBearte@users.noreply.github.com> Date: Fri, 16 Oct 2026 00:27:33 -0400 Subject: [PATCH 67/92] Renderer: skip a frame the GPU won't stage instead of crashing (#1469) (#1579) Thanks @DuBearte. --- ATTRIBUTION.md | 2 ++ vendor/README.md | 2 ++ vendor/egui-wgpu/src/renderer.rs | 23 +++++++++++++++++++---- 3 files changed, 23 insertions(+), 4 deletions(-) diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index d20962567..3a8994563 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -186,3 +186,5 @@ its original `egui.wgsl` shader are retained; no images or other artwork are cop SolidCraft's narrow patch selects a safe 1x MSAA path on the chosen OpenGL adapter and shares that effective count with the surface attachments and CAD callbacks. Vulkan, DirectX 12, Metal and WebGPU retain their requested multisampling. +A frame whose meshes the GPU refuses to stage (device lost or out of memory) is +skipped with a warning instead of panicking (#1469). diff --git a/vendor/README.md b/vendor/README.md index 62cd65e60..e748f75ee 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -147,6 +147,8 @@ SolidCraft changes: - `src/lib.rs`: use 1x MSAA on the selected OpenGL adapter before creating pipelines, exposing the effective sample count so host paint callbacks can match it. - `src/winit.rs`: use that same effective count for depth and resolve attachments. +- `src/renderer.rs`: when the GPU refuses a staging buffer for a frame's meshes (device lost + or out of memory), log a warning and draw nothing that frame instead of panicking (#1469). - Other backends retain requested MSAA, without another adapter or device probe. - `src/lib.rs`: clamp MSAA to the largest sample count the device supports for the surface and depth formats (`supported_msaa_samples`, `RenderState::msaa_supported`): a saved 8x on a diff --git a/vendor/egui-wgpu/src/renderer.rs b/vendor/egui-wgpu/src/renderer.rs index de8808de3..05b29b8f6 100644 --- a/vendor/egui-wgpu/src/renderer.rs +++ b/vendor/egui-wgpu/src/renderer.rs @@ -254,6 +254,11 @@ pub struct Renderer { options: RendererOptions, + /// The last `update_buffers` could not upload this frame's meshes (the GPU refused a + /// staging buffer: device lost or out of memory), so `render` draws nothing this frame + /// instead of panicking (SolidCraft #1469). + skip_frame: bool, + /// Storage for resources shared with all invocations of [`CallbackTrait`]'s methods. /// /// See also [`CallbackTrait`]. @@ -453,6 +458,7 @@ impl Renderer { slices: Vec::with_capacity(64), capacity: INDEX_BUFFER_START_CAPACITY, }, + skip_frame: false, uniform_buffer, // Buffers on wgpu are zero initialized, so this is indeed its current state! previous_uniform_buffer_content: UniformBuffer::zeroed(), @@ -484,6 +490,10 @@ impl Renderer { ) { profiling::function_scope!(); + if self.skip_frame { + return; + } + let pixels_per_point = screen_descriptor.pixels_per_point; let size_in_pixels = screen_descriptor.size_in_pixels; @@ -922,6 +932,7 @@ impl Renderer { ) -> Vec { profiling::function_scope!(); + self.skip_frame = false; let screen_size_in_points = screen_descriptor.screen_size_in_points(); let uniform_buffer_content = UniformBuffer { @@ -981,11 +992,13 @@ impl Renderer { ); let Some(mut index_buffer_staging) = index_buffer_staging else { - panic!( - "Failed to create staging buffer for index data. Index count: {index_count}. Required index buffer size: {required_index_buffer_size}. Actual size {} and capacity: {} (bytes)", + log::warn!( + "Failed to create staging buffer for index data; skipping this frame. Index count: {index_count}. Required index buffer size: {required_index_buffer_size}. Actual size {} and capacity: {} (bytes)", self.index_buffer.buffer.size(), self.index_buffer.capacity ); + self.skip_frame = true; + return Vec::new(); }; let mut index_offset = 0; @@ -1027,11 +1040,13 @@ impl Renderer { ); let Some(mut vertex_buffer_staging) = vertex_buffer_staging else { - panic!( - "Failed to create staging buffer for vertex data. Vertex count: {vertex_count}. Required vertex buffer size: {required_vertex_buffer_size}. Actual size {} and capacity: {} (bytes)", + log::warn!( + "Failed to create staging buffer for vertex data; skipping this frame. Vertex count: {vertex_count}. Required vertex buffer size: {required_vertex_buffer_size}. Actual size {} and capacity: {} (bytes)", self.vertex_buffer.buffer.size(), self.vertex_buffer.capacity ); + self.skip_frame = true; + return Vec::new(); }; let mut vertex_offset = 0; From d624e0a171ce703dab5ee66fd3ec72fa60b0c0ef Mon Sep 17 00:00:00 2001 From: DuBearte <130190089+DuBearte@users.noreply.github.com> Date: Fri, 16 Oct 2026 00:27:40 -0400 Subject: [PATCH 68/92] Expressions: inch and foot marks (#1502) (#1578) Thanks @DuBearte. --- crates/doc/src/expr.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/crates/doc/src/expr.rs b/crates/doc/src/expr.rs index 8ea891a9b..5e86b2bb9 100644 --- a/crates/doc/src/expr.rs +++ b/crates/doc/src/expr.rs @@ -281,6 +281,13 @@ fn lex_spans(s: &str) -> Result, DocError> { } else if c == '°' { out.push((Tok::Id("deg".into()), at(i), at(i + 1))); i += 1; + } else if c == '"' || c == '″' { + // Inch and foot marks (`1"`, `2'`, #1502), straight or as primes. + out.push((Tok::Id("in".into()), at(i), at(i + 1))); + i += 1; + } else if c == '\'' || c == '′' { + out.push((Tok::Id("ft".into()), at(i), at(i + 1))); + i += 1; } else if c == '×' || c == '·' { out.push((Tok::Op('*'), at(i), at(i + 1))); i += 1; @@ -856,6 +863,20 @@ mod tests { } } + #[test] + fn inch_and_foot_marks() { + // #1502: `1"` in a millimetre design is an inch, `2'` two feet, straight or as primes. + assert_eq!(ev("1\"", Kind::Length).unwrap(), 25.4); + assert_eq!(ev("1″", Kind::Length).unwrap(), 25.4); + assert_eq!(ev("2'", Kind::Length).unwrap(), 609.6); + assert_eq!(ev("2′", Kind::Length).unwrap(), 609.6); + assert_eq!(ev("1/2\"", Kind::Length).unwrap(), 12.7); + assert_eq!(ev("width + 1\"", Kind::Length).unwrap(), 65.4); + assert_eq!(ev("2' + 3\"", Kind::Length).unwrap(), 685.8); + // A mark alone is its unit alone, as `in` is. + assert_eq!(ev("\"", Kind::Length).ok(), ev("in", Kind::Length).ok()); + } + #[test] fn arithmetic_and_units() { assert_eq!(ev("10", Kind::Length).unwrap(), 10.0); From 42d4ebeb16f765401ad659f211a7a083edd3641e Mon Sep 17 00:00:00 2001 From: "H. Conrad" <78785932+Ian-cmd-ops@users.noreply.github.com> Date: Thu, 15 Oct 2026 21:27:48 -0700 Subject: [PATCH 69/92] STEP export: a merged partial cylinder keeps its cylinder (silent volume loss) (#1497) Thanks @Ian-cmd-ops. --- crates/engine/tests/step_merge_regressions.rs | 80 +++++++++++++++++++ crates/kernel/src/step_in/tests.rs | 14 ++++ crates/kernel/src/step_out.rs | 57 +++++++++++-- 3 files changed, 146 insertions(+), 5 deletions(-) create mode 100644 crates/engine/tests/step_merge_regressions.rs diff --git a/crates/engine/tests/step_merge_regressions.rs b/crates/engine/tests/step_merge_regressions.rs new file mode 100644 index 000000000..940e051b5 --- /dev/null +++ b/crates/engine/tests/step_merge_regressions.rs @@ -0,0 +1,80 @@ +//! STEP export regressions found by round-tripping the robustness designs: faces the writer +//! merges must keep their whole surface, so the body reads back as the same solid. + +use serde_json::{Value, json}; +use solidcraft_engine::Session; +use solidcraft_kernel::{measure, step_export, step_import}; + +fn run(s: &mut Session, script: Value) { + for c in script.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} {p}: {e}"); + } + } +} + +/// The design's one body exports, and reads back closed with the same volume and area. +fn round_trips(s: &Session) { + let st = s.model.state(); + assert_eq!(st.bodies.len(), 1); + let body = &st.bodies[0].body; + let text = step_export(&[body], "test").unwrap_or_else(|e| panic!("export: {e}")); + let imp = step_import(&text).unwrap_or_else(|e| panic!("import: {e}")); + assert_eq!(imp.bodies.len(), 1, "{:?}", imp.warnings); + assert!(imp.bodies[0].closed && imp.warnings.is_empty(), "{:?}", imp.warnings); + let (a, b) = (measure(body).unwrap(), measure(&imp.bodies[0].body).unwrap()); + assert!((a.volume - b.volume).abs() < 1e-3 * a.volume, "volume {} -> {}", a.volume, b.volume); + assert!((a.area - b.area).abs() < 1e-3 * a.area, "area {} -> {}", a.area, b.area); +} + +/// Robustness seed 17, shrunk: a thin three-quarter tube shelled 1 mm with its bottom open. The +/// export merged each wall's three quarter pieces into one face but kept the first piece's +/// quarter sheet as its surface; the body read back closed, with no warning, 7% too small. +#[test] +fn shelled_thin_three_quarter_tube_keeps_its_volume() { + let mut s = Session::default(); + run( + &mut s, + json!([ + {"command":"sketch.create","params":{"plane":"XZ"}}, + {"command":"sketch.rectangle.two_point","params":{"p0":[10.0,0],"p1":[12.5,27.5]}}, + {"command":"sketch.finish","params":{}}, + {"command":"solid.revolve","params":{"angle":"270 deg","axis":"Z"}}, + {"command":"solid.shell","params":{"faces":[[-7.182422893157272,7.182422893245109,0.0]],"thickness":1.0}} + ]), + ); + round_trips(&s); +} + +/// The same tube turned further: the merged wall leaves a gap of 60°, 30° or 10°. Its two straight +/// end edges lie either side of the gap, so the mean direction of the face's points no longer +/// points into the face, and a seam put opposite it falls inside the face. The seam belongs in the +/// middle of the gap. +#[test] +fn shelled_thin_wide_tube_keeps_its_volume() { + for turn in [300.0_f64, 330.0, 350.0] { + let mid = (turn / 2.0).to_radians(); + let mut s = Session::default(); + run( + &mut s, + json!([ + {"command":"sketch.create","params":{"plane":"XZ"}}, + {"command":"sketch.rectangle.two_point","params":{"p0":[10.0,0],"p1":[12.5,27.5]}}, + {"command":"sketch.finish","params":{}}, + {"command":"solid.revolve","params":{"angle":format!("{turn} deg"),"axis":"Z"}}, + {"command":"solid.shell","params":{"faces":[[11.0 * mid.cos(), 11.0 * mid.sin(), 0.0]],"thickness":1.0}} + ]), + ); + let st = s.model.state(); + assert_eq!(st.bodies.len(), 1, "{turn} deg"); + let body = &st.bodies[0].body; + let text = step_export(&[body], "test").unwrap_or_else(|e| panic!("{turn} deg export: {e}")); + let imp = step_import(&text).unwrap_or_else(|e| panic!("{turn} deg import: {e}")); + assert_eq!(imp.bodies.len(), 1, "{turn} deg {:?}", imp.warnings); + assert!(imp.bodies[0].closed && imp.warnings.is_empty(), "{turn} deg {:?}", imp.warnings); + let (a, b) = (measure(body).unwrap(), measure(&imp.bodies[0].body).unwrap()); + assert!((a.volume - b.volume).abs() < 1e-3 * a.volume, "{turn} deg volume {} -> {}", a.volume, b.volume); + assert!((a.area - b.area).abs() < 1e-3 * a.area, "{turn} deg area {} -> {}", a.area, b.area); + } +} diff --git a/crates/kernel/src/step_in/tests.rs b/crates/kernel/src/step_in/tests.rs index 5b7d7680f..6dd7f4ea7 100644 --- a/crates/kernel/src/step_in/tests.rs +++ b/crates/kernel/src/step_in/tests.rs @@ -238,6 +238,20 @@ fn round_trip_features() { round_trip(&donut[0]); } +/// Robustness seed 17: a thin three-quarter tube shelled with its bottom open. truck writes each +/// wall as three quarter-turn B-spline pieces; the export merges them into one 270° face and must +/// write that face's cylinder, not the first piece's quarter sheet. The seam direction came from +/// the mean direction of the face's vertices, which is zero at 0°, 90°, 180° and 270°, so the +/// merged face kept the quarter sheet and read back about 7% short with no warning. +#[test] +fn shelled_three_quarter_tube_round_trips() { + let rect = + Region2 { outer: Loop2::polygon(&[Vec2::new(10.0, 0.0), Vec2::new(12.5, 0.0), Vec2::new(12.5, 27.5), Vec2::new(10.0, 27.5)]), holes: vec![] }; + let tube = revolve(&Plane::XZ, &[rect], Vec2::ZERO, Vec2::Y, 1.5 * std::f64::consts::PI).unwrap().pop().unwrap(); + let b = crate::shell(&tube, &[Vec3::new(-7.182422893157272, 7.182422893245109, 0.0)], 1.0).unwrap(); + round_trip(&b); +} + #[test] fn several_bodies_and_names() { let a = box_solid(Vec3::ZERO, Vec3::new(10.0, 10.0, 10.0)).unwrap(); diff --git a/crates/kernel/src/step_out.rs b/crates/kernel/src/step_out.rs index c45e46a63..3cb1c59bc 100644 --- a/crates/kernel/src/step_out.rs +++ b/crates/kernel/src/step_out.rs @@ -1252,7 +1252,8 @@ fn merge_split_faces(ex: &mut p21::Exchange, paint: &mut HashMap, /// B-spline cylinder and cone sheets written as CYLINDRICAL_SURFACE and CONICAL_SURFACE (the /// sheet covers only its own piece, and a fillet's may reach far past it), with the direction of -/// the parameter seam: on the face's seam edge for a full turn, else opposite the face's middle. +/// the parameter seam: on the face's seam edge for a full turn, else in the middle of the gap the +/// face leaves (`gap_middle`), else opposite the face's middle. /// Sheets under faces merged from pieces always; a lone piece when its edges are circles square /// to the axis and rulings. (Faces replaced by merges stay in the exchange unreferenced: only the /// shells' faces count.) @@ -1292,12 +1293,13 @@ fn analytic_sheets(ex: &p21::Exchange, merged_surfaces: &std::collections::HashS let p = ex.get(edge)?.params(); [p.get(1), p.get(2)].into_iter().filter_map(|v| vertex_point(ex, v?.as_ref_id()?)).find_map(|q| unit(radial(q))) }); - let x = match seam_dir { + let x = match seam_dir.or_else(|| gap_middle(ex, &loops, z, &radial)) { Some(x) => Some(x), None => { - // Points along the edges, not just their ends: the corners of a half turn (a - // slot's round end) point both ways and cancel out (#1198). The sheet's own - // middle where even those do. + // No single gap to find (a half turn has two corners, a tube cut in pieces + // several). Points along the edges, not just their ends: the corners of a half + // turn (a slot's round end) point both ways and cancel out (#1198). The sheet's + // own middle where even those do. let mean = loops .iter() .flatten() @@ -1316,6 +1318,51 @@ fn analytic_sheets(ex: &p21::Exchange, merged_surfaces: &std::collections::HashS out } +/// The middle of the one angular gap that a face on a cylinder or cone leaves around its axis +/// `z`. The face's boundary vertices are sorted by angle; each two neighbours are joined by one +/// of its edges except across the gap (a 270° face split at 0°, 90°, 180° and 270° leaves +/// 270°–360°). None unless there are three angles or more and exactly one gap: two vertices can +/// be joined either way round. +fn gap_middle(ex: &p21::Exchange, loops: &[Vec<(u64, bool)>], z: V3, radial: &impl Fn(V3) -> V3) -> Option { + use std::f64::consts::TAU; + let mut edges: Vec<(V3, V3)> = Vec::new(); + for (e, _) in loops.iter().flatten() { + let p = ex.get(*e)?.params(); + let (a, b) = (vertex_point(ex, p.get(1)?.as_ref_id()?)?, vertex_point(ex, p.get(2)?.as_ref_id()?)?); + edges.push((unit(radial(a))?, unit(radial(b))?)); + } + let e1 = edges.first()?.0; + let e2 = unit(cross(z, e1))?; + let angle = |d: V3| dot(d, e2).atan2(dot(d, e1)).rem_euclid(TAU); + let close = |a: f64, b: f64| { + let d = (a - b).rem_euclid(TAU); + d < 1e-6 || TAU - d < 1e-6 + }; + let mut angles: Vec = Vec::new(); + for (a, b) in &edges { + for t in [angle(*a), angle(*b)] { + if !angles.iter().any(|s| close(*s, t)) { + angles.push(t); + } + } + } + if angles.len() < 3 { + return None; + } + angles.sort_by(f64::total_cmp); + let joined = |s: f64, t: f64| { + edges.iter().any(|(a, b)| { + let (x, y) = (angle(*a), angle(*b)); + (close(x, s) && close(y, t)) || (close(x, t) && close(y, s)) + }) + }; + let n = angles.len(); + let gaps: Vec<(f64, f64)> = (0..n).filter_map(|i| Some((*angles.get(i)?, *angles.get((i + 1) % n)?))).filter(|(s, t)| !joined(*s, *t)).collect(); + let [(s, t)] = gaps[..] else { return None }; + let m = s + (t - s).rem_euclid(TAU) / 2.0; + unit(add(mul(e1, m.cos()), mul(e2, m.sin()))) +} + /// Margin left round a face when its sheet is cut down to it, as a share of the face's own /// parameter range on each side. const SHEET_MARGIN: f64 = 0.02; From 3333f8a62b0f55f17c85214859907a67263eaa3e Mon Sep 17 00:00:00 2001 From: JIJINBEI <87472238+jijinbei@users.noreply.github.com> Date: Fri, 16 Oct 2026 13:27:55 +0900 Subject: [PATCH 70/92] Divide intersection edges from their neighbours' parameters (#1038) (#1412) Thanks @jijinbei. --- ATTRIBUTION.md | 1 + Cargo.lock | 2 - Cargo.toml | 1 + THIRD-PARTY-LICENSES.txt | 10 +- crates/kernel/src/issue_1038_tests.rs | 81 + crates/kernel/src/lib.rs | 2 + vendor/README.md | 12 + vendor/truck-geometry/.cargo-ok | 1 + vendor/truck-geometry/Cargo.toml | 55 + vendor/truck-geometry/LICENSE | 177 ++ vendor/truck-geometry/README.md | 5 + .../src/decorators/curve_on_surface.rs | 228 ++ .../src/decorators/extruded_curve.rs | 203 ++ .../src/decorators/intersection_curve.rs | 330 +++ vendor/truck-geometry/src/decorators/mod.rs | 149 ++ .../src/decorators/processor.rs | 658 +++++ .../src/decorators/revolved_curve.rs | 689 +++++ .../src/decorators/trimmied_curve.rs | 73 + vendor/truck-geometry/src/errors.rs | 190 ++ vendor/truck-geometry/src/lib.rs | 52 + vendor/truck-geometry/src/nurbs/bspcurve.rs | 1488 +++++++++++ vendor/truck-geometry/src/nurbs/bspsurface.rs | 2230 +++++++++++++++++ vendor/truck-geometry/src/nurbs/knot_vec.rs | 596 +++++ vendor/truck-geometry/src/nurbs/mod.rs | 135 + vendor/truck-geometry/src/nurbs/nurbscurve.rs | 619 +++++ .../truck-geometry/src/nurbs/nurbssurface.rs | 920 +++++++ .../truck-geometry/src/specifieds/circle.rs | 161 ++ .../src/specifieds/hyperbola.rs | 125 + vendor/truck-geometry/src/specifieds/line.rs | 217 ++ vendor/truck-geometry/src/specifieds/mod.rs | 115 + .../truck-geometry/src/specifieds/parabola.rs | 137 + vendor/truck-geometry/src/specifieds/plane.rs | 256 ++ .../truck-geometry/src/specifieds/sphere.rs | 219 ++ vendor/truck-geometry/src/specifieds/torus.rs | 238 ++ 34 files changed, 10368 insertions(+), 7 deletions(-) create mode 100644 crates/kernel/src/issue_1038_tests.rs create mode 100644 vendor/truck-geometry/.cargo-ok create mode 100644 vendor/truck-geometry/Cargo.toml create mode 100644 vendor/truck-geometry/LICENSE create mode 100644 vendor/truck-geometry/README.md create mode 100644 vendor/truck-geometry/src/decorators/curve_on_surface.rs create mode 100644 vendor/truck-geometry/src/decorators/extruded_curve.rs create mode 100644 vendor/truck-geometry/src/decorators/intersection_curve.rs create mode 100644 vendor/truck-geometry/src/decorators/mod.rs create mode 100644 vendor/truck-geometry/src/decorators/processor.rs create mode 100644 vendor/truck-geometry/src/decorators/revolved_curve.rs create mode 100644 vendor/truck-geometry/src/decorators/trimmied_curve.rs create mode 100644 vendor/truck-geometry/src/errors.rs create mode 100644 vendor/truck-geometry/src/lib.rs create mode 100644 vendor/truck-geometry/src/nurbs/bspcurve.rs create mode 100644 vendor/truck-geometry/src/nurbs/bspsurface.rs create mode 100644 vendor/truck-geometry/src/nurbs/knot_vec.rs create mode 100644 vendor/truck-geometry/src/nurbs/mod.rs create mode 100644 vendor/truck-geometry/src/nurbs/nurbscurve.rs create mode 100644 vendor/truck-geometry/src/nurbs/nurbssurface.rs create mode 100644 vendor/truck-geometry/src/specifieds/circle.rs create mode 100644 vendor/truck-geometry/src/specifieds/hyperbola.rs create mode 100644 vendor/truck-geometry/src/specifieds/line.rs create mode 100644 vendor/truck-geometry/src/specifieds/mod.rs create mode 100644 vendor/truck-geometry/src/specifieds/parabola.rs create mode 100644 vendor/truck-geometry/src/specifieds/plane.rs create mode 100644 vendor/truck-geometry/src/specifieds/sphere.rs create mode 100644 vendor/truck-geometry/src/specifieds/torus.rs diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 3a8994563..b5b8c4d2d 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -176,6 +176,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-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 (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) | ## Vendored renderer compatibility fix diff --git a/Cargo.lock b/Cargo.lock index 4124950ca..88f732ed5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4552,8 +4552,6 @@ dependencies = [ [[package]] name = "truck-geometry" version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d9d85f203fdbc2d206a38b8e7c4417a05a2eb589be8b81ecfe9f98faafc425d" dependencies = [ "serde", "thiserror 1.0.69", diff --git a/Cargo.toml b/Cargo.toml index 1066b71b7..8955c336a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -126,6 +126,7 @@ debug = "line-tables-only" # truck-shapeops with SolidCraft fixes (Apache-2.0, see vendor/truck-shapeops and ATTRIBUTION.md). [patch.crates-io] +truck-geometry = { path = "vendor/truck-geometry" } truck-shapeops = { path = "vendor/truck-shapeops" } truck-stepio = { path = "vendor/truck-stepio" } truck-meshalgo = { path = "vendor/truck-meshalgo" } diff --git a/THIRD-PARTY-LICENSES.txt b/THIRD-PARTY-LICENSES.txt index 6254c85ec..a702b820b 100644 --- a/THIRD-PARTY-LICENSES.txt +++ b/THIRD-PARTY-LICENSES.txt @@ -1536,10 +1536,11 @@ android-activity 0.6.1, arboard 3.6.1, color 0.3.3, fdeflate 0.3.7, fearless_sim image 0.25.10, linebender_resource_handle 0.1.1, miniz_oxide 0.8.9, miniz_oxide 0.9.1, naga 30.0.1, naga-types 30.0.1, pin-project 1.1.13, pin-project-internal 1.1.13, pin-project-lite 0.2.17, portable-atomic 1.15.0, portable-atomic-util 0.2.8, range-alloc 0.1.5, raw-window-handle 0.6.2, -simdutf8 0.1.5, truck-meshalgo 0.4.0, truck-shapeops 0.4.0, truck-stepio 0.3.0, vello_common 0.1.0, -vello_cpu 0.1.0, wgpu 30.0.1, wgpu-core 30.0.1, wgpu-core-deps-apple 30.0.1, -wgpu-core-deps-emscripten 30.0.1, wgpu-core-deps-wasm 30.0.1, wgpu-core-deps-windows-linux-android -30.0.1, wgpu-hal 30.0.1, wgpu-naga-bridge 30.0.1, wgpu-types 30.0.1 +simdutf8 0.1.5, truck-geometry 0.5.0, truck-meshalgo 0.4.0, truck-shapeops 0.4.0, truck-stepio +0.3.0, vello_common 0.1.0, vello_cpu 0.1.0, wgpu 30.0.1, wgpu-core 30.0.1, wgpu-core-deps-apple +30.0.1, wgpu-core-deps-emscripten 30.0.1, wgpu-core-deps-wasm 30.0.1, +wgpu-core-deps-windows-linux-android 30.0.1, wgpu-hal 30.0.1, wgpu-naga-bridge 30.0.1, wgpu-types +30.0.1 ================================================================================ Apache License @@ -15964,7 +15965,6 @@ rustls-platform-verifier-android 0.2.0: MIT OR Apache-2.0 (https://github.com/ru spirv 0.4.0+sdk-1.4.341.0: Apache-2.0 (https://github.com/gfx-rs/rspirv) truck-base 0.5.0: Apache-2.0 (https://github.com/ricosjp/truck) truck-derivers 0.1.0: Apache-2.0 (https://github.com/ricosjp/truck) -truck-geometry 0.5.0: Apache-2.0 (https://github.com/ricosjp/truck) truck-geotrait 0.4.0: Apache-2.0 (https://github.com/ricosjp/truck) truck-modeling 0.6.0: Apache-2.0 (https://github.com/ricosjp/truck) truck-polymesh 0.6.0: Apache-2.0 (https://github.com/ricosjp/truck) diff --git a/crates/kernel/src/issue_1038_tests.rs b/crates/kernel/src/issue_1038_tests.rs new file mode 100644 index 000000000..ca3f16f1c --- /dev/null +++ b/crates/kernel/src/issue_1038_tests.rs @@ -0,0 +1,81 @@ +//! #1038: a small hole on a large curved face divides its intersection edges from each point's +//! neighbour (the vendored `IntersectionCurve::parameter_division`) instead of searching both +//! surfaces from nothing for every point. These pin the hinted division to the search from +//! nothing, so a refresh of the vendored crate can't quietly lose the speedup or change a body. + +use std::time::{Duration, Instant}; + +use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2, Vec3}; +use truck_modeling as mt; +use truck_modeling::{BoundedCurve, ParameterDivision1D}; + +use crate::{Body, BoolOp, build::extrude, cylinder, ops::boolean}; + +/// A 200 × 200 block whose top is one cubic wave across x (a single B-spline face), with a +/// Ø1 mm hole through it at the middle. +fn holed() -> (Body, Body) { + let plane = Plane::new(Vec3::new(0.0, 200.0, 0.0), Vec3::X, Vec3::Z).unwrap(); + let (a, b, c, d) = (Vec2::new(0.0, 0.0), Vec2::new(200.0, 0.0), Vec2::new(200.0, 40.0), Vec2::new(0.0, 40.0)); + let top = Seg2::Cubic { p0: c, p1: Vec2::new(133.0, 70.0), p2: Vec2::new(67.0, 10.0), p3: d }; + let outer = Loop2 { segs: vec![Seg2::Line { a, b }, Seg2::Line { a: b, b: c }, top, Seg2::Line { a: d, b: a }] }; + let block = extrude(&plane, &[Region2 { outer, holes: vec![] }], 0.0, 200.0).unwrap().pop().unwrap(); + let tool = cylinder(Vec3::new(100.0, 100.0, -10.0), Vec3::Z, 0.5, 100.0).unwrap(); + let cut = boolean(&block, &tool, BoolOp::Cut).unwrap().unwrap(); + (block, cut) +} + +fn intersection_curves(body: &Body) -> Vec { + body.solid.edge_iter().map(|e| e.curve()).filter(|c| matches!(c, mt::Curve::IntersectionCurve(_))).collect() +} + +fn timed(f: impl Fn() -> T) -> (T, Duration) { + let start = Instant::now(); + let out = f(); + (out, start.elapsed()) +} + +#[test] +fn a_small_hole_in_a_large_spline_face_cuts_cleanly() { + let (block, cut) = holed(); + assert!(cut.validity().is_empty(), "{:?}", cut.validity()); + // The hole adds its wall (two half cylinders) and splits nothing: the bottom and the wave + // each gain a loop. + assert_eq!(cut.face_count(), block.face_count() + 2); + let curves = intersection_curves(&cut); + assert!(!curves.is_empty(), "the hole's rim on the wave is an intersection edge"); + // The wave is within a few tenths of a millimetre of flat across a Ø1 hole, so the hole + // removes a cylinder as tall as the wave at its axis (the cubic's middle: z = 40). + let (v0, v1) = (block.volume_at(0.001).unwrap(), cut.volume_at(0.001).unwrap()); + let removed = std::f64::consts::PI * 0.25 * 40.0; + assert!((v0 - v1 - removed).abs() < 0.05 * removed, "removed {} of {removed}", v0 - v1); +} + +#[test] +fn hinted_division_matches_the_search_from_nothing_and_is_faster() { + let (_, cut) = holed(); + let (mut hinted_time, mut scratch_time) = (Duration::ZERO, Duration::ZERO); + for curve in intersection_curves(&cut) { + let mt::Curve::IntersectionCurve(ic) = &curve else { continue }; + let range = ic.range_tuple(); + for tol in [0.01, 0.001] { + let ((hp, hq), ht) = timed(|| ic.parameter_division(range, tol)); + let ((sp, _), st) = timed(|| mt::algo::curve::parameter_division(ic, range, tol)); + hinted_time += ht; + scratch_time += st; + // The same division up to rounding: the hinted projections converge to within the + // Newton tolerance of the searched ones, so a split the chord test only just asks for + // can come out one way or the other, but no more than that. + assert_eq!((hp.first(), hp.last()), (sp.first(), sp.last()), "tol {tol}"); + assert!(hp.len().abs_diff(sp.len()) <= 2, "tol {tol}: {} points hinted, {} from nothing", hp.len(), sp.len()); + // Every hinted point is the curve's own point at its parameter. + for (t, h) in hp.iter().zip(&hq) { + let s = ic.search_triple(*t).unwrap().0; + assert!(mt::MetricSpace::distance(*h, s) < 1e-6, "tol {tol}, t {t}: {h:?} vs {s:?}"); + } + } + } + eprintln!("hinted {hinted_time:?}, from nothing {scratch_time:?}"); + // The hinted path skips each point's grid search of the B-spline face; a loose bound, so a + // loaded runner doesn't trip it, but one a fallback to the search for every point would. + assert!(hinted_time * 2 < scratch_time, "hinted {hinted_time:?}, from nothing {scratch_time:?}"); +} diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rs index 212483729..a152328c5 100644 --- a/crates/kernel/src/lib.rs +++ b/crates/kernel/src/lib.rs @@ -47,6 +47,8 @@ mod iges_out; #[cfg(test)] mod intersection_curve_tests; #[cfg(test)] +mod issue_1038_tests; +#[cfg(test)] mod issue_1080_tests; #[cfg(test)] mod issue_616_tests; diff --git a/vendor/README.md b/vendor/README.md index e748f75ee..3b1e4ea5c 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -42,6 +42,18 @@ Changes: 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). +## truck-geometry 0.5.0 (Apache-2.0, © RICOS Co. Ltd., https://github.com/ricosjp/truck) + +Changes: +- `decorators/intersection_curve.rs`: `IntersectionCurve::parameter_division` divides as + `algo::curve::parameter_division` does (the same split points, in the same order), but each + point's projection onto the two surfaces starts from the parameters of the point that begins + its piece, instead of a search of the whole surfaces (a grid pre-search of a B-spline surface + for every point: a small hole on a large curved face took seconds, #1038). A hinted result + farther from the leader's point than the curve's tolerance (the projection settled on another + part of a surface, such as the far side of a small hole) is dropped for the search from + nothing, as before. `crates/kernel/src/issue_1038_tests.rs` holds it to that search. + ## truck-stepio 0.3.0 (Apache-2.0, © RICOS Co. Ltd., https://github.com/ricosjp/truck) Only the writer (`out`) is used; SolidCraft reads STEP with its own reader. diff --git a/vendor/truck-geometry/.cargo-ok b/vendor/truck-geometry/.cargo-ok new file mode 100644 index 000000000..5f8b79583 --- /dev/null +++ b/vendor/truck-geometry/.cargo-ok @@ -0,0 +1 @@ +{"v":1} \ No newline at end of file diff --git a/vendor/truck-geometry/Cargo.toml b/vendor/truck-geometry/Cargo.toml new file mode 100644 index 000000000..c74275816 --- /dev/null +++ b/vendor/truck-geometry/Cargo.toml @@ -0,0 +1,55 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2021" +name = "truck-geometry" +version = "0.5.0" +authors = ["Yoshinori Tanimura "] +build = false +autobins = false +autoexamples = false +autotests = false +autobenches = false +description = "geometrical structs: knot vector, B-spline and NURBS" +homepage = "https://github.com/ricosjp/truck" +readme = "README.md" +keywords = [ + "truck", + "graphics", +] +categories = ["graphics"] +license = "Apache-2.0" +repository = "https://github.com/ricosjp/truck" + +[lib] +name = "truck_geometry" +path = "src/lib.rs" + +[dependencies.serde] +version = "1.0.210" +features = ["derive"] + +[dependencies.thiserror] +version = "1.0.63" + +[dependencies.truck-base] +version = "0.5.0" + +[dependencies.truck-geotrait] +version = "0.4.0" + +[dev-dependencies.rand] +version = "0.8.5" + +[target.'cfg(target_arch = "wasm32")'.dev-dependencies.getrandom] +version = "0.2.15" +features = ["js"] diff --git a/vendor/truck-geometry/LICENSE b/vendor/truck-geometry/LICENSE new file mode 100644 index 000000000..f433b1a53 --- /dev/null +++ b/vendor/truck-geometry/LICENSE @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/vendor/truck-geometry/README.md b/vendor/truck-geometry/README.md new file mode 100644 index 000000000..5d2212dbb --- /dev/null +++ b/vendor/truck-geometry/README.md @@ -0,0 +1,5 @@ +# truck-geometry + +[![Crates.io](https://img.shields.io/crates/v/truck-geometry.svg)](https://crates.io/crates/truck-geometry) [![Docs.rs](https://docs.rs/truck-geometry/badge.svg)](https://docs.rs/truck-geometry) + +Geometrical structs: knot vector, B-spline and NURBS diff --git a/vendor/truck-geometry/src/decorators/curve_on_surface.rs b/vendor/truck-geometry/src/decorators/curve_on_surface.rs new file mode 100644 index 000000000..690ed2ce5 --- /dev/null +++ b/vendor/truck-geometry/src/decorators/curve_on_surface.rs @@ -0,0 +1,228 @@ +use super::*; + +impl PCurve { + /// Creates composited + #[inline(always)] + pub const fn new(curve: C, surface: S) -> PCurve { PCurve { curve, surface } } + + /// Returns the reference to the parameter curve + #[inline(always)] + pub const fn curve(&self) -> &C { &self.curve } + + /// Returns the reference to the surface + #[inline(always)] + pub const fn surface(&self) -> &S { &self.surface } + + /// Decompose the pcurve into its parameter curve and surface. + #[inline(always)] + pub fn decompose(self) -> (C, S) { (self.curve, self.surface) } +} + +impl ParametricCurve for PCurve +where + C: ParametricCurve2D, + S: ParametricSurface, + S::Vector: VectorSpace, +{ + type Point = S::Point; + type Vector = S::Vector; + #[inline(always)] + fn subs(&self, t: f64) -> Self::Point { + let pt = self.curve.subs(t); + self.surface.subs(pt[0], pt[1]) + } + #[inline(always)] + fn der(&self, t: f64) -> Self::Vector { + let pt = self.curve.subs(t); + let der = self.curve.der(t); + self.surface.uder(pt[0], pt[1]) * der[0] + self.surface.vder(pt[0], pt[1]) * der[1] + } + #[inline(always)] + fn parameter_range(&self) -> ParameterRange { self.curve.parameter_range() } + #[inline(always)] + fn der2(&self, t: f64) -> Self::Vector { + let pt = self.curve.subs(t); + let der = self.curve.der(t); + let der2 = self.curve.der2(t); + self.surface.uuder(pt[0], pt[1]) * der[0] * der[0] + + self.surface.uvder(pt[0], pt[1]) * der[0] * der[1] * 2.0 + + self.surface.vvder(pt[0], pt[1]) * der[1] * der[1] + + self.surface.uder(pt[0], pt[1]) * der2[0] + + self.surface.vder(pt[0], pt[1]) * der2[1] + } +} + +impl BoundedCurve for PCurve +where + C: BoundedCurve, + PCurve: ParametricCurve, +{ +} + +impl Cut for PCurve +where + C: Cut, + S: Clone, + PCurve: ParametricCurve, +{ + fn cut(&mut self, t: f64) -> Self { + let curve = self.curve.cut(t); + Self { + curve, + surface: self.surface.clone(), + } + } +} + +impl SearchParameter for PCurve +where + C: ParametricCurve2D + SearchParameter, + S: SearchParameter, +{ + type Point = >::Point; + fn search_parameter>( + &self, + point: Self::Point, + hint: H, + trials: usize, + ) -> Option { + let hint = hint.into(); + let shint = match hint { + SPHint1D::Parameter(hint) => { + let p = self.curve.subs(hint); + SPHint2D::Parameter(p.x, p.y) + } + SPHint1D::Range(x, y) => { + let p = self.curve.subs(y); + let ranges = (0..PRESEARCH_DIVISION).fold( + ((p.x, p.x), (p.y, p.y)), + |((x0, x1), (y0, y1)), i| { + let t = x + (y - x) * i as f64 / PRESEARCH_DIVISION as f64; + let p = self.curve.subs(t); + ( + (f64::min(x0, p.x), f64::max(x1, p.x)), + (f64::min(y0, p.y), f64::max(y1, p.y)), + ) + }, + ); + SPHint2D::Range(ranges.0, ranges.1) + } + SPHint1D::None => SPHint2D::None, + }; + let (x, y) = self.surface.search_parameter(point, shint, trials)?; + self.curve.search_parameter(Point2::new(x, y), hint, trials) + } +} + +impl SearchNearestParameter for PCurve +where + Self: BoundedCurve, + ::Point: EuclideanSpace::Vector> + + MetricSpace, + ::Vector: InnerSpace + Tolerance, +{ + type Point = ::Point; + fn search_nearest_parameter>( + &self, + point: Self::Point, + hint: H, + trials: usize, + ) -> Option { + let hint = match hint.into() { + SPHint1D::Parameter(hint) => hint, + SPHint1D::Range(x, y) => { + algo::curve::presearch(self, point, (x, y), PRESEARCH_DIVISION) + } + SPHint1D::None => { + algo::curve::presearch(self, point, self.range_tuple(), PRESEARCH_DIVISION) + } + }; + algo::curve::search_nearest_parameter(self, point, hint, trials) + } +} + +impl ParameterDivision1D for PCurve +where + C: ParametricCurve2D, + S: ParametricSurface, + S::Point: EuclideanSpace + MetricSpace + HashGen, + S::Vector: VectorSpace, +{ + type Point = S::Point; + fn parameter_division(&self, range: (f64, f64), tol: f64) -> (Vec, Vec) { + algo::curve::parameter_division(self, range, tol) + } +} + +impl Invertible for PCurve +where + C: Invertible, + S: Clone, +{ + fn invert(&mut self) { self.curve.invert() } +} + +impl Transformed for PCurve +where S: Transformed +{ + #[inline(always)] + fn transform_by(&mut self, trans: T) { self.surface.transform_by(trans); } + fn transformed(&self, trans: T) -> Self { + Self { + curve: self.curve.clone(), + surface: self.surface.transformed(trans), + } + } +} + +#[test] +fn pcurve_test() { + let curve = BSplineCurve::new( + KnotVec::bezier_knot(2), + vec![ + Point2::new(1.0, 1.0), + Point2::new(1.0, 0.0), + Point2::new(0.0, 0.0), + ], + ); + let surface = BSplineSurface::new( + (KnotVec::bezier_knot(2), KnotVec::bezier_knot(1)), + vec![ + vec![Point3::new(0.0, 0.0, 0.0), Point3::new(0.0, 1.0, 0.0)], + vec![Point3::new(0.0, 0.0, 1.0), Point3::new(0.0, 1.0, 1.0)], + vec![Point3::new(1.0, 0.0, 1.0), Point3::new(1.0, 1.0, 1.0)], + ], + ); + let pcurve = PCurve::new(curve, surface); + assert_eq!(pcurve.range_tuple(), (0.0, 1.0)); + + const N: usize = 100; + for i in 0..=N { + let t = i as f64 / N as f64; + assert_near!( + pcurve.subs(t), + Point3::new( + (1.0 - t * t) * (1.0 - t * t), + (1.0 - t) * (1.0 - t), + 1.0 - t * t * t * t, + ), + ); + assert_near!( + pcurve.der(t), + Vector3::new(4.0 * t * (t * t - 1.0), 2.0 * (t - 1.0), -4.0 * t * t * t,), + ); + assert_near!( + pcurve.der2(t), + Vector3::new(4.0 * (3.0 * t * t - 1.0), 2.0, -12.0 * t * t,), + ); + } + + let t = 0.675; + let pt = pcurve.subs(t); + assert_near!(pcurve.search_parameter(pt, None, 100).unwrap(), t); + + let pt = pt + Vector3::new(0.01, 0.06, -0.03); + assert!(pcurve.search_parameter(pt, None, 100).is_none()); + let t = pcurve.search_nearest_parameter(pt, None, 100).unwrap(); + assert!(pcurve.der(t).dot(pcurve.subs(t) - pt).so_small()); +} diff --git a/vendor/truck-geometry/src/decorators/extruded_curve.rs b/vendor/truck-geometry/src/decorators/extruded_curve.rs new file mode 100644 index 000000000..7128e6971 --- /dev/null +++ b/vendor/truck-geometry/src/decorators/extruded_curve.rs @@ -0,0 +1,203 @@ +use super::*; + +impl ExtrudedCurve { + /// Creates a linear extruded curve by extrusion. + #[inline(always)] + pub const fn by_extrusion(curve: C, vector: V) -> Self { Self { curve, vector } } + + /// Returns the curve before extruded. + #[inline(always)] + pub const fn entity_curve(&self) -> &C { &self.curve } + /// Into the curve before revoluted. + #[inline(always)] + pub fn into_entity_curve(self) -> C { self.curve } + + /// Returns the vector of extruded curve. + #[inline(always)] + pub const fn extruding_vector(&self) -> V { self.vector } +} + +impl ParametricSurface for ExtrudedCurve +where + C: ParametricCurve, + C::Point: EuclideanSpace, + C::Vector: VectorSpace, +{ + type Point = C::Point; + type Vector = C::Vector; + #[inline(always)] + fn subs(&self, u: f64, v: f64) -> C::Point { self.curve.subs(u) + self.vector * v } + #[inline(always)] + fn uder(&self, u: f64, _: f64) -> C::Vector { self.curve.der(u) } + #[inline(always)] + fn vder(&self, _: f64, _: f64) -> C::Vector { self.vector } + #[inline(always)] + fn uuder(&self, u: f64, _: f64) -> C::Vector { self.curve.der2(u) } + #[inline(always)] + fn uvder(&self, _: f64, _: f64) -> C::Vector { C::Vector::zero() } + #[inline(always)] + fn vvder(&self, _: f64, _: f64) -> C::Vector { C::Vector::zero() } + #[inline(always)] + fn parameter_range(&self) -> (ParameterRange, ParameterRange) { + ( + self.curve.parameter_range(), + (Bound::Included(0.0), Bound::Included(1.0)), + ) + } + #[inline(always)] + fn u_period(&self) -> Option { self.curve.period() } +} + +impl ParametricSurface3D for ExtrudedCurve { + #[inline(always)] + fn normal(&self, u: f64, _: f64) -> C::Vector { + self.curve.der(u).cross(self.vector).normalize() + } +} + +impl BoundedSurface for ExtrudedCurve +where + C: BoundedCurve, + Self: ParametricSurface, +{ +} + +impl ParameterDivision2D for ExtrudedCurve { + #[inline(always)] + fn parameter_division( + &self, + (urange, vrange): ((f64, f64), (f64, f64)), + tol: f64, + ) -> (Vec, Vec) { + ( + self.curve.parameter_division(urange, tol).0, + vec![vrange.0, vrange.1], + ) + } +} + +impl SearchParameter for ExtrudedCurve { + type Point = Point2; + #[inline(always)] + fn search_parameter>( + &self, + point: Point2, + hint: H, + trials: usize, + ) -> Option<(f64, f64)> { + let hint = match hint.into() { + SPHint2D::Parameter(x, y) => (x, y), + SPHint2D::Range(range0, range1) => { + algo::surface::presearch(self, point, (range0, range1), PRESEARCH_DIVISION) + } + SPHint2D::None => { + algo::surface::presearch(self, point, self.range_tuple(), PRESEARCH_DIVISION) + } + }; + algo::surface::search_parameter2d(self, point, hint, trials) + } +} + +impl SearchParameter for ExtrudedCurve { + type Point = Point3; + #[inline(always)] + fn search_parameter>( + &self, + point: Point3, + hint: H, + trials: usize, + ) -> Option<(f64, f64)> { + let hint = match hint.into() { + SPHint2D::Parameter(x, y) => (x, y), + SPHint2D::Range(range0, range1) => { + algo::surface::presearch(self, point, (range0, range1), PRESEARCH_DIVISION) + } + SPHint2D::None => { + algo::surface::presearch(self, point, self.range_tuple(), PRESEARCH_DIVISION) + } + }; + algo::surface::search_parameter3d(self, point, hint, trials) + } +} + +impl SearchNearestParameter for ExtrudedCurve { + type Point = Point3; + #[inline(always)] + fn search_nearest_parameter>( + &self, + point: Point3, + hint: H, + trials: usize, + ) -> Option<(f64, f64)> { + let hint = match hint.into() { + SPHint2D::Parameter(x, y) => (x, y), + SPHint2D::Range(range0, range1) => { + algo::surface::presearch(self, point, (range0, range1), PRESEARCH_DIVISION) + } + SPHint2D::None => { + algo::surface::presearch(self, point, self.range_tuple(), PRESEARCH_DIVISION) + } + }; + algo::surface::search_nearest_parameter(self, point, hint, trials) + } +} + +impl Invertible for ExtrudedCurve { + #[inline(always)] + fn invert(&mut self) { self.curve.invert() } + #[inline(always)] + fn inverse(&self) -> Self { + Self { + curve: self.curve.inverse(), + vector: self.vector, + } + } +} + +impl> Transformed for ExtrudedCurve { + fn transform_by(&mut self, trans: Matrix4) { + self.curve.transform_by(trans); + self.vector = trans.transform_vector(self.vector); + } + fn transformed(&self, trans: Matrix4) -> Self { + Self { + curve: self.curve.transformed(trans), + vector: trans.transform_vector(self.vector), + } + } +} + +#[test] +fn extruded_curve_test() { + let cpts = vec![ + Point3::new(0.0, 0.0, 0.0), + Point3::new(0.0, 1.0, 0.0), + Point3::new(1.0, 0.0, 0.0), + ]; + let spts = vec![ + vec![Point3::new(0.0, 0.0, 0.0), Point3::new(0.0, 0.0, 1.0)], + vec![Point3::new(0.0, 1.0, 0.0), Point3::new(0.0, 1.0, 1.0)], + vec![Point3::new(1.0, 0.0, 0.0), Point3::new(1.0, 0.0, 1.0)], + ]; + let curve = BSplineCurve::new(KnotVec::bezier_knot(2), cpts); + let surface0 = ExtrudedCurve::by_extrusion(curve, Vector3::unit_z()); + let surface1 = BSplineSurface::new((KnotVec::bezier_knot(2), KnotVec::bezier_knot(1)), spts); + assert_eq!(surface0.range_tuple(), surface1.range_tuple()); + const N: usize = 10; + for i in 0..=N { + for j in 0..=N { + let u = i as f64 / N as f64; + let v = j as f64 / N as f64; + assert_near!( + surface0.subs(u, v), + ParametricSurface::subs(&surface1, u, v) + ); + assert_near!(surface0.uder(u, v), surface1.uder(u, v)); + assert_near!(surface0.vder(u, v), surface1.vder(u, v)); + assert_near!(surface0.uuder(u, v), surface1.uuder(u, v)); + assert_near!(surface0.uvder(u, v), surface1.uvder(u, v)); + assert_near!(surface0.vvder(u, v), surface1.vvder(u, v)); + assert_near!(surface0.normal(u, v), surface1.normal(u, v)); + } + } +} diff --git a/vendor/truck-geometry/src/decorators/intersection_curve.rs b/vendor/truck-geometry/src/decorators/intersection_curve.rs new file mode 100644 index 000000000..d6390e61e --- /dev/null +++ b/vendor/truck-geometry/src/decorators/intersection_curve.rs @@ -0,0 +1,330 @@ +use super::*; + +#[doc(hidden)] +pub fn double_projection( + surface0: &S, + hint0: Option<(f64, f64)>, + surface1: &S, + hint1: Option<(f64, f64)>, + mut point: Point3, + normal: Vector3, + trials: usize, +) -> Option<(Point3, Point2, Point2)> +where + S: ParametricSurface3D + SearchNearestParameter, +{ + #[cfg(all(test, debug_assertions))] + let mut log = Vec::new(); + let mut uv0 = surface0.search_nearest_parameter(point, hint0, 10)?; + let mut uv1 = surface1.search_nearest_parameter(point, hint1, 10)?; + for _ in 0..trials { + #[cfg(all(test, debug_assertions))] + log.push((point, uv0, uv1)); + uv0 = surface0.search_nearest_parameter(point, Some(uv0), 10)?; + let pt0 = surface0.subs(uv0.0, uv0.1); + uv1 = surface1.search_nearest_parameter(point, Some(uv1), 10)?; + let pt1 = surface1.subs(uv1.0, uv1.1); + if point.near(&pt0) && point.near(&pt1) && pt0.near(&pt1) { + return Some((point, Point2::from(uv0), Point2::from(uv1))); + } else { + let n0 = surface0.normal(uv0.0, uv0.1); + let n1 = surface1.normal(uv1.0, uv1.1); + let mat = Matrix3::from_cols(n0, n1, normal).transpose(); + let inv = mat.invert()?; + let pt = inv * Vector3::new(pt0.dot(n0), pt1.dot(n1), point.dot(normal)); + point = Point3::from_vec(pt); + } + } + #[cfg(all(test, debug_assertions))] + { + eprintln!("Newton method is not converges"); + log.into_iter().for_each(|t| eprintln!("{t:?}")); + } + None +} + +/// Mutable editor for `IntersectionCurve`. +#[doc(hidden)] +#[derive(Debug)] +pub struct IntersectionCurveEditor<'a, C, S> { + pub surface0: &'a mut S, + pub surface1: &'a mut S, + pub leader: &'a mut C, + pub tol: &'a mut f64, +} + +impl IntersectionCurve { + /// This curve is a part of intersection of `self.surface0()` and `self.surface1()`. + #[inline(always)] + pub fn surface0(&self) -> &S { &self.surface0 } + /// This curve is a part of intersection of `self.surface0()` and `self.surface1()`. + #[inline(always)] + pub fn surface1(&self) -> &S { &self.surface1 } + /// Returns the polyline leading this curve. + #[inline(always)] + pub fn leader(&self) -> &C { &self.leader } + /// Returns editor for `IntersectionCurve`. This method is only for developers, do not use. + #[doc(hidden)] + #[inline(always)] + pub fn editor(&mut self) -> IntersectionCurveEditor<'_, C, S> { + IntersectionCurveEditor { + surface0: &mut self.surface0, + surface1: &mut self.surface1, + leader: &mut self.leader, + tol: &mut self.tol, + } + } + /// Change leader. + #[doc(hidden)] + #[inline(always)] + pub fn change_leader(self, f: impl FnOnce(C) -> D) -> IntersectionCurve { + IntersectionCurve { + surface0: self.surface0, + surface1: self.surface1, + leader: f(self.leader), + tol: self.tol, + } + } + /// The tolerance for generating this intersection curve. + #[inline(always)] + pub fn tolerance(&self) -> f64 { self.tol } + /// Creates intersection curve with unchecked bound. This method is only for developer of `truck`, deplicated for users. + #[inline(always)] + pub fn new_unchecked(surface0: Box, surface1: Box, leader: C, tol: f64) -> Self { + Self { + surface0, + surface1, + leader, + tol, + } + } +} + +impl IntersectionCurve +where + C: ParametricCurve3D, + S: ParametricSurface3D + SearchNearestParameter, +{ + /// Search triple value of the point corresponding to the parameter `t`. + /// - the coordinate on 3D space + /// - the uv coordinate on `self.surface0()` + /// - the uv coordinate on `self.surface1()` + #[inline(always)] + pub fn search_triple(&self, t: f64) -> Option<(Point3, Point2, Point2)> { + double_projection( + self.surface0(), + None, + self.surface1(), + None, + self.leader.subs(t), + self.leader.der(t), + 100, + ) + } +} + +impl ParametricCurve for IntersectionCurve +where + C: ParametricCurve3D, + S: ParametricSurface3D + SearchNearestParameter, +{ + type Point = Point3; + type Vector = Vector3; + fn subs(&self, t: f64) -> Point3 { self.search_triple(t).unwrap().0 } + fn der(&self, t: f64) -> Vector3 { + let n = self.leader.der(t); + let (_, p0, p1) = self.search_triple(t).unwrap(); + let d = self + .surface0 + .normal(p0.x, p0.y) + .cross(self.surface1.normal(p1.x, p1.y)) + .normalize(); + d * (n.dot(n) / d.dot(n)) + } + /// This method is unimplemented! Should panic!! + #[inline(always)] + fn der2(&self, _: f64) -> Vector3 { + unimplemented!(); + } + #[inline(always)] + fn parameter_range(&self) -> ParameterRange { self.leader.parameter_range() } +} + +impl BoundedCurve for IntersectionCurve +where + C: ParametricCurve3D + BoundedCurve, + S: ParametricSurface3D + SearchNearestParameter, +{ +} + +impl ParameterDivision1D for IntersectionCurve +where + C: ParametricCurve3D, + S: ParametricSurface3D + SearchNearestParameter, +{ + type Point = Point3; + // SolidCraft: the division of `algo::curve::parameter_division` (the same split points and + // the same order), but each point's projection onto the two surfaces starts from the + // parameters of the point that begins its piece instead of a search of the whole surfaces: + // that search ran for every point and made dividing an intersection edge on a large B-spline + // surface take seconds. A point the hinted projection misses is searched for as before. + fn parameter_division(&self, range: (f64, f64), tol: f64) -> (Vec, Vec) { + nonpositive_tolerance!(tol); + let start = self.hinted_triple(range.0, None); + let end = self.hinted_triple(range.1, None); + hinted_sub_division(self, range, (start, end), tol, 100) + } +} + +// SolidCraft: a point of the curve with its parameters on both surfaces. +type Triple = (Point3, Point2, Point2); + +impl IntersectionCurve +where + C: ParametricCurve3D, + S: ParametricSurface3D + SearchNearestParameter, +{ + // SolidCraft: `search_triple` started from `hint`'s parameters, falling back to the search + // from nothing (and, where that fails too, to `subs` as before). A hinted result is taken + // only within the curve's tolerance of the leader's point, where the leader lies: started + // from a neighbour (or from a periodic surface's seam), the projection can settle on another + // part of a surface, such as the far side of a small hole, which the search from nothing + // would not. + fn hinted_triple(&self, t: f64, hint: Option) -> Triple { + let lead = self.leader.subs(t); + let near = self.tol.max(TOLERANCE); + let hinted = hint.and_then(|(_, uv0, uv1)| { + double_projection( + self.surface0(), + Some((uv0.x, uv0.y)), + self.surface1(), + Some((uv1.x, uv1.y)), + lead, + self.leader.der(t), + 100, + ) + .filter(|(p, _, _)| p.distance(lead) <= near) + }); + match hinted.or_else(|| self.search_triple(t)) { + Some(triple) => triple, + None => (self.subs(t), Point2::origin(), Point2::origin()), + } + } +} + +// SolidCraft: `algo::curve::sub_parameter_division`, carrying each end's parameters. +fn hinted_sub_division( + curve: &IntersectionCurve, + range: (f64, f64), + ends: (Triple, Triple), + tol: f64, + trials: usize, +) -> (Vec, Vec) +where + C: ParametricCurve3D, + S: ParametricSurface3D + SearchNearestParameter, +{ + let (p0, p1) = (ends.0 .0, ends.1 .0); + let gen = p0.midpoint(p1); + let p = 0.5 + (0.2 * HashGen::hash1(gen) - 0.1); + let t = range.0 * (1.0 - p) + range.1 * p; + let mid = p0 + (p1 - p0) * p; + let dist2 = curve.hinted_triple(t, Some(ends.0)).0.distance2(mid); + if dist2 < tol * tol || trials == 0 { + (vec![range.0, range.1], vec![p0, p1]) + } else { + let mid_param = (range.0 + range.1) / 2.0; + let mid_value = curve.hinted_triple(mid_param, Some(ends.0)); + let (mut params, mut pts) = + hinted_sub_division(curve, (range.0, mid_param), (ends.0, mid_value), tol, trials - 1); + let _ = (params.pop(), pts.pop()); + let (new_params, new_pts) = + hinted_sub_division(curve, (mid_param, range.1), (mid_value, ends.1), tol, trials - 1); + params.extend(new_params); + pts.extend(new_pts); + (params, pts) + } +} + +impl Cut for IntersectionCurve +where + C: Cut, + S: ParametricSurface3D + SearchNearestParameter, +{ + #[inline(always)] + fn cut(&mut self, t: f64) -> Self { + Self { + surface0: self.surface0.clone(), + surface1: self.surface1.clone(), + leader: self.leader.cut(t), + tol: self.tol, + } + } +} + +impl Invertible for IntersectionCurve { + fn invert(&mut self) { self.leader.invert(); } +} + +impl SearchParameter for IntersectionCurve +where + C: ParametricCurve3D + SearchNearestParameter, + S: ParametricSurface3D + SearchNearestParameter, +{ + type Point = Point3; + fn search_parameter>( + &self, + point: Point3, + hint: H, + trials: usize, + ) -> Option { + let t = self + .leader() + .search_nearest_parameter(point, hint, trials) + .unwrap(); + let pt = self.subs(t); + match pt.near(&point) { + true => Some(t), + false => None, + } + } +} + +/// Only derive from leading curve. Not precise. +impl SearchNearestParameter for IntersectionCurve +where + C: ParametricCurve3D + SearchNearestParameter, + S: ParametricSurface3D + SearchNearestParameter, +{ + type Point = Point3; + fn search_nearest_parameter>( + &self, + point: Point3, + hint: H, + trials: usize, + ) -> Option { + self.leader().search_nearest_parameter(point, hint, trials) + } +} + +impl Transformed for IntersectionCurve +where + C: Transformed, + S: Transformed, +{ + fn transform_by(&mut self, trans: Matrix4) { + self.surface0.transform_by(trans); + self.surface1.transform_by(trans); + self.leader.transform_by(trans); + self.tol *= trans.norm_l2(); + } +} + +impl IntersectionCurve { + /// Optimizes intersection curve of [`Plane`] into [`Line`]. + #[inline] + pub fn optimize(&self) -> Line { + let (s, t) = self.leader.range_tuple(); + Line(self.leader.subs(s), self.leader.subs(t)) + } +} diff --git a/vendor/truck-geometry/src/decorators/mod.rs b/vendor/truck-geometry/src/decorators/mod.rs new file mode 100644 index 000000000..5961c1e56 --- /dev/null +++ b/vendor/truck-geometry/src/decorators/mod.rs @@ -0,0 +1,149 @@ +use crate::{prelude::*, *}; +use std::ops::{Deref, DerefMut, Mul}; + +/// revolution +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +struct Revolution { + origin: Point3, + axis: Vector3, +} + +/// surface constructed by revoluting a curve +/// # Examples +/// Revoluted sphere +/// ``` +/// use truck_geometry::prelude::*; +/// use std::f64::consts::PI; +/// let knot_vec = KnotVec::bezier_knot(2); +/// let control_points = vec![ +/// Vector4::new(1.0, 0.0, 0.0, 1.0), +/// Vector4::new(0.0, 1.0, 0.0, 0.0), +/// Vector4::new(-1.0, 0.0, 0.0, 1.0), +/// ]; +/// // upper half circle on xy-plane +/// let uhcircle = NurbsCurve::new(BSplineCurve::new(knot_vec, control_points)); +/// // sphere constructed by revolute circle +/// let sphere = RevolutedCurve::by_revolution( +/// uhcircle, Point3::origin(), Vector3::unit_x(), +/// ); +/// const N: usize = 30; +/// for i in 0..=N { +/// for j in 0..=N { +/// let u = i as f64 / N as f64; +/// let v = 2.0 * PI * j as f64 / N as f64; +/// let pt: Vector3 = sphere.subs(u, v).to_vec(); +/// assert_near2!(pt.magnitude2(), 1.0); +/// assert_near!(pt, sphere.normal(u, v)); +/// } +/// } +/// ``` +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct RevolutedCurve { + curve: C, + revolution: Revolution, +} + +/// Linearly extruded curve +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct ExtrudedCurve { + curve: C, + vector: V, +} + +/// invertible and transformable geometric element +/// # Examples +/// Curve processing example +/// ``` +/// use truck_geometry::prelude::*; +/// let curve: BSplineCurve = BSplineCurve::new( +/// KnotVec::bezier_knot(2), +/// vec![ +/// Point3::new(0.0, 0.0, 0.0), +/// Point3::new(0.0, 0.0, 1.0), +/// Point3::new(1.0, 0.0, 0.0), +/// ], +/// ); +/// let mut processed = Processor::<_, Matrix4>::new(curve.clone()); +/// +/// // both curves are the same curve +/// const N: usize = 100; +/// for i in 0..=N { +/// let t = i as f64 / N as f64; +/// assert_eq!(curve.subs(t), processed.subs(t)); +/// } +/// +/// // Processed curve can inverted! +/// processed.invert(); +/// for i in 0..=N { +/// let t = i as f64 / N as f64; +/// assert_eq!(curve.subs(1.0 - t), processed.subs(t)); +/// } +/// ``` +/// Surface processing example +/// ``` +/// use truck_geometry::prelude::*; +/// use std::f64::consts::PI; +/// +/// let sphere = Sphere::new(Point3::new(1.0, 2.0, 3.0), 2.45); +/// let mut processed = Processor::<_, Matrix4>::new(sphere); +/// +/// // both surfaces are the same surface +/// const N: usize = 100; +/// for i in 0..=N { +/// for j in 0..=N { +/// let u = PI * i as f64 / N as f64; +/// let v = 2.0 * PI * j as f64 / N as f64; +/// assert_eq!(sphere.subs(u, v), processed.subs(u, v)); +/// } +/// } +/// +/// // Processed surface can be inverted! +/// // Here, "invert surface" means swap (u, v)-axes. +/// processed.invert(); +/// for i in 0..=N { +/// for j in 0..=N { +/// let u = PI * i as f64 / N as f64; +/// let v = 2.0 * PI * j as f64 / N as f64; +/// assert_eq!(sphere.subs(u, v), processed.subs(v, u)); +/// } +/// } +/// ``` +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct Processor { + entity: E, + transform: T, + orientation: bool, +} + +/// The composited maps +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct PCurve { + curve: C, + surface: S, +} + +/// Intersection curve between two surfaces. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct IntersectionCurve { + // Considering rotational surfaces, we can consider the case + // where the class `S` holds the curve `C` as a variable. + surface0: Box, + surface1: Box, + leader: C, + tol: f64, +} + +/// trimmed curve for parametric curve +#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] +pub struct TrimmedCurve { + curve: C, + range: (f64, f64), +} + +mod curve_on_surface; +mod extruded_curve; +mod intersection_curve; +mod processor; +mod revolved_curve; +mod trimmied_curve; +pub use intersection_curve::double_projection; diff --git a/vendor/truck-geometry/src/decorators/processor.rs b/vendor/truck-geometry/src/decorators/processor.rs new file mode 100644 index 000000000..3f44d3d8d --- /dev/null +++ b/vendor/truck-geometry/src/decorators/processor.rs @@ -0,0 +1,658 @@ +use super::*; + +impl Processor { + /// Creates new processor + #[inline(always)] + pub fn new(entity: E) -> Processor { + Processor { + entity, + transform: T::one(), + orientation: true, + } + } + + /// Returns the reference of entity + #[inline(always)] + pub const fn entity(&self) -> &E { &self.entity } + + /// Returns the reference of transform + #[inline(always)] + pub const fn transform(&self) -> &T { &self.transform } + + /// Returns the orientation of surface + #[inline(always)] + pub const fn orientation(&self) -> bool { self.orientation } + + #[inline(always)] + fn sign(&self) -> f64 { + match self.orientation { + true => 1.0, + false => -1.0, + } + } + + /// apply the function to the entity geometry + #[inline(always)] + pub fn map G>(self, f: F) -> Processor { + Processor { + entity: f(self.entity), + transform: self.transform, + orientation: self.orientation, + } + } + + /// apply the function to the entity geometry + #[inline(always)] + pub fn map_ref G>(&self, f: F) -> Processor + where T: Copy { + Processor { + entity: f(&self.entity), + transform: self.transform, + orientation: self.orientation, + } + } + + /// apply the transform and inverse + pub fn constract(self) -> E + where E: Transformed + Invertible { + let mut res = self.entity; + res.transform_by(self.transform); + if !self.orientation { + res.invert(); + } + res + } +} + +impl Invertible for Processor { + #[inline(always)] + fn invert(&mut self) { self.orientation = !self.orientation; } + #[inline(always)] + fn inverse(&self) -> Self { + Processor { + entity: self.entity.clone(), + transform: self.transform.clone(), + orientation: !self.orientation, + } + } +} + +impl Processor { + #[inline(always)] + fn get_curve_parameter(&self, t: f64) -> f64 { + let (t0, t1) = self.range_tuple(); + match self.orientation { + true => t, + false => t0 + t1 - t, + } + } +} + +impl ParametricCurve for Processor +where + C: BoundedCurve, + C::Point: EuclideanSpace, + C::Vector: VectorSpace, + T: Transform + Clone, +{ + type Point = C::Point; + type Vector = C::Vector; + #[inline(always)] + fn subs(&self, t: f64) -> C::Point { + let t = self.get_curve_parameter(t); + self.transform.transform_point(self.entity.subs(t)) + } + #[inline(always)] + fn der(&self, t: f64) -> Self::Vector { + let t = self.get_curve_parameter(t); + self.transform.transform_vector(self.entity.der(t)) * self.sign() + } + #[inline(always)] + fn der2(&self, t: f64) -> Self::Vector { + let t = self.get_curve_parameter(t); + self.transform.transform_vector(self.entity.der2(t)) + } + #[inline(always)] + fn parameter_range(&self) -> ParameterRange { self.entity.parameter_range() } + #[inline(always)] + fn period(&self) -> Option { self.entity.period() } +} + +impl BoundedCurve for Processor +where + C: BoundedCurve, + C::Point: EuclideanSpace, + C::Vector: VectorSpace, + T: Transform + Clone, +{ +} + +impl Cut for Processor +where + C: BoundedCurve + Cut, + C::Point: EuclideanSpace, + C::Vector: VectorSpace, + T: Transform + Clone, +{ + fn cut(&mut self, t: f64) -> Self { + let t = self.get_curve_parameter(t); + let mut entity = self.entity.cut(t); + if !self.orientation { + std::mem::swap(&mut entity, &mut self.entity); + } + Self { + entity, + transform: self.transform.clone(), + orientation: self.orientation, + } + } +} + +impl ParametricSurface for Processor +where + S: ParametricSurface, + S::Point: EuclideanSpace, + T: Transform + SquareMatrix + Clone, +{ + type Point = S::Point; + type Vector = S::Vector; + #[inline(always)] + fn subs(&self, u: f64, v: f64) -> Self::Point { + match self.orientation { + true => self.transform.transform_point(self.entity.subs(u, v)), + false => self.transform.transform_point(self.entity.subs(v, u)), + } + } + #[inline(always)] + fn uder(&self, u: f64, v: f64) -> Self::Vector { + match self.orientation { + true => self.transform.transform_vector(self.entity.uder(u, v)), + false => self.transform.transform_vector(self.entity.vder(v, u)), + } + } + #[inline(always)] + fn vder(&self, u: f64, v: f64) -> Self::Vector { + match self.orientation { + true => self.transform.transform_vector(self.entity.vder(u, v)), + false => self.transform.transform_vector(self.entity.uder(v, u)), + } + } + #[inline(always)] + fn uuder(&self, u: f64, v: f64) -> Self::Vector { + match self.orientation { + true => self.transform.transform_vector(self.entity.uuder(u, v)), + false => self.transform.transform_vector(self.entity.vvder(v, u)), + } + } + #[inline(always)] + fn uvder(&self, u: f64, v: f64) -> Self::Vector { + match self.orientation { + true => self.transform.transform_vector(self.entity.uvder(u, v)), + false => self.transform.transform_vector(self.entity.uvder(v, u)), + } + } + #[inline(always)] + fn vvder(&self, u: f64, v: f64) -> Self::Vector { + match self.orientation { + true => self.transform.transform_vector(self.entity.vvder(u, v)), + false => self.transform.transform_vector(self.entity.uuder(v, u)), + } + } + #[inline(always)] + fn parameter_range(&self) -> (ParameterRange, ParameterRange) { + let (urange, vrange) = self.entity.parameter_range(); + match self.orientation { + true => (urange, vrange), + false => (vrange, urange), + } + } + #[inline(always)] + fn u_period(&self) -> Option { + match self.orientation { + true => self.entity.u_period(), + false => self.entity.v_period(), + } + } + #[inline(always)] + fn v_period(&self) -> Option { + match self.orientation { + true => self.entity.v_period(), + false => self.entity.u_period(), + } + } +} + +impl ParametricSurface3D for Processor +where + S: ParametricSurface3D, + T: Transform + SquareMatrix + Clone, +{ + #[inline(always)] + fn normal(&self, u: f64, v: f64) -> Self::Vector { + let transtrans = self.transform.transpose(); + let n = match self.orientation { + true => self.entity.normal(u, v), + false => -self.entity.normal(v, u), + }; + let n = transtrans + .inverse_transform_vector(n) + .expect("invalid transform"); + (n / self.transform.determinant()).normalize() + } +} + +impl BoundedSurface for Processor +where + S: BoundedSurface, + T: Transform + SquareMatrix + Clone, +{ +} + +impl Deref for Processor { + type Target = E; + #[inline(always)] + fn deref(&self) -> &E { &self.entity } +} + +impl DerefMut for Processor { + #[inline(always)] + fn deref_mut(&mut self) -> &mut E { &mut self.entity } +} + +impl Transformed for Processor +where + T: Mul + Copy, + E: Clone, +{ + #[inline(always)] + fn transform_by(&mut self, trans: T) { self.transform = trans * self.transform; } + #[inline(always)] + fn transformed(&self, trans: T) -> Self { + Self { + entity: self.entity.clone(), + transform: trans * self.transform, + orientation: self.orientation, + } + } +} + +impl IncludeCurve for Processor +where + C: ParametricCurve + Transformed + Clone, + C::Point: EuclideanSpace, + E: IncludeCurve, + T: Transform, +{ + fn include(&self, curve: &C) -> bool { + let inv = self + .transform + .inverse_transform() + .expect("irregular transform"); + let curve = curve.clone().transformed(inv); + self.entity.include(&curve) + } +} + +impl ParameterDivision1D for Processor +where C: ParameterDivision1D + BoundedCurve +{ + type Point = Point2; + fn parameter_division(&self, range: (f64, f64), tol: f64) -> (Vec, Vec) { + let a = self.transform; + let range = match self.orientation { + true => range, + false => ( + self.get_curve_parameter(range.1), + self.get_curve_parameter(range.0), + ), + }; + let (_, k, _) = a + .iwasawa_decomposition() + .expect("transform matrix must be invertible!"); + let n = f64::abs(k[0][0]) + .max(f64::abs(k[1][1])) + .max(f64::abs(k[2][2])); + let (mut params, mut points) = self.entity.parameter_division(range, tol / n); + points + .iter_mut() + .for_each(|pt| *pt = a.transform_point(*pt)); + if !self.orientation { + params + .iter_mut() + .for_each(|t| *t = self.get_curve_parameter(*t)); + points.reverse(); + } + (params, points) + } +} + +impl ParameterDivision1D for Processor +where C: ParameterDivision1D + BoundedCurve +{ + type Point = Point3; + fn parameter_division(&self, range: (f64, f64), tol: f64) -> (Vec, Vec) { + let a = self.transform; + let range = match self.orientation { + true => range, + false => ( + self.get_curve_parameter(range.1), + self.get_curve_parameter(range.0), + ), + }; + let (_, k, _) = a + .iwasawa_decomposition() + .expect("transform matrix must be invertible!"); + let n = f64::abs(k[0][0]) + .max(f64::abs(k[1][1])) + .max(f64::abs(k[2][2])) + / f64::abs(k[3][3]); + let (mut params, mut points) = self.entity.parameter_division(range, tol / n); + points + .iter_mut() + .for_each(|pt| *pt = a.transform_point(*pt)); + if !self.orientation { + params + .iter_mut() + .for_each(|t| *t = self.get_curve_parameter(*t)); + points.reverse(); + } + (params, points) + } +} + +impl ParameterDivision2D for Processor { + fn parameter_division( + &self, + range: ((f64, f64), (f64, f64)), + tol: f64, + ) -> (Vec, Vec) { + let a = self.transform; + let range = match self.orientation { + true => range, + false => (range.1, range.0), + }; + let (_, k, _) = a + .iwasawa_decomposition() + .expect("transform matrix must be invertible!"); + let n = f64::abs(k[0][0]) + .max(f64::abs(k[1][1])) + .max(f64::abs(k[2][2])); + let (udiv, vdiv) = self.entity.parameter_division(range, tol / n); + match self.orientation { + true => (udiv, vdiv), + false => (vdiv, udiv), + } + } +} + +impl ParameterDivision2D for Processor { + fn parameter_division( + &self, + range: ((f64, f64), (f64, f64)), + tol: f64, + ) -> (Vec, Vec) { + let a = self.transform; + let range = match self.orientation { + true => range, + false => (range.1, range.0), + }; + let (_, k, _) = a + .iwasawa_decomposition() + .expect("transform matrix must be invertible!"); + let n = f64::abs(k[0][0]) + .max(f64::abs(k[1][1])) + .max(f64::abs(k[2][2])) + / f64::abs(k[3][3]); + let (udiv, vdiv) = self.entity.parameter_division(range, tol / n); + match self.orientation { + true => (udiv, vdiv), + false => (vdiv, udiv), + } + } +} + +impl SearchParameter for Processor +where + E: SearchParameter + BoundedCurve, + >::Point: EuclideanSpace, + T: Transform<>::Point>, +{ + type Point = >::Point; + fn search_parameter>( + &self, + point: >::Point, + hint: H, + trials: usize, + ) -> Option { + let inv = self.transform.inverse_transform().unwrap(); + let t = self + .entity + .search_parameter(inv.transform_point(point), hint, trials)?; + Some(self.get_curve_parameter(t)) + } +} + +impl SearchParameter for Processor +where + E: SearchParameter, + E::Point: EuclideanSpace, + T: Transform, +{ + type Point = E::Point; + fn search_parameter>( + &self, + point: E::Point, + hint: H, + trials: usize, + ) -> Option<(f64, f64)> { + let inv = self.transform.inverse_transform().unwrap(); + let (u, v) = self + .entity + .search_parameter(inv.transform_point(point), hint, trials)?; + match self.orientation { + true => Some((u, v)), + false => Some((v, u)), + } + } +} + +impl SearchNearestParameter for Processor +where + E: BoundedCurve + SearchNearestParameter, + P: EuclideanSpace, + E::Vector: InnerSpace + Tolerance, + T: Transform

+ Clone, +{ + type Point = P; + fn search_nearest_parameter>( + &self, + point: Self::Point, + hint: H, + trials: usize, + ) -> Option { + let inv = self.transform.inverse_transform().unwrap(); + let hint = + self.entity + .search_nearest_parameter(inv.transform_point(point), hint, trials)?; + let hint = self.get_curve_parameter(hint); + algo::curve::search_nearest_parameter(self, point, hint, trials) + } +} + +impl SearchNearestParameter for Processor +where + E: ParametricSurface + SearchNearestParameter, + P: EuclideanSpace, + E::Vector: InnerSpace + Tolerance, + T: Transform

+ SquareMatrix + Clone, +{ + type Point = P; + fn search_nearest_parameter>( + &self, + point: Self::Point, + hint: H, + trials: usize, + ) -> Option<(f64, f64)> { + let inv = self.transform.inverse_transform().unwrap(); + let hint = + self.entity + .search_nearest_parameter(inv.transform_point(point), hint, trials)?; + let hint = match self.orientation { + true => hint, + false => (hint.1, hint.0), + }; + algo::surface::search_nearest_parameter(self, point, hint, trials) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn exec_compatible_with_bspcurve() { + const DEGREE: usize = 3; + const DIVISION: usize = 4; + let knot_vec = KnotVec::uniform_knot(DEGREE, DIVISION); + let control_points: Vec = (0..DEGREE + DIVISION) + .map(|i| Point3::new(i as f64, 20.0 * rand::random::() - 10.0, 0.0)) + .collect(); + let mut curve = BSplineCurve::new(knot_vec, control_points); + let mut processor = Processor::new(curve.clone()); + let mat = Matrix3::new( + 4.0 * rand::random::() - 2.0, + 4.0 * rand::random::() - 2.0, + 4.0 * rand::random::() - 2.0, + 4.0 * rand::random::() - 2.0, + 4.0 * rand::random::() - 2.0, + 4.0 * rand::random::() - 2.0, + 4.0 * rand::random::() - 2.0, + 4.0 * rand::random::() - 2.0, + 4.0 * rand::random::() - 2.0, + ); + if mat.determinant().so_small() { + println!("omitted: {mat:?}"); + return; + } + curve.transform_by(mat); + processor.transform_by(mat); + assert_eq!(curve.parameter_range(), processor.parameter_range()); + + const N: usize = 100; + for i in 0..=N { + let t = i as f64 / N as f64; + assert_near!(ParametricCurve::subs(&curve, t), processor.subs(t)); + assert_near!(ParametricCurve::der(&curve, t), processor.der(t)); + assert_near!(ParametricCurve::der2(&curve, t), processor.der2(t)); + } + + curve.invert(); + processor.invert(); + assert_eq!(curve.parameter_range(), processor.parameter_range()); + for i in 0..=N { + let t = i as f64 / N as f64; + assert_near!(ParametricCurve::subs(&curve, t), processor.subs(t)); + assert_near!(ParametricCurve::der(&curve, t), processor.der(t)); + assert_near!(ParametricCurve::der2(&curve, t), processor.der2(t)); + } + } + + #[test] + fn compatible_with_bspcurve() { (0..10).for_each(|_| exec_compatible_with_bspcurve()) } + + fn exec_compatible_with_bspsurface() { + const DEGREE: usize = 3; + const DIVISION: usize = 4; + let knot_vec = KnotVec::uniform_knot(DEGREE, DIVISION); + let knot_vecs = (knot_vec.clone(), knot_vec); + let control_points: Vec> = (0..DEGREE + DIVISION) + .map(|i| { + (0..DEGREE + DIVISION) + .map(|j| Point3::new(i as f64, j as f64, 20.0 * rand::random::() - 10.0)) + .collect() + }) + .collect(); + let mut surface = BSplineSurface::new(knot_vecs, control_points); + let mut processor = Processor::new(surface.clone()); + let mat = Matrix3::new( + 4.0 * rand::random::() - 2.0, + 4.0 * rand::random::() - 2.0, + 4.0 * rand::random::() - 2.0, + 4.0 * rand::random::() - 2.0, + 4.0 * rand::random::() - 2.0, + 4.0 * rand::random::() - 2.0, + 4.0 * rand::random::() - 2.0, + 4.0 * rand::random::() - 2.0, + 4.0 * rand::random::() - 2.0, + ); + if mat.determinant().so_small() { + println!("omitted: {mat:?}"); + return; + } + surface.transform_by(mat); + processor.transform_by(mat); + assert_eq!(surface.range_tuple(), processor.range_tuple()); + + const N: usize = 30; + for i in 0..=N { + for j in 0..=N { + let u = i as f64 / N as f64; + let v = j as f64 / N as f64; + let pt0 = ParametricSurface::subs(&surface, u, v); + let pt1 = processor.subs(u, v); + assert_near!(pt0, pt1); + let uder0 = surface.uder(u, v); + let uder1 = processor.uder(u, v); + assert_near!(uder0, uder1); + let vder0 = surface.vder(u, v); + let vder1 = processor.vder(u, v); + assert_near!(vder0, vder1); + let uuder0 = surface.uuder(u, v); + let uuder1 = processor.uuder(u, v); + assert_near!(uuder0, uuder1); + let uvder0 = surface.uvder(u, v); + let uvder1 = processor.uvder(u, v); + assert_near!(uvder0, uvder1); + let vvder0 = surface.vvder(u, v); + let vvder1 = processor.vvder(u, v); + assert_near!(vvder0, vvder1); + let n0 = surface.normal(u, v); + let n1 = processor.normal(u, v); + assert_near!(n0, n1); + } + } + + surface.swap_axes(); + processor.invert(); + assert_eq!(surface.range_tuple(), processor.range_tuple()); + for i in 0..=N { + for j in 0..=N { + let u = i as f64 / N as f64; + let v = j as f64 / N as f64; + let pt0 = ParametricSurface::subs(&surface, u, v); + let pt1 = processor.subs(u, v); + assert_near!(pt0, pt1); + let uder0 = surface.uder(u, v); + let uder1 = processor.uder(u, v); + assert_near!(uder0, uder1); + let vder0 = surface.vder(u, v); + let vder1 = processor.vder(u, v); + assert_near!(vder0, vder1); + let uuder0 = surface.uuder(u, v); + let uuder1 = processor.uuder(u, v); + assert_near!(uuder0, uuder1); + let uvder0 = surface.uvder(u, v); + let uvder1 = processor.uvder(u, v); + assert_near!(uvder0, uvder1); + let vvder0 = surface.vvder(u, v); + let vvder1 = processor.vvder(u, v); + assert_near!(vvder0, vvder1); + let n0 = surface.normal(u, v); + let n1 = processor.normal(u, v); + assert_near!(n0, n1); + } + } + } + + #[test] + fn compatible_with_bspsurface() { (0..3).for_each(|_| exec_compatible_with_bspsurface()) } +} diff --git a/vendor/truck-geometry/src/decorators/revolved_curve.rs b/vendor/truck-geometry/src/decorators/revolved_curve.rs new file mode 100644 index 000000000..ee4bd7c64 --- /dev/null +++ b/vendor/truck-geometry/src/decorators/revolved_curve.rs @@ -0,0 +1,689 @@ +use super::*; +use std::f64::consts::PI; + +impl Revolution { + fn new(origin: Point3, axis: Vector3) -> Self { + Self { + origin, + axis: axis.normalize(), + } + } + #[inline(always)] + fn point_rotation_matrix(self, v: f64) -> Matrix4 { + Matrix4::from_translation(self.origin.to_vec()) + * Matrix4::from_axis_angle(self.axis, Rad(v)) + * Matrix4::from_translation(-self.origin.to_vec()) + } + #[inline(always)] + fn vector_rotation_matrix(self, v: f64) -> Matrix4 { + Matrix4::from_axis_angle(self.axis, Rad(v)) + } + #[inline(always)] + fn derivation_rotation_matrix(self, v: f64) -> Matrix4 { + let n = self.axis; + Matrix3::new( + n[0] * n[0] * f64::sin(v) - f64::sin(v), + n[0] * n[1] * f64::sin(v) + n[2] * f64::cos(v), + n[0] * n[2] * f64::sin(v) - n[1] * f64::cos(v), + n[0] * n[1] * f64::sin(v) - n[2] * f64::cos(v), + n[1] * n[1] * f64::sin(v) - f64::sin(v), + n[1] * n[2] * f64::sin(v) + n[0] * f64::cos(v), + n[0] * n[2] * f64::sin(v) + n[1] * f64::cos(v), + n[1] * n[2] * f64::sin(v) - n[0] * f64::cos(v), + n[2] * n[2] * f64::sin(v) - f64::sin(v), + ) + .into() + } + #[inline(always)] + fn invert(&mut self) { self.axis *= -1.0; } + #[inline(always)] + fn inverse(mut self) -> Self { + self.axis *= -1.0; + self + } + #[inline(always)] + fn contains(self, p: Point3) -> bool { (p - self.origin).cross(self.axis).so_small() } + #[inline(always)] + fn proj_point(&self, p: Point3) -> Point2 { + let r = p - self.origin; + let z = r.dot(self.axis); + let h = r - z * self.axis; + Point2::new(z, h.magnitude()) + } + #[inline(always)] + fn proj_vector(&self, p: Point3, v: Vector3) -> Vector2 { + let r = self.proj_point(p).y; + let vz = v.dot(self.axis); + let vxy = v - vz * self.axis; + let vq = (p - self.origin).dot(vxy) / r; + Vector2::new(vz, vq) + } + #[inline(always)] + fn proj_vector2(&self, p: Point3, v: Vector3, v2: Vector3) -> Vector2 { + let r = self.proj_point(p).y; + let v2z = v2.dot(self.axis); + let v2xy = v2 - v2z * self.axis; + let vz = v.dot(self.axis); + let vxy = v - vz * self.axis; + let a = (vxy.dot(vxy) + (p - self.origin).dot(v2xy)) / r; + let b = f64::powi((p - self.origin).dot(vxy), 2) / (r * r * r); + Vector2::new(v2z, a - b) + } + #[inline(always)] + fn proj_angle(&self, p: Point3, q: Point3) -> f64 { + let (p, q) = (p - self.origin, q - self.origin); + let hp = (p - p.dot(self.axis) * self.axis).normalize(); + let hq = (q - q.dot(self.axis) * self.axis).normalize(); + let t = f64::acos(f64::clamp(hp.dot(hq), -1.0, 1.0)); + match hp.cross(hq).dot(self.axis) < 0.0 { + false => t, + true => 2.0 * PI - t, + } + } +} + +impl ParametricSurface for RevolutedCurve { + type Point = Point3; + type Vector = Vector3; + #[inline(always)] + fn subs(&self, u: f64, v: f64) -> Point3 { + let mat = self.revolution.point_rotation_matrix(v); + mat.transform_point(self.curve.subs(u)) + } + #[inline(always)] + fn uder(&self, u: f64, v: f64) -> Vector3 { + let mat = self.revolution.vector_rotation_matrix(v); + mat.transform_vector(self.curve.der(u)) + } + #[inline(always)] + fn vder(&self, u: f64, v: f64) -> Vector3 { + let pt = self.curve.subs(u); + let radius = self.axis().cross(pt - self.origin()); + let mat = self.revolution.vector_rotation_matrix(v); + mat.transform_vector(radius) + } + #[inline(always)] + fn uuder(&self, u: f64, v: f64) -> Vector3 { + let mat = self.revolution.vector_rotation_matrix(v); + mat.transform_vector(self.curve.der2(u)) + } + #[inline(always)] + fn vvder(&self, u: f64, v: f64) -> Vector3 { + let pt = self.curve.subs(u); + let z = self.revolution.proj_point(pt).x; + let radius = pt - self.origin() - z * self.axis(); + let mat = self.revolution.vector_rotation_matrix(v); + -mat.transform_vector(radius) + } + #[inline(always)] + fn uvder(&self, u: f64, v: f64) -> Vector3 { + let mat = self.revolution.derivation_rotation_matrix(v); + mat.transform_vector(self.curve.der(u)) + } + #[inline(always)] + fn parameter_range(&self) -> (ParameterRange, ParameterRange) { + ( + self.curve.parameter_range(), + (Bound::Included(0.0), Bound::Excluded(2.0 * PI)), + ) + } + #[inline(always)] + fn u_period(&self) -> Option { self.curve.period() } + #[inline(always)] + fn v_period(&self) -> Option { Some(2.0 * PI) } +} + +impl ParametricSurface3D for RevolutedCurve { + #[inline(always)] + fn normal(&self, u: f64, v: f64) -> Vector3 { + let (u0, u1) = self.curve.range_tuple(); + let (uder, vder) = if u.near(&u0) { + let pt = self.curve.subs(u); + let radius = self.axis().cross(pt - self.origin()); + if radius.so_small() { + let uder = self.curve.der(u); + (uder, self.axis().cross(uder)) + } else { + (self.uder(u, v), self.vder(u, v)) + } + } else if u.near(&u1) { + let pt = self.curve.subs(u); + let radius = self.axis().cross(pt - self.origin()); + if radius.so_small() { + let uder = self.curve.der(u); + (uder, uder.cross(self.axis())) + } else { + (self.uder(u, v), self.vder(u, v)) + } + } else { + (self.uder(u, v), self.vder(u, v)) + }; + uder.cross(vder).normalize() + } +} + +impl BoundedSurface for RevolutedCurve {} + +impl Invertible for RevolutedCurve { + #[inline(always)] + fn invert(&mut self) { self.revolution.invert() } + #[inline(always)] + fn inverse(&self) -> Self { + RevolutedCurve { + curve: self.curve.clone(), + revolution: self.revolution.inverse(), + } + } +} + +#[derive(Clone, Debug)] +struct ProjectedCurve { + curve: C, + revolution: Revolution, +} + +impl ParametricCurve for ProjectedCurve { + type Point = Point2; + type Vector = Vector2; + #[inline(always)] + fn subs(&self, t: f64) -> Self::Point { self.revolution.proj_point(self.curve.subs(t)) } + #[inline(always)] + fn der(&self, t: f64) -> Self::Vector { + self.revolution + .proj_vector(self.curve.subs(t), self.curve.der(t)) + } + #[inline(always)] + fn der2(&self, t: f64) -> Self::Vector { + self.revolution + .proj_vector2(self.curve.subs(t), self.curve.der(t), self.curve.der2(t)) + } + #[inline(always)] + fn parameter_range(&self) -> ParameterRange { self.curve.parameter_range() } + #[inline(always)] + fn period(&self) -> Option { self.curve.period() } +} + +impl BoundedCurve for ProjectedCurve {} + +impl SearchParameter for ProjectedCurve { + type Point = Point2; + fn search_parameter>( + &self, + point: Self::Point, + hint: H, + trials: usize, + ) -> Option { + let hint = match hint.into() { + SPHint1D::Parameter(t) => t, + SPHint1D::Range(x, y) => { + algo::curve::presearch(self, point, (x, y), PRESEARCH_DIVISION) + } + SPHint1D::None => { + algo::curve::presearch(self, point, self.range_tuple(), PRESEARCH_DIVISION) + } + }; + algo::curve::search_parameter(self, point, hint, trials) + } +} + +impl SearchNearestParameter for ProjectedCurve { + type Point = Point2; + fn search_nearest_parameter>( + &self, + point: Self::Point, + hint: H, + trials: usize, + ) -> Option { + let hint = match hint.into() { + SPHint1D::Parameter(t) => t, + SPHint1D::Range(x, y) => { + algo::curve::presearch(self, point, (x, y), PRESEARCH_DIVISION) + } + SPHint1D::None => { + algo::curve::presearch(self, point, self.range_tuple(), PRESEARCH_DIVISION) + } + }; + algo::curve::search_nearest_parameter(self, point, hint, trials) + } +} + +impl RevolutedCurve { + /// Creates a surface by revoluting a curve. + #[inline(always)] + pub fn by_revolution(curve: C, origin: Point3, axis: Vector3) -> Self { + RevolutedCurve { + curve, + revolution: Revolution::new(origin, axis), + } + } + /// Returns the curve before revoluted. + #[inline(always)] + pub const fn entity_curve(&self) -> &C { &self.curve } + /// Into the curve before revoluted. + #[inline(always)] + pub fn into_entity_curve(self) -> C { self.curve } + /// Returns origin of revolution + #[inline(always)] + pub const fn origin(&self) -> Point3 { self.revolution.origin } + /// Returns axis of revolution + #[inline(always)] + pub const fn axis(&self) -> Vector3 { self.revolution.axis } +} + +impl RevolutedCurve { + /// Returns true if the front point of the curve is on the axis of rotation. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let line = BSplineCurve::new( + /// KnotVec::bezier_knot(1), + /// vec![Point3::new(0.0, 0.0, 0.0), Point3::new(0.0, 0.0, 1.0)], + /// ); + /// let surface0 = RevolutedCurve::by_revolution(line.clone(), Point3::origin(), Vector3::unit_y()); + /// assert!(surface0.is_front_fixed()); + /// let surface1 = RevolutedCurve::by_revolution(line, Point3::new(1.0, 0.0, 0.0), Vector3::unit_y()); + /// assert!(!surface1.is_front_fixed()); + /// ``` + #[inline(always)] + pub fn is_front_fixed(&self) -> bool { self.revolution.contains(self.curve.front()) } + /// Returns true if the back point of the curve is on the axis of rotation. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let line = BSplineCurve::new( + /// KnotVec::bezier_knot(1), + /// vec![Point3::new(0.0, 0.0, 1.0), Point3::new(0.0, 0.0, 0.0)], + /// ); + /// let surface0 = RevolutedCurve::by_revolution(line.clone(), Point3::origin(), Vector3::unit_y()); + /// assert!(surface0.is_back_fixed()); + /// let surface1 = RevolutedCurve::by_revolution(line, Point3::new(1.0, 0.0, 0.0), Vector3::unit_y()); + /// assert!(!surface1.is_back_fixed()); + /// ``` + #[inline(always)] + pub fn is_back_fixed(&self) -> bool { self.revolution.contains(self.curve.back()) } +} + +impl SearchParameter for RevolutedCurve { + type Point = Point3; + fn search_parameter>( + &self, + point: Point3, + hint: H, + trials: usize, + ) -> Option<(f64, f64)> { + let (t0, t1) = self.curve.range_tuple(); + if self.is_front_fixed() && self.curve.front().near(&point) { + match hint.into() { + SPHint2D::Parameter(_, y) => Some((t0, y)), + SPHint2D::Range((_, y), _) => Some((t0, y)), + SPHint2D::None => Some((t0, 0.0)), + } + } else if self.is_back_fixed() && self.curve.back().near(&point) { + match hint.into() { + SPHint2D::Parameter(_, y) => Some((t1, y)), + SPHint2D::Range(_, (_, y)) => Some((t1, y)), + SPHint2D::None => Some((t1, 2.0 * PI)), + } + } else { + let proj_curve = ProjectedCurve { + curve: &self.curve, + revolution: self.revolution, + }; + let p = self.revolution.proj_point(point); + let hint0 = match hint.into() { + SPHint2D::Parameter(x, _) => SPHint1D::Parameter(x), + SPHint2D::Range((x0, _), (x1, _)) => SPHint1D::Range(x0, x1), + SPHint2D::None => SPHint1D::None, + }; + let t = proj_curve.search_parameter(p, hint0, trials)?; + let p = self.curve.subs(t); + let ang = self.revolution.proj_angle(p, point); + match self.subs(t, ang).near(&point) { + true => Some((t, ang)), + false => None, + } + } + } +} + +impl SearchNearestParameter for RevolutedCurve { + type Point = Point3; + fn search_nearest_parameter>( + &self, + point: Point3, + hint: H, + trials: usize, + ) -> Option<(f64, f64)> { + let (t0, t1) = self.curve.range_tuple(); + let on_axis = move |o: Point3, normal: Vector3| { + let op = point - o; + op.cross(self.revolution.axis).so_small() && op.dot(normal) >= 0.0 + }; + if self.is_front_fixed() && on_axis(self.curve.front(), self.normal(t0, 0.0)) { + match hint.into() { + SPHint2D::Parameter(_, y) => Some((t0, y)), + SPHint2D::Range((_, y), _) => Some((t0, y)), + SPHint2D::None => Some((t0, 0.0)), + } + } else if self.is_back_fixed() && on_axis(self.curve.back(), self.normal(t1, 0.0)) { + match hint.into() { + SPHint2D::Parameter(_, y) => Some((t1, y)), + SPHint2D::Range(_, (_, y)) => Some((t1, y)), + SPHint2D::None => Some((t1, 2.0 * PI)), + } + } else { + let proj_curve = ProjectedCurve { + curve: &self.curve, + revolution: self.revolution, + }; + let p = self.revolution.proj_point(point); + let hint0 = match hint.into() { + SPHint2D::Parameter(x, _) => SPHint1D::Parameter(x), + SPHint2D::Range((x0, _), (x1, _)) => SPHint1D::Range(x0, x1), + SPHint2D::None => SPHint1D::None, + }; + let t = proj_curve.search_nearest_parameter(p, hint0, trials)?; + let p = self.curve.subs(t); + Some((t, self.revolution.proj_angle(p, point))) + } + } +} + +fn sub_include( + surface: &RevolutedCurve, + curve: &C1, + knots: &[f64], + degree: usize, +) -> bool +where + C0: ParametricCurve3D + BoundedCurve, + C1: ParametricCurve3D + BoundedCurve, +{ + let first = curve.subs(knots[0]); + let mut hint = match surface.search_parameter(first, None, INCLUDE_CURVE_TRIALS) { + Some(hint) => hint, + None => return false, + }; + knots + .windows(2) + .flat_map(move |knot| { + (1..=degree).map(move |i| { + let s = i as f64 / degree as f64; + knot[0] * (1.0 - s) + knot[1] * s + }) + }) + .all(move |t| { + let pt = ParametricCurve::subs(curve, t); + surface + .search_parameter(pt, Some(hint), INCLUDE_CURVE_TRIALS) + .or_else(|| surface.search_parameter(pt, None, INCLUDE_CURVE_TRIALS)) + .map(|res| hint = res) + .is_some() + }) +} + +impl<'a> IncludeCurve> for RevolutedCurve<&'a BSplineCurve> { + fn include(&self, curve: &BSplineCurve) -> bool { + let knots = curve.knot_vec().to_single_multi().0; + let degree = usize::max(2, usize::max(curve.degree(), self.curve.degree())); + sub_include(self, curve, &knots, degree) + } +} + +impl IncludeCurve> for RevolutedCurve> { + fn include(&self, curve: &BSplineCurve) -> bool { + let knots = curve.knot_vec().to_single_multi().0; + let degree = usize::max(2, usize::max(curve.degree(), self.curve.degree())); + sub_include(self, curve, &knots, degree) + } +} + +impl<'a> IncludeCurve> for RevolutedCurve<&'a NurbsCurve> { + fn include(&self, curve: &BSplineCurve) -> bool { + let knots = curve.knot_vec().to_single_multi().0; + let degree = curve.degree() + usize::max(2, self.curve.degree()); + sub_include(self, curve, &knots, degree) + } +} + +impl IncludeCurve> for RevolutedCurve> { + fn include(&self, curve: &BSplineCurve) -> bool { + let knots = curve.knot_vec().to_single_multi().0; + let degree = curve.degree() + usize::max(2, self.curve.degree()); + sub_include(self, curve, &knots, degree) + } +} + +impl<'a> IncludeCurve> for RevolutedCurve<&'a BSplineCurve> { + fn include(&self, curve: &NurbsCurve) -> bool { + let knots = curve.knot_vec().to_single_multi().0; + let degree = curve.degree() + usize::max(2, self.curve.degree()); + sub_include(self, curve, &knots, degree) + } +} + +impl IncludeCurve> for RevolutedCurve> { + fn include(&self, curve: &NurbsCurve) -> bool { + let knots = curve.knot_vec().to_single_multi().0; + let degree = curve.degree() + usize::max(2, self.curve.degree()); + sub_include(self, curve, &knots, degree) + } +} + +impl<'a> IncludeCurve> for RevolutedCurve<&'a NurbsCurve> { + fn include(&self, curve: &NurbsCurve) -> bool { + let knots = curve.knot_vec().to_single_multi().0; + let degree = curve.degree() + usize::max(2, self.curve.degree()); + sub_include(self, curve, &knots, degree) + } +} + +impl IncludeCurve> for RevolutedCurve> { + fn include(&self, curve: &NurbsCurve) -> bool { + let knots = curve.knot_vec().to_single_multi().0; + let degree = curve.degree() + usize::max(2, self.curve.degree()); + sub_include(self, curve, &knots, degree) + } +} + +impl ParameterDivision2D for RevolutedCurve +where C: ParametricCurve3D + ParameterDivision1D +{ + fn parameter_division( + &self, + (urange, vrange): ((f64, f64), (f64, f64)), + tol: f64, + ) -> (Vec, Vec) { + let curve_division = self.curve.parameter_division(urange, tol); + let max = curve_division + .1 + .into_iter() + .fold(0.0, |max2, pt| { + let h = self.revolution.proj_point(pt).y; + f64::max(max2, h) + }) + .sqrt(); + let acos = f64::acos(1.0 - tol / max); + let div: usize = 1 + ((vrange.1 - vrange.0) / acos).floor() as usize; + let circle_division = (0..=div) + .map(|j| vrange.0 + (vrange.1 - vrange.0) * j as f64 / div as f64) + .collect(); + (curve_division.0, circle_division) + } +} + +#[test] +fn revolve_test() { + let pt0 = Point3::new(0.0, 2.0, 1.0); + let pt1 = Point3::new(1.0, 0.0, 0.0); + let curve = BSplineCurve::new(KnotVec::bezier_knot(1), vec![pt0, pt1]); + let surface = RevolutedCurve::by_revolution(curve, Point3::origin(), Vector3::unit_y()); + const N: usize = 100; + for i in 0..=N { + for j in 0..=N { + let u = i as f64 / N as f64; + let v = 2.0 * PI * j as f64 / N as f64; + let res = surface.subs(u, v); + let ans = Point3::new( + u * f64::cos(v) + (1.0 - u) * f64::sin(v), + 2.0 * (1.0 - u), + -u * f64::sin(v) + (1.0 - u) * f64::cos(v), + ); + assert_near!(res, ans); + let res_uder = surface.uder(u, v); + let ans_uder = + Vector3::new(f64::cos(v) - f64::sin(v), -2.0, -f64::sin(v) - f64::cos(v)); + assert_near!(res_uder, ans_uder); + let res_vder = surface.vder(u, v); + let ans_vder = Vector3::new( + -u * f64::sin(v) + (1.0 - u) * f64::cos(v), + 0.0, + -u * f64::cos(v) - (1.0 - u) * f64::sin(v), + ); + assert_near!(res_vder, ans_vder); + let res_uuder = surface.uuder(u, v); + let ans_uuder = Vector3::zero(); + assert_near!(res_uuder, ans_uuder); + let res_uvder = surface.uvder(u, v); + let ans_uvder = + Vector3::new(-f64::sin(v) - f64::cos(v), 0.0, -f64::cos(v) + f64::sin(v)); + assert_near!(res_uvder, ans_uvder); + let res_vvder = surface.vvder(u, v); + let ans_vvder = Vector3::new( + -u * f64::cos(v) - (1.0 - u) * f64::sin(v), + 0.0, + u * f64::sin(v) - (1.0 - u) * f64::cos(v), + ); + assert_near!(res_vvder, ans_vvder); + let normal = surface.normal(u, v); + assert!(normal.dot(res_uder).so_small()); + assert!(normal.dot(res_vder).so_small()); + } + } +} + +#[test] +fn search_parameter() { + let line = BSplineCurve::new( + KnotVec::bezier_knot(1), + vec![Point3::new(0.0, 2.0, 1.0), Point3::new(1.0, 0.0, 0.0)], + ); + let surface = RevolutedCurve::by_revolution(line, Point3::origin(), Vector3::unit_y()); + let pt = Point3::new(-0.5, 1.0, 0.5); + let (u, v) = surface.search_parameter(pt, Some((0.4, 1.2)), 100).unwrap(); + assert_near!(surface.subs(u, v), pt); +} + +#[test] +fn search_parameter_with_fixed_points() { + let line = BSplineCurve::new( + KnotVec::bezier_knot(2), + vec![ + Point3::new(0.0, 1.0, 0.0), + Point3::new(0.0, 0.0, 1.0), + Point3::new(0.0, -1.0, 0.0), + ], + ); + let surface = RevolutedCurve::by_revolution(line, Point3::origin(), Vector3::unit_y()); + + let (u, v) = surface + .search_parameter(Point3::new(0.0, 1.0, 0.0), Some((0.5, 0.3)), 10) + .unwrap(); + assert_near!(Vector2::new(u, v), Vector2::new(0.0, 0.3)); + + let (u, v) = surface + .search_parameter(Point3::new(0.0, -1.0, 0.0), Some((0.5, 0.3)), 10) + .unwrap(); + assert_near!(Vector2::new(u, v), Vector2::new(1.0, 0.3)); +} + +#[test] +fn search_nearest_parameter() { + let line = BSplineCurve::new( + KnotVec::bezier_knot(1), + vec![Point3::new(0.0, 2.0, 1.0), Point3::new(1.0, 0.0, 0.0)], + ); + let surface = RevolutedCurve::by_revolution(line, Point3::origin(), Vector3::unit_y()); + let pt = surface.subs(0.4, 1.2) + 0.1 * surface.normal(0.4, 1.2); + let (u, v) = surface + .search_nearest_parameter(pt, Some((0.4, 1.2)), 100) + .unwrap(); + assert_near!(Vector2::new(u, v), Vector2::new(0.4, 1.2)); +} + +#[test] +fn search_nearest_parameter_with_fixed_points() { + let line = BSplineCurve::new( + KnotVec::bezier_knot(2), + vec![ + Point3::new(0.0, 1.0, 0.0), + Point3::new(0.0, 0.0, 1.0), + Point3::new(0.0, -1.0, 0.0), + ], + ); + let surface = RevolutedCurve::by_revolution(line, Point3::origin(), Vector3::unit_y()); + + let (u, v) = surface + .search_nearest_parameter(Point3::new(0.0, 2.0, 0.0), Some((0.5, 0.3)), 10) + .unwrap(); + assert_near!(Vector2::new(u, v), Vector2::new(0.0, 0.3)); + + let (u, v) = surface + .search_nearest_parameter(Point3::new(0.0, -2.0, 0.0), Some((0.5, 0.3)), 10) + .unwrap(); + assert_near!(Vector2::new(u, v), Vector2::new(1.0, 0.3)); +} + +#[test] +fn include_curve_normal() { + let line = BSplineCurve::new( + KnotVec::bezier_knot(1), + vec![Point3::new(0.0, 0.0, 0.0), Point3::new(0.0, 2.0, 2.0)], + ); + let surface = RevolutedCurve::by_revolution(line, Point3::origin(), Vector3::unit_y()); + let parabola = BSplineCurve::new( + KnotVec::bezier_knot(2), + vec![ + Point3::new(1.0, 1.0, 0.0), + Point3::new(0.0, 0.0, 1.0), + Point3::new(-1.0, 1.0, 0.0), + ], + ); + assert!(surface.include(¶bola)); +} + +#[test] +fn include_curve_abnormal0() { + let line = BSplineCurve::new( + KnotVec::bezier_knot(1), + vec![Point3::new(0.0, 0.0, 0.0), Point3::new(0.0, 2.0, 2.0)], + ); + let surface = RevolutedCurve::by_revolution(line, Point3::origin(), Vector3::unit_y()); + let parabola = BSplineCurve::new( + KnotVec::bezier_knot(2), + vec![ + Point3::new(1.0, 1.0, 0.0), + Point3::new(0.0, 0.0, 2.0), + Point3::new(-1.0, 1.0, 0.0), + ], + ); + assert!(!surface.include(¶bola)); +} + +#[test] +fn include_curve_abnormal1() { + let curve = NurbsCurve::new(BSplineCurve::new( + KnotVec::bezier_knot(3), + vec![ + Vector4::new(0.0, 3.0, 0.0, 1.0), + Vector4::new(0.0, 3.0, 3.0, 0.5), + Vector4::new(0.0, 0.0, 0.0, 1.0), + Vector4::new(0.0, 0.0, 3.0, 1.0), + ], + )); + let pt0 = curve.subs(0.2); + let pt1 = curve.subs(0.6); + let surface = RevolutedCurve::by_revolution(curve, Point3::origin(), Vector3::unit_y()); + let line = BSplineCurve::new(KnotVec::bezier_knot(1), vec![pt0, pt1]); + assert!(!surface.include(&line)); +} diff --git a/vendor/truck-geometry/src/decorators/trimmied_curve.rs b/vendor/truck-geometry/src/decorators/trimmied_curve.rs new file mode 100644 index 000000000..708d67a6a --- /dev/null +++ b/vendor/truck-geometry/src/decorators/trimmied_curve.rs @@ -0,0 +1,73 @@ +use super::*; + +impl TrimmedCurve { + /// constructor + #[inline(always)] + pub const fn new(curve: C, range: (f64, f64)) -> Self { Self { curve, range } } + /// Returns the reference of non-trimmed curve + #[inline(always)] + pub const fn curve(&self) -> &C { &self.curve } + /// Returns the mutable reference of non-trimmed curve + #[inline(always)] + pub fn curve_mut(&mut self) -> &mut C { &mut self.curve } +} + +impl ParametricCurve for TrimmedCurve { + type Point = C::Point; + type Vector = C::Vector; + #[inline(always)] + fn subs(&self, t: f64) -> Self::Point { self.curve.subs(t) } + #[inline(always)] + fn der(&self, t: f64) -> Self::Vector { self.curve.der(t) } + #[inline(always)] + fn der2(&self, t: f64) -> Self::Vector { self.curve.der2(t) } + #[inline(always)] + fn period(&self) -> Option { self.curve.period() } + #[inline(always)] + fn parameter_range(&self) -> ParameterRange { + (Bound::Included(self.range.0), Bound::Included(self.range.1)) + } +} + +impl BoundedCurve for TrimmedCurve {} + +impl Cut for TrimmedCurve { + fn cut(&mut self, t: f64) -> Self { + let (t0, t1) = self.range; + self.range = (t0, t); + Self::new(self.curve.clone(), (t, t1)) + } +} + +impl> SearchNearestParameter for TrimmedCurve { + type Point = C::Point; + #[inline(always)] + fn search_nearest_parameter>( + &self, + pt: C::Point, + hint: H, + trials: usize, + ) -> Option { + self.curve.search_nearest_parameter(pt, hint, trials) + } +} + +impl> SearchParameter for TrimmedCurve { + type Point = C::Point; + #[inline(always)] + fn search_parameter>( + &self, + pt: C::Point, + hint: H, + trials: usize, + ) -> Option { + self.curve.search_parameter(pt, hint, trials) + } +} + +impl ParameterDivision1D for TrimmedCurve { + type Point = C::Point; + fn parameter_division(&self, range: (f64, f64), tol: f64) -> (Vec, Vec) { + self.curve.parameter_division(range, tol) + } +} diff --git a/vendor/truck-geometry/src/errors.rs b/vendor/truck-geometry/src/errors.rs new file mode 100644 index 000000000..5d1978e80 --- /dev/null +++ b/vendor/truck-geometry/src/errors.rs @@ -0,0 +1,190 @@ +use thiserror::Error; + +/// Error handler for [`Error`](./errors/enum.Error.html) +pub type Result = std::result::Result; + +/// Geometrical Errors +#[derive(Debug, PartialEq, Error)] +pub enum Error { + /// The following operations are failed if the knot vector has zero range. + /// * Creating `BSplineCurve` or `BSplineSurface`, + /// * Calculating bspline basis functions, or + /// * Normalizing the knot vector. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// use truck_geometry::errors::Error; + /// let mut knot_vec = KnotVec::from(vec![0.0, 0.0, 0.0, 0.0]); + /// assert_eq!(knot_vec.try_normalize(), Err(Error::ZeroRange)); + /// assert_eq!(knot_vec.try_bspline_basis_functions(1, 0.0), Err(Error::ZeroRange)); + /// + /// let ctrl_pts = vec![Vector2::new(0.0, 0.0), Vector2::new(1.0, 1.0)]; + /// assert!(matches!(BSplineCurve::try_new(knot_vec, ctrl_pts), Err(Error::ZeroRange))); + /// ``` + #[error("This knot vector consists single value.")] + ZeroRange, + /// Fails concatting two knot vectors if there is a difference between the back knot of + /// the former knot vector and the front knot of the latter knot vector. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// use truck_geometry::errors::Error; + /// let mut knot_vec0 = KnotVec::from(vec![0.0, 0.0, 1.0, 1.0]); + /// let knot_vec1 = KnotVec::from(vec![2.0, 2.0, 3.0, 3.0]); + /// assert!(matches!(knot_vec0.try_concat(&knot_vec1, 1), Err(Error::DifferentBackFront(1.0, 2.0)))); + /// ``` + #[error("Cannot concat two knot vectors whose the back of the first and the front of the second are different. +the back of the first knot vector: {0} +the front of the second knot vector: {1}")] + DifferentBackFront(f64, f64), + /// If the knot vector is not clamped, then one cannot concat the vector with another knot vector. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// use truck_geometry::errors::Error; + /// let mut knot_vec0 = KnotVec::from(vec![0.0, 0.0, 1.0, 1.0]); + /// let knot_vec1 = KnotVec::from(vec![2.0, 2.0, 3.0, 3.0]); + /// assert!(matches!(knot_vec0.try_concat(&knot_vec1, 2), Err(Error::NotClampedKnotVector))); + /// ``` + #[error("This knot vector is not clamped.")] + NotClampedKnotVector, + /// Creating a knot vector by `KnotVec::try_from()` is failed if the given vector is not sorted. + /// `>>::from()` does not panic by this error because sorts the given + /// vector before creating the knot vector. So, `KnotVec::try_from()` is more efficient than + /// `>>::from()`. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// use truck_geometry::errors::Error; + /// use std::convert::*; + /// + /// assert!(matches!(KnotVec::try_from(vec![1.0, 3.0, 0.0, 2.0]), Err(Error::NotSortedVector))); + /// assert_eq!( + /// >>::from(vec![1.0, 3.0, 0.0, 2.0]), + /// KnotVec::try_from(vec![0.0, 1.0, 2.0, 3.0]).unwrap(), + /// ); + /// ``` + #[error("This knot vector is not sorted.")] + NotSortedVector, + /// The given degree is too large to calculate bspline basis functions. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// use truck_geometry::errors::Error; + /// + /// // a knot vector with length = 4. + /// let knot_vec = KnotVec::from(vec![0.0, 0.0, 1.0, 1.0]); + /// assert!(matches!( + /// knot_vec.try_bspline_basis_functions(5, 0.5), + /// Err(Error::TooLargeDegree(4, 5)), + /// )); + /// ``` + #[error( + "This knot vector is too short compared to the degree. +the length of knot_vec: {0} +the degree: {1}" + )] + TooLargeDegree(usize, usize), + /// The specified knot cannot be removed. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// use truck_geometry::errors::Error; + /// let knot_vec = KnotVec::bezier_knot(2); + /// let ctrl_pts = vec![Vector2::new(-1.0, 1.0), Vector2::new(0.0, -1.0), Vector2::new(1.0, 1.0)]; + /// let mut bspcurve = BSplineCurve::new(knot_vec, ctrl_pts); + /// let org_curve = bspcurve.clone(); + /// bspcurve.add_knot(0.5).add_knot(0.5).add_knot(0.25).add_knot(0.75); + /// assert!(bspcurve.try_remove_knot(3).is_ok()); + /// assert!(matches!(bspcurve.try_remove_knot(2), Err(Error::CannotRemoveKnot(2)))); + /// ``` + #[error("The {0}th knot in this knot vector cannot be removed.")] + CannotRemoveKnot(usize), + /// Empty vector of points cannot construct B-spline. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// use truck_geometry::errors::Error; + /// + /// let knot_vec = KnotVec::bezier_knot(2); + /// let ctrl_pts: Vec = Vec::new(); + /// assert!(matches!( + /// BSplineCurve::try_new(knot_vec, ctrl_pts), + /// Err(Error::EmptyControlPoints), + /// )); + /// ``` + #[error("The control point must not be empty.")] + EmptyControlPoints, + /// The knot vector of B-spline curves or B-spline surfaces must be longer than the corresponded + /// array of control points. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// use truck_geometry::errors::Error; + /// let knot_vec = KnotVec::from(vec![0.0, 1.0, 2.0]); + /// let ctrl_pts = vec![Vector2::new(0.0, 0.0), Vector2::new(0.0, 0.0), Vector2::new(0.0, 0.0), Vector2::new(0.0, 0.0)]; + /// assert!(matches!( + /// BSplineCurve::try_new(knot_vec, ctrl_pts), + /// Err(Error::TooShortKnotVector(3, 4)), + /// )); + /// ``` + #[error( + "The knot vector must be more than the control points. +the length of knot_vec: {0} +the number of control points: {1}" + )] + TooShortKnotVector(usize, usize), + /// The length of the given arrays of control points to create a B-spline surface is irregular. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// use truck_geometry::errors::Error; + /// let knot_vecs = (KnotVec::bezier_knot(2), KnotVec::bezier_knot(2)); + /// let ctrl_pts = vec![ + /// vec![Vector2::new(1.0, 2.0), Vector2::new(1.0, 2.0)], // length = 2 + /// vec![Vector2::new(1.0, 2.0)] // length = 1 + /// ]; + /// assert!(matches!( + /// BSplineSurface::try_new(knot_vecs, ctrl_pts), + /// Err(Error::IrregularControlPoints), + /// )); + /// ``` + #[error("The number of control points is irregular")] + IrregularControlPoints, + /// The vector of control points and the one of weights have different length. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// use truck_geometry::errors::Error; + /// let bspcurve = BSplineCurve::new( + /// KnotVec::bezier_knot(2), + /// vec![Point2::new(0.0, 1.0), Point2::new(2.0, 3.0), Point2::new(4.0, 5.0)], + /// ); + /// let weights = vec![1.0, 2.0]; // less than control points + /// + /// assert!(matches!( + /// NurbsCurve::::try_from_bspline_and_weights(bspcurve, weights), + /// Err(Error::DifferentLength), + /// )); + /// ``` + #[error("The vector of control points and the one of weights have different length.")] + DifferentLength, +} + +#[test] +#[rustfmt::skip] +fn print_messages() { + use std::io::Write; + let stderr = &mut std::io::stderr(); + writeln!(stderr, "****** test of the expressions of error messages ******\n").unwrap(); + writeln!(stderr, "{}\n", Error::ZeroRange).unwrap(); + writeln!(stderr, "{}\n", Error::DifferentBackFront(0.0, 1.0)).unwrap(); + writeln!(stderr, "{}\n", Error::NotClampedKnotVector).unwrap(); + writeln!(stderr, "{}\n", Error::NotSortedVector).unwrap(); + writeln!(stderr, "{}\n", Error::TooLargeDegree(1, 2)).unwrap(); + writeln!(stderr, "{}\n", Error::CannotRemoveKnot(7)).unwrap(); + writeln!(stderr, "{}\n", Error::EmptyControlPoints).unwrap(); + writeln!(stderr, "{}\n", Error::TooShortKnotVector(1, 2)).unwrap(); + writeln!(stderr, "{}\n", Error::IrregularControlPoints).unwrap(); + writeln!(stderr, "*******************************************************").unwrap(); +} diff --git a/vendor/truck-geometry/src/lib.rs b/vendor/truck-geometry/src/lib.rs new file mode 100644 index 000000000..50ac5ff29 --- /dev/null +++ b/vendor/truck-geometry/src/lib.rs @@ -0,0 +1,52 @@ +//! Geometrical structs: knot vector, B-spline and NURBS + +#![cfg_attr(not(debug_assertions), deny(warnings))] +#![deny(clippy::all, rust_2018_idioms)] +#![warn( + missing_docs, + missing_debug_implementations, + trivial_casts, + trivial_numeric_casts, + unsafe_code, + unstable_features, + unused_import_braces, + unused_qualifications +)] + +use serde::{Deserialize, Serialize}; +use std::{fmt::Debug, ops::Bound}; +use truck_base::bounding_box::Bounded; + +const INCLUDE_CURVE_TRIALS: usize = 100; +const PRESEARCH_DIVISION: usize = 50; + +/// re-export `truck_base` +pub mod base { + pub use truck_base::bounding_box::BoundingBox; + pub use truck_base::cgmath64::*; + pub use truck_base::tolerance::*; + pub use truck_base::{assert_near, assert_near2}; + pub use truck_base::{hash, hash::HashGen}; + pub use truck_geotrait::*; +} +/// Declares the nurbs +pub mod nurbs; + +/// Enumerats `Error`. +pub mod errors; + +/// Declares the specified gememetric items: Plane, Sphere, and so on. +pub mod specifieds; + +/// Declares some decorators +pub mod decorators; + +/// re-export all modules. +pub mod prelude { + use crate::*; + pub use base::*; + pub use decorators::*; + pub use errors::*; + pub use nurbs::*; + pub use specifieds::*; +} diff --git a/vendor/truck-geometry/src/nurbs/bspcurve.rs b/vendor/truck-geometry/src/nurbs/bspcurve.rs new file mode 100644 index 000000000..50eb46bda --- /dev/null +++ b/vendor/truck-geometry/src/nurbs/bspcurve.rs @@ -0,0 +1,1488 @@ +use super::*; +use crate::errors::Error; +use std::ops::*; + +impl

BSplineCurve

{ + /// constructor. + /// # Arguments + /// * `knot_vec` - the knot vector + /// * `control_points` - the vector of the control points + /// # Panics + /// Panics occurs if: + /// * There are no control points. + /// * The number of knots is more than the one of control points. + /// * The range of the knot vector is zero. + pub fn new(knot_vec: KnotVec, control_points: Vec

) -> BSplineCurve

{ + BSplineCurve::try_new(knot_vec, control_points).unwrap_or_else(|e| panic!("{}", e)) + } + + /// constructor. + /// # Arguments + /// * `knot_vec` - the knot vector + /// * `control_points` - the vector of the control points + /// # Failures + /// * If there are no control points, returns [`Error::EmptyControlPoints`]. + /// * If the number of knots is more than the one of control points, returns [`Error::TooShortKnotVector`]. + /// * If the range of the knot vector is zero, returns [`Error::ZeroRange`]. + /// + /// [`Error::EmptyControlPoints`]: errors/enum.Error.html#variant.EmptyControlPoints + /// [`Error::TooShortKnotVector`]: errors/enum.Error.html#variant.TooShortKnotVector + /// [`Error::ZeroRange`]: errors/enum.Error.html#variant.ZeroRange + pub fn try_new(knot_vec: KnotVec, control_points: Vec

) -> Result> { + if control_points.is_empty() { + Err(Error::EmptyControlPoints) + } else if knot_vec.len() <= control_points.len() { + Err(Error::TooShortKnotVector( + knot_vec.len(), + control_points.len(), + )) + } else if knot_vec.range_length().so_small() { + Err(Error::ZeroRange) + } else { + Ok(BSplineCurve::new_unchecked(knot_vec, control_points)) + } + } + + /// constructor. + /// # Arguments + /// * `knot_vec` - the knot vector + /// * `control_points` - the vector of the control points + /// # Remarks + /// This method is prepared only for performance-critical development and is not recommended. + /// This method does NOT check the rules for constructing B-spline curve. + /// The programmer must guarantee these conditions before using this method. + #[inline(always)] + pub const fn new_unchecked(knot_vec: KnotVec, control_points: Vec

) -> BSplineCurve

{ + Self { + knot_vec, + control_points, + } + } + + /// constructor. + /// # Arguments + /// * `knot_vec` - the knot vector + /// * `control_points` - the vector of the control points + /// # Remarks + /// This method checks the rules for constructing B-spline curve in the debug mode. + /// The programmer must guarantee these conditions before using this method. + #[inline(always)] + pub fn debug_new(knot_vec: KnotVec, control_points: Vec

) -> BSplineCurve

{ + match cfg!(debug_assertions) { + true => Self::new(knot_vec, control_points), + false => Self::new_unchecked(knot_vec, control_points), + } + } + + /// Returns the reference of the knot vector + #[inline(always)] + pub const fn knot_vec(&self) -> &KnotVec { &self.knot_vec } + + /// Returns the `idx`th knot + #[inline(always)] + pub fn knot(&self, idx: usize) -> f64 { self.knot_vec[idx] } + + /// Returns the reference of the control points. + #[inline(always)] + pub const fn control_points(&self) -> &Vec

{ &self.control_points } + + /// Returns the reference of the control point corresponding to the index `idx`. + #[inline(always)] + pub fn control_point(&self, idx: usize) -> &P { &self.control_points[idx] } + + /// Returns the mutable reference of the control point corresponding to index `idx`. + #[inline(always)] + pub fn control_point_mut(&mut self, idx: usize) -> &mut P { &mut self.control_points[idx] } + /// Returns the iterator on all control points + #[inline(always)] + pub fn control_points_mut(&mut self) -> impl Iterator { + self.control_points.iter_mut() + } + + /// Apply the given transformation to all control points. + #[inline(always)] + pub fn transform_control_points(&mut self, f: F) { + self.control_points.iter_mut().for_each(f) + } + + /// Returns the degree of B-spline curve + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vec = KnotVec::bezier_knot(2); + /// let ctrl_pts = vec![Vector2::new(1.0, 2.0), Vector2::new(2.0, 3.0), Vector2::new(3.0, 4.0)]; + /// let bspcurve = BSplineCurve::new(knot_vec, ctrl_pts); + /// assert_eq!(bspcurve.degree(), 2); + /// ``` + #[inline(always)] + pub fn degree(&self) -> usize { self.knot_vec.len() - self.control_points.len() - 1 } + /// Inverts a curve + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vec = KnotVec::uniform_knot(2, 2); + /// let ctrl_pts = vec![Vector2::new(1.0, 2.0), Vector2::new(2.0, 3.0), Vector2::new(3.0, 4.0), Vector2::new(4.0, 5.0)]; + /// let bspcurve0 = BSplineCurve::new(knot_vec, ctrl_pts); + /// let mut bspcurve1 = bspcurve0.clone(); + /// bspcurve1.invert(); + /// + /// const N: usize = 100; // sample size + /// for i in 0..=N { + /// let t = (i as f64) / (N as f64); + /// assert_near2!(bspcurve0.subs(t), bspcurve1.subs(1.0 - t)); + /// } + /// ``` + #[inline(always)] + pub fn invert(&mut self) -> &mut Self { + self.knot_vec.invert(); + self.control_points.reverse(); + self + } + + /// Returns whether the knot vector is clamped or not. + #[inline(always)] + pub fn is_clamped(&self) -> bool { self.knot_vec.is_clamped(self.degree()) } + + /// Normalizes the knot vector + #[inline(always)] + pub fn knot_normalize(&mut self) -> &mut Self { + self.knot_vec.try_normalize().unwrap(); + self + } + + /// Translates the knot vector + #[inline(always)] + pub fn knot_translate(&mut self, x: f64) -> &mut Self { + self.knot_vec.translate(x); + self + } +} + +impl> BSplineCurve

{ + /// Returns the closure of substitution. + /// # Examples + /// The following test code is the same test with the one of `BSplineCurve::subs()`. + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vec = KnotVec::from(vec![-1.0, -1.0, -1.0, 1.0, 1.0, 1.0]); + /// let ctrl_pts = vec![Vector2::new(-1.0, 1.0), Vector2::new(0.0, -1.0), Vector2::new(1.0, 1.0)]; + /// let bspcurve = BSplineCurve::new(knot_vec, ctrl_pts); + /// + /// const N: usize = 100; // sample size + /// let get_t = |i: usize| -1.0 + 2.0 * (i as f64) / (N as f64); + /// let res: Vec<_> = (0..=N).map(get_t).map(bspcurve.get_closure()).collect(); + /// let ans: Vec<_> = (0..=N).map(get_t).map(|t| Vector2::new(t, t * t)).collect(); + /// res.iter().zip(&ans).for_each(|(v0, v1)| assert_near2!(v0, v1)); + /// ``` + #[inline(always)] + pub fn get_closure(&self) -> impl Fn(f64) -> P + '_ { move |t| self.subs(t) } + #[inline(always)] + fn delta_control_points(&self, i: usize) -> P::Diff { + if i == 0 { + self.control_point(i).to_vec() + } else if i == self.control_points.len() { + self.control_points[i - 1].to_vec() * (-1.0) + } else { + self.control_points[i] - self.control_points[i - 1] + } + } + #[inline(always)] + fn delta2_control_points(&self, i: usize) -> P::Diff { + let k = self.degree(); + let knot_vec = self.knot_vec(); + if i == 0 { + let coef = inv_or_zero(knot_vec[i + k] - knot_vec[i]); + self.delta_control_points(i) * coef + } else if i == self.control_points.len() + 1 { + let coef = inv_or_zero(knot_vec[i - 1 + k] - knot_vec[i - 1]); + self.delta_control_points(i - 1) * (-coef) + } else { + let coef0 = inv_or_zero(knot_vec[i + k] - knot_vec[i]); + let coef1 = inv_or_zero(knot_vec[i - 1 + k] - knot_vec[i - 1]); + self.delta_control_points(i) * coef0 - self.delta_control_points(i - 1) * coef1 + } + } + /// Returns the derived B-spline curve. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vec = KnotVec::bezier_knot(2); + /// let ctrl_pts = vec![Vector2::new(0.0, 0.0), Vector2::new(0.5, 0.0), Vector2::new(1.0, 1.0)]; + /// let bspcurve = BSplineCurve::new(knot_vec, ctrl_pts); + /// let derived = bspcurve.derivation(); + /// + /// // `bpscurve = (t, t^2), derived = (1, 2t)` + /// const N : usize = 100; // sample size + /// for i in 0..=N { + /// let t = 1.0 / (N as f64) * (i as f64); + /// assert_near2!(derived.subs(t), Vector2::new(1.0, 2.0 * t)); + /// } + /// ``` + pub fn derivation(&self) -> BSplineCurve { + let n = self.control_points.len(); + let k = self.degree(); + let knot_vec = self.knot_vec.clone(); + let mut new_points = Vec::with_capacity(n + 1); + if k > 0 { + let (knot_vec, new_points) = (&knot_vec, &mut new_points); + (0..=n).for_each(move |i| { + let delta = knot_vec[i + k] - knot_vec[i]; + let coef = (k as f64) * inv_or_zero(delta); + new_points.push(self.delta_control_points(i) * coef); + }); + } else { + new_points = vec![P::Diff::zero(); n]; + } + BSplineCurve::new_unchecked(knot_vec, new_points) + } + pub(super) fn sub_near_as_curve bool>( + &self, + other: &BSplineCurve

, + div_coef: usize, + ord: F, + ) -> bool { + if !self.knot_vec.same_range(&other.knot_vec) { + return false; + } + + let division = std::cmp::max(self.degree(), other.degree()) * div_coef; + for i in 0..(self.knot_vec.len() - 1) { + let delta = self.knot_vec[i + 1] - self.knot_vec[i]; + if delta.so_small() { + continue; + } + + for j in 0..division { + let t = self.knot_vec[i] + delta * (j as f64) / (division as f64); + if !ord(&self.subs(t), &other.subs(t)) { + return false; + } + } + } + true + } +} + +impl> BSplineCurve { + /// lift up control points to homogeneous coordinate. + pub fn lift_up(curve: BSplineCurve) -> Self { + let control_points = curve + .control_points + .into_iter() + .map(V::from_point) + .collect(); + BSplineCurve::new_unchecked(curve.knot_vec, control_points) + } +} + +impl> ParametricCurve for BSplineCurve

{ + type Point = P; + type Vector = P::Diff; + /// Substitutes to B-spline curve. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vec = KnotVec::from(vec![-1.0, -1.0, -1.0, 1.0, 1.0, 1.0]); + /// let ctrl_pts = vec![Vector2::new(-1.0, 1.0), Vector2::new(0.0, -1.0), Vector2::new(1.0, 1.0)]; + /// let bspcurve = BSplineCurve::new(knot_vec, ctrl_pts); + /// + /// // bspcurve coincides with (t, t * t) in the range [-1.0..1.0]. + /// const N: usize = 100; // sample size + /// for i in 0..=N { + /// let t = -1.0 + 2.0 * (i as f64) / (N as f64); + /// assert_near2!(bspcurve.subs(t), Vector2::new(t, t * t)); + /// } + /// ``` + #[inline(always)] + fn subs(&self, t: f64) -> P { + let basis = self + .knot_vec + .try_bspline_basis_functions(self.degree(), t) + .unwrap(); + self.control_points + .iter() + .zip(basis) + .fold(P::origin(), |sum, (pt, basis)| sum + pt.to_vec() * basis) + } + /// Substitutes to the derived B-spline curve. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vec = KnotVec::bezier_knot(2); + /// let ctrl_pts = vec![Vector2::new(0.0, 0.0), Vector2::new(0.5, 0.0), Vector2::new(1.0, 1.0)]; + /// let bspcurve = BSplineCurve::new(knot_vec, ctrl_pts); + /// + /// // `bpscurve = (t, t^2), derived = (1, 2t)` + /// const N : usize = 100; // sample size + /// for i in 0..=N { + /// let t = 1.0 / (N as f64) * (i as f64); + /// assert_near2!(bspcurve.der(t), Vector2::new(1.0, 2.0 * t)); + /// } + /// ``` + #[inline(always)] + fn der(&self, t: f64) -> P::Diff { + let k = self.degree(); + let knot_vec = self.knot_vec(); + let closure = move |sum: P::Diff, (i, b): (usize, f64)| { + let coef = inv_or_zero(knot_vec[i + k] - knot_vec[i]); + sum + self.delta_control_points(i) * b * coef + }; + knot_vec + .bspline_basis_functions(k - 1, t) + .into_iter() + .enumerate() + .fold(P::Diff::zero(), closure) + * k as f64 + } + /// Substitutes to the 2nd-ord derived B-spline curve. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vec = KnotVec::bezier_knot(3); + /// let ctrl_pts = vec![ + /// Vector2::new(0.0, 0.0), + /// Vector2::new(1.0, 1.0), + /// Vector2::new(0.0, 1.0), + /// Vector2::new(1.0, 0.0), + /// ]; + /// let bspcurve = BSplineCurve::new(knot_vec, ctrl_pts); + /// + /// // bpscurve = (4t^3 - 6t^2 + 3t, -3t^2 + 3t), derived2 = (24t - 12, -6) + /// const N : usize = 100; // sample size + /// for i in 0..=N { + /// let t = 1.0 / (N as f64) * (i as f64); + /// assert_near2!(bspcurve.der2(t), Vector2::new(24.0 * t - 12.0, -6.0)); + /// } + /// ``` + #[inline(always)] + fn der2(&self, t: f64) -> P::Diff { + let k = self.degree(); + if k < 2 { + return P::Diff::zero(); + } + let knot_vec = self.knot_vec(); + let closure = move |sum: P::Diff, (i, b): (usize, f64)| { + let coef = inv_or_zero(knot_vec[i + k - 1] - knot_vec[i]); + sum + self.delta2_control_points(i) * b * coef + }; + knot_vec + .bspline_basis_functions(k - 2, t) + .into_iter() + .enumerate() + .fold(P::Diff::zero(), closure) + * k as f64 + * (k - 1) as f64 + } + #[inline(always)] + fn parameter_range(&self) -> ParameterRange { + ( + Bound::Included(self.knot_vec[0]), + Bound::Included(self.knot_vec[self.knot_vec.len() - 1]), + ) + } +} + +impl> BoundedCurve for BSplineCurve

{} + +impl + Tolerance> BSplineCurve

{ + /// Returns whether all control points are the same or not. + /// If the knot vector is clamped, it means whether the curve is constant or not. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// + /// let knot_vec = KnotVec::bezier_knot(2); + /// let pt = Vector2::new(1.0, 2.0); + /// let mut ctrl_pts = vec![pt.clone(), pt.clone(), pt.clone()]; + /// let const_bspcurve = BSplineCurve::new(knot_vec.clone(), ctrl_pts.clone()); + /// assert!(const_bspcurve.is_const()); + /// + /// ctrl_pts.push(Vector2::new(2.0, 3.0)); + /// let bspcurve = BSplineCurve::new(knot_vec.clone(), ctrl_pts.clone()); + /// assert!(!bspcurve.is_const()); + /// ``` + /// # Remarks + /// If the knot vector is not clamped and the BSpline basis function is not partition of unity, + /// then perhaps returns true even if the curve is not constant. + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vec = KnotVec::uniform_knot(1, 5); + /// let ctrl_pts = vec![Vector2::new(1.0, 2.0), Vector2::new(1.0, 2.0)]; + /// let bspcurve = BSplineCurve::new(knot_vec, ctrl_pts); + /// + /// // bspcurve is not constant. + /// assert_eq!(bspcurve.subs(0.0), Vector2::new(0.0, 0.0)); + /// assert_ne!(bspcurve.subs(0.5), Vector2::new(0.0, 0.0)); + /// + /// // bspcurve.is_const() is true + /// assert!(bspcurve.is_const()); + /// ``` + pub fn is_const(&self) -> bool { + self.control_points + .iter() + .all(move |vec| vec.near(&self.control_points[0])) + } + + /// Adds a knot `x`, and do not change `self` as a curve. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vec = KnotVec::bezier_knot(2); + /// let ctrl_pts = vec![Vector2::new(-1.0, 1.0), Vector2::new(0.0, -1.0), Vector2::new(1.0, 1.0)]; + /// let mut bspcurve = BSplineCurve::new(knot_vec, ctrl_pts); + /// let org_curve = bspcurve.clone(); + /// + /// // add 4 knots + /// bspcurve.add_knot(0.5).add_knot(0.5).add_knot(0.25).add_knot(0.75); + /// assert_eq!(bspcurve.knot_vec().len(), org_curve.knot_vec().len() + 4); + /// // bspcurve does not change as a curve + /// assert!(bspcurve.near2_as_curve(&org_curve)); + /// ``` + /// # Remarks + /// If the added knot `x` is out of the range of the knot vector, then the knot vector will extended. + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vec = KnotVec::bezier_knot(2); + /// let ctrl_pts = vec![Vector2::new(-1.0, 1.0), Vector2::new(0.0, -1.0), Vector2::new(1.0, 1.0)]; + /// let mut bspcurve = BSplineCurve::new(knot_vec, ctrl_pts); + /// assert_eq!(bspcurve.knot_vec().range_length(), 1.0); + /// assert_eq!(bspcurve.front(), Vector2::new(-1.0, 1.0)); + /// assert_eq!(bspcurve.back(), Vector2::new(1.0, 1.0)); + /// + /// // add knots out of the range of the knot vectors. + /// bspcurve.add_knot(-1.0).add_knot(2.0); + /// assert_eq!(bspcurve.knot_vec().range_length(), 3.0); + /// assert_eq!(bspcurve.front(), Vector2::new(0.0, 0.0)); + /// assert_eq!(bspcurve.back(), Vector2::new(0.0, 0.0)); + /// ``` + pub fn add_knot(&mut self, x: f64) -> &mut Self { + if x < self.knot_vec[0] { + self.knot_vec.add_knot(x); + self.control_points.insert(0, P::origin()); + return self; + } + + let k = self.degree(); + let n = self.control_points.len(); + + let idx = self.knot_vec.add_knot(x); + let start = if idx > k { idx - k } else { 0 }; + let end = if idx > n { + self.control_points.push(P::origin()); + n + 1 + } else { + self.control_points + .insert(idx - 1, *self.control_point(idx - 1)); + idx + }; + for i in start..end { + let i0 = end + start - i - 1; + let delta = self.knot_vec[i0 + k + 1] - self.knot_vec[i0]; + let a = (self.knot_vec[idx] - self.knot_vec[i0]) * inv_or_zero(delta); + let p = self.delta_control_points(i0) * (1.0 - a); + self.control_points[i0] -= p; + } + self + } + + /// Removes a knot corresponding to the indices `idx`, and do not change `self` as a curve. + /// If cannot remove the knot, do not change `self` and return `self`. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vec = KnotVec::bezier_knot(2); + /// let ctrl_pts = vec![Vector2::new(-1.0, 1.0), Vector2::new(0.0, -1.0), Vector2::new(1.0, 1.0)]; + /// let mut bspcurve = BSplineCurve::new(knot_vec, ctrl_pts); + /// let org_curve = bspcurve.clone(); + /// + /// // add knots and remove them. + /// bspcurve.add_knot(0.5).add_knot(0.5).add_knot(0.25).add_knot(0.75); + /// bspcurve.remove_knot(3).remove_knot(3).remove_knot(3).remove_knot(3); + /// assert!(bspcurve.near2_as_curve(&org_curve)); + /// assert_eq!(bspcurve.knot_vec().len(), org_curve.knot_vec().len()) + /// ``` + pub fn remove_knot(&mut self, idx: usize) -> &mut Self { + let _ = self.try_remove_knot(idx); + self + } + + /// Removes a knot corresponding to the indice `idx`, and do not change `self` as a curve. + /// If the knot cannot be removed, returns + /// [`Error::CannotRemoveKnot`](./errors/enum.Error.html#variant.CannotRemoveKnot). + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// use truck_geometry::errors::Error; + /// let knot_vec = KnotVec::bezier_knot(2); + /// let ctrl_pts = vec![Vector2::new(-1.0, 1.0), Vector2::new(0.0, -1.0), Vector2::new(1.0, 1.0)]; + /// let mut bspcurve = BSplineCurve::new(knot_vec, ctrl_pts); + /// let org_curve = bspcurve.clone(); + /// bspcurve.add_knot(0.5).add_knot(0.5).add_knot(0.25).add_knot(0.75); + /// assert!(bspcurve.try_remove_knot(3).is_ok()); + /// assert_eq!(bspcurve.try_remove_knot(2), Err(Error::CannotRemoveKnot(2))); + /// ``` + pub fn try_remove_knot(&mut self, idx: usize) -> Result<&mut BSplineCurve

> { + let k = self.degree(); + let n = self.control_points.len(); + let knot_vec = &self.knot_vec; + + if idx < k + 1 || idx >= n { + return Err(Error::CannotRemoveKnot(idx)); + } + + let mut new_points = Vec::with_capacity(k + 1); + new_points.push(*self.control_point(idx - k - 1)); + for i in (idx - k)..idx { + let delta = knot_vec[i + k + 1] - knot_vec[i]; + let a = inv_or_zero(delta) * (knot_vec[idx] - knot_vec[i]); + if a.so_small() { + break; + } else { + let p = *new_points.last().unwrap(); + let p = p + (self.control_points[i] - p) / a; + new_points.push(p); + } + } + + if !new_points.last().unwrap().near(self.control_point(idx)) { + return Err(Error::CannotRemoveKnot(idx)); + } + + for (i, vec) in new_points.into_iter().skip(1).enumerate() { + self.control_points[idx - k + i] = vec; + } + + self.control_points.remove(idx); + self.knot_vec.remove(idx); + Ok(self) + } + + /// elevate 1 degree for bezier curve. + fn elevate_degree_bezier(&mut self) -> &mut Self { + let k = self.degree(); + self.knot_vec.add_knot(self.knot_vec[0]); + self.knot_vec + .add_knot(self.knot_vec[self.knot_vec.len() - 1]); + self.control_points.push(P::origin()); + for i in 0..=(k + 1) { + let i0 = k + 1 - i; + let a = (i0 as f64) / ((k + 1) as f64); + let p = self.delta_control_points(i0) * a; + self.control_points[i0] -= p; + } + self + } + + /// elevate 1 degree. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vec = KnotVec::bezier_knot(1); + /// let ctrl_pts = vec![Vector2::new(0.0, 0.0), Vector2::new(1.0, 1.0)]; + /// let mut bspcurve = BSplineCurve::new(knot_vec, ctrl_pts); + /// bspcurve.elevate_degree(); + /// assert_eq!(bspcurve.degree(), 2); + /// assert_eq!(bspcurve.knot_vec(), &KnotVec::bezier_knot(2)); + /// assert_eq!(bspcurve.control_point(1), &Vector2::new(0.5, 0.5)); + /// ``` + pub fn elevate_degree(&mut self) -> &mut Self { + let mut result = CurveCollector::Singleton; + for mut bezier in self.bezier_decomposition() { + result.concat(bezier.elevate_degree_bezier()); + } + *self = result.unwrap(); + self + } + + /// Makes the B-spline curve clamped + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vec = KnotVec::from(vec![0.0, 1.0, 2.0, 3.0, 4.0, 5.0]); + /// let ctrl_pts = vec![Vector2::new(0.0, 1.0), Vector2::new(1.0, 2.0), Vector2::new(2.0, 3.0)]; + /// let mut bspcurve = BSplineCurve::new(knot_vec, ctrl_pts); + /// assert!(!bspcurve.is_clamped()); + /// bspcurve.clamp(); + /// assert!(bspcurve.is_clamped()); + /// assert_eq!(bspcurve.knot_vec().len(), 10); + /// ``` + #[inline(always)] + pub fn clamp(&mut self) -> &mut Self { + let degree = self.degree(); + + let s = self.knot_vec.multiplicity(0); + for _ in s..=degree { + self.add_knot(self.knot_vec[0]); + } + + let n = self.knot_vec.len(); + let s = self.knot_vec.multiplicity(n - 1); + for _ in s..=degree { + self.add_knot(self.knot_vec[n - 1]); + } + self + } + + /// Repeats `Self::try_remove_knot()` from the back knot in turn until the knot cannot be removed. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// + /// let knot_vec = KnotVec::bezier_knot(2); + /// let ctrl_pts = vec![Vector2::new(1.0, 2.0), Vector2::new(2.0, 3.0), Vector2::new(3.0, 4.0)]; + /// let mut bspcurve = BSplineCurve::new(knot_vec, ctrl_pts); + /// let org_curve = bspcurve.clone(); + /// + /// // add 4 new knots + /// bspcurve.add_knot(0.5).add_knot(0.5).add_knot(0.25).add_knot(0.75); + /// assert_eq!(bspcurve.knot_vec().len(), KnotVec::bezier_knot(2).len() + 4); + /// + /// // By the optimization, added knots are removed. + /// bspcurve.optimize(); + /// assert_eq!(bspcurve.knot_vec(), &KnotVec::bezier_knot(2)); + /// assert!(bspcurve.near2_as_curve(&org_curve)); + /// ``` + pub fn optimize(&mut self) -> &mut Self { + loop { + let n = self.knot_vec.len(); + let closure = |flag, i| flag && self.try_remove_knot(n - i).is_err(); + if (1..=n).fold(true, closure) { + break; + } + } + self + } + + /// Makes two splines having the same degrees. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// + /// let knot_vec0 = KnotVec::bezier_knot(1); + /// let ctrl_pts0 = vec![Vector2::new(1.0, 2.0), Vector2::new(2.0, 3.0)]; + /// let mut bspcurve0 = BSplineCurve::new(knot_vec0, ctrl_pts0); + /// let knot_vec1 = KnotVec::bezier_knot(2); + /// let ctrl_pts1 = vec![Vector2::new(1.0, 2.0), Vector2::new(2.0, 3.0), Vector2::new(3.0, 4.0)]; + /// let mut bspcurve1 = BSplineCurve::new(knot_vec1, ctrl_pts1); + /// assert_ne!(bspcurve0.degree(), bspcurve1.degree()); + /// + /// let org_curve0 = bspcurve0.clone(); + /// let org_curve1 = bspcurve1.clone(); + /// bspcurve0.syncro_degree(&mut bspcurve1); + /// assert_eq!(bspcurve0.degree(), bspcurve1.degree()); + /// assert!(bspcurve0.near2_as_curve(&org_curve0)); + /// assert!(bspcurve1.near2_as_curve(&org_curve1)); + /// ``` + pub fn syncro_degree(&mut self, other: &mut Self) { + let (degree0, degree1) = (self.degree(), other.degree()); + for _ in degree0..degree1 { + self.elevate_degree(); + } + for _ in degree1..degree0 { + other.elevate_degree(); + } + } + + /// Makes two splines having the same normalized knot vectors. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// + /// let knot_vec0 = KnotVec::from(vec![0.0, 0.0, 0.0, 0.5, 1.0, 1.0, 1.0]); + /// let ctrl_pts0 = vec![Vector2::new(0.0, 0.0), Vector2::new(1.0, 1.0), Vector2::new(2.0, 2.0), Vector2::new(3.0, 3.0)]; + /// let mut bspcurve0 = BSplineCurve::new(knot_vec0, ctrl_pts0); + /// let mut org_curve0 = bspcurve0.clone(); + /// let knot_vec1 = KnotVec::from(vec![0.0, 0.0, 1.0, 3.0, 4.0, 4.0]); + /// let ctrl_pts1 = vec![Vector2::new(0.0, 0.0), Vector2::new(1.0, 1.0), Vector2::new(2.0, 2.0), Vector2::new(3.0, 3.0)]; + /// let mut bspcurve1 = BSplineCurve::new(knot_vec1, ctrl_pts1); + /// let mut org_curve1 = bspcurve1.clone(); + /// + /// bspcurve0.syncro_knots(&mut bspcurve1); + /// + /// // The knot vectors are made the same. + /// assert_eq!(bspcurve0.knot_vec(), bspcurve1.knot_vec()); + /// assert_eq!( + /// bspcurve0.knot_vec().as_slice(), + /// &[0.0, 0.0, 0.0, 0.25, 0.5, 0.75, 1.0, 1.0, 1.0] + /// ); + /// // The degrees are not changed. + /// assert_eq!(bspcurve0.degree(), org_curve0.degree()); + /// assert_eq!(bspcurve1.degree(), org_curve1.degree()); + /// // The knot vector is normalized, however, the shape of curve is not changed. + /// assert!(bspcurve0.near2_as_curve(org_curve0.knot_normalize())); + /// assert!(bspcurve1.near2_as_curve(org_curve1.knot_normalize())); + /// ``` + pub fn syncro_knots(&mut self, other: &mut BSplineCurve

) { + self.knot_normalize(); + other.knot_normalize(); + + let mut i = 0; + let mut j = 0; + while !self.knot(i).near2(&1.0) || !other.knot(j).near2(&1.0) { + if self.knot(i) - other.knot(j) > TOLERANCE { + self.add_knot(other.knot(j)); + } else if other.knot(j) - self.knot(i) > TOLERANCE { + other.add_knot(self.knot(i)); + } + i += 1; + j += 1; + } + + use std::cmp::Ordering; + match usize::cmp(&self.knot_vec.len(), &other.knot_vec.len()) { + Ordering::Less => { + (0..(other.knot_vec.len() - self.knot_vec.len())).for_each(|_| { + self.add_knot(1.0); + }); + } + Ordering::Greater => (0..(self.knot_vec.len() - other.knot_vec.len())).for_each(|_| { + other.add_knot(1.0); + }), + _ => {} + } + } + + /// Separates `self` into Bezier curves by each knots. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// + /// let knot_vec = KnotVec::uniform_knot(2, 2); + /// let ctrl_pts = vec![Vector2::new(0.0, 1.0), Vector2::new(1.0, 2.0), Vector2::new(2.0, 3.0), Vector2::new(3.0, 4.0)]; + /// let bspcurve = BSplineCurve::new(knot_vec, ctrl_pts); + /// let beziers = bspcurve.bezier_decomposition(); + /// + /// const N: usize = 100; + /// for i in 0..=N { + /// let t = 0.5 * (i as f64) / (N as f64); + /// assert_near2!(bspcurve.subs(t), beziers[0].subs(t)); + /// } + /// for i in 0..=N { + /// let t = 0.5 + 0.5 * (i as f64) / (N as f64); + /// assert_near2!(bspcurve.subs(t), beziers[1].subs(t)); + /// } + /// ``` + pub fn bezier_decomposition(&self) -> Vec> { + let mut bspline = self.clone(); + bspline.clamp(); + let (knots, _) = self.knot_vec.to_single_multi(); + let n = knots.len(); + + let mut result = Vec::new(); + for i in 2..n { + result.push(bspline.cut(knots[n - i])); + } + result.push(bspline); + result.reverse(); + result + } + + /// Makes the curve locally injective. + /// # Example + /// ``` + /// use truck_geometry::prelude::*; + /// const N : usize = 100; // sample size for test + /// + /// let knot_vec = KnotVec::from( + /// vec![0.0, 0.0, 0.0, 1.0, 3.0, 4.0, 4.0, 4.0] + /// ); + /// let ctrl_pts = vec![ + /// Vector3::new(1.0, 0.0, 0.0), + /// Vector3::new(0.0, 1.0, 0.0), + /// Vector3::new(0.0, 1.0, 0.0), + /// Vector3::new(0.0, 1.0, 0.0), + /// Vector3::new(0.0, 0.0, 1.0), + /// ]; + /// + /// let mut bspcurve = BSplineCurve::new(knot_vec, ctrl_pts); + /// let mut flag = false; + /// for i in 0..=N { + /// let t = 4.0 * (i as f64) / (N as f64); + /// flag = flag || bspcurve.subs(t).near(&bspcurve.subs(t + 1.0 / (N as f64))); + /// } + /// // There exists t such that bspcurve(t) == bspcurve(t + 0.01). + /// assert!(flag); + /// + /// bspcurve.make_locally_injective().knot_normalize(); + /// let mut flag = false; + /// for i in 0..=N { + /// let t = 1.0 * (i as f64) / (N as f64); + /// flag = flag || bspcurve.subs(t).near(&bspcurve.subs(t + 1.0 / (N as f64))); + /// } + /// // There does not exist t such that bspcurve(t) == bspcurve(t + 0.01). + /// assert!(!flag); + /// ``` + /// # Remarks + /// If `self` is a constant curve, then does nothing. + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vec = KnotVec::from(vec![0.0, 0.0, 0.0, 1.0, 2.0, 2.0, 2.0]); + /// let ctrl_pts = vec![Vector2::new(1.0, 1.0); 4]; + /// let mut bspcurve = BSplineCurve::new(knot_vec, ctrl_pts); + /// let org_curve = bspcurve.clone(); + /// bspcurve.make_locally_injective(); + /// assert_eq!(bspcurve, org_curve); + /// ``` + pub fn make_locally_injective(&mut self) -> &mut Self { + let mut iter = self.bezier_decomposition().into_iter(); + for bezier in iter.by_ref() { + if !bezier.is_const() { + *self = bezier; + break; + } + } + let mut x = 0.0; + for mut bezier in iter { + if bezier.is_const() { + x += bezier.knot_vec.range_length(); + } else { + self.concat(bezier.knot_translate(-x)); + } + } + self + } + /// Determine whether `self` and `other` is near as the B-spline curves or not. + /// + /// Divides each knot interval into the number of degree equal parts, + /// and check `|self(t) - other(t)| < TOLERANCE` for each end points `t`. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vec = KnotVec::from( + /// vec![0.0, 0.0, 0.0, 1.0, 2.0, 3.0, 4.0, 4.0, 4.0] + /// ); + /// let ctrl_pts = vec![ + /// Vector2::new(1.0, 1.0), + /// Vector2::new(3.0, 2.0), + /// Vector2::new(2.0, 3.0), + /// Vector2::new(4.0, 5.0), + /// Vector2::new(5.0, 4.0), + /// Vector2::new(1.0, 1.0), + /// ]; + /// let bspcurve0 = BSplineCurve::new(knot_vec, ctrl_pts); + /// let mut bspcurve1 = bspcurve0.clone(); + /// assert!(bspcurve0.near_as_curve(&bspcurve1)); + /// *bspcurve1.control_point_mut(1) += Vector2::new(0.01, 0.0002); + /// assert!(!bspcurve0.near_as_curve(&bspcurve1)); + /// ``` + #[inline(always)] + pub fn near_as_curve(&self, other: &BSplineCurve

) -> bool { + self.sub_near_as_curve(other, 1, |x, y| x.near(y)) + } + + /// Determines `self` and `other` is near in square order as the B-spline curves or not. + /// + /// Divide each knot interval into the number of degree equal parts, + /// and check `|self(t) - other(t)| < TOLERANCE`for each end points `t`. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let eps = TOLERANCE; + /// let knot_vec = KnotVec::from( + /// vec![0.0, 0.0, 0.0, 1.0, 2.0, 3.0, 4.0, 4.0, 4.0] + /// ); + /// let ctrl_pts = vec![ + /// Vector2::new(1.0, 1.0), + /// Vector2::new(3.0, 2.0), + /// Vector2::new(2.0, 3.0), + /// Vector2::new(4.0, 5.0), + /// Vector2::new(5.0, 4.0), + /// Vector2::new(1.0, 1.0), + /// ]; + /// let bspcurve0 = BSplineCurve::new(knot_vec, ctrl_pts); + /// let mut bspcurve1 = bspcurve0.clone(); + /// assert!(bspcurve0.near_as_curve(&bspcurve1)); + /// *bspcurve1.control_point_mut(1) += Vector2::new(eps, 0.0); + /// assert!(!bspcurve0.near2_as_curve(&bspcurve1)); + /// ``` + #[inline(always)] + pub fn near2_as_curve(&self, other: &BSplineCurve

) -> bool { + self.sub_near_as_curve(other, 1, |x, y| x.near2(y)) + } +} + +impl> ParameterTransform for BSplineCurve

{ + #[inline(always)] + fn parameter_transform(&mut self, scalar: f64, r#move: f64) -> &mut Self { + self.knot_vec.transform(scalar, r#move); + self + } +} + +#[test] +fn parameter_transform_random_test() { + let curve = BSplineCurve::new( + KnotVec::uniform_knot(4, 4), + (0..8) + .map(|_| { + Point3::new( + rand::random::(), + rand::random::(), + rand::random::(), + ) + }) + .collect(), + ); + truck_geotrait::parameter_transform_random_test(&curve, 10); +} + +impl + Tolerance> Cut for BSplineCurve

{ + fn cut(&mut self, mut t: f64) -> BSplineCurve

{ + let degree = self.degree(); + + let idx = match self.knot_vec.floor(t) { + Some(idx) => idx, + None => { + let bspline = self.clone(); + let knot_vec = KnotVec::from(vec![t, self.knot_vec[0]]); + let ctrl_pts = vec![P::origin()]; + *self = BSplineCurve::new(knot_vec, ctrl_pts); + return bspline; + } + }; + let s = if t.near(&self.knot_vec[idx]) { + t = self.knot_vec[idx]; + self.knot_vec.multiplicity(idx) + } else { + 0 + }; + + for _ in s..=degree { + self.add_knot(t); + } + + let k = self.knot_vec.floor(t).unwrap(); + let m = self.knot_vec.len(); + let n = self.control_points.len(); + let knot_vec0 = self.knot_vec.sub_vec(0..=k); + let knot_vec1 = self.knot_vec.sub_vec((k - degree)..m); + let control_points0 = Vec::from(&self.control_points[0..(k - degree)]); + let control_points1 = Vec::from(&self.control_points[(k - degree)..n]); + *self = BSplineCurve::new_unchecked(knot_vec0, control_points0); + BSplineCurve::new_unchecked(knot_vec1, control_points1) + } +} + +#[test] +fn cut_random_test() { + let curve = BSplineCurve::new( + KnotVec::uniform_knot(4, 4), + (0..8) + .map(|_| { + Point3::new( + rand::random::(), + rand::random::(), + rand::random::(), + ) + }) + .collect(), + ); + truck_geotrait::cut_random_test(&curve, 10); +} + +impl + Tolerance> Concat> for BSplineCurve

{ + type Output = BSplineCurve

; + /// Concats two B-spline curves. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// ``` + /// # Failure + /// If the back of the knot vector of `self` does not coincides with the front of the one of `other`, + /// ``` + /// use truck_geometry::prelude::*; + /// use truck_geotrait::traits::ConcatError; + /// + /// let knot_vec0 = KnotVec::from(vec![0.0, 0.0, 1.0, 1.0]); + /// let ctrl_pts0 = vec![Vector2::new(0.0, 0.0), Vector2::new(1.0, 1.0)]; + /// let mut bspcurve0 = BSplineCurve::new(knot_vec0, ctrl_pts0); + /// let knot_vec1 = KnotVec::from(vec![2.0, 2.0, 3.0, 3.0]); + /// let ctrl_pts1 = vec![Vector2::new(1.0, 1.0), Vector2::new(2.0, 2.0)]; + /// let mut bspcurve1 = BSplineCurve::new(knot_vec1, ctrl_pts1); + /// + /// assert_eq!(bspcurve0.try_concat(&mut bspcurve1), Err(ConcatError::DisconnectedParameters(1.0, 2.0))); + /// ``` + fn try_concat(&self, other: &BSplineCurve

) -> std::result::Result> { + let mut curve0 = self.clone(); + let mut curve1 = other.clone(); + curve0.syncro_degree(&mut curve1); + curve0.clamp(); + curve1.clamp(); + curve0 + .knot_vec + .try_concat(&curve1.knot_vec, curve0.degree()) + .map_err(|err| match err { + Error::DifferentBackFront(a, b) => ConcatError::DisconnectedParameters(a, b), + _ => unreachable!(), + })?; + let front = curve0.control_points.last().unwrap(); + let back = curve1.control_points.first().unwrap(); + if !front.near(back) { + return Err(ConcatError::DisconnectedPoints(*front, *back)); + } + curve0.control_points.extend(curve1.control_points); + Ok(curve0) + } +} + +#[test] +fn concat_positive_test() { + let mut part0 = BSplineCurve::new( + KnotVec::uniform_knot(4, 4), + (0..8) + .map(|_| { + Point3::new( + rand::random::(), + rand::random::(), + rand::random::(), + ) + }) + .collect(), + ); + let part1 = part0.cut(0.56); + concat_random_test(&part0, &part1, 10); +} + +#[test] +fn concat_negative_test() { + let curve0 = BSplineCurve::new( + KnotVec::bezier_knot(1), + vec![Point2::new(0.0, 0.0), Point2::new(0.0, 1.0)], + ); + let mut curve1 = BSplineCurve::new( + KnotVec::bezier_knot(1), + vec![Point2::new(1.0, 1.0), Point2::new(1.0, 1.0)], + ); + assert_eq!( + curve0.try_concat(&curve1), + Err(ConcatError::DisconnectedParameters(1.0, 0.0)) + ); + curve1.knot_translate(1.0); + assert_eq!( + curve0.try_concat(&curve1), + Err(ConcatError::DisconnectedPoints( + Point2::new(0.0, 1.0), + Point2::new(1.0, 1.0) + )) + ); +} + +impl

ParameterDivision1D for BSplineCurve

+where P: ControlPoint + + EuclideanSpace>::Diff> + + MetricSpace + + HashGen +{ + type Point = P; + fn parameter_division(&self, range: (f64, f64), tol: f64) -> (Vec, Vec

) { + algo::curve::parameter_division(self, range, tol) + } +} + +impl

BSplineCurve

+where + P: ControlPoint + + EuclideanSpace>::Diff> + + MetricSpace + + Tolerance, +

>::Diff: InnerSpace + Tolerance, +{ + /// Determines whether `self` is an arc of `curve` by repeating applying Newton method. + /// + /// The parameter `hint` is the init value, required that `curve.subs(hint)` is the front point of `self`. + /// + /// If `self` is an arc of `curve`, then returns `Some(t)` such that `curve.subs(t)` coincides with + /// the back point of `self`. Otherwise, returns `None`. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vec = KnotVec::from( + /// vec![0.0, 0.0, 0.0, 1.0, 2.0, 3.0, 3.0, 3.0] + /// ); + /// let ctrl_pts = vec![ + /// Point3::new(0.0, 0.0, 0.0), + /// Point3::new(1.0, 0.0, 0.0), + /// Point3::new(1.0, 1.0, 0.0), + /// Point3::new(0.0, 1.0, 0.0), + /// Point3::new(0.0, 1.0, 1.0), + /// ]; + /// let bspcurve = BSplineCurve::new(knot_vec, ctrl_pts); + /// + /// let mut part = bspcurve.clone().cut(0.6); + /// part.cut(2.8); + /// let t = part.is_arc_of(&bspcurve, 0.6).unwrap(); + /// assert_near!(t, 2.8); + /// + /// // hint is required the init value. + /// assert!(part.is_arc_of(&bspcurve, 0.7).is_none()); + /// + /// // normal failure + /// *part.control_point_mut(2) += Vector3::new(1.0, 2.0, 3.0); + /// assert!(part.is_arc_of(&bspcurve, 0.6).is_none()); + /// ``` + pub fn is_arc_of(&self, curve: &BSplineCurve

, mut hint: f64) -> Option { + let degree = std::cmp::max(self.degree(), curve.degree()) * 3 + 1; + let (knots, _) = self.knot_vec.to_single_multi(); + if !self.subs(knots[0]).near(&curve.subs(hint)) { + return None; + } + + for i in 1..knots.len() { + let range = knots[i] - knots[i - 1]; + for j in 1..=degree { + let t = knots[i - 1] + range * (j as f64) / (degree as f64); + let pt = ParametricCurve::subs(self, t); + let res = curve.search_nearest_parameter(pt, Some(hint), 100); + let flag = res.map(|res| hint <= res && curve.subs(res).near(&pt)); + hint = match flag { + Some(true) => res.unwrap(), + _ => return None, + }; + } + } + Some(hint) + } +} +impl

SearchNearestParameter for BSplineCurve

+where + P: ControlPoint + + EuclideanSpace>::Diff> + + MetricSpace + + Tolerance, +

>::Diff: InnerSpace + Tolerance, +{ + type Point = P; + /// Searches the parameter `t` which minimize |self(t) - point| by Newton's method with initial guess `hint`. + /// Returns `None` if the number of attempts exceeds `trial` i.e. if `trial == 0`, then the trial is only one time. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vec = KnotVec::from( + /// vec![0.0, 0.0, 0.0, 1.0, 2.0, 3.0, 3.0, 3.0] + /// ); + /// let ctrl_pts = vec![ + /// Point3::new(0.0, 0.0, 0.0), + /// Point3::new(1.0, 0.0, 0.0), + /// Point3::new(1.0, 1.0, 0.0), + /// Point3::new(0.0, 1.0, 0.0), + /// Point3::new(0.0, 1.0, 1.0), + /// ]; + /// let bspcurve = BSplineCurve::new(knot_vec, ctrl_pts); + /// let pt = ParametricCurve::subs(&bspcurve, 1.2); + /// let t = bspcurve.search_nearest_parameter(pt, Some(0.8), 100).unwrap(); + /// assert_near!(t, 1.2); + /// ``` + /// # Remarks + /// It may converge to a local solution depending on the hint. + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vec = KnotVec::from( + /// vec![0.0, 0.0, 0.0, 1.0, 2.0, 3.0, 3.0, 3.0] + /// ); + /// let ctrl_pts = vec![ + /// Point3::new(0.0, 0.0, 0.0), + /// Point3::new(1.0, 0.0, 0.0), + /// Point3::new(1.0, 1.0, 0.0), + /// Point3::new(0.0, 1.0, 0.0), + /// Point3::new(0.0, 1.0, 1.0), + /// ]; + /// let bspcurve = BSplineCurve::new(knot_vec, ctrl_pts); + /// let pt = Point3::new(0.0, 0.5, 1.0); + /// let t = bspcurve.search_nearest_parameter(pt, Some(0.8), 100).unwrap(); + /// let pt0 = ParametricCurve::subs(&bspcurve, t); + /// let pt1 = ParametricCurve::subs(&bspcurve, 3.0); + /// // the point corresponding the obtained parameter is not + /// // the globally nearest point in the curve. + /// assert!((pt0 - pt).magnitude() > (pt1 - pt).magnitude()); + /// ``` + #[inline(always)] + fn search_nearest_parameter>( + &self, + point: P, + hint: H, + trial: usize, + ) -> Option { + let hint = match hint.into() { + SPHint1D::Parameter(hint) => hint, + SPHint1D::Range(x, y) => { + algo::curve::presearch(self, point, (x, y), PRESEARCH_DIVISION) + } + SPHint1D::None => { + algo::curve::presearch(self, point, self.range_tuple(), PRESEARCH_DIVISION) + } + }; + algo::curve::search_nearest_parameter(self, point, hint, trial) + } +} +impl

SearchParameter for BSplineCurve

+where + P: ControlPoint + + EuclideanSpace>::Diff> + + MetricSpace, +

>::Diff: InnerSpace + Tolerance, +{ + type Point = P; + #[inline(always)] + fn search_parameter>(&self, point: P, hint: H, trial: usize) -> Option { + let hint = match hint.into() { + SPHint1D::Parameter(hint) => hint, + SPHint1D::Range(x, y) => { + algo::curve::presearch(self, point, (x, y), PRESEARCH_DIVISION) + } + SPHint1D::None => { + algo::curve::presearch(self, point, self.range_tuple(), PRESEARCH_DIVISION) + } + }; + algo::curve::search_parameter(self, point, hint, trial) + } +} + +impl BSplineCurve

{ + /// Returns the bounding box including all control points. + #[inline(always)] + pub fn roughly_bounding_box(&self) -> BoundingBox

{ self.control_points.iter().collect() } +} + +impl Invertible for BSplineCurve

{ + #[inline(always)] + fn invert(&mut self) { self.invert(); } +} + +impl Transformed for BSplineCurve

+where + P: EuclideanSpace, + M: Transform

, +{ + #[inline(always)] + fn transform_by(&mut self, trans: M) { + self.control_points + .iter_mut() + .for_each(|pt| *pt = trans.transform_point(*pt)) + } +} + +impl<'de, P> Deserialize<'de> for BSplineCurve

+where P: Deserialize<'de> +{ + fn deserialize(deserializer: D) -> std::result::Result + where D: serde::Deserializer<'de> { + #[derive(Deserialize)] + struct BSplineCurve_

{ + knot_vec: KnotVec, + control_points: Vec

, + } + let BSplineCurve_ { + knot_vec, + control_points, + } = BSplineCurve_::

::deserialize(deserializer)?; + Self::try_new(knot_vec, control_points).map_err(serde::de::Error::custom) + } +} + +#[test] +fn test_near_as_curve() { + let knot_vec = KnotVec::from(vec![ + 0.0, 0.0, 0.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 5.0, 5.0, 5.0, + ]); + let control_points = vec![ + Vector4::new(1.0, 0.0, 0.0, 0.0), + Vector4::new(0.0, 1.0, 0.0, 0.0), + Vector4::new(0.0, 0.0, 1.0, 0.0), + Vector4::new(0.0, 0.0, 0.0, 1.0), + Vector4::new(1.0, 1.0, 0.0, 0.0), + Vector4::new(1.0, 0.0, 1.0, 0.0), + Vector4::new(1.0, 0.0, 0.0, 1.0), + Vector4::new(1.0, 1.0, 1.0, 0.0), + ]; + let bspline0 = BSplineCurve::new(knot_vec, control_points.clone()); + let knot_vec = KnotVec::from(vec![ + 0.0, 0.0, 0.0, 0.0, 1.0, 2.0, 2.5, 3.0, 4.0, 5.0, 5.0, 5.0, 5.0, + ]); + let control_points = vec![ + control_points[0], + control_points[1], + control_points[2], + control_points[3] * (5.0 / 6.0) + control_points[2] * (1.0 / 6.0), + control_points[4] * 0.5 + control_points[3] * 0.5, + control_points[5] * (1.0 / 6.0) + control_points[4] * (5.0 / 6.0), + control_points[5], + control_points[6], + control_points[7], + ]; + let bspline1 = BSplineCurve::new(knot_vec, control_points); + let knot_vec = KnotVec::from(vec![ + 0.0, 0.0, 0.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 5.0, 5.0, 5.0, + ]); + let control_points = vec![ + Vector4::new(1.0, 0.0, 0.0, 0.0), + Vector4::new(0.0, 1.0, 0.0, 0.0), + Vector4::new(0.0, 0.0, 1.0, 0.0), + Vector4::new(0.0, 0.0, 0.0, 1.0), + Vector4::new(1.0, 1.01, 0.0, 0.0), + Vector4::new(1.0, 0.0, 1.0, 0.0), + Vector4::new(1.0, 0.0, 0.0, 1.0), + Vector4::new(1.0, 1.0, 1.0, 0.0), + ]; + let bspline2 = BSplineCurve::new(knot_vec, control_points); + assert!(bspline0.near_as_curve(&bspline1)); + assert!(!bspline0.near_as_curve(&bspline2)); +} + +#[test] +fn test_parameter_division() { + let knot_vec = KnotVec::uniform_knot(2, 3); + let ctrl_pts = vec![ + Point3::new(0.0, 0.0, 0.0), + Point3::new(1.0, 0.0, 0.0), + Point3::new(0.0, 1.0, 0.0), + Point3::new(0.0, 0.0, 1.0), + Point3::new(1.0, 1.0, 1.0), + ]; + let bspcurve = BSplineCurve::new(knot_vec, ctrl_pts); + let tol = 0.01; + let (div, pts) = bspcurve.parameter_division(bspcurve.range_tuple(), tol); + let knot_vec = bspcurve.knot_vec(); + assert_eq!(knot_vec[0], div[0]); + assert_eq!(knot_vec.range_length(), div.last().unwrap() - div[0]); + for i in 1..div.len() { + let pt0 = bspcurve.subs(div[i - 1]); + assert_eq!(pt0, pts[i - 1]); + let pt1 = bspcurve.subs(div[i]); + assert_eq!(pt1, pts[i]); + let value_middle = pt0 + (pt1 - pt0) / 2.0; + let param_middle = bspcurve.subs((div[i - 1] + div[i]) / 2.0); + assert!(value_middle.distance(param_middle) < tol); + } +} + +impl

BSplineCurve

+where + P: ControlPoint + + EuclideanSpace>::Diff> + + MetricSpace + + Tolerance + + HashGen, +

>::Diff: InnerSpace + Tolerance, +{ + fn cubic_bezier_interpolation( + pt0: P, + pt1: P, + der0:

::Diff, + der1:

::Diff, + range: (f64, f64), + ) -> Self { + let width = range.1 - range.0; + let mut knot_vec = KnotVec::bezier_knot(3); + knot_vec.transform(width, range.0); + Self::debug_new( + knot_vec, + vec![pt0, pt0 + der0 * width / 3.0, pt1 - der1 * width / 3.0, pt1], + ) + } + + fn sub_cubic_approximation( + curve: &C, + range: (f64, f64), + ends: (P, P), + enders: (

::Diff,

::Diff), + p_tol: f64, + d_tol: f64, + trialis: usize, + ) -> Option + where + C: ParametricCurve::Diff>, + { + let bezier = Self::cubic_bezier_interpolation(ends.0, ends.1, enders.0, enders.1, range); + let gen = ends.0.midpoint(ends.1); + let p = 0.5 + (0.2 * HashGen::hash1(gen) - 0.1); + let t = range.0 * (1.0 - p) + range.1 * p; + let pt0 = bezier.subs(t); + let pt1 = curve.subs(t); + let der0 = bezier.der(t); + let der1 = curve.der(t); + let pt_dist2 = pt0.distance2(pt1); + let der_dist2 = (der0 - der1).magnitude2(); + if pt_dist2 > p_tol * p_tol || der_dist2 > d_tol * d_tol { + if trialis == 0 { + return None; + } + let t = (range.0 + range.1) / 2.0; + let pt = curve.subs(t); + let der = curve.der(t); + let bspcurve0 = Self::sub_cubic_approximation( + curve, + (range.0, t), + (ends.0, pt), + (enders.0, der), + p_tol, + d_tol, + trialis - 1, + ); + let bspcurve1 = Self::sub_cubic_approximation( + curve, + (t, range.1), + (pt, ends.1), + (der, enders.1), + p_tol, + d_tol, + trialis - 1, + ); + match (bspcurve0, bspcurve1) { + (Some(x), Some(y)) => x.try_concat(&y).ok(), + _ => None, + } + } else { + Some(bezier) + } + } + + /// C^1-approximation for `curve` by cubic Bspline curve. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// use std::f64::consts::PI; + /// let circle = UnitCircle::::new(); + /// let bspcurve = BSplineCurve::cubic_approximation(&circle, (-PI, PI), 0.01, 0.01, 10).unwrap(); + /// println!("{bspcurve:?}"); + /// + /// const N: usize = 100; + /// for i in 0..N { + /// let t = i as f64 / N as f64; + /// assert!(circle.subs(t).distance(bspcurve.subs(t)) < 0.02); + /// assert!((circle.der(t) - bspcurve.der(t)).magnitude() < 0.02); + /// } + /// ``` + pub fn cubic_approximation( + curve: &C, + range: (f64, f64), + p_tol: f64, + d_tol: f64, + trials: usize, + ) -> Option + where + C: ParametricCurve::Diff>, + { + let ends = (curve.subs(range.0), curve.subs(range.1)); + let enders = (curve.der(range.0), curve.der(range.1)); + Self::sub_cubic_approximation(curve, range, ends, enders, p_tol, d_tol, trials).map( + |mut x| { + x.optimize(); + x + }, + ) + } +} + +#[test] +fn cubic_bezier_interpolation_test() { + let pt0 = Point2::new(0.0, 0.0); + let pt1 = Point2::new(1.0, 0.0); + let der0 = Vector2::new(0.5, 1.0); + let der1 = Vector2::new(0.5, -1.0); + let bspcurve = BSplineCurve::cubic_bezier_interpolation(pt0, pt1, der0, der1, (1.23, 3.45)); + let der = bspcurve.derivation(); + assert_near!(bspcurve.front(), pt0); + assert_near!(bspcurve.back(), pt1); + assert_near!(der.front(), der0); + assert_near!(der.back(), der1); +} diff --git a/vendor/truck-geometry/src/nurbs/bspsurface.rs b/vendor/truck-geometry/src/nurbs/bspsurface.rs new file mode 100644 index 000000000..fcedac201 --- /dev/null +++ b/vendor/truck-geometry/src/nurbs/bspsurface.rs @@ -0,0 +1,2230 @@ +use super::*; +use crate::errors::Error; +use std::iter::FusedIterator; +use std::ops::*; + +impl

BSplineSurface

{ + /// constructor. + /// # Arguments + /// * `knot_vecs` - the knot vectors + /// * `control_points` - the vector of the control points + /// # Panics + /// There are 3 rules for construct B-spline curve. + /// * The number of knots is more than the one of control points. + /// * There exist at least two different knots. + /// * There are at least one control point. + #[inline(always)] + pub fn new(knot_vecs: (KnotVec, KnotVec), control_points: Vec>) -> BSplineSurface

{ + BSplineSurface::try_new(knot_vecs, control_points).unwrap_or_else(|e| panic!("{}", e)) + } + + /// constructor. + /// # Arguments + /// * `knot_vecs` - the knot vectors + /// * `control_points` - the vector of the control points + /// # Failures + /// There are 3 rules for construct B-spline curve. + /// * The number of knots is more than the one of control points. + /// * There exist at least two different knots. + /// * There are at least one control point. + #[inline(always)] + pub fn try_new( + knot_vecs: (KnotVec, KnotVec), + control_points: Vec>, + ) -> Result> { + if control_points.is_empty() || control_points[0].is_empty() { + Err(Error::EmptyControlPoints) + } else if knot_vecs.0.len() <= control_points.len() { + Err(Error::TooShortKnotVector( + knot_vecs.0.len(), + control_points.len(), + )) + } else if knot_vecs.1.len() <= control_points[0].len() { + Err(Error::TooShortKnotVector( + knot_vecs.1.len(), + control_points[0].len(), + )) + } else if knot_vecs.0.range_length().so_small() || knot_vecs.1.range_length().so_small() { + Err(Error::ZeroRange) + } else { + let len = control_points[0].len(); + if control_points.iter().any(|vec| vec.len() != len) { + Err(Error::IrregularControlPoints) + } else { + Ok(BSplineSurface::new_unchecked(knot_vecs, control_points)) + } + } + } + + /// constructor. + /// # Arguments + /// * `knot_vecs` - the knot vectors + /// * `control_points` - the vector of the control points + /// # Failures + /// This method is prepared only for performance-critical development and is not recommended. + /// This method does NOT check the 3 rules for constructing B-spline surface. + /// The programmer must guarantee these conditions before using this method. + #[inline(always)] + pub const fn new_unchecked( + knot_vecs: (KnotVec, KnotVec), + control_points: Vec>, + ) -> BSplineSurface

{ + BSplineSurface { + knot_vecs, + control_points, + } + } + + /// constructor. + /// # Arguments + /// * `knot_vecs` - the knot vectors + /// * `control_points` - the vector of the control points + /// # Failures + /// This method checks the 3 rules for constructing B-spline surface in the debug mode. + /// The programmer must guarantee these conditions before using this method. + #[inline(always)] + pub fn debug_new( + knot_vecs: (KnotVec, KnotVec), + control_points: Vec>, + ) -> BSplineSurface

{ + match cfg!(debug_assertions) { + true => Self::new(knot_vecs, control_points), + false => Self::new_unchecked(knot_vecs, control_points), + } + } + /// Returns the reference of the knot vectors + #[inline(always)] + pub const fn knot_vecs(&self) -> &(KnotVec, KnotVec) { &self.knot_vecs } + + /// Returns the u knot vector. + #[inline(always)] + pub const fn uknot_vec(&self) -> &KnotVec { &self.knot_vecs.0 } + /// Returns the v knot vector. + #[inline(always)] + pub const fn vknot_vec(&self) -> &KnotVec { &self.knot_vecs.1 } + + /// Returns the `idx`th u knot. + #[inline(always)] + pub fn uknot(&self, idx: usize) -> f64 { self.knot_vecs.0[idx] } + /// returns the `idx`th v knot. + #[inline(always)] + pub fn vknot(&self, idx: usize) -> f64 { self.knot_vecs.1[idx] } + + /// Returns the reference of the vector of the control points + #[inline(always)] + pub const fn control_points(&self) -> &Vec> { &self.control_points } + + /// Returns the reference of the control point corresponding to the index `(idx0, idx1)`. + #[inline(always)] + pub fn control_point(&self, idx0: usize, idx1: usize) -> &P { &self.control_points[idx0][idx1] } + /// Apply the given transformation to all control points. + #[inline(always)] + pub fn transform_control_points(&mut self, f: F) { + self.control_points.iter_mut().flatten().for_each(f) + } + + /// Returns the iterator over the control points in the `column_idx`th row. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let uknot_vec = KnotVec::bezier_knot(1); + /// let vknot_vec = KnotVec::bezier_knot(2); + /// let knot_vecs = (uknot_vec, vknot_vec); + /// let ctrl_pts = vec![ + /// vec![Vector3::new(0.0, 0.0, 0.0), Vector3::new(1.0, 0.0, 1.0), Vector3::new(2.0, 0.0, 2.0)], + /// vec![Vector3::new(0.0, 1.0, 0.0), Vector3::new(1.0, 1.0, 1.0), Vector3::new(2.0, 1.0, 2.0)], + /// ]; + /// let bspsurface = BSplineSurface::new(knot_vecs, ctrl_pts); + /// let mut iter = bspsurface.ctrl_pts_row_iter(1); + /// assert_eq!(iter.next(), Some(&Vector3::new(1.0, 0.0, 1.0))); + /// assert_eq!(iter.next(), Some(&Vector3::new(1.0, 1.0, 1.0))); + /// assert_eq!(iter.next(), None); + /// ``` + #[inline(always)] + pub fn ctrl_pts_row_iter( + &self, + column_idx: usize, + ) -> impl ExactSizeIterator + FusedIterator { + self.control_points.iter().map(move |vec| &vec[column_idx]) + } + + /// Returns the iterator over the control points in the `row_idx`th row. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let uknot_vec = KnotVec::bezier_knot(1); + /// let vknot_vec = KnotVec::bezier_knot(2); + /// let knot_vecs = (uknot_vec, vknot_vec); + /// let ctrl_pts = vec![ + /// vec![Vector3::new(0.0, 0.0, 0.0), Vector3::new(1.0, 0.0, 1.0), Vector3::new(2.0, 0.0, 2.0)], + /// vec![Vector3::new(0.0, 1.0, 0.0), Vector3::new(1.0, 1.0, 1.0), Vector3::new(2.0, 1.0, 2.0)], + /// ]; + /// let bspsurface = BSplineSurface::new(knot_vecs, ctrl_pts); + /// let mut iter = bspsurface.ctrl_pts_column_iter(1); + /// assert_eq!(iter.next(), Some(&Vector3::new(0.0, 1.0, 0.0))); + /// assert_eq!(iter.next(), Some(&Vector3::new(1.0, 1.0, 1.0))); + /// assert_eq!(iter.next(), Some(&Vector3::new(2.0, 1.0, 2.0))); + /// assert_eq!(iter.next(), None); + /// ``` + #[inline(always)] + pub fn ctrl_pts_column_iter(&self, row_idx: usize) -> std::slice::Iter<'_, P> { + self.control_points[row_idx].iter() + } + + /// Returns the mutable reference of the control point corresponding to index `(idx0, idx1)`. + #[inline(always)] + pub fn control_point_mut(&mut self, idx0: usize, idx1: usize) -> &mut P { + &mut self.control_points[idx0][idx1] + } + + /// Returns the iterator on all control points + #[inline(always)] + pub fn control_points_mut(&mut self) -> impl Iterator { + self.control_points.iter_mut().flatten() + } + /// Returns the degrees of B-spline surface + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let uknot_vec = KnotVec::from(vec![0.0, 0.0, 1.0, 1.0]); + /// let vknot_vec = KnotVec::from(vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0]); + /// let knot_vecs = (uknot_vec, vknot_vec); + /// let ctrl_pts = vec![ + /// vec![Vector3::new(0.0, 0.0, 0.0), Vector3::new(1.0, 0.0, 1.0), Vector3::new(2.0, 0.0, 2.0)], + /// vec![Vector3::new(0.0, 1.0, 0.0), Vector3::new(1.0, 1.0, 1.0), Vector3::new(2.0, 1.0, 2.0)], + /// ]; + /// let bspsurface = BSplineSurface::new(knot_vecs, ctrl_pts); + /// assert_eq!(bspsurface.udegree(), 1); + /// ``` + #[inline(always)] + pub fn udegree(&self) -> usize { self.knot_vecs.0.len() - self.control_points.len() - 1 } + + /// Returns the degrees of B-spline surface + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let uknot_vec = KnotVec::from(vec![0.0, 0.0, 1.0, 1.0]); + /// let vknot_vec = KnotVec::from(vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0]); + /// let knot_vecs = (uknot_vec, vknot_vec); + /// let ctrl_pts = vec![ + /// vec![Vector3::new(0.0, 0.0, 0.0), Vector3::new(1.0, 0.0, 1.0), Vector3::new(2.0, 0.0, 2.0)], + /// vec![Vector3::new(0.0, 1.0, 0.0), Vector3::new(1.0, 1.0, 1.0), Vector3::new(2.0, 1.0, 2.0)], + /// ]; + /// let bspsurface = BSplineSurface::new(knot_vecs, ctrl_pts); + /// assert_eq!(bspsurface.vdegree(), 2); + /// ``` + #[inline(always)] + pub fn vdegree(&self) -> usize { self.knot_vecs.1.len() - self.control_points[0].len() - 1 } + + /// Returns the degrees of B-spline surface + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let uknot_vec = KnotVec::from(vec![0.0, 0.0, 1.0, 1.0]); + /// let vknot_vec = KnotVec::from(vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0]); + /// let knot_vecs = (uknot_vec, vknot_vec); + /// let ctrl_pts = vec![ + /// vec![Vector3::new(0.0, 0.0, 0.0), Vector3::new(1.0, 0.0, 1.0), Vector3::new(2.0, 0.0, 2.0)], + /// vec![Vector3::new(0.0, 1.0, 0.0), Vector3::new(1.0, 1.0, 1.0), Vector3::new(2.0, 1.0, 2.0)], + /// ]; + /// let bspsurface = BSplineSurface::new(knot_vecs, ctrl_pts); + /// assert_eq!(bspsurface.degrees(), (1, 2)); + /// ``` + #[inline(always)] + pub fn degrees(&self) -> (usize, usize) { (self.udegree(), self.vdegree()) } + /// Returns whether the knot vectors are clamped or not. + #[inline(always)] + pub fn is_clamped(&self) -> bool { + self.knot_vecs.0.is_clamped(self.udegree()) && self.knot_vecs.1.is_clamped(self.vdegree()) + } + + /// Swaps two parameters. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vecs0 = (KnotVec::bezier_knot(1), KnotVec::bezier_knot(2)); + /// let ctrl_pts0 = vec![ + /// vec![Vector2::new(0.0, 0.0), Vector2::new(0.5, -1.0), Vector2::new(1.0, 0.0)], + /// vec![Vector2::new(0.0, 1.0), Vector2::new(0.5, 2.0), Vector2::new(1.0, 1.0)], + /// ]; + /// let mut bspsurface0 = BSplineSurface::new(knot_vecs0, ctrl_pts0); + /// + /// let knot_vecs1 = (KnotVec::bezier_knot(2), KnotVec::bezier_knot(1)); + /// let ctrl_pts1 = vec![ + /// vec![Vector2::new(0.0, 0.0), Vector2::new(0.0, 1.0)], + /// vec![Vector2::new(0.5, -1.0), Vector2::new(0.5, 2.0)], + /// vec![Vector2::new(1.0, 0.0), Vector2::new(1.0, 1.0)], + /// ]; + /// let mut bspsurface1 = BSplineSurface::new(knot_vecs1, ctrl_pts1); + /// assert_eq!(bspsurface0.swap_axes(), &bspsurface1); + /// ``` + pub fn swap_axes(&mut self) -> &mut Self + where P: Clone { + let knot_vec = self.knot_vecs.0.clone(); + self.knot_vecs.0 = self.knot_vecs.1.clone(); + self.knot_vecs.1 = knot_vec; + + let n0 = self.control_points.len(); + let n1 = self.control_points[0].len(); + let mut new_points = vec![Vec::with_capacity(n0); n1]; + for pts in &self.control_points { + for (vec0, pt) in new_points.iter_mut().zip(pts) { + vec0.push(pt.clone()); + } + } + self.control_points = new_points; + self + } + + /// The range of the parameter of the surface. + #[inline(always)] + pub fn parameter_range(&self) -> (ParameterRange, ParameterRange) { + ( + ( + Bound::Included(self.knot_vecs.0[0]), + Bound::Included(self.knot_vecs.0[self.knot_vecs.0.len() - 1]), + ), + ( + Bound::Included(self.knot_vecs.1[0]), + Bound::Included(self.knot_vecs.1[self.knot_vecs.1.len() - 1]), + ), + ) + } + /// Creates the curve whose control points are the `idx`th column control points of `self`. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let uknot_vec = KnotVec::bezier_knot(1); + /// let vknot_vec = KnotVec::bezier_knot(2); + /// let knot_vecs = (uknot_vec, vknot_vec); + /// let ctrl_pts = vec![ + /// vec![Vector3::new(0.0, 0.0, 0.0), Vector3::new(1.0, 0.0, 1.0), Vector3::new(2.0, 0.0, 2.0)], + /// vec![Vector3::new(0.0, 1.0, 0.0), Vector3::new(1.0, 1.0, 1.0), Vector3::new(2.0, 1.0, 2.0)], + /// ]; + /// let bspsurface = BSplineSurface::new(knot_vecs, ctrl_pts); + /// let bspcurve = bspsurface.column_curve(1); + /// + /// assert_eq!(bspcurve.knot_vec(), &KnotVec::bezier_knot(2)); + /// assert_eq!( + /// bspcurve.control_points(), + /// &vec![Vector3::new(0.0, 1.0, 0.0), Vector3::new(1.0, 1.0, 1.0), Vector3::new(2.0, 1.0, 2.0)], + /// ); + /// ``` + pub fn column_curve(&self, row_idx: usize) -> BSplineCurve

+ where P: Clone { + let knot_vec = self.vknot_vec().clone(); + let ctrl_pts = self.control_points[row_idx].clone(); + BSplineCurve::new_unchecked(knot_vec, ctrl_pts) + } + /// Creates the column sectional curve. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let uknot_vec = KnotVec::bezier_knot(1); + /// let vknot_vec = KnotVec::bezier_knot(2); + /// let knot_vecs = (uknot_vec, vknot_vec); + /// let ctrl_pts = vec![ + /// vec![Vector3::new(0.0, 0.0, 0.0), Vector3::new(1.0, 0.0, 1.0), Vector3::new(2.0, 0.0, 2.0)], + /// vec![Vector3::new(0.0, 1.0, 0.0), Vector3::new(1.0, 1.0, 1.0), Vector3::new(2.0, 1.0, 2.0)], + /// ]; + /// let bspsurface = BSplineSurface::new(knot_vecs, ctrl_pts); + /// let bspcurve = bspsurface.row_curve(1); + /// + /// assert_eq!(bspcurve.knot_vec(), &KnotVec::bezier_knot(1)); + /// assert_eq!( + /// bspcurve.control_points(), + /// &vec![Vector3::new(1.0, 0.0, 1.0), Vector3::new(1.0, 1.0, 1.0)], + /// ); + /// ``` + pub fn row_curve(&self, column_idx: usize) -> BSplineCurve

+ where P: Clone { + let knot_vec = self.uknot_vec().clone(); + let ctrl_pts: Vec<_> = self.ctrl_pts_row_iter(column_idx).cloned().collect(); + BSplineCurve::new_unchecked(knot_vec, ctrl_pts) + } +} + +impl> BSplineSurface

{ + /// Returns the closure of substitution. + #[inline(always)] + pub fn get_closure(&self) -> impl Fn(f64, f64) -> P + '_ { move |u, v| self.subs(u, v) } + + #[inline(always)] + fn udelta_control_points(&self, i: usize, j: usize) -> P::Diff { + if i == 0 { + self.control_point(i, j).to_vec() + } else if i == self.control_points.len() { + self.control_point(i - 1, j).to_vec() * (-1.0) + } else { + *self.control_point(i, j) - *self.control_point(i - 1, j) + } + } + + #[inline(always)] + fn udelta2_control_points(&self, i: usize, j: usize) -> P::Diff { + let k = self.udegree(); + let knot_vec = self.uknot_vec(); + if i == 0 { + let coef = inv_or_zero(knot_vec[i + k] - knot_vec[i]); + self.udelta_control_points(i, j) * coef + } else if i == self.control_points.len() + 1 { + let coef = inv_or_zero(knot_vec[i - 1 + k] - knot_vec[i - 1]); + self.udelta_control_points(i - 1, j) * (-coef) + } else { + let coef0 = inv_or_zero(knot_vec[i + k] - knot_vec[i]); + let coef1 = inv_or_zero(knot_vec[i - 1 + k] - knot_vec[i - 1]); + self.udelta_control_points(i, j) * coef0 - self.udelta_control_points(i - 1, j) * coef1 + } + } + + #[inline(always)] + fn vdelta_control_points(&self, i: usize, j: usize) -> P::Diff { + if j == 0 { + self.control_point(i, j).to_vec() + } else if j == self.control_points[0].len() { + self.control_point(i, j - 1).to_vec() * (-1.0) + } else { + *self.control_point(i, j) - *self.control_point(i, j - 1) + } + } + + #[inline(always)] + fn vdelta2_control_points(&self, i: usize, j: usize) -> P::Diff { + let k = self.vdegree(); + let knot_vec = self.vknot_vec(); + if j == 0 { + let coef = inv_or_zero(knot_vec[j + k] - knot_vec[j]); + self.vdelta_control_points(i, j) * coef + } else if j == self.control_points[0].len() + 1 { + let coef = inv_or_zero(knot_vec[j - 1 + k] - knot_vec[j - 1]); + self.vdelta_control_points(i, j - 1) * (-coef) + } else { + let coef0 = inv_or_zero(knot_vec[j + k] - knot_vec[j]); + let coef1 = inv_or_zero(knot_vec[j - 1 + k] - knot_vec[j - 1]); + self.vdelta_control_points(i, j) * coef0 - self.vdelta_control_points(i, j - 1) * coef1 + } + } + + /// Calculate derived B-spline surface by the first parameter `u`. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vecs = (KnotVec::bezier_knot(1), KnotVec::bezier_knot(2)); + /// let ctrl_pts = vec![ + /// vec![Vector2::new(0.0, 0.0), Vector2::new(0.5, -1.0), Vector2::new(1.0, 0.0)], + /// vec![Vector2::new(0.0, 1.0), Vector2::new(0.5, 2.0), Vector2::new(1.0, 1.0)], + /// ]; + /// let bspsurface = BSplineSurface::new(knot_vecs, ctrl_pts); + /// let uderivation = bspsurface.uderivation(); + /// + /// // bspsurface: (v, 2v(1 - v)(2u - 1) + u), uderivation: (0.0, 4v(1 - v) + 1) + /// const N: usize = 100; // sample size + /// for i in 1..N { + /// let u = (i as f64) / (N as f64); + /// for j in 0..=N { + /// let v = (j as f64) / (N as f64); + /// assert_near2!( + /// uderivation.subs(u, v), + /// Vector2::new(0.0, 4.0 * v * (1.0 - v) + 1.0), + /// ); + /// } + /// } + /// ``` + pub fn uderivation(&self) -> BSplineSurface { + let n0 = self.control_points.len(); + let n1 = self.control_points[0].len(); + let (k, _) = self.degrees(); + let (uknot_vec, vknot_vec) = self.knot_vecs.clone(); + + let new_points = if k > 0 { + (0..=n0) + .map(|i| { + let delta = uknot_vec[i + k] - uknot_vec[i]; + let coef = (k as f64) * inv_or_zero(delta); + (0..n1) + .map(|j| self.udelta_control_points(i, j) * coef) + .collect() + }) + .collect() + } else { + vec![vec![P::Diff::zero(); n1]; n0] + }; + + BSplineSurface::new_unchecked((uknot_vec, vknot_vec), new_points) + } + + /// Calculate derived B-spline surface by the second parameter `v`. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vecs = (KnotVec::bezier_knot(1), KnotVec::bezier_knot(2)); + /// let ctrl_pts = vec![ + /// vec![Vector2::new(0.0, 0.0), Vector2::new(0.5, -1.0), Vector2::new(1.0, 0.0)], + /// vec![Vector2::new(0.0, 1.0), Vector2::new(0.5, 2.0), Vector2::new(1.0, 1.0)], + /// ]; + /// let bspsurface = BSplineSurface::new(knot_vecs, ctrl_pts); + /// let vderivation = bspsurface.vderivation(); + /// + /// // bspsurface: (v, 2v(1 - v)(2u - 1) + u), vderivation: (1, -2(2u - 1)(2v - 1)) + /// const N: usize = 100; // sample size + /// for i in 0..=N { + /// let u = (i as f64) / (N as f64); + /// for j in 0..=N { + /// let v = (j as f64) / (N as f64); + /// assert_near2!( + /// vderivation.subs(u, v), + /// Vector2::new(1.0, -2.0 * (2.0 * u - 1.0) * (2.0 * v - 1.0)), + /// ); + /// } + /// } + /// ``` + pub fn vderivation(&self) -> BSplineSurface { + let n0 = self.control_points.len(); + let n1 = self.control_points[0].len(); + let (_, k) = self.degrees(); + + let (uknot_vec, vknot_vec) = self.knot_vecs.clone(); + + let new_points = if k > 0 { + let mut new_points = vec![Vec::with_capacity(n1 + 1); n0]; + for j in 0..=n1 { + let delta = vknot_vec[j + k] - vknot_vec[j]; + let coef = (k as f64) * inv_or_zero(delta); + for (i, vec) in new_points.iter_mut().enumerate() { + vec.push(self.vdelta_control_points(i, j) * coef) + } + } + new_points + } else { + vec![vec![P::Diff::zero(); n1]; n0] + }; + + BSplineSurface::new_unchecked((uknot_vec, vknot_vec), new_points) + } + + pub(super) fn sub_near_as_surface bool>( + &self, + other: &BSplineSurface

, + div_coef: usize, + ord: F, + ) -> bool { + if !self.knot_vecs.0.same_range(&other.knot_vecs.0) { + return false; + } + if !self.knot_vecs.1.same_range(&other.knot_vecs.1) { + return false; + } + + let (self_degree0, self_degree1) = self.degrees(); + let (other_degree0, other_degree1) = other.degrees(); + let division0 = std::cmp::max(self_degree0, other_degree0) * div_coef; + let division1 = std::cmp::max(self_degree1, other_degree1) * div_coef; + + for i0 in 1..self.knot_vecs.0.len() { + let delta0 = self.knot_vecs.0[i0] - self.knot_vecs.0[i0 - 1]; + if delta0.so_small() { + continue; + } + for j0 in 0..division0 { + let u = self.knot_vecs.0[i0 - 1] + delta0 * (j0 as f64) / (division0 as f64); + for i1 in 1..self.knot_vecs.1.len() { + let delta1 = self.knot_vecs.1[i1] - self.knot_vecs.1[i1 - 1]; + if delta1.so_small() { + continue; + } + for j1 in 0..division1 { + let v = + self.knot_vecs.1[i1 - 1] + delta1 * (j1 as f64) / (division1 as f64); + if !ord(&self.subs(u, v), &other.subs(u, v)) { + return false; + } + } + } + } + } + true + } +} + +impl> BSplineSurface { + /// lift up control points to homogeneous coordinate. + pub fn lift_up(surface: BSplineSurface) -> Self { + let control_points = surface + .control_points + .into_iter() + .map(|vec| vec.into_iter().map(V::from_point).collect()) + .collect(); + BSplineSurface::new_unchecked(surface.knot_vecs, control_points) + } +} + +impl> ParametricSurface for BSplineSurface

{ + type Point = P; + type Vector = P::Diff; + /// Substitutes to a B-spline surface. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vecs = (KnotVec::bezier_knot(1), KnotVec::bezier_knot(2)); + /// let ctrl_pts = vec![ + /// vec![Vector2::new(0.0, 0.0), Vector2::new(0.5, -1.0), Vector2::new(1.0, 0.0)], + /// vec![Vector2::new(0.0, 1.0), Vector2::new(0.5, 2.0), Vector2::new(1.0, 1.0)], + /// ]; + /// let bspsurface = BSplineSurface::new(knot_vecs, ctrl_pts); + /// + /// // bspsurface: (v, 2v(1 - v)(2u - 1) + u) + /// const N: usize = 100; // sample size + /// for i in 0..=N { + /// let u = (i as f64) / (N as f64); + /// for j in 0..=N { + /// let v = (j as f64) / (N as f64); + /// assert_near2!( + /// bspsurface.subs(u, v), + /// Vector2::new(v, 2.0 * v * (1.0 - v) * (2.0 * u - 1.0) + u), + /// ); + /// } + /// } + /// ``` + #[inline(always)] + fn subs(&self, u: f64, v: f64) -> P { + let (degree0, degree1) = self.degrees(); + let BSplineSurface { + knot_vecs: (ref uknot_vec, ref vknot_vec), + ref control_points, + } = self; + let basis0 = uknot_vec.bspline_basis_functions(degree0, u); + let basis1 = vknot_vec.bspline_basis_functions(degree1, v); + let closure = move |sum: P, (vec, b0): (&Vec

, f64)| { + let closure = move |sum: P, (pt, b1): (&P, &f64)| sum + pt.to_vec() * (b0 * b1); + vec.iter().zip(&basis1).fold(sum, closure) + }; + control_points.iter().zip(basis0).fold(P::origin(), closure) + } + /// Substitutes derived B-spline surface by the first parameter `u`. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vecs = (KnotVec::bezier_knot(1), KnotVec::bezier_knot(2)); + /// let ctrl_pts = vec![ + /// vec![Vector2::new(0.0, 0.0), Vector2::new(0.5, -1.0), Vector2::new(1.0, 0.0)], + /// vec![Vector2::new(0.0, 1.0), Vector2::new(0.5, 2.0), Vector2::new(1.0, 1.0)], + /// ]; + /// let bspsurface = BSplineSurface::new(knot_vecs, ctrl_pts); + /// + /// // bspsurface: (v, 2v(1 - v)(2u - 1) + u), uderivation: (0.0, 4v(1 - v) + 1) + /// const N: usize = 100; // sample size + /// for i in 0..=N { + /// let u = (i as f64) / (N as f64); + /// for j in 0..=N { + /// let v = (j as f64) / (N as f64); + /// assert_near2!( + /// bspsurface.uder(u, v), + /// Vector2::new(0.0, 4.0 * v * (1.0 - v) + 1.0), + /// ); + /// } + /// } + /// ``` + #[inline(always)] + fn uder(&self, u: f64, v: f64) -> P::Diff { + let (degree0, degree1) = self.degrees(); + let (uknot_vec, vknot_vec) = self.knot_vecs(); + let basis0 = uknot_vec.bspline_basis_functions(degree0 - 1, u); + let basis1 = vknot_vec.bspline_basis_functions(degree1, v); + let closure = move |sum: P::Diff, (i, b0): (usize, f64)| { + let coef = inv_or_zero(uknot_vec[i + degree0] - uknot_vec[i]); + let closure = |sum: P::Diff, (j, b1): (usize, &f64)| { + sum + self.udelta_control_points(i, j) * coef * b0 * *b1 + }; + basis1.iter().enumerate().fold(sum, closure) + }; + basis0 + .into_iter() + .enumerate() + .fold(P::Diff::zero(), closure) + * degree0 as f64 + } + /// Substitutes derived B-spline surface by the first parameter `v`. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vecs = (KnotVec::bezier_knot(1), KnotVec::bezier_knot(2)); + /// let ctrl_pts = vec![ + /// vec![Vector2::new(0.0, 0.0), Vector2::new(0.5, -1.0), Vector2::new(1.0, 0.0)], + /// vec![Vector2::new(0.0, 1.0), Vector2::new(0.5, 2.0), Vector2::new(1.0, 1.0)], + /// ]; + /// let bspsurface = BSplineSurface::new(knot_vecs, ctrl_pts); + /// + /// // bspsurface: (v, 2v(1 - v)(2u - 1) + u), vderivation: (1, -2(2u - 1)(2v - 1)) + /// const N: usize = 100; // sample size + /// for i in 0..=N { + /// let u = (i as f64) / (N as f64); + /// for j in 0..=N { + /// let v = (j as f64) / (N as f64); + /// assert_near2!( + /// bspsurface.vder(u, v), + /// Vector2::new(1.0, -2.0 * (2.0 * u - 1.0) * (2.0 * v - 1.0)), + /// ); + /// } + /// } + /// ``` + #[inline(always)] + fn vder(&self, u: f64, v: f64) -> P::Diff { + let (degree0, degree1) = self.degrees(); + let (uknot_vec, vknot_vec) = self.knot_vecs(); + let basis0 = uknot_vec.bspline_basis_functions(degree0, u); + let basis1 = vknot_vec.bspline_basis_functions(degree1 - 1, v); + let closure = move |sum: P::Diff, (i, b0): (usize, f64)| { + let coef = inv_or_zero(vknot_vec[i + degree1] - vknot_vec[i]); + let closure = |sum: P::Diff, (j, b1): (usize, &f64)| { + sum + self.vdelta_control_points(j, i) * coef * b0 * *b1 + }; + basis0.iter().enumerate().fold(sum, closure) + }; + basis1 + .into_iter() + .enumerate() + .fold(P::Diff::zero(), closure) + * degree1 as f64 + } + + /// Substitutes 2nd-ord derived B-spline surface by the first parameter `u`. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vecs = (KnotVec::bezier_knot(2), KnotVec::bezier_knot(2)); + /// let ctrl_pts = vec![ + /// vec![Vector2::new(0.0, 0.0), Vector2::new(0.5, -1.0), Vector2::new(1.0, 0.0)], + /// vec![Vector2::new(0.0, 0.5), Vector2::new(0.5, 1.0), Vector2::new(1.0, 0.5)], + /// vec![Vector2::new(0.0, 1.0), Vector2::new(0.5, 2.0), Vector2::new(1.0, 1.0)], + /// ]; + /// let bspsurface = BSplineSurface::new(knot_vecs, ctrl_pts); + /// + /// // bspsurface: (v, 2 u^2 v^2 - 2 u^2 v - 6 u v^2 + 6uv + 2v^2 + u - 2v) + /// // uuder: (0, 4v(v - 1)) + /// const N: usize = 100; // sample size + /// for i in 0..=N { + /// let u = (i as f64) / (N as f64); + /// for j in 0..=N { + /// let v = (j as f64) / (N as f64); + /// assert_near2!( + /// bspsurface.uuder(u, v), + /// Vector2::new(0.0, 4.0 * v * (v - 1.0)), + /// ); + /// } + /// } + /// ``` + #[inline(always)] + fn uuder(&self, u: f64, v: f64) -> P::Diff { + let (degree0, degree1) = self.degrees(); + if degree0 < 2 { + return P::Diff::zero(); + } + let (uknot_vec, vknot_vec) = self.knot_vecs(); + let basis0 = uknot_vec.bspline_basis_functions(degree0 - 2, u); + let basis1 = vknot_vec.bspline_basis_functions(degree1, v); + let closure = move |sum: P::Diff, (i, b0): (usize, f64)| { + let coef = inv_or_zero(uknot_vec[i + degree0 - 1] - uknot_vec[i]); + let closure = |sum: P::Diff, (j, b1): (usize, &f64)| { + sum + self.udelta2_control_points(i, j) * coef * b0 * *b1 + }; + basis1.iter().enumerate().fold(sum, closure) + }; + basis0 + .into_iter() + .enumerate() + .fold(P::Diff::zero(), closure) + * degree0 as f64 + } + + /// Substitutes 2nd-ord derived B-spline surface by the second parameter `v`. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vecs = (KnotVec::bezier_knot(2), KnotVec::bezier_knot(2)); + /// let ctrl_pts = vec![ + /// vec![Vector2::new(0.0, 0.0), Vector2::new(0.5, -1.0), Vector2::new(1.0, 0.0)], + /// vec![Vector2::new(0.0, 0.5), Vector2::new(0.5, 1.0), Vector2::new(1.0, 0.5)], + /// vec![Vector2::new(0.0, 1.0), Vector2::new(0.5, 2.0), Vector2::new(1.0, 1.0)], + /// ]; + /// let bspsurface = BSplineSurface::new(knot_vecs, ctrl_pts); + /// + /// // bspsurface: (v, 2 u^2 v^2 - 2 u^2 v - 6 u v^2 + 6uv + 2v^2 + u - 2v) + /// // vvder: (0, 4(u^2 - 3u + 1)) + /// const N: usize = 100; // sample size + /// for i in 0..=N { + /// let u = (i as f64) / (N as f64); + /// for j in 0..=N { + /// let v = (j as f64) / (N as f64); + /// assert_near2!( + /// bspsurface.vvder(u, v), + /// Vector2::new(0.0, 4.0 * (u * u - 3.0 * u + 1.0)), + /// ); + /// } + /// } + /// ``` + #[inline(always)] + fn vvder(&self, u: f64, v: f64) -> P::Diff { + let (degree0, degree1) = self.degrees(); + if degree1 < 2 { + return P::Diff::zero(); + } + let (uknot_vec, vknot_vec) = self.knot_vecs(); + let basis0 = uknot_vec.bspline_basis_functions(degree0, u); + let basis1 = vknot_vec.bspline_basis_functions(degree1 - 2, v); + let closure = move |sum: P::Diff, (j, b0): (usize, f64)| { + let coef = inv_or_zero(vknot_vec[j + degree1 - 1] - vknot_vec[j]); + let closure = |sum: P::Diff, (i, b1): (usize, &f64)| { + sum + self.vdelta2_control_points(i, j) * coef * b0 * *b1 + }; + basis0.iter().enumerate().fold(sum, closure) + }; + basis1 + .into_iter() + .enumerate() + .fold(P::Diff::zero(), closure) + * degree1 as f64 + } + + /// Substitutes 2nd-ord derived B-spline surface by the both parameters `u, v`. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vecs = (KnotVec::bezier_knot(2), KnotVec::bezier_knot(2)); + /// let ctrl_pts = vec![ + /// vec![Vector2::new(0.0, 0.0), Vector2::new(0.5, -1.0), Vector2::new(1.0, 0.0)], + /// vec![Vector2::new(0.0, 0.5), Vector2::new(0.5, 1.0), Vector2::new(1.0, 0.5)], + /// vec![Vector2::new(0.0, 1.0), Vector2::new(0.5, 2.0), Vector2::new(1.0, 1.0)], + /// ]; + /// let bspsurface = BSplineSurface::new(knot_vecs, ctrl_pts); + /// + /// // bspsurface: (v, 2 u^2 v^2 - 2 u^2 v - 6 u v^2 + 6uv + 2v^2 + u - 2v) + /// // uvder: (0, 8uv - 4u - 12v + 6) + /// const N: usize = 100; // sample size + /// for i in 0..=N { + /// let u = (i as f64) / (N as f64); + /// for j in 0..=N { + /// let v = (j as f64) / (N as f64); + /// assert_near2!( + /// bspsurface.uvder(u, v), + /// Vector2::new(0.0, 8.0 * u * v - 4.0 * u - 12.0 * v + 6.0), + /// ); + /// } + /// } + /// ``` + #[inline(always)] + fn uvder(&self, u: f64, v: f64) -> P::Diff { + let (degree0, degree1) = self.degrees(); + let BSplineSurface { + knot_vecs: (ref uknot_vec, ref vknot_vec), + ref control_points, + } = self; + let basis0 = uknot_vec.bspline_basis_functions(degree0 - 1, u); + let basis1 = vknot_vec.bspline_basis_functions(degree1 - 1, v); + let closure = |sum: P::Diff, (i, vec): (usize, &Vec

)| { + let coef0 = inv_or_zero(uknot_vec[i + degree0] - uknot_vec[i]); + let coef1 = inv_or_zero(uknot_vec[i + degree0 + 1] - uknot_vec[i + 1]); + let b0 = basis0[i] * coef0 - basis0[i + 1] * coef1; + let closure = |sum: P::Diff, (j, pt): (usize, &P)| { + let coef0 = inv_or_zero(vknot_vec[j + degree1] - vknot_vec[j]); + let coef1 = inv_or_zero(vknot_vec[j + degree1 + 1] - vknot_vec[j + 1]); + sum + pt.to_vec() * (basis1[j] * coef0 - basis1[j + 1] * coef1) * b0 + }; + vec.iter().enumerate().fold(sum, closure) + }; + control_points + .iter() + .enumerate() + .fold(P::Diff::zero(), closure) + * degree0 as f64 + * degree1 as f64 + } + #[inline(always)] + fn parameter_range(&self) -> (ParameterRange, ParameterRange) { self.parameter_range() } +} + +impl BSplineSurface { + /// Returns whether all control points are same or not. + /// If the knot vector is clamped, it means whether the curve is constant or not. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let uknot_vec = KnotVec::bezier_knot(1); + /// let vknot_vec = KnotVec::bezier_knot(2); + /// let pt = Vector2::new(1.0, 2.0); + /// let ctrl_pts = vec![ + /// vec![pt.clone(), pt.clone(), pt.clone()], + /// vec![pt.clone(), pt.clone(), pt.clone()], + /// ]; + /// let mut bspsurface = BSplineSurface::new((uknot_vec, vknot_vec), ctrl_pts); + /// assert!(bspsurface.is_const()); + /// + /// *bspsurface.control_point_mut(1, 2) = Vector2::new(2.0, 3.0); + /// assert!(!bspsurface.is_const()); + /// ``` + /// # Remarks + /// If the knot vector is not clamped and the BSpline basis function is not partition of unity, + /// then perhaps returns true even if the surface is not constant. + /// ``` + /// use truck_geometry::prelude::*; + /// let uknot_vec = KnotVec::uniform_knot(1, 5); + /// let vknot_vec = KnotVec::uniform_knot(1, 5); + /// let pt = Vector2::new(1.0, 2.0); + /// let ctrl_pts = vec![ + /// vec![pt.clone(), pt.clone(), pt.clone()], + /// vec![pt.clone(), pt.clone(), pt.clone()], + /// ]; + /// let mut bspsurface = BSplineSurface::new((uknot_vec, vknot_vec), ctrl_pts); + /// + /// // bspsurface is not constant. + /// assert_eq!(bspsurface.subs(0.0, 0.0), Vector2::new(0.0, 0.0)); + /// assert_ne!(bspsurface.subs(0.5, 0.5), Vector2::new(0.0, 0.0)); + /// + /// // bspsurface.is_const() is true. + /// assert!(bspsurface.is_const()); + /// ``` + #[inline(always)] + pub fn is_const(&self) -> bool { + for vec in self.control_points.iter().flat_map(|pts| pts.iter()) { + if !vec.near(&self.control_points[0][0]) { + return false; + } + } + true + } +} + +impl + Tolerance> BSplineSurface

{ + /// Adds a knot `x` of the first parameter `u`, and do not change `self` as a surface. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vecs = (KnotVec::bezier_knot(1), KnotVec::bezier_knot(2)); + /// let ctrl_pts = vec![ + /// vec![Vector2::new(0.0, 0.0), Vector2::new(0.5, -1.0), Vector2::new(1.0, 0.0)], + /// vec![Vector2::new(0.0, 1.0), Vector2::new(0.5, 2.0), Vector2::new(1.0, 1.0)], + /// ]; + /// let mut bspsurface = BSplineSurface::new(knot_vecs, ctrl_pts); + /// let org_surface = bspsurface.clone(); + /// bspsurface.add_uknot(0.0).add_uknot(0.3).add_uknot(0.5).add_uknot(1.0); + /// assert!(bspsurface.near2_as_surface(&org_surface)); + /// assert_eq!(bspsurface.uknot_vec().len(), org_surface.uknot_vec().len() + 4); + /// ``` + pub fn add_uknot(&mut self, x: f64) -> &mut Self { + let k = self.udegree(); + let n0 = self.control_points.len(); + let n1 = self.control_points[0].len(); + let uknot_vec = &mut self.knot_vecs.0; + let control_points = &mut self.control_points; + if x < uknot_vec[0] { + uknot_vec.add_knot(x); + control_points.insert(0, vec![P::origin(); n1]); + return self; + } + + let idx = uknot_vec.add_knot(x); + let start = if idx > k { idx - k } else { 0 }; + let end = if idx > n0 { + control_points.push(vec![P::origin(); n1]); + n0 + 1 + } else { + control_points.insert(idx - 1, control_points[idx - 1].clone()); + idx + }; + for i in start..end { + let i0 = end + start - i - 1; + let delta = self.uknot(i0 + k + 1) - self.uknot(i0); + let a = inv_or_zero(delta) * (self.uknot(idx) - self.uknot(i0)); + for j in 0..n1 { + let p = self.udelta_control_points(i0, j) * (1.0 - a); + self.control_points[i0][j] -= p; + } + } + self + } + + /// Adds a knot `x` for the second parameter, and do not change `self` as a surface. + /// Return `false` if cannot add the knot, i.e. + /// * the index of `x` will be lower than the degree, or + /// * the index of `x` will be higher than the number of control points. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vecs = (KnotVec::bezier_knot(1), KnotVec::bezier_knot(2)); + /// let ctrl_pts = vec![ + /// vec![Vector2::new(0.0, 0.0), Vector2::new(0.5, -1.0), Vector2::new(1.0, 0.0)], + /// vec![Vector2::new(0.0, 1.0), Vector2::new(0.5, 2.0), Vector2::new(1.0, 1.0)], + /// ]; + /// let mut bspsurface = BSplineSurface::new(knot_vecs, ctrl_pts); + /// let org_surface = bspsurface.clone(); + /// bspsurface.add_vknot(0.0).add_vknot(0.3).add_vknot(0.5).add_vknot(1.0); + /// assert!(bspsurface.near2_as_surface(&org_surface)); + /// assert_eq!(bspsurface.vknot_vec().len(), org_surface.vknot_vec().len() + 4); + /// ``` + pub fn add_vknot(&mut self, x: f64) -> &mut Self { + if x < self.knot_vecs.1[0] { + self.knot_vecs.1.add_knot(x); + self.control_points + .iter_mut() + .for_each(|vec| vec.insert(0, P::origin())); + return self; + } + + let k = self.vdegree(); + let n0 = self.control_points.len(); + let n1 = self.control_points[0].len(); + + let idx = self.knot_vecs.1.add_knot(x); + let start = if idx > k { idx - k } else { 0 }; + let end = if idx > n1 { + self.control_points + .iter_mut() + .for_each(|vec| vec.push(P::origin())); + n1 + 1 + } else { + self.control_points + .iter_mut() + .for_each(|vec| vec.insert(idx - 1, vec[idx - 1])); + idx + }; + for j in start..end { + let j0 = end + start - j - 1; + let delta = self.knot_vecs.1[j0 + k + 1] - self.knot_vecs.1[j0]; + let a = inv_or_zero(delta) * (self.knot_vecs.1[idx] - self.knot_vecs.1[j0]); + for i in 0..n0 { + let p = self.vdelta_control_points(i, j0) * (1.0 - a); + self.control_points[i][j0] -= p; + } + } + self + } + + /// Removes the uknot corresponding to the indice `idx`, and do not change `self` as a curve. + /// If the knot cannot be removed, returns + /// [`Error::CannotRemoveKnot`](./errors/enum.Error.html#variant.CannotRemoveKnot). + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// use truck_geometry::errors::Error; + /// let knot_vecs = (KnotVec::bezier_knot(2), KnotVec::bezier_knot(2)); + /// let ctrl_pts = vec![ + /// vec![Vector2::new(0.0, 0.0), Vector2::new(0.5, -1.0), Vector2::new(1.0, 0.0)], + /// vec![Vector2::new(0.0, 1.0), Vector2::new(0.5, 2.0), Vector2::new(1.0, 1.0)], + /// vec![Vector2::new(0.0, 2.0), Vector2::new(0.5, -1.0), Vector2::new(1.0, 2.0)], + /// ]; + /// let mut bspsurface = BSplineSurface::new(knot_vecs, ctrl_pts); + /// let org_surface = bspsurface.clone(); + /// + /// bspsurface.add_uknot(0.3).add_uknot(0.5); + /// + /// assert!(bspsurface.try_remove_uknot(3).is_ok()); + /// assert_eq!(bspsurface.try_remove_uknot(2), Err(Error::CannotRemoveKnot(2))); + /// + /// assert_eq!(bspsurface.uknot_vec().len(), org_surface.uknot_vec().len() + 1); + /// assert!(bspsurface.near2_as_surface(&org_surface)); + /// ``` + pub fn try_remove_uknot(&mut self, idx: usize) -> Result<&mut Self> { + let k = self.udegree(); + let knot_vec = self.uknot_vec(); + let n = self.control_points.len(); + + if idx < k + 1 || idx >= n { + return Err(Error::CannotRemoveKnot(idx)); + } + + let mut new_points = Vec::with_capacity(k + 1); + let first_vec = self + .ctrl_pts_column_iter(idx - k - 1) + .cloned() + .collect::>(); + new_points.push(first_vec); + for i in (idx - k)..idx { + let delta = knot_vec[i + k + 1] - knot_vec[i]; + let a = inv_or_zero(delta) * (knot_vec[idx] - knot_vec[i]); + if a.so_small() { + break; + } else { + let vec = self + .ctrl_pts_column_iter(i) + .zip(new_points.last().unwrap()) + .map(|(pt0, pt1)| *pt1 + (*pt0 - *pt1) / a) + .collect(); + new_points.push(vec); + } + } + + for (pt0, pt1) in self + .ctrl_pts_column_iter(idx) + .zip(new_points.last().unwrap()) + { + if !pt0.near(pt1) { + return Err(Error::CannotRemoveKnot(idx)); + } + } + + for (i, vec) in new_points.into_iter().skip(1).enumerate() { + self.control_points[idx - k + i] = vec; + } + + self.control_points.remove(idx); + self.knot_vecs.0.remove(idx); + Ok(self) + } + + /// Removes the uknot corresponding to the indices `idx`, and do not change `self` as a curve. + /// If cannot remove the knot, do not change `self` and return `self`. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// use truck_geometry::errors::Error; + /// let knot_vecs = (KnotVec::bezier_knot(2), KnotVec::bezier_knot(2)); + /// let ctrl_pts = vec![ + /// vec![Vector2::new(0.0, 0.0), Vector2::new(0.5, -1.0), Vector2::new(1.0, 0.0)], + /// vec![Vector2::new(0.0, 1.0), Vector2::new(0.5, 2.0), Vector2::new(1.0, 1.0)], + /// vec![Vector2::new(0.0, 2.0), Vector2::new(0.5, -1.0), Vector2::new(1.0, 2.0)], + /// ]; + /// let mut bspsurface = BSplineSurface::new(knot_vecs, ctrl_pts); + /// let org_surface = bspsurface.clone(); + /// + /// bspsurface.add_uknot(0.3).add_uknot(0.5); + /// bspsurface.remove_uknot(3).remove_uknot(3); + /// + /// assert!(bspsurface.near2_as_surface(&org_surface)); + /// assert_eq!(bspsurface.uknot_vec().len(), org_surface.uknot_vec().len()) + /// ``` + #[inline(always)] + pub fn remove_uknot(&mut self, idx: usize) -> &mut Self { + let _ = self.try_remove_uknot(idx); + self + } + + /// Removes a vknot corresponding to the indice `idx`, and do not change `self` as a curve. + /// If the knot cannot be removed, returns + /// [`Error::CannotRemoveKnot`](./errors/enum.Error.html#variant.CannotRemoveKnot). + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// use truck_geometry::errors::Error; + /// let knot_vecs = (KnotVec::bezier_knot(2), KnotVec::bezier_knot(2)); + /// let ctrl_pts = vec![ + /// vec![Vector2::new(0.0, 0.0), Vector2::new(0.5, -1.0), Vector2::new(1.0, 0.0)], + /// vec![Vector2::new(0.0, 1.0), Vector2::new(0.5, 2.0), Vector2::new(1.0, 1.0)], + /// vec![Vector2::new(0.0, 2.0), Vector2::new(0.5, -1.0), Vector2::new(1.0, 2.0)], + /// ]; + /// let mut bspsurface = BSplineSurface::new(knot_vecs, ctrl_pts); + /// let org_surface = bspsurface.clone(); + /// + /// bspsurface.add_vknot(0.3).add_vknot(0.5); + /// assert!(bspsurface.try_remove_vknot(3).is_ok()); + /// assert_eq!(bspsurface.try_remove_vknot(2), Err(Error::CannotRemoveKnot(2))); + /// + /// assert!(bspsurface.near2_as_surface(&org_surface)); + /// assert_eq!(bspsurface.vknot_vec().len(), org_surface.vknot_vec().len() + 1); + /// ``` + pub fn try_remove_vknot(&mut self, idx: usize) -> Result<&mut Self> { + let (_, k) = self.degrees(); + let knot_vec = self.vknot_vec(); + let n = self.control_points[0].len(); + + if idx < k + 1 || idx >= n { + return Err(Error::CannotRemoveKnot(idx)); + } + + let mut new_points = Vec::with_capacity(k + 1); + let first_vec = self + .ctrl_pts_row_iter(idx - k - 1) + .cloned() + .collect::>(); + new_points.push(first_vec); + for i in (idx - k)..idx { + let delta = knot_vec[i + k + 1] - knot_vec[i]; + let a = inv_or_zero(delta) * (knot_vec[idx] - knot_vec[i]); + if a.so_small() { + break; + } else { + let vec = self + .ctrl_pts_row_iter(i) + .zip(new_points.last().unwrap()) + .map(|(pt0, pt1)| *pt1 + (*pt0 - *pt1) / a) + .collect(); + new_points.push(vec); + } + } + + for (pt0, pt1) in self.ctrl_pts_row_iter(idx).zip(new_points.last().unwrap()) { + if !pt0.near(pt1) { + return Err(Error::CannotRemoveKnot(idx)); + } + } + + for (i, vec) in new_points.into_iter().skip(1).enumerate() { + for (j, pt) in vec.into_iter().enumerate() { + self.control_points[j][idx - k + i] = pt; + } + } + + for vec in &mut self.control_points { + vec.remove(idx); + } + self.knot_vecs.1.remove(idx); + Ok(self) + } + + /// Removes a uknot corresponding to the indices `idx`, and do not change `self` as a curve. + /// If cannot remove the knot, do not change `self` and return `self`. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// use truck_geometry::errors::Error; + /// let knot_vecs = (KnotVec::bezier_knot(2), KnotVec::bezier_knot(2)); + /// let ctrl_pts = vec![ + /// vec![Vector2::new(0.0, 0.0), Vector2::new(0.5, -1.0), Vector2::new(1.0, 0.0)], + /// vec![Vector2::new(0.0, 1.0), Vector2::new(0.5, 2.0), Vector2::new(1.0, 1.0)], + /// vec![Vector2::new(0.0, 2.0), Vector2::new(0.5, -1.0), Vector2::new(1.0, 2.0)], + /// ]; + /// let mut bspsurface = BSplineSurface::new(knot_vecs, ctrl_pts); + /// let org_surface = bspsurface.clone(); + /// + /// bspsurface.add_vknot(0.3).add_vknot(0.5); + /// bspsurface.remove_vknot(3).remove_vknot(3); + /// + /// assert!(bspsurface.near2_as_surface(&org_surface)); + /// assert_eq!(bspsurface.vknot_vec().len(), org_surface.vknot_vec().len()) + /// ``` + #[inline(always)] + pub fn remove_vknot(&mut self, idx: usize) -> &mut Self { + let _ = self.try_remove_vknot(idx); + self + } + + /// Elevates the vdegree. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vecs = (KnotVec::bezier_knot(2), KnotVec::bezier_knot(2)); + /// let ctrl_pts = vec![ + /// vec![Vector2::new(0.0, 0.0), Vector2::new(0.5, -1.0), Vector2::new(1.0, 0.0)], + /// vec![Vector2::new(0.0, 1.0), Vector2::new(0.5, 2.0), Vector2::new(1.0, 1.0)], + /// vec![Vector2::new(0.0, 2.0), Vector2::new(0.5, -1.0), Vector2::new(1.0, 2.0)], + /// ]; + /// let mut bspsurface = BSplineSurface::new(knot_vecs, ctrl_pts); + /// let org_surface = bspsurface.clone(); + /// + /// bspsurface.elevate_vdegree(); + /// + /// assert_eq!(bspsurface.udegree(), org_surface.udegree()); + /// assert_eq!(bspsurface.vdegree(), org_surface.vdegree() + 1); + /// assert!(bspsurface.near2_as_surface(&org_surface)); + /// ``` + pub fn elevate_vdegree(&mut self) -> &mut Self { + let mut new_knot_vec = KnotVec::new(); + for (i, vec) in self.control_points.iter_mut().enumerate() { + let knot_vec = self.knot_vecs.1.clone(); + let ctrl_pts = vec.clone(); + let mut curve = BSplineCurve::new(knot_vec, ctrl_pts); + curve.elevate_degree(); + if i == 0 { + new_knot_vec = curve.knot_vec().clone(); + } + *vec = curve.control_points; + } + self.knot_vecs.1 = new_knot_vec; + self + } + + /// Elevates the udegree. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vecs = (KnotVec::bezier_knot(2), KnotVec::bezier_knot(2)); + /// let ctrl_pts = vec![ + /// vec![Vector2::new(0.0, 0.0), Vector2::new(0.5, -1.0), Vector2::new(1.0, 0.0)], + /// vec![Vector2::new(0.0, 1.0), Vector2::new(0.5, 2.0), Vector2::new(1.0, 1.0)], + /// vec![Vector2::new(0.0, 2.0), Vector2::new(0.5, -1.0), Vector2::new(1.0, 2.0)], + /// ]; + /// let mut bspsurface = BSplineSurface::new(knot_vecs, ctrl_pts); + /// let org_surface = bspsurface.clone(); + /// + /// bspsurface.elevate_udegree(); + /// + /// assert_eq!(bspsurface.udegree(), org_surface.udegree() + 1); + /// assert_eq!(bspsurface.vdegree(), org_surface.vdegree()); + /// assert!(bspsurface.near2_as_surface(&org_surface)); + /// ``` + pub fn elevate_udegree(&mut self) -> &mut Self { + self.swap_axes(); + self.elevate_vdegree(); + self.swap_axes(); + self + } + + /// Aligns the udegree with the same degrees. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let uknot_vec = KnotVec::bezier_knot(1); + /// let vknot_vec = KnotVec::bezier_knot(2); + /// let knot_vecs = (uknot_vec, vknot_vec); + /// let ctrl_pts = vec![ + /// vec![Vector3::new(0.0, 0.0, 0.0), Vector3::new(1.0, 0.0, 1.0), Vector3::new(2.0, 0.0, 2.0)], + /// vec![Vector3::new(0.0, 1.0, 0.0), Vector3::new(1.0, 1.0, 1.0), Vector3::new(2.0, 1.0, 2.0)], + /// ]; + /// let mut bspsurface = BSplineSurface::new(knot_vecs, ctrl_pts); + /// let org_surface = bspsurface.clone(); + /// + /// assert_ne!(bspsurface.udegree(), bspsurface.vdegree()); + /// bspsurface.syncro_uvdegrees(); + /// assert_eq!(bspsurface.udegree(), bspsurface.vdegree()); + /// assert!(bspsurface.near2_as_surface(&org_surface)); + /// ``` + pub fn syncro_uvdegrees(&mut self) -> &mut Self { + if self.udegree() > self.vdegree() { + for _ in 0..(self.udegree() - self.vdegree()) { + self.elevate_vdegree(); + } + } + if self.vdegree() > self.udegree() { + for _ in 0..(self.vdegree() - self.udegree()) { + self.elevate_udegree(); + } + } + self + } + + /// Makes the uknot vector and the vknot vector the same knot vector. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let uknot_vec = KnotVec::uniform_knot(1, 2); + /// let vknot_vec = KnotVec::bezier_knot(2); + /// let knot_vecs = (uknot_vec, vknot_vec); + /// let ctrl_pts = vec![ + /// vec![Vector3::new(0.0, 0.0, 0.0), Vector3::new(1.0, 0.0, 1.0), Vector3::new(2.0, 0.0, 2.0)], + /// vec![Vector3::new(0.0, 1.0, 0.0), Vector3::new(1.0, 1.0, 1.0), Vector3::new(2.0, 1.0, 2.0)], + /// vec![Vector3::new(0.0, 2.0, 0.0), Vector3::new(1.0, 2.0, 1.0), Vector3::new(2.0, 2.0, 2.0)], + /// ]; + /// let mut bspsurface = BSplineSurface::new(knot_vecs, ctrl_pts); + /// let org_surface = bspsurface.clone(); + /// + /// assert_ne!(bspsurface.uknot_vec(), bspsurface.vknot_vec()); + /// bspsurface.syncro_uvknots(); + /// assert_eq!(bspsurface.uknot_vec(), bspsurface.vknot_vec()); + /// assert!(bspsurface.near2_as_surface(&org_surface)); + /// ``` + pub fn syncro_uvknots(&mut self) -> &mut Self { + self.knot_vecs.0.normalize(); + self.knot_vecs.1.normalize(); + let mut i = 0; + let mut j = 0; + while !self.uknot(i).near2(&1.0) || !self.vknot(j).near2(&1.0) { + if self.uknot(i) - self.vknot(j) > TOLERANCE { + self.add_uknot(self.vknot(j)); + } else if self.vknot(j) - self.uknot(i) > TOLERANCE { + self.add_vknot(self.uknot(i)); + } + i += 1; + j += 1; + } + + let ulen = self.uknot_vec().len(); + let vlen = self.vknot_vec().len(); + use std::cmp::Ordering; + match usize::cmp(&ulen, &vlen) { + Ordering::Less => { + for _ in 0..vlen - ulen { + self.add_uknot(1.0); + } + } + Ordering::Greater => { + for _ in 0..ulen - vlen { + self.add_vknot(1.0); + } + } + _ => {} + } + self + } + + /// Cuts the surface into two surfaces at the parameter `u` + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// + /// let knot_vec0 = KnotVec::uniform_knot(2, 2); + /// let knot_vec1 = KnotVec::uniform_knot(2, 2); + /// let ctrl_pts0 = vec![ + /// Vector2::new(0.0, 0.0), Vector2::new(0.5, 0.0), Vector2::new(2.0, 0.0), Vector2::new(2.5, 0.0), + /// ]; + /// let ctrl_pts1 = vec![ + /// Vector2::new(0.0, 1.0), Vector2::new(0.5, 1.0), Vector2::new(2.0, 1.0), Vector2::new(2.5, 1.0), + /// ]; + /// let ctrl_pts2 = vec![ + /// Vector2::new(0.0, 1.5), Vector2::new(0.5, 1.5), Vector2::new(2.0, 1.5), Vector2::new(2.5, 1.5), + /// ]; + /// let ctrl_pts3 = vec![ + /// Vector2::new(0.0, 2.5), Vector2::new(0.5, 2.5), Vector2::new(2.0, 2.5), Vector2::new(2.5, 2.5), + /// ]; + /// let ctrl_pts = vec![ctrl_pts0, ctrl_pts1, ctrl_pts2, ctrl_pts3]; + /// let bspsurface = BSplineSurface::new((knot_vec0, knot_vec1), ctrl_pts); + /// + /// let mut part0 = bspsurface.clone(); + /// let part1 = part0.ucut(0.68); + /// const N: usize = 100; + /// for i in 0..=N { + /// for j in 0..=N { + /// let u = 0.68 * (i as f64) / (N as f64); + /// let v = 1.0 * (j as f64) / (N as f64); + /// assert_near2!(bspsurface.subs(u, v), part0.subs(u, v)); + /// } + /// } + /// for i in 0..=N { + /// for j in 0..=N { + /// let u = 0.68 + 0.32 * (i as f64) / (N as f64); + /// let v = 1.0 * (j as f64) / (N as f64); + /// assert_near2!(bspsurface.subs(u, v), part1.subs(u, v)); + /// } + /// } + /// ``` + pub fn ucut(&mut self, mut u: f64) -> BSplineSurface

{ + let degree = self.udegree(); + + let idx = match self.uknot_vec().floor(u) { + Some(idx) => idx, + None => { + let bspline = self.clone(); + let uknot_vec = KnotVec::from(vec![u, self.vknot_vec()[0]]); + let vknot_vec = self.vknot_vec().clone(); + let ctrl_pts = vec![vec![P::origin(); vknot_vec.len()]]; + *self = BSplineSurface::new((uknot_vec, vknot_vec), ctrl_pts); + return bspline; + } + }; + let s = if u.near(&self.uknot_vec()[idx]) { + u = self.uknot_vec()[idx]; + self.uknot_vec().multiplicity(idx) + } else { + 0 + }; + + for _ in s..=degree { + self.add_uknot(u); + } + + let vknot_vec = self.vknot_vec().clone(); + let k = self.uknot_vec().floor(u).unwrap(); + let m = self.uknot_vec().len(); + let n = self.control_points.len(); + let knot_vec0 = self.uknot_vec().sub_vec(0..=k); + let knot_vec1 = self.uknot_vec().sub_vec((k - degree)..m); + let control_points0 = Vec::from(&self.control_points[0..(k - degree)]); + let control_points1 = Vec::from(&self.control_points[(k - degree)..n]); + *self = BSplineSurface::new((knot_vec0, vknot_vec.clone()), control_points0); + BSplineSurface::new((knot_vec1, vknot_vec), control_points1) + } + /// Cuts the curve to two curves at the parameter `t` + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// + /// let knot_vec0 = KnotVec::uniform_knot(2, 2); + /// let knot_vec1 = KnotVec::uniform_knot(2, 2); + /// let ctrl_pts0 = vec![ + /// Vector2::new(0.0, 0.0), Vector2::new(0.5, 0.0), Vector2::new(2.0, 0.0), Vector2::new(2.5, 0.0), + /// ]; + /// let ctrl_pts1 = vec![ + /// Vector2::new(0.0, 1.0), Vector2::new(0.5, 1.0), Vector2::new(2.0, 1.0), Vector2::new(2.5, 1.0), + /// ]; + /// let ctrl_pts2 = vec![ + /// Vector2::new(0.0, 1.5), Vector2::new(0.5, 1.5), Vector2::new(2.0, 1.5), Vector2::new(2.5, 1.5), + /// ]; + /// let ctrl_pts3 = vec![ + /// Vector2::new(0.0, 2.5), Vector2::new(0.5, 2.5), Vector2::new(2.0, 2.5), Vector2::new(2.5, 2.5), + /// ]; + /// let ctrl_pts = vec![ctrl_pts0, ctrl_pts1, ctrl_pts2, ctrl_pts3]; + /// let bspsurface = BSplineSurface::new((knot_vec0, knot_vec1), ctrl_pts); + /// + /// let mut part0 = bspsurface.clone(); + /// let part1 = part0.vcut(0.68); + /// const N: usize = 100; + /// for i in 0..=N { + /// for j in 0..=N { + /// let u = 1.0 * (i as f64) / (N as f64); + /// let v = 0.68 * (j as f64) / (N as f64); + /// assert_near2!(bspsurface.subs(u, v), part0.subs(u, v)); + /// } + /// } + /// for i in 0..=N { + /// for j in 0..=N { + /// let u = 1.0 * (i as f64) / (N as f64); + /// let v = 0.68 + 0.32 * (j as f64) / (N as f64); + /// assert_near2!(bspsurface.subs(u, v), part1.subs(u, v)); + /// } + /// } + /// ``` + pub fn vcut(&mut self, v: f64) -> BSplineSurface

{ + self.swap_axes(); + let mut res = self.ucut(v); + self.swap_axes(); + res.swap_axes(); + res + } + + /// Creates a sectional curve with normalized knot vector from the parameter `p` to the parameter `q`. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// + /// // a parabola surface: x = 2u - 1, y = 2v - 1, z = x^2 + y^z + /// let knot_vecs = (KnotVec::bezier_knot(2), KnotVec::bezier_knot(2)); + /// let ctrl_pts = vec![ + /// vec![Vector3::new(-1.0, -1.0, 2.0), Vector3::new(-1.0, 0.0, 0.0), Vector3::new(-1.0, 1.0, 2.0)], + /// vec![Vector3::new(0.0, -1.0, 0.0), Vector3::new(0.0, 0.0, -2.0), Vector3::new(0.0, 1.0, 0.0)], + /// vec![Vector3::new(1.0, -1.0, 2.0), Vector3::new(1.0, 0.0, 0.0), Vector3::new(1.0, 1.0, 2.0)], + /// ]; + /// let mut bspsurface = BSplineSurface::new(knot_vecs, ctrl_pts); + /// + /// // add some knots for the test! + /// bspsurface.add_uknot(0.26); + /// # bspsurface.add_uknot(0.64); + /// bspsurface.add_vknot(0.23); + /// # bspsurface.add_vknot(0.82); + /// + /// let bnd_box = BoundingBox::from_iter(&[Vector2::new(0.2, 0.3), Vector2::new(0.8, 0.6)]); + /// let curve = bspsurface.sectional_curve(bnd_box); + /// const N: usize = 100; + /// assert_near2!(curve.subs(0.0), bspsurface.subs(0.2, 0.3)); + /// assert_near2!(curve.subs(1.0), bspsurface.subs(0.8, 0.6)); + /// for i in 0..=N { + /// let t = i as f64 / N as f64; + /// let pt = curve.subs(t); + /// assert_near2!(pt[1], pt[0] * 0.5 - 0.1); + /// assert_near2!(pt[2], pt[0] * pt[0] + pt[1] * pt[1]); + /// } + /// ``` + pub fn sectional_curve(&self, bnd_box: BoundingBox) -> BSplineCurve

{ + let p = bnd_box.min(); + let q = bnd_box.max(); + let mut bspsurface = self.clone(); + if !p[0].near(&bspsurface.uknot(0)) { + bspsurface = bspsurface.ucut(p[0]); + } + if !q[0].near(&bspsurface.uknot(bspsurface.uknot_vec().len() - 1)) { + bspsurface.ucut(q[0]); + } + if !p[0].near(&bspsurface.vknot(0)) { + bspsurface = bspsurface.vcut(p[1]); + } + if !q[0].near(&bspsurface.vknot(bspsurface.vknot_vec().len() - 1)) { + bspsurface.vcut(q[1]); + } + bspsurface.syncro_uvdegrees(); + bspsurface.syncro_uvknots(); + let degree = bspsurface.udegree(); + let comb = combinatorial(degree); + let comb2 = combinatorial(degree * 2); + let (knots, _) = bspsurface.uknot_vec().to_single_multi(); + let mut cc = CurveCollector::Singleton; + for p in 1..knots.len() { + let mut backup = None; + if p + 1 != knots.len() { + backup = Some(bspsurface.ucut(knots[p])); + bspsurface.vcut(knots[p]); + } + let mut knot_vec = KnotVec::bezier_knot(degree * 2); + knot_vec.translate(p as f64 - 1.0); + let ctrl_pts: Vec<_> = (0..=degree * 2) + .map(|k| { + (0..=k).fold(P::origin(), |sum, i| { + if i <= degree && k - i <= degree { + let coef = (comb[i] * comb[k - i]) as f64 / comb2[k] as f64; + sum + bspsurface.control_points[i][k - i].to_vec() * coef + } else { + sum + } + }) + }) + .collect(); + cc.concat(&BSplineCurve::new(knot_vec, ctrl_pts)); + if p + 1 != knots.len() { + bspsurface = backup.unwrap().vcut(knots[p]); + } + } + let mut curve: BSplineCurve

= cc.unwrap(); + curve.knot_normalize(); + curve + } + + /// Creates a surface with normailized knot vectors connecting two curves. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vec0 = KnotVec::bezier_knot(2); + /// let ctrl_pts0 = vec![Vector2::new(0.0, 0.0), Vector2::new(0.5, -1.0), Vector2::new(1.0, 0.0)]; + /// let bspcurve0 = BSplineCurve::new(knot_vec0, ctrl_pts0); + /// + /// let knot_vec1 = KnotVec::bezier_knot(2); + /// let ctrl_pts1 = vec![Vector2::new(0.0, 2.0), Vector2::new(0.5, 1.0), Vector2::new(1.0, 2.0)]; + /// let bspcurve1 = BSplineCurve::new(knot_vec1, ctrl_pts1); + /// + /// let homotopy_surface = BSplineSurface::homotopy(bspcurve0, bspcurve1); + /// assert_eq!( + /// homotopy_surface.control_points(), + /// &vec![ + /// vec![Vector2::new(0.0, 0.0), Vector2::new(0.0, 2.0)], + /// vec![Vector2::new(0.5, -1.0), Vector2::new(0.5, 1.0)], + /// vec![Vector2::new(1.0, 0.0), Vector2::new(1.0, 2.0)], + /// ], + /// ); + /// ``` + pub fn homotopy( + mut bspcurve0: BSplineCurve

, + mut bspcurve1: BSplineCurve

, + ) -> BSplineSurface

{ + bspcurve0.syncro_degree(&mut bspcurve1); + + //bspcurve0.optimize(); + //bspcurve1.optimize(); + + bspcurve0.syncro_knots(&mut bspcurve1); + + let uknot_vec = bspcurve0.knot_vec().clone(); + let vknot_vec = KnotVec::from(vec![0.0, 0.0, 1.0, 1.0]); + let mut control_points = Vec::new(); + for i in 0..bspcurve0.control_points().len() { + control_points.push(Vec::new()); + control_points[i].push(*bspcurve0.control_point(i)); + control_points[i].push(*bspcurve1.control_point(i)); + } + BSplineSurface::new_unchecked((uknot_vec, vknot_vec), control_points) + } + + /// Creates a surface by its boundary. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let curve0 = BSplineCurve::new( + /// KnotVec::bezier_knot(1), + /// vec![Vector2::new(0.0, 0.0), Vector2::new(1.0, 0.0)], + /// ); + /// let curve1 = BSplineCurve::new( + /// KnotVec::bezier_knot(2), + /// vec![Vector2::new(1.0, 0.0), Vector2::new(2.0, 0.5), Vector2::new(1.0, 1.0)], + /// ); + /// let curve2 = BSplineCurve::new( + /// KnotVec::bezier_knot(1), + /// vec![Vector2::new(1.0, 1.0), Vector2::new(0.0, 1.0)], + /// ); + /// let curve3 = BSplineCurve::new( + /// KnotVec::bezier_knot(2), + /// vec![Vector2::new(0.0, 1.0), Vector2::new(-1.0, 0.5), Vector2::new(0.0, 0.0)], + /// ); + /// let surface = BSplineSurface::by_boundary(curve0, curve1, curve2, curve3); + /// assert_eq!( + /// surface.control_points(), + /// &vec![ + /// vec![Vector2::new(0.0, 0.0), Vector2::new(-1.0, 0.5), Vector2::new(0.0, 1.0)], + /// vec![Vector2::new(1.0, 0.0), Vector2::new(2.0, 0.5), Vector2::new(1.0, 1.0)], + /// ], + /// ); + /// ``` + /// # Remarks + /// If the end points of curves are not connected, `curve1` and `curve3` take precedence. i.e. + /// `curve1` and `curve3` are contained in the boundary of the surface and `curve0` and + /// `curve2` are not contained. + /// ``` + /// use truck_geometry::prelude::*; + /// let curve0 = BSplineCurve::new( + /// KnotVec::bezier_knot(1), + /// vec![Vector2::new(0.0, 0.0), Vector2::new(1.0, 0.0)], + /// ); + /// let curve1 = BSplineCurve::new( + /// KnotVec::bezier_knot(2), + /// vec![Vector2::new(2.0, 0.0), Vector2::new(3.0, 0.5), Vector2::new(2.0, 1.0)], + /// ); + /// let curve2 = BSplineCurve::new( + /// KnotVec::bezier_knot(1), + /// vec![Vector2::new(1.0, 1.0), Vector2::new(0.0, 1.0)], + /// ); + /// let curve3 = BSplineCurve::new( + /// KnotVec::bezier_knot(2), + /// vec![Vector2::new(-1.0, 1.0), Vector2::new(-2.0, 0.5), Vector2::new(-1.0, 0.0)], + /// ); + /// let surface = BSplineSurface::by_boundary( + /// curve0.clone(), + /// curve1.clone(), + /// curve2.clone(), + /// curve3.clone() + /// ); + /// assert_ne!(surface.subs(0.0, 0.0), curve0.subs(0.0)); + /// assert_eq!(surface.subs(0.0, 0.0), curve3.subs(1.0)); + /// ``` + pub fn by_boundary( + mut curve0: BSplineCurve

, + mut curve1: BSplineCurve

, + mut curve2: BSplineCurve

, + mut curve3: BSplineCurve

, + ) -> BSplineSurface

{ + curve2.invert(); + curve3.invert(); + curve0.syncro_degree(&mut curve2); + curve0.optimize(); + curve2.optimize(); + curve0.syncro_knots(&mut curve2); + curve1.syncro_degree(&mut curve3); + curve1.optimize(); + curve3.optimize(); + curve1.syncro_knots(&mut curve3); + + let knot_vecs = (curve0.knot_vec().clone(), curve3.knot_vec().clone()); + let mut control_points = vec![curve3.control_points().clone()]; + let n = curve0.control_points().len(); + let m = curve3.control_points().len(); + for i in 1..(n - 1) { + let u = (i as f64) / (n as f64); + let pt0 = curve2.control_points[i] + + (curve0.control_points[i] - curve2.control_points[i]) * u; + let mut new_row = vec![*curve0.control_point(i)]; + for j in 1..(m - 1) { + let v = (j as f64) / (m as f64); + let pt1 = curve1.control_points[j] + + (curve3.control_points[j] - curve1.control_points[j]) * v; + new_row.push(pt0 + (pt1 - pt0) / 2.0); + } + new_row.push(*curve2.control_point(i)); + control_points.push(new_row); + } + control_points.push(curve1.control_points().clone()); + BSplineSurface::new(knot_vecs, control_points) + } + + /// Normalizes the knot vectors + #[inline(always)] + pub fn knot_normalize(&mut self) -> &mut Self { + self.knot_vecs.0.normalize(); + self.knot_vecs.1.normalize(); + self + } + + /// Translates the knot vectors. + #[inline(always)] + pub fn knot_translate(&mut self, x: f64, y: f64) -> &mut Self { + self.knot_vecs.0.translate(x); + self.knot_vecs.1.translate(y); + self + } + + /// Removes knots in order from the back + pub fn optimize(&mut self) -> &mut Self { + loop { + let (n0, n1) = (self.knot_vecs.0.len(), self.knot_vecs.1.len()); + let mut flag = true; + for i in 1..=n0 { + flag = flag && self.try_remove_uknot(n0 - i).is_err(); + } + for j in 1..=n1 { + flag = flag && self.try_remove_vknot(n1 - j).is_err(); + } + if flag { + break; + } + } + self + } + + /// Gets the boundary by four splitted curves. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vecs = (KnotVec::bezier_knot(3), KnotVec::bezier_knot(2)); + /// let ctrl_pts = vec![ + /// vec![Vector2::new(0.0, 0.0), Vector2::new(0.5, -1.0), Vector2::new(1.0, 0.0)], + /// vec![Vector2::new(0.0, 1.0), Vector2::new(0.5, 1.0), Vector2::new(1.0, 1.0)], + /// vec![Vector2::new(0.0, 2.0), Vector2::new(0.5, 2.0), Vector2::new(1.0, 2.0)], + /// vec![Vector2::new(0.0, 3.0), Vector2::new(0.5, 3.5), Vector2::new(1.0, 3.0)], + /// ]; + /// let bspsurface = BSplineSurface::new(knot_vecs, ctrl_pts); + /// let curves = bspsurface.splitted_boundary(); + /// assert_eq!( + /// curves[0].control_points(), + /// &vec![Vector2::new(0.0, 0.0), Vector2::new(0.0, 1.0), Vector2::new(0.0, 2.0), Vector2::new(0.0, 3.0)], + /// ); + /// assert_eq!( + /// curves[1].control_points(), + /// &vec![Vector2::new(0.0, 3.0), Vector2::new(0.5, 3.5), Vector2::new(1.0, 3.0)], + /// ); + /// assert_eq!( + /// curves[2].control_points(), + /// &vec![Vector2::new(1.0, 3.0), Vector2::new(1.0, 2.0), Vector2::new(1.0, 1.0), Vector2::new(1.0, 0.0)], + /// ); + /// assert_eq!( + /// curves[3].control_points(), + /// &vec![Vector2::new(1.0, 0.0), Vector2::new(0.5, -1.0), Vector2::new(0.0, 0.0)], + /// ); + /// ``` + pub fn splitted_boundary(&self) -> [BSplineCurve

; 4] { + let (uknot_vec, vknot_vec) = self.knot_vecs.clone(); + let control_points0 = self.control_points.iter().map(|x| x[0]).collect(); + let control_points1 = self.control_points.last().unwrap().clone(); + let control_points2 = self + .control_points + .iter() + .map(|x| *x.last().unwrap()) + .collect(); + let control_points3 = self.control_points[0].clone(); + let curve0 = BSplineCurve::new_unchecked(uknot_vec.clone(), control_points0); + let curve1 = BSplineCurve::new_unchecked(vknot_vec.clone(), control_points1); + let mut curve2 = BSplineCurve::new_unchecked(uknot_vec, control_points2); + curve2.invert(); + let mut curve3 = BSplineCurve::new_unchecked(vknot_vec, control_points3); + curve3.invert(); + [curve0, curve1, curve2, curve3] + } + + /// Extracts the boundary of surface + pub fn boundary(&self) -> BSplineCurve

{ + let (uknot_vec, vknot_vec) = self.knot_vecs.clone(); + let (range0, range1) = (uknot_vec.range_length(), vknot_vec.range_length()); + let [bspline0, mut bspline1, mut bspline2, mut bspline3] = self.splitted_boundary(); + bspline0 + .concat(bspline1.knot_translate(range0)) + .concat(bspline2.invert().knot_translate(range0 + range1)) + .concat(bspline3.invert().knot_translate(range0 * 2.0 + range1)) + } + /// Determines whether `self` and `other` is near as the B-spline surfaces or not. + /// + /// Divides each knot domain into the number of degree equal parts, + /// and check `|self(u, v) - other(u, v)| < TOLERANCE` for each end points `(u, v)`. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vecs = (KnotVec::bezier_knot(3), KnotVec::bezier_knot(2)); + /// let ctrl_pts = vec![ + /// vec![Vector2::new(0.0, 0.0), Vector2::new(0.5, -1.0), Vector2::new(1.0, 0.0)], + /// vec![Vector2::new(0.0, 1.0), Vector2::new(0.5, 1.0), Vector2::new(1.0, 1.0)], + /// vec![Vector2::new(0.0, 2.0), Vector2::new(0.5, 2.0), Vector2::new(1.0, 2.0)], + /// vec![Vector2::new(0.0, 3.0), Vector2::new(0.5, 3.5), Vector2::new(1.0, 3.0)], + /// ]; + /// let bspsurface0 = BSplineSurface::new(knot_vecs, ctrl_pts); + /// let mut bspsurface1 = bspsurface0.clone(); + /// assert!(bspsurface0.near_as_surface(&bspsurface1)); + /// + /// *bspsurface1.control_point_mut(1, 1) = Vector2::new(0.4, 1.0); + /// assert!(!bspsurface0.near_as_surface(&bspsurface1)); + /// ``` + #[inline(always)] + pub fn near_as_surface(&self, other: &BSplineSurface

) -> bool { + self.sub_near_as_surface(other, 1, |x, y| x.near(y)) + } + /// Determines whether `self` and `other` is near in square order as the B-spline surfaces or not. + /// + /// Divides each knot domain into the number of degree equal parts, + /// and check `|self(u, v) - other(u, v)| < TOLERANCE` for each end points `(u, v)`. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let eps = TOLERANCE; + /// let knot_vecs = (KnotVec::bezier_knot(3), KnotVec::bezier_knot(2)); + /// let ctrl_pts = vec![ + /// vec![Vector2::new(0.0, 0.0), Vector2::new(0.5, -1.0), Vector2::new(1.0, 0.0)], + /// vec![Vector2::new(0.0, 1.0), Vector2::new(0.5, 1.0), Vector2::new(1.0, 1.0)], + /// vec![Vector2::new(0.0, 2.0), Vector2::new(0.5, 2.0), Vector2::new(1.0, 2.0)], + /// vec![Vector2::new(0.0, 3.0), Vector2::new(0.5, 3.5), Vector2::new(1.0, 3.0)], + /// ]; + /// let bspsurface0 = BSplineSurface::new(knot_vecs, ctrl_pts); + /// let mut bspsurface1 = bspsurface0.clone(); + /// assert!(bspsurface0.near_as_surface(&bspsurface1)); + /// + /// *bspsurface1.control_point_mut(1, 1) += Vector2::new(eps, eps / 2.0); + /// assert!(bspsurface0.near_as_surface(&bspsurface1)); + /// assert!(!bspsurface0.near2_as_surface(&bspsurface1)); + /// ``` + #[inline(always)] + pub fn near2_as_surface(&self, other: &BSplineSurface

) -> bool { + self.sub_near_as_surface(other, 1, |x, y| x.near2(y)) + } +} + +impl BSplineSurface { + /// Returns the bounding box including all control points. + #[inline(always)] + pub fn roughly_bounding_box(&self) -> BoundingBox { + self.control_points.iter().flatten().collect() + } +} + +impl> ParameterDivision2D for BSplineSurface

+where P: EuclideanSpace>::Diff> + + MetricSpace + + HashGen +{ + #[inline(always)] + fn parameter_division( + &self, + range: ((f64, f64), (f64, f64)), + tol: f64, + ) -> (Vec, Vec) { + algo::surface::parameter_division(self, range, tol) + } +} + +impl ParametricSurface3D for BSplineSurface {} + +impl BoundedSurface for BSplineSurface where BSplineSurface: ParametricSurface {} + +impl Invertible for BSplineSurface { + #[inline(always)] + fn invert(&mut self) { self.swap_axes(); } +} + +impl SearchParameter for BSplineSurface { + type Point = Point2; + fn search_parameter>( + &self, + point: Point2, + hint: H, + trials: usize, + ) -> Option<(f64, f64)> { + let hint = match hint.into() { + SPHint2D::Parameter(x, y) => (x, y), + SPHint2D::Range(range0, range1) => { + algo::surface::presearch(self, point, (range0, range1), PRESEARCH_DIVISION) + } + SPHint2D::None => { + algo::surface::presearch(self, point, self.range_tuple(), PRESEARCH_DIVISION) + } + }; + algo::surface::search_parameter2d(self, point, hint, trials) + } +} + +impl SearchParameter for BSplineSurface { + type Point = Point3; + fn search_parameter>( + &self, + point: Point3, + hint: H, + trials: usize, + ) -> Option<(f64, f64)> { + let hint = match hint.into() { + SPHint2D::Parameter(x, y) => (x, y), + SPHint2D::Range(range0, range1) => { + algo::surface::presearch(self, point, (range0, range1), PRESEARCH_DIVISION) + } + SPHint2D::None => { + algo::surface::presearch(self, point, self.range_tuple(), PRESEARCH_DIVISION) + } + }; + algo::surface::search_parameter3d(self, point, hint, trials) + } +} + +impl

SearchNearestParameter for BSplineSurface

+where + P: ControlPoint + + EuclideanSpace>::Diff> + + MetricSpace, +

>::Diff: InnerSpace + Tolerance, +{ + type Point = P; + fn search_nearest_parameter>( + &self, + point: P, + hint: H, + trials: usize, + ) -> Option<(f64, f64)> { + let hint = match hint.into() { + SPHint2D::Parameter(x, y) => (x, y), + SPHint2D::Range(range0, range1) => { + algo::surface::presearch(self, point, (range0, range1), PRESEARCH_DIVISION) + } + SPHint2D::None => { + algo::surface::presearch(self, point, self.range_tuple(), PRESEARCH_DIVISION) + } + }; + algo::surface::search_nearest_parameter(self, point, hint, trials) + } +} + +impl IncludeCurve> for BSplineSurface { + fn include(&self, curve: &BSplineCurve) -> bool { + let pt = curve.front(); + let mut hint = algo::surface::presearch(self, pt, self.range_tuple(), PRESEARCH_DIVISION); + hint = match algo::surface::search_parameter2d(self, pt, hint, INCLUDE_CURVE_TRIALS) { + Some(got) => got, + None => return false, + }; + let uknot_vec = self.uknot_vec(); + let vknot_vec = self.vknot_vec(); + let degree = curve.degree() * 6; + let (knots, _) = curve.knot_vec().to_single_multi(); + for i in 1..knots.len() { + for j in 1..=degree { + let p = j as f64 / degree as f64; + let t = knots[i - 1] * (1.0 - p) + knots[i] * p; + let pt = ParametricCurve::subs(curve, t); + hint = match algo::surface::search_parameter2d(self, pt, hint, INCLUDE_CURVE_TRIALS) + { + Some(got) => got, + None => return false, + }; + if !ParametricSurface::subs(self, hint.0, hint.1).near(&pt) + || hint.0 < uknot_vec[0] - TOLERANCE + || hint.0 - uknot_vec[0] > uknot_vec.range_length() + TOLERANCE + || hint.1 < vknot_vec[0] - TOLERANCE + || hint.1 - vknot_vec[0] > vknot_vec.range_length() + TOLERANCE + { + return false; + } + } + } + true + } +} + +impl IncludeCurve> for BSplineSurface { + fn include(&self, curve: &BSplineCurve) -> bool { + let pt = curve.front(); + let mut hint = algo::surface::presearch(self, pt, self.range_tuple(), PRESEARCH_DIVISION); + hint = match algo::surface::search_parameter3d(self, pt, hint, INCLUDE_CURVE_TRIALS) { + Some(got) => got, + None => return false, + }; + let uknot_vec = self.uknot_vec(); + let vknot_vec = self.vknot_vec(); + let degree = curve.degree() * 6; + let (knots, _) = curve.knot_vec().to_single_multi(); + for i in 1..knots.len() { + for j in 1..=degree { + let p = j as f64 / degree as f64; + let t = knots[i - 1] * (1.0 - p) + knots[i] * p; + let pt = ParametricCurve::subs(curve, t); + hint = match algo::surface::search_parameter3d(self, pt, hint, INCLUDE_CURVE_TRIALS) + { + Some(got) => got, + None => return false, + }; + if !ParametricSurface::subs(self, hint.0, hint.1).near(&pt) + || hint.0 < uknot_vec[0] - TOLERANCE + || hint.0 - uknot_vec[0] > uknot_vec.range_length() + TOLERANCE + || hint.1 < vknot_vec[0] - TOLERANCE + || hint.1 - vknot_vec[0] > vknot_vec.range_length() + TOLERANCE + { + return false; + } + } + } + true + } +} + +impl IncludeCurve> for BSplineSurface { + fn include(&self, curve: &NurbsCurve) -> bool { + let pt = curve.subs(curve.knot_vec()[0]); + let mut hint = algo::surface::presearch(self, pt, self.range_tuple(), PRESEARCH_DIVISION); + hint = match algo::surface::search_parameter3d(self, pt, hint, INCLUDE_CURVE_TRIALS) { + Some(got) => got, + None => return false, + }; + let uknot_vec = self.uknot_vec(); + let vknot_vec = self.vknot_vec(); + let degree = curve.degree() * 6; + let (knots, _) = curve.knot_vec().to_single_multi(); + for i in 1..knots.len() { + for j in 1..=degree { + let p = j as f64 / degree as f64; + let t = knots[i - 1] * (1.0 - p) + knots[i] * p; + let pt = curve.subs(t); + hint = match algo::surface::search_parameter3d(self, pt, hint, INCLUDE_CURVE_TRIALS) + { + Some(got) => got, + None => return false, + }; + if !ParametricSurface::subs(self, hint.0, hint.1).near(&pt) + || hint.0 < uknot_vec[0] - TOLERANCE + || hint.0 - uknot_vec[0] > uknot_vec.range_length() + TOLERANCE + || hint.1 < vknot_vec[0] - TOLERANCE + || hint.1 - vknot_vec[0] > vknot_vec.range_length() + TOLERANCE + { + return false; + } + } + } + true + } +} + +macro_rules! impl_mat_multi { + ($vector: ty, $matrix: ty) => { + impl Mul> for $matrix { + type Output = BSplineSurface<$vector>; + fn mul(self, mut spline: BSplineSurface<$vector>) -> Self::Output { + spline + .control_points + .iter_mut() + .flat_map(|vec| vec.iter_mut()) + .for_each(|vec| *vec = self * *vec); + spline + } + } + impl Mul<&BSplineSurface<$vector>> for $matrix { + type Output = BSplineSurface<$vector>; + fn mul(self, spline: &BSplineSurface<$vector>) -> Self::Output { self * spline.clone() } + } + }; +} + +macro_rules! impl_scalar_multi { + ($vector: ty, $scalar: ty) => { + impl_mat_multi!($vector, $scalar); + impl Mul<$scalar> for &BSplineSurface<$vector> { + type Output = BSplineSurface<$vector>; + fn mul(self, scalar: $scalar) -> Self::Output { scalar * self } + } + impl Mul<$scalar> for BSplineSurface<$vector> { + type Output = BSplineSurface<$vector>; + fn mul(self, scalar: $scalar) -> Self::Output { scalar * self } + } + }; +} + +impl_mat_multi!(Vector2, Matrix2); +impl_scalar_multi!(Vector2, f64); +impl_mat_multi!(Vector3, Matrix3); +impl_scalar_multi!(Vector3, f64); +impl_mat_multi!(Vector4, Matrix4); +impl_scalar_multi!(Vector4, f64); + +impl> Transformed for BSplineSurface

+where M: Transform

+{ + #[inline(always)] + fn transform_by(&mut self, trans: M) { + self.control_points + .iter_mut() + .flatten() + .for_each(|p| *p = trans.transform_point(*p)) + } +} + +impl<'de, P> Deserialize<'de> for BSplineSurface

+where P: Deserialize<'de> +{ + fn deserialize(deserializer: D) -> std::result::Result + where D: serde::Deserializer<'de> { + #[derive(Deserialize)] + struct BSplineSurface_

{ + knot_vecs: (KnotVec, KnotVec), + control_points: Vec>, + } + let BSplineSurface_ { + knot_vecs, + control_points, + } = BSplineSurface_::

::deserialize(deserializer)?; + Self::try_new(knot_vecs, control_points).map_err(serde::de::Error::custom) + } +} + +fn combinatorial(n: usize) -> Vec { + let mut res = vec![1]; + for i in 1..=n { + res.push(res[i - 1] * (n - i + 1) / i); + } + res +} + +#[test] +fn test_include_bspcurve2() { + let knot_vec = KnotVec::uniform_knot(2, 3); + let ctrl_pts = vec![ + vec![ + Point2::new(0.0, 0.0), + Point2::new(0.1, 0.0), + Point2::new(0.5, 0.0), + Point2::new(0.7, 0.0), + Point2::new(1.0, 0.0), + ], + vec![ + Point2::new(0.0, 0.1), + Point2::new(0.2, 0.2), + Point2::new(0.4, 0.3), + Point2::new(0.6, 0.2), + Point2::new(1.0, 0.3), + ], + vec![ + Point2::new(0.0, 0.5), + Point2::new(0.3, 0.6), + Point2::new(0.6, 0.4), + Point2::new(0.9, 0.6), + Point2::new(1.0, 0.5), + ], + vec![ + Point2::new(0.0, 0.7), + Point2::new(0.2, 0.8), + Point2::new(0.3, 0.6), + Point2::new(0.5, 0.9), + Point2::new(1.0, 0.7), + ], + vec![ + Point2::new(0.0, 1.0), + Point2::new(0.1, 1.0), + Point2::new(0.5, 1.0), + Point2::new(0.7, 1.0), + Point2::new(1.0, 1.0), + ], + ]; + let surface = BSplineSurface::new((knot_vec.clone(), knot_vec), ctrl_pts); + + let knot_vec0 = KnotVec::bezier_knot(2); + let ctrl_pts0 = vec![ + Point2::new(0.0, 0.0), + Point2::new(1.0, 1.0), + Point2::new(0.0, 1.0), + ]; + let curve0 = BSplineCurve::new(knot_vec0, ctrl_pts0); + assert!(surface.include(&curve0)); + + let knot_vec1 = KnotVec::bezier_knot(2); + let ctrl_pts1 = vec![ + Point2::new(0.0, 0.0), + Point2::new(2.5, 1.0), + Point2::new(0.0, 1.0), + ]; + let curve1 = BSplineCurve::new(knot_vec1, ctrl_pts1); + assert!(!surface.include(&curve1)); +} + +#[test] +fn test_include_bspcurve3() { + let knot_vec = KnotVec::uniform_knot(2, 3); + let ctrl_pts = vec![ + vec![ + Point3::new(0.0, 0.0, 0.0), + Point3::new(0.1, 0.0, 0.5), + Point3::new(0.5, 0.0, 0.3), + Point3::new(1.0, 0.0, 1.0), + ], + vec![ + Point3::new(0.0, 0.1, 0.1), + Point3::new(0.2, 0.2, 0.1), + Point3::new(0.4, 0.3, 0.4), + Point3::new(1.0, 0.3, 0.7), + ], + vec![ + Point3::new(0.0, 0.5, 0.4), + Point3::new(0.3, 0.6, 0.5), + Point3::new(0.6, 0.4, 1.0), + Point3::new(1.0, 0.5, 0.0), + ], + vec![ + Point3::new(0.0, 1.0, 1.0), + Point3::new(0.1, 1.0, 1.0), + Point3::new(0.5, 1.0, 0.5), + Point3::new(1.0, 1.0, 0.3), + ], + ]; + let surface = BSplineSurface::new((knot_vec.clone(), knot_vec), ctrl_pts); + let bnd_box = BoundingBox::from_iter(&[Vector2::new(0.2, 0.3), Vector2::new(0.8, 0.6)]); + let mut curve = surface.sectional_curve(bnd_box); + assert!(surface.include(&curve)); + *curve.control_point_mut(2) += Vector3::new(0.0, 0.0, 0.001); + assert!(!surface.include(&curve)); +} diff --git a/vendor/truck-geometry/src/nurbs/knot_vec.rs b/vendor/truck-geometry/src/nurbs/knot_vec.rs new file mode 100644 index 000000000..c4a448b97 --- /dev/null +++ b/vendor/truck-geometry/src/nurbs/knot_vec.rs @@ -0,0 +1,596 @@ +use super::*; +use crate::errors::Error; +use std::slice::SliceIndex; +use std::vec::Vec; + +impl KnotVec { + /// empty constructor + pub const fn new() -> KnotVec { KnotVec(Vec::new()) } + + /// Returns the length of range. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vec = KnotVec::from(vec![0.0, 6.0]); + /// assert_eq!(knot_vec.range_length(), 6.0); + /// ``` + #[inline(always)] + pub fn range_length(&self) -> f64 { + match self.is_empty() { + true => 0.0, + false => self[self.len() - 1] - self[0], + } + } + + /// Returns whether two knot vectors have the same range. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vec0 = KnotVec::new(); // empty knot vector + /// let knot_vec1 = KnotVec::from(vec![0.0, 0.0, 1.0, 1.0]); + /// let knot_vec2 = KnotVec::from(vec![0.0, 0.5, 1.0]); + /// let knot_vec3 = KnotVec::from(vec![0.0, 0.0, 2.0, 2.0]); + /// assert!(knot_vec0.same_range(&KnotVec::new())); // both empty knot vector + /// assert!(!knot_vec0.same_range(&knot_vec1)); + /// assert!(knot_vec1.same_range(&knot_vec2)); // the range of both knot vector is [0, 1]. + /// assert!(!knot_vec1.same_range(&knot_vec3)); + /// ``` + #[inline(always)] + pub fn same_range(&self, other: &KnotVec) -> bool { + match (self.is_empty(), other.is_empty()) { + (false, false) => { + self[0].near(&other[0]) && self.range_length().near(&other.range_length()) + } + (true, true) => true, + _ => false, + } + } + + /// Removes one item. + #[inline(always)] + pub fn remove(&mut self, idx: usize) -> f64 { self.0.remove(idx) } + + /// Returns the maximum index `i` of `self[i] <= x` + /// Return `None` if `x < self[0] or self.len() == 0`. + /// # Examples + /// ``` + /// use truck_geometry::prelude::KnotVec; + /// let mut knot_vec = KnotVec::from(vec![0.0, 0.0, 1.0, 2.0, 3.0, 3.0]); + /// let idx = knot_vec.floor(1.5).unwrap(); + /// assert_eq!(idx, 2); + /// ``` + #[inline(always)] + pub fn floor(&self, x: f64) -> Option { self.iter().rposition(|t| *t <= x) } + + /// Returns the multiplicity of the `i`th knot + /// # Examples + /// ``` + /// use truck_geometry::prelude::KnotVec; + /// let knot_vec = KnotVec::from(vec![0.0, 0.0, 1.0, 2.0, 2.0, 2.0, 3.0, 3.0]); + /// assert_eq!(knot_vec.multiplicity(5), 3); + /// ``` + #[inline(always)] + pub fn multiplicity(&self, i: usize) -> usize { + self.iter().filter(|u| self[i].near(u)).count() + } + + /// Adds a knot and return the index of the added knot. + /// # Examples + /// ``` + /// use truck_geometry::prelude::KnotVec; + /// let mut knot_vec = KnotVec::from(vec![0.0, 0.0, 1.0, 2.0, 3.0, 3.0]); + /// let idx0 = knot_vec.add_knot(1.5); + /// assert_eq!(idx0, 3); + /// let idx1 = knot_vec.add_knot(-1.0); + /// assert_eq!(idx1, 0); + /// let ansvec = KnotVec::from(vec![-1.0, 0.0, 0.0, 1.0, 1.5, 2.0, 3.0, 3.0]); + /// assert_eq!(knot_vec, ansvec); + /// ``` + #[inline(always)] + pub fn add_knot(&mut self, knot: f64) -> usize { + match self.floor(knot) { + Some(idx) => { + self.0.insert(idx + 1, knot); + idx + 1 + } + None => { + self.0.insert(0, knot); + 0 + } + } + } + + /// Calculates B-spline basis functions at `t` with degree `degree`. + /// # Panics + /// If the length of `self` is not more than `degree`, panic occurs. + /// # Remarks + /// In this package, the B-spline basis function is based on the characteristic function of + /// the right-open intervals [s, t). So, the value corresponding to the end point t = t_n is always 0.0. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// const N : usize = 100; // sample size in tests + /// + /// // B-spline basis functions is a partition of unity in (t_k, t_{n - k}). + /// let vec = vec![0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]; + /// let knot_vec = KnotVec::from(vec); + /// let degree = 2; + /// for i in 0..N { + /// let t = 2.0 + 4.0 / (N as f64) * (i as f64); + /// let res = knot_vec.bspline_basis_functions(degree, t); + /// let sum = res.iter().fold(0.0, |sum, a| sum + a); + /// assert_near2!(sum, 1.0); + /// } + /// ``` + /// ``` + /// use truck_geometry::prelude::*; + /// const N : usize = 100; // sample size in tests + /// + /// // In some case, B-spline basis functions coincide with Bernstein polynomials. + /// let vec = vec![0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0]; + /// let knot_vec = KnotVec::from(vec); + /// let degree = 3; + /// for i in 0..=N { + /// let t = 1.0 / (N as f64) * (i as f64); + /// let res = knot_vec.bspline_basis_functions(degree, t); + /// let ans = [ + /// 1.0 * (1.0 - t) * (1.0 - t) * (1.0 - t), + /// 3.0 * t * (1.0 - t) * (1.0 - t), + /// 3.0 * t * t * (1.0 - t), + /// 1.0 * t * t * t, + /// ]; + /// for i in 0..4 { assert_near2!(res[i], ans[i]); } + /// } + /// ``` + pub fn bspline_basis_functions(&self, degree: usize, t: f64) -> Vec { + match self.try_bspline_basis_functions(degree, t) { + Ok(got) => got, + Err(error) => panic!("{}", error), + } + } + + /// Calculates B-spline basis functions at `t` with degree `degree`. + /// # Failures + /// - If the range of the knot vector is zero, returns [`Error::ZeroRange`]. + /// - If the length of `self` is not more than `degree`, returns [`Error::TooLargeDegree`]. + /// # Remarks + /// In this package, the B-spline basis function is based on the characteristic function of + /// the right-open intervals [s, t). So, the value corresponding to the end point t = t_n is always 0.0. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// const N : usize = 100; // sample size in tests + /// + /// // B-spline basis functions is a partition of unity in (t_k, t_{n - k}). + /// let vec = vec![0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]; + /// let knot_vec = KnotVec::from(vec); + /// let degree = 2; + /// for i in 0..N { + /// let t = 2.0 + 4.0 / (N as f64) * (i as f64); + /// let res = knot_vec.try_bspline_basis_functions(degree, t).unwrap(); + /// let sum = res.iter().fold(0.0, |sum, a| sum + a); + /// assert_near2!(sum, 1.0); + /// } + /// ``` + /// ``` + /// use truck_geometry::prelude::*; + /// const N : usize = 100; // sample size in tests + /// + /// // In some case, B-spline basis functions coincide with Bernstein polynomials. + /// let vec = vec![0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0]; + /// let knot_vec = KnotVec::from(vec); + /// let degree = 3; + /// for i in 0..=N { + /// let t = i as f64 / N as f64; + /// let res = knot_vec.try_bspline_basis_functions(degree, t).unwrap(); + /// let ans = [ + /// 1.0 * (1.0 - t) * (1.0 - t) * (1.0 - t), + /// 3.0 * t * (1.0 - t) * (1.0 - t), + /// 3.0 * t * t * (1.0 - t), + /// 1.0 * t * t * t, + /// ]; + /// for i in 0..4 { assert_near2!(res[i], ans[i]); } + /// } + /// ``` + pub fn try_bspline_basis_functions(&self, degree: usize, t: f64) -> Result> { + let n = self.len() - 1; + if self[0].near(&self[n]) { + return Err(Error::ZeroRange); + } else if n < degree { + return Err(Error::TooLargeDegree(n + 1, degree)); + } + + let idx = { + let idx = self + .floor(t) + .unwrap_or_else(|| self.floor(self[0]).unwrap()); + if idx == n { + n - self.multiplicity(n) + } else { + idx + } + }; + let mut res = vec![0.0; n]; + res[idx] = 1.0; + + for k in 1..=degree { + let base = if idx < k { 0 } else { idx - k }; + let delta = self[base + k] - self[base]; + let max = if idx + k < n { idx } else { n - k - 1 }; + let mut a = inv_or_zero(delta) * (t - self[base]); + for i in base..=max { + let delta = self[i + k + 1] - self[i + 1]; + let b = inv_or_zero(delta) * (self[i + k + 1] - t); + res[i] = a * res[i] + b * res[i + 1]; + a = 1.0 - b; + } + } + + res.truncate(n - degree); + Ok(res) + } + + #[doc(hidden)] + pub fn maximum_points(&self, degree: usize) -> Vec { + let n = self.len(); + let m = n - degree - 1; + let range = self.range_length(); + const N: i32 = 100; + + let mut res = vec![0.0; m]; + let mut max = vec![0.0; m]; + for i in 1..N { + let t = self[0] + range * (i as f64) / (N as f64); + let vals = self.try_bspline_basis_functions(degree, t).unwrap(); + for j in 0..m { + if max[j] < vals[j] { + max[j] = vals[j]; + res[j] = t; + } + } + } + + res + } + + /// Transforms the knot vector + /// # Examples + /// ``` + /// use std::vec::Vec; + /// use truck_geometry::prelude::KnotVec; + /// let mut knot_vec = KnotVec::from(vec![1.0, 1.0, 2.0, 3.0, 4.0, 5.0, 5.0]); + /// knot_vec.transform(2.0, 3.0); + /// let res : Vec = knot_vec.into(); + /// assert_eq!(res, vec![5.0, 5.0, 7.0, 9.0, 11.0, 13.0, 13.0]); + /// ``` + /// # Panics + /// Panic occurs if `scalar` is not positive. + pub fn transform(&mut self, scalar: f64, r#move: f64) -> &mut Self { + assert!(scalar > 0.0, "The scalar {scalar} is not positive."); + self.0 + .iter_mut() + .for_each(move |vec| *vec = *vec * scalar + r#move); + self + } + + /// Normalizes the knot vector i.e. makes the first value 0 and the last value 1. + /// # Failures + /// Returns [`Error::ZeroRange`] if the range of the knot vector is so small. + /// # Examples + /// ``` + /// use truck_geometry::prelude::KnotVec; + /// let mut knot_vec = KnotVec::from(vec![1.0, 1.0, 2.0, 3.0, 4.0, 5.0, 5.0]); + /// knot_vec.try_normalize().unwrap(); + /// let res : Vec = knot_vec.into(); + /// assert_eq!(res, vec![0.0, 0.0, 0.25, 0.5, 0.75, 1.0, 1.0]); + /// ``` + pub fn try_normalize(&mut self) -> Result<&mut Self> { + let range = self.range_length(); + if range.so_small() { + return Err(Error::ZeroRange); + } + Ok(self.transform(1.0 / range, -self[0] / range)) + } + + /// Normalizes the knot vector i.e. makes the first value 0 and the last value 1. + /// # Panics + /// Panic occurs if the range of the knot vector is so small. + /// # Examples + /// ``` + /// use truck_geometry::prelude::KnotVec; + /// let mut knot_vec = KnotVec::from(vec![1.0, 1.0, 2.0, 3.0, 4.0, 5.0, 5.0]); + /// knot_vec.normalize(); + /// let res : Vec = knot_vec.into(); + /// assert_eq!(res, vec![0.0, 0.0, 0.25, 0.5, 0.75, 1.0, 1.0]); + /// ``` + #[inline(always)] + pub fn normalize(&mut self) -> &mut Self { + self.try_normalize() + .unwrap_or_else(|error| panic!("{}", error)) + } + + /// Translates the knot vector + /// # Example + /// ``` + /// use std::vec::Vec; + /// use truck_geometry::prelude::KnotVec; + /// let mut knot_vec = KnotVec::from(vec![1.0, 1.0, 2.0, 3.0, 4.0, 5.0, 5.0]); + /// knot_vec.translate(3.0); + /// let res : Vec = knot_vec.into(); + /// assert_eq!(res, vec![4.0, 4.0, 5.0, 6.0, 7.0, 8.0, 8.0]); + /// ``` + pub fn translate(&mut self, x: f64) -> &mut Self { self.transform(1.0, x) } + + /// Inverts the knot vector + /// # Example + /// ``` + /// use std::vec::Vec; + /// use truck_geometry::prelude::KnotVec; + /// let mut knot_vec = KnotVec::from(vec![1.0, 1.0, 1.0, 3.0, 5.0, 6.0]); + /// knot_vec.invert(); + /// let res : Vec = knot_vec.into(); + /// assert_eq!(res, vec![1.0, 2.0, 4.0, 6.0, 6.0, 6.0]); + /// + /// ``` + pub fn invert(&mut self) -> &mut Self { + let n = self.len(); + if n == 0 { + return self; + } + let range = self[0] + self[n - 1]; + let clone = self.0.clone(); + for (knot1, knot0) in clone.iter().rev().zip(&mut self.0) { + *knot0 = range - knot1; + } + self + } + + /// Determines the knot vector is clamped for the given degree. + /// # Examples + /// ``` + /// use truck_geometry::prelude::KnotVec; + /// let knot_vec = KnotVec::from(vec![0.0, 0.0, 0.0, 0.25, 0.5, 0.75, 1.0, 1.0, 1.0]); + /// assert!(knot_vec.is_clamped(2)); + /// assert!(!knot_vec.is_clamped(3)); + /// ``` + #[inline(always)] + pub fn is_clamped(&self, degree: usize) -> bool { + self.multiplicity(0) > degree && self.multiplicity(self.len() - 1) > degree + } + + /// Concats two knot vectors. + /// # Examples + /// ``` + /// use truck_geometry::prelude::KnotVec; + /// let mut knot_vec0 = KnotVec::from(vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0]); + /// let knot_vec1 = KnotVec::from(vec![1.0, 1.0, 1.0, 2.0, 2.0, 2.0]); + /// knot_vec0.try_concat(&knot_vec1, 2).unwrap(); + /// assert_eq!(knot_vec0.as_slice(), &[0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0]); + /// ``` + /// # Failures + /// - If at least one of `self` or `other` is not clamped, returns [`Error::NotClampedKnotVector`] + /// - If the last knot of `self` and the first knot of `other` are different, returns [`Error::DifferentBackFront`]. + pub fn try_concat(&mut self, other: &KnotVec, degree: usize) -> Result<&mut Self> { + if !self.is_clamped(degree) || !other.is_clamped(degree) { + return Err(Error::NotClampedKnotVector); + } + let back = self.0.last().unwrap(); + let front = other.0.first().unwrap(); + if front < back || !front.near(back) { + return Err(Error::DifferentBackFront(*back, *front)); + } + + self.0.truncate(self.len() - degree - 1); + for knot in &other.0 { + self.0.push(*knot); + } + + Ok(self) + } + + /// Concats two knot vectors. + /// # Examples + /// ``` + /// use truck_geometry::prelude::KnotVec; + /// let mut knot_vec0 = KnotVec::from(vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0]); + /// let knot_vec1 = KnotVec::from(vec![1.0, 1.0, 1.0, 2.0, 2.0, 2.0]); + /// knot_vec0.concat(&knot_vec1, 2); + /// assert_eq!(knot_vec0.as_slice(), &[0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0]); + /// ``` + /// # Panics + /// Panic occurs if: + /// - at least one of `self` or `other` is not clamped. + /// - the last knot of `self` and the first knot of `other` are different. + #[inline(always)] + pub fn concat(&mut self, other: &KnotVec, degree: usize) -> &mut Self { + self.try_concat(other, degree) + .unwrap_or_else(|error| panic!("{}", error)) + } + + /// Returns trimmed vector by the specified range. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vec = KnotVec::from(vec![0.0, 1.0, 2.0, 3.0, 4.0, 5.0]); + /// let sub_vec = knot_vec.sub_vec(1..3); + /// assert_eq!(sub_vec, KnotVec::from(vec![1.0, 2.0])); + /// ``` + #[inline(always)] + pub fn sub_vec>(&self, range: I) -> KnotVec { + KnotVec(Vec::from(&self.0[range])) + } + + /// To single-multi description. i.e. decompose the unique vector of knots and the vector of + /// multiplicity of knots. + /// # Examples + /// ``` + /// use truck_geometry::prelude::KnotVec; + /// let knot_vec = KnotVec::from(vec![0.0, 0.0, 0.0, 1.0, 2.0, 2.0, 2.0, 2.0, 3.0, 3.0]); + /// let (knots, mults) = knot_vec.to_single_multi(); + /// assert_eq!(knots, vec![0.0, 1.0, 2.0, 3.0]); + /// assert_eq!(mults, vec![3, 1, 4, 2]); + /// ``` + pub fn to_single_multi(&self) -> (Vec, Vec) { + let mut knots = Vec::new(); + let mut mults = Vec::new(); + + let mut iter = self.as_slice().iter().peekable(); + let mut mult = 1; + while let Some(knot) = iter.next() { + if let Some(next) = iter.peek() { + if knot.near(next) { + mult += 1; + } else { + knots.push(*knot); + mults.push(mult); + mult = 1; + } + } else { + knots.push(*knot); + mults.push(mult); + } + } + (knots, mults) + } + + /// Constructs from single-multi description. + /// # Examples + /// ``` + /// use truck_geometry::prelude::KnotVec; + /// let knots = vec![0.0, 1.0, 2.0, 3.0]; + /// let mults = vec![3, 1, 4, 2]; + /// let knot_vec = KnotVec::from_single_multi(knots, mults).unwrap(); + /// assert_eq!(knot_vec, KnotVec::from(vec![0.0, 0.0, 0.0, 1.0, 2.0, 2.0, 2.0, 2.0, 3.0, 3.0])); + /// ``` + pub fn from_single_multi(knots: Vec, mults: Vec) -> Result { + for i in 1..knots.len() { + if knots[i - 1] > knots[i] { + return Err(Error::NotSortedVector); + } + } + + let mut vec = Vec::new(); + for i in 0..knots.len() { + for _ in 0..mults[i] { + vec.push(knots[i]); + } + } + Ok(KnotVec(vec)) + } + /// Constructs from `Vec`. do not sort, only check sorted. + pub fn try_from(vec: Vec) -> Result { + for i in 1..vec.len() { + if vec[i - 1] > vec[i] { + return Err(Error::NotSortedVector); + } + } + Ok(KnotVec(vec)) + } + + /// Constructs the knot vector for the bezier spline. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// assert_eq!( + /// *KnotVec::bezier_knot(3), + /// vec![0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0], + /// ); + /// ``` + pub fn bezier_knot(degree: usize) -> KnotVec { + let mut vec = vec![0.0; degree + 1]; + vec.extend(std::iter::repeat(1.0).take(degree + 1)); + KnotVec(vec) + } + + /// Constructs the uniform knot vector + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// assert_eq!( + /// *KnotVec::uniform_knot(2, 5), + /// vec![0.0, 0.0, 0.0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.0, 1.0], + /// ); + /// ``` + pub fn uniform_knot(degree: usize, division: usize) -> KnotVec { + let mut vec = vec![0.0; degree + 1]; + vec.extend((1..division).map(|i| (i as f64) / (division as f64))); + vec.extend(std::iter::repeat(1.0).take(degree + 1)); + KnotVec(vec) + } +} + +impl From> for KnotVec { + /// constructs from `Vec`. The vector will sorted by the order. + /// ``` + /// use truck_geometry::prelude::KnotVec; + /// let knot_vec = KnotVec::from(vec![1.0, 0.0, 3.0, 2.0]); + /// let arr : Vec = knot_vec.into(); + /// assert_eq!(arr, vec![0.0, 1.0, 2.0, 3.0]); + /// ``` + fn from(mut vec: Vec) -> KnotVec { + vec.sort_by(|a, b| a.partial_cmp(b).unwrap()); + KnotVec(vec) + } +} + +impl From<&Vec> for KnotVec { + /// Constructs by the reference of vector. The clone of vector is sorted by the order. + /// ``` + /// use truck_geometry::prelude::KnotVec; + /// let knot_vec = KnotVec::from(&vec![1.0, 0.0, 3.0, 2.0]); + /// let arr : Vec = knot_vec.into(); + /// assert_eq!(arr, vec![0.0, 1.0, 2.0, 3.0]); + /// ``` + #[inline(always)] + fn from(vec: &Vec) -> KnotVec { + let mut copy_vec = vec.clone(); + copy_vec.sort_by(|a, b| a.partial_cmp(b).unwrap()); + KnotVec(copy_vec) + } +} + +impl From for Vec { + /// `KnotVec` into `Vec` + /// ``` + /// use truck_geometry::prelude::KnotVec; + /// let vec = vec![0.0, 1.0, 2.0, 3.0]; + /// let knot_vec = KnotVec::from(&vec); + /// let vec0 : Vec = knot_vec.into(); + /// assert_eq!(vec, vec0); + /// ``` + #[inline(always)] + fn from(knotvec: KnotVec) -> Vec { knotvec.0 } +} + +impl FromIterator for KnotVec { + #[inline(always)] + fn from_iter>(iter: I) -> KnotVec { + KnotVec::try_from(iter.into_iter().collect::>()).unwrap() + } +} + +impl<'a> IntoIterator for &'a KnotVec { + type Item = &'a f64; + type IntoIter = std::slice::Iter<'a, f64>; + #[inline(always)] + fn into_iter(self) -> Self::IntoIter { self.0.iter() } +} + +impl std::ops::Deref for KnotVec { + type Target = Vec; + #[inline(always)] + fn deref(&self) -> &Vec { &self.0 } +} + +impl AsRef<[f64]> for KnotVec { + #[inline(always)] + fn as_ref(&self) -> &[f64] { &self.0 } +} + +impl<'de> Deserialize<'de> for KnotVec { + fn deserialize(deserializer: D) -> std::result::Result + where D: serde::Deserializer<'de> { + let vec = Vec::::deserialize(deserializer)?; + Self::try_from(vec).map_err(serde::de::Error::custom) + } +} diff --git a/vendor/truck-geometry/src/nurbs/mod.rs b/vendor/truck-geometry/src/nurbs/mod.rs new file mode 100644 index 000000000..24a553133 --- /dev/null +++ b/vendor/truck-geometry/src/nurbs/mod.rs @@ -0,0 +1,135 @@ +use crate::{prelude::*, *}; +use truck_base::cgmath64::control_point::ControlPoint; + +/// knot vector +#[derive(Clone, PartialEq, Debug, Default, Serialize)] +pub struct KnotVec(Vec); + +/// B-spline curve +/// # Examples +/// ``` +/// use truck_geometry::prelude::*; +/// +/// // the knot vector +/// let knot_vec = KnotVec::from( +/// vec![0.0, 0.0, 0.0, 0.25, 0.25, 0.5, 0.5, 0.75, 0.75, 1.0, 1.0, 1.0] +/// ); +/// +/// // sign up the control points in the vector of all points +/// let ctrl_pts = vec![ // the vector of the indices of control points +/// Vector4::new(0.0, -2.0, 0.0, 2.0), +/// Vector4::new(1.0, -1.0, 0.0, 1.0), +/// Vector4::new(1.0, 0.0, 0.0, 1.0), +/// Vector4::new(1.0, 1.0, 0.0, 1.0), +/// Vector4::new(0.0, 2.0, 0.0, 2.0), +/// Vector4::new(-1.0, 1.0, 0.0, 1.0), +/// Vector4::new(-1.0, 0.0, 0.0, 1.0), +/// Vector4::new(-1.0, -1.0, 0.0, 1.0), +/// Vector4::new(0.0, -2.0, 0.0, 2.0), +/// ]; +/// +/// // construct the B-spline curve +/// let bspline = BSplineCurve::new(knot_vec, ctrl_pts); +/// +/// // This B-spline curve is a nurbs representation of the unit circle. +/// const N : usize = 100; // sample size in test +/// for i in 0..N { +/// let t = 1.0 / (N as f64) * (i as f64); +/// let v = bspline.subs(t); // We can use the instances as a function. +/// let c = (v[0] / v[3]).powi(2) + (v[1] / v[3]).powi(2); +/// assert_near2!(c, 1.0); +/// } +/// ``` +#[derive(Clone, PartialEq, Debug, Serialize)] +pub struct BSplineCurve

{ + knot_vec: KnotVec, // the knot vector + control_points: Vec

, // the indices of control points +} + +/// B-spline surface +/// # Examples +/// ``` +/// use truck_geometry::prelude::*; +/// const N : usize = 100; // sample size in test +/// +/// // the knot vectors +/// let knot_vec0 = KnotVec::bezier_knot(3); +/// let knot_vec1 = KnotVec::from( +/// vec![0.0, 0.0, 0.0, 0.0, 0.5, 0.5, 0.5, 1.0, 1.0, 1.0, 1.0] +/// ); +/// let knot_vecs = (knot_vec0, knot_vec1); +/// +/// // the control points +/// let mut v = vec![vec![Vector4::zero(); 7]; 4]; +/// v[0][0] = Vector4::new(0.0, 0.0, 1.0, 1.0); +/// v[0][1] = &v[0][0] / 3.0; +/// v[0][2] = v[0][1].clone(); +/// v[0][3] = v[0][0].clone(); +/// v[0][4] = v[0][1].clone(); +/// v[0][5] = v[0][1].clone(); +/// v[0][6] = v[0][0].clone(); +/// v[1][0] = Vector4::new(2.0, 0.0, 1.0, 1.0) / 3.0; +/// v[1][1] = Vector4::new(2.0, 4.0, 1.0, 1.0) / 9.0; +/// v[1][2] = Vector4::new(-2.0, 4.0, 1.0, 1.0) / 9.0; +/// v[1][3] = Vector4::new(-2.0, 0.0, 1.0, 1.0) / 3.0; +/// v[1][4] = Vector4::new(-2.0, -4.0, 1.0, 1.0) / 9.0; +/// v[1][5] = Vector4::new(2.0, -4.0, 1.0, 1.0) / 9.0; +/// v[1][6] = Vector4::new(2.0, 0.0, 1.0, 1.0) / 3.0; +/// v[2][0] = Vector4::new(2.0, 0.0, -1.0, 1.0) / 3.0; +/// v[2][1] = Vector4::new(2.0, 4.0, -1.0, 1.0) / 9.0; +/// v[2][2] = Vector4::new(-2.0, 4.0, -1.0, 1.0) / 9.0; +/// v[2][3] = Vector4::new(-2.0, 0.0, -1.0, 1.0) / 3.0; +/// v[2][4] = Vector4::new(-2.0, -4.0, -1.0, 1.0) / 9.0; +/// v[2][5] = Vector4::new(2.0, -4.0, -1.0, 1.0) / 9.0; +/// v[2][6] = Vector4::new(2.0, 0.0, -1.0, 1.0) / 3.0; +/// v[3][0] = Vector4::new(0.0, 0.0, -1.0, 1.0); +/// v[3][1] = &v[3][0] / 3.0; +/// v[3][2] = v[3][1].clone(); +/// v[3][3] = v[3][0].clone(); +/// v[3][4] = v[3][1].clone(); +/// v[3][5] = v[3][1].clone(); +/// v[3][6] = v[3][0].clone(); +/// +/// // cunstruct the B-spline curve +/// let bspline = BSplineSurface::new(knot_vecs, v); +/// +/// // This B-spline curve is a nurbs representation of the unit sphere. +/// for i in 0..N { +/// for j in 0..N { +/// let u = 1.0 / (N as f64) * (i as f64); +/// let v = 1.0 / (N as f64) * (j as f64); +/// let v = bspline.subs(u, v); // We can use the instances as a function. +/// let c = (v[0] / v[3]).powi(2) + (v[1] / v[3]).powi(2) + (v[2] / v[3]).powi(2); +/// assert_near2!(c, 1.0); +/// } +/// } +/// ``` +#[derive(Clone, PartialEq, Debug, Serialize)] +pub struct BSplineSurface

{ + knot_vecs: (KnotVec, KnotVec), + control_points: Vec>, +} + +/// NURBS curve +#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)] +pub struct NurbsCurve(BSplineCurve); + +/// NURBS surface +#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)] +pub struct NurbsSurface(BSplineSurface); + +mod bspcurve; +mod bspsurface; +mod knot_vec; +mod nurbscurve; +mod nurbssurface; + +#[doc(hidden)] +#[inline(always)] +pub fn inv_or_zero(delta: f64) -> f64 { + if delta.so_small() { + 0.0 + } else { + 1.0 / delta + } +} diff --git a/vendor/truck-geometry/src/nurbs/nurbscurve.rs b/vendor/truck-geometry/src/nurbs/nurbscurve.rs new file mode 100644 index 000000000..b6a769a21 --- /dev/null +++ b/vendor/truck-geometry/src/nurbs/nurbscurve.rs @@ -0,0 +1,619 @@ +use super::*; + +impl NurbsCurve { + /// Constructs the rationalized B-spline curve. + #[inline(always)] + pub const fn new(curve: BSplineCurve) -> Self { NurbsCurve(curve) } + + /// Returns the BSpline curve before rationalized. + #[inline(always)] + pub const fn non_rationalized(&self) -> &BSplineCurve { &self.0 } + + /// Returns the BSpline curve before rationalized. + #[inline(always)] + pub fn into_non_rationalized(self) -> BSplineCurve { self.0 } + + /// Returns the reference of the knot vector. cf.[`BSplineCurve::knot_vec`] + #[inline(always)] + pub const fn knot_vec(&self) -> &KnotVec { &self.0.knot_vec } + + /// Returns the `idx`th knot. cf.[`BSplineCurve::knot`] + #[inline(always)] + pub fn knot(&self, idx: usize) -> f64 { self.0.knot_vec[idx] } + + /// Returns the reference of the control points. cf.[`BSplineCurve::control_points`] + #[inline(always)] + pub const fn control_points(&self) -> &Vec { &self.0.control_points } + + /// Returns the reference of the control point corresponding to the index `idx`. + /// cf.[`BSplineCurve::control_point`] + #[inline(always)] + pub fn control_point(&self, idx: usize) -> &V { &self.0.control_points[idx] } + + /// Returns the mutable reference of the control point corresponding to index `idx`. + /// cf.[`BSplineCurve::control_point_mut`] + #[inline(always)] + pub fn control_point_mut(&mut self, idx: usize) -> &mut V { &mut self.0.control_points[idx] } + + /// Returns the iterator on all control points. cf.[`BSplineCurve::control_points_mut`] + #[inline(always)] + pub fn control_points_mut(&mut self) -> impl Iterator { + self.0.control_points.iter_mut() + } + + /// Applies the given transformation to all control points. cf.[`BSplineCurve::transform_control_points`] + #[inline(always)] + pub fn transform_control_points(&mut self, f: F) { + self.0.transform_control_points(f) + } + + /// Returns the degree of NURBS curve. cf.[`BSplineCurve::degree`] + #[inline(always)] + pub fn degree(&self) -> usize { self.0.degree() } + + /// Inverts a curve. cf.[`BSplineCurve::invert`] + #[inline(always)] + pub fn invert(&mut self) -> &mut Self { + self.0.invert(); + self + } + + /// Returns whether the knot vector is clamped or not. cf.[`BSplineCurve::is_clamped`] + #[inline(always)] + pub fn is_clamped(&self) -> bool { self.0.knot_vec.is_clamped(self.0.degree()) } + + /// Normalizes the knot vector. cf.[`BSplineCurve::knot_normalize`] + #[inline(always)] + pub fn knot_normalize(&mut self) -> &mut Self { + self.0.knot_vec.try_normalize().unwrap(); + self + } + + /// Translates the knot vector. cf.[`BSplineCurve::knot_translate`] + #[inline(always)] + pub fn knot_translate(&mut self, x: f64) -> &mut Self { + self.0.knot_vec.translate(x); + self + } +} + +impl> NurbsCurve { + /// Constructs a rationalization curve from the non-rationalized curve and weights. + /// # Failures + /// the length of `curve.control_points()` and `weights` must be the same. + #[inline(always)] + pub fn try_from_bspline_and_weights( + curve: BSplineCurve, + weights: Vec, + ) -> Result { + let BSplineCurve { + knot_vec, + control_points, + } = curve; + if control_points.len() != weights.len() { + return Err(Error::DifferentLength); + } + let control_points = control_points + .into_iter() + .zip(weights) + .map(|(pt, w)| V::from_point_weight(pt, w)) + .collect(); + Ok(Self(BSplineCurve::new_unchecked(knot_vec, control_points))) + } +} + +impl + ControlPoint> NurbsCurve { + /// Returns the closure of substitution. + #[inline(always)] + pub fn get_closure(&self) -> impl Fn(f64) -> V::Point + '_ { move |t| self.subs(t) } +} + +impl + ControlPoint> NurbsCurve +where V::Point: Tolerance +{ + /// Returns whether all control points are the same or not. + /// If the knot vector is clamped, it means whether the curve is constant or not. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// + /// let knot_vec = KnotVec::bezier_knot(2); + /// let pt = Vector3::new(1.0, 2.0, 1.0); + /// // allows differences upto scalars + /// let mut ctrl_pts = vec![pt.clone(), pt.clone() * 2.0, pt.clone() * 3.0]; + /// let bspcurve = BSplineCurve::new(knot_vec.clone(), ctrl_pts.clone()); + /// assert!(!bspcurve.is_const()); + /// let const_curve = NurbsCurve::new(bspcurve); + /// assert!(const_curve.is_const()); + /// + /// ctrl_pts.push(Vector3::new(2.0, 3.0, 1.0)); + /// let curve = NurbsCurve::new(BSplineCurve::new(knot_vec.clone(), ctrl_pts.clone())); + /// assert!(!curve.is_const()); + /// ``` + /// # Remarks + /// If the knot vector is not clamped and the BSpline basis function is not partition of unity, + /// then perhaps returns true even if the curve is not constant. + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vec = KnotVec::uniform_knot(1, 5); + /// let ctrl_pts = vec![Vector2::new(1.0, 2.0), Vector2::new(1.0, 2.0)]; + /// let bspcurve = BSplineCurve::new(knot_vec, ctrl_pts); + /// + /// // bspcurve is not constant. + /// assert_eq!(bspcurve.subs(0.0), Vector2::new(0.0, 0.0)); + /// assert_ne!(bspcurve.subs(0.5), Vector2::new(0.0, 0.0)); + /// + /// // bspcurve.is_const() is true + /// assert!(bspcurve.is_const()); + /// ``` + pub fn is_const(&self) -> bool { + let pt = self.0.control_points[0].to_point(); + self.0 + .control_points + .iter() + .all(move |vec| vec.to_point().near(&pt)) + } + /// Determines whether `self` and `other` is near as the B-spline curves or not. + /// + /// Divides each knot interval into the number of degree equal parts, + /// and check `|self(t) - other(t)| < TOLERANCE` for each end points `t`. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vec = KnotVec::from( + /// vec![0.0, 0.0, 0.0, 1.0, 2.0, 3.0, 4.0, 4.0, 4.0] + /// ); + /// let ctrl_pts = vec![ + /// Vector3::new(1.0, 1.0, 1.0), + /// Vector3::new(3.0, 2.0, 2.0), + /// Vector3::new(2.0, 3.0, 1.0), + /// Vector3::new(4.0, 5.0, 2.0), + /// Vector3::new(5.0, 4.0, 1.0), + /// Vector3::new(1.0, 1.0, 2.0), + /// ]; + /// let curve0 = NurbsCurve::new(BSplineCurve::new(knot_vec, ctrl_pts)); + /// let mut curve1 = curve0.clone(); + /// assert!(curve0.near_as_curve(&curve1)); + /// *curve1.control_point_mut(1) += Vector3::new(0.01, 0.0002, 0.0); + /// assert!(!curve0.near_as_curve(&curve1)); + /// ``` + #[inline(always)] + pub fn near_as_curve(&self, other: &Self) -> bool { + self.0 + .sub_near_as_curve(&other.0, 2, move |x, y| x.to_point().near(&y.to_point())) + } + + /// Determines `self` and `other` is near in square order as the B-spline curves or not. + /// + /// Divide each knot interval into the number of degree equal parts, + /// and check `|self(t) - other(t)| < TOLERANCE`for each end points `t`. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vec = KnotVec::from( + /// vec![0.0, 0.0, 0.0, 1.0, 2.0, 3.0, 4.0, 4.0, 4.0] + /// ); + /// let ctrl_pts = vec![ + /// Vector3::new(1.0, 1.0, 1.0), + /// Vector3::new(3.0, 2.0, 2.0), + /// Vector3::new(2.0, 3.0, 1.0), + /// Vector3::new(4.0, 5.0, 2.0), + /// Vector3::new(5.0, 4.0, 1.0), + /// Vector3::new(1.0, 1.0, 2.0), + /// ]; + /// let curve0 = NurbsCurve::new(BSplineCurve::new(knot_vec, ctrl_pts)); + /// let mut curve1 = curve0.clone(); + /// assert!(curve0.near_as_curve(&curve1)); + /// *curve1.control_point_mut(1) += Vector3::new(0.01, TOLERANCE, 0.0); + /// assert!(!curve0.near2_as_curve(&curve1)); + /// ``` + #[inline(always)] + pub fn near2_as_curve(&self, other: &Self) -> bool { + self.0 + .sub_near_as_curve(&other.0, 2, move |x, y| x.to_point().near2(&y.to_point())) + } +} + +impl + ControlPoint + Tolerance> NurbsCurve { + /// Adds a knot `x`, and do not change `self` as a curve. cf.[`BSplineCurve::add_knot`] + pub fn add_knot(&mut self, x: f64) -> &mut Self { + self.0.add_knot(x); + self + } + + /// Removes a knot corresponding to the indices `idx`, and do not change `self` as a curve. + /// If cannot remove the knot, do not change `self` and return `self`. + /// cf.[`BSplineCurve::remove_knot`] + pub fn remove_knot(&mut self, idx: usize) -> &mut Self { + let _ = self.try_remove_knot(idx); + self + } + + /// Removes a knot corresponding to the indice `idx`, and do not change `self` as a curve. + /// If the knot cannot be removed, returns [`Error::CannotRemoveKnot`]. + /// cf.[`BSplineCurve::try_remove_knot`] + pub fn try_remove_knot(&mut self, idx: usize) -> Result<&mut Self> { + self.0.try_remove_knot(idx)?; + Ok(self) + } + + /// Elevates 1 degree. cf.[`BSplineCurve::elevate_degree`] + pub fn elevate_degree(&mut self) -> &mut Self { + self.0.elevate_degree(); + self + } + + /// Makes the NURBS curve clamped. cf.[`BSplineCurve::clamp`] + #[inline(always)] + pub fn clamp(&mut self) -> &mut Self { + self.0.clamp(); + self + } + + /// Repeats `Self::try_remove_knot()` from the back knot in turn until the knot cannot be removed. + /// cf.[`BSplineCurve::optimize`] + pub fn optimize(&mut self) -> &mut Self { + self.0.optimize(); + self + } + + /// Makes two splines having the same degrees. cf.[`BSplineCurve::syncro_degree`] + pub fn syncro_degree(&mut self, other: &mut Self) { + let (degree0, degree1) = (self.degree(), other.degree()); + for _ in degree0..degree1 { + self.elevate_degree(); + } + for _ in degree1..degree0 { + other.elevate_degree(); + } + } + + /// Makes two splines having the same normalized knot vectors. cf.[`BSplineCurve::syncro_knots`] + pub fn syncro_knots(&mut self, other: &mut Self) { self.0.syncro_knots(&mut other.0) } +} + +impl + ControlPoint + Tolerance> ParameterTransform + for NurbsCurve +{ + #[inline(always)] + fn parameter_transform(&mut self, scalar: f64, r#move: f64) -> &mut Self { + self.0.parameter_transform(scalar, r#move); + self + } +} + +impl + ControlPoint + Tolerance> Cut for NurbsCurve { + #[inline(always)] + fn cut(&mut self, t: f64) -> Self { NurbsCurve(self.0.cut(t)) } +} + +impl + ControlPoint + Tolerance> Concat> + for NurbsCurve +where >::Point: Debug +{ + type Output = NurbsCurve; + fn try_concat( + &self, + other: &Self, + ) -> std::result::Result>::Point>> { + let curve0 = self.clone(); + let mut curve1 = other.clone(); + let w0 = curve0.0.control_points.last().unwrap().weight(); + let w1 = curve1.0.control_points[0].weight(); + curve1.transform_control_points(|pt| *pt *= w0 / w1); + match curve0.0.try_concat(&curve1.0) { + Ok(curve) => Ok(NurbsCurve::new(curve)), + Err(err) => Err(err.point_map(|v| v.to_point())), + } + } +} + +#[test] +fn concat_positive_test() { + let mut part0 = NurbsCurve::new(BSplineCurve::new( + KnotVec::uniform_knot(4, 4), + (0..8) + .map(|_| { + Vector4::new( + rand::random::(), + rand::random::(), + rand::random::(), + rand::random::() + 0.5, + ) + }) + .collect(), + )); + let mut part1 = part0.cut(0.56); + let w = 20.0 * rand::random::() - 10.0; + part1.transform_control_points(|vec| *vec *= w); + assert_near!(part0.back(), part1.front()); + concat_random_test(&part0, &part1, 10); +} + +impl + ControlPoint + Tolerance> NurbsCurve +where V::Point: Tolerance +{ + /// Makes the rational curve locally injective. + /// # Example + /// ``` + /// use truck_geometry::prelude::*; + /// const N : usize = 100; // sample size for test + /// + /// let knot_vec = KnotVec::from( + /// vec![0.0, 0.0, 0.0, 1.0, 3.0, 4.0, 4.0, 4.0] + /// ); + /// let control_points = vec![ + /// Vector4::new(1.0, 0.0, 0.0, 1.0), + /// Vector4::new(0.0, 1.0, 0.0, 1.0), + /// Vector4::new(0.0, 2.0, 0.0, 2.0), + /// Vector4::new(0.0, 3.0, 0.0, 3.0), + /// Vector4::new(0.0, 0.0, 3.0, 3.0), + /// ]; + /// + /// let mut curve = NurbsCurve::new(BSplineCurve::new(knot_vec, control_points)); + /// let mut flag = false; + /// for i in 0..N { + /// let t = 4.0 * (i as f64) / (N as f64); + /// let pt0 = curve.subs(t); + /// let pt1 = curve.subs(t + 1.0 / (N as f64)); + /// flag = flag || pt0.near(&pt1); + /// } + /// // There exists t such that bspcurve(t) == bspcurve(t + 0.01). + /// assert!(flag); + /// + /// curve.make_locally_injective().knot_normalize(); + /// let mut flag = false; + /// for i in 0..N { + /// let t = 1.0 * (i as f64) / (N as f64); + /// let pt0 = curve.subs(t); + /// let pt1 = curve.subs(t + 1.0 / (N as f64)); + /// flag = flag || pt0.near(&pt1); + /// } + /// // There does not exist t such that bspcurve(t) == bspcurve(t + 0.01). + /// assert!(!flag); + /// ``` + /// # Remarks + /// If `self` is a constant curve, then does nothing. + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vec = KnotVec::from(vec![0.0, 0.0, 0.0, 1.0, 2.0, 2.0, 2.0]); + /// let ctrl_pts = vec![ + /// Vector3::new(1.0, 1.0, 1.0), + /// Vector3::new(2.0, 2.0, 2.0), + /// Vector3::new(3.0, 3.0, 3.0), + /// Vector3::new(4.0, 4.0, 4.0), + /// ]; + /// let mut curve = NurbsCurve::new(BSplineCurve::new(knot_vec, ctrl_pts)); + /// let org_curve = curve.clone(); + /// curve.make_locally_injective(); + /// assert_eq!(curve, org_curve); + /// ``` + pub fn make_locally_injective(&mut self) -> &mut Self { + let mut iter = self.0.bezier_decomposition().into_iter(); + while let Some(bezier) = iter.next().map(NurbsCurve::new) { + if !bezier.is_const() { + *self = bezier; + break; + } + } + let mut x = 0.0; + for mut bezier in iter.map(NurbsCurve::new) { + if bezier.is_const() { + x += bezier.0.knot_vec.range_length(); + } else { + let s0 = self.0.control_points.last().unwrap().weight(); + let s1 = bezier.0.control_points[0].weight(); + bezier + .0 + .control_points + .iter_mut() + .for_each(move |vec| *vec *= s0 / s1); + self.concat(bezier.knot_translate(-x)); + } + } + self + } +} + +impl + ControlPoint> ParameterDivision1D for NurbsCurve +where V::Point: MetricSpace + HashGen +{ + type Point = V::Point; + #[inline(always)] + fn parameter_division(&self, range: (f64, f64), tol: f64) -> (Vec, Vec) { + algo::curve::parameter_division(self, range, tol) + } +} + +impl + ControlPoint> SearchNearestParameter for NurbsCurve +where + V::Point: MetricSpace, + ::Diff: InnerSpace + Tolerance, +{ + type Point = V::Point; + /// Searches the parameter `t` which minimize |self(t) - point| by Newton's method with initial guess `hint`. + /// Returns `None` if the number of attempts exceeds `trial` i.e. if `trial == 0`, then the trial is only one time. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// + /// // Defines the half unit circle in x > 0. + /// let knot_vec = KnotVec::bezier_knot(2); + /// let ctrl_pts = vec![Vector3::new(0.0, -1.0, 1.0), Vector3::new(1.0, 0.0, 0.0), Vector3::new(0.0, 1.0, 1.0)]; + /// let curve = NurbsCurve::new(BSplineCurve::new(knot_vec, ctrl_pts)); + /// + /// // search rational nearest parameter + /// let pt = Point2::new(1.0, 2.0); + /// let hint = 0.8; + /// let t = curve.search_nearest_parameter(pt, Some(hint), 100).unwrap(); + /// + /// // check the answer + /// let res = curve.subs(t); + /// let ans = Point2::from_vec(pt.to_vec().normalize()); + /// assert_near!(res, ans); + /// ``` + /// # Remarks + /// It may converge to a local solution depending on the hint. + /// ``` + /// use truck_geometry::prelude::*; + /// + /// // Same curve and point as above example + /// let knot_vec = KnotVec::bezier_knot(2); + /// let ctrl_pts = vec![Vector3::new(0.0, -1.0, 1.0), Vector3::new(1.0, 0.0, 0.0), Vector3::new(0.0, 1.0, 1.0)]; + /// let curve = NurbsCurve::new(BSplineCurve::new(knot_vec, ctrl_pts)); + /// let pt = Point2::new(1.0, 2.0); + /// + /// // another hint + /// let hint = 0.5; + /// + /// // Newton's method is vibration divergent. + /// assert!(curve.search_nearest_parameter(pt, Some(hint), 100).is_none()); + /// ``` + #[inline(always)] + fn search_nearest_parameter>( + &self, + point: V::Point, + hint: H, + trial: usize, + ) -> Option { + let hint = match hint.into() { + SPHint1D::Parameter(hint) => hint, + SPHint1D::Range(x, y) => { + algo::curve::presearch(self, point, (x, y), PRESEARCH_DIVISION) + } + SPHint1D::None => { + algo::curve::presearch(self, point, self.range_tuple(), PRESEARCH_DIVISION) + } + }; + algo::curve::search_nearest_parameter(self, point, hint, trial) + } +} + +impl + ControlPoint> SearchParameter for NurbsCurve +where + V::Point: MetricSpace, + ::Diff: InnerSpace + Tolerance, +{ + type Point = V::Point; + #[inline(always)] + fn search_parameter>( + &self, + point: V::Point, + hint: H, + trial: usize, + ) -> Option { + let hint = match hint.into() { + SPHint1D::Parameter(hint) => hint, + SPHint1D::Range(x, y) => { + algo::curve::presearch(self, point, (x, y), PRESEARCH_DIVISION) + } + SPHint1D::None => { + algo::curve::presearch(self, point, self.range_tuple(), PRESEARCH_DIVISION) + } + }; + algo::curve::search_parameter(self, point, hint, trial) + } +} + +impl> NurbsCurve +where V::Point: Bounded +{ + /// Returns the bounding box including all control points. + #[inline(always)] + pub fn roughly_bounding_box(&self) -> BoundingBox { + self.0.control_points.iter().map(|p| p.to_point()).collect() + } +} + +impl + ControlPoint> ParametricCurve for NurbsCurve { + type Point = V::Point; + type Vector = ::Diff; + #[inline(always)] + fn subs(&self, t: f64) -> Self::Point { self.0.subs(t).to_point() } + #[inline(always)] + fn der(&self, t: f64) -> Self::Vector { + let pt = self.0.subs(t); + let der = self.0.der(t); + pt.rat_der(der) + } + #[inline(always)] + fn der2(&self, t: f64) -> Self::Vector { + let pt = self.0.subs(t); + let der = self.0.der(t); + let der2 = self.0.der2(t); + pt.rat_der2(der, der2) + } + #[inline(always)] + fn parameter_range(&self) -> ParameterRange { + ( + Bound::Included(self.0.knot_vec[0]), + Bound::Included(self.0.knot_vec[self.0.knot_vec.len() - 1]), + ) + } +} + +impl + ControlPoint> BoundedCurve for NurbsCurve {} + +impl Invertible for NurbsCurve { + #[inline(always)] + fn invert(&mut self) { self.invert(); } + #[inline(always)] + fn inverse(&self) -> Self { + let mut curve = self.0.clone(); + curve.invert(); + NurbsCurve(curve) + } +} + +impl Transformed for NurbsCurve +where M: Copy + std::ops::Mul +{ + #[inline(always)] + fn transform_by(&mut self, trans: M) { + self.0 + .control_points + .iter_mut() + .for_each(move |v| *v = trans * *v) + } +} + +impl> From> for NurbsCurve { + fn from(bspcurve: BSplineCurve) -> NurbsCurve { + NurbsCurve::new(BSplineCurve::new_unchecked( + bspcurve.knot_vec, + bspcurve + .control_points + .into_iter() + .map(V::from_point) + .collect(), + )) + } +} + +#[test] +fn test_parameter_division() { + let knot_vec = KnotVec::uniform_knot(2, 3); + let ctrl_pts = vec![ + Vector4::new(0.0, 0.0, 0.0, 1.0), + Vector4::new(2.0, 0.0, 0.0, 2.0), + Vector4::new(0.0, 3.0, 0.0, 3.0), + Vector4::new(0.0, 0.0, 2.0, 2.0), + Vector4::new(1.0, 1.0, 1.0, 1.0), + ]; + let curve = NurbsCurve::new(BSplineCurve::new(knot_vec, ctrl_pts)); + let tol = 0.01; + let (div, pts) = curve.parameter_division(curve.range_tuple(), tol * 0.5); + let knot_vec = curve.knot_vec(); + assert_eq!(knot_vec[0], div[0]); + assert_eq!(knot_vec.range_length(), div.last().unwrap() - div[0]); + for i in 1..div.len() { + let pt0 = curve.subs(div[i - 1]); + assert_eq!(pt0, pts[i - 1]); + let pt1 = curve.subs(div[i]); + assert_eq!(pt1, pts[i]); + let value_middle = pt0.midpoint(pt1); + let param_middle = curve.subs((div[i - 1] + div[i]) / 2.0); + let dist = value_middle.distance(param_middle); + assert!(dist < tol, "large distance: {dist}"); + } +} diff --git a/vendor/truck-geometry/src/nurbs/nurbssurface.rs b/vendor/truck-geometry/src/nurbs/nurbssurface.rs new file mode 100644 index 000000000..16984dab3 --- /dev/null +++ b/vendor/truck-geometry/src/nurbs/nurbssurface.rs @@ -0,0 +1,920 @@ +use super::*; + +impl NurbsSurface { + /// constructor + #[inline(always)] + pub const fn new(bspsurface: BSplineSurface) -> Self { NurbsSurface(bspsurface) } + + /// Returns the nurbs surface before rationalized + #[inline(always)] + pub const fn non_rationalized(&self) -> &BSplineSurface { &self.0 } + /// Returns the nurbs surface before rationalized + #[inline(always)] + pub fn non_rationalized_mut(&mut self) -> &mut BSplineSurface { &mut self.0 } + + /// Returns the nurbs surface before rationalized + #[inline(always)] + pub fn into_non_rationalized(self) -> BSplineSurface { self.0 } + + /// Returns the reference of the knot vectors + #[inline(always)] + pub const fn knot_vecs(&self) -> &(KnotVec, KnotVec) { &self.0.knot_vecs } + + /// Returns the u knot vector. + #[inline(always)] + pub const fn uknot_vec(&self) -> &KnotVec { &self.0.knot_vecs.0 } + /// Returns the v knot vector. + #[inline(always)] + pub const fn vknot_vec(&self) -> &KnotVec { &self.0.knot_vecs.1 } + + /// Returns the `idx`th u knot. + #[inline(always)] + pub fn uknot(&self, idx: usize) -> f64 { self.0.knot_vecs.0[idx] } + /// returns the `idx`th v knot. + #[inline(always)] + pub fn vknot(&self, idx: usize) -> f64 { self.0.knot_vecs.1[idx] } + + /// Returns the reference of the vector of the control points + #[inline(always)] + pub const fn control_points(&self) -> &Vec> { &self.0.control_points } + + /// Returns the reference of the control point corresponding to the index `(idx0, idx1)`. + #[inline(always)] + pub fn control_point(&self, idx0: usize, idx1: usize) -> &V { + &self.0.control_points[idx0][idx1] + } + + /// Apply the given transformation to all control points. + #[inline(always)] + pub fn transform_control_points(&mut self, f: F) { + self.0.transform_control_points(f) + } + + /// Returns the iterator over the control points in the `column_idx`th row. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let uknot_vec = KnotVec::bezier_knot(1); + /// let vknot_vec = KnotVec::bezier_knot(2); + /// let knot_vecs = (uknot_vec, vknot_vec); + /// let ctrl_pts = vec![ + /// vec![Vector3::new(0.0, 0.0, 0.0), Vector3::new(1.0, 0.0, 1.0), Vector3::new(2.0, 0.0, 2.0)], + /// vec![Vector3::new(0.0, 1.0, 0.0), Vector3::new(1.0, 1.0, 1.0), Vector3::new(2.0, 1.0, 2.0)], + /// ]; + /// let bspsurface = BSplineSurface::new(knot_vecs, ctrl_pts); + /// let mut iter = bspsurface.ctrl_pts_row_iter(1); + /// assert_eq!(iter.next(), Some(&Vector3::new(1.0, 0.0, 1.0))); + /// assert_eq!(iter.next(), Some(&Vector3::new(1.0, 1.0, 1.0))); + /// assert_eq!(iter.next(), None); + /// ``` + #[inline(always)] + pub fn ctrl_pts_row_iter( + &self, + column_idx: usize, + ) -> impl ExactSizeIterator + std::iter::FusedIterator { + self.0.ctrl_pts_row_iter(column_idx) + } + + /// Returns the iterator over the control points in the `row_idx`th row. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let uknot_vec = KnotVec::bezier_knot(1); + /// let vknot_vec = KnotVec::bezier_knot(2); + /// let knot_vecs = (uknot_vec, vknot_vec); + /// let ctrl_pts = vec![ + /// vec![Vector3::new(0.0, 0.0, 0.0), Vector3::new(1.0, 0.0, 1.0), Vector3::new(2.0, 0.0, 2.0)], + /// vec![Vector3::new(0.0, 1.0, 0.0), Vector3::new(1.0, 1.0, 1.0), Vector3::new(2.0, 1.0, 2.0)], + /// ]; + /// let bspsurface = BSplineSurface::new(knot_vecs, ctrl_pts); + /// let mut iter = bspsurface.ctrl_pts_column_iter(1); + /// assert_eq!(iter.next(), Some(&Vector3::new(0.0, 1.0, 0.0))); + /// assert_eq!(iter.next(), Some(&Vector3::new(1.0, 1.0, 1.0))); + /// assert_eq!(iter.next(), Some(&Vector3::new(2.0, 1.0, 2.0))); + /// assert_eq!(iter.next(), None); + /// ``` + #[inline(always)] + pub fn ctrl_pts_column_iter(&self, row_idx: usize) -> std::slice::Iter<'_, V> { + self.0.control_points[row_idx].iter() + } + + /// Returns the mutable reference of the control point corresponding to index `(idx0, idx1)`. + #[inline(always)] + pub fn control_point_mut(&mut self, idx0: usize, idx1: usize) -> &mut V { + &mut self.0.control_points[idx0][idx1] + } + + /// Returns the iterator on all control points + #[inline(always)] + pub fn control_points_mut(&mut self) -> impl Iterator { + self.0.control_points.iter_mut().flatten() + } + /// Returns the degrees of B-spline surface + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let uknot_vec = KnotVec::from(vec![0.0, 0.0, 1.0, 1.0]); + /// let vknot_vec = KnotVec::from(vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0]); + /// let knot_vecs = (uknot_vec, vknot_vec); + /// let ctrl_pts = vec![ + /// vec![Vector3::new(0.0, 0.0, 0.0), Vector3::new(1.0, 0.0, 1.0), Vector3::new(2.0, 0.0, 2.0)], + /// vec![Vector3::new(0.0, 1.0, 0.0), Vector3::new(1.0, 1.0, 1.0), Vector3::new(2.0, 1.0, 2.0)], + /// ]; + /// let bspsurface = BSplineSurface::new(knot_vecs, ctrl_pts); + /// assert_eq!(bspsurface.udegree(), 1); + /// ``` + #[inline(always)] + pub fn udegree(&self) -> usize { self.0.udegree() } + + /// Returns the degrees of B-spline surface + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let uknot_vec = KnotVec::from(vec![0.0, 0.0, 1.0, 1.0]); + /// let vknot_vec = KnotVec::from(vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0]); + /// let knot_vecs = (uknot_vec, vknot_vec); + /// let ctrl_pts = vec![ + /// vec![Vector3::new(0.0, 0.0, 0.0), Vector3::new(1.0, 0.0, 1.0), Vector3::new(2.0, 0.0, 2.0)], + /// vec![Vector3::new(0.0, 1.0, 0.0), Vector3::new(1.0, 1.0, 1.0), Vector3::new(2.0, 1.0, 2.0)], + /// ]; + /// let bspsurface = BSplineSurface::new(knot_vecs, ctrl_pts); + /// assert_eq!(bspsurface.vdegree(), 2); + /// ``` + #[inline(always)] + pub fn vdegree(&self) -> usize { self.0.vdegree() } + + /// Returns the degrees of B-spline surface + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let uknot_vec = KnotVec::from(vec![0.0, 0.0, 1.0, 1.0]); + /// let vknot_vec = KnotVec::from(vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0]); + /// let knot_vecs = (uknot_vec, vknot_vec); + /// let ctrl_pts = vec![ + /// vec![Vector3::new(0.0, 0.0, 0.0), Vector3::new(1.0, 0.0, 1.0), Vector3::new(2.0, 0.0, 2.0)], + /// vec![Vector3::new(0.0, 1.0, 0.0), Vector3::new(1.0, 1.0, 1.0), Vector3::new(2.0, 1.0, 2.0)], + /// ]; + /// let bspsurface = BSplineSurface::new(knot_vecs, ctrl_pts); + /// assert_eq!(bspsurface.degrees(), (1, 2)); + /// ``` + #[inline(always)] + pub fn degrees(&self) -> (usize, usize) { (self.udegree(), self.vdegree()) } + /// Returns whether the knot vectors are clamped or not. + #[inline(always)] + pub fn is_clamped(&self) -> bool { self.0.is_clamped() } + /// Swaps two parameters. + pub fn swap_axes(&mut self) -> &mut Self + where V: Clone { + self.0.swap_axes(); + self + } + /// The range of the parameter of the surface. + #[inline(always)] + pub fn parameter_range(&self) -> (ParameterRange, ParameterRange) { self.0.parameter_range() } + /// Creates the curve whose control points are the `idx`th column control points of `self`. + #[inline(always)] + pub fn column_curve(&self, row_idx: usize) -> NurbsCurve + where V: Clone { + NurbsCurve(self.0.column_curve(row_idx)) + } + /// Creates the column sectional curve. + #[inline(always)] + pub fn row_curve(&self, column_idx: usize) -> NurbsCurve + where V: Clone { + NurbsCurve(self.0.row_curve(column_idx)) + } +} + +impl> NurbsSurface { + /// Constructs a rationalization surface from the non-rationalized surface and weights. + /// # Failures + /// the length of `surface.control_points()` and `weights` must be the same. + #[inline(always)] + pub fn try_from_bspline_and_weights( + surface: BSplineSurface, + weights: Vec>, + ) -> Result { + let BSplineSurface { + knot_vecs, + control_points, + } = surface; + if control_points.len() != weights.len() { + return Err(Error::DifferentLength); + } + let control_points = control_points + .into_iter() + .zip(weights) + .map(|(control_points, weights)| { + if control_points.len() != weights.len() { + return Err(Error::DifferentLength); + } + Ok(control_points + .into_iter() + .zip(weights) + .map(|(pt, w)| V::from_point_weight(pt, w)) + .collect::>()) + }) + .collect::>>()?; + Ok(Self(BSplineSurface::new_unchecked( + knot_vecs, + control_points, + ))) + } +} + +impl + ControlPoint> NurbsSurface { + /// Substitutes to a NURBS surface. + #[inline(always)] + pub fn subs(&self, u: f64, v: f64) -> V::Point { self.0.subs(u, v).to_point() } + /// Substitutes derived NURBS surface by the first parameter `u`. + #[inline(always)] + pub fn uder(&self, u: f64, v: f64) -> ::Diff { + let pt = self.0.subs(u, v); + let ud = self.0.uder(u, v); + pt.rat_der(ud) + } + /// Substitutes derived NURBS surface by the first parameter `v`. + #[inline(always)] + pub fn vder(&self, u: f64, v: f64) -> ::Diff { + let pt = self.0.subs(u, v); + let vd = self.0.vder(u, v); + pt.rat_der(vd) + } + /// Substitutes 2nd-ord derived NURBS surface by the first parameter `u`. + #[inline(always)] + pub fn uuder(&self, u: f64, v: f64) -> ::Diff { + let pt = self.0.subs(u, v); + let ud = self.0.uder(u, v); + let uud = self.0.uuder(u, v); + pt.rat_der2(ud, uud) + } + /// Substitutes 2nd-ord derived NURBS surface by the first parameter `v`. + #[inline(always)] + pub fn vvder(&self, u: f64, v: f64) -> ::Diff { + let pt = self.0.subs(u, v); + let vd = self.0.vder(u, v); + let vvd = self.0.vvder(u, v); + pt.rat_der2(vd, vvd) + } + /// Substitutes 2nd-ord derived NURBS surface by both parameter `u, v`. + #[inline(always)] + pub fn uvder(&self, u: f64, v: f64) -> ::Diff { + let pt = self.0.subs(u, v); + let ud = self.0.uder(u, v); + let vd = self.0.vder(u, v); + let uvd = self.0.uvder(u, v); + pt.rat_cross_der(ud, vd, uvd) + } + /// Returns the closure of substitution. + #[inline(always)] + pub fn get_closure(&self) -> impl Fn(f64, f64) -> V::Point + '_ { move |u, v| self.subs(u, v) } +} + +impl + ControlPoint> NurbsSurface +where V::Point: Tolerance +{ + /// Returns whether constant curve or not, i.e. all control points are same or not. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let uknot_vec = KnotVec::bezier_knot(1); + /// let vknot_vec = KnotVec::bezier_knot(2); + /// let pt = Vector3::new(1.0, 2.0, 1.0); + /// // allows differences upto scalars + /// let ctrl_pts = vec![ + /// vec![pt.clone(), pt.clone() * 2.0, pt.clone() * 3.0], + /// vec![pt.clone() * 0.5, pt.clone() * 0.25, pt.clone() * 0.125], + /// ]; + /// let mut surface = NurbsSurface::new(BSplineSurface::new((uknot_vec, vknot_vec), ctrl_pts)); + /// assert!(surface.is_const()); + /// + /// *surface.control_point_mut(1, 2) = Vector3::new(2.0, 3.0, 1.0); + /// assert!(!surface.is_const()); + /// ``` + #[inline(always)] + pub fn is_const(&self) -> bool { + let pt = self.0.control_points[0][0].to_point(); + for vec in self.0.control_points.iter().flat_map(|pts| pts.iter()) { + if !vec.to_point().near(&pt) { + return false; + } + } + true + } + /// Determines whether `self` and `other` is near as the B-spline rational surfaces or not. + /// + /// Divides each knot domain into the number of degree equal parts, + /// and check `|self(u, v) - other(u, v)| < TOLERANCE` for each end points `(u, v)`. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vecs = (KnotVec::bezier_knot(3), KnotVec::bezier_knot(2)); + /// let ctrl_pts = vec![ + /// vec![Vector3::new(0.0, 0.0, 1.0), Vector3::new(0.5, -1.0, 2.0), Vector3::new(1.0, 0.0, 1.0)], + /// vec![Vector3::new(0.0, 1.0, 1.0), Vector3::new(0.5, 1.0, 1.0), Vector3::new(1.0, 1.0, 1.0)], + /// vec![Vector3::new(0.0, 2.0, 1.0), Vector3::new(0.5, 2.0, 3.0), Vector3::new(1.0, 2.0, 1.0)], + /// vec![Vector3::new(0.0, 3.0, 1.0), Vector3::new(0.5, 3.5, 2.0), Vector3::new(1.0, 3.0, 1.0)], + /// ]; + /// let surface0 = NurbsSurface::new(BSplineSurface::new(knot_vecs, ctrl_pts)); + /// let mut surface1 = surface0.clone(); + /// assert!(surface0.near_as_surface(&surface1)); + /// + /// *surface1.control_point_mut(1, 1) = Vector3::new(0.5, 1.0, 0.9); + /// assert!(!surface0.near_as_surface(&surface1)); + /// ``` + #[inline(always)] + pub fn near_as_surface(&self, other: &Self) -> bool { + self.0 + .sub_near_as_surface(&other.0, 2, move |x, y| x.to_point().near(&y.to_point())) + } + /// Determines whether `self` and `other` is near in square order as the B-spline rational + /// surfaces or not. + /// + /// Divides each knot domain into the number of degree equal parts, + /// and check `|self(u, v) - other(u, v)| < TOLERANCE` for each end points `(u, v)`. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let eps = TOLERANCE; + /// let knot_vecs = (KnotVec::bezier_knot(3), KnotVec::bezier_knot(2)); + /// let ctrl_pts = vec![ + /// vec![Vector3::new(0.0, 0.0, 1.0), Vector3::new(0.5, -1.0, 2.0), Vector3::new(1.0, 0.0, 1.0)], + /// vec![Vector3::new(0.0, 1.0, 1.0), Vector3::new(0.5, 1.0, 1.0), Vector3::new(1.0, 1.0, 1.0)], + /// vec![Vector3::new(0.0, 2.0, 1.0), Vector3::new(0.5, 2.0, 3.0), Vector3::new(1.0, 2.0, 1.0)], + /// vec![Vector3::new(0.0, 3.0, 1.0), Vector3::new(0.5, 3.5, 2.0), Vector3::new(1.0, 3.0, 1.0)], + /// ]; + /// let surface0 = NurbsSurface::new(BSplineSurface::new(knot_vecs, ctrl_pts)); + /// let mut surface1 = surface0.clone(); + /// assert!(surface0.near_as_surface(&surface1)); + /// + /// *surface1.control_point_mut(1, 1) = Vector3::new(0.5, 1.0, 1.0 - eps); + /// assert!(surface0.near_as_surface(&surface1)); + /// assert!(!surface0.near2_as_surface(&surface1)); + /// ``` + #[inline(always)] + pub fn near2_as_surface(&self, other: &Self) -> bool { + self.0 + .sub_near_as_surface(&other.0, 2, move |x, y| x.to_point().near2(&y.to_point())) + } +} + +impl + ControlPoint + Tolerance> NurbsSurface { + /// Adds a knot `x` of the first parameter `u`, and do not change `self` as a surface. + #[inline(always)] + pub fn add_uknot(&mut self, x: f64) -> &mut Self { + self.0.add_uknot(x); + self + } + /// Adds a knot `x` of the first parameter `u`, and do not change `self` as a surface. + #[inline(always)] + pub fn add_vknot(&mut self, x: f64) -> &mut Self { + self.0.add_vknot(x); + self + } + /// Removes the uknot corresponding to the indice `idx`, and do not change `self` as a curve. + /// If the knot cannot be removed, returns [`Error::CannotRemoveKnot`]. + #[inline(always)] + pub fn try_remove_uknot(&mut self, idx: usize) -> Result<&mut Self> { + match self.0.try_remove_uknot(idx) { + Ok(_) => Ok(self), + Err(error) => Err(error), + } + } + /// Removes the uknot corresponding to the indices `idx`, and do not change `self` as a curve. + /// If cannot remove the knot, do not change `self` and return `self`. + #[inline(always)] + pub fn remove_uknot(&mut self, idx: usize) -> &mut Self { + self.0.remove_uknot(idx); + self + } + /// Removes the uknot corresponding to the indice `idx`, and do not change `self` as a curve. + /// If the knot cannot be removed, returns [`Error::CannotRemoveKnot`]. + #[inline(always)] + pub fn try_remove_vknot(&mut self, idx: usize) -> Result<&mut Self> { + match self.0.try_remove_vknot(idx) { + Ok(_) => Ok(self), + Err(error) => Err(error), + } + } + /// Removes the uknot corresponding to the indices `idx`, and do not change `self` as a curve. + /// If cannot remove the knot, do not change `self` and return `self`. + #[inline(always)] + pub fn remove_vknot(&mut self, idx: usize) -> &mut Self { + self.0.remove_vknot(idx); + self + } + /// Elevates the udegree. + #[inline(always)] + pub fn elevate_udegree(&mut self) -> &mut Self { + self.0.elevate_udegree(); + self + } + /// Elevates the vdegree. + #[inline(always)] + pub fn elevate_vdegree(&mut self) -> &mut Self { + self.0.elevate_vdegree(); + self + } + /// Aligns the udegree with the same degrees. + #[inline(always)] + pub fn syncro_uvdegrees(&mut self) -> &mut Self { + self.0.syncro_uvdegrees(); + self + } + /// Makes the uknot vector and the vknot vector the same knot vector. + #[inline(always)] + pub fn syncro_uvknots(&mut self) -> &mut Self { + self.0.syncro_uvknots(); + self + } + + /// Cuts the surface into two surfaces at the parameter `u` + #[inline(always)] + pub fn ucut(&mut self, u: f64) -> Self { Self::new(self.0.ucut(u)) } + + /// Cuts the surface into two surfaces at the parameter `v` + #[inline(always)] + pub fn vcut(&mut self, v: f64) -> Self { Self::new(self.0.vcut(v)) } + + /// Normalizes the knot vectors + #[inline(always)] + pub fn knot_normalize(&mut self) -> &mut Self { + self.0.knot_normalize(); + self + } + /// Translates the knot vectors. + #[inline(always)] + pub fn knot_translate(&mut self, x: f64, y: f64) -> &mut Self { + self.0.knot_translate(x, y); + self + } + + /// Removes knots in order from the back + #[inline(always)] + pub fn optimize(&mut self) -> &mut Self { + self.0.optimize(); + self + } + + /// Get the boundary by four splitted curves. + /// # Example + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vecs = (KnotVec::bezier_knot(3), KnotVec::bezier_knot(2)); + /// let ctrl_pts = vec![ + /// vec![Vector3::new(0.0, 0.0, 1.0), Vector3::new(0.5, -1.0, 2.0), Vector3::new(1.0, 0.0, 1.0)], + /// vec![Vector3::new(0.0, 1.0, 2.0), Vector3::new(0.5, 1.0, 3.0), Vector3::new(1.0, 1.0, 2.0)], + /// vec![Vector3::new(0.0, 2.0, 2.0), Vector3::new(0.5, 2.0, 3.0), Vector3::new(1.0, 2.0, 2.0)], + /// vec![Vector3::new(0.0, 3.0, 1.0), Vector3::new(0.5, 3.5, 2.0), Vector3::new(1.0, 3.0, 1.0)], + /// ]; + /// let bspsurface = NurbsSurface::new(BSplineSurface::new(knot_vecs, ctrl_pts)); + /// let curves = bspsurface.splitted_boundary(); + /// assert_eq!( + /// curves[0].control_points(), + /// &vec![ + /// Vector3::new(0.0, 0.0, 1.0), + /// Vector3::new(0.0, 1.0, 2.0), + /// Vector3::new(0.0, 2.0, 2.0), + /// Vector3::new(0.0, 3.0, 1.0), + /// ], + /// ); + /// assert_eq!( + /// curves[1].control_points(), + /// &vec![ + /// Vector3::new(0.0, 3.0, 1.0), + /// Vector3::new(0.5, 3.5, 2.0), + /// Vector3::new(1.0, 3.0, 1.0), + /// ], + /// ); + /// assert_eq!( + /// curves[2].control_points(), + /// &vec![ + /// Vector3::new(1.0, 3.0, 1.0), + /// Vector3::new(1.0, 2.0, 2.0), + /// Vector3::new(1.0, 1.0, 2.0), + /// Vector3::new(1.0, 0.0, 1.0), + /// ], + /// ); + /// assert_eq!( + /// curves[3].control_points(), + /// &vec![ + /// Vector3::new(1.0, 0.0, 1.0), + /// Vector3::new(0.5, -1.0, 2.0), + /// Vector3::new(0.0, 0.0, 1.0), + /// ], + /// ); + /// ``` + #[inline(always)] + pub fn splitted_boundary(&self) -> [NurbsCurve; 4] { + TryFrom::try_from( + self.0 + .splitted_boundary() + .iter() + .cloned() + .map(NurbsCurve::new) + .collect::>(), + ) + .unwrap() + } + + /// Extracts the boundary of surface + #[inline(always)] + pub fn boundary(&self) -> NurbsCurve { NurbsCurve::new(self.0.boundary()) } +} + +impl> SearchNearestParameter for NurbsSurface +where + Self: ParametricSurface::Diff>, + V::Point: EuclideanSpace + MetricSpace, + ::Diff: InnerSpace + Tolerance, +{ + type Point = V::Point; + /// Searches the parameter `(u, v)` which minimize `|self(u, v) - point|` by Newton's method + /// with initial guess `(u0, v0)`. If the repeated trial does not converge, then returns `None`. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vecs = (KnotVec::bezier_knot(3), KnotVec::bezier_knot(2)); + /// let ctrl_pts = vec![ + /// vec![Vector3::new(0.0, 0.0, 1.0), Vector3::new(1.0, -2.0, 2.0), Vector3::new(1.0, 0.0, 1.0)], + /// vec![Vector3::new(0.0, 2.0, 2.0), Vector3::new(2.0, 4.0, 4.0), Vector3::new(2.0, 2.0, 2.0)], + /// vec![Vector3::new(0.0, 4.0, 2.0), Vector3::new(2.0, 8.0, 4.0), Vector3::new(2.0, 4.0, 2.0)], + /// vec![Vector3::new(0.0, 3.0, 1.0), Vector3::new(1.0, 7.0, 2.0), Vector3::new(1.0, 3.0, 1.0)], + /// ]; + /// let surface = NurbsSurface::new(BSplineSurface::new(knot_vecs, ctrl_pts)); + /// let pt = surface.subs(0.3, 0.7); + /// let (u, v) = surface.search_nearest_parameter(pt, Some((0.5, 0.5)), 100).unwrap(); + /// assert!(u.near(&0.3) && v.near(&0.7)); + /// ``` + /// # Remarks + /// It may converge to a local solution depending on the hint. + /// cf. [`BSplineCurve::search_rational_nearest_parameter`](struct.BSplineCurve.html#method.search_rational_nearest_parameter) + #[inline(always)] + fn search_nearest_parameter>( + &self, + point: V::Point, + hint: H, + trials: usize, + ) -> Option<(f64, f64)> { + let hint = match hint.into() { + SPHint2D::Parameter(x, y) => (x, y), + SPHint2D::Range(range0, range1) => { + algo::surface::presearch(self, point, (range0, range1), PRESEARCH_DIVISION) + } + SPHint2D::None => { + algo::surface::presearch(self, point, self.range_tuple(), PRESEARCH_DIVISION) + } + }; + algo::surface::search_nearest_parameter(self, point, hint, trials) + } +} + +impl> NurbsSurface +where V::Point: Bounded +{ + /// Returns the bounding box including all control points. + #[inline(always)] + pub fn roughly_bounding_box(&self) -> BoundingBox { + self.0 + .control_points + .iter() + .flatten() + .map(|pt| pt.to_point()) + .collect() + } +} + +impl SearchParameter for NurbsSurface { + type Point = Point2; + /// Search the parameter `(u, v)` such that `self.subs(u, v).rational_projection()` is near `pt`. + /// If cannot find, then return `None`. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vec = KnotVec::uniform_knot(2, 2); + /// let ctrl_pts = vec![ + /// vec![Vector3::new(0.0, 0.0, 1.0), Vector3::new(0.1, 0.0, 0.5), Vector3::new(0.5, 0.0, 0.3), Vector3::new(1.0, 0.0, 1.0)], + /// vec![Vector3::new(0.0, 0.1, 0.1), Vector3::new(0.2, 0.2, 0.1), Vector3::new(0.4, 0.3, 0.4), Vector3::new(1.0, 0.3, 0.7)], + /// vec![Vector3::new(0.0, 0.5, 0.4), Vector3::new(0.3, 0.6, 0.5), Vector3::new(0.6, 0.4, 1.0), Vector3::new(1.0, 0.5, 0.4)], + /// vec![Vector3::new(0.0, 1.0, 1.0), Vector3::new(0.1, 1.0, 1.0), Vector3::new(0.5, 1.0, 0.5), Vector3::new(1.0, 1.0, 0.3)], + /// ]; + /// let bspsurface = BSplineSurface::new((knot_vec.clone(), knot_vec), ctrl_pts); + /// let surface = NurbsSurface::new(bspsurface); + /// + /// let pt = surface.subs(0.3, 0.7); + /// let (u, v) = surface.search_parameter(pt, Some((0.5, 0.5)), 100).unwrap(); + /// assert_near!(surface.subs(u, v), pt); + /// ``` + #[inline(always)] + fn search_parameter>( + &self, + point: Point2, + hint: H, + trials: usize, + ) -> Option<(f64, f64)> { + let hint = match hint.into() { + SPHint2D::Parameter(x, y) => (x, y), + SPHint2D::Range(range0, range1) => { + algo::surface::presearch(self, point, (range0, range1), PRESEARCH_DIVISION) + } + SPHint2D::None => { + algo::surface::presearch(self, point, self.range_tuple(), PRESEARCH_DIVISION) + } + }; + algo::surface::search_parameter2d(self, point, hint, trials) + } +} + +impl Invertible for NurbsSurface { + #[inline(always)] + fn invert(&mut self) { self.swap_axes(); } + #[inline(always)] + fn inverse(&self) -> Self { + let mut surface = self.clone(); + surface.swap_axes(); + surface + } +} + +impl + ControlPoint> ParametricSurface for NurbsSurface { + type Point = V::Point; + type Vector = ::Diff; + #[inline(always)] + fn subs(&self, u: f64, v: f64) -> Self::Point { self.subs(u, v) } + #[inline(always)] + fn uder(&self, u: f64, v: f64) -> Self::Vector { self.uder(u, v) } + #[inline(always)] + fn vder(&self, u: f64, v: f64) -> Self::Vector { self.vder(u, v) } + #[inline(always)] + fn uuder(&self, u: f64, v: f64) -> Self::Vector { self.uuder(u, v) } + #[inline(always)] + fn uvder(&self, u: f64, v: f64) -> Self::Vector { self.uvder(u, v) } + #[inline(always)] + fn vvder(&self, u: f64, v: f64) -> Self::Vector { self.vvder(u, v) } + #[inline(always)] + fn parameter_range(&self) -> (ParameterRange, ParameterRange) { self.parameter_range() } +} + +impl ParametricSurface3D for NurbsSurface { + #[inline(always)] + fn normal(&self, u: f64, v: f64) -> Vector3 { + let pt = self.0.subs(u, v); + let ud = self.0.uder(u, v); + let vd = self.0.vder(u, v); + pt.rat_der(ud).cross(pt.rat_der(vd)).normalize() + } +} + +impl + ControlPoint> ParameterDivision2D for NurbsSurface +where V::Point: MetricSpace + HashGen +{ + #[inline(always)] + fn parameter_division( + &self, + range: ((f64, f64), (f64, f64)), + tol: f64, + ) -> (Vec, Vec) { + algo::surface::parameter_division(self, range, tol) + } +} + +impl BoundedSurface for NurbsSurface where Self: ParametricSurface {} + +impl IncludeCurve> for NurbsSurface { + #[inline(always)] + fn include(&self, curve: &NurbsCurve) -> bool { + let pt = curve.subs(curve.knot_vec()[0]); + let mut hint = match self.search_parameter(pt, None, INCLUDE_CURVE_TRIALS) { + Some(got) => got, + None => return false, + }; + let uknot_vec = self.uknot_vec(); + let vknot_vec = self.vknot_vec(); + let degree = curve.degree() * 6; + let (knots, _) = curve.knot_vec().to_single_multi(); + for i in 1..knots.len() { + for j in 1..=degree { + let p = j as f64 / degree as f64; + let t = knots[i - 1] * (1.0 - p) + knots[i] * p; + let pt = curve.subs(t); + hint = match self.search_parameter(pt, Some(hint), INCLUDE_CURVE_TRIALS) { + Some(got) => got, + None => return false, + }; + if !self.subs(hint.0, hint.1).near(&pt) + || hint.0 < uknot_vec[0] - TOLERANCE + || hint.0 - uknot_vec[0] > uknot_vec.range_length() + TOLERANCE + || hint.1 < vknot_vec[0] - TOLERANCE + || hint.1 - vknot_vec[0] > vknot_vec.range_length() + TOLERANCE + { + return false; + } + } + } + true + } +} + +impl IncludeCurve> for NurbsSurface { + #[inline(always)] + fn include(&self, curve: &BSplineCurve) -> bool { + let pt = curve.front(); + let mut hint = match self.search_parameter(pt, None, INCLUDE_CURVE_TRIALS) { + Some(got) => got, + None => return false, + }; + let uknot_vec = self.uknot_vec(); + let vknot_vec = self.vknot_vec(); + let degree = curve.degree() * 6; + let (knots, _) = curve.knot_vec().to_single_multi(); + for i in 1..knots.len() { + for j in 1..=degree { + let p = j as f64 / degree as f64; + let t = knots[i - 1] * (1.0 - p) + knots[i] * p; + let pt = curve.subs(t); + hint = match self.search_parameter(pt, Some(hint), INCLUDE_CURVE_TRIALS) { + Some(got) => got, + None => return false, + }; + if !self.subs(hint.0, hint.1).near(&pt) + || hint.0 < uknot_vec[0] - TOLERANCE + || hint.0 - uknot_vec[0] > uknot_vec.range_length() + TOLERANCE + || hint.1 < vknot_vec[0] - TOLERANCE + || hint.1 - vknot_vec[0] > vknot_vec.range_length() + TOLERANCE + { + return false; + } + } + } + true + } +} + +impl IncludeCurve> for NurbsSurface { + #[inline(always)] + fn include(&self, curve: &NurbsCurve) -> bool { + let pt = curve.front(); + let mut hint = match self.search_parameter(pt, None, INCLUDE_CURVE_TRIALS) { + Some(got) => got, + None => return false, + }; + let uknot_vec = self.uknot_vec(); + let vknot_vec = self.vknot_vec(); + let degree = curve.degree() * 6; + let (knots, _) = curve.knot_vec().to_single_multi(); + for i in 1..knots.len() { + for j in 1..=degree { + let p = j as f64 / degree as f64; + let t = knots[i - 1] * (1.0 - p) + knots[i] * p; + let pt = curve.subs(t); + hint = match self.search_parameter(pt, Some(hint), INCLUDE_CURVE_TRIALS) { + Some(got) => got, + None => return false, + }; + if !self.subs(hint.0, hint.1).near(&pt) + || hint.0 < uknot_vec[0] - TOLERANCE + || hint.0 - uknot_vec[0] > uknot_vec.range_length() + TOLERANCE + || hint.1 < vknot_vec[0] - TOLERANCE + || hint.1 - vknot_vec[0] > vknot_vec.range_length() + TOLERANCE + { + return false; + } + } + } + true + } +} + +impl Transformed for NurbsSurface +where M: Copy + std::ops::Mul +{ + #[inline(always)] + fn transform_by(&mut self, trans: M) { + self.0 + .control_points + .iter_mut() + .flatten() + .for_each(move |v| *v = trans * *v) + } +} + +impl SearchParameter for NurbsSurface { + type Point = Point3; + /// Search the parameter `(u, v)` such that `self.subs(u, v).rational_projection()` is near `pt`. + /// If cannot find, then return `None`. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let knot_vec = KnotVec::uniform_knot(2, 2); + /// let ctrl_pts = vec![ + /// vec![Vector4::new(0.0, 0.0, 0.0, 1.0), Vector4::new(0.1, 0.0, 0.5, 0.4), Vector4::new(1.0, 0.0, 0.6, 2.0), Vector4::new(0.4, 0.0, 0.4, 0.4)], + /// vec![Vector4::new(0.0, 0.2, 0.2, 2.0), Vector4::new(0.24, 0.24, 0.1, 1.2), Vector4::new(2.4, 1.8, 2.4, 0.6), Vector4::new(1.4, 0.42, 0.98, 1.4)], + /// vec![Vector4::new(0.0, 1.5, 1.2, 3.0), Vector4::new(1.02, 2.04, 1.7, 3.4), Vector4::new(0.42, 0.28, 0.7, 0.7), Vector4::new(0.6, 0.3, 0.0, 0.6)], + /// vec![Vector4::new(0.0, 1.0, 1.0, 1.0), Vector4::new(0.2, 2.0, 2.0, 2.0), Vector4::new(0.85, 1.7, 0.85, 1.7), Vector4::new(1.0, 1.0, 0.3, 1.0)], + /// ]; + /// let bspsurface = BSplineSurface::new((knot_vec.clone(), knot_vec), ctrl_pts); + /// let surface = NurbsSurface::new(bspsurface); + /// + /// let pt = surface.subs(0.3, 0.7); + /// let (u, v) = surface.search_parameter(pt, Some((0.5, 0.5)), 100).unwrap(); + /// assert_near!(surface.subs(u, v), pt); + /// ``` + fn search_parameter>( + &self, + point: Point3, + hint: H, + trials: usize, + ) -> Option<(f64, f64)> { + let hint = match hint.into() { + SPHint2D::Parameter(x, y) => (x, y), + SPHint2D::Range(range0, range1) => { + algo::surface::presearch(self, point, (range0, range1), PRESEARCH_DIVISION) + } + SPHint2D::None => { + algo::surface::presearch(self, point, self.range_tuple(), PRESEARCH_DIVISION) + } + }; + algo::surface::search_parameter3d(self, point, hint, trials) + } +} + +#[test] +fn test_include2d() { + let knot_vec = KnotVec::uniform_knot(2, 3); + let ctrl_pts = vec![ + vec![ + Vector3::new(0.0, 0.0, 1.0), + Vector3::new(0.05, 0.0, 0.5), + Vector3::new(0.15, 0.0, 0.3), + Vector3::new(1.0, 0.0, 1.0), + ], + vec![ + Vector3::new(0.0, 0.01, 0.1), + Vector3::new(0.02, 0.02, 0.1), + Vector3::new(0.16, 0.12, 0.4), + Vector3::new(0.7, 0.21, 0.7), + ], + vec![ + Vector3::new(0.0, 0.02, 0.4), + Vector3::new(0.15, 0.3, 0.5), + Vector3::new(0.6, 0.4, 1.0), + Vector3::new(0.4, 0.2, 0.4), + ], + vec![ + Vector3::new(0.0, 1.0, 1.0), + Vector3::new(0.1, 1.0, 1.0), + Vector3::new(0.25, 0.5, 0.5), + Vector3::new(0.3, 0.3, 0.3), + ], + ]; + let surface = BSplineSurface::new((knot_vec.clone(), knot_vec), ctrl_pts); + let bnd_box = BoundingBox::from_iter(&[Vector2::new(0.2, 0.3), Vector2::new(0.8, 0.6)]); + let mut curve = surface.sectional_curve(bnd_box); + curve.control_points_mut().for_each(|pt| *pt *= 3.0); + let surface = NurbsSurface::new(surface); + let curve = NurbsCurve::new(curve); + assert!(surface.include(&curve)); +} + +#[test] +fn test_include3d() { + let knot_vec = KnotVec::bezier_knot(2); + let ctrl_pts = vec![ + vec![ + Vector4::new(-1.0, -1.0, 2.0, 1.0), + Vector4::new(-1.0, 0.0, 0.0, 1.0), + Vector4::new(-1.0, 1.0, 2.0, 1.0), + ], + vec![ + Vector4::new(0.0, -1.0, 0.0, 1.0), + Vector4::new(0.0, 0.0, -2.0, 1.0), + Vector4::new(0.0, 1.0, 0.0, 1.0), + ], + vec![ + Vector4::new(1.0, -1.0, 2.0, 1.0), + Vector4::new(1.0, 0.0, 0.0, 1.0), + Vector4::new(1.0, 1.0, 2.0, 1.0), + ], + ]; + let surface = NurbsSurface::new(BSplineSurface::new((knot_vec.clone(), knot_vec), ctrl_pts)); + + let knot_vec = KnotVec::from(vec![ + 0.0, 0.0, 0.0, 0.25, 0.25, 0.5, 0.5, 0.75, 0.75, 1.0, 1.0, 1.0, + ]); + let ctrl_pts = vec![ + // the vector of the indices of control points + Vector4::new(0.0, -2.0, 2.0, 2.0), + Vector4::new(1.0, -1.0, 1.0, 1.0), + Vector4::new(1.0, 0.0, 1.0, 1.0), + Vector4::new(1.0, 1.0, 1.0, 1.0), + Vector4::new(0.0, 2.0, 2.0, 2.0), + Vector4::new(-1.0, 1.0, 1.0, 1.0), + Vector4::new(-1.0, 0.0, 1.0, 1.0), + Vector4::new(-1.0, -1.0, 1.0, 1.0), + Vector4::new(0.0, -2.0, 2.0, 2.0), + ]; + let mut curve = NurbsCurve::new(BSplineCurve::new(knot_vec, ctrl_pts)); + assert!(surface.include(&curve)); + *curve.control_point_mut(1) += Vector4::new(0.0, 0.0, 0.00001, 0.0); + assert!(!surface.include(&curve)); +} diff --git a/vendor/truck-geometry/src/specifieds/circle.rs b/vendor/truck-geometry/src/specifieds/circle.rs new file mode 100644 index 000000000..876be2f5c --- /dev/null +++ b/vendor/truck-geometry/src/specifieds/circle.rs @@ -0,0 +1,161 @@ +use super::*; +use std::f64::consts::PI; + +impl

UnitCircle

{ + /// constructor + #[inline] + pub const fn new() -> Self { Self(std::marker::PhantomData) } +} + +impl ParametricCurve for UnitCircle { + type Point = Point2; + type Vector = Vector2; + #[inline] + fn subs(&self, t: f64) -> Self::Point { Point2::new(f64::cos(t), f64::sin(t)) } + #[inline] + fn der(&self, t: f64) -> Self::Vector { Vector2::new(-f64::sin(t), f64::cos(t)) } + #[inline] + fn der2(&self, t: f64) -> Self::Vector { Vector2::new(-f64::cos(t), -f64::sin(t)) } + #[inline] + fn parameter_range(&self) -> ParameterRange { + (Bound::Included(0.0), Bound::Excluded(2.0 * PI)) + } +} + +impl BoundedCurve for UnitCircle {} + +impl ParametricCurve for UnitCircle { + type Point = Point3; + type Vector = Vector3; + #[inline] + fn subs(&self, t: f64) -> Self::Point { Point3::new(f64::cos(t), f64::sin(t), 0.0) } + #[inline] + fn der(&self, t: f64) -> Self::Vector { Vector3::new(-f64::sin(t), f64::cos(t), 0.0) } + #[inline] + fn der2(&self, t: f64) -> Self::Vector { Vector3::new(-f64::cos(t), -f64::sin(t), 0.0) } + #[inline] + fn period(&self) -> Option { Some(2.0 * PI) } + #[inline] + fn parameter_range(&self) -> ParameterRange { + (Bound::Included(0.0), Bound::Excluded(2.0 * PI)) + } +} + +impl BoundedCurve for UnitCircle {} + +impl

ParameterDivision1D for UnitCircle

+where UnitCircle

: ParametricCurve +{ + type Point = P; + fn parameter_division(&self, range: (f64, f64), tol: f64) -> (Vec, Vec

) { + nonpositive_tolerance!(tol); + let tol = f64::min(tol, 0.8); + let delta = 2.0 * f64::acos(1.0 - tol); + let n = 1 + ((range.1 - range.0) / delta) as usize; + let params = (0..=n) + .map(|i| { + let t = i as f64 / n as f64; + range.0 * (1.0 - t) + range.1 * t + }) + .collect::>(); + let pts = params.iter().map(|t| self.subs(*t)).collect(); + (params, pts) + } +} + +impl SearchNearestParameter for UnitCircle { + type Point = Point2; + fn search_nearest_parameter>( + &self, + pt: Point2, + _: H, + _: usize, + ) -> Option { + let v = pt.to_vec(); + if v.magnitude().so_small() { + return None; + } + let v = v.normalize(); + let theta = f64::acos(f64::clamp(v.x, -1.0, 1.0)); + let theta = match v.y > 0.0 { + true => theta, + false => 2.0 * PI - theta, + }; + Some(theta) + } +} + +#[test] +fn search_nearest_parameter() { + const N: usize = 100; + let circle = UnitCircle::::new(); + for i in 0..N { + let t = 2.0 * PI * i as f64 / N as f64; + let a = 5.0 * rand::random::() + 0.1; + let p = a * circle.subs(t); + let s = circle.search_nearest_parameter(p, None, 1).unwrap(); + let q = a * circle.subs(s); + assert_near!(p, q); + } +} + +impl SearchParameter for UnitCircle { + type Point = Point2; + fn search_parameter>(&self, pt: Point2, _: H, _: usize) -> Option { + let v = pt.to_vec(); + if !v.magnitude().near(&1.0) { + return None; + } + let v = v.normalize(); + let theta = f64::acos(f64::clamp(v.x, -1.0, 1.0)); + let theta = match v.y > 0.0 { + true => theta, + false => 2.0 * PI - theta, + }; + Some(theta) + } +} + +#[test] +fn search_parameter() { + const N: usize = 100; + let circle = UnitCircle::::new(); + for i in 1..N { + let t = 2.0 * PI * i as f64 / N as f64; + let p = circle.subs(t); + let s = circle.search_parameter(p, None, 1).unwrap(); + assert_near!(s, t); + } +} + +impl SearchNearestParameter for UnitCircle { + type Point = Point3; + fn search_nearest_parameter>( + &self, + pt: Point3, + _: H, + _: usize, + ) -> Option { + UnitCircle::::new().search_nearest_parameter(Point2::new(pt.x, pt.y), None, 0) + } +} + +impl SearchParameter for UnitCircle { + type Point = Point3; + fn search_parameter>(&self, pt: Point3, _: H, _: usize) -> Option { + if !f64::abs(pt.z).so_small() { + return None; + } + UnitCircle::::new().search_parameter(Point2::new(pt.x, pt.y), None, 0) + } +} + +#[test] +fn parameter_division() { + let c = UnitCircle::::new(); + let (_div, pts) = c.parameter_division(c.range_tuple(), 0.05); + for a in pts.windows(2) { + let p = a[0].midpoint(a[1]); + assert!(p.to_vec().magnitude() > 0.95); + } +} diff --git a/vendor/truck-geometry/src/specifieds/hyperbola.rs b/vendor/truck-geometry/src/specifieds/hyperbola.rs new file mode 100644 index 000000000..a0c30bf8d --- /dev/null +++ b/vendor/truck-geometry/src/specifieds/hyperbola.rs @@ -0,0 +1,125 @@ +use super::*; + +impl

UnitHyperbola

{ + /// constructor + #[inline] + pub const fn new() -> UnitHyperbola

{ UnitHyperbola(std::marker::PhantomData) } +} + +impl ParametricCurve for UnitHyperbola { + type Point = Point2; + type Vector = Vector2; + #[inline] + fn subs(&self, t: f64) -> Self::Point { Point2::new(f64::cosh(t), f64::sinh(t)) } + #[inline] + fn der(&self, t: f64) -> Self::Vector { Vector2::new(f64::sinh(t), f64::cosh(t)) } + #[inline] + fn der2(&self, t: f64) -> Self::Vector { Vector2::new(f64::cosh(t), f64::sinh(t)) } +} + +impl ParametricCurve for UnitHyperbola { + type Point = Point3; + type Vector = Vector3; + #[inline] + fn subs(&self, t: f64) -> Self::Point { Point3::new(f64::cosh(t), f64::sinh(t), 0.0) } + #[inline] + fn der(&self, t: f64) -> Self::Vector { Vector3::new(f64::sinh(t), f64::cosh(t), 0.0) } + #[inline] + fn der2(&self, t: f64) -> Self::Vector { Vector3::new(f64::cosh(t), f64::sinh(t), 0.0) } +} + +impl

ParameterDivision1D for UnitHyperbola

+where + UnitHyperbola

: ParametricCurve, + P: EuclideanSpace + MetricSpace + HashGen, +{ + type Point = P; + fn parameter_division(&self, range: (f64, f64), tol: f64) -> (Vec, Vec

) { + algo::curve::parameter_division(self, range, tol) + } +} + +impl SearchNearestParameter for UnitHyperbola { + type Point = Point2; + fn search_nearest_parameter>( + &self, + p: Point2, + _: H, + _: usize, + ) -> Option { + let a = -p.y; + let b = (p.y * p.y - p.x * p.x) / 4.0 + 1.0; + let c = -p.y; + let d = p.y * p.y / 4.0; + let y = solver::solve_quartic(a, b, c, d) + .into_iter() + .filter_map(|z| match z.im.so_small() { + true => Some(z.re), + false => None, + }) + .min_by(|s, t| { + p.distance2(self.subs(*s)) + .partial_cmp(&p.distance2(self.subs(*t))) + .unwrap() + })?; + Some(f64::asinh(y)) + } +} + +impl SearchNearestParameter for UnitHyperbola { + type Point = Point3; + fn search_nearest_parameter>( + &self, + p: Point3, + _: H, + _trials: usize, + ) -> Option { + UnitHyperbola::::new().search_nearest_parameter( + Point2::new(p.x, p.y), + None, + _trials, + ) + } +} + +impl SearchParameter for UnitHyperbola { + type Point = Point2; + fn search_parameter>(&self, p: Point2, _: H, _: usize) -> Option { + let t = f64::asinh(p.y); + match p.near(&self.subs(t)) { + true => Some(t), + false => None, + } + } +} + +impl SearchParameter for UnitHyperbola { + type Point = Point3; + fn search_parameter>(&self, p: Point3, _: H, _: usize) -> Option { + let t = f64::asinh(p.y); + match p.near(&self.subs(t)) { + true => Some(t), + false => None, + } + } +} + +#[test] +fn snp_test() { + let curve = UnitHyperbola::::new(); + let p = curve.subs(2.0); + let q = p + Vector2::new(-p.x, p.y); + let t = curve.search_nearest_parameter(q, None, 0).unwrap(); + assert_near!(t, 2.0); +} + +#[test] +fn sp_test() { + let curve = UnitHyperbola::::new(); + let t = 100.0 * rand::random::() - 50.0; + let p = curve.subs(t); + assert_near!(curve.search_parameter(p, None, 0).unwrap(), t); + + let q = Point2::new(-1.0, 0.0); + assert!(curve.search_parameter(q, None, 0).is_none()); +} diff --git a/vendor/truck-geometry/src/specifieds/line.rs b/vendor/truck-geometry/src/specifieds/line.rs new file mode 100644 index 000000000..22b7afda0 --- /dev/null +++ b/vendor/truck-geometry/src/specifieds/line.rs @@ -0,0 +1,217 @@ +use super::*; +use truck_base::cgmath64::control_point::ControlPoint; + +impl Line

{ + /// initialize line from vector + #[inline] + pub fn from_origin_direction(origin: P, direction: V) -> Self + where P: std::ops::Add { + Self(origin, origin + direction) + } + /// to a bspline curve + #[inline] + pub fn to_bspline(self) -> BSplineCurve

{ + BSplineCurve::new(KnotVec::bezier_knot(1), vec![self.0, self.1]) + } +} + +impl

Line

+where + P: EuclideanSpace, + P::Diff: InnerSpace, +{ + /// Returns the projected point to the line. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let line = Line(Point2::new(0.0, 0.0), Point2::new(1.0, 2.0)); + /// let pt = Point2::new(0.0, 1.0); + /// assert_near!(line.projection(pt), Point2::new(0.4, 0.8)); + /// ``` + pub fn projection(self, point: P) -> P { + let (u, v) = (point - self.0, self.1 - self.0); + self.0 + v * u.dot(v) / v.dot(v) + } + /// Returns the distance between the line and the point `point`. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let line = Line(Point2::new(0.0, 0.0), Point2::new(3.0, 4.0)); + /// + /// // The foot of the perpendicular line is on a line segment + /// let pt = Point2::new(3.0, 0.0); + /// assert_near!(line.distance_to_point(pt), 2.4); + /// + /// // The foot of the perpendicular line is not on a line segment + /// let pt = Point2::new(0.0, -4.0); + /// assert_near!(line.distance_to_point(pt), 2.4); + /// ``` + pub fn distance_to_point(self, point: P) -> f64 { + let (u, v) = (point - self.0, self.1 - self.0); + (u - v * u.dot(v) / v.dot(v)).magnitude() + } + /// Returns the distance between the sengment and the point `point`. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let line = Line(Point2::new(0.0, 0.0), Point2::new(3.0, 4.0)); + /// + /// // The foot of the perpendicular line is on a line segment + /// let pt = Point2::new(3.0, 0.0); + /// assert_near!(line.distance_to_point_as_segment(pt), 2.4); + /// + /// // The foot of the perpendicular line is not on a line segment + /// let pt = Point2::new(0.0, -4.0); + /// assert_near!(line.distance_to_point_as_segment(pt), 4.0); + /// ``` + pub fn distance_to_point_as_segment(self, point: P) -> f64 { + let (u, v) = (point - self.0, self.1 - self.0); + let t = f64::clamp(u.dot(v) / v.dot(v), 0.0, 1.0); + (u - v * t).magnitude() + } +} + +impl Line { + /// Returns the intersection of two lines and its parameters. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let line0 = Line(Point2::new(0.0, 0.0), Point2::new(9.0, 3.0)); + /// let line1 = Line(Point2::new(0.0, 6.0), Point2::new(9.0, 0.0)); + /// let (s, t, p) = line0.intersection(line1).unwrap(); + /// assert_near!(line0.subs(s), Point2::new(6.0, 2.0)); + /// assert_near!(line1.subs(t), Point2::new(6.0, 2.0)); + /// assert_near!(p, Point2::new(6.0, 2.0)); + /// ``` + /// # Failures + /// Returns `None` if two lines are parallel. + /// ``` + /// use truck_geometry::prelude::*; + /// let line0 = Line(Point2::new(0.0, 0.0), Point2::new(9.0, 3.0)); + /// let line1 = Line(Point2::new(-1.0, 0.0), Point2::new(8.0, 3.0)); + /// assert!(line0.intersection(line1).is_none()); + /// ``` + pub fn intersection(self, other: Line) -> Option<(f64, f64, Point2)> { + let mat = Matrix2::from_cols(self.1 - self.0, other.0 - other.1); + let v = other.0 - self.0; + let params = mat.invert().map(|inv| inv * v)?; + Some((params.x, params.y, self.subs(params.x))) + } +} + +impl> ParametricCurve for Line

{ + type Point = P; + type Vector = P::Diff; + #[inline] + fn subs(&self, t: f64) -> Self::Point { self.0 + (self.1 - self.0) * t } + #[inline] + fn der(&self, _: f64) -> Self::Vector { self.1 - self.0 } + #[inline] + fn der2(&self, _: f64) -> Self::Vector { Self::Vector::zero() } + /// Return `0.0..=1.0` i.e. we regard it as a segment + #[inline] + fn parameter_range(&self) -> ParameterRange { (Bound::Included(0.0), Bound::Included(1.0)) } +} + +impl> BoundedCurve for Line

{} + +impl> Cut for Line

{ + #[inline] + fn cut(&mut self, t: f64) -> Self { + let r = self.subs(t); + let res = Self(r, self.1); + self.1 = r; + res + } +} + +impl> ParameterDivision1D for Line

{ + type Point = P; + #[inline] + fn parameter_division(&self, range: (f64, f64), _: f64) -> (Vec, Vec

) { + ( + vec![range.0, range.1], + vec![self.subs(range.0), self.subs(range.1)], + ) + } +} + +impl Invertible for Line

{ + #[inline] + fn invert(&mut self) { *self = Self(self.1, self.0); } + #[inline] + fn inverse(&self) -> Self { Self(self.1, self.0) } +} + +impl

SearchNearestParameter for Line

+where + P: ControlPoint, + P::Diff: InnerSpace, +{ + type Point = P; + #[inline] + fn search_nearest_parameter>(&self, pt: P, _: H, _: usize) -> Option { + let b = self.1 - self.0; + Some((pt - self.0).dot(b) / b.dot(b)) + } +} + +impl

SearchParameter for Line

+where + P: ControlPoint + Tolerance, + P::Diff: InnerSpace, +{ + type Point = P; + #[inline] + fn search_parameter>(&self, pt: P, _: H, _: usize) -> Option { + let b = self.1 - self.0; + let t = (pt - self.0).dot(b) / b.dot(b); + match self.subs(t).near(&pt) { + true => Some(t), + false => None, + } + } +} + +impl> Transformed for Line

{ + #[inline] + fn transform_by(&mut self, trans: M) { + self.0 = trans.transform_point(self.0); + self.1 = trans.transform_point(self.1); + } + #[inline] + fn transformed(&self, trans: M) -> Self { + Line(trans.transform_point(self.0), trans.transform_point(self.1)) + } +} + +#[test] +fn line() { + let line = Line(Point2::new(1.0, 0.0), Point2::new(0.0, 1.0)); + + // subs + assert_near!(line.subs(0.4), Point2::new(0.6, 0.4)); + + // inverse + let line_inverse = line.inverse(); + assert_eq!(line.0, line_inverse.1); + assert_eq!(line.1, line_inverse.0); + + // cut + let mut line0 = line; + let line1 = line0.cut(0.4); + assert_eq!(line.0, line0.0); + assert_near!(line0.1, line.subs(0.4)); + assert_eq!(line0.1, line1.0); + assert_eq!(line1.1, line.1); + + // SNP + assert_near!( + line.search_nearest_parameter(Point2::new(1.0, 1.0), None, 0) + .unwrap(), + 0.5 + ); + assert!(line + .search_parameter(Point2::new(1.0, 1.0), None, 0) + .is_none()); +} diff --git a/vendor/truck-geometry/src/specifieds/mod.rs b/vendor/truck-geometry/src/specifieds/mod.rs new file mode 100644 index 000000000..fc7c24a14 --- /dev/null +++ b/vendor/truck-geometry/src/specifieds/mod.rs @@ -0,0 +1,115 @@ +use crate::{prelude::*, *}; + +/// line +/// # Example +/// ``` +/// use truck_geometry::prelude::*; +/// let line = Line(Point2::new(0.0, 0.0), Point2::new(1.0, 1.0)); +/// assert_near!(line.subs(0.5), Point2::new(0.5, 0.5)); +/// ``` +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Line

(pub P, pub P); + +/// unit circle +#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize)] +pub struct UnitCircle

(std::marker::PhantomData

); + +/// unit hyperbola +#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize)] +pub struct UnitHyperbola

(std::marker::PhantomData

); + +/// parabola whose apex is the origin. +#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize)] +pub struct UnitParabola

(std::marker::PhantomData

); + +/// plane +/// # Example +/// ``` +/// use truck_geometry::prelude::*; +/// +/// // arbitrary three points +/// let pt0 = Point3::new(0.0, 1.0, 2.0); +/// let pt1 = Point3::new(1.0, 1.0, 3.0); +/// let pt2 = Point3::new(0.0, 2.0, 3.0); +/// +/// // Creates a plane +/// let plane: Plane = Plane::new(pt0, pt1, pt2); +/// // The origin of the plane is pt0. +/// assert_near!(plane.origin(), pt0); +/// // The u-axis of the plane is the vector from pt0 to pt1. +/// assert_near!(plane.u_axis(), pt1 - pt0); +/// // The v-axis of the plane is the vector from pt0 to pt2. +/// assert_near!(plane.v_axis(), pt2 - pt0); +/// // The normal is the normalized u-axis × v-axis +/// assert_near!(plane.normal(), (pt1 - pt0).cross(pt2 - pt0).normalize()); +/// ``` +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct Plane { + o: Point3, + p: Point3, + q: Point3, +} + +/// sphere +/// # Examples +/// ``` +/// use truck_geometry::prelude::*; +/// use std::f64::consts::PI; +/// +/// let center = Point3::new(1.0, 2.0, 3.0); +/// let radius = 4.56; +/// +/// let sphere = Sphere::new(center, radius); +/// const N: usize = 100; +/// for i in 0..=N { +/// for j in 0..=N { +/// // the parameter u is latitude +/// let u = PI * i as f64 / N as f64; +/// // the parameter v is longitude +/// let v = 2.0 * PI * j as f64 / N as f64; +/// +/// // simple relation between a point and its normal. +/// let pt = sphere.subs(u, v); +/// let n = sphere.normal(u, v); +/// assert_near!(pt - center, n * radius); +/// +/// // the proof of u is latitude and v is longitude +/// assert!((PI / 2.0 - u) * (pt.z - center.z) >= 0.0); +/// assert!((PI - v) * (pt.y - center.y) >= 0.0); +/// } +/// } +/// ``` +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct Sphere { + center: Point3, + radius: f64, +} + +/// torus +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct Torus { + center: Point3, + large_radius: f64, + small_radius: f64, +} + +mod circle; +mod hyperbola; +mod line; +mod parabola; +mod plane; +mod sphere; +mod torus; + +macro_rules! always_true { + ($ty: tt) => { + impl

PartialEq for $ty

{ + fn eq(&self, _: &Self) -> bool { true } + } + impl

Eq for $ty

{} + }; +} + +always_true!(UnitCircle); +always_true!(UnitParabola); +always_true!(UnitHyperbola); diff --git a/vendor/truck-geometry/src/specifieds/parabola.rs b/vendor/truck-geometry/src/specifieds/parabola.rs new file mode 100644 index 000000000..58b57f8de --- /dev/null +++ b/vendor/truck-geometry/src/specifieds/parabola.rs @@ -0,0 +1,137 @@ +use super::*; + +impl

UnitParabola

{ + /// constructor + #[inline] + pub const fn new() -> Self { Self(std::marker::PhantomData) } +} + +impl ParametricCurve for UnitParabola { + type Point = Point2; + type Vector = Vector2; + #[inline] + fn subs(&self, t: f64) -> Self::Point { Point2::new(t * t, 2.0 * t) } + #[inline] + fn der(&self, t: f64) -> Self::Vector { Vector2::new(2.0 * t, 2.0) } + #[inline] + fn der2(&self, _: f64) -> Self::Vector { Vector2::new(2.0, 0.0) } +} + +impl ParametricCurve for UnitParabola { + type Point = Point3; + type Vector = Vector3; + #[inline] + fn subs(&self, t: f64) -> Self::Point { Point3::new(t * t, 2.0 * t, 0.0) } + #[inline] + fn der(&self, t: f64) -> Self::Vector { Vector3::new(2.0 * t, 2.0, 0.0) } + #[inline] + fn der2(&self, _: f64) -> Self::Vector { Vector3::new(2.0, 0.0, 0.0) } +} + +impl

ParameterDivision1D for UnitParabola

+where + UnitParabola

: ParametricCurve, + P: EuclideanSpace + MetricSpace + HashGen, +{ + type Point = P; + fn parameter_division(&self, range: (f64, f64), tol: f64) -> (Vec, Vec

) { + algo::curve::parameter_division(self, range, tol) + } +} + +impl SearchNearestParameter for UnitParabola { + type Point = Point2; + #[inline] + fn search_nearest_parameter>( + &self, + pt: Point2, + _: H, + _: usize, + ) -> Option { + let p = 2.0 - pt.x; + let q = -pt.y; + solver::pre_solve_cubic(p, q) + .into_iter() + .filter_map(|x| match x.im.so_small() { + true => Some(x.re), + false => None, + }) + .min_by(|s, t| { + pt.distance2(self.subs(*s)) + .partial_cmp(&pt.distance2(self.subs(*t))) + .unwrap() + }) + } +} + +impl SearchNearestParameter for UnitParabola { + type Point = Point3; + #[inline] + fn search_nearest_parameter>( + &self, + pt: Point3, + _hint: H, + _trials: usize, + ) -> Option { + UnitParabola::::new().search_nearest_parameter( + Point2::new(pt.x, pt.y), + _hint, + _trials, + ) + } +} + +impl SearchParameter for UnitParabola { + type Point = Point2; + #[inline] + fn search_parameter>(&self, pt: Point2, _: H, _: usize) -> Option { + let t = pt.y / 2.0; + let pt0 = self.subs(t); + match pt.near(&pt0) { + true => Some(t), + false => None, + } + } +} + +impl SearchParameter for UnitParabola { + type Point = Point3; + #[inline] + fn search_parameter>( + &self, + pt: Point3, + _hint: H, + _trials: usize, + ) -> Option { + match pt.z.so_small() { + true => UnitParabola::::new().search_parameter( + Point2::new(pt.x, pt.y), + _hint, + _trials, + ), + false => None, + } + } +} + +#[test] +fn snp_test() { + let curve = UnitParabola::::new(); + + let p = Point2::new(-3.0, 0.0); + assert_near!(curve.search_nearest_parameter(p, None, 0).unwrap(), 0.0); + let p = Point2::new(-3.0, 6.0); + assert_near!(curve.search_nearest_parameter(p, None, 0).unwrap(), 1.0); + let p = Point2::new(1.5, 1.5); + assert_near!(curve.search_nearest_parameter(p, None, 0).unwrap(), 1.0); +} + +#[test] +fn sp_test() { + let curve = UnitParabola::::new(); + + let p = Point2::new(4.0, -4.0); + assert_near!(curve.search_parameter(p, None, 0).unwrap(), -2.0); + let p = Point2::new(-3.0, 6.0); + assert!(curve.search_parameter(p, None, 0).is_none()); +} diff --git a/vendor/truck-geometry/src/specifieds/plane.rs b/vendor/truck-geometry/src/specifieds/plane.rs new file mode 100644 index 000000000..c5ffebdcd --- /dev/null +++ b/vendor/truck-geometry/src/specifieds/plane.rs @@ -0,0 +1,256 @@ +use super::*; + +impl Plane { + /// Creates a new plane from three points. + #[inline(always)] + pub const fn new(origin: Point3, one: Point3, another: Point3) -> Plane { + Plane { + o: origin, + p: one, + q: another, + } + } + /// Returns the origin + #[inline(always)] + pub const fn origin(&self) -> Point3 { self.o } + /// Returns the u-axis + #[inline(always)] + pub fn u_axis(&self) -> Vector3 { self.p - self.o } + /// Returns the v-axis + #[inline(always)] + pub fn v_axis(&self) -> Vector3 { self.q - self.o } + /// Returns the normal + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let plane = Plane::new( + /// Point3::new(0.0, 0.0, 0.0), + /// Point3::new(1.0, 0.0, 0.0), + /// Point3::new(0.0, 1.0, 0.0), + /// ); + /// assert_near!(plane.normal(), Vector3::unit_z()); + /// ``` + #[inline(always)] + pub fn normal(&self) -> Vector3 { self.u_axis().cross(self.v_axis()).normalize() } + /// Gets the parameter of `pt` in plane's matrix. + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let plane = Plane::new( + /// Point3::new(1.0, 2.0, 3.0), + /// Point3::new(2.0, 1.0, 3.0), + /// Point3::new(3.0, 4.0, -1.0), + /// ); + /// + /// let pt = Point3::new(2.1, -6.5, 4.7); + /// let prm = plane.get_parameter(pt); + /// let rev = plane.origin() + /// + prm[0] * plane.u_axis() + /// + prm[1] * plane.v_axis() + /// + prm[2] * plane.normal(); + /// assert_near!(pt, rev); + /// ``` + #[inline(always)] + pub fn get_parameter(&self, pt: Point3) -> Vector3 { + let a = self.u_axis(); + let b = self.v_axis(); + let c = self.normal(); + let mat = Matrix3::from_cols(a, b, c).invert().unwrap(); + mat * (pt - self.o) + } + /// into B-spline surface + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let pt0 = Point3::new(0.0, 1.0, 2.0); + /// let pt1 = Point3::new(1.0, 1.0, 3.0); + /// let pt2 = Point3::new(0.0, 2.0, 3.0); + /// let plane: Plane = Plane::new(pt0, pt1, pt2); + /// let surface: BSplineSurface = plane.into_bspline(); + /// assert_eq!(surface.range_tuple(), ((0.0, 1.0), (0.0, 1.0))); + /// + /// const N: usize = 100; + /// for i in 0..=N { + /// for j in 0..=N { + /// let u = i as f64 / N as f64; + /// let v = j as f64 / N as f64; + /// let res = surface.subs(u, v); + /// let ans = plane.subs(u, v); + /// assert_near!(ans, res); + /// } + /// } + /// ``` + #[inline(always)] + pub fn into_bspline(&self) -> BSplineSurface { + let o = self.o; + let p = self.p; + let q = self.q; + BSplineSurface::debug_new( + (KnotVec::bezier_knot(1), KnotVec::bezier_knot(1)), + vec![vec![o, q], vec![p, p + (q - o)]], + ) + } + /// into NURBS surface + /// # Examples + /// ``` + /// use truck_geometry::prelude::*; + /// let pt0 = Point3::new(0.0, 1.0, 2.0); + /// let pt1 = Point3::new(1.0, 1.0, 3.0); + /// let pt2 = Point3::new(0.0, 2.0, 3.0); + /// let plane: Plane = Plane::new(pt0, pt1, pt2); + /// let surface: NurbsSurface = plane.into_nurbs(); + /// assert_eq!(surface.range_tuple(), ((0.0, 1.0), (0.0, 1.0))); + /// + /// const N: usize = 100; + /// for i in 0..=N { + /// for j in 0..=N { + /// let u = i as f64 / N as f64; + /// let v = j as f64 / N as f64; + /// let res = surface.subs(u, v); + /// let ans = plane.subs(u, v); + /// assert_near!(ans, res); + /// } + /// } + /// ``` + #[inline(always)] + pub fn into_nurbs(&self) -> NurbsSurface { + let o = self.o.to_homogeneous(); + let p = self.p.to_homogeneous(); + let q = self.q.to_homogeneous(); + NurbsSurface::new(BSplineSurface::debug_new( + (KnotVec::bezier_knot(1), KnotVec::bezier_knot(1)), + vec![vec![o, q], vec![p, p + q - o]], + )) + } +} + +impl ParametricSurface for Plane { + type Point = Point3; + type Vector = Vector3; + #[inline(always)] + fn subs(&self, u: f64, v: f64) -> Point3 { + self.o + u * (self.p - self.o) + v * (self.q - self.o) + } + #[inline(always)] + fn uder(&self, _: f64, _: f64) -> Vector3 { self.p - self.o } + #[inline(always)] + fn vder(&self, _: f64, _: f64) -> Vector3 { self.q - self.o } + #[inline(always)] + fn uuder(&self, _: f64, _: f64) -> Vector3 { Vector3::zero() } + #[inline(always)] + fn uvder(&self, _: f64, _: f64) -> Vector3 { Vector3::zero() } + #[inline(always)] + fn vvder(&self, _: f64, _: f64) -> Vector3 { Vector3::zero() } + /// as square + #[inline(always)] + fn parameter_range(&self) -> (ParameterRange, ParameterRange) { + let range = (Bound::Included(0.0), Bound::Included(1.0)); + (range, range) + } +} + +impl ParametricSurface3D for Plane { + #[inline(always)] + fn normal(&self, _: f64, _: f64) -> Vector3 { self.normal() } +} + +impl BoundedSurface for Plane {} + +impl Invertible for Plane { + #[inline(always)] + fn inverse(&self) -> Self { + Plane { + o: self.o, + p: self.q, + q: self.p, + } + } + #[inline(always)] + fn invert(&mut self) { *self = self.inverse(); } +} + +impl IncludeCurve> for Plane { + #[inline(always)] + fn include(&self, curve: &BSplineCurve) -> bool { + let origin = self.origin(); + let normal = self.normal(); + curve + .control_points() + .iter() + .all(|pt| (pt - origin).dot(normal).so_small()) + } +} + +impl IncludeCurve> for Plane { + fn include(&self, curve: &NurbsCurve) -> bool { + let origin = self.origin(); + let normal = self.normal(); + let (s, e) = (curve.front(), curve.back()); + if !(s - origin).dot(normal).so_small() || !(e - origin).dot(normal).so_small() { + return false; + } + curve.non_rationalized().control_points().iter().all(|pt| { + if pt[3].so_small() { + true + } else { + let pt = Point3::from_homogeneous(*pt); + (pt - origin).dot(normal).so_small() + } + }) + } +} + +impl ParameterDivision2D for Plane { + #[inline(always)] + fn parameter_division(&self, range: ((f64, f64), (f64, f64)), _: f64) -> (Vec, Vec) { + (vec![range.0 .0, range.0 .1], vec![range.1 .0, range.1 .1]) + } +} + +impl> Transformed for Plane { + #[inline(always)] + fn transform_by(&mut self, trans: T) { + self.o = trans.transform_point(self.o); + self.p = trans.transform_point(self.p); + self.q = trans.transform_point(self.q); + } + #[inline(always)] + fn transformed(&self, trans: T) -> Self { + Plane { + o: trans.transform_point(self.o), + p: trans.transform_point(self.p), + q: trans.transform_point(self.q), + } + } +} + +impl SearchParameter for Plane { + type Point = Point3; + #[inline(always)] + fn search_parameter>( + &self, + point: Point3, + _: H, + _: usize, + ) -> Option<(f64, f64)> { + let v = self.get_parameter(point); + match v[2].so_small() { + true => Some((v[0], v[1])), + false => None, + } + } +} + +impl SearchNearestParameter for Plane { + type Point = Point3; + #[inline(always)] + fn search_nearest_parameter>( + &self, + point: Point3, + _: H, + _: usize, + ) -> Option<(f64, f64)> { + let v = self.get_parameter(point); + Some((v[0], v[1])) + } +} diff --git a/vendor/truck-geometry/src/specifieds/sphere.rs b/vendor/truck-geometry/src/specifieds/sphere.rs new file mode 100644 index 000000000..257997e55 --- /dev/null +++ b/vendor/truck-geometry/src/specifieds/sphere.rs @@ -0,0 +1,219 @@ +use super::*; +use std::f64::consts::PI; + +impl Sphere { + /// Creates a sphere + #[inline(always)] + pub const fn new(center: Point3, radius: f64) -> Sphere { Sphere { center, radius } } + /// Returns the center + #[inline(always)] + pub const fn center(&self) -> Point3 { self.center } + /// Returns the radius + #[inline(always)] + pub const fn radius(&self) -> f64 { self.radius } + /// Returns whether the point `pt` is on sphere + #[inline(always)] + pub fn include(&self, pt: Point3) -> bool { self.center.distance(pt).near(&self.radius) } +} + +impl ParametricSurface for Sphere { + type Point = Point3; + type Vector = Vector3; + #[inline(always)] + fn subs(&self, u: f64, v: f64) -> Point3 { self.center() + self.radius * self.normal(u, v) } + #[inline(always)] + fn uder(&self, u: f64, v: f64) -> Vector3 { + self.radius + * Vector3::new( + f64::cos(u) * f64::cos(v), + f64::cos(u) * f64::sin(v), + -f64::sin(u), + ) + } + #[inline(always)] + fn vder(&self, u: f64, v: f64) -> Vector3 { + self.radius * f64::sin(u) * Vector3::new(-f64::sin(v), f64::cos(v), 0.0) + } + #[inline(always)] + fn uuder(&self, u: f64, v: f64) -> Vector3 { -self.radius * self.normal(u, v) } + #[inline(always)] + fn uvder(&self, u: f64, v: f64) -> Vector3 { + self.radius * f64::cos(u) * Vector3::new(-f64::sin(v), f64::cos(v), 0.0) + } + #[inline(always)] + fn vvder(&self, u: f64, v: f64) -> Vector3 { + -self.radius * f64::sin(u) * Vector3::new(f64::cos(v), f64::sin(v), 0.0) + } + #[inline(always)] + fn parameter_range(&self) -> (ParameterRange, ParameterRange) { + ( + (Bound::Included(0.0), Bound::Included(PI)), + (Bound::Included(0.0), Bound::Excluded(2.0 * PI)), + ) + } + #[inline(always)] + fn v_period(&self) -> Option { Some(2.0 * PI) } +} + +impl ParametricSurface3D for Sphere { + #[inline(always)] + fn normal(&self, u: f64, v: f64) -> Vector3 { + Vector3::new( + f64::sin(u) * f64::cos(v), + f64::sin(u) * f64::sin(v), + f64::cos(u), + ) + } +} + +#[test] +fn sphere_derivation_test() { + let center = Point3::new(1.0, 2.0, 3.0); + let radius = 4.56; + let sphere = Sphere::new(center, radius); + const N: usize = 100; + for i in 0..N { + for j in 0..N { + let u = PI * i as f64 / N as f64; + let v = 2.0 * PI * j as f64 / N as f64; + let normal = sphere.normal(u, v); + assert!(normal.dot(sphere.uder(u, v)).so_small()); + assert!(normal.dot(sphere.vder(u, v)).so_small()); + } + } +} + +impl BoundedSurface for Sphere {} + +impl IncludeCurve> for Sphere { + #[inline(always)] + fn include(&self, curve: &BSplineCurve) -> bool { + curve.is_const() && self.include(curve.front()) + } +} + +impl IncludeCurve> for Sphere { + fn include(&self, curve: &NurbsCurve) -> bool { + let (knots, _) = curve.knot_vec().to_single_multi(); + let degree = curve.degree() * 2; + knots + .windows(2) + .flat_map(move |window| (1..degree).map(move |i| (window, i))) + .all(move |(window, i)| { + let t = i as f64 / degree as f64; + let t = window[0] * (1.0 - t) + window[1] * t; + self.include(curve.subs(t)) + }) + } +} + +impl ParameterDivision2D for Sphere { + #[inline(always)] + fn parameter_division( + &self, + (urange, vrange): ((f64, f64), (f64, f64)), + tol: f64, + ) -> (Vec, Vec) { + nonpositive_tolerance!(tol); + assert!( + tol < self.radius, + "Tolerance is larger than the radius of sphere." + ); + let delta = 2.0 * f64::acos(1.0 - tol / self.radius); + let u_div = 1 + ((urange.1 - urange.0) / delta).floor() as usize; + let v_div = 1 + ((vrange.1 - vrange.0) / delta).floor() as usize; + ( + (0..=u_div) + .map(|i| urange.0 + (urange.1 - urange.0) * i as f64 / u_div as f64) + .collect(), + (0..=v_div) + .map(|j| vrange.0 + (vrange.1 - vrange.0) * j as f64 / v_div as f64) + .collect(), + ) + } +} + +impl SearchParameter for Sphere { + type Point = Point3; + #[inline(always)] + fn search_parameter>( + &self, + point: Point3, + hint: H, + _: usize, + ) -> Option<(f64, f64)> { + let radius = point - self.center; + if (self.radius * self.radius).near(&radius.magnitude2()) { + let radius = radius.normalize(); + let u = f64::acos(radius[2]); + let sinu = f64::sqrt(1.0 - radius[2] * radius[2]); + let cosv = f64::clamp(radius[0] / sinu, -1.0, 1.0); + let v = if sinu.so_small() { + match hint.into() { + SPHint2D::Parameter(_, hint) => hint, + _ => 0.0, + } + } else if radius[1] > 0.0 { + f64::acos(cosv) + } else { + 2.0 * PI - f64::acos(cosv) + }; + Some((u, v)) + } else { + None + } + } +} + +impl SearchNearestParameter for Sphere { + type Point = Point3; + #[inline(always)] + fn search_nearest_parameter>( + &self, + point: Point3, + _: H, + _: usize, + ) -> Option<(f64, f64)> { + let radius = (point - self.center).normalize(); + let u = f64::acos(radius[2]); + let sinu = f64::sqrt(1.0 - radius[2] * radius[2]); + let cosv = radius[0] / sinu; + let v = if radius[1] > 0.0 { + f64::acos(cosv) + } else { + 2.0 * PI - f64::acos(cosv) + }; + Some((u, v)) + } +} + +#[cfg(test)] +fn exec_search_parameter_test() { + let center = Point3::new( + 100.0 * rand::random::() - 50.0, + 100.0 * rand::random::() - 50.0, + 100.0 * rand::random::() - 50.0, + ); + let radius = 100.0 * rand::random::(); + let sphere = Sphere::new(center, radius); + let u = PI * rand::random::(); + let v = 2.0 * PI * rand::random::(); + let pt = sphere.subs(u, v); + let (u0, v0) = sphere.search_parameter(pt, None, 100).unwrap(); + assert_near!(Vector2::new(u, v), Vector2::new(u0, v0)); + let pt = pt + + Vector3::new( + (0.1 * rand::random::() + 0.01) * f64::signum(rand::random::() - 0.5), + (0.1 * rand::random::() + 0.01) * f64::signum(rand::random::() - 0.5), + (0.1 * rand::random::() + 0.01) * f64::signum(rand::random::() - 0.5), + ); + assert!(sphere.search_parameter(pt, None, 100).is_none()); + let (u, v) = sphere.search_nearest_parameter(pt, None, 100).unwrap(); + assert_near!( + sphere.subs(u, v), + center + (pt - center).normalize() * radius + ); +} + +#[test] +fn search_parameter_test() { (0..10).for_each(|_| exec_search_parameter_test()) } diff --git a/vendor/truck-geometry/src/specifieds/torus.rs b/vendor/truck-geometry/src/specifieds/torus.rs new file mode 100644 index 000000000..d53a8bfd4 --- /dev/null +++ b/vendor/truck-geometry/src/specifieds/torus.rs @@ -0,0 +1,238 @@ +use super::*; +use std::f64::consts::PI; + +impl Torus { + /// constructor + #[inline(always)] + pub fn new(center: Point3, large_radius: f64, small_radius: f64) -> Self { + if large_radius <= 0.0 || small_radius <= 0.0 { + panic!("radius must be larger than 0"); + } + Self { + center, + large_radius, + small_radius, + } + } + + /// get center + #[inline(always)] + pub const fn center(&self) -> Point3 { self.center } + + /// get large radius + #[inline(always)] + pub const fn large_radius(&self) -> f64 { self.large_radius } + + /// get small radius + #[inline(always)] + pub const fn small_radius(&self) -> f64 { self.small_radius } +} + +impl ParametricSurface for Torus { + type Point = Point3; + type Vector = Vector3; + #[inline(always)] + fn subs(&self, u: f64, v: f64) -> Point3 { + let sr = self.small_radius() * Vector2::new(f64::cos(v), f64::sin(v)); + let lr = (self.large_radius() + sr.x) * Vector2::new(f64::cos(u), f64::sin(u)); + self.center() + Vector3::new(lr.x, lr.y, sr.y) + } + #[inline(always)] + fn uder(&self, u: f64, v: f64) -> Vector3 { + let sr = self.small_radius() * f64::cos(v); + let lr = (self.large_radius() + sr) * Vector2::new(f64::cos(u), f64::sin(u)); + Vector3::new(-lr.y, lr.x, 0.0) + } + #[inline(always)] + fn vder(&self, u: f64, v: f64) -> Vector3 { + let sv = self.small_radius() * Vector2::new(-f64::sin(v), f64::cos(v)); + Vector3::new(sv.x * f64::cos(u), sv.x * f64::sin(u), sv.y) + } + #[inline(always)] + fn uuder(&self, u: f64, v: f64) -> Vector3 { + let sr = self.small_radius() * f64::cos(v); + let lr = (self.large_radius() + sr) * Vector2::new(f64::cos(u), f64::sin(u)); + Vector3::new(-lr.x, -lr.y, 0.0) + } + #[inline(always)] + fn uvder(&self, u: f64, v: f64) -> Vector3 { + let sr = -self.small_radius() * f64::sin(v); + let lr = sr * Vector2::new(f64::cos(u), f64::sin(u)); + Vector3::new(-lr.y, lr.x, 0.0) + } + #[inline(always)] + fn vvder(&self, u: f64, v: f64) -> Vector3 { + let sv = -self.small_radius() * Vector2::new(f64::cos(v), f64::sin(v)); + Vector3::new(sv.x * f64::cos(u), sv.x * f64::sin(u), sv.y) + } + #[inline(always)] + fn parameter_range(&self) -> (ParameterRange, ParameterRange) { + const RANGE: (Bound, Bound) = (Bound::Included(0.0), Bound::Excluded(2.0 * PI)); + (RANGE, RANGE) + } + #[inline(always)] + fn u_period(&self) -> Option { Some(2.0 * PI) } + #[inline(always)] + fn v_period(&self) -> Option { Some(2.0 * PI) } +} + +impl ParametricSurface3D for Torus { + fn normal(&self, u: f64, v: f64) -> Vector3 { + let sv = Vector2::new(f64::cos(v), f64::sin(v)); + Vector3::new(sv.x * f64::cos(u), sv.x * f64::sin(u), sv.y) + } +} + +impl BoundedSurface for Torus {} + +impl SearchParameter for Torus { + type Point = Point3; + fn search_parameter>( + &self, + point: Point3, + _: H, + _: usize, + ) -> Option<(f64, f64)> { + let r = point - self.center(); + let rxy = Vector2::new(r.x, r.y); + let v = f64::asin(f64::clamp(r.z / self.small_radius(), -1.0, 1.0)); + let minus = rxy.magnitude2() < self.large_radius() * self.large_radius(); + let v = match (minus, v < 0.0) { + (true, _) => PI - v, + (false, false) => v, + (false, true) => 2.0 * PI + v, + }; + let rxy_n = rxy.normalize(); + let u = f64::acos(f64::clamp(rxy_n.x, -1.0, 1.0)); + let u = match rxy_n.y < 0.0 { + true => 2.0 * PI - u, + false => u, + }; + match self.subs(u, v).near(&point) { + true => Some((u, v)), + false => None, + } + } +} + +impl SearchNearestParameter for Torus { + type Point = Point3; + fn search_nearest_parameter>( + &self, + point: Point3, + _: H, + _: usize, + ) -> Option<(f64, f64)> { + let r = point - self.center(); + let rxy = Vector2::new(r.x, r.y); + if rxy.so_small() { + return None; + } + let rxy_n = rxy.normalize(); + let large_r = self.large_radius() * rxy_n.extend(0.0); + let diff = r - large_r; + if diff.so_small() { + return None; + } + let small_r = diff.normalize(); + + let u = f64::acos(f64::clamp(rxy_n.x, -1.0, 1.0)); + let u = match rxy_n.y < 0.0 { + true => 2.0 * PI - u, + false => u, + }; + let v = f64::asin(f64::clamp(small_r.z, -1.0, 1.0)); + let v = match (small_r.dot(large_r) < 0.0, v < 0.0) { + (true, _) => PI - v, + (false, false) => v, + (false, true) => 2.0 * PI + v, + }; + Some((u, v)) + } +} + +impl ParameterDivision2D for Torus { + fn parameter_division( + &self, + (urange, vrange): ((f64, f64), (f64, f64)), + tol: f64, + ) -> (Vec, Vec) { + let circle = UnitCircle::::new(); + let utol = tol / (self.small_radius() + self.large_radius()); + let (udiv, _) = circle.parameter_division(urange, utol); + let vtol = tol / self.small_radius(); + let (vdiv, _) = circle.parameter_division(vrange, vtol); + (udiv, vdiv) + } +} + +#[test] +fn surface() { + use std::ops::RangeBounds; + let small_radius = 5.0 * rand::random::() + 1.0; + let large_radius = 2.0 * small_radius + 5.0 * rand::random::(); + let torus = Torus::new(Point3::new(0.0, 0.0, 0.0), large_radius, small_radius); + const N: usize = 10; + const EPS: f64 = 1.0e-2; + for i in 0..N { + for j in 0..N { + let u = 2.0 * PI * i as f64 / N as f64; + let v = 2.0 * PI * j as f64 / N as f64; + let p = torus.subs(u, v); + let r = large_radius * Point3::new(f64::cos(u), f64::sin(u), 0.0); + assert_near!(p.distance(r), small_radius); + assert_near!(p.z, small_radius * f64::sin(v)); + + let uder0 = torus.uder(u, v); + let uder1 = (torus.subs(u + EPS, v) - torus.subs(u - EPS, v)) / (2.0 * EPS); + assert!((uder0 - uder1).magnitude() < EPS, "{:?} {:?}", uder0, uder1); + + let vder0 = torus.vder(u, v); + let vder1 = (torus.subs(u, v + EPS) - torus.subs(u, v - EPS)) / (2.0 * EPS); + assert!((vder0 - vder1).magnitude() < EPS, "{:?} {:?}", vder0, vder1); + + let uuder0 = torus.uuder(u, v); + let uuder1 = (torus.uder(u + EPS, v) - torus.uder(u - EPS, v)) / (2.0 * EPS); + assert!( + (uuder0 - uuder1).magnitude() < EPS, + "{:?} {:?}", + uuder0, + uuder1 + ); + + let uvder0 = torus.uvder(u, v); + let uvder1 = (torus.vder(u + EPS, v) - torus.vder(u - EPS, v)) / (2.0 * EPS); + assert!( + (uvder0 - uvder1).magnitude() < EPS, + "{:?} {:?}", + uvder0, + uvder1 + ); + + let vvder0 = torus.vvder(u, v); + let vvder1 = (torus.vder(u, v + EPS) - torus.vder(u, v - EPS)) / (2.0 * EPS); + assert!( + (vvder0 - vvder1).magnitude() < EPS, + "{:?} {:?}", + vvder0, + vvder1 + ); + + let n0 = torus.normal(u, v); + let n1 = torus.uder(u, v).cross(torus.vder(u, v)).normalize(); + assert_near!(n0, n1); + + let (u0, v0) = torus.search_parameter(p, None, 1).unwrap(); + let (urange, vrange) = torus.parameter_range(); + assert!(urange.contains(&u0) && vrange.contains(&v0), "{u0}, {v0}"); + assert_near!(torus.subs(u0, v0), p); + + let deform = (0.8 * rand::random::() - 0.4) * small_radius; + let q = p + deform * n0; + let (u0, v0) = torus.search_nearest_parameter(q, None, 1).unwrap(); + let (urange, vrange) = torus.parameter_range(); + assert!(urange.contains(&u0) && vrange.contains(&v0), "{u0}, {v0}"); + assert_near!(torus.subs(u0, v0), p); + } + } +} From 44968dbfe6250e130ade14612de0716a3da68b5c Mon Sep 17 00:00:00 2001 From: JIJINBEI <87472238+jijinbei@users.noreply.github.com> Date: Fri, 16 Oct 2026 13:28:12 +0900 Subject: [PATCH 71/92] =?UTF-8?q?Feature=20fields:=20a=20type=20for=20each?= =?UTF-8?q?=20role=20(Expr,=20BodyName,=20FacePick=E2=80=A6)=20(#1273)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Thanks @jijinbei. --- crates/derive/src/lib.rs | 38 +- crates/doc/src/assembly.rs | 4 +- crates/doc/src/body_transfer.rs | 8 +- crates/doc/src/clipboard.rs | 6 +- crates/doc/src/config_shell_tests.rs | 12 +- crates/doc/src/construct.rs | 2 +- crates/doc/src/document.rs | 676 +++++++----------- crates/doc/src/eval.rs | 188 ++--- crates/doc/src/eval_more.rs | 103 +-- crates/doc/src/eval_surface.rs | 74 +- crates/doc/src/expr.rs | 88 +++ crates/doc/src/face_anchor.rs | 12 +- crates/doc/src/feature_refs.rs | 25 +- crates/doc/src/feature_walk_tests.rs | 12 +- crates/doc/src/format.rs | 8 +- crates/doc/src/format_offsets.rs | 2 +- crates/doc/src/lib.rs | 5 + crates/doc/src/names.rs | 146 ++++ crates/doc/src/naming.rs | 10 +- crates/doc/src/params.rs | 16 +- crates/doc/src/points.rs | 61 ++ crates/doc/src/profile_refs.rs | 4 +- crates/doc/src/project.rs | 7 +- crates/doc/src/tests.rs | 12 +- crates/doc/src/walk.rs | 80 ++- crates/engine/src/cmd/browser.rs | 2 +- crates/engine/src/cmd/component_clone.rs | 11 +- .../engine/src/cmd/component_clone_tests.rs | 2 +- crates/engine/src/cmd/component_transfer.rs | 3 +- crates/engine/src/cmd/construct.rs | 4 +- crates/engine/src/cmd/edit.rs | 12 +- crates/engine/src/cmd/face_tests.rs | 6 +- crates/engine/src/cmd/features.rs | 248 +++++-- crates/engine/src/cmd/features_more.rs | 52 +- crates/engine/src/cmd/plastic.rs | 34 +- crates/engine/src/cmd/sheet.rs | 51 +- crates/engine/src/cmd/sketch_create.rs | 2 +- crates/engine/src/cmd/sketch_modify.rs | 2 +- crates/engine/src/cmd/surface.rs | 83 ++- crates/engine/src/derived_units_tests.rs | 2 +- crates/engine/src/frames.rs | 12 +- crates/engine/src/large_assembly_tests.rs | 7 +- crates/engine/src/occurrences.rs | 2 +- crates/engine/src/params.rs | 9 +- crates/engine/src/pattern_suppress_tests.rs | 2 +- crates/io/src/lib.rs | 6 +- crates/ui-egui/src/dialogs.rs | 184 ++--- crates/ui-egui/src/dialogs_move.rs | 17 +- crates/ui-egui/src/dialogs_plastic.rs | 48 +- crates/ui-egui/src/dialogs_sheet.rs | 42 +- crates/ui-egui/src/dialogs_surface.rs | 72 +- crates/ui-egui/src/dialogs_sweep.rs | 10 +- crates/ui-egui/src/hole_direction_ui_tests.rs | 2 +- crates/ui-egui/src/hole_placement_ui_tests.rs | 2 +- crates/ui-egui/src/primitive_units_tests.rs | 8 +- .../ui-egui/src/revolve_manipulator_tests.rs | 2 +- crates/ui-egui/src/sweep_dialog_tests.rs | 6 +- crates/ui-egui/src/timeline.rs | 2 +- crates/ui-egui/src/timeline_left.rs | 2 +- 59 files changed, 1505 insertions(+), 1043 deletions(-) create mode 100644 crates/doc/src/names.rs create mode 100644 crates/doc/src/points.rs diff --git a/crates/derive/src/lib.rs b/crates/derive/src/lib.rs index 04a12dae6..74d4ff4e2 100644 --- a/crates/derive/src/lib.rs +++ b/crates/derive/src/lib.rs @@ -10,16 +10,17 @@ //! //! What a field is, is written once, on the field, with `#[walk(...)]`: //! -//! - no attribute: the field's own type walks itself (`impl Walk`): a plane, a nested struct, a -//! list of them, or nothing for names, flags and numbers. A bare `Vec3` has no walk, so a point -//! that does not say its role does not compile; -//! - `length = label`, `angle = label`, `unitless = label`: an expression input (a `String`, an -//! optional one, a list or an array of them, or `(f64, String)` pairs). The label is any +//! - no attribute: the field's own type walks itself (`impl Walk`): a reference (`SketchId`, +//! `BodyName`, `FeatureName`), a point with its role (`FacePick`, `Position`, `Dir`), a plane, a +//! nested struct, a list of them, or nothing for names, flags and numbers. An `Expr` or a bare +//! `Vec3` has no walk, so an expression or a point that does not say what it is does not +//! compile; +//! - `length = label`, `angle = label`, `unitless = label`: an expression input (an `Expr`, an +//! optional one, a list or an array of them, or `(f64, Expr)` pairs). The label is any //! expression: a `&'static str`, an array of them (one per element), or a closure //! `|i: usize, n: usize| -> &'static str`; it may read the other fields; -//! - `sketch`, `feature`, `body`: a reference (an id, or a name, optional or a list); -//! - `pick`, `pinned`, `pos`, `dir`: a point (`Vec3`, optional or a list) with that role; -//! `pick_if = cond`: a pick when `cond` holds, else a position; +//! - `pinned`: a face pick that stays where it is when the feature moves; +//! `pick_if = cond`: a face pick when `cond` holds, else a position; //! - `placement`: a primitive's placement point (its X, Y and Z expressions are not inputs); //! - `profiles_of = sketch_field`, optionally with `when = cond`: a profile selection; //! - `after = field`: visit this field right after `field` instead of in declaration order (where @@ -60,8 +61,6 @@ struct Roles { geo: Option, /// The kind (`Length`, `Angle`, `Unitless`) and the label. expr: Option<(&'static str, Expr)>, - /// `Sketch`, `Feature` or `Body`. - reference: Option<&'static str>, after: Option, /// The positions inside this (nested) value pick faces here. picks_faces: bool, @@ -70,7 +69,7 @@ struct Roles { impl Roles { /// No role given: the field's type walks itself. fn nested(&self) -> bool { - self.geo.is_none() && self.expr.is_none() && self.reference.is_none() + self.geo.is_none() && self.expr.is_none() } } @@ -82,10 +81,7 @@ fn roles(field: &syn::Field) -> syn::Result { attr.parse_nested_meta(|meta| { let name = meta.path.get_ident().map(Ident::to_string).unwrap_or_default(); match name.as_str() { - "pick" => r.geo = Some(Geo::Points("Pick")), "pinned" => r.geo = Some(Geo::Points("Pinned")), - "pos" => r.geo = Some(Geo::Points("Pos")), - "dir" => r.geo = Some(Geo::Points("Dir")), "placement" => r.geo = Some(Geo::Placement), "pick_if" => r.geo = Some(Geo::PickIf(meta.value()?.parse()?)), "profiles_of" => sketch = Some(meta.value()?.parse::()?), @@ -93,9 +89,6 @@ fn roles(field: &syn::Field) -> syn::Result { "length" => r.expr = Some(("Length", meta.value()?.parse()?)), "angle" => r.expr = Some(("Angle", meta.value()?.parse()?)), "unitless" => r.expr = Some(("Unitless", meta.value()?.parse()?)), - "sketch" => r.reference = Some("Sketch"), - "feature" => r.reference = Some("Feature"), - "body" => r.reference = Some("Body"), "after" => r.after = Some(meta.value()?.parse()?), "picks_faces" => r.picks_faces = true, _ => return Err(meta.error("unknown walk role")), @@ -157,14 +150,7 @@ fn walk_field(b: &Ident, r: &Roles, which: Which, mutable: bool) -> Tokens { _ => quote!(), } } - Which::Refs => match r.reference { - Some(kind) => { - let t = if kind == "Sketch" { quote!(u64) } else { quote!(String) }; - let kind = Ident::new(kind, Span::call_site()); - quote! { #w::Each::<#t>::#each(#b, &mut |x| f(#w::Ref::#kind(x))); } - } - None => quote!(), - }, + Which::Refs => quote!(), Which::Geometry => match &r.geo { Some(Geo::Points(v)) => { let v = Ident::new(v, Span::call_site()); @@ -209,7 +195,7 @@ fn pre_values(b: &Ident, r: &Roles, which: Which) -> Tokens { quote! { let #wh: bool = #when; let mut #id: Option = None; - #w::Each::::each(&*#sketch, &mut |s| #id = Some(*s)); + #w::Each::::each(&*#sketch, &mut |s| #id = Some(s.0)); } } _ => quote!(), diff --git a/crates/doc/src/assembly.rs b/crates/doc/src/assembly.rs index 20172b342..668707842 100644 --- a/crates/doc/src/assembly.rs +++ b/crates/doc/src/assembly.rs @@ -176,7 +176,7 @@ fn map_geo_ref(m: &Mat, g: &mut crate::construct::GeoRef) { /// Map a point given as expressions by `m`: numbers stay numbers; a coordinate that is an /// expression stays one (`m · (x, y, z) + t`, written out), so it still follows its parameters. pub fn map_point_expr(m: &Mat, p: &mut crate::PointExpr) { - let num = |e: &String| e.trim().parse::().ok().filter(|v| v.is_finite()); + let num = |e: &crate::Expr| e.trim().parse::().ok().filter(|v| v.is_finite()); if let [Some(x), Some(y), Some(z)] = [num(&p[0]), num(&p[1]), num(&p[2])] { *p = crate::point_expr(apply_point(m, Vec3::new(x, y, z))); return; @@ -202,7 +202,7 @@ pub fn map_point_expr(m: &Mat, p: &mut crate::PointExpr) { } else if constant.abs() >= 1e-12 { e = format!("{e} {} {} mm", if constant < 0.0 { '-' } else { '+' }, constant.abs()); } - *out = e; + *out = e.into(); } } diff --git a/crates/doc/src/body_transfer.rs b/crates/doc/src/body_transfer.rs index d29c2a341..1eca9bbe6 100644 --- a/crates/doc/src/body_transfer.rs +++ b/crates/doc/src/body_transfer.rs @@ -78,7 +78,13 @@ mod tests { (vec!["bad\nname".into()], 0, crate::IDENTITY), (vec!["Block".into()], 0, scaled), ] { - assert!(doc.add_feature(crate::FeatureKind::BodyTransfer { bodies, from, to: 0, transform }, None).is_err()); + assert!( + doc.add_feature( + crate::FeatureKind::BodyTransfer { bodies: bodies.into_iter().map(crate::BodyName).collect(), from, to: 0, transform }, + None + ) + .is_err() + ); assert_eq!(doc.to_json(), before); } } diff --git a/crates/doc/src/clipboard.rs b/crates/doc/src/clipboard.rs index 13fa98298..b8679b44a 100644 --- a/crates/doc/src/clipboard.rs +++ b/crates/doc/src/clipboard.rs @@ -114,7 +114,7 @@ fn remap_plane( } match p { PlaneRef::Offset { base, .. } | PlaneRef::AtAngle { base, .. } => remap_plane(base, ids, names, bodies, depth + 1)?, - PlaneRef::Construction { name } => mapped_name(name, names), + PlaneRef::Construction { name } => mapped_name(&mut name.0, names), PlaneRef::Face { name, anchor, .. } => { if let Some(name) = name { *name = remap_topology(name, ids, bodies); @@ -221,10 +221,10 @@ impl crate::Feature { *n = remap_topology(n, ids, bodies); } for (_, e, _) in self.kind.inputs_mut() { - *e = clone_expression(e, parameters); + *e = clone_expression(e, parameters).into(); } for e in self.kind.placement_exprs_mut() { - *e = clone_expression(e, parameters); + *e = clone_expression(e, parameters).into(); } self.kind.remap_bodies(bodies); match &mut self.kind { diff --git a/crates/doc/src/config_shell_tests.rs b/crates/doc/src/config_shell_tests.rs index 3aa5dce14..d94a72efd 100644 --- a/crates/doc/src/config_shell_tests.rs +++ b/crates/doc/src/config_shell_tests.rs @@ -17,7 +17,7 @@ fn shell_document() -> (Document, u64, u64) { let shell = doc .add_feature( FeatureKind::Shell { - faces: vec![Vec3::new(5., 6., 10.)], + faces: vec![crate::FacePick(Vec3::new(5., 6., 10.))], thickness: "wall".into(), body: Some("Case".into()), direction: "inside".into(), @@ -119,7 +119,7 @@ fn shell_planar_anchor_rebuild_cold_geometry_and_missing_source_errors() { .add_feature( FeatureKind::Extrude { thin: None, - sketch: sk, + sketch: crate::SketchId(sk), profiles: crate::ProfileSel::All, extent: serde_json::from_value(json!({"distance":"2"})).unwrap(), operation: crate::Operation::NewBody, @@ -282,7 +282,7 @@ fn saved_former_strip_projection_reports_lost_without_expanding_healthy_material .add_feature( FeatureKind::Extrude { thin: None, - sketch: sk, + sketch: crate::SketchId(sk), profiles: crate::ProfileSel::All, extent: serde_json::from_value(json!({"distance":"1"})).unwrap(), operation: crate::Operation::NewBody, @@ -344,7 +344,7 @@ fn saved_curved_strip_projection_is_lost_after_exact_wall_coalescence() { let shell = doc .add_feature( FeatureKind::Shell { - faces: vec![Vec3::new(0., 0., 30.)], + faces: vec![crate::FacePick(Vec3::new(0., 0., 30.))], thickness: "wall".into(), body: Some("Case".into()), direction: "inside".into(), @@ -432,7 +432,7 @@ fn saved_curved_strip_projection_is_lost_after_exact_wall_coalescence() { .add_feature( FeatureKind::Extrude { thin: None, - sketch: sk, + sketch: crate::SketchId(sk), profiles: crate::ProfileSel::All, extent: serde_json::from_value(json!({"distance":"1"})).unwrap(), operation: crate::Operation::NewBody, @@ -557,7 +557,7 @@ fn saved_stepped_tab_cut_piece_projection_is_lost_without_expanding_material() { .add_feature( FeatureKind::Extrude { thin: None, - sketch: sk, + sketch: crate::SketchId(sk), profiles: crate::ProfileSel::All, extent: serde_json::from_value(json!({"distance":"1"})).unwrap(), operation: crate::Operation::NewBody, diff --git a/crates/doc/src/construct.rs b/crates/doc/src/construct.rs index 21b5a3c47..da42a77eb 100644 --- a/crates/doc/src/construct.rs +++ b/crates/doc/src/construct.rs @@ -82,7 +82,7 @@ pub enum PointDef { /// Where an edge (line) crosses a plane. EdgeAndPlane { edge: GeoRef, plane: GeoRef }, /// At a fraction `t` (0…1) of the way along an edge or sketch curve. - AlongPath { path: GeoRef, t: String }, + AlongPath { path: GeoRef, t: crate::Expr }, } /// Resolved construction geometry, kept in the model state by feature. diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 3aeb554c2..688a0a57a 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -4,7 +4,9 @@ use solidcraft_kernel::Continuity; use solidcraft_sketch::Sketch; use crate::construct::{AxisDef, GeoRef, PointDef}; -use crate::expr::{self, Kind}; +use crate::expr::{self, Expr, Kind}; +use crate::names::{BodyName, FeatureName, SketchId}; +use crate::points::{Dir, FacePick, Position}; use crate::{DocError, Result}; pub const MAX_FEATURES: usize = 10_000; @@ -51,11 +53,11 @@ pub enum PlaneRef { y_dir: Vec3, }, /// Another plane offset along its normal by an expression. - Offset { base: Box, distance: String }, + Offset { base: Box, distance: Expr }, /// Another plane rotated about a line (in world coordinates) by an angle expression. - AtAngle { base: Box, axis_origin: Vec3, axis_dir: Vec3, angle: String }, + AtAngle { base: Box, axis_origin: Vec3, axis_dir: Vec3, angle: Expr }, /// A construction plane feature (by name). - Construction { name: String }, + Construction { name: FeatureName }, /// Halfway between two planes (or planar faces); bisecting them when they meet at an angle. Midplane { a: Box, b: Box }, /// Through two straight edges (lines) that lie in one plane. @@ -65,7 +67,7 @@ pub enum PlaneRef { /// Tangent to a face (cylinder, cone, sphere, torus) where the point `at` lies over it. Tangent { face: Box, at: Vec3 }, /// Square to an edge or sketch curve, a fraction `t` (expression, 0…1) of the way along it. - AlongPath { path: Box, t: String }, + AlongPath { path: Box, t: Expr }, /// Through a straight edge (or line, axis) and square to a plane (or planar face). Perpendicular { plane: Box, line: Box }, /// A planar body face. Certified attachments resolve only their exact source and report @@ -218,7 +220,7 @@ impl ExtrudeConvention { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, solidcraft_derive::Walk)] pub struct Extent { #[walk(length = "Distance")] - pub distance: String, + pub distance: Expr, #[serde(default)] pub convention: ExtrudeConvention, #[serde(default)] @@ -226,32 +228,30 @@ pub struct Extent { /// Optional second side distance (two-sided extrude), along the negative normal. #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(length = "Distance 2")] - pub distance2: Option, + pub distance2: Option, /// Start offset from the sketch plane (expression), along the sketch normal whatever the /// direction. #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(length = "Start offset")] - pub start_offset: Option, + pub start_offset: Option, /// Through all bodies in the direction(s) instead of `distance`. #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub through_all: bool, /// Taper angle (expression; positive grows the profile). #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(angle = "Taper angle")] - pub taper: Option, + pub taper: Option, /// To Object: end at the face (or vertex/point) at this point, instead of `distance`. #[serde(default, skip_serializing_if = "Option::is_none")] - #[walk(pick)] - pub to: Option, + pub to: Option, /// Offset past the To Object face (expression; negative stops short). #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(length = "To offset")] - pub to_offset: Option, + pub to_offset: Option, /// From Object: start at the face (or point) here instead of the sketch plane (plus /// `start_offset`). #[serde(default, skip_serializing_if = "Option::is_none")] - #[walk(pick)] - pub from: Option, + pub from: Option, } /// Thin Extrude: a wall of constant thickness along sketch curves instead of the profiles. @@ -262,13 +262,13 @@ pub struct ThinWall { pub curves: Vec, /// The wall thickness (expression); with `side: two_sides`, the thickness inside. #[walk(length = "Thickness")] - pub thickness: String, + pub thickness: Expr, #[serde(default, skip_serializing_if = "ThinSide::is_center")] pub side: ThinSide, /// With `side: two_sides`, the thickness outside (expression). #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(length = "Thickness 2")] - pub thickness2: Option, + pub thickness2: Option, } /// How a swept profile turns as it follows its path. @@ -282,7 +282,7 @@ pub enum SweepOrientation { Parallel, /// Square to the path, its turn about the path fixed by this direction (in the feature's /// frame): the direction's projection onto the profile stays where it was at the start. - Direction(#[walk(dir)] Vec3), + Direction(Dir), } impl SweepOrientation { @@ -332,21 +332,15 @@ pub enum AxisRef { /// World X / Y / Z axis through the origin. World { axis: String }, /// Any line in the sketch plane, in world coordinates. - Line { - #[walk(pos)] - origin: Vec3, - #[walk(dir)] - dir: Vec3, - }, + Line { origin: Position, dir: Dir }, } /// Persistent cylindrical Emboss selection, authored in the feature component frame. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, solidcraft_derive::Walk)] pub struct EmbossFace { - #[walk(body)] - pub body: String, + pub body: BodyName, #[walk(pinned)] - pub at: Vec3, + pub at: FacePick, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub path: Vec, #[serde(default, skip_serializing_if = "Vec::is_empty")] @@ -427,18 +421,17 @@ impl EmbossFace { /// values is `{"point": [x, y, z], "angle": "…", "height": "…"}`. #[derive(Clone, Debug, Default, PartialEq, solidcraft_derive::Walk)] pub struct FlangeEdge { - #[walk(pos)] - pub point: Vec3, + pub point: Position, #[walk(angle = "Edge angle")] - pub angle: Option, + pub angle: Option, #[walk(length = "Edge height")] - pub height: Option, + pub height: Option, } impl FlangeEdge { /// An edge that takes the feature's angle and height. pub fn at(point: Vec3) -> Self { - Self { point, angle: None, height: None } + Self { point: Position(point), angle: None, height: None } } } @@ -469,9 +462,9 @@ impl<'de> Deserialize<'de> for FlangeEdge { struct Own { point: Vec3, #[serde(default)] - angle: Option, + angle: Option, #[serde(default)] - height: Option, + height: Option, } struct Edge; impl<'de> serde::de::Visitor<'de> for Edge { @@ -484,7 +477,7 @@ impl<'de> Deserialize<'de> for FlangeEdge { } fn visit_map>(self, map: A) -> std::result::Result { let o = Own::deserialize(MapAccessDeserializer::new(map))?; - Ok(FlangeEdge { point: o.point, angle: o.angle, height: o.height }) + Ok(FlangeEdge { point: Position(o.point), angle: o.angle, height: o.height }) } } d.deserialize_any(Edge) @@ -498,8 +491,7 @@ pub enum FeatureKind { /// A recorded timeline ownership boundary. Geometry is converted from its /// current local frame into the destination component frame exactly once. BodyTransfer { - #[walk(body)] - bodies: Vec, + bodies: Vec, from: u64, to: u64, transform: crate::Mat, @@ -510,8 +502,7 @@ pub enum FeatureKind { }, Extrude { /// Feature id of the sketch. - #[walk(sketch)] - sketch: u64, + sketch: SketchId, // A thin extrude follows curves; its profiles are not used. #[walk(profiles_of = sketch, when = thin.is_none())] profiles: ProfileSel, @@ -520,29 +511,26 @@ pub enum FeatureKind { operation: Operation, /// Target body names for join/cut/intersect (empty = all bodies). #[serde(default, skip_serializing_if = "Vec::is_empty")] - #[walk(body)] - targets: Vec, + targets: Vec, /// Thin: a wall along sketch curves instead of the profiles (which are then unused). #[serde(default, skip_serializing_if = "Option::is_none")] thin: Option, }, Revolve { - #[walk(sketch)] - sketch: u64, + sketch: SketchId, #[walk(profiles_of = sketch)] profiles: ProfileSel, axis: AxisRef, #[walk(angle = "Angle")] - angle: String, + angle: Expr, #[serde(default)] operation: Operation, #[serde(default, skip_serializing_if = "Vec::is_empty")] - #[walk(body)] - targets: Vec, + targets: Vec, /// Two Sides: the angle on the other side. #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(angle = "Angle 2")] - angle2: Option, + angle2: Option, /// Symmetric: `angle` split evenly either side of the profile. #[serde(default, skip_serializing_if = "std::ops::Not::not")] symmetric: bool, @@ -551,18 +539,15 @@ pub enum FeatureKind { convention: RevolveConvention, /// To Object: turn until the face, vertex or point here. #[serde(default, skip_serializing_if = "Option::is_none")] - #[walk(pick)] - to: Option, + to: Option, }, Fillet { /// Reference points on the edges to round (each re-finds the nearest edge). - #[walk(pos)] - edges: Vec, + edges: Vec, #[walk(length = style.radius_label())] - radius: String, + radius: Expr, #[serde(default, skip_serializing_if = "Option::is_none")] - #[walk(body)] - body: Option, + body: Option, /// Constant radius (the default), chord length (`radius` is the width across), or a /// radius varying along each edge. #[serde(default, skip_serializing_if = "FilletStyle::is_constant")] @@ -572,35 +557,33 @@ pub enum FeatureKind { fit: FilletFit, }, Chamfer { - #[walk(pos)] - edges: Vec, + edges: Vec, #[walk(length = "Distance")] - distance: String, + distance: Expr, /// Unequal chamfers: the distance along the second face… #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(length = "Distance 2")] - distance2: Option, + distance2: Option, /// …or the angle the chamfer makes with the first face. #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(angle = "Angle")] - angle: Option, + angle: Option, /// Swap which face is the first (by default the one facing up most). #[serde(default, skip_serializing_if = "std::ops::Not::not")] flip: bool, #[serde(default, skip_serializing_if = "Option::is_none")] - #[walk(body)] - body: Option, + body: Option, }, Box { #[serde(with = "point_expr")] #[walk(placement)] corner: PointExpr, #[walk(length = "Length")] - length: String, + length: Expr, #[walk(length = "Width")] - width: String, + width: Expr, #[walk(length = "Height")] - height: String, + height: Expr, #[serde(default)] operation: Operation, }, @@ -609,12 +592,11 @@ pub enum FeatureKind { #[walk(placement)] base: PointExpr, #[serde(default = "z_axis")] - #[walk(dir)] - axis: Vec3, + axis: Dir, #[walk(length = "Radius")] - radius: String, + radius: Expr, #[walk(length = "Height")] - height: String, + height: Expr, #[serde(default)] operation: Operation, }, @@ -623,7 +605,7 @@ pub enum FeatureKind { #[walk(placement)] center: PointExpr, #[walk(length = "Radius")] - radius: String, + radius: Expr, #[serde(default)] operation: Operation, }, @@ -632,40 +614,34 @@ pub enum FeatureKind { #[walk(placement)] center: PointExpr, #[walk(length = "Major radius")] - major: String, + major: Expr, #[walk(length = "Minor radius")] - minor: String, + minor: Expr, #[serde(default)] operation: Operation, }, Combine { - #[walk(body)] - target: String, - #[walk(body)] - tools: Vec, + target: BodyName, + tools: Vec, operation: Operation, #[serde(default)] keep_tools: bool, }, /// Copies of other features' results, or of bodies (rectangular, circular or along a path). Pattern { - #[walk(feature)] - features: Vec, + features: Vec, pattern: PatternKind, /// Copy these bodies (as new bodies) instead of replaying features. #[serde(default, skip_serializing_if = "Vec::is_empty")] - #[walk(body)] - bodies: Vec, + bodies: Vec, }, /// Mirror copies of other features' results in a plane. Mirror { - #[walk(feature)] - features: Vec, + features: Vec, plane: PlaneRef, /// Mirror these bodies instead of replaying features. #[serde(default, skip_serializing_if = "Vec::is_empty")] - #[walk(body)] - bodies: Vec, + bodies: Vec, /// Join each mirrored body with its original. #[serde(default, skip_serializing_if = "std::ops::Not::not")] combine: bool, @@ -673,16 +649,15 @@ pub enum FeatureKind { /// A drilled hole (simple, counterbore or countersink) at a point, into the material. Hole { #[walk(pick_if = points.is_none())] - position: Vec3, + position: FacePick, /// Drilling direction (into the material). - #[walk(dir)] - direction: Vec3, + direction: Dir, #[walk(length = "Diameter")] - diameter: String, + diameter: Expr, /// Depth to the shoulder; `None` = through all. #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(length = "Depth")] - depth: Option, + depth: Option, #[serde(default)] hole: HoleKind, /// Drill at these sketch points instead (one hole each, perpendicular to the sketch, into the material: against the sketch normal, or along it when only that side has material); @@ -694,21 +669,19 @@ pub enum FeatureKind { thread: Option, /// To Object: drill down to the face (or point) here instead of `depth`. #[serde(default, skip_serializing_if = "Option::is_none")] - #[walk(pick)] - to: Option, + to: Option, }, /// A thread on a cylindrical face. Cosmetic by default (no geometry change; drawn and /// exported as an annotation); `modeled` cuts the real helical ISO profile into the face. /// `designation` is an ISO metric size such as "M8" or "M8x1". Thread { - #[walk(pick)] - face: Vec3, + face: FacePick, #[serde(default, skip_serializing_if = "Option::is_none")] designation: Option, /// Thread length from the face's end nearest `face`; `None` = full length. #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(length = "Length")] - length: Option, + length: Option, #[serde(default, skip_serializing_if = "std::ops::Not::not")] modeled: bool, }, @@ -718,17 +691,14 @@ pub enum FeatureKind { #[serde(default)] operation: Operation, #[serde(default, skip_serializing_if = "Vec::is_empty")] - #[walk(body)] - targets: Vec, + targets: Vec, }, /// Sweep profiles along a chain of sketch curves. Sweep { - #[walk(sketch)] - sketch: u64, + sketch: SketchId, #[walk(profiles_of = sketch)] profiles: ProfileSel, - #[walk(sketch)] - path_sketch: u64, + path_sketch: SketchId, path: Vec, /// How the profile turns along the path (default: perpendicular to it). #[serde(default, skip_serializing_if = "SweepOrientation::is_perpendicular")] @@ -736,26 +706,23 @@ pub enum FeatureKind { /// Angle the profile turns about the path over its length. #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(angle = "Twist")] - twist: Option, + twist: Option, /// The profile's scale at the end of the path (linear along its length). #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(unitless = "Scale")] - scale: Option, + scale: Option, #[serde(default)] operation: Operation, #[serde(default, skip_serializing_if = "Vec::is_empty")] - #[walk(body)] - targets: Vec, + targets: Vec, }, /// Hollow a body leaving walls of `thickness`, removing the faces at the given points. Shell { - #[walk(pick)] - faces: Vec, + faces: Vec, #[walk(length = "Thickness")] - thickness: String, + thickness: Expr, #[serde(default, skip_serializing_if = "Option::is_none")] - #[walk(body)] - body: Option, + body: Option, /// inside (default) | outside | both (the wall straddles the faces). #[serde(default, skip_serializing_if = "String::is_empty")] direction: String, @@ -765,16 +732,13 @@ pub enum FeatureKind { }, /// Tilt faces (at the given points) about a neutral plane, leaning toward `pull`. Draft { - #[walk(pick)] - faces: Vec, + faces: Vec, #[walk(angle = "Angle")] - angle: String, + angle: Expr, neutral: PlaneRef, - #[walk(dir)] - pull: Vec3, + pull: Dir, #[serde(default, skip_serializing_if = "Option::is_none")] - #[walk(body)] - body: Option, + body: Option, }, /// A construction plane (sketch placement, split tool). ConstructionPlane { @@ -783,8 +747,7 @@ pub enum FeatureKind { /// Split a body into the parts on either side of a plane, or of a face of a body (the face /// through `point`, its surface extended) when `tool` is set. Split { - #[walk(body)] - body: String, + body: BodyName, plane: PlaneRef, #[serde(default, skip_serializing_if = "Option::is_none")] tool: Option, @@ -801,51 +764,42 @@ pub enum FeatureKind { /// a face of a body (`tool`, its surface extended) or a sketch's curves (`sketch`, swept /// along its normal). The pieces are named after the face (`#k`). SplitFace { - #[walk(pick)] - faces: Vec, + faces: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] - #[walk(body)] - body: Option, + body: Option, plane: PlaneRef, #[serde(default, skip_serializing_if = "Option::is_none")] tool: Option, #[serde(default, skip_serializing_if = "Option::is_none")] - #[walk(sketch)] - sketch: Option, + sketch: Option, }, /// Scale bodies about a point (uniform, or per axis). Scale { - #[walk(body)] - bodies: Vec, + bodies: Vec, #[serde(default)] - #[walk(pos)] - origin: Vec3, + origin: Position, #[walk(unitless = "Scale factor")] - factor: String, + factor: Expr, /// Per-axis factors instead of `factor`. #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(unitless = ["X scale", "Y scale", "Z scale"])] - factors: Option<[String; 3]>, + factors: Option<[Expr; 3]>, }, /// Move planar faces (at the given points) along their normals; the body keeps its shape. OffsetFace { - #[walk(pick)] - faces: Vec, + faces: Vec, #[walk(length = "Distance")] - distance: String, + distance: Expr, #[serde(default, skip_serializing_if = "Option::is_none")] - #[walk(body)] - body: Option, + body: Option, }, /// Remove faces (at the given points) and heal the gap from the neighbouring planes, as when /// a fillet, chamfer, hole or boss is taken off. A picked face brings the rest of its surface /// (both halves of a hole's wall). DeleteFace { - #[walk(pick)] - faces: Vec, + faces: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] - #[walk(body)] - body: Option, + body: Option, /// Close the gap by extending the neighbouring faces (the default); `false` leaves it /// open, the faces left a surface body. #[serde(default = "yes", skip_serializing_if = "is_yes")] @@ -853,56 +807,50 @@ pub enum FeatureKind { }, /// A box around bodies, grown by a margin. BoundingSolid { - #[walk(body)] - bodies: Vec, + bodies: Vec, #[serde(default = "zero_expr")] #[walk(length = "Margin")] - margin: String, + margin: Expr, }, /// A tube along a chain of sketch curves (solid, or hollow with a wall thickness). Pipe { - #[walk(sketch)] - path_sketch: u64, + path_sketch: SketchId, path: Vec, #[walk(length = "Diameter")] - diameter: String, + diameter: Expr, #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(length = "Wall")] - wall: Option, + wall: Option, #[serde(default)] operation: Operation, #[serde(default, skip_serializing_if = "Vec::is_empty")] - #[walk(body)] - targets: Vec, + targets: Vec, }, /// Raise or sink profiles on a planar face, or wrap them on a selected cylindrical wall. Emboss { - #[walk(sketch)] - sketch: u64, + sketch: SketchId, #[walk(profiles_of = sketch)] profiles: ProfileSel, #[walk(length = "Depth")] - depth: String, + depth: Expr, #[serde(default, skip_serializing_if = "std::ops::Not::not")] deboss: bool, #[serde(default, skip_serializing_if = "Option::is_none")] face: Option, #[serde(default, skip_serializing_if = "Vec::is_empty")] - #[walk(body)] - targets: Vec, + targets: Vec, }, /// A thin wall from open sketch curves: `thickness` across the sketch plane, filling from /// the curves toward the body (to the next face, or `depth`). A web makes one per curve. Rib { - #[walk(sketch)] - sketch: u64, + sketch: SketchId, curves: Vec, #[walk(length = "Thickness")] - thickness: String, + thickness: Expr, /// Depth from the curves; `None` = to the next face of the body. #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(length = "Depth")] - depth: Option, + depth: Option, /// Fill toward the other side of the curves. #[serde(default, skip_serializing_if = "std::ops::Not::not")] flip: bool, @@ -912,27 +860,20 @@ pub enum FeatureKind { }, /// Move planar faces (at the given points) onto a target plane parallel to them. ReplaceFace { - #[walk(pick)] - faces: Vec, + faces: Vec, target: PlaneRef, #[serde(default, skip_serializing_if = "Option::is_none")] - #[walk(body)] - body: Option, + body: Option, }, /// Move bodies so that `from` lands on `to` (and, with normals, the faces meet face to face). Align { - #[walk(body)] - bodies: Vec, - #[walk(pos)] - from: Vec3, - #[walk(pos)] - to: Vec3, + bodies: Vec, + from: Position, + to: Position, #[serde(default, skip_serializing_if = "Option::is_none")] - #[walk(dir)] - from_normal: Option, + from_normal: Option

, #[serde(default, skip_serializing_if = "Option::is_none")] - #[walk(dir)] - to_normal: Option, + to_normal: Option, /// Normals the same way instead of facing each other. #[serde(default, skip_serializing_if = "std::ops::Not::not")] flip: bool, @@ -944,16 +885,15 @@ pub enum FeatureKind { #[walk(placement)] base: PointExpr, #[serde(default = "z_axis")] - #[walk(dir)] - axis: Vec3, + axis: Dir, #[walk(length = "Diameter")] - diameter: String, + diameter: Expr, #[walk(length = "Pitch")] - pitch: String, + pitch: Expr, #[walk(unitless = "Revolutions")] - turns: String, + turns: Expr, #[walk(length = "Section size")] - section_size: String, + section_size: Expr, #[serde(default)] section: CoilSection, /// -1 inside, 0 on the centre, 1 outside of the diameter. @@ -963,20 +903,18 @@ pub enum FeatureKind { /// perpendicular direction when the axis is x). #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(angle = "Start angle")] - start_angle: Option, + start_angle: Option, /// Turn the other way (left-handed). #[serde(default, skip_serializing_if = "std::ops::Not::not")] clockwise: bool, #[serde(default)] operation: Operation, #[serde(default, skip_serializing_if = "Vec::is_empty")] - #[walk(body)] - targets: Vec, + targets: Vec, }, /// Sheet metal base flange: a sheet from a closed profile (thickness from the rule). SheetBase { - #[walk(sketch)] - sketch: u64, + sketch: SketchId, #[walk(profiles_of = sketch)] profiles: ProfileSel, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -987,11 +925,10 @@ pub enum FeatureKind { }, /// Sheet metal contour flange: a sheet bent along an open chain of sketch lines. SheetContour { - #[walk(sketch)] - sketch: u64, + sketch: SketchId, curves: Vec, #[walk(length = "Distance")] - distance: String, + distance: Expr, #[serde(default, skip_serializing_if = "Option::is_none")] rule: Option, /// Material on the other side of the chain. @@ -1007,20 +944,19 @@ pub enum FeatureKind { #[walk(after = radius)] edges: Vec, #[walk(length = "Height")] - height: String, + height: Expr, #[walk(angle = "Angle")] - angle: String, + angle: Expr, #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(length = "Bend radius")] - radius: Option, + radius: Option, /// inside | outside | middle. #[serde(default = "inside_str")] position: String, #[serde(default, skip_serializing_if = "std::ops::Not::not")] flip: bool, #[serde(default, skip_serializing_if = "Option::is_none")] - #[walk(body)] - body: Option, + body: Option, /// The relief cut where two of this feature's bends meet at a corner of the base, in place /// of the rule's: `corner_relief_shape` (notch | round | rectangular | tear) and /// `corner_relief`, the size across. Either one left out follows the rule. @@ -1029,22 +965,20 @@ pub enum FeatureKind { /// Walked last, after the edges' values, so the inputs before it keep their names. #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(length = "Corner relief")] - corner_relief: Option, + corner_relief: Option, }, /// Flat hems on sheet edges. SheetHem { - #[walk(pos)] - edges: Vec, + edges: Vec, #[walk(length = "Length")] - length: String, + length: Expr, #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(length = "Gap")] - gap: Option, + gap: Option, #[serde(default, skip_serializing_if = "std::ops::Not::not")] flip: bool, #[serde(default, skip_serializing_if = "Option::is_none")] - #[walk(body)] - body: Option, + body: Option, }, /// A perforation field (#732): round holes of `diameter` on a staggered (60°) or square grid of `pitch` over the /// whole flat sheet, kept `margin` (default: the diameter) clear of its edges, cut-outs and bend zones. Stored like @@ -1052,52 +986,45 @@ pub enum FeatureKind { /// panel can carry tens of thousands of them. SheetPerforate { #[walk(length = "Diameter")] - diameter: String, + diameter: Expr, #[walk(length = "Pitch")] - pitch: String, + pitch: Expr, #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(length = "Margin")] - margin: Option, + margin: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pattern: Option, #[serde(default, skip_serializing_if = "Option::is_none")] - #[walk(body)] - body: Option, + body: Option, }, /// Fold a sheet along a line on its base face: a sketch line (followed when the sketch /// changes), else the points `a`, `b`. SheetFold { #[serde(default, skip_serializing_if = "Option::is_none")] - #[walk(sketch)] - sketch: Option, + sketch: Option, #[serde(default, skip_serializing_if = "Option::is_none")] curve: Option, - #[walk(pos)] - a: Vec3, - #[walk(pos)] - b: Vec3, + a: Position, + b: Position, #[walk(angle = "Angle")] - angle: String, + angle: Expr, #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(length = "Bend radius")] - radius: Option, + radius: Option, /// centerline | start | end | mould position: String, #[serde(default, skip_serializing_if = "std::ops::Not::not")] flip: bool, /// A point on the side that stays put (default: the larger side). #[serde(default, skip_serializing_if = "Option::is_none")] - #[walk(pos)] - fixed: Option, + fixed: Option, #[serde(default, skip_serializing_if = "Option::is_none")] - #[walk(body)] - body: Option, + body: Option, }, /// Unfold a sheet body flat (all bends), or refold it. SheetUnfold { #[serde(default, skip_serializing_if = "Option::is_none")] - #[walk(body)] - body: Option, + body: Option, #[serde(default, skip_serializing_if = "std::ops::Not::not")] refold: bool, }, @@ -1105,147 +1032,130 @@ pub enum FeatureKind { /// thickness or, with `bends`, a solid or shelled body whose faces reached from the fixed /// face across those edges become the sheet. SheetConvert { - #[walk(body)] - body: String, + body: BodyName, #[walk(pick_if = !bends.is_empty())] - face: Vec3, + face: FacePick, #[serde(default, skip_serializing_if = "Option::is_none")] rule: Option, /// Points on the sharp edges that become bends. #[serde(default, skip_serializing_if = "Vec::is_empty")] - #[walk(pos)] - bends: Vec, + bends: Vec, }, /// Plastic boss: a round post on a face (draft, root fillet, hole, ribs). Boss { - #[walk(pick)] - position: Vec3, + position: FacePick, /// Out of the face (the boss grows along it). #[serde(default = "z_axis")] - #[walk(dir)] - direction: Vec3, + direction: Dir, #[walk(length = "Diameter")] - diameter: String, + diameter: Expr, #[walk(length = "Height")] - height: String, + height: Expr, #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(length = "Hole diameter")] - hole_diameter: Option, + hole_diameter: Option, /// Hole depth from the top (default: down to the face). #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(length = "Hole depth")] - hole_depth: Option, + hole_depth: Option, #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(angle = "Draft angle")] - draft: Option, + draft: Option, #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(length = "Root fillet")] - fillet: Option, + fillet: Option, #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(unitless = "Ribs")] - ribs: Option, + ribs: Option, #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(length = "Rib thickness")] - rib_thickness: Option, + rib_thickness: Option, /// Rib reach out from the boss wall. #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(length = "Rib length")] - rib_length: Option, + rib_length: Option, /// Rib top below the boss top. #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(length = "Rib offset")] - rib_offset: Option, + rib_offset: Option, #[serde(default, skip_serializing_if = "Option::is_none")] - #[walk(body)] - body: Option, + body: Option, }, /// Plastic lip (raised band) or groove (recess) along the rim face picked at `face`. Lip { - #[walk(pos)] - face: Vec3, + face: Position, #[walk(length = "Width")] - width: String, + width: Expr, #[walk(length = "Height")] - height: String, + height: Expr, #[serde(default, skip_serializing_if = "std::ops::Not::not")] groove: bool, /// Clearance added to a groove's width (and depth). #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(length = "Gap")] - gap: Option, + gap: Option, /// Along the rim's outer edge instead of its inner one. #[serde(default, skip_serializing_if = "std::ops::Not::not")] outside: bool, #[serde(default, skip_serializing_if = "Option::is_none")] - #[walk(body)] - body: Option, + body: Option, }, /// Plastic snap fit: a cantilever arm on a face with a hook (catch) at its tip. SnapFit { - #[walk(pick)] - position: Vec3, + position: FacePick, /// The arm grows along this (out of the face). #[serde(default = "z_axis")] - #[walk(dir)] - direction: Vec3, + direction: Dir, /// The catch sticks out this way. - #[walk(dir)] - hook: Vec3, + hook: Dir, #[walk(length = "Length")] - length: String, + length: Expr, #[walk(length = "Thickness")] - thickness: String, + thickness: Expr, #[walk(length = "Width")] - width: String, + width: Expr, #[walk(length = "Catch depth")] - catch_depth: String, + catch_depth: Expr, /// The catch's height along the arm. #[walk(length = "Catch length")] - catch_length: String, + catch_length: Expr, #[serde(default, skip_serializing_if = "Option::is_none")] - #[walk(body)] - body: Option, + body: Option, }, /// Plastic rest: a raised pad on a face (round, or a rectangle), solid or a hollow wall, /// with draft. Rest { - #[walk(pick)] - position: Vec3, + position: FacePick, /// Out of the face (the pad grows along it). #[serde(default = "z_axis")] - #[walk(dir)] - direction: Vec3, + direction: Dir, /// The rectangle's length runs along this (default: any direction in the face). #[serde(default, skip_serializing_if = "Option::is_none")] - #[walk(dir)] - along: Option, + along: Option, /// Diameter of a round rest, or the rectangle's width. #[walk(length = "Width")] - width: String, + width: Expr, /// The rectangle's length (none: round). #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(length = "Length", after = height)] - length: Option, + length: Option, #[walk(length = "Height")] - height: String, + height: Expr, #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(angle = "Draft angle")] - draft: Option, + draft: Option, /// Wall thickness of a hollow rest (none: solid). #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(length = "Wall thickness")] - thickness: Option, + thickness: Option, #[serde(default, skip_serializing_if = "Option::is_none")] - #[walk(body)] - body: Option, + body: Option, }, /// Boundary Fill: solids from the cells the tool bodies enclose (a cell: inside some /// tools and outside the rest), each picked by a point inside it. BoundaryFill { - #[walk(body)] - tools: Vec, - #[walk(pos)] - cells: Vec, + tools: Vec, + cells: Vec, #[serde(default)] operation: Operation, /// Remove the tool bodies afterwards. @@ -1254,24 +1164,20 @@ pub enum FeatureKind { }, /// Remove bodies from the model (from here on in the timeline). Remove { - #[walk(body)] - bodies: Vec, + bodies: Vec, }, /// Surface bodies: planar patches filling sketch regions (`profiles` of `sketch`), or a /// closed loop of a body's edges (`edges`: points on them, on `body`). Patch { #[serde(default, skip_serializing_if = "Option::is_none")] - #[walk(sketch)] - sketch: Option, + sketch: Option, #[serde(default = "all_profiles")] #[walk(profiles_of = sketch)] profiles: ProfileSel, #[serde(default, skip_serializing_if = "Option::is_none")] - #[walk(body)] - body: Option, + body: Option, #[serde(default, skip_serializing_if = "Vec::is_empty")] - #[walk(pos)] - edges: Vec, + edges: Vec, /// How full a fitted patch's middle is (`crown`, -0.9…3, default 0; a planar loop is an /// exact plane whatever this says). #[serde(default, skip_serializing_if = "is_zero")] @@ -1282,36 +1188,31 @@ pub enum FeatureKind { continuity: PatchContinuity, /// Points a patch on edges passes through. #[serde(default, skip_serializing_if = "Vec::is_empty")] - #[walk(pos)] - points: Vec, + points: Vec, }, /// Surface bodies sewn along shared edges into the first one (a solid when they close). Stitch { - #[walk(body)] - bodies: Vec, + bodies: Vec, #[serde(default = "zero_expr")] #[walk(length = "Tolerance")] - tolerance: String, + tolerance: Expr, }, /// Surface bodies thickened into solids along their normals (by half each way when /// `symmetric`). Thicken { - #[walk(body)] - bodies: Vec, + bodies: Vec, #[walk(length = "Thickness")] - thickness: String, + thickness: Expr, #[serde(default)] symmetric: bool, operation: Operation, #[serde(default, skip_serializing_if = "Vec::is_empty")] - #[walk(body)] - targets: Vec, + targets: Vec, }, /// A surface body swept straight along the sketch normal from open curve chains and the /// boundaries of profiles: walls only, no caps. SurfaceExtrude { - #[walk(sketch)] - sketch: u64, + sketch: SketchId, /// Profiles whose boundary loops are swept (none: only `curves`). #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(profiles_of = sketch)] @@ -1324,19 +1225,15 @@ pub enum FeatureKind { /// A body taken apart: each face at `faces` (every face when empty) its own surface body, /// the faces left one surface body under the body's name. A solid comes apart into surfaces. Unstitch { - #[walk(body)] - body: String, + body: BodyName, #[serde(default, skip_serializing_if = "Vec::is_empty")] - #[walk(pos)] - faces: Vec, + faces: Vec, }, /// A surface body with the faces at `faces` (every face when empty) turned over. ReverseNormal { - #[walk(body)] - body: String, + body: BodyName, #[serde(default, skip_serializing_if = "Vec::is_empty")] - #[walk(pos)] - faces: Vec, + faces: Vec, }, /// The face at `face` restored towards its surface: the inner loops at the `holes` points /// taken away (every one when `None`; none when empty), and with `outer` its outer boundary @@ -1347,8 +1244,7 @@ pub enum FeatureKind { #[walk(picks_faces)] face: FaceAt, #[serde(default, skip_serializing_if = "Option::is_none")] - #[walk(pos)] - holes: Option>, + holes: Option>, #[serde(default, skip_serializing_if = "std::ops::Not::not")] outer: bool, #[serde(default, skip_serializing_if = "std::ops::Not::not")] @@ -1357,8 +1253,7 @@ pub enum FeatureKind { /// A surface body turned about an axis from open curve chains and the boundaries of /// profiles: walls only, no caps (a solid where a full turn closes them). SurfaceRevolve { - #[walk(sketch)] - sketch: u64, + sketch: SketchId, #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(profiles_of = sketch)] profiles: Option, @@ -1366,11 +1261,11 @@ pub enum FeatureKind { curves: Vec, axis: AxisRef, #[walk(angle = "Angle")] - angle: String, + angle: Expr, /// Two Sides: the angle on the other side. #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(angle = "Angle 2")] - angle2: Option, + angle2: Option, /// Symmetric: `angle` split evenly either side of the sketch. #[serde(default, skip_serializing_if = "std::ops::Not::not")] symmetric: bool, @@ -1378,15 +1273,13 @@ pub enum FeatureKind { /// A surface body swept along a chain of sketch curves from open curve chains and the /// boundaries of profiles: walls only, no caps. SurfaceSweep { - #[walk(sketch)] - sketch: u64, + sketch: SketchId, #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(profiles_of = sketch)] profiles: Option, #[serde(default, skip_serializing_if = "Vec::is_empty")] curves: Vec, - #[walk(sketch)] - path_sketch: u64, + path_sketch: SketchId, path: Vec, /// How the profile turns along the path (default: perpendicular to it). #[serde(default, skip_serializing_if = "SweepOrientation::is_perpendicular")] @@ -1394,11 +1287,11 @@ pub enum FeatureKind { /// Angle the profile turns about the path over its length. #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(angle = "Twist")] - twist: Option, + twist: Option, /// The profile's scale at the end of the path (linear along its length). #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(unitless = "Scale")] - scale: Option, + scale: Option, }, /// A surface body lofted through sections in order, each one open or closed chain of /// sketch curves: walls only, no caps. @@ -1409,57 +1302,49 @@ pub enum FeatureKind { /// surface body (0 copies them); `chain` takes each pick's whole smooth chain of faces; /// fitted faces within `tolerance`. SurfaceOffset { - #[walk(pick)] - faces: Vec, + faces: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] - #[walk(body)] - body: Option, + body: Option, #[walk(length = "Distance")] - distance: String, + distance: Expr, #[serde(default, skip_serializing_if = "std::ops::Not::not")] chain: bool, #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(length = "Tolerance")] - tolerance: Option, + tolerance: Option, }, /// A strip of ruled surface `distance` wide hanging off the chain of `body`'s edges through /// `edges`, as a new surface body: along `mode` (`angle` from `direction`, or from the /// face's normal; along `direction`), from the face at `face` where it borders the chain; /// `flip` puts it on the other side; sharp corners as `corners` says. SurfaceRuled { - #[walk(body)] - body: String, - #[walk(pos)] - edges: Vec, + body: BodyName, + edges: Vec, #[walk(length = "Distance")] - distance: String, + distance: Expr, #[serde(default, skip_serializing_if = "RuledMode::is_normal")] mode: RuledMode, #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(angle = "Angle")] - angle: Option, + angle: Option, #[serde(default, skip_serializing_if = "Option::is_none")] - #[walk(dir)] - direction: Option, + direction: Option, #[serde(default, skip_serializing_if = "std::ops::Not::not")] flip: bool, #[serde(default, skip_serializing_if = "RuledCorners::is_mitre")] corners: RuledCorners, #[serde(default, skip_serializing_if = "Option::is_none")] - #[walk(pick)] - face: Option, + face: Option, }, /// A surface body's boundary edges through `edges` extended outward: by `distance`, or up /// to `up_to`; the surface continued (`mode` natural) or a run-off face along each edge /// (tangent, curvature). `neighbours`: the edges next to an extended edge are lengthened to /// meet it (else the extension's sides run square to the edge). SurfaceExtend { - #[walk(body)] - body: String, - #[walk(pos)] - edges: Vec, + body: BodyName, + edges: Vec, #[walk(length = "Distance")] - distance: String, + distance: Expr, #[serde(default, skip_serializing_if = "ExtendMode::is_natural")] mode: ExtendMode, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -1480,8 +1365,7 @@ pub enum FeatureKind { bulge: [f64; 2], /// Points the blend leaves towards, when the faces at the picks do not say: [from, to]. #[serde(default, skip_serializing_if = "Option::is_none")] - #[walk(pos)] - align: Option<[Vec3; 2]>, + align: 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, @@ -1489,25 +1373,21 @@ pub enum FeatureKind { /// A surface body trimmed by a plane, or by a face of a body (`tool`), keeping the side of /// `keep`. SurfaceTrim { - #[walk(body)] - body: String, + body: BodyName, plane: PlaneRef, #[serde(default, skip_serializing_if = "Option::is_none")] tool: Option, - #[walk(pos)] - keep: Vec3, + keep: Position, }, Move { - #[walk(body)] - bodies: Vec, + bodies: Vec, #[walk(length = ["X distance", "Y distance", "Z distance"])] - translate: [String; 3], + translate: [Expr; 3], #[serde(default, skip_serializing_if = "Option::is_none")] - #[walk(dir)] - rotate_axis: Option, + rotate_axis: Option, #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(angle = "Angle")] - angle: Option, + angle: Option, /// When set, the original bodies are kept and the transform is applied to a new copy /// of each instead of moving them in place. #[serde(default, skip_serializing_if = "std::ops::Not::not")] @@ -1532,10 +1412,9 @@ pub enum FeatureKind { }, /// Rebuild an upstream constant-section mesh with analytic planar/cylindrical faces. MeshConvert { - #[walk(body)] - body: String, + body: BodyName, #[walk(length = "Tolerance")] - tolerance: String, + tolerance: Expr, }, /// Mesh bodies imported from a 3MF or STL file, embedded in the design. MeshImport { @@ -1591,12 +1470,11 @@ pub enum FilletStyle { /// positions between (0 to 1 from the start end); straight between them, or `smooth`. Variable { #[walk(length = "End radius")] - radius2: String, - #[walk(pos)] - start: Vec3, + radius2: Expr, + start: Position, #[serde(default, skip_serializing_if = "Vec::is_empty")] #[walk(length = "Mid radius")] - mid: Vec<(f64, String)>, + mid: Vec<(f64, Expr)>, #[serde(default, skip_serializing_if = "std::ops::Not::not")] smooth: bool, }, @@ -1604,11 +1482,10 @@ pub enum FilletStyle { /// `start` (0) to the other (1): `radius` is its first control radius and `radii` the rest, /// its degree what `knots` leave (knots = control radii + degree + 1). Spline { - #[walk(pos)] - start: Vec3, + start: Position, knots: Vec, #[walk(length = |i: usize, n: usize| if i + 1 == n { "End radius" } else { "Control radius" })] - radii: Vec, + radii: Vec, }, } @@ -1657,10 +1534,8 @@ impl FilletStyle { /// A face picked by a point on it, on a named body. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, solidcraft_derive::Walk)] pub struct FaceAt { - #[walk(body)] - pub body: String, - #[walk(pos)] - pub point: Vec3, + pub body: BodyName, + pub point: Position, } /// One end of a blend: a body and the points that pick the edges of its boundary chain. With two @@ -1668,10 +1543,8 @@ pub struct FaceAt { /// pick (the order of the picks does not matter). #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, solidcraft_derive::Walk)] pub struct BlendSide { - #[walk(body)] - pub body: String, - #[walk(pos)] - pub edges: Vec, + pub body: BodyName, + pub edges: Vec, } /// How a patch on a loop of edges meets the faces beside the loop: every edge with `all`, but the @@ -1687,8 +1560,7 @@ pub struct PatchContinuity { /// One edge of a patch's loop (a point on it) and how the patch meets the face beside it. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, solidcraft_derive::Walk)] pub struct EdgeContinuity { - #[walk(pos)] - pub edge: Vec3, + pub edge: Position, pub g: Continuity, } @@ -1733,8 +1605,7 @@ pub struct MeshData { /// Points of a sketch, by id. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, solidcraft_derive::Walk)] pub struct SketchPoints { - #[walk(sketch)] - pub sketch: u64, + pub sketch: SketchId, pub ids: Vec, /// Drill the other way: away from the side the holes would go into by themselves. #[serde(default, skip_serializing_if = "std::ops::Not::not")] @@ -1755,8 +1626,7 @@ pub struct Component { /// One loft section: profiles of a sketch. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, solidcraft_derive::Walk)] pub struct LoftSection { - #[walk(sketch)] - pub sketch: u64, + pub sketch: SketchId, #[walk(profiles_of = sketch, when = point.is_none())] pub profiles: ProfileSel, /// A sketch point instead of a profile (the loft closes to it, as a pyramid's apex). @@ -1768,8 +1638,7 @@ pub struct LoftSection { /// meeting end to end). #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, solidcraft_derive::Walk)] pub struct SheetSection { - #[walk(sketch)] - pub sketch: u64, + pub sketch: SketchId, #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(profiles_of = sketch)] pub profiles: Option, @@ -1804,19 +1673,19 @@ pub enum HoleKind { Simple, Drilled { #[walk(angle = "Tip angle")] - tip_angle: String, + tip_angle: Expr, }, Counterbore { #[walk(length = "Counterbore diameter")] - cb_diameter: String, + cb_diameter: Expr, #[walk(length = "Counterbore depth")] - cb_depth: String, + cb_depth: Expr, }, Countersink { #[walk(length = "Countersink diameter")] - cs_diameter: String, + cs_diameter: Expr, #[walk(angle = "Countersink angle")] - cs_angle: String, + cs_angle: Expr, }, } @@ -1825,44 +1694,39 @@ pub enum HoleKind { #[serde(tag = "type", rename_all = "snake_case")] pub enum PatternKind { Rectangular { - #[walk(dir)] - dir1: Vec3, + dir1: Dir, #[walk(unitless = "Quantity")] - count1: String, + count1: Expr, #[walk(length = "Spacing")] - spacing1: String, + spacing1: Expr, #[serde(default, skip_serializing_if = "Option::is_none")] - #[walk(dir)] - dir2: Option, + dir2: Option, #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(unitless = "Quantity 2")] - count2: Option, + count2: Option, #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(length = "Spacing 2")] - spacing2: Option, + spacing2: Option, }, Circular { - #[walk(pos)] - origin: Vec3, - #[walk(dir)] - axis: Vec3, + origin: Position, + axis: Dir, #[walk(unitless = "Quantity")] - count: String, + count: Expr, /// Total angle (360 deg = evenly around). #[walk(angle = "Total angle")] - angle: String, + angle: Expr, }, /// Copies along a chain of sketch curves: instance k moves by path(k·spacing) − path(0), /// measured along the path from its start. Path { - #[walk(sketch)] - path_sketch: u64, + path_sketch: SketchId, path: Vec, #[walk(unitless = "Quantity")] - count: String, + count: Expr, /// Distance along the path between instances, or the whole extent when `extent`. #[walk(length = "Distance")] - spacing: String, + spacing: Expr, /// `spacing` is the distance from the first to the last instance. #[serde(default, skip_serializing_if = "std::ops::Not::not")] extent: bool, @@ -1875,17 +1739,17 @@ pub enum PatternKind { }, } -fn z_axis() -> Vec3 { - Vec3::Z +fn z_axis() -> Dir { + Dir(Vec3::Z) } /// A point whose coordinates are length expressions (`["basin_width / 2", "10 mm", "0"]`), so /// it follows parameter changes. Primitives are placed by one. -pub type PointExpr = [String; 3]; +pub type PointExpr = [Expr; 3]; /// A point as expressions (plain numbers, mm). pub fn point_expr(p: Vec3) -> PointExpr { - [format!("{}", p.x), format!("{}", p.y), format!("{}", p.z)] + [Expr::new(format!("{}", p.x)), Expr::new(format!("{}", p.y)), Expr::new(format!("{}", p.z))] } /// Stored as `[x, y, z]`: plain numbers as numbers (as points were before they took @@ -1901,17 +1765,17 @@ mod point_expr { } pub fn serialize(p: &super::PointExpr, s: S) -> Result { - let c = |e: &String| match e.parse::() { - Ok(v) if v.is_finite() && format!("{v}") == *e => Coord::Num(v), - _ => Coord::Expr(e.clone()), + let c = |e: &crate::Expr| match e.parse::() { + Ok(v) if v.is_finite() && format!("{v}") == e.as_str() => Coord::Num(v), + _ => Coord::Expr(e.to_string()), }; [c(&p[0]), c(&p[1]), c(&p[2])].serialize(s) } pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result { let c = |x: Coord| match x { - Coord::Num(v) => format!("{v}"), - Coord::Expr(e) => e, + Coord::Num(v) => crate::Expr::new(format!("{v}")), + Coord::Expr(e) => crate::Expr::new(e), }; let [x, y, z] = <[Coord; 3]>::deserialize(d)?; Ok([c(x), c(y), c(z)]) @@ -2151,7 +2015,7 @@ fn is_yes(b: &bool) -> bool { *b } -fn zero_expr() -> String { +fn zero_expr() -> Expr { "0".into() } @@ -2671,7 +2535,7 @@ impl Document { return Err(DocError::Invalid("too many features".into())); } let component = if let FeatureKind::BodyTransfer { bodies, from, to, transform } = &kind { - crate::validate_body_transfer(self, bodies, *from, *to, transform)?; + crate::validate_body_transfer(self, &crate::plain(bodies), *from, *to, transform)?; *to } else { 0 @@ -2727,7 +2591,7 @@ impl Document { return Err(DocError::Invalid(format!("feature `{}` belongs to an unknown component", f.name))); } if let FeatureKind::BodyTransfer { bodies, from, to, transform } = &f.kind { - crate::validate_body_transfer(self, bodies, *from, *to, transform)?; + crate::validate_body_transfer(self, &crate::plain(bodies), *from, *to, transform)?; if f.component != *to { return Err(DocError::Invalid("a body transfer belongs to its destination component".into())); } diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index e468e913f..8f54b1fa8 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -951,15 +951,15 @@ fn placement_digest(doc: &Document, f: &Feature) -> u64 { _ => None, }; if let Some(path) = path - && doc.sketch(path).is_ok_and(|sketch| !sketch.wires.is_empty()) + && doc.sketch(path.0).is_ok_and(|sketch| !sketch.wires.is_empty()) { let mut hash = std::collections::hash_map::DefaultHasher::new(); - let owner = doc.feature(path).map(|feature| feature.component).unwrap_or(0); + let owner = 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, .. } | FeatureKind::SurfaceSweep { sketch, .. } = &f.kind { - let owner = doc.feature(*sketch).map(|feature| feature.component).unwrap_or(0); + 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(); @@ -1951,7 +1951,7 @@ fn face_level_at(st: &ModelState, plane: &Plane, h: f64, targets: &[String]) -> /// The body a face-based feature applies to: by name, or the one whose surface is nearest the /// first point. -fn body_at(st: &ModelState, body: &Option, points: &[Vec3]) -> Result { +fn body_at(st: &ModelState, body: &Option, points: &[Vec3]) -> Result { if let Some(n) = body { return st.bodies.iter().position(|b| &b.name == n).ok_or_else(|| DocError::Unknown(format!("body `{n}`"))); } @@ -2085,7 +2085,7 @@ fn edge_dir(e: &kernel::EdgeInfo) -> Vec3 { } /// References for edges picked at `pts` on the body a blend would go on (the state before it). -pub fn edge_refs(st: &ModelState, body: &Option, pts: &[Vec3]) -> Vec { +pub fn edge_refs(st: &ModelState, body: &Option, pts: &[Vec3]) -> Vec { let Ok(ti) = blend_target(st, body, pts) else { return Vec::new() }; let Some(mb) = st.bodies.get(ti) else { return Vec::new() }; let size = mb.body.size(); @@ -2103,7 +2103,7 @@ pub fn edge_refs(st: &ModelState, body: &Option, pts: &[Vec3]) -> Vec, pts: &[Vec3]) -> Vec { +pub fn edge_names_for(st: &ModelState, body: &Option, pts: &[Vec3]) -> Vec { match blend_target(st, body, pts).ok().and_then(|i| st.bodies.get(i)) { Some(b) => crate::naming::edge_names_at(b, pts), None => Vec::new(), @@ -2190,7 +2190,7 @@ fn resolve_edges(b: &Body, pts: &[Vec3], refs: &[EdgeRef], warning: &mut Option< } /// The body a fillet/chamfer applies to: by name, or the one closest to the first edge point. -fn blend_target(state: &ModelState, body: &Option, edges: &[Vec3]) -> Result { +fn blend_target(state: &ModelState, body: &Option, edges: &[Vec3]) -> Result { if let Some(n) = body { return state.bodies.iter().position(|b| &b.name == n).ok_or_else(|| DocError::Unknown(format!("body `{n}`"))); } @@ -2246,10 +2246,10 @@ pub(crate) fn revolve_axis(ss: &SolvedSketch, axis: &AxisRef) -> Result<(Vec2, V AxisRef::Line { origin, dir } => { let pl = &ss.plane; let d = dir.normalized().ok_or_else(|| DocError::Invalid("revolve axis has no direction".into()))?; - if d.dot(pl.normal()).abs() > 1e-9 || pl.height(*origin).abs() > 1e-6 { + if d.dot(pl.normal()).abs() > 1e-9 || pl.height(origin.0).abs() > 1e-6 { return Err(DocError::Invalid("the revolve axis does not lie in the sketch plane".into())); } - Ok((pl.to_local(*origin), Vec2::new(d.dot(pl.x), d.dot(pl.y)))) + Ok((pl.to_local(origin.0), Vec2::new(d.dot(pl.x), d.dot(pl.y)))) } } } @@ -2303,7 +2303,8 @@ fn hole_spots(st: &ModelState, f: &Feature) -> Result<(Vec, Vec3)> { let FeatureKind::Hole { position, direction, points, .. } = &f.kind else { return Err(DocError::Invalid("not a hole".into())) }; let (spots, dir) = match points { Some(sp) => { - let ss = st.sketch(sp.sketch).ok_or_else(|| DocError::Unknown(format!("sketch {} (it must come earlier in the timeline)", sp.sketch)))?; + let ss = + st.sketch(sp.sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {} (it must come earlier in the timeline)", sp.sketch)))?; let mut v = Vec::new(); for id in &sp.ids { let p = ss.sketch.points.iter().find(|p| &p.id == id).ok_or_else(|| DocError::Unknown(format!("sketch point `{id}`")))?; @@ -2315,7 +2316,7 @@ fn hole_spots(st: &ModelState, f: &Feature) -> Result<(Vec, Vec3)> { } None => { let dir = direction.normalized().ok_or_else(|| DocError::Invalid("hole direction".into()))?; - let at = hole_on_surface(st, *position, dir); + let at = hole_on_surface(st, position.0, dir); let dir = hole_dir_into_face(st, at, dir); return Ok((vec![hole_on_surface(st, at, dir)], dir)); } @@ -2328,7 +2329,7 @@ fn hole_spots(st: &ModelState, f: &Feature) -> Result<(Vec, Vec3)> { /// A hole's depth: down to the To Object (where the hole's axis meets the face there, else the /// point's depth along the axis), else as given. -fn hole_depth_to(st: &ModelState, at: &Vec3, dir: Vec3, to: &Option, depth: &Option) -> Result> { +fn hole_depth_to(st: &ModelState, at: &Vec3, dir: Vec3, to: &Option, depth: &Option) -> Result> { let Some(t) = to else { return Ok(depth.clone()) }; let mut d = (*t - *at).dot(dir); // The face at the To point, met along the axis. @@ -2345,7 +2346,7 @@ fn hole_depth_to(st: &ModelState, at: &Vec3, dir: Vec3, to: &Option, depth if !(d > 1e-6) { return Err(DocError::Invalid("the hole's To object is not ahead of the hole".into())); } - Ok(Some(format!("{d} mm"))) + Ok(Some(format!("{d} mm").into())) } /// A hole's spots as given (not yet moved onto the surface) and its direction. @@ -2353,7 +2354,7 @@ fn hole_spots_raw(st: &ModelState, f: &Feature) -> Result<(Vec, Vec3)> { let FeatureKind::Hole { position, direction, points, .. } = &f.kind else { return Err(DocError::Invalid("not a hole".into())) }; match points { Some(sp) => { - let ss = st.sketch(sp.sketch).ok_or_else(|| DocError::Unknown(format!("sketch {}", sp.sketch)))?; + let ss = st.sketch(sp.sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {}", sp.sketch)))?; let v: Vec = sp.ids.iter().filter_map(|id| ss.sketch.points.iter().find(|p| &p.id == id)).map(|p| ss.plane.to_world(p.pos)).take(10_000).collect(); let dir = sketch_hole_dir(st, &v, ss.plane.normal()); @@ -2362,7 +2363,7 @@ fn hole_spots_raw(st: &ModelState, f: &Feature) -> Result<(Vec, Vec3)> { } None => { let dir = direction.normalized().ok_or_else(|| DocError::Invalid("hole direction".into()))?; - Ok((vec![*position], hole_dir_into_face(st, hole_on_surface(st, *position, dir), dir))) + Ok((vec![position.0], hole_dir_into_face(st, hole_on_surface(st, position.0, dir), dir))) } } } @@ -2377,7 +2378,7 @@ fn hole_feature_tools(vals: &BTreeMap, st: &ModelState, f: &Featu } let mut tools = Vec::new(); for at in spots { - let depth = hole_depth_to(st, &at, dir, to, depth)?; + let depth = hole_depth_to(st, &at, dir, &to.map(Vec3::from), depth)?; tools.extend(hole_tools_and_prisms(vals, st, &at, dir, diameter, &depth, hole)?); } Ok(tools) @@ -2454,7 +2455,7 @@ fn hole_tools( position: &Vec3, dir: Vec3, diameter: &str, - depth: &Option, + depth: &Option, hole: &HoleKind, ) -> Result> { Ok(hole_tools_and_prisms(vals, st, position, dir, diameter, depth, hole)?.into_iter().map(|(tool, _)| tool).collect()) @@ -2471,7 +2472,7 @@ fn hole_tools_and_prisms( position: &Vec3, dir: Vec3, diameter: &str, - depth: &Option, + depth: &Option, hole: &HoleKind, ) -> Result)>> { let r = val(vals, diameter, Kind::Length)? / 2.0; @@ -2746,7 +2747,7 @@ fn feature_tools_with_constructor( FeatureKind::Extrude { sketch, profiles, extent, operation, targets, thin } => { let ss = sketch_in_feature_frame( doc, - st.sketch(*sketch).ok_or_else(|| DocError::Unknown(format!("sketch {sketch} (it must come earlier in the timeline)")))?, + st.sketch(sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {sketch} (it must come earlier in the timeline)")))?, f.component, )?; let regions = match thin { @@ -2762,14 +2763,14 @@ fn feature_tools_with_constructor( // The face names follow `face_points`: To, then From. let name = |k: usize| f.face_names.get(k).map(String::as_str); let (to_name, from_name) = if extent.to.is_some() { (name(0), name(1)) } else { (None, name(0)) }; - let to_face = extent.to.and_then(|p| object_face(&tst, to_name, p)); + let to_face = extent.to.and_then(|p| object_face(&tst, to_name, p.0)); let centre = { let pts: Vec = regions.iter().flat_map(|r| r.outer.polyline(1e-2)).collect(); let c = pts.iter().fold(Vec2::default(), |a, p| a + *p) * (1.0 / pts.len().max(1) as f64); ss.plane.to_world(c) }; let from = match extent.from { - Some(p) => height_at(&tst, object_face(&tst, from_name, p), &ss.plane, centre, p), + Some(p) => height_at(&tst, object_face(&tst, from_name, p.0), &ss.plane, centre, p.0), None => 0.0, }; let d = match extent.to { @@ -2778,7 +2779,7 @@ fn feature_tools_with_constructor( Some(e) => val(vals, e, Kind::Length)?, None => 0.0, }; - let h = height_at(&tst, to_face, &ss.plane, centre, p); + let h = height_at(&tst, to_face, &ss.plane, centre, p.0); let start = from + extent.start_offset.as_deref().map(|e| val(vals, e, Kind::Length)).transpose()?.unwrap_or(0.0); // Past the face by the offset, in the direction travelled. let to = h + if h >= start { off } else { -off }; @@ -2787,7 +2788,7 @@ fn feature_tools_with_constructor( } to - start } - None if extent.through_all => through_all_distance(st, &ss.plane, targets)?, + None if extent.through_all => through_all_distance(st, &ss.plane, &crate::plain(targets))?, None => val(vals, &extent.distance, Kind::Length)?, }; if let Some(tp) = &extent.taper { @@ -2805,7 +2806,7 @@ fn feature_tools_with_constructor( // How far a tool grows past its profile at either end, at most. let mut growth: f64 = 0.0; // A face of the targets in the profile's plane (the same for every profile). - let on_face = matches!(operation, Operation::Join | Operation::Cut) && face_level_at(st, &ss.plane, from, targets); + let on_face = matches!(operation, Operation::Join | Operation::Cut) && face_level_at(st, &ss.plane, from, &crate::plain(targets)); let tools: Vec = regions .iter() .map(|r| { @@ -2814,7 +2815,7 @@ fn feature_tools_with_constructor( // and the boolean finds no result there. The sides keep their slope, so // the profile stays the section at the start. let (lo, hi) = if sign < 0.0 { (from - len, from) } else { (from, from + len) }; - let (l2, h2) = extend_for_coplanar(st, &ss.plane, r, lo, hi, *operation, targets); + let (l2, h2) = extend_for_coplanar(st, &ss.plane, r, lo, hi, *operation, &crate::plain(targets)); let (a, b) = if sign < 0.0 { (from - h2, from - l2) } else { (l2 - from, h2 - from) }; // A start that can't run on (the profile hangs over the face's edge): // the sides stand straight for a hair first, so the boolean can push the @@ -2882,7 +2883,7 @@ fn feature_tools_with_constructor( if exact.iter().all(|tool| { st.bodies .iter() - .filter(|b| targets.is_empty() || targets.contains(&b.name)) + .filter(|b| targets.is_empty() || targets.iter().any(|t| *t == b.name)) .any(|b| kernel::can_join_touching_faces(&b.body, &tool.body)) }) { // Preserve a whole touching face: extending into a chamfer replaces @@ -2893,11 +2894,12 @@ fn feature_tools_with_constructor( continue; } } - let (l2, h2) = extend_for_coplanar(st, &ss.plane, r, lo + off, hi + off, *operation, targets); + let (l2, h2) = extend_for_coplanar(st, &ss.plane, r, lo + off, hi + off, *operation, &crate::plain(targets)); let probe = |p: Vec2| (1..4).map(|k| ss.plane.to_world(p) + n * (lo + off + (hi - lo) * k as f64 / 4.0)).collect::>(); let original = r; - let r = grow_profile_for_coplanar(st, r, *operation, targets, &probe); - let r = fill_void_holes(st, &r, *operation, targets, &ss.plane, (l2, h2)); + let plain_targets = crate::plain(targets); + let r = grow_profile_for_coplanar(st, r, *operation, &plain_targets, &probe); + let r = fill_void_holes(st, &r, *operation, &plain_targets, &ss.plane, (l2, h2)); untrimmed &= l2 == lo + off && h2 == hi + off && &r == original; tools.extend(centered_extrude(&ss.plane, &r, l2, h2, Some(&ss))?); footprints.push(r); @@ -2973,7 +2975,7 @@ fn feature_tools_with_constructor( } } // Certificates set face sources only: the faces, and their lineage, stay. - let body = body.with_extrude_certificates(f.id, *sketch, &curves)?.with_extrude_cap_certificates(f.id, *sketch, &caps)?; + let body = body.with_extrude_certificates(f.id, sketch.0, &curves)?.with_extrude_cap_certificates(f.id, sketch.0, &caps)?; Ok(Traced { body, lineage }) }) .collect::>>()?; @@ -2983,7 +2985,7 @@ fn feature_tools_with_constructor( FeatureKind::Revolve { sketch, profiles, axis, angle, angle2, symmetric, convention, to, .. } => { let ss = sketch_in_feature_frame( doc, - st.sketch(*sketch).ok_or_else(|| DocError::Unknown(format!("sketch {sketch} (it must come earlier in the timeline)")))?, + st.sketch(sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {sketch} (it must come earlier in the timeline)")))?, f.component, )?; let regions = solidcraft_sketch::merge_regions(&select_profiles(&ss, profiles)?); @@ -3002,7 +3004,7 @@ fn feature_tools_with_constructor( (ss.plane.to_world(o), ss.plane.dir_to_world(d)), angles, *symmetric, - *to, + to.map(Vec3::from), *convention, )?; let (start, ang) = (extent.start, extent.sweep); @@ -3017,7 +3019,7 @@ fn feature_tools_with_constructor( (ss.plane.to_world(o), ss.plane.dir_to_world(d)), angles, *symmetric, - *to, + to.map(Vec3::from), *convention, ) } else { @@ -3052,7 +3054,7 @@ fn feature_tools_with_constructor( .collect::>>()?; // To a curved face: turn past the whole target body, then cut back to its surface // (the piece that starts at the profile). - let curved = curved_face(&tst, to.and_then(|p| object_face(&tst, f.face_names.first().map(String::as_str), p)), None); + let curved = curved_face(&tst, to.and_then(|p| object_face(&tst, f.face_names.first().map(String::as_str), p.0)), None); let curved_body = curved.and_then(|bi| tst.bodies.get(bi)); // Each region's body: its sides named by the sketch curves, its caps start and end. let tool = |r: &Region2, body: Body, built: Option<&Body>| crate::lineage::ProfileRoles::swept(Some(&ss), Some(r)).tool(body, built); @@ -3114,11 +3116,11 @@ fn feature_tools_with_constructor( // A profile lofted to a sketch point (an apex). 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).ok_or_else(|| DocError::Unknown(format!("sketch {}", prof.sketch)))?; + let ss = st.sketch(prof.sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {}", prof.sketch)))?; let regions = solidcraft_sketch::merge_regions(&select_profiles(ss, &prof.profiles)?); let [r] = ®ions[..] else { return Err(DocError::Invalid("each loft section must be one profile".into())) }; refuse_loft_holes(r)?; - let ps = st.sketch(pt.sketch).ok_or_else(|| DocError::Unknown(format!("sketch {}", pt.sketch)))?; + let ps = st.sketch(pt.sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {}", pt.sketch)))?; let id = pt.point.as_deref().unwrap_or_default(); let q = ps.sketch.points.iter().find(|p| p.id == id).ok_or_else(|| DocError::Unknown(format!("point `{id}` in {}", ps.name)))?; let body = kernel::loft_to_point(&ss.plane, &r.outer, ps.plane.to_world(q.pos))?; @@ -3169,7 +3171,7 @@ fn feature_tools_with_constructor( let mut sketches = Vec::new(); for sec in sections { let ss = st - .sketch(sec.sketch) + .sketch(sec.sketch.0) .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())) }; @@ -3185,9 +3187,9 @@ fn feature_tools_with_constructor( } FeatureKind::Sweep { sketch, profiles, path_sketch, path, orientation, twist, scale, .. } => { let ctl = sweep_control(vals, orientation, twist, scale)?; - let ss = st.sketch(*sketch).ok_or_else(|| DocError::Unknown(format!("sketch {sketch} (it must come earlier in the timeline)")))?; + let ss = st.sketch(sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {sketch} (it must come earlier in the timeline)")))?; let ps = - st.sketch(*path_sketch).ok_or_else(|| DocError::Unknown(format!("sketch {path_sketch} (it must come earlier in the timeline)")))?; + st.sketch(path_sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {path_sketch} (it must come earlier in the timeline)")))?; let profile; let ss = if !ps.sketch.wires.is_empty() { profile = profile_in_frame(doc, ss, f.component)?; @@ -3209,7 +3211,7 @@ fn feature_tools_with_constructor( } FeatureKind::Pipe { path_sketch, path, diameter, wall, .. } => { let ps = - st.sketch(*path_sketch).ok_or_else(|| DocError::Unknown(format!("sketch {path_sketch} (it must come earlier in the timeline)")))?; + st.sketch(path_sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {path_sketch} (it must come earlier in the timeline)")))?; let mapped = path_in_frame(doc, ps, f.component)?; let ps = mapped.as_ref(); let r = val(vals, diameter, Kind::Length)? / 2.0; @@ -3239,7 +3241,7 @@ fn feature_tools_with_constructor( } FeatureKind::Cylinder { base, axis, radius, height, .. } => Ok(vec![crate::lineage::cylinder_tool(kernel::cylinder( point(vals, base)?, - *axis, + axis.0, val(vals, radius, Kind::Length)?, val(vals, height, Kind::Length)?, )?)]), @@ -3258,13 +3260,13 @@ fn feature_tools_with_constructor( pub(crate) fn sweep_control( vals: &BTreeMap, orientation: &crate::SweepOrientation, - twist: &Option, - scale: &Option, + twist: &Option, + scale: &Option, ) -> Result { let orientation = match *orientation { crate::SweepOrientation::Perpendicular => kernel::SweepOrientation::Perpendicular, crate::SweepOrientation::Parallel => kernel::SweepOrientation::Parallel, - crate::SweepOrientation::Direction(d) => kernel::SweepOrientation::Direction(d), + crate::SweepOrientation::Direction(d) => kernel::SweepOrientation::Direction(d.0), }; let twist = match twist { Some(t) => val(vals, t, Kind::Angle)?, @@ -3280,7 +3282,7 @@ pub(crate) fn sweep_control( } /// A pipe's section: a circle of radius `r`, hollow when it has a wall. -fn pipe_region(vals: &BTreeMap, r: f64, wall: &Option) -> Result { +fn pipe_region(vals: &BTreeMap, r: f64, wall: &Option) -> Result { let holes = match wall { Some(w) => { let wt = val(vals, w, Kind::Length)?; @@ -3485,15 +3487,15 @@ pub(crate) fn extent_sides(vals: &BTreeMap, extent: &crate::Exten /// Operation and targets of a feature that makes tools. fn feature_op(f: &Feature) -> (Operation, Vec) { match &f.kind { - FeatureKind::Extrude { operation, targets, .. } | FeatureKind::Revolve { operation, targets, .. } => (*operation, targets.clone()), + FeatureKind::Extrude { operation, targets, .. } | FeatureKind::Revolve { operation, targets, .. } => (*operation, crate::plain(targets)), FeatureKind::Box { operation, .. } | FeatureKind::Cylinder { operation, .. } | FeatureKind::Sphere { operation, .. } | FeatureKind::Torus { operation, .. } => (*operation, Vec::new()), FeatureKind::Hole { .. } => (Operation::Cut, Vec::new()), - FeatureKind::Pipe { operation, targets, .. } => (*operation, targets.clone()), - FeatureKind::Loft { operation, targets, .. } | FeatureKind::Sweep { operation, targets, .. } => (*operation, targets.clone()), - FeatureKind::Coil { operation, targets, .. } => (*operation, targets.clone()), + FeatureKind::Pipe { operation, targets, .. } => (*operation, crate::plain(targets)), + FeatureKind::Loft { operation, targets, .. } | FeatureKind::Sweep { operation, targets, .. } => (*operation, crate::plain(targets)), + FeatureKind::Coil { operation, targets, .. } => (*operation, crate::plain(targets)), _ => (Operation::NewBody, Vec::new()), } } @@ -3583,7 +3585,7 @@ fn pattern_transforms(doc: &Document, vals: &BTreeMap, st: &Model crate::PatternKind::Path { path_sketch, path, count: c, spacing, extent, flip, orient } => { let n = count(c)?; let d = val(vals, spacing, Kind::Length)?; - let ps = st.sketch(*path_sketch).ok_or_else(|| DocError::Unknown(format!("path sketch {path_sketch}")))?; + let ps = st.sketch(path_sketch.0).ok_or_else(|| DocError::Unknown(format!("path sketch {path_sketch}")))?; let mapped = path_in_frame(doc, ps, component)?; let ps = mapped.as_ref(); let mut segs = path_segments(ps, path, Vec3::new(f64::NAN, f64::NAN, f64::NAN))?; @@ -3625,7 +3627,7 @@ fn pattern_transforms(doc: &Document, vals: &BTreeMap, st: &Model 0.0 }; for i in 1..n { - out.push(rotation(*origin, *axis, step * i as f64)); + out.push(rotation(origin.0, axis.0, step * i as f64)); } } } @@ -3722,7 +3724,7 @@ fn replay( let r = val(vals, radius, Kind::Length)?; // The edges the feature blended in this evaluation (found by name), falling back to // its picked points. - let found = st.blend_edges.get(&src.id).cloned().unwrap_or_else(|| edges.clone()); + let found = st.blend_edges.get(&src.id).cloned().unwrap_or_else(|| crate::plain(edges)); for m in mats { let moved: Vec = found.iter().map(|p| crate::apply_point(m, *p)).collect(); let ti = blend_target(st, &None, &moved)?; @@ -3757,7 +3759,7 @@ fn replay( let d = crate::apply_vector(m, dir).normalized().ok_or_else(|| DocError::Invalid("hole direction".into()))?; for p in &spots { let at = hole_on_surface(st, crate::apply_point(m, *p), d); - let to = to.map(|t| crate::apply_point(m, t)); + let to = to.map(|t| crate::apply_point(m, t.0)); let depth = hole_depth_to(st, &at, d, &to, depth)?; // Each copy's faces are named as the hole's, with the instance. copies.extend( @@ -4085,8 +4087,8 @@ fn chamfer_with( b: &kernel::Body, edges: &[Vec3], d: f64, - distance2: &Option, - angle: &Option, + distance2: &Option, + angle: &Option, flip: bool, ) -> Result { let side = match (distance2, angle) { @@ -4102,7 +4104,9 @@ fn chamfer_with( fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: &mut ModelState, warning: &mut Option) -> Result<()> { match &f.kind { - FeatureKind::BodyTransfer { bodies, from, to, transform } => crate::body_transfer::evaluate(doc, st, bodies, *from, *to, *transform), + FeatureKind::BodyTransfer { bodies, from, to, transform } => { + crate::body_transfer::evaluate(doc, st, &crate::plain(bodies), *from, *to, *transform) + } FeatureKind::SheetBase { .. } | FeatureKind::SheetContour { .. } | FeatureKind::SheetFlange { .. } @@ -4189,12 +4193,12 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: // Cuts through sheet metal become cut-outs of its flat pattern. if matches!(operation, Operation::Cut | Operation::Intersect) && matches!(f.kind, FeatureKind::Extrude { .. }) && !st.sheets.is_empty() { let bodies: Vec = tools.iter().map(|t| t.body.clone()).collect(); - let handled = more::sheet_cut(f, st, &bodies, targets, constructor.as_ref(), warning)?; + let handled = more::sheet_cut(f, st, &bodies, &crate::plain(targets), constructor.as_ref(), warning)?; if !handled.is_empty() { - return apply_beside_sheet_cut(st, f, tools, *operation, targets, &handled); + return apply_beside_sheet_cut(st, f, tools, *operation, &crate::plain(targets), &handled); } } - apply_traced(st, f, tools, *operation, targets) + apply_traced(st, f, tools, *operation, &crate::plain(targets)) } FeatureKind::Hole { thread, diameter, .. } => { let (spots, dir) = hole_spots(st, f)?; @@ -4222,14 +4226,14 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: Some(e) => Some(val(vals, e, Kind::Length)?), None => None, }; - let t = thread_on(st, f.id, *face, designation.as_deref(), l)?; + let t = thread_on(st, f.id, face.0, designation.as_deref(), l)?; if !*modeled { st.threads.push(t); return Ok(()); } let i = st.bodies.iter().position(|b| b.name == t.body).ok_or_else(|| DocError::Invalid("threaded body".into()))?; let Some(mb) = st.bodies.get(i).cloned() else { return Err(DocError::Invalid("body".into())) }; - let cyl = kernel::cylinder_face_at(&mb.body, *face).ok_or_else(|| DocError::Invalid("no cylindrical face there to thread".into()))?; + let cyl = kernel::cylinder_face_at(&mb.body, face.0).ok_or_else(|| DocError::Invalid("no cylindrical face there to thread".into()))?; let tol = t.pitch * 1e-3; let groove = thread_groove(&t, cyl.radius, ((t.start - cyl.start).abs() < tol, (t.end - cyl.end).abs() < tol))?; // The B-rep boolean can't take helical walls in reasonable time: the body is cut @@ -4247,9 +4251,9 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: } FeatureKind::Shell { faces, thickness, body, direction, tangent_chain } => { let t = val(vals, thickness, Kind::Length)?; - let i = body_at(st, body, faces)?; + 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 open = if *tangent_chain { smooth_chain(&mb, faces) } else { faces.clone() }; + let open = if *tangent_chain { smooth_chain(&mb, &crate::plain(faces)) } else { crate::plain(faces) }; let input = mb.traced(); // The shell, and the operands of the operation that made it. let (nb, operands) = match direction.as_str() { @@ -4286,9 +4290,9 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: FeatureKind::Draft { faces, angle, neutral, pull, body } => { let a = val(vals, angle, Kind::Angle)?; let pl = doc.resolve_plane_in(vals, neutral, 0, Some(st))?; - let i = body_at(st, body, faces)?; + 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 nb = Traced::step(kernel::draft(&mb.body, faces, &pl, *pull, a)?, &[&mb.traced()]); + let nb = Traced::step(kernel::draft(&mb.body, &crate::plain(faces), &pl, pull.0, a)?, &[&mb.traced()]); if let Some(slot) = st.bodies.get_mut(i) { *slot = ModelBody::traced_new(mb.name, nb, mb.feature); } @@ -4332,7 +4336,7 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: let mut made = Vec::new(); for p in cells { // The cell: inside the tools that hold the point, outside the others. - let inside: Vec = tb.iter().map(|b| b.mesh().contains(*p)).collect(); + let inside: Vec = tb.iter().map(|b| b.mesh().contains(p.0)).collect(); let mut acc: Option = None; for (b, _) in tb.iter().zip(&inside).filter(|(_, i)| **i) { acc = match acc { @@ -4350,16 +4354,16 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: made.push(cell); } if *remove_tools { - st.bodies.retain(|b| !tools.contains(&b.name)); + st.bodies.retain(|b| !tools.iter().any(|t| *t == b.name)); } apply_traced(st, f, made, *operation, &[]) } FeatureKind::SplitFace { faces, body, plane, tool, sketch } => { - let i = body_at(st, body, faces)?; + 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 picked: Vec = Vec::new(); for p in faces { - let fi = crate::appearance::face_index_at(&mb, *p) + let fi = crate::appearance::face_index_at(&mb, p.0) .ok_or_else(|| DocError::Invalid(format!("Split Face: no face of {} at {p:?}", mb.name)))?; if !picked.contains(&fi) { picked.push(fi); @@ -4368,12 +4372,12 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: let nb = match (tool, sketch) { (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) + 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::split_faces(&mb.body, &picked, &kernel::SplitTool::Face { body: &tb.body, face })? } (None, Some(sid)) => { - let ss = st.sketch(*sid).ok_or_else(|| DocError::Unknown(format!("sketch {sid}")))?; + let ss = st.sketch(sid.0).ok_or_else(|| DocError::Unknown(format!("sketch {sid}")))?; // Each curve's exact segments (lines and arcs split by their own plane and cylinder). let curves: Vec> = (0..ss.sketch.curves.len()) .filter(|ci| ss.sketch.curves.get(*ci).is_some_and(|c| !c.construction)) @@ -4403,7 +4407,7 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: // A face of a body (its surface extended). 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) + 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::split_body(&mb.body, &kernel::SplitTool::Face { body: &tb.body, face })? } @@ -4432,7 +4436,7 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: FeatureKind::Pattern { features, pattern, bodies } => { let mats = pattern_transforms(doc, vals, st, f.component, pattern)?; if bodies.is_empty() { - return replay(doc, vals, f, st, features, &mats, warning); + return replay(doc, vals, f, st, &crate::plain(features), &mats, warning); } // Bodies: each copy is a new body named after its source. let mut output = 0; @@ -4450,7 +4454,7 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: FeatureKind::Mirror { features, plane, bodies, combine } => { let pl = doc.resolve_plane_in(vals, plane, 0, Some(st))?; if bodies.is_empty() { - return replay(doc, vals, f, st, features, &[mirror_matrix(&pl)], warning); + return replay(doc, vals, f, st, &crate::plain(features), &[mirror_matrix(&pl)], warning); } let m = mirror_matrix(&pl); let mut output = 0; @@ -4485,13 +4489,13 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: } FeatureKind::Fillet { edges, radius, body, .. } | FeatureKind::Chamfer { edges, distance: radius, body, .. } => { let r = val(vals, radius, Kind::Length)?; - let ti = blend_target(st, body, edges)?; + let ti = blend_target(st, body, &crate::plain(edges))?; let Some(mb) = st.bodies.get(ti) else { return Err(DocError::Invalid("body".into())) }; let edges = if f.edge_names.iter().any(|n| !n.is_empty()) { // By name first; a name that is gone falls back to the point, with a warning. let (mut out, mut notes) = (Vec::new(), Vec::new()); for (i, p) in edges.iter().enumerate() { - match f.edge_names.get(i).filter(|n| !n.is_empty()).map(|n| (n, crate::naming::locate_edge(mb, n, *p))) { + match f.edge_names.get(i).filter(|n| !n.is_empty()).map(|n| (n, crate::naming::locate_edge(mb, n, p.0))) { Some((n, Ok(hit))) => { if let Some(note) = hit.note(n) { notes.push(note); @@ -4506,9 +4510,9 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: // The name is gone. A pick on the axis of a round must not fall // through to the tangency seam (#775). A sharp edge that moved // still resolves from the point, which an edit relies on. - if pick_lies_on_a_round_axis(&mb.body, *p) { + if pick_lies_on_a_round_axis(&mb.body, p.0) { notes.push(skipped); - } else if let Ok(q) = resolve_edges(&mb.body, &[*p], &refs, &mut w) { + } else if let Ok(q) = resolve_edges(&mb.body, &[p.0], &refs, &mut w) { out.extend(q); notes.push(match f.edge_names.get(i) { Some(n) if !n.is_empty() => format!("edge `{n}` no longer exists; using the edge at the picked point"), @@ -4529,7 +4533,7 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: } out } else { - resolve_edges(&mb.body, edges, &f.edge_refs, warning)? + resolve_edges(&mb.body, &crate::plain(edges), &f.edge_refs, warning)? }; st.blend_edges.insert(f.id, edges.clone()); let input = mb.traced(); @@ -4543,7 +4547,7 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: for (t, e) in mid { pts.push((*t, val(vals, e, Kind::Length)?)); } - one_by_one(input, &edges, |b, p| kernel::fillet_variable_points(b, p, *start, &pts, *smooth))? + one_by_one(input, &edges, |b, p| kernel::fillet_variable_points(b, p, start.0, &pts, *smooth))? } FeatureKind::Fillet { style: crate::FilletStyle::Spline { start, knots, radii }, .. } => { let mut values = vec![r]; @@ -4551,7 +4555,7 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: values.push(val(vals, e, Kind::Length)?); } let law = crate::FilletStyle::spline(knots, values); - one_by_one(input, &edges, |b, p| kernel::fillet_variable_spline(b, p, *start, &law))? + one_by_one(input, &edges, |b, p| kernel::fillet_variable_spline(b, p, start.0, &law))? } FeatureKind::Fillet { fit: crate::FilletFit::Taper, .. } => { let (b, tapers) = kernel::fillet_tapered(&mb.body, &edges, r)?; @@ -4598,9 +4602,9 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: } FeatureKind::Cylinder { base, axis, radius, height, operation } => { let (base, radius, height) = (point(vals, base)?, val(vals, radius, Kind::Length)?, val(vals, height, Kind::Length)?); - let b = kernel::cylinder(base, *axis, radius, height)?; + let b = kernel::cylinder(base, axis.0, radius, height)?; let b = if matches!(operation, Operation::NewBody | Operation::Join) { b.with_cylinder_certificate(f.id)? } else { b }; - let prism = more::PrimitivePrism::Cylinder { base, axis: *axis, radius, height }; + let prism = more::PrimitivePrism::Cylinder { base, axis: axis.0, radius, height }; let handled = more::sheet_primitive_cut(f, st, &b, prism, *operation, false, warning)?; let tools = vec![crate::lineage::cylinder_tool(b)]; if !handled.is_empty() { @@ -4628,9 +4632,9 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: return Err(DocError::Unknown(format!("body `{target}`"))); } let op = if *operation == Operation::NewBody { Operation::Join } else { *operation }; - apply_traced(st, f, tb, op, std::slice::from_ref(target))?; + apply_traced(st, f, tb, op, std::slice::from_ref(&target.0))?; if !keep_tools { - st.bodies.retain(|b| !tools.contains(&b.name)); + st.bodies.retain(|b| !tools.iter().any(|t| *t == b.name)); } Ok(()) } @@ -4664,20 +4668,20 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: } FeatureKind::OffsetFace { faces, distance, body } => { let d = val(vals, distance, Kind::Length)?; - let i = body_at(st, body, faces)?; + 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 nb = Traced::step(kernel::offset_faces(&mb.body, faces, d)?, &[&mb.traced()]); + let nb = Traced::step(kernel::offset_faces(&mb.body, &crate::plain(faces), d)?, &[&mb.traced()]); if let Some(slot) = st.bodies.get_mut(i) { *slot = ModelBody::traced_new(mb.name, nb, mb.feature); } Ok(()) } FeatureKind::DeleteFace { faces, body, heal } => { - let i = body_at(st, body, faces)?; + 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 picked: Vec = Vec::new(); for p in faces { - let fi = crate::appearance::face_index_at(&mb, *p) + let fi = crate::appearance::face_index_at(&mb, p.0) .ok_or_else(|| DocError::Invalid(format!("Delete Face: no face of {} at {p:?}", mb.name)))?; if !picked.contains(&fi) { picked.push(fi); @@ -4694,7 +4698,7 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: FeatureKind::BoundingSolid { bodies, margin } => { let m = val(vals, margin, Kind::Length)?; let mut bb = solidcraft_geom::Aabb3::EMPTY; - for b in st.bodies.iter().filter(|b| bodies.is_empty() || bodies.contains(&b.name)) { + for b in st.bodies.iter().filter(|b| bodies.is_empty() || bodies.iter().any(|t| *t == b.name)) { bb = bb.union(&b.mesh().bounds()); } if bb.is_empty() { @@ -4713,7 +4717,7 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: Some(a) => val(vals, a, Kind::Angle)?, None => 0.0, }; - let axis = rotate_axis.unwrap_or(Vec3::Z); + let axis = rotate_axis.map(Vec3::from).unwrap_or(Vec3::Z); // With `copy` set, the source body is kept in place and the transform lands on a new // body pushed beside it instead of replacing it. let mut output = 0; @@ -5215,7 +5219,7 @@ mod chain_tests { .unwrap(); doc.add_feature( FeatureKind::Fillet { - edges: vec![Vec3::new(20.0, 0.0, 20.0)], + edges: vec![crate::Position(Vec3::new(20.0, 0.0, 20.0))], radius: "4".into(), body: None, style: crate::FilletStyle::Constant, diff --git a/crates/doc/src/eval_more.rs b/crates/doc/src/eval_more.rs index e2407d87c..2592cf2a6 100644 --- a/crates/doc/src/eval_more.rs +++ b/crates/doc/src/eval_more.rs @@ -10,7 +10,7 @@ use solidcraft_geom::{Loop2, Seg2}; pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, st: &mut ModelState) -> Result<()> { match &f.kind { FeatureKind::Emboss { sketch, profiles, depth, deboss, targets, face } => { - let ss = st.sketch(*sketch).ok_or_else(|| DocError::Unknown(format!("sketch {sketch}")))?; + let ss = st.sketch(sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {sketch}")))?; let regions = select_profiles(ss, profiles)?; let d = val(vals, depth, Kind::Length)?; if !(d > 0.0) { @@ -35,7 +35,7 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, crate::apply_vector(&sketch_transform, ss.plane.y), ) .ok_or_else(|| DocError::Invalid("invalid cylinder sketch frame".into()))?; - let mut at = crate::apply_point(&crate::mat_mul(&inverse, &author_frame), face.at); + let mut at = crate::apply_point(&crate::mat_mul(&inverse, &author_frame), face.at.0); let name = f .face_names .first() @@ -67,10 +67,10 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, if st.bodies.is_empty() { return Err(DocError::Invalid("there is no body to emboss".into())); } - apply_op(st, f, tools, if *deboss { Operation::Cut } else { Operation::Join }, targets) + apply_op(st, f, tools, if *deboss { Operation::Cut } else { Operation::Join }, &crate::plain(targets)) } FeatureKind::Rib { sketch, curves, thickness, depth, flip, web } => { - let ss = st.sketch(*sketch).ok_or_else(|| DocError::Unknown(format!("sketch {sketch}")))?.clone(); + let ss = st.sketch(sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {sketch}")))?.clone(); let t = val(vals, thickness, Kind::Length)?; if !(t > 0.0) { return Err(DocError::Invalid("the rib thickness must be positive".into())); @@ -95,17 +95,18 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, FeatureKind::ReplaceFace { faces, target, body } => { let tp = doc.resolve_plane_in(vals, target, 0, Some(st))?; let tn = tp.normal(); - let i = body_at(st, body, faces)?; + 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(); for p in faces { - let n = planar_normal_at(&b, *p).ok_or_else(|| DocError::Invalid("not supported yet: replacing a face that is not planar".into()))?; + let n = + planar_normal_at(&b, 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).dot(n); + let d = (tp.origin - p.0).dot(n); if d.abs() > 1e-9 { - b = kernel::offset_faces(&b, &[*p], d)?; + b = kernel::offset_faces(&b, &[p.0], d)?; } } if let Some(slot) = st.bodies.get_mut(i) { @@ -115,17 +116,17 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, } FeatureKind::Align { bodies, from, to, from_normal, to_normal, flip } => { let mut m = translation(Vec3::ZERO); - if let (Some(a), Some(b)) = (from_normal.and_then(Vec3::normalized), to_normal.and_then(Vec3::normalized)) { + if let (Some(a), Some(b)) = (from_normal.and_then(|n| n.normalized()), to_normal.and_then(|n| n.normalized())) { // Turn `a` onto −b (faces meet) or b (flipped), about the `from` point. let want = if *flip { b } else { b * -1.0 }; let axis = a.cross(want); let ang = axis.len().atan2(a.dot(want)); let axis = axis.normalized().unwrap_or_else(|| a.any_perp()); if ang.abs() > 1e-12 { - m = rotation(*from, axis, ang); + m = rotation(from.0, axis, ang); } } - let d = *to - *from; + let d = to.0 - from.0; m[3][0] += d.x; m[3][1] += d.y; m[3][2] += d.z; @@ -150,7 +151,7 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, return Err(DocError::Unknown(format!("body `{n}`"))); } } - st.bodies.retain(|b| !bodies.contains(&b.name)); + st.bodies.retain(|b| !bodies.iter().any(|t| *t == b.name)); Ok(()) } _ => Err(DocError::Invalid(format!("{} is not evaluated here", f.name))), @@ -331,7 +332,7 @@ fn rebuild_sheet(st: &mut ModelState, idx: usize) -> Result<()> { } /// The sheet a feature works on: by body name, else the one with an edge nearest the pick. -fn sheet_for(st: &ModelState, body: &Option, pick: Option) -> Result { +fn sheet_for(st: &ModelState, body: &Option, pick: Option) -> Result { if let Some(n) = body { return st.sheets.iter().position(|s| &s.body == n).ok_or_else(|| DocError::Invalid(format!("`{n}` is not a sheet metal body"))); } @@ -391,7 +392,7 @@ pub(super) fn sheet_eval( use crate::sheet; match &f.kind { FeatureKind::SheetBase { sketch, profiles, rule, flip } => { - let ss = st.sketch(*sketch).ok_or_else(|| DocError::Unknown(format!("sketch {sketch}")))?.clone(); + let ss = st.sketch(sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {sketch}")))?.clone(); let regions = solidcraft_sketch::merge_regions(&select_profiles(&ss, profiles)?); let r = doc.sheet_rule(rule.as_deref()); let rv = doc.rule_values(vals, &r)?; @@ -425,7 +426,7 @@ pub(super) fn sheet_eval( Ok(()) } FeatureKind::SheetContour { sketch, curves, distance, rule, flip, reverse } => { - let ss = st.sketch(*sketch).ok_or_else(|| DocError::Unknown(format!("sketch {sketch}")))?.clone(); + let ss = st.sketch(sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {sketch}")))?.clone(); for id in curves { let ci = ss.sketch.curve_index(id).ok_or_else(|| DocError::Unknown(format!("curve `{id}`")))?; if !ss.sketch.segs(ci).iter().all(|s| matches!(s, Seg2::Line { .. })) { @@ -450,7 +451,7 @@ pub(super) fn sheet_eval( Ok(()) } FeatureKind::SheetFlange { edges, height, angle, radius, position, flip, body, corner_relief_shape, corner_relief } => { - let i = sheet_for(st, body, edges.first().map(|e| e.point))?; + let i = sheet_for(st, body, edges.first().map(|e| e.point.0))?; let (h, a) = (val(vals, height, Kind::Length)?, val(vals, angle, Kind::Angle)?); // Each edge's own height and angle, else the feature's. let mut own = Vec::with_capacity(edges.len()); @@ -490,7 +491,7 @@ pub(super) fn sheet_eval( if sh.flat { return Err(DocError::Invalid("refold the sheet before adding flanges".into())); } - let points: Vec = edges.iter().map(|e| e.point).collect(); + let points: Vec = edges.iter().map(|e| e.point.0).collect(); let each: Vec = sheet_picks(sh, f, &points, warning) .into_iter() .zip(own) @@ -535,7 +536,7 @@ pub(super) fn sheet_eval( Ok(()) } FeatureKind::SheetHem { edges, length, gap, flip, body } => { - let i = sheet_for(st, body, edges.first().copied())?; + let i = sheet_for(st, body, edges.first().copied().map(Vec3::from))?; let l = val(vals, length, Kind::Length)?; let g = match gap { Some(e) => val(vals, e, Kind::Length)?, @@ -545,7 +546,7 @@ pub(super) fn sheet_eval( } }; let sh = st.sheets.get_mut(i).ok_or_else(|| DocError::Invalid("sheet".into()))?; - let picks = sheet_picks(sh, f, edges, warning); + let picks = sheet_picks(sh, f, &crate::plain(edges), warning); let n0 = sh.flanges.len(); for e in &picks { sh.add_hem(*e, l, g, *flip)?; @@ -557,14 +558,14 @@ pub(super) fn sheet_eval( // The sketch line, where it is now. let (a, b) = match (sketch, curve) { (Some(sk), Some(c)) => { - let ss = st.sketch(*sk).ok_or_else(|| DocError::Unknown(format!("sketch {sk}")))?; + let ss = st.sketch(sk.0).ok_or_else(|| DocError::Unknown(format!("sketch {sk}")))?; let ci = ss.sketch.curve_index(c).ok_or_else(|| DocError::Unknown(format!("curve `{c}`")))?; match ss.sketch.segs(ci).as_slice() { [Seg2::Line { a, b }] => (ss.plane.to_world(*a), ss.plane.to_world(*b)), _ => return Err(DocError::Invalid("the fold line must be a sketch line".into())), } } - _ => (*a, *b), + _ => (a.0, b.0), }; let i = sheet_for(st, body, Some((a + b) * 0.5))?; let ang = val(vals, angle, Kind::Angle)?; @@ -578,7 +579,7 @@ pub(super) fn sheet_eval( // A fixed point that touches no material at all (e.g. far above the sheet) still picks // the side it lies on, so a stored fold keeps recomputing; it says so (#371). if let Some(p) = fixed - && !on_sheet_material(st, i, *p) + && !on_sheet_material(st, i, p.0) { *warning = Some(format!( "{} at ({:.3}, {:.3}, {:.3}); the side of the fold line it lies on stays", @@ -593,7 +594,7 @@ pub(super) fn sheet_eval( return Err(DocError::Invalid("refold the sheet before folding it".into())); } let n0 = sh.flanges.len(); - sh.add_fold(a, b, ang, rr, position, *flip, *fixed, warning)?; + sh.add_fold(a, b, ang, rr, position, *flip, fixed.map(Vec3::from), warning)?; tag_flanges(sh, n0, f.id); rebuild_sheet(st, i) } @@ -618,7 +619,7 @@ pub(super) fn sheet_eval( let mut picks = Vec::with_capacity(bends.len()); for (i, p) in bends.iter().enumerate() { let name = f.edge_names.get(i).filter(|n| !n.is_empty()); - picks.push(match name.map(|n| (n, crate::naming::locate_edge(&mb, n, *p))) { + picks.push(match name.map(|n| (n, crate::naming::locate_edge(&mb, n, p.0))) { Some((n, Ok(hit))) => { if let Some(note) = hit.note(n) { append_warning(warning, note); @@ -627,12 +628,12 @@ pub(super) fn sheet_eval( } Some((n, Err(_))) => { append_warning(warning, format!("edge `{n}` no longer exists; using the edge at the picked point")); - *p + p.0 } - None => *p, + None => p.0, }); } - let (mut sh, notes) = sheet::convert_body(&mb, &r.name, &rv, *face, &picks)?; + let (mut sh, notes) = sheet::convert_body(&mb, &r.name, &rv, face.0, &picks)?; for note in notes { append_warning(warning, note); } @@ -641,10 +642,10 @@ pub(super) fn sheet_eval( } FeatureKind::SheetConvert { body, face, rule, .. } => { let mb = st.body(body).cloned().ok_or_else(|| DocError::Unknown(format!("body `{body}`")))?; - let n = planar_normal_at(&mb.body, *face).ok_or_else(|| DocError::Invalid("pick a planar face of the plate".into()))?; + let n = planar_normal_at(&mb.body, face.0).ok_or_else(|| DocError::Invalid("pick a planar face of the plate".into()))?; // Thickness: the body's extent along the face normal. let extent = |mesh: &solidcraft_geom::Mesh| { - mesh.positions.iter().map(|p| (*p - *face).dot(n)).fold((f64::MAX, f64::MIN), |(lo, hi), d| (lo.min(d), hi.max(d))) + mesh.positions.iter().map(|p| (*p - face.0).dot(n)).fold((f64::MAX, f64::MIN), |(lo, hi), d| (lo.min(d), hi.max(d))) }; // The tolerance (the mesh's chords, and how far off the face's plane a point of it may // be) is at most a tenth of the thickness, not only a thousandth of the size. On a long @@ -662,13 +663,13 @@ pub(super) fn sheet_eval( // 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 + n * lo, n * -1.0).ok_or_else(|| DocError::Invalid("face".into()))?; + let plane = Plane::from_normal(face.0 + n * lo, 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, n, (lo, hi), tol)?; + let recesses = plate_recesses(&mb.body, &mesh, &plane, face.0, n, (lo, hi), tol)?; let mut walls = std::collections::HashMap::new(); let mut wall = |f: u32| *walls.entry(f).or_insert_with(|| sheet::round_wall(&mb.body, &plane, n, f)); let mut loops: Vec = - face_outline(&mesh, &plane, *face, n, recesses.level, tol).iter().map(|l| sheet::outline_loop(l, &mut wall, tol * 1e-2)).collect(); + face_outline(&mesh, &plane, face.0, n, recesses.level, tol).iter().map(|l| sheet::outline_loop(l, &mut wall, tol * 1e-2)).collect(); loops.sort_by(|a, b| b.signed_area().abs().total_cmp(&a.signed_area().abs())); let mut it = loops.into_iter(); let outer = it.next().ok_or_else(|| DocError::Invalid("no outline on that face".into()))?.ccw(); @@ -784,7 +785,7 @@ pub(super) fn sheet_cut( if extent.taper.is_some() || !any_eligible_sheet(f, st, targets) { return Ok(Vec::new()); } - let Some(ss) = st.sketch(*sketch).cloned() else { return Ok(Vec::new()) }; + let Some(ss) = st.sketch(sketch.0).cloned() else { return Ok(Vec::new()) }; let regions = solidcraft_sketch::merge_regions(&select_profiles(&ss, profiles)?); // The outlines of the sketch's text: the sheet remembers where its letters went. let text: Vec = ss @@ -1479,7 +1480,7 @@ fn plate_recesses(body: &Body, mesh: &Mesh, plane: &Plane, at: Vec3, n: Vec3, (l } /// The body a placed plastic feature joins: by name, else the one under the point. -fn body_under(st: &ModelState, body: &Option, p: Vec3) -> Result { +fn body_under(st: &ModelState, body: &Option, p: Vec3) -> Result { let i = body_at(st, body, &[p])?; let b = st.bodies.get(i).ok_or_else(|| DocError::Invalid("there is no body".into()))?; let tolerance = (b.body.size() * 1e-5).max(1e-4); @@ -1541,7 +1542,7 @@ pub(super) fn plastic_eval(doc: &Document, vals: &BTreeMap, f: &F rib_offset, body, } => { - let target = body_under(st, body, *position)?; + let target = body_under(st, body, position.0)?; let (r0, h) = (len(diameter)? / 2.0, len(height)?); if !(r0 > 0.0 && h > 0.0) { return Err(DocError::Invalid("the boss diameter and height must be positive".into())); @@ -1559,9 +1560,9 @@ pub(super) fn plastic_eval(doc: &Document, vals: &BTreeMap, f: &F return Err(DocError::Invalid("the draft closes the boss before its top".into())); } let delta = (h * 0.05).clamp(1e-3, 0.5); - let (x, _, z) = local_frame(*direction, None)?; + let (x, _, z) = local_frame(direction.0, None)?; // The post: a (tapered) cylinder from a little inside the face. - let base = Plane::new(*position - z * delta, x, z.cross(x)).ok_or_else(|| DocError::Invalid("boss frame".into()))?; + let base = Plane::new(position.0 - z * delta, x, z.cross(x)).ok_or_else(|| DocError::Invalid("boss frame".into()))?; let r_in = r0 + delta * dr.tan(); let disc = Region2 { outer: Loop2::circle(Vec2::ZERO, r_in), holes: Vec::new() }; let post = if dr.abs() > 1e-12 { @@ -1594,7 +1595,7 @@ pub(super) fn plastic_eval(doc: &Document, vals: &BTreeMap, f: &F for k in 0..n as usize { let a = std::f64::consts::TAU * k as f64 / n; let (u, v) = (x * a.cos() + z.cross(x) * a.sin(), z.cross(x) * a.cos() - x * a.sin()); - let rp = Plane::new(*position, u, v).ok_or_else(|| DocError::Invalid("rib frame".into()))?; + let rp = Plane::new(position.0, u, v).ok_or_else(|| DocError::Invalid("rib frame".into()))?; let rect = Region2 { outer: Loop2::polygon(&[ Vec2::new(r0 * 0.5, -t / 2.0), @@ -1613,7 +1614,7 @@ pub(super) fn plastic_eval(doc: &Document, vals: &BTreeMap, f: &F let i = st.bodies.iter().position(|b| b.name == target).ok_or_else(|| DocError::Invalid("boss body".into()))?; let Some(mb) = st.bodies.get(i).cloned() else { return Err(DocError::Invalid("boss body".into())) }; let mut warn = None; - let edges = resolve_edges(&mb.body, &[*position + x * r0], &[], &mut warn)?; + let edges = resolve_edges(&mb.body, &[position.0 + x * r0], &[], &mut warn)?; let nb = mb.traced().then(kernel::fillet(&mb.body, &edges, rf)?); if let Some(slot) = st.bodies.get_mut(i) { *slot = ModelBody::traced_new(mb.name, nb, mb.feature); @@ -1628,7 +1629,7 @@ pub(super) fn plastic_eval(doc: &Document, vals: &BTreeMap, f: &F if !(rh > 0.0 && rh < r_top && depth > 0.0) { return Err(DocError::Invalid("the boss hole must fit inside the boss".into())); } - let hp = Plane::new(*position, x, z.cross(x)).ok_or_else(|| DocError::Invalid("hole frame".into()))?; + let hp = Plane::new(position.0, x, z.cross(x)).ok_or_else(|| DocError::Invalid("hole frame".into()))?; let tool = kernel::extrude(&hp, &[Region2 { outer: Loop2::circle(Vec2::ZERO, rh), holes: Vec::new() }], h - depth, h + delta)?; let tool = tool.into_iter().map(|b| crate::lineage::part_tool(b, "hole")).collect(); apply_traced(st, f, tool, Operation::Cut, std::slice::from_ref(&target))?; @@ -1636,9 +1637,9 @@ pub(super) fn plastic_eval(doc: &Document, vals: &BTreeMap, f: &F Ok(()) } FeatureKind::Lip { face, width, height, groove, gap, outside, body } => { - let target = body_under(st, body, *face)?; + let target = body_under(st, body, face.0)?; let mb = st.body(&target).cloned().ok_or_else(|| DocError::Invalid("body".into()))?; - let n = planar_normal_at(&mb.body, *face).ok_or_else(|| DocError::Invalid("pick the planar rim face".into()))?; + let n = planar_normal_at(&mb.body, face.0).ok_or_else(|| DocError::Invalid("pick the planar rim face".into()))?; let (w, h) = (len(width)?, len(height)?); let g = match gap { Some(e) => len(e)?, @@ -1648,10 +1649,10 @@ pub(super) fn plastic_eval(doc: &Document, vals: &BTreeMap, f: &F if !(w > 0.0 && h > 0.0 && g >= 0.0) { return Err(DocError::Invalid("the lip width and height must be positive".into())); } - let plane = Plane::from_normal(*face, n).ok_or_else(|| DocError::Invalid("rim plane".into()))?; + let plane = Plane::from_normal(face.0, n).ok_or_else(|| DocError::Invalid("rim plane".into()))?; let tol = (mb.body.size() * 1e-3).max(1e-3); let mesh = mb.body.tessellate(tol)?; - let mut loops = face_loops(&mesh, &plane, *face, n, 0.0, 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() }; // The inner edge is an opening (the cavity under a rim): not the foot of a boss or a @@ -1685,7 +1686,7 @@ pub(super) fn plastic_eval(doc: &Document, vals: &BTreeMap, f: &F // A lip: the band raised from the rim's own faces (its walls continue the walls // below, which a join can't do: they would coincide). if !*groove - && let Ok(b) = kernel::raise_band(&mb.body, *face, w, h, *outside) + && let Ok(b) = kernel::raise_band(&mb.body, face.0, w, h, *outside) && let Some(slot) = st.bodies.iter_mut().find(|x| x.name == target) { *slot = ModelBody::traced_new(target.clone(), Traced::step(b, &[&mb.traced()]), slot.feature); @@ -1715,17 +1716,17 @@ pub(super) fn plastic_eval(doc: &Document, vals: &BTreeMap, f: &F } } FeatureKind::SnapFit { position, direction, hook, length, thickness, width, catch_depth, catch_length, body } => { - let target = body_under(st, body, *position)?; + let target = body_under(st, body, position.0)?; let (l, t, w, cd, cl) = (len(length)?, len(thickness)?, len(width)?, len(catch_depth)?, len(catch_length)?); if !(l > 0.0 && t > 0.0 && w > 0.0 && cd > 0.0 && cl > 0.0 && cl < l) { return Err(DocError::Invalid("the snap fit's sizes must be positive and the catch shorter than the arm".into())); } - let (x, y, z) = local_frame(*direction, Some(*hook))?; + let (x, y, z) = local_frame(direction.0, Some(hook.0))?; let delta = (l * 0.05).clamp(1e-3, 0.5); // Side profile (x = toward the catch, y = up the arm), extruded across the width. let pts = [Vec2::new(-t, -delta), Vec2::new(0.0, -delta), Vec2::new(0.0, l - cl), Vec2::new(cd, l - cl), Vec2::new(0.0, l), Vec2::new(-t, l)]; - let o = *position - y * (w / 2.0); + let o = position.0 - y * (w / 2.0); let pl = Plane::new(o, x, z).ok_or_else(|| DocError::Invalid("snap fit frame".into()))?; let mut lp = Loop2::polygon(&pts); if lp.signed_area() < 0.0 { @@ -1738,7 +1739,7 @@ pub(super) fn plastic_eval(doc: &Document, vals: &BTreeMap, f: &F apply_traced(st, f, tool, Operation::Join, std::slice::from_ref(&target)) } FeatureKind::Rest { position, direction, along, width, length, height, draft, thickness, body } => { - let target = body_under(st, body, *position)?; + let target = body_under(st, body, position.0)?; let (w, h) = (len(width)?, len(height)?); let l = length.as_deref().map(len).transpose()?; let dr = match draft { @@ -1761,7 +1762,7 @@ pub(super) fn plastic_eval(doc: &Document, vals: &BTreeMap, f: &F return Err(DocError::Invalid("the draft closes the rest before its top".into())); } let delta = (h * 0.05).clamp(1e-3, 0.5); - let (x, y, z) = local_frame(*direction, *along)?; + let (x, y, z) = local_frame(direction.0, along.map(Vec3::from))?; // Sized at the face: the tool starts a little inside, grown by the draft over that. let e = delta * dr.tan(); let shape = |grow: f64| match l { @@ -1778,7 +1779,7 @@ pub(super) fn plastic_eval(doc: &Document, vals: &BTreeMap, f: &F None => Vec::new(), }; let region = Region2 { outer: shape(e), holes }; - let base = Plane::new(*position - z * delta, x, y).ok_or_else(|| DocError::Invalid("rest frame".into()))?; + let base = Plane::new(position.0 - z * delta, x, y).ok_or_else(|| DocError::Invalid("rest frame".into()))?; let tool = if dr.abs() > 1e-12 { vec![kernel::extrude_tapered(&base, ®ion, h + delta, 1.0, -dr)?] } else { diff --git a/crates/doc/src/eval_surface.rs b/crates/doc/src/eval_surface.rs index 09969eef8..19a1d35f1 100644 --- a/crates/doc/src/eval_surface.rs +++ b/crates/doc/src/eval_surface.rs @@ -11,22 +11,22 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, FeatureKind::Patch { sketch, profiles, body, edges, crown, continuity, points } => { let mut made = Vec::new(); if let Some(sk) = sketch { - let ss = st.sketch(*sk).ok_or_else(|| DocError::Unknown(format!("sketch {sk} (it must come earlier in the timeline)")))?; + let ss = st.sketch(sk.0).ok_or_else(|| DocError::Unknown(format!("sketch {sk} (it must come earlier in the timeline)")))?; let regions = solidcraft_sketch::merge_regions(&select_profiles(ss, profiles)?); for r in ®ions { made.push(kernel::patch_region(&ss.plane, r)?); } } if !edges.is_empty() { - let i = body_at(st, body, edges)?; + let i = body_at(st, body, &crate::plain(edges))?; let b = st.bodies.get(i).ok_or_else(|| DocError::Invalid("body".into()))?; let spec = kernel::PatchSpec { continuity: continuity.all, - edges: continuity.edges.iter().map(|e| (e.edge, e.g)).collect(), - points: points.clone(), + edges: continuity.edges.iter().map(|e| (e.edge.0, e.g)).collect(), + points: crate::plain(points), crown: *crown, }; - made.push(kernel::patch_edges_with(&b.body, edges, &spec)?); + made.push(kernel::patch_edges_with(&b.body, &crate::plain(edges), &spec)?); } if made.is_empty() { return Err(DocError::Invalid("a patch needs a sketch region or a loop of edges".into())); @@ -65,7 +65,7 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, if tools.is_empty() { return Err(DocError::Invalid("pick the surfaces to thicken".into())); } - apply_op(st, f, tools, *operation, targets) + apply_op(st, f, tools, *operation, &crate::plain(targets)) } FeatureKind::SurfaceTrim { body, plane, tool, keep } => { let i = st.bodies.iter().position(|b| &b.name == body).ok_or_else(|| DocError::Unknown(format!("body `{body}`")))?; @@ -73,11 +73,11 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, let trimmed = match tool { 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) + 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)? + kernel::trim(&mb.body, &kernel::SplitTool::Face { body: &tb.body, face }, keep.0)? } - None => kernel::trim(&mb.body, &kernel::SplitTool::Plane(doc.resolve_plane_in(vals, plane, 0, Some(st))?), *keep)?, + None => kernel::trim(&mb.body, &kernel::SplitTool::Plane(doc.resolve_plane_in(vals, plane, 0, Some(st))?), keep.0)?, }; if let Some(slot) = st.bodies.get_mut(i) { *slot = ModelBody::new(mb.name, trimmed, mb.feature); @@ -94,18 +94,20 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, }; let at = |limit| kernel::ExtendOptions { mode, limit, neighbours: *neighbours }; let out = match up_to { - None => kernel::extend_surface(&mb.body, edges, &at(kernel::ExtendLimit::Distance(val(vals, distance, Kind::Length)?)))?, - Some(crate::ExtendTo::Bounds) => kernel::extend_surface(&mb.body, edges, &at(kernel::ExtendLimit::Bounds))?, + None => { + kernel::extend_surface(&mb.body, &crate::plain(edges), &at(kernel::ExtendLimit::Distance(val(vals, distance, Kind::Length)?)))? + } + Some(crate::ExtendTo::Bounds) => kernel::extend_surface(&mb.body, &crate::plain(edges), &at(kernel::ExtendLimit::Bounds))?, Some(crate::ExtendTo::Plane(plane)) => { let tool = kernel::SplitTool::Plane(doc.resolve_plane_in(vals, plane, 0, Some(st))?); - kernel::extend_surface(&mb.body, edges, &at(kernel::ExtendLimit::UpTo(&tool)))? + kernel::extend_surface(&mb.body, &crate::plain(edges), &at(kernel::ExtendLimit::UpTo(&tool)))? } Some(crate::ExtendTo::Face(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) + let face = crate::appearance::face_index_at(tb, t.point.0) .ok_or_else(|| DocError::Invalid(format!("no face of `{}` at the target point", t.body)))?; let tool = kernel::SplitTool::Face { body: &tb.body, face }; - kernel::extend_surface(&mb.body, edges, &at(kernel::ExtendLimit::UpTo(&tool)))? + kernel::extend_surface(&mb.body, &crate::plain(edges), &at(kernel::ExtendLimit::UpTo(&tool)))? } }; if let Some(slot) = st.bodies.get_mut(i) { @@ -119,7 +121,17 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, if from.edges.is_empty() || to.edges.is_empty() { return Err(DocError::Invalid("a blend needs a chain of edges at each end".into())); } - let (made, gap) = kernel::blend_between(&a, &from.edges, &b, &to.edges, *continuity, *bulge, *align, BLEND_STATIONS, *stitch)?; + let (made, gap) = kernel::blend_between( + &a, + &crate::plain(&from.edges), + &b, + &crate::plain(&to.edges), + *continuity, + *bulge, + align.map(|[p, q]| [p.0, q.0]), + BLEND_STATIONS, + *stitch, + )?; if gap > 1e-9 { *warning = Some(format!("the blend's boundary lies up to {gap:.4} mm from the edges it was built on")); } @@ -127,7 +139,7 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, // A stitched blend takes the place of both bodies it joins; otherwise it is a new // surface body of its own. if *stitch { - let gone = [from.body.clone(), to.body.clone()]; + let gone = [from.body.0.clone(), to.body.0.clone()]; st.bodies.retain(|x| !gone.contains(&x.name)); } st.bodies.push(ModelBody::new(name, made, f.id)); @@ -136,7 +148,7 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, FeatureKind::SurfaceExtrude { sketch, profiles, curves, extent } => { let ss = sketch_in_feature_frame( doc, - st.sketch(*sketch).ok_or_else(|| DocError::Unknown(format!("sketch {sketch} (it must come earlier in the timeline)")))?, + st.sketch(sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {sketch} (it must come earlier in the timeline)")))?, f.component, )?; if extent.through_all || extent.taper.is_some() || extent.to.is_some() || extent.from.is_some() { @@ -153,7 +165,7 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, FeatureKind::SurfaceRevolve { sketch, profiles, curves, axis, angle, angle2, symmetric } => { let ss = sketch_in_feature_frame( doc, - st.sketch(*sketch).ok_or_else(|| DocError::Unknown(format!("sketch {sketch} (it must come earlier in the timeline)")))?, + st.sketch(sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {sketch} (it must come earlier in the timeline)")))?, f.component, )?; let (o, d) = revolve_axis(&ss, axis)?; @@ -174,7 +186,7 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, FeatureKind::Unstitch { body, faces } => { 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 (pieces, rest) = kernel::unstitch(&mb.body, faces)?; + let (pieces, rest) = kernel::unstitch(&mb.body, &crate::plain(faces))?; let source = mb.traced(); // The faces left keep the body's name; each face taken out is a new surface body. match rest { @@ -196,7 +208,7 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, FeatureKind::ReverseNormal { body, faces } => { 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 turned = mb.traced().then(kernel::reverse_faces(&mb.body, faces)?); + let turned = mb.traced().then(kernel::reverse_faces(&mb.body, &crate::plain(faces))?); if let Some(slot) = st.bodies.get_mut(i) { *slot = ModelBody::traced_new(mb.name, turned, mb.feature); } @@ -204,9 +216,9 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, } FeatureKind::SurfaceSweep { sketch, profiles, curves, path_sketch, path, orientation, twist, scale } => { let ctl = crate::eval::sweep_control(vals, orientation, twist, scale)?; - let ss = st.sketch(*sketch).ok_or_else(|| DocError::Unknown(format!("sketch {sketch} (it must come earlier in the timeline)")))?; + let ss = st.sketch(sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {sketch} (it must come earlier in the timeline)")))?; let ps = - st.sketch(*path_sketch).ok_or_else(|| DocError::Unknown(format!("sketch {path_sketch} (it must come earlier in the timeline)")))?; + st.sketch(path_sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {path_sketch} (it must come earlier in the timeline)")))?; // As Sweep: a 3D path sketch is followed in the feature's frame, the curves with it. let profile; let ss = if !ps.sketch.wires.is_empty() { @@ -235,7 +247,7 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, for sec in sections { let ss = sketch_in_feature_frame( doc, - st.sketch(sec.sketch) + st.sketch(sec.sketch.0) .ok_or_else(|| DocError::Unknown(format!("sketch {} (it must come earlier in the timeline)", sec.sketch)))?, f.component, )?; @@ -265,9 +277,9 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, Some(t) => val(vals, t, Kind::Length)?, None => 0.01, }; - let i = body_at(st, body, faces)?; + 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 picks = if *chain { smooth_chain(&mb, faces) } else { faces.clone() }; + let picks = if *chain { smooth_chain(&mb, &crate::plain(faces)) } else { crate::plain(faces) }; let mut picked: Vec = Vec::new(); for p in &picks { let fi = @@ -288,10 +300,10 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, RuledMode::Tangent => kernel::RuledMode::Tangent, RuledMode::Angle => { let a = angle.as_ref().ok_or_else(|| DocError::Invalid("a ruled surface at an angle needs `angle`".into()))?; - kernel::RuledMode::Angle { angle: val(vals, a, Kind::Angle)?, reference: *direction } + kernel::RuledMode::Angle { angle: val(vals, a, Kind::Angle)?, reference: direction.map(Vec3::from) } } RuledMode::Direction => kernel::RuledMode::Direction( - direction.ok_or_else(|| DocError::Invalid("a ruled surface along a direction needs `direction`".into()))?, + direction.map(Vec3::from).ok_or_else(|| DocError::Invalid("a ruled surface along a direction needs `direction`".into()))?, ), }; let corners = match corners { @@ -299,8 +311,8 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, RuledCorners::Round => kernel::RuledCorners::Round, }; let mb = st.body(body).cloned().ok_or_else(|| DocError::Unknown(format!("body `{body}`")))?; - let r = kernel::Ruled { distance: d, mode, flip: *flip, corners, face: *face }; - let made = Traced::step(kernel::ruled_surface(&mb.body, edges, &r)?, &[&mb.traced()]); + let r = kernel::Ruled { distance: d, mode, flip: *flip, corners, face: face.map(Vec3::from) }; + let made = Traced::step(kernel::ruled_surface(&mb.body, &crate::plain(edges), &r)?, &[&mb.traced()]); let name = new_name(st, f, 0); st.bodies.push(ModelBody::traced_new(name, made, f.id)); Ok(()) @@ -308,11 +320,11 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, FeatureKind::SurfaceUntrim { face, holes, outer, in_place } => { let i = st.bodies.iter().position(|b| b.name == face.body).ok_or_else(|| DocError::Unknown(format!("body `{}`", face.body)))?; let Some(mb) = st.bodies.get(i).cloned() else { return Err(DocError::Invalid("body".into())) }; - let fi = crate::appearance::face_index_at(&mb, face.point) + let fi = crate::appearance::face_index_at(&mb, face.point.0) .ok_or_else(|| DocError::Invalid(format!("Untrim: no face of {} at {:?}", mb.name, face.point)))?; let which = match holes { None => kernel::UntrimHoles::All, - Some(points) => kernel::UntrimHoles::At(points), + Some(points) => kernel::UntrimHoles::At(&crate::plain(points)), }; // A surface body's face is untrimmed where it is when asked; a solid's is copied out. let replace = *in_place && mb.body.is_surface(); diff --git a/crates/doc/src/expr.rs b/crates/doc/src/expr.rs index 5e86b2bb9..cb4b4d56c 100644 --- a/crates/doc/src/expr.rs +++ b/crates/doc/src/expr.rs @@ -15,6 +15,94 @@ const MAX_LEN: usize = 4096; const MAX_DEPTH: usize = 64; const MAX_ARGS: usize = 64; +/// An expression a feature holds, as the user wrote it (`2 * width + 5 mm`): kept as text and +/// evaluated with the design's parameters. It is saved as a plain string, and reads as one +/// (`&expr` is a `&str`); it changes only as a whole (`*expr = new.into()`). +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Serialize, serde::Deserialize)] +#[serde(transparent)] +pub struct Expr(String); + +impl Expr { + pub fn new(s: impl Into) -> Self { + Expr(s.into()) + } + + pub fn as_str(&self) -> &str { + &self.0 + } + + pub fn into_string(self) -> String { + self.0 + } +} + +impl std::ops::Deref for Expr { + type Target = str; + fn deref(&self) -> &str { + &self.0 + } +} + +impl AsRef for Expr { + fn as_ref(&self) -> &str { + &self.0 + } +} + +impl From for Expr { + fn from(s: String) -> Self { + Expr(s) + } +} + +impl From<&str> for Expr { + fn from(s: &str) -> Self { + Expr(s.to_string()) + } +} + +impl From<&String> for Expr { + fn from(s: &String) -> Self { + Expr(s.clone()) + } +} + +impl From for String { + fn from(e: Expr) -> Self { + e.0 + } +} + +impl std::fmt::Display for Expr { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl PartialEq for Expr { + fn eq(&self, other: &str) -> bool { + self.0 == other + } +} + +impl PartialEq<&str> for Expr { + fn eq(&self, other: &&str) -> bool { + self.0 == *other + } +} + +impl PartialEq for String { + fn eq(&self, other: &Expr) -> bool { + *self == other.0 + } +} + +impl PartialEq for Expr { + fn eq(&self, other: &String) -> bool { + &self.0 == other + } +} + /// What an expression must evaluate to. #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] diff --git a/crates/doc/src/face_anchor.rs b/crates/doc/src/face_anchor.rs index 8609ae36e..a6e1df446 100644 --- a/crates/doc/src/face_anchor.rs +++ b/crates/doc/src/face_anchor.rs @@ -69,8 +69,12 @@ impl FaceAnchor { } let inverse = crate::mat_inverse(&self.author_frame(doc, author)?) .ok_or_else(|| DocError::Invalid("attached sketch author frame is invalid".into()))?; - let source = - EmbossFace { body: self.target.body.clone(), at: self.target.point, path: self.path.clone(), author_path: self.author_path.clone() }; + let source = EmbossFace { + body: self.target.body.clone().into(), + at: crate::FacePick(self.target.point), + path: self.path.clone(), + author_path: self.author_path.clone(), + }; Ok(crate::mat_mul(&inverse, &source.body_frame(doc, body)?)) } } @@ -447,7 +451,7 @@ mod tests { .add_feature( FeatureKind::Extrude { thin: None, - sketch: source, + sketch: crate::SketchId(source), profiles: crate::ProfileSel::Indices { indices: vec![0, 1] }, extent, operation: crate::Operation::NewBody, @@ -558,7 +562,7 @@ mod tests { .add_feature( FeatureKind::Extrude { thin: None, - sketch: sk, + sketch: crate::SketchId(sk), profiles: crate::ProfileSel::All, extent, operation: crate::Operation::NewBody, diff --git a/crates/doc/src/feature_refs.rs b/crates/doc/src/feature_refs.rs index 0c1b4a599..9c3045f72 100644 --- a/crates/doc/src/feature_refs.rs +++ b/crates/doc/src/feature_refs.rs @@ -5,15 +5,14 @@ use std::collections::BTreeMap; -use crate::FeatureKind; use crate::walk::Walk; +use crate::{BodyName, FeatureKind, FeatureName, SketchId}; -/// A reference a feature holds: `S` is `&u64` or `&mut u64` (a sketch id), `N` is `&String` or -/// `&mut String` (a feature or body name). -pub(crate) enum Ref { +/// A reference a feature holds: `S` is `&SketchId` or `&mut SketchId`, and so on. +pub(crate) enum Ref { Sketch(S), - Feature(N), - Body(N), + Feature(F), + Body(B), } impl FeatureKind { @@ -23,7 +22,7 @@ impl FeatureKind { let mut v = Vec::new(); self.walk_refs(&mut |r| { if let Ref::Sketch(id) = r { - v.push(*id); + v.push(id.0); } }); v @@ -34,13 +33,13 @@ impl FeatureKind { pub fn remap_refs(&mut self, sketches: &BTreeMap, names: &BTreeMap) { self.walk_refs_mut(&mut |r| match r { Ref::Sketch(id) => { - if let Some(n) = sketches.get(id) { - *id = *n; + if let Some(n) = sketches.get(&id.0) { + *id = SketchId(*n); } } Ref::Feature(name) => { - if let Some(n) = names.get(name) { - *name = n.clone(); + if let Some(n) = names.get(name.as_ref()) { + *name = FeatureName(n.clone()); } } Ref::Body(_) => {} @@ -51,9 +50,9 @@ impl FeatureKind { pub fn remap_bodies(&mut self, bodies: &BTreeMap) { self.walk_refs_mut(&mut |r| { if let Ref::Body(name) = r - && let Some(n) = bodies.get(name) + && let Some(n) = bodies.get(name.as_ref()) { - *name = n.clone(); + *name = BodyName(n.clone()); } }); } diff --git a/crates/doc/src/feature_walk_tests.rs b/crates/doc/src/feature_walk_tests.rs index 818bc3b63..2db17da0c 100644 --- a/crates/doc/src/feature_walk_tests.rs +++ b/crates/doc/src/feature_walk_tests.rs @@ -73,9 +73,9 @@ fn ref_record() -> String { out } -/// A variant with a field that refers to a sketch (a field named `*sketch*` holding an id, sketch -/// points or loft sections) must report it from `input_sketches`, or deleting the sketch leaves -/// the feature broken. New variants are caught by the walk's exhaustive match; this catches a +/// A variant with a field that refers to a sketch (a `SketchId`, sketch points or loft +/// sections) must report it from `input_sketches`, or deleting the sketch leaves the feature +/// broken. New variants are caught by the walk's exhaustive match; this catches a /// sketch field added to an existing variant (its fixture has to set it). /// Per fixture (with every reference and position set): the fields `transform_geometry` changes /// under a turn and a shift (every point, direction and plane it maps), the face points that name @@ -107,7 +107,7 @@ fn geometry_record() -> String { out += &format!(" profiles: {}\n", profiles.join(", ")); } if let Some(p) = kind.point_expr() { - out += &format!(" placement: {}\n", p.join(", ")); + out += &format!(" placement: {}\n", p.iter().map(|e| e.as_str()).collect::>().join(", ")); } } out @@ -151,8 +151,8 @@ fn input_sketches_lists_every_variant_with_a_sketch_field() { variant = t.split(|c: char| !c.is_alphanumeric()).next().unwrap_or("").to_lowercase(); continue; } - let Some((name, ty)) = t.strip_prefix("pub ").unwrap_or(t).split_once(':') else { continue }; - let refers = (name.contains("sketch") && ty.contains("u64")) || ty.contains("SketchPoints") || ty.contains("LoftSection"); + let Some((_, ty)) = t.strip_prefix("pub ").unwrap_or(t).split_once(':') else { continue }; + let refers = ty.contains("SketchId") || ty.contains("SketchPoints") || ty.contains("LoftSection"); if refers && !t.starts_with("//") && !with_sketch.contains(&variant) { with_sketch.push(variant.clone()); } diff --git a/crates/doc/src/format.rs b/crates/doc/src/format.rs index 7f667d6ef..759200427 100644 --- a/crates/doc/src/format.rs +++ b/crates/doc/src/format.rs @@ -1435,7 +1435,7 @@ mod tests { .add_feature( FeatureKind::Extrude { thin: None, - sketch, + sketch: crate::SketchId(sketch), profiles: ProfileSel::All, extent: Extent { convention: crate::ExtrudeConvention::LegacyPerSide, @@ -1445,9 +1445,9 @@ mod tests { start_offset: None, through_all: false, taper: Some("0 deg".into()), - to: Some(solidcraft_geom::Vec3::new(0.0, 0.0, 10.0)), + to: Some(crate::FacePick(solidcraft_geom::Vec3::new(0.0, 0.0, 10.0))), to_offset: Some("offset + 1 mm".into()), - from: Some(solidcraft_geom::Vec3::new(0.0, 0.0, 5.0)), + from: Some(crate::FacePick(solidcraft_geom::Vec3::new(0.0, 0.0, 5.0))), }, operation: Operation::NewBody, targets: vec![], @@ -2077,7 +2077,7 @@ mod tests { "orientation": {"direction": [0.0, 1.0, 0.0]}, "twist": "90 deg", "scale": "0.5"}); let k: FeatureKind = serde_json::from_value(new.clone()).unwrap(); let FeatureKind::SurfaceSweep { orientation, .. } = &k else { panic!("{k:?}") }; - assert_eq!(*orientation, SweepOrientation::Direction(solidcraft_geom::Vec3::Y)); + assert_eq!(*orientation, SweepOrientation::Direction(crate::Dir(solidcraft_geom::Vec3::Y))); assert_eq!(serde_json::to_value(&k).unwrap(), new); let parallel: SweepOrientation = serde_json::from_value(serde_json::json!("parallel")).unwrap(); assert_eq!(parallel, SweepOrientation::Parallel); diff --git a/crates/doc/src/format_offsets.rs b/crates/doc/src/format_offsets.rs index aa3f52f45..073a1edd8 100644 --- a/crates/doc/src/format_offsets.rs +++ b/crates/doc/src/format_offsets.rs @@ -424,7 +424,7 @@ mod tests { .add_feature( FeatureKind::Extrude { thin: None, - sketch: if missing_sketch { 999_999 } else { id }, + sketch: crate::SketchId(if missing_sketch { 999_999 } else { id }), profiles: ProfileSel::OffsetBoundaries { associations: vec!["deleted-o1".into()] }, extent: crate::Extent { convention: crate::ExtrudeConvention::LegacyPerSide, diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 4d8b705b4..29f1d93a5 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -34,10 +34,12 @@ pub mod metadata; pub use metadata::Metadata; pub mod motion; mod name_lookup; +mod names; pub mod naming; mod params; pub mod physical_material; mod piece_names; +mod points; mod profile_refs; pub mod progress; mod walk; @@ -60,7 +62,10 @@ pub use eval::{ revolve_extent, revolve_extent_with_convention, select_profiles, sketch_hole_direction, state_in_frame, state_in_frame_at, through_all_distance, world_state, world_state_reusing, }; +pub use expr::Expr; +pub use names::{BodyName, FeatureName, SketchId}; pub use params::{ParamRow, ParamUser, cycles}; +pub use points::{Dir, FacePick, Position, plain}; pub use solidcraft_kernel as kernel; pub use solidcraft_sketch as sketch; diff --git a/crates/doc/src/names.rs b/crates/doc/src/names.rs new file mode 100644 index 000000000..e84b17a8e --- /dev/null +++ b/crates/doc/src/names.rs @@ -0,0 +1,146 @@ +//! What a feature refers to: bodies and features by name, sketches by id. Each is saved as the +//! plain name or id it wraps, but has its own type, so a body name can't be passed where a +//! feature name or an expression is meant. + +use std::ops::Deref; + +use serde::{Deserialize, Serialize}; + +macro_rules! name_type { + ($(#[$doc:meta])* $name:ident) => { + $(#[$doc])* + #[derive(Clone, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] + #[serde(transparent)] + pub struct $name(pub String); + + impl Deref for $name { + type Target = str; + fn deref(&self) -> &str { + &self.0 + } + } + + impl AsRef for $name { + fn as_ref(&self) -> &str { + &self.0 + } + } + + impl std::borrow::Borrow for $name { + fn borrow(&self) -> &str { + &self.0 + } + } + + impl From for $name { + fn from(s: String) -> Self { + $name(s) + } + } + + impl From<&str> for $name { + fn from(s: &str) -> Self { + $name(s.to_string()) + } + } + + impl From<&String> for $name { + fn from(s: &String) -> Self { + $name(s.clone()) + } + } + + impl From<$name> for String { + fn from(n: $name) -> String { + n.0 + } + } + + impl std::fmt::Display for $name { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } + } + + impl PartialEq for $name { + fn eq(&self, other: &str) -> bool { + self.0 == other + } + } + + impl PartialEq<&str> for $name { + fn eq(&self, other: &&str) -> bool { + self.0 == *other + } + } + + impl PartialEq for $name { + fn eq(&self, other: &String) -> bool { + &self.0 == other + } + } + + impl PartialEq<$name> for String { + fn eq(&self, other: &$name) -> bool { + *self == other.0 + } + } + + impl PartialEq<$name> for str { + fn eq(&self, other: &$name) -> bool { + self == other.0 + } + } + }; +} + +name_type!( + /// A body, by name. + BodyName +); +name_type!( + /// A feature, by name. + FeatureName +); + +/// A sketch, by its feature id. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(transparent)] +pub struct SketchId(pub u64); + +impl Deref for SketchId { + type Target = u64; + fn deref(&self) -> &u64 { + &self.0 + } +} + +impl From for SketchId { + fn from(id: u64) -> Self { + SketchId(id) + } +} + +impl From for u64 { + fn from(id: SketchId) -> u64 { + id.0 + } +} + +impl PartialEq for SketchId { + fn eq(&self, other: &u64) -> bool { + self.0 == *other + } +} + +impl PartialEq for u64 { + fn eq(&self, other: &SketchId) -> bool { + *self == other.0 + } +} + +impl std::fmt::Display for SketchId { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.0.fmt(f) + } +} diff --git a/crates/doc/src/naming.rs b/crates/doc/src/naming.rs index 729651361..6b1f302eb 100644 --- a/crates/doc/src/naming.rs +++ b/crates/doc/src/naming.rs @@ -540,7 +540,7 @@ fn role_name(f: &Feature, before: &ModelState, ps: &[Vec3], ns: &[Vec3], fi: usi let c = ps.iter().fold(Vec3::ZERO, |a, p| a + *p) * (1.0 / ps.len().max(1) as f64); match &f.kind { FeatureKind::Extrude { sketch, .. } => { - let Some(ss) = before.sketch(*sketch) else { return format!("F{fid}:face:{fi}") }; + let Some(ss) = before.sketch(sketch.0) else { return format!("F{fid}:face:{fi}") }; let n = ss.plane.normal(); // A face across the extrusion is a cap; others sweep a sketch curve. let flat = !ns.is_empty() && ns.iter().all(|m| m.cross(n).len() < 1e-6); @@ -552,7 +552,7 @@ fn role_name(f: &Feature, before: &ModelState, ps: &[Vec3], ns: &[Vec3], fi: usi nearest_curve(ss, Vec2::new(q.x, q.y)).map(|id| format!("F{fid}:side:{id}")).unwrap_or_else(|| format!("F{fid}:face:{fi}")) } FeatureKind::Revolve { sketch, axis, .. } => { - let Some(ss) = before.sketch(*sketch) else { return format!("F{fid}:face:{fi}") }; + let Some(ss) = before.sketch(sketch.0) else { return format!("F{fid}:face:{fi}") }; let Ok((o2, d2)) = crate::eval::revolve_axis(ss, axis) else { return format!("F{fid}:face:{fi}") }; let (o, d) = (ss.plane.to_world(o2), (ss.plane.to_world(o2 + d2) - ss.plane.to_world(o2)).normalized().unwrap_or(Vec3::Z)); // A flat face holding the axis is an angle cap: on the sketch plane, or the far one. @@ -582,7 +582,7 @@ fn role_name(f: &Feature, before: &ModelState, ps: &[Vec3], ns: &[Vec3], fi: usi FeatureKind::Loft { sections, .. } => sections.first().map(|x| x.sketch), _ => None, }; - let Some(ss) = sk.and_then(|k| before.sketch(k)) else { return format!("F{fid}:face:{fi}") }; + let Some(ss) = sk.and_then(|k| before.sketch(k.0)) else { return format!("F{fid}:face:{fi}") }; let n = ss.plane.normal(); let h = |p: &Vec3| (*p - ss.plane.origin).dot(n); let flat = !ns.is_empty() && ns.windows(2).all(|w| w[0].cross(w[1]).len() < 1e-6); @@ -613,10 +613,10 @@ fn role_name(f: &Feature, before: &ModelState, ps: &[Vec3], ns: &[Vec3], fi: usi format!("F{fid}:{role}") } FeatureKind::Cylinder { axis, .. } => { - let flat = !ns.is_empty() && ns.iter().all(|m| m.cross(*axis).len() < 1e-6); + let flat = !ns.is_empty() && ns.iter().all(|m| m.cross(axis.0).len() < 1e-6); let role = if !flat { "side" - } else if ns.first().is_some_and(|m| m.dot(*axis) > 0.0) { + } else if ns.first().is_some_and(|m| m.dot(axis.0) > 0.0) { "top" } else { "bottom" diff --git a/crates/doc/src/params.rs b/crates/doc/src/params.rs index f956bcf12..76ab07461 100644 --- a/crates/doc/src/params.rs +++ b/crates/doc/src/params.rs @@ -8,7 +8,7 @@ use std::collections::{BTreeMap, BTreeSet}; use serde::{Deserialize, Serialize}; -use crate::expr::{self, Kind, ParamDef, Value}; +use crate::expr::{self, Expr, Kind, ParamDef, Value}; use crate::walk::Walk; use crate::{DocError, Document, FeatureKind, MAX_PARAMS, Result}; @@ -23,7 +23,7 @@ pub(crate) enum ExprRole { impl FeatureKind { /// The feature's numeric inputs: (label, expression, kind), in a fixed order. - pub fn inputs_mut(&mut self) -> Vec<(&'static str, &mut String, Kind)> { + pub fn inputs_mut(&mut self) -> Vec<(&'static str, &mut Expr, Kind)> { let mut v = Vec::new(); self.walk_exprs_mut(&mut |(label, e, kind, role)| { if role == ExprRole::Input { @@ -38,7 +38,7 @@ impl FeatureKind { let mut v = Vec::new(); self.walk_exprs(&mut |(label, e, kind, role)| { if role == ExprRole::Input { - v.push((label, e.clone(), kind)); + v.push((label, e.to_string(), kind)); } }); v @@ -47,7 +47,7 @@ impl FeatureKind { /// The coordinates of the points that place the feature: a primitive's position, an /// explicit plane's origin. They are not inputs (no parameter names), but follow /// parameters as inputs do. - pub fn placement_exprs_mut(&mut self) -> Vec<&mut String> { + pub fn placement_exprs_mut(&mut self) -> Vec<&mut Expr> { let mut v = Vec::new(); self.walk_exprs_mut(&mut |(_, e, _, role)| { if role == ExprRole::Placement { @@ -260,7 +260,7 @@ impl Document { if let Some(f) = next.features.get_mut(i) && let Some((_, e, _)) = f.kind.inputs_mut().into_iter().nth(k) { - *e = expr_s.clone(); + *e = expr_s.clone().into(); } if let Some(c) = comment { next.param_comments.insert(name.to_string(), c.to_string()); @@ -308,7 +308,7 @@ impl Document { if *target != normalized { changed.insert(name.clone()); } - *target = normalized; + *target = normalized.into(); } let (_, errors) = next.param_values(); for (name, error) in errors { @@ -673,14 +673,14 @@ impl Document { for e in f.kind.placement_exprs_mut() { let r = expr::rename_reference(e, old, new); if r != *e { - *e = r; + *e = r.into(); n += 1; } } for (_, e, _) in f.kind.inputs_mut() { let r = expr::rename_reference(e, old, new); if r != *e { - *e = r; + *e = r.into(); n += 1; } } diff --git a/crates/doc/src/points.rs b/crates/doc/src/points.rs new file mode 100644 index 000000000..f8c785f96 --- /dev/null +++ b/crates/doc/src/points.rs @@ -0,0 +1,61 @@ +//! The points a feature holds, by what they are: a point that picks a face, any other +//! position, a direction. Each is a `Vec3` (and is saved as one), but a different type, so a +//! direction can't be moved like a position, and a pick can't be mistaken for either. + +use std::ops::{Deref, DerefMut}; + +use serde::{Deserialize, Serialize}; +use solidcraft_geom::Vec3; + +macro_rules! point_type { + ($(#[$doc:meta])* $name:ident) => { + $(#[$doc])* + #[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] + #[serde(transparent)] + pub struct $name(pub Vec3); + + impl Deref for $name { + type Target = Vec3; + fn deref(&self) -> &Vec3 { + &self.0 + } + } + + impl DerefMut for $name { + fn deref_mut(&mut self) -> &mut Vec3 { + &mut self.0 + } + } + + impl From for $name { + fn from(v: Vec3) -> Self { + $name(v) + } + } + + impl From<$name> for Vec3 { + fn from(p: $name) -> Vec3 { + p.0 + } + } + }; +} + +point_type!( + /// A point that picks a face: it moves with the feature, and names the face it picks. + FacePick +); +point_type!( + /// A position (an edge pick, an axis origin, a fold line): it moves with the feature. + Position +); +point_type!( + /// A direction: it turns with the feature, and never moves. + Dir +); + +/// The plain values of a list of picks, positions, directions or names (for code that takes +/// `Vec3`s or `String`s). +pub fn plain>(ps: &[P]) -> Vec { + ps.iter().map(|p| p.clone().into()).collect() +} diff --git a/crates/doc/src/profile_refs.rs b/crates/doc/src/profile_refs.rs index dca0678a1..c1881d956 100644 --- a/crates/doc/src/profile_refs.rs +++ b/crates/doc/src/profile_refs.rs @@ -309,7 +309,7 @@ mod tests { .add_feature( crate::FeatureKind::Extrude { thin: None, - sketch: feature, + sketch: crate::SketchId(feature), profiles: selection.clone(), extent: crate::Extent { convention: crate::ExtrudeConvention::LegacyPerSide, @@ -436,7 +436,7 @@ mod tests { .add_feature( crate::FeatureKind::Extrude { thin: None, - sketch: feature, + sketch: crate::SketchId(feature), profiles: selection.clone(), extent: crate::Extent { convention: crate::ExtrudeConvention::LegacyPerSide, diff --git a/crates/doc/src/project.rs b/crates/doc/src/project.rs index b2aed274c..696d3e7dc 100644 --- a/crates/doc/src/project.rs +++ b/crates/doc/src/project.rs @@ -261,8 +261,11 @@ fn resolve_uncached( // Its path is a curve of its own sketch: set with the sketch (`Sketch::text_source_geometry`). LinkSource::Text { .. } => return Err(DocError::Invalid("a text on a path is set with its sketch".into())), LinkSource::Plane { name } => { - let pr = - if Plane::named(name).is_some() { PlaneRef::Origin { name: name.clone() } } else { PlaneRef::Construction { name: name.clone() } }; + let pr = if Plane::named(name).is_some() { + PlaneRef::Origin { name: name.clone() } + } else { + PlaneRef::Construction { name: name.clone().into() } + }; let other = doc.resolve_plane_in(vals, &pr, 0, Some(st)).map_err(|_| lost(&format!("plane {name}")))?; plane_trace(plane, &other).into_iter().collect() } diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index a4f5aaa9f..c3dab4b20 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -30,7 +30,7 @@ fn plate_doc() -> (Document, u64) { doc.add_feature( FeatureKind::Extrude { thin: None, - sketch: s, + sketch: crate::SketchId(s), profiles: ProfileSel::All, extent: Extent { convention: crate::ExtrudeConvention::LegacyPerSide, @@ -108,7 +108,7 @@ fn box_fillet_cut_timeline() { let (mut doc, _) = plate_doc(); doc.add_feature( FeatureKind::Fillet { - edges: vec![Vec3::new(0.0, 0.0, 10.0)], + edges: vec![Position(Vec3::new(0.0, 0.0, 10.0))], radius: "3".into(), body: None, style: Default::default(), @@ -123,7 +123,7 @@ fn box_fillet_cut_timeline() { doc.add_feature( FeatureKind::Extrude { thin: None, - sketch: s2, + sketch: crate::SketchId(s2), profiles: ProfileSel::Points { points: vec![Vec2::new(20.0, 15.0)] }, extent: Extent { convention: crate::ExtrudeConvention::LegacyPerSide, @@ -162,7 +162,7 @@ fn errors_are_reported_not_fatal() { let (mut doc, s) = plate_doc(); doc.add_feature( FeatureKind::Revolve { - sketch: s, + sketch: crate::SketchId(s), profiles: ProfileSel::All, axis: AxisRef::SketchAxis { axis: "y".into() }, angle: "90 deg".into(), @@ -178,7 +178,7 @@ fn errors_are_reported_not_fatal() { .unwrap(); doc.add_feature( FeatureKind::Fillet { - edges: vec![Vec3::new(500.0, 0.0, 0.0)], + edges: vec![Position(Vec3::new(500.0, 0.0, 0.0))], radius: "1".into(), body: None, style: Default::default(), @@ -244,7 +244,7 @@ fn primitives_and_combine() { doc.add_feature( FeatureKind::Cylinder { base: point_expr(Vec3::new(5.0, 5.0, 0.0)), - axis: Vec3::Z, + axis: Dir(Vec3::Z), radius: "2".into(), height: "20".into(), operation: Operation::NewBody, diff --git a/crates/doc/src/walk.rs b/crates/doc/src/walk.rs index 534af73c8..d7c54c8f1 100644 --- a/crates/doc/src/walk.rs +++ b/crates/doc/src/walk.rs @@ -13,13 +13,13 @@ pub(crate) use crate::expr::Kind; pub(crate) use crate::feature_geometry::Geo; pub(crate) use crate::feature_refs::Ref; pub(crate) use crate::params::ExprRole; -use crate::{PlaneRef, PointExpr}; +use crate::{BodyName, Dir, Expr, FacePick, FeatureName, PlaneRef, PointExpr, Position, SketchId}; /// An expression: its label, the expression, its kind and its role. -pub(crate) type ExprItem<'a> = (&'static str, &'a String, Kind, ExprRole); -pub(crate) type ExprItemMut<'a> = (&'static str, &'a mut String, Kind, ExprRole); -pub(crate) type RefItem<'a> = Ref<&'a u64, &'a String>; -pub(crate) type RefItemMut<'a> = Ref<&'a mut u64, &'a mut String>; +pub(crate) type ExprItem<'a> = (&'static str, &'a Expr, Kind, ExprRole); +pub(crate) type ExprItemMut<'a> = (&'static str, &'a mut Expr, Kind, ExprRole); +pub(crate) type RefItem<'a> = Ref<&'a SketchId, &'a FeatureName, &'a BodyName>; +pub(crate) type RefItemMut<'a> = Ref<&'a mut SketchId, &'a mut FeatureName, &'a mut BodyName>; pub(crate) type GeoItem<'a> = Geo<&'a Vec3, &'a PlaneRef, &'a GeoRef, &'a PointExpr, &'a ProfileSel>; pub(crate) type GeoItemMut<'a> = Geo<&'a mut Vec3, &'a mut PlaneRef, &'a mut GeoRef, &'a mut PointExpr, &'a mut ProfileSel>; @@ -56,6 +56,52 @@ impl Walk for crate::document::RuledMode {} impl Walk for crate::document::RuledCorners {} impl Walk for crate::document::ExtrudeConvention {} +/// A reference walks itself: a sketch, a feature or a body. +macro_rules! reference { + ($t:ty, $role:ident) => { + impl Walk for $t { + fn walk_refs<'a>(&'a self, f: &mut dyn FnMut(RefItem<'a>)) { + f(Ref::$role(self)) + } + fn walk_refs_mut<'a>(&'a mut self, f: &mut dyn FnMut(RefItemMut<'a>)) { + f(Ref::$role(self)) + } + } + }; +} + +reference!(SketchId, Sketch); +reference!(FeatureName, Feature); +reference!(BodyName, Body); + +/// A point walks itself with its role: a face pick, a position or a direction. As a plain +/// `Vec3` it also serves a field whose attribute gives it another role (`pinned`, `pick_if`). +macro_rules! point { + ($t:ty, $role:ident) => { + impl Walk for $t { + fn walk_geometry<'a>(&'a self, f: &mut dyn FnMut(GeoItem<'a>)) { + f(Geo::$role(&self.0)) + } + fn walk_geometry_mut<'a>(&'a mut self, f: &mut dyn FnMut(GeoItemMut<'a>)) { + f(Geo::$role(&mut self.0)) + } + } + + impl Each for $t { + fn each<'a>(&'a self, f: &mut dyn FnMut(&'a Vec3)) { + f(&self.0) + } + fn each_mut<'a>(&'a mut self, f: &mut dyn FnMut(&'a mut Vec3)) { + f(&mut self.0) + } + } + }; +} + +point!(FacePick, Pick); +point!(Position, Pos); +point!(Dir, Dir); + /// Containers walk what they hold, in order. macro_rules! walk_each { ($([$($g:tt)*] $t:ty),*) => {$( @@ -182,36 +228,36 @@ impl Each for Option> { /// The expressions of an expression field, each with its index and their count (for its label). pub(crate) trait ExprField { - fn each<'a>(&'a self, f: &mut dyn FnMut(usize, usize, &'a String)); - fn each_mut<'a>(&'a mut self, f: &mut dyn FnMut(usize, usize, &'a mut String)); + fn each<'a>(&'a self, f: &mut dyn FnMut(usize, usize, &'a Expr)); + fn each_mut<'a>(&'a mut self, f: &mut dyn FnMut(usize, usize, &'a mut Expr)); } -impl ExprField for String { - fn each<'a>(&'a self, f: &mut dyn FnMut(usize, usize, &'a String)) { +impl ExprField for Expr { + fn each<'a>(&'a self, f: &mut dyn FnMut(usize, usize, &'a Expr)) { f(0, 1, self) } - fn each_mut<'a>(&'a mut self, f: &mut dyn FnMut(usize, usize, &'a mut String)) { + fn each_mut<'a>(&'a mut self, f: &mut dyn FnMut(usize, usize, &'a mut Expr)) { f(0, 1, self) } } /// A position along an edge with its radius (a variable fillet's mid radii). -impl ExprField for (f64, String) { - fn each<'a>(&'a self, f: &mut dyn FnMut(usize, usize, &'a String)) { +impl ExprField for (f64, Expr) { + fn each<'a>(&'a self, f: &mut dyn FnMut(usize, usize, &'a Expr)) { f(0, 1, &self.1) } - fn each_mut<'a>(&'a mut self, f: &mut dyn FnMut(usize, usize, &'a mut String)) { + fn each_mut<'a>(&'a mut self, f: &mut dyn FnMut(usize, usize, &'a mut Expr)) { f(0, 1, &mut self.1) } } impl ExprField for Option { - fn each<'a>(&'a self, f: &mut dyn FnMut(usize, usize, &'a String)) { + fn each<'a>(&'a self, f: &mut dyn FnMut(usize, usize, &'a Expr)) { if let Some(t) = self { t.each(f) } } - fn each_mut<'a>(&'a mut self, f: &mut dyn FnMut(usize, usize, &'a mut String)) { + fn each_mut<'a>(&'a mut self, f: &mut dyn FnMut(usize, usize, &'a mut Expr)) { if let Some(t) = self { t.each_mut(f) } @@ -222,13 +268,13 @@ impl ExprField for Option { macro_rules! expr_list { ($([$($g:tt)*] $t:ty),*) => {$( impl<$($g)*> ExprField for $t { - fn each<'a>(&'a self, f: &mut dyn FnMut(usize, usize, &'a String)) { + fn each<'a>(&'a self, f: &mut dyn FnMut(usize, usize, &'a Expr)) { let n = self.len(); for (i, t) in self.iter().enumerate() { t.each(&mut |_, _, e| f(i, n, e)); } } - fn each_mut<'a>(&'a mut self, f: &mut dyn FnMut(usize, usize, &'a mut String)) { + fn each_mut<'a>(&'a mut self, f: &mut dyn FnMut(usize, usize, &'a mut Expr)) { let n = self.len(); for (i, t) in self.iter_mut().enumerate() { t.each_mut(&mut |_, _, e| f(i, n, e)); diff --git a/crates/engine/src/cmd/browser.rs b/crates/engine/src/cmd/browser.rs index 83b3a50a0..607cd25de 100644 --- a/crates/engine/src/cmd/browser.rs +++ b/crates/engine/src/cmd/browser.rs @@ -837,7 +837,7 @@ mod tests { solidcraft_doc::FeatureKind::Move { bodies, .. } => Some(bodies.clone()), _ => None, }); - assert_eq!(moved, Some(vec!["Lid".to_string()]), "the move follows the rename"); + assert_eq!(moved, Some(vec![solidcraft_doc::BodyName::from("Lid")]), "the move follows the rename"); assert!(s.model.results.iter().all(|r| r.error.is_none())); } diff --git a/crates/engine/src/cmd/component_clone.rs b/crates/engine/src/cmd/component_clone.rs index bf03c14d5..368d324db 100644 --- a/crates/engine/src/cmd/component_clone.rs +++ b/crates/engine/src/cmd/component_clone.rs @@ -1,4 +1,5 @@ //! Independent copies of a component definition graph, assembled and evaluated atomically. +use solidcraft_doc::BodyName; use std::collections::{BTreeMap, BTreeSet}; use crate::params::bad; @@ -327,7 +328,7 @@ pub(super) fn paste( let entry = feats.iter().find(|f| { !f.suppressed && matches!(&f.kind, FeatureKind::BodyTransfer { bodies, from, to, .. } - if !selected.contains(from) && bodies.contains(&body.name) + if !selected.contains(from) && bodies.iter().any(|b| *b == body.name) && s.model.result(f.id).is_some_and(|result| !result.skipped && result.error.is_none() && result.state.body(&body.name).is_some_and(|entered| source.model_body_component(entered) == *to))) }); @@ -426,7 +427,7 @@ pub(super) fn paste( if let FeatureKind::Emboss { face: Some(face), .. } = &mut f.kind && !face.path.is_empty() && let FeatureKind::Emboss { face: Some(old_face), .. } = &old.kind - && bodies.contains_key(&old_face.body) + && bodies.contains_key(old_face.body.as_ref()) { face.path = cloned_path(&source, &old_face.path, component, &clone_path, &occurrences)?; } @@ -483,7 +484,7 @@ pub(super) fn paste( .collect(); if !moved_out.is_empty() { let name = unique("Assigned-out bodies", &mut used); - let id = scratch.doc_mut().add_feature(FeatureKind::Remove { bodies: moved_out }, Some(&name))?; + let id = scratch.doc_mut().add_feature(FeatureKind::Remove { bodies: moved_out.into_iter().map(BodyName).collect() }, Some(&name))?; if let Some(f) = scratch.doc_mut().feature_mut(id) { f.component = root; } @@ -526,7 +527,7 @@ pub(super) fn paste( for feature in &feats { if let FeatureKind::Emboss { face: Some(face), .. } = &feature.kind && !face.path.is_empty() - && !bodies.contains_key(&face.body) + && !bodies.contains_key(face.body.as_ref()) { notices.push(format!("{} retains external selected occurrence path {:?}", feature.name, face.path)); } @@ -588,7 +589,7 @@ pub(super) fn paste( } if let FeatureKind::Pattern { features: references, .. } | FeatureKind::Mirror { features: references, .. } = &feature.kind { for name in references { - if !names.contains_key(name) { + if !names.contains_key(name.as_ref()) { notices.push(format!("{} retains external feature reference {name}", feature.name)); } } diff --git a/crates/engine/src/cmd/component_clone_tests.rs b/crates/engine/src/cmd/component_clone_tests.rs index 4d9faaa2f..081d40385 100644 --- a/crates/engine/src/cmd/component_clone_tests.rs +++ b/crates/engine/src/cmd/component_clone_tests.rs @@ -376,7 +376,7 @@ fn generated_copy_parameters_cannot_heal_an_unrelated_missing_reference() { let feature = s.doc_mut().feature_mut(broken).unwrap(); feature.component = 0; if let solidcraft_doc::FeatureKind::Box { width, .. } = &mut feature.kind { - *width = missing; + *width = missing.into(); } s.refresh(); let original_error = s.model.result(broken).unwrap().error.clone(); diff --git a/crates/engine/src/cmd/component_transfer.rs b/crates/engine/src/cmd/component_transfer.rs index 685927276..08ede2047 100644 --- a/crates/engine/src/cmd/component_transfer.rs +++ b/crates/engine/src/cmd/component_transfer.rs @@ -1,5 +1,6 @@ //! Atomic timeline ownership changes, preserving the selected world geometry. use super::*; +use solidcraft_doc::BodyName; use std::collections::{BTreeMap, BTreeSet}; type UniqueFrames = BTreeMap, Mat)>>; @@ -83,7 +84,7 @@ fn transfer(s: &mut Session, name: &str, to: u64, frames: &UniqueFrames, cmd: &s if let Some(look) = inherited { s.doc_mut().appearances.bodies.insert(name.to_string(), look); } - let id = s.doc_mut().add_feature(FeatureKind::BodyTransfer { bodies: vec![name.to_string()], from, to, transform }, None)?; + let id = s.doc_mut().add_feature(FeatureKind::BodyTransfer { bodies: vec![BodyName::from(name)], from, to, transform }, None)?; if let Some(feature) = s.doc_mut().feature_mut(id) { feature.component = to; } diff --git a/crates/engine/src/cmd/construct.rs b/crates/engine/src/cmd/construct.rs index 38e4103e9..460cbbdd1 100644 --- a/crates/engine/src/cmd/construct.rs +++ b/crates/engine/src/cmd/construct.rs @@ -135,8 +135,8 @@ fn geo(s: &Session, v: Option<&Value>, cmd: &str, what: &str) -> Result Ok(g) } -fn t_param(s: &Session, p: &Value, cmd: &str) -> Result { - let t = if p.get("t").is_some() { req_expr(cmd, p, "t")? } else { "0.5".to_string() }; +fn t_param(s: &Session, p: &Value, cmd: &str) -> Result { + let t = if p.get("t").is_some() { req_expr(cmd, p, "t")? } else { "0.5".into() }; check_expr(s, &t, solidcraft_doc::expr::Kind::Unitless, cmd, "t")?; Ok(t) } diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 2c90bf777..9ac6a07c1 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -767,7 +767,7 @@ fn edit_feature(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, unknown_field_message(&field, &before, f.kind.type_name()))); } if let FeatureKind::BodyTransfer { bodies, from, to, transform } = &nf.kind { - solidcraft_doc::validate_body_transfer(&s.doc, bodies, *from, *to, transform)?; + solidcraft_doc::validate_body_transfer(&s.doc, &solidcraft_doc::plain(bodies), *from, *to, transform)?; nf.component = *to; } if let (FeatureKind::Sketch { sketch: a, .. }, FeatureKind::Sketch { sketch: b, .. }) = (&nf.kind, &f.kind) @@ -783,22 +783,22 @@ fn edit_feature(s: &mut Session, p: &Value) -> Result { && a != b { let before = s.model.state_before(id); - nf.edge_refs = solidcraft_doc::edge_refs(&before, body, a); - nf.edge_names = solidcraft_doc::edge_names_for(&before, body, a); + nf.edge_refs = solidcraft_doc::edge_refs(&before, body, &solidcraft_doc::plain(a)); + nf.edge_names = solidcraft_doc::edge_names_for(&before, body, &solidcraft_doc::plain(a)); } // New or reordered flange edges: their names now, so each edge's own angle and height stay // with the edge they were given for. if let (FeatureKind::SheetFlange { edges: a, .. }, FeatureKind::SheetFlange { edges: b, .. }) = (&nf.kind, &f.kind) { let points = |e: &[solidcraft_doc::FlangeEdge]| e.iter().map(|x| x.point).collect::>(); if points(a) != points(b) { - nf.edge_names = solidcraft_doc::sheet::sheet_edge_names(&s.model.state_before(id), &points(a)); + nf.edge_names = solidcraft_doc::sheet::sheet_edge_names(&s.model.state_before(id), &solidcraft_doc::plain(&points(a))); } } // New bend edges for a conversion: the names of the body's edges there now. if let (FeatureKind::SheetConvert { bends: a, body, .. }, FeatureKind::SheetConvert { bends: b, body: was, .. }) = (&nf.kind, &f.kind) && (a != b || body != was) { - nf.edge_names = solidcraft_doc::sheet::bend_edge_names(&s.model.state_before(id), body, a); + nf.edge_names = solidcraft_doc::sheet::bend_edge_names(&s.model.state_before(id), body, &solidcraft_doc::plain(a)); } // Profiles picked by index or point are kept by their curves, as when the feature was made. if nf.kind.clone().profile_sels_mut() != f.kind.clone().profile_sels_mut() { @@ -1045,7 +1045,7 @@ fn redefine(s: &mut Session, p: &Value) -> Result { && before.body == after.body && before.path == after.path && before.author_path == after.author_path - && before.at.dist(after.at) < 1e-8 + && before.at.dist(after.at.0) < 1e-8 { *after = before.clone(); } diff --git a/crates/engine/src/cmd/face_tests.rs b/crates/engine/src/cmd/face_tests.rs index 43740ebfd..5ff74c3a3 100644 --- a/crates/engine/src/cmd/face_tests.rs +++ b/crates/engine/src/cmd/face_tests.rs @@ -35,7 +35,7 @@ fn generated_face_profiles_keep_exact_links_live_after_edit_and_reopen() { let result = run(&mut s, "solid.extrude", json!({"face":[5,5,20],"distance":10,"operation":"new","name":"Pad"})); let pad = s.doc.feature(result["feature"].as_u64().unwrap()).unwrap(); let FeatureKind::Extrude { sketch, .. } = pad.kind else { panic!("extrude") }; - let generated = s.doc.feature(sketch).unwrap(); + let generated = s.doc.feature(sketch.0).unwrap(); let FeatureKind::Sketch { plane, sketch: profile } = &generated.kind else { panic!("sketch") }; let PlaneRef::Face { anchor: Some(anchor), .. } = plane else { panic!("the original Box cap remains exact after a hole cut") }; assert_eq!(anchor.target.origin_feature, base); @@ -50,8 +50,8 @@ fn generated_face_profiles_keep_exact_links_live_after_edit_and_reopen() { let edited = s.model.state(); assert!(edited.bodies.iter().any(|body| body.body.contains(Vec3::new(49.0, 5.0, 34.0)))); assert!(!edited.bodies.iter().any(|body| body.body.contains(Vec3::new(51.0, 5.0, 34.0)))); - assert!(edited.sketch(sketch).unwrap().sketch.links.iter().all(|link| link.auto_face && !link.lost)); - let solved = edited.sketch(sketch).unwrap().plane; + assert!(edited.sketch(sketch.0).unwrap().sketch.links.iter().all(|link| link.auto_face && !link.lost)); + let solved = edited.sketch(sketch.0).unwrap().plane; assert!((solved.origin.z - 25.0).abs() < 1e-6); let before = s.model.state(); let before_volume: f64 = before.bodies.iter().map(|body| solidcraft_kernel::measure(&body.body).unwrap().volume).sum(); diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs index c9055cb40..eaf371aec 100644 --- a/crates/engine/src/cmd/features.rs +++ b/crates/engine/src/cmd/features.rs @@ -2,8 +2,10 @@ use serde_json::{Value, json}; use solidcraft_doc::{ - AxisRef, Direction, Extent, FeatureKind, Operation, PointExpr, ProfileSel, SweepOrientation, ThinSide, ThinWall, expr::Kind, point_expr, + AxisRef, Direction, Expr, Extent, FeatureKind, Operation, PointExpr, ProfileSel, SweepOrientation, ThinSide, ThinWall, expr::Kind, point_expr, }; +use solidcraft_doc::{BodyName, FeatureName, SketchId}; +use solidcraft_doc::{Dir, FacePick, Position}; use solidcraft_geom::Vec3; use super::{CommandSpec, not_in_sketch}; @@ -393,7 +395,7 @@ fn add_feature_in(s: &mut Session, p: &Value, kind: FeatureKind, world: bool) -> if s.doc.units.trim() != "mm" { let doc = s.doc.clone(); for (_, e, k) in kind.inputs_mut() { - *e = doc.with_design_unit(e, k); + *e = doc.with_design_unit(e, k).into(); } } // Profiles picked by index are kept by the curves around them: a recompute can renumber a @@ -403,17 +405,20 @@ fn add_feature_in(s: &mut Session, p: &Value, kind: FeatureKind, world: bool) -> let (refs, names) = match &kind { FeatureKind::Fillet { edges, body, .. } | FeatureKind::Chamfer { edges, body, .. } => { let st = s.model.state(); - (solidcraft_doc::edge_refs(&st, body, edges), solidcraft_doc::edge_names_for(&st, body, edges)) + ( + solidcraft_doc::edge_refs(&st, body, &solidcraft_doc::plain(edges)), + solidcraft_doc::edge_names_for(&st, body, &solidcraft_doc::plain(edges)), + ) } // Sheet metal edges are named by the sheet model. FeatureKind::SheetFlange { edges, .. } => { let points: Vec<_> = edges.iter().map(|e| e.point).collect(); - (Vec::new(), solidcraft_doc::sheet::sheet_edge_names(&s.model.state(), &points)) + (Vec::new(), solidcraft_doc::sheet::sheet_edge_names(&s.model.state(), &solidcraft_doc::plain(&points))) } - FeatureKind::SheetHem { edges, .. } => (Vec::new(), solidcraft_doc::sheet::sheet_edge_names(&s.model.state(), edges)), + FeatureKind::SheetHem { edges, .. } => (Vec::new(), solidcraft_doc::sheet::sheet_edge_names(&s.model.state(), &solidcraft_doc::plain(edges))), // A conversion's bend edges are edges of the body it converts. FeatureKind::SheetConvert { body, bends, .. } if !bends.is_empty() => { - (Vec::new(), solidcraft_doc::sheet::bend_edge_names(&s.model.state(), body, bends)) + (Vec::new(), solidcraft_doc::sheet::bend_edge_names(&s.model.state(), body, &solidcraft_doc::plain(bends))) } _ => (Vec::new(), Vec::new()), }; @@ -424,7 +429,7 @@ fn add_feature_in(s: &mut Session, p: &Value, kind: FeatureKind, world: bool) -> let body = state.body(&face.body).ok_or_else(|| EngineError::Other("selected cylinder body no longer exists".into()))?; let frame = face.body_frame(&s.doc, body).map_err(|e| EngineError::Other(e.to_string()))?; let inverse = solidcraft_doc::mat_inverse(&frame).ok_or_else(|| EngineError::Other("invalid cylinder placement".into()))?; - let at = solidcraft_doc::apply_point(&solidcraft_doc::mat_mul(&inverse, &s.active_component_frame()), face.at); + let at = solidcraft_doc::apply_point(&solidcraft_doc::mat_mul(&inverse, &s.active_component_frame()), face.at.0); let mut scoped = solidcraft_doc::ModelState::default(); scoped.bodies.push(body.clone()); let names = solidcraft_doc::naming::face_names_at(&scoped, &[at]); @@ -561,7 +566,7 @@ fn extrude(s: &mut Session, p: &Value) -> Result { targets.extend(face_body.or_else(|| sketch_face_body(s, sketch))); } let kind = FeatureKind::Extrude { - sketch, + sketch: SketchId(sketch), profiles: match face_profile { Some(f) => f, None if thin.is_some() => ProfileSel::All, @@ -569,7 +574,7 @@ fn extrude(s: &mut Session, p: &Value) -> Result { }, extent, operation, - targets, + targets: targets.into_iter().map(BodyName).collect(), thin, }; add_feature(s, p, kind) @@ -685,9 +690,9 @@ pub(super) fn extent_param(s: &Session, p: &Value, cmd: &str) -> Result start_offset, through_all, taper, - to: p.get("to").and_then(vec3), + to: p.get("to").and_then(vec3).map(FacePick), to_offset: expr(p, "to_offset"), - from: p.get("from").and_then(vec3), + from: p.get("from").and_then(vec3).map(FacePick), }) } @@ -724,16 +729,16 @@ fn revolve(s: &mut Session, p: &Value) -> Result { Some(value) => serde_json::from_value(value.clone()).map_err(|_| bad(cmd, "`convention` must be sketch_normal or legacy_axis_start"))?, }; let kind = FeatureKind::Revolve { - sketch, + sketch: SketchId(sketch), profiles, axis, angle, operation: operation(p, cmd)?, - targets: string_list(p, "targets"), + targets: string_list(p, "targets").into_iter().map(BodyName).collect(), angle2, symmetric, convention, - to, + to: to.map(FacePick), }; add_feature(s, p, kind) } @@ -744,7 +749,7 @@ pub(super) fn axis_param(p: &Value, cmd: &str) -> Result { if let Some(o) = p.get("axis").filter(|v| v.is_object()) { let origin = o.get("origin").and_then(vec3).unwrap_or(Vec3::ZERO); let dir = o.get("dir").and_then(vec3).ok_or_else(|| bad(cmd, "axis needs `dir`"))?; - return Ok(AxisRef::Line { origin, dir }); + return Ok(AxisRef::Line { origin: Position(origin), dir: Dir(dir) }); } match str_(p, "axis") { Some(a @ ("X" | "Y" | "Z")) => Ok(AxisRef::World { axis: a.into() }), @@ -754,12 +759,12 @@ pub(super) fn axis_param(p: &Value, cmd: &str) -> Result { } } -fn radius_expr(s: &Session, p: &Value, cmd: &str) -> Result { +fn radius_expr(s: &Session, p: &Value, cmd: &str) -> Result { match (expr(p, "radius"), expr(p, "diameter")) { (Some(r), _) => Ok(r), (None, Some(d)) => { let [d] = length_operands(s, [(&d, &typed_length_unit(s))]); - Ok(format!("({d}) / 2")) + Ok(format!("({d}) / 2").into()) } _ => Err(bad(cmd, "needs `radius` or `diameter`")), } @@ -833,11 +838,13 @@ fn prim_box(s: &mut Session, p: &Value) -> Result { (None, Some([cx, cy, cz])) => { let unit = typed_length_unit(s); let mm_per_unit = solidcraft_doc::expr::unit_info(&unit).map_or(1.0, |(_, k)| k); - let back = |c: String, size: &String| match (c.parse::(), size.parse::()) { - (Ok(a), Ok(b)) => format!("{}", a - b * mm_per_unit / 2.0), - _ => { - let [c, size] = length_operands(s, [(&c, "mm"), (size, &unit)]); - format!("({c}) - ({size}) / 2") + let back = |c: Expr, size: &Expr| -> Expr { + match (c.parse::(), size.parse::()) { + (Ok(a), Ok(b)) => format!("{}", a - b * mm_per_unit / 2.0).into(), + _ => { + let [c, size] = length_operands(s, [(&c, "mm"), (size, &unit)]); + format!("({c}) - ({size}) / 2").into() + } } }; [back(cx, &l), back(cy, &w), back(cz, &h)] @@ -855,7 +862,7 @@ fn prim_cylinder(s: &mut Session, p: &Value) -> Result { check_expr(s, &height, Kind::Length, cmd, "height")?; let base = point_param(s, p, "base", cmd)?.unwrap_or_else(|| point_expr(Vec3::ZERO)); let axis = axis_dir_param(p, cmd)?; - add_feature(s, p, FeatureKind::Cylinder { base, axis, radius, height, operation: operation(p, cmd)? }) + add_feature(s, p, FeatureKind::Cylinder { base, axis: Dir(axis), radius, height, operation: operation(p, cmd)? }) } fn prim_sphere(s: &mut Session, p: &Value) -> Result { @@ -968,8 +975,8 @@ fn press_pull(s: &mut Session, p: &Value) -> Result { // Pushed in: the extrude cuts the other way by as much (a bare number stays one, so it keeps // being read as a bare number typed into the extrude). let flipped = match distance.trim().parse::() { - Ok(v) if solidcraft_doc::expr::is_bare_number(&distance) => format!("{}", -v), - _ => format!("-({distance})"), + Ok(v) if solidcraft_doc::expr::is_bare_number(&distance) => Expr::new(format!("{}", -v)), + _ => Expr::new(format!("-({distance})")), }; let (dist, dir, op) = if d > 0.0 { (distance, "positive", "join") } else { (flipped, "negative", "cut") }; extrude(s, &json!({"face": face, "distance": dist, "direction": dir, "operation": op})) @@ -1003,10 +1010,10 @@ fn fillet(s: &mut Session, p: &Value) -> Result { _ => return Err(bad(cmd, "a `mid` radius is a number or an expression")), }; check_expr(s, &r, Kind::Length, cmd, "mid radius")?; - mid.push((t, r)); + mid.push((t, r.into())); } let smooth = p.get("smooth").and_then(Value::as_bool).unwrap_or(false); - solidcraft_doc::FilletStyle::Variable { radius2, start, mid, smooth } + solidcraft_doc::FilletStyle::Variable { radius2, start: Position(start), mid, smooth } } Some("spline") => { let start = p @@ -1022,7 +1029,7 @@ fn fillet(s: &mut Session, p: &Value) -> Result { _ => return Err(bad(cmd, "a control radius is a number or an expression")), }; check_expr(s, &r, Kind::Length, cmd, "control radius")?; - radii.push(r); + radii.push(Expr::from(r)); } // All control radii (`radius` and `radii`) plus the degree (1…3) plus one. if radii.is_empty() || !(radii.len() + 3..=radii.len() + 5).contains(&knots.len()) { @@ -1031,7 +1038,7 @@ fn fillet(s: &mut Session, p: &Value) -> Result { "a spline fillet needs `radii` (the control radii after `radius`) and `knots` (as many as all control radii, the degree 1…3 and one more)", )); } - solidcraft_doc::FilletStyle::Spline { start, knots, radii } + solidcraft_doc::FilletStyle::Spline { start: Position(start), knots, radii } } Some(o) => return Err(bad(cmd, format!("unknown fillet type `{o}` (constant, chord, variable, spline or curvature)"))), }; @@ -1044,7 +1051,11 @@ fn fillet(s: &mut Session, p: &Value) -> Result { if !fit.is_exact() && !style.is_constant() { return Err(bad(cmd, "`fit: reduce` and `fit: taper` take a constant radius")); } - let mut out = add_feature(s, p, FeatureKind::Fillet { edges, radius, body: str_(p, "body").map(str::to_string), style, fit })?; + let mut out = add_feature( + s, + p, + FeatureKind::Fillet { edges: edges.into_iter().map(Position).collect(), radius, body: str_(p, "body").map(BodyName::from), style, fit }, + )?; // The radii the fillet used, when `fit: reduce` reduced it. if let Some(id) = out.get("feature").and_then(Value::as_u64) && let Some(state) = s.model.result(id).map(|res| &res.state) @@ -1074,7 +1085,18 @@ fn chamfer(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, "give `distance2` or `angle`, not both")); } let flip = bool_(p, "flip").unwrap_or(false); - add_feature(s, p, FeatureKind::Chamfer { edges, distance, distance2, angle, flip, body: str_(p, "body").map(str::to_string) }) + add_feature( + s, + p, + FeatureKind::Chamfer { + edges: edges.into_iter().map(Position).collect(), + distance, + distance2, + angle, + flip, + body: str_(p, "body").map(BodyName::from), + }, + ) } fn combine(s: &mut Session, p: &Value) -> Result { @@ -1091,7 +1113,12 @@ fn combine(s: &mut Session, p: &Value) -> Result { let mut out = add_feature( s, p, - FeatureKind::Combine { target: target.clone(), tools, operation: op, keep_tools: bool_(p, "keep_tools").unwrap_or(false) }, + FeatureKind::Combine { + target: target.clone().into(), + tools: tools.into_iter().map(BodyName).collect(), + operation: op, + keep_tools: bool_(p, "keep_tools").unwrap_or(false), + }, )?; // New Component: the result goes into a component of its own. if bool_(p, "new_component").unwrap_or(false) { @@ -1111,7 +1138,7 @@ fn move_bodies(s: &mut Session, p: &Value) -> Result { } let t = match p.get("translate") { Some(Value::Array(a)) if a.len() == 3 => { - let mut out: [String; 3] = Default::default(); + let mut out: [Expr; 3] = Default::default(); for (i, v) in a.iter().enumerate() { let e = expr(&json!({"v": v}), "v").ok_or_else(|| bad(cmd, "translate entries must be numbers or expressions"))?; check_expr(s, &e, Kind::Length, cmd, "translate")?; @@ -1131,7 +1158,13 @@ fn move_bodies(s: &mut Session, p: &Value) -> Result { add_feature( s, p, - FeatureKind::Move { bodies, translate: t, rotate_axis: p.get("axis").and_then(vec3), angle, copy: bool_(p, "copy").unwrap_or(false) }, + FeatureKind::Move { + bodies: bodies.into_iter().map(BodyName).collect(), + translate: t, + rotate_axis: p.get("axis").and_then(vec3).map(Dir), + angle, + copy: bool_(p, "copy").unwrap_or(false), + }, ) } @@ -1174,7 +1207,15 @@ fn axis_line(p: &Value, cmd: &str) -> Result<(Vec3, Vec3)> { fn finish_pattern(s: &mut Session, p: &Value, features: Vec, pattern: solidcraft_doc::PatternKind, bodies: Vec) -> Result { let comps = string_list(p, "components"); if comps.is_empty() { - return add_feature(s, p, FeatureKind::Pattern { features, pattern, bodies }); + return add_feature( + s, + p, + FeatureKind::Pattern { + features: features.into_iter().map(FeatureName).collect(), + pattern, + bodies: bodies.into_iter().map(BodyName).collect(), + }, + ); } let cmd = "pattern (components)"; let mats = solidcraft_doc::pattern_matrices(&s.doc, &s.model.state(), &pattern)?; @@ -1222,7 +1263,7 @@ fn pattern_rect(s: &mut Session, p: &Value) -> Result { if let Some(c) = &spacing2 { check_expr(s, c, Kind::Length, cmd, "spacing2")?; } - let pattern = solidcraft_doc::PatternKind::Rectangular { dir1, count1, spacing1, dir2, count2, spacing2 }; + let pattern = solidcraft_doc::PatternKind::Rectangular { dir1: Dir(dir1), count1, spacing1, dir2: dir2.map(Dir), count2, spacing2 }; finish_pattern(s, p, features, pattern, bodies) } @@ -1234,7 +1275,7 @@ fn pattern_circ(s: &mut Session, p: &Value) -> Result { check_expr(s, &count, Kind::Unitless, cmd, "count")?; let angle = expr(p, "angle").unwrap_or_else(|| "360 deg".into()); check_expr(s, &angle, Kind::Angle, cmd, "angle")?; - let pattern = solidcraft_doc::PatternKind::Circular { origin, axis, count, angle }; + let pattern = solidcraft_doc::PatternKind::Circular { origin: Position(origin), axis: Dir(axis), count, angle }; finish_pattern(s, p, features, pattern, bodies) } @@ -1260,7 +1301,7 @@ fn pattern_path(s: &mut Session, p: &Value) -> Result { Some(o) => return Err(bad(cmd, format!("unknown orientation `{o}` (identical or path)"))), }; let flip = bool_(p, "flip").unwrap_or(false); - let pattern = solidcraft_doc::PatternKind::Path { path_sketch, path, count, spacing, extent, flip, orient }; + let pattern = solidcraft_doc::PatternKind::Path { path_sketch: SketchId(path_sketch), path, count, spacing, extent, flip, orient }; finish_pattern(s, p, features, pattern, bodies) } @@ -1270,7 +1311,16 @@ fn mirror(s: &mut Session, p: &Value) -> Result { let features = if bodies.is_empty() { source_features(s, p, cmd)? } else { Vec::new() }; let plane = plane_param(s, p.get("plane"), cmd)?; let combine = bool_(p, "combine").unwrap_or(false); - add_feature(s, p, FeatureKind::Mirror { features, plane, bodies, combine }) + add_feature( + s, + p, + FeatureKind::Mirror { + features: features.into_iter().map(FeatureName).collect(), + plane, + bodies: bodies.into_iter().map(BodyName).collect(), + combine, + }, + ) } /// The other name of an origin plane (`Top` for `XY`, `XY` for `Top`...), if `name` is one. @@ -1306,7 +1356,7 @@ pub(super) fn plane_param(s: &Session, v: Option<&Value>, cmd: &str) -> Result Ok(PlaneRef::Construction { name: f.name.clone() }), + Some(f) if matches!(f.kind, FeatureKind::ConstructionPlane { .. }) => Ok(PlaneRef::Construction { name: f.name.clone().into() }), Some(f) => Err(bad(cmd, format!("`{}` is not a construction plane (a plane is {WANT})", f.name))), None => Err(bad(cmd, format!("no plane `{r}` (a plane is {WANT})"))), }; @@ -1339,7 +1389,7 @@ pub(super) fn plane_param(s: &Session, v: Option<&Value>, cmd: &str) -> Result point_expr(Vec3::ZERO), Some(_) => point_param(s, o, "origin", cmd)?.unwrap_or_else(|| point_expr(Vec3::ZERO)), }; - let at = |e: &String| s.doc.eval(e, Kind::Length).unwrap_or(0.0); + let at = |e: &str| s.doc.eval(e, Kind::Length).unwrap_or(0.0); let here = Vec3::new(at(&origin[0]), at(&origin[1]), at(&origin[2])); let pl = match (o.get("x_dir").and_then(vec3), o.get("y_dir").and_then(vec3), o.get("normal").and_then(vec3)) { (Some(x), Some(y), _) => solidcraft_geom::Plane::new(here, x, y), @@ -1393,13 +1443,25 @@ fn split_face(s: &mut Session, p: &Value) -> Result { let kind = if let Some(t) = p.get("tool").filter(|t| !t.is_null()) { 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(crate::params::vec3).ok_or_else(|| bad(cmd, "`tool.point` must be [x, y, z] on the tool face"))?; - FeatureKind::SplitFace { faces, body, plane: xy(), tool: Some(solidcraft_doc::FaceAt { body: tb, point }), sketch: None } + FeatureKind::SplitFace { + faces: faces.into_iter().map(FacePick).collect(), + body: body.map(BodyName), + plane: xy(), + tool: Some(solidcraft_doc::FaceAt { body: BodyName(tb), point: Position(point) }), + sketch: None, + } } else if p.get("sketch").is_some_and(|v| !v.is_null()) { let sketch = sketch_id(s, p.get("sketch"), cmd, "sketch")?; - FeatureKind::SplitFace { faces, body, plane: xy(), tool: None, sketch: Some(sketch) } + FeatureKind::SplitFace { + faces: faces.into_iter().map(FacePick).collect(), + body: body.map(BodyName), + plane: xy(), + tool: None, + sketch: Some(SketchId(sketch)), + } } else { let plane = plane_param(s, p.get("plane"), cmd)?; - FeatureKind::SplitFace { faces, body, plane, tool: None, sketch: None } + FeatureKind::SplitFace { faces: faces.into_iter().map(FacePick).collect(), body: body.map(BodyName), plane, tool: None, sketch: None } }; add_feature(s, p, kind) } @@ -1423,14 +1485,14 @@ fn split_body(s: &mut Session, p: &Value) -> Result { s, p, FeatureKind::Split { - body, + body: BodyName(body), plane: solidcraft_doc::PlaneRef::Origin { name: "XY".into() }, - tool: Some(solidcraft_doc::FaceAt { body: tb, point }), + tool: Some(solidcraft_doc::FaceAt { body: BodyName(tb), point: Position(point) }), }, ); } let plane = plane_param(s, p.get("plane"), cmd)?; - add_feature(s, p, FeatureKind::Split { body, plane, tool: None }) + add_feature(s, p, FeatureKind::Split { body: BodyName(body), plane, tool: None }) } /// ISO 273 clearance hole diameters (close, normal, loose fit) for metric bolts. @@ -1492,7 +1554,7 @@ fn hole(s: &mut Session, p: &Value) -> Result { let first = ids.first().and_then(|id| ss.sketch.points.iter().find(|q| &q.id == id)).map(|q| ss.plane.to_world(q.pos)).unwrap_or_default(); let flip = p.get("flip").and_then(Value::as_bool).unwrap_or(false); - Some((solidcraft_doc::SketchPoints { sketch, ids, flip }, first, -n)) + Some((solidcraft_doc::SketchPoints { sketch: SketchId(sketch), ids, flip }, first, -n)) } _ => None, }; @@ -1526,11 +1588,11 @@ fn hole(s: &mut Session, p: &Value) -> Result { (None, _, Some(c)) => { let fit = str_(p, "fit").unwrap_or("normal").to_ascii_lowercase(); let d = clearance_diameter(c, &fit).ok_or_else(|| bad(cmd, format!("no clearance hole for `{c}` ({fit} fit): M1.6 to M64")))?; - format!("{d} mm") + Expr::new(format!("{d} mm")) } (None, Some(t), None) => { let (major, pitch) = solidcraft_doc::parse_metric_thread(t).ok_or_else(|| bad(cmd, "thread"))?; - format!("{} mm", ((major - pitch) * 1000.0).round() / 1000.0) + Expr::new(format!("{} mm", ((major - pitch) * 1000.0).round() / 1000.0)) } (None, None, None) => return Err(bad(cmd, "needs `diameter`, `thread` (a tapped hole) or `clearance` (a bolt size)")), }; @@ -1539,7 +1601,7 @@ fn hole(s: &mut Session, p: &Value) -> Result { if let Some(d) = &depth { check_expr(s, d, Kind::Length, cmd, "depth")?; } - let get = |k: &str| -> Result { + let get = |k: &str| -> Result { let e = req_expr(cmd, p, k)?; Ok(e) }; @@ -1570,7 +1632,20 @@ fn hole(s: &mut Session, p: &Value) -> Result { { p["participants"] = json!([body]); } - add_feature(s, &p, FeatureKind::Hole { position, direction, diameter, depth, hole: kind, points: points.map(|x| x.0), thread, to }) + add_feature( + s, + &p, + FeatureKind::Hole { + position: FacePick(position), + direction: Dir(direction), + diameter, + depth, + hole: kind, + points: points.map(|x| x.0), + thread, + to: to.map(FacePick), + }, + ) } /// The body whose face is nearest `p` (within its pick tolerance), when it belongs to another @@ -1627,9 +1702,9 @@ fn shell(s: &mut Session, p: &Value) -> Result { s, p, FeatureKind::Shell { - faces, + faces: faces.into_iter().map(FacePick).collect(), thickness, - body: str_(p, "body").map(str::to_string), + body: str_(p, "body").map(BodyName::from), direction: if direction == "inside" { String::new() } else { direction }, tangent_chain: bool_(p, "tangent_chain").unwrap_or(false), }, @@ -1645,7 +1720,17 @@ fn draft(s: &mut Session, p: &Value) -> Result { let (vals, _) = s.doc.param_values(); let pl = s.doc.resolve_plane_in(&vals, &neutral, 0, Some(&s.model.state()))?; let pull = p.get("pull").and_then(vec3).unwrap_or_else(|| pl.normal()); - add_feature(s, p, FeatureKind::Draft { faces, angle, neutral, pull, body: str_(p, "body").map(str::to_string) }) + add_feature( + s, + p, + FeatureKind::Draft { + faces: faces.into_iter().map(FacePick).collect(), + angle, + neutral, + pull: Dir(pull), + body: str_(p, "body").map(BodyName::from), + }, + ) } pub(super) fn sketch_id(s: &Session, v: Option<&Value>, cmd: &str, what: &str) -> Result { @@ -1673,22 +1758,22 @@ fn sweep(s: &mut Session, p: &Value) -> Result { s, p, FeatureKind::Sweep { - sketch, + sketch: SketchId(sketch), profiles: profiles(p, cmd)?, - path_sketch, + path_sketch: SketchId(path_sketch), path, orientation, twist, scale, operation: operation(p, cmd)?, - targets: string_list(p, "targets"), + targets: string_list(p, "targets").into_iter().map(BodyName).collect(), }, ) } /// A sweep's `orientation`, `twist` and `scale` (solid.sweep and surface.sweep), checked: an /// orientation the sweep knows, a twist within four turns, an end scale within 0.01…100. -pub(super) fn sweep_options(s: &Session, p: &Value, cmd: &str) -> Result<(SweepOrientation, Option, Option)> { +pub(super) fn sweep_options(s: &Session, p: &Value, cmd: &str) -> Result<(SweepOrientation, Option, Option)> { let orientation = match p.get("orientation") { None | Some(Value::Null) => SweepOrientation::Perpendicular, Some(Value::String(o)) if o.eq_ignore_ascii_case("perpendicular") => SweepOrientation::Perpendicular, @@ -1700,7 +1785,7 @@ pub(super) fn sweep_options(s: &Session, p: &Value, cmd: &str) -> Result<(SweepO if !(d.len() > 1e-9) { return Err(bad(cmd, "the `orientation` direction must not be zero")); } - SweepOrientation::Direction(d) + SweepOrientation::Direction(Dir(d)) } }; let twist = match p.get("twist") { @@ -1744,12 +1829,20 @@ fn loft(s: &mut Session, p: &Value) -> Result { if !st.sketch(sketch).is_some_and(|ss| ss.sketch.points.iter().any(|q| q.id == pt)) { return Err(bad(cmd, format!("no point `{pt}` in the section's sketch"))); } - sections.push(solidcraft_doc::LoftSection { sketch, profiles: solidcraft_doc::ProfileSel::All, point: Some(pt.to_string()) }); + sections.push(solidcraft_doc::LoftSection { + sketch: SketchId(sketch), + profiles: solidcraft_doc::ProfileSel::All, + point: Some(pt.to_string()), + }); continue; } - sections.push(solidcraft_doc::LoftSection { sketch, profiles: profiles(sec, cmd)?, point: None }); + sections.push(solidcraft_doc::LoftSection { sketch: SketchId(sketch), profiles: profiles(sec, cmd)?, point: None }); } - add_feature(s, p, FeatureKind::Loft { sections, operation: operation(p, cmd)?, targets: string_list(p, "targets") }) + add_feature( + s, + p, + FeatureKind::Loft { sections, operation: operation(p, cmd)?, targets: string_list(p, "targets").into_iter().map(BodyName).collect() }, + ) } fn thread(s: &mut Session, p: &Value) -> Result { @@ -1769,7 +1862,7 @@ fn thread(s: &mut Session, p: &Value) -> Result { check_expr(s, l, Kind::Length, cmd, "length")?; } let modeled = p.get("modeled").and_then(Value::as_bool).unwrap_or(false); - let v = add_feature(s, p, FeatureKind::Thread { face, designation, length, modeled })?; + let v = add_feature(s, p, FeatureKind::Thread { face: FacePick(face), designation, length, modeled })?; let st = s.model.state(); let t = v.get("feature").and_then(Value::as_u64).and_then(|id| st.threads.iter().find(|t| t.feature == id).cloned()); Ok(json!({"feature": v.get("feature"), "name": v.get("name"), "thread": t})) @@ -1788,14 +1881,25 @@ fn pipe(s: &mut Session, p: &Value) -> Result { if let Some(w) = &wall { check_expr(s, w, Kind::Length, cmd, "wall")?; } - add_feature(s, p, FeatureKind::Pipe { path_sketch, path, diameter, wall, operation: operation(p, cmd)?, targets: string_list(p, "targets") }) + add_feature( + s, + p, + FeatureKind::Pipe { + path_sketch: SketchId(path_sketch), + path, + diameter, + wall, + operation: operation(p, cmd)?, + targets: string_list(p, "targets").into_iter().map(BodyName).collect(), + }, + ) } fn bounding_solid(s: &mut Session, p: &Value) -> Result { let cmd = "solid.bounding_solid"; let margin = expr(p, "margin").unwrap_or_else(|| "0".into()); check_expr(s, &margin, Kind::Length, cmd, "margin")?; - add_feature(s, p, FeatureKind::BoundingSolid { bodies: string_list(p, "bodies"), margin }) + add_feature(s, p, FeatureKind::BoundingSolid { bodies: string_list(p, "bodies").into_iter().map(BodyName).collect(), margin }) } fn scale(s: &mut Session, p: &Value) -> Result { @@ -1810,7 +1914,7 @@ fn scale(s: &mut Session, p: &Value) -> Result { for x in &e { check_expr(s, x, Kind::Unitless, cmd, "factors")?; } - Some([e[0].clone(), e[1].clone(), e[2].clone()]) + Some([e[0].clone().into(), e[1].clone().into(), e[2].clone().into()]) } Some(_) => return Err(bad(cmd, "`factors` must have three values")), None => None, @@ -1822,13 +1926,13 @@ fn scale(s: &mut Session, p: &Value) -> Result { }; check_expr(s, &factor, Kind::Unitless, cmd, "factor")?; let origin = p.get("origin").and_then(vec3).unwrap_or(Vec3::ZERO); - add_feature(s, p, FeatureKind::Scale { bodies, origin, factor, factors }) + add_feature(s, p, FeatureKind::Scale { bodies: bodies.into_iter().map(BodyName).collect(), origin: Position(origin), factor, factors }) } fn delete_face(s: &mut Session, p: &Value) -> Result { let faces = face_points(s, p, "face.delete")?; let heal = bool_(p, "heal").unwrap_or(true); - add_feature(s, p, FeatureKind::DeleteFace { faces, body: str_(p, "body").map(str::to_string), heal }) + add_feature(s, p, FeatureKind::DeleteFace { faces: faces.into_iter().map(FacePick).collect(), body: str_(p, "body").map(BodyName::from), heal }) } fn offset_face(s: &mut Session, p: &Value) -> Result { @@ -1836,7 +1940,11 @@ fn offset_face(s: &mut Session, p: &Value) -> Result { let faces = face_points(s, p, cmd)?; let distance = req_expr(cmd, p, "distance")?; check_expr(s, &distance, Kind::Length, cmd, "distance")?; - add_feature(s, p, FeatureKind::OffsetFace { faces, distance, body: str_(p, "body").map(str::to_string) }) + add_feature( + s, + p, + FeatureKind::OffsetFace { faces: faces.into_iter().map(FacePick).collect(), distance, body: str_(p, "body").map(BodyName::from) }, + ) } #[cfg(test)] diff --git a/crates/engine/src/cmd/features_more.rs b/crates/engine/src/cmd/features_more.rs index f2dd11e3f..556a0319b 100644 --- a/crates/engine/src/cmd/features_more.rs +++ b/crates/engine/src/cmd/features_more.rs @@ -3,6 +3,8 @@ use serde_json::Value; use solidcraft_doc::FeatureKind; use solidcraft_doc::expr::Kind; +use solidcraft_doc::{BodyName, SketchId}; +use solidcraft_doc::{Dir, FacePick, Position}; use solidcraft_geom::Vec3; use super::CommandSpec; @@ -57,11 +59,11 @@ fn coil(s: &mut Session, p: &Value) -> Result { (Some(n), _, Some(pt)) => (n, pt), (Some(n), Some(h), None) => { let [h] = length_operands(s, [(&h, &unit)]); - (n.clone(), format!("({h}) / ({n})")) + (n.clone(), format!("({h}) / ({n})").into()) } (None, Some(h), Some(pt)) => { let [h, by] = length_operands(s, [(&h, &unit), (&pt, &unit)]); - (format!("({h}) / ({by})"), pt) + (format!("({h}) / ({by})").into(), pt) } _ => return Err(bad(cmd, "give two of `revolutions`, `height` and `pitch`")), }; @@ -91,7 +93,7 @@ fn coil(s: &mut Session, p: &Value) -> Result { p, FeatureKind::Coil { base, - axis, + axis: Dir(axis), diameter, pitch, turns, @@ -101,7 +103,7 @@ fn coil(s: &mut Session, p: &Value) -> Result { start_angle, clockwise, operation, - targets: string_list(p, "targets"), + targets: string_list(p, "targets").into_iter().map(BodyName).collect(), }, ) } @@ -131,7 +133,7 @@ fn rib_like(s: &mut Session, p: &Value, cmd: &str, web: bool) -> Result { check_expr(s, d, Kind::Length, cmd, "depth")?; } let flip = bool_(p, "flip").unwrap_or(false); - add_feature(s, p, FeatureKind::Rib { sketch, curves, thickness, depth, flip, web }) + add_feature(s, p, FeatureKind::Rib { sketch: SketchId(sketch), curves, thickness, depth, flip, web }) } fn rib(s: &mut Session, p: &Value) -> Result { @@ -212,11 +214,15 @@ fn emboss(s: &mut Session, p: &Value) -> Result { } else { let inferred = infer_emboss_selection(s, sketch, &profiles, &depth, deboss, &targets)?; if let Some(face) = &inferred { - targets = vec![face.body.clone()]; + targets = vec![face.body.0.clone()]; } inferred }; - add_feature(s, p, FeatureKind::Emboss { sketch, profiles, depth, deboss, targets, face }) + add_feature( + s, + p, + FeatureKind::Emboss { sketch: SketchId(sketch), profiles, depth, deboss, targets: targets.into_iter().map(BodyName).collect(), face }, + ) } fn emboss_selection(s: &Session, selected: &solidcraft_doc::ModelBody, at: Vec3) -> Result { @@ -240,7 +246,7 @@ fn emboss_selection(s: &Session, selected: &solidcraft_doc::ModelBody, at: Vec3) return Err(bad(cmd, "cylinder placement is too deep")); } let inverse = solidcraft_doc::mat_inverse(&s.active_component_frame()).ok_or_else(|| bad(cmd, "invalid active frame"))?; - Ok(solidcraft_doc::EmbossFace { body: name.to_owned(), at: solidcraft_doc::apply_point(&inverse, at), path, author_path }) + Ok(solidcraft_doc::EmbossFace { body: name.into(), at: FacePick(solidcraft_doc::apply_point(&inverse, at)), path, author_path }) } fn check_emboss_positions(s: &Session, sketch: u64, body: &solidcraft_doc::ModelBody, face: &solidcraft_doc::EmbossFace) -> Result<()> { @@ -307,7 +313,7 @@ fn infer_emboss_selection( face.sketch_frame(&placed, s.active_component, sketch_owner, raw).map_err(|e| bad(cmd, e.to_string()))?; check_emboss_positions(s, sketch, selected, &face)?; let author_inverse = solidcraft_doc::mat_inverse(&s.active_component_frame()).ok_or_else(|| bad(cmd, "invalid author frame"))?; - face.at = solidcraft_doc::apply_point(&solidcraft_doc::mat_mul(&author_inverse, &body_frame), at); + face.at = FacePick(solidcraft_doc::apply_point(&solidcraft_doc::mat_mul(&author_inverse, &body_frame), at)); if chosen.is_some() { return Err(bad(cmd, "multiple tangent cylinders match the selected profiles; select a target face or body")); } @@ -341,7 +347,7 @@ fn replace_face(s: &mut Session, p: &Value) -> Result { None => plane_param(s, p.get("target"), cmd)?, }; let body = str_(p, "body").map(str::to_string); - add_feature(s, p, FeatureKind::ReplaceFace { faces, target, body }) + add_feature(s, p, FeatureKind::ReplaceFace { faces: faces.into_iter().map(FacePick).collect(), target, body: body.map(BodyName) }) } fn align(s: &mut Session, p: &Value) -> Result { @@ -376,7 +382,18 @@ fn align(s: &mut Session, p: &Value) -> Result { _ => (None, None), }; let flip = bool_(p, "flip").unwrap_or(false); - add_feature(s, p, FeatureKind::Align { bodies, from, to, from_normal, to_normal, flip }) + add_feature( + s, + p, + FeatureKind::Align { + bodies: bodies.into_iter().map(BodyName).collect(), + from: Position(from), + to: Position(to), + from_normal: from_normal.map(Dir), + to_normal: to_normal.map(Dir), + flip, + }, + ) } fn remove(s: &mut Session, p: &Value) -> Result { @@ -389,7 +406,7 @@ fn remove(s: &mut Session, p: &Value) -> Result { if let Some(b) = bodies.iter().find(|b| st.body(b).is_none()) { return Err(bad(cmd, format!("no body `{b}`"))); } - add_feature(s, p, FeatureKind::Remove { bodies }) + add_feature(s, p, FeatureKind::Remove { bodies: bodies.into_iter().map(BodyName).collect() }) } #[cfg(test)] @@ -443,5 +460,14 @@ fn boundary_fill(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, "`cells` must list 1…1000 points [x, y, z], one inside each cell")); } let operation = super::features::operation(p, cmd)?; - add_feature(s, p, FeatureKind::BoundaryFill { tools, cells, operation, remove_tools: bool_(p, "remove_tools").unwrap_or(false) }) + add_feature( + s, + p, + FeatureKind::BoundaryFill { + tools: tools.into_iter().map(BodyName).collect(), + cells: cells.into_iter().map(Position).collect(), + operation, + remove_tools: bool_(p, "remove_tools").unwrap_or(false), + }, + ) } diff --git a/crates/engine/src/cmd/plastic.rs b/crates/engine/src/cmd/plastic.rs index 4423f3bdb..e825ab75a 100644 --- a/crates/engine/src/cmd/plastic.rs +++ b/crates/engine/src/cmd/plastic.rs @@ -1,9 +1,11 @@ //! Plastic (enclosure) features: Boss, Lip / Groove, Snap Fit and Rest, and plastic rules. use serde_json::{Value, json}; +use solidcraft_doc::BodyName; use solidcraft_doc::FeatureKind; use solidcraft_doc::expr::Kind; use solidcraft_doc::plastic::PlasticRule; +use solidcraft_doc::{Dir, FacePick, Position}; use solidcraft_geom::Vec3; use super::CommandSpec; @@ -87,7 +89,7 @@ fn manage_rules(s: &mut Session, p: &Value) -> Result { let probe = e.replace("Thickness", "(1 mm)"); check_expr(s, &probe, kind, cmd, k)?; if let Some(slot) = rule.field_mut(k) { - *slot = e; + *slot = e.into(); } } } @@ -159,20 +161,20 @@ fn rest(s: &mut Session, p: &Value) -> Result { None => None, }; let kind = FeatureKind::Rest { - position, - direction, - along, + position: FacePick(position), + direction: Dir(direction), + along: along.map(Dir), width: required(s, p, "width", Kind::Length, cmd)?, length: checked(s, p, "length", Kind::Length, cmd)?, height: required(s, p, "height", Kind::Length, cmd)?, draft: checked(s, p, "draft", Kind::Angle, cmd)?, thickness: checked(s, p, "thickness", Kind::Length, cmd)?, - body: str_(p, "body").map(str::to_string), + body: str_(p, "body").map(BodyName::from), }; add_feature(s, p, kind) } -fn checked(s: &Session, p: &Value, k: &str, kind: Kind, cmd: &str) -> Result> { +fn checked(s: &Session, p: &Value, k: &str, kind: Kind, cmd: &str) -> Result> { match expr(p, k) { Some(e) => { check_expr(s, &e, kind, cmd, k)?; @@ -182,7 +184,7 @@ fn checked(s: &Session, p: &Value, k: &str, kind: Kind, cmd: &str) -> Result Result { +fn required(s: &Session, p: &Value, k: &str, kind: Kind, cmd: &str) -> Result { let e = req_expr(cmd, p, k)?; check_expr(s, &e, kind, cmd, k)?; Ok(e) @@ -202,8 +204,8 @@ fn boss(s: &mut Session, p: &Value) -> Result { let cmd = "plastic.boss"; let (position, direction) = placed(s, p, cmd)?; let kind = FeatureKind::Boss { - position, - direction, + position: FacePick(position), + direction: Dir(direction), diameter: required(s, p, "diameter", Kind::Length, cmd)?, height: required(s, p, "height", Kind::Length, cmd)?, hole_diameter: checked(s, p, "hole_diameter", Kind::Length, cmd)?, @@ -214,7 +216,7 @@ fn boss(s: &mut Session, p: &Value) -> Result { rib_thickness: checked(s, p, "rib_thickness", Kind::Length, cmd)?, rib_length: checked(s, p, "rib_length", Kind::Length, cmd)?, rib_offset: checked(s, p, "rib_offset", Kind::Length, cmd)?, - body: str_(p, "body").map(str::to_string), + body: str_(p, "body").map(BodyName::from), }; add_feature(s, p, kind) } @@ -233,13 +235,13 @@ fn lip(s: &mut Session, p: &Value) -> Result { Some(o) => return Err(bad(cmd, format!("unknown side `{o}` (inside or outside)"))), }; let kind = FeatureKind::Lip { - face, + face: Position(face), width: required(s, p, "width", Kind::Length, cmd)?, height: required(s, p, "height", Kind::Length, cmd)?, groove, gap: checked(s, p, "gap", Kind::Length, cmd)?, outside: outside || bool_(p, "outside").unwrap_or(false), - body: str_(p, "body").map(str::to_string), + body: str_(p, "body").map(BodyName::from), }; add_feature(s, p, kind) } @@ -252,15 +254,15 @@ fn snap_fit(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, "`hook` must point across the arm")); } let kind = FeatureKind::SnapFit { - position, - direction, - hook, + position: FacePick(position), + direction: Dir(direction), + hook: Dir(hook), length: required(s, p, "length", Kind::Length, cmd)?, thickness: required(s, p, "thickness", Kind::Length, cmd)?, width: required(s, p, "width", Kind::Length, cmd)?, catch_depth: required(s, p, "catch_depth", Kind::Length, cmd)?, catch_length: required(s, p, "catch_length", Kind::Length, cmd)?, - body: str_(p, "body").map(str::to_string), + body: str_(p, "body").map(BodyName::from), }; add_feature(s, p, kind) } diff --git a/crates/engine/src/cmd/sheet.rs b/crates/engine/src/cmd/sheet.rs index 0d0d55a16..630a028d9 100644 --- a/crates/engine/src/cmd/sheet.rs +++ b/crates/engine/src/cmd/sheet.rs @@ -4,6 +4,8 @@ use serde_json::{Value, json}; use solidcraft_doc::expr::Kind; 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}; @@ -110,7 +112,7 @@ fn flange_edges(s: &Session, p: &Value, cmd: &str) -> Result> { return Err(bad(cmd, format!("edges[{i}]: unknown key `{k}` (an edge takes point, angle and height)"))); } let point = o.get("point").and_then(vec3).ok_or_else(|| bad(cmd, format!("edges[{i}]: `point` must be [x, y, z]")))?; - let own = |k: &str, kind: Kind| -> Result> { + let own = |k: &str, kind: Kind| -> Result> { if o.get(k).is_none_or(Value::is_null) { return Ok(None); } @@ -118,7 +120,7 @@ fn flange_edges(s: &Session, p: &Value, cmd: &str) -> Result> { check_expr(s, &e, kind, cmd, &format!("edges[{i}].{k}"))?; Ok(Some(e)) }; - edges.push(FlangeEdge { point, angle: own("angle", Kind::Angle)?, height: own("height", Kind::Length)? }); + edges.push(FlangeEdge { point: Position(point), angle: own("angle", Kind::Angle)?, height: own("height", Kind::Length)? }); } Ok(edges) } @@ -162,7 +164,11 @@ fn flange(s: &mut Session, p: &Value) -> Result { "base" => { let sketch = feature_sketch(s, p, cmd)?; let rule = rule_param(s, p, cmd)?; - add_feature(s, p, FeatureKind::SheetBase { sketch, profiles: profiles(p, cmd)?, rule, flip: bool_(p, "flip").unwrap_or(false) }) + add_feature( + s, + p, + FeatureKind::SheetBase { sketch: SketchId(sketch), profiles: profiles(p, cmd)?, rule, flip: bool_(p, "flip").unwrap_or(false) }, + ) } "contour" => { let sketch = sketch_id(s, p.get("sketch"), cmd, "sketch")?; @@ -177,7 +183,7 @@ fn flange(s: &mut Session, p: &Value) -> Result { s, p, FeatureKind::SheetContour { - sketch, + sketch: SketchId(sketch), curves, distance, rule, @@ -225,7 +231,7 @@ fn flange(s: &mut Session, p: &Value) -> Result { radius, position, flip: bool_(p, "flip").unwrap_or(false), - body, + body: body.map(BodyName), corner_relief_shape, corner_relief, }, @@ -249,7 +255,7 @@ fn perforate(s: &mut Session, p: &Value) -> Result { if pattern.as_deref().is_some_and(|t| t != "staggered" && t != "square") { return Err(bad(cmd, "`pattern` is \"staggered\" (60°, default) or \"square\"")); } - add_feature(s, p, FeatureKind::SheetPerforate { diameter, pitch, margin, pattern, body: str_(p, "body").map(str::to_string) }) + add_feature(s, p, FeatureKind::SheetPerforate { diameter, pitch, margin, pattern, body: str_(p, "body").map(BodyName::from) }) } fn hem(s: &mut Session, p: &Value) -> Result { @@ -264,7 +270,13 @@ fn hem(s: &mut Session, p: &Value) -> Result { add_feature( s, p, - FeatureKind::SheetHem { edges, length, gap, flip: bool_(p, "flip").unwrap_or(false), body: str_(p, "body").map(str::to_string) }, + FeatureKind::SheetHem { + edges: edges.into_iter().map(Position).collect(), + length, + gap, + flip: bool_(p, "flip").unwrap_or(false), + body: str_(p, "body").map(BodyName::from), + }, ) } @@ -311,7 +323,18 @@ fn fold(s: &mut Session, p: &Value) -> Result { let r = add_feature( s, p, - FeatureKind::SheetFold { sketch, curve, a, b, angle, radius, position, flip: bool_(p, "flip").unwrap_or(false), fixed, body }, + FeatureKind::SheetFold { + sketch: sketch.map(SketchId), + curve, + a: Position(a), + b: Position(b), + angle, + radius, + position, + flip: bool_(p, "flip").unwrap_or(false), + fixed: fixed.map(Position), + body: body.map(BodyName), + }, )?; // A recompute keeps a stored fold whose fixed point no longer touches the sheet (with a // warning); a new fold refuses one, since it picks no side (#263). @@ -330,11 +353,11 @@ fn fold(s: &mut Session, p: &Value) -> Result { } fn unfold(s: &mut Session, p: &Value) -> Result { - add_feature(s, p, FeatureKind::SheetUnfold { body: str_(p, "body").map(str::to_string), refold: false }) + add_feature(s, p, FeatureKind::SheetUnfold { body: str_(p, "body").map(BodyName::from), refold: false }) } fn refold(s: &mut Session, p: &Value) -> Result { - add_feature(s, p, FeatureKind::SheetUnfold { body: str_(p, "body").map(str::to_string), refold: true }) + add_feature(s, p, FeatureKind::SheetUnfold { body: str_(p, "body").map(BodyName::from), refold: true }) } fn convert(s: &mut Session, p: &Value) -> Result { @@ -355,7 +378,11 @@ fn convert(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, format!("`{key}` is not a sheet.convert parameter: the sheet metal rule sets it. Pass a rule's name as `rule`"))); } let rule = rule_param(s, p, cmd)?; - add_feature(s, p, FeatureKind::SheetConvert { body, face, rule, bends }) + add_feature( + s, + p, + FeatureKind::SheetConvert { body: BodyName(body), face: FacePick(face), rule, bends: bends.into_iter().map(Position).collect() }, + ) } fn rules(s: &mut Session, p: &Value) -> Result { @@ -386,7 +413,7 @@ fn rules(s: &mut Session, p: &Value) -> Result { ("gap", &mut rule.gap), ] { if let Some(e) = expr(p, k) { - *slot = e; + *slot = e.into(); } } if let Some(shape) = p.get("corner_relief_shape").filter(|v| !v.is_null()) { diff --git a/crates/engine/src/cmd/sketch_create.rs b/crates/engine/src/cmd/sketch_create.rs index 9cf50fbbf..f82396cbf 100644 --- a/crates/engine/src/cmd/sketch_create.rs +++ b/crates/engine/src/cmd/sketch_create.rs @@ -746,7 +746,7 @@ fn tangent_circle(s: &mut Session, p: &Value, cmd: &str, n: usize, radius: Optio fn circle_tan_tan(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.circle.two_tangent"; let r = match (crate::params::expr(p, "radius"), num(p, "diameter")) { - (Some(r), _) => r, + (Some(r), _) => r.into_string(), (None, Some(d)) => format!("{}", d / 2.0), _ => return Err(bad(cmd, "needs `radius` or `diameter`")), }; diff --git a/crates/engine/src/cmd/sketch_modify.rs b/crates/engine/src/cmd/sketch_modify.rs index 6c6249ee2..c8f58afba 100644 --- a/crates/engine/src/cmd/sketch_modify.rs +++ b/crates/engine/src/cmd/sketch_modify.rs @@ -1193,7 +1193,7 @@ fn offset_length(s: &Session, p: &Value, key: &str, positive: bool) -> Result<(f let cmd = "sketch.offset"; let expression = match num(p, key) { Some(v) => format!("{v} mm"), - None => expr(p, key).ok_or_else(|| bad(cmd, format!("`{key}` must be a length expression")))?, + None => expr(p, key).ok_or_else(|| bad(cmd, format!("`{key}` must be a length expression")))?.into_string(), }; let expression = s.doc.with_design_unit(&expression, solidcraft_doc::expr::Kind::Length); let value = s.doc.eval(&expression, solidcraft_doc::expr::Kind::Length)?; diff --git a/crates/engine/src/cmd/surface.rs b/crates/engine/src/cmd/surface.rs index a2e9deac0..93d7a19af 100644 --- a/crates/engine/src/cmd/surface.rs +++ b/crates/engine/src/cmd/surface.rs @@ -5,6 +5,8 @@ use serde_json::Value; use solidcraft_doc::{ BlendSide, EdgeContinuity, ExtendMode, ExtendTo, FaceAt, FeatureKind, PatchContinuity, PlaneRef, ProfileSel, RuledCorners, RuledMode, expr::Kind, }; +use solidcraft_doc::{BodyName, SketchId}; +use solidcraft_doc::{Dir, FacePick, Position}; use solidcraft_kernel::Continuity; use super::CommandSpec; @@ -87,14 +89,26 @@ fn patch(s: &mut Session, p: &Value) -> Result { let cmd = "surface.patch"; let crown = crown_param(p, cmd)?; let continuity = patch_continuity(p, cmd)?; - let points = patch_points(p, cmd)?; + let points: Vec = patch_points(p, cmd)?.into_iter().map(Position).collect(); let edges: Vec = p.get("edges").and_then(Value::as_array).map(|a| a.iter().filter_map(vec3).collect()).unwrap_or_default(); let mut v = if !edges.is_empty() { if edges.len() > 10_000 { return Err(bad(cmd, "too many edges")); } let body = str_(p, "body").map(str::to_string); - add_feature(s, p, FeatureKind::Patch { sketch: None, profiles: ProfileSel::All, body, edges, crown, continuity: continuity.clone(), points })? + add_feature( + s, + p, + FeatureKind::Patch { + sketch: None, + profiles: ProfileSel::All, + body: body.map(BodyName), + edges: edges.into_iter().map(Position).collect(), + crown, + continuity: continuity.clone(), + points, + }, + )? } else { if !continuity.is_g0() || !points.is_empty() { return Err(bad(cmd, "`continuity` and `points` are for a patch on a loop of edges")); @@ -102,7 +116,7 @@ fn patch(s: &mut Session, p: &Value) -> Result { let sketch = feature_sketch(s, p, cmd)?; let profiles = profiles(p, cmd)?; let kind = FeatureKind::Patch { - sketch: Some(sketch), + sketch: Some(SketchId(sketch)), profiles, body: None, edges: Vec::new(), @@ -138,7 +152,7 @@ fn patch_continuity(p: &Value, cmd: &str) -> Result { list.iter() .map(|e| { let edge = e.get("edge").and_then(vec3).ok_or_else(|| bad(cmd, "a `continuity` entry's `edge` must be a point [x,y,z]"))?; - Ok(EdgeContinuity { edge, g: patch_order(e.get("g"), cmd)? }) + Ok(EdgeContinuity { edge: Position(edge), g: patch_order(e.get("g"), cmd)? }) }) .collect() }; @@ -192,7 +206,7 @@ fn blend_side(p: &Value, cmd: &str, key: &str) -> Result { if edges.is_empty() || edges.len() > 10_000 { return Err(bad(cmd, format!("`{key}.edges` must list 1 to 10000 points on the edges of a chain"))); } - Ok(BlendSide { body: body.to_string(), edges }) + Ok(BlendSide { body: BodyName(body.to_string()), edges: edges.into_iter().map(Position).collect() }) } /// `surface.blend`: a blend surface bridging two picked edge chains of two bodies. @@ -229,7 +243,7 @@ fn blend(s: &mut Session, p: &Value) -> Result { 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([point(list.first())?, point(list.get(1))?]) + Some([Position(point(list.first())?), Position(point(list.get(1))?)]) } }; let stitch = bool_(p, "stitch").unwrap_or(false); @@ -244,7 +258,7 @@ fn surface_extrude(s: &mut Session, p: &Value) -> Result { if extent.through_all || extent.taper.is_some() || extent.to.is_some() || extent.from.is_some() { return Err(bad(cmd, "not supported yet: through all, to or from an object, or a taper")); } - add_feature(s, p, FeatureKind::SurfaceExtrude { sketch, profiles, curves, extent }) + add_feature(s, p, FeatureKind::SurfaceExtrude { sketch: SketchId(sketch), profiles, curves, extent }) } /// A body by name, and points on some of its faces (none: all of them). @@ -262,12 +276,12 @@ fn body_faces(s: &Session, p: &Value, cmd: &str) -> Result<(String, Vec Result { let (body, faces) = body_faces(s, p, "surface.unstitch")?; - add_feature(s, p, FeatureKind::Unstitch { body, faces }) + add_feature(s, p, FeatureKind::Unstitch { body: BodyName(body), faces: faces.into_iter().map(Position).collect() }) } fn reverse_normal(s: &mut Session, p: &Value) -> Result { let (body, faces) = body_faces(s, p, "surface.reverse_normal")?; - add_feature(s, p, FeatureKind::ReverseNormal { body, faces }) + add_feature(s, p, FeatureKind::ReverseNormal { body: BodyName(body), faces: faces.into_iter().map(Position).collect() }) } fn untrim(s: &mut Session, p: &Value) -> Result { @@ -294,7 +308,12 @@ fn untrim(s: &mut Session, p: &Value) -> Result { if !outer && holes.as_ref().is_some_and(Vec::is_empty) { return Err(bad(cmd, "nothing to untrim: pick holes to remove or restore the outer boundary")); } - let kind = FeatureKind::SurfaceUntrim { face: FaceAt { body, point }, holes, outer, in_place: bool_(p, "in_place").unwrap_or(false) }; + let kind = FeatureKind::SurfaceUntrim { + face: FaceAt { body: BodyName(body), point: Position(point) }, + holes: holes.map(|h| h.into_iter().map(Position).collect()), + outer, + in_place: bool_(p, "in_place").unwrap_or(false), + }; add_feature(s, p, kind) } @@ -321,7 +340,7 @@ fn surface_revolve(s: &mut Session, p: &Value) -> Result { check_expr(s, a, Kind::Angle, cmd, "angle2")?; } let symmetric = bool_(p, "symmetric").unwrap_or(false) || str_(p, "direction").is_some_and(|d| d.eq_ignore_ascii_case("symmetric")); - add_feature(s, p, FeatureKind::SurfaceRevolve { sketch, profiles, curves, axis, angle, angle2, symmetric }) + add_feature(s, p, FeatureKind::SurfaceRevolve { sketch: SketchId(sketch), profiles, curves, axis, angle, angle2, symmetric }) } fn surface_sweep(s: &mut Session, p: &Value) -> Result { @@ -334,7 +353,11 @@ fn surface_sweep(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, "`path` must list 1…1000 curve ids")); } let (orientation, twist, scale) = super::features::sweep_options(s, p, cmd)?; - add_feature(s, p, FeatureKind::SurfaceSweep { sketch, profiles, curves, path_sketch, path, orientation, twist, scale }) + add_feature( + s, + p, + FeatureKind::SurfaceSweep { sketch: SketchId(sketch), profiles, curves, path_sketch: SketchId(path_sketch), path, orientation, twist, scale }, + ) } fn surface_loft(s: &mut Session, p: &Value) -> Result { @@ -351,7 +374,7 @@ fn surface_loft(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, "at most 1000 curves a section")); } let profiles = if sec.get("profiles").is_some() { Some(profiles(sec, cmd)?) } else { None }; - sections.push(solidcraft_doc::SheetSection { sketch, profiles, curves }); + sections.push(solidcraft_doc::SheetSection { sketch: SketchId(sketch), profiles, curves }); } add_feature(s, p, FeatureKind::SurfaceLoft { sections }) } @@ -369,8 +392,8 @@ fn offset(s: &mut Session, p: &Value) -> Result { check_expr(s, t, Kind::Length, cmd, "tolerance")?; } let kind = FeatureKind::SurfaceOffset { - faces, - body: str_(p, "body").map(str::to_string), + faces: faces.into_iter().map(FacePick).collect(), + body: str_(p, "body").map(BodyName::from), distance, chain: bool_(p, "chain").unwrap_or(false), tolerance, @@ -422,7 +445,17 @@ fn ruled(s: &mut Session, p: &Value) -> Result { Some(v) => Some(vec3(v).ok_or_else(|| bad(cmd, "`face` must be [x, y, z] on a face"))?), None => None, }; - let kind = FeatureKind::SurfaceRuled { body, edges, distance, mode, angle, direction, flip: bool_(p, "flip").unwrap_or(false), corners, face }; + let kind = FeatureKind::SurfaceRuled { + body: BodyName(body), + edges: edges.into_iter().map(Position).collect(), + distance, + mode, + angle, + direction: direction.map(Dir), + flip: bool_(p, "flip").unwrap_or(false), + corners, + face: face.map(FacePick), + }; add_feature(s, p, kind) } @@ -443,7 +476,7 @@ fn stitch(s: &mut Session, p: &Value) -> Result { let bodies = bodies_param(s, p, cmd)?; let tolerance = expr(p, "tolerance").unwrap_or_else(|| "0".into()); check_expr(s, &tolerance, Kind::Length, cmd, "tolerance")?; - add_feature(s, p, FeatureKind::Stitch { bodies, tolerance }) + add_feature(s, p, FeatureKind::Stitch { bodies: bodies.into_iter().map(BodyName).collect(), tolerance }) } fn thicken(s: &mut Session, p: &Value) -> Result { @@ -452,11 +485,11 @@ fn thicken(s: &mut Session, p: &Value) -> Result { let thickness = expr(p, "thickness").ok_or_else(|| bad(cmd, "`thickness` is required"))?; check_expr(s, &thickness, Kind::Length, cmd, "thickness")?; let kind = FeatureKind::Thicken { - bodies, + bodies: bodies.into_iter().map(BodyName).collect(), thickness, symmetric: bool_(p, "symmetric").unwrap_or(false), operation: operation(p, cmd)?, - targets: string_list(p, "targets"), + targets: string_list(p, "targets").into_iter().map(BodyName).collect(), }; add_feature(s, p, kind) } @@ -486,7 +519,7 @@ fn extend(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, format!("no body `{tb}`"))); } let point = t.get("point").and_then(vec3).ok_or_else(|| bad(cmd, "`up_to.point` must be [x, y, z] on the target face"))?; - Some(ExtendTo::Face(FaceAt { body: tb, point })) + Some(ExtendTo::Face(FaceAt { body: BodyName(tb), point: Position(point) })) } Some(v) => Some(ExtendTo::Plane(plane_param(s, Some(v), cmd)?)), }; @@ -500,7 +533,11 @@ fn extend(s: &mut Session, p: &Value) -> Result { }; check_expr(s, &distance, Kind::Length, cmd, "distance")?; let neighbours = bool_(p, "neighbours").unwrap_or(true); - add_feature(s, p, FeatureKind::SurfaceExtend { body, edges, distance, mode, up_to, neighbours }) + add_feature( + s, + p, + FeatureKind::SurfaceExtend { body: BodyName(body), edges: edges.into_iter().map(Position).collect(), distance, mode, up_to, neighbours }, + ) } fn trim(s: &mut Session, p: &Value) -> Result { @@ -514,11 +551,11 @@ fn trim(s: &mut Session, p: &Value) -> Result { Some(t) => { 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: tb, point })) + (PlaneRef::Origin { name: "XY".into() }, Some(FaceAt { body: BodyName(tb), point: Position(point) })) } None => (plane_param(s, p.get("plane"), cmd)?, None), }; - add_feature(s, p, FeatureKind::SurfaceTrim { body, plane, tool, keep }) + add_feature(s, p, FeatureKind::SurfaceTrim { body: BodyName(body), plane, tool, keep: Position(keep) }) } #[cfg(test)] diff --git a/crates/engine/src/derived_units_tests.rs b/crates/engine/src/derived_units_tests.rs index 9da2efaf7..bfce30b70 100644 --- a/crates/engine/src/derived_units_tests.rs +++ b/crates/engine/src/derived_units_tests.rs @@ -224,7 +224,7 @@ fn bare_numbers_beside_a_unitless_expression_stay_bare() { assert_eq!(inputs(&s, 0)[2], "(16) / (2 * 4)", "the revolutions"); assert!(s.model.result(s.doc.features[0].id).is_some_and(|r| r.error.is_none())); run(&mut s, "solid.box", json!({"length": 20, "width": 10, "height": 10, "center": ["2 * 5", 0, 0], "body_name": "B"})); - assert_eq!(s.doc.features[1].kind.point_expr().map(|p| p[0].clone()), Some("(2 * 5) - (20) / 2".to_string())); + assert_eq!(s.doc.features[1].kind.point_expr().map(|p| p[0].to_string()), Some("(2 * 5) - (20) / 2".to_string())); let b = shape(&mut s, "B"); assert!(b.bbox[0].abs() < 1e-6 && (b.bbox[3] - 20.0).abs() < 1e-6, "{b:?}"); } diff --git a/crates/engine/src/frames.rs b/crates/engine/src/frames.rs index 87ceecc38..10fed4943 100644 --- a/crates/engine/src/frames.rs +++ b/crates/engine/src/frames.rs @@ -200,8 +200,8 @@ impl Mapper<'_> { fn make_expr(&mut self, m: &Mat, v: &Value) -> Option { let a = v.as_array().filter(|a| a.len() == 3)?; let c = |i: usize| match a.get(i)? { - Value::Number(n) => n.as_f64().filter(|x| x.is_finite()).map(|x| format!("{x}")), - Value::String(e) => Some(e.clone()), + Value::Number(n) => n.as_f64().filter(|x| x.is_finite()).map(|x| solidcraft_doc::Expr::new(format!("{x}"))), + Value::String(e) => Some(solidcraft_doc::Expr::new(e.as_str())), _ => None, }; let mut p = [c(0)?, c(1)?, c(2)?]; @@ -349,9 +349,9 @@ pub fn to_local(s: &Session, id: &str, params: &Value) -> Option { && let solidcraft_doc::FeatureKind::Revolve { axis: solidcraft_doc::AxisRef::Line { origin, dir }, .. } = &feature.kind { let frame = context.active_component_frame(); - let displayed = serde_json::json!({"origin":pt(apply_point(&frame,*origin)),"dir":pt(apply_vector(&frame,*dir))}); + let displayed = serde_json::json!({"origin":pt(apply_point(&frame,origin.0)),"dir":pt(apply_vector(&frame,dir.0))}); if params.get("params").and_then(|p| p.get("axis")) == Some(&displayed) { - inner["axis"] = serde_json::json!({"origin":pt(*origin),"dir":pt(*dir)}); + inner["axis"] = serde_json::json!({"origin":pt(origin.0),"dir":pt(dir.0)}); } } let points = match (&feature.kind, cmd) { @@ -361,9 +361,9 @@ pub fn to_local(s: &Session, id: &str, params: &Value) -> Option { }; for (key, point) in points { if let Some(point) = point { - let displayed = pt(apply_point(&context.active_component_frame(), point)); + let displayed = pt(apply_point(&context.active_component_frame(), point.0)); if params.get("params").and_then(|p| p.get(key)) == Some(&displayed) { - inner[key] = pt(point); + inner[key] = pt(point.0); } } } diff --git a/crates/engine/src/large_assembly_tests.rs b/crates/engine/src/large_assembly_tests.rs index db29a6ac8..3fc50e339 100644 --- a/crates/engine/src/large_assembly_tests.rs +++ b/crates/engine/src/large_assembly_tests.rs @@ -7,6 +7,7 @@ //! `SOLIDCRAFT_BENCH_PARTS=400 cargo test --release -p solidcraft-engine bench_generated_assembly -- --ignored --nocapture` use serde_json::json; +use solidcraft_doc::BodyName; use solidcraft_doc::{Document, FeatureKind, Operation, mat_inverse, point_expr, rigid}; use solidcraft_geom::Vec3; @@ -24,7 +25,7 @@ fn generated_assembly(parts: usize) -> Document { (id, m) }) .collect(); - let mm = |v: f64| format!("{v} mm"); + let mm = |v: f64| solidcraft_doc::Expr::new(format!("{v} mm")); let mut made = Vec::new(); for i in 0..parts { let o = Vec3::new(30.0 * (i % 20) as f64, 30.0 * (i / 20) as f64, 0.0); @@ -33,7 +34,7 @@ fn generated_assembly(parts: usize) -> Document { for (k, x) in [2.0, 9.0, 16.0].into_iter().enumerate() { let pin = FeatureKind::Cylinder { base: point_expr(o + Vec3::new(x, 20.0, 0.0)), - axis: Vec3::Z, + axis: solidcraft_doc::Dir(Vec3::Z), radius: mm(1.5), height: mm(4.0 + k as f64), operation: Operation::NewBody, @@ -47,7 +48,7 @@ fn generated_assembly(parts: usize) -> Document { for (part, feature) in made { let (to, m) = comps[part / 4 % groups]; for b in state.bodies.iter().filter(|b| b.feature == feature) { - let kind = FeatureKind::BodyTransfer { bodies: vec![b.name.clone()], from: 0, to, transform: mat_inverse(&m).unwrap() }; + let kind = FeatureKind::BodyTransfer { bodies: vec![BodyName::from(&b.name)], from: 0, to, transform: mat_inverse(&m).unwrap() }; doc.add_feature(kind, None).unwrap(); } } diff --git a/crates/engine/src/occurrences.rs b/crates/engine/src/occurrences.rs index 2592e3754..daf3ea8d2 100644 --- a/crates/engine/src/occurrences.rs +++ b/crates/engine/src/occurrences.rs @@ -258,7 +258,7 @@ impl Session { let mut removed = std::collections::BTreeSet::new(); for feature in self.doc.features.iter().skip(marker).filter(|f| !f.suppressed) { if let FeatureKind::Remove { bodies } = &feature.kind { - removed.extend(bodies.iter().filter(|b| !kept.contains(b.as_str()) && shown.body(b).is_some()).cloned()); + removed.extend(bodies.iter().filter(|b| !kept.contains(b.0.as_str()) && shown.body(&b.0).is_some()).map(|b| b.0.clone())); } } if removed.is_empty() || self.doc.occurrences.is_empty() { diff --git a/crates/engine/src/params.rs b/crates/engine/src/params.rs index 4a7ff0698..b05f70a0e 100644 --- a/crates/engine/src/params.rs +++ b/crates/engine/src/params.rs @@ -1,6 +1,7 @@ //! Helpers to read hostile JSON parameters. use serde_json::Value; +use solidcraft_doc::Expr; use solidcraft_geom::{Vec2, Vec3}; use crate::{EngineError, Result}; @@ -58,15 +59,15 @@ pub fn vec2_list(cmd: &str, p: &Value, k: &str, max: usize) -> Result> } /// An expression parameter: a number (mm or degrees by context) or an expression string. -pub fn expr(p: &Value, k: &str) -> Option { +pub fn expr(p: &Value, k: &str) -> Option { match p.get(k)? { - Value::Number(n) => n.as_f64().and_then(finite).map(|v| format!("{v}")), - Value::String(s) if !s.trim().is_empty() && s.len() <= 4096 => Some(s.trim().to_string()), + Value::Number(n) => n.as_f64().and_then(finite).map(|v| Expr::new(format!("{v}"))), + Value::String(s) if !s.trim().is_empty() && s.len() <= 4096 => Some(Expr::new(s.trim())), _ => None, } } -pub fn req_expr(cmd: &str, p: &Value, k: &str) -> Result { +pub fn req_expr(cmd: &str, p: &Value, k: &str) -> Result { expr(p, k).ok_or_else(|| bad(cmd, format!("`{k}` must be a number or an expression"))) } diff --git a/crates/engine/src/pattern_suppress_tests.rs b/crates/engine/src/pattern_suppress_tests.rs index 0627f772d..89182fc82 100644 --- a/crates/engine/src/pattern_suppress_tests.rs +++ b/crates/engine/src/pattern_suppress_tests.rs @@ -121,7 +121,7 @@ fn enclosure_arc_extinction_keeps_a_real_sharp_inner_lip_after_resize_and_reopen let FeatureKind::Extrude { sketch, profiles, .. } = &feature.kind else { panic!("lip extrusion"); }; - let solved = state.sketch(*sketch).unwrap(); + let solved = state.sketch(sketch.0).unwrap(); assert!((solved.plane.origin.z - 30.).abs() < 1e-8); let inner = &solved.sketch.offsets[1]; assert_eq!(inner.outputs.len(), 4); diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index be8ae3be7..334f01f24 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -859,7 +859,7 @@ mod tests { .unwrap(); doc.add_feature( FeatureKind::Fillet { - edges: vec![Vec3::new(0.0, 0.0, 5.0)], + edges: vec![solidcraft_doc::Position(Vec3::new(0.0, 0.0, 5.0))], radius: "4".into(), body: None, style: Default::default(), @@ -871,7 +871,7 @@ mod tests { doc.add_feature( FeatureKind::Cylinder { base: point_expr(Vec3::new(80.0, 0.0, 0.0)), - axis: Vec3::Z, + axis: solidcraft_doc::Dir(Vec3::Z), radius: "6".into(), height: "15".into(), operation: Operation::NewBody, @@ -943,7 +943,7 @@ mod tests { .unwrap(); doc.add_feature( FeatureKind::Fillet { - edges: vec![Vec3::new(0.1, -0.3, 5.0 + 1.0 / 3.0)], + edges: vec![solidcraft_doc::Position(Vec3::new(0.1, -0.3, 5.0 + 1.0 / 3.0))], radius: "4".into(), body: None, style: Default::default(), diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 280c19731..3f264c7e8 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -637,7 +637,7 @@ impl Dialog { let preselection: &[Sel] = if matches!(d.kind, Kind::Text(_)) { &[] } else { &s.selection }; for sel in preselection { let as_body = match sel { - Sel::Face { body, .. } | Sel::Edge { body, .. } | Sel::Vertex { body, .. } => Some(Sel::Body { name: body.clone() }), + Sel::Face { body, .. } | Sel::Edge { body, .. } | Sel::Vertex { body, .. } => Some(Sel::Body { name: body.to_string() }), _ => None, }; if let Some(b) = as_body @@ -3343,7 +3343,7 @@ pub fn apply_commands(app: &SolveApp, d: &Dialog) -> Result }; if let Some(sketch) = original_all && !d.profile_selection_changed - && let Some(ss) = app.session.world_state().sketch(sketch) + && let Some(ss) = app.session.world_state().sketch(sketch.0) { let mut selected: Vec = sels(d, 0) .iter() @@ -3483,7 +3483,7 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result, S _ => None, }); let has_all = |id: u64| curves.iter().all(|c| st.sketch(id).is_some_and(|ss| ss.sketch.curve_index(c).is_some())); - let sketch = match sketch.or(edited) { + let sketch = match sketch.or(edited.map(u64::from)) { Some(id) if has_all(id) => id, _ => curves_sketch(app, &curves, None).ok_or("the curves must be in one sketch")?, }; @@ -4248,14 +4248,15 @@ fn emboss_face_sel(s: &Session, component: u64, face: &solidcraft_engine::doc::E let owner = s.doc.model_body_component(body); let world_name = s.doc.world_body_name(&source, &face.body, owner, &face.path); let author = solidcraft_engine::doc::EmbossFace::component_frame(&s.doc, component, &face.author_path).ok()?; - let point = solidcraft_engine::doc::apply_point(&author, face.at); + let point = solidcraft_engine::doc::apply_point(&author, face.at.0); s.world_state().body(&world_name)?; Some(Sel::Face { body: world_name, index, point }) } pub(crate) fn plane_sel(s: &Session, pl: &PlaneRef) -> Option { match pl { - PlaneRef::Origin { name } | PlaneRef::Construction { name } => Some(Sel::Plane { name: name.clone() }), + PlaneRef::Origin { name } => Some(Sel::Plane { name: name.clone() }), + PlaneRef::Construction { name } => Some(Sel::Plane { name: name.to_string() }), PlaneRef::Custom { plane } | PlaneRef::Face { plane, .. } => face_sel(s, plane.origin), _ => None, } @@ -4299,7 +4300,7 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option { let mut d = start("solid.extrude")?; d.kind = Kind::Extrude { - distance: extent.distance.clone(), + distance: extent.distance.to_string(), direction: match (extent.direction, &extent.distance2) { (_, Some(_)) => TWO_SIDES, (Direction::Positive, None) => 0, @@ -4309,16 +4310,16 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option) -> Option) -> Option) -> Option Some(json!({ - "origin": pt(solidcraft_engine::doc::apply_point(&frame, *origin)), - "dir": pt(solidcraft_engine::doc::apply_vector(&frame, *dir)) + "origin": pt(solidcraft_engine::doc::apply_point(&frame, origin.0)), + "dir": pt(solidcraft_engine::doc::apply_vector(&frame, dir.0)) })), _ => None, }; - d.kind = Kind::Revolve { angle: angle.clone(), operation: op_index(operation), axis: stored_axis }; + d.kind = Kind::Revolve { angle: angle.to_string(), operation: op_index(operation), axis: stored_axis }; d.extra.insert("convention".into(), json!(convention)); if let Some(a2) = angle2 { d.extra.insert("angle2".into(), json!(a2)); @@ -4369,12 +4370,12 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option Some(Sel::Axis { name: axis.to_ascii_uppercase() }), @@ -4400,10 +4401,10 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option) -> Option {} } // The start was the first edge's last point: ends swapped. - let first_end = edges.first().and_then(|p| edge_sel(s, *p)).and_then(|x| match x { + let first_end = edges.first().and_then(|p| edge_sel(s, p.0)).and_then(|x| match x { Sel::Edge { body, index, .. } => { s.world_state().body(&body).and_then(|b| b.mesh().edges.get(index).and_then(|e| e.last().copied())) } _ => None, }); - let swapped = first_end.is_some_and(|e| e.dist(*start) < 1e-6); + let swapped = first_end.is_some_and(|e| e.dist(start.0) < 1e-6); d.extra.insert("swap_ends".into(), json!(swapped)); } } } if let Some(inp) = d.inputs.first_mut() { - inp.items = edges.iter().filter_map(|p| edge_sel(s, *p)).collect(); + inp.items = edges.iter().filter_map(|p| edge_sel(s, p.0)).collect(); } d } FeatureKind::Shell { faces, thickness, direction, tangent_chain, .. } => { let mut d = start("solid.shell")?; - d.kind = Kind::Shell { thickness: thickness.clone() }; + d.kind = Kind::Shell { thickness: thickness.to_string() }; d.extra.insert("tangent_chain".into(), json!(tangent_chain)); if !direction.is_empty() && direction != "inside" { d.extra.insert("direction".into(), json!(direction)); } if let Some(inp) = d.inputs.first_mut() { - inp.items = faces.iter().filter_map(|p| face_sel(s, *p)).collect(); + inp.items = faces.iter().filter_map(|p| face_sel(s, p.0)).collect(); } d } FeatureKind::Draft { faces, angle, neutral, pull, .. } => { let mut d = start("solid.draft")?; - d.kind = Kind::Draft { angle: angle.clone() }; + d.kind = Kind::Draft { angle: angle.to_string() }; if let Some(inp) = d.inputs.get_mut(0) { - inp.items = faces.iter().filter_map(|p| face_sel(s, *p)).collect(); + inp.items = faces.iter().filter_map(|p| face_sel(s, p.0)).collect(); } if let Some(inp) = d.inputs.get_mut(1) { inp.items = plane_sel(s, neutral).into_iter().collect(); } - d.extra.insert("pull".into(), pt3(*pull)); + d.extra.insert("pull".into(), pt3(pull.0)); d } FeatureKind::Hole { position, direction, diameter, depth, hole, points, thread, to } => { let mut d = start("solid.hole")?; let mut k = hole_defaults(); if let Kind::Hole { diameter: dia, depth: dep, kind, cb_diameter, cb_depth, cs_diameter, cs_angle, opts } = &mut k { - *dia = diameter.clone(); + *dia = diameter.to_string(); opts.all = depth.is_none(); opts.angled = matches!(hole, HoleKind::Drilled { .. }); opts.multiple = points.is_some(); @@ -4499,21 +4500,21 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option { *kind = 1; - *cb_diameter = a.clone(); - *cb_depth = b.clone(); + *cb_diameter = a.to_string(); + *cb_depth = b.to_string(); } HoleKind::Countersink { cs_diameter: a, cs_angle: b } => { *kind = 2; - *cs_diameter = a.clone(); - *cs_angle = b.clone(); + *cs_diameter = a.to_string(); + *cs_angle = b.to_string(); } HoleKind::Drilled { tip_angle } => { - opts.tip_angle = tip_angle.clone(); + opts.tip_angle = tip_angle.to_string(); } HoleKind::Simple => {} } @@ -4531,16 +4532,16 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option { if let Some(inp) = d.inputs.first_mut() { - inp.items = vec![face_sel(s, *position).unwrap_or(Sel::Face { body: String::new(), index: 0, point: *position })]; + inp.items = vec![face_sel(s, position.0).unwrap_or(Sel::Face { body: String::new(), index: 0, point: position.0 })]; } - d.extra.insert("direction".into(), pt3(*direction)); + d.extra.insert("direction".into(), pt3(direction.0)); } } if to.is_some() { if let Kind::Hole { opts, .. } = &mut d.kind { opts.all = false; } - with_to_object(&mut d, s, *to); + with_to_object(&mut d, s, to.map(Vec3::from)); } // A hole at every point of a sketch. if points.as_ref().is_some_and(|sp| sp.ids.is_empty()) { @@ -4568,7 +4569,7 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option { @@ -4593,10 +4594,10 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option = - cells.iter().filter_map(|c| found.iter().min_by(|a, b| a.0.dist(*c).total_cmp(&b.0.dist(*c))).map(|x| x.1.clone())).collect(); - let items: Vec = tools.iter().map(|n| Sel::Body { name: n.clone() }).collect(); + cells.iter().filter_map(|c| found.iter().min_by(|a, b| a.0.dist(c.0).total_cmp(&b.0.dist(c.0))).map(|x| x.1.clone())).collect(); + let items: Vec = tools.iter().map(|n| Sel::Body { name: n.to_string() }).collect(); d.kind = Kind::BoundaryFill { operation: op_index(operation), cells: found.into_iter().map(|(p, l)| (p, l.clone(), filled.contains(&l))).collect(), @@ -4614,10 +4615,10 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option) -> Option) -> Option = if copied.is_empty() { st.bodies.iter().filter(|b| ids.contains(&b.feature)).map(|b| Sel::Body { name: b.name.clone() }).collect() } else { - copied.iter().map(|name| Sel::Body { name: name.clone() }).collect() + copied.iter().map(|name| Sel::Body { name: name.to_string() }).collect() }; let mut d = match pattern { PatternKind::Rectangular { dir1, count1, spacing1, dir2, count2, spacing2 } => { let mut d = start("solid.pattern.rectangular")?; d.kind = Kind::PatternRect { - count: count1.clone(), - spacing: spacing1.clone(), - count2: count2.clone().unwrap_or_else(|| "1".into()), - spacing2: spacing2.clone().unwrap_or_else(|| "20 mm".into()), + count: count1.to_string(), + spacing: spacing1.to_string(), + count2: count2.as_deref().map(str::to_string).unwrap_or_else(|| "1".into()), + spacing2: spacing2.as_deref().map(str::to_string).unwrap_or_else(|| "20 mm".into()), }; // Directions along the origin axes show as those axes; others are kept as is. for (i, (key, dir)) in [("dir1", Some(*dir1)), ("dir2", *dir2)].into_iter().enumerate() { let Some(dir) = dir else { continue }; - match world_axis(dir) { + match world_axis(dir.0) { Some(name) => { if let Some(inp) = d.inputs.get_mut(i + 1) { inp.items = vec![Sel::Axis { name }]; } } None => { - d.extra.insert(key.into(), pt3(dir)); + d.extra.insert(key.into(), pt3(dir.0)); } } } @@ -4676,15 +4677,15 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option { let mut d = start("solid.pattern.circular")?; - d.kind = Kind::PatternCirc { count: count.clone(), angle: angle.clone() }; - match world_axis(*axis).filter(|_| origin.len() < 1e-9) { + d.kind = Kind::PatternCirc { count: count.to_string(), angle: angle.to_string() }; + match world_axis(axis.0).filter(|_| origin.len() < 1e-9) { Some(name) => { if let Some(inp) = d.inputs.get_mut(1) { inp.items = vec![Sel::Axis { name }]; } } None => { - d.extra.insert("axis".into(), json!({"origin": pt3(*origin), "dir": pt3(*axis)})); + d.extra.insert("axis".into(), json!({"origin": pt3(origin.0), "dir": pt3(axis.0)})); } } d @@ -4712,8 +4713,8 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option) -> Option) -> Option { let mut d = start("construct.plane.offset")?; - d.kind = Kind::OffsetPlane { offset: distance.clone() }; + d.kind = Kind::OffsetPlane { offset: distance.to_string() }; if let Some(inp) = d.inputs.first_mut() { inp.items = plane_sel(s, base).into_iter().collect(); } @@ -4760,7 +4761,7 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option return None, }; - d.kind = Kind::PathPlane { t: t.clone(), sketch }; + d.kind = Kind::PathPlane { t: t.to_string(), sketch }; if let Some(input) = d.inputs.first_mut() { input.items = vec![item]; } @@ -4768,7 +4769,7 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option { let mut d = start("construct.plane.at_angle")?; - d.kind = Kind::AnglePlane { angle: angle.clone() }; + d.kind = Kind::AnglePlane { angle: angle.to_string() }; if let Some(inp) = d.inputs.first_mut() { inp.items = plane_sel(s, base).into_iter().collect(); } @@ -4787,11 +4788,11 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option { let mut d = start("solid.split_body")?; if let Some(inp) = d.inputs.first_mut() { - inp.items = vec![Sel::Body { name: body.clone() }]; + inp.items = vec![Sel::Body { name: body.to_string() }]; } if let Some(inp) = d.inputs.get_mut(1) { inp.items = match tool { - Some(t) => face_sel(s, t.point).into_iter().collect(), + Some(t) => face_sel(s, t.point.0).into_iter().collect(), None => plane_sel(s, plane).into_iter().collect(), }; } @@ -4799,11 +4800,11 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option { let mut d = start("solid.scale")?; - d.kind = Kind::Scale { factor: factor.clone() }; + d.kind = Kind::Scale { factor: factor.to_string() }; if let Some(inp) = d.inputs.first_mut() { - inp.items = bodies.iter().map(|n| Sel::Body { name: n.clone() }).collect(); + inp.items = bodies.iter().map(|n| Sel::Body { name: n.to_string() }).collect(); } - d.extra.insert("origin".into(), pt3(*origin)); + d.extra.insert("origin".into(), pt3(origin.0)); if let Some(f) = factors { d.extra.insert("factors".into(), json!(f)); } @@ -4811,9 +4812,9 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option { let mut d = start("solid.offset_face")?; - d.kind = Kind::OffsetFaces { distance: distance.clone() }; + d.kind = Kind::OffsetFaces { distance: distance.to_string() }; if let Some(inp) = d.inputs.first_mut() { - inp.items = faces.iter().filter_map(|p| face_sel(s, *p)).collect(); + 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)); @@ -4825,23 +4826,26 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option { let mut d = start("solid.bounding_solid")?; - d.kind = Kind::Stock { margin: margin.clone() }; + d.kind = Kind::Stock { margin: margin.to_string() }; if let Some(inp) = d.inputs.first_mut() { - inp.items = bodies.iter().map(|n| Sel::Body { name: n.clone() }).collect(); + inp.items = bodies.iter().map(|n| Sel::Body { name: n.to_string() }).collect(); } d } FeatureKind::Pipe { path, diameter, wall, operation, targets, .. } => { let mut d = start("solid.pipe")?; - d.kind = Kind::Pipe { diameter: diameter.clone(), wall: wall.clone().unwrap_or_default() }; + d.kind = Kind::Pipe { diameter: diameter.to_string(), wall: wall.as_deref().map(str::to_string).unwrap_or_default() }; if let Some(inp) = d.inputs.first_mut() { inp.items = path.iter().map(|id| Sel::SketchCurve { id: id.clone() }).collect(); } @@ -4853,10 +4857,10 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option { let mut d = start("solid.emboss")?; - d.kind = Kind::Emboss { depth: depth.clone(), deboss: *deboss }; - let items = st.sketch(*sketch).map(|ss| profile_indices(ss, profiles)).unwrap_or_default(); + d.kind = Kind::Emboss { depth: depth.to_string(), deboss: *deboss }; + let items = st.sketch(sketch.0).map(|ss| profile_indices(ss, profiles)).unwrap_or_default(); if let Some(inp) = d.inputs.first_mut() { - inp.items = items.into_iter().map(|index| Sel::Profile { sketch: *sketch, index }).collect(); + inp.items = items.into_iter().map(|index| Sel::Profile { sketch: sketch.0, index }).collect(); } if !targets.is_empty() { d.extra.insert("targets".into(), json!(targets)); @@ -4870,7 +4874,12 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option { let mut d = start(if *web { "solid.web" } else { "solid.rib" })?; - d.kind = Kind::Rib { web: *web, thickness: thickness.clone(), depth: depth.clone().unwrap_or_default(), flip: *flip }; + d.kind = Kind::Rib { + web: *web, + thickness: thickness.to_string(), + depth: depth.as_deref().map(str::to_string).unwrap_or_default(), + flip: *flip, + }; if let Some(inp) = d.inputs.first_mut() { inp.items = curves.iter().map(|id| Sel::SketchCurve { id: id.clone() }).collect(); } @@ -4879,7 +4888,7 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option { let mut d = start("solid.replace_face")?; if let Some(inp) = d.inputs.first_mut() { - inp.items = faces.iter().filter_map(|p| face_sel(s, *p)).collect(); + inp.items = faces.iter().filter_map(|p| face_sel(s, p.0)).collect(); } if let Some(inp) = d.inputs.get_mut(1) { inp.items = plane_sel(s, target).into_iter().collect(); @@ -4892,13 +4901,20 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option { let mut d = start("solid.remove")?; if let Some(inp) = d.inputs.first_mut() { - inp.items = bodies.iter().map(|n| Sel::Body { name: n.clone() }).collect(); + inp.items = bodies.iter().map(|n| Sel::Body { name: n.to_string() }).collect(); } d } FeatureKind::Move { bodies, translate, rotate_axis, angle, copy } => { let mut d = start("solid.move")?; - crate::dialogs_move::for_feature(&mut d, bodies, translate, *rotate_axis, angle.as_ref(), *copy); + crate::dialogs_move::for_feature( + &mut d, + &solidcraft_engine::doc::plain(bodies), + translate, + rotate_axis.map(Vec3::from), + angle.as_ref(), + *copy, + ); d } other => { diff --git a/crates/ui-egui/src/dialogs_move.rs b/crates/ui-egui/src/dialogs_move.rs index a7698f220..b555f4c31 100644 --- a/crates/ui-egui/src/dialogs_move.rs +++ b/crates/ui-egui/src/dialogs_move.rs @@ -288,8 +288,15 @@ pub fn drag(app: &SolveApp, d: &mut Dialog, g: Drag) { /// The dialog for editing a move: Free Move with its translation and, about a world axis /// through the origin, its angle (another axis is kept as it is). -pub fn for_feature(d: &mut Dialog, bodies: &[String], translate: &[String; 3], axis: Option, angle: Option<&String>, copy: bool) { - let [x, y, z] = translate.clone(); +pub fn for_feature( + d: &mut Dialog, + bodies: &[String], + translate: &[solidcraft_engine::doc::Expr; 3], + axis: Option, + angle: Option<&solidcraft_engine::doc::Expr>, + copy: bool, +) { + let [x, y, z] = translate.clone().map(String::from); let mut k = kind(FREE); if let Kind::Move { x: kx, y: ky, z: kz, rx, ry, rz, .. } = &mut k { (*kx, *ky, *kz) = (x, y, z); @@ -297,9 +304,9 @@ pub fn for_feature(d: &mut Dialog, bodies: &[String], translate: &[String; 3], a let dir = axis.unwrap_or(Vec3::Z); let world = [Vec3::X, Vec3::Y, Vec3::Z].iter().position(|w| dir.cross(*w).len() < 1e-9 && dir.dot(*w) > 0.0); match world { - Some(0) => *rx = a.clone(), - Some(1) => *ry = a.clone(), - Some(_) => *rz = a.clone(), + Some(0) => *rx = a.to_string(), + Some(1) => *ry = a.to_string(), + Some(_) => *rz = a.to_string(), None => { d.extra.insert("axis".into(), json!([dir.x, dir.y, dir.z])); d.extra.insert("angle".into(), json!(a)); diff --git a/crates/ui-egui/src/dialogs_plastic.rs b/crates/ui-egui/src/dialogs_plastic.rs index 4fbc4ec91..8a9d85b41 100644 --- a/crates/ui-egui/src/dialogs_plastic.rs +++ b/crates/ui-egui/src/dialogs_plastic.rs @@ -410,8 +410,8 @@ pub fn commands(app: &SolveApp, k: &Pl, inputs: &[SelInput], extra: &Map) -> String { - o.clone().unwrap_or_default() +fn s(o: &Option) -> String { + o.as_deref().map(str::to_string).unwrap_or_default() } /// The dialog editing a plastic feature, filled from it. @@ -434,7 +434,7 @@ pub fn for_feature(app: &SolveApp, kind: &FeatureKind) -> Option<(Kind, Vec { - extra.insert("direction".into(), pt(*direction)); + extra.insert("direction".into(), pt(direction.0)); if let Some(b) = body { extra.insert("body".into(), json!(b)); } @@ -452,63 +452,63 @@ pub fn for_feature(app: &SolveApp, kind: &FeatureKind) -> Option<(Kind, Vec { if let Some(b) = body { extra.insert("body".into(), json!(b)); } - (Pl::Lip { groove: *groove, width: width.clone(), height: height.clone(), gap: s(gap), outside: *outside }, "plastic.lip", *face) + (Pl::Lip { groove: *groove, width: width.to_string(), height: height.to_string(), gap: s(gap), outside: *outside }, "plastic.lip", face.0) } FeatureKind::SnapFit { position, direction, hook, length, thickness, width, catch_depth, catch_length, body } => { - extra.insert("direction".into(), pt(*direction)); + extra.insert("direction".into(), pt(direction.0)); if let Some(b) = body { extra.insert("body".into(), json!(b)); } - let h = hook_dirs(*direction).iter().position(|(_, d)| d.dist(*hook) < 1e-6); + let h = hook_dirs(direction.0).iter().position(|(_, d)| d.dist(hook.0) < 1e-6); if h.is_none() { - extra.insert("hook".into(), pt(*hook)); + extra.insert("hook".into(), pt(hook.0)); } let f = Pl::SnapFit { hook: h.unwrap_or(0), - length: length.clone(), - thickness: thickness.clone(), - width: width.clone(), - catch_depth: catch_depth.clone(), - catch_length: catch_length.clone(), + length: length.to_string(), + thickness: thickness.to_string(), + width: width.to_string(), + catch_depth: catch_depth.to_string(), + catch_length: catch_length.to_string(), }; - (f, "plastic.snap_fit", *position) + (f, "plastic.snap_fit", position.0) } FeatureKind::Rest { position, direction, along, width, length, height, draft, thickness, body } => { - extra.insert("direction".into(), pt(*direction)); + extra.insert("direction".into(), pt(direction.0)); if let Some(a) = along { - extra.insert("along".into(), pt(*a)); + extra.insert("along".into(), pt(a.0)); } if let Some(b) = body { extra.insert("body".into(), json!(b)); } let r = Pl::Rest { round: length.is_none(), - width: width.clone(), - length: length.clone().unwrap_or_else(|| "15 mm".into()), - height: height.clone(), + width: width.to_string(), + length: length.as_deref().map(str::to_string).unwrap_or_else(|| "15 mm".into()), + height: height.to_string(), draft: s(draft), thickness: s(thickness), }; - (r, "plastic.rest", *position) + (r, "plastic.rest", position.0) } _ => return None, }; diff --git a/crates/ui-egui/src/dialogs_sheet.rs b/crates/ui-egui/src/dialogs_sheet.rs index 1b52d08d2..91b5683bb 100644 --- a/crates/ui-egui/src/dialogs_sheet.rs +++ b/crates/ui-egui/src/dialogs_sheet.rs @@ -673,20 +673,20 @@ pub fn for_feature(app: &SolveApp, kind: &FeatureKind) -> Option<(Kind, Vec) = match kind { FeatureKind::SheetBase { sketch, profiles, rule, flip } => { - let ps = st.sketch(*sketch).map(|ss| profile_indices(ss, profiles)).unwrap_or_default(); + let ps = st.sketch(sketch.0).map(|ss| profile_indices(ss, profiles)).unwrap_or_default(); let mut f = new_flange(0); if let Sm::Flange { flip: fl, rule: r, .. } = &mut f { *fl = *flip; *r = rule_index(rule); } - (f, ps.into_iter().map(|index| Sel::Profile { sketch: *sketch, index }).collect()) + (f, ps.into_iter().map(|index| Sel::Profile { sketch: sketch.0, index }).collect()) } FeatureKind::SheetContour { curves, distance, rule, flip, reverse, .. } => { let mut f = new_flange(2); if let Sm::Flange { flip: fl, rule: r, distance: d, reverse: rv, .. } = &mut f { *fl = *flip; *r = rule_index(rule); - *d = distance.clone(); + *d = distance.to_string(); *rv = *reverse; } (f, curves.iter().map(|id| Sel::SketchCurve { id: id.clone() }).collect()) @@ -699,17 +699,21 @@ pub fn for_feature(app: &SolveApp, kind: &FeatureKind) -> Option<(Kind, Vec Option<(Kind, Vec Option<(Kind, Vec { @@ -738,8 +742,8 @@ pub fn for_feature(app: &SolveApp, kind: &FeatureKind) -> Option<(Kind, Vec Option<(Kind, Vec { - extra.insert("points".into(), json!([pt(*a), pt(*b)])); + extra.insert("points".into(), json!([pt(a.0), pt(b.0)])); } } if let Some(i) = ins.get_mut(1) { - i.items = fixed.and_then(|f| face_sel(s, f)).into_iter().collect(); + i.items = fixed.and_then(|f| face_sel(s, f.0)).into_iter().collect(); } return Some((Kind::Sheet(k), ins, extra)); } - FeatureKind::SheetUnfold { body, refold } => (Sm::Unfold { refold: *refold }, body.iter().map(|n| Sel::Body { name: n.clone() }).collect()), + FeatureKind::SheetUnfold { body, refold } => { + (Sm::Unfold { refold: *refold }, body.iter().map(|n| Sel::Body { name: n.to_string() }).collect()) + } FeatureKind::SheetConvert { face, rule, bends, .. } => { let (_, mut ins) = start(app, "sheet.convert")?; if let Some(i) = ins.first_mut() { - i.items = face_sel(s, *face).into_iter().collect(); + i.items = face_sel(s, face.0).into_iter().collect(); } if let Some(i) = ins.get_mut(1) { - i.items = bends.iter().filter_map(|p| edge_sel(s, *p)).collect(); + i.items = bends.iter().filter_map(|p| edge_sel(s, p.0)).collect(); } return Some((Kind::Sheet(Sm::Convert { rule: rule_index(rule) }), ins, extra)); } diff --git a/crates/ui-egui/src/dialogs_surface.rs b/crates/ui-egui/src/dialogs_surface.rs index 7621066b2..7694ad36e 100644 --- a/crates/ui-egui/src/dialogs_surface.rs +++ b/crates/ui-egui/src/dialogs_surface.rs @@ -575,7 +575,7 @@ pub fn commands(app: &SolveApp, k: &Surf, inputs: &[SelInput], extra: &Map) -> Option { match tool { - Some(t) => crate::dialogs::face_sel(&app.session, t.point), + Some(t) => crate::dialogs::face_sel(&app.session, t.point.0), None => crate::dialogs::plane_sel(&app.session, plane), } } @@ -584,7 +584,7 @@ fn tool_sel(app: &SolveApp, plane: &PlaneRef, tool: Option<&FaceAt>) -> Option Option<(Kind, Vec, Map)> { let s = &app.session; - let edge = |p: &Vec3| crate::dialogs::edge_sel(s, *p); + let edge = |p: &solidcraft_engine::doc::Position| crate::dialogs::edge_sel(s, p.0); let (k, fill): (Surf, Vec>) = match kind { FeatureKind::SurfaceRevolve { sketch, profiles, curves, axis, angle, angle2, symmetric } => { let (pick, stored) = match axis { @@ -594,8 +594,8 @@ pub fn for_feature(app: &SolveApp, kind: &FeatureKind, frame: &Mat) -> Option<(K AxisRef::Line { origin, dir } => ( None, Some(json!({ - "origin": pt(solidcraft_engine::doc::apply_point(frame, *origin)), - "dir": pt(solidcraft_engine::doc::apply_vector(frame, *dir)) + "origin": pt(solidcraft_engine::doc::apply_point(frame, origin.0)), + "dir": pt(solidcraft_engine::doc::apply_vector(frame, dir.0)) })), ), }; @@ -603,9 +603,9 @@ pub fn for_feature(app: &SolveApp, kind: &FeatureKind, frame: &Mat) -> Option<(K if let Some(a2) = angle2 { extra.insert("angle2".into(), json!(a2)); } - let k = Surf::Revolve { angle: angle.clone(), symmetric: *symmetric, axis: stored }; + let k = Surf::Revolve { angle: angle.to_string(), symmetric: *symmetric, axis: stored }; let mut ins = inputs(&k); - for (inp, items) in ins.iter_mut().zip([sheet_sels(app, *sketch, profiles.as_ref(), curves), pick.into_iter().collect()]) { + for (inp, items) in ins.iter_mut().zip([sheet_sels(app, sketch.0, profiles.as_ref(), curves), pick.into_iter().collect()]) { inp.items = items; } return Some((Kind::Surface(k), ins, extra)); @@ -615,23 +615,23 @@ pub fn for_feature(app: &SolveApp, kind: &FeatureKind, frame: &Mat) -> Option<(K ( Surf::Sweep(opts), vec![ - sheet_sels(app, *sketch, profiles.as_ref(), curves), + sheet_sels(app, sketch.0, profiles.as_ref(), curves), path.iter().map(|id| Sel::SketchCurve { id: id.clone() }).collect(), direction.into_iter().collect(), ], ) } FeatureKind::SurfaceLoft { sections } => { - (Surf::Loft, vec![sections.iter().flat_map(|sec| sheet_sels(app, sec.sketch, sec.profiles.as_ref(), &sec.curves)).collect()]) + (Surf::Loft, vec![sections.iter().flat_map(|sec| sheet_sels(app, sec.sketch.0, sec.profiles.as_ref(), &sec.curves)).collect()]) } FeatureKind::SurfaceExtrude { sketch, profiles, curves, extent } => { - let sels = sheet_sels(app, *sketch, profiles.as_ref(), curves); + let sels = sheet_sels(app, sketch.0, profiles.as_ref(), curves); let direction = match extent.direction { Direction::Positive => 0, Direction::Symmetric => 1, Direction::Negative => 2, }; - let k = Surf::Extrude { distance: extent.distance.clone(), direction }; + let k = Surf::Extrude { distance: extent.distance.to_string(), direction }; let mut ins = inputs(&k); if let Some(input) = ins.first_mut() { input.items = sels; @@ -644,14 +644,14 @@ pub fn for_feature(app: &SolveApp, kind: &FeatureKind, frame: &Mat) -> Option<(K let mut sels: Vec = edges.iter().filter_map(edge).collect(); if let Some(sk) = sketch { let st = s.world_state(); - if let Some(ss) = st.sketch(*sk) { - sels.extend((0..ss.profiles.len()).map(|index| Sel::Profile { sketch: *sk, index })); + if let Some(ss) = st.sketch(sk.0) { + sels.extend((0..ss.profiles.len()).map(|index| Sel::Profile { sketch: sk.0, index })); } } let index = PATCH_CONTINUITY.iter().position(|(_, w)| *w == continuity.all.as_str()).unwrap_or(0); // What the dialog does not show is kept as it was: the crown, edges with a // continuity of their own, and points that are not on a face any more. - let through: Vec = points.iter().filter_map(|p| crate::dialogs::face_sel(s, *p)).collect(); + let through: Vec = points.iter().filter_map(|p| crate::dialogs::face_sel(s, p.0)).collect(); let mut extra = Map::new(); if *crown != 0.0 { extra.insert("crown".into(), json!(crown)); @@ -660,7 +660,7 @@ pub fn for_feature(app: &SolveApp, kind: &FeatureKind, frame: &Mat) -> Option<(K extra.insert("continuity".into(), serde_json::to_value(continuity).unwrap_or(Value::Null)); } if through.len() != points.len() { - extra.insert("points".into(), json!(points.iter().map(|p| pt(*p)).collect::>())); + extra.insert("points".into(), json!(points.iter().map(|p| pt(p.0)).collect::>())); } let k = Surf::Patch { continuity: index }; let mut ins = inputs(&k); @@ -669,48 +669,49 @@ pub fn for_feature(app: &SolveApp, kind: &FeatureKind, frame: &Mat) -> Option<(K } return Some((Kind::Surface(k), ins, extra)); } - FeatureKind::SurfaceOffset { faces, distance, chain, .. } => { - (Surf::Offset { distance: distance.clone(), chain: *chain }, vec![faces.iter().filter_map(|p| crate::dialogs::face_sel(s, *p)).collect()]) - } + FeatureKind::SurfaceOffset { faces, distance, chain, .. } => ( + Surf::Offset { distance: distance.to_string(), chain: *chain }, + vec![faces.iter().filter_map(|p| crate::dialogs::face_sel(s, p.0)).collect()], + ), FeatureKind::SurfaceRuled { edges, distance, mode, angle, direction, flip, corners, face, .. } => { let k = Surf::Ruled { - distance: distance.clone(), + distance: distance.to_string(), mode: match mode { RuledMode::Normal => 0, RuledMode::Tangent => 1, RuledMode::Angle => 2, RuledMode::Direction => 3, }, - angle: angle.clone().unwrap_or_else(|| "5 deg".into()), + angle: angle.as_deref().map(str::to_string).unwrap_or_else(|| "5 deg".into()), flip: *flip, round: *corners == RuledCorners::Round, }; let mut ins = inputs(&k); - let fill = [edges.iter().filter_map(edge).collect(), face.and_then(|p| crate::dialogs::face_sel(s, p)).into_iter().collect()]; + let fill = [edges.iter().filter_map(edge).collect(), face.and_then(|p| crate::dialogs::face_sel(s, p.0)).into_iter().collect()]; for (inp, items) in ins.iter_mut().zip(fill) { inp.items = items; } let mut extra = Map::new(); if let Some(d) = direction { - extra.insert("direction".into(), pt(*d)); + extra.insert("direction".into(), pt(d.0)); } return Some((Kind::Surface(k), ins, extra)); } FeatureKind::Unstitch { body, faces } | FeatureKind::ReverseNormal { body, faces } => { let sels: Vec = if faces.is_empty() { - vec![Sel::Body { name: body.clone() }] + vec![Sel::Body { name: body.to_string() }] } else { - faces.iter().filter_map(|p| crate::dialogs::face_sel(s, *p)).collect() + faces.iter().filter_map(|p| crate::dialogs::face_sel(s, p.0)).collect() }; (if matches!(kind, FeatureKind::Unstitch { .. }) { Surf::Unstitch } else { Surf::ReverseNormal }, vec![sels]) } FeatureKind::Stitch { bodies, tolerance } => ( - Surf::Stitch { tolerance: if tolerance.trim() == "0" { String::new() } else { tolerance.clone() } }, - vec![bodies.iter().map(|n| Sel::Body { name: n.clone() }).collect()], + Surf::Stitch { tolerance: if tolerance.trim() == "0" { String::new() } else { tolerance.to_string() } }, + vec![bodies.iter().map(|n| Sel::Body { name: n.to_string() }).collect()], ), FeatureKind::Thicken { bodies, thickness, symmetric, operation, .. } => ( - Surf::Thicken { thickness: thickness.clone(), symmetric: *symmetric, operation: op_index(operation) }, - vec![bodies.iter().map(|n| Sel::Body { name: n.clone() }).collect()], + Surf::Thicken { thickness: thickness.to_string(), symmetric: *symmetric, operation: op_index(operation) }, + vec![bodies.iter().map(|n| Sel::Body { name: n.to_string() }).collect()], ), FeatureKind::SurfaceExtend { edges, distance, mode, up_to, neighbours, .. } => { // The dialog edits the edges and the distance; the rest is kept as it was. @@ -726,14 +727,17 @@ pub fn for_feature(app: &SolveApp, kind: &FeatureKind, frame: &Mat) -> Option<(K extra.insert("up_to".into(), json!("bounds")); } Some(solidcraft_engine::doc::ExtendTo::Face(t)) => { - extra.insert("up_to".into(), json!({"body": t.body, "point": pt(t.point)})); + extra.insert("up_to".into(), json!({"body": t.body, "point": pt(t.point.0)})); } - Some(solidcraft_engine::doc::ExtendTo::Plane(PlaneRef::Origin { name } | PlaneRef::Construction { name })) => { + Some(solidcraft_engine::doc::ExtendTo::Plane(PlaneRef::Origin { name })) => { + extra.insert("up_to".into(), json!(name)); + } + Some(solidcraft_engine::doc::ExtendTo::Plane(PlaneRef::Construction { name })) => { extra.insert("up_to".into(), json!(name)); } _ => {} } - let k = Surf::Extend { distance: distance.clone() }; + let k = Surf::Extend { distance: distance.to_string() }; let mut ins = inputs(&k); if let Some(inp) = ins.first_mut() { inp.items = edges.iter().filter_map(edge).collect(); @@ -743,9 +747,9 @@ pub fn for_feature(app: &SolveApp, kind: &FeatureKind, frame: &Mat) -> Option<(K FeatureKind::SurfaceTrim { body, plane, tool, keep } => ( Surf::Trim, vec![ - vec![Sel::Body { name: body.clone() }], + vec![Sel::Body { name: body.to_string() }], tool_sel(app, plane, tool.as_ref()).into_iter().collect(), - crate::dialogs::face_sel(s, *keep).into_iter().collect(), + crate::dialogs::face_sel(s, keep.0).into_iter().collect(), ], ), FeatureKind::SurfaceUntrim { face, holes, outer, in_place } => { @@ -756,12 +760,12 @@ pub fn for_feature(app: &SolveApp, kind: &FeatureKind, frame: &Mat) -> Option<(K }; ( Surf::Untrim { holes: index, outer: *outer, in_place: *in_place }, - vec![crate::dialogs::face_sel(s, face.point).into_iter().collect(), picked], + vec![crate::dialogs::face_sel(s, face.point.0).into_iter().collect(), picked], ) } FeatureKind::SplitFace { faces, plane, tool, .. } => ( Surf::SplitFace, - vec![faces.iter().filter_map(|p| crate::dialogs::face_sel(s, *p)).collect(), tool_sel(app, plane, tool.as_ref()).into_iter().collect()], + vec![faces.iter().filter_map(|p| crate::dialogs::face_sel(s, p.0)).collect(), tool_sel(app, plane, tool.as_ref()).into_iter().collect()], ), _ => return None, }; diff --git a/crates/ui-egui/src/dialogs_sweep.rs b/crates/ui-egui/src/dialogs_sweep.rs index ad5c7eccc..dd5e23343 100644 --- a/crates/ui-egui/src/dialogs_sweep.rs +++ b/crates/ui-egui/src/dialogs_sweep.rs @@ -3,7 +3,7 @@ use serde_json::{Value, json}; use solidcraft_engine::Sel; -use solidcraft_engine::doc::{Mat, SweepOrientation}; +use solidcraft_engine::doc::{Expr, Mat, SweepOrientation}; use solidcraft_engine::geom::Vec3; use crate::SolveApp; @@ -40,10 +40,10 @@ impl SweepOpts { /// A feature's stored options as dialog values; `frame` maps the feature's component frame to /// the world (a stored direction is in the component's frame). A direction along an origin /// axis comes back as a pick of that axis. - pub fn of(orientation: &SweepOrientation, twist: &Option, scale: &Option, frame: &Mat) -> (SweepOpts, Option) { + pub fn of(orientation: &SweepOrientation, twist: &Option, scale: &Option, frame: &Mat) -> (SweepOpts, Option) { let mut o = SweepOpts { - twist: twist.clone().unwrap_or_else(|| NO_TWIST.into()), - scale: scale.clone().unwrap_or_else(|| NO_SCALE.into()), + 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()), ..SweepOpts::default() }; let mut pick = None; @@ -52,7 +52,7 @@ impl SweepOpts { SweepOrientation::Parallel => o.orientation = 1, SweepOrientation::Direction(d) => { o.orientation = DIRECTION; - let world = solidcraft_engine::doc::apply_vector(frame, *d); + let world = solidcraft_engine::doc::apply_vector(frame, d.0); match world.normalized().and_then(world_axis) { Some(name) => pick = Some(Sel::Axis { name: name.into() }), None => o.direction = Some(world), diff --git a/crates/ui-egui/src/hole_direction_ui_tests.rs b/crates/ui-egui/src/hole_direction_ui_tests.rs index 014394f6c..c6be4157b 100644 --- a/crates/ui-egui/src/hole_direction_ui_tests.rs +++ b/crates/ui-egui/src/hole_direction_ui_tests.rs @@ -25,7 +25,7 @@ fn arrow(h: &Harness) -> (Vec3, Vec3) { fn last_hole_direction(h: &Harness) -> Vec3 { match &h.app.session.doc.features.last().unwrap().kind { - FeatureKind::Hole { direction, .. } => *direction, + FeatureKind::Hole { direction, .. } => direction.0, other => panic!("the last feature is not a hole: {}", other.type_name()), } } diff --git a/crates/ui-egui/src/hole_placement_ui_tests.rs b/crates/ui-egui/src/hole_placement_ui_tests.rs index d93ac6fb0..d87ec460b 100644 --- a/crates/ui-egui/src/hole_placement_ui_tests.rs +++ b/crates/ui-egui/src/hole_placement_ui_tests.rs @@ -77,7 +77,7 @@ fn hovered_face_point(h: &mut Harness, at: [f64; 2]) -> Vec3 { fn hole(h: &Harness) -> (u64, Vec3, bool) { let f = h.app.session.doc.features.last().unwrap(); match &f.kind { - FeatureKind::Hole { position, points, .. } => (f.id, *position, points.is_some()), + FeatureKind::Hole { position, points, .. } => (f.id, position.0, points.is_some()), other => panic!("the last feature is not a hole: {}", other.type_name()), } } diff --git a/crates/ui-egui/src/primitive_units_tests.rs b/crates/ui-egui/src/primitive_units_tests.rs index 7a4c0b975..7de003a38 100644 --- a/crates/ui-egui/src/primitive_units_tests.rs +++ b/crates/ui-egui/src/primitive_units_tests.rs @@ -156,10 +156,10 @@ fn a_centimetre_design_shows_centimetres() { fn stored(h: &Harness, id: u64) -> Vec { use solidcraft_engine::doc::FeatureKind; match h.app.session.doc.feature(id).map(|f| &f.kind) { - Some(FeatureKind::Box { length, width, height, .. }) => vec![length.clone(), width.clone(), height.clone()], - Some(FeatureKind::Cylinder { radius, height, .. }) => vec![radius.clone(), height.clone()], - Some(FeatureKind::Sphere { radius, .. }) => vec![radius.clone()], - Some(FeatureKind::Torus { major, minor, .. }) => vec![major.clone(), minor.clone()], + Some(FeatureKind::Box { length, width, height, .. }) => vec![length.to_string(), width.to_string(), height.to_string()], + Some(FeatureKind::Cylinder { radius, height, .. }) => vec![radius.to_string(), height.to_string()], + Some(FeatureKind::Sphere { radius, .. }) => vec![radius.to_string()], + Some(FeatureKind::Torus { major, minor, .. }) => vec![major.to_string(), minor.to_string()], other => panic!("not a primitive: {other:?}"), } } diff --git a/crates/ui-egui/src/revolve_manipulator_tests.rs b/crates/ui-egui/src/revolve_manipulator_tests.rs index e4e421674..1b8c85ad8 100644 --- a/crates/ui-egui/src/revolve_manipulator_tests.rs +++ b/crates/ui-egui/src/revolve_manipulator_tests.rs @@ -33,7 +33,7 @@ fn volume(h: &Harness) -> f64 { } fn angle(h: &Harness) -> String { let FeatureKind::Revolve { angle, .. } = &h.app.session.doc.find_feature("Turn").unwrap().kind else { panic!("revolve") }; - angle.clone() + angle.to_string() } fn expected_volume(degrees: f64) -> f64 { 0.5 * (225.0 - 100.0) * 5.0 * degrees.to_radians() diff --git a/crates/ui-egui/src/sweep_dialog_tests.rs b/crates/ui-egui/src/sweep_dialog_tests.rs index 6f50cf344..a2803e2de 100644 --- a/crates/ui-egui/src/sweep_dialog_tests.rs +++ b/crates/ui-egui/src/sweep_dialog_tests.rs @@ -39,9 +39,9 @@ fn a_new_sweep_takes_its_options_from_the_dialog() { assert!(h.app.dialog.is_none(), "{:?}", h.app.session.log); let f = h.app.session.doc.features.last().unwrap(); let FeatureKind::Sweep { orientation, twist, scale, .. } = &f.kind else { panic!("{:?}", f.kind) }; - assert_eq!(*orientation, SweepOrientation::Direction(Vec3::X)); - assert_eq!(twist.as_deref(), Some("90 deg")); - assert_eq!(scale.as_deref(), Some("0.5")); + assert_eq!(*orientation, SweepOrientation::Direction(solidcraft_engine::doc::Dir(Vec3::X))); + assert_eq!(twist.as_ref().map(|t| t.as_str()), Some("90 deg")); + assert_eq!(scale.as_ref().map(|k| k.as_str()), Some("0.5")); } #[test] diff --git a/crates/ui-egui/src/timeline.rs b/crates/ui-egui/src/timeline.rs index a18760115..4e7fccd26 100644 --- a/crates/ui-egui/src/timeline.rs +++ b/crates/ui-egui/src/timeline.rs @@ -333,7 +333,7 @@ pub fn timeline(app: &mut SolveApp, ui: &mut egui::Ui) { if let Some(sk) = sketch_of && ui.button(crate::i18n::tr_label("Edit Profile Sketch")).clicked() { - app.edit_sketch(sk); + app.edit_sketch(sk.0); ui.close(); } if ui.button(crate::i18n::tr_label("Rename")).clicked() { diff --git a/crates/ui-egui/src/timeline_left.rs b/crates/ui-egui/src/timeline_left.rs index 98d3429ef..d701ec49a 100644 --- a/crates/ui-egui/src/timeline_left.rs +++ b/crates/ui-egui/src/timeline_left.rs @@ -774,7 +774,7 @@ fn vertical_features(app: &mut SolveApp, ui: &mut egui::Ui) { if let Some(sketch) = sketch && ui.button("Edit Profile Sketch").clicked() { - app.edit_sketch(sketch); + app.edit_sketch(sketch.0); ui.close(); } if ui.button("Rename Feature").clicked() { From 371578a06fc29fbd31abf600af5a1e4876909f6b Mon Sep 17 00:00:00 2001 From: Karl Von Richter Date: Fri, 16 Oct 2026 14:32:32 +1000 Subject: [PATCH 72/92] Feat/Sketch: associative pattern tools with independent directions and Flip/Center controls (#1601) Thanks @Karl-VonRichter. --- assets/icons/ui/source/icons.rs | 14 + assets/locales/de.json | 7 + assets/locales/en.json | 6 + assets/locales/fr.json | 6 + assets/locales/ja.json | 6 + assets/locales/ko.json | 7 + assets/locales/ru.json | 6 + assets/locales/tr.json | 6 + assets/locales/uk.json | 6 + assets/locales/zh.json | 6 + .../pending/sketch-pattern-directions.rs | 5 + crates/engine/src/cmd/sketch_modify.rs | 13 +- crates/engine/src/cmd/sketch_pattern.rs | 132 ++++++- crates/engine/src/cmd/sketch_pattern_tests.rs | 355 ++++++++++++++++++ crates/sketch/src/lib.rs | 2 +- crates/sketch/src/model.rs | 20 +- crates/sketch/src/pattern.rs | 76 +++- crates/sketch/src/solver.rs | 11 +- crates/ui-egui/src/browser.rs | 11 + crates/ui-egui/src/canvas.rs | 2 +- crates/ui-egui/src/dialogs.rs | 125 ++++-- crates/ui-egui/src/lib.rs | 1 + .../ui-egui/src/sketch_guidance_ui_tests.rs | 4 +- crates/ui-egui/src/sketch_modify_ui.rs | 121 ++++-- crates/ui-egui/src/sketch_modify_ui_tests.rs | 126 ++++++- crates/ui-egui/src/sketch_pattern_tree.rs | 132 +++++++ crates/ui-egui/src/sketch_tools.rs | 4 +- crates/ui-egui/src/timeline_left.rs | 24 +- crates/ui-egui/src/toolbar.rs | 3 +- crates/ui-egui/src/workspace.rs | 1 + .../scenarios/sketch_pattern_alignment.json | 48 +++ .../sketch_pattern_circular_center.json | 33 ++ .../scenarios/sketch_pattern_even_center.json | 49 +++ .../sketch_pattern_two_directions.json | 38 ++ docs/book/src/guide/files.md | 3 + docs/sketch-patterns.md | 72 ++++ 36 files changed, 1394 insertions(+), 87 deletions(-) create mode 100644 crates/doc/src/format/pending/sketch-pattern-directions.rs create mode 100644 crates/ui-egui/src/sketch_pattern_tree.rs create mode 100644 crates/ui-egui/tests/scenarios/sketch_pattern_alignment.json create mode 100644 crates/ui-egui/tests/scenarios/sketch_pattern_circular_center.json create mode 100644 crates/ui-egui/tests/scenarios/sketch_pattern_even_center.json create mode 100644 crates/ui-egui/tests/scenarios/sketch_pattern_two_directions.json create mode 100644 docs/sketch-patterns.md diff --git a/assets/icons/ui/source/icons.rs b/assets/icons/ui/source/icons.rs index 8f4fb5ded..64ba3d46d 100644 --- a/assets/icons/ui/source/icons.rs +++ b/assets/icons/ui/source/icons.rs @@ -762,6 +762,20 @@ pub(crate) fn paint_with(p: &Painter, r: Rect, name: &str, ink: Color32, fill: C pen.closed(&[(21.0, 6.0), (15.0, 10.0), (15.0, 18.0), (21.0, 18.0)], a); } "sketch_circ_pattern" => paint(p, r, "pattern_circ", ink, Color32::TRANSPARENT, a), + "pattern_flip" => { + // Opposing arrows show reversal, with a short reference tick between them. + pen.arrow((4.0, 7.0), (20.0, 7.0), a); + pen.arrow((20.0, 17.0), (4.0, 17.0), ink); + pen.line(&[(12.0, 10.0), (12.0, 14.0)], ink); + } + "pattern_center" => { + // An original on a reference axis, with one equally spaced copy on either side. + pen.line(&[(12.0, 3.0), (12.0, 21.0)], a); + pen.line(&[(4.0, 12.0), (20.0, 12.0)], ink); + for x in [4.0, 12.0, 20.0] { + pen.circle(x, 12.0, 2.4, fill, if x == 12.0 { a } else { ink }); + } + } "sketch_rect_pattern" => paint(p, r, "pattern_rect", ink, Color32::TRANSPARENT, a), "line_mid" => { pen.line(&[(3.0, 19.0), (21.0, 5.0)], a); diff --git a/assets/locales/de.json b/assets/locales/de.json index 37247a446..a66781c93 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -4,6 +4,7 @@ "2. Attach your screenshot: copy and paste it, or save and upload the PNG.": "2. Screenshot anhängen: kopieren und einfügen oder als PNG speichern und hochladen.", "3. Click Submit new issue on GitHub to send your report.": "3. Auf GitHub auf Submit new issue klicken, um den Bericht zu senden.", "AI": "KI", + "Alignment": "Ausrichtung", "Arc length": "Bogenlänge", "Area": "Fläche", "BROWSER": "BROWSER", @@ -457,6 +458,11 @@ "nav.touchpad.pan": "Verschieben (Umschalt halten und bewegen; ohne Maustaste)", "nav.touchpad.scroll": "Touchpad verwendet vertikales Scrollen zum Zoomen. Die Zwei-Finger-Verschiebung bleibt für andere Vorgaben gespeichert.", "nav.touchpad.zoom": "Zoom (vertikal scrollen oder Finger spreizen/zusammenziehen)", + "pattern.alignment_2": "Ausrichtung 2", + "pattern.alignment_hint": "Die Anzahl enthält das Original. Die zentrierte Anordnung verteilt Kopien auf beide Seiten; bei gerader Anzahl legt die Richtungsumkehr die Seite mit der zusätzlichen Kopie fest.", + "pattern.direction_1": "Richtung 1", + "pattern.direction_2": "Richtung 2", + "pattern.flip_direction": "Richtung umkehren", "render.background": "Szenenhintergrund", "render.fit": "Produkt einpassen", "render.image_cancel": "Rendering abbrechen", @@ -874,6 +880,7 @@ "ui.heading_offset_plane": "ABSTANDSEBENE", "ui.heading_ok": "OK", "ui.heading_parameters": "PARAMETER", + "ui.heading_pattern": "MUSTER", "ui.heading_pattern_on_path": "PFADMUSTER", "ui.heading_pipe": "ROHR", "ui.heading_plane_at_angle": "EBENE IM WINKEL", diff --git a/assets/locales/en.json b/assets/locales/en.json index 97a63780d..a43d5e635 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -671,6 +671,11 @@ "no interference": "no interference", "no joint that moves yet": "no joint that moves yet", "no picture": "no picture", + "pattern.alignment_2": "Alignment 2", + "pattern.alignment_hint": "Counts include the original. Center balances copies; Flip chooses the extra side for even totals.", + "pattern.direction_1": "Direction 1", + "pattern.direction_2": "Direction 2", + "pattern.flip_direction": "Flip direction", "pick a hole to seat it, or OK places it at the origin": "pick a hole to seat it, or OK places it at the origin", "pick one or two vertices, edges or faces": "pick one or two vertices, edges or faces", "render.background": "Scene background", @@ -1118,6 +1123,7 @@ "ui.heading_offset_plane": "OFFSET PLANE", "ui.heading_ok": "OK", "ui.heading_parameters": "PARAMETERS", + "ui.heading_pattern": "PATTERN", "ui.heading_pattern_on_path": "PATTERN ON PATH", "ui.heading_pipe": "PIPE", "ui.heading_plane_at_angle": "PLANE AT ANGLE", diff --git a/assets/locales/fr.json b/assets/locales/fr.json index be28647c0..ef81a808b 100644 --- a/assets/locales/fr.json +++ b/assets/locales/fr.json @@ -651,6 +651,11 @@ "no interference": "aucune interférence", "no joint that moves yet": "aucune liaison mobile pour l'instant", "no picture": "aucune image", + "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", + "pattern.direction_2": "Direction 2", + "pattern.flip_direction": "Inverser la direction", "pick a hole to seat it, or OK places it at the origin": "choisir un trou pour la loger, ou OK la place à l'origine", "pick one or two vertices, edges or faces": "choisir un ou deux sommets, arêtes ou faces", "render.background": "Arrière-plan de la scène", @@ -944,6 +949,7 @@ "ui.heading_offset_plane": "PLAN DÉCALÉ", "ui.heading_ok": "OK", "ui.heading_parameters": "PARAMÈTRES", + "ui.heading_pattern": "RÉSEAU", "ui.heading_pattern_on_path": "RÉSEAU SUR TRAJECTOIRE", "ui.heading_pipe": "TUYAU", "ui.heading_plane_at_angle": "PLAN INCLINÉ", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 1a454e417..5cf189b37 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -671,6 +671,11 @@ "no interference": "干渉なし", "no joint that moves yet": "可動ジョイントがまだありません", "no picture": "画像なし", + "pattern.alignment_2": "配置 2", + "pattern.alignment_hint": "個数には元の図形が含まれます。中央配置ではコピーを両側に配置し、反転で偶数個の場合に多く配置する側を切り替えます。", + "pattern.direction_1": "方向 1", + "pattern.direction_2": "方向 2", + "pattern.flip_direction": "方向を反転", "pick a hole to seat it, or OK places it at the origin": "配置先の穴を選択するか、[OK]を押すと原点に配置します。", "pick one or two vertices, edges or faces": "1つまたは2つの頂点、エッジ、面を選択", "render.background": "シーンの背景", @@ -1118,6 +1123,7 @@ "ui.heading_offset_plane": "オフセット平面", "ui.heading_ok": "OK", "ui.heading_parameters": "パラメータ", + "ui.heading_pattern": "パターン", "ui.heading_pattern_on_path": "パス上のパターン", "ui.heading_pipe": "パイプ", "ui.heading_plane_at_angle": "傾斜平面", diff --git a/assets/locales/ko.json b/assets/locales/ko.json index 29fd3eb0a..b091bd818 100644 --- a/assets/locales/ko.json +++ b/assets/locales/ko.json @@ -4,6 +4,7 @@ "2. Attach your screenshot: copy and paste it, or save and upload the PNG.": "2. 스크린샷을 첨부하세요. 복사하여 붙여넣거나 PNG로 저장한 뒤 업로드하세요.", "3. Click Submit new issue on GitHub to send your report.": "3. GitHub에서 Submit new issue를 클릭하여 보고서를 보내세요.", "AI": "AI", + "Alignment": "정렬", "Arc length": "호 길이", "Area": "면적", "BROWSER": "브라우저", @@ -457,6 +458,11 @@ "nav.touchpad.pan": "화면 이동 (Shift를 누르고 이동, 마우스 버튼 불필요)", "nav.touchpad.scroll": "터치패드는 세로 스크롤로 확대/축소합니다. 두 손가락 이동 설정은 다른 프리셋을 위해 유지됩니다.", "nav.touchpad.zoom": "확대/축소 (세로 스크롤 또는 핀치)", + "pattern.alignment_2": "정렬 2", + "pattern.alignment_hint": "개수에는 원본이 포함됩니다. 가운데 정렬은 복사본을 양쪽에 배치하며, 개수가 짝수이면 방향 반전으로 복사본이 하나 더 배치되는 쪽을 선택합니다.", + "pattern.direction_1": "방향 1", + "pattern.direction_2": "방향 2", + "pattern.flip_direction": "방향 반전", "render.background": "장면 배경", "render.fit": "제품에 맞추기", "render.image_cancel": "렌더링 취소", @@ -874,6 +880,7 @@ "ui.heading_offset_plane": "오프셋 평면", "ui.heading_ok": "확인", "ui.heading_parameters": "매개변수", + "ui.heading_pattern": "패턴", "ui.heading_pattern_on_path": "경로 패턴", "ui.heading_pipe": "파이프", "ui.heading_plane_at_angle": "각도 평면", diff --git a/assets/locales/ru.json b/assets/locales/ru.json index 630f085f8..9557c926f 100644 --- a/assets/locales/ru.json +++ b/assets/locales/ru.json @@ -613,6 +613,11 @@ "no interference": "нет интерференции", "no joint that moves yet": "пока нет подвижных сопряжений", "no picture": "нет картинки", + "pattern.alignment_2": "Выравнивание 2", + "pattern.alignment_hint": "Количество включает оригинал. Центрирование распределяет копии по обе стороны; при чётном количестве смена направления выбирает сторону с дополнительной копией.", + "pattern.direction_1": "Направление 1", + "pattern.direction_2": "Направление 2", + "pattern.flip_direction": "Изменить направление", "pick a hole to seat it, or OK places it at the origin": "выберите отверстие для установки, или OK разместит в начале координат", "pick one or two vertices, edges or faces": "выберите одну-две вершины, ребра или грани", "render.background": "Фон сцены", @@ -896,6 +901,7 @@ "ui.heading_offset_plane": "СМЕЩЁННАЯ ПЛОСКОСТЬ", "ui.heading_ok": "OK", "ui.heading_parameters": "ПАРАМЕТРЫ", + "ui.heading_pattern": "МАССИВ", "ui.heading_pattern_on_path": "МАССИВ ПО ТРАЕКТОРИИ", "ui.heading_pipe": "ТРУБА", "ui.heading_plane_at_angle": "ПЛОСКОСТЬ ПОД УГЛОМ", diff --git a/assets/locales/tr.json b/assets/locales/tr.json index 8ccc757ad..e916335a0 100644 --- a/assets/locales/tr.json +++ b/assets/locales/tr.json @@ -628,6 +628,11 @@ "no interference": "girişim yok", "no joint that moves yet": "henüz hareket eden bir bağlantı yok", "no picture": "resim yok", + "pattern.alignment_2": "Hizalama 2", + "pattern.alignment_hint": "Adet, orijinali içerir. Ortala, kopyaları iki yana dağıtır; çift adetlerde yönü ters çevirme, fazladan kopyanın hangi tarafta olacağını belirler.", + "pattern.direction_1": "Yön 1", + "pattern.direction_2": "Yön 2", + "pattern.flip_direction": "Yönü ters çevir", "pick a hole to seat it, or OK places it at the origin": "yerleştirmek için bir delik seçin veya OK ile orijine yerleştirin", "pick one or two vertices, edges or faces": "bir veya iki köşe noktası, kenar ya da yüz seçin", "render.background": "Sahne arka planı", @@ -1056,6 +1061,7 @@ "ui.heading_offset_plane": "OFSET DÜZLEM", "ui.heading_ok": "OK", "ui.heading_parameters": "PARAMETRELER", + "ui.heading_pattern": "DESEN", "ui.heading_pattern_on_path": "YOL ÜZERİNDE DESEN", "ui.heading_pipe": "BORU", "ui.heading_plane_at_angle": "AÇILI DÜZLEM", diff --git a/assets/locales/uk.json b/assets/locales/uk.json index ce842bcb7..8ed2feab0 100644 --- a/assets/locales/uk.json +++ b/assets/locales/uk.json @@ -597,6 +597,11 @@ "no interference": "немає перетинів", "no joint that moves yet": "ще немає рухомого з'єднання", "no picture": "немає зображення", + "pattern.alignment_2": "Вирівнювання 2", + "pattern.alignment_hint": "Кількість включає оригінал. Центрування розподіляє копії з обох боків; за парної кількості зміна напрямку визначає бік із додатковою копією.", + "pattern.direction_1": "Напрямок 1", + "pattern.direction_2": "Напрямок 2", + "pattern.flip_direction": "Змінити напрямок", "pick a hole to seat it, or OK places it at the origin": "виберіть отвір для посадки, або OK розмістить його в початку координат", "pick one or two vertices, edges or faces": "виберіть одну-дві вершини, ребра або грані", "settings.measure_axis_distances": "Відстані X/Y/Z", @@ -796,6 +801,7 @@ "ui.heading_offset_plane": "ЗСУНУТА ПЛОЩИНА", "ui.heading_ok": "OK", "ui.heading_parameters": "ПАРАМЕТРИ", + "ui.heading_pattern": "МАСИВ", "ui.heading_pattern_on_path": "МАСИВ НА ТРАЄКТОРІЇ", "ui.heading_pipe": "ТРУБА", "ui.heading_plane_at_angle": "ПЛОЩИНА ПІД КУТОМ", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index b4082881d..fc26c8462 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -671,6 +671,11 @@ "no interference": "无干涉", "no joint that moves yet": "尚无运动接头", "no picture": "无图片", + "pattern.alignment_2": "对齐 2", + "pattern.alignment_hint": "数量包含原始图形。居中时副本分布在两侧;数量为偶数时,反转可切换多一个副本的一侧。", + "pattern.direction_1": "方向 1", + "pattern.direction_2": "方向 2", + "pattern.flip_direction": "反转方向", "pick a hole to seat it, or OK places it at the origin": "选择一个孔放置,或单击确定放置在原点", "pick one or two vertices, edges or faces": "选择一个或两个顶点、边或面", "render.background": "场景背景", @@ -1118,6 +1123,7 @@ "ui.heading_offset_plane": "偏移平面", "ui.heading_ok": "确定", "ui.heading_parameters": "参数", + "ui.heading_pattern": "阵列", "ui.heading_pattern_on_path": "路径阵列", "ui.heading_pipe": "管道", "ui.heading_plane_at_angle": "角度平面", diff --git a/crates/doc/src/format/pending/sketch-pattern-directions.rs b/crates/doc/src/format/pending/sketch-pattern-directions.rs new file mode 100644 index 000000000..18314a6bb --- /dev/null +++ b/crates/doc/src/format/pending/sketch-pattern-directions.rs @@ -0,0 +1,5 @@ +//! Sketch linear patterns save two independent live direction-line references and each +//! direction's alignment and reversal. Even centered totals keep the original fixed and use +//! reversal to choose which side receives the extra copy. Older patterns retain their fixed +//! vectors and positive-direction placement through defaulted fields, so no rewrite is needed. +//! The last release refuses this pending format instead of silently losing the references. diff --git a/crates/engine/src/cmd/sketch_modify.rs b/crates/engine/src/cmd/sketch_modify.rs index c8f58afba..43898ad93 100644 --- a/crates/engine/src/cmd/sketch_modify.rs +++ b/crates/engine/src/cmd/sketch_modify.rs @@ -80,20 +80,20 @@ pub static COMMANDS: &[CommandSpec] = &[ .enabled(in_sketch) .params(concat!("entities: [ids], translate?: [dx,dy], angle?: deg, center?: [x,y], copy?: bool; picking a text outline or linked point transforms its whole text source once, and copies remain editable text", created_doc!())), CommandSpec::new("sketch.mirror", "Mirror", mirror) - .at("SKETCH", "CREATE") + .at("SKETCH", "PATTERN") .icon("sketch_mirror") .enabled(in_sketch) .params(concat!("entities: [curve/point ids], line: mirror line id (symmetry constraints are added)", created_doc!())), CommandSpec::new("sketch.pattern.circular", "Circular Pattern", pattern_circular) - .at("SKETCH", "CREATE") + .at("SKETCH", "PATTERN") .icon("sketch_circ_pattern") .enabled(in_sketch) - .params(concat!("entities: [ids], center: [x,y] or point ref, count: 2…500, angle?: total deg (default 360). Adds associative pattern constraints; a coordinate center creates a constrainable point. Returns pattern and center ids. pattern?: existing pattern id to edit (omitted values retained; surviving instance ids retained)", created_doc!())), + .params(concat!("entities: [ids], center: [x,y] or point ref, count: 2…500, angle?: total deg (default 360); alignment?: left|center|right (default right); reversed?: bool (default false). Quantity includes the original. Center balances copies around it; reversed flips the direction and extra side for even totals. Partial arcs span angle with angle/(count-1) spacing; full turns use angle/count. Adds associative pattern constraints; a coordinate center creates a constrainable point. Returns pattern and center ids. pattern?: existing pattern id to edit (omitted values retained; surviving instance ids retained)", created_doc!())), CommandSpec::new("sketch.pattern.rectangular", "Rectangular Pattern", pattern_rect) - .at("SKETCH", "CREATE") + .at("SKETCH", "PATTERN") .icon("sketch_rect_pattern") .enabled(in_sketch) - .params(concat!("entities: [ids], dir?: [x,y] (default x), count, spacing; count2?, spacing2? (perpendicular direction). Adds associative pattern constraints. Returns pattern id. pattern?: existing pattern id to edit (omitted values retained; surviving instance ids retained)", created_doc!())), + .params(concat!("entities: [ids], count, spacing; count2?, spacing2?; direction?, direction2?: sketch line ids (live references); dir?, dir2?: [x,y] vectors (defaults: sketch x, perpendicular to direction 1); alignment?, alignment2?: left|center|right (default right). Signed spacings reverse each direction. reversed?, reversed2?: bool (default false); reverses placement and the extra side of even centered totals. Quantities include the original. Adds associative pattern constraints. Returns pattern id. pattern?: existing pattern id to edit (omitted values retained; surviving instance ids retained)", created_doc!())), ]; const TOL: f64 = 1e-7; @@ -1700,6 +1700,9 @@ fn mirror(s: &mut Session, p: &Value) -> Result { for (o, n) in &map { if o != n { cons.push(add_c(sk, ConstraintKind::Symmetric { p: *o, q: *n, l })?); + } else if !sk.curves.get(l).is_some_and(|curve| curve.kind.point_ids().contains(o)) { + // A shared endpoint must stay on the mirror line as the source changes. + cons.push(add_c(sk, ConstraintKind::PointOnCurve { p: *o, c: l })?); } } for (o, n) in cs.iter().zip(&made) { diff --git a/crates/engine/src/cmd/sketch_pattern.rs b/crates/engine/src/cmd/sketch_pattern.rs index 78fe29de7..d0b445f5f 100644 --- a/crates/engine/src/cmd/sketch_pattern.rs +++ b/crates/engine/src/cmd/sketch_pattern.rs @@ -1,6 +1,6 @@ //! Associative sketch patterns. Editing retains ids at surviving instance indices. -use solidcraft_sketch::{PatternInstance, SketchPattern, SketchPatternKind}; +use solidcraft_sketch::{PatternAlignment, PatternInstance, SketchPattern, SketchPatternKind}; use super::*; @@ -23,9 +23,24 @@ pub(super) fn run(s: &mut Session, p: &Value, circular: bool) -> Result { return Err(bad(cmd, "use the existing pattern's type")); } let defaults = match &old.kind { - SketchPatternKind::Circular { center, count, angle } => json!({"entities":old.entities,"center":center,"count":count,"angle":angle}), - SketchPatternKind::Rectangular { dir, count, spacing, count2, spacing2 } => { - json!({"entities":old.entities,"dir":dir,"count":count,"spacing":spacing,"count2":count2,"spacing2":spacing2}) + SketchPatternKind::Circular { center, count, angle, alignment, reversed } => { + json!({"entities":old.entities,"center":center,"count":count,"angle":angle,"alignment":alignment,"reversed":reversed}) + } + SketchPatternKind::Rectangular { + dir, + dir2, + direction, + direction2, + count, + spacing, + count2, + spacing2, + alignment, + alignment2, + reversed, + reversed2, + } => { + json!({"entities":old.entities,"dir":dir,"dir2":dir2,"direction":direction,"direction2":direction2,"count":count,"spacing":spacing,"count2":count2,"spacing2":spacing2,"alignment":alignment,"alignment2":alignment2,"reversed":reversed,"reversed2":reversed2}) } }; if let (Some(params), Some(defaults)) = (params.as_object_mut(), defaults.as_object()) { @@ -78,10 +93,12 @@ pub(super) fn run(s: &mut Session, p: &Value, circular: bool) -> Result { let id = sk.points.get(center).ok_or_else(|| bad(cmd, "missing center point"))?.id.clone(); let full = (total.abs() - 360.0).abs() < 1e-9; let step = total / if full { n as f64 } else { (n.max(2) - 1) as f64 }; + let alignment = alignment_param(¶ms, "alignment", cmd)?; + let reversed = reversed_param(¶ms, "reversed", cmd)?; ( - SketchPatternKind::Circular { center: id, count: n, angle: total }, + SketchPatternKind::Circular { center: id, count: n, angle: total, alignment, reversed }, Some(center), - (1..n).map(|i| ([i, 0], (step * i as f64).to_radians(), Vec2::ZERO)).collect::>(), + (1..n).map(|i| ([i, 0], (step * alignment.multiplier(i, reversed)).to_radians(), Vec2::ZERO)).collect::>(), ) } else { let spacing = num(¶ms, "spacing").ok_or_else(|| bad(cmd, "`spacing` must be finite"))?; @@ -98,14 +115,49 @@ pub(super) fn run(s: &mut Session, p: &Value, circular: bool) -> Result { Some(value) => vec2(value).and_then(Vec2::normalized).ok_or_else(|| bad(cmd, "`dir` must be a finite nonzero vector"))?, None => Vec2::X, }; + let dir2 = match params.get("dir2") { + Some(value) if !value.is_null() => { + Some(vec2(value).and_then(Vec2::normalized).ok_or_else(|| bad(cmd, "`dir2` must be a finite nonzero vector"))?) + } + _ => None, + }; + let direction = direction_ref(sk, ¶ms, "direction", cmd)?; + let direction2 = direction_ref(sk, ¶ms, "direction2", cmd)?; + let alignment = alignment_param(¶ms, "alignment", cmd)?; + let alignment2 = alignment_param(¶ms, "alignment2", cmd)?; + let reversed = reversed_param(¶ms, "reversed", cmd)?; + let reversed2 = reversed_param(¶ms, "reversed2", cmd)?; + let first = line_direction(sk, direction.as_deref()).unwrap_or(dir); + let second = line_direction(sk, direction2.as_deref()).or(dir2).unwrap_or_else(|| first.perp()); let slots = (0..n) .flat_map(|i| { (0..count2).filter_map(move |j| { - (i != 0 || j != 0).then_some(([i, j], 0.0, dir * (spacing * i as f64) + dir.perp() * (spacing2 * j as f64))) + (i != 0 || j != 0).then_some(( + [i, j], + 0.0, + first * (spacing * alignment.multiplier(i, reversed)) + second * (spacing2 * alignment2.multiplier(j, reversed2)), + )) }) }) .collect(); - (SketchPatternKind::Rectangular { dir, count: n, spacing, count2, spacing2 }, None, slots) + ( + SketchPatternKind::Rectangular { + dir, + dir2, + direction, + direction2, + count: n, + spacing, + count2, + spacing2, + alignment, + alignment2, + reversed, + reversed2, + }, + None, + slots, + ) }; let id = match &old { Some(old) => old.id.clone(), @@ -126,20 +178,28 @@ pub(super) fn run(s: &mut Session, p: &Value, circular: bool) -> Result { if center_id.is_some() && center.is_none() { return Err(bad(cmd, "the center belongs to an instance removed by this edit")); } + if !circular { + // A direction can have belonged to an instance retired above. Resolve it again + // before creating relations so an edit never silently substitutes a vector. + direction_ref(sk, ¶ms, "direction", cmd)?; + direction_ref(sk, ¶ms, "direction2", cmd)?; + } let mut curves = Vec::new(); let mut constraints = Vec::new(); for (index, angle, offset) in slots { + let (base_offset, directions) = linear_displacement(sk, &kind, index, offset); let c = center.and_then(|i| sk.point(i)).unwrap_or(Vec2::ZERO); let transform = |p| rotate(c, angle)(p) + offset; let instance = if let Some(i) = existing.iter().position(|instance| instance.index == index) { let instance = existing.remove(i); for cid in &instance.constraints { if let Some(constraint) = sk.constraints.iter_mut().find(|constraint| constraint.id == *cid) - && let ConstraintKind::PatternPoint { center: slot, angle: a, offset: off, .. } = &mut constraint.kind + && let ConstraintKind::PatternPoint { center: slot, angle: a, offset: off, directions: dirs, .. } = &mut constraint.kind { *slot = center; *a = angle; - *off = offset; + *off = base_offset; + *dirs = directions; } } for (seed, copy) in &instance.points { @@ -155,7 +215,7 @@ pub(super) fn run(s: &mut Session, p: &Value, circular: bool) -> Result { let (made, map) = copy_through(sk, &cs, &ps, &transform, false, &|_| false, 1.0)?; let mut cons = Vec::new(); for (p, q) in &map { - cons.push(add_c(sk, ConstraintKind::PatternPoint { p: *p, q: *q, center, angle, offset })?); + cons.push(add_c(sk, ConstraintKind::PatternPoint { p: *p, q: *q, center, angle, offset: base_offset, directions })?); } for (a, b) in cs.iter().zip(&made) { if matches!(sk.curves.get(*a).map(|c| &c.kind), Some(CurveKind::Circle { .. } | CurveKind::Ellipse { .. })) { @@ -188,3 +248,53 @@ pub(super) fn run(s: &mut Session, p: &Value, circular: bool) -> Result { } Ok(out) } + +fn direction_ref(sk: &Sketch, p: &Value, key: &str, cmd: &str) -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::String(id)) if line_direction(sk, Some(id)).is_some() => Ok(Some(id.clone())), + _ => Err(bad(cmd, format!("`{key}` must reference a nondegenerate sketch line"))), + } +} + +fn alignment_param(p: &Value, key: &str, cmd: &str) -> Result { + p.get(key).map_or(Ok(PatternAlignment::default()), |value| { + serde_json::from_value(value.clone()).map_err(|_| bad(cmd, format!("`{key}` must be left, center or right"))) + }) +} + +fn reversed_param(p: &Value, key: &str, cmd: &str) -> Result { + p.get(key).map_or(Ok(false), |value| serde_json::from_value(value.clone()).map_err(|_| bad(cmd, format!("`{key}` must be true or false")))) +} + +fn line_direction(sk: &Sketch, id: Option<&str>) -> Option { + let Shape::Line { a, b } = sk.shape(sk.curve_index(id?)?)? else { return None }; + (b - a).normalized() +} + +/// Keep sampled vector directions compatible with older designs, while picked lines are +/// solver references. The default second direction follows the first line's perpendicular. +fn linear_displacement(sk: &Sketch, kind: &SketchPatternKind, [i, j]: [usize; 2], fallback: Vec2) -> (Vec2, [Option<(usize, Vec2)>; 2]) { + let SketchPatternKind::Rectangular { dir, dir2, direction, direction2, spacing, spacing2, alignment, alignment2, reversed, reversed2, .. } = kind + else { + return (fallback, [None; 2]); + }; + let mut offset = Vec2::ZERO; + let mut directions = [None; 2]; + let d1 = *spacing * alignment.multiplier(i, *reversed); + let d2 = *spacing2 * alignment2.multiplier(j, *reversed2); + if let Some(l) = direction.as_ref().and_then(|id| sk.curve_index(id)) { + directions[0] = Some((l, Vec2::new(d1, if dir2.is_none() && direction2.is_none() { d2 } else { 0.0 }))); + } else { + offset += *dir * d1; + if dir2.is_none() && direction2.is_none() { + offset += dir.perp() * d2; + } + } + if let Some(l) = direction2.as_ref().and_then(|id| sk.curve_index(id)) { + directions[1] = Some((l, Vec2::new(d2, 0.0))); + } else if let Some(dir2) = dir2 { + offset += *dir2 * d2; + } + (offset, directions) +} diff --git a/crates/engine/src/cmd/sketch_pattern_tests.rs b/crates/engine/src/cmd/sketch_pattern_tests.rs index a00f03f99..0e3a15dfd 100644 --- a/crates/engine/src/cmd/sketch_pattern_tests.rs +++ b/crates/engine/src/cmd/sketch_pattern_tests.rs @@ -4,6 +4,329 @@ fn point(sk: &solidcraft_sketch::Sketch, id: &str) -> Vec2 { sk.point(sk.resolve_point(id).unwrap()).unwrap() } +#[test] +fn circular_centered_six_holes_span_ninety_degrees_and_flip_about_the_original() { + let mut s = new_sketch(); + run(&mut s, "sketch.circle.center", json!({"center":[20,0],"radius":1,"id":"seed"})); + let out = run(&mut s, "sketch.pattern.circular", json!({"entities":["seed"],"center":[0,0],"count":6,"angle":90,"alignment":"center"})); + let copies = ids(&out["curves"]); + let check = |s: &Session, angles: &[f64], seed: Vec2, center: Vec2| { + assert!(point(&sketch(s), "seed.center").dist(seed) < 1e-6); + for (id, angle) in copies.iter().zip(angles) { + let (sin, cos) = angle.to_radians().sin_cos(); + let d = seed - center; + let expected = center + Vec2::new(d.x * cos - d.y * sin, d.x * sin + d.y * cos); + assert!(point(&sketch(s), &format!("{id}.center")).dist(expected) < 1e-6, "angle {angle}"); + } + check_relations(s); + }; + check(&s, &[18., -18., 36., -36., 54.], Vec2::new(20., 0.), Vec2::ZERO); + let before = s.doc.to_json(); + let flipped = run(&mut s, "sketch.pattern.circular", json!({"pattern":out["pattern"],"reversed":true})); + assert_eq!(ids(&flipped["curves"]), copies); + check(&s, &[-18., 18., -36., 36., -54.], Vec2::new(20., 0.), Vec2::ZERO); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.to_json(), before); + run(&mut s, "edit.redo", json!({})); + let mut s = Session { doc: solidcraft_doc::format::read(&s.doc.to_json()).unwrap().into(), active_sketch: s.active_sketch, ..Default::default() }; + s.refresh(); + // Omitting placement settings must retain them after reopening. + run(&mut s, "sketch.pattern.circular", json!({"pattern":out["pattern"],"angle":90})); + run(&mut s, "sketch.constraint.fix", json!({"entities":[out["center"]]})); + run(&mut s, "sketch.drag", json!({"entity":"seed.center","from":[20,0],"to":[25,2]})); + check(&s, &[-18., 18., -36., 36., -54.], Vec2::new(25., 2.), Vec2::ZERO); + run(&mut s, "sketch.constraint.fix", json!({"entities":["seed"]})); + run(&mut s, "sketch.constraint.fix", json!({"entities":[out["center"]],"fixed":false})); + run(&mut s, "sketch.drag", json!({"entity":out["center"],"from":[0,0],"to":[2,3]})); + check(&s, &[-18., 18., -36., 36., -54.], Vec2::new(25., 2.), Vec2::new(2., 3.)); +} + +#[test] +fn circular_alignment_handles_odd_arcs_one_sided_rotation_and_full_turns() { + for (count, angle, alignment, reversed, expected) in [ + (5, 90., "center", false, vec![22.5_f64, -22.5, 45., -45.]), + (3, 90., "right", false, vec![45., 90.]), + (3, 90., "right", true, vec![-45., -90.]), + (3, 90., "left", false, vec![-45., -90.]), + (3, -90., "center", true, vec![45., -45.]), + (6, 360., "center", false, vec![60., -60., 120., -120., 180.]), + (6, 360., "center", true, vec![-60., 60., -120., 120., -180.]), + ] { + let mut s = new_sketch(); + run(&mut s, "sketch.circle.center", json!({"center":[20,0],"radius":1,"id":"seed"})); + let out = run( + &mut s, + "sketch.pattern.circular", + json!({"entities":["seed"],"center":[0,0],"count":count,"angle":angle,"alignment":alignment,"reversed":reversed}), + ); + let mut positions = vec![Vec2::new(20., 0.)]; + for (id, a) in ids(&out["curves"]).iter().zip(expected) { + let pos = point(&sketch(&s), &format!("{id}.center")); + let (sin, cos) = a.to_radians().sin_cos(); + assert!(pos.dist(Vec2::new(20. * cos, 20. * sin)) < 1e-6); + assert!(positions.iter().all(|p| pos.dist(*p) > 1.)); + positions.push(pos); + } + assert_eq!(positions.len(), count); + check_relations(&s); + } +} + +#[test] +fn circular_invalid_alignment_and_flip_roll_back_and_old_saved_defaults_still_load() { + let mut s = new_sketch(); + run(&mut s, "sketch.circle.center", json!({"center":[20,0],"radius":1,"id":"seed"})); + let out = run(&mut s, "sketch.pattern.circular", json!({"entities":["seed"],"center":[0,0],"count":3,"angle":90})); + let before = s.doc.to_json(); + for extra in [json!({"reversed":"true"}), json!({"reversed":null}), json!({"alignment":"unknown"}), json!({"alignment":null})] { + let mut params = json!({"pattern":out["pattern"]}); + params.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + assert!(s.execute("sketch.pattern.circular", ¶ms).is_err(), "{extra}"); + assert_eq!(s.doc.to_json(), before); + } + let mut saved: Value = serde_json::from_str(&before).unwrap(); + let kind = saved["features"][0]["sketch"]["patterns"][0]["kind"].as_object_mut().unwrap(); + kind.remove("alignment"); + kind.remove("reversed"); + let mut reopened = + Session { doc: solidcraft_doc::format::read(&saved.to_string()).unwrap().into(), active_sketch: s.active_sketch, ..Default::default() }; + reopened.refresh(); + run(&mut reopened, "sketch.pattern.circular", json!({"pattern":out["pattern"],"count":3})); + assert!(point(&sketch(&reopened), &format!("{}.center", out["curves"][1].as_str().unwrap())).dist(Vec2::new(0., 20.)) < 1e-6); +} + +#[test] +fn centered_two_direction_grid_keeps_original_fixed_and_follows_live_guides_after_reopen() { + let mut s = new_sketch(); + run(&mut s, "sketch.circle.center", json!({"center":[5,5],"radius":2,"id":"seed"})); + run(&mut s, "sketch.line", json!({"points":[[0,-10],[10,-10]],"ids":["guide1"]})); + run(&mut s, "sketch.line", json!({"points":[[0,-30],[6,-22]],"ids":["guide2"]})); + run(&mut s, "sketch.constraint.fix", json!({"entities":["guide1","guide2"]})); + let out = run( + &mut s, + "sketch.pattern.rectangular", + json!({ + "entities":["seed"],"direction":"guide1","direction2":"guide2", + "count":3,"spacing":20,"count2":3,"spacing2":10,"alignment":"center","alignment2":"center" + }), + ); + let expected = [(11., 13.), (-1., -3.), (25., 5.), (31., 13.), (19., -3.), (-15., 5.), (-9., 13.), (-21., -3.)]; + for (curve, (x, y)) in out["curves"].as_array().unwrap().iter().zip(expected) { + assert!(point(&sketch(&s), &format!("{}.center", curve.as_str().unwrap())).dist(Vec2::new(x, y)) < 1e-6); + } + assert!(point(&sketch(&s), "seed.center").dist(Vec2::new(5., 5.)) < 1e-6); + run(&mut s, "sketch.drag", json!({"entity":"seed.center","from":[5,5],"to":[7,8]})); + run(&mut s, "sketch.constraint.fix", json!({"entities":["seed"]})); + run(&mut s, "sketch.constraint.fix", json!({"entities":["guide2"],"fixed":false})); + run(&mut s, "sketch.constraint.fix", json!({"entities":["guide2.start"]})); + run(&mut s, "sketch.drag", json!({"entity":"guide2.end","from":[6,-22],"to":[8,-24]})); + check_relations(&s); + let far = out["curves"][7].as_str().unwrap(); + assert!(point(&sketch(&s), &format!("{far}.center")).dist(Vec2::new(-21., 2.)) < 1e-6); + let saved = s.doc.to_json(); + let mut s = Session { doc: solidcraft_doc::format::read(&saved).unwrap().into(), active_sketch: s.active_sketch, ..Default::default() }; + s.refresh(); + let before = s.doc.to_json(); + let edited = run(&mut s, "sketch.pattern.rectangular", json!({"pattern":out["pattern"],"alignment":"left","alignment2":"right","count":4})); + assert_eq!(edited["curves"][7], far); + assert!(point(&sketch(&s), &format!("{far}.center")).dist(Vec2::new(-17., 20.)) < 1e-6); + check_relations(&s); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.to_json(), before); +} + +#[test] +fn left_and_right_alignments_are_independent_and_invalid_alignment_values_roll_back() { + let mut s = new_sketch(); + run(&mut s, "sketch.circle.center", json!({"center":[5,5],"radius":2,"id":"seed"})); + let out = run( + &mut s, + "sketch.pattern.rectangular", + json!({ + "entities":["seed"],"count":3,"spacing":20,"count2":2,"spacing2":10,"alignment":"left","alignment2":"right" + }), + ); + let far = out["curves"][4].as_str().unwrap(); + assert!(point(&sketch(&s), &format!("{far}.center")).dist(Vec2::new(-35., 15.)) < 1e-6); + run(&mut s, "sketch.pattern.rectangular", json!({"pattern":out["pattern"],"alignment":"right","alignment2":"left"})); + assert!(point(&sketch(&s), &format!("{far}.center")).dist(Vec2::new(45., -5.)) < 1e-6); + let before = s.doc.to_json(); + for extra in [json!({"reversed":"true"}), json!({"reversed2":null}), json!({"alignment":"unknown"}), json!({"alignment2":null})] { + let mut params = json!({"pattern":out["pattern"]}); + params.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + assert!(s.execute("sketch.pattern.rectangular", ¶ms).is_err(), "{extra}"); + assert_eq!(s.doc.to_json(), before); + } + let mut broken: Value = serde_json::from_str(&before).unwrap(); + broken["features"][0]["sketch"]["patterns"][0]["kind"]["reversed2"] = json!("true"); + assert!(solidcraft_doc::format::read(&broken.to_string()).is_err()); +} + +#[test] +fn even_centered_totals_flip_the_extra_side_independently_and_remain_associative() { + let mut s = new_sketch(); + run(&mut s, "sketch.circle.center", json!({"center":[5,5],"radius":2,"id":"seed"})); + run(&mut s, "sketch.line", json!({"points":[[0,-10],[10,-10]],"ids":["guide1"]})); + run(&mut s, "sketch.line", json!({"points":[[0,-30],[6,-22]],"ids":["guide2"]})); + run(&mut s, "sketch.constraint.fix", json!({"entities":["guide1","guide2"]})); + let out = run( + &mut s, + "sketch.pattern.rectangular", + json!({ + "entities":["seed"],"direction":"guide1","direction2":"guide2", + "count":4,"spacing":20,"count2":2,"spacing2":10,"alignment":"center","alignment2":"center" + }), + ); + let copy_ids = ids(&out["curves"]); + let expected = [(11., 13.), (25., 5.), (31., 13.), (-15., 5.), (-9., 13.), (45., 5.), (51., 13.)]; + for (id, (x, y)) in copy_ids.iter().zip(expected) { + assert!(point(&sketch(&s), &format!("{id}.center")).dist(Vec2::new(x, y)) < 1e-6); + } + let before = s.doc.to_json(); + let flipped = run(&mut s, "sketch.pattern.rectangular", json!({"pattern":out["pattern"],"reversed":true})); + assert_eq!(ids(&flipped["curves"]), copy_ids); + assert!(point(&sketch(&s), &format!("{}.center", copy_ids[6])).dist(Vec2::new(-29., 13.)) < 1e-6); + run(&mut s, "sketch.pattern.rectangular", json!({"pattern":out["pattern"],"reversed2":true})); + assert!(point(&sketch(&s), &format!("{}.center", copy_ids[6])).dist(Vec2::new(-41., -3.)) < 1e-6); + assert!(point(&sketch(&s), "seed.center").dist(Vec2::new(5., 5.)) < 1e-6); + check_relations(&s); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.to_json(), before); + run(&mut s, "edit.redo", json!({})); + run(&mut s, "edit.redo", json!({})); + let mut s = Session { doc: solidcraft_doc::format::read(&s.doc.to_json()).unwrap().into(), active_sketch: s.active_sketch, ..Default::default() }; + s.refresh(); + run(&mut s, "sketch.drag", json!({"entity":"seed.center","from":[5,5],"to":[7,8]})); + assert!(point(&sketch(&s), &format!("{}.center", copy_ids[6])).dist(Vec2::new(-39., 0.)) < 1e-6); + run(&mut s, "sketch.constraint.fix", json!({"entities":["seed"]})); + run(&mut s, "sketch.constraint.fix", json!({"entities":["guide2"],"fixed":false})); + run(&mut s, "sketch.constraint.fix", json!({"entities":["guide2.start"]})); + run(&mut s, "sketch.drag", json!({"entity":"guide2.end","from":[6,-22],"to":[8,-24]})); + assert!(point(&sketch(&s), &format!("{}.center", copy_ids[6])).dist(Vec2::new(-41., 2.)) < 1e-6); + let edited = run(&mut s, "sketch.pattern.rectangular", json!({"pattern":out["pattern"],"spacing":10})); + assert_eq!(ids(&edited["curves"]), copy_ids); + assert!(point(&sketch(&s), &format!("{}.center", copy_ids[6])).dist(Vec2::new(-21., 2.)) < 1e-6); + check_relations(&s); +} + +#[test] +fn two_picked_pattern_lines_remain_live_through_drag_reopen_and_edit() { + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points":[[10,5],[15,5]],"ids":["seed"]})); + run(&mut s, "sketch.line", json!({"points":[[0,-20],[10,-20]],"ids":["dir1"]})); + run(&mut s, "sketch.line", json!({"points":[[0,-40],[6,-32]],"ids":["dir2"]})); + run(&mut s, "sketch.constraint.fix", json!({"entities":["seed","dir1.start","dir2.start"]})); + let out = run( + &mut s, + "sketch.pattern.rectangular", + json!({"entities":["seed"],"direction":"dir1","direction2":"dir2","count":3,"spacing":20,"count2":2,"spacing2":10}), + ); + let copy = out["curves"][0].as_str().unwrap(); + let far = out["curves"][4].as_str().unwrap(); + assert!(point(&sketch(&s), &format!("{copy}.start")).dist(Vec2::new(16.0, 13.0)) < 1e-6); + assert!(point(&sketch(&s), &format!("{far}.start")).dist(Vec2::new(56.0, 13.0)) < 1e-6); + run(&mut s, "sketch.drag", json!({"entity":"dir2.end","from":[6,-32],"to":[8,-34]})); + check_relations(&s); + assert!(point(&sketch(&s), &format!("{copy}.start")).dist(Vec2::new(18.0, 11.0)) < 1e-6); + let saved = s.doc.to_json(); + let mut s = Session { doc: solidcraft_doc::format::read(&saved).unwrap().into(), active_sketch: s.active_sketch, ..Default::default() }; + s.refresh(); + let edited = run(&mut s, "sketch.pattern.rectangular", json!({"pattern":out["pattern"],"count":4,"spacing2":-10})); + assert_eq!(edited["curves"][0], copy); + assert!(point(&sketch(&s), &format!("{copy}.start")).dist(Vec2::new(2.0, -1.0)) < 1e-6); + run(&mut s, "sketch.constraint.fix", json!({"entities":["dir2"]})); + run(&mut s, "sketch.drag", json!({"entity":"dir1.end","from":[10,-20],"to":[0,-10]})); + check_relations(&s); + assert!(point(&sketch(&s), &format!("{far}.start")).dist(Vec2::new(2.0, 39.0)) < 1e-6); + let before = s.doc.to_json(); + run(&mut s, "sketch.delete", json!({"entities":["dir2"]})); + assert!(sketch(&s).patterns.is_empty()); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.to_json(), before); +} + +#[test] +fn mirror_and_both_patterns_keep_selected_line_chains_driven_by_the_source() { + for mode in [0, 1, 2] { + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points":[[10,0],[15,0],[15,5]],"ids":["l1","l2"]})); + run(&mut s, "sketch.line", json!({"points":[[0,-20],[0,20]],"ids":["axis"]})); + run(&mut s, "sketch.constraint.fix", json!({"entities":["axis"]})); + let (cmd, params) = match mode { + 0 => ("sketch.mirror", json!({"entities":["l1","l2"],"line":"axis"})), + 1 => ( + "sketch.pattern.rectangular", + json!({"entities":["l1","l2"],"dir":[1,0],"dir2":[0.6,0.8],"count":2,"spacing":30,"count2":2,"spacing2":10}), + ), + _ => ("sketch.pattern.circular", json!({"entities":["l1","l2"],"center":"origin","count":4})), + }; + let out = run(&mut s, cmd, params); + run(&mut s, "sketch.drag", json!({"entity":"l1.end","from":[15,0],"to":[18,2]})); + check_relations(&s); + let sk = sketch(&s); + let original = point(&sk, "l1.end"); + assert!(original.dist(Vec2::new(18.0, 2.0)) < 1e-6); + let expected = match mode { + 0 => Vec2::new(-original.x, original.y), + 1 => original + Vec2::new(6.0, 8.0), + _ => Vec2::new(-original.y, original.x), + }; + let a = out["curves"][0].as_str().unwrap(); + let b = out["curves"][1].as_str().unwrap(); + // Reflection reverses each curve's traversal; the shared corner is still one point. + let (end, start) = if mode == 0 { ("start", "end") } else { ("end", "start") }; + assert!(point(&sk, &format!("{a}.{end}")).dist(expected) < 1e-6, "{cmd}"); + assert_eq!(sk.resolve_point(&format!("{a}.{end}")), sk.resolve_point(&format!("{b}.{start}"))); + } +} + +#[test] +fn malformed_two_direction_patterns_roll_back_and_saved_references_are_validated() { + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points":[[10,0],[20,0]],"ids":["seed"]})); + run(&mut s, "sketch.circle.center", json!({"center":[0,0],"radius":2,"id":"circle"})); + let before = s.doc.to_json(); + for extra in [ + json!({"dir2":[0,0]}), + json!({"dir2":[1e308,1e308]}), + json!({"direction2":"missing"}), + json!({"direction":"circle"}), + json!({"direction2":42}), + ] { + let mut params = json!({"entities":["seed"],"count":2,"spacing":10,"count2":2}); + params.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + assert!(s.execute("sketch.pattern.rectangular", ¶ms).is_err(), "{extra}"); + assert_eq!(s.doc.to_json(), before); + } + run(&mut s, "sketch.pattern.rectangular", json!({"entities":["seed"],"direction":"seed","count":2,"spacing":10})); + let saved: Value = serde_json::from_str(&s.doc.to_json()).unwrap(); + for invalid in [json!([[usize::MAX, [10, 0]], null]), json!([[0, [1e308, 0]], null])] { + let mut broken = saved.clone(); + let constraint = + broken["features"][0]["sketch"]["constraints"].as_array_mut().unwrap().iter_mut().find(|c| c["type"] == "pattern_point").unwrap(); + constraint["directions"] = invalid; + assert!(solidcraft_doc::format::read(&broken.to_string()).is_err()); + } +} + +#[test] +fn mirrored_chain_endpoints_on_the_axis_remain_on_it_during_source_edits() { + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points":[[0,5],[10,5],[10,15],[0,15]],"ids":["a","b","c"]})); + run(&mut s, "sketch.line", json!({"points":[[0,-10],[0,30]],"ids":["axis"]})); + run(&mut s, "sketch.constraint.fix", json!({"entities":["axis"]})); + let out = run(&mut s, "sketch.mirror", json!({"entities":["a","b","c"],"line":"axis"})); + let copy = out["curves"][0].as_str().unwrap(); + assert_eq!(sketch(&s).resolve_point("a.start"), sketch(&s).resolve_point(&format!("{copy}.end"))); + run(&mut s, "sketch.drag", json!({"entity":"a.start","from":[0,5],"to":[4,8]})); + assert!(point(&sketch(&s), "a.start").x.abs() < 1e-6); + run(&mut s, "sketch.drag", json!({"entity":"b.start","from":[10,5],"to":[13,8]})); + let original = point(&sketch(&s), "b.start"); + assert!(point(&sketch(&s), &format!("{copy}.start")).dist(Vec2::new(-original.x, original.y)) < 1e-6); + check_relations(&s); +} + fn check_relations(s: &Session) { let sk = sketch(s); for (i, constraint) in sk.constraints.iter().enumerate() { @@ -11,6 +334,38 @@ fn check_relations(s: &Session) { } } +#[test] +fn default_second_direction_follows_the_first_line_and_legacy_vectors_keep_their_grid() { + let mut s = new_sketch(); + run(&mut s, "sketch.circle.center", json!({"center":[5,5],"radius":2,"id":"seed"})); + run(&mut s, "sketch.line", json!({"points":[[0,-10],[10,-10]],"ids":["guide"]})); + run(&mut s, "sketch.constraint.fix", json!({"entities":["seed","guide.start"]})); + let out = + run(&mut s, "sketch.pattern.rectangular", json!({"entities":["seed"],"direction":"guide","count":2,"spacing":10,"count2":2,"spacing2":20})); + run(&mut s, "sketch.drag", json!({"entity":"guide.end","from":[10,-10],"to":[0,0]})); + let far = out["curves"][2].as_str().unwrap(); + assert!(point(&sketch(&s), &format!("{far}.center")).dist(Vec2::new(-15.0, 15.0)) < 1e-6); + check_relations(&s); + + let mut s = new_sketch(); + run(&mut s, "sketch.circle.center", json!({"center":[5,5],"radius":2,"id":"seed"})); + run(&mut s, "sketch.pattern.rectangular", json!({"entities":["seed"],"dir":[0,1],"count":2,"spacing":10,"count2":2,"spacing2":20})); + let mut saved: Value = serde_json::from_str(&s.doc.to_json()).unwrap(); + saved["format"] = json!("solidcraft/21"); + let sk = &mut saved["features"][0]["sketch"]; + for c in sk["constraints"].as_array_mut().unwrap() { + c.as_object_mut().unwrap().remove("directions"); + } + let settings = sk["patterns"][0]["kind"].as_object_mut().unwrap(); + for key in ["dir2", "direction", "direction2", "alignment", "alignment2", "reversed", "reversed2"] { + settings.remove(key); + } + let doc = solidcraft_doc::format::read(&saved.to_string()).unwrap(); + let sk = doc.sketch(s.active_sketch.unwrap()).unwrap(); + assert!(point(sk, "c3.center").dist(Vec2::new(-15.0, 15.0)) < 1e-6); + assert_eq!(doc.format, solidcraft_doc::format::format_string(solidcraft_doc::format::FORMAT)); +} + #[test] fn circular_pattern_keeps_seed_copy_and_center_related_during_drags() { let mut s = new_sketch(); diff --git a/crates/sketch/src/lib.rs b/crates/sketch/src/lib.rs index 8b08f97fa..75e519b1e 100644 --- a/crates/sketch/src/lib.rs +++ b/crates/sketch/src/lib.rs @@ -52,7 +52,7 @@ pub use model::{ }; pub use offset::OffsetChain; pub use offset_topology::{OffsetCreated, OffsetRole, OffsetRoleFlags, OffsetRoleKind, OffsetTopology}; -pub use pattern::{PatternInstance, SketchPattern, SketchPatternKind}; +pub use pattern::{PatternAlignment, PatternInstance, SketchPattern, SketchPatternKind}; pub use periodic::periodic_beziers; pub use profiles::{ CurvePick, Profile, distinct_curves, find_drawn_profiles, find_profiles, merge_regions, profile_at_point, profile_by_curves, diff --git a/crates/sketch/src/model.rs b/crates/sketch/src/model.rs index 042d968b8..493df7b01 100644 --- a/crates/sketch/src/model.rs +++ b/crates/sketch/src/model.rs @@ -189,6 +189,9 @@ pub enum ConstraintKind { center: Option, angle: f64, offset: Vec2, + /// Displacements along and perpendicular to live sketch lines (at most two). + #[serde(default)] + directions: [Option<(usize, Vec2)>; 2], }, /// The independent radius of a patterned circle or ellipse follows its seed. PatternRadius { @@ -423,7 +426,9 @@ impl ConstraintKind { pub fn indices(&self) -> (Vec, Vec) { use ConstraintKind::*; match *self { - PatternPoint { p, q, center, .. } => (vec![p, q].into_iter().chain(center).collect(), vec![]), + PatternPoint { p, q, center, directions, .. } => { + (vec![p, q].into_iter().chain(center).collect(), directions.into_iter().flatten().map(|(l, _)| l).collect()) + } PatternRadius { a, b } => (vec![], vec![a, b]), Coincident { p, q } | HorizontalPoints { p, q } | VerticalPoints { p, q } => (vec![p, q], vec![]), Distance { p, q, .. } | DistanceX { p, q, .. } | DistanceY { p, q, .. } => (vec![p, q], vec![]), @@ -458,12 +463,15 @@ impl ConstraintKind { None => ok2 = false, }; match self { - PatternPoint { p, q, center, .. } => { + PatternPoint { p, q, center, directions, .. } => { fp(p); fp(q); if let Some(c) = center { fp(c); } + for (l, _) in directions.iter_mut().flatten() { + fc(l); + } } PatternRadius { a, b } => { fc(a); @@ -848,7 +856,13 @@ impl Sketch { let need_line = |i: usize| if is_line(i) { Ok(()) } else { Err(SketchError::WrongKind(name(i), "needs a line".into())) }; let need_round = |i: usize| if is_round(i) { Ok(()) } else { Err(SketchError::WrongKind(name(i), "needs a circle or arc".into())) }; match *k { - PatternPoint { p, q, angle, offset, .. } => { + PatternPoint { p, q, angle, offset, directions, .. } => { + for (l, distance) in directions.into_iter().flatten() { + need_line(l)?; + if !distance.x.is_finite() || !distance.y.is_finite() || distance.x.abs() > MAX_COORD || distance.y.abs() > MAX_COORD { + return Err(SketchError::Invalid("invalid pattern direction displacement".into())); + } + } if p == q || !angle.is_finite() || angle.abs() > std::f64::consts::TAU diff --git a/crates/sketch/src/pattern.rs b/crates/sketch/src/pattern.rs index ac9d3e181..79cf990b1 100644 --- a/crates/sketch/src/pattern.rs +++ b/crates/sketch/src/pattern.rs @@ -5,11 +5,62 @@ use solidcraft_geom::Vec2; use crate::{CurveKind, Sketch, SketchError}; +/// Placement relative to the original, along a pattern direction's oriented line. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum PatternAlignment { + Left, + Center, + #[default] + Right, +} + +impl PatternAlignment { + /// Slot zero is always the original. Center alternates sides to retain stable copy ids. + pub fn multiplier(self, index: usize, reversed: bool) -> f64 { + let value = match self { + Self::Left => -(index as f64), + Self::Right => index as f64, + Self::Center if index.is_multiple_of(2) => -((index / 2) as f64), + Self::Center => index.div_ceil(2) as f64, + }; + if reversed { -value } else { value } + } +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(tag = "type", rename_all = "snake_case")] pub enum SketchPatternKind { - Circular { center: String, count: usize, angle: f64 }, - Rectangular { dir: Vec2, count: usize, spacing: f64, count2: usize, spacing2: f64 }, + Circular { + center: String, + count: usize, + angle: f64, + #[serde(default)] + alignment: PatternAlignment, + #[serde(default)] + reversed: bool, + }, + Rectangular { + dir: Vec2, + #[serde(default)] + dir2: Option, + #[serde(default)] + direction: Option, + #[serde(default)] + direction2: Option, + count: usize, + spacing: f64, + count2: usize, + spacing2: f64, + #[serde(default)] + alignment: PatternAlignment, + #[serde(default)] + alignment2: PatternAlignment, + #[serde(default)] + reversed: bool, + #[serde(default)] + reversed2: bool, + }, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -37,6 +88,8 @@ impl SketchPattern { .iter() .any(|instance| instance.curves.iter().any(|id| id == entity) || instance.points.iter().any(|(_, id)| id == entity)) || matches!(&self.kind, SketchPatternKind::Circular { center, .. } if center == entity) + || matches!(&self.kind, SketchPatternKind::Rectangular { direction, direction2, .. } + if direction.as_deref() == Some(entity) || direction2.as_deref() == Some(entity)) } } @@ -53,7 +106,14 @@ impl Sketch { continue; }; match kind { - crate::ConstraintKind::PatternPoint { p, q, center, angle, offset } => { + crate::ConstraintKind::PatternPoint { p, q, center, angle, mut offset, directions } => { + for (l, distance) in directions.into_iter().flatten() { + if let Some(crate::Shape::Line { a, b }) = self.shape(l) + && let Some(u) = (b - a).normalized() + { + offset += u * distance.x + u.perp() * distance.y; + } + } let Some(seed) = self.point(p) else { continue }; let c = center.and_then(|c| self.point(c)).unwrap_or(Vec2::ZERO); let d = seed - c; @@ -95,6 +155,8 @@ impl Sketch { .filter(|pattern| { pattern.entities.iter().any(|id| !curves.contains(id.as_str()) && !points.contains(id.as_str())) || matches!(&pattern.kind, SketchPatternKind::Circular { center, .. } if !points.contains(center.as_str())) + || matches!(&pattern.kind, SketchPatternKind::Rectangular { direction, direction2, .. } + if direction.iter().chain(direction2).any(|id| !curves.contains(id.as_str()))) || pattern.instances.iter().any(|instance| { instance.curves.iter().any(|id| !curves.contains(id.as_str())) || instance.points.iter().any(|(p, q)| !points.contains(p.as_str()) || !points.contains(q.as_str())) @@ -165,10 +227,10 @@ impl Sketch { let valid_count = |n| (1..=500).contains(&n); let finite = |v: f64| v.is_finite() && v.abs() <= crate::MAX_COORD; let valid = match &pattern.kind { - SketchPatternKind::Circular { count, angle, center } => { + SketchPatternKind::Circular { count, angle, center, .. } => { valid_count(*count) && angle.is_finite() && angle.abs() > 1e-9 && angle.abs() <= 360.0 && self.resolve_point(center).is_some() } - SketchPatternKind::Rectangular { count, count2, spacing, spacing2, dir } => { + SketchPatternKind::Rectangular { count, count2, spacing, spacing2, dir, dir2, direction, direction2, .. } => { valid_count(*count) && valid_count(*count2) && count.checked_mul(*count2).is_some_and(|n| n <= 500) @@ -177,6 +239,10 @@ impl Sketch { && finite(dir.x) && finite(dir.y) && (dir.len() - 1.0).abs() < 1e-6 + && dir2.is_none_or(|d| finite(d.x) && finite(d.y) && (d.len() - 1.0).abs() < 1e-6) + && direction.iter().chain(direction2).all(|id| { + self.curve_index(id).is_some_and(|l| matches!(self.curves.get(l).map(|c| &c.kind), Some(CurveKind::Line { .. }))) + }) } }; if !valid { diff --git a/crates/sketch/src/solver.rs b/crates/sketch/src/solver.rs index b7f6b0938..360b4c33a 100644 --- a/crates/sketch/src/solver.rs +++ b/crates/sketch/src/solver.rs @@ -400,7 +400,12 @@ fn line_dist(p: Vec2, a: Vec2, b: Vec2) -> f64 { fn residuals(s: &State, k: &ConstraintKind, out: &mut Vec) { use ConstraintKind::*; match *k { - PatternPoint { p, q, center, angle, offset } => { + PatternPoint { p, q, center, angle, mut offset, directions } => { + for (l, distance) in directions.into_iter().flatten() { + let (a, b) = s.line(l); + let u = (b - a).normalized().unwrap_or(Vec2::ZERO); + offset += u * distance.x + u.perp() * distance.y; + } let c = center.map(|c| s.p(c)).unwrap_or(Vec2::ZERO); let d = s.p(p) - c; let (sin, cos) = angle.sin_cos(); @@ -775,7 +780,9 @@ fn block_refs(sk: &Sketch, b: &Block) -> Vec { Block::Closure { a, b } => vec![P(*a), P(*b)], Block::Arc { c, a, b } => vec![P(*c), P(*a), P(*b)], Block::User(_, k) => match **k { - PatternPoint { p, q, center, .. } => vec![P(p), P(q)].into_iter().chain(center.map(P)).collect(), + PatternPoint { p, q, center, directions, .. } => { + vec![P(p), P(q)].into_iter().chain(center.map(P)).chain(directions.into_iter().flatten().map(|(l, _)| L(l))).collect() + } PatternRadius { a, b } => vec![C(a), C(b)], Coincident { p, q } | HorizontalPoints { p, q } diff --git a/crates/ui-egui/src/browser.rs b/crates/ui-egui/src/browser.rs index e2e69568e..39df45a20 100644 --- a/crates/ui-egui/src/browser.rs +++ b/crates/ui-egui/src/browser.rs @@ -1531,12 +1531,17 @@ fn entry_row( acts: &mut Actions, ) { app.tree.order.push(e.row_key.clone()); + let pattern_sketch = + (folder == "sketches").then(|| e.key.parse::().ok()).flatten().filter(|id| crate::sketch_pattern_tree::has_patterns(app, *id)); + 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 r = draw_row( ui, ui.id().with(("item", &e.row_key)), &Row { depth, + fold: pattern_sketch.map(|_| patterns_open), eye: Some(e.visible), icon: e.icon, label: &e.label, @@ -1548,6 +1553,9 @@ fn entry_row( ..Default::default() }, ); + if r.fold { + toggle(app, &pattern_key, true); + } if folder == "bodies" && app.tree.reveal.as_deref() == Some(e.key.as_str()) && let Some(rect) = r.rect @@ -1587,6 +1595,9 @@ fn entry_row( } acts.menu = Some((p, t)); } + if let Some(sketch) = pattern_sketch.filter(|_| patterns_open) { + crate::sketch_pattern_tree::rows(app, ui, sketch, depth + 1, "browser", path.map(|path| (comp, path))); + } let Some(resp) = &r.resp else { return }; // Drag: the selected items of this folder when this one is selected, else just this one. if resp.drag_started() && !r.on_control { diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 95929af31..282308815 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -494,7 +494,7 @@ fn value_box(ui: &mut egui::Ui, label: &str, value: &mut String, at: Pos2, selec crate::frame::area(egui::Id::new("sc_canvas_area")).fixed_pos(at).order(egui::Order::Foreground).show(ui.ctx(), |ui| { egui::Frame::popup(ui.style()).inner_margin(egui::Margin::symmetric(6, 3)).show(ui, |ui| { ui.horizontal(|ui| { - ui.label(egui::RichText::new(label).color(t.text_dim).size(11.5)); + ui.label(egui::RichText::new(crate::i18n::tr_label(label)).color(t.text_dim).size(11.5)); let r = ui.add(egui::TextEdit::singleline(value).id(id).desired_width(72.0)); crate::params_dialog::complete(ui, &r, value); if select_all { diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 3f264c7e8..33bba37f6 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -819,7 +819,8 @@ impl Dialog { /// Dialogs holding a table get the wide limit. pub fn is_wide(&self) -> bool { - matches!(self.kind, Kind::Params { .. }) || matches!(&self.kind, Kind::Motion(k) if k.wide()) + matches!(self.kind, Kind::Params { .. } | Kind::SketchModify(crate::sketch_modify_ui::Mod::PatternRect { .. })) + || matches!(&self.kind, Kind::Motion(k) if k.wide()) } pub fn wants_picks(&self) -> bool { @@ -1609,6 +1610,10 @@ fn selection_label(s: &Session, item: &Sel) -> String { /// Selection input rows: label, "N selected" (or a hint) and a clear button; clicking a row /// makes it the active input. fn input_rows(d: &mut Dialog, ui: &mut egui::Ui, s: &Session) { + input_rows_range(d, ui, s, 0..d.inputs.len()); +} + +fn input_rows_range(d: &mut Dialog, ui: &mut egui::Ui, s: &Session, range: std::ops::Range) { // Edit Text shows its Path input among its own rows. if matches!(d.kind, Kind::Text(_)) { return; @@ -1616,7 +1621,7 @@ fn input_rows(d: &mut Dialog, ui: &mut egui::Ui, s: &Session) { let t = Tokens::get(); let mut clear: Option = None; let mut activate: Option = None; - for (i, inp) in d.inputs.iter().enumerate() { + for (i, inp) in d.inputs.iter().enumerate().skip(range.start).take(range.end.saturating_sub(range.start)) { row_label(ui, inp.label); ui.horizontal(|ui| { let active = i == d.active; @@ -1685,6 +1690,87 @@ fn input_rows(d: &mut Dialog, ui: &mut egui::Ui, s: &Session) { } } +/// Each live reference sits with the independent values it drives. +fn rectangular_pattern_rows(d: &mut Dialog, ui: &mut egui::Ui, session: &Session) -> bool { + use crate::sketch_modify_ui::Mod; + use solidcraft_engine::sketch::PatternAlignment; + let mut enter = false; + ui.vertical(|ui| { + ui.label(tr("dialog.selection_guidance")); + egui::Grid::new("pattern_source").spacing(vec2(10.0, 8.0)).show(ui, |ui| input_rows_range(d, ui, session, 0..1)); + ui.separator(); + ui.columns(2, |columns| { + for (index, ui) in columns.iter_mut().enumerate() { + ui.strong(tr(if index == 0 { "Direction 1" } else { "Direction 2" })); + egui::Grid::new(("pattern_direction", index)).spacing(vec2(8.0, 8.0)).show(ui, |ui| { + input_rows_range(d, ui, session, index + 1..index + 2); + let Kind::SketchModify(Mod::PatternRect { count, spacing, count2, spacing2, alignment, alignment2, reversed, reversed2 }) = + &mut d.kind + else { + return; + }; + let (count, spacing, alignment, reversed, count_label, spacing_label, alignment_label) = if index == 0 { + (count, spacing, alignment, reversed, "Quantity", "Spacing", "Alignment") + } else { + (count2, spacing2, alignment2, reversed2, "Quantity 2", "Spacing 2", "Alignment 2") + }; + row_label(ui, count_label); + enter |= field(ui, count); + ui.end_row(); + row_label(ui, spacing_label); + enter |= field(ui, spacing); + ui.end_row(); + row_label(ui, alignment_label); + ui.horizontal(|ui| { + pattern_toggle(ui, alignment_label, "Flip direction", "pattern_flip", reversed); + let mut centered = *alignment == PatternAlignment::Center; + pattern_toggle(ui, alignment_label, "Center", "pattern_center", &mut centered); + *alignment = if centered { PatternAlignment::Center } else { PatternAlignment::Right }; + }); + ui.end_row(); + }); + } + }); + ui.small(tr("Counts include the original. Center balances copies; Flip chooses the extra side for even totals.")); + }); + ui.end_row(); + enter +} + +pub(crate) fn pattern_toggle(ui: &mut egui::Ui, row: &str, label: &str, icon: &str, selected: &mut bool) { + let response = ui.add(egui::Button::new("").selected(*selected).min_size(vec2(28.0, 24.0))); + let t = Tokens::get(); + crate::icons::paint(ui.painter(), response.rect.shrink(3.0), icon, t.icon, t.icon_fill, t.accent); + response.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Button, true, *selected, tr(label))); + crate::scenario::publish_handle(&format!("dialog:{row}:{label}"), response.rect.center()); + if response.on_hover_text(tr(label)).clicked() { + *selected = !*selected; + } +} + +fn error_rows(app: &mut SolveApp, ctx: &egui::Context, d: &mut Dialog, ui: &mut egui::Ui, full_width: bool) { + if matches!(d.kind, Kind::SketchModify(_)) + && d.previews() + && let Err(error) = apply_commands(app, d) + { + d.refuse(app, error); + } + if let Some(error) = d.error.as_ref().or(app.preview.error.as_ref()).cloned() { + if !full_width { + row_label(ui, ""); + } + ui.vertical(|ui| { + ui.add(egui::Label::new(RichText::new(error.as_str()).color(Tokens::get().error)).wrap()); + let response = ui.button("Create Issue…"); + crate::scenario::publish_handle("dialog:create_issue", response.rect.center()); + if response.clicked() { + crate::issue_report::begin(app, ctx, Some(d), Some(&error)); + } + }); + ui.end_row(); + } +} + /// Width limits of a docked dialog: shrink-wrapped to its content within these. use crate::frame::{DIALOG_MAX_W, DIALOG_MIN_W, DIALOG_WIDE_MAX_W}; /// Width of value fields and choice boxes in a dialog. @@ -1998,6 +2084,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { let mut cancel = false; let mut enter = false; let wide = d.is_wide(); + let pattern_columns = matches!(d.kind, Kind::SketchModify(crate::sketch_modify_ui::Mod::PatternRect { .. })); let raw_title = title(&d.kind); let heading = if d.editing.is_some() { crate::i18n::format("dialog.edit_title", &[("title", tr(raw_title))]) } else { tr(raw_title).to_string() }; let frame = crate::frame::dock_frame(ctx, side); @@ -2027,7 +2114,13 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { // Long texts (errors, notes) wrap instead of widening the dialog. ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Wrap); let margin = horizontal_frame; - let min_w = if wide { 480.0 } else { DIALOG_MIN_W } - margin; + let min_w = if pattern_columns { + 540.0 + } else if wide { + 480.0 + } else { + DIALOG_MIN_W + } - margin; ui.set_min_width(min_w); ui.set_max_width(if wide { DIALOG_WIDE_MAX_W } else { DIALOG_MAX_W } - margin); // Rows that end at the right edge line up with last frame's content width. @@ -2081,7 +2174,12 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { if let Kind::Motion(k @ crate::dialogs_motion::Mo::Configurations { .. }) = &mut d.kind { enter |= crate::dialogs_motion::rows(app, ui, k, &mut d.inputs); } - egui::Grid::new("sc_dialog_grid").num_columns(2).spacing(vec2(10.0, 8.0)).show(ui, |ui| { + egui::Grid::new("sc_dialog_grid").num_columns(if pattern_columns { 1 } else { 2 }).spacing(vec2(10.0, 8.0)).show(ui, |ui| { + if pattern_columns { + enter |= rectangular_pattern_rows(&mut d, ui, &app.session); + error_rows(app, ctx, &mut d, ui, true); + return; + } if matches!(&d.kind, Kind::Motion(crate::dialogs_motion::Mo::Configurations { .. })) { return; } @@ -2798,24 +2896,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { } } } - if matches!(d.kind, Kind::SketchModify(_)) - && d.previews() - && let Err(error) = apply_commands(app, &d) - { - d.refuse(app, error); - } - if let Some(e) = d.error.as_ref().or(app.preview.error.as_ref()).cloned() { - row_label(ui, ""); - ui.vertical(|ui| { - ui.add(egui::Label::new(RichText::new(e.as_str()).color(t.error)).wrap()); - let response = ui.button("Create Issue…"); - crate::scenario::publish_handle("dialog:create_issue", response.rect.center()); - if response.clicked() { - crate::issue_report::begin(app, ctx, Some(&d), Some(&e)); - } - }); - ui.end_row(); - } + error_rows(app, ctx, &mut d, ui, false); }); }); ui.add_space(6.0); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 6a5bf6b40..f09b2e48b 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -148,6 +148,7 @@ pub mod sketch_modify_ui; #[cfg(test)] mod sketch_modify_ui_tests; pub mod sketch_palette; +mod sketch_pattern_tree; pub(crate) mod sketch_text; mod sketch_text_handles; mod sketch_text_move; diff --git a/crates/ui-egui/src/sketch_guidance_ui_tests.rs b/crates/ui-egui/src/sketch_guidance_ui_tests.rs index 38389e340..88c8cd3ab 100644 --- a/crates/ui-egui/src/sketch_guidance_ui_tests.rs +++ b/crates/ui-egui/src/sketch_guidance_ui_tests.rs @@ -64,6 +64,8 @@ fn sketch_dialog_mirror_toggles_clears_references_previews_and_cancels() { #[test] fn sketch_dialog_patterns_update_counts_and_place_an_unsnapped_centre() { let mut h = fixture(); + // Keep the picked geometry clear of the two-column rectangular-pattern form. + step(&mut h, json!({"call":"ui.camera","params":{"target":[-60,0,0],"distance":120}})); step(&mut h, json!({"start":"sketch.pattern.rectangular"})); pick(&mut h, [-22.5, 10.0], false); if let crate::dialogs::Kind::SketchModify(Mod::PatternRect { count, count2, .. }) = &mut h.app.dialog.as_mut().unwrap().kind { @@ -78,7 +80,7 @@ fn sketch_dialog_patterns_update_counts_and_place_an_unsnapped_centre() { pick(&mut h, [-22.5, 10.0], false); step(&mut h, json!({"call":"ui.dialogInput","params":{"index":1}})); pick(&mut h, [-40.0, -20.0], false); - if let crate::dialogs::Kind::SketchModify(Mod::PatternCirc { count, angle }) = &mut h.app.dialog.as_mut().unwrap().kind { + if let crate::dialogs::Kind::SketchModify(Mod::PatternCirc { count, angle, .. }) = &mut h.app.dialog.as_mut().unwrap().kind { *count = "4".into(); *angle = "180 deg".into(); } diff --git a/crates/ui-egui/src/sketch_modify_ui.rs b/crates/ui-egui/src/sketch_modify_ui.rs index 8de84bed4..53f5e9739 100644 --- a/crates/ui-egui/src/sketch_modify_ui.rs +++ b/crates/ui-egui/src/sketch_modify_ui.rs @@ -28,9 +28,10 @@ use serde_json::{Map, Value, json}; use solidcraft_engine::Sel; use solidcraft_engine::doc::expr::Kind as ValueKind; use solidcraft_engine::geom::{Vec2, Vec3}; +use solidcraft_engine::sketch::PatternAlignment; use crate::SolveApp; -use crate::dialogs::{CHAMFER_TYPES, Dialog, Kind, check, field, icon_choice, row_label}; +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::viewport::{Hit, Proj}; @@ -76,11 +77,20 @@ pub enum Mod { /// carries the copy flag, so the Create Copy row needs no engine change. Move { x: String, y: String, angle: String, copy: bool }, /// `sketch.pattern.rectangular`: how many instances along the picked direction and how far - /// apart, then the same along the perpendicular direction the command derives from it. - PatternRect { count: String, spacing: String, count2: String, spacing2: String }, + /// apart, then the same along a second picked direction (perpendicular by default). + PatternRect { + count: String, + spacing: String, + count2: String, + spacing2: String, + alignment: PatternAlignment, + alignment2: PatternAlignment, + reversed: bool, + reversed2: bool, + }, /// `sketch.pattern.circular`: how many instances around the picked centre, and the total /// angle they span. - PatternCirc { count: String, angle: String }, + PatternCirc { count: String, angle: String, alignment: PatternAlignment, reversed: bool }, /// `sketch.fillet` and the three `sketch.chamfer.*` commands. `chamfer` chooses between a /// fillet and a chamfer and never changes while the window is open; `ctype` chooses which /// of the three chamfer commands runs (0 equal distance, 1 two distances, 2 distance and @@ -132,7 +142,11 @@ fn inputs(k: &Mod) -> Vec { Mod::Move { .. } => vec![SelInput::new("Entities", CURVES | SKETCH_POINTS, true), SelInput::new("Center", SKETCH_POINTS, false)], // The direction is optional: `sketch.pattern.rectangular` documents sketch x as its // default, the way the engine reads it. - Mod::PatternRect { .. } => vec![SelInput::new("Entities", CURVES | SKETCH_POINTS, true), SelInput::new("Direction", AXES, false)], + Mod::PatternRect { .. } => vec![ + SelInput::new("Entities", CURVES | SKETCH_POINTS, true), + SelInput::new("Direction", AXES, false), + SelInput::new("Direction 2", AXES, false), + ], // The centre is required: `sketch.pattern.circular` has no default for it. Mod::PatternCirc { .. } => vec![SelInput::new("Entities", CURVES | SKETCH_POINTS, true), SelInput::new("Center", SKETCH_POINTS, false)], // A fillet rounds any number of corners to one radius (`points`). Each chamfer command @@ -157,8 +171,19 @@ pub fn start(_app: &SolveApp, id: &str) -> Option<(Kind, Vec)> { "sketch.offset" => Mod::Offset { distance: "2 mm".into(), distance2: "2 mm".into(), mode: 0, chain: true, flip: false }, "sketch.mirror" => Mod::Mirror, "sketch.move" => Mod::Move { x: "0 mm".into(), y: "0 mm".into(), angle: "0 deg".into(), copy: false }, - "sketch.pattern.rectangular" => Mod::PatternRect { count: "3".into(), spacing: "20 mm".into(), count2: "1".into(), spacing2: "20 mm".into() }, - "sketch.pattern.circular" => Mod::PatternCirc { count: "6".into(), angle: "360 deg".into() }, + "sketch.pattern.rectangular" => Mod::PatternRect { + count: "3".into(), + spacing: "20 mm".into(), + count2: "1".into(), + spacing2: "20 mm".into(), + alignment: PatternAlignment::Right, + alignment2: PatternAlignment::Right, + reversed: false, + reversed2: false, + }, + "sketch.pattern.circular" => { + Mod::PatternCirc { count: "6".into(), angle: "360 deg".into(), alignment: PatternAlignment::Right, reversed: false } + } "sketch.fillet" => corner(false, 0), "sketch.chamfer.equal_distance" => corner(true, 0), "sketch.chamfer.two_distance" => corner(true, 1), @@ -188,12 +213,21 @@ pub fn edit_pattern(app: &mut SolveApp, id: &str) -> bool { let Some(sk) = state.sketch(sid).map(|s| &s.sketch) else { return false }; let Some(pattern) = sk.patterns.iter().find(|p| p.id == id) else { return false }; let kind = match &pattern.kind { - SketchPatternKind::Circular { count, angle, .. } => Mod::PatternCirc { count: count.to_string(), angle: format!("{angle} deg") }, - SketchPatternKind::Rectangular { count, spacing, count2, spacing2, .. } => Mod::PatternRect { + SketchPatternKind::Circular { count, angle, alignment, reversed, .. } => Mod::PatternCirc { + count: count.to_string(), + angle: format!("{angle} deg"), + alignment: if *alignment == PatternAlignment::Left { PatternAlignment::Right } else { *alignment }, + reversed: *reversed ^ (*alignment == PatternAlignment::Left), + }, + SketchPatternKind::Rectangular { count, spacing, count2, spacing2, alignment, alignment2, reversed, reversed2, .. } => Mod::PatternRect { count: count.to_string(), spacing: format!("{spacing} mm"), count2: count2.to_string(), spacing2: format!("{spacing2} mm"), + alignment: if *alignment == PatternAlignment::Left { PatternAlignment::Right } else { *alignment }, + alignment2: if *alignment2 == PatternAlignment::Left { PatternAlignment::Right } else { *alignment2 }, + reversed: *reversed ^ (*alignment == PatternAlignment::Left), + reversed2: *reversed2 ^ (*alignment2 == PatternAlignment::Left), }, }; let mut dialog = Dialog::new(Kind::SketchModify(kind.clone()), inputs(&kind)); @@ -210,8 +244,16 @@ pub fn edit_pattern(app: &mut SolveApp, id: &str) -> bool { input.items = vec![Sel::SketchPoint { id: center.clone() }]; } } - SketchPatternKind::Rectangular { dir, .. } => { + SketchPatternKind::Rectangular { dir, dir2, direction, direction2, .. } => { dialog.extra.insert("dir".into(), json!(dir)); + dialog.extra.insert("dir2".into(), json!(dir2)); + for (index, id) in [(1, direction), (2, direction2)] { + if let Some(id) = id + && let Some(input) = dialog.inputs.get_mut(index) + { + input.items = vec![Sel::SketchCurve { id: id.clone() }]; + } + } } } dialog.extra.insert("pattern".into(), json!(id)); @@ -287,19 +329,33 @@ pub fn rows(ui: &mut egui::Ui, k: &mut Mod) -> bool { check(ui, copy); ui.end_row(); } - Mod::PatternRect { count, spacing, count2, spacing2 } => { - for (label, value) in [("Quantity", count), ("Spacing", spacing), ("Quantity 2", count2), ("Spacing 2", spacing2)] { - row_label(ui, label); - enter |= field(ui, value); - ui.end_row(); - } - } - Mod::PatternCirc { count, angle } => { + // Its two direction columns include both the reference picks and values. + Mod::PatternRect { .. } => {} + Mod::PatternCirc { count, angle, alignment, reversed } => { for (label, value) in [("Quantity", count), ("Total angle", angle)] { row_label(ui, label); enter |= field(ui, value); ui.end_row(); } + row_label(ui, "Alignment"); + ui.horizontal(|ui| { + pattern_toggle(ui, "Alignment", "Flip direction", "pattern_flip", reversed); + let mut centered = *alignment == PatternAlignment::Center; + pattern_toggle(ui, "Alignment", "Center", "pattern_center", &mut centered); + *alignment = if centered { PatternAlignment::Center } else { PatternAlignment::Right }; + }); + ui.end_row(); + row_label(ui, ""); + ui.add( + egui::Label::new( + egui::RichText::new(crate::i18n::tr_label( + "Counts include the original. Center balances copies; Flip chooses the extra side for even totals.", + )) + .small(), + ) + .wrap(), + ); + ui.end_row(); } Mod::Corner { chamfer, ctype, size, distance2, angle, flip } => { if *chamfer { @@ -349,13 +405,13 @@ fn sketch_dir(app: &SolveApp, sel: &Sel) -> Option { pub fn arrow(app: &SolveApp, d: &Dialog) -> Option { let Kind::SketchModify(k) = &d.kind else { return None }; match k { - Mod::PatternRect { .. } => { + Mod::PatternRect { alignment, reversed, .. } => { let plane = app.session.world_state().sketch(app.session.active_sketch?)?.plane; let dir = match d.inputs.get(1).and_then(|i| i.items.first()) { Some(sel) => sketch_dir(app, sel)?, None => Vec2::X, }; - Some(plane.dir_to_world(dir)) + Some(plane.dir_to_world(if (*alignment == PatternAlignment::Left) ^ *reversed { -dir } else { dir })) } // A total angle is a rotation. The viewport draws a straight drag arrow and a rotation // handle only for Revolve, through machinery tied to its own extents, so the circular @@ -617,7 +673,7 @@ pub fn commands(app: &SolveApp, k: &Mod, inputs: &[SelInput], extra: &Map { + Mod::PatternRect { count, spacing, count2, spacing2, alignment, alignment2, reversed, reversed2 } => { let entities = entity_ids(&app.session, inputs, 0); if entities.is_empty() { return Err("Select the sketch curves or points to pattern first".into()); @@ -635,16 +691,24 @@ pub fn commands(app: &SolveApp, k: &Mod, inputs: &[SelInput], extra: &Map MAX_COPIES as u64 { return Err(format!("Quantity and Quantity 2 together must make at most {MAX_COPIES:.0} instances")); } - let mut p = json!({"entities": entities, "count": n1, "spacing": s1, "count2": n2, "spacing2": s2}); + let mut p = json!({"entities": entities, "count": n1, "spacing": s1, "count2": n2, "spacing2": s2, "alignment": alignment, "alignment2": alignment2, "reversed": reversed, "reversed2": reversed2}); // A picked direction that has no component in the sketch plane is reported rather // than quietly replaced by the default. - if let Some(sel) = inputs.get(1).and_then(|i| i.items.first()) { - let d = sketch_dir(app, sel).ok_or("The direction must be an axis or a straight sketch curve that lies in the sketch plane")?; - p["dir"] = json!([d.x, d.y]); + for (index, vector_key, line_key) in [(1, "dir", "direction"), (2, "dir2", "direction2")] { + if let Some(sel) = inputs.get(index).and_then(|i| i.items.first()) { + let d = sketch_dir(app, sel).ok_or("The direction must be an axis or a straight sketch curve that lies in the sketch plane")?; + p[vector_key] = json!([d.x, d.y]); + p[line_key] = match sel { + Sel::SketchCurve { id } => json!(id), + _ => Value::Null, + }; + } else { + p[line_key] = Value::Null; + } } ("sketch.pattern.rectangular", p) } - Mod::PatternCirc { count, angle } => { + Mod::PatternCirc { count, angle, alignment, reversed } => { let entities = entity_ids(&app.session, inputs, 0); if entities.is_empty() { return Err("Select the sketch curves or points to pattern first".into()); @@ -663,7 +727,10 @@ pub fn commands(app: &SolveApp, k: &Mod, inputs: &[SelInput], extra: &Map { let corners = corner_ids(app, inputs, 0); diff --git a/crates/ui-egui/src/sketch_modify_ui_tests.rs b/crates/ui-egui/src/sketch_modify_ui_tests.rs index 783ef8045..c88a575c3 100644 --- a/crates/ui-egui/src/sketch_modify_ui_tests.rs +++ b/crates/ui-egui/src/sketch_modify_ui_tests.rs @@ -456,7 +456,7 @@ fn open(cmd: &str) -> (crate::scenario::Harness, String) { fn rect(h: &mut crate::scenario::Harness, count: &str, spacing: &str, count2: &str, spacing2: &str) { let d = h.app.dialog.as_mut().expect("the window opened"); - if let Kind::SketchModify(Mod::PatternRect { count: c1, spacing: s1, count2: c2, spacing2: s2 }) = &mut d.kind { + if let Kind::SketchModify(Mod::PatternRect { count: c1, spacing: s1, count2: c2, spacing2: s2, .. }) = &mut d.kind { *c1 = count.into(); *s1 = spacing.into(); *c2 = count2.into(); @@ -472,12 +472,58 @@ fn rectangular_pattern_window_opens_instead_of_a_click_tool() { assert!(h.app.tool.is_none(), "the click tool still takes the command"); let d = h.app.dialog.as_ref().expect("the window opened"); assert!(matches!(d.kind, Kind::SketchModify(Mod::PatternRect { .. })), "{:?}", d.kind); - assert_eq!(d.inputs.iter().map(|i| i.label).collect::>(), vec!["Entities", "Direction"]); + assert_eq!(d.inputs.iter().map(|i| i.label).collect::>(), vec!["Entities", "Direction", "Direction 2"]); // Nothing is committed by opening the window. let sid = h.app.session.active_sketch.unwrap(); assert_eq!(h.app.session.model.state().sketch(sid).unwrap().sketch.curves.len(), 1); } +#[test] +fn rectangular_columns_flip_and_center_independently_and_restore_even_counts_when_editing() { + use solidcraft_engine::sketch::PatternAlignment; + let (mut h, id) = open("sketch.pattern.rectangular"); + h.app.dialog.as_mut().unwrap().inputs[0].items = vec![Sel::SketchCurve { id }]; + rect(&mut h, "4", "20", "2", "10"); + h.settle(); + let first = crate::scenario::handle_at("dialog:Spacing").unwrap(); + let second = crate::scenario::handle_at("dialog:Spacing 2").unwrap(); + assert!(second.x - first.x > 180.0, "the directions should occupy separate columns: {first:?}, {second:?}"); + assert!((second.y - first.y).abs() < 2.0, "the independent spacing fields should share a row"); + for label in ["Alignment", "Alignment 2"] { + let left = crate::scenario::handle_at(&format!("dialog:{label}:Flip direction")).unwrap(); + let right = crate::scenario::handle_at(&format!("dialog:{label}:Center")).unwrap(); + assert!((left.y - right.y).abs() < 2.0, "alignment choices should fit on a single line: {left:?}, {right:?}"); + } + h.step(&json!({"click":{"handle":"dialog:Alignment:Center"}})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:Alignment 2:Flip direction"}})).unwrap(); + let d = h.app.dialog.as_ref().unwrap(); + let commands = apply_commands(&h.app, d).unwrap(); + assert_eq!(commands[0].1["alignment"], "center"); + assert_eq!(commands[0].1["alignment2"], "right"); + assert_eq!(commands[0].1["reversed2"], true); + assert_eq!(commands[0].1["count"], 4); + h.step(&json!({"click":{"handle":"dialog:OK"}})).unwrap(); + h.settle(); + assert!(h.app.dialog.is_none()); + let sid = h.app.session.active_sketch.unwrap(); + let pattern = h.app.session.world_state().sketch(sid).unwrap().sketch.patterns[0].id.clone(); + assert!(crate::sketch_modify_ui::edit_pattern(&mut h.app, &pattern)); + assert!(matches!( + h.app.dialog.as_ref().unwrap().kind, + Kind::SketchModify(Mod::PatternRect { alignment: PatternAlignment::Center, alignment2: PatternAlignment::Right, reversed2: true, .. }) + )); + rect(&mut h, "4", "20", "3", "10"); + assert!(apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).is_ok()); + h.settle(); + h.step(&json!({"click":{"handle":"dialog:Alignment:Flip direction"}})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:Alignment 2:Center"}})).unwrap(); + let commands = apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap(); + assert_eq!(commands[0].1["alignment"], "center"); + assert_eq!(commands[0].1["reversed"], true); + assert_eq!(commands[0].1["alignment2"], "center"); + assert_eq!(commands[0].1["reversed2"], true); +} + #[test] fn typed_counts_and_spacings_reach_the_command_with_the_second_direction() { let (mut h, id) = open("sketch.pattern.rectangular"); @@ -506,6 +552,45 @@ fn a_picked_axis_becomes_an_in_plane_direction() { assert_eq!(cmds[0].1["dir"], json!([0.0, 1.0]), "sketch y on the XY plane"); } +#[test] +fn two_picked_lines_are_sent_as_live_references_and_restored_in_the_editor() { + let (mut h, id) = open("sketch.pattern.rectangular"); + h.app.run("sketch.line", json!({"points":[[0,-20],[10,-20]],"ids":["dir1"]})).unwrap(); + h.app.run("sketch.line", json!({"points":[[0,-40],[6,-32]],"ids":["dir2"]})).unwrap(); + let d = h.app.dialog.as_mut().unwrap(); + d.inputs[0].items = vec![Sel::SketchCurve { id }]; + d.inputs[1].items = vec![Sel::SketchCurve { id: "dir1".into() }]; + d.inputs[2].items = vec![Sel::SketchCurve { id: "dir2".into() }]; + rect(&mut h, "3", "20", "2", "10"); + let d = h.app.dialog.clone().unwrap(); + let cmds = apply_commands(&h.app, &d).unwrap(); + assert_eq!(cmds[0].1["direction"], "dir1"); + assert_eq!(cmds[0].1["direction2"], "dir2"); + let out = h.app.run(&cmds[0].0, cmds[0].1.clone()).unwrap(); + assert!(crate::sketch_modify_ui::edit_pattern(&mut h.app, out["pattern"].as_str().unwrap())); + let d = h.app.dialog.as_ref().unwrap(); + assert_eq!(d.inputs[1].items, vec![Sel::SketchCurve { id: "dir1".into() }]); + assert_eq!(d.inputs[2].items, vec![Sel::SketchCurve { id: "dir2".into() }]); + let reopened = apply_commands(&h.app, d).unwrap(); + assert_eq!(reopened[0].1["direction2"], "dir2"); +} + +#[test] +fn sketch_pattern_tools_are_promoted_together_and_open_from_the_toolbar() { + let mut h = Harness::new(); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + let panels = crate::toolbar_custom::panel_lists("SKETCH"); + let (_, cmds, promoted) = panels.iter().find(|(panel, ..)| *panel == "PATTERN").unwrap(); + let ids: Vec<_> = cmds.iter().take(*promoted).map(|c| c.id).collect(); + assert_eq!(ids, ["sketch.mirror", "sketch.pattern.rectangular", "sketch.pattern.circular"]); + for id in ids { + h.settle(); + h.step(&json!({"click":{"handle":format!("toolbar:{id}")}})).unwrap(); + assert!(matches!(h.app.dialog.as_ref().map(|d| &d.kind), Some(Kind::SketchModify(_))), "{id}"); + h.step(&json!({"key":"Escape"})).unwrap(); + } +} + #[test] fn an_axis_perpendicular_to_the_sketch_is_reported_not_silently_replaced() { let (mut h, id) = open("sketch.pattern.rectangular"); @@ -590,7 +675,7 @@ fn open_circ() -> (crate::scenario::Harness, String) { fn circ(h: &mut crate::scenario::Harness, count: &str, angle: &str) { let d = h.app.dialog.as_mut().expect("the window opened"); - if let Kind::SketchModify(Mod::PatternCirc { count: c, angle: a }) = &mut d.kind { + if let Kind::SketchModify(Mod::PatternCirc { count: c, angle: a, .. }) = &mut d.kind { *c = count.into(); *a = angle.into(); } else { @@ -627,6 +712,41 @@ fn the_typed_count_and_total_angle_reach_the_command() { assert_eq!(apply_commands(&h.app, &d).unwrap()[0].1["angle"], json!(90.0)); } +#[test] +fn circular_flip_and_center_buttons_apply_and_reopen_the_saved_placement() { + use solidcraft_engine::sketch::{PatternAlignment, SketchPatternKind}; + let (mut h, _) = open_circ(); + circ(&mut h, "6", "90 deg"); + h.frames(3); + h.step(&json!({"click":{"handle":"dialog:Alignment:Center"}})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:Alignment:Flip direction"}})).unwrap(); + let d = h.app.dialog.clone().unwrap(); + let params = &apply_commands(&h.app, &d).unwrap()[0].1; + assert_eq!(params["count"], json!(6)); + assert_eq!(params["angle"], json!(90.)); + assert_eq!(params["alignment"], json!("center")); + assert_eq!(params["reversed"], json!(true)); + h.step(&json!({"click":{"handle":"dialog:OK"}})).unwrap(); + let sid = h.app.session.active_sketch.unwrap(); + let id = { + let state = h.app.session.world_state(); + let pattern = &state.sketch(sid).unwrap().sketch.patterns[0]; + assert!(matches!(pattern.kind, SketchPatternKind::Circular { alignment: PatternAlignment::Center, reversed: true, .. })); + pattern.id.clone() + }; + assert!(crate::sketch_modify_ui::edit_pattern(&mut h.app, &id)); + assert!(matches!( + h.app.dialog.as_ref().unwrap().kind, + Kind::SketchModify(Mod::PatternCirc { alignment: PatternAlignment::Center, reversed: true, .. }) + )); + h.frames(3); + h.step(&json!({"click":{"handle":"dialog:Alignment:Center"}})).unwrap(); + let d = h.app.dialog.clone().unwrap(); + let params = &apply_commands(&h.app, &d).unwrap()[0].1; + assert_eq!(params["alignment"], json!("right")); + assert_eq!(params["reversed"], json!(true)); +} + /// The same lesson as upstream #218: `num` reads a JSON number only, and `sketch.pattern.circular` /// falls back to a full turn when `angle` is anything else. An expression has to be evaluated /// here or it disappears in silence. diff --git a/crates/ui-egui/src/sketch_pattern_tree.rs b/crates/ui-egui/src/sketch_pattern_tree.rs new file mode 100644 index 000000000..09c2cbea5 --- /dev/null +++ b/crates/ui-egui/src/sketch_pattern_tree.rs @@ -0,0 +1,132 @@ +//! Sketch patterns are children of their sketch, rather than separate timeline features. + +use serde_json::json; +use solidcraft_engine::{Sel, sketch::SketchPatternKind}; + +use crate::{ + SolveApp, + browser::{Row, draw_row}, +}; + +pub(crate) fn has_patterns(app: &SolveApp, sketch: u64) -> bool { + app.session.doc.sketch(sketch).is_ok_and(|sk| !sk.patterns.is_empty()) +} + +/// Shared by the parts browser and the vertical feature history. The stored document is the +/// source, so rolled-back sketches retain their children without showing preview-only copies. +pub(crate) fn rows(app: &mut SolveApp, ui: &mut egui::Ui, sketch: u64, depth: usize, scope: &str, occurrence: Option<(u64, &[u64])>) { + let patterns: Vec<_> = app.session.doc.sketch(sketch).map(|sk| sk.patterns.clone()).unwrap_or_default(); + for pattern in patterns { + let (name, icon) = match pattern.kind { + SketchPatternKind::Rectangular { .. } => ("Rectangular Pattern", "sketch_rect_pattern"), + SketchPatternKind::Circular { .. } => ("Circular Pattern", "sketch_circ_pattern"), + }; + let suffix = pattern.id.strip_prefix("pat").unwrap_or(&pattern.id); + let label = format!("{} {suffix}", crate::i18n::tr_label(name)); + let active = app.session.active_sketch == Some(sketch); + let curves: Vec<_> = app + .session + .doc + .sketch(sketch) + .map(|sk| { + pattern + .entities + .iter() + .chain(pattern.instances.iter().flat_map(|i| &i.curves)) + .map(|id| if sk.curve_index(id).is_some() { Sel::SketchCurve { id: id.clone() } } else { Sel::SketchPoint { id: id.clone() } }) + .collect() + }) + .unwrap_or_default(); + let selected = active && !curves.is_empty() && curves.iter().all(|curve| app.session.selection.contains(curve)); + let response = draw_row( + ui, + ui.id().with(("sketch_pattern", sketch, &pattern.id)), + &Row { depth, icon, label: &label, name: true, selected, ..Default::default() }, + ); + if let Some(rect) = response.rect { + crate::scenario::publish_handle(&format!("{scope}:sketch-pattern:{sketch}:{}", pattern.id), rect.center()); + } + if response.double { + if let Some((component, path)) = occurrence { + let _ = app.run("component.activate", json!({"component":component,"occurrence":path.last(),"path":path})); + } + app.edit_sketch(sketch); + if app.session.active_sketch == Some(sketch) { + crate::sketch_modify_ui::edit_pattern(app, &pattern.id); + } + } else if response.clicked { + let items = if active { curves } else { vec![Sel::Feature { id: sketch }] }; + let _ = app.run("select.set", json!({"items":items})); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{dialogs::Kind, scenario::Harness, sketch_modify_ui::Mod}; + + fn harness(left_history: bool) -> (Harness, u64, String, String) { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.ui.show_browser = true; + h.app.preferences.timeline_left = left_history; + h.app.run("sketch.create", json!({"plane":"XY","name":"Patterned Sketch"})).unwrap(); + let sketch = h.app.session.active_sketch.unwrap(); + h.app.run("sketch.line", json!({"points":[[10,5],[15,5]],"ids":["source"]})).unwrap(); + let rectangular = h + .app + .run("sketch.pattern.rectangular", json!({"entities":["source"],"count":4,"spacing":20,"alignment":"center","reversed":true})) + .unwrap(); + let circular = h.app.run("sketch.pattern.circular", json!({"entities":["source"],"center":"origin","count":3})).unwrap(); + h.app.finish_sketch(); + h.frames(6); + (h, sketch, rectangular["pattern"].as_str().unwrap().into(), circular["pattern"].as_str().unwrap().into()) + } + + #[test] + fn browser_patterns_fold_with_the_sketch_and_double_click_opens_the_saved_editor() { + let (mut h, sketch, rectangular, circular) = harness(false); + let handle = format!("browser:sketch-pattern:{sketch}:{rectangular}"); + let child = crate::scenario::handle_at(&handle).unwrap(); + let parent = crate::scenario::handle_at("row:Patterned Sketch").unwrap(); + assert!(child.y > parent.y, "patterns belong below their sketch"); + assert!(crate::scenario::handle_at(&format!("browser:sketch-pattern:{sketch}:{circular}")).is_some()); + h.step(&json!({"click":{"handle":"fold:Patterned Sketch"}})).unwrap(); + h.frames(3); + assert!(crate::scenario::handle_at(&handle).is_none()); + h.step(&json!({"click":{"handle":"fold:Patterned Sketch"}})).unwrap(); + // Let the fold clicks leave egui's triple-click interval before double-clicking a child. + h.frames(40); + h.step(&json!({"click":{"handle":handle},"double":true})).unwrap(); + h.frames(3); + assert_eq!(h.app.session.active_sketch, Some(sketch), "selection={:?}, status={:?}", h.app.session.selection, h.app.status); + let dialog = h.app.dialog.as_ref().unwrap(); + assert_eq!(dialog.extra["pattern"], rectangular); + assert!(matches!(&dialog.kind, Kind::SketchModify(Mod::PatternRect { count, reversed: true, .. }) if count == "4")); + } + + #[test] + fn left_history_lists_both_pattern_kinds_and_tracks_deletion_and_undo() { + let (mut h, sketch, rectangular, circular) = harness(true); + let handle = format!("timeline:sketch-pattern:{sketch}:{circular}"); + assert!(crate::scenario::handle_at(&format!("timeline:sketch-pattern:{sketch}:{rectangular}")).is_some()); + assert!(crate::scenario::handle_at(&handle).is_some()); + h.step(&json!({"click":{"handle":"timeline-sketch-fold:Patterned Sketch"}})).unwrap(); + h.frames(3); + assert!(crate::scenario::handle_at(&handle).is_none()); + h.step(&json!({"click":{"handle":"timeline-sketch-fold:Patterned Sketch"}})).unwrap(); + h.frames(40); + h.step(&json!({"click":{"handle":handle},"double":true})).unwrap(); + h.frames(3); + assert!(matches!(h.app.dialog.as_ref().unwrap().kind, Kind::SketchModify(Mod::PatternCirc { .. }))); + assert_eq!(h.app.dialog.as_ref().unwrap().extra["pattern"], circular); + h.step(&json!({"key":"Escape"})).unwrap(); + h.app.run("sketch.delete", json!({"entities":["source"]})).unwrap(); + h.frames(3); + assert!(crate::scenario::handle_at(&handle).is_none()); + h.app.run("edit.undo", json!({})).unwrap(); + h.frames(3); + assert!(crate::scenario::handle_at(&handle).is_some()); + } +} diff --git a/crates/ui-egui/src/sketch_tools.rs b/crates/ui-egui/src/sketch_tools.rs index cc93ae56a..34a14c470 100644 --- a/crates/ui-egui/src/sketch_tools.rs +++ b/crates/ui-egui/src/sketch_tools.rs @@ -1050,7 +1050,9 @@ fn constraint_entities(k: &solidcraft_engine::sketch::ConstraintKind) -> (Vec (vec![], vec![p, q]), - PatternPoint { p, q, center, .. } => (vec![], vec![p, q].into_iter().chain(center).collect()), + PatternPoint { p, q, center, directions, .. } => { + (directions.into_iter().flatten().map(|(l, _)| l).collect(), vec![p, q].into_iter().chain(center).collect()) + } PatternRadius { a, b } => (vec![a, b], vec![]), Fix { p } => (vec![], vec![p]), Midpoint { p, l } => (vec![l], vec![p]), diff --git a/crates/ui-egui/src/timeline_left.rs b/crates/ui-egui/src/timeline_left.rs index d701ec49a..51e1f09a3 100644 --- a/crates/ui-egui/src/timeline_left.rs +++ b/crates/ui-egui/src/timeline_left.rs @@ -685,7 +685,12 @@ fn vertical_features(app: &mut SolveApp, ui: &mut egui::Ui) { } slots.push(VerticalSlot { y: ui.cursor().top(), position: index, group: group_id, indent_group }); let indent = group_id.map(|id| (group_depth(&groups, id) + 1) as f32 * 14.0).unwrap_or(0.0); + let has_patterns = matches!(kind, FeatureKind::Sketch { .. }) && crate::sketch_pattern_tree::has_patterns(app, *id); + let pattern_key = format!("timeline/sketch/{id}/patterns"); + let patterns_open = crate::browser::is_open(app, &pattern_key, true); let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), 24.0), Sense::click_and_drag()); + let fold_rect = Rect::from_min_size(rect.left_top() + vec2(indent, 0.0), vec2(16.0, rect.height())); + let on_fold = has_patterns && response.interact_pointer_pos().is_some_and(|p| fold_rect.contains(p)); crate::scenario::publish_handle(&format!("timeline:{name}"), rect.center()); let result = app.session.model.result(*id); let error = result.and_then(|result| result.error.clone()); @@ -705,7 +710,12 @@ fn vertical_features(app: &mut SolveApp, ui: &mut egui::Ui) { if background != Color32::TRANSPARENT { ui.painter().rect_filled(rect, 3.0, background); } - let icon_rect = Rect::from_center_size(pos2(rect.left() + 13.0 + indent, rect.center().y), vec2(18.0, 18.0)); + if has_patterns { + crate::icons::glyphs::disclosure(ui.painter(), fold_rect.shrink(3.0), patterns_open, t.text_dim); + crate::scenario::publish_handle(&format!("timeline-sketch-fold:{name}"), fold_rect.center()); + } + let icon_rect = + Rect::from_center_size(pos2(rect.left() + 13.0 + indent + if has_patterns { 16.0 } else { 0.0 }, rect.center().y), vec2(18.0, 18.0)); let ink = if rolled || *suppressed { t.border } else { t.icon }; icons::paint(ui.painter(), icon_rect, icon, ink, if rolled { t.panel_header } else { t.icon_fill }, if rolled { t.border } else { t.accent }); if *suppressed { @@ -737,7 +747,7 @@ fn vertical_features(app: &mut SolveApp, ui: &mut egui::Ui) { if response.hovered() { hovered = Some(*id); } - if response.drag_started() { + if response.drag_started() && !on_fold { if !selected { select_only(app, TimelineItem::Feature(*id)); } @@ -753,10 +763,12 @@ fn vertical_features(app: &mut SolveApp, ui: &mut egui::Ui) { } tip.push_str("\nDouble-click to edit · drag to reorder · right-click for more"); let response = response.on_hover_text(tip); - if response.clicked() { + if response.clicked() && on_fold { + crate::browser::toggle(app, &pattern_key, true); + } else if response.clicked() { select_item(app, ui, TimelineItem::Feature(*id), &order); } - if response.double_clicked() { + if response.double_clicked() && !on_fold { edit = Some(*id); } let sketch = match kind { @@ -800,6 +812,10 @@ fn vertical_features(app: &mut SolveApp, ui: &mut egui::Ui) { ui.close(); } }); + if has_patterns && patterns_open { + let depth = group_id.map_or(1, |group| group_depth(&groups, group) + 2); + crate::sketch_pattern_tree::rows(app, ui, *id, depth, "timeline", None); + } previous_visible_group = group_id; } let mut trailing: Vec<_> = groups.iter().filter(|group| !shown_groups.contains(&group.id)).collect(); diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index ffc53d8ca..56cf0166c 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -52,7 +52,7 @@ pub fn panels(tab: &str) -> &'static [&'static str] { } match tab { "SOLID" => &["CREATE", "MODIFY", "ASSEMBLE", "CONSTRUCT", "INSPECT", "INSERT", "SELECT"], - "SKETCH" => &["CREATE", "MODIFY", "CONSTRAINTS", "INSPECT", "INSERT", "SELECT", "FINISH SKETCH"], + "SKETCH" => &["CREATE", "MODIFY", "PATTERN", "CONSTRAINTS", "INSPECT", "INSERT", "SELECT", "FINISH SKETCH"], "SURFACE" => &["CREATE", "MODIFY", "ASSEMBLE", "CONSTRUCT", "INSPECT", "INSERT", "SELECT"], "MESH" => &["CREATE", "PREPARE", "MODIFY", "ASSEMBLE", "CONSTRUCT", "INSPECT", "INSERT", "SELECT"], "SHEET METAL" => &["CREATE", "MODIFY", "ASSEMBLE", "CONSTRUCT", "INSPECT", "INSERT", "SELECT"], @@ -69,6 +69,7 @@ pub fn promoted(tab: &str, panel: &str) -> usize { ("SOLID", "CREATE") => 4, ("SOLID", "MODIFY") => 4, ("SKETCH", "CONSTRAINTS") => 6, + ("SKETCH", "PATTERN") => 3, (_, "FINISH SKETCH") => 1, _ => 2, } diff --git a/crates/ui-egui/src/workspace.rs b/crates/ui-egui/src/workspace.rs index a3b04c2b0..bc3438c3e 100644 --- a/crates/ui-egui/src/workspace.rs +++ b/crates/ui-egui/src/workspace.rs @@ -119,6 +119,7 @@ pub fn layout<'a>(tab: &str, panel: &str, specs: &[&'a CommandSpec]) -> Option<( tab, ), ("SOLID", "CONFIGURE") => (&["parameters.change", "config.table"], 2, tab), + ("SKETCH", "PATTERN") => (&["sketch.mirror", "sketch.pattern.rectangular", "sketch.pattern.circular"], 3, tab), ("SOLID" | "SHEET METAL" | "PLASTIC", "ASSEMBLE") => (ASSEMBLE, 3, tab), ("SHEET METAL", "CREATE") => (SHEET_CREATE, 3, tab), ("SHEET METAL", "MODIFY") => (SHEET_MODIFY, 2, tab), diff --git a/crates/ui-egui/tests/scenarios/sketch_pattern_alignment.json b/crates/ui-egui/tests/scenarios/sketch_pattern_alignment.json new file mode 100644 index 000000000..2bf99454b --- /dev/null +++ b/crates/ui-egui/tests/scenarios/sketch_pattern_alignment.json @@ -0,0 +1,48 @@ +[ + {"note":"Each column has independent spacing, quantity and alignment. Center keeps the original in the middle; Left follows the negative second guide."}, + {"call":"engine.execute","params":{"command":"sketch.create","params":{"plane":"XY"}}}, + {"call":"engine.execute","params":{"command":"sketch.circle.center","params":{"center":[5,5],"radius":2,"id":"seed"}}}, + {"call":"engine.execute","params":{"command":"sketch.line","params":{"points":[[0,-10],[20,-10]],"ids":["guide1"]}}}, + {"call":"engine.execute","params":{"command":"sketch.line","params":{"points":[[0,-30],[12,-14]],"ids":["guide2"]}}}, + {"call":"engine.execute","params":{"command":"sketch.constraint.fix","params":{"entities":["guide1","guide2"],"fixed":true}}}, + {"call":"ui.view","params":{"view":"top"}}, + {"click":{"handle":"toolbar:sketch.pattern.rectangular"}}, + {"click":{"sketch":[7,5]}}, + {"click":{"handle":"dialog:Direction"}}, + {"click":{"sketch":[10,-10]}}, + {"click":{"handle":"dialog:Direction 2"}}, + {"click":{"sketch":[6,-22]}}, + {"click":{"handle":"dialog:Quantity"}}, + {"key":"A","cmd":true}, + {"text":"3"}, + {"click":{"handle":"dialog:Spacing"}}, + {"key":"A","cmd":true}, + {"text":"20"}, + {"click":{"handle":"dialog:Quantity 2"}}, + {"key":"A","cmd":true}, + {"text":"2"}, + {"click":{"handle":"dialog:Spacing 2"}}, + {"key":"A","cmd":true}, + {"text":"10"}, + {"expect":{"dialog":"PatternRect","errors":0,"sketch_curves":{"own":3}}}, + {"click":{"handle":"dialog:Alignment:Center"}}, + {"click":{"handle":"dialog:Alignment 2:Flip direction"}}, + {"shot":"sketch_pattern_alignment_preview"}, + {"click":{"handle":"dialog:OK"}}, + {"expect":{"dialog":null,"errors":0,"sketch_curves":{"own":8}}}, + {"expect":{"query":{"command":"sketch.inspect","path":["curves",7,"center_at",0],"value":-21}}}, + {"expect":{"query":{"command":"sketch.inspect","path":["curves",7,"center_at",1],"value":-3}}}, + {"call":"ui.view","params":{"view":"fit"}}, + {"shot":"sketch_pattern_alignment_before"}, + {"call":"engine.execute","params":{"command":"sketch.drag","params":{"entity":"seed.center","from":[5,5],"to":[7,8]}}}, + {"expect":{"query":{"command":"sketch.inspect","path":["curves",7,"center_at",0],"value":-19}}}, + {"expect":{"query":{"command":"sketch.inspect","path":["curves",7,"center_at",1],"value":0}}}, + {"call":"engine.execute","params":{"command":"sketch.constraint.fix","params":{"entities":["seed"],"fixed":true}}}, + {"call":"engine.execute","params":{"command":"sketch.constraint.fix","params":{"entities":["guide2"],"fixed":false}}}, + {"call":"engine.execute","params":{"command":"sketch.constraint.fix","params":{"entities":["guide2.start"],"fixed":true}}}, + {"call":"engine.execute","params":{"command":"sketch.drag","params":{"entity":"guide2.end","from":[12,-14],"to":[16,-18]}}}, + {"expect":{"query":{"command":"sketch.inspect","path":["curves",7,"center_at",0],"value":-21}}}, + {"expect":{"query":{"command":"sketch.inspect","path":["curves",7,"center_at",1],"value":2}}}, + {"expect":{"errors":0,"sketch_curves":{"own":8}}}, + {"shot":"sketch_pattern_alignment_after"} +] diff --git a/crates/ui-egui/tests/scenarios/sketch_pattern_circular_center.json b/crates/ui-egui/tests/scenarios/sketch_pattern_circular_center.json new file mode 100644 index 000000000..8f024092c --- /dev/null +++ b/crates/ui-egui/tests/scenarios/sketch_pattern_circular_center.json @@ -0,0 +1,33 @@ +[ + {"note":"Six total holes span 90 degrees around the original; Flip chooses the extra side without moving the seed."}, + {"call":"engine.execute","params":{"command":"sketch.create","params":{"plane":"XY"}}}, + {"call":"engine.execute","params":{"command":"sketch.circle.center","params":{"center":[40,0],"radius":2,"id":"seed"}}}, + {"call":"engine.execute","params":{"command":"sketch.point","params":{"point":[0,0],"id":"axis_center"}}}, + {"call":"engine.execute","params":{"command":"sketch.constraint.fix","params":{"entities":["axis_center"]}}}, + {"call":"ui.view","params":{"view":"top"}}, + {"call":"ui.camera","params":{"target":[25,0,0],"distance":120}}, + {"start":"sketch.pattern.circular"}, + {"click":{"sketch":[42,0]}}, + {"click":{"handle":"dialog:Center"}}, + {"click":{"sketch":[0,0]}}, + {"click":{"handle":"dialog:Quantity"}}, + {"key":"A","cmd":true}, + {"text":"6"}, + {"click":{"handle":"dialog:Total angle"}}, + {"key":"A","cmd":true}, + {"text":"90 deg"}, + {"click":{"handle":"dialog:Alignment:Center"}}, + {"shot":"sketch_pattern_circular_center_before_flip"}, + {"click":{"handle":"dialog:Alignment:Flip direction"}}, + {"shot":"sketch_pattern_circular_center_after_flip"}, + {"click":{"handle":"dialog:OK"}}, + {"expect":{"dialog":null,"errors":0,"sketch_curves":{"own":6}}}, + {"expect":{"query":{"command":"sketch.inspect","path":["curves",5,"center_at",0],"value":23.511410091698927}}}, + {"expect":{"query":{"command":"sketch.inspect","path":["curves",5,"center_at",1],"value":-32.3606797749979}}}, + {"expect":{"query":{"command":"sketch.inspect","path":["curves",0,"center_at",0],"value":40}}}, + {"expect":{"query":{"command":"sketch.inspect","path":["curves",0,"center_at",1],"value":0}}}, + {"call":"engine.execute","params":{"command":"sketch.drag","params":{"entity":"seed.center","from":[40,0],"to":[45,0]}}}, + {"expect":{"query":{"command":"sketch.inspect","path":["curves",5,"center_at",0],"value":26.45033635316129}}}, + {"expect":{"query":{"command":"sketch.inspect","path":["curves",5,"center_at",1],"value":-36.405764746872634}}}, + {"shot":"sketch_pattern_circular_center_source_edit"} +] diff --git a/crates/ui-egui/tests/scenarios/sketch_pattern_even_center.json b/crates/ui-egui/tests/scenarios/sketch_pattern_even_center.json new file mode 100644 index 000000000..7f1f38e4a --- /dev/null +++ b/crates/ui-egui/tests/scenarios/sketch_pattern_even_center.json @@ -0,0 +1,49 @@ +[ + {"note":"Even centered totals keep the original fixed; Flip chooses the extra side independently for each direction."}, + {"call":"engine.execute","params":{"command":"sketch.create","params":{"plane":"XY"}}}, + {"call":"engine.execute","params":{"command":"sketch.circle.center","params":{"center":[5,5],"radius":2,"id":"seed"}}}, + {"call":"engine.execute","params":{"command":"sketch.line","params":{"points":[[0,-10],[20,-10]],"ids":["guide1"]}}}, + {"call":"engine.execute","params":{"command":"sketch.line","params":{"points":[[0,-30],[12,-14]],"ids":["guide2"]}}}, + {"call":"engine.execute","params":{"command":"sketch.constraint.fix","params":{"entities":["guide1","guide2"],"fixed":true}}}, + {"call":"ui.view","params":{"view":"top"}}, + {"click":{"handle":"toolbar:sketch.pattern.rectangular"}}, + {"click":{"sketch":[7,5]}}, + {"click":{"handle":"dialog:Direction"}}, + {"click":{"sketch":[10,-10]}}, + {"click":{"handle":"dialog:Direction 2"}}, + {"click":{"sketch":[6,-22]}}, + {"click":{"handle":"dialog:Quantity"}}, + {"key":"A","cmd":true}, + {"text":"4"}, + {"click":{"handle":"dialog:Spacing"}}, + {"key":"A","cmd":true}, + {"text":"20"}, + {"click":{"handle":"dialog:Quantity 2"}}, + {"key":"A","cmd":true}, + {"text":"2"}, + {"click":{"handle":"dialog:Spacing 2"}}, + {"key":"A","cmd":true}, + {"text":"10"}, + {"expect":{"dialog":"PatternRect","errors":0,"sketch_curves":{"own":3}}}, + {"click":{"handle":"dialog:Alignment:Center"}}, + {"click":{"handle":"dialog:Alignment 2:Center"}}, + {"click":{"handle":"dialog:Alignment:Flip direction"}}, + {"shot":"sketch_pattern_even_center_preview"}, + {"click":{"handle":"dialog:OK"}}, + {"expect":{"dialog":null,"errors":0,"sketch_curves":{"own":10}}}, + {"expect":{"query":{"command":"sketch.inspect","path":["curves",9,"center_at",0],"value":-29}}}, + {"expect":{"query":{"command":"sketch.inspect","path":["curves",9,"center_at",1],"value":13}}}, + {"call":"ui.view","params":{"view":"fit"}}, + {"shot":"sketch_pattern_even_center_before"}, + {"call":"engine.execute","params":{"command":"sketch.drag","params":{"entity":"seed.center","from":[5,5],"to":[7,8]}}}, + {"expect":{"query":{"command":"sketch.inspect","path":["curves",9,"center_at",0],"value":-27}}}, + {"expect":{"query":{"command":"sketch.inspect","path":["curves",9,"center_at",1],"value":16}}}, + {"call":"engine.execute","params":{"command":"sketch.constraint.fix","params":{"entities":["seed"],"fixed":true}}}, + {"call":"engine.execute","params":{"command":"sketch.constraint.fix","params":{"entities":["guide2"],"fixed":false}}}, + {"call":"engine.execute","params":{"command":"sketch.constraint.fix","params":{"entities":["guide2.start"],"fixed":true}}}, + {"call":"engine.execute","params":{"command":"sketch.drag","params":{"entity":"guide2.end","from":[12,-14],"to":[16,-18]}}}, + {"expect":{"query":{"command":"sketch.inspect","path":["curves",9,"center_at",0],"value":-25}}}, + {"expect":{"query":{"command":"sketch.inspect","path":["curves",9,"center_at",1],"value":14}}}, + {"expect":{"errors":0,"sketch_curves":{"own":10}}}, + {"shot":"sketch_pattern_even_center_after"} +] diff --git a/crates/ui-egui/tests/scenarios/sketch_pattern_two_directions.json b/crates/ui-egui/tests/scenarios/sketch_pattern_two_directions.json new file mode 100644 index 000000000..d9131bd76 --- /dev/null +++ b/crates/ui-egui/tests/scenarios/sketch_pattern_two_directions.json @@ -0,0 +1,38 @@ +[ + {"note":"The PATTERN toolbar opens a linear pattern with two independent picked direction lines. Copies follow the original and both lines."}, + {"call":"engine.execute","params":{"command":"sketch.create","params":{"plane":"XY"}}}, + {"call":"engine.execute","params":{"command":"sketch.circle.center","params":{"center":[5,5],"radius":2,"id":"seed"}}}, + {"call":"engine.execute","params":{"command":"sketch.line","params":{"points":[[0,-10],[20,-10]],"ids":["guide1"]}}}, + {"call":"engine.execute","params":{"command":"sketch.line","params":{"points":[[0,-30],[12,-14]],"ids":["guide2"]}}}, + {"call":"engine.execute","params":{"command":"sketch.constraint.fix","params":{"entities":["guide1","guide2"],"fixed":true}}}, + {"call":"ui.view","params":{"view":"top"}}, + {"click":{"handle":"toolbar:sketch.pattern.rectangular"}}, + {"click":{"sketch":[7,5]}}, + {"click":{"handle":"dialog:Direction"}}, + {"click":{"sketch":[10,-10]}}, + {"click":{"handle":"dialog:Direction 2"}}, + {"click":{"sketch":[6,-22]}}, + {"click":{"handle":"dialog:Quantity"}}, {"key":"A","cmd":true}, {"text":"3"}, + {"click":{"handle":"dialog:Spacing"}}, {"key":"A","cmd":true}, {"text":"20"}, + {"click":{"handle":"dialog:Quantity 2"}}, {"key":"A","cmd":true}, {"text":"2"}, + {"click":{"handle":"dialog:Spacing 2"}}, {"key":"A","cmd":true}, {"text":"10"}, + {"expect":{"dialog":"PatternRect","errors":0,"sketch_curves":{"own":3}}}, + {"shot":"sketch_pattern_two_directions_preview"}, + {"click":{"handle":"dialog:OK"}}, + {"expect":{"dialog":null,"errors":0,"sketch_curves":{"own":8}}}, + {"expect":{"query":{"command":"sketch.inspect","path":["curves",7,"center_at",0],"value":51}}}, + {"expect":{"query":{"command":"sketch.inspect","path":["curves",7,"center_at",1],"value":13}}}, + {"call":"ui.view","params":{"view":"fit"}}, + {"shot":"sketch_pattern_two_directions_before"}, + {"call":"engine.execute","params":{"command":"sketch.drag","params":{"entity":"seed.center","from":[5,5],"to":[7,8]}}}, + {"expect":{"query":{"command":"sketch.inspect","path":["curves",7,"center_at",0],"value":53}}}, + {"expect":{"query":{"command":"sketch.inspect","path":["curves",7,"center_at",1],"value":16}}}, + {"call":"engine.execute","params":{"command":"sketch.constraint.fix","params":{"entities":["seed"],"fixed":true}}}, + {"call":"engine.execute","params":{"command":"sketch.constraint.fix","params":{"entities":["guide2"],"fixed":false}}}, + {"call":"engine.execute","params":{"command":"sketch.constraint.fix","params":{"entities":["guide2.start"],"fixed":true}}}, + {"call":"engine.execute","params":{"command":"sketch.drag","params":{"entity":"guide2.end","from":[12,-14],"to":[16,-18]}}}, + {"expect":{"query":{"command":"sketch.inspect","path":["curves",7,"center_at",0],"value":55}}}, + {"expect":{"query":{"command":"sketch.inspect","path":["curves",7,"center_at",1],"value":14}}}, + {"expect":{"errors":0,"sketch_curves":{"own":8}}}, + {"shot":"sketch_pattern_two_directions_after"} +] diff --git a/docs/book/src/guide/files.md b/docs/book/src/guide/files.md index 888e04dfd..f0e5eeb30 100644 --- a/docs/book/src/guide/files.md +++ b/docs/book/src/guide/files.md @@ -91,6 +91,9 @@ in the file). It opens designs of every older format and upgrades them as they o from a newer version asks you to update instead of being guessed at. Development (nightly) builds save a format number no release reads yet. +Sketch patterns retain their live direction-line references and placement settings when saved. +Older patterns keep their fixed vector directions and original placement defaults. + Upgrading keeps what a design meant. Designs keep recorded body transfers, explicit 3D curve coordinate spaces and certified face bindings, alongside semantic configuration styles, associative free-form offsets and cylindrical emboss selections. Older ownership maps, geometry and diff --git a/docs/sketch-patterns.md b/docs/sketch-patterns.md new file mode 100644 index 000000000..1a0b7a4b3 --- /dev/null +++ b/docs/sketch-patterns.md @@ -0,0 +1,72 @@ +# Sketch patterns + +While editing a sketch, use the **PATTERN** toolbar group for **Mirror**, +**Rectangular Pattern** or **Circular Pattern**. On a narrow window the group +collapses to a dropdown. Select several curves before starting a tool, or add +them to its **Entities** input. Each tool previews the result before **OK**; +**Escape** cancels it. + +- **Mirror:** select the source geometry and a straight sketch **Mirror line**. + Symmetry constraints keep the copies linked to the source and mirror line. +- **Rectangular Pattern:** pick **Direction** and optionally **Direction 2**. + Each accepts a straight sketch line or an origin axis in the sketch plane. + The lines can meet at any angle. Each direction has its own column with a line + picker, quantity, spacing and two icon buttons: **Flip direction** and **Center**. + Without Center, copies extend from the original along the line from start to end; + Flip reverses that direction. Center distributes copies on both sides while the + original remains fixed. Quantities are totals including the original: 3 means + one copy on either side; 4 means two on one side and one on the other. Flip swaps + which side receives the extra copy. Both controls are independent for each direction. + Negative spacing reverses the chosen direction. With no direction selected, the first uses sketch X + and the second is perpendicular to the first. A second quantity of 1 makes + a single row. Picked sketch lines remain live references as they change. +- **Circular Pattern:** pick a **Center** point (or click empty sketch space), + then set **Quantity** and **Total angle**. A full turn distributes instances + evenly without duplicating the first; a partial turn includes both endpoints. + **Center** places copies on both angular sides of the original. **Flip direction** + reverses rotation and chooses the extra side for even totals. For six total holes + over 90 degrees, the spacing is 18 degrees: the original stays at 0 degrees, with + copies at +18, -18, +36, -36 and +54 degrees. Flip moves the last copy to -54 degrees. + Five holes over 90 degrees use 22.5-degree spacing and extend 45 degrees either side. + Without Center, a positive angle proceeds counterclockwise from the original; + Flip reverses it. + +Quantities include the original. Edit the original lines or their dimensions +to update their copies. Right-click a rectangular or circular pattern instance +and choose **Edit Sketch Pattern**, or double-click its pattern constraint badge, +to change the quantities, spacing, directions or angle. Rectangular and circular +patterns also appear as children beneath their sketch in the browser and left +feature history. Expand the sketch to find them; double-click a +pattern to open its saved editor, including from a finished sketch. Surviving copies keep +their IDs. Patterns support undo/redo and survive saving and reopening. + +The same operations are available through `sketch.mirror`, +`sketch.pattern.rectangular` and `sketch.pattern.circular`. For example: + +```json +{ + "command": "sketch.pattern.rectangular", + "params": { + "entities": ["l1", "l2", "l3"], + "direction": "guide1", + "direction2": "guide2", + "count": 3, + "spacing": 20, + "count2": 2, + "spacing2": 10, + "alignment": "center", + "alignment2": "center", + "reversed": false, + "reversed2": true + } +} +``` + +`direction` and `direction2` reference sketch line IDs. `dir` and `dir2` +instead accept fixed `[x,y]` vectors. Distances are millimetres; the circular +command's `angle` parameter is in degrees. The combined quantity is capped at 500. +Deleting a direction line breaks its rectangular pattern association and leaves +the remaining geometry in place; undo restores the association. + +Circular patterns accept the same `alignment` and `reversed` parameters, for example +`{"entities":["hole"],"center":[0,0],"count":6,"angle":90,"alignment":"center","reversed":false}`. From 5e9285ca75960461706136f644b12ede275993ce Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 16 Oct 2026 04:37:13 +0000 Subject: [PATCH 73/92] Regenerate THIRD-PARTY-LICENSES.txt and docs/features.md [skip ci] --- docs/features.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/features.md b/docs/features.md index 7b0495e3e..44a3e3666 100644 --- a/docs/features.md +++ b/docs/features.md @@ -91,9 +91,9 @@ SolidCraft's commands by area, generated by `cargo xtask features` from the comm | Break | `sketch.break` | SKETCH › MODIFY | | Sketch Scale | `sketch.scale` | SKETCH › MODIFY | | Move/Copy Sketch Entities | `sketch.move` | SKETCH › MODIFY | -| Mirror | `sketch.mirror` | SKETCH › CREATE | -| Circular Pattern | `sketch.pattern.circular` | SKETCH › CREATE | -| Rectangular Pattern | `sketch.pattern.rectangular` | SKETCH › CREATE | +| Mirror | `sketch.mirror` | SKETCH › PATTERN | +| Circular Pattern | `sketch.pattern.circular` | SKETCH › PATTERN | +| Rectangular Pattern | `sketch.pattern.rectangular` | SKETCH › PATTERN | | Project (P) | `sketch.project` | SKETCH › CREATE | | Intersect | `sketch.intersect` | SKETCH › CREATE | | Include 3D Geometry | `sketch.include_3d` | SKETCH › CREATE | From d29ca29578d54a012a62d824fb83bada57f77b77 Mon Sep 17 00:00:00 2001 From: "H. Conrad" <78785932+Ian-cmd-ops@users.noreply.github.com> Date: Thu, 15 Oct 2026 22:12:39 -0700 Subject: [PATCH 74/92] Perf/mesh collision (#1307) Thanks @Ian-cmd-ops. --- crates/kernel/Cargo.toml | 3 + .../tests/mesh_collision_equivalence.rs | 24 ++ vendor/README.md | 7 + vendor/truck-meshalgo/Cargo.toml | 2 + .../truck-meshalgo/src/analyzers/collision.rs | 291 +++++++++++++----- vendor/truck-meshalgo/src/analyzers/mod.rs | 3 + 6 files changed, 257 insertions(+), 73 deletions(-) create mode 100644 crates/kernel/tests/mesh_collision_equivalence.rs diff --git a/crates/kernel/Cargo.toml b/crates/kernel/Cargo.toml index 1ab5837c3..d174e08f6 100644 --- a/crates/kernel/Cargo.toml +++ b/crates/kernel/Cargo.toml @@ -25,4 +25,7 @@ spade = { workspace = true } rayon = { workspace = true } [dev-dependencies] +# The vendored crate tests never build in CI, so its equivalence checks run from kernel tests. +# Resolver 3 keeps this dev-only feature out of shipped builds. +truck-meshalgo = { workspace = true, features = ["test-hooks"] } proptest = { version = "1", default-features = false, features = ["std"] } diff --git a/crates/kernel/tests/mesh_collision_equivalence.rs b/crates/kernel/tests/mesh_collision_equivalence.rs new file mode 100644 index 000000000..19d9051b7 --- /dev/null +++ b/crates/kernel/tests/mesh_collision_equivalence.rs @@ -0,0 +1,24 @@ +//! Equivalence checks for SolidCraft's changes to the vendored truck crates. +//! +//! The vendored crates are outside the workspace, so their own tests never run in CI. Each +//! change that replaces an algorithm keeps the old one behind the crate's `test-hooks` feature +//! (on only for these tests) and these tests check the new one gives the same answers. + +use truck_meshalgo::analyzers::collision_test_hooks as collision; + +/// Mesh collision candidate search (sweep with per-triangle boxes): same collisions, same order. +#[test] +fn mesh_collision_same_as_before() { + match collision::same_collisions_in_the_same_order(0..200) { + Ok(n) => assert!(n > 0, "the random meshes produced no collisions to compare"), + Err(e) => panic!("{e}"), + } +} + +/// NaN coordinates in a mesh: the collision search goes on without a panic. +#[test] +fn mesh_collision_nan_triangles_do_not_panic() { + if let Err(e) = collision::nan_triangles_do_not_panic() { + panic!("{e}"); + } +} diff --git a/vendor/README.md b/vendor/README.md index 3b1e4ea5c..98202edf1 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -135,6 +135,13 @@ Changes: stops refining a face's grid at 16 384 points. Each edge is still divided once for both its faces. `triangulation` and `robust_triangulation` divide by the chord tolerance alone, as before. +- `analyzers/collision.rs`: the collision search builds each triangle's box once, filters the + sweep's open list by box overlap as it goes (it cloned the list for every triangle and built + both boxes for every pair), and runs the exact triangle tests on the rayon pool, in order + (sequential on wasm). Same collisions in the same order. The old search is kept as + `analyzers::collision_test_hooks`, behind a `test-hooks` feature that only + `solidcraft-kernel`'s tests turn on, and `crates/kernel/tests/mesh_collision_equivalence.rs` + compares the two. - `lib.rs`: compiler warnings no longer fail the build. Example, test and bench targets are dropped (their sources are not vendored). diff --git a/vendor/truck-meshalgo/Cargo.toml b/vendor/truck-meshalgo/Cargo.toml index 73c8199ca..0570e8f06 100644 --- a/vendor/truck-meshalgo/Cargo.toml +++ b/vendor/truck-meshalgo/Cargo.toml @@ -97,6 +97,8 @@ default = [ "tessellation", ] filters = [] +# Exposes equivalence checks for the SolidCraft kernel tests. Never on in shipped builds. +test-hooks = [] tessellation = [ "spade", "filters", diff --git a/vendor/truck-meshalgo/src/analyzers/collision.rs b/vendor/truck-meshalgo/src/analyzers/collision.rs index e435ce9d5..cf71ee8e7 100644 --- a/vendor/truck-meshalgo/src/analyzers/collision.rs +++ b/vendor/truck-meshalgo/src/analyzers/collision.rs @@ -97,53 +97,6 @@ where res } -fn colliding_segment_pairs(sort_endpoints: Vec) -> impl Iterator { - let mut current = [Vec::::new(), Vec::::new()]; - sort_endpoints - .into_iter() - .filter_map( - move |EndPoint { - r#type, - segnum, - index, - .. - }| match r#type { - EndPointType::Front => { - current[segnum].push(index); - Some(current[1 - segnum].clone().into_iter().map(move |i| { - if segnum == 0 { - (index, i) - } else { - (i, index) - } - })) - } - EndPointType::Back => { - let i = current[segnum] - .iter() - .enumerate() - .find(|(_, idx)| **idx == index) - .unwrap() - .0; - current[segnum].swap_remove(i); - None - } - }, - ) - .flatten() -} - -fn disjoint_bdbs(tri0: [Point3; 3], tri1: [Point3; 3]) -> bool { - let bdb0: BoundingBox = tri0.iter().collect(); - let bdb1: BoundingBox = tri1.iter().collect(); - bdb0.max()[0] < bdb1.min()[0] - || bdb1.max()[0] < bdb0.min()[0] - || bdb0.max()[1] < bdb1.min()[1] - || bdb1.max()[1] < bdb0.min()[1] - || bdb0.max()[2] < bdb1.min()[2] - || bdb1.max()[2] < bdb0.min()[2] -} - fn collide_seg_triangle(seg: [Point3; 2], tri: [Point3; 3]) -> Option { let ab = tri[1] - tri[0]; let bc = tri[2] - tri[1]; @@ -208,25 +161,99 @@ fn make_pos_tri(poly: &PolygonMesh, face: [StandardVertex; 3]) -> [Point3; 3] { array![i => poly.positions()[face[i].pos]; 3] } +/// Triangles of a mesh with their bounding boxes, each computed once. +fn boxed_triangles(poly: &PolygonMesh) -> Vec<([Point3; 3], BoundingBox)> { + poly.faces() + .triangle_iter() + .map(|face| { + let tri = make_pos_tri(poly, face); + (tri, tri.iter().collect()) + }) + .collect() +} + +/// Whether two triangles' bounding boxes miss each other (touching boxes do not miss). +#[inline(always)] +fn disjoint_boxes(bdb0: &BoundingBox, bdb1: &BoundingBox) -> bool { + bdb0.max()[0] < bdb1.min()[0] + || bdb1.max()[0] < bdb0.min()[0] + || bdb0.max()[1] < bdb1.min()[1] + || bdb1.max()[1] < bdb0.min()[1] + || bdb0.max()[2] < bdb1.min()[2] + || bdb1.max()[2] < bdb0.min()[2] +} + +/// Pairs of triangles (one from each mesh) whose bounding boxes overlap, in the order the +/// sweep along `unit` meets them. +/// +/// The sweep keeps the triangles whose interval along `unit` is open. When a triangle opens, +/// it pairs with every open triangle of the other mesh whose box it overlaps. The pairs and +/// their order are the same as the earlier version, which cloned the open list for every +/// triangle and rejected disjoint boxes afterwards (rebuilding both boxes for each pair). +fn candidate_pairs( + tris0: &[([Point3; 3], BoundingBox)], + tris1: &[([Point3; 3], BoundingBox)], + unit: Vector3, +) -> Vec<(usize, usize)> { + let endpoints = sorted_endpoints( + tris0.iter().map(|(t, _)| *t), + tris1.iter().map(|(t, _)| *t), + unit, + ); + let boxes = [tris0, tris1]; + let mut open = [Vec::::new(), Vec::::new()]; + let mut pairs = Vec::new(); + for EndPoint { + r#type, + segnum, + index, + .. + } in endpoints + { + match r#type { + EndPointType::Front => { + let mine = &boxes[segnum][index].1; + for &other in &open[1 - segnum] { + if !disjoint_boxes(mine, &boxes[1 - segnum][other].1) { + pairs.push(if segnum == 0 { + (index, other) + } else { + (other, index) + }); + } + } + open[segnum].push(index); + } + EndPointType::Back => { + // Every interval opens before it closes unless a NaN broke the sort. Then the + // interval stays open: more box tests, never a panic (the web build aborts on any). + if let Some(i) = open[segnum].iter().position(|idx| *idx == index) { + open[segnum].swap_remove(i); + } + } + } + } + pairs +} + fn collision(poly0: &PolygonMesh, poly1: &PolygonMesh) -> Vec<(Point3, Point3)> { let unit = match poly0.positions().is_empty() { true => return Vec::new(), false => hash::take_one_unit(poly0.positions()[0]), }; - let tris0 = poly0.faces().triangle_iter().collect::>(); - let tris1 = poly1.faces().triangle_iter().collect::>(); - let iter0 = tris0.iter().map(|face| make_pos_tri(poly0, *face)); - let iter1 = tris1.iter().map(|face| make_pos_tri(poly1, *face)); - colliding_segment_pairs(sorted_endpoints(iter0, iter1, unit)) - .filter_map(|(idx0, idx1)| { - let tri0 = make_pos_tri(poly0, tris0[idx0]); - let tri1 = make_pos_tri(poly1, tris1[idx1]); - match disjoint_bdbs(tri0, tri1) { - true => None, - false => collide_triangles(tri0, tri1), - } - }) - .collect() + let (tris0, tris1) = (boxed_triangles(poly0), boxed_triangles(poly1)); + let pairs = candidate_pairs(&tris0, &tris1, unit); + let test = |&(i, j): &(usize, usize)| collide_triangles(tris0[i].0, tris1[j].0); + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + // Indexed parallel collect: results in the same order as the sequential loop. + pairs.par_iter().filter_map(test).collect() + } + #[cfg(target_arch = "wasm32")] + { + pairs.iter().filter_map(test).collect() + } } fn are_colliding(poly0: &PolygonMesh, poly1: &PolygonMesh) -> Option<(Point3, Point3)> { @@ -234,18 +261,19 @@ fn are_colliding(poly0: &PolygonMesh, poly1: &PolygonMesh) -> Option<(Point3, Po true => return None, false => hash::take_one_unit(poly0.positions()[0]), }; - let tris0 = poly0.faces().triangle_iter().collect::>(); - let tris1 = poly1.faces().triangle_iter().collect::>(); - let iter0 = tris0.iter().map(|face| make_pos_tri(poly0, *face)); - let iter1 = tris1.iter().map(|face| make_pos_tri(poly1, *face)); - colliding_segment_pairs(sorted_endpoints(iter0, iter1, unit)).find_map(|(idx0, idx1)| { - let tri0 = make_pos_tri(poly0, tris0[idx0]); - let tri1 = make_pos_tri(poly1, tris1[idx1]); - match disjoint_bdbs(tri0, tri1) { - true => None, - false => collide_triangles(tri0, tri1), - } - }) + let (tris0, tris1) = (boxed_triangles(poly0), boxed_triangles(poly1)); + let pairs = candidate_pairs(&tris0, &tris1, unit); + let test = |&(i, j): &(usize, usize)| collide_triangles(tris0[i].0, tris1[j].0); + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + // The first collision in sweep order, as the sequential search returns. + pairs.par_iter().find_map_first(test) + } + #[cfg(target_arch = "wasm32")] + { + pairs.iter().find_map(test) + } } #[test] @@ -273,3 +301,120 @@ fn collide_triangles_test() { ]; assert!(collide_triangles(tri0, tri1).is_none()); } + +/// The candidate search before boxes were computed once and the open list stopped being +/// cloned: kept to check the new search finds the same collisions in the same order. +/// +/// Not part of the API. Built only for tests, or with the `test-hooks` feature, so the +/// SolidCraft kernel tests can run these checks in CI (this crate's own tests do not run there). +#[cfg(any(test, feature = "test-hooks"))] +#[doc(hidden)] +pub mod test_hooks { + use super::*; + + fn old_pairs(sort_endpoints: Vec) -> Vec<(usize, usize)> { + let mut current = [Vec::::new(), Vec::::new()]; + let mut out = Vec::new(); + for EndPoint { r#type, segnum, index, .. } in sort_endpoints { + match r#type { + EndPointType::Front => { + current[segnum].push(index); + for i in current[1 - segnum].clone() { + out.push(if segnum == 0 { (index, i) } else { (i, index) }); + } + } + EndPointType::Back => { + if let Some(i) = current[segnum].iter().position(|idx| *idx == index) { + current[segnum].swap_remove(i); + } + } + } + } + out + } + + fn old_disjoint(tri0: [Point3; 3], tri1: [Point3; 3]) -> bool { + let b0: BoundingBox = tri0.iter().collect(); + let b1: BoundingBox = tri1.iter().collect(); + disjoint_boxes(&b0, &b1) + } + + /// Small seeded generator (no extra dependency). + struct Lcg(u64); + impl Lcg { + fn unit(&mut self) -> f64 { + self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (self.0 >> 11) as f64 / (1u64 << 53) as f64 + } + /// On a coarse grid half the time, so shared vertices, touching boxes and + /// degenerate triangles come up. + fn coord(&mut self) -> f64 { + if self.unit() < 0.5 { (self.unit() * 8.0).floor() * 0.5 } else { self.unit() * 4.0 } + } + fn tri(&mut self) -> [Point3; 3] { + array![_ => Point3::new(self.coord(), self.coord(), self.coord()); 3] + } + } + + /// A NaN coordinate breaks the endpoint sort: the search must go on without a panic. + pub fn nan_triangles_do_not_panic() -> Result<(), String> { + let good = [Point3::new(0.0, 0.0, 0.0), Point3::new(1.0, 0.0, 0.0), Point3::new(0.0, 1.0, 0.0)]; + let nan = [Point3::new(f64::NAN, 0.0, 0.0), Point3::new(1.0, f64::NAN, 0.0), Point3::new(0.0, 1.0, 0.5)]; + let crossing = [Point3::new(0.2, 0.2, -1.0), Point3::new(0.2, 0.2, 1.0), Point3::new(0.6, 0.2, 0.0)]; + for (a, b) in [(vec![good, nan], vec![crossing, nan]), (vec![nan, nan], vec![nan]), (vec![nan], vec![good])] { + let ba: Vec<_> = a.iter().map(|t| (*t, t.iter().collect())).collect(); + let bb: Vec<_> = b.iter().map(|t| (*t, t.iter().collect())).collect(); + let r = std::panic::catch_unwind(|| candidate_pairs(&ba, &bb, Vector3::new(1.0, 0.0, 0.0))); + if r.is_err() { + return Err(format!("panicked on {a:?} / {b:?}")); + } + } + Ok(()) + } + + /// The new candidate search finds the same collisions, in the same order, as the old one + /// on random triangle sets. Returns how many collisions were compared. + pub fn same_collisions_in_the_same_order(seeds: std::ops::Range) -> Result { + let mut compared = 0; + for seed in seeds { + let mut r = Lcg(seed * 7919 + 1); + let n0 = 1 + (r.unit() * 60.0) as usize; + let n1 = 1 + (r.unit() * 60.0) as usize; + let t0: Vec<[Point3; 3]> = (0..n0).map(|_| r.tri()).collect(); + let t1: Vec<[Point3; 3]> = (0..n1).map(|_| r.tri()).collect(); + let unit = hash::take_one_unit(t0[0][0]); + + let old: Vec<(Point3, Point3)> = old_pairs(sorted_endpoints(t0.iter().copied(), t1.iter().copied(), unit)) + .into_iter() + .filter(|&(i, j)| !old_disjoint(t0[i], t1[j])) + .filter_map(|(i, j)| collide_triangles(t0[i], t1[j])) + .collect(); + + let b0: Vec<_> = t0.iter().map(|t| (*t, t.iter().collect())).collect(); + let b1: Vec<_> = t1.iter().map(|t| (*t, t.iter().collect())).collect(); + let new: Vec<(Point3, Point3)> = candidate_pairs(&b0, &b1, unit) + .into_iter() + .filter_map(|(i, j)| collide_triangles(t0[i], t1[j])) + .collect(); + + if old.len() != new.len() { + return Err(format!("seed {seed}: {} collisions before, {} now", old.len(), new.len())); + } + for (k, (a, b)) in old.iter().zip(&new).enumerate() { + if !(a.0 == b.0 && a.1 == b.1) { + return Err(format!("seed {seed}: collision {k} differs: {a:?} vs {b:?}")); + } + } + compared += old.len(); + } + Ok(compared) + } + + #[cfg(test)] + #[test] + fn hooks_pass() { + assert_eq!(nan_triangles_do_not_panic(), Ok(())); + let n = same_collisions_in_the_same_order(0..200); + assert!(matches!(n, Ok(n) if n > 0), "{n:?}"); + } +} diff --git a/vendor/truck-meshalgo/src/analyzers/mod.rs b/vendor/truck-meshalgo/src/analyzers/mod.rs index 993bc706d..292c8f1de 100644 --- a/vendor/truck-meshalgo/src/analyzers/mod.rs +++ b/vendor/truck-meshalgo/src/analyzers/mod.rs @@ -8,6 +8,9 @@ mod topology; mod volume; pub use collision::Collision; +#[cfg(feature = "test-hooks")] +#[doc(hidden)] +pub use collision::test_hooks as collision_test_hooks; pub use in_out_judge::IncludingPointInDomain; pub use point_cloud::WithPointCloud; pub use splitting::ExperimentalSplitters; From dc6eca6830466719ecd5563c495305e366aa0023 Mon Sep 17 00:00:00 2001 From: "H. Conrad" <78785932+Ian-cmd-ops@users.noreply.github.com> Date: Thu, 15 Oct 2026 22:19:42 -0700 Subject: [PATCH 75/92] Fix/shell saddle corners (#1316) Thanks @Ian-cmd-ops. --- crates/engine/tests/shell_regressions.rs | 88 +++++++++++++++++++++ crates/kernel/src/offset.rs | 98 +++++++++++++++++++----- tests/robustness/goldens.json | 3 +- 3 files changed, 167 insertions(+), 22 deletions(-) create mode 100644 crates/engine/tests/shell_regressions.rs diff --git a/crates/engine/tests/shell_regressions.rs b/crates/engine/tests/shell_regressions.rs new file mode 100644 index 000000000..5243877ff --- /dev/null +++ b/crates/engine/tests/shell_regressions.rs @@ -0,0 +1,88 @@ +//! Shell regressions found by the robustness fuzzer (tests/robustness/goldens.json). +//! +//! The box-on-box designs below have a saddle corner: where the top box's left face meets the +//! lower box's back face, four planar faces meet with convex and concave edges in turn (the +//! top box overhangs the lower box's back face). A shell splits that corner into two corners +//! joined by a new edge. +//! +//! Lower box `[0, 25] × [0, 17.5] × [0, 35]`, top box `[7.5, 22.5] × [0, 17.5 + o] × [35, 42.5]`. +//! With the bottom face open, a shell of thickness `t` leaves this cavity (for `o < 17.5 − 2t`): +//! +//! - in the lower box: `[t, 25 − t] × [t, 17.5 − t] × [0, 35 − t]` +//! - in the top box, over the lower box: `[7.5 + t, 22.5 − t] × [t, 17.5 − t] × [35 − t, 42.5 − t]` +//! - in the overhang: `[7.5 + t, 22.5 − t] × [17.5 − t, 17.5 + o − t] × [35 + t, 42.5 − t]` +//! +//! The shell's volume is the solid's volume less those three boxes. +use serde_json::json; +use solidcraft_engine::Session; + +fn run(s: &mut Session, id: &str, p: serde_json::Value) { + if let Err(e) = s.execute(id, &p) { + panic!("{id} {p}: {e}"); + } +} + +/// The box on a box, overhanging the lower box's back face by `o`. +fn box_on_box(o: f64) -> Session { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"height": 35.0, "length": 25.0, "width": 17.5})); + run(&mut s, "solid.box", json!({"corner": [7.5, 0.0, 35.0], "height": 7.5, "length": 15.0, "operation": "join", "width": 17.5 + o})); + s +} + +/// The shell's volume with the bottom face open (see the module comment). +fn open_bottom_shell_volume(o: f64, t: f64) -> f64 { + let solid = 25.0 * 17.5 * 35.0 + 15.0 * (17.5 + o) * 7.5; + let lower = (25.0 - 2.0 * t) * (17.5 - 2.0 * t) * (35.0 - t); + let above = (15.0 - 2.0 * t) * (17.5 - 2.0 * t) * 7.5; + let overhang = (15.0 - 2.0 * t) * o * (7.5 - 2.0 * t); + solid - lower - above - overhang +} + +/// Seed 83 (minimised): the overhang is 2.5 mm, and the shell opens the top box's left face. +/// The shell refused the saddle corner (`a corner whose faces don't meet the same way`). +#[test] +fn shell_box_on_box_overhanging_saddle_corner() { + let mut s = box_on_box(2.5); + run(&mut s, "solid.shell", json!({"faces": [[7.5, 17.5, 38.75]], "thickness": 1.5})); + sound(&s); +} + +/// The same saddle corner with the bottom open: every face round the corner moves, and the +/// volume is exact. +#[test] +fn shell_saddle_corner_volume_is_exact() { + for t in [1.0, 1.5] { + let mut s = box_on_box(2.5); + run(&mut s, "solid.shell", json!({"faces": [[12.5, 8.75, 0.0]], "thickness": t})); + sound(&s); + let (got, want) = (volume(&s), open_bottom_shell_volume(2.5, t)); + assert!((got - want).abs() < 1e-6 * want, "thickness {t}: shell volume {got}, want {want}"); + } +} + +/// An overhang (1 mm) thinner than the wall (1.5 mm): the overhang's cavity is only 1 mm deep. +/// A corner landing outside the solid, or a wall left thin, would change the volume. +#[test] +fn shell_saddle_corner_with_an_overhang_thinner_than_the_wall() { + let mut s = box_on_box(1.0); + run(&mut s, "solid.shell", json!({"faces": [[12.5, 8.75, 0.0]], "thickness": 1.5})); + sound(&s); + let (got, want) = (volume(&s), open_bottom_shell_volume(1.0, 1.5)); + assert!((got - want).abs() < 1e-6 * want, "shell volume {got}, want {want}"); +} + +fn volume(s: &Session) -> f64 { + s.model.state().bodies.iter().map(|b| solidcraft_kernel::measure(&b.body).map(|m| m.volume).unwrap_or(f64::NAN)).sum() +} + +fn sound(s: &Session) { + let errors: Vec<_> = s.model.results.iter().filter_map(|r| r.error.clone()).collect(); + assert!(errors.is_empty(), "{errors:?}"); + let st = s.model.state(); + assert_eq!(st.bodies.len(), 1, "one body"); + for b in &st.bodies { + assert_eq!(b.body.shell_count(), 1, "one shell"); + assert!(b.body.validity().is_empty(), "{:?}", b.body.validity()); + } +} diff --git a/crates/kernel/src/offset.rs b/crates/kernel/src/offset.rs index ae15a7502..7dd0c2490 100644 --- a/crates/kernel/src/offset.rs +++ b/crates/kernel/src/offset.rs @@ -459,6 +459,7 @@ fn split_corner( // normal, so its inside is to the left; the edge is convex when the face beyond it falls // away from there. let mut sign = 0.0f64; + let mut mixed = false; let mut pairs: Vec<(usize, usize)> = Vec::new(); for &(fi, na, ..) in &planes { for w in faces.get(fi)?.boundaries() { @@ -474,7 +475,7 @@ fn split_corner( continue; } if sign * s < 0.0 { - return None; + mixed = true; } sign = s.signum(); } @@ -483,33 +484,55 @@ fn split_corner( if sign == 0.0 { return None; } + // Which triples of faces may meet at a new corner. All convex or all concave: any triple + // whose point is inside all the other moved planes. Mixed (a saddle, such as a box on a + // box that overhangs its side): the faces round the corner in order, and each new corner + // on three faces in a row (the two new edges on the middle face meet there). A saddle's + // faces bound no convex region, so a right corner can be outside another face's moved + // plane, and the inside-all-the-others test does not apply. What keeps a corner in place + // is that it is where its middle face's two new edges meet; a corner past the far end of + // one of the corner's edges turns that edge round, and a face whose loops cross after the + // move is refused (both checked in `offset_body`). + let triples: Vec<[usize; 3]> = if mixed { + let ring = face_ring(&pairs, planes.len())?; + let n = ring.len(); + (0..n).map(|i| [ring[(i + n - 1) % n], ring[i], ring[(i + 1) % n]]).collect() + } else { + let mut t = Vec::new(); + for ia in 0..planes.len() { + for ib in ia + 1..planes.len() { + for ic in ib + 1..planes.len() { + t.push([planes[ia].0, planes[ib].0, planes[ic].0]); + } + } + } + t + }; + let plane_of = |fi: usize| planes.iter().find(|x| x.0 == fi); // Convex: the body's side, n·x ≤ d; concave: the outside's, n·x ≥ d. let side = -sign; let merge = size * 1e-6; let mut nodes: Vec<(Vec3, Vec)> = Vec::new(); - for (ia, a) in planes.iter().enumerate() { - for (ib, b) in planes.iter().enumerate().skip(ia + 1) { - for c in planes.iter().skip(ib + 1) { - let den = a.1.dot(b.1.cross(c.1)); - if den.abs() < 1e-9 { - continue; - } - let x = (b.1.cross(c.1) * a.3 + c.1.cross(a.1) * b.3 + a.1.cross(b.1) * c.3) * (1.0 / den); - if !x.is_finite() || x.dist(p) > size || planes.iter().any(|q| side * (q.1.dot(x) - q.3) > merge) { - continue; - } - let fs = [a.0, b.0, c.0]; - match nodes.iter_mut().find(|(q, _)| q.dist(x) < merge) { - Some((_, nf)) => { - for f in fs { - if !nf.contains(&f) { - nf.push(f); - } - } + for [fa, fb, fc] in triples { + let (a, b, c) = (plane_of(fa)?, plane_of(fb)?, plane_of(fc)?); + let den = a.1.dot(b.1.cross(c.1)); + if den.abs() < 1e-9 { + continue; + } + let x = (b.1.cross(c.1) * a.3 + c.1.cross(a.1) * b.3 + a.1.cross(b.1) * c.3) * (1.0 / den); + if !x.is_finite() || x.dist(p) > size || (!mixed && planes.iter().any(|q| side * (q.1.dot(x) - q.3) > merge)) { + continue; + } + let fs = [fa, fb, fc]; + match nodes.iter_mut().find(|(q, _)| q.dist(x) < merge) { + Some((_, nf)) => { + for f in fs { + if !nf.contains(&f) { + nf.push(f); } - None => nodes.push((x, fs.to_vec())), } } + None => nodes.push((x, fs.to_vec())), } } // Every face keeps a corner here, and every edge an end. @@ -527,6 +550,39 @@ fn split_corner( Some(nodes) } +/// The faces round a corner in order, from the pairs of faces on each of its edges: `None` +/// unless they form one simple ring of `count` faces (each face meets the corner once, between +/// exactly two neighbours). +fn face_ring(pairs: &[(usize, usize)], count: usize) -> Option> { + let mut next: HashMap> = HashMap::new(); + for &(a, b) in pairs { + for (x, y) in [(a, b), (b, a)] { + let ns = next.entry(x).or_default(); + if !ns.contains(&y) { + ns.push(y); + } + } + } + if next.len() != count || next.values().any(|ns| ns.len() != 2) { + return None; + } + let first = *next.keys().min()?; + let mut ring = vec![first]; + let mut prev = first; + let mut cur = *next.get(&first)?.first()?; + while cur != first { + if ring.len() >= count { + return None; + } + ring.push(cur); + let ns = next.get(&cur)?; + let to = if ns[0] == prev { ns[1] } else { ns[0] }; + prev = cur; + cur = to; + } + (ring.len() == count).then_some(ring) +} + /// The corners of a split corner (see [`split_corner`]) on face `face`, in order from corner /// `from` to corner `to`, along the new edges between them. fn split_path(nodes: &[(Vec3, Vec)], face: usize, from: usize, to: usize) -> Option> { diff --git a/tests/robustness/goldens.json b/tests/robustness/goldens.json index cc943915d..b6253d6fb 100644 --- a/tests/robustness/goldens.json +++ b/tests/robustness/goldens.json @@ -84,7 +84,7 @@ "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}, "81": {"area":4001.847983,"bodies":2,"edges":75,"error":null,"faces":29,"outcome":"ok","rejected":1,"shells":2,"steps":["revolved section","cut sphere","circular pattern","rectangular pattern","hole","join cylinder","join box","cut sphere"],"unsupported":2,"volume":13139.658749}, "82": {"area":3195.487112,"bodies":1,"edges":30,"error":null,"faces":13,"outcome":"ok","rejected":0,"shells":1,"steps":["box","hole","circular pattern","cut box"],"unsupported":0,"volume":5902.162954}, - "83": {"area":5125.0,"bodies":1,"edges":28,"error":"offset: a corner whose faces don't meet the same way after t","faces":12,"outcome":"failed","rejected":0,"shells":1,"steps":["box","join box","rectangular pattern","shell"],"unsupported":0,"volume":19250.0}, + "83": {"area":8489.059183,"bodies":1,"edges":97,"error":null,"faces":35,"outcome":"ok","rejected":0,"shells":2,"steps":["box","join box","rectangular pattern","shell","fillet","cut sphere","join box"],"unsupported":1,"volume":6217.394627}, "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}, @@ -122,6 +122,7 @@ {"reason":"#391 after merging main with #1213: seed 41 now reaches its second fillet (built since #1213), and the end-snap fix again drops a sliver edge the cuts left (94 to 93 edges); its steps, outcome, faces and shells are unchanged, volume moves by 0.005 mm³ (5185.215737 to 5185.221068) and area by 0.0014 mm²","seeds":[41]}, {"reason":"the chamfer bug is on main too, see #1390","seeds":[57]}, {"reason":"#1390: a chamfer of a convex edge that would grow the part is refused (TooLarge). Seed 57's 0.5 mm chamfer on the sphere cut's rim, which grew the part since #391 reordered its steps, is now refused, so the run goes on to its later steps and ends ok (16017.21 mm³, 24 faces)","seeds":[57]}, + {"reason":"Seed 83 builds: a shell splits a saddle corner (convex and concave edges in turn) into two corners","seeds":[83]}, {"reason":"seed 15 now cuts around a sealed void","seeds":[15]}, {"reason":"#1490: when the last-resort nudge fails both ways, two more screw axes are tried; seed 63's final box join (its face 0.00005 mm off the half-ring's cut face) now builds instead of being refused with an implausible volume, and the design goes on to its fillet","seeds":[63]} ] From 6f270f62591c43207e8fb9486d34474373172ac9 Mon Sep 17 00:00:00 2001 From: DuBearte <130190089+DuBearte@users.noreply.github.com> Date: Fri, 16 Oct 2026 01:35:15 -0400 Subject: [PATCH 76/92] Split Body: a sketch line as the splitting tool (#1552) (#1592) Thanks @DuBearte. --- crates/doc/src/document.rs | 6 +++ crates/doc/src/eval.rs | 23 ++++++++++- crates/doc/src/feature_walk_tests/fixtures.rs | 2 + .../src/feature_walk_tests/golden_exprs.txt | 5 +++ .../feature_walk_tests/golden_geometry.txt | 2 + .../src/feature_walk_tests/golden_refs.txt | 4 ++ .../format/pending/split-by-sketch-line.rs | 4 ++ crates/doc/src/lib.rs | 4 +- crates/engine/src/cmd/features.rs | 27 +++++++++++- crates/engine/src/tests.rs | 41 +++++++++++++++++++ crates/ui-egui/src/dialogs.rs | 30 +++++++++++--- crates/ui-egui/src/viewport.rs | 8 ++++ 12 files changed, 145 insertions(+), 11 deletions(-) create mode 100644 crates/doc/src/format/pending/split-by-sketch-line.rs diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 688a0a57a..81e79c06d 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -751,6 +751,12 @@ pub enum FeatureKind { plane: PlaneRef, #[serde(default, skip_serializing_if = "Option::is_none")] tool: Option, + /// A straight line of this sketch as the tool (#1552): the plane through it along the + /// sketch's normal, which follows the sketch. + #[serde(default, skip_serializing_if = "Option::is_none")] + sketch: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + line: Option, }, /// A construction axis (Fusion's CONSTRUCT axes). ConstructionAxis { diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 8f54b1fa8..8b42a9227 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -4400,10 +4400,17 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: } Ok(()) } - FeatureKind::Split { body, plane, tool } => { + FeatureKind::Split { body, plane, tool, sketch, line } => { 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::Unknown(format!("body `{body}`"))) }; let parts = match tool { + // A sketch line: the plane through it along the sketch's normal. + _ if sketch.is_some() || line.is_some() => { + let (Some(sketch), Some(line)) = (sketch, line) else { + return Err(DocError::Invalid("a sketch line tool needs both its sketch and its line".into())); + }; + kernel::split_by_plane(&mb.body, &sketch_line_plane(st, sketch.0, line)?)? + } // A face of a body (its surface extended). Some(t) => { let tb = st.body(&t.body).ok_or_else(|| DocError::Unknown(format!("body `{}`", t.body)))?; @@ -5267,3 +5274,17 @@ mod body_name_tests { assert!(began.elapsed() < std::time::Duration::from_secs(5), "{:?}", began.elapsed()); } } + +/// The plane a straight sketch line sweeps along its sketch's normal: through the line, its x +/// along the line and its y along the normal (a Split Body tool, #1552). +pub fn sketch_line_plane(st: &ModelState, sketch: u64, line: &str) -> Result { + let ss = st.sketch(sketch).ok_or_else(|| DocError::Unknown(format!("sketch {sketch}")))?; + let ci = ss.sketch.curve_index(line).ok_or_else(|| DocError::Unknown(format!("curve `{line}`")))?; + let (a, b) = match ss.sketch.segs(ci).as_slice() { + [solidcraft_geom::Seg2::Line { a, b }] => (*a, *b), + _ => return Err(DocError::Invalid(format!("`{line}` is not a straight line: split by a sketch line"))), + }; + let (wa, wb) = (ss.plane.to_world(a), ss.plane.to_world(b)); + let x = (wb - wa).normalized().ok_or_else(|| DocError::Invalid(format!("`{line}` has no length")))?; + Ok(Plane { origin: wa, x, y: ss.plane.normal() }) +} diff --git a/crates/doc/src/feature_walk_tests/fixtures.rs b/crates/doc/src/feature_walk_tests/fixtures.rs index eaf315dca..6a23ee71c 100644 --- a/crates/doc/src/feature_walk_tests/fixtures.rs +++ b/crates/doc/src/feature_walk_tests/fixtures.rs @@ -84,6 +84,7 @@ pub(super) fn fixtures() -> Vec<(&'static str, Value)> { ("draft", json!({"type": "draft", "faces": [o], "angle": "draft.angle", "neutral": plane("draft_neutral"), "pull": [0, 0, 1]})), ("construction_plane", json!({"type": "construction_plane", "plane": plane("cplane")})), ("split", json!({"type": "split", "body": "B", "plane": plane("split")})), + ("split_line", json!({"type": "split", "body": "B", "plane": plane("split_line")})), ( "construction_axis", json!({"type": "construction_axis", "def": {"type": "two_planes", "a": geo_plane("axis_a"), "b": geo_plane("axis_b")}}), @@ -203,6 +204,7 @@ pub(super) fn with_refs(name: &str, mut v: Value) -> Value { "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"]}), "split" | "surface_trim" => json!({"tool": tool}), + "split_line" => json!({"sketch": 6, "line": "l1"}), "surface_loft" => json!({"sections": [{"sketch": 4}, {"sketch": 5}]}), "split_face" => json!({"body": "B", "tool": tool, "sketch": 6}), "emboss" => json!({"face": {"body": "B", "at": o}, "targets": ["B"]}), diff --git a/crates/doc/src/feature_walk_tests/golden_exprs.txt b/crates/doc/src/feature_walk_tests/golden_exprs.txt index c21df3236..7a060857a 100644 --- a/crates/doc/src/feature_walk_tests/golden_exprs.txt +++ b/crates/doc/src/feature_walk_tests/golden_exprs.txt @@ -161,6 +161,11 @@ split Angle = split.angle (Angle) Offset = split.offset (Length) expressions: split.angle, split.offset +split_line + inputs: + Angle = split_line.angle (Angle) + Offset = split_line.offset (Length) + expressions: split_line.angle, split_line.offset construction_axis inputs: Angle = axis_a.angle (Angle) diff --git a/crates/doc/src/feature_walk_tests/golden_geometry.txt b/crates/doc/src/feature_walk_tests/golden_geometry.txt index 0f50600fd..32f8592e4 100644 --- a/crates/doc/src/feature_walk_tests/golden_geometry.txt +++ b/crates/doc/src/feature_walk_tests/golden_geometry.txt @@ -76,6 +76,8 @@ construction_plane moves: plane.axis_dir[0], plane.axis_dir[1], plane.axis_origin[0], plane.axis_origin[1], plane.axis_origin[2] split moves: 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] +split_line + moves: plane.axis_dir[0], plane.axis_dir[1], plane.axis_origin[0], plane.axis_origin[1], plane.axis_origin[2] construction_axis moves: def.a.plane.axis_dir[0], def.a.plane.axis_dir[1], def.a.plane.axis_origin[0], def.a.plane.axis_origin[1], def.a.plane.axis_origin[2], def.b.plane.axis_dir[0], def.b.plane.axis_dir[1], def.b.plane.axis_origin[0], def.b.plane.axis_origin[1], def.b.plane.axis_origin[2] construction_point_planes diff --git a/crates/doc/src/feature_walk_tests/golden_refs.txt b/crates/doc/src/feature_walk_tests/golden_refs.txt index edc123b41..9c56ab0b1 100644 --- a/crates/doc/src/feature_walk_tests/golden_refs.txt +++ b/crates/doc/src/feature_walk_tests/golden_refs.txt @@ -81,6 +81,10 @@ construction_plane split remap_refs: plane.base.base.name remap_bodies: body, tool.body +split_line + sketches: [6] + remap_refs: plane.base.base.name, sketch + remap_bodies: body construction_axis construction_point_planes construction_point_along diff --git a/crates/doc/src/format/pending/split-by-sketch-line.rs b/crates/doc/src/format/pending/split-by-sketch-line.rs new file mode 100644 index 000000000..dcd551656 --- /dev/null +++ b/crates/doc/src/format/pending/split-by-sketch-line.rs @@ -0,0 +1,4 @@ +//! A Split Body feature can take a straight sketch line as its tool (`sketch`, the sketch's +//! feature id, and `line`, the line's id), splitting by the plane through the line along the +//! sketch's normal (#1552). Older designs need no transformation: a split without them uses its +//! plane or face as before; 0.13.x asks for an update instead of splitting by the stored plane. diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 29f1d93a5..ae00b365d 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -59,8 +59,8 @@ 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, object_height, parse_metric_thread, pattern_matrices, - revolve_extent, revolve_extent_with_convention, select_profiles, sketch_hole_direction, state_in_frame, state_in_frame_at, through_all_distance, - world_state, world_state_reusing, + revolve_extent, revolve_extent_with_convention, select_profiles, sketch_hole_direction, sketch_line_plane, state_in_frame, state_in_frame_at, + through_all_distance, world_state, world_state_reusing, }; pub use expr::Expr; pub use names::{BodyName, FeatureName, SketchId}; diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs index eaf371aec..a86ad7bd6 100644 --- a/crates/engine/src/cmd/features.rs +++ b/crates/engine/src/cmd/features.rs @@ -105,7 +105,7 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("solid.split_body", "Split Body", split_body) .at("SOLID", "MODIFY") .icon("split") - .params("body: name; plane: XY|XZ|YZ|plane name|{origin, normal} — or tool: {body, point} (a face of a body, its surface extended)"), + .params("body: name; plane: XY|XZ|YZ|plane name|{origin, normal} — or tool: {body, point} (a face of a body, its surface extended) — or sketch: id, line: curve id (a straight sketch line, along the sketch's normal)"), CommandSpec::new("solid.press_pull", "Press Pull", press_pull) .at("SOLID", "MODIFY") .icon("presspull") @@ -1472,6 +1472,27 @@ fn split_body(s: &mut Session, p: &Value) -> Result { if s.model.state().body(&body).is_none() { return Err(bad(cmd, format!("no body `{body}`"))); } + // A straight sketch line as the tool: `sketch` and `line` (#1552). + if p.get("sketch").is_some_and(|v| !v.is_null()) || p.get("line").is_some_and(|v| !v.is_null()) { + let sketch = p.get("sketch").and_then(Value::as_u64).ok_or_else(|| bad(cmd, "`sketch` must be a sketch feature id"))?; + let line = str_(p, "line").ok_or_else(|| bad(cmd, "`line` must name a line of the sketch"))?.to_string(); + let st = s.model.state(); + if st.sketch(sketch).is_none() { + return Err(bad(cmd, format!("no sketch {sketch}"))); + } + solidcraft_doc::sketch_line_plane(&st, sketch, &line).map_err(|e| bad(cmd, e.to_string()))?; + return add_feature( + s, + p, + FeatureKind::Split { + body: BodyName(body), + plane: solidcraft_doc::PlaneRef::Origin { name: "XY".into() }, + tool: None, + sketch: Some(solidcraft_doc::SketchId(sketch)), + line: Some(line), + }, + ); + } // A face as the tool: `tool: {body, point}` (its surface extended); else a plane. if let Some(t) = p.get("tool").filter(|t| !t.is_null()) { let tb = t.get("body").and_then(Value::as_str).ok_or_else(|| bad(cmd, "`tool.body` must name a body"))?.to_string(); @@ -1488,11 +1509,13 @@ fn split_body(s: &mut Session, p: &Value) -> Result { body: BodyName(body), plane: solidcraft_doc::PlaneRef::Origin { name: "XY".into() }, tool: Some(solidcraft_doc::FaceAt { body: BodyName(tb), point: Position(point) }), + sketch: None, + line: None, }, ); } let plane = plane_param(s, p.get("plane"), cmd)?; - add_feature(s, p, FeatureKind::Split { body: BodyName(body), plane, tool: None }) + add_feature(s, p, FeatureKind::Split { body: BodyName(body), plane, tool: None, sketch: None, line: None }) } /// ISO 273 clearance hole diameters (close, normal, loose fit) for metric bolts. diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 02ff35551..d0be87f32 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1804,6 +1804,47 @@ fn split_body_by_a_face() { assert!(s.execute("solid.split_body", &json!({"body": "Block", "tool": {"body": "Tool", "point": [100, 0, 0]}})).is_err()); } +/// Split Body by a sketch line (#1552): the plane through the line along the sketch's normal +/// splits a box; the split follows the line when the sketch changes, the design saves the line, +/// and anything but a straight line of a sketch is refused. +#[test] +fn split_body_by_a_sketch_line() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 10, "width": 20, "height": 30, "body_name": "Block"})); + let sk = run(&mut s, "sketch.create", json!({"plane": "XY"}))["sketch"].as_u64().unwrap(); + run(&mut s, "sketch.line", json!({"points": [[4, -5], [4, 25]], "ids": ["cut"]})); + run(&mut s, "sketch.circle.center", json!({"center": [50, 50], "radius": 2, "id": "c"})); + run(&mut s, "sketch.finish", json!({})); + let volumes = |s: &Session| { + let st = s.world_state(); + let mut v: Vec = + st.bodies.iter().filter(|b| b.name.starts_with("Block")).map(|b| solidcraft_kernel::measure(&b.body).unwrap().volume).collect(); + v.sort_by(f64::total_cmp); + v + }; + for bad in [ + json!({"body": "Block", "sketch": sk, "line": "c"}), + json!({"body": "Block", "sketch": sk}), + json!({"body": "Block", "sketch": 999, "line": "cut"}), + ] { + assert!(s.execute("solid.split_body", &bad).is_err(), "{bad}"); + } + run(&mut s, "solid.split_body", json!({"body": "Block", "sketch": sk, "line": "cut"})); + let v = volumes(&s); + assert!(v.len() == 2 && rel(v[0], 2400.0) < 1e-6 && rel(v[1], 3600.0) < 1e-6, "{v:?}"); + // The split follows the line. + run(&mut s, "sketch.edit", json!({"sketch": sk})); + run(&mut s, "sketch.move_point", json!({"point": "cut.start", "to": [2, -5]})); + run(&mut s, "sketch.move_point", json!({"point": "cut.end", "to": [2, 25]})); + run(&mut s, "sketch.finish", json!({})); + let v = volumes(&s); + assert!(v.len() == 2 && rel(v[0], 1200.0) < 1e-6 && rel(v[1], 4800.0) < 1e-6, "{v:?}"); + // The design keeps the sketch and the line. + let saved: Value = serde_json::from_str(&s.doc.to_json()).unwrap(); + let split = saved["features"].as_array().and_then(|f| f.iter().find(|f| f["type"] == "split")).cloned().unwrap(); + assert_eq!((split["sketch"].as_u64(), split["line"].as_str()), (Some(sk), Some("cut")), "{split}"); +} + /// Fillet types: chord length (radius from the face angle) and a radius varying along the /// edge; volumes from the removed material. #[test] diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 33bba37f6..2f6911c6c 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -522,9 +522,10 @@ impl Dialog { Kind::AnglePlane { angle: "45 deg".into() }, vec![SelInput::new("Plane", PLANES, false), SelInput::new("Axis", AXES, false)], ), - "solid.split_body" => { - Dialog::new(Kind::Split, vec![SelInput::new("Body to split", BODIES, false), SelInput::new("Splitting tool", PLANES | FACES, false)]) - } + "solid.split_body" => Dialog::new( + Kind::Split, + vec![SelInput::new("Body to split", BODIES, false), SelInput::new("Splitting tool", PLANES | FACES | AXES, false)], + ), "solid.scale" => Dialog::new(Kind::Scale { factor: "2".into() }, vec![SelInput::new("Bodies", BODIES, true)]), "solid.offset_face" => Dialog::new(Kind::OffsetFaces { distance: "2 mm".into() }, vec![SelInput::new("Faces", PLANAR_FACES, true)]), "solid.thread" => { @@ -3889,7 +3890,19 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result, S Some((_, n)) => json!({"body": body, "plane": {"origin": pt(*point), "normal": pt(n)}}), None => json!({"body": body, "tool": {"body": b, "point": pt(*point)}}), }, - _ => return Err("pick a plane or a face".into()), + // A straight sketch line, in the sketch it was picked in (#1552). + Some(Sel::SketchCurve { id }) => { + let picked = d.extra.get("tool_sketch").and_then(Value::as_u64); + let st = s.world_state(); + let holding: Vec = st.sketches.iter().filter(|ss| ss.sketch.curve_index(id).is_some()).map(|ss| ss.feature).collect(); + let sketch = match picked { + Some(k) if holding.contains(&k) => k, + None if holding.len() == 1 => holding.first().copied().ok_or("pick a sketch line")?, + _ => return Err("pick the sketch line in the viewport".into()), + }; + json!({"body": body, "sketch": sketch, "line": id}) + } + _ => return Err("pick a plane, a face or a sketch line".into()), }; ("solid.split_body", p) } @@ -4866,12 +4879,17 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option { + FeatureKind::Split { body, plane, tool, sketch, line } => { let mut d = start("solid.split_body")?; if let Some(inp) = d.inputs.first_mut() { inp.items = vec![Sel::Body { name: body.to_string() }]; } - if let Some(inp) = d.inputs.get_mut(1) { + if let (Some(k), Some(id)) = (sketch, line) { + d.extra.insert("tool_sketch".into(), json!(k.0)); + if let Some(inp) = d.inputs.get_mut(1) { + inp.items = vec![Sel::SketchCurve { id: id.clone() }]; + } + } else if let Some(inp) = d.inputs.get_mut(1) { inp.items = match tool { Some(t) => face_sel(s, t.point.0).into_iter().collect(), None => plane_sel(s, plane).into_iter().collect(), diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 267a3bc05..95eb6fdae 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -1677,6 +1677,14 @@ pub(crate) fn dialog_pick(app: &mut SolveApp, hit: &Hit, sel: Sel) { }; d.extra.remove("path"); } + // Split Body's sketch line keeps the sketch it was picked in (curve ids repeat across sketches). + if matches!(d.kind, crate::dialogs::Kind::Split) { + if let Hit::SketchCurve { sketch, .. } = hit { + d.extra.insert("tool_sketch".into(), serde_json::json!(sketch)); + } else { + d.extra.remove("tool_sketch"); + } + } app.dialog = Some(d); } From dcffab09b1bd50e1a39bf8ed675b3f3289facc03 Mon Sep 17 00:00:00 2001 From: "H. Conrad" <78785932+Ian-cmd-ops@users.noreply.github.com> Date: Thu, 15 Oct 2026 22:54:29 -0700 Subject: [PATCH 77/92] =?UTF-8?q?Tessellation:=20point-in-trim=20tests=20s?= =?UTF-8?q?kip=20runs=20of=20segments=20the=20ray=20canno=E2=80=A6=20(#130?= =?UTF-8?q?9)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Thanks @Ian-cmd-ops. --- .../kernel/tests/tess_include_equivalence.rs | 16 ++ vendor/README.md | 5 + vendor/truck-meshalgo/src/tessellation/mod.rs | 3 + .../src/tessellation/triangulation.rs | 184 +++++++++++++++++- 4 files changed, 203 insertions(+), 5 deletions(-) create mode 100644 crates/kernel/tests/tess_include_equivalence.rs diff --git a/crates/kernel/tests/tess_include_equivalence.rs b/crates/kernel/tests/tess_include_equivalence.rs new file mode 100644 index 000000000..e6b946fdf --- /dev/null +++ b/crates/kernel/tests/tess_include_equivalence.rs @@ -0,0 +1,16 @@ +//! Equivalence check for SolidCraft's change to the vendored tessellator's point-in-trim test. +//! +//! The vendored crates are outside the workspace, so their own tests never run in CI. The old +//! test is kept behind the crate's `test-hooks` feature (on only for kernel tests) and this +//! checks the faster one gives the same answer everywhere it is probed. + +use truck_meshalgo::tessellation::include_test_hooks; + +/// Point-in-trim with run boxes: same inside/outside answer as before on more than 100k points. +#[test] +fn tessellation_include_same_as_before() { + match include_test_hooks::include_answers_as_before(0..120) { + Ok(n) => assert!(n > 100_000, "only {n} points checked"), + Err(e) => panic!("{e}"), + } +} diff --git a/vendor/README.md b/vendor/README.md index 98202edf1..3d4a592f1 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -142,6 +142,11 @@ Changes: `analyzers::collision_test_hooks`, behind a `test-hooks` feature that only `solidcraft-kernel`'s tests turn on, and `crates/kernel/tests/mesh_collision_equivalence.rs` compares the two. +- `tessellation/triangulation.rs`: the inside test of a face's boundary also skips runs of 32 + segments whose box, grown by the tolerance, the test's ray cannot meet. Same answers. The + old test is kept as `tessellation::include_test_hooks`, behind a `test-hooks` feature that + only `solidcraft-kernel`'s tests turn on, and `crates/kernel/tests/tess_include_equivalence.rs` + compares the two. - `lib.rs`: compiler warnings no longer fail the build. Example, test and bench targets are dropped (their sources are not vendored). diff --git a/vendor/truck-meshalgo/src/tessellation/mod.rs b/vendor/truck-meshalgo/src/tessellation/mod.rs index 1bcfd8a71..896de00f8 100644 --- a/vendor/truck-meshalgo/src/tessellation/mod.rs +++ b/vendor/truck-meshalgo/src/tessellation/mod.rs @@ -509,3 +509,6 @@ impl RobustMeshableShape } mod triangulation; +#[cfg(feature = "test-hooks")] +#[doc(hidden)] +pub use triangulation::include_test_hooks; diff --git a/vendor/truck-meshalgo/src/tessellation/triangulation.rs b/vendor/truck-meshalgo/src/tessellation/triangulation.rs index 3049e3893..b1b9b5a60 100644 --- a/vendor/truck-meshalgo/src/tessellation/triangulation.rs +++ b/vendor/truck-meshalgo/src/tessellation/triangulation.rs @@ -495,9 +495,49 @@ fn get_mindiff(u: f64, u0: f64, up: f64) -> f64 { } /// SolidCraft: the second field holds each loop's parameter box, so `include` skips loops that -/// cannot hold the point (a face with hundreds of holes meshed in quadratic time). +/// cannot hold the point (a face with hundreds of holes meshed in quadratic time). The third +/// holds, for each loop, the box of each run of [`RUN`] segments in a row, so `include` tests +/// only the runs its ray can meet (a long trim loop is otherwise crossed segment by segment +/// for every grid point and every triangle). #[derive(Debug, Default, Clone)] -struct PolyBoundary(Vec>, Vec>); +struct PolyBoundary(Vec>, Vec>, Vec>>); + +/// Segments per run in [`PolyBoundary`]'s third field. +const RUN: usize = 32; + +/// The box of each run of [`RUN`] segments of a closed loop (segment `i` joins point `i` to +/// point `i + 1`, the last back to the first). +fn run_boxes(curve: &[Point2]) -> Vec> { + let n = curve.len(); + (0..n.div_ceil(RUN)) + .map(|k| (k * RUN..((k + 1) * RUN).min(n)).flat_map(|i| [curve[i], curve[(i + 1) % n]]).collect()) + .collect() +} + +/// Whether the ray from `c` along `r`, started `margin` behind `c`, can meet `bdb` grown by +/// `margin` on every side. A segment the ray crosses (or passes within the tolerance of `c`) +/// has its crossing point in its box, so a run whose box the ray misses changes nothing. +fn ray_meets_box(c: Point2, r: Vector2, bdb: &BoundingBox, margin: f64) -> bool { + let (min, max) = (bdb.min(), bdb.max()); + let (mut t0, mut t1) = (-margin, f64::INFINITY); + for i in 0..2 { + let (lo, hi) = (min[i] - margin, max[i] + margin); + if r[i].abs() < 1e-300 { + if c[i] < lo || c[i] > hi { + return false; + } + continue; + } + let (a, b) = ((lo - c[i]) / r[i], (hi - c[i]) / r[i]); + let (a, b) = if a <= b { (a, b) } else { (b, a) }; + t0 = t0.max(a); + t1 = t1.min(b); + if t0 > t1 { + return false; + } + } + true +} fn normalize_range(curve: &mut Vec, compidx: usize, (u0, u1): (f64, f64)) { let p = curve[0]; @@ -649,7 +689,8 @@ impl PolyBoundary { } } let boxes = closed.iter().map(|curve| curve.iter().collect()).collect(); - Self(closed, boxes) + let runs = closed.iter().map(|curve| run_boxes(curve)).collect(); + Self(closed, boxes, runs) } /// whether `c` is included in the domain with boundary = `self`. @@ -663,11 +704,22 @@ impl PolyBoundary { let (min, max) = (bdb.min(), bdb.max()); !(c.x < min.x - margin || c.x > max.x + margin || c.y < min.y - margin || c.y > max.y + margin) }; + // Wide enough for every crossing the test below can find: within the tolerance of `c` + // (the boundary case) and anywhere along the ray, with room for rounding. + let scale = c.x.abs().max(c.y.abs()).max(1.0); + let ray_margin = 4.0 * TOLERANCE + 1e-9 * scale; self.0 .iter() .zip(&self.1) - .filter(|(_, bdb)| near(bdb)) - .flat_map(|(vec, _)| vec.iter().circular_tuple_windows()) + .zip(&self.2) + .filter(|((_, bdb), _)| near(bdb)) + .flat_map(|((vec, _), runs)| { + let n = vec.len(); + runs.iter() + .enumerate() + .filter(move |(_, rb)| ray_meets_box(c, r, rb, ray_margin)) + .flat_map(move |(k, _)| (k * RUN..((k + 1) * RUN).min(n)).map(move |i| (&vec[i], &vec[(i + 1) % n]))) + }) .try_fold(0_i32, move |counter, (p0, p1)| { let a = p0 - c; let b = p1 - c; @@ -1192,3 +1244,125 @@ fn par_bench() { }); println!("{}ms", instant.elapsed().as_millis()); } + +/// `include` before the runs: kept to check the new one answers the same everywhere. +/// +/// Not part of the API. Built only for tests, or with the `test-hooks` feature, so the +/// SolidCraft kernel tests can run this check in CI (this crate's own tests do not run there). +#[cfg(any(test, feature = "test-hooks"))] +#[doc(hidden)] +pub mod include_test_hooks { + use super::*; + + fn old_include(b: &PolyBoundary, c: Point2) -> bool { + let t = 2.0 * std::f64::consts::PI * HashGen::hash1(c); + let r = Vector2::new(f64::cos(t), f64::sin(t)); + let margin = 2.0 * TOLERANCE; + let near = |bdb: &BoundingBox| { + let (min, max) = (bdb.min(), bdb.max()); + !(c.x < min.x - margin || c.x > max.x + margin || c.y < min.y - margin || c.y > max.y + margin) + }; + b.0.iter() + .zip(&b.1) + .filter(|(_, bdb)| near(bdb)) + .flat_map(|(vec, _)| vec.iter().circular_tuple_windows()) + .try_fold(0_i32, move |counter, (p0, p1): (&Point2, &Point2)| { + let a = p0 - c; + let b = p1 - c; + let s0 = r.x * a.y - r.y * a.x; + let s1 = r.x * b.y - r.y * b.x; + let s2 = a.x * b.y - a.y * b.x; + let x = s2 / (s1 - s0); + if x.so_small() && s0 * s1 < 0.0 { + None + } else if x > 0.0 && s0 <= 0.0 && s1 > 0.0 { + Some(counter + 1) + } else if x > 0.0 && s0 >= 0.0 && s1 < 0.0 { + Some(counter - 1) + } else { + Some(counter) + } + }) + .map(|counter| counter > 0) + .unwrap_or(false) + } + + struct Lcg(u64); + impl Lcg { + fn unit(&mut self) -> f64 { + self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (self.0 >> 11) as f64 / (1u64 << 53) as f64 + } + } + + fn boundary(loops: Vec>) -> PolyBoundary { + let boxes = loops.iter().map(|l| l.iter().collect()).collect(); + let runs = loops.iter().map(|l| run_boxes(l)).collect(); + PolyBoundary(loops, boxes, runs) + } + + /// The point-in-trim test with run boxes answers as the old one did, on random loops + /// (some on a grid) probed at random, on vertices, on edges and just either side of them. + /// Returns how many points were checked. + pub fn include_answers_as_before(seeds: std::ops::Range) -> std::result::Result { + let mut checked = 0usize; + for seed in seeds { + let mut g = Lcg(seed * 104729 + 3); + // A wobbly outer loop and a few holes, up to 300 segments each, some on a grid. + let mut loops = Vec::new(); + for l in 0..1 + (g.unit() * 4.0) as usize { + let n = 3 + (g.unit() * 300.0) as usize; + let (cx, cy, rad) = if l == 0 { (0.0, 0.0, 10.0) } else { (g.unit() * 8.0 - 4.0, g.unit() * 8.0 - 4.0, 0.5 + g.unit() * 2.0) }; + let grid = g.unit() < 0.3; + let mut lp: Vec = (0..n) + .map(|i| { + let a = 2.0 * std::f64::consts::PI * i as f64 / n as f64; + let rr = rad * (0.7 + 0.3 * g.unit()); + let (x, y) = (cx + rr * a.cos(), cy + rr * a.sin()); + if grid { Point2::new((x * 4.0).round() / 4.0, (y * 4.0).round() / 4.0) } else { Point2::new(x, y) } + }) + .collect(); + if l > 0 { + lp.reverse(); + } + loops.push(lp); + } + let b = boundary(loops.clone()); + let mut wrong = None; + let mut probe = |c: Point2| { + if wrong.is_none() && b.include(c) != old_include(&b, c) { + wrong = Some(c); + } + checked += 1; + }; + for _ in 0..400 { + probe(Point2::new(g.unit() * 24.0 - 12.0, g.unit() * 24.0 - 12.0)); + } + for lp in &loops { + for i in 0..lp.len() { + let (p, q) = (lp[i], lp[(i + 1) % lp.len()]); + let t = g.unit(); + let on = p + (q - p) * t; + let d = q - p; + let nrm = Vector2::new(-d.y, d.x) * (1.0 / d.magnitude().max(1e-300)); + probe(p); + probe(on); + probe(on + nrm * (TOLERANCE * 0.5)); + probe(on + nrm * (TOLERANCE * 3.0)); + probe(on - nrm * (TOLERANCE * 3.0)); + } + } + if let Some(c) = wrong { + return Err(format!("seed {seed}: point {c:?} answered differently")); + } + } + Ok(checked) + } + + #[cfg(test)] + #[test] + fn hook_passes() { + let n = include_answers_as_before(0..120); + assert!(matches!(n, Ok(n) if n > 100_000), "{n:?}"); + } +} From 571122c4ba6668b8d91ea7f03bb7ba4985279b67 Mon Sep 17 00:00:00 2001 From: Mateusz Sych <151755914+SychPL@users.noreply.github.com> Date: Fri, 16 Oct 2026 07:54:34 +0200 Subject: [PATCH 78/92] Motion Trace: a point's path as a joint is driven or a study plays, kept as a 3D spline (#1529) Thanks @SychPL. --- ROADMAP.md | 1 + assets/icons/ui/source/icons.rs | 8 + assets/locales/de.json | 5 + assets/locales/en.json | 5 + assets/locales/fr.json | 5 + assets/locales/ja.json | 5 + assets/locales/ko.json | 5 + assets/locales/ru.json | 5 + assets/locales/uk.json | 5 + assets/locales/zh.json | 5 + crates/engine/src/cmd/joints_tests.rs | 230 +++++++++++++++++++ crates/engine/src/cmd/motion.rs | 178 ++++++++++++++ crates/sketch/src/wire.rs | 20 ++ crates/ui-egui/src/dialogs_assembly.rs | 34 ++- crates/ui-egui/src/dialogs_assembly_tests.rs | 50 ++++ crates/ui-egui/src/dialogs_trace.rs | 199 ++++++++++++++++ crates/ui-egui/src/workspace.rs | 1 + docs/book/src/guide/assemblies.md | 16 ++ skills/solidcraft-mechanisms/SKILL.md | 1 + 19 files changed, 769 insertions(+), 9 deletions(-) create mode 100644 crates/ui-egui/src/dialogs_trace.rs diff --git a/ROADMAP.md b/ROADMAP.md index 681339c85..1887bc9c8 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -56,6 +56,7 @@ PCB / Package, Render, Animation, Simulation, Manufacture/CAM, Drawings. | M8 | Surface workspace (#772). Done: Patch (sketch regions; edge loops of any shape and number of sides as one face, G0/G1/G2 to the faces beside each edge, through points, #759), 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. Proposed, in order: surface Extrude/Revolve/Sweep/Loft from open and closed curves (#757), Offset surface (#758), Unstitch and Reverse Normal (#766), Delete Face without healing (#768); Extend curved faces and edges (#760), mutual trim and trim by projected curves (#767), Untrim (#761), Thicken every surface kind (#765); Ruled (#762), Boundary surface and curve networks with G0/G1/G2 (#763), Blend surface (#764), sweep guide rails and two-rail sweeps (#771; orientation, twist and end scale done; loft rails #201), fillet between surface bodies (#769); continuity analysis, surface curvature combs and isocurves (#770) | 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), 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), 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 and Interference (overlaps shown red); joints in the timeline and the Browser | in progress | 32 | | M8 | Surface workspace (#772). Done: Patch (sketch regions; edge loops filled G0), 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. Proposed, in order: surface Extrude/Revolve/Sweep/Loft from open and closed curves (#757), Offset surface (#758), Unstitch and Reverse Normal (#766), Delete Face without healing (#768); Extend curved faces and edges (#760), mutual trim and trim by projected curves (#767), Untrim (#761), Thicken every surface kind (#765); Ruled (#762), Boundary surface and curve networks with G0/G1/G2 (#763), Patch with G1/G2 and general loops (#759), Blend surface (#764), sweep guide rails and two-rail sweeps (#771; orientation, twist and end scale done; loft rails #201), fillet between surface bodies (#769); continuity analysis, surface curvature combs and isocurves (#770) | 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), gears, rack and pinion and screws (motion links whose ratio follows picked radii, parameters or a pitch, also inside closed loops), 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 Trace (a picked point's path as a joint is driven or a study plays, closed loops following; kept as a 3D sketch spline), 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, Gear, Rack and Pinion, Screw and Interference (overlaps shown red); joints in the timeline and the Browser | in progress | 32 | | 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), gears, rack and pinion and screws (motion links whose ratio follows picked radii, parameters or a pitch, also inside closed loops), inverse kinematics (`joint.reach`: a part's point to a target through the joints on its chain, within limits and with loops closed, nearest pose and its stopper when out of reach; dragging a jointed part in the viewport moves it as far as its joints allow), 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), 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, Gear, Rack and Pinion, Screw 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 | | M11 | 2D drawings | deferred | — | diff --git a/assets/icons/ui/source/icons.rs b/assets/icons/ui/source/icons.rs index 64ba3d46d..2f342a8c5 100644 --- a/assets/icons/ui/source/icons.rs +++ b/assets/icons/ui/source/icons.rs @@ -1293,6 +1293,14 @@ pub(crate) fn paint_with(p: &Painter, r: Rect, name: &str, ink: Color32, fill: C pen.arc(12.0, 12.0, 8.5, 0.3, 4.6, a); pen.arrow((11.0, 20.4), (14.5, 20.3), a); } + // A crank on its pivot and the closed path its far end draws (accent). + "trace" => { + pen.curve([(15.0, 13.0), (22.0, 13.0), (23.0, 3.0), (15.0, 3.0)], a); + pen.curve([(15.0, 3.0), (8.0, 3.0), (9.0, 13.0), (15.0, 13.0)], a); + pen.line(&[(5.0, 20.0), (15.0, 13.0)], ink); + pen.circle(5.0, 20.0, 2.4, pen.fill, ink); + pen.dot(15.0, 13.0, a); + } "motion_link" => { pen.circle(7.0, 14.0, 4.5, pen.fill, ink); pen.circle(17.5, 9.0, 3.0, pen.fill, ink); diff --git a/assets/locales/de.json b/assets/locales/de.json index a66781c93..69381095e 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -228,6 +228,8 @@ "cmd.motion_list": "Bewegungsuntersuchungen auflisten", "cmd.motion_play": "Bewegungsuntersuchung abspielen", "cmd.motion_study": "Bewegungsuntersuchung", + "cmd.motion_trace": "Bewegungsbahn", + "cmd.motion_trace_keep": "Bewegungsbahn behalten", "cmd.occurrence_copy": "Einfügen (Instanz)", "cmd.occurrence_ground": "Festsetzen", "cmd.occurrence_move": "Instanz verschieben", @@ -549,6 +551,9 @@ "toolbar.image": "BILD", "toolbar.render": "RENDERN", "toolbar.render_scene": "SZENE", + "trace.points": "{count} Punkte entlang der Bahn", + "trace.stopped_by_contact": "Endet bei Probe {sample}: {a} würde {b} durchdringen", + "trace.stopped_by_loop": "Endet bei Probe {sample}: die Schleife über {joint} lässt sich nicht weiter schließen", "ui.1_degree_of_freedom": "1 Freiheitsgrad", "ui.3d_sketch": "3D-Skizze", "ui.about": "Über", diff --git a/assets/locales/en.json b/assets/locales/en.json index a43d5e635..5767b5ddd 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -429,6 +429,8 @@ "cmd.motion_list": "List Motion Studies", "cmd.motion_play": "Play Motion Study", "cmd.motion_study": "Motion Study", + "cmd.motion_trace": "Motion Trace", + "cmd.motion_trace_keep": "Keep Motion Trace", "cmd.occurrence_copy": "Paste (Instance)", "cmd.occurrence_ground": "Ground", "cmd.occurrence_move": "Move Occurrence", @@ -766,6 +768,9 @@ "toolbar.image": "IMAGE", "toolbar.render": "RENDER", "toolbar.render_scene": "SCENE", + "trace.points": "{count} points along the path", + "trace.stopped_by_contact": "Ends at sample {sample}: {a} would pass through {b}", + "trace.stopped_by_loop": "Ends at sample {sample}: the loop through {joint} can't close any further", "ui.1_degree_of_freedom": "1 degree of freedom", "ui.3d_mouse_speed": "3D mouse speed", "ui.3d_mouse_windows": "3D mouse", diff --git a/assets/locales/fr.json b/assets/locales/fr.json index ef81a808b..8e52631cb 100644 --- a/assets/locales/fr.json +++ b/assets/locales/fr.json @@ -409,6 +409,8 @@ "cmd.motion_list": "Lister les études de mouvement", "cmd.motion_play": "Lire l'étude de mouvement", "cmd.motion_study": "Étude de mouvement", + "cmd.motion_trace": "Trajectoire de mouvement", + "cmd.motion_trace_keep": "Conserver la trajectoire de mouvement", "cmd.occurrence_copy": "Coller (instance)", "cmd.occurrence_ground": "Fixer", "cmd.occurrence_move": "Déplacer l'occurrence", @@ -746,6 +748,9 @@ "toolbar.image": "IMAGE", "toolbar.render": "RENDU", "toolbar.render_scene": "SCÈNE", + "trace.points": "{count} points le long de la trajectoire", + "trace.stopped_by_contact": "Se termine à l'échantillon {sample} : {a} traverserait {b}", + "trace.stopped_by_loop": "Se termine à l'échantillon {sample} : la boucle passant par {joint} ne peut plus se fermer", "ui.1_degree_of_freedom": "1 degré de liberté", "ui.3d_mouse_speed": "Vitesse de la souris 3D", "ui.3d_mouse_windows": "Souris 3D", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 5cf189b37..350dccc75 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -429,6 +429,8 @@ "cmd.motion_list": "モーション スタディを一覧表示", "cmd.motion_play": "モーション スタディを再生", "cmd.motion_study": "モーション スタディ", + "cmd.motion_trace": "モーション トレース", + "cmd.motion_trace_keep": "モーション トレースを保持", "cmd.occurrence_copy": "貼り付け(インスタンス)", "cmd.occurrence_ground": "空間固定", "cmd.occurrence_move": "オカレンスを移動", @@ -766,6 +768,9 @@ "toolbar.image": "画像", "toolbar.render": "レンダリング", "toolbar.render_scene": "シーン", + "trace.points": "経路上の {count} 点", + "trace.stopped_by_contact": "サンプル {sample} で終了: {a} が {b} を通り抜けてしまいます", + "trace.stopped_by_loop": "サンプル {sample} で終了: {joint} を通るループはこれ以上閉じられません", "ui.1_degree_of_freedom": "自由度 1", "ui.3d_mouse_speed": "3D マウス速度", "ui.3d_mouse_windows": "3D マウス", diff --git a/assets/locales/ko.json b/assets/locales/ko.json index b091bd818..09c175fbd 100644 --- a/assets/locales/ko.json +++ b/assets/locales/ko.json @@ -228,6 +228,8 @@ "cmd.motion_list": "운동 연구 목록", "cmd.motion_play": "운동 연구 재생", "cmd.motion_study": "운동 연구", + "cmd.motion_trace": "모션 궤적", + "cmd.motion_trace_keep": "모션 궤적 유지", "cmd.occurrence_copy": "붙여넣기(인스턴스)", "cmd.occurrence_ground": "고정", "cmd.occurrence_move": "인스턴스 이동", @@ -549,6 +551,9 @@ "toolbar.image": "이미지", "toolbar.render": "렌더링", "toolbar.render_scene": "장면", + "trace.points": "경로를 따라 {count}개 점", + "trace.stopped_by_contact": "샘플 {sample}에서 끝남: {a}이(가) {b}을(를) 통과합니다", + "trace.stopped_by_loop": "샘플 {sample}에서 끝남: {joint}을(를) 지나는 루프를 더 이상 닫을 수 없습니다", "ui.1_degree_of_freedom": "자유도 1개", "ui.3d_sketch": "3D 스케치", "ui.about": "정보", diff --git a/assets/locales/ru.json b/assets/locales/ru.json index 9557c926f..30f1ab3b4 100644 --- a/assets/locales/ru.json +++ b/assets/locales/ru.json @@ -381,6 +381,8 @@ "cmd.motion_list": "Список исследований движения", "cmd.motion_play": "Воспроизвести исследование движения", "cmd.motion_study": "Исследование движения", + "cmd.motion_trace": "Траектория движения", + "cmd.motion_trace_keep": "Сохранить траекторию движения", "cmd.occurrence_copy": "Вставить (вхождение)", "cmd.occurrence_ground": "Закрепить", "cmd.occurrence_move": "Переместить вхождение", @@ -705,6 +707,9 @@ "toolbar.image": "ИЗОБРАЖЕНИЕ", "toolbar.render": "РЕНДЕРИНГ", "toolbar.render_scene": "СЦЕНА", + "trace.points": "{count} точек на траектории", + "trace.stopped_by_contact": "Заканчивается на отсчёте {sample}: {a} прошёл бы сквозь {b}", + "trace.stopped_by_loop": "Заканчивается на отсчёте {sample}: контур через {joint} дальше не замыкается", "ui.1_degree_of_freedom": "1 степень свободы", "ui.3d_mouse_speed": "Скорость 3D-мыши", "ui.3d_mouse_windows": "3D-мышь", diff --git a/assets/locales/uk.json b/assets/locales/uk.json index 8ed2feab0..bd52bef4f 100644 --- a/assets/locales/uk.json +++ b/assets/locales/uk.json @@ -386,6 +386,8 @@ "cmd.motion_list": "Список досліджень руху", "cmd.motion_play": "Відтворити дослідження руху", "cmd.motion_study": "Дослідження руху", + "cmd.motion_trace": "Траєкторія руху", + "cmd.motion_trace_keep": "Зберегти траєкторію руху", "cmd.occurrence_copy": "Вставити (екземпляр)", "cmd.occurrence_ground": "Закріпити", "cmd.occurrence_move": "Перемістити екземпляр", @@ -634,6 +636,9 @@ "timeline.reorder_many": "Перевпорядкувати операції", "timeline.ungroup": "Прибрати теки операцій", "to the next face": "до наступної грані", + "trace.points": "{count} точок на траєкторії", + "trace.stopped_by_contact": "Закінчується на відліку {sample}: {a} пройшов би крізь {b}", + "trace.stopped_by_loop": "Закінчується на відліку {sample}: контур через {joint} далі не замикається", "ui.1_degree_of_freedom": "1 ступінь вільності", "ui.3d_mouse_speed": "Швидкість 3D-миші", "ui.3d_mouse_windows": "3D-миша", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index fc26c8462..264d61d72 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -429,6 +429,8 @@ "cmd.motion_list": "列出运动研究", "cmd.motion_play": "播放运动研究", "cmd.motion_study": "运动研究", + "cmd.motion_trace": "运动轨迹", + "cmd.motion_trace_keep": "保留运动轨迹", "cmd.occurrence_copy": "粘贴(实例)", "cmd.occurrence_ground": "固定", "cmd.occurrence_move": "移动实例", @@ -766,6 +768,9 @@ "toolbar.image": "图像", "toolbar.render": "渲染", "toolbar.render_scene": "场景", + "trace.points": "路径上的 {count} 个点", + "trace.stopped_by_contact": "在采样 {sample} 处结束:{a} 会穿过 {b}", + "trace.stopped_by_loop": "在采样 {sample} 处结束:经过 {joint} 的环路无法再闭合", "ui.1_degree_of_freedom": "1 个自由度", "ui.3d_mouse_speed": "3D 鼠标速度", "ui.3d_mouse_windows": "3D 鼠标", diff --git a/crates/engine/src/cmd/joints_tests.rs b/crates/engine/src/cmd/joints_tests.rs index 66da370ed..e86571f8f 100644 --- a/crates/engine/src/cmd/joints_tests.rs +++ b/crates/engine/src/cmd/joints_tests.rs @@ -1179,5 +1179,235 @@ fn a_new_joint_starts_inside_its_limits_and_says_so() { assert!(r.get("warnings").is_none(), "{r}"); } +/// The trace's points as world points. +fn traced(r: &Value) -> Vec { + r["points"].as_array().into_iter().flatten().filter_map(crate::params::vec3).collect() +} + +/// A point rigidly carried from segment (a0, b0) to segment (a, b) in the XY plane. +fn carried(p0: Vec3, a0: Vec3, b0: Vec3, a: Vec3, b: Vec3) -> Vec3 { + let turn = (b.y - a.y).atan2(b.x - a.x) - (b0.y - a0.y).atan2(b0.x - a0.x); + let d = p0 - a0; + a + Vec3::new(d.x * turn.cos() - d.y * turn.sin(), d.x * turn.sin() + d.y * turn.cos(), d.z) +} + +/// A point on the four-bar's coupler, 10 mm off the line between its pins, traces the coupler +/// curve: the crank pin on its circle, the rocker pin where the coupler and rocker circles meet +/// (on the open branch), and the point carried with the pins. A motion study turning the crank +/// traces the same curve, and the design is left as it was. +#[test] +fn four_bar_coupler_point_traces_its_closed_form_curve() { + let (mut s, p0, q0) = four_bar(); + let d = (q0 - p0) * (1.0 / q0.dist(p0)); + let c0 = (p0 + q0) * 0.5 + Vec3::new(-d.y, d.x, 0.0) * 10.0; + let before = s.doc.clone(); + let p = json!({"occurrence": "Coupler", "point": [c0.x, c0.y, c0.z], "joint": "Crank", "from": 0, "to": 360, "samples": 73}); + let r = run(&mut s, "motion.trace", p); + assert_eq!(*s.doc, *before, "a trace leaves the design as it was"); + assert!(r["stopped_at"].is_null() && r["samples"] == 73, "{r}"); + let pts = traced(&r); + assert_eq!(pts.len(), 73); + let mut q = q0; + for (k, got) in pts.iter().enumerate() { + let v = 5.0 * k as f64; + if k > 0 { + q = rocker_pin(v - 5.0, v, q); + } + let th = (90.0 + v).to_radians(); + let want = carried(c0, p0, q0, Vec3::new(20.0 * th.cos(), 20.0 * th.sin(), 0.0), q); + assert!(near(*got, want), "{v}°: {got:?} wants {want:?}"); + } + assert!(pts.first().zip(pts.last()).is_some_and(|(a, b)| near(*a, *b)), "a full turn closes the curve"); + run(&mut s, "motion.study", json!({"name": "Turn", "steps": 72, "keys": [{"joint": "Crank", "points": [[0, 0], [72, 360]]}]})); + let r = run(&mut s, "motion.trace", json!({"occurrence": "Coupler", "point": [c0.x, c0.y, c0.z], "study": "Turn"})); + let from_study = traced(&r); + assert_eq!(from_study.len(), 73, "{r}"); + assert!(from_study.iter().zip(&pts).all(|(a, b)| near(*a, *b)), "{r}"); +} + +/// The middle of a slider-crank's rod: halfway between the crank pin on its circle and the wrist +/// pin at a·cos θ + √(b² − (a·sin θ)²). +#[test] +fn slider_crank_rod_traces_its_closed_form_curve() { + let (mut s, p0, s0) = slider_crank(); + let m0 = (p0 + s0) * 0.5; + let r = + run(&mut s, "motion.trace", json!({"occurrence": "Rod", "point": [m0.x, m0.y, m0.z], "joint": "Crank", "from": 0, "to": 360, "samples": 37})); + let pts = traced(&r); + assert_eq!(pts.len(), 37, "{r}"); + for (k, got) in pts.iter().enumerate() { + let th = (90.0 + 10.0 * k as f64).to_radians(); + let x = 15.0 * th.cos() + (40.0f64.powi(2) - (15.0 * th.sin()).powi(2)).sqrt(); + let want = (Vec3::new(15.0 * th.cos(), 15.0 * th.sin(), 0.0) + Vec3::new(x, 0.0, 0.0)) * 0.5; + assert!(near(*got, want), "{}°: {got:?} wants {want:?}", 10 * k); + } +} + +/// Driving the rocker past its swing stops where the loop can't close: the trace ends there. +#[test] +fn a_trace_ends_where_the_loop_stops_the_motion() { + let (mut s, _, q0) = four_bar(); + let start = q0.y.atan2(q0.x - 45.0).to_degrees(); + let r = run( + &mut s, + "motion.trace", + json!({"occurrence": "Rocker", "point": [q0.x, q0.y, q0.z], "joint": "Rocker", "from": 0, "to": 100, "samples": 21}), + ); + assert!(r["stopped_by_loop"].is_object(), "{r}"); + let k = r["stopped_at"].as_u64().unwrap_or(u64::MAX) as usize; + let pts = traced(&r); + assert!(k > 0 && k < 20 && pts.len() == k + 1 && r["samples"] == k + 1, "{r}"); + let angle = |p: &Vec3| p.y.atan2(p.x - 45.0).to_degrees(); + for (i, p) in pts.iter().take(k).enumerate() { + assert!((angle(p) - (start + 5.0 * i as f64)).abs() < 1e-6, "sample {i}: {}", angle(p)); + } + let limit = ((900.0f64 - 3625.0) / 3600.0).acos().to_degrees(); + let last = pts.last().map(angle).unwrap_or(f64::NAN); + assert!(last > limit - 5.0 && last <= limit + 1e-9, "stopped at {last}°, the limit is {limit}°"); +} + +/// Keep makes a 3D sketch spline through the trace, in one undo step. +#[test] +fn a_kept_trace_is_a_3d_sketch_spline() { + let (mut s, p0, q0) = four_bar(); + let c0 = (p0 + q0) * 0.5; + let p = json!({"occurrence": "Coupler", "point": [c0.x, c0.y, c0.z], "joint": "Crank", "from": 0, "to": 180, "samples": 19}); + let pts = traced(&run(&mut s, "motion.trace", p.clone())); + let features = s.doc.features.len(); + let r = run(&mut s, "motion.trace.keep", p); + assert_eq!((r["name"].as_str(), r["points"].as_u64()), (Some("Motion Trace1"), Some(19)), "{r}"); + assert!(s.active_sketch.is_none(), "the sketch is left"); + let id = r["sketch"].as_u64().unwrap_or(0); + let sk = s.doc.sketch(id).cloned().unwrap_or_default(); + assert!(sk.view.three_d && sk.wires.len() == 1, "{r}"); + let fit = sk.wires.first().map(|w| w.fit.clone()).unwrap_or_default(); + assert!(fit.len() == pts.len() && fit.iter().zip(&pts).all(|(a, b)| a.dist(*b) < 1e-9), "{fit:?}"); + let again = json!({"occurrence": "Coupler", "point": [0, 0, 0], "joint": "Crank", "from": 0, "to": 90}); + assert_eq!(run(&mut s, "motion.trace.keep", again)["name"], "Motion Trace2"); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.features.len(), features); + // A point on the ground does not move: there is nothing to keep. + let e = s.execute("motion.trace.keep", &json!({"occurrence": "Ground", "point": [0, 0, 0], "joint": "Crank", "from": 0, "to": 90})).unwrap_err(); + assert!(e.to_string().contains("does not move"), "{e}"); +} + +/// A full turn kept closes exactly on its start, also when the sample before the end lies a hair +/// from it (a study keyed to 359.99999° one step before 360°). +#[test] +fn a_kept_full_turn_closes_on_its_start() { + let mut s = Session::default(); + part(&mut s, "Ground", [-1.0, -1.0, -5.0]); + part(&mut s, "Arm", [0.0, -1.0, 0.0]); + let g = occ(&s, "Ground"); + run(&mut s, "occurrence.ground", json!({"occurrence": g, "grounded": true})); + pin(&mut s, "revolute", "Pivot", "Ground", "Arm", Vec3::ZERO, Vec3::Z); + run(&mut s, "motion.study", json!({"name": "Turn", "steps": 5, "keys": [{"joint": "Pivot", "points": [[0, 0], [4, 359.99999], [5, 360]]}]})); + let r = run(&mut s, "motion.trace.keep", json!({"occurrence": "Arm", "point": [1, 0, 0], "study": "Turn"})); + let id = r["sketch"].as_u64().unwrap_or(0); + let fit = s.doc.sketch(id).ok().and_then(|sk| sk.wires.first().map(|w| w.fit.clone())).unwrap_or_default(); + assert_eq!(fit.len(), 5, "{fit:?}"); + assert_eq!(fit.first(), fit.last(), "{fit:?}"); +} + +/// Kept while a component is active and shown moved (a move not captured yet): the spline goes +/// in the root, where no joint moves it, through the traced points; the component stays active. +#[test] +fn a_trace_kept_in_a_moved_component_stays_on_the_path() { + let (mut s, p0, q0) = four_bar(); + let crank = occ(&s, "Crank"); + let c0 = (p0 + q0) * 0.5; + let p = json!({"occurrence": "Coupler", "point": [c0.x, c0.y, c0.z], "joint": "Crank", "from": 0, "to": 90, "samples": 4}); + let pts = traced(&run(&mut s, "motion.trace", p.clone())); + run(&mut s, "component.activate", json!({"component": "Crank", "occurrence": crank, "path": [crank]})); + run(&mut s, "occurrence.move", json!({"occurrence": crank, "translate": [0, 0, 100], "capture": false})); + let active = (s.active_component, s.active_occurrence_path.clone()); + let r = run(&mut s, "motion.trace.keep", p); + assert_eq!((s.active_component, s.active_occurrence_path.clone()), active); + let id = r["sketch"].as_u64().unwrap_or(0); + assert_eq!(s.doc.feature(id).map(|f| f.component), Some(0), "{r}"); + let fit = s.doc.sketch(id).ok().and_then(|sk| sk.wires.first().map(|w| w.fit.clone())).unwrap_or_default(); + assert!(fit.len() == pts.len() && fit.iter().zip(&pts).all(|(a, b)| near(*a, *b)), "{fit:?} wants {pts:?}"); +} + +/// A part inside a sub-assembly placed twice: the occurrence path picks the instance traced. The +/// second Arm turns about its pivot and its Tip goes round; the first Arm, and so the Tip at its +/// first placement, stays put. +#[test] +fn a_trace_follows_the_instance_its_path_names() { + let mut s = Session::default(); + part(&mut s, "Ground", [-1.0, -1.0, -5.0]); + let g = occ(&s, "Ground"); + run(&mut s, "occurrence.ground", json!({"occurrence": g, "grounded": true})); + run(&mut s, "component.activate", json!({"component": "root"})); + let arm = run(&mut s, "component.create", json!({"name": "Arm"})); + run(&mut s, "component.create", json!({"name": "Tip"})); + run(&mut s, "solid.box", json!({"length": 2, "width": 2, "height": 2, "corner": [10, 0, 0]})); + run(&mut s, "component.activate", json!({"component": "root"})); + let second = run(&mut s, "occurrence.copy", json!({"component": arm["component"], "translate": [0, 50, 0]}))["occurrence"].as_u64().unwrap_or(0); + let at = |o: Value| json!({"occurrence": o, "point": [0, 50, 0], "z": [0, 0, 1]}); + run(&mut s, "joint.create", json!({"type": "revolute", "a": at(json!(g)), "b": at(json!(second)), "flip": true, "name": "Pivot"})); + let tip = occ(&s, "Tip"); + let trace = |s: &mut Session, o: Value| { + traced(&run(s, "motion.trace", json!({"occurrence": o, "point": [11, 51, 1], "joint": "Pivot", "from": 0, "to": 90, "samples": 3}))) + }; + let turned = trace(&mut s, json!([second, tip])); + let pivot = Vec3::new(0.0, 50.0, 1.0); + assert!(turned.iter().all(|p| (p.dist(pivot) - 122f64.sqrt()).abs() < 1e-6), "{turned:?}"); + assert!(turned.first().zip(turned.last()).is_some_and(|(a, b)| (a.dist(*b) - 244f64.sqrt()).abs() < 1e-6), "a quarter turn: {turned:?}"); + let first = trace(&mut s, json!(tip)); + assert!(first.iter().all(|p| p.dist(Vec3::new(11.0, 51.0, 1.0)) < 1e-9), "{first:?}"); + assert!(s.execute("motion.trace", &json!({"occurrence": [tip, second], "point": [0, 0, 0], "joint": "Pivot", "from": 0, "to": 90})).is_err()); + assert!(s.execute("motion.trace", &json!({"occurrence": vec![second; 65], "point": [0, 0, 0], "joint": "Pivot", "from": 0, "to": 90})).is_err()); +} + +/// Trace params come from scripts and the control channel: bad ones are refused, never a panic. +#[test] +fn hostile_trace_params_are_refused() { + let (mut s, _, _) = four_bar(); + run(&mut s, "motion.study", json!({"name": "Turn", "steps": 4, "keys": [{"joint": "Crank", "points": [[0, 0], [4, 90]]}]})); + let base = json!({"occurrence": "Coupler", "point": [0, 0, 0], "joint": "Crank", "from": 0, "to": 90}); + let with = |k: &str, v: Value| { + let mut p = base.clone(); + p[k] = v; + p + }; + let without = |k: &str| { + let mut p = base.clone(); + p.as_object_mut().map(|o| o.remove(k)); + p + }; + for p in [ + with("samples", json!(0)), + with("samples", json!(1)), + with("samples", json!(501)), + with("samples", json!(1e300)), + with("samples", json!(-3)), + with("samples", json!("many")), + with("point", json!([f64::MAX, 0, 0])), + with("point", json!([0, 0])), + with("point", json!("here")), + without("point"), + with("occurrence", json!("Nowhere")), + without("occurrence"), + with("joint", json!("Nowhere")), + with("index", json!(1)), + with("index", json!(-1)), + with("from", json!("nonsense +")), + with("to", json!(1e300)), + without("from"), + without("to"), + with("study", json!("Turn")), + with("study", json!(null)), + without("joint"), + ] { + for cmd in ["motion.trace", "motion.trace.keep"] { + assert!(s.execute(cmd, &p).is_err(), "{cmd} {p}"); + } + } + run(&mut s, "joint.as_built", json!({"type": "rigid", "a": "Ground", "b": "Crank", "name": "Lock"})); + assert!(s.execute("motion.trace", &with("joint", json!("Lock"))).is_err(), "a rigid joint does not move"); +} + #[path = "joints_coupling_tests.rs"] mod coupling; diff --git a/crates/engine/src/cmd/motion.rs b/crates/engine/src/cmd/motion.rs index 33332ca01..2e5759119 100644 --- a/crates/engine/src/cmd/motion.rs +++ b/crates/engine/src/cmd/motion.rs @@ -17,6 +17,14 @@ use crate::{EngineError, Result, Session}; #[path = "contact_sweep.rs"] mod contact_sweep; +macro_rules! trace_doc { + () => { + "occurrence: id|name, or an occurrence path [ids] (an instance inside sub-assemblies); point: [x,y,z] world point on it, where it is placed now; study: id|name, or joint: id|name with from and \ + to (degrees for angles, mm for distances, or expressions) and index? (which value, default 0); samples? (2…500, default \ + the study's steps + 1, or 100) - the point's path as the study plays or the joint is driven, closed loops following" + }; +} + pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("contact.enable_sets", "Enable Contact Sets", enable_sets).at("SOLID", "ASSEMBLE").icon("joint").params( "enabled?: bool (default true) — driving joints and motion studies stop where bodies in one contact set would pass through each other", @@ -46,6 +54,16 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("motion.export", "Export Motion Study", export) .noundo() .params("study; samples? (default steps + 1); path? (.json or .csv) → occurrence positions per step (the design is not changed)"), + CommandSpec::new("motion.trace", "Motion Trace", trace).at("SOLID", "ASSEMBLE").icon("trace").noundo().params(concat!( + trace_doc!(), + " → points: [[x,y,z]…] world positions, samples (taken), stopped_at (the sample where the motion stopped short; the trace \ + ends there), stopped_by_loop, stopped_by_contact (the design is not changed)" + )), + CommandSpec::new("motion.trace.keep", "Keep Motion Trace", keep_trace).params(concat!( + trace_doc!(), + "; name? (default Motion TraceN) - keeps the trace as a 3D sketch spline through its points (a new sketch with 3D Sketch \ + on, in the root component, where no joint moves it; a fixed curve, it does not follow later changes) → sketch, name, curves, points" + )), CommandSpec::new("motion.list", "List Motion Studies", list_studies).noundo(), CommandSpec::new("motion.delete", "Delete Motion Study", delete_study).params("study"), CommandSpec::new("explode.create", "Exploded View", explode_create).at("SOLID", "ASSEMBLE").icon("joint").params( @@ -658,6 +676,166 @@ fn export(s: &mut Session, p: &Value) -> Result { Ok(out) } +/// Most samples of a motion trace: each is a solve, and a kept trace keeps every one as a fit +/// point of its spline. +const MAX_TRACE: usize = solidcraft_sketch::MAX_FIT_POINTS; + +/// The joint values a trace drives to at sample `k` of `n`. +type Plan = Box Vec<(u64, Vec)>>; + +/// Where a point of an occurrence goes as a study plays or a joint is driven: its world +/// positions, sampled on a copy (the design is not changed). Each sample is driven from the one +/// before, so closed loops follow on their branch and contact sets stop them; the trace ends at +/// the sample where the motion stops short. Returns the points and the answer without them. +fn sample_trace(s: &Session, p: &Value, cmd: &str) -> Result<(Vec, Value)> { + // The placement traced: an occurrence path through nested sub-assemblies (one instance of + // each), or an occurrence at its first placement (none: the root). + let path: Vec = match p.get("occurrence") { + Some(Value::Array(ids)) if ids.len() <= 64 => { + ids.iter().map(|v| v.as_u64().ok_or_else(|| bad(cmd, "an occurrence path lists occurrence ids"))).collect::>()? + } + Some(Value::Array(_)) => return Err(bad(cmd, "an occurrence path has at most 64 ids")), + v => { + let occ = occurrence_id(s, v, cmd)?; + match s.doc.occurrences.iter().find(|o| o.id == occ) { + Some(o) => s.doc.first_path(o.parent).into_iter().chain([o.id]).collect(), + None => Vec::new(), + } + } + }; + let at = p.get("point").and_then(vec3).filter(|v| v.len() < 1e7).ok_or_else(|| bad(cmd, "`point` must be [x, y, z], a world point"))?; + let mut t = s.scratch(); + // Traced from where the parts are placed: moves only shown (an exploded view, a move not + // captured yet) are not where the joints are solved. + t.pending_moves.clear(); + let world = |t: &Session| -> Result { + if path.is_empty() { + Ok(solidcraft_doc::IDENTITY) + } else { + t.occurrence_placement(&path).map(|o| o.world).map_err(|e| bad(cmd, e.to_string())) + } + }; + let local = solidcraft_doc::mat_inverse(&world(&t)?) + .map(|m| solidcraft_doc::apply_point(&m, at)) + .ok_or_else(|| bad(cmd, "the occurrence's placement is not invertible"))?; + let samples = |default: usize| match p.get("samples") { + Some(v) => v + .as_f64() + .filter(|n| n.is_finite() && *n >= 2.0 && *n <= MAX_TRACE as f64) + .map(|n| n.round() as usize) + .ok_or_else(|| bad(cmd, format!("`samples` must be 2…{MAX_TRACE}"))), + None => Ok(default), + }; + let (n, given, plan): (usize, BTreeSet<(u64, usize)>, Plan) = match (p.get("study"), p.get("joint")) { + (Some(_), Some(_)) => return Err(bad(cmd, "give `study` or `joint`, not both")), + (Some(_), None) => { + let m = s.doc.assembly.studies.get(study_index(s, p, cmd)?).cloned().ok_or_else(|| bad(cmd, "study"))?; + let n = samples((m.steps as usize).saturating_add(1).clamp(2, MAX_TRACE))?; + (n, keyed(&m), Box::new(move |t, k, n| values_at(t, &m, f64::from(m.steps) * k as f64 / (n - 1) as f64))) + } + (None, Some(j)) => { + let id = joint_id(s, Some(j), cmd)?; + let kind = s.doc.assembly.joints.iter().find(|j| j.id == id).map(|j| j.kind).ok_or_else(|| bad(cmd, "joint"))?; + 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 => 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 end = |key: &str| match p.get(key) { + Some(v) => value(s, v, kind.is_angle(index), cmd), + None => Err(bad(cmd, format!("give `from` and `to`: the joint's values the trace runs between (no `{key}`)"))), + }; + let (from, to) = (end("from")?, end("to")?); + let plan: Plan = Box::new(move |t, k, n| { + 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 = from + (to - from) * k as f64 / (n - 1) as f64; + } + vec![(id, q)] + }); + (samples(100)?, BTreeSet::from([(id, index)]), plan) + } + (None, None) => return Err(bad(cmd, "give a `study`, or a `joint` with `from` and `to`")), + }; + let mut points = Vec::new(); + let mut stop = (Value::Null, Value::Null, Value::Null); + for k in 0..n { + let want = plan(&t, k, n); + let (r, _) = drive_with_contact(&mut t, &want, &given)?; + points.push(solidcraft_doc::apply_point(&world(&t)?, local)); + if r["stopped_by_loop"].is_object() || r["stopped_by_contact"].is_object() { + stop = (json!(k), r["stopped_by_loop"].clone(), r["stopped_by_contact"].clone()); + break; + } + } + let name = s.doc.occurrences.iter().find(|o| Some(&o.id) == path.last()).map_or_else(|| "root".to_string(), |o| o.name.clone()); + let out = json!({"occurrence": name, "samples": points.len(), "stopped_at": stop.0, "stopped_by_loop": stop.1, "stopped_by_contact": stop.2}); + Ok((points, out)) +} + +fn trace(s: &mut Session, p: &Value) -> Result { + let (points, mut out) = sample_trace(s, p, "motion.trace")?; + out["points"] = points.iter().map(|v| json!([v.x, v.y, v.z])).collect(); + Ok(out) +} + +/// The trace as a 3D sketch spline, in one undo step: a new sketch of the root component (the +/// world, which no joint moves) with 3D Sketch on and the spline through the trace's points. +fn keep_trace(s: &mut Session, p: &Value) -> Result { + let cmd = "motion.trace.keep"; + let (mut points, mut out) = sample_trace(s, p, cmd)?; + // Where the motion stood still (at a limit or a stop), one fit point. + points.dedup_by(|a, b| a.dist(*b) < 1e-6); + // A full cycle comes back to where it started (to the loop solver's tolerance): the spline + // closes there, smoothly, through the start itself (and a sample that would double it goes). + if points.len() > 3 + && let (Some(&first), Some(&last)) = (points.first(), points.last()) + && first.dist(last) < 1e-4 + { + points.pop(); + if points.last().is_some_and(|p| p.dist(first) < 1e-6) { + points.pop(); + } + points.push(first); + } + if points.len() < 2 { + return Err(bad(cmd, "the point does not move: there is no trace to keep")); + } + let name = match str_(p, "name").map(str::trim).filter(|n| !n.is_empty()) { + Some(n) => n.to_string(), + None => (1..=s.doc.features.len() + 1).map(|k| format!("Motion Trace{k}")).find(|n| s.doc.find_feature(n).is_none()).unwrap_or_default(), + }; + let pts: Vec = points.iter().map(|v| json!([v.x, v.y, v.z])).collect(); + // Made in the root, whatever is being edited, which is then as it was (also on an error). + let before = (s.active_sketch, s.active_component, s.active_occurrence_path.take()); + s.active_component = 0; + let made = (|| { + let run = |s: &mut Session, id: &str, q: Value| super::find_command(id).ok_or_else(|| bad(cmd, id.to_string()))?.run_nested(s, &q); + let made = run(s, "sketch.create", json!({"plane": "XY", "project_edges": false, "name": name}))?; + let sketch = made.get("sketch").cloned().unwrap_or(Value::Null); + run(s, "sketch.options", json!({"sketch": sketch, "sketch_3d": true}))?; + let spline = run(s, "sketch.spline3d", json!({"sketch": sketch, "points": pts}))?; + Ok::<_, EngineError>((made, spline)) + })(); + (s.active_sketch, s.active_component, s.active_occurrence_path) = before; + s.revision += 1; + let (made, spline) = made?; + let sketch = made.get("sketch").cloned().unwrap_or(Value::Null); + out["sketch"] = sketch; + out["name"] = made.get("name").cloned().unwrap_or(Value::Null); + out["curves"] = spline.get("curves").cloned().unwrap_or(Value::Null); + out["points"] = json!(points.len()); + Ok(out) +} + fn list_studies(s: &mut Session, _p: &Value) -> Result { Ok(json!({"studies": s.doc.assembly.studies})) } diff --git a/crates/sketch/src/wire.rs b/crates/sketch/src/wire.rs index 39db8b3b9..b0bc5f32e 100644 --- a/crates/sketch/src/wire.rs +++ b/crates/sketch/src/wire.rs @@ -61,9 +61,13 @@ pub fn fit_polyline(fit: &[Vec3]) -> Vec { return fit.to_vec(); } let n = fit.len(); + // A curve that ends where it starts is smooth through that point (its neighbours wrap). + let closed = n > 3 && fit[0].dist(fit[n - 1]) < 1e-9; let at = |i: isize| -> Vec3 { match usize::try_from(i) { Ok(i) if i < n => fit[i], + Ok(_) if closed => fit[1], + Err(_) if closed => fit[n - 2], // Mirrored end tangents. Ok(_) => fit[n - 1] * 2.0 - fit[n - 2], Err(_) => fit[0] * 2.0 - fit[1], @@ -330,4 +334,20 @@ mod tests { assert_eq!(sk, before); sk.validate_wires().unwrap(); } + + /// Through points around a circle that end where they start, the spline turns as smoothly at + /// the closing point as everywhere else; an open one keeps its mirrored end tangents. + #[test] + fn a_closed_spline_is_smooth_where_it_closes() { + let ring: Vec = (0..=12).map(|k| f64::from(k) * std::f64::consts::TAU / 12.0).map(|a| Vec3::new(a.cos(), a.sin(), 0.0)).collect(); + let pts = fit_polyline(&ring); + let dir = |a: Vec3, b: Vec3| (b - a).normalized().unwrap(); + let n = pts.len(); + let (start, end) = (dir(pts[0], pts[1]), dir(pts[n - 2], pts[n - 1])); + let mid = |i: usize| dir(pts[i - 1], pts[i]).dot(dir(pts[i], pts[i + 1])); + assert!(start.dot(end) >= mid(SPAN_SAMPLES) - 1e-9, "turn at the close {}, at a fit point {}", start.dot(end), mid(SPAN_SAMPLES)); + let open = fit_polyline(&ring[..12]); + assert_eq!(open.first(), ring.first()); + assert_eq!(open.last(), ring.get(11)); + } } diff --git a/crates/ui-egui/src/dialogs_assembly.rs b/crates/ui-egui/src/dialogs_assembly.rs index 06fd681a1..7a51992fd 100644 --- a/crates/ui-egui/src/dialogs_assembly.rs +++ b/crates/ui-egui/src/dialogs_assembly.rs @@ -21,6 +21,10 @@ use crate::theme::Tokens; use crate::viewport::Proj; +#[path = "dialogs_trace.rs"] +mod trace; +pub use trace::TraceForm; + /// 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"]; @@ -73,6 +77,8 @@ pub enum Asm { overlaps: Vec, of: Vec, }, + /// Motion Trace: a picked point's path, previewed; OK keeps it as a 3D sketch spline. + Trace(Box), } /// The snap under the cursor, remembered for the selection it was found for. @@ -146,6 +152,7 @@ impl Asm { _ => "SCREW", }, Asm::Interference { .. } => "INTERFERENCE", + Asm::Trace(_) => "MOTION TRACE", } } @@ -169,16 +176,10 @@ pub fn start(app: &SolveApp, id: &str) -> Option<(Kind, Vec)> { "joint.origin" => (Asm::JointOrigin { name: String::new(), hover: None }, vec![SelInput::new("Snap", SNAPS, false)]), "joint.rigid_group" => (Asm::RigidGroup, vec![SelInput::new("Components", BODIES, true)]), "joint.drive" => { - // The joint picked in the browser, else the first that moves. - let list = movable(s); - let picked = app - .tree - .picked_joints - .iter() - .find_map(|id| list.iter().copied().find(|i| s.doc.assembly.joints.get(*i).is_some_and(|j| j.id == *id))); - let joint = picked.or(list.first().copied()).unwrap_or(0); + let joint = picked_joint(app); (Asm::Drive { joint, values: current_values(s, joint), focus: true }, vec![]) } + "motion.trace" => (Asm::Trace(Box::new(trace::form(s, picked_joint(app)))), vec![SelInput::new("Point", SNAPS, false)]), "joint.motion_link" => { let b = usize::from(movable(s).len() > 1); (Asm::MotionLink { a: 0, b, ia: 0, ib: 0, ratio: "1".into(), offset: "0".into() }, vec![]) @@ -234,6 +235,15 @@ pub fn preset(s: &Session, k: &mut Asm, p: &Value) -> Result<(), String> { Ok(()) } +/// The joint picked in the browser, else the first that moves (an index into the design's joints). +fn picked_joint(app: &SolveApp) -> usize { + let s = &app.session; + let list = movable(s); + let picked = + app.tree.picked_joints.iter().find_map(|id| list.iter().copied().find(|i| s.doc.assembly.joints.get(*i).is_some_and(|j| j.id == *id))); + picked.or(list.first().copied()).unwrap_or(0) +} + /// Indices (into the design's joints) of joints that move (not rigid). fn movable(s: &Session) -> Vec { s.doc.assembly.joints.iter().enumerate().filter(|(_, j)| j.kind != JointKind::Rigid).map(|(i, _)| i).collect() @@ -691,6 +701,7 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Asm, inputs: &mut [Se interference_rows(app, ui, r); } } + Asm::Trace(f) => enter |= trace::rows(app, ui, f, inputs), } enter } @@ -905,6 +916,7 @@ pub fn commands(app: &SolveApp, k: &Asm, inputs: &[SelInput]) -> Result return crate::dialogs_coupling::commands(app, f, inputs), // The check runs from its Compute button; OK only closes. Asm::Interference { .. } => Vec::new(), + Asm::Trace(f) => cmd("motion.trace.keep", trace::params(s, f, inputs)?), }) } @@ -1052,11 +1064,15 @@ pub fn overlay(app: &SolveApp, painter: &egui::Painter, proj: &Proj, d: &mut Dia } return; } - // A joint names its two picks; a joint origin has one. + if let Asm::Trace(f) = k { + trace::overlay(painter, proj, f); + } + // A joint names its two picks; a joint origin and a trace have one. let two = matches!(k, Asm::Joint(_)); let hover = match k { Asm::Joint(f) => Some(&mut f.hover), Asm::JointOrigin { hover, .. } => Some(hover), + Asm::Trace(f) => Some(&mut f.hover), _ => None, }; let Some(hover) = hover else { return }; diff --git a/crates/ui-egui/src/dialogs_assembly_tests.rs b/crates/ui-egui/src/dialogs_assembly_tests.rs index 24c05c9bd..2e36408c5 100644 --- a/crates/ui-egui/src/dialogs_assembly_tests.rs +++ b/crates/ui-egui/src/dialogs_assembly_tests.rs @@ -551,3 +551,53 @@ fn drive_preset_refuses_a_rigid_joint() { let e = preset(&app.session, &mut k, &json!({"joint": "Glue"})).unwrap_err(); assert!(e.contains("rigid"), "{e}"); } + +/// Motion Trace on the four-bar: a pick on the coupler and the first joint (the crank) driven a +/// turn give the trace's parameters, and OK keeps the path as a 3D sketch spline. A pick on the +/// coupler where an exploded view shows it traces from where the coupler is placed. +#[test] +fn motion_trace_keeps_the_picked_point_path() { + let mut app = four_bar(); + let coupler = occ(&app, "Coupler"); + let top = |app: &SolveApp| { + let b = occurrence_bounds(&app.session, &[coupler]); + Vec3::new((b.min.x + b.max.x) / 2.0, (b.min.y + b.max.y) / 2.0, b.max.z) + }; + let placed = top(&app); + app.start("motion.trace"); + let mut d = app.dialog.clone().unwrap(); + assert!(apply_commands(&app, &d).is_err(), "no point yet"); + d.pick(&app.session, face_sel(&app.session, placed).unwrap()); + let c = apply_commands(&app, &d).unwrap(); + let (id, p) = &c[0]; + assert_eq!(id, "motion.trace.keep"); + let crank = app.session.doc.assembly.joints.iter().find(|j| j.name == "Crank").unwrap().id; + assert_eq!((&p["occurrence"], &p["joint"], &p["from"], &p["to"]), (&json!([coupler]), &json!(crank), &json!("0 deg"), &json!("360 deg")), "{p}"); + let at = |p: &Value| Vec3::new(p["point"][0].as_f64().unwrap(), p["point"][1].as_f64().unwrap(), p["point"][2].as_f64().unwrap()); + assert!(at(p).dist(placed) < 1e-6, "{p}"); + let preview = app.session.scratch().execute("motion.trace", p).unwrap(); + assert!(preview["samples"] == 100 && preview["stopped_at"].is_null(), "{preview}"); + crate::dialogs::run_dialog(&mut app, &d).unwrap(); + let sketch = app.session.doc.find_feature("Motion Trace1").unwrap().id; + let wire = app.session.doc.sketch(sketch).unwrap().wires[0].clone(); + assert_eq!(wire.fit.len(), 100); + assert_eq!(wire.fit.first(), wire.fit.last(), "a full turn closes the spline"); + // Exploded: the coupler shows away from its placement; the pick maps back to it. + app.run("explode.create", json!({"name": "Apart", "scale": 1})).unwrap(); + app.run("explode.show", json!({"view": "Apart"})).unwrap(); + let shown = top(&app); + assert!(shown.dist(placed) > 1.0, "the exploded view moves the coupler"); + app.start("motion.trace"); + let mut d = app.dialog.clone().unwrap(); + d.pick(&app.session, face_sel(&app.session, shown).unwrap()); + let p = apply_commands(&app, &d).unwrap()[0].1.clone(); + assert!(at(&p).dist(placed) < 1e-6, "{p}"); + // The preview is drawn moved with the coupler: it starts at the point picked where it shows. + let start = app.session.scratch().execute("motion.trace", &p).unwrap()["points"][0].clone(); + let (_, _, seen, put) = trace::placement(&app.session, &d.inputs).unwrap(); + let drawn = { + use solidcraft_engine::doc::{apply_point, mat_inverse}; + apply_point(&seen, apply_point(&mat_inverse(&put).unwrap(), at(&json!({"point": start})))) + }; + assert!(drawn.dist(shown) < 1e-6, "{drawn:?} wants {shown:?}"); +} diff --git a/crates/ui-egui/src/dialogs_trace.rs b/crates/ui-egui/src/dialogs_trace.rs new file mode 100644 index 000000000..32c88ceb2 --- /dev/null +++ b/crates/ui-egui/src/dialogs_trace.rs @@ -0,0 +1,199 @@ +//! Motion Trace: the path a picked point of a component takes while a joint is driven between +//! two values or a motion study plays. The path is computed on a scratch copy (`motion.trace`) +//! and drawn in the viewport; OK keeps it as a 3D sketch spline (`motion.trace.keep`). + +use egui::{Pos2, RichText, Stroke}; +use serde_json::{Value, json}; +use solidcraft_engine::doc::{IDENTITY, Mat, apply_point, mat_inverse, mat_mul}; +use solidcraft_engine::geom::Vec3; +use solidcraft_engine::{Sel, Session}; + +use super::{Hover, body_of, capital, movable, num, pt, sel_items, snap_of}; +use crate::dialogs::{combo, field, row_label}; +use crate::selection::SelInput; +use crate::theme::Tokens; +use crate::viewport::Proj; + +#[derive(Clone, Debug)] +pub struct TraceForm { + /// Traced as a motion study plays (else as a joint is driven from `from` to `to`). + pub by_study: bool, + /// Indices into the design's joints and motion studies. + pub joint: usize, + pub index: usize, + pub from: String, + pub to: String, + pub study: usize, + /// Empty: the command's default. + pub samples: String, + pub hover: Hover, + /// The trace shown: what it was computed for, and `motion.trace`'s answer (or why none). + pub shown: Option<(String, Result)>, + /// The picked part's frame as shown and the inverse of its placement: the traced path (where + /// the parts are placed) is drawn moved with the part, through the picked point. + pub view: Option<(Mat, Mat)>, +} + +/// The dialog on a joint (an index into the design's joints), from its value now over a turn. +pub fn form(s: &Session, joint: usize) -> TraceForm { + let (from, to) = range(s, joint, 0); + TraceForm { by_study: false, joint, index: 0, from, to, study: 0, samples: String::new(), hover: None, shown: None, view: None } +} + +/// From a joint's value now over a turn (an angle) or 20 mm (a distance). +fn range(s: &Session, joint: usize, index: usize) -> (String, String) { + let Some(j) = s.doc.assembly.joints.get(joint) else { return Default::default() }; + let v = j.values.get(index).copied().unwrap_or(0.0); + if j.kind.is_angle(index) { (num(v.to_degrees(), "deg"), num(v.to_degrees() + 360.0, "deg")) } else { (num(v, "mm"), num(v + 20.0, "mm")) } +} + +/// The occurrence path placing the picked body: the instance clicked, also when its component +/// (or a sub-assembly holding it) is placed more than once (empty: the root design). +fn path(s: &Session, sel: &Sel) -> Option> { + let body = body_of(sel)?; + s.doc.body_frames(&s.model.state()).into_iter().find(|(name, ..)| name == body).map(|(_, _, path, _)| path) +} + +/// The pick: its occurrence path, the point where the part shows, and the part's frame as shown +/// and as placed (they differ under an exploded view or a move not captured yet). +pub(super) fn placement(s: &Session, inputs: &[SelInput]) -> Option<(Vec, Vec3, Mat, Mat)> { + let pick = sel_items(inputs, 0).first()?; + let (snap, path) = (snap_of(s, pick)?, path(s, pick)?); + let world = |shown: bool| { + path.iter().try_fold(IDENTITY, |m, id| { + let o = s.doc.occurrences.iter().find(|o| o.id == *id)?; + Some(mat_mul(&m, s.pending_moves.get(id).filter(|_| shown).unwrap_or(&o.transform))) + }) + }; + let (shown, placed) = (world(true)?, world(false)?); + Some((path, snap.at, shown, placed)) +} + +/// The trace's parameters (OK's `motion.trace.keep` and the preview's `motion.trace`). +pub fn params(s: &Session, f: &TraceForm, inputs: &[SelInput]) -> Result { + let (path, at, shown, placed) = placement(s, inputs).ok_or("select a point on a component")?; + // The trace starts where the part is placed, not where it may be shown. + let at = mat_inverse(&shown).map(|m| apply_point(&placed, apply_point(&m, at))).ok_or("select a point on a component")?; + let occurrence = if path.is_empty() { json!(0) } else { json!(path) }; + let mut p = json!({"occurrence": occurrence, "point": pt(at)}); + if f.by_study { + p["study"] = json!(s.doc.assembly.studies.get(f.study).ok_or("no motion study yet")?.id); + } else { + let j = s.doc.assembly.joints.get(f.joint).ok_or("no joint that moves yet")?; + p["joint"] = json!(j.id); + p["index"] = json!(f.index); + p["from"] = json!(f.from.trim()); + p["to"] = json!(f.to.trim()); + } + if !f.samples.trim().is_empty() { + p["samples"] = json!(f.samples.trim().parse::().map_err(|_| "samples must be a number")?); + } + Ok(p) +} + +/// Where and why the motion stopped short, ending the trace (`None`: it went all the way). +fn stop_text(v: &Value) -> Option { + let at = v["stopped_at"].as_u64()?.to_string(); + let name = |x: &Value| x.as_str().unwrap_or_default().to_string(); + if let Some(l) = v["stopped_by_loop"].as_object() { + return Some(crate::i18n::format("trace.stopped_by_loop", &[("sample", &at), ("joint", &name(&l["joint"]))])); + } + let c = v["stopped_by_contact"].as_object()?; + Some(crate::i18n::format("trace.stopped_by_contact", &[("sample", &at), ("a", &name(&c["a"])), ("b", &name(&c["b"]))])) +} + +/// The dialog's rows; true when Enter was pressed in a value. +pub fn rows(app: &mut crate::SolveApp, ui: &mut egui::Ui, f: &mut TraceForm, inputs: &[SelInput]) -> bool { + let t = Tokens::get(); + let s = &app.session; + let mut enter = false; + let studies: Vec<&str> = s.doc.assembly.studies.iter().map(|m| m.name.as_str()).collect(); + f.by_study &= !studies.is_empty(); + if !studies.is_empty() { + row_label(ui, "Motion"); + let mut by = usize::from(f.by_study); + combo(ui, "tr_by", &["Joint", "Motion Study"], &mut by); + f.by_study = by == 1; + ui.end_row(); + } + if f.by_study { + row_label(ui, "Study"); + combo(ui, "tr_study", &studies, &mut f.study); + ui.end_row(); + } else { + let list = movable(s); + if list.is_empty() { + row_label(ui, ""); + ui.label(RichText::new(crate::i18n::tr_label("no joint that moves yet")).color(t.text_dim)); + ui.end_row(); + return false; + } + let labels: Vec<&str> = list.iter().filter_map(|i| s.doc.assembly.joints.get(*i)).map(|j| j.name.as_str()).collect(); + let mut pos = list.iter().position(|i| *i == f.joint).unwrap_or(0); + row_label(ui, "Joint"); + combo(ui, "tr_joint", &labels, &mut pos); + ui.end_row(); + let joint = list.get(pos).copied().unwrap_or(0); + let dofs = s.doc.assembly.joints.get(joint).map(|j| j.kind.dofs()).unwrap_or(&[]); + let mut index = if joint == f.joint { f.index.min(dofs.len().saturating_sub(1)) } else { 0 }; + if dofs.len() > 1 { + row_label(ui, " Of"); + let caps: Vec = dofs.iter().map(|d| capital(d)).collect(); + let refs: Vec<&str> = caps.iter().map(String::as_str).collect(); + combo(ui, "tr_index", &refs, &mut index); + ui.end_row(); + } + if joint != f.joint || index != f.index { + (f.joint, f.index) = (joint, index); + (f.from, f.to) = range(s, joint, index); + } + row_label(ui, "From"); + enter |= field(ui, &mut f.from); + ui.end_row(); + row_label(ui, "To"); + enter |= field(ui, &mut f.to); + ui.end_row(); + } + let default = match s.doc.assembly.studies.get(f.study).filter(|_| f.by_study) { + Some(m) => (u64::from(m.steps) + 1).clamp(2, 500), + None => 100, + }; + row_label(ui, "Samples"); + let r = ui.add(egui::TextEdit::singleline(&mut f.samples).hint_text(default.to_string())); + enter |= r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)); + ui.end_row(); + // The preview, traced again when what it traces (or the design) changes. + let p = params(s, f, inputs); + let key = format!("{}:{p:?}", s.revision); + if f.shown.as_ref().is_none_or(|(k, _)| *k != key) { + let r = p.and_then(|p| s.scratch().execute("motion.trace", &p).map_err(|e| e.to_string())); + f.shown = Some((key, r)); + f.view = placement(s, inputs).and_then(|(_, _, shown, placed)| Some((shown, mat_inverse(&placed)?))); + } + if let Some((_, r)) = &f.shown { + let (text, colour) = match r { + Ok(v) => match stop_text(v) { + Some(why) => (why, t.warning), + None => (crate::i18n::format("trace.points", &[("count", &v["samples"].to_string())]), t.text_dim), + }, + Err(e) => (e.clone(), t.text_dim), + }; + row_label(ui, ""); + ui.add(egui::Label::new(RichText::new(text).color(colour)).wrap()); + ui.end_row(); + } + enter +} + +/// The traced path in the viewport, with a dot where it starts. +pub fn overlay(painter: &egui::Painter, proj: &Proj, f: &TraceForm) { + let Some((_, Ok(v))) = &f.shown else { return }; + let at = |p: &Value| p.as_array().and_then(|a| Some(Vec3::new(a.first()?.as_f64()?, a.get(1)?.as_f64()?, a.get(2)?.as_f64()?))); + let shown = |p: Vec3| f.view.map_or(p, |(shown, inverse)| apply_point(&shown, apply_point(&inverse, p))); + let pts: Vec = v["points"].as_array().into_iter().flatten().filter_map(at).map(shown).filter_map(|p| proj.to_screen(p)).collect(); + let t = Tokens::get(); + if let Some(first) = pts.first() { + painter.circle_filled(*first, 3.5, t.preview_sketch); + } + painter.add(egui::Shape::line(pts, Stroke::new(2.0, t.preview_sketch))); +} diff --git a/crates/ui-egui/src/workspace.rs b/crates/ui-egui/src/workspace.rs index bc3438c3e..674d14372 100644 --- a/crates/ui-egui/src/workspace.rs +++ b/crates/ui-egui/src/workspace.rs @@ -20,6 +20,7 @@ const ASSEMBLE: &[&str] = &[ "joint.rack_pinion", "joint.screw", "motion.study", + "motion.trace", "explode.create", "contact.enable_sets", "contact.enable_all", diff --git a/docs/book/src/guide/assemblies.md b/docs/book/src/guide/assemblies.md index ca29a5613..f3a1de7fa 100644 --- a/docs/book/src/guide/assemblies.md +++ b/docs/book/src/guide/assemblies.md @@ -106,6 +106,22 @@ instead, so two origins given at one point with the same z stay as they are. For 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 +takes while a joint is driven or a motion study plays, such as the coupler curve of a four-bar. +Pick the point on the part (a face centre, a circle centre, an edge midpoint or a vertex), then +either a joint with the values to drive it from and to (a turn of the joint from where it is, at +first) or a motion study. The path previews in the viewport as the mechanism would move: closed +loops follow, and the path ends where a loop can no longer close or a contact set stops the +motion, which the dialog says under the values. OK keeps the path as a 3D sketch spline in a new +sketch of the root component (**Motion Trace1**, ...), where no joint moves it, and it can serve +as a sweep or pipe path. It is a fixed curve: it +does not follow later changes to the mechanism. A path that comes back to where it started is +kept as a closed, smooth spline. +`motion.trace {occurrence, point, joint, from, to, index?, samples?}` (or `{occurrence, point, +study, samples?}`) answers the world points without changing the design, and +`motion.trace.keep` with the same parameters (and `name?`) keeps them. A trace takes 2 to 500 +samples: 100 by default for a joint, one per step for a study. + **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 its own document. A STEP or mesh file picked there is inserted as **Insert STEP** or **Insert diff --git a/skills/solidcraft-mechanisms/SKILL.md b/skills/solidcraft-mechanisms/SKILL.md index 535bcdc04..14562cbda 100644 --- a/skills/solidcraft-mechanisms/SKILL.md +++ b/skills/solidcraft-mechanisms/SKILL.md @@ -55,6 +55,7 @@ Written against SolidCraft `main` after 0.11.1, which counts the degrees of free - **Contact:** `contact.create {"occurrences":[...], "name":...}` and `contact.enable_sets {}`. A drive then stops where two bodies of one set would pass through each other, with `stopped_by_contact: {a, b, fraction}`. `contact.check {}` lists the pairs that overlap now. - **Motion study:** `motion.study {"name":..., "steps":N, "keys":[{"joint":..., "points":[[step, value], ...]}]}`. Values are degrees or mm, linear between points. Key only the driving joints; linked joints and loops follow. - **Play:** `motion.play {"study":..., "step":s}` sets the joints there, which changes the design, and answers every occurrence's pose (about 0.2 KB per occurrence). `motion.export {"study":..., "samples":n}` gives the poses at every step without changing the design. +- **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. ## 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 3707a67cee8ff9da897d9a9b9b5174739a0d4ee2 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 16 Oct 2026 06:01:11 +0000 Subject: [PATCH 79/92] Regenerate THIRD-PARTY-LICENSES.txt and docs/features.md [skip ci] --- docs/features.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/features.md b/docs/features.md index 44a3e3666..3a4bd19ae 100644 --- a/docs/features.md +++ b/docs/features.md @@ -1,6 +1,6 @@ # Features -SolidCraft's commands by area, generated by `cargo xtask features` from the command registry (`solidcraft-cli commands`). **379 commands.** Planned (registered, not built yet): 3. 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`). **381 commands.** Planned (registered, not built yet): 3. 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 (103) @@ -484,13 +484,15 @@ SolidCraft's commands by area, generated by `cargo xtask features` from the comm | List Faces | `model.faces` | – | | List Threads | `model.threads` | – | -## `motion.*` (5) +## `motion.*` (7) | Command | Id | Toolbar | |---|---|---| | Motion Study | `motion.study` | SOLID › ASSEMBLE | | Play Motion Study | `motion.play` | – | | Export Motion Study | `motion.export` | – | +| Motion Trace | `motion.trace` | SOLID › ASSEMBLE | +| Keep Motion Trace | `motion.trace.keep` | – | | List Motion Studies | `motion.list` | – | | Delete Motion Study | `motion.delete` | – | From 26bf1af93b9215cd47ea8be2426d571e5f3077a4 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Fri, 16 Oct 2026 03:00:24 -0400 Subject: [PATCH 80/92] Sketch on an origin plane faces the side you clicked (#1587) Fixes #1586. --- crates/doc/src/assembly.rs | 2 +- crates/doc/src/clipboard.rs | 6 +- crates/doc/src/construct.rs | 2 +- crates/doc/src/document.rs | 9 ++ crates/doc/src/eval.rs | 3 + crates/doc/src/face_anchor.rs | 8 +- .../format/pending/flipped-sketch-plane.rs | 5 + crates/doc/src/sheet.rs | 8 +- crates/doc/src/walk.rs | 4 +- crates/engine/src/cmd/clipboard.rs | 2 +- crates/engine/src/cmd/sketch.rs | 34 ++++- crates/engine/src/cmd/sketch_face.rs | 4 +- crates/engine/src/cmd/sketch_flip_tests.rs | 136 ++++++++++++++++++ crates/engine/src/occurrences.rs | 2 +- crates/geom/src/plane.rs | 6 + crates/ui-egui/src/dialogs.rs | 48 ++++++- crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/sketch_side_ui_tests.rs | 87 +++++++++++ .../scenarios/s07_components_joint_drive.json | 2 +- .../s20_section_with_joint_drive.json | 2 +- .../scenarios/s26_drive_joint_typed.json | 2 +- .../s32_cut_in_active_component.json | 2 +- .../tests/scenarios/s37_browser_chevrons.json | 2 +- 23 files changed, 351 insertions(+), 27 deletions(-) create mode 100644 crates/doc/src/format/pending/flipped-sketch-plane.rs create mode 100644 crates/engine/src/cmd/sketch_flip_tests.rs create mode 100644 crates/ui-egui/src/sketch_side_ui_tests.rs diff --git a/crates/doc/src/assembly.rs b/crates/doc/src/assembly.rs index 668707842..a52580e3d 100644 --- a/crates/doc/src/assembly.rs +++ b/crates/doc/src/assembly.rs @@ -145,7 +145,7 @@ fn map_plane_ref(m: &Mat, p: &mut PlaneRef) { *plane = map_plane(m, plane); *at = apply_point(m, *at); } - PlaneRef::Offset { base, .. } => map_plane_ref(m, base), + PlaneRef::Offset { base, .. } | PlaneRef::Flipped { base, .. } => map_plane_ref(m, base), PlaneRef::AtAngle { base, axis_origin, axis_dir, .. } => { map_plane_ref(m, base); *axis_origin = apply_point(m, *axis_origin); diff --git a/crates/doc/src/clipboard.rs b/crates/doc/src/clipboard.rs index b8679b44a..5581892cb 100644 --- a/crates/doc/src/clipboard.rs +++ b/crates/doc/src/clipboard.rs @@ -113,7 +113,9 @@ fn remap_plane( return Err(crate::DocError::Invalid("clone plane reference depth exceeded".into())); } match p { - PlaneRef::Offset { base, .. } | PlaneRef::AtAngle { base, .. } => remap_plane(base, ids, names, bodies, depth + 1)?, + PlaneRef::Offset { base, .. } | PlaneRef::AtAngle { base, .. } | PlaneRef::Flipped { base, .. } => { + remap_plane(base, ids, names, bodies, depth + 1)? + } PlaneRef::Construction { name } => mapped_name(&mut name.0, names), PlaneRef::Face { name, anchor, .. } => { if let Some(name) = name { @@ -283,7 +285,7 @@ fn checked_plane(p: &PlaneRef, depth: usize) -> crate::Result<()> { return Err(crate::DocError::Invalid("copy reference nesting exceeds 64".into())); } match p { - PlaneRef::Offset { base, .. } | PlaneRef::AtAngle { base, .. } => checked_plane(base, depth + 1)?, + PlaneRef::Offset { base, .. } | PlaneRef::AtAngle { base, .. } | PlaneRef::Flipped { base, .. } => checked_plane(base, depth + 1)?, PlaneRef::Midplane { a, b } | PlaneRef::TwoEdges { a, b } => { checked_geo(a, depth + 1)?; checked_geo(b, depth + 1)?; diff --git a/crates/doc/src/construct.rs b/crates/doc/src/construct.rs index da42a77eb..5940eab9e 100644 --- a/crates/doc/src/construct.rs +++ b/crates/doc/src/construct.rs @@ -633,7 +633,7 @@ impl PlaneRef { PlaneRef::ThreePoints { a, b, c } => vec![a.as_mut(), b.as_mut(), c.as_mut()], PlaneRef::Tangent { face, .. } => vec![face.as_mut()], PlaneRef::AlongPath { path, .. } => vec![path.as_mut()], - PlaneRef::Offset { base, .. } | PlaneRef::AtAngle { base, .. } => base.refs_mut(), + PlaneRef::Offset { base, .. } | PlaneRef::AtAngle { base, .. } | PlaneRef::Flipped { base, .. } => base.refs_mut(), _ => Vec::new(), } } diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 81e79c06d..c7c142f9a 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -58,6 +58,14 @@ pub enum PlaneRef { AtAngle { base: Box, axis_origin: Vec3, axis_dir: Vec3, angle: Expr }, /// A construction plane feature (by name). Construction { name: FeatureName }, + /// `base` seen from its other side: the normal reversed by a half turn about the base's + /// own x axis (y reversed), or about its y axis (x reversed) when `about_y`. A sketch + /// started from behind a plane faces the viewer this way. + Flipped { + base: Box, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + about_y: bool, + }, /// Halfway between two planes (or planar faces); bisecting them when they meet at an angle. Midplane { a: Box, b: Box }, /// Through two straight edges (lines) that lie in one plane. @@ -2884,6 +2892,7 @@ impl Document { let o = *axis_origin + rot(b.origin - *axis_origin); Plane::new(o, rot(b.x), rot(b.y)).ok_or_else(|| DocError::Invalid("degenerate plane".into())) } + PlaneRef::Flipped { base, about_y } => Ok(self.resolve_plane_in(vals, base, depth + 1, st)?.flipped(*about_y)), PlaneRef::Construction { name } => { // Evaluated already: as it came out. if let Some(c) = st.and_then(|st| st.construct.iter().find(|c| &c.name == name)) diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 8b42a9227..10fecf971 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -3998,6 +3998,9 @@ pub(crate) fn sheet_face_plane_in_frame(doc: &Document, st: &ModelState, comp: u axis_dir: *axis_dir, angle: angle.clone(), }, + PlaneRef::Flipped { base, about_y } => { + PlaneRef::Flipped { base: Box::new(sheet_face_plane_in_frame(doc, st, comp, base)?), about_y: *about_y } + } other => other.clone(), }) } diff --git a/crates/doc/src/face_anchor.rs b/crates/doc/src/face_anchor.rs index a6e1df446..8d32d9268 100644 --- a/crates/doc/src/face_anchor.rs +++ b/crates/doc/src/face_anchor.rs @@ -82,7 +82,7 @@ impl FaceAnchor { pub fn plane_face_anchor(plane: &PlaneRef) -> Option<&FaceAnchor> { match plane { PlaneRef::Face { anchor, .. } => anchor.as_deref(), - PlaneRef::Offset { base, .. } | PlaneRef::AtAngle { base, .. } => plane_face_anchor(base), + PlaneRef::Offset { base, .. } | PlaneRef::AtAngle { base, .. } | PlaneRef::Flipped { base, .. } => plane_face_anchor(base), _ => None, } } @@ -90,7 +90,7 @@ pub fn plane_face_anchor(plane: &PlaneRef) -> Option<&FaceAnchor> { fn has_face_reference(plane: &PlaneRef) -> bool { match plane { PlaneRef::Face { .. } => true, - PlaneRef::Offset { base, .. } | PlaneRef::AtAngle { base, .. } => has_face_reference(base), + PlaneRef::Offset { base, .. } | PlaneRef::AtAngle { base, .. } | PlaneRef::Flipped { base, .. } => has_face_reference(base), _ => false, } } @@ -110,7 +110,9 @@ impl Document { } match plane { PlaneRef::Face { anchor: Some(anchor), .. } => *plane = PlaneRef::Custom { plane: doc.resolve_face_anchor(anchor, author, state)? }, - PlaneRef::Offset { base, .. } | PlaneRef::AtAngle { base, .. } => replace(doc, base, author, state, depth + 1)?, + PlaneRef::Offset { base, .. } | PlaneRef::AtAngle { base, .. } | PlaneRef::Flipped { base, .. } => { + replace(doc, base, author, state, depth + 1)? + } _ => {} } Ok(()) diff --git a/crates/doc/src/format/pending/flipped-sketch-plane.rs b/crates/doc/src/format/pending/flipped-sketch-plane.rs new file mode 100644 index 000000000..973f13f6c --- /dev/null +++ b/crates/doc/src/format/pending/flipped-sketch-plane.rs @@ -0,0 +1,5 @@ +//! A sketch can sit on a plane seen from its other side: `{"type": "flipped", "base": }` +//! (with `"about_y": true` when it turns about the plane's y axis rather than its x axis). New +//! sketches started from behind an origin or construction plane save this, so they face the +//! viewer. Older designs have no flipped planes and open unchanged; the last release refuses a +//! design that has one (it asks for an update) instead of putting the sketch on the wrong side. diff --git a/crates/doc/src/sheet.rs b/crates/doc/src/sheet.rs index 6538b3bbb..b8dcc0eca 100644 --- a/crates/doc/src/sheet.rs +++ b/crates/doc/src/sheet.rs @@ -4257,7 +4257,9 @@ pub fn rename_plane_sheet_body(plane: &mut crate::PlaneRef, old: &str, new: &str *name = renamed; } } - crate::PlaneRef::Offset { base, .. } | crate::PlaneRef::AtAngle { base, .. } => rename_plane_sheet_body(base, old, new), + crate::PlaneRef::Offset { base, .. } | crate::PlaneRef::AtAngle { base, .. } | crate::PlaneRef::Flipped { base, .. } => { + rename_plane_sheet_body(base, old, new) + } _ => {} } } @@ -4267,7 +4269,9 @@ pub fn rename_plane_sheet_body(plane: &mut crate::PlaneRef, old: &str, new: &str pub fn plane_sheet_face(plane: &crate::PlaneRef) -> Option<&str> { match plane { crate::PlaneRef::Face { name: Some(name), anchor: None, .. } if split_sheet_face_name(name).is_some() => Some(name), - crate::PlaneRef::Offset { base, .. } | crate::PlaneRef::AtAngle { base, .. } => plane_sheet_face(base), + crate::PlaneRef::Offset { base, .. } | crate::PlaneRef::AtAngle { base, .. } | crate::PlaneRef::Flipped { base, .. } => { + plane_sheet_face(base) + } _ => None, } } diff --git a/crates/doc/src/walk.rs b/crates/doc/src/walk.rs index d7c54c8f1..64726064c 100644 --- a/crates/doc/src/walk.rs +++ b/crates/doc/src/walk.rs @@ -364,7 +364,7 @@ impl Walk for PlaneRef { let mut p = self; for _ in 0..64 { match p { - PlaneRef::Offset { base, .. } | PlaneRef::AtAngle { base, .. } => p = base, + PlaneRef::Offset { base, .. } | PlaneRef::AtAngle { base, .. } | PlaneRef::Flipped { base, .. } => p = base, PlaneRef::Construction { name } => return f(Ref::Feature(name)), _ => return, } @@ -374,7 +374,7 @@ impl Walk for PlaneRef { let mut p = self; for _ in 0..64 { match p { - PlaneRef::Offset { base, .. } | PlaneRef::AtAngle { base, .. } => p = base, + PlaneRef::Offset { base, .. } | PlaneRef::AtAngle { base, .. } | PlaneRef::Flipped { base, .. } => p = base, PlaneRef::Construction { name } => return f(Ref::Feature(name)), _ => return, } diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index 4b37b39a3..eff00a90b 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -45,7 +45,7 @@ fn explicit_planes(p: &mut PlaneRef) { *p = PlaneRef::Custom { plane }; } } - PlaneRef::Offset { base, .. } | PlaneRef::AtAngle { base, .. } => explicit_planes(base), + PlaneRef::Offset { base, .. } | PlaneRef::AtAngle { base, .. } | PlaneRef::Flipped { base, .. } => explicit_planes(base), _ => {} } } diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rs index 6cc69a3d7..4cf5e4b0e 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, project_edges?: bool, name?"), + .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?"), 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) @@ -543,7 +543,7 @@ pub(crate) fn author_path_for_rebind(s: &Session, feature: &solidcraft_doc::Feat let mut plane = plane; loop { match plane { - PlaneRef::Offset { base, .. } | PlaneRef::AtAngle { base, .. } => plane = base, + PlaneRef::Offset { base, .. } | PlaneRef::AtAngle { base, .. } | PlaneRef::Flipped { base, .. } => plane = base, PlaneRef::Face { anchor: Some(anchor), .. } => { saved = Some(anchor.author_path.clone()); break; @@ -635,7 +635,31 @@ fn create_sketch(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, format!("`{key}` belongs inside `plane`: {example}"))); } } - create_sketch_with_plane(s, p, plane_ref(s, p, cmd)?, None) + let mut plane = plane_ref(s, p, cmd)?; + if let Some(about_y) = flip_param(s, p, &plane, cmd)? { + plane = PlaneRef::Flipped { base: Box::new(plane), about_y }; + } + create_sketch_with_plane(s, p, plane, None) +} + +/// `flip` of `sketch.create`: `None` keeps the plane's own side, otherwise the axis to turn +/// about (`true`: about y when the plane's y axis points upward, so it stays up, else about x). +fn flip_param(s: &Session, p: &Value, plane: &PlaneRef, cmd: &str) -> Result> { + let about_y = match p.get("flip") { + None | Some(Value::Null) | Some(Value::Bool(false)) => return Ok(None), + Some(Value::String(a)) if a.eq_ignore_ascii_case("x") => false, + Some(Value::String(a)) if a.eq_ignore_ascii_case("y") => true, + Some(Value::Bool(true)) => { + let (vals, _) = s.doc.param_values(); + let resolved = s.doc.resolve_plane_in(&vals, plane, 0, Some(&s.model.state()))?; + resolved.y.z > 1e-9 + } + Some(_) => return Err(bad(cmd, "`flip` must be true, false, \"x\" or \"y\"")), + }; + if face::is_face(p) { + return Err(bad(cmd, "`flip` is for origin, construction and explicit planes; a face already faces outward")); + } + Ok(Some(about_y)) } /// Used only by face Extrude/Revolve/PressPull, preserving pre-certificate linked profiles. @@ -2493,6 +2517,10 @@ fn solve_cmd(s: &mut Session, p: &Value) -> Result { Ok(json!({"status": ss.report.status, "dof": ss.report.dof, "failing": ss.report.failing, "profiles": ss.profiles.len()})) } +#[cfg(test)] +#[path = "sketch_flip_tests.rs"] +mod flip_tests; + #[cfg(test)] #[path = "sketch_rect_tests.rs"] mod rect_tests; diff --git a/crates/engine/src/cmd/sketch_face.rs b/crates/engine/src/cmd/sketch_face.rs index 985cdf0c6..35d30953a 100644 --- a/crates/engine/src/cmd/sketch_face.rs +++ b/crates/engine/src/cmd/sketch_face.rs @@ -206,7 +206,7 @@ fn capture_impl(s: &Session, value: &Value, cmd: &str, internal: bool) -> Result pub(in crate::cmd) fn anchor(mut plane: &PlaneRef) -> Option<&solidcraft_doc::FaceAnchor> { loop { match plane { - PlaneRef::Offset { base, .. } | PlaneRef::AtAngle { base, .. } => plane = base, + PlaneRef::Offset { base, .. } | PlaneRef::AtAngle { base, .. } | PlaneRef::Flipped { base, .. } => plane = base, PlaneRef::Face { anchor, .. } => return anchor.as_deref(), _ => return None, } @@ -216,7 +216,7 @@ pub(in crate::cmd) fn anchor(mut plane: &PlaneRef) -> Option<&solidcraft_doc::Fa pub(in crate::cmd) fn anchor_mut(mut plane: &mut PlaneRef) -> Option<&mut solidcraft_doc::FaceAnchor> { loop { match plane { - PlaneRef::Offset { base, .. } | PlaneRef::AtAngle { base, .. } => plane = base, + PlaneRef::Offset { base, .. } | PlaneRef::AtAngle { base, .. } | PlaneRef::Flipped { base, .. } => plane = base, PlaneRef::Face { anchor, .. } => return anchor.as_deref_mut(), _ => return None, } diff --git a/crates/engine/src/cmd/sketch_flip_tests.rs b/crates/engine/src/cmd/sketch_flip_tests.rs new file mode 100644 index 000000000..2385cb743 --- /dev/null +++ b/crates/engine/src/cmd/sketch_flip_tests.rs @@ -0,0 +1,136 @@ +//! `sketch.create` `flip`: a sketch on a plane seen from its other side (#1586). Without it a +//! sketch keeps the plane's own side, and older designs open, rebuild and save as before. + +use serde_json::{Value, json}; +use solidcraft_doc::{FeatureKind, PlaneRef}; +use solidcraft_geom::{Plane, 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}"), + } +} + +fn sketch_plane(s: &Session, id: u64) -> Plane { + s.model.state().sketch(id).map(|ss| ss.plane).expect("an evaluated sketch") +} + +fn measured(s: &mut Session) -> Value { + run(s, "inspect.measure", json!({}))["bodies"].clone() +} + +fn close(a: Vec3, b: Vec3) -> bool { + a.dist(b) < 1e-9 +} + +#[test] +fn without_flip_a_sketch_keeps_the_planes_own_side_and_saves_as_before() { + for name in ["XY", "XZ", "YZ"] { + let mut s = Session::default(); + let id = run(&mut s, "sketch.create", json!({"plane": name}))["sketch"].as_u64().unwrap(); + let saved = serde_json::to_value(&s.doc.feature(id).unwrap().kind).unwrap(); + assert_eq!(saved["plane"], json!({"type": "origin", "name": name}), "{name}"); + assert_eq!(sketch_plane(&s, id), Plane::named(name).unwrap(), "{name}"); + } +} + +#[test] +fn flip_turns_the_plane_about_the_axis_asked_for() { + // (plane, flip, expected x, expected y) + let cases = [ + ("XZ", json!(true), Vec3::X, Vec3::Z), + ("XZ", json!("y"), -Vec3::X, -Vec3::Z), + ("YZ", json!(true), -Vec3::Y, Vec3::Z), + ("YZ", json!("x"), Vec3::Y, -Vec3::Z), + ("XY", json!(true), Vec3::X, -Vec3::Y), + ("XY", json!("Y"), -Vec3::X, Vec3::Y), + ]; + for (name, flip, x, y) in cases { + let mut s = Session::default(); + let id = run(&mut s, "sketch.create", json!({"plane": name, "flip": flip}))["sketch"].as_u64().unwrap(); + let p = sketch_plane(&s, id); + assert!(close(p.x, x) && close(p.y, y), "{name} flip {flip}: {p:?}"); + assert!(close(p.normal(), -Plane::named(name).unwrap().normal()), "{name} flip {flip}"); + assert!(matches!(&s.doc.feature(id).unwrap().kind, FeatureKind::Sketch { plane: PlaneRef::Flipped { .. }, .. })); + } + let mut s = Session::default(); + let id = run(&mut s, "sketch.create", json!({"plane": "XZ", "flip": false}))["sketch"].as_u64().unwrap(); + assert!(matches!(&s.doc.feature(id).unwrap().kind, FeatureKind::Sketch { plane: PlaneRef::Origin { .. }, .. })); + assert!(s.execute("sketch.create", &json!({"plane": "XZ", "flip": "z"})).is_err()); +} + +#[test] +fn a_flipped_sketch_extrudes_the_other_way_and_offsets_along_the_planes_own_normal() { + let mut s = Session::default(); + let id = run(&mut s, "sketch.create", json!({"plane": "XZ", "flip": true, "offset": "5 mm"}))["sketch"].as_u64().unwrap(); + assert!(close(sketch_plane(&s, id).origin, Vec3::new(0.0, 5.0, 0.0))); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [10, 4]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"sketch": id, "distance": 3, "operation": "new_body", "body_name": "B"})); + let bounds = s.model.state().body("B").map(|b| b.mesh().bounds()).unwrap(); + // Sketch y is world +Z; extruded along -Y, from y = 5 to y = 2. + assert!((bounds.min.y - 2.0).abs() < 1e-9 && (bounds.max.y - 5.0).abs() < 1e-9, "{bounds:?}"); + assert!((bounds.min.z).abs() < 1e-9 && (bounds.max.z - 4.0).abs() < 1e-9, "{bounds:?}"); + // Saved and opened again, it is the same. + let path = std::env::temp_dir().join(format!("solidcraft-flip-{}.solidcraft", std::process::id())); + run(&mut s, "file.save", json!({"path": path})); + let mut reopened = Session::default(); + run(&mut reopened, "doc.open", json!({"path": path})); + assert_eq!(*reopened.doc, *s.doc); + assert_eq!(measured(&mut reopened), measured(&mut s)); + std::fs::remove_file(path).unwrap(); +} + +#[test] +fn a_construction_plane_flips_too_and_follows_its_parameter() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "h", "expression": "7 mm"})); + run(&mut s, "construct.plane.offset", json!({"base": "XY", "offset": "h", "name": "P"})); + let id = run(&mut s, "sketch.create", json!({"plane": "P", "flip": true}))["sketch"].as_u64().unwrap(); + let p = sketch_plane(&s, id); + assert!(close(p.origin, Vec3::new(0.0, 0.0, 7.0)) && close(p.normal(), -Vec3::Z), "{p:?}"); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "parameters.change", json!({"name": "h", "expression": "9 mm"})); + let p = sketch_plane(&s, id); + assert!(close(p.origin, Vec3::new(0.0, 0.0, 9.0)) && close(p.normal(), -Vec3::Z), "{p:?}"); +} + +#[test] +fn flip_is_refused_on_a_face() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10})); + assert!(s.execute("sketch.create", &json!({"plane": {"face": [5, 5, 10]}, "flip": true})).is_err()); +} + +/// Designs from before `flip` open with every sketch where it was, never flipped, rebuild the +/// same bodies and save and reopen unchanged. +#[test] +fn older_designs_open_rebuild_and_save_unchanged() { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../apps/solidcraft-cli/tests/corpus"); + let mut files: Vec<_> = + std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "solidcraft")).collect(); + files.sort(); + assert!(files.len() >= 7, "corpus designs in {}", dir.display()); + for old in files { + let mut s = Session::default(); + run(&mut s, "doc.open", json!({"path": old})); + assert!(!serde_json::to_string(&*s.doc).unwrap().contains("\"flipped\""), "{}", old.display()); + // The oldest one's XZ sketch: sketch y along +Z, as it was drawn. + if old.ends_with("m0-revolve-primitives.solidcraft") { + let id = s.doc.features.iter().find(|f| matches!(f.kind, FeatureKind::Sketch { .. })).map(|f| f.id).unwrap(); + let p = sketch_plane(&s, id); + assert!(close(p.origin, Vec3::ZERO) && close(p.x, Vec3::X) && close(p.y, Vec3::Z), "{p:?}"); + } + let bodies = measured(&mut s); + let path = std::env::temp_dir().join(format!("solidcraft-old-{}.solidcraft", std::process::id())); + run(&mut s, "file.save", json!({"path": path})); + let mut reopened = Session::default(); + run(&mut reopened, "doc.open", json!({"path": path})); + assert_eq!(*reopened.doc, *s.doc, "{}", old.display()); + assert_eq!(measured(&mut reopened), bodies, "{}", old.display()); + std::fs::remove_file(path).unwrap(); + } +} diff --git a/crates/engine/src/occurrences.rs b/crates/engine/src/occurrences.rs index daf3ea8d2..0fd615cfe 100644 --- a/crates/engine/src/occurrences.rs +++ b/crates/engine/src/occurrences.rs @@ -240,7 +240,7 @@ impl Session { let mut plane = plane; loop { match plane { - PlaneRef::Offset { base, .. } | PlaneRef::AtAngle { base, .. } => plane = base, + PlaneRef::Offset { base, .. } | PlaneRef::AtAngle { base, .. } | PlaneRef::Flipped { base, .. } => plane = base, // A face attachment that names no exact source: which body it sits on is unknown, // so none is taken from the view. PlaneRef::Face { anchor: None, .. } => return none, diff --git a/crates/geom/src/plane.rs b/crates/geom/src/plane.rs index ee51a010c..1d7d882ec 100644 --- a/crates/geom/src/plane.rs +++ b/crates/geom/src/plane.rs @@ -39,6 +39,12 @@ impl Plane { Plane::new(origin, x, n.cross(x)) } + /// The same plane seen from its other side: a half turn about the sketch x axis (y + /// reversed), or about the y axis (x reversed) when `about_y`. Still right-handed. + pub fn flipped(&self, about_y: bool) -> Plane { + if about_y { Plane { x: -self.x, ..*self } } else { Plane { y: -self.y, ..*self } } + } + /// Named origin plane: `XY`, `XZ`, `YZ` (case-insensitive). pub fn named(name: &str) -> Option { match name.to_ascii_uppercase().as_str() { diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 2f6911c6c..2d4ab062e 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -3327,13 +3327,18 @@ pub(crate) fn change_param(app: &mut SolveApp, name: &str, expression: &str) -> /// Start a sketch on a picked plane or planar face and turn the view to face it. pub fn start_sketch(app: &mut SolveApp, sel: &Sel) -> Result<(), String> { - let plane = match sel { - Sel::Plane { name } => json!(name), - Sel::Face { .. } => crate::sketch_attachment_ui::face_plane(app, sel).ok_or("Selected face placement no longer exists")?, + let mut params = match sel { + Sel::Plane { name } => json!({ "plane": name }), + Sel::Face { .. } => json!({ "plane": crate::sketch_attachment_ui::face_plane(app, sel).ok_or("Selected face placement no longer exists")? }), _ => return Err("Select an origin plane, construction plane or planar body face".into()), }; + if let Sel::Plane { name } = sel + && let Some(flip) = flip_toward_viewer(app, name) + { + params["flip"] = json!(flip); + } let before = app.cam; - app.run("sketch.create", json!({ "plane": plane })).map_err(|error| crate::friendly_error("sketch.create", &error))?; + app.run("sketch.create", params).map_err(|error| crate::friendly_error("sketch.create", &error))?; app.pre_sketch_cam = Some(before); look_at_sketch(app); // On a face: look at the picked point, not the plane's origin (a corner of the face), @@ -3347,6 +3352,40 @@ pub fn start_sketch(app: &mut SolveApp, sel: &Sel) -> Result<(), String> { Ok(()) } +/// A new sketch on origin or construction plane `name` faces the viewer: when the camera is +/// behind the plane's normal, the in-plane axis to turn the plane about (`"x"` or `"y"`), chosen +/// so the sketch's y axis stays as upright on screen as it can (x then runs to the right). +fn flip_toward_viewer(app: &SolveApp, name: &str) -> Option<&'static str> { + let plane = plane_by_name(app, name)?; + let n = plane.normal(); + // Where the eye is: in perspective its position, in orthographic only its direction counts. + let side = if app.cam.fov > 0.0 { (app.cam.eye() - plane.origin).dot(n) } else { app.cam.basis().2.dot(n) }; + if side >= -1e-9 { + return None; + } + let up = app.cam.up.dir(); + Some(if plane.y.dot(up) > 1e-9 { "y" } else { "x" }) +} + +/// The world plane of an origin plane or a construction plane by name. +fn plane_by_name(app: &SolveApp, name: &str) -> Option { + if let Some(p) = solidcraft_engine::geom::Plane::named(name) { + // In an active component its origin planes are the component's. + let m = app.session.active_component_frame(); + let (o, x, y) = ( + solidcraft_engine::doc::apply_point(&m, p.origin), + solidcraft_engine::doc::apply_vector(&m, p.x), + solidcraft_engine::doc::apply_vector(&m, p.y), + ); + return solidcraft_engine::geom::Plane::new(o, x, y); + } + let st = app.session.world_state(); + st.construct.iter().find(|c| c.name == name).and_then(|c| match &c.geom { + solidcraft_engine::doc::construct::ConstructGeom::Plane(pl) => Some(*pl), + _ => None, + }) +} + /// Animate the camera to look straight at the active sketch plane. pub fn look_at_sketch(app: &mut SolveApp) { let st = app.session.world_state(); @@ -4352,6 +4391,7 @@ pub(crate) fn plane_sel(s: &Session, pl: &PlaneRef) -> Option { PlaneRef::Origin { name } => Some(Sel::Plane { name: name.clone() }), PlaneRef::Construction { name } => Some(Sel::Plane { name: name.to_string() }), PlaneRef::Custom { plane } | PlaneRef::Face { plane, .. } => face_sel(s, plane.origin), + PlaneRef::Flipped { base, .. } => plane_sel(s, base), _ => None, } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index f09b2e48b..8e5a2a439 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -149,6 +149,8 @@ pub mod sketch_modify_ui; mod sketch_modify_ui_tests; pub mod sketch_palette; mod sketch_pattern_tree; +#[cfg(test)] +mod sketch_side_ui_tests; pub(crate) mod sketch_text; mod sketch_text_handles; mod sketch_text_move; diff --git a/crates/ui-egui/src/sketch_side_ui_tests.rs b/crates/ui-egui/src/sketch_side_ui_tests.rs new file mode 100644 index 000000000..bb62fa614 --- /dev/null +++ b/crates/ui-egui/src/sketch_side_ui_tests.rs @@ -0,0 +1,87 @@ +//! Sketch on an origin plane from either side: the new sketch faces the viewer and the view +//! turns to it from where it was, never round to the far side (#1586). + +use crate::scenario::Harness; +use serde_json::json; +use solidcraft_engine::doc::{FeatureKind, PlaneRef}; +use solidcraft_engine::geom::{Plane, Vec3}; + +fn sketch_from(yaw: f64, pitch: f64, name: &str) -> (Harness, Vec3, Plane) { + let mut h = Harness::new(); + h.app.preferences.look_at_anim = false; + h.app.cam.yaw = yaw; + h.app.cam.pitch = pitch; + let eye = h.app.cam.eye(); + h.step(&json!({"start":"sketch.create"})).unwrap(); + h.step(&json!({"click":{"plane":name}})).unwrap(); + h.settle(); + let plane = h.app.session.world_state().sketches.first().map(|s| s.plane).expect("a sketch on the plane"); + (h, eye, plane) +} + +#[test] +fn a_new_sketch_on_an_origin_plane_faces_the_side_it_was_started_from() { + // (yaw, pitch, plane, the plane's own normal); each plane from both of its sides. + let cases = [ + (0.4, 0.4, "XZ", Vec3::Y), + (std::f64::consts::PI - 0.4, 0.4, "XZ", Vec3::Y), + (-1.2, 0.4, "YZ", Vec3::X), + (1.2, 0.4, "YZ", Vec3::X), + (-0.6, 0.5, "XY", Vec3::Z), + (-0.6, -0.5, "XY", Vec3::Z), + ]; + for (yaw, pitch, name, own) in cases { + let (h, eye, plane) = sketch_from(yaw, pitch, name); + let n = plane.normal(); + let what = format!("{name} from yaw {yaw} pitch {pitch}"); + assert!(n.dot(own).abs() > 0.999, "{what}: sketched on {n:?}"); + assert!(eye.dot(n) > 0.0, "{what}: the sketch normal {n:?} points away from the eye {eye:?}"); + // The view looks straight at the sketch from the side it was looking from. + let after = h.app.cam.eye(); + assert!(after.dot(own * eye.dot(own).signum()) > 0.0, "{what}: the view turned to the far side {after:?}"); + let (right, up, back) = h.app.cam.basis(); + assert!(back.dot(n) > 0.999, "{what}: not looking straight at the sketch ({back:?})"); + // Only a sketch from behind the plane saves the flip, turned so its x runs right and + // its y up on screen (a plane's own side keeps its own axes, as before). + let sketch = h.app.session.active_sketch.unwrap(); + let FeatureKind::Sketch { plane: saved, .. } = &h.app.session.doc.feature(sketch).unwrap().kind else { panic!() }; + let behind = eye.dot(own) < 0.0; + if behind { + assert!(right.dot(plane.x) > 0.999 && up.dot(plane.y) > 0.999, "{what}: sketch axes {:?} {:?} on screen", plane.x, plane.y); + } + assert_eq!(matches!(saved, PlaneRef::Flipped { .. }), behind, "{what}: saved {saved:?}"); + } +} + +#[test] +fn a_flipped_sketch_extrudes_toward_the_viewer_and_reopens_the_same() { + let (mut h, _, plane) = sketch_from(0.4, 0.4, "XZ"); + assert!(plane.normal().dot(Vec3::Y) < -0.999); + h.app.run("sketch.rectangle.two_point", json!({"p0":[0,0],"p1":[10,5]})).unwrap(); + let sketch = h.app.session.active_sketch.unwrap(); + h.app.finish_sketch(); + h.app.run("solid.extrude", json!({"sketch":sketch,"distance":4,"operation":"new_body","body_name":"Block"})).unwrap(); + let bounds = |h: &Harness| h.app.session.world_state().body("Block").map(|b| b.mesh().bounds()).expect("an extruded body"); + let before = bounds(&h); + assert!(before.min.y < -3.9 && before.max.y < 1e-6, "extruded away from the viewer: {before:?}"); + let path = h.dir.join("flipped-sketch.solidcraft"); + h.app.run("file.save", json!({"path":path})).unwrap(); + h.app.run("doc.open", json!({"path":path})).unwrap(); + assert_eq!(bounds(&h), before); +} + +#[test] +fn a_construction_plane_seen_from_below_gets_a_sketch_facing_down() { + let mut h = Harness::new(); + h.app.preferences.look_at_anim = false; + h.app.run("construct.plane.offset", json!({"base":"XY","offset":"5 mm","name":"P"})).unwrap(); + h.app.cam.yaw = -0.6; + h.app.cam.pitch = -0.5; + h.app.session.selection = vec![solidcraft_engine::Sel::Plane { name: "P".into() }]; + h.step(&json!({"key":"L"})).unwrap(); + h.settle(); + let sketch = h.app.session.active_sketch.expect("a sketch on P"); + let plane = h.app.session.world_state().sketch(sketch).map(|s| s.plane).unwrap(); + assert!(plane.normal().z < -0.999 && (plane.origin.z - 5.0).abs() < 1e-9, "{plane:?}"); + assert!(h.app.cam.eye().z < 5.0, "the view stays below the plane"); +} diff --git a/crates/ui-egui/tests/scenarios/s07_components_joint_drive.json b/crates/ui-egui/tests/scenarios/s07_components_joint_drive.json index 8d4e318c7..34cc697c8 100644 --- a/crates/ui-egui/tests/scenarios/s07_components_joint_drive.json +++ b/crates/ui-egui/tests/scenarios/s07_components_joint_drive.json @@ -113,7 +113,7 @@ "click": { "sketch": [ 50, - -10 + 10 ] } }, diff --git a/crates/ui-egui/tests/scenarios/s20_section_with_joint_drive.json b/crates/ui-egui/tests/scenarios/s20_section_with_joint_drive.json index aaefdc346..845f4ea58 100644 --- a/crates/ui-egui/tests/scenarios/s20_section_with_joint_drive.json +++ b/crates/ui-egui/tests/scenarios/s20_section_with_joint_drive.json @@ -113,7 +113,7 @@ "click": { "sketch": [ 50, - -10 + 10 ] } }, diff --git a/crates/ui-egui/tests/scenarios/s26_drive_joint_typed.json b/crates/ui-egui/tests/scenarios/s26_drive_joint_typed.json index 1785b7997..183810757 100644 --- a/crates/ui-egui/tests/scenarios/s26_drive_joint_typed.json +++ b/crates/ui-egui/tests/scenarios/s26_drive_joint_typed.json @@ -113,7 +113,7 @@ "click": { "sketch": [ 50, - -10 + 10 ] } }, diff --git a/crates/ui-egui/tests/scenarios/s32_cut_in_active_component.json b/crates/ui-egui/tests/scenarios/s32_cut_in_active_component.json index a02cef5c8..5141ca64d 100644 --- a/crates/ui-egui/tests/scenarios/s32_cut_in_active_component.json +++ b/crates/ui-egui/tests/scenarios/s32_cut_in_active_component.json @@ -102,7 +102,7 @@ "click": { "sketch": [ 52, - -10 + 10 ] } }, diff --git a/crates/ui-egui/tests/scenarios/s37_browser_chevrons.json b/crates/ui-egui/tests/scenarios/s37_browser_chevrons.json index 124b89f42..cff637675 100644 --- a/crates/ui-egui/tests/scenarios/s37_browser_chevrons.json +++ b/crates/ui-egui/tests/scenarios/s37_browser_chevrons.json @@ -116,7 +116,7 @@ "click": { "sketch": [ 50, - -10 + 10 ] } }, From 25c89a706eda972eab3dd15efe1692e65c786569 Mon Sep 17 00:00:00 2001 From: DuBearte <130190089+DuBearte@users.noreply.github.com> Date: Fri, 16 Oct 2026 03:00:49 -0400 Subject: [PATCH 81/92] Sketch: a tangent arc starts from a trimmed end (#1485) (#1604) Thanks @DuBearte. --- crates/engine/src/cmd/sketch_create.rs | 27 ++++++++++++++------ crates/engine/src/cmd/sketch_modify_tests.rs | 27 ++++++++++++++++++++ 2 files changed, 46 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/sketch_create.rs b/crates/engine/src/cmd/sketch_create.rs index f82396cbf..c4eebc0d9 100644 --- a/crates/engine/src/cmd/sketch_create.rs +++ b/crates/engine/src/cmd/sketch_create.rs @@ -659,15 +659,26 @@ fn arc_tangent(s: &mut Session, p: &Value) -> Result { 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 pi = st.idx().ok_or_else(|| bad(cmd, "`start` must be the end point of a line or arc"))?; - let ci = match str_(p, "curve") { - Some(id) => sk.curve_index(id).ok_or_else(|| bad(cmd, format!("unknown curve `{id}`")))?, - None => sk - .curves + 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). + let at = st.pos(); + let tol = 1e-6 * at.len().max(1.0); + let candidates: Vec = + std::iter::once(picked).chain((0..sk.points.len()).filter(|&q| q != picked && sk.point(q).is_some_and(|x| x.dist(at) <= tol))).collect(); + let (ci, pi) = match str_(p, "curve") { + Some(id) => { + let ci = sk.curve_index(id).ok_or_else(|| bad(cmd, format!("unknown curve `{id}`")))?; + let pi = candidates + .iter() + .copied() + .find(|&q| leaving_dir(sk, ci, q).is_some()) + .ok_or_else(|| bad(cmd, "`start` is not an end of that curve"))?; + (ci, pi) + } + None => candidates .iter() - .enumerate() - .find(|(i, c)| !c.construction && leaving_dir(sk, *i, pi).is_some()) - .map(|(i, _)| i) + .find_map(|&q| sk.curves.iter().enumerate().find(|(i, c)| !c.construction && leaving_dir(sk, *i, q).is_some()).map(|(i, _)| (i, q))) .ok_or_else(|| bad(cmd, "no line or arc ends at `start`"))?, }; let t = leaving_dir(sk, ci, pi).ok_or_else(|| bad(cmd, "`start` is not an end of that curve"))?; diff --git a/crates/engine/src/cmd/sketch_modify_tests.rs b/crates/engine/src/cmd/sketch_modify_tests.rs index ac5526690..805c8a190 100644 --- a/crates/engine/src/cmd/sketch_modify_tests.rs +++ b/crates/engine/src/cmd/sketch_modify_tests.rs @@ -310,6 +310,33 @@ fn offset_chain_mirror_patterns_move_scale() { assert!(sk.center(sk.curve_index(&cp).unwrap()).unwrap().dist(Vec2::new(-110.0, 0.0)) < 1e-7); } +/// #1485: after a circle is trimmed between two construction lines, clicking the trimmed end +/// picks the construction line's end lying there, not the arc's own; the tangent arc still starts +/// from the trimmed arc, tangent to it. +#[test] +fn a_tangent_arc_starts_from_a_trimmed_end() { + let mut s = new_sketch(); + let c = ids(&run(&mut s, "sketch.circle.center", json!({"center": [0, 0], "radius": 10}))["curves"])[0].clone(); + run(&mut s, "sketch.line", json!({"points": [[0, 0], [10, 0]], "ids": ["guide_a"]})); + run(&mut s, "sketch.line", json!({"points": [[0, 0], [0, 10]], "ids": ["guide_b"]})); + run(&mut s, "sketch.construction", json!({"curves": ["guide_a", "guide_b"]})); + run(&mut s, "sketch.trim", json!({"curve": c, "at": [7.07, 7.07]})); + let sk = sketch(&s); + let picked = sk.resolve_point("guide_a.end").unwrap(); + assert!(sk.point(picked).unwrap().dist(Vec2::new(10.0, 0.0)) < 1e-6); + let trimmed = sk.curves.iter().position(|cu| !cu.construction && matches!(cu.kind, CurveKind::Arc { .. })).expect("the trimmed arc"); + let r = run(&mut s, "sketch.arc.tangent", json!({"start": "guide_a.end", "end": [14, 6]})); + let sk = sketch(&s); + let a = sk.curve_index(&ids(&r["curves"])[0]).unwrap(); + let a_ends: Vec = sk.curves[a].kind.point_ids(); + let t_ends: Vec = sk.curves[trimmed].kind.point_ids(); + assert!(a_ends.iter().any(|q| t_ends.contains(q) && *q != picked), "the new arc shares the trimmed arc's own end"); + assert!( + sk.constraints.iter().any(|k| matches!(k.kind, ConstraintKind::Tangent { a: x, b: y } if (x, y) == (trimmed, a) || (x, y) == (a, trimmed))), + "and is tangent to it" + ); +} + #[test] fn new_creation_tools() { let mut s = new_sketch(); From 61678654c25e1f94da11d116f0c763cf5d7ff994 Mon Sep 17 00:00:00 2001 From: DuBearte <130190089+DuBearte@users.noreply.github.com> Date: Fri, 16 Oct 2026 03:00:52 -0400 Subject: [PATCH 82/92] Extrude: dragging the taper stops where the profile would close (#1602) (#1614) Thanks @DuBearte. --- crates/geom/src/profile.rs | 93 ++++++++++++++++++++++++++++++++++++ crates/ui-egui/src/canvas.rs | 82 +++++++++++++++++++++++++++++-- 2 files changed, 170 insertions(+), 5 deletions(-) diff --git a/crates/geom/src/profile.rs b/crates/geom/src/profile.rs index 229109891..4ff226669 100644 --- a/crates/geom/src/profile.rs +++ b/crates/geom/src/profile.rs @@ -372,6 +372,10 @@ pub struct Loop2 { } impl Loop2 { + /// The radius of the largest circle inside the loop, to about `tol` ([`Region2::inradius`]). + pub fn inradius(&self, tol: f64) -> f64 { + max_clearance(&[self.polyline(tol)]) + } /// Full circle as two half arcs (counter-clockwise). pub fn circle(center: Vec2, radius: f64) -> Loop2 { Loop2 { @@ -505,6 +509,79 @@ impl Region2 { pub fn contains(&self, p: Vec2) -> bool { self.outer.contains(p) && !self.holes.iter().any(|h| h.contains(p)) } + /// The radius of the largest circle inside the region: how far its sides can move inwards + /// 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(); + 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 { + return 0.0; + }; + let inside = |p: Vec2| { + let mut odd = false; + for (a, b) in &sides { + 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 clearance = |p: Vec2| -> f64 { + if !inside(p) { + return 0.0; + } + sides + .iter() + .map(|(a, b)| { + let ab = *b - *a; + let t = ((p - *a).dot(ab) / ab.len2()).clamp(0.0, 1.0); + p.dist(*a + ab * t) + }) + .fold(f64::INFINITY, f64::min) + }; + const N: usize = 32; + let size = hi - lo; + let mut best = (0.0, (lo + hi) * 0.5); + for i in 0..=N { + for j in 0..=N { + let p = Vec2::new(lo.x + size.x * i as f64 / N as f64, lo.y + size.y * j as f64 / N as f64); + let c = clearance(p); + if c > best.0 { + best = (c, p); + } + } + } + // Refine: try the eight neighbours, halving the step whenever none is better. + let mut step = size.x.max(size.y) / N as f64; + for _ in 0..60 { + if step < size.x.max(size.y) * 1e-9 { + break; + } + let around = [(1.0, 0.0), (-1.0, 0.0), (0.0, 1.0), (0.0, -1.0), (1.0, 1.0), (1.0, -1.0), (-1.0, 1.0), (-1.0, -1.0)]; + match around.iter().map(|(dx, dy)| best.1 + Vec2::new(dx * step, dy * step)).map(|p| (clearance(p), p)).max_by(|a, b| a.0.total_cmp(&b.0)) { + Some(n) if n.0 > best.0 => best = n, + _ => step *= 0.5, + } + } + best.0 +} + +impl Region2 { /// Triangles covering the region (for filled display), by slabs between the vertex /// heights: inside each slab the boundary edges don't cross, so consecutive crossings pair /// up into trapezoids. @@ -672,6 +749,22 @@ mod tests { Region2 { outer: l, holes: Vec::new() } } + /// #1602: the largest circle inside a region, which bounds how far a taper can go. + #[test] + fn inradius_of_rectangles_circles_and_rings() { + let close = |a: f64, b: f64| (a - b).abs() < 1e-3 * b.max(1.0); + let rect = Loop2::polygon(&[Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), Vec2::new(10.0, 4.0), Vec2::new(0.0, 4.0)]); + assert!(close(solid(rect.clone()).inradius(1e-3), 2.0), "{}", solid(rect.clone()).inradius(1e-3)); + assert!(close(rect.inradius(1e-3), 2.0)); + let disc = Loop2::circle(Vec2::new(3.0, -2.0), 5.0); + assert!(close(solid(disc.clone()).inradius(1e-4), 5.0), "{}", solid(disc).inradius(1e-4)); + // A ring 10 to 6: the material is 4 wide (radius 2); the hole alone has radius 6. + let ring = Region2 { outer: Loop2::circle(Vec2::ZERO, 10.0), holes: vec![Loop2::circle(Vec2::ZERO, 6.0).reversed()] }; + assert!(close(ring.inradius(1e-4), 2.0), "{}", ring.inradius(1e-4)); + assert!(close(ring.holes[0].inradius(1e-4), 6.0)); + assert_eq!(Region2::default().inradius(1e-3), 0.0); + } + #[test] fn regions_are_apart_only_when_nothing_meets_or_holds_another() { let gap = 1e-3; diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 282308815..300a5d459 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -425,7 +425,20 @@ fn draw(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj, let px = 2.0 * half_height / f64::from(proj.rect.height().max(1.0)); let ang = app.session.doc.eval(taper, ValueKind::Angle).ok().filter(|v| v.is_finite()).unwrap_or(0.0); let before = taper.clone(); - taper_handle(ui, painter, proj, base - e * (40.0 * px), n * l, -e, ang, taper); + let st = app.session.world_state(); + let regions: Vec<&solidcraft_engine::geom::Region2> = d + .inputs + .first() + .map(|i| &i.items[..]) + .unwrap_or(&[]) + .iter() + .filter_map(|x| match x { + Sel::Profile { sketch, index } => st.sketch(*sketch).and_then(|ss| ss.profiles.get(*index)).map(|pr| &pr.region), + _ => None, + }) + .collect(); + let limits = taper_limits(®ions, l.abs()); + taper_handle(ui, painter, proj, base - e * (40.0 * px), n * l, -e, ang, limits, taper); if *taper != before { *taper_present = true; } @@ -857,16 +870,42 @@ fn measure_components(app: &SolveApp, painter: &egui::Painter, proj: &Proj, a: V } } +/// The tapers (degrees, least and most) a drag of the taper handle may reach for `regions` +/// extruded `height` (#1602): going in, the sides close the material where they have moved its +/// inradius; going out, they close the smallest hole. Each stops just short, so the drag ends at +/// the largest taper that builds instead of one that fails. A typed angle is not limited. +pub(crate) fn taper_limits(regions: &[&solidcraft_engine::geom::Region2], height: f64) -> (f64, f64) { + const MAX: f64 = 89.0; + if !(height > 1e-9) || regions.is_empty() { + return (-MAX, MAX); + } + let at = |r: f64| (0.99 * r / height).atan().to_degrees().min(MAX); + let inward = regions.iter().map(|r| r.inradius(1e-3)).fold(f64::INFINITY, f64::min); + let outward = regions.iter().flat_map(|r| &r.holes).map(|h| h.inradius(1e-3)).fold(f64::INFINITY, f64::min); + (if inward.is_finite() { -at(inward) } else { -MAX }, if outward.is_finite() { at(outward) } else { MAX }) +} + /// The taper handle: a line from `foot` along the extrude (`span`) leaning by `angle` towards /// `e`, with a ring at its end; dragging the ring sideways sets the angle (1° steps, Alt/Ctrl: -/// free). +/// free), within `limits` ([`taper_limits`]). #[allow(clippy::too_many_arguments)] -fn taper_handle(ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj, foot: Vec3, span: Vec3, e: Vec3, angle: f64, value: &mut String) { +fn taper_handle( + ui: &mut egui::Ui, + painter: &egui::Painter, + proj: &Proj, + foot: Vec3, + span: Vec3, + e: Vec3, + angle: f64, + limits: (f64, f64), + value: &mut String, +) { let t = Tokens::get(); let l = span.len(); let end = foot + span + e * (l * angle.tan().clamp(-10.0, 10.0)); let (Some(fs), Some(es)) = (proj.to_screen(foot), proj.to_screen(end)) else { return }; let r = ui.interact(egui::Rect::from_center_size(es, vec2(16.0, 16.0)), egui::Id::new("sc_taper"), egui::Sense::drag()); + crate::scenario::publish_handle("taper", es); let hot = r.hovered() || r.dragged(); let col = if hot { t.accent } else { t.manipulator }; painter.add(egui::Shape::dashed_line(&[fs, es], Stroke::new(1.2, col), 5.0, 3.0)); @@ -879,8 +918,12 @@ fn taper_handle(ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj, foot: V && let Some(s) = along(proj, p, foot + span, e) { let mut deg = s.atan2(l).to_degrees(); - if !ui.input(|i| i.modifiers.alt || i.modifiers.ctrl || i.modifiers.command) { - deg = deg.round(); + let (lo, hi) = limits; + if ui.input(|i| i.modifiers.alt || i.modifiers.ctrl || i.modifiers.command) { + deg = deg.clamp(lo, hi); + } else { + // Whole degrees, rounded towards zero at a limit so they stay inside it. + deg = deg.round().clamp(lo.ceil().min(0.0), hi.floor().max(0.0)); } let txt = format!("{deg:.1}"); *value = format!("{} deg", txt.trim_end_matches('0').trim_end_matches('.')); @@ -1262,3 +1305,32 @@ mod tests { assert_eq!(format_len(-0.0001), "0 mm"); } } + +#[cfg(test)] +mod taper_limit_tests { + use super::taper_limits; + use solidcraft_engine::geom::{Loop2, Region2, Vec2}; + + /// #1602: a drag stops just short of the taper that closes the profile, either way. + #[test] + fn a_taper_drag_stops_before_the_profile_closes() { + let close = |a: f64, b: f64| (a - b).abs() < 0.05; + let deg = |r: f64, h: f64| (0.99 * r / h).atan().to_degrees(); + // A 10 × 4 rectangle 26 high: going in closes at its half width; going out never does. + let rect = Region2 { + outer: Loop2::polygon(&[Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), Vec2::new(10.0, 4.0), Vec2::new(0.0, 4.0)]), + holes: Vec::new(), + }; + let (lo, hi) = taper_limits(&[&rect], 26.0); + assert!(close(lo, -deg(2.0, 26.0)) && hi == 89.0, "{lo} {hi}"); + // A ring 10 to 6, 10 high: in, its 4 mm wall; out, its hole of radius 6. + let ring = Region2 { outer: Loop2::circle(Vec2::ZERO, 10.0), holes: vec![Loop2::circle(Vec2::ZERO, 6.0).reversed()] }; + let (lo, hi) = taper_limits(&[&ring], 10.0); + assert!(close(lo, -deg(2.0, 10.0)) && close(hi, deg(6.0, 10.0)), "{lo} {hi}"); + // The tightest of several profiles; no profile or no height, no limit. + let (lo, _) = taper_limits(&[&ring, &rect], 10.0); + assert!(close(lo, -deg(2.0, 10.0))); + assert_eq!(taper_limits(&[], 10.0), (-89.0, 89.0)); + assert_eq!(taper_limits(&[&rect], 0.0), (-89.0, 89.0)); + } +} From f57a62deb7c8ee9c7f23fa6fec29dc93f2452caf Mon Sep 17 00:00:00 2001 From: Irakli Kourtis Date: Fri, 16 Oct 2026 03:00:56 -0400 Subject: [PATCH 83/92] Intersection edge nodes advance along the curve at fine display qualities (#1615) Thanks @jyviko. --- crates/engine/src/boolean_regression_tests.rs | 24 + crates/kernel/src/tess/ssi.rs | 93 +- .../front_triangle_hull_triangle.json | 836 ++++++++++++++++++ .../loft_join_bracket_hull_triangle.json | 305 +++++++ 4 files changed, 1243 insertions(+), 15 deletions(-) create mode 100644 examples/regressions/front_triangle_hull_triangle.json create mode 100644 examples/regressions/loft_join_bracket_hull_triangle.json diff --git a/crates/engine/src/boolean_regression_tests.rs b/crates/engine/src/boolean_regression_tests.rs index 9041841fa..5f89fc151 100644 --- a/crates/engine/src/boolean_regression_tests.rs +++ b/crates/engine/src/boolean_regression_tests.rs @@ -288,3 +288,27 @@ fn cut_of_a_whole_face_beside_round_corners_after_a_chamfer() { let top = mesh.bounds().max.z; assert!((top - 15.0).abs() < 1e-6, "top at {top}"); } + +/// The display tessellation of loft bodies joined into a bike frame plans at every display +/// quality and every refinement step. The edge nodes on an intersection of two lofts once +/// stepped back along the curve (the edge's fit rang where truck's parameter changes speed, and +/// took a leader point off the curve past a vertex), so a face's boundary crossed itself and +/// the body fell back to the reference mesher, which drew a sheet across the down tube. +#[test] +fn joined_loft_frames_plan_their_display_at_every_quality() { + use solidcraft_doc::display_quality::{DisplayQuality, MAX_REFINE}; + for (script, name) in [ + (include_str!("../../../examples/regressions/loft_join_bracket_hull_triangle.json"), "DT2"), + (include_str!("../../../examples/regressions/front_triangle_hull_triangle.json"), "FrontTriangle"), + ] { + let s = replay(script); + let state = s.model.state(); + let body = &state.body(name).unwrap().body; + for q in DisplayQuality::ALL { + for k in 0..=MAX_REFINE { + let plan = body.display_plan_angular(q.refined_chord(body.size(), k), q.refined_angle(k)); + assert!(plan.is_ok(), "{name} at {} + {k}: {:?}", q.id(), plan.err()); + } + } + } +} diff --git a/crates/kernel/src/tess/ssi.rs b/crates/kernel/src/tess/ssi.rs index c69a36c58..ca32e9487 100644 --- a/crates/kernel/src/tess/ssi.rs +++ b/crates/kernel/src/tess/ssi.rs @@ -5,8 +5,13 @@ //! each surface in turn from no starting guess: a nearest-point search per surface per point. //! Here the intersection is solved exactly at a set of leader parameters, and a cubic B-spline //! is fitted through those points together with both surfaces' parameters there (a smooth -//! leader with its curves on both surfaces). Each point is then refined from the B-spline by -//! Newton's method on the four unknowns (u1, v1, u2, v2): S1(u1, v1) = S2(u2, v2), held on the +//! leader with its curves on both surfaces). The B-spline runs over the chord length of the +//! solved points, never over the curve's own parameter: truck's parameter can change speed +//! abruptly (a polyline leader with short and long spans), and a cubic interpolated over it +//! rings there, stepping back along the curve (Lee, "Choosing nodes in parametric curve +//! interpolation", CAD 21, 1989). The curve's parameter reaches the chord length through the +//! piecewise-linear map between the seeds, which is monotone. Each point is then refined from +//! the B-spline by Newton's method on the four unknowns (u1, v1, u2, v2): S1(u1, v1) = S2(u2, v2), held on the //! plane through the B-spline point normal to the B-spline (Barnhill & Kersey, "A marching //! method for parametric surface/surface intersection", CAGD 7, 1990; Patrikalakis & Maekawa, //! "Shape Interrogation for CAD/CAM", 2002, ch. 5). Every point is independent once seeded. Where the surfaces are close to @@ -34,9 +39,11 @@ const MIN_SIN: f64 = 0.05; pub(crate) struct Intersection { surfaces: [EvalSurface; 2], domains: [Domain; 2], - /// The smooth leader over the curve's parameter: the intersection point (x, y, z) and both - /// surfaces' parameters (u1, v1, u2, v2), periodic directions unwrapped along it. + /// The smooth leader over the chord length of the seeds: the intersection point (x, y, z) + /// and both surfaces' parameters (u1, v1, u2, v2), periodic directions unwrapped along it. leader: CurveN<7>, + /// The curve's parameter at each seed and the chord length there, both increasing. + seeds: Vec<(f64, f64)>, /// Convergence tolerance (mm). eps: f64, } @@ -59,8 +66,14 @@ impl Intersection { // The leader lies within the curve's tolerance of both surfaces. let accept = (ic.tolerance() * 100.0).max(1e-6); let scale = (0..=SEEDS).map(|k| leader(t0 + (t1 - t0) * k as f64 / SEEDS as f64).0.len()).fold(1.0, f64::max); - let mut it = Intersection { surfaces, domains, leader: CurveN { degree: 1, knots: Vec::new(), ctrl: Vec::new() }, eps: scale * 1e-10 }; - let (mut params, mut points) = (Vec::with_capacity(SEEDS + 1), Vec::with_capacity(SEEDS + 1)); + let mut it = Intersection { + surfaces, + domains, + leader: CurveN { degree: 1, knots: Vec::new(), ctrl: Vec::new() }, + seeds: Vec::new(), + eps: scale * 1e-10, + }; + let (mut params, mut points): (Vec, Vec<[f64; 7]>) = (Vec::with_capacity(SEEDS + 1), Vec::with_capacity(SEEDS + 1)); let mut prev: Option<[f64; 4]> = None; for k in 0..=SEEDS { let t = t0 + (t1 - t0) * k as f64 / SEEDS as f64; @@ -77,25 +90,60 @@ impl Intersection { q[2 * i] = uv[0]; q[2 * i + 1] = uv[1]; } - // Exactly on the intersection where Newton converges (near-tangent seeds keep the - // leader point and its projections). - let (p, q) = d.normalized().and_then(|dir| it.newton(p, dir, q)).unwrap_or((p, q)); - params.push(t); + // The fit takes only points exactly on the intersection: a leader point Newton + // cannot place (near-tangent, or the solution leaves a surface's domain where a + // polyline leader overshoots a vertex) is off the curve and would bend the fit back + // along it. The ends stay either way, so the fit spans the whole curve. + let solved = d.normalized().and_then(|dir| it.newton(p, dir, q)); + prev = Some(solved.map_or(q, |(_, q)| q)); + let (p, q) = match solved { + Some(x) => x, + None if k == 0 || k == SEEDS => (p, q), + None => continue, + }; + // A seed that lands on the previous one adds no chord and stays out of the fit + // (whose parameters must increase). + let s = match it.seeds.last().zip(points.last()) { + Some((&(_, s), &[x, y, z, ..])) => { + let chord = p.dist(Vec3::new(x, y, z)); + if !(chord > it.eps) { + continue; + } + s + chord + } + None => 0.0, + }; + it.seeds.push((t, s)); + params.push(s); points.push([p.x, p.y, p.z, q[0], q[1], q[2], q[3]]); - prev = Some(q); } - it.leader = CurveN::interpolate(¶ms, &points, 3).ok()?; + let degree = points.len().checked_sub(1)?.min(3); + it.leader = CurveN::interpolate(¶ms, &points, degree).ok()?; Some(it) } /// The point at curve parameter `t` and both surfaces' parameters there, or `None` /// (near-tangent, or Newton failed). pub(crate) fn eval(&self, t: f64) -> Option<(Vec3, [f64; 4])> { - let (x, dx) = self.leader.eval(t)?; + let (x, dx) = self.leader.eval(self.chord_at(t)?)?; let dir = Vec3::new(dx[0], dx[1], dx[2]).normalized()?; self.newton(Vec3::new(x[0], x[1], x[2]), dir, [x[3], x[4], x[5], x[6]]) } + /// The chord length at curve parameter `t`: linear between the seeds, clamped to the ends. + fn chord_at(&self, t: f64) -> Option { + let (&(ta, sa), &(tb, sb)) = (self.seeds.first()?, self.seeds.last()?); + if !(t > ta) { + return Some(sa); + } + if !(t < tb) { + return Some(sb); + } + let k = self.seeds.partition_point(|&(tk, _)| tk <= t); + let (Some(&(t0, s0)), Some(&(t1, s1))) = (<[_]>::get(&self.seeds, k.checked_sub(1)?), <[_]>::get(&self.seeds, k)) else { return None }; + Some(s0 + (s1 - s0) * (t - t0) / (t1 - t0)) + } + /// The two surfaces, in the order of the parameters [`Intersection::eval`] gives. pub(crate) fn surfaces(&self) -> &[EvalSurface; 2] { &self.surfaces @@ -186,7 +234,7 @@ mod tests { /// Points on the intersection edges of a boolean (a cross hole: two cylinders) lie on both /// surfaces, on truck's curve (the parameterisation follows our smooth leader, so the same - /// parameter may sit at a slightly different place along it), and advance along the curve. + /// parameter may sit at a slightly different place along it), and advance along it. #[test] fn intersection_points_lie_on_both_surfaces_and_on_truck_s_curve() { let Ok(pin) = crate::cylinder(Vec3::new(5.0, 5.0, -1.0), Vec3::Z, 2.0, 6.0) else { panic!("pin") }; @@ -199,6 +247,21 @@ mod tests { let (t0, t1) = curve.range_tuple(); let dense: Vec = (0..=1000).map(|k| from_p3(curve.subs(t0 + (t1 - t0) * f64::from(k) / 1000.0))).collect(); let near = |p: Vec3| dense.windows(2).map(|w| p.dist_to_segment(w[0], w[1])).fold(f64::MAX, f64::min); + // Arc length along truck's curve to the point nearest `p`. + let along = |p: Vec3| { + let (mut run, mut best) = (0.0, (f64::MAX, 0.0)); + for w in dense.windows(2) { + let (a, b) = (w[0], w[1]); + let len = a.dist(b); + let f = if len > 0.0 { ((p - a).dot(b - a) / (len * len)).clamp(0.0, 1.0) } else { 0.0 }; + let d = p.dist(a + (b - a) * f); + if d < best.0 { + best = (d, run + f * len); + } + run += len; + } + best.1 + }; let mut last: Option = None; for k in 0..=50 { let t = t0 + (t1 - t0) * f64::from(k) / 50.0; @@ -208,7 +271,7 @@ mod tests { } assert!(near(p) < 1e-4, "t {t}: {p:?} is {} from truck's curve", near(p)); if let Some(q) = last { - assert!(p.dist(q) > 0.0, "t {t}: the points advance"); + assert!(along(p) > along(q), "t {t}: the points advance along the curve"); } last = Some(p); checked += 1; diff --git a/examples/regressions/front_triangle_hull_triangle.json b/examples/regressions/front_triangle_hull_triangle.json new file mode 100644 index 000000000..83bff9a35 --- /dev/null +++ b/examples/regressions/front_triangle_hull_triangle.json @@ -0,0 +1,836 @@ +{ + "description": "Bike front triangle (lofted tubes joined to a bottom-bracket cylinder): the display mesh drew a flat triangle inside the down tube bend at Fine/Ultra.", + "commands": [ + { + "command": "sketch.create", + "params": { + "plane": { + "origin": [ + 12, + 0.0, + 18 + ], + "x_dir": [ + 0.0, + 1.0, + 0.0 + ], + "y_dir": [ + -0.947, + 0.0, + -0.322 + ] + }, + "name": "S13" + } + }, + { + "command": "sketch.ellipse", + "params": { + "center": [ + 0, + 0 + ], + "major": [ + 19.0, + 0 + ], + "minor_radius": 18.0 + } + }, + { + "command": "sketch.finish", + "params": {} + }, + { + "command": "sketch.create", + "params": { + "plane": { + "origin": [ + -13.0, + 0.0, + 91.5 + ], + "x_dir": [ + 0.0, + 1.0, + 0.0 + ], + "y_dir": [ + -0.947, + 0.0, + -0.322 + ] + }, + "name": "S14" + } + }, + { + "command": "sketch.ellipse", + "params": { + "center": [ + 0, + 0 + ], + "major": [ + 27.0, + 0 + ], + "minor_radius": 24.0 + } + }, + { + "command": "sketch.finish", + "params": {} + }, + { + "command": "sketch.create", + "params": { + "plane": { + "origin": [ + -38, + 0.0, + 165 + ], + "x_dir": [ + 0.0, + 1.0, + 0.0 + ], + "y_dir": [ + -0.959, + 0.0, + -0.282 + ] + }, + "name": "S15" + } + }, + { + "command": "sketch.ellipse", + "params": { + "center": [ + 0, + 0 + ], + "major": [ + 24.0, + 0 + ], + "minor_radius": 22.0 + } + }, + { + "command": "sketch.finish", + "params": {} + }, + { + "command": "sketch.create", + "params": { + "plane": { + "origin": [ + -76.646, + 0.0, + 320.0 + ], + "x_dir": [ + 0.0, + 1.0, + 0.0 + ], + "y_dir": [ + -0.97, + 0.0, + -0.242 + ] + }, + "name": "S16" + } + }, + { + "command": "sketch.circle.center", + "params": { + "center": [ + 0, + 0 + ], + "radius": 20.0 + } + }, + { + "command": "sketch.finish", + "params": {} + }, + { + "command": "sketch.create", + "params": { + "plane": { + "origin": [ + -110.577, + 0.0, + 456.089 + ], + "x_dir": [ + 0.0, + 1.0, + 0.0 + ], + "y_dir": [ + -0.97, + 0.0, + -0.242 + ] + }, + "name": "S17" + } + }, + { + "command": "sketch.circle.center", + "params": { + "center": [ + 0, + 0 + ], + "radius": 19.0 + } + }, + { + "command": "sketch.finish", + "params": {} + }, + { + "command": "solid.loft", + "params": { + "sections": [ + { + "sketch": "S13" + }, + { + "sketch": "S14" + }, + { + "sketch": "S15" + }, + { + "sketch": "S16" + }, + { + "sketch": "S17" + } + ], + "operation": "new", + "name": "SeatTube", + "body_name": "SeatTube" + } + }, + { + "command": "solid.cylinder", + "params": { + "diameter": 46, + "height": 73.0, + "base": [ + 0, + -36.5, + 0 + ], + "axis": "Y", + "operation": "new", + "name": "BBShell", + "body_name": "BBShell" + } + }, + { + "command": "sketch.create", + "params": { + "plane": { + "origin": [ + 459.471, + 0.0, + 607.143 + ], + "x_dir": [ + 0.0, + 1.0, + 0.0 + ], + "y_dir": [ + 0.349, + 0.0, + -0.937 + ] + }, + "name": "S10" + } + }, + { + "command": "sketch.ellipse", + "params": { + "center": [ + 0, + 0 + ], + "major": [ + 22.0, + 0 + ], + "minor_radius": 20.0 + } + }, + { + "command": "sketch.finish", + "params": {} + }, + { + "command": "sketch.create", + "params": { + "plane": { + "origin": [ + 181.44, + 0.0, + 503.572 + ], + "x_dir": [ + 0.0, + 1.0, + 0.0 + ], + "y_dir": [ + 0.349, + 0.0, + -0.937 + ] + }, + "name": "S11" + } + }, + { + "command": "sketch.ellipse", + "params": { + "center": [ + 0, + 0 + ], + "major": [ + 27.0, + 0 + ], + "minor_radius": 23.0 + } + }, + { + "command": "sketch.finish", + "params": {} + }, + { + "command": "sketch.create", + "params": { + "plane": { + "origin": [ + -96.592, + 0.0, + 400.0 + ], + "x_dir": [ + 0.0, + 1.0, + 0.0 + ], + "y_dir": [ + 0.349, + 0.0, + -0.937 + ] + }, + "name": "S12" + } + }, + { + "command": "sketch.ellipse", + "params": { + "center": [ + 0, + 0 + ], + "major": [ + 17.0, + 0 + ], + "minor_radius": 16.0 + } + }, + { + "command": "sketch.finish", + "params": {} + }, + { + "command": "solid.loft", + "params": { + "sections": [ + { + "sketch": "S10" + }, + { + "sketch": "S11" + }, + { + "sketch": "S12" + } + ], + "operation": "new", + "name": "TopTube", + "body_name": "TopTube" + } + }, + { + "command": "sketch.create", + "params": { + "plane": { + "origin": [ + 501.231, + 0.0, + 519.592 + ], + "x_dir": [ + 0.0, + 1.0, + 0.0 + ], + "y_dir": [ + -0.903, + 0.0, + -0.431 + ] + }, + "name": "S1" + } + }, + { + "command": "sketch.circle.center", + "params": { + "center": [ + 0, + 0 + ], + "radius": 32.0 + } + }, + { + "command": "sketch.finish", + "params": {} + }, + { + "command": "sketch.create", + "params": { + "plane": { + "origin": [ + 473.678, + 0.0, + 577.358 + ], + "x_dir": [ + 0.0, + 1.0, + 0.0 + ], + "y_dir": [ + -0.903, + 0.0, + -0.431 + ] + }, + "name": "S2" + } + }, + { + "command": "sketch.circle.center", + "params": { + "center": [ + 0, + 0 + ], + "radius": 28.0 + } + }, + { + "command": "sketch.finish", + "params": {} + }, + { + "command": "sketch.create", + "params": { + "plane": { + "origin": [ + 447.417, + 0.0, + 632.416 + ], + "x_dir": [ + 0.0, + 1.0, + 0.0 + ], + "y_dir": [ + -0.903, + 0.0, + -0.431 + ] + }, + "name": "S3" + } + }, + { + "command": "sketch.circle.center", + "params": { + "center": [ + 0, + 0 + ], + "radius": 26.0 + } + }, + { + "command": "sketch.finish", + "params": {} + }, + { + "command": "solid.loft", + "params": { + "sections": [ + { + "sketch": "S1" + }, + { + "sketch": "S2" + }, + { + "sketch": "S3" + } + ], + "operation": "new", + "name": "HeadTube", + "body_name": "HeadTube" + } + }, + { + "command": "sketch.create", + "params": { + "plane": { + "origin": [ + 8, + 0.0, + 3 + ], + "x_dir": [ + 0.0, + 1.0, + 0.0 + ], + "y_dir": [ + -0.178, + 0.0, + 0.984 + ] + }, + "name": "S4" + } + }, + { + "command": "sketch.rectangle.rounded", + "params": { + "p0": [ + -19.0, + -18.0 + ], + "p1": [ + 19.0, + 18.0 + ], + "radius": 10.799999999999999 + } + }, + { + "command": "sketch.finish", + "params": {} + }, + { + "command": "sketch.create", + "params": { + "plane": { + "origin": [ + 80, + 0.0, + 16 + ], + "x_dir": [ + 0.0, + 1.0, + 0.0 + ], + "y_dir": [ + -0.211, + 0.0, + 0.977 + ] + }, + "name": "S5" + } + }, + { + "command": "sketch.rectangle.rounded", + "params": { + "p0": [ + -30.0, + -26.0 + ], + "p1": [ + 30.0, + 26.0 + ], + "radius": 15.6 + } + }, + { + "command": "sketch.finish", + "params": {} + }, + { + "command": "sketch.create", + "params": { + "plane": { + "origin": [ + 175, + 0.0, + 40 + ], + "x_dir": [ + 0.0, + 1.0, + 0.0 + ], + "y_dir": [ + -0.596, + 0.0, + 0.803 + ] + }, + "name": "S6" + } + }, + { + "command": "sketch.rectangle.rounded", + "params": { + "p0": [ + -38.0, + -33.0 + ], + "p1": [ + 38.0, + 33.0 + ], + "radius": 19.8 + } + }, + { + "command": "sketch.finish", + "params": {} + }, + { + "command": "sketch.create", + "params": { + "plane": { + "origin": [ + 314.248, + 0.0, + 271.657 + ], + "x_dir": [ + 0.0, + 1.0, + 0.0 + ], + "y_dir": [ + -0.857, + 0.0, + 0.515 + ] + }, + "name": "S7" + } + }, + { + "command": "sketch.rectangle.rounded", + "params": { + "p0": [ + -37.0, + -33.0 + ], + "p1": [ + 37.0, + 33.0 + ], + "radius": 19.8 + } + }, + { + "command": "sketch.finish", + "params": {} + }, + { + "command": "sketch.create", + "params": { + "plane": { + "origin": [ + 422.553, + 0.0, + 451.835 + ], + "x_dir": [ + 0.0, + 1.0, + 0.0 + ], + "y_dir": [ + -0.857, + 0.0, + 0.515 + ] + }, + "name": "S8" + } + }, + { + "command": "sketch.rectangle.rounded", + "params": { + "p0": [ + -33.0, + -30.0 + ], + "p1": [ + 33.0, + 30.0 + ], + "radius": 18.0 + } + }, + { + "command": "sketch.finish", + "params": {} + }, + { + "command": "sketch.create", + "params": { + "plane": { + "origin": [ + 484.441, + 0.0, + 554.793 + ], + "x_dir": [ + 0.0, + 1.0, + 0.0 + ], + "y_dir": [ + -0.857, + 0.0, + 0.515 + ] + }, + "name": "S9" + } + }, + { + "command": "sketch.rectangle.rounded", + "params": { + "p0": [ + -23.0, + -22.0 + ], + "p1": [ + 23.0, + 22.0 + ], + "radius": 13.2 + } + }, + { + "command": "sketch.finish", + "params": {} + }, + { + "command": "solid.loft", + "params": { + "sections": [ + { + "sketch": "S4" + }, + { + "sketch": "S5" + }, + { + "sketch": "S6" + }, + { + "sketch": "S7" + }, + { + "sketch": "S8" + }, + { + "sketch": "S9" + } + ], + "operation": "new", + "name": "DownTube", + "body_name": "DownTube" + } + }, + { + "command": "solid.combine", + "params": { + "target": "SeatTube", + "tools": [ + "BBShell" + ], + "operation": "join" + } + }, + { + "command": "solid.combine", + "params": { + "target": "SeatTube", + "tools": [ + "TopTube" + ], + "operation": "join" + } + }, + { + "command": "solid.combine", + "params": { + "target": "SeatTube", + "tools": [ + "HeadTube" + ], + "operation": "join" + } + }, + { + "command": "solid.combine", + "params": { + "target": "SeatTube", + "tools": [ + "DownTube" + ], + "operation": "join" + } + }, + { + "command": "body.rename", + "params": { + "body": "SeatTube", + "name": "FrontTriangle" + } + } + ] +} \ No newline at end of file diff --git a/examples/regressions/loft_join_bracket_hull_triangle.json b/examples/regressions/loft_join_bracket_hull_triangle.json new file mode 100644 index 000000000..640672c47 --- /dev/null +++ b/examples/regressions/loft_join_bracket_hull_triangle.json @@ -0,0 +1,305 @@ +{ + "description": "A lofted down tube (rounded-rectangle sections, widest 82 mm) joined to a 46 mm \u00d7 73 mm bottom-bracket cylinder: the display mesh of the tube's side face gained a flat triangle across the inside of its bend.", + "commands": [ + { + "command": "sketch.create", + "params": { + "plane": { + "origin": [ + -4, + 0.0, + 2 + ], + "x_dir": [ + 0.0, + 1.0, + 0.0 + ], + "y_dir": [ + -0.164, + 0.0, + 0.986 + ] + }, + "name": "S4b" + } + }, + { + "command": "sketch.rectangle.rounded", + "params": { + "p0": [ + -19.0, + -18.0 + ], + "p1": [ + 19.0, + 18.0 + ], + "radius": 10.799999999999999 + } + }, + { + "command": "sketch.finish", + "params": {} + }, + { + "command": "sketch.create", + "params": { + "plane": { + "origin": [ + 80, + 0.0, + 16 + ], + "x_dir": [ + 0.0, + 1.0, + 0.0 + ], + "y_dir": [ + -0.205, + 0.0, + 0.979 + ] + }, + "name": "S5b" + } + }, + { + "command": "sketch.rectangle.rounded", + "params": { + "p0": [ + -41.0, + -33.0 + ], + "p1": [ + 41.0, + 33.0 + ], + "radius": 19.8 + } + }, + { + "command": "sketch.finish", + "params": {} + }, + { + "command": "sketch.create", + "params": { + "plane": { + "origin": [ + 175, + 0.0, + 40 + ], + "x_dir": [ + 0.0, + 1.0, + 0.0 + ], + "y_dir": [ + -0.596, + 0.0, + 0.803 + ] + }, + "name": "S6b" + } + }, + { + "command": "sketch.rectangle.rounded", + "params": { + "p0": [ + -41.0, + -35.0 + ], + "p1": [ + 41.0, + 35.0 + ], + "radius": 21.0 + } + }, + { + "command": "sketch.finish", + "params": {} + }, + { + "command": "sketch.create", + "params": { + "plane": { + "origin": [ + 314.248, + 0.0, + 271.657 + ], + "x_dir": [ + 0.0, + 1.0, + 0.0 + ], + "y_dir": [ + -0.857, + 0.0, + 0.515 + ] + }, + "name": "S7b" + } + }, + { + "command": "sketch.rectangle.rounded", + "params": { + "p0": [ + -39.0, + -35.0 + ], + "p1": [ + 39.0, + 35.0 + ], + "radius": 21.0 + } + }, + { + "command": "sketch.finish", + "params": {} + }, + { + "command": "sketch.create", + "params": { + "plane": { + "origin": [ + 422.553, + 0.0, + 451.835 + ], + "x_dir": [ + 0.0, + 1.0, + 0.0 + ], + "y_dir": [ + -0.857, + 0.0, + 0.515 + ] + }, + "name": "S8b" + } + }, + { + "command": "sketch.rectangle.rounded", + "params": { + "p0": [ + -35.0, + -32.0 + ], + "p1": [ + 35.0, + 32.0 + ], + "radius": 19.2 + } + }, + { + "command": "sketch.finish", + "params": {} + }, + { + "command": "sketch.create", + "params": { + "plane": { + "origin": [ + 484.441, + 0.0, + 554.793 + ], + "x_dir": [ + 0.0, + 1.0, + 0.0 + ], + "y_dir": [ + -0.857, + 0.0, + 0.515 + ] + }, + "name": "S9b" + } + }, + { + "command": "sketch.rectangle.rounded", + "params": { + "p0": [ + -23.0, + -22.0 + ], + "p1": [ + 23.0, + 22.0 + ], + "radius": 13.2 + } + }, + { + "command": "sketch.finish", + "params": {} + }, + { + "command": "solid.loft", + "params": { + "sections": [ + { + "sketch": "S4b" + }, + { + "sketch": "S5b" + }, + { + "sketch": "S6b" + }, + { + "sketch": "S7b" + }, + { + "sketch": "S8b" + }, + { + "sketch": "S9b" + } + ], + "operation": "new", + "name": "DT2", + "body_name": "DT2" + } + }, + { + "command": "solid.cylinder", + "params": { + "diameter": 46, + "height": 73.0, + "base": [ + 0, + -36.5, + 0 + ], + "axis": "Y", + "operation": "new", + "name": "BBShell", + "body_name": "BBShell" + } + }, + { + "command": "solid.combine", + "params": { + "target": "DT2", + "tools": [ + "BBShell" + ], + "operation": "join" + } + } + ] +} \ No newline at end of file From 9422853cf9ee761675a9ba8b910323cf158d14bb Mon Sep 17 00:00:00 2001 From: Karl Von Richter Date: Fri, 16 Oct 2026 17:01:00 +1000 Subject: [PATCH 84/92] Feature mirrors and patterns: preserve replay and add Flip/Center placement (#1619) Thanks @Karl-VonRichter. --- crates/doc/src/document.rs | 16 ++ crates/doc/src/eval.rs | 8 +- .../pending/feature-pattern-alignment.rs | 4 + crates/doc/src/walk.rs | 1 + crates/engine/src/cmd/features.rs | 26 ++- crates/engine/src/cmd/mod.rs | 12 ++ crates/engine/src/cmd/patterns_tests.rs | 91 +++++++++++ crates/engine/src/cmd/sketch_pattern.rs | 13 +- crates/ui-egui/src/dialogs.rs | 124 +++++++++++--- crates/ui-egui/src/preselect_tests.rs | 153 ++++++++++++++++++ docs/feature-patterns.md | 49 ++++++ 11 files changed, 456 insertions(+), 41 deletions(-) create mode 100644 crates/doc/src/format/pending/feature-pattern-alignment.rs create mode 100644 docs/feature-patterns.md diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index c7c142f9a..37062da19 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -1721,6 +1721,14 @@ pub enum PatternKind { #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(length = "Spacing 2")] spacing2: Option, + #[serde(default, skip_serializing_if = "default_pattern_alignment")] + alignment: solidcraft_sketch::PatternAlignment, + #[serde(default, skip_serializing_if = "default_pattern_alignment")] + alignment2: solidcraft_sketch::PatternAlignment, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + reversed: bool, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + reversed2: bool, }, Circular { origin: Position, @@ -1730,6 +1738,10 @@ pub enum PatternKind { /// Total angle (360 deg = evenly around). #[walk(angle = "Total angle")] angle: Expr, + #[serde(default, skip_serializing_if = "default_pattern_alignment")] + alignment: solidcraft_sketch::PatternAlignment, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + reversed: bool, }, /// Copies along a chain of sketch curves: instance k moves by path(k·spacing) − path(0), /// measured along the path from its start. @@ -1753,6 +1765,10 @@ pub enum PatternKind { }, } +fn default_pattern_alignment(alignment: &solidcraft_sketch::PatternAlignment) -> bool { + *alignment == solidcraft_sketch::PatternAlignment::Right +} + fn z_axis() -> Dir { Dir(Vec3::Z) } diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 10fecf971..d2b523196 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -3561,7 +3561,7 @@ fn pattern_transforms(doc: &Document, vals: &BTreeMap, st: &Model }; let mut out = Vec::new(); match p { - crate::PatternKind::Rectangular { dir1, count1, spacing1, dir2, count2, spacing2 } => { + crate::PatternKind::Rectangular { dir1, count1, spacing1, dir2, count2, spacing2, alignment, alignment2, reversed, reversed2 } => { let (n1, s1) = (count(count1)?, val(vals, spacing1, Kind::Length)?); let d1 = dir1.normalized().ok_or_else(|| DocError::Invalid("pattern direction".into()))?; let (n2, s2, d2) = match (dir2, count2, spacing2) { @@ -3578,7 +3578,7 @@ fn pattern_transforms(doc: &Document, vals: &BTreeMap, st: &Model if i == 0 && j == 0 { continue; } - out.push(translation(d1 * (s1 * i as f64) + d2 * (s2 * j as f64))); + out.push(translation(d1 * (s1 * alignment.multiplier(i, *reversed)) + d2 * (s2 * alignment2.multiplier(j, *reversed2)))); } } } @@ -3615,7 +3615,7 @@ fn pattern_transforms(doc: &Document, vals: &BTreeMap, st: &Model out.push(m); } } - crate::PatternKind::Circular { origin, axis, count: c, angle } => { + crate::PatternKind::Circular { origin, axis, count: c, angle, alignment, reversed } => { let n = count(c)?; let total = val(vals, angle, Kind::Angle)?; let full = (total.abs() - std::f64::consts::TAU).abs() < 1e-9; @@ -3627,7 +3627,7 @@ fn pattern_transforms(doc: &Document, vals: &BTreeMap, st: &Model 0.0 }; for i in 1..n { - out.push(rotation(origin.0, axis.0, step * i as f64)); + out.push(rotation(origin.0, axis.0, step * alignment.multiplier(i, *reversed))); } } } diff --git a/crates/doc/src/format/pending/feature-pattern-alignment.rs b/crates/doc/src/format/pending/feature-pattern-alignment.rs new file mode 100644 index 000000000..09e3f13da --- /dev/null +++ b/crates/doc/src/format/pending/feature-pattern-alignment.rs @@ -0,0 +1,4 @@ +//! Rectangular and circular feature patterns store alignment and reversal, independently for +//! each rectangular direction. Defaults preserve older positive-direction placements. +//! Center retains the source and alternates copies on either side, as sketch patterns do. +//! The last release refuses this pending format and asks for an update instead of losing it. diff --git a/crates/doc/src/walk.rs b/crates/doc/src/walk.rs index 64726064c..64073b311 100644 --- a/crates/doc/src/walk.rs +++ b/crates/doc/src/walk.rs @@ -42,6 +42,7 @@ impl Walk for i8 {} impl Walk for f64 {} impl Walk for ProfileSel {} impl Walk for solidcraft_sketch::Sketch {} +impl Walk for solidcraft_sketch::PatternAlignment {} impl Walk for solidcraft_kernel::StepNode {} impl Walk for crate::document::Operation {} impl Walk for solidcraft_kernel::Continuity {} diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs index a86ad7bd6..170f1419e 100644 --- a/crates/engine/src/cmd/features.rs +++ b/crates/engine/src/cmd/features.rs @@ -41,11 +41,11 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("solid.pattern.rectangular", "Rectangular Pattern", pattern_rect) .at("SOLID", "CREATE") .icon("pattern_rect") - .params("features: [names] | bodies: [names] | components: [names]; dir1: [x,y,z]; count1; spacing1; dir2?, count2?, spacing2?"), + .params("features: [names] | bodies: [names] | components: [names]; dir1: [x,y,z]; count1; spacing1; dir2?, count2?, spacing2?; alignment?, alignment2?: left|center|right (default right; counts include the original); reversed?, reversed2?: bool (Flip)"), CommandSpec::new("solid.pattern.circular", "Circular Pattern", pattern_circ) .at("SOLID", "CREATE") .icon("pattern_circ") - .params("features: [names] | bodies: [names] | components: [names]; axis: X|Y|Z | {origin, dir}; count; angle? (default 360 deg)"), + .params("features: [names] | bodies: [names] | components: [names]; axis: X|Y|Z | {origin, dir}; count; angle? (default 360 deg; partial arcs include both ends); alignment?: left|center|right (default right; original stays fixed); reversed?: bool (Flip; selects the extra side for even centered counts)"), CommandSpec::new("solid.pattern.path", "Pattern on Path", pattern_path) .at("SOLID", "CREATE") .icon("pattern_rect") @@ -1263,7 +1263,18 @@ fn pattern_rect(s: &mut Session, p: &Value) -> Result { if let Some(c) = &spacing2 { check_expr(s, c, Kind::Length, cmd, "spacing2")?; } - let pattern = solidcraft_doc::PatternKind::Rectangular { dir1: Dir(dir1), count1, spacing1, dir2: dir2.map(Dir), count2, spacing2 }; + let pattern = solidcraft_doc::PatternKind::Rectangular { + dir1: Dir(dir1), + count1, + spacing1, + dir2: dir2.map(Dir), + count2, + spacing2, + alignment: super::alignment_param(p, "alignment", cmd)?, + alignment2: super::alignment_param(p, "alignment2", cmd)?, + reversed: super::reversed_param(p, "reversed", cmd)?, + reversed2: super::reversed_param(p, "reversed2", cmd)?, + }; finish_pattern(s, p, features, pattern, bodies) } @@ -1275,7 +1286,14 @@ fn pattern_circ(s: &mut Session, p: &Value) -> Result { check_expr(s, &count, Kind::Unitless, cmd, "count")?; let angle = expr(p, "angle").unwrap_or_else(|| "360 deg".into()); check_expr(s, &angle, Kind::Angle, cmd, "angle")?; - let pattern = solidcraft_doc::PatternKind::Circular { origin: Position(origin), axis: Dir(axis), count, angle }; + let pattern = solidcraft_doc::PatternKind::Circular { + origin: Position(origin), + axis: Dir(axis), + count, + angle, + alignment: super::alignment_param(p, "alignment", cmd)?, + reversed: super::reversed_param(p, "reversed", cmd)?, + }; finish_pattern(s, p, features, pattern, bodies) } diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index 7c1353ca8..db7fa5c3f 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -318,3 +318,15 @@ fn edit_distance(a: &str, b: &str) -> usize { } row[b.len()] } + +pub(super) fn alignment_param(p: &Value, key: &str, cmd: &str) -> Result { + p.get(key).map_or(Ok(solidcraft_sketch::PatternAlignment::default()), |value| { + serde_json::from_value(value.clone()).map_err(|_| crate::params::bad(cmd, format!("`{key}` must be left, center or right"))) + }) +} + +pub(super) fn reversed_param(p: &Value, key: &str, cmd: &str) -> Result { + p.get(key).map_or(Ok(false), |value| { + serde_json::from_value(value.clone()).map_err(|_| crate::params::bad(cmd, format!("`{key}` must be true or false"))) + }) +} diff --git a/crates/engine/src/cmd/patterns_tests.rs b/crates/engine/src/cmd/patterns_tests.rs index 94083c1d0..0444c02aa 100644 --- a/crates/engine/src/cmd/patterns_tests.rs +++ b/crates/engine/src/cmd/patterns_tests.rs @@ -34,6 +34,97 @@ fn plate_with_hole() -> Session { const PLATE: f64 = 100.0 * 50.0 * 5.0; const HOLE: f64 = PI * 4.0 * 5.0; +fn feature_pattern_plate() -> Session { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length":120,"width":120,"height":5,"corner":[0,0,0],"name":"Plate"})); + run(&mut s, "solid.hole", json!({"position":[60,60,5],"diameter":2,"name":"Hole"})); + s +} + +#[test] +fn feature_rectangular_center_flip_and_oblique_direction_keep_source_and_recompute() { + use solidcraft_geom::Vec3; + for flipped in [false, true] { + let mut s = feature_pattern_plate(); + let before = s.doc.to_json(); + run( + &mut s, + "solid.pattern.rectangular", + json!({ + "features":["Hole"],"dir1":[1,0,0],"count1":4,"spacing1":15, + "dir2":[0.6,0.8,0],"count2":2,"spacing2":20, + "alignment":"center","alignment2":"center","reversed":flipped,"reversed2":flipped,"name":"Pattern" + }), + ); + let sign = if flipped { -1.0 } else { 1.0 }; + let st = s.world_state(); + let body = &st.bodies[0].body; + // Analytic slots: the source, +1, -1, +2. The second direction is independent. + for i in [0.0, 1.0, -1.0, 2.0] { + for j in [0.0, 1.0] { + let p = Vec3::new(60.0 + sign * (15.0 * i + 12.0 * j), 60.0 + sign * 16.0 * j, 2.5); + assert!(!body.contains(p), "hole at {p:?}"); + assert!(body.contains(p + Vec3::new(0.0, 2.0, 0.0))); + } + } + assert!(rel(volume(&mut s), 120.0 * 120.0 * 5.0 - 8.0 * PI * 5.0) < 1e-5); + let saved = s.doc.to_json(); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.to_json(), before); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.doc.to_json(), saved); + let mut reopened = Session::new(solidcraft_doc::Document::from_json(&saved).unwrap()); + assert!(rel(volume(&mut reopened), volume(&mut s)) < 1e-8); + // The copies replay the edited feature rather than freezing its original tool. + run(&mut reopened, "timeline.redefine", json!({"feature":"Hole","command":"solid.hole","params":{"position":[60,60,5],"diameter":3}})); + assert!(rel(volume(&mut reopened), 120.0 * 120.0 * 5.0 - 8.0 * PI * 2.25 * 5.0) < 1e-5); + } +} + +#[test] +fn feature_circular_center_flip_uses_partial_arc_endpoints_and_full_circle_spacing() { + use solidcraft_geom::Vec3; + for total in [90.0_f64, 360.0] { + for flipped in [false, true] { + let mut s = feature_pattern_plate(); + run( + &mut s, + "solid.pattern.circular", + json!({ + "features":["Hole"],"axis":{"origin":[40,60,0],"dir":[0,0,1]}, + "count":6,"angle":total,"alignment":"center","reversed":flipped + }), + ); + let step = total / if total == 360.0 { 6.0 } else { 5.0 }; + let st = s.world_state(); + for slot in [0.0, 1.0, -1.0, 2.0, -2.0, 3.0] { + let a = (step * slot * if flipped { -1.0 } else { 1.0 }).to_radians(); + let p = Vec3::new(40.0 + 20.0 * a.cos(), 60.0 + 20.0 * a.sin(), 2.5); + assert!(!st.bodies[0].body.contains(p), "hole at {p:?}"); + assert!(st.bodies[0].body.contains(p + Vec3::new(2.0 * a.cos(), 2.0 * a.sin(), 0.0))); + } + assert!(rel(volume(&mut s), 120.0 * 120.0 * 5.0 - 6.0 * PI * 5.0) < 1e-5); + let saved = s.doc.to_json(); + let mut reopened = Session::new(solidcraft_doc::Document::from_json(&saved).unwrap()); + assert!(rel(volume(&mut reopened), volume(&mut s)) < 1e-8); + } + } +} + +#[test] +fn feature_pattern_rejects_malformed_alignment_and_flip_atomically() { + let mut s = feature_pattern_plate(); + let before = s.doc.to_json(); + let undo = s.undo.len(); + for (key, value) in [("alignment", json!("diagonal")), ("alignment2", json!(null)), ("reversed", json!(1)), ("reversed2", json!("true"))] { + let mut p = json!({"features":["Hole"],"dir1":[1,0,0],"count1":4,"spacing1":10}); + p[key] = value; + assert!(s.execute("solid.pattern.rectangular", &p).is_err()); + assert_eq!(s.doc.to_json(), before); + assert_eq!(s.undo.len(), undo); + } +} + #[test] fn circular_axis_origin_rejects_invalid_values_atomically() { let mut s = plate_with_hole(); diff --git a/crates/engine/src/cmd/sketch_pattern.rs b/crates/engine/src/cmd/sketch_pattern.rs index d0b445f5f..bb9282796 100644 --- a/crates/engine/src/cmd/sketch_pattern.rs +++ b/crates/engine/src/cmd/sketch_pattern.rs @@ -1,8 +1,9 @@ //! Associative sketch patterns. Editing retains ids at surviving instance indices. -use solidcraft_sketch::{PatternAlignment, PatternInstance, SketchPattern, SketchPatternKind}; +use solidcraft_sketch::{PatternInstance, SketchPattern, SketchPatternKind}; use super::*; +use crate::cmd::{alignment_param, reversed_param}; pub(super) fn run(s: &mut Session, p: &Value, circular: bool) -> Result { let cmd = if circular { "sketch.pattern.circular" } else { "sketch.pattern.rectangular" }; @@ -257,16 +258,6 @@ fn direction_ref(sk: &Sketch, p: &Value, key: &str, cmd: &str) -> Result Result { - p.get(key).map_or(Ok(PatternAlignment::default()), |value| { - serde_json::from_value(value.clone()).map_err(|_| bad(cmd, format!("`{key}` must be left, center or right"))) - }) -} - -fn reversed_param(p: &Value, key: &str, cmd: &str) -> Result { - p.get(key).map_or(Ok(false), |value| serde_json::from_value(value.clone()).map_err(|_| bad(cmd, format!("`{key}` must be true or false")))) -} - fn line_direction(sk: &Sketch, id: Option<&str>) -> Option { let Shape::Line { a, b } = sk.shape(sk.curve_index(id?)?)? else { return None }; (b - a).normalized() diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 2d4ab062e..dbe7edf6f 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -821,6 +821,7 @@ impl Dialog { /// Dialogs holding a table get the wide limit. pub fn is_wide(&self) -> bool { matches!(self.kind, Kind::Params { .. } | Kind::SketchModify(crate::sketch_modify_ui::Mod::PatternRect { .. })) + || (matches!(self.kind, Kind::PatternRect { .. }) && self.inputs.first().is_some_and(|i| i.accept == selection::FEATURES)) || matches!(&self.kind, Kind::Motion(k) if k.wide()) } @@ -898,6 +899,9 @@ impl Dialog { /// A pick in the viewport (already accepted by the active input). pub fn pick(&mut self, s: &Session, sel: Sel) { + if let Some(key) = feature_pattern_reference_key(self, self.active) { + self.extra.remove(key); + } if let Kind::PathPlane { sketch, .. } = &mut self.kind { *sketch = None; self.extra.remove("path"); @@ -1614,6 +1618,19 @@ fn input_rows(d: &mut Dialog, ui: &mut egui::Ui, s: &Session) { input_rows_range(d, ui, s, 0..d.inputs.len()); } +/// Saved vectors/axes are real inputs even when they have no origin-axis selection chip. +fn feature_pattern_reference_key(d: &Dialog, index: usize) -> Option<&'static str> { + if !d.inputs.first().is_some_and(|i| i.accept == selection::FEATURES) { + return None; + } + match (&d.kind, index) { + (Kind::PatternRect { .. }, 1) => Some("dir1"), + (Kind::PatternRect { .. }, 2) => Some("dir2"), + (Kind::PatternCirc { .. }, 1) => Some("axis"), + _ => None, + } +} + fn input_rows_range(d: &mut Dialog, ui: &mut egui::Ui, s: &Session, range: std::ops::Range) { // Edit Text shows its Path input among its own rows. if matches!(d.kind, Kind::Text(_)) { @@ -1623,14 +1640,15 @@ fn input_rows_range(d: &mut Dialog, ui: &mut egui::Ui, s: &Session, range: std:: let mut clear: Option = None; let mut activate: Option = None; for (i, inp) in d.inputs.iter().enumerate().skip(range.start).take(range.end.saturating_sub(range.start)) { + let stored_reference = feature_pattern_reference_key(d, i).and_then(|key| d.extra.get(key)).filter(|_| inp.items.is_empty()); row_label(ui, inp.label); ui.horizontal(|ui| { let active = i == d.active; // A chip: "↖ Select" (outlined) while empty, "N selected" (filled) once picked. let custom_axis = i == 1 && inp.items.is_empty() && matches!(d.kind, Kind::Revolve { axis: Some(_), .. }); - let filled = !inp.items.is_empty() || custom_axis; + let filled = !inp.items.is_empty() || custom_axis || stored_reference.is_some(); let text = if filled { - RichText::new(if custom_axis { + RichText::new(if custom_axis || stored_reference.is_some() { crate::i18n::tr("dialog.custom_axis").into() } else if !inp.multi { inp.items.first().map(|item| selection_label(s, item)).unwrap_or_default() @@ -1651,7 +1669,9 @@ fn input_rows_range(d: &mut Dialog, ui: &mut egui::Ui, s: &Session, range: std:: .sense(egui::Sense::CLICK); let chip = crate::frame::add_outlined(ui, b, stroke.width); publish_row(&chip); - let tooltip = if custom_axis { + let tooltip = if let Some(reference) = stored_reference { + reference.to_string() + } else if custom_axis { if let Kind::Revolve { axis: Some(axis), .. } = &d.kind { format!( "Custom axis\nOrigin: {}\nDirection: {}\nClick to select a replacement axis", @@ -1667,7 +1687,7 @@ fn input_rows_range(d: &mut Dialog, ui: &mut egui::Ui, s: &Session, range: std:: if chip.on_hover_text(tooltip).clicked() { activate = Some(i); } - if !inp.items.is_empty() { + if !inp.items.is_empty() || stored_reference.is_some() { let button = ui.small_button("×").on_hover_text(tr("Clear the selection")); crate::scenario::publish_handle(&format!("dialog:clear:{}", inp.label), button.rect.center()); if button.clicked() { @@ -1680,9 +1700,11 @@ fn input_rows_range(d: &mut Dialog, ui: &mut egui::Ui, s: &Session, range: std:: if let Some(i) = activate { d.active = i; } - if let Some(i) = clear - && let Some(inp) = d.inputs.get_mut(i) - { + if let Some(i) = clear { + if let Some(key) = feature_pattern_reference_key(d, i) { + d.extra.remove(key); + } + let Some(inp) = d.inputs.get_mut(i) else { return }; inp.items.clear(); if i == 0 { d.profile_selection_changed = true; @@ -1698,13 +1720,30 @@ fn rectangular_pattern_rows(d: &mut Dialog, ui: &mut egui::Ui, session: &Session let mut enter = false; ui.vertical(|ui| { ui.label(tr("dialog.selection_guidance")); - egui::Grid::new("pattern_source").spacing(vec2(10.0, 8.0)).show(ui, |ui| input_rows_range(d, ui, session, 0..1)); + egui::Grid::new("pattern_source").spacing(vec2(10.0, 8.0)).show(ui, |ui| { + if matches!(d.kind, Kind::PatternRect { .. }) { + placement_row(d, ui); + } + input_rows_range(d, ui, session, 0..1); + }); ui.separator(); ui.columns(2, |columns| { for (index, ui) in columns.iter_mut().enumerate() { ui.strong(tr(if index == 0 { "Direction 1" } else { "Direction 2" })); egui::Grid::new(("pattern_direction", index)).spacing(vec2(8.0, 8.0)).show(ui, |ui| { input_rows_range(d, ui, session, index + 1..index + 2); + if let Kind::PatternRect { count, spacing, count2, spacing2 } = &mut d.kind { + let (count, spacing, count_label, spacing_label) = + if index == 0 { (count, spacing, "Quantity", "Spacing") } else { (count2, spacing2, "Quantity 2", "Spacing 2") }; + row_label(ui, count_label); + enter |= field(ui, count); + ui.end_row(); + row_label(ui, spacing_label); + enter |= field(ui, spacing); + ui.end_row(); + feature_pattern_alignment_row(ui, &mut d.extra, index); + return; + } let Kind::SketchModify(Mod::PatternRect { count, spacing, count2, spacing2, alignment, alignment2, reversed, reversed2 }) = &mut d.kind else { @@ -1738,8 +1777,31 @@ fn rectangular_pattern_rows(d: &mut Dialog, ui: &mut egui::Ui, session: &Session enter } +/// Feature patterns use the same source-fixed slot ordering and controls as sketch patterns. +fn feature_pattern_alignment_row(ui: &mut egui::Ui, extra: &mut serde_json::Map, index: usize) { + use solidcraft_engine::sketch::PatternAlignment; + let (label, alignment_key, reversed_key) = + if index == 0 { ("Alignment", "alignment", "reversed") } else { ("Alignment 2", "alignment2", "reversed2") }; + let alignment = extra.get(alignment_key).cloned().and_then(|v| serde_json::from_value::(v).ok()).unwrap_or_default(); + let mut reversed = extra.get(reversed_key).and_then(Value::as_bool).unwrap_or(false); + // Retain programmatic Left placement until the user changes its alignment. + let mut centered = alignment == PatternAlignment::Center; + let was_centered = centered; + row_label(ui, label); + ui.horizontal(|ui| { + pattern_toggle(ui, label, "Flip direction", "pattern_flip", &mut reversed); + pattern_toggle(ui, label, "Center", "pattern_center", &mut centered); + }); + extra.insert(reversed_key.into(), json!(reversed)); + if centered != was_centered { + extra.insert(alignment_key.into(), json!(if centered { PatternAlignment::Center } else { PatternAlignment::Right })); + } + ui.end_row(); +} + pub(crate) fn pattern_toggle(ui: &mut egui::Ui, row: &str, label: &str, icon: &str, selected: &mut bool) { - let response = ui.add(egui::Button::new("").selected(*selected).min_size(vec2(28.0, 24.0))); + // Tab moves between value fields; Enter after a value edit applies the dialog. + let response = ui.add(egui::Button::new("").selected(*selected).min_size(vec2(28.0, 24.0)).sense(egui::Sense::CLICK)); let t = Tokens::get(); crate::icons::paint(ui.painter(), response.rect.shrink(3.0), icon, t.icon, t.icon_fill, t.accent); response.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Button, true, *selected, tr(label))); @@ -2085,7 +2147,8 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { let mut cancel = false; let mut enter = false; let wide = d.is_wide(); - let pattern_columns = matches!(d.kind, Kind::SketchModify(crate::sketch_modify_ui::Mod::PatternRect { .. })); + let pattern_columns = matches!(d.kind, Kind::SketchModify(crate::sketch_modify_ui::Mod::PatternRect { .. })) + || (matches!(d.kind, Kind::PatternRect { .. }) && d.inputs.first().is_some_and(|i| i.accept == selection::FEATURES)); let raw_title = title(&d.kind); let heading = if d.editing.is_some() { crate::i18n::format("dialog.edit_title", &[("title", tr(raw_title))]) } else { tr(raw_title).to_string() }; let frame = crate::frame::dock_frame(ctx, side); @@ -2565,11 +2628,14 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { ui.end_row(); } Kind::Mirror => { - row_label(ui, "Operation"); - let mut op = usize::from(d.extra.get("combine").and_then(Value::as_bool).unwrap_or(false)); - combo(ui, "mi_op", &["New Body", "Join"], &mut op); - d.extra.insert("combine".into(), json!(op == 1)); - ui.end_row(); + // Feature replay retains the source operation; Join is for body copies. + if !d.inputs.first().is_some_and(|i| i.accept == selection::FEATURES) { + row_label(ui, "Operation"); + let mut op = usize::from(d.extra.get("combine").and_then(Value::as_bool).unwrap_or(false)); + combo(ui, "mi_op", &["New Body", "Join"], &mut op); + d.extra.insert("combine".into(), json!(op == 1)); + ui.end_row(); + } } Kind::Measure { result, show, .. } => measure_rows(app, ui, result.as_ref(), show), Kind::OffsetPlane { offset } => { @@ -2730,6 +2796,9 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { enter |= field(ui, v); ui.end_row(); } + if d.inputs.first().is_some_and(|i| i.accept == selection::FEATURES) { + feature_pattern_alignment_row(ui, &mut d.extra, 0); + } } Kind::Loft { operation } => { row_label(ui, "Operation"); @@ -3737,7 +3806,12 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result, S }; let mut p = json!({"dir1": pt(d1), "count1": count, "spacing1": spacing}); pattern_objects(s, sels(d, 0), &mut p); - if let Some((_, d2)) = sels(d, 2).first().and_then(|x| axis_of(app, x)) { + let kept2 = d.extra.get("dir2").and_then(|v| serde_json::from_value::<[f64; 3]>(v.clone()).ok()).map(|a| Vec3::new(a[0], a[1], a[2])); + let d2 = match sels(d, 2).first() { + Some(x) => Some(axis_of(app, x).ok_or("the second direction must be an axis, a sketch line or a straight edge")?.1), + None => kept2, + }; + if let Some(d2) = d2 { p["dir2"] = pt(d2); p["count2"] = json!(count2); p["spacing2"] = json!(spacing2); @@ -4759,8 +4833,8 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option { let mut d = start("solid.mirror")?; let ids: Vec = features.iter().filter_map(|n| s.doc.find_feature(n).map(|f| f.id)).collect(); - // Features that made no body of their own (a hole) were picked as features. - let as_features = ids.iter().any(|id| !st.bodies.iter().any(|b| b.feature == *id)); + // Replay references stay features, including features that created a body. + let as_features = !features.is_empty(); if let Some(inp) = d.inputs.get_mut(0) { if !bodies.is_empty() { inp.items = bodies.iter().map(|name| Sel::Body { name: name.to_string() }).collect(); @@ -4785,8 +4859,12 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option { + PatternKind::Rectangular { dir1, count1, spacing1, dir2, count2, spacing2, alignment, alignment2, reversed, reversed2 } => { let mut d = start("solid.pattern.rectangular")?; + d.extra.insert("alignment".into(), json!(alignment)); + d.extra.insert("alignment2".into(), json!(alignment2)); + d.extra.insert("reversed".into(), json!(reversed)); + d.extra.insert("reversed2".into(), json!(reversed2)); d.kind = Kind::PatternRect { count: count1.to_string(), spacing: spacing1.to_string(), @@ -4809,8 +4887,10 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option { + PatternKind::Circular { origin, axis, count, angle, alignment, reversed } => { let mut d = start("solid.pattern.circular")?; + d.extra.insert("alignment".into(), json!(alignment)); + d.extra.insert("reversed".into(), json!(reversed)); d.kind = Kind::PatternCirc { count: count.to_string(), angle: angle.to_string() }; match world_axis(axis.0).filter(|_| origin.len() < 1e-9) { Some(name) => { @@ -4827,8 +4907,8 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option return None, }; - // Features that made no body of their own (a hole, a fillet) were picked as features. - let as_features = copied.is_empty() && ids.iter().any(|id| !st.bodies.iter().any(|b| b.feature == *id)); + // Replay references stay features, including features that created a body. + let as_features = !features.is_empty(); if let Some(inp) = d.inputs.first_mut() { if as_features { inp.accept = selection::FEATURES; diff --git a/crates/ui-egui/src/preselect_tests.rs b/crates/ui-egui/src/preselect_tests.rs index adebe32ac..f9433aecd 100644 --- a/crates/ui-egui/src/preselect_tests.rs +++ b/crates/ui-egui/src/preselect_tests.rs @@ -9,6 +9,159 @@ use solidcraft_engine::{Sel, Session}; use crate::dialogs::{Dialog, Kind, apply_commands}; use crate::{Services, SolveApp}; +#[test] +fn feature_mirror_and_patterns_reopen_as_feature_replays_even_for_body_creators() { + for (cmd, params) in [ + ("solid.mirror", json!({"features":["Base"],"plane":"YZ"})), + ( + "solid.pattern.rectangular", + json!({"features":["Base"],"dir1":[1,0,0],"count1":4,"spacing1":20, + "dir2":[0.6,0.8,0],"count2":2,"spacing2":20,"alignment":"center","alignment2":"center","reversed":true,"reversed2":true}), + ), + ("solid.pattern.circular", json!({"features":["Base"],"axis":"Z","count":6,"angle":90,"alignment":"center","reversed":true})), + ] { + let mut app = app_with(json!([ + {"command":"solid.box","params":{"corner":[40,0,0],"length":2,"width":2,"height":2,"name":"Base"}} + ])); + app.session.execute(cmd, ¶ms).unwrap(); + let feature = app.session.doc.features.last().unwrap().clone(); + // Exercise the save/reopen boundary as well as reopening the feature editor. + app.session = Session::new(solidcraft_engine::doc::Document::from_json(&app.session.doc.to_json()).unwrap()); + let d = crate::dialogs::for_feature(&app, feature.id, None).unwrap(); + assert_eq!(d.inputs[0].accept, crate::selection::FEATURES, "{cmd}"); + assert_eq!(d.inputs[0].items, vec![Sel::Feature { id: app.session.doc.features[0].id }]); + let (edit, p) = apply_commands(&app, &d).unwrap().remove(0); + assert_eq!(edit, "timeline.redefine"); + assert_eq!(p["params"]["features"], json!(["Base"])); + assert!(p["params"].get("bodies").is_none()); + app.session.execute(&edit, &p).unwrap(); + assert_eq!(app.session.doc.feature(feature.id).unwrap().kind, feature.kind, "{cmd}: accepting the reopened editor preserves its definition"); + } +} + +#[test] +fn feature_pattern_controls_preview_without_committing_and_cancel_cleanly() { + for command in ["solid.pattern.rectangular", "solid.pattern.circular"] { + let mut h = crate::scenario::Harness::new(); + h.app.run("solid.box", json!({"corner":[40,0,0],"length":2,"width":2,"height":2,"name":"Base"})).unwrap(); + let source = h.app.session.doc.features[0].id; + h.app.session.selection = vec![Sel::Feature { id: source }]; + h.step(&json!({"start":command})).unwrap(); + let d = h.app.dialog.as_mut().unwrap(); + d.inputs[1].items = vec![Sel::Axis { name: if command.ends_with("rectangular") { "X".into() } else { "Z".into() } }]; + if command.ends_with("rectangular") { + d.inputs[2].items = vec![Sel::Axis { name: "Y".into() }]; + } + let saved = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + h.frames(3); + for handle in ["dialog:Alignment:Center", "dialog:Alignment:Flip direction"] { + h.step(&json!({"click":{"handle":handle}})).unwrap(); + } + if command.ends_with("rectangular") { + for handle in ["dialog:Alignment 2:Center", "dialog:Alignment 2:Flip direction"] { + h.step(&json!({"click":{"handle":handle}})).unwrap(); + } + } + let d = h.app.dialog.as_ref().unwrap(); + let (_, p) = apply_commands(&h.app, d).unwrap().remove(0); + assert_eq!(p["alignment"], json!("center")); + assert_eq!(p["reversed"], json!(true)); + if command.ends_with("rectangular") { + assert_eq!(p["alignment2"], json!("center")); + assert_eq!(p["reversed2"], json!(true)); + } + assert_eq!(h.app.session.doc.to_json(), saved); + assert_eq!(h.app.session.undo.len(), undo); + wait_feature_preview(&mut h); + h.step(&json!({"key":"Escape"})).unwrap(); + h.frames(3); + assert!(h.app.dialog.is_none()); + assert!(!h.app.preview.active); + assert_eq!(h.app.session.doc.to_json(), saved); + } +} + +fn wait_feature_preview(h: &mut crate::scenario::Harness) { + for _ in 0..300 { + h.frames(2); + if h.app.preview.active && !h.app.preview.busy { + 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.error.is_none()); +} + +#[test] +fn saved_feature_pattern_vectors_are_visible_clearable_and_replaceable() { + let mut h = crate::scenario::Harness::new(); + h.app.run("solid.box", json!({"length":2,"width":2,"height":2,"name":"Base"})).unwrap(); + h.app + .run( + "solid.pattern.rectangular", + json!({"features":["Base"],"dir1":[1,1,0],"count1":2,"spacing1":30, + "dir2":[0.6,0.8,0],"count2":2,"spacing2":50}), + ) + .unwrap(); + let id = h.app.session.doc.features.last().unwrap().id; + h.step(&json!({"call":"ui.editFeature","params":{"feature":id}})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:clear:Direction 2"}})).unwrap(); + let d = h.app.dialog.as_ref().unwrap(); + let (_, p) = apply_commands(&h.app, d).unwrap().remove(0); + assert!(p["params"].get("dir2").is_none(), "clearing the saved second vector makes a single row: {d:?} -> {p}"); + assert_eq!(p["params"]["dir1"], json!([1.0, 1.0, 0.0])); + h.step(&json!({"click":{"handle":"dialog:clear:Direction"}})).unwrap(); + assert!(apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).is_err()); + let d = h.app.dialog.as_mut().unwrap(); + d.pick(&h.app.session, Sel::Axis { name: "X".into() }); + let (_, p) = apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap().remove(0); + assert_eq!(p["params"]["dir1"], json!([1.0, 0.0, 0.0])); +} + +#[test] +fn feature_mirror_picks_clear_preview_and_replay_the_source_cut() { + let mut h = crate::scenario::Harness::new(); + for (cmd, p) in [ + ("solid.box", json!({"length":100,"width":50,"height":5,"corner":[0,0,0]})), + ("solid.hole", json!({"position":[30,25,5],"diameter":4,"name":"Hole"})), + ("construct.plane.offset", json!({"base":"YZ","offset":50,"name":"Mid"})), + ] { + h.app.run(cmd, p).unwrap(); + } + let source = Sel::Feature { id: h.app.session.doc.find_feature("Hole").unwrap().id }; + h.app.session.selection = vec![source.clone()]; + h.step(&json!({"start":"solid.mirror"})).unwrap(); + let saved = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + let d = h.app.dialog.as_mut().unwrap(); + d.active = 0; + d.pick(&h.app.session, source.clone()); + assert!(d.inputs[0].items.is_empty()); + d.pick(&h.app.session, source); + d.active = 1; + d.pick(&h.app.session, Sel::Plane { name: "Mid".into() }); + wait_feature_preview(&mut h); + assert_eq!(h.app.session.doc.to_json(), saved); + assert_eq!(h.app.session.undo.len(), undo); + h.step(&json!({"click":{"handle":"dialog:clear:Mirror Plane"}})).unwrap(); + assert!(h.app.dialog.as_ref().unwrap().inputs[1].items.is_empty()); + assert!(apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).is_err()); + let d = h.app.dialog.as_mut().unwrap(); + d.pick(&h.app.session, Sel::Plane { name: "Mid".into() }); + wait_feature_preview(&mut h); + h.step(&json!({"click":{"handle":"dialog:OK"}})).unwrap(); + h.step(&json!({"until":{"dialog":null,"features":4}})).unwrap(); + let state = h.app.session.world_state(); + assert_eq!(state.bodies.len(), 1, "a mirrored hole cuts the plate instead of copying it"); + assert!(!state.bodies[0].body.contains(Vec3::new(70.0, 25.0, 2.5))); + let mirror = h.app.session.doc.features.last().unwrap().id; + let reopened = crate::dialogs::for_feature(&h.app, mirror, None).unwrap(); + assert_eq!(reopened.inputs[0].accept, crate::selection::FEATURES); + assert_eq!(reopened.inputs[1].items, vec![Sel::Plane { name: "Mid".into() }]); +} + #[test] fn a_face_extrude_keeps_the_picked_body_when_faces_coincide() { let mut app = app_with(json!([ diff --git a/docs/feature-patterns.md b/docs/feature-patterns.md new file mode 100644 index 000000000..a1ac067b6 --- /dev/null +++ b/docs/feature-patterns.md @@ -0,0 +1,49 @@ +# Feature mirrors and patterns + +Choose **Mirror**, **Rectangular Pattern** or **Circular Pattern** from the Solid +Create panel and set **Object Type** to **Features**. Select the source features +in the timeline or pick their faces in the viewport. Selecting features before +starting the command fills the Features input automatically. + +Feature copies replay the source operations: a patterned hole cuts the target +solid, and an additive feature adds material. The mirror's New Body / Join +selector belongs to body copying and is hidden for feature replays. + +Select the mirror plane, rectangular directions or circular axis using the +selection inputs. Click an input to pick into it; click a selected item again to +remove it, or use its clear button. The preview uses the same commands as OK. +Cancel leaves the design and undo history unchanged. + +Rectangular feature patterns have two direction columns, each with Quantity, +Spacing, Flip and Center controls. Directions can meet at any angle. A missing +second direction produces a single row. Direction vectors are saved with the +feature; editing a picked guide later does not change these saved vectors. + +Circular feature patterns have Quantity, Total angle, Flip and Center controls. +Six instances over 90 degrees use 18-degree steps, including both ends of the +arc. A full circle divides 360 degrees by the quantity without duplicating the +source at 360 degrees. + +Quantities include the original. Center keeps the original fixed and alternates +copies on its two sides. For four instances the slots are `0, +1, -1, +2`; +Flip changes them to `0, -1, +1, -2`. This also chooses the extra side for an even +centered circular pattern. Rectangular directions have independent controls. + +Double-click a saved feature in the timeline to edit it. Mirrors and patterns +retain their feature sources, including features that created bodies, and +patterns retain their placement controls and arbitrary direction vectors after +save/reopen. Source edits recompute the copies. Undo and redo cover the whole edit. + +The command forms share sketch patterns' alignment names: + +```json +{"command":"solid.pattern.rectangular","params":{"features":["Hole1"],"dir1":[1,0,0],"count1":4,"spacing1":15,"dir2":[0.6,0.8,0],"count2":2,"spacing2":20,"alignment":"center","alignment2":"center","reversed":true,"reversed2":false}} +``` + +```json +{"command":"solid.pattern.circular","params":{"features":["Hole1"],"axis":{"origin":[40,60,0],"dir":[0,0,1]},"count":6,"angle":"90 deg","alignment":"center","reversed":true}} +``` + +Omitted alignments default to `right`, and omitted reversals to `false`, preserving +older designs. `left` is also accepted by the command API. New placement values +are stored through the pending document-format migration. From 18ec44d77306efbb247fbafd185407b5963e8783 Mon Sep 17 00:00:00 2001 From: Lasse Lian Date: Fri, 16 Oct 2026 09:26:09 +0200 Subject: [PATCH 85/92] AppImage: leave the menu entry to launchers that set DESKTOPINTEGRATION (#1635) Thanks @lasselian. --- docs/book/src/guide/getting-started.md | 3 ++- packaging/linux/AppRun | 17 +++++++++++++++-- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/docs/book/src/guide/getting-started.md b/docs/book/src/guide/getting-started.md index 30940c6ee..e98a158cc 100644 --- a/docs/book/src/guide/getting-started.md +++ b/docs/book/src/guide/getting-started.md @@ -32,7 +32,8 @@ When updating from a build released under the previous product name, follow the The first time you open the AppImage it adds a menu entry and icons under `~/.local/share` (`applications/ai.storyteller.solidcraft.desktop`, `icons/hicolor`), so the desktop shows the right name and icon. It adds nothing if [appimaged](https://github.com/probonopd/go-appimage) -already made an entry for the file (and removes the entry SolidCraft added before). To +already made an entry for the file, or if a launcher such as Gear Lever or AppImageLauncher +started it (and removes the entry SolidCraft added before). To turn it off for good, create an empty file `~/.local/share/solidcraft/no-desktop-integration`, or start the AppImage with `SOLIDCRAFT_NO_DESKTOP_INTEGRATION=1`. diff --git a/packaging/linux/AppRun b/packaging/linux/AppRun index 6f718517a..acd8f67f8 100755 --- a/packaging/linux/AppRun +++ b/packaging/linux/AppRun @@ -11,7 +11,9 @@ # the launch untouched. Opt out with SOLIDCRAFT_NO_DESKTOP_INTEGRATION=1 (the pre-rename # SOLVECRAFT_NO_DESKTOP_INTEGRATION still works: compatibility shim, docs/compatibility.md), # or for good with an empty file $XDG_DATA_HOME/solidcraft/no-desktop-integration. Nothing is -# installed either when appimaged (go-appimage) already made an entry for this AppImage. +# installed either when appimaged (go-appimage) already made an entry for this AppImage, or when +# a launcher that manages AppImages (Gear Lever, AppImageLauncher) started it: it sets +# DESKTOPINTEGRATION and owns the menu entry. set -u @@ -42,10 +44,21 @@ integrate() { src_desktop="$APPDIR/usr/share/applications/$DESK_ID.desktop" [ -f "$src_desktop" ] || return 0 + apps="$data/applications" + # Gear Lever and AppImageLauncher write their own entry and start the AppImage with + # DESKTOPINTEGRATION set; treat that like appimaged: no entry from here, and drop the one + # this script wrote earlier (it would otherwise come back after the launcher's is removed). + if [ -n "${DESKTOPINTEGRATION:-}" ]; then + mine="$apps/$DESK_ID.desktop" + if [ -f "$mine" ] && grep -q '^Exec="' "$mine"; then + rm -f "$mine" + command -v update-desktop-database >/dev/null 2>&1 && update-desktop-database "$apps" >/dev/null 2>&1 + fi + return 0 + fi # appimaged integrates AppImages itself (appimagekit_-.desktop, Exec= this file): # a second entry from here would show the app twice, so drop an entry this script wrote earlier # (only one it wrote: it points Exec at a path in quotes) and leave the rest to appimaged. - apps="$data/applications" for other in "$apps"/appimagekit_*.desktop; do if ! { [ -f "$other" ] && grep -qF "$appimage" "$other" 2>/dev/null; }; then continue From 9bb65b4d6825034f0060888db55d7aff40fcf485 Mon Sep 17 00:00:00 2001 From: phanoob Date: Fri, 16 Oct 2026 09:26:13 +0200 Subject: [PATCH 86/92] Booleans: a prism cut beside the target's other faces takes the exact 2D route in a column (#1629) Thanks @phanoob. --- crates/engine/src/cmd/features.rs | 4 + crates/engine/src/cmd/prism_local_tests.rs | 94 ++++++ crates/kernel/src/lib.rs | 1 + crates/kernel/src/ops.rs | 13 + crates/kernel/src/polybool.rs | 149 +++++---- crates/kernel/src/prism.rs | 28 ++ crates/kernel/src/prism_local.rs | 352 +++++++++++++++++++++ tests/robustness/goldens.json | 5 +- 8 files changed, 579 insertions(+), 67 deletions(-) create mode 100644 crates/engine/src/cmd/prism_local_tests.rs create mode 100644 crates/kernel/src/prism_local.rs diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs index 170f1419e..923ac4858 100644 --- a/crates/engine/src/cmd/features.rs +++ b/crates/engine/src/cmd/features.rs @@ -1992,6 +1992,10 @@ fn offset_face(s: &mut Session, p: &Value) -> Result { #[path = "patterns_tests.rs"] mod patterns_tests; +#[cfg(test)] +#[path = "prism_local_tests.rs"] +mod prism_local_tests; + #[cfg(test)] #[path = "revolve_convention_tests.rs"] mod revolve_convention_tests; diff --git a/crates/engine/src/cmd/prism_local_tests.rs b/crates/engine/src/cmd/prism_local_tests.rs new file mode 100644 index 000000000..eff63392e --- /dev/null +++ b/crates/engine/src/cmd/prism_local_tests.rs @@ -0,0 +1,94 @@ +//! A cut whose walls lie on the target's, in a target that is a prism along the cut only round +//! it (a chamfer or a round elsewhere): the 2D route in a column cut round the tool +//! (`solidcraft_kernel`'s `prism_local`). The B-rep boolean finds no result on these. + +use serde_json::{Value, json}; +use std::f64::consts::PI; + +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) +} + +/// A cut of `params`: the volume it takes, after checking it built. +fn cut(s: &mut Session, params: Value) -> f64 { + let before = volume(s); + let id = run(s, "solid.extrude", params)["feature"].as_u64().unwrap(); + let r = s.model.result(id).unwrap(); + assert!(r.error.is_none(), "{r:?}"); + before - volume(s) +} + +/// An 80 x 50 x 10 plate with a 10 mm round pocket 2 mm deep in its top; `edge` dressed first. +fn plate(edge: impl FnOnce(&mut Session)) -> Session { + 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":[80,50]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"distance":10})); + edge(&mut s); + pocket(&mut s, 2.0); + s +} + +/// The round pocket cut `depth` down from the plate's top. +fn pocket(s: &mut Session, depth: f64) -> f64 { + run(s, "sketch.create", json!({"plane":"XY","offset":10})); + run(s, "sketch.circle.center", json!({"center":[40,25],"radius":5})); + run(s, "sketch.finish", json!({})); + cut(s, json!({"distance":-depth,"operation":"cut"})) +} + +/// The pocket made deeper (2 to 5 mm): its wall lies on the pocket's. The plate is a prism +/// along the cut but for its chamfered rim, or its rounded bottom edges. +#[test] +fn a_round_pocket_made_deeper_beside_a_chamfer_or_a_round() { + let chamfered = |s: &mut Session| { + run(s, "solid.chamfer", json!({"edges":[[40,0,10],[40,50,10],[0,25,10],[80,25,10]],"distance":1})); + }; + let rounded = |s: &mut Session| { + run(s, "solid.fillet", json!({"edges":[[40,0,0],[40,50,0],[0,25,0],[80,25,0]],"radius":2})); + }; + let want = PI * 25.0 * 3.0; + for (what, mut s) in [("chamfered", plate(chamfered)), ("rounded", plate(rounded))] { + let taken = pocket(&mut s, 5.0); + assert!((taken - want).abs() < want * 1e-3, "{what}: {taken} taken, want {want}"); + } +} + +/// #1360's ring cut round a hole, the hole counterbored: the ring's inner wall lies on the +/// hole's, in a disc whose top rim is chamfered. Without the chamfer the disc is a prism and +/// the 2D route takes it whole. +#[test] +fn a_ring_cut_round_a_counterbored_hole_in_a_chamfered_disc() { + let ring = |chamfer: bool| { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane":"XY"})); + run(&mut s, "sketch.circle.center", json!({"center":[0,0],"radius":40})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"distance":10})); + run(&mut s, "solid.hole", json!({"position":[20,0,10],"diameter":6,"type":"counterbore","cb_diameter":9,"cb_depth":1.5})); + if chamfer { + run(&mut s, "solid.chamfer", json!({"edges":[[40,0,10]],"distance":1})); + } + run(&mut s, "sketch.create", json!({"plane":{"face":[0,0,10]}})); + run(&mut s, "sketch.circle.center", json!({"center":[20,0],"radius":3})); + run(&mut s, "sketch.circle.center", json!({"center":[20,0],"radius":6})); + run(&mut s, "sketch.finish", json!({})); + // The ring between the counterbore's rim (projected from the face) and the 6 mm circle. + cut(&mut s, json!({"direction":"negative","distance":3,"operation":"cut","profiles":[{"point":[25.25,0]}]})) + }; + let want = PI * (36.0 - 20.25) * 3.0; + for chamfer in [false, true] { + let taken = ring(chamfer); + assert!((taken - want).abs() < want * 1e-3, "chamfer {chamfer}: {taken} taken, want {want}"); + } +} diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rs index a152328c5..0376c6a7a 100644 --- a/crates/kernel/src/lib.rs +++ b/crates/kernel/src/lib.rs @@ -90,6 +90,7 @@ mod polybool; mod polyhedron; mod prism; mod prism_curve; +mod prism_local; mod prism_measure; pub mod provenance; mod record; diff --git a/crates/kernel/src/ops.rs b/crates/kernel/src/ops.rs index 6bb9a9835..5cfc713c6 100644 --- a/crates/kernel/src/ops.rs +++ b/crates/kernel/src/ops.rs @@ -817,6 +817,19 @@ fn boolean_whole(a: &Body, b: &Body, op: BoolOp) -> Result> { return Ok(Some(body)); } } + // A prism tool whose target is a prism along its direction only round it (a pocket made + // deeper in a plate with a chamfered rim, a ring cut round a counterbored hole in a + // chamfered disc): the exact 2D route in a column cut round the tool. Its walls lying on + // the target's are what the tries below fail on. + if attempt == 1 && matches!(op, BoolOp::Cut | BoolOp::Intersect) { + let (local, diagnostics) = capture_boolean_diagnostics(|| crate::prism_local::local_prism_boolean(a, b, op)); + if let Some(Ok(Some(body))) = local + && check(&body).0 + { + merge(diagnostics); + return Ok(Some(body)); + } + } 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); diff --git a/crates/kernel/src/polybool.rs b/crates/kernel/src/polybool.rs index 970205dc7..7d03a82d9 100644 --- a/crates/kernel/src/polybool.rs +++ b/crates/kernel/src/polybool.rs @@ -527,79 +527,98 @@ pub(crate) fn sliced_planar_boolean(a: &Body, b: &Body, op: BoolOp) -> Option = match r { - Some(m) => { - let healed = recorded::heal_body(&m, m.deep_copy(), size, a.split_keep(), &record::counts(&[&middle.0, b]))?; - let h = recorded::of_pair(&healed, &middle.1, &h_b); - vec![(healed, h)] - } - None => Vec::new(), - }; - // Each piece in its lumps: a cut plane crossing a frame or a ring leaves the middle (or - // a piece outside) in several parts, which meet the others along several cut faces. - let lumps = |(whole, h): Traced| -> Result> { - if whole.solid.boundaries().len() == 1 { - return Ok(vec![(whole, h)]); - } - let parts = whole.lumps()?; - let histories = recorded::parts_of(&parts, &whole); - Ok(parts - .into_iter() - .zip(histories) - .map(|(p, hp)| { - let h = match (hp, h.as_ref()) { - (Some(hp), Some(h)) => recorded::composed(hp.substituted(0, h)), - _ => None, - }; - (p, h) - }) - .collect()) - }; - let mut all: Vec = Vec::new(); - for piece in pieces.into_iter().chain(outside) { - all.extend(lumps(piece)?); - } - // Glue pieces that meet along their cut faces until one is left; every cut face pair - // goes (a pair left behind would be a slit through the result). - let mut joined: Vec = Vec::new(); - while let Some(mut cur) = all.pop() { - loop { - let found = all.iter().enumerate().find_map(|(i, (o, _))| Some((i, crate::coplanar::glue(&cur.0, o)?.ok()?))); - let Some((i, j)) = found else { break }; - let other = all.swap_remove(i); - let h = recorded::of_pair(&j, &cur.1, &other.1); - cur = (j, h); - } - joined.push(cur); - } - if joined.iter().any(|(x, _)| x.solid.boundaries().len() != 1) { - return Err(fail("a piece in several parts")); - } - // A join onto one piece is one piece: anything apart is a cut face that did not glue. - if op == BoolOp::Union && a.solid.boundaries().len() == 1 && joined.len() != 1 { - return Err(fail("a piece does not join back")); - } - let pieces = joined; - recorded::join(pieces.into_iter().map(|(p, h)| (p, dropped(h))).collect(), &counts) + reassembled(a, b, op, &middle, r, outside, n, &fail) }; Some(run()) } +/// The middle piece's boolean with `b` (`r`, over `[middle, b]`) and the pieces of `a` split +/// away from the middle (`outside`) glued back into one result over `[a, b]`: the operands past +/// the second (`n` in all, the boxes a piece was cut with) are dropped. `fail` names the route +/// in its errors. Shared with [`crate::prism_local`]. +#[allow(clippy::too_many_arguments)] +pub(crate) fn reassembled( + a: &Body, + b: &Body, + op: BoolOp, + middle: &Traced, + r: Option, + outside: Vec, + n: usize, + fail: &dyn Fn(&str) -> KernelError, +) -> Result> { + let size = a.size().max(b.size()); + let h_b = recorded::kept(b, 1, n); + let counts = record::counts(&[a, b]); + if op == BoolOp::Intersect { + return Ok(r.map(|r| { + let h = dropped(recorded::of_pair(&r, &middle.1, &h_b)); + r.with_checked_history(h, &counts) + })); + } + // The rebuild leaves the cut faces' edges split where other polygons were cut; healed, + // they match the pieces outside edge for edge. + let pieces: Vec = match r { + Some(m) => { + let healed = recorded::heal_body(&m, m.deep_copy(), size, a.split_keep(), &record::counts(&[&middle.0, b]))?; + let h = recorded::of_pair(&healed, &middle.1, &h_b); + vec![(healed, h)] + } + None => Vec::new(), + }; + // Each piece in its lumps: a cut plane crossing a frame or a ring leaves the middle (or + // a piece outside) in several parts, which meet the others along several cut faces. + let lumps = |(whole, h): Traced| -> Result> { + if whole.solid.boundaries().len() == 1 { + return Ok(vec![(whole, h)]); + } + let parts = whole.lumps()?; + let histories = recorded::parts_of(&parts, &whole); + Ok(parts + .into_iter() + .zip(histories) + .map(|(p, hp)| { + let h = match (hp, h.as_ref()) { + (Some(hp), Some(h)) => recorded::composed(hp.substituted(0, h)), + _ => None, + }; + (p, h) + }) + .collect()) + }; + let mut all: Vec = Vec::new(); + for piece in pieces.into_iter().chain(outside) { + all.extend(lumps(piece)?); + } + // Glue pieces that meet along their cut faces until one is left; every cut face pair + // goes (a pair left behind would be a slit through the result). + let mut joined: Vec = Vec::new(); + while let Some(mut cur) = all.pop() { + loop { + let found = all.iter().enumerate().find_map(|(i, (o, _))| Some((i, crate::coplanar::glue(&cur.0, o)?.ok()?))); + let Some((i, j)) = found else { break }; + let other = all.swap_remove(i); + let h = recorded::of_pair(&j, &cur.1, &other.1); + cur = (j, h); + } + joined.push(cur); + } + if joined.iter().any(|(x, _)| x.solid.boundaries().len() != 1) { + return Err(fail("a piece in several parts")); + } + // A join onto one piece is one piece: anything apart is a cut face that did not glue. + if op == BoolOp::Union && a.solid.boundaries().len() == 1 && joined.len() != 1 { + return Err(fail("a piece does not join back")); + } + let pieces = joined; + recorded::join(pieces.into_iter().map(|(p, h)| (p, dropped(h))).collect(), &counts) +} + /// `piece` split by `plane` (at `x` along `axis`): the parts on the side away from the tool /// and the one part on its side (positive along `axis` when `keep_positive`), each with its /// history over the operands `piece`'s is over. `None` when the split leaves no part on either /// side, or several on the tool's. -fn split_beside(piece: &Traced, plane: &solidcraft_geom::Plane, axis: Vec3, x: f64, keep_positive: bool) -> Option<(Vec, Traced)> { +pub(crate) fn split_beside(piece: &Traced, plane: &solidcraft_geom::Plane, axis: Vec3, x: f64, keep_positive: bool) -> Option<(Vec, Traced)> { let parts = crate::splitface::split_body(&piece.0, &crate::splitface::SplitTool::Plane(*plane)).ok()?; if parts.len() < 2 { return None; diff --git a/crates/kernel/src/prism.rs b/crates/kernel/src/prism.rs index 7e5642c74..58b9cd809 100644 --- a/crates/kernel/src/prism.rs +++ b/crates/kernel/src/prism.rs @@ -2217,6 +2217,34 @@ fn directions(a: &Body, b: &Body) -> Option> { Some(dirs) } +/// The direction `b` is a prism (or a stack of prisms) along: the first of its planar faces' +/// normals along which it is one. `None` when there is none. +pub(crate) fn prism_axis(b: &Body) -> Option { + if b.face_count() > MAX_PLANAR_SEGMENTS { + return None; + } + let tol = (b.size() * 1e-7).max(1e-9) * 10.0; + let index = LazyIndex::new(b, 1); + let mut tried: Vec = Vec::new(); + for f in b.solid.face_iter() { + let mt::Surface::Plane(p) = f.oriented_surface() else { continue }; + let n = p.normal(); + let Some(n) = Vec3::new(n.x, n.y, n.z).normalized() else { continue }; + if tried.iter().any(|m| m.dot(n).abs() > 1.0 - 1e-9) { + continue; + } + tried.push(n); + if tried.len() > 16 { + return None; + } + let plane = Plane::from_normal(Vec3::ZERO, n)?; + if stack_tagged(b, n, &plane, tol, &index).is_some() { + return Some(n); + } + } + None +} + /// Whether a boolean of sections left one of area `v` as it was (area `u` after): the same to /// within rounding, as the very same outline gives (a change is at least a sliver `tol` wide). fn same_area(u: f64, v: f64, tol: f64) -> bool { diff --git a/crates/kernel/src/prism_local.rs b/crates/kernel/src/prism_local.rs new file mode 100644 index 000000000..4bbb4d443 --- /dev/null +++ b/crates/kernel/src/prism_local.rs @@ -0,0 +1,352 @@ +//! Booleans of a prism tool with a target that is a prism along the tool's direction only round +//! the tool: a pocket made deeper in a plate whose rim is chamfered, a ring cut round a +//! counterbored hole in a chamfered disc. The tool's walls lie on the target's there, which the +//! B-rep boolean can't intersect, and the 2D route ([`crate::prism::prism_boolean`]) declines the +//! target for a face far away (the chamfer) that is neither a wall along the direction nor a cap +//! square to it. +//! +//! The target is split by planes into a column round the tool that holds none of those faces; +//! the column takes the exact 2D boolean, and the pieces are glued back along the cut faces, as +//! [`crate::polybool::sliced_planar_boolean`] does for an all-planar tool beside curved faces. +//! The cuts are imprints (no boolean), each placed beside the tool on one of three axes: the +//! tool's direction and two square to it. A cut that leaves every offending face of the middle +//! piece beyond it goes first; otherwise one close beside the tool, which splits them (a +//! chamfer all round a disc is split into two pieces apart, which the next cut leaves out). + +use solidcraft_geom::{Plane, Vec3}; +use truck_modeling as mt; + +use crate::body::Body; +use crate::boolean_record::{self as recorded, Traced}; +use crate::{BoolOp, KernelError, Result}; + +/// Cuts at most, each splitting the middle piece once. +const MAX_CUTS: usize = 6; + +/// Cuts made with half boxes at most (two booleans each, with their retries): an imprint traced +/// wrong across a curved face is rare, and the booleans cost seconds on curved parts. +const MAX_BOX_CUTS: usize = 2; + +/// Operands a piece's history is over: `a`, `b`, then the two half boxes each cut may be made +/// with (dropped from the result, whose faces are none of theirs). +const OPERANDS: usize = 2 + 2 * MAX_CUTS; + +thread_local! { + /// Set while [`local_prism_boolean`] runs: the booleans it makes a cut with (a piece and a + /// half box) take the general path, not this one again. + static RUNNING: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// An extent along each of three axes. +type Extent = [(f64, f64); 3]; + +/// [`crate::prism::prism_boolean`] of `a` and the prism `b`, taken in a column of `a` round `b` +/// (see the module notes). `None` when `b` is not a prism, `a` is one along `b`'s direction +/// already, or no column round `b` is clear of `a`'s other faces: the caller goes on as before. +pub(crate) fn local_prism_boolean(a: &Body, b: &Body, op: BoolOp) -> Option>> { + // A cut or an intersection: what a tool meeting the target's walls fails on. A union (a + // shell's cavity joined with its opening) is left to the general path. + if !matches!(op, BoolOp::Cut | BoolOp::Intersect) || a.face_count() > 4096 || RUNNING.with(std::cell::Cell::get) { + return None; + } + /// Clears the flag however the boolean ends, a caught panic included. + struct Reset; + impl Drop for Reset { + fn drop(&mut self) { + RUNNING.with(|r| r.set(false)); + } + } + RUNNING.with(|r| r.set(true)); + let _reset = Reset; + let d = crate::prism::prism_axis(b)?; + let size = a.size().max(b.size()); + let tol = (size * 1e-7).max(1e-9) * 10.0; + let frame = Plane::from_normal(Vec3::ZERO, d)?; + let axes = [frame.x, frame.y, d]; + // Extents come from meshes this close to the faces, widened by as much. + let mesh_tol = (size * 1e-3).max(1e-4); + let tool = widened(extent(&b.tessellate(mesh_tol).ok()?.positions, axes)?, mesh_tol); + let gap = size * 1e-4 + 1e-6; + let pieces = survey(a, d, tol, mesh_tol, axes)?.pieces; + if pieces.is_empty() { + return None; + } + // A piece of an offending face within a hair of the tool's box: no column round the tool + // can leave it out, so nothing is cut. + let reach = size * 2e-3 + 2.0 * gap; + if pieces.iter().any(|(_, e)| e.iter().zip(&tool).all(|((c0, c1), (t0, t1))| *c1 > t0 - reach && *c0 < t1 + reach)) { + return None; + } + let run = || -> Result> { + let fail = |m: &str| KernelError::Failed(format!("prism boolean in a column round the tool: {m}")); + let mut middle: Traced = (a.clone(), recorded::kept(a, 0, OPERANDS)); + let mut outside: Vec = Vec::new(); + // The sides already cut (axis, positive side): each is cut once. + let mut cut: Vec<(usize, bool)> = Vec::new(); + let mut box_cuts = 0; + for _ in 0..MAX_CUTS { + let survey = survey(&middle.0, d, tol, mesh_tol, axes).ok_or_else(|| fail("the middle piece"))?; + let off = survey.faces(); + if off.is_empty() { + break; + } + let (k, places, keep_positive) = + next_cut(&off, &tool, &survey.here, &survey.flat, &cut, axes, size, gap).ok_or_else(|| fail("no cut leaves the other faces out"))?; + cut.push((k, !keep_positive)); + let axis = axes[k]; + let (u, w) = (axes[(k + 1) % 3], axes[(k + 2) % 3]); + // The first of the places where the piece splits into parts that add up to it (a + // plane whose section through the piece doesn't close is passed over). The cut's + // half boxes, if it takes them, are operands `slot` and `slot + 1`. + let slot = 2 * cut.len(); + let (away, kept) = places + .iter() + .enumerate() + .find_map(|(i, x)| { + let plane = Plane::new(axis * *x, u, w)?; + let with_boxes = i == 0 && box_cuts < MAX_BOX_CUTS; + // Only a plane across an offending face can be traced wrong (a cone's piece + // meshed past its bounds): the others are taken as they are. + let verify = survey.pieces.iter().any(|(_, e)| e[k].0 < *x && e[k].1 > *x); + let r = split(&middle, &plane, axis, *x, keep_positive, slot, with_boxes, verify)?; + box_cuts += usize::from(r.2); + Some((r.0, r.1)) + }) + .ok_or_else(|| fail("a cut beside the tool"))?; + outside.extend(away); + middle = kept; + } + if !survey(&middle.0, d, tol, mesh_tol, axes).is_some_and(|s| s.pieces.is_empty()) { + return Err(fail("other faces are left round the tool")); + } + let r = match crate::prism::prism_boolean(&middle.0, b, op) { + Some(r) => r?, + None => return Err(fail("the column is not a prism along the tool")), + }; + crate::polybool::reassembled(a, b, op, &middle, r, outside, OPERANDS, &fail) + }; + Some(run()) +} + +/// `piece` split by `plane` (at `x` along `axis`, square to it): the parts away from the tool +/// and the one on its side (positive along `axis` when `keep_positive`), with their histories. +/// An imprint of the plane, taken as it is unless `verify`; else where its parts don't add up to +/// the piece (a plane across a cone can be traced wrong) and `with_boxes`, the piece's intersections with the half boxes +/// either side (the cut's operands `slot` and `slot + 1`), and then whether it took them. `None` +/// when neither adds up. +#[allow(clippy::too_many_arguments)] +fn split( + piece: &Traced, + plane: &Plane, + axis: Vec3, + x: f64, + keep_positive: bool, + slot: usize, + with_boxes: bool, + verify: bool, +) -> Option<(Vec, Traced, bool)> { + if !verify { + let (away, kept) = crate::polybool::split_beside(piece, plane, axis, x, keep_positive)?; + return Some((away, kept, false)); + } + let whole = crate::measure(&piece.0).ok()?.volume; + let adds_up = |away: &[Traced], kept: &Traced| { + let sum: Option = away.iter().chain([kept]).map(|(p, _)| crate::measure(p).ok().map(|m| m.volume)).sum(); + sum.is_some_and(|sum| (sum - whole).abs() <= whole.abs() * 5e-5 + 1e-9) + }; + if let Some((away, kept)) = crate::polybool::split_beside(piece, plane, axis, x, keep_positive) + && adds_up(&away, &kept) + { + return Some((away, kept, false)); + } + if !with_boxes { + return None; + } + let boxes = (crate::ops::half_box(&piece.0, plane, !keep_positive).ok()?, crate::ops::half_box(&piece.0, plane, keep_positive).ok()?); + let (h_away, h_kept) = (recorded::kept(&boxes.0, slot, OPERANDS), recorded::kept(&boxes.1, slot + 1, OPERANDS)); + let away = crate::ops::boolean(&piece.0, &boxes.0, BoolOp::Intersect).ok()?; + let kept = crate::ops::boolean(&piece.0, &boxes.1, BoolOp::Intersect).ok()??; + let away: Vec = away + .into_iter() + .map(|o| { + let h = recorded::of_pair(&o, &piece.1, &h_away); + (o, h) + }) + .collect(); + let kept: Traced = { + let h = recorded::of_pair(&kept, &piece.1, &h_kept); + (kept, h) + }; + adds_up(&away, &kept).then_some((away, kept, true)) +} + +/// The extent of `points` along each of `axes`; `None` for no points. +fn extent(points: &[Vec3], axes: [Vec3; 3]) -> Option { + if points.is_empty() { + return None; + } + let mut e = [(f64::INFINITY, f64::NEG_INFINITY); 3]; + for p in points { + for (slot, axis) in e.iter_mut().zip(axes) { + let t = p.dot(axis); + *slot = (slot.0.min(t), slot.1.max(t)); + } + } + e.iter().all(|(lo, hi)| lo.is_finite() && hi.is_finite()).then_some(e) +} + +/// What a cut is chosen from: a piece's extent (`here`), the mesh triangles of its faces that +/// are neither a wall along the direction nor a plane square to it (the faces that keep it from +/// being a prism along it: each one's index and extent), and its planar faces (unit normal, +/// offset along it) for a cut to keep out of. Extents are widened by the mesh's tolerance. +struct Survey { + here: Extent, + pieces: Vec<(usize, Extent)>, + flat: Vec<(Vec3, f64)>, +} + +impl Survey { + /// The extent of each offending face. + fn faces(&self) -> Vec { + let mut faces: Vec<(usize, Extent)> = Vec::new(); + for (i, e) in &self.pieces { + match faces.iter_mut().find(|(j, _)| j == i) { + Some((_, acc)) => { + for (x, y) in acc.iter_mut().zip(e) { + *x = (x.0.min(y.0), x.1.max(y.1)); + } + } + None => faces.push((*i, *e)), + } + } + faces.into_iter().map(|(_, e)| e).collect() + } +} + +/// [`Survey`] of `body` along `d`, from one mesh of it. `None` when it can't be meshed. +fn survey(body: &Body, d: Vec3, tol: f64, mesh_tol: f64, axes: [Vec3; 3]) -> Option { + let mut work = 262_144usize; + let mut flat = Vec::new(); + let off: Vec = body + .solid + .face_iter() + .map(|f| { + let surface = f.oriented_surface(); + match &surface { + mt::Surface::Plane(p) => { + let n = p.normal(); + let Some(n) = Vec3::new(n.x, n.y, n.z).normalized() else { return true }; + let o = p.origin(); + flat.push((n, n.dot(Vec3::new(o.x, o.y, o.z)))); + let along = n.dot(d).abs(); + !(along > 1.0 - 1e-9 || along < 1e-9) + } + _ => !crate::prism::wall_along(&surface, d, tol, &mut work), + } + }) + .collect(); + let mesh = body.tessellate(mesh_tol).ok()?; + let here = widened(extent(&mesh.positions, axes)?, mesh_tol); + let mut pieces = Vec::new(); + if off.iter().any(|x| *x) { + for (t, fi) in mesh.triangles.iter().zip(&mesh.tri_face) { + let i = *fi as usize; + if !off.get(i).copied().unwrap_or(false) { + continue; + } + let Some(tri) = mesh.tri(t) else { continue }; + if let Some(e) = extent(&tri, axes) { + pieces.push((i, widened(e, mesh_tol))); + } + } + } + Some(Survey { here, pieces, flat }) +} + +/// `e` grown by `by` each way. +fn widened(mut e: Extent, by: f64) -> Extent { + for (lo, hi) in e.iter_mut() { + *lo -= by; + *hi += by; + } + e +} + +/// The next cut of the middle piece (its extent `here`, its planar faces `flat`): the axis, the +/// place along it and whether the tool's side is the positive one. A cut leaving the most +/// offending faces (`off`) wholly beyond it, on a side not `cut` yet, placed halfway to the nearest of them; failing +/// that, one beside the tool across the most of them (on an axis square to the direction +/// first). `None` when no cut beside the tool has any offending face beyond it. +#[allow(clippy::too_many_arguments)] +fn next_cut( + off: &[Extent], + tool: &Extent, + here: &Extent, + flat: &[(Vec3, f64)], + cut: &[(usize, bool)], + axes: [Vec3; 3], + size: f64, + gap: f64, +) -> Option<(usize, Vec, bool)> { + // Places between `near` (beside the tool) and `far`, best first, out of the planes of the + // piece's faces square to the axis. + let place = |k: usize, near: f64, far: f64| -> Option> { + let axis = axes[k]; + let places: Vec = [0.5, 0.37, 0.63, 0.25, 0.75, 0.1, 0.9] + .iter() + .map(|t| near + (far - near) * t) + .filter(|x| !flat.iter().any(|(n, o)| n.dot(axis).abs() > 1.0 - 1e-9 && (o * n.dot(axis).signum() - x).abs() < gap)) + .collect(); + (!places.is_empty()).then_some(places) + }; + let mut whole: Option<(usize, usize, Vec, bool)> = None; + let mut across: Option<(usize, usize, Vec, bool)> = None; + let beside = size * 2e-3; + for k in [0usize, 1, 2] { + let (t0, t1) = tool[k]; + let (h0, h1) = here[k]; + for positive_side in [true, false] { + if cut.contains(&(k, positive_side)) { + continue; + } + // Past the tool on this side: is there any of the piece to cut away? + let (edge, room) = if positive_side { (t1 + gap, h1 - t1) } else { (t0 - gap, t0 - h0) }; + if room <= 2.0 * gap { + continue; + } + let beyond: Vec = off + .iter() + .filter_map(|e| { + let (c0, c1) = e[k]; + if positive_side { (c0 > edge).then_some(c0) } else { (c1 < edge).then_some(c1) } + }) + .collect(); + if let Some(nearest) = beyond.iter().copied().reduce(if positive_side { f64::min } else { f64::max }) { + let Some(x) = place(k, edge, nearest) else { continue }; + if whole.as_ref().is_none_or(|(_, n, ..)| beyond.len() > *n) { + whole = Some((k, beyond.len(), x, !positive_side)); + } + continue; + } + if k == 2 && across.is_some() { + continue; + } + let near = edge + if positive_side { beside } else { -beside }; + let crossing = off.iter().filter(|e| if positive_side { e[k].1 > near } else { e[k].0 < near }).count(); + let limit = if positive_side { h1 } else { h0 }; + if crossing == 0 { + continue; + } + let Some(x) = place(k, edge, near + (near - edge)) + .map(|p| p.into_iter().filter(|x| if positive_side { *x < limit - gap } else { *x > limit + gap }).collect::>()) + .filter(|p| !p.is_empty()) + else { + continue; + }; + if across.as_ref().is_none_or(|(_, n, ..)| crossing > *n) { + across = Some((k, crossing, x, !positive_side)); + } + } + } + whole.or(across).map(|(k, _, x, keep_positive)| (k, x, keep_positive)) +} diff --git a/tests/robustness/goldens.json b/tests/robustness/goldens.json index b6253d6fb..12d35e350 100644 --- a/tests/robustness/goldens.json +++ b/tests/robustness/goldens.json @@ -66,7 +66,7 @@ "62": {"area":8771.003732,"bodies":1,"edges":60,"error":null,"faces":23,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","cut cylinder","circular pattern","cut box","cut box","join cylinder"],"unsupported":2,"volume":40107.001728}, "63": {"area":3198.797259,"bodies":1,"edges":84,"error":null,"faces":30,"outcome":"ok","rejected":1,"shells":1,"steps":["revolved section","join box","cut cylinder","hole","cut cylinder","join box","fillet"],"unsupported":0,"volume":7075.892751}, "64": {"area":4088.335645,"bodies":1,"edges":36,"error":null,"faces":14,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","fillet","join cylinder"],"unsupported":0,"volume":8495.220295}, - "65": {"area":8442.175249,"bodies":1,"edges":33,"error":null,"faces":13,"outcome":"ok","rejected":0,"shells":1,"steps":["box","cut cylinder","fillet","rectangular pattern","circular pattern","circular pattern","fillet","cut box"],"unsupported":0,"volume":45117.305023}, + "65": {"area":8436.255548,"bodies":1,"edges":37,"error":null,"faces":15,"outcome":"ok","rejected":0,"shells":1,"steps":["box","cut cylinder","fillet","rectangular pattern","circular pattern","circular pattern","fillet","cut box"],"unsupported":0,"volume":45143.475817}, "66": {"area":9222.76638,"bodies":1,"edges":99,"error":null,"faces":37,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","join box","join box","join box","cut sphere","cut box"],"unsupported":1,"volume":35217.203139}, "67": {"area":7943.46222,"bodies":2,"edges":88,"error":null,"faces":37,"outcome":"ok","rejected":0,"shells":2,"steps":["extruded profile","cut cylinder","hole","join cylinder","join box","hole","chamfer","rectangular pattern"],"unsupported":2,"volume":27607.962186}, "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}, @@ -124,6 +124,7 @@ {"reason":"#1390: a chamfer of a convex edge that would grow the part is refused (TooLarge). Seed 57's 0.5 mm chamfer on the sphere cut's rim, which grew the part since #391 reordered its steps, is now refused, so the run goes on to its later steps and ends ok (16017.21 mm³, 24 faces)","seeds":[57]}, {"reason":"Seed 83 builds: a shell splits a saddle corner (convex and concave edges in turn) into two corners","seeds":[83]}, {"reason":"seed 15 now cuts around a sealed void","seeds":[15]}, - {"reason":"#1490: when the last-resort nudge fails both ways, two more screw axes are tried; seed 63's final box join (its face 0.00005 mm off the half-ring's cut face) now builds instead of being refused with an implausible volume, and the design goes on to its fillet","seeds":[63]} + {"reason":"#1490: when the last-resort nudge fails both ways, two more screw axes are tried; seed 63's final box join (its face 0.00005 mm off the half-ring's cut face) now builds instead of being refused with an implausible volume, and the design goes on to its fillet","seeds":[63]}, + {"reason":"a prism cut in a column round the tool (prism_local): seed 65's rectangular pattern (step 4, a second half-cylinder groove overlapping the first, in a block with a rounded vertical edge) is now built by the exact 2D route in a column clear of the round, where the B-rep tries left it with split edges. The step's part has the 10 faces, 24 edges and 16 vertices it should (28 edges and 18 vertices before), and its volume is 45145.383 mm³ against 45145.214 (exactly 45145.103, both within the mesh measure); the generator then picks other edges for its step 7 fillet, so the run ends on another design (45143.48 mm³, 15 faces)","seeds":[65]} ] } From 7f79443b469821cc41f4c0be5987e5c8767bbe80 Mon Sep 17 00:00:00 2001 From: DuBearte <130190089+DuBearte@users.noreply.github.com> Date: Fri, 16 Oct 2026 03:26:16 -0400 Subject: [PATCH 87/92] Control channel: a timed-out request says it is still running, and its result can be asked for (#1618) (#1627) Thanks @DuBearte. --- apps/solidcraft/src/control_server.rs | 129 ++++++++++++++++++++++++-- docs/control-protocol.md | 11 ++- 2 files changed, 130 insertions(+), 10 deletions(-) diff --git a/apps/solidcraft/src/control_server.rs b/apps/solidcraft/src/control_server.rs index 2e566afcc..8680d0cd1 100644 --- a/apps/solidcraft/src/control_server.rs +++ b/apps/solidcraft/src/control_server.rs @@ -4,7 +4,7 @@ use std::io::{BufRead, BufReader, Write}; use std::net::{TcpListener, TcpStream}; use std::sync::atomic::{AtomicUsize, Ordering}; -use std::sync::mpsc::{Receiver, Sender, channel}; +use std::sync::mpsc::{Receiver, Sender, TryRecvError, channel}; use std::time::Duration; use serde_json::{Value, json}; @@ -160,12 +160,35 @@ fn refuse(out: &mut TcpStream, reader: &mut BufReader) { let _ = std::io::copy(&mut reader.by_ref().take(64 * 1024), &mut std::io::sink()); } +/// How long a request waits for the app's reply: most requests, and a batch (or every request, +/// on a patient connection). +#[derive(Clone, Copy)] +struct Waits { + short: Duration, + long: Duration, +} + +const WAITS: Waits = Waits { short: Duration::from_secs(60), long: Duration::from_secs(3600) }; + +/// A request that timed out but is still running in the app (#1618): its id and method, and where +/// its reply will land. +struct Pending { + id: Value, + method: String, + reply: Receiver, +} + fn serve(stream: TcpStream, token: &str, tx: Sender, ctx: egui::Context, patient: bool) { + serve_with(stream, token, tx, ctx, patient, WAITS); +} + +fn serve_with(stream: TcpStream, token: &str, tx: Sender, ctx: egui::Context, patient: bool, waits: Waits) { let Ok(read) = stream.try_clone() else { return }; let mut out = stream; let mut reader = BufReader::new(read); let mut bad = 0usize; let mut authenticated = false; + let mut pending: Option = None; loop { let line = match read_line(&mut reader, MAX_LINE) { Ok(Some(l)) => String::from_utf8_lossy(&l).into_owned(), @@ -193,14 +216,46 @@ fn serve(stream: TcpStream, token: &str, tx: Sender, ctx: egui:: let id = msg.get("id").cloned().unwrap_or(Value::Null); let method = msg.get("method").and_then(Value::as_str).unwrap_or("").to_string(); let params = msg.get("params").cloned().unwrap_or(json!({})); - // A batch replaces many short requests: the whole of it may take long (#743). - let wait = Duration::from_secs(if patient || method == "engine.batch" { 3600 } else { 60 }); - let (req, rrx) = ControlRequest::new(method, params); - if tx.send(req).is_err() { - break; - } - ctx.request_repaint(); - let mut r = rrx.recv_timeout(wait).unwrap_or_else(|_| json!({"ok": false, "error": "timeout"})); + // A request that timed out may have finished since (#1618). + let late = pending.as_ref().and_then(|p| match p.reply.try_recv() { + Ok(reply) => Some(reply), + Err(TryRecvError::Disconnected) => Some(json!({"ok": false, "error": "the app ended the request without a reply"})), + Err(TryRecvError::Empty) => None, + }); + let mut r = if method == "control.pending" { + match (pending.take(), late) { + (None, _) => json!({"ok": true, "result": {"pending": null}}), + (Some(p), Some(reply)) => json!({"ok": true, "result": {"pending": p.id, "method": p.method, "done": true, "reply": reply}}), + (Some(p), None) => { + let r = json!({"ok": true, "result": {"pending": p.id, "method": p.method, "done": false}}); + pending = Some(p); + r + } + } + } else if let Some(p) = pending.as_ref().filter(|_| late.is_none()) { + // Nothing more is queued behind it, to run unseen when it ends. + json!({"ok": false, "busy": true, "error": format!("busy: request {} (`{}`) is still running; ask `control.pending` for its result", p.id, p.method)}) + } else { + if late.is_some() { + // Finished, and the client moved on without asking: it is dropped. + pending = None; + } + // A batch replaces many short requests: the whole of it may take long (#743). + let wait = if patient || method == "engine.batch" { waits.long } else { waits.short }; + let (req, rrx) = ControlRequest::new(method.clone(), params); + if tx.send(req).is_err() { + break; + } + ctx.request_repaint(); + match rrx.recv_timeout(wait) { + Ok(r) => r, + Err(_) => { + let r = json!({"ok": false, "running": true, "error": format!("timeout: `{method}` is still running in the app and will still apply; ask `control.pending` for its result")}); + pending = Some(Pending { id: id.clone(), method, reply: rrx }); + r + } + } + }; if let Some(o) = r.as_object_mut() { o.insert("id".into(), id); } @@ -228,6 +283,62 @@ fn serve(stream: TcpStream, token: &str, tx: Sender, ctx: egui:: mod tests { use super::*; + /// #1618: a request that outlasts its wait says it is still running; the connection keeps its + /// reply for `control.pending`, and refuses other requests as `busy` until it lands, so none + /// is queued to run unseen behind it. + #[test] + fn a_timed_out_request_can_be_asked_for_later() { + let token = "0123456789abcdef0123456789abcdef"; + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let (tx, rx) = channel::(); + let ran = std::sync::Arc::new(std::sync::Mutex::new(Vec::::new())); + let seen = ran.clone(); + std::thread::spawn(move || { + for req in rx { + seen.lock().unwrap().push(req.method.clone()); + if req.method == "slow" { + std::thread::sleep(Duration::from_millis(400)); + } + let _ = req.reply.send(json!({"ok": true, "result": req.method})); + } + }); + let waits = Waits { short: Duration::from_millis(100), long: Duration::from_millis(100) }; + std::thread::spawn(move || { + if let Some(stream) = listener.incoming().flatten().next() { + serve_with(stream, token, tx, egui::Context::default(), false, waits); + } + }); + let s = TcpStream::connect(addr).unwrap(); + s.set_read_timeout(Some(Duration::from_secs(10))).unwrap(); + let mut out = s.try_clone().unwrap(); + let mut lines = BufReader::new(s); + let mut ask = |v: Value| -> Value { + writeln!(out, "{v}").unwrap(); + let mut l = String::new(); + lines.read_line(&mut l).unwrap(); + serde_json::from_str(&l).unwrap() + }; + let r = ask(json!({"id": 1, "method": "slow", "token": token})); + assert!(r["ok"] == false && r["running"] == true && r["error"].as_str().is_some_and(|e| e.starts_with("timeout")), "{r}"); + let r = ask(json!({"id": 2, "method": "ui.view"})); + assert!(r["busy"] == true && r["id"] == 2, "{r}"); + let r = ask(json!({"id": 3, "method": "control.pending"})); + assert_eq!((&r["result"]["pending"], &r["result"]["done"]), (&json!(1), &json!(false)), "{r}"); + std::thread::sleep(Duration::from_millis(600)); + let r = ask(json!({"id": 4, "method": "control.pending"})); + assert_eq!( + (&r["result"]["pending"], &r["result"]["done"], &r["result"]["reply"]["result"]), + (&json!(1), &json!(true), &json!("slow")), + "{r}" + ); + let r = ask(json!({"id": 5, "method": "control.pending"})); + assert_eq!(r["result"]["pending"], Value::Null, "{r}"); + let r = ask(json!({"id": 6, "method": "ui.view"})); + assert_eq!((&r["ok"], &r["result"]), (&json!(true), &json!("ui.view")), "{r}"); + assert_eq!(*ran.lock().unwrap(), ["slow", "ui.view"], "the busy request never reached the app"); + } + /// #205: a connection runs nothing until a request carries the launch's token; a wrong or /// missing token, or garbage, is refused and the connection closed. Once shown, the token /// need not be repeated on that connection. diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 142ea2639..ebddf4c34 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -48,7 +48,16 @@ connections that send eight lines that are not JSON. At most 16 connections are (further ones get `{"ok": false, "error": "too many connections"}`), at most 64 queued requests run per frame so a flood cannot starve drawing, and a request that the UI thread has not answered within 60 seconds (3600 seconds for `engine.batch`) is replied to with -`{"ok": false, "error": "timeout"}`. The same 16 MiB line limit applies to the MCP server. +`{"ok": false, "running": true, "error": "timeout: … is still running …"}`. The same 16 MiB line +limit applies to the MCP server. + +A timed-out request has not failed: it is still running in the app and will still apply (a long +fillet, say), so don't simply send it again. The connection keeps its reply (#1618). Ask for it +with `control.pending`: `{"pending": , "method": …, "done": false}` while it runs, then +`{"pending": , "method": …, "done": true, "reply": {…}}` (its own reply, once), and +`{"pending": null}` when nothing is outstanding. Until it lands, any other request on that +connection is refused at once with `{"ok": false, "busy": true, "error": "busy: …"}` and not +run, so nothing is queued to apply unseen behind it. Any request's `params` may carry `allow_paths: ["/abs/folder", …]`: every file that request reads, writes or deletes (command paths such as `file.export`'s `path` or `doc.recovery_*`'s From 07da7f8065cda54e2e9813bf50cb08abbce927f6 Mon Sep 17 00:00:00 2001 From: midasdf <205497066+midasdf@users.noreply.github.com> Date: Fri, 16 Oct 2026 16:26:20 +0900 Subject: [PATCH 88/92] Class-A surfacing 2/3: surface match, boundary patch and CV fairing (#1487) Thanks @midasdf. --- ATTRIBUTION.md | 1 + assets/locales/de.json | 2 + assets/locales/en.json | 2 + assets/locales/ja.json | 2 + assets/locales/ko.json | 2 + assets/locales/zh.json | 2 + crates/doc/src/document.rs | 82 + crates/doc/src/eval.rs | 3 + crates/doc/src/eval_surface.rs | 136 ++ crates/doc/src/feature_walk_tests/fixtures.rs | 5 + .../src/feature_walk_tests/golden_exprs.txt | 7 + .../feature_walk_tests/golden_geometry.txt | 9 + .../src/feature_walk_tests/golden_refs.txt | 9 + .../src/format/pending/class-a-surfaces.rs | 5 + crates/doc/src/walk.rs | 2 + crates/engine/src/cmd/mod.rs | 2 + crates/engine/src/cmd/surface.rs | 102 +- crates/engine/src/cmd/surface_boundary.rs | 197 +++ crates/engine/src/cmd/surface_match.rs | 160 ++ crates/kernel/src/boundary.rs | 123 ++ crates/kernel/src/boundary_tests.rs | 276 +++ crates/kernel/src/fair.rs | 1538 +++++++++++++++++ crates/kernel/src/lib.rs | 9 + crates/kernel/src/matchsurf.rs | 601 +++++++ crates/kernel/src/matchsurf_tests.rs | 225 +++ crates/sketch/src/model.rs | 22 +- docs/screenshots/class-a-boundary.png | Bin 0 -> 616830 bytes 27 files changed, 3513 insertions(+), 11 deletions(-) create mode 100644 crates/doc/src/format/pending/class-a-surfaces.rs create mode 100644 crates/engine/src/cmd/surface_boundary.rs create mode 100644 crates/engine/src/cmd/surface_match.rs create mode 100644 crates/kernel/src/boundary.rs create mode 100644 crates/kernel/src/boundary_tests.rs create mode 100644 crates/kernel/src/fair.rs create mode 100644 crates/kernel/src/matchsurf.rs create mode 100644 crates/kernel/src/matchsurf_tests.rs create mode 100644 docs/screenshots/class-a-boundary.png diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index b5b8c4d2d..97dca7e5d 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -36,6 +36,7 @@ Editable drawing code, native projects and shipped exports are collected under ` | assets/archive/icons/macos-v1/exports/icon.iconset/icon_256x256@2x.png | SolidCraft contributors | native sips export from assets/archive/icons/macos-v1/exports/icon.png | MIT OR Apache-2.0 | | assets/archive/icons/macos-v1/exports/icon.iconset/icon_512x512.png | SolidCraft contributors | native sips export from assets/archive/icons/macos-v1/exports/icon.png | MIT OR Apache-2.0 | | assets/archive/icons/macos-v1/exports/icon.iconset/icon_512x512@2x.png | SolidCraft contributors | native sips export from assets/archive/icons/macos-v1/exports/icon.png | 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 | | 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 | diff --git a/assets/locales/de.json b/assets/locales/de.json index 69381095e..c74bd78cf 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -366,8 +366,10 @@ "cmd.surface_blend": "Verbindungsfläche", "cmd.surface_boundary": "Begrenzungsfläche", "cmd.surface_extrude": "Flächen-Extrusion", + "cmd.surface_fair": "Flächenbegradigung", "cmd.surface_fillet": "Flächenverrundung", "cmd.surface_loft": "Flächen-Loft", + "cmd.surface_match": "Flächenanpassung", "cmd.surface_offset": "Offsetfläche", "cmd.surface_patch": "Patch", "cmd.surface_reverse_normal": "Normale umkehren", diff --git a/assets/locales/en.json b/assets/locales/en.json index 5767b5ddd..ffbe52a36 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -568,8 +568,10 @@ "cmd.surface_blend": "Blend Surface", "cmd.surface_boundary": "Boundary Surface", "cmd.surface_extrude": "Surface Extrude", + "cmd.surface_fair": "Fair Surface", "cmd.surface_fillet": "Surface Fillet", "cmd.surface_loft": "Surface Loft", + "cmd.surface_match": "Match Surface", "cmd.surface_offset": "Offset Surface", "cmd.surface_patch": "Patch", "cmd.surface_reverse_normal": "Reverse Normal", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 350dccc75..4bb4502fe 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -568,8 +568,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": "法線を反転", diff --git a/assets/locales/ko.json b/assets/locales/ko.json index 09c175fbd..a274a3582 100644 --- a/assets/locales/ko.json +++ b/assets/locales/ko.json @@ -366,8 +366,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": "법선 반전", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index 264d61d72..b310f839a 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -568,8 +568,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": "反转法向", diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 37062da19..21e4125c6 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -1384,6 +1384,59 @@ pub enum FeatureKind { #[serde(default, skip_serializing_if = "std::ops::Not::not")] stitch: bool, }, + /// One surface patch through a network of two to four boundary curves of a sketch + /// (`surface.boundary`, issue #763): the patch runs through the curves in loop order and leaves + /// each boundary at its own `order` — a sketch curve's boundary is a plane, so G1 and up hold + /// exactly — with `crown` shaping the middle without touching a boundary. + SurfaceBoundary { + sketch: SketchId, + /// The curves in loop order: each one ends where the next begins, and the last where the + /// first does. + curves: Vec, + /// How much of the surface across each boundary the patch repeats, one per curve (none: a + /// tangent plane, `g1`, on every side). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + orders: Vec, + /// How full the middle is: 0 the plain construction, up to 3 fuller, down to -0.9 flatter. + #[serde(default)] + crown: f64, + /// The stations every boundary carries. + #[serde(default = "boundary_samples")] + samples: usize, + }, + /// One face of a surface body rebuilt against another body (`surface.match`): the rebuilt + /// boundary nearest the chain of `edges` on `target` takes that chain's place and repeats the + /// target's own shape along the seam up to `order`, while the boundary opposite it, and the + /// body's name, stay where they were. `faces` picks the face to rebuild (its first, when none). + SurfaceMatch { + body: BodyName, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + faces: Vec, + target: BodyName, + edges: Vec, + #[serde(default = "match_order")] + order: Continuity, + }, + /// The B-spline faces at `faces` of `body` faired (`surface.fair`): each face's interior + /// control vertices move to flatten the thin-plate (curvature-variation) energy of the face, + /// `strength` of the full least-squares step at a time, for at most `iterations` steps. + /// `keep_edges` holds the row of control points next to each edge as well as the boundary row + /// itself, so the face keeps meeting its neighbours in position and in tangent. `tolerance` + /// is the farthest a control point may move, so the faired face stays within it of the one the + /// design asked for; an empty `faces` fairs every face of the body. + SurfaceFair { + body: BodyName, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + faces: Vec, + #[serde(default = "fair_strength")] + strength: f64, + #[serde(default = "fair_iterations")] + iterations: u32, + #[serde(default = "fair_keep_edges")] + keep_edges: bool, + #[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`. SurfaceTrim { @@ -1600,10 +1653,33 @@ fn is_g0(g: &Continuity) -> bool { } /// The continuity a blend repeats by default: the tangent plane on both sides. +/// The stations a boundary patch carries by default. +fn boundary_samples() -> usize { + 25 +} + fn blend_orders() -> [Continuity; 2] { [Continuity::G1, Continuity::G1] } +/// The continuity a match holds by default: position, tangent plane and curvature. +fn match_order() -> Continuity { + Continuity::G2 +} + +/// A fairing's defaults for a design that leaves them out: the whole least-squares step at a +/// time, and the boundary held (the row next to each edge too, so the face still meets its +/// neighbours in tangent). +fn fair_strength() -> f64 { + 1.0 +} +fn fair_iterations() -> u32 { + 1 +} +fn fair_keep_edges() -> bool { + true +} + /// Triangles of one imported mesh body (millimetres). #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MeshData { @@ -1896,6 +1972,9 @@ impl FeatureKind { FeatureKind::SurfaceSweep { .. } => "SurfaceSweepFeature", FeatureKind::SurfaceLoft { .. } => "SurfaceLoftFeature", FeatureKind::SurfaceBlend { .. } => "BlendFeature", + FeatureKind::SurfaceBoundary { .. } => "BoundaryFeature", + FeatureKind::SurfaceMatch { .. } => "MatchFeature", + FeatureKind::SurfaceFair { .. } => "FairFeature", FeatureKind::Stitch { .. } => "StitchFeature", FeatureKind::Thicken { .. } => "ThickenFeature", FeatureKind::SurfaceTrim { .. } => "TrimFeature", @@ -1973,6 +2052,9 @@ impl FeatureKind { FeatureKind::SurfaceSweep { .. } => "SurfaceSweep", FeatureKind::SurfaceLoft { .. } => "SurfaceLoft", FeatureKind::SurfaceBlend { .. } => "Blend", + FeatureKind::SurfaceBoundary { .. } => "Boundary", + FeatureKind::SurfaceMatch { .. } => "Match", + FeatureKind::SurfaceFair { .. } => "Fair", FeatureKind::Stitch { .. } => "Stitch", FeatureKind::Thicken { .. } => "Thicken", FeatureKind::SurfaceTrim { .. } => "Trim", diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index d2b523196..12003ecdb 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -4133,6 +4133,9 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: | FeatureKind::SurfaceSweep { .. } | FeatureKind::SurfaceLoft { .. } | FeatureKind::SurfaceBlend { .. } + | FeatureKind::SurfaceBoundary { .. } + | FeatureKind::SurfaceMatch { .. } + | FeatureKind::SurfaceFair { .. } | FeatureKind::SurfaceOffset { .. } | FeatureKind::SurfaceRuled { .. } | FeatureKind::SurfaceUntrim { .. } => surface::eval(doc, vals, f, st, warning), diff --git a/crates/doc/src/eval_surface.rs b/crates/doc/src/eval_surface.rs index 19a1d35f1..d6c8a5737 100644 --- a/crates/doc/src/eval_surface.rs +++ b/crates/doc/src/eval_surface.rs @@ -145,6 +145,78 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, st.bodies.push(ModelBody::new(name, made, f.id)); Ok(()) } + FeatureKind::SurfaceBoundary { sketch, curves, orders, crown, samples } => { + let ss = sketch_in_feature_frame( + doc, + st.sketch(sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {sketch} (it must come earlier in the timeline)")))?, + f.component, + )?; + let boundaries = boundary_frames(&ss, curves, orders, *samples)?; + let body = kernel::boundary_patch(&boundaries, *crown, *samples)?; + let name = new_name(st, f, 0); + st.bodies.push(ModelBody::new(name, body, f.id)); + Ok(()) + } + FeatureKind::SurfaceMatch { body, faces, target, edges, order } => { + 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 tb = st.body(target).ok_or_else(|| DocError::Unknown(format!("body `{target}`")))?.body.clone(); + if edges.is_empty() { + return Err(DocError::Invalid("a match needs a chain of the target's edges".into())); + } + // Picked by a point on the face; without picks, the body's first face. + let picked: Vec = if faces.is_empty() { + let faces = mb.body.faces(mb.body.size() * 1e-2)?; + vec![faces.first().ok_or_else(|| DocError::Invalid(format!("`{body}` has no face to match")))?.centroid] + } else { + crate::plain(faces) + }; + let made = kernel::match_surface(&mb.body, &picked, &tb, &crate::plain(edges), *order)?; + // A match rebuilds the face in place: the body keeps its name, and whatever meets it + // downstream still finds it. + if let Some(slot) = st.bodies.get_mut(i) { + *slot = ModelBody::new(mb.name, made, mb.feature); + } + Ok(()) + } + FeatureKind::SurfaceFair { body, faces, strength, iterations, keep_edges, tolerance } => { + let tol = val(vals, tolerance, Kind::Length)?; + let opts = kernel::FairOptions::new(*strength, *iterations as usize, *keep_edges, tol)?; + 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())) }; + // Picked by a point on the face; without picks, every face of the body. + let mut picked: Vec = Vec::new(); + if faces.is_empty() { + picked.extend(0..mb.body.face_count()); + } else { + for p in faces { + let fi = + crate::appearance::face_index_at(&mb, p.0).ok_or_else(|| DocError::Invalid(format!("Fair: no face of {body} at {p:?}")))?; + if !picked.contains(&fi) { + picked.push(fi); + } + } + } + if picked.is_empty() { + return Err(DocError::Invalid("the body has no faces to fair".into())); + } + // The face keeps every edge it had: only the surface between them is faired. The + // energy before and after goes into the feature's warning, so the reply can say how + // much the face moved. + let (faired, report) = kernel::fair_faces(&mb.body, &picked, &opts)?; + *warning = Some(format!( + "faired {} face(s): energy {:.6} → {:.6} in {} step(s), control points moved up to {:.4} mm", + picked.len(), + report.energy_before, + report.energy_after, + report.steps, + report.movement + )); + if let Some(slot) = st.bodies.get_mut(i) { + *slot = ModelBody::new(mb.name, faired, mb.feature); + } + Ok(()) + } FeatureKind::SurfaceExtrude { sketch, profiles, curves, extent } => { let ss = sketch_in_feature_frame( doc, @@ -349,6 +421,70 @@ fn push_sheet(st: &mut ModelState, f: &Feature, traced: crate::lineage::Traced) st.bodies.push(ModelBody::traced_new(name, traced, f.id)); } +/// The boundaries `surface.boundary` builds its patch from: each picked curve's own stations in +/// the sketch's frame, every one of them leaving the boundary square into the loop — the direction +/// from the curve towards the middle of the loop, taken across its tangent — over the plane the +/// curve lies in (so a chain of planar curves makes a flat patch, and a network that is not +/// coplanar is followed as the plane through the curve's own tangent). `orders` sets how much of +/// that plane each side repeats. +fn boundary_frames( + ss: &SolvedSketch, + curves: &[String], + orders: &[solidcraft_kernel::Continuity], + samples: usize, +) -> Result> { + use solidcraft_kernel::{Boundary, Frame}; + // The stations along each curve, evenly in its own arclength, so every side carries the same + // number of frames and the patch's net is square. + let mut sides: Vec> = Vec::with_capacity(curves.len()); + for id in curves { + let ci = ss.sketch.curve_index(id).ok_or_else(|| DocError::Unknown(format!("sketch curve `{id}`")))?; + let pieces = ss.sketch.exact_pieces(ci); + if pieces.is_empty() { + return Err(DocError::Invalid(format!("curve `{id}` has no exact geometry to build on"))); + } + let lengths: Vec = pieces.iter().map(Seg2::length).collect(); + let total: f64 = lengths.iter().sum(); + if !total.is_finite() || total <= 1e-9 { + return Err(DocError::Invalid(format!("curve `{id}` has no length"))); + } + let mut pts = Vec::with_capacity(samples); + let (mut used, mut at) = (0.0, 0usize); + for k in 0..samples { + let want = total * k as f64 / (samples.saturating_sub(1)).max(1) as f64; + while at + 1 < pieces.len() && used + lengths[at] < want { + used += lengths[at]; + at += 1; + } + let (Some(piece), Some(len)) = (pieces.get(at), lengths.get(at)) else { return Err(DocError::Invalid("boundary piece".into())) }; + let t = ((want - used) / len.max(1e-12)).clamp(0.0, 1.0); + pts.push(ss.plane.to_world(piece.point_at(t))); + } + sides.push(pts); + } + // The middle of the loop, so every side leaves towards the inside of the patch. + let count = sides.iter().map(Vec::len).sum::().max(1) as f64; + let centre = sides.iter().flatten().fold(solidcraft_geom::Vec3::ZERO, |a, p| a + *p) * (1.0 / count); + let mut out = Vec::with_capacity(sides.len()); + for (side, pts) in sides.iter().enumerate() { + let mut frames = Vec::with_capacity(pts.len()); + for (i, p) in pts.iter().enumerate() { + // The tangent from the stations on either side, one-sided at the ends (where the side + // only has one neighbour). + let before = if i == 0 { *p } else { pts[i - 1] }; + let after = if i + 1 == pts.len() { *p } else { pts[i + 1] }; + let tangent = (after - before).normalized().ok_or_else(|| DocError::Invalid("a boundary curve has a stationary station".into()))?; + let across = centre - *p; + let leave = (across - tangent * across.dot(tangent)) + .normalized() + .ok_or_else(|| DocError::Invalid("a boundary runs through the middle of the loop: no patch can leave it".into()))?; + frames.push(Frame { p: *p, leave, bend: Vec3::ZERO, bend_change: Vec3::ZERO }); + } + out.push(Boundary { frames, order: orders.get(side).copied().unwrap_or(solidcraft_kernel::Continuity::G1) }); + } + Ok(out) +} + /// 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 6a23ee71c..2364cf6c6 100644 --- a/crates/doc/src/feature_walk_tests/fixtures.rs +++ b/crates/doc/src/feature_walk_tests/fixtures.rs @@ -161,6 +161,11 @@ pub(super) fn fixtures() -> Vec<(&'static str, Value)> { ("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_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_boundary", json!({"type": "surface_boundary", "sketch": 1, "curves": ["l1", "l2"]})), + ("surface_match", json!({"type": "surface_match", "body": "B", "faces": [o], "target": "C", "edges": [o]})), + ("surface_fair", json!({"type": "surface_fair", "body": "B", "faces": [o], "tolerance": "sfair.tolerance"})), ("unstitch", json!({"type": "unstitch", "body": "B"})), ("reverse_normal", json!({"type": "reverse_normal", "body": "B"})), ("surface_untrim", json!({"type": "surface_untrim", "face": {"body": "B", "point": o}, "holes": [o], "outer": true})), diff --git a/crates/doc/src/feature_walk_tests/golden_exprs.txt b/crates/doc/src/feature_walk_tests/golden_exprs.txt index 7a060857a..5a8877777 100644 --- a/crates/doc/src/feature_walk_tests/golden_exprs.txt +++ b/crates/doc/src/feature_walk_tests/golden_exprs.txt @@ -340,6 +340,13 @@ surface_offset Distance = soff.distance (Length) Tolerance = soff.tolerance (Length) expressions: soff.distance, soff.tolerance +surface_blend +surface_boundary +surface_match +surface_fair + inputs: + Tolerance = sfair.tolerance (Length) + expressions: sfair.tolerance unstitch reverse_normal surface_untrim diff --git a/crates/doc/src/feature_walk_tests/golden_geometry.txt b/crates/doc/src/feature_walk_tests/golden_geometry.txt index 32f8592e4..767444fa7 100644 --- a/crates/doc/src/feature_walk_tests/golden_geometry.txt +++ b/crates/doc/src/feature_walk_tests/golden_geometry.txt @@ -154,6 +154,15 @@ surface_blend 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] +surface_boundary +surface_match + moves: edges[0][0], edges[0][1], edges[0][2], faces[0][0], faces[0][1], faces[0][2] + face points: [0, 0, 0] +surface_fair + moves: faces[0][0], faces[0][1], faces[0][2] + face points: [0, 0, 0] unstitch moves: faces[0][0], faces[0][1], faces[0][2] reverse_normal diff --git a/crates/doc/src/feature_walk_tests/golden_refs.txt b/crates/doc/src/feature_walk_tests/golden_refs.txt index 9c56ab0b1..0b621c6a0 100644 --- a/crates/doc/src/feature_walk_tests/golden_refs.txt +++ b/crates/doc/src/feature_walk_tests/golden_refs.txt @@ -177,6 +177,15 @@ surface_blend remap_bodies: from.body surface_offset remap_bodies: body +surface_blend + remap_bodies: from.body +surface_boundary + sketches: [1] + remap_refs: sketch +surface_match + remap_bodies: body +surface_fair + remap_bodies: body unstitch remap_bodies: body reverse_normal diff --git a/crates/doc/src/format/pending/class-a-surfaces.rs b/crates/doc/src/format/pending/class-a-surfaces.rs new file mode 100644 index 000000000..ee4e58597 --- /dev/null +++ b/crates/doc/src/format/pending/class-a-surfaces.rs @@ -0,0 +1,5 @@ +//! The Class-A surface pass adds `SurfaceBoundary` (Boundary Surface: `sketch`, `curves`, +//! optional `orders`, `crown`, `samples`), `SurfaceMatch` (Match Surface: `body`, optional +//! `faces`, `target`, `edges`, optional `order`) and `SurfaceFair` (Fair Surface: `body`, optional +//! `faces`, `strength`, `iterations`, `keep_edges`, `tolerance`). Older designs need no +//! transformation; 0.13.x asks for an update instead of meeting a feature it can't read. diff --git a/crates/doc/src/walk.rs b/crates/doc/src/walk.rs index 64073b311..7c571a1bb 100644 --- a/crates/doc/src/walk.rs +++ b/crates/doc/src/walk.rs @@ -40,6 +40,8 @@ impl Walk for bool {} impl Walk for u64 {} impl Walk for i8 {} impl Walk for f64 {} +impl Walk for usize {} +impl Walk for u32 {} impl Walk for ProfileSel {} impl Walk for solidcraft_sketch::Sketch {} impl Walk for solidcraft_sketch::PatternAlignment {} diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index db7fa5c3f..a37f226a7 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -74,6 +74,7 @@ mod sketch_modify; mod sketch_project; mod surface; mod surface_analysis; +mod surface_match; mod view_dxf; mod view_navigation; @@ -236,6 +237,7 @@ pub fn command_specs() -> Vec<&'static CommandSpec> { v.extend(sketch_3d::COMMANDS.iter()); v.extend(surface_analysis::COMMANDS.iter()); v.extend(surface::COMMANDS.iter()); + v.extend(surface_match::COMMANDS.iter()); v.extend(sketch_modify::COMMANDS.iter()); v.extend(sketch_project::COMMANDS.iter()); v.extend(features::COMMANDS.iter()); diff --git a/crates/engine/src/cmd/surface.rs b/crates/engine/src/cmd/surface.rs index 93d7a19af..4e76e0d46 100644 --- a/crates/engine/src/cmd/surface.rs +++ b/crates/engine/src/cmd/surface.rs @@ -3,7 +3,8 @@ use serde_json::Value; use solidcraft_doc::{ - BlendSide, EdgeContinuity, ExtendMode, ExtendTo, FaceAt, FeatureKind, PatchContinuity, PlaneRef, ProfileSel, RuledCorners, RuledMode, expr::Kind, + BlendSide, EdgeContinuity, Expr, ExtendMode, ExtendTo, FaceAt, FeatureKind, PatchContinuity, PlaneRef, ProfileSel, RuledCorners, RuledMode, + expr::Kind, }; use solidcraft_doc::{BodyName, SketchId}; use solidcraft_doc::{Dir, FacePick, Position}; @@ -11,7 +12,7 @@ use solidcraft_kernel::Continuity; use super::CommandSpec; use super::features::{add_feature, axis_param, check_expr, extent_param, feature_sketch, operation, plane_param, profiles, sketch_id}; -use crate::params::{bad, bool_, expr, str_, string_list, vec3}; +use crate::params::{bad, bool_, expr, num, str_, string_list, vec3}; use crate::{Result, Session}; pub static COMMANDS: &[CommandSpec] = &[ @@ -59,10 +60,6 @@ pub static COMMANDS: &[CommandSpec] = &[ .at("SURFACE", "CREATE") .icon("ruled") .params("body; edges: [[x,y,z]] (points on a chain of its edges, open or closed); distance: expr (how far the strip reaches); mode?: normal|tangent|angle|direction (default normal: along the normal of the face beside each edge; tangent: continuing it); angle?: expr (angle mode: from `direction`, else from the face's normal, turned away from the face; 90 deg from the normal is tangent); direction?: [x,y,z] (direction mode: the rulings; angle mode: the reference, e.g. a pull direction for a draft); face?: [x,y,z] (a point on the face the directions come from; default: the face beside the most picked edges); flip?: bool (the other side); corners?: mitre|round (sharp corners of the chain; inside corners are always cut back). Lines and arcs give exact planes, cylinders and cones, other edges a fitted ruled B-spline. A new surface body"), - planned!("surface.boundary", "Boundary Surface", "763") - .at("SURFACE", "CREATE") - .icon("boundary") - .params("planned: u: [curves], v?: [curves] (sketch curves, 3D sketch wires or {body, point} edges; 2–4 boundaries, more make a network); continuity?: [{curve, g: 0|1|2}] for edge boundaries; operation?: new|join"), CommandSpec::new("surface.blend", "Blend Surface", blend) .at("SURFACE", "CREATE") .icon("surface_blend") @@ -79,6 +76,10 @@ pub static COMMANDS: &[CommandSpec] = &[ .at("SURFACE", "MODIFY") .icon("reverse_normal") .params("body (a surface); faces?: [[x,y,z]] (points on the faces to turn over; default: all of them)"), + CommandSpec::new("surface.fair", "Fair Surface", fair) + .at("SURFACE", "MODIFY") + .icon("spline_cv") + .params("body: surface name; faces?: [[x,y,z]] points on the faces to fair (default: every face); strength?: number (0..1 of the full fairing step, default 1); iterations?: number (1..1000 steps, default 1); keep_edges?: bool (default true: hold the boundary row and the row next to it, so a face keeps meeting its neighbours in position and in tangent); tolerance?: expr mm (how far a control vertex may move, default 0.001 of the body's size). Moves the interior control vertices of each B-spline face to flatten its curvature variation while the boundary stays put: the face keeps its edges and the body its shape within the tolerance, and the warning in the reply carries the energy before and after; name?"), planned!("surface.fillet", "Surface Fillet", "769") .at("SURFACE", "MODIFY") .icon("surface_fillet") @@ -558,6 +559,39 @@ fn trim(s: &mut Session, p: &Value) -> Result { add_feature(s, p, FeatureKind::SurfaceTrim { body: BodyName(body), plane, tool, keep: Position(keep) }) } +/// `surface.fair`: the B-spline faces of a body faired in place. The tolerance a caller leaves +/// out is a thousandth of the body's own size, so a fairing run can never make a design jump by +/// more than a hair of itself. +fn fair(s: &mut Session, p: &Value) -> Result { + let cmd = "surface.fair"; + let (body, faces) = body_faces(s, p, cmd)?; + let size = { + let state = s.model.state(); + let Some(mb) = state.body(&body) else { return Err(bad(cmd, format!("no body `{body}`"))) }; + mb.body.size() + }; + let strength = num(p, "strength").unwrap_or(1.0); + if !(strength.is_finite() && strength > 0.0 && strength <= 1.0) { + return Err(bad(cmd, "`strength` must be greater than 0 and at most 1 (the whole fairing step)")); + } + let steps = num(p, "iterations").unwrap_or(1.0); + if !(steps.is_finite() && (1.0..=1000.0).contains(&steps)) { + return Err(bad(cmd, "`iterations` must be 1 to 1000")); + } + let keep_edges = bool_(p, "keep_edges").unwrap_or(true); + let tolerance = expr(p, "tolerance").unwrap_or_else(|| Expr::new(format!("{:.6}", (size * 1e-3).max(1e-6)))); + check_expr(s, tolerance.as_str(), Kind::Length, cmd, "tolerance")?; + let kind = FeatureKind::SurfaceFair { + body: BodyName::from(body), + faces: faces.into_iter().map(FacePick).collect(), + strength, + iterations: steps as u32, + keep_edges, + tolerance, + }; + add_feature(s, p, kind) +} + #[cfg(test)] mod tests { use super::*; @@ -1178,7 +1212,7 @@ mod tests { /// as it was. #[test] fn planned_commands_refuse_and_leave_the_design_alone() { - let planned = ["surface.boundary", "surface.fillet", "inspect.continuity"]; + let planned = ["surface.fillet", "inspect.continuity"]; let mut s = Session::default(); run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "B"})); let before = s.doc.features.len(); @@ -1500,4 +1534,58 @@ mod tests { let sketch_patch = json!({"sketch": 1, "continuity": "g1"}); assert!(s.execute("surface.patch", &sketch_patch).is_err(), "continuity on a sketch patch"); } + /// The energies the reply's warning carries: the fairness energy before and after. + fn energies(reply: &Value) -> (f64, f64) { + let warning = reply["warning"].as_str().unwrap_or_else(|| panic!("no warning in {reply}")); + let after = warning.split("energy ").nth(1).unwrap_or_else(|| panic!("no energies in `{warning}`")); + let numbers: Vec = after + .split(|c: char| !(c.is_ascii_digit() || c == '.' || c == 'e' || c == '-' || c == '+')) + .filter_map(|w| w.parse::().ok()) + .collect(); + assert!(numbers.len() >= 2, "no energies in `{warning}`"); + (numbers[0], numbers[1]) + } + + /// Surface Fair on the fitted B-spline face of an offset sphere: the face is smoothed in + /// place, its edges do not move at all, the reply carries the energy before and after, undo, + /// redo and a cold reopen keep it, and hostile inputs are refused. + #[test] + fn fairing_a_b_spline_face_keeps_its_edges_and_reports_its_energy() { + let mut s = Session::default(); + run(&mut s, "solid.sphere", json!({"radius": 20, "body_name": "Ball"})); + // A sphere is neither a plane nor a cylinder, so its offset is a fitted B-spline face. + run(&mut s, "surface.offset", json!({"faces": [[0, 0, 20]], "body": "Ball", "distance": 2, "body_name": "Shell"})); + let st = s.world_state(); + assert!(st.body("Shell").unwrap().body.is_surface(), "an offset sphere face is a sheet"); + let before: Vec = st.body("Shell").unwrap().body.edges(0.1).unwrap().iter().flat_map(|e| e.points.clone()).collect(); + assert!(!before.is_empty()); + let area_before = area(&s, "Shell"); + // The fairing reports both energies, the second no larger than the first. + let reply = run(&mut s, "surface.fair", json!({"body": "Shell", "tolerance": 1.0, "iterations": 3})); + let (energy_before, energy_after) = energies(&reply); + let area_after = area(&s, "Shell"); + eprintln!("surface.fair: {reply}\nenergies {energy_before:e} → {energy_after:e}, area {area_before} → {area_after}"); + assert!(energy_before > 0.0 && energy_after <= energy_before, "{energy_before:e} → {energy_after:e}"); + // The face moved (the fit is not the flattest surface on its own rim), but not its edges: + // every boundary point of the body is where it was, bit for bit. + assert!((area_after - area_before).abs() > 0.0 || energy_after < energy_before); + let after: Vec = st.body("Shell").unwrap().body.edges(0.1).unwrap().iter().flat_map(|e| e.points.clone()).collect(); + assert_eq!(after, before, "fairing must not move the face's edges"); + assert_eq!(st.body("Shell").unwrap().body.face_count(), 1); + // Undo takes the fairing back, redo puts it back, and a cold reopen rebuilds the same. + run(&mut s, "edit.undo", json!({})); + assert!((area(&s, "Shell") - area_before).abs() < 1e-9, "undo did not take the fairing back"); + run(&mut s, "edit.redo", json!({})); + assert!((area(&s, "Shell") - area_after).abs() < 1e-9, "redo did not put the fairing back"); + let cold = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); + assert!((area(&cold, "Shell") - area_after).abs() < 1e-9, "a cold reopen did not rebuild the same sheet"); + // Refusals: an unknown body, a body whose faces are all planes, an out-of-range strength + // or step count, and a missing tolerance expression. + assert!(s.execute("surface.fair", &json!({"body": "Nope", "tolerance": 1.0})).is_err()); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Box"})); + assert!(s.execute("surface.fair", &json!({"body": "Box", "tolerance": 1.0})).is_err()); + assert!(s.execute("surface.fair", &json!({"body": "Shell", "strength": 2, "tolerance": 1.0})).is_err()); + assert!(s.execute("surface.fair", &json!({"body": "Shell", "iterations": 0, "tolerance": 1.0})).is_err()); + assert!(s.execute("surface.fair", &json!({"body": "Shell", "tolerance": 0})).is_err()); + } } diff --git a/crates/engine/src/cmd/surface_boundary.rs b/crates/engine/src/cmd/surface_boundary.rs new file mode 100644 index 000000000..6bbc3f1a4 --- /dev/null +++ b/crates/engine/src/cmd/surface_boundary.rs @@ -0,0 +1,197 @@ +//! Boundary surfaces: one patch through a network of two to four sketch curves (`surface.boundary`, +//! issue #763). The kernel builds the face from the curves' own frames; this is the command's +//! parameters and its checks, so that a loop it cannot hold is refused before anything is built. + +use serde_json::Value; +use solidcraft_doc::{FeatureKind, SketchId}; +use solidcraft_kernel::Continuity; + +use super::CommandSpec; +use super::features::{add_feature, feature_sketch}; +use crate::params::{bad, string_list}; +use crate::{Result, Session}; + +/// The stations a boundary carries by default (the patch's resolution along the loop). +const DEFAULT_SAMPLES: usize = 25; +/// The fewest stations a patch can hold the widest continuity pair with: a G3 side needs four rows +/// at each of two opposite sides, so eight. +const MIN_SAMPLES: usize = 8; +/// The most stations a boundary may carry (the kernel's own cap). +const MAX_SAMPLES: usize = 512; + +pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("surface.boundary", "Boundary Surface", boundary) + .at("SURFACE", "CREATE") + .icon("boundary") + .params( + "sketch?: id|name (default: the sketch being edited); curves: [2 to 4 sketch curve ids in loop order] (each one ends where the next begins and the last where the first does; the patch runs through them and leaves each boundary along the tangent across it); continuity?: g0|g1|g2|g3 | [one per curve] (default g1: how much of the surface across each boundary the patch repeats — a sketch curve's own plane, so g1 and up hold exactly and g0 lets the middle bow); crown?: number -0.9…3 (default 0: how full the middle is, without touching a boundary); samples?: 8…512 stations per boundary (default 25); name?, body_name? (a surface body)", + )]; + +/// `surface.boundary`: one patch through a network of two to four sketch curves. +fn boundary(s: &mut Session, p: &Value) -> Result { + let cmd = "surface.boundary"; + let sketch = feature_sketch(s, p, cmd)?; + let curves = string_list(p, "curves"); + if !(2..=4).contains(&curves.len()) { + return Err(bad(cmd, "`curves` must list 2 to 4 sketch curves in loop order")); + } + // The curves must be the sketch's own, and they must run on into one another: the last station + // of each is the first of the next, and the last boundary's end is the first one's start. + let state = s.model.state(); + let sk = state.sketch(sketch).ok_or_else(|| bad(cmd, "the sketch has not been solved"))?; + let mut ends: Vec<(solidcraft_geom::Vec2, solidcraft_geom::Vec2)> = Vec::with_capacity(curves.len()); + for id in &curves { + let ci = sk.sketch.curve_index(id).ok_or_else(|| bad(cmd, format!("no sketch curve `{id}`")))?; + let pieces = sk.sketch.exact_pieces(ci); + let (Some(first), Some(last)) = (pieces.first(), pieces.last()) else { + return Err(bad(cmd, format!("curve `{id}` has no exact geometry to build on"))); + }; + if last.end().dist(first.start()) < 1e-9 { + return Err(bad(cmd, format!("curve `{id}` is closed: a boundary must be one side of the loop"))); + } + ends.push((first.start(), last.end())); + } + // Two boundaries are the two sides of a bridge, which do not meet; three or four run round a + // loop, so each has to end where the next begins. + let scale = ends.iter().map(|(a, b)| a.dist(*b)).fold(1.0_f64, f64::max); + let tol = scale * 1e-4 + 1e-9; + for i in 0..if curves.len() >= 3 { ends.len() } else { 0 } { + let next = (i + 1) % ends.len(); + let (Some(end), Some(start)) = (ends.get(i).map(|e| e.1), ends.get(next).map(|e| e.0)) else { + return Err(bad(cmd, "a curve is missing its ends")); + }; + let gap = end.dist(start); + if gap > tol { + return Err(bad( + cmd, + format!("curve `{}` ends {gap:.4} mm from where `{}` starts: list the curves in loop order", curves[i], curves[next]), + )); + } + } + drop(state); + let orders = match p.get("continuity") { + None | Some(Value::Null) => vec![Continuity::G1; curves.len()], + Some(Value::String(w)) => { + let one = Continuity::parse(w).ok_or_else(|| bad(cmd, "`continuity` must be g0, g1, g2 or g3"))?; + vec![one; curves.len()] + } + Some(v) => { + let list = v.as_array().filter(|a| a.len() == curves.len()).ok_or_else(|| bad(cmd, "`continuity` must be one word, or one per curve"))?; + let mut out = Vec::with_capacity(list.len()); + for x in list { + out.push(x.as_str().and_then(Continuity::parse).ok_or_else(|| bad(cmd, "`continuity` entries must be g0, g1, g2 or g3"))?); + } + out + } + }; + let crown = match p.get("crown") { + None | Some(Value::Null) => 0.0, + Some(v) => v + .as_f64() + .filter(|x| x.is_finite() && (solidcraft_geom::fill::MIN_CROWN..=solidcraft_geom::fill::MAX_CROWN).contains(x)) + .ok_or_else(|| bad(cmd, "`crown` must be a number between -0.9 and 3"))?, + }; + let samples = match p.get("samples") { + None | Some(Value::Null) => DEFAULT_SAMPLES, + Some(v) => { + let n = v.as_f64().filter(|x| x.is_finite() && x.fract() == 0.0).map(|x| x as usize); + n.filter(|x| (MIN_SAMPLES..=MAX_SAMPLES).contains(x)) + .ok_or_else(|| bad(cmd, format!("`samples` must be a whole number of stations between {MIN_SAMPLES} and {MAX_SAMPLES}")))? + } + }; + add_feature(s, p, FeatureKind::SurfaceBoundary { sketch: SketchId(sketch), curves, orders, crown, samples }) +} + +#[cfg(test)] +mod tests { + 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 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 new_sketch() -> Session { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY"})); + s + } + + /// Two parallel 20 mm lines 10 mm apart, and the patch between them. + fn two_walls(s: &mut Session) -> Vec { + let a = ids(&run(s, "sketch.line", json!({"points": [[0, 0], [20, 0]]}))["created"]["curves"])[0].clone(); + let b = ids(&run(s, "sketch.line", json!({"points": [[0, 10], [20, 10]]}))["created"]["curves"])[0].clone(); + vec![a, b] + } + + #[test] + fn a_boundary_patch_between_two_sketch_curves_is_the_sheet_they_span() { + for continuity in [json!("g0"), json!("g1"), json!("g2"), json!(["g1", "g2"])] { + let mut s = new_sketch(); + let curves = two_walls(&mut s); + let r = run(&mut s, "surface.boundary", json!({"curves": curves, "continuity": continuity})); + let body = ids(&r["created_bodies"])[0].clone(); + // It is one face, its boundary is the two lines themselves, and it covers exactly the + // 20 × 10 sheet between them — all four frames lie in the sketch's plane. + let f = run(&mut s, "model.faces", json!({"body": body})); + let faces = f["faces"].as_array().cloned().unwrap_or_default(); + assert_eq!(faces.len(), 1, "{continuity}: {f}"); + assert!((faces[0]["area"].as_f64().unwrap_or(f64::NAN) - 200.0).abs() < 1e-4, "{continuity}: {f}"); + let normal = faces[0]["plane_normal"].as_array().cloned().unwrap_or_default(); + assert_eq!(normal.len(), 3, "{continuity}: the patch is planar: {f}"); + assert!(normal[2].as_f64().unwrap_or(0.0).abs() > 1.0 - 1e-9, "{continuity}: it lies in the sketch's plane: {f}"); + let m = run(&mut s, "inspect.measure", json!({})); + let area = m["total"]["area_mm2"].as_f64().unwrap_or(f64::NAN); + assert!((area - 200.0).abs() < 1e-4, "{continuity}: {area}"); + } + } + + #[test] + fn a_boundary_patch_refuses_a_loop_and_values_it_cannot_hold() { + let mut s = new_sketch(); + let curves = two_walls(&mut s); + let extra = ids(&run(&mut s, "sketch.line", json!({"points": [[30, 30], [40, 40]]}))["created"]["curves"])[0].clone(); + // A loop of three or four: the kernel refuses it with its own reason (a tensor-product patch + // cannot hold two sides' data at a corner, issue #763) rather than building it approximately. + let triangle = ["l1", "l2", "l3"].map(|id| { + let _ = id; + String::new() + }); + let _ = triangle; + let a = ids(&run(&mut s, "sketch.line", json!({"points": [[0, 0], [20, 0]]}))["created"]["curves"])[0].clone(); + let b = ids(&run(&mut s, "sketch.line", json!({"points": [[20, 0], [10, 15]]}))["created"]["curves"])[0].clone(); + let c = ids(&run(&mut s, "sketch.line", json!({"points": [[10, 15], [0, 0]]}))["created"]["curves"])[0].clone(); + let e = s.execute("surface.boundary", &json!({"curves": [a, b, c], "continuity": "g2"})).unwrap_err().to_string(); + assert!(e.contains("not supported yet") && e.contains("#763"), "three boundaries: {e}"); + // A closed square of four lines, in loop order. + let sq = [[[0, 0], [10, 0]], [[10, 0], [10, 10]], [[10, 10], [0, 10]], [[0, 10], [0, 0]]]; + let square: Vec = sq.iter().map(|p| ids(&run(&mut s, "sketch.line", json!({"points": p}))["created"]["curves"])[0].clone()).collect(); + let e = s.execute("surface.boundary", &json!({"curves": square})).unwrap_err().to_string(); + assert!(e.contains("not supported yet") && e.contains("#763"), "four boundaries: {e}"); + // Parameters and curves that make no sense. + let cases: Vec<(Value, &str)> = vec![ + (json!({"curves": [curves[0]]}), "2 to 4"), + (json!({"curves": [curves[0], curves[1], extra.clone(), extra.clone(), extra.clone()]}), "2 to 4"), + (json!({"curves": [curves[0], "nope"]}), "no sketch curve"), + (json!({"curves": curves, "continuity": "g9"}), "continuity"), + (json!({"curves": curves, "continuity": ["g1", "g2", "g3"]}), "continuity"), + (json!({"curves": curves, "crown": 5}), "crown"), + (json!({"curves": curves, "crown": "full"}), "crown"), + (json!({"curves": curves, "samples": 3}), "samples"), + (json!({"curves": curves, "samples": 2.5}), "samples"), + ]; + for (params, want) in cases { + let e = s.execute("surface.boundary", ¶ms).unwrap_err().to_string(); + assert!(e.contains(want), "{params}: {e}"); + } + // Nothing was built by any of them. + assert!(s.model.state().bodies.is_empty(), "a refused patch left a body behind"); + } +} diff --git a/crates/engine/src/cmd/surface_match.rs b/crates/engine/src/cmd/surface_match.rs new file mode 100644 index 000000000..78f5b8ec8 --- /dev/null +++ b/crates/engine/src/cmd/surface_match.rs @@ -0,0 +1,160 @@ +//! `surface.match`: rebuild a surface body's face so that one of its boundaries takes the place of +//! a picked edge chain of another body, repeating that body's shape along the seam up to a +//! requested continuity, while the boundary opposite it keeps its place. The body keeps its name: +//! a match is a modify, like Trim, Extend and Fair. + +use serde_json::Value; +use solidcraft_doc::{BodyName, FacePick, FeatureKind, Position}; +use solidcraft_kernel::Continuity; + +use super::CommandSpec; +use super::features::add_feature; +use crate::params::{bad, str_, vec3}; +use crate::{Result, Session}; + +pub static COMMANDS: &[CommandSpec] = &[ + CommandSpec::new("surface.match", "Match Surface", match_surface) + .at("SURFACE", "MODIFY") + .icon("continuity") + .params( + "body: surface name (the body whose face is rebuilt); faces?: [[x,y,z]] (points on that face, default: the body's first); target: body name (the body the seam must meet); edges: [[x,y,z]] (points on one edge chain of the target: the rebuilt boundary takes its place); order?: g1|g2|g3 (default g2: position and tangent plane, the curvature too, or how that curvature changes along the seam). The far boundary stays where it was and the body keeps its name", + ), +]; + +/// `surface.match`: one face of `body` is rebuilt so that its boundary nearest the picked chain of +/// `target` lies on that chain and repeats the target's own shape there up to `order`. +fn match_surface(s: &mut Session, p: &Value) -> Result { + let cmd = "surface.match"; + 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 target = str_(p, "target").ok_or_else(|| bad(cmd, "`target` is required"))?.to_string(); + if s.model.state().body(&target).is_none() { + return Err(bad(cmd, format!("no body `{target}`"))); + } + let faces: Vec = p.get("faces").and_then(Value::as_array).map(|a| a.iter().filter_map(vec3).collect()).unwrap_or_default(); + if faces.len() > 64 { + return Err(bad(cmd, "too many points on the face to rebuild")); + } + let edges: Vec = p.get("edges").and_then(Value::as_array).map(|a| a.iter().filter_map(vec3).collect()).unwrap_or_default(); + if edges.is_empty() || edges.len() > 10_000 { + return Err(bad(cmd, "`edges` must list 1 to 10000 points on the target's edge chain")); + } + let order = match p.get("order") { + None => Continuity::G2, + Some(v) => v.as_str().and_then(Continuity::parse).filter(|o| *o != Continuity::G0).ok_or_else(|| bad(cmd, "`order` must be g1, g2 or g3"))?, + }; + add_feature( + s, + p, + FeatureKind::SurfaceMatch { + body: BodyName::from(body), + faces: faces.into_iter().map(FacePick).collect(), + target: BodyName::from(target), + edges: edges.into_iter().map(Position).collect(), + order, + }, + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Session; + use serde_json::json; + use solidcraft_geom::Vec3; + + fn run(s: &mut Session, c: &str, p: Value) -> Value { + s.execute(c, &p).unwrap_or_else(|e| panic!("{c}: {e}")) + } + + /// The picked chain: two points of the cylinder's own vertical wall seam, clear of the corners + /// at either end. The seam is where `solid.extrude` starts the circle, so it is read off the + /// body rather than assumed. + fn picks(s: &Session) -> Vec { + let boss = s.world_state().body("Boss").unwrap().body.clone(); + let e = boss + .edges(boss.size() * 1e-2) + .unwrap() + .into_iter() + .find(|e| e.length > 25.0 && (e.mid.x.hypot(e.mid.y) - 10.0).abs() < 0.05 && e.mid.z > 5.0 && e.mid.z < 25.0) + .expect("the cylinder has a straight vertical wall seam"); + let (a, b) = (e.points.first().copied(), e.points.last().copied()); + let (a, b) = (a.unwrap_or(e.mid), b.unwrap_or(e.mid)); + vec![a + (b - a) * 0.25, a + (b - a) * 0.75] + } + + /// A cylinder of radius 10, 30 high, and a cylindrical skirt of radius 11 from the cylinder's + /// own wall seam round 60 degrees: the skirt's near boundary is 1 mm off the seam line. + fn boss_and_skirt(s: &mut Session) { + run(s, "sketch.create", json!({"plane": "XY", "name": "Round"})); + run(s, "sketch.circle.center", json!({"center": [0, 0], "radius": 10})); + run(s, "sketch.finish", json!({})); + run(s, "solid.extrude", json!({"sketch": "Round", "distance": 30, "body_name": "Boss"})); + let seam = picks(s)[0]; + let a = seam.y.atan2(seam.x); + let at = |t: f64| json!([11.0 * t.cos(), 11.0 * t.sin()]); + run(s, "sketch.create", json!({"plane": "XY", "name": "Skirt sketch"})); + let arc = run(s, "sketch.arc.three_point", json!({"start": at(a), "end": at(a + 60f64.to_radians()), "through": at(a + 30f64.to_radians())})) + ["created"]["curves"][0] + .as_str() + .unwrap() + .to_string(); + run(s, "sketch.finish", json!({})); + run(s, "surface.extrude", json!({"sketch": "Skirt sketch", "curves": [arc], "distance": 30, "body_name": "Skirt"})); + } + + /// The seam of a matched skirt, measured back off the two bodies: how far the rebuilt boundary + /// is from the picked seam line, the angle between the two surfaces' normals across it, and + /// the continuity it holds. + fn seam(s: &Session) -> (f64, f64, Continuity) { + let st = s.world_state(); + let made = st.body("Skirt").unwrap().body.clone(); + let target = st.body("Boss").unwrap().body.clone(); + solidcraft_kernel::seam_continuity(&made, &target, &picks(s)).unwrap() + } + + /// `surface.match`: a skirt meets a cylinder's wall seam at g2; the body keeps its name, undo + /// and redo move it back and forth, a cold reopen gives the same seam, and what cannot be + /// matched is refused. + #[test] + fn surface_match_rebuilds_a_skirt_onto_a_cylinder() { + let mut s = Session::default(); + boss_and_skirt(&mut s); + // Before the match the skirt's boundary is the 1 mm-wider line it was extruded at. + let (gap, _, _) = seam(&s); + assert!((gap - 1.0).abs() < 0.05, "the skirt starts a millimetre off the seam: {gap}"); + let chain = picks(&s); + run(&mut s, "surface.match", json!({"body": "Skirt", "target": "Boss", "edges": chain, "order": "g2"})); + let st = s.world_state(); + assert!(st.body("Skirt").is_some(), "the matched body keeps its name"); + assert!(st.body("Boss").is_some(), "the body it was matched to stays too"); + assert!(st.body("Skirt").unwrap().body.is_surface(), "a match stays a surface"); + let (gap, deg, order) = seam(&s); + println!("engine: gap {gap:e} mm, normal {deg:e} deg, order {order:?}"); + assert!(gap < 1e-6, "the seam is on the picked line: {gap:e} mm"); + assert!(deg < 0.05, "the seam holds the wall's tangent plane: {deg} deg"); + assert!(order.conditions() >= Continuity::G1.conditions(), "{order:?}"); + // Undo puts the boundary back, redo matches it again, and a cold reopen agrees. + run(&mut s, "edit.undo", json!({})); + assert!(seam(&s).0 > 0.5, "undo restores the original skirt"); + run(&mut s, "edit.redo", json!({})); + assert!(seam(&s).1 < 0.05, "redo matches it again"); + let cold = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); + assert!(seam(&cold).1 < 0.05, "a reopened design matches the same"); + // Refusals: an unknown body, no target, no picks on the target, a word that is no order, + // and a body that is not a surface. + assert!(s.execute("surface.match", &json!({"body": "Nope", "target": "Boss", "edges": picks(&s)})).is_err()); + assert!(s.execute("surface.match", &json!({"body": "Skirt", "edges": picks(&s)})).is_err()); + assert!(s.execute("surface.match", &json!({"body": "Skirt", "target": "Boss", "edges": []})).is_err()); + assert!(s.execute("surface.match", &json!({"body": "Skirt", "target": "Nope", "edges": picks(&s)})).is_err()); + assert!(s.execute("surface.match", &json!({"body": "Skirt", "target": "Boss", "edges": picks(&s), "order": "g5"})).is_err()); + assert!(s.execute("surface.match", &json!({"body": "Skirt", "target": "Boss", "edges": [[100, 0, 0]]})).is_err()); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "B"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [4, 4]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"sketch": "B", "distance": 4, "body_name": "Block"})); + assert!(s.execute("surface.match", &json!({"body": "Block", "target": "Boss", "edges": picks(&s)})).is_err(), "a solid is not a surface"); + } +} diff --git a/crates/kernel/src/boundary.rs b/crates/kernel/src/boundary.rs new file mode 100644 index 000000000..c0825f2ef --- /dev/null +++ b/crates/kernel/src/boundary.rs @@ -0,0 +1,123 @@ +//! Boundary patches: one face through the boundary curves of a sketch, each side meeting the +//! surface it was taken from at a requested continuity (G0 up to G3). +//! +//! Two boundaries are the two sides of a [`crate::bridge`]: the patch is the Hermite surface that +//! leaves each boundary along the direction its frames state and repeats as much of that support +//! surface — its tangent plane, its curvature, the change of that curvature — as the side's order +//! asks for, with `crown` shaping the middle without touching a boundary condition. +//! +//! A patch through *three or four* boundaries is refused rather than built approximately. At a +//! corner two sides prescribe the same entries of the control net from two different surfaces, and +//! a tensor-product patch can hold both only where those two prescriptions already agree (one wall +//! carrying every side, say). Where they do not — the general case — the requested order would +//! silently drop near the corner, or the boundary curve would visibly leave its stations, and a +//! Gregory-type corner (a rational blend of the sides' own data) is needed to hold them instead +//! (issue #763). Everything this module refuses is an error, never a quietly worse surface. + +use solidcraft_geom::Vec3; + +use crate::body::Body; +use crate::bridge::{Continuity, Frame, bridge}; +use crate::{KernelError, Result}; + +/// The most stations a boundary of a patch may carry. +const MAX_SAMPLES: usize = 512; + +/// One boundary of a patch: the stations along it, and how much of the surface it was taken from +/// the patch repeats there. +#[derive(Clone, Debug)] +pub struct Boundary { + /// The stations along the boundary, in the order they run: the end of one boundary meets the + /// start of the next, and the last meets the first. + pub frames: Vec, + /// How much of the neighbouring surface the patch repeats at this boundary. + pub order: Continuity, +} + +/// A two-sided patch: one face that meets boundary `i` at the continuity its `order` asks for (G0 up +/// to G3), with `samples` stations every boundary must carry and `crown` shaping the middle of the +/// patch without touching any boundary condition (0 the plain blend, up to 3 fuller, down to -0.9 +/// flatter). Three or four boundaries are refused: see the module docs. +pub fn boundary_patch(boundaries: &[Boundary], crown: f64, samples: usize) -> Result { + check_input(boundaries, crown, samples)?; + if boundaries.len() > 2 { + return Err(KernelError::Invalid(format!( + "not supported yet: a patch through {} boundaries — a three- or four-sided patch needs a Gregory-type corner (issue #763); \ + give two boundaries, which is the bridge this builds exactly", + boundaries.len() + ))); + } + let (Some(a), Some(b)) = (boundaries.first(), boundaries.get(1)) else { + return Err(KernelError::Invalid("a boundary patch joins 2 boundaries: one of them is missing".into())); + }; + bridge(&a.frames, &b.frames, [a.order, b.order], [crown, crown]) +} + +/// Everything a patch refuses, before any geometry is built. +fn check_input(boundaries: &[Boundary], crown: f64, samples: usize) -> Result<()> { + let n = boundaries.len(); + if !(2..=4).contains(&n) { + return Err(KernelError::Invalid(format!("a boundary patch joins 2 to 4 boundaries, {n} given"))); + } + if !(2..=MAX_SAMPLES).contains(&samples) { + return Err(KernelError::Invalid(format!("a boundary patch needs 2 to {MAX_SAMPLES} stations per boundary, {samples} given"))); + } + if !crown.is_finite() || !(-0.9..=3.0).contains(&crown) { + return Err(KernelError::Invalid("a boundary patch's crown must be between -0.9 and 3".into())); + } + for (i, b) in boundaries.iter().enumerate() { + if b.frames.len() != samples { + return Err(KernelError::Invalid(format!( + "boundary {i} carries {} stations, not the {samples} every boundary of a patch needs", + b.frames.len() + ))); + } + for f in &b.frames { + if ![f.p, f.leave, f.bend, f.bend_change].into_iter().all(Vec3::is_finite) { + return Err(KernelError::Invalid(format!("boundary {i} has a station that is not finite"))); + } + if f.leave.normalized().is_none() { + return Err(KernelError::Invalid(format!("boundary {i} has a station with no leave direction"))); + } + } + if boundary_length(&b.frames) <= 1e-9 { + return Err(KernelError::Invalid(format!("boundary {i} has no length: a patch needs a curve, not a single point"))); + } + } + // Two boundaries are the two sides of a bridge, which do not meet; three or four would run round + // a loop, so each one would have to end where the next one begins. + if n >= 3 { + let mut scale: f64 = 1.0; + for b in boundaries { + scale = scale.max(boundary_length(&b.frames)); + } + let tol = scale * 1e-4 + 1e-9; + for i in 0..n { + let (Some(a), Some(b)) = (boundaries.get(i), boundaries.get((i + 1) % n)) else { continue }; + let (Some(end), Some(start)) = (a.frames.last(), b.frames.first()) else { continue }; + let gap = end.p.dist(start.p); + if gap > tol { + return Err(KernelError::Invalid(format!( + "boundary {i} ends and boundary {} starts {gap:.6} mm apart: the boundaries of a loop must run on into one another", + (i + 1) % n + ))); + } + } + } + Ok(()) +} + +/// The length of a run of stations. +fn boundary_length(frames: &[Frame]) -> f64 { + let mut length: f64 = 0.0; + for w in frames.windows(2) { + if let (Some(a), Some(b)) = (w.first(), w.get(1)) { + length += a.p.dist(b.p); + } + } + length +} + +#[cfg(test)] +#[path = "boundary_tests.rs"] +mod tests; diff --git a/crates/kernel/src/boundary_tests.rs b/crates/kernel/src/boundary_tests.rs new file mode 100644 index 000000000..ce7abfcb0 --- /dev/null +++ b/crates/kernel/src/boundary_tests.rs @@ -0,0 +1,276 @@ +//! Tests of boundary patches: the bridge this builds is measured back off the face it made — not +//! from the construction — and everything it cannot hold is an error rather than a quiet +//! approximation. + +use super::*; +use crate::body::from_p3; +use truck_modeling::ParametricSurface; + +/// The angle between two vectors, in degrees. +fn angle_deg(a: Vec3, b: Vec3) -> f64 { + (a.normalized().unwrap().dot(b.normalized().unwrap())).clamp(-1.0, 1.0).acos().to_degrees() +} + +/// The geometric shape of a surface curve from its first three derivatives along it: the unit +/// tangent, the curvature vector and the arclength derivative of that curvature vector — the same +/// reading `bridge` states its conditions with. +fn shape_of(d1: Vec3, d2: Vec3, d3: Vec3) -> (Vec3, Vec3, Vec3) { + let sigma = d1.len(); + let t = d1 * (1.0 / sigma); + let tp = d2 * (1.0 / sigma) - d1 * (d1.dot(d2) / (sigma * sigma * sigma)); + let nn = d2 - t * d2.dot(t); + let np = d3 - t * d3.dot(t) - tp * d2.dot(t) - t * d2.dot(tp); + let kappa = np * (sigma * sigma) - nn * (2.0 * d1.dot(d2)); + (t, nn * (1.0 / (sigma * sigma)), kappa * (1.0 / (sigma.powi(5)))) +} + +/// Across a boundary: five samples a step `h` apart, `into` the patch from the parameter `(u, v)`, +/// read back as the position, the unit tangent, the curvature vector and the change of curvature +/// along that inward direction. +fn across(body: &Body, uv: (f64, f64), into: (f64, f64), h: f64) -> (Vec3, Vec3, Vec3, Vec3) { + let face = body.solid.face_iter().next().unwrap(); + let surf = face.surface(); + let q: Vec = (0..5).map(|k| from_p3(surf.subs(uv.0 + k as f64 * h * into.0, uv.1 + k as f64 * h * into.1))).collect(); + let (f0, f1, f2, f3, f4) = (q[0], q[1], q[2], q[3], q[4]); + let d1 = (f0 * -25.0 + f1 * 48.0 + f2 * -36.0 + f3 * 16.0 + f4 * -3.0) * (1.0 / (12.0 * h)); + let d2 = (f0 * 35.0 + f1 * -104.0 + f2 * 114.0 + f3 * -56.0 + f4 * 11.0) * (1.0 / (12.0 * h * h)); + let d3 = (f0 * -5.0 + f1 * 18.0 + f2 * -24.0 + f3 * 14.0 + f4 * -3.0) * (1.0 / (2.0 * h * h * h)); + let (t, bend, change) = shape_of(d1, d2, d3); + (f0, t, bend, change) +} + +/// The stations' parameters: `n` of them, evenly spread over the patch. +fn stations(n: usize) -> Vec { + (0..n).map(|i| i as f64 / (n - 1) as f64).collect() +} + +/// The normal angle a side may be off by. +const ANGLE_TOL: f64 = 0.01; +/// How much of the supporting wall's own curvature a side must repeat, relative to it. +const CURV_TOL: f64 = 1e-3; +/// The normal part of the change of curvature a G3 side may leave over, relative to 1/r² (the +/// finite differences that read the third derivative off the face amplify round-off by 1/h³, so +/// this is a noise floor rather than a geometric tolerance). +const CHANGE_TOL: f64 = 1e-4; + +/// Measure one side of a built patch at every station of `frames`, and check what its order asks +/// for: the boundary curve itself always, the tangent plane from G1 on, the curvature vector from +/// G2 on and its change along the leave direction at G3. +fn check_side(body: &Body, frames: &[Frame], order: Continuity, at: impl Fn(usize) -> ((f64, f64), (f64, f64)), r: f64) { + for (i, f) in frames.iter().enumerate() { + let (uv, into) = at(i); + let (p, t, bend, change) = across(body, uv, into, 1e-3); + let gap = p.dist(f.p); + assert!(gap < 1e-9, "station {i} sits on its boundary: {p:?} vs {:?} ({gap:.2e} mm)", f.p); + if order == Continuity::G0 { + continue; + } + assert!(angle_deg(t, f.leave) < ANGLE_TOL, "station {i} leaves along the tangent: {t:?} vs {:?}", f.leave); + if order == Continuity::G1 { + continue; + } + if f.bend.len() > 1e-9 { + assert!(bend.dist(f.bend) / f.bend.len() < CURV_TOL, "station {i}: curvature {bend:?} vs the wall's {:?}", f.bend); + if order == Continuity::G3 { + let normal = f.bend * (1.0 / f.bend.len()); + assert!(change.dot(normal).abs() < CHANGE_TOL / (r * r), "station {i}: the change of curvature has a normal part {change:?}"); + } + } else { + assert!(bend.len() < CURV_TOL / r, "station {i}: the wall is straight here, the patch curves by {bend:?}"); + if order == Continuity::G3 { + assert!(change.len() < CHANGE_TOL / (r * r), "station {i}: a straight cross-section changes curvature by {change:?}"); + } + } + } +} + +/// Two walls 20 mm apart, each leaving towards the other, both walls of the same cylinder of radius +/// `r` (the valley `bridge` is tested with): the two sides of a two-sided patch. +fn two_walls(n: usize, r: f64) -> (Vec, Vec) { + let mut a = Vec::new(); + let mut b = Vec::new(); + for t in stations(n) { + let y = 20.0 * t; + a.push(Frame { + p: Vec3::new(0.0, y, 0.0), + leave: Vec3::new(0.0, 1.0, 0.0), + bend: Vec3::new(0.0, 0.0, 1.0 / r), + bend_change: Vec3::new(0.0, -1.0 / (r * r), 0.0), + }); + b.push(Frame { + p: Vec3::new(0.0, y + 20.0, 0.0), + leave: Vec3::new(0.0, -1.0, 0.0), + bend: Vec3::new(0.0, 0.0, 1.0 / r), + bend_change: Vec3::new(0.0, 1.0 / (r * r), 0.0), + }); + } + (a, b) +} + +#[test] +fn a_two_sided_patch_is_a_bridge_that_holds_both_ends() { + let n = 9; + let r = 10.0; + let (a, b) = two_walls(n, r); + let boundaries = vec![Boundary { frames: a.clone(), order: Continuity::G2 }, Boundary { frames: b.clone(), order: Continuity::G2 }]; + let body = boundary_patch(&boundaries, 0.0, n).unwrap(); + let s = stations(n); + check_side(&body, &a, Continuity::G2, |i| ((s[i], 0.0), (0.0, 1.0)), r); + check_side(&body, &b, Continuity::G2, |i| ((s[i], 1.0), (0.0, -1.0)), r); +} + +/// Four chained sides round a 20 × 20 square in the XY plane, each leaving into the square: the +/// loop a patch through three or four boundaries would have to close. +fn square_loop(n: usize) -> Vec { + let corners = [(0.0_f64, 0.0_f64), (20.0, 0.0), (20.0, 20.0), (0.0, 20.0)]; + let leaves = [Vec3::new(0.0, 1.0, 0.0), Vec3::new(-1.0, 0.0, 0.0), Vec3::new(0.0, -1.0, 0.0), Vec3::new(1.0, 0.0, 0.0)]; + (0..4) + .map(|side| { + let (a, b) = (corners[side], corners[(side + 1) % 4]); + let frames = stations(n) + .into_iter() + .map(|t| Frame { + p: Vec3::new(a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t, 0.0), + leave: leaves[side], + bend: Vec3::ZERO, + bend_change: Vec3::ZERO, + }) + .collect(); + Boundary { frames, order: Continuity::G2 } + }) + .collect() +} + +#[test] +fn a_two_sided_patch_meets_its_walls_up_to_the_curvature() { + let n = 11; + let r = 10.0; + let (a, b) = two_walls(n, r); + // G0, G1 and G2 are what this patch states: position, tangent plane and curvature across each + // boundary. (A G3 bridge's third-order rows are `bridge`'s own subject, measured in its tests.) + for order in [Continuity::G0, Continuity::G1, Continuity::G2] { + let boundaries = vec![Boundary { frames: a.clone(), order }, Boundary { frames: b.clone(), order }]; + let body = boundary_patch(&boundaries, 0.0, n).unwrap(); + let s = stations(n); + if order == Continuity::G0 { + for (i, f) in a.iter().enumerate() { + let (p, _, _, _) = across(&body, (s[i], 0.0), (0.0, 1.0), 1e-3); + assert!(p.dist(f.p) < 1e-9, "station {i}: {p:?} vs {:?}", f.p); + } + continue; + } + check_side(&body, &a, order, |i| ((s[i], 0.0), (0.0, 1.0)), r); + check_side(&body, &b, order, |i| ((s[i], 1.0), (0.0, -1.0)), r); + } +} + +#[test] +fn a_crown_shapes_the_middle_without_touching_the_boundary_rows() { + let n = 9; + let r = 10.0; + let (a, b) = two_walls(n, r); + let boundaries = vec![Boundary { frames: a.clone(), order: Continuity::G2 }, Boundary { frames: b.clone(), order: Continuity::G2 }]; + let s = stations(n); + let mut middles = Vec::new(); + for crown in [-0.5, 0.0, 1.0, 2.0] { + let body = boundary_patch(&boundaries, crown, n).unwrap(); + let grid = crate::bridge::sample_grid(&body, 9, 9).unwrap(); + middles.push(grid[4][4].z); + // The interior is the cross-section between the two walls: its middle sits in the gap, not + // outside it, and it stays finite everywhere on the grid. + for row in &grid { + for p in row { + assert!(p.is_finite() && (-2.0..=42.0).contains(&p.y), "the interior stays between the walls: {p:?}"); + } + } + assert!((18.0..=22.0).contains(&grid[4][4].y), "the middle of the patch sits midway in the 20 mm band: {:?}", grid[4][4]); + // The conditions are untouched: the same boundary points, tangent and curvature. + check_side(&body, &a, Continuity::G2, |i| ((s[i], 0.0), (0.0, 1.0)), r); + check_side(&body, &b, Continuity::G2, |i| ((s[i], 1.0), (0.0, -1.0)), r); + } + let steps: Vec = middles.windows(2).map(|w| w[1] - w[0]).collect(); + assert!(steps.iter().all(|d| d.abs() > 1e-9), "a fuller crown moves the middle: {middles:?}"); +} + +#[test] +fn the_patch_refuses_what_it_cannot_hold() { + let n = 9; + let (a, b) = two_walls(n, 10.0); + let two = vec![Boundary { frames: a.clone(), order: Continuity::G2 }, Boundary { frames: b.clone(), order: Continuity::G2 }]; + // Not 2 to 4 boundaries. + assert!(boundary_patch(&[], 0.0, n).is_err()); + assert!(boundary_patch(&two[..1], 0.0, n).is_err()); + let five = vec![two[0].clone(), two[1].clone(), two[0].clone(), two[1].clone(), two[0].clone()]; + assert!(boundary_patch(&five, 0.0, n).is_err()); + // Three or four sides are refused: a tensor-product patch cannot hold two sides' data at a + // corner, which needs a Gregory-type corner (issue #763). The message says so. + let square = square_loop(n); + let e = boundary_patch(&square, 0.0, n).unwrap_err().to_string(); + assert!(e.contains("not supported yet") && e.contains("#763"), "4 sides: {e}"); + // Three sides that do close: a triangle, whose last side runs from the second one's end back to + // the first one's start. + let triangle: Vec = vec![ + square[0].clone(), + square[1].clone(), + Boundary { + frames: stations(n) + .into_iter() + .map(|t| Frame { + p: Vec3::new(20.0 * (1.0 - t), 20.0 * (1.0 - t), 0.0), + leave: Vec3::new(-std::f64::consts::FRAC_1_SQRT_2, -std::f64::consts::FRAC_1_SQRT_2, 0.0), + bend: Vec3::ZERO, + bend_change: Vec3::ZERO, + }) + .collect(), + order: Continuity::G2, + }, + ]; + let e = boundary_patch(&triangle, 0.0, n).unwrap_err().to_string(); + assert!(e.contains("not supported yet") && e.contains("#763"), "3 sides: {e}"); + // A loop whose sides do not even meet is refused earlier and for its own reason. + let broken = square_loop(n); + let mut moved = broken[1].frames.clone(); + moved[0] = Frame { p: Vec3::new(30.0, 0.0, 0.0), ..moved[0] }; + let broken = vec![broken[0].clone(), Boundary { frames: moved, order: Continuity::G2 }, broken[2].clone()]; + let e = boundary_patch(&broken, 0.0, n).unwrap_err().to_string(); + assert!(e.contains("run on into one another"), "{e}"); + // The stations and the crown. + let short = vec![Boundary { frames: a[..n - 1].to_vec(), order: Continuity::G2 }, two[1].clone()]; + assert!(boundary_patch(&short, 0.0, n).is_err(), "a boundary with the wrong number of stations"); + assert!(boundary_patch(&two, 0.0, n - 1).is_err()); + assert!(boundary_patch(&two, 0.0, 1).is_err()); + for crown in [-1.5, 3.5, f64::NAN, f64::INFINITY] { + assert!(boundary_patch(&two, crown, n).is_err(), "crown {crown}"); + } + // A station that is not finite, and a station with no leave direction. + for field in 0..4 { + let mut bad = two.clone(); + let mut frames = bad[0].frames.clone(); + frames[3] = match field { + 0 => Frame { p: Vec3::new(f64::NAN, 0.0, 0.0), ..frames[3] }, + 1 => Frame { leave: Vec3::new(f64::NAN, 0.0, 0.0), ..frames[3] }, + 2 => Frame { bend: Vec3::new(f64::INFINITY, 0.0, 0.0), ..frames[3] }, + _ => Frame { bend_change: Vec3::new(f64::NAN, 0.0, 0.0), ..frames[3] }, + }; + if let Some(b) = bad.first_mut() { + b.frames = frames; + } + assert!(boundary_patch(&bad, 0.0, n).is_err(), "a station that is not finite: field {field}"); + } + let mut flat = two.clone(); + if let Some(b) = flat.first_mut() { + b.frames = vec![Frame { p: Vec3::new(0.0, 1.0, 0.0), leave: Vec3::ZERO, bend: Vec3::ZERO, bend_change: Vec3::ZERO }; n]; + } + assert!(boundary_patch(&flat, 0.0, n).is_err(), "a station with no leave direction"); + let point = vec![ + Boundary { + frames: vec![Frame { p: Vec3::new(1.0, 1.0, 1.0), leave: Vec3::X, bend: Vec3::ZERO, bend_change: Vec3::ZERO }; n], + order: Continuity::G1, + }, + Boundary { + frames: vec![Frame { p: Vec3::new(1.0, 1.0, 1.0), leave: Vec3::X, bend: Vec3::ZERO, bend_change: Vec3::ZERO }; n], + order: Continuity::G1, + }, + ]; + assert!(boundary_patch(&point, 0.0, n).is_err(), "a boundary with no length"); +} diff --git a/crates/kernel/src/fair.rs b/crates/kernel/src/fair.rs new file mode 100644 index 000000000..d8b4a0bbc --- /dev/null +++ b/crates/kernel/src/fair.rs @@ -0,0 +1,1538 @@ +//! Fairing the control points of a B-spline curve or surface: moving the interior control +//! vertices to the least-bending shape while the ends, or the boundary rows, stay exactly where +//! the design put them. +//! +//! The fairness energy is the thin-plate (curvature-variation) energy of the *geometry* the +//! control net describes, in the net's own parameter directions: +//! +//! - a curve: `E = ∫‖C″(t)‖² dt`, +//! - a surface: `E = ∫∫ ‖S_uu‖² + 2‖S_uv‖² + ‖S_vv‖² du dv`. +//! +//! A plane has energy zero and anything else pays for how much it bends, which is what a +//! designer means by "fair". Both energies are quadratic in the control points, `E(P) = Pᵀ·G·P`, +//! with `G` the Gram matrix of the basis functions' derivatives (`Gᵢⱼ = ∫Nᵢ″Nⱼ″ dt`, and the +//! tensor products of the one-direction Gram matrices for a surface). Each one-direction Gram is +//! integrated span by span with four-point Gauss–Legendre, exact to degree 7 — a cubic's second +//! derivative products are quadratic, so the cubic curves and bicubic faces fairing meets in +//! practice are integrated exactly. +//! +//! One fairing step is then a constrained least-squares solve: hold the boundary control points, +//! take the exact minimiser of `E` over the interior (for a quadratic that is one Newton step, +//! `G_ff·d = −(G·P)_f`), and apply a fraction `strength` of it, so `strength = 1` is the full +//! solution and a smaller value walks towards it. With the exact step the energy falls by +//! `q·s·(1 − s)` for `q ≥ 0`, so a run at any strength decreases it strictly until it converges. +//! `G_ff` does not change as the control points move, so it is factorised once, by banded +//! Cholesky, and every further step is a matrix–vector product and a triangular solve. +//! +//! Two guarantees are built in rather than checked afterwards: +//! +//! - **The boundary never moves.** The result starts as a copy of the input and only interior +//! entries are written, so a held control point is bit-identical to the one the design gave. +//! - **The geometry cannot jump.** A B-spline lies in the convex hull of its control points +//! (NURBS Book §3.1; with the weights unchanged the rational basis functions are still +//! non-negative and sum to one), so the geometry moves at most as far as the farthest control +//! point. Every step is clamped so that no control point leaves the ball of radius +//! `tolerance` about where it started: the faired curve or surface is then within `tolerance` +//! of the input at the same parameters, by a bound rather than by measurement. A step that +//! would not lower the energy is halved and, if it still would not, the run stops — it never +//! loops for ever and never moves the design further than the caller allowed. +//! +//! Everything is checked before it is used: degrees, knot vectors and counts must be consistent, +//! the control points finite, `strength ∈ (0, 1]`, `iterations` in `1…`[`MAX_FAIR_ITERATIONS`] and +//! `tolerance > 0`. A singular system — fewer than two interior control points, or an interior +//! 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 truck_modeling as mt; + +use crate::body::Body; +use crate::history::Change; +use crate::{KernelError, Result, guard}; + +/// Most steps one fairing run takes (see [`FairOptions::iterations`]). +pub const MAX_FAIR_ITERATIONS: usize = 1000; +/// Most control points one fairing run accepts (a 64 × 64 net): plenty for any face's control +/// net, and small enough that a step stays cheap whatever a design file contains. +pub const MAX_FAIR_POINTS: usize = 4096; +/// Most entries of the banded system (2²¹ doubles, 16 MB). +const MAX_FAIR_BAND: usize = 1 << 21; +/// The fairness energy of a curve, as a one-direction net: the `(order in u, order in v, weight)` +/// term list of `∫∫ (∂S)²`. +const CURVE_ENERGY: [(usize, usize, f64); 1] = [(2, 0, 1.0)]; +/// The thin-plate energy of a surface: `‖S_uu‖² + 2‖S_uv‖² + ‖S_vv‖²` — the classic +/// curvature-variation energy, zero on a plane and the same if u and v are swapped. +const SURFACE_ENERGY: [(usize, usize, f64); 3] = [(2, 0, 1.0), (1, 1, 2.0), (0, 2, 1.0)]; +/// Four-point Gauss–Legendre nodes and weights on `[−1, 1]` (exact to degree 7). +const GAUSS4: [(f64, f64); 4] = [ + (-0.861_136_311_594_052_6, 0.347_854_845_137_453_8), + (-0.339_981_043_584_856_3, 0.652_145_154_862_546_2), + (0.339_981_043_584_856_3, 0.652_145_154_862_546_2), + (0.861_136_311_594_052_6, 0.347_854_845_137_453_8), +]; +/// The second direction of a curve seen as a control net: one basis function of degree 0 over +/// `[0, 1]`, whose Gram entry is exactly `∫1 dt = 1`, so the net's energy is the curve's own +/// energy unchanged. +const TRIVIAL_KNOTS: [f64; 2] = [0.0, 1.0]; +/// How often a step is halved before the run calls the point converged. +const MAX_HALVINGS: u32 = 40; +/// A step smaller than this fraction of the full Newton step is not worth taking. +const MIN_STEP: f64 = 1e-12; +/// Steps are clamped this far inside the tolerance, so rounding cannot push a control point +/// past it. +const TOLERANCE_SLACK: f64 = 1.0 - 1e-12; + +/// How a fairing run is asked to behave. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct FairOptions { + /// The fraction of each energy step to apply, `0 < strength ≤ 1`: `1` is the full least + /// squares solution (the exact minimiser of the energy at the held boundary), a smaller + /// value takes that fraction of the way there. The energy falls at every step either way. + pub strength: f64, + /// How many steps at most, one to [`MAX_FAIR_ITERATIONS`]. + pub iterations: usize, + /// Hold the layer of control points next to the boundary as well as the boundary itself (two + /// layers held at each end). For a clamped knot vector the boundary row fixes the position + /// along the edge and the row next to it fixes the derivative across the edge, so with this + /// set the boundary keeps the position and the tangent the design gave it. + pub keep_edges: bool, + /// The farthest a control point may move from where the design put it, in mm. The geometry + /// then stays within this distance of the input at the same parameters (see the module + /// docs), so a fairing run can never make a design jump. + pub tolerance: f64, +} + +impl FairOptions { + /// Checked options for one fairing run: an error, never a panic, for a strength outside + /// `(0, 1]`, zero iterations, more than [`MAX_FAIR_ITERATIONS`] of them, or a tolerance that + /// is not a positive finite number. + pub fn new(strength: f64, iterations: usize, keep_edges: bool, tolerance: f64) -> Result { + FairOptions { strength, iterations, keep_edges, tolerance }.checked() + } + + /// The same checks as [`FairOptions::new`], for options built field by field. + pub fn checked(self) -> Result { + if !(self.strength.is_finite() && self.strength > 0.0 && self.strength <= 1.0) { + return Err(KernelError::Invalid(format!("the fairing strength {} must be greater than 0 and at most 1", self.strength))); + } + if self.iterations == 0 || self.iterations > MAX_FAIR_ITERATIONS { + return Err(KernelError::Invalid(format!("{} fairing iterations (1 to {MAX_FAIR_ITERATIONS})", self.iterations))); + } + if !(self.tolerance.is_finite() && self.tolerance > 0.0) { + return Err(KernelError::Invalid(format!("the fairing tolerance {} must be a positive number of mm", self.tolerance))); + } + Ok(self) + } +} + +impl Default for FairOptions { + /// One full step with the boundary held, at most 1 mm of movement: the defaults a command can + /// start from before a user picks their own. + fn default() -> Self { + FairOptions { strength: 1.0, iterations: 1, keep_edges: false, tolerance: 1.0 } + } +} + +/// What a fairing run did: the energy before and after, how many steps were applied, how far the +/// control points moved and the energy after every applied step. The energy is a sum of squares, +/// so where rounding leaves it a hair below zero the true value is zero: it is reported as zero. +#[derive(Clone, Debug, PartialEq)] +pub struct FairReport { + /// The fairness energy of the input, in the parameter units of the net's own knots. + pub energy_before: f64, + /// The fairness energy of the result: never more than `energy_before`, and equal to it only + /// when no step could lower it. + pub energy_after: f64, + /// How many steps were applied (at most the requested `iterations`). + pub steps: usize, + /// The farthest any control point moved from where the design put it, in mm. It bounds how + /// far the geometry moved from the input (see the module docs) and never exceeds the + /// requested tolerance. + pub movement: f64, + /// The energy after each applied step, the last equal to `energy_after`: it never rises, and + /// falls strictly at every step until the run reaches the rounding of its own arithmetic. + pub energy_trace: Vec, +} + +/// A faired B-spline curve: the input's degree and knots, the moved control points and the run's +/// report. +#[derive(Clone, Debug, PartialEq)] +pub struct FairCurve { + pub degree: usize, + pub knots: Vec, + /// The faired control points; the ends (and, with `keep_edges`, the points next to them) are + /// bit-identical to the input. + pub ctrl: Vec<[f64; N]>, + 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. +#[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]>, + pub report: FairReport, +} + +/// A geom spline error as the kernel's. +fn spline_error(what: &str, e: SplineError) -> KernelError { + match e { + SplineError::TooLarge(m) => KernelError::TooLarge(format!("{what}: {m}")), + other => KernelError::Invalid(format!("{what}: {other}")), + } +} + +/// The dot product of two control points' coordinate vectors. +fn dot(a: &[f64; N], b: &[f64; N]) -> f64 { + a.iter().zip(b).map(|(x, y)| x * y).sum() +} + +/// The distance between two control points. +fn dist(a: &[f64; N], b: &[f64; N]) -> f64 { + let d: [f64; N] = std::array::from_fn(|c| a[c] - b[c]); + dot(&d, &d).sqrt() +} + +/// The Gram matrices of one parameter direction, stored banded: entry `r` is +/// `∫ Nᵢ^{(r)}(t)·Nₖ^{(r)}(t) dt` over the direction's domain, and since a basis function +/// overlaps only its `degree` neighbours an entry is non-zero only for `|i − k| ≤ degree`, so +/// the whole thing is `count·(degree + 1)` numbers per order. +struct Gram { + count: usize, + bw: usize, + g: [Vec; 3], +} + +impl Gram { + /// The Gram matrices of `count` basis functions of `degree` over `knots`, for orders 0, 1 and + /// 2 — the derivatives a thin-plate energy is built from. + fn new(degree: usize, knots: &[f64], count: usize) -> Result { + let bw = degree; + let mut g: [Vec; 3] = std::array::from_fn(|_| vec![0.0; count * (bw + 1)]); + // On the span `[knots[s], knots[s + 1])` only the basis functions `i ∈ [s − degree, s]` + // are non-zero. The quadrature nodes lie strictly inside the span, so either one-sided + // limit gives the same value there. + let mut ders = [[0.0f64; 3]; MAX_SPLINE_DEGREE + 1]; + for s in degree..count { + let (Some(&a), Some(&b)) = (knots.get(s), knots.get(s + 1)) else { continue }; + if !(b > a) { + continue; + } + for &(x, w) in GAUSS4.iter() { + let t = 0.5 * (a + b) + 0.5 * (b - a) * x; + let first = s - degree; + let mut live = 0usize; + for i in first..=s { + let Some(local) = knots.get(i..=i + degree + 1) else { break }; + let d = local_basis(local, t, Side::Right, 2); + if let Some(slot) = ders.get_mut(live) { + for (o, v) in slot.iter_mut().zip(d.iter()) { + *o = *v; + } + } + live += 1; + } + let weight = 0.5 * (b - a) * w; + let value = |rel: usize, r: usize| ders.get(rel).and_then(|d| d.get(r)).copied().unwrap_or(0.0); + // The upper triangle only — the band holds one copy of a symmetric entry — and at + // the basis functions' own indices, not their places in this span. + for i in 0..live { + for k in i..live { + let (row, off) = (first + i, k - i); + for (r, gg) in g.iter_mut().enumerate() { + if let Some(slot) = gg.get_mut(row * (bw + 1) + off) { + *slot += weight * value(i, r) * value(k, r); + } + } + } + } + } + } + if g.iter().flatten().any(|v| !v.is_finite()) { + return Err(KernelError::Invalid("the fairness energy of this net is not a finite number".into())); + } + Ok(Gram { count, bw, g }) + } + + /// `∫ Nᵢ^{(r)} Nₖ^{(r)} dt`, zero outside the band or off the end of the basis. + fn at(&self, r: usize, i: usize, k: usize) -> f64 { + let Some(m) = self.g.get(r) else { return 0.0 }; + let (row, off) = if i <= k { (i, k - i) } else { (k, i - k) }; + if off > self.bw || row >= self.count { + return 0.0; + } + m.get(row * (self.bw + 1) + off).copied().unwrap_or(0.0) + } +} + +/// 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 { + degree: [usize; 2], + count: [usize; 2], + /// The number of control points, `count[0] · count[1]`. + total: usize, + gram: [Gram; 2], + terms: &'static [(usize, usize, f64)], +} + +impl Net { + /// 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 { + 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 { + return Err(KernelError::TooLarge(format!("fairing a spline of degree {p} (at most {MAX_SPLINE_DEGREE})"))); + } + if c <= p { + return Err(KernelError::Invalid(format!("{c} control points is too few across one direction of a spline of degree {p}"))); + } + if kn.len() != c + p + 1 { + return Err(KernelError::Invalid(format!( + "{} knots across one direction, expected {} for {c} control points of degree {p}", + kn.len(), + c + p + 1 + ))); + } + check_knots(kn).map_err(|e| spline_error("fairing", e))?; + let (lo, hi) = (kn.get(p).copied().unwrap_or(f64::NAN), kn.get(c).copied().unwrap_or(f64::NAN)); + if !(lo < hi) { + return Err(KernelError::Invalid("the fairing's parameter range is empty".into())); + } + } + if terms.iter().any(|&(ru, rv, w)| ru > degree[0] || rv > degree[1] || !(w.is_finite() && w >= 0.0)) { + 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 }) + } + + /// 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 + } + + /// 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; + let (pu, pv) = (self.degree[0], self.degree[1]); + let mut energy = 0.0; + for j in 0..cv { + for i in 0..cu { + let mut acc = [0.0f64; N]; + for &(ru, rv, w) in self.terms { + for l in j.saturating_sub(pv)..=(j + pv).min(cv - 1) { + for k in i.saturating_sub(pu)..=(i + pu).min(cu - 1) { + let a = w * self.gram[0].at(ru, i, k) * self.gram[1].at(rv, j, l); + if a == 0.0 { + continue; + } + if let Some(p) = ctrl.get(self.index(k, l)) { + for (x, v) in acc.iter_mut().zip(p) { + *x += a * v; + } + } + } + } + } + let at = self.index(i, j); + if let Some(c) = ctrl.get(at) { + energy += dot(c, &acc); + } + if let Some(g) = grad.get_mut(at) { + *g = acc; + } + } + } + energy + } + + /// The energy matrix `G` over the interior control points, banded and already factorised (the + /// matrix does not change as the control points move, so one factorisation serves every + /// 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 (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)?; + for (r, &at) in interior.points.iter().enumerate() { + let (i, j) = (at % cu, at / cu); + for &(ru, rv, w) in self.terms { + for l in j.saturating_sub(pv)..=(j + pv).min(cv - 1) { + for k in i.saturating_sub(pu)..=(i + pu).min(cu - 1) { + let Some(s) = interior.slot.get(self.index(k, l)).copied().flatten() else { continue }; + band.add(r, s, w * self.gram[0].at(ru, i, k) * self.gram[1].at(rv, j, l)); + } + } + } + } + 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))); + } + 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); + if !energy_before.is_finite() { + return Err(KernelError::Invalid("the fairness energy of this net is not a finite number".into())); + } + // The energy is a sum of squares, so where rounding leaves it a hair below zero the true + // value is zero: report it that way rather than as a negative number. + let energy_before = energy_before.max(0.0); + // How big the net itself is, for telling a fairing step from rounding (see below). + let size = interior.size(ctrl); + let mut step = vec![[0.0; N]; interior.points.len()]; + 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); + if !e_now.is_finite() { + break; + } + // The exact minimiser over the interior is the Newton step `G_ff·d = −(G·P)_f`; the + // system is per coordinate, all three sharing the one factorisation. + for c in 0..N { + for (slot, &at) in interior.points.iter().enumerate() { + b[slot] = -grad.get(at).and_then(|g| g.get(c)).copied().unwrap_or(0.0); + } + system.solve(&mut b)?; + for (slot, v) in b.iter().enumerate() { + if let Some(d) = step.get_mut(slot).and_then(|d| d.get_mut(c)) { + *d = *v; + } + } + } + if step.iter().flatten().all(|&x| x == 0.0) { + break; + } + // 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)); + if !(s > 0.0) { + break; + } + // A step this much shorter than the net's own size cannot be told from the rounding + // of the arithmetic that found it: the net is as fair as it gets. + let longest = step.iter().flatten().fold(0.0f64, |m, x| m.max(x.abs())); + if s * longest <= MIN_STEP * size { + break; + } + let mut taken = false; + for _ in 0..MAX_HALVINGS { + let candidate = interior.apply(¤t, &step, s); + let e = self.energy_gradient(&candidate, &mut grad); + if e < e_now { + current = candidate; + report.steps += 1; + report.energy_trace.push(e.max(0.0)); + taken = true; + break; + } + // The step did not lower the energy: halve it and try again, and when even a hair + // of a step will not, this is as fair as the net gets. + s *= 0.5; + if s <= MIN_STEP { + break; + } + } + if !taken { + break; + } + } + report.energy_after = report.energy_trace.last().copied().unwrap_or(energy_before); + report.movement = interior.movement(ctrl, ¤t); + Ok((current, report)) + } +} + +/// Which control points a fairing run may move, and where each sits in the banded system. +struct Interior { + /// The flattened index (u fastest) of interior point number `k`. + points: Vec, + /// The interior number of each flattened index, `None` where the point is held. + slot: Vec>, + /// How many control points across u (`cols`) and across v (`rows`) are interior. + cols: usize, + rows: usize, +} + +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; + 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]; + for j in j0..j1 { + for i in i0..i1 { + if let Some(s) = slot.get_mut(net.index(i, j)) { + *s = Some(points.len()); + } + points.push(net.index(i, j)); + } + } + if points.len() < 2 { + return Err(KernelError::Invalid(format!( + "fairing needs at least two interior control points; this {cu} × {cv} net has {}", + points.len() + ))); + } + Ok(Interior { points, slot, cols, rows }) + } + + /// `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(); + for (slot, &at) in self.points.iter().enumerate() { + let (Some(p), Some(v)) = (out.get_mut(at), d.get(slot)) else { continue }; + for (x, dx) in p.iter_mut().zip(v) { + *x += s * dx; + } + } + out + } + + /// How big the interior is: the farthest interior control point from the first one, in mm. + /// A fairing step far below this belongs to the rounding of the arithmetic, not the design. + fn size(&self, ctrl: &[[f64; N]]) -> f64 { + let Some(first) = self.points.first().and_then(|&at| ctrl.get(at)) else { return 0.0 }; + self.points.iter().fold(0.0f64, |m, &at| ctrl.get(at).map_or(m, |p| m.max(dist(first, p)))) + } + + /// The largest fraction `s ≤ 1` of the step `d` that keeps every interior control point + /// within `tolerance` of where the design put it (`input`). The movement is `‖Δ + s·d‖ ≤ tol` + /// per point — a quadratic in `s` opening upwards, with the accumulated movement + /// `Δ = current − input` already inside the ball, so the bound is its positive root. + fn limit(&self, input: &[[f64; N]], current: &[[f64; N]], d: &[[f64; N]], tolerance: f64) -> f64 { + let mut s = 1.0f64; + for (slot, &at) in self.points.iter().enumerate() { + let (Some(dv), Some(cv), Some(iv)) = (d.get(slot), current.get(at), input.get(at)) else { continue }; + let a = dot(dv, dv); + if a <= 0.0 { + continue; + } + let delta: [f64; N] = std::array::from_fn(|c| cv[c] - iv[c]); + let b = 2.0 * dot(&delta, dv); + let c = dot(&delta, &delta) - tolerance * tolerance; + let disc = b * b - 4.0 * a * c; + let root = if disc >= 0.0 { (-b + disc.sqrt()) / (2.0 * a) } else { 0.0 }; + // `f64::max` ignores a NaN, so a step whose arithmetic overflows stops the run + // instead of leaking a not-a-number into a control point. + s = s.min(root.max(0.0)); + } + (s * TOLERANCE_SLACK).clamp(0.0, 1.0) + } + + /// The farthest any interior control point moved from the design's own position, in mm. + fn movement(&self, input: &[[f64; N]], current: &[[f64; N]]) -> f64 { + self.points.iter().fold(0.0f64, |m, &at| match (input.get(at), current.get(at)) { + (Some(a), Some(b)) => m.max(dist(a, b)), + _ => m, + }) + } +} + +/// The control points of one direction a fairing run may move, as `[lo, hi)`. A direction of one +/// control point — a curve seen as a net one row deep — is all interior; otherwise `keep` layers +/// are held at each end: the boundary, and with `keep = 2` the layer next to it. +fn free_span(count: usize, keep: usize) -> Result<(usize, usize)> { + if count == 1 { + return Ok((0, 1)); + } + if count <= 2 * keep { + return Err(KernelError::Invalid(format!( + "fairing a net {count} control points across one direction and holding {keep} at each edge leaves nothing to move" + ))); + } + Ok((keep, count - keep)) +} + +/// A symmetric banded matrix in upper-triangular form: row `r` holds columns `r ..= r + bw`. +struct Band { + n: usize, + bw: usize, + /// The upper band, `n · (bw + 1)` numbers; the scaling by the largest diagonal is folded in + /// when the matrix is factorised. + a: Vec, + scale: f64, +} + +impl Band { + fn new(n: usize, bw: usize) -> Result { + let Some(len) = (bw + 1).checked_mul(n).filter(|&l| l <= MAX_FAIR_BAND) else { + return Err(KernelError::TooLarge(format!("a fairing system of {n} unknowns {bw} apart"))); + }; + Ok(Band { n, bw, a: vec![0.0; len], scale: 1.0 }) + } + + fn index(&self, r: usize, s: usize) -> Option { + let (r, s) = if r <= s { (r, s) } else { (s, r) }; + (s - r <= self.bw && s < self.n).then_some(r * (self.bw + 1) + (s - r)) + } + + fn get(&self, r: usize, s: usize) -> f64 { + self.index(r, s).and_then(|i| self.a.get(i)).copied().unwrap_or(0.0) + } + + fn set(&mut self, r: usize, s: usize, v: f64) { + if let Some(x) = self.index(r, s).and_then(|i| self.a.get_mut(i)) { + *x = v; + } + } + + /// Add `v` at `(r, s)`. Only `r ≤ s` is stored (the matrix is symmetric, so callers adding a + /// whole symmetric neighbourhood reach each stored entry once). + fn add(&mut self, r: usize, s: usize, v: f64) { + if r <= s + && let Some(x) = self.index(r, s).and_then(|i| self.a.get_mut(i)) + { + *x += v; + } + } + + /// `A = Uᵀ·U` in place, the entries scaled by the largest diagonal first (the scaling does + /// not change the solution, only the size of the pivots, so a net whose knots span microns or + /// kilometres factorises just as well). An error, never a panic, when a pivot is not + /// positive: the system is singular there and the geometry must not move. + fn factorised(mut self) -> Result { + let (n, bw) = (self.n, self.bw); + let scale = (0..n).fold(0.0f64, |m, r| m.max(self.get(r, r).abs())); + if !(scale > 0.0) || !scale.is_finite() { + return Err(KernelError::Invalid("the fairness energy does not depend on any interior control point: nothing to fair".into())); + } + self.scale = scale; + for v in self.a.iter_mut() { + *v /= scale; + } + for r in 0..n { + let mut d = self.get(r, r); + for k in r.saturating_sub(bw)..r { + let u = self.get(k, r); + d -= u * u; + } + if !(d > 0.0) { + return Err(KernelError::Invalid( + "the fairing equations are singular (an interior control point that does not move the geometry)".into(), + )); + } + let d = d.sqrt(); + self.set(r, r, d); + for s in r + 1..(r + bw + 1).min(n) { + let mut v = self.get(r, s); + for k in s.saturating_sub(bw)..r { + v -= self.get(k, r) * self.get(k, s); + } + self.set(r, s, v / d); + } + } + Ok(self) + } + + /// Solve `A·x = b` with the stored factorisation, in place. + fn solve(&self, b: &mut [f64]) -> Result<()> { + let (n, bw) = (self.n, self.bw); + if b.len() != n { + return Err(KernelError::Invalid(format!("{} fairing unknowns for a system of {n}", b.len()))); + } + for x in b.iter_mut() { + *x /= self.scale; + } + // Uᵀ·y = b, then U·x = y. + for r in 0..n { + let mut v = b.get(r).copied().unwrap_or(0.0); + for k in r.saturating_sub(bw)..r { + v -= self.get(k, r) * b.get(k).copied().unwrap_or(0.0); + } + if let Some(x) = b.get_mut(r) { + *x = v / self.get(r, r); + } + } + for r in (0..n).rev() { + let mut v = b.get(r).copied().unwrap_or(0.0); + for s in r + 1..(r + bw + 1).min(n) { + v -= self.get(r, s) * b.get(s).copied().unwrap_or(0.0); + } + if let Some(x) = b.get_mut(r) { + *x = v / self.get(r, r); + } + } + if b.iter().any(|x| !x.is_finite()) { + return Err(KernelError::Invalid("the fairing step is not a finite number".into())); + } + Ok(()) + } +} + +/// Fair a B-spline curve's control points of any dimension: hold control points `0` and `n − 1` +/// and (with [`FairOptions::keep_edges`]) those next to them, and move the rest to lower the +/// bending energy `∫‖C″‖² dt` in the curve's own parameter (see the module docs). `N` is 3 for a +/// 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 }) +} + +/// 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 +/// [`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> { + 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 }) +} + +/// Fair a truck B-spline curve's control points: [`fair_curve`] on its three-dimensional points, +/// rebuilt as a B-spline of the same knots. Guarded here itself, like every call into truck, so a +/// panic inside comes back as an error and the design is left alone. +pub fn fair_bspline_curve(curve: &mt::BSplineCurve, opts: &FairOptions) -> Result<(mt::BSplineCurve, FairReport)> { + guard("fair a B-spline curve", || { + let ctrl: Vec<[f64; 3]> = curve.control_points().iter().map(|p| [p.x, p.y, p.z]).collect(); + let faired = fair_curve(curve.degree(), curve.knot_vec(), &ctrl, opts)?; + let points: Vec = faired.ctrl.iter().map(|c| mt::Point3::new(c[0], c[1], c[2])).collect(); + let curve = mt::BSplineCurve::try_new(mt::KnotVec::from(faired.knots), points).map_err(|e| KernelError::Failed(format!("fair: {e}")))?; + Ok((curve, faired.report)) + }) +} + +/// Fair a truck rational curve's control points: its Cartesian control points are faired like any +/// other curve and its weights are kept, so the result is the same rational curve with moved +/// control points. The convex-hull bound that keeps the geometry within the tolerance still +/// holds, because with the weights unchanged the rational basis functions are non-negative and +/// sum to one. Guarded like [`fair_bspline_curve`]. +pub fn fair_nurbs_curve(curve: &mt::NurbsCurve, opts: &FairOptions) -> Result<(mt::NurbsCurve, FairReport)> { + guard("fair a NURBS curve", || { + let count = curve.control_points().len(); + let mut ctrl = Vec::with_capacity(count); + let mut weights = Vec::with_capacity(count); + for h in curve.control_points() { + 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 faired = fair_curve(curve.degree(), curve.knot_vec(), &ctrl, opts)?; + let points: Vec = faired.ctrl.iter().zip(&weights).map(|(c, w)| mt::Vector4::new(c[0] * w, c[1] * w, c[2] * w, *w)).collect(); + let bsp = mt::BSplineCurve::try_new(mt::KnotVec::from(faired.knots), points).map_err(|e| KernelError::Failed(format!("fair: {e}")))?; + Ok((mt::NurbsCurve::new(bsp), faired.report)) + }) +} + +/// Fair a truck B-spline surface's control net: [`fair_net`] on its points, rebuilt as a B-spline +/// 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 (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 surface = mt::BSplineSurface::try_new((ku.clone(), kv.clone()), net).map_err(|e| KernelError::Failed(format!("fair: {e}")))?; + Ok((surface, faired.report)) + }) +} + +/// 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 [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))?; + Ok((out, faired.report)) +} + +/// Fair a truck rational surface's control net, like [`fair_surface`]: the Cartesian control +/// points are faired, the weights kept, and the result is a NURBS surface of the same knots. +/// Guarded like [`fair_bspline_curve`]. +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 (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 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)) + }) +} + +/// Fair the B-spline faces at `faces` (indices in `body`'s face order) of `body`: each face's +/// interior control vertices move to flatten the thin-plate energy of the face while its boundary +/// rows stay put, so the face keeps meeting its neighbours as it did. +/// +/// Every picked face keeps the very wires, edges and vertices it had and the way it pointed: only +/// the surface between them changes, so the body is as closed (or as open) as it was, holes and +/// all. A face that is not a B-spline (a plane, cylinder, cone, sphere, torus or swept face) has no +/// control points to fair and is refused by name; a mesh body has no faces to fair at all. +/// +/// The report is over the picked faces together: the energies summed, the largest movement of any +/// control point, and the energy trace as the sum at each step (a face that stops early keeps its +/// last energy for the steps the others still take). +pub fn fair_faces(body: &Body, faces: &[usize], opts: &FairOptions) -> Result<(Body, FairReport)> { + let opts = opts.checked()?; + body.require_brep("fair")?; + let all: Vec = body.solid.face_iter().cloned().collect(); + if all.is_empty() { + return Err(KernelError::Invalid("the body has no faces".into())); + } + let mut picked: Vec = Vec::new(); + for &i in faces { + if i >= all.len() { + return Err(KernelError::Invalid(format!("no face {i}: the body has {}", all.len()))); + } + if !picked.contains(&i) { + picked.push(i); + } + } + if picked.is_empty() { + return Err(KernelError::Invalid("pick the faces to fair".into())); + } + guard("fair faces", || { + let mut faired = all.clone(); + let mut reports: Vec = Vec::with_capacity(picked.len()); + for &i in &picked { + let Some(face) = all.get(i) else { continue }; + let (surface, report) = match face.surface() { + mt::Surface::BSplineSurface(s) => { + let (faired, report) = fair_bspline_surface(&s, &opts)?; + (mt::Surface::BSplineSurface(faired), report) + } + mt::Surface::NurbsSurface(s) => { + let (faired, report) = fair_nurbs_surface(&s, &opts)?; + (mt::Surface::NurbsSurface(faired), report) + } + _ => { + return Err(KernelError::Invalid(format!( + "face {i} is not a B-spline face: a plane, cylinder, cone, sphere, torus or swept face has no control points to fair" + ))); + } + }; + // The same face as before, wires and all, with the faired surface between them. + let mut nf = mt::Face::new_unchecked(face.absolute_boundaries().clone(), surface); + if !face.orientation() { + nf.invert(); + } + if let Some(slot) = faired.get_mut(i) { + *slot = nf; + } + reports.push(report); + } + let report = FairReport { + energy_before: reports.iter().map(|r| r.energy_before).sum(), + energy_after: reports.iter().map(|r| r.energy_after).sum(), + steps: reports.iter().map(|r| r.steps).max().unwrap_or(0), + movement: reports.iter().fold(0.0f64, |m, r| m.max(r.movement)), + energy_trace: { + let longest = reports.iter().map(|r| r.energy_trace.len()).max().unwrap_or(0); + (0..longest).map(|k| reports.iter().map(|r| r.energy_trace.get(k).copied().unwrap_or(r.energy_after)).sum()).collect() + }, + }; + // The body shell for shell, in its own face order: a body with holes keeps them. + let mut shells: Vec = Vec::with_capacity(body.solid.boundaries().len()); + let mut index = 0usize; + for shell in body.solid.boundaries() { + let mut shell_faces = Vec::with_capacity(shell.face_iter().count()); + for f in shell.face_iter() { + let i = index; + index += 1; + shell_faces.push(faired.get(i).cloned().unwrap_or_else(|| f.clone())); + } + shells.push(mt::Shell::from(shell_faces)); + } + // The topology is the body's own, face for face, so the solid is built as it (the shells + // are as closed, or as open, as they were) and only the shape is measured anew. + let mut result = body.clone(); + result.solid = std::sync::Arc::new(mt::Solid::new_unchecked(shells)); + result.size = 0.0; + result.volume = Some(std::sync::Arc::new(std::sync::Mutex::new(None))); + result.coarse_missing = None; + result.history = None; + 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())?; + Ok((result, report)) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use mt::ParametricCurve; + + /// A clamped uniform knot vector over `[0, spans]` of degree `degree`: `spans + degree` + /// control points. + fn clamped(spans: usize, degree: usize) -> Vec { + let mut k = vec![0.0; degree + 1]; + k.extend((1..spans).map(|i| i as f64)); + k.extend(std::iter::repeat_n(spans as f64, degree + 1)); + k + } + + /// The knot average `(kᵢ₊₁ + … + kᵢ₊ₚ)/p` of control point `i`: `Σ Nᵢ(t)·ξᵢ = t` (NURBS Book + /// eq. 3.4), so control points at `a + b·ξᵢ` describe the affine curve `a + b·t` exactly. + fn average(knots: &[f64], degree: usize, i: usize) -> f64 { + (1..=degree).map(|r| knots.get(i + r).copied().unwrap_or(0.0)).sum::() / degree as f64 + } + + /// The control points of the affine curve `ξ ↦ a + b·ξ` at the knot averages of `knots`: a + /// curve of exactly zero bending energy. + fn affine_curve(knots: &[f64], degree: usize, a: [f64; 3], b: [f64; 3]) -> Vec<[f64; 3]> { + (0..knots.len() - degree - 1).map(|i| std::array::from_fn(|c| a[c] + b[c] * average(knots, degree, i))).collect() + } + + /// The control net (u fastest) of the plane `(ξ, η) ↦ a + b·ξ + c·η` at the knot averages of + /// `ku` and `kv`: a net of exactly zero thin-plate energy. + fn planar_net(ku: &[f64], kv: &[f64], degree: [usize; 2], a: [f64; 3], b: [f64; 3], c: [f64; 3]) -> Vec<[f64; 3]> { + let (cu, cv) = (ku.len() - degree[0] - 1, kv.len() - degree[1] - 1); + let mut net = Vec::with_capacity(cu * cv); + for j in 0..cv { + for i in 0..cu { + let (xi, eta) = (average(ku, degree[0], i), average(kv, degree[1], j)); + net.push(std::array::from_fn(|d| a[d] + b[d] * xi + c[d] * eta)); + } + } + net + } + + /// The point of the curve `(degree, knots, ctrl)` at `t`, through the same basis geom uses: a + /// basis function `i` owns the `degree + 2` knots `knots[i..=i + degree + 1]`. + fn curve_at(degree: usize, knots: &[f64], ctrl: &[[f64; N]], t: f64) -> [f64; N] { + let n = ctrl.len(); + let side = if t >= knots.get(n).copied().unwrap_or(f64::INFINITY) { Side::Left } else { Side::Right }; + let mut out = [0.0; N]; + for (i, c) in ctrl.iter().enumerate() { + let b = knots.get(i..=i + degree + 1).and_then(|l| local_basis(l, t, side, 0).first().copied()).unwrap_or(0.0); + for (o, x) in out.iter_mut().zip(c) { + *o += b * x; + } + } + out + } + + /// The greatest distance between two points of space, in mm. + fn apart(a: mt::Point3, b: mt::Point3) -> f64 { + ((a.x - b.x).powi(2) + (a.y - b.y).powi(2) + (a.z - b.z).powi(2)).sqrt() + } + + /// A geom point as a coordinate triple. + fn triple(p: Vec3) -> [f64; 3] { + [p.x, p.y, p.z] + } + + #[test] + fn a_perturbed_curve_is_faired_back_to_its_smooth_shape_and_its_ends_stay_put() { + // A cubic curve whose control points sit at the knot averages of an affine curve: zero + // bending energy, so a fairing run must return to the same control polygon. The knots are + // deliberately uneven, so a fairing that ignored the curve's own parameter would not. + let knots = [0.0, 0.0, 0.0, 0.0, 1.0, 3.0, 5.0, 9.0, 9.0, 9.0, 9.0]; + let (a, b) = ([-20.0, 5.0, 1.5], [4.0, -2.5, 3.0]); + let smooth = affine_curve(&knots, 3, a, b); + let mut rough = smooth.clone(); + rough[2] = [rough[2][0] + 1.5, rough[2][1] - 2.0, rough[2][2] + 3.0]; + rough[3][2] += 2.5; + rough[4][0] -= 1.25; + rough[5][1] += 1.75; + let far = (0..smooth.len()).map(|i| dist(&rough[i], &smooth[i])).fold(0.0, f64::max); + + let opts = FairOptions::new(1.0, 8, false, 100.0).unwrap(); + let faired = fair_curve(3, &knots, &rough, &opts).unwrap(); + // The ends did not move at all, bit for bit. + assert_eq!(faired.ctrl[0], rough[0]); + assert_eq!(faired.ctrl[6], rough[6]); + // Every interior control point came back to the smooth shape. + let near = (1..6).map(|i| dist(&faired.ctrl[i], &smooth[i])).fold(0.0, f64::max); + eprintln!( + "curve: perturbation {far} mm, faired to {near:e} mm, energy {:e} → {:e} in {} steps, movement {:e} mm", + faired.report.energy_before, faired.report.energy_after, faired.report.steps, faired.report.movement + ); + assert!(near < 1e-6 && near < far * 1e-6, "faired to {near:e}, was {far} mm out"); + // The energy is a real number before, fell to nothing, and never rose on the way. + assert!(faired.report.energy_before > 1e-3, "{:e}", faired.report.energy_before); + assert!(faired.report.energy_after >= 0.0 && faired.report.energy_after < 1e-9 * faired.report.energy_before); + assert!(faired.report.steps >= 1 && faired.report.energy_trace.len() == faired.report.steps); + assert_eq!(faired.report.energy_trace.last().copied(), Some(faired.report.energy_after)); + assert!(faired.report.energy_trace.windows(2).all(|w| w[1] < w[0]), "{:?}", faired.report.energy_trace); + // A step never moves a control point further than the tolerance, and here it moved the + // whole way back to the smooth shape. + assert!(faired.report.movement <= 100.0 && (faired.report.movement - far).abs() < 1e-9, "{:e}", faired.report.movement); + // The faired curve is the affine line it was meant to be. + let mut off = 0.0f64; + for k in 0..=32 { + let t = 9.0 * f64::from(k) / 32.0; + let want: [f64; 3] = std::array::from_fn(|c| a[c] + b[c] * t); + off = off.max(dist(&curve_at(3, &knots, &faired.ctrl, t), &want)); + } + eprintln!("curve: the faired curve is {off:e} mm off the affine line it describes"); + assert!(off < 1e-6, "{off:e}"); + } + + #[test] + fn a_half_strength_run_walks_to_the_same_shape_over_its_iterations() { + // The same perturbation, walked a half step at a time: the energy must fall at every step + // (monotone, strictly) and still arrive at the smooth shape. + let knots = [0.0, 0.0, 0.0, 0.0, 1.0, 3.0, 5.0, 9.0, 9.0, 9.0, 9.0]; + let smooth = affine_curve(&knots, 3, [-20.0, 5.0, 1.5], [4.0, -2.5, 3.0]); + let mut rough = smooth.clone(); + rough[2][2] += 4.0; + rough[3][0] += 2.0; + let opts = FairOptions::new(0.5, 40, false, 100.0).unwrap(); + let faired = fair_curve(3, &knots, &rough, &opts).unwrap(); + eprintln!("half strength: energy {:e} → {:e} in {} steps", faired.report.energy_before, faired.report.energy_after, faired.report.steps); + assert!(faired.report.energy_trace.len() > 4, "one step is not a walk"); + assert!(faired.report.energy_trace.windows(2).all(|w| w[1] < w[0]), "the energy must fall at every step"); + assert!(faired.report.energy_after < 1e-9 * faired.report.energy_before); + assert_eq!(faired.ctrl[0], rough[0]); + assert_eq!(faired.ctrl[6], rough[6]); + assert!(dist(&faired.ctrl[3], &smooth[3]) < 1e-6); + } + + #[test] + fn the_faired_curve_stays_within_the_tolerance_of_the_design() { + // A heavily perturbed curve with a 0.75 mm tolerance: the design may be smoothed, but + // never by more than the caller allowed, and the bound is on the geometry itself. + let knots = clamped(3, 3); + let smooth = affine_curve(&knots, 3, [0.0, 0.0, 0.0], [30.0, 8.0, 0.0]); + let mut rough = smooth.clone(); + for (i, d) in [(1, [1.0, -2.0, 4.0]), (2, [-3.0, 2.0, -6.0]), (3, [2.0, -1.0, 5.0]), (4, [-2.0, 3.0, -4.0])] { + for c in 0..3 { + rough[i][c] += d[c]; + } + } + let tolerance = 0.75; + let opts = FairOptions::new(1.0, 12, false, tolerance).unwrap(); + let faired = fair_curve(3, &knots, &rough, &opts).unwrap(); + let mut off = 0.0f64; + for k in 0..=64 { + let t = 3.0 * f64::from(k) / 64.0; + off = off.max(dist(&curve_at(3, &knots, &faired.ctrl, t), &curve_at(3, &knots, &rough, t))); + } + eprintln!( + "tolerance {tolerance}: the curve moved {off:e} mm at worst ({:e} mm of control points), energy {:e} → {:e}", + faired.report.movement, faired.report.energy_before, faired.report.energy_after + ); + assert!(faired.report.movement <= tolerance, "{:e}", faired.report.movement); + assert!(off <= tolerance * (1.0 + 1e-9), "{off:e} over {tolerance}"); + assert!(faired.report.energy_after < faired.report.energy_before); + // The tolerance did not stop the run from heading for the smooth shape. + let before = (0..6).map(|i| dist(&rough[i], &smooth[i])).fold(0.0, f64::max); + let after = (0..6).map(|i| dist(&faired.ctrl[i], &smooth[i])).fold(0.0, f64::max); + assert!(after < before, "{after} vs {before}"); + assert_eq!(faired.ctrl[0], rough[0]); + assert_eq!(faired.ctrl[5], rough[5]); + } + + #[test] + fn a_sketch_curve_of_two_dimensions_fairs_the_same_way() { + // The generic core takes `[f64; 2]` just as well: a quadratic sketch curve, its middle + // pulled 2 mm out of the smooth polyline. + let knots = clamped(4, 2); + let smooth: Vec<[f64; 2]> = (0..knots.len() - 3).map(|i| [average(&knots, 2, i) * 10.0, average(&knots, 2, i) * 2.0]).collect(); + let mut rough = smooth.clone(); + rough[2] = [rough[2][0] + 1.0, rough[2][1] - 2.0]; + rough[3][1] += 1.5; + let opts = FairOptions::new(1.0, 10, false, 50.0).unwrap(); + let faired = fair_curve(2, &knots, &rough, &opts).unwrap(); + eprintln!("2D sketch curve: energy {:e} → {:e} in {} steps", faired.report.energy_before, faired.report.energy_after, faired.report.steps); + assert_eq!(faired.ctrl[0], rough[0]); + assert_eq!(faired.ctrl[5], rough[5]); + assert!(faired.report.energy_after >= 0.0 && faired.report.energy_after < 1e-9 * faired.report.energy_before); + for (i, want) in smooth.iter().enumerate().take(5).skip(1) { + assert!(dist(&faired.ctrl[i], want) < 1e-6, "point {i}"); + } + } + + #[test] + fn a_perturbed_net_is_faired_back_to_its_plane_with_its_boundary_rows_held() { + // A bicubic net of a plane (zero thin-plate energy), its middle pushed out; the boundary + // rows must not move at all and the interior must come back to the plane. + let (ku, kv) = (clamped(3, 3), clamped(4, 3)); + let degree = [3, 3]; + let (cu, cv) = (ku.len() - 4, kv.len() - 4); + let (a, b, c) = ([1.0, -2.0, 4.0], [2.0, 0.5, -0.25], [-0.5, 1.5, 0.75]); + let smooth = planar_net(&ku, &kv, degree, a, b, c); + let mut rough = smooth.clone(); + for &(i, j, d) in &[(2usize, 2usize, 3.0), (3, 3, -2.5), (1, 4, 1.5), (4, 5, -1.0)] { + 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(); + 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"); + } + } + 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"); + } + } + let near = (0..cu * cv).map(|k| dist(&faired.ctrl[k], &smooth[k])).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}"); + assert!(faired.report.energy_after < 1e-9 * faired.report.energy_before); + assert!(faired.report.energy_trace.windows(2).all(|w| w[1] < w[0])); + // With keep_edges the two outer layers at each side stay exactly as designed — so the + // bump goes into the middle of the net — and the rest still comes back to the plane. + let mut inner = smooth.clone(); + for &(i, j, d) in &[(2usize, 2usize, 3.0), (3, 3, -2.5), (2, 3, 1.5), (3, 2, -1.0)] { + 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 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"); + } + } + } + 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); + 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); + } + + #[test] + fn a_faired_geom_surface_stays_within_the_tolerance_of_the_design_and_keeps_its_weights() { + // A rational surface (weights off one) whose middle is pushed out: fair it with a 0.5 mm + // tolerance. The weights must be untouched, the boundary rows must not move, and the + // surface must stay within the tolerance of the one the design asked for. + let (ku, kv) = (clamped(3, 3), clamped(3, 3)); + let degree = [3, 3]; + let (cu, cv) = (ku.len() - 4, kv.len() - 4); + let smooth = planar_net(&ku, &kv, degree, [0.0, 0.0, 0.0], [20.0, 0.0, 0.0], [0.0, 15.0, 0.0]); + let weights: Vec = (0..cu * cv).map(|k| 0.5 + (k % 5) as f64 * 0.25).collect(); + let mut rough = smooth.clone(); + for &(i, j, d) in &[(2usize, 2usize, 4.0), (3, 3, -3.0), (1, 2, 2.0)] { + rough[j * cu + i][2] += d; + } + let surface = + NurbsSurface::new(degree, [ku.clone(), kv.clone()], &rough.iter().map(|c| Vec3::new(c[0], c[1], c[2])).collect::>(), &weights) + .unwrap(); + let tolerance = 0.5; + let opts = FairOptions::new(1.0, 8, false, tolerance).unwrap(); + let (faired, report) = fair_surface(&surface, &opts).unwrap(); + for k in 0..cu * cv { + let (i, j) = (k % cu, k / cu); + assert_eq!(faired.point(i, j).w, surface.point(i, j).w, "the weight of ({i}, {j}) changed"); + } + for j in 0..cv { + for i in [0, cu - 1] { + assert_eq!(faired.point(i, j), surface.point(i, j), "column {i} moved"); + } + } + let dom = surface.domain(); + let mut off = 0.0f64; + for k in 0..=24 { + for l in 0..=24 { + let (u, v) = (dom[0][0] + (dom[0][1] - dom[0][0]) * f64::from(k) / 24.0, dom[1][0] + (dom[1][1] - dom[1][0]) * f64::from(l) / 24.0); + off = off.max(surface.eval(u, v).unwrap().dist(faired.eval(u, v).unwrap())); + } + } + eprintln!( + "surface: moved {off:e} mm at worst ({:e} mm of control points), energy {:e} → {:e}", + report.movement, report.energy_before, report.energy_after + ); + assert!(report.movement <= tolerance, "{:e}", report.movement); + assert!(off <= tolerance * (1.0 + 1e-9), "{off:e} over {tolerance}"); + assert!(report.energy_after < report.energy_before); + // Every interior control point is nearer the plane than it was. + let before = (0..cu * cv).map(|k| dist(&rough[k], &smooth[k])).fold(0.0, f64::max); + let after = (0..cu * cv).map(|k| dist(&triple(faired.point(k % cu, k / cu).project().unwrap()), &smooth[k])).fold(0.0, f64::max); + assert!(after < before, "{after} vs {before}"); + } + + #[test] + fn the_truck_wrappers_fair_a_spline_curve_and_surface_with_their_ends_held() { + let knots = [0.0, 0.0, 0.0, 0.0, 1.0, 3.0, 5.0, 9.0, 9.0, 9.0, 9.0]; + let smooth = affine_curve(&knots, 3, [-20.0, 5.0, 1.5], [4.0, -2.5, 3.0]); + let mut rough = smooth.clone(); + rough[2][2] += 3.0; + rough[4][1] -= 2.0; + let points = |net: &[[f64; 3]]| -> Vec { net.iter().map(|c| mt::Point3::new(c[0], c[1], c[2])).collect() }; + let curve = mt::BSplineCurve::try_new(mt::KnotVec::from(knots.to_vec()), points(&rough)).unwrap(); + let tolerance = 5.0; + let opts = FairOptions::new(1.0, 8, false, tolerance).unwrap(); + let (faired, report) = fair_bspline_curve(&curve, &opts).unwrap(); + let mut off = 0.0f64; + for k in 0..=64 { + let t = 9.0 * f64::from(k) / 64.0; + off = off.max(apart(faired.subs(t), curve.subs(t))); + } + eprintln!( + "truck curve: energy {:e} → {:e} in {} steps, moved {off:e} mm ({:e} mm of control points)", + report.energy_before, report.energy_after, report.steps, report.movement + ); + assert_eq!(faired.control_points().first().copied(), curve.control_points().first().copied()); + assert_eq!(faired.control_points().last().copied(), curve.control_points().last().copied()); + assert!(off <= tolerance * (1.0 + 1e-9), "{off:e}"); + assert!(report.energy_after < 1e-9 * report.energy_before); + + // The same on a B-spline surface: boundary rows bit-identical, the bump in the middle + // comes down, the energy falls. + let (ku, kv) = (clamped(3, 3), clamped(3, 3)); + let degree = [3, 3]; + let (cu, cv) = (ku.len() - 4, kv.len() - 4); + let smooth = planar_net(&ku, &kv, degree, [0.0, 0.0, 0.0], [20.0, 0.0, 0.0], [0.0, 15.0, 0.0]); + let mut rough = smooth.clone(); + rough[2 * cu + 2][2] += 5.0; + let rows: Vec> = + (0..cu).map(|i| (0..cv).map(|j| mt::Point3::new(rough[j * cu + i][0], rough[j * cu + i][1], rough[j * cu + i][2])).collect()).collect(); + let surface = mt::BSplineSurface::try_new((mt::KnotVec::from(ku.clone()), mt::KnotVec::from(kv.clone())), rows).unwrap(); + let (faired, report) = fair_bspline_surface(&surface, &FairOptions::new(1.0, 6, true, 8.0).unwrap()).unwrap(); + eprintln!("truck surface: energy {:e} → {:e}, {} steps", report.energy_before, report.energy_after, report.steps); + for i in 0..cu { + for j in 0..cv { + if i < 2 || i + 2 >= cu || j < 2 || j + 2 >= cv { + assert_eq!(faired.control_points()[i][j], surface.control_points()[i][j], "({i}, {j}) is a boundary layer and moved"); + } + } + } + assert!(report.energy_after < report.energy_before); + assert!(faired.control_points()[2][2].z < surface.control_points()[2][2].z, "the bump should come down"); + } + + #[test] + fn a_rational_surface_fairs_with_its_boundary_and_tolerance_intact() { + // The truck NURBS wrapper, on weights away from one: fairing moves the Cartesian control + // points and keeps the weights, so the surface still cannot move more than the tolerance. + let (ku, kv) = (clamped(3, 3), clamped(3, 3)); + let degree = [3, 3]; + let (cu, cv) = (ku.len() - 4, kv.len() - 4); + let smooth = planar_net(&ku, &kv, degree, [0.0, 0.0, 0.0], [20.0, 0.0, 0.0], [0.0, 15.0, 0.0]); + let mut rough = smooth.clone(); + rough[2 * cu + 3][2] += 6.0; + let weights: Vec = (0..cu * cv).map(|k| 0.75 + (k % 3) as f64 * 0.5).collect(); + let rows: Vec> = (0..cu) + .map(|i| { + (0..cv) + .map(|j| { + let (c, w) = (rough[j * cu + i], weights[j * cu + i]); + mt::Vector4::new(c[0] * w, c[1] * w, c[2] * w, w) + }) + .collect() + }) + .collect(); + let bsp = mt::BSplineSurface::try_new((mt::KnotVec::from(ku.clone()), mt::KnotVec::from(kv.clone())), rows).unwrap(); + let surface = mt::NurbsSurface::new(bsp); + let (faired, report) = fair_nurbs_surface(&surface, &FairOptions::new(1.0, 6, false, 0.5).unwrap()).unwrap(); + eprintln!("rational surface: energy {:e} → {:e}, movement {:e} mm", report.energy_before, report.energy_after, report.movement); + assert!(report.movement <= 0.5 && report.energy_after < report.energy_before); + for i in 0..cu { + for j in 0..cv { + let (before, after) = (surface.non_rationalized().control_points()[i][j], faired.non_rationalized().control_points()[i][j]); + assert_eq!(after.w, before.w, "the weight of ({i}, {j}) changed"); + if i == 0 || i + 1 == cu || j == 0 || j + 1 == cv { + assert_eq!(after, before, "({i}, {j}) is on the boundary and moved"); + } + } + } + } + + #[test] + fn hostile_fairing_inputs_are_refused() { + let knots = clamped(3, 3); + let ctrl = affine_curve(&knots, 3, [0.0, 0.0, 0.0], [10.0, 4.0, 2.0]); + let ok = FairOptions::new(1.0, 4, false, 10.0).unwrap(); + // Out-of-range parameters: strength, iterations and tolerance are all input-derived. + for strength in [0.0, -0.25, 1.000_001, f64::NAN, f64::INFINITY] { + assert!(FairOptions::new(strength, 4, false, 10.0).is_err(), "strength {strength}"); + } + for iterations in [0, MAX_FAIR_ITERATIONS + 1, usize::MAX] { + assert!(FairOptions::new(1.0, iterations, false, 10.0).is_err(), "iterations {iterations}"); + } + for tolerance in [0.0, -1.0, f64::NAN, f64::INFINITY] { + assert!(FairOptions::new(1.0, 4, false, tolerance).is_err(), "tolerance {tolerance}"); + } + // A control point that is not a finite number. + for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + let mut nan = ctrl.clone(); + nan[2][1] = bad; + assert!(fair_curve(3, &knots, &nan, &ok).is_err(), "a control point of {bad} was faired"); + } + // Knot vectors that do not fit the control points or the degree. + assert!(fair_curve(3, &knots[..9], &ctrl, &ok).is_err(), "nine knots for six control points of degree three"); + assert!(fair_curve(3, &[0.0, 0.0, 0.0, 0.0, 2.0, 1.0, 3.0, 4.0, 4.0, 4.0], &ctrl, &ok).is_err(), "knots that decrease"); + assert!(fair_curve(3, &vec![f64::NAN; knots.len()], &ctrl, &ok).is_err(), "a knot that is not a number"); + assert!(fair_curve(9, &knots, &ctrl, &ok).is_err(), "a degree above the supported maximum"); + // Fewer than two interior control points: one free point (a triangle of a quadratic), and + // a 3 × 3 net whose two edge layers leave nothing at all. + let triangle = [[0.0, 0.0, 0.0], [5.0, 2.0, 0.0], [10.0, 0.0, 1.0]]; + let one = fair_curve(2, &[0.0, 0.0, 0.0, 1.0, 1.0, 1.0], &triangle, &ok).unwrap_err(); + assert!(one.to_string().contains("at least two interior"), "{one}"); + 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"); + // 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"); + // 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. + let odd = [0.0, 0.0, 0.0, 0.0, 0.5, 0.5, 0.5, 1.0, 1.0, 1.0]; + let six: Vec<[f64; 3]> = (0..6).map(|i| [i as f64, 0.0, 1.0]).collect(); + let singular = fair_curve(3, &odd, &six, &ok).unwrap_err(); + eprintln!("hostile inputs: refused with {singular}"); + assert!(singular.to_string().contains("singular"), "{singular}"); + } + + #[test] + fn a_small_quadratic_net_and_a_quintic_curve_fair_the_same_way() { + // Degrees and band shapes away from the bicubic case. A 5 × 5 quadratic net has fewer + // rows than the degree, so the solver's band is narrower than `degree_u + degree_v · cols` + // (the coupling cannot reach that far in v); a quintic curve carries six basis functions + // per span instead of four. Both must reproduce a zero-energy shape exactly. + let (ku, kv) = (clamped(3, 2), clamped(3, 2)); + let degree = [2, 2]; + let (cu, cv) = (ku.len() - 3, kv.len() - 3); + assert_eq!((cu, cv), (5, 5)); + let smooth = planar_net(&ku, &kv, degree, [0.0, 0.0, 0.0], [12.0, 1.0, 0.0], [-2.0, 9.0, 0.0]); + let mut rough = smooth.clone(); + 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); + 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"); + } + } + } + // A quintic curve, its middle pulled out. + let knots = clamped(3, 5); + let smooth = affine_curve(&knots, 5, [-10.0, 0.0, 2.0], [6.0, 4.0, -1.0]); + let mut rough = smooth.clone(); + rough[3][1] += 3.0; + rough[4][2] -= 2.0; + let faired = fair_curve(5, &knots, &rough, &FairOptions::new(1.0, 8, false, 100.0).unwrap()).unwrap(); + let near = (1..smooth.len() - 1).map(|i| dist(&faired.ctrl[i], &smooth[i])).fold(0.0, f64::max); + eprintln!("quintic curve: 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); + assert_eq!(faired.ctrl[0], rough[0]); + assert_eq!(faired.ctrl[rough.len() - 1], rough[rough.len() - 1]); + } + + /// A one-face sheet body of the bicubic surface `net` (u fastest) over the clamped knots `ku` + /// and `kv`, its sides the straight lines between the surface's corners — true while the + /// net's boundary rows describe lines, which is how a plane's control net is built here. + fn sheet(ku: &[f64], kv: &[f64], net: &[[f64; 3]]) -> Body { + let (cu, cv) = (ku.len() - 4, kv.len() - 4); + assert_eq!(net.len(), cu * cv, "the net does not fit the knots"); + let rows: Vec> = + (0..cu).map(|i| (0..cv).map(|j| mt::Point3::new(net[j * cu + i][0], net[j * cu + i][1], net[j * cu + i][2])).collect()).collect(); + let bsp = mt::BSplineSurface::try_new((mt::KnotVec::from(ku.to_vec()), mt::KnotVec::from(kv.to_vec())), rows).unwrap(); + let corner = |i: usize, j: usize| { + let c = net[j * cu + i]; + mt::Vertex::new(mt::Point3::new(c[0], c[1], c[2])) + }; + let v = [corner(0, 0), corner(cu - 1, 0), corner(cu - 1, cv - 1), corner(0, cv - 1)]; + let line = |a: &mt::Vertex, b: &mt::Vertex| mt::Edge::new(a, b, mt::Curve::Line(mt::Line(a.point(), b.point()))); + let wire: mt::Wire = vec![line(&v[0], &v[1]), line(&v[1], &v[2]), line(&v[2], &v[3]), line(&v[3], &v[0])].into(); + crate::surfaces::surface_body(vec![mt::Face::try_new(vec![wire], mt::Surface::BSplineSurface(bsp)).unwrap()]) + } + + #[test] + fn a_body_face_is_faired_with_its_edges_untouched_and_its_history_kept() { + // A sheet whose middle is bumped: fairing the face must smooth it without moving a single + // edge, vertex or neighbouring face of the body, and must leave a history saying so. + let (ku, kv) = (clamped(3, 3), clamped(3, 3)); + let (cu, cv) = (ku.len() - 4, kv.len() - 4); + let smooth = planar_net(&ku, &kv, [3, 3], [0.0, 0.0, 0.0], [20.0, 0.0, 0.0], [0.0, 15.0, 0.0]); + let mut rough = smooth.clone(); + for &(i, j, d) in &[(2usize, 2usize, 3.0), (3, 3, -2.0), (2, 3, 1.5)] { + rough[j * cu + i][2] += d; + } + let body = sheet(&ku, &kv, &rough); + let before: Vec<_> = + body.solid.face_iter().flat_map(|f| f.absolute_boundaries().iter()).flat_map(|w| w.edge_iter().map(|e| e.id())).collect(); + assert!(!before.is_empty()); + let (faired, report) = fair_faces(&body, &[0], &FairOptions::new(1.0, 6, false, 50.0).unwrap()).unwrap(); + let after: Vec<_> = + faired.solid.face_iter().flat_map(|f| f.absolute_boundaries().iter()).flat_map(|w| w.edge_iter().map(|e| e.id())).collect(); + eprintln!( + "face: energy {:e} → {:e} in {} steps, movement {:e} mm, {} faces, history {}", + report.energy_before, + report.energy_after, + report.steps, + report.movement, + faired.face_count(), + faired.history().is_some() + ); + assert_eq!(before, after, "the body's edges must be the very ones it had"); + assert_eq!(faired.face_count(), 1); + assert!(faired.history().is_some(), "the face came from the one it was faired from"); + assert!(report.energy_after < 1e-9 * report.energy_before); + // The face's own surface is back on the plane, boundary rows bit for bit as they were. + let Some(mt::Surface::BSplineSurface(s)) = faired.solid.face_iter().next().map(|f| f.surface()) else { panic!("a B-spline face") }; + for j in 0..cv { + for i in 0..cu { + let p = s.control_points()[i][j]; + let want = if i == 0 || i + 1 == cu || j == 0 || j + 1 == cv { rough[j * cu + i] } else { smooth[j * cu + i] }; + assert!(dist(&[p.x, p.y, p.z], &want) < 1e-6, "({i}, {j})"); + } + } + // A solid keeps its shells, its faces and its edges: thickening the sheet gives a closed + // body whose top face is still the B-spline one, and fairing that face leaves the body a + // solid of the same shape. + let solid = crate::thicken(&body, 2.0, false).unwrap(); + assert!(!solid.is_surface()); + let top = + (0..solid.face_count()).find(|&i| matches!(solid.solid.face_iter().nth(i).map(|f| f.surface()), Some(mt::Surface::BSplineSurface(_)))); + let Some(top) = top else { panic!("the thickened sheet keeps its B-spline face") }; + let edges: Vec<_> = + solid.solid.face_iter().flat_map(|f| f.absolute_boundaries().iter()).flat_map(|w| w.edge_iter().map(|e| e.id())).collect(); + let (faired, report) = fair_faces(&solid, &[top], &FairOptions::new(1.0, 6, false, 0.5).unwrap()).unwrap(); + eprintln!("thickened solid: energy {:e} → {:e}, movement {:e} mm", report.energy_before, report.energy_after, report.movement); + assert!(!faired.is_surface() && faired.face_count() == solid.face_count() && faired.shell_count() == solid.shell_count()); + assert_eq!( + faired.solid.face_iter().flat_map(|f| f.absolute_boundaries().iter()).flat_map(|w| w.edge_iter().map(|e| e.id())).collect::>(), + edges + ); + assert!(report.energy_after < report.energy_before); + // A face with no control points to fair is refused, by name. + let cube = crate::box_solid(Vec3::ZERO, Vec3::new(10.0, 10.0, 10.0)).unwrap(); + let refused = fair_faces(&cube, &[0], &FairOptions::new(1.0, 1, false, 1.0).unwrap()).unwrap_err(); + eprintln!("cube face: {refused}"); + assert!(refused.to_string().contains("not a B-spline face"), "{refused}"); + assert!(fair_faces(&body, &[7], &FairOptions::new(1.0, 1, false, 1.0).unwrap()).is_err(), "no such face"); + assert!(fair_faces(&body, &[], &FairOptions::new(1.0, 1, false, 1.0).unwrap()).is_err(), "no face picked"); + } + + #[test] + fn an_already_fair_curve_is_left_where_it_is() { + // Zero bending energy, no reason to move: nothing churns, and an input at the minimum + // cannot be faired into a worse shape. + let knots = clamped(4, 3); + let smooth = affine_curve(&knots, 3, [1.0, 2.0, 3.0], [5.0, -1.0, 0.5]); + let opts = FairOptions::new(1.0, 20, false, 10.0).unwrap(); + let faired = fair_curve(3, &knots, &smooth, &opts).unwrap(); + eprintln!( + "already fair: energy {:e} → {:e}, {} steps, {:e} mm", + faired.report.energy_before, faired.report.energy_after, faired.report.steps, faired.report.movement + ); + assert!(faired.report.energy_after <= faired.report.energy_before); + assert!(faired.report.energy_after >= 0.0); + assert!(faired.report.movement < 1e-9, "{:e}", faired.report.movement); + for (i, want) in smooth.iter().enumerate() { + assert!(dist(&faired.ctrl[i], want) < 1e-9, "control point {i}"); + } + } +} diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rs index 0376c6a7a..22756f874 100644 --- a/crates/kernel/src/lib.rs +++ b/crates/kernel/src/lib.rs @@ -24,6 +24,7 @@ mod boolean_diagnostics; mod boolean_guard; mod boolean_record; mod bore_guard; +mod boundary; mod bridge; mod build; mod clearance; @@ -36,6 +37,7 @@ mod emboss; mod face_params; #[cfg(test)] mod face_source_tests; +mod fair; mod fill; mod freeform; pub mod fuzz; @@ -66,6 +68,7 @@ mod issue_871_tests; mod join_between_caps_tests; mod lip; mod loopblend; +mod matchsurf; mod measure; mod mesh_convert; mod meshbody; @@ -125,6 +128,7 @@ 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 boolean_diagnostics::{BooleanDiagnostics, BooleanFallback, BooleanStrategy, capture_boolean_diagnostics}; +pub use boundary::{Boundary, boundary_patch}; 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, loft, revolve, sphere, sweep, @@ -132,11 +136,16 @@ pub use build::{ }; pub use delete_face::delete_faces; pub use emboss::{cylinder_emboss_anchor, emboss_cylinder, emboss_cylinder_at, has_cylinder_emboss_wall, infer_cylinder_emboss}; +pub use fair::{ + FairCurve, FairNet, FairOptions, FairReport, MAX_FAIR_ITERATIONS, MAX_FAIR_POINTS, fair_bspline_curve, fair_bspline_surface, fair_curve, + fair_faces, fair_net, fair_nurbs_curve, fair_nurbs_surface, fair_surface, +}; pub use fill::{PATCH_ANGLE_TOL_DEG, PatchReport, PatchSpec, patch_edges_crowned, patch_edges_report, patch_edges_with}; 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 matchsurf::{match_surface, seam_continuity}; pub use measure::{BodyMeasure, measure}; pub use mesh_convert::convert_prismatic_mesh; pub use meshbody::{MAX_TRIANGLES, mesh_body}; diff --git a/crates/kernel/src/matchsurf.rs b/crates/kernel/src/matchsurf.rs new file mode 100644 index 000000000..8134ea341 --- /dev/null +++ b/crates/kernel/src/matchsurf.rs @@ -0,0 +1,601 @@ +//! Surface matching: rebuild a surface body's face so that one boundary of it meets a picked +//! edge chain of another body up to a requested continuity (G1, G2 or G3), while the boundary +//! opposite it does not move. +//! +//! A match is the bridge core ([`crate::bridge`]) pointed at a different pair of boundaries. One +//! end reads its position, tangent, curvature and change of curvature from the *target's* face +//! along the picked chain — that is the end that moves. The other end reads them from the body's +//! own surface along the boundary opposite it, built through the original boundary's own points: +//! a match may shape the middle, never that seam. In between the cross-sections are the bridge's +//! cubic Hermites, whose crown is free, so the crown whose surface stays closest to the original +//! one — sampled on a grid and measured against it — is the one kept: a match moves the seam and +//! as little else as the conditions allow. +//! +//! Which boundary of the face moves is read off the geometry: the one nearest the picked chain. +//! The order a match may ask for is read off the target the same way: a chain that several faces +//! of the target meet, with shapes that part company, is a seam the target itself does not hold +//! beyond that order, and no surface can be told to carry a condition the target has not got. + +use mt::{BoundedCurve, ParametricCurve, ParametricSurface, ParametricSurface3D, SearchNearestParameter}; +use solidcraft_geom::Vec3; +use truck_modeling as mt; + +use crate::body::{Body, from_p3, p3}; +use crate::bridge::{self, Continuity, Frame}; +use crate::record::Rebuild; +use crate::surfaces::surface_body; +use crate::{KernelError, Result, guard}; + +/// Stations a match reads along the seam and along the boundary it keeps. +const STATIONS: usize = 33; + +/// Samples each way of the grid the rebuilt surface is compared with the original on. +const GRID: usize = 7; + +/// The crowns the match tries at each end: [`crate::bridge::bridge`]'s free knob, which shapes +/// the middle without touching either end's conditions. +const CROWNS: [f64; 5] = [-0.5, 0.0, 0.5, 1.0, 2.0]; + +/// Points a caller may pick one face with. +const MAX_PICKS: usize = 64; + +/// Samples per edge of a chain, for lengths and distances. +const PER_EDGE: usize = 32; + +/// A seam is credited with G1 when its normals agree this closely (degrees), with G2 when the +/// two curvature vectors agree within this fraction of the larger of them, and with G3 when the +/// change of curvature agrees within this fraction of the curvature over the body's size. +const G1_DEG: f64 = 0.05; +const G2_REL: f64 = 5e-3; +const G3_REL: f64 = 5e-2; + +/// Two faces of the target count as meeting each other at the picked chain when their normals +/// agree this closely, their curvature within this fraction of the larger, and their change of +/// curvature within this fraction of the curvature over the body's size. +const SUPPLY_DEG: f64 = 0.05; +const SUPPLY_REL: f64 = 2e-2; +const SUPPLY_BEND_REL: f64 = 1e-1; + +/// Rebuild the face of `body` picked by `faces` (points on it) so that its boundary nearest the +/// chain of `target`'s edges picked by `target_pick` takes that chain's place and repeats the +/// target's own shape along it up to `order` — position, tangent, curvature vector, and the +/// change of that curvature vector along the direction the match leaves in. The boundary +/// opposite keeps its place and the original surface's own frame, and the middle is shaped to +/// stay as close to the original surface as the conditions allow. +pub fn match_surface(body: &Body, faces: &[Vec3], target: &Body, target_pick: &[Vec3], order: Continuity) -> Result { + body.require_brep("match")?; + target.require_brep("match")?; + if !body.is_surface() { + return Err(KernelError::Invalid("match rebuilds a surface body: this one is closed".into())); + } + let face = face_near(body, faces)?; + let chain = bridge::chain(target, target_pick)?; + let near = nearest_side(&face, &chain)?; + let far = near.opposite(); + let far_edges = side_edges(&face, far, body.size() * 1e-6 + 1e-9)?; + let (mid_near, mid_far) = (chain_mid(&chain)?, Side::at(&face.surface(), &ranges(&face)?, far, 0.5)); + let leave = (mid_far - mid_near) + .normalized() + .filter(|l| l.is_finite()) + .ok_or_else(|| KernelError::Invalid("the far boundary sits on the picked chain: there is nothing to match".into()))?; + // Which face of the target the match continues from, and how much of the requested order the + // target itself holds along that chain. + let candidates = support_faces(target, &chain, leave)?; + let supply = supply_order(&candidates, &chain, leave, target.size())?; + if order.conditions() > supply.conditions() { + return Err(KernelError::Invalid(format!( + "the target's own surfaces part company at the picked edges: they hold only {} there, so a seam cannot hold {}", + supply.as_str(), + order.as_str() + ))); + } + let Some((target_face, _)) = candidates.first() else { + return Err(KernelError::Invalid("no face of the target holds the picked edges".into())); + }; + // The stations of the seam: what the target does there along the direction the match leaves + // in, and what the far boundary does coming back the other way. + let mut near_frames = bridge::frames(target_face, &chain, leave, STATIONS)?; + let far_frames = bridge::frames(&face, &far_edges, leave * -1.0, STATIONS)?; + // The two chains are sampled from their own starts: turn one round when that pairs the + // stations better (a match is built station to station). + let direct: f64 = near_frames.iter().zip(&far_frames).map(|(a, b)| a.p.dist(b.p)).sum(); + let reversed: f64 = near_frames.iter().zip(far_frames.iter().rev()).map(|(a, b)| a.p.dist(b.p)).sum(); + if reversed < direct { + near_frames.reverse(); + } + guard("surface match", || { + // The crown is the free knob: keep the one whose surface stays closest to the original. + let mut best: Option<(f64, mt::Face)> = None; + for crown_near in CROWNS { + for crown_far in CROWNS { + let made = bridge::bridge(&near_frames, &far_frames, [order, Continuity::G1], [crown_near, crown_far])?; + let Some(made) = made.solid.face_iter().next().cloned() else { + return Err(KernelError::Failed("match: the bridge made no face".into())); + }; + let stray = deviation(&made, &face)?; + if best.as_ref().is_none_or(|(b, _)| stray < *b) { + best = Some((stray, made)); + } + } + } + let Some((_, made)) = best else { + return Err(KernelError::Failed("match: no crown built a surface".into())); + }; + let mut kept = made; + // The rebuilt face takes the target's own sense at the seam: the two surfaces then meet + // the same way round, which is what a stitch, a thicken or a display of the result reads. + let seam = chain_mid(&chain)?; + if let (Some((made_n, _)), Some((target_n, _))) = (normal_near(&kept, seam), normal_near(target_face, seam)) + && made_n.dot(target_n) < 0.0 + { + kept.invert(); + } + let mut rec = Rebuild::default(); + rec.face(&kept, &face); + Ok(crate::record::rebuilt_body(surface_body(vec![kept]), &[&body.solid, &target.solid], &rec)) + }) +} + +/// How well the rebuilt surface `made` meets `target` along the chain picked by `target_pick`: +/// the worst distance from the seam to that chain, the worst angle between the two surfaces' +/// normals across it (degrees), and the highest continuity the seam holds +/// ([`Continuity::G0`] when even the normals disagree). +pub fn seam_continuity(made: &Body, target: &Body, target_pick: &[Vec3]) -> Result<(f64, f64, Continuity)> { + made.require_brep("match")?; + target.require_brep("match")?; + let chain = bridge::chain(target, target_pick)?; + let poly = chain_polyline(&chain)?; + // The face whose boundary runs along the chain: the one nearest it, so that a body that has + // not been matched yet — where the seam is still some way off — can be measured too. + let mid = chain_mid(&chain)?; + let face = made + .solid + .face_iter() + .filter_map(|f| face_distance(f, mid).map(|d| (d, f))) + .min_by(|a, b| a.0.total_cmp(&b.0)) + .map(|(_, f)| f.clone()) + .ok_or_else(|| KernelError::Failed("match: the body has no faces".into()))?; + let near = nearest_side(&face, &chain)?; + let far = near.opposite(); + let ranges = ranges(&face)?; + let mid_far = Side::at(&face.surface(), &ranges, far, 0.5); + let leave = (mid_far - chain_mid(&chain)?) + .normalized() + .ok_or_else(|| KernelError::Invalid("the seam and the far boundary coincide: there is nothing to measure".into()))?; + let candidates = support_faces(target, &chain, leave)?; + let Some((target_face, _)) = candidates.first() else { + return Err(KernelError::Invalid("no face of the target holds the picked edges".into())); + }; + let frames = bridge::frames(target_face, &chain, leave, STATIONS)?; + let size = target.size(); + guard("surface match", || { + let surf = face.surface(); + let (mut gap, mut deg, mut curv, mut bend) = (0.0f64, 0.0f64, 0.0f64, 0.0f64); + for i in 0..STATIONS { + let t = i as f64 / (STATIONS - 1) as f64; + let p = Side::at(&surf, &ranges, near, t); + gap = gap.max(chain_distance(&poly, p)); + // What the target says there, and what the rebuilt surface actually does there. + let Some(frame) = frames.iter().min_by(|a, b| a.p.dist(p).total_cmp(&b.p.dist(p))) else { + return Err(KernelError::Failed("match: the target has no frames".into())); + }; + let (_, t_made, bend_made, change_made) = seam_shape(&surf, &ranges, near, t)?; + if let Some((n_made, _)) = normal_near(&face, p) + && let Some((n_target, _)) = normal_near(target_face, p) + { + deg = deg.max(angle_deg(n_made, n_target)); + } + let scale = frame.bend.len().max(bend_made.len()).max(1.0 / size); + curv = curv.max((bend_made - frame.bend).len() / scale); + // The change of curvature is what a surface can hold: only its normal part counts, + // and it turns round with the direction of travel. + let change = if t_made.dot(frame.leave) < 0.0 { change_made * -1.0 } else { change_made }; + let scale3 = frame.bend_change.len().max(change.len()).max(scale / size); + bend = bend.max((change - frame.bend_change).len() / scale3); + } + let mut order = Continuity::G0; + if deg <= G1_DEG { + order = Continuity::G1; + if curv <= G2_REL { + order = Continuity::G2; + if bend <= G3_REL { + order = Continuity::G3; + } + } + } + Ok((gap, deg, order)) + }) +} + +/// Which side of a face's parameter rectangle a boundary runs along: the match reads its face as +/// a tensor patch, so its four sides are its own parameter lines. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Side { + /// The `u = u0` side (its points run along `v`). + U0, + /// The `u = u1` side. + U1, + /// The `v = v0` side (its points run along `u`). + V0, + /// The `v = v1` side. + V1, +} + +impl Side { + /// The four sides, in a fixed order. + const ALL: [Side; 4] = [Side::U0, Side::U1, Side::V0, Side::V1]; + + /// The side opposite this one: what a match keeps when this one moves. + fn opposite(self) -> Side { + match self { + Side::U0 => Side::U1, + Side::U1 => Side::U0, + Side::V0 => Side::V1, + Side::V1 => Side::V0, + } + } + + /// Whether this side pins `u` (its points run along `v`). + fn is_u(self) -> bool { + matches!(self, Side::U0 | Side::U1) + } + + /// The value this side pins, and the range the side runs over. + fn fixed_and_along(self, u: (f64, f64), v: (f64, f64)) -> (f64, (f64, f64)) { + match self { + Side::U0 => (u.0, v), + Side::U1 => (u.1, v), + Side::V0 => (v.0, u), + Side::V1 => (v.1, u), + } + } + + /// The point at the normalized station `t` along the side. + fn at(surf: &mt::Surface, ranges: &[(f64, f64); 2], side: Side, t: f64) -> Vec3 { + let (u, v) = (ranges[0], ranges[1]); + let (fixed, along) = side.fixed_and_along(u, v); + let t = along.0 + (along.1 - along.0) * t.clamp(0.0, 1.0); + if side.is_u() { from_p3(surf.subs(fixed, t)) } else { from_p3(surf.subs(t, fixed)) } + } +} + +/// The bounded parameter ranges of a face's surface. +fn ranges(face: &mt::Face) -> Result<[(f64, f64); 2]> { + let surf = face.surface(); + let (Some(u), Some(v)) = surf.try_range_tuple() else { + return Err(KernelError::Failed("match: the face's surface is unbounded".into())); + }; + Ok([u, v]) +} + +/// How far `p` is from the face's own surface. +fn face_distance(face: &mt::Face, p: Vec3) -> Option { + let surf = face.surface(); + let (u, v) = surf.search_nearest_parameter(p3(p), None, 100)?; + Some(from_p3(surf.subs(u, v)).dist(p)) +} + +/// The surface's unit normal at the point nearest `p`, and how far `p` is from that point. +fn normal_near(face: &mt::Face, p: Vec3) -> Option<(Vec3, f64)> { + let surf = face.surface(); + let (u, v) = surf.search_nearest_parameter(p3(p), None, 100)?; + let n = surf.normal(u, v); + let n = Vec3::new(n.x, n.y, n.z).normalized()?; + Some((n, from_p3(surf.subs(u, v)).dist(p))) +} + +/// The face of `body` the picks lie on: they must all pick the same one. A pick is a point the +/// caller clicked, so the face nearest it within the body's own pick tolerance is the face it +/// means (`crate::surfaces::edge_near` reads points the same way). +fn face_near(body: &Body, picks: &[Vec3]) -> Result { + if picks.is_empty() || picks.len() > MAX_PICKS || picks.iter().any(|p| !p.is_finite()) { + return Err(KernelError::Invalid(format!("pick 1 to {MAX_PICKS} points on the face to match"))); + } + let tol = body.size() * 0.05 + 1e-6; + let mut found: Option = None; + for p in picks { + let hit = body + .solid + .face_iter() + .filter_map(|f| face_distance(f, *p).map(|d| (d, f))) + .min_by(|a, b| a.0.total_cmp(&b.0)) + .filter(|(d, _)| *d <= tol) + .map(|(_, f)| f.clone()) + .ok_or_else(|| KernelError::Invalid(format!("no face of the body passes through {p:?}")))?; + if found.as_ref().is_some_and(|f| f.id() != hit.id()) { + return Err(KernelError::Invalid("the picks are on different faces: match one face".into())); + } + found = Some(hit); + } + found.ok_or_else(|| KernelError::Invalid("pick a point on the face to match".into())) +} + +/// A chain of edges as a polyline (each edge sampled), for lengths and distances. +fn chain_polyline(chain: &[mt::Edge]) -> Result> { + if chain.is_empty() { + return Err(KernelError::Invalid("the chain has no edges".into())); + } + let mut out = Vec::with_capacity(chain.len() * (PER_EDGE + 1)); + for e in chain { + let c = e.curve(); + let (t0, t1) = c.range_tuple(); + if !(t1 > t0) || ![t0, t1].into_iter().all(f64::is_finite) { + return Err(KernelError::Failed("match: an edge has no parameter range".into())); + } + for k in 0..=PER_EDGE { + out.push(from_p3(c.subs(t0 + (t1 - t0) * k as f64 / PER_EDGE as f64))); + } + } + Ok(out) +} + +/// The point at the middle of a chain, by length. +fn chain_mid(chain: &[mt::Edge]) -> Result { + let poly = chain_polyline(chain)?; + 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)); + } + let total = cum.last().copied().unwrap_or(0.0); + if !(total > 1e-9) || !total.is_finite() { + return Err(KernelError::Invalid("the picked chain has no length".into())); + } + let half = total * 0.5; + let hi = cum.partition_point(|x| *x < half).clamp(1, poly.len().saturating_sub(1)); + let (Some(a), Some(b)) = (poly.get(hi - 1), poly.get(hi)) else { + return Err(KernelError::Failed("match: chain".into())); + }; + let (Some(&lo), Some(&up)) = (cum.get(hi - 1), cum.get(hi)) else { + return Err(KernelError::Failed("match: chain".into())); + }; + let span = up - lo; + let t = if span > 1e-12 { (half - lo) / span } else { 0.0 }; + Ok(*a + (*b - *a) * t) +} + +/// How far `p` is from a polyline. +fn chain_distance(poly: &[Vec3], p: Vec3) -> f64 { + let mut best = f64::INFINITY; + for w in poly.windows(2) { + let (Some(a), Some(b)) = (w.first(), w.get(1)) else { continue }; + let d = b.dist(*a); + let t = if d > 1e-12 { ((p - *a).dot(*b - *a) / (d * d)).clamp(0.0, 1.0) } else { 0.0 }; + best = best.min(p.dist(*a + (*b - *a) * t)); + } + best +} + +/// The side of the face's own parameter rectangle the picked chain sits nearest. +fn nearest_side(face: &mt::Face, chain: &[mt::Edge]) -> Result { + let surf = face.surface(); + let ranges = ranges(face)?; + let poly = chain_polyline(chain)?; + /// Samples of each side used to tell which one the chain runs along. + const SAMPLES: usize = 17; + let mut best: Option<(f64, Side)> = None; + for side in Side::ALL { + let mut total = 0.0; + for k in 0..SAMPLES { + let t = k as f64 / (SAMPLES - 1) as f64; + total += chain_distance(&poly, Side::at(&surf, &ranges, side, t)); + } + let mean = total / SAMPLES as f64; + if best.is_none_or(|(b, _)| mean < b) { + best = Some((mean, side)); + } + } + best.map(|(_, s)| s).ok_or_else(|| KernelError::Failed("match: the face has no sides".into())) +} + +/// The face's own edges that run along a side of its parameter rectangle, chained head to tail. +/// A match keeps the far side's own edges, so they must be a chain that runs on. +fn side_edges(face: &mt::Face, side: Side, tol: f64) -> Result> { + let surf = face.surface(); + let ranges = ranges(face)?; + let (fixed, along) = side.fixed_and_along(ranges[0], ranges[1]); + let band = (along.1 - along.0).abs().max(1e-12) * 1e-3; + let mut pool: Vec = Vec::new(); + for e in face.edge_iter() { + let c = e.curve(); + let (t0, t1) = c.range_tuple(); + let p = from_p3(c.subs(0.5 * (t0 + t1))); + let Some((u, v)) = surf.search_nearest_parameter(p3(p), None, 100) else { continue }; + if from_p3(surf.subs(u, v)).dist(p) > tol { + continue; + } + let got = if side.is_u() { u } else { v }; + if (got - fixed).abs() <= band { + pool.push(e.clone()); + } + } + if pool.is_empty() { + return Err(KernelError::Invalid("the face has no edges along the boundary a match would keep".into())); + } + let first = pool.remove(0); + let mut chain = vec![first]; + let mut end = match chain.first() { + Some(e) => e.back().clone(), + None => return Err(KernelError::Failed("match: chain".into())), + }; + while let Some(k) = pool.iter().position(|e| e.front().id() == end.id() || e.back().id() == end.id()) { + let e = pool.remove(k); + let e = if e.front().id() == end.id() { e } else { e.inverse() }; + end = e.back().clone(); + chain.push(e); + } + let mut start = match chain.first() { + Some(e) => e.front().clone(), + None => return Err(KernelError::Failed("match: chain".into())), + }; + while let Some(k) = pool.iter().position(|e| e.front().id() == start.id() || e.back().id() == start.id()) { + let e = pool.remove(k); + let e = if e.back().id() == start.id() { e } else { e.inverse() }; + start = e.front().clone(); + chain.insert(0, e); + } + if !pool.is_empty() { + return Err(KernelError::Invalid("the face's edges along that boundary do not run on from one another".into())); + } + Ok(chain) +} + +/// The faces of `target` that meet the chain and whose tangent plane holds the leave direction, +/// best first: the face a match continues from, and the ones it might have been read from. +fn support_faces(target: &Body, chain: &[mt::Edge], leave: Vec3) -> Result> { + let mid = chain_mid(chain)?; + let tol = target.size() * 1e-6 + 1e-9; + let mut out: Vec<(mt::Face, f64)> = Vec::new(); + for face in target.solid.face_iter() { + if !chain.iter().all(|e| face.edge_iter().any(|f| f.id() == e.id())) { + continue; + } + let Some((n, d)) = normal_near(face, mid) else { continue }; + if d > tol { + continue; + } + let score = (leave - n * leave.dot(n)).len(); + if score.is_finite() && score >= 0.2 { + out.push((face.clone(), score)); + } + } + if out.is_empty() { + return Err(KernelError::Invalid( + "no face of the target holds the picked edges in the direction the match leaves in: pick the chain of a face the surface can continue" + .into(), + )); + } + out.sort_by(|a, b| b.1.total_cmp(&a.1)); + Ok(out) +} + +/// The highest order the target itself holds along the chain: every face that meets those edges +/// and whose tangent plane holds the leave direction reads the chain's shape from its own +/// surface, and where two of them part company the target's own geometry jumps at the seam. +fn supply_order(candidates: &[(mt::Face, f64)], chain: &[mt::Edge], leave: Vec3, size: f64) -> Result { + let Some((first, best)) = candidates.first() else { + return Err(KernelError::Invalid("no face of the target holds the picked edges".into())); + }; + let keep: Vec<&mt::Face> = candidates.iter().filter(|(_, s)| *s >= 0.5 * best).map(|(f, _)| f).collect(); + let mut order = Continuity::G3; + if keep.len() < 2 { + return Ok(order); + } + let primary: Vec = bridge::frames(first, chain, leave, STATIONS)?; + for other in keep.iter().skip(1) { + // A face that cannot be read along the whole chain says nothing here: the face the match + // is built on is the one that must be able to supply it. + let Ok(other_frames) = bridge::frames(other, chain, leave, STATIONS) else { continue }; + let mut worst_deg = 0.0f64; + let mut worst = 0.0f64; + let mut worst_change = 0.0f64; + for (a, b) in primary.iter().zip(&other_frames) { + if let (Some((na, _)), Some((nb, _))) = (normal_near(first, a.p), normal_near(other, b.p)) { + worst_deg = worst_deg.max(angle_deg(na, nb)); + } + let scale = a.bend.len().max(b.bend.len()).max(1.0 / size); + worst = worst.max((a.bend - b.bend).len() / scale); + let scale3 = a.bend_change.len().max(b.bend_change.len()).max(scale / size); + worst_change = worst_change.max((a.bend_change - b.bend_change).len() / scale3); + } + if worst_deg > SUPPLY_DEG { + order = Continuity::G0; + } + if worst > SUPPLY_REL && order.conditions() > 1 { + order = Continuity::G1; + } + if worst_change > SUPPLY_BEND_REL && order.conditions() > 2 { + order = Continuity::G2; + } + } + Ok(order) +} + +/// The acute angle between two directions, in degrees. For two surfaces' normals this is the +/// angle between their tangent planes: a sheet has no inside, so which way a normal points says +/// nothing about whether the surfaces meet smoothly. +fn angle_deg(a: Vec3, b: Vec3) -> f64 { + let d = a.dot(b) / (a.len() * b.len()); + if !d.is_finite() { + return f64::NAN; + } + d.abs().clamp(0.0, 1.0).acos().to_degrees() +} + +/// The geometric shape of a surface curve at a point from its first three derivatives along the +/// curve: the same statement [`crate::bridge`] makes of a support surface — the unit tangent, the +/// curvature vector, and the arclength derivative of that curvature vector. +fn shape(d1: Vec3, d2: Vec3, d3: Vec3) -> Result<(Vec3, Vec3, Vec3)> { + let sigma = d1.len(); + if !(sigma > 1e-12) || !sigma.is_finite() { + return Err(KernelError::Failed("match: the seam's cross-section does not move".into())); + } + let t = d1 * (1.0 / sigma); + let tp = d2 * (1.0 / sigma) - d1 * (d1.dot(d2) / (sigma * sigma * sigma)); + let nn = d2 - t * d2.dot(t); + let np = d3 - t * d3.dot(t) - tp * d2.dot(t) - t * d2.dot(tp); + let kappa = np * (sigma * sigma) - nn * (2.0 * d1.dot(d2)); + let change = kappa * (1.0 / (sigma.powi(5))); + if ![t, nn, change].into_iter().all(Vec3::is_finite) { + return Err(KernelError::Failed("match: the seam's shape is not finite".into())); + } + Ok((t, nn * (1.0 / (sigma * sigma)), change)) +} + +/// The shape of a face's surface along its cross direction at the station `t`, read inwards from +/// the boundary `near` over five one-sided samples: the point, the unit tangent, the curvature +/// vector and the change of that curvature. The same finite difference [`crate::bridge::frames`] +/// reads a support surface with, so that a rebuilt seam can be compared with what it matched. +fn seam_shape(surf: &mt::Surface, ranges: &[(f64, f64); 2], near: Side, t: f64) -> Result<(Vec3, Vec3, Vec3, Vec3)> { + let (station, cross, at_start) = if near.is_u() { + (ranges[1].0 + (ranges[1].1 - ranges[1].0) * t, ranges[0], near == Side::U0) + } else { + (ranges[0].0 + (ranges[0].1 - ranges[0].0) * t, ranges[1], near == Side::V0) + }; + let span = (cross.1 - cross.0).abs().max(1e-12); + let h = span * 1e-3; + let c0 = if at_start { cross.0 } else { cross.1 }; + let sgn = if at_start { 1.0 } else { -1.0 }; + let at = |x: f64| if near.is_u() { from_p3(surf.subs(x, station)) } else { from_p3(surf.subs(station, x)) }; + let q: Vec = (0..5).map(|k| at(c0 + sgn * k as f64 * h)).collect(); + let (Some(&q0), Some(&q1), Some(&q2), Some(&q3), Some(&q4)) = (q.first(), q.get(1), q.get(2), q.get(3), q.get(4)) else { + return Err(KernelError::Failed("match: seam samples".into())); + }; + let d1 = (q0 * -25.0 + q1 * 48.0 + q2 * -36.0 + q3 * 16.0 + q4 * -3.0) * (sgn / (12.0 * h)); + let d2 = (q0 * 35.0 + q1 * -104.0 + q2 * 114.0 + q3 * -56.0 + q4 * 11.0) * (1.0 / (12.0 * h * h)); + let d3 = (q0 * -5.0 + q1 * 18.0 + q2 * -24.0 + q3 * 14.0 + q4 * -3.0) * (sgn / (2.0 * h * h * h)); + let (t, bend, change) = shape(d1, d2, d3)?; + Ok((q0, t, bend, change)) +} + +/// How far the rebuilt surface strays from the original one: the root mean square of the +/// distances from a grid of its samples to the original surface. +fn deviation(made: &mt::Face, original: &mt::Face) -> Result { + let (surf, os) = (made.surface(), original.surface()); + let ranges = ranges(made)?; + let mut sum = 0.0f64; + let mut n = 0usize; + for i in 0..GRID { + for j in 0..GRID { + let u = ranges[0].0 + (ranges[0].1 - ranges[0].0) * i as f64 / (GRID - 1) as f64; + let v = ranges[1].0 + (ranges[1].1 - ranges[1].0) * j as f64 / (GRID - 1) as f64; + let q = from_p3(surf.subs(u, v)); + let Some((a, b)) = os.search_nearest_parameter(p3(q), None, 100) else { continue }; + let d = from_p3(os.subs(a, b)).dist(q); + if d.is_finite() { + sum += d * d; + n += 1; + } + } + } + if n == 0 { + return Err(KernelError::Failed("match: the original surface cannot be sampled".into())); + } + Ok((sum / n as f64).sqrt()) +} + +#[cfg(test)] +#[path = "matchsurf_tests.rs"] +mod tests; diff --git a/crates/kernel/src/matchsurf_tests.rs b/crates/kernel/src/matchsurf_tests.rs new file mode 100644 index 000000000..f99066be4 --- /dev/null +++ b/crates/kernel/src/matchsurf_tests.rs @@ -0,0 +1,225 @@ +//! Tests of surface matching: a sheet is rebuilt to meet a cylinder's wall up to G1, G2 and G3, +//! its seam, its far boundary and its interior are measured, and what cannot be matched is +//! refused. + +use super::*; +use crate::bridge::{Continuity, Frame}; +use crate::build::SEAM_ANGLE; +use crate::{cylinder, stitch}; +use solidcraft_geom::Vec3; +use truck_modeling as mt; + +/// The radius of the cylinder a sheet is matched to, the radius the sheet starts at, its height, +/// and how far round the cylinder the sheet runs. +const R_TARGET: f64 = 10.0; +const R_SHEET: f64 = 11.0; +const HEIGHT: f64 = 30.0; +const SPAN: f64 = 0.6; + +/// A point on the vertical line at radius `r`, angle `a`, height `z` (Z up). +fn at(a: f64, r: f64, z: f64) -> Vec3 { + Vec3::new(r * a.cos(), r * a.sin(), z) +} + +/// The outward radial and the circumferential unit directions at the angle `a`. +fn radial(a: f64) -> Vec3 { + Vec3::new(a.cos(), a.sin(), 0.0) +} + +fn circ(a: f64) -> Vec3 { + Vec3::new(-a.sin(), a.cos(), 0.0) +} + +/// A cylindrical sheet of radius `r` between the angles `a0` and `a1`, `stations` high: the body +/// a match rebuilds. Its near boundary is the vertical line at `a0`, its far boundary at `a1`. +fn cylinder_sheet(r: f64, a0: f64, a1: f64, stations: usize) -> Body { + let mut a = Vec::new(); + let mut b = Vec::new(); + for i in 0..stations { + let z = HEIGHT * i as f64 / (stations - 1) as f64; + a.push(Frame { p: at(a0, r, z), leave: circ(a0), bend: radial(a0) * (-1.0 / r), bend_change: Vec3::ZERO }); + b.push(Frame { p: at(a1, r, z), leave: circ(a1) * -1.0, bend: radial(a1) * (-1.0 / r), bend_change: Vec3::ZERO }); + } + bridge::bridge(&a, &b, [Continuity::G2, Continuity::G2], [0.0, 0.0]).unwrap() +} + +/// The stock cylinder, and two picks on the vertical seam line of its wall. +fn cylinder_and_picks() -> (Body, [Vec3; 2]) { + let c = cylinder(Vec3::ZERO, Vec3::new(0.0, 0.0, 1.0), R_TARGET, HEIGHT).unwrap(); + (c, [at(SEAM_ANGLE, R_TARGET, 6.0), at(SEAM_ANGLE, R_TARGET, 24.0)]) +} + +/// The sheet of the usual shape, and a pick on its near boundary. +fn sheet_and_pick() -> (Body, [Vec3; 1]) { + (cylinder_sheet(R_SHEET, SEAM_ANGLE, SEAM_ANGLE + SPAN, 9), [at(SEAM_ANGLE, R_SHEET, HEIGHT * 0.5)]) +} + +/// The middle of the edge of `body`'s first face nearest `p`. +fn edge_at(body: &Body, p: Vec3) -> mt::Edge { + let face = body.solid.face_iter().next().unwrap(); + let mut best: Option<(f64, mt::Edge)> = None; + for e in face.edge_iter() { + let c = e.curve(); + let (t0, t1) = c.range_tuple(); + let m = from_p3(c.subs(0.5 * (t0 + t1))); + let d = m.dist(p); + if best.as_ref().is_none_or(|(b, _)| d < *b) { + best = Some((d, e.clone())); + } + } + best.unwrap().1 +} + +/// How far the rebuilt face's far boundary lies from the original one, in mm: the far row of the +/// rebuilt surface sampled at its own stations, against the original boundary edge's own points. +fn far_drift(made: &Body, sheet: &Body, far_mid: Vec3) -> f64 { + let face = made.solid.face_iter().next().unwrap(); + let surf = face.surface(); + let (Some((u0, u1)), Some((_, v1))) = surf.try_range_tuple() else { panic!("unbounded") }; + let edge = edge_at(sheet, far_mid); + let poly = chain_polyline(&[edge]).unwrap(); + let mut worst = 0.0f64; + for k in 0..=8 { + let p = from_p3(surf.subs(u0 + (u1 - u0) * k as f64 / 8.0, v1)); + worst = worst.max(chain_distance(&poly, p)); + } + worst +} + +/// What the rebuilt sheet does at the normalized station `t` of its matching boundary: the +/// point, the unit tangent, the curvature vector and the change of that curvature, read off the +/// finished surface (never from the construction). +fn seam_at(body: &Body, t: f64) -> (Vec3, Vec3, Vec3, Vec3) { + let face = body.solid.face_iter().next().unwrap(); + let ranges = super::ranges(face).unwrap(); + super::seam_shape(&face.surface(), &ranges, Side::V0, t).unwrap() +} + +/// The stations a seam is measured at, as fractions of its length. +fn stations() -> Vec { + (0..9).map(|k| k as f64 / 8.0).collect() +} + +#[test] +fn a_g2_match_meets_a_cylinder_with_its_own_curvature() { + let (target, picks) = cylinder_and_picks(); + let (sheet, pick) = sheet_and_pick(); + let made = match_surface(&sheet, &pick, &target, &picks, Continuity::G2).unwrap(); + // The rebuilt boundary has moved onto the picked line: the seam is on the cylinder's wall. + assert!(seam_at(&made, 0.5).0.dist(at(SEAM_ANGLE, R_TARGET, HEIGHT * 0.5)) < 1e-6, "the seam is on the picked line"); + let (gap, deg, order) = seam_continuity(&made, &target, &picks).unwrap(); + println!("g2: gap {gap:e} mm, normal {deg:e} deg, order {order:?}"); + assert!(gap < 1e-6, "position gap {gap:e}"); + assert!(deg < 0.01, "normal angle {deg}"); + assert!(order.conditions() >= Continuity::G2.conditions(), "{order:?}"); + // The curvature the cylinder bends with along the seam: matched to a thousandth of itself. + let want = radial(SEAM_ANGLE) * (-1.0 / R_TARGET); + let mut worst = 0.0f64; + for t in stations() { + worst = worst.max(seam_at(&made, t).2.dist(want) * R_TARGET); + } + println!("g2: worst curvature jump {worst:e} of the cylinder's own"); + assert!(worst < 1e-3, "curvature jump {worst:e}"); + // The far boundary did not move: it is built through the original boundary's own points and + // stays on the original edge between them to round-off. + let far = at(SEAM_ANGLE + SPAN, R_SHEET, HEIGHT * 0.5); + let drift = far_drift(&made, &sheet, far); + println!("g2: far boundary drift {drift:e} mm"); + assert!(drift < 1e-9, "the far boundary drifted {drift:e} mm"); + // The interior stays near the original: the crowning that leaves it closest. + let (face, original) = (made.solid.face_iter().next().unwrap().clone(), sheet.solid.face_iter().next().unwrap().clone()); + let stray = deviation(&face, &original).unwrap(); + println!("g2: interior stray {stray:.6} mm rms"); + // The seam moved 1 mm, so the face cannot be closer than that at the seam itself: over the + // whole face the root mean square distance is well under half of it. + assert!(stray < 0.6, "the interior strays {stray} mm"); +} + +#[test] +fn a_g1_match_holds_the_tangent_and_leaves_the_curvature_free() { + let (target, picks) = cylinder_and_picks(); + let (sheet, pick) = sheet_and_pick(); + let made = match_surface(&sheet, &pick, &target, &picks, Continuity::G1).unwrap(); + let (gap, deg, order) = seam_continuity(&made, &target, &picks).unwrap(); + let want = radial(SEAM_ANGLE) * (-1.0 / R_TARGET); + let worst = stations().into_iter().map(|t| seam_at(&made, t).2.dist(want) * R_TARGET).fold(0.0f64, f64::max); + println!("g1: gap {gap:e} mm, normal {deg:e} deg, order {order:?}, curvature jump {worst:e}"); + assert!(gap < 1e-6 && deg < 0.01, "position {gap:e}, normal {deg}"); + assert_eq!(order, Continuity::G1, "a tangent match leaves the curvature free"); + assert!(worst > 1e-3, "a G1 match need not hold the curvature: {worst:e}"); + // The far boundary is kept whatever the order. + let far = at(SEAM_ANGLE + SPAN, R_SHEET, HEIGHT * 0.5); + assert!(far_drift(&made, &sheet, far) < 1e-9); +} + +#[test] +fn a_g3_match_holds_the_change_of_curvature() { + let (target, picks) = cylinder_and_picks(); + let (sheet, pick) = sheet_and_pick(); + let made = match_surface(&sheet, &pick, &target, &picks, Continuity::G3).unwrap(); + let (gap, deg, order) = seam_continuity(&made, &target, &picks).unwrap(); + let want = radial(SEAM_ANGLE) * (-1.0 / R_TARGET); + let (mut bend, mut change) = (0.0f64, 0.0f64); + for t in stations() { + let (_, _, b, c) = seam_at(&made, t); + bend = bend.max(b.dist(want) * R_TARGET); + // A cylinder's curvature does not change in its own surface: the normal part of the + // change of curvature across the seam must be zero too. + change = change.max(c.dot(radial(SEAM_ANGLE)).abs() * R_TARGET * R_TARGET); + } + println!("g3: gap {gap:e} mm, normal {deg:e} deg, order {order:?}, curvature jump {bend:e}, change {change:e}"); + assert!(gap < 1e-6 && deg < 0.01, "position {gap:e}, normal {deg}"); + assert_eq!(order, Continuity::G3, "the seam holds the change of curvature"); + assert!(bend < 1e-3, "curvature jump {bend:e}"); + assert!(change < 1e-3, "change of curvature {change:e}"); + let far = at(SEAM_ANGLE + SPAN, R_SHEET, HEIGHT * 0.5); + assert!(far_drift(&made, &sheet, far) < 1e-9); +} + +#[test] +fn a_match_refuses_what_it_cannot_hold() { + let (target, picks) = cylinder_and_picks(); + let (sheet, pick) = sheet_and_pick(); + // No pick on the body's face, no pick on the target's edges, and picks that are not numbers. + assert!(match_surface(&sheet, &[], &target, &picks, Continuity::G1).is_err()); + assert!(match_surface(&sheet, &[Vec3::new(0.0, 0.0, 100.0)], &target, &picks, Continuity::G1).is_err()); + assert!(match_surface(&sheet, &[Vec3::new(f64::NAN, 0.0, 0.0)], &target, &picks, Continuity::G1).is_err()); + assert!(match_surface(&sheet, &vec![Vec3::ZERO; MAX_PICKS + 1], &target, &picks, Continuity::G1).is_err()); + assert!(match_surface(&sheet, &pick, &target, &[], Continuity::G1).is_err()); + // A pick that is not on the target at all, and one in the middle of its wall: no chain there. + assert!(match_surface(&sheet, &pick, &target, &[Vec3::new(100.0, 0.0, 15.0)], Continuity::G1).is_err()); + assert!(match_surface(&sheet, &pick, &target, &[Vec3::new(10.0, 0.0, 15.0)], Continuity::G1).is_err()); + // A body that is not a surface: the stock cylinder itself. + assert!(match_surface(&target, &[at(SEAM_ANGLE, R_TARGET, 15.0)], &target, &picks, Continuity::G1).is_err()); +} + +#[test] +fn a_target_that_jumps_in_curvature_supplies_only_g1() { + // Two sheets of the target meet along a line with the same tangent plane but different + // curvature: a cylinder's wall and the plane tangent to it there. The target itself does not + // hold the curvature along that line, so no match may be told to. + let wall = cylinder_sheet(R_TARGET, SEAM_ANGLE, SEAM_ANGLE + 0.5, 5); + let mut a = Vec::new(); + let mut b = Vec::new(); + for i in 0..5 { + let z = HEIGHT * i as f64 / 4.0; + let (p, q) = (at(SEAM_ANGLE, R_TARGET, z), at(SEAM_ANGLE, R_TARGET, z) + circ(SEAM_ANGLE) * 8.0); + a.push(Frame { p, leave: circ(SEAM_ANGLE), bend: Vec3::ZERO, bend_change: Vec3::ZERO }); + b.push(Frame { p: q, leave: circ(SEAM_ANGLE) * -1.0, bend: Vec3::ZERO, bend_change: Vec3::ZERO }); + } + let plane = bridge::bridge(&a, &b, [Continuity::G2, Continuity::G2], [0.0, 0.0]).unwrap(); + let joined = stitch(&[&wall, &plane], 1e-6).unwrap(); + assert_eq!(joined.solid.face_iter().count(), 2, "the two sheets sewed into one body"); + let picks = [at(SEAM_ANGLE, R_TARGET, 6.0), at(SEAM_ANGLE, R_TARGET, 24.0)]; + let (sheet, pick) = sheet_and_pick(); + // The seam is smooth enough to match, so G1 goes through; the curvature jumps there, so G2 + // and G3 do not. + assert!(match_surface(&sheet, &pick, &joined, &picks, Continuity::G1).is_ok()); + let err = match_surface(&sheet, &pick, &joined, &picks, Continuity::G2).unwrap_err().to_string(); + println!("refused g2: {err}"); + assert!(err.contains("only g1"), "{err}"); + assert!(match_surface(&sheet, &pick, &joined, &picks, Continuity::G3).is_err()); + // The plain cylinder, whose two wall faces are the same surface, supplies G3. + let (target, plain_picks) = cylinder_and_picks(); + assert!(match_surface(&sheet, &pick, &target, &plain_picks, Continuity::G3).is_ok()); +} diff --git a/crates/sketch/src/model.rs b/crates/sketch/src/model.rs index 493df7b01..655818777 100644 --- a/crates/sketch/src/model.rs +++ b/crates/sketch/src/model.rs @@ -1289,8 +1289,8 @@ impl Sketch { } /// Exact boundary segments of a free-form curve: ellipses as four conics, conics, fit - /// splines and control splines up to degree 3 as Béziers. None for other curves (and for - /// higher-degree splines, which stay polylines). + /// splines and control splines up to `MAX_BEZIER_DEGREE` as Béziers. None for other curves + /// (and for higher-degree splines, which stay polylines). pub fn exact_segs(&self, ci: usize) -> Option> { let cu = self.curves.get(ci)?; let pt = |i: &usize| self.point(*i); @@ -1326,6 +1326,17 @@ impl Sketch { } } + /// The exact [`Seg2`] pieces of a curve of any kind, in the curve's own direction of travel: + /// lines, circles and arcs from their analytic form, free-form curves through + /// [`Sketch::exact_segs`]. Empty for a curve with no exact pieces (a spline above + /// `solidcraft_geom::MAX_BEZIER_DEGREE`). + pub fn exact_pieces(&self, ci: usize) -> Vec { + match self.exact_segs(ci) { + Some(segs) => segs, + None => self.segs(ci), + } + } + /// Polyline of a free-form curve (ellipse, spline, conic); other curves: their segments' /// polylines. pub fn polyline(&self, ci: usize) -> Vec { @@ -1375,8 +1386,11 @@ impl Sketch { "e" } CurveKind::Spline { pts, control, degree, periodic } => { - if pts.len() < 2 || pts.len() > crate::curves::MAX_SPLINE_POINTS || !(1..=7).contains(degree) { - return Err(SketchError::Invalid("a spline needs 2 to 500 points and degree 1 to 7".into())); + if pts.len() < 2 || pts.len() > crate::curves::MAX_SPLINE_POINTS || !(1..=solidcraft_geom::MAX_BEZIER_DEGREE as u8).contains(degree) { + return Err(SketchError::Invalid(format!( + "a spline needs 2 to 500 points and degree 1 to {}", + solidcraft_geom::MAX_BEZIER_DEGREE + ))); } if *periodic { if *control || *degree != 3 { diff --git a/docs/screenshots/class-a-boundary.png b/docs/screenshots/class-a-boundary.png new file mode 100644 index 0000000000000000000000000000000000000000..e5f436e963723c18e655a3a2fad6035947aa199a GIT binary patch literal 616830 zcmZs^3tZ24|Noz{VNSy?IaKDfW~R_2D(zr%h+O0Qoh>EFGzuM1G(N^0S`^xZO1rkv z*WW@CC4^3Eqzy|{I#F{`Nh3}A{O`}#`}2uizw36pZntZCf8Ou+^ZhzLpO5F`@qC5; z(`90pm;1hKVq(%|@}vnfOiW(nKij_6;U)g>i(UCoOgb+7VDf}_|0lRj&Dpl!4gPdz zcD+8RcI(d<;{%+%4lOP^ZusBAEqixPIlOn2&A{5G6(<(0+P}%(=l8?4wbprIbN9Ty z*FVQ`YGvm87GDfneXYL#fzJXS6@T!R-SU6;PJXq;(e-sxE4S}I3;64n|Dxf|6Bi91 z8`LuJC6_n{mxK+vh>N$1H@N%SEwAXE+^c0!a)F($yvOiJoA~MfbS^I)WRqG~{J~)V zf8QFpXlV1qJ^Mqwi~YMTUgYrj-7&ugnd>bQhIr?DOgMWWGUq_@{r(4%Z#8E*+vV}k z|4Y7KH`1kNe#+A&uFe(@zU%i#TDX2v!jS4qbpy}ka(&HX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DAms*C~==GhtLPBbYGjBOJZD%{=6YCrR028px`awA~j`+8@ zt<2a-9}gjDn_HWpy8VH2Ae+{Yq0i2JAv}O9Q$I{1vI6K0NxfcqGDo=AV#b>=I+IJ> znjf80XN)&KS;CWOHo6O(jckrrCza%%ZRo2<6dQYl$On^?>zjKp0RMY`-7RMD+_ZT^ xf*HpyTkh_QqWX{xOBtQdvF*Ki>3!eh?3&}Ju2x?E*m^(1ufMO9yLa&9_%9|_*S7!w literal 0 HcmV?d00001 From db1fd39139596ecfcce0c27dfcc9fa33d1c45e5b Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 16 Oct 2026 07:38:05 +0000 Subject: [PATCH 89/92] Regenerate THIRD-PARTY-LICENSES.txt and docs/features.md [skip ci] --- docs/features.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/features.md b/docs/features.md index 3a4bd19ae..996ef0b07 100644 --- a/docs/features.md +++ b/docs/features.md @@ -1,6 +1,6 @@ # Features -SolidCraft's commands by area, generated by `cargo xtask features` from the command registry (`solidcraft-cli commands`). **381 commands.** Planned (registered, not built yet): 3. 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`). **383 commands.** Planned (registered, not built yet): 2. 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 (103) @@ -150,7 +150,7 @@ SolidCraft's commands by area, generated by `cargo xtask features` from the comm | Align | `solid.align` | SOLID › MODIFY | | Remove | `solid.remove` | SOLID › MODIFY | -## Surfaces (15, 2 planned) +## Surfaces (17, 1 planned) | Command | Id | Toolbar | |---|---|---| @@ -165,12 +165,13 @@ SolidCraft's commands by area, generated by `cargo xtask features` from the comm | Surface Loft | `surface.loft` | SURFACE › CREATE | | Offset Surface | `surface.offset` | SURFACE › CREATE | | Ruled Surface | `surface.ruled` | SURFACE › CREATE | -| Boundary Surface *(planned: [#763](https://github.com/bherbruck/solidcraft/issues/763))* | `surface.boundary` | 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 | +| Fair Surface | `surface.fair` | SURFACE › MODIFY | | Surface Fillet *(planned: [#769](https://github.com/bherbruck/solidcraft/issues/769))* | `surface.fillet` | SURFACE › MODIFY | +| Match Surface | `surface.match` | SURFACE › MODIFY | ## Construction geometry (19) From a9beb437b381a421b25283c6271ccad2dc7eb0a3 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Fri, 16 Oct 2026 04:35:53 -0400 Subject: [PATCH 90/92] Boolean property tests: nightly only, and the cases they found as ignored tests (#1650) Pushes to main skip boolean_props (random inputs); the nightly property-tests job runs it. The three shrunk cases are ignored tests with their issues (#1647, #1648, #1649), and proptest's failure file is named outright. Co-Authored-By: Claude Opus 5.5 --- .config/nextest.toml | 3 +- .github/workflows/ci.yml | 9 ++++- CONTRIBUTING.md | 3 +- crates/kernel/tests/boolean_props.rs | 60 ++++++++++++++++++++++++++-- docs/book/src/dev/testing.md | 3 +- 5 files changed, 69 insertions(+), 9 deletions(-) diff --git a/.config/nextest.toml b/.config/nextest.toml index d393c69be..66fe1043d 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -3,7 +3,8 @@ [profile.ci] # Heavy tests (one to four 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`. +# 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. default-filter = """ not ( diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5b6769121..8b523826b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -229,7 +229,11 @@ jobs: run: | # Pull requests skip the heavy tests (default-filter in .config/nextest.toml). all=() - if [ "$EVENT_NAME" != pull_request ]; then all=(--ignore-default-filter); fi + # 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. + 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 \ @@ -319,7 +323,8 @@ jobs: property-tests: # The boolean property tests and the atomic command tests with many cases. Pull requests skip - # them (.config/nextest.toml); pushes to main run them with small defaults (8 cases, seeds 0..4). + # them (.config/nextest.toml); pushes to main run atomic_commands with small defaults (seeds + # 0..4) and skip boolean_props, whose random inputs would fail main at random. name: Property tests (many cases) needs: build-tests if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 095a61afa..b835ed41c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -181,7 +181,8 @@ Pull requests skip a few heavy tests (one to four minutes each), which run on ev `pattern_suppress_tests::enclosure_arc_extinction_keeps_a_real_sharp_inner_lip_after_resize_and_reopen`, `pattern_suppress_tests::enclosure_datums_follow_wall_height_and_board_depth_with_material_proofs`, `cmd::plastic::tests::enclosure_snap_fit_follows_resized_front_wall`, the `atomic_commands` contract tests -- `solidcraft-kernel`: `tests::boolean_identity_on_tangent_primitives`, the `boolean_props` property tests +- `solidcraft-kernel`: `tests::boolean_identity_on_tangent_primitives`, and the `boolean_props` property tests + (these run only in the nightly "Property tests" job: their inputs are random, so main skips them too) - `solidcraft-ui-egui` scenarios: `acceptance_sensor_enclosure` **The action matrix** tries every ordinary action on every face, edge, vertex and body of a diff --git a/crates/kernel/tests/boolean_props.rs b/crates/kernel/tests/boolean_props.rs index fadecae79..57a7d4657 100644 --- a/crates/kernel/tests/boolean_props.rs +++ b/crates/kernel/tests/boolean_props.rs @@ -4,10 +4,13 @@ //! inputs, and when a case fails it shrinks the inputs to a small case that still fails. Paste //! that case into a normal `#[test]` as a regression test. //! -//! Case count: `PROPTEST_CASES` (default 8). Pull requests skip this file (.config/nextest.toml); -//! pushes to main run it, and the nightly `property-tests` job uses more cases. A long local run: +//! Case count: `PROPTEST_CASES` (default 8). Pull requests and pushes to main skip this file +//! (.config/nextest.toml, .github/workflows/ci.yml): its random inputs differ on every run, so a +//! known kernel bug would turn main red at random. The nightly `property-tests` job runs it with +//! more cases. A long local run: //! `PROPTEST_CASES=2000 cargo test -p solidcraft-kernel --test boolean_props`. -//! proptest saves every failing seed in `tests/boolean_props.proptest-regressions`. Commit it. +//! proptest saves every failing seed in `tests/boolean_props.proptest-regressions`. Commit it, and +//! copy the shrunk case into a `#[test]` below (ignored, with its issue, until the kernel is fixed). use proptest::prelude::*; use solidcraft_geom::Vec3; @@ -102,7 +105,15 @@ 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. let cases = std::env::var("PROPTEST_CASES").ok().and_then(|s| s.parse().ok()).unwrap_or(default); - ProptestConfig { cases, max_shrink_iters: 200, ..ProptestConfig::default() } + // Integration tests have no lib.rs or main.rs beside them, so proptest's default persistence + // cannot place its file; name it. + let file = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/boolean_props.proptest-regressions"); + ProptestConfig { + cases, + max_shrink_iters: 200, + failure_persistence: Some(Box::new(prop::test_runner::FileFailurePersistence::Direct(file))), + ..ProptestConfig::default() + } } proptest! { @@ -218,3 +229,44 @@ proptest! { prop_assert!(close(run(&plate, &boss, BoolOp::Union)?, vp + vb, vp + vb), "plate + boss lost or gained volume"); } } + +// Cases the property tests found, as plain tests. Ignored until the kernel bug is fixed: run them +// with `cargo test -p solidcraft-kernel --test boolean_props -- --ignored`. + +fn check(r: Result<(), TestCaseError>) { + if let Err(e) = r { + panic!("{e}"); + } +} + +/// A box and a cylinder in general position: the intersect is refused as an implausible volume. +#[test] +#[ignore = "kernel bug, #1647"] +fn generic_box_cylinder_intersect() { + let a = Prim::Box { at: [11.483767761089219, 4.801612107504224, 3.6313476467611787], size: [4.789088988834864, 3.0, 10.419335961063835] }; + let b = Prim::Cyl { at: [29.2480632732879, 8.3683289461485, 6.947922225984966], axis: 2, r: 13.502884497756853, h: 19.719218725477496 }; + check(identity(&a, &b)); +} + +/// A sphere and a box on the grid: the union has a face that does not mesh. +#[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] }; + 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"] +fn crossing_cylinders_union_moved_far() { + let a = Prim::Cyl { at: [17.5, 30.0, 7.5], axis: 0, r: 5.0, h: 10.0 }.body(); + let b = Prim::Cyl { at: [17.5, 30.0, 15.0], axis: 1, r: 12.5, h: 5.0 }.body(); + let t = Vec3::new(1000.0, -700.0, 300.0); + let mv = |x: &Body| transform(x, t, Vec3::ZERO, Vec3::Z, 0.0).expect("translate"); + let s = vol(&a) + vol(&b); + let here = run(&a, &b, BoolOp::Union).unwrap(); + let there = run(&mv(&a), &mv(&b), BoolOp::Union).unwrap(); + assert!(close(here, there, s), "union at origin {here:.4}, moved by 1000 gives {there:.4}"); +} diff --git a/docs/book/src/dev/testing.md b/docs/book/src/dev/testing.md index 105160b5b..e275dc42a 100644 --- a/docs/book/src/dev/testing.md +++ b/docs/book/src/dev/testing.md @@ -81,7 +81,8 @@ Pull requests skip a few heavy tests (each takes one to four minutes); they run `pattern_suppress_tests::enclosure_arc_extinction_keeps_a_real_sharp_inner_lip_after_resize_and_reopen`, `pattern_suppress_tests::enclosure_datums_follow_wall_height_and_board_depth_with_material_proofs`, `cmd::plastic::tests::enclosure_snap_fit_follows_resized_front_wall`, the `atomic_commands` contract tests -- `solidcraft-kernel`: `tests::boolean_identity_on_tangent_primitives`, the `boolean_props` property tests +- `solidcraft-kernel`: `tests::boolean_identity_on_tangent_primitives`, and the `boolean_props` property tests + (these run only in the nightly "Property tests" job: their inputs are random, so main skips them too) - `solidcraft-ui-egui` scenarios: `acceptance_sensor_enclosure` The **action matrix** (`apps/solidcraft-cli/tests/action_matrix.rs`) tries every ordinary action From 9d82b944691529c806cd4e87acc032577f72eaf1 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Fri, 16 Oct 2026 04:55:20 -0400 Subject: [PATCH 91/92] Robustness goldens: record seeds 31 and 83 after #1581 and #1495 (#1657) Seed 31: #1581 refuses a fillet selection with an earlier round's smooth seam instead of re-rounding another nearby edge. Seed 83: #1316 was recorded before its branch took in #1495, whose shell keeps the wall beside a concave edge. Co-Authored-By: Claude Opus 5.5 --- tests/robustness/goldens.json | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/tests/robustness/goldens.json b/tests/robustness/goldens.json index 12d35e350..7b265c10c 100644 --- a/tests/robustness/goldens.json +++ b/tests/robustness/goldens.json @@ -32,7 +32,7 @@ "28": {"area":2394.691384,"bodies":1,"edges":15,"error":null,"faces":9,"outcome":"ok","rejected":0,"shells":2,"steps":["revolved section","join cylinder"],"unsupported":0,"volume":5902.121375}, "29": {"area":6965.599057,"bodies":1,"edges":74,"error":null,"faces":30,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","shell","join cylinder"],"unsupported":0,"volume":3977.885339}, "30": {"area":853.525389,"bodies":1,"edges":23,"error":null,"faces":10,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","chamfer"],"unsupported":0,"volume":1337.14821}, - "31": {"area":10198.42294,"bodies":3,"edges":67,"error":null,"faces":29,"outcome":"ok","rejected":1,"shells":3,"steps":["box","cut box","fillet","join box","fillet","circular pattern","cut box","circular pattern"],"unsupported":0,"volume":56408.3612}, + "31": {"area":10221.945046,"bodies":3,"edges":68,"error":null,"faces":29,"outcome":"ok","rejected":2,"shells":3,"steps":["box","cut box","fillet","join box","circular pattern","cut box","circular pattern","hole"],"unsupported":0,"volume":56397.581359}, "32": {"area":3220.802769,"bodies":1,"edges":51,"error":null,"faces":19,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","cut sphere","cut box","cut box","join box"],"unsupported":0,"volume":7565.955897}, "33": {"area":5286.736353,"bodies":2,"edges":59,"error":null,"faces":27,"outcome":"ok","rejected":0,"shells":3,"steps":["revolved section","fillet","join box","cut cylinder","chamfer","join box","chamfer","fillet"],"unsupported":2,"volume":13858.467983}, "34": {"area":1086.305562,"bodies":1,"edges":30,"error":null,"faces":14,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","cut sphere","hole"],"unsupported":0,"volume":2134.365275}, @@ -84,7 +84,7 @@ "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}, "81": {"area":4001.847983,"bodies":2,"edges":75,"error":null,"faces":29,"outcome":"ok","rejected":1,"shells":2,"steps":["revolved section","cut sphere","circular pattern","rectangular pattern","hole","join cylinder","join box","cut sphere"],"unsupported":2,"volume":13139.658749}, "82": {"area":3195.487112,"bodies":1,"edges":30,"error":null,"faces":13,"outcome":"ok","rejected":0,"shells":1,"steps":["box","hole","circular pattern","cut box"],"unsupported":0,"volume":5902.162954}, - "83": {"area":8489.059183,"bodies":1,"edges":97,"error":null,"faces":35,"outcome":"ok","rejected":0,"shells":2,"steps":["box","join box","rectangular pattern","shell","fillet","cut sphere","join box"],"unsupported":1,"volume":6217.394627}, + "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}, @@ -125,6 +125,7 @@ {"reason":"Seed 83 builds: a shell splits a saddle corner (convex and concave edges in turn) into two corners","seeds":[83]}, {"reason":"seed 15 now cuts around a sealed void","seeds":[15]}, {"reason":"#1490: when the last-resort nudge fails both ways, two more screw axes are tried; seed 63's final box join (its face 0.00005 mm off the half-ring's cut face) now builds instead of being refused with an implausible volume, and the design goes on to its fillet","seeds":[63]}, - {"reason":"a prism cut in a column round the tool (prism_local): seed 65's rectangular pattern (step 4, a second half-cylinder groove overlapping the first, in a block with a rounded vertical edge) is now built by the exact 2D route in a column clear of the round, where the B-rep tries left it with split edges. The step's part has the 10 faces, 24 edges and 16 vertices it should (28 edges and 18 vertices before), and its volume is 45145.383 mm³ against 45145.214 (exactly 45145.103, both within the mesh measure); the generator then picks other edges for its step 7 fillet, so the run ends on another design (45143.48 mm³, 15 faces)","seeds":[65]} + {"reason":"a prism cut in a column round the tool (prism_local): seed 65's rectangular pattern (step 4, a second half-cylinder groove overlapping the first, in a block with a rounded vertical edge) is now built by the exact 2D route in a column clear of the round, where the B-rep tries left it with split edges. The step's part has the 10 faces, 24 edges and 16 vertices it should (28 edges and 18 vertices before), and its volume is 45145.383 mm³ against 45145.214 (exactly 45145.103, both within the mesh measure); the generator then picks other edges for its step 7 fillet, so the run ends on another design (45143.48 mm³, 15 faces)","seeds":[65]}, + {"reason":"Seed 31: #1581 no longer maps a pick on an earlier round's seam to some other nearby edge; the second fillet's selection includes the smooth seam at [2, 27.5, 13.5] beside the first round, which is now refused (no corner to round) instead of silently re-rounding a different edge at 1 mm, so the run goes on to a hole. Seed 83: #1316 was recorded before its branch took in #1495; with #1495's shell (an open face next to a concave edge no longer cuts the wall past it) the shelled part keeps more wall (6217 to 6339 mm3), its edges differ, and the 2.5 mm fillet of the first run is not picked; a later fillet is refused as not supported yet (an end face parallel to the edge)","seeds":[31,83]} ] } From cedb51b8ea35bf5a0dba207c83be54b1f3866ca1 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Fri, 16 Oct 2026 09:19:10 +0000 Subject: [PATCH 92/92] Release 0.14.0 Version 0.14.0; the pending design-format changes are folded into format 25. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 30 +++++++++---------- Cargo.toml | 2 +- .../{pending => v25}/class-a-surfaces.rs | 0 .../feature-pattern-alignment.rs | 0 .../{pending => v25}/flipped-sketch-plane.rs | 0 .../{pending => v25}/infinite-sketch-lines.rs | 0 .../patch-continuity-and-points.rs | 0 .../{pending => v25}/placed-plane-origins.rs | 0 .../sketch-pattern-directions.rs | 0 .../{pending => v25}/split-by-sketch-line.rs | 0 10 files changed, 16 insertions(+), 16 deletions(-) rename crates/doc/src/format/{pending => v25}/class-a-surfaces.rs (100%) rename crates/doc/src/format/{pending => v25}/feature-pattern-alignment.rs (100%) rename crates/doc/src/format/{pending => v25}/flipped-sketch-plane.rs (100%) rename crates/doc/src/format/{pending => v25}/infinite-sketch-lines.rs (100%) rename crates/doc/src/format/{pending => v25}/patch-continuity-and-points.rs (100%) rename crates/doc/src/format/{pending => v25}/placed-plane-origins.rs (100%) rename crates/doc/src/format/{pending => v25}/sketch-pattern-directions.rs (100%) rename crates/doc/src/format/{pending => v25}/split-by-sketch-line.rs (100%) diff --git a/Cargo.lock b/Cargo.lock index 88f732ed5..1fa23852d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4051,7 +4051,7 @@ dependencies = [ [[package]] name = "solidcraft" -version = "0.13.1" +version = "0.14.0" dependencies = [ "block2 0.6.2", "eframe", @@ -4080,7 +4080,7 @@ dependencies = [ [[package]] name = "solidcraft-cli" -version = "0.13.1" +version = "0.14.0" dependencies = [ "image", "serde_json", @@ -4091,7 +4091,7 @@ dependencies = [ [[package]] name = "solidcraft-derive" -version = "0.13.1" +version = "0.14.0" dependencies = [ "proc-macro2", "quote", @@ -4100,7 +4100,7 @@ dependencies = [ [[package]] name = "solidcraft-doc" -version = "0.13.1" +version = "0.14.0" dependencies = [ "log", "serde", @@ -4117,7 +4117,7 @@ dependencies = [ [[package]] name = "solidcraft-engine" -version = "0.13.1" +version = "0.14.0" dependencies = [ "log", "serde", @@ -4133,7 +4133,7 @@ dependencies = [ [[package]] name = "solidcraft-geom" -version = "0.13.1" +version = "0.14.0" dependencies = [ "serde", "serde_json", @@ -4142,7 +4142,7 @@ dependencies = [ [[package]] name = "solidcraft-gpu" -version = "0.13.1" +version = "0.14.0" dependencies = [ "log", "naga", @@ -4159,7 +4159,7 @@ dependencies = [ [[package]] name = "solidcraft-io" -version = "0.13.1" +version = "0.14.0" dependencies = [ "cadmpeg-core", "cadmpeg-ir", @@ -4178,7 +4178,7 @@ dependencies = [ [[package]] name = "solidcraft-kernel" -version = "0.13.1" +version = "0.14.0" dependencies = [ "log", "proptest", @@ -4197,7 +4197,7 @@ dependencies = [ [[package]] name = "solidcraft-mcp" -version = "0.13.1" +version = "0.14.0" dependencies = [ "serde_json", "solidcraft-engine", @@ -4206,7 +4206,7 @@ dependencies = [ [[package]] name = "solidcraft-render" -version = "0.13.1" +version = "0.14.0" dependencies = [ "image", "moxcms", @@ -4219,7 +4219,7 @@ dependencies = [ [[package]] name = "solidcraft-sketch" -version = "0.13.1" +version = "0.14.0" dependencies = [ "serde", "serde_json", @@ -4230,7 +4230,7 @@ dependencies = [ [[package]] name = "solidcraft-ui-egui" -version = "0.13.1" +version = "0.14.0" dependencies = [ "egui", "egui-wgpu", @@ -4251,7 +4251,7 @@ dependencies = [ [[package]] name = "solidcraft-web" -version = "0.13.1" +version = "0.14.0" dependencies = [ "eframe", "egui", @@ -5750,7 +5750,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7" [[package]] name = "xtask" -version = "0.13.1" +version = "0.14.0" dependencies = [ "serde_json", "sha2 0.10.9", diff --git a/Cargo.toml b/Cargo.toml index 8955c336a..d48e8a619 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,7 +5,7 @@ members = ["crates/*", "apps/*", "xtask"] exclude = ["vendor"] [workspace.package] -version = "0.13.1" +version = "0.14.0" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" diff --git a/crates/doc/src/format/pending/class-a-surfaces.rs b/crates/doc/src/format/v25/class-a-surfaces.rs similarity index 100% rename from crates/doc/src/format/pending/class-a-surfaces.rs rename to crates/doc/src/format/v25/class-a-surfaces.rs diff --git a/crates/doc/src/format/pending/feature-pattern-alignment.rs b/crates/doc/src/format/v25/feature-pattern-alignment.rs similarity index 100% rename from crates/doc/src/format/pending/feature-pattern-alignment.rs rename to crates/doc/src/format/v25/feature-pattern-alignment.rs diff --git a/crates/doc/src/format/pending/flipped-sketch-plane.rs b/crates/doc/src/format/v25/flipped-sketch-plane.rs similarity index 100% rename from crates/doc/src/format/pending/flipped-sketch-plane.rs rename to crates/doc/src/format/v25/flipped-sketch-plane.rs diff --git a/crates/doc/src/format/pending/infinite-sketch-lines.rs b/crates/doc/src/format/v25/infinite-sketch-lines.rs similarity index 100% rename from crates/doc/src/format/pending/infinite-sketch-lines.rs rename to crates/doc/src/format/v25/infinite-sketch-lines.rs diff --git a/crates/doc/src/format/pending/patch-continuity-and-points.rs b/crates/doc/src/format/v25/patch-continuity-and-points.rs similarity index 100% rename from crates/doc/src/format/pending/patch-continuity-and-points.rs rename to crates/doc/src/format/v25/patch-continuity-and-points.rs diff --git a/crates/doc/src/format/pending/placed-plane-origins.rs b/crates/doc/src/format/v25/placed-plane-origins.rs similarity index 100% rename from crates/doc/src/format/pending/placed-plane-origins.rs rename to crates/doc/src/format/v25/placed-plane-origins.rs diff --git a/crates/doc/src/format/pending/sketch-pattern-directions.rs b/crates/doc/src/format/v25/sketch-pattern-directions.rs similarity index 100% rename from crates/doc/src/format/pending/sketch-pattern-directions.rs rename to crates/doc/src/format/v25/sketch-pattern-directions.rs diff --git a/crates/doc/src/format/pending/split-by-sketch-line.rs b/crates/doc/src/format/v25/split-by-sketch-line.rs similarity index 100% rename from crates/doc/src/format/pending/split-by-sketch-line.rs rename to crates/doc/src/format/v25/split-by-sketch-line.rs

fo0JRwh-zD=PXVxFn z7#A9*N4Oyj^(28)j8t#Iw%JK$5hAMCTkn^;{kPGg)kK14=qc=!5s2If#o`}IYSd2a zRmhjZTChTw+Nm6U;zmViwTz`z@#J98w$;cwkBdZeALEJ!9>QvY;ILO7;=Rp6cp1Um z6lTa)p~_&9=FGIJ*w8hPnle9^L|#U6xgZkZocTb>^dbfsneC;(q0->Yvw8YXu;TDXyv?!TKSR|@0-d!B#9&i5V9 zY6B~&KMIHki_lMS`T|h1H4*n{;0FYBcQHOdVNz3Q!&p7~{O}e|n*|QSzRJEc9nj;- z%4Ge1U&{;ALowq!pZkt&Uee7L3%PH}wzZEUZYEGzl9}+B9^8F3!m@G-K#`1Prr?F2EnNH*q0lj8 zUW*f%5Q>msyahFZf|C+|Z+8DG=CV zV~HTP;Cb71Mh^uT1))jaCi4MoRD%XEHd9l(Ieo>ZgM=EJJN1a2q&xmue!Iw&()JIz zWK2}z4QMPxi&V*I!2|1uXO$Ap7dlB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