Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
097b8b7550 | ||
|
|
f120285c96 | ||
|
|
af7ca3a8a2 | ||
|
|
b31fddb98e | ||
|
|
27ddb725c7 | ||
|
|
2bf3d4e11f | ||
|
|
9852a2e758 | ||
|
|
a05a0f1053 | ||
|
|
60efbe39e3 | ||
|
|
9e20a373ca | ||
|
|
2f55a39c9c | ||
|
|
80fd2fbbf1 | ||
|
|
c3d1ce8237 | ||
|
|
567bc50723 | ||
|
|
1a5fcd05d6 | ||
|
|
3a6153d18f | ||
|
|
d273c45de6 | ||
|
|
da46c660df | ||
|
|
92d1331978 | ||
|
|
01bbc0aa9f | ||
|
|
dbbad6d4ee | ||
|
|
4f69e6540c | ||
|
|
55608665ef | ||
|
|
0fb4a3e868 | ||
|
|
2dc31a30d4 | ||
|
|
8b68eb7eac | ||
|
|
96679f3e2b | ||
|
|
3ba17bb517 | ||
|
|
ae3b36ac88 | ||
|
|
5367ef4367 | ||
|
|
caa1e6e196 | ||
|
|
8bd17cea42 | ||
|
|
4256775274 | ||
|
|
5962f56f87 | ||
|
|
b6a45b8278 | ||
|
|
8ae90f9667 | ||
|
|
17f0d6bc68 | ||
|
|
8b1a722f06 | ||
|
|
63d81cc096 | ||
|
|
46a8f86e80 | ||
|
|
94279fe059 | ||
|
|
867df396ea | ||
|
|
858e5995d6 | ||
|
|
edf57cec29 | ||
|
|
0c72ad56d2 | ||
|
|
92d3a2fde5 | ||
|
|
b0048a6104 | ||
|
|
0db2abbeca | ||
|
|
9761d75699 |
No files matched your search
@@ -203,6 +203,8 @@ jobs:
|
||||
name: Snap ${{ matrix.arch }}
|
||||
needs: [version, linux]
|
||||
if: needs.version.outputs.build == 'true'
|
||||
# The Snap Store hasn't accepted SolidCraft yet, so a snap failure never holds up a release.
|
||||
continue-on-error: true
|
||||
# Repackages the Linux job's tarball, like the Flatpak. On 24.04 because the core24 base is
|
||||
# Ubuntu 24.04, which lets snapcraft build on the runner itself (--destructive-mode).
|
||||
runs-on: ${{ matrix.runner }}
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
/.claude/worktrees/
|
||||
/target-snapshot
|
||||
__pycache__/
|
||||
.vscode/
|
||||
|
||||
# cargo-mutants output (docs/mutation-testing.md)
|
||||
mutants.out*/
|
||||
@@ -14,6 +14,7 @@ Editable drawing code, native projects and shipped exports are collected under `
|
||||
|
||||
| File | Author | Source | Licence |
|
||||
|---|---|---|---|
|
||||
| examples/chebyshev-motion-trace.json | SolidCraft contributors | Original parametric Chebyshev lambda mechanism and associative-trace demo, constructed from analytic circle intersections; classical link proportions documented at https://doi.org/10.1002/rcs.70095; no external CAD geometry or artwork | MIT OR Apache-2.0 |
|
||||
| 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/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 |
|
||||
@@ -107,7 +108,7 @@ Editable drawing code, native projects and shipped exports are collected under `
|
||||
| assets/icons/app/linux/exports/hicolor/48x48/apps/ai.storyteller.solidcraft.png | SolidCraft contributors | Generated from assets/icons/app/shared/source/app_icon.rs with the original CLI/ICO encoders | MIT OR Apache-2.0 |
|
||||
| assets/icons/app/linux/exports/hicolor/512x512/apps/ai.storyteller.solidcraft.png | SolidCraft contributors | Generated from assets/icons/app/shared/source/app_icon.rs with the original CLI/ICO encoders | MIT OR Apache-2.0 |
|
||||
| assets/icons/app/linux/exports/hicolor/64x64/apps/ai.storyteller.solidcraft.png | SolidCraft contributors | Generated from assets/icons/app/shared/source/app_icon.rs with the original CLI/ICO encoders | MIT OR Apache-2.0 |
|
||||
| assets/icons/app/shared/source/app_icon.rs | SolidCraft contributors | Original SolidCraft resource data or drawing code, collected without redesign | MIT OR Apache-2.0 |
|
||||
| assets/icons/app/shared/source/app_icon.rs | SolidCraft contributors | Original SolidCraft drawing code: the borderless mark, drawn from the faces and gradients of assets/icons/app/macos/source/SolidCraft.icon/Assets/03-solid-blue-cutout.svg | MIT OR Apache-2.0 |
|
||||
| assets/icons/app/shared/source/windows_ico.rs | SolidCraft contributors | Original SolidCraft resource data or drawing code, collected without redesign | MIT OR Apache-2.0 |
|
||||
| assets/icons/app/windows/exports/solidcraft-executable.ico | SolidCraft contributors | Generated from assets/icons/app/shared/source/app_icon.rs with the original CLI/ICO encoders | MIT OR Apache-2.0 |
|
||||
| assets/icons/app/windows/exports/solidcraft.ico | SolidCraft contributors | Generated from assets/icons/app/shared/source/app_icon.rs with the original CLI/ICO encoders | MIT OR Apache-2.0 |
|
||||
|
||||
@@ -4162,7 +4162,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "solidcraft"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0-rc.1"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"eframe",
|
||||
@@ -4193,11 +4193,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "solidcraft-3dx-client"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0-rc.1"
|
||||
|
||||
[[package]]
|
||||
name = "solidcraft-cli"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0-rc.1"
|
||||
dependencies = [
|
||||
"image",
|
||||
"log",
|
||||
@@ -4209,7 +4209,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "solidcraft-derive"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0-rc.1"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
@@ -4218,7 +4218,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "solidcraft-doc"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0-rc.1"
|
||||
dependencies = [
|
||||
"log",
|
||||
"serde",
|
||||
@@ -4235,7 +4235,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "solidcraft-engine"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0-rc.1"
|
||||
dependencies = [
|
||||
"log",
|
||||
"schemars",
|
||||
@@ -4254,7 +4254,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "solidcraft-geom"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0-rc.1"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -4263,7 +4263,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "solidcraft-gpu"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0-rc.1"
|
||||
dependencies = [
|
||||
"log",
|
||||
"naga",
|
||||
@@ -4280,7 +4280,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "solidcraft-io"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0-rc.1"
|
||||
dependencies = [
|
||||
"cadmpeg-core",
|
||||
"cadmpeg-ir",
|
||||
@@ -4303,7 +4303,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "solidcraft-kernel"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0-rc.1"
|
||||
dependencies = [
|
||||
"log",
|
||||
"proptest",
|
||||
@@ -4323,7 +4323,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "solidcraft-mcp"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0-rc.1"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
"solidcraft-engine",
|
||||
@@ -4332,7 +4332,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "solidcraft-render"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0-rc.1"
|
||||
dependencies = [
|
||||
"image",
|
||||
"moxcms",
|
||||
@@ -4346,7 +4346,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "solidcraft-sketch"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0-rc.1"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -4357,14 +4357,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "solidcraft-space-mouse"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0-rc.1"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "solidcraft-ui-egui"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0-rc.1"
|
||||
dependencies = [
|
||||
"arboard",
|
||||
"egui",
|
||||
@@ -4392,7 +4392,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "solidcraft-web"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0-rc.1"
|
||||
dependencies = [
|
||||
"eframe",
|
||||
"egui",
|
||||
@@ -5922,7 +5922,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"
|
||||
|
||||
[[package]]
|
||||
name = "xtask"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0-rc.1"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"serde_json",
|
||||
|
||||
@@ -5,7 +5,7 @@ members = ["crates/*", "apps/*", "xtask"]
|
||||
exclude = ["vendor"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.20.0"
|
||||
version = "0.21.0-rc.1"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
|
||||
@@ -30,5 +30,5 @@ web-sys = { version = "0.3", features = [
|
||||
"FileSystemHandle", "FileSystemDirectoryHandle", "FileSystemFileHandle", "FileSystemGetFileOptions", "FileSystemWritableFileStream",
|
||||
"WritableStream", "File", "FileList", "Blob", "BlobPropertyBag", "Url", "HtmlAnchorElement", "HtmlInputElement", "Storage",
|
||||
"IdbFactory", "IdbDatabase", "IdbObjectStore", "IdbOpenDbRequest", "IdbRequest", "IdbTransaction", "IdbTransactionMode",
|
||||
"BeforeUnloadEvent", "Event", "EventTarget", "Response", "MediaQueryList", "Gamepad", "Performance",
|
||||
"BeforeUnloadEvent", "Event", "EventTarget", "KeyboardEvent", "Response", "MediaQueryList", "Gamepad", "Performance",
|
||||
] }
|
||||
@@ -499,7 +499,9 @@ fn input_picker(files: &Rc<Files>, 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::<web_sys::HtmlInputElement>()) else { return };
|
||||
input.set_type("file");
|
||||
input.set_accept(".solidcraft,.solvecraft,.json,.step,.stp,.3mf,.stl,.obj,.glb,.gltf");
|
||||
// Everything the browser build imports, from the format registry (no cadmpeg formats here).
|
||||
let accept = solidcraft_engine::io::formats::open_extensions(false).iter().map(|e| format!(".{e}")).collect::<Vec<_>>().join(",");
|
||||
input.set_accept(&accept);
|
||||
// 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() {
|
||||
|
||||
@@ -17,6 +17,14 @@ mod install;
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
mod space_mouse;
|
||||
|
||||
/// The browser switches tabs with Ctrl+Tab and Ctrl+Shift+Tab, so the page leaves those keys to
|
||||
/// it (#5227); plain Tab and Shift+Tab still move between the app's fields. (Ctrl+PageUp and
|
||||
/// Ctrl+PageDown already reach the browser.)
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
fn browser_switches_tabs(key: &str, ctrl: bool) -> bool {
|
||||
ctrl && key == "Tab"
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod web {
|
||||
use std::rc::Rc;
|
||||
@@ -84,6 +92,20 @@ mod web {
|
||||
on_unload.forget();
|
||||
}
|
||||
|
||||
/// eframe cancels the browser's action for every Tab it gets, so the browser couldn't switch
|
||||
/// tabs while the app has the keyboard. Its tab-switching keys stop here, on the way down to
|
||||
/// the canvas, before eframe sees them; the browser then acts on them as usual.
|
||||
fn leave_tab_switching_to_browser(window: &web_sys::Window) {
|
||||
let on_key = wasm_bindgen::closure::Closure::<dyn FnMut(web_sys::KeyboardEvent)>::new(|e: web_sys::KeyboardEvent| {
|
||||
if crate::browser_switches_tabs(&e.key(), e.ctrl_key()) {
|
||||
e.stop_propagation();
|
||||
}
|
||||
});
|
||||
let _ = window.add_event_listener_with_callback_and_bool("keydown", on_key.as_ref().unchecked_ref(), true);
|
||||
// The listener lives as long as the page.
|
||||
on_key.forget();
|
||||
}
|
||||
|
||||
const JAPANESE_FONT_PATH: &str = "./fonts/BIZUDPGothic-Regular.ttf";
|
||||
|
||||
type FontLoadResult = Rc<std::cell::RefCell<Option<Result<Vec<u8>, String>>>>;
|
||||
@@ -553,6 +575,7 @@ mod web {
|
||||
wasm_bindgen_futures::spawn_local(async {
|
||||
let Some(window) = web_sys::window() else { return };
|
||||
ask_before_unload(&window);
|
||||
leave_tab_switching_to_browser(&window);
|
||||
let Some(document) = window.document() else { return };
|
||||
let Some(canvas) = document.get_element_by_id(CANVAS_ID).and_then(|e| e.dyn_into::<web_sys::HtmlCanvasElement>().ok()) else {
|
||||
log::error!("missing <canvas id=\"{CANVAS_ID}\">");
|
||||
@@ -675,3 +698,17 @@ fn main() {
|
||||
fn main() {
|
||||
eprintln!("solidcraft-web only runs in the browser: build it with `trunk build --release` in apps/solidcraft-web");
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn only_ctrl_tab_is_left_to_the_browser() {
|
||||
// Ctrl+Tab and Ctrl+Shift+Tab (the event's key is "Tab" either way) switch browser tabs.
|
||||
assert!(browser_switches_tabs("Tab", true));
|
||||
// Tab and Shift+Tab move between the app's fields; Ctrl with other keys stays the app's.
|
||||
assert!(!browser_switches_tabs("Tab", false));
|
||||
assert!(!browser_switches_tabs("s", true));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
//! The graphics device was lost after the window opened: the driver was reset (on Windows a TDR,
|
||||
//! "Display driver stopped responding and has recovered") or the GPU went away (#4172). A lost
|
||||
//! device can't draw again, so the window can't show anything more, not even a message. The
|
||||
//! painter stops drawing (`egui_wgpu::DeviceLost`); the app then closes, keeping unsaved changes
|
||||
//! for recovery as a forced quit does, and starts again ([`restart`]), and the new start says what
|
||||
//! happened ([`note`]). A device lost again soon after such a restart starts the next one on the
|
||||
//! software renderer, which doesn't depend on the graphics driver.
|
||||
|
||||
use crate::startup;
|
||||
|
||||
/// Set on the start after a lost device: when the device was lost (seconds since 1970).
|
||||
pub const LOST_ENV: &str = "SOLIDCRAFT_DEVICE_LOST";
|
||||
|
||||
/// A loss this recent (seconds) counts for the start after it: its note, and a second loss
|
||||
/// within it starts on the software renderer. Inherited by later starts, an older stamp is
|
||||
/// ignored.
|
||||
const RECENT_SECS: u64 = 600;
|
||||
|
||||
/// Seconds since 1970.
|
||||
pub fn now_secs() -> u64 {
|
||||
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs())
|
||||
}
|
||||
|
||||
/// Whether `stamp` ([`LOST_ENV`]) names a loss at most [`RECENT_SECS`] before `now`.
|
||||
pub fn recent(stamp: Option<&str>, now: u64) -> bool {
|
||||
stamp.and_then(|s| s.trim().parse::<u64>().ok()).is_some_and(|at| at <= now && now - at <= RECENT_SECS)
|
||||
}
|
||||
|
||||
/// Whether the start after a lost device uses the software renderer: when this launch already
|
||||
/// followed a recent loss (the driver keeps losing it), or ran on it anyway.
|
||||
pub fn restart_on_software(after_recent_loss: bool, cpu_renderer: bool) -> bool {
|
||||
after_recent_loss || cpu_renderer
|
||||
}
|
||||
|
||||
/// What the start after a lost device tells the user, `software` when it runs on the software
|
||||
/// renderer.
|
||||
pub fn note(software: bool) -> String {
|
||||
let mut note = String::from(
|
||||
"The graphics device was reset (the graphics driver stopped responding), so SolidCraft closed and started again. Unsaved changes were kept for recovery.",
|
||||
);
|
||||
if software {
|
||||
note.push_str(" This start uses software rendering, which doesn't depend on the graphics driver.");
|
||||
}
|
||||
note
|
||||
}
|
||||
|
||||
/// Start SolidCraft again with the same arguments, the loss stamped at `lost_at`, on the software
|
||||
/// renderer when `software`.
|
||||
pub fn restart(software: bool, lost_at: u64) {
|
||||
let Ok(exe) = std::env::current_exe() else { return };
|
||||
let mut command = std::process::Command::new(exe);
|
||||
command.args(std::env::args_os().skip(1)).env(LOST_ENV, lost_at.to_string());
|
||||
if software {
|
||||
command.env(startup::RENDERER_ENV, "cpu");
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
// Not tied to this process: its own process group, no console.
|
||||
command.creation_flags(0x0000_0200 | 0x0000_0008);
|
||||
}
|
||||
if let Err(e) = command.spawn() {
|
||||
log::error!("graphics: starting again after the device was lost: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
/// Only a recent, well-formed stamp counts: a later start that inherited it says nothing.
|
||||
#[test]
|
||||
fn only_a_recent_loss_counts() {
|
||||
let now = 1_000_000;
|
||||
assert!(super::recent(Some("999990"), now));
|
||||
assert!(super::recent(Some(" 999400 "), now));
|
||||
assert!(!super::recent(Some("999399"), now), "older than ten minutes");
|
||||
assert!(!super::recent(Some("1000001"), now), "from the future");
|
||||
assert!(!super::recent(Some("soon"), now));
|
||||
assert!(!super::recent(None, now));
|
||||
}
|
||||
|
||||
/// The first loss starts again on the GPU; a second one soon after, on the software renderer.
|
||||
#[test]
|
||||
fn a_second_loss_in_a_row_starts_on_the_software_renderer() {
|
||||
assert!(!super::restart_on_software(false, false));
|
||||
assert!(super::restart_on_software(true, false));
|
||||
assert!(super::restart_on_software(false, true));
|
||||
assert!(super::note(true).contains("software rendering"));
|
||||
assert!(!super::note(false).contains("software rendering"));
|
||||
assert!(super::note(false).contains("kept for recovery"));
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,7 @@
|
||||
#[path = "../../../assets/icons/app/shared/source/app_icon.rs"]
|
||||
mod app_icon;
|
||||
mod control_server;
|
||||
mod device_lost;
|
||||
#[cfg(target_os = "windows")]
|
||||
mod native_crash;
|
||||
#[cfg(target_os = "windows")]
|
||||
@@ -76,6 +77,8 @@ struct App {
|
||||
frames: u32,
|
||||
/// Started over the control channel: the window doesn't ask for the foreground.
|
||||
take_focus_unwanted: bool,
|
||||
/// The graphics device: lost, it can't draw again (`App::watch_device`, #4172).
|
||||
gpu: Option<LostWatch>,
|
||||
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
|
||||
space_mouse: space_mouse::SpaceMouse,
|
||||
}
|
||||
@@ -107,6 +110,7 @@ impl eframe::App for App {
|
||||
}
|
||||
}
|
||||
}
|
||||
self.watch_device();
|
||||
// The design on screen is the one whose commands a crash report replays.
|
||||
self.solve.session.crash_journal = solidcraft_engine::crash::enabled();
|
||||
// The OS closing the window (Alt+F4, Cmd+Q, the window manager): ask about unsaved
|
||||
@@ -147,6 +151,9 @@ impl eframe::App for App {
|
||||
solidcraft_ui_egui::save_job::tick(&mut self.solve, true);
|
||||
solidcraft_ui_egui::recovery_ui::close(&mut self.solve);
|
||||
solidcraft_engine::crash::end_session();
|
||||
if let Some(lost_at) = self.gpu.as_ref().and_then(|g| g.lost_at) {
|
||||
device_lost::restart(self.gpu.as_ref().is_some_and(|g| g.restart_on_software), lost_at);
|
||||
}
|
||||
// An update asked to restart into the new version or to run its installer.
|
||||
if let Some((program, args)) = solidcraft_ui_egui::update::take_launch(&mut self.solve) {
|
||||
let mut command = std::process::Command::new(&program);
|
||||
@@ -166,6 +173,48 @@ impl eframe::App for App {
|
||||
}
|
||||
}
|
||||
|
||||
/// The window's graphics device, watched for its loss.
|
||||
struct LostWatch {
|
||||
lost: eframe::egui_wgpu::DeviceLost,
|
||||
/// Where the next start runs once this device is lost ([`device_lost::restart_on_software`]).
|
||||
restart_on_software: bool,
|
||||
/// When the loss was seen: the app is closing to start again.
|
||||
lost_at: Option<u64>,
|
||||
}
|
||||
|
||||
impl App {
|
||||
/// The graphics device was lost (#4172): the window can't draw again, so close, keeping
|
||||
/// unsaved changes for recovery as a forced quit does (the window can't ask about them), and
|
||||
/// start again once closed ([`device_lost::restart`]).
|
||||
fn watch_device(&mut self) {
|
||||
let Some(gpu) = self.gpu.as_mut().filter(|g| g.lost_at.is_none() && g.lost.is_lost()) else { return };
|
||||
let reason = gpu.lost.reason().unwrap_or_default();
|
||||
log::error!("graphics: the device was lost ({reason}); closing to start again");
|
||||
eprintln!("SolidCraft graphics: the device was lost ({reason}); starting again");
|
||||
solidcraft_engine::crash::phase(&format!("graphics device lost: {reason}"));
|
||||
gpu.lost_at = Some(device_lost::now_secs());
|
||||
self.solve.quit_requested = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Linux file dialogs match patterns by case, so each extension goes in as lower and upper
|
||||
/// case, plus FreeCAD's own mixed casing.
|
||||
fn case_variants(exts: &[&str]) -> Vec<String> {
|
||||
let mut all: Vec<String> = Vec::new();
|
||||
for e in exts {
|
||||
let mut forms = vec![e.to_ascii_lowercase(), e.to_ascii_uppercase()];
|
||||
if e.eq_ignore_ascii_case("fcstd") {
|
||||
forms.push("FCStd".into());
|
||||
}
|
||||
for v in forms {
|
||||
if !all.contains(&v) {
|
||||
all.push(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
all
|
||||
}
|
||||
|
||||
fn services(cc: &eframe::CreationContext<'_>) -> Services {
|
||||
let parent = rfd::AsyncFileDialog::new().set_parent(cc);
|
||||
let open_parent = parent.clone();
|
||||
@@ -177,48 +226,14 @@ fn services(cc: &eframe::CreationContext<'_>) -> Services {
|
||||
let mut dialog = open_parent.clone();
|
||||
if !first.is_empty() {
|
||||
let label = first.iter().map(|e| e.to_uppercase()).collect::<Vec<_>>().join(", ");
|
||||
let both: Vec<String> = first.iter().flat_map(|e| [e.to_lowercase(), e.to_uppercase()]).collect();
|
||||
dialog = dialog.add_filter(label, &both);
|
||||
dialog = dialog.add_filter(label, &case_variants(first));
|
||||
}
|
||||
let future = dialog
|
||||
.add_filter(
|
||||
"Designs, CAD files and meshes",
|
||||
&[
|
||||
io::DESIGN_EXT,
|
||||
io::LEGACY_DESIGN_EXT,
|
||||
"json",
|
||||
"step",
|
||||
"stp",
|
||||
"STEP",
|
||||
"STP",
|
||||
"igs",
|
||||
"iges",
|
||||
"IGS",
|
||||
"IGES",
|
||||
"FCStd",
|
||||
"fcstd",
|
||||
"3dm",
|
||||
"3DM",
|
||||
"3mf",
|
||||
"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("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", &["*"])
|
||||
.pick_file();
|
||||
// The groups come from the format registry, so a new format joins this dialog by itself.
|
||||
dialog = dialog.add_filter("Designs, CAD files and meshes", &case_variants(&io::formats::open_extensions(true)));
|
||||
for (label, exts) in io::formats::import_filters(true) {
|
||||
dialog = dialog.add_filter(label, &case_variants(&exts));
|
||||
}
|
||||
let future = dialog.add_filter("All files", &["*"]).pick_file();
|
||||
Box::pin(async move { future.await.map(|p| p.path().to_string_lossy().into_owned()) })
|
||||
})),
|
||||
// One kind of file (the agent chat's attachments): only the types it names, as given and in
|
||||
@@ -483,6 +498,18 @@ fn backend_preference() -> Option<String> {
|
||||
graphics().and_then(|v| v.get("backend").and_then(serde_json::Value::as_str).map(str::to_string))
|
||||
}
|
||||
|
||||
/// The viewport scene's sample count: the app's anti-aliasing (the window's pass is 1x), clamped
|
||||
/// by the backend's policy (OpenGL renders 1x, see `effective_msaa_samples`). A count the device
|
||||
/// cannot render with falls back to the supported default.
|
||||
fn scene_samples(backend: eframe::wgpu::Backend, samples: u32, supported: &[u32]) -> u32 {
|
||||
let requested = eframe::egui_wgpu::effective_msaa_samples(backend, samples.max(1));
|
||||
if requested <= 1 || supported.is_empty() || supported.contains(&requested) {
|
||||
requested
|
||||
} else {
|
||||
supported.iter().copied().filter(|&n| n <= solidcraft_ui_egui::prefs::Prefs::default().msaa).max().unwrap_or(1)
|
||||
}
|
||||
}
|
||||
|
||||
/// Anti-aliasing samples from Preferences (4 when unset).
|
||||
fn msaa() -> u16 {
|
||||
graphics()
|
||||
@@ -579,6 +606,11 @@ fn main() -> eframe::Result {
|
||||
notes.push(format!("The last {failed_starts} launches stopped before the window opened, so this one is in safe mode."));
|
||||
}
|
||||
let cpu_renderer = safe_mode || startup::cpu_renderer_env(std::env::var(startup::RENDERER_ENV).ok().as_deref());
|
||||
// The launch before this one closed because its graphics device was lost (`App::watch_device`).
|
||||
let after_loss = device_lost::recent(std::env::var(device_lost::LOST_ENV).ok().as_deref(), device_lost::now_secs());
|
||||
if after_loss {
|
||||
notes.push(device_lost::note(cpu_renderer));
|
||||
}
|
||||
if safe_mode {
|
||||
notes.push("Safe mode: default settings (yours are kept for the next normal start), no recovery offer, software rendering.".into());
|
||||
}
|
||||
@@ -604,9 +636,11 @@ fn main() -> eframe::Result {
|
||||
solidcraft_engine::crash::phase("window");
|
||||
let options = eframe::NativeOptions {
|
||||
viewport: app_viewport()?,
|
||||
depth_buffer: depth_bits,
|
||||
stencil_buffer: STENCIL_BITS,
|
||||
multisampling: samples,
|
||||
// The window's pass (egui's) has no depth and one sample: the viewport draws its scene
|
||||
// offscreen with its own depth and MSAA, then blits it, so the UI pass pays for neither.
|
||||
depth_buffer: 0,
|
||||
stencil_buffer: 0,
|
||||
multisampling: 1,
|
||||
// Kept with the other settings, not in a folder named after the app id. Safe mode reads
|
||||
// and writes a scratch copy, leaving the user's settings as they were.
|
||||
persistence_path: if safe_mode {
|
||||
@@ -669,10 +703,16 @@ fn main() -> eframe::Result {
|
||||
app.load_prefs(&p);
|
||||
}
|
||||
mark("app state and prefs");
|
||||
let gpu = cc.wgpu_render_state.as_ref().map(|rs| LostWatch {
|
||||
lost: rs.device_lost.clone(),
|
||||
restart_on_software: device_lost::restart_on_software(after_loss, cpu_renderer),
|
||||
lost_at: None,
|
||||
});
|
||||
if let Some(rs) = &cc.wgpu_render_state {
|
||||
eprintln!("SolidCraft graphics: {:?}, MSAA {}x (requested {}x)", rs.adapter.get_info().backend, rs.msaa_samples, samples);
|
||||
let scene_samples = scene_samples(rs.adapter.get_info().backend, u32::from(samples), &rs.msaa_supported);
|
||||
eprintln!("SolidCraft graphics: {:?}, MSAA {scene_samples}x (requested {}x)", rs.adapter.get_info().backend, samples);
|
||||
solidcraft_engine::crash::phase("viewport pipelines (shader compile)");
|
||||
app.set_wgpu(rs, depth_bits, STENCIL_BITS, rs.msaa_samples);
|
||||
app.set_wgpu_split(rs, depth_bits, STENCIL_BITS, scene_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.
|
||||
@@ -682,8 +722,8 @@ fn main() -> eframe::Result {
|
||||
solidcraft_ui_egui::prefs::check_msaa(&mut app, u32::from(samples));
|
||||
let info = rs.adapter.get_info();
|
||||
solidcraft_engine::crash::set_environment(&format!(
|
||||
"Renderer: {:?} {} ({}), MSAA {}x",
|
||||
info.backend, info.name, info.driver, rs.msaa_samples
|
||||
"Renderer: {:?} {} ({}), MSAA {scene_samples}x",
|
||||
info.backend, info.name, info.driver
|
||||
));
|
||||
}
|
||||
mark("viewport pipelines");
|
||||
@@ -746,6 +786,7 @@ fn main() -> eframe::Result {
|
||||
starting,
|
||||
frames: 0,
|
||||
take_focus_unwanted: control_port.is_some(),
|
||||
gpu,
|
||||
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
|
||||
space_mouse,
|
||||
}))
|
||||
@@ -909,4 +950,13 @@ mod msaa_tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_scene_follows_the_backend_policy_too() {
|
||||
use eframe::wgpu::Backend;
|
||||
assert_eq!(super::scene_samples(Backend::Gl, 4, &[1, 4]), 1);
|
||||
assert_eq!(super::scene_samples(Backend::Gl, 4, &[]), 1);
|
||||
assert_eq!(super::scene_samples(Backend::Vulkan, 4, &[1, 4]), 4);
|
||||
assert_eq!(super::scene_samples(Backend::Dx12, 8, &[1, 2, 4]), 4);
|
||||
}
|
||||
}
|
||||
@@ -284,15 +284,18 @@ fn decode_report(report: &[u8], layout: Layout, reading: &mut Reading, now: Inst
|
||||
true
|
||||
}
|
||||
|
||||
/// Publishes one input report from the device to the egui thread.
|
||||
/// Publishes one input report from the device to the egui thread. A report that reads the same as
|
||||
/// the reading it replaces is no news — a device may repeat its report at rest — so it asks for no
|
||||
/// frame; while the cap moves, the view asks for the next frame itself.
|
||||
fn publish(ctx: &Context, shared: &Mutex<Reading>, layout: Layout, report: &[u8]) {
|
||||
if DRIVER_CONNECTED.load(Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
if let Ok(mut reading) = shared.lock()
|
||||
&& decode_report(report, layout, &mut reading, Instant::now())
|
||||
{
|
||||
ctx.request_repaint();
|
||||
if let Ok(mut reading) = shared.lock() {
|
||||
let before = reading.axes;
|
||||
if decode_report(report, layout, &mut reading, Instant::now()) && reading.axes != before {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -886,6 +889,31 @@ mod tests {
|
||||
assert_eq!(reading.current(now + STALE_AFTER, Axes::default()).translation, [0; 3]);
|
||||
}
|
||||
|
||||
/// A device that repeats its reading at rest asks for no frame; a reading that changes does.
|
||||
#[test]
|
||||
fn a_repeated_report_at_rest_asks_for_no_frame() {
|
||||
let ctx = Context::default();
|
||||
let shared = Mutex::new(Reading::new(Instant::now()));
|
||||
let layout = Layout::default();
|
||||
let frame = || {
|
||||
let mut out = ctx.run_ui(egui::RawInput::default(), |_| {});
|
||||
out.textures_delta.clear();
|
||||
};
|
||||
let asked = || {
|
||||
frame();
|
||||
ctx.repaint_causes().iter().any(|c| c.file.ends_with("space_mouse.rs"))
|
||||
};
|
||||
frame();
|
||||
// Report 1 carries translation (see the split-layout test).
|
||||
let report = [1, 0x9c, 0xff, 0x2c, 0x01, 0, 0];
|
||||
publish(&ctx, &shared, layout, &report);
|
||||
assert!(asked(), "a report that moves the cap asks for a frame");
|
||||
publish(&ctx, &shared, layout, &report);
|
||||
assert!(!asked(), "the same reading at rest is no news");
|
||||
publish(&ctx, &shared, layout, &[1, 0x9d, 0xff, 0x2c, 0x01, 0, 0]);
|
||||
assert!(asked(), "a changed reading asks for a frame");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_held_reading_stays_until_the_next_one_and_a_hid_reading_goes_stale() {
|
||||
let now = Instant::now();
|
||||
|
||||
|
Before Width: | Height: | Size: 6.2 KiB After Width: | Height: | Size: 9.4 KiB |
|
Before Width: | Height: | Size: 629 B After Width: | Height: | Size: 660 B |
|
Before Width: | Height: | Size: 944 B After Width: | Height: | Size: 1.1 KiB |
|
Before Width: | Height: | Size: 13 KiB After Width: | Height: | Size: 21 KiB |
|
Before Width: | Height: | Size: 1.3 KiB After Width: | Height: | Size: 1.6 KiB |
|
Before Width: | Height: | Size: 2.0 KiB After Width: | Height: | Size: 2.7 KiB |
|
Before Width: | Height: | Size: 28 KiB After Width: | Height: | Size: 48 KiB |
|
Before Width: | Height: | Size: 2.9 KiB After Width: | Height: | Size: 4.0 KiB |
@@ -1,88 +1,93 @@
|
||||
//! Original SolidCraft mark, shared by desktop, packaging and CLI.
|
||||
//! Original SolidCraft mark, shared by desktop, packaging and CLI: the borderless mark, five
|
||||
//! faces with transparent gaps between them, drawn from the macOS icon's
|
||||
//! `macos/source/SolidCraft.icon/Assets/03-solid-blue-cutout.svg`.
|
||||
type P = (f32, f32);
|
||||
|
||||
/// One face in that SVG's units: its outline, and its linear gradient from one point and
|
||||
/// colour to another.
|
||||
struct Face {
|
||||
outline: &'static [P],
|
||||
from: (P, [u8; 3]),
|
||||
to: (P, [u8; 3]),
|
||||
}
|
||||
|
||||
const FACES: [Face; 5] = [
|
||||
// Inner side of the upper step.
|
||||
Face {
|
||||
outline: &[(547.883, 282.66), (709.797, 188.211), (709.797, 375.985)],
|
||||
from: ((619.14, 179.734), [29, 99, 198]),
|
||||
to: ((694.687, 396.761), [21, 73, 158]),
|
||||
},
|
||||
// Top of the lower step.
|
||||
Face {
|
||||
outline: &[(727.797, 593.626), (727.797, 407.136), (889.571, 500.381)],
|
||||
from: ((619.14, 413.244), [69, 159, 255]),
|
||||
to: ((790.839, 605.547), [35, 121, 231]),
|
||||
},
|
||||
// Right face, with the recess.
|
||||
Face {
|
||||
outline: &[(530.0, 521.17), (691.797, 427.912), (691.797, 655.928), (907.594, 531.545), (907.594, 740.159), (530.0, 957.8)],
|
||||
from: ((632.876, 399.508), [27, 102, 207]),
|
||||
to: ((783.971, 968.175), [18, 69, 150]),
|
||||
},
|
||||
// Left face, stepped.
|
||||
Face {
|
||||
outline: &[(116.406, 510.769), (116.406, 303.529), (494.0, 521.17), (494.0, 957.8), (314.203, 854.167), (314.203, 624.777)],
|
||||
from: ((207.063, 303.357), [37, 141, 245]),
|
||||
to: ((426.837, 968.175), [20, 97, 218]),
|
||||
},
|
||||
// Top of the extruded profile.
|
||||
Face {
|
||||
outline: &[(134.374, 272.334), (512.0, 53.364), (691.828, 157.015), (476.117, 282.846), (673.752, 396.761), (512.0, 489.993)],
|
||||
from: ((385.63, 53.364), [81, 173, 255]),
|
||||
to: ((522.989, 510.769), [43, 131, 241]),
|
||||
},
|
||||
];
|
||||
|
||||
/// The mark's extent in SVG units: left, top, width, height.
|
||||
const BOUNDS: (f32, f32, f32, f32) = (116.406, 53.364, 791.188, 904.436);
|
||||
|
||||
/// This block is the icon image data
|
||||
pub fn rgba(size: usize) -> Result<Vec<u8>, String> {
|
||||
if !(1..=2048).contains(&size) {
|
||||
return Err("icon size must be 1..=2048".into());
|
||||
}
|
||||
type P = (f32, f32);
|
||||
// Coverage buffer at 4x4 samples per pixel (2x2 for big sizes), averaged down at the end.
|
||||
let ss = if size > 512 { 2 } else { 4 };
|
||||
let n = size * ss;
|
||||
let mut buf = vec![[0u8; 4]; n * n];
|
||||
let s = n as f32 / 412.217; // SVG units -> samples: the logo fills the height
|
||||
let ox = (n as f32 - 357.0 * s) / 2.0; // and is centred sideways
|
||||
// Fill a convex polygon given in SVG units.
|
||||
let mut fill = |pts: &[P], col: [u8; 3]| {
|
||||
let v: Vec<P> = pts.iter().map(|p| (ox + p.0 * s, p.1 * s)).collect();
|
||||
let (bx, by, bw, bh) = BOUNDS;
|
||||
let s = n as f32 / bh; // SVG units -> samples: the mark fills the height
|
||||
let (ox, oy) = ((n as f32 - bw * s) / 2.0 - bx * s, -by * s); // and is centred sideways
|
||||
// Fill each face's outline (even-odd spans per row, so concave outlines work) with its gradient.
|
||||
for face in &FACES {
|
||||
let v: Vec<P> = face.outline.iter().map(|p| (ox + p.0 * s, oy + p.1 * s)).collect();
|
||||
let (((fx, fy), c0), ((tx, ty), c1)) = (face.from, face.to);
|
||||
let (gx, gy) = (tx - fx, ty - fy);
|
||||
let g2 = gx * gx + gy * gy;
|
||||
let (top, bottom) = v.iter().fold((f32::MAX, f32::MIN), |(a, b), p| (a.min(p.1), b.max(p.1)));
|
||||
let mut xs = Vec::with_capacity(v.len());
|
||||
for y in ((top - 0.5).ceil() as i32).max(0)..=((bottom - 0.5).floor() as i32).min(n as i32 - 1) {
|
||||
let cy = y as f32 + 0.5;
|
||||
let (mut lo, mut hi) = (f32::MAX, f32::MIN);
|
||||
xs.clear();
|
||||
for i in 0..v.len() {
|
||||
let (a, b) = (v[i], v[(i + 1) % v.len()]);
|
||||
if (a.1 <= cy) != (b.1 <= cy) {
|
||||
let x = a.0 + (cy - a.1) / (b.1 - a.1) * (b.0 - a.0);
|
||||
lo = lo.min(x);
|
||||
hi = hi.max(x);
|
||||
xs.push(a.0 + (cy - a.1) / (b.1 - a.1) * (b.0 - a.0));
|
||||
}
|
||||
}
|
||||
if lo > hi {
|
||||
continue;
|
||||
}
|
||||
for x in ((lo - 0.5).ceil() as i32).max(0)..=((hi - 0.5).floor() as i32).min(n as i32 - 1) {
|
||||
buf[y as usize * n + x as usize] = [col[0], col[1], col[2], 255];
|
||||
xs.sort_by(f32::total_cmp);
|
||||
for &[from, to] in xs.as_chunks::<2>().0 {
|
||||
for x in ((from - 0.5).ceil() as i32).max(0)..=((to - 0.5).floor() as i32).min(n as i32 - 1) {
|
||||
// The sample's place along the gradient, in SVG units.
|
||||
let (px, py) = ((x as f32 + 0.5 - ox) / s, (cy - oy) / s);
|
||||
let t = (((px - fx) * gx + (py - fy) * gy) / g2).clamp(0.0, 1.0);
|
||||
let mix = |k: usize| (f32::from(c0[k]) + (f32::from(c1[k]) - f32::from(c0[k])) * t).round() as u8;
|
||||
buf[y as usize * n + x as usize] = [mix(0), mix(1), mix(2), 255];
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
// Faces: each is a few overlapping convex pieces (the filler only does convex shapes).
|
||||
let (light, mid, dark) = ([96, 158, 236], [58, 136, 238], [55, 108, 197]);
|
||||
fill(&[(3.5, 105.9), (177.0, 5.8), (263.4, 55.6), (263.8, 156.0), (177.0, 406.4)], light);
|
||||
fill(&[(177.0, 206.1), (263.8, 156.0), (350.5, 206.2), (350.5, 306.3), (177.0, 406.4)], light);
|
||||
fill(&[(3.5, 105.9), (177.0, 206.1), (177.0, 406.4)], mid);
|
||||
fill(&[(3.5, 105.9), (3.5, 205.7), (90.3, 256.2), (177.0, 206.1)], mid);
|
||||
fill(&[(177.0, 206.1), (90.3, 256.2), (90.0, 356.2), (177.0, 406.4)], mid);
|
||||
fill(&[(264.1, 155.8), (177.0, 206.1), (177.0, 406.4), (263.8, 256.2)], dark);
|
||||
fill(&[(263.8, 256.2), (350.5, 206.2), (350.5, 306.3), (177.0, 406.4)], dark);
|
||||
fill(&[(177.0, 206.1), (177.0, 406.4), (350.5, 306.3)], dark);
|
||||
fill(&[(263.8, 55.9), (263.8, 156.0), (177.1, 105.9)], dark);
|
||||
// White edge lines, 10 units wide: a rectangle per segment and a disc at each inner corner.
|
||||
let white = [255, 255, 255];
|
||||
let mut stroke = |pts: &[P], closed: bool| {
|
||||
let m = pts.len();
|
||||
for i in 0..(if closed { m } else { m - 1 }) {
|
||||
let (a, b) = (pts[i], pts[(i + 1) % m]);
|
||||
let l = ((b.0 - a.0).powi(2) + (b.1 - a.1).powi(2)).sqrt();
|
||||
let (nx, ny) = (-(b.1 - a.1) / l * 5.0, (b.0 - a.0) / l * 5.0);
|
||||
fill(&[(a.0 + nx, a.1 + ny), (b.0 + nx, b.1 + ny), (b.0 - nx, b.1 - ny), (a.0 - nx, a.1 - ny)], white);
|
||||
}
|
||||
for c in &pts[if closed { 0 } else { 1 }..if closed { m } else { m - 1 }] {
|
||||
let disc: Vec<P> = (0..16)
|
||||
.map(|k| {
|
||||
let t = k as f32 * std::f32::consts::TAU / 16.0;
|
||||
(c.0 + 5.0 * t.cos(), c.1 + 5.0 * t.sin())
|
||||
})
|
||||
.collect();
|
||||
fill(&disc, white);
|
||||
}
|
||||
};
|
||||
stroke(&[(263.8, 55.9), (177.1, 105.9), (263.8, 156.0), (263.8, 256.2), (350.6, 206.1)], false);
|
||||
stroke(&[(5.0, 105.9), (178.5, 206.1), (178.5, 406.4)], false);
|
||||
stroke(&[(177.0, 206.1), (263.8, 156.0)], false);
|
||||
stroke(
|
||||
&[
|
||||
(178.5, 5.8),
|
||||
(5.0, 105.9),
|
||||
(5.0, 206.1),
|
||||
(91.7, 256.2),
|
||||
(91.7, 356.4),
|
||||
(178.5, 406.4),
|
||||
(352.0, 306.3),
|
||||
(352.0, 206.1),
|
||||
(265.2, 156.0),
|
||||
(265.2, 55.9),
|
||||
],
|
||||
true,
|
||||
);
|
||||
}
|
||||
// Average each ss x ss block down to one pixel (straight alpha = covered share).
|
||||
let mut rgba = Vec::with_capacity(size * size * 4);
|
||||
for y in 0..size {
|
||||
@@ -123,4 +128,20 @@ mod tests {
|
||||
assert!(super::rgba(0).is_err());
|
||||
assert!(super::rgba(2049).is_err());
|
||||
}
|
||||
|
||||
/// Borderless: no white edge lines, and the gaps between faces are see-through. At 256 px
|
||||
/// the gap between the left and right faces (SVG x 494..530) is transparent on the row
|
||||
/// through the middle of the mark, and no opaque pixel is white.
|
||||
#[test]
|
||||
fn shared_mark_is_borderless() {
|
||||
let size = 256;
|
||||
let pixels = super::rgba(size).expect("valid size");
|
||||
let px = |x: usize, y: usize| pixels.as_chunks::<4>().0[y * size + x];
|
||||
let s = size as f32 / 904.436;
|
||||
let gap_x = ((size as f32 - 791.188 * s) / 2.0 + (512.0 - 116.406) * s) as usize;
|
||||
let row = ((750.0 - 53.364) * s) as usize;
|
||||
assert_eq!(px(gap_x, row)[3], 0, "the seam between the left and right faces is a gap");
|
||||
assert!(px(gap_x - 8, row)[3] == 255 && px(gap_x + 8, row)[3] == 255, "faces on both sides of the gap");
|
||||
assert!(pixels.as_chunks::<4>().0.iter().all(|p| p[3] == 0 || p[0] < 200), "no white edges");
|
||||
}
|
||||
}
|
||||
|
Before Width: | Height: | Size: 364 KiB After Width: | Height: | Size: 364 KiB |
|
Before Width: | Height: | Size: 30 KiB After Width: | Height: | Size: 44 KiB |
@@ -104,10 +104,10 @@ pub(crate) fn brand_mark(p: &egui::Painter, c: Pos2) {
|
||||
|
||||
/// The same original mark as a single quiet silhouette, without face seams or outlines.
|
||||
pub(crate) fn brand_mark_silhouette(p: &egui::Painter, c: Pos2, height: f32, ink: Color32) {
|
||||
brand_mark_styled(p, c, height, [ink; 4], false);
|
||||
brand_mark_styled(p, c, height, [ink; 3], false);
|
||||
}
|
||||
|
||||
fn brand_mark_styled(p: &egui::Painter, c: Pos2, height: f32, colours: [Color32; 4], edges: bool) {
|
||||
fn brand_mark_styled(p: &egui::Painter, c: Pos2, height: f32, colours: [Color32; 3], edges: bool) {
|
||||
let s = height / 412.217;
|
||||
let m = |pts: &[(f32, f32)]| -> Vec<egui::Pos2> { pts.iter().map(|&(x, y)| pos2(c.x + (x - 178.5) * s, c.y + (y - 206.1) * s)).collect() };
|
||||
// egui only fills convex shapes, so each face is a few overlapping convex pieces.
|
||||
@@ -115,7 +115,7 @@ fn brand_mark_styled(p: &egui::Painter, c: Pos2, height: f32, colours: [Color32;
|
||||
p.add(egui::Shape::convex_polygon(m(pts), col, Stroke::NONE));
|
||||
};
|
||||
// The faces are separated by gaps that show the application bar, not by white lines.
|
||||
let [light, mid, dark, _] = colours;
|
||||
let [light, mid, dark] = colours;
|
||||
let edge_col = crate::theme::Tokens::get().app_bar;
|
||||
face(light, &[(3.5, 105.9), (177.0, 5.8), (263.4, 55.6), (263.8, 156.0), (177.0, 406.4)]);
|
||||
face(light, &[(177.0, 206.1), (263.8, 156.0), (350.5, 206.2), (350.5, 306.3), (177.0, 406.4)]);
|
||||
@@ -129,7 +129,7 @@ fn brand_mark_styled(p: &egui::Painter, c: Pos2, height: f32, colours: [Color32;
|
||||
if !edges {
|
||||
return;
|
||||
}
|
||||
// White edge lines.
|
||||
// The seams between the faces and around the mark, in the bar's colour, so they read as gaps.
|
||||
let edge = Stroke::new(10.0 * s, edge_col);
|
||||
let line = |pts: &[(f32, f32)]| {
|
||||
p.add(egui::Shape::line(m(pts), edge));
|
||||
|
||||
@@ -1060,7 +1060,7 @@
|
||||
"search.try": "Zadejte název příkazu, prvek v tomto návrhu nebo parametr. Chcete-li spustit příkaz s hodnotami, zadejte jeho id a objekt JSON: {example}",
|
||||
"search.valid": "Platné",
|
||||
"settings.display_quality_note": "Jemnější úrovně kreslí zakřivené plochy a hrany hladčeji, ale síťování trvá déle. Mění se jen zobrazení, nikdy návrh ani exporty.",
|
||||
"settings.frame_rate_note": "Zobrazuje snímky za sekundu v pravém dolním rohu pohledu. Dokud je zapnuto, pohled se překresluje nepřetržitě.",
|
||||
"settings.frame_rate_note": "Zobrazuje snímky za sekundu v pravém dolním rohu pohledu.",
|
||||
"settings.measure_axis_distances": "Zobrazit vzdálenosti X/Y/Z",
|
||||
"settings.measure_axis_distances_help": "Při otevřeném měření zobrazit kromě celkové vzdálenosti i složky ve směru os.",
|
||||
"settings.msaa_applies_on_restart": "Vyhlazování se projeví při příštím spuštění SolidCraftu",
|
||||
@@ -1183,6 +1183,7 @@
|
||||
"ui.agent_chat_files_left_out": "K jedné zprávě lze připojit nejvýše {max} souborů; vynecháno: {files}",
|
||||
"ui.agent_chat_files_loading": "Čekání na přečtení souborů",
|
||||
"ui.agent_chat_files_max": "K jedné zprávě nejvýše {max} souborů",
|
||||
"ui.agent_chat_flatpak_none_found": "Nebyl nalezen žádný kódovací agent. Sandbox Flatpaku ve výchozím stavu nevidí agenty nainstalované ve vaší domovské složce a nemá přístup k síti. Chcete-li povolit Claude Code a jeho adaptér ACP nainstalované přes nvm nebo do ~/.local/bin, spusťte v terminálu tento příkaz a poté SolidCraft restartujte. Udělí přístup k uvedeným programům a přihlašovacím souborům a také přístup k síti:",
|
||||
"ui.agent_chat_import_failed": "{name}: import selhal: {error}",
|
||||
"ui.agent_chat_intro": "Chatujte s kódovacím agentem, kterého již používáte, nebo s modelem na zvoleném endpointu. Pracuje na otevřeném návrhu pomocí nástrojů SolidCraftu: jeho změny vidíte průběžně a každou zprávu lze vrátit jedním krokem. Co smí dělat bez ptaní, nastavíte v Předvolby > AI.",
|
||||
"ui.agent_chat_key_in_env": "klíč nastaven",
|
||||
|
||||
@@ -1060,7 +1060,7 @@
|
||||
"search.try": "Skriv et kommandonavn, en feature i dette design eller en parameter. Du kører en kommando med værdier ved at skrive dens id og et JSON-objekt: {example}",
|
||||
"search.valid": "Gyldig",
|
||||
"settings.display_quality_note": "Finere niveauer viser krumme flader og kanter mere jævnt og tager længere tid at opbygge mesh til. Kun modelvisningen ændres, aldrig designet eller eksporten.",
|
||||
"settings.frame_rate_note": "Viser billeder pr. sekund nederst til højre i modelvisningen. Når dette er slået til, gentegnes visningen løbende.",
|
||||
"settings.frame_rate_note": "Viser billeder pr. sekund nederst til højre i modelvisningen.",
|
||||
"settings.measure_axis_distances": "Vis X/Y/Z-afstande",
|
||||
"settings.measure_axis_distances_help": "Vis afstanden langs X-, Y- og Z-aksen sammen med den samlede afstand i Mål.",
|
||||
"settings.msaa_applies_on_restart": "Kantudjævning træder i kraft, næste gang SolidCraft starter",
|
||||
@@ -1183,6 +1183,7 @@
|
||||
"ui.agent_chat_files_left_out": "Højst {max} filer pr. besked; udeladt: {files}",
|
||||
"ui.agent_chat_files_loading": "Venter på indlæsning af filerne",
|
||||
"ui.agent_chat_files_max": "Højst {max} filer i én besked",
|
||||
"ui.agent_chat_flatpak_none_found": "Ingen kodeagent fundet. Flatpak-sandkassen kan som standard ikke se agenter, der er installeret i din hjemmemappe, og har ingen netværksadgang. For at tillade Claude Code og dets ACP-adapter installeret via nvm eller i ~/.local/bin skal du køre denne kommando i en terminal og derefter genstarte SolidCraft. Den giver adgang til de nævnte programmer og loginfiler samt netværksadgang:",
|
||||
"ui.agent_chat_import_failed": "{name}: Importen mislykkedes: {error}",
|
||||
"ui.agent_chat_intro": "Chat med en kodeagent, du allerede bruger, eller en modeltjeneste, du vælger. Den arbejder på det åbne design gennem SolidCrafts værktøjer: Ændringer vises undervejs og fortrydes som ét trin pr. besked. Hvad den må gøre uden at spørge, angives i Indstillinger > AI.",
|
||||
"ui.agent_chat_key_in_env": "nøgle angivet",
|
||||
|
||||
@@ -562,8 +562,10 @@
|
||||
"cmd.component_activate": "Komponente aktivieren",
|
||||
"cmd.component_break_link": "Verknüpfung trennen",
|
||||
"cmd.component_capture_position": "Position erfassen",
|
||||
"cmd.component_copies": "Identische Kopien finden",
|
||||
"cmd.component_create": "Neue Komponente",
|
||||
"cmd.component_delete": "Komponente löschen",
|
||||
"cmd.component_extract": "In Datei extrahieren",
|
||||
"cmd.component_from_bodies": "Komponenten aus Körpern erstellen",
|
||||
"cmd.component_insert_design": "Konstruktion einfügen",
|
||||
"cmd.component_links": "Verknüpfungen auflisten",
|
||||
@@ -576,6 +578,7 @@
|
||||
"cmd.component_properties": "Physikalische Eigenschaften der Komponente",
|
||||
"cmd.component_relink": "Quelle neu verknüpfen",
|
||||
"cmd.component_rename": "Komponente umbenennen",
|
||||
"cmd.component_replace_with_link": "Durch Verknüpfung ersetzen",
|
||||
"cmd.component_revert_position": "Position zurücksetzen",
|
||||
"cmd.component_unlock": "Inhalt entsperren",
|
||||
"cmd.component_update_links": "Verknüpfungen aktualisieren",
|
||||
@@ -1178,7 +1181,7 @@
|
||||
"search.try": "Geben Sie einen Befehlsnamen, ein Merkmal in diesem Design oder einen Parameter ein. Um einen Befehl mit Werten auszuführen, geben Sie seine ID und ein JSON-Objekt ein: {example}",
|
||||
"search.valid": "Gültig",
|
||||
"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.frame_rate_note": "Zeigt die Bilder pro Sekunde unten rechts in der Ansicht.",
|
||||
"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",
|
||||
@@ -1301,6 +1304,7 @@
|
||||
"ui.agent_chat_files_left_out": "Höchstens {max} Dateien pro Nachricht; ausgelassen: {files}",
|
||||
"ui.agent_chat_files_loading": "Warten, bis die Dateien gelesen sind",
|
||||
"ui.agent_chat_files_max": "Höchstens {max} Dateien pro Nachricht",
|
||||
"ui.agent_chat_flatpak_none_found": "Kein Coding-Agent gefunden. Die Flatpak-Sandbox sieht standardmäßig keine Agenten in Ihrem Benutzerordner und hat keinen Netzwerkzugriff. Um Claude Code und seinen ACP-Adapter zu erlauben, die über nvm oder in ~/.local/bin installiert sind, führen Sie diesen Befehl in einem Terminal aus und starten Sie SolidCraft dann neu. Er gewährt Zugriff auf die genannten Programme und Anmeldedateien sowie Netzwerkzugriff:",
|
||||
"ui.agent_chat_import_failed": "{name}: Der Import ist fehlgeschlagen: {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",
|
||||
@@ -1589,6 +1593,9 @@
|
||||
"ui.export_keymap_tip": "Tasten, S-Box-Favoriten und die Symbolleiste als Datei",
|
||||
"ui.extend": "Verlängern",
|
||||
"ui.extent_type": "Ausdehnungstyp",
|
||||
"ui.extract_component": "In Datei extrahieren…",
|
||||
"ui.extract_design_changed": "Das Design hat sich beim Wählen einer Datei geändert. Starten Sie In Datei extrahieren erneut.",
|
||||
"ui.extract_done": "Die Komponente ist jetzt ein eigenes Design und hier verknüpft.",
|
||||
"ui.extrude": "Extrudieren",
|
||||
"ui.factor": "Faktor",
|
||||
"ui.feature_history": "Feature-Verlauf",
|
||||
@@ -1720,6 +1727,10 @@
|
||||
"ui.length_decimals": "Längen-Dezimalstellen",
|
||||
"ui.light": "Hell",
|
||||
"ui.line": "Linie",
|
||||
"ui.link_copies": "Identische Kopien verknüpfen",
|
||||
"ui.link_copies_keep": "Behalten",
|
||||
"ui.link_copies_link": "Verknüpfen",
|
||||
"ui.link_copies_text": "Diese Komponenten erzeugen dieselben Körper wie {name}. Sollen sie zu Platzierungen seiner Verknüpfung werden?",
|
||||
"ui.lock": "Sperren",
|
||||
"ui.loft": "Loft",
|
||||
"ui.look_at": "Ansehen",
|
||||
@@ -1843,6 +1854,7 @@
|
||||
"ui.render": "Rendern",
|
||||
"ui.renderer": "Renderer",
|
||||
"ui.repeat": "Wiederholen",
|
||||
"ui.replace_with_link_done": "Die Kopien sind jetzt Platzierungen des verknüpften Designs.",
|
||||
"ui.report_a_bug": "Fehler melden",
|
||||
"ui.reset": "Zurücksetzen",
|
||||
"ui.reset_all": "Alle zurücksetzen",
|
||||
|
||||
@@ -609,8 +609,10 @@
|
||||
"cmd.component_activate": "Activate Component",
|
||||
"cmd.component_break_link": "Break Link",
|
||||
"cmd.component_capture_position": "Capture Position",
|
||||
"cmd.component_copies": "Find Identical Copies",
|
||||
"cmd.component_create": "New Component",
|
||||
"cmd.component_delete": "Delete Component",
|
||||
"cmd.component_extract": "Extract to File",
|
||||
"cmd.component_from_bodies": "Create Components from Bodies",
|
||||
"cmd.component_insert_design": "Insert Design",
|
||||
"cmd.component_links": "List Links",
|
||||
@@ -623,6 +625,7 @@
|
||||
"cmd.component_properties": "Component Physical Properties",
|
||||
"cmd.component_relink": "Relink Source",
|
||||
"cmd.component_rename": "Rename Component",
|
||||
"cmd.component_replace_with_link": "Replace with Link",
|
||||
"cmd.component_revert_position": "Revert Position",
|
||||
"cmd.component_unlock": "Unlock Contents",
|
||||
"cmd.component_update_links": "Update Links",
|
||||
@@ -740,6 +743,7 @@
|
||||
"cmd.motion_plot": "Plot Motion Study",
|
||||
"cmd.motion_study": "Motion Study",
|
||||
"cmd.motion_trace": "Motion Trace",
|
||||
"cmd.motion_trace_edit": "Edit Motion Trace",
|
||||
"cmd.motion_trace_keep": "Keep Motion Trace",
|
||||
"cmd.occurrence_copy": "Paste (Instance)",
|
||||
"cmd.occurrence_ground": "Ground",
|
||||
@@ -1353,7 +1357,7 @@
|
||||
"search.try": "Type a command name, a feature in this design, or a parameter. To run a command with values, type its id and a JSON object: {example}",
|
||||
"search.valid": "Valid",
|
||||
"settings.display_quality_note": "Only the display. Designs and exports are not affected.",
|
||||
"settings.frame_rate_note": "Shows frames per second in the view's bottom-right corner. While it is on, the view redraws continuously.",
|
||||
"settings.frame_rate_note": "Shows frames per second in the view's bottom-right corner.",
|
||||
"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",
|
||||
@@ -1398,6 +1402,9 @@
|
||||
"thread.designation": "Designation",
|
||||
"thread.iso_metric": "ISO metric",
|
||||
"thread.select_size": "Select size",
|
||||
"timeline.delete_after_marker_one": "Delete 1 Feature After History Marker",
|
||||
"timeline.delete_after_marker_other": "Delete {count} Features After History Marker",
|
||||
"timeline.delete_many": "Delete {count} Selected Features",
|
||||
"timeline.group": "New Feature Folder",
|
||||
"timeline.move_many": "Move Timeline Items",
|
||||
"timeline.move_to_group": "Move Features to Folder",
|
||||
@@ -1476,6 +1483,7 @@
|
||||
"ui.agent_chat_files_left_out": "At most {max} files go with one message; left out: {files}",
|
||||
"ui.agent_chat_files_loading": "Waiting for the files to be read",
|
||||
"ui.agent_chat_files_max": "At most {max} files on one message",
|
||||
"ui.agent_chat_flatpak_none_found": "No coding agent found. The Flatpak sandbox cannot see agents installed in your home folder and has no network access by default. To allow Claude Code and its ACP adapter installed through nvm or ~/.local/bin, run this command in a terminal, then restart SolidCraft. It grants access to the listed program and sign-in files, plus network access:",
|
||||
"ui.agent_chat_import_failed": "{name}: the import failed: {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_key_in_env": "key set",
|
||||
@@ -1548,8 +1556,10 @@
|
||||
"ui.ai_add": "Add",
|
||||
"ui.ai_add_agent": "Add agent…",
|
||||
"ui.ai_add_agent_title": "Add agent",
|
||||
"ui.ai_add_anthropic": "Anthropic-compatible API",
|
||||
"ui.ai_add_api": "OpenAI-compatible API",
|
||||
"ui.ai_add_custom": "Custom command",
|
||||
"ui.ai_add_endpoint": "API endpoint",
|
||||
"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",
|
||||
@@ -1578,6 +1588,7 @@
|
||||
"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_kind": "Kind",
|
||||
"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.",
|
||||
@@ -1599,6 +1610,7 @@
|
||||
"ui.ai_panel": "Panel",
|
||||
"ui.ai_permissions": "Permissions",
|
||||
"ui.ai_preset": "Preset",
|
||||
"ui.ai_protocol": "Protocol",
|
||||
"ui.ai_remove": "Remove",
|
||||
"ui.ai_request_limit": "stopped after 24 requests for one message; send another message to go on",
|
||||
"ui.ai_reset": "Reset",
|
||||
@@ -1609,6 +1621,8 @@
|
||||
"ui.ai_test": "Test",
|
||||
"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_answered": "Reached: {model} answered",
|
||||
"ui.ai_test_anthropic_tip": "Sends a short message to the endpoint",
|
||||
"ui.ai_test_api_tip": "Asks the endpoint for its models",
|
||||
"ui.ai_test_no_model": "Reached: {count} models, but not {model}",
|
||||
"ui.ai_test_ok": "Reached: {count} models",
|
||||
@@ -1766,6 +1780,9 @@
|
||||
"ui.export_keymap_tip": "Keys, S box favourites and the toolbar, as a file",
|
||||
"ui.extend": "Extend",
|
||||
"ui.extent_type": "Extent Type",
|
||||
"ui.extract_component": "Extract to File…",
|
||||
"ui.extract_design_changed": "The design changed while choosing a file. Start Extract to File again.",
|
||||
"ui.extract_done": "The component is now its own design, linked here.",
|
||||
"ui.extrude": "Extrude",
|
||||
"ui.factor": "Factor",
|
||||
"ui.feature_history": "Feature history",
|
||||
@@ -1904,6 +1921,10 @@
|
||||
"ui.length_decimals": "Length decimals",
|
||||
"ui.light": "Light",
|
||||
"ui.line": "Line",
|
||||
"ui.link_copies": "Link Identical Copies",
|
||||
"ui.link_copies_keep": "Keep",
|
||||
"ui.link_copies_link": "Link",
|
||||
"ui.link_copies_text": "These components build the same bodies as {name}. Make them placements of its link?",
|
||||
"ui.lock": "Lock",
|
||||
"ui.loft": "Loft",
|
||||
"ui.look_at": "Look At",
|
||||
@@ -2027,6 +2048,7 @@
|
||||
"ui.render": "Render",
|
||||
"ui.renderer": "Renderer",
|
||||
"ui.repeat": "Repeat",
|
||||
"ui.replace_with_link_done": "The copies are now placements of the linked design.",
|
||||
"ui.report_a_bug": "Report a bug",
|
||||
"ui.reset": "Reset",
|
||||
"ui.reset_all": "Reset All",
|
||||
|
||||
@@ -1060,7 +1060,7 @@
|
||||
"search.try": "Escribe el nombre de un comando, una operación de este diseño o un parámetro. Para ejecutar un comando con valores, escribe su id y un objeto JSON: {example}",
|
||||
"search.valid": "Válido",
|
||||
"settings.display_quality_note": "Los niveles más finos muestran las caras y aristas curvas con mayor suavidad, pero tardan más en generar la malla. Solo cambia el visor, nunca el diseño ni las exportaciones.",
|
||||
"settings.frame_rate_note": "Muestra los fotogramas por segundo en la esquina inferior derecha de la vista. Mientras esté activado, la vista se redibuja continuamente.",
|
||||
"settings.frame_rate_note": "Muestra los fotogramas por segundo en la esquina inferior derecha de la vista.",
|
||||
"settings.measure_axis_distances": "Mostrar distancias X/Y/Z",
|
||||
"settings.measure_axis_distances_help": "Mostrar las cotas de cada eje global junto a la distancia total mientras está abierta la herramienta Medir.",
|
||||
"settings.msaa_applies_on_restart": "El suavizado de bordes se aplicará la próxima vez que se inicie SolidCraft",
|
||||
@@ -1183,6 +1183,7 @@
|
||||
"ui.agent_chat_files_left_out": "Se pueden enviar como máximo {max} archivos con un mensaje; omitidos: {files}",
|
||||
"ui.agent_chat_files_loading": "Esperando a que se lean los archivos",
|
||||
"ui.agent_chat_files_max": "Como máximo {max} archivos por mensaje",
|
||||
"ui.agent_chat_flatpak_none_found": "No se ha encontrado ningún agente de programación. De forma predeterminada, el entorno aislado de Flatpak no ve los agentes instalados en tu carpeta personal y no tiene acceso a la red. Para permitir Claude Code y su adaptador ACP instalados con nvm o en ~/.local/bin, ejecuta este comando en un terminal y reinicia SolidCraft. Concede acceso a los programas y archivos de inicio de sesión indicados, además de acceso a la red:",
|
||||
"ui.agent_chat_import_failed": "{name}: la importación falló: {error}",
|
||||
"ui.agent_chat_intro": "Habla con un agente de programación que ya utilices o con un servicio de modelos que elijas. Trabaja sobre el diseño abierto mediante las herramientas de SolidCraft: sus cambios se muestran al realizarlos y pueden deshacerse de una vez por mensaje. Lo que puede hacer sin preguntar se configura en Preferencias > IA.",
|
||||
"ui.agent_chat_key_in_env": "clave configurada",
|
||||
|
||||
@@ -1066,7 +1066,7 @@
|
||||
"search.try": "Saisissez un nom de commande, une entité de cette conception ou un paramètre. Pour exécuter une commande avec des valeurs, saisissez son id et un objet JSON : {example}",
|
||||
"search.valid": "Valide",
|
||||
"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.frame_rate_note": "Affiche les images par seconde dans le coin inférieur droit de la vue.",
|
||||
"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",
|
||||
@@ -1189,6 +1189,7 @@
|
||||
"ui.agent_chat_files_left_out": "Un message ne peut contenir que {max} fichiers au plus ; non joints : {files}",
|
||||
"ui.agent_chat_files_loading": "Lecture des fichiers en cours",
|
||||
"ui.agent_chat_files_max": "{max} fichiers au plus par message",
|
||||
"ui.agent_chat_flatpak_none_found": "Aucun agent de programmation trouvé. Par défaut, le bac à sable Flatpak ne voit pas les agents installés dans votre dossier personnel et n’a pas accès au réseau. Pour autoriser Claude Code et son adaptateur ACP installés avec nvm ou dans ~/.local/bin, exécuter cette commande dans un terminal, puis redémarrer SolidCraft. Elle donne accès aux programmes et fichiers de connexion indiqués, ainsi qu’au réseau :",
|
||||
"ui.agent_chat_import_failed": "{name} : l'importation a échoué : {error}",
|
||||
"ui.agent_chat_intro": "Discuter avec un agent de programmation que vous utilisez déjà, ou avec un point d'accès de modèle de votre choix. Il travaille sur la conception ouverte avec les outils de SolidCraft : ses modifications apparaissent au fur et à mesure et s'annulent en une seule étape par message. Ce qu'il peut faire sans demander se règle dans Préférences › IA.",
|
||||
"ui.agent_chat_key_in_env": "clé définie",
|
||||
|
||||
@@ -1060,7 +1060,7 @@
|
||||
"search.try": "Escribe o nome dunha orde, unha operación deste deseño ou un parámetro. Para executar unha orde con valores, escribe o seu id e un obxecto JSON: {example}",
|
||||
"search.valid": "Válido",
|
||||
"settings.display_quality_note": "Os niveis máis finos debuxan as caras e arestas curvas máis suaves e tardan máis en xerar a malla. Só cambia a vista, nunca o deseño nin as exportacións.",
|
||||
"settings.frame_rate_note": "Mostra as imaxes por segundo na esquina inferior dereita da vista. Mentres está activado, a vista redebúxase continuamente.",
|
||||
"settings.frame_rate_note": "Mostra as imaxes por segundo na esquina inferior dereita da vista.",
|
||||
"settings.measure_axis_distances": "Mostrar as distancias en X/Y/Z",
|
||||
"settings.measure_axis_distances_help": "Mostra as compoñentes da distancia segundo os eixes do mundo xunto á distancia total mentres Medir está aberto.",
|
||||
"settings.msaa_applies_on_restart": "O antialiasing aplicarase a próxima vez que se inicie SolidCraft",
|
||||
@@ -1183,6 +1183,7 @@
|
||||
"ui.agent_chat_files_left_out": "Cunha mensaxe van como máximo {max} ficheiros; deixados fóra: {files}",
|
||||
"ui.agent_chat_files_loading": "Agardando a que se lean os ficheiros",
|
||||
"ui.agent_chat_files_max": "Como máximo {max} ficheiros por mensaxe",
|
||||
"ui.agent_chat_flatpak_none_found": "Non se atopou ningún axente de programación. De forma predeterminada, o illamento de Flatpak non ve os axentes instalados no teu cartafol persoal e non ten acceso á rede. Para permitir Claude Code e o seu adaptador ACP instalados con nvm ou en ~/.local/bin, executa esta orde nun terminal e despois reinicia SolidCraft. Concede acceso aos programas e ficheiros de inicio de sesión indicados, ademais de acceso á rede:",
|
||||
"ui.agent_chat_import_failed": "{name}: fallou a importación: {error}",
|
||||
"ui.agent_chat_intro": "Conversa cun axente de programación que xa uses, ou cun punto de acceso de modelo que escollas. Traballa no deseño aberto a través das ferramentas de SolidCraft: os seus cambios vense mentres os fai e desfanse nun paso por mensaxe. O que pode facer sen preguntar defínese en Preferencias > IA.",
|
||||
"ui.agent_chat_key_in_env": "clave configurada",
|
||||
|
||||
@@ -1059,7 +1059,7 @@
|
||||
"search.try": "Írja be egy parancs nevét, a terv egy elemét vagy egy paramétert. Parancs értékekkel való futtatásához írja be az azonosítóját és egy JSON-objektumot: {example}",
|
||||
"search.valid": "Érvényes",
|
||||
"settings.display_quality_note": "A finomabb szintek simábban rajzolják az ívelt lapokat és éleket, de tovább tart a hálózás. Csak a nézetablak változik, a terv és az exportok soha.",
|
||||
"settings.frame_rate_note": "Megjeleníti a másodpercenkénti képkockaszámot a nézet jobb alsó sarkában. Bekapcsolt állapotban a nézet folyamatosan újrarajzolódik.",
|
||||
"settings.frame_rate_note": "Megjeleníti a másodpercenkénti képkockaszámot a nézet jobb alsó sarkában.",
|
||||
"settings.measure_axis_distances": "X/Y/Z távolságok megjelenítése",
|
||||
"settings.measure_axis_distances_help": "A világtengely-összetevők méreteit is megjeleníti a teljes távolság mellett, amíg a Mérés nyitva van.",
|
||||
"settings.msaa_applies_on_restart": "Az élsimítás a SolidCraft következő indításakor lép érvénybe",
|
||||
@@ -1182,6 +1182,7 @@
|
||||
"ui.agent_chat_files_left_out": "Egy üzenethez legfeljebb {max} fájl tartozhat; kihagyva: {files}",
|
||||
"ui.agent_chat_files_loading": "Várakozás a fájlok beolvasására",
|
||||
"ui.agent_chat_files_max": "Egy üzenetben legfeljebb {max} fájl lehet",
|
||||
"ui.agent_chat_flatpak_none_found": "Nem található kódolóügynök. A Flatpak homokozó alapértelmezés szerint nem látja a saját mappájába telepített ügynököket, és nincs hálózati hozzáférése. Az nvm-mel vagy a ~/.local/bin mappába telepített Claude Code és ACP-adaptere engedélyezéséhez futtassa ezt a parancsot egy terminálban, majd indítsa újra a SolidCraftot. Hozzáférést ad a felsorolt programokhoz és bejelentkezési fájlokhoz, valamint a hálózathoz:",
|
||||
"ui.agent_chat_import_failed": "{name}: az importálás sikertelen: {error}",
|
||||
"ui.agent_chat_intro": "Csevegjen egy már használt kódolóügynökkel vagy egy választott modellvégponttal. A megnyitott terven a SolidCraft eszközein keresztül dolgozik: a módosításai láthatók közben, és üzenetenként egy lépésben vonhatók vissza. Hogy mit tehet kérdés nélkül, azt a Beállítások > AI menüpontban adhatja meg.",
|
||||
"ui.agent_chat_key_in_env": "kulcs beállítva",
|
||||
|
||||
@@ -1059,7 +1059,7 @@
|
||||
"search.try": "Ketik nama perintah, fitur di desain ini, atau parameter. Untuk menjalankan perintah dengan nilai, ketik id-nya dan objek JSON: {example}",
|
||||
"search.valid": "Valid",
|
||||
"settings.display_quality_note": "Level lebih halus menggambar muka dan tepi lengkung lebih mulus dan butuh waktu meshing lebih lama. Hanya viewport yang berubah, tidak pernah desain atau ekspor.",
|
||||
"settings.frame_rate_note": "Menampilkan frame per detik di sudut kanan bawah tampilan. Saat aktif, tampilan digambar ulang terus-menerus.",
|
||||
"settings.frame_rate_note": "Menampilkan frame per detik di sudut kanan bawah tampilan.",
|
||||
"settings.measure_axis_distances": "Tampilkan jarak X/Y/Z",
|
||||
"settings.measure_axis_distances_help": "Tampilkan dimensi komponen sumbu dunia di samping jarak total saat Ukur terbuka.",
|
||||
"settings.msaa_applies_on_restart": "Anti-aliasing berlaku saat SolidCraft dimulai berikutnya",
|
||||
@@ -1182,6 +1182,7 @@
|
||||
"ui.agent_chat_files_left_out": "Maksimal {max} file per pesan; tidak disertakan: {files}",
|
||||
"ui.agent_chat_files_loading": "Menunggu file selesai dibaca",
|
||||
"ui.agent_chat_files_max": "Maksimal {max} file per pesan",
|
||||
"ui.agent_chat_flatpak_none_found": "Agen coding tidak ditemukan. Secara bawaan, sandbox Flatpak tidak dapat melihat agen yang terpasang di folder rumah Anda dan tidak memiliki akses jaringan. Untuk mengizinkan Claude Code dan adaptor ACP-nya yang dipasang melalui nvm atau di ~/.local/bin, jalankan perintah ini di terminal, lalu mulai ulang SolidCraft. Perintah ini memberi akses ke program dan berkas masuk yang disebutkan, serta akses jaringan:",
|
||||
"ui.agent_chat_import_failed": "{name}: impor gagal: {error}",
|
||||
"ui.agent_chat_intro": "Mengobrol dengan agen coding yang sudah Anda pakai, atau endpoint model pilihan Anda. Agen bekerja pada desain yang terbuka lewat alat SolidCraft: perubahannya tampil saat dibuat dan dapat diurungkan satu langkah per pesan. Yang boleh dilakukannya tanpa bertanya diatur di Preferensi > AI.",
|
||||
"ui.agent_chat_key_in_env": "key diatur",
|
||||
|
||||
@@ -1063,7 +1063,7 @@
|
||||
"search.try": "Digita il nome di un comando, una feature di questo progetto o un parametro. Per eseguire un comando con dei valori, digita il suo id e un oggetto JSON: {example}",
|
||||
"search.valid": "Valido",
|
||||
"settings.display_quality_note": "I livelli più fini rendono più uniformi le facce curve e gli spigoli e richiedono più tempo per la mesh. Cambia solo la vista, mai il progetto o le esportazioni.",
|
||||
"settings.frame_rate_note": "Mostra i fotogrammi al secondo nell'angolo inferiore destro della vista. Quando è attivo, la vista viene ridisegnata continuamente.",
|
||||
"settings.frame_rate_note": "Mostra i fotogrammi al secondo nell'angolo inferiore destro della vista.",
|
||||
"settings.measure_axis_distances": "Mostra distanze X/Y/Z",
|
||||
"settings.measure_axis_distances_help": "Mostra le componenti lungo gli assi globali accanto alla distanza totale quando Misura è aperto.",
|
||||
"settings.msaa_applies_on_restart": "L'antialiasing verrà applicato al prossimo avvio di SolidCraft",
|
||||
@@ -1186,6 +1186,7 @@
|
||||
"ui.agent_chat_files_left_out": "Un messaggio può contenere al massimo {max} file; esclusi: {files}",
|
||||
"ui.agent_chat_files_loading": "In attesa della lettura dei file",
|
||||
"ui.agent_chat_files_max": "Al massimo {max} file per messaggio",
|
||||
"ui.agent_chat_flatpak_none_found": "Nessun agente di programmazione trovato. Per impostazione predefinita, la sandbox Flatpak non vede gli agenti installati nella tua cartella home e non ha accesso alla rete. Per consentire Claude Code e il suo adattatore ACP installati con nvm o in ~/.local/bin, esegui questo comando in un terminale, poi riavvia SolidCraft. Concede l’accesso ai programmi e ai file di accesso elencati, oltre all’accesso alla rete:",
|
||||
"ui.agent_chat_import_failed": "{name}: importazione non riuscita: {error}",
|
||||
"ui.agent_chat_intro": "Conversa con un agente di programmazione che già usi o con un endpoint di modello a tua scelta. Opera sul progetto aperto tramite gli strumenti di SolidCraft: le modifiche sono visibili mentre vengono eseguite e si annullano in un solo passo per messaggio. Le azioni consentite senza conferma si impostano in Preferenze > IA.",
|
||||
"ui.agent_chat_key_in_env": "chiave impostata",
|
||||
|
||||
@@ -609,8 +609,10 @@
|
||||
"cmd.component_activate": "コンポーネントをアクティブ化",
|
||||
"cmd.component_break_link": "リンクを解除",
|
||||
"cmd.component_capture_position": "位置をキャプチャ",
|
||||
"cmd.component_copies": "同一のコピーを検索",
|
||||
"cmd.component_create": "新規コンポーネント",
|
||||
"cmd.component_delete": "コンポーネントを削除",
|
||||
"cmd.component_extract": "ファイルに抽出",
|
||||
"cmd.component_from_bodies": "ボディからコンポーネントを作成",
|
||||
"cmd.component_insert_design": "デザインを挿入",
|
||||
"cmd.component_links": "リンクを一覧表示",
|
||||
@@ -623,6 +625,7 @@
|
||||
"cmd.component_properties": "コンポーネントの物理的プロパティ",
|
||||
"cmd.component_relink": "参照元を再リンク",
|
||||
"cmd.component_rename": "コンポーネントの名前を変更",
|
||||
"cmd.component_replace_with_link": "リンクに置き換え",
|
||||
"cmd.component_revert_position": "位置を元に戻す",
|
||||
"cmd.component_unlock": "内容のロックを解除",
|
||||
"cmd.component_update_links": "リンクを更新",
|
||||
@@ -740,6 +743,7 @@
|
||||
"cmd.motion_plot": "モーション スタディのグラフ",
|
||||
"cmd.motion_study": "モーション スタディ",
|
||||
"cmd.motion_trace": "モーション トレース",
|
||||
"cmd.motion_trace_edit": "モーション トレースを編集",
|
||||
"cmd.motion_trace_keep": "モーション トレースを保持",
|
||||
"cmd.occurrence_copy": "貼り付け(インスタンス)",
|
||||
"cmd.occurrence_ground": "空間固定",
|
||||
@@ -1353,7 +1357,7 @@
|
||||
"search.try": "コマンド名、このデザインのフィーチャー、またはパラメーターを入力します。値を指定して実行するには、IDとJSONオブジェクトを入力します:{example}",
|
||||
"search.valid": "有効",
|
||||
"settings.display_quality_note": "表示だけに影響します。設計や書き出しは変わりません。",
|
||||
"settings.frame_rate_note": "ビューの右下に 1 秒あたりのフレーム数を表示します。オンの間、ビューは常に再描画されます。",
|
||||
"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 を起動したときに適用されます",
|
||||
@@ -1398,6 +1402,9 @@
|
||||
"thread.designation": "ねじの呼び",
|
||||
"thread.iso_metric": "ISOメートルねじ",
|
||||
"thread.select_size": "サイズを選択",
|
||||
"timeline.delete_after_marker_one": "履歴マーカー以降の 1 個のフィーチャーを削除",
|
||||
"timeline.delete_after_marker_other": "履歴マーカー以降の {count} 個のフィーチャーを削除",
|
||||
"timeline.delete_many": "選択した {count} 個のフィーチャーを削除",
|
||||
"timeline.group": "フィーチャーフォルダを新規作成",
|
||||
"timeline.move_many": "タイムライン項目を移動",
|
||||
"timeline.move_to_group": "フィーチャーをフォルダへ移動",
|
||||
@@ -1476,6 +1483,7 @@
|
||||
"ui.agent_chat_files_left_out": "1 つのメッセージで送れるファイルは {max} 個までです。送らなかったファイル: {files}",
|
||||
"ui.agent_chat_files_loading": "ファイルの読み込みを待っています",
|
||||
"ui.agent_chat_files_max": "1 つのメッセージに添付できるのは {max} 個までです",
|
||||
"ui.agent_chat_flatpak_none_found": "コーディングエージェントが見つかりません。Flatpak のサンドボックスは、既定ではホームフォルダー内のエージェントにアクセスできず、ネットワークにも接続できません。nvm または ~/.local/bin にインストールした Claude Code と ACP アダプターを許可するには、端末で次のコマンドを実行し、SolidCraft を再起動してください。指定したプログラムとログインファイルへのアクセス、およびネットワーク接続を許可します:",
|
||||
"ui.agent_chat_import_failed": "{name}: インポートに失敗しました: {error}",
|
||||
"ui.agent_chat_intro": "普段使っているコーディングエージェント、または選んだモデルのエンドポイントとチャットできます。SolidCraft のツールで開いているデザインを操作し、変更はその場で表示され、メッセージごとに1回で元に戻せます。確認なしで許可する範囲は「環境設定 > AI」で設定します。",
|
||||
"ui.agent_chat_key_in_env": "キー設定済み",
|
||||
@@ -1548,8 +1556,10 @@
|
||||
"ui.ai_add": "追加",
|
||||
"ui.ai_add_agent": "エージェントを追加…",
|
||||
"ui.ai_add_agent_title": "エージェントを追加",
|
||||
"ui.ai_add_anthropic": "Anthropic 互換 API",
|
||||
"ui.ai_add_api": "OpenAI 互換 API",
|
||||
"ui.ai_add_custom": "カスタムコマンド",
|
||||
"ui.ai_add_endpoint": "API エンドポイント",
|
||||
"ui.ai_add_installed": "インストール済みエージェント",
|
||||
"ui.ai_add_installed_note": "インストール済みエージェントの独自エントリ(例: 別の引数で起動)。インストール済みのエージェントは自動で一覧に表示されます。",
|
||||
"ui.ai_added": "追加済み",
|
||||
@@ -1578,6 +1588,7 @@
|
||||
"ui.ai_key_needs_https": "キーは HTTPS 経由、またはこのコンピューター宛てにのみ送信されます。",
|
||||
"ui.ai_key_note": "システムのキーチェーンに保存され、SolidCraft の設定には保存されません。ローカルサーバーの場合は空欄のままにします。",
|
||||
"ui.ai_keychain_error": "システムのキーチェーンが拒否しました: {error}",
|
||||
"ui.ai_kind": "種類",
|
||||
"ui.ai_mode_all": "すべて許可",
|
||||
"ui.ai_mode_all_note": "確認なしで実行します。クラッシュレポートは引き続き対象外で、フォルダー制限も有効です。",
|
||||
"ui.ai_mode_all_warning": "エージェントは確認なしでデザインの保存・上書き・エクスポート・置き換えができます。信頼できるエージェントで、保存済みのデザインに対してのみ使ってください。",
|
||||
@@ -1599,6 +1610,7 @@
|
||||
"ui.ai_panel": "パネル",
|
||||
"ui.ai_permissions": "権限",
|
||||
"ui.ai_preset": "プリセット",
|
||||
"ui.ai_protocol": "プロトコル",
|
||||
"ui.ai_remove": "削除",
|
||||
"ui.ai_request_limit": "1メッセージあたり24リクエストで停止しました。続けるには、もう一度メッセージを送ってください",
|
||||
"ui.ai_reset": "リセット",
|
||||
@@ -1609,6 +1621,8 @@
|
||||
"ui.ai_test": "テスト",
|
||||
"ui.ai_test_acp_ok": "応答あり: {agent}",
|
||||
"ui.ai_test_acp_tip": "エージェントを短時間起動してセッションを要求し、終了します",
|
||||
"ui.ai_test_answered": "接続成功: {model} が応答しました",
|
||||
"ui.ai_test_anthropic_tip": "エンドポイントに短いメッセージを送信します",
|
||||
"ui.ai_test_api_tip": "エンドポイントにモデル一覧を問い合わせます",
|
||||
"ui.ai_test_no_model": "接続成功: {count} 個のモデル({model} はありません)",
|
||||
"ui.ai_test_ok": "接続成功: {count} 個のモデル",
|
||||
@@ -1766,6 +1780,9 @@
|
||||
"ui.export_keymap_tip": "ショートカット、Sボックスのお気に入り、ツールバー設定をファイルに保存",
|
||||
"ui.extend": "延長",
|
||||
"ui.extent_type": "範囲タイプ",
|
||||
"ui.extract_component": "ファイルに抽出…",
|
||||
"ui.extract_design_changed": "ファイルの選択中にデザインが変更されました。ファイルへの抽出をやり直してください。",
|
||||
"ui.extract_done": "コンポーネントは独立したデザインになり、ここにリンクされました。",
|
||||
"ui.extrude": "押し出し",
|
||||
"ui.factor": "倍率",
|
||||
"ui.feature_history": "フィーチャー履歴",
|
||||
@@ -1904,6 +1921,10 @@
|
||||
"ui.length_decimals": "長さの小数点以下の桁数",
|
||||
"ui.light": "ライト",
|
||||
"ui.line": "線分",
|
||||
"ui.link_copies": "同一のコピーをリンク",
|
||||
"ui.link_copies_keep": "そのまま",
|
||||
"ui.link_copies_link": "リンク",
|
||||
"ui.link_copies_text": "これらのコンポーネントは {name} と同じボディを作成します。そのリンクの配置にしますか?",
|
||||
"ui.lock": "ロック",
|
||||
"ui.loft": "ロフト",
|
||||
"ui.look_at": "正面視",
|
||||
@@ -2027,6 +2048,7 @@
|
||||
"ui.render": "レンダリング",
|
||||
"ui.renderer": "レンダラー",
|
||||
"ui.repeat": "繰り返し",
|
||||
"ui.replace_with_link_done": "コピーはリンクされたデザインの配置になりました。",
|
||||
"ui.report_a_bug": "不具合を報告",
|
||||
"ui.reset": "リセット",
|
||||
"ui.reset_all": "すべてリセット",
|
||||
|
||||
@@ -1064,7 +1064,7 @@
|
||||
"search.try": "명령 이름, 이 디자인의 피처 또는 매개변수를 입력하세요. 값과 함께 명령을 실행하려면 명령 ID와 JSON 객체를 입력하세요: {example}",
|
||||
"search.valid": "올바름",
|
||||
"settings.display_quality_note": "세밀할수록 곡면과 모서리가 더 매끄럽게 표시되지만 메시 생성 시간이 늘어납니다. 뷰포트만 바뀌며 설계나 내보내기는 바뀌지 않습니다.",
|
||||
"settings.frame_rate_note": "뷰의 오른쪽 아래에 초당 프레임 수를 표시합니다. 켜져 있는 동안 뷰를 계속 다시 그립니다.",
|
||||
"settings.frame_rate_note": "뷰의 오른쪽 아래에 초당 프레임 수를 표시합니다.",
|
||||
"settings.measure_axis_distances": "X/Y/Z 거리 표시",
|
||||
"settings.measure_axis_distances_help": "측정 대화상자가 열려 있는 동안 전체 거리와 함께 월드 축 방향 치수와 거리를 표시합니다.",
|
||||
"settings.msaa_applies_on_restart": "안티앨리어싱은 다음에 SolidCraft를 시작할 때 적용됩니다",
|
||||
@@ -1187,6 +1187,7 @@
|
||||
"ui.agent_chat_files_left_out": "메시지 하나에는 파일을 최대 {max}개까지 보낼 수 있습니다. 제외됨: {files}",
|
||||
"ui.agent_chat_files_loading": "파일을 읽는 동안 기다리는 중",
|
||||
"ui.agent_chat_files_max": "메시지 하나에 파일은 최대 {max}개",
|
||||
"ui.agent_chat_flatpak_none_found": "코딩 에이전트를 찾지 못했습니다. Flatpak 샌드박스는 기본적으로 홈 폴더에 설치된 에이전트를 볼 수 없고 네트워크에도 접근할 수 없습니다. nvm 또는 ~/.local/bin에 설치한 Claude Code와 ACP 어댑터를 허용하려면 터미널에서 다음 명령을 실행한 뒤 SolidCraft를 다시 시작하세요. 나열된 프로그램과 로그인 파일에 대한 접근 권한 및 네트워크 접근 권한을 부여합니다:",
|
||||
"ui.agent_chat_import_failed": "{name}: 가져오기 실패: {error}",
|
||||
"ui.agent_chat_intro": "이미 사용 중인 코딩 에이전트나 선택한 모델 엔드포인트와 채팅하세요. SolidCraft 도구로 열린 디자인을 다루며, 변경 사항은 바로 보이고 메시지마다 한 번에 실행 취소할 수 있습니다. 묻지 않고 할 수 있는 일은 환경 설정 > AI에서 정합니다.",
|
||||
"ui.agent_chat_key_in_env": "키 설정됨",
|
||||
|
||||
@@ -1060,7 +1060,7 @@
|
||||
"search.try": "Taip nama arahan, ciri dalam reka bentuk ini, atau parameter. Untuk menjalankan arahan dengan nilai, taip ID-nya dan objek JSON: {example}",
|
||||
"search.valid": "Sah",
|
||||
"settings.display_quality_note": "Tahap halus melicinkan muka dan tepi melengkung, tetapi mesh lebih lambat disiapkan. Hanya paparan berubah, bukan reka bentuk atau eksport.",
|
||||
"settings.frame_rate_note": "Papar bingkai sesaat di kanan bawah. Jika diaktifkan, pandangan dilukis semula tanpa henti.",
|
||||
"settings.frame_rate_note": "Papar bingkai sesaat di kanan bawah.",
|
||||
"settings.measure_axis_distances": "Papar jarak X/Y/Z",
|
||||
"settings.measure_axis_distances_help": "Papar jarak paksi dunia X/Y/Z bersama jarak keseluruhan semasa Ukur dibuka.",
|
||||
"settings.msaa_applies_on_restart": "Antialias digunakan apabila SolidCraft dimulakan semula",
|
||||
@@ -1183,6 +1183,7 @@
|
||||
"ui.agent_chat_files_left_out": "Paling banyak {max} fail bersama satu mesej; ditinggalkan: {files}",
|
||||
"ui.agent_chat_files_loading": "Menunggu fail dibaca",
|
||||
"ui.agent_chat_files_max": "Paling banyak {max} fail pada satu mesej",
|
||||
"ui.agent_chat_flatpak_none_found": "Tiada ejen pengekodan. Secara lalai, kotak pasir Flatpak tidak dapat melihat ejen yang dipasang dalam folder rumah anda dan tiada akses rangkaian. Untuk membenarkan Claude Code dan penyesuai ACP-nya yang dipasang melalui nvm atau dalam ~/.local/bin, jalankan arahan ini dalam terminal, kemudian mulakan semula SolidCraft. Ia memberi akses kepada program dan fail log masuk yang disenaraikan, serta akses rangkaian:",
|
||||
"ui.agent_chat_import_failed": "{name}: import gagal: {error}",
|
||||
"ui.agent_chat_intro": "Sembang dengan ejen pengekodan biasa anda atau titik akhir model pilihan. Ejen mengubah reka bentuk melalui alat SolidCraft; perubahan dipaparkan terus dan boleh dibatalkan sekali bagi setiap mesej. Tetapkan kebenaran di Tetapan > AI.",
|
||||
"ui.agent_chat_key_in_env": "kunci tersedia",
|
||||
|
||||
@@ -1059,7 +1059,7 @@
|
||||
"search.try": "Typ een opdrachtnaam, een kenmerk in dit ontwerp of een parameter. Om een opdracht met waarden uit te voeren, typt u de id en een JSON-object: {example}",
|
||||
"search.valid": "Geldig",
|
||||
"settings.display_quality_note": "Fijnere niveaus tekenen gebogen vlakken en randen vloeiender en kosten meer tijd om te meshen. Alleen de viewport verandert, nooit het ontwerp of de exports.",
|
||||
"settings.frame_rate_note": "Toont frames per seconde in de rechteronderhoek van de weergave. Zolang dit aan staat, wordt de weergave continu opnieuw getekend.",
|
||||
"settings.frame_rate_note": "Toont frames per seconde in de rechteronderhoek van de weergave.",
|
||||
"settings.measure_axis_distances": "X/Y/Z-afstanden tonen",
|
||||
"settings.measure_axis_distances_help": "Toon de componentmaten langs de wereldassen naast de totale afstand terwijl Meten open is.",
|
||||
"settings.msaa_applies_on_restart": "Anti-aliasing wordt toegepast bij de volgende start van SolidCraft",
|
||||
@@ -1182,6 +1182,7 @@
|
||||
"ui.agent_chat_files_left_out": "Maximaal {max} bestanden per bericht; weggelaten: {files}",
|
||||
"ui.agent_chat_files_loading": "Wachten tot de bestanden zijn gelezen",
|
||||
"ui.agent_chat_files_max": "Maximaal {max} bestanden per bericht",
|
||||
"ui.agent_chat_flatpak_none_found": "Geen codeeragent gevonden. De Flatpak-sandbox ziet standaard geen agents die in je persoonlijke map zijn geïnstalleerd en heeft geen netwerktoegang. Voer dit commando uit in een terminal en start SolidCraft daarna opnieuw om Claude Code en de ACP-adapter toe te staan die via nvm of in ~/.local/bin zijn geïnstalleerd. Het geeft toegang tot de genoemde programma’s en aanmeldbestanden, plus netwerktoegang:",
|
||||
"ui.agent_chat_import_failed": "{name}: importeren mislukt: {error}",
|
||||
"ui.agent_chat_intro": "Chat met een codeeragent die u al gebruikt, of met een modeleindpunt naar keuze. De agent werkt aan het geopende ontwerp via de tools van SolidCraft: de wijzigingen verschijnen terwijl ze worden gemaakt en worden per bericht als één stap ongedaan gemaakt. Wat hij zonder te vragen mag doen, stelt u in via Voorkeuren > AI.",
|
||||
"ui.agent_chat_key_in_env": "sleutel ingesteld",
|
||||
|
||||
@@ -28,6 +28,7 @@
|
||||
"Also deletes": "Usuwa również",
|
||||
"Angle 2": "Kąt 2",
|
||||
"Animate": "Animuj",
|
||||
"App/system information and command settings are included. Review private details before sharing.": "Dołączone są informacje o aplikacji i systemie oraz ustawienia poleceń. Przed udostępnieniem sprawdź, czy nie ma tam prywatnych danych.",
|
||||
"Appearance name": "Nazwa wyglądu",
|
||||
"Applied Radius": "Zastosowany promień",
|
||||
"Apply To": "Zastosuj do",
|
||||
@@ -83,6 +84,7 @@
|
||||
"Contact": "Kontakt",
|
||||
"Contact Sets": "Zestawy kontaktów",
|
||||
"Contact sets": "Zestawy kontaktów",
|
||||
"Continue on GitHub": "Kontynuuj na GitHubie",
|
||||
"Continuity": "Ciągłość",
|
||||
"Copy Error Message": "Kopiuj komunikat błędu",
|
||||
"Copy Warning Message": "Kopiuj komunikat ostrzeżenia",
|
||||
@@ -102,6 +104,7 @@
|
||||
"Curv. Comb": "Grzebień krzyw.",
|
||||
"Curvature (G2)": "Krzywizna (G2)",
|
||||
"Curvature change (G3)": "Zmiana krzywizny (G3)",
|
||||
"Custom": "Niestandardowy",
|
||||
"Customize Toolbar": "Dostosuj pasek narzędzi",
|
||||
"Delete": "Usuń",
|
||||
"Delete all": "Usuń wszystko",
|
||||
@@ -110,6 +113,8 @@
|
||||
"Delete the set": "Usuń zestaw",
|
||||
"Density": "Gęstość",
|
||||
"Dependents": "Elementy zależne",
|
||||
"Describe the problem you saw": "Opisz zauważony problem",
|
||||
"Describe what happened before continuing.": "Zanim przejdziesz dalej, opisz, co się stało.",
|
||||
"Designs you open or save appear here.": "Tutaj pojawiają się otwierane lub zapisywane projekty.",
|
||||
"Determined by To Object. Choose Angle to edit the angular extent.": "Wynika z opcji Do obiektu. Wybierz Kąt, aby edytować zakres kątowy.",
|
||||
"Direction": "Kierunek",
|
||||
@@ -127,6 +132,7 @@
|
||||
"Enabled": "Włączone",
|
||||
"End bulge": "Wybrzuszenie końca",
|
||||
"End continuity": "Ciągłość końca",
|
||||
"Expected result (optional)": "Oczekiwany wynik (opcjonalnie)",
|
||||
"Explode": "Rozstrzel",
|
||||
"Explode Text": "Rozbij tekst",
|
||||
"Export Animation…": "Eksportuj animację…",
|
||||
@@ -168,6 +174,7 @@
|
||||
"Height": "Wysokość",
|
||||
"Hidden edges": "Krawędzie niewidoczne",
|
||||
"History layout": "Układ historii",
|
||||
"History names": "Nazwy w historii",
|
||||
"Holes": "Otwory",
|
||||
"Holes (edges on them)": "Otwory (krawędzie na nich)",
|
||||
"Home view": "Widok główny",
|
||||
@@ -234,6 +241,7 @@
|
||||
"No matching appearance presets.": "Brak pasujących ustawień wyglądu.",
|
||||
"No matching appearances": "Brak pasujących wyglądów",
|
||||
"No visible bodies or sketches to export.": "Brak widocznych brył lub szkiców do wyeksportowania.",
|
||||
"Nominal diameter": "Średnica nominalna",
|
||||
"None": "Brak",
|
||||
"Not available yet": "Jeszcze niedostępne",
|
||||
"Notch": "Wycięcie",
|
||||
@@ -242,7 +250,10 @@
|
||||
"Open GitHub draft": "Otwórz szkic zgłoszenia na GitHubie",
|
||||
"Open local libraries in the desktop app. You can export this design's library here.": "Otwórz biblioteki lokalne w aplikacji komputerowej. Tutaj możesz wyeksportować bibliotekę tego projektu.",
|
||||
"Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "Otwartoźródłowy parametryczny CAD 3D w języku Rust. Licencja MIT OR Apache-2.0.",
|
||||
"Opens your browser and copies the report text for you to paste into GitHub.": "Otwiera przeglądarkę internetową i kopiuje treść raportu, którą wkleisz na GitHubie.",
|
||||
"Opens your browser. Review and submit your report on GitHub.": "Otwiera przeglądarkę internetową. Sprawdź raport i wyślij go na GitHubie.",
|
||||
"Operator": "Operator",
|
||||
"Orbit (right drag)": "Obracanie widoku (przeciąganie prawym przyciskiem)",
|
||||
"Other side": "Druga strona",
|
||||
"Other surface (mutual trim)": "Druga powierzchnia (wzajemne przycięcie)",
|
||||
"Outside": "Na zewnątrz",
|
||||
@@ -257,6 +268,7 @@
|
||||
"Pick the tool bodies": "Wybierz bryły narzędziowe",
|
||||
"Picked": "Wybrane",
|
||||
"Picked point": "Wybrany punkt",
|
||||
"Pitch": "Skok",
|
||||
"Place at the origin instead": "Zamiast tego umieść w początku układu",
|
||||
"Plastic Rules": "Reguły tworzyw",
|
||||
"Playback": "Odtwarzanie",
|
||||
@@ -290,6 +302,8 @@
|
||||
"Remove the track": "Usuń ścieżkę",
|
||||
"Remove this point": "Usuń ten punkt",
|
||||
"Report a bug — review a screenshot and open a GitHub draft": "Zgłoś błąd — sprawdź zrzut ekranu i otwórz szkic zgłoszenia na GitHubie",
|
||||
"Report text copied. Paste it into GitHub and submit your report there.": "Skopiowano treść raportu. Wklej ją na GitHubie i tam wyślij raport.",
|
||||
"Reports are public. A GitHub account is required.": "Raporty są publiczne. Wymagane jest konto GitHub.",
|
||||
"Reset Toolbar": "Przywróć pasek narzędzi",
|
||||
"Resize Part": "Zmień rozmiar części",
|
||||
"Restore View": "Przywróć widok",
|
||||
@@ -304,6 +318,7 @@
|
||||
"Revert Pos.": "Przywróć poł.",
|
||||
"Revert Position": "Przywróć położenie",
|
||||
"Review the report and screenshot before opening GitHub.": "Przed otwarciem GitHuba sprawdź raport i zrzut ekranu.",
|
||||
"Review your report on GitHub and click Submit new issue to publish it.": "Sprawdź raport na GitHubie i kliknij Submit new issue, aby go opublikować.",
|
||||
"Rim Edge": "Krawędź obrzeża",
|
||||
"Roll History Marker Here": "Przesuń tutaj znacznik historii",
|
||||
"Round": "Okrągłe",
|
||||
@@ -314,10 +329,12 @@
|
||||
"SURFACE QUALITY": "JAKOŚĆ POWIERZCHNI",
|
||||
"Save Rule": "Zapisz regułę",
|
||||
"Save View": "Zapisz widok",
|
||||
"Save screenshot…": "Zapisz zrzut ekranu…",
|
||||
"Save the study as an animated GIF, seen as the viewport shows it": "Zapisz badanie jako animowany GIF, tak jak widać je w widoku",
|
||||
"Saved preview. Geometry is being checked before editing.": "Zapisany podgląd. Geometria jest sprawdzana przed edycją.",
|
||||
"Scale factor": "Współczynnik skali",
|
||||
"Scene": "Scena",
|
||||
"Screenshot (optional)": "Zrzut ekranu (opcjonalnie)",
|
||||
"Search": "Szukaj",
|
||||
"Search commands": "Szukaj poleceń",
|
||||
"Search this library": "Przeszukaj tę bibliotekę",
|
||||
@@ -352,17 +369,21 @@
|
||||
"Start continuity": "Ciągłość początku",
|
||||
"Step": "Krok",
|
||||
"Steps": "Kroki",
|
||||
"Steps to reproduce (optional)": "Kroki do odtworzenia (opcjonalnie)",
|
||||
"Stitch the kept pieces": "Zszyj zachowane części",
|
||||
"Stitch to both bodies": "Zszyj z obiema bryłami",
|
||||
"Study": "Badanie",
|
||||
"Style": "Styl",
|
||||
"Summary": "Podsumowanie",
|
||||
"Suppressed": "Wygaszone",
|
||||
"Surface": "Powierzchnia",
|
||||
"Swap Ends": "Zamień końce",
|
||||
"TRIM": "PRZYCINANIE",
|
||||
"Tangent (G1)": "Styczność (G1)",
|
||||
"Tangent Chain": "Łańcuch styczny",
|
||||
"Tap drill diameter": "Średnica wiertła pod gwint",
|
||||
"Tear": "Rozdarcie",
|
||||
"Technical details": "Szczegóły techniczne",
|
||||
"The dashed sketch is a saved plane guide. Select a new face to repair the attachment.": "Przerywany szkic to zapisana płaszczyzna pomocnicza. Wybierz nową ścianę, aby naprawić zaczepienie.",
|
||||
"The saved author occurrence is missing. Select a valid author placement before rebinding.": "Brak zapisanego wystąpienia autora. Przed ponownym powiązaniem wybierz prawidłowe położenie autora.",
|
||||
"Then": "Wtedy",
|
||||
@@ -374,6 +395,7 @@
|
||||
"This child is shared. Deleting it removes it from every copy of its parent.": "Ten element podrzędny jest współdzielony. Usunięcie go usuwa go z każdej kopii elementu nadrzędnego.",
|
||||
"This child is shared. Position changes apply to every copy of its parent.": "Ten element podrzędny jest współdzielony. Zmiany położenia dotyczą każdej kopii elementu nadrzędnego.",
|
||||
"This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "Ta ściana nie zapewnia trwałego zaczepienia. Wybierz inną ścianę lub jawnie użyj stałej płaszczyzny.",
|
||||
"This image is not attached to GitHub yet. Copy or save it, then attach it on GitHub.": "Ten obraz nie jest jeszcze dołączony na GitHubie. Skopiuj go lub zapisz, a potem dołącz na GitHubie.",
|
||||
"To Offset": "Do odsunięcia",
|
||||
"To edges": "Do krawędzi",
|
||||
"Tolerance": "Tolerancja",
|
||||
@@ -399,6 +421,9 @@
|
||||
"Wall": "Ścianka",
|
||||
"Wall Location": "Położenie ścianki",
|
||||
"Wall Thickness": "Grubość ścianki",
|
||||
"What did you do just before the problem? A short list is enough": "Co robiłeś tuż przed wystąpieniem problemu? Wystarczy krótka lista",
|
||||
"What did you expect to see?": "Czego się spodziewałeś?",
|
||||
"What happened?": "Co się stało?",
|
||||
"When": "Gdy",
|
||||
"Width": "Szerokość",
|
||||
"Will fail": "Nie powiedzie się",
|
||||
@@ -409,6 +434,29 @@
|
||||
"Z angle": "Kąt Z",
|
||||
"Z distance": "Odległość Z",
|
||||
"Zebra": "Zebra",
|
||||
"ai.prefs.availability": "Sterowanie asystentem",
|
||||
"ai.prefs.background_commands": "Uruchamiaj polecenia agenta w tle",
|
||||
"ai.prefs.follow_camera": "Obracaj kamerę do szkiców",
|
||||
"ai.prefs.follow_camera_off": "Automatyczne podążanie kamery jest wyłączone.",
|
||||
"ai.prefs.follow_camera_on": "Kamera obraca się przodem do szkiców tworzonych przez agenta.",
|
||||
"ai.prefs.intro": "Agenty, uprawnienia i sposób pokazywania ich pracy.",
|
||||
"ai.prefs.make_default": "Używaj domyślnie",
|
||||
"ai.prefs.no_agents": "Brak agentów. Dodaj agenta lub odśwież, aby wyszukać zainstalowane agenty.",
|
||||
"ai.prefs.no_saved_approvals": "Brak zapisanych zgód.",
|
||||
"ai.prefs.override_all_warning": "Ten agent może zapisywać, nadpisywać, eksportować i zastępować projekt bez pytania.",
|
||||
"ai.prefs.permission_all": "Zezwalaj na wszystko",
|
||||
"ai.prefs.permission_all_summary": "Dostępne narzędzia SolidCraft działają bez pytania.",
|
||||
"ai.prefs.permission_ask": "Pytaj przed zmianami",
|
||||
"ai.prefs.permission_ask_summary": "Zatwierdzaj każdą zmianę projektu i każdą operację na plikach.",
|
||||
"ai.prefs.permission_edits": "Zezwalaj na edycję modelu",
|
||||
"ai.prefs.permission_edits_summary": "Edycja modelu działa bez pytania; operacje na plikach i nieodwracalne nadal wymagają pytania.",
|
||||
"ai.prefs.permission_scope": "Dotyczy tylko narzędzi SolidCraft. Powłoka agenta i edycja plików podlegają jego własnym uprawnieniom.",
|
||||
"ai.prefs.pointer_preview_hidden": "Wskaźnik ukryty",
|
||||
"ai.prefs.pointer_preview_speed": "Wskaźnik agenta · {speed}",
|
||||
"ai.prefs.pointer_speed": "Szybkość ruchu",
|
||||
"ai.prefs.privacy_note": "Rozmowę otrzymuje tylko wybrany przez Ciebie agent lub punkt końcowy. Klucze punktów końcowych są przechowywane w systemowym pęku kluczy.",
|
||||
"ai.prefs.show_pointer": "Pokaż wskaźnik agenta",
|
||||
"ai.prefs.turn_limit_hint": "Maksymalna liczba wywołań narzędzi zmieniających projekt, które asystent może wykonać dla jednej wiadomości.",
|
||||
"angle, height": "kąt, wysokość",
|
||||
"appearance.dielectric_ior": "Współczynnik załamania dielektryka (IOR)",
|
||||
"appearance.metallic": "Metaliczność",
|
||||
@@ -759,6 +807,7 @@
|
||||
"cmd.view_graphics_preset": "Ustawienie graficzne",
|
||||
"cmd.view_list": "Lista widoków nazwanych",
|
||||
"cmd.view_navigate": "Nawiguj widokiem",
|
||||
"cmd.view_normal_to": "Prostopadle do zaznaczenia",
|
||||
"cmd.view_rename": "Zmień nazwę widoku nazwanego",
|
||||
"cmd.view_save": "Nowy widok nazwany",
|
||||
"color.copy": "Kliknij, aby skopiować wartości koloru",
|
||||
@@ -856,6 +905,12 @@
|
||||
"help.licences": "Licencje",
|
||||
"help.mit": "Licencja MIT",
|
||||
"help.notice": "NOTICE",
|
||||
"help.solid.chamfer": "Ścina zaznaczone krawędzie płaską fazą o zadanej odległości. Służy do łamania ostrych krawędzi lub ułatwienia wprowadzenia kołka czy śruby.",
|
||||
"help.solid.extrude": "Wyciąga profil szkicu w 3D na zadaną odległość, dodając lub usuwając materiał. Służy do zamiany płaskiego obrysu w blok, występ lub kieszeń.",
|
||||
"help.solid.fillet": "Zaokrągla zaznaczone krawędzie gładkim łukiem o zadanym promieniu. Służy do złagodzenia ostrych krawędzi dla wytrzymałości, wygody lub wyglądu.",
|
||||
"help.solid.hole": "Wierci okrągły otwór o zadanej średnicy w wybranym punkcie ściany. Służy do otworów przelotowych pod śruby, kołki i innych prostych okrągłych otworów.",
|
||||
"help.solid.revolve": "Obraca profil szkicu wokół osi, tworząc okrągłą bryłę. Służy do wałków, gałek, misek i wszystkich części okrągłych względem osi.",
|
||||
"help.solid.shell": "Wydrąża bryłę, pozostawiając ścianki o zadanej grubości, i może otworzyć wybrane ściany. Służy do pudełek, pokryw i innych części cienkościennych.",
|
||||
"help.third_party": "Licencje stron trzecich",
|
||||
"home.back": "Wróć do {name}",
|
||||
"home.crashes": "Raporty awarii",
|
||||
@@ -965,6 +1020,8 @@
|
||||
"motion.to_end": "Na koniec",
|
||||
"motion.to_start": "Na początek",
|
||||
"motion.track_name": "Ścieżka {number}",
|
||||
"nav.free_orbit.help": "Mysz i mysz 3D obracają widok przez oba bieguny i zachowują przechylenie. Przyciąganie do osi z Shift jest wyłączone.",
|
||||
"nav.free_orbit.label": "Swobodne obracanie",
|
||||
"nav.touchpad.help": "Przytrzymaj Shift i poruszaj wskaźnikiem, aby przesuwać; przytrzymaj Alt/Option i poruszaj nim, aby obracać widok. Przycisk myszy nie jest potrzebny. Przewijanie w pionie powiększa.",
|
||||
"nav.touchpad.label": "Touchpad",
|
||||
"nav.touchpad.orbit": "Obracanie widoku (przytrzymaj Alt/Option i poruszaj; bez przycisku myszy)",
|
||||
@@ -987,8 +1044,130 @@
|
||||
"pattern.flip_direction": "Odwróć kierunek",
|
||||
"pick a hole to seat it, or OK places it at the origin": "wybierz otwór, aby go osadzić, lub OK umieszcza go w początku układu",
|
||||
"pick one or two vertices, edges or faces": "wybierz jeden lub dwa wierzchołki, krawędzie lub ściany",
|
||||
"prefs.add_item": "Dodaj element",
|
||||
"prefs.alt_frees_manipulators": "Alt / Option zwalnia również strzałki manipulatora",
|
||||
"prefs.anti_aliasing_note": "Wygładza poszarpane krawędzie.",
|
||||
"prefs.applies_on_restart": "Działa po ponownym uruchomieniu",
|
||||
"prefs.assistant": "Asystent",
|
||||
"prefs.axes": "Osie",
|
||||
"prefs.axis": "Oś",
|
||||
"prefs.bottom": "Dół",
|
||||
"prefs.browser": "Przeglądarka",
|
||||
"prefs.built_in": "Wbudowana",
|
||||
"prefs.button_left": "Przeciąganie lewym",
|
||||
"prefs.button_middle": "Przeciąganie środkowym",
|
||||
"prefs.button_right": "Przeciąganie prawym",
|
||||
"prefs.choose_font": "Wybierz plik czcionki…",
|
||||
"prefs.click": "Kliknięcie",
|
||||
"prefs.contact_shading": "Miękkie cieniowanie kontaktowe",
|
||||
"prefs.contact_shading_note": "Miękkie cieniowanie tam, gdzie części są blisko siebie.",
|
||||
"prefs.context_menu": "Menu kontekstowe",
|
||||
"prefs.context_menu_ring": "Menu kontekstowe · przytrzymaj, aby otworzyć menu promieniste",
|
||||
"prefs.cpu": "CPU (programowo)",
|
||||
"prefs.crash_reports": "Otwórz raporty o awariach…",
|
||||
"prefs.crash_reports_note": "Raporty są przechowywane na tym komputerze, razem z projektem i poleceniami, które odtwarzają problem.",
|
||||
"prefs.ctrl_cmd": "Ctrl / Cmd",
|
||||
"prefs.curved_surfaces": "Powierzchnie zakrzywione",
|
||||
"prefs.curves": "Powierzchnie zakrzywione",
|
||||
"prefs.dead_zone_note": "Zakreskowany pas to strefa martwa: ruch wewnątrz niej jest pomijany.",
|
||||
"prefs.default": "domyślnie",
|
||||
"prefs.design": "Ustawienia domyślne projektu",
|
||||
"prefs.design_note": "Ustawienia, z którymi startują nowe projekty. Otwarte projekty zachowują własne.",
|
||||
"prefs.devices": "Mysz 3D",
|
||||
"prefs.display": "Wyświetlanie",
|
||||
"prefs.edges": "Krawędzie i cieniowanie",
|
||||
"prefs.extend": "Rozszerz",
|
||||
"prefs.extra_navigation": "Ctrl+przeciąganie lewym na pustym miejscu obraca widok; przytrzymaj Spację, aby przesuwać.",
|
||||
"prefs.follows_os": "Zgodnie z systemem",
|
||||
"prefs.font": "Czcionka",
|
||||
"prefs.font_fallback": "Znaki, których brakuje w wybranej czcionce, są brane z czcionki wbudowanej, więc żadna etykieta nie pokaże pustego prostokąta.",
|
||||
"prefs.font_sample": "Zażółć gęślą jaźń · Ø12.50 mm · 45.0° · 0123456789",
|
||||
"prefs.font_unreadable": "Nie można odczytać wybranej czcionki.",
|
||||
"prefs.general": "Ogólne",
|
||||
"prefs.general_note": "Język, zapisywanie i aktualizacje.",
|
||||
"prefs.gesture_orbit": "Obracanie widoku",
|
||||
"prefs.gesture_pan": "Przesuwanie",
|
||||
"prefs.gesture_zoom": "Powiększanie",
|
||||
"prefs.graphics": "Grafika",
|
||||
"prefs.graphics_note": "Wybierz między szybkością a gładkością. Każda opcja pokazuje swój efekt na przykładzie.",
|
||||
"prefs.graphics_presets_note": "Ustawienia wstępne zmieniają razem poniższe opcje.",
|
||||
"prefs.history": "Historia",
|
||||
"prefs.hold_stop_snapping": "Przytrzymaj, aby wyłączyć przyciąganie",
|
||||
"prefs.icons_only": "Tylko ikony",
|
||||
"prefs.imported_file": "Zaimportowany plik",
|
||||
"prefs.input": "Wprowadzanie",
|
||||
"prefs.interface": "Interfejs",
|
||||
"prefs.interface_language": "Język interfejsu",
|
||||
"prefs.interface_note": "Wygląd SolidCraft i rozmieszczenie jego elementów.",
|
||||
"prefs.interval_minutes": "{n} min",
|
||||
"prefs.labels": "Etykiety",
|
||||
"prefs.layout": "Układ",
|
||||
"prefs.layout_note": "Kompaktowy dokuje panele do krawędzi okna. Przezroczystość przeglądarki jest dostępna w układzie Pływający. Stronę asystenta zmienisz na stronie Asystent.",
|
||||
"prefs.left": "Lewo",
|
||||
"prefs.left_click": "Kliknięcie lewym",
|
||||
"prefs.live_input": "Bieżące wejście",
|
||||
"prefs.live_preview": "Podgląd na żywo",
|
||||
"prefs.minutes": "minut",
|
||||
"prefs.minutes_suffix": " min",
|
||||
"prefs.mouse": "Mysz i gładzik",
|
||||
"prefs.mouse_heading": "Mysz",
|
||||
"prefs.mouse_mapping": "Przypisanie przycisków myszy",
|
||||
"prefs.navigation": "Nawigacja",
|
||||
"prefs.navigation_note": "Jak mysz, gładzik i mysz 3D poruszają widokiem.",
|
||||
"prefs.not_on_gpu": "niedostępne na tym GPU",
|
||||
"prefs.on": "Włączone",
|
||||
"prefs.opaque": "Nieprzezroczysta",
|
||||
"prefs.orbit_snap": "Przytrzymaj Shift podczas obracania widoku, aby przyciągnąć do osi.",
|
||||
"prefs.orientation": "Orientacja",
|
||||
"prefs.overall_speed": "Szybkość ogólna",
|
||||
"prefs.preview_choices": "Podgląd wybranych opcji",
|
||||
"prefs.quality_default": "domyślnie",
|
||||
"prefs.quality_fastest": "najszybciej",
|
||||
"prefs.quality_slowest": "najwolniej",
|
||||
"prefs.quality_smoother": "gładziej",
|
||||
"prefs.reports_saved": "Zapisane: {n}",
|
||||
"prefs.right_click": "Kliknięcie prawym",
|
||||
"prefs.saving": "Autozapis i odzyskiwanie",
|
||||
"prefs.scale_note": "Także Ctrl + / Ctrl − w oknie. Przyciski mają 28 px przy 100%.",
|
||||
"prefs.scale_text": "Skala i tekst",
|
||||
"prefs.select": "Zaznacz",
|
||||
"prefs.select_one_item": "Zaznacz jeden element",
|
||||
"prefs.selecting": "Zaznaczanie",
|
||||
"prefs.shift": "Shift",
|
||||
"prefs.shift_add_ctrl_toggle": "Shift tylko dodaje; Ctrl / Cmd przełącza",
|
||||
"prefs.shift_add_note": "Włączone: Shift dodaje, Ctrl / Cmd przełącza. Wyłączone (domyślnie): oba przełączają.",
|
||||
"prefs.shortcuts": "Skróty",
|
||||
"prefs.sketch_selection": "Szkic i zaznaczanie",
|
||||
"prefs.sketch_selection_heading": "Szkic i zaznaczanie",
|
||||
"prefs.sketch_selection_note": "Jak działa przyciąganie w szkicach i jak kliknięcia zaznaczają.",
|
||||
"prefs.sketching": "Szkicowanie",
|
||||
"prefs.snap_drawing_note": "Podczas rysowania lub przeciągania punktu szkicu.",
|
||||
"prefs.source": "Źródło",
|
||||
"prefs.speed": "Szybkość",
|
||||
"prefs.stand_up_note": "Gdy plik STEP lub IGES otworzy się z osią Z w górę, proponuj obrót o ćwierć obrotu wokół osi X.",
|
||||
"prefs.status_done": "Gotowe",
|
||||
"prefs.status_error": "Błąd",
|
||||
"prefs.status_selected": "Zaznaczone",
|
||||
"prefs.status_warning": "Ostrzeżenie",
|
||||
"prefs.supersampling_brief": "Rysuje widok w większym rozmiarze i go zmniejsza: bardzo ostro, ale bardziej obciąża.",
|
||||
"prefs.tab_accent_note": "Kolor akcentu podąża za aktywną kartą",
|
||||
"prefs.theme_file": "plik motywu",
|
||||
"prefs.timeline_half_hour": "−30 min",
|
||||
"prefs.timeline_now": "teraz",
|
||||
"prefs.timeline_quarter_hour": "−15",
|
||||
"prefs.toggle_item": "Dodaj element lub usuń go ponownie",
|
||||
"prefs.toolbar": "Pasek narzędzi",
|
||||
"prefs.translucent": "Półprzezroczysta",
|
||||
"prefs.under_browser": "Pod przeglądarką",
|
||||
"prefs.under_cursor": "Pod kursorem",
|
||||
"prefs.units_precision": "Jednostki i dokładność",
|
||||
"prefs.updates": "Aktualizacje",
|
||||
"prefs.view": "Zachowanie widoku",
|
||||
"prefs.viewport": "Widok",
|
||||
"prefs.wheel": "Kółko",
|
||||
"prefs.wheel_trackpad": "Kółko i gładzik",
|
||||
"prefs.workspace": "Środowisko pracy",
|
||||
"prefs.zoom_toward_cursor": "Powiększanie w stronę kursora",
|
||||
"properties.title": "Właściwości: {name}",
|
||||
"recovery.days_ago": "{count} dni temu",
|
||||
"recovery.detail": "{file} · elementy: {features} · autozapis {when}",
|
||||
@@ -1060,7 +1239,7 @@
|
||||
"search.try": "Wpisz nazwę polecenia, element tego projektu lub parametr. Aby uruchomić polecenie z wartościami, wpisz jego identyfikator i obiekt JSON: {example}",
|
||||
"search.valid": "Prawidłowe",
|
||||
"settings.display_quality_note": "Wyższe poziomy rysują zakrzywione ściany i krawędzie gładziej, ale siatka powstaje dłużej. Zmienia się tylko widok, nigdy projekt ani eksport.",
|
||||
"settings.frame_rate_note": "Pokazuje liczbę klatek na sekundę w prawym dolnym rogu widoku. Gdy jest włączone, widok odświeża się bez przerwy.",
|
||||
"settings.frame_rate_note": "Pokazuje liczbę klatek na sekundę w prawym dolnym rogu widoku.",
|
||||
"settings.measure_axis_distances": "Pokaż odległości X/Y/Z",
|
||||
"settings.measure_axis_distances_help": "Gdy pomiar jest otwarty, pokazuj składowe wzdłuż osi globalnych obok odległości całkowitej.",
|
||||
"settings.msaa_applies_on_restart": "Wygładzanie krawędzi zadziała po ponownym uruchomieniu SolidCraft",
|
||||
@@ -1105,6 +1284,9 @@
|
||||
"thread.designation": "Oznaczenie",
|
||||
"thread.iso_metric": "Metryczny ISO",
|
||||
"thread.select_size": "Wybierz rozmiar",
|
||||
"timeline.delete_after_marker_one": "Usuń 1 funkcję za znacznikiem historii",
|
||||
"timeline.delete_after_marker_other": "Usuń funkcje za znacznikiem historii: {count}",
|
||||
"timeline.delete_many": "Usuń zaznaczone funkcje: {count}",
|
||||
"timeline.group": "Nowy folder funkcji",
|
||||
"timeline.move_many": "Przenieś elementy osi czasu",
|
||||
"timeline.move_to_group": "Przenieś funkcje do folderu",
|
||||
@@ -1183,6 +1365,7 @@
|
||||
"ui.agent_chat_files_left_out": "Do jednej wiadomości można dołączyć najwyżej {max} plików; pominięto: {files}",
|
||||
"ui.agent_chat_files_loading": "Oczekiwanie na odczytanie plików",
|
||||
"ui.agent_chat_files_max": "Najwyżej {max} plików w jednej wiadomości",
|
||||
"ui.agent_chat_flatpak_none_found": "Nie znaleziono agenta programistycznego. Piaskownica Flatpak domyślnie nie widzi agentów zainstalowanych w folderze domowym i nie ma dostępu do sieci. Aby zezwolić na Claude Code i jego adapter ACP zainstalowane przez nvm lub w ~/.local/bin, uruchom to polecenie w terminalu, a potem uruchom ponownie SolidCraft. Daje ono dostęp do wymienionych programów i plików logowania oraz dostęp do sieci:",
|
||||
"ui.agent_chat_import_failed": "{name}: import się nie powiódł: {error}",
|
||||
"ui.agent_chat_intro": "Rozmawiaj z agentem programistycznym, którego już używasz, lub z wybranym punktem końcowym modelu. Pracuje on na otwartym projekcie za pomocą narzędzi SolidCraft: jego zmiany są widoczne na bieżąco, a cofa się je jednym krokiem na wiadomość. To, co może robić bez pytania, ustawisz w Preferencje > AI.",
|
||||
"ui.agent_chat_key_in_env": "klucz ustawiony",
|
||||
@@ -1250,6 +1433,8 @@
|
||||
"ui.agent_chat_waiting": "Czeka na Ciebie",
|
||||
"ui.agent_cursor": "Kursor agenta",
|
||||
"ui.agent_cursor_speed": "Szybkość kursora agenta",
|
||||
"ui.agent_off_thread": "Zachowaj responsywność okna, gdy agenty wykonują polecenia",
|
||||
"ui.agent_off_thread_note": "Wolne polecenia agenta (z panelu AI lub klienta MCP) są liczone obok okna: możesz dalej obracać i oglądać widok oraz zatrzymać polecenie przyciskiem w widoku. Wyłączone: każde działa w wątku okna, a okno na nie czeka.",
|
||||
"ui.ai_add": "Dodaj",
|
||||
"ui.ai_add_agent": "Dodaj agenta…",
|
||||
"ui.ai_add_agent_title": "Dodaj agenta",
|
||||
@@ -1577,10 +1762,17 @@
|
||||
"ui.hideProfile": "Ukryj profil",
|
||||
"ui.history_back": "Cofnij o jeden krok",
|
||||
"ui.history_below_browser": "Pod przeglądarką",
|
||||
"ui.history_edge_hint": "kliknij dwukrotnie krawędź",
|
||||
"ui.history_first": "Przejdź do początku",
|
||||
"ui.history_forward": "Przejdź o jeden krok do przodu",
|
||||
"ui.history_hide_names": "Ukryj nazwy",
|
||||
"ui.history_last": "Przejdź do końca",
|
||||
"ui.history_marker_tip": "Znacznik historii: przeciągnij, aby cofnąć model; nowe funkcje trafiają tutaj",
|
||||
"ui.history_names": "Nazwy",
|
||||
"ui.history_play": "Odtwórz do końca",
|
||||
"ui.history_show_names": "Pokaż nazwy",
|
||||
"ui.history_title": "Historia",
|
||||
"ui.history_toggle_names": "Pokaż lub ukryj nazwy funkcji",
|
||||
"ui.hole": "Otwór",
|
||||
"ui.hole_tap_type": "Typ gwintu otworu",
|
||||
"ui.hole_type": "Typ otworu",
|
||||
@@ -1792,6 +1984,7 @@
|
||||
"ui.smooth_wheel_zoom": "Płynne powiększanie kółkiem",
|
||||
"ui.smooth_wheel_zoom_tip": "Wyłącz, aby każdy ruch kółka działał od razu, bez wygładzania",
|
||||
"ui.snap": "Przyciąganie",
|
||||
"ui.space_mouse_axes_reassigned": "Osie są przypisane inaczej w Preferencjach i to przypisanie nadal działa niezależnie od tej kalibracji.",
|
||||
"ui.space_mouse_calibrate": "Kalibruj…",
|
||||
"ui.space_mouse_calibrate_tip": "Przesuwaj nakładkę zgodnie z poleceniami okna, aby SolidCraft nauczył się kierunku i zakresu każdej osi tej myszy 3D. Zapisywane dla tej myszy 3D.",
|
||||
"ui.space_mouse_calibrate_title": "Kalibracja myszy 3D",
|
||||
@@ -1801,12 +1994,26 @@
|
||||
"ui.space_mouse_calibration_no_response": "Jedna oś prawie się nie poruszyła, więc nie można jej skalibrować. Zacznij od nowa i za każdym razem wychylaj nakładkę mocniej.",
|
||||
"ui.space_mouse_dead_zone": "Strefa martwa",
|
||||
"ui.space_mouse_dead_zone_tip": "O ile trzeba wychylić nakładkę, zanim widok się poruszy, jako część pełnego wychylenia. Zwiększ, jeśli widok dryfuje przy nieruszanej nakładce.",
|
||||
"ui.space_mouse_driven_by": "Który skalibrowany ruch urządzenia steruje tą osią. Wybranie ruchu używanego już przez inną oś zamienia je miejscami.",
|
||||
"ui.space_mouse_driven_by_label": "sterowana przez",
|
||||
"ui.space_mouse_driver": "Sterownik myszy 3D",
|
||||
"ui.space_mouse_driver_auto": "Automatycznie",
|
||||
"ui.space_mouse_driver_direct": "Bezpośrednio (hidraw)",
|
||||
"ui.space_mouse_driver_only_direct": "Bezpośredni odczyt urządzenia; spacenavd nie działa",
|
||||
"ui.space_mouse_driver_only_spacenavd": "Odczyt przez spacenavd, jedyny dostępny sposób",
|
||||
"ui.space_mouse_forget": "Zapomnij kalibrację",
|
||||
"ui.space_mouse_hint": "Przesuwaj i obracaj widok jednocześnie; w szkicach działa tylko przesuwanie i powiększanie.",
|
||||
"ui.space_mouse_motion_rotation_x": "Obrót X",
|
||||
"ui.space_mouse_motion_rotation_y": "Obrót Y",
|
||||
"ui.space_mouse_motion_rotation_z": "Obrót Z",
|
||||
"ui.space_mouse_motion_translation_x": "Przesunięcie X",
|
||||
"ui.space_mouse_motion_translation_y": "Przesunięcie Y",
|
||||
"ui.space_mouse_motion_translation_z": "Przesunięcie Z",
|
||||
"ui.space_mouse_navigate": "Nawiguj za pomocą SpaceNavigator / SpaceMouse",
|
||||
"ui.space_mouse_none": "Nie znaleziono myszy 3D",
|
||||
"ui.space_mouse_not_calibrated": "Nieskalibrowano",
|
||||
"ui.space_mouse_reading": "Odczyt",
|
||||
"ui.space_mouse_reset_axes": "Resetuj przypisanie osi",
|
||||
"ui.space_mouse_step_lift": "Unieś nakładkę, przytrzymaj, a następnie puść.",
|
||||
"ui.space_mouse_step_press": "Wciśnij nakładkę w dół, przytrzymaj, a następnie puść.",
|
||||
"ui.space_mouse_step_pull": "Pociągnij nakładkę do siebie, przytrzymaj, a następnie puść.",
|
||||
@@ -1820,6 +2027,16 @@
|
||||
"ui.space_mouse_step_tilt_right": "Przechyl nakładkę w prawo (prawa krawędź w dół), przytrzymaj, a następnie puść.",
|
||||
"ui.space_mouse_step_twist_clockwise": "Obróć nakładkę zgodnie z ruchem wskazówek zegara, przytrzymaj, a następnie puść.",
|
||||
"ui.space_mouse_step_twist_counterclockwise": "Obróć nakładkę przeciwnie do ruchu wskazówek zegara, przytrzymaj, a następnie puść.",
|
||||
"ui.space_mouse_view_axis": "Oś widoku",
|
||||
"ui.space_mouse_view_off": "Wyłączona",
|
||||
"ui.space_mouse_view_off_tip": "Profil sterownika myszy 3D wyłącza tę oś, więc jej ruch nie porusza widokiem. Wybranie tutaj ruchu innej osi zamienia je miejscami, a ten ruch przestaje poruszać widokiem.",
|
||||
"ui.space_mouse_view_orbit_sideways": "Obracanie w lewo / w prawo",
|
||||
"ui.space_mouse_view_orbit_up_down": "Obracanie w górę / w dół",
|
||||
"ui.space_mouse_view_pan_sideways": "Przesuwanie w lewo / w prawo",
|
||||
"ui.space_mouse_view_pan_up_down": "Przesuwanie w górę / w dół",
|
||||
"ui.space_mouse_view_roll": "Przechylenie",
|
||||
"ui.space_mouse_view_unmapped": "Oś {n}",
|
||||
"ui.space_mouse_view_zoom": "Powiększanie",
|
||||
"ui.spacing": "Odstęp",
|
||||
"ui.spacing_2": "Odstęp 2",
|
||||
"ui.sphere": "Sfera",
|
||||
|
||||
@@ -1060,7 +1060,7 @@
|
||||
"search.try": "Digite o nome de um comando, um recurso deste projeto ou um parâmetro. Para executar um comando com valores, digite seu id e um objeto JSON: {example}",
|
||||
"search.valid": "Válido",
|
||||
"settings.display_quality_note": "Níveis mais finos desenham faces e arestas curvas mais suaves e demoram mais para gerar a malha. Só a janela de visualização muda, nunca o projeto ou as exportações.",
|
||||
"settings.frame_rate_note": "Mostra quadros por segundo no canto inferior direito da vista. Enquanto estiver ativo, a vista é redesenhada continuamente.",
|
||||
"settings.frame_rate_note": "Mostra quadros por segundo no canto inferior direito da vista.",
|
||||
"settings.measure_axis_distances": "Mostrar distâncias X/Y/Z",
|
||||
"settings.measure_axis_distances_help": "Mostrar as componentes nos eixos do mundo junto com a distância total enquanto Medir está aberto.",
|
||||
"settings.msaa_applies_on_restart": "O antisserrilhamento vale na próxima vez que o SolidCraft iniciar",
|
||||
@@ -1183,6 +1183,7 @@
|
||||
"ui.agent_chat_files_left_out": "No máximo {max} arquivos acompanham uma mensagem; deixados de fora: {files}",
|
||||
"ui.agent_chat_files_loading": "Aguardando a leitura dos arquivos",
|
||||
"ui.agent_chat_files_max": "No máximo {max} arquivos por mensagem",
|
||||
"ui.agent_chat_flatpak_none_found": "Nenhum agente de programação encontrado. Por padrão, a sandbox do Flatpak não vê agentes instalados na sua pasta pessoal e não tem acesso à rede. Para permitir o Claude Code e o adaptador ACP dele instalados via nvm ou em ~/.local/bin, execute este comando em um terminal e reinicie o SolidCraft. Ele concede acesso aos programas e arquivos de login listados, além de acesso à rede:",
|
||||
"ui.agent_chat_import_failed": "{name}: falha na importação: {error}",
|
||||
"ui.agent_chat_intro": "Converse com um agente de programação que você já usa, ou com um endpoint de modelo que você escolher. Ele trabalha no projeto aberto pelas ferramentas do SolidCraft: as alterações aparecem conforme são feitas e se desfazem em um passo por mensagem. O que ele pode fazer sem perguntar é definido em Preferências > IA.",
|
||||
"ui.agent_chat_key_in_env": "chave definida",
|
||||
|
||||
@@ -1059,7 +1059,7 @@
|
||||
"search.try": "Tastați numele unei comenzi, o operație din acest proiect sau un parametru. Pentru a executa o comandă cu valori, tastați id-ul ei și un obiect JSON: {example}",
|
||||
"search.valid": "Valid",
|
||||
"settings.display_quality_note": "Nivelurile mai fine desenează fețele și muchiile curbe mai neted și durează mai mult la generarea plasei. Se schimbă doar fereastra de vizualizare, niciodată proiectul sau exporturile.",
|
||||
"settings.frame_rate_note": "Afișează cadrele pe secundă în colțul din dreapta jos al vizualizării. Cât timp este activat, vizualizarea se redesenează continuu.",
|
||||
"settings.frame_rate_note": "Afișează cadrele pe secundă în colțul din dreapta jos al vizualizării.",
|
||||
"settings.measure_axis_distances": "Afișează distanțele X/Y/Z",
|
||||
"settings.measure_axis_distances_help": "Afișează cotele pe axele globale alături de distanța totală cât timp Măsurare este deschis.",
|
||||
"settings.msaa_applies_on_restart": "Anti-aliasing se aplică la următoarea pornire a SolidCraft",
|
||||
@@ -1182,6 +1182,7 @@
|
||||
"ui.agent_chat_files_left_out": "Cel mult {max} fișiere merg cu un mesaj; omise: {files}",
|
||||
"ui.agent_chat_files_loading": "Se așteaptă citirea fișierelor",
|
||||
"ui.agent_chat_files_max": "Cel mult {max} fișiere pe un mesaj",
|
||||
"ui.agent_chat_flatpak_none_found": "Nu s-a găsit niciun agent de programare. Implicit, sandboxul Flatpak nu vede agenții instalați în dosarul personal și nu are acces la rețea. Pentru a permite Claude Code și adaptorul său ACP instalate prin nvm sau în ~/.local/bin, rulați această comandă într-un terminal, apoi reporniți SolidCraft. Ea acordă acces la programele și fișierele de autentificare enumerate, precum și acces la rețea:",
|
||||
"ui.agent_chat_import_failed": "{name}: importul a eșuat: {error}",
|
||||
"ui.agent_chat_intro": "Conversați cu un agent de programare pe care îl folosiți deja sau cu un endpoint de model ales de dumneavoastră. Lucrează la proiectul deschis prin instrumentele SolidCraft: modificările lui apar pe măsură ce le face și se anulează ca un singur pas per mesaj. Ce poate face fără să întrebe se stabilește în Preferințe > AI.",
|
||||
"ui.agent_chat_key_in_env": "cheie setată",
|
||||
|
||||
@@ -1059,7 +1059,7 @@
|
||||
"search.try": "Введите название команды, операцию этого дизайна или параметр. Чтобы выполнить команду со значениями, введите её id и объект JSON: {example}",
|
||||
"search.valid": "Допустимо",
|
||||
"settings.display_quality_note": "Более высокие уровни рисуют криволинейные грани и рёбра глаже, но сетка строится дольше. Меняется только видовой экран, но не дизайн и не экспорт.",
|
||||
"settings.frame_rate_note": "Показывает кадры в секунду в правом нижнем углу вида. Пока включено, вид перерисовывается непрерывно.",
|
||||
"settings.frame_rate_note": "Показывает кадры в секунду в правом нижнем углу вида.",
|
||||
"settings.measure_axis_distances": "Расстояния X/Y/Z",
|
||||
"settings.measure_axis_distances_help": "Показывать размеры вдоль мировых осей вместе с общим расстоянием, пока открыто окно измерения.",
|
||||
"settings.msaa_applies_on_restart": "Сглаживание вступит в силу при следующем запуске SolidCraft",
|
||||
@@ -1182,6 +1182,7 @@
|
||||
"ui.agent_chat_files_left_out": "К одному сообщению можно приложить не более {max} файлов; не добавлены: {files}",
|
||||
"ui.agent_chat_files_loading": "Ожидание чтения файлов",
|
||||
"ui.agent_chat_files_max": "Не более {max} файлов в одном сообщении",
|
||||
"ui.agent_chat_flatpak_none_found": "Кодирующий агент не найден. По умолчанию песочница Flatpak не видит агентов, установленных в домашней папке, и не имеет доступа к сети. Чтобы разрешить Claude Code и его адаптер ACP, установленные через nvm или в ~/.local/bin, выполните эту команду в терминале и перезапустите SolidCraft. Она даёт доступ к перечисленным программам и файлам входа, а также доступ к сети:",
|
||||
"ui.agent_chat_import_failed": "{name}: не удалось импортировать: {error}",
|
||||
"ui.agent_chat_intro": "Общайтесь с уже используемым кодирующим агентом или выбранной конечной точкой модели. Он работает с открытым дизайном через инструменты SolidCraft: изменения видны по мере выполнения и отменяются одним шагом на сообщение. Что ему разрешено без запроса, задаётся в Настройки > ИИ.",
|
||||
"ui.agent_chat_key_in_env": "ключ задан",
|
||||
|
||||
@@ -1059,7 +1059,7 @@
|
||||
"search.try": "Skriv ett kommandonamn, en funktion i denna konstruktion eller en parameter. För att köra ett kommando med värden, skriv dess id och ett JSON-objekt: {example}",
|
||||
"search.valid": "Giltig",
|
||||
"settings.display_quality_note": "Finare nivåer ritar krökta ytor och kanter jämnare och tar längre tid att mesha. Endast vyporten ändras, aldrig konstruktionen eller exporter.",
|
||||
"settings.frame_rate_note": "Visar bildrutor per sekund i vyns nedre högra hörn. Medan det är på ritas vyn om kontinuerligt.",
|
||||
"settings.frame_rate_note": "Visar bildrutor per sekund i vyns nedre högra hörn.",
|
||||
"settings.measure_axis_distances": "Visa X/Y/Z-avstånd",
|
||||
"settings.measure_axis_distances_help": "Visa världsaxelns komponentmått bredvid det totala avståndet medan Mät är öppet.",
|
||||
"settings.msaa_applies_on_restart": "Kantutjämning tillämpas nästa gång SolidCraft startar",
|
||||
@@ -1182,6 +1182,7 @@
|
||||
"ui.agent_chat_files_left_out": "Högst {max} filer följer med ett meddelande; utelämnade: {files}",
|
||||
"ui.agent_chat_files_loading": "Väntar på att filerna ska läsas",
|
||||
"ui.agent_chat_files_max": "Högst {max} filer i ett meddelande",
|
||||
"ui.agent_chat_flatpak_none_found": "Ingen kodningsagent hittades. Flatpak-sandlådan ser som standard inte agenter som är installerade i din hemmapp och har ingen nätverksåtkomst. För att tillåta Claude Code och dess ACP-adapter installerade via nvm eller i ~/.local/bin kör du det här kommandot i en terminal och startar sedan om SolidCraft. Det ger åtkomst till de angivna programmen och inloggningsfilerna samt nätverksåtkomst:",
|
||||
"ui.agent_chat_import_failed": "{name}: importen misslyckades: {error}",
|
||||
"ui.agent_chat_intro": "Chatta med en kodningsagent du redan använder, eller en modellslutpunkt du väljer. Den arbetar med den öppna konstruktionen via SolidCrafts verktyg: dess ändringar syns medan den gör dem och ångras som ett steg per meddelande. Vad den får göra utan att fråga ställs in under Inställningar > AI.",
|
||||
"ui.agent_chat_key_in_env": "nyckel angiven",
|
||||
|
||||
@@ -1059,7 +1059,7 @@
|
||||
"search.try": "Bir komut adı, bu tasarımdaki bir özellik veya bir parametre yazın. Bir komutu değerlerle çalıştırmak için kimliğini ve bir JSON nesnesi yazın: {example}",
|
||||
"search.valid": "Geçerli",
|
||||
"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.frame_rate_note": "Görünümün sağ alt köşesinde saniyedeki kare sayısını gösterir. Açıkken görünüm sürekli yeniden çizilir.",
|
||||
"settings.frame_rate_note": "Görünümün sağ alt köşesinde saniyedeki kare sayısını gösterir.",
|
||||
"settings.measure_axis_distances": "X/Y/Z mesafelerini göster",
|
||||
"settings.measure_axis_distances_help": "Ölç açıkken toplam mesafenin yanında dünya ekseni bileşen ölçülerini gösterir.",
|
||||
"settings.msaa_applies_on_restart": "Kenar yumuşatma, SolidCraft bir sonraki başlatıldığında uygulanır",
|
||||
@@ -1182,6 +1182,7 @@
|
||||
"ui.agent_chat_files_left_out": "Bir iletiyle en fazla {max} dosya gider; dışarıda kalanlar: {files}",
|
||||
"ui.agent_chat_files_loading": "Dosyaların okunması bekleniyor",
|
||||
"ui.agent_chat_files_max": "Bir iletide en fazla {max} dosya olabilir",
|
||||
"ui.agent_chat_flatpak_none_found": "Kodlama ajanı bulunamadı. Flatpak korumalı alanı varsayılan olarak ana klasörünüze yüklenen ajanları göremez ve ağ erişimi yoktur. nvm ile veya ~/.local/bin içine yüklenen Claude Code'a ve ACP bağdaştırıcısına izin vermek için bu komutu bir terminalde çalıştırın, ardından SolidCraft'ı yeniden başlatın. Komut, listelenen programlara ve oturum açma dosyalarına erişimin yanı sıra ağ erişimi de verir:",
|
||||
"ui.agent_chat_import_failed": "{name}: içe aktarma başarısız oldu: {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_key_in_env": "anahtar ayarlı",
|
||||
|
||||
@@ -1060,7 +1060,7 @@
|
||||
"search.try": "Введіть назву команди, елемент цього проєкту або параметр. Щоб виконати команду зі значеннями, введіть її id та об'єкт JSON: {example}",
|
||||
"search.valid": "Дійсне",
|
||||
"settings.display_quality_note": "Дрібніші рівні малюють криві грані й ребра плавнішими, але тріангуляція триває довше. Змінюється лише вікно перегляду, ніколи не проєкт чи експорт.",
|
||||
"settings.frame_rate_note": "Показує кадри за секунду в правому нижньому куті виду. Поки це ввімкнено, вид перемальовується безперервно.",
|
||||
"settings.frame_rate_note": "Показує кадри за секунду в правому нижньому куті виду.",
|
||||
"settings.measure_axis_distances": "Відстані X/Y/Z",
|
||||
"settings.measure_axis_distances_help": "Показувати розміри вздовж світових осей разом із загальною відстанню, поки відкрите вікно вимірювання.",
|
||||
"settings.msaa_applies_on_restart": "Згладжування застосується під час наступного запуску SolidCraft",
|
||||
@@ -1183,6 +1183,7 @@
|
||||
"ui.agent_chat_files_left_out": "З одним повідомленням надсилається щонайбільше {max} файлів; пропущено: {files}",
|
||||
"ui.agent_chat_files_loading": "Очікування читання файлів",
|
||||
"ui.agent_chat_files_max": "Щонайбільше {max} файлів на одне повідомлення",
|
||||
"ui.agent_chat_flatpak_none_found": "Агента для програмування не знайдено. Пісочниця Flatpak типово не бачить агентів, установлених у домашній теці, і не має доступу до мережі. Щоб дозволити Claude Code і його адаптер ACP, установлені через nvm або в ~/.local/bin, виконайте цю команду в терміналі, а потім перезапустіть SolidCraft. Вона надає доступ до перелічених програм і файлів входу, а також доступ до мережі:",
|
||||
"ui.agent_chat_import_failed": "{name}: не вдалося імпортувати: {error}",
|
||||
"ui.agent_chat_intro": "Спілкуйтеся з агентом для програмування, яким уже користуєтеся, або з обраною вами модельною кінцевою точкою. Він працює з відкритим проєктом через інструменти SolidCraft: його зміни з'являються в міру виконання й скасовуються одним кроком на повідомлення. Що він може робити без запиту, задано в Налаштування > ШІ.",
|
||||
"ui.agent_chat_key_in_env": "ключ задано",
|
||||
|
||||
@@ -1060,7 +1060,7 @@
|
||||
"search.try": "Nhập tên lệnh, một tính năng trong thiết kế này hoặc một tham số. Để chạy lệnh kèm giá trị, hãy nhập mã lệnh và một đối tượng JSON: {example}",
|
||||
"search.valid": "Hợp lệ",
|
||||
"settings.display_quality_note": "Mức độ chi tiết cao hơn giúp hiển thị các mặt cong và cạnh mượt mà hơn nhưng tốn nhiều thời gian tạo lưới hơn. Thiết lập này chỉ thay đổi vùng nhìn, không ảnh hưởng đến thiết kế hay dữ liệu xuất tệp.",
|
||||
"settings.frame_rate_note": "Hiển thị số khung hình trên giây (FPS) ở góc dưới bên phải khung nhìn. Khi bật, khung nhìn sẽ vẽ lại liên tục.",
|
||||
"settings.frame_rate_note": "Hiển thị số khung hình trên giây (FPS) ở góc dưới bên phải khung nhìn.",
|
||||
"settings.measure_axis_distances": "Hiển thị khoảng cách theo trục X/Y/Z",
|
||||
"settings.measure_axis_distances_help": "Hiển thị kích thước thành phần theo các trục tọa độ cùng với khoảng cách tổng thể khi mở công cụ Đo lường.",
|
||||
"settings.msaa_applies_on_restart": "Khử răng cưa sẽ áp dụng vào lần khởi động tiếp theo của SolidCraft",
|
||||
@@ -1183,6 +1183,7 @@
|
||||
"ui.agent_chat_files_left_out": "Tối đa {max} tệp đính kèm trong một tin nhắn; đã bỏ qua: {files}",
|
||||
"ui.agent_chat_files_loading": "Đang chờ đọc các tệp đính kèm",
|
||||
"ui.agent_chat_files_max": "Tối đa {max} tệp trong một tin nhắn",
|
||||
"ui.agent_chat_flatpak_none_found": "Không tìm thấy tác tử lập trình nào. Theo mặc định, hộp cát Flatpak không thấy các tác tử được cài trong thư mục nhà của bạn và không có quyền truy cập mạng. Để cho phép Claude Code và bộ điều hợp ACP của nó được cài qua nvm hoặc trong ~/.local/bin, hãy chạy lệnh này trong terminal, rồi khởi động lại SolidCraft. Lệnh cấp quyền truy cập các chương trình và tệp đăng nhập được liệt kê, cùng quyền truy cập mạng:",
|
||||
"ui.agent_chat_import_failed": "{name}: nhập tệp thất bại: {error}",
|
||||
"ui.agent_chat_intro": "Trò chuyện với tác tử lập trình (AI agent) bạn đang dùng hoặc một điểm cuối mô hình bạn chọn. AI thao tác trên thiết kế đang mở thông qua các công cụ của SolidCraft: các thay đổi hiển thị ngay khi thực hiện và có thể hoàn tác theo từng bước cho mỗi tin nhắn. Các thao tác AI được phép thực hiện mà không cần hỏi được đặt trong Tùy chọn cài đặt > AI.",
|
||||
"ui.agent_chat_key_in_env": "đã đặt khóa",
|
||||
|
||||
@@ -1059,7 +1059,7 @@
|
||||
"search.try": "輸入命令名稱、此設計中的特徵或參數。要帶值執行命令,請輸入其ID和JSON物件:{example}",
|
||||
"search.valid": "有效",
|
||||
"settings.display_quality_note": "等級越精細,曲面和邊顯示越平滑,但網格化耗時更長。只影響檢視區,不影響設計或匯出。",
|
||||
"settings.frame_rate_note": "在檢視右下角顯示每秒影格數。開啟時檢視會持續重繪。",
|
||||
"settings.frame_rate_note": "在檢視右下角顯示每秒影格數。",
|
||||
"settings.measure_axis_distances": "顯示 X/Y/Z 距離",
|
||||
"settings.measure_axis_distances_help": "開啟測量時,在總距離之外顯示沿世界座標軸方向的分量尺寸。",
|
||||
"settings.msaa_applies_on_restart": "抗鋸齒將在下次啟動 SolidCraft 時生效",
|
||||
@@ -1182,6 +1182,7 @@
|
||||
"ui.agent_chat_files_left_out": "一條訊息最多傳送 {max} 個檔案;未傳送:{files}",
|
||||
"ui.agent_chat_files_loading": "正在等待檔案讀取完成",
|
||||
"ui.agent_chat_files_max": "一條訊息最多附加 {max} 個檔案",
|
||||
"ui.agent_chat_flatpak_none_found": "未找到程式設計代理。預設情況下,Flatpak 沙箱無法存取主資料夾中安裝的代理,也無法存取網路。若要允許透過 nvm 或在 ~/.local/bin 中安裝的 Claude Code 及其 ACP 轉接器,請在終端機執行以下命令,然後重新啟動 SolidCraft。此命令會授予對所列程式和登入檔案的存取權限,以及網路存取權限:",
|
||||
"ui.agent_chat_import_failed": "{name}:匯入失敗:{error}",
|
||||
"ui.agent_chat_intro": "與您已在使用的程式設計代理或您選擇的模型端點聊天。它透過 SolidCraft 的工具處理開啟的設計:變更即時顯示,每條訊息的變更可一步復原。無需詢問即可執行的範圍在「偏好設定 > AI」中設定。",
|
||||
"ui.agent_chat_key_in_env": "已設定金鑰",
|
||||
|
||||
@@ -609,8 +609,10 @@
|
||||
"cmd.component_activate": "激活组件",
|
||||
"cmd.component_break_link": "断开链接",
|
||||
"cmd.component_capture_position": "捕获位置",
|
||||
"cmd.component_copies": "查找相同副本",
|
||||
"cmd.component_create": "新建组件",
|
||||
"cmd.component_delete": "删除组件",
|
||||
"cmd.component_extract": "提取到文件",
|
||||
"cmd.component_from_bodies": "由实体创建组件",
|
||||
"cmd.component_insert_design": "插入设计",
|
||||
"cmd.component_links": "列出链接",
|
||||
@@ -623,6 +625,7 @@
|
||||
"cmd.component_properties": "组件物理属性",
|
||||
"cmd.component_relink": "重新链接源文件",
|
||||
"cmd.component_rename": "重命名组件",
|
||||
"cmd.component_replace_with_link": "替换为链接",
|
||||
"cmd.component_revert_position": "恢复位置",
|
||||
"cmd.component_unlock": "解锁内容",
|
||||
"cmd.component_update_links": "更新链接",
|
||||
@@ -740,6 +743,7 @@
|
||||
"cmd.motion_plot": "运动研究图表",
|
||||
"cmd.motion_study": "运动研究",
|
||||
"cmd.motion_trace": "运动轨迹",
|
||||
"cmd.motion_trace_edit": "编辑运动轨迹",
|
||||
"cmd.motion_trace_keep": "保留运动轨迹",
|
||||
"cmd.occurrence_copy": "粘贴(实例)",
|
||||
"cmd.occurrence_ground": "固定",
|
||||
@@ -1353,7 +1357,7 @@
|
||||
"search.try": "输入命令名称、此设计中的特征或参数。要带值运行命令,请输入其ID和JSON对象:{example}",
|
||||
"search.valid": "有效",
|
||||
"settings.display_quality_note": "仅影响显示,不影响设计和导出。",
|
||||
"settings.frame_rate_note": "在视图右下角显示每秒帧数。开启时视图会持续重绘。",
|
||||
"settings.frame_rate_note": "在视图右下角显示每秒帧数。",
|
||||
"settings.measure_axis_distances": "显示 X/Y/Z 距离",
|
||||
"settings.measure_axis_distances_help": "测量对话框打开时,在总距离之外显示沿世界坐标轴方向的尺寸线和距离。",
|
||||
"settings.msaa_applies_on_restart": "抗锯齿将在下次启动 SolidCraft 时生效",
|
||||
@@ -1398,6 +1402,9 @@
|
||||
"thread.designation": "螺纹标记",
|
||||
"thread.iso_metric": "ISO 公制",
|
||||
"thread.select_size": "选择尺寸",
|
||||
"timeline.delete_after_marker_one": "删除历史标记之后的 1 个特征",
|
||||
"timeline.delete_after_marker_other": "删除历史标记之后的 {count} 个特征",
|
||||
"timeline.delete_many": "删除所选的 {count} 个特征",
|
||||
"timeline.group": "新建特征文件夹",
|
||||
"timeline.move_many": "移动时间线项目",
|
||||
"timeline.move_to_group": "将特征移至文件夹",
|
||||
@@ -1476,6 +1483,7 @@
|
||||
"ui.agent_chat_files_left_out": "一条消息最多发送 {max} 个文件;未发送:{files}",
|
||||
"ui.agent_chat_files_loading": "正在等待文件读取完成",
|
||||
"ui.agent_chat_files_max": "一条消息最多附加 {max} 个文件",
|
||||
"ui.agent_chat_flatpak_none_found": "未找到编程代理。默认情况下,Flatpak 沙箱无法访问主目录中安装的代理,也无法访问网络。要允许使用通过 nvm 或 ~/.local/bin 安装的 Claude Code 及其 ACP 适配器,请在终端运行以下命令,然后重新启动 SolidCraft。此命令授予对所列程序和登录文件的访问权限以及网络访问权限:",
|
||||
"ui.agent_chat_import_failed": "{name}:导入失败:{error}",
|
||||
"ui.agent_chat_intro": "与你已在使用的编程智能体或你选择的模型端点聊天。它通过 SolidCraft 的工具处理打开的设计:更改即时显示,每条消息的更改可一步撤销。无需询问即可执行的范围在“首选项 > AI”中设置。",
|
||||
"ui.agent_chat_key_in_env": "已设置密钥",
|
||||
@@ -1548,8 +1556,10 @@
|
||||
"ui.ai_add": "添加",
|
||||
"ui.ai_add_agent": "添加智能体…",
|
||||
"ui.ai_add_agent_title": "添加智能体",
|
||||
"ui.ai_add_anthropic": "Anthropic 兼容 API",
|
||||
"ui.ai_add_api": "OpenAI 兼容 API",
|
||||
"ui.ai_add_custom": "自定义命令",
|
||||
"ui.ai_add_endpoint": "API 端点",
|
||||
"ui.ai_add_installed": "已安装的智能体",
|
||||
"ui.ai_add_installed_note": "为已安装的智能体添加一个自己的条目,例如使用其他参数。已安装的智能体会自动列出。",
|
||||
"ui.ai_added": "已添加",
|
||||
@@ -1578,6 +1588,7 @@
|
||||
"ui.ai_key_needs_https": "密钥只会通过 HTTPS 发送,或发送到本机。",
|
||||
"ui.ai_key_note": "保存在系统钥匙串中,绝不保存在 SolidCraft 的设置里。本地服务器可留空。",
|
||||
"ui.ai_keychain_error": "系统钥匙串拒绝:{error}",
|
||||
"ui.ai_kind": "类型",
|
||||
"ui.ai_mode_all": "全部允许",
|
||||
"ui.ai_mode_all_note": "不再询问。崩溃报告仍不可访问,文件夹限制仍然有效。",
|
||||
"ui.ai_mode_all_warning": "智能体可以不经询问保存、覆盖、导出和替换你的设计。只在你信任的智能体和已保存的设计上使用。",
|
||||
@@ -1599,6 +1610,7 @@
|
||||
"ui.ai_panel": "面板",
|
||||
"ui.ai_permissions": "权限",
|
||||
"ui.ai_preset": "预设",
|
||||
"ui.ai_protocol": "协议",
|
||||
"ui.ai_remove": "移除",
|
||||
"ui.ai_request_limit": "每条消息 24 次请求后已停止;再发送一条消息即可继续",
|
||||
"ui.ai_reset": "重置",
|
||||
@@ -1609,6 +1621,8 @@
|
||||
"ui.ai_test": "测试",
|
||||
"ui.ai_test_acp_ok": "已响应:{agent}",
|
||||
"ui.ai_test_acp_tip": "短暂启动智能体并请求一个会话,然后结束它",
|
||||
"ui.ai_test_answered": "已连接:{model} 已响应",
|
||||
"ui.ai_test_anthropic_tip": "向端点发送一条简短消息",
|
||||
"ui.ai_test_api_tip": "向端点查询其模型列表",
|
||||
"ui.ai_test_no_model": "已连接:{count} 个模型,但没有 {model}",
|
||||
"ui.ai_test_ok": "已连接:{count} 个模型",
|
||||
@@ -1766,6 +1780,9 @@
|
||||
"ui.export_keymap_tip": "将按键、S 框收藏和工具栏导出为文件",
|
||||
"ui.extend": "延伸",
|
||||
"ui.extent_type": "延伸类型",
|
||||
"ui.extract_component": "提取到文件…",
|
||||
"ui.extract_design_changed": "选择文件时设计已更改。请重新开始提取到文件。",
|
||||
"ui.extract_done": "该组件现在是独立的设计,并已在此处链接。",
|
||||
"ui.extrude": "拉伸",
|
||||
"ui.factor": "系数",
|
||||
"ui.feature_history": "特征历史",
|
||||
@@ -1904,6 +1921,10 @@
|
||||
"ui.length_decimals": "长度小数位",
|
||||
"ui.light": "浅色",
|
||||
"ui.line": "直线",
|
||||
"ui.link_copies": "链接相同副本",
|
||||
"ui.link_copies_keep": "保留",
|
||||
"ui.link_copies_link": "链接",
|
||||
"ui.link_copies_text": "这些组件生成的实体与 {name} 相同。要将它们改为其链接的放置吗?",
|
||||
"ui.lock": "锁定",
|
||||
"ui.loft": "放样",
|
||||
"ui.look_at": "朝向",
|
||||
@@ -2027,6 +2048,7 @@
|
||||
"ui.render": "渲染",
|
||||
"ui.renderer": "渲染器",
|
||||
"ui.repeat": "重复",
|
||||
"ui.replace_with_link_done": "这些副本现在是链接设计的放置。",
|
||||
"ui.report_a_bug": "报告缺陷",
|
||||
"ui.reset": "重置",
|
||||
"ui.reset_all": "全部重置",
|
||||
|
||||
@@ -230,7 +230,7 @@ impl Tokens {
|
||||
],
|
||||
analysis: AnalysisColors::DEFAULT,
|
||||
icons: IconColors { highlight: Color32::WHITE, agent: Color32::from_rgb(168, 85, 247), marker_halo: Color32::from_black_alpha(150) },
|
||||
logo: [Color32::from_rgb(96, 158, 236), Color32::from_rgb(58, 136, 238), Color32::from_rgb(55, 108, 197), Color32::WHITE],
|
||||
logo: [Color32::from_rgb(96, 158, 236), Color32::from_rgb(58, 136, 238), Color32::from_rgb(55, 108, 197)],
|
||||
}
|
||||
}
|
||||
pub const fn dark() -> Tokens {
|
||||
|
||||
@@ -126,8 +126,7 @@
|
||||
"logo": [
|
||||
"#ffad38",
|
||||
"#eda134",
|
||||
"#855a1d",
|
||||
"#ffad38"
|
||||
"#855a1d"
|
||||
],
|
||||
"manipulator": "#ffad38",
|
||||
"mesh_accent": "#d6922f",
|
||||
|
||||
@@ -126,8 +126,7 @@
|
||||
"logo": [
|
||||
"#d8f4ff",
|
||||
"#8edcf5",
|
||||
"#4386ac",
|
||||
"#eef8ff"
|
||||
"#4386ac"
|
||||
],
|
||||
"manipulator": "#66ddff",
|
||||
"mesh_accent": "#78c6e8",
|
||||
|
||||
@@ -126,8 +126,7 @@
|
||||
"logo": [
|
||||
"#cba6f7",
|
||||
"#477dc8",
|
||||
"#586382",
|
||||
"#cdd6f4"
|
||||
"#586382"
|
||||
],
|
||||
"manipulator": "#cba6f7",
|
||||
"mesh_accent": "#cba6f7",
|
||||
|
||||
@@ -126,8 +126,7 @@
|
||||
"logo": [
|
||||
"#85b9ef",
|
||||
"#4096e9",
|
||||
"#2b71be",
|
||||
"#ffffff"
|
||||
"#2b71be"
|
||||
],
|
||||
"manipulator": "#007aff",
|
||||
"mesh_accent": "#927300",
|
||||
|
||||
@@ -126,8 +126,7 @@
|
||||
"logo": [
|
||||
"#4aa3d8",
|
||||
"#2878a9",
|
||||
"#68717d",
|
||||
"#e0e2e5"
|
||||
"#68717d"
|
||||
],
|
||||
"manipulator": "#4aa3d8",
|
||||
"mesh_accent": "#4aa3d8",
|
||||
|
||||
@@ -126,8 +126,7 @@
|
||||
"logo": [
|
||||
"#b3ffc4",
|
||||
"#79ed95",
|
||||
"#34854b",
|
||||
"#d8ffdf"
|
||||
"#34854b"
|
||||
],
|
||||
"manipulator": "#4dff79",
|
||||
"mesh_accent": "#59d67b",
|
||||
|
||||
@@ -126,8 +126,7 @@
|
||||
"logo": [
|
||||
"#00bfff",
|
||||
"#0070d0",
|
||||
"#555555",
|
||||
"#ffffff"
|
||||
"#555555"
|
||||
],
|
||||
"manipulator": "#00bfff",
|
||||
"mesh_accent": "#00bfff",
|
||||
|
||||
@@ -126,8 +126,7 @@
|
||||
"logo": [
|
||||
"#88c0d0",
|
||||
"#5e81ac",
|
||||
"#657991",
|
||||
"#eceff4"
|
||||
"#657991"
|
||||
],
|
||||
"manipulator": "#88c0d0",
|
||||
"mesh_accent": "#88c0d0",
|
||||
|
||||
@@ -126,8 +126,7 @@
|
||||
"logo": [
|
||||
"#bd93f9",
|
||||
"#8456b8",
|
||||
"#656581",
|
||||
"#f8f8f2"
|
||||
"#656581"
|
||||
],
|
||||
"manipulator": "#bd93f9",
|
||||
"mesh_accent": "#bd93f9",
|
||||
|
||||
@@ -126,8 +126,7 @@
|
||||
"logo": [
|
||||
"#61afef",
|
||||
"#56b6c2",
|
||||
"#c678dd",
|
||||
"#abb2bf"
|
||||
"#c678dd"
|
||||
],
|
||||
"manipulator": "#61afef",
|
||||
"mesh_accent": "#857100",
|
||||
|
||||
@@ -126,8 +126,7 @@
|
||||
"logo": [
|
||||
"#ccccff",
|
||||
"#9999cc",
|
||||
"#666699",
|
||||
"#ffffff"
|
||||
"#666699"
|
||||
],
|
||||
"manipulator": "#555599",
|
||||
"mesh_accent": "#666699",
|
||||
|
||||
@@ -126,8 +126,7 @@
|
||||
"logo": [
|
||||
"#268bd2",
|
||||
"#346e88",
|
||||
"#b5b6a0",
|
||||
"#586e75"
|
||||
"#b5b6a0"
|
||||
],
|
||||
"manipulator": "#268bd2",
|
||||
"mesh_accent": "#268bd2",
|
||||
|
||||
@@ -126,8 +126,7 @@
|
||||
"logo": [
|
||||
"#ffffff",
|
||||
"#c0c0c0",
|
||||
"#808080",
|
||||
"#ffffff"
|
||||
"#808080"
|
||||
],
|
||||
"manipulator": "#000080",
|
||||
"mesh_accent": "#000080",
|
||||
|
||||
@@ -126,8 +126,7 @@
|
||||
"logo": [
|
||||
"#7aa2f7",
|
||||
"#4775ce",
|
||||
"#4f6089",
|
||||
"#c0caf5"
|
||||
"#4f6089"
|
||||
],
|
||||
"manipulator": "#7aa2f7",
|
||||
"mesh_accent": "#7aa2f7",
|
||||
|
||||
@@ -2419,6 +2419,12 @@ pub struct Document {
|
||||
pub marker: Option<usize>,
|
||||
#[serde(default)]
|
||||
pub next_id: u64,
|
||||
/// Body names the design used and must not use again: a name a `body.rename` freed (#4957).
|
||||
/// The design's own counter starts over at every evaluation, so without these a design that
|
||||
/// is evaluated again after a rename hands the freed name to the next body, and a script
|
||||
/// that names a body finds another one.
|
||||
#[serde(default, skip_serializing_if = "std::collections::BTreeSet::is_empty")]
|
||||
pub reserved_body_names: std::collections::BTreeSet<String>,
|
||||
/// Components below the root, as a tree (by parent).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub components: Vec<Component>,
|
||||
@@ -2665,6 +2671,7 @@ impl Document {
|
||||
features: Vec::new(),
|
||||
marker: None,
|
||||
next_id: 1,
|
||||
reserved_body_names: Default::default(),
|
||||
components: Vec::new(),
|
||||
occurrences: Vec::new(),
|
||||
assembly: Default::default(),
|
||||
@@ -2692,7 +2699,14 @@ impl Document {
|
||||
/// Rename body `old` to `new` where the design keeps things by body name outside its
|
||||
/// features: materials, appearances, configuration columns, offsets, components and the
|
||||
/// browser's groups and order. (The features are the rename command's to change.)
|
||||
///
|
||||
/// A name the design numbered (`Body1`) is not used again after the rename: the design's
|
||||
/// counter starts over at every evaluation, so without this a design that is evaluated
|
||||
/// again hands the freed name to the next body (#4957).
|
||||
pub fn rename_body_keys(&mut self, old: &str, new: &str) {
|
||||
if old.strip_prefix("Body").and_then(|n| n.parse::<usize>().ok()).is_some() {
|
||||
self.reserved_body_names.insert(old.to_string());
|
||||
}
|
||||
if let Some(m) = self.materials.remove(old) {
|
||||
self.materials.insert(new.to_string(), m);
|
||||
}
|
||||
|
||||
@@ -17,6 +17,8 @@ use crate::expr::{self, Kind, Value};
|
||||
use crate::lineage::Traced;
|
||||
use crate::{AxisRef, DocError, Document, Feature, FeatureKind, HoleKind, Operation, PlaneRef, ProfileSel, Result};
|
||||
|
||||
type JointFaces = (Body, kernel::Result<Arc<[kernel::FaceInfo]>>);
|
||||
|
||||
/// A body in the evaluated model.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ModelBody {
|
||||
@@ -31,6 +33,9 @@ pub struct ModelBody {
|
||||
// Timeline snapshots are cloned before meshes are requested. Share the cell itself so
|
||||
// meshing any snapshot also warms every unchanged copy of this body.
|
||||
mesh: Arc<OnceLock<Arc<Mesh>>>,
|
||||
/// Joint face measurements use their own tolerance, independent of display quality.
|
||||
/// Shared by snapshots of this geometry; the body identity guards direct replacement.
|
||||
joint_faces: Arc<OnceLock<JointFaces>>,
|
||||
/// Lazy canonical reference triangles for a proper rigid occurrence placement.
|
||||
mesh_placement: Option<Arc<placed_mesh::PlacedMesh>>,
|
||||
/// The display plan (none when the body has no plan: a mesh body, or one the planner
|
||||
@@ -71,6 +76,7 @@ impl ModelBody {
|
||||
body,
|
||||
feature,
|
||||
mesh: Arc::new(OnceLock::new()),
|
||||
joint_faces: Arc::new(OnceLock::new()),
|
||||
mesh_placement: None,
|
||||
plan: Arc::new(Default::default()),
|
||||
plan_mesh: Arc::new(Default::default()),
|
||||
@@ -86,6 +92,19 @@ impl ModelBody {
|
||||
}
|
||||
}
|
||||
|
||||
/// Face measurements for joint origins, at their original chord tolerance. Pose changes
|
||||
/// and scratch copies share them; a geometry edit makes a new body and cache.
|
||||
pub(crate) fn joint_faces(&self) -> Result<Arc<[kernel::FaceInfo]>> {
|
||||
let measure = || {
|
||||
#[cfg(test)]
|
||||
cost_tests::count(|c| c.joint_faces += 1);
|
||||
let tol = (self.body.size() * 2e-3).max(1e-3);
|
||||
self.body.faces(tol).map(Arc::from)
|
||||
};
|
||||
let (body, faces) = self.joint_faces.get_or_init(|| (self.body.clone(), measure()));
|
||||
if body.same(&self.body) { faces.clone().map_err(Into::into) } else { measure().map_err(Into::into) }
|
||||
}
|
||||
|
||||
/// A box around the body without meshing it ([`Body::outline_bounds`]), worked out once.
|
||||
pub fn outline_bounds(&self) -> solidcraft_geom::Aabb3 {
|
||||
match self.outline.get_or_init(|| (self.body.clone(), self.body.outline_bounds())) {
|
||||
@@ -120,6 +139,9 @@ impl ModelBody {
|
||||
// finding their surface, picks naming their face, sketch planes), and a different
|
||||
// triangulation moved those and changed what designs build. A GPU viewport draws the
|
||||
// plan ([`ModelBody::display_plan`]).
|
||||
if let Some(mesh) = self.mesh.get() {
|
||||
return mesh.clone();
|
||||
}
|
||||
match self.mesh_placement.as_deref() {
|
||||
Some(placed) => self.mesh.get_or_init(|| placed.mesh()).clone(),
|
||||
None => placed_mesh::reference_mesh(&self.body, &self.mesh, self.display_tol()),
|
||||
@@ -694,6 +716,10 @@ pub struct ModelState {
|
||||
/// Shared between states: a feature that does not change a sketch keeps it as it was.
|
||||
pub sketches: Vec<Arc<SolvedSketch>>,
|
||||
pub body_counter: usize,
|
||||
/// Body names the design used and must not use again (a name a `body.rename` freed, #4957).
|
||||
/// The counter starts over at every evaluation, so without these a design that is evaluated
|
||||
/// again after a rename hands the freed name to the next body.
|
||||
pub reserved_body_names: std::collections::BTreeSet<String>,
|
||||
/// Sheet metal bodies (by body name) and their flat patterns.
|
||||
pub sheets: Vec<crate::sheet::SheetBody>,
|
||||
/// Construction planes, axes and points as evaluated (by feature).
|
||||
@@ -729,6 +755,9 @@ impl ModelState {
|
||||
self.sketch_keys.get(&s.feature).hash(&mut h);
|
||||
}
|
||||
self.body_counter.hash(&mut h);
|
||||
for n in &self.reserved_body_names {
|
||||
n.hash(&mut h);
|
||||
}
|
||||
for (feature, points) in &self.blend_edges {
|
||||
feature.hash(&mut h);
|
||||
for p in points {
|
||||
@@ -1739,7 +1768,8 @@ impl Model {
|
||||
let (vals, perr) = evaluation_values(doc);
|
||||
self.param_errors = perr;
|
||||
let mut prev_fp = 0u64;
|
||||
let mut state = self.empty.clone();
|
||||
// The names the design must not use again travel with the state (#4957).
|
||||
let mut state = std::sync::Arc::new(ModelState { reserved_body_names: doc.reserved_body_names.clone(), ..(*self.empty).clone() });
|
||||
let mut out: Vec<FeatureResult> = Vec::with_capacity(doc.features.len());
|
||||
let mut reuse = !self.no_cache;
|
||||
let mut recomputed = 0;
|
||||
@@ -1829,6 +1859,9 @@ impl Model {
|
||||
recomputed += 1;
|
||||
let t0 = now();
|
||||
let mut next = (*state).clone();
|
||||
// The names the design must not use again travel with the state (#4957): a state
|
||||
// taken from an earlier evaluation may have been made before a rename freed one.
|
||||
next.reserved_body_names = doc.reserved_body_names.clone();
|
||||
for b in &mut next.bodies {
|
||||
b.made = crate::lineage::Made::Before;
|
||||
}
|
||||
@@ -2006,6 +2039,8 @@ impl Model {
|
||||
b.name = new.to_string();
|
||||
b.names = b.names.renamed();
|
||||
}
|
||||
// The names the design must not use again travel with the state (#4957).
|
||||
st.reserved_body_names = doc.reserved_body_names.clone();
|
||||
Arc::new(st)
|
||||
})
|
||||
.clone();
|
||||
@@ -2121,8 +2156,10 @@ pub fn select_profiles(ss: &SolvedSketch, sel: &ProfileSel) -> Result<Vec<Region
|
||||
solidcraft_sketch::without_text_counters(&ss.sketch, chosen).into_iter().map(|p| p.region).collect()
|
||||
}
|
||||
ProfileSel::Indices { indices } => {
|
||||
// A design file may list a profile more than once; it is still one profile.
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
let mut v = Vec::new();
|
||||
for i in indices {
|
||||
for i in indices.iter().filter(|i| seen.insert(**i)) {
|
||||
v.push(ps.get(*i).ok_or_else(|| DocError::Unknown(format!("profile {i} of {}", ss.name)))?.region.clone());
|
||||
}
|
||||
v
|
||||
@@ -2188,7 +2225,8 @@ fn new_name(state: &mut ModelState, f: &Feature, k: usize) -> String {
|
||||
loop {
|
||||
state.body_counter += 1;
|
||||
let n = format!("Body{}", state.body_counter);
|
||||
if state.body(&n).is_none() {
|
||||
// A name a rename freed is not handed out again (#4957).
|
||||
if state.body(&n).is_none() && !state.reserved_body_names.contains(&n) {
|
||||
return n;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,15 +13,16 @@ use solidcraft_sketch::Sketch;
|
||||
|
||||
use crate::*;
|
||||
|
||||
/// Work counted on this thread: bodies moved into a component's frame, STEP texts digested.
|
||||
/// Work counted on this thread: bodies moved, STEP texts digested, joint faces measured.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub(super) struct Counts {
|
||||
pub moved: usize,
|
||||
pub digested: usize,
|
||||
pub joint_faces: usize,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static COUNTS: Cell<Counts> = const { Cell::new(Counts { moved: 0, digested: 0 }) };
|
||||
static COUNTS: Cell<Counts> = const { Cell::new(Counts { moved: 0, digested: 0, joint_faces: 0 }) };
|
||||
}
|
||||
|
||||
pub(super) fn count(f: impl FnOnce(&mut Counts)) {
|
||||
@@ -39,6 +40,103 @@ fn counted(f: impl FnOnce()) -> Counts {
|
||||
COUNTS.with(Cell::get)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn joint_face_measurements_are_shared_across_motion_samples_and_snap_kinds() {
|
||||
use crate::joints::{Joint, JointKind, JointOrigin, Snap, XRef};
|
||||
let mut doc = Document::new("joint face work");
|
||||
let part = doc.add_component(Some("Crank"), 0).unwrap();
|
||||
let occurrence = doc.occurrences.iter().find(|o| o.component == part).unwrap().id;
|
||||
let id = doc
|
||||
.add_feature(
|
||||
FeatureKind::Cylinder {
|
||||
base: point_expr(Vec3::ZERO),
|
||||
axis: Dir(Vec3::Z),
|
||||
radius: "2".into(),
|
||||
height: "10".into(),
|
||||
operation: Operation::NewBody,
|
||||
},
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
doc.feature_mut(id).unwrap().component = part;
|
||||
let mut model = Model::new();
|
||||
model.evaluate(&doc);
|
||||
let state = model.state();
|
||||
let pick = Vec3::new(0.0, 0.0, 10.0);
|
||||
let face = joints::face_name_at(&doc, &state, part, pick, false).unwrap();
|
||||
doc.assembly.joints.push(Joint {
|
||||
id: 100,
|
||||
name: "Pivot".into(),
|
||||
kind: JointKind::Revolute,
|
||||
a: JointOrigin { occurrence: 0, snap: Snap::Frame { origin: pick, z: Vec3::Z, x: Some(Vec3::X) } },
|
||||
b: JointOrigin { occurrence, snap: Snap::FaceCenter { pick, face: None, x: Some(XRef::Dir(Vec3::X)) } },
|
||||
values: vec![0.0],
|
||||
limits: Vec::new(),
|
||||
flip: true,
|
||||
offset: 0.0,
|
||||
angle: 0.0,
|
||||
suppressed: false,
|
||||
exprs: Default::default(),
|
||||
});
|
||||
// One body supplies both old nearest-face snaps and persistent named-face snaps.
|
||||
// A scratch model shares its measurements, even though each sample changes the pose.
|
||||
let snapshot = model.clone();
|
||||
let work = counted(|| {
|
||||
for name in [None, Some(face)] {
|
||||
doc.assembly.joints[0].b.snap = Snap::FaceCenter { pick, face: name, x: Some(XRef::Dir(Vec3::X)) };
|
||||
for k in 0..145 {
|
||||
let angle = (k as f64 * 2.5).to_radians();
|
||||
doc.assembly.joints[0].values[0] = angle;
|
||||
let solution = joints::solve(&doc, &snapshot.state());
|
||||
assert!(solution.errors.is_empty() && solution.conflicts.is_empty(), "{solution:?}");
|
||||
let point = apply_point(&solution.world[&occurrence], Vec3::new(5.0, 0.0, 10.0));
|
||||
assert!(point.dist(Vec3::new(5.0 * angle.cos(), 5.0 * angle.sin(), 10.0)) < 1e-9);
|
||||
doc.apply_joint_solution(&solution);
|
||||
}
|
||||
}
|
||||
});
|
||||
assert_eq!(work.joint_faces, 1, "pose-only samples must not remeasure unchanged faces: {work:?}");
|
||||
|
||||
// Editing geometry creates a fresh measurement without changing a retained snapshot.
|
||||
let FeatureKind::Cylinder { height, .. } = &mut doc.feature_mut(id).unwrap().kind else { panic!("cylinder") };
|
||||
*height = "12".into();
|
||||
model.evaluate(&doc);
|
||||
let origin = &doc.assembly.joints[0].b;
|
||||
let work = counted(|| {
|
||||
let changed = joints::resolve_origin(&doc, &model.state(), origin).unwrap();
|
||||
let retained = joints::resolve_origin(&doc, &snapshot.state(), origin).unwrap();
|
||||
assert!((changed[3][2] - 12.0).abs() < 1e-9);
|
||||
assert!((retained[3][2] - 10.0).abs() < 1e-9);
|
||||
});
|
||||
assert_eq!(work.joint_faces, 1, "only the edited body must be measured: {work:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn joint_face_measurements_never_follow_a_replaced_body_or_stale_offset() {
|
||||
use crate::joints::{JointOrigin, Snap};
|
||||
let mut doc = Document::new("replaced joint geometry");
|
||||
let mut state = ModelState::default();
|
||||
state.bodies.push(ModelBody::new("Pin".into(), kernel::cylinder(Vec3::ZERO, Vec3::Z, 2.0, 10.0).unwrap(), 0));
|
||||
let origin = JointOrigin { occurrence: 0, snap: Snap::FaceCenter { pick: Vec3::new(0.0, 0.0, 10.0), face: None, x: None } };
|
||||
let work = counted(|| {
|
||||
joints::resolve_origin(&doc, &state, &origin).unwrap();
|
||||
});
|
||||
assert_eq!(work.joint_faces, 1);
|
||||
let retained = state.clone();
|
||||
// Body is public; a clone's old measurement must never mask a direct replacement.
|
||||
state.bodies[0].body = kernel::cylinder(Vec3::ZERO, Vec3::Z, 2.0, 12.0).unwrap();
|
||||
let changed = joints::resolve_origin(&doc, &state, &origin).unwrap();
|
||||
assert!((changed[3][2] - 12.0).abs() < 1e-9);
|
||||
let work = counted(|| {
|
||||
let old = joints::resolve_origin(&doc, &retained, &origin).unwrap();
|
||||
assert!((old[3][2] - 10.0).abs() < 1e-9);
|
||||
doc.body_offsets.insert("Pin".into(), rigid(Vec3::new(0.0, 0.0, 1.0), Vec3::ZERO, Vec3::Z, 0.0));
|
||||
let moved = joints::resolve_origin(&doc, &retained, &origin).unwrap();
|
||||
assert!((moved[3][2] - 11.0).abs() < 1e-9);
|
||||
});
|
||||
assert_eq!(work.joint_faces, 0, "offsets are applied after the shared face measurements");
|
||||
}
|
||||
|
||||
/// `parts` imported files of two boxes each, every one in its own component placed away from
|
||||
/// the origin (as inserted parts are).
|
||||
fn placed_imports(parts: usize) -> Document {
|
||||
|
||||
@@ -1714,6 +1714,21 @@ fn offset_left(p: &[Vec2], d: f64) -> Vec<Vec2> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The smallest size a plastic feature's lengths may have, in millimetres. Thinner walls and
|
||||
/// shorter arms than this are below what the solid booleans can resolve.
|
||||
const PLASTIC_MIN_SIZE: f64 = 0.01;
|
||||
|
||||
/// `v`, the feature's `what`, when it is at least [`PLASTIC_MIN_SIZE`].
|
||||
fn plastic_size(feature: &str, what: &str, v: f64) -> Result<f64> {
|
||||
if v.is_finite() && v >= PLASTIC_MIN_SIZE {
|
||||
Ok(v)
|
||||
} else {
|
||||
// Tiny values in exponent form: 1e-320 written out is hundreds of zeros.
|
||||
let got = if v != 0.0 && v.abs() < 1e-3 { format!("{v:e}") } else { format!("{v}") };
|
||||
Err(DocError::Invalid(format!("the {feature}'s {what} must be at least {PLASTIC_MIN_SIZE} mm (got {got} mm)")))
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn plastic_eval(doc: &Document, vals: &BTreeMap<String, Value>, f: &Feature, st: &mut ModelState) -> Result<()> {
|
||||
let len = |e: &str| val(vals, e, Kind::Length);
|
||||
// The plastic rule of the body a feature goes on gives its defaults (draft, clearance).
|
||||
@@ -1738,10 +1753,8 @@ pub(super) fn plastic_eval(doc: &Document, vals: &BTreeMap<String, Value>, f: &F
|
||||
body,
|
||||
} => {
|
||||
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()));
|
||||
}
|
||||
let r0 = plastic_size("boss", "diameter", len(diameter)?)? / 2.0;
|
||||
let h = plastic_size("boss", "height", len(height)?)?;
|
||||
let dr = match draft {
|
||||
Some(e) => val(vals, e, Kind::Angle)?,
|
||||
None => rule(&target)?.map_or(0.0, |r| r.draft),
|
||||
@@ -1784,8 +1797,10 @@ pub(super) fn plastic_eval(doc: &Document, vals: &BTreeMap<String, Value>, f: &F
|
||||
None => 0.0,
|
||||
};
|
||||
let hr = h - off;
|
||||
if n > 0.0 && !(t > 0.0 && l > 0.0 && hr > 0.0) {
|
||||
return Err(DocError::Invalid("ribs need a positive thickness, length and height".into()));
|
||||
if n > 0.0 {
|
||||
plastic_size("boss", "rib_thickness", t)?;
|
||||
plastic_size("boss", "rib_length", l)?;
|
||||
plastic_size("boss", "rib height (height less rib_offset)", hr)?;
|
||||
}
|
||||
for k in 0..n as usize {
|
||||
let a = std::f64::consts::TAU * k as f64 / n;
|
||||
@@ -1816,9 +1831,9 @@ pub(super) fn plastic_eval(doc: &Document, vals: &BTreeMap<String, Value>, f: &F
|
||||
}
|
||||
}
|
||||
if let Some(hd) = hole_diameter {
|
||||
let rh = len(hd)? / 2.0;
|
||||
let rh = plastic_size("boss", "hole_diameter", len(hd)?)? / 2.0;
|
||||
let depth = match hole_depth {
|
||||
Some(e) => len(e)?,
|
||||
Some(e) => plastic_size("boss", "hole_depth", len(e)?)?,
|
||||
None => h,
|
||||
};
|
||||
if !(rh > 0.0 && rh < r_top && depth > 0.0) {
|
||||
@@ -1835,14 +1850,15 @@ pub(super) fn plastic_eval(doc: &Document, vals: &BTreeMap<String, Value>, f: &F
|
||||
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.0).ok_or_else(|| DocError::Invalid("pick the planar rim face".into()))?;
|
||||
let (w, h) = (len(width)?, len(height)?);
|
||||
let what = if *groove { "groove" } else { "lip" };
|
||||
let (w, h) = (plastic_size(what, "width", len(width)?)?, plastic_size(what, "height", len(height)?)?);
|
||||
let g = match gap {
|
||||
Some(e) => len(e)?,
|
||||
None if *groove => rule(&target)?.map_or(0.0, |r| r.clearance),
|
||||
None => 0.0,
|
||||
};
|
||||
if !(w > 0.0 && h > 0.0 && g >= 0.0) {
|
||||
return Err(DocError::Invalid("the lip width and height must be positive".into()));
|
||||
if !(g >= 0.0) {
|
||||
return Err(DocError::Invalid("the groove's gap must not be negative".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);
|
||||
@@ -1920,9 +1936,11 @@ pub(super) fn plastic_eval(doc: &Document, vals: &BTreeMap<String, Value>, f: &F
|
||||
}
|
||||
FeatureKind::SnapFit { position, direction, hook, length, thickness, width, catch_depth, catch_length, body } => {
|
||||
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 size = |what: &str, e: &str| plastic_size("snap fit", what, len(e)?);
|
||||
let (l, t, w) = (size("length", length)?, size("thickness", thickness)?, size("width", width)?);
|
||||
let (cd, cl) = (size("catch_depth", catch_depth)?, size("catch_length", catch_length)?);
|
||||
if !(cl < l) {
|
||||
return Err(DocError::Invalid("the snap fit's catch must be shorter than its arm".into()));
|
||||
}
|
||||
let (x, y, z) = local_frame(direction.0, Some(hook.0))?;
|
||||
let delta = (l * 0.05).clamp(1e-3, 0.5);
|
||||
@@ -1943,15 +1961,16 @@ pub(super) fn plastic_eval(doc: &Document, vals: &BTreeMap<String, Value>, f: &F
|
||||
}
|
||||
FeatureKind::Rest { position, direction, along, width, length, height, draft, thickness, body } => {
|
||||
let target = body_under(st, body, position.0)?;
|
||||
let (w, h) = (len(width)?, len(height)?);
|
||||
let l = length.as_deref().map(len).transpose()?;
|
||||
let size = |what: &str, e: &str| plastic_size("rest", what, len(e)?);
|
||||
let (w, h) = (size("width", width)?, size("height", height)?);
|
||||
let l = length.as_deref().map(|e| size("length", e)).transpose()?;
|
||||
let dr = match draft {
|
||||
Some(e) => val(vals, e, Kind::Angle)?,
|
||||
None => rule(&target)?.map_or(0.0, |r| r.draft),
|
||||
};
|
||||
let t = thickness.as_deref().map(len).transpose()?;
|
||||
if !(w > 0.0 && h > 0.0 && l.is_none_or(|l| l > 0.0) && t.is_none_or(|t| t > 0.0 && 2.0 * t < w.min(l.unwrap_or(w)))) {
|
||||
return Err(DocError::Invalid("the rest's sizes must be positive and its wall thinner than half its width".into()));
|
||||
let t = thickness.as_deref().map(|e| size("thickness", e)).transpose()?;
|
||||
if t.is_some_and(|t| 2.0 * t >= w.min(l.unwrap_or(w))) {
|
||||
return Err(DocError::Invalid("the rest's wall must be thinner than half its width".into()));
|
||||
}
|
||||
if !(dr.abs() < 1.0) {
|
||||
return Err(DocError::Invalid("the rest's draft must be under 57°".into()));
|
||||
|
||||
@@ -578,6 +578,7 @@ pub fn read(s: &str) -> Result<Document> {
|
||||
validate_body_transfers(&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}")))?;
|
||||
check_typed_numbers(&d)?;
|
||||
let mut legacy_by_feature = std::collections::BTreeMap::<usize, Vec<usize>>::new();
|
||||
for (feature, wire) in legacy_wires {
|
||||
legacy_by_feature.entry(feature).or_default().push(wire);
|
||||
@@ -1046,6 +1047,16 @@ fn check_design_numbers(v: &Value) -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The range check again, on the typed design: an integer such as `9223372036854775808` passes
|
||||
/// [`check_numbers`] in the file (ids and counters are integers and may be large), but once it
|
||||
/// lands in a coordinate or size it is a float, and floats are written as floats. Integer fields
|
||||
/// (ids, counters, indexes) stay integers and are never limited, so the field's type decides
|
||||
/// what is checked, not its name.
|
||||
fn check_typed_numbers(d: &Document) -> Result<()> {
|
||||
let typed = serde_json::to_value(d).map_err(|e| DocError::Invalid(format!("design file: {e}")))?;
|
||||
check_design_numbers(&typed)
|
||||
}
|
||||
|
||||
/// Every non-integer number in the file is finite and within ±`MAX_REAL` (a damaged or hostile
|
||||
/// file is refused instead of overflowing the geometry later).
|
||||
fn check_numbers(v: &Value, depth: usize) -> Result<()> {
|
||||
@@ -2095,6 +2106,38 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// An integer-valued coordinate is range-checked like a float one, while ids and counters
|
||||
/// may still be large integers (solidcraft#5021).
|
||||
#[test]
|
||||
fn integer_valued_coordinates_are_range_checked_and_large_ids_still_load() {
|
||||
let mut sketch = solidcraft_sketch::Sketch::new();
|
||||
sketch.add_point(solidcraft_geom::Vec2::new(40.0, 0.0), None).unwrap();
|
||||
let mut d = Document::new("range");
|
||||
d.add_feature(crate::FeatureKind::Sketch { plane: crate::PlaneRef::Origin { name: "XY".into() }, sketch }, None).unwrap();
|
||||
let last = |v: &Value| v["features"][0]["sketch"]["points"].as_array().map_or(0, |a| a.len() - 1);
|
||||
for huge in ["9223372036854775808", "4294967295", "2000000000", "-2000000000"] {
|
||||
let json = edited(&d, |v| {
|
||||
let i = last(v);
|
||||
v["features"][0]["sketch"]["points"][i]["pos"][1] = serde_json::from_str(huge).unwrap();
|
||||
});
|
||||
let error = read(&json).unwrap_err().to_string();
|
||||
assert!(error.contains("damaged design") && error.contains("out of range"), "{huge}: {error}");
|
||||
}
|
||||
// In range, an integer-valued coordinate is fine.
|
||||
let json = edited(&d, |v| {
|
||||
let i = last(v);
|
||||
v["features"][0]["sketch"]["points"][i]["pos"][1] = 1_000_000_000u64.into();
|
||||
});
|
||||
assert!(read(&json).is_ok());
|
||||
// Ids and counters are integers and may be past the coordinate limit.
|
||||
let json = edited(&d, |v| {
|
||||
v["features"][0]["id"] = 5_000_000_000u64.into();
|
||||
v["next_id"] = 5_000_000_001u64.into();
|
||||
});
|
||||
let back = read(&json).unwrap();
|
||||
assert_eq!(back.features[0].id, 5_000_000_000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exhausted_id_space_is_an_error_not_a_panic() {
|
||||
let d = two_components_one_occurrence();
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
//! Associative motion traces retain their occurrence path, point reference, joint bounds or
|
||||
//! study identity, sample count and assembly branch seeds, alongside the generated sketch.
|
||||
//! Older designs default to no associations: their saved curves remain fixed. Readers from
|
||||
//! the last release refuse the newer format number instead of silently dropping associations.
|
||||
@@ -0,0 +1,5 @@
|
||||
//! The design saves the body names a `body.rename` freed (`Body1` after the body it named was
|
||||
//! renamed), so a name the design used is not used again.
|
||||
//!
|
||||
//! A design saved before this has no such names: it keeps the names it has, and the next body
|
||||
//! it makes may take a name an earlier rename freed.
|
||||
@@ -572,6 +572,8 @@ pub struct Assembly {
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub studies: Vec<crate::motion::MotionStudy>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub traces: Vec<crate::motion::MotionTrace>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub exploded: Vec<crate::motion::ExplodedView>,
|
||||
}
|
||||
|
||||
@@ -597,6 +599,15 @@ impl Assembly {
|
||||
}
|
||||
}
|
||||
}
|
||||
for trace in &self.traces {
|
||||
if let crate::motion::TraceMotion::Joint { joint, from, to, .. } = &trace.motion {
|
||||
for (label, value) in [("from", from), ("to", to)] {
|
||||
if let serde_json::Value::String(e) = value {
|
||||
out.push((*joint, format!("trace {} {label}", trace.sketch), e.as_str()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -616,6 +627,15 @@ impl Assembly {
|
||||
}
|
||||
}
|
||||
}
|
||||
for trace in &mut self.traces {
|
||||
if let crate::motion::TraceMotion::Joint { from, to, .. } = &mut trace.motion {
|
||||
for value in [from, to] {
|
||||
if let serde_json::Value::String(e) = value {
|
||||
out.push(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -627,6 +647,7 @@ impl Assembly {
|
||||
&& !self.contact_enabled
|
||||
&& !self.contact_all
|
||||
&& self.studies.is_empty()
|
||||
&& self.traces.is_empty()
|
||||
&& self.exploded.is_empty()
|
||||
}
|
||||
}
|
||||
@@ -731,8 +752,7 @@ fn nearest_plane(doc: &Document, st: &ModelState, o: &JointOrigin, pick: Vec3) -
|
||||
let mut best: Option<(f64, Vec3, Vec3)> = None;
|
||||
for b in component_bodies(doc, st, comp) {
|
||||
let offset = doc.model_body_offset(b);
|
||||
let tol = (b.body.size() * 2e-3).max(1e-3);
|
||||
for f in b.body.faces(tol)? {
|
||||
for f in b.joint_faces()?.iter() {
|
||||
let Some(n) = f.plane_normal else { continue };
|
||||
let (c, n) = match offset {
|
||||
Some(m) => (apply_point(m, f.centroid), apply_vector(m, n)),
|
||||
@@ -836,6 +856,15 @@ pub fn clamp(j: &Joint, q: &mut [f64]) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Work requested after placing occurrences and checking their joint constraints.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Analysis {
|
||||
/// Placement, loop closure, conflicts and errors only; `Solution::dof` is empty.
|
||||
Placement,
|
||||
/// Also count each occurrence's remaining motion, including nearby singular poses.
|
||||
DegreesOfFreedom,
|
||||
}
|
||||
|
||||
/// The result of placing occurrences by their joints.
|
||||
#[derive(Clone, Debug, Default, Serialize)]
|
||||
pub struct Solution {
|
||||
@@ -852,7 +881,7 @@ pub struct Solution {
|
||||
/// Remaining degrees of freedom per occurrence (6 = free, 0 = fixed): how many independent
|
||||
/// values still move it, from the fixed occurrences, with loops kept closed and a value a
|
||||
/// motion link sets moving with the values its link chain starts from (a driven gear has its
|
||||
/// driving gear's one, a screw's travel its turn's).
|
||||
/// driving gear's one, a screw's travel its turn's). Empty for [`Analysis::Placement`].
|
||||
pub dof: BTreeMap<u64, usize>,
|
||||
/// Occurrences fixed in place (grounded, or the root's).
|
||||
pub fixed: Vec<u64>,
|
||||
@@ -943,22 +972,36 @@ fn flip_of(j: &Joint) -> Mat {
|
||||
if !j.flip { mat_mul(&m, &[[1.0, 0.0, 0.0, 0.0], [0.0, -1.0, 0.0, 0.0], [0.0, 0.0, -1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]) } else { m }
|
||||
}
|
||||
|
||||
/// Component-space frames stay fixed throughout one solve. Cache their inverses without
|
||||
/// regrouping products: reversed joints still invert the value-dependent link as before.
|
||||
struct JointFrames {
|
||||
a: Mat,
|
||||
b: Mat,
|
||||
inverse_a: Option<Mat>,
|
||||
inverse_b: Option<Mat>,
|
||||
}
|
||||
|
||||
impl JointFrames {
|
||||
fn new(a: Mat, b: Mat) -> Self {
|
||||
Self { a, b, inverse_a: mat_inverse(&a), inverse_b: mat_inverse(&b) }
|
||||
}
|
||||
|
||||
fn through(&self, joint: &Joint, values: &[f64], from_a: bool, t: &Mat) -> Option<Mat> {
|
||||
let link = mat_mul(&link_of(joint, values), self.inverse_b.as_ref()?);
|
||||
if from_a { Some(mat_mul(&mat_mul(t, &self.a), &link)) } else { Some(mat_mul(&mat_mul(t, &mat_inverse(&link)?), self.inverse_a.as_ref()?)) }
|
||||
}
|
||||
}
|
||||
|
||||
/// B's world transform from A's (or A's from B's, going the other way) for the joint's values.
|
||||
fn through(j: &Joint, (fa, fb): &(Mat, Mat), q: &[f64], from_a: bool, t: &Mat) -> Option<Mat> {
|
||||
let link = mat_mul(&link_of(j, q), &mat_inverse(fb)?);
|
||||
if from_a {
|
||||
Some(mat_mul(&mat_mul(t, fa), &link))
|
||||
} else {
|
||||
// T_A = T_B · link⁻¹ · F_a⁻¹
|
||||
Some(mat_mul(&mat_mul(t, &mat_inverse(&link)?), &mat_inverse(fa)?))
|
||||
}
|
||||
JointFrames::new(*fa, *fb).through(j, q, from_a, t)
|
||||
}
|
||||
|
||||
/// The spanning tree the solver places occurrences along, out from the fixed ones.
|
||||
struct Tree<'a> {
|
||||
joints: BTreeMap<u64, &'a Joint>,
|
||||
/// Joint frames in component coordinates (A's, B's).
|
||||
frames: BTreeMap<u64, (Mat, Mat)>,
|
||||
frames: BTreeMap<u64, JointFrames>,
|
||||
fixed: BTreeMap<u64, Mat>,
|
||||
/// Placed occurrence → (the occurrence it is placed from, the joint, from the joint's A side).
|
||||
parent: BTreeMap<u64, (u64, u64, bool)>,
|
||||
@@ -968,8 +1011,10 @@ struct Tree<'a> {
|
||||
|
||||
impl Tree<'_> {
|
||||
fn step(&self, joint: u64, from_a: bool, t: &Mat, vals: &Values) -> Option<Mat> {
|
||||
#[cfg(test)]
|
||||
tests::PLACEMENT_STEPS.with(|steps| steps.set(steps.get() + 1));
|
||||
let q = vals.get(&joint).map(Vec::as_slice).unwrap_or(&[]);
|
||||
through(self.joints.get(&joint)?, self.frames.get(&joint)?, q, from_a, t)
|
||||
self.frames.get(&joint)?.through(self.joints.get(&joint)?, q, from_a, t)
|
||||
}
|
||||
|
||||
/// Where every placed occurrence is for these values.
|
||||
@@ -1008,6 +1053,75 @@ impl Tree<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Storage shared by one residual callback's evaluations, scoped to its immutable tree.
|
||||
/// Keep map nodes and path capacity, but invalidate every placement before reading new values.
|
||||
struct PlacementWorkspace<'tree, 'doc> {
|
||||
tree: &'tree Tree<'doc>,
|
||||
placed: BTreeMap<u64, Option<Mat>>,
|
||||
path: Vec<(u64, u64, bool)>,
|
||||
}
|
||||
|
||||
impl<'tree, 'doc> PlacementWorkspace<'tree, 'doc> {
|
||||
fn new(tree: &'tree Tree<'doc>) -> Self {
|
||||
Self { tree, placed: BTreeMap::new(), path: Vec::new() }
|
||||
}
|
||||
|
||||
fn at<'values>(&'values mut self, values: &'values Values) -> Placements<'values, 'tree, 'doc> {
|
||||
for placed in self.placed.values_mut() {
|
||||
*placed = None;
|
||||
}
|
||||
Placements { workspace: self, values }
|
||||
}
|
||||
}
|
||||
|
||||
/// Only this guard can read placements. Its values stay immutable until it is dropped;
|
||||
/// obtaining the next guard clears validity while retaining the allocated storage.
|
||||
struct Placements<'values, 'tree, 'doc> {
|
||||
workspace: &'values mut PlacementWorkspace<'tree, 'doc>,
|
||||
values: &'values Values,
|
||||
}
|
||||
|
||||
impl Placements<'_, '_, '_> {
|
||||
fn world(&mut self, mut occurrence: u64) -> Option<Mat> {
|
||||
self.workspace.path.clear();
|
||||
let mut t = loop {
|
||||
if let Some(t) = self.workspace.placed.get(&occurrence).and_then(Option::as_ref).or_else(|| self.workspace.tree.fixed.get(&occurrence)) {
|
||||
break *t;
|
||||
}
|
||||
if self.workspace.path.len() >= self.workspace.tree.order.len() {
|
||||
return None;
|
||||
}
|
||||
let &(from, joint, from_a) = self.workspace.tree.parent.get(&occurrence)?;
|
||||
self.workspace.path.push((occurrence, joint, from_a));
|
||||
occurrence = from;
|
||||
};
|
||||
while let Some((occurrence, joint, from_a)) = self.workspace.path.pop() {
|
||||
t = self.workspace.tree.step(joint, from_a, &t, self.values)?;
|
||||
#[cfg(test)]
|
||||
if !self.workspace.placed.contains_key(&occurrence) {
|
||||
tests::PLACEMENT_INSERTS.with(|inserts| inserts.set(inserts.get() + 1));
|
||||
}
|
||||
self.workspace.placed.insert(occurrence, Some(t));
|
||||
}
|
||||
Some(t)
|
||||
}
|
||||
|
||||
fn closure_gaps(&mut self, closing: &[u64], scale: f64, out: &mut Vec<f64>) -> Option<()> {
|
||||
for id in closing {
|
||||
let (joint, frames) = (self.workspace.tree.joints.get(id)?, self.workspace.tree.frames.get(id)?);
|
||||
let tb = self.world(joint.b.occurrence)?;
|
||||
let ta = self.world(joint.a.occurrence)?;
|
||||
let want = self.workspace.tree.step(*id, true, &ta, self.values)?;
|
||||
for p in [Vec3::ZERO, Vec3::X * scale, Vec3::Y * scale] {
|
||||
let at = apply_point(&frames.b, p);
|
||||
let d = apply_point(&want, at) - apply_point(&tb, at);
|
||||
out.extend([d.x, d.y, d.z]);
|
||||
}
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Values the loop solver moves at most in one group of loops, and loop-closing joints it takes
|
||||
/// on at most: larger ones are only checked.
|
||||
const MAX_LOOP_VALUES: usize = 64;
|
||||
@@ -1212,8 +1326,8 @@ fn loop_scale(tree: &Tree, around: &BTreeSet<u64>, vals: &Values) -> f64 {
|
||||
let joints: Aabb3 = around
|
||||
.iter()
|
||||
.filter_map(|id| {
|
||||
let (j, (fa, _)) = (tree.joints.get(id)?, tree.frames.get(id)?);
|
||||
Some(apply_point(&mat_mul(&tree.world(j.a.occurrence, vals)?, fa), Vec3::ZERO))
|
||||
let (j, frames) = (tree.joints.get(id)?, tree.frames.get(id)?);
|
||||
Some(apply_point(&mat_mul(&tree.world(j.a.occurrence, vals)?, &frames.a), Vec3::ZERO))
|
||||
})
|
||||
.collect();
|
||||
if joints.is_empty() { 1.0 } else { joints.diagonal().clamp(1.0, 1e6) }
|
||||
@@ -1221,18 +1335,8 @@ fn loop_scale(tree: &Tree, around: &BTreeSet<u64>, vals: &Values) -> f64 {
|
||||
|
||||
/// How far each closing joint is from meeting: three points of B's joint frame, `scale` apart,
|
||||
/// where the joint wants them against where the tree puts them (appended to `out`).
|
||||
fn closure_gaps(tree: &Tree, closing: &[u64], vals: &Values, scale: f64, out: &mut Vec<f64>) -> Option<()> {
|
||||
for id in closing {
|
||||
let (j, (_, fb)) = (tree.joints.get(id)?, tree.frames.get(id)?);
|
||||
let tb = tree.world(j.b.occurrence, vals)?;
|
||||
let want = tree.step(*id, true, &tree.world(j.a.occurrence, vals)?, vals)?;
|
||||
for p in [Vec3::ZERO, Vec3::X * scale, Vec3::Y * scale] {
|
||||
let at = apply_point(fb, p);
|
||||
let d = apply_point(&want, at) - apply_point(&tb, at);
|
||||
out.extend([d.x, d.y, d.z]);
|
||||
}
|
||||
}
|
||||
Some(())
|
||||
fn closure_gaps(workspace: &mut PlacementWorkspace, closing: &[u64], vals: &Values, scale: f64, out: &mut Vec<f64>) -> Option<()> {
|
||||
workspace.at(vals).closure_gaps(closing, scale, out)
|
||||
}
|
||||
|
||||
/// How far a closing joint may be off before it is a conflict: its frames apart by more than
|
||||
@@ -1294,6 +1398,7 @@ fn nearby_pose(tree: &Tree, groups: &[Group], asm: &Assembly, linked: &BTreeSet<
|
||||
(v + d * if k % 2 == 0 { w } else { -w }).max(*lo).min(*hi)
|
||||
})
|
||||
.collect();
|
||||
let mut workspace = PlacementWorkspace::new(tree);
|
||||
let mut work = near.clone();
|
||||
let mut gaps = |x: &[f64]| -> Option<Vec<f64>> {
|
||||
spent += 1;
|
||||
@@ -1307,7 +1412,7 @@ fn nearby_pose(tree: &Tree, groups: &[Group], asm: &Assembly, linked: &BTreeSet<
|
||||
}
|
||||
apply_links(asm, &mut work);
|
||||
let mut out = Vec::with_capacity(closing.len() * 9);
|
||||
closure_gaps(tree, closing, &work, scale, &mut out)?;
|
||||
closure_gaps(&mut workspace, closing, &work, scale, &mut out)?;
|
||||
out.iter().all(|v| v.is_finite()).then_some(out)
|
||||
};
|
||||
if close_within(&mut gaps, &mut x, &bounds, (1e-10 * scale).min(1e-7), loose_gap(scale)).is_some()
|
||||
@@ -1422,6 +1527,7 @@ fn loop_dof(tree: &Tree, closing: &[u64], asm: &Assembly, vals: &Values, dof: &m
|
||||
let (n, gaps) = (values.len(), closers.len() * 9);
|
||||
// How many ways the occurrence moves at a pose, with the loops kept closed.
|
||||
let mut free_at = |at: &Values| -> Option<usize> {
|
||||
let mut workspace = PlacementWorkspace::new(tree);
|
||||
let mut work = at.clone();
|
||||
// The loops' gaps, then three points of the occurrence `scale` apart.
|
||||
let mut f = |x: &[f64]| -> Option<Vec<f64>> {
|
||||
@@ -1433,8 +1539,9 @@ fn loop_dof(tree: &Tree, closing: &[u64], asm: &Assembly, vals: &Values, dof: &m
|
||||
}
|
||||
apply_links(asm, &mut work);
|
||||
let mut out = Vec::with_capacity(closers.len() * 9 + 9);
|
||||
closure_gaps(tree, &closers, &work, scale, &mut out)?;
|
||||
let t = tree.world(*occ, &work)?;
|
||||
let mut placed = workspace.at(&work);
|
||||
placed.closure_gaps(&closers, scale, &mut out)?;
|
||||
let t = placed.world(*occ)?;
|
||||
for p in [Vec3::ZERO, Vec3::X * scale, Vec3::Y * scale] {
|
||||
let q = apply_point(&t, p);
|
||||
out.extend([q.x, q.y, q.z]);
|
||||
@@ -1530,6 +1637,7 @@ fn close_group(
|
||||
if !moves.is_empty() {
|
||||
first = first.min(1.0 / stride(&effective(&x0, 0.0), &effective(&x0, 1.0)));
|
||||
}
|
||||
let mut workspace = PlacementWorkspace::new(tree);
|
||||
let mut work = vals.clone();
|
||||
// How far each closing joint is from meeting with the held values `t` of the way along:
|
||||
// three points of B's joint frame, where the joint wants them against where the tree puts them.
|
||||
@@ -1540,7 +1648,7 @@ fn close_group(
|
||||
}
|
||||
place(&mut work, x, t);
|
||||
let mut out = Vec::with_capacity(closing.len() * 9);
|
||||
closure_gaps(tree, closing, &work, scale, &mut out)?;
|
||||
closure_gaps(&mut workspace, closing, &work, scale, &mut out)?;
|
||||
out.iter().all(|v| v.is_finite()).then_some(out)
|
||||
};
|
||||
// Already closed, with no held value moving. (A moving one is followed all the way: a
|
||||
@@ -1690,6 +1798,13 @@ pub fn solve(doc: &Document, st: &ModelState) -> Solution {
|
||||
/// of the other joints around the loop. The `held` values (the ones being driven) keep theirs,
|
||||
/// moving there from the values given (where the loops last closed) so the others follow them.
|
||||
pub fn solve_holding(doc: &Document, st: &ModelState, held: &Held) -> Solution {
|
||||
solve_holding_with_analysis(doc, st, held, Analysis::DegreesOfFreedom)
|
||||
}
|
||||
|
||||
/// Place occurrences and check constraints with the requested diagnostic work. Placement-only
|
||||
/// solves still close and check every loop, respect held values and limits, and report errors;
|
||||
/// they leave `Solution::dof` empty rather than returning the spanning tree's approximate count.
|
||||
pub fn solve_holding_with_analysis(doc: &Document, st: &ModelState, held: &Held, analysis: Analysis) -> Solution {
|
||||
let asm = &doc.assembly;
|
||||
let mut sol = Solution::default();
|
||||
let mut vals = joint_values(asm);
|
||||
@@ -1704,9 +1819,9 @@ pub fn solve_holding(doc: &Document, st: &ModelState, held: &Held) -> Solution {
|
||||
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 };
|
||||
let (Some(want), Some(frames)) = (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));
|
||||
let (dt, da) = mismatch(&mat_mul(&want, &frames.b), &mat_mul(tb, &frames.b));
|
||||
if dt > CONFLICT_MM || da > CONFLICT_RAD {
|
||||
sol.conflicts.push((
|
||||
j.id,
|
||||
@@ -1719,11 +1834,15 @@ pub fn solve_holding(doc: &Document, st: &ModelState, held: &Held) -> Solution {
|
||||
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);
|
||||
if analysis == Analysis::DegreesOfFreedom {
|
||||
if !closing.is_empty() {
|
||||
loop_dof(&tree, &closing, asm, &vals, &mut dof);
|
||||
}
|
||||
for o in &doc.occurrences {
|
||||
dof.entry(o.id).or_insert(6);
|
||||
}
|
||||
} else {
|
||||
dof.clear();
|
||||
}
|
||||
placed.remove(&0);
|
||||
sol.world = placed;
|
||||
@@ -1749,7 +1868,7 @@ fn build<'a>(doc: &'a Document, st: &ModelState, vals: &Values, sol: &mut Soluti
|
||||
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). An origin several joints
|
||||
// share (a panel face every part sits on) is found once.
|
||||
let mut frames: BTreeMap<u64, (Mat, Mat)> = BTreeMap::new();
|
||||
let mut frames: BTreeMap<u64, JointFrames> = BTreeMap::new();
|
||||
let mut found: BTreeMap<(u64, String), std::result::Result<Mat, String>> = BTreeMap::new();
|
||||
let mut resolve = |o: &JointOrigin| -> Result<Mat> {
|
||||
let Ok(comp) = component_of(doc, o.occurrence) else { return resolve_origin(doc, st, o) };
|
||||
@@ -1770,7 +1889,7 @@ fn build<'a>(doc: &'a Document, st: &ModelState, vals: &Values, sol: &mut Soluti
|
||||
}
|
||||
match (resolve(&j.a), resolve(&j.b)) {
|
||||
(Ok(fa), Ok(fb)) => {
|
||||
frames.insert(j.id, (fa, fb));
|
||||
frames.insert(j.id, JointFrames::new(fa, fb));
|
||||
}
|
||||
(Err(e), _) | (_, Err(e)) => sol.errors.push((j.id, j.name.clone(), e.to_string())),
|
||||
}
|
||||
@@ -1953,6 +2072,138 @@ pub fn frame_of(o: Vec3, z: Vec3, x: Option<Vec3>) -> Option<Mat> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
thread_local! {
|
||||
pub(super) static PLACEMENT_STEPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
pub(super) static PLACEMENT_INSERTS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
pub(super) fn placement_tree(asm: &Assembly) -> Tree<'_> {
|
||||
Tree {
|
||||
joints: asm.joints.iter().map(|j| (j.id, j)).collect(),
|
||||
frames: asm.joints.iter().map(|j| (j.id, JointFrames::new(mat_mul(&shift(3.0, 4.0, 5.0), &rot_y(0.3)), rot_x(-0.2)))).collect(),
|
||||
fixed: BTreeMap::from([(0, IDENTITY)]),
|
||||
parent: BTreeMap::from([(1, (0, 1, true)), (2, (1, 2, false)), (3, (2, 3, true)), (4, (1, 4, true)), (99, (0, 5, true))]),
|
||||
order: vec![1, 2, 3, 4, 99],
|
||||
}
|
||||
}
|
||||
|
||||
/// Shared ancestors are evaluated once, without visiting an unrelated assembly branch.
|
||||
/// The same arithmetic must be used after values change and on a reversed tree edge.
|
||||
#[test]
|
||||
fn residual_placements_reuse_ancestors_only_for_the_current_values() {
|
||||
let asm = chain(6, 0.2);
|
||||
let tree = placement_tree(&asm);
|
||||
let mut values = joint_values(&asm);
|
||||
let expected: BTreeMap<u64, Mat> = [1, 2, 3, 4].into_iter().map(|id| (id, tree.world(id, &values).unwrap())).collect();
|
||||
let mut workspace = PlacementWorkspace::new(&tree);
|
||||
PLACEMENT_STEPS.with(|steps| steps.set(0));
|
||||
{
|
||||
let mut placed = workspace.at(&values);
|
||||
for id in [3, 4, 3, 2, 4] {
|
||||
assert_eq!(placed.world(id), expected.get(&id).copied());
|
||||
}
|
||||
assert_eq!(placed.world(0), Some(IDENTITY));
|
||||
assert_eq!(placed.world(1234), None);
|
||||
}
|
||||
assert_eq!(PLACEMENT_STEPS.with(|steps| steps.get()), 4, "one step per needed occurrence; no unrelated branch");
|
||||
values.get_mut(&1).unwrap()[0] += 0.1;
|
||||
apply_links(&asm, &mut values);
|
||||
let changed = tree.world(3, &values).unwrap();
|
||||
assert_ne!(Some(&changed), expected.get(&3));
|
||||
let mut placed = workspace.at(&values);
|
||||
assert_eq!(placed.world(3), Some(changed), "a new residual evaluation cannot reuse the previous values' placements");
|
||||
}
|
||||
|
||||
/// Cached static inverses retain the original multiplication order for every joint kind,
|
||||
/// flip and traversal direction. A non-invertible frame remains a failed step.
|
||||
#[test]
|
||||
fn prepared_joint_frames_match_fresh_inverses() {
|
||||
fn reference(j: &Joint, fa: &Mat, fb: &Mat, q: &[f64], from_a: bool, t: &Mat) -> Option<Mat> {
|
||||
let link = mat_mul(&link_of(j, q), &mat_inverse(fb)?);
|
||||
if from_a { Some(mat_mul(&mat_mul(t, fa), &link)) } else { Some(mat_mul(&mat_mul(t, &mat_inverse(&link)?), &mat_inverse(fa)?)) }
|
||||
}
|
||||
let mut joint = chain(1, 0.0).joints.remove(0);
|
||||
let fa = mat_mul(&shift(3.0, -7.0, 11.0), &rot_y(0.3));
|
||||
let fb = mat_mul(&shift(-2.0, 5.0, 13.0), &rot_x(-0.2));
|
||||
let t = mat_mul(&shift(17.0, 19.0, -23.0), &rot_z(0.7));
|
||||
let singular = [[0.0; 4]; 4];
|
||||
for (a, b) in [(fa, fb), (singular, fb), (fa, singular)] {
|
||||
let frames = JointFrames::new(a, b);
|
||||
for kind in [
|
||||
JointKind::Rigid,
|
||||
JointKind::Revolute,
|
||||
JointKind::Slider,
|
||||
JointKind::Cylindrical,
|
||||
JointKind::PinSlot,
|
||||
JointKind::Planar,
|
||||
JointKind::Ball,
|
||||
JointKind::Parallel,
|
||||
JointKind::Perpendicular,
|
||||
JointKind::Angle,
|
||||
JointKind::PointOnPlane,
|
||||
JointKind::PointOnLine,
|
||||
JointKind::LineOnPlane,
|
||||
] {
|
||||
joint.kind = kind;
|
||||
joint.offset = 2.7;
|
||||
joint.angle = -0.41;
|
||||
for flip in [false, true] {
|
||||
joint.flip = flip;
|
||||
for angle in [0.0, 1e-6, -0.37, std::f64::consts::PI] {
|
||||
let q: Vec<f64> = (0..kind.dofs().len()).map(|i| angle * (i + 1) as f64).collect();
|
||||
for forward in [false, true] {
|
||||
assert_eq!(
|
||||
frames.through(&joint, &q, forward, &t),
|
||||
reference(&joint, &a, &b, &q, forward, &t),
|
||||
"{kind:?}, {flip}, {angle}, {forward}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The loop solver's residual entry point reuses shared ancestors for each perturbation;
|
||||
/// row order, duplicate rows, append semantics and missing-origin failure stay unchanged.
|
||||
#[test]
|
||||
fn closure_residuals_reuse_shared_ancestors_for_each_perturbation() {
|
||||
let mut asm = chain(6, 0.2);
|
||||
asm.joints[5].a.occurrence = 3;
|
||||
asm.joints[5].b.occurrence = 4;
|
||||
let tree = placement_tree(&asm);
|
||||
let mut workspace = PlacementWorkspace::new(&tree);
|
||||
let mut cold = true;
|
||||
for start in [0.2, 0.2 + 1e-6, 0.2 - 1e-6, 1.3] {
|
||||
let mut values = joint_values(&asm);
|
||||
values.get_mut(&1).unwrap()[0] = start;
|
||||
apply_links(&asm, &mut values);
|
||||
let mut expected = vec![42.0];
|
||||
for id in [6, 6] {
|
||||
let joint = tree.joints.get(&id).unwrap();
|
||||
let frames = tree.frames.get(&id).unwrap();
|
||||
let a = tree.world(joint.a.occurrence, &values).unwrap();
|
||||
let b = tree.world(joint.b.occurrence, &values).unwrap();
|
||||
let want = through(joint, &(frames.a, frames.b), values.get(&id).unwrap(), true, &a).unwrap();
|
||||
for point in [Vec3::ZERO, Vec3::X * 37.0, Vec3::Y * 37.0] {
|
||||
let at = apply_point(&frames.b, point);
|
||||
let d = apply_point(&want, at) - apply_point(&b, at);
|
||||
expected.extend([d.x, d.y, d.z]);
|
||||
}
|
||||
}
|
||||
PLACEMENT_STEPS.with(|steps| steps.set(0));
|
||||
PLACEMENT_INSERTS.with(|inserts| inserts.set(0));
|
||||
let mut actual = vec![42.0];
|
||||
assert_eq!(closure_gaps(&mut workspace, &[6, 6], &values, 37.0, &mut actual), Some(()));
|
||||
assert_eq!(actual, expected);
|
||||
assert_eq!(PLACEMENT_INSERTS.with(|inserts| inserts.get()), if cold { 4 } else { 0 }, "reuse cache storage between perturbations");
|
||||
cold = false;
|
||||
assert_eq!(PLACEMENT_STEPS.with(|steps| steps.get()), 6, "four tree placements and two closing-joint steps");
|
||||
assert_eq!(closure_gaps(&mut workspace, &[u64::MAX], &values, 37.0, &mut actual), None);
|
||||
assert_eq!(actual, expected, "an unresolved joint does not insert a zero residual");
|
||||
}
|
||||
}
|
||||
|
||||
fn close(a: &Mat, b: &Mat) -> bool {
|
||||
let (t, r) = mismatch(a, b);
|
||||
t < 1e-9 && r < 1e-9
|
||||
@@ -1960,7 +2211,7 @@ mod tests {
|
||||
|
||||
/// Revolute joints 1…n (joint 1 at `start`, the others at 0) linked 1 → 2 → … → n with
|
||||
/// ratio 2, the links stored from the end of the chain; joint 3 limited to ±50.
|
||||
fn chain(n: u64, start: f64) -> Assembly {
|
||||
pub(super) fn chain(n: u64, start: f64) -> Assembly {
|
||||
let origin = JointOrigin { occurrence: 0, snap: Snap::Point { point: Vec3::ZERO, z: None, x: None } };
|
||||
let joints = (1..=n)
|
||||
.map(|id| Joint {
|
||||
|
||||
@@ -64,8 +64,7 @@ impl NamedFace<'_> {
|
||||
|
||||
/// The face's centre and outward normal (the component's coordinates), when it is planar.
|
||||
pub fn plane(&self) -> Result<Option<(Vec3, Vec3)>> {
|
||||
let tol = (self.body.body.size() * 2e-3).max(1e-3);
|
||||
let faces = self.body.body.faces(tol)?;
|
||||
let faces = self.body.joint_faces()?;
|
||||
Ok(faces.get(self.face).and_then(|f| f.plane_normal.map(|n| (apply_point(&self.offset, f.centroid), apply_vector(&self.offset, n)))))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,8 +9,8 @@ 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, close_within, closure_gaps, jacobian,
|
||||
joint_values, largest, least_squares, limit_bounds, link_chains, loop_groups, loop_scale, loose_gap, unknowns,
|
||||
Assembly, Held, MAX_LOOP_VALUES, MAX_LOOP_WORK, MAX_LOOPS, Solution, Tree, Values, apply_links, build, close_within, jacobian, joint_values,
|
||||
largest, least_squares, limit_bounds, link_chains, loop_groups, loop_scale, loose_gap, unknowns,
|
||||
};
|
||||
use crate::{Document, ModelState, apply_point, apply_vector, mat_mul};
|
||||
|
||||
@@ -133,8 +133,8 @@ pub fn reach(doc: &Document, st: &ModelState, r: &Reach) -> Result<Reached, Stri
|
||||
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?))
|
||||
let (j, frames) = (tree.joints.get(id)?, tree.frames.get(id)?);
|
||||
Some(apply_point(&mat_mul(&tree.world(j.a.occurrence, &vals)?, &frames.a), Vec3::ZERO).dist(point?))
|
||||
})
|
||||
.fold(0.0, f64::max);
|
||||
let span = point.map_or(scale, |p| scale.max(p.dist(r.to)).max(lever));
|
||||
@@ -155,7 +155,8 @@ pub fn reach(doc: &Document, st: &ModelState, r: &Reach) -> Result<Reached, Stri
|
||||
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 workspace = super::PlacementWorkspace::new(tree);
|
||||
let mut f = |x: &[f64]| misses(&mut workspace, 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::<f64>().sqrt();
|
||||
let before = f(&x0).map_or(f64::INFINITY, |r| miss(&r));
|
||||
@@ -216,7 +217,8 @@ pub fn reach(doc: &Document, st: &ModelState, r: &Reach) -> Result<Reached, Stri
|
||||
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 alone_workspace = super::PlacementWorkspace::new(tree);
|
||||
let mut g = |x: &[f64]| misses(&mut alone_workspace, 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, loose_gap(scale))
|
||||
@@ -249,7 +251,7 @@ pub fn reach(doc: &Document, st: &ModelState, r: &Reach) -> Result<Reached, Stri
|
||||
/// 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,
|
||||
workspace: &mut super::PlacementWorkspace,
|
||||
asm: &Assembly,
|
||||
r: &Reach,
|
||||
scale: f64,
|
||||
@@ -269,9 +271,18 @@ fn misses(
|
||||
}
|
||||
}
|
||||
apply_links(asm, work);
|
||||
let mut out = target(tree, r, scale, work)?;
|
||||
let n = out.len();
|
||||
closure_gaps(tree, closers, work, scale, &mut out)?;
|
||||
let tree = workspace.tree;
|
||||
// An open chain has only one target placement to read. Loops share their ancestors with
|
||||
// that target, but a single placement needs no residual-local map.
|
||||
let mut out = if closers.is_empty() {
|
||||
target(tree, r, scale, work)?
|
||||
} else {
|
||||
let mut placed = workspace.at(work);
|
||||
let mut out = target_at(&placed.world(r.occurrence)?, r, scale);
|
||||
placed.closure_gaps(closers, scale, &mut out)?;
|
||||
out
|
||||
};
|
||||
let n = if r.axis.is_some() { 6 } else { 3 };
|
||||
for v in out.iter_mut().skip(n) {
|
||||
*v *= LOOP_WEIGHT;
|
||||
}
|
||||
@@ -280,14 +291,17 @@ fn misses(
|
||||
|
||||
/// 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<Vec<f64>> {
|
||||
let t = tree.world(r.occurrence, vals)?;
|
||||
let d = apply_point(&t, r.point) - r.to;
|
||||
Some(target_at(&tree.world(r.occurrence, vals)?, r, scale))
|
||||
}
|
||||
|
||||
fn target_at(t: &crate::Mat, r: &Reach, scale: f64) -> Vec<f64> {
|
||||
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;
|
||||
let w = (apply_vector(t, a) - z) * scale;
|
||||
out.extend([w.x, w.y, w.z]);
|
||||
}
|
||||
Some(out)
|
||||
out
|
||||
}
|
||||
|
||||
/// How many steps apart the values `vars` at `a` and at `b` put the `paced` values (each with its
|
||||
@@ -447,3 +461,55 @@ fn approach(
|
||||
}
|
||||
Some(r)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::super::tests::{PLACEMENT_INSERTS, PLACEMENT_STEPS, chain, placement_tree};
|
||||
use super::*;
|
||||
|
||||
/// Exercise the IK callback itself: removing sharing at this call site must fail even if
|
||||
/// the reusable placement helper still passes its own tests.
|
||||
#[test]
|
||||
fn ik_residual_reuses_target_and_loop_ancestors_at_the_call_site() {
|
||||
let mut asm = chain(6, 0.2);
|
||||
asm.joints[5].a.occurrence = 3;
|
||||
asm.joints[5].b.occurrence = 4;
|
||||
let tree = placement_tree(&asm);
|
||||
let base = joint_values(&asm);
|
||||
let mut workspace = super::super::PlacementWorkspace::new(&tree);
|
||||
let mut cold = true;
|
||||
for axis in [None, Some((Vec3::Y, Vec3::Z))] {
|
||||
let r = Reach { occurrence: 3, point: Vec3::new(1.0, 2.0, 3.0), to: Vec3::new(7.0, 11.0, 13.0), axis, joints: None };
|
||||
for x in [0.2, 0.2 + 1e-6, 0.2 - 1e-6, 1.3] {
|
||||
let mut reference = base.clone();
|
||||
reference.get_mut(&1).unwrap()[0] = x;
|
||||
apply_links(&asm, &mut reference);
|
||||
let mut expected = target(&tree, &r, 37.0, &reference).unwrap();
|
||||
let n = expected.len();
|
||||
super::super::closure_gaps(&mut super::super::PlacementWorkspace::new(&tree), &[6], &reference, 37.0, &mut expected).unwrap();
|
||||
for v in expected.iter_mut().skip(n) {
|
||||
*v *= LOOP_WEIGHT;
|
||||
}
|
||||
let mut work = base.clone();
|
||||
let spent = Cell::new(0);
|
||||
PLACEMENT_STEPS.with(|steps| steps.set(0));
|
||||
PLACEMENT_INSERTS.with(|inserts| inserts.set(0));
|
||||
let actual = misses(&mut workspace, &asm, &r, 37.0, &[(1, 0)], &[6], &[x], &mut work, &spent);
|
||||
assert_eq!(actual, Some(expected));
|
||||
assert_eq!(
|
||||
PLACEMENT_INSERTS.with(|inserts| inserts.get()),
|
||||
if cold { 4 } else { 0 },
|
||||
"IK must retain cache storage across evaluations"
|
||||
);
|
||||
cold = false;
|
||||
assert_eq!(spent.get(), 1, "reuse must not skip a finite-difference evaluation or bypass its work cap");
|
||||
assert_eq!(PLACEMENT_STEPS.with(|steps| steps.get()), 5, "four tree placements shared by the target and loop, plus the closing step");
|
||||
}
|
||||
let mut work = base.clone();
|
||||
let spent = Cell::new(MAX_LOOP_WORK);
|
||||
PLACEMENT_STEPS.with(|steps| steps.set(0));
|
||||
assert!(misses(&mut workspace, &asm, &r, 37.0, &[(1, 0)], &[6], &[0.2], &mut work, &spent).is_none());
|
||||
assert_eq!(PLACEMENT_STEPS.with(|steps| steps.get()), 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -181,6 +181,7 @@ impl Writer {
|
||||
let sketches = st.sketches.iter().map(|s| self.sketch(s)).collect::<Option<Vec<_>>>()?;
|
||||
let r = json!({
|
||||
"bodies": runs(&bodies), "sketches": runs(&sketches), "body_counter": st.body_counter,
|
||||
"reserved_body_names": st.reserved_body_names.iter().collect::<Vec<_>>(),
|
||||
"sheets": serde_json::to_value(&st.sheets).ok()?, "construct": serde_json::to_value(&st.construct).ok()?,
|
||||
"threads": serde_json::to_value(&st.threads).ok()?,
|
||||
"sketch_keys": st.sketch_keys.iter().map(|(f, k)| json!([f, hex(*k)])).collect::<Vec<_>>(),
|
||||
@@ -320,6 +321,11 @@ impl SavedModel {
|
||||
bodies: ids("bodies", model_bodies.len())?.into_iter().filter_map(|i| model_bodies.get(i).cloned()).collect(),
|
||||
sketches: ids("sketches", sketches.len())?.into_iter().filter_map(|i| sketches.get(i).cloned()).collect(),
|
||||
body_counter: index(s.get("body_counter"), usize::MAX)?,
|
||||
reserved_body_names: s
|
||||
.get("reserved_body_names")
|
||||
.and_then(Json::as_array)
|
||||
.map(|a| a.iter().filter_map(|n| n.as_str().map(str::to_string)).collect())
|
||||
.unwrap_or_default(),
|
||||
sheets: serde_json::from_value(field("sheets")?).map_err(invalid)?,
|
||||
construct: serde_json::from_value(field("construct")?).map_err(invalid)?,
|
||||
threads: serde_json::from_value(field("threads")?).map_err(invalid)?,
|
||||
|
||||
@@ -5,6 +5,29 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use solidcraft_geom::Vec3;
|
||||
|
||||
/// The motion retained by an associative trace. Joint bounds keep their expressions, in
|
||||
/// command units (degrees or millimetres); studies are referenced by their stable identity.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum TraceMotion {
|
||||
Joint { joint: u64, index: usize, from: serde_json::Value, to: serde_json::Value },
|
||||
Study { study: u64 },
|
||||
}
|
||||
|
||||
/// A generated root sketch curve and the inputs needed to regenerate it. The seed values
|
||||
/// select the original assembly branch: playing or dragging the mechanism does not redefine
|
||||
/// its trace. Older saved curves have no entry here and remain ordinary fixed sketch curves.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct MotionTrace {
|
||||
pub sketch: u64,
|
||||
pub wire: String,
|
||||
pub occurrence: Vec<u64>,
|
||||
pub point: crate::joints::JointOrigin,
|
||||
pub motion: TraceMotion,
|
||||
pub samples: Option<usize>,
|
||||
pub seeds: Vec<(u64, Vec<f64>)>,
|
||||
}
|
||||
|
||||
/// Occurrences whose bodies may touch but not pass through each other while joints move.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct ContactSet {
|
||||
|
||||
@@ -266,10 +266,7 @@ pub fn locate_face(st: &ModelState, name: &str, p: Vec3) -> Option<FaceHit> {
|
||||
// Every body's names are read below: work out the ones not known yet on all cores first
|
||||
// (each body's names are its own, whichever thread works them out).
|
||||
if legacy_name(name).is_none() {
|
||||
let bodies: Vec<&ModelBody> = st.bodies.iter().filter(|b| !b.body.is_mesh()).collect();
|
||||
solidcraft_kernel::for_each_on_threads(&bodies, 16, |b| {
|
||||
let _ = naming::names(b);
|
||||
});
|
||||
naming::warm_names(st.bodies.iter().filter(|b| !b.body.is_mesh()));
|
||||
}
|
||||
locate_in(st.bodies.iter().enumerate().filter(|(_, b)| !b.body.is_mesh()), name, p)
|
||||
}
|
||||
@@ -445,9 +442,7 @@ pub fn locate_one(st: &ModelState, body: Option<&str>, name: &str) -> Result<Fac
|
||||
st.bodies.iter().enumerate().filter(|(_, b)| !b.body.is_mesh() && body.is_none_or(|n| b.name == n)).collect();
|
||||
// As [`locate_face`]: the names of several bodies are worked out on all cores first.
|
||||
if bodies.len() > 1 && legacy_name(name).is_none() {
|
||||
solidcraft_kernel::for_each_on_threads(&bodies, 16, |(_, b)| {
|
||||
let _ = naming::names(b);
|
||||
});
|
||||
naming::warm_names(bodies.iter().map(|(_, b)| *b));
|
||||
}
|
||||
let hit = locate_in(bodies.into_iter(), name, Vec3::ZERO).ok_or_else(|| format!("no face is named `{name}` (`model.faces` lists the names)"))?;
|
||||
if hit.split {
|
||||
|
||||
@@ -229,6 +229,23 @@ pub fn face_name_exact(b: &ModelBody, index: usize) -> bool {
|
||||
names(b).verified(index)
|
||||
}
|
||||
|
||||
/// Prepare only names not yet known before a lookup reads several bodies. A ready cell is
|
||||
/// shared by snapshots and poses: dispatching threads just to read it costs more than a lookup.
|
||||
pub(crate) fn warm_names<'a>(bodies: impl Iterator<Item = &'a ModelBody>) {
|
||||
let bodies: Vec<_> = bodies.filter(|b| b.names.names.get().is_none()).collect();
|
||||
#[cfg(test)]
|
||||
tests::record_warm_jobs(bodies.len());
|
||||
match bodies.as_slice() {
|
||||
[] => {}
|
||||
[body] => {
|
||||
let _ = names(body);
|
||||
}
|
||||
_ => solidcraft_kernel::for_each_on_threads(&bodies, 16, |b| {
|
||||
let _ = names(b);
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// A body's names, with what finding them again needs: from the history of the feature that
|
||||
/// made it where it reports one, else from geometry (unverified).
|
||||
pub(crate) fn names(b: &ModelBody) -> Arc<Names> {
|
||||
@@ -872,6 +889,85 @@ pub fn face_on_body(body: &ModelBody, name: &str, p: Vec3) -> Option<(usize, Vec
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
thread_local! {
|
||||
static WARM_JOBS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
pub(super) fn record_warm_jobs(n: usize) {
|
||||
WARM_JOBS.with(|jobs| jobs.set(jobs.get() + n));
|
||||
}
|
||||
|
||||
fn take_warm_jobs() -> usize {
|
||||
WARM_JOBS.with(|jobs| jobs.replace(0))
|
||||
}
|
||||
|
||||
fn lookup_bodies() -> ModelState {
|
||||
let body = solidcraft_kernel::box_solid(Vec3::ZERO, Vec3::new(4., 2., 1.)).unwrap();
|
||||
let mut st = ModelState::default();
|
||||
st.bodies = (0..13).map(|i| ModelBody::new(format!("Part{i}"), body.clone(), i + 1)).collect();
|
||||
st
|
||||
}
|
||||
|
||||
fn same_hit(a: &FaceHit, b: &FaceHit) {
|
||||
assert_eq!((a.body, a.face, a.point), (b.body, b.face, b.point));
|
||||
assert_eq!((a.split, a.merged, a.verified, a.on_point, a.legacy), (b.split, b.merged, b.verified, b.on_point, b.legacy));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cached_face_lookups_schedule_no_name_warmup() {
|
||||
let st = lookup_bodies();
|
||||
for b in &st.bodies {
|
||||
let _ = face_names(b);
|
||||
}
|
||||
let name = face_names(&st.bodies[0])[0].clone();
|
||||
let picked = locate_face(&st, &name, Vec3::ZERO).unwrap();
|
||||
let unique = locate_one(&st, None, &name).unwrap();
|
||||
take_warm_jobs();
|
||||
// The two public lookup paths used by picked origins and named-face commands.
|
||||
for _ in 0..145 {
|
||||
same_hit(&locate_face(&st, &name, Vec3::ZERO).unwrap(), &picked);
|
||||
same_hit(&locate_one(&st, None, &name).unwrap(), &unique);
|
||||
}
|
||||
assert!(locate_face(&st, "absent:face:0", Vec3::ZERO).is_none());
|
||||
assert!(locate_one(&st, None, "absent:face:0").is_err());
|
||||
assert_eq!(take_warm_jobs(), 0, "cached names must not dispatch preparation work");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn face_lookup_warms_only_cold_and_invalidated_names() {
|
||||
// Exercise both entry points as the first reader of a partly named model.
|
||||
for picked in [false, true] {
|
||||
let mut st = lookup_bodies();
|
||||
let name = face_names(&st.bodies[0])[0].clone();
|
||||
let lookup = |st: &ModelState, name: &str| {
|
||||
if picked { locate_face(st, name, Vec3::ZERO).unwrap() } else { locate_one(st, None, name).unwrap() }
|
||||
};
|
||||
take_warm_jobs();
|
||||
let hit = lookup(&st, &name);
|
||||
assert_eq!(take_warm_jobs(), 12, "only the other bodies need names");
|
||||
let snapshot = st.clone();
|
||||
same_hit(&lookup(&snapshot, &name), &hit);
|
||||
assert_eq!(take_warm_jobs(), 0, "snapshots share ready names");
|
||||
|
||||
st.bodies[0].name = "Renamed".into();
|
||||
st.bodies[0].names = st.bodies[0].names.renamed();
|
||||
let renamed = lookup(&st, "Renamed:face:0");
|
||||
same_hit(&renamed, &hit);
|
||||
assert_eq!(take_warm_jobs(), 1, "a rename invalidates only its own names");
|
||||
assert!(locate_face(&st, &name, Vec3::ZERO).is_none());
|
||||
same_hit(&lookup(&snapshot, &name), &hit);
|
||||
assert_eq!(take_warm_jobs(), 0, "the retained snapshot stays ready");
|
||||
|
||||
let source = st.bodies[1].clone();
|
||||
st.bodies[1].names = NameCell::same(&source);
|
||||
same_hit(&lookup(&st, "Renamed:face:0"), &renamed);
|
||||
assert_eq!(take_warm_jobs(), 1, "a lazy moved copy is prepared once");
|
||||
assert!(Arc::ptr_eq(&names(&st.bodies[1]), &names(&source)));
|
||||
same_hit(&lookup(&st, "Renamed:face:0"), &renamed);
|
||||
assert_eq!(take_warm_jobs(), 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Pieces lying almost level along the sort axis must keep the order they arrived in, whatever
|
||||
/// the low bits of their centres do. The centre is the mean of a tessellated boundary, so those
|
||||
/// bits depend on where the loop's polyline starts and can differ between processes — which is
|
||||
|
||||
@@ -34,7 +34,7 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("view.delete", "Delete Named View", view_delete).icon("delete").params("view: name"),
|
||||
CommandSpec::new("view.list", "List Named Views", view_list).icon("list").noundo().doc_only(),
|
||||
CommandSpec::new("view.apply", "Restore Named View", view_apply).icon("camera").noundo().params(
|
||||
"view?: front|back|top|bottom|left|right|iso|home (frames the model) | a named view's name; or camera?: {target: [x,y,z], yaw, pitch, distance, fov?} (radians, mm) → camera. The viewport (and the MCP screenshot) moves there. View state: not saved, not an undo step",
|
||||
"view?: front|back|top|bottom|left|right|iso|home (frames the model) | a named view's name; or camera?: {target: [x,y,z], yaw, pitch, distance, fov?, roll?} (radians, mm; roll defaults to 0, must be finite and is clamped to ±π; up is refused: the up axis comes from the design settings) → camera. The viewport (and the MCP screenshot) moves there. View state: not saved, not an undo step",
|
||||
),
|
||||
CommandSpec::new("browser.order", "Order Browser Items", order).icon("reorder").params("folder, component?, order: [keys] (the folder's items in display order)"),
|
||||
CommandSpec::new("browser.visibility", "Show/Hide", visibility).icon("eye").noundo().params(
|
||||
@@ -453,8 +453,17 @@ fn view_apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
(Some(_), Some(_)) => return Err(bad(cmd, "give `view` or `camera`, not both")),
|
||||
(None, None) => return Err(bad(cmd, "`view` (a name) or `camera` is required")),
|
||||
(None, Some(c)) => {
|
||||
if c.get("up").is_some() {
|
||||
return Err(bad(cmd, "camera `up` is not supported: the up axis comes from the design settings"));
|
||||
}
|
||||
let roll = match c.get("roll") {
|
||||
Some(value) => {
|
||||
value.as_f64().filter(|r| r.is_finite()).ok_or_else(|| bad(cmd, "camera `roll` must be a finite number in radians"))?
|
||||
}
|
||||
None => 0.0,
|
||||
};
|
||||
let v: solidcraft_doc::NamedView = serde_json::from_value(c.clone()).map_err(|e| bad(cmd, format!("bad camera: {e}")))?;
|
||||
camera_of(&v)
|
||||
crate::render::Camera { roll: roll.clamp(-std::f64::consts::PI, std::f64::consts::PI), ..camera_of(&v) }
|
||||
}
|
||||
// Standard view names come first, as in the browser's Named Views folder.
|
||||
(Some(name), None) => match crate::render::StandardView::parse(name) {
|
||||
@@ -985,8 +994,14 @@ mod tests {
|
||||
run(&mut s, "view.apply", json!({"view": "top"}));
|
||||
let c = s.camera.expect("a camera for the top view");
|
||||
assert!((c.pitch - std::f64::consts::FRAC_PI_2).abs() < 1e-3 && (c.target.x - 20.0).abs() < 1e-6, "{c:?}");
|
||||
run(&mut s, "view.apply", json!({"camera": {"target": [0, 0, 0], "yaw": 1, "pitch": 0.2, "distance": 80, "fov": 0.5}}));
|
||||
assert_eq!(s.camera.map(|c| (c.yaw, c.distance, c.fov)), Some((1.0, 80.0, 0.5)));
|
||||
let r = run(&mut s, "view.apply", json!({"camera": {"target": [0, 0, 0], "yaw": 1, "pitch": 0.2, "distance": 80, "fov": 0.5, "roll": 1.0}}));
|
||||
assert_eq!(s.camera.map(|c| (c.yaw, c.distance, c.fov, c.roll)), Some((1.0, 80.0, 0.5, 1.0)));
|
||||
assert_eq!(r["camera"]["roll"], 1.0);
|
||||
for (roll, expected) in [(f64::MAX, std::f64::consts::PI), (-f64::MAX, -std::f64::consts::PI)] {
|
||||
let r = run(&mut s, "view.apply", json!({"camera": {"target": [0, 0, 0], "yaw": 0, "pitch": 0, "distance": 80, "roll": roll}}));
|
||||
assert_eq!(r["camera"]["roll"], expected);
|
||||
assert_eq!(s.camera.map(|c| c.roll), Some(expected));
|
||||
}
|
||||
assert_eq!(s.undo.len(), undo, "view state, not an undo step");
|
||||
for p in [
|
||||
json!({}),
|
||||
@@ -999,6 +1014,31 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn applying_a_camera_rejects_up() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "view.apply", json!({"view": "front"}));
|
||||
let before = serde_json::to_value(s.camera).unwrap();
|
||||
let err = s.execute("view.apply", &json!({"camera": {"target": [0, 0, 0], "yaw": 0, "pitch": 0, "distance": 80, "up": "y"}})).unwrap_err();
|
||||
let message = err.to_string();
|
||||
assert!(message.contains("up") && message.contains("design") && message.contains("settings"), "{message}");
|
||||
assert_eq!(serde_json::to_value(s.camera).unwrap(), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn applying_a_camera_rejects_invalid_roll() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "view.apply", json!({"view": "front"}));
|
||||
let before = serde_json::to_value(s.camera).unwrap();
|
||||
// Non-finite floating-point values serialize as null in JSON.
|
||||
for roll in [json!(f64::NAN), json!(f64::INFINITY), json!(f64::NEG_INFINITY), json!("NaN"), json!(true)] {
|
||||
let err =
|
||||
s.execute("view.apply", &json!({"camera": {"target": [0, 0, 0], "yaw": 0, "pitch": 0, "distance": 80, "roll": roll}})).unwrap_err();
|
||||
assert!(err.to_string().contains("roll"), "{err}");
|
||||
assert_eq!(serde_json::to_value(s.camera).unwrap(), before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn named_views_are_saved_renamed_and_deleted() {
|
||||
let mut s = Session::default();
|
||||
|
||||
@@ -109,6 +109,12 @@ pub(super) fn valid_position(m: &Mat) -> bool {
|
||||
|
||||
pub(super) fn new_component(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "component.create";
|
||||
if let Some(params) = p.as_object()
|
||||
&& let Some(key) = params.keys().find(|key| !matches!(key.as_str(), "name" | "parent" | "parent_path" | "activate"))
|
||||
{
|
||||
let hint = if params.contains_key("bodies") { "; use component.move_bodies or component.from_bodies to move bodies" } else { "" };
|
||||
return Err(bad(cmd, format!("unknown parameter `{key}`; accepted parameters: name, parent, parent_path, activate{hint}")));
|
||||
}
|
||||
let parent = if p.get("parent").is_some() { component(s, p, "parent", cmd)? } else { s.active_component };
|
||||
let parent_path = if let Some(value) = p.get("parent_path") {
|
||||
let path = value
|
||||
|
||||
@@ -99,7 +99,7 @@ fn unique(base: &str, used: &mut BTreeSet<String>) -> String {
|
||||
/// name is built as stored, or as `stored (n)` when a body of that name exists already: the solids
|
||||
/// of a STEP file that share a label are stored as `X`, `X`, `X` and built as `X`, `X (2)`, `X (3)`,
|
||||
/// and a second import of a file builds `Aa (2)` for the stored `Aa`.
|
||||
fn named_by(stored: &[String], built: &[String]) -> bool {
|
||||
pub(super) fn named_by(stored: &[String], built: &[String]) -> bool {
|
||||
!stored.is_empty()
|
||||
&& stored.len() == built.len()
|
||||
&& stored.iter().zip(built).all(|(stored, built)| {
|
||||
|
||||
@@ -15,6 +15,9 @@ use super::CommandSpec;
|
||||
use crate::params::{bad, str_, vec3};
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
#[path = "component_extract.rs"]
|
||||
mod extract;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "component_relink_tests.rs"]
|
||||
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
@@ -35,6 +38,19 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("component.break_link", "Break Link", break_link)
|
||||
.icon("break")
|
||||
.params("component: id or name of a linked component — keeps its bodies as they are and forgets the design file"),
|
||||
CommandSpec::new("component.extract", "Extract to File", extract::extract).icon("export").params(
|
||||
"component: id or name of a component that is not linked; path: the .solidcraft design to write → its history, subcomponents and their joints \
|
||||
move to that design, and the component becomes linked to it (as component.insert_design makes it); returns path, file, feature, bodies, \
|
||||
notices (what stays behind), warnings and copies (components that build the same bodies: see component.replace_with_link)",
|
||||
),
|
||||
CommandSpec::new("component.copies", "Find Identical Copies", extract::copies).icon("inspect").noundo().params(
|
||||
"component: id or name of a linked component → copies: [{component, name}], the components not linked whose own history builds the same bodies",
|
||||
),
|
||||
CommandSpec::new("component.replace_with_link", "Replace with Link", extract::replace_with_link).icon("chain").params(
|
||||
"component or components: [ids or names] of components that are not linked; with: a linked component, or path: a .solidcraft design \
|
||||
(its link here, else a new linked component) → each component's history goes and its placements become placements of the linked \
|
||||
component; refused when its bodies are not the same as the link's; returns component, name, replaced and warnings",
|
||||
),
|
||||
CommandSpec::new("component.links", "List Links", list_links)
|
||||
.icon("chain")
|
||||
.noundo()
|
||||
@@ -112,8 +128,12 @@ fn linked_bodies(file: &Path, own: Option<&str>) -> Result<(String, solidcraft_i
|
||||
}
|
||||
let bytes = solidcraft_io::vfs::read(&shown, solidcraft_io::MAX_DESIGN_BYTES).map_err(|e| EngineError::Other(format!("{shown}: {e}")))?;
|
||||
let doc = solidcraft_io::read_design(&bytes).map_err(|e| EngineError::Other(format!("{shown}: {e}")))?;
|
||||
let name = doc.name.clone();
|
||||
let part = Session::new(doc);
|
||||
session_bodies(&Session::new(doc), &shown)
|
||||
}
|
||||
|
||||
/// The solid bodies of `part`, the design saved as `shown`, as an Import feature.
|
||||
fn session_bodies(part: &Session, shown: &str) -> Result<(String, solidcraft_io::StepFeature)> {
|
||||
let name = part.doc.name.clone();
|
||||
if let Some(e) = part.model.results.iter().find_map(|r| r.error.clone()) {
|
||||
return Err(EngineError::Other(format!("{shown}: the design has a feature that fails ({e}); fix it before linking it")));
|
||||
}
|
||||
@@ -124,7 +144,7 @@ fn linked_bodies(file: &Path, own: Option<&str>) -> Result<(String, solidcraft_i
|
||||
}
|
||||
let step = solidcraft_io::export(&part.doc.painted(&world), &solids, solidcraft_io::Format::Step, &name)
|
||||
.map_err(|e| EngineError::Other(format!("{shown}: {e}")))?;
|
||||
let mut feature = solidcraft_io::step_import_feature(&step, &shown).map_err(|e| EngineError::Other(format!("{shown}: {e}")))?;
|
||||
let mut feature = solidcraft_io::step_import_feature(&step, shown).map_err(|e| EngineError::Other(format!("{shown}: {e}")))?;
|
||||
if world.bodies.len() > solids.len() {
|
||||
feature.warnings.push(format!("{} mesh bodies of {shown} are not linked", world.bodies.len() - solids.len()));
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
.key("E")
|
||||
.contract(&EXTRUDE_CONTRACT)
|
||||
.output(output_schema_for::<FeatureResult>)
|
||||
.params("distance: expr (or through_all: true); taper?: angle expr; sketch?: id|name (default: active or last sketch); profiles?: all | [index] | [{curves: [ids]}] (the profile whose outer loop is made of exactly these curves, or pieces of them; found again on every recompute, so it follows parameter changes; islands inside are its holes; an error when no profile or several match) | [{point:[x,y]}] (index and point picks are stored by their curves when that finds the same profile); face?: [x,y,z] (extrude a planar body face instead of a sketch profile); faces?: [[x,y,z],…] (coplanar faces of one body); face_body?: name (whose face, where faces of several bodies meet at the point); direction?: positive|negative|symmetric (distance is total thickness, split evenly around the start plane); convention?: total_distance|legacy_per_side (default total_distance; legacy preserves older symmetric extents); distance2?: expr (Two Sides: a second distance the other way from the first side, which may be through_all or to; with direction: negative the first side goes against the normal and distance2 along it); start_offset?: expr (along the sketch normal, also with direction: negative); to?: [x,y,z] (To Object: a face, vertex or point; to_offset?: expr past it); from?: [x,y,z] (From Object: start at that face or point); operation?: new|join|cut|intersect|auto (cut into a body, otherwise join existing solids; new in an empty component); targets?: [body] (Join from a face, or from a sketch on a body's face, defaults to that face's body; explicit targets or participants override); name?; body_name?; thin?: true (Thin: a wall along sketch curves instead of the profiles) with curves?: [curve ids] (open chains and closed loops, joined where they meet end to end; default: every drawn curve of the sketch), thickness: expr, side?: center|inside|outside|two_sides (a closed loop's inside is the area it encloses, an open chain's the side it bends toward, a straight line's the left of its first curve as drawn; default center), thickness2?: expr (two_sides: the thickness outside); corners are mitred, crossing walls are one"),
|
||||
.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); default: every drawn profile, except that a loop inside another is its hole and a loop inside that hole is material again; face?: [x,y,z] (extrude a planar body face instead of a sketch profile); faces?: [[x,y,z],…] (coplanar faces of one body); face_body?: name (whose face, where faces of several bodies meet at the point); direction?: positive|negative|symmetric (distance is total thickness, split evenly around the start plane); convention?: total_distance|legacy_per_side (default total_distance; legacy preserves older symmetric extents); distance2?: expr (Two Sides: a second distance the other way from the first side, which may be through_all or to; with direction: negative the first side goes against the normal and distance2 along it); start_offset?: expr (along the sketch normal, also with direction: negative); to?: [x,y,z] (To Object: a face, vertex or point; to_offset?: expr past it); from?: [x,y,z] (From Object: start at that face or point); operation?: new|join|cut|intersect|auto (cut into a body, otherwise join existing solids; new in an empty component); targets?: [body] (Join from a face, or from a sketch on a body's face, defaults to that face's body; explicit targets or participants override); name?; body_name?; thin?: true (Thin: a wall along sketch curves instead of the profiles) with curves?: [curve ids] (open chains and closed loops, joined where they meet end to end; default: every drawn curve of the sketch), thickness: expr, side?: center|inside|outside|two_sides (a closed loop's inside is the area it encloses, an open chain's the side it bends toward, a straight line's the left of its first curve as drawn; default center), thickness2?: expr (two_sides: the thickness outside); corners are mitred, crossing walls are one"),
|
||||
CommandSpec::new("solid.revolve", "Revolve", revolve)
|
||||
.at("SOLID", "CREATE")
|
||||
.icon("revolve")
|
||||
@@ -108,7 +108,7 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("construct.plane.at_angle", "Plane at Angle", plane_angle)
|
||||
.at("SOLID", "CONSTRUCT")
|
||||
.icon("plane_angle")
|
||||
.params("base: XY|XZ|YZ|plane name; axis: X|Y|Z|construction axis name (where it is now)|{origin, dir}; angle: expr; name?"),
|
||||
.params("base: XY|XZ|YZ|plane name, or a planar face {face: [x,y,z], body?, index?, path?}; axis: X|Y|Z|construction axis name (where it is now)|{origin, dir}; angle: expr; name?"),
|
||||
CommandSpec::new("solid.split_face", "Split Face", split_face)
|
||||
.at("SOLID", "MODIFY")
|
||||
.icon("split_face")
|
||||
@@ -208,7 +208,13 @@ fn auto_operation_in(s: &Session, p: &Value, world_faces: bool) -> Option<&'stat
|
||||
} else {
|
||||
extrude_base(s, p)?
|
||||
};
|
||||
let d = if grouped.is_some() && p.get("to").is_some() { (p.get("to").and_then(vec3)? - base).dot(n) } else { extrude_reach(s, p)? };
|
||||
let d = if grouped.is_some() && p.get("to").is_some() {
|
||||
(p.get("to").and_then(vec3)? - base).dot(n)
|
||||
} else if let Some(d) = extrude_reach(s, p) {
|
||||
d
|
||||
} else {
|
||||
through_all_reach(&st, p, base)?
|
||||
};
|
||||
if st.bodies.is_empty() || !d.is_finite() {
|
||||
return Some("new");
|
||||
}
|
||||
@@ -245,6 +251,20 @@ fn auto_operation_in(s: &Session, p: &Value, world_faces: bool) -> Option<&'stat
|
||||
}
|
||||
}
|
||||
|
||||
/// How far a Through All extrude with no distance reaches from `base`, signed by its
|
||||
/// direction: past every body of the model. Without it `auto` could not tell a cut through
|
||||
/// a part from an addition and made a separate body.
|
||||
fn through_all_reach(st: &solidcraft_doc::ModelState, p: &Value, base: Vec3) -> Option<f64> {
|
||||
let through_all = bool_(p, "through_all").unwrap_or(false) || str_(p, "extent").is_some_and(|e| e.eq_ignore_ascii_case("through_all"));
|
||||
if !through_all {
|
||||
return None;
|
||||
}
|
||||
let reach =
|
||||
st.bodies.iter().map(|b| b.mesh().bounds()).map(|bb| bb.center().dist(base) + bb.diagonal()).filter(|r| r.is_finite()).fold(1.0, f64::max);
|
||||
let dir = str_(p, "direction").map(str::to_ascii_lowercase);
|
||||
Some(if matches!(dir.as_deref(), Some("negative" | "reverse" | "flip")) { -reach } else { reach })
|
||||
}
|
||||
|
||||
pub(super) fn operation(p: &Value, cmd: &str) -> Result<Operation> {
|
||||
match str_(p, "operation") {
|
||||
None => Ok(Operation::NewBody),
|
||||
@@ -287,9 +307,30 @@ pub(super) fn stable_profiles(s: &Session, kind: &mut FeatureKind) -> Result<()>
|
||||
for (sketch, sel) in kind.profile_sels_mut() {
|
||||
let Some(ss) = st.sketch(sketch) else { continue };
|
||||
let indices = match sel {
|
||||
ProfileSel::Indices { .. } => solidcraft_doc::profile_selection_indices(ss, sel)?,
|
||||
ProfileSel::Indices { indices } => {
|
||||
let have = ss.profiles.len();
|
||||
if indices.len() > have {
|
||||
return Err(EngineError::Other(format!("{} profiles are listed, but {} has {have}", indices.len(), ss.name)));
|
||||
}
|
||||
if let Some(i) = indices.iter().find(|i| **i >= have) {
|
||||
return Err(EngineError::Other(format!("there is no profile {i} in {} (it has {have})", ss.name)));
|
||||
}
|
||||
solidcraft_doc::profile_selection_indices(ss, sel)?
|
||||
}
|
||||
ProfileSel::Points { points } => {
|
||||
if points.len() > ss.profiles.len() {
|
||||
return Err(EngineError::Other(format!(
|
||||
"{} profile points are given, but {} has {} profiles",
|
||||
points.len(),
|
||||
ss.name,
|
||||
ss.profiles.len()
|
||||
)));
|
||||
}
|
||||
let Some(indices) = points.iter().map(|point| profile_at_point(&ss.profiles, *point)).collect::<Option<Vec<_>>>() else { continue };
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
if let Some(i) = indices.iter().find(|i| !seen.insert(**i)) {
|
||||
return Err(EngineError::Other(format!("two profile points pick the same profile ({i}) in {}", ss.name)));
|
||||
}
|
||||
indices
|
||||
}
|
||||
ProfileSel::Curves { loops } => {
|
||||
@@ -390,7 +431,17 @@ pub(crate) fn profiles(p: &Value, cmd: &str) -> Result<ProfileSel> {
|
||||
Value::Array(a) if a.len() > 10_000 => Err(bad(cmd, "too many profiles")),
|
||||
Value::Array(a) => {
|
||||
if a.iter().all(Value::is_u64) {
|
||||
return Ok(ProfileSel::Indices { indices: a.iter().filter_map(Value::as_u64).map(|x| x as usize).collect() });
|
||||
// Each profile once: a repeat would build the same body again.
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
let mut indices = Vec::with_capacity(a.len());
|
||||
for i in a.iter().filter_map(Value::as_u64) {
|
||||
let i = usize::try_from(i).map_err(|_| bad(cmd, format!("there is no profile {i}")))?;
|
||||
if !seen.insert(i) {
|
||||
return Err(bad(cmd, format!("profile {i} is listed twice")));
|
||||
}
|
||||
indices.push(i);
|
||||
}
|
||||
return Ok(ProfileSel::Indices { indices });
|
||||
}
|
||||
if a.iter().all(|x| x.get("point").is_some()) {
|
||||
let pts =
|
||||
@@ -653,6 +704,7 @@ fn extrude(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
profiles: match face_profile {
|
||||
Some(f) => f,
|
||||
None if thin.is_some() => ProfileSel::All,
|
||||
None if p.get("profiles").is_none() => default_extrude_profiles(s, sketch),
|
||||
None => profiles(p, cmd)?,
|
||||
},
|
||||
extent,
|
||||
@@ -663,6 +715,47 @@ fn extrude(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
add_feature(s, p, kind)
|
||||
}
|
||||
|
||||
/// The profiles an extrude takes when `profiles` is omitted: even-odd nesting over what was drawn,
|
||||
/// so a loop inside an outline is its hole and a loop inside that hole is material again (#5172).
|
||||
/// Without nesting this is `All`, as before. When the pick cannot be stored so that it finds the
|
||||
/// same profiles again (the sketch is not solved, or two profiles share their curves), it stays
|
||||
/// `All` too.
|
||||
fn default_extrude_profiles(s: &Session, sketch: u64) -> ProfileSel {
|
||||
let st = s.model.state();
|
||||
let Some(ss) = st.sketch(sketch) else { return ProfileSel::All };
|
||||
let drawn = solidcraft_sketch::find_drawn_profiles(&ss.sketch);
|
||||
let ps = if drawn.is_empty() { ss.profiles.clone() } else { drawn };
|
||||
if ps.len() > 10_000 || ps.iter().all(|p| p.region.holes.is_empty()) {
|
||||
return ProfileSel::All;
|
||||
}
|
||||
// Each profile has the profiles directly inside it as holes, so the number of holes around a
|
||||
// point of a profile's material is its nesting depth.
|
||||
let material: Vec<_> = ps
|
||||
.iter()
|
||||
.filter(|p| {
|
||||
let probe = p.region.interior_point();
|
||||
ps.iter().filter(|other| other.region.holes.iter().any(|hole| hole.contains(probe))).count() % 2 == 0
|
||||
})
|
||||
.collect();
|
||||
let all = solidcraft_sketch::without_text_counters(&ss.sketch, ps.clone());
|
||||
if material.iter().map(|p| &p.outer_curves).eq(all.iter().map(|p| &p.outer_curves)) {
|
||||
return ProfileSel::All;
|
||||
}
|
||||
// Profiles of the solved sketch itself are stored by index, which `stable_profiles` turns
|
||||
// into curves; drawn profiles of a sketch with projected references are named by curves.
|
||||
let same = ps.len() == ss.profiles.len() && ps.iter().zip(&ss.profiles).all(|(a, b)| a.outer_curves == b.outer_curves);
|
||||
let sel = if same {
|
||||
let indices = ps.iter().enumerate().filter(|(_, p)| material.iter().any(|m| std::ptr::eq(*m, *p))).map(|(i, _)| i).collect();
|
||||
ProfileSel::Indices { indices }
|
||||
} else {
|
||||
ProfileSel::Curves { loops: material.iter().map(|p| p.outer_curves.clone()).collect() }
|
||||
};
|
||||
match solidcraft_doc::profile_selection_indices(ss, &sel) {
|
||||
Ok(found) if found.len() == material.len() && material.iter().all(|p| !p.outer_curves.is_empty()) => sel,
|
||||
_ => ProfileSel::All,
|
||||
}
|
||||
}
|
||||
|
||||
/// The body whose face `sketch` is attached to (on the face itself, not offset from it), when
|
||||
/// it is one the active component works on ([`active_scope`]).
|
||||
fn sketch_face_body(s: &Session, sketch: u64) -> Option<String> {
|
||||
@@ -1634,11 +1727,19 @@ fn plane_offset(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn plane_angle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "construct.plane.at_angle";
|
||||
let base = plane_param(s, p.get("base"), cmd)?;
|
||||
// The plane keeps the axis line as it is now.
|
||||
let (axis_origin, axis_dir, _) = axis_line(s, p, cmd)?;
|
||||
let angle = req_expr(cmd, p, "angle")?;
|
||||
check_expr(s, &angle, Kind::Angle, cmd, "angle")?;
|
||||
// A planar body face: attached exactly, as a sketch on that face is, so the plane follows it.
|
||||
if let Some(face) = p.get("base").filter(|b| b.get("face").is_some()) {
|
||||
let base = super::sketch::face::capture(s, face, cmd)?;
|
||||
super::sketch::face::capture_positions(s, &base)?;
|
||||
let kind = FeatureKind::ConstructionPlane { plane: solidcraft_doc::PlaneRef::AtAngle { base: Box::new(base), axis_origin, axis_dir, angle } };
|
||||
// The capture is already in the authoring frame.
|
||||
return add_feature_in(s, p, kind, false);
|
||||
}
|
||||
let base = plane_param(s, p.get("base"), cmd)?;
|
||||
add_feature(
|
||||
s,
|
||||
p,
|
||||
|
||||
@@ -59,6 +59,107 @@ fn grouped_face_auto_operation_keeps_implicit_and_explicit_participants() {
|
||||
assert_eq!(crate::auto_operation(&s, ¶ms), Some("join"));
|
||||
}
|
||||
|
||||
/// A part inserted into a new design (a STEP file) sits in its own component under the empty
|
||||
/// root. A sketch on its face must join it going out and cut it going in, never make a
|
||||
/// separate body beside it.
|
||||
#[test]
|
||||
fn sketch_on_a_part_in_another_component_joins_and_cuts_it() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "component.create", json!({"name":"Part"}));
|
||||
run(&mut s, "solid.box", json!({"length":10,"width":10,"height":10,"body_name":"Stock"}));
|
||||
run(&mut s, "component.activate", json!({"component":0}));
|
||||
run(&mut s, "sketch.create", json!({"plane":{"face":[5,5,10]},"project_edges":false}));
|
||||
run(&mut s, "sketch.rectangle.center", json!({"center":[5,5],"corner":[6,6]}));
|
||||
run(&mut s, "sketch.circle.center", json!({"center":[2,2],"radius":1}));
|
||||
run(&mut s, "sketch.finish", json!({}));
|
||||
let added = 3. * (4. + std::f64::consts::PI);
|
||||
for (params, expected, volume) in [
|
||||
(json!({"distance":3}), "join", 1000. + added),
|
||||
(json!({"distance":-3}), "cut", 1000. - added),
|
||||
(json!({"distance":3,"direction":"negative"}), "cut", 1000. - added),
|
||||
// Through All with no distance cut nothing and made a separate body.
|
||||
(json!({"through_all":true,"direction":"negative"}), "cut", 1000. - 10. / 3. * added),
|
||||
] {
|
||||
assert_eq!(crate::auto_operation(&s, ¶ms), Some(expected), "{params}");
|
||||
for operation in ["auto", expected] {
|
||||
let mut t = s.scratch();
|
||||
let mut p = params.clone();
|
||||
p["operation"] = json!(operation);
|
||||
p["profiles"] = json!("all");
|
||||
run(&mut t, "solid.extrude", p);
|
||||
let st = t.model.state();
|
||||
assert_eq!(st.bodies.len(), 1, "{params} {operation}: no separate body");
|
||||
let got = solidcraft_kernel::measure(&st.body("Stock").unwrap().body).unwrap().volume;
|
||||
assert!((got - volume).abs() < 1e-2, "{params} {operation}: volume {got}, expected {volume}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every way an extrude can go into a part inserted in its own component (negative distance,
|
||||
/// negative direction, Through All, symmetric, To Object, a start offset, past the far side,
|
||||
/// a face instead of a sketch) cuts that part, with `auto` and with an explicit Cut; going
|
||||
/// out joins it. None makes a separate body.
|
||||
#[test]
|
||||
fn every_inward_extrude_into_a_part_in_another_component_cuts_it() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "component.create", json!({"name":"Part"}));
|
||||
run(&mut s, "solid.box", json!({"length":10,"width":10,"height":10,"body_name":"Stock"}));
|
||||
run(&mut s, "component.activate", json!({"component":0}));
|
||||
let mut sketched = s.scratch();
|
||||
run(&mut sketched, "sketch.create", json!({"plane":{"face":[5,5,10]},"project_edges":false}));
|
||||
run(&mut sketched, "sketch.rectangle.center", json!({"center":[5,5],"corner":[6,6]}));
|
||||
run(&mut sketched, "sketch.circle.center", json!({"center":[2,2],"radius":1}));
|
||||
run(&mut sketched, "sketch.finish", json!({}));
|
||||
let area = 4. + std::f64::consts::PI;
|
||||
let sketch = |p: Value, depth: f64, op: &'static str| (p, depth, op, true);
|
||||
let face = |p: Value, depth: f64, op: &'static str| (p, depth, op, false);
|
||||
let cases = [
|
||||
sketch(json!({"distance":-3}), 3., "cut"),
|
||||
sketch(json!({"distance":3,"direction":"negative"}), 3., "cut"),
|
||||
sketch(json!({"distance":"-3 mm"}), 3., "cut"),
|
||||
sketch(json!({"distance":-25}), 10., "cut"),
|
||||
sketch(json!({"through_all":true,"direction":"negative"}), 10., "cut"),
|
||||
sketch(json!({"extent":"through_all","direction":"negative"}), 10., "cut"),
|
||||
sketch(json!({"distance":6,"direction":"symmetric"}), 3., "cut"),
|
||||
sketch(json!({"distance":-3,"start_offset":-2}), 3., "cut"),
|
||||
sketch(json!({"to":[5,5,0]}), 10., "cut"),
|
||||
sketch(json!({"to":[5,5,4]}), 6., "cut"),
|
||||
sketch(json!({"distance":3}), -3., "join"),
|
||||
sketch(json!({"distance":-3,"direction":"negative"}), -3., "join"),
|
||||
face(json!({"face":[5,5,10],"distance":-3}), 3., "cut"),
|
||||
face(json!({"face":[5,5,10],"distance":3,"direction":"negative"}), 3., "cut"),
|
||||
face(json!({"face":[5,5,10],"distance":3}), -3., "join"),
|
||||
];
|
||||
let mut wrong = Vec::new();
|
||||
for (params, depth, expected, from_sketch) in cases {
|
||||
// A face extrude moves the whole 10 x 10 face; a sketch only its two profiles.
|
||||
let volume = 1000. - depth * if from_sketch { area } else { 100. };
|
||||
for operation in ["auto", expected] {
|
||||
let mut t = if from_sketch { sketched.scratch() } else { s.scratch() };
|
||||
let mut p = params.clone();
|
||||
p["operation"] = json!(operation);
|
||||
if from_sketch {
|
||||
p["profiles"] = json!("all");
|
||||
}
|
||||
let auto = crate::auto_operation(&t, &p);
|
||||
if operation == "auto" && auto != Some(expected) {
|
||||
wrong.push(format!("{params}: auto reads {auto:?}, expected {expected}"));
|
||||
}
|
||||
if let Err(e) = t.execute("solid.extrude", &p) {
|
||||
wrong.push(format!("{params} {operation}: {e}"));
|
||||
continue;
|
||||
}
|
||||
let st = t.model.state();
|
||||
let names: Vec<_> = st.bodies.iter().map(|b| b.name.to_string()).collect();
|
||||
let got = st.body("Stock").and_then(|b| solidcraft_kernel::measure(&b.body).ok()).map(|m| m.volume);
|
||||
if names != ["Stock"] || got.is_none_or(|v| (v - volume).abs() > 1e-2) {
|
||||
wrong.push(format!("{params} {operation}: bodies {names:?}, Stock volume {got:?}, expected {volume:.3}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(wrong.is_empty(), "{} wrong:\n{}", wrong.len(), wrong.join("\n"));
|
||||
}
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
match s.execute(id, &p) {
|
||||
Ok(v) => v,
|
||||
@@ -1618,3 +1719,33 @@ fn loft_through_coplanar_sections_is_refused() {
|
||||
assert!(e.contains("same plane"), "{e}");
|
||||
assert!(s.model.state().bodies.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_and_excess_profile_picks_are_refused_quickly() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Bottom"}));
|
||||
run(&mut s, "sketch.circle.center", json!({"center": [2.5, 2.5], "radius": 2.5}));
|
||||
run(&mut s, "sketch.finish", json!({}));
|
||||
run(&mut s, "sketch.create", json!({"plane": "XY", "offset": 30, "name": "Top"}));
|
||||
run(&mut s, "sketch.circle.center", json!({"center": [2.5, 2.5], "radius": 2}));
|
||||
run(&mut s, "sketch.finish", json!({}));
|
||||
let started = std::time::Instant::now();
|
||||
let many = vec![0; 10_000];
|
||||
let e = s.execute("solid.extrude", &json!({"sketch": "Bottom", "distance": 5, "profiles": many})).unwrap_err().to_string();
|
||||
assert!(e.contains("profile 0 is listed twice"), "{e}");
|
||||
let loft = json!({"sections": [{"sketch": "Bottom", "profiles": many}, {"sketch": "Top"}]});
|
||||
let e = s.execute("solid.loft", &loft).unwrap_err().to_string();
|
||||
assert!(e.contains("profile 0 is listed twice"), "{e}");
|
||||
// More profiles than the sketch has, or one it doesn't have.
|
||||
let e = s.execute("solid.extrude", &json!({"sketch": "Bottom", "distance": 5, "profiles": [0, 1]})).unwrap_err().to_string();
|
||||
assert!(e.contains("2 profiles are listed, but Bottom has 1"), "{e}");
|
||||
let e = s.execute("solid.extrude", &json!({"sketch": "Bottom", "distance": 5, "profiles": [3]})).unwrap_err().to_string();
|
||||
assert!(e.contains("there is no profile 3 in Bottom"), "{e}");
|
||||
let points = json!([{"point": [1, 1]}, {"point": [2, 2]}]);
|
||||
let e = s.execute("solid.extrude", &json!({"sketch": "Bottom", "distance": 5, "profiles": points})).unwrap_err().to_string();
|
||||
assert!(e.contains("2 profile points are given, but Bottom has 1"), "{e}");
|
||||
assert!(started.elapsed().as_secs_f64() < 5.0, "refusing took {:?}", started.elapsed());
|
||||
assert!(s.world_state().bodies.is_empty(), "nothing was built");
|
||||
// One pick of the profile still builds.
|
||||
run(&mut s, "solid.loft", json!({"sections": [{"sketch": "Bottom", "profiles": [0]}, {"sketch": "Top"}]}));
|
||||
}
|
||||
@@ -103,6 +103,19 @@ fn read_step(path: &str, names: solidcraft_io::StepNames) -> Result<solidcraft_i
|
||||
solidcraft_io::step_import_feature_named(&bytes, path, names).map_err(|e| EngineError::Other(format!("{path}: {e}")))
|
||||
}
|
||||
|
||||
/// Which way is up in a STEP or IGES file, from the program its header names: `("y", name)` for
|
||||
/// an exporter whose files have Y up, `("z", name)` for SolidCraft's own (its STEP and IGES exports both name it), else `None`. Only
|
||||
/// SolidWorks is listed as Y up: its STEP and IGES writers are well known to keep that program's
|
||||
/// Y-up front view, and its name is in FILE_NAME (originating system, preprocessor version) and
|
||||
/// often FILE_DESCRIPTION. Programs we aren't sure of stay unknown, so the file is only offered.
|
||||
fn exporter_up(import: &solidcraft_kernel::StepImport) -> Option<(&'static str, &'static str)> {
|
||||
if import.system.trim().starts_with("SolidCraft") {
|
||||
return Some(("z", "SolidCraft"));
|
||||
}
|
||||
let named = [&import.system, &import.preprocessor, &import.description].iter().any(|h| h.to_ascii_lowercase().contains("solidworks"));
|
||||
named.then_some(("y", "SolidWorks"))
|
||||
}
|
||||
|
||||
/// A quarter turn about X through the origin: a file's Y up becomes Z up.
|
||||
fn quarter_turn_x() -> solidcraft_doc::Mat {
|
||||
solidcraft_doc::rigid(solidcraft_geom::Vec3::ZERO, solidcraft_geom::Vec3::ZERO, solidcraft_geom::Vec3::X, std::f64::consts::FRAC_PI_2)
|
||||
@@ -120,7 +133,11 @@ fn add_step(s: &mut Session, path: &str, name: Option<&str>, options: &StepOptio
|
||||
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});
|
||||
let mut out = json!({"path": path, "feature": id, "name": fname, "bodies": created, "created_bodies": created, "warnings": sf.warnings, "system": sf.import.system});
|
||||
if let Some((up, exporter)) = exporter_up(&sf.import) {
|
||||
out["exporter"] = json!(exporter);
|
||||
out["exporter_up"] = json!(up);
|
||||
}
|
||||
placed.report(&mut out);
|
||||
if let Some(turned) = turned {
|
||||
out["stand_up"] = json!(turned);
|
||||
@@ -261,7 +278,7 @@ fn open(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.replace_design(fresh);
|
||||
let errors = s.model.results.iter().filter(|r| r.error.is_some()).count();
|
||||
let mut out = json!({"path": path, "features": s.doc.features.len(), "errors": errors, "bodies": r["bodies"], "warnings": r["warnings"]});
|
||||
for k in ["component", "component_name", "occurrence", "subcomponents", "rigid_joints", "stand_up"] {
|
||||
for k in ["component", "component_name", "occurrence", "subcomponents", "rigid_joints", "stand_up", "system", "exporter", "exporter_up"] {
|
||||
if let Some(v) = r.get(k) {
|
||||
out[k] = v.clone();
|
||||
}
|
||||
@@ -1078,4 +1095,33 @@ mod tests {
|
||||
assert!(stopped.world_state().bodies.is_empty());
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
/// Every option the format registry offers is a parameter its owning command documents,
|
||||
/// so the registry and the commands can't drift apart.
|
||||
#[test]
|
||||
fn registry_options_name_documented_command_parameters() {
|
||||
use solidcraft_io::formats;
|
||||
let params_of = |id: &str| crate::find_command(id).map(|c| c.params).unwrap_or_else(|| panic!("registry names unknown command {id}"));
|
||||
for f in formats::FORMATS {
|
||||
if let Some(import) = &f.import {
|
||||
for o in import.options {
|
||||
for id in ["doc.open", if import.target == formats::ImportTarget::Mesh { "file.insert_mesh" } else { "file.insert_step" }] {
|
||||
assert!(params_of(id).contains(o.param), "{}: `{}` is not a documented parameter of {id}", f.id, o.param);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(export) = &f.export {
|
||||
let params = params_of(export.command);
|
||||
if let Some(format) = export.format {
|
||||
assert!(params.contains(format), "{}: `{format}` is not a documented format of {}", f.id, export.command);
|
||||
}
|
||||
for o in export.options {
|
||||
assert!(params.contains(o.param), "{}: `{}` is not a documented parameter of {}", f.id, o.param, export.command);
|
||||
}
|
||||
}
|
||||
}
|
||||
for o in formats::DESIGN_SAVE_OPTIONS {
|
||||
assert!(params_of("file.save_as").contains(o.param), "`{}` is not a documented parameter of file.save_as", o.param);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -106,6 +106,14 @@ pub fn resolve(s: &mut Session) -> joints::Solution {
|
||||
resolve_holding(s, &BTreeMap::new())
|
||||
}
|
||||
|
||||
/// Update placements after an edit without computing a DOF report that the caller discards.
|
||||
/// Expressions and geometry-dependent couplings are refreshed just as in [`resolve`].
|
||||
pub fn place(s: &mut Session) -> joints::Solution {
|
||||
reexpress(s);
|
||||
recouple(s);
|
||||
place_holding(s, &BTreeMap::new())
|
||||
}
|
||||
|
||||
/// Work out the offsets, angles and values joints were given as expressions again (a parameter
|
||||
/// may have changed). One that can't be worked out (its parameter gone) keeps its numbers; the
|
||||
/// solve leaves that joint out and says why.
|
||||
@@ -165,8 +173,22 @@ fn recouple(s: &mut Session) {
|
||||
/// 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 {
|
||||
let st = s.model.state();
|
||||
let sol = joints::solve_holding(&s.doc, &st, held);
|
||||
resolve_with_analysis(s, held, joints::Analysis::DegreesOfFreedom)
|
||||
}
|
||||
|
||||
/// Contact and loop-search trials need placements and conflicts, not a DOF report.
|
||||
pub(super) fn place_holding(s: &mut Session, held: &joints::Held) -> joints::Solution {
|
||||
resolve_with_analysis(s, held, joints::Analysis::Placement)
|
||||
}
|
||||
|
||||
fn solution(s: &Session, held: &joints::Held, analysis: joints::Analysis) -> joints::Solution {
|
||||
#[cfg(test)]
|
||||
solve_counts::record(analysis);
|
||||
joints::solve_holding_with_analysis(&s.doc, &s.model.state(), held, analysis)
|
||||
}
|
||||
|
||||
fn resolve_with_analysis(s: &mut Session, held: &joints::Held, analysis: joints::Analysis) -> joints::Solution {
|
||||
let sol = solution(s, held, analysis);
|
||||
if !sol.world.is_empty() {
|
||||
let mut next = (*s.doc).clone();
|
||||
if next.apply_joint_solution(&sol) {
|
||||
@@ -177,6 +199,11 @@ pub fn resolve_holding(s: &mut Session, held: &joints::Held) -> joints::Solution
|
||||
sol
|
||||
}
|
||||
|
||||
/// A quiet drive/reach does not publish DOF, so it needs only placement and constraint checks.
|
||||
fn response_analysis(p: &Value) -> joints::Analysis {
|
||||
if bool_(p, "quiet").unwrap_or(false) { joints::Analysis::Placement } else { joints::Analysis::DegreesOfFreedom }
|
||||
}
|
||||
|
||||
/// A solve's answer; `quiet: true` in the command's params leaves out the per-occurrence lists.
|
||||
fn sol_json(sol: &joints::Solution, p: &Value) -> Value {
|
||||
let mut out = json!({
|
||||
@@ -313,7 +340,7 @@ pub(crate) fn occurrence_at(s: &Session, p: Vec3) -> Option<u64> {
|
||||
}
|
||||
|
||||
/// A joint origin from parameters: a named origin, or a snap given in world coordinates.
|
||||
fn origin_param(s: &Session, v: Option<&Value>, cmd: &str) -> Result<JointOrigin> {
|
||||
pub(crate) fn origin_param(s: &Session, v: Option<&Value>, cmd: &str) -> Result<JointOrigin> {
|
||||
let v = v.ok_or_else(|| bad(cmd, "joint origins `a` and `b` are required"))?;
|
||||
if let Value::String(name) = v {
|
||||
return s
|
||||
@@ -407,7 +434,13 @@ fn origin_by_name(s: &Session, v: &Value, what: &str, name: &str, cmd: &str) ->
|
||||
return Err(bad(cmd, "a face name is 1…512 characters"));
|
||||
}
|
||||
let st = s.model.state();
|
||||
let (component, pick) = joints::named_face_spot(&s.doc, &st, str_(v, "body"), name).map_err(|why| bad(cmd, why))?;
|
||||
let (component, pick) = joints::named_face_spot(&s.doc, &st, str_(v, "body"), name).map_err(|why| {
|
||||
if s.doc.assembly.origins.iter().any(|o| o.name == name) {
|
||||
bad(cmd, format!("`{name}` is a joint origin: pass it as the whole origin, not as a `{what}` name"))
|
||||
} else {
|
||||
bad(cmd, why)
|
||||
}
|
||||
})?;
|
||||
let occurrence = match v.get("occurrence") {
|
||||
Some(o) => occurrence_id(s, Some(o), cmd)?,
|
||||
None if component == 0 => 0,
|
||||
@@ -787,7 +820,7 @@ fn drive(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let before = super::motion::positions(s);
|
||||
let r = super::motion::drive_joint(s, id, q, given)?;
|
||||
let sol = joints::solve(&s.doc, &s.model.state());
|
||||
let sol = solution(s, &BTreeMap::new(), response_analysis(p));
|
||||
let mut out = sol_json(&sol, p);
|
||||
out["joint"] = json!(id);
|
||||
out["values"] = json!(effective_values(s, id));
|
||||
@@ -852,7 +885,7 @@ fn reach(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Err(_) => joints::Reached::default(),
|
||||
};
|
||||
// Loops closed again from there, and where it ended up.
|
||||
let sol = resolve(s);
|
||||
let sol = if response_analysis(p) == joints::Analysis::Placement { place(s) } else { 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);
|
||||
@@ -1439,3 +1472,25 @@ mod tests;
|
||||
#[cfg(test)]
|
||||
#[path = "joints_turn_tests.rs"]
|
||||
mod turn_tests;
|
||||
|
||||
/// Per-thread work counts for ordinary engine regression tests; no production instrumentation.
|
||||
#[cfg(test)]
|
||||
pub(super) mod solve_counts {
|
||||
use solidcraft_doc::joints::Analysis;
|
||||
use std::cell::Cell;
|
||||
|
||||
thread_local! {
|
||||
static COUNTS: Cell<(usize, usize)> = const { Cell::new((0, 0)) };
|
||||
}
|
||||
|
||||
pub fn record(analysis: Analysis) {
|
||||
COUNTS.with(|c| {
|
||||
let (all, full) = c.get();
|
||||
c.set((all + 1, full + usize::from(analysis == Analysis::DegreesOfFreedom)));
|
||||
});
|
||||
}
|
||||
|
||||
pub fn take() -> (usize, usize) {
|
||||
COUNTS.with(|c| c.replace((0, 0)))
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,35 @@ fn near(a: Vec3, b: Vec3) -> bool {
|
||||
a.dist(b) < 1e-6
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn joint_origin_names_in_face_or_circle_explain_the_correct_form() {
|
||||
let mut s = Session::default();
|
||||
for (name, corner) in [("A", [0, 0, 0]), ("B", [40, 0, 0])] {
|
||||
run(&mut s, "component.create", json!({"name": name}));
|
||||
run(&mut s, "solid.box", json!({"length": 20, "width": 20, "height": 10, "corner": corner}));
|
||||
run(&mut s, "component.activate", json!({"component": "root"}));
|
||||
}
|
||||
run(&mut s, "joint.origin", json!({"name": "TopA", "occurrence": "A:1", "face": [10, 10, 10]}));
|
||||
run(&mut s, "joint.origin", json!({"name": "BotB", "occurrence": "B:1", "face": [50, 10, 0]}));
|
||||
for field in ["face", "circle"] {
|
||||
for (side, name, occurrence) in [("a", "TopA", "A:1"), ("b", "BotB", "B:1")] {
|
||||
let mut params = json!({"type": "rigid", "a": "TopA", "b": "BotB"});
|
||||
params[side] = json!({"occurrence": occurrence, field: name});
|
||||
let error = s.execute("joint.create", ¶ms).unwrap_err().to_string();
|
||||
assert_eq!(
|
||||
error,
|
||||
format!("invalid parameters for `joint.create`: `{name}` is a joint origin: pass it as the whole origin, not as a `{field}` name")
|
||||
);
|
||||
assert!(s.doc.assembly.joints.is_empty());
|
||||
}
|
||||
}
|
||||
let error = s.execute("joint.create", &json!({"type": "rigid", "a": {"face": "Missing"}, "b": "BotB"})).unwrap_err().to_string();
|
||||
assert!(error.contains("no face is named `Missing`"), "{error}");
|
||||
let result = run(&mut s, "joint.create", json!({"type": "rigid", "a": "TopA", "b": "BotB"}));
|
||||
assert_eq!(result["errors"].as_array().map(Vec::len), Some(0), "{result}");
|
||||
assert_eq!(s.doc.assembly.joints.len(), 1);
|
||||
}
|
||||
|
||||
/// Widths swept: small steps (a hole's wall in a 1 mm plate is a few long facets, and a pick
|
||||
/// stored at the old width lies beside the moved hole) and large ones.
|
||||
const WIDTHS: [f64; 9] = [302.0, 304.0, 310.0, 330.0, 400.0, 450.0, 510.0, 301.0, 300.0];
|
||||
|
||||
@@ -313,3 +313,74 @@ fn reach_refuses_bad_params_and_says_why_nothing_moves() {
|
||||
assert!(r["reason"].as_str().is_some_and(|w| w.contains(why)), "{p}: {r}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Reach still publishes fresh full diagnostics after a lightweight refresh, including stationary
|
||||
/// mouse frames, loop-limited targets and undo/redo. Full analysis runs once only when requested.
|
||||
#[test]
|
||||
fn reach_preserves_full_diagnostics_without_repeating_dof_analysis() {
|
||||
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);
|
||||
for (angle, quiet) in [(-10.0_f64, false), (-5.0, true), (-5.0, true), (100.0, false)] {
|
||||
let a = start + angle.to_radians();
|
||||
let to = o4 + Vec3::new(40.0 * a.cos(), 40.0 * a.sin(), 0.0);
|
||||
super::solve_counts::take();
|
||||
let r = reach(&mut s, "Rocker", q0, json!({"point":pt(to), "continuous":true, "quiet":quiet}));
|
||||
assert_eq!(super::solve_counts::take().1, usize::from(!quiet));
|
||||
assert_eq!(r["reached"], angle != 100.0, "{r}");
|
||||
assert_eq!(r["stopped_by_loop"].is_object(), angle == 100.0, "{r}");
|
||||
let expected = super::sol_json(&solidcraft_doc::joints::solve(&s.doc, &s.model.state()), &json!({"quiet":quiet}));
|
||||
for key in ["dof", "fixed", "errors", "conflicts"] {
|
||||
assert_eq!(r.get(key), expected.get(key), "{key}: {r}");
|
||||
}
|
||||
let listed = run(&mut s, "joint.list", json!({}));
|
||||
let full = super::sol_json(&solidcraft_doc::joints::solve(&s.doc, &s.model.state()), &json!({}));
|
||||
assert_eq!(listed["dof"], full["dof"]);
|
||||
}
|
||||
for command in ["edit.undo", "edit.redo"] {
|
||||
run(&mut s, command, json!({}));
|
||||
let full = solidcraft_doc::joints::solve(&s.doc, &s.model.state());
|
||||
assert!(full.conflicts.is_empty() && full.errors.is_empty());
|
||||
for part in ["Crank", "Coupler", "Rocker"] {
|
||||
assert_eq!(full.dof.get(&occ(&s, part)), Some(&1), "{command}: {part}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Successive large pointer goals must use the new joint values at every perturbation and
|
||||
/// solve, keep all loop pins together and preserve mobility reports through undo/redo.
|
||||
#[test]
|
||||
fn quarter_turn_reaches_keep_the_four_bar_closed_and_diagnostics_current() {
|
||||
let (mut s, p0, q0) = four_bar();
|
||||
let ground = place(&s, "Ground", Vec3::ZERO);
|
||||
for (i, point) in
|
||||
[Vec3::new(-20.0, 0.0, 0.0), Vec3::new(0.0, -20.0, 0.0), Vec3::new(20.0, 0.0, 0.0), Vec3::new(0.0, 20.0, 0.0)].into_iter().enumerate()
|
||||
{
|
||||
let r = reach(&mut s, "Crank", p0, json!({"point":pt(point), "continuous":true, "quiet":i % 2 == 0}));
|
||||
assert_eq!((&r["reached"], &r["stopped_by_loop"], &r["stopped_by_limit"]), (&json!(true), &Value::Null, &Value::Null), "{r}");
|
||||
assert!(place(&s, "Crank", p0).dist(point) < 1e-5, "{r}");
|
||||
let rocker = place(&s, "Rocker", q0);
|
||||
let [a, b] = meet(point, 50.0, Vec3::new(45.0, 0.0, 0.0), 40.0);
|
||||
assert!(rocker.dist(a).min(rocker.dist(b)) < 1e-5, "{r}");
|
||||
assert!(place(&s, "Coupler", q0).dist(rocker) < 1e-6, "{r}");
|
||||
assert!(place(&s, "Coupler", p0).dist(point) < 1e-5, "{r}");
|
||||
assert_eq!(place(&s, "Ground", Vec3::ZERO), ground);
|
||||
let full = solidcraft_doc::joints::solve(&s.doc, &s.model.state());
|
||||
assert!(full.errors.is_empty() && full.conflicts.is_empty(), "{full:?}");
|
||||
for part in ["Crank", "Coupler", "Rocker"] {
|
||||
assert_eq!(full.dof.get(&occ(&s, part)), Some(&1));
|
||||
}
|
||||
let steps = s.undo.len();
|
||||
let again = reach(&mut s, "Crank", p0, json!({"point":pt(point), "continuous":true, "quiet":true}));
|
||||
assert_eq!((&again["reached"], &again["moved"], s.undo.len()), (&json!(true), &json!(false), steps), "{again}");
|
||||
}
|
||||
for (command, point) in [("edit.undo", Vec3::new(20.0, 0.0, 0.0)), ("edit.redo", p0)] {
|
||||
run(&mut s, command, json!({}));
|
||||
assert!(place(&s, "Crank", p0).dist(point) < 1e-5, "{command}");
|
||||
let full = solidcraft_doc::joints::solve(&s.doc, &s.model.state());
|
||||
assert!(full.errors.is_empty() && full.conflicts.is_empty(), "{command}: {full:?}");
|
||||
for part in ["Crank", "Coupler", "Rocker"] {
|
||||
assert_eq!(full.dof.get(&occ(&s, part)), Some(&1));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -977,6 +977,9 @@ fn a_part_at_a_dead_point_of_its_loop_keeps_its_mobility() {
|
||||
pin(&mut s, "revolute", "Root pin", "Ground", "Barrel", root, Vec3::Z);
|
||||
pin(&mut s, "slider", "Stroke", "Barrel", "Rod", root, Vec3::Y);
|
||||
pin(&mut s, "revolute", "Tip pin", "Rod", "Panel", tip, Vec3::Z);
|
||||
super::solve_counts::take();
|
||||
s.refresh();
|
||||
assert_eq!(super::solve_counts::take().1, 0, "refresh must not repeat the singular-pose analysis");
|
||||
for part in ["Panel", "Barrel", "Rod"] {
|
||||
assert_eq!(dof_of(&mut s, part), 1, "dead point: {part}");
|
||||
}
|
||||
@@ -1377,6 +1380,194 @@ fn four_bar_coupler_point_traces_its_closed_form_curve() {
|
||||
assert!(from_study.iter().zip(&pts).all(|(a, b)| near(*a, *b)), "{r}");
|
||||
}
|
||||
|
||||
fn kept_trace_fit(s: &Session, id: u64) -> Vec<Vec3> {
|
||||
s.doc.sketch(id).unwrap().wires.first().unwrap().fit.clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chebyshev_demo_regenerates_its_analytic_trajectory_without_resampling_playback() {
|
||||
let mut s = Session::default();
|
||||
s.run_script(&serde_json::from_str(include_str!("../../../../examples/chebyshev-motion-trace.json")).unwrap()).unwrap();
|
||||
let trace = s.doc.assembly.traces.first().unwrap().clone();
|
||||
let original = kept_trace_fit(&s, trace.sketch);
|
||||
assert_eq!(original.len(), 145);
|
||||
assert_eq!(s.doc.assembly.joints.len(), 4);
|
||||
assert!(s.model.results.iter().all(|r| r.error.is_none()), "{:?}", s.model.results);
|
||||
// Independent circle-intersection construction: P is the crank end, Q the
|
||||
// coupler/rocker pin, and the tracer extends the coupler by another PQ.
|
||||
let mut q = Vec3::new(40.0, 50.0, 0.0);
|
||||
for (i, got) in original.iter().enumerate() {
|
||||
let theta = (90.0 + 2.5 * i as f64).to_radians();
|
||||
let p = Vec3::new(20.0 * theta.cos(), 20.0 * theta.sin(), 0.0);
|
||||
let [a, b] = meet(p, 50.0, Vec3::new(40.0, 0.0, 0.0), 50.0);
|
||||
q = if a.dist(q) < b.dist(q) { a } else { b };
|
||||
let want = q * 2.0 - p + Vec3::Z * 10.0;
|
||||
assert!(near(*got, want), "sample {i}: {got:?} wants {want:?}");
|
||||
}
|
||||
let count = s.motion_traces.recomputations;
|
||||
for angle in [30, 90, 180, 270, 0] {
|
||||
let result = run(&mut s, "joint.drive", json!({"joint":"Crank drive","value":angle,"quiet":true}));
|
||||
assert!(result["stopped_by_loop"].is_null(), "{result}");
|
||||
}
|
||||
assert_eq!(s.motion_traces.recomputations, count);
|
||||
assert_eq!(kept_trace_fit(&s, trace.sketch), original);
|
||||
|
||||
run(&mut s, "parameters.change", json!({"name":"coupler_length","expression":"55 mm"}));
|
||||
let updated = kept_trace_fit(&s, trace.sketch);
|
||||
let [q, _] = meet(Vec3::new(0.0, 20.0, 0.0), 55.0, Vec3::new(40.0, 0.0, 0.0), 50.0);
|
||||
assert!(near(updated[0], q * 2.0 - Vec3::new(0.0, 20.0, 0.0) + Vec3::Z * 10.0));
|
||||
assert_ne!(updated, original);
|
||||
assert_eq!(s.doc.assembly.traces[0].wire, trace.wire);
|
||||
assert_eq!(s.motion_traces.recomputations, count + 1, "a dimension edit resamples once");
|
||||
assert!(s.model.result(trace.sketch).unwrap().warning.is_none());
|
||||
|
||||
run(&mut s, "parameters.change", json!({"changes":{"coupler_length":"2.5 * unit_length","unit_length":"24 mm"}}));
|
||||
let scaled = kept_trace_fit(&s, trace.sketch);
|
||||
assert!(scaled.iter().zip(&original).all(|(a, b)| near(*a, Vec3::new(b.x * 1.2, b.y * 1.2, 10.0))));
|
||||
run(&mut s, "parameters.change", json!({"name":"trace_sweep","expression":"180 deg"}));
|
||||
let half = kept_trace_fit(&s, trace.sketch);
|
||||
assert!(near(half[0], scaled[0]) && near(*half.last().unwrap(), scaled[72]));
|
||||
assert!(s.model.results.iter().all(|r| r.error.is_none()), "{:?}", s.model.results);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn associative_trace_reuses_pose_and_unrelated_edits_but_follows_drive_expressions() {
|
||||
let (mut s, p0, q0) = four_bar();
|
||||
let mid = (p0 + q0) * 0.5;
|
||||
run(&mut s, "parameters.add", json!({"name":"swing","expression":"90 deg"}));
|
||||
let r = run(
|
||||
&mut s,
|
||||
"motion.trace.keep",
|
||||
json!({"occurrence":"Coupler","point":[mid.x,mid.y,mid.z],
|
||||
"joint":"Crank","from":0,"to":"swing","samples":19}),
|
||||
);
|
||||
let id = r["sketch"].as_u64().unwrap();
|
||||
let original = kept_trace_fit(&s, id);
|
||||
let count = s.motion_traces.recomputations;
|
||||
for angle in [20, 45, 75, 10] {
|
||||
run(&mut s, "joint.drive", json!({"joint":"Crank","value":angle,"quiet":true}));
|
||||
assert_eq!(kept_trace_fit(&s, id), original);
|
||||
}
|
||||
run(&mut s, "parameters.add", json!({"name":"unrelated","expression":"123 mm"}));
|
||||
run(&mut s, "parameters.change", json!({"name":"unrelated","expression":"456 mm"}));
|
||||
assert_eq!(s.motion_traces.recomputations, count, "pose and unrelated edits must not resample");
|
||||
let mut preview = s.scratch();
|
||||
run(&mut preview, "joint.drive", json!({"joint":"Crank","value":80,"quiet":true}));
|
||||
assert_eq!(preview.motion_traces.recomputations, count, "scratch previews reuse the same valid inputs");
|
||||
run(&mut s, "parameters.change", json!({"name":"swing","expression":"180 deg"}));
|
||||
let updated = kept_trace_fit(&s, id);
|
||||
assert_ne!(updated, original);
|
||||
assert_eq!(s.motion_traces.recomputations, count + 1, "a parameter command may refresh twice; sample once");
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(kept_trace_fit(&s, id), original);
|
||||
run(&mut s, "edit.redo", json!({}));
|
||||
assert_eq!(kept_trace_fit(&s, id), updated);
|
||||
assert_eq!(s.motion_traces.recomputations, count + 1, "undo and redo reuse the retained input results");
|
||||
run(&mut s, "parameters.rename", json!({"name":"swing","new_name":"travel"}));
|
||||
assert_eq!(s.motion_traces.recomputations, count + 1, "renaming a parameter leaves resolved inputs unchanged");
|
||||
let count = s.motion_traces.recomputations;
|
||||
let before = s.doc.clone();
|
||||
for invalid in [
|
||||
json!({"sketch":id,"samples":501}),
|
||||
json!({"sketch":id,"index":99}),
|
||||
json!({"sketch":id,"from":"missing_parameter"}),
|
||||
json!({"sketch":id,"joint":"Missing","from":0,"to":90}),
|
||||
] {
|
||||
assert!(s.execute("motion.trace.edit", &invalid).is_err());
|
||||
assert_eq!(*s.doc, *before, "invalid trace edits must be atomic");
|
||||
}
|
||||
run(&mut s, "motion.trace.edit", json!({"sketch":id,"samples":19}));
|
||||
assert_eq!(s.motion_traces.recomputations, count, "an identical definition is reusable");
|
||||
assert!(std::sync::Arc::ptr_eq(&before, &s.doc), "an identical edit must not refresh the model or add an undo step");
|
||||
run(&mut s, "motion.trace.edit", json!({"sketch":id,"auto_update":false}));
|
||||
run(&mut s, "parameters.change", json!({"name":"travel","expression":"270 deg"}));
|
||||
assert_eq!(kept_trace_fit(&s, id), updated, "detaching preserves the curve");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn associative_trace_follows_a_study_and_survives_serialization() {
|
||||
let (mut s, p0, q0) = four_bar();
|
||||
let mid = (p0 + q0) * 0.5;
|
||||
let study = run(
|
||||
&mut s,
|
||||
"motion.study",
|
||||
json!({"name":"Turn","steps":18,
|
||||
"keys":[{"joint":"Crank","points":[[0,0],[18,90]]}]}),
|
||||
);
|
||||
let r = run(&mut s, "motion.trace.keep", json!({"occurrence":"Coupler","point":[mid.x,mid.y,mid.z],"study":"Turn"}));
|
||||
let id = r["sketch"].as_u64().unwrap();
|
||||
let original = kept_trace_fit(&s, id);
|
||||
run(
|
||||
&mut s,
|
||||
"motion.study",
|
||||
json!({"study":study["study"],"name":"Turn","steps":36,
|
||||
"keys":[{"joint":"Crank","points":[[0,0],[36,180]]}]}),
|
||||
);
|
||||
assert_eq!(kept_trace_fit(&s, id).len(), 37);
|
||||
assert_ne!(kept_trace_fit(&s, id), original);
|
||||
let doc: solidcraft_doc::Document = serde_json::from_value(serde_json::to_value(&*s.doc).unwrap()).unwrap();
|
||||
let mut opened = Session::new(doc);
|
||||
run(&mut opened, "motion.trace.edit", json!({"sketch":id,"samples":25}));
|
||||
assert_eq!(kept_trace_fit(&opened, id).len(), 25);
|
||||
run(&mut opened, "motion.delete", json!({"study":"Turn"}));
|
||||
assert!(run(&mut opened, "motion.list", json!({}))["traces"][0]["error"].is_string());
|
||||
assert!(opened.model.result(id).unwrap().warning.as_ref().unwrap().contains("last successful"));
|
||||
let count = opened.motion_traces.recomputations;
|
||||
opened.refresh();
|
||||
assert_eq!(opened.motion_traces.recomputations, count, "a missing dependency must not retry on every refresh");
|
||||
run(&mut opened, "edit.undo", json!({}));
|
||||
assert!(run(&mut opened, "motion.list", json!({}))["traces"][0]["error"].is_null());
|
||||
assert!(opened.model.result(id).unwrap().warning.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn associative_trace_follows_a_resized_picked_face_and_keeps_downstream_paths_current() {
|
||||
let mut s = two_cubes();
|
||||
pin(&mut s, "revolute", "Pivot", "A", "B", Vec3::new(20.0, 0.0, 0.0), Vec3::Z);
|
||||
let r = run(
|
||||
&mut s,
|
||||
"motion.trace.keep",
|
||||
json!({"occurrence":"B","point":[25,5,10],
|
||||
"point_ref":{"occurrence":"B","face":[25,5,10]},"joint":"Pivot","from":0,"to":90,"samples":2}),
|
||||
);
|
||||
let id = r["sketch"].as_u64().unwrap();
|
||||
let original = kept_trace_fit(&s, id);
|
||||
run(&mut s, "component.activate", json!({"component":"root"}));
|
||||
run(&mut s, "solid.pipe", json!({"path_sketch":id,"path":r["curves"],"diameter":1,"operation":"new","body_name":"TracePipe"}));
|
||||
let pipe_before = s.model.state().body("TracePipe").unwrap().outline_bounds();
|
||||
let comp = s.doc.find_component("B").unwrap();
|
||||
let height =
|
||||
s.doc.features.iter().find(|f| f.component == comp && matches!(f.kind, solidcraft_doc::FeatureKind::Box { .. })).unwrap().param_names[2]
|
||||
.clone();
|
||||
let count = s.motion_traces.recomputations;
|
||||
run(&mut s, "parameters.change", json!({"name":height,"expression":"15 mm"}));
|
||||
let updated = kept_trace_fit(&s, id);
|
||||
assert!(updated.iter().all(|p| (p.z - 15.0).abs() < 1e-6));
|
||||
assert_ne!(original, updated);
|
||||
assert_eq!(s.motion_traces.recomputations, count + 1);
|
||||
let model = s.model.state();
|
||||
assert_eq!(model.sketch(id).unwrap().sketch.wires.first().unwrap().fit, updated);
|
||||
let pipe_after = model.body("TracePipe").unwrap().outline_bounds();
|
||||
assert!((pipe_after.min.z - pipe_before.min.z - 5.0).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn associative_trace_ignores_another_mechanism_on_the_same_ground() {
|
||||
let (mut s, p0, q0) = four_bar();
|
||||
part(&mut s, "Other", [100.0, 0.0, -5.0]);
|
||||
pin(&mut s, "revolute", "Other pivot", "Ground", "Other", Vec3::new(100.0, 0.0, 0.0), Vec3::Z);
|
||||
let mid = (p0 + q0) * 0.5;
|
||||
run(
|
||||
&mut s,
|
||||
"motion.trace.keep",
|
||||
json!({"occurrence":"Coupler","point":[mid.x,mid.y,mid.z],
|
||||
"joint":"Crank","from":0,"to":180,"samples":19}),
|
||||
);
|
||||
let count = s.motion_traces.recomputations;
|
||||
run(&mut s, "joint.limits", json!({"joint":"Other pivot","min":-20,"max":30}));
|
||||
assert_eq!(s.motion_traces.recomputations, count);
|
||||
}
|
||||
|
||||
/// 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]
|
||||
@@ -1760,3 +1951,63 @@ fn joint_inspect_reads_only() {
|
||||
assert_eq!(run(&mut s, "document.inspect", json!({}))["undo"], undo);
|
||||
assert_eq!(serde_json::to_value(&s.doc).unwrap_or_default(), before);
|
||||
}
|
||||
|
||||
/// Trial placements use exactly the same constraints as a full solve. Only the expensive DOF
|
||||
/// report is optional: loop stops, errors and the resulting pose must not depend on it.
|
||||
#[test]
|
||||
fn placement_analysis_preserves_held_loop_constraints_and_diagnostics() {
|
||||
use solidcraft_doc::joints::{self, Analysis};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
let (s, _, _) = four_bar();
|
||||
let rocker = s.doc.assembly.joints.iter().find(|j| j.name == "Rocker").unwrap().id;
|
||||
let held = BTreeMap::from([((rocker, 0), 0.0)]);
|
||||
for angle in [-10.0_f64, 40.0, 100.0] {
|
||||
let mut doc = (*s.doc).clone();
|
||||
doc.assembly.joints.iter_mut().find(|j| j.id == rocker).unwrap().values[0] = angle.to_radians();
|
||||
let full = joints::solve_holding(&doc, &s.model.state(), &held);
|
||||
let placement = joints::solve_holding_with_analysis(&doc, &s.model.state(), &held, Analysis::Placement);
|
||||
assert!(placement.dof.is_empty(), "trial placement must not compute DOF");
|
||||
assert_eq!(placement.world, full.world);
|
||||
assert_eq!(placement.values, full.values);
|
||||
assert_eq!(placement.fixed, full.fixed);
|
||||
assert_eq!(placement.conflicts, full.conflicts);
|
||||
assert_eq!(placement.errors, full.errors);
|
||||
let mut placed = doc.clone();
|
||||
placed.apply_joint_solution(&placement);
|
||||
let mut reference = doc;
|
||||
reference.apply_joint_solution(&full);
|
||||
assert_eq!(placed, reference);
|
||||
assert_eq!(joints::solve(&placed, &s.model.state()).dof, joints::solve(&reference, &s.model.state()).dof);
|
||||
}
|
||||
// A degenerate origin remains an error even in a placement-only trial.
|
||||
let mut broken = (*s.doc).clone();
|
||||
broken.assembly.joints[0].b.snap = solidcraft_doc::joints::Snap::Point { point: Vec3::ZERO, z: Some(Vec3::ZERO), x: None };
|
||||
let full = joints::solve(&broken, &s.model.state());
|
||||
let placement = joints::solve_holding_with_analysis(&broken, &s.model.state(), &BTreeMap::new(), Analysis::Placement);
|
||||
assert!(!full.errors.is_empty());
|
||||
assert_eq!(placement.errors, full.errors);
|
||||
assert_eq!(placement.conflicts, full.conflicts);
|
||||
}
|
||||
|
||||
/// Ordinary commands publish one complete report; refresh only updates constraint placements.
|
||||
/// Counts are deterministic work assertions, not timing thresholds tied to a test machine.
|
||||
#[test]
|
||||
fn joint_drive_and_refresh_do_not_repeat_dof_analysis() {
|
||||
let (mut s, _, _) = four_bar();
|
||||
for (angle, quiet) in [(17, false), (58, true), (105, false)] {
|
||||
super::solve_counts::take();
|
||||
let r = run(&mut s, "joint.drive", json!({"joint":"Crank", "value":angle, "quiet":quiet}));
|
||||
let (all, full) = super::solve_counts::take();
|
||||
assert!(all > full, "placement trials must still run");
|
||||
assert_eq!(full, usize::from(!quiet), "only a published DOF report needs full analysis");
|
||||
let expected = super::sol_json(&solidcraft_doc::joints::solve(&s.doc, &s.model.state()), &json!({"quiet":quiet}));
|
||||
for key in ["dof", "fixed", "errors", "conflicts"] {
|
||||
assert_eq!(r.get(key), expected.get(key), "{key}: {r}");
|
||||
}
|
||||
let before = s.doc.clone();
|
||||
s.refresh();
|
||||
assert_eq!(super::solve_counts::take().1, 0, "refresh discards the DOF report");
|
||||
assert_eq!(*s.doc, *before);
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@ use solidcraft_geom::{Aabb3, Vec3};
|
||||
use solidcraft_kernel::Body;
|
||||
|
||||
use super::CommandSpec;
|
||||
use super::joints::{cannot_move, effective_values, joint_id, occurrence_id, resolve_holding, value};
|
||||
use super::joints::{cannot_move, effective_values, joint_id, occurrence_id, place_holding, value};
|
||||
use crate::params::{bad, bool_, str_, vec3};
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
@@ -18,6 +18,8 @@ use crate::{EngineError, Result, Session};
|
||||
mod analysis;
|
||||
#[path = "motion_animation.rs"]
|
||||
mod animation;
|
||||
#[path = "motion_trace.rs"]
|
||||
pub(crate) mod associative;
|
||||
#[path = "contact_sweep.rs"]
|
||||
pub(crate) mod contact_sweep;
|
||||
#[path = "motion_sweep.rs"]
|
||||
@@ -76,9 +78,14 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
)),
|
||||
CommandSpec::new("motion.trace.keep", "Keep Motion Trace", keep_trace).icon("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"
|
||||
"; name? (default Motion TraceN); auto_update?: bool (default true); point_ref?: joint origin snap - keeps the trace as a \
|
||||
root 3D sketch spline. Associative curves follow mechanism and driving-input edits; false keeps a fixed curve. \
|
||||
point_ref retains a geometry snap; otherwise point is retained in component coordinates → sketch, name, curves, points"
|
||||
)),
|
||||
CommandSpec::new("motion.trace.edit", "Edit Motion Trace", associative::edit).icon("trace").params(
|
||||
"sketch: id|name; joint? with from and to, or study?; index?; samples? (2…500); auto_update?: false to detach. \
|
||||
Edits a saved associative trace's driving conditions in one undo step",
|
||||
),
|
||||
CommandSpec::new("motion.plot", "Plot Motion Study", analysis::plot).icon("graph").noundo().params(analysis::PLOT_DOC),
|
||||
CommandSpec::new("motion.interference", "Motion Interference", analysis::interference).icon("interference").noundo().params(analysis::INTERFERENCE_DOC),
|
||||
CommandSpec::new("joint.sweep", "Sweep Joint", sweep::sweep).icon("interference").params(sweep::SWEEP_DOC),
|
||||
@@ -370,7 +377,7 @@ fn drive_with_contact(s: &mut Session, want: &[(u64, Vec<f64>)], given: &BTreeSe
|
||||
j.values = q;
|
||||
}
|
||||
}
|
||||
resolve_holding(s, &held)
|
||||
place_holding(s, &held)
|
||||
};
|
||||
// Loops already open at the start stay as they are; a loop the motion opens stops it.
|
||||
let open_at_start: BTreeSet<u64> = set(s, 0.0).conflicts.iter().map(|c| c.0).collect();
|
||||
@@ -881,7 +888,16 @@ fn trace(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// 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<Value> {
|
||||
let cmd = "motion.trace.keep";
|
||||
let (mut points, mut out) = sample_trace(s, p, cmd)?;
|
||||
let source = if bool_(p, "auto_update") != Some(false) { Some(associative::source(s, p, cmd)?) } else { None };
|
||||
let (mut points, out) = sample_trace(s, p, cmd)?;
|
||||
finish_trace(&mut points);
|
||||
if points.len() < 2 {
|
||||
return Err(bad(cmd, "the point does not move: there is no trace to keep"));
|
||||
}
|
||||
keep_sampled_trace(s, p, cmd, points, out, source)
|
||||
}
|
||||
|
||||
fn finish_trace(points: &mut Vec<Vec3>) {
|
||||
// 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
|
||||
@@ -896,9 +912,16 @@ fn keep_trace(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
points.push(first);
|
||||
}
|
||||
if points.len() < 2 {
|
||||
return Err(bad(cmd, "the point does not move: there is no trace to keep"));
|
||||
}
|
||||
}
|
||||
|
||||
fn keep_sampled_trace(
|
||||
s: &mut Session,
|
||||
p: &Value,
|
||||
cmd: &str,
|
||||
points: Vec<Vec3>,
|
||||
mut out: Value,
|
||||
source: Option<solidcraft_doc::motion::MotionTrace>,
|
||||
) -> Result<Value> {
|
||||
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(),
|
||||
@@ -919,15 +942,27 @@ fn keep_trace(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.revision += 1;
|
||||
let (made, spline) = made?;
|
||||
let sketch = made.get("sketch").cloned().unwrap_or(Value::Null);
|
||||
out["sketch"] = sketch;
|
||||
out["sketch"] = sketch.clone();
|
||||
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());
|
||||
if let Some(mut source) = source {
|
||||
source.sketch = sketch.as_u64().ok_or_else(|| bad(cmd, "trace sketch is missing"))?;
|
||||
source.wire = spline
|
||||
.get("curves")
|
||||
.and_then(Value::as_array)
|
||||
.and_then(|v| v.first())
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| bad(cmd, "trace curve is missing"))?
|
||||
.to_string();
|
||||
associative::remember(s, &source);
|
||||
s.doc_mut().assembly.traces.push(source);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn list_studies(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
Ok(json!({"studies": s.doc.assembly.studies}))
|
||||
Ok(json!({"studies": s.doc.assembly.studies, "traces": associative::list(s)}))
|
||||
}
|
||||
|
||||
fn delete_study(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -479,7 +479,11 @@ fn contact_sets_stop_a_driven_joint_at_touching() {
|
||||
assert!((b_x(&s) - 5.0).abs() < 1e-6);
|
||||
run(&mut s, "joint.drive", json!({"joint": "Rail", "value": 10}));
|
||||
run(&mut s, "contact.create", json!({"occurrences": ["A", "B"]}));
|
||||
super::super::joints::solve_counts::take();
|
||||
let r = run(&mut s, "joint.drive", json!({"joint": "Rail", "value": -5}));
|
||||
let (all, full) = super::super::joints::solve_counts::take();
|
||||
assert!(all > 4, "contact must still test intermediate placements");
|
||||
assert_eq!(full, 1, "contact trials must not repeat DOF analysis");
|
||||
assert!(r["stopped_by_contact"].is_object(), "{r}");
|
||||
// Stopped where the faces touch (to the search's resolution, 15 mm / 2^14).
|
||||
assert!((b_x(&s) - 10.0).abs() < 2e-3, "{}", b_x(&s));
|
||||
|
||||
@@ -0,0 +1,428 @@
|
||||
//! Associative trace definitions and dependency checks. Sampling uses the existing motion
|
||||
//! driver on a scratch session; only a changed generated wire is handed to the evaluator.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use solidcraft_doc::joints::{self, JointOrigin, Snap};
|
||||
use solidcraft_doc::motion::{MotionTrace, TraceMotion};
|
||||
use solidcraft_doc::{IDENTITY, apply_point};
|
||||
use solidcraft_geom::Vec3;
|
||||
|
||||
use crate::params::{bad, bool_};
|
||||
use crate::{Result, Session};
|
||||
|
||||
const CMD: &str = "motion.trace.edit";
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct Cache {
|
||||
entries: Arc<BTreeMap<u64, CacheEntry>>,
|
||||
history: Arc<BTreeMap<u64, Vec<(Value, Vec<Vec3>)>>>,
|
||||
#[cfg(test)]
|
||||
pub(crate) recomputations: usize,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct CacheEntry {
|
||||
inputs: std::result::Result<Value, String>,
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
fn motion(s: &Session, p: &Value, cmd: &str) -> Result<TraceMotion> {
|
||||
let _ = super::motion_plan(s, p, cmd)?;
|
||||
if p.get("study").is_some() {
|
||||
let study = s.doc.assembly.studies.get(super::study_index(s, p, cmd)?).ok_or_else(|| bad(cmd, "study is missing"))?;
|
||||
Ok(TraceMotion::Study { study: study.id })
|
||||
} else {
|
||||
Ok(TraceMotion::Joint {
|
||||
joint: super::joint_id(s, p.get("joint"), cmd)?,
|
||||
index: p.get("index").and_then(Value::as_u64).unwrap_or(0) as usize,
|
||||
from: p.get("from").cloned().unwrap_or(Value::Null),
|
||||
to: p.get("to").cloned().unwrap_or(Value::Null),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn source(s: &Session, p: &Value, cmd: &str) -> Result<MotionTrace> {
|
||||
if s.doc.assembly.traces.len() >= super::MAX_ITEMS {
|
||||
return Err(bad(cmd, "too many motion traces"));
|
||||
}
|
||||
let (occurrence, local) = super::traced_point(s, p, cmd)?;
|
||||
let point = match p.get("point_ref") {
|
||||
Some(v) => {
|
||||
let mut reference = v.clone();
|
||||
// The origin parser uses an occurrence's first placement. A trace can name a
|
||||
// different nested instance; convert its world pick to that canonical frame.
|
||||
let id = occurrence.last().copied().unwrap_or(0);
|
||||
let placed = placed_world(s, &occurrence)?;
|
||||
let inverse = solidcraft_doc::mat_inverse(&placed).ok_or_else(|| bad(cmd, "invalid occurrence placement"))?;
|
||||
let canonical = joints::occurrence_world(&s.doc, id);
|
||||
for key in ["face", "circle", "edge", "point"] {
|
||||
if let Some(at) = reference.get(key).and_then(crate::params::vec3) {
|
||||
let at = apply_point(&canonical, apply_point(&inverse, at));
|
||||
reference[key] = json!([at.x, at.y, at.z]);
|
||||
}
|
||||
}
|
||||
let o = super::super::joints::origin_param(s, Some(&reference), cmd)?;
|
||||
if o.occurrence != occurrence.last().copied().unwrap_or(0) {
|
||||
return Err(bad(cmd, "point_ref must belong to the traced occurrence"));
|
||||
}
|
||||
o
|
||||
}
|
||||
None => JointOrigin { occurrence: occurrence.last().copied().unwrap_or(0), snap: Snap::Point { point: local, z: None, x: None } },
|
||||
};
|
||||
let referenced = apply_point(&joints::resolve_origin(&s.doc, &s.model.state(), &point)?, Vec3::ZERO);
|
||||
if referenced.dist(local) > 1e-4 {
|
||||
return Err(bad(cmd, "point_ref must resolve to the traced point"));
|
||||
}
|
||||
let motion = motion(s, p, cmd)?;
|
||||
let samples = p.get("samples").map(|_| super::sample_count(p, 100, super::MAX_TRACE, cmd)).transpose()?;
|
||||
Ok(MotionTrace {
|
||||
sketch: 0,
|
||||
wire: String::new(),
|
||||
occurrence,
|
||||
point,
|
||||
motion,
|
||||
samples,
|
||||
seeds: s.doc.assembly.joints.iter().map(|j| (j.id, j.values.clone())).collect(),
|
||||
})
|
||||
}
|
||||
|
||||
fn params(t: &MotionTrace, point: Vec3) -> Value {
|
||||
let mut p = match &t.motion {
|
||||
TraceMotion::Joint { joint, index, from, to } => json!({"joint":joint,"index":index,"from":from,"to":to}),
|
||||
TraceMotion::Study { study } => json!({"study":study}),
|
||||
};
|
||||
p["occurrence"] = json!(t.occurrence);
|
||||
p["point"] = json!([point.x, point.y, point.z]);
|
||||
if let Some(n) = t.samples {
|
||||
p["samples"] = json!(n);
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
fn local(s: &Session, t: &MotionTrace) -> Result<Vec3> {
|
||||
if t.occurrence.len() > 64
|
||||
|| t.seeds.len() > joints::MAX_JOINTS
|
||||
|| t.seeds.iter().any(|(_, q)| q.len() > 6 || q.iter().any(|v| !v.is_finite()))
|
||||
|| t.point.occurrence != t.occurrence.last().copied().unwrap_or(0)
|
||||
{
|
||||
return Err(bad(CMD, "invalid saved trace inputs"));
|
||||
}
|
||||
let m = joints::resolve_origin(&s.doc, &s.model.state(), &t.point)?;
|
||||
let p = apply_point(&m, Vec3::ZERO);
|
||||
if !p.len().is_finite() || p.len() >= 1e7 {
|
||||
return Err(bad(CMD, "invalid trace point"));
|
||||
}
|
||||
Ok(p)
|
||||
}
|
||||
|
||||
fn placed_world(s: &Session, path: &[u64]) -> Result<solidcraft_doc::Mat> {
|
||||
s.doc.path_placement(path).map(|(_, world)| world).ok_or_else(|| bad(CMD, "the trace occurrence path is missing"))
|
||||
}
|
||||
|
||||
/// Only the moving graph connected to the trace/driver is followed. Grounded anchors stop
|
||||
/// traversal, so another mechanism attached to the same ground does not invalidate this one.
|
||||
fn graph(s: &Session, t: &MotionTrace) -> (BTreeSet<u64>, BTreeSet<u64>) {
|
||||
let a = &s.doc.assembly;
|
||||
// With contact enabled another mechanism can be an obstacle. Its joint frames and
|
||||
// stationary placements are then dependencies too, even without a joint to this trace.
|
||||
if a.contact_enabled {
|
||||
return (s.doc.occurrences.iter().map(|o| o.id).collect(), a.joints.iter().map(|j| j.id).collect());
|
||||
}
|
||||
let anchor = |id: u64| id == 0 || s.doc.occurrences.iter().any(|o| o.id == id && o.grounded);
|
||||
let mut occurrences: BTreeSet<u64> = t.occurrence.iter().copied().collect();
|
||||
let mut ids: BTreeSet<u64> = match &t.motion {
|
||||
TraceMotion::Joint { joint, .. } => BTreeSet::from([*joint]),
|
||||
TraceMotion::Study { study } => a.studies.iter().find(|m| m.id == *study).into_iter().flat_map(|m| m.keys.iter().map(|k| k.joint)).collect(),
|
||||
};
|
||||
loop {
|
||||
let before = (occurrences.len(), ids.len());
|
||||
for j in a.joints.iter().take(joints::MAX_JOINTS) {
|
||||
if ids.contains(&j.id) || (!j.suppressed && [j.a.occurrence, j.b.occurrence].iter().any(|o| !anchor(*o) && occurrences.contains(o))) {
|
||||
ids.insert(j.id);
|
||||
occurrences.extend([j.a.occurrence, j.b.occurrence]);
|
||||
}
|
||||
}
|
||||
for l in a.links.iter().take(joints::MAX_JOINTS) {
|
||||
if ids.contains(&l.a) || ids.contains(&l.b) {
|
||||
ids.extend([l.a, l.b]);
|
||||
}
|
||||
}
|
||||
let parents: Vec<_> = s.doc.occurrences.iter().filter(|o| occurrences.contains(&o.id)).flat_map(|o| s.doc.first_path(o.parent)).collect();
|
||||
occurrences.extend(parents);
|
||||
if before == (occurrences.len(), ids.len()) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
(occurrences, ids)
|
||||
}
|
||||
|
||||
fn inputs(s: &Session, t: &MotionTrace) -> Result<Value> {
|
||||
let at = local(s, t)?;
|
||||
// The plan reads only driving inputs, not the picked point or displayed placement.
|
||||
let p = params(t, at);
|
||||
placed_world(s, &t.occurrence)?;
|
||||
let (default, given, plan) = super::motion_plan(s, &p, CMD)?;
|
||||
let n = super::sample_count(&p, default.min(super::MAX_TRACE), super::MAX_TRACE, CMD)?;
|
||||
let (occurrences, ids) = graph(s, t);
|
||||
let st = s.model.state();
|
||||
let seeds: BTreeMap<u64, &Vec<f64>> = t.seeds.iter().map(|(id, q)| (*id, q)).collect();
|
||||
let mut joints = Vec::new();
|
||||
for j in s.doc.assembly.joints.iter().filter(|j| ids.contains(&j.id)) {
|
||||
let mut definition = j.clone();
|
||||
definition.name.clear();
|
||||
definition.values = seeds.get(&j.id).map(|q| (*q).clone()).unwrap_or_default();
|
||||
let (offset, angle, q) = joints::expressed(&s.doc, &definition)?;
|
||||
definition.offset = offset;
|
||||
definition.angle = angle;
|
||||
definition.values = q;
|
||||
definition.exprs = Default::default();
|
||||
let fa = joints::resolve_origin(&s.doc, &st, &j.a)?;
|
||||
let fb = joints::resolve_origin(&s.doc, &st, &j.b)?;
|
||||
joints.push(json!([definition, fa, fb]));
|
||||
}
|
||||
// Poses of driven parts are outputs. Only anchors and placements no joint places are
|
||||
// inputs. Include ancestors of nested paths to notice an enclosing assembly's move.
|
||||
let placed: BTreeSet<u64> = s.doc.assembly.joints.iter().filter(|j| !j.suppressed).flat_map(|j| [j.a.occurrence, j.b.occurrence]).collect();
|
||||
let poses: Vec<Value> = s
|
||||
.doc
|
||||
.occurrences
|
||||
.iter()
|
||||
.filter(|o| occurrences.contains(&o.id))
|
||||
.map(|o| json!([o.id, o.parent, o.component, o.grounded, if o.grounded || !placed.contains(&o.id) { o.transform } else { IDENTITY }]))
|
||||
.collect();
|
||||
let links: Vec<_> = s
|
||||
.doc
|
||||
.assembly
|
||||
.links
|
||||
.iter()
|
||||
.filter(|l| ids.contains(&l.a) || ids.contains(&l.b))
|
||||
.map(|l| {
|
||||
let mut l = l.clone();
|
||||
l.coupling = None;
|
||||
l
|
||||
})
|
||||
.collect();
|
||||
let study = match &t.motion {
|
||||
TraceMotion::Study { study } => s.doc.assembly.studies.iter().find(|m| m.id == *study).map(|m| json!([m.steps, m.keys])),
|
||||
_ => None,
|
||||
};
|
||||
let contact = if s.doc.assembly.contact_enabled {
|
||||
// Contact reads geometry, not just the joint frames. Content keys avoid meshing or
|
||||
// hashing triangles here; unkeyed bodies conservatively invalidate on a new revision.
|
||||
let bodies: Vec<_> = st.bodies.iter().map(|b| json!([b.name, b.component, b.geometry_key().unwrap_or(s.revision)])).collect();
|
||||
json!([s.doc.assembly.contact_all, s.doc.assembly.contact_sets, bodies])
|
||||
} else {
|
||||
Value::Null
|
||||
};
|
||||
// A plan fills unkeyed coordinates from the current pose. They belong to the retained
|
||||
// branch seed instead; normalizing the small value vectors avoids copying the document
|
||||
// merely to check whether a cached trace is still valid.
|
||||
let mut ends = [plan(s, 0, n), plan(s, n - 1, n)];
|
||||
for end in &mut ends {
|
||||
for (id, values) in end {
|
||||
if let Some(seed) = seeds.get(id) {
|
||||
for (i, v) in values.iter_mut().enumerate() {
|
||||
if !given.contains(&(*id, i)) {
|
||||
*v = seed.get(i).copied().unwrap_or(0.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(json!([t.sketch, t.wire, t.occurrence, at, n, given, ends, joints, poses, links, study, contact]))
|
||||
}
|
||||
|
||||
fn seeded(s: &Session, t: &MotionTrace) -> Session {
|
||||
let mut scratch = s.scratch();
|
||||
let seeds: BTreeMap<_, _> = t.seeds.iter().map(|(id, q)| (*id, q)).collect();
|
||||
for j in &mut scratch.doc_mut().assembly.joints {
|
||||
if let Some(q) = seeds.get(&j.id) {
|
||||
j.values = (*q).clone();
|
||||
}
|
||||
}
|
||||
scratch
|
||||
}
|
||||
|
||||
pub(super) fn remember(s: &mut Session, t: &MotionTrace) {
|
||||
let key = inputs(s, t).map_err(|e| e.to_string());
|
||||
if let Ok(key) = &key
|
||||
&& let Some(points) = s.doc.sketch(t.sketch).ok().and_then(|sk| sk.wires.iter().find(|w| w.id == t.wire)).map(|w| w.fit.clone())
|
||||
{
|
||||
remember_points(s, t.sketch, key.clone(), points);
|
||||
}
|
||||
Arc::make_mut(&mut s.motion_traces.entries).insert(t.sketch, CacheEntry { inputs: key, error: None });
|
||||
}
|
||||
|
||||
fn remember_points(s: &mut Session, id: u64, key: Value, points: Vec<Vec3>) {
|
||||
let history = Arc::make_mut(&mut s.motion_traces.history).entry(id).or_default();
|
||||
if history.iter().all(|(old, _)| *old != key) {
|
||||
if history.len() >= 8 {
|
||||
history.remove(0);
|
||||
}
|
||||
history.push((key, points));
|
||||
}
|
||||
}
|
||||
|
||||
fn same_points(a: &[Vec3], b: &[Vec3]) -> bool {
|
||||
a.len() == b.len() && a.iter().zip(b).all(|(a, b)| a.dist(*b) < 1e-9)
|
||||
}
|
||||
|
||||
fn sample(s: &Session, t: &MotionTrace) -> Result<Vec<Vec3>> {
|
||||
let at = local(s, t)?;
|
||||
let mut scratch = seeded(s, t);
|
||||
scratch.pending_moves.clear();
|
||||
let world = placed_world(&scratch, &t.occurrence)?;
|
||||
let p = params(t, apply_point(&world, at));
|
||||
let (mut points, _) = super::sample_trace(&scratch, &p, CMD)?;
|
||||
super::finish_trace(&mut points);
|
||||
if points.len() < 2 {
|
||||
return Err(bad(CMD, "the traced point no longer moves"));
|
||||
}
|
||||
Ok(points)
|
||||
}
|
||||
|
||||
/// Refresh generated curves once after the input model and joint origins are current. A
|
||||
/// failed dependency retains the last curve and publishes a warning instead of a stale success.
|
||||
pub(crate) fn refresh(s: &mut Session) {
|
||||
// Designs without associations pay no dependency-walk or geometry-check cost.
|
||||
if s.doc.assembly.traces.is_empty() {
|
||||
s.motion_traces.entries = Default::default();
|
||||
s.motion_traces.history = Default::default();
|
||||
return;
|
||||
}
|
||||
let existing: BTreeSet<u64> = s.doc.features.iter().map(|f| f.id).collect();
|
||||
if s.doc.assembly.traces.iter().any(|t| !existing.contains(&t.sketch)) {
|
||||
s.doc_mut().assembly.traces.retain(|t| existing.contains(&t.sketch));
|
||||
}
|
||||
if s.doc.assembly.traces.is_empty() {
|
||||
s.motion_traces.entries = Default::default();
|
||||
s.motion_traces.history = Default::default();
|
||||
return;
|
||||
}
|
||||
let traces: Vec<_> = s.doc.assembly.traces.iter().take(super::MAX_ITEMS).cloned().collect();
|
||||
for r in &mut s.model.results {
|
||||
if traces.iter().any(|t| t.sketch == r.id) && r.warning.as_ref().is_some_and(|w| w.starts_with("Motion Trace: ")) {
|
||||
r.warning = None;
|
||||
}
|
||||
}
|
||||
if s.motion_traces.entries.keys().any(|id| !traces.iter().any(|t| t.sketch == *id)) {
|
||||
Arc::make_mut(&mut s.motion_traces.entries).retain(|id, _| traces.iter().any(|t| t.sketch == *id));
|
||||
Arc::make_mut(&mut s.motion_traces.history).retain(|id, _| traces.iter().any(|t| t.sketch == *id));
|
||||
}
|
||||
let mut changed = false;
|
||||
for t in &traces {
|
||||
if s.doc.feature(t.sketch).is_none_or(|f| f.suppressed) {
|
||||
continue;
|
||||
}
|
||||
let key = inputs(s, t).map_err(|e| e.to_string());
|
||||
let cached = key
|
||||
.as_ref()
|
||||
.ok()
|
||||
.and_then(|key| s.motion_traces.history.get(&t.sketch).and_then(|h| h.iter().find(|(old, _)| old == key)).map(|(_, p)| p.clone()));
|
||||
let unchanged = s.motion_traces.entries.get(&t.sketch).is_some_and(|old| old.inputs == key);
|
||||
if unchanged
|
||||
&& cached.as_ref().is_none_or(|points| {
|
||||
s.doc.sketch(t.sketch).ok().and_then(|sk| sk.wires.iter().find(|w| w.id == t.wire)).is_some_and(|w| same_points(&w.fit, points))
|
||||
})
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let result = match &key {
|
||||
Ok(_) => match cached {
|
||||
Some(points) => Ok(points),
|
||||
None => {
|
||||
#[cfg(test)]
|
||||
{
|
||||
s.motion_traces.recomputations += 1;
|
||||
}
|
||||
sample(s, t).map_err(|e| e.to_string())
|
||||
}
|
||||
},
|
||||
Err(e) => Err(e.clone()),
|
||||
};
|
||||
if let (Ok(key), Ok(points)) = (&key, &result) {
|
||||
remember_points(s, t.sketch, key.clone(), points.clone());
|
||||
}
|
||||
let error = match result {
|
||||
Ok(points) => match s.doc.sketch(t.sketch).ok().and_then(|sk| sk.wires.iter().find(|w| w.id == t.wire)) {
|
||||
Some(wire) if same_points(&wire.fit, &points) => None,
|
||||
Some(_) => {
|
||||
if let Ok(sk) = s.doc_mut().sketch_mut(t.sketch)
|
||||
&& let Some(wire) = sk.wires.iter_mut().find(|w| w.id == t.wire)
|
||||
{
|
||||
wire.pts = solidcraft_sketch::fit_polyline(&points);
|
||||
wire.fit = points;
|
||||
changed = true;
|
||||
}
|
||||
None
|
||||
}
|
||||
None => Some("the generated trace curve is missing; detach or recreate the trace".to_string()),
|
||||
},
|
||||
Err(e) => Some(e),
|
||||
};
|
||||
Arc::make_mut(&mut s.motion_traces.entries).insert(t.sketch, CacheEntry { inputs: key, error });
|
||||
}
|
||||
if changed {
|
||||
s.model.evaluate(&s.doc);
|
||||
s.revision += 1;
|
||||
}
|
||||
for t in &traces {
|
||||
if let Some(error) = s.motion_traces.entries.get(&t.sketch).and_then(|e| e.error.as_ref())
|
||||
&& let Some(r) = s.model.results.iter_mut().find(|r| r.id == t.sketch)
|
||||
{
|
||||
r.warning = Some(format!("Motion Trace: {error}; showing its last successful curve"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn list(s: &Session) -> Vec<Value> {
|
||||
s.doc
|
||||
.assembly
|
||||
.traces
|
||||
.iter()
|
||||
.map(|t| {
|
||||
json!({"sketch":t.sketch,"motion":t.motion,"samples":t.samples,
|
||||
"error":s.motion_traces.entries.get(&t.sketch).and_then(|e| e.error.as_ref())})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(super) fn edit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let key = p.get("sketch").map(|v| v.as_str().map(str::to_string).unwrap_or_else(|| v.to_string())).ok_or_else(|| bad(CMD, "give a sketch"))?;
|
||||
let id = s.doc.find_feature(&key).map(|f| f.id).ok_or_else(|| bad(CMD, "trace sketch is missing"))?;
|
||||
let i = s.doc.assembly.traces.iter().position(|t| t.sketch == id).ok_or_else(|| bad(CMD, "the sketch has no associative trace"))?;
|
||||
if bool_(p, "auto_update") == Some(false) {
|
||||
s.doc_mut().assembly.traces.remove(i);
|
||||
Arc::make_mut(&mut s.motion_traces.entries).remove(&id);
|
||||
Arc::make_mut(&mut s.motion_traces.history).remove(&id);
|
||||
return Ok(json!({"sketch":id,"auto_update":false}));
|
||||
}
|
||||
let mut t = s.doc.assembly.traces.get(i).cloned().ok_or_else(|| bad(CMD, "trace is missing"))?;
|
||||
if p.get("study").is_some() || p.get("joint").is_some() {
|
||||
t.motion = motion(s, p, CMD)?;
|
||||
} else if let TraceMotion::Joint { from, to, index, .. } = &mut t.motion {
|
||||
if let Some(v) = p.get("from") {
|
||||
*from = v.clone();
|
||||
}
|
||||
if let Some(v) = p.get("to") {
|
||||
*to = v.clone();
|
||||
}
|
||||
if let Some(v) = p.get("index") {
|
||||
*index = v.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or_else(|| bad(CMD, "invalid index"))?;
|
||||
}
|
||||
}
|
||||
if p.get("samples").is_some() {
|
||||
t.samples = Some(super::sample_count(p, 100, super::MAX_TRACE, CMD)?);
|
||||
}
|
||||
inputs(s, &t)?;
|
||||
// Validate before publishing an edited definition; execute can then undo the whole edit.
|
||||
if s.doc.assembly.traces.get(i) != Some(&t)
|
||||
&& let Some(slot) = s.doc_mut().assembly.traces.get_mut(i)
|
||||
{
|
||||
*slot = t;
|
||||
}
|
||||
Ok(json!({"sketch":id,"auto_update":true}))
|
||||
}
|
||||
@@ -13,6 +13,45 @@ fn near(value: &Value, expected: f64) {
|
||||
assert!((value.as_f64().unwrap() - expected).abs() < 1e-6, "{value} != {expected}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn component_create_rejects_bodies_without_changing_design() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "solid.box", json!({"length":10,"width":10,"height":10,"body_name":"Body1"}));
|
||||
let doc = s.doc.clone();
|
||||
let active_path = s.active_occurrence_path.clone();
|
||||
let error = s.execute("component.create", &json!({"name":"Part","bodies":["Body1"]})).unwrap_err();
|
||||
assert!(matches!(&error, crate::EngineError::BadParams { cmd, .. } if cmd == "component.create"));
|
||||
let msg = error.to_string();
|
||||
for expected in ["bodies", "name, parent, parent_path, activate", "component.move_bodies", "component.from_bodies"] {
|
||||
assert!(msg.contains(expected), "{msg}");
|
||||
}
|
||||
assert_eq!(s.doc, doc);
|
||||
assert_eq!(s.active_component, 0);
|
||||
assert_eq!(s.active_occurrence_path, active_path);
|
||||
assert_eq!(s.doc.model_body_component(s.model.state().body("Body1").unwrap()), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn component_create_rejects_unknown_keys_and_accepts_documented_keys() {
|
||||
let mut s = Session::default();
|
||||
let (parent, occurrence) = created(&mut s, "Parent");
|
||||
let params = json!({"name":"Child","parent":parent,"parent_path":[occurrence],"activate":false});
|
||||
let mut invalid = params.clone();
|
||||
invalid["activte"] = json!(true);
|
||||
let doc = s.doc.clone();
|
||||
let error = s.execute("component.create", &invalid).unwrap_err().to_string();
|
||||
assert!(error.contains("activte"), "{error}");
|
||||
assert!(error.contains("name, parent, parent_path, activate"), "{error}");
|
||||
assert_eq!(s.doc, doc);
|
||||
assert_eq!(s.active_component, parent);
|
||||
assert_eq!(s.active_occurrence_path, Some(vec![occurrence]));
|
||||
let child = run(&mut s, "component.create", params);
|
||||
assert_eq!(child["name"], "Child");
|
||||
assert_eq!(child["parent"], parent);
|
||||
assert_eq!(s.active_component, parent);
|
||||
assert_eq!(s.active_occurrence_path, Some(vec![occurrence]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instance_copy_uses_selected_source_transform() {
|
||||
let mut s = Session::default();
|
||||
|
||||
@@ -99,3 +99,59 @@ fn offset_plane_redefined_on_itself_is_refused() {
|
||||
run(&mut s, "timeline.redefine", redefine(json!({"face": [30, 0, 10]})));
|
||||
assert!((plane(&s, "Side").origin.y + 7.0).abs() < 1e-9, "{:?}", plane(&s, "Side"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plane_at_angle_from_a_planar_face_follows_the_face() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20, "name": "Base"}));
|
||||
|
||||
// Top face (z = 20), 45 degrees about X axis.
|
||||
run(&mut s, "construct.plane.at_angle", json!({"base": {"face": [5, 5, 20]}, "axis": "X", "angle": "45 deg", "name": "Slanted"}));
|
||||
let slanted = plane(&s, "Slanted");
|
||||
// Base plane has normal Z and its origin on the top face, (0, 0, 20). Rotated 45 degrees
|
||||
// about X: the origin is (0, -20/sqrt(2), 20/sqrt(2)) and the normal [0, -sin(45), cos(45)].
|
||||
let half = 1.0_f64 / 2.0_f64.sqrt();
|
||||
assert!(slanted.origin.x.abs() < 1e-9, "{slanted:?}");
|
||||
assert!((slanted.origin.y - -20.0 * half).abs() < 1e-9, "{slanted:?}");
|
||||
assert!((slanted.origin.z - 20.0 * half).abs() < 1e-9, "{slanted:?}");
|
||||
assert!((slanted.normal().y - (-half)).abs() < 1e-9, "{slanted:?}");
|
||||
assert!((slanted.normal().z - half).abs() < 1e-9, "{slanted:?}");
|
||||
|
||||
let feature = s.doc.find_feature("Slanted").unwrap();
|
||||
let FeatureKind::ConstructionPlane { plane: PlaneRef::AtAngle { base, .. } } = &feature.kind else { panic!("at_angle plane") };
|
||||
assert!(matches!(base.as_ref(), PlaneRef::Face { anchor: Some(_), .. }), "{base:?}");
|
||||
|
||||
// Height changes: the slanted plane moves with the top face (0, 0, 30).
|
||||
run(&mut s, "timeline.edit", json!({"feature": "Base", "set": {"height": "30"}}));
|
||||
let slanted2 = plane(&s, "Slanted");
|
||||
assert!(slanted2.origin.x.abs() < 1e-9, "{slanted2:?}");
|
||||
assert!((slanted2.origin.y - -30.0 * half).abs() < 1e-9, "{slanted2:?}");
|
||||
assert!((slanted2.origin.z - 30.0 * half).abs() < 1e-9, "{slanted2:?}");
|
||||
assert!((slanted2.normal().y - (-half)).abs() < 1e-9, "{slanted2:?}");
|
||||
assert!((slanted2.normal().z - half).abs() < 1e-9, "{slanted2:?}");
|
||||
|
||||
// Saved and reopened, the attachment still resolves.
|
||||
let reopened = Session::new(Document::from_json(&s.doc.to_json()).unwrap());
|
||||
let reopened_slanted = plane(&reopened, "Slanted");
|
||||
assert!((reopened_slanted.origin.y - -30.0 * half).abs() < 1e-9, "{reopened_slanted:?}");
|
||||
assert!((reopened_slanted.origin.z - 30.0 * half).abs() < 1e-9, "{reopened_slanted:?}");
|
||||
assert!((reopened_slanted.normal().y - (-half)).abs() < 1e-9, "{reopened_slanted:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plane_at_angle_rejects_bad_face_picks_without_panicking() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20}));
|
||||
for base in [
|
||||
json!({"face": [100, 100, 100]}),
|
||||
json!({"face": [1e300, 0, 0]}),
|
||||
json!({"face": "top"}),
|
||||
json!({"face": [5, 5]}),
|
||||
json!({"face": [5, 5, 20], "index": 0}),
|
||||
json!({"face": [5, 5, 20], "body": 7, "index": 0}),
|
||||
] {
|
||||
let features = s.doc.features.len();
|
||||
assert!(s.execute("construct.plane.at_angle", &json!({"base": base, "axis": "X", "angle": "45 deg"})).is_err(), "{base}");
|
||||
assert_eq!(s.doc.features.len(), features, "{base}");
|
||||
}
|
||||
}
|
||||
@@ -425,6 +425,40 @@ mod tests {
|
||||
assert!(s.execute("plastic.snap_fit", &json!({"position": [5, 5, 4], "direction": [0, 0, 1], "hook": [0, 0, 1], "length": 15, "thickness": 1.5, "width": 6, "catch_depth": 1, "catch_length": 3})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plastic_sizes_below_the_minimum_are_refused_by_name() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "solid.box", json!({"length": 40, "width": 40, "height": 4}));
|
||||
let v0 = volume(&mut s);
|
||||
let snap =
|
||||
json!({"position": [20, 20, 4], "hook": [1, 0, 0], "length": 15, "thickness": 1.5, "width": 6, "catch_depth": 1, "catch_length": 3});
|
||||
for (key, tiny) in
|
||||
[("thickness", 1e-9), ("thickness", 1e-320), ("length", 1e-5), ("width", 0.005), ("catch_depth", 1e-9), ("catch_length", 1e-9)]
|
||||
{
|
||||
let mut p = snap.clone();
|
||||
p[key] = json!(tiny);
|
||||
let e = s.execute("plastic.snap_fit", &p).unwrap_err().to_string();
|
||||
assert!(e.contains(&format!("snap fit's {key} must be at least 0.01 mm")), "{key}={tiny}: {e}");
|
||||
}
|
||||
let boss = json!({"position": [20, 20, 4], "diameter": 6, "height": 5});
|
||||
for (key, tiny) in [("diameter", 1e-9), ("height", 1e-9), ("hole_diameter", 1e-9), ("rib_thickness", 1e-9)] {
|
||||
let mut p = boss.clone();
|
||||
p[key] = json!(tiny);
|
||||
if key == "rib_thickness" {
|
||||
p["ribs"] = json!(4);
|
||||
}
|
||||
let e = s.execute("plastic.boss", &p).unwrap_err().to_string();
|
||||
assert!(e.contains(&format!("boss's {key} must be at least 0.01 mm")), "{key}={tiny}: {e}");
|
||||
}
|
||||
let e = s.execute("plastic.rest", &json!({"position": [20, 20, 4], "width": 6, "height": 1e-9})).unwrap_err().to_string();
|
||||
assert!(e.contains("rest's height must be at least 0.01 mm"), "{e}");
|
||||
assert!(rel(volume(&mut s), v0) < 1e-9, "the refused features changed nothing");
|
||||
// The minimum itself still builds.
|
||||
let mut p = snap.clone();
|
||||
p["thickness"] = json!(0.01);
|
||||
run(&mut s, "plastic.snap_fit", p);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enclosure_snap_fit_follows_resized_front_wall() {
|
||||
let mut s = Session::default();
|
||||
|
||||
@@ -126,7 +126,7 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
.at("SKETCH", "CONSTRAINTS")
|
||||
.icon("c_coincident")
|
||||
.enabled(in_sketch)
|
||||
.params("a, b: points, a point and a curve or sketch axis (x / y: the sketch's own axes, unless a curve has that id; an axis becomes a linked construction line on it, reported in created), or two distinct lines (joins their closest endpoints)"),
|
||||
.params("a, b: points, a point and a curve or sketch axis (x / y: the sketch's own axes, unless a curve has that id; an axis becomes a linked construction line on it, reported in created), or two distinct lines (joins their closest endpoints), or two circles/arcs (the second lies on the first: concentric and equal, `constraints` lists both)"),
|
||||
CommandSpec::new("sketch.constraint.tangent", "Tangent", c_tangent)
|
||||
.at("SKETCH", "CONSTRAINTS")
|
||||
.icon("c_tangent")
|
||||
@@ -1728,6 +1728,9 @@ fn c_coincident(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "sketch.constraint.coincident";
|
||||
// Already tied (e.g. connected when it was drawn there): nothing to add.
|
||||
let sk = s.doc.sketch(target_sketch(s, p, cmd)?)?;
|
||||
if let Some((a, b)) = two_round(sk, p) {
|
||||
return coincident_circles(s, p, cmd, a, b);
|
||||
}
|
||||
let pt = |k: &str| p.get(k).and_then(Value::as_str).and_then(|r| sk.resolve_point(r));
|
||||
let line_points = coincident_line_points(sk, p, cmd)?;
|
||||
if let Some((a, b)) = line_points.or_else(|| pt("a").zip(pt("b")))
|
||||
@@ -1758,6 +1761,41 @@ fn c_coincident(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})
|
||||
}
|
||||
|
||||
/// `a` and `b` both circles or arcs (two different ones).
|
||||
fn two_round(sk: &Sketch, p: &Value) -> Option<(usize, usize)> {
|
||||
let round = |k: &str| {
|
||||
let c = sk.curve_index(p.get(k)?.as_str()?)?;
|
||||
matches!(sk.curves.get(c)?.kind, CurveKind::Circle { .. } | CurveKind::Arc { .. }).then_some(c)
|
||||
};
|
||||
let (a, b) = (round("a")?, round("b")?);
|
||||
(a != b).then_some((a, b))
|
||||
}
|
||||
|
||||
/// Two circles or arcs made coincident lie on each other: one centre and one radius (Concentric
|
||||
/// and Equal), the second pick moving onto the first, in one step. A half already there is
|
||||
/// not added again.
|
||||
fn coincident_circles(s: &mut Session, p: &Value, cmd: &str, a: usize, b: usize) -> Result<Value> {
|
||||
let (ids, info) = edit(s, p, cmd, true, |sk, _| {
|
||||
let rep = solve(&mut sk.clone());
|
||||
let pair = |x: usize, y: usize| (x, y) == (a, b) || (x, y) == (b, a);
|
||||
let concentric = sk.constraints.iter().any(|c| !c.driven && matches!(c.kind, ConstraintKind::Concentric { a: x, b: y } if pair(x, y)));
|
||||
let equal = sk.constraints.iter().any(|c| !c.driven && matches!(c.kind, ConstraintKind::Equal { a: x, b: y } if pair(x, y)));
|
||||
let mut ids = Vec::new();
|
||||
if !concentric {
|
||||
ids.push(add_c(sk, ConstraintKind::Concentric { a, b })?);
|
||||
}
|
||||
if !equal {
|
||||
ids.push(add_c(sk, ConstraintKind::Equal { a, b })?);
|
||||
}
|
||||
if ids.is_empty() {
|
||||
return Err(bad(cmd, "these circles already lie on each other"));
|
||||
}
|
||||
apply_in_order(sk, &rep, &[Ent::Curve(a)], Ent::Curve(b), cmd)?;
|
||||
Ok(ids)
|
||||
})?;
|
||||
Ok(json!({"constraint": ids[0], "constraints": ids, "sketch": info}))
|
||||
}
|
||||
|
||||
/// Four endpoint pairs, ordered independently of pick order when distances tie.
|
||||
fn coincident_line_points(sk: &Sketch, p: &Value, cmd: &str) -> Result<Option<(usize, usize)>> {
|
||||
let curve = |key: &str| p.get(key).and_then(Value::as_str).and_then(|id| sk.curve_index(id));
|
||||
|
||||
@@ -888,3 +888,38 @@ fn undoing_a_defining_dimension_removes_the_parameter_too() {
|
||||
assert_eq!(param_row(&mut s, "w")["expression"], "20");
|
||||
assert!((line_length(&s, "la") - 20.0).abs() < 1e-6);
|
||||
}
|
||||
|
||||
/// Coincident on two circles (or arcs) lays the second on the first: one centre and one
|
||||
/// radius, in one step, and the first stays. It used to be refused ("two curves must both be
|
||||
/// straight lines").
|
||||
#[test]
|
||||
fn coincident_circles_lie_on_each_other() {
|
||||
let mut s = new_sketch();
|
||||
run(&mut s, "sketch.circle.center", json!({"center":[0,0],"radius":10}));
|
||||
run(&mut s, "sketch.circle.center", json!({"center":[3,1],"radius":8}));
|
||||
let undo = s.undo.len();
|
||||
let r = run(&mut s, "sketch.constraint.coincident", json!({"a":"c1","b":"c2"}));
|
||||
assert_eq!(r["constraints"].as_array().unwrap().len(), 2, "{r}");
|
||||
assert_eq!(s.undo.len(), undo + 1);
|
||||
let sk = sketch(&s);
|
||||
let circle = |id: &str| {
|
||||
let c = sk.curve_index(id).unwrap();
|
||||
match sk.curves[c].kind {
|
||||
solidcraft_sketch::CurveKind::Circle { c, r } => (sk.point(c).unwrap(), r),
|
||||
_ => panic!("{id} is a circle"),
|
||||
}
|
||||
};
|
||||
let ((c1, r1), (c2, r2)) = (circle("c1"), circle("c2"));
|
||||
assert!(c1.dist(Vec2::new(0.0, 0.0)) < 1e-6 && (r1 - 10.0).abs() < 1e-6, "the first stays");
|
||||
assert!(c2.dist(c1) < 1e-6 && (r2 - r1).abs() < 1e-6, "the second lies on it: {c2:?} r {r2}");
|
||||
// Again: nothing to add.
|
||||
assert!(s.execute("sketch.constraint.coincident", &json!({"a":"c1","b":"c2"})).is_err());
|
||||
// An arc onto a circle.
|
||||
run(&mut s, "sketch.arc.three_point", json!({"start":[20,0],"through":[25,5],"end":[30,0]}));
|
||||
run(&mut s, "sketch.constraint.coincident", json!({"a":"c1","b":"a1"}));
|
||||
let sk = sketch(&s);
|
||||
let a = sk.curve_index("a1").unwrap();
|
||||
let solidcraft_sketch::CurveKind::Arc { c, a: start, .. } = sk.curves[a].kind else { panic!("a1 is an arc") };
|
||||
assert!(sk.point(c).unwrap().dist(Vec2::new(0.0, 0.0)) < 1e-6);
|
||||
assert!((sk.point(start).unwrap().dist(sk.point(c).unwrap()) - 10.0).abs() < 1e-6);
|
||||
}
|
||||
@@ -309,6 +309,8 @@ pub struct Session {
|
||||
/// Full model evaluations (`refresh`), for tests.
|
||||
#[cfg(test)]
|
||||
pub(crate) evaluations: usize,
|
||||
/// Resolved associative trace inputs, independent of the document revision and view state.
|
||||
pub(crate) motion_traces: cmd::motion::associative::Cache,
|
||||
}
|
||||
|
||||
/// A sketch changed by one frame of an interactive gesture (`live: true`).
|
||||
@@ -445,6 +447,7 @@ impl Session {
|
||||
render_jobs: Default::default(),
|
||||
#[cfg(test)]
|
||||
evaluations: 0,
|
||||
motion_traces: Default::default(),
|
||||
crash_journal: false,
|
||||
}
|
||||
}
|
||||
@@ -651,8 +654,9 @@ impl Session {
|
||||
self.prune_occurrence_state();
|
||||
// Joints follow the geometry their origins snap to.
|
||||
if !self.doc.assembly.joints.is_empty() {
|
||||
cmd::joints::resolve(self);
|
||||
cmd::joints::place(self);
|
||||
}
|
||||
cmd::motion::associative::refresh(self);
|
||||
if let Some(id) = self.active_sketch
|
||||
&& self.doc.feature(id).is_none()
|
||||
{
|
||||
@@ -669,7 +673,7 @@ impl Session {
|
||||
{
|
||||
self.revision += 1;
|
||||
if !self.doc.assembly.joints.is_empty() {
|
||||
cmd::joints::resolve(self);
|
||||
cmd::joints::place(self);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -978,6 +982,7 @@ impl Session {
|
||||
saved_visibility: self.saved_visibility.clone(),
|
||||
#[cfg(test)]
|
||||
evaluations: 0,
|
||||
motion_traces: self.motion_traces.clone(),
|
||||
crash_journal: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3381,6 +3381,47 @@ fn deleting_a_sketch_leaves_no_silently_failing_feature() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_extrude_profiles_preserve_two_holes() {
|
||||
let mut sketch = Session::default();
|
||||
run(&mut sketch, "sketch.create", json!({"plane": "XY"}));
|
||||
run(&mut sketch, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [60, 40]}));
|
||||
for x in [15, 45] {
|
||||
run(&mut sketch, "sketch.circle.center", json!({"center": [x, 20], "radius": 5}));
|
||||
}
|
||||
run(&mut sketch, "sketch.finish", json!({}));
|
||||
for (selection, expected) in [
|
||||
(None, (2400.0 - 50.0 * PI) * 5.0),
|
||||
(Some(json!([0])), (2400.0 - 50.0 * PI) * 5.0),
|
||||
(Some(json!("all")), 12000.0),
|
||||
(Some(json!([0, 1, 2])), 12000.0),
|
||||
] {
|
||||
let mut s = Session::new((*sketch.doc).clone());
|
||||
let mut params = json!({"distance": 5});
|
||||
if let Some(selection) = selection {
|
||||
params["profiles"] = selection;
|
||||
}
|
||||
run(&mut s, "solid.extrude", params);
|
||||
let actual = volume(&mut s);
|
||||
assert!(rel(actual, expected) < 1e-4, "{actual} vs {expected}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_extrude_profiles_keep_even_depth_islands_and_separate_outlines() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "sketch.create", json!({"plane": "XY"}));
|
||||
for (p0, p1) in [([0, 0], [30, 30]), ([5, 5], [25, 25]), ([10, 10], [20, 20]), ([40, 0], [50, 10])] {
|
||||
run(&mut s, "sketch.rectangle.two_point", json!({"p0": p0, "p1": p1}));
|
||||
}
|
||||
run(&mut s, "sketch.finish", json!({}));
|
||||
run(&mut s, "solid.extrude", json!({"distance": 5}));
|
||||
assert_eq!(s.model.state().bodies.len(), 3);
|
||||
let expected = (900.0 - 400.0 + 100.0 + 100.0) * 5.0;
|
||||
let actual = volume(&mut s);
|
||||
assert!(rel(actual, expected) < 1e-6, "{actual} vs {expected}");
|
||||
}
|
||||
|
||||
/// Every body a multi-profile `new` extrude creates carries its `body_name`, not a generic BodyN (#266).
|
||||
#[test]
|
||||
fn multi_profile_extrude_names_every_body_after_body_name() {
|
||||
@@ -3546,6 +3587,36 @@ fn a_pattern_repeats_a_fillet_on_the_edges_it_found() {
|
||||
assert!(rel(volume(&mut s), expect) < 1e-5, "{} vs {expect}", volume(&mut s));
|
||||
}
|
||||
|
||||
/// A body renamed after a join: the next new body does not take the name the rename freed
|
||||
/// (#4957). The join changed the body, so the rename is followed by a full evaluation of the
|
||||
/// design; the numbers the design handed out must not go back with it, or a script that names
|
||||
/// a body finds another one.
|
||||
#[test]
|
||||
fn a_renamed_body_keeps_its_number_from_the_next_body() {
|
||||
for join in [false, true] {
|
||||
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": [10, 10]}));
|
||||
run(&mut s, "sketch.finish", json!({}));
|
||||
run(&mut s, "solid.extrude", json!({"distance": 5, "operation": "new"}));
|
||||
if join {
|
||||
// A second box joined to the first: the join changes the body, so the rename
|
||||
// cannot be followed without evaluating the design again.
|
||||
run(&mut s, "sketch.create", json!({"plane": "XY"}));
|
||||
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [5, 0], "p1": [15, 10]}));
|
||||
run(&mut s, "sketch.finish", json!({}));
|
||||
run(&mut s, "solid.extrude", json!({"distance": 5, "operation": "join"}));
|
||||
}
|
||||
run(&mut s, "body.rename", json!({"body": "Body1", "name": "First"}));
|
||||
run(&mut s, "sketch.create", json!({"plane": "XY"}));
|
||||
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!({"distance": 5, "operation": "new"}));
|
||||
let names: Vec<String> = s.model.state().bodies.iter().map(|b| b.name.clone()).collect();
|
||||
assert_eq!(names, ["First", "Body2"], "with a join: {join}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A copy added by raising the count after a rename takes the next number, not the freed one (#372).
|
||||
#[test]
|
||||
fn raising_a_pattern_count_after_a_rename_numbers_the_new_copy_after_the_others() {
|
||||
|
||||
@@ -274,3 +274,61 @@ fn automatic_part_names_and_assembly_survive_reopening() {
|
||||
assert!(near(extent(&again).0, [0.0, 0.0, 0.0]) && near(extent(&again).1, [40.0, 34.0, 20.0]));
|
||||
assert!((total_volume(&mut again) - (40.0 * 4.0 * 20.0 + 2.0 * 4.0 * 30.0 * 4.0)).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn step_replies_include_originating_system() -> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||
let dir = std::env::temp_dir().join(format!("solidcraft-step-system-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
let path = dir.join("box.step");
|
||||
let mut source = Session::default();
|
||||
source.execute("solid.box", &json!({"length": 10, "width": 40, "height": 5}))?;
|
||||
source.execute("file.export", &json!({"path": path.to_string_lossy()}))?;
|
||||
let text = std::fs::read_to_string(&path)?;
|
||||
assert!(text.contains("'SolidCraft','SolidCraft'"));
|
||||
for system in ["SolidCraft", "Example CAD"] {
|
||||
std::fs::write(&path, text.replace("'SolidCraft','SolidCraft'", &format!("'SolidCraft','{system}'")))?;
|
||||
for command in ["file.insert_step", "doc.open"] {
|
||||
let reply = Session::default().execute(command, &json!({"path": path.to_string_lossy()}))?;
|
||||
assert_eq!(reply.get("system").and_then(Value::as_str), Some(system), "{command}: {reply}");
|
||||
}
|
||||
}
|
||||
std::fs::remove_dir_all(dir)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A header naming SolidWorks says the file has Y up; SolidCraft's own says Z; anything else
|
||||
/// says nothing (synthetic headers only).
|
||||
#[test]
|
||||
fn step_replies_name_a_y_up_exporter() -> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||
let dir = std::env::temp_dir().join(format!("solidcraft-step-exporter-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
let path = dir.join("box.step");
|
||||
let mut source = Session::default();
|
||||
source.execute("solid.box", &json!({"length": 10, "width": 40, "height": 5}))?;
|
||||
source.execute("file.export", &json!({"path": path.to_string_lossy()}))?;
|
||||
let text = std::fs::read_to_string(&path)?;
|
||||
let header = "'SolidCraft','SolidCraft'";
|
||||
assert!(text.contains(header));
|
||||
for (preprocessor, system, want) in [
|
||||
("SolidCraft", "SolidCraft", Some(("z", "SolidCraft"))),
|
||||
("SolidWorks 2021", "SolidWorks 2021", Some(("y", "SolidWorks"))),
|
||||
("Example CAD", "SOLIDWORKS 2019", Some(("y", "SolidWorks"))),
|
||||
("Example CAD", "Example CAD", None),
|
||||
] {
|
||||
std::fs::write(&path, text.replace(header, &format!("'{preprocessor}','{system}'")))?;
|
||||
for command in ["file.insert_step", "doc.open"] {
|
||||
let reply = Session::default().execute(command, &json!({"path": path.to_string_lossy()}))?;
|
||||
let got = reply.get("exporter_up").and_then(Value::as_str).zip(reply.get("exporter").and_then(Value::as_str));
|
||||
assert_eq!(got, want, "{command} {system}: {reply}");
|
||||
}
|
||||
}
|
||||
// The program may be named only in FILE_DESCRIPTION.
|
||||
std::fs::write(
|
||||
&path,
|
||||
text.replace("FILE_DESCRIPTION((", "FILE_DESCRIPTION(('SolidWorks export',").replace(header, "'Example CAD','Example CAD'"),
|
||||
)?;
|
||||
let reply = Session::default().execute("file.insert_step", &json!({"path": path.to_string_lossy()}))?;
|
||||
assert_eq!(reply.get("exporter_up").and_then(Value::as_str), Some("y"), "{reply}");
|
||||
std::fs::remove_dir_all(dir)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -262,3 +262,81 @@ fn the_coupler_edge_follows_with_both_ends_free_to_rotate() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Two parallelogram linkages, each held parallel and equal on both pairs of sides (two
|
||||
/// redundant constraints each), the upper one hanging off the lower one's moving side and tied
|
||||
/// to a fixed pivot by a 30 mm rod: one degree of freedom (#4585).
|
||||
fn parallelograms() -> solidcraft_engine::Session {
|
||||
let mut s = solidcraft_engine::Session::default();
|
||||
let run = |s: &mut solidcraft_engine::Session, id: &str, p: serde_json::Value| {
|
||||
s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
|
||||
};
|
||||
run(&mut s, "sketch.create", json!({"plane":"XY"}));
|
||||
let at = |deg: f64, r: f64| Vec2::new(deg.to_radians().cos(), deg.to_radians().sin()) * r;
|
||||
let p1 = at(147.7, 80.0);
|
||||
let m = p1 + Vec2::new(0.0, 20.0);
|
||||
let r = m + at(20.0, 80.0);
|
||||
let (c, t) = (m + Vec2::new(0.0, 20.0), r + Vec2::new(0.0, 20.0));
|
||||
let g = r + at(-70.0, 30.0);
|
||||
let xy = |p: Vec2| [p.x, p.y];
|
||||
let (o, q) = (xy(Vec2::ZERO), xy(Vec2::new(0.0, 20.0)));
|
||||
run(&mut s, "sketch.line", json!({"points":[o, xy(p1), xy(m), q, o],"ids":["bot","left","top","right"],"infer":false}));
|
||||
run(&mut s, "sketch.line", json!({"points":["left.end", xy(r), xy(t), xy(c), "left.end"],"ids":["ubot","uright","utop","uleft"],"infer":false}));
|
||||
run(&mut s, "sketch.line", json!({"points":["ubot.end", xy(g)],"ids":["rod"],"infer":false}));
|
||||
run(&mut s, "sketch.constraint.fix", json!({"entities":["bot.start", "rod.end"]}));
|
||||
run(&mut s, "sketch.constraint.horizontal_vertical", json!({"line":"right"}));
|
||||
for (line, value) in [("right", 20.0), ("bot", 80.0), ("ubot", 80.0), ("uleft", 20.0), ("rod", 30.0)] {
|
||||
run(&mut s, "sketch.dimension", json!({"entities":[line],"value":value}));
|
||||
}
|
||||
for (a, b) in [("top", "bot"), ("left", "right"), ("utop", "ubot"), ("uright", "uleft")] {
|
||||
run(&mut s, "sketch.constraint.parallel", json!({"a":a,"b":b}));
|
||||
run(&mut s, "sketch.constraint.equal", json!({"a":a,"b":b}));
|
||||
}
|
||||
run(&mut s, "sketch.constraint.parallel", json!({"a":"uleft","b":"left"}));
|
||||
s
|
||||
}
|
||||
|
||||
/// The parallelograms' lengths, directions and fixed points, as the largest error.
|
||||
fn parallelogram_error(s: &solidcraft_engine::Session) -> f64 {
|
||||
let p = |name: &str| four_bar::point(s, name).unwrap();
|
||||
let side = |line: &str| p(&format!("{line}.end")) - p(&format!("{line}.start"));
|
||||
let mut error = p("bot.start").len().max(p("right.start").dist(Vec2::new(0.0, 20.0)));
|
||||
for (line, value) in [("bot", 80.0), ("ubot", 80.0), ("uleft", 20.0), ("rod", 30.0)] {
|
||||
error = error.max((side(line).len() - value).abs());
|
||||
}
|
||||
for (a, b) in [("top", "bot"), ("left", "right"), ("utop", "ubot"), ("uright", "uleft")] {
|
||||
error = error.max((side(a).len() - side(b).len()).abs()).max(side(a).cross(side(b)).abs() / side(b).len());
|
||||
}
|
||||
error
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_linkage_held_by_redundant_parallelograms_follows_the_cursor() {
|
||||
// Each held parallelogram's parallel and equal sides are dependent only at an exact
|
||||
// solution: a pose corrected to the solver's tolerance must still show the linkage's freedom.
|
||||
for live in [true, false] {
|
||||
let mut s = parallelograms();
|
||||
let report = s.execute("sketch.solve", &json!({})).unwrap();
|
||||
assert_eq!((&report["status"], &report["dof"]), (&json!("solved"), &json!(1)), "{report}");
|
||||
// The lower parallelogram's free corner, its moving sides and the upper one's side, each
|
||||
// dragged in turn from where the last drag left the linkage, follows most of the way
|
||||
// (the rest is off the path the linkage allows).
|
||||
for (entity, along) in [("bot.end", None), ("bot", Some(0.5)), ("left", Some(0.5)), ("ubot", Some(0.5)), ("bot.end", None)] {
|
||||
let from = along.map_or_else(|| four_bar::point(&s, entity).unwrap(), |f| grab(&s, entity, f));
|
||||
let to = from + Vec2::new(2.0, 2.0);
|
||||
let r = s.execute("sketch.drag", &json!({"entity":entity,"from":[from.x,from.y],"to":[to.x,to.y],"live":live})).unwrap();
|
||||
let reached = r["reached"].as_f64().unwrap();
|
||||
assert!(reached > 0.8, "live {live}: {entity} reached {reached}: {r}");
|
||||
assert!(parallelogram_error(&s) < 1e-6, "live {live}: {entity}: {}", parallelogram_error(&s));
|
||||
assert_eq!(r["sketch"]["solved"], json!(true));
|
||||
}
|
||||
// The lower parallelogram's free corner lands on its 80 mm circle, as close to the
|
||||
// cursor as the circle allows.
|
||||
let from = four_bar::point(&s, "bot.end").unwrap();
|
||||
let to = from + Vec2::new(1.0, 2.0);
|
||||
s.execute("sketch.drag", &json!({"entity":"bot.end","from":[from.x,from.y],"to":[to.x,to.y],"live":live})).unwrap();
|
||||
let at = four_bar::point(&s, "bot.end").unwrap();
|
||||
assert!(at.dist(to * (80.0 / to.len())) < 1e-4, "live {live}: {at:?}");
|
||||
assert!(parallelogram_error(&s) < 1e-6);
|
||||
}
|
||||
}
|
||||